@shipstatic/ship 0.3.11 → 0.3.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +1 -1
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var et=Object.create;var ie=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>{for(var t in e)ie(n,t,{get:e[t],enumerable:!0})},ne=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nt(e))!ot.call(n,s)&&s!==t&&ie(n,s,{get:()=>e[s],enumerable:!(i=tt(e,s))||i.enumerable});return n},p=(n,e,t)=>(ne(n,e,"default"),t&&ne(t,e,"default")),E=(n,e,t)=>(t=n!=null?et(it(n)):{},ne(e||!n||!n.__esModule?ie(t,"default",{value:n,enumerable:!0}):t,n)),st=n=>ne(ie({},"__esModule",{value:!0}),n);var Ne={};B(Ne,{__setTestEnvironment:()=>j,getENV:()=>y});function j(n){we=n}function rt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return we||rt()}var we,C=T(()=>{"use strict";we=null});function _(n){Fe=n}function b(){if(Fe===null)throw ze.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Fe}var ze,Fe,N=T(()=>{"use strict";ze=require("@shipstatic/types"),Fe=null});var Be={};B(Be,{loadConfig:()=>K});function Ue(n){try{return ct.parse(n)}catch(e){if(e instanceof L.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw ae.ShipError.config(`Configuration validation failed${i}: ${t.message}`)}throw ae.ShipError.config("Configuration validation failed")}}async function ft(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(Se,{searchPlaces:[`.${Se}rc`,"package.json",`${t.homedir()}/.${Se}rc`],stopDir:t.homedir()}),s;if(n?s=i.load(n):s=i.search(),s&&s.config)return Ue(s.config)}catch(e){if(e instanceof ae.ShipError)throw e}return{}}async function K(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ft(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ue(i)}var L,ae,Se,ct,le=T(()=>{"use strict";L=require("zod"),ae=require("@shipstatic/types");C();Se="ship",ct=L.z.object({apiUrl:L.z.string().url().optional(),apiKey:L.z.string().optional(),deployToken:L.z.string().optional()}).strict()});async function ut(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,f=new FileReader,g=()=>{let w=r*2097152,l=Math.min(w+2097152,n.size);f.readAsArrayBuffer(n.slice(w,l))};f.onload=w=>{let l=w.target?.result;if(!l){i(M.ShipError.business("Failed to read file chunk"));return}a.append(l),r++,r<o?g():t({md5:a.end()})},f.onerror=()=>{i(M.ShipError.business("Failed to calculate MD5: FileReader error"))},g()})}async function dt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,s)=>{let o=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>s(M.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>o.update(a)),r.on("end",()=>i({md5:o.digest("hex")}))})}async function $(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw M.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ut(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw M.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return dt(n)}throw M.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var M,W=T(()=>{"use strict";C();M=require("@shipstatic/types")});function z(n){return!n||n.length===0?[]:n.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 s=t.slice(0,-1);for(let o of s)if(ce.some(r=>o.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ke,ce,fe=T(()=>{"use strict";Ke=require("junk"),ce=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function qe(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function me(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var xe=T(()=>{"use strict"});function U(n,e={}){if(e.flatten===!1)return n.map(i=>({path:me(i),name:Te(i)}));let t=yt(n);return n.map(i=>{let s=me(i);if(t){let o=t.endsWith("/")?t:`${t}/`;s.startsWith(o)&&(s=s.substring(o.length))}return s||(s=Te(i)),{path:s,name:Te(i)}})}function yt(n){if(!n.length)return"";let t=n.map(o=>me(o)).map(o=>o.split("/")),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s-1;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function Te(n){return n.split(/[/\\]/).pop()||n}var ue=T(()=>{"use strict";xe()});function He(n){let e=[];try{let t=I.readdirSync(n);for(let i of t){let s=F.join(n,i),o=I.statSync(s);if(o.isDirectory()){let r=He(s);e.push(...r)}else o.isFile()&&e.push(s)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function Q(n,e={}){if(y()!=="node")throw O.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let u=F.resolve(m);try{return I.statSync(u).isDirectory()?He(u):[u]}catch{throw O.ShipError.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],s=z(i);if(s.length===0)return[];let o=n.map(m=>F.resolve(m)),r=qe(o.map(m=>{try{return I.statSync(m).isDirectory()?m:F.dirname(m)}catch{return F.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=F.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return F.basename(m)}),f=U(a,{flatten:e.pathDetect!==!1}),g=[],w=0,l=b();for(let m=0;m<s.length;m++){let u=s[m],x=f[m].path;try{let R=I.statSync(u);if(R.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(R.size>l.maxFileSize)throw O.ShipError.business(`File ${u} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(w+=R.size,w>l.maxTotalSize)throw O.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let ye=I.readFileSync(u),{md5:Qe}=await $(ye);if(x.includes("\0")||x.includes("/../")||x.startsWith("../")||x.endsWith("/.."))throw O.ShipError.business(`Security error: Unsafe file path "${x}" for file: ${u}`);g.push({path:x,content:ye,size:ye.length,md5:Qe})}catch(R){if(R instanceof O.ShipError&&R.isClientError&&R.isClientError())throw R;console.error(`Could not process file ${u}:`,R)}}if(g.length>l.maxFilesCount)throw O.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return g}var O,I,F,$e=T(()=>{"use strict";C();W();fe();O=require("@shipstatic/types");N();ue();xe();I=E(require("fs"),1),F=E(require("path"),1)});async function Ve(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(C(),Ne));if(t()!=="browser")throw Ie.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(l=>l.webkitRelativePath||l.name),o=U(s,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<i.length;l++){let m=i[l],u=o[l].path;if(u.includes("..")||u.includes("\0"))throw Ie.ShipError.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(l=>l.relativePath),f=z(a),g=new Set(f),w=[];for(let l of r){if(!g.has(l.relativePath))continue;let{md5:m}=await $(l.file);w.push({content:l.file,path:l.relativePath,size:l.file.size,md5:m})}return w}var Ie,je=T(()=>{"use strict";W();Ie=require("@shipstatic/types");fe();ue()});var Xe={};B(Xe,{convertBrowserInput:()=>Ye,convertDeployInput:()=>Ft,convertNodeInput:()=>ke});function Ge(n,e={}){let t=b();if(!e.skipEmptyCheck&&n.length===0)throw S.ShipError.business("No files to deploy.");if(n.length>t.maxFilesCount)throw S.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let s of n){if(s.size>t.maxFileSize)throw S.ShipError.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw S.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function We(n,e){if(e==="node"){if(!Array.isArray(n))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw S.ShipError.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function Je(n){let e=n.map(t=>({name:t.path,size:t.size}));return Ge(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function ke(n,e={}){We(n,"node");let t=await Q(n,e);return Je(t)}async function Ye(n,e={}){We(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw S.ShipError.business("Invalid input type for browser environment. Expected File[].");t=n}else throw S.ShipError.business("Invalid input type for browser environment. Expected File[].");t=t.filter(s=>s.size===0?(console.warn(`Skipping empty file: ${s.name}`),!1):!0),Ge(t);let i=await Ve(t,e);return Je(i)}async function Ft(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw S.ShipError.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await ke([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await ke(n,e);else throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Ye(n,e);return s}var S,Ze=T(()=>{"use strict";S=require("@shipstatic/types");C();$e();je();N()});var te={};B(te,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>z,formatFileSize:()=>V,getCurrentConfig:()=>b,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>Ae});module.exports=st(te);var h={};B(h,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>z,formatFileSize:()=>V,getCurrentConfig:()=>b,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>Ae});var ge=E(require("mime-db"),1),ve={};for(let n in ge.default){let e=ge.default[n];e&&e.extensions&&e.extensions.forEach(t=>{ve[t]||(ve[t]=n)})}function oe(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ve[e]||"application/octet-stream"}var D=require("@shipstatic/types");var se=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 i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let s=Array.from(i);for(let o of s)try{o(...t)}catch(r){i.delete(o),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(s=>{e.on(i,s)})})}clear(){this.handlers.clear()}};C();var re="/deployments",Me="/ping",P="/domains",at="/config",lt="/account",De="/tokens",pt="/spa-check",A=class extends se{constructor(e){super(),this.apiUrl=e.apiUrl||D.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o={...t,headers:s,credentials:s.Authorization?void 0:"include"};this.emit("request",e,o);try{let r=await fetch(e,o);r.ok||await this.handleResponseError(r,i);let a=this.safeClone(r),f=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(f)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,i),r}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}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 i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${t} failed due to API error`;throw e.status===401?D.ShipError.authentication(s):D.ShipError.api(s,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?D.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?D.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof D.ShipError?e:D.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${at}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:s}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...s,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${re}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${re}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${re}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${re}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let s={deployment:t};i&&i.length>0&&(s.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},r=this.getAuthHeaders(o.headers),a={...o,headers:r,credentials:r.Authorization?void 0:"include"};this.emit("request",`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let g=this.safeClone(f),w=this.safeClone(f);return this.emit("response",g,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),{...await this.parseResponse(w),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${P}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${lt}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${De}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${De}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${De}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let s={files:e.map(r=>r.path),index:i};return(await this.request(`${this.apiUrl}${pt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw D.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw D.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:s}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:s}}else throw D.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,s=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw D.ShipError.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let r=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:r});i.append("files[]",a),s.push(o.md5)}return i.append("checksums",JSON.stringify(s)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),r=new i,a=[];for(let l of e){let m=oe(l.path),u;if(Buffer.isBuffer(l.content))u=new s([l.content],l.path,{type:m});else if(typeof Blob<"u"&&l.content instanceof Blob)u=new s([l.content],l.path,{type:m});else throw D.ShipError.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let x=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",u,x),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let f=new o(r),g=[];for await(let l of f.encode())g.push(Buffer.from(l));let w=Buffer.concat(g);return{body:w,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}getBrowserContentType(e){return typeof e=="string"?oe(e):e.type||oe(e.name)}};var Ce=require("@shipstatic/types");N();var _e=require("@shipstatic/types");C();async function mt(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(le(),Be));return t(n)}else return{}}function q(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||_e.DEFAULT_API,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.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 G(n,e){let t={...n};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}var Ee=require("@shipstatic/types");W();async function ht(){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 $(t);return{path:Ee.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:i}}async function Le(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Ee.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let s=await ht();return[...n,s]}}catch{}return n}function J(n,e,t,i,s){return{create:async(o,r={})=>{if(s&&!s()&&!r.deployToken&&!r.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");t&&await t();let a=e?G(r,e):r,f=n();if(!i)throw new Error("processInput function is not provided.");let g=await i(o,a);return g=await Le(g,f,a),await f.deploy(g,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async o=>{t&&await t(),await n().removeDeployment(o)},get:async o=>(t&&await t(),n().getDeployment(o))}}function Y(n,e){return{set:async(t,i,s)=>(e&&await e(),n().setDomain(t,i,s)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function X(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Z(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var H=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new A({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=J(s,this.clientOptions,i,(o,r)=>this.processInput(o,r),()=>this.hasAuth()),this._domains=Y(s,i),this._account=X(s,i),this._tokens=Z(s,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 domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=b(),this._config)}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}setDeployToken(e){if(!e||typeof e!="string")throw Ce.ShipError.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw Ce.ShipError.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};var he=require("@shipstatic/types");C();le();N();var c={};B(c,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>H,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,filterJunk:()=>z,formatFileSize:()=>V,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>mt,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,resolveConfig:()=>q,validateFiles:()=>Ae});var v={};p(v,require("@shipstatic/types"));p(c,v);var pe=require("@shipstatic/types");W();function Pe(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}fe();ue();C();var d=require("@shipstatic/types"),Re=E(require("mime-db"),1),gt=new Set(Object.keys(Re.default)),vt=new Map(Object.entries(Re.default).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function V(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,s)).toFixed(e))+" "+i[s]}function wt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(".")===!1&&(n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Dt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],s=vt.get(e);if(s&&!s.has(i))return!1}return!0}function Ae(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:d.FileValidationStatus.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let s=0;for(let o of n){let r=d.FileValidationStatus.READY,a="Ready for upload",f=o.name?wt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.FileValidationStatus.PROCESSING_ERROR?(r=d.FileValidationStatus.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):f.valid?o.size<=0?(r=d.FileValidationStatus.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(g=>o.type.startsWith(g))?gt.has(o.type)?Dt(o.name,o.type)?o.size>e.maxFileSize?(r=d.FileValidationStatus.VALIDATION_FAILED,a=`File size (${V(o.size)}) exceeds limit of ${V(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(s+=o.size,s>e.maxTotalSize&&(r=d.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${V(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(r=d.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=f.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:r,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.FileValidationStatus.READY&&a.status!==d.FileValidationStatus.PENDING),r="Validation Failed";return o?.status===d.FileValidationStatus.PROCESSING_ERROR?r="Processing Error":o?.status===d.FileValidationStatus.EMPTY_FILE?r="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")||o?.statusMessage?.includes("File name contains")||o?.statusMessage?.includes("File name uses")||o?.statusMessage?.includes("File name cannot start")||o?.statusMessage?.includes("traversal")?r="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?r="Invalid File Type":o?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":o?.statusMessage?.includes("Total size")?r="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:d.FileValidationStatus.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function de(n){return n.filter(e=>e.status===d.FileValidationStatus.READY)}function be(n){return de(n).length>0}var k=require("@shipstatic/types");p(h,c);le();N();N();$e();C();var ee=class extends H{constructor(e={}){if(y()!=="node")throw he.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return q(e,{})}async loadFullConfig(){try{let e=await K(this.clientOptions.configFile),t=q(this.clientOptions,e),i=new A({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let s=await this.http.getConfig();_(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw he.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw he.ShipError.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Ze(),Xe));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Oe=ee;p(te,h,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,FILE_VALIDATION_STATUS,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,filterJunk,formatFileSize,getCurrentConfig,getENV,getValidFiles,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig,setPlatformConfig,validateFiles});
|
|
1
|
+
"use strict";var et=Object.create;var ie=Object.defineProperty;var tt=Object.getOwnPropertyDescriptor;var nt=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var T=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>{for(var t in e)ie(n,t,{get:e[t],enumerable:!0})},ne=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nt(e))!ot.call(n,s)&&s!==t&&ie(n,s,{get:()=>e[s],enumerable:!(i=tt(e,s))||i.enumerable});return n},p=(n,e,t)=>(ne(n,e,"default"),t&&ne(t,e,"default")),E=(n,e,t)=>(t=n!=null?et(it(n)):{},ne(e||!n||!n.__esModule?ie(t,"default",{value:n,enumerable:!0}):t,n)),st=n=>ne(ie({},"__esModule",{value:!0}),n);var Ne={};B(Ne,{__setTestEnvironment:()=>j,getENV:()=>y});function j(n){we=n}function rt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return we||rt()}var we,C=T(()=>{"use strict";we=null});function _(n){Fe=n}function b(){if(Fe===null)throw ze.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return Fe}var ze,Fe,N=T(()=>{"use strict";ze=require("@shipstatic/types"),Fe=null});var Be={};B(Be,{loadConfig:()=>K});function Ue(n){try{return ct.parse(n)}catch(e){if(e instanceof L.z.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw ae.ShipError.config(`Configuration validation failed${i}: ${t.message}`)}throw ae.ShipError.config("Configuration validation failed")}}async function ft(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(Se,{searchPlaces:[`.${Se}rc`,"package.json",`${t.homedir()}/.${Se}rc`],stopDir:t.homedir()}),s;if(n?s=i.load(n):s=i.search(),s&&s.config)return Ue(s.config)}catch(e){if(e instanceof ae.ShipError)throw e}return{}}async function K(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await ft(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ue(i)}var L,ae,Se,ct,le=T(()=>{"use strict";L=require("zod"),ae=require("@shipstatic/types");C();Se="ship",ct=L.z.object({apiUrl:L.z.string().url().optional(),apiKey:L.z.string().optional(),deployToken:L.z.string().optional()}).strict()});async function ut(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),r=0,a=new e.ArrayBuffer,f=new FileReader,g=()=>{let w=r*2097152,l=Math.min(w+2097152,n.size);f.readAsArrayBuffer(n.slice(w,l))};f.onload=w=>{let l=w.target?.result;if(!l){i(M.ShipError.business("Failed to read file chunk"));return}a.append(l),r++,r<o?g():t({md5:a.end()})},f.onerror=()=>{i(M.ShipError.business("Failed to calculate MD5: FileReader error"))},g()})}async function dt(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,s)=>{let o=e.createHash("md5"),r=t.createReadStream(n);r.on("error",a=>s(M.ShipError.business(`Failed to read file for MD5: ${a.message}`))),r.on("data",a=>o.update(a)),r.on("end",()=>i({md5:o.digest("hex")}))})}async function $(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw M.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return ut(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw M.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return dt(n)}throw M.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var M,W=T(()=>{"use strict";C();M=require("@shipstatic/types")});function z(n){return!n||n.length===0?[]:n.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 s=t.slice(0,-1);for(let o of s)if(ce.some(r=>o.toLowerCase()===r.toLowerCase()))return!1;return!0})}var Ke,ce,fe=T(()=>{"use strict";Ke=require("junk"),ce=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function qe(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function me(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var xe=T(()=>{"use strict"});function U(n,e={}){if(e.flatten===!1)return n.map(i=>({path:me(i),name:Te(i)}));let t=yt(n);return n.map(i=>{let s=me(i);if(t){let o=t.endsWith("/")?t:`${t}/`;s.startsWith(o)&&(s=s.substring(o.length))}return s||(s=Te(i)),{path:s,name:Te(i)}})}function yt(n){if(!n.length)return"";let t=n.map(o=>me(o)).map(o=>o.split("/")),i=[],s=Math.min(...t.map(o=>o.length));for(let o=0;o<s-1;o++){let r=t[0][o];if(t.every(a=>a[o]===r))i.push(r);else break}return i.join("/")}function Te(n){return n.split(/[/\\]/).pop()||n}var ue=T(()=>{"use strict";xe()});function He(n){let e=[];try{let t=I.readdirSync(n);for(let i of t){let s=F.join(n,i),o=I.statSync(s);if(o.isDirectory()){let r=He(s);e.push(...r)}else o.isFile()&&e.push(s)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function Q(n,e={}){if(y()!=="node")throw O.ShipError.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let u=F.resolve(m);try{return I.statSync(u).isDirectory()?He(u):[u]}catch{throw O.ShipError.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],s=z(i);if(s.length===0)return[];let o=n.map(m=>F.resolve(m)),r=qe(o.map(m=>{try{return I.statSync(m).isDirectory()?m:F.dirname(m)}catch{return F.dirname(m)}})),a=s.map(m=>{if(r&&r.length>0){let u=F.relative(r,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return F.basename(m)}),f=U(a,{flatten:e.pathDetect!==!1}),g=[],w=0,l=b();for(let m=0;m<s.length;m++){let u=s[m],x=f[m].path;try{let R=I.statSync(u);if(R.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(R.size>l.maxFileSize)throw O.ShipError.business(`File ${u} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(w+=R.size,w>l.maxTotalSize)throw O.ShipError.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let ye=I.readFileSync(u),{md5:Qe}=await $(ye);if(x.includes("\0")||x.includes("/../")||x.startsWith("../")||x.endsWith("/.."))throw O.ShipError.business(`Security error: Unsafe file path "${x}" for file: ${u}`);g.push({path:x,content:ye,size:ye.length,md5:Qe})}catch(R){if(R instanceof O.ShipError&&R.isClientError&&R.isClientError())throw R;console.error(`Could not process file ${u}:`,R)}}if(g.length>l.maxFilesCount)throw O.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return g}var O,I,F,$e=T(()=>{"use strict";C();W();fe();O=require("@shipstatic/types");N();ue();xe();I=E(require("fs"),1),F=E(require("path"),1)});async function Ve(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(C(),Ne));if(t()!=="browser")throw Ie.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let i=n,s=i.map(l=>l.webkitRelativePath||l.name),o=U(s,{flatten:e.pathDetect!==!1}),r=[];for(let l=0;l<i.length;l++){let m=i[l],u=o[l].path;if(u.includes("..")||u.includes("\0"))throw Ie.ShipError.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);r.push({file:m,relativePath:u})}let a=r.map(l=>l.relativePath),f=z(a),g=new Set(f),w=[];for(let l of r){if(!g.has(l.relativePath))continue;let{md5:m}=await $(l.file);w.push({content:l.file,path:l.relativePath,size:l.file.size,md5:m})}return w}var Ie,je=T(()=>{"use strict";W();Ie=require("@shipstatic/types");fe();ue()});var Xe={};B(Xe,{convertBrowserInput:()=>Ye,convertDeployInput:()=>Ft,convertNodeInput:()=>ke});function Ge(n,e={}){let t=b();if(!e.skipEmptyCheck&&n.length===0)throw S.ShipError.business("No files to deploy.");if(n.length>t.maxFilesCount)throw S.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let s of n){if(s.size>t.maxFileSize)throw S.ShipError.business(`File ${s.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=s.size,i>t.maxTotalSize)throw S.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function We(n,e){if(e==="node"){if(!Array.isArray(n))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw S.ShipError.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}}function Je(n){let e=n.map(t=>({name:t.path,size:t.size}));return Ge(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function ke(n,e={}){We(n,"node");let t=await Q(n,e);return Je(t)}async function Ye(n,e={}){We(n,"browser");let t;if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw S.ShipError.business("Invalid input type for browser environment. Expected File[].");t=n}else throw S.ShipError.business("Invalid input type for browser environment. Expected File[].");t=t.filter(s=>s.size===0?(console.warn(`Skipping empty file: ${s.name}`),!1):!0),Ge(t);let i=await Ve(t,e);return Je(i)}async function Ft(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw S.ShipError.business("Unsupported execution environment.");let s;if(i==="node")if(typeof n=="string")s=await ke([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))s=await ke(n,e);else throw S.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");else s=await Ye(n,e);return s}var S,Ze=T(()=>{"use strict";S=require("@shipstatic/types");C();$e();je();N()});var te={};B(te,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>z,formatFileSize:()=>V,getCurrentConfig:()=>b,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>Ae});module.exports=st(te);var h={};B(h,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>ee,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,default:()=>Oe,filterJunk:()=>z,formatFileSize:()=>V,getCurrentConfig:()=>b,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>K,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,processFilesForNode:()=>Q,resolveConfig:()=>q,setConfig:()=>_,setPlatformConfig:()=>_,validateFiles:()=>Ae});var ge=E(require("mime-db"),1),ve={};for(let n in ge.default){let e=ge.default[n];e&&e.extensions&&e.extensions.forEach(t=>{ve[t]||(ve[t]=n)})}function oe(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ve[e]||"application/octet-stream"}var D=require("@shipstatic/types");var se=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 i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let s=Array.from(i);for(let o of s)try{o(...t)}catch(r){i.delete(o),e!=="error"&&setTimeout(()=>{r instanceof Error?this.emit("error",r,String(e)):this.emit("error",new Error(String(r)),String(e))},0)}}transfer(e){this.handlers.forEach((t,i)=>{t.forEach(s=>{e.on(i,s)})})}clear(){this.handlers.clear()}};C();var re="/deployments",Me="/ping",P="/domains",at="/config",lt="/account",De="/tokens",pt="/spa-check",A=class extends se{constructor(e){super(),this.apiUrl=e.apiUrl||D.DEFAULT_API,this.getAuthHeadersCallback=e.getAuthHeaders}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let s=this.getAuthHeaders(t.headers),o={...t,headers:s,credentials:s.Authorization?void 0:"include"};this.emit("request",e,o);try{let r=await fetch(e,o);r.ok||await this.handleResponseError(r,i);let a=this.safeClone(r),f=this.safeClone(r);return this.emit("response",a,e),await this.parseResponse(f)}catch(r){throw this.emit("error",r,e),this.handleFetchError(r,i),r}}getAuthHeaders(e={}){let t=this.getAuthHeadersCallback();return{...e,...t}}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 i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let s=i.message||i.error||`${t} failed due to API error`;throw e.status===401?D.ShipError.authentication(s):D.ShipError.api(s,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?D.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?D.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof D.ShipError?e:D.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Me}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${at}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:s}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let r={method:"POST",body:i,headers:{...s,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${re}`,r,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${re}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${re}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${re}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let s={};t&&(s.deployment=t),i&&i.length>0&&(s.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},r=this.getAuthHeaders(o.headers),a={...o,headers:r,credentials:r.Authorization?void 0:"include"};this.emit("request",`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let g=this.safeClone(f),w=this.safeClone(f);return this.emit("response",g,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),{...await this.parseResponse(w),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${P}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${P}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${P}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${lt}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${De}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${De}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${De}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(r=>r.path==="index.html"||r.path==="/index.html");if(!t||t.size>100*1024)return!1;let i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let s={files:e.map(r=>r.path),index:i};return(await this.request(`${this.apiUrl}${pt}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw D.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw D.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:s}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:s}}else throw D.ShipError.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,s=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw D.ShipError.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let r=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:r});i.append("files[]",a),s.push(o.md5)}return i.append("checksums",JSON.stringify(s)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:s}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),r=new i,a=[];for(let l of e){let m=oe(l.path),u;if(Buffer.isBuffer(l.content))u=new s([l.content],l.path,{type:m});else if(typeof Blob<"u"&&l.content instanceof Blob)u=new s([l.content],l.path,{type:m});else throw D.ShipError.file(`Unsupported file.content type for Node.js FormData: ${l.path}`,l.path);let x=l.path.startsWith("/")?l.path:"/"+l.path;r.append("files[]",u,x),a.push(l.md5)}r.append("checksums",JSON.stringify(a)),t&&t.length>0&&r.append("tags",JSON.stringify(t));let f=new o(r),g=[];for await(let l of f.encode())g.push(Buffer.from(l));let w=Buffer.concat(g);return{body:w,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}getBrowserContentType(e){return typeof e=="string"?oe(e):e.type||oe(e.name)}};var Ce=require("@shipstatic/types");N();var _e=require("@shipstatic/types");C();async function mt(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(le(),Be));return t(n)}else return{}}function q(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||_e.DEFAULT_API,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.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 G(n,e){let t={...n};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}var Ee=require("@shipstatic/types");W();async function ht(){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 $(t);return{path:Ee.DEPLOYMENT_CONFIG_FILENAME,content:t,size:e.length,md5:i}}async function Le(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Ee.DEPLOYMENT_CONFIG_FILENAME))return n;try{if(await e.checkSPA(n)){let s=await ht();return[...n,s]}}catch{}return n}function J(n,e,t,i,s){return{create:async(o,r={})=>{if(s&&!s()&&!r.deployToken&&!r.apiKey)throw new Error("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");t&&await t();let a=e?G(r,e):r,f=n();if(!i)throw new Error("processInput function is not provided.");let g=await i(o,a);return g=await Le(g,f,a),await f.deploy(g,a)},list:async()=>(t&&await t(),n().listDeployments()),remove:async o=>{t&&await t(),await n().removeDeployment(o)},get:async o=>(t&&await t(),n().getDeployment(o))}}function Y(n,e){return{set:async(t,i,s)=>(e&&await e(),n().setDomain(t,i,s)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function X(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function Z(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var H=class{constructor(e={}){this.initPromise=null;this._config=null;this.auth=null;this.clientOptions=e,e.deployToken?this.auth={type:"token",value:e.deployToken}:e.apiKey&&(this.auth={type:"apiKey",value:e.apiKey}),this.authHeadersCallback=()=>this.getAuthHeaders();let t=this.resolveInitialConfig(e);this.http=new A({...e,...t,getAuthHeaders:this.authHeadersCallback});let i=()=>this.ensureInitialized(),s=()=>this.http;this._deployments=J(s,this.clientOptions,i,(o,r)=>this.processInput(o,r),()=>this.hasAuth()),this._domains=Y(s,i),this._account=X(s,i),this._tokens=Z(s,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 domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=b(),this._config)}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}setDeployToken(e){if(!e||typeof e!="string")throw Ce.ShipError.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:e}}setApiKey(e){if(!e||typeof e!="string")throw Ce.ShipError.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:e}}getAuthHeaders(){if(!this.auth)return{};switch(this.auth.type){case"token":return{Authorization:`Bearer ${this.auth.value}`};case"apiKey":return{Authorization:`Bearer ${this.auth.value}`};default:return{}}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};var he=require("@shipstatic/types");C();le();N();var c={};B(c,{ApiHttp:()=>A,DEFAULT_API:()=>pe.DEFAULT_API,FILE_VALIDATION_STATUS:()=>d.FileValidationStatus,JUNK_DIRECTORIES:()=>ce,Ship:()=>H,ShipError:()=>k.ShipError,ShipErrorType:()=>k.ShipErrorType,__setTestEnvironment:()=>j,allValidFilesReady:()=>be,calculateMD5:()=>$,createAccountResource:()=>X,createDeploymentResource:()=>J,createDomainResource:()=>Y,createTokenResource:()=>Z,filterJunk:()=>z,formatFileSize:()=>V,getENV:()=>y,getValidFiles:()=>de,loadConfig:()=>mt,mergeDeployOptions:()=>G,optimizeDeployPaths:()=>U,pluralize:()=>Pe,resolveConfig:()=>q,validateFiles:()=>Ae});var v={};p(v,require("@shipstatic/types"));p(c,v);var pe=require("@shipstatic/types");W();function Pe(n,e,t,i=!0){let s=n===1?e:t;return i?`${n} ${s}`:s}fe();ue();C();var d=require("@shipstatic/types"),Re=E(require("mime-db"),1),gt=new Set(Object.keys(Re.default)),vt=new Map(Object.entries(Re.default).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));function V(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],s=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,s)).toFixed(e))+" "+i[s]}function wt(n){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(".")===!1&&(n.startsWith(" ")||n.endsWith(" ")||n.endsWith(".")))return{valid:!1,reason:"File name cannot start/end with spaces or end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,i=n.split("/").pop()||n;return t.test(i)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function Dt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],s=vt.get(e);if(s&&!s.has(i))return!1}return!0}function Ae(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(r=>({...r,status:d.FileValidationStatus.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let s=0;for(let o of n){let r=d.FileValidationStatus.READY,a="Ready for upload",f=o.name?wt(o.name):{valid:!1,reason:"File name cannot be empty"};o.status===d.FileValidationStatus.PROCESSING_ERROR?(r=d.FileValidationStatus.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("\0")?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${o.name}: ${a}`)):f.valid?o.size<=0?(r=d.FileValidationStatus.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(r=d.FileValidationStatus.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(g=>o.type.startsWith(g))?gt.has(o.type)?Dt(o.name,o.type)?o.size>e.maxFileSize?(r=d.FileValidationStatus.VALIDATION_FAILED,a=`File size (${V(o.size)}) exceeds limit of ${V(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(s+=o.size,s>e.maxTotalSize&&(r=d.FileValidationStatus.VALIDATION_FAILED,a=`Total size would exceed limit of ${V(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(r=d.FileValidationStatus.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)):(r=d.FileValidationStatus.VALIDATION_FAILED,a=f.reason||"Invalid file name",t.push(`${o.name}: ${a}`)),i.push({...o,status:r,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==d.FileValidationStatus.READY&&a.status!==d.FileValidationStatus.PENDING),r="Validation Failed";return o?.status===d.FileValidationStatus.PROCESSING_ERROR?r="Processing Error":o?.status===d.FileValidationStatus.EMPTY_FILE?r="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")||o?.statusMessage?.includes("File name contains")||o?.statusMessage?.includes("File name uses")||o?.statusMessage?.includes("File name cannot start")||o?.statusMessage?.includes("traversal")?r="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?r="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?r="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?r="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?r="Invalid File Type":o?.statusMessage?.includes("extension does not match")?r="Extension Mismatch":o?.statusMessage?.includes("Total size")?r="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(r="File Too Large"),{files:i.map(a=>({...a,status:d.FileValidationStatus.VALIDATION_FAILED})),validFiles:[],error:{error:r,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function de(n){return n.filter(e=>e.status===d.FileValidationStatus.READY)}function be(n){return de(n).length>0}var k=require("@shipstatic/types");p(h,c);le();N();N();$e();C();var ee=class extends H{constructor(e={}){if(y()!=="node")throw he.ShipError.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return q(e,{})}async loadFullConfig(){try{let e=await K(this.clientOptions.configFile),t=q(this.clientOptions,e),i=new A({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback});this.replaceHttpClient(i);let s=await this.http.getConfig();_(s)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw he.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw he.ShipError.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Ze(),Xe));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Oe=ee;p(te,h,module.exports);0&&(module.exports={ApiHttp,DEFAULT_API,FILE_VALIDATION_STATUS,JUNK_DIRECTORIES,Ship,ShipError,ShipErrorType,__setTestEnvironment,allValidFilesReady,calculateMD5,createAccountResource,createDeploymentResource,createDomainResource,createTokenResource,filterJunk,formatFileSize,getCurrentConfig,getENV,getValidFiles,loadConfig,mergeDeployOptions,optimizeDeployPaths,pluralize,processFilesForNode,resolveConfig,setConfig,setPlatformConfig,validateFiles});
|
|
2
2
|
|
|
3
3
|
// Ship SDK: Enable axios-style CommonJS imports
|
|
4
4
|
const originalExports = module.exports;
|