@dxos/migrations 0.10.0 → 0.11.0

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.
@@ -0,0 +1,325 @@
1
+ import * as Schema from "effect/Schema";
2
+ import { Annotation, Obj } from "@dxos/echo";
3
+ import { SpaceState } from "@dxos/client/echo";
4
+ import { invariant } from "@dxos/invariant";
5
+ import { next, toJS } from "@automerge/automerge";
6
+ import { CreateEpochRequest } from "@dxos/client/halo";
7
+ import { ObjectCore, migrateDocument } from "@dxos/echo-client/internal";
8
+ import { EncodedReference, SpaceDocVersion } from "@dxos/echo-protocol";
9
+ import { getSchemaURI } from "@dxos/echo/internal";
10
+ import * as Type from "@dxos/echo/Type";
11
+ import { EID, EntityId } from "@dxos/keys";
12
+ import { Atom } from "@effect-atom/atom";
13
+ import * as Registry from "@effect-atom/atom/Registry";
14
+ import * as Option from "effect/Option";
15
+ //#region src/annotations.ts
16
+ /** Migration version stored on space properties meta. */
17
+ var MigrationVersionAnnotation = Annotation.make({
18
+ id: "org.dxos.migrations.version",
19
+ schema: Schema.String
20
+ });
21
+ //#endregion
22
+ //#region src/migration-builder.ts
23
+ var __dxlog_file$2 = "/__w/dxos/dxos/packages/sdk/migrations/src/migration-builder.ts";
24
+ var MigrationBuilder = class {
25
+ _space;
26
+ _repo;
27
+ _rootDoc;
28
+ _newLinks = {};
29
+ _flushIds = [];
30
+ _deleteObjects = [];
31
+ _newRoot = void 0;
32
+ constructor(_space) {
33
+ this._space = _space;
34
+ this._repo = this._space.internal.db._repo;
35
+ const rootDoc = this._space.internal.db._getSpaceRootDocHandle().doc();
36
+ invariant(rootDoc, "Space root document must be available when creating MigrationBuilder", {
37
+ "~LogMeta": "~LogMeta",
38
+ F: __dxlog_file$2,
39
+ L: 51,
40
+ S: this,
41
+ A: ["rootDoc", "'Space root document must be available when creating MigrationBuilder'"]
42
+ });
43
+ this._rootDoc = rootDoc;
44
+ }
45
+ async findObject(id) {
46
+ const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString();
47
+ const docHandle = documentId && this._repo.find(documentId);
48
+ if (!docHandle) return;
49
+ await docHandle.whenReady();
50
+ return docHandle.doc().objects?.[id];
51
+ }
52
+ async migrateObject(id, migrate) {
53
+ const objectStructure = await this.findObject(id);
54
+ if (!objectStructure) return;
55
+ const { type, props } = await migrate(objectStructure);
56
+ const schema = Type.getSchema(type);
57
+ const oldHandle = await this._findObjectContainingHandle(id);
58
+ invariant(oldHandle, void 0, {
59
+ "~LogMeta": "~LogMeta",
60
+ F: __dxlog_file$2,
61
+ L: 80,
62
+ S: this,
63
+ A: ["oldHandle", ""]
64
+ });
65
+ const newState = {
66
+ version: SpaceDocVersion.CURRENT,
67
+ access: this._makeAccess(),
68
+ objects: { [id]: {
69
+ system: { type: EncodedReference.fromURI(getSchemaURI(schema)) },
70
+ data: props,
71
+ meta: { keys: [] }
72
+ } }
73
+ };
74
+ const migratedDoc = migrateDocument(oldHandle.doc(), newState);
75
+ const newHandle = this._repo.import(next.save(migratedDoc));
76
+ await newHandle.whenReady();
77
+ invariant(newHandle.url, "Migrated document URL not available after whenReady", {
78
+ "~LogMeta": "~LogMeta",
79
+ F: __dxlog_file$2,
80
+ L: 100,
81
+ S: this,
82
+ A: ["newHandle.url", "'Migrated document URL not available after whenReady'"]
83
+ });
84
+ this._newLinks[id] = newHandle.url;
85
+ this._addHandleToFlushList(newHandle.documentId);
86
+ }
87
+ async addObject(type, props) {
88
+ const resolved = Type.getSchema(type);
89
+ return (await this._createObject({
90
+ schema: resolved,
91
+ props
92
+ })).id;
93
+ }
94
+ createReference(id) {
95
+ invariant(EntityId.isValid(id), "Invalid EntityId.", {
96
+ "~LogMeta": "~LogMeta",
97
+ F: __dxlog_file$2,
98
+ L: 112,
99
+ S: this,
100
+ A: ["EntityId.isValid(id)", "'Invalid EntityId.'"]
101
+ });
102
+ return EncodedReference.fromURI(EID.make({ entityId: id }));
103
+ }
104
+ deleteObject(id) {
105
+ this._deleteObjects.push(id);
106
+ }
107
+ /**
108
+ * Re-materializes linked object documents into fresh Automerge docs without history.
109
+ * Call {@link _commit} to publish a new space epoch with updated root links.
110
+ */
111
+ async compactLinkedDocuments(objectIds) {
112
+ const linkIds = objectIds ?? Object.keys(this._rootDoc.links ?? {});
113
+ const compacted = [];
114
+ const skipped = [];
115
+ for (const id of linkIds) {
116
+ const oldHandle = await this._findObjectContainingHandle(id);
117
+ if (!oldHandle) {
118
+ skipped.push(id);
119
+ continue;
120
+ }
121
+ await oldHandle.whenReady();
122
+ const materialized = toJS(oldHandle.doc());
123
+ materialized.access = this._makeAccess();
124
+ const newHandle = this._repo.create(materialized);
125
+ await newHandle.whenReady();
126
+ invariant(newHandle.url, "Compacted document URL not available after whenReady", {
127
+ "~LogMeta": "~LogMeta",
128
+ F: __dxlog_file$2,
129
+ L: 142,
130
+ S: this,
131
+ A: ["newHandle.url", "'Compacted document URL not available after whenReady'"]
132
+ });
133
+ this._newLinks[id] = newHandle.url;
134
+ this._addHandleToFlushList(newHandle.documentId);
135
+ compacted.push(id);
136
+ }
137
+ return {
138
+ compacted,
139
+ skipped
140
+ };
141
+ }
142
+ async changeProperties(changeFn) {
143
+ if (!this._newRoot) await this._buildNewRoot();
144
+ invariant(this._newRoot, "New root not created", {
145
+ "~LogMeta": "~LogMeta",
146
+ F: __dxlog_file$2,
147
+ L: 155,
148
+ S: this,
149
+ A: ["this._newRoot", "'New root not created'"]
150
+ });
151
+ this._newRoot.change((doc) => {
152
+ const propertiesStructure = doc.objects?.[this._space.properties.id];
153
+ propertiesStructure && changeFn(propertiesStructure);
154
+ });
155
+ await this._newRoot.whenReady();
156
+ this._addHandleToFlushList(this._newRoot.documentId);
157
+ }
158
+ /**
159
+ * @internal
160
+ */
161
+ async _commit() {
162
+ if (!this._newRoot) await this._buildNewRoot();
163
+ invariant(this._newRoot, "New root not created", {
164
+ "~LogMeta": "~LogMeta",
165
+ F: __dxlog_file$2,
166
+ L: 172,
167
+ S: this,
168
+ A: ["this._newRoot", "'New root not created'"]
169
+ });
170
+ await this._space.db.flush();
171
+ invariant(this._newRoot.url, "New root URL not available", {
172
+ "~LogMeta": "~LogMeta",
173
+ F: __dxlog_file$2,
174
+ L: 177,
175
+ S: this,
176
+ A: ["this._newRoot.url", "'New root URL not available'"]
177
+ });
178
+ await this._space.internal.createEpoch({
179
+ migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,
180
+ automergeRootUrl: this._newRoot.url
181
+ });
182
+ }
183
+ async _findObjectContainingHandle(id) {
184
+ const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString();
185
+ const docHandle = documentId && this._repo.find(documentId);
186
+ if (!docHandle) return;
187
+ await docHandle.whenReady();
188
+ return docHandle;
189
+ }
190
+ async _buildNewRoot() {
191
+ const links = { ...this._rootDoc.links ?? {} };
192
+ for (const id of this._deleteObjects) delete links[id];
193
+ for (const [id, url] of Object.entries(this._newLinks)) links[id] = new next.RawString(url);
194
+ this._newRoot = this._repo.create({
195
+ version: SpaceDocVersion.CURRENT,
196
+ access: this._makeAccess(),
197
+ objects: this._rootDoc.objects,
198
+ links
199
+ });
200
+ await this._newRoot.whenReady();
201
+ this._addHandleToFlushList(this._newRoot.documentId);
202
+ }
203
+ async _createObject({ id, schema, props }) {
204
+ const core = new ObjectCore();
205
+ if (id) core.id = id;
206
+ core.initNewObject(props);
207
+ core.setType(EncodedReference.fromURI(getSchemaURI(schema)));
208
+ const newHandle = this._repo.create({
209
+ version: SpaceDocVersion.CURRENT,
210
+ access: this._makeAccess(),
211
+ objects: { [core.id]: core.getDoc() }
212
+ });
213
+ await newHandle.whenReady();
214
+ this._newLinks[core.id] = newHandle.url;
215
+ this._addHandleToFlushList(newHandle.documentId);
216
+ return core;
217
+ }
218
+ _makeAccess() {
219
+ return {
220
+ spaceId: this._space.id,
221
+ spaceKey: this._space.key.toHex()
222
+ };
223
+ }
224
+ _addHandleToFlushList(id) {
225
+ this._flushIds.push(id);
226
+ }
227
+ };
228
+ //#endregion
229
+ //#region src/document-compaction.ts
230
+ var __dxlog_file$1 = "/__w/dxos/dxos/packages/sdk/migrations/src/document-compaction.ts";
231
+ /**
232
+ * Re-materializes linked object documents into fresh Automerge docs (no history) and commits
233
+ * a new space epoch with {@link CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT}.
234
+ */
235
+ var compactDocumentsEpochMigration = async (space, options = {}) => {
236
+ invariant(space.state.get() === SpaceState.SPACE_READY, "Space must be open and ready before compaction.", {
237
+ "~LogMeta": "~LogMeta",
238
+ F: __dxlog_file$1,
239
+ L: 32,
240
+ S: void 0,
241
+ A: ["space.state.get() === SpaceState.SPACE_READY", "'Space must be open and ready before compaction.'"]
242
+ });
243
+ const builder = new MigrationBuilder(space);
244
+ const { compacted, skipped } = await builder.compactLinkedDocuments(options.objectIds);
245
+ await builder._commit();
246
+ const epochs = await space.internal.getEpochs();
247
+ return {
248
+ compacted,
249
+ skipped,
250
+ epochNumber: epochs[epochs.length - 1]?.subject.assertion.number ?? 0
251
+ };
252
+ };
253
+ //#endregion
254
+ //#region src/migrations.ts
255
+ var __dxlog_file = "/__w/dxos/dxos/packages/sdk/migrations/src/migrations.ts";
256
+ var Migrations = class {
257
+ static namespace;
258
+ static migrations = [];
259
+ static _registry = Registry.make();
260
+ static _stateAtom = Atom.make({ running: [] }).pipe(Atom.keepAlive);
261
+ /**
262
+ * @deprecated Use `MigrationVersionAnnotation` via `Annotation.get/set` on space properties.
263
+ */
264
+ static get versionProperty() {
265
+ return this.namespace && `${this.namespace}.version`;
266
+ }
267
+ static get targetVersion() {
268
+ return this.migrations[this.migrations.length - 1]?.version;
269
+ }
270
+ static running(space) {
271
+ return this._registry.get(this._stateAtom).running.includes(space.key.toHex());
272
+ }
273
+ static define(namespace, migrations) {
274
+ this.namespace = namespace;
275
+ this.migrations = migrations;
276
+ }
277
+ static async migrate(space, targetVersion) {
278
+ invariant(!this.running(space), "Migration already running", {
279
+ "~LogMeta": "~LogMeta",
280
+ F: __dxlog_file,
281
+ L: 55,
282
+ S: this,
283
+ A: ["!this.running(space)", "'Migration already running'"]
284
+ });
285
+ invariant(space.state.get() === SpaceState.SPACE_READY, "Space not ready", {
286
+ "~LogMeta": "~LogMeta",
287
+ F: __dxlog_file,
288
+ L: 56,
289
+ S: this,
290
+ A: ["space.state.get() === SpaceState.SPACE_READY", "'Space not ready'"]
291
+ });
292
+ const currentVersion = Annotation.get(space.properties, MigrationVersionAnnotation).pipe(Option.getOrUndefined);
293
+ const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;
294
+ const i = this.migrations.findIndex((m) => m.version === targetVersion);
295
+ const targetIndex = i === -1 ? this.migrations.length : i + 1;
296
+ if (currentIndex === targetIndex) return false;
297
+ const spaceKey = space.key.toHex();
298
+ const currentState = this._registry.get(this._stateAtom);
299
+ this._registry.set(this._stateAtom, { running: [...currentState.running, spaceKey] });
300
+ try {
301
+ if (targetIndex > currentIndex) {
302
+ const migrations = this.migrations.slice(currentIndex, targetIndex);
303
+ for (const migration of migrations) {
304
+ const builder = new MigrationBuilder(space);
305
+ await migration.next({
306
+ space,
307
+ builder
308
+ });
309
+ await builder._commit();
310
+ Obj.update(space.properties, (properties) => {
311
+ Annotation.set(properties, MigrationVersionAnnotation, migration.version);
312
+ });
313
+ }
314
+ }
315
+ } finally {
316
+ const finalState = this._registry.get(this._stateAtom);
317
+ this._registry.set(this._stateAtom, { running: finalState.running.filter((key) => key !== spaceKey) });
318
+ }
319
+ return true;
320
+ }
321
+ };
322
+ //#endregion
323
+ export { MigrationBuilder, MigrationVersionAnnotation, Migrations, compactDocumentsEpochMigration };
324
+
325
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/annotations.ts","../../src/migration-builder.ts","../../src/document-compaction.ts","../../src/migrations.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Schema from 'effect/Schema';\n\nimport { Annotation } from '@dxos/echo';\n\n/** Migration version stored on space properties meta. */\nexport const MigrationVersionAnnotation = Annotation.make({\n id: 'org.dxos.migrations.version',\n schema: Schema.String,\n});\n","//\n// Copyright 2024 DXOS.org\n//\n\nimport { next as A, type Doc, toJS } from '@automerge/automerge';\nimport { type AnyDocumentId, type DocumentId } from '@automerge/automerge-repo';\nimport type * as Schema from 'effect/Schema';\n\nimport { type Space } from '@dxos/client/echo';\nimport { CreateEpochRequest } from '@dxos/client/halo';\nimport { type DocHandleProxy, ObjectCore, type RepoProxy, migrateDocument } from '@dxos/echo-client/internal';\nimport { type DatabaseDirectory, EncodedReference, type EntityStructure, SpaceDocVersion } from '@dxos/echo-protocol';\nimport { getSchemaURI } from '@dxos/echo/internal';\nimport * as Type from '@dxos/echo/Type';\nimport { invariant } from '@dxos/invariant';\nimport { EID, EntityId } from '@dxos/keys';\nimport { type MaybePromise } from '@dxos/util';\n\n/*\n\nConsidering a better API for this:\n\n```ts\nconst migration = space.db.beginMigration(); // all actions are not visible to queries and are only applied once you call `apply`\n\nmigration.applyObjectMigration(defineMigration(From, To, { ... }));\n\nmigration.delete(id);\nmigration.add(obj);\n\nawait migration.apply(); // Will create new epoch.\n```\n\n*/\n\n// TODO(dmaretskyi): We no longer need to hook into ECHO internals, with the changes to echo APIs.\nexport class MigrationBuilder {\n private readonly _repo: RepoProxy;\n private readonly _rootDoc: Doc<DatabaseDirectory>;\n\n // echoUri -> automergeUrl\n private readonly _newLinks: Record<string, string> = {};\n private readonly _flushIds: DocumentId[] = [];\n private readonly _deleteObjects: string[] = [];\n\n private _newRoot?: DocHandleProxy<DatabaseDirectory> = undefined;\n\n constructor(private readonly _space: Space) {\n this._repo = this._space.internal.db._repo;\n const rootDoc = this._space.internal.db._getSpaceRootDocHandle().doc();\n invariant(rootDoc, 'Space root document must be available when creating MigrationBuilder');\n this._rootDoc = rootDoc;\n }\n\n async findObject(id: string): Promise<EntityStructure | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n const doc = docHandle.doc() as Doc<DatabaseDirectory>;\n return doc.objects?.[id];\n }\n\n async migrateObject(\n id: string,\n migrate: (objectStructure: EntityStructure) => MaybePromise<{ type: Type.AnyEntity; props: any }>,\n ): Promise<void> {\n const objectStructure = await this.findObject(id);\n if (!objectStructure) {\n return;\n }\n\n const { type, props } = await migrate(objectStructure);\n const schema = Type.getSchema(type);\n\n const oldHandle = await this._findObjectContainingHandle(id);\n invariant(oldHandle);\n\n const newState: DatabaseDirectory = {\n version: SpaceDocVersion.CURRENT,\n access: this._makeAccess(),\n objects: {\n [id]: {\n system: {\n type: EncodedReference.fromURI(getSchemaURI(schema)!),\n },\n data: props,\n meta: {\n keys: [],\n },\n },\n },\n };\n const migratedDoc = migrateDocument(oldHandle.doc() as Doc<DatabaseDirectory>, newState);\n const newHandle = this._repo.import<DatabaseDirectory>(A.save(migratedDoc));\n await newHandle.whenReady();\n invariant(newHandle.url, 'Migrated document URL not available after whenReady');\n this._newLinks[id] = newHandle.url;\n this._addHandleToFlushList(newHandle.documentId!);\n }\n\n async addObject(type: Type.AnyEntity, props: any): Promise<string> {\n const resolved = Type.getSchema(type);\n const core = await this._createObject({ schema: resolved, props });\n return core.id;\n }\n\n createReference(id: string) {\n invariant(EntityId.isValid(id), 'Invalid EntityId.');\n return EncodedReference.fromURI(EID.make({ entityId: id }));\n }\n\n deleteObject(id: string): void {\n this._deleteObjects.push(id);\n }\n\n /**\n * Re-materializes linked object documents into fresh Automerge docs without history.\n * Call {@link _commit} to publish a new space epoch with updated root links.\n */\n async compactLinkedDocuments(objectIds?: string[]): Promise<{ compacted: string[]; skipped: string[] }> {\n const linkIds = objectIds ?? Object.keys(this._rootDoc.links ?? {});\n const compacted: string[] = [];\n const skipped: string[] = [];\n\n for (const id of linkIds) {\n const oldHandle = await this._findObjectContainingHandle(id);\n if (!oldHandle) {\n skipped.push(id);\n continue;\n }\n\n await oldHandle.whenReady();\n const materialized = toJS(oldHandle.doc()!) as DatabaseDirectory;\n // Re-stamp access so documents that predate access.spaceId pick it up during compaction.\n materialized.access = this._makeAccess();\n const newHandle = this._repo.create<DatabaseDirectory>(materialized);\n await newHandle.whenReady();\n invariant(newHandle.url, 'Compacted document URL not available after whenReady');\n this._newLinks[id] = newHandle.url;\n this._addHandleToFlushList(newHandle.documentId!);\n compacted.push(id);\n }\n\n return { compacted, skipped };\n }\n\n async changeProperties(changeFn: (properties: EntityStructure) => void): Promise<void> {\n if (!this._newRoot) {\n await this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n this._newRoot.change((doc: DatabaseDirectory) => {\n const propertiesStructure = doc.objects?.[this._space.properties.id];\n propertiesStructure && changeFn(propertiesStructure);\n });\n await this._newRoot.whenReady();\n this._addHandleToFlushList(this._newRoot.documentId!);\n }\n\n /**\n * @internal\n */\n async _commit(): Promise<void> {\n if (!this._newRoot) {\n await this._buildNewRoot();\n }\n invariant(this._newRoot, 'New root not created');\n\n await this._space.db.flush();\n\n // Create new epoch.\n invariant(this._newRoot.url, 'New root URL not available');\n await this._space.internal.createEpoch({\n migration: CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT,\n automergeRootUrl: this._newRoot.url,\n });\n }\n\n private async _findObjectContainingHandle(id: string): Promise<DocHandleProxy<DatabaseDirectory> | undefined> {\n const documentId = (this._rootDoc.links?.[id] || this._newLinks[id])?.toString() as AnyDocumentId | undefined;\n const docHandle = documentId && this._repo.find(documentId);\n if (!docHandle) {\n return undefined;\n }\n\n await docHandle.whenReady();\n return docHandle;\n }\n\n private async _buildNewRoot(): Promise<void> {\n const links = { ...(this._rootDoc.links ?? {}) };\n for (const id of this._deleteObjects) {\n delete links[id];\n }\n\n for (const [id, url] of Object.entries(this._newLinks)) {\n links[id] = new A.RawString(url);\n }\n\n this._newRoot = this._repo.create<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: this._makeAccess(),\n objects: this._rootDoc.objects,\n links,\n });\n await this._newRoot.whenReady();\n this._addHandleToFlushList(this._newRoot.documentId!);\n }\n\n private async _createObject({\n id,\n schema,\n props,\n }: {\n id?: string;\n schema: Schema.Schema.AnyNoContext;\n props: any;\n }): Promise<ObjectCore> {\n const core = new ObjectCore();\n if (id) {\n core.id = id;\n }\n\n core.initNewObject(props);\n core.setType(EncodedReference.fromURI(getSchemaURI(schema)!));\n const newHandle = this._repo.create<DatabaseDirectory>({\n version: SpaceDocVersion.CURRENT,\n access: this._makeAccess(),\n objects: {\n [core.id]: core.getDoc() as EntityStructure,\n },\n });\n await newHandle.whenReady();\n this._newLinks[core.id] = newHandle.url!;\n this._addHandleToFlushList(newHandle.documentId!);\n\n return core;\n }\n\n private _makeAccess(): NonNullable<DatabaseDirectory['access']> {\n return {\n spaceId: this._space.id,\n // spaceKey is deprecated but still written so older clients can resolve the owning space.\n spaceKey: this._space.key.toHex(),\n };\n }\n\n private _addHandleToFlushList(id: DocumentId): void {\n this._flushIds.push(id);\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport { type Space, SpaceState } from '@dxos/client/echo';\nimport { invariant } from '@dxos/invariant';\n\nimport { MigrationBuilder } from './migration-builder';\n\nexport type CompactDocumentsOptions = {\n /**\n * Entity ids whose linked Automerge documents should be compacted.\n * Defaults to all ids in the space root `links` map.\n */\n objectIds?: string[];\n};\n\nexport type CompactDocumentsResult = {\n compacted: string[];\n skipped: string[];\n epochNumber: number;\n};\n\n/**\n * Re-materializes linked object documents into fresh Automerge docs (no history) and commits\n * a new space epoch with {@link CreateEpochRequest.Migration.REPLACE_AUTOMERGE_ROOT}.\n */\nexport const compactDocumentsEpochMigration = async (\n space: Space,\n options: CompactDocumentsOptions = {},\n): Promise<CompactDocumentsResult> => {\n invariant(space.state.get() === SpaceState.SPACE_READY, 'Space must be open and ready before compaction.');\n\n const builder = new MigrationBuilder(space);\n const { compacted, skipped } = await builder.compactLinkedDocuments(options.objectIds);\n await builder._commit();\n\n const epochs = await space.internal.getEpochs();\n const lastEpoch = epochs[epochs.length - 1];\n const epochNumber = lastEpoch?.subject.assertion.number ?? 0;\n\n return { compacted, skipped, epochNumber };\n};\n","//\n// Copyright 2023 DXOS.org\n//\n\nimport { Atom } from '@effect-atom/atom';\nimport * as Registry from '@effect-atom/atom/Registry';\nimport * as Option from 'effect/Option';\n\nimport { type Space, SpaceState } from '@dxos/client/echo';\nimport { Annotation, Obj } from '@dxos/echo';\nimport { invariant } from '@dxos/invariant';\nimport { type MaybePromise } from '@dxos/util';\n\nimport { MigrationVersionAnnotation } from './annotations';\nimport { MigrationBuilder } from './migration-builder';\n\nexport type MigrationContext = {\n space: Space;\n builder: MigrationBuilder;\n};\n\nexport type Migration = {\n version: string;\n next: (context: MigrationContext) => MaybePromise<void>;\n};\n\nexport class Migrations {\n static namespace?: string;\n static migrations: Migration[] = [];\n private static _registry = Registry.make();\n private static _stateAtom = Atom.make<{ running: string[] }>({ running: [] }).pipe(Atom.keepAlive);\n\n /**\n * @deprecated Use `MigrationVersionAnnotation` via `Annotation.get/set` on space properties.\n */\n static get versionProperty() {\n return this.namespace && `${this.namespace}.version`;\n }\n\n static get targetVersion() {\n return this.migrations[this.migrations.length - 1]?.version;\n }\n\n static running(space: Space): boolean {\n const state = this._registry.get(this._stateAtom);\n return state.running.includes(space.key.toHex());\n }\n\n static define(namespace: string, migrations: Migration[]): void {\n this.namespace = namespace;\n this.migrations = migrations;\n }\n\n static async migrate(space: Space, targetVersion?: string | number): Promise<boolean> {\n invariant(!this.running(space), 'Migration already running');\n invariant(space.state.get() === SpaceState.SPACE_READY, 'Space not ready');\n const currentVersion = Annotation.get(space.properties, MigrationVersionAnnotation).pipe(Option.getOrUndefined);\n const currentIndex = this.migrations.findIndex((m) => m.version === currentVersion) + 1;\n const i = this.migrations.findIndex((m) => m.version === targetVersion);\n const targetIndex = i === -1 ? this.migrations.length : i + 1;\n if (currentIndex === targetIndex) {\n return false;\n }\n\n const spaceKey = space.key.toHex();\n const currentState = this._registry.get(this._stateAtom);\n this._registry.set(this._stateAtom, { running: [...currentState.running, spaceKey] });\n try {\n if (targetIndex > currentIndex) {\n const migrations = this.migrations.slice(currentIndex, targetIndex);\n for (const migration of migrations) {\n const builder = new MigrationBuilder(space);\n await migration.next({ space, builder });\n await builder._commit();\n Obj.update(space.properties, (properties) => {\n Annotation.set(properties, MigrationVersionAnnotation, migration.version);\n });\n }\n }\n } finally {\n const finalState = this._registry.get(this._stateAtom);\n this._registry.set(this._stateAtom, { running: finalState.running.filter((key) => key !== spaceKey) });\n }\n\n return true;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AASA,IAAa,6BAA6B,WAAW,KAAK;CACxD,IAAI;CACJ,QAAQ,OAAO;AACjB,CAAC;;;;ACwBD,IAAa,mBAAb,MAA8B;CAWC;CAV7B;CACA;CAGA,YAAqD,CAAC;CACtD,YAA2C,CAAC;CAC5C,iBAA4C,CAAC;CAE7C,WAAuD,KAAA;CAEvD,YAAY,QAAgC;EAAf,KAAA,SAAA;EAC3B,KAAK,QAAQ,KAAK,OAAO,SAAS,GAAG;EACrC,MAAM,UAAU,KAAK,OAAO,SAAS,GAAG,uBAAuB,CAAC,CAAC,IAAI;EACrE,UAAU,SAAS,wEAAqE;GAAA,YAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA;GAAA,GAAA,CAAA,WAAA,wEAAA;EAAA,CAAC;EACzF,KAAK,WAAW;CAClB;CAEA,MAAM,WAAW,IAAkD;EACjE,MAAM,cAAc,KAAK,SAAS,QAAQ,OAAO,KAAK,UAAU,IAAA,EAAM,SAAS;EAC/E,MAAM,YAAY,cAAc,KAAK,MAAM,KAAK,UAAU;EAC1D,IAAI,CAAC,WACH;EAGF,MAAM,UAAU,UAAU;EAE1B,OADY,UAAU,IACf,CAAA,CAAI,UAAU;CACvB;CAEA,MAAM,cACJ,IACA,SACe;EACf,MAAM,kBAAkB,MAAM,KAAK,WAAW,EAAE;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Q,QAAQ;KACtB,IAAI,OAAO,MAAM,aAAa,eAAe;MAC3C,WAAW,IAAI,YAAY,4BAA4B,UAAU,OAAO;KAC1E,CAAC;IACH;GACF;EACF,UAAU;GACR,MAAM,aAAa,KAAK,UAAU,IAAI,KAAK,UAAU;GACrD,KAAK,UAAU,IAAI,KAAK,YAAY,EAAE,SAAS,WAAW,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,EAAE,CAAC;EACvG;EAEA,OAAO;CACT;AACF"}
@@ -31,6 +31,7 @@ export declare class MigrationBuilder {
31
31
  private _findObjectContainingHandle;
32
32
  private _buildNewRoot;
33
33
  private _createObject;
34
+ private _makeAccess;
34
35
  private _addHandleToFlushList;
35
36
  }
36
37
  //# sourceMappingURL=migration-builder.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"migration-builder.d.ts","sourceRoot":"","sources":["../../../src/migration-builder.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAG/C,OAAO,EAA0B,gBAAgB,EAAE,KAAK,eAAe,EAAmB,MAAM,qBAAqB,CAAC;AAEtH,OAAO,KAAK,IAAI,MAAM,iBAAiB,CAAC;AAGxC,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,YAAY,CAAC;AAoB/C,qBAAa,gBAAgB;IAWf,OAAO,CAAC,QAAQ,CAAC,MAAM;IAVnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAY;IAClC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAyB;IAGlD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA8B;IACxD,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAoB;IAC9C,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAgB;IAE/C,OAAO,CAAC,QAAQ,CAAC,CAAgD;IAEjE,YAA6B,MAAM,EAAE,KAAK,EAKzC;IAEK,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,GAA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