@shipstatic/ship 0.2.4 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -91,118 +91,132 @@ interface ShipClientOptions {
91
91
  */
92
92
  timeout?: number | undefined;
93
93
  }
94
+ /**
95
+ * Event map for Ship SDK events
96
+ * Core events for observability: request, response, error
97
+ */
98
+ interface ShipEvents extends Record<string, any[]> {
99
+ /** Emitted before each API request */
100
+ request: [url: string, init: RequestInit];
101
+ /** Emitted after successful API response */
102
+ response: [response: Response, url: string];
103
+ /** Emitted when API request fails */
104
+ error: [error: Error, url: string];
105
+ }
94
106
 
95
107
  /**
96
- * Handles direct HTTP communication with the Ship API, including deploys and health checks.
97
- * Responsible for constructing requests, managing authentication, and error translation.
98
- * @internal
108
+ * Event system for Ship SDK
109
+ * Lightweight, reliable event handling with proper error boundaries
99
110
  */
100
- declare class ApiHttp {
101
- #private;
102
- private readonly apiUrl;
103
- private readonly apiKey;
104
- private readonly deployToken;
111
+
112
+ /**
113
+ * Lightweight event system
114
+ * - Add handler: on()
115
+ * - Remove handler: off()
116
+ * - Emit events: emit() [internal]
117
+ * - Transfer events: transfer() [internal]
118
+ * - Reliable error handling and cleanup
119
+ */
120
+ declare class SimpleEvents {
121
+ private handlers;
105
122
  /**
106
- * Constructs a new ApiHttp instance with the provided client options.
107
- * @param options - Client options including API host, authentication credentials, and timeout settings.
123
+ * Add event handler
108
124
  */
109
- constructor(options: ShipClientOptions);
125
+ on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
110
126
  /**
111
- * Sends a ping request to the Ship API server to verify connectivity and authentication.
112
- * @returns Promise resolving to `true` if the ping is successful, `false` otherwise.
113
- * @throws {ShipApiError} If the API returns an error response (4xx, 5xx).
114
- * @throws {ShipNetworkError} If a network error occurs (e.g., DNS failure, connection refused).
127
+ * Remove event handler
115
128
  */
116
- ping(): Promise<boolean>;
129
+ off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
117
130
  /**
118
- * Get full ping response from the API server
119
- * @returns Promise resolving to the full PingResponse object.
131
+ * Emit event (internal use only)
132
+ * @internal
120
133
  */
121
- getPingResponse(): Promise<PingResponse>;
134
+ emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void;
122
135
  /**
123
- * Fetches platform configuration from the API.
124
- * @returns Promise resolving to the config response.
125
- * @throws {ShipError} If the config request fails.
136
+ * Transfer all handlers to another events instance
137
+ * @internal
126
138
  */
127
- getConfig(): Promise<ConfigResponse>;
139
+ transfer(target: SimpleEvents): void;
128
140
  /**
129
- * Deploys an array of StaticFile objects to the Ship API.
130
- * Constructs and sends a multipart/form-data POST request, handling both browser and Node.js environments.
131
- * Validates files and manages deploy progress and error translation.
132
- * @param files - Array of StaticFile objects to deploy (must include MD5 checksums).
133
- * @param options - Optional per-deploy configuration (overrides instance defaults).
134
- * @returns Promise resolving to a full Deployment object on success.
135
- * @throws {ShipFileError} If a file is missing an MD5 checksum or content type is unsupported.
136
- * @throws {ShipClientError} If no files are provided or if environment is unknown.
137
- * @throws {ShipNetworkError} If a network error occurs during deploy.
138
- * @throws {ShipApiError} If the API returns an error response.
139
- * @throws {ShipCancelledError} If the deploy is cancelled via an AbortSignal.
141
+ * Clear all handlers (for cleanup)
142
+ * @internal
140
143
  */
141
- deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
144
+ clear(): void;
145
+ }
146
+
147
+ /**
148
+ * @file HTTP client with integrated event system
149
+ * Clean, direct implementation with reliable error handling
150
+ */
151
+
152
+ /**
153
+ * HTTP client with integrated event system
154
+ * - Direct event integration
155
+ * - Clean inheritance from SimpleEvents
156
+ * - Reliable error handling
157
+ */
158
+ declare class ApiHttp extends SimpleEvents {
159
+ private readonly apiUrl;
160
+ private readonly apiKey;
161
+ private readonly deployToken;
162
+ constructor(options: ShipClientOptions);
142
163
  /**
143
- * Lists all deployments for the authenticated account
144
- * @returns Promise resolving to deployment list response
164
+ * Transfer events to another client (clean intentional API)
145
165
  */
146
- listDeployments(): Promise<DeploymentListResponse>;
166
+ transferEventsTo(target: ApiHttp): void;
147
167
  /**
148
- * Gets a specific deployment by ID
149
- * @param id - Deployment ID to retrieve
150
- * @returns Promise resolving to deployment details
168
+ * Make authenticated HTTP request with events
151
169
  */
152
- getDeployment(id: string): Promise<Deployment>;
170
+ private request;
153
171
  /**
154
- * Removes a deployment by ID
155
- * @param id - Deployment ID to remove
156
- * @returns Promise resolving when removal is complete
172
+ * Generate auth headers
157
173
  */
158
- removeDeployment(id: string): Promise<void>;
174
+ private getAuthHeaders;
159
175
  /**
160
- * Sets an alias (create or update)
161
- * @param name - Alias name
162
- * @param deployment - Deployment name to point to
163
- * @returns Promise resolving to the created/updated alias with operation context
176
+ * Check if credentials are needed
164
177
  */
165
- setAlias(name: string, deployment: string): Promise<_shipstatic_types.Alias>;
178
+ private needsCredentials;
166
179
  /**
167
- * Gets a specific alias by name
168
- * @param name - Alias name to retrieve
169
- * @returns Promise resolving to alias details
180
+ * Safely clone response for events
170
181
  */
171
- getAlias(name: string): Promise<Alias>;
182
+ private safeClone;
172
183
  /**
173
- * Lists all aliases for the authenticated account
174
- * @returns Promise resolving to alias list response
184
+ * Parse JSON response
175
185
  */
176
- listAliases(): Promise<AliasListResponse>;
186
+ private parseResponse;
177
187
  /**
178
- * Removes an alias by name
179
- * @param name - Alias name to remove
180
- * @returns Promise resolving to removal confirmation
188
+ * Handle response errors
181
189
  */
182
- removeAlias(name: string): Promise<void>;
190
+ private handleResponseError;
183
191
  /**
184
- * Triggers a manual DNS check for an external alias
185
- * @param name - Alias name to check DNS for
186
- * @returns Promise resolving to confirmation message
192
+ * Handle fetch errors
187
193
  */
194
+ private handleFetchError;
195
+ ping(): Promise<boolean>;
196
+ getPingResponse(): Promise<PingResponse>;
197
+ getConfig(): Promise<ConfigResponse>;
198
+ deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
199
+ listDeployments(): Promise<DeploymentListResponse>;
200
+ getDeployment(id: string): Promise<Deployment>;
201
+ removeDeployment(id: string): Promise<void>;
202
+ setAlias(name: string, deployment: string): Promise<Alias>;
203
+ getAlias(name: string): Promise<Alias>;
204
+ listAliases(): Promise<AliasListResponse>;
205
+ removeAlias(name: string): Promise<void>;
188
206
  checkAlias(name: string): Promise<{
189
207
  message: string;
190
208
  }>;
191
- /**
192
- * Gets account details for the authenticated user
193
- * @returns Promise resolving to account details
194
- */
195
209
  getAccount(): Promise<Account>;
196
- /**
197
- * Checks if files represent a SPA structure using AI analysis
198
- * @param files - Array of StaticFile objects to analyze
199
- * @returns Promise resolving to boolean indicating if it's a SPA
200
- */
201
210
  checkSPA(files: StaticFile[]): Promise<boolean>;
211
+ private validateFiles;
212
+ private prepareRequestPayload;
213
+ private createBrowserBody;
214
+ private createNodeBody;
215
+ private getBrowserContentType;
202
216
  }
203
217
 
204
218
  /**
205
- * @file All Ship SDK resources in one place - impossibly simple.
219
+ * @file Ship SDK resource implementations for deployments, aliases, and accounts.
206
220
  */
207
221
 
208
222
  declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?: ShipClientOptions, ensureInit?: () => Promise<void>, processInput?: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>): DeploymentResource;
@@ -254,6 +268,24 @@ declare abstract class Ship$1 {
254
268
  * Get account resource
255
269
  */
256
270
  get account(): AccountResource;
271
+ /**
272
+ * Add event listener
273
+ * @param event - Event name
274
+ * @param handler - Event handler function
275
+ */
276
+ on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
277
+ /**
278
+ * Remove event listener
279
+ * @param event - Event name
280
+ * @param handler - Event handler function
281
+ */
282
+ off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
283
+ /**
284
+ * Replace HTTP client while preserving event listeners
285
+ * Used during initialization to maintain user event subscriptions
286
+ * @protected
287
+ */
288
+ protected replaceHttpClient(newClient: ApiHttp): void;
257
289
  }
258
290
 
259
291
  /**
@@ -452,4 +484,4 @@ declare class Ship extends Ship$1 {
452
484
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
453
485
  }
454
486
 
455
- export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
487
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
package/dist/index.d.ts CHANGED
@@ -91,118 +91,132 @@ interface ShipClientOptions {
91
91
  */
92
92
  timeout?: number | undefined;
93
93
  }
94
+ /**
95
+ * Event map for Ship SDK events
96
+ * Core events for observability: request, response, error
97
+ */
98
+ interface ShipEvents extends Record<string, any[]> {
99
+ /** Emitted before each API request */
100
+ request: [url: string, init: RequestInit];
101
+ /** Emitted after successful API response */
102
+ response: [response: Response, url: string];
103
+ /** Emitted when API request fails */
104
+ error: [error: Error, url: string];
105
+ }
94
106
 
95
107
  /**
96
- * Handles direct HTTP communication with the Ship API, including deploys and health checks.
97
- * Responsible for constructing requests, managing authentication, and error translation.
98
- * @internal
108
+ * Event system for Ship SDK
109
+ * Lightweight, reliable event handling with proper error boundaries
99
110
  */
100
- declare class ApiHttp {
101
- #private;
102
- private readonly apiUrl;
103
- private readonly apiKey;
104
- private readonly deployToken;
111
+
112
+ /**
113
+ * Lightweight event system
114
+ * - Add handler: on()
115
+ * - Remove handler: off()
116
+ * - Emit events: emit() [internal]
117
+ * - Transfer events: transfer() [internal]
118
+ * - Reliable error handling and cleanup
119
+ */
120
+ declare class SimpleEvents {
121
+ private handlers;
105
122
  /**
106
- * Constructs a new ApiHttp instance with the provided client options.
107
- * @param options - Client options including API host, authentication credentials, and timeout settings.
123
+ * Add event handler
108
124
  */
109
- constructor(options: ShipClientOptions);
125
+ on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
110
126
  /**
111
- * Sends a ping request to the Ship API server to verify connectivity and authentication.
112
- * @returns Promise resolving to `true` if the ping is successful, `false` otherwise.
113
- * @throws {ShipApiError} If the API returns an error response (4xx, 5xx).
114
- * @throws {ShipNetworkError} If a network error occurs (e.g., DNS failure, connection refused).
127
+ * Remove event handler
115
128
  */
116
- ping(): Promise<boolean>;
129
+ off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
117
130
  /**
118
- * Get full ping response from the API server
119
- * @returns Promise resolving to the full PingResponse object.
131
+ * Emit event (internal use only)
132
+ * @internal
120
133
  */
121
- getPingResponse(): Promise<PingResponse>;
134
+ emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void;
122
135
  /**
123
- * Fetches platform configuration from the API.
124
- * @returns Promise resolving to the config response.
125
- * @throws {ShipError} If the config request fails.
136
+ * Transfer all handlers to another events instance
137
+ * @internal
126
138
  */
127
- getConfig(): Promise<ConfigResponse>;
139
+ transfer(target: SimpleEvents): void;
128
140
  /**
129
- * Deploys an array of StaticFile objects to the Ship API.
130
- * Constructs and sends a multipart/form-data POST request, handling both browser and Node.js environments.
131
- * Validates files and manages deploy progress and error translation.
132
- * @param files - Array of StaticFile objects to deploy (must include MD5 checksums).
133
- * @param options - Optional per-deploy configuration (overrides instance defaults).
134
- * @returns Promise resolving to a full Deployment object on success.
135
- * @throws {ShipFileError} If a file is missing an MD5 checksum or content type is unsupported.
136
- * @throws {ShipClientError} If no files are provided or if environment is unknown.
137
- * @throws {ShipNetworkError} If a network error occurs during deploy.
138
- * @throws {ShipApiError} If the API returns an error response.
139
- * @throws {ShipCancelledError} If the deploy is cancelled via an AbortSignal.
141
+ * Clear all handlers (for cleanup)
142
+ * @internal
140
143
  */
141
- deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
144
+ clear(): void;
145
+ }
146
+
147
+ /**
148
+ * @file HTTP client with integrated event system
149
+ * Clean, direct implementation with reliable error handling
150
+ */
151
+
152
+ /**
153
+ * HTTP client with integrated event system
154
+ * - Direct event integration
155
+ * - Clean inheritance from SimpleEvents
156
+ * - Reliable error handling
157
+ */
158
+ declare class ApiHttp extends SimpleEvents {
159
+ private readonly apiUrl;
160
+ private readonly apiKey;
161
+ private readonly deployToken;
162
+ constructor(options: ShipClientOptions);
142
163
  /**
143
- * Lists all deployments for the authenticated account
144
- * @returns Promise resolving to deployment list response
164
+ * Transfer events to another client (clean intentional API)
145
165
  */
146
- listDeployments(): Promise<DeploymentListResponse>;
166
+ transferEventsTo(target: ApiHttp): void;
147
167
  /**
148
- * Gets a specific deployment by ID
149
- * @param id - Deployment ID to retrieve
150
- * @returns Promise resolving to deployment details
168
+ * Make authenticated HTTP request with events
151
169
  */
152
- getDeployment(id: string): Promise<Deployment>;
170
+ private request;
153
171
  /**
154
- * Removes a deployment by ID
155
- * @param id - Deployment ID to remove
156
- * @returns Promise resolving when removal is complete
172
+ * Generate auth headers
157
173
  */
158
- removeDeployment(id: string): Promise<void>;
174
+ private getAuthHeaders;
159
175
  /**
160
- * Sets an alias (create or update)
161
- * @param name - Alias name
162
- * @param deployment - Deployment name to point to
163
- * @returns Promise resolving to the created/updated alias with operation context
176
+ * Check if credentials are needed
164
177
  */
165
- setAlias(name: string, deployment: string): Promise<_shipstatic_types.Alias>;
178
+ private needsCredentials;
166
179
  /**
167
- * Gets a specific alias by name
168
- * @param name - Alias name to retrieve
169
- * @returns Promise resolving to alias details
180
+ * Safely clone response for events
170
181
  */
171
- getAlias(name: string): Promise<Alias>;
182
+ private safeClone;
172
183
  /**
173
- * Lists all aliases for the authenticated account
174
- * @returns Promise resolving to alias list response
184
+ * Parse JSON response
175
185
  */
176
- listAliases(): Promise<AliasListResponse>;
186
+ private parseResponse;
177
187
  /**
178
- * Removes an alias by name
179
- * @param name - Alias name to remove
180
- * @returns Promise resolving to removal confirmation
188
+ * Handle response errors
181
189
  */
182
- removeAlias(name: string): Promise<void>;
190
+ private handleResponseError;
183
191
  /**
184
- * Triggers a manual DNS check for an external alias
185
- * @param name - Alias name to check DNS for
186
- * @returns Promise resolving to confirmation message
192
+ * Handle fetch errors
187
193
  */
194
+ private handleFetchError;
195
+ ping(): Promise<boolean>;
196
+ getPingResponse(): Promise<PingResponse>;
197
+ getConfig(): Promise<ConfigResponse>;
198
+ deploy(files: StaticFile[], options?: ApiDeployOptions): Promise<Deployment>;
199
+ listDeployments(): Promise<DeploymentListResponse>;
200
+ getDeployment(id: string): Promise<Deployment>;
201
+ removeDeployment(id: string): Promise<void>;
202
+ setAlias(name: string, deployment: string): Promise<Alias>;
203
+ getAlias(name: string): Promise<Alias>;
204
+ listAliases(): Promise<AliasListResponse>;
205
+ removeAlias(name: string): Promise<void>;
188
206
  checkAlias(name: string): Promise<{
189
207
  message: string;
190
208
  }>;
191
- /**
192
- * Gets account details for the authenticated user
193
- * @returns Promise resolving to account details
194
- */
195
209
  getAccount(): Promise<Account>;
196
- /**
197
- * Checks if files represent a SPA structure using AI analysis
198
- * @param files - Array of StaticFile objects to analyze
199
- * @returns Promise resolving to boolean indicating if it's a SPA
200
- */
201
210
  checkSPA(files: StaticFile[]): Promise<boolean>;
211
+ private validateFiles;
212
+ private prepareRequestPayload;
213
+ private createBrowserBody;
214
+ private createNodeBody;
215
+ private getBrowserContentType;
202
216
  }
203
217
 
204
218
  /**
205
- * @file All Ship SDK resources in one place - impossibly simple.
219
+ * @file Ship SDK resource implementations for deployments, aliases, and accounts.
206
220
  */
207
221
 
208
222
  declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?: ShipClientOptions, ensureInit?: () => Promise<void>, processInput?: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>): DeploymentResource;
@@ -254,6 +268,24 @@ declare abstract class Ship$1 {
254
268
  * Get account resource
255
269
  */
256
270
  get account(): AccountResource;
271
+ /**
272
+ * Add event listener
273
+ * @param event - Event name
274
+ * @param handler - Event handler function
275
+ */
276
+ on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
277
+ /**
278
+ * Remove event listener
279
+ * @param event - Event name
280
+ * @param handler - Event handler function
281
+ */
282
+ off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
283
+ /**
284
+ * Replace HTTP client while preserving event listeners
285
+ * Used during initialization to maintain user event subscriptions
286
+ * @protected
287
+ */
288
+ protected replaceHttpClient(newClient: ApiHttp): void;
257
289
  }
258
290
 
259
291
  /**
@@ -452,4 +484,4 @@ declare class Ship extends Ship$1 {
452
484
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
453
485
  }
454
486
 
455
- export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
487
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createAliasResource, createDeploymentResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Se=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var b=(o,e)=>()=>(o&&(e=o(o=0)),e);var $=(o,e)=>{for(var t in e)Se(o,t,{get:e[t],enumerable:!0})},Pe=(o,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Me(e))!_e.call(o,n)&&n!==t&&Se(o,n,{get:()=>e[n],enumerable:!(i=Le(e,n))||i.enumerable});return o},p=(o,e,t)=>(Pe(o,e,"default"),t&&Pe(t,e,"default"));var Fe={};$(Fe,{__setTestEnvironment:()=>L,getENV:()=>h});function L(o){re=o}function je(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return re||je()}var re,D=b(()=>{"use strict";re=null});var De={};$(De,{loadConfig:()=>I});import{z as _}from"zod";import{ShipError as ae}from"@shipstatic/types";function Ce(o){try{return We.parse(o)}catch(e){if(e instanceof _.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw ae.config(`Configuration validation failed${i}: ${t.message}`)}throw ae.config("Configuration validation failed")}}async function Ye(o){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(se,{searchPlaces:[`.${se}rc`,"package.json",`${t.homedir()}/.${se}rc`],stopDir:t.homedir()}),n;if(o?n=i.load(o):n=i.search(),n&&n.config)return Ce(n.config)}catch(e){if(e instanceof ae)throw e}return{}}async function I(o){if(h()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Ye(o),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ce(i)}var se,We,ee=b(()=>{"use strict";D();se="ship",We=_.object({apiUrl:_.string().url().optional(),apiKey:_.string().optional(),deployToken:_.string().optional()}).strict()});import{ShipError as B}from"@shipstatic/types";async function Qe(o){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let r=Math.ceil(o.size/2097152),s=0,m=new e.ArrayBuffer,u=new FileReader,w=()=>{let g=s*2097152,c=Math.min(g+2097152,o.size);u.readAsArrayBuffer(o.slice(g,c))};u.onload=g=>{let c=g.target?.result;if(!c){i(B.business("Failed to read file chunk"));return}m.append(c),s++,s<r?w():t({md5:m.end()})},u.onerror=()=>{i(B.business("Failed to calculate MD5: FileReader error"))},w()})}async function et(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let i=e.createHash("md5");return i.update(o),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,n)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",m=>n(B.business(`Failed to read file for MD5: ${m.message}`))),s.on("data",m=>r.update(m)),s.on("end",()=>i({md5:r.digest("hex")}))})}async function v(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw B.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Qe(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw B.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return et(o)}throw B.business("Unknown or unsupported execution environment for MD5 calculation.")}var K=b(()=>{"use strict";D()});import{ShipError as ot}from"@shipstatic/types";function J(o){pe=o}function T(){if(pe===null)throw ot.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return pe}var pe,V=b(()=>{"use strict";pe=null});import{isJunk as it}from"junk";function k(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(it(i))return!1;let n=t.slice(0,-1);for(let r of n)if(te.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var te,oe=b(()=>{"use strict";te=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ve(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),i=[],n=Math.min(...t.map(r=>r.length));for(let r=0;r<n;r++){let s=t[0][r];if(t.every(m=>m[r]===s))i.push(s);else break}return i.join("/")}function ie(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var fe=b(()=>{"use strict"});function R(o,e={}){if(e.flatten===!1)return o.map(i=>({path:ie(i),name:me(i)}));let t=nt(o);return o.map(i=>{let n=ie(i);if(t){let r=t.endsWith("/")?t:`${t}/`;n.startsWith(r)&&(n=n.substring(r.length))}return n||(n=me(i)),{path:n,name:me(i)}})}function nt(o){if(!o.length)return"";let t=o.map(r=>ie(r)).map(r=>r.split("/")),i=[],n=Math.min(...t.map(r=>r.length));for(let r=0;r<n-1;r++){let s=t[0][r];if(t.every(m=>m[r]===s))i.push(s);else break}return i.join("/")}function me(o){return o.split(/[/\\]/).pop()||o}var ne=b(()=>{"use strict";fe()});import{ShipError as O}from"@shipstatic/types";import*as E from"fs";import*as F from"path";function Ee(o){let e=[];try{let t=E.readdirSync(o);for(let i of t){let n=F.join(o,i),r=E.statSync(n);if(r.isDirectory()){let s=Ee(n);e.push(...s)}else r.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function W(o,e={}){if(h()!=="node")throw O.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(f=>{let a=F.resolve(f);try{return E.statSync(a).isDirectory()?Ee(a):[a]}catch{throw O.file(`Path does not exist: ${f}`,f)}}),i=[...new Set(t)],n=k(i);if(n.length===0)return[];let r=o.map(f=>F.resolve(f)),s=ve(r.map(f=>{try{return E.statSync(f).isDirectory()?f:F.dirname(f)}catch{return F.dirname(f)}})),m=n.map(f=>{if(s&&s.length>0){let a=F.relative(s,f);if(a&&typeof a=="string"&&!a.startsWith(".."))return a.replace(/\\/g,"/")}return F.basename(f)}),u=R(m,{flatten:e.pathDetect!==!1}),w=[],g=0,c=T();for(let f=0;f<n.length;f++){let a=n[f],C=u[f].path;try{let S=E.statSync(a);if(S.size===0){console.warn(`Skipping empty file: ${a}`);continue}if(S.size>c.maxFileSize)throw O.business(`File ${a} is too large. Maximum allowed size is ${c.maxFileSize/(1024*1024)}MB.`);if(g+=S.size,g>c.maxTotalSize)throw O.business(`Total deploy size is too large. Maximum allowed is ${c.maxTotalSize/(1024*1024)}MB.`);let z=E.readFileSync(a),{md5:ze}=await v(z);if(C.includes("\0")||C.includes("/../")||C.startsWith("../")||C.endsWith("/.."))throw O.business(`Security error: Unsafe file path "${C}" for file: ${a}`);w.push({path:C,content:z,size:z.length,md5:ze})}catch(S){if(S instanceof O&&S.isClientError&&S.isClientError())throw S;console.error(`Could not process file ${a}:`,S)}}if(w.length>c.maxFilesCount)throw O.business(`Too many files to deploy. Maximum allowed is ${c.maxFilesCount} files.`);return w}var he=b(()=>{"use strict";D();K();oe();V();ne();fe()});import{ShipError as Te}from"@shipstatic/types";async function ke(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(D(),Fe));if(t()!=="browser")throw Te.business("processFilesForBrowser can only be called in a browser environment.");let i=Array.isArray(o)?o:Array.from(o),n=i.map(c=>c.webkitRelativePath||c.name),r=R(n,{flatten:e.pathDetect!==!1}),s=[];for(let c=0;c<i.length;c++){let f=i[c],a=r[c].path;if(a.includes("..")||a.includes("\0"))throw Te.business(`Security error: Unsafe file path "${a}" for file: ${f.name}`);s.push({file:f,relativePath:a})}let m=s.map(c=>c.relativePath),u=k(m),w=new Set(u),g=[];for(let c of s){if(!w.has(c.relativePath))continue;let{md5:f}=await v(c.file);g.push({content:c.file,path:c.relativePath,size:c.file.size,md5:f})}return g}var Re=b(()=>{"use strict";K();oe();ne()});var Be={};$(Be,{convertBrowserInput:()=>Ne,convertDeployInput:()=>rt,convertNodeInput:()=>ye});import{ShipError as A}from"@shipstatic/types";function Oe(o,e={}){let t=T();if(!e.skipEmptyCheck&&o.length===0)throw A.business("No files to deploy.");if(o.length>t.maxFilesCount)throw A.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let n of o){if(n.size>t.maxFileSize)throw A.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=n.size,i>t.maxTotalSize)throw A.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function $e(o,e){if(e==="node"){if(!Array.isArray(o))throw A.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw A.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw A.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw A.business("No files selected in HTMLInputElement")}function Ie(o){let e=o.map(t=>({name:t.path,size:t.size}));return Oe(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function ye(o,e={}){$e(o,"node");let t=await W(o,e);return Ie(t)}async function Ne(o,e={}){$e(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw A.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw A.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),Oe(t);let i=await ke(t,e);return Ie(i)}async function rt(o,e={},t){let i=h();if(i!=="node"&&i!=="browser")throw A.business("Unsupported execution environment.");let n;if(i==="node")if(typeof o=="string")n=await ye([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))n=await ye(o,e);else throw A.business("Invalid input type for Node.js environment. Expected string[] file paths.");else n=await Ne(o,e);return n}var Ue=b(()=>{"use strict";D();he();Re();V()});var X={};$(X,{ApiHttp:()=>x,DEFAULT_API:()=>le,JUNK_DIRECTORIES:()=>te,Ship:()=>Y,ShipError:()=>ue,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,default:()=>we,filterJunk:()=>k,getCurrentConfig:()=>T,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>R,pluralize:()=>ce,processFilesForNode:()=>W,resolveConfig:()=>N,setConfig:()=>J});var d={};$(d,{ApiHttp:()=>x,DEFAULT_API:()=>le,JUNK_DIRECTORIES:()=>te,Ship:()=>Y,ShipError:()=>ue,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,default:()=>we,filterJunk:()=>k,getCurrentConfig:()=>T,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>R,pluralize:()=>ce,processFilesForNode:()=>W,resolveConfig:()=>N,setConfig:()=>J});D();import*as Q from"mime-types";import{ShipError as P,DEFAULT_API as Ke}from"@shipstatic/types";var Z="/deployments",Ae="/ping",M="/aliases",He="/config",qe="/account",Ge="/spa-check";function Je(o){return typeof o=="string"?Q.lookup(o)||"application/octet-stream":Q.lookup(o.name)||o.type||"application/octet-stream"}async function Ve(o){let e=[];for await(let t of o)e.push(t);return e}var x=class{constructor(e){this.apiUrl=e.apiUrl||Ke,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}#t(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},i){let n=this.#t(t.headers),r={...t,headers:n},s=!!(this.apiKey||this.deployToken),m=!!n?.Authorization;!s&&!m&&(r.credentials="include");try{return await fetch(e,r)}catch(u){throw this.#o(u,i),u}}async#e(e,t={},i){try{let n=await this.#i(e,t,i);return n.ok||await this.#n(n,i),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof P||this.#o(n,i),n}}async ping(){return(await this.#e(`${this.apiUrl}${Ae}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Ae}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${He}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#r(e);let{apiUrl:i=this.apiUrl,signal:n,apiKey:r,deployToken:s}=t,{requestBody:m,requestHeaders:u}=await this.#s(e),w={};s?w={Authorization:`Bearer ${s}`}:r&&(w={Authorization:`Bearer ${r}`});let g={method:"POST",body:m,headers:{...u,...w},signal:n||null};return await this.#e(`${i}${Z}`,g,"Deploy")}#r(e){if(!e.length)throw P.business("No files to deploy.");for(let t of e)if(!t.md5)throw P.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#s(e){let t,i={};if(h()==="browser")t=this.#a(e);else if(h()==="node"){let{body:n,headers:r}=await this.#p(e);t=n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),i=r}else throw P.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:i}}#a(e){let t=new FormData,i=[];for(let n=0;n<e.length;n++){let r=e[n],s;if(r.content instanceof File||r.content instanceof Blob)s=r.content;else throw P.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let m=Je(s instanceof File?s:r.path),u=new File([s],r.path,{type:m});t.append("files[]",u),i.push(r.md5)}return t.append("checksums",JSON.stringify(i)),t}async#p(e){let{FormData:t,File:i}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),r=await import("path"),s=new t,m=[];for(let f=0;f<e.length;f++){let a=e[f],C=Q.lookup(a.path)||"application/octet-stream",S;if(Buffer.isBuffer(a.content))S=new i([a.content],a.path,{type:C});else if(typeof Blob<"u"&&a.content instanceof Blob)S=new i([a.content],a.path,{type:C});else throw P.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let z=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",S,z),m.push(a.md5)}s.append("checksums",JSON.stringify(m));let u=new n(s),w=await Ve(u.encode()),g=Buffer.concat(w.map(f=>Buffer.from(f))),c={"Content-Type":u.contentType,"Content-Length":Buffer.byteLength(g).toString()};return{body:g,headers:c}}async#n(e,t){let i={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}if(i.error||i.code||i.message){let n=i.message||i.error||`${t} failed due to API error`;throw e.status===401?P.authentication(n):P.api(n,e.status,i.code,i)}throw e.status===401?P.authentication(`Authentication failed for ${t}`):P.api(`${t} failed due to API error`,e.status,void 0,i)}#o(e,t){throw e.name==="AbortError"?P.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed due to network error: ${e.message}`,e):e instanceof P?e:P.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${Z}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${Z}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let i=await this.#i(`${this.apiUrl}${M}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},"Set Alias");return i.ok||await this.#n(i,"Set Alias"),{...await i.json(),isCreate:i.status===201}}catch(i){this.#o(i,"Set Alias")}}async getAlias(e){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${M}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.#e(`${this.apiUrl}${M}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${qe}`,{method:"GET"},"Get Account")}async checkSPA(e){let t=e.find(u=>u.path==="index.html"||u.path==="/index.html");if(!t)return!1;let i=100*1024;if(t.size>i)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let s={files:e.map(u=>u.path),index:n};return(await this.#e(`${this.apiUrl}${Ge}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"SPA Check")).isSPA}};D();import{DEFAULT_API as Xe}from"@shipstatic/types";async function Ze(o){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ee(),De));return t(o)}else return{}}function N(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Xe,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function j(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}K();import{DEPLOYMENT_CONFIG_FILENAME as be}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:i}=await v(t);return{path:be,content:t,size:e.length,md5:i}}async function xe(o,e,t){if(t.spaDetect===!1||o.some(i=>i.path===be))return o;try{if(await e.checkSPA(o)){let n=await tt();return[...o,n]}}catch{}return o}function H(o,e,t,i){return{create:async(n,r={})=>{t&&await t();let s=e?j(r,e):r,m=o();if(!i)throw new Error("processInput function is not provided.");let u=await i(n,s);return u=await xe(u,m,s),await m.deploy(u,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async n=>{t&&await t(),await o().removeDeployment(n)},get:async n=>(t&&await t(),o().getDeployment(n))}}function q(o,e){return{set:async(t,i)=>(e&&await e(),o().setAlias(t,i)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},check:async t=>(e&&await e(),o().checkAlias(t))}}function G(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}var U=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new x({...e,...t});let i=()=>this.ensureInitialized(),n=()=>this.http;this._deployments=H(n,this.clientOptions,i,(r,s)=>this.processInput(r,s)),this._aliases=q(n,i),this._account=G(n,i)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}};D();ee();import{ShipError as ge}from"@shipstatic/types";V();var l={};$(l,{ApiHttp:()=>x,DEFAULT_API:()=>le,JUNK_DIRECTORIES:()=>te,Ship:()=>U,ShipError:()=>ue,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>v,createAccountResource:()=>G,createAliasResource:()=>q,createDeploymentResource:()=>H,filterJunk:()=>k,getENV:()=>h,loadConfig:()=>Ze,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>R,pluralize:()=>ce,resolveConfig:()=>N});var y={};p(y,kt);import*as kt from"@shipstatic/types";p(l,y);import{DEFAULT_API as le}from"@shipstatic/types";K();function ce(o,e,t,i=!0){let n=o===1?e:t;return i?`${o} ${n}`:n}oe();ne();D();import{ShipError as ue,ShipErrorType as de}from"@shipstatic/types";p(d,l);ee();V();he();D();var Y=class extends U{constructor(e={}){if(h()!=="node")throw ge.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return N(e,{})}async loadFullConfig(){try{let e=await I(this.clientOptions.configFile),t=N(this.clientOptions,e);this.http=new x({...this.clientOptions,...t});let i=await this.http.getConfig();J(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#t(e))throw ge.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw ge.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Ue(),Be));return i(e,t,this.http)}#t(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},we=Y;p(X,d);export{x as ApiHttp,le as DEFAULT_API,te as JUNK_DIRECTORIES,Y as Ship,ue as ShipError,de as ShipErrorType,L as __setTestEnvironment,v as calculateMD5,G as createAccountResource,q as createAliasResource,H as createDeploymentResource,we as default,k as filterJunk,T as getCurrentConfig,h as getENV,I as loadConfig,j as mergeDeployOptions,R as optimizeDeployPaths,ce as pluralize,W as processFilesForNode,N as resolveConfig,J as setConfig};
1
+ var Pe=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Me=Object.getOwnPropertyNames;var _e=Object.prototype.hasOwnProperty;var E=(o,e)=>()=>(o&&(e=o(o=0)),e);var I=(o,e)=>{for(var t in e)Pe(o,t,{get:e[t],enumerable:!0})},ve=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Me(e))!_e.call(o,i)&&i!==t&&Pe(o,i,{get:()=>e[i],enumerable:!(n=Ke(e,i))||n.enumerable});return o},a=(o,e,t)=>(ve(o,e,"default"),t&&ve(t,e,"default"));var Ce={};I(Ce,{__setTestEnvironment:()=>L,getENV:()=>d});function L(o){se=o}function qe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function d(){return se||qe()}var se,P=E(()=>{"use strict";se=null});var xe={};I(xe,{loadConfig:()=>B});import{z as K}from"zod";import{ShipError as pe}from"@shipstatic/types";function Fe(o){try{return Ve.parse(o)}catch(e){if(e instanceof K.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw pe.config(`Configuration validation failed${n}: ${t.message}`)}throw pe.config("Configuration validation failed")}}async function We(o){try{if(d()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(ae,{searchPlaces:[`.${ae}rc`,"package.json",`${t.homedir()}/.${ae}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return Fe(i.config)}catch(e){if(e instanceof pe)throw e}return{}}async function B(o){if(d()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await We(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Fe(n)}var ae,Ve,ee=E(()=>{"use strict";P();ae="ship",Ve=K.object({apiUrl:K.string().url().optional(),apiKey:K.string().optional(),deployToken:K.string().optional()}).strict()});import{ShipError as N}from"@shipstatic/types";async function Ze(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,m=new e.ArrayBuffer,y=new FileReader,w=()=>{let f=s*2097152,p=Math.min(f+2097152,o.size);y.readAsArrayBuffer(o.slice(f,p))};y.onload=f=>{let p=f.target?.result;if(!p){n(N.business("Failed to read file chunk"));return}m.append(p),s++,s<r?w():t({md5:m.end()})},y.onerror=()=>{n(N.business("Failed to calculate MD5: FileReader error"))},w()})}async function Qe(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",m=>i(N.business(`Failed to read file for MD5: ${m.message}`))),s.on("data",m=>r.update(m)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function A(o){let e=d();if(e==="browser"){if(!(o instanceof Blob))throw N.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ze(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw N.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Qe(o)}throw N.business("Unknown or unsupported execution environment for MD5 calculation.")}var _=E(()=>{"use strict";P()});import{ShipError as tt}from"@shipstatic/types";function G(o){le=o}function T(){if(le===null)throw tt.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return le}var le,J=E(()=>{"use strict";le=null});import{isJunk as ot}from"junk";function k(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(ot(n))return!1;let i=t.slice(0,-1);for(let r of i)if(te.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var te,oe=E(()=>{"use strict";te=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(m=>m[r]===s))n.push(s);else break}return n.join("/")}function ne(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var me=E(()=>{"use strict"});function O(o,e={}){if(e.flatten===!1)return o.map(n=>({path:ne(n),name:ue(n)}));let t=nt(o);return o.map(n=>{let i=ne(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=ue(n)),{path:i,name:ue(n)}})}function nt(o){if(!o.length)return"";let t=o.map(r=>ne(r)).map(r=>r.split("/")),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(m=>m[r]===s))n.push(s);else break}return n.join("/")}function ue(o){return o.split(/[/\\]/).pop()||o}var ie=E(()=>{"use strict";me()});import{ShipError as $}from"@shipstatic/types";import*as D from"fs";import*as S from"path";function Re(o){let e=[];try{let t=D.readdirSync(o);for(let n of t){let i=S.join(o,n),r=D.statSync(i);if(r.isDirectory()){let s=Re(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function V(o,e={}){if(d()!=="node")throw $.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(c=>{let u=S.resolve(c);try{return D.statSync(u).isDirectory()?Re(u):[u]}catch{throw $.file(`Path does not exist: ${c}`,c)}}),n=[...new Set(t)],i=k(n);if(i.length===0)return[];let r=o.map(c=>S.resolve(c)),s=be(r.map(c=>{try{return D.statSync(c).isDirectory()?c:S.dirname(c)}catch{return S.dirname(c)}})),m=i.map(c=>{if(s&&s.length>0){let u=S.relative(s,c);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return S.basename(c)}),y=O(m,{flatten:e.pathDetect!==!1}),w=[],f=0,p=T();for(let c=0;c<i.length;c++){let u=i[c],b=y[c].path;try{let F=D.statSync(u);if(F.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(F.size>p.maxFileSize)throw $.business(`File ${u} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(f+=F.size,f>p.maxTotalSize)throw $.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let re=D.readFileSync(u),{md5:Le}=await A(re);if(b.includes("\0")||b.includes("/../")||b.startsWith("../")||b.endsWith("/.."))throw $.business(`Security error: Unsafe file path "${b}" for file: ${u}`);w.push({path:b,content:re,size:re.length,md5:Le})}catch(F){if(F instanceof $&&F.isClientError&&F.isClientError())throw F;console.error(`Could not process file ${u}:`,F)}}if(w.length>p.maxFilesCount)throw $.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return w}var ye=E(()=>{"use strict";P();_();oe();J();ie();me()});import{ShipError as Te}from"@shipstatic/types";async function ke(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(P(),Ce));if(t()!=="browser")throw Te.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(p=>p.webkitRelativePath||p.name),r=O(i,{flatten:e.pathDetect!==!1}),s=[];for(let p=0;p<n.length;p++){let c=n[p],u=r[p].path;if(u.includes("..")||u.includes("\0"))throw Te.business(`Security error: Unsafe file path "${u}" for file: ${c.name}`);s.push({file:c,relativePath:u})}let m=s.map(p=>p.relativePath),y=k(m),w=new Set(y),f=[];for(let p of s){if(!w.has(p.relativePath))continue;let{md5:c}=await A(p.file);f.push({content:p.file,path:p.relativePath,size:p.file.size,md5:c})}return f}var Oe=E(()=>{"use strict";_();oe();ie()});var Ne={};I(Ne,{convertBrowserInput:()=>Ue,convertDeployInput:()=>it,convertNodeInput:()=>ge});import{ShipError as v}from"@shipstatic/types";function $e(o,e={}){let t=T();if(!e.skipEmptyCheck&&o.length===0)throw v.business("No files to deploy.");if(o.length>t.maxFilesCount)throw v.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){if(i.size>t.maxFileSize)throw v.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>t.maxTotalSize)throw v.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ie(o,e){if(e==="node"){if(!Array.isArray(o))throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw v.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw v.business("No files selected in HTMLInputElement")}function Be(o){let e=o.map(t=>({name:t.path,size:t.size}));return $e(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function ge(o,e={}){Ie(o,"node");let t=await V(o,e);return Be(t)}async function Ue(o,e={}){Ie(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw v.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw v.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),$e(t);let n=await ke(t,e);return Be(n)}async function it(o,e={},t){let n=d();if(n!=="node"&&n!=="browser")throw v.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await ge([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await ge(o,e);else throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await Ue(o,e);return i}var ze=E(()=>{"use strict";P();ye();Oe();J()});var Y={};I(Y,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>he,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>A,createAccountResource:()=>H,createAliasResource:()=>j,createDeploymentResource:()=>q,default:()=>Se,filterJunk:()=>k,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>B,mergeDeployOptions:()=>M,optimizeDeployPaths:()=>O,pluralize:()=>fe,processFilesForNode:()=>V,resolveConfig:()=>U,setConfig:()=>G});var h={};I(h,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>te,Ship:()=>W,ShipError:()=>he,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>A,createAccountResource:()=>H,createAliasResource:()=>j,createDeploymentResource:()=>q,default:()=>Se,filterJunk:()=>k,getCurrentConfig:()=>T,getENV:()=>d,loadConfig:()=>B,mergeDeployOptions:()=>M,optimizeDeployPaths:()=>O,pluralize:()=>fe,processFilesForNode:()=>V,resolveConfig:()=>U,setConfig:()=>G});import*as Q from"mime-types";import{ShipError as C,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 n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};P();var Z="/deployments",Ee="/ping",R="/aliases",He="/config",Ge="/account",Je="/spa-check",x=class extends X{constructor(e){super(),this.apiUrl=e.apiUrl||je,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},n){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,n);let m=this.safeClone(s),y=this.safeClone(s);return this.emit("response",m,e),await this.parseResponse(y)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,n),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?C.authentication(i):C.api(i,e.status,n.code,n)}handleFetchError(e,t){throw e.name==="AbortError"?C.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?C.network(`${t} failed due to network error: ${e.message}`,e):e instanceof C?e:C.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Ee}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Ee}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${He}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${Z}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${Z}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${Z}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${Z}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){let n={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},i=this.getAuthHeaders(n.headers),r={...n,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",`${this.apiUrl}${R}/${encodeURIComponent(e)}`,r);try{let s=await fetch(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,r);s.ok||await this.handleResponseError(s,"Set Alias");let m=this.safeClone(s),y=this.safeClone(s);return this.emit("response",m,`${this.apiUrl}${R}/${encodeURIComponent(e)}`),{...await this.parseResponse(y),isCreate:s.status===201}}catch(s){throw this.emit("error",s,`${this.apiUrl}${R}/${encodeURIComponent(e)}`),this.handleFetchError(s,"Set Alias"),s}}async getAlias(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.request(`${this.apiUrl}${R}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async checkAlias(e){return await this.request(`${this.apiUrl}${R}/${encodeURIComponent(e)}/dns-check`,{method:"POST"},"Check Alias")}async getAccount(){return await this.request(`${this.apiUrl}${Ge}`,{method:"GET"},"Get Account")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${Je}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw C.business("No files to deploy.");for(let t of e)if(!t.md5)throw C.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e){if(d()==="browser")return{requestBody:this.createBrowserBody(e),requestHeaders:{}};if(d()==="node"){let{body:t,headers:n}=await this.createNodeBody(e);return{requestBody:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength),requestHeaders:n}}else throw C.business("Unknown or unsupported execution environment")}createBrowserBody(e){let t=new FormData,n=[];for(let i of e){if(!(i.content instanceof File||i.content instanceof Blob))throw C.file(`Unsupported file.content type for browser FormData: ${i.path}`,i.path);let r=this.getBrowserContentType(i.content instanceof File?i.content:i.path),s=new File([i.content],i.path,{type:r});t.append("files[]",s),n.push(i.md5)}return t.append("checksums",JSON.stringify(n)),t}async createNodeBody(e){let{FormData:t,File:n}=await import("formdata-node"),{FormDataEncoder:i}=await import("form-data-encoder"),r=new t,s=[];for(let f of e){let p=Q.lookup(f.path)||"application/octet-stream",c;if(Buffer.isBuffer(f.content))c=new n([f.content],f.path,{type:p});else if(typeof Blob<"u"&&f.content instanceof Blob)c=new n([f.content],f.path,{type:p});else throw C.file(`Unsupported file.content type for Node.js FormData: ${f.path}`,f.path);let u=f.path.startsWith("/")?f.path:"/"+f.path;r.append("files[]",c,u),s.push(f.md5)}r.append("checksums",JSON.stringify(s));let m=new i(r),y=[];for await(let f of m.encode())y.push(Buffer.from(f));let w=Buffer.concat(y);return{body:w,headers:{"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}getBrowserContentType(e){return typeof e=="string"?Q.lookup(e)||"application/octet-stream":Q.lookup(e.name)||e.type||"application/octet-stream"}};P();import{DEFAULT_API as Ye}from"@shipstatic/types";async function Xe(o){let e=d();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ee(),xe));return t(o)}else return{}}function U(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ye,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 M(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}_();import{DEPLOYMENT_CONFIG_FILENAME as Ae}from"@shipstatic/types";async function et(){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 A(t);return{path:Ae,content:t,size:e.length,md5:n}}async function De(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===Ae))return o;try{if(await e.checkSPA(o)){let i=await et();return[...o,i]}}catch{}return o}function q(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?M(r,e):r,m=o();if(!n)throw new Error("processInput function is not provided.");let y=await n(i,s);return y=await De(y,m,s),await m.deploy(y,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function j(o,e){return{set:async(t,n)=>(e&&await e(),o().setAlias(t,n)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},check:async t=>(e&&await e(),o().checkAlias(t))}}function H(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}var z=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new x({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=q(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._aliases=j(i,n),this._account=H(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};P();ee();import{ShipError as we}from"@shipstatic/types";J();var l={};I(l,{ApiHttp:()=>x,DEFAULT_API:()=>ce,JUNK_DIRECTORIES:()=>te,Ship:()=>z,ShipError:()=>he,ShipErrorType:()=>de,__setTestEnvironment:()=>L,calculateMD5:()=>A,createAccountResource:()=>H,createAliasResource:()=>j,createDeploymentResource:()=>q,filterJunk:()=>k,getENV:()=>d,loadConfig:()=>Xe,mergeDeployOptions:()=>M,optimizeDeployPaths:()=>O,pluralize:()=>fe,resolveConfig:()=>U});var g={};a(g,kt);import*as kt from"@shipstatic/types";a(l,g);import{DEFAULT_API as ce}from"@shipstatic/types";_();function fe(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}oe();ie();P();import{ShipError as he,ShipErrorType as de}from"@shipstatic/types";a(h,l);ee();J();ye();P();var W=class extends z{constructor(e={}){if(d()!=="node")throw we.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return U(e,{})}async loadFullConfig(){try{let e=await B(this.clientOptions.configFile),t=U(this.clientOptions,e),n=new x({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();G(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw we.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw we.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(ze(),Ne));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Se=W;a(Y,h);export{x as ApiHttp,ce as DEFAULT_API,te as JUNK_DIRECTORIES,W as Ship,he as ShipError,de as ShipErrorType,L as __setTestEnvironment,A as calculateMD5,H as createAccountResource,j as createAliasResource,q as createDeploymentResource,Se as default,k as filterJunk,T as getCurrentConfig,d as getENV,B as loadConfig,M as mergeDeployOptions,O as optimizeDeployPaths,fe as pluralize,V as processFilesForNode,U as resolveConfig,G as setConfig};
2
2
  //# sourceMappingURL=index.js.map