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