@uipath/api-workflow-tool
Advanced tools
| import { | ||
| BrowserContextStorage, | ||
| ConsoleTelemetryProvider, | ||
| ProjectPackager, | ||
| TelemetryService, | ||
| ToolLogger, | ||
| setGlobalLogHandler | ||
| } from "./packager-tool-2zhkjkmy.js"; | ||
| import { | ||
| translate | ||
| } from "./packager-tool-h1tyrbff.js"; | ||
| import"./packager-tool-wckvcay0.js"; | ||
| // ../filesystem/dist/index.browser.js | ||
| var __create = Object.create; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| function __accessProp(key) { | ||
| return this[key]; | ||
| } | ||
| var __toESMCache_node; | ||
| var __toESMCache_esm; | ||
| var __toESM = (mod, isNodeMode, target) => { | ||
| var canCache = mod != null && typeof mod === "object"; | ||
| if (canCache) { | ||
| var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap; | ||
| var cached = cache.get(mod); | ||
| if (cached) | ||
| return cached; | ||
| } | ||
| target = mod != null ? __create(__getProtoOf(mod)) : {}; | ||
| const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; | ||
| for (let key of __getOwnPropNames(mod)) | ||
| if (!__hasOwnProp.call(to, key)) | ||
| __defProp(to, key, { | ||
| get: __accessProp.bind(mod, key), | ||
| enumerable: true | ||
| }); | ||
| if (canCache) | ||
| cache.set(mod, to); | ||
| return to; | ||
| }; | ||
| var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); | ||
| var require_just_once = __commonJS((exports, module) => { | ||
| module.exports = once; | ||
| function once(fn) { | ||
| var called, value; | ||
| if (typeof fn !== "function") { | ||
| throw new Error("expected a function but got " + fn); | ||
| } | ||
| return function wrap() { | ||
| if (called) { | ||
| return value; | ||
| } | ||
| called = true; | ||
| value = fn.apply(this, arguments); | ||
| return value; | ||
| }; | ||
| } | ||
| }); | ||
| var require_text_min = __commonJS((exports) => { | ||
| (function(scope) { | ||
| function B(r, e) { | ||
| var f; | ||
| return r instanceof Buffer ? f = r : f = Buffer.from(r.buffer, r.byteOffset, r.byteLength), f.toString(e); | ||
| } | ||
| var w = function(r) { | ||
| return Buffer.from(r); | ||
| }; | ||
| function h(r) { | ||
| for (var e = 0, f = Math.min(256 * 256, r.length + 1), n = new Uint16Array(f), i = [], o = 0;; ) { | ||
| var t = e < r.length; | ||
| if (!t || o >= f - 1) { | ||
| var s = n.subarray(0, o), m = s; | ||
| if (i.push(String.fromCharCode.apply(null, m)), !t) | ||
| return i.join(""); | ||
| r = r.subarray(e), e = 0, o = 0; | ||
| } | ||
| var a = r[e++]; | ||
| if ((a & 128) === 0) | ||
| n[o++] = a; | ||
| else if ((a & 224) === 192) { | ||
| var d = r[e++] & 63; | ||
| n[o++] = (a & 31) << 6 | d; | ||
| } else if ((a & 240) === 224) { | ||
| var d = r[e++] & 63, l = r[e++] & 63; | ||
| n[o++] = (a & 31) << 12 | d << 6 | l; | ||
| } else if ((a & 248) === 240) { | ||
| var d = r[e++] & 63, l = r[e++] & 63, R = r[e++] & 63, c = (a & 7) << 18 | d << 12 | l << 6 | R; | ||
| c > 65535 && (c -= 65536, n[o++] = c >>> 10 & 1023 | 55296, c = 56320 | c & 1023), n[o++] = c; | ||
| } | ||
| } | ||
| } | ||
| function F(r) { | ||
| for (var e = 0, f = r.length, n = 0, i = Math.max(32, f + (f >>> 1) + 7), o = new Uint8Array(i >>> 3 << 3);e < f; ) { | ||
| var t = r.charCodeAt(e++); | ||
| if (t >= 55296 && t <= 56319) { | ||
| if (e < f) { | ||
| var s = r.charCodeAt(e); | ||
| (s & 64512) === 56320 && (++e, t = ((t & 1023) << 10) + (s & 1023) + 65536); | ||
| } | ||
| if (t >= 55296 && t <= 56319) | ||
| continue; | ||
| } | ||
| if (n + 4 > o.length) { | ||
| i += 8, i *= 1 + e / r.length * 2, i = i >>> 3 << 3; | ||
| var m = new Uint8Array(i); | ||
| m.set(o), o = m; | ||
| } | ||
| if ((t & 4294967168) === 0) { | ||
| o[n++] = t; | ||
| continue; | ||
| } else if ((t & 4294965248) === 0) | ||
| o[n++] = t >>> 6 & 31 | 192; | ||
| else if ((t & 4294901760) === 0) | ||
| o[n++] = t >>> 12 & 15 | 224, o[n++] = t >>> 6 & 63 | 128; | ||
| else if ((t & 4292870144) === 0) | ||
| o[n++] = t >>> 18 & 7 | 240, o[n++] = t >>> 12 & 63 | 128, o[n++] = t >>> 6 & 63 | 128; | ||
| else | ||
| continue; | ||
| o[n++] = t & 63 | 128; | ||
| } | ||
| return o.slice ? o.slice(0, n) : o.subarray(0, n); | ||
| } | ||
| var u = "Failed to ", p = function(r, e, f) { | ||
| if (r) | ||
| throw new Error("".concat(u).concat(e, ": the '").concat(f, "' option is unsupported.")); | ||
| }; | ||
| var x = typeof Buffer == "function" && Buffer.from; | ||
| var A = x ? w : F; | ||
| function v() { | ||
| this.encoding = "utf-8"; | ||
| } | ||
| v.prototype.encode = function(r, e) { | ||
| return p(e && e.stream, "encode", "stream"), A(r); | ||
| }; | ||
| function U(r) { | ||
| var e; | ||
| try { | ||
| var f = new Blob([r], { type: "text/plain;charset=UTF-8" }); | ||
| e = URL.createObjectURL(f); | ||
| var n = new XMLHttpRequest; | ||
| return n.open("GET", e, false), n.send(), n.responseText; | ||
| } finally { | ||
| e && URL.revokeObjectURL(e); | ||
| } | ||
| } | ||
| var O = !x && typeof Blob == "function" && typeof URL == "function" && typeof URL.createObjectURL == "function", S = ["utf-8", "utf8", "unicode-1-1-utf-8"], T = h; | ||
| x ? T = B : O && (T = function(r) { | ||
| try { | ||
| return U(r); | ||
| } catch (e) { | ||
| return h(r); | ||
| } | ||
| }); | ||
| var y = "construct 'TextDecoder'", E = "".concat(u, " ").concat(y, ": the "); | ||
| function g(r, e) { | ||
| p(e && e.fatal, y, "fatal"), r = r || "utf-8"; | ||
| var f; | ||
| if (x ? f = Buffer.isEncoding(r) : f = S.indexOf(r.toLowerCase()) !== -1, !f) | ||
| throw new RangeError("".concat(E, " encoding label provided ('").concat(r, "') is invalid.")); | ||
| this.encoding = r, this.fatal = false, this.ignoreBOM = false; | ||
| } | ||
| g.prototype.decode = function(r, e) { | ||
| p(e && e.stream, "decode", "stream"); | ||
| var f; | ||
| return r instanceof Uint8Array ? f = r : r.buffer instanceof ArrayBuffer ? f = new Uint8Array(r.buffer) : f = new Uint8Array(r), T(f, this.encoding); | ||
| }; | ||
| scope.TextEncoder = scope.TextEncoder || v; | ||
| scope.TextDecoder = scope.TextDecoder || g; | ||
| })(typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : exports); | ||
| }); | ||
| var require_browser = __commonJS((exports, module) => { | ||
| require_text_min(); | ||
| module.exports = { | ||
| encode: (string) => new TextEncoder().encode(string), | ||
| decode: (buffer) => new TextDecoder().decode(buffer) | ||
| }; | ||
| }); | ||
| var require_just_debounce_it = __commonJS((exports, module) => { | ||
| module.exports = debounce; | ||
| function debounce(fn, wait, callFirst) { | ||
| var timeout; | ||
| return function() { | ||
| if (!wait) { | ||
| return fn.apply(this, arguments); | ||
| } | ||
| var context = this; | ||
| var args = arguments; | ||
| var callNow = callFirst && !timeout; | ||
| clearTimeout(timeout); | ||
| timeout = setTimeout(function() { | ||
| timeout = null; | ||
| if (!callNow) { | ||
| return fn.apply(context, args); | ||
| } | ||
| }, wait); | ||
| if (callNow) { | ||
| return fn.apply(this, arguments); | ||
| } | ||
| }; | ||
| } | ||
| }); | ||
| var require_path = __commonJS((exports, module) => { | ||
| function normalizePath(path) { | ||
| if (path.length === 0) { | ||
| return "."; | ||
| } | ||
| let parts = splitPath(path); | ||
| parts = parts.reduce(reducer, []); | ||
| return joinPath(...parts); | ||
| } | ||
| function resolvePath(...paths) { | ||
| let result = ""; | ||
| for (let path of paths) { | ||
| if (path.startsWith("/")) { | ||
| result = path; | ||
| } else { | ||
| result = normalizePath(joinPath(result, path)); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
| function joinPath(...parts) { | ||
| if (parts.length === 0) | ||
| return ""; | ||
| let path = parts.join("/"); | ||
| path = path.replace(/\/{2,}/g, "/"); | ||
| return path; | ||
| } | ||
| function splitPath(path) { | ||
| if (path.length === 0) | ||
| return []; | ||
| if (path === "/") | ||
| return ["/"]; | ||
| let parts = path.split("/"); | ||
| if (parts[parts.length - 1] === "") { | ||
| parts.pop(); | ||
| } | ||
| if (path[0] === "/") { | ||
| parts[0] = "/"; | ||
| } else { | ||
| if (parts[0] !== ".") { | ||
| parts.unshift("."); | ||
| } | ||
| } | ||
| return parts; | ||
| } | ||
| function dirname(path) { | ||
| const last = path.lastIndexOf("/"); | ||
| if (last === -1) | ||
| throw new Error(`Cannot get dirname of "${path}"`); | ||
| if (last === 0) | ||
| return "/"; | ||
| return path.slice(0, last); | ||
| } | ||
| function basename(path) { | ||
| if (path === "/") | ||
| throw new Error(`Cannot get basename of "${path}"`); | ||
| const last = path.lastIndexOf("/"); | ||
| if (last === -1) | ||
| return path; | ||
| return path.slice(last + 1); | ||
| } | ||
| function reducer(ancestors, current) { | ||
| if (ancestors.length === 0) { | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| if (current === ".") | ||
| return ancestors; | ||
| if (current === "..") { | ||
| if (ancestors.length === 1) { | ||
| if (ancestors[0] === "/") { | ||
| throw new Error("Unable to normalize path - traverses above root directory"); | ||
| } | ||
| if (ancestors[0] === ".") { | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| } | ||
| if (ancestors[ancestors.length - 1] === "..") { | ||
| ancestors.push(".."); | ||
| return ancestors; | ||
| } else { | ||
| ancestors.pop(); | ||
| return ancestors; | ||
| } | ||
| } | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| module.exports = { | ||
| join: joinPath, | ||
| normalize: normalizePath, | ||
| split: splitPath, | ||
| basename, | ||
| dirname, | ||
| resolve: resolvePath | ||
| }; | ||
| }); | ||
| var require_errors = __commonJS((exports, module) => { | ||
| function Err(name) { | ||
| return class extends Error { | ||
| constructor(...args) { | ||
| super(...args); | ||
| this.code = name; | ||
| if (this.message) { | ||
| this.message = name + ": " + this.message; | ||
| } else { | ||
| this.message = name; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| var EEXIST = Err("EEXIST"); | ||
| var ENOENT = Err("ENOENT"); | ||
| var ENOTDIR = Err("ENOTDIR"); | ||
| var ENOTEMPTY = Err("ENOTEMPTY"); | ||
| var ETIMEDOUT = Err("ETIMEDOUT"); | ||
| var EISDIR = Err("EISDIR"); | ||
| module.exports = { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, ETIMEDOUT, EISDIR }; | ||
| }); | ||
| var require_CacheFS = __commonJS((exports, module) => { | ||
| var path = require_path(); | ||
| var { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, EISDIR } = require_errors(); | ||
| var STAT = 0; | ||
| module.exports = class CacheFS { | ||
| constructor() {} | ||
| _makeRoot(root = new Map) { | ||
| root.set(STAT, { mode: 511, type: "dir", size: 0, ino: 0, mtimeMs: Date.now() }); | ||
| return root; | ||
| } | ||
| activate(superblock = null) { | ||
| if (superblock === null) { | ||
| this._root = new Map([["/", this._makeRoot()]]); | ||
| } else if (typeof superblock === "string") { | ||
| this._root = new Map([["/", this._makeRoot(this.parse(superblock))]]); | ||
| } else { | ||
| this._root = superblock; | ||
| } | ||
| } | ||
| get activated() { | ||
| return !!this._root; | ||
| } | ||
| deactivate() { | ||
| this._root = undefined; | ||
| } | ||
| size() { | ||
| return this._countInodes(this._root.get("/")) - 1; | ||
| } | ||
| _countInodes(map) { | ||
| let count = 1; | ||
| for (let [key, val] of map) { | ||
| if (key === STAT) | ||
| continue; | ||
| count += this._countInodes(val); | ||
| } | ||
| return count; | ||
| } | ||
| autoinc() { | ||
| let val = this._maxInode(this._root.get("/")) + 1; | ||
| return val; | ||
| } | ||
| _maxInode(map) { | ||
| let max = map.get(STAT).ino; | ||
| for (let [key, val] of map) { | ||
| if (key === STAT) | ||
| continue; | ||
| max = Math.max(max, this._maxInode(val)); | ||
| } | ||
| return max; | ||
| } | ||
| print(root = this._root.get("/")) { | ||
| let str = ""; | ||
| const printTree = (root2, indent) => { | ||
| for (let [file, node] of root2) { | ||
| if (file === 0) | ||
| continue; | ||
| let stat = node.get(STAT); | ||
| let mode = stat.mode.toString(8); | ||
| str += `${"\t".repeat(indent)}${file} ${mode}`; | ||
| if (stat.type === "file") { | ||
| str += ` ${stat.size} ${stat.mtimeMs} | ||
| `; | ||
| } else { | ||
| str += ` | ||
| `; | ||
| printTree(node, indent + 1); | ||
| } | ||
| } | ||
| }; | ||
| printTree(root, 0); | ||
| return str; | ||
| } | ||
| parse(print) { | ||
| let autoinc = 0; | ||
| function mk(stat) { | ||
| const ino = ++autoinc; | ||
| const type = stat.length === 1 ? "dir" : "file"; | ||
| let [mode, size, mtimeMs] = stat; | ||
| mode = parseInt(mode, 8); | ||
| size = size ? parseInt(size) : 0; | ||
| mtimeMs = mtimeMs ? parseInt(mtimeMs) : Date.now(); | ||
| return new Map([[STAT, { mode, type, size, mtimeMs, ino }]]); | ||
| } | ||
| let lines = print.trim().split(` | ||
| `); | ||
| let _root = this._makeRoot(); | ||
| let stack = [ | ||
| { indent: -1, node: _root }, | ||
| { indent: 0, node: null } | ||
| ]; | ||
| for (let line of lines) { | ||
| let prefix = line.match(/^\t*/)[0]; | ||
| let indent = prefix.length; | ||
| line = line.slice(indent); | ||
| let [filename, ...stat] = line.split("\t"); | ||
| let node = mk(stat); | ||
| if (indent <= stack[stack.length - 1].indent) { | ||
| while (indent <= stack[stack.length - 1].indent) { | ||
| stack.pop(); | ||
| } | ||
| } | ||
| stack.push({ indent, node }); | ||
| let cd = stack[stack.length - 2].node; | ||
| cd.set(filename, node); | ||
| } | ||
| return _root; | ||
| } | ||
| _lookup(filepath, follow = true) { | ||
| let dir = this._root; | ||
| let partialPath = "/"; | ||
| let parts = path.split(filepath); | ||
| for (let i = 0;i < parts.length; ++i) { | ||
| let part = parts[i]; | ||
| dir = dir.get(part); | ||
| if (!dir) | ||
| throw new ENOENT(filepath); | ||
| if (follow || i < parts.length - 1) { | ||
| const stat = dir.get(STAT); | ||
| if (stat.type === "symlink") { | ||
| let target = path.resolve(partialPath, stat.target); | ||
| dir = this._lookup(target); | ||
| } | ||
| if (!partialPath) { | ||
| partialPath = part; | ||
| } else { | ||
| partialPath = path.join(partialPath, part); | ||
| } | ||
| } | ||
| } | ||
| return dir; | ||
| } | ||
| mkdir(filepath, { mode }) { | ||
| if (filepath === "/") | ||
| throw new EEXIST; | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| if (dir.has(basename)) { | ||
| throw new EEXIST; | ||
| } | ||
| let entry = new Map; | ||
| let stat = { | ||
| mode, | ||
| type: "dir", | ||
| size: 0, | ||
| mtimeMs: Date.now(), | ||
| ino: this.autoinc() | ||
| }; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| } | ||
| rmdir(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| if (dir.get(STAT).type !== "dir") | ||
| throw new ENOTDIR; | ||
| if (dir.size > 1) | ||
| throw new ENOTEMPTY; | ||
| let parent = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| parent.delete(basename); | ||
| } | ||
| readdir(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| if (dir.get(STAT).type !== "dir") | ||
| throw new ENOTDIR; | ||
| return [...dir.keys()].filter((key) => typeof key === "string"); | ||
| } | ||
| writeStat(filepath, size, { mode }) { | ||
| let ino; | ||
| let oldStat; | ||
| try { | ||
| oldStat = this.stat(filepath); | ||
| } catch (err) {} | ||
| if (oldStat !== undefined) { | ||
| if (oldStat.type === "dir") { | ||
| throw new EISDIR; | ||
| } | ||
| if (mode == null) { | ||
| mode = oldStat.mode; | ||
| } | ||
| ino = oldStat.ino; | ||
| } | ||
| if (mode == null) { | ||
| mode = 438; | ||
| } | ||
| if (ino == null) { | ||
| ino = this.autoinc(); | ||
| } | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| let stat = { | ||
| mode, | ||
| type: "file", | ||
| size, | ||
| mtimeMs: Date.now(), | ||
| ino | ||
| }; | ||
| let entry = new Map; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| return stat; | ||
| } | ||
| unlink(filepath) { | ||
| let parent = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| parent.delete(basename); | ||
| } | ||
| rename(oldFilepath, newFilepath) { | ||
| let basename = path.basename(newFilepath); | ||
| let entry = this._lookup(oldFilepath); | ||
| let destDir = this._lookup(path.dirname(newFilepath)); | ||
| destDir.set(basename, entry); | ||
| this.unlink(oldFilepath); | ||
| } | ||
| stat(filepath) { | ||
| return this._lookup(filepath).get(STAT); | ||
| } | ||
| lstat(filepath) { | ||
| return this._lookup(filepath, false).get(STAT); | ||
| } | ||
| readlink(filepath) { | ||
| return this._lookup(filepath, false).get(STAT).target; | ||
| } | ||
| symlink(target, filepath) { | ||
| let ino, mode; | ||
| try { | ||
| let oldStat = this.stat(filepath); | ||
| if (mode === null) { | ||
| mode = oldStat.mode; | ||
| } | ||
| ino = oldStat.ino; | ||
| } catch (err) {} | ||
| if (mode == null) { | ||
| mode = 40960; | ||
| } | ||
| if (ino == null) { | ||
| ino = this.autoinc(); | ||
| } | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| let stat = { | ||
| mode, | ||
| type: "symlink", | ||
| target, | ||
| size: 0, | ||
| mtimeMs: Date.now(), | ||
| ino | ||
| }; | ||
| let entry = new Map; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| return stat; | ||
| } | ||
| _du(dir) { | ||
| let size = 0; | ||
| for (const [name, entry] of dir.entries()) { | ||
| if (name === STAT) { | ||
| size += entry.size; | ||
| } else { | ||
| size += this._du(entry); | ||
| } | ||
| } | ||
| return size; | ||
| } | ||
| du(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| return this._du(dir); | ||
| } | ||
| }; | ||
| }); | ||
| var require_idb_keyval_cjs = __commonJS((exports) => { | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| class Store { | ||
| constructor(dbName = "keyval-store", storeName = "keyval") { | ||
| this.storeName = storeName; | ||
| this._dbName = dbName; | ||
| this._storeName = storeName; | ||
| this._init(); | ||
| } | ||
| _init() { | ||
| if (this._dbp) { | ||
| return; | ||
| } | ||
| this._dbp = new Promise((resolve, reject) => { | ||
| const openreq = indexedDB.open(this._dbName); | ||
| openreq.onerror = () => reject(openreq.error); | ||
| openreq.onsuccess = () => resolve(openreq.result); | ||
| openreq.onupgradeneeded = () => { | ||
| openreq.result.createObjectStore(this._storeName); | ||
| }; | ||
| }); | ||
| } | ||
| _withIDBStore(type, callback) { | ||
| this._init(); | ||
| return this._dbp.then((db) => new Promise((resolve, reject) => { | ||
| const transaction = db.transaction(this.storeName, type); | ||
| transaction.oncomplete = () => resolve(); | ||
| transaction.onabort = transaction.onerror = () => reject(transaction.error); | ||
| callback(transaction.objectStore(this.storeName)); | ||
| })); | ||
| } | ||
| _close() { | ||
| this._init(); | ||
| return this._dbp.then((db) => { | ||
| db.close(); | ||
| this._dbp = undefined; | ||
| }); | ||
| } | ||
| } | ||
| var store; | ||
| function getDefaultStore() { | ||
| if (!store) | ||
| store = new Store; | ||
| return store; | ||
| } | ||
| function get(key, store2 = getDefaultStore()) { | ||
| let req; | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| req = store3.get(key); | ||
| }).then(() => req.result); | ||
| } | ||
| function set(key, value, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.put(value, key); | ||
| }); | ||
| } | ||
| function update(key, updater, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| const req = store3.get(key); | ||
| req.onsuccess = () => { | ||
| store3.put(updater(req.result), key); | ||
| }; | ||
| }); | ||
| } | ||
| function del(key, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.delete(key); | ||
| }); | ||
| } | ||
| function clear(store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.clear(); | ||
| }); | ||
| } | ||
| function keys(store2 = getDefaultStore()) { | ||
| const keys2 = []; | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| (store3.openKeyCursor || store3.openCursor).call(store3).onsuccess = function() { | ||
| if (!this.result) | ||
| return; | ||
| keys2.push(this.result.key); | ||
| this.result.continue(); | ||
| }; | ||
| }).then(() => keys2); | ||
| } | ||
| function close(store2 = getDefaultStore()) { | ||
| return store2._close(); | ||
| } | ||
| exports.Store = Store; | ||
| exports.get = get; | ||
| exports.set = set; | ||
| exports.update = update; | ||
| exports.del = del; | ||
| exports.clear = clear; | ||
| exports.keys = keys; | ||
| exports.close = close; | ||
| }); | ||
| var require_IdbBackend = __commonJS((exports, module) => { | ||
| var idb = require_idb_keyval_cjs(); | ||
| module.exports = class IdbBackend { | ||
| constructor(dbname, storename) { | ||
| this._database = dbname; | ||
| this._storename = storename; | ||
| this._store = new idb.Store(this._database, this._storename); | ||
| } | ||
| saveSuperblock(superblock) { | ||
| return idb.set("!root", superblock, this._store); | ||
| } | ||
| loadSuperblock() { | ||
| return idb.get("!root", this._store); | ||
| } | ||
| readFile(inode) { | ||
| return idb.get(inode, this._store); | ||
| } | ||
| writeFile(inode, data) { | ||
| return idb.set(inode, data, this._store); | ||
| } | ||
| unlink(inode) { | ||
| return idb.del(inode, this._store); | ||
| } | ||
| wipe() { | ||
| return idb.clear(this._store); | ||
| } | ||
| close() { | ||
| return idb.close(this._store); | ||
| } | ||
| }; | ||
| }); | ||
| var require_HttpBackend = __commonJS((exports, module) => { | ||
| module.exports = class HttpBackend { | ||
| constructor(url) { | ||
| this._url = url; | ||
| } | ||
| loadSuperblock() { | ||
| return fetch(this._url + "/.superblock.txt").then((res) => res.ok ? res.text() : null); | ||
| } | ||
| async readFile(filepath) { | ||
| const res = await fetch(this._url + filepath); | ||
| if (res.status === 200) { | ||
| return res.arrayBuffer(); | ||
| } else { | ||
| throw new Error("ENOENT"); | ||
| } | ||
| } | ||
| async sizeFile(filepath) { | ||
| const res = await fetch(this._url + filepath, { method: "HEAD" }); | ||
| if (res.status === 200) { | ||
| return res.headers.get("content-length"); | ||
| } else { | ||
| throw new Error("ENOENT"); | ||
| } | ||
| } | ||
| }; | ||
| }); | ||
| var require_Mutex = __commonJS((exports, module) => { | ||
| var idb = require_idb_keyval_cjs(); | ||
| var sleep = (ms) => new Promise((r) => setTimeout(r, ms)); | ||
| module.exports = class Mutex { | ||
| constructor(dbname, storename) { | ||
| this._id = Math.random(); | ||
| this._database = dbname; | ||
| this._storename = storename; | ||
| this._store = new idb.Store(this._database, this._storename); | ||
| this._lock = null; | ||
| } | ||
| async has({ margin = 2000 } = {}) { | ||
| if (this._lock && this._lock.holder === this._id) { | ||
| const now = Date.now(); | ||
| if (this._lock.expires > now + margin) { | ||
| return true; | ||
| } else { | ||
| return await this.renew(); | ||
| } | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| async renew({ ttl = 5000 } = {}) { | ||
| let success; | ||
| await idb.update("lock", (current) => { | ||
| const now = Date.now(); | ||
| const expires = now + ttl; | ||
| success = current && current.holder === this._id; | ||
| this._lock = success ? { holder: this._id, expires } : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| return success; | ||
| } | ||
| async acquire({ ttl = 5000 } = {}) { | ||
| let success; | ||
| let expired; | ||
| let doubleLock; | ||
| await idb.update("lock", (current) => { | ||
| const now = Date.now(); | ||
| const expires = now + ttl; | ||
| expired = current && current.expires < now; | ||
| success = current === undefined || expired; | ||
| doubleLock = current && current.holder === this._id; | ||
| this._lock = success ? { holder: this._id, expires } : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| if (doubleLock) { | ||
| throw new Error("Mutex double-locked"); | ||
| } | ||
| return success; | ||
| } | ||
| async wait({ interval = 100, limit = 6000, ttl } = {}) { | ||
| while (limit--) { | ||
| if (await this.acquire({ ttl })) | ||
| return true; | ||
| await sleep(interval); | ||
| } | ||
| throw new Error("Mutex timeout"); | ||
| } | ||
| async release({ force = false } = {}) { | ||
| let success; | ||
| let doubleFree; | ||
| let someoneElseHasIt; | ||
| await idb.update("lock", (current) => { | ||
| success = force || current && current.holder === this._id; | ||
| doubleFree = current === undefined; | ||
| someoneElseHasIt = current && current.holder !== this._id; | ||
| this._lock = success ? undefined : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| await idb.close(this._store); | ||
| if (!success && !force) { | ||
| if (doubleFree) | ||
| throw new Error("Mutex double-freed"); | ||
| if (someoneElseHasIt) | ||
| throw new Error("Mutex lost ownership"); | ||
| } | ||
| return success; | ||
| } | ||
| }; | ||
| }); | ||
| var require_Mutex2 = __commonJS((exports, module) => { | ||
| module.exports = class Mutex { | ||
| constructor(name) { | ||
| this._id = Math.random(); | ||
| this._database = name; | ||
| this._has = false; | ||
| this._release = null; | ||
| } | ||
| async has() { | ||
| return this._has; | ||
| } | ||
| async acquire() { | ||
| return new Promise((resolve) => { | ||
| navigator.locks.request(this._database + "_lock", { ifAvailable: true }, (lock) => { | ||
| this._has = !!lock; | ||
| resolve(!!lock); | ||
| return new Promise((resolve2) => { | ||
| this._release = resolve2; | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async wait({ timeout = 600000 } = {}) { | ||
| return new Promise((resolve, reject) => { | ||
| const controller = new AbortController; | ||
| setTimeout(() => { | ||
| controller.abort(); | ||
| reject(new Error("Mutex timeout")); | ||
| }, timeout); | ||
| navigator.locks.request(this._database + "_lock", { signal: controller.signal }, (lock) => { | ||
| this._has = !!lock; | ||
| resolve(!!lock); | ||
| return new Promise((resolve2) => { | ||
| this._release = resolve2; | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async release({ force = false } = {}) { | ||
| this._has = false; | ||
| if (this._release) { | ||
| this._release(); | ||
| } else if (force) { | ||
| navigator.locks.request(this._database + "_lock", { steal: true }, (lock) => true); | ||
| } | ||
| } | ||
| }; | ||
| }); | ||
| var require_DefaultBackend = __commonJS((exports, module) => { | ||
| var { encode, decode } = require_browser(); | ||
| var debounce = require_just_debounce_it(); | ||
| var CacheFS = require_CacheFS(); | ||
| var { ENOENT, ENOTEMPTY, ETIMEDOUT } = require_errors(); | ||
| var IdbBackend = require_IdbBackend(); | ||
| var HttpBackend = require_HttpBackend(); | ||
| var Mutex = require_Mutex(); | ||
| var Mutex2 = require_Mutex2(); | ||
| var path = require_path(); | ||
| module.exports = class DefaultBackend { | ||
| constructor() { | ||
| this.saveSuperblock = debounce(() => { | ||
| this.flush(); | ||
| }, 500); | ||
| } | ||
| async init(name, { | ||
| wipe, | ||
| url, | ||
| urlauto, | ||
| fileDbName = name, | ||
| db = null, | ||
| fileStoreName = name + "_files", | ||
| lockDbName = name + "_lock", | ||
| lockStoreName = name + "_lock" | ||
| } = {}) { | ||
| this._name = name; | ||
| this._idb = db || new IdbBackend(fileDbName, fileStoreName); | ||
| this._mutex = navigator.locks ? new Mutex2(name) : new Mutex(lockDbName, lockStoreName); | ||
| this._cache = new CacheFS(name); | ||
| this._opts = { wipe, url }; | ||
| this._needsWipe = !!wipe; | ||
| if (url) { | ||
| this._http = new HttpBackend(url); | ||
| this._urlauto = !!urlauto; | ||
| } | ||
| } | ||
| async activate() { | ||
| if (this._cache.activated) | ||
| return; | ||
| if (this._needsWipe) { | ||
| this._needsWipe = false; | ||
| await this._idb.wipe(); | ||
| await this._mutex.release({ force: true }); | ||
| } | ||
| if (!await this._mutex.has()) | ||
| await this._mutex.wait(); | ||
| const root = await this._idb.loadSuperblock(); | ||
| if (root) { | ||
| this._cache.activate(root); | ||
| } else if (this._http) { | ||
| const text = await this._http.loadSuperblock(); | ||
| this._cache.activate(text); | ||
| await this._saveSuperblock(); | ||
| } else { | ||
| this._cache.activate(); | ||
| } | ||
| if (await this._mutex.has()) { | ||
| return; | ||
| } else { | ||
| throw new ETIMEDOUT; | ||
| } | ||
| } | ||
| async deactivate() { | ||
| if (await this._mutex.has()) { | ||
| await this._saveSuperblock(); | ||
| } | ||
| this._cache.deactivate(); | ||
| try { | ||
| await this._mutex.release(); | ||
| } catch (e) { | ||
| console.log(e); | ||
| } | ||
| await this._idb.close(); | ||
| } | ||
| async _saveSuperblock() { | ||
| if (this._cache.activated) { | ||
| this._lastSavedAt = Date.now(); | ||
| await this._idb.saveSuperblock(this._cache._root); | ||
| } | ||
| } | ||
| _writeStat(filepath, size, opts) { | ||
| let dirparts = path.split(path.dirname(filepath)); | ||
| let dir = dirparts.shift(); | ||
| for (let dirpart of dirparts) { | ||
| dir = path.join(dir, dirpart); | ||
| try { | ||
| this._cache.mkdir(dir, { mode: 511 }); | ||
| } catch (e) {} | ||
| } | ||
| return this._cache.writeStat(filepath, size, opts); | ||
| } | ||
| async readFile(filepath, opts) { | ||
| const encoding = typeof opts === "string" ? opts : opts && opts.encoding; | ||
| if (encoding && encoding !== "utf8") | ||
| throw new Error('Only "utf8" encoding is supported in readFile'); | ||
| let data = null, stat = null; | ||
| try { | ||
| stat = this._cache.stat(filepath); | ||
| data = await this._idb.readFile(stat.ino); | ||
| } catch (e) { | ||
| if (!this._urlauto) | ||
| throw e; | ||
| } | ||
| if (!data && this._http) { | ||
| let lstat = this._cache.lstat(filepath); | ||
| while (lstat.type === "symlink") { | ||
| filepath = path.resolve(path.dirname(filepath), lstat.target); | ||
| lstat = this._cache.lstat(filepath); | ||
| } | ||
| data = await this._http.readFile(filepath); | ||
| } | ||
| if (data) { | ||
| if (!stat || stat.size != data.byteLength) { | ||
| stat = await this._writeStat(filepath, data.byteLength, { mode: stat ? stat.mode : 438 }); | ||
| this.saveSuperblock(); | ||
| } | ||
| if (encoding === "utf8") { | ||
| data = decode(data); | ||
| } else { | ||
| data.toString = () => decode(data); | ||
| } | ||
| } | ||
| if (!stat) | ||
| throw new ENOENT(filepath); | ||
| return data; | ||
| } | ||
| async writeFile(filepath, data, opts) { | ||
| const { mode, encoding = "utf8" } = opts; | ||
| if (typeof data === "string") { | ||
| if (encoding !== "utf8") { | ||
| throw new Error('Only "utf8" encoding is supported in writeFile'); | ||
| } | ||
| data = encode(data); | ||
| } | ||
| const stat = await this._cache.writeStat(filepath, data.byteLength, { mode }); | ||
| await this._idb.writeFile(stat.ino, data); | ||
| } | ||
| async unlink(filepath, opts) { | ||
| const stat = this._cache.lstat(filepath); | ||
| this._cache.unlink(filepath); | ||
| if (stat.type !== "symlink") { | ||
| await this._idb.unlink(stat.ino); | ||
| } | ||
| } | ||
| readdir(filepath, opts) { | ||
| return this._cache.readdir(filepath); | ||
| } | ||
| mkdir(filepath, opts) { | ||
| const { mode = 511 } = opts; | ||
| this._cache.mkdir(filepath, { mode }); | ||
| } | ||
| rmdir(filepath, opts) { | ||
| if (filepath === "/") { | ||
| throw new ENOTEMPTY; | ||
| } | ||
| this._cache.rmdir(filepath); | ||
| } | ||
| rename(oldFilepath, newFilepath) { | ||
| this._cache.rename(oldFilepath, newFilepath); | ||
| } | ||
| stat(filepath, opts) { | ||
| return this._cache.stat(filepath); | ||
| } | ||
| lstat(filepath, opts) { | ||
| return this._cache.lstat(filepath); | ||
| } | ||
| readlink(filepath, opts) { | ||
| return this._cache.readlink(filepath); | ||
| } | ||
| symlink(target, filepath) { | ||
| this._cache.symlink(target, filepath); | ||
| } | ||
| async backFile(filepath, opts) { | ||
| let size = await this._http.sizeFile(filepath); | ||
| await this._writeStat(filepath, size, opts); | ||
| } | ||
| du(filepath) { | ||
| return this._cache.du(filepath); | ||
| } | ||
| flush() { | ||
| return this._saveSuperblock(); | ||
| } | ||
| }; | ||
| }); | ||
| var require_Stat = __commonJS((exports, module) => { | ||
| module.exports = class Stat { | ||
| constructor(stats) { | ||
| this.type = stats.type; | ||
| this.mode = stats.mode; | ||
| this.size = stats.size; | ||
| this.ino = stats.ino; | ||
| this.mtimeMs = stats.mtimeMs; | ||
| this.ctimeMs = stats.ctimeMs || stats.mtimeMs; | ||
| this.uid = 1; | ||
| this.gid = 1; | ||
| this.dev = 1; | ||
| } | ||
| isFile() { | ||
| return this.type === "file"; | ||
| } | ||
| isDirectory() { | ||
| return this.type === "dir"; | ||
| } | ||
| isSymbolicLink() { | ||
| return this.type === "symlink"; | ||
| } | ||
| }; | ||
| }); | ||
| var require_PromisifiedFS = __commonJS((exports, module) => { | ||
| var DefaultBackend = require_DefaultBackend(); | ||
| var Stat = require_Stat(); | ||
| var path = require_path(); | ||
| function cleanParamsFilepathOpts(filepath, opts, ...rest) { | ||
| filepath = path.normalize(filepath); | ||
| if (typeof opts === "undefined" || typeof opts === "function") { | ||
| opts = {}; | ||
| } | ||
| if (typeof opts === "string") { | ||
| opts = { | ||
| encoding: opts | ||
| }; | ||
| } | ||
| return [filepath, opts, ...rest]; | ||
| } | ||
| function cleanParamsFilepathDataOpts(filepath, data, opts, ...rest) { | ||
| filepath = path.normalize(filepath); | ||
| if (typeof opts === "undefined" || typeof opts === "function") { | ||
| opts = {}; | ||
| } | ||
| if (typeof opts === "string") { | ||
| opts = { | ||
| encoding: opts | ||
| }; | ||
| } | ||
| return [filepath, data, opts, ...rest]; | ||
| } | ||
| function cleanParamsFilepathFilepath(oldFilepath, newFilepath, ...rest) { | ||
| return [path.normalize(oldFilepath), path.normalize(newFilepath), ...rest]; | ||
| } | ||
| module.exports = class PromisifiedFS { | ||
| constructor(name, options = {}) { | ||
| this.init = this.init.bind(this); | ||
| this.readFile = this._wrap(this.readFile, cleanParamsFilepathOpts, false); | ||
| this.writeFile = this._wrap(this.writeFile, cleanParamsFilepathDataOpts, true); | ||
| this.unlink = this._wrap(this.unlink, cleanParamsFilepathOpts, true); | ||
| this.readdir = this._wrap(this.readdir, cleanParamsFilepathOpts, false); | ||
| this.mkdir = this._wrap(this.mkdir, cleanParamsFilepathOpts, true); | ||
| this.rmdir = this._wrap(this.rmdir, cleanParamsFilepathOpts, true); | ||
| this.rename = this._wrap(this.rename, cleanParamsFilepathFilepath, true); | ||
| this.stat = this._wrap(this.stat, cleanParamsFilepathOpts, false); | ||
| this.lstat = this._wrap(this.lstat, cleanParamsFilepathOpts, false); | ||
| this.readlink = this._wrap(this.readlink, cleanParamsFilepathOpts, false); | ||
| this.symlink = this._wrap(this.symlink, cleanParamsFilepathFilepath, true); | ||
| this.backFile = this._wrap(this.backFile, cleanParamsFilepathOpts, true); | ||
| this.du = this._wrap(this.du, cleanParamsFilepathOpts, false); | ||
| this._deactivationPromise = null; | ||
| this._deactivationTimeout = null; | ||
| this._activationPromise = null; | ||
| this._operations = new Set; | ||
| if (name) { | ||
| this.init(name, options); | ||
| } | ||
| } | ||
| async init(...args) { | ||
| if (this._initPromiseResolve) | ||
| await this._initPromise; | ||
| this._initPromise = this._init(...args); | ||
| return this._initPromise; | ||
| } | ||
| async _init(name, options = {}) { | ||
| await this._gracefulShutdown(); | ||
| if (this._activationPromise) | ||
| await this._deactivate(); | ||
| if (this._backend && this._backend.destroy) { | ||
| await this._backend.destroy(); | ||
| } | ||
| this._backend = options.backend || new DefaultBackend; | ||
| if (this._backend.init) { | ||
| await this._backend.init(name, options); | ||
| } | ||
| if (this._initPromiseResolve) { | ||
| this._initPromiseResolve(); | ||
| this._initPromiseResolve = null; | ||
| } | ||
| if (!options.defer) { | ||
| this.stat("/"); | ||
| } | ||
| } | ||
| async _gracefulShutdown() { | ||
| if (this._operations.size > 0) { | ||
| this._isShuttingDown = true; | ||
| await new Promise((resolve) => this._gracefulShutdownResolve = resolve); | ||
| this._isShuttingDown = false; | ||
| this._gracefulShutdownResolve = null; | ||
| } | ||
| } | ||
| _wrap(fn, paramCleaner, mutating) { | ||
| return async (...args) => { | ||
| args = paramCleaner(...args); | ||
| let op = { | ||
| name: fn.name, | ||
| args | ||
| }; | ||
| this._operations.add(op); | ||
| try { | ||
| await this._activate(); | ||
| return await fn.apply(this, args); | ||
| } finally { | ||
| this._operations.delete(op); | ||
| if (mutating) | ||
| this._backend.saveSuperblock(); | ||
| if (this._operations.size === 0) { | ||
| if (!this._deactivationTimeout) | ||
| clearTimeout(this._deactivationTimeout); | ||
| this._deactivationTimeout = setTimeout(this._deactivate.bind(this), 500); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| async _activate() { | ||
| if (!this._initPromise) | ||
| console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)); | ||
| await this._initPromise; | ||
| if (this._deactivationTimeout) { | ||
| clearTimeout(this._deactivationTimeout); | ||
| this._deactivationTimeout = null; | ||
| } | ||
| if (this._deactivationPromise) | ||
| await this._deactivationPromise; | ||
| this._deactivationPromise = null; | ||
| if (!this._activationPromise) { | ||
| this._activationPromise = this._backend.activate ? this._backend.activate() : Promise.resolve(); | ||
| } | ||
| await this._activationPromise; | ||
| } | ||
| async _deactivate() { | ||
| if (this._activationPromise) | ||
| await this._activationPromise; | ||
| if (!this._deactivationPromise) { | ||
| this._deactivationPromise = this._backend.deactivate ? this._backend.deactivate() : Promise.resolve(); | ||
| } | ||
| this._activationPromise = null; | ||
| if (this._gracefulShutdownResolve) | ||
| this._gracefulShutdownResolve(); | ||
| return this._deactivationPromise; | ||
| } | ||
| async readFile(filepath, opts) { | ||
| return this._backend.readFile(filepath, opts); | ||
| } | ||
| async writeFile(filepath, data, opts) { | ||
| await this._backend.writeFile(filepath, data, opts); | ||
| return null; | ||
| } | ||
| async unlink(filepath, opts) { | ||
| await this._backend.unlink(filepath, opts); | ||
| return null; | ||
| } | ||
| async readdir(filepath, opts) { | ||
| return this._backend.readdir(filepath, opts); | ||
| } | ||
| async mkdir(filepath, opts) { | ||
| await this._backend.mkdir(filepath, opts); | ||
| return null; | ||
| } | ||
| async rmdir(filepath, opts) { | ||
| await this._backend.rmdir(filepath, opts); | ||
| return null; | ||
| } | ||
| async rename(oldFilepath, newFilepath) { | ||
| await this._backend.rename(oldFilepath, newFilepath); | ||
| return null; | ||
| } | ||
| async stat(filepath, opts) { | ||
| const data = await this._backend.stat(filepath, opts); | ||
| return new Stat(data); | ||
| } | ||
| async lstat(filepath, opts) { | ||
| const data = await this._backend.lstat(filepath, opts); | ||
| return new Stat(data); | ||
| } | ||
| async readlink(filepath, opts) { | ||
| return this._backend.readlink(filepath, opts); | ||
| } | ||
| async symlink(target, filepath) { | ||
| await this._backend.symlink(target, filepath); | ||
| return null; | ||
| } | ||
| async backFile(filepath, opts) { | ||
| await this._backend.backFile(filepath, opts); | ||
| return null; | ||
| } | ||
| async du(filepath) { | ||
| return this._backend.du(filepath); | ||
| } | ||
| async flush() { | ||
| return this._backend.flush(); | ||
| } | ||
| }; | ||
| }); | ||
| var require_src = __commonJS((exports, module) => { | ||
| var once = require_just_once(); | ||
| var PromisifiedFS = require_PromisifiedFS(); | ||
| function wrapCallback(opts, cb) { | ||
| if (typeof opts === "function") { | ||
| cb = opts; | ||
| } | ||
| cb = once(cb); | ||
| const resolve = (...args) => cb(null, ...args); | ||
| return [resolve, cb]; | ||
| } | ||
| module.exports = class FS { | ||
| constructor(...args) { | ||
| this.promises = new PromisifiedFS(...args); | ||
| this.init = this.init.bind(this); | ||
| this.readFile = this.readFile.bind(this); | ||
| this.writeFile = this.writeFile.bind(this); | ||
| this.unlink = this.unlink.bind(this); | ||
| this.readdir = this.readdir.bind(this); | ||
| this.mkdir = this.mkdir.bind(this); | ||
| this.rmdir = this.rmdir.bind(this); | ||
| this.rename = this.rename.bind(this); | ||
| this.stat = this.stat.bind(this); | ||
| this.lstat = this.lstat.bind(this); | ||
| this.readlink = this.readlink.bind(this); | ||
| this.symlink = this.symlink.bind(this); | ||
| this.backFile = this.backFile.bind(this); | ||
| this.du = this.du.bind(this); | ||
| this.flush = this.flush.bind(this); | ||
| } | ||
| init(name, options) { | ||
| return this.promises.init(name, options); | ||
| } | ||
| readFile(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readFile(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| writeFile(filepath, data, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.writeFile(filepath, data, opts).then(resolve).catch(reject); | ||
| } | ||
| unlink(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.unlink(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| readdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| mkdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.mkdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| rmdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.rmdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| rename(oldFilepath, newFilepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.rename(oldFilepath, newFilepath).then(resolve).catch(reject); | ||
| } | ||
| stat(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.stat(filepath).then(resolve).catch(reject); | ||
| } | ||
| lstat(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.lstat(filepath).then(resolve).catch(reject); | ||
| } | ||
| readlink(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readlink(filepath).then(resolve).catch(reject); | ||
| } | ||
| symlink(target, filepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.symlink(target, filepath).then(resolve).catch(reject); | ||
| } | ||
| backFile(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.backFile(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| du(filepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.du(filepath).then(resolve).catch(reject); | ||
| } | ||
| flush(cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.flush().then(resolve).catch(reject); | ||
| } | ||
| }; | ||
| }); | ||
| var import_lightning_fs = __toESM(require_src(), 1); | ||
| var LOCK_MAX_WAIT_MS = 20000; | ||
| var IN_MEMORY_LOCK_TAILS_KEY = Symbol.for("@uipath/filesystem/lock-tails"); | ||
| var getInMemoryLockTails = () => { | ||
| const globalsHost = globalThis; | ||
| const existing = globalsHost[IN_MEMORY_LOCK_TAILS_KEY]; | ||
| if (existing && typeof existing.get === "function" && typeof existing.set === "function" && typeof existing.delete === "function") { | ||
| return existing; | ||
| } | ||
| const created = new Map; | ||
| globalsHost[IN_MEMORY_LOCK_TAILS_KEY] = created; | ||
| return created; | ||
| }; | ||
| var getWebLocks = () => { | ||
| if (typeof navigator === "undefined") | ||
| return; | ||
| return navigator.locks; | ||
| }; | ||
| class BrowserFileSystem { | ||
| initialized = false; | ||
| fsInstance = null; | ||
| async init() { | ||
| if (this.initialized) | ||
| return; | ||
| this.fsInstance = new import_lightning_fs.default("uipcli-fs"); | ||
| this.initialized = true; | ||
| } | ||
| normalizePath(p) { | ||
| const isAbs = p.startsWith("/"); | ||
| const segments = p.split("/"); | ||
| const normalized = []; | ||
| for (const seg of segments) { | ||
| if (seg === "." || seg === "") | ||
| continue; | ||
| if (seg === "..") { | ||
| normalized.pop(); | ||
| } else { | ||
| normalized.push(seg); | ||
| } | ||
| } | ||
| return (isAbs ? "/" : "") + normalized.join("/"); | ||
| } | ||
| path = { | ||
| join: (...paths) => { | ||
| const joined = paths.filter(Boolean).join("/"); | ||
| return this.normalizePath(joined); | ||
| }, | ||
| resolve: (...paths) => { | ||
| let resolved = ""; | ||
| for (let i = paths.length - 1;i >= 0; i--) { | ||
| const p = paths[i]; | ||
| if (!p) | ||
| continue; | ||
| resolved = resolved ? `${p}/${resolved}` : p; | ||
| if (p.startsWith("/")) | ||
| break; | ||
| } | ||
| if (!resolved.startsWith("/")) { | ||
| resolved = `/${resolved}`; | ||
| } | ||
| return this.normalizePath(resolved); | ||
| }, | ||
| relative: (from, to) => { | ||
| const fromParts = this.normalizePath(from).split("/").filter(Boolean); | ||
| const toParts = this.normalizePath(to).split("/").filter(Boolean); | ||
| let common = 0; | ||
| while (common < fromParts.length && common < toParts.length && fromParts[common] === toParts[common]) { | ||
| common++; | ||
| } | ||
| const ups = Array(fromParts.length - common).fill(".."); | ||
| const downs = toParts.slice(common); | ||
| return [...ups, ...downs].join("/") || "."; | ||
| }, | ||
| dirname: (p) => { | ||
| const parts = p.split("/").filter(Boolean); | ||
| parts.pop(); | ||
| return `/${parts.join("/")}`; | ||
| }, | ||
| isAbsolute: (p) => p.startsWith("/"), | ||
| basename: (p, ext) => { | ||
| const parts = p.split("/").filter(Boolean); | ||
| const base = parts[parts.length - 1] || ""; | ||
| if (ext && base.endsWith(ext)) | ||
| return base.slice(0, -ext.length); | ||
| return base; | ||
| } | ||
| }; | ||
| env = { | ||
| cwd: () => "/", | ||
| homedir: () => "/home", | ||
| tmpdir: () => "/tmp", | ||
| getenv: (_key) => { | ||
| return; | ||
| } | ||
| }; | ||
| utils = { | ||
| open: async (url) => { | ||
| if (typeof window !== "undefined") { | ||
| window.open(url, "_blank"); | ||
| } | ||
| } | ||
| }; | ||
| async prepare() { | ||
| await this.init(); | ||
| } | ||
| getFs() { | ||
| if (!this.fsInstance) { | ||
| throw new Error("Browser filesystem is not initialized."); | ||
| } | ||
| return this.fsInstance; | ||
| } | ||
| async readFile(path, options) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| if (options) { | ||
| return await fs.promises.readFile(path, "utf8"); | ||
| } | ||
| const content = await fs.promises.readFile(path); | ||
| return new Uint8Array(content); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return null; | ||
| throw error; | ||
| } | ||
| } | ||
| async writeFile(filePath, data) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const dir = this.path.dirname(filePath); | ||
| if (dir && dir !== "/") { | ||
| await this.mkdir(dir); | ||
| } | ||
| await fs.promises.writeFile(filePath, data); | ||
| } | ||
| async appendFile(filePath, data) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const dir = this.path.dirname(filePath); | ||
| if (dir && dir !== "/") { | ||
| await this.mkdir(dir); | ||
| } | ||
| const existing = await this.readFile(filePath, "utf-8"); | ||
| const head = existing ?? ""; | ||
| const tail = typeof data === "string" ? data : new TextDecoder().decode(data); | ||
| await fs.promises.writeFile(filePath, head + tail); | ||
| } | ||
| async readdir(path) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| return await fs.promises.readdir(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return []; | ||
| throw error; | ||
| } | ||
| } | ||
| async stat(path) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const stats = await fs.promises.stat(path); | ||
| return { | ||
| isFile: () => stats.isFile(), | ||
| isDirectory: () => stats.isDirectory(), | ||
| size: stats.size, | ||
| mtimeMs: stats.mtimeMs | ||
| }; | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return null; | ||
| throw error; | ||
| } | ||
| } | ||
| async exists(path) { | ||
| return await this.stat(path) !== null; | ||
| } | ||
| async mkdir(path) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const normalizedPath = this.normalizePath(path); | ||
| if (normalizedPath === "/" || normalizedPath === "") { | ||
| return; | ||
| } | ||
| const parentDir = this.path.dirname(normalizedPath); | ||
| if (parentDir !== normalizedPath && parentDir !== "/") { | ||
| await this.mkdir(parentDir); | ||
| } else if (parentDir === "/") { | ||
| await this.checkRootDirectory(); | ||
| } | ||
| try { | ||
| await fs.promises.mkdir(normalizedPath); | ||
| } catch (error) { | ||
| if (this.isEexist(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| } | ||
| async acquireLock(lockPath) { | ||
| const canonical = this.normalizePath(this.path.isAbsolute(lockPath) ? lockPath : `/${lockPath}`); | ||
| const name = `@uipath/filesystem:lock:${canonical}`; | ||
| const webLocks = getWebLocks(); | ||
| if (webLocks) { | ||
| return await this.acquireWebLock(webLocks, name); | ||
| } | ||
| return this.acquireInMemoryLock(name); | ||
| } | ||
| async acquireWebLock(webLocks, name) { | ||
| const abortController = new AbortController; | ||
| const timeoutHandle = setTimeout(() => { | ||
| abortController.abort(); | ||
| }, LOCK_MAX_WAIT_MS); | ||
| return await new Promise((resolveAcquire, rejectAcquire) => { | ||
| let releaseHeld; | ||
| const requested = webLocks.request(name, { signal: abortController.signal }, () => new Promise((resolveHeld) => { | ||
| clearTimeout(timeoutHandle); | ||
| releaseHeld = resolveHeld; | ||
| resolveAcquire(async () => { | ||
| resolveHeld(); | ||
| }); | ||
| })); | ||
| requested.catch((error) => { | ||
| clearTimeout(timeoutHandle); | ||
| if (releaseHeld) { | ||
| return; | ||
| } | ||
| if (error?.name === "AbortError") { | ||
| rejectAcquire(new Error(`ELOCKED: timed out waiting for lock on ${name}`)); | ||
| return; | ||
| } | ||
| rejectAcquire(error); | ||
| }); | ||
| }); | ||
| } | ||
| acquireInMemoryLock(name) { | ||
| const tails = getInMemoryLockTails(); | ||
| const prior = tails.get(name) ?? Promise.resolve(); | ||
| let releaseHeld; | ||
| const held = new Promise((resolve) => { | ||
| releaseHeld = resolve; | ||
| }); | ||
| const chained = prior.then(() => held); | ||
| tails.set(name, chained); | ||
| chained.then(() => { | ||
| if (tails.get(name) === chained) { | ||
| tails.delete(name); | ||
| } | ||
| }); | ||
| return new Promise((resolveAcquire, rejectAcquire) => { | ||
| const timer = setTimeout(() => { | ||
| releaseHeld(); | ||
| rejectAcquire(new Error(`ELOCKED: timed out waiting for lock on ${name}`)); | ||
| }, LOCK_MAX_WAIT_MS); | ||
| prior.then(() => { | ||
| clearTimeout(timer); | ||
| resolveAcquire(async () => { | ||
| releaseHeld(); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async rm(path) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const stats = await this.stat(path); | ||
| if (!stats) { | ||
| return; | ||
| } | ||
| if (stats.isDirectory()) { | ||
| const entries = await this.readdir(path); | ||
| for (const entry of entries) { | ||
| await this.rm(this.path.join(path, entry)); | ||
| } | ||
| try { | ||
| await fs.promises.rmdir(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| return; | ||
| } | ||
| try { | ||
| await fs.promises.unlink(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| } | ||
| async rename(oldPath, newPath) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| await fs.promises.rename(oldPath, newPath); | ||
| } | ||
| async realpath(filePath) { | ||
| return filePath; | ||
| } | ||
| async getTempDir() { | ||
| const dir = `/tmp/uipath-fs-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; | ||
| await this.mkdir(dir); | ||
| return dir; | ||
| } | ||
| async copyDirectory(sourcePath, destPath) { | ||
| const sourceStats = await this.stat(sourcePath); | ||
| if (!sourceStats) { | ||
| throw new Error(`Source directory does not exist: ${sourcePath}`); | ||
| } | ||
| if (!sourceStats.isDirectory()) { | ||
| throw new Error(`Source path is not a directory: ${sourcePath}`); | ||
| } | ||
| await this.mkdir(destPath); | ||
| const entries = await this.readdir(sourcePath); | ||
| for (const entry of entries) { | ||
| const srcEntry = this.path.join(sourcePath, entry); | ||
| const destEntry = this.path.join(destPath, entry); | ||
| const entryStats = await this.stat(srcEntry); | ||
| if (!entryStats) | ||
| continue; | ||
| if (entryStats.isDirectory()) { | ||
| await this.copyDirectory(srcEntry, destEntry); | ||
| } else if (entryStats.isFile()) { | ||
| const content = await this.readFile(srcEntry); | ||
| if (content !== null) { | ||
| await this.writeFile(destEntry, content); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| isEnoent(error) { | ||
| return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; | ||
| } | ||
| isEexist(error) { | ||
| return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST"; | ||
| } | ||
| async checkRootDirectory() { | ||
| try { | ||
| const fs = this.getFs(); | ||
| await fs.promises.stat("/"); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) { | ||
| const fs = this.getFs(); | ||
| await fs.promises.mkdir("/"); | ||
| return; | ||
| } | ||
| throw error; | ||
| } | ||
| } | ||
| } | ||
| var defaultFs = new BrowserFileSystem; | ||
| var initPromise = defaultFs.init(); | ||
| // ../packager/project-packager/src/base-browser-packager-factory.ts | ||
| var sharedFileSystem = null; | ||
| var GLOBAL_FS_KEY = "__uipath_sharedFileSystem"; | ||
| class BaseBrowserPackagerFactory { | ||
| async getOrCreateFileSystem(config) { | ||
| if (config?.fileSystem) { | ||
| return config.fileSystem; | ||
| } | ||
| const globalRecord = globalThis; | ||
| if (!sharedFileSystem) { | ||
| sharedFileSystem = globalRecord[GLOBAL_FS_KEY] ?? null; | ||
| } | ||
| if (!sharedFileSystem) { | ||
| const fs = new BrowserFileSystem; | ||
| try { | ||
| await fs.init(); | ||
| } catch (error) { | ||
| if (error instanceof Error && error.message.includes("Mount point is already in use")) { | ||
| fs.initialized = true; | ||
| } else { | ||
| throw error; | ||
| } | ||
| } | ||
| sharedFileSystem = fs; | ||
| globalRecord[GLOBAL_FS_KEY] = fs; | ||
| } | ||
| return sharedFileSystem; | ||
| } | ||
| getOrCreateTelemetryService(config) { | ||
| if (config?.telemetryService) { | ||
| return config.telemetryService; | ||
| } | ||
| const provider = new ConsoleTelemetryProvider; | ||
| const contextStorage = new BrowserContextStorage; | ||
| return new TelemetryService(provider, contextStorage); | ||
| } | ||
| configureLogHandler(config) { | ||
| if (config?.logHandler) { | ||
| setGlobalLogHandler(config.logHandler); | ||
| } | ||
| } | ||
| configureLanguage(config) { | ||
| const language = config?.language ?? "en"; | ||
| translate.setLocale(language); | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/browser-project-packager-factory.ts | ||
| class BrowserProjectPackagerFactory extends BaseBrowserPackagerFactory { | ||
| async createAsync(config) { | ||
| const logger = new ToolLogger("ProjectPackagerFactory", "Create"); | ||
| this.configureLanguage(config); | ||
| this.configureLogHandler(config); | ||
| logger.info("Creating ProjectPackager instance..."); | ||
| const fileSystem = await this.getOrCreateFileSystem(config); | ||
| const telemetryService = this.getOrCreateTelemetryService(config); | ||
| const projectPackager = new ProjectPackager(fileSystem, telemetryService); | ||
| logger.info("ProjectPackager created successfully."); | ||
| return projectPackager; | ||
| } | ||
| } | ||
| async function createBrowserProjectPackager(options) { | ||
| const factory = new BrowserProjectPackagerFactory; | ||
| return factory.createAsync(options); | ||
| } | ||
| export { | ||
| createBrowserProjectPackager, | ||
| BaseBrowserPackagerFactory | ||
| }; | ||
| //# debugId=BEA0DF616EA4E56964756E2164756E21 |
| import { | ||
| WorkflowRunService | ||
| } from "./packager-tool-bprnbg91.js"; | ||
| import"./packager-tool-4pvh3k50.js"; | ||
| import"./packager-tool-y7hv8v54.js"; | ||
| import"./packager-tool-9qecd4wb.js"; | ||
| import"./packager-tool-5arsyj36.js"; | ||
| import"./packager-tool-wckvcay0.js"; | ||
| // ../executor/project-executor/src/models/run-status.ts | ||
| var TERMINAL_RUN_STATUSES = [ | ||
| "Succeeded" /* Succeeded */, | ||
| "Faulted" /* Faulted */, | ||
| "Cancelled" /* Cancelled */ | ||
| ]; | ||
| function isTerminalRunStatus(status) { | ||
| return TERMINAL_RUN_STATUSES.includes(status); | ||
| } | ||
| // ../executor/project-executor/src/models/run-result.ts | ||
| class RunResult { | ||
| status; | ||
| errorCode; | ||
| rawStatus; | ||
| message; | ||
| jobKey; | ||
| instanceId; | ||
| runId; | ||
| traceId; | ||
| steps; | ||
| output; | ||
| url; | ||
| details; | ||
| constructor(status, errorCode = "None" /* None */, message) { | ||
| this.status = status; | ||
| this.errorCode = errorCode; | ||
| this.message = message; | ||
| } | ||
| get isSuccess() { | ||
| return this.status === "Succeeded" /* Succeeded */ && this.errorCode === "None" /* None */; | ||
| } | ||
| get isTerminal() { | ||
| return isTerminalRunStatus(this.status); | ||
| } | ||
| static succeeded(init = {}) { | ||
| return Object.assign(new RunResult("Succeeded" /* Succeeded */, "None" /* None */), init); | ||
| } | ||
| static failed(errorCode, message, init = {}) { | ||
| return Object.assign(new RunResult("Faulted" /* Faulted */, errorCode, message), init); | ||
| } | ||
| } | ||
| // ../executor/project-executor/src/services/executors-factory-repository.ts | ||
| class ExecutorsFactoryRepository { | ||
| factoryMap = new Map; | ||
| onConflict; | ||
| constructor(onConflict) { | ||
| this.onConflict = onConflict ?? ((message) => console.warn(message)); | ||
| } | ||
| registerProjectExecutorFactory(factory) { | ||
| for (const projectType of factory.supportedTypes) { | ||
| const existing = this.factoryMap.get(projectType); | ||
| if (existing) { | ||
| if (existing.constructor?.name !== factory.constructor?.name) { | ||
| this.onConflict(`Executor factory conflict for project type '${projectType}': ` + `'${existing.constructor?.name}' already registered, ` + `ignoring '${factory.constructor?.name}'.`); | ||
| } | ||
| continue; | ||
| } | ||
| this.factoryMap.set(projectType, factory); | ||
| } | ||
| } | ||
| canHandleProject(projectType) { | ||
| return this.factoryMap.has(projectType); | ||
| } | ||
| getProjectExecutorFactory(projectType) { | ||
| const factory = this.factoryMap.get(projectType); | ||
| if (!factory) { | ||
| throw new Error(`No executor is registered for project type '${projectType}'. ` + `Registered types: ${this.registeredTypes.join(", ") || "none"}.`); | ||
| } | ||
| return factory; | ||
| } | ||
| get registeredTypes() { | ||
| return [...this.factoryMap.keys()]; | ||
| } | ||
| reset() { | ||
| this.factoryMap.clear(); | ||
| } | ||
| } | ||
| var REGISTRY_KEY = Symbol.for("@uipath/project-executor/executorsFactoryRepository"); | ||
| var _global = globalThis; | ||
| if (!_global[REGISTRY_KEY]) { | ||
| _global[REGISTRY_KEY] = new ExecutorsFactoryRepository; | ||
| } | ||
| var executorsFactoryRepository = _global[REGISTRY_KEY]; | ||
| // ../executor/project-executor/src/services/executor-factory-provider.ts | ||
| var PROVIDER_KEY = Symbol.for("@uipath/project-executor/executorFactoryProvider"); | ||
| // ../executor/project-executor/src/services/project-executor.ts | ||
| class ProjectExecutor { | ||
| fileSystem; | ||
| logger; | ||
| constructor(fileSystem, logger) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = logger; | ||
| } | ||
| runAsync(_options, _cancellationToken) { | ||
| return Promise.resolve(RunResult.failed("UnsupportedProjectType" /* UnsupportedProjectType */, `${this.constructor.name} does not support run.`)); | ||
| } | ||
| async resolveDefaultEntryPoint(projectPath) { | ||
| const entryPointsFile = this.fileSystem.path.join(projectPath, ENTRY_POINTS_FILE_NAME); | ||
| try { | ||
| const raw = await this.fileSystem.readFile(entryPointsFile, "utf-8"); | ||
| if (!raw) { | ||
| return; | ||
| } | ||
| const declared = JSON.parse(raw).entryPoints; | ||
| return this.firstDeclaredEntryPoint(declared); | ||
| } catch (error) { | ||
| this.logger.warn(`Could not read the default entry point from ${entryPointsFile}: ${error instanceof Error ? error.message : String(error)}`); | ||
| return; | ||
| } | ||
| } | ||
| asEntryPoint(value) { | ||
| return typeof value === "string" && value.length > 0 ? value : undefined; | ||
| } | ||
| firstDeclaredEntryPoint(entryPoints) { | ||
| if (!Array.isArray(entryPoints)) { | ||
| return; | ||
| } | ||
| for (const entry of entryPoints) { | ||
| const filePath = this.asEntryPoint(entry?.filePath); | ||
| if (filePath) { | ||
| return filePath; | ||
| } | ||
| } | ||
| return; | ||
| } | ||
| dispose() { | ||
| return Promise.resolve(); | ||
| } | ||
| } | ||
| var ENTRY_POINTS_FILE_NAME = "entry-points.json"; | ||
| // src/executor/api-workflow-project-executor.ts | ||
| var FALLBACK_ENTRY_POINT = "Workflow.json"; | ||
| var PACKED_CONTENT_PREFIX = "content/"; | ||
| var defaultRunnerFactory = (fileSystem) => new WorkflowRunService(fileSystem); | ||
| class ApiWorkflowProjectExecutor extends ProjectExecutor { | ||
| createRunner; | ||
| constructor(fileSystem, logger, createRunner = defaultRunnerFactory) { | ||
| super(fileSystem, logger); | ||
| this.createRunner = createRunner; | ||
| } | ||
| async runAsync(options, cancellationToken) { | ||
| const { project } = options; | ||
| if (!project.projectPath) { | ||
| return RunResult.failed("InvalidInput" /* InvalidInput */, "Running an API Workflow requires the project directory."); | ||
| } | ||
| if (cancellationToken?.aborted) { | ||
| return RunResult.failed("Cancelled" /* Cancelled */, "Run cancelled before it started."); | ||
| } | ||
| const entryPoint = options.entryPoint ?? await this.resolveDefaultEntryPoint(project.projectPath) ?? FALLBACK_ENTRY_POINT; | ||
| const workflowPath = this.fileSystem.path.join(project.projectPath, entryPoint); | ||
| this.logger.info(`Running API Workflow '${project.name}' locally: ${entryPoint}`); | ||
| options.callbacks?.onStatusChange?.("Running" /* Running */); | ||
| let outcome; | ||
| try { | ||
| outcome = await this.createRunner(this.fileSystem).run({ | ||
| filePath: workflowPath, | ||
| input: options.inputArguments, | ||
| auth: Boolean(options.connection?.accessToken), | ||
| connection: options.connection | ||
| }); | ||
| } catch (error) { | ||
| return RunResult.failed("Unknown" /* Unknown */, `Could not run API Workflow '${project.name}': ${messageOf(error)}`, { details: { entryPoint } }); | ||
| } | ||
| if (cancellationToken?.aborted) { | ||
| return RunResult.failed("Cancelled" /* Cancelled */, "Run cancelled."); | ||
| } | ||
| return toRunResult(outcome, entryPoint); | ||
| } | ||
| async resolveDefaultEntryPoint(projectPath) { | ||
| const declared = await this.mainFileFromProject(projectPath); | ||
| if (declared) { | ||
| return declared; | ||
| } | ||
| const packed = await super.resolveDefaultEntryPoint(projectPath); | ||
| return packed?.startsWith(PACKED_CONTENT_PREFIX) ? packed.slice(PACKED_CONTENT_PREFIX.length) : packed; | ||
| } | ||
| async mainFileFromProject(projectPath) { | ||
| const projectFile = this.fileSystem.path.join(projectPath, "project.uiproj"); | ||
| try { | ||
| const raw = await this.fileSystem.readFile(projectFile, "utf-8"); | ||
| if (!raw) { | ||
| return; | ||
| } | ||
| const mainFile = JSON.parse(raw).MainFile; | ||
| return typeof mainFile === "string" && mainFile.length > 0 ? mainFile : undefined; | ||
| } catch (error) { | ||
| this.logger.warn(`Could not read the entry point from ${projectFile}: ${messageOf(error)}`); | ||
| return; | ||
| } | ||
| } | ||
| } | ||
| function toRunResult(outcome, entryPoint) { | ||
| const details = { | ||
| entryPoint, | ||
| workflowPath: outcome.workflowPath | ||
| }; | ||
| if (outcome.success) { | ||
| const result2 = RunResult.succeeded({ | ||
| output: asOutputArguments(outcome.data), | ||
| details: hasData(outcome.data) ? { ...details, data: outcome.data } : details | ||
| }); | ||
| result2.rawStatus = outcome.status; | ||
| return result2; | ||
| } | ||
| const result = RunResult.failed(errorCodeFor(outcome.failedStage), outcome.errorMessage ?? "The workflow run did not succeed.", { details }); | ||
| result.rawStatus = outcome.status; | ||
| return result; | ||
| } | ||
| function errorCodeFor(stage) { | ||
| switch (stage) { | ||
| case "load": | ||
| return "InvalidInput" /* InvalidInput */; | ||
| case "auth": | ||
| return "Unauthorized" /* Unauthorized */; | ||
| default: | ||
| return "ExecutionFailed" /* ExecutionFailed */; | ||
| } | ||
| } | ||
| function asOutputArguments(data) { | ||
| return data !== null && typeof data === "object" && !Array.isArray(data) ? data : undefined; | ||
| } | ||
| function hasData(data) { | ||
| return data !== undefined && data !== null; | ||
| } | ||
| function messageOf(error) { | ||
| return error instanceof Error ? error.message : String(error); | ||
| } | ||
| // src/executor/api-workflow-executor-factory.ts | ||
| var API_WORKFLOW_PROJECT_TYPES = ["Api"]; | ||
| class ApiWorkflowExecutorFactory { | ||
| supportedTypes = API_WORKFLOW_PROJECT_TYPES; | ||
| createAsync(logger, fileSystem) { | ||
| return Promise.resolve(new ApiWorkflowProjectExecutor(fileSystem, logger)); | ||
| } | ||
| } | ||
| // src/executor-tool.ts | ||
| var createExecutorFactory = () => new ApiWorkflowExecutorFactory; | ||
| export { | ||
| createExecutorFactory | ||
| }; | ||
| //# debugId=E512E96D87D7F48D64756E2164756E21 |
| import { | ||
| BrowserContextStorage, | ||
| ConsoleTelemetryProvider, | ||
| GovernancePolicyService, | ||
| PackService, | ||
| PackagerParameters, | ||
| PackagerParametersValidator, | ||
| ProjectBuildOptionsValidator, | ||
| ProjectLoader, | ||
| ProjectPackager, | ||
| ProjectToolExecutor, | ||
| ProjectValidateOptionsValidator, | ||
| RulesConfigFileType, | ||
| TelemetryNames, | ||
| TelemetryService, | ||
| ToolLogger, | ||
| ToolsFactory, | ||
| resolveProducedNupkgsAsync, | ||
| setGlobalLogHandler, | ||
| signNupkgsAsync | ||
| } from "./packager-tool-2zhkjkmy.js"; | ||
| import { | ||
| ToolErrorCodes, | ||
| ToolResult, | ||
| translate | ||
| } from "./packager-tool-h1tyrbff.js"; | ||
| import"./packager-tool-wckvcay0.js"; | ||
| // ../packager/project-packager/src/models/project-restore-options.ts | ||
| class ProjectRestoreOptions extends PackagerParameters { | ||
| } | ||
| // ../packager/project-packager/src/models/project-validate-options.ts | ||
| class ProjectValidateOptions extends ProjectRestoreOptions { | ||
| validateOptions = { | ||
| skipAnalyze: false, | ||
| skipValidate: false, | ||
| governanceFileType: "Default" /* Default */ | ||
| }; | ||
| } | ||
| // ../packager/project-packager/src/models/project-build-options.ts | ||
| class ProjectBuildOptions extends ProjectValidateOptions { | ||
| outputType; | ||
| } | ||
| // ../packager/project-packager/src/models/project-cleanup-options.ts | ||
| class ProjectCleanupOptions extends PackagerParameters { | ||
| dryRun = false; | ||
| skipImports = false; | ||
| lockKey; | ||
| } | ||
| // ../packager/project-packager/src/models/project-pack-options.ts | ||
| class ProjectPackOptions extends ProjectBuildOptions { | ||
| destinationPath; | ||
| package; | ||
| signingInfo; | ||
| packOptions; | ||
| } | ||
| // ../packager/project-packager/src/publish/models/publish-options.ts | ||
| var PublishDestinationKind; | ||
| ((PublishDestinationKind2) => { | ||
| PublishDestinationKind2["LocalFolder"] = "LocalFolder"; | ||
| PublishDestinationKind2["NugetFeed"] = "NugetFeed"; | ||
| PublishDestinationKind2["OrchestratorPersonalWorkspace"] = "OrchestratorPersonalWorkspace"; | ||
| PublishDestinationKind2["OrchestratorTenantProcesses"] = "OrchestratorTenantProcesses"; | ||
| PublishDestinationKind2["OrchestratorSharedLibraries"] = "OrchestratorSharedLibraries"; | ||
| PublishDestinationKind2["OrchestratorCustom"] = "OrchestratorCustom"; | ||
| })(PublishDestinationKind ||= {}); | ||
| class ProjectPublishOptions { | ||
| packagePaths; | ||
| destination; | ||
| constructor(packagePaths, destination) { | ||
| this.packagePaths = packagePaths; | ||
| this.destination = destination; | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/local-folder-publisher.ts | ||
| class LocalFolderPublisher { | ||
| fileSystem; | ||
| logger; | ||
| constructor(fileSystem) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "LocalFolder"); | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| const overwrite = destination.overwrite ?? true; | ||
| if (!destination.folderPath) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.localFolderRequired")); | ||
| } | ||
| if (!await this.fileSystem.exists(destination.folderPath)) { | ||
| await this.fileSystem.mkdir(destination.folderPath); | ||
| } | ||
| const written = []; | ||
| for (const sourcePath of packagePaths) { | ||
| const fileName = this.fileSystem.path.basename(sourcePath); | ||
| const destPath = this.fileSystem.path.join(destination.folderPath, fileName); | ||
| if (!overwrite && await this.fileSystem.exists(destPath)) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.localFolderFileExists", { path: destPath })); | ||
| } | ||
| const data = await this.fileSystem.readFile(sourcePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: sourcePath })); | ||
| } | ||
| await this.fileSystem.writeFile(destPath, data); | ||
| written.push(destPath); | ||
| this.logger.info(`Copied package to ${destPath}`); | ||
| } | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, written); | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/nuget-feed-publisher.ts | ||
| var NUGET_V3_PACKAGE_PUBLISH_TYPE = "PackagePublish/2.0.0"; | ||
| class NugetFeedPublisher { | ||
| fileSystem; | ||
| logger; | ||
| constructor(fileSystem) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "NugetFeed"); | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| if (!destination.feedUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetFeedUrlRequired")); | ||
| } | ||
| let pushUrl; | ||
| try { | ||
| pushUrl = await this.resolvePushUrl(destination.feedUrl, destination.apiKey); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetPushUrlResolutionFailed", { feedUrl: destination.feedUrl, message })); | ||
| } | ||
| const published = []; | ||
| for (const packagePath of packagePaths) { | ||
| const data = await this.fileSystem.readFile(packagePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: packagePath })); | ||
| } | ||
| const fileName = this.fileSystem.path.basename(packagePath); | ||
| const form = new FormData; | ||
| form.append("package", new Blob([data], { | ||
| type: "application/octet-stream" | ||
| }), fileName); | ||
| const headers = {}; | ||
| if (destination.apiKey) { | ||
| headers["X-NuGet-ApiKey"] = destination.apiKey; | ||
| } | ||
| this.logger.info(`Pushing ${fileName} to ${pushUrl}`); | ||
| const response = await fetch(pushUrl, { | ||
| method: "PUT", | ||
| headers, | ||
| body: form | ||
| }); | ||
| if (!response.ok) { | ||
| const body = await this.safeReadBody(response); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetPushFailed", { | ||
| fileName, | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| })); | ||
| } | ||
| published.push(packagePath); | ||
| this.logger.info(`Pushed ${fileName} successfully.`); | ||
| } | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, published); | ||
| } | ||
| async resolvePushUrl(feedUrl, apiKey) { | ||
| let end = feedUrl.length; | ||
| while (end > 0 && feedUrl.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| const trimmed = feedUrl.slice(0, end); | ||
| if (/\/api\/v2\/package\/?$/i.test(trimmed)) { | ||
| return trimmed; | ||
| } | ||
| if (/\.json$/i.test(trimmed)) { | ||
| return this.resolveFromServiceIndex(trimmed, apiKey); | ||
| } | ||
| return `${trimmed}/api/v2/package`; | ||
| } | ||
| async resolveFromServiceIndex(serviceIndexUrl, apiKey) { | ||
| const headers = { Accept: "application/json" }; | ||
| if (apiKey) { | ||
| headers["X-NuGet-ApiKey"] = apiKey; | ||
| } | ||
| const response = await fetch(serviceIndexUrl, { headers }); | ||
| if (!response.ok) { | ||
| throw new Error(`service index returned ${response.status} ${response.statusText}`); | ||
| } | ||
| const index = await response.json(); | ||
| const resource = index.resources?.find((r) => r["@type"] === NUGET_V3_PACKAGE_PUBLISH_TYPE); | ||
| if (!resource?.["@id"]) { | ||
| throw new Error(`service index has no ${NUGET_V3_PACKAGE_PUBLISH_TYPE} resource`); | ||
| } | ||
| return resource["@id"]; | ||
| } | ||
| async safeReadBody(response) { | ||
| try { | ||
| const text = await response.text(); | ||
| return text.slice(0, 500); | ||
| } catch { | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/orchestrator-feed-types.ts | ||
| var PackageFeedDtoPurposeEnum = { | ||
| Undefined: "Undefined", | ||
| Processes: "Processes", | ||
| Libraries: "Libraries", | ||
| PersonalWorkspace: "PersonalWorkspace", | ||
| FolderHierarchy: "FolderHierarchy" | ||
| }; | ||
| var PackageFeedDtoAuthenticationTypeEnum = { | ||
| Secure: "Secure", | ||
| ApiKey: "ApiKey", | ||
| Basic: "Basic" | ||
| }; | ||
| var ExtendedFolderDtoFeedTypeEnum = { | ||
| Undefined: "Undefined", | ||
| Processes: "Processes", | ||
| Libraries: "Libraries", | ||
| PersonalWorkspace: "PersonalWorkspace", | ||
| FolderHierarchy: "FolderHierarchy" | ||
| }; | ||
| // ../common/dist/sdk-user-agent.js | ||
| var PREFIX = "@uipath/common/"; | ||
| var _g = globalThis; | ||
| function singleton(ctorOrName) { | ||
| const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name; | ||
| const key = Symbol.for(PREFIX + name); | ||
| return { | ||
| get(fallback) { | ||
| return _g[key] ?? fallback; | ||
| }, | ||
| set(value) { | ||
| _g[key] = value; | ||
| }, | ||
| clear() { | ||
| delete _g[key]; | ||
| }, | ||
| getOrInit(factory, guard) { | ||
| const existing = _g[key]; | ||
| if (existing != null && typeof existing === "object") { | ||
| if (!guard || guard(existing)) { | ||
| return existing; | ||
| } | ||
| } | ||
| const instance = factory(); | ||
| _g[key] = instance; | ||
| return instance; | ||
| } | ||
| }; | ||
| } | ||
| var telemetryPropsSlot = singleton("TelemetryDefaultProps"); | ||
| var USER_AGENT_HEADER = "User-Agent"; | ||
| var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken"); | ||
| function splitUserAgentTokens(value) { | ||
| return value?.trim().split(/\s+/).filter(Boolean) ?? []; | ||
| } | ||
| function appendUserAgentToken(value, userAgent) { | ||
| const tokens = splitUserAgentTokens(value); | ||
| const seen = new Set(tokens); | ||
| for (const token of splitUserAgentTokens(userAgent)) { | ||
| if (!seen.has(token)) { | ||
| tokens.push(token); | ||
| seen.add(token); | ||
| } | ||
| } | ||
| return tokens.join(" "); | ||
| } | ||
| function getEffectiveUserAgent(userAgent) { | ||
| return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent); | ||
| } | ||
| function getHeaderName(headers, headerName) { | ||
| return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase()); | ||
| } | ||
| function addSdkUserAgentHeader(headers, userAgent) { | ||
| const result = { ...headers ?? {} }; | ||
| const headerName = getHeaderName(result, USER_AGENT_HEADER); | ||
| result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent)); | ||
| return result; | ||
| } | ||
| // ../packager/project-packager/package.json | ||
| var package_default = { | ||
| name: "@uipath/project-packager", | ||
| license: "MIT", | ||
| version: "1.201.0-preview.121", | ||
| description: "UiPath Project Packager - core library for packing individual UiPath projects", | ||
| type: "module", | ||
| main: "./dist/index.js", | ||
| exports: { | ||
| ".": { | ||
| types: "./dist/src/index.d.ts", | ||
| default: "./dist/index.js" | ||
| }, | ||
| "./node": { | ||
| types: "./dist/src/node.d.ts", | ||
| default: "./dist/node.js" | ||
| }, | ||
| "./browser": { | ||
| types: "./dist/src/browser.d.ts", | ||
| default: "./dist/browser.js" | ||
| } | ||
| }, | ||
| types: "./dist/src/index.d.ts", | ||
| repository: { | ||
| type: "git", | ||
| url: "https://github.com/UiPath/cli.git", | ||
| directory: "packages/packager/project-packager" | ||
| }, | ||
| publishConfig: { | ||
| registry: "https://npm.pkg.github.com/" | ||
| }, | ||
| files: [ | ||
| "dist" | ||
| ], | ||
| scripts: { | ||
| build: "bun build ./src/index.ts --outdir dist --format esm --target browser --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && bun build ./src/browser.ts --outdir dist --format esm --target browser --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && bun build ./src/node.ts --outdir dist --format esm --target node --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && tsc --emitDeclarationOnly --outDir dist", | ||
| clean: "rimraf dist", | ||
| test: "vitest run", | ||
| e2e: "vitest run --config vitest.e2e.config.ts", | ||
| "test:coverage": "vitest run --coverage", | ||
| prepack: "bun run build", | ||
| "publish:dry": "bun publish --dry-run", | ||
| "publish:gh": "bun publish", | ||
| "version:patch": "bun version patch --no-git-tag-version", | ||
| "version:minor": "bun version minor --no-git-tag-version", | ||
| "version:major": "bun version major --no-git-tag-version", | ||
| lint: "biome check ." | ||
| }, | ||
| dependencies: { | ||
| "@uipath/filesystem": "workspace:*", | ||
| "@uipath/solutionpackager-tool-core": "workspace:*", | ||
| "@uipath/common": "workspace:*" | ||
| }, | ||
| peerDependencies: { | ||
| fflate: "^0.8.2" | ||
| }, | ||
| devDependencies: { | ||
| "@types/node": "^25.5.2", | ||
| "@uipath/resource-builder-tool": "2025.11.0-alpha4535-3530", | ||
| "@uipath/tool-agent": "^2.0.0", | ||
| "@uipath/packager-tool-apiworkflow": "workspace:*", | ||
| "@uipath/packager-tool-connector": "workspace:*", | ||
| "@uipath/packager-tool-flow": "workspace:*", | ||
| "@uipath/packager-tool-functions": "workspace:*", | ||
| "@uipath/packager-tool-webapp": "workspace:*", | ||
| "@uipath/packager-tool-workflowcompiler": "workspace:*", | ||
| "@vitest/coverage-v8": "^4.1.6", | ||
| jsdom: "^30.0.1", | ||
| typescript: "^7.0.2", | ||
| "vite-tsconfig-paths": "^6.1.1", | ||
| vitest: "^4.1.6" | ||
| } | ||
| }; | ||
| // ../packager/project-packager/src/publish/services/orchestrator-feeds-service.ts | ||
| var HEADER_TENANT_ID = "X-UIPATH-TenantId"; | ||
| var FEEDS_PATH = "/api/PackageFeeds/GetFeeds"; | ||
| var FOLDERS_PATH = "/api/FoldersNavigation/GetAllFoldersForCurrentUser"; | ||
| var SDK_USER_AGENT = `${package_default.name.replace(/^@uipath\//, "")}/${package_default.version}`; | ||
| class OrchestratorFeedsService { | ||
| logger; | ||
| constructor() { | ||
| this.logger = new ToolLogger("OrchestratorFeedsService", "Feeds"); | ||
| } | ||
| async getAccessibleFeedsAsync(connection) { | ||
| this.ensureOrchestratorUrl(connection); | ||
| this.logger.info(`Fetching accessible feeds from ${connection.orchestratorUrl}`); | ||
| try { | ||
| const json = await orchestratorGet(connection, FEEDS_PATH); | ||
| return Array.isArray(json) ? json : []; | ||
| } catch (error) { | ||
| const { status, statusText, body } = await describeResponseError(error); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.getAccessibleFeedsFailed", { status, statusText, body })); | ||
| } | ||
| } | ||
| async getFoldersForCurrentUserAsync(connection) { | ||
| this.ensureOrchestratorUrl(connection); | ||
| this.logger.info(`Fetching folders from ${connection.orchestratorUrl}`); | ||
| try { | ||
| const json = await orchestratorGet(connection, FOLDERS_PATH); | ||
| return Array.isArray(json) ? json.map(mapExtendedFolder) : []; | ||
| } catch (error) { | ||
| const { status, statusText, body } = await describeResponseError(error); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.getFoldersForCurrentUserFailed", { status, statusText, body })); | ||
| } | ||
| } | ||
| ensureOrchestratorUrl(connection) { | ||
| if (!connection.orchestratorUrl) { | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorUrlRequired")); | ||
| } | ||
| } | ||
| } | ||
| function mapExtendedFolder(json) { | ||
| return { | ||
| isSelectable: json.IsSelectable, | ||
| hasChildren: json.HasChildren, | ||
| level: json.Level, | ||
| key: json.Key, | ||
| displayName: json.DisplayName, | ||
| fullyQualifiedName: json.FullyQualifiedName, | ||
| description: json.Description, | ||
| folderType: json.FolderType, | ||
| isPersonal: json.IsPersonal, | ||
| provisionType: json.ProvisionType, | ||
| permissionModel: json.PermissionModel, | ||
| parentId: json.ParentId, | ||
| parentKey: json.ParentKey, | ||
| feedType: json.FeedType, | ||
| id: json.Id | ||
| }; | ||
| } | ||
| class OrchestratorResponseError extends Error { | ||
| response; | ||
| constructor(response) { | ||
| super(`Orchestrator request failed with status ${response.status}.`); | ||
| this.response = response; | ||
| this.name = "OrchestratorResponseError"; | ||
| } | ||
| } | ||
| async function orchestratorGet(connection, relativePath) { | ||
| const url = `${normalizeOrchestratorBasePath(connection.orchestratorUrl)}${relativePath}`; | ||
| const response = await fetch(url, { | ||
| method: "GET", | ||
| headers: buildHeaders(connection) | ||
| }); | ||
| if (!response.ok) { | ||
| throw new OrchestratorResponseError(response); | ||
| } | ||
| const text = await response.text(); | ||
| if (text === "" || text === "null") { | ||
| return null; | ||
| } | ||
| return JSON.parse(text); | ||
| } | ||
| function buildHeaders(connection) { | ||
| const headers = {}; | ||
| if (connection.accessToken) { | ||
| headers.Authorization = `Bearer ${connection.accessToken}`; | ||
| } | ||
| if (connection.tenantId) { | ||
| headers[HEADER_TENANT_ID] = connection.tenantId; | ||
| } | ||
| return addSdkUserAgentHeader(headers, SDK_USER_AGENT); | ||
| } | ||
| function normalizeOrchestratorBasePath(orchestratorUrl) { | ||
| let end = orchestratorUrl.length; | ||
| while (end > 0 && orchestratorUrl.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| const trimmed = orchestratorUrl.slice(0, end); | ||
| return /\/orchestrator_$/i.test(trimmed) ? trimmed : `${trimmed}/orchestrator_`; | ||
| } | ||
| async function describeResponseError(error) { | ||
| const response = error?.response; | ||
| if (response) { | ||
| let body = ""; | ||
| try { | ||
| body = (await response.text()).slice(0, 500); | ||
| } catch { | ||
| body = ""; | ||
| } | ||
| return { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| }; | ||
| } | ||
| const cause = error?.cause; | ||
| const message = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error); | ||
| return { status: "?", statusText: message, body: "" }; | ||
| } | ||
| // ../packager/project-packager/src/publish/services/orchestrator-publisher.ts | ||
| var HEADER_FOLDER_ID = "X-UIPATH-OrganizationUnitId"; | ||
| var HEADER_TENANT_ID2 = "X-UIPATH-TenantId"; | ||
| var HEADER_NUGET_API_KEY = "X-NuGet-ApiKey"; | ||
| var ORCHESTRATOR_RELATIVE_URL = "/orchestrator_"; | ||
| var PROCESSES_UPLOAD_PATH = "/odata/Processes/UiPath.Server.Configuration.OData.UploadPackage"; | ||
| var LIBRARIES_UPLOAD_PATH = "/odata/Libraries/UiPath.Server.Configuration.OData.UploadPackage"; | ||
| class OrchestratorPublisher { | ||
| fileSystem; | ||
| logger; | ||
| feedsService; | ||
| constructor(fileSystem, feedsService) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "Orchestrator"); | ||
| this.feedsService = feedsService ?? new OrchestratorFeedsService; | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| if (packagePaths.length === 0) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorNoPackages")); | ||
| } | ||
| if (destination.kind === "OrchestratorCustom" /* OrchestratorCustom */) { | ||
| if (!destination.publishUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorCustomPublishUrlRequired")); | ||
| } | ||
| this.logger.info(`Publishing ${packagePaths.length} package(s) to ${destination.publishUrl} (custom)`); | ||
| return this.postPackages(packagePaths, destination.publishUrl, this.buildCustomHeaders(destination)); | ||
| } | ||
| if (!destination.connectionInfo?.cloudUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorCloudUrlRequired")); | ||
| } | ||
| const orchestratorUrl = this.deriveOrchestratorUrl(destination.connectionInfo); | ||
| let feed; | ||
| try { | ||
| feed = await this.resolveFeed(destination, orchestratorUrl); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorFeedResolutionFailed", { message })); | ||
| } | ||
| const targetUrl = this.buildPublishUrl(orchestratorUrl, feed); | ||
| const headers = this.buildHeaders(destination, feed); | ||
| this.logger.info(`Publishing ${packagePaths.length} package(s) to ${targetUrl} (feed ${feed.name}, ${feed.purpose})`); | ||
| return this.postPackages(packagePaths, targetUrl, headers); | ||
| } | ||
| async postPackages(packagePaths, targetUrl, headers) { | ||
| const form = new FormData; | ||
| for (const packagePath of packagePaths) { | ||
| const data = await this.fileSystem.readFile(packagePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: packagePath })); | ||
| } | ||
| const fileName = this.fileSystem.path.basename(packagePath); | ||
| form.append("file", new Blob([data], { | ||
| type: "application/octet-stream" | ||
| }), fileName); | ||
| } | ||
| const response = await fetch(targetUrl, { | ||
| method: "POST", | ||
| headers, | ||
| body: form | ||
| }); | ||
| if (!response.ok) { | ||
| const body = await this.safeReadBody(response); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorPublishFailed", { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| })); | ||
| } | ||
| this.logger.info("Orchestrator publish completed."); | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, packagePaths); | ||
| } | ||
| async resolveFeed(destination, orchestratorUrl) { | ||
| const connection = { | ||
| orchestratorUrl, | ||
| accessToken: destination.connectionInfo.accessToken, | ||
| tenantId: destination.connectionInfo.tenantId | ||
| }; | ||
| const feeds = await this.feedsService.getAccessibleFeedsAsync(connection); | ||
| if (destination.kind === "OrchestratorPersonalWorkspace" /* OrchestratorPersonalWorkspace */) { | ||
| const folders = await this.feedsService.getFoldersForCurrentUserAsync(connection); | ||
| const personalFolder = folders.find((f) => f.feedType === ExtendedFolderDtoFeedTypeEnum.PersonalWorkspace); | ||
| if (!personalFolder) { | ||
| const foldersDebug = folders.length === 0 ? "<none>" : folders.map((f) => `${f.displayName} (id=${f.id}, feedType=${f.feedType})`).join(", "); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorPersonalWorkspaceFolderNotFound", { folders: foldersDebug })); | ||
| } | ||
| if (personalFolder.id == null) { | ||
| throw new Error(`Personal-workspace folder "${personalFolder.displayName}" has no id; cannot resolve its feed.`); | ||
| } | ||
| const match2 = feeds.find((f) => f.folderId === personalFolder.id); | ||
| if (!match2) { | ||
| this.throwFeedNotFound(destination, feeds); | ||
| } | ||
| return match2; | ||
| } | ||
| const expectedPurpose = destination.kind === "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */ ? PackageFeedDtoPurposeEnum.Libraries : PackageFeedDtoPurposeEnum.Processes; | ||
| const match = feeds.find((f) => f.purpose === expectedPurpose && f.folderId == null); | ||
| if (!match) { | ||
| this.throwFeedNotFound(destination, feeds); | ||
| } | ||
| return match; | ||
| } | ||
| throwFeedNotFound(destination, feeds) { | ||
| const available = feeds.length === 0 ? "<none>" : feeds.map((f) => `${f.name} (purpose=${f.purpose}, folderId=${f.folderId ?? "null"})`).join(", "); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorFeedNotFound", { | ||
| kind: destination.kind, | ||
| available | ||
| })); | ||
| } | ||
| buildPublishUrl(orchestratorUrl, feed) { | ||
| const baseUrl = feed.publishUrl ? feed.publishUrl : `${orchestratorUrl}${feed.purpose === PackageFeedDtoPurposeEnum.Libraries ? LIBRARIES_UPLOAD_PATH : PROCESSES_UPLOAD_PATH}`; | ||
| const parsed = new URL(baseUrl); | ||
| if (feed.id) { | ||
| parsed.searchParams.set("feedId", feed.id); | ||
| } | ||
| return parsed.toString(); | ||
| } | ||
| deriveOrchestratorUrl(connectionInfo) { | ||
| const raw = connectionInfo.cloudUrl ?? ""; | ||
| let end = raw.length; | ||
| while (end > 0 && raw.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| return `${raw.slice(0, end)}${ORCHESTRATOR_RELATIVE_URL}`; | ||
| } | ||
| buildHeaders(destination, feed) { | ||
| const headers = this.buildAuthHeaders(destination.connectionInfo); | ||
| const folderHeader = destination.kind === "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */ ? destination.folderId : feed.folderId; | ||
| if (folderHeader != null) { | ||
| headers[HEADER_FOLDER_ID] = String(folderHeader); | ||
| } | ||
| if (feed.authenticationType === PackageFeedDtoAuthenticationTypeEnum.ApiKey && feed.apiKey) { | ||
| headers[HEADER_NUGET_API_KEY] = feed.apiKey; | ||
| } | ||
| return headers; | ||
| } | ||
| buildCustomHeaders(destination) { | ||
| const headers = this.buildAuthHeaders(destination.connectionInfo); | ||
| if (destination.folderId != null) { | ||
| headers[HEADER_FOLDER_ID] = String(destination.folderId); | ||
| } | ||
| if (destination.apiKey) { | ||
| headers[HEADER_NUGET_API_KEY] = destination.apiKey; | ||
| } | ||
| return headers; | ||
| } | ||
| buildAuthHeaders(connectionInfo) { | ||
| const headers = {}; | ||
| if (connectionInfo.accessToken) { | ||
| headers.Authorization = `Bearer ${connectionInfo.accessToken}`; | ||
| } | ||
| if (connectionInfo.tenantId) { | ||
| headers[HEADER_TENANT_ID2] = connectionInfo.tenantId; | ||
| } | ||
| return headers; | ||
| } | ||
| async safeReadBody(response) { | ||
| try { | ||
| const text = await response.text(); | ||
| return text.slice(0, 500); | ||
| } catch { | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/project-publisher.ts | ||
| class ProjectPublisher { | ||
| fileSystem; | ||
| logger; | ||
| localFolderPublisher; | ||
| nugetFeedPublisher; | ||
| orchestratorPublisher; | ||
| constructor(fileSystem, publishers) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "Publish"); | ||
| this.localFolderPublisher = publishers?.localFolder ?? new LocalFolderPublisher(fileSystem); | ||
| this.nugetFeedPublisher = publishers?.nugetFeed ?? new NugetFeedPublisher(fileSystem); | ||
| this.orchestratorPublisher = publishers?.orchestrator ?? new OrchestratorPublisher(fileSystem); | ||
| } | ||
| async publishAsync(options) { | ||
| if (!options.packagePaths || options.packagePaths.length === 0) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.atLeastOnePackage")); | ||
| } | ||
| for (const path of options.packagePaths) { | ||
| if (!await this.fileSystem.exists(path)) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.packageNotFound", { path })); | ||
| } | ||
| } | ||
| try { | ||
| const destination = options.destination; | ||
| switch (destination.kind) { | ||
| case "LocalFolder" /* LocalFolder */: | ||
| return await this.localFolderPublisher.publishAsync(options.packagePaths, destination); | ||
| case "NugetFeed" /* NugetFeed */: | ||
| return await this.nugetFeedPublisher.publishAsync(options.packagePaths, destination); | ||
| case "OrchestratorPersonalWorkspace" /* OrchestratorPersonalWorkspace */: | ||
| case "OrchestratorTenantProcesses" /* OrchestratorTenantProcesses */: | ||
| case "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */: | ||
| case "OrchestratorCustom" /* OrchestratorCustom */: | ||
| return await this.orchestratorPublisher.publishAsync(options.packagePaths, destination); | ||
| default: { | ||
| const exhaustive = destination; | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.unknownDestination", { destination: JSON.stringify(exhaustive) })); | ||
| } | ||
| } | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| const localized = translate.t("solutionpackager.publish.errors.publishFailed", { message }); | ||
| this.logger.error(localized); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, localized); | ||
| } | ||
| } | ||
| } | ||
| export { | ||
| signNupkgsAsync, | ||
| setGlobalLogHandler, | ||
| resolveProducedNupkgsAsync, | ||
| ToolsFactory, | ||
| ToolLogger, | ||
| TelemetryService, | ||
| TelemetryNames, | ||
| RulesConfigFileType, | ||
| PublishDestinationKind, | ||
| ProjectValidateOptionsValidator, | ||
| ProjectValidateOptions, | ||
| ProjectToolExecutor, | ||
| ProjectRestoreOptions, | ||
| ProjectPublisher, | ||
| ProjectPublishOptions, | ||
| ProjectPackager, | ||
| ProjectPackOptions, | ||
| ProjectLoader, | ||
| ProjectCleanupOptions, | ||
| ProjectBuildOptionsValidator, | ||
| ProjectBuildOptions, | ||
| PackagerParametersValidator, | ||
| PackagerParameters, | ||
| PackService, | ||
| GovernancePolicyService, | ||
| ConsoleTelemetryProvider, | ||
| BrowserContextStorage | ||
| }; | ||
| //# debugId=1FC1AE2280E19D9064756E2164756E21 |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
+7
-5
| #!/usr/bin/env node | ||
| import { | ||
| Command, | ||
| metadata, | ||
| registerCommands | ||
| } from "./packager-tool-e0yjd91y.js"; | ||
| import"./packager-tool-y7hv8v54.js"; | ||
| } from "./packager-tool-evraq47v.js"; | ||
| import"./packager-tool-1v8fmky0.js"; | ||
| import"./packager-tool-h1tyrbff.js"; | ||
| import { | ||
| Command | ||
| } from "./packager-tool-bprnbg91.js"; | ||
| import"./packager-tool-4pvh3k50.js"; | ||
| import"./packager-tool-y7hv8v54.js"; | ||
| import"./packager-tool-t01cjyjh.js"; | ||
| import"./packager-tool-9qecd4wb.js"; | ||
| import"./packager-tool-4pvh3k50.js"; | ||
| import"./packager-tool-5arsyj36.js"; | ||
@@ -22,2 +24,2 @@ import"./packager-tool-wckvcay0.js"; | ||
| //# debugId=1BEEB2B24358010764756E2164756E21 | ||
| //# debugId=DD47897ACDB6FFAB64756E2164756E21 |
+5
-4
| import { | ||
| metadata, | ||
| registerCommands | ||
| } from "./packager-tool-e0yjd91y.js"; | ||
| import"./packager-tool-y7hv8v54.js"; | ||
| } from "./packager-tool-evraq47v.js"; | ||
| import"./packager-tool-1v8fmky0.js"; | ||
| import"./packager-tool-h1tyrbff.js"; | ||
| import"./packager-tool-bprnbg91.js"; | ||
| import"./packager-tool-4pvh3k50.js"; | ||
| import"./packager-tool-y7hv8v54.js"; | ||
| import"./packager-tool-t01cjyjh.js"; | ||
| import"./packager-tool-9qecd4wb.js"; | ||
| import"./packager-tool-4pvh3k50.js"; | ||
| import"./packager-tool-5arsyj36.js"; | ||
@@ -18,2 +19,2 @@ import"./packager-tool-wckvcay0.js"; | ||
| //# debugId=FD67DA0FE081F42264756E2164756E21 | ||
| //# debugId=5FBBAAC25D1BBA2A64756E2164756E21 |
+4
-3
| { | ||
| "name": "@uipath/api-workflow-tool", | ||
| "license": "MIT", | ||
| "version": "1.201.0-preview.115", | ||
| "version": "1.201.0-preview.121", | ||
| "description": "Run UiPath API Workflows locally.", | ||
@@ -22,3 +22,4 @@ "private": false, | ||
| ".": "./dist/tool.js", | ||
| "./packager-tool": "./dist/packager-tool.js" | ||
| "./packager-tool": "./dist/packager-tool.js", | ||
| "./executor-tool": "./dist/executor-tool.js" | ||
| }, | ||
@@ -28,3 +29,3 @@ "files": [ | ||
| ], | ||
| "gitHead": "f1086b73654d7728cb71f280588b3e0c77d535fc" | ||
| "gitHead": "c70ccfc0b12e637441d67df1d212b71d7784b5f8" | ||
| } |
| import { | ||
| BrowserContextStorage, | ||
| ConsoleTelemetryProvider, | ||
| ProjectPackager, | ||
| TelemetryService, | ||
| ToolLogger, | ||
| setGlobalLogHandler | ||
| } from "./packager-tool-6ph5rsqt.js"; | ||
| import { | ||
| translate | ||
| } from "./packager-tool-h1tyrbff.js"; | ||
| import"./packager-tool-wckvcay0.js"; | ||
| // ../filesystem/dist/index.browser.js | ||
| var __create = Object.create; | ||
| var __getProtoOf = Object.getPrototypeOf; | ||
| var __defProp = Object.defineProperty; | ||
| var __getOwnPropNames = Object.getOwnPropertyNames; | ||
| var __hasOwnProp = Object.prototype.hasOwnProperty; | ||
| function __accessProp(key) { | ||
| return this[key]; | ||
| } | ||
| var __toESMCache_node; | ||
| var __toESMCache_esm; | ||
| var __toESM = (mod, isNodeMode, target) => { | ||
| var canCache = mod != null && typeof mod === "object"; | ||
| if (canCache) { | ||
| var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap; | ||
| var cached = cache.get(mod); | ||
| if (cached) | ||
| return cached; | ||
| } | ||
| target = mod != null ? __create(__getProtoOf(mod)) : {}; | ||
| const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; | ||
| for (let key of __getOwnPropNames(mod)) | ||
| if (!__hasOwnProp.call(to, key)) | ||
| __defProp(to, key, { | ||
| get: __accessProp.bind(mod, key), | ||
| enumerable: true | ||
| }); | ||
| if (canCache) | ||
| cache.set(mod, to); | ||
| return to; | ||
| }; | ||
| var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); | ||
| var require_just_once = __commonJS((exports, module) => { | ||
| module.exports = once; | ||
| function once(fn) { | ||
| var called, value; | ||
| if (typeof fn !== "function") { | ||
| throw new Error("expected a function but got " + fn); | ||
| } | ||
| return function wrap() { | ||
| if (called) { | ||
| return value; | ||
| } | ||
| called = true; | ||
| value = fn.apply(this, arguments); | ||
| return value; | ||
| }; | ||
| } | ||
| }); | ||
| var require_text_min = __commonJS((exports) => { | ||
| (function(scope) { | ||
| function B(r, e) { | ||
| var f; | ||
| return r instanceof Buffer ? f = r : f = Buffer.from(r.buffer, r.byteOffset, r.byteLength), f.toString(e); | ||
| } | ||
| var w = function(r) { | ||
| return Buffer.from(r); | ||
| }; | ||
| function h(r) { | ||
| for (var e = 0, f = Math.min(256 * 256, r.length + 1), n = new Uint16Array(f), i = [], o = 0;; ) { | ||
| var t = e < r.length; | ||
| if (!t || o >= f - 1) { | ||
| var s = n.subarray(0, o), m = s; | ||
| if (i.push(String.fromCharCode.apply(null, m)), !t) | ||
| return i.join(""); | ||
| r = r.subarray(e), e = 0, o = 0; | ||
| } | ||
| var a = r[e++]; | ||
| if ((a & 128) === 0) | ||
| n[o++] = a; | ||
| else if ((a & 224) === 192) { | ||
| var d = r[e++] & 63; | ||
| n[o++] = (a & 31) << 6 | d; | ||
| } else if ((a & 240) === 224) { | ||
| var d = r[e++] & 63, l = r[e++] & 63; | ||
| n[o++] = (a & 31) << 12 | d << 6 | l; | ||
| } else if ((a & 248) === 240) { | ||
| var d = r[e++] & 63, l = r[e++] & 63, R = r[e++] & 63, c = (a & 7) << 18 | d << 12 | l << 6 | R; | ||
| c > 65535 && (c -= 65536, n[o++] = c >>> 10 & 1023 | 55296, c = 56320 | c & 1023), n[o++] = c; | ||
| } | ||
| } | ||
| } | ||
| function F(r) { | ||
| for (var e = 0, f = r.length, n = 0, i = Math.max(32, f + (f >>> 1) + 7), o = new Uint8Array(i >>> 3 << 3);e < f; ) { | ||
| var t = r.charCodeAt(e++); | ||
| if (t >= 55296 && t <= 56319) { | ||
| if (e < f) { | ||
| var s = r.charCodeAt(e); | ||
| (s & 64512) === 56320 && (++e, t = ((t & 1023) << 10) + (s & 1023) + 65536); | ||
| } | ||
| if (t >= 55296 && t <= 56319) | ||
| continue; | ||
| } | ||
| if (n + 4 > o.length) { | ||
| i += 8, i *= 1 + e / r.length * 2, i = i >>> 3 << 3; | ||
| var m = new Uint8Array(i); | ||
| m.set(o), o = m; | ||
| } | ||
| if ((t & 4294967168) === 0) { | ||
| o[n++] = t; | ||
| continue; | ||
| } else if ((t & 4294965248) === 0) | ||
| o[n++] = t >>> 6 & 31 | 192; | ||
| else if ((t & 4294901760) === 0) | ||
| o[n++] = t >>> 12 & 15 | 224, o[n++] = t >>> 6 & 63 | 128; | ||
| else if ((t & 4292870144) === 0) | ||
| o[n++] = t >>> 18 & 7 | 240, o[n++] = t >>> 12 & 63 | 128, o[n++] = t >>> 6 & 63 | 128; | ||
| else | ||
| continue; | ||
| o[n++] = t & 63 | 128; | ||
| } | ||
| return o.slice ? o.slice(0, n) : o.subarray(0, n); | ||
| } | ||
| var u = "Failed to ", p = function(r, e, f) { | ||
| if (r) | ||
| throw new Error("".concat(u).concat(e, ": the '").concat(f, "' option is unsupported.")); | ||
| }; | ||
| var x = typeof Buffer == "function" && Buffer.from; | ||
| var A = x ? w : F; | ||
| function v() { | ||
| this.encoding = "utf-8"; | ||
| } | ||
| v.prototype.encode = function(r, e) { | ||
| return p(e && e.stream, "encode", "stream"), A(r); | ||
| }; | ||
| function U(r) { | ||
| var e; | ||
| try { | ||
| var f = new Blob([r], { type: "text/plain;charset=UTF-8" }); | ||
| e = URL.createObjectURL(f); | ||
| var n = new XMLHttpRequest; | ||
| return n.open("GET", e, false), n.send(), n.responseText; | ||
| } finally { | ||
| e && URL.revokeObjectURL(e); | ||
| } | ||
| } | ||
| var O = !x && typeof Blob == "function" && typeof URL == "function" && typeof URL.createObjectURL == "function", S = ["utf-8", "utf8", "unicode-1-1-utf-8"], T = h; | ||
| x ? T = B : O && (T = function(r) { | ||
| try { | ||
| return U(r); | ||
| } catch (e) { | ||
| return h(r); | ||
| } | ||
| }); | ||
| var y = "construct 'TextDecoder'", E = "".concat(u, " ").concat(y, ": the "); | ||
| function g(r, e) { | ||
| p(e && e.fatal, y, "fatal"), r = r || "utf-8"; | ||
| var f; | ||
| if (x ? f = Buffer.isEncoding(r) : f = S.indexOf(r.toLowerCase()) !== -1, !f) | ||
| throw new RangeError("".concat(E, " encoding label provided ('").concat(r, "') is invalid.")); | ||
| this.encoding = r, this.fatal = false, this.ignoreBOM = false; | ||
| } | ||
| g.prototype.decode = function(r, e) { | ||
| p(e && e.stream, "decode", "stream"); | ||
| var f; | ||
| return r instanceof Uint8Array ? f = r : r.buffer instanceof ArrayBuffer ? f = new Uint8Array(r.buffer) : f = new Uint8Array(r), T(f, this.encoding); | ||
| }; | ||
| scope.TextEncoder = scope.TextEncoder || v; | ||
| scope.TextDecoder = scope.TextDecoder || g; | ||
| })(typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : exports); | ||
| }); | ||
| var require_browser = __commonJS((exports, module) => { | ||
| require_text_min(); | ||
| module.exports = { | ||
| encode: (string) => new TextEncoder().encode(string), | ||
| decode: (buffer) => new TextDecoder().decode(buffer) | ||
| }; | ||
| }); | ||
| var require_just_debounce_it = __commonJS((exports, module) => { | ||
| module.exports = debounce; | ||
| function debounce(fn, wait, callFirst) { | ||
| var timeout; | ||
| return function() { | ||
| if (!wait) { | ||
| return fn.apply(this, arguments); | ||
| } | ||
| var context = this; | ||
| var args = arguments; | ||
| var callNow = callFirst && !timeout; | ||
| clearTimeout(timeout); | ||
| timeout = setTimeout(function() { | ||
| timeout = null; | ||
| if (!callNow) { | ||
| return fn.apply(context, args); | ||
| } | ||
| }, wait); | ||
| if (callNow) { | ||
| return fn.apply(this, arguments); | ||
| } | ||
| }; | ||
| } | ||
| }); | ||
| var require_path = __commonJS((exports, module) => { | ||
| function normalizePath(path) { | ||
| if (path.length === 0) { | ||
| return "."; | ||
| } | ||
| let parts = splitPath(path); | ||
| parts = parts.reduce(reducer, []); | ||
| return joinPath(...parts); | ||
| } | ||
| function resolvePath(...paths) { | ||
| let result = ""; | ||
| for (let path of paths) { | ||
| if (path.startsWith("/")) { | ||
| result = path; | ||
| } else { | ||
| result = normalizePath(joinPath(result, path)); | ||
| } | ||
| } | ||
| return result; | ||
| } | ||
| function joinPath(...parts) { | ||
| if (parts.length === 0) | ||
| return ""; | ||
| let path = parts.join("/"); | ||
| path = path.replace(/\/{2,}/g, "/"); | ||
| return path; | ||
| } | ||
| function splitPath(path) { | ||
| if (path.length === 0) | ||
| return []; | ||
| if (path === "/") | ||
| return ["/"]; | ||
| let parts = path.split("/"); | ||
| if (parts[parts.length - 1] === "") { | ||
| parts.pop(); | ||
| } | ||
| if (path[0] === "/") { | ||
| parts[0] = "/"; | ||
| } else { | ||
| if (parts[0] !== ".") { | ||
| parts.unshift("."); | ||
| } | ||
| } | ||
| return parts; | ||
| } | ||
| function dirname(path) { | ||
| const last = path.lastIndexOf("/"); | ||
| if (last === -1) | ||
| throw new Error(`Cannot get dirname of "${path}"`); | ||
| if (last === 0) | ||
| return "/"; | ||
| return path.slice(0, last); | ||
| } | ||
| function basename(path) { | ||
| if (path === "/") | ||
| throw new Error(`Cannot get basename of "${path}"`); | ||
| const last = path.lastIndexOf("/"); | ||
| if (last === -1) | ||
| return path; | ||
| return path.slice(last + 1); | ||
| } | ||
| function reducer(ancestors, current) { | ||
| if (ancestors.length === 0) { | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| if (current === ".") | ||
| return ancestors; | ||
| if (current === "..") { | ||
| if (ancestors.length === 1) { | ||
| if (ancestors[0] === "/") { | ||
| throw new Error("Unable to normalize path - traverses above root directory"); | ||
| } | ||
| if (ancestors[0] === ".") { | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| } | ||
| if (ancestors[ancestors.length - 1] === "..") { | ||
| ancestors.push(".."); | ||
| return ancestors; | ||
| } else { | ||
| ancestors.pop(); | ||
| return ancestors; | ||
| } | ||
| } | ||
| ancestors.push(current); | ||
| return ancestors; | ||
| } | ||
| module.exports = { | ||
| join: joinPath, | ||
| normalize: normalizePath, | ||
| split: splitPath, | ||
| basename, | ||
| dirname, | ||
| resolve: resolvePath | ||
| }; | ||
| }); | ||
| var require_errors = __commonJS((exports, module) => { | ||
| function Err(name) { | ||
| return class extends Error { | ||
| constructor(...args) { | ||
| super(...args); | ||
| this.code = name; | ||
| if (this.message) { | ||
| this.message = name + ": " + this.message; | ||
| } else { | ||
| this.message = name; | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| var EEXIST = Err("EEXIST"); | ||
| var ENOENT = Err("ENOENT"); | ||
| var ENOTDIR = Err("ENOTDIR"); | ||
| var ENOTEMPTY = Err("ENOTEMPTY"); | ||
| var ETIMEDOUT = Err("ETIMEDOUT"); | ||
| var EISDIR = Err("EISDIR"); | ||
| module.exports = { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, ETIMEDOUT, EISDIR }; | ||
| }); | ||
| var require_CacheFS = __commonJS((exports, module) => { | ||
| var path = require_path(); | ||
| var { EEXIST, ENOENT, ENOTDIR, ENOTEMPTY, EISDIR } = require_errors(); | ||
| var STAT = 0; | ||
| module.exports = class CacheFS { | ||
| constructor() {} | ||
| _makeRoot(root = new Map) { | ||
| root.set(STAT, { mode: 511, type: "dir", size: 0, ino: 0, mtimeMs: Date.now() }); | ||
| return root; | ||
| } | ||
| activate(superblock = null) { | ||
| if (superblock === null) { | ||
| this._root = new Map([["/", this._makeRoot()]]); | ||
| } else if (typeof superblock === "string") { | ||
| this._root = new Map([["/", this._makeRoot(this.parse(superblock))]]); | ||
| } else { | ||
| this._root = superblock; | ||
| } | ||
| } | ||
| get activated() { | ||
| return !!this._root; | ||
| } | ||
| deactivate() { | ||
| this._root = undefined; | ||
| } | ||
| size() { | ||
| return this._countInodes(this._root.get("/")) - 1; | ||
| } | ||
| _countInodes(map) { | ||
| let count = 1; | ||
| for (let [key, val] of map) { | ||
| if (key === STAT) | ||
| continue; | ||
| count += this._countInodes(val); | ||
| } | ||
| return count; | ||
| } | ||
| autoinc() { | ||
| let val = this._maxInode(this._root.get("/")) + 1; | ||
| return val; | ||
| } | ||
| _maxInode(map) { | ||
| let max = map.get(STAT).ino; | ||
| for (let [key, val] of map) { | ||
| if (key === STAT) | ||
| continue; | ||
| max = Math.max(max, this._maxInode(val)); | ||
| } | ||
| return max; | ||
| } | ||
| print(root = this._root.get("/")) { | ||
| let str = ""; | ||
| const printTree = (root2, indent) => { | ||
| for (let [file, node] of root2) { | ||
| if (file === 0) | ||
| continue; | ||
| let stat = node.get(STAT); | ||
| let mode = stat.mode.toString(8); | ||
| str += `${"\t".repeat(indent)}${file} ${mode}`; | ||
| if (stat.type === "file") { | ||
| str += ` ${stat.size} ${stat.mtimeMs} | ||
| `; | ||
| } else { | ||
| str += ` | ||
| `; | ||
| printTree(node, indent + 1); | ||
| } | ||
| } | ||
| }; | ||
| printTree(root, 0); | ||
| return str; | ||
| } | ||
| parse(print) { | ||
| let autoinc = 0; | ||
| function mk(stat) { | ||
| const ino = ++autoinc; | ||
| const type = stat.length === 1 ? "dir" : "file"; | ||
| let [mode, size, mtimeMs] = stat; | ||
| mode = parseInt(mode, 8); | ||
| size = size ? parseInt(size) : 0; | ||
| mtimeMs = mtimeMs ? parseInt(mtimeMs) : Date.now(); | ||
| return new Map([[STAT, { mode, type, size, mtimeMs, ino }]]); | ||
| } | ||
| let lines = print.trim().split(` | ||
| `); | ||
| let _root = this._makeRoot(); | ||
| let stack = [ | ||
| { indent: -1, node: _root }, | ||
| { indent: 0, node: null } | ||
| ]; | ||
| for (let line of lines) { | ||
| let prefix = line.match(/^\t*/)[0]; | ||
| let indent = prefix.length; | ||
| line = line.slice(indent); | ||
| let [filename, ...stat] = line.split("\t"); | ||
| let node = mk(stat); | ||
| if (indent <= stack[stack.length - 1].indent) { | ||
| while (indent <= stack[stack.length - 1].indent) { | ||
| stack.pop(); | ||
| } | ||
| } | ||
| stack.push({ indent, node }); | ||
| let cd = stack[stack.length - 2].node; | ||
| cd.set(filename, node); | ||
| } | ||
| return _root; | ||
| } | ||
| _lookup(filepath, follow = true) { | ||
| let dir = this._root; | ||
| let partialPath = "/"; | ||
| let parts = path.split(filepath); | ||
| for (let i = 0;i < parts.length; ++i) { | ||
| let part = parts[i]; | ||
| dir = dir.get(part); | ||
| if (!dir) | ||
| throw new ENOENT(filepath); | ||
| if (follow || i < parts.length - 1) { | ||
| const stat = dir.get(STAT); | ||
| if (stat.type === "symlink") { | ||
| let target = path.resolve(partialPath, stat.target); | ||
| dir = this._lookup(target); | ||
| } | ||
| if (!partialPath) { | ||
| partialPath = part; | ||
| } else { | ||
| partialPath = path.join(partialPath, part); | ||
| } | ||
| } | ||
| } | ||
| return dir; | ||
| } | ||
| mkdir(filepath, { mode }) { | ||
| if (filepath === "/") | ||
| throw new EEXIST; | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| if (dir.has(basename)) { | ||
| throw new EEXIST; | ||
| } | ||
| let entry = new Map; | ||
| let stat = { | ||
| mode, | ||
| type: "dir", | ||
| size: 0, | ||
| mtimeMs: Date.now(), | ||
| ino: this.autoinc() | ||
| }; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| } | ||
| rmdir(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| if (dir.get(STAT).type !== "dir") | ||
| throw new ENOTDIR; | ||
| if (dir.size > 1) | ||
| throw new ENOTEMPTY; | ||
| let parent = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| parent.delete(basename); | ||
| } | ||
| readdir(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| if (dir.get(STAT).type !== "dir") | ||
| throw new ENOTDIR; | ||
| return [...dir.keys()].filter((key) => typeof key === "string"); | ||
| } | ||
| writeStat(filepath, size, { mode }) { | ||
| let ino; | ||
| let oldStat; | ||
| try { | ||
| oldStat = this.stat(filepath); | ||
| } catch (err) {} | ||
| if (oldStat !== undefined) { | ||
| if (oldStat.type === "dir") { | ||
| throw new EISDIR; | ||
| } | ||
| if (mode == null) { | ||
| mode = oldStat.mode; | ||
| } | ||
| ino = oldStat.ino; | ||
| } | ||
| if (mode == null) { | ||
| mode = 438; | ||
| } | ||
| if (ino == null) { | ||
| ino = this.autoinc(); | ||
| } | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| let stat = { | ||
| mode, | ||
| type: "file", | ||
| size, | ||
| mtimeMs: Date.now(), | ||
| ino | ||
| }; | ||
| let entry = new Map; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| return stat; | ||
| } | ||
| unlink(filepath) { | ||
| let parent = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| parent.delete(basename); | ||
| } | ||
| rename(oldFilepath, newFilepath) { | ||
| let basename = path.basename(newFilepath); | ||
| let entry = this._lookup(oldFilepath); | ||
| let destDir = this._lookup(path.dirname(newFilepath)); | ||
| destDir.set(basename, entry); | ||
| this.unlink(oldFilepath); | ||
| } | ||
| stat(filepath) { | ||
| return this._lookup(filepath).get(STAT); | ||
| } | ||
| lstat(filepath) { | ||
| return this._lookup(filepath, false).get(STAT); | ||
| } | ||
| readlink(filepath) { | ||
| return this._lookup(filepath, false).get(STAT).target; | ||
| } | ||
| symlink(target, filepath) { | ||
| let ino, mode; | ||
| try { | ||
| let oldStat = this.stat(filepath); | ||
| if (mode === null) { | ||
| mode = oldStat.mode; | ||
| } | ||
| ino = oldStat.ino; | ||
| } catch (err) {} | ||
| if (mode == null) { | ||
| mode = 40960; | ||
| } | ||
| if (ino == null) { | ||
| ino = this.autoinc(); | ||
| } | ||
| let dir = this._lookup(path.dirname(filepath)); | ||
| let basename = path.basename(filepath); | ||
| let stat = { | ||
| mode, | ||
| type: "symlink", | ||
| target, | ||
| size: 0, | ||
| mtimeMs: Date.now(), | ||
| ino | ||
| }; | ||
| let entry = new Map; | ||
| entry.set(STAT, stat); | ||
| dir.set(basename, entry); | ||
| return stat; | ||
| } | ||
| _du(dir) { | ||
| let size = 0; | ||
| for (const [name, entry] of dir.entries()) { | ||
| if (name === STAT) { | ||
| size += entry.size; | ||
| } else { | ||
| size += this._du(entry); | ||
| } | ||
| } | ||
| return size; | ||
| } | ||
| du(filepath) { | ||
| let dir = this._lookup(filepath); | ||
| return this._du(dir); | ||
| } | ||
| }; | ||
| }); | ||
| var require_idb_keyval_cjs = __commonJS((exports) => { | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| class Store { | ||
| constructor(dbName = "keyval-store", storeName = "keyval") { | ||
| this.storeName = storeName; | ||
| this._dbName = dbName; | ||
| this._storeName = storeName; | ||
| this._init(); | ||
| } | ||
| _init() { | ||
| if (this._dbp) { | ||
| return; | ||
| } | ||
| this._dbp = new Promise((resolve, reject) => { | ||
| const openreq = indexedDB.open(this._dbName); | ||
| openreq.onerror = () => reject(openreq.error); | ||
| openreq.onsuccess = () => resolve(openreq.result); | ||
| openreq.onupgradeneeded = () => { | ||
| openreq.result.createObjectStore(this._storeName); | ||
| }; | ||
| }); | ||
| } | ||
| _withIDBStore(type, callback) { | ||
| this._init(); | ||
| return this._dbp.then((db) => new Promise((resolve, reject) => { | ||
| const transaction = db.transaction(this.storeName, type); | ||
| transaction.oncomplete = () => resolve(); | ||
| transaction.onabort = transaction.onerror = () => reject(transaction.error); | ||
| callback(transaction.objectStore(this.storeName)); | ||
| })); | ||
| } | ||
| _close() { | ||
| this._init(); | ||
| return this._dbp.then((db) => { | ||
| db.close(); | ||
| this._dbp = undefined; | ||
| }); | ||
| } | ||
| } | ||
| var store; | ||
| function getDefaultStore() { | ||
| if (!store) | ||
| store = new Store; | ||
| return store; | ||
| } | ||
| function get(key, store2 = getDefaultStore()) { | ||
| let req; | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| req = store3.get(key); | ||
| }).then(() => req.result); | ||
| } | ||
| function set(key, value, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.put(value, key); | ||
| }); | ||
| } | ||
| function update(key, updater, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| const req = store3.get(key); | ||
| req.onsuccess = () => { | ||
| store3.put(updater(req.result), key); | ||
| }; | ||
| }); | ||
| } | ||
| function del(key, store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.delete(key); | ||
| }); | ||
| } | ||
| function clear(store2 = getDefaultStore()) { | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| store3.clear(); | ||
| }); | ||
| } | ||
| function keys(store2 = getDefaultStore()) { | ||
| const keys2 = []; | ||
| return store2._withIDBStore("readwrite", (store3) => { | ||
| (store3.openKeyCursor || store3.openCursor).call(store3).onsuccess = function() { | ||
| if (!this.result) | ||
| return; | ||
| keys2.push(this.result.key); | ||
| this.result.continue(); | ||
| }; | ||
| }).then(() => keys2); | ||
| } | ||
| function close(store2 = getDefaultStore()) { | ||
| return store2._close(); | ||
| } | ||
| exports.Store = Store; | ||
| exports.get = get; | ||
| exports.set = set; | ||
| exports.update = update; | ||
| exports.del = del; | ||
| exports.clear = clear; | ||
| exports.keys = keys; | ||
| exports.close = close; | ||
| }); | ||
| var require_IdbBackend = __commonJS((exports, module) => { | ||
| var idb = require_idb_keyval_cjs(); | ||
| module.exports = class IdbBackend { | ||
| constructor(dbname, storename) { | ||
| this._database = dbname; | ||
| this._storename = storename; | ||
| this._store = new idb.Store(this._database, this._storename); | ||
| } | ||
| saveSuperblock(superblock) { | ||
| return idb.set("!root", superblock, this._store); | ||
| } | ||
| loadSuperblock() { | ||
| return idb.get("!root", this._store); | ||
| } | ||
| readFile(inode) { | ||
| return idb.get(inode, this._store); | ||
| } | ||
| writeFile(inode, data) { | ||
| return idb.set(inode, data, this._store); | ||
| } | ||
| unlink(inode) { | ||
| return idb.del(inode, this._store); | ||
| } | ||
| wipe() { | ||
| return idb.clear(this._store); | ||
| } | ||
| close() { | ||
| return idb.close(this._store); | ||
| } | ||
| }; | ||
| }); | ||
| var require_HttpBackend = __commonJS((exports, module) => { | ||
| module.exports = class HttpBackend { | ||
| constructor(url) { | ||
| this._url = url; | ||
| } | ||
| loadSuperblock() { | ||
| return fetch(this._url + "/.superblock.txt").then((res) => res.ok ? res.text() : null); | ||
| } | ||
| async readFile(filepath) { | ||
| const res = await fetch(this._url + filepath); | ||
| if (res.status === 200) { | ||
| return res.arrayBuffer(); | ||
| } else { | ||
| throw new Error("ENOENT"); | ||
| } | ||
| } | ||
| async sizeFile(filepath) { | ||
| const res = await fetch(this._url + filepath, { method: "HEAD" }); | ||
| if (res.status === 200) { | ||
| return res.headers.get("content-length"); | ||
| } else { | ||
| throw new Error("ENOENT"); | ||
| } | ||
| } | ||
| }; | ||
| }); | ||
| var require_Mutex = __commonJS((exports, module) => { | ||
| var idb = require_idb_keyval_cjs(); | ||
| var sleep = (ms) => new Promise((r) => setTimeout(r, ms)); | ||
| module.exports = class Mutex { | ||
| constructor(dbname, storename) { | ||
| this._id = Math.random(); | ||
| this._database = dbname; | ||
| this._storename = storename; | ||
| this._store = new idb.Store(this._database, this._storename); | ||
| this._lock = null; | ||
| } | ||
| async has({ margin = 2000 } = {}) { | ||
| if (this._lock && this._lock.holder === this._id) { | ||
| const now = Date.now(); | ||
| if (this._lock.expires > now + margin) { | ||
| return true; | ||
| } else { | ||
| return await this.renew(); | ||
| } | ||
| } else { | ||
| return false; | ||
| } | ||
| } | ||
| async renew({ ttl = 5000 } = {}) { | ||
| let success; | ||
| await idb.update("lock", (current) => { | ||
| const now = Date.now(); | ||
| const expires = now + ttl; | ||
| success = current && current.holder === this._id; | ||
| this._lock = success ? { holder: this._id, expires } : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| return success; | ||
| } | ||
| async acquire({ ttl = 5000 } = {}) { | ||
| let success; | ||
| let expired; | ||
| let doubleLock; | ||
| await idb.update("lock", (current) => { | ||
| const now = Date.now(); | ||
| const expires = now + ttl; | ||
| expired = current && current.expires < now; | ||
| success = current === undefined || expired; | ||
| doubleLock = current && current.holder === this._id; | ||
| this._lock = success ? { holder: this._id, expires } : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| if (doubleLock) { | ||
| throw new Error("Mutex double-locked"); | ||
| } | ||
| return success; | ||
| } | ||
| async wait({ interval = 100, limit = 6000, ttl } = {}) { | ||
| while (limit--) { | ||
| if (await this.acquire({ ttl })) | ||
| return true; | ||
| await sleep(interval); | ||
| } | ||
| throw new Error("Mutex timeout"); | ||
| } | ||
| async release({ force = false } = {}) { | ||
| let success; | ||
| let doubleFree; | ||
| let someoneElseHasIt; | ||
| await idb.update("lock", (current) => { | ||
| success = force || current && current.holder === this._id; | ||
| doubleFree = current === undefined; | ||
| someoneElseHasIt = current && current.holder !== this._id; | ||
| this._lock = success ? undefined : current; | ||
| return this._lock; | ||
| }, this._store); | ||
| await idb.close(this._store); | ||
| if (!success && !force) { | ||
| if (doubleFree) | ||
| throw new Error("Mutex double-freed"); | ||
| if (someoneElseHasIt) | ||
| throw new Error("Mutex lost ownership"); | ||
| } | ||
| return success; | ||
| } | ||
| }; | ||
| }); | ||
| var require_Mutex2 = __commonJS((exports, module) => { | ||
| module.exports = class Mutex { | ||
| constructor(name) { | ||
| this._id = Math.random(); | ||
| this._database = name; | ||
| this._has = false; | ||
| this._release = null; | ||
| } | ||
| async has() { | ||
| return this._has; | ||
| } | ||
| async acquire() { | ||
| return new Promise((resolve) => { | ||
| navigator.locks.request(this._database + "_lock", { ifAvailable: true }, (lock) => { | ||
| this._has = !!lock; | ||
| resolve(!!lock); | ||
| return new Promise((resolve2) => { | ||
| this._release = resolve2; | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async wait({ timeout = 600000 } = {}) { | ||
| return new Promise((resolve, reject) => { | ||
| const controller = new AbortController; | ||
| setTimeout(() => { | ||
| controller.abort(); | ||
| reject(new Error("Mutex timeout")); | ||
| }, timeout); | ||
| navigator.locks.request(this._database + "_lock", { signal: controller.signal }, (lock) => { | ||
| this._has = !!lock; | ||
| resolve(!!lock); | ||
| return new Promise((resolve2) => { | ||
| this._release = resolve2; | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async release({ force = false } = {}) { | ||
| this._has = false; | ||
| if (this._release) { | ||
| this._release(); | ||
| } else if (force) { | ||
| navigator.locks.request(this._database + "_lock", { steal: true }, (lock) => true); | ||
| } | ||
| } | ||
| }; | ||
| }); | ||
| var require_DefaultBackend = __commonJS((exports, module) => { | ||
| var { encode, decode } = require_browser(); | ||
| var debounce = require_just_debounce_it(); | ||
| var CacheFS = require_CacheFS(); | ||
| var { ENOENT, ENOTEMPTY, ETIMEDOUT } = require_errors(); | ||
| var IdbBackend = require_IdbBackend(); | ||
| var HttpBackend = require_HttpBackend(); | ||
| var Mutex = require_Mutex(); | ||
| var Mutex2 = require_Mutex2(); | ||
| var path = require_path(); | ||
| module.exports = class DefaultBackend { | ||
| constructor() { | ||
| this.saveSuperblock = debounce(() => { | ||
| this.flush(); | ||
| }, 500); | ||
| } | ||
| async init(name, { | ||
| wipe, | ||
| url, | ||
| urlauto, | ||
| fileDbName = name, | ||
| db = null, | ||
| fileStoreName = name + "_files", | ||
| lockDbName = name + "_lock", | ||
| lockStoreName = name + "_lock" | ||
| } = {}) { | ||
| this._name = name; | ||
| this._idb = db || new IdbBackend(fileDbName, fileStoreName); | ||
| this._mutex = navigator.locks ? new Mutex2(name) : new Mutex(lockDbName, lockStoreName); | ||
| this._cache = new CacheFS(name); | ||
| this._opts = { wipe, url }; | ||
| this._needsWipe = !!wipe; | ||
| if (url) { | ||
| this._http = new HttpBackend(url); | ||
| this._urlauto = !!urlauto; | ||
| } | ||
| } | ||
| async activate() { | ||
| if (this._cache.activated) | ||
| return; | ||
| if (this._needsWipe) { | ||
| this._needsWipe = false; | ||
| await this._idb.wipe(); | ||
| await this._mutex.release({ force: true }); | ||
| } | ||
| if (!await this._mutex.has()) | ||
| await this._mutex.wait(); | ||
| const root = await this._idb.loadSuperblock(); | ||
| if (root) { | ||
| this._cache.activate(root); | ||
| } else if (this._http) { | ||
| const text = await this._http.loadSuperblock(); | ||
| this._cache.activate(text); | ||
| await this._saveSuperblock(); | ||
| } else { | ||
| this._cache.activate(); | ||
| } | ||
| if (await this._mutex.has()) { | ||
| return; | ||
| } else { | ||
| throw new ETIMEDOUT; | ||
| } | ||
| } | ||
| async deactivate() { | ||
| if (await this._mutex.has()) { | ||
| await this._saveSuperblock(); | ||
| } | ||
| this._cache.deactivate(); | ||
| try { | ||
| await this._mutex.release(); | ||
| } catch (e) { | ||
| console.log(e); | ||
| } | ||
| await this._idb.close(); | ||
| } | ||
| async _saveSuperblock() { | ||
| if (this._cache.activated) { | ||
| this._lastSavedAt = Date.now(); | ||
| await this._idb.saveSuperblock(this._cache._root); | ||
| } | ||
| } | ||
| _writeStat(filepath, size, opts) { | ||
| let dirparts = path.split(path.dirname(filepath)); | ||
| let dir = dirparts.shift(); | ||
| for (let dirpart of dirparts) { | ||
| dir = path.join(dir, dirpart); | ||
| try { | ||
| this._cache.mkdir(dir, { mode: 511 }); | ||
| } catch (e) {} | ||
| } | ||
| return this._cache.writeStat(filepath, size, opts); | ||
| } | ||
| async readFile(filepath, opts) { | ||
| const encoding = typeof opts === "string" ? opts : opts && opts.encoding; | ||
| if (encoding && encoding !== "utf8") | ||
| throw new Error('Only "utf8" encoding is supported in readFile'); | ||
| let data = null, stat = null; | ||
| try { | ||
| stat = this._cache.stat(filepath); | ||
| data = await this._idb.readFile(stat.ino); | ||
| } catch (e) { | ||
| if (!this._urlauto) | ||
| throw e; | ||
| } | ||
| if (!data && this._http) { | ||
| let lstat = this._cache.lstat(filepath); | ||
| while (lstat.type === "symlink") { | ||
| filepath = path.resolve(path.dirname(filepath), lstat.target); | ||
| lstat = this._cache.lstat(filepath); | ||
| } | ||
| data = await this._http.readFile(filepath); | ||
| } | ||
| if (data) { | ||
| if (!stat || stat.size != data.byteLength) { | ||
| stat = await this._writeStat(filepath, data.byteLength, { mode: stat ? stat.mode : 438 }); | ||
| this.saveSuperblock(); | ||
| } | ||
| if (encoding === "utf8") { | ||
| data = decode(data); | ||
| } else { | ||
| data.toString = () => decode(data); | ||
| } | ||
| } | ||
| if (!stat) | ||
| throw new ENOENT(filepath); | ||
| return data; | ||
| } | ||
| async writeFile(filepath, data, opts) { | ||
| const { mode, encoding = "utf8" } = opts; | ||
| if (typeof data === "string") { | ||
| if (encoding !== "utf8") { | ||
| throw new Error('Only "utf8" encoding is supported in writeFile'); | ||
| } | ||
| data = encode(data); | ||
| } | ||
| const stat = await this._cache.writeStat(filepath, data.byteLength, { mode }); | ||
| await this._idb.writeFile(stat.ino, data); | ||
| } | ||
| async unlink(filepath, opts) { | ||
| const stat = this._cache.lstat(filepath); | ||
| this._cache.unlink(filepath); | ||
| if (stat.type !== "symlink") { | ||
| await this._idb.unlink(stat.ino); | ||
| } | ||
| } | ||
| readdir(filepath, opts) { | ||
| return this._cache.readdir(filepath); | ||
| } | ||
| mkdir(filepath, opts) { | ||
| const { mode = 511 } = opts; | ||
| this._cache.mkdir(filepath, { mode }); | ||
| } | ||
| rmdir(filepath, opts) { | ||
| if (filepath === "/") { | ||
| throw new ENOTEMPTY; | ||
| } | ||
| this._cache.rmdir(filepath); | ||
| } | ||
| rename(oldFilepath, newFilepath) { | ||
| this._cache.rename(oldFilepath, newFilepath); | ||
| } | ||
| stat(filepath, opts) { | ||
| return this._cache.stat(filepath); | ||
| } | ||
| lstat(filepath, opts) { | ||
| return this._cache.lstat(filepath); | ||
| } | ||
| readlink(filepath, opts) { | ||
| return this._cache.readlink(filepath); | ||
| } | ||
| symlink(target, filepath) { | ||
| this._cache.symlink(target, filepath); | ||
| } | ||
| async backFile(filepath, opts) { | ||
| let size = await this._http.sizeFile(filepath); | ||
| await this._writeStat(filepath, size, opts); | ||
| } | ||
| du(filepath) { | ||
| return this._cache.du(filepath); | ||
| } | ||
| flush() { | ||
| return this._saveSuperblock(); | ||
| } | ||
| }; | ||
| }); | ||
| var require_Stat = __commonJS((exports, module) => { | ||
| module.exports = class Stat { | ||
| constructor(stats) { | ||
| this.type = stats.type; | ||
| this.mode = stats.mode; | ||
| this.size = stats.size; | ||
| this.ino = stats.ino; | ||
| this.mtimeMs = stats.mtimeMs; | ||
| this.ctimeMs = stats.ctimeMs || stats.mtimeMs; | ||
| this.uid = 1; | ||
| this.gid = 1; | ||
| this.dev = 1; | ||
| } | ||
| isFile() { | ||
| return this.type === "file"; | ||
| } | ||
| isDirectory() { | ||
| return this.type === "dir"; | ||
| } | ||
| isSymbolicLink() { | ||
| return this.type === "symlink"; | ||
| } | ||
| }; | ||
| }); | ||
| var require_PromisifiedFS = __commonJS((exports, module) => { | ||
| var DefaultBackend = require_DefaultBackend(); | ||
| var Stat = require_Stat(); | ||
| var path = require_path(); | ||
| function cleanParamsFilepathOpts(filepath, opts, ...rest) { | ||
| filepath = path.normalize(filepath); | ||
| if (typeof opts === "undefined" || typeof opts === "function") { | ||
| opts = {}; | ||
| } | ||
| if (typeof opts === "string") { | ||
| opts = { | ||
| encoding: opts | ||
| }; | ||
| } | ||
| return [filepath, opts, ...rest]; | ||
| } | ||
| function cleanParamsFilepathDataOpts(filepath, data, opts, ...rest) { | ||
| filepath = path.normalize(filepath); | ||
| if (typeof opts === "undefined" || typeof opts === "function") { | ||
| opts = {}; | ||
| } | ||
| if (typeof opts === "string") { | ||
| opts = { | ||
| encoding: opts | ||
| }; | ||
| } | ||
| return [filepath, data, opts, ...rest]; | ||
| } | ||
| function cleanParamsFilepathFilepath(oldFilepath, newFilepath, ...rest) { | ||
| return [path.normalize(oldFilepath), path.normalize(newFilepath), ...rest]; | ||
| } | ||
| module.exports = class PromisifiedFS { | ||
| constructor(name, options = {}) { | ||
| this.init = this.init.bind(this); | ||
| this.readFile = this._wrap(this.readFile, cleanParamsFilepathOpts, false); | ||
| this.writeFile = this._wrap(this.writeFile, cleanParamsFilepathDataOpts, true); | ||
| this.unlink = this._wrap(this.unlink, cleanParamsFilepathOpts, true); | ||
| this.readdir = this._wrap(this.readdir, cleanParamsFilepathOpts, false); | ||
| this.mkdir = this._wrap(this.mkdir, cleanParamsFilepathOpts, true); | ||
| this.rmdir = this._wrap(this.rmdir, cleanParamsFilepathOpts, true); | ||
| this.rename = this._wrap(this.rename, cleanParamsFilepathFilepath, true); | ||
| this.stat = this._wrap(this.stat, cleanParamsFilepathOpts, false); | ||
| this.lstat = this._wrap(this.lstat, cleanParamsFilepathOpts, false); | ||
| this.readlink = this._wrap(this.readlink, cleanParamsFilepathOpts, false); | ||
| this.symlink = this._wrap(this.symlink, cleanParamsFilepathFilepath, true); | ||
| this.backFile = this._wrap(this.backFile, cleanParamsFilepathOpts, true); | ||
| this.du = this._wrap(this.du, cleanParamsFilepathOpts, false); | ||
| this._deactivationPromise = null; | ||
| this._deactivationTimeout = null; | ||
| this._activationPromise = null; | ||
| this._operations = new Set; | ||
| if (name) { | ||
| this.init(name, options); | ||
| } | ||
| } | ||
| async init(...args) { | ||
| if (this._initPromiseResolve) | ||
| await this._initPromise; | ||
| this._initPromise = this._init(...args); | ||
| return this._initPromise; | ||
| } | ||
| async _init(name, options = {}) { | ||
| await this._gracefulShutdown(); | ||
| if (this._activationPromise) | ||
| await this._deactivate(); | ||
| if (this._backend && this._backend.destroy) { | ||
| await this._backend.destroy(); | ||
| } | ||
| this._backend = options.backend || new DefaultBackend; | ||
| if (this._backend.init) { | ||
| await this._backend.init(name, options); | ||
| } | ||
| if (this._initPromiseResolve) { | ||
| this._initPromiseResolve(); | ||
| this._initPromiseResolve = null; | ||
| } | ||
| if (!options.defer) { | ||
| this.stat("/"); | ||
| } | ||
| } | ||
| async _gracefulShutdown() { | ||
| if (this._operations.size > 0) { | ||
| this._isShuttingDown = true; | ||
| await new Promise((resolve) => this._gracefulShutdownResolve = resolve); | ||
| this._isShuttingDown = false; | ||
| this._gracefulShutdownResolve = null; | ||
| } | ||
| } | ||
| _wrap(fn, paramCleaner, mutating) { | ||
| return async (...args) => { | ||
| args = paramCleaner(...args); | ||
| let op = { | ||
| name: fn.name, | ||
| args | ||
| }; | ||
| this._operations.add(op); | ||
| try { | ||
| await this._activate(); | ||
| return await fn.apply(this, args); | ||
| } finally { | ||
| this._operations.delete(op); | ||
| if (mutating) | ||
| this._backend.saveSuperblock(); | ||
| if (this._operations.size === 0) { | ||
| if (!this._deactivationTimeout) | ||
| clearTimeout(this._deactivationTimeout); | ||
| this._deactivationTimeout = setTimeout(this._deactivate.bind(this), 500); | ||
| } | ||
| } | ||
| }; | ||
| } | ||
| async _activate() { | ||
| if (!this._initPromise) | ||
| console.warn(new Error(`Attempted to use LightningFS ${this._name} before it was initialized.`)); | ||
| await this._initPromise; | ||
| if (this._deactivationTimeout) { | ||
| clearTimeout(this._deactivationTimeout); | ||
| this._deactivationTimeout = null; | ||
| } | ||
| if (this._deactivationPromise) | ||
| await this._deactivationPromise; | ||
| this._deactivationPromise = null; | ||
| if (!this._activationPromise) { | ||
| this._activationPromise = this._backend.activate ? this._backend.activate() : Promise.resolve(); | ||
| } | ||
| await this._activationPromise; | ||
| } | ||
| async _deactivate() { | ||
| if (this._activationPromise) | ||
| await this._activationPromise; | ||
| if (!this._deactivationPromise) { | ||
| this._deactivationPromise = this._backend.deactivate ? this._backend.deactivate() : Promise.resolve(); | ||
| } | ||
| this._activationPromise = null; | ||
| if (this._gracefulShutdownResolve) | ||
| this._gracefulShutdownResolve(); | ||
| return this._deactivationPromise; | ||
| } | ||
| async readFile(filepath, opts) { | ||
| return this._backend.readFile(filepath, opts); | ||
| } | ||
| async writeFile(filepath, data, opts) { | ||
| await this._backend.writeFile(filepath, data, opts); | ||
| return null; | ||
| } | ||
| async unlink(filepath, opts) { | ||
| await this._backend.unlink(filepath, opts); | ||
| return null; | ||
| } | ||
| async readdir(filepath, opts) { | ||
| return this._backend.readdir(filepath, opts); | ||
| } | ||
| async mkdir(filepath, opts) { | ||
| await this._backend.mkdir(filepath, opts); | ||
| return null; | ||
| } | ||
| async rmdir(filepath, opts) { | ||
| await this._backend.rmdir(filepath, opts); | ||
| return null; | ||
| } | ||
| async rename(oldFilepath, newFilepath) { | ||
| await this._backend.rename(oldFilepath, newFilepath); | ||
| return null; | ||
| } | ||
| async stat(filepath, opts) { | ||
| const data = await this._backend.stat(filepath, opts); | ||
| return new Stat(data); | ||
| } | ||
| async lstat(filepath, opts) { | ||
| const data = await this._backend.lstat(filepath, opts); | ||
| return new Stat(data); | ||
| } | ||
| async readlink(filepath, opts) { | ||
| return this._backend.readlink(filepath, opts); | ||
| } | ||
| async symlink(target, filepath) { | ||
| await this._backend.symlink(target, filepath); | ||
| return null; | ||
| } | ||
| async backFile(filepath, opts) { | ||
| await this._backend.backFile(filepath, opts); | ||
| return null; | ||
| } | ||
| async du(filepath) { | ||
| return this._backend.du(filepath); | ||
| } | ||
| async flush() { | ||
| return this._backend.flush(); | ||
| } | ||
| }; | ||
| }); | ||
| var require_src = __commonJS((exports, module) => { | ||
| var once = require_just_once(); | ||
| var PromisifiedFS = require_PromisifiedFS(); | ||
| function wrapCallback(opts, cb) { | ||
| if (typeof opts === "function") { | ||
| cb = opts; | ||
| } | ||
| cb = once(cb); | ||
| const resolve = (...args) => cb(null, ...args); | ||
| return [resolve, cb]; | ||
| } | ||
| module.exports = class FS { | ||
| constructor(...args) { | ||
| this.promises = new PromisifiedFS(...args); | ||
| this.init = this.init.bind(this); | ||
| this.readFile = this.readFile.bind(this); | ||
| this.writeFile = this.writeFile.bind(this); | ||
| this.unlink = this.unlink.bind(this); | ||
| this.readdir = this.readdir.bind(this); | ||
| this.mkdir = this.mkdir.bind(this); | ||
| this.rmdir = this.rmdir.bind(this); | ||
| this.rename = this.rename.bind(this); | ||
| this.stat = this.stat.bind(this); | ||
| this.lstat = this.lstat.bind(this); | ||
| this.readlink = this.readlink.bind(this); | ||
| this.symlink = this.symlink.bind(this); | ||
| this.backFile = this.backFile.bind(this); | ||
| this.du = this.du.bind(this); | ||
| this.flush = this.flush.bind(this); | ||
| } | ||
| init(name, options) { | ||
| return this.promises.init(name, options); | ||
| } | ||
| readFile(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readFile(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| writeFile(filepath, data, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.writeFile(filepath, data, opts).then(resolve).catch(reject); | ||
| } | ||
| unlink(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.unlink(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| readdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| mkdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.mkdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| rmdir(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.rmdir(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| rename(oldFilepath, newFilepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.rename(oldFilepath, newFilepath).then(resolve).catch(reject); | ||
| } | ||
| stat(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.stat(filepath).then(resolve).catch(reject); | ||
| } | ||
| lstat(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.lstat(filepath).then(resolve).catch(reject); | ||
| } | ||
| readlink(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.readlink(filepath).then(resolve).catch(reject); | ||
| } | ||
| symlink(target, filepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.symlink(target, filepath).then(resolve).catch(reject); | ||
| } | ||
| backFile(filepath, opts, cb) { | ||
| const [resolve, reject] = wrapCallback(opts, cb); | ||
| this.promises.backFile(filepath, opts).then(resolve).catch(reject); | ||
| } | ||
| du(filepath, cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.du(filepath).then(resolve).catch(reject); | ||
| } | ||
| flush(cb) { | ||
| const [resolve, reject] = wrapCallback(cb); | ||
| this.promises.flush().then(resolve).catch(reject); | ||
| } | ||
| }; | ||
| }); | ||
| var import_lightning_fs = __toESM(require_src(), 1); | ||
| var LOCK_MAX_WAIT_MS = 20000; | ||
| var IN_MEMORY_LOCK_TAILS_KEY = Symbol.for("@uipath/filesystem/lock-tails"); | ||
| var getInMemoryLockTails = () => { | ||
| const globalsHost = globalThis; | ||
| const existing = globalsHost[IN_MEMORY_LOCK_TAILS_KEY]; | ||
| if (existing && typeof existing.get === "function" && typeof existing.set === "function" && typeof existing.delete === "function") { | ||
| return existing; | ||
| } | ||
| const created = new Map; | ||
| globalsHost[IN_MEMORY_LOCK_TAILS_KEY] = created; | ||
| return created; | ||
| }; | ||
| var getWebLocks = () => { | ||
| if (typeof navigator === "undefined") | ||
| return; | ||
| return navigator.locks; | ||
| }; | ||
| class BrowserFileSystem { | ||
| initialized = false; | ||
| fsInstance = null; | ||
| async init() { | ||
| if (this.initialized) | ||
| return; | ||
| this.fsInstance = new import_lightning_fs.default("uipcli-fs"); | ||
| this.initialized = true; | ||
| } | ||
| normalizePath(p) { | ||
| const isAbs = p.startsWith("/"); | ||
| const segments = p.split("/"); | ||
| const normalized = []; | ||
| for (const seg of segments) { | ||
| if (seg === "." || seg === "") | ||
| continue; | ||
| if (seg === "..") { | ||
| normalized.pop(); | ||
| } else { | ||
| normalized.push(seg); | ||
| } | ||
| } | ||
| return (isAbs ? "/" : "") + normalized.join("/"); | ||
| } | ||
| path = { | ||
| join: (...paths) => { | ||
| const joined = paths.filter(Boolean).join("/"); | ||
| return this.normalizePath(joined); | ||
| }, | ||
| resolve: (...paths) => { | ||
| let resolved = ""; | ||
| for (let i = paths.length - 1;i >= 0; i--) { | ||
| const p = paths[i]; | ||
| if (!p) | ||
| continue; | ||
| resolved = resolved ? `${p}/${resolved}` : p; | ||
| if (p.startsWith("/")) | ||
| break; | ||
| } | ||
| if (!resolved.startsWith("/")) { | ||
| resolved = `/${resolved}`; | ||
| } | ||
| return this.normalizePath(resolved); | ||
| }, | ||
| relative: (from, to) => { | ||
| const fromParts = this.normalizePath(from).split("/").filter(Boolean); | ||
| const toParts = this.normalizePath(to).split("/").filter(Boolean); | ||
| let common = 0; | ||
| while (common < fromParts.length && common < toParts.length && fromParts[common] === toParts[common]) { | ||
| common++; | ||
| } | ||
| const ups = Array(fromParts.length - common).fill(".."); | ||
| const downs = toParts.slice(common); | ||
| return [...ups, ...downs].join("/") || "."; | ||
| }, | ||
| dirname: (p) => { | ||
| const parts = p.split("/").filter(Boolean); | ||
| parts.pop(); | ||
| return `/${parts.join("/")}`; | ||
| }, | ||
| isAbsolute: (p) => p.startsWith("/"), | ||
| basename: (p, ext) => { | ||
| const parts = p.split("/").filter(Boolean); | ||
| const base = parts[parts.length - 1] || ""; | ||
| if (ext && base.endsWith(ext)) | ||
| return base.slice(0, -ext.length); | ||
| return base; | ||
| } | ||
| }; | ||
| env = { | ||
| cwd: () => "/", | ||
| homedir: () => "/home", | ||
| tmpdir: () => "/tmp", | ||
| getenv: (_key) => { | ||
| return; | ||
| } | ||
| }; | ||
| utils = { | ||
| open: async (url) => { | ||
| if (typeof window !== "undefined") { | ||
| window.open(url, "_blank"); | ||
| } | ||
| } | ||
| }; | ||
| async prepare() { | ||
| await this.init(); | ||
| } | ||
| getFs() { | ||
| if (!this.fsInstance) { | ||
| throw new Error("Browser filesystem is not initialized."); | ||
| } | ||
| return this.fsInstance; | ||
| } | ||
| async readFile(path, options) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| if (options) { | ||
| return await fs.promises.readFile(path, "utf8"); | ||
| } | ||
| const content = await fs.promises.readFile(path); | ||
| return new Uint8Array(content); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return null; | ||
| throw error; | ||
| } | ||
| } | ||
| async writeFile(filePath, data) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const dir = this.path.dirname(filePath); | ||
| if (dir && dir !== "/") { | ||
| await this.mkdir(dir); | ||
| } | ||
| await fs.promises.writeFile(filePath, data); | ||
| } | ||
| async appendFile(filePath, data) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const dir = this.path.dirname(filePath); | ||
| if (dir && dir !== "/") { | ||
| await this.mkdir(dir); | ||
| } | ||
| const existing = await this.readFile(filePath, "utf-8"); | ||
| const head = existing ?? ""; | ||
| const tail = typeof data === "string" ? data : new TextDecoder().decode(data); | ||
| await fs.promises.writeFile(filePath, head + tail); | ||
| } | ||
| async readdir(path) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| return await fs.promises.readdir(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return []; | ||
| throw error; | ||
| } | ||
| } | ||
| async stat(path) { | ||
| try { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const stats = await fs.promises.stat(path); | ||
| return { | ||
| isFile: () => stats.isFile(), | ||
| isDirectory: () => stats.isDirectory(), | ||
| size: stats.size, | ||
| mtimeMs: stats.mtimeMs | ||
| }; | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return null; | ||
| throw error; | ||
| } | ||
| } | ||
| async exists(path) { | ||
| return await this.stat(path) !== null; | ||
| } | ||
| async mkdir(path) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const normalizedPath = this.normalizePath(path); | ||
| if (normalizedPath === "/" || normalizedPath === "") { | ||
| return; | ||
| } | ||
| const parentDir = this.path.dirname(normalizedPath); | ||
| if (parentDir !== normalizedPath && parentDir !== "/") { | ||
| await this.mkdir(parentDir); | ||
| } else if (parentDir === "/") { | ||
| await this.checkRootDirectory(); | ||
| } | ||
| try { | ||
| await fs.promises.mkdir(normalizedPath); | ||
| } catch (error) { | ||
| if (this.isEexist(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| } | ||
| async acquireLock(lockPath) { | ||
| const canonical = this.normalizePath(this.path.isAbsolute(lockPath) ? lockPath : `/${lockPath}`); | ||
| const name = `@uipath/filesystem:lock:${canonical}`; | ||
| const webLocks = getWebLocks(); | ||
| if (webLocks) { | ||
| return await this.acquireWebLock(webLocks, name); | ||
| } | ||
| return this.acquireInMemoryLock(name); | ||
| } | ||
| async acquireWebLock(webLocks, name) { | ||
| const abortController = new AbortController; | ||
| const timeoutHandle = setTimeout(() => { | ||
| abortController.abort(); | ||
| }, LOCK_MAX_WAIT_MS); | ||
| return await new Promise((resolveAcquire, rejectAcquire) => { | ||
| let releaseHeld; | ||
| const requested = webLocks.request(name, { signal: abortController.signal }, () => new Promise((resolveHeld) => { | ||
| clearTimeout(timeoutHandle); | ||
| releaseHeld = resolveHeld; | ||
| resolveAcquire(async () => { | ||
| resolveHeld(); | ||
| }); | ||
| })); | ||
| requested.catch((error) => { | ||
| clearTimeout(timeoutHandle); | ||
| if (releaseHeld) { | ||
| return; | ||
| } | ||
| if (error?.name === "AbortError") { | ||
| rejectAcquire(new Error(`ELOCKED: timed out waiting for lock on ${name}`)); | ||
| return; | ||
| } | ||
| rejectAcquire(error); | ||
| }); | ||
| }); | ||
| } | ||
| acquireInMemoryLock(name) { | ||
| const tails = getInMemoryLockTails(); | ||
| const prior = tails.get(name) ?? Promise.resolve(); | ||
| let releaseHeld; | ||
| const held = new Promise((resolve) => { | ||
| releaseHeld = resolve; | ||
| }); | ||
| const chained = prior.then(() => held); | ||
| tails.set(name, chained); | ||
| chained.then(() => { | ||
| if (tails.get(name) === chained) { | ||
| tails.delete(name); | ||
| } | ||
| }); | ||
| return new Promise((resolveAcquire, rejectAcquire) => { | ||
| const timer = setTimeout(() => { | ||
| releaseHeld(); | ||
| rejectAcquire(new Error(`ELOCKED: timed out waiting for lock on ${name}`)); | ||
| }, LOCK_MAX_WAIT_MS); | ||
| prior.then(() => { | ||
| clearTimeout(timer); | ||
| resolveAcquire(async () => { | ||
| releaseHeld(); | ||
| }); | ||
| }); | ||
| }); | ||
| } | ||
| async rm(path) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| const stats = await this.stat(path); | ||
| if (!stats) { | ||
| return; | ||
| } | ||
| if (stats.isDirectory()) { | ||
| const entries = await this.readdir(path); | ||
| for (const entry of entries) { | ||
| await this.rm(this.path.join(path, entry)); | ||
| } | ||
| try { | ||
| await fs.promises.rmdir(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| return; | ||
| } | ||
| try { | ||
| await fs.promises.unlink(path); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) | ||
| return; | ||
| throw error; | ||
| } | ||
| } | ||
| async rename(oldPath, newPath) { | ||
| await this.init(); | ||
| const fs = this.getFs(); | ||
| await fs.promises.rename(oldPath, newPath); | ||
| } | ||
| async realpath(filePath) { | ||
| return filePath; | ||
| } | ||
| async getTempDir() { | ||
| const dir = `/tmp/uipath-fs-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`; | ||
| await this.mkdir(dir); | ||
| return dir; | ||
| } | ||
| async copyDirectory(sourcePath, destPath) { | ||
| const sourceStats = await this.stat(sourcePath); | ||
| if (!sourceStats) { | ||
| throw new Error(`Source directory does not exist: ${sourcePath}`); | ||
| } | ||
| if (!sourceStats.isDirectory()) { | ||
| throw new Error(`Source path is not a directory: ${sourcePath}`); | ||
| } | ||
| await this.mkdir(destPath); | ||
| const entries = await this.readdir(sourcePath); | ||
| for (const entry of entries) { | ||
| const srcEntry = this.path.join(sourcePath, entry); | ||
| const destEntry = this.path.join(destPath, entry); | ||
| const entryStats = await this.stat(srcEntry); | ||
| if (!entryStats) | ||
| continue; | ||
| if (entryStats.isDirectory()) { | ||
| await this.copyDirectory(srcEntry, destEntry); | ||
| } else if (entryStats.isFile()) { | ||
| const content = await this.readFile(srcEntry); | ||
| if (content !== null) { | ||
| await this.writeFile(destEntry, content); | ||
| } | ||
| } | ||
| } | ||
| } | ||
| isEnoent(error) { | ||
| return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT"; | ||
| } | ||
| isEexist(error) { | ||
| return typeof error === "object" && error !== null && "code" in error && error.code === "EEXIST"; | ||
| } | ||
| async checkRootDirectory() { | ||
| try { | ||
| const fs = this.getFs(); | ||
| await fs.promises.stat("/"); | ||
| } catch (error) { | ||
| if (this.isEnoent(error)) { | ||
| const fs = this.getFs(); | ||
| await fs.promises.mkdir("/"); | ||
| return; | ||
| } | ||
| throw error; | ||
| } | ||
| } | ||
| } | ||
| var defaultFs = new BrowserFileSystem; | ||
| var initPromise = defaultFs.init(); | ||
| // ../packager/project-packager/src/base-browser-packager-factory.ts | ||
| var sharedFileSystem = null; | ||
| var GLOBAL_FS_KEY = "__uipath_sharedFileSystem"; | ||
| class BaseBrowserPackagerFactory { | ||
| async getOrCreateFileSystem(config) { | ||
| if (config?.fileSystem) { | ||
| return config.fileSystem; | ||
| } | ||
| const globalRecord = globalThis; | ||
| if (!sharedFileSystem) { | ||
| sharedFileSystem = globalRecord[GLOBAL_FS_KEY] ?? null; | ||
| } | ||
| if (!sharedFileSystem) { | ||
| const fs = new BrowserFileSystem; | ||
| try { | ||
| await fs.init(); | ||
| } catch (error) { | ||
| if (error instanceof Error && error.message.includes("Mount point is already in use")) { | ||
| fs.initialized = true; | ||
| } else { | ||
| throw error; | ||
| } | ||
| } | ||
| sharedFileSystem = fs; | ||
| globalRecord[GLOBAL_FS_KEY] = fs; | ||
| } | ||
| return sharedFileSystem; | ||
| } | ||
| getOrCreateTelemetryService(config) { | ||
| if (config?.telemetryService) { | ||
| return config.telemetryService; | ||
| } | ||
| const provider = new ConsoleTelemetryProvider; | ||
| const contextStorage = new BrowserContextStorage; | ||
| return new TelemetryService(provider, contextStorage); | ||
| } | ||
| configureLogHandler(config) { | ||
| if (config?.logHandler) { | ||
| setGlobalLogHandler(config.logHandler); | ||
| } | ||
| } | ||
| configureLanguage(config) { | ||
| const language = config?.language ?? "en"; | ||
| translate.setLocale(language); | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/browser-project-packager-factory.ts | ||
| class BrowserProjectPackagerFactory extends BaseBrowserPackagerFactory { | ||
| async createAsync(config) { | ||
| const logger = new ToolLogger("ProjectPackagerFactory", "Create"); | ||
| this.configureLanguage(config); | ||
| this.configureLogHandler(config); | ||
| logger.info("Creating ProjectPackager instance..."); | ||
| const fileSystem = await this.getOrCreateFileSystem(config); | ||
| const telemetryService = this.getOrCreateTelemetryService(config); | ||
| const projectPackager = new ProjectPackager(fileSystem, telemetryService); | ||
| logger.info("ProjectPackager created successfully."); | ||
| return projectPackager; | ||
| } | ||
| } | ||
| async function createBrowserProjectPackager(options) { | ||
| const factory = new BrowserProjectPackagerFactory; | ||
| return factory.createAsync(options); | ||
| } | ||
| export { | ||
| createBrowserProjectPackager, | ||
| BaseBrowserPackagerFactory | ||
| }; | ||
| //# debugId=BEA0DF616EA4E56964756E2164756E21 |
Sorry, the diff of this file is too big to display
| import { | ||
| BrowserContextStorage, | ||
| ConsoleTelemetryProvider, | ||
| GovernancePolicyService, | ||
| PackService, | ||
| PackagerParameters, | ||
| PackagerParametersValidator, | ||
| ProjectBuildOptionsValidator, | ||
| ProjectLoader, | ||
| ProjectPackager, | ||
| ProjectToolExecutor, | ||
| ProjectValidateOptionsValidator, | ||
| RulesConfigFileType, | ||
| TelemetryNames, | ||
| TelemetryService, | ||
| ToolLogger, | ||
| ToolsFactory, | ||
| resolveProducedNupkgsAsync, | ||
| setGlobalLogHandler, | ||
| signNupkgsAsync | ||
| } from "./packager-tool-6ph5rsqt.js"; | ||
| import { | ||
| ToolErrorCodes, | ||
| ToolResult, | ||
| translate | ||
| } from "./packager-tool-h1tyrbff.js"; | ||
| import"./packager-tool-wckvcay0.js"; | ||
| // ../packager/project-packager/src/models/project-restore-options.ts | ||
| class ProjectRestoreOptions extends PackagerParameters { | ||
| } | ||
| // ../packager/project-packager/src/models/project-validate-options.ts | ||
| class ProjectValidateOptions extends ProjectRestoreOptions { | ||
| validateOptions = { | ||
| skipAnalyze: false, | ||
| skipValidate: false, | ||
| governanceFileType: "Default" /* Default */ | ||
| }; | ||
| } | ||
| // ../packager/project-packager/src/models/project-build-options.ts | ||
| class ProjectBuildOptions extends ProjectValidateOptions { | ||
| outputType; | ||
| } | ||
| // ../packager/project-packager/src/models/project-cleanup-options.ts | ||
| class ProjectCleanupOptions extends PackagerParameters { | ||
| dryRun = false; | ||
| skipImports = false; | ||
| lockKey; | ||
| } | ||
| // ../packager/project-packager/src/models/project-pack-options.ts | ||
| class ProjectPackOptions extends ProjectBuildOptions { | ||
| destinationPath; | ||
| package; | ||
| signingInfo; | ||
| packOptions; | ||
| } | ||
| // ../packager/project-packager/src/publish/models/publish-options.ts | ||
| var PublishDestinationKind; | ||
| ((PublishDestinationKind2) => { | ||
| PublishDestinationKind2["LocalFolder"] = "LocalFolder"; | ||
| PublishDestinationKind2["NugetFeed"] = "NugetFeed"; | ||
| PublishDestinationKind2["OrchestratorPersonalWorkspace"] = "OrchestratorPersonalWorkspace"; | ||
| PublishDestinationKind2["OrchestratorTenantProcesses"] = "OrchestratorTenantProcesses"; | ||
| PublishDestinationKind2["OrchestratorSharedLibraries"] = "OrchestratorSharedLibraries"; | ||
| PublishDestinationKind2["OrchestratorCustom"] = "OrchestratorCustom"; | ||
| })(PublishDestinationKind ||= {}); | ||
| class ProjectPublishOptions { | ||
| packagePaths; | ||
| destination; | ||
| constructor(packagePaths, destination) { | ||
| this.packagePaths = packagePaths; | ||
| this.destination = destination; | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/local-folder-publisher.ts | ||
| class LocalFolderPublisher { | ||
| fileSystem; | ||
| logger; | ||
| constructor(fileSystem) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "LocalFolder"); | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| const overwrite = destination.overwrite ?? true; | ||
| if (!destination.folderPath) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.localFolderRequired")); | ||
| } | ||
| if (!await this.fileSystem.exists(destination.folderPath)) { | ||
| await this.fileSystem.mkdir(destination.folderPath); | ||
| } | ||
| const written = []; | ||
| for (const sourcePath of packagePaths) { | ||
| const fileName = this.fileSystem.path.basename(sourcePath); | ||
| const destPath = this.fileSystem.path.join(destination.folderPath, fileName); | ||
| if (!overwrite && await this.fileSystem.exists(destPath)) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.localFolderFileExists", { path: destPath })); | ||
| } | ||
| const data = await this.fileSystem.readFile(sourcePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: sourcePath })); | ||
| } | ||
| await this.fileSystem.writeFile(destPath, data); | ||
| written.push(destPath); | ||
| this.logger.info(`Copied package to ${destPath}`); | ||
| } | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, written); | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/nuget-feed-publisher.ts | ||
| var NUGET_V3_PACKAGE_PUBLISH_TYPE = "PackagePublish/2.0.0"; | ||
| class NugetFeedPublisher { | ||
| fileSystem; | ||
| logger; | ||
| constructor(fileSystem) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "NugetFeed"); | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| if (!destination.feedUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetFeedUrlRequired")); | ||
| } | ||
| let pushUrl; | ||
| try { | ||
| pushUrl = await this.resolvePushUrl(destination.feedUrl, destination.apiKey); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetPushUrlResolutionFailed", { feedUrl: destination.feedUrl, message })); | ||
| } | ||
| const published = []; | ||
| for (const packagePath of packagePaths) { | ||
| const data = await this.fileSystem.readFile(packagePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: packagePath })); | ||
| } | ||
| const fileName = this.fileSystem.path.basename(packagePath); | ||
| const form = new FormData; | ||
| form.append("package", new Blob([data], { | ||
| type: "application/octet-stream" | ||
| }), fileName); | ||
| const headers = {}; | ||
| if (destination.apiKey) { | ||
| headers["X-NuGet-ApiKey"] = destination.apiKey; | ||
| } | ||
| this.logger.info(`Pushing ${fileName} to ${pushUrl}`); | ||
| const response = await fetch(pushUrl, { | ||
| method: "PUT", | ||
| headers, | ||
| body: form | ||
| }); | ||
| if (!response.ok) { | ||
| const body = await this.safeReadBody(response); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.nugetPushFailed", { | ||
| fileName, | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| })); | ||
| } | ||
| published.push(packagePath); | ||
| this.logger.info(`Pushed ${fileName} successfully.`); | ||
| } | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, published); | ||
| } | ||
| async resolvePushUrl(feedUrl, apiKey) { | ||
| let end = feedUrl.length; | ||
| while (end > 0 && feedUrl.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| const trimmed = feedUrl.slice(0, end); | ||
| if (/\/api\/v2\/package\/?$/i.test(trimmed)) { | ||
| return trimmed; | ||
| } | ||
| if (/\.json$/i.test(trimmed)) { | ||
| return this.resolveFromServiceIndex(trimmed, apiKey); | ||
| } | ||
| return `${trimmed}/api/v2/package`; | ||
| } | ||
| async resolveFromServiceIndex(serviceIndexUrl, apiKey) { | ||
| const headers = { Accept: "application/json" }; | ||
| if (apiKey) { | ||
| headers["X-NuGet-ApiKey"] = apiKey; | ||
| } | ||
| const response = await fetch(serviceIndexUrl, { headers }); | ||
| if (!response.ok) { | ||
| throw new Error(`service index returned ${response.status} ${response.statusText}`); | ||
| } | ||
| const index = await response.json(); | ||
| const resource = index.resources?.find((r) => r["@type"] === NUGET_V3_PACKAGE_PUBLISH_TYPE); | ||
| if (!resource?.["@id"]) { | ||
| throw new Error(`service index has no ${NUGET_V3_PACKAGE_PUBLISH_TYPE} resource`); | ||
| } | ||
| return resource["@id"]; | ||
| } | ||
| async safeReadBody(response) { | ||
| try { | ||
| const text = await response.text(); | ||
| return text.slice(0, 500); | ||
| } catch { | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/orchestrator-feed-types.ts | ||
| var PackageFeedDtoPurposeEnum = { | ||
| Undefined: "Undefined", | ||
| Processes: "Processes", | ||
| Libraries: "Libraries", | ||
| PersonalWorkspace: "PersonalWorkspace", | ||
| FolderHierarchy: "FolderHierarchy" | ||
| }; | ||
| var PackageFeedDtoAuthenticationTypeEnum = { | ||
| Secure: "Secure", | ||
| ApiKey: "ApiKey", | ||
| Basic: "Basic" | ||
| }; | ||
| var ExtendedFolderDtoFeedTypeEnum = { | ||
| Undefined: "Undefined", | ||
| Processes: "Processes", | ||
| Libraries: "Libraries", | ||
| PersonalWorkspace: "PersonalWorkspace", | ||
| FolderHierarchy: "FolderHierarchy" | ||
| }; | ||
| // ../common/dist/sdk-user-agent.js | ||
| var PREFIX = "@uipath/common/"; | ||
| var _g = globalThis; | ||
| function singleton(ctorOrName) { | ||
| const name = typeof ctorOrName === "string" ? ctorOrName : ctorOrName.name; | ||
| const key = Symbol.for(PREFIX + name); | ||
| return { | ||
| get(fallback) { | ||
| return _g[key] ?? fallback; | ||
| }, | ||
| set(value) { | ||
| _g[key] = value; | ||
| }, | ||
| clear() { | ||
| delete _g[key]; | ||
| }, | ||
| getOrInit(factory, guard) { | ||
| const existing = _g[key]; | ||
| if (existing != null && typeof existing === "object") { | ||
| if (!guard || guard(existing)) { | ||
| return existing; | ||
| } | ||
| } | ||
| const instance = factory(); | ||
| _g[key] = instance; | ||
| return instance; | ||
| } | ||
| }; | ||
| } | ||
| var telemetryPropsSlot = singleton("TelemetryDefaultProps"); | ||
| var USER_AGENT_HEADER = "User-Agent"; | ||
| var sdkUserAgentHostToken = singleton("SdkUserAgentHostToken"); | ||
| function splitUserAgentTokens(value) { | ||
| return value?.trim().split(/\s+/).filter(Boolean) ?? []; | ||
| } | ||
| function appendUserAgentToken(value, userAgent) { | ||
| const tokens = splitUserAgentTokens(value); | ||
| const seen = new Set(tokens); | ||
| for (const token of splitUserAgentTokens(userAgent)) { | ||
| if (!seen.has(token)) { | ||
| tokens.push(token); | ||
| seen.add(token); | ||
| } | ||
| } | ||
| return tokens.join(" "); | ||
| } | ||
| function getEffectiveUserAgent(userAgent) { | ||
| return appendUserAgentToken(sdkUserAgentHostToken.get(), userAgent); | ||
| } | ||
| function getHeaderName(headers, headerName) { | ||
| return Object.keys(headers).find((key) => key.toLowerCase() === headerName.toLowerCase()); | ||
| } | ||
| function addSdkUserAgentHeader(headers, userAgent) { | ||
| const result = { ...headers ?? {} }; | ||
| const headerName = getHeaderName(result, USER_AGENT_HEADER); | ||
| result[headerName ?? USER_AGENT_HEADER] = appendUserAgentToken(headerName ? result[headerName] : undefined, getEffectiveUserAgent(userAgent)); | ||
| return result; | ||
| } | ||
| // ../packager/project-packager/package.json | ||
| var package_default = { | ||
| name: "@uipath/project-packager", | ||
| license: "MIT", | ||
| version: "1.201.0-preview.115", | ||
| description: "UiPath Project Packager - core library for packing individual UiPath projects", | ||
| type: "module", | ||
| main: "./dist/index.js", | ||
| exports: { | ||
| ".": { | ||
| types: "./dist/src/index.d.ts", | ||
| default: "./dist/index.js" | ||
| }, | ||
| "./node": { | ||
| types: "./dist/src/node.d.ts", | ||
| default: "./dist/node.js" | ||
| }, | ||
| "./browser": { | ||
| types: "./dist/src/browser.d.ts", | ||
| default: "./dist/browser.js" | ||
| } | ||
| }, | ||
| types: "./dist/src/index.d.ts", | ||
| repository: { | ||
| type: "git", | ||
| url: "https://github.com/UiPath/cli.git", | ||
| directory: "packages/packager/project-packager" | ||
| }, | ||
| publishConfig: { | ||
| registry: "https://npm.pkg.github.com/" | ||
| }, | ||
| files: [ | ||
| "dist" | ||
| ], | ||
| scripts: { | ||
| build: "bun build ./src/index.ts --outdir dist --format esm --target browser --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && bun build ./src/browser.ts --outdir dist --format esm --target browser --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && bun build ./src/node.ts --outdir dist --format esm --target node --external @uipath/solutionpackager-tool-core --external '@uipath/filesystem/*' --external @uipath/filesystem --sourcemap=linked && tsc --emitDeclarationOnly --outDir dist", | ||
| clean: "rimraf dist", | ||
| test: "vitest run", | ||
| e2e: "vitest run --config vitest.e2e.config.ts", | ||
| "test:coverage": "vitest run --coverage", | ||
| prepack: "bun run build", | ||
| "publish:dry": "bun publish --dry-run", | ||
| "publish:gh": "bun publish", | ||
| "version:patch": "bun version patch --no-git-tag-version", | ||
| "version:minor": "bun version minor --no-git-tag-version", | ||
| "version:major": "bun version major --no-git-tag-version", | ||
| lint: "biome check ." | ||
| }, | ||
| dependencies: { | ||
| "@uipath/filesystem": "workspace:*", | ||
| "@uipath/solutionpackager-tool-core": "workspace:*", | ||
| "@uipath/common": "workspace:*" | ||
| }, | ||
| peerDependencies: { | ||
| fflate: "^0.8.2" | ||
| }, | ||
| devDependencies: { | ||
| "@types/node": "^25.5.2", | ||
| "@uipath/resource-builder-tool": "2025.11.0-alpha4535-3530", | ||
| "@uipath/tool-agent": "^2.0.0", | ||
| "@uipath/packager-tool-apiworkflow": "workspace:*", | ||
| "@uipath/packager-tool-connector": "workspace:*", | ||
| "@uipath/packager-tool-flow": "workspace:*", | ||
| "@uipath/packager-tool-functions": "workspace:*", | ||
| "@uipath/packager-tool-webapp": "workspace:*", | ||
| "@uipath/packager-tool-workflowcompiler": "workspace:*", | ||
| "@vitest/coverage-v8": "^4.1.6", | ||
| jsdom: "^30.0.1", | ||
| typescript: "^7.0.2", | ||
| "vite-tsconfig-paths": "^6.1.1", | ||
| vitest: "^4.1.6" | ||
| } | ||
| }; | ||
| // ../packager/project-packager/src/publish/services/orchestrator-feeds-service.ts | ||
| var HEADER_TENANT_ID = "X-UIPATH-TenantId"; | ||
| var FEEDS_PATH = "/api/PackageFeeds/GetFeeds"; | ||
| var FOLDERS_PATH = "/api/FoldersNavigation/GetAllFoldersForCurrentUser"; | ||
| var SDK_USER_AGENT = `${package_default.name.replace(/^@uipath\//, "")}/${package_default.version}`; | ||
| class OrchestratorFeedsService { | ||
| logger; | ||
| constructor() { | ||
| this.logger = new ToolLogger("OrchestratorFeedsService", "Feeds"); | ||
| } | ||
| async getAccessibleFeedsAsync(connection) { | ||
| this.ensureOrchestratorUrl(connection); | ||
| this.logger.info(`Fetching accessible feeds from ${connection.orchestratorUrl}`); | ||
| try { | ||
| const json = await orchestratorGet(connection, FEEDS_PATH); | ||
| return Array.isArray(json) ? json : []; | ||
| } catch (error) { | ||
| const { status, statusText, body } = await describeResponseError(error); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.getAccessibleFeedsFailed", { status, statusText, body })); | ||
| } | ||
| } | ||
| async getFoldersForCurrentUserAsync(connection) { | ||
| this.ensureOrchestratorUrl(connection); | ||
| this.logger.info(`Fetching folders from ${connection.orchestratorUrl}`); | ||
| try { | ||
| const json = await orchestratorGet(connection, FOLDERS_PATH); | ||
| return Array.isArray(json) ? json.map(mapExtendedFolder) : []; | ||
| } catch (error) { | ||
| const { status, statusText, body } = await describeResponseError(error); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.getFoldersForCurrentUserFailed", { status, statusText, body })); | ||
| } | ||
| } | ||
| ensureOrchestratorUrl(connection) { | ||
| if (!connection.orchestratorUrl) { | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorUrlRequired")); | ||
| } | ||
| } | ||
| } | ||
| function mapExtendedFolder(json) { | ||
| return { | ||
| isSelectable: json.IsSelectable, | ||
| hasChildren: json.HasChildren, | ||
| level: json.Level, | ||
| key: json.Key, | ||
| displayName: json.DisplayName, | ||
| fullyQualifiedName: json.FullyQualifiedName, | ||
| description: json.Description, | ||
| folderType: json.FolderType, | ||
| isPersonal: json.IsPersonal, | ||
| provisionType: json.ProvisionType, | ||
| permissionModel: json.PermissionModel, | ||
| parentId: json.ParentId, | ||
| parentKey: json.ParentKey, | ||
| feedType: json.FeedType, | ||
| id: json.Id | ||
| }; | ||
| } | ||
| class OrchestratorResponseError extends Error { | ||
| response; | ||
| constructor(response) { | ||
| super(`Orchestrator request failed with status ${response.status}.`); | ||
| this.response = response; | ||
| this.name = "OrchestratorResponseError"; | ||
| } | ||
| } | ||
| async function orchestratorGet(connection, relativePath) { | ||
| const url = `${normalizeOrchestratorBasePath(connection.orchestratorUrl)}${relativePath}`; | ||
| const response = await fetch(url, { | ||
| method: "GET", | ||
| headers: buildHeaders(connection) | ||
| }); | ||
| if (!response.ok) { | ||
| throw new OrchestratorResponseError(response); | ||
| } | ||
| const text = await response.text(); | ||
| if (text === "" || text === "null") { | ||
| return null; | ||
| } | ||
| return JSON.parse(text); | ||
| } | ||
| function buildHeaders(connection) { | ||
| const headers = {}; | ||
| if (connection.accessToken) { | ||
| headers.Authorization = `Bearer ${connection.accessToken}`; | ||
| } | ||
| if (connection.tenantId) { | ||
| headers[HEADER_TENANT_ID] = connection.tenantId; | ||
| } | ||
| return addSdkUserAgentHeader(headers, SDK_USER_AGENT); | ||
| } | ||
| function normalizeOrchestratorBasePath(orchestratorUrl) { | ||
| let end = orchestratorUrl.length; | ||
| while (end > 0 && orchestratorUrl.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| const trimmed = orchestratorUrl.slice(0, end); | ||
| return /\/orchestrator_$/i.test(trimmed) ? trimmed : `${trimmed}/orchestrator_`; | ||
| } | ||
| async function describeResponseError(error) { | ||
| const response = error?.response; | ||
| if (response) { | ||
| let body = ""; | ||
| try { | ||
| body = (await response.text()).slice(0, 500); | ||
| } catch { | ||
| body = ""; | ||
| } | ||
| return { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| }; | ||
| } | ||
| const cause = error?.cause; | ||
| const message = cause instanceof Error ? cause.message : error instanceof Error ? error.message : String(error); | ||
| return { status: "?", statusText: message, body: "" }; | ||
| } | ||
| // ../packager/project-packager/src/publish/services/orchestrator-publisher.ts | ||
| var HEADER_FOLDER_ID = "X-UIPATH-OrganizationUnitId"; | ||
| var HEADER_TENANT_ID2 = "X-UIPATH-TenantId"; | ||
| var HEADER_NUGET_API_KEY = "X-NuGet-ApiKey"; | ||
| var ORCHESTRATOR_RELATIVE_URL = "/orchestrator_"; | ||
| var PROCESSES_UPLOAD_PATH = "/odata/Processes/UiPath.Server.Configuration.OData.UploadPackage"; | ||
| var LIBRARIES_UPLOAD_PATH = "/odata/Libraries/UiPath.Server.Configuration.OData.UploadPackage"; | ||
| class OrchestratorPublisher { | ||
| fileSystem; | ||
| logger; | ||
| feedsService; | ||
| constructor(fileSystem, feedsService) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "Orchestrator"); | ||
| this.feedsService = feedsService ?? new OrchestratorFeedsService; | ||
| } | ||
| async publishAsync(packagePaths, destination) { | ||
| if (packagePaths.length === 0) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorNoPackages")); | ||
| } | ||
| if (destination.kind === "OrchestratorCustom" /* OrchestratorCustom */) { | ||
| if (!destination.publishUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorCustomPublishUrlRequired")); | ||
| } | ||
| this.logger.info(`Publishing ${packagePaths.length} package(s) to ${destination.publishUrl} (custom)`); | ||
| return this.postPackages(packagePaths, destination.publishUrl, this.buildCustomHeaders(destination)); | ||
| } | ||
| if (!destination.connectionInfo?.cloudUrl) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorCloudUrlRequired")); | ||
| } | ||
| const orchestratorUrl = this.deriveOrchestratorUrl(destination.connectionInfo); | ||
| let feed; | ||
| try { | ||
| feed = await this.resolveFeed(destination, orchestratorUrl); | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorFeedResolutionFailed", { message })); | ||
| } | ||
| const targetUrl = this.buildPublishUrl(orchestratorUrl, feed); | ||
| const headers = this.buildHeaders(destination, feed); | ||
| this.logger.info(`Publishing ${packagePaths.length} package(s) to ${targetUrl} (feed ${feed.name}, ${feed.purpose})`); | ||
| return this.postPackages(packagePaths, targetUrl, headers); | ||
| } | ||
| async postPackages(packagePaths, targetUrl, headers) { | ||
| const form = new FormData; | ||
| for (const packagePath of packagePaths) { | ||
| const data = await this.fileSystem.readFile(packagePath); | ||
| if (!data) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.failedToReadPackage", { path: packagePath })); | ||
| } | ||
| const fileName = this.fileSystem.path.basename(packagePath); | ||
| form.append("file", new Blob([data], { | ||
| type: "application/octet-stream" | ||
| }), fileName); | ||
| } | ||
| const response = await fetch(targetUrl, { | ||
| method: "POST", | ||
| headers, | ||
| body: form | ||
| }); | ||
| if (!response.ok) { | ||
| const body = await this.safeReadBody(response); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.orchestratorPublishFailed", { | ||
| status: response.status, | ||
| statusText: response.statusText, | ||
| body: body ? ` - ${body}` : "" | ||
| })); | ||
| } | ||
| this.logger.info("Orchestrator publish completed."); | ||
| return new ToolResult(ToolErrorCodes.Success, undefined, packagePaths); | ||
| } | ||
| async resolveFeed(destination, orchestratorUrl) { | ||
| const connection = { | ||
| orchestratorUrl, | ||
| accessToken: destination.connectionInfo.accessToken, | ||
| tenantId: destination.connectionInfo.tenantId | ||
| }; | ||
| const feeds = await this.feedsService.getAccessibleFeedsAsync(connection); | ||
| if (destination.kind === "OrchestratorPersonalWorkspace" /* OrchestratorPersonalWorkspace */) { | ||
| const folders = await this.feedsService.getFoldersForCurrentUserAsync(connection); | ||
| const personalFolder = folders.find((f) => f.feedType === ExtendedFolderDtoFeedTypeEnum.PersonalWorkspace); | ||
| if (!personalFolder) { | ||
| const foldersDebug = folders.length === 0 ? "<none>" : folders.map((f) => `${f.displayName} (id=${f.id}, feedType=${f.feedType})`).join(", "); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorPersonalWorkspaceFolderNotFound", { folders: foldersDebug })); | ||
| } | ||
| if (personalFolder.id == null) { | ||
| throw new Error(`Personal-workspace folder "${personalFolder.displayName}" has no id; cannot resolve its feed.`); | ||
| } | ||
| const match2 = feeds.find((f) => f.folderId === personalFolder.id); | ||
| if (!match2) { | ||
| this.throwFeedNotFound(destination, feeds); | ||
| } | ||
| return match2; | ||
| } | ||
| const expectedPurpose = destination.kind === "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */ ? PackageFeedDtoPurposeEnum.Libraries : PackageFeedDtoPurposeEnum.Processes; | ||
| const match = feeds.find((f) => f.purpose === expectedPurpose && f.folderId == null); | ||
| if (!match) { | ||
| this.throwFeedNotFound(destination, feeds); | ||
| } | ||
| return match; | ||
| } | ||
| throwFeedNotFound(destination, feeds) { | ||
| const available = feeds.length === 0 ? "<none>" : feeds.map((f) => `${f.name} (purpose=${f.purpose}, folderId=${f.folderId ?? "null"})`).join(", "); | ||
| throw new Error(translate.t("solutionpackager.publish.errors.orchestratorFeedNotFound", { | ||
| kind: destination.kind, | ||
| available | ||
| })); | ||
| } | ||
| buildPublishUrl(orchestratorUrl, feed) { | ||
| const baseUrl = feed.publishUrl ? feed.publishUrl : `${orchestratorUrl}${feed.purpose === PackageFeedDtoPurposeEnum.Libraries ? LIBRARIES_UPLOAD_PATH : PROCESSES_UPLOAD_PATH}`; | ||
| const parsed = new URL(baseUrl); | ||
| if (feed.id) { | ||
| parsed.searchParams.set("feedId", feed.id); | ||
| } | ||
| return parsed.toString(); | ||
| } | ||
| deriveOrchestratorUrl(connectionInfo) { | ||
| const raw = connectionInfo.cloudUrl ?? ""; | ||
| let end = raw.length; | ||
| while (end > 0 && raw.charCodeAt(end - 1) === 47) | ||
| end--; | ||
| return `${raw.slice(0, end)}${ORCHESTRATOR_RELATIVE_URL}`; | ||
| } | ||
| buildHeaders(destination, feed) { | ||
| const headers = this.buildAuthHeaders(destination.connectionInfo); | ||
| const folderHeader = destination.kind === "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */ ? destination.folderId : feed.folderId; | ||
| if (folderHeader != null) { | ||
| headers[HEADER_FOLDER_ID] = String(folderHeader); | ||
| } | ||
| if (feed.authenticationType === PackageFeedDtoAuthenticationTypeEnum.ApiKey && feed.apiKey) { | ||
| headers[HEADER_NUGET_API_KEY] = feed.apiKey; | ||
| } | ||
| return headers; | ||
| } | ||
| buildCustomHeaders(destination) { | ||
| const headers = this.buildAuthHeaders(destination.connectionInfo); | ||
| if (destination.folderId != null) { | ||
| headers[HEADER_FOLDER_ID] = String(destination.folderId); | ||
| } | ||
| if (destination.apiKey) { | ||
| headers[HEADER_NUGET_API_KEY] = destination.apiKey; | ||
| } | ||
| return headers; | ||
| } | ||
| buildAuthHeaders(connectionInfo) { | ||
| const headers = {}; | ||
| if (connectionInfo.accessToken) { | ||
| headers.Authorization = `Bearer ${connectionInfo.accessToken}`; | ||
| } | ||
| if (connectionInfo.tenantId) { | ||
| headers[HEADER_TENANT_ID2] = connectionInfo.tenantId; | ||
| } | ||
| return headers; | ||
| } | ||
| async safeReadBody(response) { | ||
| try { | ||
| const text = await response.text(); | ||
| return text.slice(0, 500); | ||
| } catch { | ||
| return ""; | ||
| } | ||
| } | ||
| } | ||
| // ../packager/project-packager/src/publish/services/project-publisher.ts | ||
| class ProjectPublisher { | ||
| fileSystem; | ||
| logger; | ||
| localFolderPublisher; | ||
| nugetFeedPublisher; | ||
| orchestratorPublisher; | ||
| constructor(fileSystem, publishers) { | ||
| this.fileSystem = fileSystem; | ||
| this.logger = new ToolLogger("ProjectPublisher", "Publish"); | ||
| this.localFolderPublisher = publishers?.localFolder ?? new LocalFolderPublisher(fileSystem); | ||
| this.nugetFeedPublisher = publishers?.nugetFeed ?? new NugetFeedPublisher(fileSystem); | ||
| this.orchestratorPublisher = publishers?.orchestrator ?? new OrchestratorPublisher(fileSystem); | ||
| } | ||
| async publishAsync(options) { | ||
| if (!options.packagePaths || options.packagePaths.length === 0) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.atLeastOnePackage")); | ||
| } | ||
| for (const path of options.packagePaths) { | ||
| if (!await this.fileSystem.exists(path)) { | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.packageNotFound", { path })); | ||
| } | ||
| } | ||
| try { | ||
| const destination = options.destination; | ||
| switch (destination.kind) { | ||
| case "LocalFolder" /* LocalFolder */: | ||
| return await this.localFolderPublisher.publishAsync(options.packagePaths, destination); | ||
| case "NugetFeed" /* NugetFeed */: | ||
| return await this.nugetFeedPublisher.publishAsync(options.packagePaths, destination); | ||
| case "OrchestratorPersonalWorkspace" /* OrchestratorPersonalWorkspace */: | ||
| case "OrchestratorTenantProcesses" /* OrchestratorTenantProcesses */: | ||
| case "OrchestratorSharedLibraries" /* OrchestratorSharedLibraries */: | ||
| case "OrchestratorCustom" /* OrchestratorCustom */: | ||
| return await this.orchestratorPublisher.publishAsync(options.packagePaths, destination); | ||
| default: { | ||
| const exhaustive = destination; | ||
| return ToolResult.error(ToolErrorCodes.InternalError, translate.t("solutionpackager.publish.errors.unknownDestination", { destination: JSON.stringify(exhaustive) })); | ||
| } | ||
| } | ||
| } catch (error) { | ||
| const message = error instanceof Error ? error.message : String(error); | ||
| const localized = translate.t("solutionpackager.publish.errors.publishFailed", { message }); | ||
| this.logger.error(localized); | ||
| return ToolResult.error(ToolErrorCodes.InternalError, localized); | ||
| } | ||
| } | ||
| } | ||
| export { | ||
| signNupkgsAsync, | ||
| setGlobalLogHandler, | ||
| resolveProducedNupkgsAsync, | ||
| ToolsFactory, | ||
| ToolLogger, | ||
| TelemetryService, | ||
| TelemetryNames, | ||
| RulesConfigFileType, | ||
| PublishDestinationKind, | ||
| ProjectValidateOptionsValidator, | ||
| ProjectValidateOptions, | ||
| ProjectToolExecutor, | ||
| ProjectRestoreOptions, | ||
| ProjectPublisher, | ||
| ProjectPublishOptions, | ||
| ProjectPackager, | ||
| ProjectPackOptions, | ||
| ProjectLoader, | ||
| ProjectCleanupOptions, | ||
| ProjectBuildOptionsValidator, | ||
| ProjectBuildOptions, | ||
| PackagerParametersValidator, | ||
| PackagerParameters, | ||
| PackService, | ||
| GovernancePolicyService, | ||
| ConsoleTelemetryProvider, | ||
| BrowserContextStorage | ||
| }; | ||
| //# debugId=7B28B6A84040C8FE64756E2164756E21 |
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Sorry, the diff of this file is too big to display
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Shell access
Supply chain riskThis module accesses the system shell. Accessing the system shell increases the risk of executing arbitrary code.
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 3 instances
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Long strings
Supply chain riskContains long string literals, which may be a sign of obfuscated or packed code.
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
AI-detected potential code anomaly
Supply chain riskAI has identified unusual behaviors that may pose a security risk.
Found 2 instances
URL strings
Supply chain riskPackage contains fragments of external URLs or IP addresses, which the package may be accessing at runtime.
5297522
0.32%26
8.33%131897
0.37%64
25.49%75
59.57%