/
engineClient.ts
356 lines (330 loc) · 8.93 KB
/
engineClient.ts
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import {
ConfigGetPayload,
ConfigWriteOpts,
DendronError,
DEngineClientV2,
DEngineDeleteSchemaRespV2,
DEngineInitRespV2,
DEngineV2,
DLink,
DNodePropsV2,
DVault,
EngineDeleteNoteResp,
EngineDeleteOptsV2,
EngineUpdateNodesOptsV2,
EngineWriteOptsV2,
ERROR_CODES,
GetNoteOptsV2,
GetNotePayloadV2,
NoteChangeEntry,
NotePropsDictV2,
NotePropsV2,
NoteUtilsV2,
QueryNotesOpts,
RenameNoteOptsV2,
RenameNotePayload,
RespV2,
SchemaModuleDictV2,
SchemaModulePropsV2,
SchemaQueryResp,
SchemaUtilsV2,
WriteNoteResp,
} from "@dendronhq/common-all";
import {
createLogger,
DendronAPI,
DLogger,
VaultUtils,
} from "@dendronhq/common-server";
import fs from "fs-extra";
import _ from "lodash";
import { FileStorageV2 } from "../lib";
import { FuseEngine } from "./fuseEngine";
import { HistoryService } from "./history";
import { getPortFilePath } from "./utils";
type DendronEngineClientOpts = {
vaults: string[];
ws: string;
};
export class DendronEngineClient implements DEngineClientV2 {
public notes: NotePropsDictV2;
public wsRoot: string;
public schemas: SchemaModuleDictV2;
public vaults: string[];
public links: DLink[];
public ws: string;
public fuseEngine: FuseEngine;
public api: DendronAPI;
public vaultsv3: DVault[];
public configRoot: string;
public history?: HistoryService;
public logger: DLogger;
public store: FileStorageV2;
static create({
port,
vaults,
ws,
history,
}: {
port: number | string;
history?: HistoryService;
} & DendronEngineClientOpts) {
const api = new DendronAPI({
endpoint: `http://localhost:${port}`,
apiPath: "api",
});
return new DendronEngineClient({ api, vaults, ws, history });
}
static getPort({ wsRoot }: { wsRoot: string }): number {
const portFile = getPortFilePath({ wsRoot });
if (!fs.pathExistsSync(portFile)) {
throw new DendronError({ msg: "no port file" });
}
return _.toInteger(_.trim(fs.readFileSync(portFile, { encoding: "utf8" })));
}
constructor({
api,
vaults,
ws,
history,
logger,
}: {
api: DendronAPI;
vaults: string[];
ws: string;
history?: HistoryService;
logger?: DLogger;
}) {
this.api = api;
this.notes = {};
this.schemas = {};
this.links = [];
this.fuseEngine = new FuseEngine({});
this.vaults = vaults;
this.vaultsv3 = vaults.map((ent) => ({ fsPath: ent }));
this.wsRoot = ws;
this.ws = ws;
this.configRoot = this.wsRoot;
this.history = history;
this.logger = logger || createLogger();
this.store = new FileStorageV2({
wsRoot: this.ws,
vaultsv3: this.vaultsv3,
logger: this.logger,
});
}
/**
* Load all nodes
*/
async init(): Promise<DEngineInitRespV2> {
const resp = await this.api.workspaceInit({
uri: this.ws,
config: { vaults: this.vaults },
});
if (resp.error && resp.error.code !== ERROR_CODES.MINOR) {
return {
error: resp.error,
data: { notes: {}, schemas: {} },
};
}
if (!resp.data) {
throw new DendronError({ msg: "no data" });
}
const { notes, schemas } = resp.data;
this.notes = notes;
this.schemas = schemas;
await this.fuseEngine.updateNotesIndex(notes);
await this.fuseEngine.updateSchemaIndex(schemas);
this.store.notes = notes;
this.store.schemas = schemas;
return {
error: resp.error,
data: { notes, schemas },
};
}
async deleteNote(
id: string,
opts?: EngineDeleteOptsV2
): Promise<EngineDeleteNoteResp> {
const ws = this.ws;
const resp = await this.api.engineDelete({ id, opts, ws });
if (!resp.data) {
throw new DendronError({ msg: "no data" });
}
await this.refreshNotesV2(resp.data);
return {
error: null,
data: resp.data,
};
}
async deleteSchema(
id: string,
opts?: EngineDeleteOptsV2
): Promise<DEngineDeleteSchemaRespV2> {
const ws = this.ws;
const resp = await this.api.schemaDelete({ id, opts, ws });
delete this.schemas[id];
if (!resp?.data?.notes || !resp?.data?.schemas) {
throw new DendronError({ msg: "bad delete operation" });
}
const { notes, schemas } = resp.data;
this.notes = notes;
this.schemas = schemas;
this.fuseEngine.updateNotesIndex(notes);
this.fuseEngine.updateSchemaIndex(schemas);
return {
error: null,
data: resp.data,
};
}
async getConfig(): Promise<RespV2<ConfigGetPayload>> {
const resp = await this.api.configGet({
ws: this.ws,
});
return resp;
}
async getNoteByPath(opts: GetNoteOptsV2): Promise<RespV2<GetNotePayloadV2>> {
const resp = await this.api.engineGetNoteByPath({
...opts,
ws: this.ws,
});
if (!_.isUndefined(resp.data)) {
await this.refreshNotesV2(resp.data.changed);
}
return resp;
}
async queryNote(
opts: Parameters<DEngineClientV2["queryNotes"]>[0]
): Promise<NotePropsV2[]> {
const { qs, vault } = opts;
let noteIndexProps = await this.fuseEngine.queryNote({ qs });
// TODO: hack
if (!_.isUndefined(vault)) {
noteIndexProps = noteIndexProps.filter((ent) =>
VaultUtils.isEqual(vault, ent.vault, this.wsRoot)
);
}
return noteIndexProps.map((ent) => this.notes[ent.id]);
}
async queryNotes(opts: QueryNotesOpts) {
const items = await this.queryNote(opts);
return {
data: items,
error: null,
};
}
async buildNotes() {}
queryNotesSync({ qs }: { qs: string }) {
const items = this.fuseEngine.queryNote({ qs });
return {
error: null,
data: items.map((ent) => this.notes[ent.id]),
};
}
async refreshNotes(notes: NotePropsV2[]) {
notes.forEach((node: DNodePropsV2) => {
const { id } = node;
this.notes[id] = node;
});
this.fuseEngine.updateNotesIndex(this.notes);
}
async refreshNotesV2(notes: NoteChangeEntry[]) {
notes.forEach((ent: NoteChangeEntry) => {
const { id } = ent.note;
const uri = NoteUtilsV2.getURI({ note: ent.note, wsRoot: this.wsRoot });
if (ent.status === "delete") {
delete this.notes[id];
this.history &&
this.history.add({ source: "engine", action: "delete", uri });
} else {
if (ent.status === "create") {
this.history &&
this.history.add({ source: "engine", action: "create", uri });
}
this.notes[id] = ent.note;
}
});
this.fuseEngine.updateNotesIndex(this.notes);
}
async refreshSchemas(smods: SchemaModulePropsV2[]) {
smods.forEach((smod) => {
const id = SchemaUtilsV2.getModuleRoot(smod).id;
this.schemas[id] = smod;
});
}
async renameNote(opts: RenameNoteOptsV2): Promise<RespV2<RenameNotePayload>> {
const resp = await this.api.engineRenameNote({ ...opts, ws: this.ws });
await this.refreshNotesV2(resp.data as NoteChangeEntry[]);
return resp;
}
async sync(): Promise<DEngineInitRespV2> {
const resp = await this.api.workspaceSync({ ws: this.ws });
if (!resp.data) {
throw new DendronError({ msg: "no data" });
}
const { notes, schemas } = resp.data;
this.notes = notes;
this.schemas = schemas;
await this.fuseEngine.updateNotesIndex(notes);
await this.fuseEngine.updateSchemaIndex(schemas);
return {
error: resp.error,
data: { notes, schemas },
};
}
async updateNote(
note: NotePropsV2,
opts?: EngineUpdateNodesOptsV2
): Promise<void> {
await this.api.engineUpdateNote({ ws: this.ws, note, opts });
const maybeNote = this.notes[note.id];
if (maybeNote) {
note = { ...maybeNote, ...note };
}
await this.refreshNotes([note]);
return;
}
async writeNote(
note: NotePropsV2,
opts?: EngineWriteOptsV2
): Promise<WriteNoteResp> {
const resp = await this.api.engineWrite({
node: note,
opts,
ws: this.ws,
});
let changed = resp.data;
// we are updating in place, remove deletes
if (opts?.updateExisting) {
changed = _.reject(changed, (ent) => ent.status === "delete");
}
await this.refreshNotesV2(changed);
return resp;
}
// ~~~ schemas
async getSchema(_qs: string): Promise<RespV2<SchemaModulePropsV2>> {
throw Error("not implemetned");
}
async querySchema(qs: string): Promise<SchemaQueryResp> {
const out = await this.api.schemaQuery({ qs, ws: this.ws });
return _.defaults(out, { data: [] });
}
async updateSchema(schema: SchemaModulePropsV2): Promise<void> {
await this.api.schemaUpdate({ schema, ws: this.ws });
await this.refreshSchemas([schema]);
return;
}
async writeConfig(
opts: ConfigWriteOpts
): ReturnType<DEngineV2["writeConfig"]> {
await this.api.configWrite({ ...opts, ws: this.ws });
return {
error: null,
};
}
async writeSchema(schema: SchemaModulePropsV2): Promise<void> {
await this.api.schemaWrite({ schema, ws: this.ws });
await this.refreshSchemas([schema]);
return;
}
}