Skip to content

AI-native design editor. Open-source Figma alternative.

fix(fig): reject cyclic record ancestry instead of overflowing the stack (#1009)

Danila Poyarkova7bd19f6b7dc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd13bbe9f..18faf17fe 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -245,7 +245,7 @@
### Performance
-- Open large `.fig` files with a fraction of the memory: records stay in the file's bytes except for the few fields indexing needs, and are decoded whole only for the pages being read and the components they use. Opening the Nuxt UI design kit takes 0.7 GB instead of 2.2 GB, and its first twelve pages 1.2 GB instead of 2.6 GB.
+- Open large `.fig` files with a fraction of the memory: records stay in the file's bytes except for the few fields indexing needs, and are decoded whole when read, kept only for the pages being read and the components they use. Opening the Nuxt UI design kit takes 0.7 GB instead of 2.2 GB, and its first twelve pages 1.2 GB instead of 2.6 GB.
- Save an edited `.fig` file by rewriting only the layers that changed and copying the rest from the file it was opened from, as it is stored, without decoding it; in the browser that work runs off the main thread. Saving the 109 MB Preline UI kit after an edit takes about 3 seconds instead of over two minutes, and crash recovery no longer freezes Safari after the first edit to a large file. Editing a component also rewrites its instances on pages that were not opened yet.
- Open `.fig` design kits with less memory: layers inside instances hold their component layers' paints, glyphs, and other unchanged values instead of a copy each, about a third fewer objects and an eighth less memory per loaded page.
- Save large `.fig` documents with less memory: once every page is loaded, the first save releases the decoded original file, and saves write from the document instead of a copy of it, about 1.5 GB less on a 74 MB design kit.
diff --git a/packages/fig/src/document/read.ts b/packages/fig/src/document/read.ts
index b5ef758f8..63072958e 100644
--- a/packages/fig/src/document/read.ts
+++ b/packages/fig/src/document/read.ts
@@ -123,10 +123,14 @@ function wholeRecords(source: readonly NodeChange[]): ReaderRecords {
}
}
-/** A header's whole record, read again from the archive bytes, its plugin data deduplicated. */
+/**
+ * A header's whole record, read again from the archive bytes, its plugin data deduplicated. A
+ * header that lost those bytes, as a copy does, holds only its header fields, so it fails here
+ * rather than read as a record without its contents.
+ */
function decodeRecord(header: NodeChange): NodeChange {
const record = decodeWhole(header) as NodeChange | undefined
- if (!record) return header
+ if (!record) throw new Error('Record header has no archive bytes to read it whole')
deduplicateNodeChangePluginData([record])
return record
}
@@ -151,27 +155,31 @@ function archiveRecords(headers: readonly NodeChange[]): ReaderRecords {
const styles = new DecodedMap(index.sources, (header) =>
header.styleType ? shared(header) : header
)
+ /** Records whose preparation is running: preparing an ancestor reaches them only in a cycle. */
+ const preparing = new Set<NodeChange>()
const prepare = (header: NodeChange, whole: WholeRecord): NodeChange => {
- const record = decodeRecord(header)
- normalize(record)
- const ancestors: NodeChange[] = []
- const visited = new Set<NodeChange>([header])
- for (
- let parent = index.sources.get(parentIdOf(header) ?? '');
- parent;
- parent = index.sources.get(parentIdOf(parent) ?? '')
- ) {
- if (visited.has(parent)) throw new Error('Cyclic component-property ancestry')
- visited.add(parent)
- ancestors.push(whole(parent))
- }
- inheritFromAncestors(record, ancestors)
- const resolveStyles = (node: NodeChange): void => {
- applyStyleRefsToFields(styles, node, assets)
- for (const override of symbolOverridesOf(node)) resolveStyles(override as NodeChange)
+ if (preparing.has(header)) throw new Error('Cyclic component-property ancestry')
+ preparing.add(header)
+ try {
+ const record = decodeRecord(header)
+ normalize(record)
+ const ancestors: NodeChange[] = []
+ for (
+ let parent = index.sources.get(parentIdOf(header) ?? '');
+ parent;
+ parent = index.sources.get(parentIdOf(parent) ?? '')
+ )
+ ancestors.push(whole(parent))
+ inheritFromAncestors(record, ancestors)
+ const resolveStyles = (node: NodeChange): void => {
+ applyStyleRefsToFields(styles, node, assets)
+ for (const override of symbolOverridesOf(node)) resolveStyles(override as NodeChange)
+ }
+ resolveStyles(record)
+ return record
+ } finally {
+ preparing.delete(header)
}
- resolveStyles(record)
- return record
}
const shared: WholeRecord = (header) => {
let record = kept.get(header)
diff --git a/packages/fig/tests/document/record-headers.test.ts b/packages/fig/tests/document/record-headers.test.ts
index 1f9cbafd8..19a7511bf 100644
--- a/packages/fig/tests/document/record-headers.test.ts
+++ b/packages/fig/tests/document/record-headers.test.ts
@@ -1,10 +1,22 @@
import { expect, test } from 'bun:test'
import { readFixtureArrayBuffer } from '#fig-tests/helpers/fig-fixtures'
-import { parseFigBuffer } from '#fig/archive'
+import { parseFigBuffer, writeFigArchive } from '#fig/archive'
import { materializeDocument, materializeFigArchive } from '#fig/document/materialize'
-import { RECORD_HEADER_FIELDS } from '#fig/document/read'
+import {
+ createArchiveDocumentReader,
+ createDocumentReader,
+ RECORD_HEADER_FIELDS
+} from '#fig/document/read'
+import { deflateSync } from 'fflate'
+import {
+ createNodeChangesMessage,
+ encodeMessage,
+ getSchemaBytes,
+ initCodec,
+ type NodeChange
+} from '@open-pencil/kiwi/fig/codec'
import { deduplicateNodeChangePluginData } from '@open-pencil/kiwi/fig/parse'
import { decodeWhole } from '@open-pencil/kiwi/schema-runtime'
import { setIdSession, type SceneGraph } from '@open-pencil/scene-graph'
@@ -66,3 +78,28 @@ test('an archive reader with record headers builds the document records decoded
setIdSession(0)
}
})
+
+// A file whose layers each name the other as parent cannot be read; reading those records must
+// fail as a document read whole fails, not by recursing until the stack runs out. The archive
+// reader decodes a record when it is read, so no page reaching them lets the file open.
+test('an archive reader rejects a cyclic parent chain as a document read whole does', async () => {
+ await initCodec()
+ const guid = (localID: number) => ({ sessionID: 0, localID })
+ const under = (parent: number) => ({ guid: guid(parent), position: '!' })
+ const records: NodeChange[] = [
+ { guid: guid(0), type: 'DOCUMENT', phase: 'CREATED', name: 'Document' },
+ { guid: guid(1), type: 'CANVAS', phase: 'CREATED', name: 'Page', parentIndex: under(0) },
+ { guid: guid(2), type: 'FRAME', phase: 'CREATED', name: 'A', parentIndex: under(3) },
+ { guid: guid(3), type: 'FRAME', phase: 'CREATED', name: 'B', parentIndex: under(2) }
+ ]
+ const bytes = writeFigArchive({
+ schemaDeflated: deflateSync(getSchemaBytes()),
+ kiwiData: encodeMessage(createNodeChangesMessage(0, 0, records)),
+ thumbnailPNG: new Uint8Array([1]),
+ metaJSON: '{}'
+ })
+
+ expect(() => createDocumentReader(records)).toThrow('Cyclic component-property ancestry')
+ const { reader } = createArchiveDocumentReader(bytes.slice().buffer)
+ expect(() => reader.sourceRecords).toThrow('Cyclic component-property ancestry')
+})