Packages > @fluid-experimental/tree2

@fluid-experimental/tree2 Package

Interfaces

Interface Alerts Description
Adapters ALPHA

Minimal selection of adapters (nothing for general out of schema, field level adjustments etc.). Would be used with schematize and have actual conversion/update functionality.

TODO: Support more kinds of adapters TODO: support efficient lookup of adapters

AnchorEvents ALPHA

Events for AnchorNode. These events are triggered while the internal data structures are being updated. Thus these events must not trigger reading of the anchorSet or forest.

TODO: - Include sub-deltas in events. - Add more events.

AnchorLocator ALPHA Maps anchors (which must be ones this locator knows about) to paths.
AnchorNode ALPHA Node in a tree of anchors.
AnchorSetRootEvents ALPHA

Events for AnchorSet. These events are triggered while the internal data structures are being updated. Thus these events must not trigger reading of the anchorSet or forest.

TODO: - Design how events should be ordered. - Include sub-deltas in events. - Add more events.

AnnouncedVisitor ALPHA Visitor that is notified of changes before, after, and when changes are made. Must be freed after use.
ArrayLikeMut ALPHA ArrayLike numeric indexed access, but writable.
BrandedMapSubset ALPHA

A Map where the keys carry the types of values which they correspond to.

Example usage:

type FooSlot<TContent> = BrandedKey<Opaque<Brand<number, "FooSlot">>, TContent>;
const counterSlot = brandedSlot<FooSlot<number>>();
const slots: BrandedMapSubset<FooSlot<any>> = new Map();
slots.set(counterSlot, slots.get(counterSlot) ?? 0 + 1);

CheckoutEvents BETA Events for ITreeCheckout.
ChildLocation ALPHA Location of a tree relative to is parent container (which can be a tree or forest).
ContextuallyTypedNodeDataObject ALPHA Object case of ContextuallyTypedNodeData.
Contravariant ALPHA Constrain generic type parameters to Contravariant.
Covariant ALPHA Constrain generic type parameters to Covariant.
CursorAdapter ALPHA Provides functionality to allow a stackTreeNodeCursor(adapter, root) and stackTreeFieldCursor(adapter, root, detachedField) to implement cursors.
CursorWithNode ALPHA ITreeCursorSynchronous that can return the underlying node objects.
DeltaDetachedNodeBuild ALPHA

Represents the creation of detached nodes.

Tree creation is idempotent: if a tree with the same ID already exists, then this build is ignored in favor of the existing tree.

DeltaDetachedNodeChanges ALPHA Represents changes made to a detached node
DeltaDetachedNodeDestruction ALPHA Represents the destruction of detached nodes
DeltaDetachedNodeId ALPHA A globally unique ID for a node in a detached field.
DeltaDetachedNodeRename ALPHA Represents a detached node being assigned a new DetachedNodeId.
DeltaFieldChanges ALPHA Represents the changes to perform on a given field.
DeltaMark ALPHA Represents a change being made to a part of the document tree.
DeltaRoot ALPHA Represents the change made to a document. Immutable, therefore safe to retain for async processing.
DeltaVisitor ALPHA Visitor for changes in a delta. Must be freed after use.
DetachedField ALPHA

A root in the forest.

The range is a "container" like a field: any additional content inserted before or after contents of this range will be included in the range. This also means that moving the content from this range elsewhere will leave this range valid, but empty.

In some APIs DetachedFields are used as FieldKeys on a special implicit root node to simplify the APIs and implementation.

EditableTreeEvents ALPHA

A collection of events that can be raised by a FlexTreeNode. These events are triggered while the internal data structures are being updated. Thus these events must not trigger reading of the anchorSet or forest.

TODO: - Design how events should be ordered. - Include sub-deltas in events. - Add more events. - Have some events (or a way to defer events) until the tree can be read.

FieldAnchor ALPHA Anchor to a field. This is structurally based on the parent, so it will move only as the parent moves.
FieldKindSpecifier ALPHA Specifies which field kind to use.
FieldLocation ALPHA Location of a field within a tree that is not a detached/root field.
FieldMapObject ALPHA

Json compatible map as object. Keys are FieldKey strings. Values are the content of the field specified by the key.

WARNING: Be very careful when using objects as maps: Use Object.prototype.hasOwnProperty.call(fieldMap, key) to safely check for keys. Do NOT simply read the field and check for undefined as this will return values for __proto__ and various methods on Object.prototype, like hasOwnProperty and toString. This exposes numerous bug possibilities, including prototype pollution.

Due to the above issue, try to avoid this type (and the whole object as map pattern). Only use this type when needed for json compatible maps, but even in those cases consider lists of key value pairs for serialization and using Map for runtime.

Fields ALPHA
FieldUpPath ALPHA

Path from a field in the tree upward.

See UpPath.

FlexTreeEntity ALPHA Part of a tree. Iterates over children.
FlexTreeField ALPHA

A collaboratively editable collection of nodes within a FlexTreeEntity.

Fields are inherently part of their parent, and thus cannot be moved. Instead their content can be moved, deleted or created.

Editing operations are only valid on trees with the TreeStatus#InDocument TreeStatus.

FlexTreeFieldNode ALPHA A FlexTreeNode that wraps a single FlexTreeField (which is placed under the EmptyKey).
FlexTreeLeafNode ALPHA Leaf holding a value.
FlexTreeMapNode ALPHA A FlexTreeNode that behaves like a Map<string, Field> for a specific Field type.
FlexTreeNode ALPHA

Generic tree node API.

Nodes are (shallowly) immutable and have a logical identity, a type and either a value or fields under string keys.

This "logical identity" is exposed as the object identity: if a node is moved within a document, the same FlexTreeNode instance will be used in the new location. Similarly, edits applied to a node's sub-tree concurrently with the move of the node will still be applied to its subtree in its new location.

FlexTreeNodeKeyField ALPHA Field that contains an immutable StableNodeKey identifying this node.
FlexTreeObjectNode ALPHA

A FlexTreeNode that behaves like an "object" or "struct", providing properties to access its fields.

ObjectNodes consist of a finite collection of fields, each with their own (distinct) key and TreeFieldSchema.

FlexTreeOptionalField ALPHA Field that stores zero or one child.
FlexTreeRequiredField ALPHA Field that stores exactly one child.
FlexTreeSequenceField ALPHA

FlexTreeField that stores a sequence of children.

Sequence fields can contain an ordered sequence any number of FlexTreeNodes which must be of the AllowedTypes from the TreeFieldSchema).

FlexTreeView ALPHA An editable view of a (version control style) branch of a shared tree.
Forbidden ALPHA
ForestEvents ALPHA

Events for IForestSubscription.

TODO: consider having before and after events per subtree instead while applying anchor (and this just shows what happens at the root).

FullSchemaPolicy ALPHA Policy from the app for interpreting the stored schema. The app must ensure consistency for all users of the document.
GenericFieldsNode ALPHA Json comparable field collection, generic over child type. Json compatibility assumes TChild is also json compatible.
GenericTreeNode ALPHA Json comparable tree node, generic over child type. Json compatibility assumes TChild is also json compatible.
HasListeners ALPHA
ICodecOptions ALPHA Options relating to handling of persisted data.
IdAllocator ALPHA Used for allocating IDs unique to a particular instance of the allocator.
IDefaultEditBuilder ALPHA Default editor for transactions.
IDisposable BETA An object with an explicit lifetime that can be ended.
IEditableForest ALPHA Editing APIs.
IEmitter ALPHA Interface for an event emitter that can emit typed events to subscribed listeners.
IForestSubscription ALPHA

Invalidates whenever the tree content changes. For now (might change later) downloading new parts of the forest counts as a change. Not invalidated when schema changes.

When invalidating, all outstanding cursors must be freed or cleared.

InitializeAndSchematizeConfiguration ALPHA Options used to initialize (if needed) and schematize a SharedTree.
Invariant ALPHA Constrain generic type parameters to Invariant.
ISharedTree ALPHA

Collaboratively editable tree distributed data-structure, powered by ISharedObject.

See [the README](../../README.md) for details.

ISubscribable BETA

An object which allows the registration of listeners so that subscribers can be notified when an event happens.

createEmitter(noListeners) can help implement this interface via delegation. EventEmitter can be used as a base class to implement this via extension.

ITransaction ALPHA

A collection of functions for managing transactions. Transactions allow edits to be batched into atomic units. Edits made during a transaction will update the local state of the tree immediately, but will be squashed into a single edit when the transaction is committed. If the transaction is aborted, the local state will be reset to what it was before the transaction began. Transactions may nest, meaning that a transaction may be started while a transaction is already ongoing.

To avoid updating observers of the view state with intermediate results during a transaction, use ITreeCheckout#fork and ISharedTreeFork#merge.

ITree BETA Channel for a Fluid Tree DDS.
ITreeCheckout ALPHA Provides a means for interacting with a SharedTree. This includes reading data from the tree and running transactions to mutate the tree.
ITreeCheckoutFork ALPHA

Branch (like in a version control system) of SharedTree.

ITreeCheckout that has forked off of the main trunk/branch.

ITreeCursor ALPHA A stateful low-level interface for reading tree data.
ITreeCursorSynchronous ALPHA ITreeCursor that is never pending.
ITreeSubscriptionCursor ALPHA ITreeCursor supporting IForestSubscription and its changes over time.
ITreeViewFork ALPHA

Branch (like in a version control system) of SharedTree.

FlexTreeView that has forked off of the main trunk/branch.

JsonableTree ALPHA

A tree represented using plain JavaScript objects. Can be passed to JSON.stringify() to produce a human-readable/editable JSON tree.

JsonableTrees should not store empty fields.

JsonValidator ALPHA JSON schema validator compliant with draft 6 schema. See https://json-schema.org.
LocalNodeKey ALPHA A key which uniquely identifies a node in the tree within this session.
MapTree ALPHA Simple in memory tree representation based on Maps. MapTrees should not store empty fields.
MarkedArrayLike ALPHA Can be used to mark a type which works like an array, but is not compatible with Array.isArray.
Named ALPHA Type with a name describing what it is. Typically used with values (like schema) that can be stored in a map, but in some representations have their name/key as a field.
NodeData ALPHA The fields required by a node in a tree.
NodeExistsConstraint ALPHA
NodeKeyFieldKind ALPHA
NodeKeys ALPHA A collection of utilities for managing StableNodeKeys. A node key can be assigned to a node and allows that node to be easily retrieved from the tree at a later time. (see nodeKey.map).
Optional ALPHA
OptionalFieldEditBuilder ALPHA
PathRootPrefix ALPHA Prefix to apply as the root of a UpPath or FieldUpPath.
PathVisitor ALPHA

Delta visitor for the path tree.

For any of these events, the paths are guaranteed to be valid at the time of the event, and it is valid to read from the Forest at that path.

PlaceUpPath ALPHA A place in a field.
Range_2 ALPHA Delimits the extend of a range.
RangeQueryResult ALPHA The result of a query about a range of keys.
RangeUpPath ALPHA A possibly empty range of nodes in a field. This object only characterizes the location of the range, it does not own/contain the nodes in the range.
Required_2 ALPHA
Revertible BETA

Allows reversion of a change made to SharedTree.

Applications wanting to implement undo/redo support might typically maintain two stacks of Revertibles, with optional eviction policy to free up memory.

RootField ALPHA Wrapper around DetachedField that can be detected at runtime.
SchemaBuilderOptions ALPHA Configuration for a SchemaBuilder.
SchemaCollection ALPHA Schema data that can be be used to view a document.
SchemaConfiguration ALPHA View Schema for a SharedTree.
SchemaEvents ALPHA

Events for StoredSchemaRepository.

TODO: consider having before and after events per subtree instead while applying anchor (and this just shows what happens at the root).

SchemaLibrary ALPHA Schema information collected by a SchemaBuilder, including referenced libraries. Can be aggregated into other libraries by adding to their builders.
SchemaLibraryData ALPHA Schema data collected by a single SchemaBuilder (does not include referenced libraries).
SchemaLintConfiguration ALPHA Allows opting into and out of errors for some unusual schema patterns which are usually bugs.
SchematizeConfiguration ALPHA Options used to schematize a SharedTree.
SchemaValidationFunction ALPHA Validates data complies with some particular schema. Implementations are typically created by a JsonValidator.
Sequence ALPHA
SequenceFieldEditBuilder ALPHA
SharedTreeContentSnapshot ALPHA Copy of data from an ISharedTree at some point in time.
SharedTreeOptions ALPHA
StoredSchemaCollection ALPHA Collection of TreeNodeSchema data that can be stored in a document.
StoredSchemaRepository ALPHA

Mutable collection of stored schema.

TODO: could implement more fine grained dependency tracking.

TreeAdapter ALPHA
TreeApi BETA Provides various functions for analyzing NodeBases.
TreeContent ALPHA Content that can populate a SharedTree.
TreeContext ALPHA A common context of a "forest" of EditableTrees. It handles group operations like transforming cursors into anchors for edits.
TreeDataContext ALPHA

Information needed to interpret a subtree described by ContextuallyTypedNodeData and ContextuallyTypedFieldData.

TODO: Currently being exposed at the package level which also requires us to export MapTree at the package level. Refactor the FieldGenerator to use JsonableTree instead of MapTree, and convert them internally.

TreeEvent ALPHA An event raised on a FlexTreeNode.
TreeFieldStoredSchema ALPHA
TreeListNode BETA A NodeBase which implements 'readonly T[]' and the list mutation APIs.
TreeLocation ALPHA
TreeMapNode BETA A map of string keys to tree objects.
TreeMapNodeBase BETA A map of string keys to tree objects.
TreeNodeEvents BETA A collection of events that can be raised by a NodeBase.
TreeNodeStoredSchema ALPHA
TreeOptions ALPHA Configuration to specialize a Tree DDS for a particular use.
TreeSchema ALPHA Schema data that can be be used to view a document. Strongly typed over its rootFieldSchema.
TreeStoredSchema ALPHA Document schema data that can be stored in a document.
TreeView BETA An editable view of a (version control style) branch of a shared tree.
UpPath ALPHA

Path from a location in the tree upward. UpPaths can be used with deduplicated upper parts to allow working with paths localized to part of the tree without incurring costs related to the depth of the local subtree.

UpPaths can be thought of as terminating at a special root node (that is undefined) whose FieldKeys correspond to detached sequences.

UpPaths can be mutated over time and should be considered to be invalidated when any edits occurs: Use of an UpPath that was acquired before the most recent edit is undefined behavior.

ValueFieldEditBuilder ALPHA

Classes

Class Alerts Modifiers Description
AnchorSet ALPHA sealed

Collection of Anchors at a specific revision.

See Rebaser for how to update across revisions.

TODO: this should not be package exported. If it's needed outside the package an Interface should be used instead which can reduce its API surface to a small subset.

BrandedType ALPHA sealed

Helper for Brand. This is split out into its own as that's the only way to: - have doc comments for the member. - make the member protected (so you don't accidentally try and read it). - get nominal typing (so types produced without using this class can never be assignable to it). - allow use as Opaque branded type (not assignable to ValueType, but captures ValueType).

See InternalTypes#MakeNominal for some more details.

Do not use this class with instanceof: this will always be false at runtime, but the compiler may think it's true in some cases.

FieldKind ALPHA sealed

Functionality for FieldKinds that is stable, meaning that it can not change in any measurable way without providing a new identifier.

It is assumed that this information and policy is available on all clients interacting with a document using the identifier.

This must contain enough information to process remote edits to this FieldKind consistently with all clients. All behavior must be deterministic, and not change across versions of the app/library.

These policies include the data encoding, change encoding, change rebase and change application.

FieldNodeSchema ALPHA TODO: replace (or subclass) this with more specific types, like "List".
IterableTreeListContent BETA Used to insert iterable content into a TreeListNode. Use (TreeListNode:variable).inline to create an instance of this type.
LeafNodeSchema ALPHA
MapNodeSchema ALPHA
NodeBase BETA Base type which all nodes extend.
ObjectNodeSchema ALPHA
SchemaBuilderBase ALPHA Builds schema libraries, and the schema within them.
SchemaFactory BETA sealed Builds schema libraries, and the schema within them.
SharedTreeFactory ALPHA A channel factory that creates ISharedTrees.
test_RecursiveObject ALPHA
TreeConfiguration BETA Configuration for how to schematize a tree.
TreeFactory ALPHA A channel factory that creates an ITree.
TreeFieldSchema ALPHA sealed

All policy for a specific field, including functionality that does not have to be kept consistent across versions or deterministic.

This can include policy for how to use this schema for "view" purposes, and well as how to expose editing APIs.

TreeNodeSchemaBase ALPHA T must extend TreeSchemaSpecification. This can not be enforced using TypeScript since doing so breaks recursive type support. See note on SchemaBuilder.fieldRecursive.

Enumerations

Enum Alerts Description
AllowedUpdateType ALPHA

What kinds of updates to stored schema to permit.

TODO: Currently this does not account for lazy schema updates, and/or use of adapters.

CursorLocationType ALPHA
DiscardResult BETA The result of a discard operation.
FlexTreeEntityKind ALPHA
ForestType ALPHA Used to distinguish between different forest types.
ITreeSubscriptionCursorState ALPHA
Multiplicity ALPHA

Describes how a particular field functions.

This determine its reading and editing APIs, multiplicity, and what merge resolution policies it will use.

RevertibleKind BETA The type of revertible commit.
RevertResult BETA The result of a revert operation.
TransactionResult ALPHA Describes the result of a transaction. Transactions may either succeed and commit, or fail and abort.
TreeCompressionStrategy ALPHA Selects which heuristics to use when encoding tree content. All encoding options here are compatible with the same decoder: the selection here does not impact compatibility.
TreeNavigationResult ALPHA
TreeStatus BETA Status of the tree that a particular node belongs to.
ValueSchema ALPHA Schema for what TreeValue is allowed on a Leaf node.

Types

TypeAlias Alerts Description
_InlineTrick ALPHA Use for trick to "inline" generic types.
_RecursiveTrick ALPHA

Use for trick to prevent self reference error ts(2456).

Prefix a type expression with K extends _RecursiveTrick ? _RecursiveTrick : for some K to break the cycle.

AllowedTypes ALPHA

Types for use in fields.

"Any" is boxed in an array to allow use as variadic parameter.

AllowedTypeSet ALPHA Types for use in fields. This representation is optimized for runtime use in view-schema.
AllowedTypesToFlexInsertableTree ALPHA Takes in AllowedTypes and returns a TypedTree union.
AllowOptional ALPHA Converts properties of an object which permit undefined into optional properties. Removes fields which only allow undefined.
AllowOptionalNotFlattened ALPHA Converts properties of an object which permit undefined into optional properties. Removes fields which only allow undefined.
Anchor ALPHA A way to refer to a particular tree location within an AnchorSet. Associated with a ref count on the underlying AnchorNode.
AnchorSlot ALPHA Stores arbitrary, user-defined data on an Anchor. This data is preserved over the course of that anchor's lifetime.
Any ALPHA Allow any node (as long as it meets the schema for its own type).
ApplyMultiplicity ALPHA Adjusts the API for a field based on its Multiplicity.
AssignableFieldKinds ALPHA Field kinds that allow value assignment.
Assume ALPHA Assume that TInput is a TAssumeToBe.
Brand ALPHA

Constructs a "Branded" type, adding a type-checking only field to ValueType.

Two usages of Brand should never use the same Name. If they do, the resulting types will be assignable which defeats the point of this type.

This type is constructed such that the first line of type errors when assigning mismatched branded types will be: Type 'Name1' is not assignable to type 'Name2'.

These branded types are not opaque: A Brand<A, B> can still be used as a B.

BrandedKey ALPHA Key in a BrandedMapSubset.
BrandedKeyContent ALPHA
ChangesetLocalId ALPHA An ID which is unique within a revision of a ModularChangeset. A ModularChangeset which is a composition of multiple revisions may contain duplicate ChangesetLocalIds, but they are unique when qualified by the revision of the change they are used in.
CheckTypesOverlap ALPHA Type to ensures two types overlap in at least one way. It evaluates to the input type if this is true, and never otherwise. Examples: CheckTypesOverlap\ = number | boolean CheckTypesOverlap\ = never
ChildCollection ALPHA Identifier for a child collection, either on a node/tree or at the root of a forest.
CollectOptions ALPHA Collects the various parts of the API together.
ContextuallyTypedFieldData ALPHA

Content of a field which needs external schema information to interpret.

This format is intended for concise authoring of tree literals when the schema is statically known.

Once schema aware APIs are implemented, they can be used to provide schema specific subsets of this type.

ContextuallyTypedNodeData ALPHA

Content of a tree which needs external schema information to interpret.

This format is intended for concise authoring of tree literals when the schema is statically known.

Once schema aware APIs are implemented, they can be used to provide schema specific subsets of this type.

DeltaFieldMap ALPHA
DeltaProtoNode ALPHA

The default representation for inserted content.

TODO: Ownership and lifetime of data referenced by this cursor is unclear, so it is a poor abstraction for this use-case which needs to hold onto the data in a non-exclusive (readonly) way. Cursors can be one supported way to input data, but aren't a good storage format.

DetachedPlaceUpPath ALPHA A place in a detached field.
DetachedRangeUpPath ALPHA A range of nodes in a detached field. Unlike RangeUpPath, such ranges are generated by create and detach operations, as well as consumed by destroy and attach operations.
EmptyObject ALPHA Empty Object for use in type computations that should contribute no fields when &ed with another type.
Events BETA Used to specify the kinds of events emitted by an ISubscribable.
ExtractFromOpaque ALPHA See extractFromOpaque(value).
FieldGenerator ALPHA

Generates field content for a MapTree on demand.

TODO: Currently being exposed at the package level which also requires us to export MapTree at the package level. Refactor the FieldGenerator to use JsonableTree instead of MapTree, and convert them internally.

FieldKey ALPHA

Key (aka Name or Label) for a field which is scoped to a specific TreeNodeStoredSchema.

Stable identifier, used when persisting data.

FieldKindIdentifier ALPHA Identifier for a FieldKind. Refers to an exact stable policy (ex: specific version of a policy), for how to handle (ex: edit and merge edits to) fields marked with this kind. Persisted in documents as part of stored schema.
FlattenKeys ALPHA Return a type thats equivalent to the input, but with different IntelliSense. This tends to convert unions and intersections into objects.
FlexibleFieldContent ALPHA

Strongly typed tree literals for inserting as the content of a field.

If a cursor is provided, it must be in Fields mode.

FlexibleNodeContent ALPHA

Strongly typed tree literals for inserting as a node.

If a cursor is provided, it must be in Nodes mode.

FlexibleNodeSubSequence ALPHA

Strongly typed tree literals for inserting a subsequence of nodes.

Used to insert a batch of 0 or more nodes into some location in a FlexTreeSequenceField.

If a cursor is provided, it must be in Fields mode.

FlexImplicitFieldSchema ALPHA Type that when combined with a default FieldKind can be normalized into a TreeFieldSchema.
FlexTreeNodeSchema ALPHA
FlexTreeObjectNodeFields ALPHA Properties to access an object node's fields. See FlexTreeObjectNodeTyped.
FlexTreeObjectNodeTyped ALPHA An FlexTreeObjectNode with schema aware accessors for its fields.
FlexTreeTypedField ALPHA Schema aware specialization of FlexTreeField.
FlexTreeTypedFieldInner ALPHA Helper for implementing FlexTreeTypedField.
FlexTreeTypedNode ALPHA Schema aware specialization of FlexTreeNode for a given TreeNodeSchema.
FlexTreeTypedNodeUnion ALPHA Schema aware specialization of FlexTreeNode for a given AllowedTypes.
FlexTreeUnboxField ALPHA Schema aware unboxed field.
FlexTreeUnboxFieldInner ALPHA Helper for implementing FlexTreeUnboxField.
FlexTreeUnboxNode ALPHA Schema aware unboxed tree type.
FlexTreeUnboxNodeUnion ALPHA Schema aware unboxed union of tree types.
FlexTreeUnknownUnboxed ALPHA Unboxed tree type for unknown schema cases.
ForestLocation ALPHA Ways to refer to a node in an IEditableForest.
ImplicitAllowedTypes ALPHA Generalized version of AllowedTypes allowing for more concise expressions in some cases.
ImplicitFieldSchema BETA Schema for a field of a tree node.
InsertableFlexField ALPHA TreeFieldSchema to TypedField. May unwrap to child depending on FieldKind.
InsertableFlexNode ALPHA Generate a schema aware API for a single tree schema.
InsertableTreeNodeFromImplicitAllowedTypes BETA Type of content that can be inserted into the tree for a node of the given schema.
isAny ALPHA Returns a type parameter that is true iff T is any.
IsArrayOfOne ALPHA true if T is known to be an array of one item. false if T is known not to be an array of one item. boolean if it is unknown if T is an array of one item or not.
IsEvent BETA true iff the given type is an acceptable shape for an event
JsonCompatible ALPHA

Use for Json compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

JsonCompatibleObject ALPHA

Use for Json object compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

JsonCompatibleReadOnly ALPHA

Use for readonly view of Json compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

LazyTreeNodeSchema ALPHA Tree type, but can be wrapped in a function to allow referring to types before they are declared. This makes recursive and co-recursive types possible.
MapFieldSchema ALPHA Subset of TreeFieldSchema thats legal in maps. This requires empty to be a valid value for the map.
NameFromBranded ALPHA Implementation detail of type branding. Should not be used directly outside this file, but shows up as part of branded types so API-Extractor requires it to be exported.
NestedMap ALPHA

A dictionary whose values are keyed off of two objects (key1, key2). As it is a nested map, size() will return the number of distinct key1s. If you need constant-time access to the number of values, use SizedNestedMap instead.

This code assumes values will not be undefined (keys can be undefined).

NewFieldContent ALPHA

Content to use for a field.

When used, this content will be deeply copied into the tree, and must comply with the schema.

The content must follow the Multiplicity of the FieldKind: - use a single cursor for an optional or value field; - use array of cursors for a sequence field;

TODO: this should allow a field cursor instead of an array of cursors. TODO: Make this generic so a variant of this type that allows placeholders for detached sequences to consume.

NodeFromSchema BETA Takes in TreeNodeSchema[] and returns a TypedNode union.
NodeIndex ALPHA Indicates the index of a node in a field. Zero indicates the first node in a field.
NoListenersCallback ALPHA Called when the last listener for eventName is removed. Useful for determining when to clean up resources related to detecting when the event might occurs.
NormalizeAllowedTypes ALPHA Normalizes an ImplicitAllowedTypes into AllowedTypes.
NormalizeField ALPHA Normalizes an ImplicitFieldSchema into a TreeFieldSchema.
NormalizeFieldSchema ALPHA Convert FieldSchemaSpecification | undefined into TreeFieldSchema.
NormalizeObjectNodeFields ALPHA
Opaque ALPHA

Converts a Branded type into an "opaque" handle. This prevents the value from being used directly, but does not fully type erase it (and this its not really fully opaque): The type can be recovered using extractFromOpaque(value), however if we assume only code that produces these "opaque" handles does that conversion, they can function like opaque handles.

Recommended usage is to use interface instead of type so tooling (such as tsc and refactoring tools) uses the type name instead of expanding it:

export interface MyType extends Opaque<Brand<string, "myPackage.MyType">>{}

OptionalFields ALPHA Extract fields which permit undefined but can also hold other types.
PlaceIndex ALPHA Indicates a place between nodes in a field or at the extremity of a field. Zero indicates the place at the start of the field (before the first node if any).
ProtoNodes ALPHA

The default representation a chunk (sub-sequence) of inserted content.

TODO: See issue TODO with ProtoNode. Additionally, Cursors support sequences, so if using cursors, there are better ways to handle this than an array of cursors, like using a cursor over all the content (starting in fields mode). Long term something like TreeChunk should probably be used here.

RequiredFields ALPHA Remove all fields which permit undefined from T.
StableNodeKey ALPHA A UUID which identifies a node in the tree. This key is universally unique and stable forever; therefore it is safe to persist as data in a SharedTree or other DDS/database. When not persisted or serialized, it is preferable to use a LocalNodeKey instead for better performance.
TreeFieldFromImplicitField BETA Converts ImplicitFieldSchema to the corresponding tree node's field type.
TreeNodeSchema BETA Schema for a tree node.
TreeNodeSchemaIdentifier ALPHA

Identifier for a TreeNode schema. Also known as "Definition"

Stable identifier, used when persisting data.

TreeType ALPHA
TreeTypeSet ALPHA

Set of allowed tree types. Providing multiple values here allows polymorphism, tagged union style.

If not specified, types are unconstrained (equivalent to the set containing every TreeNodeSchemaIdentifier defined in the document).

Note that even when unconstrained, children must still be in-schema for their own type.

In the future, this could be extended to allow inlining a TreeNodeStoredSchema here (or some similar structural schema system). For structural types which could go here, there are a few interesting options:

- Allow replacing the whole set with a structural type for terminal / non-tree data, and use this as a replacement for values on the tree nodes.

- Allow expression structural constraints for child trees, for example requiring specific traits (ex: via TreeNodeStoredSchema), instead of by type.

There are two ways this could work:

- Constrain the child nodes based on their shape: this makes schema safe editing difficult because nodes would incur extra editing constraints to prevent them from going out of schema based on their location in such a field.

- Constrain the types allowed based on which types guarantee their data will always meet the constraints.

Care would need to be taken to make sure this is sound for the schema updating mechanisms.

TreeValue ALPHA Value that may be stored on a leaf node.
TypedFields ALPHA

{ [key: string]: FieldSchemaTypeInfo } to { [key: string]: TypedTree }

In Editable mode, unwraps the fields.

UnbrandedName ALPHA Remove type brand from name.
Unenforced ALPHA

A placeholder to use in extends constraints when using the real type breaks compilation of some recursive types due to [a design limitation of TypeScript](https://github.com/microsoft/TypeScript/issues/55758).

These extends constraints only serve as documentation: to avoid breaking compilation, this type has to not actually enforce anything, and thus is just unknown. Therefore the type safety is the responsibility of the user of the API.

Unhydrated BETA

Type alias to document which values are un-hydrated.

Un-hydrated values are nodes produced from schema's create functions that haven't been inserted into a tree yet.

Since un-hydrated nodes become hydrated when inserted, strong typing can't be used to distinguish them. This no-op wrapper is used instead.

UpPathDefault ALPHA Identical to UpPath, but a duplicate declaration is needed to make the default type parameter compile.
Value ALPHA Value stored on a node.
ValueFromBranded ALPHA Implementation detail of type branding. Should not be used directly outside this file, but shows up as part of branded types so API-Extractor requires it to be exported.

Functions

Function Alerts Return Type Description
anchorSlot() ALPHA AnchorSlot<TContent> Define a strongly typed slot on anchors in which data can be stored.
brand(value) ALPHA T

Adds a type Brand to a value.

Only do this when specifically allowed by the requirements of the type being converted to.

buildTreeConfiguration(config) ALPHA InitializeAndSchematizeConfiguration<T> Options used to initialize (if needed) and schematize a SharedTree.
compareLocalNodeKeys(a, b) ALPHA -1 | 0 | 1 Compares two LocalNodeKeys. All LocalNodeKeys retrieved from a single SharedTree client can be totally ordered using this comparator.
createEmitter(noListeners) ALPHA ISubscribable<E> & IEmitter<E> & HasListeners<E>

Create an ISubscribable that can be instructed to emit events via the IEmitter interface.

A class can delegate handling ISubscribable to the returned value while using it to emit the events. See also EventEmitter which be used as a base class to implement ISubscribable via extension.

cursorForTypedTreeData(context, schema, data) ALPHA ITreeCursorSynchronous Strongly typed cursorFromContextualData(context, typeSet, data) for a TreeNodeSchema.
cursorFromContextualData(context, typeSet, data) ALPHA ITreeCursorSynchronous

Construct a tree from ContextuallyTypedNodeData.

TODO: this should probably be refactored into a try function which either returns a Cursor or a SchemaError with a path to the error.

encodeTreeSchema(schema) ALPHA JsonCompatible Dumps schema into a deterministic JSON compatible semi-human readable but unspecified format.
extractFromOpaque(value) ALPHA ExtractFromOpaque<TOpaque>

Converts a Opaque handle to the underlying branded type.

It is assumed that only code that produces these "opaque" handles does this conversion, allowing these handles to be considered opaque.

fail(message) ALPHA never
getPrimaryField(schema) ALPHA { key: FieldKey; schema: TreeFieldStoredSchema; } | undefined
isContextuallyTypedNodeDataObject(data) ALPHA data is ContextuallyTypedNodeDataObject Checks the type of a ContextuallyTypedNodeData.
isNeverField(policy, originalData, field) ALPHA boolean
jsonableTreeFromCursor(cursor) ALPHA JsonableTree Extract a JsonableTree from the contents of the given ITreeCursor's current node.
oneFromSet(set) ALPHA T | undefined Returns the value from set if it contains exactly one item, otherwise undefined.
prefixFieldPath(prefix, path) ALPHA FieldUpPath Apply prefix to path.
prefixPath(prefix, path) ALPHA UpPath | undefined Apply prefix to path.
runSynchronous(view, transaction) ALPHA TransactionResult Run a synchronous transaction on the given shared tree view. This is a convenience helper around the SharedTreeFork#transaction APIs.
schemaIsFieldNode(schema) ALPHA schema is FieldNodeSchema Checks if a TreeNodeSchema is a FieldNodeSchema.
schemaIsLeaf(schema) ALPHA schema is LeafNodeSchema Checks if a TreeNodeSchema is a LeafNodeSchema.
schemaIsMap(schema) ALPHA schema is MapNodeSchema Checks if a TreeNodeSchema is a MapNodeSchema.
schemaIsObjectNode(schema) ALPHA schema is ObjectNodeSchema Checks if a TreeNodeSchema is a ObjectNodeSchema.
singleTextCursor(root) ALPHA ITreeCursorSynchronous Create a cursor, in nodes mode at the root of the provided tree.
stackTreeFieldCursor(adapter, root, detachedField) ALPHA CursorWithNode<TNode> Create a cursor, in fields mode at the detachedField under the provided root.
stackTreeNodeCursor(adapter, root) ALPHA CursorWithNode<TNode> Create a cursor, in nodes mode at the root of the provided tree.
treeSchemaFromStoredSchema(schema) ALPHA TreeSchema Creates a new view schema using the stored schema.

Variables

Variable Alerts Modifiers Description
Any ALPHA readonly Allow any node (as long as it meets the schema for its own type).
defaultSchemaPolicy ALPHA readonly FullSchemaPolicy with the default field kinds.
disposeSymbol BETA readonly

Placeholder for Symbol.dispose.

Replace this with Symbol.dispose when it is available.

EmptyKey ALPHA readonly

The empty key ("") is used for unnamed relationships, such as the indexer of an explicit array node.

This key is a hint that this field is the primary function of the node, and in some abstractions the APIs for this field should be inlined onto the node.

TODO: This has to be a FieldKey since different nodes will have different TreeFieldStoredSchema for it. This makes it prone to collisions and suggests that this intention may be better conveyed by metadata on the ITreeSchema.

FieldKinds ALPHA readonly Default FieldKinds with their editor types erased.
flexTreeMarker ALPHA readonly Indicates that an object is a flex tree.
forbiddenFieldKindIdentifier ALPHA readonly Identifier used for the FieldKind for fields which must be empty.
leaf ALPHA readonly Built-in LeafNodeSchema.
nodeKeyFieldKey ALPHA readonly The key for the special field for LocalNodeKeys, which allows nodes to be given keys that can be used to find the nodes via the node key index.
noopValidator ALPHA readonly A JsonValidator implementation which performs no validation and accepts all data as valid.
rootField ALPHA readonly
rootFieldKey ALPHA readonly FieldKey to use for the root of documents in places that need to refer to detached sequences or the root. TODO: if we do want to standardize on a single value for this, it likely should be namespaced or a UUID to avoid risk of collisions.
test_RecursiveObject_base ALPHA readonly

To make API-Extractor happy, the base type has to be exported in addition to the actual schema class. Ideally this would be inlined into the class definition below.

TODO: Fix API-Extractor to support class based schema, and remove this workaround (inline this type into RecursiveObject extends below). Error: src/class-tree/testRecursiveDomain.ts:32:1 - (ae-forgotten-export) The symbol "RecursiveObject_base" needs to be exported by the entry point index.d.ts See https://github.com/microsoft/rushstack/issues/4429

Tree BETA readonly The Tree object holds various functions for analyzing NodeBases.
TreeListNode BETA readonly A NodeBase which implements 'readonly T[]' and the list mutation APIs.
typeboxValidator ALPHA readonly A JsonValidator implementation which uses TypeBox's JSON schema validator.
typeNameSymbol ALPHA readonly A symbol for the name of the type of a tree in contexts where string keys are already in use for fields. See TreeNodeSchemaIdentifier.
valueSymbol ALPHA readonly A symbol for the value of a tree node in contexts where string keys are already in use for fields.

Namespaces

Namespace Description
InternalTypedSchemaTypes
InternalTypes

Type Details

_InlineTrick (ALPHA)

Use for trick to “inline” generic types.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type _InlineTrick = 0;

Remarks

The TypeScript compiler can be convinced to inline a generic type (so the result of evaluating the generic type show up in IntelliSense and error messages instead of just the invocation of the generic type) by creating an object with a field, and returning the type of that field.

For example:

type MyGeneric<T1, T2> = {x: T1 extends [] ? T1 : T2 };
type MyGenericExpanded<T1, T2> = [{x: T1 extends [] ? T1 : T2 }][_InlineTrick]
// Type is MyGeneric<5, string>
const foo: MyGeneric<5, string> = {x: "x"}
// Type is {x: "x"}
const foo2: MyGenericExpanded<5, string> = {x: "x"}

This constant is defined to provide a way to find this documentation from types which use this pattern, and to locate types which use this pattern in case they need updating for compiler changes.

_RecursiveTrick (ALPHA)

Use for trick to prevent self reference error ts(2456).

Prefix a type expression with K extends _RecursiveTrick ? _RecursiveTrick : for some K to break the cycle.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type _RecursiveTrick = never;

Remarks

The TypeScript compiler handles some cases of recursive types, but not others. Sometimes adding an otherwise needless conditional can make a type compile. Use this type in such cases.

For example:

// The TypeScript compiler can't handle this case
type Broken<T> = FlattenKeys<
	{
		[K in keyof T]: 0;
	} & {
		[K in keyof T]: Broken<T[K]>;
	}
>;
// Adding `K extends _RecursiveTrick ? _RecursiveTrick :` makes it compile, and has no effect on the type produced.
type Works<T> = FlattenKeys<
	{
		[K in keyof T]: 0;
	} & {
		// Trick added here. Since `k` never extends `never`, the second conditional option is always taken,
		// making this equivalent to the broken version, except this one compiles.
		[K in keyof T]: K extends _RecursiveTrick ? _RecursiveTrick : Works<T[K]>;
	}
>;

This trick appears to start working in TypeScript 4.1 and is confirmed to still work in 5.0.4.

This constant is defined to provide a way to find this documentation from types which use this pattern, and to locate types which use this pattern in case they need updating for compiler changes.

AllowedTypes (ALPHA)

Types for use in fields.

“Any” is boxed in an array to allow use as variadic parameter.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AllowedTypes = readonly [Any] | readonly LazyItem<TreeNodeSchema>[];

AllowedTypeSet (ALPHA)

Types for use in fields. This representation is optimized for runtime use in view-schema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AllowedTypeSet = Any | ReadonlySet<TreeNodeSchema>;

Remarks

See TreeTypeSet for a stored-schema compatible version using the TreeNodeSchemaIdentifier . See AllowedTypes for a compile time optimized version.

AllowedTypesToFlexInsertableTree (ALPHA)

Takes in AllowedTypes and returns a TypedTree union.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AllowedTypesToFlexInsertableTree<T extends AllowedTypes> = [
    T extends readonly LazyItem<TreeNodeSchema>[] ? InsertableFlexNode<Assume<FlexListToUnion<T>, TreeNodeSchema>> : ContextuallyTypedNodeData
][_InlineTrick];

AllowOptional (ALPHA)

Converts properties of an object which permit undefined into optional properties. Removes fields which only allow undefined.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AllowOptional<T> = [FlattenKeys<RequiredFields<T> & OptionalFields<T>>][_InlineTrick];

AllowOptionalNotFlattened (ALPHA)

Converts properties of an object which permit undefined into optional properties. Removes fields which only allow undefined.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AllowOptionalNotFlattened<T> = [RequiredFields<T> & OptionalFields<T>][_InlineTrick];

Remarks

This version does not flatten the resulting type. This version exists because some cases recursive types need to avoid this flattening since it causes complication issues.

See also AllowOptional.

Anchor (ALPHA)

A way to refer to a particular tree location within an AnchorSet . Associated with a ref count on the underlying AnchorNode .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Anchor = Brand<number, "rebaser.Anchor">;

AnchorSlot (ALPHA)

Stores arbitrary, user-defined data on an Anchor . This data is preserved over the course of that anchor’s lifetime.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AnchorSlot<TContent> = BrandedKey<Opaque<Brand<number, "AnchorSlot">>, TContent>;

See Also

anchorSlot() for creation and an example use case.

Any (ALPHA)

Allow any node (as long as it meets the schema for its own type).

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Any = typeof Any;

ApplyMultiplicity (ALPHA)

Adjusts the API for a field based on its Multiplicity.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ApplyMultiplicity<TMultiplicity extends Multiplicity, TypedChild> = {
    [Multiplicity.Forbidden]: undefined;
    [Multiplicity.Optional]: undefined | TypedChild;
    [Multiplicity.Sequence]: TypedChild[];
    [Multiplicity.Single]: TypedChild;
}[TMultiplicity];

AssignableFieldKinds (ALPHA)

Field kinds that allow value assignment.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type AssignableFieldKinds = typeof FieldKinds.optional | typeof FieldKinds.required;

Assume (ALPHA)

Assume that TInput is a TAssumeToBe.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Assume<TInput, TAssumeToBe> = [TInput] extends [TAssumeToBe] ? TInput : TAssumeToBe;

Remarks

This is useful in generic code when it is impractical (or messy) to to convince the compiler that a generic type TInput will extend TAssumeToBe. In these cases TInput can be replaced with Assume<TInput, TAssumeToBe> to allow compilation of the generic code. When the generic code is parameterized with a concrete type, if that type actually does extend TAssumeToBe, it will behave like TInput was used directly.

Brand (ALPHA)

Constructs a “Branded” type, adding a type-checking only field to ValueType.

Two usages of Brand should never use the same Name. If they do, the resulting types will be assignable which defeats the point of this type.

This type is constructed such that the first line of type errors when assigning mismatched branded types will be: Type 'Name1' is not assignable to type 'Name2'.

These branded types are not opaque: A Brand<A, B> can still be used as a B.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Brand<ValueType, Name extends string> = ValueType & BrandedType<ValueType, Name>;

BrandedKey (ALPHA)

Key in a BrandedMapSubset .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type BrandedKey<TKey, TContent> = TKey & Invariant<TContent>;

BrandedKeyContent (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type BrandedKeyContent<TKey extends BrandedKey<unknown, any>> = TKey extends BrandedKey<unknown, infer TContent> ? TContent : never;

ChangesetLocalId (ALPHA)

An ID which is unique within a revision of a ModularChangeset. A ModularChangeset which is a composition of multiple revisions may contain duplicate ChangesetLocalIds, but they are unique when qualified by the revision of the change they are used in.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ChangesetLocalId = Brand<number, "ChangesetLocalId">;

CheckTypesOverlap (ALPHA)

Type to ensures two types overlap in at least one way. It evaluates to the input type if this is true, and never otherwise. Examples: CheckTypesOverlap<number | boolean, number | object> = number | boolean CheckTypesOverlap<number | boolean, string | object> = never

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type CheckTypesOverlap<T, TCheck> = [Extract<T, TCheck> extends never ? never : T][0];

ChildCollection (ALPHA)

Identifier for a child collection, either on a node/tree or at the root of a forest.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ChildCollection = FieldKey | RootField;

CollectOptions (ALPHA)

Collects the various parts of the API together.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type CollectOptions<TTypedFields, TValueSchema extends ValueSchema | undefined, TName> = TValueSchema extends undefined ? FlattenKeys<{
    [typeNameSymbol]?: UnbrandedName<TName>;
} & (TValueSchema extends ValueSchema ? {
    [valueSymbol]: TreeValue<TValueSchema>;
} : EmptyObject)> & TTypedFields : TValueSchema extends ValueSchema ? TreeValue<TValueSchema> : undefined;

ContextuallyTypedFieldData (ALPHA)

Content of a field which needs external schema information to interpret.

This format is intended for concise authoring of tree literals when the schema is statically known.

Once schema aware APIs are implemented, they can be used to provide schema specific subsets of this type.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ContextuallyTypedFieldData = ContextuallyTypedNodeData | undefined;

ContextuallyTypedNodeData (ALPHA)

Content of a tree which needs external schema information to interpret.

This format is intended for concise authoring of tree literals when the schema is statically known.

Once schema aware APIs are implemented, they can be used to provide schema specific subsets of this type.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ContextuallyTypedNodeData = ContextuallyTypedNodeDataObject | number | string | boolean | null | readonly ContextuallyTypedNodeData[] | MarkedArrayLike<ContextuallyTypedNodeData>;

DeltaFieldMap (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FieldMap<TTree = ProtoNode> = ReadonlyMap<FieldKey, FieldChanges<TTree>>;

DeltaProtoNode (ALPHA)

The default representation for inserted content.

TODO: Ownership and lifetime of data referenced by this cursor is unclear, so it is a poor abstraction for this use-case which needs to hold onto the data in a non-exclusive (readonly) way. Cursors can be one supported way to input data, but aren’t a good storage format.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ProtoNode = ITreeCursorSynchronous;

DetachedPlaceUpPath (ALPHA)

A place in a detached field.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type DetachedPlaceUpPath = Brand<Omit<PlaceUpPath, "parent">, "DetachedRangeUpPath">;

DetachedRangeUpPath (ALPHA)

A range of nodes in a detached field. Unlike RangeUpPath, such ranges are generated by create and detach operations, as well as consumed by destroy and attach operations.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type DetachedRangeUpPath = Brand<Omit<RangeUpPath, "parent">, "DetachedRangeUpPath">;

EmptyObject (ALPHA)

Empty Object for use in type computations that should contribute no fields when &ed with another type.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type EmptyObject = {};

Events (BETA)

Used to specify the kinds of events emitted by an ISubscribable .

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type Events<E> = {
    [P in (string | symbol) & keyof E as IsEvent<E[P]> extends true ? P : never]: E[P];
};

Remarks

Any object type is a valid Events , but only the event-like properties of that type will be included.

Example

interface MyEvents {
  load: (user: string, data: IUserData) => void;
  error: (errorCode: number) => void;
}

ExtractFromOpaque (ALPHA)

See extractFromOpaque(value) .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ExtractFromOpaque<TOpaque extends BrandedType<any, string>> = TOpaque extends BrandedType<infer ValueType, infer Name> ? isAny<ValueType> extends true ? unknown : Brand<ValueType, Name> : never;

FieldGenerator (ALPHA)

Generates field content for a MapTree on demand.

TODO: Currently being exposed at the package level which also requires us to export MapTree at the package level. Refactor the FieldGenerator to use JsonableTree instead of MapTree, and convert them internally.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FieldGenerator = () => MapTree[];

FieldKey (ALPHA)

Key (aka Name or Label) for a field which is scoped to a specific TreeNodeStoredSchema.

Stable identifier, used when persisting data.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FieldKey = Brand<string, "tree.FieldKey">;

FieldKindIdentifier (ALPHA)

Identifier for a FieldKind. Refers to an exact stable policy (ex: specific version of a policy), for how to handle (ex: edit and merge edits to) fields marked with this kind. Persisted in documents as part of stored schema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FieldKindIdentifier = Brand<string, "tree.FieldKindIdentifier">;

FlattenKeys (ALPHA)

Return a type thats equivalent to the input, but with different IntelliSense. This tends to convert unions and intersections into objects.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlattenKeys<T> = [{
    [Property in keyof T]: T[Property];
}][_InlineTrick];

FlexibleFieldContent (ALPHA)

Strongly typed tree literals for inserting as the content of a field.

If a cursor is provided, it must be in Fields mode.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexibleFieldContent<TSchema extends TreeFieldSchema> = InsertableFlexField<TSchema> | ITreeCursorSynchronous;

FlexibleNodeContent (ALPHA)

Strongly typed tree literals for inserting as a node.

If a cursor is provided, it must be in Nodes mode.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexibleNodeContent<TTypes extends AllowedTypes> = AllowedTypesToFlexInsertableTree<TTypes> | ITreeCursorSynchronous;

FlexibleNodeSubSequence (ALPHA)

Strongly typed tree literals for inserting a subsequence of nodes.

Used to insert a batch of 0 or more nodes into some location in a FlexTreeSequenceField .

If a cursor is provided, it must be in Fields mode.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexibleNodeSubSequence<TTypes extends AllowedTypes> = Iterable<AllowedTypesToFlexInsertableTree<TTypes>> | ITreeCursorSynchronous;

FlexImplicitFieldSchema (ALPHA)

Type that when combined with a default FieldKind can be normalized into a TreeFieldSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ImplicitFieldSchema = TreeFieldSchema | ImplicitAllowedTypes;

FlexTreeNodeSchema (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TreeNodeSchema = TreeNodeSchemaBase;

FlexTreeObjectNodeFields (ALPHA)

Properties to access an object node’s fields. See FlexTreeObjectNodeTyped .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeObjectNodeFields<TFields extends Fields> = FlattenKeys<{
    readonly [key in keyof TFields as `boxed${Capitalize<key & string>}`]: FlexTreeTypedField<TFields[key]>;
} & {
    readonly [key in keyof TFields as TFields[key]["kind"] extends AssignableFieldKinds ? never : key]: FlexTreeUnboxField<TFields[key]>;
} & {
    -readonly [key in keyof TFields as TFields[key]["kind"] extends AssignableFieldKinds ? key : never]: FlexTreeUnboxField<TFields[key]>;
} & {
    readonly [key in keyof TFields as TFields[key]["kind"] extends AssignableFieldKinds ? `set${Capitalize<key & string>}` : never]: (content: FlexibleFieldContent<TFields[key]>) => void;
}>;

FlexTreeObjectNodeTyped (ALPHA)

An FlexTreeObjectNode with schema aware accessors for its fields.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeObjectNodeTyped<TSchema extends ObjectNodeSchema> = ObjectNodeSchema extends TSchema ? FlexTreeObjectNode : FlexTreeObjectNode & FlexTreeObjectNodeFields<TSchema["info"]>;

FlexTreeTypedField (ALPHA)

Schema aware specialization of FlexTreeField .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeTypedField<TSchema extends TreeFieldSchema> = FlexTreeTypedFieldInner<TSchema["kind"], TSchema["allowedTypes"]>;

FlexTreeTypedFieldInner (ALPHA)

Helper for implementing FlexTreeTypedField .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeTypedFieldInner<Kind extends FieldKind, Types extends AllowedTypes> = Kind extends typeof FieldKinds.sequence ? FlexTreeSequenceField<Types> : Kind extends typeof FieldKinds.required ? FlexTreeRequiredField<Types> : Kind extends typeof FieldKinds.optional ? FlexTreeOptionalField<Types> : Kind extends typeof FieldKinds.nodeKey ? FlexTreeNodeKeyField : FlexTreeField;

FlexTreeTypedNode (ALPHA)

Schema aware specialization of FlexTreeNode for a given TreeNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeTypedNode<TSchema extends TreeNodeSchema> = TSchema extends LeafNodeSchema ? FlexTreeLeafNode<TSchema> : TSchema extends MapNodeSchema ? FlexTreeMapNode<TSchema> : TSchema extends FieldNodeSchema ? FlexTreeFieldNode<TSchema> : TSchema extends ObjectNodeSchema ? FlexTreeObjectNodeTyped<TSchema> : FlexTreeNode;

FlexTreeTypedNodeUnion (ALPHA)

Schema aware specialization of FlexTreeNode for a given AllowedTypes .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeTypedNodeUnion<T extends AllowedTypes> = T extends FlexList<TreeNodeSchema> ? FlexTreeTypedNode<Assume<FlexListToUnion<T>, TreeNodeSchema>> : FlexTreeNode;

FlexTreeUnboxField (ALPHA)

Schema aware unboxed field.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeUnboxField<TSchema extends TreeFieldSchema, Emptiness extends "maybeEmpty" | "notEmpty" = "maybeEmpty"> = FlexTreeUnboxFieldInner<TSchema["kind"], TSchema["allowedTypes"], Emptiness>;

Remarks

Unboxes fields to their content if appropriate for the kind. Recursively unboxes that content (then its content etc.) as well if the node union does unboxing.

FlexTreeUnboxFieldInner (ALPHA)

Helper for implementing FlexTreeUnboxField.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeUnboxFieldInner<Kind extends FieldKind, TTypes extends AllowedTypes, Emptiness extends "maybeEmpty" | "notEmpty"> = Kind extends typeof FieldKinds.sequence ? FlexTreeSequenceField<TTypes> : Kind extends typeof FieldKinds.required ? FlexTreeUnboxNodeUnion<TTypes> : Kind extends typeof FieldKinds.optional ? FlexTreeUnboxNodeUnion<TTypes> | (Emptiness extends "notEmpty" ? never : undefined) : Kind extends typeof FieldKinds.nodeKey ? FlexTreeNodeKeyField : unknown;

FlexTreeUnboxNode (ALPHA)

Schema aware unboxed tree type.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeUnboxNode<TSchema extends TreeNodeSchema> = TSchema extends LeafNodeSchema ? TreeValue<TSchema["info"]> : TSchema extends MapNodeSchema ? FlexTreeMapNode<TSchema> : TSchema extends FieldNodeSchema ? FlexTreeFieldNode<TSchema> : TSchema extends ObjectNodeSchema ? FlexTreeObjectNodeTyped<TSchema> : FlexTreeUnknownUnboxed;

Remarks

Unboxes if the node kind does unboxing. Recursively unboxes that content as well if it does unboxing.

FlexTreeUnboxNodeUnion (ALPHA)

Schema aware unboxed union of tree types.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeUnboxNodeUnion<TTypes extends AllowedTypes> = TTypes extends readonly [
    InternalTypedSchemaTypes.LazyItem<infer InnerType>
] ? InnerType extends TreeNodeSchema ? FlexTreeUnboxNode<InnerType> : InnerType extends Any ? FlexTreeNode : unknown : boolean extends IsArrayOfOne<TTypes> ? FlexTreeUnknownUnboxed : FlexTreeTypedNodeUnion<TTypes>;

Remarks

Unboxes when not polymorphic. Recursively unboxes that content as well if the node kind does unboxing.

FlexTreeUnknownUnboxed (ALPHA)

Unboxed tree type for unknown schema cases.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type FlexTreeUnknownUnboxed = TreeValue | FlexTreeNode;

ForestLocation (ALPHA)

Ways to refer to a node in an IEditableForest.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ForestLocation = ITreeSubscriptionCursor | Anchor;

ImplicitAllowedTypes (ALPHA)

Generalized version of AllowedTypes allowing for more concise expressions in some cases.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ImplicitAllowedTypes = AllowedTypes | TreeNodeSchema | Any;

ImplicitFieldSchema (BETA)

Schema for a field of a tree node.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type ImplicitFieldSchema = FieldSchema | ImplicitAllowedTypes;

Remarks

Implicitly treats ImplicitAllowedTypes as a Required field of that type.

InsertableFlexField (ALPHA)

TreeFieldSchema to TypedField. May unwrap to child depending on FieldKind.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type InsertableFlexField<TField extends TreeFieldSchema> = [
    ApplyMultiplicity<TField["kind"]["multiplicity"], AllowedTypesToFlexInsertableTree<TField["allowedTypes"]>>
][_InlineTrick];

InsertableFlexNode (ALPHA)

Generate a schema aware API for a single tree schema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type InsertableFlexNode<TSchema extends TreeNodeSchema> = FlattenKeys<CollectOptions<TSchema extends ObjectNodeSchema<string, infer TFields extends Fields> ? TypedFields<TFields> : TSchema extends FieldNodeSchema<string, infer TField extends TreeFieldSchema> ? InsertableFlexField<TField> : TSchema extends MapNodeSchema<string, infer TField extends TreeFieldSchema> ? {
    readonly [P in string]: InsertableFlexField<TField>;
} : EmptyObject, TSchema extends LeafNodeSchema<string, infer TValueSchema> ? TValueSchema : undefined, TSchema["name"]>>;

InsertableTreeNodeFromImplicitAllowedTypes (BETA)

Type of content that can be inserted into the tree for a node of the given schema.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type InsertableTreeNodeFromImplicitAllowedTypes<TSchema extends ImplicitAllowedTypes = TreeNodeSchema> = TSchema extends TreeNodeSchema ? InsertableTypedNode<TSchema> : TSchema extends AllowedTypes ? InsertableTypedNode<FlexListToUnion<TSchema>> : never;

isAny (ALPHA)

Returns a type parameter that is true iff T is any.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type isAny<T> = boolean extends (T extends never ? true : false) ? true : false;

IsArrayOfOne (ALPHA)

true if T is known to be an array of one item. false if T is known not to be an array of one item. boolean if it is unknown if T is an array of one item or not.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type IsArrayOfOne<T extends readonly unknown[]> = T["length"] extends 1 ? true : 1 extends T["length"] ? boolean : false;

IsEvent (BETA)

true iff the given type is an acceptable shape for an event

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type IsEvent<Event> = Event extends (...args: any[]) => any ? true : false;

JsonCompatible (ALPHA)

Use for Json compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type JsonCompatible = string | number | boolean | null | JsonCompatible[] | JsonCompatibleObject;

JsonCompatibleObject (ALPHA)

Use for Json object compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type JsonCompatibleObject = {
    [P in string]?: JsonCompatible;
};

JsonCompatibleReadOnly (ALPHA)

Use for readonly view of Json compatible data.

Note that this does not robustly forbid non json comparable data via type checking, but instead mostly restricts access to it.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type JsonCompatibleReadOnly = string | number | boolean | null | readonly JsonCompatibleReadOnly[] | {
    readonly [P in string]?: JsonCompatibleReadOnly;
};

LazyTreeNodeSchema (ALPHA)

Tree type, but can be wrapped in a function to allow referring to types before they are declared. This makes recursive and co-recursive types possible.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type LazyTreeNodeSchema = TreeNodeSchema | (() => TreeNodeSchema);

MapFieldSchema (ALPHA)

Subset of TreeFieldSchema thats legal in maps. This requires empty to be a valid value for the map.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type MapFieldSchema = TreeFieldSchema<typeof FieldKinds.optional | typeof FieldKinds.sequence>;

NameFromBranded (ALPHA)

Implementation detail of type branding. Should not be used directly outside this file, but shows up as part of branded types so API-Extractor requires it to be exported.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NameFromBranded<T extends BrandedType<any, string>> = T extends BrandedType<any, infer Name> ? Name : never;

NestedMap (ALPHA)

A dictionary whose values are keyed off of two objects (key1, key2). As it is a nested map, size() will return the number of distinct key1s. If you need constant-time access to the number of values, use SizedNestedMap instead.

This code assumes values will not be undefined (keys can be undefined).

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NestedMap<Key1, Key2, Value> = Map<Key1, Map<Key2, Value>>;

NewFieldContent (ALPHA)

Content to use for a field.

When used, this content will be deeply copied into the tree, and must comply with the schema.

The content must follow the Multiplicity of the FieldKind : - use a single cursor for an optional or value field; - use array of cursors for a sequence field;

TODO: this should allow a field cursor instead of an array of cursors. TODO: Make this generic so a variant of this type that allows placeholders for detached sequences to consume.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NewFieldContent = ITreeCursorSynchronous | readonly ITreeCursorSynchronous[] | ContextuallyTypedFieldData;

NodeFromSchema (BETA)

Takes in TreeNodeSchema[] and returns a TypedNode union.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type NodeFromSchema<T extends TreeNodeSchema> = T extends TreeNodeSchema<string, NodeKind, infer TNode> ? TNode : never;

NodeIndex (ALPHA)

Indicates the index of a node in a field. Zero indicates the first node in a field.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NodeIndex = number;

NoListenersCallback (ALPHA)

Called when the last listener for eventName is removed. Useful for determining when to clean up resources related to detecting when the event might occurs.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NoListenersCallback<E extends Events<E>> = (eventName: keyof Events<E>) => void;

NormalizeAllowedTypes (ALPHA)

Normalizes an ImplicitAllowedTypes into AllowedTypes .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NormalizeAllowedTypes<TSchema extends ImplicitAllowedTypes> = TSchema extends TreeNodeSchema ? readonly [TSchema] : TSchema extends Any ? readonly [Any] : TSchema;

NormalizeField (ALPHA)

Normalizes an ImplicitFieldSchema into a TreeFieldSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NormalizeField<TSchema extends ImplicitFieldSchema, TDefault extends FieldKind> = TSchema extends TreeFieldSchema ? TSchema : TreeFieldSchema<TDefault, NormalizeAllowedTypes<Assume<TSchema, ImplicitAllowedTypes>>>;

NormalizeFieldSchema (ALPHA)

Convert FieldSchemaSpecification | undefined into TreeFieldSchema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NormalizeField<T extends TreeFieldSchema | undefined> = T extends TreeFieldSchema ? T : TreeFieldSchema<typeof FieldKinds.forbidden, []>;

NormalizeObjectNodeFields (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type NormalizeObjectNodeFields<T extends Fields> = {
    readonly [Property in keyof T]: NormalizeField<T[Property]>;
};

Opaque (ALPHA)

Converts a Branded type into an “opaque” handle. This prevents the value from being used directly, but does not fully type erase it (and this its not really fully opaque): The type can be recovered using extractFromOpaque(value) , however if we assume only code that produces these “opaque” handles does that conversion, they can function like opaque handles.

Recommended usage is to use interface instead of type so tooling (such as tsc and refactoring tools) uses the type name instead of expanding it:

export interface MyType extends Opaque<Brand<string, "myPackage.MyType">>{}

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Opaque<T extends Brand<any, string>> = T extends Brand<infer ValueType, infer Name> ? BrandedType<ValueType, Name> : never;

OptionalFields (ALPHA)

Extract fields which permit undefined but can also hold other types.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type OptionalFields<T> = [
    {
        [P in keyof T as undefined extends T[P] ? T[P] extends undefined ? never : P : never]?: T[P];
    }
][_InlineTrick];

PlaceIndex (ALPHA)

Indicates a place between nodes in a field or at the extremity of a field. Zero indicates the place at the start of the field (before the first node if any).

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type PlaceIndex = number;

ProtoNodes (ALPHA)

The default representation a chunk (sub-sequence) of inserted content.

TODO: See issue TODO with ProtoNode. Additionally, Cursors support sequences, so if using cursors, there are better ways to handle this than an array of cursors, like using a cursor over all the content (starting in fields mode). Long term something like TreeChunk should probably be used here.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ProtoNodes = readonly ProtoNode[];

RequiredFields (ALPHA)

Remove all fields which permit undefined from T.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type RequiredFields<T> = [
    {
        [P in keyof T as undefined extends T[P] ? never : P]: T[P];
    }
][_InlineTrick];

StableNodeKey (ALPHA)

A UUID which identifies a node in the tree. This key is universally unique and stable forever; therefore it is safe to persist as data in a SharedTree or other DDS/database. When not persisted or serialized, it is preferable to use a LocalNodeKey instead for better performance.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type StableNodeKey = Brand<StableId, "Stable Node Key">;

TreeFieldFromImplicitField (BETA)

Converts ImplicitFieldSchema to the corresponding tree node’s field type.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type TreeFieldFromImplicitField<TSchema extends ImplicitFieldSchema = FieldSchema> = TSchema extends FieldSchema<infer Kind, infer Types> ? ApplyKind<TreeNodeFromImplicitAllowedTypes<Types>, Kind> : TSchema extends ImplicitAllowedTypes ? TreeNodeFromImplicitAllowedTypes<TSchema> : unknown;

TreeNodeSchema (BETA)

Schema for a tree node.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type TreeNodeSchema<Name extends string = string, Kind extends NodeKind = NodeKind, TNode = unknown, TBuild = never> = TreeNodeSchemaClass<Name, Kind, TNode, TBuild> | TreeNodeSchemaNonClass<Name, Kind, TNode, TBuild>;

Remarks

Captures the schema both as runtime data and compile time type information.

TreeNodeSchemaIdentifier (ALPHA)

Identifier for a TreeNode schema. Also known as “Definition”

Stable identifier, used when persisting data.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TreeNodeSchemaIdentifier<TName extends string = string> = Brand<TName, "tree.TreeNodeSchemaIdentifier">;

TreeType (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TreeType = TreeNodeSchemaIdentifier;

TreeTypeSet (ALPHA)

Set of allowed tree types. Providing multiple values here allows polymorphism, tagged union style.

If not specified, types are unconstrained (equivalent to the set containing every TreeNodeSchemaIdentifier defined in the document).

Note that even when unconstrained, children must still be in-schema for their own type.

In the future, this could be extended to allow inlining a TreeNodeStoredSchema here (or some similar structural schema system). For structural types which could go here, there are a few interesting options:

  • Allow replacing the whole set with a structural type for terminal / non-tree data, and use this as a replacement for values on the tree nodes.

  • Allow expression structural constraints for child trees, for example requiring specific traits (ex: via TreeNodeStoredSchema), instead of by type.

There are two ways this could work:

  • Constrain the child nodes based on their shape: this makes schema safe editing difficult because nodes would incur extra editing constraints to prevent them from going out of schema based on their location in such a field.

  • Constrain the types allowed based on which types guarantee their data will always meet the constraints.

Care would need to be taken to make sure this is sound for the schema updating mechanisms.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TreeTypeSet = ReadonlySet<TreeNodeSchemaIdentifier> | undefined;

TreeValue (ALPHA)

Value that may be stored on a leaf node.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TreeValue<TSchema extends ValueSchema = ValueSchema> = [
    {
        [ValueSchema.Number]: number;
        [ValueSchema.String]: string;
        [ValueSchema.Boolean]: boolean;
        [ValueSchema.FluidHandle]: IFluidHandle;
        [ValueSchema.Null]: null;
    }[TSchema]
][_InlineTrick];

TypedFields (ALPHA)

{ [key: string]: FieldSchemaTypeInfo } to { [key: string]: TypedTree }

In Editable mode, unwraps the fields.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type TypedFields<TFields extends undefined | {
    readonly [key: string]: TreeFieldSchema;
}> = [
    TFields extends {
        [key: string]: TreeFieldSchema;
    } ? {
        -readonly [key in keyof TFields]: InsertableFlexField<TFields[key]>;
    } : EmptyObject
][_InlineTrick];

UnbrandedName (ALPHA)

Remove type brand from name.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type UnbrandedName<TName> = [
    TName extends TreeNodeSchemaIdentifier<infer S> ? S : string
][_InlineTrick];

Unenforced (ALPHA)

A placeholder to use in extends constraints when using the real type breaks compilation of some recursive types due to [a design limitation of TypeScript](https://github.com/microsoft/TypeScript/issues/55758) .

These extends constraints only serve as documentation: to avoid breaking compilation, this type has to not actually enforce anything, and thus is just unknown. Therefore the type safety is the responsibility of the user of the API.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Unenforced<_DesiredExtendsConstraint> = unknown;

Unhydrated (BETA)

Type alias to document which values are un-hydrated.

Un-hydrated values are nodes produced from schema’s create functions that haven’t been inserted into a tree yet.

Since un-hydrated nodes become hydrated when inserted, strong typing can’t be used to distinguish them. This no-op wrapper is used instead.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

export type Unhydrated<T> = T;

UpPathDefault (ALPHA)

Identical to UpPath , but a duplicate declaration is needed to make the default type parameter compile.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type UpPathDefault = UpPath;

Value (ALPHA)

Value stored on a node.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type Value = undefined | TreeValue;

ValueFromBranded (ALPHA)

Implementation detail of type branding. Should not be used directly outside this file, but shows up as part of branded types so API-Extractor requires it to be exported.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export type ValueFromBranded<T extends BrandedType<any, string>> = T extends BrandedType<infer ValueType, string> ? ValueType : never;

Function Details

anchorSlot (ALPHA)

Define a strongly typed slot on anchors in which data can be stored.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function anchorSlot<TContent>(): AnchorSlot<TContent>;

Remarks

This is mainly useful for caching data associated with a location in the tree.

Example usage:

const counterSlot = anchorSlot<number>();
function useSlot(anchor: AnchorNode): void {
	anchor.slots.set(counterSlot, 1 + anchor.slots.get(counterSlot) ?? 0);
}

Returns

Return type: AnchorSlot <TContent>

brand (ALPHA)

Adds a type Brand to a value.

Only do this when specifically allowed by the requirements of the type being converted to.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function brand<T extends Brand<any, string>>(value: T extends BrandedType<infer ValueType, string> ? ValueType : never): T;

Parameters

Parameter Type Description
value T extends BrandedType<infer ValueType, string> ? ValueType : never

Returns

Return type: T

buildTreeConfiguration (ALPHA)

Options used to initialize (if needed) and schematize a SharedTree.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function buildTreeConfiguration<T extends TreeFieldSchema>(config: InitializeAndSchematizeConfiguration<T>): InitializeAndSchematizeConfiguration<T>;

Remarks

Using this builder improves type safety and error quality over just constructing the configuration as a object.

Parameters

Parameter Type Description
config InitializeAndSchematizeConfiguration<T>

Returns

Return type: InitializeAndSchematizeConfiguration <T>

compareLocalNodeKeys (ALPHA)

Compares two LocalNodeKey s. All LocalNodeKey s retrieved from a single SharedTree client can be totally ordered using this comparator.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function compareLocalNodeKeys(a: LocalNodeKey, b: LocalNodeKey): -1 | 0 | 1;

Parameters

Parameter Type Description
a LocalNodeKey the first key to compare
b LocalNodeKey the second key to compare

Returns

0 if a and b are the same key, otherwise -1 if a is ordered before b or 1 if a is ordered after b.

Return type: -1 | 0 | 1

createEmitter (ALPHA)

Create an ISubscribable that can be instructed to emit events via the IEmitter interface.

A class can delegate handling ISubscribable to the returned value while using it to emit the events. See also EventEmitter which be used as a base class to implement ISubscribable via extension.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function createEmitter<E extends Events<E>>(noListeners?: NoListenersCallback<E>): ISubscribable<E> & IEmitter<E> & HasListeners<E>;

Parameters

Parameter Modifiers Type Description
noListeners optional NoListenersCallback<E>

Returns

Return type: ISubscribable <E> & IEmitter <E> & HasListeners <E>

cursorForTypedTreeData (ALPHA)

Strongly typed cursorFromContextualData(context, typeSet, data) for a TreeNodeSchema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function cursorForTypedTreeData<T extends TreeNodeSchema>(context: TreeDataContext, schema: T, data: InsertableFlexNode<T>): ITreeCursorSynchronous;

Parameters

Parameter Type Description
context TreeDataContext
schema T
data InsertableFlexNode<T>

Returns

a cursor in Nodes mode for a single node containing the provided data.

Return type: ITreeCursorSynchronous

cursorFromContextualData (ALPHA)

Construct a tree from ContextuallyTypedNodeData.

TODO: this should probably be refactored into a try function which either returns a Cursor or a SchemaError with a path to the error.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function cursorFromContextualData(context: TreeDataContext, typeSet: TreeTypeSet, data: ContextuallyTypedNodeData): ITreeCursorSynchronous;

Parameters

Parameter Type Description
context TreeDataContext
typeSet TreeTypeSet
data ContextuallyTypedNodeData

Returns

a cursor in Nodes mode for a single node containing the provided data.

Return type: ITreeCursorSynchronous

encodeTreeSchema (ALPHA)

Dumps schema into a deterministic JSON compatible semi-human readable but unspecified format.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function encodeTreeSchema(schema: TreeStoredSchema): JsonCompatible;

Remarks

This can be used to help inspect schema for debugging, and to save a snapshot of schema to help detect and review changes to an applications schema.

This format may change across major versions of this package: such changes are considered breaking. Beyond that, no compatibility guarantee is provided for this format: it should never be relied upon to load data, it should only be used for comparing outputs from this function.

Parameters

Parameter Type Description
schema TreeStoredSchema

Returns

Return type: JsonCompatible

extractFromOpaque (ALPHA)

Converts a Opaque handle to the underlying branded type.

It is assumed that only code that produces these “opaque” handles does this conversion, allowing these handles to be considered opaque.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function extractFromOpaque<TOpaque extends BrandedType<any, string>>(value: TOpaque): ExtractFromOpaque<TOpaque>;

Parameters

Parameter Type Description
value TOpaque

Returns

Return type: ExtractFromOpaque <TOpaque>

fail (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function fail(message: string): never;

Parameters

Parameter Type Description
message string

Returns

Return type: never

getPrimaryField (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function getPrimaryField(schema: TreeNodeStoredSchema): {
    key: FieldKey;
    schema: TreeFieldStoredSchema;
} | undefined;

Parameters

Parameter Type Description
schema TreeNodeStoredSchema

Returns

the key and the schema of the primary field out of the given tree schema.

See note on EmptyKey for what is a primary field.

Return type: { key: FieldKey ; schema: TreeFieldStoredSchema ; } | undefined

isContextuallyTypedNodeDataObject (ALPHA)

Checks the type of a ContextuallyTypedNodeData.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function isContextuallyTypedNodeDataObject(data: ContextuallyTypedNodeData | undefined): data is ContextuallyTypedNodeDataObject;

Parameters

Parameter Type Description
data ContextuallyTypedNodeData | undefined

Returns

Return type: data is ContextuallyTypedNodeDataObject

isNeverField (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function isNeverField(policy: FullSchemaPolicy, originalData: TreeStoredSchema, field: TreeFieldStoredSchema): boolean;

Parameters

Parameter Type Description
policy FullSchemaPolicy
originalData TreeStoredSchema
field TreeFieldStoredSchema

Returns

Return type: boolean

jsonableTreeFromCursor (ALPHA)

Extract a JsonableTree from the contents of the given ITreeCursor’s current node.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function jsonableTreeFromCursor(cursor: ITreeCursor): JsonableTree;

Parameters

Parameter Type Description
cursor ITreeCursor

Returns

Return type: JsonableTree

oneFromSet (ALPHA)

Returns the value from set if it contains exactly one item, otherwise undefined.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function oneFromSet<T>(set: ReadonlySet<T> | undefined): T | undefined;

Parameters

Parameter Type Description
set ReadonlySet<T> | undefined

Returns

Return type: T | undefined

prefixFieldPath (ALPHA)

Apply prefix to path.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function prefixFieldPath(prefix: PathRootPrefix | undefined, path: FieldUpPath): FieldUpPath;

Parameters

Parameter Type Description
prefix PathRootPrefix | undefined
path FieldUpPath

Returns

Return type: FieldUpPath

prefixPath (ALPHA)

Apply prefix to path.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function prefixPath(prefix: PathRootPrefix | undefined, path: UpPath | undefined): UpPath | undefined;

Parameters

Parameter Type Description
prefix PathRootPrefix | undefined
path UpPath | undefined

Returns

Return type: UpPath | undefined

runSynchronous (ALPHA)

Run a synchronous transaction on the given shared tree view. This is a convenience helper around the SharedTreeFork#transaction APIs.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function runSynchronous(view: ITreeCheckout, transaction: (view: ITreeCheckout) => TransactionResult | void): TransactionResult;

Parameters

Parameter Type Description
view ITreeCheckout the view on which to run the transaction
transaction (view: ITreeCheckout) => TransactionResult | void the transaction function. This will be executed immediately. It is passed view as an argument for convenience. If this function returns an Abort result then the transaction will be aborted. Otherwise, it will be committed.

Returns

whether or not the transaction was committed or aborted

Return type: TransactionResult

schemaIsFieldNode (ALPHA)

Checks if a TreeNodeSchema is a FieldNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function schemaIsFieldNode(schema: TreeNodeSchema): schema is FieldNodeSchema;

Parameters

Parameter Type Description
schema TreeNodeSchema

Returns

Return type: schema is FieldNodeSchema

schemaIsLeaf (ALPHA)

Checks if a TreeNodeSchema is a LeafNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function schemaIsLeaf(schema: TreeNodeSchema): schema is LeafNodeSchema;

Parameters

Parameter Type Description
schema TreeNodeSchema

Returns

Return type: schema is LeafNodeSchema

schemaIsMap (ALPHA)

Checks if a TreeNodeSchema is a MapNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function schemaIsMap(schema: TreeNodeSchema): schema is MapNodeSchema;

Parameters

Parameter Type Description
schema TreeNodeSchema

Returns

Return type: schema is MapNodeSchema

schemaIsObjectNode (ALPHA)

Checks if a TreeNodeSchema is a ObjectNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function schemaIsObjectNode(schema: TreeNodeSchema): schema is ObjectNodeSchema;

Parameters

Parameter Type Description
schema TreeNodeSchema

Returns

Return type: schema is ObjectNodeSchema

singleTextCursor (ALPHA)

Create a cursor, in nodes mode at the root of the provided tree.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function cursorForJsonableTreeNode(root: JsonableTree): ITreeCursorSynchronous;

Remarks

Do not confuse this with JsonableTree with the JSON domain: this takes in data in a specific format that is json compatible (except for FluidHandle values). That is distinct from treating arbitrary JSON data as a tree in the JSON domain.

Parameters

Parameter Type Description
root JsonableTree

Returns

an ITreeCursorSynchronous in nodes mode for a single JsonableTree .

Return type: ITreeCursorSynchronous

stackTreeFieldCursor (ALPHA)

Create a cursor, in fields mode at the detachedField under the provided root.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function stackTreeFieldCursor<TNode>(adapter: CursorAdapter<TNode>, root: TNode, detachedField?: DetachedField): CursorWithNode<TNode>;

Parameters

Parameter Modifiers Type Description
adapter CursorAdapter<TNode>
root TNode
detachedField optional DetachedField

Returns

an ITreeCursorSynchronous for detachedField of root in fields mode.

Return type: CursorWithNode <TNode>

stackTreeNodeCursor (ALPHA)

Create a cursor, in nodes mode at the root of the provided tree.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function stackTreeNodeCursor<TNode>(adapter: CursorAdapter<TNode>, root: TNode): CursorWithNode<TNode>;

Parameters

Parameter Type Description
adapter CursorAdapter<TNode>
root TNode

Returns

an ITreeCursorSynchronous for a single root in nodes mode.

Return type: CursorWithNode <TNode>

treeSchemaFromStoredSchema (ALPHA)

Creates a new view schema using the stored schema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

export declare function treeSchemaFromStoredSchema(schema: TreeStoredSchema): TreeSchema;

Remarks

This is really only suitable for use with code that happens to need access to things which require a view schema, but isn’t actually schema aware. If the input schema came from a view schema, it will not return the same view schema, and will not be compatible: the returned TreeSchema is simply one which schematize will not object to. Assumes the schema uses the default field kinds.

Parameters

Parameter Type Description
schema TreeStoredSchema

Returns

Return type: TreeSchema

Variable Details

Any (ALPHA)

Allow any node (as long as it meets the schema for its own type).

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

Any: "Any"

defaultSchemaPolicy (ALPHA)

FullSchemaPolicy with the default field kinds.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

defaultSchemaPolicy: FullSchemaPolicy

disposeSymbol (BETA)

Placeholder for Symbol.dispose.

Replace this with Symbol.dispose when it is available.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

disposeSymbol: unique symbol

EmptyKey (ALPHA)

The empty key ("") is used for unnamed relationships, such as the indexer of an explicit array node.

This key is a hint that this field is the primary function of the node, and in some abstractions the APIs for this field should be inlined onto the node.

TODO: This has to be a FieldKey since different nodes will have different TreeFieldStoredSchema for it. This makes it prone to collisions and suggests that this intention may be better conveyed by metadata on the ITreeSchema.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

EmptyKey: FieldKey

FieldKinds (ALPHA)

Default FieldKinds with their editor types erased.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

FieldKinds: {
    readonly required: Required;
    readonly optional: Optional;
    readonly sequence: Sequence;
    readonly nodeKey: NodeKeyFieldKind;
    readonly forbidden: Forbidden;
}

flexTreeMarker (ALPHA)

Indicates that an object is a flex tree.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

flexTreeMarker: unique symbol

forbiddenFieldKindIdentifier (ALPHA)

Identifier used for the FieldKind for fields which must be empty.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

forbiddenFieldKindIdentifier = "Forbidden"

Remarks

This mainly show up in: 1. The root default field for documents. 2. The schema used for out of schema fields (which thus must be empty/not exist) on object and leaf nodes.

leaf (ALPHA)

Built-in LeafNodeSchema .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

leaf: {
    number: import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.number", ValueSchema.Number>;
    boolean: import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.boolean", ValueSchema.Boolean>;
    string: import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.string", ValueSchema.String>;
    handle: import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.handle", ValueSchema.FluidHandle>;
    null: import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.null", ValueSchema.Null>;
    primitives: readonly [import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.number", ValueSchema.Number>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.boolean", ValueSchema.Boolean>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.string", ValueSchema.String>];
    all: readonly [import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.handle", ValueSchema.FluidHandle>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.null", ValueSchema.Null>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.number", ValueSchema.Number>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.boolean", ValueSchema.Boolean>, import("../feature-libraries").LeafNodeSchema<"com.fluidframework.leaf.string", ValueSchema.String>];
    library: import("../feature-libraries").SchemaLibrary;
}

nodeKeyFieldKey (ALPHA)

The key for the special field for LocalNodeKey s, which allows nodes to be given keys that can be used to find the nodes via the node key index.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

nodeKeyFieldKey = "__n_id__"

noopValidator (ALPHA)

A JsonValidator implementation which performs no validation and accepts all data as valid.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

noopValidator: JsonValidator

rootField (ALPHA)

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

rootField: DetachedField

rootFieldKey (ALPHA)

FieldKey to use for the root of documents in places that need to refer to detached sequences or the root. TODO: if we do want to standardize on a single value for this, it likely should be namespaced or a UUID to avoid risk of collisions.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

rootFieldKey: FieldKey

test_RecursiveObject_base (ALPHA)

To make API-Extractor happy, the base type has to be exported in addition to the actual schema class. Ideally this would be inlined into the class definition below.

TODO: Fix API-Extractor to support class based schema, and remove this workaround (inline this type into RecursiveObject extends below). Error: src/class-tree/testRecursiveDomain.ts:32:1 - (ae-forgotten-export) The symbol “RecursiveObject_base” needs to be exported by the entry point index.d.ts See https://github.com/microsoft/rushstack/issues/4429

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

base: import("./schemaTypes").TreeNodeSchemaClass<"Test Recursive Domain.testObject", _dummy.Object, import("./schemaTypes").ObjectFromSchemaRecord<{
    readonly recursive: import("./schemaTypes").FieldSchema<import("./schemaTypes").FieldKind.Optional, readonly [() => typeof RecursiveObject]>;
    readonly number: import("./schemaTypes").TreeNodeSchema<"com.fluidframework.leaf.number", _dummy.Leaf, number, number>;
}>, import("./schemaTypes").InsertableObjectFromSchemaRecord<{
    readonly recursive: import("./schemaTypes").FieldSchema<import("./schemaTypes").FieldKind.Optional, readonly [() => typeof RecursiveObject]>;
    readonly number: import("./schemaTypes").TreeNodeSchema<"com.fluidframework.leaf.number", _dummy.Leaf, number, number>;
}>>

Tree (BETA)

The Tree object holds various functions for analyzing NodeBase s.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

nodeApi: TreeApi

TreeListNode (BETA)

A NodeBase which implements ‘readonly T[]’ and the list mutation APIs.

WARNING: This API is provided as a beta preview and may change without notice. Use at your own risk.

Signature

TreeListNode: {
    inline: <T>(content: Iterable<T>) => IterableTreeListContent<T>;
}

typeboxValidator (ALPHA)

A JsonValidator implementation which uses TypeBox’s JSON schema validator.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

typeboxValidator: JsonValidator

typeNameSymbol (ALPHA)

A symbol for the name of the type of a tree in contexts where string keys are already in use for fields. See TreeNodeSchemaIdentifier .

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

typeNameSymbol: unique symbol

valueSymbol (ALPHA)

A symbol for the value of a tree node in contexts where string keys are already in use for fields.

WARNING: This API is provided as an alpha preview and may change without notice. Use at your own risk.

Signature

valueSymbol: unique symbol