module.exports = /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ /***/ 7351: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const os = __importStar(__webpack_require__(2087)); /** * Commands * * Command Format: * ::name key=value,key=value::message * * Examples: * ::warning::This is the message * ::set-env name=MY_VAR::some value */ function issueCommand(command, properties, message) { const cmd = new Command(command, properties, message); process.stdout.write(cmd.toString() + os.EOL); } exports.issueCommand = issueCommand; function issue(name, message = '') { issueCommand(name, {}, message); } exports.issue = issue; const CMD_STRING = '::'; class Command { constructor(command, properties, message) { if (!command) { command = 'missing.command'; } this.command = command; this.properties = properties; this.message = message; } toString() { let cmdStr = CMD_STRING + this.command; if (this.properties && Object.keys(this.properties).length > 0) { cmdStr += ' '; let first = true; for (const key in this.properties) { if (this.properties.hasOwnProperty(key)) { const val = this.properties[key]; if (val) { if (first) { first = false; } else { cmdStr += ','; } cmdStr += `${key}=${escapeProperty(val)}`; } } } } cmdStr += `${CMD_STRING}${escapeData(this.message)}`; return cmdStr; } } /** * Sanitizes an input into a string so it can be passed into issueCommand safely * @param input input to sanitize into a string */ function toCommandValue(input) { if (input === null || input === undefined) { return ''; } else if (typeof input === 'string' || input instanceof String) { return input; } return JSON.stringify(input); } exports.toCommandValue = toCommandValue; function escapeData(s) { return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A'); } function escapeProperty(s) { return toCommandValue(s) .replace(/%/g, '%25') .replace(/\r/g, '%0D') .replace(/\n/g, '%0A') .replace(/:/g, '%3A') .replace(/,/g, '%2C'); } //# sourceMappingURL=command.js.map /***/ }), /***/ 2186: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result["default"] = mod; return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); const command_1 = __webpack_require__(7351); const os = __importStar(__webpack_require__(2087)); const path = __importStar(__webpack_require__(5622)); /** * The code to exit an action */ var ExitCode; (function (ExitCode) { /** * A code indicating that the action was successful */ ExitCode[ExitCode["Success"] = 0] = "Success"; /** * A code indicating that the action was a failure */ ExitCode[ExitCode["Failure"] = 1] = "Failure"; })(ExitCode = exports.ExitCode || (exports.ExitCode = {})); //----------------------------------------------------------------------- // Variables //----------------------------------------------------------------------- /** * Sets env variable for this action and future actions in the job * @param name the name of the variable to set * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function exportVariable(name, val) { const convertedVal = command_1.toCommandValue(val); process.env[name] = convertedVal; command_1.issueCommand('set-env', { name }, convertedVal); } exports.exportVariable = exportVariable; /** * Registers a secret which will get masked from logs * @param secret value of the secret */ function setSecret(secret) { command_1.issueCommand('add-mask', {}, secret); } exports.setSecret = setSecret; /** * Prepends inputPath to the PATH (for this action and future actions) * @param inputPath */ function addPath(inputPath) { command_1.issueCommand('add-path', {}, inputPath); process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; } exports.addPath = addPath; /** * Gets the value of an input. The value is also trimmed. * * @param name name of the input to get * @param options optional. See InputOptions. * @returns string */ function getInput(name, options) { const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; if (options && options.required && !val) { throw new Error(`Input required and not supplied: ${name}`); } return val.trim(); } exports.getInput = getInput; /** * Sets the value of an output. * * @param name name of the output to set * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function setOutput(name, value) { command_1.issueCommand('set-output', { name }, value); } exports.setOutput = setOutput; /** * Enables or disables the echoing of commands into stdout for the rest of the step. * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. * */ function setCommandEcho(enabled) { command_1.issue('echo', enabled ? 'on' : 'off'); } exports.setCommandEcho = setCommandEcho; //----------------------------------------------------------------------- // Results //----------------------------------------------------------------------- /** * Sets the action status to failed. * When the action exits it will be with an exit code of 1 * @param message add error issue message */ function setFailed(message) { process.exitCode = ExitCode.Failure; error(message); } exports.setFailed = setFailed; //----------------------------------------------------------------------- // Logging Commands //----------------------------------------------------------------------- /** * Gets whether Actions Step Debug is on or not */ function isDebug() { return process.env['RUNNER_DEBUG'] === '1'; } exports.isDebug = isDebug; /** * Writes debug message to user log * @param message debug message */ function debug(message) { command_1.issueCommand('debug', {}, message); } exports.debug = debug; /** * Adds an error issue * @param message error issue message. Errors will be converted to string via toString() */ function error(message) { command_1.issue('error', message instanceof Error ? message.toString() : message); } exports.error = error; /** * Adds an warning issue * @param message warning issue message. Errors will be converted to string via toString() */ function warning(message) { command_1.issue('warning', message instanceof Error ? message.toString() : message); } exports.warning = warning; /** * Writes info to log with console.log. * @param message info message */ function info(message) { process.stdout.write(message + os.EOL); } exports.info = info; /** * Begin an output group. * * Output until the next `groupEnd` will be foldable in this group * * @param name The name of the output group */ function startGroup(name) { command_1.issue('group', name); } exports.startGroup = startGroup; /** * End an output group. */ function endGroup() { command_1.issue('endgroup'); } exports.endGroup = endGroup; /** * Wrap an asynchronous function call in a group. * * Returns the same type as the function itself. * * @param name The name of the group * @param fn The function to wrap in the group */ function group(name, fn) { return __awaiter(this, void 0, void 0, function* () { startGroup(name); let result; try { result = yield fn(); } finally { endGroup(); } return result; }); } exports.group = group; //----------------------------------------------------------------------- // Wrapper action state //----------------------------------------------------------------------- /** * Saves state for current action, the state can only be retrieved by this action's post job execution. * * @param name name of the state to store * @param value value to store. Non-string values will be converted to a string via JSON.stringify */ // eslint-disable-next-line @typescript-eslint/no-explicit-any function saveState(name, value) { command_1.issueCommand('save-state', { name }, value); } exports.saveState = saveState; /** * Gets the value of an state set by this action's main execution. * * @param name name of the state to get * @returns string */ function getState(name) { return process.env[`STATE_${name}`] || ''; } exports.getState = getState; //# sourceMappingURL=core.js.map /***/ }), /***/ 5176: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.createFilter = void 0; const normalize_1 = __webpack_require__(7561); const util_1 = __webpack_require__(9735); function createFilter(options, ...args) { let criteria = args.length <= 1 ? args[0] : args; let filters = normalize_1.normalize(criteria, options); pathFilter[util_1._filters] = filters; return pathFilter; function pathFilter(...args) { // Does the file path match any of the exclude filters? let exclude = filters.exclude.some((filter) => filter(...args)); if (exclude) { return false; } if (filters.include.length === 0) { // Include everything that's not excluded return true; } // Does the file path match any of the include filters? let include = filters.include.some((filter) => filter(...args)); return include; } } exports.createFilter = createFilter; //# sourceMappingURL=create-filter.js.map /***/ }), /***/ 2405: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.filePathFilter = void 0; const create_filter_1 = __webpack_require__(5176); function filePathFilter(...args) { return create_filter_1.createFilter({}, ...args); } exports.filePathFilter = filePathFilter; //# sourceMappingURL=file-path-filter.js.map /***/ }), /***/ 3410: /***/ (function(module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.filePathFilter = void 0; const file_path_filter_1 = __webpack_require__(2405); Object.defineProperty(exports, "filePathFilter", ({ enumerable: true, get: function () { return file_path_filter_1.filePathFilter; } })); __exportStar(__webpack_require__(3225), exports); var create_filter_1 = __webpack_require__(5176); Object.defineProperty(exports, "createFilter", ({ enumerable: true, get: function () { return create_filter_1.createFilter; } })); // Export `filePathFilter` as a named export and the default export exports.default = file_path_filter_1.filePathFilter; // CommonJS default export hack /* eslint-env commonjs */ if ( true && typeof module.exports === "object") { module.exports = Object.assign(module.exports.default, module.exports); } //# sourceMappingURL=index.js.map /***/ }), /***/ 7561: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalize = void 0; const globToRegExp = __webpack_require__(7117); const path = __webpack_require__(5622); const util_1 = __webpack_require__(9735); /** * Normalizes the user-provided filter criteria. The normalized form is a `Filters` object * whose `include` and `exclude` properties are both `FilterFunction` arrays. */ function normalize(criteria, opts) { let filters = { include: [], exclude: [], }; let options = normalizeOptions(opts); // Convert each criterion to a FilterFunction let tuples = normalizeCriteria(criteria, options); // Populate the `include` and `exclude` arrays for (let [filter, filterFunction] of tuples) { filters[filter].push(filterFunction); } return filters; } exports.normalize = normalize; /** * Fills-in defaults for any options that weren't specified by the caller. */ function normalizeOptions(options) { return { // TODO: Remove the "getPath" fallback in the next minor release map: options.map || options.getPath || String, sep: options.sep || path.sep, }; } /** * Creates a `FilterFunction` for each given criterion. */ function normalizeCriteria(criteria, options, filter) { let tuples = []; if (Array.isArray(criteria)) { for (let criterion of criteria) { tuples.push(...normalizeCriteria(criterion, options, filter)); } } else if (util_1.isPathFilter(criteria)) { for (let filterFunction of criteria[util_1._filters].include) { tuples.push(["include", filterFunction]); } for (let filterFunction of criteria[util_1._filters].exclude) { tuples.push(["exclude", filterFunction]); } } else if (util_1.isFilterCriterion(criteria)) { tuples.push(normalizeCriterion(criteria, options, filter)); } else if (criteria && typeof criteria === "object" && !filter) { if (criteria.include !== undefined) { tuples.push(...normalizeCriteria(criteria.include, options, "include")); } if (criteria.exclude !== undefined) { tuples.push(...normalizeCriteria(criteria.exclude, options, "exclude")); } } else { throw new Error(`Invalid filter criteria: ${criteria}`); } return tuples; } /** * Creates a `FilterFunction` for the given criterion. * * @param criteria - One or more filter critiera * @param options - Options for how the `FilterFunction` should behave * @param filter - The type of filter. Defaults to `include`, except for glob patterns that start with "!" */ function normalizeCriterion(criterion, options, filter) { const globOptions = { extended: true, globstar: true }; let type = typeof criterion; let filterFunction; if (type === "function") { filterFunction = criterion; } else if (type === "boolean") { let bool = criterion; filterFunction = function booleanFilter() { return bool; }; } else if (type === "string") { let glob = criterion; let invert = false; if (glob.startsWith("!")) { glob = glob.substr(1); invert = Boolean(filter); filter = filter || "exclude"; } let pattern = globToRegExp(glob, globOptions); filterFunction = createGlobFilter(pattern, options, invert); } else if (criterion instanceof RegExp) { let pattern = criterion; let { map } = options; filterFunction = function regExpFilter(...args) { let filePath = map(...args); return pattern.test(filePath); }; } else { throw new Error(`Invalid filter criteria: ${criterion}`); } return [filter || "include", filterFunction]; } /** * Creates a `FilterFunction` for filtering based on glob patterns */ function createGlobFilter(pattern, options, invert) { let { map, sep } = options; return function globFilter(...args) { let filePath = map(...args); if (sep !== "/") { // Glob patterns always expect forward slashes, even on Windows filePath = filePath.replace(new RegExp("\\" + sep, "g"), "/"); } let match = pattern.test(filePath); return invert ? !match : match; }; } //# sourceMappingURL=normalize.js.map /***/ }), /***/ 3225: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=types.js.map /***/ }), /***/ 9735: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.isPathFilter = exports.isFilterCriterion = exports._filters = void 0; /** * Symbol used to store the underlying filters of a `pathFilter()` function. */ exports._filters = Symbol("_filters"); /** * Determines whether the given value is a `FilterCriterion`. */ function isFilterCriterion(value) { let type = typeof value; return type === "string" || type === "boolean" || type === "function" || value instanceof RegExp; } exports.isFilterCriterion = isFilterCriterion; /** * Determines whether the given value is one of our internal `pathFilter()` functions. */ function isPathFilter(value) { let fn = value; return fn && typeof fn === "function" && typeof fn[exports._filters] === "object"; } exports.isPathFilter = isPathFilter; //# sourceMappingURL=util.js.map /***/ }), /***/ 504: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.asyncForEach = void 0; /** * Simultaneously processes all items in the given array. * * @param array - The array to iterate over * @param iterator - The function to call for each item in the array * @param done - The function to call when all iterators have completed * * @internal */ function asyncForEach(array, iterator, done) { if (!Array.isArray(array)) { throw new TypeError(`${array} is not an array`); } if (array.length === 0) { // NOTE: Normally a bad idea to mix sync and async, but it's safe here because // of the way that this method is currently used by DirectoryReader. done(); return; } // Simultaneously process all items in the array. let pending = array.length; for (let item of array) { iterator(item, callback); } function callback() { if (--pending === 0) { done(); } } } exports.asyncForEach = asyncForEach; //# sourceMappingURL=for-each.js.map /***/ }), /***/ 5833: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdirAsync = void 0; const fs = __webpack_require__(5747); const directory_reader_1 = __webpack_require__(4918); const for_each_1 = __webpack_require__(504); const asyncFacade = { fs, forEach: for_each_1.asyncForEach }; function readdirAsync(dir, options, callback) { if (typeof options === "function") { callback = options; options = undefined; } let promise = new Promise((resolve, reject) => { let results = []; let reader = new directory_reader_1.DirectoryReader(dir, options, asyncFacade); let stream = reader.stream; stream.on("error", (err) => { reject(err); stream.pause(); }); stream.on("data", (result) => { results.push(result); }); stream.on("end", () => { resolve(results); }); }); if (callback) { promise.then((results) => callback(null, results), (err) => callback(err, undefined)); } else { return promise; } } exports.readdirAsync = readdirAsync; //# sourceMappingURL=index.js.map /***/ }), /***/ 8188: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.callOnce = exports.safeCall = void 0; /** * Calls a function with the given arguments, and ensures that the error-first callback is _always_ * invoked exactly once, even if the function throws an error. * * @param fn - The function to invoke * @param args - The arguments to pass to the function. The final argument must be a callback function. * * @internal */ function safeCall(fn, input, callback) { // Replace the callback function with a wrapper that ensures it will only be called once callback = callOnce(callback); try { fn(input, callback); } catch (err) { callback(err, undefined); } } exports.safeCall = safeCall; /** * Returns a wrapper function that ensures the given callback function is only called once. * Subsequent calls are ignored, unless the first argument is an Error, in which case the * error is thrown. * * @param callback - The function that should only be called once * * @internal */ function callOnce(callback) { let fulfilled = false; return function onceWrapper(err, result) { if (!fulfilled) { fulfilled = true; callback.call(this, err, result); } else if (err) { // The callback has already been called, but now an error has occurred // (most likely inside the callback function). So re-throw the error, // so it gets handled further up the call stack throw err; } }; } exports.callOnce = callOnce; //# sourceMappingURL=call.js.map /***/ }), /***/ 4918: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.DirectoryReader = void 0; const path = __webpack_require__(5622); const stream_1 = __webpack_require__(2413); const call_1 = __webpack_require__(8188); const normalize_options_1 = __webpack_require__(2977); const stat_1 = __webpack_require__(9445); /** * Asynchronously reads the contents of a directory and streams the results * via a `ReadableStream`. * * @internal */ class DirectoryReader { /** * @param dir - The absolute or relative directory path to read * @param [options] - User-specified options, if any (see `normalizeOptions()`) * @param facade - sync or async function implementations * @param emit - Indicates whether the reader should emit "file", "directory", and "symlink" events. */ constructor(dir, options, facade, emit = false) { this.options = normalize_options_1.normalizeOptions(options, facade, emit); // Indicates whether we should keep reading // This is set false if stream.Readable.push() returns false. this.shouldRead = true; // The directories to read // (initialized with the top-level directory) this.queue = [{ path: dir, basePath: this.options.basePath, depth: 0 }]; // The number of directories that are currently being processed this.pending = 0; // The data that has been read, but not yet emitted this.buffer = []; this.stream = new stream_1.Readable({ objectMode: true }); this.stream._read = () => { // Start (or resume) reading this.shouldRead = true; // If we have data in the buffer, then send the next chunk if (this.buffer.length > 0) { this.pushFromBuffer(); } // If we have directories queued, then start processing the next one if (this.queue.length > 0) { this.readNextDirectory(); } this.checkForEOF(); }; } /** * Reads the next directory in the queue */ readNextDirectory() { let { facade } = this.options; let dir = this.queue.shift(); this.pending++; // Read the directory listing call_1.safeCall(facade.fs.readdir, dir.path, (err, items) => { if (err) { // fs.readdir threw an error this.emit("error", err); return this.finishedReadingDirectory(); } try { // Process each item in the directory (simultaneously, if async) facade.forEach(items, this.processItem.bind(this, dir), this.finishedReadingDirectory.bind(this, dir)); } catch (err2) { // facade.forEach threw an error // (probably because fs.readdir returned an invalid result) this.emit("error", err2); this.finishedReadingDirectory(); } }); } /** * This method is called after all items in a directory have been processed. * * NOTE: This does not necessarily mean that the reader is finished, since there may still * be other directories queued or pending. */ finishedReadingDirectory() { this.pending--; if (this.shouldRead) { // If we have directories queued, then start processing the next one if (this.queue.length > 0) { this.readNextDirectory(); } this.checkForEOF(); } } /** * Determines whether the reader has finished processing all items in all directories. * If so, then the "end" event is fired (via {@Readable#push}) */ checkForEOF() { if (this.buffer.length === 0 && // The stuff we've already read this.pending === 0 && // The stuff we're currently reading this.queue.length === 0) { // The stuff we haven't read yet // There's no more stuff! this.stream.push(null); } } /** * Processes a single item in a directory. * * If the item is a directory, and `option.deep` is enabled, then the item will be added * to the directory queue. * * If the item meets the filter criteria, then it will be emitted to the reader's stream. * * @param dir - A directory object from the queue * @param item - The name of the item (name only, no path) * @param done - A callback function that is called after the item has been processed */ processItem(dir, item, done) { let stream = this.stream; let options = this.options; let itemPath = dir.basePath + item; let fullPath = path.join(dir.path, item); // If `options.deep` is a number, and we've already recursed to the max depth, // then there's no need to check fs.Stats to know if it's a directory. // If `options.deep` is a function, then we'll need fs.Stats let maxDepthReached = dir.depth >= options.recurseDepth; // Do we need to call `fs.stat`? let needStats = !maxDepthReached || // we need the fs.Stats to know if it's a directory options.stats || // the user wants fs.Stats objects returned options.recurseFnNeedsStats || // we need fs.Stats for the recurse function options.filterFnNeedsStats || // we need fs.Stats for the filter function stream.listenerCount("file") || // we need the fs.Stats to know if it's a file stream.listenerCount("directory") || // we need the fs.Stats to know if it's a directory stream.listenerCount("symlink"); // we need the fs.Stats to know if it's a symlink // If we don't need stats, then exit early if (!needStats) { if (this.filter({ path: itemPath })) { this.pushOrBuffer({ data: itemPath }); } return done(); } // Get the fs.Stats object for this path stat_1.stat(options.facade.fs, fullPath, (err, stats) => { if (err) { // fs.stat threw an error this.emit("error", err); return done(); } try { // Add the item's path to the fs.Stats object // The base of this path, and its separators are determined by the options // (i.e. options.basePath and options.sep) stats.path = itemPath; // Add depth of the path to the fs.Stats object for use this in the filter function stats.depth = dir.depth; if (this.shouldRecurse(stats, maxDepthReached)) { // Add this subdirectory to the queue this.queue.push({ path: fullPath, basePath: itemPath + options.sep, depth: dir.depth + 1, }); } // Determine whether this item matches the filter criteria if (this.filter(stats)) { this.pushOrBuffer({ data: options.stats ? stats : itemPath, file: stats.isFile(), directory: stats.isDirectory(), symlink: stats.isSymbolicLink(), }); } done(); } catch (err2) { // An error occurred while processing the item // (probably during a user-specified function, such as options.deep, options.filter, etc.) this.emit("error", err2); done(); } }); } /** * Pushes the given chunk of data to the stream, or adds it to the buffer, * depending on the state of the stream. */ pushOrBuffer(chunk) { // Add the chunk to the buffer this.buffer.push(chunk); // If we're still reading, then immediately emit the next chunk in the buffer // (which may or may not be the chunk that we just added) if (this.shouldRead) { this.pushFromBuffer(); } } /** * Immediately pushes the next chunk in the buffer to the reader's stream. * The "data" event will always be fired (via `Readable.push()`). * In addition, the "file", "directory", and/or "symlink" events may be fired, * depending on the type of properties of the chunk. */ pushFromBuffer() { let stream = this.stream; let chunk = this.buffer.shift(); // Stream the data try { this.shouldRead = stream.push(chunk.data); } catch (err) { this.emit("error", err); } if (this.options.emit) { // Also emit specific events, based on the type of chunk chunk.file && this.emit("file", chunk.data); chunk.symlink && this.emit("symlink", chunk.data); chunk.directory && this.emit("directory", chunk.data); } } /** * Determines whether the given directory meets the user-specified recursion criteria. * If the user didn't specify recursion criteria, then this function will default to true. * * @param stats - The directory's `Stats` object * @param maxDepthReached - Whether we've already crawled the user-specified depth */ shouldRecurse(stats, maxDepthReached) { let { recurseFn } = this.options; if (maxDepthReached) { // We've already crawled to the maximum depth. So no more recursion. return false; } else if (!stats.isDirectory()) { // It's not a directory. So don't try to crawl it. return false; } else if (recurseFn) { try { // Run the user-specified recursion criteria return !!recurseFn(stats); } catch (err) { // An error occurred in the user's code. // In Sync and Async modes, this will return an error. // In Streaming mode, we emit an "error" event, but continue processing this.emit("error", err); } } else { // No recursion function was specified, and we're within the maximum depth. // So crawl this directory. return true; } } /** * Determines whether the given item meets the user-specified filter criteria. * If the user didn't specify a filter, then this function will always return true. * * @param stats - The item's `Stats` object, or an object with just a `path` property */ filter(stats) { let { filterFn } = this.options; if (filterFn) { try { // Run the user-specified filter function return !!filterFn(stats); } catch (err) { // An error occurred in the user's code. // In Sync and Async modes, this will return an error. // In Streaming mode, we emit an "error" event, but continue processing this.emit("error", err); } } else { // No filter was specified, so match everything return true; } } /** * Emits an event. If one of the event listeners throws an error, * then an "error" event is emitted. */ emit(eventName, data) { let stream = this.stream; try { stream.emit(eventName, data); } catch (err) { if (eventName === "error") { // Don't recursively emit "error" events. // If the first one fails, then just throw throw err; } else { stream.emit("error", err); } } } } exports.DirectoryReader = DirectoryReader; //# sourceMappingURL=directory-reader.js.map /***/ }), /***/ 8811: /***/ (function(module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdir = void 0; const async_1 = __webpack_require__(5833); const iterator_1 = __webpack_require__(5944); const stream_1 = __webpack_require__(5521); const sync_1 = __webpack_require__(704); const readdir = async_1.readdirAsync; exports.readdir = readdir; readdir.sync = sync_1.readdirSync; readdir.async = async_1.readdirAsync; readdir.stream = stream_1.readdirStream; readdir.iterator = iterator_1.readdirIterator; var async_2 = __webpack_require__(5833); Object.defineProperty(exports, "readdirAsync", ({ enumerable: true, get: function () { return async_2.readdirAsync; } })); var iterator_2 = __webpack_require__(5944); Object.defineProperty(exports, "readdirIterator", ({ enumerable: true, get: function () { return iterator_2.readdirIterator; } })); var stream_2 = __webpack_require__(5521); Object.defineProperty(exports, "readdirStream", ({ enumerable: true, get: function () { return stream_2.readdirStream; } })); var sync_2 = __webpack_require__(704); Object.defineProperty(exports, "readdirSync", ({ enumerable: true, get: function () { return sync_2.readdirSync; } })); __exportStar(__webpack_require__(6299), exports); exports.default = readdir; // CommonJS default export hack /* eslint-env commonjs */ if ( true && typeof module.exports === "object") { module.exports = Object.assign(module.exports.default, module.exports); } //# sourceMappingURL=index.js.map /***/ }), /***/ 5944: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdirIterator = void 0; const fs = __webpack_require__(5747); const for_each_1 = __webpack_require__(504); const directory_reader_1 = __webpack_require__(4918); const pending_1 = __webpack_require__(8553); const iteratorFacade = { fs, forEach: for_each_1.asyncForEach }; function readdirIterator(dir, options) { let reader = new directory_reader_1.DirectoryReader(dir, options, iteratorFacade); let stream = reader.stream; let pendingValues = []; let pendingReads = []; let error; let readable = false; let done = false; stream.on("error", function streamError(err) { error = err; stream.pause(); fulfillPendingReads(); }); stream.on("end", function streamEnd() { done = true; fulfillPendingReads(); }); stream.on("readable", function streamReadable() { readable = true; fulfillPendingReads(); }); return { [Symbol.asyncIterator]() { return this; }, next() { let pendingRead = pending_1.pending(); pendingReads.push(pendingRead); // eslint-disable-next-line @typescript-eslint/no-floating-promises Promise.resolve().then(fulfillPendingReads); return pendingRead.promise; } }; function fulfillPendingReads() { if (error) { while (pendingReads.length > 0) { let pendingRead = pendingReads.shift(); pendingRead.reject(error); } } else if (pendingReads.length > 0) { while (pendingReads.length > 0) { let pendingRead = pendingReads.shift(); let value = getNextValue(); if (value) { pendingRead.resolve({ value }); } else if (done) { pendingRead.resolve({ done, value }); } else { pendingReads.unshift(pendingRead); break; } } } } function getNextValue() { let value = pendingValues.shift(); if (value) { return value; } else if (readable) { readable = false; while (true) { value = stream.read(); if (value) { pendingValues.push(value); } else { break; } } return pendingValues.shift(); } } } exports.readdirIterator = readdirIterator; //# sourceMappingURL=index.js.map /***/ }), /***/ 8553: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.pending = void 0; /** * Returns a `Promise` and the functions to resolve or reject it. * @internal */ function pending() { let resolve, reject; let promise = new Promise((res, rej) => { resolve = res; reject = rej; }); return { promise, resolve(result) { // eslint-disable-next-line @typescript-eslint/no-floating-promises Promise.resolve(result).then(resolve); }, reject(reason) { Promise.reject(reason).catch(reject); } }; } exports.pending = pending; //# sourceMappingURL=pending.js.map /***/ }), /***/ 2977: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.normalizeOptions = void 0; const file_path_filter_1 = __webpack_require__(3410); const path = __webpack_require__(5622); /** * Validates and normalizes the options argument * * @param [options] - User-specified options, if any * @param facade - sync or async function implementations * @param emit - Indicates whether the reader should emit "file", "directory", and "symlink" events. * * @internal */ function normalizeOptions(options, facade, emit) { if (options === null || options === undefined) { options = {}; } else if (typeof options !== "object") { throw new TypeError("options must be an object"); } let sep = options.sep; if (sep === null || sep === undefined) { sep = path.sep; } else if (typeof sep !== "string") { throw new TypeError("options.sep must be a string"); } let stats = Boolean(options.stats || options.withFileTypes); let recurseDepth, recurseFn, recurseFnNeedsStats = false, deep = options.deep; if (deep === null || deep === undefined) { recurseDepth = 0; } else if (typeof deep === "boolean") { recurseDepth = deep ? Infinity : 0; } else if (typeof deep === "number") { if (deep < 0 || isNaN(deep)) { throw new Error("options.deep must be a positive number"); } else if (Math.floor(deep) !== deep) { throw new Error("options.deep must be an integer"); } else { recurseDepth = deep; } } else if (typeof deep === "function") { // Recursion functions require a Stats object recurseFnNeedsStats = true; recurseDepth = Infinity; recurseFn = deep; } else if (deep instanceof RegExp || (typeof deep === "string" && deep.length > 0)) { recurseDepth = Infinity; recurseFn = file_path_filter_1.createFilter({ map, sep }, deep); } else { throw new TypeError("options.deep must be a boolean, number, function, regular expression, or glob pattern"); } let filterFn, filterFnNeedsStats = false, filter = options.filter; if (filter !== null && filter !== undefined) { if (typeof filter === "function") { // Filter functions requres a Stats object filterFnNeedsStats = true; filterFn = filter; } else if (filter instanceof RegExp || typeof filter === "boolean" || (typeof filter === "string" && filter.length > 0)) { filterFn = file_path_filter_1.createFilter({ map, sep }, filter); } else { throw new TypeError("options.filter must be a boolean, function, regular expression, or glob pattern"); } } let basePath = options.basePath; if (basePath === null || basePath === undefined) { basePath = ""; } else if (typeof basePath === "string") { // Append a path separator to the basePath, if necessary if (basePath && basePath.substr(-1) !== sep) { basePath += sep; } } else { throw new TypeError("options.basePath must be a string"); } // Determine which facade methods to use if (options.fs === null || options.fs === undefined) { // The user didn't provide their own facades, so use our internal ones } else if (typeof options.fs === "object") { // Merge the internal facade methods with the user-provided `fs` facades facade = Object.assign({}, facade); facade.fs = Object.assign({}, facade.fs, options.fs); } else { throw new TypeError("options.fs must be an object"); } return { recurseDepth, recurseFn, recurseFnNeedsStats, filterFn, filterFnNeedsStats, stats, sep, basePath, facade, emit, }; } exports.normalizeOptions = normalizeOptions; /** * Maps our modified fs.Stats objects to file paths */ function map(stats) { return stats.path; } //# sourceMappingURL=normalize-options.js.map /***/ }), /***/ 9445: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.stat = void 0; const call_1 = __webpack_require__(8188); /** * Retrieves the `Stats` for the given path. If the path is a symbolic link, * then the Stats of the symlink's target are returned instead. If the symlink is broken, * then the Stats of the symlink itself are returned. * * @param fs - Synchronous or Asynchronouse facade for the "fs" module * @param path - The path to return stats for * * @internal */ function stat(fs, path, callback) { let isSymLink = false; call_1.safeCall(fs.lstat, path, (err, lstats) => { if (err) { // fs.lstat threw an eror return callback(err, undefined); } try { isSymLink = lstats.isSymbolicLink(); } catch (err2) { // lstats.isSymbolicLink() threw an error // (probably because fs.lstat returned an invalid result) return callback(err2, undefined); } if (isSymLink) { // Try to resolve the symlink symlinkStat(fs, path, lstats, callback); } else { // It's not a symlink, so return the stats as-is callback(null, lstats); } }); } exports.stat = stat; /** * Retrieves the `Stats` for the target of the given symlink. * If the symlink is broken, then the Stats of the symlink itself are returned. * * @param fs - Synchronous or Asynchronouse facade for the "fs" module * @param path - The path of the symlink to return stats for * @param lstats - The stats of the symlink */ function symlinkStat(fs, path, lstats, callback) { call_1.safeCall(fs.stat, path, (err, stats) => { if (err) { // The symlink is broken, so return the stats for the link itself return callback(null, lstats); } try { // Return the stats for the resolved symlink target, // and override the `isSymbolicLink` method to indicate that it's a symlink stats.isSymbolicLink = () => true; } catch (err2) { // Setting stats.isSymbolicLink threw an error // (probably because fs.stat returned an invalid result) return callback(err2, undefined); } callback(null, stats); }); } //# sourceMappingURL=stat.js.map /***/ }), /***/ 5521: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdirStream = void 0; const fs = __webpack_require__(5747); const for_each_1 = __webpack_require__(504); const directory_reader_1 = __webpack_require__(4918); const streamFacade = { fs, forEach: for_each_1.asyncForEach }; function readdirStream(dir, options) { let reader = new directory_reader_1.DirectoryReader(dir, options, streamFacade, true); return reader.stream; } exports.readdirStream = readdirStream; //# sourceMappingURL=index.js.map /***/ }), /***/ 7448: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.syncForEach = void 0; /** * A facade that allows `Array.forEach()` to be called as though it were asynchronous. * * @param array - The array to iterate over * @param iterator - The function to call for each item in the array * @param done - The function to call when all iterators have completed * * @internal */ function syncForEach(array, iterator, done) { if (!Array.isArray(array)) { throw new TypeError(`${array} is not an array`); } for (let item of array) { iterator(item, () => { // Note: No error-handling here because this is currently only ever called // by DirectoryReader, which never passes an `error` parameter to the callback. // Instead, DirectoryReader emits an "error" event if an error occurs. }); } done(); } exports.syncForEach = syncForEach; //# sourceMappingURL=for-each.js.map /***/ }), /***/ 3073: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.syncFS = void 0; const fs = __webpack_require__(5747); const call_1 = __webpack_require__(8188); /** * Synchronous versions of `fs` methods. * * @internal */ exports.syncFS = { /** * A facade around `fs.readdirSync()` that allows it to be called * the same way as `fs.readdir()`. */ readdir(dir, callback) { // Make sure the callback is only called once callback = call_1.callOnce(callback); try { let items = fs.readdirSync(dir); callback(null, items); } catch (err) { callback(err, undefined); } }, /** * A facade around `fs.statSync()` that allows it to be called * the same way as `fs.stat()`. */ stat(path, callback) { // Make sure the callback is only called once callback = call_1.callOnce(callback); try { let stats = fs.statSync(path); callback(null, stats); } catch (err) { callback(err, undefined); } }, /** * A facade around `fs.lstatSync()` that allows it to be called * the same way as `fs.lstat()`. */ lstat(path, callback) { // Make sure the callback is only called once callback = call_1.callOnce(callback); try { let stats = fs.lstatSync(path); callback(null, stats); } catch (err) { callback(err, undefined); } }, }; //# sourceMappingURL=fs.js.map /***/ }), /***/ 704: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.readdirSync = void 0; const directory_reader_1 = __webpack_require__(4918); const for_each_1 = __webpack_require__(7448); const fs_1 = __webpack_require__(3073); const syncFacade = { fs: fs_1.syncFS, forEach: for_each_1.syncForEach }; function readdirSync(dir, options) { let reader = new directory_reader_1.DirectoryReader(dir, options, syncFacade); let stream = reader.stream; let results = []; let data = stream.read(); while (data !== null) { results.push(data); data = stream.read(); } return results; } exports.readdirSync = readdirSync; //# sourceMappingURL=index.js.map /***/ }), /***/ 6299: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); //# sourceMappingURL=types-public.js.map /***/ }), /***/ 9946: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.HashDiff = void 0; function formatNumber(number) { return number.toLocaleString(); } class HashDiff { getDiffs(localFiles, serverFiles, logger) { var _a, _b, _c; const uploadList = []; const deleteList = []; const replaceList = []; let sizeUpload = 0; let sizeDelete = 0; let sizeReplace = 0; // alphabetize each list based off path const localFilesSorted = localFiles.data.sort((first, second) => first.name.localeCompare(second.name)); const serverFilesSorted = serverFiles.data.sort((first, second) => first.name.localeCompare(second.name)); logger.info(`----------------------------------------------------------------`); logger.info(`Local Files:\t${formatNumber(localFilesSorted.length)}`); logger.info(`Server Files:\t${formatNumber(localFilesSorted.length)}`); logger.info(`----------------------------------------------------------------`); logger.info(`Calculating differences between client & server`); logger.info(`----------------------------------------------------------------`); let localPosition = 0; let serverPosition = 0; while (localPosition + serverPosition < localFilesSorted.length + serverFilesSorted.length) { let localFile = localFilesSorted[localPosition]; let serverFile = serverFilesSorted[serverPosition]; let fileNameCompare = 0; if (localFile === undefined) { fileNameCompare = 1; } if (serverFile === undefined) { fileNameCompare = -1; } if (localFile !== undefined && serverFile !== undefined) { fileNameCompare = localFile.name.localeCompare(serverFile.name); } if (fileNameCompare < 0) { let icon = localFile.type === "folder" ? `๐ Create` : `โ Upload`; logger.info(`${icon}: ${localFile.name}`); uploadList.push(localFile); sizeUpload += (_a = localFile.size) !== null && _a !== void 0 ? _a : 0; localPosition += 1; } else if (fileNameCompare > 0) { let icon = serverFile.type === "folder" ? `๐` : `๐๏ธ`; logger.info(`${icon} Delete: ${serverFile.name} `); deleteList.push(serverFile); sizeDelete += (_b = serverFile.size) !== null && _b !== void 0 ? _b : 0; serverPosition += 1; } else if (fileNameCompare === 0) { // paths are a match if (localFile.type === "file" && serverFile.type === "file") { if (localFile.hash === serverFile.hash) { logger.info(`โ๏ธ File content is the same, doing nothing: ${localFile.name}`); } else { logger.info(`๐ File replace: ${localFile.name}`); sizeReplace += (_c = localFile.size) !== null && _c !== void 0 ? _c : 0; replaceList.push(localFile); } } localPosition += 1; serverPosition += 1; } } return { upload: uploadList, delete: deleteList, replace: replaceList, sizeDelete, sizeReplace, sizeUpload }; } } exports.HashDiff = HashDiff; /***/ }), /***/ 3678: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.prettyError = void 0; const types_1 = __webpack_require__(6703); function outputOriginalErrorAndExit(logger, error) { logger.all(); logger.all(`----------------------------------------------------------------`); logger.all(`---------------------- Full Error below ----------------------`); logger.all(error); process.exit(); } /** * Converts a exception to helpful debug info * @param error exception */ function prettyError(logger, args, error) { logger.all(); logger.all(`----------------------------------------------------------------`); logger.all(`--------------- ๐ฅ๐ฅ๐ฅ A error occurred ๐ฅ๐ฅ๐ฅ --------------`); logger.all(`----------------------------------------------------------------`); if (typeof error.code === "string") { const errorCode = error.code; if (errorCode === "ENOTFOUND") { logger.warn(`The server "${args.server}" doesn't seem to exist. Do you have a typo?`); outputOriginalErrorAndExit(logger, error); } } if (typeof error.name === "string") { const errorName = error.name; if (errorName.includes("ERR_TLS_CERT_ALTNAME_INVALID")) { logger.warn(`The certificate for "${args.server}" is likely shared. The host did not place your server on the list of valid domains for this cert.`); logger.warn(`This is a common issue with shared hosts. You have a few options:`); logger.warn(` - Ignore this error by setting security back to loose`); logger.warn(` - Contact your hosting provider and ask them for your servers hostname`); outputOriginalErrorAndExit(logger, error); } } const ftpError = error; if (typeof ftpError.code === "number") { if (ftpError.code === types_1.ErrorCode.NotLoggedIn) { const serverRequiresFTPS = ftpError.message.toLowerCase().includes("must use encryption"); if (serverRequiresFTPS) { logger.warn(`The server you are connecting to requires encryption (ftps)`); logger.warn(`Enable FTPS by using the protocol option.`); outputOriginalErrorAndExit(logger, error); } else { logger.warn(`Could not login with the username "${args.username}" and password "${args.password}".`); logger.warn(`Make sure you can login with those credentials. If you have a space or a quote in your username or password be sure to escape them!`); outputOriginalErrorAndExit(logger, error); } } } // unknown error :( outputOriginalErrorAndExit(logger, error); } exports.prettyError = prettyError; /***/ }), /***/ 8347: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.deploy = exports.excludeDefaults = void 0; const ftp = __importStar(__webpack_require__(7957)); const readdir_enhanced_1 = __importDefault(__webpack_require__(8811)); const crypto_1 = __importDefault(__webpack_require__(6417)); const fs_1 = __importDefault(__webpack_require__(5747)); const multiMatch_1 = __importDefault(__webpack_require__(4865)); const stream_1 = __webpack_require__(2413); const types_1 = __webpack_require__(6703); const HashDiff_1 = __webpack_require__(9946); const utilities_1 = __webpack_require__(4389); const pretty_bytes_1 = __importDefault(__webpack_require__(5168)); const errorHandling_1 = __webpack_require__(3678); /** * Default excludes, ignores all git files and the node_modules folder */ exports.excludeDefaults = [".git*", ".git*/**", "node_modules/**", "node_modules/**/*"]; function fileHash(filename, algorithm) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => { // Algorithm depends on availability of OpenSSL on platform // Another algorithms: "sha1", "md5", "sha256", "sha512" ... let shasum = crypto_1.default.createHash(algorithm); try { let s = fs_1.default.createReadStream(filename); s.on("data", function (data) { shasum.update(data); }); // making digest s.on("end", function () { const hash = shasum.digest("hex"); return resolve(hash); }); } catch (error) { return reject("calc fail"); } }); }); } // Excludes takes precedence over includes function includeExcludeFilter(stat, args) { // match exclude, return immediatley if (args.exclude !== null) { const exclude = multiMatch_1.default(stat.path, args.exclude, { matchBase: true, dot: true }); if (exclude.length > 0) { return false; } } if (args.include !== null) { // matches include - return immediatley const include = multiMatch_1.default(stat.path, args.include, { matchBase: true, dot: true }); if (include.length > 0) { return true; } } return true; } function getLocalFiles(args) { return __awaiter(this, void 0, void 0, function* () { const files = yield readdir_enhanced_1.default.async(args["local-dir"], { deep: true, stats: true, sep: "/", filter: (stat) => includeExcludeFilter(stat, args) }); const records = []; for (let stat of files) { if (stat.isDirectory()) { records.push({ type: "folder", name: stat.path, size: undefined }); continue; } if (stat.isFile()) { records.push({ type: "file", name: stat.path, size: stat.size, hash: yield fileHash(stat.path, "sha256") }); continue; } if (stat.isSymbolicLink()) { console.warn("Currently unable to handle symbolic links"); } } return { description: types_1.syncFileDescription, version: types_1.currentVersion, generatedTime: new Date().getTime(), data: records }; }); } function downloadFileList(client, path) { return __awaiter(this, void 0, void 0, function* () { return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { const downloadStream = new stream_1.Stream.Writable(); const chunks = []; downloadStream._write = (chunk, encoding, next) => { chunks.push(chunk); next(); }; downloadStream.on("error", reject); downloadStream.on("finish", () => { const file = Buffer.concat(chunks).toString("utf8"); try { resolve(JSON.parse(file)); } catch (e) { reject(e); } }); client.downloadTo(downloadStream, path).catch((reason) => { reject(`Can't open due to: "${reason}"`); }); })); }); } /** * Converts a file path (ex: "folder/otherfolder/file.txt") to an array of folder and a file path * @param fullPath */ function getFileBreadcrumbs(fullPath) { var _a; // todo see if this regex will work for nonstandard folder names // todo what happens if the path is relative to the root dir? (starts with /) const pathSplit = fullPath.split("/"); const file = (_a = pathSplit === null || pathSplit === void 0 ? void 0 : pathSplit.pop()) !== null && _a !== void 0 ? _a : ""; // get last item const folders = pathSplit.filter(folderName => folderName != ""); return { folders: folders.length === 0 ? null : folders, file: file === "" ? null : file }; } /** * Navigates up {dirCount} number of directories from the current working dir */ function upDir(client, dirCount) { return __awaiter(this, void 0, void 0, function* () { if (typeof dirCount !== "number") { return; } // navigate back to the starting folder for (let i = 0; i < dirCount; i++) { yield client.cdup(); } }); } function ensureDir(client, logger, timings, folder) { return __awaiter(this, void 0, void 0, function* () { timings.start("changingDir"); logger.debug(` changing dir to ${folder}`); yield client.ensureDir(folder); logger.debug(` dir changed`); timings.stop("changingDir"); }); } /** * * @param client ftp client * @param file file can include folder(s) * Note working dir is modified and NOT reset after upload * For now we are going to reset it - but this will be removed for performance */ function uploadFile(client, filePath, logger, timings, type = "upload") { return __awaiter(this, void 0, void 0, function* () { const typePresent = type === "upload" ? "uploading" : "replacing"; const typePast = type === "upload" ? "uploaded" : "replaced"; logger.all(`${typePresent} "${filePath}"`); yield client.uploadFrom(filePath, filePath); logger.debug(` file ${typePast}`); }); } function createFolder(client, folderPath, logger, timings) { var _a; return __awaiter(this, void 0, void 0, function* () { logger.all(`creating folder "${folderPath + "/"}"`); const path = getFileBreadcrumbs(folderPath + "/"); if (path.folders === null) { logger.debug(` no need to change dir`); } else { yield ensureDir(client, logger, timings, path.folders.join("/")); } // navigate back to the root folder yield upDir(client, (_a = path.folders) === null || _a === void 0 ? void 0 : _a.length); logger.debug(` completed`); }); } function removeFolder(client, folderPath, logger) { var _a; return __awaiter(this, void 0, void 0, function* () { logger.all(`removing folder "${folderPath + "/"}"`); const path = getFileBreadcrumbs(folderPath + "/"); if (path.folders === null) { logger.debug(` no need to change dir`); } else { try { logger.debug(` removing folder "${path.folders.join("/") + "/"}"`); yield client.removeDir(path.folders.join("/") + "/"); } catch (e) { let error = e; if (error.code === types_1.ErrorCode.FileNotFoundOrNoAccess) { logger.debug(` could not remove folder. It doesn't exist!`); } else { // unknown error throw error; } } } // navigate back to the root folder yield upDir(client, (_a = path.folders) === null || _a === void 0 ? void 0 : _a.length); logger.debug(` completed`); }); } function removeFile(client, filePath, logger) { return __awaiter(this, void 0, void 0, function* () { logger.all(`removing ${filePath}...`); try { yield client.remove(filePath); logger.debug(` file removed`); } catch (e) { let error = e; if (error.code === types_1.ErrorCode.FileNotFoundOrNoAccess) { logger.info(` could not remove file. It doesn't exist!`); } else { // unknown error throw error; } } logger.debug(` completed`); }); } function createLocalState(localFiles, logger, args) { logger.debug(`Creating local state at ${args["local-dir"]}${args["state-name"]}`); fs_1.default.writeFileSync(`${args["local-dir"]}${args["state-name"]}`, JSON.stringify(localFiles, undefined, 4), { encoding: "utf8" }); logger.debug("Local state created"); } function connect(client, args) { return __awaiter(this, void 0, void 0, function* () { let secure = false; if (args.protocol === "ftps") { secure = true; } else if (args.protocol === "ftps-legacy") { secure = "implicit"; } const rejectUnauthorized = args.security === "loose"; yield client.access({ host: args.server, user: args.username, password: args.password, port: args.port, secure: secure, secureOptions: { rejectUnauthorized: rejectUnauthorized } }); }); } function getServerFiles(client, logger, timings, args) { return __awaiter(this, void 0, void 0, function* () { try { yield ensureDir(client, logger, timings, args["server-dir"]); if (args["dangerous-clean-slate"]) { logger.all(`----------------------------------------------------------------`); logger.all("๐๏ธ Removing all files on the server because 'dangerous-clean-slate' was set, this will make the deployment very slow..."); yield client.clearWorkingDir(); logger.all("Clear complete"); throw new Error("nope"); } const serverFiles = yield downloadFileList(client, args["state-name"]); logger.all(`----------------------------------------------------------------`); logger.all(`Last published on ๐ ${new Date(serverFiles.generatedTime).toLocaleDateString(undefined, { weekday: "long", year: "numeric", month: "long", day: "numeric", hour: "numeric", minute: "numeric" })}`); return serverFiles; } catch (e) { logger.all(`----------------------------------------------------------------`); logger.all(`No file exists on the server "${args["server-dir"] + args["state-name"]}" - this much be your first publish! ๐`); logger.all(`The first publish will take a while... but once the initial sync is done only differences are published!`); logger.all(`If you get this message and its NOT your first publish, something is wrong.`); // set the server state to nothing, because we don't know what the server state is return { description: types_1.syncFileDescription, version: types_1.currentVersion, generatedTime: new Date().getTime(), data: [], }; } }); } function getDefaultSettings(withoutDefaults) { var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l; if (withoutDefaults["local-dir"] !== undefined) { if (!withoutDefaults["local-dir"].endsWith("/")) { throw new Error("local-dir should be a folder (must end with /)"); } } if (withoutDefaults["server-dir"] !== undefined) { if (!withoutDefaults["server-dir"].endsWith("/")) { throw new Error("server-dir should be a folder (must end with /)"); } } return { "server": withoutDefaults.server, "username": withoutDefaults.username, "password": withoutDefaults.password, "port": (_a = withoutDefaults.port) !== null && _a !== void 0 ? _a : 21, "protocol": (_b = withoutDefaults.protocol) !== null && _b !== void 0 ? _b : "ftp", "local-dir": (_c = withoutDefaults["local-dir"]) !== null && _c !== void 0 ? _c : "./", "server-dir": (_d = withoutDefaults["server-dir"]) !== null && _d !== void 0 ? _d : "./", "state-name": (_e = withoutDefaults["state-name"]) !== null && _e !== void 0 ? _e : ".ftp-deploy-sync-state.json", "dry-run": (_f = withoutDefaults["dry-run"]) !== null && _f !== void 0 ? _f : false, "dangerous-clean-slate": (_g = withoutDefaults["dangerous-clean-slate"]) !== null && _g !== void 0 ? _g : false, "include": (_h = withoutDefaults.include) !== null && _h !== void 0 ? _h : [], "exclude": (_j = withoutDefaults.exclude) !== null && _j !== void 0 ? _j : exports.excludeDefaults, "log-level": (_k = withoutDefaults["log-level"]) !== null && _k !== void 0 ? _k : "info", "security": (_l = withoutDefaults.security) !== null && _l !== void 0 ? _l : "loose", }; } function syncLocalToServer(client, diffs, logger, timings, args) { return __awaiter(this, void 0, void 0, function* () { const totalCount = diffs.delete.length + diffs.upload.length + diffs.replace.length; logger.all(`----------------------------------------------------------------`); logger.all(`Making changes to ${totalCount} ${utilities_1.pluralize(totalCount, "file", "files")} to sync server state`); logger.all(`Uploading: ${pretty_bytes_1.default(diffs.sizeUpload)} -- Deleting: ${pretty_bytes_1.default(diffs.sizeDelete)} -- Replacing: ${pretty_bytes_1.default(diffs.sizeReplace)}`); logger.all(`----------------------------------------------------------------`); // create new folders for (const file of diffs.upload.filter(item => item.type === "folder")) { yield createFolder(client, file.name, logger, timings); } // upload new files for (const file of diffs.upload.filter(item => item.type === "file").filter(item => item.name !== args["state-name"])) { yield uploadFile(client, file.name, logger, timings); } // replace new files for (const file of diffs.replace.filter(item => item.type === "file").filter(item => item.name !== args["state-name"])) { // note: FTP will replace old files with new files. We run replacements after uploads to limit downtime yield uploadFile(client, file.name, logger, timings, "replace"); } // delete old files for (const file of diffs.delete.filter(item => item.type === "file")) { yield removeFile(client, file.name, logger); } // delete old folders for (const file of diffs.delete.filter(item => item.type === "folder")) { yield removeFolder(client, file.name, logger); } logger.all(`----------------------------------------------------------------`); logger.all(`๐ Sync complete. Saving current server state to "${args["server-dir"] + args["state-name"]}"`); yield client.uploadFrom(args["state-name"], args["state-name"]); }); } function deploy(deployArgs) { return __awaiter(this, void 0, void 0, function* () { const args = getDefaultSettings(deployArgs); const logger = new utilities_1.Logger(args["log-level"]); const timings = new utilities_1.Timings(); timings.start("total"); // header // todo allow swapping out library/version text based on if we are using action logger.all(`----------------------------------------------------------------`); logger.all(`๐ Thanks for using ftp-deploy version ${types_1.currentVersion}. Let's deploy some stuff! `); logger.all(`----------------------------------------------------------------`); logger.all(`If you found this project helpful, please support it`); logger.all(`by giving it a โญ on Github --> https://github.com/SamKirkland/FTP-Deploy-Action`); logger.all(`or add a badge ๐ท๏ธ to your projects readme --> https://github.com/SamKirkland/FTP-Deploy-Action#badge`); timings.start("hash"); const localFiles = yield getLocalFiles(args); timings.stop("hash"); createLocalState(localFiles, logger, args); const client = new ftp.Client(); client.ftp.verbose = args["log-level"] === "debug"; let totalBytesUploaded = 0; try { timings.start("connecting"); yield connect(client, args); timings.stop("connecting"); try { const serverFiles = yield getServerFiles(client, logger, timings, args); const diffTool = new HashDiff_1.HashDiff(); const diffs = diffTool.getDiffs(localFiles, serverFiles, logger); totalBytesUploaded = diffs.sizeUpload + diffs.sizeReplace; timings.start("upload"); try { yield syncLocalToServer(client, diffs, logger, timings, args); } catch (e) { if (e.code === types_1.ErrorCode.FileNameNotAllowed) { logger.warn("Error 553 FileNameNotAllowed, you don't have access to upload that file"); logger.warn(e); process.exit(); } logger.warn(e); process.exit(); } finally { timings.stop("upload"); } } catch (error) { const ftpError = error; if (ftpError.code === types_1.ErrorCode.FileNotFoundOrNoAccess) { logger.warn("Couldn't find file"); } logger.warn(ftpError); } } catch (error) { errorHandling_1.prettyError(logger, args, error); } finally { client.close(); timings.stop("total"); } const uploadSpeed = pretty_bytes_1.default(totalBytesUploaded / (timings.getTime("upload") / 1000)); // footer logger.all(`----------------------------------------------------------------`); logger.all(`Time spent hashing: ${timings.getTimeFormatted("hash")}`); logger.all(`Time spent connecting to server: ${timings.getTimeFormatted("connecting")}`); logger.all(`Time spent deploying: ${timings.getTimeFormatted("upload")} (${uploadSpeed}/second)`); logger.all(` - changing dirs: ${timings.getTimeFormatted("changingDir")}`); logger.all(`----------------------------------------------------------------`); logger.all(`Total time: ${timings.getTimeFormatted("total")}`); logger.all(`----------------------------------------------------------------`); }); } exports.deploy = deploy; /***/ }), /***/ 6703: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ErrorCode = exports.syncFileDescription = exports.currentVersion = void 0; exports.currentVersion = "1.0.0"; exports.syncFileDescription = "DO NOT DELETE THIS FILE. This file is used to keep track of which files have been synced in the most recent deployment. If you delete this file a resync will need to be done (which can take a while) - read more: https://github.com/SamKirkland/FTP-Deploy-Action"; var ErrorCode; (function (ErrorCode) { // The requested action is being initiated, expect another reply before proceeding with a new command. ErrorCode[ErrorCode["RestartMarkerReplay"] = 110] = "RestartMarkerReplay"; ErrorCode[ErrorCode["ServiceReadyInNNNMinutes"] = 120] = "ServiceReadyInNNNMinutes"; ErrorCode[ErrorCode["DataConnectionAlreadyOpenStartingTransfer"] = 125] = "DataConnectionAlreadyOpenStartingTransfer"; ErrorCode[ErrorCode["FileStatusOkayOpeningDataConnection"] = 150] = "FileStatusOkayOpeningDataConnection"; // The requested action has been successfully completed. ErrorCode[ErrorCode["CommandNotImplemented"] = 202] = "CommandNotImplemented"; ErrorCode[ErrorCode["SystemStatus"] = 211] = "SystemStatus"; ErrorCode[ErrorCode["DirectoryStatus"] = 212] = "DirectoryStatus"; ErrorCode[ErrorCode["FileStatus"] = 213] = "FileStatus"; ErrorCode[ErrorCode["HelpMessage"] = 214] = "HelpMessage"; ErrorCode[ErrorCode["IANAOfficialName"] = 215] = "IANAOfficialName"; ErrorCode[ErrorCode["ReadyForNewUser"] = 220] = "ReadyForNewUser"; ErrorCode[ErrorCode["ClosingControlConnection"] = 221] = "ClosingControlConnection"; ErrorCode[ErrorCode["DataConnectionOpen"] = 225] = "DataConnectionOpen"; ErrorCode[ErrorCode["SuccessNowClosingDataConnection"] = 226] = "SuccessNowClosingDataConnection"; ErrorCode[ErrorCode["EnteringPassiveMode"] = 227] = "EnteringPassiveMode"; ErrorCode[ErrorCode["EnteringLongPassiveMode"] = 228] = "EnteringLongPassiveMode"; ErrorCode[ErrorCode["EnteringExtendedPassiveMode"] = 229] = "EnteringExtendedPassiveMode"; ErrorCode[ErrorCode["UserLoggedIn"] = 230] = "UserLoggedIn"; ErrorCode[ErrorCode["UserLoggedOut"] = 231] = "UserLoggedOut"; ErrorCode[ErrorCode["LogoutWillCompleteWhenTransferDone"] = 232] = "LogoutWillCompleteWhenTransferDone"; ErrorCode[ErrorCode["ServerAcceptsAuthenticationMethod"] = 234] = "ServerAcceptsAuthenticationMethod"; ErrorCode[ErrorCode["ActionComplete"] = 250] = "ActionComplete"; ErrorCode[ErrorCode["PathNameCreated"] = 257] = "PathNameCreated"; // The command has been accepted, but the requested action is on hold, pending receipt of further information. ErrorCode[ErrorCode["UsernameOkayPasswordNeeded"] = 331] = "UsernameOkayPasswordNeeded"; ErrorCode[ErrorCode["NeedAccountForLogin"] = 332] = "NeedAccountForLogin"; ErrorCode[ErrorCode["RequestedFileActionPendingFurtherInformation"] = 350] = "RequestedFileActionPendingFurtherInformation"; // The command was not accepted and the requested action did not take place, but the error condition is temporary and the action may be requested again. ErrorCode[ErrorCode["ServiceNotAvailable"] = 421] = "ServiceNotAvailable"; ErrorCode[ErrorCode["CantOpenDataConnection"] = 425] = "CantOpenDataConnection"; ErrorCode[ErrorCode["ConnectionClosed"] = 426] = "ConnectionClosed"; ErrorCode[ErrorCode["InvalidUsernameOrPassword"] = 430] = "InvalidUsernameOrPassword"; ErrorCode[ErrorCode["HostUnavailable"] = 434] = "HostUnavailable"; ErrorCode[ErrorCode["FileActionNotTaken"] = 450] = "FileActionNotTaken"; ErrorCode[ErrorCode["LocalErrorProcessing"] = 451] = "LocalErrorProcessing"; ErrorCode[ErrorCode["InsufficientStorageSpaceOrFileInUse"] = 452] = "InsufficientStorageSpaceOrFileInUse"; // Syntax error, command unrecognized and the requested action did not take place. This may include errors such as command line too long. ErrorCode[ErrorCode["SyntaxErrorInParameters"] = 501] = "SyntaxErrorInParameters"; ErrorCode[ErrorCode["CommandNotImpemented"] = 502] = "CommandNotImpemented"; ErrorCode[ErrorCode["BadSequenceOfCommands"] = 503] = "BadSequenceOfCommands"; ErrorCode[ErrorCode["CommandNotImplementedForThatParameter"] = 504] = "CommandNotImplementedForThatParameter"; ErrorCode[ErrorCode["NotLoggedIn"] = 530] = "NotLoggedIn"; ErrorCode[ErrorCode["NeedAccountForStoringFiles"] = 532] = "NeedAccountForStoringFiles"; ErrorCode[ErrorCode["CouldNotConnectToServerRequiresSSL"] = 534] = "CouldNotConnectToServerRequiresSSL"; ErrorCode[ErrorCode["FileNotFoundOrNoAccess"] = 550] = "FileNotFoundOrNoAccess"; ErrorCode[ErrorCode["UnknownPageType"] = 551] = "UnknownPageType"; ErrorCode[ErrorCode["ExceededStorageAllocation"] = 552] = "ExceededStorageAllocation"; ErrorCode[ErrorCode["FileNameNotAllowed"] = 553] = "FileNameNotAllowed"; // Replies regarding confidentiality and integrity ErrorCode[ErrorCode["IntegrityProtectedReply"] = 631] = "IntegrityProtectedReply"; ErrorCode[ErrorCode["ConfidentialityAndIntegrityProtectedReply"] = 632] = "ConfidentialityAndIntegrityProtectedReply"; ErrorCode[ErrorCode["ConfidentialityProtectedReply"] = 633] = "ConfidentialityProtectedReply"; // Common Winsock Error Codes[2] (These are not FTP return codes) ErrorCode[ErrorCode["ConnectionClosedByServer"] = 10054] = "ConnectionClosedByServer"; ErrorCode[ErrorCode["CannotConnect"] = 10060] = "CannotConnect"; ErrorCode[ErrorCode["CannotConnectRefusedByServer"] = 10061] = "CannotConnectRefusedByServer"; ErrorCode[ErrorCode["DirectoryNotEmpty"] = 10066] = "DirectoryNotEmpty"; ErrorCode[ErrorCode["TooManyUsers"] = 10068] = "TooManyUsers"; })(ErrorCode = exports.ErrorCode || (exports.ErrorCode = {})); ; /***/ }), /***/ 4389: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Timer = exports.Timings = exports.pluralize = exports.Logger = void 0; const pretty_ms_1 = __importDefault(__webpack_require__(1127)); class Logger { constructor(level) { this.level = level !== null && level !== void 0 ? level : "info"; } all(...data) { console.log(...data); } warn(...data) { if (this.level === "debug") { return; } console.log(...data); } info(...data) { if (this.level === "warn") { return; } console.log(...data); } debug(...data) { if (this.level !== "debug") { return; } console.log(...data); } } exports.Logger = Logger; function pluralize(count, singular, plural) { if (count === 1) { return singular; } return plural; } exports.pluralize = pluralize; class Timings { constructor() { this.timers = {}; } start(type) { if (this.timers[type] === undefined) { this.timers[type] = new Timer(); } this.timers[type].start(); } stop(type) { this.timers[type].stop(); } getTime(type) { const timer = this.timers[type]; if (timer === undefined || timer.time === null) { return 0; } return timer.time; } getTimeFormatted(type) { const timer = this.timers[type]; if (timer === undefined || timer.time === null) { return "๐ฃ Failed"; } return pretty_ms_1.default(timer.time, { verbose: true }); } } exports.Timings = Timings; class Timer { constructor() { this.totalTime = null; this.startTime = null; this.endTime = null; } start() { this.startTime = process.hrtime(); } stop() { if (this.startTime === null) { throw new Error("Called .stop() before calling .start()"); } this.endTime = process.hrtime(this.startTime); const currentSeconds = this.totalTime === null ? 0 : this.totalTime[0]; const currentNS = this.totalTime === null ? 0 : this.totalTime[1]; this.totalTime = [ currentSeconds + this.endTime[0], currentNS + this.endTime[1] ]; } get time() { if (this.totalTime === null) { return null; } return (this.totalTime[0] * 1000) + (this.totalTime[1] / 1000000); } } exports.Timer = Timer; /***/ }), /***/ 6554: /***/ ((module) => { "use strict"; const arrayDiffer = (array, ...values) => { const rest = new Set([].concat(...values)); return array.filter(element => !rest.has(element)); }; module.exports = arrayDiffer; /***/ }), /***/ 9600: /***/ ((module) => { "use strict"; module.exports = (...arguments_) => { return [...new Set([].concat(...arguments_))]; }; /***/ }), /***/ 1546: /***/ ((module) => { "use strict"; const arrify = value => { if (value === null || value === undefined) { return []; } if (Array.isArray(value)) { return value; } if (typeof value === 'string') { return [value]; } if (typeof value[Symbol.iterator] === 'function') { return [...value]; } return [value]; }; module.exports = arrify; /***/ }), /***/ 9417: /***/ ((module) => { "use strict"; module.exports = balanced; function balanced(a, b, str) { if (a instanceof RegExp) a = maybeMatch(a, str); if (b instanceof RegExp) b = maybeMatch(b, str); var r = range(a, b, str); return r && { start: r[0], end: r[1], pre: str.slice(0, r[0]), body: str.slice(r[0] + a.length, r[1]), post: str.slice(r[1] + b.length) }; } function maybeMatch(reg, str) { var m = str.match(reg); return m ? m[0] : null; } balanced.range = range; function range(a, b, str) { var begs, beg, left, right, result; var ai = str.indexOf(a); var bi = str.indexOf(b, ai + 1); var i = ai; if (ai >= 0 && bi > 0) { begs = []; left = str.length; while (i >= 0 && !result) { if (i == ai) { begs.push(i); ai = str.indexOf(a, i + 1); } else if (begs.length == 1) { result = [ begs.pop(), bi ]; } else { beg = begs.pop(); if (beg < left) { left = beg; right = bi; } bi = str.indexOf(b, i + 1); } i = ai < bi && ai >= 0 ? ai : bi; } if (begs.length) { result = [ left, right ]; } } return result; } /***/ }), /***/ 8337: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.Client = void 0; const fs_1 = __webpack_require__(5747); const path_1 = __webpack_require__(5622); const tls_1 = __webpack_require__(4016); const util_1 = __webpack_require__(1669); const FtpContext_1 = __webpack_require__(9052); const parseList_1 = __webpack_require__(2993); const ProgressTracker_1 = __webpack_require__(7170); const StringWriter_1 = __webpack_require__(8184); const parseListMLSD_1 = __webpack_require__(8157); const netUtils_1 = __webpack_require__(6288); const transfer_1 = __webpack_require__(5803); const parseControlResponse_1 = __webpack_require__(9948); // Use promisify to keep the library compatible with Node 8. const fsReadDir = util_1.promisify(fs_1.readdir); const fsMkDir = util_1.promisify(fs_1.mkdir); const fsStat = util_1.promisify(fs_1.stat); const fsOpen = util_1.promisify(fs_1.open); const fsClose = util_1.promisify(fs_1.close); const fsUnlink = util_1.promisify(fs_1.unlink); /** * High-level API to interact with an FTP server. */ class Client { /** * Instantiate an FTP client. * * @param timeout Timeout in milliseconds, use 0 for no timeout. Optional, default is 30 seconds. */ constructor(timeout = 30000) { /** * Multiple commands to retrieve a directory listing are possible. This instance * will try all of them in the order presented the first time a directory listing * is requested. After that, `availableListCommands` will hold only the first * entry that worked. */ this.availableListCommands = ["MLSD", "LIST -a", "LIST"]; this.ftp = new FtpContext_1.FTPContext(timeout); this.prepareTransfer = this._enterFirstCompatibleMode([transfer_1.enterPassiveModeIPv6, transfer_1.enterPassiveModeIPv4]); this.parseList = parseList_1.parseList; this._progressTracker = new ProgressTracker_1.ProgressTracker(); } /** * Close the client and all open socket connections. * * Close the client and all open socket connections. The client canโt be used anymore after calling this method, * you have to either reconnect with `access` or `connect` or instantiate a new instance to continue any work. * A client is also closed automatically if any timeout or connection error occurs. */ close() { this.ftp.close(); this._progressTracker.stop(); } /** * Returns true if the client is closed and can't be used anymore. */ get closed() { return this.ftp.closed; } /** * Connect (or reconnect) to an FTP server. * * This is an instance method and thus can be called multiple times during the lifecycle of a `Client` * instance. Whenever you do, the client is reset with a new control connection. This also implies that * you can reopen a `Client` instance that has been closed due to an error when reconnecting with this * method. In fact, reconnecting is the only way to continue using a closed `Client`. * * @param host Host the client should connect to. Optional, default is "localhost". * @param port Port the client should connect to. Optional, default is 21. */ connect(host = "localhost", port = 21) { this.ftp.reset(); this.ftp.socket.connect({ host, port, family: this.ftp.ipFamily }, () => this.ftp.log(`Connected to ${netUtils_1.describeAddress(this.ftp.socket)} (${netUtils_1.describeTLS(this.ftp.socket)})`)); return this._handleConnectResponse(); } /** * As `connect` but using implicit TLS. Implicit TLS is not an FTP standard and has been replaced by * explicit TLS. There are still FTP servers that support only implicit TLS, though. */ connectImplicitTLS(host = "localhost", port = 21, tlsOptions = {}) { this.ftp.reset(); this.ftp.socket = tls_1.connect(port, host, tlsOptions, () => this.ftp.log(`Connected to ${netUtils_1.describeAddress(this.ftp.socket)} (${netUtils_1.describeTLS(this.ftp.socket)})`)); this.ftp.tlsOptions = tlsOptions; return this._handleConnectResponse(); } /** * Handles the first reponse by an FTP server after the socket connection has been established. */ _handleConnectResponse() { return this.ftp.handle(undefined, (res, task) => { if (res instanceof Error) { // The connection has been destroyed by the FTPContext at this point. task.reject(res); } else if (parseControlResponse_1.positiveCompletion(res.code)) { task.resolve(res); } // Reject all other codes, including 120 "Service ready in nnn minutes". else { // Don't stay connected but don't replace the socket yet by using reset() // so the user can inspect properties of this instance. this.ftp.socket.destroy(); task.reject(new FtpContext_1.FTPError(res)); } }); } /** * Send an FTP command and handle the first response. */ send(command, ignoreErrorCodesDEPRECATED = false) { if (ignoreErrorCodesDEPRECATED) { // Deprecated starting from 3.9.0 this.ftp.log("Deprecated call using send(command, flag) with boolean flag to ignore errors. Use sendIgnoringError(command)."); return this.sendIgnoringError(command); } return this.ftp.request(command); } /** * Send an FTP command and ignore an FTP error response. Any other kind of error or timeout will still reject the Promise. * * @param command */ sendIgnoringError(command) { return this.ftp.handle(command, (res, task) => { if (res instanceof FtpContext_1.FTPError) { task.resolve({ code: res.code, message: res.message }); } else if (res instanceof Error) { task.reject(res); } else { task.resolve(res); } }); } /** * Upgrade the current socket connection to TLS. * * @param options TLS options as in `tls.connect(options)`, optional. * @param command Set the authentication command. Optional, default is "AUTH TLS". */ async useTLS(options = {}, command = "AUTH TLS") { const ret = await this.send(command); this.ftp.socket = await netUtils_1.upgradeSocket(this.ftp.socket, options); this.ftp.tlsOptions = options; // Keep the TLS options for later data connections that should use the same options. this.ftp.log(`Control socket is using: ${netUtils_1.describeTLS(this.ftp.socket)}`); return ret; } /** * Login a user with a password. * * @param user Username to use for login. Optional, default is "anonymous". * @param password Password to use for login. Optional, default is "guest". */ login(user = "anonymous", password = "guest") { this.ftp.log(`Login security: ${netUtils_1.describeTLS(this.ftp.socket)}`); return this.ftp.handle("USER " + user, (res, task) => { if (res instanceof Error) { task.reject(res); } else if (parseControlResponse_1.positiveCompletion(res.code)) { // User logged in proceed OR Command superfluous task.resolve(res); } else if (res.code === 331) { // User name okay, need password this.ftp.send("PASS " + password); } else { // Also report error on 332 (Need account) task.reject(new FtpContext_1.FTPError(res)); } }); } /** * Set the usual default settings. * * Settings used: * * Binary mode (TYPE I) * * File structure (STRU F) * * Additional settings for FTPS (PBSZ 0, PROT P) */ async useDefaultSettings() { await this.send("TYPE I"); // Binary mode await this.sendIgnoringError("STRU F"); // Use file structure await this.sendIgnoringError("OPTS UTF8 ON"); // Some servers expect UTF-8 to be enabled explicitly await this.sendIgnoringError("OPTS MLST type;size;modify;unique;unix.mode;unix.owner;unix.group;unix.ownername;unix.groupname;"); // Make sure MLSD listings include all we can parse if (this.ftp.hasTLS) { await this.sendIgnoringError("PBSZ 0"); // Set to 0 for TLS await this.sendIgnoringError("PROT P"); // Protect channel (also for data connections) } } /** * Convenience method that calls `connect`, `useTLS`, `login` and `useDefaultSettings`. * * This is an instance method and thus can be called multiple times during the lifecycle of a `Client` * instance. Whenever you do, the client is reset with a new control connection. This also implies that * you can reopen a `Client` instance that has been closed due to an error when reconnecting with this * method. In fact, reconnecting is the only way to continue using a closed `Client`. */ async access(options = {}) { const useExplicitTLS = options.secure === true; const useImplicitTLS = options.secure === "implicit"; let welcome; if (useImplicitTLS) { welcome = await this.connectImplicitTLS(options.host, options.port, options.secureOptions); } else { welcome = await this.connect(options.host, options.port); } if (useExplicitTLS) { await this.useTLS(options.secureOptions); } await this.login(options.user, options.password); await this.useDefaultSettings(); return welcome; } /** * Get the current working directory. */ async pwd() { const res = await this.send("PWD"); // The directory is part of the return message, for example: // 257 "/this/that" is current directory. const parsed = res.message.match(/"(.+)"/); if (parsed === null || parsed[1] === undefined) { throw new Error(`Can't parse response to command 'PWD': ${res.message}`); } return parsed[1]; } /** * Get a description of supported features. * * This sends the FEAT command and parses the result into a Map where keys correspond to available commands * and values hold further information. Be aware that your FTP servers might not support this * command in which case this method will not throw an exception but just return an empty Map. */ async features() { const res = await this.sendIgnoringError("FEAT"); const features = new Map(); // Not supporting any special features will be reported with a single line. if (res.code < 400 && parseControlResponse_1.isMultiline(res.message)) { // The first and last line wrap the multiline response, ignore them. res.message.split("\n").slice(1, -1).forEach(line => { // A typical lines looks like: " REST STREAM" or " MDTM". // Servers might not use an indentation though. const entry = line.trim().split(" "); features.set(entry[0], entry[1] || ""); }); } return features; } /** * Set the working directory. */ async cd(path) { const validPath = await this.protectWhitespace(path); return this.send("CWD " + validPath); } /** * Switch to the parent directory of the working directory. */ async cdup() { return this.send("CDUP"); } /** * Get the last modified time of a file. This is not supported by every FTP server, in which case * calling this method will throw an exception. */ async lastMod(path) { const validPath = await this.protectWhitespace(path); const res = await this.send(`MDTM ${validPath}`); const date = res.message.slice(4); return parseListMLSD_1.parseMLSxDate(date); } /** * Get the size of a file. */ async size(path) { const validPath = await this.protectWhitespace(path); const command = `SIZE ${validPath}`; const res = await this.send(command); // The size is part of the response message, for example: "213 555555". It's // possible that there is a commmentary appended like "213 5555, some commentary". const size = parseInt(res.message.slice(4), 10); if (Number.isNaN(size)) { throw new Error(`Can't parse response to command '${command}' as a numerical value: ${res.message}`); } return size; } /** * Rename a file. * * Depending on the FTP server this might also be used to move a file from one * directory to another by providing full paths. */ async rename(srcPath, destPath) { const validSrc = await this.protectWhitespace(srcPath); const validDest = await this.protectWhitespace(destPath); await this.send("RNFR " + validSrc); return this.send("RNTO " + validDest); } /** * Remove a file from the current working directory. * * You can ignore FTP error return codes which won't throw an exception if e.g. * the file doesn't exist. */ async remove(path, ignoreErrorCodes = false) { const validPath = await this.protectWhitespace(path); return this.send(`DELE ${validPath}`, ignoreErrorCodes); } /** * Report transfer progress for any upload or download to a given handler. * * This will also reset the overall transfer counter that can be used for multiple transfers. You can * also call the function without a handler to stop reporting to an earlier one. * * @param handler Handler function to call on transfer progress. */ trackProgress(handler) { this._progressTracker.bytesOverall = 0; this._progressTracker.reportTo(handler); } /** * Upload data from a readable stream or a local file to a remote file. * * @param source Readable stream or path to a local file. * @param toRemotePath Path to a remote file to write to. */ async uploadFrom(source, toRemotePath, options = {}) { return this._uploadWithCommand(source, toRemotePath, "STOR", options); } /** * Upload data from a readable stream or a local file by appending it to an existing file. If the file doesn't * exist the FTP server should create it. * * @param source Readable stream or path to a local file. * @param toRemotePath Path to a remote file to write to. */ async appendFrom(source, toRemotePath, options = {}) { return this._uploadWithCommand(source, toRemotePath, "APPE", options); } /** * @protected */ async _uploadWithCommand(source, remotePath, command, options) { if (typeof source === "string") { return this._uploadLocalFile(source, remotePath, command, options); } return this._uploadFromStream(source, remotePath, command); } /** * @protected */ async _uploadLocalFile(localPath, remotePath, command, options) { const fd = await fsOpen(localPath, "r"); const source = fs_1.createReadStream("", { fd, start: options.localStart, end: options.localEndInclusive, autoClose: false }); try { return await this._uploadFromStream(source, remotePath, command); } finally { await ignoreError(() => fsClose(fd)); } } /** * @protected */ async _uploadFromStream(source, remotePath, command) { const onError = (err) => this.ftp.closeWithError(err); source.once("error", onError); try { const validPath = await this.protectWhitespace(remotePath); await this.prepareTransfer(this.ftp); // Keep the keyword `await` or the `finally` clause below runs too early // and removes the event listener for the source stream too early. return await transfer_1.uploadFrom(source, { ftp: this.ftp, tracker: this._progressTracker, command, remotePath: validPath, type: "upload" }); } finally { source.removeListener("error", onError); } } /** * Download a remote file and pipe its data to a writable stream or to a local file. * * You can optionally define at which position of the remote file you'd like to start * downloading. If the destination you provide is a file, the offset will be applied * to it as well. For example: To resume a failed download, you'd request the size of * the local, partially downloaded file and use that as the offset. Assuming the size * is 23, you'd download the rest using `downloadTo("local.txt", "remote.txt", 23)`. * * @param destination Stream or path for a local file to write to. * @param fromRemotePath Path of the remote file to read from. * @param startAt Position within the remote file to start downloading at. If the destination is a file, this offset is also applied to it. */ async downloadTo(destination, fromRemotePath, startAt = 0) { if (typeof destination === "string") { return this._downloadToFile(destination, fromRemotePath, startAt); } return this._downloadToStream(destination, fromRemotePath, startAt); } /** * @protected */ async _downloadToFile(localPath, remotePath, startAt) { const appendingToLocalFile = startAt > 0; const fileSystemFlags = appendingToLocalFile ? "r+" : "w"; const fd = await fsOpen(localPath, fileSystemFlags); const destination = fs_1.createWriteStream("", { fd, start: startAt, autoClose: false }); try { return await this._downloadToStream(destination, remotePath, startAt); } catch (err) { const localFileStats = await ignoreError(() => fsStat(localPath)); const hasDownloadedData = localFileStats && localFileStats.size > 0; const shouldRemoveLocalFile = !appendingToLocalFile && !hasDownloadedData; if (shouldRemoveLocalFile) { await ignoreError(() => fsUnlink(localPath)); } throw err; } finally { await ignoreError(() => fsClose(fd)); } } /** * @protected */ async _downloadToStream(destination, remotePath, startAt) { const onError = (err) => this.ftp.closeWithError(err); destination.once("error", onError); try { const validPath = await this.protectWhitespace(remotePath); await this.prepareTransfer(this.ftp); // Keep the keyword `await` or the `finally` clause below runs too early // and removes the event listener for the source stream too early. return await transfer_1.downloadTo(destination, { ftp: this.ftp, tracker: this._progressTracker, command: startAt > 0 ? `REST ${startAt}` : `RETR ${validPath}`, remotePath: validPath, type: "download" }); } finally { destination.removeListener("error", onError); destination.end(); } } /** * List files and directories in the current working directory, or from `path` if specified. * * @param [path] Path to remote file or directory. */ async list(path = "") { const validPath = await this.protectWhitespace(path); let lastError; for (const candidate of this.availableListCommands) { const command = validPath === "" ? candidate : `${candidate} ${validPath}`; await this.prepareTransfer(this.ftp); try { const parsedList = await this._requestListWithCommand(command); // Use successful candidate for all subsequent requests. this.availableListCommands = [candidate]; return parsedList; } catch (err) { const shouldTryNext = err instanceof FtpContext_1.FTPError; if (!shouldTryNext) { throw err; } lastError = err; } } throw lastError; } /** * @protected */ async _requestListWithCommand(command) { const buffer = new StringWriter_1.StringWriter(); await transfer_1.downloadTo(buffer, { ftp: this.ftp, tracker: this._progressTracker, command, remotePath: "", type: "list" }); const text = buffer.getText(this.ftp.encoding); this.ftp.log(text); return this.parseList(text); } /** * Remove a directory and all of its content. * * @param remoteDirPath The path of the remote directory to delete. * @example client.removeDir("foo") // Remove directory 'foo' using a relative path. * @example client.removeDir("foo/bar") // Remove directory 'bar' using a relative path. * @example client.removeDir("/foo/bar") // Remove directory 'bar' using an absolute path. * @example client.removeDir("/") // Remove everything. */ async removeDir(remoteDirPath) { return this._exitAtCurrentDirectory(async () => { await this.cd(remoteDirPath); await this.clearWorkingDir(); if (remoteDirPath !== "/") { await this.cdup(); await this.removeEmptyDir(remoteDirPath); } }); } /** * Remove all files and directories in the working directory without removing * the working directory itself. */ async clearWorkingDir() { for (const file of await this.list()) { if (file.isDirectory) { await this.cd(file.name); await this.clearWorkingDir(); await this.cdup(); await this.removeEmptyDir(file.name); } else { await this.remove(file.name); } } } /** * Upload the contents of a local directory to the remote working directory. * * This will overwrite existing files with the same names and reuse existing directories. * Unrelated files and directories will remain untouched. You can optionally provide a `remoteDirPath` * to put the contents inside a directory which will be created if necessary including all * intermediate directories. If you did provide a remoteDirPath the working directory will stay * the same as before calling this method. * * @param localDirPath Local path, e.g. "foo/bar" or "../test" * @param [remoteDirPath] Remote path of a directory to upload to. Working directory if undefined. */ async uploadFromDir(localDirPath, remoteDirPath) { return this._exitAtCurrentDirectory(async () => { if (remoteDirPath) { await this.ensureDir(remoteDirPath); } return await this._uploadToWorkingDir(localDirPath); }); } /** * @protected */ async _uploadToWorkingDir(localDirPath) { const files = await fsReadDir(localDirPath); for (const file of files) { const fullPath = path_1.join(localDirPath, file); const stats = await fsStat(fullPath); if (stats.isFile()) { await this.uploadFrom(fullPath, file); } else if (stats.isDirectory()) { await this._openDir(file); await this._uploadToWorkingDir(fullPath); await this.cdup(); } } } /** * Download all files and directories of the working directory to a local directory. * * @param localDirPath The local directory to download to. * @param remoteDirPath Remote directory to download. Current working directory if not specified. */ async downloadToDir(localDirPath, remoteDirPath) { return this._exitAtCurrentDirectory(async () => { if (remoteDirPath) { await this.cd(remoteDirPath); } return await this._downloadFromWorkingDir(localDirPath); }); } /** * @protected */ async _downloadFromWorkingDir(localDirPath) { await ensureLocalDirectory(localDirPath); for (const file of await this.list()) { const localPath = path_1.join(localDirPath, file.name); if (file.isDirectory) { await this.cd(file.name); await this._downloadFromWorkingDir(localPath); await this.cdup(); } else if (file.isFile) { await this.downloadTo(localPath, file.name); } } } /** * Make sure a given remote path exists, creating all directories as necessary. * This function also changes the current working directory to the given path. */ async ensureDir(remoteDirPath) { // If the remoteDirPath was absolute go to root directory. if (remoteDirPath.startsWith("/")) { await this.cd("/"); } const names = remoteDirPath.split("/").filter(name => name !== ""); for (const name of names) { await this._openDir(name); } } /** * Try to create a directory and enter it. This will not raise an exception if the directory * couldn't be created if for example it already exists. * @protected */ async _openDir(dirName) { await this.sendIgnoringError("MKD " + dirName); await this.cd(dirName); } /** * Remove an empty directory, will fail if not empty. */ async removeEmptyDir(path) { const validPath = await this.protectWhitespace(path); return this.send(`RMD ${validPath}`); } /** * FTP servers can't handle filenames that have leading whitespace. This method transforms * a given path to fix that issue for most cases. */ async protectWhitespace(path) { if (!path.startsWith(" ")) { return path; } // Handle leading whitespace by prepending the absolute path: // " test.txt" while being in the root directory becomes "/ test.txt". const pwd = await this.pwd(); const absolutePathPrefix = pwd.endsWith("/") ? pwd : pwd + "/"; return absolutePathPrefix + path; } async _exitAtCurrentDirectory(func) { const userDir = await this.pwd(); try { return await func(); } finally { if (!this.closed) { await ignoreError(() => this.cd(userDir)); } } } /** * Try all available transfer strategies and pick the first one that works. Update `client` to * use the working strategy for all successive transfer requests. * * @param strategies * @returns a function that will try the provided strategies. */ _enterFirstCompatibleMode(strategies) { return async (ftp) => { ftp.log("Trying to find optimal transfer strategy..."); for (const strategy of strategies) { try { const res = await strategy(ftp); ftp.log("Optimal transfer strategy found."); this.prepareTransfer = strategy; // eslint-disable-line require-atomic-updates return res; } catch (err) { // Receiving an FTPError means that the last transfer strategy failed and we should // try the next one. Any other exception should stop the evaluation of strategies because // something else went wrong. if (!(err instanceof FtpContext_1.FTPError)) { throw err; } } } throw new Error("None of the available transfer strategies work."); }; } /** * DEPRECATED, use `uploadFrom`. * @deprecated */ async upload(source, toRemotePath, options = {}) { this.ftp.log("Warning: upload() has been deprecated, use uploadFrom()."); return this.uploadFrom(source, toRemotePath, options); } /** * DEPRECATED, use `appendFrom`. * @deprecated */ async append(source, toRemotePath, options = {}) { this.ftp.log("Warning: append() has been deprecated, use appendFrom()."); return this.appendFrom(source, toRemotePath, options); } /** * DEPRECATED, use `downloadTo`. * @deprecated */ async download(destination, fromRemotePath, startAt = 0) { this.ftp.log("Warning: download() has been deprecated, use downloadTo()."); return this.downloadTo(destination, fromRemotePath, startAt); } /** * DEPRECATED, use `uploadFromDir`. * @deprecated */ async uploadDir(localDirPath, remoteDirPath) { this.ftp.log("Warning: uploadDir() has been deprecated, use uploadFromDir()."); return this.uploadFromDir(localDirPath, remoteDirPath); } /** * DEPRECATED, use `downloadToDir`. * @deprecated */ async downloadDir(localDirPath) { this.ftp.log("Warning: downloadDir() has been deprecated, use downloadToDir()."); return this.downloadToDir(localDirPath); } } exports.Client = Client; async function ensureLocalDirectory(path) { try { await fsStat(path); } catch (err) { await fsMkDir(path, { recursive: true }); } } async function ignoreError(func) { try { return await func(); } catch (err) { // Ignore return undefined; } } /***/ }), /***/ 202: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FileInfo = exports.FileType = void 0; var FileType; (function (FileType) { FileType[FileType["Unknown"] = 0] = "Unknown"; FileType[FileType["File"] = 1] = "File"; FileType[FileType["Directory"] = 2] = "Directory"; FileType[FileType["SymbolicLink"] = 3] = "SymbolicLink"; })(FileType = exports.FileType || (exports.FileType = {})); /** * Describes a file, directory or symbolic link. */ class FileInfo { constructor(name) { this.name = name; this.type = FileType.Unknown; this.size = 0; /** * Unparsed, raw modification date as a string. * * If `modifiedAt` is undefined, the FTP server you're connected to doesn't support the more modern * MLSD command for machine-readable directory listings. The older command LIST is then used returning * results that vary a lot between servers as the format hasn't been standardized. Here, directory listings * and especially modification dates were meant to be human-readable first. * * Be careful when still trying to parse this by yourself. Parsing dates from listings using LIST is * unreliable. This library decides to offer parsed dates only when they're absolutely reliable and safe to * use e.g. for comparisons. */ this.rawModifiedAt = ""; /** * Parsed modification date. * * Available if the FTP server supports the MLSD command. Only MLSD guarantees dates than can be reliably * parsed with the correct timezone and a resolution down to seconds. See `rawModifiedAt` property for the unparsed * date that is always available. */ this.modifiedAt = undefined; /** * Unix permissions if present. If the underlying FTP server is not running on Unix this will be undefined. * If set, you might be able to edit permissions with the FTP command `SITE CHMOD`. */ this.permissions = undefined; /** * Hard link count if available. */ this.hardLinkCount = undefined; /** * Link name for symbolic links if available. */ this.link = undefined; /** * Unix group if available. */ this.group = undefined; /** * Unix user if available. */ this.user = undefined; /** * Unique ID if available. */ this.uniqueID = undefined; this.name = name; } get isDirectory() { return this.type === FileType.Directory; } get isSymbolicLink() { return this.type === FileType.SymbolicLink; } get isFile() { return this.type === FileType.File; } /** * Deprecated, legacy API. Use `rawModifiedAt` instead. * @deprecated */ get date() { return this.rawModifiedAt; } set date(rawModifiedAt) { this.rawModifiedAt = rawModifiedAt; } } exports.FileInfo = FileInfo; FileInfo.UnixPermission = { Read: 4, Write: 2, Execute: 1 }; /***/ }), /***/ 9052: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.FTPContext = exports.FTPError = void 0; const net_1 = __webpack_require__(1631); const parseControlResponse_1 = __webpack_require__(9948); /** * Describes an FTP server error response including the FTP response code. */ class FTPError extends Error { constructor(res) { super(res.message); this.name = this.constructor.name; this.code = res.code; } } exports.FTPError = FTPError; /** * FTPContext holds the control and data sockets of an FTP connection and provides a * simplified way to interact with an FTP server, handle responses, errors and timeouts. * * It doesn't implement or use any FTP commands. It's only a foundation to make writing an FTP * client as easy as possible. You won't usually instantiate this, but use `Client`. */ class FTPContext { /** * Instantiate an FTP context. * * @param timeout - Timeout in milliseconds to apply to control and data connections. Use 0 for no timeout. * @param encoding - Encoding to use for control connection. UTF-8 by default. Use "latin1" for older servers. */ constructor(timeout = 0, encoding = "utf8") { this.timeout = timeout; /** Debug-level logging of all socket communication. */ this.verbose = false; /** IP version to prefer (4: IPv4, 6: IPv6, undefined: automatic). */ this.ipFamily = undefined; /** Options for TLS connections. */ this.tlsOptions = {}; /** A multiline response might be received as multiple chunks. */ this._partialResponse = ""; this._encoding = encoding; // Help Typescript understand that we do indeed set _socket in the constructor but use the setter method to do so. this._socket = this.socket = this._newSocket(); this._dataSocket = undefined; } /** * Close the context. */ close() { // Internally, closing a context is always described with an error. If there is still a task running, it will // abort with an exception that the user closed the client during a task. If no task is running, no exception is // thrown but all newly submitted tasks after that will abort the exception that the client has been closed. // In addition the user will get a stack trace pointing to where exactly the client has been closed. So in any // case use _closingError to determine whether a context is closed. This also allows us to have a single code-path // for closing a context making the implementation easier. const message = this._task ? "User closed client during task" : "User closed client"; const err = new Error(message); this.closeWithError(err); } /** * Close the context with an error. */ closeWithError(err) { // If this context already has been closed, don't overwrite the reason. if (this._closingError) { return; } this._closingError = err; // Before giving the user's task a chance to react, make sure we won't be bothered with any inputs. this._closeSocket(this._socket); this._closeSocket(this._dataSocket); // Give the user's task a chance to react, maybe cleanup resources. this._passToHandler(err); // The task might not have been rejected by the user after receiving the error. this._stopTrackingTask(); } /** * Returns true if this context has been closed or hasn't been connected yet. You can reopen it with `access`. */ get closed() { return this.socket.remoteAddress === undefined || this._closingError !== undefined; } /** * Reset this contex and all of its state. */ reset() { this.socket = this._newSocket(); } /** * Get the FTP control socket. */ get socket() { return this._socket; } /** * Set the socket for the control connection. This will only close the current control socket * if the new one is not an upgrade to the current one. */ set socket(socket) { // No data socket should be open in any case where the control socket is set or upgraded. this.dataSocket = undefined; this.tlsOptions = {}; // This being a soft reset, remove any remaining partial response. this._partialResponse = ""; if (this._socket) { // Only close the current connection if the new is not an upgrade. const isUpgrade = socket.localPort === this._socket.localPort; if (!isUpgrade) { this._socket.destroy(); } this._removeSocketListeners(this._socket); } if (socket) { // Setting a completely new control socket is in essence something like a reset. That's // why we also close any open data connection above. We can go one step further and reset // a possible closing error. That means that a closed FTPContext can be "reopened" by // setting a new control socket. this._closingError = undefined; // Don't set a timeout yet. Timeout for control sockets is only active during a task, see handle() below. socket.setTimeout(0); socket.setEncoding(this._encoding); socket.setKeepAlive(true); socket.on("data", data => this._onControlSocketData(data)); // Server sending a FIN packet is treated as an error. socket.on("end", () => this.closeWithError(new Error("Server sent FIN packet unexpectedly, closing connection."))); // Control being closed without error by server is treated as an error. socket.on("close", hadError => { if (!hadError) this.closeWithError(new Error("Server closed connection unexpectedly.")); }); this._setupDefaultErrorHandlers(socket, "control socket"); } this._socket = socket; } /** * Get the current FTP data connection if present. */ get dataSocket() { return this._dataSocket; } /** * Set the socket for the data connection. This will automatically close the former data socket. */ set dataSocket(socket) { this._closeSocket(this._dataSocket); if (socket) { // Don't set a timeout yet. Timeout data socket should be activated when data transmission starts // and timeout on control socket is deactivated. socket.setTimeout(0); this._setupDefaultErrorHandlers(socket, "data socket"); } this._dataSocket = socket; } /** * Get the currently used encoding. */ get encoding() { return this._encoding; } /** * Set the encoding used for the control socket. * * See https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings for what encodings * are supported by Node. */ set encoding(encoding) { this._encoding = encoding; if (this.socket) { this.socket.setEncoding(encoding); } } /** * Send an FTP command without waiting for or handling the result. */ send(command) { const containsPassword = command.startsWith("PASS"); const message = containsPassword ? "> PASS ###" : `> ${command}`; this.log(message); this._socket.write(command + "\r\n", this.encoding); } /** * Send an FTP command and handle the first response. Use this if you have a simple * request-response situation. */ request(command) { return this.handle(command, (res, task) => { if (res instanceof Error) { task.reject(res); } else { task.resolve(res); } }); } /** * Send an FTP command and handle any response until you resolve/reject. Use this if you expect multiple responses * to a request. This returns a Promise that will hold whatever the response handler passed on when resolving/rejecting its task. */ handle(command, responseHandler) { if (this._task) { // The user or client instance called `handle()` while a task is still running. const err = new Error("User launched a task while another one is still running. Forgot to use 'await' or '.then()'?"); err.stack += `\nRunning task launched at: ${this._task.stack}`; this.closeWithError(err); // Don't return here, continue with returning the Promise that will then be rejected // because the context closed already. That way, users will receive an exception where // they called this method by mistake. } return new Promise((resolvePromise, rejectPromise) => { const stack = new Error().stack || "Unknown call stack"; const resolver = { resolve: (...args) => { this._stopTrackingTask(); resolvePromise(...args); }, reject: err => { this._stopTrackingTask(); rejectPromise(err); } }; this._task = { stack, resolver, responseHandler }; if (this._closingError) { // This client has been closed. Provide an error that describes this one as being caused // by `_closingError`, include stack traces for both. const err = new Error("Client is closed"); // Type 'Error' is not correctly defined, doesn't have 'code'. err.stack += `\nClosing reason: ${this._closingError.stack}`; err.code = this._closingError.code !== undefined ? this._closingError.code : "0"; this._passToHandler(err); return; } // Only track control socket timeout during the lifecycle of a task. This avoids timeouts on idle sockets, // the default socket behaviour which is not expected by most users. this.socket.setTimeout(this.timeout); if (command) { this.send(command); } }); } /** * Log message if set to be verbose. */ log(message) { if (this.verbose) { // tslint:disable-next-line no-console console.log(message); } } /** * Return true if the control socket is using TLS. This does not mean that a session * has already been negotiated. */ get hasTLS() { return "encrypted" in this._socket; } /** * Removes reference to current task and handler. This won't resolve or reject the task. * @protected */ _stopTrackingTask() { // Disable timeout on control socket if there is no task active. this.socket.setTimeout(0); this._task = undefined; } /** * Handle incoming data on the control socket. The chunk is going to be of type `string` * because we let `socket` handle encoding with `setEncoding`. * @protected */ _onControlSocketData(chunk) { this.log(`< ${chunk}`); // This chunk might complete an earlier partial response. const completeResponse = this._partialResponse + chunk; const parsed = parseControlResponse_1.parseControlResponse(completeResponse); // Remember any incomplete remainder. this._partialResponse = parsed.rest; // Each response group is passed along individually. for (const message of parsed.messages) { const code = parseInt(message.substr(0, 3), 10); const response = { code, message }; const err = code >= 400 ? new FTPError(response) : undefined; this._passToHandler(err ? err : response); } } /** * Send the current handler a response. This is usually a control socket response * or a socket event, like an error or timeout. * @protected */ _passToHandler(response) { if (this._task) { this._task.responseHandler(response, this._task.resolver); } // Errors other than FTPError always close the client. If there isn't an active task to handle the error, // the next one submitted will receive it using `_closingError`. // There is only one edge-case: If there is an FTPError while no task is active, the error will be dropped. // But that means that the user sent an FTP command with no intention of handling the result. So why should the // error be handled? Maybe log it at least? Debug logging will already do that and the client stays useable after // FTPError. So maybe no need to do anything here. } /** * Setup all error handlers for a socket. * @protected */ _setupDefaultErrorHandlers(socket, identifier) { socket.once("error", error => { error.message += ` (${identifier})`; this.closeWithError(error); }); socket.once("close", hadError => { if (hadError) { this.closeWithError(new Error(`Socket closed due to transmission error (${identifier})`)); } }); socket.once("timeout", () => this.closeWithError(new Error(`Timeout (${identifier})`))); } /** * Close a socket. * @protected */ _closeSocket(socket) { if (socket) { socket.destroy(); this._removeSocketListeners(socket); } } /** * Remove all default listeners for socket. * @protected */ _removeSocketListeners(socket) { socket.removeAllListeners(); // Before Node.js 10.3.0, using `socket.removeAllListeners()` without any name did not work: https://github.com/nodejs/node/issues/20923. socket.removeAllListeners("timeout"); socket.removeAllListeners("data"); socket.removeAllListeners("end"); socket.removeAllListeners("error"); socket.removeAllListeners("close"); socket.removeAllListeners("connect"); } /** * Provide a new socket instance. * * Internal use only, replaced for unit tests. */ _newSocket() { return new net_1.Socket(); } } exports.FTPContext = FTPContext; /***/ }), /***/ 7170: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ProgressTracker = void 0; /** * Tracks progress of one socket data transfer at a time. */ class ProgressTracker { constructor() { this.bytesOverall = 0; this.intervalMs = 500; this.onStop = noop; this.onHandle = noop; } /** * Register a new handler for progress info. Use `undefined` to disable reporting. */ reportTo(onHandle = noop) { this.onHandle = onHandle; } /** * Start tracking transfer progress of a socket. * * @param socket The socket to observe. * @param name A name associated with this progress tracking, e.g. a filename. * @param type The type of the transfer, typically "upload" or "download". */ start(socket, name, type) { let lastBytes = 0; this.onStop = poll(this.intervalMs, () => { const bytes = socket.bytesRead + socket.bytesWritten; this.bytesOverall += bytes - lastBytes; lastBytes = bytes; this.onHandle({ name, type, bytes, bytesOverall: this.bytesOverall }); }); } /** * Stop tracking transfer progress. */ stop() { this.onStop(false); } /** * Call the progress handler one more time, then stop tracking. */ updateAndStop() { this.onStop(true); } } exports.ProgressTracker = ProgressTracker; /** * Starts calling a callback function at a regular interval. The first call will go out * immediately. The function returns a function to stop the polling. */ function poll(intervalMs, updateFunc) { const id = setInterval(updateFunc, intervalMs); const stopFunc = (stopWithUpdate) => { clearInterval(id); if (stopWithUpdate) { updateFunc(); } // Prevent repeated calls to stop calling handler. updateFunc = noop; }; updateFunc(); return stopFunc; } function noop() { } /***/ }), /***/ 4677: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); /***/ }), /***/ 8184: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.StringWriter = void 0; const stream_1 = __webpack_require__(2413); class StringWriter extends stream_1.Writable { constructor() { super(...arguments); this.buf = Buffer.alloc(0); } _write(chunk, _, callback) { if (chunk instanceof Buffer) { this.buf = Buffer.concat([this.buf, chunk]); callback(null); } else { callback(new Error("StringWriter expects chunks of type 'Buffer'.")); } } getText(encoding) { return this.buf.toString(encoding); } } exports.StringWriter = StringWriter; /***/ }), /***/ 7957: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", ({ value: true })); /** * Public API */ __exportStar(__webpack_require__(8337), exports); __exportStar(__webpack_require__(9052), exports); __exportStar(__webpack_require__(202), exports); __exportStar(__webpack_require__(2993), exports); __exportStar(__webpack_require__(4677), exports); var transfer_1 = __webpack_require__(5803); Object.defineProperty(exports, "enterPassiveModeIPv4", ({ enumerable: true, get: function () { return transfer_1.enterPassiveModeIPv4; } })); Object.defineProperty(exports, "enterPassiveModeIPv6", ({ enumerable: true, get: function () { return transfer_1.enterPassiveModeIPv6; } })); /***/ }), /***/ 6288: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.ipIsPrivateV4Address = exports.upgradeSocket = exports.describeAddress = exports.describeTLS = void 0; const tls_1 = __webpack_require__(4016); /** * Returns a string describing the encryption on a given socket instance. */ function describeTLS(socket) { if (socket instanceof tls_1.TLSSocket) { const protocol = socket.getProtocol(); return protocol ? protocol : "Server socket or disconnected client socket"; } return "No encryption"; } exports.describeTLS = describeTLS; /** * Returns a string describing the remote address of a socket. */ function describeAddress(socket) { if (socket.remoteFamily === "IPv6") { return `[${socket.remoteAddress}]:${socket.remotePort}`; } return `${socket.remoteAddress}:${socket.remotePort}`; } exports.describeAddress = describeAddress; /** * Upgrade a socket connection with TLS. */ function upgradeSocket(socket, options) { return new Promise((resolve, reject) => { const tlsOptions = Object.assign({}, options, { socket }); const tlsSocket = tls_1.connect(tlsOptions, () => { const expectCertificate = tlsOptions.rejectUnauthorized !== false; if (expectCertificate && !tlsSocket.authorized) { reject(tlsSocket.authorizationError); } else { // Remove error listener added below. tlsSocket.removeAllListeners("error"); resolve(tlsSocket); } }).once("error", error => { reject(error); }); }); } exports.upgradeSocket = upgradeSocket; /** * Returns true if an IP is a private address according to https://tools.ietf.org/html/rfc1918#section-3. * This will handle IPv4-mapped IPv6 addresses correctly but return false for all other IPv6 addresses. * * @param ip The IP as a string, e.g. "192.168.0.1" */ function ipIsPrivateV4Address(ip = "") { // Handle IPv4-mapped IPv6 addresses like ::ffff:192.168.0.1 if (ip.startsWith("::ffff:")) { ip = ip.substr(7); // Strip ::ffff: prefix } const octets = ip.split(".").map(o => parseInt(o, 10)); return octets[0] === 10 // 10.0.0.0 - 10.255.255.255 || (octets[0] === 172 && octets[1] >= 16 && octets[1] <= 31) // 172.16.0.0 - 172.31.255.255 || (octets[0] === 192 && octets[1] === 168); // 192.168.0.0 - 192.168.255.255 } exports.ipIsPrivateV4Address = ipIsPrivateV4Address; /***/ }), /***/ 9948: /***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.positiveIntermediate = exports.positiveCompletion = exports.isMultiline = exports.isSingleLine = exports.parseControlResponse = void 0; const LF = "\n"; /** * Parse an FTP control response as a collection of messages. A message is a complete * single- or multiline response. A response can also contain multiple multiline responses * that will each be represented by a message. A response can also be incomplete * and be completed on the next incoming data chunk for which case this function also * describes a `rest`. This function converts all CRLF to LF. */ function parseControlResponse(text) { const lines = text.split(/\r?\n/).filter(isNotBlank); const messages = []; let startAt = 0; let tokenRegex; for (let i = 0; i < lines.length; i++) { const line = lines[i]; // No group has been opened. if (!tokenRegex) { if (isMultiline(line)) { // Open a group by setting an expected token. const token = line.substr(0, 3); tokenRegex = new RegExp(`^${token}(?:$| )`); startAt = i; } else if (isSingleLine(line)) { // Single lines can be grouped immediately. messages.push(line); } } // Group has been opened, expect closing token. else if (tokenRegex.test(line)) { tokenRegex = undefined; messages.push(lines.slice(startAt, i + 1).join(LF)); } } // The last group might not have been closed, report it as a rest. const rest = tokenRegex ? lines.slice(startAt).join(LF) + LF : ""; return { messages, rest }; } exports.parseControlResponse = parseControlResponse; function isSingleLine(line) { return /^\d\d\d(?:$| )/.test(line); } exports.isSingleLine = isSingleLine; function isMultiline(line) { return /^\d\d\d-/.test(line); } exports.isMultiline = isMultiline; /** * Return true if an FTP return code describes a positive completion. */ function positiveCompletion(code) { return code >= 200 && code < 300; } exports.positiveCompletion = positiveCompletion; /** * Return true if an FTP return code describes a positive intermediate response. */ function positiveIntermediate(code) { return code >= 300 && code < 400; } exports.positiveIntermediate = positiveIntermediate; function isNotBlank(str) { return str !== ""; } /***/ }), /***/ 2993: /***/ (function(__unused_webpack_module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.parseList = void 0; const dosParser = __importStar(__webpack_require__(6199)); const unixParser = __importStar(__webpack_require__(2622)); const mlsdParser = __importStar(__webpack_require__(8157)); /** * Available directory listing parsers. These are candidates that will be tested * in the order presented. The first candidate will be used to parse the whole list. */ const availableParsers = [ dosParser, unixParser, mlsdParser // Keep MLSD last, may accept filename only ]; function firstCompatibleParser(line, parsers) { return parsers.find(parser => parser.testLine(line) === true); } function stringIsNotBlank(str) { return str.trim() !== ""; } const REGEX_NEWLINE = /\r?\n/; /** * Parse raw directory listing. */ function parseList(rawList) { const lines = rawList .split(REGEX_NEWLINE) .filter(stringIsNotBlank); if (lines.length === 0) { return []; } const testLine = lines[lines.length - 1]; const parser = firstCompatibleParser(testLine, availableParsers); if (!parser) { throw new Error("This library only supports MLSD, Unix- or DOS-style directory listing. Your FTP server seems to be using another format. You can see the transmitted listing when setting `client.ftp.verbose = true`. You can then provide a custom parser to `client.parseList`, see the documentation for details."); } const files = lines .map(parser.parseLine) .filter((info) => info !== undefined); return parser.transformList(files); } exports.parseList = parseList; /***/ }), /***/ 6199: /***/ ((__unused_webpack_module, exports, __webpack_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); exports.transformList = exports.parseLine = exports.testLine = void 0; const FileInfo_1 = __webpack_require__(202); /** * This parser is based on the FTP client library source code in Apache Commons Net provided * under the Apache 2.0 license. It has been simplified and rewritten to better fit the Javascript language. * * https://github.com/apache/commons-net/blob/master/src/main/java/org/apache/commons/net/ftp/parser/NTFTPEntryParser.java */ const RE_LINE = new RegExp("(\\S+)\\s+(\\S+)\\s+" // MM-dd-yy whitespace hh:mma|kk:mm swallow trailing spaces + "(?:(