@lincyaw/workspace 1.0.0-rc.15 → 1.0.0-rc.151
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/README.md +6 -4
- package/package.json +12 -6
- package/src/domain/paths.ts +0 -15
- package/src/node/agent-activity.ts +46 -0
- package/src/node/archive.ts +33 -0
- package/src/node/authoring-clients.ts +73 -20
- package/src/node/authoring-windows.ts +165 -0
- package/src/node/build.ts +16 -6
- package/src/node/capture.ts +383 -0
- package/src/node/config.ts +135 -50
- package/src/node/document-assets.ts +2 -2
- package/src/node/document-audio.ts +66 -47
- package/src/node/document-authoring.ts +30 -15
- package/src/node/document-check.ts +36 -0
- package/src/node/document-history.ts +32 -5
- package/src/node/document-images.ts +24 -14
- package/src/node/document-import.ts +123 -0
- package/src/node/document-index.ts +654 -0
- package/src/node/document-materials.ts +80 -0
- package/src/node/document-operations.ts +4 -2
- package/src/node/document-transcription.ts +2 -1
- package/src/node/document-voice.ts +121 -13
- package/src/node/git-runner.mjs +19 -0
- package/src/node/git.ts +141 -22
- package/src/node/host-activity.ts +17 -0
- package/src/node/host-upgrade.ts +28 -0
- package/src/node/jobs.ts +40 -8
- package/src/node/local-history.ts +85 -0
- package/src/node/locks.ts +12 -0
- package/src/node/mcp-settings.ts +68 -0
- package/src/node/media-upload-messages.ts +4 -0
- package/src/node/media-upload-page.ts +57 -0
- package/src/node/media-upload.css +4 -0
- package/src/node/media-uploads.ts +116 -0
- package/src/node/page-delete.ts +0 -1
- package/src/node/project-files.ts +2 -2
- package/src/node/projects.ts +20 -5
- package/src/node/review/agent-session-reviews.ts +211 -68
- package/src/node/review/agent-workspace.ts +151 -0
- package/src/node/review/git-review.ts +72 -29
- package/src/node/review/record.ts +41 -9
- package/src/node/review/routes.ts +9 -1
- package/src/node/review/windows-dependencies.ts +163 -0
- package/src/node/review/workspace-review.ts +87 -0
- package/src/node/revision-files.ts +54 -0
- package/src/node/revisions.ts +318 -80
- package/src/node/routes.ts +52 -59
- package/src/node/serve.ts +267 -52
- package/src/node/site.ts +5 -5
- package/src/node/source-editor.ts +66 -26
- package/src/node/speech-settings.ts +6 -8
- package/src/node/templates.ts +2 -2
- package/src/node/tree-operations.ts +425 -0
- package/src/node/tree-routes.ts +107 -0
- package/src/node/workbench-api.ts +14 -3
- package/src/node/workspace-changes.ts +130 -0
- package/src/node/workspace-migrate.ts +54 -0
- package/src/node/workspace-source.ts +133 -0
- package/src/node/writer.ts +21 -8
- package/templates/document/default/{lecture.json → index.pmd} +5 -1
|
@@ -0,0 +1,654 @@
|
|
|
1
|
+
import { existsSync, readFileSync, watch } from 'node:fs'
|
|
2
|
+
import type { FSWatcher } from 'node:fs'
|
|
3
|
+
import { readdir, readFile, realpath, stat } from 'node:fs/promises'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
import { setImmediate as yieldToEvents } from 'node:timers/promises'
|
|
6
|
+
import { provideDocumentEntries } from '@lincyaw/compiler'
|
|
7
|
+
import type { ScannedDocument } from '@lincyaw/compiler'
|
|
8
|
+
import { blockFirstText, blockSubtree, DOCUMENT_ENTRY, documentCitationSites, documentSearchText, documentTree, isRecord, targetExcerpt } from '@lincyaw/kernel'
|
|
9
|
+
import type { AttentionCount, BlockId, DocumentCitation, DocumentId, DocumentLinks, DocumentPlacement, DocumentPreview, DocumentSearchHit, DocumentTree, EmbedSource, OutgoingLink, PlacementTree, PresmiumDocument, ReferenceTarget, SectionId, TrashEntry, TreeIssue, TreeNode, WorkspaceAttention } from '@lincyaw/kernel'
|
|
10
|
+
import { primeDocumentHead } from './config.ts'
|
|
11
|
+
import type { WorkspaceConfig } from './config.ts'
|
|
12
|
+
|
|
13
|
+
/** The workspace folder trashed documents are moved to, one folder per document ID. */
|
|
14
|
+
export const TRASH_DIR = '.trash'
|
|
15
|
+
/** The record beside a trashed document: where it came from and where it sat in the tree. */
|
|
16
|
+
export const TRASH_RECORD = 'trashed.json'
|
|
17
|
+
/** Folders discovery never enters, as in the compiler's scan; `locales/<lang>/` holds translations. */
|
|
18
|
+
const SKIPPED = new Set(['node_modules', '.git', '.presmium', 'dist', TRASH_DIR])
|
|
19
|
+
/** How long file events are gathered before the index reads the files they name. */
|
|
20
|
+
const SETTLE_MS = 40
|
|
21
|
+
/** A walk of the whole workspace also runs this often, for what file events cannot tell (watching unavailable, new folders deep in a document). */
|
|
22
|
+
const SWEEP_MS = 30_000
|
|
23
|
+
/** Work done between two yields to the event loop while reading many files. */
|
|
24
|
+
const SLICE_MS = 8
|
|
25
|
+
const READ_CONCURRENCY = 8
|
|
26
|
+
|
|
27
|
+
export interface TrashRecord {
|
|
28
|
+
deletedAt: string
|
|
29
|
+
/** The document folder it was trashed from, relative to the workspace root. */
|
|
30
|
+
from: string
|
|
31
|
+
parent: DocumentId | null
|
|
32
|
+
rank: string
|
|
33
|
+
/** The documents trashed with it, its descendants at the time. */
|
|
34
|
+
children: DocumentId[]
|
|
35
|
+
/** Set on a descendant: the document whose trashing took it along. */
|
|
36
|
+
with?: DocumentId
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** A reference or synced block in a document, as the index keeps it. */
|
|
40
|
+
interface Site { kind: 'reference' | 'embed', target: ReferenceTarget, block: BlockId, section?: SectionId, excerpt: string, label?: string, fallback?: string }
|
|
41
|
+
|
|
42
|
+
/** What the index keeps of one document: never the whole document, which is read again when needed. */
|
|
43
|
+
export interface IndexEntry {
|
|
44
|
+
id: DocumentId
|
|
45
|
+
/** The document folder, relative to the workspace root. */
|
|
46
|
+
dir: string
|
|
47
|
+
title: string
|
|
48
|
+
placement: DocumentPlacement
|
|
49
|
+
sites: Site[]
|
|
50
|
+
/** The current titles its pages and blocks give references to them. */
|
|
51
|
+
pages: Map<SectionId, string>
|
|
52
|
+
blocks: Map<BlockId, string>
|
|
53
|
+
/** The first text of the document and of each page, for previews. */
|
|
54
|
+
excerpt: string
|
|
55
|
+
pageExcerpts: Map<SectionId, string>
|
|
56
|
+
steps: number
|
|
57
|
+
/** Lowercase search text: the title, then everything (for a quick test), then page titles and blocks. */
|
|
58
|
+
search: { title: string, all: string, pages: { id: SectionId, title: string, lower: string }[], blocks: { id: BlockId, section?: SectionId, text: string, lower: string }[] }
|
|
59
|
+
schemaVersion: unknown
|
|
60
|
+
/** What a client's tree shows of it; a change of this is a change of the tree. */
|
|
61
|
+
treeKey: string
|
|
62
|
+
/** What references to it show; a change of this can make other documents' fallbacks outdated. */
|
|
63
|
+
titleKey: string
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface TrashedEntry extends IndexEntry { record: TrashRecord }
|
|
67
|
+
|
|
68
|
+
interface FileState { mtimeMs: number, size: number, entry?: IndexEntry }
|
|
69
|
+
interface LocatedDocument { document: PresmiumDocument, dir: string, trashed: boolean }
|
|
70
|
+
|
|
71
|
+
const dirOf = (entry: string) => entry.split('/').slice(0, -1).join('/')
|
|
72
|
+
|
|
73
|
+
/** The index's view of one parsed document. */
|
|
74
|
+
function indexEntry(document: PresmiumDocument, dir: string): IndexEntry {
|
|
75
|
+
const sites = documentCitationSites(document).map(site => ({ kind: site.kind, target: site.target, block: site.block, ...site.section !== undefined ? { section: site.section } : {}, excerpt: site.excerpt, ...site.node?.label !== undefined ? { label: site.node.label } : {}, ...site.node ? { fallback: site.node.fallback } : {} }))
|
|
76
|
+
const text = documentSearchText(document)
|
|
77
|
+
const pages = new Map(document.sectionOrder.flatMap(id => document.sections[id] ? [[id, document.sections[id]!.title] as const] : []))
|
|
78
|
+
const blocks = new Map(Object.keys(document.blocks).map(id => [id, blockFirstText(document, id) || document.metadata.title]))
|
|
79
|
+
const pageExcerpts = new Map(document.sectionOrder.map(id => [id, targetExcerpt(document, { section: id })]))
|
|
80
|
+
const title = document.metadata.title
|
|
81
|
+
const searchPages = text.pages.map(page => ({ ...page, lower: page.title.toLowerCase() }))
|
|
82
|
+
const searchBlocks = text.blocks.map(block => ({ ...block, lower: block.text.toLowerCase() }))
|
|
83
|
+
return {
|
|
84
|
+
id: document.id, dir, title, placement: document.placement, sites, pages, blocks, schemaVersion: document.schemaVersion,
|
|
85
|
+
excerpt: targetExcerpt(document, {}), pageExcerpts,
|
|
86
|
+
steps: document.sectionOrder.reduce((sum, section) => sum + (document.sections[section]?.stepOrder.length ?? 0), 0),
|
|
87
|
+
search: { title: title.toLowerCase(), all: [title, ...text.pages.map(page => page.title), ...text.blocks.map(block => block.text)].join('\n').toLowerCase(), pages: searchPages, blocks: searchBlocks },
|
|
88
|
+
treeKey: JSON.stringify([document.id, title, document.placement?.parent ?? null, document.placement?.rank ?? '', dir]),
|
|
89
|
+
titleKey: JSON.stringify([title, [...pages], [...blocks]]),
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function parseDocument(text: string): PresmiumDocument | undefined {
|
|
94
|
+
let value: unknown
|
|
95
|
+
try { value = JSON.parse(text.replace(/^/, '')) } catch { return undefined }
|
|
96
|
+
if (!isRecord(value) || typeof value.id !== 'string' || !isRecord(value.metadata) || !isRecord(value.blocks) || !isRecord(value.sections) || !Array.isArray(value.sectionOrder) || !isRecord(value.steps) || !isRecord(value.definitions)) return undefined
|
|
97
|
+
return value as unknown as PresmiumDocument
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function trashRecord(value: unknown): TrashRecord | undefined {
|
|
101
|
+
if (!isRecord(value) || typeof value.from !== 'string') return undefined
|
|
102
|
+
return { deletedAt: typeof value.deletedAt === 'string' ? value.deletedAt : '', from: value.from, parent: typeof value.parent === 'string' ? value.parent : null, rank: typeof value.rank === 'string' ? value.rank : '', children: Array.isArray(value.children) ? value.children.filter((id): id is string => typeof id === 'string') : [], ...typeof value.with === 'string' ? { with: value.with } : {} }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The tree, the references in both directions, and what is derived from them; rebuilt only when what they depend on changed. */
|
|
106
|
+
interface Derived {
|
|
107
|
+
documents: Map<DocumentId, IndexEntry>
|
|
108
|
+
order: DocumentId[]
|
|
109
|
+
tree?: PlacementTree
|
|
110
|
+
incoming: Map<DocumentId, { citing: IndexEntry, site: Site }[]>
|
|
111
|
+
clientTree?: DocumentTree
|
|
112
|
+
/** Every entry file as the compiler's scan describes it. */
|
|
113
|
+
scanned: ScannedDocument[]
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The workspace's document index (docs/authoring-actions.md, section 15): the tree from every document's placement,
|
|
118
|
+
* the trash, the references and synced blocks between documents in both directions, and a search over titles and text.
|
|
119
|
+
* Derived from the files and never stored. File events on the document folders (and on the folders that hold them)
|
|
120
|
+
* mark what to read again; reading is asynchronous, parses only the files that changed and yields to the event loop
|
|
121
|
+
* between slices, and every answer is computed from what is already in memory. A slow walk of the whole workspace
|
|
122
|
+
* now and then catches what file events cannot report.
|
|
123
|
+
*/
|
|
124
|
+
export class DocumentIndex {
|
|
125
|
+
readonly #config: WorkspaceConfig
|
|
126
|
+
/** Every entry file found, by its path relative to the root. */
|
|
127
|
+
readonly #files = new Map<string, FileState>()
|
|
128
|
+
readonly #trash = new Map<string, TrashedEntry>()
|
|
129
|
+
readonly #watchers = new Map<string, FSWatcher>()
|
|
130
|
+
readonly #listeners = new Set<() => void>()
|
|
131
|
+
readonly #titleListeners = new Set<(changed: DocumentId[]) => void>()
|
|
132
|
+
readonly #attentionListeners = new Set<() => void>()
|
|
133
|
+
/** The attention summary of one generation of the index, with its text to tell a change. */
|
|
134
|
+
#attention?: { generation: number, value: WorkspaceAttention, text: string }
|
|
135
|
+
#derived?: Derived
|
|
136
|
+
#dirty = new Set<string>()
|
|
137
|
+
readonly #folders = new Set<string>()
|
|
138
|
+
#walk = true
|
|
139
|
+
#trashDirty = true
|
|
140
|
+
#pending?: Promise<void>
|
|
141
|
+
#timer?: ReturnType<typeof setTimeout>
|
|
142
|
+
#sweep?: ReturnType<typeof setInterval>
|
|
143
|
+
#watching = true
|
|
144
|
+
#closed = false
|
|
145
|
+
/** What the compiler's scans see of each file: its time and size. */
|
|
146
|
+
readonly #stamps = new Map<string, string>()
|
|
147
|
+
readonly #trashStamps = new Map<string, string>()
|
|
148
|
+
#generation = 0
|
|
149
|
+
#stopProviding?: () => void
|
|
150
|
+
|
|
151
|
+
constructor(config: WorkspaceConfig) {
|
|
152
|
+
this.#config = config
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Starts watching and the occasional walk, and builds the index; until this, `ready` builds it on first use. */
|
|
156
|
+
async start(): Promise<void> {
|
|
157
|
+
this.#sweep = setInterval(() => { this.#walk = true; this.#trashDirty = true; this.#schedule() }, SWEEP_MS)
|
|
158
|
+
this.#sweep.unref()
|
|
159
|
+
// The compiler's scans in this process list the documents from the index instead of walking the workspace.
|
|
160
|
+
if (!this.#config.singleDeck) this.#stopProviding = provideDocumentEntries(this.#config.root, () => this.#derived && !this.#walk ? { generation: this.#generation, documents: this.#derived.scanned, stamps: this.#stamps } : undefined)
|
|
161
|
+
await this.ready()
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
close(): void {
|
|
165
|
+
this.#closed = true
|
|
166
|
+
clearTimeout(this.#timer)
|
|
167
|
+
clearInterval(this.#sweep)
|
|
168
|
+
this.#stopProviding?.()
|
|
169
|
+
for (const watcher of this.#watchers.values()) watcher.close()
|
|
170
|
+
this.#watchers.clear()
|
|
171
|
+
this.#listeners.clear()
|
|
172
|
+
this.#titleListeners.clear()
|
|
173
|
+
this.#attentionListeners.clear()
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Resolves once everything known to have changed has been read. */
|
|
177
|
+
ready(): Promise<void> {
|
|
178
|
+
if (!this.#derived || this.#walk || this.#dirty.size || this.#folders.size || this.#trashDirty) return this.#refresh()
|
|
179
|
+
return this.#pending ?? Promise.resolve()
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/** Tell the index which files an operation of this process changed (paths relative to the root); `structure` when folders appeared or went. */
|
|
183
|
+
async changed(paths: string[], structure = false): Promise<void> {
|
|
184
|
+
for (const path of paths) {
|
|
185
|
+
if (path.startsWith(`${TRASH_DIR}/`) || path === TRASH_DIR) this.#trashDirty = true
|
|
186
|
+
else this.#dirty.add(path.endsWith(DOCUMENT_ENTRY) ? path : path ? `${path}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)
|
|
187
|
+
}
|
|
188
|
+
if (structure) this.#walk = true
|
|
189
|
+
await this.#refresh()
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
#schedule(): void {
|
|
193
|
+
if (this.#closed || this.#timer) return
|
|
194
|
+
this.#timer = setTimeout(() => { this.#timer = undefined; void this.#refresh().catch(() => {}) }, SETTLE_MS)
|
|
195
|
+
this.#timer.unref?.()
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
#refresh(): Promise<void> {
|
|
199
|
+
const run = (this.#pending ?? Promise.resolve()).then(() => this.#update())
|
|
200
|
+
const tracked: Promise<void> = run.finally(() => { if (this.#pending === tracked) this.#pending = undefined })
|
|
201
|
+
this.#pending = tracked
|
|
202
|
+
return tracked
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
#watch(dir: string, onEvent: (name: string | null) => void): void {
|
|
206
|
+
if (!this.#watching || this.#watchers.has(dir)) return
|
|
207
|
+
try {
|
|
208
|
+
const watcher = watch(join(this.#config.root, dir), { persistent: false }, (_event, name) => onEvent(name === null ? null : String(name)))
|
|
209
|
+
watcher.on('error', () => { watcher.close(); this.#watchers.delete(dir); this.#walk = true; this.#schedule() })
|
|
210
|
+
this.#watchers.set(dir, watcher)
|
|
211
|
+
} catch (error) {
|
|
212
|
+
// Too many watches (or none at all): the occasional walk keeps the index current, if later. A folder that is
|
|
213
|
+
// gone by now is simply not watched.
|
|
214
|
+
const code = (error as NodeJS.ErrnoException).code
|
|
215
|
+
if (code === 'ENOSPC' || code === 'EMFILE' || code === 'ENOSYS') this.#watching = false
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** Every entry file and the folders worth watching, walked without blocking. */
|
|
220
|
+
async #discover(): Promise<{ entries: string[], containers: string[] }> {
|
|
221
|
+
const root = this.#config.root
|
|
222
|
+
if (this.#config.singleDeck) return { entries: [DOCUMENT_ENTRY], containers: [] }
|
|
223
|
+
const entries: string[] = [], containers: string[] = [], seen = new Set<string>()
|
|
224
|
+
const walk = async (rel: string, inDocument: boolean): Promise<void> => {
|
|
225
|
+
const path = rel ? join(root, rel) : root
|
|
226
|
+
let names
|
|
227
|
+
try {
|
|
228
|
+
const real = await realpath(path)
|
|
229
|
+
if (seen.has(real)) return
|
|
230
|
+
seen.add(real)
|
|
231
|
+
names = await readdir(path, { withFileTypes: true })
|
|
232
|
+
} catch { return }
|
|
233
|
+
const holds = names.some(item => item.name === DOCUMENT_ENTRY && (item.isFile() || item.isSymbolicLink()))
|
|
234
|
+
if (holds) entries.push(rel ? `${rel}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)
|
|
235
|
+
if (!inDocument || holds) containers.push(rel)
|
|
236
|
+
const folders = names.filter(item => !SKIPPED.has(item.name) && !item.name.startsWith('.') && item.name !== DOCUMENT_ENTRY && (item.isDirectory() || item.isSymbolicLink()))
|
|
237
|
+
for (const item of folders.sort((a, b) => a.name < b.name ? -1 : 1)) {
|
|
238
|
+
const next = rel ? `${rel}/${item.name}` : item.name
|
|
239
|
+
if (item.isSymbolicLink()) { try { if (!(await stat(join(root, next))).isDirectory()) continue } catch { continue } }
|
|
240
|
+
if (item.name !== 'locales') await walk(next, inDocument || holds)
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
await walk('', false)
|
|
244
|
+
return { entries, containers }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Reads the given entry files (relative paths), in slices that leave the event loop free. */
|
|
248
|
+
async #read(paths: string[], into: (path: string, state: FileState | undefined) => void): Promise<void> {
|
|
249
|
+
let slice = performance.now()
|
|
250
|
+
for (let at = 0; at < paths.length; at += READ_CONCURRENCY) {
|
|
251
|
+
const batch = paths.slice(at, at + READ_CONCURRENCY)
|
|
252
|
+
const read = await Promise.all(batch.map(async (path) => {
|
|
253
|
+
const file = join(this.#config.root, path)
|
|
254
|
+
try {
|
|
255
|
+
const info = await stat(file)
|
|
256
|
+
const known = this.#files.get(path)
|
|
257
|
+
if (known && known.mtimeMs === info.mtimeMs && known.size === info.size) return { path, state: known, text: undefined }
|
|
258
|
+
return { path, state: { mtimeMs: info.mtimeMs, size: info.size } as FileState, text: await readFile(file, 'utf8') }
|
|
259
|
+
} catch { return { path, state: undefined, text: undefined } }
|
|
260
|
+
}))
|
|
261
|
+
for (const { path, state, text } of read) {
|
|
262
|
+
if (state && text !== undefined) {
|
|
263
|
+
const document = parseDocument(text)
|
|
264
|
+
try { if (document) state.entry = indexEntry(document, dirOf(path)) } catch { /* Indexed as a file without a document. */ }
|
|
265
|
+
// The document list reads the same file's metadata; it finds it parsed already.
|
|
266
|
+
if (document) primeDocumentHead(join(this.#config.root, path), state.mtimeMs, state.size, document)
|
|
267
|
+
}
|
|
268
|
+
into(path, state)
|
|
269
|
+
if (performance.now() - slice > SLICE_MS) { await yieldToEvents(); slice = performance.now() }
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** The callback of a watched folder that holds documents (`document`: it is one itself). */
|
|
275
|
+
#folderEvents(dir: string, document: boolean): (name: string | null) => void {
|
|
276
|
+
const entryOf = (folder: string) => folder ? `${folder}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY
|
|
277
|
+
return (name) => {
|
|
278
|
+
// An entry file written here: this folder's document (new or changed).
|
|
279
|
+
if (name === DOCUMENT_ENTRY) this.#dirty.add(entryOf(dir))
|
|
280
|
+
else if (name === null) this.#walk = true
|
|
281
|
+
// A folder appeared or went: looked at when the index next reads (an operation of this process has usually told it already).
|
|
282
|
+
else if (!document) this.#folders.add(dir ? `${dir}/${name}` : name)
|
|
283
|
+
this.#schedule()
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Folders file events named: their documents are read again; only a folder that may hold documents deeper is walked. */
|
|
288
|
+
#lookAtFolders(): void {
|
|
289
|
+
for (const folder of this.#folders) {
|
|
290
|
+
// The trash folder itself appeared (or went): it is read, and watched while it exists.
|
|
291
|
+
if (folder === TRASH_DIR) { this.#trashDirty = true; continue }
|
|
292
|
+
const entry = `${folder}/${DOCUMENT_ENTRY}`
|
|
293
|
+
if (existsSync(join(this.#config.root, entry))) { if (!this.#files.has(entry)) this.#dirty.add(entry) }
|
|
294
|
+
else if (existsSync(join(this.#config.root, folder))) {
|
|
295
|
+
// A new folder without a document yet: watched, so the document written into it is seen (deeper ones by the walk).
|
|
296
|
+
const name = folder.split('/').at(-1)!
|
|
297
|
+
if (!SKIPPED.has(name) && !name.startsWith('.') && name !== 'locales') this.#watch(folder, this.#folderEvents(folder, false))
|
|
298
|
+
}
|
|
299
|
+
else for (const path of this.#files.keys()) if (path.startsWith(`${folder}/`)) this.#dirty.add(path)
|
|
300
|
+
}
|
|
301
|
+
this.#folders.clear()
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async #update(): Promise<void> {
|
|
305
|
+
if (this.#closed) return
|
|
306
|
+
this.#lookAtFolders()
|
|
307
|
+
const before = this.#derived
|
|
308
|
+
const changes: { path: string, before?: IndexEntry, after?: IndexEntry }[] = []
|
|
309
|
+
let structural = false
|
|
310
|
+
if (this.#walk) {
|
|
311
|
+
this.#walk = false
|
|
312
|
+
const { entries, containers } = await this.#discover()
|
|
313
|
+
const found = new Set(entries)
|
|
314
|
+
for (const [path, state] of [...this.#files]) if (!found.has(path)) { this.#files.delete(path); this.#stamps.delete(path); changes.push({ path, ...state.entry ? { before: state.entry } : {} }); structural = true }
|
|
315
|
+
// Watched folders: those that hold documents, and those on the way to them; never a document's own subfolders.
|
|
316
|
+
const wanted = new Set(containers)
|
|
317
|
+
for (const [dir, watcher] of this.#watchers) if (dir !== TRASH_DIR && !wanted.has(dir)) { watcher.close(); this.#watchers.delete(dir) }
|
|
318
|
+
for (const dir of containers) this.#watch(dir, this.#folderEvents(dir, found.has(dir ? `${dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
|
|
319
|
+
for (const entry of entries) if (!this.#files.has(entry)) this.#dirty.add(entry)
|
|
320
|
+
// Known files are looked at again only on the occasional walk (their events may have been missed).
|
|
321
|
+
if (before) for (const entry of entries) this.#dirty.add(entry)
|
|
322
|
+
}
|
|
323
|
+
if (this.#dirty.size) {
|
|
324
|
+
const paths = [...this.#dirty]
|
|
325
|
+
this.#dirty.clear()
|
|
326
|
+
await this.#read(paths, (path, state) => {
|
|
327
|
+
const known = this.#files.get(path)
|
|
328
|
+
if (state === known) return
|
|
329
|
+
changes.push({ path, ...known?.entry ? { before: known.entry } : {}, ...state?.entry ? { after: state.entry } : {} })
|
|
330
|
+
if (state) {
|
|
331
|
+
if (!known) {
|
|
332
|
+
structural = true
|
|
333
|
+
// A document this index did not know: watch its folder and the folder holding it.
|
|
334
|
+
const dir = dirOf(path)
|
|
335
|
+
this.#watch(dir, this.#folderEvents(dir, true))
|
|
336
|
+
const parent = dirOf(dir)
|
|
337
|
+
if (dir) this.#watch(parent, this.#folderEvents(parent, this.#files.has(parent ? `${parent}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)))
|
|
338
|
+
}
|
|
339
|
+
this.#files.set(path, state)
|
|
340
|
+
this.#stamps.set(path, `${state.mtimeMs}:${state.size}`)
|
|
341
|
+
} else {
|
|
342
|
+
this.#stamps.delete(path)
|
|
343
|
+
structural = true
|
|
344
|
+
this.#files.delete(path)
|
|
345
|
+
this.#watchers.get(dirOf(path))?.close()
|
|
346
|
+
this.#watchers.delete(dirOf(path))
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
}
|
|
350
|
+
let trashChanged = false
|
|
351
|
+
if (this.#trashDirty) {
|
|
352
|
+
this.#trashDirty = false
|
|
353
|
+
trashChanged = await this.#readTrash()
|
|
354
|
+
}
|
|
355
|
+
if (before && !changes.length && !trashChanged) return
|
|
356
|
+
this.#generation++
|
|
357
|
+
const treeChanged = !before || structural || trashChanged || changes.some(change => change.before?.treeKey !== change.after?.treeKey)
|
|
358
|
+
if (treeChanged) this.#derived = this.#derive()
|
|
359
|
+
else for (const change of changes) if (change.before && change.after) this.#replace(before, change.before, change.after)
|
|
360
|
+
const titleChanged = changes.flatMap(change => change.after && change.before?.titleKey !== change.after.titleKey ? [change.after.id] : [])
|
|
361
|
+
if (before && treeChanged) for (const listener of [...this.#listeners]) listener()
|
|
362
|
+
if (before && titleChanged.length) for (const listener of [...this.#titleListeners]) listener(titleChanged)
|
|
363
|
+
if (before && this.#attentionListeners.size) {
|
|
364
|
+
const was = this.#attention?.text
|
|
365
|
+
this.attention()
|
|
366
|
+
if (this.#attention!.text !== was) for (const listener of [...this.#attentionListeners]) listener()
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** One document changed without changing the tree: only its own entries are replaced. */
|
|
371
|
+
#replace(derived: Derived, before: IndexEntry, after: IndexEntry): void {
|
|
372
|
+
if (derived.documents.get(after.id) !== before) return
|
|
373
|
+
derived.documents.set(after.id, after)
|
|
374
|
+
for (const site of before.sites) {
|
|
375
|
+
const list = derived.incoming.get(site.target.document)
|
|
376
|
+
if (!list) continue
|
|
377
|
+
const kept = list.filter(item => item.citing !== before)
|
|
378
|
+
if (kept.length) derived.incoming.set(site.target.document, kept)
|
|
379
|
+
else derived.incoming.delete(site.target.document)
|
|
380
|
+
}
|
|
381
|
+
for (const site of after.sites) {
|
|
382
|
+
const list = derived.incoming.get(site.target.document)
|
|
383
|
+
if (list) list.push({ citing: after, site })
|
|
384
|
+
else derived.incoming.set(site.target.document, [{ citing: after, site }])
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
async #readTrash(): Promise<boolean> {
|
|
389
|
+
const folder = join(this.#config.root, TRASH_DIR)
|
|
390
|
+
let names: string[] = []
|
|
391
|
+
try {
|
|
392
|
+
names = (await readdir(folder)).sort()
|
|
393
|
+
this.#watch(TRASH_DIR, () => { this.#trashDirty = true; this.#schedule() })
|
|
394
|
+
} catch {
|
|
395
|
+
// No trash (any more): the workspace root's watcher reports when it appears.
|
|
396
|
+
this.#watchers.get(TRASH_DIR)?.close()
|
|
397
|
+
this.#watchers.delete(TRASH_DIR)
|
|
398
|
+
}
|
|
399
|
+
const signature = [...this.#trash.values()].map(entry => entry.treeKey + entry.record.deletedAt).join()
|
|
400
|
+
const known = new Map([...this.#trash.values()].map(entry => [entry.dir, entry]))
|
|
401
|
+
this.#trash.clear()
|
|
402
|
+
for (const name of names) {
|
|
403
|
+
const dir = `${TRASH_DIR}/${name}`
|
|
404
|
+
try {
|
|
405
|
+
const record = trashRecord(JSON.parse(await readFile(join(this.#config.root, dir, TRASH_RECORD), 'utf8')))
|
|
406
|
+
const info = await stat(join(this.#config.root, dir, DOCUMENT_ENTRY))
|
|
407
|
+
const stamp = `${info.mtimeMs}:${info.size}`
|
|
408
|
+
const reused = known.get(dir)
|
|
409
|
+
// A trashed document is parsed once; only its record is read again.
|
|
410
|
+
const entry = reused && this.#trashStamps.get(dir) === stamp ? reused : (() => { const document = parseDocument(readFileSync(join(this.#config.root, dir, DOCUMENT_ENTRY), 'utf8')); return document && indexEntry(document, dir) })()
|
|
411
|
+
if (record && entry) { this.#trash.set(entry.id, { ...entry, record }); this.#trashStamps.set(dir, stamp) }
|
|
412
|
+
} catch { /* Not a trashed document. */ }
|
|
413
|
+
}
|
|
414
|
+
return signature !== [...this.#trash.values()].map(entry => entry.treeKey + entry.record.deletedAt).join()
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** The tree, the references and the compiler's scan, from every document: when the tree changed. */
|
|
418
|
+
#derive(): Derived {
|
|
419
|
+
const entries = [...this.#files.entries()].flatMap(([path, state]) => state.entry ? [{ path, entry: state.entry }] : [])
|
|
420
|
+
const documents = new Map<DocumentId, IndexEntry>()
|
|
421
|
+
let tree: PlacementTree | undefined
|
|
422
|
+
if (this.#config.singleDeck) for (const { entry } of entries) documents.set(entry.id, entry)
|
|
423
|
+
else {
|
|
424
|
+
tree = documentTree(entries.map(({ path, entry }) => ({ id: entry.id, path, title: entry.title, placement: { parent: entry.placement?.parent ?? null, rank: entry.placement?.rank ?? '' } })))
|
|
425
|
+
for (const { entry } of entries) if (!documents.has(entry.id) && tree!.byId.get(entry.id)?.path === (entry.dir ? `${entry.dir}/${DOCUMENT_ENTRY}` : DOCUMENT_ENTRY)) documents.set(entry.id, entry)
|
|
426
|
+
}
|
|
427
|
+
const incoming = new Map<DocumentId, { citing: IndexEntry, site: Site }[]>()
|
|
428
|
+
for (const citing of documents.values()) for (const site of citing.sites) {
|
|
429
|
+
const list = incoming.get(site.target.document)
|
|
430
|
+
if (list) list.push({ citing, site })
|
|
431
|
+
else incoming.set(site.target.document, [{ citing, site }])
|
|
432
|
+
}
|
|
433
|
+
const order = tree ? tree.order.map(node => node.id) : [...documents.keys()]
|
|
434
|
+
const scanned = [...this.#files.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, state]): ScannedDocument => state.entry
|
|
435
|
+
? { id: state.entry.id, path, title: state.entry.title.trim() || dirOf(path) || path, placement: { parent: state.entry.placement?.parent ?? null, rank: state.entry.placement?.rank ?? '' }, schemaVersion: state.entry.schemaVersion }
|
|
436
|
+
: { id: `path:${path}`, path, title: dirOf(path) || path, placement: { parent: null, rank: '' }, schemaVersion: undefined, problem: 'not a document' })
|
|
437
|
+
return { documents, order, scanned, ...tree ? { tree } : {}, incoming }
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
#now(): Derived {
|
|
441
|
+
if (!this.#derived) throw new Error('document-index-not-ready')
|
|
442
|
+
return this.#derived
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
/** The documents in the workspace (not in the trash) and the tree their placements make. */
|
|
446
|
+
scan(): { documents: Map<DocumentId, IndexEntry>, tree?: PlacementTree, order: DocumentId[] } {
|
|
447
|
+
const { documents, tree, order } = this.#now()
|
|
448
|
+
return { documents, ...tree ? { tree } : {}, order }
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Every trashed document by ID, the ones trashed along with an ancestor included. */
|
|
452
|
+
trashed(): Map<DocumentId, TrashedEntry> {
|
|
453
|
+
this.#now()
|
|
454
|
+
return this.#trash
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** The whole document by ID, read from its file (in the workspace or in the trash). */
|
|
458
|
+
async read(id: DocumentId): Promise<LocatedDocument | undefined> {
|
|
459
|
+
const entry = this.#now().documents.get(id) ?? this.#trash.get(id)
|
|
460
|
+
if (!entry) return undefined
|
|
461
|
+
try {
|
|
462
|
+
const document = parseDocument(await readFile(join(this.#config.root, entry.dir, DOCUMENT_ENTRY), 'utf8'))
|
|
463
|
+
return document && document.id === id ? { document, dir: entry.dir, trashed: !this.#now().documents.has(id) } : undefined
|
|
464
|
+
} catch { return undefined }
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
tree(): DocumentTree {
|
|
468
|
+
const derived = this.#now()
|
|
469
|
+
if (derived.clientTree) return derived.clientTree
|
|
470
|
+
const { documents, tree } = derived
|
|
471
|
+
const nodes: Record<DocumentId, TreeNode> = {}
|
|
472
|
+
if (!tree) {
|
|
473
|
+
for (const entry of documents.values()) nodes[entry.id] = { id: entry.id, title: entry.title, path: entry.dir, parent: null, rank: entry.placement?.rank ?? '', depth: 0, children: [] }
|
|
474
|
+
return derived.clientTree = { roots: Object.keys(nodes), nodes, trash: [] }
|
|
475
|
+
}
|
|
476
|
+
const issues = new Map<DocumentId, TreeIssue[]>()
|
|
477
|
+
const add = (id: DocumentId, issue: TreeIssue) => issues.set(id, [...issues.get(id) ?? [], issue])
|
|
478
|
+
for (const problem of tree.problems) {
|
|
479
|
+
if (problem.code === 'tree.duplicate-id') add(problem.id, { code: problem.code, message: `Two documents have the ID ${problem.id}: ${problem.paths.join(' and ')}; only the first is in the tree.` })
|
|
480
|
+
else if (problem.code === 'tree.unknown-parent') add(problem.id, { code: problem.code, message: `The parent ${problem.parent} does not exist; the document is shown at the top level.` })
|
|
481
|
+
else add(problem.id, { code: problem.code, message: 'The document is placed under its own descendant; it is shown at the top level.' })
|
|
482
|
+
}
|
|
483
|
+
for (const node of tree.order) {
|
|
484
|
+
nodes[node.id] = { id: node.id, title: node.title, path: dirOf(node.path), parent: node.parent, rank: node.placement.rank, depth: node.depth, children: [...tree.children.get(node.id) ?? []], ...issues.has(node.id) ? { issues: issues.get(node.id) } : {} }
|
|
485
|
+
}
|
|
486
|
+
const trash: TrashEntry[] = [...this.#trash.values()].filter(entry => !entry.record.with).map((entry) => {
|
|
487
|
+
const parent = entry.record.parent
|
|
488
|
+
return { id: entry.id, title: entry.title, deletedAt: entry.record.deletedAt, from: entry.record.from, parent, children: entry.record.children, ...parent !== null && !documents.has(parent) && this.#trash.has(parent) ? { parentTrashed: true } : {} }
|
|
489
|
+
})
|
|
490
|
+
trash.sort((a, b) => a.deletedAt < b.deletedAt ? 1 : a.deletedAt > b.deletedAt ? -1 : 0)
|
|
491
|
+
return derived.clientTree = { roots: [...tree.children.get(null) ?? []], nodes, trash }
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/** The titles of the document's ancestors, root first. */
|
|
495
|
+
ancestors(id: DocumentId): string[] {
|
|
496
|
+
const { tree } = this.#now()
|
|
497
|
+
return tree && tree.byId.has(id) ? tree.ancestors(id).map(node => node.title) : []
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** The current title of a reference's target, or undefined when the document, page or block is gone (or trashed, with `live`). */
|
|
501
|
+
titleOf(target: ReferenceTarget, live = false): string | undefined {
|
|
502
|
+
const entry = this.#now().documents.get(target.document) ?? (live ? undefined : this.#trash.get(target.document))
|
|
503
|
+
if (!entry) return undefined
|
|
504
|
+
if (target.block !== undefined) return entry.blocks.get(target.block)
|
|
505
|
+
if (target.section !== undefined) return entry.pages.get(target.section)
|
|
506
|
+
return entry.title
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
links(id: DocumentId): DocumentLinks {
|
|
510
|
+
const { documents, incoming } = this.#now()
|
|
511
|
+
const own = documents.get(id) ?? this.#trash.get(id)
|
|
512
|
+
if (!own) return { document: id, incoming: [], outgoing: [] }
|
|
513
|
+
const outgoing: OutgoingLink[] = own.sites.map((site) => {
|
|
514
|
+
const title = this.titleOf(site.target)
|
|
515
|
+
const trashed = !documents.has(site.target.document) && this.#trash.has(site.target.document)
|
|
516
|
+
return { kind: site.kind, target: site.target, title: site.label ?? title ?? site.fallback ?? site.target.document, missing: title === undefined, ...trashed ? { trashed: true } : {} }
|
|
517
|
+
})
|
|
518
|
+
const cited: DocumentCitation[] = (incoming.get(id) ?? []).map(({ citing, site }) => ({
|
|
519
|
+
kind: site.kind, document: citing.id, title: citing.title, ...site.section !== undefined ? { section: site.section } : {}, block: site.block,
|
|
520
|
+
excerpt: site.kind === 'embed' ? (site.target.block !== undefined ? own.blocks.get(site.target.block) ?? '' : '') : site.excerpt,
|
|
521
|
+
}))
|
|
522
|
+
return { document: id, incoming: cited, outgoing }
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
/** Titles first (in tree order), then page titles and block text; the text was made lowercase when it was indexed. */
|
|
526
|
+
search(query: string, limit: number): DocumentSearchHit[] {
|
|
527
|
+
const q = query.trim().toLowerCase()
|
|
528
|
+
if (!q) return []
|
|
529
|
+
const { documents, order } = this.#now()
|
|
530
|
+
const hits: DocumentSearchHit[] = []
|
|
531
|
+
for (const id of order) {
|
|
532
|
+
if (hits.length >= limit) return hits
|
|
533
|
+
const entry = documents.get(id)
|
|
534
|
+
if (entry?.search.title.includes(q)) hits.push({ id, title: entry.title, ancestors: this.ancestors(id), match: 'title' })
|
|
535
|
+
}
|
|
536
|
+
const titled = new Set(hits.map(hit => hit.id))
|
|
537
|
+
for (const id of order) {
|
|
538
|
+
if (hits.length >= limit) break
|
|
539
|
+
const entry = documents.get(id)
|
|
540
|
+
if (!entry || titled.has(id) || !entry.search.all.includes(q)) continue
|
|
541
|
+
const page = entry.search.pages.find(page => page.lower.includes(q))
|
|
542
|
+
const block = page ? undefined : entry.search.blocks.find(block => block.lower.includes(q))
|
|
543
|
+
if (!page && !block) continue
|
|
544
|
+
hits.push({ id, title: entry.title, ancestors: this.ancestors(id), match: 'content', excerpt: page ? page.title : sentenceOf(block!.text, block!.lower.indexOf(q)), ...page ? { section: page.id } : block!.section !== undefined ? { section: block!.section, block: block!.id } : { block: block!.id } })
|
|
545
|
+
}
|
|
546
|
+
return hits
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
preview(id: DocumentId, target: { section?: SectionId, block?: BlockId }): DocumentPreview {
|
|
550
|
+
const { documents, incoming } = this.#now()
|
|
551
|
+
const entry = documents.get(id) ?? this.#trash.get(id)
|
|
552
|
+
if (!entry) return { id, title: '', ancestors: [], excerpt: '', pages: 0, steps: 0, citedBy: 0, missing: true }
|
|
553
|
+
const trashed = !documents.has(id)
|
|
554
|
+
const missing = (target.block !== undefined && !entry.blocks.has(target.block)) || (target.section !== undefined && !entry.pages.has(target.section))
|
|
555
|
+
const excerpt = missing ? '' : target.block !== undefined ? entry.blocks.get(target.block)! : target.section !== undefined ? entry.pageExcerpts.get(target.section) ?? '' : entry.excerpt
|
|
556
|
+
return {
|
|
557
|
+
id,
|
|
558
|
+
title: (target.block !== undefined ? entry.blocks.get(target.block) : target.section !== undefined ? entry.pages.get(target.section) : undefined) ?? entry.title,
|
|
559
|
+
ancestors: trashed ? [] : this.ancestors(id),
|
|
560
|
+
excerpt,
|
|
561
|
+
pages: entry.pages.size,
|
|
562
|
+
steps: entry.steps,
|
|
563
|
+
citedBy: new Set((incoming.get(id) ?? []).map(item => item.citing.id)).size,
|
|
564
|
+
...trashed ? { trashed: true } : {},
|
|
565
|
+
...missing ? { missing: true } : {},
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
async embedSource(id: DocumentId, block: BlockId): Promise<EmbedSource> {
|
|
570
|
+
return this.#embedSource(id, block, await this.read(id))
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/** One current file snapshot for this batch only; later requests read the source again. */
|
|
574
|
+
async embedSources(id: DocumentId, blocks: readonly BlockId[]): Promise<EmbedSource[]> {
|
|
575
|
+
const located = await this.read(id)
|
|
576
|
+
return blocks.map(block => this.#embedSource(id, block, located))
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
#embedSource(id: DocumentId, block: BlockId, located: LocatedDocument | undefined): EmbedSource {
|
|
580
|
+
const blocks = located && blockSubtree(located.document, block)
|
|
581
|
+
if (!located || !blocks) return { document: id, title: located?.document.metadata.title ?? '', block, missing: true, ...located?.trashed ? { trashed: true } : {} }
|
|
582
|
+
const { document } = located
|
|
583
|
+
const root = blocks[block]!
|
|
584
|
+
const used = Object.values(blocks).flatMap(item => item.type === 'image' && item.assetId && Object.hasOwn(document.assets, item.assetId) ? [item.assetId] : [])
|
|
585
|
+
// Relative to the workspace routes, as the client reaches the document's own assets.
|
|
586
|
+
const assets = located.trashed ? {} : Object.fromEntries(used.map(asset => [asset, `document/asset?${new URLSearchParams({ document: located.dir, asset })}`]))
|
|
587
|
+
const states = root.type === 'component' ? document.definitions[root.definitionId]?.states.map(state => state.id) : undefined
|
|
588
|
+
return { document: id, title: document.metadata.title, block, blocks, ...Object.keys(assets).length ? { assets } : {}, ...states ? { states } : {}, ...located.trashed ? { trashed: true } : {} }
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/**
|
|
592
|
+
* References and synced blocks whose target is gone or in the trash, counted across the workspace. One pass over the
|
|
593
|
+
* references the index keeps, at most once per change of the index.
|
|
594
|
+
*/
|
|
595
|
+
attention(): WorkspaceAttention {
|
|
596
|
+
const { documents, order } = this.#now()
|
|
597
|
+
if (this.#attention?.generation === this.#generation) return this.#attention.value
|
|
598
|
+
const counts = { reference: undefined as AttentionCount | undefined, embed: undefined as AttentionCount | undefined }
|
|
599
|
+
for (const id of order) {
|
|
600
|
+
const entry = documents.get(id)
|
|
601
|
+
if (!entry) continue
|
|
602
|
+
const counted = new Set<'reference' | 'embed'>()
|
|
603
|
+
for (const site of entry.sites) {
|
|
604
|
+
if (this.titleOf(site.target, true) !== undefined) continue
|
|
605
|
+
const count = counts[site.kind] ??= { places: 0, documents: 0, first: { document: id, ...site.section !== undefined ? { section: site.section } : {}, block: site.block } }
|
|
606
|
+
count.places++
|
|
607
|
+
if (!counted.has(site.kind)) { counted.add(site.kind); count.documents++ }
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const value: WorkspaceAttention = { ...counts.reference ? { references: counts.reference } : {}, ...counts.embed ? { embeds: counts.embed } : {} }
|
|
611
|
+
this.#attention = { generation: this.#generation, value, text: JSON.stringify(value) }
|
|
612
|
+
return value
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/** Called whenever what `attention` answers has changed. */
|
|
616
|
+
onAttention(listener: () => void): () => void {
|
|
617
|
+
this.#attentionListeners.add(listener)
|
|
618
|
+
return () => { this.#attentionListeners.delete(listener) }
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
/** The documents whose references may show an outdated fallback after the titles of `changed` changed: those citing them, and themselves. */
|
|
622
|
+
citing(changed: DocumentId[]): IndexEntry[] {
|
|
623
|
+
const { documents, incoming } = this.#now()
|
|
624
|
+
const out = new Map<DocumentId, IndexEntry>()
|
|
625
|
+
for (const id of changed) {
|
|
626
|
+
const own = documents.get(id)
|
|
627
|
+
if (own?.sites.some(site => site.kind === 'reference')) out.set(id, own)
|
|
628
|
+
for (const { citing, site } of incoming.get(id) ?? []) if (site.kind === 'reference') out.set(citing.id, citing)
|
|
629
|
+
}
|
|
630
|
+
return [...out.values()]
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** Called with no argument whenever the tree or the trash has changed. */
|
|
634
|
+
subscribe(listener: () => void): () => void {
|
|
635
|
+
this.#listeners.add(listener)
|
|
636
|
+
return () => { this.#listeners.delete(listener) }
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/** Called with the documents whose titles (document, pages or blocks) changed. */
|
|
640
|
+
onTitles(listener: (changed: DocumentId[]) => void): () => void {
|
|
641
|
+
this.#titleListeners.add(listener)
|
|
642
|
+
return () => { this.#titleListeners.delete(listener) }
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/** The sentence of `text` around `at`, at most about 120 characters. */
|
|
647
|
+
function sentenceOf(text: string, at: number): string {
|
|
648
|
+
const ends = /[.!?。!?;;\n]/
|
|
649
|
+
let start = at, end = at
|
|
650
|
+
while (start > 0 && !ends.test(text[start - 1]!)) start--
|
|
651
|
+
while (end < text.length && !ends.test(text[end]!)) end++
|
|
652
|
+
const sentence = text.slice(start, Math.min(text.length, end + 1)).trim()
|
|
653
|
+
return [...sentence].length <= 120 ? sentence : `${[...sentence].slice(0, 119).join('')}…`
|
|
654
|
+
}
|