-
Notifications
You must be signed in to change notification settings - Fork 91
/
memoryFs.ts
655 lines (557 loc) · 18.7 KB
/
memoryFs.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import type { NodeishFilesystem, NodeishStats, FileChangeInfo } from "./NodeishFilesystemApi.js"
import { FilesystemError } from "./errors/FilesystemError.js"
import { normalizePath, getBasename, getDirname } from "./utilities/helpers.js"
type Inode = Uint8Array | Set<string> | { placeholder: true }
export type Snapshot = {
fsMap: {
[key: string]: string[] | string | { placeholder: true }
}
fsStats: {
[key: string]: {
ctimeMs: number
mtimeMs: number
dev: number
mode: number
uid: number
gid: number
size: number
_kind: number
_oid?: string
_rootHash?: string
}
}
}
export function toSnapshot(fs: NodeishFilesystem) {
return {
fsMap: Object.fromEntries(
[...fs._state.fsMap].map(([path, content]) => {
let serializedContent
if (content instanceof Set) {
serializedContent = [...content].sort()
} else if (content.placeholder) {
serializedContent = content
} else {
serializedContent = content.toString("base64")
}
return [
path,
// requires node buffers, but no web standard method exists
serializedContent,
// Alternative to try:
// onst binaryData = new Uint8Array([255, 116, 79, 99 /*...*/]);
// const base64Encoded = btoa(String.fromCharCode.apply(null, binaryData));
// // Decode Base64 back to binary
// const decodedBinaryString = atob(base64Encoded);
// const decodedBinaryData = new Uint8Array([...decodedBinaryString].map(char => char.charCodeAt(0)));
// this breaks packfile binary data but could be fixed in future btoa(unescape(encodeURIComponent(new TextDecoder().decode(content)))),
]
})
),
fsStats: Object.fromEntries(
[...fs._state.fsStats].map(([path, fsStat]) => {
return [
path,
{
...fsStat,
ino: undefined,
isFile: undefined,
isDirectory: undefined,
isSymbolicLink: undefined,
},
]
})
),
}
}
export function fromSnapshot(
fs: NodeishFilesystem,
snapshot: { fsMap: any; fsStats: any },
{ pathPrefix = "" } = {}
) {
// TODO: windows withothout repo will hang tests. fix this with windows vm¯
fs._state.lastIno = 1
fs._state.fsMap = new Map(
// @ts-ignore FIXME: no idea what ts wants me to do here the error message is ridiculous
Object.entries(snapshot.fsMap).map(([path, content]) => {
if (typeof content === "string") {
// requires node buffers, but no web standard method exists
const data = Buffer.from(content, "base64")
// new TextEncoder().encode(decodeURIComponent(escape(atob(content)))) Buffer.from()
return [pathPrefix + path, data]
// @ts-ignore
} else if (content?.placeholder) {
return [pathPrefix + path, content]
}
return [pathPrefix + path, new Set(content as string[])]
})
)
fs._state.fsStats = new Map(
Object.entries(snapshot.fsStats).map(([path, rawStat]) => {
const serializedStat = rawStat as Omit<
NodeishStats,
"isFile" | "isDirectory" | "isSymbolicLink" | "ino"
>
const statsObj = {
...serializedStat,
ino: fs._state.lastIno++,
isFile: () => serializedStat._kind === 0,
isDirectory: () => serializedStat._kind === 1,
isSymbolicLink: () => serializedStat._kind === 2,
} as NodeishStats
return [pathPrefix + path, statsObj]
})
)
if (pathPrefix) {
const prefixParts = pathPrefix.split("/")
const rootStat = fs._state.fsStats.get(pathPrefix + "/")
for (let i = 1; i < prefixParts.length; i++) {
const path = prefixParts.slice(0, i).join("/") + "/"
fs._state.fsMap.set(path, new Set([prefixParts[i]]))
fs._state.fsStats.set(path, rootStat)
}
}
}
export function createNodeishMemoryFs(): NodeishFilesystem {
// local state
const state: {
lastIno: number
fsMap: Map<string, Inode>
fsStats: Map<string, NodeishStats>
} = {
lastIno: 1,
fsMap: new Map(),
fsStats: new Map(),
}
// initialize the root to an empty dir
state.fsMap.set("/", new Set())
newStatEntry({
path: "/",
stats: state.fsStats,
kind: 1,
modeBits: 0o755,
})
const listeners: Set<(event: FileChangeInfo) => void> = new Set()
// MISSING: exists and reddir with recursive option
async function stat(path: Parameters<NodeishFilesystem["stat"]>[0]): Promise<NodeishStats> {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const stats: NodeishStats | undefined = state.fsStats.get(path)
if (stats === undefined) {
throw new FilesystemError("ENOENT", path, "stat")
}
if (stats.symlinkTarget) {
return stat(stats.symlinkTarget)
}
return Object.assign({}, stats)
}
// lstat is like stat, but does not follow symlinks
async function lstat(path: Parameters<NodeishFilesystem["lstat"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const stats: NodeishStats | undefined = state.fsStats.get(path)
if (stats === undefined) {
throw new FilesystemError("ENOENT", path, "lstat")
}
if (!stats.symlinkTarget) {
return stat(path)
}
return Object.assign({}, stats)
}
return {
_state: state,
_createPlaceholder: async function (
path: Parameters<NodeishFilesystem["writeFile"]>[0],
options: {
mode: number
oid: string
rootHash: string
}
) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dirName = getDirname(path)
const baseName = getBasename(path)
let parentDir: Inode | undefined = state.fsMap.get(dirName)
if (!(parentDir instanceof Set)) {
await this.mkdir(dirName, { recursive: true })
parentDir = state.fsMap.get(dirName)
if (!(parentDir instanceof Set)) {
throw new FilesystemError("ENOENT", path, "writeFile")
}
}
parentDir.add(baseName)
const isSymbolicLink = options.mode === 120000
newStatEntry({
path,
stats: state.fsStats,
kind: isSymbolicLink ? 2 : 0,
modeBits: options.mode,
oid: options.oid,
rootHash: options.rootHash,
})
state.fsMap.set(path, { placeholder: true })
},
_isPlaceholder: function (path: Parameters<NodeishFilesystem["writeFile"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const entry = state.fsMap.get(path)
if (entry && "placeholder" in entry) {
return true
}
return false
},
writeFile: async function (
path: Parameters<NodeishFilesystem["writeFile"]>[0],
data: Parameters<NodeishFilesystem["writeFile"]>[1],
options?: Parameters<NodeishFilesystem["writeFile"]>[2]
) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dirName = getDirname(path)
const baseName = getBasename(path)
const parentDir: Inode | undefined = state.fsMap.get(dirName)
if (!(parentDir instanceof Set)) throw new FilesystemError("ENOENT", path, "writeFile")
let inodeData: Inode
if (typeof data === "string") {
inodeData = Buffer.from(new TextEncoder().encode(data))
} else if (!(data instanceof Uint8Array)) {
throw new FilesystemError(
'The "data" argument must be of type string/Uint8Array',
data,
"readFile"
)
} else if (!Buffer.isBuffer(data)) {
inodeData = Buffer.from(data)
} else {
inodeData = data
}
parentDir.add(baseName)
newStatEntry({
path,
stats: state.fsStats,
kind: 0,
modeBits: options?.mode ?? 0o644,
})
state.fsMap.set(path, inodeData)
for (const listener of listeners) {
listener({ eventType: "rename", filename: dirName + baseName })
}
},
// @ts-expect-error
// Typescript can't derive that the return type is either
// a string or a Uint8Array based on the options.
readFile: async function (
path: Parameters<NodeishFilesystem["readFile"]>[0],
options?: Parameters<NodeishFilesystem["readFile"]>[1]
) {
const decoder = new TextDecoder()
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const file: Inode | undefined = state.fsMap.get(path)
if (file instanceof Set) throw new FilesystemError("EISDIR", path, "readFile")
if (file === undefined) throw new FilesystemError("ENOENT", path, "readFile")
if ("placeholder" in file) throw new FilesystemError("EPLACEHOLDER", path, "readFile")
if (!(options?.encoding || typeof options === "string")) return file
return decoder.decode(file)
},
readdir: async function (path: Parameters<NodeishFilesystem["readdir"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dir: Inode | undefined = state.fsMap.get(path)
if (dir instanceof Set) return [...dir.keys()]
if (dir === undefined) throw new FilesystemError("ENOENT", path, "readdir")
throw new FilesystemError("ENOTDIR", path, "readdir")
},
mkdir: async function mkdir(
path: Parameters<NodeishFilesystem["mkdir"]>[0],
options: Parameters<NodeishFilesystem["mkdir"]>[1]
): Promise<string | undefined> {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dirName = getDirname(path)
const baseName = getBasename(path)
const parentDir: Inode | undefined = state.fsMap.get(dirName)
if (typeof parentDir === "string" || (parentDir && "palceholder" in parentDir)) {
throw new FilesystemError("ENOTDIR", path, "mkdir")
}
if (parentDir && parentDir instanceof Set) {
if (state.fsMap.has(path)) {
if (!options?.recursive) {
throw new FilesystemError("EEXIST", path, "mkdir")
} else {
return undefined
}
}
parentDir.add(baseName)
newStatEntry({
path,
stats: state.fsStats,
kind: 1,
modeBits: 0o755,
})
state.fsMap.set(path, new Set())
for (const listener of listeners) {
listener({ eventType: "rename", filename: dirName + baseName })
}
return path
} else if (options?.recursive) {
const parent = getDirname(path)
const parentRes = await mkdir(parent, options)
await mkdir(path, { recursive: false }).catch(() => {})
return parentRes
}
throw new FilesystemError("ENOENT", path, "mkdir")
},
rm: async function rm(
path: Parameters<NodeishFilesystem["rm"]>[0],
options: Parameters<NodeishFilesystem["rm"]>[1]
) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dirName = getDirname(path)
const baseName = getBasename(path)
const target: Inode | undefined = state.fsMap.get(path)
const targetStats = state.fsStats.get(path)
const parentDir: Inode | undefined = state.fsMap.get(dirName)
if (parentDir === undefined || targetStats === undefined)
throw new FilesystemError("ENOENT", path, "rm")
if (parentDir instanceof Uint8Array || "placeholder" in parentDir) {
throw new FilesystemError("ENOTDIR", path, "rm")
}
if (
target instanceof Uint8Array ||
(target && "placeholder" in target) ||
targetStats.isSymbolicLink()
) {
parentDir.delete(baseName)
state.fsStats.delete(path)
state.fsMap.delete(path)
// TODO: check if placeholder should skip firing
for (const listener of listeners) {
listener({ eventType: "rename", filename: dirName + baseName })
}
return
}
if (target instanceof Set && options?.recursive) {
await Promise.all(
[...target.keys()].map(async (child) => {
await rm(`${path}/${child}`, { recursive: true })
})
)
parentDir.delete(baseName)
state.fsStats.delete(path)
state.fsMap.delete(path)
for (const listener of listeners) {
listener({ eventType: "rename", filename: dirName + baseName })
}
return
}
throw new FilesystemError("EISDIR", path, "rm")
},
/**
*
* @throws {"ENOENT" | WatchAbortedError} // TODO: move to lix error classes FileDoesNotExistError
*/
watch: function (
path: Parameters<NodeishFilesystem["watch"]>[0],
options: Parameters<NodeishFilesystem["watch"]>[1]
) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const watchName = getBasename(path)
const watchDir = getDirname(path)
const watchPath = watchName === "/" ? watchDir : watchDir + watchName
// @ts-ignore
if (options?.persistent || options?.encoding) {
throw new Error("Some watch opptions not implemented, only 'recursive' allowed")
}
const queue: FileChangeInfo[] = []
let handleNext: (arg: any) => void
let rejecteNext: (err: Error) => void
let changeEvent: Promise<Error | undefined> = new Promise((resolve, reject) => {
handleNext = resolve
rejecteNext = reject
})
const listener = ({ eventType, filename }: FileChangeInfo) => {
const event: FileChangeInfo = {
eventType,
filename,
}
if (event.filename === null) {
throw new Error("Internal watcher error: missing filename")
}
const changeName = getBasename(event.filename)
const changeDir = getDirname(event.filename)
if (event.filename === watchPath) {
event.filename = changeName
queue.push(event)
setTimeout(() => handleNext(undefined), 0)
} else if (changeDir === `${watchPath}/`) {
event.filename = event.filename.replace(`${watchPath}/`, "") || changeName
queue.push(event)
setTimeout(() => handleNext(undefined), 0)
} else if (options?.recursive && event.filename.startsWith(watchPath)) {
event.filename = event.filename.replace(`${watchPath}/`, "") || changeName
queue.push(event)
setTimeout(() => handleNext(undefined), 0)
}
}
listeners.add(listener)
if (options?.signal) {
options.signal.addEventListener(
"abort",
() => {
listeners.delete(listener)
try {
options.signal?.throwIfAborted()
} catch (err) {
rejecteNext(err as Error)
}
},
{ once: true }
)
}
// inline async definition like "return (async function* () {" are not supported by the figma api
const asyncIterator = async function* () {
while (!options?.signal?.aborted) {
if (queue.length > 0) {
yield queue.shift() as FileChangeInfo
} else {
await changeEvent
changeEvent = new Promise((resolve, reject) => {
handleNext = resolve
rejecteNext = reject
})
}
}
}
return asyncIterator()
},
rmdir: async function (path: Parameters<NodeishFilesystem["rmdir"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const dirName = getDirname(path)
const baseName = getBasename(path)
const target: Inode | undefined = state.fsMap.get(path)
const parentDir: Inode | undefined = state.fsMap.get(dirName)
if (parentDir === undefined || target === undefined)
throw new FilesystemError("ENOENT", path, "rmdir")
if (parentDir instanceof Uint8Array || target instanceof Uint8Array)
throw new FilesystemError("ENOTDIR", path, "rmdir")
if ("placeholder" in parentDir || "placeholder" in target) {
throw new FilesystemError("ENOTDIR", path, "rmdir")
}
if (target.size) throw new FilesystemError("ENOTEMPTY", path, "rmdir")
parentDir.delete(baseName)
state.fsStats.delete(path)
state.fsMap.delete(path)
for (const listener of listeners) {
listener({ eventType: "rename", filename: dirName + baseName })
}
},
symlink: async function (
target: Parameters<NodeishFilesystem["symlink"]>[0],
path: Parameters<NodeishFilesystem["symlink"]>[1]
) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const rawTarget = target.startsWith("/") ? target : `${path}/../${target}`
const targetWithTrailing = normalizePath(rawTarget, {
trailingSlash: "always",
leadingSlash: "always",
})
const targetInode: Inode | undefined = state.fsMap.get(targetWithTrailing)
const parentDir: Inode | undefined = state.fsMap.get(getDirname(path))
if (state.fsMap.get(path)) {
throw new FilesystemError("EEXIST", path, "symlink", target)
}
if (parentDir === undefined) {
throw new FilesystemError("ENOENT", path, "symlink", target)
}
if (parentDir instanceof Uint8Array || "placeholder" in parentDir) {
throw new FilesystemError("ENOTDIR", path, "symlink", target)
}
if (targetInode !== undefined) {
state.fsMap.set(path, targetInode)
}
parentDir.add(getBasename(path))
newStatEntry({
path,
stats: state.fsStats,
kind: 2,
modeBits: 0o777,
target: rawTarget,
})
},
unlink: async function (path: Parameters<NodeishFilesystem["unlink"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const targetStats = state.fsStats.get(path)
const target: Inode | undefined = state.fsMap.get(path)
const parentDir: Inode | undefined = state.fsMap.get(getDirname(path))
if (parentDir === undefined || target === undefined)
throw new FilesystemError("ENOENT", path, "unlink")
if (parentDir instanceof Uint8Array || "placeholder" in parentDir) {
throw new FilesystemError("ENOTDIR", path, "unlink")
}
if (targetStats?.isDirectory()) {
throw new FilesystemError("EISDIR", path, "unlink")
}
parentDir.delete(getBasename(path))
state.fsStats.delete(path)
state.fsMap.delete(path)
},
readlink: async function (path: Parameters<NodeishFilesystem["readlink"]>[0]) {
path = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const linkStats = await lstat(path)
if (linkStats === undefined) {
throw new FilesystemError("ENOENT", path, "readlink")
}
if (linkStats.symlinkTarget === undefined) {
throw new FilesystemError("EINVAL", path, "readlink")
}
return linkStats.symlinkTarget
},
stat,
lstat,
}
/**
* Creates a new stat entry. 'kind' refers to whether the entry is for a file,
* directory or symlink:
* 0 = File
* 1 = Directory
* 2 = Symlink
*/
function newStatEntry({
path,
stats,
kind,
modeBits,
target,
oid,
rootHash,
}: {
path: string
stats: Map<string, NodeishStats>
kind: number
modeBits: number
target?: string
oid?: string
rootHash?: string
}) {
const currentTime: number = Date.now()
const _kind = kind
const targetPath = normalizePath(path, { trailingSlash: "always", leadingSlash: "always" })
const oldStats = stats.get(targetPath)
// We need to always bump by 1 second in case mtime did not change since last write to trigger iso git 1 second resolution change detection
const mtimeMs =
Math.floor(currentTime / 1000) === (oldStats?.mtimeMs && Math.floor(oldStats?.mtimeMs / 1000))
? currentTime + 1000
: currentTime
stats.set(targetPath, {
ctimeMs: oldStats?.ctimeMs || currentTime,
mtimeMs,
dev: 0,
ino: oldStats?.ino || state.lastIno++,
mode: (!kind ? 0o100000 : kind === 1 ? 0o040000 : 0o120000) | modeBits,
uid: 0,
gid: 0,
size: -1,
isFile: () => kind === 0,
isDirectory: () => kind === 1,
isSymbolicLink: () => kind === 2,
// symlinkTarget is only for symlinks, and is not normalized
symlinkTarget: target,
_oid: oid,
_rootHash: rootHash,
_kind,
})
}
}