summaryrefslogtreecommitdiff
path: root/apps/web/src/project/transfer/migrate.ts
blob: 14f597904c4c839be232a8e614a25ad9bbb49e8d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import type { StorageMigration } from "@/services/storage/migrations/base";
import type { ProjectRecord } from "@/services/storage/migrations/transformers/types";
import { getProjectId } from "@/services/storage/migrations/transformers/utils";

/**
 * In-memory counterpart to `runStorageMigrations`: applies the same migration
 * registry to a single project record (e.g. parsed from an imported project
 * archive) without touching IndexedDB.
 */

export function getRecordVersion({
	project,
}: {
	project: ProjectRecord;
}): number {
	const versionValue = project.version;
	if (typeof versionValue === "number") {
		return versionValue;
	}

	const scenesValue = project.scenes;
	if (Array.isArray(scenesValue) && scenesValue.length > 0) {
		return 1;
	}

	return 0;
}

export interface MigratedProjectRecord {
	project: ProjectRecord;
	fromVersion: number;
	toVersion: number;
	complete: boolean;
}

export async function migrateProjectRecord({
	project,
	migrations,
}: {
	project: ProjectRecord;
	migrations: StorageMigration[];
}): Promise<MigratedProjectRecord> {
	const orderedMigrations = [...migrations].sort((a, b) => a.from - b.from);
	const fromVersion = getRecordVersion({ project });
	const targetVersion = orderedMigrations.at(-1)?.to ?? fromVersion;

	let currentVersion = fromVersion;
	let record = project;
	const projectId = getProjectId({ project: record }) ?? "imported-project";

	for (const migration of orderedMigrations) {
		if (migration.from !== currentVersion) {
			continue;
		}

		const result = await migration.run({
			projectId,
			project: record,
		});

		if (result.skipped) {
			break;
		}

		record = result.project;
		currentVersion = migration.to;
	}

	return {
		project: record,
		fromVersion,
		toVersion: currentVersion,
		complete: currentVersion >= targetVersion,
	};
}