@shipstatic/ship 0.9.5 → 1.0.0
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 +66 -20
- package/SKILL.md +21 -4
- package/dist/browser.d.ts +21 -5
- package/dist/browser.js +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +12 -12
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.fish +1 -1
- package/dist/completions/ship.zsh +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -5
- package/dist/index.d.ts +21 -5
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -76,6 +76,8 @@ interface DeployBodyContext {
|
|
|
76
76
|
* Implemented differently for Node.js and Browser.
|
|
77
77
|
*/
|
|
78
78
|
type DeployBodyCreator = (files: StaticFile[], context?: DeployBodyContext) => Promise<DeployBody>;
|
|
79
|
+
/** Standard `fetch` signature — the type of the `fetch` client option. */
|
|
80
|
+
type Fetch = typeof fetch;
|
|
79
81
|
/**
|
|
80
82
|
* Options for configuring a `Ship` instance.
|
|
81
83
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -85,7 +87,7 @@ interface ShipClientOptions {
|
|
|
85
87
|
apiUrl?: string | undefined;
|
|
86
88
|
/** API key for authenticated deployments (format: ship-<64-char-hex>, total 69 chars). */
|
|
87
89
|
apiKey?: string | undefined;
|
|
88
|
-
/** Deploy token for
|
|
90
|
+
/** Deploy token for authenticated deployments (format: token-<64-char-hex>, total 70 chars). */
|
|
89
91
|
deployToken?: string | undefined;
|
|
90
92
|
/**
|
|
91
93
|
* Default callback for deploy progress for deploys made with this client.
|
|
@@ -112,6 +114,14 @@ interface ShipClientOptions {
|
|
|
112
114
|
* to proceed with cookie-based credentials.
|
|
113
115
|
*/
|
|
114
116
|
useCredentials?: boolean | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Custom `fetch` implementation. Defaults to `globalThis.fetch`.
|
|
119
|
+
*
|
|
120
|
+
* Use to inject a Cloudflare service-binding `Fetcher`
|
|
121
|
+
* (`env.API.fetch.bind(env.API)`) for Worker-to-Worker calls, to wrap
|
|
122
|
+
* requests with tracing/retries/signing, or to mock in tests.
|
|
123
|
+
*/
|
|
124
|
+
fetch?: Fetch | undefined;
|
|
115
125
|
/**
|
|
116
126
|
* Default caller identifier for multi-tenant deployments.
|
|
117
127
|
* Alphanumeric characters, dots, underscores, and hyphens allowed (max 128 chars).
|
|
@@ -119,9 +129,14 @@ interface ShipClientOptions {
|
|
|
119
129
|
* Used by orchestrators (e.g. n8n nodes processing many tenants from one
|
|
120
130
|
* worker) so the API's rate-limit bucket keys per caller rather than per
|
|
121
131
|
* shared IP. **Programmatic-only by design** — there is no `--caller`
|
|
122
|
-
* CLI flag because
|
|
123
|
-
*
|
|
124
|
-
*
|
|
132
|
+
* CLI flag because every CLI invocation belongs to one human; a per-tenant
|
|
133
|
+
* rate-limit bucket would defeat the purpose.
|
|
134
|
+
*
|
|
135
|
+
* Distinct from `via` (the client identifier — `'cli'`, `'sdk'`, `'web'`,
|
|
136
|
+
* `'git'`, etc.). `via` is for analytics/origin tracking and is
|
|
137
|
+
* env-overridable via `SHIP_VIA` for integrations that wrap the CLI
|
|
138
|
+
* (GitHub Action, MCP). `caller` is for rate-limit isolation and stays
|
|
139
|
+
* programmatic-only.
|
|
125
140
|
*/
|
|
126
141
|
caller?: string | undefined;
|
|
127
142
|
/**
|
|
@@ -190,6 +205,7 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
190
205
|
private readonly getAuthHeadersCallback;
|
|
191
206
|
private readonly useCredentials;
|
|
192
207
|
private readonly timeout;
|
|
208
|
+
private readonly fetch;
|
|
193
209
|
private readonly createDeployBody;
|
|
194
210
|
private readonly deployEndpoint;
|
|
195
211
|
private globalHeaders;
|
|
@@ -694,4 +710,4 @@ declare class Ship extends Ship$1 {
|
|
|
694
710
|
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
695
711
|
}
|
|
696
712
|
|
|
697
|
-
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
|
713
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, type Fetch, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
package/dist/index.d.ts
CHANGED
|
@@ -76,6 +76,8 @@ interface DeployBodyContext {
|
|
|
76
76
|
* Implemented differently for Node.js and Browser.
|
|
77
77
|
*/
|
|
78
78
|
type DeployBodyCreator = (files: StaticFile[], context?: DeployBodyContext) => Promise<DeployBody>;
|
|
79
|
+
/** Standard `fetch` signature — the type of the `fetch` client option. */
|
|
80
|
+
type Fetch = typeof fetch;
|
|
79
81
|
/**
|
|
80
82
|
* Options for configuring a `Ship` instance.
|
|
81
83
|
* Sets default API host, authentication credentials, progress callbacks, concurrency, and timeouts for the client.
|
|
@@ -85,7 +87,7 @@ interface ShipClientOptions {
|
|
|
85
87
|
apiUrl?: string | undefined;
|
|
86
88
|
/** API key for authenticated deployments (format: ship-<64-char-hex>, total 69 chars). */
|
|
87
89
|
apiKey?: string | undefined;
|
|
88
|
-
/** Deploy token for
|
|
90
|
+
/** Deploy token for authenticated deployments (format: token-<64-char-hex>, total 70 chars). */
|
|
89
91
|
deployToken?: string | undefined;
|
|
90
92
|
/**
|
|
91
93
|
* Default callback for deploy progress for deploys made with this client.
|
|
@@ -112,6 +114,14 @@ interface ShipClientOptions {
|
|
|
112
114
|
* to proceed with cookie-based credentials.
|
|
113
115
|
*/
|
|
114
116
|
useCredentials?: boolean | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Custom `fetch` implementation. Defaults to `globalThis.fetch`.
|
|
119
|
+
*
|
|
120
|
+
* Use to inject a Cloudflare service-binding `Fetcher`
|
|
121
|
+
* (`env.API.fetch.bind(env.API)`) for Worker-to-Worker calls, to wrap
|
|
122
|
+
* requests with tracing/retries/signing, or to mock in tests.
|
|
123
|
+
*/
|
|
124
|
+
fetch?: Fetch | undefined;
|
|
115
125
|
/**
|
|
116
126
|
* Default caller identifier for multi-tenant deployments.
|
|
117
127
|
* Alphanumeric characters, dots, underscores, and hyphens allowed (max 128 chars).
|
|
@@ -119,9 +129,14 @@ interface ShipClientOptions {
|
|
|
119
129
|
* Used by orchestrators (e.g. n8n nodes processing many tenants from one
|
|
120
130
|
* worker) so the API's rate-limit bucket keys per caller rather than per
|
|
121
131
|
* shared IP. **Programmatic-only by design** — there is no `--caller`
|
|
122
|
-
* CLI flag because
|
|
123
|
-
*
|
|
124
|
-
*
|
|
132
|
+
* CLI flag because every CLI invocation belongs to one human; a per-tenant
|
|
133
|
+
* rate-limit bucket would defeat the purpose.
|
|
134
|
+
*
|
|
135
|
+
* Distinct from `via` (the client identifier — `'cli'`, `'sdk'`, `'web'`,
|
|
136
|
+
* `'git'`, etc.). `via` is for analytics/origin tracking and is
|
|
137
|
+
* env-overridable via `SHIP_VIA` for integrations that wrap the CLI
|
|
138
|
+
* (GitHub Action, MCP). `caller` is for rate-limit isolation and stays
|
|
139
|
+
* programmatic-only.
|
|
125
140
|
*/
|
|
126
141
|
caller?: string | undefined;
|
|
127
142
|
/**
|
|
@@ -190,6 +205,7 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
190
205
|
private readonly getAuthHeadersCallback;
|
|
191
206
|
private readonly useCredentials;
|
|
192
207
|
private readonly timeout;
|
|
208
|
+
private readonly fetch;
|
|
193
209
|
private readonly createDeployBody;
|
|
194
210
|
private readonly deployEndpoint;
|
|
195
211
|
private globalHeaders;
|
|
@@ -694,4 +710,4 @@ declare class Ship extends Ship$1 {
|
|
|
694
710
|
protected getDeployBodyCreator(): DeployBodyCreator;
|
|
695
711
|
}
|
|
696
712
|
|
|
697
|
-
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
|
713
|
+
export { type ApiDeployOptions, ApiHttp, type ApiHttpOptions, type DeployBody, type DeployBodyContext, type DeployBodyCreator, type DeployFile, type DeploymentOptions, type DeploymentResourceContext, type ExecutionEnvironment, type Fetch, JUNK_DIRECTORIES, type MD5Result, type ResourceContext, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getENV, getValidFiles, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, validateDeployFile, validateDeployPath, validateFileName, validateFiles };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ne=Object.defineProperty;var v=(n,t)=>()=>(n&&(t=n(n=0)),t);var Ce=(n,t)=>{for(var e in t)Ne(n,e,{get:t[e],enumerable:!0})};function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return ke.has(e)}function oe(n){return $e.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>j.has(e))}function et(n){if(!n.startsWith(x.PREFIX))throw a.validation(`API key must start with "${x.PREFIX}"`);if(n.length!==x.TOTAL_LENGTH)throw a.validation(`API key must be ${x.TOTAL_LENGTH} characters total (${x.PREFIX} + ${x.HEX_LENGTH} hex chars)`);let t=n.slice(x.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${x.HEX_LENGTH} hexadecimal characters after "${x.PREFIX}" prefix`)}function tt(n){if(!n.startsWith(I.PREFIX))throw a.validation(`Deploy token must start with "${I.PREFIX}"`);if(n.length!==I.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${I.TOTAL_LENGTH} characters total (${I.PREFIX} + ${I.HEX_LENGTH} hex chars)`);let t=n.slice(I.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${I.HEX_LENGTH} hexadecimal characters after "${I.PREFIX}" prefix`)}function nt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw N(t)?t:a.validation("API URL must be a valid URL")}}function it(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function le(n,t){return n.endsWith(`.${t}`)}function rt(n,t){return!le(n,t)}function st(n,t){return le(n,t)?n.slice(0,-(t.length+1)):null}function ot(n){return`https://${n}`}function at(n){return`https://${n}`}function lt(n){return!n||n.length===0?null:JSON.stringify(n)}function pt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}var We,Je,Qe,d,Fe,V,Oe,a,ke,$e,j,x,I,Ze,q,ae,_,g,b,pe,O,E=v(()=>{"use strict";We={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Qe={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Fe=new Set([d.Network,d.Cancelled,d.File,d.Config]),V={client:new Set([d.Business,d.Config,d.File,d.Forbidden,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Oe=new Set(Object.values(d).filter(n=>!Fe.has(n))),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Oe.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new n(p,i,t.status,r)}static fromFetchError(t,e){if(N(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static forbidden(t,e){return new n(d.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(d.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400,i){return new n(d.Business,t,e,i)}static network(t,e){return new n(d.Network,t,void 0,e)}static cancelled(t,e){return new n(d.Cancelled,t,void 0,e)}static file(t,e){return new n(d.File,t,void 0,e)}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500,i){return new n(d.Api,t,e,i)}isClientError(){return V.client.has(this.type)}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isType(t){return this.type===t}};ke=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);$e=/[\x00-\x1f\x7f#?%\\<>"]/;j=new Set(["node_modules","package.json"]);x={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},I={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Ze={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},q="ship.json",ae={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={PENDING:"pending",PROCESSING_ERROR:"processing_error",EXCLUDED:"excluded",VALIDATION_FAILED:"validation_failed",READY:"ready"};b={MIN_LENGTH:3,MAX_LENGTH:25,MAX_COUNT:10,SEPARATORS:"._-"},pe=/^[a-z0-9]+(?:[._-][a-z0-9]+)*$/;O={MIN_LENGTH:6,MAX_LENGTH:128}});function St(n){X=n}function _e(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return X||_e()}var X,C=v(()=>{"use strict";X=null});async function Me(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),p=0,c=new t.ArrayBuffer,o=new FileReader,l=()=>{let u=p*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),p++,p<s?l():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},l()})}async function Be(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,r)=>{let s=t.createHash("md5"),p=e.createReadStream(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=P();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Me(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Be(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var z=v(()=>{"use strict";C();E()});import{isJunk as Ge}from"junk";function Ae(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(Ge(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Ve.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ve,W=v(()=>{"use strict";E();Ve=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var J=v(()=>{"use strict"});function Re(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Q(i)}));let e=je(n);return n.map(i=>{let r=G(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Q(i)),{path:r,name:Q(i)}})}function je(n){if(!n.length)return"";let e=n.map(s=>G(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function Q(n){return n.split(/[/\\]/).pop()||n}var Z=v(()=>{"use strict";J()});function ee(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function te(n){if(oe(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function tn(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=g.READY,u="Ready for upload",h=o.name?te(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)l=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(l=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=g.VALIDATION_FAILED,u=`File size (${ee(o.size)}) exceeds limit of ${ee(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${ee(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function qe(n){return n.filter(t=>t.status===g.READY)}function nn(n){return qe(n).length>0}var ne=v(()=>{"use strict";E()});function ve(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function xe(n,t){let e=te(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var ie=v(()=>{"use strict";E();ne()});var Pe={};Ce(Pe,{processFilesForNode:()=>be});import*as S from"fs";import*as T from"path";function Ie(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=Ie(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function be(n,t={},e){if(P()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=T.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>j.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(N(A))throw A}}let i=n.flatMap(m=>{let y=T.resolve(m);try{return S.statSync(y).isDirectory()?Ie(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,{filePath:m})}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=we(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let y=T.relative(p,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(m)}),l=Re(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(Ae(l));if(u.size===0)return[];let h=[],L=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(h.push(r[m]),L.push(l[m]));let R=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<h.length;m++){let y=h[m],A=L[m];try{ve(A,y);let w=S.statSync(y);if(w.size===0)continue;if(xe(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let F=S.readFileSync(y),{md5:Le}=await H(F);R.push({path:A,content:F,size:F.length,md5:Le})}catch(w){if(N(w))throw w;let F=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${F}`,{filePath:y})}}if(R.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return R}var re=v(()=>{"use strict";C();z();W();ie();E();Z();J()});E();E();var M=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};E();function ce(n){if(n!=null){if(typeof n!="string")throw a.validation("Password must be a string");if(n.length<O.MIN_LENGTH||n.length>O.MAX_LENGTH)throw a.validation(`Password must be between ${O.MIN_LENGTH} and ${O.MAX_LENGTH} characters`)}}function k(n){if(n==null)return;if(n.length===0)return n;if(n.length>b.MAX_COUNT)throw a.validation(`Maximum ${b.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<b.MIN_LENGTH)throw a.validation(`Labels must be at least ${b.MIN_LENGTH} characters long`);if(s.length>b.MAX_LENGTH)throw a.validation(`Labels must be no more than ${b.MAX_LENGTH} characters long`);if(!pe.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${b.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},Ue=3e4,B=class extends M{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??Ue,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,r);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,{filePath:l.path});ce(i.password);let r=k(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=k(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=k(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=k(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(l=>l.path==="index.html"||l.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function ue(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function de(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}E();E();z();async function He(){let n=JSON.stringify(ae,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:q,content:t,size:n.length,md5:e}}async function me(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===q))return n;try{if(await t.checkSPA(n,e)){let r=await He();return[...n,r]}}catch{}return n}function fe(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?de(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:L}=await h.fetchAgentToken();o.deployToken=L}catch(h){throw N(h)&&h.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await me(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function he(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function ye(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ge(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var K=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...ue(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=fe({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=he(e),this.account=ye(e),this.tokens=ge(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();C();E();C();import{z as De}from"zod";import{z as Y}from"zod";var Ee={apiUrl:Y.string().url().optional(),apiKey:Y.string().min(1).optional(),deployToken:Y.string().min(1).optional()};var ze=De.object(Ee).strict(),Ke={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Se(){if(P()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return ze.parse(n)}catch(t){if(t instanceof De.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&Ke[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Te(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,{filePath:D.path});if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,{filePath:D.path});let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let h=new r(l),L=[];for await(let D of h.encode())L.push(Buffer.from(D));let R=Buffer.concat(L);return{body:R.buffer.slice(R.byteOffset,R.byteOffset+R.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(R).toString()}}}z();function jt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}W();Z();C();ne();ie();E();re();var se=class extends K{constructor(t={}){if(P()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Se();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(re(),Pe));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Te}},Xe=se;export{x as API_KEY,Qe as AccountPlan,B as ApiHttp,Ze as AuthMethod,ke as BLOCKED_EXTENSIONS,_ as DEFAULT_API,q as DEPLOYMENT_CONFIG_FILENAME,I as DEPLOY_TOKEN,We as DeploymentStatus,Je as DomainStatus,d as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Ve as JUNK_DIRECTORIES,b as LABEL_CONSTRAINTS,pe as LABEL_PATTERN,O as PASSWORD_CONSTRAINTS,ae as SPA_DEFAULT_CONFIG,se as Ship,a as ShipError,j as UNBUILT_PROJECT_MARKERS,$e as UNSAFE_FILENAME_CHARS,St as __setTestEnvironment,nn as allValidFilesReady,H as calculateMD5,ye as createAccountResource,fe as createDeploymentResource,he as createDomainResource,ge as createTokenResource,Xe as default,pt as deserializeLabels,st as extractSubdomain,Ae as filterJunk,ee as formatFileSize,ot as generateDeploymentUrl,at as generateDomainUrl,P as getENV,qe as getValidFiles,U as hasUnbuiltMarker,oe as hasUnsafeChars,$ as isBlockedExtension,rt as isCustomDomain,it as isDeployment,le as isPlatformDomain,N as isShipError,de as mergeDeployOptions,Re as optimizeDeployPaths,jt as pluralize,be as processFilesForNode,ue as resolveConfig,lt as serializeLabels,et as validateApiKey,nt as validateApiUrl,xe as validateDeployFile,ve as validateDeployPath,tt as validateDeployToken,te as validateFileName,tn as validateFiles};
|
|
1
|
+
var Ne=Object.defineProperty;var v=(n,t)=>()=>(n&&(t=n(n=0)),t);var Fe=(n,t)=>{for(var e in t)Ne(n,e,{get:t[e],enumerable:!0})};function N(n){return n!==null&&typeof n=="object"&&"name"in n&&n.name==="ShipError"&&"status"in n}function $(n){let t=n.lastIndexOf(".");if(t===-1||t===n.length-1)return!1;let e=n.slice(t+1).toLowerCase();return ke.has(e)}function ae(n){return $e.test(n)}function U(n){return n.replace(/\\/g,"/").split("/").filter(Boolean).some(e=>j.has(e))}function et(n){if(!n.startsWith(x.PREFIX))throw a.validation(`API key must start with "${x.PREFIX}"`);if(n.length!==x.TOTAL_LENGTH)throw a.validation(`API key must be ${x.TOTAL_LENGTH} characters total (${x.PREFIX} + ${x.HEX_LENGTH} hex chars)`);let t=n.slice(x.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`API key must contain ${x.HEX_LENGTH} hexadecimal characters after "${x.PREFIX}" prefix`)}function tt(n){if(!n.startsWith(b.PREFIX))throw a.validation(`Deploy token must start with "${b.PREFIX}"`);if(n.length!==b.TOTAL_LENGTH)throw a.validation(`Deploy token must be ${b.TOTAL_LENGTH} characters total (${b.PREFIX} + ${b.HEX_LENGTH} hex chars)`);let t=n.slice(b.PREFIX.length);if(!/^[a-f0-9]{64}$/i.test(t))throw a.validation(`Deploy token must contain ${b.HEX_LENGTH} hexadecimal characters after "${b.PREFIX}" prefix`)}function nt(n){try{let t=new URL(n);if(!["http:","https:"].includes(t.protocol))throw a.validation("API URL must use http:// or https:// protocol");if(t.pathname!=="/"&&t.pathname!=="")throw a.validation("API URL must not contain a path");if(t.search||t.hash)throw a.validation("API URL must not contain query parameters or fragments")}catch(t){throw N(t)?t:a.validation("API URL must be a valid URL")}}function it(n){return/^[a-z]+-[a-z]+-[a-z0-9]{7}(\.[a-z0-9.-]+)?$/i.test(n)}function pe(n,t){return n.endsWith(`.${t}`)}function rt(n,t){return!pe(n,t)}function st(n,t){return pe(n,t)?n.slice(0,-(t.length+1)):null}function ot(n){return`https://${n}`}function at(n){return`https://${n}`}function lt(n){return!n||n.length===0?null:JSON.stringify(n)}function pt(n){if(!n)return[];try{let t=JSON.parse(n);return Array.isArray(t)?t:[]}catch{return[]}}function X(n){if(n==null)return;if(typeof n!="string")throw a.validation("Password must be a string");let t=n.trim();if(t.length<k.MIN_LENGTH||t.length>k.MAX_LENGTH)throw a.validation(`Password must be between ${k.MIN_LENGTH} and ${k.MAX_LENGTH} characters`);return t}var We,Je,Qe,d,Ce,V,Oe,a,ke,$e,j,x,b,Ze,q,le,_,g,I,ce,k,E=v(()=>{"use strict";We={PENDING:"pending",SUCCESS:"success",FAILED:"failed",DELETING:"deleting"},Je={PENDING:"pending",PARTIAL:"partial",SUCCESS:"success",PAUSED:"paused"},Qe={FREE:"free",STANDARD:"standard",SPONSORED:"sponsored",ENTERPRISE:"enterprise",SUSPENDED:"suspended",TERMINATING:"terminating",TERMINATED:"terminated"},d={Validation:"validation_failed",NotFound:"not_found",Forbidden:"forbidden",RateLimit:"rate_limit_exceeded",Authentication:"authentication_failed",Business:"business_logic_error",Api:"internal_server_error",Network:"network_error",Cancelled:"operation_cancelled",File:"file_error",Config:"config_error"},Ce=new Set([d.Network,d.Cancelled,d.File,d.Config]),V={client:new Set([d.Business,d.Config,d.File,d.Forbidden,d.Validation]),network:new Set([d.Network]),auth:new Set([d.Authentication])},Oe=new Set(Object.values(d).filter(n=>!Ce.has(n))),a=class n extends Error{type;status;details;constructor(t,e,i,r){super(e),this.type=t,this.status=i,this.details=r,this.name="ShipError"}toResponse(){let t=this.details,e=this.type===d.Authentication&&t?.internal?void 0:this.details;return{error:this.type,message:this.message,status:this.status,details:e}}static async fromHttpResponse(t,e){let i,r,s;try{if(t.headers.get("content-type")?.includes("application/json")){let o=await t.json();if(o&&typeof o=="object"){let l=o;typeof l.message=="string"?i=l.message:typeof l.error=="string"&&(i=l.error),r=l.details,typeof l.error=="string"&&Oe.has(l.error)&&(s=l.error)}}else{let o=await t.text();o&&(i=o)}}catch{}i=i||`${e||"Request"} failed with status ${t.status}`;let p=s??(t.status===401?d.Authentication:t.status===403?d.Forbidden:t.status===429?d.RateLimit:d.Api);return new n(p,i,t.status,r)}static fromFetchError(t,e){if(N(t))return t;let i=e||"Request";return t instanceof Error?t.name==="AbortError"?n.cancelled(`${i} was cancelled`):t instanceof TypeError&&t.message.includes("fetch")?n.network(`${i} failed: ${t.message}`,{cause:t}):new n(d.Api,`${i} failed: ${t.message}`):new n(d.Api,`${i} failed: Unknown error`)}static validation(t,e){return new n(d.Validation,t,400,e)}static notFound(t,e){let i=e?`${t} ${e} not found`:`${t} not found`;return new n(d.NotFound,i,404)}static forbidden(t,e){return new n(d.Forbidden,t,403,e)}static rateLimit(t="Too many requests",e){return new n(d.RateLimit,t,429,e)}static authentication(t="Authentication required",e){return new n(d.Authentication,t,401,e)}static business(t,e=400,i){return new n(d.Business,t,e,i)}static network(t,e){return new n(d.Network,t,void 0,e)}static cancelled(t,e){return new n(d.Cancelled,t,void 0,e)}static file(t,e){return new n(d.File,t,void 0,e)}static config(t,e){return new n(d.Config,t,void 0,e)}static api(t,e=500,i){return new n(d.Api,t,e,i)}isClientError(){return V.client.has(this.type)}isNetworkError(){return V.network.has(this.type)}isAuthError(){return V.auth.has(this.type)}isType(t){return this.type===t}};ke=new Set(["exe","msi","dll","scr","bat","cmd","com","pif","app","deb","rpm","pkg","mpkg","dmg","iso","img","cab","cpl","chm","ps1","vbs","vbe","ws","wsf","wsc","wsh","reg","jar","jnlp","apk","crx","lnk","inf","hta"]);$e=/[\x00-\x1f\x7f#?%\\<>"]/;j=new Set(["node_modules","package.json"]);x={PREFIX:"ship-",HEX_LENGTH:64,TOTAL_LENGTH:69,HINT_LENGTH:4},b={PREFIX:"token-",HEX_LENGTH:64,TOTAL_LENGTH:70},Ze={JWT:"jwt",API_KEY:"apiKey",TOKEN:"token",WEBHOOK:"webhook",SYSTEM:"system"},q="ship.json",le={rewrites:[{source:"/(.*)",destination:"/index.html"}]};_="https://api.shipstatic.com",g={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]+)*$/;k={MIN_LENGTH:6,MAX_LENGTH:128}});function Tt(n){Y=n}function _e(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function P(){return Y||_e()}var Y,F=v(()=>{"use strict";Y=null});async function Me(n){let t=(await import("spark-md5")).default;return new Promise((e,i)=>{let s=Math.ceil(n.size/2097152),p=0,c=new t.ArrayBuffer,o=new FileReader,l=()=>{let u=p*2097152,h=Math.min(u+2097152,n.size);o.readAsArrayBuffer(n.slice(u,h))};o.onload=u=>{let h=u.target?.result;if(!h){i(a.business("Failed to read file chunk"));return}c.append(h),p++,p<s?l():e({md5:c.end()})},o.onerror=()=>{i(a.business("Failed to calculate MD5: FileReader error"))},l()})}async function Be(n){let t=await import("crypto");if(Buffer.isBuffer(n)){let i=t.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let e=await import("fs");return new Promise((i,r)=>{let s=t.createHash("md5"),p=e.createReadStream(n);p.on("error",c=>r(a.business(`Failed to read file for MD5: ${c.message}`))),p.on("data",c=>s.update(c)),p.on("end",()=>i({md5:s.digest("hex")}))})}async function H(n){let t=P();if(t==="browser"){if(!(n instanceof Blob))throw a.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Me(n)}if(t==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw a.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Be(n)}throw a.business("Unknown or unsupported execution environment for MD5 calculation.")}var z=v(()=>{"use strict";F();E()});import{isJunk as Ge}from"junk";function Ae(n,t){if(!n||n.length===0)return[];if(!t?.allowUnbuilt&&n.find(i=>i&&U(i)))throw a.business("Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder");return n.filter(e=>{if(!e)return!1;let i=e.replace(/\\/g,"/").split("/").filter(Boolean);if(i.length===0)return!0;let r=i[i.length-1];if(Ge(r))return!1;for(let p of i)if(p!==".well-known"&&(p.startsWith(".")||p.length>255))return!1;let s=i.slice(0,-1);for(let p of s)if(Ve.some(c=>p.toLowerCase()===c.toLowerCase()))return!1;return!0})}var Ve,J=v(()=>{"use strict";E();Ve=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function we(n){if(!n||n.length===0)return"";let t=n.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(t.length===0)return"";if(t.length===1)return t[0];let e=t.map(s=>s.split("/").filter(Boolean)),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function G(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Q=v(()=>{"use strict"});function Re(n,t={}){if(t.flatten===!1)return n.map(i=>({path:G(i),name:Z(i)}));let e=je(n);return n.map(i=>{let r=G(i);if(e){let s=e.endsWith("/")?e:`${e}/`;r.startsWith(s)&&(r=r.substring(s.length))}return r||(r=Z(i)),{path:r,name:Z(i)}})}function je(n){if(!n.length)return"";let e=n.map(s=>G(s)).map(s=>s.split("/")),i=[],r=Math.min(...e.map(s=>s.length));for(let s=0;s<r-1;s++){let p=e[0][s];if(e.every(c=>c[s]===p))i.push(p);else break}return i.join("/")}function Z(n){return n.split(/[/\\]/).pop()||n}var ee=v(()=>{"use strict";Q()});function te(n,t=1){if(n===0)return"0 Bytes";let e=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(e));return parseFloat((n/Math.pow(e,r)).toFixed(t))+" "+i[r]}function ne(n){if(ae(n))return{valid:!1,reason:"File name contains unsafe characters"};if(n.startsWith(" ")||n.endsWith(" "))return{valid:!1,reason:"File name cannot start/end with spaces"};if(n.endsWith("."))return{valid:!1,reason:"File name cannot end with dots"};let t=/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(\.|$)/i,e=n.split("/").pop()||n;return t.test(e)?{valid:!1,reason:"File name uses a reserved system name"}:n.includes("..")?{valid:!1,reason:"File name contains path traversal pattern"}:{valid:!0}}function nn(n,t){let e=[],i=[],r=[];if(n.length===0){let o={file:"(no files)",message:"At least one file must be provided"};return e.push(o),{files:[],validFiles:[],errors:e,warnings:[],canDeploy:!1}}for(let o of n)if(U(o.name))return e.push({file:o.name,message:"Unbuilt project detected \u2014 deploy your build output (dist/, build/, out/), not the project folder"}),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:"Unbuilt project detected"})),validFiles:[],errors:e,warnings:[],canDeploy:!1};if(n.length>t.maxFilesCount){let o={file:`(${n.length} files)`,message:`File count (${n.length}) exceeds limit of ${t.maxFilesCount}`};return e.push(o),{files:n.map(l=>({...l,status:g.VALIDATION_FAILED,statusMessage:o.message})),validFiles:[],errors:e,warnings:[],canDeploy:!1}}let s=0;for(let o of n){let l=g.READY,u="Ready for upload",h=o.name?ne(o.name):{valid:!1,reason:"File name cannot be empty"};if(o.status===g.PROCESSING_ERROR)l=g.VALIDATION_FAILED,u=o.statusMessage||"File failed during processing",e.push({file:o.name,message:u});else if(o.size===0){l=g.EXCLUDED,u="File is empty (0 bytes) and cannot be deployed due to storage limitations",i.push({file:o.name,message:u}),r.push({...o,status:l,statusMessage:u});continue}else o.size<0?(l=g.VALIDATION_FAILED,u="File size must be positive",e.push({file:o.name,message:u})):!o.name||o.name.trim().length===0?(l=g.VALIDATION_FAILED,u="File name cannot be empty",e.push({file:o.name||"(empty)",message:u})):o.name.includes("\0")?(l=g.VALIDATION_FAILED,u="File name contains invalid characters (null byte)",e.push({file:o.name,message:u})):h.valid?$(o.name)?(l=g.VALIDATION_FAILED,u=`File extension not allowed: "${o.name}"`,e.push({file:o.name,message:u})):o.size>t.maxFileSize?(l=g.VALIDATION_FAILED,u=`File size (${te(o.size)}) exceeds limit of ${te(t.maxFileSize)}`,e.push({file:o.name,message:u})):(s+=o.size,s>t.maxTotalSize&&(l=g.VALIDATION_FAILED,u=`Total size would exceed limit of ${te(t.maxTotalSize)}`,e.push({file:o.name,message:u}))):(l=g.VALIDATION_FAILED,u=h.reason||"Invalid file name",e.push({file:o.name,message:u}));r.push({...o,status:l,statusMessage:u})}e.length>0&&(r=r.map(o=>o.status===g.EXCLUDED?o:{...o,status:g.VALIDATION_FAILED,statusMessage:o.status===g.VALIDATION_FAILED?o.statusMessage:"Deployment failed due to validation errors in bundle"}));let p=e.length===0?r.filter(o=>o.status===g.READY):[],c=e.length===0;return{files:r,validFiles:p,errors:e,warnings:i,canDeploy:c}}function qe(n){return n.filter(t=>t.status===g.READY)}function rn(n){return qe(n).length>0}var ie=v(()=>{"use strict";E()});function ve(n,t){if(n.includes("\0")||n.includes("/../")||n.startsWith("../")||n.endsWith("/.."))throw a.business(`Security error: Unsafe file path "${n}" for file: ${t}`)}function xe(n,t){let e=ne(n);if(!e.valid)throw a.business(e.reason||"Invalid file name");if($(n))throw a.business(`File extension not allowed: "${t}"`)}var re=v(()=>{"use strict";E();ie()});var Pe={};Fe(Pe,{processFilesForNode:()=>Ie});import*as S from"fs";import*as T from"path";function be(n,t=new Set){let e=[],i=S.realpathSync(n);if(t.has(i))return e;t.add(i);let r=S.readdirSync(n);for(let s of r){let p=T.join(n,s),c=S.statSync(p);if(c.isDirectory()){let o=be(p,t);e.push(...o)}else c.isFile()&&e.push(p)}return e}async function Ie(n,t={},e){if(P()!=="node")throw a.business("processFilesForNode can only be called in Node.js environment.");for(let m of n){let y=T.resolve(m);try{if(S.statSync(y).isDirectory()){let A=S.readdirSync(y).find(w=>j.has(w));if(A)throw a.business(`"${A}" detected \u2014 deploy your build output (dist/, build/, out/), not the project folder`)}}catch(A){if(N(A))throw A}}let i=n.flatMap(m=>{let y=T.resolve(m);try{return S.statSync(y).isDirectory()?be(y):[y]}catch{throw a.file(`Path does not exist: ${m}`,{filePath:m})}}),r=[...new Set(i)],s=n.map(m=>T.resolve(m)),p=we(s.map(m=>{try{return S.statSync(m).isDirectory()?m:T.dirname(m)}catch{return T.dirname(m)}})),c=r.map(m=>{if(p&&p.length>0){let y=T.relative(p,m);if(y&&typeof y=="string"&&!y.startsWith(".."))return y.replace(/\\/g,"/")}return T.basename(m)}),l=Re(c,{flatten:t.pathDetect!==!1}).map(m=>m.path),u=new Set(Ae(l));if(u.size===0)return[];let h=[],L=[];for(let m=0;m<r.length;m++)u.has(l[m])&&(h.push(r[m]),L.push(l[m]));let R=[],D=0;if(!e)throw a.config("Platform limits not provided. processFilesForNode requires the limits argument \u2014 pass `ship.getLimits()` result.");for(let m=0;m<h.length;m++){let y=h[m],A=L[m];try{ve(A,y);let w=S.statSync(y);if(w.size===0)continue;if(xe(A,y),w.size>e.maxFileSize)throw a.business(`File ${y} is too large. Maximum allowed size is ${e.maxFileSize/(1024*1024)}MB.`);if(D+=w.size,D>e.maxTotalSize)throw a.business(`Total deploy size is too large. Maximum allowed is ${e.maxTotalSize/(1024*1024)}MB.`);let C=S.readFileSync(y),{md5:Le}=await H(C);R.push({path:A,content:C,size:C.length,md5:Le})}catch(w){if(N(w))throw w;let C=w instanceof Error?w.message:String(w);throw a.file(`Failed to read file "${y}": ${C}`,{filePath:y})}}if(R.length>e.maxFilesCount)throw a.business(`Too many files to deploy. Maximum allowed is ${e.maxFilesCount} files.`);return R}var se=v(()=>{"use strict";F();z();J();re();E();ee();Q()});E();E();var M=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){let i=this.handlers.get(t);i&&(i.delete(e),i.size===0&&this.handlers.delete(t))}emit(t,...e){let i=this.handlers.get(t);if(!i)return;let r=Array.from(i);for(let s of r)try{s(...e)}catch(p){i.delete(s),t!=="error"&&setTimeout(()=>{let c=p instanceof Error?p:new Error(String(p));this.emit("error",c,String(t))},0)}}};E();E();function O(n){if(n==null)return;if(n.length===0)return n;if(n.length>I.MAX_COUNT)throw a.validation(`Maximum ${I.MAX_COUNT} labels allowed`);let t=n.map((i,r)=>{if(typeof i!="string")throw a.validation(`Label at index ${r} must be a string`);let s=i.trim().toLowerCase();if(s.length<I.MIN_LENGTH)throw a.validation(`Labels must be at least ${I.MIN_LENGTH} characters long`);if(s.length>I.MAX_LENGTH)throw a.validation(`Labels must be no more than ${I.MAX_LENGTH} characters long`);if(!ce.test(s))throw a.validation(`Labels must start and end with alphanumeric characters, with optional separators (${I.SEPARATORS}) between segments`);return s}),e=[...new Set(t)];if(e.length!==t.length)throw a.validation("Duplicate labels are not allowed");return e}var f={DEPLOYMENTS:"/deployments",DOMAINS:"/domains",TOKENS:"/tokens",ACCOUNT:"/account",LIMITS:"/limits",PING:"/ping",SPA_CHECK:"/spa-check"},Ue=3e4,B=class extends M{constructor(e){super();this.globalHeaders={};this.apiUrl=e.apiUrl||_,this.getAuthHeadersCallback=e.getAuthHeaders,this.useCredentials=e.useCredentials??!1,this.timeout=e.timeout??Ue,this.fetch=e.fetch??globalThis.fetch,this.createDeployBody=e.createDeployBody,this.deployEndpoint=e.deployEndpoint||f.DEPLOYMENTS}setGlobalHeaders(e){this.globalHeaders=e}async executeRequest(e,i,r){let s=this.mergeHeaders(i.headers),{signal:p,cleanup:c}=this.createTimeoutSignal(i.signal),o={...i,headers:s,credentials:this.useCredentials&&!s.Authorization?"include":void 0,signal:p};this.emit("request",e,o);try{let l=await this.fetch(e,o);if(c(),!l.ok)throw await a.fromHttpResponse(l,r);return this.emit("response",this.safeClone(l),e),{data:await this.parseResponse(this.safeClone(l)),status:l.status}}catch(l){c();let u=a.fromFetchError(l,r);throw this.emit("error",u,e),u}}async request(e,i,r){let{data:s}=await this.executeRequest(e,i,r);return s}async requestWithStatus(e,i,r){return this.executeRequest(e,i,r)}mergeHeaders(e={}){return{...this.globalHeaders,...this.getAuthHeadersCallback(),...e}}createTimeoutSignal(e){let i=new AbortController,r=setTimeout(()=>i.abort(),this.timeout);if(e){let s=()=>i.abort();e.addEventListener("abort",s),e.aborted&&i.abort()}return{signal:i.signal,cleanup:()=>clearTimeout(r)}}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return e.json()}async deploy(e,i={}){if(!e.length)throw a.business("No files to deploy");for(let l of e)if(!l.md5)throw a.file(`MD5 checksum missing for file: ${l.path}`,{filePath:l.path});X(i.password);let r=O(i.labels),s=i.build||i.prerender||i.spa?{build:i.build,prerender:i.prerender,spa:i.spa}:void 0,{body:p,headers:c}=await this.createDeployBody(e,{labels:r,via:i.via,password:i.password,flags:s}),o={};return i.deployToken?o.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(o.Authorization=`Bearer ${i.apiKey}`),i.caller&&(o["X-Caller"]=i.caller),this.request(`${i.apiUrl||this.apiUrl}${this.deployEndpoint}`,{method:"POST",body:p,headers:{...c,...o},signal:i.signal||null},"Deploy")}async listDeployments(){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}`,{method:"GET"},"List deployments")}async getDeployment(e){return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"GET"},"Get deployment")}async updateDeploymentLabels(e,i){let r=O(i);return this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({labels:r})},"Update deployment labels")}async removeDeployment(e){await this.request(`${this.apiUrl}${f.DEPLOYMENTS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove deployment")}async setDomain(e,i,r){let s=O(r),p={};i&&(p.deployment=i),s!==void 0&&(p.labels=s);let{data:c,status:o}=await this.requestWithStatus(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)},"Set domain");return{...c,isCreate:o===201}}async listDomains(){return this.request(`${this.apiUrl}${f.DOMAINS}`,{method:"GET"},"List domains")}async getDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"GET"},"Get domain")}async removeDomain(e){await this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove domain")}async verifyDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/verify`,{method:"POST"},"Verify domain")}async getDomainDns(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get domain DNS")}async getDomainRecords(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get domain records")}async getDomainShare(e){return this.request(`${this.apiUrl}${f.DOMAINS}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get domain share")}async validateDomain(e){return this.request(`${this.apiUrl}${f.DOMAINS}/validate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({domain:e})},"Validate domain")}async createToken(e,i){let r=O(i),s={};return e!==void 0&&(s.ttl=e),r!==void 0&&(s.labels=r),this.request(`${this.apiUrl}${f.TOKENS}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)},"Create token")}async listTokens(){return this.request(`${this.apiUrl}${f.TOKENS}`,{method:"GET"},"List tokens")}async removeToken(e){await this.request(`${this.apiUrl}${f.TOKENS}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove token")}async fetchAgentToken(){return this.request(`${this.apiUrl}${f.TOKENS}/agent`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})},"Fetch agent token")}async getAccount(){return this.request(`${this.apiUrl}${f.ACCOUNT}`,{method:"GET"},"Get account")}async getLimits(){return this.request(`${this.apiUrl}${f.LIMITS}`,{method:"GET"},"Get limits")}async ping(){return(await this.request(`${this.apiUrl}${f.PING}`,{method:"GET"},"Ping"))?.success||!1}async checkSPA(e,i={}){let r=e.find(l=>l.path==="index.html"||l.path==="/index.html");if(!r||r.size>100*1024)return!1;let s;if(typeof Buffer<"u"&&Buffer.isBuffer(r.content))s=r.content.toString("utf-8");else if(typeof Blob<"u"&&r.content instanceof Blob)s=await r.content.text();else if(typeof File<"u"&&r.content instanceof File)s=await r.content.text();else return!1;let p={"Content-Type":"application/json"};i.deployToken?p.Authorization=`Bearer ${i.deployToken}`:i.apiKey&&(p.Authorization=`Bearer ${i.apiKey}`);let c={files:e.map(l=>l.path),index:s};return(await this.request(`${this.apiUrl}${f.SPA_CHECK}`,{method:"POST",headers:p,body:JSON.stringify(c)},"SPA check")).isSPA}};E();function ue(n={}){let t={apiUrl:n.apiUrl||_};return n.apiKey!==void 0&&(t.apiKey=n.apiKey),n.deployToken!==void 0&&(t.deployToken=n.deployToken),t}function de(n,t){let e={...n};return e.apiUrl===void 0&&t.apiUrl!==void 0&&(e.apiUrl=t.apiUrl),e.apiKey===void 0&&t.apiKey!==void 0&&(e.apiKey=t.apiKey),e.deployToken===void 0&&t.deployToken!==void 0&&(e.deployToken=t.deployToken),e.timeout===void 0&&t.timeout!==void 0&&(e.timeout=t.timeout),e.maxConcurrency===void 0&&t.maxConcurrency!==void 0&&(e.maxConcurrency=t.maxConcurrency),e.onProgress===void 0&&t.onProgress!==void 0&&(e.onProgress=t.onProgress),e.caller===void 0&&t.caller!==void 0&&(e.caller=t.caller),e}E();E();z();async function He(){let n=JSON.stringify(le,null,2),t;typeof Buffer<"u"?t=Buffer.from(n,"utf-8"):t=new Blob([n],{type:"application/json"});let{md5:e}=await H(t);return{path:q,content:t,size:n.length,md5:e}}async function me(n,t,e){if(e.spaDetect===!1||e.spa||e.build||e.prerender||n.some(i=>i.path===q))return n;try{if(await t.checkSPA(n,e)){let r=await He();return[...n,r]}}catch{}return n}function fe(n){let{getApi:t,ensureInit:e,processInput:i,clientDefaults:r,hasAuth:s}=n;return{upload:async(p,c={})=>{await e();let o=r?de(c,r):c;if(s&&!s()&&!o.deployToken&&!o.apiKey)try{let h=t(),{secret:L}=await h.fetchAgentToken();o.deployToken=L}catch(h){throw N(h)&&h.type===d.RateLimit?a.rateLimit("public deploy rate limit exceeded, try again later or run 'ship config' for a free account with higher limits"):h}if(!i)throw a.config("processInput function is not provided.");let l=t(),u=await i(p,o);return u=await me(u,l,o),l.deploy(u,o)},list:async()=>(await e(),t().listDeployments()),get:async p=>(await e(),t().getDeployment(p)),set:async(p,c)=>(await e(),t().updateDeploymentLabels(p,c.labels)),remove:async p=>{await e(),await t().removeDeployment(p)}}}function he(n){let{getApi:t,ensureInit:e}=n;return{set:async(i,r={})=>(await e(),t().setDomain(i,r.deployment,r.labels)),list:async()=>(await e(),t().listDomains()),get:async i=>(await e(),t().getDomain(i)),remove:async i=>{await e(),await t().removeDomain(i)},verify:async i=>(await e(),t().verifyDomain(i)),validate:async i=>(await e(),t().validateDomain(i)),dns:async i=>(await e(),t().getDomainDns(i)),records:async i=>(await e(),t().getDomainRecords(i)),share:async i=>(await e(),t().getDomainShare(i))}}function ye(n){let{getApi:t,ensureInit:e}=n;return{get:async()=>(await e(),t().getAccount())}}function ge(n){let{getApi:t,ensureInit:e}=n;return{create:async(i={})=>(await e(),t().createToken(i.ttl,i.labels)),list:async()=>(await e(),t().listTokens()),remove:async i=>{await e(),await t().removeToken(i)}}}var K=class{constructor(t={}){this.initPromise=null;this.platformLimits=null;this.auth=null;t={...t,apiUrl:t.apiUrl||void 0,apiKey:t.apiKey||void 0,deployToken:t.deployToken||void 0},this.clientOptions=t,t.deployToken?this.auth={type:"token",value:t.deployToken}:t.apiKey&&(this.auth={type:"apiKey",value:t.apiKey}),this.http=new B({...t,...ue(t),getAuthHeaders:()=>this.getAuthHeaders(),createDeployBody:this.getDeployBodyCreator()});let e={getApi:()=>this.http,ensureInit:()=>this.ensureInitialized()};this.deployments=fe({...e,processInput:(i,r)=>this.processInput(i,r),clientDefaults:this.clientOptions,hasAuth:()=>this.hasAuth()}),this.domains=he(e),this.account=ye(e),this.tokens=ge(e)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.fetchPlatformLimits()),this.initPromise}async fetchPlatformLimits(){try{this.platformLimits=await this.http.getLimits()}catch(t){throw this.initPromise=null,t}}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(t,e){return this.deployments.upload(t,e)}async whoami(){return this.account.get()}async getLimits(){return this.platformLimits?this.platformLimits:(await this.ensureInitialized(),this.platformLimits)}on(t,e){this.http.on(t,e)}off(t,e){this.http.off(t,e)}setHeaders(t){this.http.setGlobalHeaders(t)}clearHeaders(){this.http.setGlobalHeaders({})}setDeployToken(t){if(!t||typeof t!="string")throw a.business("Invalid deploy token provided. Deploy token must be a non-empty string.");this.auth={type:"token",value:t}}setApiKey(t){if(!t||typeof t!="string")throw a.business("Invalid API key provided. API key must be a non-empty string.");this.auth={type:"apiKey",value:t}}getAuthHeaders(){return this.auth?{Authorization:`Bearer ${this.auth.value}`}:{}}hasAuth(){return this.clientOptions.useCredentials?!0:this.auth!==null}};E();F();E();F();import{z as De}from"zod";import{z as W}from"zod";var Ee={apiUrl:W.string().url().optional(),apiKey:W.string().min(1).optional(),deployToken:W.string().min(1).optional()};var ze=De.object(Ee).strict(),Ke={apiUrl:"SHIP_API_URL",apiKey:"SHIP_API_KEY",deployToken:"SHIP_DEPLOY_TOKEN"};function Se(){if(P()!=="node")return{};let n={apiUrl:process.env.SHIP_API_URL||void 0,apiKey:process.env.SHIP_API_KEY||void 0,deployToken:process.env.SHIP_DEPLOY_TOKEN||void 0};try{return ze.parse(n)}catch(t){if(t instanceof De.ZodError){let e=t.issues[0],i=e.path[0],r=(i&&Ke[i])??"SHIP environment configuration";throw a.config(`Invalid ${r}: ${e.message}`)}throw a.config("Invalid environment configuration")}}E();async function Te(n,t={}){let{FormData:e,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),{labels:s,via:p,password:c,flags:o}=t,l=new e,u=[];for(let D of n){if(!Buffer.isBuffer(D.content)&&!(typeof Blob<"u"&&D.content instanceof Blob))throw a.file(`Unsupported file.content type for Node.js: ${D.path}`,{filePath:D.path});if(!D.md5)throw a.file(`File missing md5 checksum: ${D.path}`,{filePath:D.path});let m=new i([D.content],D.path,{type:"application/octet-stream"});l.append("files[]",m),u.push(D.md5)}l.append("checksums",JSON.stringify(u)),s&&s.length>0&&l.append("labels",JSON.stringify(s)),p&&l.append("via",p),c&&l.append("password",c),o?.build&&l.append("build","true"),o?.prerender&&l.append("prerender","true"),o?.spa&&l.append("spa","true");let h=new r(l),L=[];for await(let D of h.encode())L.push(Buffer.from(D));let R=Buffer.concat(L);return{body:R.buffer.slice(R.byteOffset,R.byteOffset+R.byteLength),headers:{"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(R).toString()}}}z();function qt(n,t,e,i=!0){let r=n===1?t:e;return i?`${n} ${r}`:r}J();ee();F();ie();re();E();se();var oe=class extends K{constructor(t={}){if(P()!=="node")throw a.business("Node.js Ship class can only be used in Node.js environment.");let e=Se();super({...t,apiUrl:t.apiUrl||e.apiUrl,apiKey:t.apiKey||e.apiKey,deployToken:t.deployToken||e.deployToken})}async deploy(t,e){return super.deploy(t,e)}async processInput(t,e){let i=typeof t=="string"?[t]:t;if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))throw a.business("Invalid input type for Node.js environment. Expected string or string[].");if(i.length===0)throw a.business("No files to deploy.");let{processFilesForNode:r}=await Promise.resolve().then(()=>(se(),Pe));return r(i,e,this.platformLimits??void 0)}getDeployBodyCreator(){return Te}},Xe=oe;export{x as API_KEY,Qe as AccountPlan,B as ApiHttp,Ze as AuthMethod,ke as BLOCKED_EXTENSIONS,_ as DEFAULT_API,q as DEPLOYMENT_CONFIG_FILENAME,b as DEPLOY_TOKEN,We as DeploymentStatus,Je as DomainStatus,d as ErrorType,g as FILE_VALIDATION_STATUS,g as FileValidationStatus,Ve as JUNK_DIRECTORIES,I as LABEL_CONSTRAINTS,ce as LABEL_PATTERN,k as PASSWORD_CONSTRAINTS,le as SPA_DEFAULT_CONFIG,oe as Ship,a as ShipError,j as UNBUILT_PROJECT_MARKERS,$e as UNSAFE_FILENAME_CHARS,Tt as __setTestEnvironment,rn as allValidFilesReady,H as calculateMD5,ye as createAccountResource,fe as createDeploymentResource,he as createDomainResource,ge as createTokenResource,Xe as default,pt as deserializeLabels,st as extractSubdomain,Ae as filterJunk,te as formatFileSize,ot as generateDeploymentUrl,at as generateDomainUrl,P as getENV,qe as getValidFiles,U as hasUnbuiltMarker,ae as hasUnsafeChars,$ as isBlockedExtension,rt as isCustomDomain,it as isDeployment,pe as isPlatformDomain,N as isShipError,de as mergeDeployOptions,Re as optimizeDeployPaths,qt as pluralize,Ie as processFilesForNode,ue as resolveConfig,lt as serializeLabels,et as validateApiKey,nt as validateApiUrl,xe as validateDeployFile,ve as validateDeployPath,tt as validateDeployToken,ne as validateFileName,nn as validateFiles,X as validatePassword};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|