From b1ef57673442b7efaebbe51f31e067fb023b19fe Mon Sep 17 00:00:00 2001 From: wangnianping Date: Wed, 2 Dec 2026 18:20:47 +0800 Subject: [PATCH] feat(spec): support per-platform targets.minAppVersion and capability mappings --- .../ztools-plugins-spec/plugin.schema.json | 25 +- .../src/host-requirements.js | 391 +++++++++++++++--- packages/ztools-plugins-spec/src/validator.js | 36 +- .../tests/catalog-validator.test.mjs | 87 ++++ .../tests/host-requirements.test.mjs | 141 ++++++- scripts/build-plugins-release.mjs | 52 ++- scripts/verify-changed-plugins.mjs | 29 +- 7 files changed, 684 insertions(+), 77 deletions(-) diff --git a/packages/ztools-plugins-spec/plugin.schema.json b/packages/ztools-plugins-spec/plugin.schema.json index 793201d..3814972 100644 --- a/packages/ztools-plugins-spec/plugin.schema.json +++ b/packages/ztools-plugins-spec/plugin.schema.json @@ -183,6 +183,15 @@ "pattern": "^\\d+(\\.\\d+){1,3}$", "description": "运行插件所需的最低客户端版本(如 1.1.8.3);发布时还会按插件用到的宿主接口自动提高" }, + "optionalHostApis": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]{1,63}$" + }, + "description": "插件已内置降级逻辑的可选宿主接口列表(命中时不抬高最低客户端版本,也不因某平台未实现而阻断发布)" + }, "requiredCapabilities": { "type": "array", "uniqueItems": true, @@ -309,7 +318,21 @@ "runtime": { "type": "string", "enum": ["electron", "legacy-delphi"] }, "arch": { "type": "string", "enum": ["any", "ia32", "x64", "arm64", "universal"] }, "abi": { "type": "string" }, - "minSdkContractVersion": { "type": "integer", "minimum": 1 } + "minSdkContractVersion": { "type": "integer", "minimum": 1 }, + "minAppVersion": { + "type": "string", + "pattern": "^\\d+(?:\\.\\d+){1,3}$", + "description": "该平台目标所需的最低客户端版本(如 1.3.0.4)" + }, + "optionalHostApis": { + "type": "array", + "uniqueItems": true, + "items": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]{1,63}$" + }, + "description": "该平台目标可降级的可选宿主接口列表" + } }, "additionalProperties": false }, diff --git a/packages/ztools-plugins-spec/src/host-requirements.js b/packages/ztools-plugins-spec/src/host-requirements.js index 24a08f9..1903dfb 100644 --- a/packages/ztools-plugins-spec/src/host-requirements.js +++ b/packages/ztools-plugins-spec/src/host-requirements.js @@ -1,53 +1,78 @@ import fs from 'node:fs' import path from 'node:path' +const ELECTRON_PLATFORMS = Object.freeze(['windows', 'macos']) + +function bothPlatforms(version) { + return Object.freeze({ windows: version, macos: version }) +} + /** - * 插件依赖的宿主接口 → 首个提供该接口的客户端版本。 + * 插件依赖的宿主接口 → 各平台首个提供该接口的客户端版本。 * - * 插件目录里的 minAppVersion 由发布脚本按这张表自动算出:客户端低于这个版本时, - * 插件市场不提供更新、安装前会提示先升级客户端,避免旧客户端装上后功能直接失败。 - * 新增宿主接口并且有插件离不开它时,在这里登记;插件自带退路(旧客户端也能用)的接口不要登记。 - * 版本号以实际发布的安装包为准:v1.1.8.4 的宿主接口与 v1.1.8.3 相同,下面标 1.1.8.5 的接口从 1.1.8.5 起才有。 + * - 双端独立维护 `{ windows, macos }`,某端暂未实现时记为 `null`(将在 PR 校验与构建门禁中阻断发布,除非插件在 `optionalHostApis` 中显式声明降级); + * - 插件目录里的 `targets[].minAppVersion` 与顶层兜底 `minAppVersion` 均按此表自动计算; + * - 新增宿主接口并且有插件离不开它时在此登记;插件自带退路且已在清单声明 `optionalHostApis` 的接口不会抬高门槛。 */ export const HOST_API_REQUIREMENTS = Object.freeze([ - { api: 'system_list_volumes', minAppVersion: '1.1.8.3', pattern: /\bsystem_list_volumes\b/ }, - { api: 'clipboard_history_restore', minAppVersion: '1.1.8.3', pattern: /\bclipboard_history_restore\b/ }, - { api: 'filesystem_move_file_no_replace', minAppVersion: '1.1.8.3', pattern: /\bfilesystem_move_file_no_replace\b/ }, - { api: 'browser_bookmarks_scan', minAppVersion: '1.1.8.5', pattern: /\bbrowser_bookmarks_(?:scan|cancel)\b/ }, - { api: 'system_power_session', minAppVersion: '1.1.8.5', pattern: /\bsystem_power_session\b/ }, - { api: 'keyboard_lock', minAppVersion: '1.1.8.5', pattern: /\bkeyboard_lock\b/ }, - { api: 'dns_benchmark', minAppVersion: '1.1.8.5', pattern: /\bdns_benchmark\b/ }, - { api: 'docker_manager', minAppVersion: '1.1.8.5', pattern: /\bdocker_manager\b/ }, - { api: 'downloads_manager', minAppVersion: '1.1.8.5', pattern: /\bdownloads_manager\b/ }, - { api: 'environment_manager', minAppVersion: '1.1.8.5', pattern: /\benvironment_manager\b/ }, - { api: 'file_unlock', minAppVersion: '1.1.8.5', pattern: /\bfile_unlock\b/ }, - { api: 'folder_sync', minAppVersion: '1.1.8.5', pattern: /\bfolder_sync(?:_cancel)?\b/ }, - { api: 'font_manager', minAppVersion: '1.1.8.5', pattern: /\bfont_manager(?:_cancel)?\b/ }, - { api: 'hosts_manager', minAppVersion: '1.1.8.5', pattern: /\bhosts_manager\b/ }, - { api: 'hotkey_probe', minAppVersion: '1.1.8.5', pattern: /\bhotkey_probe\b/ }, - { api: 'lan_network', minAppVersion: '1.1.8.5', pattern: /\blan_network\b/ }, - { api: 'markdown_document', minAppVersion: '1.1.8.5', pattern: /\bmarkdown_document\b/ }, - { api: 'media_metadata', minAppVersion: '1.1.8.5', pattern: /\bmedia_metadata(?:_cancel)?\b/ }, - { api: 'monitor_control', minAppVersion: '1.1.8.5', pattern: /\bmonitor_control\b/ }, - { api: 'network_speedtest', minAppVersion: '1.1.8.5', pattern: /\bnetwork_speedtest\b/ }, - { api: 'office_document', minAppVersion: '1.1.8.5', pattern: /\boffice_(?:document|cancel)\b/ }, - { api: 'recent_projects', minAppVersion: '1.1.8.5', pattern: /\brecent_projects\b/ }, - { api: 'ssh_proxy', minAppVersion: '1.1.8.5', pattern: /\bssh_proxy\b/ }, - { api: 'startup_manager', minAppVersion: '1.1.8.5', pattern: /\bstartup_manager\b/ }, - { api: 'tls_inspect', minAppVersion: '1.1.8.5', pattern: /\btls_inspect\b/ }, - { api: 'image_ocr', minAppVersion: '1.1.8.9', pattern: /\bimage_ocr\b/ }, - { api: 'tool_runtime', minAppVersion: '1.3.0.0', pattern: /\btool_(?:runtime_(?:capabilities|ensure)|task_cancel)\b/ }, - { api: 'tool_media', minAppVersion: '1.3.0.0', pattern: /\btool_media_(?:probe|transcode_run)\b/ }, - { api: 'tool_download', minAppVersion: '1.3.0.0', pattern: /\btool_download_(?:stream_(?:probe|run)|transfer_(?:add|pause|resume|cancel|status))\b/ }, - { api: 'network_adapter', minAppVersion: '1.3.0.2', pattern: /\bnetwork_adapter\b/ }, - { api: 'context_menu', minAppVersion: '1.3.0.2', pattern: /\bcontext_menu\b/ }, - { api: 'browser_history', minAppVersion: '1.3.0.2', pattern: /\bbrowser_history_(?:query|cancel)\b/ }, - { api: 'tool_media_capture', minAppVersion: '1.3.0.2', pattern: /\btool_media_capture_(?:sources|start|stop|status)\b/ }, - { api: 'tool_archive', minAppVersion: '1.3.0.4', pattern: /\btool_archive_(?:list|extract|create)\b/ }, - { api: 'tool_document_pdf', minAppVersion: '1.3.0.4', pattern: /\btool_document_pdf_(?:inspect|transform|render)\b/ }, - { api: 'tool_image', minAppVersion: '1.3.0.4', pattern: /\btool_image_(?:inspect|process)\b/ } + Object.freeze({ api: 'system_list_volumes', minAppVersion: bothPlatforms('1.1.8.3'), pattern: /\bsystem_list_volumes\b/ }), + Object.freeze({ api: 'clipboard_history_restore', minAppVersion: bothPlatforms('1.1.8.3'), pattern: /\bclipboard_history_restore\b/ }), + Object.freeze({ api: 'filesystem_move_file_no_replace', minAppVersion: bothPlatforms('1.1.8.3'), pattern: /\bfilesystem_move_file_no_replace\b/ }), + Object.freeze({ api: 'browser_bookmarks_scan', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bbrowser_bookmarks_(?:scan|cancel)\b/ }), + Object.freeze({ api: 'system_power_session', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bsystem_power_session\b/ }), + Object.freeze({ api: 'keyboard_lock', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bkeyboard_lock\b/ }), + Object.freeze({ api: 'dns_benchmark', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bdns_benchmark\b/ }), + Object.freeze({ api: 'docker_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bdocker_manager\b/ }), + Object.freeze({ api: 'downloads_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bdownloads_manager\b/ }), + Object.freeze({ api: 'environment_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\benvironment_manager\b/ }), + Object.freeze({ api: 'file_unlock', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bfile_unlock\b/ }), + Object.freeze({ api: 'folder_sync', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bfolder_sync(?:_cancel)?\b/ }), + Object.freeze({ api: 'font_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bfont_manager(?:_cancel)?\b/ }), + Object.freeze({ api: 'hosts_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bhosts_manager\b/ }), + Object.freeze({ api: 'hotkey_probe', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bhotkey_probe\b/ }), + Object.freeze({ api: 'lan_network', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\blan_network\b/ }), + Object.freeze({ api: 'markdown_document', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bmarkdown_document\b/ }), + Object.freeze({ api: 'media_metadata', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bmedia_metadata(?:_cancel)?\b/ }), + Object.freeze({ api: 'monitor_control', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bmonitor_control\b/ }), + Object.freeze({ api: 'network_speedtest', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bnetwork_speedtest\b/ }), + Object.freeze({ api: 'office_document', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\boffice_(?:document|cancel)\b/ }), + Object.freeze({ api: 'recent_projects', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\brecent_projects\b/ }), + Object.freeze({ api: 'ssh_proxy', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bssh_proxy\b/ }), + Object.freeze({ api: 'startup_manager', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\bstartup_manager\b/ }), + Object.freeze({ api: 'tls_inspect', minAppVersion: bothPlatforms('1.1.8.5'), pattern: /\btls_inspect\b/ }), + Object.freeze({ api: 'image_ocr', minAppVersion: bothPlatforms('1.1.8.9'), pattern: /\bimage_ocr\b/ }), + Object.freeze({ api: 'tool_runtime', minAppVersion: bothPlatforms('1.3.0.0'), pattern: /\btool_(?:runtime_(?:capabilities|ensure)|task_cancel)\b/ }), + Object.freeze({ api: 'tool_media', minAppVersion: bothPlatforms('1.3.0.0'), pattern: /\btool_media_(?:probe|transcode_run)\b/ }), + Object.freeze({ api: 'tool_download', minAppVersion: bothPlatforms('1.3.0.0'), pattern: /\btool_download_(?:stream_(?:probe|run)|transfer_(?:add|pause|resume|cancel|status))\b/ }), + Object.freeze({ api: 'network_adapter', minAppVersion: bothPlatforms('1.3.0.2'), pattern: /\bnetwork_adapter\b/ }), + Object.freeze({ api: 'context_menu', minAppVersion: bothPlatforms('1.3.0.2'), pattern: /\bcontext_menu\b/ }), + Object.freeze({ api: 'browser_history', minAppVersion: bothPlatforms('1.3.0.2'), pattern: /\bbrowser_history_(?:query|cancel)\b/ }), + Object.freeze({ api: 'tool_media_capture', minAppVersion: bothPlatforms('1.3.0.2'), pattern: /\btool_media_capture_(?:sources|start|stop|status)\b/ }), + Object.freeze({ api: 'tool_archive', minAppVersion: bothPlatforms('1.3.0.4'), pattern: /\btool_archive_(?:list|extract|create)\b/ }), + Object.freeze({ api: 'tool_document_pdf', minAppVersion: bothPlatforms('1.3.0.4'), pattern: /\btool_document_pdf_(?:inspect|transform|render)\b/ }), + Object.freeze({ api: 'tool_image', minAppVersion: bothPlatforms('1.3.0.4'), pattern: /\btool_image_(?:inspect|process)\b/ }) ]) +/** + * 插件声明的 `requiredCapabilities`(13 个薄原语能力枚举)→ 各平台首个提供该能力的客户端版本。 + * 某端暂未实现时可记为 `null`,以阻断错误平台发布。 + */ +export const CAPABILITY_MIN_APP_VERSIONS = Object.freeze({ + 'media.probe': bothPlatforms('1.3.0.0'), + 'media.transcode': bothPlatforms('1.3.0.0'), + 'download.stream': bothPlatforms('1.3.0.0'), + 'download.transfer': bothPlatforms('1.3.0.0'), + 'media.capture': bothPlatforms('1.3.0.2'), + 'archive.list': bothPlatforms('1.3.0.4'), + 'archive.extract': bothPlatforms('1.3.0.4'), + 'archive.create': bothPlatforms('1.3.0.4'), + 'document.pdf.inspect': bothPlatforms('1.3.0.4'), + 'document.pdf.transform': bothPlatforms('1.3.0.4'), + 'document.pdf.render': bothPlatforms('1.3.0.4'), + 'image.inspect': bothPlatforms('1.3.0.4'), + 'image.process': bothPlatforms('1.3.0.4') +}) + export const APP_VERSION_REGEX = /^\d+(?:\.\d+){1,3}$/ /** 比较客户端版本号(2~4 段数字,缺的段按 0);格式不对返回 null */ @@ -62,11 +87,53 @@ export function compareAppVersion(a, b) { return 0 } +function normalizeValidAppVersion(version) { + return typeof version === 'string' && APP_VERSION_REGEX.test(version) ? version : undefined +} + +function pickHigherAppVersion(current, candidate) { + const validCandidate = normalizeValidAppVersion(candidate) + if (!validCandidate) return current + if (!current) return validCandidate + return compareAppVersion(validCandidate, current) > 0 ? validCandidate : current +} + +function pickLowerAppVersion(current, candidate) { + const validCandidate = normalizeValidAppVersion(candidate) + if (!validCandidate) return current + if (!current) return validCandidate + return compareAppVersion(validCandidate, current) < 0 ? validCandidate : current +} + +/** 读取某项版本要求在指定平台上的最低版本:支持 `{ windows, macos }` 与兼容字符串;未实现或缺失返回 null */ +function resolvePlatformRequirementVersion(spec, platform) { + if (typeof spec === 'string') return normalizeValidAppVersion(spec) ?? null + if (spec && typeof spec === 'object' && !Array.isArray(spec)) { + const value = Object.hasOwn(spec, platform) ? spec[platform] : null + if (value === null || value === undefined) return null + return normalizeValidAppVersion(value) ?? null + } + return null +} + +/** 读取某项版本要求在所有已支持平台上的最高合法版本号(供无 targets 退回分支保持兼容) */ +function resolveHighestVersionAcrossPlatforms(spec) { + if (typeof spec === 'string') return normalizeValidAppVersion(spec) + if (spec && typeof spec === 'object' && !Array.isArray(spec)) { + let highest + for (const platform of ELECTRON_PLATFORMS) { + highest = pickHigherAppVersion(highest, spec[platform]) + } + return highest + } + return undefined +} + const RUNTIME_EXTENSIONS = new Set(['.js', '.mjs', '.cjs']) const SKIP_DIRS = new Set(['node_modules', '.git', 'tests', '__tests__', 'src']) function collectRuntimeFiles(dir, out = []) { - if (!fs.existsSync(dir)) return out + if (!dir || !fs.existsSync(dir)) return out for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { if (entry.isDirectory()) { if (!SKIP_DIRS.has(entry.name)) collectRuntimeFiles(path.join(dir, entry.name), out) @@ -77,30 +144,236 @@ function collectRuntimeFiles(dir, out = []) { return out } +function mergeUnique(base, extras) { + const seen = new Set(base) + for (const item of extras) { + if (!seen.has(item)) { + seen.add(item) + base.push(item) + } + } + return base +} + /** - * 计算插件要求的最低客户端版本:plugin.json 里手写的 minAppVersion 与运行代码(不含 src/、测试) - * 用到的登记接口取最高者。没有任何要求时返回 { minAppVersion: undefined }。 + * 按插件声明的各 Electron 平台 target 分别计算最低客户端版本门槛、命中接口/能力与平台未支持阻断项。 + * + * - 支持 `manifest.optionalHostApis` 与 `target.optionalHostApis` 合并降级集合(命中的可选 API 不抬高门槛也不计入 `unsupported`); + * - 顶层兼容兜底 `minAppVersion` 仅当全部 electron target 都有 `minAppVersion` 时取其中最小值,否则取 `manifest.minAppVersion`(若有); + * - 当 `manifest.targets` 未声明(如纯目录单测)时,退回按双端版本较高者计算顶层 `minAppVersion` 以保持向后兼容。 + * * @param {string} pluginDir - * @param {object} manifest - * @returns {{ minAppVersion?: string, apis: string[] }} + * @param {object} [manifest] + * @param {{ requirements?: ReadonlyArray, capabilityVersions?: Record }} [options] + * @returns {{ + * targets: Record, + * targetEntries: Array<{ id?: string, platform: string, runtime: string, arch?: string, minAppVersion?: string, apis: string[], capabilities: string[], unsupportedApis: string[] }>, + * minAppVersion?: string, + * apis: string[], + * unsupported: Array<{ platform: string, targetId?: string, api: string, capability?: string }> + * }} */ -export function resolvePluginMinAppVersion(pluginDir, manifest = {}) { - let minAppVersion = typeof manifest.minAppVersion === 'string' && APP_VERSION_REGEX.test(manifest.minAppVersion) - ? manifest.minAppVersion - : undefined - const apis = [] +export function resolvePluginTargetMinAppVersions(pluginDir, manifest = {}, options = {}) { + const safeManifest = manifest && typeof manifest === 'object' && !Array.isArray(manifest) ? manifest : {} + const requirements = Array.isArray(options.requirements) ? options.requirements : HOST_API_REQUIREMENTS + const capabilityVersions = + options.capabilityVersions && typeof options.capabilityVersions === 'object' + ? options.capabilityVersions + : CAPABILITY_MIN_APP_VERSIONS + const sources = collectRuntimeFiles(pluginDir).map((file) => fs.readFileSync(file, 'utf8')) - for (const requirement of HOST_API_REQUIREMENTS) { - if (!sources.some((source) => requirement.pattern.test(source))) continue + const matchedRequirements = [] + const apis = [] + for (const requirement of requirements) { + if (!requirement?.pattern || !sources.some((source) => requirement.pattern.test(source))) continue + matchedRequirements.push(requirement) apis.push(requirement.api) - if (!minAppVersion || compareAppVersion(requirement.minAppVersion, minAppVersion) > 0) { - minAppVersion = requirement.minAppVersion + } + + const manifestMinAppVersion = normalizeValidAppVersion(safeManifest.minAppVersion) + const manifestOptionalApis = Array.isArray(safeManifest.optionalHostApis) + ? safeManifest.optionalHostApis.filter((item) => typeof item === 'string') + : [] + const requiredCapabilities = Array.isArray(safeManifest.requiredCapabilities) + ? safeManifest.requiredCapabilities.filter((item) => typeof item === 'string') + : [] + + const electronTargets = Array.isArray(safeManifest.targets) + ? safeManifest.targets.filter( + (target) => + target && + typeof target === 'object' && + !Array.isArray(target) && + target.runtime === 'electron' && + ELECTRON_PLATFORMS.includes(target.platform) + ) + : [] + + const targetsByPlatform = {} + const targetEntries = [] + const unsupported = [] + + // 无显式 electron targets 时退回顶层计算(保持纯目录单测与历史调用方语义一致) + if (electronTargets.length === 0) { + const optionalSet = new Set(manifestOptionalApis) + let fallbackMinAppVersion = manifestMinAppVersion + for (const requirement of matchedRequirements) { + if (optionalSet.has(requirement.api)) continue + fallbackMinAppVersion = pickHigherAppVersion( + fallbackMinAppVersion, + resolveHighestVersionAcrossPlatforms(requirement.minAppVersion) + ) } + for (const capability of requiredCapabilities) { + const capSpec = Object.hasOwn(capabilityVersions, capability) ? capabilityVersions[capability] : null + const capVersion = capSpec ? resolveHighestVersionAcrossPlatforms(capSpec) : '1.3.0.0' + fallbackMinAppVersion = pickHigherAppVersion(fallbackMinAppVersion, capVersion) + } + return { + targets: targetsByPlatform, + targetEntries, + minAppVersion: fallbackMinAppVersion, + apis, + unsupported + } + } + + for (const target of electronTargets) { + const platform = target.platform + const targetOptionalApis = Array.isArray(target.optionalHostApis) + ? target.optionalHostApis.filter((item) => typeof item === 'string') + : [] + const optionalSet = new Set([...manifestOptionalApis, ...targetOptionalApis]) + + let targetMinAppVersion = pickHigherAppVersion(manifestMinAppVersion, target.minAppVersion) + const targetApis = [] + const targetCapabilities = [] + const targetUnsupportedApis = [] + + for (const requirement of matchedRequirements) { + if (optionalSet.has(requirement.api)) continue + const platformVersion = resolvePlatformRequirementVersion(requirement.minAppVersion, platform) + if (platformVersion === null) { + targetUnsupportedApis.push(requirement.api) + unsupported.push({ platform, targetId: target.id, api: requirement.api }) + continue + } + targetApis.push(requirement.api) + targetMinAppVersion = pickHigherAppVersion(targetMinAppVersion, platformVersion) + } + + for (const capability of requiredCapabilities) { + if (Object.hasOwn(capabilityVersions, capability)) { + const capVersion = resolvePlatformRequirementVersion(capabilityVersions[capability], platform) + if (capVersion === null) { + targetUnsupportedApis.push(capability) + unsupported.push({ platform, targetId: target.id, api: capability, capability }) + continue + } + targetCapabilities.push(capability) + targetMinAppVersion = pickHigherAppVersion(targetMinAppVersion, capVersion) + } else { + targetCapabilities.push(capability) + targetMinAppVersion = pickHigherAppVersion(targetMinAppVersion, '1.3.0.0') + } + } + + const entry = { + ...(typeof target.id === 'string' ? { id: target.id } : {}), + platform, + runtime: target.runtime, + ...(typeof target.arch === 'string' ? { arch: target.arch } : {}), + minAppVersion: targetMinAppVersion, + apis: targetApis, + capabilities: targetCapabilities, + unsupportedApis: targetUnsupportedApis + } + targetEntries.push(entry) + + if (!targetsByPlatform[platform]) { + targetsByPlatform[platform] = { + minAppVersion: targetMinAppVersion, + apis: [...targetApis], + capabilities: [...targetCapabilities], + unsupportedApis: [...targetUnsupportedApis] + } + } else { + const existing = targetsByPlatform[platform] + existing.minAppVersion = pickHigherAppVersion(existing.minAppVersion, targetMinAppVersion) + mergeUnique(existing.apis, targetApis) + mergeUnique(existing.capabilities, targetCapabilities) + mergeUnique(existing.unsupportedApis, targetUnsupportedApis) + } + } + + // 顶层兼容兜底:仅当全部 electron target 均存在 minAppVersion 时取其中最小值,否则回退为 manifest.minAppVersion(避免旧客户端误拒无门槛平台) + let minAppVersion = manifestMinAppVersion + if (targetEntries.every((entry) => Boolean(entry.minAppVersion))) { + let lowest + for (const entry of targetEntries) { + lowest = pickLowerAppVersion(lowest, entry.minAppVersion) + } + minAppVersion = lowest } - if (Array.isArray(manifest.requiredCapabilities) && manifest.requiredCapabilities.length > 0) { - if (!minAppVersion || compareAppVersion('1.3.0.0', minAppVersion) > 0) { - minAppVersion = '1.3.0.0' + + return { + targets: targetsByPlatform, + targetEntries, + minAppVersion, + apis, + unsupported + } +} + +/** + * 计算插件要求的最低客户端版本(向后兼容入口): + * 基于 `resolvePluginTargetMinAppVersions` 返回顶层与分平台门槛明细。 + * @param {string} pluginDir + * @param {object} [manifest] + * @param {object} [options] + * @returns {{ minAppVersion?: string, apis: string[], targets: Record, targetEntries: Array, unsupported: Array }} + */ +export function resolvePluginMinAppVersion(pluginDir, manifest = {}, options = {}) { + const resolved = resolvePluginTargetMinAppVersions(pluginDir, manifest, options) + return { + minAppVersion: resolved.minAppVersion, + apis: resolved.apis, + targets: resolved.targets, + targetEntries: resolved.targetEntries, + unsupported: resolved.unsupported + } +} + +/** + * 格式化分平台最低宿主版本摘要(供 PR 校验报告与日志复用): + * - 双端版本不同返回 `Win ≥ X / Mac ≥ Y`(某端无门槛显示 `-`); + * - 双端相同或单端返回 `≥ X`; + * - 无门槛返回 `-`。 + * @param {{ targets?: Record, minAppVersion?: string }} result + * @returns {string} + */ +export function formatTargetMinAppVersionsSummary(result) { + const targets = result?.targets && typeof result.targets === 'object' ? result.targets : {} + const hasWin = Object.hasOwn(targets, 'windows') + const hasMac = Object.hasOwn(targets, 'macos') + + if (hasWin && hasMac) { + const winVer = normalizeValidAppVersion(targets.windows?.minAppVersion) + const macVer = normalizeValidAppVersion(targets.macos?.minAppVersion) + if (!winVer && !macVer) return '-' + if (winVer && macVer && compareAppVersion(winVer, macVer) === 0 && winVer === macVer) { + return `≥ ${winVer}` } + const winLabel = winVer ? `Win ≥ ${winVer}` : 'Win -' + const macLabel = macVer ? `Mac ≥ ${macVer}` : 'Mac -' + return `${winLabel} / ${macLabel}` + } + + if (hasWin || hasMac) { + const singleVer = normalizeValidAppVersion((hasWin ? targets.windows : targets.macos)?.minAppVersion) + return singleVer ? `≥ ${singleVer}` : '-' } - return { minAppVersion, apis } + + const fallbackVer = normalizeValidAppVersion(result?.minAppVersion) + return fallbackVer ? `≥ ${fallbackVer}` : '-' } diff --git a/packages/ztools-plugins-spec/src/validator.js b/packages/ztools-plugins-spec/src/validator.js index f15d629..39ac9a4 100644 --- a/packages/ztools-plugins-spec/src/validator.js +++ b/packages/ztools-plugins-spec/src/validator.js @@ -177,10 +177,30 @@ export const NODE_BUILTIN_MODULES = new Set([ */ export const SUPPORTED_PLATFORMS = Object.freeze(['windows', 'macos']) export const PLATFORM_LABELS = Object.freeze({ windows: 'Windows', macos: 'macOS' }) -const TARGET_KEYS = new Set(['id', 'platform', 'runtime', 'arch', 'abi', 'minSdkContractVersion']) +const TARGET_KEYS = new Set(['id', 'platform', 'runtime', 'arch', 'abi', 'minSdkContractVersion', 'minAppVersion', 'optionalHostApis']) const TARGET_RUNTIMES = new Set(['electron', 'legacy-delphi']) const TARGET_ARCHES = new Set(['any', 'ia32', 'x64', 'arm64', 'universal']) const TARGET_ID_REGEX = /^[a-z][a-z0-9-]*$/ +const OPTIONAL_HOST_API_REGEX = /^[a-z][a-z0-9_]{1,63}$/ + +function validateOptionalHostApis(value, label, errors) { + if (value === undefined) return + if (!Array.isArray(value)) { + errors.push(`${label} must be an array`) + return + } + const seen = new Set() + for (const [idx, api] of value.entries()) { + if (typeof api !== 'string' || !OPTIONAL_HOST_API_REGEX.test(api)) { + errors.push(`${label}[${idx}] has invalid host API name: "${String(api)}" (must match ^[a-z][a-z0-9_]{1,63}$)`) + continue + } + if (seen.has(api)) { + errors.push(`Duplicate ${label} entry: "${api}"`) + } + seen.add(api) + } +} /** * 按平台列表生成标准 targets 声明(纯 JS 插件,不绑定原生组件) @@ -245,6 +265,10 @@ function validateTargets(manifest, errors) { if (!TARGET_ARCHES.has(target.arch)) errors.push(`${label}.arch must be one of ${[...TARGET_ARCHES].join(' / ')}`) if (target.runtime === 'legacy-delphi' && target.platform !== 'windows') errors.push(`${label} legacy-delphi runtime is only allowed on Windows`) if (target.platform === 'macos' && target.arch === 'ia32') errors.push(`${label} macOS does not support ia32 architecture`) + if (target.minAppVersion !== undefined && (typeof target.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(target.minAppVersion))) { + errors.push(`${label}.minAppVersion has invalid format: "${target.minAppVersion}" (expected client version such as 1.3.0.4)`) + } + validateOptionalHostApis(target.optionalHostApis, `${label}.optionalHostApis`, errors) } if (getManifestPlatforms(manifest).length === 0) { errors.push('targets must include at least one target with runtime "electron", otherwise no ZTools client can install this plugin') @@ -353,6 +377,7 @@ export function validatePluginManifest(manifest, options = {}) { if (manifest.minAppVersion !== undefined && (typeof manifest.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(manifest.minAppVersion))) { errors.push(`Invalid minAppVersion format: "${manifest.minAppVersion}" (expected client version such as 1.1.8.3)`) } + validateOptionalHostApis(manifest.optionalHostApis, 'optionalHostApis', errors) if (manifest.requiredCapabilities !== undefined) { if (!Array.isArray(manifest.requiredCapabilities)) { errors.push('requiredCapabilities must be an array') @@ -965,6 +990,15 @@ export function validateCatalogPluginItem(item) { if (item.minAppVersion !== undefined && (typeof item.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(item.minAppVersion))) { errors.push(`Invalid minAppVersion format: "${item.minAppVersion}"`) } + if (Array.isArray(item.targets)) { + for (const [idx, target] of item.targets.entries()) { + if (!target || typeof target !== 'object' || Array.isArray(target)) continue + if (target.minAppVersion !== undefined && (typeof target.minAppVersion !== 'string' || !APP_VERSION_REGEX.test(target.minAppVersion))) { + errors.push(`targets[${idx}].minAppVersion has invalid format: "${target.minAppVersion}"`) + } + validateOptionalHostApis(target.optionalHostApis, `targets[${idx}].optionalHostApis`, errors) + } + } if (item.requiredCapabilities !== undefined) { if (!Array.isArray(item.requiredCapabilities)) { errors.push('requiredCapabilities must be an array') diff --git a/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs b/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs index da03556..cfeb6ff 100644 --- a/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs +++ b/packages/ztools-plugins-spec/tests/catalog-validator.test.mjs @@ -191,6 +191,34 @@ describe('Store Catalog & Plugin Item Validator (Beyond Happy Path)', () => { assert.ok(res.errors.some((e) => e.includes('screenshots[0]'))) assert.equal(validateCatalogPluginItem({ id: 'bad-root', name: '测试', version: '1.0.0', i18n: ['en-US'] }).valid, false) }) + + it('支持校验目录条目 targets[].minAppVersion 与 targets[].optionalHostApis,拒绝非法格式', () => { + const validItem = { + id: 'platform-versioned-tool', + name: '分平台版本工具', + version: '1.0.0', + minAppVersion: '1.3.0.2', + targets: [ + { id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any', minAppVersion: '1.3.0.4', optionalHostApis: ['image_ocr'] }, + { id: 'macos-electron-any', platform: 'macos', runtime: 'electron', arch: 'any', minAppVersion: '1.3.0.2' } + ] + } + assert.equal(validateCatalogPluginItem(validItem).valid, true) + + const badVer = validateCatalogPluginItem({ + ...validItem, + targets: [{ id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any', minAppVersion: 'v1.3.0' }] + }) + assert.equal(badVer.valid, false) + assert.ok(badVer.errors.some((e) => e.includes('targets[0].minAppVersion'))) + + const badOpt = validateCatalogPluginItem({ + ...validItem, + targets: [{ id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any', optionalHostApis: ['BadName', 'image_ocr', 'image_ocr'] }] + }) + assert.equal(badOpt.valid, false) + assert.ok(badOpt.errors.some((e) => e.includes('targets[0].optionalHostApis'))) + }) }) describe('validateStoreCatalog', () => { @@ -500,6 +528,65 @@ describe('Store Catalog & Plugin Item Validator (Beyond Happy Path)', () => { assert.equal(missingTop.valid, false) assert.ok(missingTop.errors.some((e) => e.includes('top-level features is not defined'))) }) + + it('支持声明顶层 optionalHostApis 与 target 级 minAppVersion / optionalHostApis,并拒绝非法值与重复项', () => { + const schema = JSON.parse(fs.readFileSync(new URL('../plugin.schema.json', import.meta.url), 'utf8')) + assert.equal(schema.properties.optionalHostApis.uniqueItems, true) + assert.equal(schema.properties.targets.items.properties.minAppVersion.type, 'string') + assert.equal(schema.properties.targets.items.properties.optionalHostApis.uniqueItems, true) + + const base = { + id: 'optional-api-demo', + name: '可选接口演示', + version: '1.0.0', + description: '验证分平台门槛与可选降级声明', + author: 'Plugin Dev', + category: ['开发工具'], + entry: 'dist/index.js', + icon: 'icon.svg', + permissions: [], + optionalHostApis: ['image_ocr'], + targets: [ + { + id: 'windows-electron-any', + platform: 'windows', + runtime: 'electron', + arch: 'any', + minAppVersion: '1.3.0.4', + optionalHostApis: ['tool_image'] + }, + { + id: 'macos-electron-any', + platform: 'macos', + runtime: 'electron', + arch: 'any', + minAppVersion: '1.3.0.2' + } + ], + nativeComponents: [] + } + const ok = validatePluginManifest(base) + assert.equal(ok.valid, true, ok.errors.join('; ')) + + const badTopOpt = validatePluginManifest({ ...base, optionalHostApis: ['image_ocr', 'image_ocr', 'UpperCase'] }) + assert.equal(badTopOpt.valid, false) + assert.ok(badTopOpt.errors.some((e) => e.includes('Duplicate optionalHostApis'))) + assert.ok(badTopOpt.errors.some((e) => e.includes('invalid host API name'))) + + const badTargetMin = validatePluginManifest({ + ...base, + targets: [{ ...base.targets[0], minAppVersion: '1.3.0-beta.1' }] + }) + assert.equal(badTargetMin.valid, false) + assert.ok(badTargetMin.errors.some((e) => e.includes('targets[0].minAppVersion'))) + + const badTargetOpt = validatePluginManifest({ + ...base, + targets: [{ ...base.targets[0], optionalHostApis: 'not-array' }] + }) + assert.equal(badTargetOpt.valid, false) + assert.ok(badTargetOpt.errors.some((e) => e.includes('targets[0].optionalHostApis must be an array'))) + }) }) describe('官方名单与官方作者名', () => { diff --git a/packages/ztools-plugins-spec/tests/host-requirements.test.mjs b/packages/ztools-plugins-spec/tests/host-requirements.test.mjs index e5e8700..b7595c6 100644 --- a/packages/ztools-plugins-spec/tests/host-requirements.test.mjs +++ b/packages/ztools-plugins-spec/tests/host-requirements.test.mjs @@ -3,8 +3,15 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import os from 'node:os' import path from 'node:path' -import { compareAppVersion, resolvePluginMinAppVersion, HOST_API_REQUIREMENTS } from '../src/host-requirements.js' -import { validateCatalogPluginItem, validatePluginManifest } from '../src/validator.js' +import { + compareAppVersion, + resolvePluginMinAppVersion, + resolvePluginTargetMinAppVersions, + formatTargetMinAppVersionsSummary, + HOST_API_REQUIREMENTS, + CAPABILITY_MIN_APP_VERSIONS +} from '../src/host-requirements.js' +import { validateCatalogPluginItem, validatePluginManifest, TOOL_CAPABILITY_IDS } from '../src/validator.js' const tmpDirs = new Set() @@ -50,7 +57,9 @@ describe('最低客户端版本(minAppVersion)', () => { it('运行代码用到登记的宿主接口时自动要求对应客户端版本', () => { const dir = makePlugin({ 'dist/volume-ipc.js': "callHostTransport('system_list_volumes', {})" }) const result = resolvePluginMinAppVersion(dir, {}) - assert.deepEqual(result, { minAppVersion: '1.1.8.3', apis: ['system_list_volumes'] }) + assert.equal(result.minAppVersion, '1.1.8.3') + assert.deepEqual(result.apis, ['system_list_volumes']) + assert.deepEqual(result.unsupported, []) }) it('只看运行代码:src/ 与测试里出现接口名不算', () => { @@ -60,7 +69,10 @@ describe('最低客户端版本(minAppVersion)', () => { 'tests/a.test.mjs': "'clipboard_history_restore'", 'dist/b.test.js': "'filesystem_move_file_no_replace'" }) - assert.deepEqual(resolvePluginMinAppVersion(dir, {}), { minAppVersion: undefined, apis: [] }) + const result = resolvePluginMinAppVersion(dir, {}) + assert.equal(result.minAppVersion, undefined) + assert.deepEqual(result.apis, []) + assert.deepEqual(result.unsupported, []) }) it('plugin.json 手写的版本更高时以手写为准,更低时以接口要求为准', () => { @@ -69,8 +81,21 @@ describe('最低客户端版本(minAppVersion)', () => { assert.equal(resolvePluginMinAppVersion(dir, { minAppVersion: '1.1.0.0' }).minAppVersion, '1.1.8.3') }) - it('登记表的版本号格式都合法', () => { - for (const item of HOST_API_REQUIREMENTS) assert.notEqual(compareAppVersion(item.minAppVersion, '1.0.0.0'), null, item.api) + it('登记表的分平台版本号与 CAPABILITY_MIN_APP_VERSIONS 映射格式都合法', () => { + assert.equal(HOST_API_REQUIREMENTS.length, 36) + for (const item of HOST_API_REQUIREMENTS) { + assert.equal(typeof item.minAppVersion, 'object', item.api) + for (const platform of ['windows', 'macos']) { + const ver = item.minAppVersion[platform] + assert.ok(ver === null || compareAppVersion(ver, '1.0.0.0') !== null, `${item.api}.${platform}`) + } + } + assert.deepEqual(Object.keys(CAPABILITY_MIN_APP_VERSIONS).sort(), [...TOOL_CAPABILITY_IDS].sort()) + for (const [cap, map] of Object.entries(CAPABILITY_MIN_APP_VERSIONS)) { + for (const platform of ['windows', 'macos']) { + assert.ok(map[platform] === null || compareAppVersion(map[platform], '1.0.0.0') !== null, `${cap}.${platform}`) + } + } }) it('依赖 1.1.8.5 新宿主能力的安装包要求 1.1.8.5(v1.1.8.4 安装包不带这些接口),且不被旧清单要求降级', (t) => { @@ -192,4 +217,108 @@ describe('最低客户端版本(minAppVersion)', () => { assert.equal(validateCatalogPluginItem({ ...item, minAppVersion: '1.1.8.3' }).valid, true) assert.equal(validateCatalogPluginItem({ ...item, minAppVersion: 1 }).valid, false) }) + + it('分平台推断:双端异构版本各自回填、顶层取双端最小值;仅单端有门槛时顶层不误拦无门槛端', () => { + const dir = makePlugin({ 'dist/logic.js': "call('custom_cross_api', {})" }) + const customReqs = [ + { api: 'custom_cross_api', minAppVersion: { windows: '1.3.1.0', macos: '1.3.0.4' }, pattern: /\bcustom_cross_api\b/ } + ] + const dualTargets = [ + { id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any' }, + { id: 'macos-electron-any', platform: 'macos', runtime: 'electron', arch: 'any' } + ] + + const res = resolvePluginTargetMinAppVersions(dir, { targets: dualTargets }, { requirements: customReqs }) + assert.equal(res.targets.windows.minAppVersion, '1.3.1.0') + assert.equal(res.targets.macos.minAppVersion, '1.3.0.4') + assert.equal(res.minAppVersion, '1.3.0.4', '双端均有门槛时顶层兼容兜底应取最小值') + assert.deepEqual(res.unsupported, []) + assert.equal(formatTargetMinAppVersionsSummary(res), 'Win ≥ 1.3.1.0 / Mac ≥ 1.3.0.4') + + // 仅 Windows 有 target.minAppVersion、macOS 无门槛且未命中 API:顶层 minAppVersion 应为 undefined,避免旧客户端误拒 macOS + const plainDir = makePlugin({ 'dist/index.js': 'export default 1' }) + const oneSide = resolvePluginTargetMinAppVersions(plainDir, { + targets: [ + { id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any', minAppVersion: '1.3.1.0' }, + { id: 'macos-electron-any', platform: 'macos', runtime: 'electron', arch: 'any' } + ] + }) + assert.equal(oneSide.targets.windows.minAppVersion, '1.3.1.0') + assert.equal(oneSide.targets.macos.minAppVersion, undefined) + assert.equal(oneSide.minAppVersion, undefined) + assert.equal(formatTargetMinAppVersionsSummary(oneSide), 'Win ≥ 1.3.1.0 / Mac -') + }) + + it('分平台推断:某平台暂未实现(null)时记入 unsupported;通过顶层或 target 级 optionalHostApis 可显式降级放行', () => { + const dir = makePlugin({ 'dist/logic.js': "call('win_only_host_api', {})" }) + const customReqs = [ + { api: 'win_only_host_api', minAppVersion: { windows: '1.3.2.0', macos: null }, pattern: /\bwin_only_host_api\b/ } + ] + const dualTargets = [ + { id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any' }, + { id: 'macos-electron-any', platform: 'macos', runtime: 'electron', arch: 'any' } + ] + + // 1. 未声明降级:macOS target 命中 null -> 阻断 + const blocked = resolvePluginTargetMinAppVersions(dir, { targets: dualTargets }, { requirements: customReqs }) + assert.equal(blocked.targets.windows.minAppVersion, '1.3.2.0') + assert.equal(blocked.targets.macos.minAppVersion, undefined) + assert.deepEqual(blocked.unsupported, [ + { platform: 'macos', targetId: 'macos-electron-any', api: 'win_only_host_api' } + ]) + + // 2. 在 macOS target 声明 optionalHostApis 降级:不再阻断,且不抬高 macOS 门槛 + const macDegraded = resolvePluginTargetMinAppVersions( + dir, + { + targets: [ + dualTargets[0], + { ...dualTargets[1], optionalHostApis: ['win_only_host_api'] } + ] + }, + { requirements: customReqs } + ) + assert.deepEqual(macDegraded.unsupported, []) + assert.equal(macDegraded.targets.windows.minAppVersion, '1.3.2.0') + assert.equal(macDegraded.targets.macos.minAppVersion, undefined) + + // 3. 在顶层声明 optionalHostApis 降级:双端均不抬高门槛也不阻断 + const topDegraded = resolvePluginTargetMinAppVersions( + dir, + { optionalHostApis: ['win_only_host_api'], targets: dualTargets }, + { requirements: customReqs } + ) + assert.deepEqual(topDegraded.unsupported, []) + assert.equal(topDegraded.targets.windows.minAppVersion, undefined) + assert.equal(topDegraded.targets.macos.minAppVersion, undefined) + assert.equal(formatTargetMinAppVersionsSummary(topDegraded), '-') + }) + + it('分平台推断:requiredCapabilities 按 13 项映射表精准提升各端版本并阻断 null 平台能力', () => { + const dir = makePlugin({ 'dist/index.js': 'export default {}' }) + const dualTargets = [ + { id: 'windows-electron-any', platform: 'windows', runtime: 'electron', arch: 'any' }, + { id: 'macos-electron-any', platform: 'macos', runtime: 'electron', arch: 'any' } + ] + + const cap1302 = resolvePluginTargetMinAppVersions(dir, { targets: dualTargets, requiredCapabilities: ['media.capture'] }) + assert.equal(cap1302.targets.windows.minAppVersion, '1.3.0.2') + assert.equal(cap1302.targets.macos.minAppVersion, '1.3.0.2') + assert.equal(cap1302.minAppVersion, '1.3.0.2') + assert.equal(formatTargetMinAppVersionsSummary(cap1302), '≥ 1.3.0.2') + + const cap1304 = resolvePluginTargetMinAppVersions(dir, { targets: dualTargets, requiredCapabilities: ['archive.extract'] }) + assert.equal(cap1304.targets.windows.minAppVersion, '1.3.0.4') + assert.equal(cap1304.targets.macos.minAppVersion, '1.3.0.4') + assert.equal(cap1304.minAppVersion, '1.3.0.4') + + const blockedCap = resolvePluginTargetMinAppVersions( + dir, + { targets: dualTargets, requiredCapabilities: ['media.capture'] }, + { capabilityVersions: { 'media.capture': { windows: '1.3.0.2', macos: null } } } + ) + assert.equal(blockedCap.unsupported.length, 1) + assert.equal(blockedCap.unsupported[0].platform, 'macos') + assert.equal(blockedCap.unsupported[0].api, 'media.capture') + }) }) diff --git a/scripts/build-plugins-release.mjs b/scripts/build-plugins-release.mjs index ec88401..b7b5bd1 100644 --- a/scripts/build-plugins-release.mjs +++ b/scripts/build-plugins-release.mjs @@ -34,7 +34,10 @@ import { normalizeCategoryId, resolveCategoryLabel } from '../packages/ztools-plugins-spec/src/validator.js' -import { resolvePluginMinAppVersion } from '../packages/ztools-plugins-spec/src/host-requirements.js' +import { + resolvePluginTargetMinAppVersions, + formatTargetMinAppVersionsSummary +} from '../packages/ztools-plugins-spec/src/host-requirements.js' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.resolve(__dirname, '..') @@ -721,7 +724,19 @@ export async function buildPluginsRelease(options = {}) { continue } - // 2. 打包为 ZIP 文件 + // 1.5 分平台计算最低宿主版本,并对声明平台不支持的宿主接口/能力 Fail-Fast 阻断构建 + const targetMinVersions = resolvePluginTargetMinAppVersions(dir, manifest, { + requirements: options.hostRequirements, + capabilityVersions: options.capabilityVersions + }) + if (targetMinVersions.unsupported.length > 0) { + const detail = targetMinVersions.unsupported + .map((item) => `${item.platform} (${item.targetId || item.platform}): ${item.api}`) + .join('; ') + throw new Error(`插件 ${pluginId} 使用了声明平台暂不支持的宿主接口/能力,构建中止: ${detail}`) + } + + // 2. 打包为 ZIP 文件(严禁改写 ZIP 内原始 plugin.json,守住 30 天 immutable 缓存) const zipFileName = `${pluginId}-${version}.zip` const pluginOutputDir = path.join(outputDir, authorSlug, pluginId) fs.mkdirSync(pluginOutputDir, { recursive: true }) @@ -784,11 +799,34 @@ export async function buildPluginsRelease(options = {}) { // 作者名谁都能写,按作者名判断会让社区插件拿到官方标记 const isOfficial = OFFICIAL_PLUGIN_IDS.has(manifest.id) - const { minAppVersion, apis: requiredHostApis } = resolvePluginMinAppVersion(dir, manifest) - if (minAppVersion) { - console.log(`ℹ 最低客户端版本 ${minAppVersion}${requiredHostApis.length ? `(用到 ${requiredHostApis.join('、')})` : ''}`) + const minAppVersion = targetMinVersions.minAppVersion + const requiredHostApis = targetMinVersions.apis + const minAppSummary = formatTargetMinAppVersionsSummary(targetMinVersions) + if (minAppSummary !== '-') { + console.log(`ℹ 最低客户端版本 ${minAppSummary}${requiredHostApis.length ? `(用到 ${requiredHostApis.join('、')})` : ''}`) } + // 仅在目录条目的 targets 浅拷贝中回填分平台 minAppVersion,不改动源码/ZIP 内的 plugin.json + const targetEntryById = new Map() + for (const te of targetMinVersions.targetEntries) { + if (te.id) targetEntryById.set(te.id, te) + } + const catalogTargets = Array.isArray(manifest.targets) + ? manifest.targets.map((target) => { + if (!target || typeof target !== 'object' || Array.isArray(target)) return target + const cloned = { ...target } + if (cloned.runtime === 'electron') { + const resolvedEntry = (cloned.id ? targetEntryById.get(cloned.id) : null) || targetMinVersions.targets?.[cloned.platform] + if (resolvedEntry?.minAppVersion) { + cloned.minAppVersion = resolvedEntry.minAppVersion + } else { + delete cloned.minAppVersion + } + } + return cloned + }) + : manifest.targets + const { category, categoryId } = resolveCatalogCategories(manifest) const defaultLocale = typeof manifest.defaultLocale === 'string' && LOCALE_TAG_REGEX.test(manifest.defaultLocale) ? manifest.defaultLocale @@ -820,8 +858,8 @@ export async function buildPluginsRelease(options = {}) { ? { requiredCapabilities: [...manifest.requiredCapabilities] } : {}), requireAdmin: !!manifest.requireAdmin, - // 平台声明由 plugin.json 的 targets 决定(安全扫描已校验必填与格式),不再默认填「双端」 - targets: manifest.targets, + // 平台声明由 plugin.json 的 targets 决定(安全扫描已校验必填与格式),并附加分平台最低客户端版本门槛 + targets: catalogTargets, // 便于客户端与市场直接展示:'windows' / 'macos' 的子集 platforms: getManifestPlatforms(manifest), nativeComponents: [], diff --git a/scripts/verify-changed-plugins.mjs b/scripts/verify-changed-plugins.mjs index 8a3f59e..2c36105 100644 --- a/scripts/verify-changed-plugins.mjs +++ b/scripts/verify-changed-plugins.mjs @@ -29,6 +29,10 @@ import { fileURLToPath } from 'node:url' import { scanPluginSecurity } from './scan-plugin-security.mjs' import { checkSinglePluginI18n } from './check-i18n-public.mjs' import { describePlatforms, getManifestPlatforms, isNativePluginManifest } from '../packages/ztools-plugins-spec/src/validator.js' +import { + resolvePluginTargetMinAppVersions, + formatTargetMinAppVersionsSummary +} from '../packages/ztools-plugins-spec/src/host-requirements.js' const SHARED_DIR = 'shared' const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', SHARED_DIR, 'scripts', 'packages']) @@ -138,7 +142,14 @@ function runStep(cmd, args, cwd) { /** * 执行检查,返回每个插件的结果;不直接退出进程,便于测试 */ -export async function verifyChangedPlugins({ root = process.cwd(), base = null, all = false, skipTests = false } = {}) { +export async function verifyChangedPlugins({ + root = process.cwd(), + base = null, + all = false, + skipTests = false, + hostRequirements = undefined, + capabilityVersions = undefined +} = {}) { root = path.resolve(root) const pluginsRel = fs.existsSync(path.join(root, 'extensions')) ? 'extensions' : 'plugins' const plugins = listPluginDirs(root, pluginsRel) @@ -265,6 +276,18 @@ export async function verifyChangedPlugins({ root = process.cwd(), base = null, } if (scan.requiresTwoManReview) r.notes.push(`需重点审核: ${scan.twoManReviewReasons.join('; ')}`) + // 分平台最低宿主版本推断与平台能力支持校验:若命中声明平台暂未支持的宿主 API/能力则阻断合并 + const minAppResult = resolvePluginTargetMinAppVersions(path.join(root, dir), manifest, { + requirements: hostRequirements, + capabilityVersions + }) + r.minAppVersionSummary = formatTargetMinAppVersionsSummary(minAppResult) + for (const item of minAppResult.unsupported) { + r.errors.push( + `平台 ${item.platform}(target: ${item.targetId || item.platform})暂不支持宿主接口/能力 "${item.api}",请调整 targets 或在 optionalHostApis 中声明降级` + ) + } + // 多语言基础完整性校验(仅对已含 i18n 或 src/i18n.ts 的插件,或官方插件执行严格检查) const hasI18nConfig = Boolean(manifest.i18n) || fs.existsSync(path.join(root, dir, 'src', 'i18n.ts')) if (hasI18nConfig) { @@ -298,10 +321,10 @@ export function renderSummary(report) { } lines.push(report.passed ? '**全部通过,可以合并。**' : '**未通过,修复后才能合并。**', '') if (report.infra) lines.push('改到了脚本/规范等公共部分,已检查全部插件。', '') - lines.push('| 插件 | 平台 | 结果 | 说明 |', '| --- | --- | --- | --- |') + lines.push('| 插件 | 平台 | 最低宿主版本 | 结果 | 说明 |', '| --- | --- | --- | --- | --- |') for (const r of report.results) { const note = [...r.errors.map((e) => e.split('\n')[0]), ...r.notes].join('
').replace(/\|/g, '\\|') - lines.push(`| ${r.dir} | ${r.platform || '-'} | ${r.errors.length ? '不通过' : '通过'} | ${note} |`) + lines.push(`| ${r.dir} | ${r.platform || '-'} | ${r.minAppVersionSummary || '-'} | ${r.errors.length ? '不通过' : '通过'} | ${note} |`) } return lines.join('\n') }