fluid-framework 2.0.0-dev-rc.3.0.0.254513 → 2.0.0-dev-rc.3.0.0.254674

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2326 +0,0 @@
1
- /**
2
- * Bundles a collection of Fluid Framework client libraries for easy use when paired with a corresponding service client
3
- * package (e.g. `@fluidframework/azure-client`, `@fluidframework/tinylicious-client`, or `@fluid-experimental/osdp-client (BETA)`).
4
- *
5
- * @packageDocumentation
6
- */
7
-
8
- import { FluidObject } from '@fluidframework/core-interfaces';
9
- import { IChannel } from '@fluidframework/datastore-definitions';
10
- import type { IErrorBase } from '@fluidframework/core-interfaces';
11
- import { IEvent } from '@fluidframework/core-interfaces';
12
- import { IEventProvider } from '@fluidframework/core-interfaces';
13
- import { IEventThisPlaceHolder } from '@fluidframework/core-interfaces';
14
- import { IFluidHandle } from '@fluidframework/core-interfaces';
15
- import { IFluidLoadable } from '@fluidframework/core-interfaces';
16
- import { ISharedObject } from '@fluidframework/shared-object-base';
17
- import { ISharedObjectEvents } from '@fluidframework/shared-object-base';
18
- import { ISharedObjectKind } from '@fluidframework/shared-object-base';
19
-
20
- /**
21
- * Types for use in fields.
22
- * @public
23
- */
24
- export declare type AllowedTypes = readonly LazyItem<TreeNodeSchema>[];
25
-
26
- /**
27
- * Suitable for output.
28
- * For input must error on side of excluding undefined instead.
29
- * @public
30
- */
31
- export declare type ApplyKind<T, Kind extends FieldKind> = Kind extends FieldKind.Required ? T : undefined | T;
32
-
33
- /**
34
- * The attachment state of some Fluid data (e.g. a container or data store), denoting whether it is uploaded to the
35
- * service. The transition from detached to attached state is a one-way transition.
36
- * @public
37
- */
38
- export declare enum AttachState {
39
- /**
40
- * In detached state, the data is only present on the local client's machine. It has not yet been uploaded
41
- * to the service.
42
- */
43
- Detached = "Detached",
44
- /**
45
- * In attaching state, the data has started the upload to the service, but has not yet completed.
46
- */
47
- Attaching = "Attaching",
48
- /**
49
- * In attached state, the data has completed upload to the service. It can be accessed by other clients after
50
- * reaching attached state.
51
- */
52
- Attached = "Attached"
53
- }
54
-
55
- /**
56
- * The type of a commit. This is used to describe the context in which the commit was created.
57
- *
58
- * @public
59
- */
60
- export declare enum CommitKind {
61
- /** A commit corresponding to a change that is not the result of an undo/redo. */
62
- Default = 0,
63
- /** A commit that is the result of an undo. */
64
- Undo = 1,
65
- /** A commit that is the result of a redo. */
66
- Redo = 2
67
- }
68
-
69
- /**
70
- * Information about a commit that has been applied.
71
- *
72
- * @public
73
- */
74
- export declare interface CommitMetadata {
75
- /**
76
- * A {@link CommitKind} enum value describing whether the commit represents an Edit, an Undo, or a Redo.
77
- */
78
- readonly kind: CommitKind;
79
- /**
80
- * Indicates whether the commit is a local edit
81
- */
82
- readonly isLocal: boolean;
83
- }
84
-
85
- /**
86
- * The state of the Container's connection to the service.
87
- * @public
88
- */
89
- export declare enum ConnectionState {
90
- /**
91
- * The container is not connected to the ordering service
92
- * Note - When in this state the container may be about to reconnect,
93
- * or may remain disconnected until explicitly told to connect.
94
- */
95
- Disconnected = 0,
96
- /**
97
- * The container is disconnected but actively trying to establish a new connection
98
- * PLEASE NOTE that this numerical value falls out of the order you may expect for this state
99
- */
100
- EstablishingConnection = 3,
101
- /**
102
- * The container has an inbound connection only, and is catching up to the latest known state from the service.
103
- */
104
- CatchingUp = 1,
105
- /**
106
- * The container is fully connected and syncing
107
- */
108
- Connected = 2
109
- }
110
-
111
- /**
112
- * Namespace for the different connection states a container can be in.
113
- * PLEASE NOTE: The sequence of the numerical values does no correspond to the typical connection state progression.
114
- * @public
115
- */
116
- export declare namespace ConnectionStateType {
117
- /**
118
- * The container is not connected to the delta server.
119
- * Note - When in this state the container may be about to reconnect,
120
- * or may remain disconnected until explicitly told to connect.
121
- * @public
122
- */
123
- export type Disconnected = 0;
124
- /**
125
- * The container is disconnected but actively trying to establish a new connection.
126
- * PLEASE NOTE that this numerical value falls out of the order you may expect for this state.
127
- * @public
128
- */
129
- export type EstablishingConnection = 3;
130
- /**
131
- * The container has an inbound connection only, and is catching up to the latest known state from the service.
132
- * @public
133
- */
134
- export type CatchingUp = 1;
135
- /**
136
- * The container is fully connected and syncing.
137
- * @public
138
- */
139
- export type Connected = 2;
140
- }
141
-
142
- /**
143
- * Type defining the different states of connectivity a Container can be in.
144
- * @public
145
- */
146
- export declare type ConnectionStateType = ConnectionStateType.Disconnected | ConnectionStateType.EstablishingConnection | ConnectionStateType.CatchingUp | ConnectionStateType.Connected;
147
-
148
- /**
149
- * Represents properties that can be attached to a container.
150
- * @public
151
- */
152
- export declare type ContainerAttachProps<T = unknown> = T;
153
-
154
- /**
155
- * Different error types the ClientSession may report out to the Host.
156
- * @alpha
157
- */
158
- export declare const ContainerErrorTypes: {
159
- /**
160
- * Error indicating an client session has expired. Currently this only happens when GC is allowed on a document and
161
- * aids in safely deleting unused objects.
162
- */
163
- readonly clientSessionExpiredError: "clientSessionExpiredError";
164
- readonly genericError: "genericError";
165
- readonly throttlingError: "throttlingError";
166
- readonly dataCorruptionError: "dataCorruptionError";
167
- readonly dataProcessingError: "dataProcessingError";
168
- readonly usageError: "usageError";
169
- };
170
-
171
- /**
172
- * {@inheritDoc (ContainerErrorTypes:variable)}
173
- * @alpha
174
- */
175
- export declare type ContainerErrorTypes = (typeof ContainerErrorTypes)[keyof typeof ContainerErrorTypes];
176
-
177
- /**
178
- * Declares the Fluid objects that will be available in the {@link IFluidContainer | Container}.
179
- *
180
- * @remarks
181
- *
182
- * It includes both the instances of objects that are initially available upon `Container` creation, as well
183
- * as the types of objects that may be dynamically created throughout the lifetime of the `Container`.
184
- * @public
185
- */
186
- export declare interface ContainerSchema {
187
- /**
188
- * Defines loadable objects that will be created when the {@link IFluidContainer | Container} is first created.
189
- *
190
- * @remarks It uses the key as the id and the value as the loadable object to create.
191
- *
192
- * @example
193
- *
194
- * In the example below two objects will be created when the `Container` is first
195
- * created. One with id "map1" that will return a `SharedMap` and the other with
196
- * id "pair1" that will return a `KeyValueDataObject`.
197
- *
198
- * ```typescript
199
- * {
200
- * map1: SharedMap,
201
- * pair1: KeyValueDataObject,
202
- * }
203
- * ```
204
- */
205
- readonly initialObjects: LoadableObjectClassRecord;
206
- /**
207
- * Loadable objects that can be created after the initial {@link IFluidContainer | Container} creation.
208
- *
209
- * @remarks
210
- *
211
- * Types defined in `initialObjects` will always be available and are not required to be provided here.
212
- *
213
- * For best practice it's recommended to define all the dynamic types you create even if they are
214
- * included via initialObjects.
215
- */
216
- readonly dynamicObjectTypes?: readonly LoadableObjectClass[];
217
- }
218
-
219
- /**
220
- * A class that has a factory that can create a `DataObject` and a
221
- * constructor that will return the type of the `DataObject`.
222
- *
223
- * @typeParam T - The class of the `DataObject`.
224
- * @privateRemarks
225
- * Having both `factory` and `LoadableObjectCtor` is redundant, and having `factory` not actually work as a factory is also strange.
226
- * This may need some refinement.
227
- * @public
228
- */
229
- export declare type DataObjectClass<T extends IFluidLoadable = IFluidLoadable> = {
230
- readonly factory: {
231
- readonly IFluidDataStoreFactory: DataObjectClass<T>["factory"];
232
- };
233
- } & (new (...args: any[]) => T);
234
-
235
- /**
236
- * Placeholder for `Symbol.dispose`.
237
- *
238
- * Replace this with `Symbol.dispose` when it is available.
239
- * @public
240
- */
241
- export declare const disposeSymbol: unique symbol;
242
-
243
- /**
244
- * Different error types the Driver may report out to the Host.
245
- * @public
246
- */
247
- export declare const DriverErrorTypes: {
248
- /**
249
- * Some non-categorized (below) networking error
250
- * Include errors like fatal server error (usually 500).
251
- */
252
- readonly genericNetworkError: "genericNetworkError";
253
- /**
254
- * Access denied - user does not have enough privileges to open a file, or continue to operate on a file
255
- */
256
- readonly authorizationError: "authorizationError";
257
- /**
258
- * File not found, or file deleted during session
259
- */
260
- readonly fileNotFoundOrAccessDeniedError: "fileNotFoundOrAccessDeniedError";
261
- /**
262
- * We can not reach server due to computer being offline.
263
- */
264
- readonly offlineError: "offlineError";
265
- readonly unsupportedClientProtocolVersion: "unsupportedClientProtocolVersion";
266
- /**
267
- * User does not have write permissions to a file, but is changing content of a file.
268
- * That might be indication of some data store error - data stores should not generate ops in readonly mode.
269
- */
270
- readonly writeError: "writeError";
271
- /**
272
- * A generic fetch failure that indicates we were not able to get a response from the server.
273
- * This may be due to the client being offline (though, if we are able to detect offline state it will be
274
- * logged as an offlineError instead). Other possibilities could be DNS errors, malformed fetch request,
275
- * CSP violation, etc.
276
- */
277
- readonly fetchFailure: "fetchFailure";
278
- /**
279
- * This error occurs when token provider fails to fetch orderer token
280
- */
281
- readonly fetchTokenError: "fetchTokenError";
282
- /**
283
- * Unexpected response from server. Either JSON is malformed, or some required properties are missing
284
- */
285
- readonly incorrectServerResponse: "incorrectServerResponse";
286
- /**
287
- * This error occurs when the file is modified externally (not through Fluid protocol) in storage.
288
- * It will occur in cases where client has some state or cache that is based on old content (identity) of a file,
289
- * and storage / driver / loader detects such mismatch.
290
- * When it's hit, client needs to forget all the knowledge about this file and start over.
291
- */
292
- readonly fileOverwrittenInStorage: "fileOverwrittenInStorage";
293
- /**
294
- * The document is read-only and delta stream connection is forbidden.
295
- */
296
- readonly deltaStreamConnectionForbidden: "deltaStreamConnectionForbidden";
297
- /**
298
- * The location of file/container can change on server. So if the file location moves and we try to access the old
299
- * location, then this error is thrown to let the client know about the new location info.
300
- */
301
- readonly locationRedirection: "locationRedirection";
302
- /**
303
- * When a file is not a Fluid file, but has Fluid extension such as ".note",
304
- * server won't be able to open it and will return this error. The innerMostErrorCode will be
305
- * "fluidInvalidSchema"
306
- */
307
- readonly fluidInvalidSchema: "fluidInvalidSchema";
308
- /**
309
- * File is locked for read/write by storage, e.g. whole collection is locked and access denied.
310
- */
311
- readonly fileIsLocked: "fileIsLocked";
312
- /**
313
- * Storage is out of space
314
- */
315
- readonly outOfStorageError: "outOfStorageError";
316
- readonly genericError: "genericError";
317
- readonly throttlingError: "throttlingError";
318
- readonly usageError: "usageError";
319
- };
320
-
321
- /**
322
- * {@inheritDoc (DriverErrorTypes:variable)}
323
- * @public
324
- */
325
- export declare type DriverErrorTypes = (typeof DriverErrorTypes)[keyof typeof DriverErrorTypes];
326
-
327
- /**
328
- * Used to specify the kinds of events emitted by an {@link ISubscribable}.
329
- *
330
- * @remarks
331
- *
332
- * Any object type is a valid {@link Events}, but only the event-like properties of that
333
- * type will be included.
334
- *
335
- * @example
336
- *
337
- * ```typescript
338
- * interface MyEvents {
339
- * load: (user: string, data: IUserData) => void;
340
- * error: (errorCode: number) => void;
341
- * }
342
- * ```
343
- *
344
- * @public
345
- */
346
- export declare type Events<E> = {
347
- [P in (string | symbol) & keyof E as IsEvent<E[P]> extends true ? P : never]: E[P];
348
- };
349
-
350
- /**
351
- * Get the `Item` type from a `LazyItem<Item>`.
352
- * @public
353
- */
354
- export declare type ExtractItemType<Item extends LazyItem> = Item extends () => infer Result ? Result : Item;
355
-
356
- /**
357
- * Kind of a field on a node.
358
- * @public
359
- */
360
- export declare enum FieldKind {
361
- /**
362
- * A field which can be empty or filled.
363
- * @remarks
364
- * Allows 0 or one child.
365
- */
366
- Optional = 0,
367
- /**
368
- * A field which must always be filled.
369
- * @remarks
370
- * Only allows exactly one child.
371
- */
372
- Required = 1,
373
- /**
374
- * A special field used for node identifiers.
375
- * @remarks
376
- * Only allows exactly one child.
377
- */
378
- Identifier = 2
379
- }
380
-
381
- /**
382
- * Additional information to provide to a {@link FieldSchema}.
383
- *
384
- * @public
385
- */
386
- export declare interface FieldProps {
387
- /**
388
- * The unique identifier of a field, used in the persisted form of the tree.
389
- *
390
- * @remarks
391
- * If not explicitly set via the schema, this is the same as the schema's property key.
392
- *
393
- * Specifying a stored key that differs from the property key is particularly useful in refactoring scenarios.
394
- * To update the developer-facing API, while maintaining backwards compatibility with existing SharedTree data,
395
- * you can change the property key and specify the previous property key as the stored key.
396
- *
397
- * Notes:
398
- *
399
- * - Stored keys have no impact on standard JavaScript behavior, on tree nodes. For example, `Object.keys`
400
- * will always return the property keys specified in the schema, ignoring any stored keys that differ from
401
- * the property keys.
402
- *
403
- * - When specifying stored keys in an object schema, you must ensure that the final set of stored keys
404
- * (accounting for those implicitly derived from property keys) contains no duplicates.
405
- * This is validated at runtime.
406
- *
407
- * @example Refactoring code without breaking compatibility with existing data
408
- *
409
- * Consider some existing object schema:
410
- *
411
- * ```TypeScript
412
- * class Point extends schemaFactory.object("Point", {
413
- * xPosition: schemaFactory.number,
414
- * yPosition: schemaFactory.number,
415
- * zPosition: schemaFactory.optional(schemaFactory.number),
416
- * });
417
- * ```
418
- *
419
- * Developers using nodes of this type would access the the `xPosition` property as `point.xPosition`.
420
- *
421
- * We would like to refactor the schema to omit "Position" from the property keys, but application data has
422
- * already been persisted using the original property keys. To maintain compatibility with existing data,
423
- * we can refactor the schema as follows:
424
- *
425
- * ```TypeScript
426
- * class Point extends schemaFactory.object("Point", {
427
- * x: schemaFactory.required(schemaFactory.number, { key: "xPosition" }),
428
- * y: schemaFactory.required(schemaFactory.number, { key: "yPosition" }),
429
- * z: schemaFactory.optional(schemaFactory.number, { key: "zPosition" }),
430
- * });
431
- * ```
432
- *
433
- * Now, developers can access the `x` property as `point.x`, while existing data can still be collaborated on.
434
- *
435
- * @defaultValue If not specified, the key that is persisted is the property key that was specified in the schema.
436
- */
437
- readonly key?: string;
438
- }
439
-
440
- /**
441
- * All policy for a specific field,
442
- * including functionality that does not have to be kept consistent across versions or deterministic.
443
- *
444
- * This can include policy for how to use this schema for "view" purposes, and well as how to expose editing APIs.
445
- * @sealed @public
446
- */
447
- export declare class FieldSchema<out Kind extends FieldKind = FieldKind, out Types extends ImplicitAllowedTypes = ImplicitAllowedTypes> {
448
- /**
449
- * The {@link https://en.wikipedia.org/wiki/Kind_(type_theory) | kind } of this field.
450
- * Determines the multiplicity, viewing and editing APIs as well as the merge resolution policy.
451
- */
452
- readonly kind: Kind;
453
- /**
454
- * What types of tree nodes are allowed in this field.
455
- */
456
- readonly allowedTypes: Types;
457
- /**
458
- * Optional properties associated with the field.
459
- */
460
- readonly props?: FieldProps | undefined;
461
- /**
462
- * This class is used with instanceof, and therefore should have nominal typing.
463
- * This field enforces that.
464
- */
465
- protected _typeCheck?: MakeNominal;
466
- private readonly lazyTypes;
467
- /**
468
- * What types of tree nodes are allowed in this field.
469
- * @remarks Counterpart to {@link FieldSchema.allowedTypes}, with any lazy definitions evaluated.
470
- */
471
- get allowedTypeSet(): ReadonlySet<TreeNodeSchema>;
472
- constructor(
473
- /**
474
- * The {@link https://en.wikipedia.org/wiki/Kind_(type_theory) | kind } of this field.
475
- * Determines the multiplicity, viewing and editing APIs as well as the merge resolution policy.
476
- */
477
- kind: Kind,
478
- /**
479
- * What types of tree nodes are allowed in this field.
480
- */
481
- allowedTypes: Types,
482
- /**
483
- * Optional properties associated with the field.
484
- */
485
- props?: FieldProps | undefined);
486
- }
487
-
488
- /**
489
- * A flexible way to list values.
490
- * Each item in the list can either be an "eager" **value** or a "lazy" **function that returns a value** (the latter allows cyclic references to work).
491
- * @privateRemarks
492
- * By default, items that are of type `"function"` will be considered lazy and all other items will be considered eager.
493
- * To force a `"function"` item to be treated as an eager item, call `markEager` before putting it in the list.
494
- * This is necessary e.g. when the eager list items are function types and the lazy items are functions that _return_ function types.
495
- * `FlexList`s are processed by `normalizeFlexList` and `normalizeFlexListEager`.
496
- * @public
497
- */
498
- export declare type FlexList<Item = unknown> = readonly LazyItem<Item>[];
499
-
500
- /**
501
- * Normalize FlexList type to a union.
502
- * @public
503
- */
504
- export declare type FlexListToUnion<TList extends FlexList> = ExtractItemType<TList[number]>;
505
-
506
- /**
507
- * Base interface for information for each connection made to the Fluid session.
508
- *
509
- * @remarks This interface can be extended to provide additional information specific to each service.
510
- * @public
511
- */
512
- export declare interface IConnection {
513
- /**
514
- * A unique ID for the connection. A single user may have multiple connections, each with a different ID.
515
- */
516
- readonly id: string;
517
- /**
518
- * Whether the connection is in read or read/write mode.
519
- */
520
- readonly mode: "write" | "read";
521
- }
522
-
523
- /**
524
- * Represents errors raised on container.
525
- *
526
- * @see
527
- *
528
- * The following are commonly thrown error types, but `errorType` could be any string.
529
- *
530
- * - {@link @fluidframework/core-interfaces#ContainerErrorTypes}
531
- *
532
- * - {@link @fluidframework/driver-definitions#DriverErrorTypes}
533
- *
534
- * - {@link @fluidframework/odsp-driver-definitions#OdspErrorTypes}
535
- *
536
- * - {@link @fluidframework/routerlicious-driver#RouterliciousErrorType}
537
- * @public
538
- */
539
- export declare type ICriticalContainerError = IErrorBase;
540
-
541
- /**
542
- * An object with an explicit lifetime that can be ended.
543
- * @privateRemarks
544
- * TODO: align this with core-utils/IDisposable and {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html#using-declarations-and-explicit-resource-management| TypeScript's Disposable}.
545
- * @public
546
- */
547
- export declare interface IDisposable {
548
- /**
549
- * Call to end the lifetime of this object.
550
- *
551
- * It is invalid to use this object after this,
552
- * except for operations which explicitly document they are valid after disposal.
553
- *
554
- * @remarks
555
- * May cleanup resources retained by this object.
556
- * Often includes un-registering from events and thus preventing other objects from retaining a reference to this indefinably.
557
- *
558
- * Usually the only operations allowed after disposal are querying if an object is already disposed,
559
- * but this can vary between implementations.
560
- */
561
- [disposeSymbol](): void;
562
- }
563
-
564
- /**
565
- * Provides an entrypoint into the client side of collaborative Fluid data.
566
- * Provides access to the data as well as status on the collaboration session.
567
- *
568
- * @typeparam TContainerSchema - Used to determine the type of 'initialObjects'.
569
- *
570
- * @remarks Note: external implementations of this interface are not supported.
571
- *
572
- * @sealed
573
- * @public
574
- */
575
- export declare interface IFluidContainer<TContainerSchema extends ContainerSchema = ContainerSchema> extends IEventProvider<IFluidContainerEvents> {
576
- /**
577
- * Provides the current connected state of the container
578
- */
579
- readonly connectionState: ConnectionStateType;
580
- /**
581
- * A container is considered **dirty** if it has local changes that have not yet been acknowledged by the service.
582
- *
583
- * @remarks
584
- *
585
- * You should always check the `isDirty` flag before closing the container or navigating away from the page.
586
- * Closing the container while `isDirty === true` may result in the loss of operations that have not yet been
587
- * acknowledged by the service.
588
- *
589
- * A container is considered dirty in the following cases:
590
- *
591
- * 1. The container has been created in the detached state, and either it has not been attached yet or it is
592
- * in the process of being attached (container is in `attaching` state). If container is closed prior to being
593
- * attached, host may never know if the file was created or not.
594
- *
595
- * 2. The container was attached, but it has local changes that have not yet been saved to service endpoint.
596
- * This occurs as part of normal op flow where pending operation (changes) are awaiting acknowledgement from the
597
- * service. In some cases this can be due to lack of network connection. If the network connection is down,
598
- * it needs to be restored for the pending changes to be acknowledged.
599
- */
600
- readonly isDirty: boolean;
601
- /**
602
- * Whether or not the container is disposed, which permanently disables it.
603
- */
604
- readonly disposed: boolean;
605
- /**
606
- * The collection of data objects and Distributed Data Stores (DDSes) that were specified by the schema.
607
- *
608
- * @remarks These data objects and DDSes exist for the lifetime of the container.
609
- */
610
- readonly initialObjects: InitialObjects<TContainerSchema>;
611
- /**
612
- * The current attachment state of the container.
613
- *
614
- * @remarks
615
- *
616
- * Once a container has been attached, it remains attached.
617
- * When loading an existing container, it will already be attached.
618
- */
619
- readonly attachState: AttachState;
620
- /**
621
- * A newly created container starts detached from the collaborative service.
622
- * Calling `attach()` uploads the new container to the service and connects to the collaborative service.
623
- *
624
- * @remarks
625
- *
626
- * This should only be called when the container is in the
627
- * {@link @fluidframework/container-definitions#AttachState.Detatched} state.
628
- *
629
- * This can be determined by observing {@link IFluidContainer.attachState}.
630
- *
631
- * @returns A promise which resolves when the attach is complete, with the string identifier of the container.
632
- */
633
- attach(props?: ContainerAttachProps): Promise<string>;
634
- /**
635
- * Attempts to connect the container to the delta stream and process operations.
636
- *
637
- * @throws Will throw an error if connection is unsuccessful.
638
- *
639
- * @remarks
640
- *
641
- * This should only be called when the container is in the
642
- * {@link @fluidframework/container-definitions#(ConnectionState:namespace).Disconnected} state.
643
- *
644
- * This can be determined by observing {@link IFluidContainer.connectionState}.
645
- */
646
- connect(): void;
647
- /**
648
- * Disconnects the container from the delta stream and stops processing operations.
649
- *
650
- * @remarks
651
- *
652
- * This should only be called when the container is in the
653
- * {@link @fluidframework/container-definitions#(ConnectionState:namespace).Connected} state.
654
- *
655
- * This can be determined by observing {@link IFluidContainer.connectionState}.
656
- */
657
- disconnect(): void;
658
- /**
659
- * Create a new data object or Distributed Data Store (DDS) of the specified type.
660
- *
661
- * @remarks
662
- *
663
- * In order to share the data object or DDS with other
664
- * collaborators and retrieve it later, store its handle in a collection like a SharedDirectory from your
665
- * initialObjects.
666
- *
667
- * @param objectClass - The class of the `DataObject` or `SharedObject` to create.
668
- *
669
- * @typeParam T - The class of the `DataObject` or `SharedObject`.
670
- */
671
- create<T extends IFluidLoadable>(objectClass: LoadableObjectClass<T>): Promise<T>;
672
- /**
673
- * Dispose of the container instance, permanently disabling it.
674
- */
675
- dispose(): void;
676
- }
677
-
678
- /**
679
- * Events emitted from {@link IFluidContainer}.
680
- *
681
- * @remarks Note: external implementations of this interface are not supported.
682
- * @sealed
683
- * @public
684
- */
685
- export declare interface IFluidContainerEvents extends IEvent {
686
- /**
687
- * Emitted when the {@link IFluidContainer} completes connecting to the Fluid service.
688
- *
689
- * @remarks Reflects connection state changes against the (delta) service acknowledging ops/edits.
690
- *
691
- * @see
692
- *
693
- * - {@link IFluidContainer.connectionState}
694
- *
695
- * - {@link IFluidContainer.connect}
696
- */
697
- (event: "connected", listener: () => void): void;
698
- /**
699
- * Emitted when the {@link IFluidContainer} becomes disconnected from the Fluid service.
700
- *
701
- * @remarks Reflects connection state changes against the (delta) service acknowledging ops/edits.
702
- *
703
- * @see
704
- *
705
- * - {@link IFluidContainer.connectionState}
706
- *
707
- * - {@link IFluidContainer.disconnect}
708
- */
709
- (event: "disconnected", listener: () => void): void;
710
- /**
711
- * Emitted when all local changes/edits have been acknowledged by the service.
712
- *
713
- * @remarks "dirty" event will be emitted when the next local change has been made.
714
- *
715
- * @see {@link IFluidContainer.isDirty}
716
- */
717
- (event: "saved", listener: () => void): void;
718
- /**
719
- * Emitted when the first local change has been made, following a "saved" event.
720
- *
721
- * @remarks "saved" event will be emitted once all local changes have been acknowledged by the service.
722
- *
723
- * @see {@link IFluidContainer.isDirty}
724
- */
725
- (event: "dirty", listener: () => void): void;
726
- /**
727
- * Emitted when the {@link IFluidContainer} is closed, which permanently disables it.
728
- *
729
- * @remarks Listener parameters:
730
- *
731
- * - `error`: If the container was closed due to error (as opposed to an explicit call to
732
- * {@link IFluidContainer.dispose}), this will contain details about the error that caused it.
733
- */
734
- (event: "disposed", listener: (error?: ICriticalContainerError) => void): any;
735
- }
736
-
737
- /**
738
- * Base interface to be implemented to fetch each service's member.
739
- *
740
- * @remarks This interface can be extended by each service to provide additional service-specific user metadata.
741
- * @public
742
- */
743
- export declare interface IMember {
744
- /**
745
- * An ID for the user, unique among each individual user connecting to the session.
746
- */
747
- readonly userId: string;
748
- /**
749
- * The set of connections the user has made, e.g. from multiple tabs or devices.
750
- */
751
- readonly connections: IConnection[];
752
- }
753
-
754
- /**
755
- * Types allowed in a field.
756
- * @remarks
757
- * Implicitly treats a single type as an array of one type.
758
- * @public
759
- */
760
- export declare type ImplicitAllowedTypes = AllowedTypes | TreeNodeSchema;
761
-
762
- /**
763
- * Schema for a field of a tree node.
764
- * @remarks
765
- * Implicitly treats {@link ImplicitAllowedTypes} as a Required field of that type.
766
- * @public
767
- */
768
- export declare type ImplicitFieldSchema = FieldSchema | ImplicitAllowedTypes;
769
-
770
- /**
771
- * Extract the type of 'initialObjects' from the given {@link ContainerSchema} type.
772
- * @public
773
- */
774
- export declare type InitialObjects<T extends ContainerSchema> = {
775
- [K in keyof T["initialObjects"]]: T["initialObjects"][K] extends LoadableObjectClass<infer TChannel> ? TChannel : never;
776
- };
777
-
778
- /**
779
- * Helper used to produce types for:
780
- *
781
- * 1. Insertable content which can be used to construct an object node.
782
- *
783
- * 2. Insertable content which is an unhydrated object node.
784
- *
785
- * 3. Union of 1 and 2.
786
- *
787
- * @privateRemarks TODO: consider separating these cases into different types.
788
- *
789
- * @public
790
- */
791
- export declare type InsertableObjectFromSchemaRecord<T extends RestrictiveReadonlyRecord<string, ImplicitFieldSchema>> = {
792
- readonly [Property in keyof T]: InsertableTreeFieldFromImplicitField<T[Property]>;
793
- };
794
-
795
- /**
796
- * Type of content that can be inserted into the tree for a field of the given schema.
797
- * @public
798
- */
799
- export declare type InsertableTreeFieldFromImplicitField<TSchema extends ImplicitFieldSchema = FieldSchema> = TSchema extends FieldSchema<infer Kind, infer Types> ? ApplyKind<InsertableTreeNodeFromImplicitAllowedTypes<Types>, Kind> : TSchema extends ImplicitAllowedTypes ? InsertableTreeNodeFromImplicitAllowedTypes<TSchema> : unknown;
800
-
801
- /**
802
- * Type of content that can be inserted into the tree for a node of the given schema.
803
- * @public
804
- */
805
- export declare type InsertableTreeNodeFromImplicitAllowedTypes<TSchema extends ImplicitAllowedTypes = TreeNodeSchema> = TSchema extends TreeNodeSchema ? InsertableTypedNode<TSchema> : TSchema extends AllowedTypes ? InsertableTypedNode<FlexListToUnion<TSchema>> : never;
806
-
807
- /**
808
- * Data which can be used as a node to be inserted.
809
- * Either an unhydrated node, or content to build a new node.
810
- * @public
811
- */
812
- export declare type InsertableTypedNode<T extends TreeNodeSchema> = (T extends {
813
- implicitlyConstructable: true;
814
- } ? NodeBuilderData<T> : never) | Unhydrated<NodeFromSchema<T>>;
815
-
816
- /**
817
- * Base interface to be implemented to fetch each service's audience.
818
- *
819
- * @remarks
820
- *
821
- * The type parameter `M` allows consumers to further extend the client object with service-specific
822
- * details about the connecting client, such as device information, environment, or a username.
823
- *
824
- * @typeParam M - A service-specific {@link IMember} type.
825
- * @public
826
- */
827
- export declare interface IServiceAudience<M extends IMember> extends IEventProvider<IServiceAudienceEvents<M>> {
828
- /**
829
- * Returns an map of all users currently in the Fluid session where key is the userId and the value is the
830
- * member object. The implementation may choose to exclude certain connections from the returned map.
831
- * E.g. ServiceAudience excludes non-interactive connections to represent only the roster of live users.
832
- */
833
- getMembers(): ReadonlyMap<string, M>;
834
- /**
835
- * Returns the current active user on this client once they are connected. Otherwise, returns undefined.
836
- */
837
- getMyself(): Myself<M> | undefined;
838
- }
839
-
840
- /**
841
- * Events that trigger when the roster of members in the Fluid session change.
842
- *
843
- * @remarks
844
- *
845
- * Only changes that would be reflected in the returned map of {@link IServiceAudience}'s
846
- * {@link IServiceAudience.getMembers} method will emit events.
847
- *
848
- * @typeParam M - A service-specific {@link IMember} implementation.
849
- * @public
850
- */
851
- export declare interface IServiceAudienceEvents<M extends IMember> extends IEvent {
852
- /**
853
- * Emitted when a {@link IMember | member}(s) are either added or removed.
854
- *
855
- * @eventProperty
856
- */
857
- (event: "membersChanged", listener: () => void): void;
858
- /**
859
- * Emitted when a {@link IMember | member} joins the audience.
860
- *
861
- * @eventProperty
862
- */
863
- (event: "memberAdded", listener: MemberChangedListener<M>): void;
864
- /**
865
- * Emitted when a {@link IMember | member} leaves the audience.
866
- *
867
- * @eventProperty
868
- */
869
- (event: "memberRemoved", listener: MemberChangedListener<M>): void;
870
- }
871
-
872
- /**
873
- * `true` iff the given type is an acceptable shape for an event
874
- * @public
875
- */
876
- export declare type IsEvent<Event> = Event extends (...args: any[]) => any ? true : false;
877
-
878
- /**
879
- * The SharedMap distributed data structure can be used to store key-value pairs. It provides the same API for setting
880
- * and retrieving values that JavaScript developers are accustomed to with the
881
- * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map | Map} built-in object.
882
- * However, the keys of a SharedMap must be strings, and the values must either be a JSON-serializable object or a
883
- * {@link @fluidframework/datastore#FluidObjectHandle}.
884
- *
885
- * For more information, including example usages, see {@link https://fluidframework.com/docs/data-structures/map/}.
886
- * @sealed
887
- * @public
888
- */
889
- export declare interface ISharedMap extends ISharedObject<ISharedMapEvents>, Map<string, any> {
890
- /**
891
- * Retrieves the given key from the map if it exists.
892
- * @param key - Key to retrieve from
893
- * @returns The stored value, or undefined if the key is not set
894
- */
895
- get<T = any>(key: string): T | undefined;
896
- /**
897
- * Sets the value stored at key to the provided value.
898
- * @param key - Key to set
899
- * @param value - Value to set
900
- * @returns The {@link ISharedMap} itself
901
- */
902
- set<T = unknown>(key: string, value: T): this;
903
- }
904
-
905
- /**
906
- * Events emitted in response to changes to the {@link ISharedMap | map} data.
907
- * @sealed
908
- * @public
909
- */
910
- export declare interface ISharedMapEvents extends ISharedObjectEvents {
911
- /**
912
- * Emitted when a key is set or deleted.
913
- *
914
- * @remarks Listener parameters:
915
- *
916
- * - `changed` - Information on the key that changed and its value prior to the change.
917
- *
918
- * - `local` - Whether the change originated from this client.
919
- *
920
- * - `target` - The {@link ISharedMap} itself.
921
- */
922
- (event: "valueChanged", listener: (changed: IValueChanged, local: boolean, target: IEventThisPlaceHolder) => void): any;
923
- /**
924
- * Emitted when the map is cleared.
925
- *
926
- * @remarks Listener parameters:
927
- *
928
- * - `local` - Whether the clear originated from this client.
929
- *
930
- * - `target` - The {@link ISharedMap} itself.
931
- */
932
- (event: "clear", listener: (local: boolean, target: IEventThisPlaceHolder) => void): any;
933
- }
934
-
935
- /**
936
- * An object which allows the registration of listeners so that subscribers can be notified when an event happens.
937
- *
938
- * `EventEmitter` can be used as a base class to implement this via extension.
939
- * @param E - All the events that this emitter supports
940
- * @example
941
- * ```ts
942
- * type MyEventEmitter = IEventEmitter<{
943
- * load: (user: string, data: IUserData) => void;
944
- * error: (errorCode: number) => void;
945
- * }>
946
- * ```
947
- * @privateRemarks
948
- * {@link createEmitter} can help implement this interface via delegation.
949
- *
950
- * @public
951
- */
952
- export declare interface ISubscribable<E extends Events<E>> {
953
- /**
954
- * Register an event listener.
955
- * @param eventName - the name of the event
956
- * @param listener - the handler to run when the event is fired by the emitter
957
- * @returns a function which will deregister the listener when run. This function has undefined behavior
958
- * if called more than once.
959
- */
960
- on<K extends keyof Events<E>>(eventName: K, listener: E[K]): () => void;
961
- }
962
-
963
- /**
964
- * Used to insert iterable content into a {@link (TreeArrayNode:interface)}.
965
- * Use {@link (TreeArrayNode:variable).spread} to create an instance of this type.
966
- * @public
967
- */
968
- export declare class IterableTreeArrayContent<T> implements Iterable<T> {
969
- private readonly content;
970
- private constructor();
971
- /**
972
- * Iterates over content for nodes to insert.
973
- */
974
- [Symbol.iterator](): Iterator<T>;
975
- }
976
-
977
- /**
978
- * Channel for a Fluid Tree DDS.
979
- * @remarks
980
- * Allows storing and collaboratively editing schema-aware hierarchial data.
981
- * @public
982
- */
983
- export declare interface ITree extends IChannel {
984
- /**
985
- * Returns a {@link TreeView} using the provided schema.
986
- * If the tree's stored schema is compatible, this will provide a schema-aware API for accessing the tree's content.
987
- * If the provided schema is incompatible with the stored data, the view will instead expose an error indicating the incompatibility.
988
- *
989
- * @remarks
990
- * If the tree is uninitialized (has no schema and no content), the tree is initialized with the `initialTree` and
991
- * view `schema` in the provided `config`.
992
- *
993
- * The tree (now known to have been initialized) has its stored schema checked against the provided view schema.
994
- *
995
- * If the schemas are compatible, the returned {@link TreeView} will expose the root with a schema-aware API based on the provided view schema.
996
- *
997
- * If the schemas are not compatible, the view will indicate the error.
998
- *
999
- * Note that other clients can modify the document at any time, causing the view to enter or leave this error state: see {@link TreeView.events} for how to handle invalidation in these cases.
1000
- *
1001
- * Only one schematized view may exist for a given ITree at a time.
1002
- * If creating a second, the first must be disposed before calling `schematize` again.
1003
- *
1004
- * @privateRemarks
1005
- * TODO: Provide a way to make a generic view schema for any document.
1006
- * TODO: Support adapters for handling out-of-schema data.
1007
- *
1008
- * Doing initialization here allows a small API that is hard to use incorrectly.
1009
- * Other approaches tend to have easy-to-make mistakes.
1010
- * For example, having a separate initialization function means apps can forget to call it, making an app that can only open existing documents,
1011
- * or call it unconditionally leaving an app that can only create new documents.
1012
- * It also would require the schema to be passed into separate places and could cause issues if they didn't match.
1013
- * Since the initialization function couldn't return a typed tree, the type checking wouldn't help catch that.
1014
- * Also, if an app manages to create a document, but the initialization fails to get persisted, an app that only calls the initialization function
1015
- * on the create code-path (for example how a schematized factory might do it),
1016
- * would leave the document in an unusable state which could not be repaired when it is reopened (by the same or other clients).
1017
- * Additionally, once out of schema content adapters are properly supported (with lazy document updates),
1018
- * this initialization could become just another out of schema content adapter and this initialization is no longer a special case.
1019
- */
1020
- schematize<TRoot extends ImplicitFieldSchema>(config: TreeConfiguration<TRoot>): TreeView<TRoot>;
1021
- }
1022
-
1023
- /**
1024
- * Type of "valueChanged" event parameter.
1025
- * @sealed
1026
- * @public
1027
- */
1028
- export declare interface IValueChanged {
1029
- /**
1030
- * The key storing the value that changed.
1031
- */
1032
- readonly key: string;
1033
- /**
1034
- * The value that was stored at the key prior to the change.
1035
- */
1036
- readonly previousValue: any;
1037
- }
1038
-
1039
- /**
1040
- * An "eager" or "lazy" Item in a `FlexList`.
1041
- * Lazy items are wrapped in a function to allow referring to themselves before they are declared.
1042
- * This makes recursive and co-recursive items possible.
1043
- * @public
1044
- */
1045
- export declare type LazyItem<Item = unknown> = Item | (() => Item);
1046
-
1047
- /**
1048
- * A class object of `DataObject` or `SharedObject`.
1049
- *
1050
- * @typeParam T - The class of the `DataObject` or `SharedObject`.
1051
- * @public
1052
- *
1053
- * @privateRemarks
1054
- * There are some edge cases in TypeScript where the order of the members in a union matter.
1055
- * Once such edge case is when multiple members of a generic union partially match, and the type parameter is being inferred.
1056
- * In this case, its better to have the desired match and/or the simpler type first.
1057
- * In this case placing ISharedObjectKind fixed one usage and didn't break anything, and generally seems more likely to work than the reverse, so this is the order being used.
1058
- * This is likely (a bug in TypeScript)[https://github.com/microsoft/TypeScript/issues/45809].
1059
- */
1060
- export declare type LoadableObjectClass<T extends IFluidLoadable = IFluidLoadable> = ISharedObjectKind<T> | DataObjectClass<T>;
1061
-
1062
- /**
1063
- * A mapping of string identifiers to classes that will later be used to instantiate a corresponding `DataObject`
1064
- * or `SharedObject`.
1065
- * @public
1066
- */
1067
- export declare type LoadableObjectClassRecord = Record<string, LoadableObjectClass>;
1068
-
1069
- /**
1070
- * Utilities for manipulating the typescript typechecker.
1071
- *
1072
- * @remarks
1073
- * While it appears the the variance parts of this library are made obsolete by TypeScript 4.7's explicit variance annotations,
1074
- * many cases still type check with incorrect variance even when using the explicit annotations,
1075
- * and are fixed by using the patterns in this library.
1076
- *
1077
- * TypeScript uses structural typing if there are no private or protected members,
1078
- * and variance of generic type parameters depends on their usages.
1079
- * Thus when trying to constrain code by adding extra type information,
1080
- * it often fails to actually constrain as desired, and these utilities can help with those cases.
1081
- *
1082
- * This library is designed so that the desired variance can be documented in a way that is easy to read, concise,
1083
- * and allows easy navigation to documentation explaining what is being done
1084
- * for readers who are not familiar with this library.
1085
- * Additionally it constrains the types so the undesired usage patterns will not compile,
1086
- * and will give somewhat intelligible errors.
1087
- *
1088
- * Additionally this library provides the tools needed to test that the type constraints are working as expected,
1089
- * or test any other similar typing constraints in an application.
1090
- *
1091
- * This library assumes you are compiling with --strictFunctionTypes:
1092
- * (Covariance and Contravariance is explained along with how these helpers cause it in typescript at this link)
1093
- * {@link https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-6.html#strict-function-types}.
1094
- * If compiled with a TypeScript configuration that is not strict enough for these features to work,
1095
- * the test suite should fail to build.
1096
- *
1097
- * Classes in TypeScript by default allow all assignments:
1098
- * its only though adding members that any type constraints actually get applied.
1099
- * This library provides types that can be used on a protected member of a class to add the desired constraints.
1100
- *
1101
- * Typical usages (use one field like this at the top of a class):
1102
- * ```typescript
1103
- * protected _typeCheck?: MakeNominal;
1104
- * protected _typeCheck?: Contravariant<T>;
1105
- * protected _typeCheck?: Covariant<T>;
1106
- * protected _typeCheck?: Invariant<T>;
1107
- * protected _typeCheck?: Contravariant<T> & Invariant<K>;
1108
- * ```
1109
- *
1110
- * See tests for examples.
1111
- *
1112
- * Note that all of these cause nominal typing.
1113
- * If constraints on generic type parameter variance are desired, but nominal typing is not,
1114
- * these types can be used on a public field. This case also works with interfaces.
1115
- *
1116
- * Be aware that other members of your type might apply further constraints
1117
- * (ex: you might try and write a Contravariant<T> class, but it ends up being Invariant<T> due to a field of type T).
1118
- *
1119
- * Be aware of TypeScript Bug:
1120
- * {@link https://github.com/microsoft/TypeScript/issues/36906}.
1121
- * This bug is why the fields here are protected not private.
1122
- * Note that this bug is closed as a duplicate of {@link https://github.com/microsoft/TypeScript/issues/20979}
1123
- * which was closed because fixing it would be too large of a breaking change.
1124
- * Thus we expect this bug to be part of TypeScript for the forseeable future.
1125
- */
1126
- /**
1127
- * Use this as the type of a protected field to cause a type to use nominal typing instead of structural.
1128
- *
1129
- * @remarks
1130
- * Using nominal typing in this way prevents assignment of objects which are not instances of this class to values of this class's type.
1131
- * Classes which are used with "instanceof", or are supposed to be instantiated in particular ways (not just made with object literals)
1132
- * can use this to prevent undesired assignments.
1133
- * @example
1134
- * ```typescript
1135
- * protected _typeCheck?: MakeNominal;
1136
- * ```
1137
- * @privateRemarks
1138
- * See: {@link https://dev.azure.com/intentional/intent/_wiki/wikis/NP%20Platform/7146/Nominal-vs-Structural-Types}
1139
- * @public
1140
- */
1141
- export declare interface MakeNominal {
1142
- }
1143
-
1144
- /**
1145
- * Signature for {@link IMember} change events.
1146
- *
1147
- * @param clientId - A unique identifier for the client.
1148
- * @param member - The service-specific member object for the client.
1149
- *
1150
- * @see See {@link IServiceAudienceEvents} for usage details.
1151
- * @public
1152
- */
1153
- export declare type MemberChangedListener<M extends IMember> = (clientId: string, member: M) => void;
1154
-
1155
- /**
1156
- * An extended member object that includes currentConnection
1157
- * @public
1158
- */
1159
- export declare type Myself<M extends IMember = IMember> = M & {
1160
- readonly currentConnection: string;
1161
- };
1162
-
1163
- /**
1164
- * Given a node's schema, return the corresponding object from which the node could be built.
1165
- * @privateRemarks
1166
- * Currently this assumes factory functions take exactly one argument.
1167
- * This could be changed if needed.
1168
- *
1169
- * These factory functions can also take a FlexTreeNode, but this is not exposed in the public facing types.
1170
- * @public
1171
- */
1172
- export declare type NodeBuilderData<T extends TreeNodeSchema> = T extends TreeNodeSchema<string, NodeKind, unknown, infer TBuild> ? TBuild : never;
1173
-
1174
- /**
1175
- * Takes in `TreeNodeSchema[]` and returns a TypedNode union.
1176
- * @public
1177
- */
1178
- export declare type NodeFromSchema<T extends TreeNodeSchema> = T extends TreeNodeSchema<string, NodeKind, infer TNode> ? TNode : never;
1179
-
1180
- /**
1181
- * Kind of tree node.
1182
- * @public
1183
- */
1184
- export declare enum NodeKind {
1185
- /**
1186
- * A node which serves as a map, storing children under string keys.
1187
- */
1188
- Map = 0,
1189
- /**
1190
- * A node which serves as an array, storing children in an ordered sequence.
1191
- */
1192
- Array = 1,
1193
- /**
1194
- * A node which stores a heterogenous collection of children in named fields.
1195
- * @remarks
1196
- * Each field gets its own schema.
1197
- */
1198
- Object = 2,
1199
- /**
1200
- * A node which stores a single leaf value.
1201
- */
1202
- Leaf = 3
1203
- }
1204
-
1205
- /**
1206
- * Helper used to produce types for object nodes.
1207
- * @public
1208
- */
1209
- export declare type ObjectFromSchemaRecord<T extends RestrictiveReadonlyRecord<string, ImplicitFieldSchema>> = {
1210
- -readonly [Property in keyof T]: TreeFieldFromImplicitField<T[Property]>;
1211
- };
1212
-
1213
- /**
1214
- * Alternative to the built in Record type which does not permit unexpected members,
1215
- * and is readonly.
1216
- *
1217
- * @privateRemarks
1218
- * `number` is not allowed as a key here since doing so causes the compiler to reject recursive schema.
1219
- * The cause for this is unclear, but empirically it was the case when this comment was written.
1220
- * @public
1221
- */
1222
- export declare type RestrictiveReadonlyRecord<K extends symbol | string, T> = {
1223
- readonly [P in symbol | string]: P extends K ? T : never;
1224
- };
1225
-
1226
- /**
1227
- * Allows reversion of a change made to SharedTree.
1228
- *
1229
- * @remarks
1230
- * Applications wanting to implement undo/redo support might typically maintain two stacks of Revertibles, with optional eviction policy to free up memory.
1231
- *
1232
- * @public
1233
- */
1234
- export declare interface Revertible {
1235
- /**
1236
- * The current status of the revertible.
1237
- */
1238
- readonly status: RevertibleStatus;
1239
- /**
1240
- * Reverts the associated change and disposes it.
1241
- */
1242
- revert(): void;
1243
- /**
1244
- * Reverts the associated change and optionally disposes it.
1245
- *
1246
- * @param dispose - If true, the revertible will be disposed after being reverted.
1247
- * If false, the revertible will remain valid. This can be useful for scenarios where the revert may be dropped
1248
- * due to merge conflicts, and one wants to attempt reverting again.
1249
- */
1250
- revert(dispose: boolean): void;
1251
- /**
1252
- * Disposes this revertible, allowing associated resources to be released.
1253
- */
1254
- [disposeSymbol](): void;
1255
- }
1256
-
1257
- /**
1258
- * Factory for creating a {@link Revertible}.
1259
- * Will error if invoked outside the scope of the `commitApplied` event that provides it, or if invoked multiple times.
1260
- *
1261
- * @param onRevertibleDisposed - A callback that will be invoked when the `Revertible` generated by this factory is disposed.
1262
- * This happens when the `Revertible` is disposed manually, or when the `TreeView` that the `Revertible` belongs to is disposed,
1263
- * whichever happens first.
1264
- * This is typically used to clean up any resources associated with the `Revertible` in the host application.
1265
- *
1266
- * @public
1267
- */
1268
- export declare type RevertibleFactory = (onRevertibleDisposed?: (revertible: Revertible) => void) => Revertible;
1269
-
1270
- /**
1271
- * The status of a {@link Revertible}.
1272
- *
1273
- * @public
1274
- */
1275
- export declare enum RevertibleStatus {
1276
- /** The revertible can be reverted. */
1277
- Valid = 0,
1278
- /** The revertible has been disposed. Reverting it will have no effect. */
1279
- Disposed = 1
1280
- }
1281
-
1282
- /**
1283
- * Creates various types of {@link TreeNodeSchema|schema} for {@link TreeNode}s.
1284
- *
1285
- * @typeParam TScope - Scope added as a prefix to the name of every schema produced by this factory.
1286
- * @typeParam TName - Type of names used to identify each schema produced in this factory.
1287
- * Typically this is just `string` but it is also possible to use `string` or `number` based enums if you prefer to identify your types that way.
1288
- *
1289
- * @remarks
1290
- * All schema produced by this factory get a {@link TreeNodeSchemaCore.identifier|unique identifier} by {@link ScopedSchemaName|combining} the {@link SchemaFactory.scope} with the schema's `Name`.
1291
- * The `Name` part may be explicitly provided as a parameter, or inferred as a structural combination of the provided types.
1292
- * The APIs which use this second approach, structural naming, also deduplicate all equivalent calls.
1293
- * Therefor two calls to `array(allowedTypes)` with the same allowedTypes will return the same {@link TreeNodeSchema} instance.
1294
- * On the other hand, two calls to `array(name, allowedTypes)` will always return different {@link TreeNodeSchema} instances
1295
- * and it is an error to use both in the same tree (since their identifiers are not unique).
1296
- *
1297
- * Note:
1298
- * POJO stands for Plain Old JavaScript Object.
1299
- * This means an object that works like a `{}` style object literal.
1300
- * In this case it means the prototype is `Object.prototype` and acts like a set of key value pairs (data, not methods).
1301
- * The usage below generalizes this to include array and map like objects as well.
1302
- *
1303
- * There are two ways to use these APIs:
1304
- * | | Customizable | POJO Emulation |
1305
- * | ------------------- | ------------ |--------------- |
1306
- * | Declaration | `class X extends schemaFactory.object("x", {}) {}` | `const X = schemaFactory.object("x", {}); type X = NodeFromSchema<typeof X>; `
1307
- * | Allows adding "local" (non-persisted) members | Yes. Members (including methods) can be added to class. | No. Attempting to set non-field members will error. |
1308
- * | Prototype | The user defined class | `Object.prototype`, `Map.prototype` or `Array.prototype` depending on node kind |
1309
- * | Structurally named Schema | Not Supported | Supported |
1310
- * | Explicitly named Objects | Supported | Supported |
1311
- * | Explicitly named Maps and Arrays | Supported: Both declaration approaches can be used | Not Supported |
1312
- * | node.js assert.deepEqual | Compares like class instances: equal to other nodes of the same type with the same content, including custom local fields. | Compares like plain objects: equal to plain JavaScript objects with the same fields, and other nodes with the same fields, even if the types are different. |
1313
- * | IntelliSense | Shows and links to user defined class by name: `X` | Shows internal type generation logic: `object & TreeNode & ObjectFromSchemaRecord<{}> & WithType<"test.x">` |
1314
- * | Recursion | Supported with special declaration patterns. | Unsupported: Generated d.ts files replace recursive references with `any`, breaking use of recursive schema across compilation boundaries |
1315
- *
1316
- * Note that while "POJO Emulation" nodes act a lot like POJO objects, they are not true POJO objects:
1317
- *
1318
- * - Adding new arbitrary fields will error, as well some cases of invalid edits.
1319
- *
1320
- * - They are implemented using proxies.
1321
- *
1322
- * - They have state that is not exposed via enumerable own properties, including a {@link TreeNodeSchema}.
1323
- * This makes libraries like node.js `assert.deepEqual` fail to detect differences in type.
1324
- *
1325
- * - Assigning members has side effects (in this case editing the persisted/shared tree).
1326
- *
1327
- * - Not all operations implied by the prototype will work correctly: stick to the APIs explicitly declared in the TypeScript types.
1328
- *
1329
- * @privateRemarks
1330
- * It's perfectly possible to make `POJO Emulation` mode (or even just hiding the prototype) selectable even when using the custom user class declaration syntax.
1331
- * When doing this, it's still possible to make `instanceof` perform correctly.
1332
- * Allowing (or banning) custom/out-of-schema properties on the class is also possible in both modes: it could be orthogonal.
1333
- * Also for consistency, if keeping the current approach to detecting `POJO Emulation` mode it might make sense to make explicitly named Maps and Arrays do the detection the same as how object does it.
1334
- *
1335
- * @sealed @public
1336
- */
1337
- export declare class SchemaFactory<out TScope extends string | undefined = string | undefined, TName extends number | string = string> {
1338
- readonly scope: TScope;
1339
- private readonly structuralTypes;
1340
- /**
1341
- * @param scope - Prefix appended to the identifiers of all {@link TreeNodeSchema} produced by this builder.
1342
- * Use of [Reverse domain name notation](https://en.wikipedia.org/wiki/Reverse_domain_name_notation) or a UUIDv4 is recommended to avoid collisions.
1343
- * You may opt out of using a scope by passing `undefined`, but note that this increases the risk of collisions.
1344
- */
1345
- constructor(scope: TScope);
1346
- private scoped;
1347
- /**
1348
- * {@link TreeNodeSchema} for holding a JavaScript `string`.
1349
- *
1350
- * @remarks
1351
- * Strings containing unpaired UTF-16 surrogate pair code units may not be handled correctly.
1352
- *
1353
- * These limitations come from the use of UTF-8 encoding of the strings, which requires them to be valid unicode.
1354
- * JavaScript does not make this requirement for its strings so not all possible JavaScript strings are supported.
1355
- * @privateRemarks
1356
- * TODO:
1357
- * We should be much more clear about what happens if you use problematic values.
1358
- * We should validate and/or normalize them when inserting content.
1359
- */
1360
- readonly string: TreeNodeSchema<"com.fluidframework.leaf.string", NodeKind.Leaf, string, string>;
1361
- /**
1362
- * {@link TreeNodeSchema} for holding a JavaScript `number`.
1363
- *
1364
- * @remarks
1365
- * The number is a [double-precision 64-bit binary format IEEE 754](https://en.wikipedia.org/wiki/Double-precision_floating-point_format) value, however there are some exceptions:
1366
- * - `NaN`, and the infinities are converted to `null` (and may therefore only be used where `null` is allowed by the schema).
1367
- * - `-0` may be converted to `0` in some cases.
1368
- *
1369
- * These limitations match the limitations of JSON.
1370
- * @privateRemarks
1371
- * TODO:
1372
- * We should be much more clear about what happens if you use problematic values.
1373
- * We should validate and/or normalize them when inserting content.
1374
- */
1375
- readonly number: TreeNodeSchema<"com.fluidframework.leaf.number", NodeKind.Leaf, number, number>;
1376
- /**
1377
- * {@link TreeNodeSchema} for holding a boolean.
1378
- */
1379
- readonly boolean: TreeNodeSchema<"com.fluidframework.leaf.boolean", NodeKind.Leaf, boolean, boolean>;
1380
- /**
1381
- * {@link TreeNodeSchema} for JavaScript `null`.
1382
- *
1383
- * @remarks
1384
- * There are good [reasons to avoid using null](https://www.npmjs.com/package/%40rushstack/eslint-plugin#rushstackno-new-null) in JavaScript, however sometimes it is desired.
1385
- * This {@link TreeNodeSchema} node provides the option to include nulls in trees when desired.
1386
- * Unless directly inter-operating with existing data using null, consider other approaches, like wrapping the value in an optional field, or using a more specifically named empty object node.
1387
- */
1388
- readonly null: TreeNodeSchema<"com.fluidframework.leaf.null", NodeKind.Leaf, null, null>;
1389
- /**
1390
- * {@link TreeNodeSchema} for holding an {@link @fluidframework/core-interfaces#(IFluidHandle:interface)}.
1391
- */
1392
- readonly handle: TreeNodeSchema<"com.fluidframework.leaf.handle", NodeKind.Leaf, IFluidHandle<FluidObject<unknown> & IFluidLoadable>, IFluidHandle<FluidObject<unknown> & IFluidLoadable>>;
1393
- /**
1394
- * Construct a class that provides the common parts all TreeNodeSchemaClass share.
1395
- * More specific schema extend this class.
1396
- */
1397
- private nodeSchema;
1398
- /**
1399
- * Define a {@link TreeNodeSchema} for a {@link TreeObjectNode}.
1400
- *
1401
- * @param name - Unique identifier for this schema within this factory's scope.
1402
- * @param fields - Schema for fields of the object node's schema. Defines what children can be placed under each key.
1403
- */
1404
- object<const Name extends TName, const T extends RestrictiveReadonlyRecord<string, ImplicitFieldSchema>>(name: Name, fields: T): TreeNodeSchemaClass<ScopedSchemaName<TScope, Name>, NodeKind.Object, TreeObjectNode<T, ScopedSchemaName<TScope, Name>>, object & InsertableObjectFromSchemaRecord<T>, true, T>;
1405
- /**
1406
- * Define a structurally typed {@link TreeNodeSchema} for a {@link TreeMapNode}.
1407
- *
1408
- * @remarks
1409
- * The unique identifier for this Map is defined as a function of the provided types.
1410
- * It is still scoped to this SchemaBuilder, but multiple calls with the same arguments will return the same schema object, providing somewhat structural typing.
1411
- * This does not support recursive types.
1412
- *
1413
- * If using these structurally named maps, other types in this schema builder should avoid names of the form `Map<${string}>`.
1414
- *
1415
- * @example
1416
- * The returned schema should be used as a schema directly:
1417
- * ```typescript
1418
- * const MyMap = factory.map(factory.number);
1419
- * type MyMap = NodeFromSchema<typeof MyMap>;
1420
- * ```
1421
- * Or inline:
1422
- * ```typescript
1423
- * factory.object("Foo", {myMap: factory.map(factory.number)});
1424
- * ```
1425
- * @privateRemarks
1426
- * See note on array.
1427
- */
1428
- map<const T extends TreeNodeSchema | readonly TreeNodeSchema[]>(allowedTypes: T): TreeNodeSchema<ScopedSchemaName<TScope, `Map<${string}>`>, NodeKind.Map, TreeMapNode<T> & WithType<ScopedSchemaName<TScope, `Map<${string}>`>>, Iterable<[string, InsertableTreeNodeFromImplicitAllowedTypes<T>]>, true, T>;
1429
- /**
1430
- * Define a {@link TreeNodeSchema} for a {@link TreeMapNode}.
1431
- *
1432
- * @param name - Unique identifier for this schema within this factory's scope.
1433
- *
1434
- * @example
1435
- * ```typescript
1436
- * class NamedMap extends factory.map("name", factory.number) {}
1437
- * ```
1438
- */
1439
- map<Name extends TName, const T extends ImplicitAllowedTypes>(name: Name, allowedTypes: T): TreeNodeSchemaClass<ScopedSchemaName<TScope, Name>, NodeKind.Map, TreeMapNode<T> & WithType<ScopedSchemaName<TScope, Name>>, Iterable<[string, InsertableTreeNodeFromImplicitAllowedTypes<T>]>, true, T>;
1440
- /**
1441
- * Define a {@link TreeNodeSchema} for a {@link (TreeMapNode:interface)}.
1442
- *
1443
- * @param name - Unique identifier for this schema within this factory's scope.
1444
- *
1445
- * @remarks See remarks on {@link SchemaFactory.namedArray_internal}.
1446
- */
1447
- namedMap_internal<Name extends TName | string, const T extends ImplicitAllowedTypes, const ImplicitlyConstructable extends boolean>(name: Name, allowedTypes: T, customizable: boolean, implicitlyConstructable: ImplicitlyConstructable): TreeNodeSchemaClass<ScopedSchemaName<TScope, Name>, NodeKind.Map, TreeMapNode<T> & WithType<ScopedSchemaName<TScope, Name>>, Iterable<[string, InsertableTreeNodeFromImplicitAllowedTypes<T>]>, ImplicitlyConstructable, T>;
1448
- /**
1449
- * Define a structurally typed {@link TreeNodeSchema} for a {@link (TreeArrayNode:interface)}.
1450
- *
1451
- * @remarks
1452
- * The identifier for this Array is defined as a function of the provided types.
1453
- * It is still scoped to this SchemaFactory, but multiple calls with the same arguments will return the same schema object, providing somewhat structural typing.
1454
- * This does not support recursive types.
1455
- *
1456
- * If using these structurally named arrays, other types in this schema builder should avoid names of the form `Array<${string}>`.
1457
- *
1458
- * @example
1459
- * The returned schema should be used as a schema directly:
1460
- * ```typescript
1461
- * const MyArray = factory.array(factory.number);
1462
- * type MyArray = NodeFromSchema<typeof MyArray>;
1463
- * ```
1464
- * Or inline:
1465
- * ```typescript
1466
- * factory.object("Foo", {myArray: factory.array(factory.number)});
1467
- * ```
1468
- * @privateRemarks
1469
- * The name produced at the type level here is not as specific as it could be, however doing type level sorting and escaping is a real mess.
1470
- * There are cases where not having this full type provided will be less than ideal since TypeScript's structural types.
1471
- * For example attempts to narrow unions of structural arrays by name won't work.
1472
- * Planned future changes to move to a class based schema system as well as factor function based node construction should mostly avoid these issues,
1473
- * though there may still be some problematic cases even after that work is done.
1474
- *
1475
- * The return value is a class, but its the type is intentionally not specific enough to indicate it is a class.
1476
- * This prevents callers of this from sub-classing it, which is unlikely to work well (due to the ease of accidentally giving two different calls o this different subclasses)
1477
- * when working with structural typing.
1478
- *
1479
- * {@label STRUCTURAL}
1480
- */
1481
- array<const T extends TreeNodeSchema | readonly TreeNodeSchema[]>(allowedTypes: T): TreeNodeSchema<ScopedSchemaName<TScope, `Array<${string}>`>, NodeKind.Array, TreeArrayNode<T> & WithType<ScopedSchemaName<TScope, `Array<${string}>`>>, Iterable<InsertableTreeNodeFromImplicitAllowedTypes<T>>, true, T>;
1482
- /**
1483
- * Define (and add to this library) a {@link TreeNodeSchemaClass} for a {@link (TreeArrayNode:interface)}.
1484
- *
1485
- * @param name - Unique identifier for this schema within this factory's scope.
1486
- *
1487
- * @example
1488
- * ```typescript
1489
- * class NamedArray extends factory.array("name", factory.number) {}
1490
- * ```
1491
- *
1492
- * {@label NAMED}
1493
- */
1494
- array<const Name extends TName, const T extends ImplicitAllowedTypes>(name: Name, allowedTypes: T): TreeNodeSchemaClass<ScopedSchemaName<TScope, Name>, NodeKind.Array, TreeArrayNode<T> & WithType<ScopedSchemaName<TScope, Name>>, Iterable<InsertableTreeNodeFromImplicitAllowedTypes<T>>, true, T>;
1495
- /**
1496
- * Define a {@link TreeNodeSchema} for a {@link (TreeArrayNode:interface)}.
1497
- *
1498
- * @param name - Unique identifier for this schema within this factory's scope.
1499
- *
1500
- * @remarks
1501
- * This is not intended to be used directly, use the overload of `array` which takes a name instead.
1502
- * This is only public to work around a compiler limitation.
1503
- *
1504
- * @privateRemarks
1505
- * TODO: this should be made private or protected.
1506
- * Doing so breaks due to:
1507
- * `src/class-tree/schemaFactoryRecursive.ts:42:9 - error TS2310: Type 'Array' recursively references itself as a base type.`
1508
- * Once recursive APIs are better sorted out and integrated into this class, switch this back to private.
1509
- */
1510
- namedArray_internal<Name extends TName | string, const T extends ImplicitAllowedTypes, const ImplicitlyConstructable extends boolean>(name: Name, allowedTypes: T, customizable: boolean, implicitlyConstructable: ImplicitlyConstructable): TreeNodeSchemaClass<ScopedSchemaName<TScope, Name>, NodeKind.Array, TreeArrayNode<T> & WithType<ScopedSchemaName<TScope, string>>, Iterable<InsertableTreeNodeFromImplicitAllowedTypes<T>>, ImplicitlyConstructable, T>;
1511
- /**
1512
- * Make a field optional instead of the default, which is required.
1513
- *
1514
- * @param t - The types allowed under the field.
1515
- * @param props - Optional properties to associate with the field.
1516
- */
1517
- optional<const T extends ImplicitAllowedTypes>(t: T, props?: FieldProps): FieldSchema<FieldKind.Optional, T>;
1518
- /**
1519
- * Make a field explicitly required.
1520
- *
1521
- * @param t - The types allowed under the field.
1522
- * @param props - Optional properties to associate with the field.
1523
- *
1524
- * @remarks
1525
- * Fields are required by default, but this API can be used to make the required nature explicit in the schema,
1526
- * and allows associating custom {@link FieldProps | properties} with the field.
1527
- */
1528
- required<const T extends ImplicitAllowedTypes>(t: T, props?: FieldProps): FieldSchema<FieldKind.Required, T>;
1529
- /**
1530
- * Make a field of type identifier instead of the default which is required.
1531
- */
1532
- get identifier(): FieldSchema<FieldKind.Identifier>;
1533
- /**
1534
- * Function which can be used for its compile time side-effects to tweak the evaluation order of recursive types to make them compile.
1535
- * @remarks
1536
- * Some related information in https://github.com/microsoft/TypeScript/issues/55758.
1537
- *
1538
- * Also be aware that code which relies on this tends to break VSCode's IntelliSense every time anything related to that code (even comments) is edited.
1539
- * Running the command `TypeScript: Restart TS Server` with the schema file focused should fix it.
1540
- * Sometimes this does not work: closing all open files except the schema before running the command can help.
1541
- * Real compile errors (for example elsewhere in the file) can also cause the IntelliSense to not work correctly ever after `TypeScript: Restart TS Server`.
1542
- *
1543
- * Intellisense has also shown problems when schema files with recursive types are part of a cyclic file dependency.
1544
- * Splitting the schema into its own file with minimal dependencies can help with this.
1545
- *
1546
- * Ensure `"noImplicitAny": true` is set in the `tsconfig.json`.
1547
- * Without it, recursive types that are not working properly can infer `any` and give very non-type-safe results instead of erroring.
1548
- *
1549
- * @example
1550
- * ```typescript
1551
- * const factory = new SchemaFactory("example");
1552
- * const recursiveReference = () => RecursiveObject;
1553
- * factory.fixRecursiveReference(recursiveReference);
1554
- * export class RecursiveObject extends factory.object("exampleObject", {
1555
- * recursive: [recursiveReference],
1556
- * }) {}
1557
- * ```
1558
- * @deprecated Use special `recursive` versions of builders instead of relying on this.
1559
- */
1560
- fixRecursiveReference<T extends AllowedTypes>(...types: T): void;
1561
- }
1562
-
1563
- /**
1564
- * Information about how a view schema was incompatible.
1565
- * @public
1566
- */
1567
- export declare interface SchemaIncompatible {
1568
- /**
1569
- * True iff the view schema supports all possible documents permitted by the stored schema.
1570
- *
1571
- * @remarks
1572
- * When true, this is still an error because the view schema supports more documents than the stored schema.
1573
- * This means that writes to the document using the view schema could make the document violate its stored schema.
1574
- * In this case, the stored schema could be updated to match the provided view schema, allowing read write access to the tree.
1575
- *
1576
- * Future version of SharedTree may provide readonly access to the document in this case because that would be safe:
1577
- * but this is not currently supported.
1578
- */
1579
- readonly canUpgrade: boolean;
1580
- }
1581
-
1582
- /**
1583
- * The name of a schema produced by {@link SchemaFactory}, including its optional scope prefix.
1584
- *
1585
- * @public
1586
- */
1587
- export declare type ScopedSchemaName<TScope extends string | undefined, TName extends number | string> = TScope extends undefined ? `${TName}` : `${TScope}.${TName}`;
1588
-
1589
- /**
1590
- * Entrypoint for {@link ISharedMap} creation.
1591
- * @public
1592
- * @deprecated Please use SharedTree for new containers. SharedMap is supported for loading preexisting Fluid Framework 1.0 containers only.
1593
- */
1594
- export declare const SharedMap: ISharedObjectKind<ISharedMap>;
1595
-
1596
- /**
1597
- * Entrypoint for {@link ISharedMap} creation.
1598
- * @public
1599
- * @deprecated Use ISharedMap instead.
1600
- * @privateRemarks
1601
- * This alias is for legacy compat from when the SharedMap class was exported as public.
1602
- */
1603
- export declare type SharedMap = ISharedMap;
1604
-
1605
- /**
1606
- * SharedTree is a hierarchical data structure for collaboratively editing strongly typed JSON-like trees
1607
- * of objects, arrays, and other data types.
1608
- * @public
1609
- */
1610
- export declare const SharedTree: ISharedObjectKind<ITree>;
1611
-
1612
- /**
1613
- * The `Tree` object holds various functions for interacting with {@link TreeNode}s.
1614
- * @public
1615
- */
1616
- export declare const Tree: TreeApi;
1617
-
1618
- /**
1619
- * Provides various functions for interacting with {@link TreeNode}s.
1620
- * @public
1621
- */
1622
- export declare interface TreeApi extends TreeNodeApi {
1623
- /**
1624
- * Apply one or more edits to the tree as a single atomic unit.
1625
- * @param node - The node that will be passed to `transaction`.
1626
- * This is typically the root node of the subtree that will be modified by the transaction.
1627
- * @param transaction - The function to run as the body of the transaction.
1628
- * This function is passed the provided `node`.
1629
- * At any point during the transaction, the function may return the value `"rollback"` to abort the transaction and discard any changes it made so far.
1630
- * @remarks
1631
- * All of the changes in the transaction are applied synchronously and therefore no other changes (either from this client or from a remote client) can be interleaved with those changes.
1632
- * Note that this is guaranteed by Fluid for any sequence of changes that are submitted synchronously, whether in a transaction or not.
1633
- * However, using a transaction has the following additional consequences:
1634
- * - If reverted (e.g. via an "undo" operation), all the changes in the transaction are reverted together.
1635
- * - The internal data representation of a transaction with many changes is generally smaller and more efficient than that of the changes when separate.
1636
- *
1637
- * Local change events will be emitted for each change as the transaction is being applied.
1638
- * If the transaction is cancelled and rolled back, a corresponding change event will also be emitted for the rollback.
1639
- */
1640
- runTransaction<TNode extends TreeNode>(node: TNode, transaction: (node: TNode) => void | "rollback"): void;
1641
- /**
1642
- * Apply one or more edits to the tree as a single atomic unit.
1643
- * @param tree - The tree which will be edited by the transaction
1644
- * @param transaction - The function to run as the body of the transaction.
1645
- * This function is passed the root of the tree.
1646
- * At any point during the transaction, the function may return the value `"rollback"` to abort the transaction and discard any changes it made so far.
1647
- * @remarks
1648
- * All of the changes in the transaction are applied synchronously and therefore no other changes (either from this client or from a remote client) can be interleaved with those changes.
1649
- * Note that this is guaranteed by Fluid for any sequence of changes that are submitted synchronously, whether in a transaction or not.
1650
- * However, using a transaction has the following additional consequences:
1651
- * - If reverted (e.g. via an "undo" operation), all the changes in the transaction are reverted together.
1652
- * - The internal data representation of a transaction with many changes is generally smaller and more efficient than that of the changes when separate.
1653
- *
1654
- * Local change events will be emitted for each change as the transaction is being applied.
1655
- * If the transaction is cancelled and rolled back, a corresponding change event will also be emitted for the rollback.
1656
- */
1657
- runTransaction<TView extends TreeView<ImplicitFieldSchema>>(tree: TView, transaction: (root: TView["root"]) => void | "rollback"): void;
1658
- /**
1659
- * Check if the subtree defined by `node` contains `other`.
1660
- *
1661
- * @returns true if `other` is an inclusive descendant of `node`, and false otherwise.
1662
- * @remarks
1663
- * This includes direct and indirect children:
1664
- * as long as `node` is an ancestor of `other` (occurs in its parentage chain), this returns true, regardless of the number of levels of the tree between.
1665
- *
1666
- * `node` is considered to contain itself, so the case where `node === other` returns true.
1667
- *
1668
- * This is handy when checking if moving `node` into `other` would create a cycle and thus is invalid.
1669
- *
1670
- * This check walks the parents of `other` looking for `node`,
1671
- * and thus runs in time proportional to the depth of child in the tree.
1672
- */
1673
- contains(node: TreeNode, other: TreeNode): boolean;
1674
- }
1675
-
1676
- /**
1677
- * A {@link TreeNode} which implements 'readonly T[]' and the array mutation APIs.
1678
- *
1679
- * @typeParam TAllowedTypes - Schema for types which are allowed as members of this array.
1680
- *
1681
- * @public
1682
- */
1683
- export declare interface TreeArrayNode<TAllowedTypes extends ImplicitAllowedTypes = ImplicitAllowedTypes> extends TreeArrayNodeBase<TreeNodeFromImplicitAllowedTypes<TAllowedTypes>, InsertableTreeNodeFromImplicitAllowedTypes<TAllowedTypes>, TreeArrayNode> {
1684
- }
1685
-
1686
- /**
1687
- * A {@link TreeNode} which implements 'readonly T[]' and the array mutation APIs.
1688
- * @public
1689
- */
1690
- export declare const TreeArrayNode: {
1691
- /**
1692
- * Wrap an iterable of items to inserted as consecutive items in a array.
1693
- * @remarks
1694
- * The object returned by this function can be inserted into a {@link (TreeArrayNode:interface)}.
1695
- * Its contents will be inserted consecutively in the corresponding location in the array.
1696
- * @example
1697
- * ```ts
1698
- * array.insertAtEnd(TreeArrayNode.spread(iterable))
1699
- * ```
1700
- */
1701
- spread: <T>(content: Iterable<T>) => IterableTreeArrayContent<T>;
1702
- };
1703
-
1704
- /**
1705
- * A generic array type, used to defined types like {@link (TreeArrayNode:interface)}.
1706
- *
1707
- * @privateRemarks
1708
- * Inlining this into TreeArrayNode causes recursive array use to stop compiling.
1709
- *
1710
- * @public
1711
- */
1712
- export declare interface TreeArrayNodeBase<out T, in TNew, in TMoveFrom> extends ReadonlyArray<T>, TreeNode {
1713
- /**
1714
- * Inserts new item(s) at a specified location.
1715
- * @param index - The index at which to insert `value`.
1716
- * @param value - The content to insert.
1717
- * @throws Throws if `index` is not in the range [0, `array.length`).
1718
- */
1719
- insertAt(index: number, ...value: (TNew | IterableTreeArrayContent<TNew>)[]): void;
1720
- /**
1721
- * Inserts new item(s) at the start of the array.
1722
- * @param value - The content to insert.
1723
- */
1724
- insertAtStart(...value: (TNew | IterableTreeArrayContent<TNew>)[]): void;
1725
- /**
1726
- * Inserts new item(s) at the end of the array.
1727
- * @param value - The content to insert.
1728
- */
1729
- insertAtEnd(...value: (TNew | IterableTreeArrayContent<TNew>)[]): void;
1730
- /**
1731
- * Removes the item at the specified location.
1732
- * @param index - The index at which to remove the item.
1733
- * @throws Throws if `index` is not in the range [0, `array.length`).
1734
- */
1735
- removeAt(index: number): void;
1736
- /**
1737
- * Removes all items between the specified indices.
1738
- * @param start - The starting index of the range to remove (inclusive). Defaults to the start of the array.
1739
- * @param end - The ending index of the range to remove (exclusive).
1740
- * @throws Throws if `start` is not in the range [0, `array.length`).
1741
- * @throws Throws if `end` is less than `start`.
1742
- * If `end` is not supplied or is greater than the length of the array, all items after `start` are removed.
1743
- */
1744
- removeRange(start?: number, end?: number): void;
1745
- /**
1746
- * Moves the specified item to the start of the array.
1747
- * @param sourceIndex - The index of the item to move.
1748
- * @throws Throws if `sourceIndex` is not in the range [0, `array.length`).
1749
- */
1750
- moveToStart(sourceIndex: number): void;
1751
- /**
1752
- * Moves the specified item to the start of the array.
1753
- * @param sourceIndex - The index of the item to move.
1754
- * @param source - The source array to move the item out of.
1755
- * @throws Throws if `sourceIndex` is not in the range [0, `array.length`).
1756
- */
1757
- moveToStart(sourceIndex: number, source: TMoveFrom): void;
1758
- /**
1759
- * Moves the specified item to the end of the array.
1760
- * @param sourceIndex - The index of the item to move.
1761
- * @throws Throws if `sourceIndex` is not in the range [0, `array.length`).
1762
- */
1763
- moveToEnd(sourceIndex: number): void;
1764
- /**
1765
- * Moves the specified item to the end of the array.
1766
- * @param sourceIndex - The index of the item to move.
1767
- * @param source - The source array to move the item out of.
1768
- * @throws Throws if `sourceIndex` is not in the range [0, `array.length`).
1769
- */
1770
- moveToEnd(sourceIndex: number, source: TMoveFrom): void;
1771
- /**
1772
- * Moves the specified item to the desired location in the array.
1773
- * @param index - The index to move the item to.
1774
- * This is based on the state of the array before moving the source item.
1775
- * @param sourceIndex - The index of the item to move.
1776
- * @throws Throws if any of the input indices are not in the range [0, `array.length`).
1777
- */
1778
- moveToIndex(index: number, sourceIndex: number): void;
1779
- /**
1780
- * Moves the specified item to the desired location in the array.
1781
- * @param index - The index to move the item to.
1782
- * @param sourceIndex - The index of the item to move.
1783
- * @param source - The source array to move the item out of.
1784
- * @throws Throws if any of the input indices are not in the range [0, `array.length`).
1785
- */
1786
- moveToIndex(index: number, sourceIndex: number, source: TMoveFrom): void;
1787
- /**
1788
- * Moves the specified items to the start of the array.
1789
- * @param sourceStart - The starting index of the range to move (inclusive).
1790
- * @param sourceEnd - The ending index of the range to move (exclusive)
1791
- * @throws Throws if either of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1792
- */
1793
- moveRangeToStart(sourceStart: number, sourceEnd: number): void;
1794
- /**
1795
- * Moves the specified items to the start of the array.
1796
- * @param sourceStart - The starting index of the range to move (inclusive).
1797
- * @param sourceEnd - The ending index of the range to move (exclusive)
1798
- * @param source - The source array to move items out of.
1799
- * @throws Throws if the types of any of the items being moved are not allowed in the destination array,
1800
- * if either of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1801
- */
1802
- moveRangeToStart(sourceStart: number, sourceEnd: number, source: TMoveFrom): void;
1803
- /**
1804
- * Moves the specified items to the end of the array.
1805
- * @param sourceStart - The starting index of the range to move (inclusive).
1806
- * @param sourceEnd - The ending index of the range to move (exclusive)
1807
- * @throws Throws if either of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1808
- */
1809
- moveRangeToEnd(sourceStart: number, sourceEnd: number): void;
1810
- /**
1811
- * Moves the specified items to the end of the array.
1812
- * @param sourceStart - The starting index of the range to move (inclusive).
1813
- * @param sourceEnd - The ending index of the range to move (exclusive)
1814
- * @param source - The source array to move items out of.
1815
- * @throws Throws if the types of any of the items being moved are not allowed in the destination array,
1816
- * if either of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1817
- */
1818
- moveRangeToEnd(sourceStart: number, sourceEnd: number, source: TMoveFrom): void;
1819
- /**
1820
- * Moves the specified items to the desired location within the array.
1821
- * @param index - The index to move the items to.
1822
- * This is based on the state of the array before moving the source items.
1823
- * @param sourceStart - The starting index of the range to move (inclusive).
1824
- * @param sourceEnd - The ending index of the range to move (exclusive)
1825
- * @throws Throws if any of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1826
- */
1827
- moveRangeToIndex(index: number, sourceStart: number, sourceEnd: number): void;
1828
- /**
1829
- * Moves the specified items to the desired location within the array.
1830
- * @param index - The index to move the items to.
1831
- * @param sourceStart - The starting index of the range to move (inclusive).
1832
- * @param sourceEnd - The ending index of the range to move (exclusive)
1833
- * @param source - The source array to move items out of.
1834
- * @throws Throws if the types of any of the items being moved are not allowed in the destination array,
1835
- * if any of the input indices are not in the range [0, `array.length`) or if `sourceStart` is greater than `sourceEnd`.
1836
- */
1837
- moveRangeToIndex(index: number, sourceStart: number, sourceEnd: number, source: TMoveFrom): void;
1838
- }
1839
-
1840
- /**
1841
- * A collection of events that can be raised by a {@link TreeNode}.
1842
- *
1843
- * @privateRemarks
1844
- * TODO: add a way to subscribe to a specific field (for nodeChanged and treeChanged).
1845
- * Probably have object node and map node specific APIs for this.
1846
- *
1847
- * TODO: ensure that subscription API for fields aligns with API for subscribing to the root.
1848
- *
1849
- * TODO: add more wider area (avoid needing tons of nodeChanged registration) events for use-cases other than treeChanged.
1850
- * Some ideas:
1851
- *
1852
- * - treeChanged, but with some subtrees/fields/paths excluded
1853
- * - helper to batch several nodeChanged calls to a treeChanged scope
1854
- * - parent change (ex: registration on the parent field for a specific index: maybe allow it for a range. Ex: node event takes optional field and optional index range?)
1855
- * - new content inserted into subtree. Either provide event for this and/or enough info to treeChanged to find and search the new sub-trees.
1856
- * Add separate (non event related) API to efficiently scan tree for given set of types (using low level cursor and schema based filtering)
1857
- * to allow efficiently searching for new content (and initial content) of a given type.
1858
- *
1859
- * @public
1860
- */
1861
- export declare interface TreeChangeEvents {
1862
- /**
1863
- * Emitted by a node when a batch of changes is applied to it, where a change is:
1864
- *
1865
- * - For an object node, when the value of one of its properties changes (i.e., the property's value is set
1866
- * to something else, including `undefined`).
1867
- *
1868
- * - For an array node, when an element is added, removed, or moved.
1869
- *
1870
- * - For a map node, when an entry is added, updated, or removed.
1871
- *
1872
- * @remarks
1873
- * This event is not raised when:
1874
- *
1875
- * - Properties of a child node change. Notably, updates to an array node or a map node (like adding or removing
1876
- * elements/entries) will raise this event on the array/map node itself, but not on the node that contains the
1877
- * array/map node as one of its properties.
1878
- *
1879
- * - The node is moved to a different location in the tree or removed from the tree.
1880
- * In this case the event is raised on the _parent_ node, not the node itself.
1881
- *
1882
- * For remote edits, this event is not guaranteed to occur in the same order or quantity that it did in
1883
- * the client that made the original edit.
1884
- * While a batch of edits will as a whole update the tree to the appropriate end state, no guarantees are made about
1885
- * how many times this event will be raised during any intermediate states.
1886
- * When it is raised, the tree is guaranteed to be in-schema.
1887
- *
1888
- * @privateRemarks
1889
- * This event occurs whenever the apparent contents of the node instance change, regardless of what caused the change.
1890
- * For example, it will fire when the local client reassigns a child, when part of a remote edit is applied to the
1891
- * node, or when the node has to be updated due to resolution of a merge conflict
1892
- * (for example a previously applied local change might be undone, then reapplied differently or not at all).
1893
- */
1894
- nodeChanged(): void;
1895
- /**
1896
- * Emitted by a node when something _may_ have changed anywhere in the subtree rooted at it.
1897
- *
1898
- * @remarks
1899
- * This event is guaranteed to be emitted whenever the subtree _has_ changed.
1900
- * However, it might also be emitted when the subtree has no visible changes compared to before the event firing.
1901
- *
1902
- * Consumers of this event have the guarantee that they won't miss any changes, but should also handle the scenario
1903
- * where the event fires with no visible changes as well.
1904
- *
1905
- * This event is not raised when the node itself is moved to a different location in the tree or removed from the tree.
1906
- * In that case it is raised on the _parent_ node, not the node itself.
1907
- *
1908
- * The node itself is part of the subtree, so this event will be emitted even if the only changes are to the properties
1909
- * of the node itself.
1910
- *
1911
- * For remote edits, this event is not guaranteed to occur in the same order or quantity that it did in
1912
- * the client that made the original edit.
1913
- * While a batch of edits will as a whole update the tree to the appropriate end state, no guarantees are made about
1914
- * how many times this event will be raised during any intermediate states.
1915
- * When it is raised, the tree is guaranteed to be in-schema.
1916
- */
1917
- treeChanged(): void;
1918
- }
1919
-
1920
- /**
1921
- * Configuration for how to {@link ITree.schematize|schematize} a tree.
1922
- * @public
1923
- */
1924
- export declare class TreeConfiguration<TSchema extends ImplicitFieldSchema = ImplicitFieldSchema> {
1925
- readonly schema: TSchema;
1926
- readonly initialTree: () => InsertableTreeFieldFromImplicitField<TSchema>;
1927
- /**
1928
- * @param schema - The schema which the application wants to view the tree with.
1929
- * @param initialTree - A function that returns the default tree content to initialize the tree with iff the tree is uninitialized
1930
- * (meaning it does not even have any schema set at all).
1931
- * If `initialTree` returns any actual node instances, they should be recreated each time `initialTree` runs.
1932
- * This is because if the config is used a second time any nodes that were not recreated could error since nodes cannot be inserted into the tree multiple times.
1933
- */
1934
- constructor(schema: TSchema, initialTree: () => InsertableTreeFieldFromImplicitField<TSchema>);
1935
- }
1936
-
1937
- /**
1938
- * Converts ImplicitFieldSchema to the corresponding tree node's field type.
1939
- * @public
1940
- */
1941
- export declare type TreeFieldFromImplicitField<TSchema extends ImplicitFieldSchema = FieldSchema> = TSchema extends FieldSchema<infer Kind, infer Types> ? ApplyKind<TreeNodeFromImplicitAllowedTypes<Types>, Kind> : TSchema extends ImplicitAllowedTypes ? TreeNodeFromImplicitAllowedTypes<TSchema> : unknown;
1942
-
1943
- /**
1944
- * Value that may be stored as a leaf node.
1945
- * @public
1946
- */
1947
- export declare type TreeLeafValue = number | string | boolean | IFluidHandle | null;
1948
-
1949
- /**
1950
- * A map of string keys to tree objects.
1951
- *
1952
- * @privateRemarks
1953
- * Add support for `clear` once we have established merge semantics for it.
1954
- *
1955
- * @public
1956
- */
1957
- export declare interface TreeMapNode<T extends ImplicitAllowedTypes = ImplicitAllowedTypes> extends ReadonlyMap<string, TreeNodeFromImplicitAllowedTypes<T>>, TreeNode {
1958
- /**
1959
- * Adds or updates an entry in the map with a specified `key` and a `value`.
1960
- *
1961
- * @param key - The key of the element to add to the map.
1962
- * @param value - The value of the element to add to the map.
1963
- *
1964
- * @remarks
1965
- * Setting the value at a key to `undefined` is equivalent to calling {@link TreeMapNode.delete} with that key.
1966
- */
1967
- set(key: string, value: InsertableTreeNodeFromImplicitAllowedTypes<T> | undefined): void;
1968
- /**
1969
- * Removes the specified element from this map by its `key`.
1970
- *
1971
- * @remarks
1972
- * Note: unlike JavaScript's Map API, this method does not return a flag indicating whether or not the value was
1973
- * deleted.
1974
- *
1975
- * @privateRemarks
1976
- * Regarding the choice to not return a boolean: Since this data structure is distributed in nature, it isn't
1977
- * possible to tell whether or not the item was deleted as a result of this method call. Returning a "best guess"
1978
- * is more likely to create issues / promote bad usage patterns than offer useful information.
1979
- *
1980
- * @param key - The key of the element to remove from the map.
1981
- */
1982
- delete(key: string): void;
1983
- }
1984
-
1985
- /**
1986
- * A non-leaf SharedTree node. Includes objects, arrays, and maps.
1987
- *
1988
- * @remarks
1989
- * Base type which all nodes implement.
1990
- *
1991
- * This can be used as a type to indicate/document values which should be tree nodes.
1992
- * Runtime use of this class object (for example when used with `instanceof` or subclassed), is not supported:
1993
- * it may be replaced with an interface or union in the future.
1994
- * @privateRemarks
1995
- * Future changes may replace this with a branded interface if the runtime oddities related to this are not cleaned up.
1996
- *
1997
- * Currently not all node implications include this in their prototype chain (some hide it with a proxy), and thus cause `instanceof` to fail.
1998
- * This results in the runtime and compile time behavior of `instanceof` differing.
1999
- * TypeScript 5.3 allows altering the compile time behavior of `instanceof`.
2000
- * The runtime behavior can be changed by implementing `Symbol.hasInstance`.
2001
- * One of those approaches could be used to resolve this inconsistency if TreeNode is kept as a class.
2002
- * @public
2003
- */
2004
- export declare abstract class TreeNode implements WithType {
2005
- /**
2006
- * This is added to prevent TypeScript from implicitly allowing non-TreeNode types to be used as TreeNodes.
2007
- * @privateRemarks
2008
- * This is a JavaScript private field, so is not accessible from outside this class.
2009
- * This prevents it from having name collisions with object fields.
2010
- * Since this is private, the type of this field is stripped in the d.ts file.
2011
- * To get matching type checking within and from outside the package, the least informative type (`unknown`) is used.
2012
- * To avoid this having any runtime impact, the field is uninitialized.
2013
- *
2014
- * Making this field optional results in different type checking within this project than outside of it, since the d.ts file drops the optional aspect of the field.
2015
- * This is extra confusing since sin ce the tests get in-project typing for intellisense and separate project checking at build time.
2016
- * To avoid all this mess, this field is required, not optional.
2017
- *
2018
- * Another option would be to use a symbol (possibly as a private field).
2019
- * That approach ran into some strange difficulties causing SchemaFactory to fail to compile, and was not investigated further.
2020
- *
2021
- * TODO: This is disabled due to compilation of this project not targeting es2022,
2022
- * which causes this to polyfill to use of a weak map which has some undesired runtime overhead.
2023
- * Consider enabling this for stronger typing after targeting es2022.
2024
- * The [type] symbol here provides a lot of the value this private brand would, but is not all of it:
2025
- * someone could manually make an object literal with it and pass it off as a node: this private brand would prevent that.
2026
- * Another option would be to add a protected or private symbol, which would also get the stronger typing.
2027
- */
2028
- /**
2029
- * {@inheritdoc "type"}
2030
- * @privateRemarks
2031
- * Subclasses provide more specific strings for this to get strong typing of otherwise type compatible nodes.
2032
- */
2033
- abstract get [type](): string;
2034
- }
2035
-
2036
- /**
2037
- * Provides various functions for analyzing {@link TreeNode}s.
2038
- *
2039
- * @privateRemarks
2040
- * Inlining the typing of this interface onto the `Tree` object provides slightly different .d.ts generation,
2041
- * which avoids typescript expanding the type of TreeNodeSchema and thus encountering
2042
- * https://github.com/microsoft/rushstack/issues/1958.
2043
- * @public
2044
- */
2045
- export declare interface TreeNodeApi {
2046
- /**
2047
- * The schema information for this node.
2048
- */
2049
- schema<T extends TreeNode | TreeLeafValue>(node: T): TreeNodeSchema<string, NodeKind, unknown, T>;
2050
- /**
2051
- * Narrow the type of the given value if it satisfies the given schema.
2052
- * @example
2053
- * ```ts
2054
- * if (node.is(myNode, point)) {
2055
- * const y = myNode.y; // `myNode` is now known to satisfy the `point` schema and therefore has a `y` coordinate.
2056
- * }
2057
- * ```
2058
- */
2059
- is<TSchema extends TreeNodeSchema>(value: unknown, schema: TSchema): value is NodeFromSchema<TSchema>;
2060
- /**
2061
- * Return the node under which this node resides in the tree (or undefined if this is a root node of the tree).
2062
- */
2063
- parent(node: TreeNode): TreeNode | undefined;
2064
- /**
2065
- * The key of the given node under its parent.
2066
- * @remarks
2067
- * If `node` is an element in a {@link (TreeArrayNode:interface)}, this returns the index of `node` in the array node (a `number`).
2068
- * Otherwise, this returns the key of the field that it is under (a `string`).
2069
- */
2070
- key(node: TreeNode): string | number;
2071
- /**
2072
- * Register an event listener on the given node.
2073
- * @param node - The node whose events should be subscribed to.
2074
- * @param eventName - Which event to subscribe to.
2075
- * @param listener - The callback to trigger for the event. The tree can be read during the callback, but it is invalid to modify the tree during this callback.
2076
- * @returns A callback function which will deregister the event.
2077
- * This callback should be called only once.
2078
- */
2079
- on<K extends keyof TreeChangeEvents>(node: TreeNode, eventName: K, listener: TreeChangeEvents[K]): () => void;
2080
- /**
2081
- * Returns the {@link TreeStatus} of the given node.
2082
- */
2083
- readonly status: (node: TreeNode) => TreeStatus;
2084
- /**
2085
- * If the given node has an identifier specified by a field of kind "identifier" then this returns the compressed form of that identifier.
2086
- * Otherwise returns undefined.
2087
- */
2088
- shortId(node: TreeNode): number | undefined;
2089
- }
2090
-
2091
- /**
2092
- * Type of of tree node for a field of the given schema.
2093
- * @public
2094
- */
2095
- export declare type TreeNodeFromImplicitAllowedTypes<TSchema extends ImplicitAllowedTypes = TreeNodeSchema> = TSchema extends TreeNodeSchema ? NodeFromSchema<TSchema> : TSchema extends AllowedTypes ? NodeFromSchema<FlexListToUnion<TSchema>> : unknown;
2096
-
2097
- /**
2098
- * Schema for a tree node.
2099
- * @typeParam Name - The full (including scope) name/identifier for the schema.
2100
- * @typeParam Kind - Which kind of node this schema is for.
2101
- * @typeParam TNode - API for nodes that use this schema.
2102
- * @typeParam TBuild - Data which can be used to construct an {@link Unhydrated} node of this type.
2103
- * @typeParam Info - Data used when defining this schema.
2104
- * @remarks
2105
- * Captures the schema both as runtime data and compile time type information.
2106
- * @public
2107
- */
2108
- export declare type TreeNodeSchema<Name extends string = string, Kind extends NodeKind = NodeKind, TNode = unknown, TBuild = never, ImplicitlyConstructable extends boolean = boolean, Info = unknown> = TreeNodeSchemaClass<Name, Kind, TNode, TBuild, ImplicitlyConstructable, Info> | TreeNodeSchemaNonClass<Name, Kind, TNode, TBuild, ImplicitlyConstructable, Info>;
2109
-
2110
- /**
2111
- * Tree node schema which is implemented using a class.
2112
- * @remarks
2113
- * Instances of this class are nodes in the tree.
2114
- * This is also a constructor so that it can be subclassed.
2115
- *
2116
- * Using classes in this way allows introducing a named type and a named value at the same time, helping keep the runtime and compile time information together and easy to refer to un a uniform way.
2117
- * Additionally, this works around https://github.com/microsoft/TypeScript/issues/55832 which causes similar patterns with less explicit types to infer "any" in the d.ts file.
2118
- * @public
2119
- */
2120
- export declare interface TreeNodeSchemaClass<out Name extends string = string, out Kind extends NodeKind = NodeKind, out TNode = unknown, in TInsertable = never, out ImplicitlyConstructable extends boolean = boolean, out Info = unknown> extends TreeNodeSchemaCore<Name, Kind, ImplicitlyConstructable, Info> {
2121
- /**
2122
- * Constructs an {@link Unhydrated} node with this schema.
2123
- * @remarks
2124
- * This constructor is also used internally to construct hydrated nodes with a different parameter type.
2125
- * Therefor overriding this constructor is not type-safe and is not supported.
2126
- * @sealed
2127
- */
2128
- new (data: TInsertable): Unhydrated<TNode>;
2129
- }
2130
-
2131
- /**
2132
- * Data common to all tree node schema.
2133
- * @public
2134
- */
2135
- export declare interface TreeNodeSchemaCore<out Name extends string, out Kind extends NodeKind, out ImplicitlyConstructable extends boolean, out Info = unknown> {
2136
- readonly identifier: Name;
2137
- readonly kind: Kind;
2138
- /**
2139
- * Data used to define this schema.
2140
- *
2141
- * @remarks
2142
- * The format depends on the kind of node it is for.
2143
- * For example, the "object" node kind could store the field schema here.
2144
- */
2145
- readonly info: Info;
2146
- /**
2147
- * When constructing insertable content,
2148
- * data that could be passed to the node's constructor can be used instead of an {@link Unhydrated} node
2149
- * iff implicitlyConstructable is true.
2150
- * @privateRemarks
2151
- * Currently the logic for traversing insertable content,
2152
- * both to build trees and to hydrate them does not defer to the schema classes to handle the policy,
2153
- * so if their constructors differ from what is supported, some cases will not work.
2154
- * Setting this to false adjusts the insertable types to disallow cases which could be impacted by these inconsistencies.
2155
- */
2156
- readonly implicitlyConstructable: ImplicitlyConstructable;
2157
- }
2158
-
2159
- /**
2160
- * Schema which is not a class.
2161
- * @remarks
2162
- * This is used for schema which cannot have their instances constructed using constructors, like leaf schema.
2163
- * @privateRemarks
2164
- * Non-class based schema can have issues with recursive types due to https://github.com/microsoft/TypeScript/issues/55832.
2165
- * @public
2166
- */
2167
- export declare interface TreeNodeSchemaNonClass<out Name extends string = string, out Kind extends NodeKind = NodeKind, out TNode = unknown, in TInsertable = never, out ImplicitlyConstructable extends boolean = boolean, out Info = unknown> extends TreeNodeSchemaCore<Name, Kind, ImplicitlyConstructable, Info> {
2168
- create(data: TInsertable): TNode;
2169
- }
2170
-
2171
- /**
2172
- * A {@link TreeNode} which modules a JavaScript object.
2173
- * @remarks
2174
- * Object nodes consist of a type which specifies which {@link TreeNodeSchema} they use (see {@link TreeNodeApi.schema}), and a collections of fields, each with a distinct `key` and its own {@link FieldSchema} defining what can be placed under that key.
2175
- *
2176
- * All non-empty fields on an object node are exposed as enumerable own properties with string keys.
2177
- * No other own `own` or `enumerable` properties are included on object nodes unless the user of the node manually adds custom session only state.
2178
- * This allows a majority of general purpose JavaScript object processing operations (like `for...in`, `Reflect.ownKeys()` and `Object.entries()`) to enumerate all the children.
2179
- * @public
2180
- */
2181
- export declare type TreeObjectNode<T extends RestrictiveReadonlyRecord<string, ImplicitFieldSchema>, TypeName extends string = string> = TreeNode & ObjectFromSchemaRecord<T> & WithType<TypeName>;
2182
-
2183
- /**
2184
- * Status of the tree that a particular node belongs to.
2185
- * @public
2186
- */
2187
- export declare enum TreeStatus {
2188
- /**
2189
- * Is parented under the root field.
2190
- */
2191
- InDocument = 0,
2192
- /**
2193
- * Is not parented under the root field, but can be added back to the original document tree.
2194
- */
2195
- Removed = 1,
2196
- /**
2197
- * Is removed and cannot be added back to the original document tree.
2198
- */
2199
- Deleted = 2
2200
- }
2201
-
2202
- /**
2203
- * An editable view of a (version control style) branch of a shared tree.
2204
- *
2205
- * This view is always in one of two states:
2206
- * 1. In schema: the stored schema is compatible with the provided view schema. There is no error, and root can be used.
2207
- * 2. Out of schema: the stored schema is incompatible with the provided view schema. There is an error, and root cannot be used.
2208
- *
2209
- * @privateRemarks
2210
- * From an API design perspective, `upgradeSchema` could be merged into `schematize` anb/or `schematize` could return errors explicitly.
2211
- * Such approaches would make it discoverable that out of schema handling may need to be done.
2212
- * Doing that would however complicate trivial "hello world" style example slightly, as well as be a breaking API change.
2213
- * It also seems more complex to handle invalidation with that pattern.
2214
- * Thus this design was chosen at the risk of apps blindly accessing `root` then breaking unexpectedly when the document is incompatible.
2215
- * If this does become a problem,
2216
- * it could be mitigated by adding a `rootOrError` member and deprecating `root` to give users a warning if they might be missing the error checking.
2217
- * @public
2218
- */
2219
- export declare interface TreeView<TSchema extends ImplicitFieldSchema> extends IDisposable {
2220
- /**
2221
- * The current root of the tree.
2222
- *
2223
- * If in the out of schema state, accessing this will throw.
2224
- * To handle this case, check `error` before using.
2225
- *
2226
- * To get notified about changes to this field (including to it being in an `error` state),
2227
- * use {@link TreeViewEvents.rootChanged} via `view.events.on("rootChanged", callback)`.
2228
- */
2229
- get root(): TreeFieldFromImplicitField<TSchema>;
2230
- set root(newRoot: InsertableTreeFieldFromImplicitField<TSchema>);
2231
- /**
2232
- * Description of the error state, if any.
2233
- * When this is undefined, the view schema and stored schema are compatible, and `root` can be used.
2234
- */
2235
- readonly error?: SchemaIncompatible;
2236
- /**
2237
- * When there is an `error` and {@link SchemaIncompatible.canUpgrade} is true,
2238
- * this can be used to modify the stored schema to make it match the view schema.
2239
- * This will clear the error state, and allow access to `root`.
2240
- * @remarks
2241
- * It is an error to call this when {@link SchemaIncompatible.canUpgrade} is false, and a no-op when not in an `error` state.
2242
- * When this changes the stored schema, any existing or future clients which were compatible with the old stored schema will get an `error` state when trying to schematize the document.
2243
- * @privateRemarks
2244
- * In the future, more upgrade options could be provided here.
2245
- * Some options that could be added:
2246
- * - check the actual document contents (not just the schema) and attempt an atomic document update if the data is compatible.
2247
- * - apply converters and upgrade the document.
2248
- * - apply converters to lazily to adapt the document to the requested view schema (with optional lazy schema updates or transparent conversions on write).
2249
- */
2250
- upgradeSchema(): void;
2251
- /**
2252
- * Events for the tree.
2253
- */
2254
- readonly events: ISubscribable<TreeViewEvents>;
2255
- }
2256
-
2257
- /**
2258
- * Events for {@link TreeView}.
2259
- * @public
2260
- */
2261
- export declare interface TreeViewEvents {
2262
- /**
2263
- * A batch of changes has finished processing and the view has been updated.
2264
- */
2265
- afterBatch(): void;
2266
- /**
2267
- * {@link TreeView.root} has changed.
2268
- * This includes going into or out of an `error` state where the root is unavailable due to stored schema changes.
2269
- * It also includes changes to the field containing the root such as setting or clearing an optional root or changing which node is the root.
2270
- * This does NOT include changes to the content (fields/children) of the root node: for that case subscribe to events on the root node.
2271
- */
2272
- rootChanged(): void;
2273
- /**
2274
- * Fired when:
2275
- * - a local commit is applied outside of a transaction
2276
- * - a local transaction is committed
2277
- *
2278
- * The event is not fired when:
2279
- * - a local commit is applied within a transaction
2280
- * - a remote commit is applied
2281
- *
2282
- * @param data - information about the commit that was applied
2283
- * @param getRevertible - a function provided that allows users to get a revertible for the commit that was applied. If not provided,
2284
- * this commit is not revertible.
2285
- */
2286
- commitApplied(data: CommitMetadata, getRevertible?: RevertibleFactory): void;
2287
- }
2288
-
2289
- /**
2290
- * The type of a {@link TreeNode}.
2291
- * For moore information about the type, use `Tree.schema(theNode)` instead.
2292
- * @remarks
2293
- * This symbol mainly exists on nodes to allow TypeScript to provide more accurate type checking.
2294
- * `Tree.is` and `Tree.schema` provide a superset of this information in more friendly ways.
2295
- *
2296
- * This symbol should not manually be added to objects as doing so allows the object to be invalidly used where nodes are expected.
2297
- * Instead construct a real node of the desired type using its constructor.
2298
- * @privateRemarks
2299
- * This prevents non-nodes from being accidentally used as nodes, as well as allows the type checker to distinguish different node types.
2300
- * @public
2301
- */
2302
- export declare const type: unique symbol;
2303
-
2304
- /**
2305
- * Type alias to document which values are un-hydrated.
2306
- *
2307
- * Un-hydrated values are nodes produced from schema's create functions that haven't been inserted into a tree yet.
2308
- *
2309
- * Since un-hydrated nodes become hydrated when inserted, strong typing can't be used to distinguish them.
2310
- * This no-op wrapper is used instead.
2311
- * @public
2312
- */
2313
- export declare type Unhydrated<T> = T;
2314
-
2315
- /**
2316
- * Adds a {@link "type"} field.
2317
- * @public
2318
- */
2319
- export declare interface WithType<TName extends string = string> {
2320
- /**
2321
- * {@inheritdoc "type"}
2322
- */
2323
- get [type](): TName;
2324
- }
2325
-
2326
- export { }