@shipstatic/ship 3.4.0-beta.18 → 3.4.0-beta.19
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 -0
- package/SKILL.md +3 -2
- package/THIRD-PARTY-LICENSES.md +1 -1
- package/dist/browser.d.ts +71 -16
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +71 -70
- 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 -16
- package/dist/index.d.ts +71 -16
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -116,19 +116,6 @@ interface Deployment {
|
|
|
116
116
|
readonly config: boolean;
|
|
117
117
|
/** Whether deployment has a password set */
|
|
118
118
|
readonly password: boolean;
|
|
119
|
-
/**
|
|
120
|
-
* The default page the deployment declares for a missing path: the
|
|
121
|
-
* platform's single-page preset (a deployment whose only page is
|
|
122
|
-
* `index.html`, or React Router's `__spa-fallback.html`), or the target of
|
|
123
|
-
* the author's own catch-all (`/(.*)` or `/:path*`) to one file. The
|
|
124
|
-
* author's other rules still run ahead of it. `null` when no default is
|
|
125
|
-
* declared, which is what an application with pages beside its shell gets
|
|
126
|
-
* until its author declares the route. Carried by a deployment, not by a
|
|
127
|
-
* list of deployments; omitted when the deployment's artifact cannot be
|
|
128
|
-
* read, and by an API older than the field. Absent is not `null`: `null`
|
|
129
|
-
* is a declaration of none.
|
|
130
|
-
*/
|
|
131
|
-
readonly fallback?: string | null;
|
|
132
119
|
/** Labels for categorization and filtering (lowercase, alphanumeric with separators). Always present, empty array when none. */
|
|
133
120
|
labels: string[];
|
|
134
121
|
/**
|
|
@@ -1086,6 +1073,7 @@ declare const API_PATHS: {
|
|
|
1086
1073
|
readonly PLANS: "/plans";
|
|
1087
1074
|
readonly PING: "/ping";
|
|
1088
1075
|
readonly SETUP: "/setup";
|
|
1076
|
+
readonly SPA_CHECK: "/spa-check";
|
|
1089
1077
|
readonly UPLOAD: "/upload";
|
|
1090
1078
|
};
|
|
1091
1079
|
/**
|
|
@@ -1124,6 +1112,8 @@ declare const DEPLOY_FIELDS: {
|
|
|
1124
1112
|
readonly BUILD: "build";
|
|
1125
1113
|
/** @internal Server-processing flag — first-party `/upload` only. */
|
|
1126
1114
|
readonly PRERENDER: "prerender";
|
|
1115
|
+
/** @internal Server-processing flag — first-party `/upload` only. */
|
|
1116
|
+
readonly SPA: "spa";
|
|
1127
1117
|
/**
|
|
1128
1118
|
* @internal The build settings, first-party `/upload` only and meaningful
|
|
1129
1119
|
* only with `BUILD`: the command to run instead of the manifest's build
|
|
@@ -1840,6 +1830,33 @@ declare const OAuthScope: {
|
|
|
1840
1830
|
};
|
|
1841
1831
|
type OAuthScopeType = (typeof OAuthScope)[keyof typeof OAuthScope];
|
|
1842
1832
|
declare const DEPLOYMENT_CONFIG_FILENAME = "ship.json";
|
|
1833
|
+
/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */
|
|
1834
|
+
declare const SPA_DEFAULT_CONFIG: {
|
|
1835
|
+
readonly rewrites: readonly [{
|
|
1836
|
+
readonly source: "/(.*)";
|
|
1837
|
+
readonly destination: "/index.html";
|
|
1838
|
+
}];
|
|
1839
|
+
};
|
|
1840
|
+
/**
|
|
1841
|
+
* The `/spa-check` pre-flight's client-side envelope: which file is the
|
|
1842
|
+
* check's subject, and how large it may be before a client skips the call.
|
|
1843
|
+
*
|
|
1844
|
+
* One fact with three holders until this export — the API's config declared
|
|
1845
|
+
* the cap, the SDK's `checkSPA` hardcoded `100 * 1024`, and prose restated
|
|
1846
|
+
* "100KB". `INDEX_FILE` is the selection rule (the file whose content rides
|
|
1847
|
+
* `SPACheckRequest.index`), restated by every client that builds the request.
|
|
1848
|
+
*
|
|
1849
|
+
* Neither member is a validation boundary: a client over the cap simply
|
|
1850
|
+
* skips the pre-flight, because the server answers an oversized index
|
|
1851
|
+
* `isSPA: false` anyway. A consumer that cannot import this (n8n) needs no
|
|
1852
|
+
* size copy at all — outcome parity is the server's, not the client's.
|
|
1853
|
+
*/
|
|
1854
|
+
declare const SPA_CHECK_CONSTRAINTS: {
|
|
1855
|
+
/** The file whose content is the check's subject. */
|
|
1856
|
+
readonly INDEX_FILE: "index.html";
|
|
1857
|
+
/** Skip the pre-flight above this size — the server would answer false. */
|
|
1858
|
+
readonly MAX_INDEX_BYTES: number;
|
|
1859
|
+
};
|
|
1843
1860
|
/**
|
|
1844
1861
|
* Assert that a ship.json file is *syntactically* loadable. Syntax only —
|
|
1845
1862
|
* never schema.
|
|
@@ -1952,6 +1969,39 @@ declare const TTL_CONSTRAINTS: {
|
|
|
1952
1969
|
* schema), the SDK's request boundary, and the CLI's parser.
|
|
1953
1970
|
*/
|
|
1954
1971
|
declare function validateTtl(value: unknown): number | undefined;
|
|
1972
|
+
/**
|
|
1973
|
+
* Request payload for SPA check endpoint
|
|
1974
|
+
*/
|
|
1975
|
+
interface SPACheckRequest {
|
|
1976
|
+
/** Array of file paths */
|
|
1977
|
+
files: string[];
|
|
1978
|
+
/** HTML content of index.html file */
|
|
1979
|
+
index: string;
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Response from SPA check endpoint
|
|
1983
|
+
*/
|
|
1984
|
+
/**
|
|
1985
|
+
* Which of the classifier's tiers reached the verdict, and why. Named rather
|
|
1986
|
+
* than inline so the API's own `checkSPA` can return `SPACheckResponse`
|
|
1987
|
+
* instead of restating its shape.
|
|
1988
|
+
*/
|
|
1989
|
+
interface SPACheckDebug {
|
|
1990
|
+
/** Which tier made the detection */
|
|
1991
|
+
tier: 'exclusions' | 'inclusions' | 'scoring' | 'ai' | 'fallback';
|
|
1992
|
+
/** The reason for the detection result */
|
|
1993
|
+
reason: string;
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* A report: it answers a question and carries only the answer (`CLAUDE.md`,
|
|
1997
|
+
* "A report answers a question").
|
|
1998
|
+
*/
|
|
1999
|
+
interface SPACheckResponse {
|
|
2000
|
+
/** Whether the project is detected as a Single Page Application */
|
|
2001
|
+
isSPA: boolean;
|
|
2002
|
+
/** Debugging information about detection */
|
|
2003
|
+
debug: SPACheckDebug;
|
|
2004
|
+
}
|
|
1955
2005
|
/**
|
|
1956
2006
|
* Represents a file that has been processed and is ready for deploy.
|
|
1957
2007
|
* Used across the platform (API, SDK, CLI) for file operations.
|
|
@@ -2263,6 +2313,8 @@ interface DeploymentUploadOptions {
|
|
|
2263
2313
|
build?: boolean;
|
|
2264
2314
|
/** @internal Trigger server-side prerender. Only available via /upload endpoint. */
|
|
2265
2315
|
prerender?: boolean;
|
|
2316
|
+
/** @internal Trigger server-side SPA detection. Only available via /upload endpoint. */
|
|
2317
|
+
spa?: boolean;
|
|
2266
2318
|
/**
|
|
2267
2319
|
* @internal The command the build runs instead of the manifest's own
|
|
2268
2320
|
* `build` script (`npm run build:site`, `hugo`, …). Only with `build`, only
|
|
@@ -2892,7 +2944,7 @@ interface DeploymentOptions extends DeploymentUploadOptions {
|
|
|
2892
2944
|
/**
|
|
2893
2945
|
* An AbortSignal to allow cancellation of the deploy operation. The one
|
|
2894
2946
|
* cancellation mechanism: it reaches every request the deploy makes (the
|
|
2895
|
-
* limits it validates against and the upload itself),
|
|
2947
|
+
* limits it validates against, the SPA question and the upload itself),
|
|
2896
2948
|
* and aborting it rejects the deploy with a typed `Cancelled` error
|
|
2897
2949
|
* wherever it stands. A deploy the server had already committed stays
|
|
2898
2950
|
* committed. Request timeouts are a client concern
|
|
@@ -2901,6 +2953,8 @@ interface DeploymentOptions extends DeploymentUploadOptions {
|
|
|
2901
2953
|
signal?: AbortSignal;
|
|
2902
2954
|
/** Whether to auto-detect and optimize file paths by flattening common directories. Defaults to true. */
|
|
2903
2955
|
pathDetect?: boolean;
|
|
2956
|
+
/** Whether to auto-detect SPAs and generate ship.json configuration. Defaults to true. */
|
|
2957
|
+
spaDetect?: boolean;
|
|
2904
2958
|
}
|
|
2905
2959
|
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
2906
2960
|
/**
|
|
@@ -2938,6 +2992,7 @@ interface DeployBodyContext {
|
|
|
2938
2992
|
flags?: {
|
|
2939
2993
|
build?: boolean;
|
|
2940
2994
|
prerender?: boolean;
|
|
2995
|
+
spa?: boolean;
|
|
2941
2996
|
buildCommand?: string;
|
|
2942
2997
|
outputDir?: string;
|
|
2943
2998
|
};
|
|
@@ -3052,7 +3107,7 @@ interface ShipClientOptions {
|
|
|
3052
3107
|
* Override the deploy endpoint path. Defaults to `/deployments`.
|
|
3053
3108
|
*
|
|
3054
3109
|
* @internal First-party hook used by `web/my` and `web/www` to target the
|
|
3055
|
-
* `/upload` route (which runs
|
|
3110
|
+
* `/upload` route (which runs server-side build / SPA detection). External
|
|
3056
3111
|
* SDK consumers must not set this — the `/deployments` endpoint is the
|
|
3057
3112
|
* stable public contract. See `cloudflare/api/CLAUDE.md` for why the two
|
|
3058
3113
|
* endpoints exist and what `/upload` does that `/deployments` doesn't.
|
|
@@ -3807,6 +3862,6 @@ declare class Ship extends Ship$1 {
|
|
|
3807
3862
|
}
|
|
3808
3863
|
|
|
3809
3864
|
declare namespace Ship {
|
|
3810
|
-
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountAccess, AccountDeleteResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountRefusal, AccountRefusalType, AccountResource, AccountRole, 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, 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, SIGN_IN_RETURN_PARAM, 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, USER_VISIBLE_EVENTS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, doors, errandOf, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isInvitationPath, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3865
|
+
export { ACCOUNT_HEADER, API_KEY, API_PATHS, AUTH_BASE_PATH, Account, AccountAccess, AccountDeleteResponse, AccountKeyResponse, AccountPlan, AccountPlanType, AccountRefusal, AccountRefusalType, AccountResource, AccountRole, 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, 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, SIGN_IN_RETURN_PARAM, SPACheckDebug, 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, USER_VISIBLE_EVENTS, UploadedFile, UserVisibleActivityEvent, ValidatableFile, ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, deserializeLabels, doors, errandOf, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isInvitationPath, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3811
3866
|
}
|
|
3812
3867
|
export = Ship;
|
package/dist/index.d.ts
CHANGED
|
@@ -116,19 +116,6 @@ interface Deployment {
|
|
|
116
116
|
readonly config: boolean;
|
|
117
117
|
/** Whether deployment has a password set */
|
|
118
118
|
readonly password: boolean;
|
|
119
|
-
/**
|
|
120
|
-
* The default page the deployment declares for a missing path: the
|
|
121
|
-
* platform's single-page preset (a deployment whose only page is
|
|
122
|
-
* `index.html`, or React Router's `__spa-fallback.html`), or the target of
|
|
123
|
-
* the author's own catch-all (`/(.*)` or `/:path*`) to one file. The
|
|
124
|
-
* author's other rules still run ahead of it. `null` when no default is
|
|
125
|
-
* declared, which is what an application with pages beside its shell gets
|
|
126
|
-
* until its author declares the route. Carried by a deployment, not by a
|
|
127
|
-
* list of deployments; omitted when the deployment's artifact cannot be
|
|
128
|
-
* read, and by an API older than the field. Absent is not `null`: `null`
|
|
129
|
-
* is a declaration of none.
|
|
130
|
-
*/
|
|
131
|
-
readonly fallback?: string | null;
|
|
132
119
|
/** Labels for categorization and filtering (lowercase, alphanumeric with separators). Always present, empty array when none. */
|
|
133
120
|
labels: string[];
|
|
134
121
|
/**
|
|
@@ -1086,6 +1073,7 @@ declare const API_PATHS: {
|
|
|
1086
1073
|
readonly PLANS: "/plans";
|
|
1087
1074
|
readonly PING: "/ping";
|
|
1088
1075
|
readonly SETUP: "/setup";
|
|
1076
|
+
readonly SPA_CHECK: "/spa-check";
|
|
1089
1077
|
readonly UPLOAD: "/upload";
|
|
1090
1078
|
};
|
|
1091
1079
|
/**
|
|
@@ -1124,6 +1112,8 @@ declare const DEPLOY_FIELDS: {
|
|
|
1124
1112
|
readonly BUILD: "build";
|
|
1125
1113
|
/** @internal Server-processing flag — first-party `/upload` only. */
|
|
1126
1114
|
readonly PRERENDER: "prerender";
|
|
1115
|
+
/** @internal Server-processing flag — first-party `/upload` only. */
|
|
1116
|
+
readonly SPA: "spa";
|
|
1127
1117
|
/**
|
|
1128
1118
|
* @internal The build settings, first-party `/upload` only and meaningful
|
|
1129
1119
|
* only with `BUILD`: the command to run instead of the manifest's build
|
|
@@ -1840,6 +1830,33 @@ declare const OAuthScope: {
|
|
|
1840
1830
|
};
|
|
1841
1831
|
type OAuthScopeType = (typeof OAuthScope)[keyof typeof OAuthScope];
|
|
1842
1832
|
declare const DEPLOYMENT_CONFIG_FILENAME = "ship.json";
|
|
1833
|
+
/** Default ship.json config for SPA routing. Single source of truth — used by both API and SDK. */
|
|
1834
|
+
declare const SPA_DEFAULT_CONFIG: {
|
|
1835
|
+
readonly rewrites: readonly [{
|
|
1836
|
+
readonly source: "/(.*)";
|
|
1837
|
+
readonly destination: "/index.html";
|
|
1838
|
+
}];
|
|
1839
|
+
};
|
|
1840
|
+
/**
|
|
1841
|
+
* The `/spa-check` pre-flight's client-side envelope: which file is the
|
|
1842
|
+
* check's subject, and how large it may be before a client skips the call.
|
|
1843
|
+
*
|
|
1844
|
+
* One fact with three holders until this export — the API's config declared
|
|
1845
|
+
* the cap, the SDK's `checkSPA` hardcoded `100 * 1024`, and prose restated
|
|
1846
|
+
* "100KB". `INDEX_FILE` is the selection rule (the file whose content rides
|
|
1847
|
+
* `SPACheckRequest.index`), restated by every client that builds the request.
|
|
1848
|
+
*
|
|
1849
|
+
* Neither member is a validation boundary: a client over the cap simply
|
|
1850
|
+
* skips the pre-flight, because the server answers an oversized index
|
|
1851
|
+
* `isSPA: false` anyway. A consumer that cannot import this (n8n) needs no
|
|
1852
|
+
* size copy at all — outcome parity is the server's, not the client's.
|
|
1853
|
+
*/
|
|
1854
|
+
declare const SPA_CHECK_CONSTRAINTS: {
|
|
1855
|
+
/** The file whose content is the check's subject. */
|
|
1856
|
+
readonly INDEX_FILE: "index.html";
|
|
1857
|
+
/** Skip the pre-flight above this size — the server would answer false. */
|
|
1858
|
+
readonly MAX_INDEX_BYTES: number;
|
|
1859
|
+
};
|
|
1843
1860
|
/**
|
|
1844
1861
|
* Assert that a ship.json file is *syntactically* loadable. Syntax only —
|
|
1845
1862
|
* never schema.
|
|
@@ -1952,6 +1969,39 @@ declare const TTL_CONSTRAINTS: {
|
|
|
1952
1969
|
* schema), the SDK's request boundary, and the CLI's parser.
|
|
1953
1970
|
*/
|
|
1954
1971
|
declare function validateTtl(value: unknown): number | undefined;
|
|
1972
|
+
/**
|
|
1973
|
+
* Request payload for SPA check endpoint
|
|
1974
|
+
*/
|
|
1975
|
+
interface SPACheckRequest {
|
|
1976
|
+
/** Array of file paths */
|
|
1977
|
+
files: string[];
|
|
1978
|
+
/** HTML content of index.html file */
|
|
1979
|
+
index: string;
|
|
1980
|
+
}
|
|
1981
|
+
/**
|
|
1982
|
+
* Response from SPA check endpoint
|
|
1983
|
+
*/
|
|
1984
|
+
/**
|
|
1985
|
+
* Which of the classifier's tiers reached the verdict, and why. Named rather
|
|
1986
|
+
* than inline so the API's own `checkSPA` can return `SPACheckResponse`
|
|
1987
|
+
* instead of restating its shape.
|
|
1988
|
+
*/
|
|
1989
|
+
interface SPACheckDebug {
|
|
1990
|
+
/** Which tier made the detection */
|
|
1991
|
+
tier: 'exclusions' | 'inclusions' | 'scoring' | 'ai' | 'fallback';
|
|
1992
|
+
/** The reason for the detection result */
|
|
1993
|
+
reason: string;
|
|
1994
|
+
}
|
|
1995
|
+
/**
|
|
1996
|
+
* A report: it answers a question and carries only the answer (`CLAUDE.md`,
|
|
1997
|
+
* "A report answers a question").
|
|
1998
|
+
*/
|
|
1999
|
+
interface SPACheckResponse {
|
|
2000
|
+
/** Whether the project is detected as a Single Page Application */
|
|
2001
|
+
isSPA: boolean;
|
|
2002
|
+
/** Debugging information about detection */
|
|
2003
|
+
debug: SPACheckDebug;
|
|
2004
|
+
}
|
|
1955
2005
|
/**
|
|
1956
2006
|
* Represents a file that has been processed and is ready for deploy.
|
|
1957
2007
|
* Used across the platform (API, SDK, CLI) for file operations.
|
|
@@ -2263,6 +2313,8 @@ interface DeploymentUploadOptions {
|
|
|
2263
2313
|
build?: boolean;
|
|
2264
2314
|
/** @internal Trigger server-side prerender. Only available via /upload endpoint. */
|
|
2265
2315
|
prerender?: boolean;
|
|
2316
|
+
/** @internal Trigger server-side SPA detection. Only available via /upload endpoint. */
|
|
2317
|
+
spa?: boolean;
|
|
2266
2318
|
/**
|
|
2267
2319
|
* @internal The command the build runs instead of the manifest's own
|
|
2268
2320
|
* `build` script (`npm run build:site`, `hugo`, …). Only with `build`, only
|
|
@@ -2892,7 +2944,7 @@ interface DeploymentOptions extends DeploymentUploadOptions {
|
|
|
2892
2944
|
/**
|
|
2893
2945
|
* An AbortSignal to allow cancellation of the deploy operation. The one
|
|
2894
2946
|
* cancellation mechanism: it reaches every request the deploy makes (the
|
|
2895
|
-
* limits it validates against and the upload itself),
|
|
2947
|
+
* limits it validates against, the SPA question and the upload itself),
|
|
2896
2948
|
* and aborting it rejects the deploy with a typed `Cancelled` error
|
|
2897
2949
|
* wherever it stands. A deploy the server had already committed stays
|
|
2898
2950
|
* committed. Request timeouts are a client concern
|
|
@@ -2901,6 +2953,8 @@ interface DeploymentOptions extends DeploymentUploadOptions {
|
|
|
2901
2953
|
signal?: AbortSignal;
|
|
2902
2954
|
/** Whether to auto-detect and optimize file paths by flattening common directories. Defaults to true. */
|
|
2903
2955
|
pathDetect?: boolean;
|
|
2956
|
+
/** Whether to auto-detect SPAs and generate ship.json configuration. Defaults to true. */
|
|
2957
|
+
spaDetect?: boolean;
|
|
2904
2958
|
}
|
|
2905
2959
|
type ApiDeployOptions = Omit<DeploymentOptions, 'pathDetect'>;
|
|
2906
2960
|
/**
|
|
@@ -2938,6 +2992,7 @@ interface DeployBodyContext {
|
|
|
2938
2992
|
flags?: {
|
|
2939
2993
|
build?: boolean;
|
|
2940
2994
|
prerender?: boolean;
|
|
2995
|
+
spa?: boolean;
|
|
2941
2996
|
buildCommand?: string;
|
|
2942
2997
|
outputDir?: string;
|
|
2943
2998
|
};
|
|
@@ -3052,7 +3107,7 @@ interface ShipClientOptions {
|
|
|
3052
3107
|
* Override the deploy endpoint path. Defaults to `/deployments`.
|
|
3053
3108
|
*
|
|
3054
3109
|
* @internal First-party hook used by `web/my` and `web/www` to target the
|
|
3055
|
-
* `/upload` route (which runs
|
|
3110
|
+
* `/upload` route (which runs server-side build / SPA detection). External
|
|
3056
3111
|
* SDK consumers must not set this — the `/deployments` endpoint is the
|
|
3057
3112
|
* stable public contract. See `cloudflare/api/CLAUDE.md` for why the two
|
|
3058
3113
|
* endpoints exist and what `/upload` does that `/deployments` doesn't.
|
|
@@ -3806,4 +3861,4 @@ declare class Ship extends Ship$1 {
|
|
|
3806
3861
|
protected processInput(input: DeployInput, options: DeploymentOptions, limits: PlatformLimits): Promise<StaticFile[]>;
|
|
3807
3862
|
}
|
|
3808
3863
|
|
|
3809
|
-
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 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 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, SIGN_IN_RETURN_PARAM, 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, USER_VISIBLE_EVENTS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, doors, errandOf, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isInvitationPath, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
|
3864
|
+
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 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 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, SIGN_IN_RETURN_PARAM, type SPACheckDebug, 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, USER_VISIBLE_EVENTS, type UploadedFile, type UserVisibleActivityEvent, type ValidatableFile, type ValidationIssue, WEB_FILE_ACCEPT, __setTestEnvironment, accountOfPath, allValidFilesReady, assertShipJsonSyntax, billingReturnOf, calculateMD5, classifyToken, consolePaths, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, deserializeLabels, doors, errandOf, extractSubdomain, filterJunk, formatDuration, formatFileSize, formatTimeRemaining, generateDeploymentUrl, generateDomainUrl, getENV, getValidFiles, hasUnbuiltMarker, hasUnsafeChars, isBlockedExtension, isClaimPath, isCustomDomain, isDeployment, isInvitationPath, isPlatformDomain, isShipError, isUpgradePath, normalizeVia, optimizeDeployPaths, personName, personShortName, pluralize, processFilesForNode, readBearerValue, serializeLabels, validateApiKey, validateApiUrl, validateBuildCommand, validateCaller, validateDeployCount, validateDeployFile, validateDeployPath, validateDeployToken, validateFileName, validateFiles, validateIdempotencyKey, validateOAuthToken, validateOutputDir, validatePassword, validateToken, validateTtl };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var nt=Object.defineProperty;var D=(e,t)=>()=>(e&&(t=e(e=0)),t);var rt=(e,t)=>{for(var n in t)nt(e,n,{get:t[n],enumerable:!0})};function tn(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(ot).includes(t)?t:void 0}function De(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 on(e){return e.name?.trim()||e.email}function sn(e){return e.name?.trim().split(" ")[0]||e.email}function lt(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 ct(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 Re(e,t){let n=ct(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function Ae(e){return pt.test(e)}function U(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>J.has(n))}function dt(e){return e.startsWith(Se.PREFIX)?A.API_KEY:e.startsWith(Ie.PREFIX)?A.DEPLOY_TOKEN:e.startsWith(Ne.PREFIX)?A.OAUTH:A.OPAQUE}function dn(e){return e.slice(0,X.length).toLowerCase()!==X?null:e.slice(X.length)||null}function Le(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:I})}if(n===null||typeof n!="object"||Array.isArray(n))throw a.config(`${I} must contain a JSON object`,{filePath:I})}function Q(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 mt(e){Q(e,Se,"API key")}function ft(e){Q(e,Ie,"Deploy token")}function ht(e){Q(e,Ne,"OAuth access token")}function Z(e){switch(dt(e)){case A.API_KEY:mt(e);return;case A.DEPLOY_TOKEN:ft(e);return;case A.OAUTH:ht(e);return;case A.OPAQUE:if(!e)throw a.validation("Token must be a non-empty string")}}function be(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 fn(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 hn(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function ee(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 Tt(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"),settingsAfterBilling:()=>n(`/settings?${Ee("portal")}`),upgrade:r=>n(r?`/upgrade/${r}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${Ee("checkout")}`),apiKey:()=>n("/api-key")}}function En(e){let t=new URLSearchParams(e);for(let[n,[r,o]]of Object.entries(Oe))if(t.get(r)===o)return n;return null}function k(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",r=""]=t.split("/").filter(Boolean);return Dt(n)?{kind:"door",door:n}:n===gt?{kind:"admin"}:n===""||Te(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:Te(r)?r:null}}function gn(e){let t=k(e);return t.kind==="account"?t.account:null}function Tn(e){return Rt(e)?"claim":At(e)?"invite":St(e)?"upgrade":null}function It(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return W(t,"minute");let n=Math.round(e/3600);return n<48?W(n,"hour"):W(Math.round(e/86400),"day")}function Sn(e,t=Date.now()/1e3){let n=e-t;return n>0?It(n):null}function W(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 xe(e,t){return e.endsWith(`.${t}`)}function Nn(e,t){return!xe(e,t)}function Ln(e,t){return xe(e,t)?e.slice(0,-(t.length+1)):null}function bn(e){return`https://${e}`}function On(e){return`https://${e}`}function xn(e){return!e||e.length===0?null:JSON.stringify(e)}function Pn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function _e(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 we(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 ne(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 Jt,ot,Qt,Zt,en,N,nn,rn,m,g,an,p,it,q,st,at,a,ut,ln,pt,J,cn,un,Y,Se,Ie,Ne,O,pn,A,X,mn,I,C,yt,Et,gt,Oe,Ee,ge,yn,Dt,Te,Rt,At,St,te,P,Dn,Rn,An,In,h,S,Pe,x,F,f=D(()=>{"use strict";Jt={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},ot={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},Qt={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},Zt={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},en="troubleshooting",N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};nn={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},rn={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",UPLOAD:"/upload"},g={FILES:"files[]",CHECKSUMS:"checksums",LABELS:"labels",VIA:"via",PASSWORD:"password",TTL:"ttl",BUILD:"build",PRERENDER:"prerender",BUILD_COMMAND:"buildCommand",OUTPUT_DIR:"outputDir",CAPTCHA:"captcha"},an={PATH:"path",CONTENT:"content",ENCODING:"encoding",DEFAULT_ENCODING:"utf-8",ENCODINGS:["utf-8","base64"]},p={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"},it=new Set([p.Network,p.Timeout,p.Cancelled,p.File,p.Config]),q={client:new Set([p.Build,p.Business,p.Cancelled,p.Config,p.File,p.Forbidden,p.NotFound,p.RateLimit,p.Validation]),network:new Set([p.Network,p.Timeout]),auth:new Set([p.Authentication])},st=new Set(Object.values(p).filter(e=>!it.has(e))),at=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===p.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 d=await t.json();if(d&&typeof d=="object"){let c=d;typeof c.message=="string"?r=c.message:typeof c.error=="string"&&(r=c.error),o=c.details,typeof c.error=="string"&&st.has(c.error)&&(i=c.error)}}else{let d=(await t.text()).trim();d&&!d.startsWith("<")&&d.length<=at&&(r=d)}}catch{}let l=t.headers.get("retry-after");if(l!==null){let s=l.trim(),d=/^\d+$/.test(s)?Number(s):Math.ceil((Date.parse(s)-Date.now())/1e3);if(Number.isFinite(d)&&d>=0){let c=o&&typeof o=="object"?o:{};c.retryAfter===void 0&&(o={...c,retryAfter:d})}}r=r||`${n||"Request"} failed with status ${t.status}`;let u=i??(t.status===401?p.Authentication:t.status===403?p.Forbidden:t.status===429?p.RateLimit:p.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?lt(t)?e.network(`${r} failed: ${t.message}`,{cause:t}):new e(p.Api,`${r} failed: ${t.message}`):new e(p.Api,`${r} failed: Unknown error`)}static validation(t,n){return new e(p.Validation,t,400,n)}static notFound(t,n){let r=n?`${t} ${n} not found`:`${t} not found`;return new e(p.NotFound,r,404)}static forbidden(t,n){return new e(p.Forbidden,t,403,n)}static rateLimit(t="Too many requests",n){return new e(p.RateLimit,t,429,n)}static authentication(t="Authentication required",n){return new e(p.Authentication,t,401,n)}static business(t,n=400,r){return new e(p.Business,t,n,r)}static network(t,n){return new e(p.Network,t,void 0,n)}static timeout(t,n){return new e(p.Timeout,t,void 0,n)}static cancelled(t,n){return new e(p.Cancelled,t,void 0,n)}static file(t,n){return new e(p.File,t,void 0,n)}static config(t,n){return new e(p.Config,t,void 0,n)}static api(t,n=500,r){return new e(p.Api,t,n,r)}static maintenance(t,n){return new e(p.Maintenance,t,503,n)}static build(t,n){return new e(p.Build,t,422,n)}isClientError(){return q.client.has(this.type)?!0:this.status!==void 0&&this.status>=400&&this.status<500}isNetworkError(){return q.network.has(this.type)}isAuthError(){return q.auth.has(this.type)}isType(t){return this.type===t}};ut=["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"],ln=ut.map(e=>`.${e}`).join(","),pt=/[\x00-\x1f\x7f#?%\\<>"]/;J=new Set(["node_modules","package.json"]);cn="/auth",un="signing-in",Y={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Se={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Ie={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},Ne={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},O={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},pn="X-Account",A={API_KEY:Y.API_KEY,DEPLOY_TOKEN:Y.TOKEN,OAUTH:Y.OAUTH,OPAQUE:"opaque"};X="bearer ";mn={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},I="ship.json";C={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};yt={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},Et=["login","register","logout","invitations","claim","consent"],gt="admin",Oe={checkout:["upgrading","true"],portal:["billing","returned"]},Ee=e=>Oe[e].join("="),ge=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;yn={login:e=>ge("/login",e),register:e=>ge("/register",e),logout:()=>"/logout",invitation:e=>`/invitations/${e}`,claim:e=>`/claim/${e}`,consent:()=>"/consent"};Dt=e=>Et.includes(e),Te=e=>Object.hasOwn(yt,e);Rt=e=>{let t=k(e);return t.kind==="door"&&t.door==="claim"},At=e=>{let t=k(e);return t.kind==="door"&&t.door==="invitations"},St=e=>{let t=k(e);return t.kind==="account"&&t.section==="upgrade"};te="https://api.shipstatic.com",P={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Dn="SHIP_VIA",Rn=`https://my.shipstatic.com${Tt().apiKey()}`,An=4320*60;In=["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"};S={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},Pe=/^[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}});function Xn(e){oe=e}function Ct(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return oe||Ct()}var oe,v=D(()=>{"use strict";oe=null});function ze(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 V(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ie=D(()=>{"use strict"});function Ke(e,t={}){if(t.flatten===!1)return e.map(r=>({path:V(r),name:se(r)}));let n=Ut(e);return e.map(r=>{let o=V(r);if(n){let i=n.endsWith("/")?n:`${n}/`;o.startsWith(i)&&(o=o.substring(i.length))}return o||(o=se(r)),{path:o,name:se(r)}})}function Ut(e){if(!e.length)return"";let n=e.map(i=>V(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 se(e){return e.split(/[/\\]/).pop()||e}var ae=D(()=>{"use strict";ie()});function le(e,t,n){let r=t.suggestions?.[n];return r?`${e} ${r}`:e}function z(e,t){return kt.find(n=>n.broken(e,t))}var kt,b,ue=D(()=>{"use strict";f();pe();kt=[{name:"name",broken:({path:e})=>!ce(e).valid,sentence:({path:e})=>ce(e).reason??`File name "${e}" is invalid.`},{name:"extension",broken:({path:e},t)=>Re(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)=>le(`File "${e}" is too large. Maximum ${_(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>le(`Files add up to ${_(e)}. Maximum ${_(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],b={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>le(`Too many files (${e}). Maximum ${t.maxFilesCount} files allowed.`,t,"maxFilesCount")}});function ce(e){let t=o=>({valid:!1,reason:`File name "${e}" ${o}.`});if(Ae(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 fr(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(d=>({...d,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(d=>({...d,status:h.VALIDATION_FAILED,statusMessage:s.message})),validFiles:[],errors:n,warnings:[],canDeploy:!1}}let i=0;for(let s of e){let d=h.READY,c="Ready for upload";if(s.status===h.PROCESSING_ERROR)d=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){d=h.EXCLUDED,c=`File "${s.name}" is empty, so it is excluded.`,r.push({file:s.name,message:c}),o.push({...s,status:d,statusMessage:c});continue}else if(s.size<0)d=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)d=h.VALIDATION_FAILED,c="File name cannot be empty.",n.push({file:s.name||"(empty)",message:c});else if(s.name.includes("\0"))d=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},R=z(y,t);R?(d=h.VALIDATION_FAILED,c=R.sentence(y,t),n.push({file:R.name==="totalSize"?`(${e.length} files)`:s.name,message:c})):i=y.totalSize}o.push({...s,status:d,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 $t(e){return e.filter(t=>t.status===h.READY)}function hr(e){return $t(e).length>0}var pe=D(()=>{"use strict";f();ue();f()});import{isJunk as Ht}from"junk";function je(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(Ht(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(Gt.some(u=>l.toLowerCase()===u.toLowerCase()))return!1;return!0})}var Gt,de=D(()=>{"use strict";f();Gt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});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 Vt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function zt(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 qe(e){if(e instanceof Blob)return Bt(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return Vt(e);if(typeof e=="string")return zt(e);throw a.business("Invalid input for MD5 calculation")}var me=D(()=>{"use strict";f()});function Ye(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 Xe(e,t){let n=z(e,t);if(n)throw a.business(n.sentence(e,t))}function We(e,t){if(b.broken(e,t))throw a.business(b.sentence(e,t))}var fe=D(()=>{"use strict";f();ue()});async function Je(e,t={},n){let r=!!(t.build||t.prerender),o=Ke(e.map(c=>c.path),{flatten:t.pathDetect!==!1}).map(c=>c.path),i=new Set(je(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:Kt(n),s=[],d=0;for(let{source:c,deployPath:y}of l){if(u&&Ye(y,c.origin),c.size===0)continue;u&&(d+=c.size,Xe({path:y,size:c.size,totalSize:d},u));let R=await c.read(),{md5:K}=await qe(R);s.push({path:y,content:R,size:c.size,md5:K})}return u&&We(s.length,u),s}function Kt(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 Qe=D(()=>{"use strict";f();ae();de();me();fe()});var tt={};rt(tt,{processFilesForNode:()=>et});import*as T from"fs";import*as E from"path";function Ze(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=E.join(e,o),l=T.statSync(i);l.isDirectory()?n.push(...Ze(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function jt(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 qt(e){for(let t of e){let n=E.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(o=>J.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 et(e,t={},n){if(L()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");qt(e);let r=e.flatMap(u=>{let s=E.resolve(u);try{let d=T.statSync(s);return d.isDirectory()?Ze(s):[{absPath:s,size:d.size}]}catch{throw a.file(`Path does not exist: ${u}`,{filePath:u})}}),o=new Map(r.map(u=>[u.absPath,u.size])),i=ze(e.map(u=>E.resolve(u)).map(u=>{try{return T.statSync(u).isDirectory()?u:E.dirname(u)}catch{return E.dirname(u)}})),l=[...o].map(([u,s])=>({path:Yt(u,i),origin:u,size:s,read:()=>jt(u)}));return Je(l,t,n)}function Yt(e,t){if(t&&t.length>0){let n=E.relative(t,e);if(n&&typeof n=="string"&&!n.startsWith(".."))return n.replace(/\\/g,"/")}return E.basename(e)}var he=D(()=>{"use strict";f();Qe();v();ie()});f();f();f();var $=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 Nt=3e4,Lt=2,bt=300,Ot=2e3,xt=new Set([500,502,503,504]);function Pt(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 ve=3e5,_t=3e5,wt=ve+_t,H=class extends ${constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||te,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Nt,this.maxRetries=Math.max(0,n.maxRetries??Lt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??ve,buildTimeout:n.timeout??wt}}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 d=Math.min(Ot,bt*2**l);try{await Pt(Math.random()*d,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(p.Maintenance)||n.isType(p.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&xt.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 d={...r,headers:u,credentials:this.session&&!u.Authorization?"include":void 0,signal:s.signal};this.emit("request",n,d);let c=await this.fetch(n,d);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 Ce(e,t={}){let{labels:n,via:r,password:o,ttl:i,flags:l,captcha:u}=t,s=new FormData,d=[];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(g.FILES,new File([c.content],c.path,{type:"application/octet-stream"})),d.push(c.md5)}return s.append(g.CHECKSUMS,JSON.stringify(d)),n&&n.length>0&&s.append(g.LABELS,JSON.stringify(n)),r&&s.append(g.VIA,r),o&&s.append(g.PASSWORD,o),i!==void 0&&s.append(g.TTL,String(i)),l?.build&&s.append(g.BUILD,"true"),l?.prerender&&s.append(g.PRERENDER,"true"),l?.buildCommand&&s.append(g.BUILD_COMMAND,l.buildCommand),l?.outputDir&&s.append(g.OUTPUT_DIR,l.outputDir),u&&s.append(g.CAPTCHA,u),s}f();f();function w(e){if(e==null)return;if(e.length===0)return e;if(e.length>S.MAX_COUNT)throw a.validation(`Maximum ${S.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<S.MIN_LENGTH)throw a.validation(`Labels must be at least ${S.MIN_LENGTH} characters long`);if(i.length>S.MAX_LENGTH)throw a.validation(`Labels must be no more than ${S.MAX_LENGTH} characters long`);if(!Pe.test(i))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${S.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 Fe(e){let t=e.find(o=>o.path===I||o.path===`/${I}`);if(!t)return;let n=t.content,r=typeof n.text=="function"?await n.text():t.content.toString("utf8");Le(r)}var G={"Content-Type":"application/json"},vt="sdk";function re(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 Me(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);if(!l.length)throw a.business("No files to deploy");for(let j of l)if(!j.md5)throw a.file(`MD5 checksum missing for file: ${j.path}`,{filePath:j.path});ne(o.password);let u=ee(o.ttl),s=De(o.idempotencyKey),d=w(o.labels);await Fe(l);let c=_e(o.buildCommand),y=we(o.outputDir),R=o.build||o.prerender?{build:o.build,prerender:o.prerender,buildCommand:c,outputDir:y}:void 0,K=await Ce(l,{labels:d,via:o.via??vt,password:o.password,ttl:u,flags:R,captcha:o.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:K,...s?{headers:{[N.HEADER]:s}}:{},signal:o.signal||null},"Deploy",o.build||o.prerender?i.deploy.buildTimeout:i.deploy.timeout)},list:async r=>t().request(`${m.DEPLOYMENTS}${re(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:G,body:JSON.stringify({labels:w(o.labels)})},"Update deployment labels"),delete:async r=>t().request(m.DEPLOYMENT(encodeURIComponent(r)),{method:"DELETE"},"Delete deployment")}}function Ue(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:G,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:u===201}},list:async n=>t().request(`${m.DOMAINS}${re(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:G,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 $e(e){let{getApi:t}=e;return{create:async(n={})=>{let r=ee(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:G,body:JSON.stringify(i)},"Create token")},list:async n=>t().request(`${m.TOKENS}${re(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 B=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&&be(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(Z(t.token),this.credential=t.token):t.token&&(this.credential=t.token),this.http=new H({...t,getAuthHeaders:()=>this.getAuthHeaders()});let n={getApi:()=>this.http};this.deployments=Me({...n,processInput:async(r,o)=>this.processInput(r,o,await this.getLimits({signal:o.signal}))}),this.domains=Ue(n),this.account=ke(n),this.tokens=$e(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.");Z(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 Be}from"zod";import{z as He}from"zod";var Ge={apiUrl:He.string().url().optional(),token:He.string().min(1).optional()};v();var Ft=Be.object(Ge).strict(),Mt={apiUrl:P.API_URL,token:P.TOKEN};function Ve(){if(L()!=="node")return{};let e={apiUrl:process.env[P.API_URL]||void 0,token:process.env[P.TOKEN]||void 0};try{return Ft.parse(e)}catch(t){if(t instanceof Be.ZodError){let n=t.issues[0],r=n.path[0],o=(r&&Mt[r])??"SHIP environment configuration";throw a.config(`Invalid ${o}: ${n.message}`)}throw a.config("Invalid environment configuration")}}f();f();ae();v();pe();de();me();fe();function Lr(e,t,n,r=!0){let o=e===1?t:n;return r?`${e} ${o}`:o}he();var ye=class extends B{constructor(t={}){if(L()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let n=Ve();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(()=>(he(),tt));return i(o,n,r)}},Xt=ye;export{pn as ACCOUNT_HEADER,Se as API_KEY,m as API_PATHS,cn as AUTH_BASE_PATH,nn as AccountPlan,rn as AccountRefusal,H as ApiHttp,Y as AuthMethod,x as BUILD_SETTINGS,O as CALLER,te as DEFAULT_API,I as DEPLOYMENT_CONFIG_FILENAME,g as DEPLOY_FIELDS,an as DEPLOY_FILE_GRAMMAR,Ie as DEPLOY_TOKEN,Jt as DeploymentStatus,ot as DeploymentVia,Qt as DomainStatus,Zt as DomainVerification,p as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,Gt as JUNK_DIRECTORIES,S as LABEL_CONSTRAINTS,Pe as LABEL_PATTERN,Rn as MY_API_KEY_URL,Ne as OAUTH_TOKEN,mn as OAuthScope,F as PASSWORD_CONSTRAINTS,An as PUBLIC_DEPLOYMENT_TTL_SECONDS,yt as SECTIONS,en as SETUP_TROUBLESHOOTING_ANCHOR,P as SHIP_ENV,Dn as SHIP_VIA_ENV,un as SIGN_IN_RETURN_PARAM,ye as Ship,a as ShipError,C as TTL_CONSTRAINTS,A as TokenKind,J as UNBUILT_PROJECT_MARKERS,pt as UNSAFE_FILENAME_CHARS,In as USER_VISIBLE_EVENTS,ln as WEB_FILE_ACCEPT,Xn as __setTestEnvironment,gn as accountOfPath,hr as allValidFilesReady,Le as assertShipJsonSyntax,En as billingReturnOf,qe as calculateMD5,dt as classifyToken,Tt as consolePaths,ke as createAccountResource,Me as createDeploymentResource,Ue as createDomainResource,$e as createTokenResource,Xt as default,Pn as deserializeLabels,yn as doors,Tn as errandOf,Ln as extractSubdomain,je as filterJunk,It as formatDuration,_ as formatFileSize,Sn as formatTimeRemaining,bn as generateDeploymentUrl,On as generateDomainUrl,L as getENV,$t as getValidFiles,U as hasUnbuiltMarker,Ae as hasUnsafeChars,Re as isBlockedExtension,Rt as isClaimPath,Nn as isCustomDomain,hn as isDeployment,At as isInvitationPath,xe as isPlatformDomain,M as isShipError,St as isUpgradePath,tn as normalizeVia,Ke as optimizeDeployPaths,on as personName,sn as personShortName,Lr as pluralize,et as processFilesForNode,dn as readBearerValue,xn as serializeLabels,mt as validateApiKey,fn as validateApiUrl,_e as validateBuildCommand,be as validateCaller,We as validateDeployCount,Xe as validateDeployFile,Ye as validateDeployPath,ft as validateDeployToken,ce as validateFileName,fr as validateFiles,De as validateIdempotencyKey,ht as validateOAuthToken,we as validateOutputDir,ne as validatePassword,Z as validateToken,ee as validateTtl};
|
|
1
|
+
var st=Object.defineProperty;var A=(e,t)=>()=>(e&&(t=e(e=0)),t);var at=(e,t)=>{for(var n in t)st(e,n,{get:t[n],enumerable:!0})};function ln(e){if(!e||typeof e!="string")return;let t=e.trim().toLowerCase();return Object.values(lt).includes(t)?t:void 0}function De(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 un(e){return e.name?.trim()||e.email}function dn(e){return e.name?.trim().split(" ")[0]||e.email}function dt(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 mt(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 Re(e,t){let n=mt(e);return n===null?!1:Array.isArray(t)?t.includes(n):t.has(n)}function Ie(e){return ht.test(e)}function U(e){return e.replace(/\\/g,"/").split("/").filter(Boolean).some(n=>ee.has(n))}function yt(e){return e.startsWith(Ne.PREFIX)?R.API_KEY:e.startsWith(Le.PREFIX)?R.DEPLOY_TOKEN:e.startsWith(be.PREFIX)?R.OAUTH:R.OPAQUE}function gn(e){return e.slice(0,Q.length).toLowerCase()!==Q?null:e.slice(Q.length)||null}function Pe(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 te(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 Et(e){te(e,Ne,"API key")}function gt(e){te(e,Le,"Deploy token")}function Tt(e){te(e,be,"OAuth access token")}function ne(e){switch(yt(e)){case R.API_KEY:Et(e);return;case R.DEPLOY_TOKEN:gt(e);return;case R.OAUTH:Tt(e);return;case R.OPAQUE:if(!e)throw a.validation("Token must be a non-empty string")}}function xe(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 An(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 Sn(e){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(e)}function re(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<v.MIN_SECONDS||e>v.MAX_SECONDS)throw a.validation(`TTL must be between ${v.MIN_SECONDS} and ${v.MAX_SECONDS} seconds`);return e}}function Rt(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"),settingsAfterBilling:()=>n(`/settings?${Te("portal")}`),upgrade:r=>n(r?`/upgrade/${r}`:"/upgrade"),success:()=>n("/success"),successAfterCheckout:()=>n(`/success?${Te("checkout")}`),apiKey:()=>n("/api-key")}}function Rn(e){let t=new URLSearchParams(e);for(let[n,[r,o]]of Object.entries(_e))if(t.get(r)===o)return n;return null}function $(e){let t=e.split(/[?#]/)[0].toLowerCase(),[n="",r=""]=t.split("/").filter(Boolean);return It(n)?{kind:"door",door:n}:n===Dt?{kind:"admin"}:n===""||Se(n)?{kind:"account",account:null,section:n===""?null:n}:{kind:"account",account:n,section:Se(r)?r:null}}function In(e){let t=$(e);return t.kind==="account"?t.account:null}function Nn(e){return Nt(e)?"claim":Lt(e)?"invite":bt(e)?"upgrade":null}function Ot(e){let t=Math.round(e/60);if(!(t>=1))return"less than a minute";if(t<120)return Z(t,"minute");let n=Math.round(e/3600);return n<48?Z(n,"hour"):Z(Math.round(e/86400),"day")}function Pn(e,t=Date.now()/1e3){let n=e-t;return n>0?Ot(n):null}function Z(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 we(e,t){return e.endsWith(`.${t}`)}function _n(e,t){return!we(e,t)}function wn(e,t){return we(e,t)?e.slice(0,-(t.length+1)):null}function Cn(e){return`https://${e}`}function vn(e){return`https://${e}`}function Fn(e){return!e||e.length===0?null:JSON.stringify(e)}function Mn(e){if(!e)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ve(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 Fe(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 ie(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 rn,lt,on,sn,an,N,cn,pn,m,E,mn,d,ct,W,pt,ut,a,ft,fn,ht,ee,hn,yn,J,Ne,Le,be,O,En,R,Q,Tn,S,Oe,k,v,At,St,Dt,_e,Te,Ae,Dn,It,Se,Nt,Lt,bt,oe,x,Ln,bn,On,xn,h,I,Ce,P,F,f=A(()=>{"use strict";rn={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},lt={WEB:"web",SDK:"sdk",CLI:"cli",MCP:"mcp",GIT:"git",N8N:"n8n",GPT:"gpt",VSC:"vsc",CLD:"cld",CRS:"crs",GMN:"gmn",API:"api"},on={LIVE:"live",UNLINKED:"unlinked",UNVERIFIED:"unverified",PAUSED:"paused"},sn={PENDING:"pending",PARTIAL:"partial",VERIFIED:"verified"},an="troubleshooting",N={HEADER:"Idempotency-Key",MAX_LENGTH:256,WINDOW_SECONDS:1440*60};cn={FREE:"free",PRO:"pro",TEAM:"team",SCALE:"scale",SPONSORED:"sponsored"},pn={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"},mn={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"},ct=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])},pt=new Set(Object.values(d).filter(e=>!ct.has(e))),ut=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 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"&&pt.has(c.error)&&(i=c.error)}}else{let u=(await t.text()).trim();u&&!u.startsWith("<")&&u.length<=ut&&(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?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.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?dt(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}};ft=["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"],fn=ft.map(e=>`.${e}`).join(","),ht=/[\x00-\x1f\x7f#?%\\<>"]/;ee=new Set(["node_modules","package.json"]);hn="/auth",yn="signing-in",J={SESSION:"session",API_KEY:"apiKey",TOKEN:"token",AGENT:"agent",OAUTH:"oauth",SYSTEM:"system"},Ne={PREFIX:"ship-",HEX_LENGTH:32,TOTAL_LENGTH:37,HINT_LENGTH:4},Le={PREFIX:"deploy-",HEX_LENGTH:32,TOTAL_LENGTH:39},be={PREFIX:"oauth-",HEX_LENGTH:32,TOTAL_LENGTH:38},O={HEADER:"X-Caller",MAX_LENGTH:128,PATTERN:/^[a-zA-Z0-9._-]+$/},En="X-Account",R={API_KEY:J.API_KEY,DEPLOY_TOKEN:J.TOKEN,OAUTH:J.OAUTH,OPAQUE:"opaque"};Q="bearer ";Tn={ACCOUNT_READ:"account:read",DEPLOYMENTS_READ:"deployments:read",DEPLOYMENTS_WRITE:"deployments:write",DOMAINS_READ:"domains:read",DOMAINS_WRITE:"domains:write"},S="ship.json",Oe={rewrites:[{source:"/(.*)",destination:"/index.html"}]},k={INDEX_FILE:"index.html",MAX_INDEX_BYTES:100*1024};v={MIN_SECONDS:1,MAX_SECONDS:365*24*60*60};At={new:{owner:!1},deployments:{owner:!1},domains:{owner:!1},settings:{owner:!1},upgrade:{owner:!0},success:{owner:!0},"api-key":{owner:!0}},St=["login","register","logout","invitations","claim","consent"],Dt="admin",_e={checkout:["upgrading","true"],portal:["billing","returned"]},Te=e=>_e[e].join("="),Ae=(e,t)=>t?`${e}?next=${encodeURIComponent(t)}`:e;Dn={login:e=>Ae("/login",e),register:e=>Ae("/register",e),logout:()=>"/logout",invitation:e=>`/invitations/${e}`,claim:e=>`/claim/${e}`,consent:()=>"/consent"};It=e=>St.includes(e),Se=e=>Object.hasOwn(At,e);Nt=e=>{let t=$(e);return t.kind==="door"&&t.door==="claim"},Lt=e=>{let t=$(e);return t.kind==="door"&&t.door==="invitations"},bt=e=>{let t=$(e);return t.kind==="account"&&t.section==="upgrade"};oe="https://api.shipstatic.com",x={TOKEN:"SHIP_TOKEN",API_URL:"SHIP_API_URL"},Ln="SHIP_VIA",bn=`https://my.shipstatic.com${Rt().apiKey()}`,On=4320*60;xn=["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:"._-"},Ce=/^[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 Ut(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 kt(e){let{createHash:t}=await import("crypto"),n=t("md5");return n.update(e),{md5:n.digest("hex")}}async function $t(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 Ut(e);if(typeof Buffer<"u"&&Buffer.isBuffer(e))return kt(e);if(typeof e=="string")return $t(e);throw a.business("Invalid input for MD5 calculation")}var z=A(()=>{"use strict";f()});function ar(e){ae=e}function zt(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function L(){return ae||zt()}var ae,C=A(()=>{"use strict";ae=null});function Xe(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 le=A(()=>{"use strict"});function Ye(e,t={}){if(t.flatten===!1)return e.map(r=>({path:j(r),name:ce(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=ce(r)),{path:o,name:ce(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(p=>p[i]===l))r.push(l);else break}return r.join("/")}function ce(e){return e.split(/[/\\]/).pop()||e}var pe=A(()=>{"use strict";le()});function ue(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,me=A(()=>{"use strict";f();fe();qt=[{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)=>Re(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)=>ue(`File "${e}" is too large. Maximum ${_(t.maxFileSize)} allowed.`,t,"maxFileSize")},{name:"totalSize",broken:({totalSize:e},t)=>e>t.maxTotalSize,sentence:({totalSize:e},t)=>ue(`Files add up to ${_(e)}. Maximum ${_(t.maxTotalSize)} allowed.`,t,"maxTotalSize")}],b={name:"filesCount",broken:(e,t)=>e>t.maxFilesCount,sentence:(e,t)=>ue(`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(Ie(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 Lr(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(b.broken(e.length,t)){let s={file:`(${e.length} files)`,message:b.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},D=q(y,t);D?(u=h.VALIDATION_FAILED,c=D.sentence(y,t),n.push({file:D.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 Xt(e){return e.filter(t=>t.status===h.READY)}function br(e){return Xt(e).length>0}var fe=A(()=>{"use strict";f();me();f()});import{isJunk as Yt}from"junk";function We(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(Yt(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(Wt.some(p=>l.toLowerCase()===p.toLowerCase()))return!1;return!0})}var Wt,he=A(()=>{"use strict";f();Wt=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Je(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 Qe(e,t){let n=q(e,t);if(n)throw a.business(n.sentence(e,t))}function Ze(e,t){if(b.broken(e,t))throw a.business(b.sentence(e,t))}var ye=A(()=>{"use strict";f();me()});async function et(e,t={},n){let r=!!(t.build||t.prerender),o=Ye(e.map(c=>c.path),{flatten:t.pathDetect!==!1}).map(c=>c.path),i=new Set(We(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:Jt(n),s=[],u=0;for(let{source:c,deployPath:y}of l){if(p&&Je(y,c.origin),c.size===0)continue;p&&(u+=c.size,Qe({path:y,size:c.size,totalSize:u},p));let D=await c.read(),{md5:X}=await B(D);s.push({path:y,content:D,size:c.size,md5:X})}return p&&Ze(s.length,p),s}function Jt(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 tt=A(()=>{"use strict";f();pe();he();z();ye()});var ot={};at(ot,{processFilesForNode:()=>rt});import*as T from"fs";import*as g from"path";function nt(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(...nt(i,t)):l.isFile()&&n.push({absPath:i,size:l.size})}return n}async function Qt(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 Zt(e){for(let t of e){let n=g.resolve(t);try{if(T.statSync(n).isDirectory()){let r=T.readdirSync(n).find(o=>ee.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 rt(e,t={},n){if(L()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");Zt(e);let r=e.flatMap(p=>{let s=g.resolve(p);try{let u=T.statSync(s);return u.isDirectory()?nt(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=Xe(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:en(p,i),origin:p,size:s,read:()=>Qt(p)}));return et(l,t,n)}function en(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 Ee=A(()=>{"use strict";f();tt();C();le()});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 Pt=3e4,xt=2,_t=300,wt=2e3,Ct=new Set([500,502,503,504]);function vt(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 Me=3e5,Ft=3e5,Mt=Me+Ft,G=class extends H{constructor(n){super();this.globalHeaders={};this.apiUrl=n.apiUrl||oe,this.getAuthHeadersCallback=n.getAuthHeaders,this.session=n.session??!1,this.caller=n.caller,this.timeout=n.timeout??Pt,this.maxRetries=Math.max(0,n.maxRetries??xt),this.fetch=n.fetch??globalThis.fetch.bind(globalThis),this.deploy={endpoint:n.deployEndpoint||m.DEPLOYMENTS,timeout:n.timeout??Me,buildTimeout:n.timeout??Mt}}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(wt,_t*2**l);try{await vt(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(d.Maintenance)||n.isType(d.Cancelled)||!(n.isNetworkError()||n.status!==void 0&&Ct.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?{[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 Ue(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 Ht(){let e=JSON.stringify(Oe,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 Gt(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(m.SPA_CHECK,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),signal:n??null},"SPA check")).isSPA}async function ke(e,t,n){if(n.spaDetect===!1||n.spa||n.build||n.prerender||e.some(r=>r.path===S))return e;try{if(await Gt(e,t,n.signal)){let o=await Ht();return[...e,o]}}catch(r){if(n.signal?.aborted)throw r}return 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(!Ce.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 $e(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");Pe(r)}var V={"Content-Type":"application/json"},Bt="sdk";function se(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 He(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 ke(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});ie(o.password);let s=re(o.ttl),u=De(o.idempotencyKey),c=w(o.labels);await $e(p);let y=ve(o.buildCommand),D=Fe(o.outputDir),X=o.build||o.prerender||o.spa?{build:o.build,prerender:o.prerender,spa:o.spa,buildCommand:y,outputDir:D}:void 0,it=await Ue(p,{labels:c,via:o.via??Bt,password:o.password,ttl:s,flags:X,captcha:o.captcha});return i.request(i.deploy.endpoint,{method:"POST",body:it,...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(`${m.DEPLOYMENTS}${se(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 Ge(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:p}=await t().requestWithStatus(m.DOMAIN(encodeURIComponent(n)),{method:"PUT",headers:V,body:JSON.stringify(i)},"Set domain");return{...l,isCreate:p===201}},list:async n=>t().request(`${m.DOMAINS}${se(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 Be(e){let{getApi:t}=e;return{get:async()=>t().request(m.ACCOUNT,{method:"GET"},"Get account")}}function ze(e){let{getApi:t}=e;return{create:async(n={})=>{let r=re(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}${se(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&&xe(t.caller),t.token&&t.session)throw a.config("Provide either `token` or `session`, not both.");typeof t.token=="string"?(ne(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=He({...n,processInput:async(r,o)=>this.processInput(r,o,await this.getLimits({signal:o.signal}))}),this.domains=Ge(n),this.account=Be(n),this.tokens=ze(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.");ne(t),this.credential=t;return}if(typeof t!="function")throw a.business("Invalid token provided. Token must be a non-empty string or a provider function.");this.credential=t}async getAuthHeaders(){if(this.credential===null)return{};let t=typeof this.credential=="function"?await this.credential():this.credential;if(!t)throw a.authentication("Token provider returned no token.");if(typeof t!="string")throw a.authentication("Token provider returned a non-string value.");return{Authorization:`Bearer ${t}`}}};C();f();import{z as je}from"zod";import{z as Ve}from"zod";var Ke={apiUrl:Ve.string().url().optional(),token:Ve.string().min(1).optional()};C();var Vt=je.object(Ke).strict(),Kt={apiUrl:x.API_URL,token:x.TOKEN};function qe(){if(L()!=="node")return{};let e={apiUrl:process.env[x.API_URL]||void 0,token:process.env[x.TOKEN]||void 0};try{return Vt.parse(e)}catch(t){if(t instanceof je.ZodError){let n=t.issues[0],r=n.path[0],o=(r&&Kt[r])??"SHIP environment configuration";throw a.config(`Invalid ${o}: ${n.message}`)}throw a.config("Invalid environment configuration")}}f();f();pe();C();fe();he();z();ye();function Mr(e,t,n,r=!0){let o=e===1?t:n;return r?`${e} ${o}`:o}Ee();var ge=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=qe();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(()=>(Ee(),ot));return i(o,n,r)}},tn=ge;export{En as ACCOUNT_HEADER,Ne as API_KEY,m as API_PATHS,hn as AUTH_BASE_PATH,cn as AccountPlan,pn as AccountRefusal,G as ApiHttp,J as AuthMethod,P as BUILD_SETTINGS,O as CALLER,oe as DEFAULT_API,S as DEPLOYMENT_CONFIG_FILENAME,E as DEPLOY_FIELDS,mn as DEPLOY_FILE_GRAMMAR,Le as DEPLOY_TOKEN,rn as DeploymentStatus,lt as DeploymentVia,on as DomainStatus,sn as DomainVerification,d as ErrorType,h as FILE_VALIDATION_STATUS,h as FileValidationStatus,N as IDEMPOTENCY_KEY_CONSTRAINTS,Wt as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,Ce as LABEL_PATTERN,bn as MY_API_KEY_URL,be as OAUTH_TOKEN,Tn as OAuthScope,F as PASSWORD_CONSTRAINTS,On as PUBLIC_DEPLOYMENT_TTL_SECONDS,At as SECTIONS,an as SETUP_TROUBLESHOOTING_ANCHOR,x as SHIP_ENV,Ln as SHIP_VIA_ENV,yn as SIGN_IN_RETURN_PARAM,k as SPA_CHECK_CONSTRAINTS,Oe as SPA_DEFAULT_CONFIG,ge as Ship,a as ShipError,v as TTL_CONSTRAINTS,R as TokenKind,ee as UNBUILT_PROJECT_MARKERS,ht as UNSAFE_FILENAME_CHARS,xn as USER_VISIBLE_EVENTS,fn as WEB_FILE_ACCEPT,ar as __setTestEnvironment,In as accountOfPath,br as allValidFilesReady,Pe as assertShipJsonSyntax,Rn as billingReturnOf,B as calculateMD5,yt as classifyToken,Rt as consolePaths,Be as createAccountResource,He as createDeploymentResource,Ge as createDomainResource,ze as createTokenResource,tn as default,Mn as deserializeLabels,Dn as doors,Nn as errandOf,wn as extractSubdomain,We as filterJunk,Ot as formatDuration,_ as formatFileSize,Pn as formatTimeRemaining,Cn as generateDeploymentUrl,vn as generateDomainUrl,L as getENV,Xt as getValidFiles,U as hasUnbuiltMarker,Ie as hasUnsafeChars,Re as isBlockedExtension,Nt as isClaimPath,_n as isCustomDomain,Sn as isDeployment,Lt as isInvitationPath,we as isPlatformDomain,M as isShipError,bt as isUpgradePath,ln as normalizeVia,Ye as optimizeDeployPaths,un as personName,dn as personShortName,Mr as pluralize,rt as processFilesForNode,gn as readBearerValue,Fn as serializeLabels,Et as validateApiKey,An as validateApiUrl,ve as validateBuildCommand,xe as validateCaller,Ze as validateDeployCount,Qe as validateDeployFile,Je as validateDeployPath,gt as validateDeployToken,de as validateFileName,Lr as validateFiles,De as validateIdempotencyKey,Tt as validateOAuthToken,Fe as validateOutputDir,ie as validatePassword,ne as validateToken,re as validateTtl};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|