@fluidframework/aqueduct 2.0.0-dev-rc.3.0.0.254866 → 2.0.0-dev-rc.5.0.0.263932

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.
Files changed (59) hide show
  1. package/.eslintrc.cjs +14 -0
  2. package/.mocharc.cjs +12 -0
  3. package/CHANGELOG.md +346 -0
  4. package/api-extractor-lint.json +4 -0
  5. package/api-extractor.json +4 -0
  6. package/api-report/aqueduct.api.md +165 -0
  7. package/dist/container-runtime-factories/baseContainerRuntimeFactory.d.ts.map +1 -1
  8. package/dist/container-runtime-factories/baseContainerRuntimeFactory.js.map +1 -1
  9. package/dist/container-runtime-factories/containerRuntimeFactoryWithDefaultDataStore.d.ts.map +1 -1
  10. package/dist/container-runtime-factories/containerRuntimeFactoryWithDefaultDataStore.js.map +1 -1
  11. package/dist/data-object-factories/dataObjectFactory.d.ts.map +1 -1
  12. package/dist/data-object-factories/dataObjectFactory.js +1 -0
  13. package/dist/data-object-factories/dataObjectFactory.js.map +1 -1
  14. package/dist/data-objects/dataObject.d.ts.map +1 -1
  15. package/dist/data-objects/dataObject.js +2 -0
  16. package/dist/data-objects/dataObject.js.map +1 -1
  17. package/dist/data-objects/pureDataObject.d.ts +4 -3
  18. package/dist/data-objects/pureDataObject.d.ts.map +1 -1
  19. package/dist/data-objects/pureDataObject.js.map +1 -1
  20. package/dist/{alpha.d.ts → legacy.d.ts} +2 -1
  21. package/dist/public.d.ts +3 -0
  22. package/{dist/beta.d.ts → internal.d.ts} +2 -0
  23. package/{lib/beta.d.ts → legacy.d.ts} +2 -0
  24. package/lib/container-runtime-factories/baseContainerRuntimeFactory.d.ts.map +1 -1
  25. package/lib/container-runtime-factories/baseContainerRuntimeFactory.js.map +1 -1
  26. package/lib/container-runtime-factories/containerRuntimeFactoryWithDefaultDataStore.d.ts.map +1 -1
  27. package/lib/container-runtime-factories/containerRuntimeFactoryWithDefaultDataStore.js.map +1 -1
  28. package/lib/data-object-factories/dataObjectFactory.d.ts.map +1 -1
  29. package/lib/data-object-factories/dataObjectFactory.js +4 -1
  30. package/lib/data-object-factories/dataObjectFactory.js.map +1 -1
  31. package/lib/data-objects/dataObject.d.ts.map +1 -1
  32. package/lib/data-objects/dataObject.js +2 -0
  33. package/lib/data-objects/dataObject.js.map +1 -1
  34. package/lib/data-objects/pureDataObject.d.ts +4 -3
  35. package/lib/data-objects/pureDataObject.d.ts.map +1 -1
  36. package/lib/data-objects/pureDataObject.js.map +1 -1
  37. package/lib/{alpha.d.ts → legacy.d.ts} +2 -1
  38. package/lib/public.d.ts +3 -0
  39. package/lib/tsdoc-metadata.json +1 -1
  40. package/package.json +34 -40
  41. package/prettier.config.cjs +8 -0
  42. package/src/container-runtime-factories/baseContainerRuntimeFactory.ts +145 -0
  43. package/src/container-runtime-factories/containerRuntimeFactoryWithDefaultDataStore.ts +112 -0
  44. package/src/container-runtime-factories/index.ts +13 -0
  45. package/src/data-object-factories/dataObjectFactory.ts +63 -0
  46. package/src/data-object-factories/index.ts +7 -0
  47. package/src/data-object-factories/pureDataObjectFactory.ts +379 -0
  48. package/src/data-objects/dataObject.ts +80 -0
  49. package/src/data-objects/index.ts +8 -0
  50. package/src/data-objects/pureDataObject.ts +186 -0
  51. package/src/data-objects/types.ts +40 -0
  52. package/src/index.ts +33 -0
  53. package/tsconfig.cjs.json +7 -0
  54. package/tsconfig.json +9 -0
  55. package/lib/test/aqueduct.spec.js +0 -8
  56. package/lib/test/aqueduct.spec.js.map +0 -1
  57. package/lib/test/tsconfig.tsbuildinfo +0 -1
  58. package/lib/test/types/validateAqueductPrevious.generated.js +0 -30
  59. package/lib/test/types/validateAqueductPrevious.generated.js.map +0 -1
@@ -0,0 +1,379 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { FluidDataStoreRegistry } from "@fluidframework/container-runtime/internal";
7
+ import { type IContainerRuntime } from "@fluidframework/container-runtime-definitions/internal";
8
+ import { type FluidObject, type IRequest } from "@fluidframework/core-interfaces";
9
+ import { assert } from "@fluidframework/core-utils/internal";
10
+ import {
11
+ FluidDataStoreRuntime,
12
+ type ISharedObjectRegistry,
13
+ mixinRequestHandler,
14
+ } from "@fluidframework/datastore/internal";
15
+ import {
16
+ type IChannelFactory,
17
+ type IFluidDataStoreRuntime,
18
+ } from "@fluidframework/datastore-definitions";
19
+ import {
20
+ type IContainerRuntimeBase,
21
+ type IDataStore,
22
+ type IFluidDataStoreChannel,
23
+ type IFluidDataStoreContext,
24
+ type IFluidDataStoreContextDetached,
25
+ type IFluidDataStoreFactory,
26
+ type IFluidDataStoreRegistry,
27
+ type IProvideFluidDataStoreRegistry,
28
+ type NamedFluidDataStoreRegistryEntries,
29
+ type NamedFluidDataStoreRegistryEntry,
30
+ } from "@fluidframework/runtime-definitions/internal";
31
+ import {
32
+ type AsyncFluidObjectProvider,
33
+ type FluidObjectSymbolProvider,
34
+ type IFluidDependencySynthesizer,
35
+ } from "@fluidframework/synthesize/internal";
36
+
37
+ import {
38
+ type DataObjectTypes,
39
+ type IDataObjectProps,
40
+ type PureDataObject,
41
+ } from "../data-objects/index.js";
42
+
43
+ /**
44
+ * Proxy over PureDataObject
45
+ * Does delayed creation & initialization of PureDataObject
46
+ */
47
+ async function createDataObject<
48
+ TObj extends PureDataObject,
49
+ I extends DataObjectTypes = DataObjectTypes,
50
+ >(
51
+ ctor: new (props: IDataObjectProps<I>) => TObj,
52
+ context: IFluidDataStoreContext,
53
+ sharedObjectRegistry: ISharedObjectRegistry,
54
+ optionalProviders: FluidObjectSymbolProvider<I["OptionalProviders"]>,
55
+ runtimeClassArg: typeof FluidDataStoreRuntime,
56
+ existing: boolean,
57
+ initProps?: I["InitialState"],
58
+ ): Promise<{
59
+ instance: TObj;
60
+ runtime: FluidDataStoreRuntime;
61
+ }> {
62
+ // base
63
+ let runtimeClass = runtimeClassArg;
64
+
65
+ // request mixin in
66
+ runtimeClass = mixinRequestHandler(
67
+ async (request: IRequest, runtimeArg: FluidDataStoreRuntime) => {
68
+ // The provideEntryPoint callback below always returns TObj, so this cast is safe
69
+ const dataObject = (await runtimeArg.entryPoint.get()) as TObj;
70
+ assert(
71
+ dataObject.request !== undefined,
72
+ 0x795 /* Data store runtime entryPoint does not have request */,
73
+ );
74
+ return dataObject.request(request);
75
+ },
76
+ runtimeClass,
77
+ );
78
+
79
+ // Create a new runtime for our data store, as if via new FluidDataStoreRuntime,
80
+ // but using the runtimeClass that's been augmented with mixins
81
+ // The runtime is what Fluid uses to create DDS' and route to your data store
82
+ const runtime: FluidDataStoreRuntime = new runtimeClass( // calls new FluidDataStoreRuntime(...)
83
+ context,
84
+ sharedObjectRegistry,
85
+ existing,
86
+ async (rt: IFluidDataStoreRuntime) => {
87
+ assert(instance !== undefined, 0x46a /* entryPoint is undefined */);
88
+ // Calling finishInitialization here like PureDataObject.getDataObject did, to keep the same behavior,
89
+ // since accessing the runtime's entryPoint is how we want the data object to be retrieved going forward.
90
+ // Without this I ran into issues with the load-existing flow not working correctly.
91
+ await instance.finishInitialization(true);
92
+ return instance;
93
+ } /* provideEntryPoint */,
94
+ );
95
+
96
+ // Create object right away.
97
+ // This allows object to register various callbacks with runtime before runtime
98
+ // becomes globally available. But it's not full initialization - constructor can't
99
+ // access DDSes or other services of runtime as objects are not fully initialized.
100
+ // In order to use object, we need to go through full initialization by calling finishInitialization().
101
+ const scope: FluidObject<IFluidDependencySynthesizer> = context.scope;
102
+ const providers =
103
+ scope.IFluidDependencySynthesizer?.synthesize<I["OptionalProviders"]>(
104
+ optionalProviders,
105
+ {},
106
+ ) ??
107
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
108
+ ({} as AsyncFluidObjectProvider<never>);
109
+
110
+ const instance = new ctor({ runtime, context, providers, initProps });
111
+
112
+ // if it's a newly created object, we need to wait for it to finish initialization
113
+ // as that results in creation of DDSes, before it gets attached, providing atomic
114
+ // guarantee of creation.
115
+ // WARNING: we can't do the same (yet) for already existing PureDataObject!
116
+ // This will result in deadlock, as it tries to resolve internal handles, but any
117
+ // handle resolution goes through root (container runtime), which can't route it back
118
+ // to this data store, as it's still not initialized and not known to container runtime yet.
119
+ // In the future, we should address it by using relative paths for handles and be able to resolve
120
+ // local DDSes while data store is not fully initialized.
121
+ if (!existing) {
122
+ await instance.finishInitialization(existing);
123
+ }
124
+
125
+ return { instance, runtime };
126
+ }
127
+
128
+ /**
129
+ * PureDataObjectFactory is a barebones IFluidDataStoreFactory for use with PureDataObject.
130
+ * Consumers should typically use DataObjectFactory instead unless creating
131
+ * another base data store factory.
132
+ *
133
+ * @typeParam TObj - DataObject (concrete type)
134
+ * @typeParam I - The input types for the DataObject
135
+ * @alpha
136
+ */
137
+ export class PureDataObjectFactory<
138
+ TObj extends PureDataObject<I>,
139
+ I extends DataObjectTypes = DataObjectTypes,
140
+ >
141
+ implements IFluidDataStoreFactory, Partial<IProvideFluidDataStoreRegistry>
142
+ {
143
+ private readonly sharedObjectRegistry: ISharedObjectRegistry;
144
+ private readonly registry: IFluidDataStoreRegistry | undefined;
145
+
146
+ public constructor(
147
+ /**
148
+ * {@inheritDoc @fluidframework/runtime-definitions#IFluidDataStoreFactory."type"}
149
+ */
150
+ public readonly type: string,
151
+ private readonly ctor: new (props: IDataObjectProps<I>) => TObj,
152
+ sharedObjects: readonly IChannelFactory[],
153
+ private readonly optionalProviders: FluidObjectSymbolProvider<I["OptionalProviders"]>,
154
+ registryEntries?: NamedFluidDataStoreRegistryEntries,
155
+ private readonly runtimeClass: typeof FluidDataStoreRuntime = FluidDataStoreRuntime,
156
+ ) {
157
+ if (this.type === "") {
158
+ throw new Error("undefined type member");
159
+ }
160
+ if (registryEntries !== undefined) {
161
+ this.registry = new FluidDataStoreRegistry(registryEntries);
162
+ }
163
+ this.sharedObjectRegistry = new Map(sharedObjects.map((ext) => [ext.type, ext]));
164
+ }
165
+
166
+ /**
167
+ * {@inheritDoc @fluidframework/runtime-definitions#IProvideFluidDataStoreFactory.IFluidDataStoreFactory}
168
+ */
169
+ public get IFluidDataStoreFactory(): this {
170
+ return this;
171
+ }
172
+
173
+ /**
174
+ * {@inheritDoc @fluidframework/runtime-definitions#IProvideFluidDataStoreRegistry.IFluidDataStoreRegistry}
175
+ */
176
+ public get IFluidDataStoreRegistry(): IFluidDataStoreRegistry | undefined {
177
+ return this.registry;
178
+ }
179
+
180
+ /**
181
+ * Convenience helper to get the data store's/factory's data store registry entry.
182
+ * The return type hides the factory's generics, easing grouping of registry
183
+ * entries that differ only in this way into the same array.
184
+ * @returns The NamedFluidDataStoreRegistryEntry
185
+ */
186
+ public get registryEntry(): NamedFluidDataStoreRegistryEntry {
187
+ return [this.type, Promise.resolve(this)];
188
+ }
189
+
190
+ /**
191
+ * {@inheritDoc @fluidframework/runtime-definitions#IFluidDataStoreFactory.instantiateDataStore}
192
+ */
193
+ public async instantiateDataStore(
194
+ context: IFluidDataStoreContext,
195
+ existing: boolean,
196
+ ): Promise<IFluidDataStoreChannel> {
197
+ const { runtime } = await createDataObject(
198
+ this.ctor,
199
+ context,
200
+ this.sharedObjectRegistry,
201
+ this.optionalProviders,
202
+ this.runtimeClass,
203
+ existing,
204
+ );
205
+
206
+ return runtime;
207
+ }
208
+
209
+ /**
210
+ * Creates a new instance of the object. Uses parent context's registry to build package path to this factory.
211
+ * In other words, registry of context passed in has to contain this factory, with the name that matches
212
+ * this factory's type.
213
+ * It is intended to be used by data store objects that create sub-objects.
214
+ * @param context - The context being used to create the runtime
215
+ * (the created object will have its own new context created as well)
216
+ * @param initialState - The initial state to provide to the created data store.
217
+ * @param loadingGroupId - NOT production ready, EXPERIMENTAL, please read {@link https://github.com/microsoft/FluidFramework/blob/main/packages/runtime/container-runtime/README.md | README}. The service needs to support this feature, does not work for most services
218
+ * @returns an object created by this factory. Data store and objects created are not attached to container.
219
+ * They get attached only when a handle to one of them is attached to already attached objects.
220
+ */
221
+ public async createChildInstance(
222
+ parentContext: IFluidDataStoreContext,
223
+ initialState?: I["InitialState"],
224
+ loadingGroupId?: string,
225
+ ): Promise<TObj> {
226
+ return this.createNonRootInstanceCore(
227
+ parentContext.containerRuntime,
228
+ [...parentContext.packagePath, this.type],
229
+ initialState,
230
+ loadingGroupId,
231
+ );
232
+ }
233
+
234
+ /**
235
+ * Creates a new instance of the object. Uses peer context's registry and its package path to identify this factory.
236
+ * In other words, registry of context passed in has to have this factory.
237
+ * Intended to be used by data store objects that need to create peers (similar) instances of existing objects.
238
+ * @param context - The component context being used to create the object
239
+ * (the created object will have its own new context created as well)
240
+ * @param initialState - The initial state to provide to the created component.
241
+ * @param loadingGroupId - NOT production ready, EXPERIMENTAL, please read {@link https://github.com/microsoft/FluidFramework/blob/main/packages/runtime/container-runtime/README.md | README}. The service needs to support this feature, does not work for most services
242
+ * @returns an object created by this factory. Data store and objects created are not attached to container.
243
+ * They get attached only when a handle to one of them is attached to already attached objects.
244
+ */
245
+ public async createPeerInstance(
246
+ peerContext: IFluidDataStoreContext,
247
+ initialState?: I["InitialState"],
248
+ loadingGroupId?: string, // DO NOT USE, this is an experimental feature
249
+ ): Promise<TObj> {
250
+ return this.createNonRootInstanceCore(
251
+ peerContext.containerRuntime,
252
+ peerContext.packagePath,
253
+ initialState,
254
+ loadingGroupId,
255
+ );
256
+ }
257
+
258
+ /**
259
+ * Creates a new instance of the object. Uses container's registry to find this factory.
260
+ * It's expected that only container owners would use this functionality, as only such developers
261
+ * have knowledge of entries in container registry.
262
+ * The name in this registry for such record should match type of this factory.
263
+ * @param runtime - container runtime. It's registry is used to create an object.
264
+ * @param initialState - The initial state to provide to the created component.
265
+ * @param loadingGroupId - NOT production ready, EXPERIMENTAL, please read {@link https://github.com/microsoft/FluidFramework/blob/main/packages/runtime/container-runtime/README.md | README}. The service needs to support this feature, does not work for most services
266
+ * @returns an object created by this factory. Data store and objects created are not attached to container.
267
+ * They get attached only when a handle to one of them is attached to already attached objects.
268
+ */
269
+ public async createInstance(
270
+ runtime: IContainerRuntimeBase,
271
+ initialState?: I["InitialState"],
272
+ loadingGroupId?: string,
273
+ ): Promise<TObj> {
274
+ return this.createNonRootInstanceCore(runtime, [this.type], initialState, loadingGroupId);
275
+ }
276
+
277
+ /**
278
+ * Creates a new instance of the object with a datastore which exposes the aliasing api.
279
+ * @param runtime - container runtime. It is the runtime that will be used to create the object. It will produce
280
+ * the underlying infrastructure to get the data object to operate.
281
+ * @param initialState - The initial state to provide to the created component.
282
+ * @param packagePath - The path to the data store factory to use to create the data object.
283
+ * @param loadingGroupId - NOT production ready, EXPERIMENTAL, please read {@link https://github.com/microsoft/FluidFramework/blob/main/packages/runtime/container-runtime/README.md | README}. The service needs to support this feature, does not work for most services
284
+ * @returns an array containing the object created by this factory and an IDataStore object that enables users to
285
+ * alias the data object.
286
+ * The data object is attached only when it is attached to the handle graph that connects to an aliased object or
287
+ * when the data object is aliased.
288
+ */
289
+ public async createInstanceWithDataStore(
290
+ containerRuntime: IContainerRuntimeBase,
291
+ initialState?: I["InitialState"],
292
+ packagePath?: Readonly<string[]>,
293
+ loadingGroupId?: string,
294
+ ): Promise<[TObj, IDataStore]> {
295
+ const context = containerRuntime.createDetachedDataStore(
296
+ packagePath ?? [this.type],
297
+ loadingGroupId,
298
+ );
299
+ const { instance, runtime } = await createDataObject(
300
+ this.ctor,
301
+ context,
302
+ this.sharedObjectRegistry,
303
+ this.optionalProviders,
304
+ this.runtimeClass,
305
+ false, // existing
306
+ initialState,
307
+ );
308
+ const dataStore = await context.attachRuntime(this, runtime);
309
+
310
+ return [instance, dataStore];
311
+ }
312
+
313
+ /**
314
+ * Creates a new root instance of the object. Uses container's registry to find this factory.
315
+ * It's expected that only container owners would use this functionality, as only such developers
316
+ * have knowledge of entries in container registry.
317
+ * The name in this registry for such record should match type of this factory.
318
+ * @param runtime - container runtime. It's registry is used to create an object.
319
+ * @param initialState - The initial state to provide to the created component.
320
+ * @returns an object created by this factory. Data store and objects created are not attached to container.
321
+ * They get attached only when a handle to one of them is attached to already attached objects.
322
+ *
323
+ * @deprecated - the issue is that it does not allow the customer to decide the conflict resolution policy when an
324
+ * aliasing conflict occurs. Use {@link PureDataObjectFactory.createInstanceWithDataStore} instead.
325
+ */
326
+ public async createRootInstance(
327
+ rootDataStoreId: string,
328
+ runtime: IContainerRuntime,
329
+ initialState?: I["InitialState"],
330
+ ): Promise<TObj> {
331
+ const context = runtime.createDetachedDataStore([this.type]);
332
+ const { instance, runtime: dataStoreRuntime } = await createDataObject(
333
+ this.ctor,
334
+ context,
335
+ this.sharedObjectRegistry,
336
+ this.optionalProviders,
337
+ this.runtimeClass,
338
+ false, // existing
339
+ initialState,
340
+ );
341
+ const dataStore = await context.attachRuntime(this, dataStoreRuntime);
342
+ const result = await dataStore.trySetAlias(rootDataStoreId);
343
+ if (result !== "Success") {
344
+ const handle = await runtime.getAliasedDataStoreEntryPoint(rootDataStoreId);
345
+ assert(handle !== undefined, 0x8e1 /* Should have retrieved aliased handle */);
346
+ return (await handle.get()) as TObj;
347
+ }
348
+ return instance;
349
+ }
350
+
351
+ protected async createNonRootInstanceCore(
352
+ containerRuntime: IContainerRuntimeBase,
353
+ packagePath: Readonly<string[]>,
354
+ initialState?: I["InitialState"],
355
+ loadingGroupId?: string,
356
+ ): Promise<TObj> {
357
+ const context = containerRuntime.createDetachedDataStore(packagePath, loadingGroupId);
358
+ return this.createInstanceCore(context, initialState);
359
+ }
360
+
361
+ protected async createInstanceCore(
362
+ context: IFluidDataStoreContextDetached,
363
+ initialState?: I["InitialState"],
364
+ ): Promise<TObj> {
365
+ const { instance, runtime } = await createDataObject(
366
+ this.ctor,
367
+ context,
368
+ this.sharedObjectRegistry,
369
+ this.optionalProviders,
370
+ this.runtimeClass,
371
+ false, // existing
372
+ initialState,
373
+ );
374
+
375
+ await context.attachRuntime(this, runtime);
376
+
377
+ return instance;
378
+ }
379
+ }
@@ -0,0 +1,80 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ // eslint-disable-next-line import/no-deprecated
7
+ import { type ISharedDirectory, MapFactory, SharedDirectory } from "@fluidframework/map/internal";
8
+
9
+ import { PureDataObject } from "./pureDataObject.js";
10
+ import { type DataObjectTypes } from "./types.js";
11
+
12
+ /**
13
+ * DataObject is a base data store that is primed with a root directory. It
14
+ * ensures that it is created and ready before you can access it.
15
+ *
16
+ * Having a single root directory allows for easier development. Instead of creating
17
+ * and registering channels with the runtime any new DDS that is set on the root
18
+ * will automatically be registered.
19
+ *
20
+ * @typeParam I - The optional input types used to strongly type the data object
21
+ * @alpha
22
+ */
23
+ export abstract class DataObject<
24
+ I extends DataObjectTypes = DataObjectTypes,
25
+ > extends PureDataObject<I> {
26
+ private internalRoot: ISharedDirectory | undefined;
27
+ private readonly rootDirectoryId = "root";
28
+
29
+ /**
30
+ * The root directory will either be ready or will return an error. If an error is thrown
31
+ * the root has not been correctly created/set.
32
+ */
33
+ protected get root(): ISharedDirectory {
34
+ if (!this.internalRoot) {
35
+ throw new Error(this.getUninitializedErrorString(`root`));
36
+ }
37
+
38
+ return this.internalRoot;
39
+ }
40
+
41
+ /**
42
+ * Initializes internal objects and calls initialization overrides.
43
+ * Caller is responsible for ensuring this is only invoked once.
44
+ */
45
+ public async initializeInternal(existing: boolean): Promise<void> {
46
+ if (existing) {
47
+ // data store has a root directory so we just need to set it before calling initializingFromExisting
48
+ this.internalRoot = (await this.runtime.getChannel(
49
+ this.rootDirectoryId,
50
+ )) as ISharedDirectory;
51
+
52
+ // This will actually be an ISharedMap if the channel was previously created by the older version of
53
+ // DataObject which used a SharedMap. Since SharedMap and SharedDirectory are compatible unless
54
+ // SharedDirectory-only commands are used on SharedMap, this will mostly just work for compatibility.
55
+ if (this.internalRoot.attributes.type === MapFactory.Type) {
56
+ this.runtime.logger.send({
57
+ category: "generic",
58
+ eventName: "MapDataObject",
59
+ message:
60
+ "Legacy document, SharedMap is masquerading as SharedDirectory in DataObject",
61
+ });
62
+ }
63
+ } else {
64
+ // Create a root directory and register it before calling initializingFirstTime
65
+ // eslint-disable-next-line import/no-deprecated
66
+ this.internalRoot = SharedDirectory.create(this.runtime, this.rootDirectoryId);
67
+ this.internalRoot.bindToContext();
68
+ }
69
+
70
+ await super.initializeInternal(existing);
71
+ }
72
+
73
+ /**
74
+ * Generates an error string indicating an item is uninitialized.
75
+ * @param item - The name of the item that was uninitialized.
76
+ */
77
+ protected getUninitializedErrorString(item: string): string {
78
+ return `${item} must be initialized before being accessed.`;
79
+ }
80
+ }
@@ -0,0 +1,8 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ export { DataObject } from "./dataObject.js";
7
+ export { PureDataObject } from "./pureDataObject.js";
8
+ export type { DataObjectTypes, IDataObjectProps } from "./types.js";
@@ -0,0 +1,186 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { TypedEventEmitter } from "@fluid-internal/client-utils";
7
+ import { type IEvent } from "@fluidframework/core-interfaces";
8
+ import {
9
+ type IFluidHandleInternal,
10
+ type IFluidLoadable,
11
+ type IProvideFluidHandle,
12
+ type IRequest,
13
+ type IResponse,
14
+ } from "@fluidframework/core-interfaces/internal";
15
+ import { assert } from "@fluidframework/core-utils/internal";
16
+ import { type IFluidDataStoreRuntime } from "@fluidframework/datastore-definitions";
17
+ import { type IFluidDataStoreContext } from "@fluidframework/runtime-definitions/internal";
18
+ import { create404Response } from "@fluidframework/runtime-utils/internal";
19
+ import { type AsyncFluidObjectProvider } from "@fluidframework/synthesize/internal";
20
+
21
+ import { type DataObjectTypes, type IDataObjectProps } from "./types.js";
22
+
23
+ /**
24
+ * This is a bare-bones base class that does basic setup and enables for factory on an initialize call.
25
+ * You probably don't want to inherit from this data store directly unless
26
+ * you are creating another base data store class
27
+ *
28
+ * @typeParam I - The optional input types used to strongly type the data object
29
+ * @alpha
30
+ */
31
+ export abstract class PureDataObject<I extends DataObjectTypes = DataObjectTypes>
32
+ extends TypedEventEmitter<I["Events"] & IEvent>
33
+ implements IFluidLoadable, IProvideFluidHandle
34
+ {
35
+ /**
36
+ * This is your FluidDataStoreRuntime object
37
+ */
38
+ protected readonly runtime: IFluidDataStoreRuntime;
39
+
40
+ /**
41
+ * This context is used to talk up to the ContainerRuntime
42
+ */
43
+ protected readonly context: IFluidDataStoreContext;
44
+
45
+ /**
46
+ * Providers are FluidObject keyed objects that provide back
47
+ * a promise to the corresponding FluidObject or undefined.
48
+ * Providers injected/provided by the Container and/or HostingApplication
49
+ *
50
+ * To define providers set FluidObject interfaces in the OptionalProviders generic type for your data store
51
+ */
52
+ protected readonly providers: AsyncFluidObjectProvider<I["OptionalProviders"]>;
53
+
54
+ protected initProps?: I["InitialState"];
55
+
56
+ protected initializeP: Promise<void> | undefined;
57
+
58
+ public get id(): string {
59
+ return this.runtime.id;
60
+ }
61
+
62
+ /**
63
+ * {@inheritDoc @fluidframework/core-interfaces#IProvideFluidLoadable.IFluidLoadable}
64
+ */
65
+ public get IFluidLoadable(): this {
66
+ return this;
67
+ }
68
+
69
+ /**
70
+ * {@inheritDoc @fluidframework/core-interfaces#IProvideFluidHandle.IFluidHandle}
71
+ */
72
+ public get IFluidHandle(): IFluidHandleInternal<this> {
73
+ return this.handle;
74
+ }
75
+
76
+ /**
77
+ * Handle to a data store
78
+ */
79
+ public get handle(): IFluidHandleInternal<this> {
80
+ // PureDataObjectFactory already provides an entryPoint initialization function to the data store runtime,
81
+ // so this object should always have access to a non-null entryPoint. Need to cast because PureDataObject
82
+ // tried to be too smart with its typing for handles :).
83
+ assert(this.runtime.entryPoint !== undefined, 0x46b /* EntryPoint was undefined */);
84
+ return this.runtime.entryPoint as IFluidHandleInternal<this>;
85
+ }
86
+
87
+ public static async getDataObject(runtime: IFluidDataStoreRuntime): Promise<PureDataObject> {
88
+ const obj = await runtime.entryPoint.get();
89
+ return obj as PureDataObject;
90
+ }
91
+
92
+ public constructor(props: IDataObjectProps<I>) {
93
+ super();
94
+ this.runtime = props.runtime;
95
+ this.context = props.context;
96
+ this.providers = props.providers;
97
+ this.initProps = props.initProps;
98
+
99
+ /* eslint-disable @typescript-eslint/no-unsafe-member-access */
100
+ /* eslint-disable @typescript-eslint/no-explicit-any */
101
+ assert(
102
+ (this.runtime as any)._dataObject === undefined,
103
+ 0x0bd /* "Object runtime already has DataObject!" */,
104
+ );
105
+ (this.runtime as any)._dataObject = this;
106
+ /* eslint-enable @typescript-eslint/no-explicit-any */
107
+ /* eslint-enable @typescript-eslint/no-unsafe-member-access */
108
+ }
109
+
110
+ /**
111
+ * Return this object if someone requests it directly
112
+ * We will return this object in two scenarios:
113
+ *
114
+ * 1. the request url is a "/"
115
+ *
116
+ * 2. the request url is empty
117
+ */
118
+ public async request(req: IRequest): Promise<IResponse> {
119
+ return req.url === "" || req.url === "/" || req.url.startsWith("/?")
120
+ ? { mimeType: "fluid/object", status: 200, value: this }
121
+ : create404Response(req);
122
+ }
123
+
124
+ /**
125
+ * Call this API to ensure PureDataObject is fully initialized.
126
+ * Initialization happens on demand, only on as-needed bases.
127
+ * In most cases you should allow factory/object to decide when to finish initialization.
128
+ * But if you are supplying your own implementation of DataStoreRuntime factory and overriding some methods
129
+ * and need a fully initialized object, then you can call this API to ensure object is fully initialized.
130
+ */
131
+ public async finishInitialization(existing: boolean): Promise<void> {
132
+ if (this.initializeP !== undefined) {
133
+ return this.initializeP;
134
+ }
135
+ this.initializeP = this.initializeInternal(existing);
136
+ return this.initializeP;
137
+ }
138
+
139
+ /**
140
+ * Internal initialize implementation. Overwriting this will change the flow of the PureDataObject and should
141
+ * generally not be done.
142
+ *
143
+ * Calls initializingFirstTime, initializingFromExisting, and hasInitialized. Caller is
144
+ * responsible for ensuring this is only invoked once.
145
+ */
146
+ public async initializeInternal(existing: boolean): Promise<void> {
147
+ await this.preInitialize();
148
+ if (existing) {
149
+ assert(
150
+ this.initProps === undefined,
151
+ 0x0be /* "Trying to initialize from existing while initProps is set!" */,
152
+ );
153
+ await this.initializingFromExisting();
154
+ } else {
155
+ await this.initializingFirstTime(
156
+ (this.context.createProps as I["InitialState"]) ?? this.initProps,
157
+ );
158
+ }
159
+ await this.hasInitialized();
160
+ }
161
+
162
+ /**
163
+ * Called every time the data store is initialized, before initializingFirstTime or
164
+ * initializingFromExisting is called.
165
+ */
166
+ protected async preInitialize(): Promise<void> {}
167
+
168
+ /**
169
+ * Called the first time the data store is initialized (new creations with a new
170
+ * data store runtime)
171
+ *
172
+ * @param props - Optional props to be passed in on create
173
+ */
174
+ protected async initializingFirstTime(props?: I["InitialState"]): Promise<void> {}
175
+
176
+ /**
177
+ * Called every time but the first time the data store is initialized (creations
178
+ * with an existing data store runtime)
179
+ */
180
+ protected async initializingFromExisting(): Promise<void> {}
181
+
182
+ /**
183
+ * Called every time the data store is initialized after create or existing.
184
+ */
185
+ protected async hasInitialized(): Promise<void> {}
186
+ }
@@ -0,0 +1,40 @@
1
+ /*!
2
+ * Copyright (c) Microsoft Corporation and contributors. All rights reserved.
3
+ * Licensed under the MIT License.
4
+ */
5
+
6
+ import { type FluidObject, type IEvent } from "@fluidframework/core-interfaces";
7
+ import { type IFluidDataStoreRuntime } from "@fluidframework/datastore-definitions";
8
+ import { type IFluidDataStoreContext } from "@fluidframework/runtime-definitions/internal";
9
+ import { type AsyncFluidObjectProvider } from "@fluidframework/synthesize/internal";
10
+
11
+ /**
12
+ * This type is used as the base generic input to DataObject and PureDataObject.
13
+ * @alpha
14
+ */
15
+ export interface DataObjectTypes {
16
+ /**
17
+ * Represents a type that will define optional providers that will be injected.
18
+ */
19
+ OptionalProviders?: FluidObject;
20
+ /**
21
+ * The initial state type that the produced data object may take during creation.
22
+ */
23
+ // TODO: Use a real type here.
24
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
+ InitialState?: any;
26
+ /**
27
+ * Represents events that will be available in the EventForwarder.
28
+ */
29
+ Events?: IEvent;
30
+ }
31
+
32
+ /**
33
+ * @alpha
34
+ */
35
+ export interface IDataObjectProps<I extends DataObjectTypes = DataObjectTypes> {
36
+ readonly runtime: IFluidDataStoreRuntime;
37
+ readonly context: IFluidDataStoreContext;
38
+ readonly providers: AsyncFluidObjectProvider<I["OptionalProviders"]>;
39
+ readonly initProps?: I["InitialState"];
40
+ }