@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/README.md CHANGED
@@ -1,11 +1,12 @@
1
1
  # 🚢 Ship CLI & SDK
2
2
 
3
- A modern, lightweight SDK and CLI for deploying static files, designed for both **Node.js** and **Browser** environments with a clean resource-based API.
3
+ A modern, lightweight SDK and CLI for deploying static files, designed for both **Node.js** and **Browser** environments with a clean resource-based API and comprehensive event system for observability.
4
4
 
5
5
  ## Features
6
6
 
7
7
  - **🚀 Modern Resource API**: Clean `ship.deployments.create()` interface - no legacy wrappers
8
8
  - **🌍 Universal**: Automatic environment detection (Node.js/Browser) with optimized implementations
9
+ - **📡 Event System**: Complete observability with request, response, and error events
9
10
  - **🔧 Dynamic Configuration**: Automatically fetches platform limits from API
10
11
  - **📁 Flexible Input**: File paths (Node.js) or File objects (Browser/drag-drop)
11
12
  - **🔐 Secure**: MD5 checksums and data integrity validation
@@ -114,7 +115,7 @@ Ship SDK automatically fetches platform configuration from the API on initializa
114
115
  // SDK automatically calls GET /config and applies limits
115
116
  const ship = new Ship({ apiKey: 'ship-your-key' });
116
117
 
117
- // Platform limits are now available for validation:
118
+ // Platform limits are available for validation:
118
119
  // - maxFileSize: Dynamic file size limit
119
120
  // - maxFilesCount: Dynamic file count limit
120
121
  // - maxTotalSize: Dynamic total size limit
@@ -122,7 +123,7 @@ const ship = new Ship({ apiKey: 'ship-your-key' });
122
123
 
123
124
  **Benefits:**
124
125
  - **Single source of truth** - Limits only need to be changed on the API side
125
- - **Automatic updates** - SDK always uses current platform limits
126
+ - **Always current** - SDK always uses current platform limits
126
127
  - **Fail fast** - SDK fails if unable to fetch valid configuration
127
128
 
128
129
  ## API Reference
@@ -151,6 +152,8 @@ interface ShipOptions {
151
152
  - `ship.deployments` - Access deployment resource
152
153
  - `ship.aliases` - Access alias resource
153
154
  - `ship.account` - Access account resource
155
+ - `ship.on(event, handler)` - Add event listener for API observability
156
+ - `ship.off(event, handler)` - Remove event listener
154
157
 
155
158
  ### Deployments Resource
156
159
 
@@ -255,6 +258,161 @@ const files: File[] = Array.from(fileInput.files || []);
255
258
  const result2 = await ship.deployments.create(files);
256
259
  ```
257
260
 
261
+ ## Event System
262
+
263
+ Ship SDK provides a comprehensive event system for complete observability of all API operations. The event system is lightweight, reliable, and provides detailed insights into requests, responses, and errors.
264
+
265
+ ### Event Types
266
+
267
+ The SDK emits three core events:
268
+
269
+ - **`request`** - Emitted before each API request
270
+ - **`response`** - Emitted after successful API responses
271
+ - **`error`** - Emitted when API requests fail
272
+
273
+ ### Basic Event Usage
274
+
275
+ ```javascript
276
+ import Ship from '@shipstatic/ship';
277
+
278
+ const ship = new Ship({ apiKey: 'ship-your-api-key' });
279
+
280
+ // Listen to all API requests
281
+ ship.on('request', (url, requestInit) => {
282
+ console.log(`→ ${requestInit.method} ${url}`);
283
+ });
284
+
285
+ // Listen to all API responses
286
+ ship.on('response', (response, url) => {
287
+ console.log(`← ${response.status} ${url}`);
288
+ });
289
+
290
+ // Listen to all API errors
291
+ ship.on('error', (error, url) => {
292
+ console.error(`✗ Error at ${url}:`, error.message);
293
+ });
294
+
295
+ // Deploy with events
296
+ const result = await ship.deployments.create('./dist');
297
+ ```
298
+
299
+ ### Advanced Event Patterns
300
+
301
+ #### Request/Response Logging
302
+ ```javascript
303
+ // Log all API traffic
304
+ ship.on('request', (url, init) => {
305
+ console.log(`[${new Date().toISOString()}] → ${init.method} ${url}`);
306
+ if (init.body) {
307
+ console.log(` Body: ${init.body instanceof FormData ? '[FormData]' : init.body}`);
308
+ }
309
+ });
310
+
311
+ ship.on('response', (response, url) => {
312
+ console.log(`[${new Date().toISOString()}] ← ${response.status} ${response.statusText} ${url}`);
313
+ });
314
+ ```
315
+
316
+ #### Error Monitoring
317
+ ```javascript
318
+ // Comprehensive error tracking
319
+ ship.on('error', (error, url) => {
320
+ // Send to monitoring service
321
+ analytics.track('ship_api_error', {
322
+ url,
323
+ error: error.message,
324
+ type: error.constructor.name,
325
+ timestamp: Date.now()
326
+ });
327
+ });
328
+ ```
329
+
330
+ #### Performance Monitoring
331
+ ```javascript
332
+ const requestTimes = new Map();
333
+
334
+ ship.on('request', (url, init) => {
335
+ requestTimes.set(url, Date.now());
336
+ });
337
+
338
+ ship.on('response', (response, url) => {
339
+ const startTime = requestTimes.get(url);
340
+ if (startTime) {
341
+ const duration = Date.now() - startTime;
342
+ console.log(`${url} took ${duration}ms`);
343
+ requestTimes.delete(url);
344
+ }
345
+ });
346
+ ```
347
+
348
+ #### Custom Analytics Integration
349
+ ```javascript
350
+ // Google Analytics integration
351
+ ship.on('request', (url, init) => {
352
+ gtag('event', 'api_request', {
353
+ 'custom_url': url,
354
+ 'method': init.method
355
+ });
356
+ });
357
+
358
+ ship.on('response', (response, url) => {
359
+ gtag('event', 'api_response', {
360
+ 'custom_url': url,
361
+ 'status_code': response.status
362
+ });
363
+ });
364
+ ```
365
+
366
+ ### Event Handler Management
367
+
368
+ ```javascript
369
+ // Add event handlers
370
+ const requestHandler = (url, init) => console.log(`Request: ${url}`);
371
+ ship.on('request', requestHandler);
372
+
373
+ // Remove specific handlers
374
+ ship.off('request', requestHandler);
375
+
376
+ // Event handlers are automatically cleaned up when ship instance is garbage collected
377
+ ```
378
+
379
+ ### Event System Features
380
+
381
+ - **Reliable**: Handlers that throw errors are automatically removed to prevent cascading failures
382
+ - **Safe**: Response objects are safely cloned for event handlers to prevent body consumption conflicts
383
+ - **Lightweight**: Minimal overhead - only 70 lines of code
384
+ - **Type Safe**: Full TypeScript support with proper event argument typing
385
+ - **Clean**: Automatic cleanup prevents memory leaks
386
+
387
+ ### TypeScript Event Types
388
+
389
+ ```typescript
390
+ import Ship from '@shipstatic/ship';
391
+
392
+ const ship = new Ship({ apiKey: 'ship-your-api-key' });
393
+
394
+ // Fully typed event handlers
395
+ ship.on('request', (url: string, init: RequestInit) => {
396
+ console.log(`Request to ${url}`);
397
+ });
398
+
399
+ ship.on('response', (response: Response, url: string) => {
400
+ console.log(`Response from ${url}: ${response.status}`);
401
+ });
402
+
403
+ ship.on('error', (error: Error, url: string) => {
404
+ console.error(`Error at ${url}:`, error);
405
+ });
406
+ ```
407
+
408
+ ### Event System Architecture
409
+
410
+ The event system is built directly into the HTTP client with:
411
+ - **Direct Integration**: Events are emitted from the core HTTP operations
412
+ - **Error Boundaries**: Failed event handlers don't crash API operations
413
+ - **Response Cloning**: Dedicated response clones for events and parsing
414
+ - **Graceful Degradation**: Event system failures don't affect core functionality
415
+
258
416
  ## Unified Error Handling
259
417
 
260
418
  The Ship SDK uses a unified error system with a single `ShipError` class:
@@ -418,7 +576,7 @@ ship account # Get account details
418
576
  - **Browser**: 185KB (ESM with dependencies)
419
577
  - **CLI**: 38KB (CJS)
420
578
 
421
- **Recent Optimizations:**
579
+ **Key Optimizations:**
422
580
  - ✅ **Unified error system** - Single `ShipError` class for all components
423
581
  - ✅ **Dynamic platform configuration** - Fetches limits from API
424
582
  - ✅ **Replaced axios with native fetch** - Bundle size reduction
@@ -434,6 +592,7 @@ Full TypeScript support with exported types from shared `@shipstatic/types`:
434
592
  // TypeScript - works with both import styles
435
593
  import type {
436
594
  ShipOptions,
595
+ ShipEvents,
437
596
  NodeDeployInput,
438
597
  BrowserDeployInput,
439
598
  DeployOptions,
@@ -451,6 +610,7 @@ import type {
451
610
  - **Class-based API**: `new Ship()` with resource properties
452
611
  - **Environment detection**: Automatic Node.js/Browser optimizations
453
612
  - **Native dependencies**: Uses built-in `fetch`, `crypto`, and `fs` APIs
613
+ - **Event system**: Comprehensive observability with lightweight, reliable events
454
614
  - **Type safety**: Strict TypeScript with comprehensive error types
455
615
  - **Dynamic configuration**: Platform limits fetched from API
456
616
  - **Unified DTOs**: Shared type definitions from `@shipstatic/types`
@@ -471,6 +631,7 @@ src/
471
631
  │ ├── api/ # HTTP client and API communication
472
632
  │ ├── base-ship.ts # Base Ship class implementation
473
633
  │ ├── core/ # Configuration and constants
634
+ │ ├── events.ts # Event system implementation
474
635
  │ ├── lib/ # Utility libraries
475
636
  │ ├── resources.ts # Resource implementations
476
637
  │ └── types.ts # Shared type definitions
@@ -500,24 +661,24 @@ File Objects → Path Extraction → Junk Filtering → Content Processing → S
500
661
  - **Wire format support**: Automatic serialization/deserialization
501
662
  - **Helper methods**: Easy type checking with `is*Error()` methods
502
663
 
503
- ## Development Status
504
-
505
- This is an **unlaunched project** optimized for modern development:
506
-
507
- - **Deployment Resource**: Full implementation (create, list, get, remove)
508
- - **Alias Resource**: Full implementation (set, get, list, remove)
509
- - **Account Resource**: Full implementation (get account details)
510
- - **Unified Error System**: Single `ShipError` class with factory methods
511
- - **Dynamic Platform Config**: Automatic limit fetching from API
512
- - **Ultra-Simple CLI**: Deploy shortcut + explicit commands
513
- - **Streamlined Multipart**: `files[]` array + JSON checksums format
514
- - **Direct Validation**: Functions throw errors instead of returning results
515
- - **Shared DTOs**: All types from `@shipstatic/types` package
516
- - **Tree-shakeable**: `"sideEffects": false` for optimal bundling
517
- - **Impossible Simplicity**: Maximum functionality with minimal complexity
518
- - 🎯 No legacy compatibility constraints
519
- - 🔧 Native fetch API for optimal performance
520
- - Modern ESM modules with TypeScript
664
+ ## Features & Capabilities
665
+
666
+ Ship SDK provides comprehensive deployment functionality:
667
+
668
+ - **Deployment Resource**: Complete operations (create, list, get, remove)
669
+ - **Alias Resource**: Complete operations (set, get, list, remove)
670
+ - **Account Resource**: Account information retrieval
671
+ - **Event System**: Comprehensive observability with request, response, error events
672
+ - **Unified Error System**: Single `ShipError` class with factory methods
673
+ - **Dynamic Platform Config**: Automatic limit fetching from API
674
+ - **Simple CLI**: Deploy shortcut + explicit commands
675
+ - **Streamlined Multipart**: `files[]` array + JSON checksums format
676
+ - **Direct Validation**: Functions throw errors for immediate feedback
677
+ - **Shared DTOs**: All types from `@shipstatic/types` package
678
+ - **Tree-shakeable**: `"sideEffects": false` for optimal bundling
679
+ - **Production Ready**: Clean, reliable implementation with comprehensive test coverage
680
+ - **Native APIs**: Built on `fetch`, `crypto`, and `fs` for optimal performance
681
+ - **Modern TypeScript**: Full type safety with ESM modules
521
682
 
522
683
  ## Testing
523
684
 
@@ -543,7 +704,7 @@ pnpm build && pnpm test --run
543
704
  - **Node.js tests**: Filesystem and path manipulation
544
705
  - **Error tests**: Unified error handling patterns
545
706
 
546
- **Current Status:** 566 tests passing (596 total) ✅
707
+ **Current Status:** 614 tests passing (614 total) ✅
547
708
 
548
709
  ## Contributing
549
710
 
package/dist/browser.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
  /**
@@ -438,4 +470,4 @@ declare class Ship extends Ship$1 {
438
470
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
439
471
  }
440
472
 
441
- 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, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForBrowser, resolveConfig, setConfig };
473
+ 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, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForBrowser, resolveConfig, setConfig };