forked from microsoft/FluidFramework
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathutils.ts
More file actions
262 lines (244 loc) · 8.15 KB
/
utils.ts
File metadata and controls
262 lines (244 loc) · 8.15 KB
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
/*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
// This is a node powered CLI application, so using node makes sense:
/* eslint-disable unicorn/no-process-exit */
/* eslint-disable import-x/no-nodejs-modules */
import { readFileSync, writeFileSync } from "node:fs";
import type { IFluidHandle } from "@fluidframework/core-interfaces";
import type { SerializedIdCompressorWithOngoingSession } from "@fluidframework/id-compressor/legacy";
import {
createIdCompressor,
deserializeIdCompressor,
} from "@fluidframework/id-compressor/legacy";
import { isFluidHandle } from "@fluidframework/runtime-utils";
import { TreeArrayNode, type InsertableTypedNode } from "@fluidframework/tree";
import {
extractPersistedSchema,
FluidClientVersion,
independentInitializedView,
FormatValidatorBasic,
type ForestOptions,
type ICodecOptions,
type JsonCompatible,
type VerboseTree,
type ViewContent,
type ConciseTree,
TreeAlpha,
KeyEncodingOptions,
} from "@fluidframework/tree/alpha";
import { TreeBeta } from "@fluidframework/tree/beta";
import { type Static, Type } from "@sinclair/typebox";
import type { Item } from "./schema.js";
import { config, List } from "./schema.js";
/**
* Examples showing how to import data in a variety of formats.
*
* @param source - What data to load.
* If "default" or `undefined` data will come from a hard coded small default tree.
* Otherwise assumed to be a file path ending in a file matching `*.FORMAT.json` where format defines how to parse the file.
* See implementation for supported formats and how they are encoded.
*/
export function loadDocument(source: string | undefined): List {
if (source === undefined || source === "default") {
return new List([{ name: "default", position: { x: 0, y: 0 } }]);
}
const parts = source.split(".");
if (parts.length < 3 || parts.at(-1) !== "json") {
console.log(`Invalid source: ${source}`);
process.exit(1);
}
// Data parsed from JSON is safe to consider JsonCompatible.
// If file is invalid JSON, that will throw and is fine for this app.
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const fileData: JsonCompatible = JSON.parse(readFileSync(source).toString());
switch (parts.at(-2)) {
case "concise": {
return TreeBeta.importConcise(List, fileData as ConciseTree);
}
case "verbose": {
return TreeAlpha.importVerbose(List, fileData as VerboseTree);
}
case "verbose-stored": {
return TreeAlpha.importVerbose(List, fileData as VerboseTree, {
keys: KeyEncodingOptions.knownStoredKeys,
});
}
case "compressed": {
return TreeAlpha.importCompressed(List, fileData, {
jsonValidator: FormatValidatorBasic,
});
}
case "snapshot": {
// TODO: This should probably do a validating parse of the data (probably using type box) rather than just casting it.
const combo: File = fileData as File;
const content: ViewContent = {
schema: combo.schema,
tree: combo.tree,
idCompressor: deserializeIdCompressor(combo.idCompressor),
};
const view = independentInitializedView(config, options, content);
return view.root;
}
default: {
console.log(`Invalid source format: ${parts.at(-2)}`);
process.exit(1);
}
}
}
/**
* Examples showing how to export data in a variety of formats.
*
* @param destination - Where to save the data, and in what format.
* If `undefined` data will logged to the console.
* Otherwise see {@link exportContent}.
*/
export function saveDocument(destination: string | undefined, tree: List): void {
if (destination === undefined || destination === "default") {
console.log("Tree Content:");
console.log(tree);
return;
}
const parts = destination.split(".");
if (parts.length < 3 || parts.at(-1) !== "json") {
console.log(`Invalid destination: ${destination}`);
process.exit(1);
}
const fileData: JsonCompatible = exportContent(destination, tree);
console.log(`Writing: ${destination}`);
writeFileSync(destination, JSON.stringify(fileData, rejectHandles));
}
/**
* Oldest version of the Fluid Framework client that is supported for reading data output by this app.
*/
const compatVersion = FluidClientVersion.v2_0;
/**
* Examples showing how to export data in a variety of formats.
*
* @param destination - File path used to select the format.
* Assumed to be a file path ending in a file matching `*.FORMAT.json` where format defines how to parse the file.
* See implementation for supported formats and how they are encoded.
*/
export function exportContent(destination: string, tree: List): JsonCompatible {
const parts = destination.split(".");
if (parts.length < 3 || parts.at(-1) !== "json") {
console.log(`Invalid destination: ${destination}`);
process.exit(1);
}
switch (parts.at(-2)) {
case "concise": {
return TreeBeta.exportConcise(tree) as JsonCompatible;
}
case "verbose": {
return TreeAlpha.exportVerbose(tree) as JsonCompatible;
}
case "concise-stored": {
return TreeBeta.exportConcise(tree, {
keys: KeyEncodingOptions.knownStoredKeys,
}) as JsonCompatible;
}
case "verbose-stored": {
return TreeAlpha.exportVerbose(tree, {
keys: KeyEncodingOptions.knownStoredKeys,
}) as JsonCompatible;
}
case "compressed": {
return TreeAlpha.exportCompressed(tree, {
...options,
minVersionForCollab: compatVersion,
}) as JsonCompatible;
}
case "snapshot": {
// TODO: This should be made better. See privateRemarks on TreeAlpha.exportCompressed.
const idCompressor = createIdCompressor();
const file: File = {
tree: TreeAlpha.exportCompressed(tree, {
minVersionForCollab: compatVersion,
idCompressor,
}),
schema: extractPersistedSchema(config.schema, compatVersion, () => true),
idCompressor: idCompressor.serialize(true),
};
return file as JsonCompatible;
}
default: {
console.log(`Invalid source format: ${parts.at(-2)}`);
process.exit(1);
}
}
}
/**
* Example of editing a tree.
* This allows for some basic editing of `list` sufficient to add and remove items to create trees of different sizes.
*
* This interprets `edits` as a comma separated list of edits to apply to `tree`.
*
* Each edit is in the format `kind:count`.
* Count is a number and indicates how many nodes to add when positive, and how many to remove when negative.
*
* Positive numbers have valid kinds of "string" and "item" to insert that many strings or items to `list`.
* Negative numbers have valid kinds of "start" or "end" to indicate if the items should be removed from the start or end of `list`.
*/
export function applyEdit(edits: string, list: List): void {
for (const edit of edits.split(",")) {
console.log(`Applying edit ${edit}`);
const parts = edit.split(":");
if (parts.length !== 2) {
throw new Error(`Invalid edit ${edit}`);
}
const [kind, countString] = parts;
const count = Number(countString);
if (count === 0 || !Number.isInteger(count)) {
throw new TypeError(`Invalid count in edit ${edit}`);
}
if (count > 0) {
let data: InsertableTypedNode<typeof Item> | string;
switch (kind) {
case "string": {
data = "x";
break;
}
case "item": {
data = { position: { x: 0, y: 0 }, name: "item" };
break;
}
default: {
throw new TypeError(`Invalid kind in insert edit ${edit}`);
}
}
// eslint-disable-next-line unicorn/no-new-array
list.insertAtEnd(TreeArrayNode.spread(new Array(count).fill(data)));
} else {
switch (kind) {
case "start": {
list.removeRange(0, -count);
break;
}
case "end": {
list.removeRange(list.length + count, -count);
break;
}
default: {
throw new TypeError(`Invalid end in remove edit ${edit}`);
}
}
}
}
}
/**
* Throw if handle.
*/
export function rejectHandles(key: string, value: unknown): unknown {
if (isFluidHandle(value)) {
throw new Error("Fluid handles are not supported");
}
return value;
}
const options: ForestOptions & ICodecOptions = { jsonValidator: FormatValidatorBasic };
const File = Type.Object({
tree: Type.Unsafe<JsonCompatible<IFluidHandle>>(),
schema: Type.Unsafe<JsonCompatible>(),
idCompressor: Type.Unsafe<SerializedIdCompressorWithOngoingSession>(),
});
type File = Static<typeof File>;