@openfairygui/backend 0.5.0-alpha.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -3
- package/dist/docs.cjs +190 -611
- package/dist/docs.d.cts +9 -27
- package/dist/docs.d.mts +9 -27
- package/dist/docs.mjs +190 -611
- package/dist/index.cjs +445 -635
- package/dist/index.d.cts +46 -160
- package/dist/index.d.mts +46 -160
- package/dist/index.mjs +445 -636
- package/dist/node.cjs +476 -664
- package/dist/node.d.cts +20 -94
- package/dist/node.d.mts +20 -94
- package/dist/node.mjs +476 -664
- package/package.json +3 -3
- package/src/contracts.ts +2 -2
- package/src/diagnostics.ts +4 -5
- package/src/generated/contracts.ts +208 -837
- package/src/generated/docs.ts +3 -3
- package/src/index.ts +2 -13
- package/src/node.ts +36 -30
- package/src/runtime/capabilities.ts +2 -12
- package/src/runtime/contracts.ts +33 -107
- package/src/runtime.ts +22 -57
- package/src/services/authoring-service.ts +9 -572
- package/src/services/cache-service.ts +32 -10
- package/src/services/context.ts +27 -14
- package/src/services/event-service.ts +10 -8
- package/src/services/persistence-service.ts +550 -0
- package/src/services/read-service.ts +18 -18
- package/src/services/runtime-service.ts +27 -36
- package/src/services/session-operation-queue.ts +21 -0
- package/src/services/session-project-writer.ts +3 -1
- package/src/services/session-registry.ts +70 -0
- package/src/services/session-utils.ts +4 -4
- package/src/services/job-service.ts +0 -238
package/src/generated/docs.ts
CHANGED
|
@@ -2,11 +2,11 @@
|
|
|
2
2
|
export const INSTALLED_DOCS = {
|
|
3
3
|
"version": {
|
|
4
4
|
"packageName": "@openfairygui/backend",
|
|
5
|
-
"packageVersion": "0.
|
|
5
|
+
"packageVersion": "0.6.0",
|
|
6
6
|
"nodeEngine": ">=22",
|
|
7
|
-
"documentationDigest": "
|
|
7
|
+
"documentationDigest": "b816b3710f39da19fee23a39c8b8c431df23180faae8eef0a0a4373240b7696f"
|
|
8
8
|
},
|
|
9
9
|
"workflow": "# Installed OpenFairyGUI workflow\n\nThis is a minimal offline companion, not the full website. Read `ofgui docs ls --json` for the installed package version, contract version, capability schema version and digest. Use the project's installed `ofgui`/`ofgui-mcp`, not a global executable or an online latest-version lookup. A mismatched installation must be reconciled by the host before editing.\n\n## Discover the current contract\n\n- `ofgui docs find \"selector\" --json` searches this installed corpus.\n- `ofgui docs cat contracts --json` lists Core operations and Backend/MCP mappings.\n- `ofgui docs schema setDisplayNodeProps --json` reads one self-contained operation schema.\n- `ofgui docs schema cli/validate --json` reads the installed CLI output schema; `cli/docs cat` is a valid exact document ID for the nested command.\n- `ofgui docs cat methods/queryEntity --json` reads precise input/output wire schemas.\n- `ofgui docs diagnostic stale_write --json` reads recovery guidance.\n- MCP `resources/read` at `openfairygui://docs/index` provides the same index and content URIs. MCP is local stdio, not an assumed HTTP port.\n\nThe generated schemas describe JSON wire structure and input budgets, not semantic validity. Native SDK byte fields remain Uint8Array; MCP transports declared byte fields as integer arrays. Arbitrary extension data is not converted. Host objects/functions are omitted from MCP wire schemas; use SDK declarations for host injection, not guessed JSON fields.\n\nMCP allows up to 8 MiB of aggregate byte input at generated byte paths, without applying the general 10000-element array or per-byte node limits. Arbitrary metadata retains general limits. All value-bearing Gear defaults may be null, preserving the owner's initial state when no default override exists; component-instance controllerOverrides retains controller selections.\n\nAll CLI JSON uses `{schemaVersion:1,command,success:true,result}` or `{schemaVersion:1,command,success:false,error:{code,message},result?}`. Documentation version/index/body fields are inside `result`; read `result.text` for document content. Invalid/incomplete validate and doctor responses retain their full report under `result`. Help/version are text; other JSON-mode stdout contains exactly one document and human logs use stderr. Exit codes: 0 success, 1 workflow failure, 2 arguments, 3 incomplete validation. CLI owns envelopes, not new workflow semantics.\n\n## Edit safely\n\n1. Read capabilities. Existing projects use openSession (with host authorization and a lifetime lock); openProjectSession accepts a host-supplied authoritative UAM, not a shortcut around lossy file-session guards.\n2. Read getProjectOutline to discover exact identities, then queryEntity for the relevant current properties and actual revision. Capabilities list the supported read.entityQuery.kinds: project, package, resource, component, displayNode, controller and transition. Project queries use target {kind:\"project\"} without a selector; package queries use {kind:\"package\",selector:{packageId}}. Both return identity and complete entity.properties.settings. Controllers use packageId + componentResourceId + controllerName; transitions use packageId + componentResourceId + transitionName. Names are exact and component-scoped; duplicates fail as ambiguous. Controller snapshots include pages/actions; transition snapshots include items. Gears are already included in displayNode snapshots. Fixed projections exclude source bytes; budget failures require host inspection.\n3. Read the operation and method schemas. Plan the smallest authorized batch using current identifiers and expectedRevision.\n4. preflightTransaction executes on an isolated snapshot and discards it. Inspect projectedRevision, impact.entities (exact identities and changed fields, including reference normalization), impact.files (ProjectWriter model diff, not a disk write plan) and persistence.nextAction. The diff starts at the current revision, not the last save. It contains no source bytes. Summary overflow or serialization failure returns transaction_preview_failed without a partial result. No revision is reserved; writeVerified is always false. It does not save files or guarantee later apply/save/publish.\n5. Only when authorized, applyTransaction with the planned batch and expectedRevision. On stale_write, refresh and replan; never blindly substitute a newer revision.\n6. validateSession checks the new authoritative state. A successful response can contain an invalid or incomplete validation report; require status valid and complete true before treating validation as passed.\n7. When authorized, saveSession checks revision independently and writes the original project only. Keep path policy, UAM fidelity and rollback guards. Close the session only after handling unsaved changes. Read saved output again when disk round-trip is part of acceptance.\n\nPreview permits invalid references in the existing snapshot so a repair can be reviewed, but serializes that snapshot only into memory. The projected state and all persistence remain validated; unsupported or unrepresentable snapshots still fail explicitly.\n\nupdateProjectSettings and updatePackageSettings replace complete settings snapshots. Copy the corresponding query's entity.properties.settings, change only requested fields, retain other nested settings and optional fields, and submit the complete settings with the queried revision. Package updates also require the original packageId selector. Settings queries share the same response budgets as other entity kinds.\n\nupdateController and updateTransition replace complete snapshots, not partial patches. Copy the queried entity.properties, change only the requested fields, preserve page IDs/remarks/actions, item order/targets, settings and references, and submit the original selector with the queried revision. A stale_write requires refreshing and replanning the full snapshot for all these replacement operations. Querying does not validate references or grant permission to edit them.\n\n## Consume the committed session state\n\nFor complete public UAM consumption, use readSessionState({sessionId, expectedRevision?}); use queryEntity for targeted properties. The detached model excludes only asset resources' primary sourceBytes, retaining sourcePath and JSON extensions. It includes revision, dirty, lastSavedRevision, readComplete, readDiagnostics and uamFidelity. Only this read-model output schema accepts unnamed object fields; transaction input contracts remain unchanged.\n\nRead each asset with readResourceBytes({sessionId, expectedRevision: state.revision, selector:{packageId,resourceId}}). Bytes are detached Uint8Array values in the SDK and integer arrays in MCP, limited to the primary file already held in memory. There is no disk hydration or auxiliary-file discovery. Components are unsupported; unavailable bytes produce session_read_failed with reason bytes_unavailable.\n\nOn stale_read, discard the incomplete model/bytes collection and restart from readSessionState. Reads do not wait for uncommitted transactions, retain historical versions, or reserve revisions. Saving can update sourcePath and dirty without increasing the edit revision; the same revision does not identify permanently identical complete UAM. Completeness/fidelity flags preserve existing meaning and do not guarantee bytes, rendering or saving. Preserve failed reads as failures; never save or repair merely to obtain a read.\n\nCapabilities advertise a 4 MiB compact JSON data limit (depth 64, 500000 nodes) for the model and 1 MiB per primary resource. Both new MCP tools additionally limit the complete JSON CallToolResult, including compact text and structuredContent, to 16 MiB; excess returns mcp_response_budget_exceeded. Native model/buffer overflow returns session_read_failed with reason response_budget_exceeded, without truncation. Read the installed methods/readSessionState and methods/readResourceBytes schemas for precise inputs, results and errors.\n\n## Diagnose without repair\n\n`ofgui doctor --json` checks installed CLI/documentation versions, the Node Backend capability snapshot, in-memory Sharp PNG/JPEG encoding and pixel decoding, and temporary-directory access flags. `ofgui doctor <project-directory-or-fairy-file> --json` additionally runs existing Node project validation, including source reads and available image decoding. Optional `--output-dir <directory>` checks an explicit destination or its nearest existing ancestor, without creating it. Directory checks return the absolute requested `path`, link-resolved `inspectedPath` and `exists` (null when unknown); files, dangling links and access errors fail. The temporary directory must exist. It opens no Backend session, creates no lock, installs nothing, writes no probe files and changes no configuration.\n\nExit 0 means the requested checks completed; exit 1 means a detected error; exit 2 means invalid arguments; exit 3 means native image capability is unavailable/failed or project validation is incomplete. Inspect result.checks, result.errors and result.project. Without a project, its source bytes are not checked. Access flags do not prove effective ACL permissions, available space, later writes/rename/rollback or continued access. The capability manifest remains a declaration; a successful doctor does not prove publish/restore or runtime rendering. Plugins and configured output destinations are not executed or checked automatically; only explicit --output-dir is inspected. This product doctor does not inspect Git, pnpm, repository builds or fixture submodules; maintainers use pnpm repo:doctor for those.\n\nRead diagnostic guides for ownership and recovery boundaries. Every formal Core/Backend diagnostic code is covered; shared codes list all `owners`, while response `owner` identifies the actual source. Missing bytes/decoders, rejected paths and expired sessions require host action; do not invent repair/hydration tools, widen roots, discard unsaved work, or turn incomplete validation into success. Invalid/unsupported operations require schema-based replanning, live locks cannot be removed, and write failures require preserving dirty state and inspecting actual files.\n\n## Publish and recover trusted local artifacts\n\nPublishing and restoration are external Node-hosted workflows, not Backend session methods or general MCP editing tools. The host must authorize input and output directories independently. They require the native image capability; do not rename binary extensions to imitate a different target profile.\n\n- `ofgui publish <project> --output <release-directory> --project-type layabox --json` publishes the current saved project. `--output` overrides runtime artifact destinations; configured code generation still uses its own destinations and project plugins run as trusted local code.\n- The JSON document is `{schemaVersion:1,command:\"publish\",success:true,result:{files:[{path,size}]}}`. Paths are final absolute paths and sizes are bytes. The Node SDK `publishNode()` returns the same `result`. The manifest records actual successful filesystem/atlas writes, including code written through the supplied publish filesystem; it excludes pre-existing untouched files, deletions and arbitrary plugin I/O outside that filesystem. It is not an inventory of everything in the output directory. Explicit runtime output is staged and rolled back on failure; separately configured code outputs and arbitrary plugin effects are not covered by that directory transaction.\n- `ofgui restore <trusted-release-directory> --output <separate-project-directory> --project-type layabox --json` returns `{schemaVersion:1,command:\"restore\",success:true,result:{projectPath,packages:[{id,name}],warnings:[]}}`. Warnings are not a validation pass. Reread the returned projectPath and run `ofgui validate <projectPath> --json`; require valid and complete validation.\n- Both artifact commands exit 0 on workflow success, 1 on workflow failure, and 2 on command syntax errors. Errors are `{schemaVersion:1,command,success:false,error:{code,message}}`, with `publish_failed`, `restore_failed` or `invalid_arguments`. In JSON mode stdout contains only this document; human/plugin output goes to stderr. Help remains human-readable. Errors do not include a claimed successful file manifest.\n- Restore requires a separate directory, not a `.fairy` file. Do not force overwrite by default. `--force` replaces an existing nonempty target only after complete staged recovery; parse/image failures retain the previous target. Only trusted local artifacts are supported, not arbitrary third-party imports.\n- Read `ofgui docs cat restore-limits --json` or MCP resource `openfairygui://docs/restore-limits` for the installed version's full recovery boundary. Accept readable, structurally valid supported semantics and decoded assets, not original project IDs, workspace state, unpublished resources, original filenames/extensions, controller editor selection/export flags, float32 text precision or byte-identical XML.\n",
|
|
10
|
-
"restoreLimits": "# 受限发布产物恢复边界\n\n`restore` 只是一条受限的本地故障恢复路径,不是 FairyGUI 的常规创作入口、第三方发布物导入器或源码还原承诺。本文档记录其安全使用范围,以及当前仓库已经验证过、无法仅凭发布产物稳定恢复的内容。\n\n## 使用范围与安全边界\n\n| 项目 | 当前口径 |\n|---|---|\n| 输入 | 仅处理可信的本地发布目录;不把未知来源 `.fui` / `_fui.bytes` 视为安全输入 |\n| 输出 | 必须是独立工程目录,不接受 `.fairy` 单文件目标 |\n| 路径约束 | 拒绝资源路径、包名、分支名、文件名中的路径逃逸;发布目录内资源若解析到输入目录外也会失败 |\n| 覆盖行为 | 先在相邻暂存目录完成工程和资源写入,再替换目标;`--force` 不会在二进制解析或资源重建前删除旧输出 |\n| 不代表 | 不是恶意文件检测器,也不保证第三方产物能够安全或完整恢复 |\n\n这里的“不可还原”指:\n\n| 项目 | 含义 |\n|---|---|\n| 输入范围 | 仅使用发布目录中的 `.fui` / `_fui.bytes`、图集 PNG、以及同目录 loose 资源 |\n| 判定标准 | 不能稳定、通用、无外部辅助地恢复回原工程语义或原始 XML 文本 |\n| 不包含 | 仍可通过补协议、补 writer 规则、补测试继续收敛的普通实现问题 |\n\n## 总结\n\n| 结论 | 说明 |\n|---|---|\n| 受限恢复目标 | 在可信输入下生成一个可重读、可打开、结构自洽的 FairyGUI 工程 |\n| 不保证目标 | 还原成与原工程逐字节一致的源码工程 |\n| 主要原因 | 发布产物会丢失一部分编辑器阶段信息,或把原始值降精度到运行时格式 |\n\n## 当前已确认的不可还原项\n\n### 1. 发布包中根本不存在的资源或动作\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 组件资源 | 原工程存在、但发布包未携带的组件 XML | 发布产物没有资源定义,restore 无法凭空生成真实内容 | `HitTest/component1.xml`、`PullToRefresh/Button1.xml`、`PullToRefresh/Button2.xml`、`TurnPage/Button3.xml` |\n| Transition item | 原工程存在、但二进制 transition block 未携带的 item | 二进制里没有对应时间轴项,无法可靠反推 | `Transition/BOSS.xml` 中 `target=\"n3\"` 的 6 个 item |\n\n说明:这类内容如果强行补出,只能生成占位内容,不能声称是“还原原工程”。\n\n### 2. 原始资源文件名与扩展名\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 普通图片资源 | 原工程使用的真实文件扩展名与双后缀命名 | 发布包只保留运行时资源名,不稳定保留工程文件名 | `change.jpg -> change.png`、`Paper.jpg -> Paper.png`、`i3.png.png -> i3.png` |\n| 部分 loose 资源 | 若发布名与工程名完全脱钩,且缺少稳定映射线索 | 发布目录只提供发布后文件名,原工程命名信息已经丢失 | 仍可能出现少量发布名残留 |\n\n说明:当前实现已经尽量把“资源 id 命名”还原回工程名,但对原始扩展名并不能做通用、可靠的反推。\n\n### 3. Transition path 的原始文本精度\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 路径字符串 | 编辑器 XML 中 path 的原始小数位数与文本格式 | 发布二进制只保存 float32 数值;写回时只能输出数值等价的字符串 | `Transition/PathDemo.xml` 的 `path` |\n\n说明:这类路径通常还能恢复到相同几何轨迹,但不能保证与原 XML 的字符串完全一致。\n\n### 4. 被降级为运行时默认值的编辑器信息\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| Transition easing | 原工程中的特定 ease 名称 | 当前样本对应二进制读出的就是默认 easing,无法证明原工程曾写过哪个非默认 ease | `Transition/BOSS.xml`、`TRAP.xml`、`GoodHit.xml` 中部分 `Expo.Out` / `Back.Out` / `Bounce.Out` |\n| 简单 Group 节点 | 仅用于编辑器分组、但没有额外运行时语义的 `GGroup` 节点 | 当前样本中的发布组件数据会直接裁掉这类 group,二进制 child list 里既没有 group 节点,也没有可稳定回推的 group 归属索引 | `Basics/Demo_Clip&Scroll.xml`、`Emoji/Main.xml`、`TurnPage/Book.xml` |\n| Group 高级模式 | 原工程 XML 中的 `group.advanced=\"true\"` | 发布 group block写出的是布局与间距等运行时数据,不单独保留编辑器里的高级模式开关;当前样本中二进制读回的 group 会直接落成 `advanced=false` | `Basics/Demo_Grid.xml`、`Transition/Main.xml`、`Transition/PowerUp.xml` |\n| Controller 当前选中页 | 原工程 XML 中的 `controller.selected` 当前页状态 | 发布 controller block稳定保存的是 `homePageType/homePage` 发布首页信息;当前样本中的二进制常写成 `default`,并不保留编辑器工程里当时的非零当前页 | `TurnPage/Main.xml` 的 `bookPos=\"2\"`、`TurnPage/Page.xml` 的 `style=\"1\"` / `side=\"1\"`、`FrontCover.xml` / `BackCover.xml` 的 `side=\"1\"` |\n| Controller 导出标记 | 原工程 XML 中的 `controller.exported=\"true\"` | 当前样本对应的 controller 发布 block只写 `name/pages/homePageType/homePage/actions`,没有独立写出 `exported` | `TurnPage/BackCover.xml`、`TurnPage/FrontCover.xml`、`TurnPage/Page.xml` |\n| 默认值显式性 | 原工程是否显式写出默认属性 | 发布包只保留语义值,不保留“这个默认值当时是否显式写在 XML 里” | 如 `xy=\"0,0\"`、空文本、默认布尔值等 |\n\n说明:这类信息恢复后通常仍然语义可用,但无法保证与原工程的编辑器写法逐项一致。\n\n### 5. 编辑器工程本地设置\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 工程标识 | 原始 `projectId` | restore 会生成新的工程标识 |\n| 工程设置 | 原始 `.objs` / workspace / 编辑器本地状态 | 发布目录不包含这些本地工程文件 |\n| 初始化设置之外的项目配置 | 原工程的非发布产物配置 | 当前 restore 按初始化默认值生成工程设置,而不是恢复源工程工作区状态 |\n\n说明:当前 restore 的目标是“重建可用工程”,不是恢复编辑器本地工作环境。\n\n### 6. 原工程 XML 的文本级细节\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 属性顺序 | 原标签属性排列顺序 | XML 语义不依赖属性顺序,发布产物也不保留该信息 |\n| 格式风格 | 换行、缩进、是否自闭合、空格风格 | 这是 writer 生成结果,不是发布产物协议内容 |\n| 大小写风格 | 某些颜色值、小数文本风格 | 发布包保留的是数值语义,不是原文本样式 |\n\n说明:当前实现会尽量贴近 FairyGUI 编辑器写法,但不会把这类文本风格视为“可从发布产物逆推出的正式数据”。\n\n## 当前恢复输出范围\n\n| 项目 | 当前口径 |\n|---|---|\n| 工程目标 | 在可信输入下生成可读、可打开、可继续编辑的 FairyGUI 工程 |\n| 资源目标 | 尽量恢复包内素材、组件 XML、字体派生图与 `.jta` / `.fnt` 等正式资源 |\n| 不承诺 | 与原工程一模一样的文件名、文本格式、局部编辑器状态 |\n\n## 何时需要外部辅助信息\n\n若目标不是“重建可用工程”,而是“尽量贴近原工程文本或命名”,则需要额外输入:\n\n| 额外输入 | 作用 |\n|---|---|\n| 原工程目录 | 作为命名、路径、缺失资源、文本样式的真实基准 |\n| 编辑器工作区文件 | 恢复 `.objs`、workspace、本地工程状态 |\n| 发布前清单或映射表 | 回填发布名与工程名之间的脱钩关系 |\n\n## 当前样本下仍然成立的判断\n\n| 判断 | 说明 |\n|---|---|\n| 可以从发布产物重建“可工作的工程” | 是 |\n| 可以从发布产物重建“原工程的源码真迹” | 否 |\n| 还原结果是否应该继续优化 | 可以,但应只优化“发布产物里确实有证据的部分” |\n",
|
|
10
|
+
"restoreLimits": "# 受限发布产物恢复边界\n\n`restore` 只是一条受限的本地故障恢复路径,不是 FairyGUI 的常规创作入口、第三方发布物导入器或源码还原承诺。本文档记录其安全使用范围,以及当前仓库已经验证过、无法仅凭发布产物稳定恢复的内容。\n\n## 使用范围与安全边界\n\n| 项目 | 当前口径 |\n|---|---|\n| 输入 | 仅处理可信的本地发布目录;不把未知来源 `.fui` / `_fui.bytes` 视为安全输入 |\n| 输出 | 必须是独立工程目录,不接受 `.fairy` 单文件目标 |\n| 路径约束 | 拒绝资源路径、包名、分支名、文件名中的路径逃逸;发布目录内资源若解析到输入目录外也会失败 |\n| 覆盖行为 | 先在相邻暂存目录完成工程和资源写入,再替换目标;`--force` 不会在二进制解析或资源重建前删除旧输出 |\n| 不代表 | 不是恶意文件检测器,也不保证第三方产物能够安全或完整恢复 |\n\n这里的“不可还原”指:\n\n| 项目 | 含义 |\n|---|---|\n| 输入范围 | 仅使用发布目录中的 `.fui` / `_fui.bytes`、图集 PNG、以及同目录 loose 资源 |\n| 判定标准 | 不能稳定、通用、无外部辅助地恢复回原工程语义或原始 XML 文本 |\n| 不包含 | 仍可通过补协议、补 writer 规则、补测试继续收敛的普通实现问题 |\n\n## 总结\n\n| 结论 | 说明 |\n|---|---|\n| 受限恢复目标 | 在可信输入下生成一个可重读、可打开、结构自洽的 FairyGUI 工程 |\n| 不保证目标 | 还原成与原工程逐字节一致的源码工程 |\n| 主要原因 | 发布产物会丢失一部分编辑器阶段信息,或把原始值降精度到运行时格式 |\n\n## 当前已确认的不可还原项\n\n恢复时推导出的图片尺寸用于资源重建,但不作为原始声明尺寸写入 `package.xml`;生成的字体纹理和字形图片按顺序跟随对应字体。`RestoreResult.document` 保留尺寸省略与资源排序两种写入提示,交给新的 `ProjectWriter` 或 `NodeIO.writeProject()` 仍生效。提示属于内存中的序列化控制,不随 UAM 转换或重新读取传播。`ProjectWriter.setImageWriteHints(image, {})` 清除该图片的全部提示,恢复普通尺寸写回和资源排序;需要保留排序时,设置 `{ packageOrder: { afterId, weight } }`,其中目标是同包、同分支且未设置排序提示的资源。\n\n### 1. 发布包中根本不存在的资源或动作\n\n发布物中缺失独立资源项的字形图像使用稳定 glyph 图像 ID 的 UTF-8 十六进制生成 `images/glyph-<id>.png`,不同字体的不同图像 ID 不会因字符相同而重名。已有资源项保留发布物中的名称和路径;生成名称不代表原始源文件名,不依据示例包名或字体名称猜测。\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 组件资源 | 原工程存在、但发布包未携带的组件 XML | 发布产物没有资源定义,restore 无法凭空生成真实内容 | `HitTest/component1.xml`、`PullToRefresh/Button1.xml`、`PullToRefresh/Button2.xml`、`TurnPage/Button3.xml` |\n| Transition item | 原工程存在、但二进制 transition block 未携带的 item | 二进制里没有对应时间轴项,无法可靠反推 | `Transition/BOSS.xml` 中 `target=\"n3\"` 的 6 个 item |\n\n说明:这类内容如果强行补出,只能生成占位内容,不能声称是“还原原工程”。\n\n### 2. 原始资源文件名与扩展名\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 普通图片资源 | 原工程使用的真实文件扩展名与双后缀命名 | 发布包只保留运行时资源名,不稳定保留工程文件名 | `change.jpg -> change.png`、`Paper.jpg -> Paper.png`、`i3.png.png -> i3.png` |\n| 部分 loose 资源 | 若发布名与工程名完全脱钩,且缺少稳定映射线索 | 发布目录只提供发布后文件名,原工程命名信息已经丢失 | 仍可能出现少量发布名残留 |\n\n说明:当前实现已经尽量把“资源 id 命名”还原回工程名,但对原始扩展名并不能做通用、可靠的反推。\n\n### 3. Transition path 的原始文本精度\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| 路径字符串 | 编辑器 XML 中 path 的原始小数位数与文本格式 | 发布二进制只保存 float32 数值;写回时只能输出数值等价的字符串 | `Transition/PathDemo.xml` 的 `path` |\n\n说明:这类路径通常还能恢复到相同几何轨迹,但不能保证与原 XML 的字符串完全一致。\n\n### 4. 被降级为运行时默认值的编辑器信息\n\n| 类别 | 不可还原内容 | 原因 | 当前样本证据 |\n|---|---|---|---|\n| Transition easing | 原工程中的特定 ease 名称 | 当前样本对应二进制读出的就是默认 easing,无法证明原工程曾写过哪个非默认 ease | `Transition/BOSS.xml`、`TRAP.xml`、`GoodHit.xml` 中部分 `Expo.Out` / `Back.Out` / `Bounce.Out` |\n| 简单 Group 节点 | 仅用于编辑器分组、但没有额外运行时语义的 `GGroup` 节点 | 当前样本中的发布组件数据会直接裁掉这类 group,二进制 child list 里既没有 group 节点,也没有可稳定回推的 group 归属索引 | `Basics/Demo_Clip&Scroll.xml`、`Emoji/Main.xml`、`TurnPage/Book.xml` |\n| Group 高级模式 | 原工程 XML 中的 `group.advanced=\"true\"` | 发布 group block写出的是布局与间距等运行时数据,不单独保留编辑器里的高级模式开关;当前样本中二进制读回的 group 会直接落成 `advanced=false` | `Basics/Demo_Grid.xml`、`Transition/Main.xml`、`Transition/PowerUp.xml` |\n| Controller 当前选中页 | 原工程 XML 中的 `controller.selected` 当前页状态 | 发布 controller block稳定保存的是 `homePageType/homePage` 发布首页信息;当前样本中的二进制常写成 `default`,并不保留编辑器工程里当时的非零当前页 | `TurnPage/Main.xml` 的 `bookPos=\"2\"`、`TurnPage/Page.xml` 的 `style=\"1\"` / `side=\"1\"`、`FrontCover.xml` / `BackCover.xml` 的 `side=\"1\"` |\n| Controller 导出标记 | 原工程 XML 中的 `controller.exported=\"true\"` | 当前样本对应的 controller 发布 block只写 `name/pages/homePageType/homePage/actions`,没有独立写出 `exported` | `TurnPage/BackCover.xml`、`TurnPage/FrontCover.xml`、`TurnPage/Page.xml` |\n| 默认值显式性 | 原工程是否显式写出默认属性 | 发布包只保留语义值,不保留“这个默认值当时是否显式写在 XML 里” | 如 `xy=\"0,0\"`、空文本、默认布尔值等 |\n\n说明:这类信息恢复后通常仍然语义可用,但无法保证与原工程的编辑器写法逐项一致。\n\n### 5. 编辑器工程本地设置\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 工程标识 | 原始 `projectId` | restore 会生成新的工程标识 |\n| 工程设置 | 原始 `.objs` / workspace / 编辑器本地状态 | 发布目录不包含这些本地工程文件 |\n| 初始化设置之外的项目配置 | 原工程的非发布产物配置 | 当前 restore 按初始化默认值生成工程设置,而不是恢复源工程工作区状态 |\n\n说明:当前 restore 的目标是“重建可用工程”,不是恢复编辑器本地工作环境。\n\n### 6. 原工程 XML 的文本级细节\n\n| 类别 | 不可还原内容 | 原因 |\n|---|---|---|\n| 属性顺序 | 原标签属性排列顺序 | XML 语义不依赖属性顺序,发布产物也不保留该信息 |\n| 格式风格 | 换行、缩进、是否自闭合、空格风格 | 这是 writer 生成结果,不是发布产物协议内容 |\n| 大小写风格 | 某些颜色值、小数文本风格 | 发布包保留的是数值语义,不是原文本样式 |\n\n说明:当前实现会尽量贴近 FairyGUI 编辑器写法,但不会把这类文本风格视为“可从发布产物逆推出的正式数据”。\n\n## 当前恢复输出范围\n\n| 项目 | 当前口径 |\n|---|---|\n| 工程目标 | 在可信输入下生成可读、可打开、可继续编辑的 FairyGUI 工程 |\n| 资源目标 | 尽量恢复包内素材、组件 XML、字体派生图与 `.jta` / `.fnt` 等正式资源 |\n| 不承诺 | 与原工程一模一样的文件名、文本格式、局部编辑器状态 |\n\n## 何时需要外部辅助信息\n\n若目标不是“重建可用工程”,而是“尽量贴近原工程文本或命名”,则需要额外输入:\n\n| 额外输入 | 作用 |\n|---|---|\n| 原工程目录 | 作为命名、路径、缺失资源、文本样式的真实基准 |\n| 编辑器工作区文件 | 恢复 `.objs`、workspace、本地工程状态 |\n| 发布前清单或映射表 | 回填发布名与工程名之间的脱钩关系 |\n\n## 当前样本下仍然成立的判断\n\n| 判断 | 说明 |\n|---|---|\n| 可以从发布产物重建“可工作的工程” | 是 |\n| 可以从发布产物重建“原工程的源码真迹” | 否 |\n| 还原结果是否应该继续优化 | 可以,但应只优化“发布产物里确实有证据的部分” |\n",
|
|
11
11
|
"skill": "---\nname: openfairygui\ndescription: Navigate an installed OpenFairyGUI SDK, CLI or MCP server for FairyGUI project inspection, precise queries, revision-checked authoring and diagnosis. Use the installed version's offline documentation and generated schemas before constructing operations.\n---\n\n# OpenFairyGUI installed-version navigation\n\nUse this skill for OpenFairyGUI project workflows, not unrelated GUI frameworks.\n\n1. Locate the intended project's installed `ofgui` binary (local `node_modules/.bin/ofgui`, `ofgui.cmd` on Windows) or its configured MCP server. Do not use `npx`, install, upgrade, or fall back to a global executable automatically. If missing, report the missing installation and ask the host to choose it.\n2. Read `ofgui --version` and `ofgui docs ls --json`; compare the CLI and documentation package versions. In MCP, read `openfairygui://docs/index` and the server's version. Report mismatches before authoring; do not use online latest-version docs as the installed contract.\n3. Read `ofgui docs cat workflow` or the index's workflow URI. Use `docs find`, `docs schema <kind>`, `docs cat methods/<method>` and `docs diagnostic <code>` (or the listed MCP URIs) for exact current inputs and recovery boundaries. Never copy or guess operation grammar from this skill.\n4. Follow outline → exact query → plan → preflight → authorized apply → validate → authorized save → reread. Revision changes require refreshing and replanning, not blind retries. Read-only requests do not authorize opening locked file sessions, mutations or repairs.\n5. Use `ofgui doctor [project] --json` for read-only installation/project diagnosis. Missing bytes/decoders and path/session failures may require host action. Preserve unsaved work and report incomplete checks honestly.\n\nThe commands above navigate this installed corpus; they do not grant permission to change projects, install dependencies or widen filesystem access.\n"
|
|
12
12
|
};
|
package/src/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ export {
|
|
|
19
19
|
} from './diagnostics.js';
|
|
20
20
|
export {
|
|
21
21
|
type AdvisoryLockConflictError,
|
|
22
|
+
ProjectWriteTransactionError,
|
|
22
23
|
type ApplySessionTransactionInput,
|
|
23
24
|
type BackendArtifactBridgeCapability,
|
|
24
25
|
type BackendCacheEntry,
|
|
@@ -33,15 +34,6 @@ export {
|
|
|
33
34
|
type BackendFileStat,
|
|
34
35
|
type BackendFileSystem,
|
|
35
36
|
type BackendHostAdapter,
|
|
36
|
-
type BackendJobErrors,
|
|
37
|
-
type BackendJobKind,
|
|
38
|
-
type BackendJobListSnapshot,
|
|
39
|
-
type BackendJobListStatusFilter,
|
|
40
|
-
type BackendJobNotCancellableError,
|
|
41
|
-
type BackendJobNotFoundError,
|
|
42
|
-
type BackendJobProgress,
|
|
43
|
-
type BackendJobSnapshot,
|
|
44
|
-
type BackendJobStatus,
|
|
45
37
|
type BackendMethodName,
|
|
46
38
|
BACKEND_ENTITY_QUERY_LIMITS,
|
|
47
39
|
BACKEND_SESSION_READ_LIMITS,
|
|
@@ -76,16 +68,12 @@ export {
|
|
|
76
68
|
type BackendTransactionPreview,
|
|
77
69
|
type BackendTransactionEntityChange,
|
|
78
70
|
type TransactionPreviewError,
|
|
79
|
-
type CacheRefreshFailedError,
|
|
80
|
-
type CancelJobInput,
|
|
81
71
|
type EventCursorInvalidError,
|
|
82
72
|
type GetCacheSnapshotInput,
|
|
83
73
|
type GetEventsInput,
|
|
84
74
|
type GetEventsSnapshot,
|
|
85
|
-
type GetJobInput,
|
|
86
75
|
type GetProjectOutlineInput,
|
|
87
76
|
type InProcessLockConflictError,
|
|
88
|
-
type ListJobsInput,
|
|
89
77
|
type MaterializeSessionInput,
|
|
90
78
|
type MaterializeSessionSnapshot,
|
|
91
79
|
type MaterializeValidationFailedError,
|
|
@@ -98,6 +86,7 @@ export {
|
|
|
98
86
|
type SaveSessionInput,
|
|
99
87
|
type SessionIdConflictError,
|
|
100
88
|
type SessionNotFoundError,
|
|
89
|
+
type SessionCloseFailedError,
|
|
101
90
|
type SessionStaleWriteError,
|
|
102
91
|
type UamFidelityUnsupportedError,
|
|
103
92
|
type ValidateSessionInput,
|
package/src/node.ts
CHANGED
|
@@ -4,6 +4,7 @@ import path from 'node:path';
|
|
|
4
4
|
import { randomUUID } from 'node:crypto';
|
|
5
5
|
import {
|
|
6
6
|
BackendRuntime,
|
|
7
|
+
ProjectWriteTransactionError,
|
|
7
8
|
type BackendFileStat,
|
|
8
9
|
type BackendFileSystem,
|
|
9
10
|
type BackendHostAdapter,
|
|
@@ -145,33 +146,36 @@ async function runNodeProjectWriteTransaction(
|
|
|
145
146
|
const staging = path.join(parent, `.${name}.save-${randomUUID()}`);
|
|
146
147
|
const backup = path.join(parent, `.${name}.save-backup-${randomUUID()}`);
|
|
147
148
|
const existed = await pathExists(root);
|
|
148
|
-
if (existed) {
|
|
149
|
-
await assertNoSymlinks(root);
|
|
150
|
-
await fs.cp(root, staging, { recursive: true, errorOnExist: true, force: false });
|
|
151
|
-
} else {
|
|
152
|
-
await fs.mkdir(staging, { recursive: true });
|
|
153
|
-
}
|
|
154
149
|
try {
|
|
150
|
+
if (existed) {
|
|
151
|
+
await assertNoSymlinks(root);
|
|
152
|
+
await fs.cp(root, staging, { recursive: true, errorOnExist: true, force: false });
|
|
153
|
+
} else {
|
|
154
|
+
await fs.mkdir(staging, { recursive: true });
|
|
155
|
+
}
|
|
155
156
|
await write(createStagedNodeFileSystem(root, staging));
|
|
157
|
+
// ponytail: two-step rename preserves rollback; use directory exchange if zero reader gap becomes required.
|
|
158
|
+
if (existed) await fs.rename(root, backup);
|
|
159
|
+
try {
|
|
160
|
+
await fs.rename(staging, root);
|
|
161
|
+
} catch (commitError) {
|
|
162
|
+
if (existed) {
|
|
163
|
+
try {
|
|
164
|
+
await fs.rename(backup, root);
|
|
165
|
+
} catch (rollbackError) {
|
|
166
|
+
throw new ProjectWriteTransactionError(
|
|
167
|
+
new AggregateError([commitError, rollbackError], 'Project commit and rollback both failed.'), true, [backup, staging],
|
|
168
|
+
);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
throw commitError;
|
|
172
|
+
}
|
|
156
173
|
} catch (error) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
if (!existed) {
|
|
161
|
-
await fs.rename(staging, root);
|
|
162
|
-
return;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
// ponytail: two-step rename preserves rollback; use directory exchange if zero reader gap becomes required.
|
|
166
|
-
await fs.rename(root, backup);
|
|
167
|
-
try {
|
|
168
|
-
await fs.rename(staging, root);
|
|
169
|
-
} catch (error) {
|
|
170
|
-
await fs.rename(backup, root);
|
|
171
|
-
await fs.rm(staging, { recursive: true, force: true });
|
|
172
|
-
throw error;
|
|
174
|
+
if (ProjectWriteTransactionError.is(error)) throw error;
|
|
175
|
+
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined);
|
|
176
|
+
throw new ProjectWriteTransactionError(error, false);
|
|
173
177
|
}
|
|
174
|
-
await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined);
|
|
178
|
+
if (existed) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined);
|
|
175
179
|
}
|
|
176
180
|
|
|
177
181
|
export function createNodeBackendFileSystem(): BackendFileSystem {
|
|
@@ -253,13 +257,15 @@ export function createNodeBackendFileSystem(): BackendFileSystem {
|
|
|
253
257
|
async release(): Promise<void> {
|
|
254
258
|
if (released) return;
|
|
255
259
|
await closeHandle();
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
260
|
+
try {
|
|
261
|
+
if (metadataWritten) {
|
|
262
|
+
const current = parseLockMetadata(await fs.readFile(filePath, 'utf-8'));
|
|
263
|
+
if (!current) throw new Error('Cannot release session lock: invalid ownership metadata');
|
|
264
|
+
if (current.token !== owner.token) throw new Error('Cannot release session lock: ownership token changed');
|
|
265
|
+
}
|
|
266
|
+
await fs.unlink(filePath);
|
|
267
|
+
} catch (error) {
|
|
268
|
+
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;
|
|
263
269
|
}
|
|
264
270
|
released = true;
|
|
265
271
|
},
|
|
@@ -28,9 +28,6 @@ export const BACKEND_METHODS = [
|
|
|
28
28
|
'materializeSession',
|
|
29
29
|
'closeSession',
|
|
30
30
|
'getEvents',
|
|
31
|
-
'getJob',
|
|
32
|
-
'listJobs',
|
|
33
|
-
'cancelJob',
|
|
34
31
|
'getCacheSnapshot',
|
|
35
32
|
'refreshCache',
|
|
36
33
|
] as const satisfies readonly BackendMethodName[];
|
|
@@ -122,17 +119,10 @@ export function createCapabilities(atomicSave = false): BackendCapabilities {
|
|
|
122
119
|
retentionLimit: 1000,
|
|
123
120
|
sequenceScope: 'runtime',
|
|
124
121
|
},
|
|
125
|
-
jobs: {
|
|
126
|
-
inMemory: true,
|
|
127
|
-
cooperativeCancel: true,
|
|
128
|
-
persistent: false,
|
|
129
|
-
supportedKinds: ['cache.refresh'],
|
|
130
|
-
artifactJobs: false,
|
|
131
|
-
completedRetentionLimit: 100,
|
|
132
|
-
},
|
|
133
122
|
cache: {
|
|
134
123
|
derivedReadOnly: true,
|
|
135
|
-
keyedBy: '
|
|
124
|
+
keyedBy: 'sessionId',
|
|
125
|
+
refreshMode: 'synchronous',
|
|
136
126
|
sourceOfTruth: false,
|
|
137
127
|
refreshMethod: 'refreshCache',
|
|
138
128
|
},
|
package/src/runtime/contracts.ts
CHANGED
|
@@ -144,6 +144,25 @@ export interface BackendFileStat {
|
|
|
144
144
|
isDirectory(): boolean;
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
+
/** A failed staged write with an explicit outcome for the original project. */
|
|
148
|
+
export class ProjectWriteTransactionError extends Error {
|
|
149
|
+
public readonly code = 'project_write_transaction_failed';
|
|
150
|
+
|
|
151
|
+
/** Recognizes the same contract across separately bundled Node/root or ESM/CJS entries. */
|
|
152
|
+
public static is(error: unknown): error is ProjectWriteTransactionError {
|
|
153
|
+
if (typeof error !== 'object' || error === null) return false;
|
|
154
|
+
const value = error as Partial<ProjectWriteTransactionError>;
|
|
155
|
+
return value.code === 'project_write_transaction_failed' && typeof value.message === 'string'
|
|
156
|
+
&& typeof value.diskMayBePartiallyUpdated === 'boolean'
|
|
157
|
+
&& Array.isArray(value.recoveryPaths) && value.recoveryPaths.every((path) => typeof path === 'string');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
constructor(cause: unknown, public readonly diskMayBePartiallyUpdated: boolean, public readonly recoveryPaths: string[] = []) {
|
|
161
|
+
super(cause instanceof Error ? cause.message : String(cause), { cause });
|
|
162
|
+
this.name = 'ProjectWriteTransactionError';
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
147
166
|
export interface BackendFileSystem {
|
|
148
167
|
stat(filePath: string): Promise<BackendFileStat>;
|
|
149
168
|
readdir(dirPath: string): Promise<string[]>;
|
|
@@ -157,7 +176,7 @@ export interface BackendFileSystem {
|
|
|
157
176
|
validateProjectRoot?(projectRoot: string): Promise<void>;
|
|
158
177
|
/** Optional host-specific lock location. Node keeps it beside the project so directory swaps do not move it. */
|
|
159
178
|
getSessionLockPath?(canonicalProjectPath: string): string;
|
|
160
|
-
/**
|
|
179
|
+
/** Stages project writes. On failure, throw ProjectWriteTransactionError to report rollback and recovery paths. */
|
|
161
180
|
runProjectWriteTransaction?(
|
|
162
181
|
projectRoot: string,
|
|
163
182
|
write: (stagedFileSystem: BackendFileSystem) => Promise<void>,
|
|
@@ -274,17 +293,10 @@ export interface BackendCapabilities {
|
|
|
274
293
|
retentionLimit: 1000;
|
|
275
294
|
sequenceScope: 'runtime';
|
|
276
295
|
};
|
|
277
|
-
jobs: {
|
|
278
|
-
inMemory: true;
|
|
279
|
-
cooperativeCancel: true;
|
|
280
|
-
persistent: false;
|
|
281
|
-
supportedKinds: readonly ['cache.refresh'];
|
|
282
|
-
artifactJobs: false;
|
|
283
|
-
completedRetentionLimit: 100;
|
|
284
|
-
};
|
|
285
296
|
cache: {
|
|
286
297
|
derivedReadOnly: true;
|
|
287
|
-
keyedBy: '
|
|
298
|
+
keyedBy: 'sessionId';
|
|
299
|
+
refreshMode: 'synchronous';
|
|
288
300
|
sourceOfTruth: false;
|
|
289
301
|
refreshMethod: 'refreshCache';
|
|
290
302
|
};
|
|
@@ -364,6 +376,13 @@ export interface SessionNotFoundError {
|
|
|
364
376
|
sessionId: string;
|
|
365
377
|
}
|
|
366
378
|
|
|
379
|
+
export interface SessionCloseFailedError {
|
|
380
|
+
code: 'session_close_failed';
|
|
381
|
+
message: string;
|
|
382
|
+
sessionId: string;
|
|
383
|
+
lockFilePath: string;
|
|
384
|
+
}
|
|
385
|
+
|
|
367
386
|
export interface SessionStaleWriteError {
|
|
368
387
|
code: 'stale_write';
|
|
369
388
|
message: string;
|
|
@@ -407,6 +426,7 @@ export interface SavePartialFailureError {
|
|
|
407
426
|
committedPaths: string[];
|
|
408
427
|
failedPaths: string[];
|
|
409
428
|
diskMayBePartiallyUpdated: boolean;
|
|
429
|
+
recoveryPaths?: string[];
|
|
410
430
|
}
|
|
411
431
|
|
|
412
432
|
export interface UamFidelityUnsupportedError {
|
|
@@ -437,6 +457,7 @@ export interface MaterializeWriteFailedError {
|
|
|
437
457
|
skippedPaths: string[];
|
|
438
458
|
diagnostics: BackendDiagnostic[];
|
|
439
459
|
diskMayBePartiallyUpdated: boolean;
|
|
460
|
+
recoveryPaths?: string[];
|
|
440
461
|
}
|
|
441
462
|
|
|
442
463
|
export type BackendEventKind =
|
|
@@ -449,14 +470,7 @@ export type BackendEventKind =
|
|
|
449
470
|
| 'session.closeRequested'
|
|
450
471
|
| 'session.closed'
|
|
451
472
|
| 'cache.invalidated'
|
|
452
|
-
| 'cache.updated'
|
|
453
|
-
| 'job.created'
|
|
454
|
-
| 'job.started'
|
|
455
|
-
| 'job.progress'
|
|
456
|
-
| 'job.cancelRequested'
|
|
457
|
-
| 'job.cancelled'
|
|
458
|
-
| 'job.completed'
|
|
459
|
-
| 'job.failed';
|
|
473
|
+
| 'cache.updated';
|
|
460
474
|
|
|
461
475
|
export interface BackendEvent {
|
|
462
476
|
sequence: number;
|
|
@@ -466,7 +480,6 @@ export interface BackendEvent {
|
|
|
466
480
|
canonicalPathKey?: string;
|
|
467
481
|
revision?: number;
|
|
468
482
|
cacheRevision?: number;
|
|
469
|
-
jobId?: string;
|
|
470
483
|
diagnostics: BackendDiagnostic[];
|
|
471
484
|
payload?: unknown;
|
|
472
485
|
}
|
|
@@ -491,84 +504,6 @@ export interface EventCursorInvalidError {
|
|
|
491
504
|
after: string;
|
|
492
505
|
}
|
|
493
506
|
|
|
494
|
-
export type BackendJobStatus = 'queued' | 'running' | 'completed' | 'failed' | 'cancelled';
|
|
495
|
-
export type BackendJobKind = 'cache.refresh';
|
|
496
|
-
export type BackendJobListStatusFilter = BackendJobStatus | 'active' | 'terminal';
|
|
497
|
-
|
|
498
|
-
export interface BackendJobProgress {
|
|
499
|
-
completed: number;
|
|
500
|
-
total?: number;
|
|
501
|
-
message?: string;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
export interface BackendJobSnapshot {
|
|
505
|
-
jobId: string;
|
|
506
|
-
kind: BackendJobKind;
|
|
507
|
-
status: BackendJobStatus;
|
|
508
|
-
createdAt: string;
|
|
509
|
-
startedAt?: string;
|
|
510
|
-
finishedAt?: string;
|
|
511
|
-
sessionId?: string;
|
|
512
|
-
canonicalPathKey?: string;
|
|
513
|
-
revision?: number;
|
|
514
|
-
cacheRevision?: number;
|
|
515
|
-
diagnostics: BackendDiagnostic[];
|
|
516
|
-
progress?: BackendJobProgress;
|
|
517
|
-
result?: unknown;
|
|
518
|
-
error?: BackendError;
|
|
519
|
-
}
|
|
520
|
-
|
|
521
|
-
export interface BackendJobListSnapshot {
|
|
522
|
-
jobs: BackendJobSnapshot[];
|
|
523
|
-
}
|
|
524
|
-
|
|
525
|
-
export interface GetJobInput {
|
|
526
|
-
sessionId: string;
|
|
527
|
-
jobId: string;
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
export interface ListJobsInput {
|
|
531
|
-
sessionId: string;
|
|
532
|
-
status?: BackendJobListStatusFilter;
|
|
533
|
-
kind?: BackendJobKind;
|
|
534
|
-
limit?: number;
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
export interface CancelJobInput {
|
|
538
|
-
sessionId: string;
|
|
539
|
-
jobId: string;
|
|
540
|
-
}
|
|
541
|
-
|
|
542
|
-
export interface BackendJobNotFoundError {
|
|
543
|
-
code: 'job_not_found';
|
|
544
|
-
message: string;
|
|
545
|
-
sessionId: string;
|
|
546
|
-
jobId: string;
|
|
547
|
-
}
|
|
548
|
-
|
|
549
|
-
export interface BackendJobNotCancellableError {
|
|
550
|
-
code: 'job_not_cancellable';
|
|
551
|
-
message: string;
|
|
552
|
-
sessionId: string;
|
|
553
|
-
jobId: string;
|
|
554
|
-
status: 'completed' | 'failed' | 'cancelled';
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
export interface BackendJobCancelledError {
|
|
558
|
-
code: 'job_cancelled';
|
|
559
|
-
message: string;
|
|
560
|
-
sessionId: string;
|
|
561
|
-
jobId: string;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
|
-
export interface CacheRefreshFailedError {
|
|
565
|
-
code: 'cache_refresh_failed';
|
|
566
|
-
message: string;
|
|
567
|
-
sessionId: string;
|
|
568
|
-
jobId: string;
|
|
569
|
-
causeCode?: string;
|
|
570
|
-
}
|
|
571
|
-
|
|
572
507
|
export interface BackendCapabilityUnavailableError {
|
|
573
508
|
code: 'capability_unavailable';
|
|
574
509
|
message: string;
|
|
@@ -578,12 +513,6 @@ export interface BackendCapabilityUnavailableError {
|
|
|
578
513
|
bridgeBoundary?: 'external-bridge';
|
|
579
514
|
}
|
|
580
515
|
|
|
581
|
-
export type BackendJobErrors =
|
|
582
|
-
| BackendJobNotFoundError
|
|
583
|
-
| BackendJobNotCancellableError
|
|
584
|
-
| BackendJobCancelledError
|
|
585
|
-
| CacheRefreshFailedError;
|
|
586
|
-
|
|
587
516
|
export interface BackendCacheSnapshot {
|
|
588
517
|
cacheRevision: number;
|
|
589
518
|
entries: BackendCacheEntry[];
|
|
@@ -615,6 +544,7 @@ export interface RefreshCacheInput {
|
|
|
615
544
|
|
|
616
545
|
export type BackendError =
|
|
617
546
|
| SessionNotFoundError
|
|
547
|
+
| SessionCloseFailedError
|
|
618
548
|
| TransactionPreviewError
|
|
619
549
|
| EntityQueryError
|
|
620
550
|
| SessionReadError
|
|
@@ -629,10 +559,6 @@ export type BackendError =
|
|
|
629
559
|
| MaterializeWriteFailedError
|
|
630
560
|
| PathPolicyViolationError
|
|
631
561
|
| EventCursorInvalidError
|
|
632
|
-
| BackendJobNotFoundError
|
|
633
|
-
| BackendJobNotCancellableError
|
|
634
|
-
| BackendJobCancelledError
|
|
635
|
-
| CacheRefreshFailedError
|
|
636
562
|
| BackendCapabilityUnavailableError
|
|
637
563
|
| ProjectRootNotAllowedError
|
|
638
564
|
| ProjectOpenFailedError
|
package/src/runtime.ts
CHANGED
|
@@ -2,38 +2,32 @@ import type { ApplyUamTransactionAppError } from '@openfairygui/functions/uam';
|
|
|
2
2
|
import type { ProjectValidationReport } from '@openfairygui/core';
|
|
3
3
|
import type { PathPolicyViolationError } from './path-policy.js';
|
|
4
4
|
import { AuthoringService } from './services/authoring-service.js';
|
|
5
|
+
import { PersistenceService } from './services/persistence-service.js';
|
|
5
6
|
import { CacheService } from './services/cache-service.js';
|
|
6
|
-
import { type BackendContext,
|
|
7
|
+
import { type BackendContext, failure, readView } from './services/context.js';
|
|
8
|
+
import { SessionRegistry } from './services/session-registry.js';
|
|
9
|
+
import { SessionOperationQueue } from './services/session-operation-queue.js';
|
|
7
10
|
import { EventService } from './services/event-service.js';
|
|
8
|
-
import { JobService } from './services/job-service.js';
|
|
9
11
|
import { ReadService } from './services/read-service.js';
|
|
10
12
|
import { RuntimeService } from './services/runtime-service.js';
|
|
11
13
|
import { createCapabilities } from './runtime/capabilities.js';
|
|
12
14
|
import type {
|
|
13
15
|
AdvisoryLockConflictError,
|
|
14
16
|
ApplySessionTransactionInput,
|
|
15
|
-
BackendCacheEntry,
|
|
16
17
|
BackendCacheSnapshot,
|
|
17
18
|
BackendCapabilities,
|
|
18
19
|
BackendCapabilityUnavailableError,
|
|
19
|
-
BackendEvent,
|
|
20
20
|
BackendFileSystem,
|
|
21
|
-
BackendJobListSnapshot,
|
|
22
|
-
BackendJobNotCancellableError,
|
|
23
|
-
BackendJobNotFoundError,
|
|
24
|
-
BackendJobSnapshot,
|
|
25
21
|
BackendProjectOutline,
|
|
26
22
|
BackendResult,
|
|
27
23
|
BackendRuntimeOptions,
|
|
28
24
|
BackendSessionSnapshot,
|
|
29
25
|
BackendSuccess,
|
|
30
26
|
BackendTransactionPreview,
|
|
31
|
-
CancelJobInput,
|
|
32
27
|
EventCursorInvalidError,
|
|
33
28
|
GetCacheSnapshotInput,
|
|
34
29
|
GetEventsInput,
|
|
35
30
|
GetEventsSnapshot,
|
|
36
|
-
GetJobInput,
|
|
37
31
|
GetProjectOutlineInput,
|
|
38
32
|
QueryEntityInput,
|
|
39
33
|
BackendEntitySnapshot,
|
|
@@ -46,7 +40,6 @@ import type {
|
|
|
46
40
|
SessionStaleReadError,
|
|
47
41
|
ValidateSessionInput,
|
|
48
42
|
InProcessLockConflictError,
|
|
49
|
-
ListJobsInput,
|
|
50
43
|
MaterializeSessionInput,
|
|
51
44
|
MaterializeSessionSnapshot,
|
|
52
45
|
MaterializeValidationFailedError,
|
|
@@ -59,6 +52,7 @@ import type {
|
|
|
59
52
|
SaveSessionInput,
|
|
60
53
|
SessionIdConflictError,
|
|
61
54
|
SessionNotFoundError,
|
|
55
|
+
SessionCloseFailedError,
|
|
62
56
|
SessionStaleWriteError,
|
|
63
57
|
TransactionPreviewError,
|
|
64
58
|
UamFidelityUnsupportedError,
|
|
@@ -69,19 +63,15 @@ export * from './runtime/contracts.js';
|
|
|
69
63
|
export class BackendRuntime {
|
|
70
64
|
private readonly fileSystem?: BackendFileSystem;
|
|
71
65
|
private readonly capabilities: BackendCapabilities;
|
|
72
|
-
private readonly sessions = new
|
|
73
|
-
private readonly
|
|
74
|
-
private readonly eventsBySession = new Map<string, BackendEvent[]>();
|
|
75
|
-
private readonly jobsBySession = new Map<string, BackendJobSnapshot[]>();
|
|
76
|
-
private readonly cacheBySession = new Map<string, BackendCacheEntry>();
|
|
77
|
-
private eventSequence = 0;
|
|
66
|
+
private readonly sessions = new SessionRegistry();
|
|
67
|
+
private readonly sessionOperations = new SessionOperationQueue();
|
|
78
68
|
private readonly context: BackendContext;
|
|
79
69
|
private readonly readService: ReadService;
|
|
80
70
|
private readonly runtimeService: RuntimeService;
|
|
81
71
|
private readonly authoringService: AuthoringService;
|
|
72
|
+
private readonly persistenceService: PersistenceService;
|
|
82
73
|
private readonly cacheService: CacheService;
|
|
83
74
|
private readonly eventService: EventService;
|
|
84
|
-
private readonly jobService: JobService;
|
|
85
75
|
|
|
86
76
|
public constructor(options: BackendRuntimeOptions = {}) {
|
|
87
77
|
this.fileSystem = options.fileSystem;
|
|
@@ -92,21 +82,14 @@ export class BackendRuntime {
|
|
|
92
82
|
allowedProjectRoots: options.allowedProjectRoots,
|
|
93
83
|
capabilities: this.capabilities,
|
|
94
84
|
sessions: this.sessions,
|
|
95
|
-
sessionsByPath: this.sessionsByPath,
|
|
96
|
-
eventsBySession: this.eventsBySession,
|
|
97
|
-
jobsBySession: this.jobsBySession,
|
|
98
|
-
cacheBySession: this.cacheBySession,
|
|
99
|
-
nextEventSequence: () => {
|
|
100
|
-
this.eventSequence += 1;
|
|
101
|
-
return this.eventSequence;
|
|
102
|
-
},
|
|
103
85
|
};
|
|
104
|
-
|
|
105
|
-
this.
|
|
106
|
-
this.
|
|
107
|
-
this.
|
|
108
|
-
this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService
|
|
109
|
-
this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService);
|
|
86
|
+
const getSession = (sessionId: string) => this.sessions.get(sessionId);
|
|
87
|
+
this.readService = new ReadService((sessionId) => readView(getSession(sessionId)), this.capabilities);
|
|
88
|
+
this.eventService = new EventService(getSession);
|
|
89
|
+
this.cacheService = new CacheService(getSession, this.eventService);
|
|
90
|
+
this.runtimeService = new RuntimeService(this.context, this.cacheService, this.eventService);
|
|
91
|
+
this.authoringService = new AuthoringService(this.context, this.cacheService, this.eventService, this.sessionOperations);
|
|
92
|
+
this.persistenceService = new PersistenceService(this.context, this.cacheService, this.eventService, this.sessionOperations);
|
|
110
93
|
}
|
|
111
94
|
|
|
112
95
|
public getCapabilities(): BackendSuccess<BackendCapabilities> {
|
|
@@ -204,7 +187,7 @@ export class BackendRuntime {
|
|
|
204
187
|
| BackendCapabilityUnavailableError
|
|
205
188
|
>
|
|
206
189
|
> {
|
|
207
|
-
return this.
|
|
190
|
+
return this.persistenceService.saveSession(input);
|
|
208
191
|
}
|
|
209
192
|
|
|
210
193
|
public async materializeSession(
|
|
@@ -222,13 +205,14 @@ export class BackendRuntime {
|
|
|
222
205
|
| BackendCapabilityUnavailableError
|
|
223
206
|
>
|
|
224
207
|
> {
|
|
225
|
-
return this.
|
|
208
|
+
return this.persistenceService.materializeSession(input);
|
|
226
209
|
}
|
|
227
210
|
|
|
228
211
|
public async closeSession(input: {
|
|
229
212
|
sessionId: string;
|
|
230
|
-
}): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError>> {
|
|
231
|
-
|
|
213
|
+
}): Promise<BackendResult<{ sessionId: string; closed: true }, SessionNotFoundError | SessionCloseFailedError>> {
|
|
214
|
+
const captured = { ...input };
|
|
215
|
+
return this.sessionOperations.run(captured.sessionId, () => this.runtimeService.closeSession(captured));
|
|
232
216
|
}
|
|
233
217
|
|
|
234
218
|
public getEvents(
|
|
@@ -237,30 +221,11 @@ export class BackendRuntime {
|
|
|
237
221
|
return this.eventService.getEvents(input);
|
|
238
222
|
}
|
|
239
223
|
|
|
240
|
-
public getJob(
|
|
241
|
-
input: GetJobInput,
|
|
242
|
-
): BackendResult<BackendJobSnapshot, SessionNotFoundError | BackendJobNotFoundError> {
|
|
243
|
-
return this.jobService.getJob(input);
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
public listJobs(input: ListJobsInput): BackendResult<BackendJobListSnapshot, SessionNotFoundError> {
|
|
247
|
-
return this.jobService.listJobs(input);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
public cancelJob(
|
|
251
|
-
input: CancelJobInput,
|
|
252
|
-
): BackendResult<
|
|
253
|
-
BackendJobSnapshot,
|
|
254
|
-
SessionNotFoundError | BackendJobNotFoundError | BackendJobNotCancellableError
|
|
255
|
-
> {
|
|
256
|
-
return this.jobService.cancelJob(input);
|
|
257
|
-
}
|
|
258
|
-
|
|
259
224
|
public getCacheSnapshot(input: GetCacheSnapshotInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
|
|
260
225
|
return this.cacheService.getCacheSnapshot(input);
|
|
261
226
|
}
|
|
262
227
|
|
|
263
|
-
public refreshCache(input: RefreshCacheInput): BackendResult<
|
|
264
|
-
return this.
|
|
228
|
+
public refreshCache(input: RefreshCacheInput): BackendResult<BackendCacheSnapshot, SessionNotFoundError> {
|
|
229
|
+
return this.cacheService.refreshCache(input);
|
|
265
230
|
}
|
|
266
231
|
}
|