@shipstatic/ship 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -439,6 +439,96 @@ declare function __setTestEnvironment(env: ExecutionEnvironment | null): void;
439
439
  */
440
440
  declare function getENV(): ExecutionEnvironment;
441
441
 
442
+ /**
443
+ * @file File validation utilities for Ship SDK
444
+ * Provides client-side validation for file uploads before deployment
445
+ */
446
+
447
+ /**
448
+ * File status constants for validation state tracking
449
+ */
450
+ declare const FILE_VALIDATION_STATUS: {
451
+ readonly PENDING: "pending";
452
+ readonly PROCESSING_ERROR: "processing_error";
453
+ readonly EMPTY_FILE: "empty_file";
454
+ readonly VALIDATION_FAILED: "validation_failed";
455
+ readonly READY: "ready";
456
+ };
457
+ type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
458
+ /**
459
+ * Client-side validation error structure
460
+ */
461
+ interface ValidationError {
462
+ error: string;
463
+ details: string;
464
+ errors: string[];
465
+ isClientError: true;
466
+ }
467
+ /**
468
+ * Minimal file interface required for validation
469
+ */
470
+ interface ValidatableFile {
471
+ name: string;
472
+ size: number;
473
+ type: string;
474
+ status?: string;
475
+ statusMessage?: string;
476
+ }
477
+ /**
478
+ * File validation result
479
+ *
480
+ * NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
481
+ * This ensures deployments are all-or-nothing for data integrity.
482
+ */
483
+ interface FileValidationResult<T extends ValidatableFile> {
484
+ /** All files with updated status */
485
+ files: T[];
486
+ /** Files that passed validation (empty if ANY file failed - atomic validation) */
487
+ validFiles: T[];
488
+ /** Validation error if any files failed */
489
+ error: ValidationError | null;
490
+ }
491
+ /**
492
+ * Format file size to human-readable string
493
+ */
494
+ declare function formatFileSize(bytes: number, decimals?: number): string;
495
+ /**
496
+ * Validate files against configuration limits
497
+ *
498
+ * ATOMIC VALIDATION: If ANY file fails validation, ALL files are rejected.
499
+ * This ensures deployments are all-or-nothing for data integrity.
500
+ *
501
+ * @param files - Array of files to validate
502
+ * @param config - Validation configuration from ship.getConfig()
503
+ * @returns Validation result with updated file status
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * const config = await ship.getConfig();
508
+ * const result = validateFiles(files, config);
509
+ *
510
+ * if (result.error) {
511
+ * // Validation failed - result.validFiles will be empty
512
+ * console.error(result.error.details);
513
+ * // Show individual file errors:
514
+ * result.files.forEach(f => console.log(`${f.name}: ${f.statusMessage}`));
515
+ * } else {
516
+ * // All files valid - safe to upload
517
+ * await ship.deploy(result.validFiles);
518
+ * }
519
+ * ```
520
+ */
521
+ declare function validateFiles<T extends ValidatableFile>(files: T[], config: ConfigResponse): FileValidationResult<T>;
522
+ /**
523
+ * Get only the valid files from validation results
524
+ */
525
+ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
526
+ /**
527
+ * Check if all valid files have required properties for upload
528
+ * (Can be extended to check for MD5, etc.)
529
+ */
530
+ declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
531
+
442
532
  /**
443
533
  * @file Manages loading and validation of client configuration.
444
534
  * This module uses `cosmiconfig` to find and load configuration from various
@@ -513,4 +603,4 @@ declare class Ship extends Ship$1 {
513
603
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
514
604
  }
515
605
 
516
- 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 };
606
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, type ValidatableFile, type ValidationError, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
package/dist/index.d.ts CHANGED
@@ -439,6 +439,96 @@ declare function __setTestEnvironment(env: ExecutionEnvironment | null): void;
439
439
  */
440
440
  declare function getENV(): ExecutionEnvironment;
441
441
 
442
+ /**
443
+ * @file File validation utilities for Ship SDK
444
+ * Provides client-side validation for file uploads before deployment
445
+ */
446
+
447
+ /**
448
+ * File status constants for validation state tracking
449
+ */
450
+ declare const FILE_VALIDATION_STATUS: {
451
+ readonly PENDING: "pending";
452
+ readonly PROCESSING_ERROR: "processing_error";
453
+ readonly EMPTY_FILE: "empty_file";
454
+ readonly VALIDATION_FAILED: "validation_failed";
455
+ readonly READY: "ready";
456
+ };
457
+ type FileValidationStatus = (typeof FILE_VALIDATION_STATUS)[keyof typeof FILE_VALIDATION_STATUS];
458
+ /**
459
+ * Client-side validation error structure
460
+ */
461
+ interface ValidationError {
462
+ error: string;
463
+ details: string;
464
+ errors: string[];
465
+ isClientError: true;
466
+ }
467
+ /**
468
+ * Minimal file interface required for validation
469
+ */
470
+ interface ValidatableFile {
471
+ name: string;
472
+ size: number;
473
+ type: string;
474
+ status?: string;
475
+ statusMessage?: string;
476
+ }
477
+ /**
478
+ * File validation result
479
+ *
480
+ * NOTE: Validation is ATOMIC - if any file fails validation, ALL files are rejected.
481
+ * This ensures deployments are all-or-nothing for data integrity.
482
+ */
483
+ interface FileValidationResult<T extends ValidatableFile> {
484
+ /** All files with updated status */
485
+ files: T[];
486
+ /** Files that passed validation (empty if ANY file failed - atomic validation) */
487
+ validFiles: T[];
488
+ /** Validation error if any files failed */
489
+ error: ValidationError | null;
490
+ }
491
+ /**
492
+ * Format file size to human-readable string
493
+ */
494
+ declare function formatFileSize(bytes: number, decimals?: number): string;
495
+ /**
496
+ * Validate files against configuration limits
497
+ *
498
+ * ATOMIC VALIDATION: If ANY file fails validation, ALL files are rejected.
499
+ * This ensures deployments are all-or-nothing for data integrity.
500
+ *
501
+ * @param files - Array of files to validate
502
+ * @param config - Validation configuration from ship.getConfig()
503
+ * @returns Validation result with updated file status
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * const config = await ship.getConfig();
508
+ * const result = validateFiles(files, config);
509
+ *
510
+ * if (result.error) {
511
+ * // Validation failed - result.validFiles will be empty
512
+ * console.error(result.error.details);
513
+ * // Show individual file errors:
514
+ * result.files.forEach(f => console.log(`${f.name}: ${f.statusMessage}`));
515
+ * } else {
516
+ * // All files valid - safe to upload
517
+ * await ship.deploy(result.validFiles);
518
+ * }
519
+ * ```
520
+ */
521
+ declare function validateFiles<T extends ValidatableFile>(files: T[], config: ConfigResponse): FileValidationResult<T>;
522
+ /**
523
+ * Get only the valid files from validation results
524
+ */
525
+ declare function getValidFiles<T extends ValidatableFile>(files: T[]): T[];
526
+ /**
527
+ * Check if all valid files have required properties for upload
528
+ * (Can be extended to check for MD5, etc.)
529
+ */
530
+ declare function allValidFilesReady<T extends ValidatableFile>(files: T[]): boolean;
531
+
442
532
  /**
443
533
  * @file Manages loading and validation of client configuration.
444
534
  * This module uses `cosmiconfig` to find and load configuration from various
@@ -513,4 +603,4 @@ declare class Ship extends Ship$1 {
513
603
  protected processInput(input: DeployInput, options: DeploymentOptions): Promise<StaticFile[]>;
514
604
  }
515
605
 
516
- 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 };
606
+ export { type ApiDeployOptions, ApiHttp, type Config, type DeployFile, type DeploymentOptions, type ExecutionEnvironment, FILE_VALIDATION_STATUS, type FileValidationResult, type FileValidationStatus, JUNK_DIRECTORIES, type MD5Result, type ProgressStats, Ship, type ShipClientOptions, type ShipEvents, type ValidatableFile, type ValidationError, __setTestEnvironment, allValidFilesReady, calculateMD5, createAccountResource, createDeploymentResource, createDomainResource, createTokenResource, Ship as default, filterJunk, formatFileSize, getCurrentConfig, getENV, getValidFiles, loadConfig, mergeDeployOptions, optimizeDeployPaths, pluralize, processFilesForNode, resolveConfig, setConfig, setConfig as setPlatformConfig, validateFiles };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var Ce=Object.defineProperty;var Me=Object.getOwnPropertyDescriptor;var qe=Object.getOwnPropertyNames;var je=Object.prototype.hasOwnProperty;var F=(o,e)=>()=>(o&&(e=o(o=0)),e);var N=(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=Me(e,i))||n.enumerable});return o},p=(o,e,t)=>(Pe(o,e,"default"),t&&Pe(t,e,"default"));var Ee={};N(Ee,{__setTestEnvironment:()=>K,getENV:()=>h});function K(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});import{ShipError as Ye}from"@shipstatic/types";function B(o){ce=o}function R(){if(ce===null)throw Ye.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return ce}var ce,$=F(()=>{"use strict";ce=null});var Te={};N(Te,{loadConfig:()=>I});import{z as M}from"zod";import{ShipError as fe}from"@shipstatic/types";function xe(o){try{return Xe.parse(o)}catch(e){if(e instanceof M.ZodError){let t=e.issues[0],n=t.path.length>0?` at ${t.path.join(".")}`:"";throw fe.config(`Configuration validation failed${n}: ${t.message}`)}throw fe.config("Configuration validation failed")}}async function Ze(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 xe(i.config)}catch(e){if(e instanceof fe)throw e}return{}}async function I(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 Ze(o),n={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return xe(n)}var le,Xe,te=F(()=>{"use strict";v();le="ship",Xe=M.object({apiUrl:M.string().url().optional(),apiKey:M.string().optional(),deployToken:M.string().optional()}).strict()});import{ShipError as _}from"@shipstatic/types";async function tt(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(_.business("Failed to read file chunk"));return}l.append(a),s++,s<r?w():t({md5:l.end()})},f.onerror=()=>{n(_.business("Failed to calculate MD5: FileReader error"))},w()})}async function ot(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(_.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 k(o){let e=h();if(e==="browser"){if(!(o instanceof Blob))throw _.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return tt(o)}if(e==="node"){if(!(Buffer.isBuffer(o)||typeof o=="string"))throw _.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ot(o)}throw _.business("Unknown or unsupported execution environment for MD5 calculation.")}var j=F(()=>{"use strict";v()});import{isJunk as it}from"junk";function O(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 A(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 U}from"@shipstatic/types";import*as b from"fs";import*as S from"path";function $e(o){let e=[];try{let t=b.readdirSync(o);for(let n of t){let i=S.join(o,n),r=b.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 U.business("processFilesForNode can only be called in Node.js environment.");let t=o.flatMap(m=>{let d=S.resolve(m);try{return b.statSync(d).isDirectory()?$e(d):[d]}catch{throw U.file(`Path does not exist: ${m}`,m)}}),n=[...new Set(t)],i=O(n);if(i.length===0)return[];let r=o.map(m=>S.resolve(m)),s=be(r.map(m=>{try{return b.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=A(l,{flatten:e.pathDetect!==!1}),w=[],g=0,a=R();for(let m=0;m<i.length;m++){let d=i[m],E=f[m].path;try{let x=b.statSync(d);if(x.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(x.size>a.maxFileSize)throw U.business(`File ${d} is too large. Maximum allowed size is ${a.maxFileSize/(1024*1024)}MB.`);if(g+=x.size,g>a.maxTotalSize)throw U.business(`Total deploy size is too large. Maximum allowed is ${a.maxTotalSize/(1024*1024)}MB.`);let se=b.readFileSync(d),{md5:Ke}=await k(se);if(E.includes("\0")||E.includes("/../")||E.startsWith("../")||E.endsWith("/.."))throw U.business(`Security error: Unsafe file path "${E}" for file: ${d}`);w.push({path:E,content:se,size:se.length,md5:Ke})}catch(x){if(x instanceof U&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${d}:`,x)}}if(w.length>a.maxFilesCount)throw U.business(`Too many files to deploy. Maximum allowed is ${a.maxFilesCount} files.`);return w}var we=F(()=>{"use strict";v();j();ne();$();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=A(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=O(l),w=new Set(f),g=[];for(let a of s){if(!w.has(a.relativePath))continue;let{md5:m}=await k(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 _e={};N(_e,{convertBrowserInput:()=>ze,convertDeployInput:()=>st,convertNodeInput:()=>Se});import{ShipError as D}from"@shipstatic/types";function Ne(o,e={}){let t=R();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 Le=F(()=>{"use strict";v();we();Ue();$()});var X={};N(X,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>K,calculateMD5:()=>k,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>ve,filterJunk:()=>O,getCurrentConfig:()=>R,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>de,processFilesForNode:()=>W,resolveConfig:()=>z,setConfig:()=>B,setPlatformConfig:()=>B});var u={};N(u,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>Y,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>K,calculateMD5:()=>k,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,default:()=>ve,filterJunk:()=>O,getCurrentConfig:()=>R,getENV:()=>h,loadConfig:()=>I,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>de,processFilesForNode:()=>W,resolveConfig:()=>z,setConfig:()=>B,setPlatformConfig:()=>B});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 Qe}from"@shipstatic/types";async function et(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 z(o={},e={}){let t={apiUrl:o.apiUrl||e.apiUrl||Qe,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 nt(){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 k(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 nt();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 L=class{constructor(e={}){this.initPromise=null;this._config=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}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=R(),this._config)}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";$();var c={};N(c,{ApiHttp:()=>T,DEFAULT_API:()=>me,JUNK_DIRECTORIES:()=>oe,Ship:()=>L,ShipError:()=>ye,ShipErrorType:()=>ge,__setTestEnvironment:()=>K,calculateMD5:()=>k,createAccountResource:()=>J,createDeploymentResource:()=>H,createDomainResource:()=>G,createTokenResource:()=>V,filterJunk:()=>O,getENV:()=>h,loadConfig:()=>et,mergeDeployOptions:()=>q,optimizeDeployPaths:()=>A,pluralize:()=>de,resolveConfig:()=>z});var y={};p(y,Ut);import*as Ut 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();$();$();we();v();var Y=class extends L{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 z(e,{})}async loadFullConfig(){try{let e=await I(this.clientOptions.configFile),t=z(this.clientOptions,e),n=new T({...this.clientOptions,...t});this.replaceHttpClient(n);let i=await this.http.getConfig();B(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(()=>(Le(),_e));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,K as __setTestEnvironment,k as calculateMD5,J as createAccountResource,H as createDeploymentResource,G as createDomainResource,V as createTokenResource,ve as default,O as filterJunk,R as getCurrentConfig,h as getENV,I as loadConfig,q as mergeDeployOptions,A as optimizeDeployPaths,de as pluralize,W as processFilesForNode,z as resolveConfig,B as setConfig,B as setPlatformConfig};
1
+ var Ae=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Xe=Object.getOwnPropertyNames;var Ze=Object.prototype.hasOwnProperty;var C=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>{for(var t in e)Ae(n,t,{get:e[t],enumerable:!0})},Re=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Xe(e))!Ze.call(n,r)&&r!==t&&Ae(n,r,{get:()=>e[r],enumerable:!(i=We(e,r))||i.enumerable});return n},l=(n,e,t)=>(Re(n,e,"default"),t&&Re(t,e,"default"));var be={};N(be,{__setTestEnvironment:()=>q,getENV:()=>y});function q(n){fe=n}function Qe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function y(){return fe||Qe()}var fe,F=C(()=>{"use strict";fe=null});import{ShipError as ot}from"@shipstatic/types";function L(n){de=n}function A(){if(de===null)throw ot.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return de}var de,$=C(()=>{"use strict";de=null});var ke={};N(ke,{loadConfig:()=>_});import{z as V}from"zod";import{ShipError as he}from"@shipstatic/types";function Oe(n){try{return rt.parse(n)}catch(e){if(e instanceof V.ZodError){let t=e.issues[0],i=t.path.length>0?` at ${t.path.join(".")}`:"";throw he.config(`Configuration validation failed${i}: ${t.message}`)}throw he.config("Configuration validation failed")}}async function st(n){try{if(y()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),i=e(ue,{searchPlaces:[`.${ue}rc`,"package.json",`${t.homedir()}/.${ue}rc`],stopDir:t.homedir()}),r;if(n?r=i.load(n):r=i.search(),r&&r.config)return Oe(r.config)}catch(e){if(e instanceof he)throw e}return{}}async function _(n){if(y()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY,deployToken:process.env.SHIP_DEPLOY_TOKEN},t=await st(n),i={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey,deployToken:e.deployToken??t.deployToken};return Oe(i)}var ue,rt,ie=C(()=>{"use strict";F();ue="ship",rt=V.object({apiUrl:V.string().url().optional(),apiKey:V.string().optional(),deployToken:V.string().optional()}).strict()});import{ShipError as U}from"@shipstatic/types";async function lt(n){let e=(await import("spark-md5")).default;return new Promise((t,i)=>{let o=Math.ceil(n.size/2097152),s=0,a=new e.ArrayBuffer,f=new FileReader,S=()=>{let E=s*2097152,p=Math.min(E+2097152,n.size);f.readAsArrayBuffer(n.slice(E,p))};f.onload=E=>{let p=E.target?.result;if(!p){i(U.business("Failed to read file chunk"));return}a.append(p),s++,s<o?S():t({md5:a.end()})},f.onerror=()=>{i(U.business("Failed to calculate MD5: FileReader error"))},S()})}async function ct(n){let e=await import("crypto");if(Buffer.isBuffer(n)){let i=e.createHash("md5");return i.update(n),{md5:i.digest("hex")}}let t=await import("fs");return new Promise((i,r)=>{let o=e.createHash("md5"),s=t.createReadStream(n);s.on("error",a=>r(U.business(`Failed to read file for MD5: ${a.message}`))),s.on("data",a=>o.update(a)),s.on("end",()=>i({md5:o.digest("hex")}))})}async function I(n){let e=y();if(e==="browser"){if(!(n instanceof Blob))throw U.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return lt(n)}if(e==="node"){if(!(Buffer.isBuffer(n)||typeof n=="string"))throw U.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return ct(n)}throw U.business("Unknown or unsupported execution environment for MD5 calculation.")}var H=C(()=>{"use strict";F()});import{isJunk as mt}from"junk";function O(n){return!n||n.length===0?[]:n.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let i=t[t.length-1];if(mt(i))return!1;let r=t.slice(0,-1);for(let o of r)if(oe.some(s=>o.toLowerCase()===s.toLowerCase()))return!1;return!0})}var oe,re=C(()=>{"use strict";oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"]});function Le(n){if(!n||n.length===0)return"";let e=n.filter(o=>o&&typeof o=="string").map(o=>o.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(o=>o.split("/").filter(Boolean)),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function se(n){return n.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"")}var Ee=C(()=>{"use strict"});function k(n,e={}){if(e.flatten===!1)return n.map(i=>({path:se(i),name:Se(i)}));let t=dt(n);return n.map(i=>{let r=se(i);if(t){let o=t.endsWith("/")?t:`${t}/`;r.startsWith(o)&&(r=r.substring(o.length))}return r||(r=Se(i)),{path:r,name:Se(i)}})}function dt(n){if(!n.length)return"";let t=n.map(o=>se(o)).map(o=>o.split("/")),i=[],r=Math.min(...t.map(o=>o.length));for(let o=0;o<r-1;o++){let s=t[0][o];if(t.every(a=>a[o]===s))i.push(s);else break}return i.join("/")}function Se(n){return n.split(/[/\\]/).pop()||n}var ae=C(()=>{"use strict";Ee()});import{ShipError as M}from"@shipstatic/types";import*as b from"fs";import*as D from"path";function ze(n){let e=[];try{let t=b.readdirSync(n);for(let i of t){let r=D.join(n,i),o=b.statSync(r);if(o.isDirectory()){let s=ze(r);e.push(...s)}else o.isFile()&&e.push(r)}}catch(t){console.error(`Error reading directory ${n}:`,t)}return e}async function X(n,e={}){if(y()!=="node")throw M.business("processFilesForNode can only be called in Node.js environment.");let t=n.flatMap(m=>{let d=D.resolve(m);try{return b.statSync(d).isDirectory()?ze(d):[d]}catch{throw M.file(`Path does not exist: ${m}`,m)}}),i=[...new Set(t)],r=O(i);if(r.length===0)return[];let o=n.map(m=>D.resolve(m)),s=Le(o.map(m=>{try{return b.statSync(m).isDirectory()?m:D.dirname(m)}catch{return D.dirname(m)}})),a=r.map(m=>{if(s&&s.length>0){let d=D.relative(s,m);if(d&&typeof d=="string"&&!d.startsWith(".."))return d.replace(/\\/g,"/")}return D.basename(m)}),f=k(a,{flatten:e.pathDetect!==!1}),S=[],E=0,p=A();for(let m=0;m<r.length;m++){let d=r[m],P=f[m].path;try{let x=b.statSync(d);if(x.size===0){console.warn(`Skipping empty file: ${d}`);continue}if(x.size>p.maxFileSize)throw M.business(`File ${d} is too large. Maximum allowed size is ${p.maxFileSize/(1024*1024)}MB.`);if(E+=x.size,E>p.maxTotalSize)throw M.business(`Total deploy size is too large. Maximum allowed is ${p.maxTotalSize/(1024*1024)}MB.`);let le=b.readFileSync(d),{md5:Ye}=await I(le);if(P.includes("\0")||P.includes("/../")||P.startsWith("../")||P.endsWith("/.."))throw M.business(`Security error: Unsafe file path "${P}" for file: ${d}`);S.push({path:P,content:le,size:le.length,md5:Ye})}catch(x){if(x instanceof M&&x.isClientError&&x.isClientError())throw x;console.error(`Could not process file ${d}:`,x)}}if(S.length>p.maxFilesCount)throw M.business(`Too many files to deploy. Maximum allowed is ${p.maxFilesCount} files.`);return S}var Te=C(()=>{"use strict";F();H();re();$();ae();Ee()});import{ShipError as Ue}from"@shipstatic/types";async function Be(n,e={}){let{getENV:t}=await Promise.resolve().then(()=>(F(),be));if(t()!=="browser")throw Ue.business("processFilesForBrowser can only be called in a browser environment.");let i=Array.isArray(n)?n:Array.from(n),r=i.map(p=>p.webkitRelativePath||p.name),o=k(r,{flatten:e.pathDetect!==!1}),s=[];for(let p=0;p<i.length;p++){let m=i[p],d=o[p].path;if(d.includes("..")||d.includes("\0"))throw Ue.business(`Security error: Unsafe file path "${d}" for file: ${m.name}`);s.push({file:m,relativePath:d})}let a=s.map(p=>p.relativePath),f=O(a),S=new Set(f),E=[];for(let p of s){if(!S.has(p.relativePath))continue;let{md5:m}=await I(p.file);E.push({content:p.file,path:p.relativePath,size:p.file.size,md5:m})}return E}var Ke=C(()=>{"use strict";H();re();ae()});var Ge={};N(Ge,{convertBrowserInput:()=>He,convertDeployInput:()=>gt,convertNodeInput:()=>Pe});import{ShipError as w}from"@shipstatic/types";function qe(n,e={}){let t=A();if(!e.skipEmptyCheck&&n.length===0)throw w.business("No files to deploy.");if(n.length>t.maxFilesCount)throw w.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let i=0;for(let r of n){if(r.size>t.maxFileSize)throw w.business(`File ${r.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(i+=r.size,i>t.maxTotalSize)throw w.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function Ve(n,e){if(e==="node"){if(!Array.isArray(n))throw w.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(n.length===0)throw w.business("No files to deploy.");if(!n.every(t=>typeof t=="string"))throw w.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&n instanceof HTMLInputElement&&!n.files)throw w.business("No files selected in HTMLInputElement")}function je(n){let e=n.map(t=>({name:t.path,size:t.size}));return qe(e,{skipEmptyCheck:!0}),n.forEach(t=>{t.path&&(t.path=t.path.replace(/\\/g,"/"))}),n}async function Pe(n,e={}){Ve(n,"node");let t=await X(n,e);return je(t)}async function He(n,e={}){Ve(n,"browser");let t;if(n instanceof HTMLInputElement)t=Array.from(n.files);else if(typeof n=="object"&&n!==null&&typeof n.length=="number"&&typeof n.item=="function")t=Array.from(n);else if(Array.isArray(n)){if(n.length>0&&typeof n[0]=="string")throw w.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=n}else throw w.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(r=>r.size===0?(console.warn(`Skipping empty file: ${r.name}`),!1):!0),qe(t);let i=await Be(t,e);return je(i)}async function gt(n,e={},t){let i=y();if(i!=="node"&&i!=="browser")throw w.business("Unsupported execution environment.");let r;if(i==="node")if(typeof n=="string")r=await Pe([n],e);else if(Array.isArray(n)&&n.every(o=>typeof o=="string"))r=await Pe(n,e);else throw w.business("Invalid input type for Node.js environment. Expected string[] file paths.");else r=await He(n,e);return r}var Je=C(()=>{"use strict";F();Te();Ke();$()});var Q={};N(Q,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>ve,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>I,createAccountResource:()=>Y,createDeploymentResource:()=>G,createDomainResource:()=>J,createTokenResource:()=>W,default:()=>xe,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>_,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>z,setConfig:()=>L,setPlatformConfig:()=>L,validateFiles:()=>De});var h={};N(h,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>oe,Ship:()=>Z,ShipError:()=>Fe,ShipErrorType:()=>ve,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>I,createAccountResource:()=>Y,createDeploymentResource:()=>G,createDomainResource:()=>J,createTokenResource:()=>W,default:()=>xe,filterJunk:()=>O,formatFileSize:()=>K,getCurrentConfig:()=>A,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>_,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,processFilesForNode:()=>X,resolveConfig:()=>z,setConfig:()=>L,setPlatformConfig:()=>L,validateFiles:()=>De});import Ie from"mime-db";var ce={};for(let n in Ie){let e=Ie[n];e&&e.extensions&&e.extensions.forEach(t=>{ce[t]||(ce[t]=n)})}function ee(n){let e=n.includes(".")?n.substring(n.lastIndexOf(".")+1).toLowerCase():"";return ce[e]||"application/octet-stream"}import{ShipError as v,DEFAULT_API as et}from"@shipstatic/types";var te=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 i=this.handlers.get(e);i&&(i.delete(t),i.size===0&&this.handlers.delete(e))}emit(e,...t){let i=this.handlers.get(e);if(!i)return;let r=Array.from(i);for(let o of r)try{o(...t)}catch(s){i.delete(o),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,i)=>{t.forEach(r=>{e.on(i,r)})})}clear(){this.handlers.clear()}};F();var ne="/deployments",$e="/ping",T="/domains",tt="/config",nt="/account",me="/tokens",it="/spa-check",R=class extends te{constructor(e){super(),this.apiUrl=e.apiUrl||et,this.apiKey=e.apiKey??"",this.deployToken=e.deployToken??""}transferEventsTo(e){this.transfer(e)}async request(e,t={},i){let r=this.getAuthHeaders(t.headers),o={...t,headers:r,credentials:this.needsCredentials(r)?"include":void 0};this.emit("request",e,o);try{let s=await fetch(e,o);s.ok||await this.handleResponseError(s,i);let a=this.safeClone(s),f=this.safeClone(s);return this.emit("response",a,e),await this.parseResponse(f)}catch(s){throw this.emit("error",s,e),this.handleFetchError(s,i),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 i={};try{e.headers.get("content-type")?.includes("application/json")?i=await e.json():i={message:await e.text()}}catch{i={message:"Failed to parse error response"}}let r=i.message||i.error||`${t} failed due to API error`;throw e.status===401?v.authentication(r):v.api(r,e.status,i.code,i)}handleFetchError(e,t){throw e.name==="AbortError"?v.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?v.network(`${t} failed due to network error: ${e.message}`,e):e instanceof v?e:v.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async ping(){return(await this.request(`${this.apiUrl}${$e}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.request(`${this.apiUrl}${$e}`,{method:"GET"},"Ping")}async getConfig(){return await this.request(`${this.apiUrl}${tt}`,{method:"GET"},"Config")}async deploy(e,t={}){this.validateFiles(e);let{requestBody:i,requestHeaders:r}=await this.prepareRequestPayload(e,t.tags),o={};t.deployToken?o={Authorization:`Bearer ${t.deployToken}`}:t.apiKey&&(o={Authorization:`Bearer ${t.apiKey}`});let s={method:"POST",body:i,headers:{...r,...o},signal:t.signal||null};return await this.request(`${t.apiUrl||this.apiUrl}${ne}`,s,"Deploy")}async listDeployments(){return await this.request(`${this.apiUrl}${ne}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.request(`${this.apiUrl}${ne}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.request(`${this.apiUrl}${ne}/${e}`,{method:"DELETE"},"Remove Deployment")}async setDomain(e,t,i){let r={deployment:t};i&&i.length>0&&(r.tags=i);let o={method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},s=this.getAuthHeaders(o.headers),a={...o,headers:s,credentials:this.needsCredentials(s)?"include":void 0};this.emit("request",`${this.apiUrl}${T}/${encodeURIComponent(e)}`,a);try{let f=await fetch(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,a);f.ok||await this.handleResponseError(f,"Set Domain");let S=this.safeClone(f),E=this.safeClone(f);return this.emit("response",S,`${this.apiUrl}${T}/${encodeURIComponent(e)}`),{...await this.parseResponse(E),isCreate:f.status===201}}catch(f){throw this.emit("error",f,`${this.apiUrl}${T}/${encodeURIComponent(e)}`),this.handleFetchError(f,"Set Domain"),f}}async getDomain(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"GET"},"Get Domain")}async listDomains(){return await this.request(`${this.apiUrl}${T}`,{method:"GET"},"List Domains")}async removeDomain(e){await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Domain")}async confirmDomain(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}/confirm`,{method:"POST"},"Confirm Domain")}async getDomainDns(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}/dns`,{method:"GET"},"Get Domain DNS")}async getDomainRecords(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}/records`,{method:"GET"},"Get Domain Records")}async getDomainShare(e){return await this.request(`${this.apiUrl}${T}/${encodeURIComponent(e)}/share`,{method:"GET"},"Get Domain Share")}async getAccount(){return await this.request(`${this.apiUrl}${nt}`,{method:"GET"},"Get Account")}async createToken(e,t){let i={};return e!==void 0&&(i.ttl=e),t&&t.length>0&&(i.tags=t),await this.request(`${this.apiUrl}${me}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)},"Create Token")}async listTokens(){return await this.request(`${this.apiUrl}${me}`,{method:"GET"},"List Tokens")}async removeToken(e){await this.request(`${this.apiUrl}${me}/${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 i;if(typeof Buffer<"u"&&Buffer.isBuffer(t.content))i=t.content.toString("utf-8");else if(typeof Blob<"u"&&t.content instanceof Blob)i=await t.content.text();else if(typeof File<"u"&&t.content instanceof File)i=await t.content.text();else return!1;let r={files:e.map(s=>s.path),index:i};return(await this.request(`${this.apiUrl}${it}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)},"SPA Check")).isSPA}validateFiles(e){if(!e.length)throw v.business("No files to deploy.");for(let t of e)if(!t.md5)throw v.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async prepareRequestPayload(e,t){if(y()==="browser")return{requestBody:this.createBrowserBody(e,t),requestHeaders:{}};if(y()==="node"){let{body:i,headers:r}=await this.createNodeBody(e,t);return{requestBody:i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength),requestHeaders:r}}else throw v.business("Unknown or unsupported execution environment")}createBrowserBody(e,t){let i=new FormData,r=[];for(let o of e){if(!(o.content instanceof File||o.content instanceof Blob))throw v.file(`Unsupported file.content type for browser FormData: ${o.path}`,o.path);let s=this.getBrowserContentType(o.content instanceof File?o.content:o.path),a=new File([o.content],o.path,{type:s});i.append("files[]",a),r.push(o.md5)}return i.append("checksums",JSON.stringify(r)),t&&t.length>0&&i.append("tags",JSON.stringify(t)),i}async createNodeBody(e,t){let{FormData:i,File:r}=await import("formdata-node"),{FormDataEncoder:o}=await import("form-data-encoder"),s=new i,a=[];for(let p of e){let m=ee(p.path),d;if(Buffer.isBuffer(p.content))d=new r([p.content],p.path,{type:m});else if(typeof Blob<"u"&&p.content instanceof Blob)d=new r([p.content],p.path,{type:m});else throw v.file(`Unsupported file.content type for Node.js FormData: ${p.path}`,p.path);let P=p.path.startsWith("/")?p.path:"/"+p.path;s.append("files[]",d,P),a.push(p.md5)}s.append("checksums",JSON.stringify(a)),t&&t.length>0&&s.append("tags",JSON.stringify(t));let f=new o(s),S=[];for await(let p of f.encode())S.push(Buffer.from(p));let E=Buffer.concat(S);return{body:E,headers:{"Content-Type":f.contentType,"Content-Length":Buffer.byteLength(E).toString()}}}getBrowserContentType(e){return typeof e=="string"?ee(e):e.type||ee(e.name)}};$();F();import{DEFAULT_API as at}from"@shipstatic/types";async function pt(n){let e=y();if(e==="browser")return{};if(e==="node"){let{loadConfig:t}=await Promise.resolve().then(()=>(ie(),ke));return t(n)}else return{}}function z(n={},e={}){let t={apiUrl:n.apiUrl||e.apiUrl||at,apiKey:n.apiKey!==void 0?n.apiKey:e.apiKey,deployToken:n.deployToken!==void 0?n.deployToken:e.deployToken},i={apiUrl:t.apiUrl};return t.apiKey!==void 0&&(i.apiKey=t.apiKey),t.deployToken!==void 0&&(i.deployToken=t.deployToken),i}function j(n,e){let t={...n};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}H();import{DEPLOYMENT_CONFIG_FILENAME as Me}from"@shipstatic/types";async function ft(){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:i}=await I(t);return{path:Me,content:t,size:e.length,md5:i}}async function Ne(n,e,t){if(t.spaDetect===!1||n.some(i=>i.path===Me))return n;try{if(await e.checkSPA(n)){let r=await ft();return[...n,r]}}catch{}return n}function G(n,e,t,i){return{create:async(r,o={})=>{t&&await t();let s=e?j(o,e):o,a=n();if(!i)throw new Error("processInput function is not provided.");let f=await i(r,s);return f=await Ne(f,a,s),await a.deploy(f,s)},list:async()=>(t&&await t(),n().listDeployments()),remove:async r=>{t&&await t(),await n().removeDeployment(r)},get:async r=>(t&&await t(),n().getDeployment(r))}}function J(n,e){return{set:async(t,i,r)=>(e&&await e(),n().setDomain(t,i,r)),get:async t=>(e&&await e(),n().getDomain(t)),list:async()=>(e&&await e(),n().listDomains()),remove:async t=>{e&&await e(),await n().removeDomain(t)},confirm:async t=>(e&&await e(),n().confirmDomain(t)),dns:async t=>(e&&await e(),n().getDomainDns(t)),records:async t=>(e&&await e(),n().getDomainRecords(t)),share:async t=>(e&&await e(),n().getDomainShare(t))}}function Y(n,e){return{get:async()=>(e&&await e(),n().getAccount())}}function W(n,e){return{create:async(t,i)=>(e&&await e(),n().createToken(t,i)),list:async()=>(e&&await e(),n().listTokens()),remove:async t=>{e&&await e(),await n().removeToken(t)}}}var B=class{constructor(e={}){this.initPromise=null;this._config=null;this.clientOptions=e;let t=this.resolveInitialConfig(e);this.http=new R({...e,...t});let i=()=>this.ensureInitialized(),r=()=>this.http;this._deployments=G(r,this.clientOptions,i,(o,s)=>this.processInput(o,s)),this._domains=J(r,i),this._account=Y(r,i),this._tokens=W(r,i)}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}async getConfig(){return this._config?this._config:(await this.ensureInitialized(),this._config=A(),this._config)}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}};F();ie();import{ShipError as Ce}from"@shipstatic/types";$();var c={};N(c,{ApiHttp:()=>R,DEFAULT_API:()=>ye,FILE_VALIDATION_STATUS:()=>u,JUNK_DIRECTORIES:()=>oe,Ship:()=>B,ShipError:()=>Fe,ShipErrorType:()=>ve,__setTestEnvironment:()=>q,allValidFilesReady:()=>we,calculateMD5:()=>I,createAccountResource:()=>Y,createDeploymentResource:()=>G,createDomainResource:()=>J,createTokenResource:()=>W,filterJunk:()=>O,formatFileSize:()=>K,getENV:()=>y,getValidFiles:()=>pe,loadConfig:()=>pt,mergeDeployOptions:()=>j,optimizeDeployPaths:()=>k,pluralize:()=>ge,resolveConfig:()=>z,validateFiles:()=>De});var g={};l(g,Jt);import*as Jt from"@shipstatic/types";l(c,g);import{DEFAULT_API as ye}from"@shipstatic/types";H();function ge(n,e,t,i=!0){let r=n===1?e:t;return i?`${n} ${r}`:r}re();ae();F();import _e from"mime-db";var ut=new Set(Object.keys(_e)),ht=new Map(Object.entries(_e).filter(([n,e])=>e.extensions).map(([n,e])=>[n,new Set(e.extensions)])),u={PENDING:"pending",PROCESSING_ERROR:"processing_error",EMPTY_FILE:"empty_file",VALIDATION_FAILED:"validation_failed",READY:"ready"};function K(n,e=1){if(n===0)return"0 Bytes";let t=1024,i=["Bytes","KB","MB","GB"],r=Math.floor(Math.log(n)/Math.log(t));return parseFloat((n/Math.pow(t,r)).toFixed(e))+" "+i[r]}function yt(n,e){if(n.startsWith("."))return!0;let t=n.toLowerCase().split(".");if(t.length>1&&t[t.length-1]){let i=t[t.length-1],r=ht.get(e);if(r&&!r.has(i))return!1}return!0}function De(n,e){let t=[],i=[];if(n.length===0){let o="At least one file must be provided";return{files:[],validFiles:[],error:{error:"No Files Provided",details:o,errors:[o],isClientError:!0}}}if(n.length>e.maxFilesCount){let o=`Number of files (${n.length}) exceeds the limit of ${e.maxFilesCount}.`;return{files:n.map(s=>({...s,status:u.VALIDATION_FAILED,statusMessage:o})),validFiles:[],error:{error:"File Count Exceeded",details:o,errors:[o],isClientError:!0}}}let r=0;for(let o of n){let s=u.READY,a="Ready for upload";o.status===u.PROCESSING_ERROR?(s=u.PROCESSING_ERROR,a=o.statusMessage||"A file failed during processing.",t.push(`${o.name}: ${a}`)):!o.name||o.name.trim().length===0?(s=u.VALIDATION_FAILED,a="File name cannot be empty",t.push(`${o.name||"(empty)"}: ${a}`)):o.name.includes("..")?(s=u.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",t.push(`${o.name}: ${a}`)):o.name.includes("\0")?(s=u.VALIDATION_FAILED,a="Invalid file name. File name contains invalid characters",t.push(`${o.name}: ${a}`)):o.size<=0?(s=u.EMPTY_FILE,a=o.size===0?"File is empty (0 bytes)":"File size must be positive",t.push(`${o.name}: ${a}`)):!o.type||o.type.trim().length===0?(s=u.VALIDATION_FAILED,a="File MIME type is required",t.push(`${o.name}: ${a}`)):e.allowedMimeTypes.some(f=>o.type.startsWith(f))?ut.has(o.type)?yt(o.name,o.type)?o.size>e.maxFileSize?(s=u.VALIDATION_FAILED,a=`File size (${K(o.size)}) exceeds limit of ${K(e.maxFileSize)}`,t.push(`${o.name}: ${a}`)):(r+=o.size,r>e.maxTotalSize&&(s=u.VALIDATION_FAILED,a=`Total size would exceed limit of ${K(e.maxTotalSize)}`,t.push(`${o.name}: ${a}`))):(s=u.VALIDATION_FAILED,a="File extension does not match MIME type",t.push(`${o.name}: ${a}`)):(s=u.VALIDATION_FAILED,a=`Invalid MIME type "${o.type}"`,t.push(`${o.name}: ${a}`)):(s=u.VALIDATION_FAILED,a=`File type "${o.type}" is not allowed`,t.push(`${o.name}: ${a}`)),i.push({...o,status:s,statusMessage:a})}if(t.length>0){let o=i.find(a=>a.status!==u.READY&&a.status!==u.PENDING),s="Validation Failed";return o?.status===u.PROCESSING_ERROR?s="Processing Error":o?.status===u.EMPTY_FILE?s="Empty File":o?.statusMessage?.includes("File name cannot be empty")||o?.statusMessage?.includes("Invalid file name")?s="Invalid File Name":o?.statusMessage?.includes("File size must be positive")?s="Invalid File Size":o?.statusMessage?.includes("MIME type is required")?s="Missing MIME Type":o?.statusMessage?.includes("Invalid MIME type")?s="Invalid MIME Type":o?.statusMessage?.includes("not allowed")?s="Invalid File Type":o?.statusMessage?.includes("extension does not match")?s="Extension Mismatch":o?.statusMessage?.includes("Total size")?s="Total Size Exceeded":o?.statusMessage?.includes("exceeds limit")&&(s="File Too Large"),{files:i.map(a=>({...a,status:u.VALIDATION_FAILED})),validFiles:[],error:{error:s,details:t.length===1?t[0]:`${t.length} file(s) failed validation`,errors:t,isClientError:!0}}}return{files:i,validFiles:i,error:null}}function pe(n){return n.filter(e=>e.status===u.READY)}function we(n){return pe(n).length>0}import{ShipError as Fe,ShipErrorType as ve}from"@shipstatic/types";l(h,c);ie();$();$();Te();F();var Z=class extends B{constructor(e={}){if(y()!=="node")throw Ce.business("Node.js Ship class can only be used in Node.js environment.");super(e)}resolveInitialConfig(e){return z(e,{})}async loadFullConfig(){try{let e=await _(this.clientOptions.configFile),t=z(this.clientOptions,e),i=new R({...this.clientOptions,...t});this.replaceHttpClient(i);let r=await this.http.getConfig();L(r)}catch(e){throw this.initPromise=null,e}}async processInput(e,t){if(!this.#e(e))throw Ce.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(Array.isArray(e)&&e.length===0)throw Ce.business("No files to deploy.");let{convertDeployInput:i}=await Promise.resolve().then(()=>(Je(),Ge));return i(e,t,this.http)}#e(e){return typeof e=="string"?!0:Array.isArray(e)?e.every(t=>typeof t=="string"):!1}},xe=Z;l(Q,h);export{R as ApiHttp,ye as DEFAULT_API,u as FILE_VALIDATION_STATUS,oe as JUNK_DIRECTORIES,Z as Ship,Fe as ShipError,ve as ShipErrorType,q as __setTestEnvironment,we as allValidFilesReady,I as calculateMD5,Y as createAccountResource,G as createDeploymentResource,J as createDomainResource,W as createTokenResource,xe as default,O as filterJunk,K as formatFileSize,A as getCurrentConfig,y as getENV,pe as getValidFiles,_ as loadConfig,j as mergeDeployOptions,k as optimizeDeployPaths,ge as pluralize,X as processFilesForNode,z as resolveConfig,L as setConfig,L as setPlatformConfig,De as validateFiles};
2
2
  //# sourceMappingURL=index.js.map