@shipstatic/ship 0.2.8 → 0.3.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 +29 -29
- package/dist/browser.d.ts +19 -19
- package/dist/browser.js +3 -3
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +27 -27
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +3 -3
- package/dist/completions/ship.fish +6 -6
- package/dist/completions/ship.zsh +5 -5
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +19 -19
- package/dist/index.d.ts +19 -19
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse,
|
|
2
|
+
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, PlatformConfig } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
|
-
export { Account,
|
|
4
|
+
export { Account, DEFAULT_API, DeployInput, Deployment, Domain, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* @file SDK-specific type definitions
|
|
@@ -201,23 +201,23 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
201
201
|
listDeployments(): Promise<DeploymentListResponse>;
|
|
202
202
|
getDeployment(id: string): Promise<Deployment>;
|
|
203
203
|
removeDeployment(id: string): Promise<void>;
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
204
|
+
setDomain(name: string, deployment: string, tags?: string[]): Promise<Domain>;
|
|
205
|
+
getDomain(name: string): Promise<Domain>;
|
|
206
|
+
listDomains(): Promise<DomainListResponse>;
|
|
207
|
+
removeDomain(name: string): Promise<void>;
|
|
208
|
+
confirmDomain(name: string): Promise<{
|
|
209
209
|
message: string;
|
|
210
210
|
}>;
|
|
211
|
-
|
|
212
|
-
|
|
211
|
+
getDomainDns(name: string): Promise<{
|
|
212
|
+
domain: string;
|
|
213
213
|
dns: any;
|
|
214
214
|
}>;
|
|
215
|
-
|
|
216
|
-
|
|
215
|
+
getDomainRecords(name: string): Promise<{
|
|
216
|
+
domain: string;
|
|
217
217
|
records: any[];
|
|
218
218
|
}>;
|
|
219
|
-
|
|
220
|
-
|
|
219
|
+
getDomainShare(name: string): Promise<{
|
|
220
|
+
domain: string;
|
|
221
221
|
hash: string;
|
|
222
222
|
}>;
|
|
223
223
|
getAccount(): Promise<Account>;
|
|
@@ -233,11 +233,11 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
233
233
|
}
|
|
234
234
|
|
|
235
235
|
/**
|
|
236
|
-
* @file Ship SDK resource implementations for deployments,
|
|
236
|
+
* @file Ship SDK resource implementations for deployments, domains, and accounts.
|
|
237
237
|
*/
|
|
238
238
|
|
|
239
239
|
declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?: ShipClientOptions, ensureInit?: () => Promise<void>, processInput?: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>): DeploymentResource;
|
|
240
|
-
declare function
|
|
240
|
+
declare function createDomainResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): DomainResource;
|
|
241
241
|
declare function createAccountResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AccountResource;
|
|
242
242
|
declare function createTokenResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): TokenResource;
|
|
243
243
|
|
|
@@ -252,7 +252,7 @@ declare abstract class Ship$1 {
|
|
|
252
252
|
protected readonly clientOptions: ShipClientOptions;
|
|
253
253
|
protected initPromise: Promise<void> | null;
|
|
254
254
|
protected _deployments: DeploymentResource;
|
|
255
|
-
protected
|
|
255
|
+
protected _domains: DomainResource;
|
|
256
256
|
protected _account: AccountResource;
|
|
257
257
|
protected _tokens: TokenResource;
|
|
258
258
|
constructor(options?: ShipClientOptions);
|
|
@@ -280,9 +280,9 @@ declare abstract class Ship$1 {
|
|
|
280
280
|
*/
|
|
281
281
|
get deployments(): DeploymentResource;
|
|
282
282
|
/**
|
|
283
|
-
* Get
|
|
283
|
+
* Get domains resource
|
|
284
284
|
*/
|
|
285
|
-
get
|
|
285
|
+
get domains(): DomainResource;
|
|
286
286
|
/**
|
|
287
287
|
* Get account resource
|
|
288
288
|
*/
|
|
@@ -507,4 +507,4 @@ declare class Ship extends Ship$1 {
|
|
|
507
507
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
508
508
|
}
|
|
509
509
|
|
|
510
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource,
|
|
510
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import * as _shipstatic_types from '@shipstatic/types';
|
|
2
|
-
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse,
|
|
2
|
+
import { PingResponse, ConfigResponse, StaticFile, Deployment, DeploymentListResponse, Domain, DomainListResponse, Account, TokenCreateResponse, TokenListResponse, DeployInput, DeploymentResource, DomainResource, AccountResource, TokenResource, PlatformConfig } from '@shipstatic/types';
|
|
3
3
|
export * from '@shipstatic/types';
|
|
4
|
-
export { Account,
|
|
4
|
+
export { Account, DEFAULT_API, DeployInput, Deployment, Domain, PingResponse, ShipError, ShipErrorType } from '@shipstatic/types';
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* @file SDK-specific type definitions
|
|
@@ -201,23 +201,23 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
201
201
|
listDeployments(): Promise<DeploymentListResponse>;
|
|
202
202
|
getDeployment(id: string): Promise<Deployment>;
|
|
203
203
|
removeDeployment(id: string): Promise<void>;
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
204
|
+
setDomain(name: string, deployment: string, tags?: string[]): Promise<Domain>;
|
|
205
|
+
getDomain(name: string): Promise<Domain>;
|
|
206
|
+
listDomains(): Promise<DomainListResponse>;
|
|
207
|
+
removeDomain(name: string): Promise<void>;
|
|
208
|
+
confirmDomain(name: string): Promise<{
|
|
209
209
|
message: string;
|
|
210
210
|
}>;
|
|
211
|
-
|
|
212
|
-
|
|
211
|
+
getDomainDns(name: string): Promise<{
|
|
212
|
+
domain: string;
|
|
213
213
|
dns: any;
|
|
214
214
|
}>;
|
|
215
|
-
|
|
216
|
-
|
|
215
|
+
getDomainRecords(name: string): Promise<{
|
|
216
|
+
domain: string;
|
|
217
217
|
records: any[];
|
|
218
218
|
}>;
|
|
219
|
-
|
|
220
|
-
|
|
219
|
+
getDomainShare(name: string): Promise<{
|
|
220
|
+
domain: string;
|
|
221
221
|
hash: string;
|
|
222
222
|
}>;
|
|
223
223
|
getAccount(): Promise<Account>;
|
|
@@ -233,11 +233,11 @@ declare class ApiHttp extends SimpleEvents {
|
|
|
233
233
|
}
|
|
234
234
|
|
|
235
235
|
/**
|
|
236
|
-
* @file Ship SDK resource implementations for deployments,
|
|
236
|
+
* @file Ship SDK resource implementations for deployments, domains, and accounts.
|
|
237
237
|
*/
|
|
238
238
|
|
|
239
239
|
declare function createDeploymentResource(getApi: () => ApiHttp, clientDefaults?: ShipClientOptions, ensureInit?: () => Promise<void>, processInput?: (input: DeployInput, options: DeploymentOptions) => Promise<StaticFile[]>): DeploymentResource;
|
|
240
|
-
declare function
|
|
240
|
+
declare function createDomainResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): DomainResource;
|
|
241
241
|
declare function createAccountResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): AccountResource;
|
|
242
242
|
declare function createTokenResource(getApi: () => ApiHttp, ensureInit?: () => Promise<void>): TokenResource;
|
|
243
243
|
|
|
@@ -252,7 +252,7 @@ declare abstract class Ship$1 {
|
|
|
252
252
|
protected readonly clientOptions: ShipClientOptions;
|
|
253
253
|
protected initPromise: Promise<void> | null;
|
|
254
254
|
protected _deployments: DeploymentResource;
|
|
255
|
-
protected
|
|
255
|
+
protected _domains: DomainResource;
|
|
256
256
|
protected _account: AccountResource;
|
|
257
257
|
protected _tokens: TokenResource;
|
|
258
258
|
constructor(options?: ShipClientOptions);
|
|
@@ -280,9 +280,9 @@ declare abstract class Ship$1 {
|
|
|
280
280
|
*/
|
|
281
281
|
get deployments(): DeploymentResource;
|
|
282
282
|
/**
|
|
283
|
-
* Get
|
|
283
|
+
* Get domains resource
|
|
284
284
|
*/
|
|
285
|
-
get
|
|
285
|
+
get domains(): DomainResource;
|
|
286
286
|
/**
|
|
287
287
|
* Get account resource
|
|
288
288
|
*/
|
|
@@ -507,4 +507,4 @@ declare class Ship extends Ship$1 {
|
|
|
507
507
|
protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
|
|
508
508
|
}
|
|
509
509
|
|
|
510
|
-
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource,
|
|
510
|
+
export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, __setTestEnvironment, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, getCurrentConfig, getENV, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Ee=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var x=(o,e)=>()=>(o&&(e=o(o=0)),e);var U=(o,e)=>{for(var t in e)Ee(o,t,{get:e[t],enumerable:!0})},Ce=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qe(e))!je.call(o,i)&&i!==t&&Ee(o,i,{get:()=>e[i],enumerable:!(n=_e(e,i))||n.enumerable});return o},p=(o,e,t)=>(Ce(o,e,"default"),t&&Ce(t,e,"default"));var Fe={};U(Fe,{__setTestEnvironment:()=>M,getENV:()=>h});function M(o){ae=o}function He(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return ae||He()}var ae,P=x(()=>{"use strict";ae=null});var Te={};U(Te,{loadConfig:()=>B});import{z as _}from"zod";import{ShipError as ce}from"@shipstatic/types";function Ae(o){try{return Ye.parse(o)}catch(e){if(e instanceof _.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw ce.config(`Configuration validation failed${n}: ${t.message}`)}throw ce.config("Configuration validation failed")}}async function Xe(o){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(le,{searchPlaces:[`.${le}rc`,"package.json",`${t.homedir()}/.${le}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return Ae(i.config)}catch(e){if(e instanceof ce)throw e}return{}}async function B(o){if(h()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Xe(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Ae(n)}var le,Ye,te=x(()=>{"use strict";P();le="ship",Ye=_.object({apiUrl:_.string().url().optional(),apiKey:_.string().optional(),deployToken:_.string().optional()}).strict()});import{ShipError as I}from"@shipstatic/types";async function et(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,c=new e.ArrayBuffer,f=new FileReader,w=()=>{let g=s*2097152,a=Math.min(g+2097152,o.size);f.readAsArrayBuffer(o.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){n(I.business("Failed to read file chunk"));return}c.append(a),s++,s<r?w():t({md5:c.end()})},f.onerror=()=>{n(I.business("Failed to calculate MD5: FileReader error"))},w()})}async function tt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",c=>i(I.business(`Failed to read file for MD5: ${c.message}`))),s.on("data",c=>r.update(c)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function D(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw I.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return et(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw I.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return tt(o)}throw I.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=x(()=>{"use strict";P()});import{ShipError as nt}from"@shipstatic/types";function L(o){fe=o}function k(){if(fe===null)throw nt.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return fe}var fe,K=x(()=>{"use strict";fe=null});import{isJunk as it}from"junk";function b(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if(it(n))return!1;let i=t.slice(0,-1);for(let r of i)if(oe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var oe,ne=x(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function ke(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(c=>c[r]===s))n.push(s);else break}return n.join("/")}function ie(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var de=x(()=>{"use strict"});function $(o,e={}){if(e.flatten===!1)return o.map(n=>({path:ie(n),name:he(n)}));let t=rt(o);return o.map(n=>{let i=ie(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=he(n)),{path:i,name:he(n)}})}function rt(o){if(!o.length)return"";let t=o.map(r=>ie(r)).map(r=>r.split("/")),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(c=>c[r]===s))n.push(s);else break}return n.join("/")}function he(o){return o.split(/[/\\]/).pop()||o}var re=x(()=>{"use strict";de()});import{ShipError as O}from"@shipstatic/types";import*as R from"fs";import*as S from"path";function be(o){let e=[];try{let t=R.readdirSync(o);for(let n of t){let i=S.join(o,n),r=R.statSync(i);if(r.isDirectory()){let s=be(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function W(o,e={}){if(h()!=="node")throw O.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(m=>{let u=S.resolve(m);try{return R.statSync(u).isDirectory()?be(u):[u]}catch{throw O.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=b(n);if(i.length===0)return[];let r=o.map(m=>S.resolve(m)),s=ke(r.map(m=>{try{return R.statSync(m).isDirectory()?m:S.dirname(m)}catch{return S.dirname(m)}})),c=i.map(m=>{if(s&&s.length>0){let u=S.relative(s,m);if(u&&typeof u=="string"&&!u.startsWith(".."))return u.replace(/\\/g,"/")}return S.basename(m)}),f=$(c,{flatten:e.pathDetect!==!1}),w=[],g=0,a=k();for(let m=0;m<i.length;m++){let u=i[m],F=f[m].path;try{let A=R.statSync(u);if(A.size===0){console.warn(`Skipping empty file: ${u}`);continue}if(A.size>a.maxFileSize)throw O.business(`File ${u} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=A.size,g>a.maxTotalSize)throw O.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let se=R.readFileSync(u),{md5:Me}=await D(se);if(F.includes("\0")||F.includes("/../")||F.startsWith("../")||F.endsWith("/.."))throw O.business(`Security error: Unsafe file path "${F}" for file: ${u}`);w.push({path:F,content:se,size:se.length,md5:Me})}catch(A){if(A instanceof O&&A.isClientError&&A.isClientError())throw A;console.error(`Could not process file ${u}:`,A)}}if(w.length>a.maxFilesCount)throw O.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return w}var we=x(()=>{"use strict";P();j();ne();K();re();de()});import{ShipError as $e}from"@shipstatic/types";async function Oe(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(P(),Fe));if(t()!=="browser")throw $e.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(a=>a.webkitRelativePath||a.name),r=$(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<n.length;a++){let m=n[a],u=r[a].path;if(u.includes("..")||u.includes("\0"))throw $e.business(`Security error: Unsafe file path "${u}" for file: ${m.name}`);s.push({file:m,relativePath:u})}let c=s.map(a=>a.relativePath),f=b(c),w=new Set(f),g=[];for(let a of s){if(!w.has(a.relativePath))continue;let{md5:m}=await D(a.file);g.push({content:a.file,path:a.relativePath,size:a.file.size,md5:m})}return g}var Ue=x(()=>{"use strict";j();ne();re()});var Le={};U(Le,{convertBrowserInput:()=>ze,convertDeployInput:()=>st,convertNodeInput:()=>Se});import{ShipError as v}from"@shipstatic/types";function Be(o,e={}){let t=k();if(!e.skipEmptyCheck&&o.length===0)throw v.business("No files to deploy.");if(o.length>t.maxFilesCount)throw v.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){if(i.size>t.maxFileSize)throw v.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>t.maxTotalSize)throw v.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ne(o,e){if(e==="node"){if(!Array.isArray(o))throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw v.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw v.business("No files selected in HTMLInputElement")}function Ie(o){let e=o.map(t=>({name:t.path,size:t.size}));return Be(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Se(o,e={}){Ne(o,"node");let t=await W(o,e);return Ie(t)}async function ze(o,e={}){Ne(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw v.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw v.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),Be(t);let n=await Oe(t,e);return Ie(n)}async function st(o,e={},t){let n=h();if(n!=="node"&&n!=="browser")throw v.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await Se([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await Se(o,e);else throw v.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await ze(o,e);return i}var Ke=x(()=>{"use strict";P();we();Ue();K()});var X={};U(X,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,createTokenResource:()=>V,default:()=>Pe,filterJunk:()=>b,getCurrentConfig:()=>k,getENV:()=>h,loadConfig:()=>B,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>$,pluralize:()=>ue,processFilesForNode:()=>W,resolveConfig:()=>N,setConfig:()=>L,setPlatformConfig:()=>L});var d={};U(d,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,createTokenResource:()=>V,default:()=>Pe,filterJunk:()=>b,getCurrentConfig:()=>k,getENV:()=>h,loadConfig:()=>B,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>$,pluralize:()=>ue,processFilesForNode:()=>W,resolveConfig:()=>N,setConfig:()=>L,setPlatformConfig:()=>L});import*as ee from"mime-types";import{ShipError as C,DEFAULT_API as Ge}from"@shipstatic/types";var Z=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};P();var Q="/deployments",xe="/ping",E="/aliases",Je="/config",Ve="/account",pe="/tokens",We="/spa-check",T=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||Ge,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},n){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,n);let c=this.safeClone(s),f=this.safeClone(s);return this.emit("response",c,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,n),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?C.authentication(i):C.api(i,e.status,n.code,n)}handleFetchError(e,t){throw e.name==="AbortError"?C.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?C.network(`${t} failed due to network error: ${e.message}`,e):e instanceof C?e:C.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${xe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${xe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Je}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e,t.tags),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${Q}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t,n){let i={deployment:t};n&&n.length>0&&(i.tags=n);let r={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},s=this.getAuthHeaders(r.headers),c={...r,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${E}/${encodeURIComponent(e)}`,c);try{let f=await fetch(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,c);f.ok||await this.handleResponseError(f,"Set Alias");let w=this.safeClone(f),g=this.safeClone(f);return this.emit("response",w,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),{...await this.parseResponse(g),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${E}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Alias"),f}}async getAlias(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.request(`${this.apiUrl}${E}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async confirmAlias(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Alias")}async getAliasDns(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Alias DNS")}async getAliasRecords(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Alias Records")}async getAliasShare(e){return await this.request(`${this.apiUrl}${E}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Alias Share")}async getAccount(){return await this.request(`${this.apiUrl}${Ve}`,{method:"GET"},"Get Account")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t&&t.length>0&&(n.tags=t),await this.request(`${this.apiUrl}${pe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${pe}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${pe}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${We}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw C.business("No files to deploy.");for(let t of e)if(!t.md5)throw C.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(h()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(h()==="node"){let{body:n,headers:i}=await this.createNodeBody(e,t);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw C.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let n=new FormData,i=[];for(let r of e){if(!(r.content instanceof File||r.content instanceof Blob))throw C.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let s=this.getBrowserContentType(r.content instanceof File?r.content:r.path),c=new File([r.content],r.path,{type:s});n.append("files[]",c),i.push(r.md5)}return n.append("checksums",JSON.stringify(i)),t&&t.length>0&&n.append("tags",JSON.stringify(t)),n}async createNodeBody(e,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new n,c=[];for(let a of e){let m=ee.lookup(a.path)||"application/octet-stream",u;if(Buffer.isBuffer(a.content))u=new i([a.content],a.path,{type:m});else if(typeof Blob<"u"&&a.content instanceof Blob)u=new i([a.content],a.path,{type:m});else throw C.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let F=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",u,F),c.push(a.md5)}s.append("checksums",JSON.stringify(c)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new r(s),w=[];for await(let a of f.encode())w.push(Buffer.from(a));let g=Buffer.concat(w);return{body:g,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}getBrowserContentType(e){return typeof e=="string"?ee.lookup(e)||"application/octet-stream":ee.lookup(e.name)||e.type||"application/octet-stream"}};P();import{DEFAULT_API as Ze}from"@shipstatic/types";async function Qe(o){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(te(),Te));return t(o)}else return{}}function N(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ze,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function q(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}j();import{DEPLOYMENT_CONFIG_FILENAME as De}from"@shipstatic/types";async function ot(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await D(t);return{path:De,content:t,size:e.length,md5:n}}async function Re(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===De))return o;try{if(await e.checkSPA(o)){let i=await ot();return[...o,i]}}catch{}return o}function H(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?q(r,e):r,c=o();if(!n)throw new Error("processInput function is not provided.");let f=await n(i,s);return f=await Re(f,c,s),await c.deploy(f,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function G(o,e){return{set:async(t,n,i)=>(e&&await e(),o().setAlias(t,n,i)),get:async t=>(e&&await e(),o().getAlias(t)),list:async()=>(e&&await e(),o().listAliases()),remove:async t=>{e&&await e(),await o().removeAlias(t)},confirm:async t=>(e&&await e(),o().confirmAlias(t)),dns:async t=>(e&&await e(),o().getAliasDns(t)),records:async t=>(e&&await e(),o().getAliasRecords(t)),share:async t=>(e&&await e(),o().getAliasShare(t))}}function J(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function V(o,e){return{create:async(t,n)=>(e&&await e(),o().createToken(t,n)),list:async()=>(e&&await e(),o().listTokens()),remove:async t=>{e&&await e(),await o().removeToken(t)}}}var z=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new T({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=H(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._aliases=G(i,n),this._account=J(i,n),this._tokens=V(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get aliases(){return this._aliases}get account(){return this._account}get tokens(){return this._tokens}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};P();te();import{ShipError as ve}from"@shipstatic/types";K();var l={};U(l,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>z,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>D,createAccountResource:()=>J,createAliasResource:()=>G,createDeploymentResource:()=>H,createTokenResource:()=>V,filterJunk:()=>b,getENV:()=>h,loadConfig:()=>Qe,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>$,pluralize:()=>ue,resolveConfig:()=>N});var y={};p(y,Ot);import*as Ot from"@shipstatic/types";p(l,y);import{DEFAULT_API as me}from"@shipstatic/types";j();function ue(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}ne();re();P();import{ShipError as ye,ShipErrorType as ge}from"@shipstatic/types";p(d,l);te();K();K();we();P();var Y=class extends z{constructor(e={}){if(h()!=="node")throw ve.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return N(e,{})}async loadFullConfig(){try{let e=await B(this.clientOptions.configFile),t=N(this.clientOptions,e),n=new T({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();L(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw ve.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw ve.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(Ke(),Le));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},Pe=Y;p(X,d);export{T as ApiHttp,me as DEFAULT_API,oe as JUNK_DIRECTORIES,Y as Ship,ye as ShipError,ge as ShipErrorType,M as __setTestEnvironment,D as calculateMD5,J as createAccountResource,G as createAliasResource,H as createDeploymentResource,V as createTokenResource,Pe as default,b as filterJunk,k as getCurrentConfig,h as getENV,B as loadConfig,q as mergeDeployOptions,$ as optimizeDeployPaths,ue as pluralize,W as processFilesForNode,N as resolveConfig,L as setConfig,L as setPlatformConfig};
|
|
1
|
+
var Ce=Object.defineProperty;var _e=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var F=(o,e)=>()=>(o&&(e=o(o=0)),e);var U=(o,e)=>{for(var t in e)Ce(o,t,{get:e[t],enumerable:!0})},Pe=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of qe(e))!je.call(o,i)&&i!==t&&Ce(o,i,{get:()=>e[i],enumerable:!(n=_e(e,i))||n.enumerable});return o},p=(o,e,t)=>(Pe(o,e,"default"),t&&Pe(t,e,"default"));var Ee={};U(Ee,{__setTestEnvironment:()=>M,getENV:()=>h});function M(o){ae=o}function He(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function h(){return ae||He()}var ae,v=F(()=>{"use strict";ae=null});var Te={};U(Te,{loadConfig:()=>N});import{z as _}from"zod";import{ShipError as le}from"@shipstatic/types";function xe(o){try{return Ye.parse(o)}catch(e){if(e instanceof _.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw le.config(`Configuration validation failed${n}: ${t.message}`)}throw le.config("Configuration validation failed")}}async function Xe(o){try{if(h()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),n=e(ce,{searchPlaces:[`.${ce}rc`,"package.json",`${t.homedir()}/.${ce}rc`],stopDir:t.homedir()}),i;if(o?i=n.load(o):i=n.search(),i&&i.config)return xe(i.config)}catch(e){if(e instanceof le)throw e}return{}}async function N(o){if(h()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await Xe(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return xe(n)}var ce,Ye,te=F(()=>{"use strict";v();ce="ship",Ye=_.object({apiUrl:_.string().url().optional(),apiKey:_.string().optional(),deployToken:_.string().optional()}).strict()});import{ShipError as I}from"@shipstatic/types";async function et(o){let e=(await import("spark-md5")).default;return new Promise((t,n)=>{let r=Math.ceil(o.size/2097152),s=0,l=new e.ArrayBuffer,f=new FileReader,w=()=>{let g=s*2097152,a=Math.min(g+2097152,o.size);f.readAsArrayBuffer(o.slice(g,a))};f.onload=g=>{let a=g.target?.result;if(!a){n(I.business("Failed to read file chunk"));return}l.append(a),s++,s<r?w():t({md5:l.end()})},f.onerror=()=>{n(I.business("Failed to calculate MD5: FileReader error"))},w()})}async function tt(o){let e=await import("crypto");if(Buffer.isBuffer(o)){let n=e.createHash("md5");return n.update(o),{md5:n.digest("hex")}}let t=await import("fs");return new Promise((n,i)=>{let r=e.createHash("md5"),s=t.createReadStream(o);s.on("error",l=>i(I.business(`Failed to read file for MD5: ${l.message}`))),s.on("data",l=>r.update(l)),s.on("end",()=>n({md5:r.digest("hex")}))})}async function R(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw I.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return et(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw I.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return tt(o)}throw I.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=F(()=>{"use strict";v()});import{ShipError as nt}from"@shipstatic/types";function L(o){fe=o}function b(){if(fe===null)throw nt.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return fe}var fe,K=F(()=>{"use strict";fe=null});import{isJunk as it}from"junk";function $(o){return!o||o.length===0?[]:o.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let n=t[t.length-1];if(it(n))return!1;let i=t.slice(0,-1);for(let r of i)if(oe.some(s=>r.toLowerCase()===s.toLowerCase()))return!1;return!0})}var oe,ne=F(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function be(o){if(!o||o.length===0)return"";let e=o.filter(r=>r&&typeof r=="string").map(r=>r.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(r=>r.split("/").filter(Boolean)),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i;r++){let s=t[0][r];if(t.every(l=>l[r]===s))n.push(s);else break}return n.join("/")}function ie(o){return o.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var ue=F(()=>{"use strict"});function O(o,e={}){if(e.flatten===!1)return o.map(n=>({path:ie(n),name:he(n)}));let t=rt(o);return o.map(n=>{let i=ie(n);if(t){let r=t.endsWith("/")?t:`${t}/`;i.startsWith(r)&&(i=i.substring(r.length))}return i||(i=he(n)),{path:i,name:he(n)}})}function rt(o){if(!o.length)return"";let t=o.map(r=>ie(r)).map(r=>r.split("/")),n=[],i=Math.min(...t.map(r=>r.length));for(let r=0;r<i-1;r++){let s=t[0][r];if(t.every(l=>l[r]===s))n.push(s);else break}return n.join("/")}function he(o){return o.split(/[/\\]/).pop()||o}var re=F(()=>{"use strict";ue()});import{ShipError as A}from"@shipstatic/types";import*as k from"fs";import*as S from"path";function $e(o){let e=[];try{let t=k.readdirSync(o);for(let n of t){let i=S.join(o,n),r=k.statSync(i);if(r.isDirectory()){let s=$e(i);e.push(...s)}else r.isFile()&&e.push(i)}}catch(t){console.error(`Error reading directory ${o}:`,t)}return e}async function W(o,e={}){if(h()!=="node")throw A.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(m=>{let d=S.resolve(m);try{return k.statSync(d).isDirectory()?$e(d):[d]}catch{throw A.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=$(n);if(i.length===0)return[];let r=o.map(m=>S.resolve(m)),s=be(r.map(m=>{try{return k.statSync(m).isDirectory()?m:S.dirname(m)}catch{return S.dirname(m)}})),l=i.map(m=>{if(s&&s.length>0){let d=S.relative(s,m);if(d&&typeof d=="string"&&!d.startsWith(".."))return d.replace(/\\/g,"/")}return S.basename(m)}),f=O(l,{flatten:e.pathDetect!==!1}),w=[],g=0,a=b();for(let m=0;m<i.length;m++){let d=i[m],E=f[m].path;try{let x=k.statSync(d);if(x.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(x.size>a.maxFileSize)throw A.business(`File ${d} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=x.size,g>a.maxTotalSize)throw A.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let se=k.readFileSync(d),{md5:Me}=await R(se);if(E.includes("\0")||E.includes("/../")||E.startsWith("../")||E.endsWith("/.."))throw A.business(`Security error: Unsafe file path "${E}" for file: ${d}`);w.push({path:E,content:se,size:se.length,md5:Me})}catch(x){if(x instanceof A&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${d}:`,x)}}if(w.length>a.maxFilesCount)throw A.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return w}var we=F(()=>{"use strict";v();j();ne();K();re();ue()});import{ShipError as Oe}from"@shipstatic/types";async function Ae(o,e={}){let{getENV:t}=await Promise.resolve().then(()=>(v(),Ee));if(t()!=="browser")throw Oe.business("processFilesForBrowser can only be called in a browser environment.");let n=Array.isArray(o)?o:Array.from(o),i=n.map(a=>a.webkitRelativePath||a.name),r=O(i,{flatten:e.pathDetect!==!1}),s=[];for(let a=0;a<n.length;a++){let m=n[a],d=r[a].path;if(d.includes("..")||d.includes("\0"))throw Oe.business(`Security error: Unsafe file path "${d}" for file: ${m.name}`);s.push({file:m,relativePath:d})}let l=s.map(a=>a.relativePath),f=$(l),w=new Set(f),g=[];for(let a of s){if(!w.has(a.relativePath))continue;let{md5:m}=await R(a.file);g.push({content:a.file,path:a.relativePath,size:a.file.size,md5:m})}return g}var Ue=F(()=>{"use strict";j();ne();re()});var Le={};U(Le,{convertBrowserInput:()=>ze,convertDeployInput:()=>st,convertNodeInput:()=>Se});import{ShipError as D}from"@shipstatic/types";function Ne(o,e={}){let t=b();if(!e.skipEmptyCheck&&o.length===0)throw D.business("No files to deploy.");if(o.length>t.maxFilesCount)throw D.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let n=0;for(let i of o){if(i.size>t.maxFileSize)throw D.business(`File ${i.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(n+=i.size,n>t.maxTotalSize)throw D.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Be(o,e){if(e==="node"){if(!Array.isArray(o))throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(o.length===0)throw D.business("No files to deploy.");if(!o.every(t=>typeof t=="string"))throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&o instanceof HTMLInputElement&&!o.files)throw D.business("No files selected in HTMLInputElement")}function Ie(o){let e=o.map(t=>({name:t.path,size:t.size}));return Ne(e,{skipEmptyCheck:!0}),o.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),o}async function Se(o,e={}){Be(o,"node");let t=await W(o,e);return Ie(t)}async function ze(o,e={}){Be(o,"browser");let t;if(o instanceof HTMLInputElement)t=Array.from(o.files);else if(typeof o=="object"&&o!==null&&typeof o.length=="number"&&typeof o.item=="function")t=Array.from(o);else if(Array.isArray(o)){if(o.length>0&&typeof o[0]=="string")throw D.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=o}else throw D.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(i=>i.size===0?(console.warn(`Skipping empty file: ${i.name}`),!1):!0),Ne(t);let n=await Ae(t,e);return Ie(n)}async function st(o,e={},t){let n=h();if(n!=="node"&&n!=="browser")throw D.business("Unsupported execution environment.");let i;if(n==="node")if(typeof o=="string")i=await Se([o],e);else if(Array.isArray(o)&&o.every(r=>typeof r=="string"))i=await Se(o,e);else throw D.business("Invalid input type for Node.js environment. Expected string[] file paths.");else i=await ze(o,e);return i}var Ke=F(()=>{"use strict";v();we();Ue();K()});var X={};U(X,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>R,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>ve,filterJunk:()=>$,getCurrentConfig:()=>b,getENV:()=>h,loadConfig:()=>N,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>O,pluralize:()=>de,processFilesForNode:()=>W,resolveConfig:()=>B,setConfig:()=>L,setPlatformConfig:()=>L});var u={};U(u,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>R,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>ve,filterJunk:()=>$,getCurrentConfig:()=>b,getENV:()=>h,loadConfig:()=>N,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>O,pluralize:()=>de,processFilesForNode:()=>W,resolveConfig:()=>B,setConfig:()=>L,setPlatformConfig:()=>L});import*as ee from"mime-types";import{ShipError as P,DEFAULT_API as Ge}from"@shipstatic/types";var Z=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){let n=this.handlers.get(e);n&&(n.delete(t),n.size===0&&this.handlers.delete(e))}emit(e,...t){let n=this.handlers.get(e);if(!n)return;let i=Array.from(n);for(let r of i)try{r(...t)}catch(s){n.delete(r),e!=="error"&&setTimeout(()=>{s instanceof Error?this.emit("error",s,String(e)):this.emit("error",new Error(String(s)),String(e))},0)}}transfer(e){this.handlers.forEach((t,n)=>{t.forEach(i=>{e.on(n,i)})})}clear(){this.handlers.clear()}};v();var Q="/deployments",Fe="/ping",C="/domains",Je="/config",Ve="/account",pe="/tokens",We="/spa-check",T=class extends Z{constructor(e){super(),this.apiUrl=e.apiUrl||Ge,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},n){let i=this.getAuthHeaders(t.headers),r={...t,headers:i,credentials:this.needsCredentials(i)?"include":void 0};this.emit("request",e,r);try{let s=await fetch(e,r);s.ok||await this.handleResponseError(s,n);let l=this.safeClone(s),f=this.safeClone(s);return this.emit("response",l,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,n),s}}getAuthHeaders(e={}){let t={...e};return this.deployToken?t.Authorization=`Bearer ${this.deployToken}`:this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}needsCredentials(e){return!this.apiKey&&!this.deployToken&&!e.Authorization}safeClone(e){try{return e.clone()}catch{return e}}async parseResponse(e){if(!(e.headers.get("Content-Length")==="0"||e.status===204))return await e.json()}async handleResponseError(e,t){let n={};try{e.headers.get("content-type")?.includes("application/json")?n=await e.json():n={message:await e.text()}}catch{n={message:"Failed to parse error response"}}let i=n.message||n.error||`${t} failed due to API error`;throw e.status===401?P.authentication(i):P.api(i,e.status,n.code,n)}handleFetchError(e,t){throw e.name==="AbortError"?P.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?P.network(`${t} failed due to network error: ${e.message}`,e):e instanceof P?e:P.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${Fe}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${Je}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:n,requestHeaders:i}=await this.prepareRequestPayload(e,t.tags),r={};t.deployToken?r={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(r={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:n,headers:{...i,...r},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${Q}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${Q}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${Q}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${Q}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,n){let i={deployment:t};n&&n.length>0&&(i.tags=n);let r={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},s=this.getAuthHeaders(r.headers),l={...r,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);try{let f=await fetch(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,l);f.ok||await this.handleResponseError(f,"Set Domain");let w=this.safeClone(f),g=this.safeClone(f);return this.emit("response",w,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),{...await this.parseResponse(g),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${C}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${C}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${C}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${Ve}`,{method:"GET"},"Get Account")}async createToken(e,t){let n={};return e!==void 0&&(n.ttl=e),t&&t.length>0&&(n.tags=t),await this.request(`${this.apiUrl}${pe}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${pe}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${pe}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Token")}async checkSPA(e){let t=e.find(s=>s.path==="index.html"||s.path==="/index.html");if(!t||t.size>100*1024)return!1;let n;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))n=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)n=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)n=await t.content.text();else return!1;let i={files:e.map(s=>s.path),index:n};return(await this.request(`${this.apiUrl}${We}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw P.business("No files to deploy.");for(let t of e)if(!t.md5)throw P.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(h()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(h()==="node"){let{body:n,headers:i}=await this.createNodeBody(e,t);return{requestBody:n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength),requestHeaders:i}}else throw P.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let n=new FormData,i=[];for(let r of e){if(!(r.content instanceof File||r.content instanceof Blob))throw P.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let s=this.getBrowserContentType(r.content instanceof File?r.content:r.path),l=new File([r.content],r.path,{type:s});n.append("files[]",l),i.push(r.md5)}return n.append("checksums",JSON.stringify(i)),t&&t.length>0&&n.append("tags",JSON.stringify(t)),n}async createNodeBody(e,t){let{FormData:n,File:i}=await import("formdata-node"),{FormDataEncoder:r}=await import("form-data-encoder"),s=new n,l=[];for(let a of e){let m=ee.lookup(a.path)||"application/octet-stream",d;if(Buffer.isBuffer(a.content))d=new i([a.content],a.path,{type:m});else if(typeof Blob<"u"&&a.content instanceof Blob)d=new i([a.content],a.path,{type:m});else throw P.file(`Unsupported file.content type for Node.js FormData: ${a.path}`,a.path);let E=a.path.startsWith("/")?a.path:"/"+a.path;s.append("files[]",d,E),l.push(a.md5)}s.append("checksums",JSON.stringify(l)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new r(s),w=[];for await(let a of f.encode())w.push(Buffer.from(a));let g=Buffer.concat(w);return{body:g,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(g).toString()}}}getBrowserContentType(e){return typeof e=="string"?ee.lookup(e)||"application/octet-stream":ee.lookup(e.name)||e.type||"application/octet-stream"}};v();import{DEFAULT_API as Ze}from"@shipstatic/types";async function Qe(o){let e=h();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(te(),Te));return t(o)}else return{}}function B(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Ze,apiKey:o.apiKey!==void 0?o.apiKey:e.apiKey,deployToken:o.deployToken!==void 0?o.deployToken:e.deployToken},n={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(n.apiKey=t.apiKey),t.deployToken!==void 0&&(n.deployToken=t.deployToken),n}function q(o,e){let t={...o};return t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.deployToken===void 0&&e.deployToken!==void 0&&(t.deployToken=e.deployToken),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.maxConcurrency===void 0&&e.maxConcurrency!==void 0&&(t.maxConcurrency=e.maxConcurrency),t.onProgress===void 0&&e.onProgress!==void 0&&(t.onProgress=e.onProgress),t.onProgressStats===void 0&&e.onProgressStats!==void 0&&(t.onProgressStats=e.onProgressStats),t}j();import{DEPLOYMENT_CONFIG_FILENAME as Re}from"@shipstatic/types";async function ot(){let e=JSON.stringify({rewrites:[{source:"/(.*)",destination:"/index.html"}]},null,2),t;typeof Buffer<"u"?t=Buffer.from(e,"utf-8"):t=new Blob([e],{type:"application/json"});let{md5:n}=await R(t);return{path:Re,content:t,size:e.length,md5:n}}async function ke(o,e,t){if(t.spaDetect===!1||o.some(n=>n.path===Re))return o;try{if(await e.checkSPA(o)){let i=await ot();return[...o,i]}}catch{}return o}function H(o,e,t,n){return{create:async(i,r={})=>{t&&await t();let s=e?q(r,e):r,l=o();if(!n)throw new Error("processInput function is not provided.");let f=await n(i,s);return f=await ke(f,l,s),await l.deploy(f,s)},list:async()=>(t&&await t(),o().listDeployments()),remove:async i=>{t&&await t(),await o().removeDeployment(i)},get:async i=>(t&&await t(),o().getDeployment(i))}}function G(o,e){return{set:async(t,n,i)=>(e&&await e(),o().setDomain(t,n,i)),get:async t=>(e&&await e(),o().getDomain(t)),list:async()=>(e&&await e(),o().listDomains()),remove:async t=>{e&&await e(),await o().removeDomain(t)},confirm:async t=>(e&&await e(),o().confirmDomain(t)),dns:async t=>(e&&await e(),o().getDomainDns(t)),records:async t=>(e&&await e(),o().getDomainRecords(t)),share:async t=>(e&&await e(),o().getDomainShare(t))}}function J(o,e){return{get:async()=>(e&&await e(),o().getAccount())}}function V(o,e){return{create:async(t,n)=>(e&&await e(),o().createToken(t,n)),list:async()=>(e&&await e(),o().listTokens()),remove:async t=>{e&&await e(),await o().removeToken(t)}}}var z=class{constructor(e={}){this.initPromise=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new T({...e,...t});let n=()=>this.ensureInitialized(),i=()=>this.http;this._deployments=H(i,this.clientOptions,n,(r,s)=>this.processInput(r,s)),this._domains=G(i,n),this._account=J(i,n),this._tokens=V(i,n)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.loadFullConfig()),this.initPromise}async ping(){return await this.ensureInitialized(),this.http.ping()}async deploy(e,t){return this.deployments.create(e,t)}async whoami(){return this.account.get()}get deployments(){return this._deployments}get domains(){return this._domains}get account(){return this._account}get tokens(){return this._tokens}on(e,t){this.http.on(e,t)}off(e,t){this.http.off(e,t)}replaceHttpClient(e){if(this.http?.transferEventsTo)try{this.http.transferEventsTo(e)}catch(t){console.warn("Event transfer failed during client replacement:",t)}this.http=e}};v();te();import{ShipError as De}from"@shipstatic/types";K();var c={};U(c,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>z,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>M,calculateMD5:()=>R,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,filterJunk:()=>$,getENV:()=>h,loadConfig:()=>Qe,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>O,pluralize:()=>de,resolveConfig:()=>B});var y={};p(y,At);import*as At from"@shipstatic/types";p(c,y);import{DEFAULT_API as me}from"@shipstatic/types";j();function de(o,e,t,n=!0){let i=o===1?e:t;return n?`${o} ${i}`:i}ne();re();v();import{ShipError as ye,ShipErrorType as ge}from"@shipstatic/types";p(u,c);te();K();K();we();v();var Y=class extends z{constructor(e={}){if(h()!=="node")throw De.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return B(e,{})}async loadFullConfig(){try{let e=await N(this.clientOptions.configFile),t=B(this.clientOptions,e),n=new T({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();L(i)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw De.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw De.business("No files to deploy.");let{convertDeployInput:n}=await Promise.resolve().then(()=>(Ke(),Le));return n(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},ve=Y;p(X,u);export{T as ApiHttp,me as DEFAULT_API,oe as JUNK_DIRECTORIES,Y as Ship,ye as ShipError,ge as ShipErrorType,M as __setTestEnvironment,R as calculateMD5,J as createAccountResource,H as createDeploymentResource,G as createDomainResource,V as createTokenResource,ve as default,$ as filterJunk,b as getCurrentConfig,h as getENV,N as loadConfig,q as mergeDeployOptions,O as optimizeDeployPaths,de as pluralize,W as processFilesForNode,B as resolveConfig,L as setConfig,L as setPlatformConfig};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|