Embedded document font files

Status: F08 implementation in progress. Resource ownership, commands, native persistence and independent REST admission/relinking have unit/API coverage. Native browser verification covers embedding/reopening, isolated metrics, shared views, workspace worker bytes, SVG, source-close transfer, rejected/concurrent admission, source collection, atomic relinking, all nine export formats and retained wet replay. Relinking preserves exact Undo/Redo and reopened pixels; active operations retain sources through live history collection and release them on success, failure or cancellation. Versioned recipe/package/batch font transport is described in FONT_RECIPES.md. Supported SVG font/text reimport follows SVG_FONT_IMPORT.md; broader font/CSS/viewer/device/mixed-source acceptance remains required. This is not completion of F08 or the roadmap.

Ownership and commands

Document.fonts.files is a FontFileCollection. Its items, length, iterator and getById(id):FontFile|null resolve declarations across the document and every stored embedded scope. FontFile is constructed from strict {id,name,resource} data, not a mutable alternate document API. IDs are the SHA-256 source/face identity; family is the stable native family request. resource and toJSON() return owned metadata. Attached name assignment, files.add(file), files.remove(file,options={}) and file.remove(options={}) use shared commands and history. A removed handle becomes detached; Undo restores its identity. Reading or renaming a removed handle rejects.

font.file.add, font.file.rename and font.file.remove are strict shared commands. Metadata carries no source Blobs or native handles. On an attached host, declarations must match separately owned resources before activation. Add is idempotent for an identical identity/descriptor; use rename to change a label. Names contain 1–240 UTF-16 units and cannot be all whitespace. Removing an in-use face requires {replaceWith:string}; replacement cannot contain the removed family. Exact tokens in quoted/escaped fallback lists are replaced while retaining the other fallbacks. Shared reflow, inheritance, effective locks and dependent-instance checks apply atomically, including adding a face whose requested alias already occurs in locked artwork.

Document schema 43 admits fontFiles; older labels reject even an empty new table. Legacy documents without the field and ordinary installed/missing-family requests remain valid. Root and stored-scope declarations may share an identical resource, but conflicting declarations for one identity reject.

Trusted asynchronous embedding

Document.fonts.embed(source:Blob,options:FontEmbedOptions={},control:FontEmbedControl={}):Promise<FontFile> requires an attached source store and must run outside synchronous transactions. Options are strict {faceIndex?:number,name?:string,replace?:string}. Single-face input defaults to face 0; collections require explicit selection. Name defaults to the trimmed declared full name, family or “Embedded font”, truncated to 240 units; existing labels remain unchanged on duplicate embedding. replace optionally replaces an exact existing family request in the same Undo entry as attachment. Without it, embedding does not change existing family requests.

FontEmbedControl extends the source-inspection control with optional synchronous beforeCommit():void, used by captured UI owners. It also accepts AbortSignal, active parser timeout (60000 ms default) and phase progress. A throwing beforeCommit rejects; cancellation, store and revision are rechecked after it, without another await before publication. The disposable parser and native validation prepare privately. Before commit, cancellation, store lifetime/identity and the target document revision are rechecked. Malformed sources/options, missing stores, cancellation, stale owners/revisions, parser/native failures and effective locks reject. An observer may throw after an accepted command; the source and accepted history remain intact. Temporary source leases are acquired before asynchronous publication. Rejection, cancellation and unadopted late results release their leases; identical concurrent imports keep independent leases. Accepted observer failures retain sources through the model/history closure.

The store keeps immutable complete originals and exact selected native bytes separately from image geometry/bitmaps. Multiple selected collection faces share their original Blob. Native registrations have independent document-store leases; closing one owner does not unregister another's font. Final release removes the owned registration. Registry identity and descriptor checks detect external native tampering. Owned additions/removals invalidate renderer caches even though adding an already loaded FontFace emits no native loading event.

Relinking and source lifetime

Document.fonts.relink(file:FontFile,source:Blob,options:FontRelinkOptions={},control:FontEmbedControl={}):Promise<FontFile> and attached FontFile.relink(source,options={},control={}):Promise<FontFile> prepare a selected replacement outside transactions, then replace the old declaration and every family token in one ordinary Undo entry. Options are strict {faceIndex?:number,name?:string}; replace is not a relink option. Selection, timeout, cancellation and final-owner defaults match embedding. The old label is preserved for a new resource; an already attached target keeps its existing label unless name explicitly overrides it. Identical source/face relinking is a no-op unless a name changes. The returned handle identifies the replacement; an old different-ID handle is detached until Undo. Original source text, fallback order, style links, other typography and selection are preserved; affected bounds reflow. Effective text/ancestor/dependent-instance locks, stale revisions and missing ownership reject atomically and release an unused replacement.

Model-owned resources remain while referenced by any current state, Undo/Redo transition, saved branch, comparison or stored master in any bound Document view. Bindings use weak references so an unused component view does not keep its Document alive; an explicit source-store detach releases its binding. A view that is still alive can retain its own uncommitted component sources independently of parent history. Collection runs on model/history changes and lease release; deleting the last reference after history trimming releases the store's bytes and native registration. Native browser caches or caller-held immutable Blobs can outlive this release; no immediate process-memory reclamation is promised.

Active exports and retained wet-paint sessions hold explicit font leases. Snapshot output can finish after unrelated live edits trim the last model/history reference; operation completion, failure, cancellation or disposal releases its leases. Private copies stage destination leases before asynchronous image work, then transfer ownership on accepted publication or release on rollback. Explicit trusted source removal/disposal still invalidates captured checks. Checks distinguish entry identity even if identical immutable resources are removed and reinstalled. History navigation rejects missing referenced sources before publication.

The internal trusted FontSourceStore.prepare remains caller-owned before model adoption; stage returns {resource,check(),release()} for bounded preparation, retain(id) pins an existing record, and stageTo(destination,id) protects a temporary transfer. These methods do not expose a font import capability to isolated scripts/plugins. Model adoption makes a record eligible for collection once all model/history/view references and operation leases end. Unadopted explicit preparations remain until their trusted caller removes them or disposes the store.

Saving and reopening

Native project 5 uses the existing checksummed header with a version-5 marker. Strict font records reference deduplicated payloads by original/render SHA-256 and byte length. Standalone original/native bytes share one payload. Collection originals are retained whole, while each selected face has its own native payload. Source closure follows the history supplied to the serializer: when retained history is included, fonts referenced only by Undo, future states, branches or comparisons remain in that closure alongside current artwork and stored masters.

Ordinary unbranched project downloads retain current-result attribution without adding the Undo timeline. Workspace snapshots and projects with saved branches or comparisons include their retained history and its font sources. Relink Undo/Redo works in the live document; reopening an ordinary unbranched download restores its saved result.

Reading validates container version, ordered nonoverlapping extents, complete byte coverage, hashes, face IDs, native signatures, descriptor/source agreement and referenced/unused records. loadProject reparses each original and compares the canonical selected-face descriptor before exposing its store; activation occurs when a Document attaches that store. Font-free native saves remain version 3 or 4; native versions 1–4 remain readable without font records. Workspace encoding captures descriptors/Blobs before its asynchronous graph transfer and sends no native handles. Workspace envelope and history formats are unchanged.

Cross-document artwork/library copies include required declarations and independently leased sources. Component extraction binds inherited source families. History previews acquire their own native leases. Portable recipe schema 2/package 3 retain exact font dependencies and whole originals; batch snapshots and editable prepared scenes use the same source ownership. See FONT_RECIPES.md for their separate contract.

Independent REST font admission

POST /api/v1/documents/:id/fonts?expectedRevision=N accepts binary source bytes with optional strict JSON X-Font-Options: {faceIndex?,name?,replace?}. It returns HTTP 201 with the normal id/revision/document snapshot, file declaration and metrics:"estimated". Defaults and command semantics match trusted embedding. Invalid input/selection/options or locks return 400; stale revisions return 409 and deleted sessions return 404. Configured API authentication, loopback/origin restrictions and request-disconnect cancellation apply. No arbitrary source-file size cutoff is introduced.

The independent server has a FIFO font-parser queue and disposable Node workers, with a 60000ms active parser deadline excluding queue wait. Cancellation/deletion/server closure terminates active work and prevents publication; the source store separately verifies bytes/identity. It creates no fake native FontFaces and does not claim browser-native layout or synchronize with open browser documents.

GET /api/v1/documents/:id/fonts retains its existing fonts request inventory and adds files:FontFileData[]. GET /api/v1/documents/:id/fonts/:fontId returns id/revision/file for a currently declared file; missing/removed files return 404. Add ?source=original or ?source=render to download exact complete original or selected native bytes. Source download uses the same API authentication, Cache-Control:no-store, attachment disposition and nosniff. Originals use application/octet-stream, independent of the uploaded type; render bytes use the validated font MIME. Native project delivery retains these sources in version 5. POST .../fonts/:fontId?expectedRevision=N accepts a binary replacement and strict relink options (faceIndex, name), returning HTTP 200 with the replacement file and estimated metrics. Rename/remove/reuse of existing resources uses the normal strict command endpoint and expectedRevision, including ordinary Undo/Redo. A second headless session cannot attach an unowned declaration from the first.

Editor and output

Document fonts keeps inspection/private preview read-only until Embed selected face is chosen. Embedded files have friendly labels, explicit rename/removal controls and normal Undo. Typography and replacement presets use friendly names while storing the stable family request. Installed system fonts are not embedded automatically. The complete original file will be included in projects; source embedding flags/copyright remain declarations, and the user must have sharing rights.

Isolated Scripts and internal plugins receive only currently declared selected render faces through a private initial message. The disposable worker loads its native font set before document/layer constructors run, then removes the raw payload before user execution. It receives no font file chooser, host store, image bytes, credentials or network capability. Missing native worker support rejects instead of returning fallback metrics. Source identities are checked before transport and before accepting results; the existing five-second script budget and host permission/revision checks remain. Trusted embed rejects there because no source store is attached.

Raster exports render with owned native faces. Referenced source/native identities are pinned before progress callbacks and rechecked through rendering/encoding; loss rejects even when another document retains the same native face. Explicit host SVG delivery includes complete selected native font bytes referenced by visible editable text in inline @font-face resources, with strict generated family/descriptor values. It excludes hidden/unused faces, unselected collection faces and system font files. Text rendered into SVG image portions retains source lifetime checks without adding editable font binaries. Viewer support, shaping and Canvas/SVG differences remain explicit; save a project for originals and use native raster output for the editor's rendered pixels. Supported SVG embedded-font and horizontal-text reimport is documented in SVG_FONT_IMPORT.md; broader CSS/viewer acceptance remains unfinished.

Character runs, arbitrary axis authoring, path text, broader shaping/font/device quality, broader automation and mixed-source acceptance, and sustained editor-wide performance remain required.

Private glyph paint sources

Native text preparation may retain an independent private glyph-selector face for a captured uncompressed selected SFNT source. Temporary fonts preserve original glyph/hint/metric/axis/paint tables and authored mappings; extra private selectors do not replace the original file or its document identity. Worker jobs share the font parser queue, complete derived-byte validation and cancellation; parent/source retirement removes private registrations. No alias, derived font, source chooser or new operation is exposed to isolated scripts/plugins. Existing source formats/imports, originals and native persistence remain unchanged. This is private resolved-glyph paint groundwork with explicit remaining source/ shaping/color limitations, described in FLOAT_TEXT.md.