@shipstatic/ship 0.8.17 → 0.9.1

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
@@ -123,7 +123,7 @@ ship ping
123
123
  ```typescript
124
124
  ship.account.get() // → whoami
125
125
  ship.ping() // → boolean
126
- ship.getConfig() // → platform config and plan limits (cached)
126
+ ship.getLimits() // → platform plan limits (cached)
127
127
  ```
128
128
 
129
129
  ## CLI Reference
@@ -260,11 +260,18 @@ try {
260
260
 
261
261
  ## Configuration
262
262
 
263
- Resolved in order of precedence:
263
+ The **CLI** (`ship`) resolves credentials in this order:
264
264
 
265
- 1. **Constructor options**: `new Ship({ apiUrl, apiKey })`
266
- 2. **Environment variables**: `SHIP_API_URL`, `SHIP_API_KEY`
267
- 3. **Config files**: `.shiprc` or `package.json` `"ship"` key
265
+ 1. CLI flags: `--api-key`, `--api-url`, `--deploy-token`
266
+ 2. Environment variables: `SHIP_API_KEY`, `SHIP_API_URL`, `SHIP_DEPLOY_TOKEN`
267
+ 3. Config files: `.shiprc` or `package.json` `"ship"` key (run `ship config` to create one)
268
+
269
+ The **SDK** (`new Ship(...)`) resolves credentials in this order:
270
+
271
+ 1. Constructor options: `new Ship({ apiUrl, apiKey })`
272
+ 2. Environment variables: `SHIP_API_KEY`, `SHIP_API_URL`, `SHIP_DEPLOY_TOKEN`
273
+
274
+ The SDK never reads `.shiprc` or `package.json` — file resolution is a CLI feature, not an SDK feature. This keeps `new Ship({})` safe to use from embedded contexts (MCP, n8n, library wrappers) without inheriting the host developer's personal credentials.
268
275
 
269
276
  ```bash
270
277
  SHIP_API_KEY=ship-... ship deployments list
package/dist/browser.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import * as _shipstatic_types from '@shipstatic/types';
2
- import { DeploymentUploadOptions, ProgressInfo, StaticFile, Domain, DeploymentCreateResponse, DeploymentListResponse, Deployment, DomainListResponse, DomainDnsResponse, DomainRecordsResponse, DomainValidateResponse, TokenCreateResponse, TokenListResponse, Account, ConfigResponse, ResolvedConfig, DeployInput, AccountResource, DeploymentResource, DomainResource, TokenResource, ValidatableFile, FileValidationResult } from '@shipstatic/types';
2
+ import { DeploymentUploadOptions, ProgressInfo, StaticFile, DeploymentCreateResponse, DeploymentListResponse, Deployment, DomainSetResult, DomainListResponse, Domain, DomainDnsResponse, DomainRecordsResponse, DomainValidateResponse, TokenCreateResponse, TokenListResponse, Account, PlatformLimits, DeployInput, AccountResource, DeploymentResource, DomainResource, TokenResource, ResolvedConfig, ValidatableFile, FileValidationResult } 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
 
@@ -9,14 +9,6 @@ export { Account, AccountResource, DEFAULT_API, DeployInput, Deployment, Deploym
9
9
  * Core types come from @shipstatic/types, while SDK-specific types are defined here.
10
10
  */
11
11
 
12
- /**
13
- * Domain set result with SDK-injected isCreate flag.
14
- * isCreate is derived from HTTP status code (201 = create, 200 = update)
15
- * and is not part of the Domain entity contract.
16
- */
17
- type DomainSetResult = Domain & {
18
- isCreate: boolean;
19
- };
20
12
  /**
21
13
  * Universal deploy options for both Node.js and Browser environments.
22
14
  * Extends the API contract (DeploymentUploadOptions) with SDK-specific options.
@@ -95,8 +87,6 @@ interface ShipClientOptions {
95
87
  apiKey?: string | undefined;
96
88
  /** Deploy token for single-use deployments (format: token-<64-char-hex>, total 70 chars). */
97
89
  deployToken?: string | undefined;
98
- /** Path to custom config file. */
99
- configFile?: string | undefined;
100
90
  /**
101
91
  * Default callback for deploy progress for deploys made with this client.
102
92
  * @param info - Progress information including percentage and byte counts.
@@ -125,11 +115,23 @@ interface ShipClientOptions {
125
115
  /**
126
116
  * Default caller identifier for multi-tenant deployments.
127
117
  * Alphanumeric characters, dots, underscores, and hyphens allowed (max 128 chars).
118
+ *
119
+ * Used by orchestrators (e.g. n8n nodes processing many tenants from one
120
+ * worker) so the API's rate-limit bucket keys per caller rather than per
121
+ * shared IP. **Programmatic-only by design** — there is no `--caller`
122
+ * CLI flag because the CLI is a single-user tool (`via: 'cli'` is hardcoded
123
+ * in `performDeploy`); every CLI invocation belongs to one human, and
124
+ * a per-tenant rate-limit bucket would defeat the purpose.
128
125
  */
129
126
  caller?: string | undefined;
130
127
  /**
131
- * Override the deploy endpoint path. Defaults to '/deployments'.
132
- * Used by first-party clients to target alternative upload routes (e.g., '/upload').
128
+ * Override the deploy endpoint path. Defaults to `/deployments`.
129
+ *
130
+ * @internal First-party hook used by `web/my` and `web/www` to target the
131
+ * `/upload` route (which runs server-side build / SPA detection). External
132
+ * SDK consumers must not set this — the `/deployments` endpoint is the
133
+ * stable public contract. See `cloudflare/api/CLAUDE.md` for why the two
134
+ * endpoints exist and what `/upload` does that `/deployments` doesn't.
133
135
  */
134
136
  deployEndpoint?: string | undefined;
135
137
  }
@@ -152,12 +154,11 @@ interface ShipEvents {
152
154
  */
153
155
 
154
156
  /**
155
- * Lightweight event system
156
- * - Add handler: on()
157
- * - Remove handler: off()
158
- * - Emit events: emit() [internal]
159
- * - Transfer events: transfer() [internal]
160
- * - Reliable error handling and cleanup
157
+ * Lightweight typed event emitter.
158
+ *
159
+ * Public API: `on()` / `off()`. `emit()` is internal — only the SDK
160
+ * publishes events. Throwing handlers are evicted automatically and
161
+ * surfaced as `error` events on the next tick.
161
162
  */
162
163
  declare class SimpleEvents {
163
164
  private handlers;
@@ -174,16 +175,6 @@ declare class SimpleEvents {
174
175
  * @internal
175
176
  */
176
177
  emit<K extends keyof ShipEvents>(event: K, ...args: ShipEvents[K]): void;
177
- /**
178
- * Transfer all handlers to another events instance
179
- * @internal
180
- */
181
- transfer(target: SimpleEvents): void;
182
- /**
183
- * Clear all handlers (for cleanup)
184
- * @internal
185
- */
186
- clear(): void;
187
178
  }
188
179
 
189
180
  /**
@@ -208,10 +199,6 @@ declare class ApiHttp extends SimpleEvents {
208
199
  * Priority: globalHeaders (lowest) < instance auth < per-request headers (highest)
209
200
  */
210
201
  setGlobalHeaders(headers: Record<string, string>): void;
211
- /**
212
- * Transfer events to another client
213
- */
214
- transferEventsTo(target: ApiHttp): void;
215
202
  /**
216
203
  * Execute HTTP request with timeout, events, and error handling
217
204
  */
@@ -254,34 +241,11 @@ declare class ApiHttp extends SimpleEvents {
254
241
  removeToken(token: string): Promise<void>;
255
242
  fetchAgentToken(): Promise<TokenCreateResponse>;
256
243
  getAccount(): Promise<Account>;
257
- getConfig(): Promise<ConfigResponse>;
244
+ getLimits(): Promise<PlatformLimits>;
258
245
  ping(): Promise<boolean>;
259
246
  checkSPA(files: StaticFile[], options?: ApiDeployOptions): Promise<boolean>;
260
247
  }
261
248
 
262
- /**
263
- * @file Shared configuration logic for both environments.
264
- *
265
- * CONFIGURATION PRECEDENCE (highest to lowest):
266
- * 1. Constructor options / CLI flags (passed directly to Ship())
267
- * 2. Environment variables (SHIP_API_KEY, SHIP_DEPLOY_TOKEN, SHIP_API_URL)
268
- * 3. Config file (.shiprc or package.json "ship" key)
269
- * 4. Default values (DEFAULT_API)
270
- *
271
- * This means CLI flags always win, followed by env vars, then config files.
272
- */
273
-
274
- /**
275
- * Universal configuration resolver for all environments.
276
- * This is the single source of truth for config resolution.
277
- */
278
- declare function resolveConfig(userOptions?: ShipClientOptions, loadedConfig?: Partial<ShipClientOptions>): ResolvedConfig;
279
- /**
280
- * Merge deployment options with client defaults.
281
- * This is shared logic used by both environments.
282
- */
283
- declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
284
-
285
249
  /**
286
250
  * Ship SDK resource factory functions.
287
251
  */
@@ -324,75 +288,45 @@ declare function createTokenResource(ctx: ResourceContext): TokenResource;
324
288
 
325
289
  /**
326
290
  * Abstract base class for Ship SDK implementations.
327
- *
328
- * Provides shared functionality while allowing environment-specific
329
- * implementations to handle configuration loading and deployment processing.
330
291
  */
331
292
  declare abstract class Ship$1 {
332
- protected http: ApiHttp;
333
- protected readonly clientOptions: ShipClientOptions;
334
- protected initPromise: Promise<void> | null;
335
- protected _config: ConfigResponse | null;
293
+ readonly deployments: DeploymentResource;
294
+ readonly domains: DomainResource;
295
+ readonly account: AccountResource;
296
+ readonly tokens: TokenResource;
297
+ private readonly http;
298
+ private readonly clientOptions;
299
+ private initPromise;
300
+ protected platformLimits: PlatformLimits | null;
336
301
  private auth;
337
- private customHeaders;
338
- protected readonly authHeadersCallback: () => Record<string, string>;
339
- protected _deployments: DeploymentResource;
340
- protected _domains: DomainResource;
341
- protected _account: AccountResource;
342
- protected _tokens: TokenResource;
343
302
  constructor(options?: ShipClientOptions);
344
- protected abstract resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
345
- protected abstract loadFullConfig(): Promise<void>;
346
303
  protected abstract processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
347
304
  protected abstract getDeployBodyCreator(): DeployBodyCreator;
348
305
  /**
349
- * Ensure full initialization is complete - called lazily by resources
306
+ * Lazy initialization fetches platform limits (file size / count caps) once,
307
+ * on the first API call. Subsequent calls reuse the resolved promise.
350
308
  */
351
309
  protected ensureInitialized(): Promise<void>;
310
+ private fetchPlatformLimits;
352
311
  /**
353
- * Ping the API server to check connectivity
312
+ * Ping the API server to check connectivity.
354
313
  */
355
314
  ping(): Promise<boolean>;
356
315
  /**
357
- * Deploy project (convenience shortcut to ship.deployments.upload())
316
+ * Deploy project (convenience shortcut to `ship.deployments.upload()`).
358
317
  */
359
318
  deploy(input: DeployInput, options?: DeploymentOptions): Promise<Deployment>;
360
319
  /**
361
- * Get current account information (convenience shortcut to ship.account.get())
320
+ * Get current account information (convenience shortcut to `ship.account.get()`).
362
321
  */
363
322
  whoami(): Promise<_shipstatic_types.Account>;
364
323
  /**
365
- * Get deployments resource (environment-specific)
366
- */
367
- get deployments(): DeploymentResource;
368
- /**
369
- * Get domains resource
370
- */
371
- get domains(): DomainResource;
372
- /**
373
- * Get account resource
374
- */
375
- get account(): AccountResource;
376
- /**
377
- * Get tokens resource
378
- */
379
- get tokens(): TokenResource;
380
- /**
381
- * Get API configuration (file upload limits, etc.)
382
- * Reuses platform config fetched during initialization, then caches the result
383
- */
384
- getConfig(): Promise<ConfigResponse>;
385
- /**
386
- * Add event listener
387
- * @param event - Event name
388
- * @param handler - Event handler function
324
+ * Get platform limits (max file size, file count, total size).
325
+ * Reuses the response fetched during initialization. Per-instance state —
326
+ * does not leak between concurrent Ships against different API URLs.
389
327
  */
328
+ getLimits(): Promise<PlatformLimits>;
390
329
  on<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
391
- /**
392
- * Remove event listener
393
- * @param event - Event name
394
- * @param handler - Event handler function
395
- */
396
330
  off<K extends keyof ShipEvents>(event: K, handler: (...args: ShipEvents[K]) => void): void;
397
331
  /**
398
332
  * Set global headers included in every request.
@@ -403,38 +337,60 @@ declare abstract class Ship$1 {
403
337
  * Clear all custom global headers.
404
338
  */
405
339
  clearHeaders(): void;
406
- /**
407
- * Replace HTTP client while preserving event listeners
408
- * Used during initialization to maintain user event subscriptions
409
- * @protected
410
- */
411
- protected replaceHttpClient(newClient: ApiHttp): void;
412
340
  /**
413
341
  * Sets the deploy token for authentication.
414
- * This will override any previously set API key or deploy token.
415
- * @param token The deploy token (format: token-<64-char-hex>)
342
+ * Overrides any previously set API key or deploy token.
343
+ * @param token Deploy token (format: `token-<64-char-hex>`)
416
344
  */
417
345
  setDeployToken(token: string): void;
418
346
  /**
419
347
  * Sets the API key for authentication.
420
- * This will override any previously set API key or deploy token.
421
- * @param key The API key (format: ship-<64-char-hex>)
348
+ * Overrides any previously set API key or deploy token.
349
+ * @param key API key (format: `ship-<64-char-hex>`)
422
350
  */
423
351
  setApiKey(key: string): void;
424
- /**
425
- * Generate authorization headers based on current auth state
426
- * Called dynamically on each request to ensure latest credentials are used
427
- * @private
428
- */
429
352
  private getAuthHeaders;
430
353
  /**
431
- * Check if authentication credentials are configured
432
- * Used by resources to fail fast if auth is required
433
- * @private
354
+ * Check whether authentication credentials are configured.
355
+ * Used by resources to fail fast (or trigger the agent-token fallback) when
356
+ * auth is required.
434
357
  */
435
358
  private hasAuth;
436
359
  }
437
360
 
361
+ /**
362
+ * @file Cross-platform configuration helpers.
363
+ *
364
+ * Two pure helpers used by both Node and Browser:
365
+ *
366
+ * - `resolveConfig(options)` — applies the API-URL default. The Node Ship
367
+ * calls this after merging env vars under the user's options; the Browser
368
+ * Ship calls it directly (no ambient sources).
369
+ * - `mergeDeployOptions(perCallOptions, clientDefaults)` — overlays
370
+ * instance-level defaults under per-call overrides for a single deploy.
371
+ *
372
+ * Credential precedence is owned by callers, not this file:
373
+ *
374
+ * - SDK (Node): constructor args > `SHIP_*` env vars (see `node/index.ts`)
375
+ * - SDK (Browser): constructor args only
376
+ * - CLI: `--flag` > env > `.shiprc` / `package.json` (see `cli/create-client.ts`)
377
+ */
378
+
379
+ /**
380
+ * Apply the API-URL default and project the credential triplet into a
381
+ * `ResolvedConfig` shape. Optional fields are omitted (rather than set to
382
+ * `undefined`) so spread merges downstream behave predictably.
383
+ */
384
+ declare function resolveConfig(options?: ShipClientOptions): ResolvedConfig;
385
+ /**
386
+ * Overlay client-level defaults under per-call deploy options.
387
+ *
388
+ * Per-call options always win — they're the explicit override for a single
389
+ * `deployments.upload()`. Defaults fill in only when the per-call option is
390
+ * `undefined` (an explicit `null` / empty value passes through).
391
+ */
392
+ declare function mergeDeployOptions(options: DeploymentOptions, clientDefaults: ShipClientOptions): DeploymentOptions;
393
+
438
394
  interface MD5Result {
439
395
  md5: string;
440
396
  }
@@ -615,12 +571,12 @@ declare function validateFileName(filename: string): {
615
571
  * - **Warnings**: Exclude files but allow deployment (empty files, etc.)
616
572
  *
617
573
  * @param files - Array of files to validate
618
- * @param config - Validation configuration from ship.getConfig()
574
+ * @param config - Validation configuration from ship.getLimits()
619
575
  * @returns Validation result with errors and warnings
620
576
  *
621
577
  * @example
622
578
  * ```typescript
623
- * const config = await ship.getConfig();
579
+ * const config = await ship.getLimits();
624
580
  * const result = validateFiles(files, config);
625
581
  *
626
582
  * if (!result.canDeploy) {
@@ -636,7 +592,7 @@ declare function validateFileName(filename: string): {
636
592
  * }
637
593
  * ```
638
594
  */
639
- declare function validateFiles<T extends ValidatableFile>(files: T[], config: ConfigResponse): FileValidationResult<T>;
595
+ declare function validateFiles<T extends ValidatableFile>(files: T[], config: PlatformLimits): FileValidationResult<T>;
640
596
  /**
641
597
  * Get only the valid files from validation results
642
598
  */
@@ -675,21 +631,6 @@ declare function validateDeployPath(deployPath: string, sourceIdentifier: string
675
631
  */
676
632
  declare function validateDeployFile(deployPath: string, sourceIdentifier: string): void;
677
633
 
678
- /**
679
- * @file Platform configuration management for the Ship SDK.
680
- * Implements fail-fast dynamic configuration with mandatory API fetch.
681
- */
682
-
683
- /**
684
- * Set the current config (called after fetching from API)
685
- */
686
- declare function setConfig(config: ConfigResponse): void;
687
- /**
688
- * Get current config - throws if not initialized (fail-fast approach)
689
- * @throws {ShipError.config} If configuration hasn't been fetched from API
690
- */
691
- declare function getCurrentConfig(): ConfigResponse;
692
-
693
634
  /**
694
635
  * @file Browser-specific file utilities for the Ship SDK.
695
636
  * Provides helpers for processing browser files into deploy-ready objects.
@@ -711,42 +652,52 @@ declare function getCurrentConfig(): ConfigResponse;
711
652
  *
712
653
  * @param browserFiles - File[] to process for deploy.
713
654
  * @param options - Processing options including pathDetect for automatic path optimization.
655
+ * @param platformLimits - Per-instance platform limits (file-size / count / total-size caps)
656
+ * from the originating Ship's `GET /config` fetch. Passed in rather than read from a
657
+ * module global so concurrent Ships against different API URLs cannot clobber each
658
+ * other's caps.
714
659
  * @returns Promise resolving to an array of StaticFile objects.
715
660
  * @throws {ShipError} If called outside a browser or with invalid input.
716
661
  */
717
- declare function processFilesForBrowser(browserFiles: File[], options?: DeploymentOptions): Promise<StaticFile[]>;
662
+ declare function processFilesForBrowser(browserFiles: File[], options?: DeploymentOptions, platformLimits?: PlatformLimits): Promise<StaticFile[]>;
718
663
 
719
664
  /**
720
- * @file Ship SDK for browser environments with streamlined configuration.
665
+ * @file Ship SDK for browser environments.
666
+ *
667
+ * Configuration is fully explicit — the browser has no env vars or config files
668
+ * to inherit. All credentials are supplied via constructor options (or, for
669
+ * first-party browser apps, an HTTP-only cookie via `useCredentials: true`).
721
670
  */
722
671
 
723
672
  /**
724
673
  * Ship SDK Client for browser environments.
725
674
  *
726
- * Optimized for browser compatibility with no Node.js dependencies.
727
- * Configuration is provided explicitly through constructor options.
728
- *
729
675
  * @example
730
676
  * ```typescript
731
- * // Deploy with token obtained from server
677
+ * // Deploy with a token obtained from your server
732
678
  * const ship = new Ship({
733
- * deployToken: "token-xxxx",
734
- * apiUrl: "https://api.shipstatic.com"
679
+ * deployToken: 'token-xxxx',
680
+ * apiUrl: 'https://api.shipstatic.com',
735
681
  * });
736
682
  *
737
- * // Deploy files from input element
738
683
  * const files = Array.from(fileInput.files);
739
684
  * await ship.deploy(files);
740
685
  * ```
741
686
  */
742
687
  declare class Ship extends Ship$1 {
743
- constructor(options?: ShipClientOptions);
744
- protected resolveInitialConfig(options: ShipClientOptions): ResolvedConfig;
745
- protected loadFullConfig(): Promise<void>;
688
+ /**
689
+ * Deploy `File[]` (typically from `<input type="file">` or drag-and-drop)
690
+ * to ShipStatic. Convenience shortcut for `ship.deployments.upload()`.
691
+ *
692
+ * Wrong-platform inputs (e.g. string paths) fail at compile time. For
693
+ * platform-neutral code, use `ship.deployments.upload()`, which accepts
694
+ * the wider `DeployInput` and validates at runtime — that asymmetry is
695
+ * intentional: the convenience shortcut narrows; the resource-layer
696
+ * contract stays platform-neutral.
697
+ */
698
+ deploy(input: File[], options?: DeploymentOptions): Promise<Deployment>;
746
699
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
747
- /** Type guard that validates all elements are File objects */
748
- private isFileArray;
749
700
  protected getDeployBodyCreator(): DeployBodyCreator;
750
701
  }
751
702
 
752
- export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type DomainSetResult, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForBrowser, resolveConfig, setConfig as setPlatformConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
703
+ export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForBrowser, resolveConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };