@shipstatic/ship 0.3.16 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _shipstatic_types from '@shipstatic/types';
2
- import { ProgressInfo, StaticFile, PingResponse, ConfigResponse, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
2
+ import { ProgressInfo, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, TokenCreateResponse, TokenListResponse, Account, ConfigResponse, PingResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
3
3
  export * from '@shipstatic/types';
4
4
  export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, ErrorType, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ResolvedConfig, ShipError, StaticFile, TokenResource } from '@shipstatic/types';
5
5
 
@@ -168,53 +168,36 @@ declare class ApiHttp extends SimpleEvents {
168
168
  private readonly createDeployBody;
169
169
  constructor(options: ApiHttpOptions);
170
170
  /**
171
- * Transfer events to another client (clean intentional API)
171
+ * Transfer events to another client
172
172
  */
173
173
  transferEventsTo(target: ApiHttp): void;
174
174
  /**
175
- * Make authenticated HTTP request with events and timeout
175
+ * Execute HTTP request with timeout, events, and error handling
176
176
  */
177
- private request;
177
+ private executeRequest;
178
178
  /**
179
- * Combine multiple AbortSignals into one
179
+ * Simple request - returns data only
180
180
  */
181
- private combineSignals;
181
+ private request;
182
182
  /**
183
- * Make request and return both data and HTTP status code
184
- * Used when the caller needs to inspect the status (e.g., 201 vs 200)
183
+ * Request with status - returns data and HTTP status code
185
184
  */
186
185
  private requestWithStatus;
187
- /**
188
- * Generate auth headers from Ship instance callback
189
- */
190
- private getAuthHeaders;
191
- /**
192
- * Safely clone response for events
193
- */
186
+ private mergeHeaders;
187
+ private createTimeoutSignal;
194
188
  private safeClone;
195
- /**
196
- * Parse JSON response
197
- */
198
189
  private parseResponse;
199
- /**
200
- * Handle response errors
201
- */
202
190
  private handleResponseError;
203
- /**
204
- * Handle fetch errors
205
- */
206
191
  private handleFetchError;
207
- ping(): Promise<boolean>;
208
- getPingResponse(): Promise<PingResponse>;
209
- getConfig(): Promise<ConfigResponse>;
210
192
  deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
211
193
  listDeployments(): Promise<DeploymentListResponse>;
212
194
  getDeployment(id: string): Promise<Deployment>;
195
+ updateDeploymentTags(id: string, tags: string[]): Promise<Deployment>;
213
196
  removeDeployment(id: string): Promise<void>;
214
197
  setDomain(name: string, deployment?: string, tags?: string[]): Promise<Domain>;
198
+ listDomains(): Promise<DomainListResponse>;
215
199
  getDomain(name: string): Promise<Domain>;
216
200
  updateDomainTags(name: string, tags: string[]): Promise<Domain>;
217
- listDomains(): Promise<DomainListResponse>;
218
201
  removeDomain(name: string): Promise<void>;
219
202
  verifyDomain(name: string): Promise<{
220
203
  message: string;
@@ -225,10 +208,13 @@ declare class ApiHttp extends SimpleEvents {
225
208
  domain: string;
226
209
  hash: string;
227
210
  }>;
228
- getAccount(): Promise<Account>;
229
211
  createToken(ttl?: number, tags?: string[]): Promise<TokenCreateResponse>;
230
212
  listTokens(): Promise<TokenListResponse>;
231
213
  removeToken(token: string): Promise<void>;
214
+ getAccount(): Promise<Account>;
215
+ getConfig(): Promise<ConfigResponse>;
216
+ ping(): Promise<boolean>;
217
+ getPingResponse(): Promise<PingResponse>;
232
218
  checkSPA(files: StaticFile[]): Promise<boolean>;
233
219
  }
234
220
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _shipstatic_types from '@shipstatic/types';
2
- import { ProgressInfo, StaticFile, PingResponse, ConfigResponse, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, Account, TokenCreateResponse, TokenListResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
2
+ import { ProgressInfo, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, TokenCreateResponse, TokenListResponse, Account, ConfigResponse, PingResponse, ResolvedConfig, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, ValidatableFile, FileValidationResult, ShipError } from '@shipstatic/types';
3
3
  export * from '@shipstatic/types';
4
4
  export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, DeploymentResource, Domain, DomainResource, ErrorType, FileValidationStatus as FILE_VALIDATION_STATUS, PingResponse, ResolvedConfig, ShipError, StaticFile, TokenResource } from '@shipstatic/types';
5
5
 
@@ -168,53 +168,36 @@ declare class ApiHttp extends SimpleEvents {
168
168
  private readonly createDeployBody;
169
169
  constructor(options: ApiHttpOptions);
170
170
  /**
171
- * Transfer events to another client (clean intentional API)
171
+ * Transfer events to another client
172
172
  */
173
173
  transferEventsTo(target: ApiHttp): void;
174
174
  /**
175
- * Make authenticated HTTP request with events and timeout
175
+ * Execute HTTP request with timeout, events, and error handling
176
176
  */
177
- private request;
177
+ private executeRequest;
178
178
  /**
179
- * Combine multiple AbortSignals into one
179
+ * Simple request - returns data only
180
180
  */
181
- private combineSignals;
181
+ private request;
182
182
  /**
183
- * Make request and return both data and HTTP status code
184
- * Used when the caller needs to inspect the status (e.g., 201 vs 200)
183
+ * Request with status - returns data and HTTP status code
185
184
  */
186
185
  private requestWithStatus;
187
- /**
188
- * Generate auth headers from Ship instance callback
189
- */
190
- private getAuthHeaders;
191
- /**
192
- * Safely clone response for events
193
- */
186
+ private mergeHeaders;
187
+ private createTimeoutSignal;
194
188
  private safeClone;
195
- /**
196
- * Parse JSON response
197
- */
198
189
  private parseResponse;
199
- /**
200
- * Handle response errors
201
- */
202
190
  private handleResponseError;
203
- /**
204
- * Handle fetch errors
205
- */
206
191
  private handleFetchError;
207
- ping(): Promise<boolean>;
208
- getPingResponse(): Promise<PingResponse>;
209
- getConfig(): Promise<ConfigResponse>;
210
192
  deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
211
193
  listDeployments(): Promise<DeploymentListResponse>;
212
194
  getDeployment(id: string): Promise<Deployment>;
195
+ updateDeploymentTags(id: string, tags: string[]): Promise<Deployment>;
213
196
  removeDeployment(id: string): Promise<void>;
214
197
  setDomain(name: string, deployment?: string, tags?: string[]): Promise<Domain>;
198
+ listDomains(): Promise<DomainListResponse>;
215
199
  getDomain(name: string): Promise<Domain>;
216
200
  updateDomainTags(name: string, tags: string[]): Promise<Domain>;
217
- listDomains(): Promise<DomainListResponse>;
218
201
  removeDomain(name: string): Promise<void>;
219
202
  verifyDomain(name: string): Promise<{
220
203
  message: string;
@@ -225,10 +208,13 @@ declare class ApiHttp extends SimpleEvents {
225
208
  domain: string;
226
209
  hash: string;
227
210
  }>;
228
- getAccount(): Promise<Account>;
229
211
  createToken(ttl?: number, tags?: string[]): Promise<TokenCreateResponse>;
230
212
  listTokens(): Promise<TokenListResponse>;
231
213
  removeToken(token: string): Promise<void>;
214
+ getAccount(): Promise<Account>;
215
+ getConfig(): Promise<ConfigResponse>;
216
+ ping(): Promise<boolean>;
217
+ getPingResponse(): Promise<PingResponse>;
232
218
  checkSPA(files: StaticFile[]): Promise<boolean>;
233
219
  }
234
220
 
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Pe=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var x=(o,e)=>()=>(o&&(e=o(o=0)),e);var _=(o,e)=>{for(var t in e)Pe(o,t,{get:e[t],enumerable:!0})},Ae=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of je(e))!Ge.call(o,r)&&r!==t&&Pe(o,r,{get:()=>e[r],enumerable:!(n=Ve(e,r))||n.enumerable});return o},p=(o,e,t)=>(Ae(o,e,"default"),t&&Ae(t,e,"default"));import{ShipError as Ze}from"@shipstatic/types";function L(o){ae=o}function I(){if(ae===null)throw Ze.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ae}var ae,U=x(()=>{"use strict";ae=null});function Z(o){pe=o}function et(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return pe||et()}var pe,P=x(()=>{"use strict";pe=null});var be={};_(be,{loadConfig:()=>$});import{z}from"zod";import{ShipError as ce}from"@shipstatic/types";function Ie(o){try{return tt.parse(o)}catch(e){if(e instanceof z.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw ce.config(`Configuration validation failed${n}: ${t.message}`)}throw ce.config("Configuration validation failed")}}async function nt(o){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),r;if(o?r=n.load(o):r=n.search(),r&&r.config)return Ie(r.config)}catch(e){if(e instanceof ce)throw e}return{}}async function $(o){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 nt(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ie(n)}var le,tt,ee=x(()=>{"use strict";P();le="ship",tt=z.object({apiUrl:z.string().url().optional(),apiKey:z.string().optional(),deployToken:z.string().optional()}).strict()});import{ShipError as O}from"@shipstatic/types";async function rt(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let i=Math.ceil(o.size/2097152),s=0,a=new e.ArrayBuffer,m=new FileReader,c=()=>{let y=s*2097152,l=Math.min(y+2097152,o.size);m.readAsArrayBuffer(o.slice(y,l))};m.onload=y=>{let l=y.target?.result;if(!l){n(O.business("Failed to read file chunk"));return}a.append(l),s++,s<i?c():t({md5:a.end()})},m.onerror=()=>{n(O.business("Failed to calculate MD5: FileReader error"))},c()})}async function st(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,r)=>{let i=e.createHash("md5"),s=t.createReadStream(o);s.on("error",a=>r(O.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>i.update(a)),s.on("end",()=>n({md5:i.digest("hex")}))})}async function b(o){let e=C();if(e==="browser"){if(!(o instanceof Blob))throw O.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return rt(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw O.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return st(o)}throw O.business("Unknown or unsupported execution environment for MD5 calculation.")}var te=x(()=>{"use strict";P()});import{isJunk as pt}from"junk";function G(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if(pt(n))return!1;let r=t.slice(0,-1);for(let i of r)if(ne.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var ne,de=x(()=>{"use strict";ne=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(o){if(!o||o.length===0)return"";let e=o.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)),n=[],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))n.push(s);else break}return n.join("/")}function oe(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var he=x(()=>{"use strict"});function W(o,e={}){if(e.flatten===!1)return o.map(n=>({path:oe(n),name:ye(n)}));let t=lt(o);return o.map(n=>{let r=oe(n);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=ye(n)),{path:r,name:ye(n)}})}function lt(o){if(!o.length)return"";let t=o.map(i=>oe(i)).map(i=>i.split("/")),n=[],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))n.push(s);else break}return n.join("/")}function ye(o){return o.split(/[/\\]/).pop()||o}var ge=x(()=>{"use strict";he()});var qe={};_(qe,{processFilesForNode:()=>re});import{ShipError as F}from"@shipstatic/types";import*as E from"fs";import*as v from"path";function Ke(o,e=new Set){let t=[],n=E.realpathSync(o);if(e.has(n))return t;e.add(n);let r=E.readdirSync(o);for(let i of r){let s=v.join(o,i),a=E.statSync(s);if(a.isDirectory()){let m=Ke(s,e);t.push(...m)}else a.isFile()&&t.push(s)}return t}async function re(o,e={}){if(C()!=="node")throw F.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(h=>{let g=v.resolve(h);try{return E.statSync(g).isDirectory()?Ke(g):[g]}catch{throw F.file(`Path does not exist: ${h}`,h)}}),n=[...new Set(t)],r=G(n);if(r.length===0)return[];let i=o.map(h=>v.resolve(h)),s=Ue(i.map(h=>{try{return E.statSync(h).isDirectory()?h:v.dirname(h)}catch{return v.dirname(h)}})),a=r.map(h=>{if(s&&s.length>0){let g=v.relative(s,h);if(g&&typeof g=="string"&&!g.startsWith(".."))return g.replace(/\\/g,"/")}return v.basename(h)}),m=W(a,{flatten:e.pathDetect!==!1}),c=[],y=0,l=I();for(let h=0;h<r.length;h++){let g=r[h],S=m[h].path;try{let T=E.statSync(g);if(T.size===0)continue;if(T.size>l.maxFileSize)throw F.business(`File ${g} is too large. Maximum allowed size is ${l.maxFileSize/(1024*1024)}MB.`);if(y+=T.size,y>l.maxTotalSize)throw F.business(`Total deploy size is too large. Maximum allowed is ${l.maxTotalSize/(1024*1024)}MB.`);let B=E.readFileSync(g),{md5:He}=await b(B);if(S.includes("\0")||S.includes("/../")||S.startsWith("../")||S.endsWith("/.."))throw F.business(`Security error: Unsafe file path "${S}" for file: ${g}`);c.push({path:S,content:B,size:B.length,md5:He})}catch(T){if(T instanceof F)throw T;let B=T instanceof Error?T.message:String(T);throw F.file(`Failed to read file "${g}": ${B}`,g)}}if(c.length>l.maxFilesCount)throw F.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}var Re=x(()=>{"use strict";P();te();de();U();ge();he()});var J={};_(J,{ApiHttp:()=>w,DEFAULT_API:()=>me,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,default:()=>xe,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getCurrentConfig:()=>I,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>$,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>fe,processFilesForNode:()=>re,resolveConfig:()=>k,setPlatformConfig:()=>L,validateFiles:()=>De});var d={};_(d,{ApiHttp:()=>w,DEFAULT_API:()=>me,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>ne,Ship:()=>Y,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,default:()=>xe,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getCurrentConfig:()=>I,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>$,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>fe,processFilesForNode:()=>re,resolveConfig:()=>k,setPlatformConfig:()=>L,validateFiles:()=>De});import{ShipError as A,DEFAULT_API as We}from"@shipstatic/types";var X=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let r=Array.from(n);for(let i of r)try{i(...t)}catch(s){n.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,n)=>{t.forEach(r=>{e.on(n,r)})})}clear(){this.handlers.clear()}};var Q="/deployments",Fe="/ping",R="/domains",Ye="/config",Je="/account",se="/tokens",Xe="/spa-check",Qe=3e4,w=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||We,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Qe,this.createDeployBody=e.createDeployBody}transferEventsTo(e){this.transfer(e)}async request(e,t={},n){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,m={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,m);try{let c=await fetch(e,m);clearTimeout(s),c.ok||await this.handleResponseError(c,n);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),await this.parseResponse(l)}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,n),c}}combineSignals(e,t){let n=new AbortController,r=()=>n.abort();return e.addEventListener("abort",r),t.addEventListener("abort",r),(e.aborted||t.aborted)&&n.abort(),n.signal}async requestWithStatus(e,t={},n){let r=this.getAuthHeaders(t.headers),i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),a=t.signal?this.combineSignals(t.signal,i.signal):i.signal,m={...t,headers:r,credentials:r.Authorization?void 0:"include",signal:a};this.emit("request",e,m);try{let c=await fetch(e,m);clearTimeout(s),c.ok||await this.handleResponseError(c,n);let y=this.safeClone(c),l=this.safeClone(c);return this.emit("response",y,e),{data:await this.parseResponse(l),status:c.status}}catch(c){throw clearTimeout(s),this.emit("error",c,e),this.handleFetchError(c,n),c}}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 n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let r=n.message||n.error||`${t} failed due to API error`;throw e.status===401?A.authentication(r):A.api(r,e.status,n.code,n)}handleFetchError(e,t){throw e.name==="AbortError"?A.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?A.network(`${t} failed due to network error: ${e.message}`,e):e instanceof A?e:A.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Ye}`,{method:"GET"},"Config")}async deploy(e,t={}){if(!e.length)throw A.business("No files to deploy.");for(let a of e)if(!a.md5)throw A.file(`MD5 checksum missing for file: ${a.path}`,a.path);let{body:n,headers:r}=await this.createDeployBody(e,t.tags,t.via),i={};t.deployToken?i.Authorization=`Bearer ${t.deployToken}`:t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`),t.caller&&(i["X-Caller"]=t.caller);let s={method:"POST",body:n,headers:{...r,...i},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${Q}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,n){let r={};t&&(r.deployment=t),n&&n.length>0&&(r.tags=n);let i=`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{data:s,status:a}=await this.requestWithStatus(i,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"Set Domain");return{...s,isCreate:a===201}}async getDomain(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async updateDomainTags(e,t){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({tags:t})},"Update Domain Tags")}async listDomains(){return await this.request(`${this.apiUrl}${R}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async verifyDomain(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${Je}`,{method:"GET"},"Get Account")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t&&t.length>0&&(n.tags=t),await this.request(`${this.apiUrl}${se}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${se}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${se}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${Xe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}};U();import{ShipError as Ne}from"@shipstatic/types";import{ShipError as Oe}from"@shipstatic/types";P();import{DEFAULT_API as ot}from"@shipstatic/types";async function it(o){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ee(),be));return t(o)}else return{}}function k(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||ot,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function K(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.caller===void 0&&e.caller!==void 0&&(t.caller=e.caller),t}te();import{DEPLOYMENT_CONFIG_FILENAME as $e}from"@shipstatic/types";async function at(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await b(t);return{path:$e,content:t,size:e.length,md5:n}}async function ke(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===$e))return o;try{if(await e.checkSPA(o)){let r=await at();return[...o,r]}}catch{}return o}function q(o){let{getApi:e,ensureInit:t,processInput:n,clientDefaults:r,hasAuth:i}=o;return{create:async(s,a={})=>{await t();let m=r?K(a,r):a;if(i&&!i()&&!m.deployToken&&!m.apiKey)throw Oe.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!n)throw Oe.config("processInput function is not provided.");let c=e(),y=await n(s,m);return y=await ke(y,c,m),c.deploy(y,m)},list:async()=>(await t(),e().listDeployments()),remove:async s=>{await t(),await e().removeDeployment(s)},get:async s=>(await t(),e().getDeployment(s))}}function H(o){let{getApi:e,ensureInit:t}=o;return{set:async(n,r,i)=>(await t(),e().setDomain(n,r,i)),update:async(n,r)=>(await t(),e().updateDomainTags(n,r)),get:async n=>(await t(),e().getDomain(n)),list:async()=>(await t(),e().listDomains()),remove:async n=>{await t(),await e().removeDomain(n)},verify:async n=>(await t(),e().verifyDomain(n)),dns:async n=>(await t(),e().getDomainDns(n)),records:async n=>(await t(),e().getDomainRecords(n)),share:async n=>(await t(),e().getDomainShare(n))}}function V(o){let{getApi:e,ensureInit:t}=o;return{get:async()=>(await t(),e().getAccount())}}function j(o){let{getApi:e,ensureInit:t}=o;return{create:async(n,r)=>(await t(),e().createToken(n,r)),list:async()=>(await t(),e().listTokens()),remove:async n=>{await t(),await e().removeToken(n)}}}var N=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 w({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let n={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=q({...n,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=H(n),this._account=V(n),this._tokens=j(n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get 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=I(),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 Ne.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 Ne.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}};P();ee();import{ShipError as we}from"@shipstatic/types";U();import{ShipError as _e}from"@shipstatic/types";import Me from"mime-db";var ue={};for(let o in Me){let e=Me[o];e&&e.extensions&&e.extensions.forEach(t=>{ue[t]||(ue[t]=o)})}function Be(o){let e=o.includes(".")?o.substring(o.lastIndexOf(".")+1).toLowerCase():"";return ue[e]||"application/octet-stream"}async function Le(o,e,t){let{FormData:n,File:r}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),s=new n,a=[];for(let l of o){let h=Be(l.path),g;if(Buffer.isBuffer(l.content))g=new r([l.content],l.path,{type:h});else if(typeof Blob<"u"&&l.content instanceof Blob)g=new r([l.content],l.path,{type:h});else throw _e.file(`Unsupported file.content type for Node.js: ${l.path}`,l.path);if(!l.md5)throw _e.file(`File missing md5 checksum: ${l.path}`,l.path);let S=l.path.startsWith("/")?l.path:"/"+l.path;s.append("files[]",g,S),a.push(l.md5)}s.append("checksums",JSON.stringify(a)),e&&e.length>0&&s.append("tags",JSON.stringify(e)),t&&s.append("via",t);let m=new i(s),c=[];for await(let l of m.encode())c.push(Buffer.from(l));let y=Buffer.concat(c);return{body:y.buffer.slice(y.byteOffset,y.byteOffset+y.byteLength),headers:{"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(y).toString()}}}var u={};_(u,{ApiHttp:()=>w,DEFAULT_API:()=>me,ErrorType:()=>Te,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>ne,Ship:()=>N,ShipError:()=>Se,__setTestEnvironment:()=>Z,allValidFilesReady:()=>Ce,calculateMD5:()=>b,createAccountResource:()=>V,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>j,ensureShipError:()=>Ee,filterJunk:()=>G,formatFileSize:()=>M,getENV:()=>C,getValidFiles:()=>ie,loadConfig:()=>it,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>W,pluralize:()=>fe,resolveConfig:()=>k,validateFiles:()=>De});var D={};p(D,Jt);import*as Jt from"@shipstatic/types";p(u,D);import{DEFAULT_API as me}from"@shipstatic/types";te();function fe(o,e,t,n=!0){let r=o===1?e:t;return n?`${o} ${r}`:r}de();ge();P();import{FileValidationStatus as f}from"@shipstatic/types";import ze from"mime-db";var ct=new Set(Object.keys(ze)),ut=new Map(Object.entries(ze).filter(([o,e])=>e.extensions).map(([o,e])=>[o,new Set(e.extensions)]));var mt=[[/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 ft(o,e){if(o===f.PROCESSING_ERROR)return"Processing Error";if(o===f.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,n]of mt)if(t.test(e))return n;return"Validation Failed"}function M(o,e=1){if(o===0)return"0 Bytes";let t=1024,n=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(o)/Math.log(t));return parseFloat((o/Math.pow(t,r)).toFixed(e))+" "+n[r]}function dt(o){if(/[?&#%<>\[\]{}|\\^~`;$()'"*\r\n\t]/.test(o))return{valid:!1,reason:"File name contains unsafe characters"};if(o.startsWith(" ")||o.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(o.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,n=o.split("/").pop()||o;return t.test(n)?{valid:!1,reason:"File name uses a reserved system name"}:o.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function ht(o,e){if(o.startsWith("."))return!0;let t=o.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let n=t[t.length-1],r=ut.get(e);if(r&&!r.has(n))return!1}return!0}function De(o,e){let t=[],n=[];if(o.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(o.length>e.maxFilesCount){let i=`Number of files (${o.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:o.map(s=>({...s,status:f.VALIDATION_FAILED,statusMessage:i})),validFiles:[],error:{error:"File Count Exceeded",details:i,errors:[i],isClientError:!0}}}let r=0;for(let i of o){let s=f.READY,a="Ready for upload",m=i.name?dt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===f.PROCESSING_ERROR?(s=f.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=f.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=f.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):m.valid?i.size<=0?(s=f.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.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(c=>i.type.startsWith(c))?ct.has(i.type)?ht(i.name,i.type)?i.size>e.maxFileSize?(s=f.VALIDATION_FAILED,a=`File size (${M(i.size)}) exceeds limit of ${M(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=f.VALIDATION_FAILED,a=`Total size would exceed limit of ${M(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=f.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=m.reason||"Invalid file name",t.push(`${i.name}: ${a}`)),n.push({...i,status:s,statusMessage:a})}if(t.length>0){let i=n.find(a=>a.status!==f.READY&&a.status!==f.PENDING),s=ft(i?.status,i?.statusMessage);return{files:n.map(a=>({...a,status:f.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:n,validFiles:n,error:null}}function ie(o){return o.filter(e=>e.status===f.READY)}function Ce(o){return ie(o).length>0}import{ShipError as ve}from"@shipstatic/types";function Ee(o){return o instanceof ve?o:o instanceof Error?ve.business(o.message):ve.business(String(o??"Unknown error"))}import{ShipError as Se,ErrorType as Te}from"@shipstatic/types";p(d,u);ee();U();Re();P();var Y=class extends N{constructor(e={}){if(C()!=="node")throw we.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return k(e,{})}async loadFullConfig(){try{let e=await $(this.clientOptions.configFile),t=k(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let n=new w({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(n);let r=await this.http.getConfig();L(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){let n=typeof e=="string"?[e]:e;if(!Array.isArray(n)||!n.every(i=>typeof i=="string"))throw we.business("Invalid input type for Node.js environment. Expected string or string[].");if(n.length===0)throw we.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Re(),qe));return r(n,t)}getDeployBodyCreator(){return Le}},xe=Y;p(J,d);export{w as ApiHttp,me as DEFAULT_API,Te as ErrorType,f as FILE_VALIDATION_STATUS,ne as JUNK_DIRECTORIES,Y as Ship,Se as ShipError,Z as __setTestEnvironment,Ce as allValidFilesReady,b as calculateMD5,V as createAccountResource,q as createDeploymentResource,H as createDomainResource,j as createTokenResource,xe as default,Ee as ensureShipError,G as filterJunk,M as formatFileSize,I as getCurrentConfig,C as getENV,ie as getValidFiles,$ as loadConfig,K as mergeDeployOptions,W as optimizeDeployPaths,fe as pluralize,re as processFilesForNode,k as resolveConfig,L as setPlatformConfig,De as validateFiles};
1
+ var Pe=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var He=Object.prototype.hasOwnProperty;var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var B=(n,e)=>{for(var t in e)Pe(n,t,{get:e[t],enumerable:!0})},Ae=(n,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qe(e))!He.call(n,r)&&r!==t&&Pe(n,r,{get:()=>e[r],enumerable:!(o=Ke(e,r))||o.enumerable});return n},p=(n,e,t)=>(Ae(n,e,"default"),t&&Ae(t,e,"default"));import{ShipError as Ge}from"@shipstatic/types";function L(n){re=n}function F(){if(re===null)throw Ge.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return re}var re,_=A(()=>{"use strict";re=null});function Q(n){se=n}function Ye(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function C(){return se||Ye()}var se,I=A(()=>{"use strict";se=null});var we={};B(we,{loadConfig:()=>O});import{z}from"zod";import{ShipError as pe}from"@shipstatic/types";function Ie(n){try{return We.parse(n)}catch(e){if(e instanceof z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${o}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function Je(n){try{if(C()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),r;if(n?r=o.load(n):r=o.search(),r&&r.config)return Ie(r.config)}catch(e){if(e instanceof pe)throw e}return{}}async function O(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 Je(n),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ie(o)}var ae,We,Z=A(()=>{"use strict";I();ae="ship",We=z.object({apiUrl:z.string().url().optional(),apiKey:z.string().optional(),deployToken:z.string().optional()}).strict()});import{ShipError as k}from"@shipstatic/types";async function Ze(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(k.business("Failed to read file chunk"));return}a.append(c),s++,s<i?S():t({md5:a.end()})},u.onerror=()=>{o(k.business("Failed to calculate MD5: FileReader error"))},S()})}async function et(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(k.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 b(n){let e=C();if(e==="browser"){if(!(n instanceof Blob))throw k.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ze(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw k.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return et(n)}throw k.business("Unknown or unsupported execution environment for MD5 calculation.")}var ee=A(()=>{"use strict";I()});import{isJunk as nt}from"junk";function G(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(nt(o))return!1;let r=t.slice(0,-1);for(let i of r)if(te.some(s=>i.toLowerCase()===s.toLowerCase()))return!1;return!0})}var te,me=A(()=>{"use strict";te=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ue(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 ne(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=A(()=>{"use strict"});function Y(n,e={}){if(e.flatten===!1)return n.map(o=>({path:ne(o),name:he(o)}));let t=ot(n);return n.map(o=>{let r=ne(o);if(t){let i=t.endsWith("/")?t:`${t}/`;r.startsWith(i)&&(r=r.substring(i.length))}return r||(r=he(o)),{path:r,name:he(o)}})}function ot(n){if(!n.length)return"";let t=n.map(i=>ne(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 he(n){return n.split(/[/\\]/).pop()||n}var ye=A(()=>{"use strict";de()});var _e={};B(_e,{processFilesForNode:()=>ie});import{ShipError as w}from"@shipstatic/types";import*as v from"fs";import*as E from"path";function Le(n,e=new Set){let t=[],o=v.realpathSync(n);if(e.has(o))return t;e.add(o);let r=v.readdirSync(n);for(let i of r){let s=E.join(n,i),a=v.statSync(s);if(a.isDirectory()){let u=Le(s,e);t.push(...u)}else a.isFile()&&t.push(s)}return t}async function ie(n,e={}){if(C()!=="node")throw w.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(h=>{let y=E.resolve(h);try{return v.statSync(y).isDirectory()?Le(y):[y]}catch{throw w.file(`Path does not exist: ${h}`,h)}}),o=[...new Set(t)],r=G(o);if(r.length===0)return[];let i=n.map(h=>E.resolve(h)),s=Ue(i.map(h=>{try{return v.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=Y(a,{flatten:e.pathDetect!==!1}),S=[],D=0,c=F();for(let h=0;h<r.length;h++){let y=r[h],T=u[h].path;try{let R=v.statSync(y);if(R.size===0)continue;if(R.size>c.maxFileSize)throw w.business(`File ${y} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(D+=R.size,D>c.maxTotalSize)throw w.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let U=v.readFileSync(y),{md5:ze}=await b(U);if(T.includes("\0")||T.includes("/../")||T.startsWith("../")||T.endsWith("/.."))throw w.business(`Security error: Unsafe file path "${T}" for file: ${y}`);S.push({path:T,content:U,size:U.length,md5:ze})}catch(R){if(R instanceof w)throw R;let U=R instanceof Error?R.message:String(R);throw w.file(`Failed to read file "${y}": ${U}`,y)}}if(S.length>c.maxFilesCount)throw w.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return S}var Te=A(()=>{"use strict";I();ee();me();_();ye();de()});var J={};B(J,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>xe,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});var m={};B(m,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,default:()=>xe,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getCurrentConfig:()=>F,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>O,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,processFilesForNode:()=>ie,resolveConfig:()=>$,setPlatformConfig:()=>L,validateFiles:()=>ge});import{ShipError as P,DEFAULT_API as je}from"@shipstatic/types";var X=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"},Ve=3e4,x=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||je,this.getAuthHeadersCallback=e.getAuthHeaders,this.timeout=e.timeout??Ve,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?P.authentication(r):P.api(r,e.status,o.code,o)}handleFetchError(e,t){throw e.name==="AbortError"?P.cancelled(`${t} was cancelled`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed: ${e.message}`,e):e instanceof P?e:P.business(`${t} failed: ${e.message||"Unknown error"}`)}async deploy(e,t={}){if(!e.length)throw P.business("No files to deploy");for(let s of e)if(!s.md5)throw P.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}};_();import{ShipError as Oe}from"@shipstatic/types";import{ShipError as le}from"@shipstatic/types";I();import{DEFAULT_API as Xe}from"@shipstatic/types";async function Qe(n){let e=C();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(Z(),we));return t(n)}else return{}}function $(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||Xe,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 K(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}ee();import{DEPLOYMENT_CONFIG_FILENAME as Fe}from"@shipstatic/types";async function tt(){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 b(t);return{path:Fe,content:t,size:e.length,md5:o}}async function be(n,e,t){if(t.spaDetect===!1||n.some(o=>o.path===Fe))return n;try{if(await e.checkSPA(n)){let r=await tt();return[...n,r]}}catch{}return n}function q(n){let{getApi:e,ensureInit:t,processInput:o,clientDefaults:r,hasAuth:i}=n;return{create:async(s,a={})=>{await t();let u=r?K(a,r):a;if(i&&!i()&&!u.deployToken&&!u.apiKey)throw le.authentication("Authentication credentials are required for deployment. Please call setDeployToken() or setApiKey() first, or pass credentials in the deployment options.");if(!o)throw le.config("processInput function is not provided.");let S=e(),D=await o(s,u);return D=await be(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 H(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 le.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 j(n){let{getApi:e,ensureInit:t}=n;return{get:async()=>(await t(),e().getAccount())}}function V(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 M=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 x({...e,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});let o={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this._deployments=q({...o,processInput:(r,i)=>this.processInput(r,i),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this._domains=H(o),this._account=j(o),this._tokens=V(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=F(),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 Oe.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 Oe.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}};I();Z();import{ShipError as Re}from"@shipstatic/types";_();import{ShipError as Me}from"@shipstatic/types";import $e from"mime-db";var ce={};for(let n in $e){let e=$e[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function ke(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}async function Ne(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=ke(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 Me.file(`Unsupported file.content type for Node.js: ${c.path}`,c.path);if(!c.md5)throw Me.file(`File missing md5 checksum: ${c.path}`,c.path);let T=c.path.startsWith("/")?c.path:"/"+c.path;s.append("files[]",y,T),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={};B(l,{ApiHttp:()=>x,DEFAULT_API:()=>ue,ErrorType:()=>ve,FILE_VALIDATION_STATUS:()=>f,JUNK_DIRECTORIES:()=>te,Ship:()=>M,ShipError:()=>Ee,__setTestEnvironment:()=>Q,allValidFilesReady:()=>De,calculateMD5:()=>b,createAccountResource:()=>j,createDeploymentResource:()=>q,createDomainResource:()=>H,createTokenResource:()=>V,ensureShipError:()=>Ce,filterJunk:()=>G,formatFileSize:()=>N,getENV:()=>C,getValidFiles:()=>oe,loadConfig:()=>Qe,mergeDeployOptions:()=>K,optimizeDeployPaths:()=>Y,pluralize:()=>fe,resolveConfig:()=>$,validateFiles:()=>ge});var g={};p(g,Ht);import*as Ht from"@shipstatic/types";p(l,g);import{DEFAULT_API as ue}from"@shipstatic/types";ee();function fe(n,e,t,o=!0){let r=n===1?e:t;return o?`${n} ${r}`:r}me();ye();I();import{FileValidationStatus as f}from"@shipstatic/types";import Be from"mime-db";var it=new Set(Object.keys(Be)),rt=new Map(Object.entries(Be).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)]));var st=[[/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 at(n,e){if(n===f.PROCESSING_ERROR)return"Processing Error";if(n===f.EMPTY_FILE)return"Empty File";if(!e)return"Validation Failed";for(let[t,o]of st)if(t.test(e))return o;return"Validation Failed"}function N(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 pt(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 lt(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=rt.get(e);if(r&&!r.has(o))return!1}return!0}function ge(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.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.READY,a="Ready for upload",u=i.name?pt(i.name):{valid:!1,reason:"File name cannot be empty"};i.status===f.PROCESSING_ERROR?(s=f.PROCESSING_ERROR,a=i.statusMessage||"A file failed during processing.",t.push(`${i.name}: ${a}`)):!i.name||i.name.trim().length===0?(s=f.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${i.name||"(empty)"}: ${a}`)):i.name.includes("\0")?(s=f.VALIDATION_FAILED,a="File name contains invalid characters (null byte)",t.push(`${i.name}: ${a}`)):u.valid?i.size<=0?(s=f.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.VALIDATION_FAILED,a="File MIME type is required",t.push(`${i.name}: ${a}`)):e.allowedMimeTypes.some(S=>i.type.startsWith(S))?it.has(i.type)?lt(i.name,i.type)?i.size>e.maxFileSize?(s=f.VALIDATION_FAILED,a=`File size (${N(i.size)}) exceeds limit of ${N(e.maxFileSize)}`,t.push(`${i.name}: ${a}`)):(r+=i.size,r>e.maxTotalSize&&(s=f.VALIDATION_FAILED,a=`Total size would exceed limit of ${N(e.maxTotalSize)}`,t.push(`${i.name}: ${a}`))):(s=f.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`Invalid MIME type "${i.type}"`,t.push(`${i.name}: ${a}`)):(s=f.VALIDATION_FAILED,a=`File type "${i.type}" is not allowed`,t.push(`${i.name}: ${a}`)):(s=f.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.READY&&a.status!==f.PENDING),s=at(i?.status,i?.statusMessage);return{files:o.map(a=>({...a,status:f.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 oe(n){return n.filter(e=>e.status===f.READY)}function De(n){return oe(n).length>0}import{ShipError as Se}from"@shipstatic/types";function Ce(n){return n instanceof Se?n:n instanceof Error?Se.business(n.message):Se.business(String(n??"Unknown error"))}import{ShipError as Ee,ErrorType as ve}from"@shipstatic/types";p(m,l);Z();_();Te();I();var W=class extends M{constructor(e={}){if(C()!=="node")throw Re.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return $(e,{})}async loadFullConfig(){try{let e=await O(this.clientOptions.configFile),t=$(this.clientOptions,e);t.deployToken&&!this.clientOptions.deployToken?this.setDeployToken(t.deployToken):t.apiKey&&!this.clientOptions.apiKey&&this.setApiKey(t.apiKey);let o=new x({...this.clientOptions,...t,getAuthHeaders:this.authHeadersCallback,createDeployBody:this.getDeployBodyCreator()});this.replaceHttpClient(o);let r=await this.http.getConfig();L(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 Re.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw Re.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(Te(),_e));return r(o,t)}getDeployBodyCreator(){return Ne}},xe=W;p(J,m);export{x as ApiHttp,ue as DEFAULT_API,ve as ErrorType,f as FILE_VALIDATION_STATUS,te as JUNK_DIRECTORIES,W as Ship,Ee as ShipError,Q as __setTestEnvironment,De as allValidFilesReady,b as calculateMD5,j as createAccountResource,q as createDeploymentResource,H as createDomainResource,V as createTokenResource,xe as default,Ce as ensureShipError,G as filterJunk,N as formatFileSize,F as getCurrentConfig,C as getENV,oe as getValidFiles,O as loadConfig,K as mergeDeployOptions,Y as optimizeDeployPaths,fe as pluralize,ie as processFilesForNode,$ as resolveConfig,L as setPlatformConfig,ge as validateFiles};
2
2
  //# sourceMappingURL=index.js.map