@shipstatic/ship 0.1.6 → 0.1.8
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 +4 -4
- package/dist/browser.js +17 -25
- package/dist/browser.js.map +1 -1
- package/dist/cli.cjs +25 -18
- package/dist/cli.cjs.map +1 -1
- package/dist/completions/ship.bash +30 -0
- package/dist/completions/ship.fish +24 -0
- package/dist/completions/ship.zsh +46 -0
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +26 -21
- package/dist/index.d.ts +26 -21
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +13 -10
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
|
|
3
|
+
_ship_completions() {
|
|
4
|
+
# COMP_CWORD is the index of the current word
|
|
5
|
+
# COMP_WORDS is an array of words in the current command
|
|
6
|
+
local current_word="${COMP_WORDS[COMP_CWORD]}"
|
|
7
|
+
local prev_word="${COMP_WORDS[COMP_CWORD-1]}"
|
|
8
|
+
local completions
|
|
9
|
+
|
|
10
|
+
# Delegate to native file completion if the word looks like a path
|
|
11
|
+
if [[ "$current_word" == ~* || "$current_word" == /* || "$current_word" == .* ]]; then
|
|
12
|
+
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
13
|
+
return
|
|
14
|
+
fi
|
|
15
|
+
|
|
16
|
+
# Delegate for commands that expect files, like 'create'
|
|
17
|
+
if [[ "$prev_word" == "create" || "$prev_word" == "--config" || "$prev_word" == "-c" ]]; then
|
|
18
|
+
COMPREPLY=( $(compgen -f -- "${current_word}") )
|
|
19
|
+
return
|
|
20
|
+
fi
|
|
21
|
+
|
|
22
|
+
# Get static completions from CLI
|
|
23
|
+
completions=$(ship --compbash 2>/dev/null)
|
|
24
|
+
|
|
25
|
+
# Filter completions based on the current word and reply
|
|
26
|
+
COMPREPLY=( $(compgen -W "${completions}" -- "${current_word}") )
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
# Register the completion function for the 'ship' command
|
|
30
|
+
complete -F _ship_completions ship
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# ship.fish
|
|
2
|
+
|
|
3
|
+
# Don't complete if it looks like a path
|
|
4
|
+
function __ship_is_path
|
|
5
|
+
set -l cmd (commandline -opc)
|
|
6
|
+
if test (count $cmd) -gt 1
|
|
7
|
+
# The last token will be what we are completing
|
|
8
|
+
set -l last_token $cmd[-1]
|
|
9
|
+
if string match -q -- "*/*" "$last_token"
|
|
10
|
+
return 0
|
|
11
|
+
end
|
|
12
|
+
if string match -q -- "~*" "$last_token"
|
|
13
|
+
return 0
|
|
14
|
+
end
|
|
15
|
+
if string match -q -- ".*" "$last_token"
|
|
16
|
+
return 0
|
|
17
|
+
end
|
|
18
|
+
end
|
|
19
|
+
return 1
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# Command completion by calling the CLI
|
|
23
|
+
complete -c ship -n '__fish_use_subcommand' -a '(ship --compfish --compgen (commandline -b) 2>/dev/null)'
|
|
24
|
+
complete -c ship -n 'not __ship_is_path' -a '(ship --compfish --compgen (commandline -b) 2>/dev/null)'
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
#compdef ship
|
|
2
|
+
|
|
3
|
+
# Only define the completion function if we're in a completion context
|
|
4
|
+
if [[ -n ${ZSH_VERSION-} ]]; then
|
|
5
|
+
_ship() {
|
|
6
|
+
local -a completions
|
|
7
|
+
local state line
|
|
8
|
+
|
|
9
|
+
# Only proceed if we're actually in a completion context
|
|
10
|
+
if [[ -z ${words-} ]]; then
|
|
11
|
+
return 1
|
|
12
|
+
fi
|
|
13
|
+
|
|
14
|
+
# The word being completed
|
|
15
|
+
local current_word="${words[CURRENT]}"
|
|
16
|
+
# The previous word
|
|
17
|
+
local prev_word="${words[CURRENT-1]}"
|
|
18
|
+
|
|
19
|
+
# --- File Path Logic ---
|
|
20
|
+
# If the user is typing a path, use native file completion immediately.
|
|
21
|
+
if [[ "$current_word" == \~* || "$current_word" == \/* || "$current_word" == \./* || "$current_word" == \.\./* ]]; then
|
|
22
|
+
_files
|
|
23
|
+
return
|
|
24
|
+
fi
|
|
25
|
+
|
|
26
|
+
# If the previous command expects a file path, also use file completion.
|
|
27
|
+
if [[ "$prev_word" == "create" || "$prev_word" == "--config" || "$prev_word" == "-c" ]]; then
|
|
28
|
+
_files
|
|
29
|
+
return
|
|
30
|
+
fi
|
|
31
|
+
|
|
32
|
+
# --- Command Completion Logic ---
|
|
33
|
+
# If we're not completing a path, call our Node.js script for command suggestions.
|
|
34
|
+
# We pass the full command line and cursor position to our script for context.
|
|
35
|
+
completions=($(ship --compzsh --compgen="${BUFFER}" --compword="${CURRENT}" 2>/dev/null))
|
|
36
|
+
|
|
37
|
+
if [[ ${#completions[@]} -gt 0 ]]; then
|
|
38
|
+
_describe 'commands' completions
|
|
39
|
+
fi
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
# Only register the completion if compdef is available
|
|
43
|
+
if (( ${+functions[compdef]} )); then
|
|
44
|
+
compdef _ship ship
|
|
45
|
+
fi
|
|
46
|
+
fi
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var fe=Object.create;var R=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var he=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var ge=(i,e)=>{for(var t in e)R(i,t,{get:e[t],enumerable:!0})},E=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of ye(e))!de.call(i,n)&&n!==t&&R(i,n,{get:()=>e[n],enumerable:!(o=ue(e,n))||o.enumerable});return i},G=(i,e,t)=>(E(i,e,"default"),t&&E(t,e,"default")),F=(i,e,t)=>(t=i!=null?fe(he(i)):{},E(e||!i||!i.__esModule?R(t,"default",{value:i,enumerable:!0}):t,i)),we=i=>E(R({},"__esModule",{value:!0}),i);var $e={};ge($e,{Ship:()=>N,ShipError:()=>M.ShipError,ShipErrorType:()=>M.ShipErrorType,__setTestEnvironment:()=>J,default:()=>Te,processFilesForBrowser:()=>k,processFilesForNode:()=>B});module.exports=we($e);var _=null;function J(i){_=i}function Fe(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function u(){return _||Fe()}var S=require("zod");var D={};G(D,require("@shipstatic/types"));var I="https://api.shipstatic.com";var V="ship",Pe=S.z.object({apiUrl:S.z.string().url().optional(),apiKey:S.z.string().optional()}).strict();function W(i){try{return Pe.parse(i)}catch(e){if(e instanceof S.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw D.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw D.ShipError.config("Configuration validation failed")}}async function De(){try{if(u()!=="node")return{};let{cosmiconfigSync:i}=await import("cosmiconfig"),t=i(V,{searchPlaces:[`.${V}rc`,"package.json"]}).search();if(t&&!t.isEmpty&&t.config)return W(t.config)}catch(i){if(i instanceof D.ShipError)throw i}return{}}async function Y(){if(u()!=="node")return{};let i={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},e=await De(),t={apiUrl:i.apiUrl??e.apiUrl,apiKey:i.apiKey??e.apiKey};return W(t)}function K(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||I,apiKey:i.apiKey!==void 0?i.apiKey:e.apiKey};return t.apiKey!==void 0?{apiUrl:t.apiUrl,apiKey:t.apiKey}:{apiUrl:t.apiUrl}}function X(i={},e){let t={...i};return 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.maxConcurrency===void 0&&e.maxConcurrentDeploys!==void 0&&(t.maxConcurrency=e.maxConcurrentDeploys),t.timeout===void 0&&e.timeout!==void 0&&(t.timeout=e.timeout),t.apiKey===void 0&&e.apiKey!==void 0&&(t.apiKey=e.apiKey),t.apiUrl===void 0&&e.apiUrl!==void 0&&(t.apiUrl=e.apiUrl),t}var $=F(require("mime-types"),1),y=require("@shipstatic/types");var O="/deployments",be="/ping",T="/aliases",ve="/config",Se="/account";function xe(i){return typeof i=="string"?$.lookup(i)||"application/octet-stream":$.lookup(i.name)||i.type||"application/octet-stream"}async function Ae(i){let e=[];for await(let t of i)e.push(t);return e}var x=class{constructor(e){this.apiUrl=e.apiUrl||I,this.apiKey=e.apiKey??""}#n(e={}){let t={...e};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},o){let n=this.#n(t.headers),r={...t,headers:n,credentials:u()==="browser"?"include":"same-origin"};try{return await fetch(e,r)}catch(a){throw this.#t(a,o),a}}async#e(e,t={},o){try{let n=await this.#i(e,t,o);return n.ok||await this.#o(n,o),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof y.ShipError||this.#t(n,o),n}}async ping(){return(await this.#e(`${this.apiUrl}${be}`,{method:"GET"},"Ping"))?.success||!1}async getConfig(){return await this.#e(`${this.apiUrl}${ve}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#r(e);let{apiUrl:o=this.apiUrl,signal:n}=t;try{let{requestBody:r,requestHeaders:a}=await this.#s(e),c={method:"POST",body:r,headers:a,signal:n||null},m=await this.#i(`${o}${O}`,c,"Deploy");return m.ok||await this.#o(m,"Deploy"),await m.json()}catch(r){throw r instanceof y.ShipError?r:(this.#t(r,"Deploy"),y.ShipError.business("An unexpected error occurred and was not handled."))}}#r(e){if(!e.length)throw y.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw y.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#s(e){let t,o={};if(u()==="browser")t=this.#a(e);else if(u()==="node"){let{body:n,headers:r}=await this.#l(e);t=n,o=r}else throw y.ShipError.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:o}}#a(e){let t=new FormData,o=[];for(let n=0;n<e.length;n++){let r=e[n],a;if(r.content instanceof File||r.content instanceof Blob)a=r.content;else throw y.ShipError.file(`Unsupported file.content type for browser FormData: ${r.path}`,r.path);let c=xe(a instanceof File?a:r.path),m=new File([a],r.path,{type:c});t.append("files[]",m),o.push(r.md5)}return t.append("checksums",JSON.stringify(o)),t}async#l(e){let{FormData:t,File:o}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),r=await import("path"),a=new t,c=[];for(let g=0;g<e.length;g++){let f=e[g],C=$.lookup(f.path)||"application/octet-stream",w;if(Buffer.isBuffer(f.content))w=new o([f.content],r.basename(f.path),{type:C});else if(typeof Blob<"u"&&f.content instanceof Blob)w=new o([f.content],r.basename(f.path),{type:C});else throw y.ShipError.file(`Unsupported file.content type for Node.js FormData: ${f.path}`,f.path);let me=f.path.startsWith("/")?f.path:"/"+f.path;a.append("files[]",w,me),c.push(f.md5)}a.append("checksums",JSON.stringify(c));let m=new n(a),l=await Ae(m.encode()),s=Buffer.concat(l.map(g=>Buffer.from(g))),p={"Content-Type":m.contentType,"Content-Length":Buffer.byteLength(s).toString()};return{body:s,headers:p}}async#o(e,t){let o={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}if(o.error||o.code||o.message){let n=o.message||o.error||`${t} failed due to API error`;throw y.ShipError.api(n,e.status,o.code,o)}throw y.ShipError.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?y.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?y.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof y.ShipError?e:y.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${O}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${O}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${O}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){return await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deploymentId:t})},"Set Alias")}async getAlias(e){return await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${T}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Se}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}};var ce=require("@shipstatic/types");var Z=require("@shipstatic/types"),j=null;function Q(i){j=i}function A(){if(j===null)throw Z.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return j}var d=require("@shipstatic/types");var b=require("@shipstatic/types");async function Ce(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let r=Math.ceil(i.size/2097152),a=0,c=new e.ArrayBuffer,m=new FileReader,l=()=>{let s=a*2097152,p=Math.min(s+2097152,i.size);m.readAsArrayBuffer(i.slice(s,p))};m.onload=s=>{let p=s.target?.result;if(!p){o(b.ShipError.business("Failed to read file chunk"));return}c.append(p),a++,a<r?l():t({md5:c.end()})},m.onerror=()=>{o(b.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Ee(i){let e=await import("crypto");if(Buffer.isBuffer(i)){let o=e.createHash("md5");return o.update(i),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,n)=>{let r=e.createHash("md5"),a=t.createReadStream(i);a.on("error",c=>n(b.ShipError.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>r.update(c)),a.on("end",()=>o({md5:r.digest("hex")}))})}async function U(i){let e=u();if(e==="browser"){if(!(i instanceof Blob))throw b.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Ce(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw b.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ee(i)}throw b.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var ee=require("junk"),Re=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function L(i){return!i||i.length===0?[]:i.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if((0,ee.isJunk)(o))return!1;let n=t.slice(0,-1);for(let r of n)if(Re.some(a=>r.toLowerCase()===a.toLowerCase()))return!1;return!0})}var v=require("@shipstatic/types");function z(i){if(!i||i.length===0)return"";let e=i.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)),o=[],n=Math.min(...t.map(r=>r.length));for(let r=0;r<n;r++){let a=t[0][r];if(t.every(c=>c[r]===a))o.push(a);else break}return o.join("/")}function H(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}var P=F(require("fs"),1),h=F(require("path"),1);function ie(i){let e=[];try{let t=P.readdirSync(i);for(let o of t){let n=h.join(i,o),r=P.statSync(n);if(r.isDirectory()){let a=ie(n);e.push(...a)}else r.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function te(i,e={}){let t=h.resolve(i),n=(()=>{let s=P.statSync(t);return s.isFile()?[t]:s.isDirectory()?ie(t):[]})().filter(s=>{let p=h.basename(s);return L([p]).length>0}),r=P.statSync(t),a;if(e.preserveDirs)a=r.isDirectory()?t:h.dirname(t);else{let s=n.map(p=>h.dirname(p));a=z(s)}let c=[],m=0;for(let s of n)try{let p=P.statSync(s);if(p.size===0){console.warn(`Skipping empty file: ${s}`);continue}let g=A();if(p.size>g.maxFileSize)throw v.ShipError.business(`File ${s} is too large. Maximum allowed size is ${g.maxFileSize/(1024*1024)}MB.`);if(m+=p.size,m>g.maxTotalSize)throw v.ShipError.business(`Total deploy size is too large. Maximum allowed is ${g.maxTotalSize/(1024*1024)}MB.`);let f=P.readFileSync(s),{md5:C}=await U(f),w=h.relative(a,s).replace(/\\/g,"/");(w.includes("..")||w.includes("\0"))&&(w=h.basename(s)),w||(w=h.basename(s)),c.push({path:w,content:f,size:f.length,md5:C})}catch(p){if(p instanceof v.ShipError&&p.isClientError&&p.isClientError())throw p;console.error(`Could not process file ${s}:`,p)}let l=A();if(c.length>l.maxFilesCount)throw v.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}async function B(i,e={}){if(u()!=="node")throw v.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(i.length>1){let t=[];for(let o of i){let n=await te(o,e);t.push(...n)}return t}return await te(i[0],e)}var q=require("@shipstatic/types");async function k(i,e={}){if(u()!=="browser")throw q.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o="";if(!e.preserveDirs){let l=t.map(s=>s.webkitRelativePath||s.name).filter(s=>s).map(s=>s.includes("/")?s.substring(0,s.lastIndexOf("/")):"");o=z(l)}let n=[];for(let l of t){let s=l.webkitRelativePath||l.name;if(o&&!e.preserveDirs){s=H(s);let p=o.endsWith("/")?o:`${o}/`;s.startsWith(p)?s=s.substring(p.length):s===o&&(s="")}if(s=H(s),s.includes("..")||s.includes("\0"))throw q.ShipError.business(`Security error: Unsafe file path "${s}" for file: ${l.name}`);s||(s=l.name),n.push({file:l,relativePath:s})}let r=n.map(l=>l.relativePath),a=L(r),c=new Set(a),m=[];for(let l of n){if(!c.has(l.relativePath)||l.file.size===0)continue;let{md5:s}=await U(l.file);m.push({content:l.file,path:l.relativePath,size:l.file.size,md5:s})}return m}function oe(i,e={}){let t=A();if(!e.skipEmptyCheck&&i.length===0)throw d.ShipError.business("No files to deploy.");if(i.length>t.maxFilesCount)throw d.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let n of i){if(n.size>t.maxFileSize)throw d.ShipError.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);o+=n.size}if(o>t.maxTotalSize)throw d.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}function ne(i){return oe(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function Ie(i,e={}){if(!Array.isArray(i)||!i.every(o=>typeof o=="string"))throw d.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw d.ShipError.business("No files to deploy.");let t=await B(i,e);return ne(t)}async function Oe(i,e={}){let t;if(i instanceof HTMLInputElement){if(!i.files)throw d.ShipError.business("No files selected in HTMLInputElement");t=Array.from(i.files)}else if(typeof i=="object"&&i!==null&&typeof i.length=="number"&&typeof i.item=="function")t=Array.from(i);else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string")throw d.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw d.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),oe(t);let o=await k(t,e);return ne(o)}async function re(i,e={}){let t=u();if(t==="node"){if(!Array.isArray(i)||!i.every(o=>typeof o=="string"))throw d.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");return Ie(i,e)}else if(t==="browser"){if(!(i instanceof HTMLInputElement||Array.isArray(i)||typeof FileList<"u"&&i instanceof FileList))throw d.ShipError.business("In browser, input must be FileList, File[], or HTMLInputElement.");return Oe(i,e)}else throw d.ShipError.business("Unsupported execution environment.")}function se(i,e,t){return{create:async(o,n={})=>{e&&await e();let r=t?X(n,t):n,a=await re(o,r);return await i.deploy(a,r)},list:async()=>i.listDeployments(),remove:async o=>{await i.removeDeployment(o)},get:async o=>i.getDeployment(o)}}function ae(i){return{set:async(e,t)=>i.setAlias(e,t),get:async e=>i.getAlias(e),list:async()=>i.listAliases(),remove:async e=>{await i.removeAlias(e)}}}function le(i){return{get:async()=>i.getAccount()}}function pe(i){return{create:async()=>i.createApiKey()}}var M=require("@shipstatic/types"),N=class{constructor(e={}){this.configInitialized=!1;this.configLoaded=!1;if(this.clientOptions=e,this.environment=u(),this.environment!=="node"&&this.environment!=="browser")throw ce.ShipError.business("Unsupported execution environment.");let t=K(e,{});this.http=new x({...e,...t})}async initializeConfig(){if(this.configInitialized)return;if(!this.configLoaded){let t=await Y(),o=K(this.clientOptions,t);this.http=new x({...this.clientOptions,...o}),this.configLoaded=!0}let e=await this.http.getConfig();Q(e),this.configInitialized=!0}async ping(){return await this.initializeConfig(),this.http.ping()}get deployments(){return this._deployments||(this._deployments=se(this.http,()=>this.initializeConfig(),this.clientOptions)),this._deployments}get aliases(){return this._aliases||(this._aliases=ae(this.http)),this._aliases}get account(){return this._account||(this._account=le(this.http)),this._account}get keys(){return this._keys||(this._keys=pe(this.http)),this._keys}async deploy(e,t){return this.deployments.create(e,t)}},Te=N;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
1
|
+
"use strict";var he=Object.create;var E=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var de=Object.getOwnPropertyNames;var ge=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Pe=(i,e)=>{for(var t in e)E(i,t,{get:e[t],enumerable:!0})},R=(i,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of de(e))!we.call(i,n)&&n!==t&&E(i,n,{get:()=>e[n],enumerable:!(o=ye(e,n))||o.enumerable});return i},J=(i,e,t)=>(R(i,e,"default"),t&&R(t,e,"default")),g=(i,e,t)=>(t=i!=null?he(ge(i)):{},R(e||!i||!i.__esModule?E(t,"default",{value:i,enumerable:!0}):t,i)),De=i=>R(E({},"__esModule",{value:!0}),i);var Ue={};Pe(Ue,{Ship:()=>z,ShipError:()=>M.ShipError,ShipErrorType:()=>M.ShipErrorType,__setTestEnvironment:()=>V,default:()=>Ie,processFilesForBrowser:()=>L,processFilesForNode:()=>N});module.exports=De(Ue);var K=null;function V(i){K=i}function ve(){return typeof process<"u"&&process.versions&&process.versions.node?"node":typeof window<"u"||typeof self<"u"?"browser":"unknown"}function f(){return K||ve()}var S=require("zod");var v={};J(v,require("@shipstatic/types"));var O="https://api.shipstatic.com";var _="ship",Fe=S.z.object({apiUrl:S.z.string().url().optional(),apiKey:S.z.string().optional()}).strict();function W(i){try{return Fe.parse(i)}catch(e){if(e instanceof S.z.ZodError){let t=e.issues[0],o=t.path.length>0?` at ${t.path.join(".")}`:"";throw v.ShipError.config(`Configuration validation failed${o}: ${t.message}`)}throw v.ShipError.config("Configuration validation failed")}}async function be(i){try{if(f()!=="node")return{};let{cosmiconfigSync:e}=await import("cosmiconfig"),t=await import("os"),o=e(_,{searchPlaces:[`.${_}rc`,"package.json",`${t.homedir()}/.${_}rc`],stopDir:t.homedir()}),n;if(i?n=o.load(i):n=o.search(),n&&n.config)return W(n.config)}catch(e){if(e instanceof v.ShipError)throw e}return{}}async function Y(i){if(f()!=="node")return{};let e={apiUrl:process.env.SHIP_API_URL,apiKey:process.env.SHIP_API_KEY},t=await be(i),o={apiUrl:e.apiUrl??t.apiUrl,apiKey:e.apiKey??t.apiKey};return W(o)}function j(i={},e={}){let t={apiUrl:i.apiUrl||e.apiUrl||O,apiKey:i.apiKey||e.apiKey};return t.apiKey!==void 0?{apiUrl:t.apiUrl,apiKey:t.apiKey}:{apiUrl:t.apiUrl}}function X(i={},e){return{onProgress:e.onProgress,onProgressStats:e.onProgressStats,maxConcurrency:e.maxConcurrentDeploys,timeout:e.timeout,apiKey:e.apiKey,apiUrl:e.apiUrl,...i}}var I=g(require("mime-types"),1),u=require("@shipstatic/types");var $="/deployments",Z="/ping",T="/aliases",Se="/config",Ae="/account";function Ce(i){return typeof i=="string"?I.lookup(i)||"application/octet-stream":I.lookup(i.name)||i.type||"application/octet-stream"}async function xe(i){let e=[];for await(let t of i)e.push(t);return e}var A=class{constructor(e){this.apiUrl=e.apiUrl||O,this.apiKey=e.apiKey??""}#n(e={}){let t={...e};return this.apiKey&&(t.Authorization=`Bearer ${this.apiKey}`),t}async#i(e,t={},o){let n=this.#n(t.headers),s={...t,headers:n,credentials:f()==="browser"?"include":"same-origin"};try{return await fetch(e,s)}catch(a){throw this.#t(a,o),a}}async#e(e,t={},o){try{let n=await this.#i(e,t,o);return n.ok||await this.#o(n,o),n.headers.get("Content-Length")==="0"||n.status===204?void 0:await n.json()}catch(n){throw n instanceof u.ShipError||this.#t(n,o),n}}async ping(){return(await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping"))?.success||!1}async getPingResponse(){return await this.#e(`${this.apiUrl}${Z}`,{method:"GET"},"Ping")}async getConfig(){return await this.#e(`${this.apiUrl}${Se}`,{method:"GET"},"Config")}async deploy(e,t={}){this.#r(e);let{apiUrl:o=this.apiUrl,signal:n}=t,{requestBody:s,requestHeaders:a}=await this.#s(e),c={method:"POST",body:s,headers:a,signal:n||null};return await this.#e(`${o}${$}`,c,"Deploy")}#r(e){if(!e.length)throw u.ShipError.business("No files to deploy.");for(let t of e)if(!t.md5)throw u.ShipError.file(`MD5 checksum missing for file: ${t.path}`,t.path)}async#s(e){let t,o={};if(f()==="browser")t=this.#a(e);else if(f()==="node"){let{body:n,headers:s}=await this.#l(e);t=n,o=s}else throw u.ShipError.business("Unknown or unsupported execution environment");return{requestBody:t,requestHeaders:o}}#a(e){let t=new FormData,o=[];for(let n=0;n<e.length;n++){let s=e[n],a;if(s.content instanceof File||s.content instanceof Blob)a=s.content;else throw u.ShipError.file(`Unsupported file.content type for browser FormData: ${s.path}`,s.path);let c=Ce(a instanceof File?a:s.path),h=new File([a],s.path,{type:c});t.append("files[]",h),o.push(s.md5)}return t.append("checksums",JSON.stringify(o)),t}async#l(e){let{FormData:t,File:o}=await import("formdata-node"),{FormDataEncoder:n}=await import("form-data-encoder"),s=await import("path"),a=new t,c=[];for(let w=0;w<e.length;w++){let m=e[w],x=I.lookup(m.path)||"application/octet-stream",P;if(Buffer.isBuffer(m.content))P=new o([m.content],s.basename(m.path),{type:x});else if(typeof Blob<"u"&&m.content instanceof Blob)P=new o([m.content],s.basename(m.path),{type:x});else throw u.ShipError.file(`Unsupported file.content type for Node.js FormData: ${m.path}`,m.path);let ue=m.path.startsWith("/")?m.path:"/"+m.path;a.append("files[]",P,ue),c.push(m.md5)}a.append("checksums",JSON.stringify(c));let h=new n(a),l=await xe(h.encode()),r=Buffer.concat(l.map(w=>Buffer.from(w))),p={"Content-Type":h.contentType,"Content-Length":Buffer.byteLength(r).toString()};return{body:r,headers:p}}async#o(e,t){let o={};try{let n=e.headers.get("content-type");n&&n.includes("application/json")?o=await e.json():o={message:await e.text()}}catch{o={message:"Failed to parse error response"}}if(o.error||o.code||o.message){let n=o.message||o.error||`${t} failed due to API error`;throw e.status===401?u.ShipError.authentication(n):u.ShipError.api(n,e.status,o.code,o)}throw e.status===401?u.ShipError.authentication(`Authentication failed for ${t}`):u.ShipError.api(`${t} failed due to API error`,e.status,void 0,o)}#t(e,t){throw e.name==="AbortError"?u.ShipError.cancelled(`${t} operation was cancelled.`):e instanceof TypeError&&e.message.includes("fetch")?u.ShipError.network(`${t} failed due to network error: ${e.message}`,e):e instanceof u.ShipError?e:u.ShipError.business(`An unexpected error occurred during ${t}: ${e.message||"Unknown error"}`)}async listDeployments(){return await this.#e(`${this.apiUrl}${$}`,{method:"GET"},"List Deployments")}async getDeployment(e){return await this.#e(`${this.apiUrl}${$}/${e}`,{method:"GET"},"Get Deployment")}async removeDeployment(e){await this.#e(`${this.apiUrl}${$}/${e}`,{method:"DELETE"},"Remove Deployment")}async setAlias(e,t){try{let o=await this.#i(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({deployment:t})},"Set Alias");return o.ok||await this.#o(o,"Set Alias"),{...await o.json(),isCreate:o.status===201}}catch(o){this.#t(o,"Set Alias")}}async getAlias(e){return await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"GET"},"Get Alias")}async listAliases(){return await this.#e(`${this.apiUrl}${T}`,{method:"GET"},"List Aliases")}async removeAlias(e){await this.#e(`${this.apiUrl}${T}/${encodeURIComponent(e)}`,{method:"DELETE"},"Remove Alias")}async getAccount(){return await this.#e(`${this.apiUrl}${Ae}`,{method:"GET"},"Get Account")}async createApiKey(){return await this.#e(`${this.apiUrl}/key`,{method:"POST"},"Create API Key")}};var fe=require("@shipstatic/types");var Q=require("@shipstatic/types"),H=null;function ee(i){H=i}function C(){if(H===null)throw Q.ShipError.config("Platform configuration not initialized. The SDK must fetch configuration from the API before performing operations.");return H}var d=require("@shipstatic/types");var F=require("@shipstatic/types");async function Re(i){let e=(await import("spark-md5")).default;return new Promise((t,o)=>{let s=Math.ceil(i.size/2097152),a=0,c=new e.ArrayBuffer,h=new FileReader,l=()=>{let r=a*2097152,p=Math.min(r+2097152,i.size);h.readAsArrayBuffer(i.slice(r,p))};h.onload=r=>{let p=r.target?.result;if(!p){o(F.ShipError.business("Failed to read file chunk"));return}c.append(p),a++,a<s?l():t({md5:c.end()})},h.onerror=()=>{o(F.ShipError.business("Failed to calculate MD5: FileReader error"))},l()})}async function Ee(i){let e=await import("crypto");if(Buffer.isBuffer(i)){let o=e.createHash("md5");return o.update(i),{md5:o.digest("hex")}}let t=await import("fs");return new Promise((o,n)=>{let s=e.createHash("md5"),a=t.createReadStream(i);a.on("error",c=>n(F.ShipError.business(`Failed to read file for MD5: ${c.message}`))),a.on("data",c=>s.update(c)),a.on("end",()=>o({md5:s.digest("hex")}))})}async function U(i){let e=f();if(e==="browser"){if(!(i instanceof Blob))throw F.ShipError.business("Invalid input for browser MD5 calculation: Expected Blob or File.");return Re(i)}if(e==="node"){if(!(Buffer.isBuffer(i)||typeof i=="string"))throw F.ShipError.business("Invalid input for Node.js MD5 calculation: Expected Buffer or file path string.");return Ee(i)}throw F.ShipError.business("Unknown or unsupported execution environment for MD5 calculation.")}var te=require("junk"),Oe=["__MACOSX",".Trashes",".fseventsd",".Spotlight-V100"];function k(i){return!i||i.length===0?[]:i.filter(e=>{if(!e)return!1;let t=e.replace(/\\/g,"/").split("/").filter(Boolean);if(t.length===0)return!0;let o=t[t.length-1];if((0,te.isJunk)(o))return!1;let n=t.slice(0,-1);for(let s of n)if(Oe.some(a=>s.toLowerCase()===a.toLowerCase()))return!1;return!0})}var b=require("@shipstatic/types");function B(i){if(!i||i.length===0)return"";let e=i.filter(s=>s&&typeof s=="string").map(s=>s.replace(/\\/g,"/"));if(e.length===0)return"";if(e.length===1)return e[0];let t=e.map(s=>s.split("/").filter(Boolean)),o=[],n=Math.min(...t.map(s=>s.length));for(let s=0;s<n;s++){let a=t[0][s];if(t.every(c=>c[s]===a))o.push(a);else break}return o.join("/")}function G(i){return i.replace(/\\/g,"/").replace(/^\/+/,"")}var D=g(require("fs"),1),y=g(require("path"),1);function oe(i){let e=[];try{let t=D.readdirSync(i);for(let o of t){let n=y.join(i,o),s=D.statSync(n);if(s.isDirectory()){let a=oe(n);e.push(...a)}else s.isFile()&&e.push(n)}}catch(t){console.error(`Error reading directory ${i}:`,t)}return e}async function ie(i,e={}){let t=y.resolve(i),n=(()=>{let r=D.statSync(t);return r.isFile()?[t]:r.isDirectory()?oe(t):[]})().filter(r=>{let p=y.basename(r);return k([p]).length>0}),s=D.statSync(t),a;if(e.preserveDirs)a=s.isDirectory()?t:y.dirname(t);else{let r=n.map(p=>y.dirname(p));a=B(r)}let c=[],h=0;for(let r of n)try{let p=D.statSync(r);if(p.size===0){console.warn(`Skipping empty file: ${r}`);continue}let w=C();if(p.size>w.maxFileSize)throw b.ShipError.business(`File ${r} is too large. Maximum allowed size is ${w.maxFileSize/(1024*1024)}MB.`);if(h+=p.size,h>w.maxTotalSize)throw b.ShipError.business(`Total deploy size is too large. Maximum allowed is ${w.maxTotalSize/(1024*1024)}MB.`);let m=D.readFileSync(r),{md5:x}=await U(m),P=y.relative(a,r).replace(/\\/g,"/");(P.includes("..")||P.includes("\0"))&&(P=y.basename(r)),P||(P=y.basename(r)),c.push({path:P,content:m,size:m.length,md5:x})}catch(p){if(p instanceof b.ShipError&&p.isClientError&&p.isClientError())throw p;console.error(`Could not process file ${r}:`,p)}let l=C();if(c.length>l.maxFilesCount)throw b.ShipError.business(`Too many files to deploy. Maximum allowed is ${l.maxFilesCount} files.`);return c}async function N(i,e={}){if(f()!=="node")throw b.ShipError.business("processFilesForNode can only be called in a Node.js environment.");if(i.length>1){let t=[];for(let o of i){let n=await ie(o,e);t.push(...n)}return t}return await ie(i[0],e)}var q=require("@shipstatic/types");async function L(i,e={}){if(f()!=="browser")throw q.ShipError.business("processFilesForBrowser can only be called in a browser environment.");let t=Array.isArray(i)?i:Array.from(i),o="";if(!e.preserveDirs){let l=t.map(r=>r.webkitRelativePath||r.name).filter(r=>r).map(r=>r.includes("/")?r.substring(0,r.lastIndexOf("/")):"");o=B(l)}let n=[];for(let l of t){let r=l.webkitRelativePath||l.name;if(o&&!e.preserveDirs){r=G(r);let p=o.endsWith("/")?o:`${o}/`;r.startsWith(p)?r=r.substring(p.length):r===o&&(r="")}if(r=G(r),r.includes("..")||r.includes("\0"))throw q.ShipError.business(`Security error: Unsafe file path "${r}" for file: ${l.name}`);r||(r=l.name),n.push({file:l,relativePath:r})}let s=n.map(l=>l.relativePath),a=k(s),c=new Set(a),h=[];for(let l of n){if(!c.has(l.relativePath)||l.file.size===0)continue;let{md5:r}=await U(l.file);h.push({content:l.file,path:l.relativePath,size:l.file.size,md5:r})}return h}function ne(i,e={}){let t=C();if(!e.skipEmptyCheck&&i.length===0)throw d.ShipError.business("No files to deploy.");if(i.length>t.maxFilesCount)throw d.ShipError.business(`Too many files to deploy. Maximum allowed is ${t.maxFilesCount}.`);let o=0;for(let n of i){if(n.size>t.maxFileSize)throw d.ShipError.business(`File ${n.name} is too large. Maximum allowed size is ${t.maxFileSize/(1024*1024)}MB.`);if(o+=n.size,o>t.maxTotalSize)throw d.ShipError.business(`Total deploy size is too large. Maximum allowed is ${t.maxTotalSize/(1024*1024)}MB.`)}}function re(i,e){if(e==="node"){if(!Array.isArray(i))throw d.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.");if(i.length===0)throw d.ShipError.business("No files to deploy.");if(!i.every(t=>typeof t=="string"))throw d.ShipError.business("Invalid input type for Node.js environment. Expected string[] file paths.")}else if(e==="browser"&&i instanceof HTMLInputElement&&!i.files)throw d.ShipError.business("No files selected in HTMLInputElement")}function se(i){return ne(i,{skipEmptyCheck:!0}),i.forEach(e=>{e.path&&(e.path=e.path.replace(/\\/g,"/"))}),i}async function $e(i,e={}){re(i,"node");let t=await N(i,e);return se(t)}async function Te(i,e={}){re(i,"browser");let t;if(i instanceof HTMLInputElement)t=Array.from(i.files);else if(typeof i=="object"&&i!==null&&typeof i.length=="number"&&typeof i.item=="function")t=Array.from(i);else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string")throw d.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=i}else throw d.ShipError.business("Invalid input type for browser environment. Expected File[], FileList, or HTMLInputElement.");t=t.filter(n=>n.size===0?(console.warn(`Skipping empty file: ${n.name}`),!1):!0),ne(t);let o=await L(t,e);return se(o)}async function ae(i,e={}){let t=f();if(t!=="node"&&t!=="browser")throw d.ShipError.business("Unsupported execution environment.");return t==="node"?$e(i,e):Te(i,e)}function le(i,e,t){return{create:async(o,n={})=>{t&&await t();let s=e?X(n,e):n,a=await ae(o,s);return await i().deploy(a,s)},list:async()=>(t&&await t(),i().listDeployments()),remove:async o=>{t&&await t(),await i().removeDeployment(o)},get:async o=>(t&&await t(),i().getDeployment(o))}}function pe(i,e){return{set:async(t,o)=>(e&&await e(),i().setAlias(t,o)),get:async t=>(e&&await e(),i().getAlias(t)),list:async()=>(e&&await e(),i().listAliases()),remove:async t=>{e&&await e(),await i().removeAlias(t)}}}function ce(i,e){return{get:async()=>(e&&await e(),i().getAccount())}}function me(i,e){return{create:async()=>(e&&await e(),i().createApiKey())}}var M=require("@shipstatic/types"),z=class{constructor(e={}){this.initPromise=null;if(this.clientOptions=e,this.environment=f(),this.environment!=="node"&&this.environment!=="browser")throw fe.ShipError.business("Unsupported execution environment.");let t=j(e,{});this.http=new A({...e,...t});let o=this.getInitCallback(),n=()=>this.http;this._deployments=le(n,this.clientOptions,o),this._aliases=pe(n,o),this._account=ce(n,o),this._keys=me(n,o)}async ensureInitialized(){return this.initPromise||(this.initPromise=this.initializeConfig()),this.initPromise}getInitCallback(){return()=>this.ensureInitialized()}async initializeConfig(){try{let e=await Y(this.clientOptions.configFile),t=j(this.clientOptions,e);this.http=new A({...this.clientOptions,...t});let o=await this.http.getConfig();ee(o)}catch(e){throw this.initPromise=null,e}}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 keys(){return this._keys}},Ie=z;0&&(module.exports={Ship,ShipError,ShipErrorType,__setTestEnvironment,processFilesForBrowser,processFilesForNode});
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|