@shipstatic/ship 3.5.0 → 3.6.0-beta.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 +2 -2
- package/SKILL.md +3 -3
- package/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +71 -26
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +44 -44
- package/dist/cli.cjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -26
- package/dist/index.d.ts +71 -26
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -72,7 +72,7 @@ declare const DeploymentVia: {
|
|
|
72
72
|
readonly GIT: "git";
|
|
73
73
|
/** The n8n community node. */
|
|
74
74
|
readonly N8N: "n8n";
|
|
75
|
-
/** Channel: the ChatGPT
|
|
75
|
+
/** Channel: the ChatGPT plugin → `mcp.<domain>/gpt`. */
|
|
76
76
|
readonly GPT: "gpt";
|
|
77
77
|
/** The VS Code extension. */
|
|
78
78
|
readonly VSC: "vsc";
|
|
@@ -116,7 +116,7 @@ interface Deployment {
|
|
|
116
116
|
readonly config: boolean;
|
|
117
117
|
/** Whether deployment has a password set */
|
|
118
118
|
readonly password: boolean;
|
|
119
|
-
/** Labels for categorization and filtering (
|
|
119
|
+
/** Labels for categorization and filtering (a word like `production`, or a key and a value like `env:production`). Always present, empty array when none. */
|
|
120
120
|
labels: string[];
|
|
121
121
|
/**
|
|
122
122
|
* The client/tool that created this deployment. Every deployment created
|
|
@@ -380,7 +380,7 @@ interface Domain {
|
|
|
380
380
|
verifications: number;
|
|
381
381
|
/** Unix timestamp (seconds) when plan enforcement paused serving, null while the plan has room for it */
|
|
382
382
|
paused: number | null;
|
|
383
|
-
/** Labels for categorization and filtering (
|
|
383
|
+
/** Labels for categorization and filtering (a word like `production`, or a key and a value like `env:production`). Always present, empty array when none. */
|
|
384
384
|
labels: string[];
|
|
385
385
|
/** Unix timestamp (seconds) when domain was created */
|
|
386
386
|
readonly created: number;
|
|
@@ -1150,9 +1150,9 @@ declare const API_PATHS: {
|
|
|
1150
1150
|
readonly UPLOAD: "/upload";
|
|
1151
1151
|
};
|
|
1152
1152
|
/**
|
|
1153
|
-
* The deploy request's multipart field names
|
|
1154
|
-
* surface beside {@link API_PATHS}.
|
|
1155
|
-
*
|
|
1153
|
+
* The deploy request's multipart field names: the other half of the wire
|
|
1154
|
+
* surface beside {@link API_PATHS}. These are the names the API reads from a
|
|
1155
|
+
* multipart body on `POST /deployments` and the first-party `/upload`.
|
|
1156
1156
|
*
|
|
1157
1157
|
* Declared once because the body has three independent WRITERS — the SDK's
|
|
1158
1158
|
* Node and browser body builders, and the n8n community node's hand-rolled
|
|
@@ -1199,10 +1199,10 @@ declare const DEPLOY_FIELDS: {
|
|
|
1199
1199
|
readonly CAPTCHA: "captcha";
|
|
1200
1200
|
};
|
|
1201
1201
|
/**
|
|
1202
|
-
* The JSON deploy body's file grammar: the OTHER body
|
|
1203
|
-
* beside the multipart one {@link DEPLOY_FIELDS} names. A JSON caller
|
|
1204
|
-
* `{ files: [{ path, content, encoding? }] }`, and this is the whole
|
|
1205
|
-
* one entry may say: three field names, two encodings, one default.
|
|
1202
|
+
* The JSON deploy body's file grammar: the OTHER body both deploy doors
|
|
1203
|
+
* accept, beside the multipart one {@link DEPLOY_FIELDS} names. A JSON caller
|
|
1204
|
+
* sends `{ files: [{ path, content, encoding? }] }`, and this is the whole
|
|
1205
|
+
* of what one entry may say: three field names, two encodings, one default.
|
|
1206
1206
|
*
|
|
1207
1207
|
* Declared once because the grammar has three independent holders that the
|
|
1208
1208
|
* wire forces to restate it: the API's zod schema (the original), the hosted
|
|
@@ -2898,28 +2898,73 @@ declare function generateDeploymentUrl(deployment: string): string;
|
|
|
2898
2898
|
*/
|
|
2899
2899
|
declare function generateDomainUrl(domain: string): string;
|
|
2900
2900
|
/**
|
|
2901
|
-
*
|
|
2902
|
-
*
|
|
2901
|
+
* A label is a short identifier attached to a deployment, a domain or a token.
|
|
2902
|
+
* It has one of two forms:
|
|
2903
|
+
*
|
|
2904
|
+
* - a word: `production`, `v1.2.3`, `us-east-1`
|
|
2905
|
+
* - a key and a value, split by one `:`: `env:production`, `team:web`
|
|
2906
|
+
*
|
|
2907
|
+
* Each side is lowercase letters and digits, with single `.`, `_` or `-`
|
|
2908
|
+
* between them. The whole label, the key and the `:` and the value together,
|
|
2909
|
+
* counts toward {@link LABEL_CONSTRAINTS.MAX_LENGTH}.
|
|
2910
|
+
*
|
|
2911
|
+
* The platform stores a label in lowercase and shows it as stored. It reads
|
|
2912
|
+
* nothing from a key or a value and changes no behaviour because of one: a
|
|
2913
|
+
* label describes a resource and lets its owner find it. So a resource may carry several
|
|
2914
|
+
* values for one key (`team:web` and `team:api`), and only the same label
|
|
2915
|
+
* twice is refused.
|
|
2916
|
+
*
|
|
2917
|
+
* Labels stay a list of strings on the wire and in storage. A caller that
|
|
2918
|
+
* wants a key's value splits on the `:` itself.
|
|
2903
2919
|
*/
|
|
2904
2920
|
declare const LABEL_CONSTRAINTS: {
|
|
2905
|
-
/** Minimum label length in characters */
|
|
2921
|
+
/** Minimum label length in characters. */
|
|
2906
2922
|
readonly MIN_LENGTH: 3;
|
|
2907
|
-
/**
|
|
2908
|
-
|
|
2909
|
-
|
|
2923
|
+
/**
|
|
2924
|
+
* Maximum label length in characters. A key, its `:` and its value share it,
|
|
2925
|
+
* and it fits a key with a UUID (36 characters) or a full git SHA (40).
|
|
2926
|
+
*/
|
|
2927
|
+
readonly MAX_LENGTH: 63;
|
|
2928
|
+
/** Maximum number of labels on one resource. */
|
|
2910
2929
|
readonly MAX_COUNT: 10;
|
|
2911
|
-
/** Allowed separator characters between label segments */
|
|
2912
|
-
readonly SEPARATORS: "._-";
|
|
2913
2930
|
};
|
|
2914
2931
|
/**
|
|
2915
|
-
*
|
|
2916
|
-
*
|
|
2917
|
-
*
|
|
2932
|
+
* The shape of a label: one side, or two with a `:` between them. A side is
|
|
2933
|
+
* lowercase letters and digits with single `.`, `_` or `-` between them, and
|
|
2934
|
+
* the pattern spells it twice. Length is {@link LABEL_CONSTRAINTS}' rule, and
|
|
2935
|
+
* {@link validateLabel} applies both.
|
|
2918
2936
|
*
|
|
2919
|
-
*
|
|
2920
|
-
*
|
|
2937
|
+
* Matches: `production`, `v1.2.3`, `env:production`, `commit:3f9c2ab`
|
|
2938
|
+
* Refuses: `-prod`, `foo--bar`, `:production`, `env:`, `a:b:c`, `Env:Prod`
|
|
2921
2939
|
*/
|
|
2922
2940
|
declare const LABEL_PATTERN: RegExp;
|
|
2941
|
+
/**
|
|
2942
|
+
* Validate one label and return it normalized: trimmed and lowercased, then
|
|
2943
|
+
* held to {@link LABEL_CONSTRAINTS}' length and to {@link LABEL_PATTERN}.
|
|
2944
|
+
* Throws `ShipError.validation` when it does not fit.
|
|
2945
|
+
*
|
|
2946
|
+
* Lowercasing is the one normalization and it applies to both sides of a
|
|
2947
|
+
* `:`, so `Env:Prod` is stored as `env:prod`. A value that must keep its
|
|
2948
|
+
* case does not belong in a label.
|
|
2949
|
+
*
|
|
2950
|
+
* The one label check on the platform: the SDK and the console call it for
|
|
2951
|
+
* fast feedback and the API calls it as the boundary, so all three refuse
|
|
2952
|
+
* the same strings in the same words.
|
|
2953
|
+
*/
|
|
2954
|
+
declare function validateLabel(value: unknown): string;
|
|
2955
|
+
/**
|
|
2956
|
+
* Validate a resource's labels and return them normalized, each through
|
|
2957
|
+
* {@link validateLabel}. Absent (`undefined` / `null`) returns `undefined`;
|
|
2958
|
+
* an empty array returns as is, which is how an update clears every label.
|
|
2959
|
+
* At most {@link LABEL_CONSTRAINTS.MAX_COUNT}, and no label twice after
|
|
2960
|
+
* normalization.
|
|
2961
|
+
*
|
|
2962
|
+
* It takes any value, like the other checks here, because two callers hand it
|
|
2963
|
+
* one the compiler has not seen: the API's multipart door (a parsed JSON
|
|
2964
|
+
* field) and an SDK caller without TypeScript.
|
|
2965
|
+
*/
|
|
2966
|
+
declare function validateLabels(labels: string[]): string[];
|
|
2967
|
+
declare function validateLabels(labels: unknown): string[] | undefined;
|
|
2923
2968
|
/**
|
|
2924
2969
|
* Serialize labels array to JSON string for database storage.
|
|
2925
2970
|
* Returns null for empty or undefined arrays.
|
|
@@ -3040,8 +3085,8 @@ type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
|
3040
3085
|
*/
|
|
3041
3086
|
interface DeployBodyContext {
|
|
3042
3087
|
/**
|
|
3043
|
-
* Deployment labels
|
|
3044
|
-
* `
|
|
3088
|
+
* Deployment labels, each a word (`production`) or a key and a value
|
|
3089
|
+
* (`env:production`), already through `validateLabels`.
|
|
3045
3090
|
*/
|
|
3046
3091
|
labels?: string[];
|
|
3047
3092
|
/**
|
|
@@ -3939,6 +3984,6 @@ declare class Ship extends Ship$1 {
|
|
|
3939
3984
|
}
|
|
3940
3985
|
|
|
3941
3986
|
declare namespace Ship {
|
|
3942
|
-
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountAccess, AccountDeleteResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountRefusal, AccountRefusalType, AccountResource, AccountRole, AccountUsage, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BUILD_SETTINGS, BillingInterval, BillingPortalSession, BillingSyncResponse, BuildFailureDetails, CALLER, Caps, ConsoleErrand, ConsolePaths, ConsoleSection, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, DeployBodyContext, DeployFile, DeployFileEncoding, DeployFileSpec, DeployInput, DeployTransport, Deployment, DeploymentCreateResponse, DeploymentDeleteResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentSetOptions, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DeploymentVia, DeploymentViaType, DnsLookup, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDeleteResponse, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetOptions, DomainSetResult, DomainShareResponse, DomainStatus, DomainStatusType, DomainValidateResponse, DomainVerification, DomainVerificationType, DomainVerifyResponse, DoorSegment, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, LabelsResponse, ListOptions, ListResponse, MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, PingResponse, Plan, PlanChangeRefusalDetails, PlanChangeRequest, PlanChangeResponse, PlanDestination, PlansResponse, PlatformLimitKey, PlatformLimits, RequestResult, ResourceContext, SECTIONS, SETUP_TROUBLESHOOTING_ANCHOR, SHIP_ENV, SHIP_VIA_ENV, SPACheckRequest, SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, ScheduledChange, SettingsFragment, SetupInstructionsResponse, ShipClientOptions, ShipError, ShipEvents, ShipRequestInit, StaticFile, TTL_CONSTRAINTS, Token, TokenCreateOptions, TokenCreateResponse, TokenDeleteResponse, TokenKind, TokenKindType, TokenListResponse, TokenProvider, TokenResource, Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, USAGE_KIND, USER_VISIBLE_EVENTS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, countPhrase, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, doorOf, doors, errandOf, excessOver, extractSubdomain, filterJunk, fitPhrase, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, placesTaken, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3987
|
+
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountAccess, AccountDeleteResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountRefusal, AccountRefusalType, AccountResource, AccountRole, AccountUsage, Activity, ActivityEvent, ActivityListResponse, ActivityMeta, ApiDeployOptions, ApiHttp, ApiHttpOptions, AuthMethod, AuthMethodType, BUILD_SETTINGS, BillingInterval, BillingPortalSession, BillingSyncResponse, BuildFailureDetails, CALLER, Caps, ConsoleErrand, ConsolePaths, ConsoleSection, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, DeployBodyContext, DeployFile, DeployFileEncoding, DeployFileSpec, DeployInput, DeployTransport, Deployment, DeploymentCreateResponse, DeploymentDeleteResponse, DeploymentListResponse, DeploymentOptions, DeploymentResource, DeploymentResourceContext, DeploymentSetOptions, DeploymentStatus, DeploymentStatusType, DeploymentUploadOptions, DeploymentVia, DeploymentViaType, DnsLookup, DnsProvider, DnsRecord, DnsRecordType, Domain, DomainDeleteResponse, DomainDnsResponse, DomainListResponse, DomainRecordsResponse, DomainResource, DomainSetOptions, DomainSetResult, DomainShareResponse, DomainStatus, DomainStatusType, DomainValidateResponse, DomainVerification, DomainVerificationType, DomainVerifyResponse, DoorSegment, ErrorResponse, ErrorType, ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, Fetch, FileValidationResult, FileValidationStatus, FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, LabelsResponse, ListOptions, ListResponse, MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, PingResponse, Plan, PlanChangeRefusalDetails, PlanChangeRequest, PlanChangeResponse, PlanDestination, PlansResponse, PlatformLimitKey, PlatformLimits, RequestResult, ResourceContext, SECTIONS, SETUP_TROUBLESHOOTING_ANCHOR, SHIP_ENV, SHIP_VIA_ENV, SPACheckRequest, SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, ScheduledChange, SettingsFragment, SetupInstructionsResponse, ShipClientOptions, ShipError, ShipEvents, ShipRequestInit, StaticFile, TTL_CONSTRAINTS, Token, TokenCreateOptions, TokenCreateResponse, TokenDeleteResponse, TokenKind, TokenKindType, TokenListResponse, TokenProvider, TokenResource, Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, USAGE_KIND, USER_VISIBLE_EVENTS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, countPhrase, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, doorOf, doors, errandOf, excessOver, extractSubdomain, filterJunk, fitPhrase, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, placesTaken, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateLabel, validateLabels, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3943
3988
|
}
|
|
3944
3989
|
export = Ship;
|
package/dist/index.d.ts
CHANGED
|
@@ -72,7 +72,7 @@ declare const DeploymentVia: {
|
|
|
72
72
|
readonly GIT: "git";
|
|
73
73
|
/** The n8n community node. */
|
|
74
74
|
readonly N8N: "n8n";
|
|
75
|
-
/** Channel: the ChatGPT
|
|
75
|
+
/** Channel: the ChatGPT plugin → `mcp.<domain>/gpt`. */
|
|
76
76
|
readonly GPT: "gpt";
|
|
77
77
|
/** The VS Code extension. */
|
|
78
78
|
readonly VSC: "vsc";
|
|
@@ -116,7 +116,7 @@ interface Deployment {
|
|
|
116
116
|
readonly config: boolean;
|
|
117
117
|
/** Whether deployment has a password set */
|
|
118
118
|
readonly password: boolean;
|
|
119
|
-
/** Labels for categorization and filtering (
|
|
119
|
+
/** Labels for categorization and filtering (a word like `production`, or a key and a value like `env:production`). Always present, empty array when none. */
|
|
120
120
|
labels: string[];
|
|
121
121
|
/**
|
|
122
122
|
* The client/tool that created this deployment. Every deployment created
|
|
@@ -380,7 +380,7 @@ interface Domain {
|
|
|
380
380
|
verifications: number;
|
|
381
381
|
/** Unix timestamp (seconds) when plan enforcement paused serving, null while the plan has room for it */
|
|
382
382
|
paused: number | null;
|
|
383
|
-
/** Labels for categorization and filtering (
|
|
383
|
+
/** Labels for categorization and filtering (a word like `production`, or a key and a value like `env:production`). Always present, empty array when none. */
|
|
384
384
|
labels: string[];
|
|
385
385
|
/** Unix timestamp (seconds) when domain was created */
|
|
386
386
|
readonly created: number;
|
|
@@ -1150,9 +1150,9 @@ declare const API_PATHS: {
|
|
|
1150
1150
|
readonly UPLOAD: "/upload";
|
|
1151
1151
|
};
|
|
1152
1152
|
/**
|
|
1153
|
-
* The deploy request's multipart field names
|
|
1154
|
-
* surface beside {@link API_PATHS}.
|
|
1155
|
-
*
|
|
1153
|
+
* The deploy request's multipart field names: the other half of the wire
|
|
1154
|
+
* surface beside {@link API_PATHS}. These are the names the API reads from a
|
|
1155
|
+
* multipart body on `POST /deployments` and the first-party `/upload`.
|
|
1156
1156
|
*
|
|
1157
1157
|
* Declared once because the body has three independent WRITERS — the SDK's
|
|
1158
1158
|
* Node and browser body builders, and the n8n community node's hand-rolled
|
|
@@ -1199,10 +1199,10 @@ declare const DEPLOY_FIELDS: {
|
|
|
1199
1199
|
readonly CAPTCHA: "captcha";
|
|
1200
1200
|
};
|
|
1201
1201
|
/**
|
|
1202
|
-
* The JSON deploy body's file grammar: the OTHER body
|
|
1203
|
-
* beside the multipart one {@link DEPLOY_FIELDS} names. A JSON caller
|
|
1204
|
-
* `{ files: [{ path, content, encoding? }] }`, and this is the whole
|
|
1205
|
-
* one entry may say: three field names, two encodings, one default.
|
|
1202
|
+
* The JSON deploy body's file grammar: the OTHER body both deploy doors
|
|
1203
|
+
* accept, beside the multipart one {@link DEPLOY_FIELDS} names. A JSON caller
|
|
1204
|
+
* sends `{ files: [{ path, content, encoding? }] }`, and this is the whole
|
|
1205
|
+
* of what one entry may say: three field names, two encodings, one default.
|
|
1206
1206
|
*
|
|
1207
1207
|
* Declared once because the grammar has three independent holders that the
|
|
1208
1208
|
* wire forces to restate it: the API's zod schema (the original), the hosted
|
|
@@ -2898,28 +2898,73 @@ declare function generateDeploymentUrl(deployment: string): string;
|
|
|
2898
2898
|
*/
|
|
2899
2899
|
declare function generateDomainUrl(domain: string): string;
|
|
2900
2900
|
/**
|
|
2901
|
-
*
|
|
2902
|
-
*
|
|
2901
|
+
* A label is a short identifier attached to a deployment, a domain or a token.
|
|
2902
|
+
* It has one of two forms:
|
|
2903
|
+
*
|
|
2904
|
+
* - a word: `production`, `v1.2.3`, `us-east-1`
|
|
2905
|
+
* - a key and a value, split by one `:`: `env:production`, `team:web`
|
|
2906
|
+
*
|
|
2907
|
+
* Each side is lowercase letters and digits, with single `.`, `_` or `-`
|
|
2908
|
+
* between them. The whole label, the key and the `:` and the value together,
|
|
2909
|
+
* counts toward {@link LABEL_CONSTRAINTS.MAX_LENGTH}.
|
|
2910
|
+
*
|
|
2911
|
+
* The platform stores a label in lowercase and shows it as stored. It reads
|
|
2912
|
+
* nothing from a key or a value and changes no behaviour because of one: a
|
|
2913
|
+
* label describes a resource and lets its owner find it. So a resource may carry several
|
|
2914
|
+
* values for one key (`team:web` and `team:api`), and only the same label
|
|
2915
|
+
* twice is refused.
|
|
2916
|
+
*
|
|
2917
|
+
* Labels stay a list of strings on the wire and in storage. A caller that
|
|
2918
|
+
* wants a key's value splits on the `:` itself.
|
|
2903
2919
|
*/
|
|
2904
2920
|
declare const LABEL_CONSTRAINTS: {
|
|
2905
|
-
/** Minimum label length in characters */
|
|
2921
|
+
/** Minimum label length in characters. */
|
|
2906
2922
|
readonly MIN_LENGTH: 3;
|
|
2907
|
-
/**
|
|
2908
|
-
|
|
2909
|
-
|
|
2923
|
+
/**
|
|
2924
|
+
* Maximum label length in characters. A key, its `:` and its value share it,
|
|
2925
|
+
* and it fits a key with a UUID (36 characters) or a full git SHA (40).
|
|
2926
|
+
*/
|
|
2927
|
+
readonly MAX_LENGTH: 63;
|
|
2928
|
+
/** Maximum number of labels on one resource. */
|
|
2910
2929
|
readonly MAX_COUNT: 10;
|
|
2911
|
-
/** Allowed separator characters between label segments */
|
|
2912
|
-
readonly SEPARATORS: "._-";
|
|
2913
2930
|
};
|
|
2914
2931
|
/**
|
|
2915
|
-
*
|
|
2916
|
-
*
|
|
2917
|
-
*
|
|
2932
|
+
* The shape of a label: one side, or two with a `:` between them. A side is
|
|
2933
|
+
* lowercase letters and digits with single `.`, `_` or `-` between them, and
|
|
2934
|
+
* the pattern spells it twice. Length is {@link LABEL_CONSTRAINTS}' rule, and
|
|
2935
|
+
* {@link validateLabel} applies both.
|
|
2918
2936
|
*
|
|
2919
|
-
*
|
|
2920
|
-
*
|
|
2937
|
+
* Matches: `production`, `v1.2.3`, `env:production`, `commit:3f9c2ab`
|
|
2938
|
+
* Refuses: `-prod`, `foo--bar`, `:production`, `env:`, `a:b:c`, `Env:Prod`
|
|
2921
2939
|
*/
|
|
2922
2940
|
declare const LABEL_PATTERN: RegExp;
|
|
2941
|
+
/**
|
|
2942
|
+
* Validate one label and return it normalized: trimmed and lowercased, then
|
|
2943
|
+
* held to {@link LABEL_CONSTRAINTS}' length and to {@link LABEL_PATTERN}.
|
|
2944
|
+
* Throws `ShipError.validation` when it does not fit.
|
|
2945
|
+
*
|
|
2946
|
+
* Lowercasing is the one normalization and it applies to both sides of a
|
|
2947
|
+
* `:`, so `Env:Prod` is stored as `env:prod`. A value that must keep its
|
|
2948
|
+
* case does not belong in a label.
|
|
2949
|
+
*
|
|
2950
|
+
* The one label check on the platform: the SDK and the console call it for
|
|
2951
|
+
* fast feedback and the API calls it as the boundary, so all three refuse
|
|
2952
|
+
* the same strings in the same words.
|
|
2953
|
+
*/
|
|
2954
|
+
declare function validateLabel(value: unknown): string;
|
|
2955
|
+
/**
|
|
2956
|
+
* Validate a resource's labels and return them normalized, each through
|
|
2957
|
+
* {@link validateLabel}. Absent (`undefined` / `null`) returns `undefined`;
|
|
2958
|
+
* an empty array returns as is, which is how an update clears every label.
|
|
2959
|
+
* At most {@link LABEL_CONSTRAINTS.MAX_COUNT}, and no label twice after
|
|
2960
|
+
* normalization.
|
|
2961
|
+
*
|
|
2962
|
+
* It takes any value, like the other checks here, because two callers hand it
|
|
2963
|
+
* one the compiler has not seen: the API's multipart door (a parsed JSON
|
|
2964
|
+
* field) and an SDK caller without TypeScript.
|
|
2965
|
+
*/
|
|
2966
|
+
declare function validateLabels(labels: string[]): string[];
|
|
2967
|
+
declare function validateLabels(labels: unknown): string[] | undefined;
|
|
2923
2968
|
/**
|
|
2924
2969
|
* Serialize labels array to JSON string for database storage.
|
|
2925
2970
|
* Returns null for empty or undefined arrays.
|
|
@@ -3040,8 +3085,8 @@ type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
|
3040
3085
|
*/
|
|
3041
3086
|
interface DeployBodyContext {
|
|
3042
3087
|
/**
|
|
3043
|
-
* Deployment labels
|
|
3044
|
-
* `
|
|
3088
|
+
* Deployment labels, each a word (`production`) or a key and a value
|
|
3089
|
+
* (`env:production`), already through `validateLabels`.
|
|
3045
3090
|
*/
|
|
3046
3091
|
labels?: string[];
|
|
3047
3092
|
/**
|
|
@@ -3938,4 +3983,4 @@ declare class Ship extends Ship$1 {
|
|
|
3938
3983
|
protected processInput(input: DeployInput, options: DeploymentOptions, limits: PlatformLimits): Promise<StaticFile[]>;
|
|
3939
3984
|
}
|
|
3940
3985
|
|
|
3941
|
-
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, type Account, type AccountAccess, type AccountDeleteResponse, type AccountKeyResponse, AccountPlan, type AccountPlanType, AccountRefusal, type AccountRefusalType, type AccountResource, type AccountRole, type AccountUsage, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BUILD_SETTINGS, type BillingInterval, type BillingPortalSession, type BillingSyncResponse, type BuildFailureDetails, CALLER, type Caps, type ConsoleErrand, type ConsolePaths, type ConsoleSection, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, type DeployBodyContext, type DeployFile, type DeployFileEncoding, type DeployFileSpec, type DeployInput, type DeployTransport, type Deployment, type DeploymentCreateResponse, type DeploymentDeleteResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, type DeploymentSetOptions, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, DeploymentVia, type DeploymentViaType, type DnsLookup, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDeleteResponse, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetOptions, type DomainSetResult, type DomainShareResponse, DomainStatus, type DomainStatusType, type DomainValidateResponse, DomainVerification, type DomainVerificationType, type DomainVerifyResponse, type DoorSegment, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type LabelsResponse, type ListOptions, type ListResponse, type MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, type PingResponse, type Plan, type PlanChangeRefusalDetails, type PlanChangeRequest, type PlanChangeResponse, type PlanDestination, type PlansResponse, type PlatformLimitKey, type PlatformLimits, type RequestResult, type ResourceContext, SECTIONS, SETUP_TROUBLESHOOTING_ANCHOR, SHIP_ENV, SHIP_VIA_ENV, type SPACheckRequest, type SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, type ScheduledChange, type SettingsFragment, type SetupInstructionsResponse, Ship, type ShipClientOptions, ShipError, type ShipEvents, type ShipRequestInit, type StaticFile, TTL_CONSTRAINTS, type Token, type TokenCreateOptions, type TokenCreateResponse, type TokenDeleteResponse, TokenKind, type TokenKindType, type TokenListResponse, type TokenProvider, type TokenResource, type Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, USAGE_KIND, USER_VISIBLE_EVENTS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, countPhrase, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, doorOf, doors, errandOf, excessOver, extractSubdomain, filterJunk, fitPhrase, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, placesTaken, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3986
|
+
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, type Account, type AccountAccess, type AccountDeleteResponse, type AccountKeyResponse, AccountPlan, type AccountPlanType, AccountRefusal, type AccountRefusalType, type AccountResource, type AccountRole, type AccountUsage, type Activity, type ActivityEvent, type ActivityListResponse, type ActivityMeta, type ApiDeployOptions, ApiHttp, type ApiHttpOptions, AuthMethod, type AuthMethodType, BUILD_SETTINGS, type BillingInterval, type BillingPortalSession, type BillingSyncResponse, type BuildFailureDetails, CALLER, type Caps, type ConsoleErrand, type ConsolePaths, type ConsoleSection, DEFAULT_API, DEPLOYMENT_CONFIG_FILENAME, DEPLOY_FIELDS, DEPLOY_FILE_GRAMMAR, DEPLOY_TOKEN, type DeployBodyContext, type DeployFile, type DeployFileEncoding, type DeployFileSpec, type DeployInput, type DeployTransport, type Deployment, type DeploymentCreateResponse, type DeploymentDeleteResponse, type DeploymentListResponse, type DeploymentOptions, type DeploymentResource, type DeploymentResourceContext, type DeploymentSetOptions, DeploymentStatus, type DeploymentStatusType, type DeploymentUploadOptions, DeploymentVia, type DeploymentViaType, type DnsLookup, type DnsProvider, type DnsRecord, type DnsRecordType, type Domain, type DomainDeleteResponse, type DomainDnsResponse, type DomainListResponse, type DomainRecordsResponse, type DomainResource, type DomainSetOptions, type DomainSetResult, type DomainShareResponse, DomainStatus, type DomainStatusType, type DomainValidateResponse, DomainVerification, type DomainVerificationType, type DomainVerifyResponse, type DoorSegment, type ErrorResponse, ErrorType, type ExecutionEnvironment, FileValidationStatus as FILE_VALIDATION_STATUS, type Fetch, type FileValidationResult, FileValidationStatus, type FileValidationStatusType, IDEMPOTENCY_KEY_CONSTRAINTS, JUNK_DIRECTORIES, LABEL_CONSTRAINTS, LABEL_PATTERN, type LabelsResponse, type ListOptions, type ListResponse, type MD5Result, MY_API_KEY_URL, OAUTH_TOKEN, OAuthScope, type OAuthScopeType, PASSWORD_CONSTRAINTS, PUBLIC_DEPLOYMENT_TTL_SECONDS, type PingResponse, type Plan, type PlanChangeRefusalDetails, type PlanChangeRequest, type PlanChangeResponse, type PlanDestination, type PlansResponse, type PlatformLimitKey, type PlatformLimits, type RequestResult, type ResourceContext, SECTIONS, SETUP_TROUBLESHOOTING_ANCHOR, SHIP_ENV, SHIP_VIA_ENV, type SPACheckRequest, type SPACheckResponse, SPA_CHECK_CONSTRAINTS, SPA_DEFAULT_CONFIG, type ScheduledChange, type SettingsFragment, type SetupInstructionsResponse, Ship, type ShipClientOptions, ShipError, type ShipEvents, type ShipRequestInit, type StaticFile, TTL_CONSTRAINTS, type Token, type TokenCreateOptions, type TokenCreateResponse, type TokenDeleteResponse, TokenKind, type TokenKindType, type TokenListResponse, type TokenProvider, type TokenResource, type Transport, UNBUILT_PROJECT_MARKERS, UNSAFE_FILENAME_CHARS, USAGE_KIND, USER_VISIBLE_EVENTS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, countPhrase, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, doorOf, doors, errandOf, excessOver, extractSubdomain, filterJunk, fitPhrase, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, placesTaken, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateLabel, validateLabels, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ct=Object.defineProperty;var S=(e,t)=>()=>(e&&(t=e(e=0)),t);var ut=(e,t)=>{for(var n in t)ct(e,n,{get:t[n],enumerable:!0})};function mn(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(pt).includes(t)?t:void 0}function Re(e){if(e==null)return;if(typeof e!="string")throw a.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw a.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function dt(e){return e.members+e.invitations}function hn(e,t){let n=Math.max(0,dt(e)-t.members),r=Math.max(0,e.members-t.members),o={members:r,invitations:n-r,customDomains:e.customDomains-t.customDomains,platformDomains:e.platformDomains-t.platformDomains};return Object.fromEntries(Object.entries(o).filter(([,i])=>i>0))}function mt(e){return Ne(["members","customDomains","platformDomains"].filter(t=>(e[t]??0)>0).map(t=>Ie(t,e[t]??0)))}function yn(e){let t=mt(e),n=e.invitations??0;return Ne([...t?[`remove ${t}`]:[],...n>0?[`cancel ${Ie("invitations",n)}`]:[]])}function gn(e){return e.name?.trim()||e.email}function Tn(e){return e.name?.trim().split(" ")[0]||e.email}function Et(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function M(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function gt(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function Le(e,t){let n=gt(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function be(e){return St.test(e)}function U(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>te.has(n))}function Dt(e){return e.startsWith(Oe.PREFIX)?R.API_KEY:e.startsWith(xe.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(Pe.PREFIX)?R.OAUTH:R.OPAQUE}function In(e){return e.slice(0,Q.length).toLowerCase()!==Q?null:e.slice(Q.length)||null}function we(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw a.config(`invalid JSON format in config: ${r.message}`,{filePath:D})}if(n===null||typeof n!="object"||Array.isArray(n))throw a.config(`${D} must contain a JSON object`,{filePath:D})}function ne(e,t,n){if(!e.startsWith(t.PREFIX))throw a.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw a.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw a.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function At(e){ne(e,Oe,"API key")}function Rt(e){ne(e,xe,"Deploy token")}function It(e){ne(e,Pe,"OAuth access token")}function re(e){switch(Dt(e)){case R.API_KEY:At(e);return;case R.DEPLOY_TOKEN:Rt(e);return;case R.OAUTH:It(e);return;case R.OPAQUE:if(!e)throw a.validation("Token must be a non-empty string")}}function ve(e){if(!e||e.length>O.MAX_LENGTH||!O.PATTERN.test(e))throw a.validation(`Caller must be 1-${O.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ln(e){try{let t=new URL(e);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 M(t)?t:a.validation("API URL must be a valid URL")}}function bn(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function oe(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw a.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw a.validation("TTL must be a whole number of seconds");if(e<C.MIN_SECONDS||e>C.MAX_SECONDS)throw a.validation(`TTL must be between ${C.MIN_SECONDS} and ${C.MAX_SECONDS} seconds`);return e}}function Ot(e){let t=e?`/${e}`:"",n=r=>`${t}${r}`;return{dashboard:()=>t||"/",newSite:()=>n("/new"),deployments:Object.assign(()=>n("/deployments"),{upload:()=>n("/deployments/upload")}),domains:Object.assign(()=>n("/domains"),{connect:r=>n(`/domains/${r}/connect`),deployment:r=>n(`/domains/${r}/deployment`)}),settings:r=>n(r?`/settings#${r}`:"/settings"),claim:r=>n(`/claim/${r}`),settingsAfterBilling:()=>n(`/settings?${De("portal")}`),upgrade:r=>n(r?`/upgrade/${r}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${De("checkout")}`),apiKey:()=>n("/api-key")}}function xn(e){let t=new URLSearchParams(e);for(let[n,[r,o]]of Object.entries(Ce))if(t.get(r)===o)return n;return null}function $(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",r=""]=t.split("/").filter(Boolean);return xt(n)?{kind:"door",door:n}:n===bt?{kind:"admin"}:n===""||Ae(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:Ae(r)?r:null}}function Pn(e){let t=$(e);return t.kind==="account"?t.account:null}function Pt(e){let t=$(e);return t.kind==="door"?t.door:null}function _n(e){return _t(e)?"claim":Pt(e)==="invitation"?"invite":wt(e)?"upgrade":null}function vt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return ee(t,"minute");let n=Math.round(e/3600);return n<48?ee(n,"hour"):ee(Math.round(e/86400),"day")}function Fn(e,t=Date.now()/1e3){let n=e-t;return n>0?vt(n):null}function ee(e,t){return`${e} ${t}${e===1?"":"s"}`}function _(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**o).toFixed(t))} ${r[o]}`}function Fe(e,t){return e.endsWith(`.${t}`)}function Un(e,t){return!Fe(e,t)}function kn(e,t){return Fe(e,t)?e.slice(0,-(t.length+1)):null}function $n(e){return`https://${e}`}function Hn(e){return`https://${e}`}function Gn(e){return!e||e.length===0?null:JSON.stringify(e)}function Bn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Ue(e){if(e==null||e==="")return;if(typeof e!="string")throw a.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>x.COMMAND_MAX_LENGTH)throw a.validation(`Build command must be between 1 and ${x.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw a.validation("Build command must be a single line");return t}function ke(e){if(e==null||e==="")return;if(typeof e!="string")throw a.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>x.OUTPUT_DIR_MAX_LENGTH)throw a.validation(`Output folder must be between 1 and ${x.OUTPUT_DIR_MAX_LENGTH} characters`);if(!x.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw a.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function se(e){if(e==null)return;if(typeof e!="string")throw a.validation("Password must be a string");let t=e.trim();if(t.length<F.MIN_LENGTH||t.length>F.MAX_LENGTH)throw a.validation(`Password must be between ${F.MIN_LENGTH} and ${F.MAX_LENGTH} characters`);return t}var cn,pt,un,pn,dn,N,fn,Se,Ie,Ne,En,m,E,Sn,d,ft,W,ht,yt,a,Tt,Dn,St,te,An,J,Oe,xe,Pe,O,Rn,R,Q,Nn,D,_e,k,C,Nt,Lt,bt,Ce,De,Z,On,xt,Ae,_t,wt,ie,P,wn,vn,Cn,Mn,h,I,Me,x,F,f=S(()=>{"use strict";cn={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},pt={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},un={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},pn={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},dn="troubleshooting",N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};fn={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"};Se={deployments:{one:"deployment",many:"deployments"},platformDomains:{one:"ShipStatic domain",many:"ShipStatic domains"},customDomains:{one:"custom domain",many:"custom domains"},members:{one:"member",many:"members"},invitations:{one:"invitation",many:"invitations"}};Ie=(e,t)=>`${t} ${t===1?Se[e].one:Se[e].many}`,Ne=e=>e.length>1?`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`:e[0]??"",En={PAUSED:"paused",UNKNOWN:"unknown"};m={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},Sn={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},ft=new Set([d.Network,d.Timeout,d.Cancelled,d.File,d.Config]),W={client:new Set([d.Build,d.Business,d.Cancelled,d.Config,d.File,d.Forbidden,d.NotFound,d.RateLimit,d.Validation]),network:new Set([d.Network,d.Timeout]),auth:new Set([d.Authentication])},ht=new Set(Object.values(d).filter(e=>!ft.has(e))),yt=200;a=class e extends Error{type;status;details;constructor(t,n,r,o){super(n),this.type=t,this.status=r,this.details=o,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,o,i;try{if(t.headers.get("content-type")?.includes("application/json")){let p=await t.json();if(p&&typeof p=="object"){let c=p;typeof c.message=="string"?r=c.message:typeof c.error=="string"&&(r=c.error),o=c.details,typeof c.error=="string"&&ht.has(c.error)&&(i=c.error)}}else{let p=(await t.text()).trim();p&&!p.startsWith("<")&&p.length<=yt&&(r=p)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let s=l.trim(),p=/^\d+$/.test(s)?Number(s):Math.ceil((Date.parse(s)-Date.now())/1e3);if(Number.isFinite(p)&&p>=0){let c=o&&typeof o=="object"?o:{};c.retryAfter===void 0&&(o={...c,retryAfter:p})}}r=r||`${n||"Request"} failed with status ${t.status}`;let u=i??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new e(u,r,t.status,o)}static fromFetchError(t,n){if(M(t))return t;let r=n||"Request",o=t?.name;return o==="AbortError"?e.cancelled(`${r} was cancelled`):o==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?Et(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(d.Api,`${r} failed: ${t.message}`):new e(d.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(d.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(d.NotFound,r,404)}static forbidden(t,n){return new e(d.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(d.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(d.Authentication,t,401,n)}static business(t,n=400,r){return new e(d.Business,t,n,r)}static network(t,n){return new e(d.Network,t,void 0,n)}static timeout(t,n){return new e(d.Timeout,t,void 0,n)}static cancelled(t,n){return new e(d.Cancelled,t,void 0,n)}static file(t,n){return new e(d.File,t,void 0,n)}static config(t,n){return new e(d.Config,t,void 0,n)}static api(t,n=500,r){return new e(d.Api,t,n,r)}static maintenance(t,n){return new e(d.Maintenance,t,503,n)}static build(t,n){return new e(d.Build,t,422,n)}isClientError(){return W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};Tt=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],Dn=Tt.map(e=>`.${e}`).join(","),St=/[\x00-\x1f\x7f#?%\\<>"]/;te=new Set(["node_modules","package.json"]);An="/auth",J={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Oe={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},xe={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},Pe={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},O={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},Rn="X-Account",R={API_KEY:J.API_KEY,DEPLOY_TOKEN:J.TOKEN,OAUTH:J.OAUTH,OPAQUE:"opaque"};Q="bearer ";Nn={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},D="ship.json",_e={rewrites:[{source:"/(.*)",destination:"/index.html"}]},k={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};C={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};Nt={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},claim:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},Lt=["login","register","logout","invitation","consent"],bt="admin",Ce={checkout:["upgrading","true"],portal:["billing","returned"]},De=e=>Ce[e].join("="),Z=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;On={login:({token:e,next:t}={})=>Z(e?`/login/${e}`:"/login",t),register:({next:e}={})=>Z("/register",e),logout:({next:e}={})=>Z("/logout",e),invitation:e=>`/invitation/${e}`,consent:()=>"/consent"};xt=e=>Lt.includes(e),Ae=e=>Object.hasOwn(Nt,e);_t=e=>{let t=$(e);return t.kind==="account"&&t.section==="claim"},wt=e=>{let t=$(e);return t.kind==="account"&&t.section==="upgrade"};ie="https://api.shipstatic.com",P={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},wn="SHIP_VIA",vn=`https://my.shipstatic.com${Ot().apiKey()}`,Cn=4320*60;Mn=["account.create","account.update","account.delete","account.key.generate","account.plan.transition","deployment.create","deployment.update","deployment.delete","deployment.claim","domain.create","domain.update","domain.delete","domain.verify","token.create","token.consume","token.delete","member.join","member.leave","consent.grant"],h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Me=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;x={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};F={MIN_LENGTH:6,MAX_LENGTH:128}});async function Bt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let o=0;o<e.size;o+=r){let i=Math.min(o+r,e.size);n.append(await e.slice(o,i).arrayBuffer())}return{md5:n.end()}}async function zt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Vt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,o)=>{let i=t("md5"),l=n(e);l.on("error",u=>o(a.file(`Failed to read file for MD5: ${u.message}`,{filePath:e}))),l.on("data",u=>i.update(u)),l.on("end",()=>r({md5:i.digest("hex")}))})}async function B(e){if(e instanceof Blob)return Bt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return zt(e);if(typeof e=="string")return Vt(e);throw a.business("Invalid input for MD5 calculation")}var z=S(()=>{"use strict";f()});function mr(e){le=e}function Xt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return le||Xt()}var le,v=S(()=>{"use strict";le=null});function Je(e){if(!e||e.length===0)return"";let t=e.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(i=>i.split("/").filter(Boolean)),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o;i++){let l=n[0][i];if(n.every(u=>u[i]===l))r.push(l);else break}return r.join("/")}function j(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ce=S(()=>{"use strict"});function Qe(e,t={}){if(t.flatten===!1)return e.map(r=>({path:j(r),name:ue(r)}));let n=Jt(e);return e.map(r=>{let o=j(r);if(n){let i=n.endsWith("/")?n:`${n}/`;o.startsWith(i)&&(o=o.substring(i.length))}return o||(o=ue(r)),{path:o,name:ue(r)}})}function Jt(e){if(!e.length)return"";let n=e.map(i=>j(i)).map(i=>i.split("/")),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o-1;i++){let l=n[0][i];if(n.every(u=>u[i]===l))r.push(l);else break}return r.join("/")}function ue(e){return e.split(/[/\\]/).pop()||e}var pe=S(()=>{"use strict";ce()});function de(e,t,n){let r=t.suggestions?.[n];return r?`${e} ${r}`:e}function q(e,t){return Qt.find(n=>n.broken(e,t))}var Qt,b,fe=S(()=>{"use strict";f();he();Qt=[{name:"name",broken:({path:e})=>!me(e).valid,sentence:({path:e})=>me(e).reason??`File name "${e}" is invalid.`},{name:"extension",broken:({path:e},t)=>Le(e,t.blockedExtensions??[]),sentence:({path:e})=>`File "${e}" has an extension that is not allowed.`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>de(`File "${e}" is too large. Maximum ${_(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>de(`Files add up to ${_(e)}. Maximum ${_(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],b={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>de(`Too many files (${e}). Maximum ${t.maxFilesCount} files allowed.`,t,"maxFilesCount")}});function me(e){let t=o=>({valid:!1,reason:`File name "${e}" ${o}.`});if(be(e))return t("contains unsafe characters");if(e.startsWith(" ")||e.endsWith(" "))return t("cannot start or end with spaces");if(e.endsWith("."))return t("cannot end with dots");let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,r=e.split("/").pop()||e;return n.test(r)?t("uses a reserved system name"):e.includes("..")?t("contains a path traversal pattern"):{valid:!0}}function wr(e,t){let n=[],r=[],o=[];if(e.length===0){let s={file:"(no files)",message:"At least one file must be provided."};return n.push(s),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let s of e)if(U(s.name))return n.push({file:s.name,message:"Unbuilt project detected. Deploy your build output (dist/, build/, out/), not the project folder."}),{files:e.map(p=>({...p,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(b.broken(e.length,t)){let s={file:`(${e.length} files)`,message:b.sentence(e.length,t)};return n.push(s),{files:e.map(p=>({...p,status:h.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let i=0;for(let s of e){let p=h.READY,c="Ready for upload";if(s.status===h.PROCESSING_ERROR)p=h.VALIDATION_FAILED,c=s.statusMessage||`File "${s.name}" could not be read.`,n.push({file:s.name,message:c});else if(s.size===0){p=h.EXCLUDED,c=`File "${s.name}" is empty, so it is excluded.`,r.push({file:s.name,message:c}),o.push({...s,status:p,statusMessage:c});continue}else if(s.size<0)p=h.VALIDATION_FAILED,c=`File "${s.name}" reports a negative size.`,n.push({file:s.name,message:c});else if(!s.name||s.name.trim().length===0)p=h.VALIDATION_FAILED,c="File name cannot be empty.",n.push({file:s.name||"(empty)",message:c});else if(s.name.includes("\0"))p=h.VALIDATION_FAILED,c=`File name "${s.name}" contains invalid characters (null byte).`,n.push({file:s.name,message:c});else{let y={path:s.name,size:s.size,totalSize:i+s.size},A=q(y,t);A?(p=h.VALIDATION_FAILED,c=A.sentence(y,t),n.push({file:A.name==="totalSize"?`(${e.length} files)`:s.name,message:c})):i=y.totalSize}o.push({...s,status:p,statusMessage:c})}n.length>0&&(o=o.map(s=>s.status===h.EXCLUDED?s:{...s,status:h.VALIDATION_FAILED,statusMessage:s.status===h.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?o.filter(s=>s.status===h.READY):[],u=n.length===0;return{files:o,validFiles:l,errors:n,warnings:r,canDeploy:u}}function Zt(e){return e.filter(t=>t.status===h.READY)}function vr(e){return Zt(e).length>0}var he=S(()=>{"use strict";f();fe();f()});import{isJunk as en}from"junk";function Ze(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&U(r)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let o=r[r.length-1];if(en(o))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let i=r.slice(0,-1);for(let l of i)if(tn.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var tn,ye=S(()=>{"use strict";f();tn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function et(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function tt(e,t){let n=q(e,t);if(n)throw a.business(n.sentence(e,t))}function nt(e,t){if(b.broken(e,t))throw a.business(b.sentence(e,t))}var Ee=S(()=>{"use strict";f();fe()});async function rt(e,t={},n){let r=!!(t.build||t.prerender),o=Qe(e.map(c=>c.path),{flatten:t.pathDetect!==!1}).map(c=>c.path),i=new Set(Ze(o,{allowUnbuilt:r})),l=e.map((c,y)=>({source:c,deployPath:o[y]})).filter(({deployPath:c})=>i.has(c));if(l.length===0)return[];let u=r?null:nn(n),s=[],p=0;for(let{source:c,deployPath:y}of l){if(u&&et(y,c.origin),c.size===0)continue;u&&(p+=c.size,tt({path:y,size:c.size,totalSize:p},u));let A=await c.read(),{md5:X}=await B(A);s.push({path:y,content:A,size:c.size,md5:X})}return u&&nt(s.length,u),s}function nn(e){if(!e)throw a.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var ot=S(()=>{"use strict";f();pe();ye();z();Ee()});var at={};ut(at,{processFilesForNode:()=>st});import*as T from"fs";import*as g from"path";function it(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let o of T.readdirSync(e)){let i=g.join(e,o),l=T.statSync(i);l.isDirectory()?n.push(...it(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function rn(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw a.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function on(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(o=>te.has(o));if(r)throw a.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(M(r))throw r}}}async function st(e,t={},n){if(L()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");on(e);let r=e.flatMap(u=>{let s=g.resolve(u);try{let p=T.statSync(s);return p.isDirectory()?it(s):[{absPath:s,size:p.size}]}catch{throw a.file(`Path does not exist: ${u}`,{filePath:u})}}),o=new Map(r.map(u=>[u.absPath,u.size])),i=Je(e.map(u=>g.resolve(u)).map(u=>{try{return T.statSync(u).isDirectory()?u:g.dirname(u)}catch{return g.dirname(u)}})),l=[...o].map(([u,s])=>({path:sn(u,i),origin:u,size:s,read:()=>rn(u)}));return rt(l,t,n)}function sn(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var ge=S(()=>{"use strict";f();ot();v();ce()});f();f();f();var H=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let o=Array.from(r);for(let i of o)try{i(...n)}catch(l){r.delete(i),t!=="error"&&setTimeout(()=>{let u=l instanceof Error?l:new Error(String(l));this.emit("error",u,String(t))},0)}}};var Ct=3e4,Ft=2,Mt=300,Ut=2e3,kt=new Set([500,502,503,504]);function $t(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let o=()=>{clearTimeout(l),t?.removeEventListener("abort",i)},i=()=>{o(),r(t?.reason)},l=setTimeout(()=>{o(),n()},e);t?.addEventListener("abort",i)})}var $e=3e5,Ht=3e5,Gt=$e+Ht,G=class extends H{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ie,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Ct,this.maxRetries=Math.max(0,n.maxRetries??Ft),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??$e,buildTimeout:n.timeout??Gt}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,o,i=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,o,i)}catch(u){let s=a.fromFetchError(u,o);if(l>=this.maxRetries||!this.isRetryable(s,r))throw this.emit("error",s,n),s;this.emit("retry",s,n,l+1);let p=Math.min(Ut,Mt*2**l);try{await $t(Math.random()*p,r.signal)}catch(c){let y=a.fromFetchError(c,o);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&kt.has(n.status)))return!1;let i=(r.method??"GET").toUpperCase();return i==="GET"||i==="HEAD"?!0:i==="PUT"||i==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(o=>o.toLowerCase()===r)}async attemptOnce(n,r,o,i=this.timeout){let l=()=>{};try{let u=await this.mergeHeaders(r.headers),s=this.createTimeoutSignal(r.signal,i);l=s.cleanup;let p={...r,headers:u,credentials:this.session&&!u.Authorization?"include":void 0,signal:s.signal};this.emit("request",n,p);let c=await this.fetch(n,p);if(l(),!c.ok)throw await a.fromHttpResponse(c,o);return this.emit("response",this.safeClone(c),n),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(u){throw l(),a.fromFetchError(u,o)}}async request(n,r,o,i){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,o,i);return l}async requestWithStatus(n,r,o){return this.executeRequest(`${this.apiUrl}${n}`,r,o)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[O.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let o=new AbortController,i=setTimeout(()=>o.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>o.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&o.abort(n.reason)),{signal:o.signal,cleanup:()=>{clearTimeout(i),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function He(e,t={}){let{labels:n,via:r,password:o,ttl:i,flags:l,captcha:u}=t,s=new FormData,p=[];for(let c of e){if(typeof c.content=="string"||c.content===null||c.content===void 0)throw a.file(`Unsupported file.content type: ${c.path}`,{filePath:c.path});if(!c.md5)throw a.file(`File missing md5 checksum: ${c.path}`,{filePath:c.path});s.append(E.FILES,new File([c.content],c.path,{type:"application/octet-stream"})),p.push(c.md5)}return s.append(E.CHECKSUMS,JSON.stringify(p)),n&&n.length>0&&s.append(E.LABELS,JSON.stringify(n)),r&&s.append(E.VIA,r),o&&s.append(E.PASSWORD,o),i!==void 0&&s.append(E.TTL,String(i)),l?.build&&s.append(E.BUILD,"true"),l?.prerender&&s.append(E.PRERENDER,"true"),l?.spa&&s.append(E.SPA,"true"),l?.buildCommand&&s.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&s.append(E.OUTPUT_DIR,l.outputDir),u&&s.append(E.CAPTCHA,u),s}f();z();async function Kt(){let e=JSON.stringify(_e,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await B(t);return{path:D,content:t,size:e.length,md5:n}}async function jt(e,t,n){let r=e.find(u=>u.path===k.INDEX_FILE||u.path===`/${k.INDEX_FILE}`);if(!r||r.size>k.MAX_INDEX_BYTES)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))o=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)o=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)o=await r.content.text();else return!1;let i={files:e.map(u=>u.path),index:o};return(await t.request(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:n??null},"SPA check")).isSPA}async function Ge(e,t,n){return n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===D)?e:await jt(e,t,n.signal)?[...e,await Kt()]:e}f();f();function w(e){if(e==null)return;if(e.length===0)return e;if(e.length>I.MAX_COUNT)throw a.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=e.map((r,o)=>{if(typeof r!="string")throw a.validation(`Label at index ${o} must be a string`);let i=r.trim().toLowerCase();if(i.length<I.MIN_LENGTH)throw a.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(i.length>I.MAX_LENGTH)throw a.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!Me.test(i))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${I.SEPARATORS}) between segments`);return i}),n=[...new Set(t)];if(n.length!==t.length)throw a.validation("Duplicate labels are not allowed");return n}async function Be(e){let t=e.find(o=>o.path===D||o.path===`/${D}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");we(r)}var V={"Content-Type":"application/json"},qt="sdk";function ae(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function ze(e){let{getApi:t,processInput:n}=e;return{upload:async(r,o={})=>{if(!n)throw a.config("processInput function is not provided.");let i=t(),l=await n(r,o),u=await Ge(l,i,o);if(!u.length)throw a.business("No files to deploy");for(let Y of u)if(!Y.md5)throw a.file(`MD5 checksum missing for file: ${Y.path}`,{filePath:Y.path});se(o.password);let s=oe(o.ttl),p=Re(o.idempotencyKey),c=w(o.labels);await Be(u);let y=Ue(o.buildCommand),A=ke(o.outputDir),X=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa,buildCommand:y,outputDir:A}:void 0,lt=await He(u,{labels:c,via:o.via??qt,password:o.password,ttl:s,flags:X,captcha:o.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:lt,...p?{headers:{[N.HEADER]:p}}:{},signal:o.signal||null},"Deploy",o.build||o.prerender?i.deploy.buildTimeout:i.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${ae(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,o)=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:V,body:JSON.stringify({labels:w(o.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function Ve(e){let{getApi:t}=e;return{set:async(n,r={})=>{let o=w(r.labels),i={};r.deployment&&(i.deployment=r.deployment),o!==void 0&&(i.labels=o);let{data:l,status:u}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:V,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:u===201}},list:async n=>t().request(`${m.DOMAINS}${ae(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(m.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(m.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(m.DOMAINS_VALIDATE,{method:"POST",headers:V,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(m.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(m.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(m.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Ke(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function je(e){let{getApi:t}=e;return{create:async(n={})=>{let r=oe(n.ttl),o=w(n.labels),i={};return r!==void 0&&(i.ttl=r),o!==void 0&&(i.labels=o),t().request(m.TOKENS,{method:"POST",headers:V,body:JSON.stringify(i)},"Create token")},list:async n=>t().request(`${m.TOKENS}${ae(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(m.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var K=class{constructor(t={}){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&&ve(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(re(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new G({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=ze({...n,processInput:async(r,o)=>this.processInput(r,o,await this.getLimits({signal:o.signal}))}),this.domains=Ve(n),this.account=Ke(n),this.tokens=je(n)}async ping(){return this.http.request(m.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(t={}){return this.http.request(m.LIMITS,{method:"GET",signal:t.signal??null},"Get limits")}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}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.");re(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}`}}};v();f();import{z as Ye}from"zod";import{z as qe}from"zod";var Xe={apiUrl:qe.string().url().optional(),token:qe.string().min(1).optional()};v();var Yt=Ye.object(Xe).strict(),Wt={apiUrl:P.API_URL,token:P.TOKEN};function We(){if(L()!=="node")return{};let e={apiUrl:process.env[P.API_URL]||void 0,token:process.env[P.TOKEN]||void 0};try{return Yt.parse(e)}catch(t){if(t instanceof Ye.ZodError){let n=t.issues[0],r=n.path[0],o=(r&&Wt[r])??"SHIP environment configuration";throw a.config(`Invalid ${o}: ${n.message}`)}throw a.config("Invalid environment configuration")}}f();f();pe();v();he();ye();z();Ee();function Br(e,t,n,r=!0){let o=e===1?t:n;return r?`${e} ${o}`:o}ge();var Te=class extends K{constructor(t={}){if(L()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let n=We();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n,r){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(l=>typeof l=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw a.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(ge(),at));return i(o,n,r)}},an=Te;export{Rn as ACCOUNT_HEADER,Oe as API_KEY,m as API_PATHS,An as AUTH_BASE_PATH,fn as AccountPlan,En as AccountRefusal,G as ApiHttp,J as AuthMethod,x as BUILD_SETTINGS,O as CALLER,ie as DEFAULT_API,D as DEPLOYMENT_CONFIG_FILENAME,E as DEPLOY_FIELDS,Sn as DEPLOY_FILE_GRAMMAR,xe as DEPLOY_TOKEN,cn as DeploymentStatus,pt as DeploymentVia,un as DomainStatus,pn as DomainVerification,d as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,tn as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,Me as LABEL_PATTERN,vn as MY_API_KEY_URL,Pe as OAUTH_TOKEN,Nn as OAuthScope,F as PASSWORD_CONSTRAINTS,Cn as PUBLIC_DEPLOYMENT_TTL_SECONDS,Nt as SECTIONS,dn as SETUP_TROUBLESHOOTING_ANCHOR,P as SHIP_ENV,wn as SHIP_VIA_ENV,k as SPA_CHECK_CONSTRAINTS,_e as SPA_DEFAULT_CONFIG,Te as Ship,a as ShipError,C as TTL_CONSTRAINTS,R as TokenKind,te as UNBUILT_PROJECT_MARKERS,St as UNSAFE_FILENAME_CHARS,Se as USAGE_KIND,Mn as USER_VISIBLE_EVENTS,Dn as WEB_FILE_ACCEPT,mr as __setTestEnvironment,Pn as accountOfPath,vr as allValidFilesReady,we as assertShipJsonSyntax,xn as billingReturnOf,B as calculateMD5,Dt as classifyToken,Ot as consolePaths,mt as countPhrase,Ke as createAccountResource,ze as createDeploymentResource,Ve as createDomainResource,je as createTokenResource,an as default,Bn as deserializeLabels,Pt as doorOf,On as doors,_n as errandOf,hn as excessOver,kn as extractSubdomain,Ze as filterJunk,yn as fitPhrase,vt as formatDuration,_ as formatFileSize,Fn as formatTimeRemaining,$n as generateDeploymentUrl,Hn as generateDomainUrl,L as getENV,Zt as getValidFiles,U as hasUnbuiltMarker,be as hasUnsafeChars,Le as isBlockedExtension,_t as isClaimPath,Un as isCustomDomain,bn as isDeployment,Fe as isPlatformDomain,M as isShipError,wt as isUpgradePath,mn as normalizeVia,Qe as optimizeDeployPaths,gn as personName,Tn as personShortName,dt as placesTaken,Br as pluralize,st as processFilesForNode,In as readBearerValue,Gn as serializeLabels,At as validateApiKey,Ln as validateApiUrl,Ue as validateBuildCommand,ve as validateCaller,nt as validateDeployCount,tt as validateDeployFile,et as validateDeployPath,Rt as validateDeployToken,me as validateFileName,wr as validateFiles,Re as validateIdempotencyKey,It as validateOAuthToken,ke as validateOutputDir,se as validatePassword,re as validateToken,oe as validateTtl};
|
|
1
|
+
var lt=Object.defineProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var ct=(e,t)=>{for(var n in t)lt(e,n,{get:t[n],enumerable:!0})};function fn(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(pt).includes(t)?t:void 0}function Re(e){if(e==null)return;if(typeof e!="string")throw a.validation("Idempotency key must be a string.");let t=e.trim();if(!t)throw a.validation("Idempotency key must not be empty.");if(t.length>N.MAX_LENGTH)throw a.validation(`Idempotency key must be at most ${N.MAX_LENGTH} characters.`);return t}function ut(e){return e.members+e.invitations}function yn(e,t){let n=Math.max(0,ut(e)-t.members),r=Math.max(0,e.members-t.members),o={members:r,invitations:n-r,customDomains:e.customDomains-t.customDomains,platformDomains:e.platformDomains-t.platformDomains};return Object.fromEntries(Object.entries(o).filter(([,i])=>i>0))}function mt(e){return Ne(["members","customDomains","platformDomains"].filter(t=>(e[t]??0)>0).map(t=>Ie(t,e[t]??0)))}function En(e){let t=mt(e),n=e.invitations??0;return Ne([...t?[`remove ${t}`]:[],...n>0?[`cancel ${Ie("invitations",n)}`]:[]])}function Tn(e){return e.name?.trim()||e.email}function Dn(e){return e.name?.trim().split(" ")[0]||e.email}function yt(e){let t=e.code;return t==="ERR_INVALID_URL"?!1:typeof t=="string"?!0:e instanceof TypeError?!/\burl\b/i.test(e.message):!1}function M(e){return e!==null&&typeof e=="object"&&"name"in e&&e.name==="ShipError"&&"status"in e}function Et(e){let t=e.replace(/\\/g,"/").split("/").pop()??"",n=t.lastIndexOf(".");return n<=0||n===t.length-1?null:t.slice(n+1).toLowerCase()}function be(e,t){let n=Et(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function Le(e){return Tt.test(e)}function U(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>te.has(n))}function Dt(e){return e.startsWith(Oe.PREFIX)?R.API_KEY:e.startsWith(xe.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(Pe.PREFIX)?R.OAUTH:R.OPAQUE}function Nn(e){return e.slice(0,Q.length).toLowerCase()!==Q?null:e.slice(Q.length)||null}function we(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n;try{n=JSON.parse(t)}catch(r){throw a.config(`invalid JSON format in config: ${r.message}`,{filePath:S})}if(n===null||typeof n!="object"||Array.isArray(n))throw a.config(`${S} must contain a JSON object`,{filePath:S})}function ne(e,t,n){if(!e.startsWith(t.PREFIX))throw a.validation(`${n} must start with "${t.PREFIX}"`);if(e.length!==t.TOTAL_LENGTH)throw a.validation(`${n} must be ${t.TOTAL_LENGTH} characters total (${t.PREFIX} + ${t.HEX_LENGTH} hex chars)`);let r=e.slice(t.PREFIX.length);if(!new RegExp(`^[a-f0-9]{${t.HEX_LENGTH}}$`,"i").test(r))throw a.validation(`${n} must contain ${t.HEX_LENGTH} hexadecimal characters after "${t.PREFIX}" prefix`)}function St(e){ne(e,Oe,"API key")}function At(e){ne(e,xe,"Deploy token")}function Rt(e){ne(e,Pe,"OAuth access token")}function re(e){switch(Dt(e)){case R.API_KEY:St(e);return;case R.DEPLOY_TOKEN:At(e);return;case R.OAUTH:Rt(e);return;case R.OPAQUE:if(!e)throw a.validation("Token must be a non-empty string")}}function ve(e){if(!e||e.length>x.MAX_LENGTH||!x.PATTERN.test(e))throw a.validation(`Caller must be 1-${x.MAX_LENGTH} characters: letters, digits, dots, underscores, or hyphens`)}function Ln(e){try{let t=new URL(e);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 M(t)?t:a.validation("API URL must be a valid URL")}}function On(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function oe(e){if(e!=null){if(typeof e!="number"||!Number.isFinite(e))throw a.validation("TTL must be a number of seconds");if(!Number.isInteger(e))throw a.validation("TTL must be a whole number of seconds");if(e<C.MIN_SECONDS||e>C.MAX_SECONDS)throw a.validation(`TTL must be between ${C.MIN_SECONDS} and ${C.MAX_SECONDS} seconds`);return e}}function Lt(e){let t=e?`/${e}`:"",n=r=>`${t}${r}`;return{dashboard:()=>t||"/",newSite:()=>n("/new"),deployments:Object.assign(()=>n("/deployments"),{upload:()=>n("/deployments/upload")}),domains:Object.assign(()=>n("/domains"),{connect:r=>n(`/domains/${r}/connect`),deployment:r=>n(`/domains/${r}/deployment`)}),settings:r=>n(r?`/settings#${r}`:"/settings"),claim:r=>n(`/claim/${r}`),settingsAfterBilling:()=>n(`/settings?${Se("portal")}`),upgrade:r=>n(r?`/upgrade/${r}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${Se("checkout")}`),apiKey:()=>n("/api-key")}}function Pn(e){let t=new URLSearchParams(e);for(let[n,[r,o]]of Object.entries(Ce))if(t.get(r)===o)return n;return null}function $(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",r=""]=t.split("/").filter(Boolean);return Ot(n)?{kind:"door",door:n}:n===bt?{kind:"admin"}:n===""||Ae(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:Ae(r)?r:null}}function _n(e){let t=$(e);return t.kind==="account"?t.account:null}function xt(e){let t=$(e);return t.kind==="door"?t.door:null}function wn(e){return Pt(e)?"claim":xt(e)==="invitation"?"invite":_t(e)?"upgrade":null}function wt(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return ee(t,"minute");let n=Math.round(e/3600);return n<48?ee(n,"hour"):ee(Math.round(e/86400),"day")}function Mn(e,t=Date.now()/1e3){let n=e-t;return n>0?wt(n):null}function ee(e,t){return`${e} ${t}${e===1?"":"s"}`}function w(e,t=1){if(e===0)return"0 Bytes";let n=1024,r=["Bytes","KB","MB","GB"],o=Math.floor(Math.log(e)/Math.log(n));return`${Number.parseFloat((e/n**o).toFixed(t))} ${r[o]}`}function Fe(e,t){return e.endsWith(`.${t}`)}function kn(e,t){return!Fe(e,t)}function $n(e,t){return Fe(e,t)?e.slice(0,-(t.length+1)):null}function Hn(e){return`https://${e}`}function Gn(e){return`https://${e}`}function Ct(e){if(typeof e!="string")throw a.validation("Labels must be strings");let t=e.trim().toLowerCase();if(t.length<I.MIN_LENGTH)throw a.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(t.length>I.MAX_LENGTH)throw a.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!vt.test(t))throw a.validation("Labels use letters and numbers, with . _ or - between them, and can have one : between a key and a value, like env:production");return t}function b(e){if(e==null)return;if(!Array.isArray(e))throw a.validation("Labels must be an array");if(e.length>I.MAX_COUNT)throw a.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=e.map(Ct);if(new Set(t).size!==t.length)throw a.validation("Duplicate labels are not allowed");return t}function Bn(e){return!e||e.length===0?null:JSON.stringify(e)}function zn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function Me(e){if(e==null||e==="")return;if(typeof e!="string")throw a.validation("Build command must be a string");let t=e.trim();if(t.length===0||t.length>P.COMMAND_MAX_LENGTH)throw a.validation(`Build command must be between 1 and ${P.COMMAND_MAX_LENGTH} characters`);if(/[\x00-\x1f\x7f]/.test(t))throw a.validation("Build command must be a single line");return t}function Ue(e){if(e==null||e==="")return;if(typeof e!="string")throw a.validation("Output folder must be a string");let t=e.trim().replace(/\/+$/,"");if(t.length===0||t.length>P.OUTPUT_DIR_MAX_LENGTH)throw a.validation(`Output folder must be between 1 and ${P.OUTPUT_DIR_MAX_LENGTH} characters`);if(!P.OUTPUT_DIR_PATTERN.test(t)||t.split("/").some(n=>n===".."||n==="."))throw a.validation("Output folder must be a relative path inside the project, like dist or dist/site");return t}function se(e){if(e==null)return;if(typeof e!="string")throw a.validation("Password must be a string");let t=e.trim();if(t.length<F.MIN_LENGTH||t.length>F.MAX_LENGTH)throw a.validation(`Password must be between ${F.MIN_LENGTH} and ${F.MAX_LENGTH} characters`);return t}var pn,pt,un,mn,dn,N,hn,De,Ie,Ne,gn,d,E,Sn,m,dt,W,ft,ht,a,gt,An,Tt,te,Rn,J,Oe,xe,Pe,x,In,R,Q,bn,S,_e,k,C,It,Nt,bt,Ce,Se,Z,xn,Ot,Ae,Pt,_t,ie,_,vn,Cn,Fn,Un,h,I,vt,P,F,f=D(()=>{"use strict";pn={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},pt={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},un={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},mn={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},dn="troubleshooting",N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};hn={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"};De={deployments:{one:"deployment",many:"deployments"},platformDomains:{one:"ShipStatic domain",many:"ShipStatic domains"},customDomains:{one:"custom domain",many:"custom domains"},members:{one:"member",many:"members"},invitations:{one:"invitation",many:"invitations"}};Ie=(e,t)=>`${t} ${t===1?De[e].one:De[e].many}`,Ne=e=>e.length>1?`${e.slice(0,-1).join(", ")} and ${e[e.length-1]}`:e[0]??"",gn={PAUSED:"paused",UNKNOWN:"unknown"};d={DEPLOYMENTS:"/deployments",DEPLOYMENT:e=>`/deployments/${e}`,DEPLOYMENT_CONFIG:e=>`/deployments/${e}/config`,DOMAINS:"/domains",DOMAIN:e=>`/domains/${e}`,DOMAIN_VERIFY:e=>`/domains/${e}/verify`,DOMAIN_DNS:e=>`/domains/${e}/dns`,DOMAIN_RECORDS:e=>`/domains/${e}/records`,DOMAIN_SHARE:e=>`/domains/${e}/share`,DOMAIN_PROPAGATION:e=>`/domains/${e}/propagation`,DOMAINS_VALIDATE:"/domains/validate",TOKENS:"/tokens",TOKEN:e=>`/tokens/${e}`,ACCOUNT:"/account",ACCOUNT_KEY:"/account/key",ACCOUNT_CLAIM:"/account/claim",ACTIVITIES:"/activities",LABELS:"/labels",LIMITS:"/limits",PLANS:"/plans",PING:"/ping",SETUP:"/setup",SPA_CHECK:"/spa-check",UPLOAD:"/upload"},E={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",SPA:"spa",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},Sn={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},m={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Maintenance:"maintenance",Build:"build_failed",Network:"network_error",Timeout:"timeout_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},dt=new Set([m.Network,m.Timeout,m.Cancelled,m.File,m.Config]),W={client:new Set([m.Build,m.Business,m.Cancelled,m.Config,m.File,m.Forbidden,m.NotFound,m.RateLimit,m.Validation]),network:new Set([m.Network,m.Timeout]),auth:new Set([m.Authentication])},ft=new Set(Object.values(m).filter(e=>!dt.has(e))),ht=200;a=class e extends Error{type;status;details;constructor(t,n,r,o){super(n),this.type=t,this.status=r,this.details=o,this.name="ShipError"}toResponse(){let t=this.details,n=this.type===m.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:n}}static async fromHttpResponse(t,n){let r,o,i;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"?r=c.message:typeof c.error=="string"&&(r=c.error),o=c.details,typeof c.error=="string"&&ft.has(c.error)&&(i=c.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=ht&&(r=u)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let s=l.trim(),u=/^\d+$/.test(s)?Number(s):Math.ceil((Date.parse(s)-Date.now())/1e3);if(Number.isFinite(u)&&u>=0){let c=o&&typeof o=="object"?o:{};c.retryAfter===void 0&&(o={...c,retryAfter:u})}}r=r||`${n||"Request"} failed with status ${t.status}`;let p=i??(t.status===401?m.Authentication:t.status===403?m.Forbidden:t.status===429?m.RateLimit:m.Api);return new e(p,r,t.status,o)}static fromFetchError(t,n){if(M(t))return t;let r=n||"Request",o=t?.name;return o==="AbortError"?e.cancelled(`${r} was cancelled`):o==="TimeoutError"?e.timeout(`${r} timed out`,{cause:t}):t instanceof Error?yt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(m.Api,`${r} failed: ${t.message}`):new e(m.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(m.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(m.NotFound,r,404)}static forbidden(t,n){return new e(m.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(m.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(m.Authentication,t,401,n)}static business(t,n=400,r){return new e(m.Business,t,n,r)}static network(t,n){return new e(m.Network,t,void 0,n)}static timeout(t,n){return new e(m.Timeout,t,void 0,n)}static cancelled(t,n){return new e(m.Cancelled,t,void 0,n)}static file(t,n){return new e(m.File,t,void 0,n)}static config(t,n){return new e(m.Config,t,void 0,n)}static api(t,n=500,r){return new e(m.Api,t,n,r)}static maintenance(t,n){return new e(m.Maintenance,t,503,n)}static build(t,n){return new e(m.Build,t,422,n)}isClientError(){return W.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return W.network.has(this.type)}isAuthError(){return W.auth.has(this.type)}isType(t){return this.type===t}};gt=["html","htm","xhtml","xml","txt","md","markdown","pdf","csv","json","jsonc","webmanifest","map","toml","yaml","yml","rss","atom","css","scss","sass","less","js","mjs","cjs","jsx","ts","tsx","wasm","vue","svelte","png","jpg","jpeg","gif","webp","avif","svg","ico","bmp","tif","tiff","heic","heif","woff","woff2","ttf","otf","eot","mp3","wav","ogg","oga","opus","m4a","aac","flac","weba","mp4","webm","ogv","mov","m4v","avi","glb","gltf","usdz","vtt","srt","zip"],An=gt.map(e=>`.${e}`).join(","),Tt=/[\x00-\x1f\x7f#?%\\<>"]/;te=new Set(["node_modules","package.json"]);Rn="/auth",J={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Oe={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},xe={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},Pe={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},x={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},In="X-Account",R={API_KEY:J.API_KEY,DEPLOY_TOKEN:J.TOKEN,OAUTH:J.OAUTH,OPAQUE:"opaque"};Q="bearer ";bn={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},S="ship.json",_e={rewrites:[{source:"/(.*)",destination:"/index.html"}]},k={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};C={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};It={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},claim:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},Nt=["login","register","logout","invitation","consent"],bt="admin",Ce={checkout:["upgrading","true"],portal:["billing","returned"]},Se=e=>Ce[e].join("="),Z=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;xn={login:({token:e,next:t}={})=>Z(e?`/login/${e}`:"/login",t),register:({next:e}={})=>Z("/register",e),logout:({next:e}={})=>Z("/logout",e),invitation:e=>`/invitation/${e}`,consent:()=>"/consent"};Ot=e=>Nt.includes(e),Ae=e=>Object.hasOwn(It,e);Pt=e=>{let t=$(e);return t.kind==="account"&&t.section==="claim"},_t=e=>{let t=$(e);return t.kind==="account"&&t.section==="upgrade"};ie="https://api.shipstatic.com",_={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},vn="SHIP_VIA",Cn=`https://my.shipstatic.com${Lt().apiKey()}`,Fn=4320*60;Un=["account.create","account.update","account.delete","account.key.generate","account.plan.transition","deployment.create","deployment.update","deployment.delete","deployment.claim","domain.create","domain.update","domain.delete","domain.verify","token.create","token.consume","token.delete","member.join","member.leave","consent.grant"],h={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};I={MIN_LENGTH:3,MAX_LENGTH:63,MAX_COUNT:10},vt=/^[a-z0-9]+(?:[._-][a-z0-9]+)*(?::[a-z0-9]+(?:[._-][a-z0-9]+)*)?$/;P={COMMAND_MAX_LENGTH:200,OUTPUT_DIR_MAX_LENGTH:100,OUTPUT_DIR_PATTERN:/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)*$/};F={MIN_LENGTH:6,MAX_LENGTH:128}});async function zt(e){let t=(await import("spark-md5")).default,n=new t.ArrayBuffer,r=2097152;for(let o=0;o<e.size;o+=r){let i=Math.min(o+r,e.size);n.append(await e.slice(o,i).arrayBuffer())}return{md5:n.end()}}async function Vt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function Kt(e){let{createHash:t}=await import("crypto"),{createReadStream:n}=await import("fs");return new Promise((r,o)=>{let i=t("md5"),l=n(e);l.on("error",p=>o(a.file(`Failed to read file for MD5: ${p.message}`,{filePath:e}))),l.on("data",p=>i.update(p)),l.on("end",()=>r({md5:i.digest("hex")}))})}async function B(e){if(e instanceof Blob)return zt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Vt(e);if(typeof e=="string")return Kt(e);throw a.business("Invalid input for MD5 calculation")}var z=D(()=>{"use strict";f()});function fr(e){le=e}function Yt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return le||Yt()}var le,v=D(()=>{"use strict";le=null});function We(e){if(!e||e.length===0)return"";let t=e.filter(i=>i&&typeof i=="string").map(i=>i.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map(i=>i.split("/").filter(Boolean)),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o;i++){let l=n[0][i];if(n.every(p=>p[i]===l))r.push(l);else break}return r.join("/")}function j(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ce=D(()=>{"use strict"});function Je(e,t={}){if(t.flatten===!1)return e.map(r=>({path:j(r),name:pe(r)}));let n=Qt(e);return e.map(r=>{let o=j(r);if(n){let i=n.endsWith("/")?n:`${n}/`;o.startsWith(i)&&(o=o.substring(i.length))}return o||(o=pe(r)),{path:o,name:pe(r)}})}function Qt(e){if(!e.length)return"";let n=e.map(i=>j(i)).map(i=>i.split("/")),r=[],o=Math.min(...n.map(i=>i.length));for(let i=0;i<o-1;i++){let l=n[0][i];if(n.every(p=>p[i]===l))r.push(l);else break}return r.join("/")}function pe(e){return e.split(/[/\\]/).pop()||e}var ue=D(()=>{"use strict";ce()});function me(e,t,n){let r=t.suggestions?.[n];return r?`${e} ${r}`:e}function X(e,t){return Zt.find(n=>n.broken(e,t))}var Zt,O,fe=D(()=>{"use strict";f();he();Zt=[{name:"name",broken:({path:e})=>!de(e).valid,sentence:({path:e})=>de(e).reason??`File name "${e}" is invalid.`},{name:"extension",broken:({path:e},t)=>be(e,t.blockedExtensions??[]),sentence:({path:e})=>`File "${e}" has an extension that is not allowed.`},{name:"fileSize",broken:({size:e},t)=>e>t.maxFileSize,sentence:({path:e},t)=>me(`File "${e}" is too large. Maximum ${w(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>me(`Files add up to ${w(e)}. Maximum ${w(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],O={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>me(`Too many files (${e}). Maximum ${t.maxFilesCount} files allowed.`,t,"maxFilesCount")}});function de(e){let t=o=>({valid:!1,reason:`File name "${e}" ${o}.`});if(Le(e))return t("contains unsafe characters");if(e.startsWith(" ")||e.endsWith(" "))return t("cannot start or end with spaces");if(e.endsWith("."))return t("cannot end with dots");let n=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,r=e.split("/").pop()||e;return n.test(r)?t("uses a reserved system name"):e.includes("..")?t("contains a path traversal pattern"):{valid:!0}}function vr(e,t){let n=[],r=[],o=[];if(e.length===0){let s={file:"(no files)",message:"At least one file must be provided."};return n.push(s),{files:[],validFiles:[],errors:n,warnings:[],canDeploy:!1}}for(let s of e)if(U(s.name))return n.push({file:s.name,message:"Unbuilt project detected. Deploy your build output (dist/, build/, out/), not the project folder."}),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:n,warnings:[],canDeploy:!1};if(O.broken(e.length,t)){let s={file:`(${e.length} files)`,message:O.sentence(e.length,t)};return n.push(s),{files:e.map(u=>({...u,status:h.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let i=0;for(let s of e){let u=h.READY,c="Ready for upload";if(s.status===h.PROCESSING_ERROR)u=h.VALIDATION_FAILED,c=s.statusMessage||`File "${s.name}" could not be read.`,n.push({file:s.name,message:c});else if(s.size===0){u=h.EXCLUDED,c=`File "${s.name}" is empty, so it is excluded.`,r.push({file:s.name,message:c}),o.push({...s,status:u,statusMessage:c});continue}else if(s.size<0)u=h.VALIDATION_FAILED,c=`File "${s.name}" reports a negative size.`,n.push({file:s.name,message:c});else if(!s.name||s.name.trim().length===0)u=h.VALIDATION_FAILED,c="File name cannot be empty.",n.push({file:s.name||"(empty)",message:c});else if(s.name.includes("\0"))u=h.VALIDATION_FAILED,c=`File name "${s.name}" contains invalid characters (null byte).`,n.push({file:s.name,message:c});else{let y={path:s.name,size:s.size,totalSize:i+s.size},A=X(y,t);A?(u=h.VALIDATION_FAILED,c=A.sentence(y,t),n.push({file:A.name==="totalSize"?`(${e.length} files)`:s.name,message:c})):i=y.totalSize}o.push({...s,status:u,statusMessage:c})}n.length>0&&(o=o.map(s=>s.status===h.EXCLUDED?s:{...s,status:h.VALIDATION_FAILED,statusMessage:s.status===h.VALIDATION_FAILED?s.statusMessage:"Deployment failed due to validation errors in bundle"}));let l=n.length===0?o.filter(s=>s.status===h.READY):[],p=n.length===0;return{files:o,validFiles:l,errors:n,warnings:r,canDeploy:p}}function en(e){return e.filter(t=>t.status===h.READY)}function Cr(e){return en(e).length>0}var he=D(()=>{"use strict";f();fe();f()});import{isJunk as tn}from"junk";function Qe(e,t){if(!e||e.length===0)return[];if(!t?.allowUnbuilt&&e.find(r=>r&&U(r)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return e.filter(n=>{if(!n)return!1;let r=n.replace(/\\/g,"/").split("/").filter(Boolean);if(r.length===0)return!0;let o=r[r.length-1];if(tn(o))return!1;for(let l of r)if(l!==".well-known"&&(l.startsWith(".")||l.length>255))return!1;let i=r.slice(0,-1);for(let l of i)if(nn.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var nn,ye=D(()=>{"use strict";f();nn=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Ze(e,t){if(e.includes("\0")||e.includes("/../")||e.startsWith("../")||e.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${e}" for file: ${t}`)}function et(e,t){let n=X(e,t);if(n)throw a.business(n.sentence(e,t))}function tt(e,t){if(O.broken(e,t))throw a.business(O.sentence(e,t))}var Ee=D(()=>{"use strict";f();fe()});async function nt(e,t={},n){let r=!!(t.build||t.prerender),o=Je(e.map(c=>c.path),{flatten:t.pathDetect!==!1}).map(c=>c.path),i=new Set(Qe(o,{allowUnbuilt:r})),l=e.map((c,y)=>({source:c,deployPath:o[y]})).filter(({deployPath:c})=>i.has(c));if(l.length===0)return[];let p=r?null:rn(n),s=[],u=0;for(let{source:c,deployPath:y}of l){if(p&&Ze(y,c.origin),c.size===0)continue;p&&(u+=c.size,et({path:y,size:c.size,totalSize:u},p));let A=await c.read(),{md5:q}=await B(A);s.push({path:y,content:A,size:c.size,md5:q})}return p&&tt(s.length,p),s}function rn(e){if(!e)throw a.config("Platform limits not provided. Deploy-mode validation requires the limits argument \u2014 pass `ship.getLimits()` result.");return e}var rt=D(()=>{"use strict";f();ue();ye();z();Ee()});var st={};ct(st,{processFilesForNode:()=>it});import*as T from"fs";import*as g from"path";function ot(e,t=new Set){let n=[],r=T.realpathSync(e);if(t.has(r))return n;t.add(r);for(let o of T.readdirSync(e)){let i=g.join(e,o),l=T.statSync(i);l.isDirectory()?n.push(...ot(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function on(e){try{return T.readFileSync(e)}catch(t){let n=t instanceof Error?t.message:String(t);throw a.file(`Failed to read file "${e}": ${n}`,{filePath:e})}}function sn(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(o=>te.has(o));if(r)throw a.business(`"${r}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(r){if(M(r))throw r}}}async function it(e,t={},n){if(L()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");sn(e);let r=e.flatMap(p=>{let s=g.resolve(p);try{let u=T.statSync(s);return u.isDirectory()?ot(s):[{absPath:s,size:u.size}]}catch{throw a.file(`Path does not exist: ${p}`,{filePath:p})}}),o=new Map(r.map(p=>[p.absPath,p.size])),i=We(e.map(p=>g.resolve(p)).map(p=>{try{return T.statSync(p).isDirectory()?p:g.dirname(p)}catch{return g.dirname(p)}})),l=[...o].map(([p,s])=>({path:an(p,i),origin:p,size:s,read:()=>on(p)}));return nt(l,t,n)}function an(e,t){if(t&&t.length>0){let n=g.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return g.basename(e)}var ge=D(()=>{"use strict";f();rt();v();ce()});f();f();f();var H=class{constructor(){this.handlers=new Map}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t)?.add(n)}off(t,n){let r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t))}emit(t,...n){let r=this.handlers.get(t);if(!r)return;let o=Array.from(r);for(let i of o)try{i(...n)}catch(l){r.delete(i),t!=="error"&&setTimeout(()=>{let p=l instanceof Error?l:new Error(String(l));this.emit("error",p,String(t))},0)}}};var Ft=3e4,Mt=2,Ut=300,kt=2e3,$t=new Set([500,502,503,504]);function Ht(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason);return}let o=()=>{clearTimeout(l),t?.removeEventListener("abort",i)},i=()=>{o(),r(t?.reason)},l=setTimeout(()=>{o(),n()},e);t?.addEventListener("abort",i)})}var ke=3e5,Gt=3e5,Bt=ke+Gt,G=class extends H{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||ie,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Ft,this.maxRetries=Math.max(0,n.maxRetries??Mt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||d.DEPLOYMENTS,timeout:n.timeout??ke,buildTimeout:n.timeout??Bt}}setGlobalHeaders(n){this.globalHeaders=n}async executeRequest(n,r,o,i=this.timeout){for(let l=0;;l++)try{return await this.attemptOnce(n,r,o,i)}catch(p){let s=a.fromFetchError(p,o);if(l>=this.maxRetries||!this.isRetryable(s,r))throw this.emit("error",s,n),s;this.emit("retry",s,n,l+1);let u=Math.min(kt,Ut*2**l);try{await Ht(Math.random()*u,r.signal)}catch(c){let y=a.fromFetchError(c,o);throw this.emit("error",y,n),y}}}isRetryable(n,r){if(r.signal?.aborted||n.isType(m.Maintenance)||n.isType(m.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&$t.has(n.status)))return!1;let i=(r.method??"GET").toUpperCase();return i==="GET"||i==="HEAD"?!0:i==="PUT"||i==="DELETE"?!1:this.hasIdempotencyKey(r.headers)}hasIdempotencyKey(n){if(!n)return!1;let r=N.HEADER.toLowerCase();return Object.keys(n).some(o=>o.toLowerCase()===r)}async attemptOnce(n,r,o,i=this.timeout){let l=()=>{};try{let p=await this.mergeHeaders(r.headers),s=this.createTimeoutSignal(r.signal,i);l=s.cleanup;let u={...r,headers:p,credentials:this.session&&!p.Authorization?"include":void 0,signal:s.signal};this.emit("request",n,u);let c=await this.fetch(n,u);if(l(),!c.ok)throw await a.fromHttpResponse(c,o);return this.emit("response",this.safeClone(c),n),{data:await this.parseResponse(this.safeClone(c)),status:c.status}}catch(p){throw l(),a.fromFetchError(p,o)}}async request(n,r,o,i){let{data:l}=await this.executeRequest(`${this.apiUrl}${n}`,r,o,i);return l}async requestWithStatus(n,r,o){return this.executeRequest(`${this.apiUrl}${n}`,r,o)}async mergeHeaders(n={}){return{...this.globalHeaders,...this.caller?{[x.HEADER]:this.caller}:{},...await this.getAuthHeadersCallback(),...n}}createTimeoutSignal(n,r=this.timeout){let o=new AbortController,i=setTimeout(()=>o.abort(new DOMException(`Timed out after ${r}ms`,"TimeoutError")),r),l=n?()=>o.abort(n.reason):void 0;return n&&l&&(n.addEventListener("abort",l),n.aborted&&o.abort(n.reason)),{signal:o.signal,cleanup:()=>{clearTimeout(i),n&&l&&n.removeEventListener("abort",l)}}}safeClone(n){try{return n.clone()}catch{return n}}async parseResponse(n){if(!(n.headers.get("Content-Length")==="0"||n.status===204))return n.json()}};f();f();async function $e(e,t={}){let{labels:n,via:r,password:o,ttl:i,flags:l,captcha:p}=t,s=new FormData,u=[];for(let c of e){if(typeof c.content=="string"||c.content===null||c.content===void 0)throw a.file(`Unsupported file.content type: ${c.path}`,{filePath:c.path});if(!c.md5)throw a.file(`File missing md5 checksum: ${c.path}`,{filePath:c.path});s.append(E.FILES,new File([c.content],c.path,{type:"application/octet-stream"})),u.push(c.md5)}return s.append(E.CHECKSUMS,JSON.stringify(u)),n&&n.length>0&&s.append(E.LABELS,JSON.stringify(n)),r&&s.append(E.VIA,r),o&&s.append(E.PASSWORD,o),i!==void 0&&s.append(E.TTL,String(i)),l?.build&&s.append(E.BUILD,"true"),l?.prerender&&s.append(E.PRERENDER,"true"),l?.spa&&s.append(E.SPA,"true"),l?.buildCommand&&s.append(E.BUILD_COMMAND,l.buildCommand),l?.outputDir&&s.append(E.OUTPUT_DIR,l.outputDir),p&&s.append(E.CAPTCHA,p),s}f();z();async function jt(){let e=JSON.stringify(_e,null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await B(t);return{path:S,content:t,size:e.length,md5:n}}async function Xt(e,t,n){let r=e.find(p=>p.path===k.INDEX_FILE||p.path===`/${k.INDEX_FILE}`);if(!r||r.size>k.MAX_INDEX_BYTES)return!1;let o;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))o=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)o=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)o=await r.content.text();else return!1;let i={files:e.map(p=>p.path),index:o};return(await t.request(d.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:n??null},"SPA check")).isSPA}async function He(e,t,n){return n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===S)?e:await Xt(e,t,n.signal)?[...e,await jt()]:e}f();f();async function Ge(e){let t=e.find(o=>o.path===S||o.path===`/${S}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");we(r)}var V={"Content-Type":"application/json"},qt="sdk";function ae(e){let t=new URLSearchParams;e?.limit!==void 0&&t.set("limit",String(e.limit)),e?.cursor!==void 0&&t.set("cursor",e.cursor);let n=t.toString();return n?`?${n}`:""}function Be(e){let{getApi:t,processInput:n}=e;return{upload:async(r,o={})=>{if(!n)throw a.config("processInput function is not provided.");let i=t(),l=await n(r,o),p=await He(l,i,o);if(!p.length)throw a.business("No files to deploy");for(let Y of p)if(!Y.md5)throw a.file(`MD5 checksum missing for file: ${Y.path}`,{filePath:Y.path});se(o.password);let s=oe(o.ttl),u=Re(o.idempotencyKey),c=b(o.labels);await Ge(p);let y=Me(o.buildCommand),A=Ue(o.outputDir),q=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa,buildCommand:y,outputDir:A}:void 0,at=await $e(p,{labels:c,via:o.via??qt,password:o.password,ttl:s,flags:q,captcha:o.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:at,...u?{headers:{[N.HEADER]:u}}:{},signal:o.signal||null},"Deploy",o.build||o.prerender?i.deploy.buildTimeout:i.deploy.timeout)},list:async r=>t().request(`${d.DEPLOYMENTS}${ae(r)}`,{method:"GET"},"List deployments"),get:async r=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"GET"},"Get deployment"),set:async(r,o)=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"PATCH",headers:V,body:JSON.stringify({labels:b(o.labels)})},"Update deployment labels"),delete:async r=>t().request(d.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function ze(e){let{getApi:t}=e;return{set:async(n,r={})=>{let o=b(r.labels),i={};r.deployment&&(i.deployment=r.deployment),o!==void 0&&(i.labels=o);let{data:l,status:p}=await t().requestWithStatus(d.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:V,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:p===201}},list:async n=>t().request(`${d.DOMAINS}${ae(n)}`,{method:"GET"},"List domains"),get:async n=>t().request(d.DOMAIN(encodeURIComponent(n)),{method:"GET"},"Get domain"),delete:async n=>t().request(d.DOMAIN(encodeURIComponent(n)),{method:"DELETE"},"Delete domain"),verify:async n=>t().request(d.DOMAIN_VERIFY(encodeURIComponent(n)),{method:"POST"},"Verify domain"),validate:async n=>t().request(d.DOMAINS_VALIDATE,{method:"POST",headers:V,body:JSON.stringify({domain:n})},"Validate domain"),dns:async n=>t().request(d.DOMAIN_DNS(encodeURIComponent(n)),{method:"GET"},"Get domain DNS"),records:async n=>t().request(d.DOMAIN_RECORDS(encodeURIComponent(n)),{method:"GET"},"Get domain records"),share:async n=>t().request(d.DOMAIN_SHARE(encodeURIComponent(n)),{method:"GET"},"Get domain share")}}function Ve(e){let{getApi:t}=e;return{get:async()=>t().request(d.ACCOUNT,{method:"GET"},"Get account")}}function Ke(e){let{getApi:t}=e;return{create:async(n={})=>{let r=oe(n.ttl),o=b(n.labels),i={};return r!==void 0&&(i.ttl=r),o!==void 0&&(i.labels=o),t().request(d.TOKENS,{method:"POST",headers:V,body:JSON.stringify(i)},"Create token")},list:async n=>t().request(`${d.TOKENS}${ae(n)}`,{method:"GET"},"List tokens"),get:async n=>t().request(d.TOKEN(encodeURIComponent(n)),{method:"GET"},"Get token"),delete:async n=>t().request(d.TOKEN(encodeURIComponent(n)),{method:"DELETE"},"Delete token")}}var K=class{constructor(t={}){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&&ve(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(re(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new G({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Be({...n,processInput:async(r,o)=>this.processInput(r,o,await this.getLimits({signal:o.signal}))}),this.domains=ze(n),this.account=Ve(n),this.tokens=Ke(n)}async ping(){return this.http.request(d.PING,{method:"GET"},"Ping")}async deploy(t,n){return this.deployments.upload(t,n)}async whoami(){return this.account.get()}async getLimits(t={}){return this.http.request(d.LIMITS,{method:"GET",signal:t.signal??null},"Get limits")}on(t,n){this.http.on(t,n)}off(t,n){this.http.off(t,n)}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.");re(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}`}}};v();f();import{z as qe}from"zod";import{z as je}from"zod";var Xe={apiUrl:je.string().url().optional(),token:je.string().min(1).optional()};v();var Wt=qe.object(Xe).strict(),Jt={apiUrl:_.API_URL,token:_.TOKEN};function Ye(){if(L()!=="node")return{};let e={apiUrl:process.env[_.API_URL]||void 0,token:process.env[_.TOKEN]||void 0};try{return Wt.parse(e)}catch(t){if(t instanceof qe.ZodError){let n=t.issues[0],r=n.path[0],o=(r&&Jt[r])??"SHIP environment configuration";throw a.config(`Invalid ${o}: ${n.message}`)}throw a.config("Invalid environment configuration")}}f();f();ue();v();he();ye();z();Ee();function zr(e,t,n,r=!0){let o=e===1?t:n;return r?`${e} ${o}`:o}ge();var Te=class extends K{constructor(t={}){if(L()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let n=Ye();super({...t,apiUrl:t.apiUrl||n.apiUrl,token:t.token||(t.session?void 0:n.token)})}async deploy(t,n){return super.deploy(t,n)}async processInput(t,n,r){let o=typeof t=="string"?[t]:t;if(!Array.isArray(o)||!o.every(l=>typeof l=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(o.length===0)throw a.business("No files to deploy.");let{processFilesForNode:i}=await Promise.resolve().then(()=>(ge(),st));return i(o,n,r)}},ln=Te;export{In as ACCOUNT_HEADER,Oe as API_KEY,d as API_PATHS,Rn as AUTH_BASE_PATH,hn as AccountPlan,gn as AccountRefusal,G as ApiHttp,J as AuthMethod,P as BUILD_SETTINGS,x as CALLER,ie as DEFAULT_API,S as DEPLOYMENT_CONFIG_FILENAME,E as DEPLOY_FIELDS,Sn as DEPLOY_FILE_GRAMMAR,xe as DEPLOY_TOKEN,pn as DeploymentStatus,pt as DeploymentVia,un as DomainStatus,mn as DomainVerification,m as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,nn as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,vt as LABEL_PATTERN,Cn as MY_API_KEY_URL,Pe as OAUTH_TOKEN,bn as OAuthScope,F as PASSWORD_CONSTRAINTS,Fn as PUBLIC_DEPLOYMENT_TTL_SECONDS,It as SECTIONS,dn as SETUP_TROUBLESHOOTING_ANCHOR,_ as SHIP_ENV,vn as SHIP_VIA_ENV,k as SPA_CHECK_CONSTRAINTS,_e as SPA_DEFAULT_CONFIG,Te as Ship,a as ShipError,C as TTL_CONSTRAINTS,R as TokenKind,te as UNBUILT_PROJECT_MARKERS,Tt as UNSAFE_FILENAME_CHARS,De as USAGE_KIND,Un as USER_VISIBLE_EVENTS,An as WEB_FILE_ACCEPT,fr as __setTestEnvironment,_n as accountOfPath,Cr as allValidFilesReady,we as assertShipJsonSyntax,Pn as billingReturnOf,B as calculateMD5,Dt as classifyToken,Lt as consolePaths,mt as countPhrase,Ve as createAccountResource,Be as createDeploymentResource,ze as createDomainResource,Ke as createTokenResource,ln as default,zn as deserializeLabels,xt as doorOf,xn as doors,wn as errandOf,yn as excessOver,$n as extractSubdomain,Qe as filterJunk,En as fitPhrase,wt as formatDuration,w as formatFileSize,Mn as formatTimeRemaining,Hn as generateDeploymentUrl,Gn as generateDomainUrl,L as getENV,en as getValidFiles,U as hasUnbuiltMarker,Le as hasUnsafeChars,be as isBlockedExtension,Pt as isClaimPath,kn as isCustomDomain,On as isDeployment,Fe as isPlatformDomain,M as isShipError,_t as isUpgradePath,fn as normalizeVia,Je as optimizeDeployPaths,Tn as personName,Dn as personShortName,ut as placesTaken,zr as pluralize,it as processFilesForNode,Nn as readBearerValue,Bn as serializeLabels,St as validateApiKey,Ln as validateApiUrl,Me as validateBuildCommand,ve as validateCaller,tt as validateDeployCount,et as validateDeployFile,Ze as validateDeployPath,At as validateDeployToken,de as validateFileName,vr as validateFiles,Re as validateIdempotencyKey,Ct as validateLabel,b as validateLabels,Rt as validateOAuthToken,Ue as validateOutputDir,se as validatePassword,re as validateToken,oe as validateTtl};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|