UNPKG

@tachybase/module-workflow

Version:

A powerful BPM tool that provides foundational support for business automation, with the capability to extend unlimited triggers and nodes.

371 lines (370 loc) 18.6 kB
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name); var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __decoratorStart = (base) => [, , , __create((base == null ? void 0 : base[__knownSymbol("metadata")]) ?? null)]; var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"]; var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn; var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) }); var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]); var __runInitializers = (array, flags, self, value) => { for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) flags & 1 ? fns[i].call(self) : value = fns[i].call(self, value); return value; }; var __decorateElement = (array, flags, name, decorators, target, extra) => { var fn, it, done, ctx, access, k = flags & 7, s = !!(flags & 8), p = !!(flags & 16); var j = k > 3 ? array.length + 1 : k ? s ? 1 : 2 : 0, key = __decoratorStrings[k + 5]; var initializers = k > 3 && (array[j - 1] = []), extraInitializers = array[j] || (array[j] = []); var desc = k && (!p && !s && (target = target.prototype), k < 5 && (k > 3 || !p) && __getOwnPropDesc(k < 4 ? target : { get [name]() { return __privateGet(this, extra); }, set [name](x) { return __privateSet(this, extra, x); } }, name)); k ? p && k < 4 && __name(extra, (k > 2 ? "set " : k > 1 ? "get " : "") + name) : __name(target, name); for (var i = decorators.length - 1; i >= 0; i--) { ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers); if (k) { ctx.static = s, ctx.private = p, access = ctx.access = { has: p ? (x) => __privateIn(target, x) : (x) => name in x }; if (k ^ 3) access.get = p ? (x) => (k ^ 1 ? __privateGet : __privateMethod)(x, target, k ^ 4 ? extra : desc.get) : (x) => x[name]; if (k > 2) access.set = p ? (x, y) => __privateSet(x, target, y, k ^ 4 ? extra : desc.set) : (x, y) => x[name] = y; } it = (0, decorators[i])(k ? k < 4 ? p ? extra : desc[key] : k > 4 ? void 0 : { get: desc.get, set: desc.set } : target, ctx), done._ = 1; if (k ^ 4 || it === void 0) __expectFn(it) && (k > 4 ? initializers.unshift(it) : k ? p ? extra = it : desc[key] = it : target = it); else if (typeof it !== "object" || it === null) __typeError("Object expected"); else __expectFn(fn = it.get) && (desc.get = fn), __expectFn(fn = it.set) && (desc.set = fn), __expectFn(fn = it.init) && initializers.unshift(fn); } return k || __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target; }; var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateIn = (member, obj) => Object(obj) !== obj ? __typeError('Cannot use the "in" operator on this value') : member.has(obj); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value); var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method); var remote_code_fetcher_exports = {}; __export(remote_code_fetcher_exports, { WorkflowRemoteCodeFetcher: () => WorkflowRemoteCodeFetcher }); module.exports = __toCommonJS(remote_code_fetcher_exports); var import_node_http = __toESM(require("node:http")); var import_node_https = __toESM(require("node:https")); var import_node_url = require("node:url"); var import_server = require("@tego/server"); var _logger_dec, _WorkflowRemoteCodeFetcher_decorators, _init; _WorkflowRemoteCodeFetcher_decorators = [(0, import_server.Service)()], _logger_dec = [(0, import_server.InjectLog)()]; class WorkflowRemoteCodeFetcher { constructor() { this.logger = __runInitializers(_init, 8, this), __runInitializers(_init, 11, this); } /** * 从 CDN 获取代码 * @param url 代码 URL * @param timeout 超时时间(毫秒) * @param authType 认证类型: 'none' | 'token' | 'basic' * @param authToken Bearer Token 或 Basic Auth 的密码 * @param authUsername Basic Auth 的用户名 */ async fetchFromCDN(url, timeout = 1e4, authType, authToken, authUsername) { return new Promise((resolve, reject) => { const urlObj = new import_node_url.URL(url); const client = urlObj.protocol === "https:" ? import_node_https.default : import_node_http.default; this.logger.info(`Fetching from URL: ${url}${authType && authType !== "none" ? ` (with ${authType} auth)` : ""}`); const headers = { "User-Agent": "TegoWorkflow/1.0" }; if (authType === "token" && authToken) { headers["Authorization"] = `Bearer ${authToken}`; this.logger.info(`Using Bearer Token authentication (token length: ${authToken.length})`); } else if (authType === "basic" && authUsername && authToken) { const credentials = Buffer.from(`${authUsername}:${authToken}`).toString("base64"); headers["Authorization"] = `Basic ${credentials}`; this.logger.info(`Using Basic Auth authentication (username: ${authUsername})`); } else if (authType && authType !== "none") { this.logger.warn(`Auth type is ${authType} but missing required credentials`); } const request = client.get( { hostname: urlObj.hostname, port: urlObj.port || (urlObj.protocol === "https:" ? 443 : 80), path: urlObj.pathname + urlObj.search, headers, timeout }, (res) => { if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { const redirectUrl = res.headers.location.startsWith("http") ? res.headers.location : `${urlObj.protocol}//${urlObj.hostname}${res.headers.location}`; this.logger.info(`Following redirect from ${url} to ${redirectUrl}`); request.destroy(); return this.fetchFromCDN(redirectUrl, timeout, authType, authToken, authUsername).then(resolve).catch(reject); } if (res.statusCode !== 200) { const errorMsg = `Failed to fetch from URL: HTTP ${res.statusCode}. URL: ${url}`; this.logger.error(errorMsg); reject(new Error(errorMsg)); return; } let data = ""; res.on("data", (chunk) => { data += chunk; }); res.on("end", () => { this.logger.info(`Successfully fetched ${data.length} bytes from ${url}`); resolve(data); }); } ); request.on("error", (error) => { const errorMsg = `Failed to fetch from URL: ${error.message}. URL: ${url}`; this.logger.error(errorMsg); reject(new Error(errorMsg)); }); request.on("timeout", () => { request.destroy(); const errorMsg = `Request timeout after ${timeout}ms. URL: ${url}`; this.logger.error(errorMsg); reject(new Error(errorMsg)); }); }); } /** * 检测 URL 是否已经是 Raw 文件 URL(可以直接访问) */ isRawFileUrl(url) { try { const urlObj = new import_node_url.URL(url); return urlObj.hostname.includes("raw.githubusercontent.com") || urlObj.pathname.includes("/-/raw/") || urlObj.pathname.includes("/raw/branch/"); } catch { return false; } } /** * 从 URL 中解析分支和文件路径 */ parseGitUrl(url) { try { const urlObj = new import_node_url.URL(url); const pathParts = urlObj.pathname.split("/").filter(Boolean); if (pathParts.length < 2) { return null; } const owner = pathParts[0]; const repo = pathParts[1]; let branch; let filePath; if (urlObj.hostname === "github.com" || urlObj.hostname.includes("github")) { const blobIndex = pathParts.findIndex((p) => p === "blob"); const treeIndex = pathParts.findIndex((p) => p === "tree"); if (blobIndex !== -1 && blobIndex + 1 < pathParts.length) { branch = pathParts[blobIndex + 1]; if (blobIndex + 2 < pathParts.length) { filePath = pathParts.slice(blobIndex + 2).join("/"); } } else if (treeIndex !== -1 && treeIndex + 1 < pathParts.length) { branch = pathParts[treeIndex + 1]; if (treeIndex + 2 < pathParts.length) { filePath = pathParts.slice(treeIndex + 2).join("/"); } } } else if (urlObj.hostname.includes("gitlab.com") || urlObj.hostname.includes("gitlab")) { const dashIndex = pathParts.findIndex((p) => p === "-"); if (dashIndex !== -1 && dashIndex + 1 < pathParts.length) { const nextPart = pathParts[dashIndex + 1]; if (nextPart === "blob" || nextPart === "tree") { if (dashIndex + 2 < pathParts.length) { branch = pathParts[dashIndex + 2]; if (dashIndex + 3 < pathParts.length) { filePath = pathParts.slice(dashIndex + 3).join("/"); } } } } } else if (urlObj.pathname.includes("/src/branch/")) { const srcIndex = pathParts.findIndex((p) => p === "src"); if (srcIndex !== -1 && pathParts[srcIndex + 1] === "branch" && srcIndex + 2 < pathParts.length) { branch = pathParts[srcIndex + 2]; if (srcIndex + 3 < pathParts.length) { filePath = pathParts.slice(srcIndex + 3).join("/"); } } } else if (this.isRawFileUrl(url)) { if (pathParts.length >= 3) { branch = pathParts[2]; if (pathParts.length > 3) { filePath = pathParts.slice(3).join("/"); } } } return { owner, repo, branch, filePath }; } catch { return null; } } /** * 从 Git 仓库获取代码(通过 Raw 文件 URL) */ async fetchFromGit(url, branch = "main", path, authType, authToken, authUsername) { try { const urlObj = new import_node_url.URL(url); let rawUrl = ""; if (this.isRawFileUrl(url)) { this.logger.info(`URL appears to be a raw file URL, using directly: ${url}`); return await this.fetchFromCDN(url, 1e4, authType, authToken, authUsername); } const parsed = this.parseGitUrl(url); const finalBranch = branch || (parsed == null ? void 0 : parsed.branch) || "main"; const finalPath = path || (parsed == null ? void 0 : parsed.filePath); if (urlObj.hostname === "github.com" || urlObj.hostname.includes("github")) { const pathParts = urlObj.pathname.split("/").filter(Boolean); if (pathParts.length >= 2) { const owner = pathParts[0]; const repo = pathParts[1]; if (parsed == null ? void 0 : parsed.filePath) { rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${finalBranch}/${parsed.filePath}`; } else if (finalPath) { rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${finalBranch}/${finalPath}`; } else { const blobIndex = pathParts.findIndex((p) => p === "blob"); const treeIndex = pathParts.findIndex((p) => p === "tree"); let filePath; if (blobIndex !== -1 && blobIndex + 2 < pathParts.length) { filePath = pathParts.slice(blobIndex + 2).join("/"); } else if (treeIndex !== -1 && treeIndex + 2 < pathParts.length) { const possiblePath = pathParts.slice(treeIndex + 2).join("/"); if (possiblePath.match(/\.(tsx?|jsx?|ts|js)$/)) { filePath = possiblePath; } } if (filePath) { rawUrl = `https://raw.githubusercontent.com/${owner}/${repo}/${finalBranch}/${filePath}`; } else { throw new Error( `Unable to determine file path from GitHub URL: ${url}. Please ensure the URL points to a specific file (e.g., /blob/branch/path/to/file.tsx) or provide codePath.` ); } } } else { throw new Error(`Invalid GitHub URL format: ${url}`); } } else if (urlObj.hostname.includes("gitlab.com") || urlObj.hostname.includes("gitlab")) { const pathParts = urlObj.pathname.split("/").filter(Boolean); if (pathParts.length >= 2) { const owner = pathParts[0]; const repo = pathParts[1]; if (parsed == null ? void 0 : parsed.filePath) { rawUrl = `${urlObj.protocol}//${urlObj.hostname}/${owner}/${repo}/-/raw/${finalBranch}/${parsed.filePath}`; } else if (finalPath) { rawUrl = `${urlObj.protocol}//${urlObj.hostname}/${owner}/${repo}/-/raw/${finalBranch}/${finalPath}`; } else { throw new Error( `Unable to determine file path from GitLab URL: ${url}. Please ensure the URL points to a specific file or provide codePath.` ); } } else { throw new Error(`Invalid GitLab URL format: ${url}`); } } else { if (parsed) { const { owner, repo } = parsed; if (urlObj.pathname.includes("/src/branch/")) { const actualPath = finalPath || parsed.filePath; if (!actualPath) { throw new Error( `Unable to determine file path from Gitea URL: ${url}. Please ensure the URL points to a specific file or provide codePath.` ); } rawUrl = `${urlObj.protocol}//${urlObj.hostname}/${owner}/${repo}/raw/branch/${finalBranch}/${actualPath}`; } else if (finalPath || parsed.filePath) { const filePath = finalPath || parsed.filePath; rawUrl = `${urlObj.protocol}//${urlObj.hostname}/${owner}/${repo}/-/raw/${finalBranch}/${filePath}`; } else { throw new Error( `Unable to determine file path from URL: ${url}. Please provide codePath or use a URL that points to a specific file.` ); } } else { if (this.isRawFileUrl(url)) { rawUrl = url; } else { throw new Error(`Invalid Git URL format: ${url}`); } } } this.logger.info(`Fetching from Git: ${rawUrl}`); return await this.fetchFromCDN(rawUrl, 1e4, authType, authToken, authUsername); } catch (error) { this.logger.error(`Failed to fetch from Git: ${error instanceof Error ? error.message : String(error)}`); throw error; } } /** * 获取远程代码 * @param codeUrl 代码地址 * @param codeType 代码类型:'cdn' 或 'git' * @param codeBranch Git 分支名称(仅 Git 类型需要) * @param codePath Git 文件路径(仅 Git 类型需要) * @param authType 认证类型: 'none' | 'token' | 'basic' * @param authToken Bearer Token 或 Basic Auth 的密码 * @param authUsername Basic Auth 的用户名 */ async fetchCode(codeUrl, codeType, codeBranch, codePath, authType, authToken, authUsername) { if (!codeUrl) { throw new Error("Code URL is required"); } if (codeType === "cdn") { this.logger.info(`Fetching code from CDN: ${codeUrl}`); return await this.fetchFromCDN(codeUrl, 1e4, authType, authToken, authUsername); } else if (codeType === "git") { this.logger.info(`Fetching code from Git: ${codeUrl}, branch: ${codeBranch || "main"}`); return await this.fetchFromGit(codeUrl, codeBranch || "main", codePath, authType, authToken, authUsername); } else { throw new Error(`Unsupported code type: ${codeType}. Must be 'cdn' or 'git'`); } } /** * 检查缓存是否有效(默认缓存 1 小时) * @param cache 缓存对象,包含 content 和 timestamp * @param maxAge 最大缓存时间(毫秒),默认 1 小时 (3600000ms) */ isCacheValid(cache, maxAge = 36e5) { if (!cache) { return false; } return Date.now() - cache.timestamp < maxAge; } } _init = __decoratorStart(null); __decorateElement(_init, 5, "logger", _logger_dec, WorkflowRemoteCodeFetcher); WorkflowRemoteCodeFetcher = __decorateElement(_init, 0, "WorkflowRemoteCodeFetcher", _WorkflowRemoteCodeFetcher_decorators, WorkflowRemoteCodeFetcher); __runInitializers(_init, 1, WorkflowRemoteCodeFetcher); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { WorkflowRemoteCodeFetcher });