@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/lib/dsh.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/lib/errors.js ADDED
@@ -0,0 +1,20 @@
1
+ export class NotebookError extends Error {
2
+ code;
3
+ constructor(code, message) {
4
+ super(message);
5
+ this.name = 'NotebookError';
6
+ this.code = code;
7
+ }
8
+ }
9
+ /**
10
+ * Narrow an unknown rejection into a `NotebookError`.
11
+ * @param error - the caught value.
12
+ * @param fallback - message used when the value carries no usable text.
13
+ * @returns the value itself when it already is a `NotebookError`, else a wrapped one.
14
+ */
15
+ export function asNotebookError(error, fallback = 'unexpected failure') {
16
+ if (error instanceof NotebookError)
17
+ return error;
18
+ const message = error instanceof Error && error.message.length > 0 ? error.message : fallback;
19
+ return new NotebookError('internal', message);
20
+ }
@@ -0,0 +1,230 @@
1
+ import { NotebookError, asNotebookError } from '../errors.js';
2
+ import { assertPathName, assertRelativePath } from '../story/paths.js';
3
+ import { assessWriteAccess, writeAccessGuidance } from '../story/sandbox.js';
4
+ import { WORKSPACE_PROJECT } from '../story/project.js';
5
+ import { workspaceStore } from '../story/workspace.js';
6
+ import { revealCommand, revealInFileManager } from './reveal.js';
7
+ import { workspaceReadme } from '../story/readme.js';
8
+ import { STATUS_BY_CODE } from './status.js';
9
+ /** The one path this plugin claims on the Connection Fetch registry. */
10
+ export const API_PATH = '/api/notebook';
11
+ function json(body, status = 200) {
12
+ return new Response(JSON.stringify(body), {
13
+ status,
14
+ headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' },
15
+ });
16
+ }
17
+ function failure(error) {
18
+ const notebookError = asNotebookError(error);
19
+ const body = { code: notebookError.code, message: notebookError.message };
20
+ return json(body, STATUS_BY_CODE[notebookError.code]);
21
+ }
22
+ /**
23
+ * Refuse a mutation on a deployment that cannot write.
24
+ *
25
+ * `ctx.fs` refuses a file write on its own (the policy is stamped on it), but a
26
+ * directory is changed through `node:fs`, which no policy guards. Without this
27
+ * check a read-only deployment would silently allow "new folder", rename and
28
+ * delete — three operations whose refusal every other write in the panel already
29
+ * explains with the same guidance.
30
+ * @param access - this request's write assessment.
31
+ * @param workspaceDir - the directory it was assessed against, for the message.
32
+ */
33
+ function refuseReadOnly(access, workspaceDir) {
34
+ if (access.writable)
35
+ return;
36
+ throw new NotebookError('forbidden', writeAccessGuidance(workspaceDir, access) ?? 'this workspace is read-only');
37
+ }
38
+ /**
39
+ * Read one JSON request body.
40
+ *
41
+ * A missing or malformed body is the caller's mistake and is reported as such,
42
+ * rather than surfacing as an opaque crash inside a handler.
43
+ * @param request - the incoming request.
44
+ * @returns the parsed object; an empty body reads as `{}`.
45
+ */
46
+ async function readBody(request) {
47
+ const text = await request.text();
48
+ if (text.trim().length === 0)
49
+ return {};
50
+ try {
51
+ const value = JSON.parse(text);
52
+ return typeof value === 'object' && value !== null ? value : {};
53
+ }
54
+ catch {
55
+ throw new NotebookError('bad-request', 'the request body is not JSON');
56
+ }
57
+ }
58
+ /**
59
+ * Register the control-plane route.
60
+ * @param deps - services and state the operations need.
61
+ * @returns the registration disposer.
62
+ */
63
+ export function registerApi(deps) {
64
+ const { connection, fs, roots, log, policy, focus } = deps;
65
+ const handle = async (request) => {
66
+ const url = new URL(request.url);
67
+ const op = url.searchParams.get('op') ?? '';
68
+ // One resolution for the whole request, so every branch below — and the
69
+ // failure path that explains a refusal — agrees on which directory is being
70
+ // talked about. The panel sends the Session it belongs to; a scripted caller
71
+ // may send none, and then the activation fallback applies.
72
+ const sessionId = url.searchParams.get('session') ?? undefined;
73
+ const { root, session } = roots(sessionId);
74
+ // The panel's directory column is rooted at the workspace itself, and that
75
+ // workspace *is* the root: one directory, resolved once for this request.
76
+ const workspaceDir = root.dir;
77
+ const workspace = workspaceStore({ fs, policy, log }, session, workspaceDir);
78
+ const open = async (name) => {
79
+ if (name === WORKSPACE_PROJECT)
80
+ return { store: workspace, project: await workspace.openRoot() };
81
+ throw new NotebookError('bad-request', 'this plugin serves the workspace itself; project must be ""');
82
+ };
83
+ const access = assessWriteAccess(workspaceDir, policy, session);
84
+ try {
85
+ switch (op) {
86
+ case 'state': {
87
+ return json({
88
+ rootDir: workspaceDir,
89
+ sandbox: {
90
+ mode: access.mode ?? null,
91
+ workspaceRoot: access.workspaceRoot ?? null,
92
+ writable: access.writable,
93
+ // Sending the text rather than a reason code keeps the one copy of
94
+ // the remedy on the half that knows the paths. `null` while the
95
+ // arrangement is the ordinary one: the workspace the operator opened.
96
+ guidance: writeAccessGuidance(workspaceDir, access),
97
+ },
98
+ });
99
+ }
100
+ case 'files': {
101
+ const { store, project } = await open(url.searchParams.get('project'));
102
+ return json({ project: project.id, files: await store.listFiles(project) });
103
+ }
104
+ case 'file': {
105
+ const { store, project } = await open(url.searchParams.get('project'));
106
+ return json(await store.readTextFile(project, url.searchParams.get('path') ?? ''));
107
+ }
108
+ case 'save-file': {
109
+ const body = await readBody(request);
110
+ const { store, project } = await open(body.project);
111
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
112
+ const content = typeof body.content === 'string' ? body.content : '';
113
+ return json(await store.writeTextFile(project, path, content));
114
+ }
115
+ case 'create-dir': {
116
+ const body = await readBody(request);
117
+ const { store, project } = await open(body.project);
118
+ // One segment, not a path: the panel sends the directory it is aimed
119
+ // at separately, so a name carrying separators could only ever mean
120
+ // something other than what it looks like.
121
+ const name = assertPathName(body.name);
122
+ const dir = typeof body.dir === 'string' && body.dir.length > 0 ? assertRelativePath(body.dir) : '';
123
+ const path = dir === '' ? name : `${dir}/${name}`;
124
+ return json(await store.createDirectory(project, path), 201);
125
+ }
126
+ case 'create-file': {
127
+ const body = await readBody(request);
128
+ const { store, project } = await open(body.project);
129
+ const title = typeof body.title === 'string' && body.title.trim().length > 0 ? body.title : '未命名';
130
+ // The directory the author is browsing, sent by the panel. Without one,
131
+ // the workspace root is where the tree is.
132
+ const dir = typeof body.dir === 'string' && body.dir.length > 0 ? assertRelativePath(body.dir) : '';
133
+ // The name is kept exactly as typed: no `.md` the author did not ask
134
+ // for, and no second extension when the name has one. The heading is
135
+ // seeded only for prose names — a `.json` is not a document.
136
+ const name = assertPathName(title);
137
+ const extension = /\.[A-Za-z0-9]+$/.exec(name)?.[0].toLowerCase() ?? '';
138
+ const prose = extension === '' || extension === '.md' || extension === '.markdown';
139
+ const stem = extension === '' ? name : name.slice(0, -extension.length);
140
+ const path = await store.newNamedPath(project, dir, name);
141
+ return json(await store.writeTextFile(project, path, prose ? `# ${stem}\n\n` : ''), 201);
142
+ }
143
+ case 'focus': {
144
+ // The page's directory, made to matter to the model: the Session's
145
+ // working directory becomes the workspace the tree shows. No file is
146
+ // touched, so this is not a write op: a read-only deployment still gets
147
+ // it, and the model still reads the right directory.
148
+ const body = await readBody(request);
149
+ const { project } = await open(body.project);
150
+ const focused = await focus(sessionId, project.abs);
151
+ return json({ project: project.id, dir: project.abs, focused });
152
+ }
153
+ case 'reveal': {
154
+ // Show the workspace in the OS file manager. The path is optional and, when
155
+ // given, is resolved and re-checked against the workspace before anything is
156
+ // opened — so the panel can reveal a folder (or the folder holding a file)
157
+ // without the browser ever naming a directory the Host did not prove is
158
+ // inside the tree it shows. `dryRun` is the test hook: it answers what
159
+ // would be launched without launching it.
160
+ const body = await readBody(request);
161
+ const wanted = typeof body.path === 'string' && body.path.length > 0
162
+ ? assertRelativePath(body.path)
163
+ : '';
164
+ const { project } = await open(WORKSPACE_PROJECT);
165
+ const target = await workspace.revealDirectoryFor(project, wanted);
166
+ if (body.dryRun === true) {
167
+ const launch = revealCommand(process.platform, target);
168
+ return json({ dir: target, command: launch.command, args: launch.args, opened: false });
169
+ }
170
+ const opened = await revealInFileManager(target);
171
+ if (!opened)
172
+ log.warn(`cannot open a file manager for ${target}`);
173
+ return json({ dir: target, opened });
174
+ }
175
+ case 'rename': {
176
+ // One entry, in place: the new name is a single segment, so this cannot
177
+ // move a chapter folder somewhere else in the tree.
178
+ const body = await readBody(request);
179
+ const { store, project } = await open(body.project);
180
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
181
+ const name = assertPathName(body.name);
182
+ refuseReadOnly(access, workspaceDir);
183
+ const renamed = await store.renameEntry(project, path, name);
184
+ return json({ ...renamed, from: path });
185
+ }
186
+ case 'delete': {
187
+ // Irreversible, so the answer says what went: the panel asks first and
188
+ // needs to tell the author what the confirmation actually removed.
189
+ const body = await readBody(request);
190
+ const { store, project } = await open(body.project);
191
+ const path = assertRelativePath(typeof body.path === 'string' ? body.path : '');
192
+ refuseReadOnly(access, workspaceDir);
193
+ const removed = await store.deleteEntry(project, path);
194
+ return json(removed);
195
+ }
196
+ case 'count': {
197
+ // How much a delete would take, for the confirmation. Read-only, so it is
198
+ // answered even on a deployment that refuses the delete itself.
199
+ const { store, project } = await open(url.searchParams.get('project'));
200
+ const path = assertRelativePath(url.searchParams.get('path') ?? '');
201
+ return json({ path, files: await store.countFilesUnder(project, path) });
202
+ }
203
+ case 'ensure-readme': {
204
+ // The one file the panel adds to a workspace on first open. Never an
205
+ // overwrite: a workspace that already has a README keeps it, and the
206
+ // answer says so.
207
+ const { store, project } = await open(WORKSPACE_PROJECT);
208
+ const present = await store.readTextFile(project, 'README.md')
209
+ .then(() => true, () => false);
210
+ if (present)
211
+ return json({ path: 'README.md', created: false });
212
+ await store.writeTextFile(project, 'README.md', workspaceReadme());
213
+ return json({ path: 'README.md', created: true }, 201);
214
+ }
215
+ // Not in the write set: a reply touches nothing.
216
+ default:
217
+ return json({ code: 'bad-request', message: `unknown op ${JSON.stringify(op)}` }, 400);
218
+ }
219
+ }
220
+ catch (error) {
221
+ return failure(error);
222
+ }
223
+ };
224
+ return connection.fetch.register({
225
+ path: API_PATH,
226
+ methods: ['GET', 'POST'],
227
+ requestBody: 'buffered',
228
+ fetch: handle,
229
+ });
230
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Show the workspace in the operating system's file manager.
3
+ *
4
+ * The directory column is a *view* of the workspace, and the browser cannot open
5
+ * a local folder — so "show me the real folder" is the one thing the page has to
6
+ * ask the Host for. The directory is always the workspace that request resolved
7
+ * to: nothing here takes a path from the client, so the panel can never be talked
8
+ * into opening somewhere else.
9
+ *
10
+ * On Windows the launch goes through **`cmd /c start`**, not `explorer.exe`
11
+ * directly, and the child is **not** started hidden. Both halves were measured:
12
+ * spawning `explorer.exe` starts a process that exits without ever showing a
13
+ * window, and a hidden show-state (`windowsHide`, `-WindowStyle Hidden`) is
14
+ * inherited by the window ShellExecute creates, so the folder opens invisibly.
15
+ * `cmd /c start` with the default show state uses ShellExecute, and the
16
+ * already-running Explorer opens a window the author can see.
17
+ *
18
+ * @module notebook/http/reveal
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ /**
22
+ * The command that opens one directory on a platform.
23
+ *
24
+ * Exported for the test that asserts the mapping without launching anything: a
25
+ * test suite that opens windows on the machine running it is not a test.
26
+ * @param platform - `process.platform`.
27
+ * @param dir - an absolute directory path.
28
+ * @returns what to launch.
29
+ */
30
+ export function revealCommand(platform, dir) {
31
+ if (platform === 'win32') {
32
+ // ShellExecute through `start`: the empty argument is the window title slot,
33
+ // which `start` requires before a quoted target.
34
+ return {
35
+ command: process.env.ComSpec ?? 'cmd.exe',
36
+ args: ['/c', `start "" "${dir}"`],
37
+ verbatim: true,
38
+ };
39
+ }
40
+ if (platform === 'darwin')
41
+ return { command: 'open', args: [dir], verbatim: false };
42
+ return { command: 'xdg-open', args: [dir], verbatim: false };
43
+ }
44
+ /**
45
+ * Launch the platform's file manager on a directory.
46
+ * @param dir - an absolute directory path.
47
+ * @returns whether the launcher was started; `false` means it was not.
48
+ */
49
+ export function revealInFileManager(dir) {
50
+ const launch = revealCommand(process.platform, dir);
51
+ return new Promise((resolve) => {
52
+ try {
53
+ const child = spawn(launch.command, launch.args, {
54
+ detached: true,
55
+ stdio: 'ignore',
56
+ // No `windowsHide`: it would be inherited by the Explorer window this
57
+ // launches, which then opens invisibly. The child inherits this process's
58
+ // console, so there is no console flash to hide either.
59
+ windowsVerbatimArguments: launch.verbatim,
60
+ });
61
+ child.on('error', () => { resolve(false); });
62
+ child.on('spawn', () => { child.unref(); resolve(true); });
63
+ }
64
+ catch {
65
+ resolve(false);
66
+ }
67
+ });
68
+ }
@@ -0,0 +1,15 @@
1
+ export const STATUS_BY_CODE = {
2
+ 'bad-request': 400,
3
+ forbidden: 403,
4
+ 'not-found': 404,
5
+ conflict: 409,
6
+ internal: 500,
7
+ };
8
+ /**
9
+ * The status for one error code, for a caller that already has the code.
10
+ * @param code - the failure's code.
11
+ * @returns the HTTP status to answer with.
12
+ */
13
+ export function statusFor(code) {
14
+ return STATUS_BY_CODE[code];
15
+ }
package/lib/index.js ADDED
@@ -0,0 +1,100 @@
1
+ /**
2
+ * Host half of the 笔记本 (Notebook) bundle.
3
+ *
4
+ * Activation wires exactly one thing onto one owned effect, so unloading the
5
+ * plugin removes it: the authenticated JSON control plane. The client half is the
6
+ * panel; the files it edits are the workspace's own, and the harness's `read`/
7
+ * `write` tools already reach them.
8
+ *
9
+ * The three services this depends on are declared in `inject`, which is what
10
+ * keeps the plugin inactive — rather than broken — in a profile that has no web
11
+ * carrier.
12
+ */
13
+ import { fallbackRootDir } from './story/bootstrap.js';
14
+ import { API_PATH, registerApi } from './http/api.js';
15
+ import { createRootResolver } from './story/root.js';
16
+ import { createFocus } from './story/focus.js';
17
+ import { assessWriteAccess, writeAccessGuidance } from './story/sandbox.js';
18
+ /**
19
+ * Services that must exist for this plugin to be useful.
20
+ *
21
+ * Nothing else is required, and nothing optional decides whether the panel
22
+ * works: the tree is rooted at the workspace the Session opened, so there is no
23
+ * directory to choose and no config row to write.
24
+ */
25
+ export const inject = ['fs', 'webServer', 'connection'];
26
+ /**
27
+ * Activate the plugin.
28
+ * @param ctx - the owning context; every registration below is an effect of it.
29
+ * @param rawConfig - the Loader row's `config`, which this plugin no longer has.
30
+ * It is read only to warn about a row still carrying the retired `rootDir`:
31
+ * silently ignoring it would leave a profile that looks pinned to a directory
32
+ * the panel is not showing.
33
+ */
34
+ export function apply(ctx, rawConfig) {
35
+ const log = ctx.logger;
36
+ const policy = ctx.get('sandboxPolicy');
37
+ const configured = typeof rawConfig === 'object' && rawConfig !== null
38
+ ? rawConfig
39
+ : {};
40
+ if (configured.rootDir !== undefined) {
41
+ log.warn('notebook: rootDir is no longer a configuration field; the tree follows the workspace. '
42
+ + 'To keep a notebook somewhere else, open that directory as the workspace.');
43
+ }
44
+ for (const field of Object.keys(configured)) {
45
+ if (field !== 'rootDir')
46
+ log.warn(`notebook: unknown configuration field ${field}; this plugin takes none`);
47
+ }
48
+ const fallbackRoot = fallbackRootDir(policy);
49
+ // The root is resolved per call rather than here: it follows the workspace of
50
+ // the Session making the call, so one plugin instance serves every workspace in
51
+ // the profile instead of pinning one mutable root. See `root.ts` for the rule
52
+ // and the per-root write policy it stamps.
53
+ const roots = createRootResolver({ fs: ctx.fs, fallbackRoot, policy, agents: ctx.get('agents'), log });
54
+ const initialRoot = roots().root;
55
+ const access = assessWriteAccess(initialRoot.dir, policy);
56
+ // Puts the Session into the directory the panel shows, so the model's relative
57
+ // paths and the tree agree; see `story/focus.ts`.
58
+ const focus = createFocus({
59
+ agents: () => ctx.get('agents'),
60
+ workingDirectory: () => ctx.get('workingDirectory'),
61
+ log,
62
+ });
63
+ log.info(`notebook: root=${initialRoot.dir} (${initialRoot.source})`);
64
+ if (initialRoot.source === 'fallback') {
65
+ // A session-less activation. The panel and every call resolve their own root
66
+ // from the Session that made the call, so this fallback is what a scripted
67
+ // caller with no Session would see.
68
+ log.info(`notebook: no Session at activation; fallback root is ${initialRoot.dir}`);
69
+ }
70
+ if (policy === undefined) {
71
+ log.info('notebook: no sandbox-policy service in this profile; writes are unconfined');
72
+ }
73
+ else if (access.writable) {
74
+ // The boundary a write is checked against is the root of that call, not this
75
+ // deployment value: each write stamps `{ mode, workspaceRoot: <that root> }`
76
+ // (see `sandbox.ts`). The mode, though, is the Session's own.
77
+ log.info(`notebook: writes allowed (mode=${String(access.mode)}, boundary=each call's root)`);
78
+ }
79
+ else {
80
+ // Worth a warning rather than an error: the plugin still mounts and still
81
+ // reads, and the panel shows the same guidance with the exact YAML to paste.
82
+ log.warn(`notebook: deployment is read-only; every write will be refused\n${String(writeAccessGuidance(initialRoot.dir, access))}`);
83
+ }
84
+ ctx.effect(() => {
85
+ // Registration is synchronous; the returned disposer settles asynchronously
86
+ // because the Fetch bridge may be tearing down a live request.
87
+ const disposeApi = registerApi({
88
+ connection: ctx.connection,
89
+ fs: ctx.fs,
90
+ roots,
91
+ log,
92
+ policy,
93
+ focus,
94
+ });
95
+ return () => { void disposeApi(); };
96
+ }, 'notebook: api');
97
+ // Surfaced so the page can show the exact mount point it is talking to without
98
+ // hard-coding it a second time.
99
+ log.info(`notebook: api ${API_PATH}`);
100
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * The directory a session-less caller falls back to.
3
+ *
4
+ * Notes live **in the workspace the operator opened** (see `root.ts`), so this
5
+ * module covers only what is left over: the directory a caller with no Session at
6
+ * all falls back to.
7
+ *
8
+ * The fallback is the deployment's own write boundary — not a `novels/` shelf
9
+ * inside it. The shelf is gone: the panel's tree was already the workspace, and a
10
+ * second root the plugin invented only had to be explained. Nothing is seeded
11
+ * here either; the workspace's `README.md` is written on first open by
12
+ * `op=ensure-readme`, which is the one file the panel adds rather than a scaffold
13
+ * of empty folders.
14
+ */
15
+ import { homedir } from 'node:os';
16
+ import { join } from 'node:path';
17
+ /**
18
+ * Where notes live when no Session resolves a root.
19
+ *
20
+ * Used only for a session-less caller: the panel and every tool call carry a
21
+ * Session, and that Session's workspace is the root. Chosen inside the
22
+ * deployment's write boundary so that even this last resort is writable.
23
+ *
24
+ * `workingDirectory.defaultDirectory` is deliberately not consulted. Its own
25
+ * contract calls it the "absolute deployment fallback for Sessions with no
26
+ * recorded original directory", which on a normal install is simply wherever the
27
+ * Harness was launched from.
28
+ * @param policy - the sandbox policy service, when this profile has one.
29
+ * @returns an absolute directory path; it need not exist yet.
30
+ */
31
+ export function fallbackRootDir(policy) {
32
+ const boundary = policy?.workspaceRoot;
33
+ if (boundary !== undefined && boundary.trim().length > 0)
34
+ return boundary.trim();
35
+ const configured = process.env.DSH_HOME;
36
+ const home = configured !== undefined && configured.trim().length > 0
37
+ ? configured.trim()
38
+ : join(homedir(), '.dsh');
39
+ return join(home, 'notebook');
40
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Build the focus function over the host's services.
3
+ *
4
+ * The move itself is best-effort — a panel that opened a story must not fail
5
+ * because this profile has no working-directory service, because the Session is
6
+ * gone, or because the directory was removed between the read and the write.
7
+ * Every failure is reported in the log and answered with `false`.
8
+ *
9
+ * @param deps - the agent registry, working-directory service and logger.
10
+ * @returns a function that moves one Session into one story.
11
+ */
12
+ export function createFocus(deps) {
13
+ const { agents, workingDirectory, log } = deps;
14
+ let warned = false;
15
+ return async (sessionId, book) => {
16
+ if (sessionId === undefined)
17
+ return false;
18
+ const service = workingDirectory();
19
+ if (service === undefined) {
20
+ // Once, not per selection: a profile without the service would otherwise log
21
+ // on every story the panel opens.
22
+ if (!warned) {
23
+ warned = true;
24
+ log.warn('notebook: no working-directory service in this profile; the Session keeps its own directory');
25
+ }
26
+ return false;
27
+ }
28
+ const agent = agents()?.get(sessionId);
29
+ // A scripted caller can name a Session that is not live; there is nothing to
30
+ // move and nothing worth reporting, since the next panel request retries.
31
+ if (agent === undefined)
32
+ return false;
33
+ try {
34
+ await service.set(agent, book);
35
+ log.info(`notebook: Session ${sessionId} works in ${book}`);
36
+ return true;
37
+ }
38
+ catch (error) {
39
+ log.warn(`notebook: could not move Session ${sessionId} into ${book}`, error);
40
+ return false;
41
+ }
42
+ };
43
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * What the notebook's tree shows, and how a file is read back.
3
+ *
4
+ * The format layer, kept apart from the IO that serves it: everything here is
5
+ * pure — which names the browser may open, how a text is counted — and the store
6
+ * in `project.ts` owns the filesystem, the sandbox policy and the listing.
7
+ *
8
+ * @module notebook/story/manuscript
9
+ */
10
+ import { basename } from 'node:path';
11
+ /** Deepest nesting the tree descends into. */
12
+ export const MAX_TREE_DEPTH = 8;
13
+ /** Ceiling on files listed for one root, so a huge tree cannot stall the page. */
14
+ export const MAX_TREE_ENTRIES = 2_000;
15
+ /** Extensions the browser opens as editable text. */
16
+ export const TEXT_EXTENSIONS = new Set(['.md', '.markdown', '.txt', '.json', '.jsonl', '.yml', '.yaml', '.csv']);
17
+ /**
18
+ * Whether a file is text the editor may open.
19
+ *
20
+ * An allowlist rather than a denylist: a working directory accumulates images,
21
+ * archives and OS droppings, and showing all of it would bury the notes. A bare
22
+ * name has no extension at all — the panel names files by title (`第一章`) — and
23
+ * a title is a text file; only an *unknown* extension is refused.
24
+ * @param path - project-relative path; only its basename is considered.
25
+ * @returns true when the file is editable text.
26
+ */
27
+ export function isTextFile(path) {
28
+ const name = basename(path);
29
+ const dot = name.lastIndexOf('.');
30
+ if (dot <= 0)
31
+ return true;
32
+ return TEXT_EXTENSIONS.has(name.slice(dot).toLowerCase());
33
+ }
34
+ /** Whether an error means "the file is not there". */
35
+ export function isMissing(error) {
36
+ const code = error?.code;
37
+ return code === 'ENOENT' || code === 'FS_NOT_FOUND';
38
+ }
39
+ /**
40
+ * Count characters the way a writer counts them: code points, front-matter aside.
41
+ * @param content - the full file text.
42
+ * @returns the code-point count of the body.
43
+ */
44
+ export function countChars(content) {
45
+ const withoutFrontMatter = content.startsWith('---')
46
+ ? content.replace(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/, '')
47
+ : content;
48
+ return [...withoutFrontMatter].length;
49
+ }