@shipstatic/ship 2.0.0-beta.3 → 2.0.0-beta.4

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
@@ -201,6 +201,8 @@ interface TokenListItem {
201
201
  interface TokenListResponse {
202
202
  /** Array of tokens (security-redacted for list display) */
203
203
  tokens: TokenListItem[];
204
+ /** Cursor for pagination, null if no more pages */
205
+ cursor: string | null;
204
206
  /** Total number of tokens */
205
207
  total: number;
206
208
  }
@@ -421,6 +423,18 @@ declare class ShipError extends Error {
421
423
  static file(message: string, details?: unknown): ShipError;
422
424
  static config(message: string, details?: unknown): ShipError;
423
425
  static api(message: string, status?: number, details?: unknown): ShipError;
426
+ /**
427
+ * The caller is at fault — by HTTP's own definition of a 4xx, or by a type
428
+ * that is client-attributable without ever having a status (`Config`,
429
+ * `File`, raised locally by the SDK).
430
+ *
431
+ * Both arms are load-bearing, because type and status are independent
432
+ * axes. `fromHttpResponse` trusts `body.error` only when it names a
433
+ * server-producible type; a non-OK response without one is status-derived,
434
+ * so a CDN 404 or any intermediary error arrives as `Api` — a server-fault
435
+ * *type* carrying a client *status*. Judging by type alone would report it
436
+ * as a platform failure and bury the server's own message.
437
+ */
424
438
  isClientError(): boolean;
425
439
  isNetworkError(): boolean;
426
440
  isAuthError(): boolean;
@@ -645,6 +659,36 @@ declare const SPA_DEFAULT_CONFIG: {
645
659
  readonly destination: "/index.html";
646
660
  }];
647
661
  };
662
+ /**
663
+ * Assert that a ship.json file is *syntactically* loadable. Syntax only —
664
+ * never schema.
665
+ *
666
+ * ship.json is validated and compiled on the server, deliberately: the schema
667
+ * and the compiler evolve, and a client that judged them would reject configs
668
+ * a newer platform accepts. That reasoning bounds what a client may check to
669
+ * the properties which are true of *every* past and future schema:
670
+ *
671
+ * 1. it parses as JSON — JSON syntax is frozen (RFC 8259), so text that
672
+ * does not parse can never be a valid config;
673
+ * 2. its top level is an object — ship.json is `{ ... }` in every version.
674
+ *
675
+ * Both are monotonic: neither can ever reject something the server would
676
+ * accept. Everything beyond them (field names, types, rule semantics, which
677
+ * keys are permitted) stays server-side, where it can change.
678
+ *
679
+ * The payoff is the common case. Hand-edited JSON fails on a trailing comma,
680
+ * a `//` comment, single quotes, unquoted keys, or smart quotes pasted from
681
+ * documentation — mistakes that otherwise cost a full upload round-trip to
682
+ * discover. A UTF-8 BOM (Windows editors, PowerShell redirects) is stripped
683
+ * before parsing rather than rejected, because the server accepts it too;
684
+ * diverging there would reintroduce exactly the false rejection this
685
+ * function exists to avoid.
686
+ *
687
+ * @throws {ShipError} `ErrorType.Config` — the same type the server's own
688
+ * config rejection carries, so the error contract is identical wherever the
689
+ * failure is detected.
690
+ */
691
+ declare function assertShipJsonSyntax(text: string): void;
648
692
  /**
649
693
  * Validate API key format
650
694
  */
@@ -834,7 +878,7 @@ interface TokenResource {
834
878
  ttl?: number;
835
879
  labels?: string[];
836
880
  }) => Promise<TokenCreateResponse>;
837
- list: () => Promise<TokenListResponse>;
881
+ list: (options?: ListOptions) => Promise<TokenListResponse>;
838
882
  remove: (token: string) => Promise<void>;
839
883
  }
840
884
  /**
@@ -932,6 +976,10 @@ interface ActivityMeta {
932
976
  interface ActivityListResponse {
933
977
  /** Array of activities */
934
978
  activities: Activity[];
979
+ /** Cursor for pagination, null if no more pages */
980
+ cursor: string | null;
981
+ /** Total number of activities */
982
+ total: number;
935
983
  }
936
984
  /**
937
985
  * File status constants for validation state tracking
@@ -1393,7 +1441,7 @@ declare class ApiHttp extends SimpleEvents {
1393
1441
  }>;
1394
1442
  validateDomain(name: string): Promise<DomainValidateResponse>;
1395
1443
  createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse>;
1396
- listTokens(): Promise<TokenListResponse>;
1444
+ listTokens(options?: ListOptions): Promise<TokenListResponse>;
1397
1445
  removeToken(token: string): Promise<void>;
1398
1446
  getAccount(): Promise<AccountGetResponse>;
1399
1447
  getLimits(): Promise<PlatformLimits>;
@@ -1830,6 +1878,6 @@ declare class Ship extends Ship$1 {
1830
1878
  }
1831
1879
 
1832
1880
  declare namespace Ship {
1833
- export { API_KEY, AUTH_BASE_PATH, Account, AccountGetResponse, AccountOverrides, AccountPlan, AccountPlanType, AccountResource, AccountUsage, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BLOCKED_EXTENSIONS, BillingStatus, CALLER, CheckoutSession, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_TOKEN, DeployBody, DeployBodyContext, DeployBodyCreator, DeployFile, DeployInput, Deployment, DeploymentCreateResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetResult, DomainStatus, DomainStatusType, DomainValidateResponse, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, ListOptions, MD5Result, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PingResponse, PlatformLimits, ResourceContext, SPACheckRequest, SPACheckResponse, SPA_DEFAULT_CONFIG, ShipClientOptions, ShipError, ShipEvents, StaticFile, TokenCreateResponse, TokenKind, TokenKindType, TokenListItem, TokenListResponse, TokenProvider, TokenResource, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, __setTestEnvironment, allValidFilesReady, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, extractSubdomain, filterJunk, formatFileSize, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, optimizeDeployPaths, pluralize, processFilesForNode, serializeLabels, validateApiKey, validateApiUrl, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validatePassword, validateToken };
1881
+ export { API_KEY, AUTH_BASE_PATH, Account, AccountGetResponse, AccountOverrides, AccountPlan, AccountPlanType, AccountResource, AccountUsage, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BLOCKED_EXTENSIONS, BillingStatus, CALLER, CheckoutSession, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_TOKEN, DeployBody, DeployBodyContext, DeployBodyCreator, DeployFile, DeployInput, Deployment, DeploymentCreateResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetResult, DomainStatus, DomainStatusType, DomainValidateResponse, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, ListOptions, MD5Result, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PingResponse, PlatformLimits, ResourceContext, SPACheckRequest, SPACheckResponse, SPA_DEFAULT_CONFIG, ShipClientOptions, ShipError, ShipEvents, StaticFile, TokenCreateResponse, TokenKind, TokenKindType, TokenListItem, TokenListResponse, TokenProvider, TokenResource, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, extractSubdomain, filterJunk, formatFileSize, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, optimizeDeployPaths, pluralize, processFilesForNode, serializeLabels, validateApiKey, validateApiUrl, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validatePassword, validateToken };
1834
1882
  }
1835
1883
  export = Ship;
package/dist/index.d.ts CHANGED
@@ -201,6 +201,8 @@ interface TokenListItem {
201
201
  interface TokenListResponse {
202
202
  /** Array of tokens (security-redacted for list display) */
203
203
  tokens: TokenListItem[];
204
+ /** Cursor for pagination, null if no more pages */
205
+ cursor: string | null;
204
206
  /** Total number of tokens */
205
207
  total: number;
206
208
  }
@@ -421,6 +423,18 @@ declare class ShipError extends Error {
421
423
  static file(message: string, details?: unknown): ShipError;
422
424
  static config(message: string, details?: unknown): ShipError;
423
425
  static api(message: string, status?: number, details?: unknown): ShipError;
426
+ /**
427
+ * The caller is at fault — by HTTP's own definition of a 4xx, or by a type
428
+ * that is client-attributable without ever having a status (`Config`,
429
+ * `File`, raised locally by the SDK).
430
+ *
431
+ * Both arms are load-bearing, because type and status are independent
432
+ * axes. `fromHttpResponse` trusts `body.error` only when it names a
433
+ * server-producible type; a non-OK response without one is status-derived,
434
+ * so a CDN 404 or any intermediary error arrives as `Api` — a server-fault
435
+ * *type* carrying a client *status*. Judging by type alone would report it
436
+ * as a platform failure and bury the server's own message.
437
+ */
424
438
  isClientError(): boolean;
425
439
  isNetworkError(): boolean;
426
440
  isAuthError(): boolean;
@@ -645,6 +659,36 @@ declare const SPA_DEFAULT_CONFIG: {
645
659
  readonly destination: "/index.html";
646
660
  }];
647
661
  };
662
+ /**
663
+ * Assert that a ship.json file is *syntactically* loadable. Syntax only —
664
+ * never schema.
665
+ *
666
+ * ship.json is validated and compiled on the server, deliberately: the schema
667
+ * and the compiler evolve, and a client that judged them would reject configs
668
+ * a newer platform accepts. That reasoning bounds what a client may check to
669
+ * the properties which are true of *every* past and future schema:
670
+ *
671
+ * 1. it parses as JSON — JSON syntax is frozen (RFC 8259), so text that
672
+ * does not parse can never be a valid config;
673
+ * 2. its top level is an object — ship.json is `{ ... }` in every version.
674
+ *
675
+ * Both are monotonic: neither can ever reject something the server would
676
+ * accept. Everything beyond them (field names, types, rule semantics, which
677
+ * keys are permitted) stays server-side, where it can change.
678
+ *
679
+ * The payoff is the common case. Hand-edited JSON fails on a trailing comma,
680
+ * a `//` comment, single quotes, unquoted keys, or smart quotes pasted from
681
+ * documentation — mistakes that otherwise cost a full upload round-trip to
682
+ * discover. A UTF-8 BOM (Windows editors, PowerShell redirects) is stripped
683
+ * before parsing rather than rejected, because the server accepts it too;
684
+ * diverging there would reintroduce exactly the false rejection this
685
+ * function exists to avoid.
686
+ *
687
+ * @throws {ShipError} `ErrorType.Config` — the same type the server's own
688
+ * config rejection carries, so the error contract is identical wherever the
689
+ * failure is detected.
690
+ */
691
+ declare function assertShipJsonSyntax(text: string): void;
648
692
  /**
649
693
  * Validate API key format
650
694
  */
@@ -834,7 +878,7 @@ interface TokenResource {
834
878
  ttl?: number;
835
879
  labels?: string[];
836
880
  }) => Promise<TokenCreateResponse>;
837
- list: () => Promise<TokenListResponse>;
881
+ list: (options?: ListOptions) => Promise<TokenListResponse>;
838
882
  remove: (token: string) => Promise<void>;
839
883
  }
840
884
  /**
@@ -932,6 +976,10 @@ interface ActivityMeta {
932
976
  interface ActivityListResponse {
933
977
  /** Array of activities */
934
978
  activities: Activity[];
979
+ /** Cursor for pagination, null if no more pages */
980
+ cursor: string | null;
981
+ /** Total number of activities */
982
+ total: number;
935
983
  }
936
984
  /**
937
985
  * File status constants for validation state tracking
@@ -1393,7 +1441,7 @@ declare class ApiHttp extends SimpleEvents {
1393
1441
  }>;
1394
1442
  validateDomain(name: string): Promise<DomainValidateResponse>;
1395
1443
  createToken(ttl?: number, labels?: string[]): Promise<TokenCreateResponse>;
1396
- listTokens(): Promise<TokenListResponse>;
1444
+ listTokens(options?: ListOptions): Promise<TokenListResponse>;
1397
1445
  removeToken(token: string): Promise<void>;
1398
1446
  getAccount(): Promise<AccountGetResponse>;
1399
1447
  getLimits(): Promise<PlatformLimits>;
@@ -1829,4 +1877,4 @@ declare class Ship extends Ship$1 {
1829
1877
  protected getDeployBodyCreator(): DeployBodyCreator;
1830
1878
  }
1831
1879
 
1832
- export { API_KEY, AUTH_BASE_PATH, type Account, type AccountGetResponse, type AccountOverrides, AccountPlan, type AccountPlanType, type AccountResource, type AccountUsage, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BLOCKED_EXTENSIONS, type BillingStatus, CALLER, type CheckoutSession, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_TOKEN, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeployInput, type Deployment, type DeploymentCreateResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetResult, DomainStatus, type DomainStatusType, type DomainValidateResponse, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type ListOptions, type MD5Result, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, type PingResponse, type PlatformLimits, type ResourceContext, type SPACheckRequest, type SPACheckResponse, SPA_DEFAULT_CONFIG, Ship, type ShipClientOptions, ShipError, type ShipEvents, type StaticFile, type TokenCreateResponse, TokenKind, type TokenKindType, type TokenListItem, type TokenListResponse, type TokenProvider, type TokenResource, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, __setTestEnvironment, allValidFilesReady, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, extractSubdomain, filterJunk, formatFileSize, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, optimizeDeployPaths, pluralize, processFilesForNode, serializeLabels, validateApiKey, validateApiUrl, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validatePassword, validateToken };
1880
+ export { API_KEY, AUTH_BASE_PATH, type Account, type AccountGetResponse, type AccountOverrides, AccountPlan, type AccountPlanType, type AccountResource, type AccountUsage, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BLOCKED_EXTENSIONS, type BillingStatus, CALLER, type CheckoutSession, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_TOKEN, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeployInput, type Deployment, type DeploymentCreateResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetResult, DomainStatus, type DomainStatusType, type DomainValidateResponse, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type ListOptions, type MD5Result, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, type PingResponse, type PlatformLimits, type ResourceContext, type SPACheckRequest, type SPACheckResponse, SPA_DEFAULT_CONFIG, Ship, type ShipClientOptions, ShipError, type ShipEvents, type StaticFile, type TokenCreateResponse, TokenKind, type TokenKindType, type TokenListItem, type TokenListResponse, type TokenProvider, type TokenResource, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, __setTestEnvironment, allValidFilesReady, assertShipJsonSyntax, calculateMD5, classifyToken, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, extractSubdomain, filterJunk, formatFileSize, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isCustomDomain, isDeployment, isPlatformDomain, isShipError, optimizeDeployPaths, pluralize, processFilesForNode, serializeLabels, validateApiKey, validateApiUrl, validateCaller, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validatePassword, validateToken };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var _e=Object.defineProperty;var R=(n,t)=>()=>(n&&(t=n(n=0)),t);var ke=(n,t)=>{for(var e in t)_e(n,e,{get:t[e],enumerable:!0})};function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Be.has(e)}function le(n){return He.test(n)}function _(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>q.has(e))}function Ge(n){return n.startsWith(pe.PREFIX)?x.API_KEY:n.startsWith(ce.PREFIX)?x.DEPLOY_TOKEN:x.OPAQUE}function de(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let i=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(i))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function ze(n){de(n,pe,"API key")}function Ve(n){de(n,ce,"Deploy token")}function K(n){switch(Ge(n)){case x.API_KEY:ze(n);return;case x.DEPLOY_TOKEN:Ve(n);return;case x.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function me(n){if(!n||n.length>V.MAX_LENGTH||!V.PATTERN.test(n))throw a.validation(`Caller must be 1-${V.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function ct(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw N(t)?t:a.validation("API URL must be a valid URL")}}function ut(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function fe(n,t){return n.endsWith(`.${t}`)}function dt(n,t){return!fe(n,t)}function mt(n,t){return fe(n,t)?n.slice(0,-(t.length+1)):null}function ft(n){return`https://${n}`}function ht(n){return`https://${n}`}function yt(n){return!n||n.length===0?null:JSON.stringify(n)}function gt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function Y(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<C.MIN_LENGTH||t.length>C.MAX_LENGTH)throw a.validation(`Password must be between ${C.MIN_LENGTH} and ${C.MAX_LENGTH} characters`);return t}var st,ot,at,m,Ue,z,Me,a,Be,He,q,lt,ae,pe,ce,V,x,pt,j,ue,X,y,v,he,C,g=R(()=>{"use strict";st={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ot={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},at={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Ue=new Set([m.Network,m.Cancelled,m.File,m.Config]),z={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},Me=new Set(Object.values(m).filter(n=>!Ue.has(n))),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let p=u;typeof p.message=="string"?i=p.message:typeof p.error=="string"&&(i=p.error),r=p.details,typeof p.error=="string"&&Me.has(p.error)&&(s=p.error)}}else{let u=await t.text();u&&(i=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let o=l.trim(),u=/^\d+$/.test(o)?Number(o):Math.ceil((Date.parse(o)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let p=r&&typeof r=="object"?r:{};p.retryAfter===void 0&&(r={...p,retryAfter:u})}}i=i||`${e||"Request"} failed with status ${t.status}`;let d=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(d,i,t.status,r)}static fromFetchError(t,e){if(N(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(m.Api,`${i} failed: ${t.message}`):new n(m.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(m.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(m.NotFound,i,404)}static forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,i){return new n(m.Business,t,e,i)}static network(t,e){return new n(m.Network,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,i){return new n(m.Api,t,e,i)}isClientError(){return z.client.has(this.type)}isNetworkError(){return z.network.has(this.type)}isAuthError(){return z.auth.has(this.type)}isType(t){return this.type===t}};Be=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);He=/[\x00-\x1f\x7f#?%\\<>"]/;q=new Set(["node_modules","package.json"]);lt="/auth",ae={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},pe={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ce={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},V={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},x={API_KEY:ae.API_KEY,DEPLOY_TOKEN:ae.TOKEN,OPAQUE:"opaque"};pt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},j="ship.json",ue={rewrites:[{source:"/(.*)",destination:"/index.html"}]};X="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};v={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},he=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;C={MIN_LENGTH:6,MAX_LENGTH:128}});async function je(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,i=2097152;for(let r=0;r<n.size;r+=i){let s=Math.min(r+i,n.size);e.append(await n.slice(r,s).arrayBuffer())}return{md5:e.end()}}async function Ke(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function Xe(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,r)=>{let s=t("md5"),l=e(n);l.on("error",d=>r(a.business(`Failed to read file for MD5: ${d.message}`))),l.on("data",d=>s.update(d)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function M(n){if(n instanceof Blob)return je(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return Ke(n);if(typeof n=="string")return Xe(n);throw a.business("Invalid input for MD5 calculation")}var B=R(()=>{"use strict";g()});function Mt(n){W=n}function We(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function I(){return W||We()}var W,F=R(()=>{"use strict";W=null});function xe(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let l=e[0][s];if(e.every(d=>d[s]===l))i.push(l);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var J=R(()=>{"use strict"});function Ie(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Q(i)}));let e=Ze(n);return n.map(i=>{let r=G(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Q(i)),{path:r,name:Q(i)}})}function Ze(n){if(!n.length)return"";let e=n.map(s=>G(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let l=e[0][s];if(e.every(d=>d[s]===l))i.push(l);else break}return i.join("/")}function Q(n){return n.split(/[/\\]/).pop()||n}var Z=R(()=>{"use strict";J()});function ee(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**r).toFixed(t))} ${i[r]}`}function te(n){if(le(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function nn(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(_(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let u=y.READY,p="Ready for upload",T=o.name?te(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,p=o.statusMessage||"File failed during processing",e.push({file:o.name,message:p});else if(o.size===0){u=y.EXCLUDED,p="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:p}),r.push({...o,status:u,statusMessage:p});continue}else o.size<0?(u=y.VALIDATION_FAILED,p="File size must be positive",e.push({file:o.name,message:p})):!o.name||o.name.trim().length===0?(u=y.VALIDATION_FAILED,p="File name cannot be empty",e.push({file:o.name||"(empty)",message:p})):o.name.includes("\0")?(u=y.VALIDATION_FAILED,p="File name contains invalid characters (null byte)",e.push({file:o.name,message:p})):T.valid?$(o.name)?(u=y.VALIDATION_FAILED,p=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:p})):o.size>t.maxFileSize?(u=y.VALIDATION_FAILED,p=`File size (${ee(o.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:o.name,message:p})):(s+=o.size,s>t.maxTotalSize&&(u=y.VALIDATION_FAILED,p=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:o.name,message:p}))):(u=y.VALIDATION_FAILED,p=T.reason||"Invalid file name",e.push({file:o.name,message:p}));r.push({...o,status:u,statusMessage:p})}e.length>0&&(r=r.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?r.filter(o=>o.status===y.READY):[],d=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:d}}function et(n){return n.filter(t=>t.status===y.READY)}function rn(n){return et(n).length>0}var ne=R(()=>{"use strict";g()});import{isJunk as tt}from"junk";function be(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&_(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(tt(r))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=i.slice(0,-1);for(let l of s)if(nt.some(d=>l.toLowerCase()===d.toLowerCase()))return!1;return!0})}var nt,ie=R(()=>{"use strict";g();nt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Le(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function Ne(n,t){let e=te(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var re=R(()=>{"use strict";g();ne()});var Ce={};ke(Ce,{processFilesForNode:()=>Fe});import*as E from"fs";import*as D from"path";function Oe(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let r=E.readdirSync(n);for(let s of r){let l=D.join(n,s),d=E.statSync(l);if(d.isDirectory()){let o=Oe(l,t);e.push(...o)}else d.isFile()&&e.push(l)}return e}async function Fe(n,t={},e){if(I()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let c of n){let f=D.resolve(c);try{if(E.statSync(f).isDirectory()){let S=E.readdirSync(f).find(A=>q.has(A));if(S)throw a.business(`"${S}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(S){if(N(S))throw S}}let i=n.flatMap(c=>{let f=D.resolve(c);try{return E.statSync(f).isDirectory()?Oe(f):[f]}catch{throw a.file(`Path does not exist: ${c}`,{filePath:c})}}),r=[...new Set(i)],s=n.map(c=>D.resolve(c)),l=xe(s.map(c=>{try{return E.statSync(c).isDirectory()?c:D.dirname(c)}catch{return D.dirname(c)}})),d=r.map(c=>{if(l&&l.length>0){let f=D.relative(l,c);if(f&&typeof f=="string"&&!f.startsWith(".."))return f.replace(/\\/g,"/")}return D.basename(c)}),u=Ie(d,{flatten:t.pathDetect!==!1}).map(c=>c.path),p=new Set(be(u));if(p.size===0)return[];let T=[],b=[];for(let c=0;c<r.length;c++)p.has(u[c])&&(T.push(r[c]),b.push(u[c]));let P=[],w=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let c=0;c<T.length;c++){let f=T[c],S=b[c];try{Le(S,f);let A=E.statSync(f);if(A.size===0)continue;if(Ne(S,f),A.size>e.maxFileSize)throw a.business(`File ${f} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(w+=A.size,w>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let L=E.readFileSync(f),{md5:$e}=await M(L);P.push({path:S,content:L,size:L.length,md5:$e})}catch(A){if(N(A))throw A;let L=A instanceof Error?A.message:String(A);throw a.file(`Failed to read file "${f}": ${L}`,{filePath:f})}}if(P.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return P}var se=R(()=>{"use strict";g();Z();F();ie();B();J();re()});g();g();g();var k=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{let d=l instanceof Error?l:new Error(String(l));this.emit("error",d,String(t))},0)}}};g();g();function O(n){if(n==null)return;if(n.length===0)return n;if(n.length>v.MAX_COUNT)throw a.validation(`Maximum ${v.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<v.MIN_LENGTH)throw a.validation(`Labels must be at least ${v.MIN_LENGTH} characters long`);if(s.length>v.MAX_LENGTH)throw a.validation(`Labels must be no more than ${v.MAX_LENGTH} characters long`);if(!he.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${v.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},qe=3e4;function ye(n){let t=new URLSearchParams;n?.limit!==void 0&&t.set("limit",String(n.limit)),n?.cursor!==void 0&&t.set("cursor",n.cursor);let e=t.toString();return e?`?${e}`:""}var U=class extends k{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||X,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??qe,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||h.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=()=>{};try{let l=await this.mergeHeaders(i.headers),d=this.createTimeoutSignal(i.signal);s=d.cleanup;let o={...i,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:d.signal};this.emit("request",e,o);let u=await this.fetch(e,o);if(s(),!u.ok)throw await a.fromHttpResponse(u,r);return this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(l){s();let d=a.fromFetchError(l,r);throw this.emit("error",d,e),d}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let o of e)if(!o.md5)throw a.file(`MD5 checksum missing for file: ${o.path}`,{filePath:o.path});Y(i.password);let r=O(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:d}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:d,signal:i.signal||null},"Deploy")}async listDeployments(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}${ye(e)}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=O(i);return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=O(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:d,status:o}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...d,isCreate:o===201}}async listDomains(e){return this.request(`${this.apiUrl}${h.DOMAINS}${ye(e)}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=O(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${h.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${h.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(o=>o.path==="index.html"||o.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let l={files:e.map(o=>o.path),index:s};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"SPA check")).isSPA}};g();g();B();async function Ye(){let n=JSON.stringify(ue,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await M(t);return{path:j,content:t,size:n.length,md5:e}}async function ge(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===j))return n;try{if(await t.checkSPA(n,e)){let r=await Ye();return[...n,r]}}catch{}return n}function Ee(n){let{getApi:t,ensureInit:e,processInput:i}=n;return{upload:async(r,s={})=>{if(await e(),!i)throw a.config("processInput function is not provided.");let l=t(),d=await i(r,s);return d=await ge(d,l,s),l.deploy(d,s)},list:async r=>(await e(),t().listDeployments(r)),get:async r=>(await e(),t().getDeployment(r)),set:async(r,s)=>(await e(),t().updateDeploymentLabels(r,s.labels)),remove:async r=>{await e(),await t().removeDeployment(r)}}}function De(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async i=>(await e(),t().listDomains(i)),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function Se(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function Ae(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var H=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&me(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new U({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Ee({...e,processInput:(i,r)=>this.processInput(i,r)}),this.domains=De(e),this.account=Se(e),this.tokens=Ae(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};F();g();import{z as we}from"zod";import{z as Te}from"zod";var Re={apiUrl:Te.string().url().optional(),token:Te.string().min(1).optional()};F();var Je=we.object(Re).strict(),Qe={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function ve(){if(I()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return Je.parse(n)}catch(t){if(t instanceof we.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&Qe[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Pe(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:d,flags:o,captcha:u}=t,p=new e,T=[];for(let c of n){if(!Buffer.isBuffer(c.content)&&!(typeof Blob<"u"&&c.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${c.path}`,{filePath:c.path});if(!c.md5)throw a.file(`File missing md5 checksum: ${c.path}`,{filePath:c.path});let f=new i([c.content],c.path,{type:"application/octet-stream"});p.append("files[]",f),T.push(c.md5)}p.append("checksums",JSON.stringify(T)),s&&s.length>0&&p.append("labels",JSON.stringify(s)),l&&p.append("via",l),d&&p.append("password",d),o?.build&&p.append("build","true"),o?.prerender&&p.append("prerender","true"),o?.spa&&p.append("spa","true"),u&&p.append("captcha",u);let b=new r(p),P=[];for await(let c of b.encode())P.push(Buffer.from(c));let w=Buffer.concat(P);return{body:w.buffer.slice(w.byteOffset,w.byteOffset+w.byteLength),headers:{"Content-Type":b.contentType,"Content-Length":Buffer.byteLength(w).toString()}}}g();g();Z();F();ne();ie();B();re();function dn(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}se();var oe=class extends H{constructor(t={}){if(I()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=ve();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(se(),Ce));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Pe}},it=oe;export{pe as API_KEY,lt as AUTH_BASE_PATH,at as AccountPlan,U as ApiHttp,ae as AuthMethod,Be as BLOCKED_EXTENSIONS,V as CALLER,X as DEFAULT_API,j as DEPLOYMENT_CONFIG_FILENAME,ce as DEPLOY_TOKEN,st as DeploymentStatus,ot as DomainStatus,m as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,nt as JUNK_DIRECTORIES,v as LABEL_CONSTRAINTS,he as LABEL_PATTERN,pt as OAuthScope,C as PASSWORD_CONSTRAINTS,ue as SPA_DEFAULT_CONFIG,oe as Ship,a as ShipError,x as TokenKind,q as UNBUILT_PROJECT_MARKERS,He as UNSAFE_FILENAME_CHARS,Mt as __setTestEnvironment,rn as allValidFilesReady,M as calculateMD5,Ge as classifyToken,Se as createAccountResource,Ee as createDeploymentResource,De as createDomainResource,Ae as createTokenResource,it as default,gt as deserializeLabels,mt as extractSubdomain,be as filterJunk,ee as formatFileSize,ft as generateDeploymentUrl,ht as generateDomainUrl,I as getENV,et as getValidFiles,_ as hasUnbuiltMarker,le as hasUnsafeChars,$ as isBlockedExtension,dt as isCustomDomain,ut as isDeployment,fe as isPlatformDomain,N as isShipError,Ie as optimizeDeployPaths,dn as pluralize,Fe as processFilesForNode,yt as serializeLabels,ze as validateApiKey,ct as validateApiUrl,me as validateCaller,Ne as validateDeployFile,Le as validateDeployPath,Ve as validateDeployToken,te as validateFileName,nn as validateFiles,Y as validatePassword,K as validateToken};
1
+ var Ue=Object.defineProperty;var w=(n,t)=>()=>(n&&(t=n(n=0)),t);var Me=(n,t)=>{for(var e in t)Ue(n,e,{get:t[e],enumerable:!0})};function O(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function _(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return Ge.has(e)}function ce(n){return ze.test(n)}function k(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>q.has(e))}function Ve(n){return n.startsWith(pe.PREFIX)?I.API_KEY:n.startsWith(ue.PREFIX)?I.DEPLOY_TOKEN:I.OPAQUE}function me(n){let t=n.charCodeAt(0)===65279?n.slice(1):n,e;try{e=JSON.parse(t)}catch(i){throw a.config(`invalid JSON format in config: ${i.message}`,{filePath:R})}if(e===null||typeof e!="object"||Array.isArray(e))throw a.config(`${R} must contain a JSON object`,{filePath:R})}function fe(n,t,e){if(!n.startsWith(t.PREFIX))throw a.validation(`${e} must start with "${t.PREFIX}"`);if(n.length!==t.TOTAL_LENGTH)throw a.validation(`${e} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let i=n.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(i))throw a.validation(`${e} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function je(n){fe(n,pe,"API key")}function qe(n){fe(n,ue,"Deploy token")}function K(n){switch(Ve(n)){case I.API_KEY:je(n);return;case I.DEPLOY_TOKEN:qe(n);return;case I.OPAQUE:if(!n)throw a.validation("Token must be a non-empty string")}}function he(n){if(!n||n.length>j.MAX_LENGTH||!j.PATTERN.test(n))throw a.validation(`Caller must be 1-${j.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function mt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw O(t)?t:a.validation("API URL must be a valid URL")}}function ft(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function ye(n,t){return n.endsWith(`.${t}`)}function ht(n,t){return!ye(n,t)}function yt(n,t){return ye(n,t)?n.slice(0,-(t.length+1)):null}function gt(n){return`https://${n}`}function Et(n){return`https://${n}`}function Dt(n){return!n||n.length===0?null:JSON.stringify(n)}function St(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function Y(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<$.MIN_LENGTH||t.length>$.MAX_LENGTH)throw a.validation(`Password must be between ${$.MIN_LENGTH} and ${$.MAX_LENGTH} characters`);return t}var lt,ct,pt,m,Be,V,He,a,Ge,ze,q,ut,le,pe,ue,j,I,dt,R,de,X,y,P,ge,$,g=w(()=>{"use strict";lt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ct={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},pt={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Be=new Set([m.Network,m.Cancelled,m.File,m.Config]),V={client:new Set([m.Business,m.Config,m.File,m.Forbidden,m.NotFound,m.RateLimit,m.Validation]),network:new Set([m.Network]),auth:new Set([m.Authentication])},He=new Set(Object.values(m).filter(n=>!Be.has(n))),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let u=await t.json();if(u&&typeof u=="object"){let c=u;typeof c.message=="string"?i=c.message:typeof c.error=="string"&&(i=c.error),r=c.details,typeof c.error=="string"&&He.has(c.error)&&(s=c.error)}}else{let u=await t.text();u&&(i=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let o=l.trim(),u=/^\d+$/.test(o)?Number(o):Math.ceil((Date.parse(o)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let c=r&&typeof r=="object"?r:{};c.retryAfter===void 0&&(r={...c,retryAfter:u})}}i=i||`${e||"Request"} failed with status ${t.status}`;let d=s??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new n(d,i,t.status,r)}static fromFetchError(t,e){if(O(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(m.Api,`${i} failed: ${t.message}`):new n(m.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(m.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(m.NotFound,i,404)}static forbidden(t,e){return new n(m.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(m.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(m.Authentication,t,401,e)}static business(t,e=400,i){return new n(m.Business,t,e,i)}static network(t,e){return new n(m.Network,t,void 0,e)}static cancelled(t,e){return new n(m.Cancelled,t,void 0,e)}static file(t,e){return new n(m.File,t,void 0,e)}static config(t,e){return new n(m.Config,t,void 0,e)}static api(t,e=500,i){return new n(m.Api,t,e,i)}isClientError(){return V.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isType(t){return this.type===t}};Ge=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);ze=/[\x00-\x1f\x7f#?%\\<>"]/;q=new Set(["node_modules","package.json"]);ut="/auth",le={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",WEBHOOK:"webhook",SYSTEM:"system"},pe={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},ue={PREFIX:"deploy-",HEX_LENGTH:64,TOTAL_LENGTH:71},j={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},I={API_KEY:le.API_KEY,DEPLOY_TOKEN:le.TOKEN,OPAQUE:"opaque"};dt={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},R="ship.json",de={rewrites:[{source:"/(.*)",destination:"/index.html"}]};X="https://api.shipstatic.com",y={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};P={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},ge=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;$={MIN_LENGTH:6,MAX_LENGTH:128}});async function Ye(n){let t=(await import("spark-md5")).default,e=new t.ArrayBuffer,i=2097152;for(let r=0;r<n.size;r+=i){let s=Math.min(r+i,n.size);e.append(await n.slice(r,s).arrayBuffer())}return{md5:e.end()}}async function We(n){let{createHash:t}=await import("crypto"),e=t("md5");return e.update(n),{md5:e.digest("hex")}}async function Je(n){let{createHash:t}=await import("crypto"),{createReadStream:e}=await import("fs");return new Promise((i,r)=>{let s=t("md5"),l=e(n);l.on("error",d=>r(a.business(`Failed to read file for MD5: ${d.message}`))),l.on("data",d=>s.update(d)),l.on("end",()=>i({md5:s.digest("hex")}))})}async function B(n){if(n instanceof Blob)return Ye(n);if(typeof Buffer<"u"&&Buffer.isBuffer(n))return We(n);if(typeof n=="string")return Je(n);throw a.business("Invalid input for MD5 calculation")}var H=w(()=>{"use strict";g()});function Gt(n){J=n}function Ze(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function b(){return J||Ze()}var J,C=w(()=>{"use strict";J=null});function be(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let l=e[0][s];if(e.every(d=>d[s]===l))i.push(l);else break}return i.join("/")}function z(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Q=w(()=>{"use strict"});function Le(n,t={}){if(t.flatten===!1)return n.map(i=>({path:z(i),name:Z(i)}));let e=nt(n);return n.map(i=>{let r=z(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Z(i)),{path:r,name:Z(i)}})}function nt(n){if(!n.length)return"";let e=n.map(s=>z(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let l=e[0][s];if(e.every(d=>d[s]===l))i.push(l);else break}return i.join("/")}function Z(n){return n.split(/[/\\]/).pop()||n}var ee=w(()=>{"use strict";Q()});function te(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return`${parseFloat((n/e**r).toFixed(t))} ${i[r]}`}function ne(n){if(ce(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function on(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(k(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(u=>({...u,status:y.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let u=y.READY,c="Ready for upload",T=o.name?ne(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===y.PROCESSING_ERROR)u=y.VALIDATION_FAILED,c=o.statusMessage||"File failed during processing",e.push({file:o.name,message:c});else if(o.size===0){u=y.EXCLUDED,c="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:c}),r.push({...o,status:u,statusMessage:c});continue}else o.size<0?(u=y.VALIDATION_FAILED,c="File size must be positive",e.push({file:o.name,message:c})):!o.name||o.name.trim().length===0?(u=y.VALIDATION_FAILED,c="File name cannot be empty",e.push({file:o.name||"(empty)",message:c})):o.name.includes("\0")?(u=y.VALIDATION_FAILED,c="File name contains invalid characters (null byte)",e.push({file:o.name,message:c})):T.valid?_(o.name)?(u=y.VALIDATION_FAILED,c=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:c})):o.size>t.maxFileSize?(u=y.VALIDATION_FAILED,c=`File size (${te(o.size)}) exceeds limit of ${te(t.maxFileSize)}`,e.push({file:o.name,message:c})):(s+=o.size,s>t.maxTotalSize&&(u=y.VALIDATION_FAILED,c=`Total size would exceed limit of ${te(t.maxTotalSize)}`,e.push({file:o.name,message:c}))):(u=y.VALIDATION_FAILED,c=T.reason||"Invalid file name",e.push({file:o.name,message:c}));r.push({...o,status:u,statusMessage:c})}e.length>0&&(r=r.map(o=>o.status===y.EXCLUDED?o:{...o,status:y.VALIDATION_FAILED,statusMessage:o.status===y.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=e.length===0?r.filter(o=>o.status===y.READY):[],d=e.length===0;return{files:r,validFiles:l,errors:e,warnings:i,canDeploy:d}}function it(n){return n.filter(t=>t.status===y.READY)}function an(n){return it(n).length>0}var ie=w(()=>{"use strict";g()});import{isJunk as rt}from"junk";function Ne(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&k(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(rt(r))return!1;for(let l of i)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let s=i.slice(0,-1);for(let l of s)if(st.some(d=>l.toLowerCase()===d.toLowerCase()))return!1;return!0})}var st,re=w(()=>{"use strict";g();st=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Oe(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function Fe(n,t){let e=ne(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if(_(n))throw a.business(`File extension not allowed: "${t}"`)}var se=w(()=>{"use strict";g();ie()});var _e={};Me(_e,{processFilesForNode:()=>$e});import*as E from"fs";import*as D from"path";function Ce(n,t=new Set){let e=[],i=E.realpathSync(n);if(t.has(i))return e;t.add(i);let r=E.readdirSync(n);for(let s of r){let l=D.join(n,s),d=E.statSync(l);if(d.isDirectory()){let o=Ce(l,t);e.push(...o)}else d.isFile()&&e.push(l)}return e}async function $e(n,t={},e){if(b()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let p of n){let f=D.resolve(p);try{if(E.statSync(f).isDirectory()){let S=E.readdirSync(f).find(A=>q.has(A));if(S)throw a.business(`"${S}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(S){if(O(S))throw S}}let i=n.flatMap(p=>{let f=D.resolve(p);try{return E.statSync(f).isDirectory()?Ce(f):[f]}catch{throw a.file(`Path does not exist: ${p}`,{filePath:p})}}),r=[...new Set(i)],s=n.map(p=>D.resolve(p)),l=be(s.map(p=>{try{return E.statSync(p).isDirectory()?p:D.dirname(p)}catch{return D.dirname(p)}})),d=r.map(p=>{if(l&&l.length>0){let f=D.relative(l,p);if(f&&typeof f=="string"&&!f.startsWith(".."))return f.replace(/\\/g,"/")}return D.basename(p)}),u=Le(d,{flatten:t.pathDetect!==!1}).map(p=>p.path),c=new Set(Ne(u));if(c.size===0)return[];let T=[],L=[];for(let p=0;p<r.length;p++)c.has(u[p])&&(T.push(r[p]),L.push(u[p]));let x=[],v=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let p=0;p<T.length;p++){let f=T[p],S=L[p];try{Oe(S,f);let A=E.statSync(f);if(A.size===0)continue;if(Fe(S,f),A.size>e.maxFileSize)throw a.business(`File ${f} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(v+=A.size,v>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let N=E.readFileSync(f),{md5:ke}=await B(N);x.push({path:S,content:N,size:N.length,md5:ke})}catch(A){if(O(A))throw A;let N=A instanceof Error?A.message:String(A);throw a.file(`Failed to read file "${f}": ${N}`,{filePath:f})}}if(x.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return x}var oe=w(()=>{"use strict";g();ee();C();re();H();Q();se()});g();g();g();var U=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(l){i.delete(s),t!=="error"&&setTimeout(()=>{let d=l instanceof Error?l:new Error(String(l));this.emit("error",d,String(t))},0)}}};g();g();function F(n){if(n==null)return;if(n.length===0)return n;if(n.length>P.MAX_COUNT)throw a.validation(`Maximum ${P.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<P.MIN_LENGTH)throw a.validation(`Labels must be at least ${P.MIN_LENGTH} characters long`);if(s.length>P.MAX_LENGTH)throw a.validation(`Labels must be no more than ${P.MAX_LENGTH} characters long`);if(!ge.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${P.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}async function Ee(n){let t=n.find(r=>r.path===R||r.path===`/${R}`);if(!t)return;let e=t.content,i=typeof e.text=="function"?await e.text():t.content.toString("utf8");me(i)}var h={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},Ke=3e4,Xe="sdk";function W(n){let t=new URLSearchParams;n?.limit!==void 0&&t.set("limit",String(n.limit)),n?.cursor!==void 0&&t.set("cursor",n.cursor);let e=t.toString();return e?`?${e}`:""}var M=class extends U{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||X,this.getAuthHeadersCallback=e.getAuthHeaders,this.session=e.session??!1,this.caller=e.caller,this.timeout=e.timeout??Ke,this.fetch=e.fetch??globalThis.fetch.bind(globalThis),this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||h.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=()=>{};try{let l=await this.mergeHeaders(i.headers),d=this.createTimeoutSignal(i.signal);s=d.cleanup;let o={...i,headers:l,credentials:this.session&&!l.Authorization?"include":void 0,signal:d.signal};this.emit("request",e,o);let u=await this.fetch(e,o);if(s(),!u.ok)throw await a.fromHttpResponse(u,r);return this.emit("response",this.safeClone(u),e),{data:await this.parseResponse(this.safeClone(u)),status:u.status}}catch(l){s();let d=a.fromFetchError(l,r);throw this.emit("error",d,e),d}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}async mergeHeaders(e={}){return{...this.globalHeaders,...this.caller?{"X-Caller":this.caller}:{},...await this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let o of e)if(!o.md5)throw a.file(`MD5 checksum missing for file: ${o.path}`,{filePath:o.path});Y(i.password);let r=F(i.labels);await Ee(e);let s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:l,headers:d}=await this.createDeployBody(e,{labels:r,via:i.via??Xe,password:i.password,flags:s,captcha:i.captcha});return this.request(`${this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:l,headers:d,signal:i.signal||null},"Deploy")}async listDeployments(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}${W(e)}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=F(i);return this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${h.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=F(r),l={};i&&(l.deployment=i),s!==void 0&&(l.labels=s);let{data:d,status:o}=await this.requestWithStatus(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"Set domain");return{...d,isCreate:o===201}}async listDomains(e){return this.request(`${this.apiUrl}${h.DOMAINS}${W(e)}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${h.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${h.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=F(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${h.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(e){return this.request(`${this.apiUrl}${h.TOKENS}${W(e)}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${h.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async getAccount(){return this.request(`${this.apiUrl}${h.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${h.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${h.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(o=>o.path==="index.html"||o.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let l={files:e.map(o=>o.path),index:s};return(await this.request(`${this.apiUrl}${h.SPA_CHECK}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)},"SPA check")).isSPA}};g();g();H();async function Qe(){let n=JSON.stringify(de,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await B(t);return{path:R,content:t,size:n.length,md5:e}}async function De(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===R))return n;try{if(await t.checkSPA(n,e)){let r=await Qe();return[...n,r]}}catch{}return n}function Se(n){let{getApi:t,ensureInit:e,processInput:i}=n;return{upload:async(r,s={})=>{if(await e(),!i)throw a.config("processInput function is not provided.");let l=t(),d=await i(r,s);return d=await De(d,l,s),l.deploy(d,s)},list:async r=>(await e(),t().listDeployments(r)),get:async r=>(await e(),t().getDeployment(r)),set:async(r,s)=>(await e(),t().updateDeploymentLabels(r,s.labels)),remove:async r=>{await e(),await t().removeDeployment(r)}}}function Ae(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async i=>(await e(),t().listDomains(i)),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function Te(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function we(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async i=>(await e(),t().listTokens(i)),remove:async i=>{await e(),await t().removeToken(i)}}}var G=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.credential=null;if(t={...t,apiUrl:t.apiUrl||void 0,token:t.token||void 0,caller:t.caller||void 0},this.clientOptions=t,t.caller!==void 0&&he(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(K(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new M({...t,getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=Se({...e,processInput:(i,r)=>this.processInput(i,r)}),this.domains=Ae(e),this.account=Te(e),this.tokens=we(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setToken(t){if(this.clientOptions.session)throw a.config("Provide either `token` or `session`, not both.");if(typeof t=="string"){if(!t)throw a.business("Invalid token provided. Token must be a non-empty string.");K(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};C();g();import{z as Pe}from"zod";import{z as Re}from"zod";var ve={apiUrl:Re.string().url().optional(),token:Re.string().min(1).optional()};C();var et=Pe.object(ve).strict(),tt={apiUrl:"SHIP_API_URL",token:"SHIP_TOKEN"};function xe(){if(b()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,token:process.env.SHIP_TOKEN||void 0};try{return et.parse(n)}catch(t){if(t instanceof Pe.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&tt[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}g();async function Ie(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:l,password:d,flags:o,captcha:u}=t,c=new e,T=[];for(let p of n){if(!Buffer.isBuffer(p.content)&&!(typeof Blob<"u"&&p.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${p.path}`,{filePath:p.path});if(!p.md5)throw a.file(`File missing md5 checksum: ${p.path}`,{filePath:p.path});let f=new i([p.content],p.path,{type:"application/octet-stream"});c.append("files[]",f),T.push(p.md5)}c.append("checksums",JSON.stringify(T)),s&&s.length>0&&c.append("labels",JSON.stringify(s)),l&&c.append("via",l),d&&c.append("password",d),o?.build&&c.append("build","true"),o?.prerender&&c.append("prerender","true"),o?.spa&&c.append("spa","true"),u&&c.append("captcha",u);let L=new r(c),x=[];for await(let p of L.encode())x.push(Buffer.from(p));let v=Buffer.concat(x);return{body:v.buffer.slice(v.byteOffset,v.byteOffset+v.byteLength),headers:{"Content-Type":L.contentType,"Content-Length":Buffer.byteLength(v).toString()}}}g();g();ee();C();ie();re();H();se();function hn(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}oe();var ae=class extends G{constructor(t={}){if(b()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=xe();super({...t,apiUrl:t.apiUrl||e.apiUrl,token:t.token||(t.session?void 0:e.token)})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(oe(),_e));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Ie}},ot=ae;export{pe as API_KEY,ut as AUTH_BASE_PATH,pt as AccountPlan,M as ApiHttp,le as AuthMethod,Ge as BLOCKED_EXTENSIONS,j as CALLER,X as DEFAULT_API,R as DEPLOYMENT_CONFIG_FILENAME,ue as DEPLOY_TOKEN,lt as DeploymentStatus,ct as DomainStatus,m as ErrorType,y as FILE_VALIDATION_STATUS,y as FileValidationStatus,st as JUNK_DIRECTORIES,P as LABEL_CONSTRAINTS,ge as LABEL_PATTERN,dt as OAuthScope,$ as PASSWORD_CONSTRAINTS,de as SPA_DEFAULT_CONFIG,ae as Ship,a as ShipError,I as TokenKind,q as UNBUILT_PROJECT_MARKERS,ze as UNSAFE_FILENAME_CHARS,Gt as __setTestEnvironment,an as allValidFilesReady,me as assertShipJsonSyntax,B as calculateMD5,Ve as classifyToken,Te as createAccountResource,Se as createDeploymentResource,Ae as createDomainResource,we as createTokenResource,ot as default,St as deserializeLabels,yt as extractSubdomain,Ne as filterJunk,te as formatFileSize,gt as generateDeploymentUrl,Et as generateDomainUrl,b as getENV,it as getValidFiles,k as hasUnbuiltMarker,ce as hasUnsafeChars,_ as isBlockedExtension,ht as isCustomDomain,ft as isDeployment,ye as isPlatformDomain,O as isShipError,Le as optimizeDeployPaths,hn as pluralize,$e as processFilesForNode,Dt as serializeLabels,je as validateApiKey,mt as validateApiUrl,he as validateCaller,Fe as validateDeployFile,Oe as validateDeployPath,qe as validateDeployToken,ne as validateFileName,on as validateFiles,Y as validatePassword,K as validateToken};
2
2
  //# sourceMappingURL=index.js.map