# 辅助函数

> 浏览器和服务器都能用的文档引擎辅助函数：下载导出文件、键盘快捷键、文档校验和迁移。

Source: https://fabricjs-document-engine.jscrate.dev/zh/docs/api/helpers
Last updated: 2026-09-28

主入口在 `createDocumentEngine` 之外还导出了几个文档引擎辅助函数。浏览器相关的函数把引擎接入页面，文档相关的函数在 Node 里无需画布也能运行。

## 浏览器辅助函数

```ts
function bindKeyboardShortcuts(engine: UndoRedoTarget, options?: KeyboardShortcutOptions): () => void
```

Ctrl/Cmd+Z undoes. Ctrl/Cmd+Shift+Z and Ctrl+Y redo. Ignored while the user types in an input or in Fabric text. Returns an unbind function.

```ts
function bindUnsavedChangesWarning(engine: UnsavedChangesSource, target?: EventTarget): () => void
```

Asks the browser to confirm before a page with unsaved changes closes. Returns an unbind function.

```ts
function downloadExport(result: DownloadableExport, fileName?: string): void
```

Starts a browser download of an export result.

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `target` | `EventTarget` | `window` | Where to listen for key presses. |

## 适用于任何框架的状态

```ts
function createDocumentStateStore(engine: DocumentEngine): DocumentStateStore
```

Framework-free `{ getSnapshot, subscribe, destroy }` with `DocumentState`. Fits Vue, Svelte and `useSyncExternalStore`.

## 文档辅助函数

这些文档引擎辅助函数在任何地方都能运行，包括服务器：

```ts
function validateDocument(value: unknown): DocumentIssue[]
```

Checks a value against the document format. Returns a list of issues with the path of each problem.

```ts
function migrateDocument(value: unknown, context: MigrationContext, steps?: Readonly<Record<number, Migration>>, targetVersion?: number): MigrationResult
```

Upgrades an older document or plain Fabric JSON to the current format. Useful for server-side batch upgrades.

```ts
function detectSchemaVersion(value: unknown): number | undefined
```

Returns `1` for a document, `0` for plain Fabric JSON, otherwise `undefined`.

```ts
function secureDocument(input: unknown, limits?: ContentLimits): unknown
```

Removes prototype keys and enforces the object and depth limits. Throws `UNSAFE_DOCUMENT`.

```ts
function isSafeImageUrl(url: string): boolean
```

The default image address rule: `http`, `https`, `blob`, relative addresses and `data:image/` are allowed.

## 错误

```ts
function isDocumentEngineError(value: unknown): value is DocumentEngineError
```

Type guard for `DocumentEngineError`, which carries a stable `code`.

## 示例：在服务器上检查上传

```ts
import {
  migrateDocument,
  secureDocument,
  validateDocument,
} from "fabricjs-document-engine";

const safe = secureDocument(body, { maxObjects: 20000 });
const { document } = migrateDocument(safe, {
  canvasWidth: 1200,
  canvasHeight: 800,
});
const issues = validateDocument(document);
```

关于这些文档引擎辅助函数的更多内容，见[安全](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/security)和[迁移](https://fabricjs-document-engine.jscrate.dev/zh/docs/guides/migration)。
