@zmskco/dsh-notebook 0.0.0-stage → 0.2.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.
- package/LICENSE +23 -0
- package/README.md +238 -3
- package/assets/material-icons/LICENSE.txt +8 -0
- package/assets/material-icons/NOTICE.md +13 -0
- package/cordis.patch.yml +9 -0
- package/icon.png +0 -0
- package/lib/client.js +20249 -0
- package/lib/dsh.js +1 -0
- package/lib/errors.js +20 -0
- package/lib/http/api.js +230 -0
- package/lib/http/reveal.js +68 -0
- package/lib/http/status.js +15 -0
- package/lib/index.js +100 -0
- package/lib/story/bootstrap.js +40 -0
- package/lib/story/focus.js +43 -0
- package/lib/story/manuscript.js +49 -0
- package/lib/story/paths.js +95 -0
- package/lib/story/project.js +459 -0
- package/lib/story/readme.js +26 -0
- package/lib/story/root.js +63 -0
- package/lib/story/sandbox.js +113 -0
- package/lib/story/workspace.js +32 -0
- package/lib/types.js +7 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +93 -6
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Name and relative-path validation.
|
|
3
|
+
*
|
|
4
|
+
* Every path that reaches the filesystem is built here first. The defence is
|
|
5
|
+
* two-layered on purpose: this module rejects the shapes that are never
|
|
6
|
+
* legitimate (absolute paths, `..`, backslashes, drive letters), and
|
|
7
|
+
* {@link ProjectStore.resolveInside} then re-checks the canonicalized target
|
|
8
|
+
* against the root through the filesystem provider, so a symlink or a
|
|
9
|
+
* backend-specific alias cannot escape either.
|
|
10
|
+
*/
|
|
11
|
+
import { NotebookError } from '../errors.js';
|
|
12
|
+
/**
|
|
13
|
+
* Characters no mainstream filesystem accepts inside one path segment.
|
|
14
|
+
*
|
|
15
|
+
* The ASCII forms only. Their fullwidth cousins (`:`, `?`, `*`) are ordinary
|
|
16
|
+
* characters to every filesystem, so a Chinese title is free to use them.
|
|
17
|
+
*/
|
|
18
|
+
const ILLEGAL_IN_NAME = /[<>:"/\\|?*\u0000-\u001f\u007f]/;
|
|
19
|
+
/** Windows device names, reserved with or without an extension. */
|
|
20
|
+
const RESERVED_NAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
|
|
21
|
+
/**
|
|
22
|
+
* Cap on a name, in bytes rather than characters.
|
|
23
|
+
*
|
|
24
|
+
* The limit that bites first is ext4's 255 bytes per path segment, and one CJK
|
|
25
|
+
* character costs three of them, so a character-count cap would allow a name
|
|
26
|
+
* that cannot be created.
|
|
27
|
+
*/
|
|
28
|
+
const MAX_NAME_BYTES = 120;
|
|
29
|
+
/** Windows silently drops a trailing dot or space, so a name ending in one is a lie. */
|
|
30
|
+
const TRAILING_DOTS = /[. ]+$/;
|
|
31
|
+
/**
|
|
32
|
+
* Validate one name used as a path segment — a file or a folder.
|
|
33
|
+
*
|
|
34
|
+
* Unicode is allowed — a note called 第一章 gets a file called 第一章, which is
|
|
35
|
+
* the point. What is *not* allowed is anything the filesystem would refuse,
|
|
36
|
+
* silently rewrite, or resolve somewhere unintended: separators, the
|
|
37
|
+
* Windows-illegal set, control characters, the reserved device names, a trailing
|
|
38
|
+
* dot or space, and `.` / `..`.
|
|
39
|
+
*
|
|
40
|
+
* Normalizing to NFC first matters on macOS, where the filesystem decomposes
|
|
41
|
+
* accented names: without it, the name the user typed and the name read back
|
|
42
|
+
* from disk are different strings, and every containment or equality check
|
|
43
|
+
* between them fails.
|
|
44
|
+
* @param value - the untrusted name.
|
|
45
|
+
* @returns the normalized, filesystem-safe name.
|
|
46
|
+
* @throws {NotebookError} `bad-request` when the name cannot be a path segment.
|
|
47
|
+
*/
|
|
48
|
+
export function assertPathName(value) {
|
|
49
|
+
if (typeof value !== 'string') {
|
|
50
|
+
throw new NotebookError('bad-request', `name must be a string; received ${JSON.stringify(value)}`);
|
|
51
|
+
}
|
|
52
|
+
const name = value.normalize('NFC').trim().replace(TRAILING_DOTS, '');
|
|
53
|
+
if (name.length === 0) {
|
|
54
|
+
throw new NotebookError('bad-request', 'name must contain something other than spaces and dots');
|
|
55
|
+
}
|
|
56
|
+
if (name === '.' || name === '..') {
|
|
57
|
+
throw new NotebookError('bad-request', `name must not be ${JSON.stringify(name)}`);
|
|
58
|
+
}
|
|
59
|
+
if (ILLEGAL_IN_NAME.test(name)) {
|
|
60
|
+
throw new NotebookError('bad-request', `name must not contain < > : " / \\ | ? * or control characters; received ${JSON.stringify(name)}`);
|
|
61
|
+
}
|
|
62
|
+
if (RESERVED_NAME.test(name)) {
|
|
63
|
+
throw new NotebookError('bad-request', `name must not be a reserved device name such as CON or LPT1; received ${JSON.stringify(name)}`);
|
|
64
|
+
}
|
|
65
|
+
if (Buffer.byteLength(name, 'utf8') > MAX_NAME_BYTES) {
|
|
66
|
+
throw new NotebookError('bad-request', `name must be at most ${String(MAX_NAME_BYTES)} bytes; received ${String(Buffer.byteLength(name, 'utf8'))}`);
|
|
67
|
+
}
|
|
68
|
+
return name;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Normalize a project-relative file path.
|
|
72
|
+
*
|
|
73
|
+
* Accepts forward slashes only; backslashes are rejected rather than rewritten
|
|
74
|
+
* so a Windows-style path from a confused caller fails loudly instead of
|
|
75
|
+
* silently addressing a different file.
|
|
76
|
+
* @param value - the untrusted path.
|
|
77
|
+
* @returns the normalized relative path.
|
|
78
|
+
* @throws {NotebookError} `bad-request` when the path is absolute or escapes upward.
|
|
79
|
+
*/
|
|
80
|
+
export function assertRelativePath(value) {
|
|
81
|
+
if (typeof value !== 'string' || value.length === 0) {
|
|
82
|
+
throw new NotebookError('bad-request', 'path must be a non-empty string');
|
|
83
|
+
}
|
|
84
|
+
if (value.includes('\\')) {
|
|
85
|
+
throw new NotebookError('bad-request', `path must use forward slashes; received ${JSON.stringify(value)}`);
|
|
86
|
+
}
|
|
87
|
+
if (value.startsWith('/') || /^[A-Za-z]:/.test(value)) {
|
|
88
|
+
throw new NotebookError('bad-request', `path must be relative to the workspace; received ${JSON.stringify(value)}`);
|
|
89
|
+
}
|
|
90
|
+
const segments = value.split('/');
|
|
91
|
+
if (segments.some(segment => segment.length === 0 || segment === '.' || segment === '..')) {
|
|
92
|
+
throw new NotebookError('bad-request', `path must not contain empty, "." or ".." segments; received ${JSON.stringify(value)}`);
|
|
93
|
+
}
|
|
94
|
+
return segments.join('/');
|
|
95
|
+
}
|
|
@@ -0,0 +1,459 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The workspace store: everything that touches the notebook's files.
|
|
3
|
+
*
|
|
4
|
+
* There is one root and no project layer any more: the panel's tree is the
|
|
5
|
+
* workspace itself, so the store is built over that directory and every path it
|
|
6
|
+
* returns is relative to it.
|
|
7
|
+
*
|
|
8
|
+
* Text goes through `ctx.fs`, so reads and writes inherit the Harness filesystem
|
|
9
|
+
* provider, its sandbox policy, and its canonicalization. Two operations have no
|
|
10
|
+
* provider equivalent and reach `node:fs` instead — creating a directory, and
|
|
11
|
+
* moving or removing one — always at a path the provider already resolved and
|
|
12
|
+
* proved is inside the root, exactly as {@link ProjectStore.createDirectory} does.
|
|
13
|
+
*
|
|
14
|
+
* Files are different, and deliberately so: deleting and renaming one goes through
|
|
15
|
+
* `ctx.fs.deleteFile` / `moveFile`, which stamp the same sandbox policy a write
|
|
16
|
+
* does. A workspace pinned outside the deployment boundary is therefore writable
|
|
17
|
+
* here and still stamped correctly, and a read-only deployment refuses it at the
|
|
18
|
+
* seam rather than trusting this file to remember the rule.
|
|
19
|
+
*/
|
|
20
|
+
import { mkdir, rename, rm } from 'node:fs/promises';
|
|
21
|
+
import { dirname, join } from 'node:path';
|
|
22
|
+
import { NotebookError, asNotebookError } from '../errors.js';
|
|
23
|
+
import { assertPathName, assertRelativePath } from './paths.js';
|
|
24
|
+
import { countChars, isMissing, isTextFile, MAX_TREE_DEPTH, MAX_TREE_ENTRIES } from './manuscript.js';
|
|
25
|
+
/**
|
|
26
|
+
* Directories the tree never descends into.
|
|
27
|
+
*
|
|
28
|
+
* `node_modules` is not writing, and a workspace-sized tree that walked it would
|
|
29
|
+
* spend seconds per listing and push the author's own files past the entry cap.
|
|
30
|
+
*/
|
|
31
|
+
const SKIP_DIRS = new Set(['node_modules']);
|
|
32
|
+
/**
|
|
33
|
+
* The project id the panel uses for the workspace itself.
|
|
34
|
+
*
|
|
35
|
+
* The empty string is the id — it cannot collide with a directory name, whose
|
|
36
|
+
* name is non-empty by construction.
|
|
37
|
+
*/
|
|
38
|
+
export const WORKSPACE_PROJECT = '';
|
|
39
|
+
export class ProjectStore {
|
|
40
|
+
fs;
|
|
41
|
+
rootDir;
|
|
42
|
+
log;
|
|
43
|
+
writePolicy;
|
|
44
|
+
rootCache;
|
|
45
|
+
constructor(fs, rootDir, log,
|
|
46
|
+
/**
|
|
47
|
+
* The policy stamped on every content write.
|
|
48
|
+
*
|
|
49
|
+
* A write through `ctx.fs` with no explicit policy resolves against the
|
|
50
|
+
* *deployment* fallback (`defaultMode` + `workspaceRoot`), which is not
|
|
51
|
+
* necessarily the directory the notebook lives in. Stamping the root as the
|
|
52
|
+
* boundary is what lets a fresh install serve a workspace outside the
|
|
53
|
+
* deployment workspace with no profile edit at all; see
|
|
54
|
+
* {@link module:notebook/story/sandbox}. `undefined` means this profile
|
|
55
|
+
* mounted no confining filesystem, so there is nothing to stamp.
|
|
56
|
+
*/
|
|
57
|
+
writePolicy) {
|
|
58
|
+
this.fs = fs;
|
|
59
|
+
this.rootDir = rootDir;
|
|
60
|
+
this.log = log;
|
|
61
|
+
this.writePolicy = writePolicy;
|
|
62
|
+
}
|
|
63
|
+
/** Resolve (and create on first use) the root directory. */
|
|
64
|
+
async root() {
|
|
65
|
+
if (this.rootCache !== undefined)
|
|
66
|
+
return this.rootCache;
|
|
67
|
+
let target = await this.fs.resolve(this.rootDir);
|
|
68
|
+
if (await this.fs.stat(target) === undefined) {
|
|
69
|
+
await mkdir(this.fs.processPath(target), { recursive: true });
|
|
70
|
+
target = await this.fs.resolve(this.rootDir);
|
|
71
|
+
}
|
|
72
|
+
this.rootCache = target;
|
|
73
|
+
return target;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Open the store's own root as the project.
|
|
77
|
+
*
|
|
78
|
+
* The operator's folder is not a project id, so this skips the name check and
|
|
79
|
+
* hands back the root the store already owns. Paths stay relative and stay
|
|
80
|
+
* containment-checked against it.
|
|
81
|
+
* @returns the root, opened as a project whose id is {@link WORKSPACE_PROJECT}.
|
|
82
|
+
* @throws {NotebookError} `not-found` when the root is not a directory.
|
|
83
|
+
*/
|
|
84
|
+
async openRoot() {
|
|
85
|
+
const dir = await this.root();
|
|
86
|
+
const info = await this.fs.stat(dir);
|
|
87
|
+
if (info === undefined || info.type !== 'directory') {
|
|
88
|
+
throw new NotebookError('not-found', `workspace ${this.rootDir} is not a directory`);
|
|
89
|
+
}
|
|
90
|
+
return { id: WORKSPACE_PROJECT, dir, abs: this.fs.processPath(dir) };
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Resolve a project-relative path and re-check containment on the canonical target.
|
|
94
|
+
* @param project - an opened root.
|
|
95
|
+
* @param rel - a project-relative POSIX path.
|
|
96
|
+
* @returns the resolved target.
|
|
97
|
+
* @throws {NotebookError} `forbidden` when the canonical target escapes the root.
|
|
98
|
+
*/
|
|
99
|
+
async resolveInside(project, rel) {
|
|
100
|
+
const safe = assertRelativePath(rel);
|
|
101
|
+
const target = await this.fs.resolve(safe, { cwd: project.abs });
|
|
102
|
+
if (!this.fs.contains(project.dir, target)) {
|
|
103
|
+
throw new NotebookError('forbidden', `${safe} resolves outside the workspace`);
|
|
104
|
+
}
|
|
105
|
+
return target;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Create the parent directories of a project-relative path.
|
|
109
|
+
*
|
|
110
|
+
* Every segment is already validated by {@link assertRelativePath}, and the base
|
|
111
|
+
* is the provider-resolved root, so this cannot create anything outside it.
|
|
112
|
+
*/
|
|
113
|
+
async ensureParent(project, rel) {
|
|
114
|
+
const segments = assertRelativePath(rel).split('/').slice(0, -1);
|
|
115
|
+
if (segments.length === 0)
|
|
116
|
+
return;
|
|
117
|
+
try {
|
|
118
|
+
await mkdir(join(project.abs, ...segments), { recursive: true });
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
throw asNotebookError(error, `cannot create the directory for ${rel}`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* The names directly inside one folder of the workspace.
|
|
126
|
+
*
|
|
127
|
+
* Used when naming a new file: the question is "is this name taken *here*", so
|
|
128
|
+
* listing the whole tree would walk every subdirectory — seconds on a workspace
|
|
129
|
+
* that holds a `node_modules` — to answer something one `listDir` answers.
|
|
130
|
+
* @param project - an opened root.
|
|
131
|
+
* @param folder - project-relative folder, `''` for the root.
|
|
132
|
+
* @returns the entry names in that folder; empty when it cannot be read.
|
|
133
|
+
*/
|
|
134
|
+
async namesIn(project, folder) {
|
|
135
|
+
const target = folder === '' ? project.dir : await this.resolveInside(project, folder);
|
|
136
|
+
const entries = await this.fs.listDir(target).catch(() => []);
|
|
137
|
+
return new Set(entries.map(entry => entry.name));
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* List every file and directory under the root.
|
|
141
|
+
*
|
|
142
|
+
* Dot entries are tooling rather than notes (`.git`), `node_modules` is not
|
|
143
|
+
* writing, and unknown extensions are hidden: a file the tree cannot open is
|
|
144
|
+
* noise in a list whose purpose is to be clicked.
|
|
145
|
+
* @param project - an opened root.
|
|
146
|
+
* @returns the entries, sorted by path.
|
|
147
|
+
*/
|
|
148
|
+
async listFiles(project) {
|
|
149
|
+
const out = [];
|
|
150
|
+
const walk = async (dir, relDir, depth) => {
|
|
151
|
+
if (depth > MAX_TREE_DEPTH || out.length >= MAX_TREE_ENTRIES)
|
|
152
|
+
return;
|
|
153
|
+
let entries;
|
|
154
|
+
try {
|
|
155
|
+
entries = await this.fs.listDir(dir);
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
// One unreadable subdirectory must not cost the user the whole tree.
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
for (const entry of entries) {
|
|
162
|
+
if (out.length >= MAX_TREE_ENTRIES)
|
|
163
|
+
return;
|
|
164
|
+
if (entry.name.startsWith('.'))
|
|
165
|
+
continue;
|
|
166
|
+
if (entry.type === 'directory' && SKIP_DIRS.has(entry.name))
|
|
167
|
+
continue;
|
|
168
|
+
// Re-checked per child rather than trusting the walk, so a symlink
|
|
169
|
+
// pointing out of the root cannot smuggle an outside file in.
|
|
170
|
+
if (!this.fs.contains(project.dir, entry.target))
|
|
171
|
+
continue;
|
|
172
|
+
const rel = relDir === '' ? entry.name : `${relDir}/${entry.name}`;
|
|
173
|
+
if (entry.type === 'directory') {
|
|
174
|
+
out.push({ path: rel, name: entry.name, bytes: 0, kind: 'directory' });
|
|
175
|
+
await walk(entry.target, rel, depth + 1);
|
|
176
|
+
continue;
|
|
177
|
+
}
|
|
178
|
+
if (entry.type !== 'file')
|
|
179
|
+
continue;
|
|
180
|
+
if (!isTextFile(entry.name))
|
|
181
|
+
continue;
|
|
182
|
+
const size = entry.size ?? (await this.fs.stat(entry.target).catch(() => undefined))?.size ?? 0;
|
|
183
|
+
out.push({ path: rel, name: entry.name, bytes: size, kind: 'text' });
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
await walk(project.dir, '', 0);
|
|
187
|
+
// `numeric` so 第2章 sorts before 第10章 rather than after it, and Chinese
|
|
188
|
+
// collation so the folder names group the way a reader expects.
|
|
189
|
+
out.sort((left, right) => left.path.localeCompare(right.path, 'zh-Hans-CN', { numeric: true }));
|
|
190
|
+
return out;
|
|
191
|
+
}
|
|
192
|
+
/**
|
|
193
|
+
* Read one text file.
|
|
194
|
+
* @param project - an opened root.
|
|
195
|
+
* @param rel - project-relative POSIX path.
|
|
196
|
+
* @returns the document.
|
|
197
|
+
* @throws {NotebookError} `bad-request` when the extension is not editable text,
|
|
198
|
+
* `not-found` when the file is absent.
|
|
199
|
+
*/
|
|
200
|
+
async readTextFile(project, rel) {
|
|
201
|
+
const safe = assertRelativePath(rel);
|
|
202
|
+
if (!isTextFile(safe))
|
|
203
|
+
throw new NotebookError('bad-request', `${safe} is not a text file this editor opens`);
|
|
204
|
+
const target = await this.resolveInside(project, safe);
|
|
205
|
+
let content;
|
|
206
|
+
try {
|
|
207
|
+
content = await this.fs.readText(target);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
if (isMissing(error))
|
|
211
|
+
throw new NotebookError('not-found', `${safe} does not exist`);
|
|
212
|
+
throw asNotebookError(error, `cannot read ${safe}`);
|
|
213
|
+
}
|
|
214
|
+
return { path: safe, content, chars: countChars(content), bytes: Buffer.byteLength(content, 'utf8') };
|
|
215
|
+
}
|
|
216
|
+
/**
|
|
217
|
+
* Write one text file, creating parent directories as needed.
|
|
218
|
+
* @param project - an opened root.
|
|
219
|
+
* @param rel - project-relative POSIX path.
|
|
220
|
+
* @param content - the full new contents.
|
|
221
|
+
* @returns the stored document.
|
|
222
|
+
* @throws {NotebookError} `bad-request` when the extension is not editable text.
|
|
223
|
+
*/
|
|
224
|
+
async writeTextFile(project, rel, content) {
|
|
225
|
+
const safe = assertRelativePath(rel);
|
|
226
|
+
if (!isTextFile(safe))
|
|
227
|
+
throw new NotebookError('bad-request', `${safe} is not a text file this editor writes`);
|
|
228
|
+
await this.ensureParent(project, safe);
|
|
229
|
+
const target = await this.resolveInside(project, safe);
|
|
230
|
+
try {
|
|
231
|
+
await this.fs.writeText(target, content, undefined, undefined, this.writePolicy);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
throw asNotebookError(error, `cannot write ${safe}`);
|
|
235
|
+
}
|
|
236
|
+
return { path: safe, content, chars: countChars(content), bytes: Buffer.byteLength(content, 'utf8') };
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Create one directory inside the workspace.
|
|
240
|
+
*
|
|
241
|
+
* `ctx.fs` writes files but cannot make a directory, so this reaches `node:fs`
|
|
242
|
+
* at a path the provider resolved and proved is inside the root. The path is
|
|
243
|
+
* validated by {@link assertRelativePath} before it is resolved, so it cannot
|
|
244
|
+
* name an absolute path or climb out with `..`.
|
|
245
|
+
* @param project - an opened root.
|
|
246
|
+
* @param rel - project-relative POSIX path of the new directory.
|
|
247
|
+
* @returns the path that was created.
|
|
248
|
+
* @throws {NotebookError} `conflict` when something already holds that path.
|
|
249
|
+
*/
|
|
250
|
+
async createDirectory(project, rel) {
|
|
251
|
+
const safe = assertRelativePath(rel);
|
|
252
|
+
const target = await this.resolveInside(project, safe);
|
|
253
|
+
if (await this.fs.stat(target) !== undefined) {
|
|
254
|
+
throw new NotebookError('conflict', `${safe} already exists`);
|
|
255
|
+
}
|
|
256
|
+
try {
|
|
257
|
+
await mkdir(this.fs.processPath(target), { recursive: true });
|
|
258
|
+
}
|
|
259
|
+
catch (error) {
|
|
260
|
+
throw asNotebookError(error, `cannot create ${safe}`);
|
|
261
|
+
}
|
|
262
|
+
return { path: safe };
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The path for a new file whose name is exactly what the author typed.
|
|
266
|
+
*
|
|
267
|
+
* A title is the file name: appending `.md` would give the same document a
|
|
268
|
+
* second name, and a title that already carries an extension would get two
|
|
269
|
+
* (`.md.md`). Uniqueness is the only thing enforced here — a number goes before
|
|
270
|
+
* the extension, so `名.md` becomes `名-2.md` rather than `名.md-2`.
|
|
271
|
+
* @param project - an opened root.
|
|
272
|
+
* @param dir - the folder to create it in, project-relative; `''` is the root.
|
|
273
|
+
* @param name - the file name, already validated as one path segment.
|
|
274
|
+
* @returns the project-relative path, free of collisions.
|
|
275
|
+
*/
|
|
276
|
+
async newNamedPath(project, dir, name) {
|
|
277
|
+
const folder = dir.length === 0 ? '' : assertRelativePath(dir);
|
|
278
|
+
const at = (file) => (folder === '' ? file : `${folder}/${file}`);
|
|
279
|
+
const used = await this.namesIn(project, folder);
|
|
280
|
+
if (!used.has(name))
|
|
281
|
+
return at(name);
|
|
282
|
+
const dot = name.lastIndexOf('.');
|
|
283
|
+
const stem = dot > 0 ? name.slice(0, dot) : name;
|
|
284
|
+
const extension = dot > 0 ? name.slice(dot) : '';
|
|
285
|
+
for (let index = 2; index < 10_000; index += 1) {
|
|
286
|
+
const candidate = `${stem}-${String(index)}${extension}`;
|
|
287
|
+
if (!used.has(candidate))
|
|
288
|
+
return at(candidate);
|
|
289
|
+
}
|
|
290
|
+
throw new NotebookError('conflict', 'no free file name remains');
|
|
291
|
+
}
|
|
292
|
+
/** Validate one user-supplied name as a single path segment. */
|
|
293
|
+
assertName(value) {
|
|
294
|
+
return assertPathName(value);
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Whether a project-relative path names a directory.
|
|
298
|
+
*
|
|
299
|
+
* Asked before a rename or a delete decides *how* to do it: a file goes through
|
|
300
|
+
* the filesystem provider (which stamps the sandbox policy), a directory through
|
|
301
|
+
* `node:fs` (which has no provider equivalent). Guessing from a trailing slash
|
|
302
|
+
* would be guessing about the caller's intent rather than about the disk.
|
|
303
|
+
* @param project - an opened root.
|
|
304
|
+
* @param rel - a project-relative POSIX path.
|
|
305
|
+
* @returns true for a directory; false for a file or anything absent.
|
|
306
|
+
*/
|
|
307
|
+
async isDirectory(project, rel) {
|
|
308
|
+
const target = await this.resolveInside(project, rel);
|
|
309
|
+
const info = await this.fs.stat(target).catch(() => undefined);
|
|
310
|
+
return info?.type === 'directory';
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Rename one file or directory, in place in its own folder.
|
|
314
|
+
*
|
|
315
|
+
* The new name is one path segment, validated exactly as a create name is, so a
|
|
316
|
+
* rename can never turn into a move: the folder stays where it was and only the
|
|
317
|
+
* last segment changes. That restriction is deliberate — "rename" in a file tree
|
|
318
|
+
* means the thing stays put, and a control that could silently relocate a chapter
|
|
319
|
+
* folder is not the gesture the author made.
|
|
320
|
+
*
|
|
321
|
+
* A file keeps its content byte for byte: `moveFile` publishes the source text at
|
|
322
|
+
* the destination and removes the source, both guarded by the write policy. A
|
|
323
|
+
* directory is moved with `rename(2)`, which is atomic and cheap even for a
|
|
324
|
+
* thousand chapters.
|
|
325
|
+
* @param project - an opened root.
|
|
326
|
+
* @param rel - the existing project-relative path.
|
|
327
|
+
* @param name - the new name for it, one segment.
|
|
328
|
+
* @returns the new project-relative path.
|
|
329
|
+
* @throws {NotebookError} `not-found` when the source is absent, `conflict` when
|
|
330
|
+
* the destination is taken.
|
|
331
|
+
*/
|
|
332
|
+
async renameEntry(project, rel, name) {
|
|
333
|
+
const safe = assertRelativePath(rel);
|
|
334
|
+
const newName = assertPathName(name);
|
|
335
|
+
const parent = safe.includes('/') ? safe.slice(0, safe.lastIndexOf('/')) : '';
|
|
336
|
+
const next = parent === '' ? newName : `${parent}/${newName}`;
|
|
337
|
+
// A rename to the name it already has is a no-op, not a conflict: the user may
|
|
338
|
+
// simply have confirmed an unchanged field, and both branches below would
|
|
339
|
+
// otherwise refuse a state that is already what was asked for.
|
|
340
|
+
if (next === safe)
|
|
341
|
+
return { path: safe };
|
|
342
|
+
const source = await this.resolveInside(project, safe);
|
|
343
|
+
if (await this.fs.stat(source) === undefined) {
|
|
344
|
+
throw new NotebookError('not-found', `${safe} does not exist`);
|
|
345
|
+
}
|
|
346
|
+
const destination = await this.resolveInside(project, next);
|
|
347
|
+
if (await this.fs.stat(destination) !== undefined) {
|
|
348
|
+
throw new NotebookError('conflict', `${next} already exists`);
|
|
349
|
+
}
|
|
350
|
+
if (await this.isDirectory(project, safe)) {
|
|
351
|
+
try {
|
|
352
|
+
await rename(this.fs.processPath(source), this.fs.processPath(destination));
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
throw asNotebookError(error, `cannot rename ${safe}`);
|
|
356
|
+
}
|
|
357
|
+
return { path: next };
|
|
358
|
+
}
|
|
359
|
+
try {
|
|
360
|
+
await this.fs.moveFile(source, destination, {}, undefined, this.writePolicy);
|
|
361
|
+
}
|
|
362
|
+
catch (error) {
|
|
363
|
+
throw asNotebookError(error, `cannot rename ${safe}`);
|
|
364
|
+
}
|
|
365
|
+
return { path: next };
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Delete one file or directory.
|
|
369
|
+
*
|
|
370
|
+
* A directory goes with everything under it, which is what a file manager does
|
|
371
|
+
* and what "delete this folder" means. The panel asks first and says how much is
|
|
372
|
+
* inside (see `api.delete`), because this is the one operation in the plugin that
|
|
373
|
+
* cannot be undone by typing.
|
|
374
|
+
*
|
|
375
|
+
* Containment is checked before anything is removed, so a symlink pointing out of
|
|
376
|
+
* the workspace is refused rather than followed.
|
|
377
|
+
* @param project - an opened root.
|
|
378
|
+
* @param rel - the project-relative path to remove.
|
|
379
|
+
* @returns the path that was removed, and whether it was a directory.
|
|
380
|
+
* @throws {NotebookError} `not-found` when the path is absent.
|
|
381
|
+
*/
|
|
382
|
+
async deleteEntry(project, rel) {
|
|
383
|
+
const safe = assertRelativePath(rel);
|
|
384
|
+
const target = await this.resolveInside(project, safe);
|
|
385
|
+
if (await this.fs.stat(target) === undefined) {
|
|
386
|
+
throw new NotebookError('not-found', `${safe} does not exist`);
|
|
387
|
+
}
|
|
388
|
+
if (await this.isDirectory(project, safe)) {
|
|
389
|
+
try {
|
|
390
|
+
await rm(this.fs.processPath(target), { recursive: true, force: false });
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
throw asNotebookError(error, `cannot delete ${safe}`);
|
|
394
|
+
}
|
|
395
|
+
return { path: safe, directory: true };
|
|
396
|
+
}
|
|
397
|
+
try {
|
|
398
|
+
await this.fs.deleteFile(target, undefined, undefined, this.writePolicy);
|
|
399
|
+
}
|
|
400
|
+
catch (error) {
|
|
401
|
+
throw asNotebookError(error, `cannot delete ${safe}`);
|
|
402
|
+
}
|
|
403
|
+
return { path: safe, directory: false };
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* The absolute directory a path should be revealed in.
|
|
407
|
+
*
|
|
408
|
+
* "Show this in the file manager" means: the folder itself for a folder, and the
|
|
409
|
+
* folder containing it for a file — the file manager's own selection gesture is
|
|
410
|
+
* platform-specific and unreliable (`explorer /select,` starts a second shell that
|
|
411
|
+
* does not always surface), while opening a directory is the one launch this
|
|
412
|
+
* plugin has already measured on every platform.
|
|
413
|
+
* @param project - an opened root.
|
|
414
|
+
* @param rel - a project-relative path, or `''` for the workspace itself.
|
|
415
|
+
* @returns an absolute directory path, proven to be inside the root.
|
|
416
|
+
*/
|
|
417
|
+
async revealDirectoryFor(project, rel) {
|
|
418
|
+
if (rel === '')
|
|
419
|
+
return project.abs;
|
|
420
|
+
const target = await this.resolveInside(project, rel);
|
|
421
|
+
if (await this.isDirectory(project, rel))
|
|
422
|
+
return this.fs.processPath(target);
|
|
423
|
+
return dirname(this.fs.processPath(target));
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* How many files a directory holds, for a delete confirmation.
|
|
427
|
+
*
|
|
428
|
+
* Read through the same provider and the same skips as the tree, so the number
|
|
429
|
+
* the dialog shows is the number the author can see. A directory that cannot be
|
|
430
|
+
* read counts as unknown (`null`) rather than as empty.
|
|
431
|
+
* @param project - an opened root.
|
|
432
|
+
* @param rel - a project-relative directory path.
|
|
433
|
+
* @returns the recursive file count, or null when it could not be read.
|
|
434
|
+
*/
|
|
435
|
+
async countFilesUnder(project, rel) {
|
|
436
|
+
try {
|
|
437
|
+
let total = 0;
|
|
438
|
+
const walk = async (dir, depth) => {
|
|
439
|
+
if (depth > MAX_TREE_DEPTH || total >= MAX_TREE_ENTRIES)
|
|
440
|
+
return;
|
|
441
|
+
for (const entry of await this.fs.listDir(dir)) {
|
|
442
|
+
if (entry.type === 'directory') {
|
|
443
|
+
if (SKIP_DIRS.has(entry.name))
|
|
444
|
+
continue;
|
|
445
|
+
await walk(entry.target, depth + 1);
|
|
446
|
+
}
|
|
447
|
+
else if (entry.type === 'file') {
|
|
448
|
+
total += 1;
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
await walk(await this.resolveInside(project, rel), 0);
|
|
453
|
+
return total;
|
|
454
|
+
}
|
|
455
|
+
catch {
|
|
456
|
+
return null;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The README the panel writes into a workspace the first time it is opened.
|
|
3
|
+
*
|
|
4
|
+
* @module notebook/story/readme
|
|
5
|
+
*/
|
|
6
|
+
/**
|
|
7
|
+
* The workspace's README, written on first open.
|
|
8
|
+
*
|
|
9
|
+
* Fixed text on purpose: it names the plugin and lists what the panel does,
|
|
10
|
+
* which is what someone opening an unknown directory wants to know. It is
|
|
11
|
+
* created only when absent — a workspace that already has a `README.md` keeps
|
|
12
|
+
* its own.
|
|
13
|
+
* @returns the markdown.
|
|
14
|
+
*/
|
|
15
|
+
export function workspaceReadme() {
|
|
16
|
+
return `# dsh-notepad
|
|
17
|
+
|
|
18
|
+
deepseek harness 简易的markdown笔记插件
|
|
19
|
+
|
|
20
|
+
- 支持目录树浏览,创建文件夹,创建文件
|
|
21
|
+
- 支持字体样式,大小,背景颜色调整
|
|
22
|
+
- 支持字数显示,自动保存
|
|
23
|
+
- 支持AI对话框功能
|
|
24
|
+
- 重命名,删除,需要在系统资源管理器完成,或提示AI操作
|
|
25
|
+
`;
|
|
26
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { ProjectStore } from './project.js';
|
|
2
|
+
import { storyWritePolicy } from './sandbox.js';
|
|
3
|
+
/**
|
|
4
|
+
* The live Session behind one id, when there is one.
|
|
5
|
+
* @param agents - the agent registry, when this profile has one.
|
|
6
|
+
* @param sessionId - the calling Session, when the caller knows it.
|
|
7
|
+
* @returns the Session, or `undefined` when it cannot be known.
|
|
8
|
+
*/
|
|
9
|
+
function liveSession(agents, sessionId) {
|
|
10
|
+
if (agents === undefined || sessionId === undefined)
|
|
11
|
+
return undefined;
|
|
12
|
+
return agents.get(sessionId)?.session;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Decide which directory a call's notes live in.
|
|
16
|
+
*
|
|
17
|
+
* There is nothing to choose between: a live Session *is* the root.
|
|
18
|
+
* @param fallbackRoot - the activation default, for a caller with no Session.
|
|
19
|
+
* @param workspace - the calling Session's workspace, when known.
|
|
20
|
+
* @returns the root and the rule that chose it.
|
|
21
|
+
*/
|
|
22
|
+
export function storyRootFor(fallbackRoot, workspace) {
|
|
23
|
+
// The path is used verbatim: a trailing space is legal input, and trimming the
|
|
24
|
+
// value would resolve a directory the operator did not open. Only the
|
|
25
|
+
// emptiness test looks at the trimmed form.
|
|
26
|
+
if (workspace !== undefined && workspace.trim().length > 0)
|
|
27
|
+
return { dir: workspace, source: 'workspace' };
|
|
28
|
+
return { dir: fallbackRoot, source: 'fallback' };
|
|
29
|
+
}
|
|
30
|
+
/** Roots kept as live stores; a session beyond this evicts the least recently added. */
|
|
31
|
+
const MAX_CACHED_ROOTS = 8;
|
|
32
|
+
/**
|
|
33
|
+
* Build the per-call root resolver.
|
|
34
|
+
*
|
|
35
|
+
* One store per (root, mode), cached because every call in a Session resolves to
|
|
36
|
+
* the same root and a store holds nothing but its own listing cache. The mode is
|
|
37
|
+
* part of the key rather than fixed at activation because a Session's mode can be
|
|
38
|
+
* switched while the plugin is serving it, and the write policy was stamped with
|
|
39
|
+
* the old one — a second store costs a directory listing, a stale mode costs a
|
|
40
|
+
* write that should have been allowed.
|
|
41
|
+
* @param deps - filesystem, the session-less fallback root, sandbox policy, agent registry, logger.
|
|
42
|
+
* @returns a resolver from an optional Session id to that call's store and root.
|
|
43
|
+
*/
|
|
44
|
+
export function createRootResolver(deps) {
|
|
45
|
+
const cache = new Map();
|
|
46
|
+
return (sessionId) => {
|
|
47
|
+
const session = liveSession(deps.agents, sessionId);
|
|
48
|
+
const root = storyRootFor(deps.fallbackRoot, session?.header.cwd);
|
|
49
|
+
const writePolicy = storyWritePolicy(root.dir, deps.policy, session);
|
|
50
|
+
const key = `${root.dir}\u0000${writePolicy?.mode ?? ''}`;
|
|
51
|
+
let store = cache.get(key);
|
|
52
|
+
if (store === undefined) {
|
|
53
|
+
store = new ProjectStore(deps.fs, root.dir, deps.log, writePolicy);
|
|
54
|
+
cache.set(key, store);
|
|
55
|
+
if (cache.size > MAX_CACHED_ROOTS) {
|
|
56
|
+
const oldest = cache.keys().next().value;
|
|
57
|
+
if (oldest !== undefined)
|
|
58
|
+
cache.delete(oldest);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { store, root, session };
|
|
62
|
+
};
|
|
63
|
+
}
|