dsh-tiddlywiki 0.27.2 → 0.28.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 +21 -21
- package/README.md +3 -0
- package/cordis.patch.yml +13 -13
- package/docs/CHANGELOG.md +2 -1
- package/docs/code-review-2026-09-17.md +151 -0
- package/docs/features.md +5 -2
- package/docs/usage.md +34 -3
- package/docs/wiki-split.md +97 -0
- package/lib/client.js +54 -27
- package/lib/index.js +2803 -517
- package/lib/index.js.map +1 -1
- package/package.json +5 -4
- package/skills/wiki-split/SKILL.md +106 -0
- package/src/client/endpoints.ts +37 -0
- package/src/client/index.ts +14 -0
- package/src/client/knowledge-fab.ts +62 -3
- package/src/client/markdown-editor.ts +128 -128
- package/src/client/panel.ts +2 -1
- package/src/client/settings-page.ts +217 -3
- package/src/client/state.ts +39 -39
- package/src/client/status-cache.ts +17 -0
- package/src/client/styles.ts +27 -0
- package/src/client/toast.ts +22 -22
- package/src/client/tw-frame.ts +28 -4
- package/src/client/wiki-focus.ts +70 -0
- package/src/client/wiki-scope-dock.ts +116 -0
- package/src/host/admin.ts +175 -35
- package/src/host/git.ts +50 -5
- package/src/host/path-key.ts +35 -0
- package/src/host/prompt.ts +24 -0
- package/src/host/repo-committers.ts +149 -0
- package/src/host/routes.ts +254 -81
- package/src/host/seeds.ts +51 -10
- package/src/host/session-scope.ts +154 -0
- package/src/host/skill-install.ts +121 -0
- package/src/host/tools.ts +141 -49
- package/src/host/wiki-farm.ts +417 -0
- package/src/host/wiki-instance.ts +596 -0
- package/src/host/wiki-registry.ts +601 -0
- package/src/host/wiki.ts +19 -0
- package/src/index.ts +686 -459
|
@@ -0,0 +1,596 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One knowledge base's runtime (v0.28.0) — the "wiki farm" replaces the single
|
|
3
|
+
* `WikiServer` + client + config + committer quartet that used to live as loose
|
|
4
|
+
* closure variables inside `apply()`.
|
|
5
|
+
*
|
|
6
|
+
* WHAT IS PER-WIKI, AND WHAT IS NOT
|
|
7
|
+
* ---------------------------------
|
|
8
|
+
* Per instance (everything that holds a folder or a port):
|
|
9
|
+
*
|
|
10
|
+
* - `WikiServer` one TW child process, one loopback port;
|
|
11
|
+
* - `TiddlyWebClient` the REST client for THAT port;
|
|
12
|
+
* - `ConfigStore` the wiki's own `$:/plugins/dsh-tiddlywiki/config`
|
|
13
|
+
* overlay (which is why per-wiki config already worked
|
|
14
|
+
* before this refactor — it just was not addressable);
|
|
15
|
+
* - fs watcher for its own folder (the AUTO-COMMITTER is per REPOSITORY — see
|
|
16
|
+
* host/repo-committers.ts — because several wikis may share one repository
|
|
17
|
+
* and only one `git add -A` per repository may run);
|
|
18
|
+
*
|
|
19
|
+
* Shared by the whole plugin, therefore NOT here:
|
|
20
|
+
*
|
|
21
|
+
* - `GitFace` — every method takes the directory as an argument, so it is
|
|
22
|
+
* stateless; M2 keys the COMMITTER by repository, not by wiki;
|
|
23
|
+
* - the clip bridge (one listener on one port) and the WeChat runner;
|
|
24
|
+
* - the registered agent tools, routes and the prompt section (singletons by
|
|
25
|
+
* construction: the host rejects a duplicate tool/route/section name).
|
|
26
|
+
*
|
|
27
|
+
* LIFECYCLE CONTRACT
|
|
28
|
+
* ------------------
|
|
29
|
+
* start() server.start → load config tiddler → bootstrap seeds → git → arm extras
|
|
30
|
+
* restart() drain the syncer queue, THEN restart (ironclad rule #1)
|
|
31
|
+
* stop() drain, then stop, then release the extras
|
|
32
|
+
* dispose() flush a pending commit, release extras, stop the child
|
|
33
|
+
*
|
|
34
|
+
* A failed `start()` must not leave a half-wired instance behind: the caller
|
|
35
|
+
* decides whether to roll back, and `dispose()` is idempotent.
|
|
36
|
+
*
|
|
37
|
+
* @module dsh-tiddlywiki/host/wiki-instance
|
|
38
|
+
*/
|
|
39
|
+
import { watch, type FSWatcher } from 'node:fs'
|
|
40
|
+
import { readFile, writeFile } from 'node:fs/promises'
|
|
41
|
+
import { join } from 'node:path'
|
|
42
|
+
import { type GitFace } from './git.ts'
|
|
43
|
+
import { ConfigStore, DARK_PALETTE_DEFAULT, type PluginConfigShape } from './config.ts'
|
|
44
|
+
import { TiddlyWebClient } from './tw-api.ts'
|
|
45
|
+
import { ensureLanguage, ensurePlugin, pinLanguageTiddler } from './admin.ts'
|
|
46
|
+
import { drainThenStop, flushPendingWrites, needsRestartAfterSeeds, runAllSeeds, waitForFileWrite } from './seeds.ts'
|
|
47
|
+
import { RENDER_PLUGIN_FILE } from './seed-render.ts'
|
|
48
|
+
import { WikiServer, TW_PROXY_PATH } from './wiki.ts'
|
|
49
|
+
import { entryPath, type WikiEntry } from './wiki-registry.ts'
|
|
50
|
+
import { tiddlywikiToolSummary } from './tools.ts'
|
|
51
|
+
import { normalizeWechatConfig } from './wechat-publish.ts'
|
|
52
|
+
import type { UiDefaultsPublic } from './routes.ts'
|
|
53
|
+
import type { BridgeConfig } from './clip-bridge.ts'
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Official plugin whose parser every note this plugin writes depends on
|
|
57
|
+
* (`text/markdown`). `--init server` does NOT include it — see ensurePlugin().
|
|
58
|
+
*/
|
|
59
|
+
export const MARKDOWN_PLUGIN = 'tiddlywiki/markdown'
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The cordis `config:` block values one instance needs as its BASE layer (the
|
|
63
|
+
* wiki's own config tiddler overlays them). Mirrors `ResolvedConfig` in
|
|
64
|
+
* src/index.ts minus the per-instance location fields.
|
|
65
|
+
*/
|
|
66
|
+
export interface WikiInstanceBase {
|
|
67
|
+
git: { autoCommit: boolean; debounceMs: number; remote: string; branch: string }
|
|
68
|
+
note: { tag: string; workspaceMark: boolean }
|
|
69
|
+
bridge: { enabled: boolean; port: number; token: string; tag: string }
|
|
70
|
+
startup: { readyTimeoutMs: number }
|
|
71
|
+
wechat: { enabled: boolean; command: string; token: string; adapter: 'publish-note' | 'publish-note-imgs'; dsn: string }
|
|
72
|
+
ui: {
|
|
73
|
+
showQuickNote: boolean
|
|
74
|
+
showQuickNoteDock: boolean
|
|
75
|
+
quickNoteMode: 'native' | 'card'
|
|
76
|
+
sidebarLabel: string
|
|
77
|
+
showPanelStatus: boolean
|
|
78
|
+
showSyncButton: boolean
|
|
79
|
+
followDshTheme: boolean
|
|
80
|
+
darkPalette: string
|
|
81
|
+
tabLabel: string
|
|
82
|
+
showSessionTab: boolean
|
|
83
|
+
showRightbarTab: boolean
|
|
84
|
+
sendToAgent: { enabled: boolean; endpoint?: string; token?: string }
|
|
85
|
+
allArticles: { pageSize: number }
|
|
86
|
+
}
|
|
87
|
+
uiLanguage: string
|
|
88
|
+
auth: { username?: string; password?: string }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface WikiInstanceOptions {
|
|
92
|
+
/** The registry entry this instance serves (kept in sync via {@link updateEntry}). */
|
|
93
|
+
entry: WikiEntry
|
|
94
|
+
/** cordis config block = the base layer for this wiki's effective config. */
|
|
95
|
+
base: WikiInstanceBase
|
|
96
|
+
/** Shared, stateless git face. */
|
|
97
|
+
git: GitFace
|
|
98
|
+
/** Resolve the installed tiddlywiki package root (plugin / language management). */
|
|
99
|
+
twRoot: () => string
|
|
100
|
+
/**
|
|
101
|
+
* Debounced auto-commit for the folder this wiki lives in (v0.28.0).
|
|
102
|
+
*
|
|
103
|
+
* It goes through host/repo-committers.ts, NOT through a committer owned here:
|
|
104
|
+
* several wikis may share one repository, and only ONE `git add -A` per
|
|
105
|
+
* repository may run. Fire-and-forget by design (the fs watcher calls it).
|
|
106
|
+
*/
|
|
107
|
+
touchCommit?: (dir: string) => void
|
|
108
|
+
/** Flush that repository's pending commit (teardown / explicit sync). */
|
|
109
|
+
flushCommits?: (dir: string) => Promise<void> | void
|
|
110
|
+
/**
|
|
111
|
+
* The same-origin proxy base this wiki's TW frontend must use (v0.28.0).
|
|
112
|
+
*
|
|
113
|
+
* The host wires it from the current mode: single mode keeps the legacy bare
|
|
114
|
+
* path (so every existing install sees no diff), multi mode gives each wiki
|
|
115
|
+
* `/dsh-tiddlywiki/tw/<id>/`. Without it, a wiki's embedded editor would build
|
|
116
|
+
* its API URLs for the LEGACY path and be proxied to whichever wiki is default
|
|
117
|
+
* — one wiki's UI over another wiki's data.
|
|
118
|
+
*
|
|
119
|
+
* Both forms route to the same child, so a stale value left over from a mode
|
|
120
|
+
* flip is harmless.
|
|
121
|
+
*/
|
|
122
|
+
proxyBase?: () => string
|
|
123
|
+
/** Log sink (defaults to console.warn with the plugin prefix). */
|
|
124
|
+
log?: (message: string) => void
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Where a restart/stop is allowed to come from (kept for diagnostics). */
|
|
128
|
+
export type WikiInstanceState = 'stopped' | 'starting' | 'running' | 'failed'
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Ensure the wiki's `.gitignore` covers TW's transient artifacts, WITHOUT
|
|
132
|
+
* clobbering rules the user added. Only touched when one of the managed lines
|
|
133
|
+
* is missing; the user's own content is preserved verbatim.
|
|
134
|
+
*/
|
|
135
|
+
const MANAGED_GITIGNORE_LINES = [
|
|
136
|
+
'tiddlers/$__temp_*',
|
|
137
|
+
'tiddlers/$__StoryList*',
|
|
138
|
+
'tiddlers/$__HistoryList*',
|
|
139
|
+
'*.meta.tmp',
|
|
140
|
+
// flush 哨兵(每次「重启前排干 syncer」都会重写,内容是时间戳):不进 git,
|
|
141
|
+
// 否则每次同步/播种都会给用户仓库塞一个无意义的 diff(v0.19.1)。
|
|
142
|
+
'tiddlers/$__plugins_dsh-tiddlywiki_flush-probe.tid',
|
|
143
|
+
'tiddlers/$__plugins_dsh-tiddlywiki_flush-probe.txt',
|
|
144
|
+
'tiddlers/$__plugins_dsh-tiddlywiki_flush-probe.txt.meta',
|
|
145
|
+
]
|
|
146
|
+
|
|
147
|
+
async function writeGitignore(wikiPath: string): Promise<void> {
|
|
148
|
+
const file = join(wikiPath, '.gitignore')
|
|
149
|
+
let current = ''
|
|
150
|
+
try {
|
|
151
|
+
current = await readFile(file, 'utf8')
|
|
152
|
+
} catch {
|
|
153
|
+
/* absent → first run, write the default block */
|
|
154
|
+
}
|
|
155
|
+
const existing = current.split(/\r?\n/).map((line) => line.trim())
|
|
156
|
+
const missing = MANAGED_GITIGNORE_LINES.filter((line) => !existing.includes(line))
|
|
157
|
+
if (missing.length === 0) return
|
|
158
|
+
const block = [
|
|
159
|
+
'# TiddlyWiki transient artifacts (auto-managed by dsh-tiddlywiki)',
|
|
160
|
+
...missing,
|
|
161
|
+
'',
|
|
162
|
+
].join('\n')
|
|
163
|
+
const prefix = current.length === 0 ? '' : current.endsWith('\n') ? `${current}\n` : `${current}\n\n`
|
|
164
|
+
await writeFile(file, `${prefix}${block}`, 'utf8')
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Watch one wiki's folders and touch the auto-committer on changes.
|
|
169
|
+
*
|
|
170
|
+
* ALWAYS attach an 'error' listener: `fs.watch` reports failures (Windows EPERM,
|
|
171
|
+
* Linux ENOSPC when the inotify watch limit is exhausted) as an ASYNC 'error'
|
|
172
|
+
* event, which a surrounding try/catch cannot catch. Node rethrows an unhandled
|
|
173
|
+
* 'error' as an uncaught exception, and the host installs no handler → the whole
|
|
174
|
+
* `dsh web` process dies. Degrading to "no watcher" is safe: our own writes still
|
|
175
|
+
* call `touch()`.
|
|
176
|
+
*
|
|
177
|
+
* ⚠️ With N wikis there are N watchers. On Linux the inotify watch limit is a
|
|
178
|
+
* real ceiling; the degradation above is what keeps that survivable.
|
|
179
|
+
*/
|
|
180
|
+
function watchWiki(wikiPath: string, onChange: () => void): () => void {
|
|
181
|
+
const watchers: FSWatcher[] = []
|
|
182
|
+
for (const dir of [join(wikiPath, 'tiddlers'), wikiPath]) {
|
|
183
|
+
try {
|
|
184
|
+
const watcher = watch(dir, { persistent: false }, () => onChange())
|
|
185
|
+
watcher.on('error', (err) => {
|
|
186
|
+
console.warn('[dsh-tiddlywiki] wiki watcher error (auto-commit still runs on our own writes):', err.message)
|
|
187
|
+
})
|
|
188
|
+
watchers.push(watcher)
|
|
189
|
+
} catch {
|
|
190
|
+
/* directory may not exist yet; the committer also fires on our own writes */
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return () => {
|
|
194
|
+
for (const watcher of watchers) {
|
|
195
|
+
try { watcher.close() } catch { /* already closed */ }
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** One knowledge base: its child process, client, config overlay and committer. */
|
|
201
|
+
export class WikiInstance {
|
|
202
|
+
/** The TW child process this knowledge base runs on its own loopback port. */
|
|
203
|
+
readonly server: WikiServer
|
|
204
|
+
/** This wiki's own `$:/plugins/dsh-tiddlywiki/config` overlay. */
|
|
205
|
+
readonly config: ConfigStore
|
|
206
|
+
|
|
207
|
+
private entryValue: WikiEntry
|
|
208
|
+
private wikiPath: string
|
|
209
|
+
private clientCache: TiddlyWebClient | undefined
|
|
210
|
+
private clientPort: number | undefined
|
|
211
|
+
private unwatch: (() => void) | undefined
|
|
212
|
+
private disposed = false
|
|
213
|
+
private readonly log: (message: string) => void
|
|
214
|
+
|
|
215
|
+
constructor(private readonly options: WikiInstanceOptions) {
|
|
216
|
+
this.entryValue = options.entry
|
|
217
|
+
this.wikiPath = entryPath(options.entry)
|
|
218
|
+
this.log = options.log ?? ((message) => { console.warn('[dsh-tiddlywiki]', message) })
|
|
219
|
+
this.server = new WikiServer({
|
|
220
|
+
wikiRoot: options.entry.root,
|
|
221
|
+
wiki: options.entry.name,
|
|
222
|
+
port: 0,
|
|
223
|
+
username: options.base.auth.username,
|
|
224
|
+
password: options.base.auth.password,
|
|
225
|
+
readyTimeoutMs: options.base.startup.readyTimeoutMs,
|
|
226
|
+
})
|
|
227
|
+
this.config = new ConfigStore({
|
|
228
|
+
note: options.base.note,
|
|
229
|
+
git: options.base.git,
|
|
230
|
+
ui: options.base.ui,
|
|
231
|
+
uiLanguage: options.base.uiLanguage,
|
|
232
|
+
bridge: options.base.bridge,
|
|
233
|
+
startup: options.base.startup,
|
|
234
|
+
wechat: options.base.wechat,
|
|
235
|
+
} satisfies PluginConfigShape)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Registry entry currently served (id/label/flags live here). */
|
|
239
|
+
get entry(): WikiEntry {
|
|
240
|
+
return this.entryValue
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Absolute folder of this wiki. */
|
|
244
|
+
get path(): string {
|
|
245
|
+
return this.wikiPath
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** True once {@link dispose} ran: no path may spawn or start anything after it. */
|
|
249
|
+
get isDisposed(): boolean {
|
|
250
|
+
return this.disposed
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Folder key used by the repo-keyed git model (M2). */
|
|
254
|
+
get tiddlersDir(): string {
|
|
255
|
+
return join(this.wikiPath, 'tiddlers')
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Effective config = cordis base overlaid with THIS wiki's config tiddler. */
|
|
259
|
+
eff(): PluginConfigShape {
|
|
260
|
+
return this.config.get()
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** The note tag new notes get here (config tiddler overrides the base). */
|
|
264
|
+
noteTag(): string {
|
|
265
|
+
const tag = this.eff().note?.tag
|
|
266
|
+
return typeof tag === 'string' && tag.trim().length > 0 ? tag : this.options.base.note.tag
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Whether agent-created notes get the automatic workspace marker (v0.24.0):
|
|
271
|
+
* tag `ws/<project>` + field `workspace`. Default ON; an explicit `false` in
|
|
272
|
+
* this wiki's config tiddler wins.
|
|
273
|
+
*/
|
|
274
|
+
workspaceMark(): boolean {
|
|
275
|
+
const value = this.eff().note?.workspaceMark
|
|
276
|
+
return typeof value === 'boolean' ? value : this.options.base.note.workspaceMark
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Effective clip-bridge config for THIS wiki. Used per request by the shared
|
|
281
|
+
* bridge: enabled/token/tag apply immediately; only the port is fixed at
|
|
282
|
+
* startup (the listener binds once, plugin-wide).
|
|
283
|
+
*/
|
|
284
|
+
bridgeConfig(): BridgeConfig {
|
|
285
|
+
const b = this.eff().bridge ?? {}
|
|
286
|
+
const port = typeof b.port === 'number' && Number.isInteger(b.port) && b.port > 0 && b.port < 65536 ? b.port : this.options.base.bridge.port
|
|
287
|
+
const token = typeof b.token === 'string' ? b.token : ''
|
|
288
|
+
const tag = typeof b.tag === 'string' && b.tag.trim().length > 0 ? b.tag.trim() : this.options.base.bridge.tag
|
|
289
|
+
return { enabled: b.enabled === true, port, token, tag }
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* Effective UI flags from a config overlay.
|
|
294
|
+
*
|
|
295
|
+
* STATIC on purpose (v0.28.0): the plugin also needs them when NO wiki is
|
|
296
|
+
* running — a stopped farm must answer the settings page with the cordis base
|
|
297
|
+
* values instead of inventing them, and duplicating this mapping in index.ts
|
|
298
|
+
* is exactly the kind of drift this repo keeps paying for.
|
|
299
|
+
*/
|
|
300
|
+
static uiDefaultsFrom(base: WikiInstanceBase, ui: PluginConfigShape['ui'] = {}): UiDefaultsPublic {
|
|
301
|
+
const palette = typeof ui.darkPalette === 'string' && ui.darkPalette.trim().length > 0 ? ui.darkPalette.trim() : DARK_PALETTE_DEFAULT
|
|
302
|
+
const label = typeof ui.sidebarLabel === 'string' && ui.sidebarLabel.trim().length > 0 ? ui.sidebarLabel.trim() : base.ui.sidebarLabel
|
|
303
|
+
const tabLabel = typeof ui.tabLabel === 'string' && ui.tabLabel.trim().length > 0 ? ui.tabLabel.trim() : base.ui.tabLabel
|
|
304
|
+
const quickNoteMode: 'native' | 'card' = ui.quickNoteMode === 'card' ? 'card' : 'native'
|
|
305
|
+
return {
|
|
306
|
+
showQuickNote: ui.showQuickNote !== false,
|
|
307
|
+
showQuickNoteDock: ui.showQuickNoteDock !== false,
|
|
308
|
+
quickNoteMode,
|
|
309
|
+
sidebarLabel: label,
|
|
310
|
+
showPanelStatus: ui.showPanelStatus !== false,
|
|
311
|
+
showSyncButton: ui.showSyncButton !== false,
|
|
312
|
+
followDshTheme: ui.followDshTheme !== false,
|
|
313
|
+
darkPalette: palette,
|
|
314
|
+
tabLabel,
|
|
315
|
+
showSessionTab: ui.showSessionTab !== false,
|
|
316
|
+
showRightbarTab: ui.showRightbarTab !== false,
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Effective UI flags for THIS wiki. */
|
|
321
|
+
uiDefaults(): UiDefaultsPublic {
|
|
322
|
+
return WikiInstance.uiDefaultsFrom(this.options.base, this.eff().ui)
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Effective 公众号发布 config for THIS wiki (read per request). */
|
|
326
|
+
wechatConfig(): ReturnType<typeof normalizeWechatConfig> {
|
|
327
|
+
return normalizeWechatConfig(this.eff().wechat)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** This wiki's send-to-agent switch / shared token. */
|
|
331
|
+
sendToAgent(): { enabled: boolean; token: string } {
|
|
332
|
+
const s2a = this.eff().ui?.sendToAgent ?? {}
|
|
333
|
+
return {
|
|
334
|
+
enabled: s2a.enabled !== false,
|
|
335
|
+
token: typeof s2a.token === 'string' ? s2a.token : '',
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/** Whether the wechat feature is on for this wiki (gates seeds + prompt line). */
|
|
340
|
+
wechatEnabled(): boolean {
|
|
341
|
+
return (this.eff().wechat ?? {}).enabled === true
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Lazy TW client. Rebuilt whenever the bound PORT changes (a crash before
|
|
346
|
+
* readiness makes the child re-probe a free port, so a cached client must not
|
|
347
|
+
* stay pinned to a dead one). Credentials are attached preemptively: with
|
|
348
|
+
* `auth.username` configured the child runs behind `readers`/`writers`, so
|
|
349
|
+
* EVERY request needs Basic auth.
|
|
350
|
+
*/
|
|
351
|
+
client(): TiddlyWebClient | undefined {
|
|
352
|
+
const port = this.server.currentPort
|
|
353
|
+
if (port === undefined) return undefined
|
|
354
|
+
if (this.clientCache === undefined || this.clientPort !== port) {
|
|
355
|
+
this.clientCache = new TiddlyWebClient(`http://127.0.0.1:${port}`, {
|
|
356
|
+
username: this.options.base.auth.username,
|
|
357
|
+
password: this.options.base.auth.password,
|
|
358
|
+
})
|
|
359
|
+
this.clientPort = port
|
|
360
|
+
}
|
|
361
|
+
return this.clientCache
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Drop the cached client (its cached listing belongs to the old folder). */
|
|
365
|
+
private resetClient(): void {
|
|
366
|
+
this.clientCache = undefined
|
|
367
|
+
this.clientPort = undefined
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Point this instance at another folder. THROWS while the child runs — the
|
|
372
|
+
* switch orchestrator stops it first (see host/wiki-switch.ts).
|
|
373
|
+
*/
|
|
374
|
+
updateEntry(entry: WikiEntry): void {
|
|
375
|
+
const nextPath = entryPath(entry)
|
|
376
|
+
if (nextPath !== this.wikiPath) {
|
|
377
|
+
this.server.setLocation({ root: entry.root, name: entry.name })
|
|
378
|
+
this.wikiPath = nextPath
|
|
379
|
+
this.resetClient()
|
|
380
|
+
}
|
|
381
|
+
this.entryValue = entry
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Re-apply the effective readiness window (next start/restart). */
|
|
385
|
+
applyServerTuning(): void {
|
|
386
|
+
this.server.setReadyTimeout(this.eff().startup?.readyTimeoutMs)
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Debounced auto-commit touch for this wiki's folder. Routed to the
|
|
391
|
+
* REPOSITORY's committer (several wikis may share one repository).
|
|
392
|
+
*/
|
|
393
|
+
touchAutoCommit(): void {
|
|
394
|
+
this.options.touchCommit?.(this.wikiPath)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** Flush this wiki's repository commit now (teardown / explicit sync). */
|
|
398
|
+
async flushCommitter(): Promise<void> {
|
|
399
|
+
try { await this.options.flushCommits?.(this.wikiPath) } catch { /* best-effort */ }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Arm the fs watcher for the CURRENT folder.
|
|
404
|
+
*
|
|
405
|
+
* The committer is NOT here any more (v0.28.0): it is per repository, in
|
|
406
|
+
* host/repo-committers.ts, and this watcher only reports "something changed in
|
|
407
|
+
* this wiki's folder" to it.
|
|
408
|
+
*/
|
|
409
|
+
setupExtras(): void {
|
|
410
|
+
this.unwatch = watchWiki(this.wikiPath, () => this.touchAutoCommit())
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** Release the fs watcher (the repository's committer outlives it). */
|
|
414
|
+
async teardownExtras(): Promise<void> {
|
|
415
|
+
try { this.unwatch?.() } catch { /* already closed */ }
|
|
416
|
+
this.unwatch = undefined
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Git bootstrap: repo init + initial commit + .gitignore (+ remote/first push).
|
|
421
|
+
* Kept per-wiki in M1; M2 makes it repo-keyed (two wikis may share one repo).
|
|
422
|
+
*/
|
|
423
|
+
async bootstrapGit(): Promise<void> {
|
|
424
|
+
const g = this.eff().git ?? {}
|
|
425
|
+
const branch = g.branch ?? this.options.base.git.branch
|
|
426
|
+
const remote = g.remote ?? this.options.base.git.remote
|
|
427
|
+
const isRepo = await this.options.git.isRepo(this.wikiPath)
|
|
428
|
+
if (!isRepo) {
|
|
429
|
+
await this.options.git.init(this.wikiPath, branch)
|
|
430
|
+
await writeGitignore(this.wikiPath)
|
|
431
|
+
await this.options.git.initialCommit(this.wikiPath)
|
|
432
|
+
} else {
|
|
433
|
+
await writeGitignore(this.wikiPath)
|
|
434
|
+
}
|
|
435
|
+
if (remote.trim().length > 0) {
|
|
436
|
+
const ensured = await this.options.git.ensureRemote(this.wikiPath, remote.trim())
|
|
437
|
+
if (ensured.ok) {
|
|
438
|
+
const first = await this.options.git.firstPush(this.wikiPath)
|
|
439
|
+
if (!first.ok) this.log(`first push failed (retry with tiddlywiki_git_sync): ${first.message}`)
|
|
440
|
+
} else {
|
|
441
|
+
this.log(`git remote setup: ${ensured.message}`)
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Core-bootstrap this wiki: markdown parser plugin, the core + starter seeds,
|
|
448
|
+
* and the configured UI language.
|
|
449
|
+
*
|
|
450
|
+
* Only `render-route` needs a TW restart (it carries a SERVER route loaded at
|
|
451
|
+
* boot); plain-content seeds must NOT restart, or the syncer's unflushed REST
|
|
452
|
+
* writes would be lost.
|
|
453
|
+
*/
|
|
454
|
+
async bootstrapWiki(): Promise<void> {
|
|
455
|
+
const seedClient = this.client()
|
|
456
|
+
if (seedClient === undefined) return
|
|
457
|
+
let pluginAdded = false
|
|
458
|
+
try {
|
|
459
|
+
pluginAdded = await ensurePlugin(this.wikiPath, this.options.twRoot(), MARKDOWN_PLUGIN)
|
|
460
|
+
if (pluginAdded) this.log(`enabled ${MARKDOWN_PLUGIN} for this wiki`)
|
|
461
|
+
} catch (err) {
|
|
462
|
+
this.log(`enabling ${MARKDOWN_PLUGIN}: ${err instanceof Error ? err.message : String(err)}`)
|
|
463
|
+
}
|
|
464
|
+
const seedStartedAt = Date.now()
|
|
465
|
+
const results = await runAllSeeds({
|
|
466
|
+
client: seedClient,
|
|
467
|
+
tools: tiddlywikiToolSummary(),
|
|
468
|
+
// Opt-in feature gate (v0.23.0): the「发布元数据规范」seed is skipped unless
|
|
469
|
+
// THIS wiki turned 微信发布 on (its own config tiddler wins over the base).
|
|
470
|
+
wechat: this.wechatEnabled(),
|
|
471
|
+
// Per-wiki same-origin base: `/tw/<id>/` in multi mode (see the option).
|
|
472
|
+
proxyBase: this.options.proxyBase?.() ?? TW_PROXY_PATH,
|
|
473
|
+
})
|
|
474
|
+
for (const r of results) {
|
|
475
|
+
if (!r.ok) this.log(`seed ${r.id} failed: ${r.error ?? r.detail}`)
|
|
476
|
+
}
|
|
477
|
+
if (needsRestartAfterSeeds(results)) {
|
|
478
|
+
const renderFile = join(this.wikiPath, 'tiddlers', RENDER_PLUGIN_FILE)
|
|
479
|
+
const flushed = await waitForFileWrite(renderFile, 8_000, 150, seedStartedAt)
|
|
480
|
+
if (!flushed) this.log('seeded render plugin file not seen on disk before restart')
|
|
481
|
+
// Drain the rest of the syncer queue as well: a restart that boots from a
|
|
482
|
+
// stale snapshot loses every write still queued (v0.19.0).
|
|
483
|
+
const drained = await flushPendingWrites(seedClient, this.tiddlersDir)
|
|
484
|
+
if (!drained) this.log('seed writes may not have been flushed before restart')
|
|
485
|
+
if (!this.disposed) await this.server.restart()
|
|
486
|
+
} else if (pluginAdded) {
|
|
487
|
+
// tiddlywiki.info is written directly by us (no TW flush to wait for),
|
|
488
|
+
// but TW only loads the plugin at boot.
|
|
489
|
+
if (!this.disposed) await this.server.restart()
|
|
490
|
+
}
|
|
491
|
+
// Apply the configured UI language (e.g. "zh-Hans"): enable the bundled
|
|
492
|
+
// language plugin in tiddlywiki.info.languages + restart once so TW loads
|
|
493
|
+
// it at boot (fully offline — official language packs ship in the pkg).
|
|
494
|
+
const uiLang = this.eff().uiLanguage
|
|
495
|
+
if (typeof uiLang === 'string' && uiLang.trim().length > 0) {
|
|
496
|
+
try {
|
|
497
|
+
const code = uiLang.trim()
|
|
498
|
+
const changed = await ensureLanguage(this.wikiPath, this.options.twRoot(), code)
|
|
499
|
+
if (changed && !this.disposed) await this.server.restart()
|
|
500
|
+
// Pin the active language tiddler so TW's UI actually switches.
|
|
501
|
+
// v0.24.2: conditional — an identical body still rewrites
|
|
502
|
+
// `$__language.txt.meta`'s created/modified on EVERY startup, and two
|
|
503
|
+
// machines doing that conflict on every pull.
|
|
504
|
+
const langClient = this.client()
|
|
505
|
+
if (langClient !== undefined) {
|
|
506
|
+
await pinLanguageTiddler(langClient, `$:/languages/${code}`, (message, err) => {
|
|
507
|
+
if (err === undefined) this.log(message)
|
|
508
|
+
else this.log(`pinning $:/language failed: ${err}`)
|
|
509
|
+
}).catch(() => undefined)
|
|
510
|
+
}
|
|
511
|
+
} catch (err) {
|
|
512
|
+
this.log(`applying uiLanguage: ${err instanceof Error ? err.message : String(err)}`)
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
/**
|
|
518
|
+
* Bring this wiki up: spawn the child, load its config overlay, bootstrap it,
|
|
519
|
+
* then arm the committer + watcher.
|
|
520
|
+
*
|
|
521
|
+
* Disposal-aware: teardown may run while this is awaiting (hot reload / dsh web
|
|
522
|
+
* exit within the first seconds), so the child is stopped rather than orphaned.
|
|
523
|
+
*/
|
|
524
|
+
async start(): Promise<void> {
|
|
525
|
+
if (this.disposed) throw new Error(`知识库「${this.entryValue.id}」已卸载,无法启动`)
|
|
526
|
+
try {
|
|
527
|
+
await this.server.start()
|
|
528
|
+
if (this.disposed) {
|
|
529
|
+
await this.server.stop().catch(() => undefined)
|
|
530
|
+
return
|
|
531
|
+
}
|
|
532
|
+
await this.config.load(this.client())
|
|
533
|
+
this.applyServerTuning()
|
|
534
|
+
await this.bootstrapWiki()
|
|
535
|
+
} finally {
|
|
536
|
+
// Git bootstrap + the committer do NOT depend on the TW child: they must
|
|
537
|
+
// run even when the wiki FAILED to start, so every write is still versioned
|
|
538
|
+
// and a later retry finds a ready repository (pre-v0.28 behaviour, kept
|
|
539
|
+
// when the startup path moved in here).
|
|
540
|
+
if (!this.disposed) {
|
|
541
|
+
try {
|
|
542
|
+
await this.bootstrapGit()
|
|
543
|
+
if (!this.disposed) this.setupExtras()
|
|
544
|
+
} catch (err) {
|
|
545
|
+
this.log(`git bootstrap failed: ${err instanceof Error ? err.message : String(err)}`)
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
/**
|
|
552
|
+
* Drain the syncer queue, then restart the child (ironclad rule #1). Returns
|
|
553
|
+
* whether the store was provably quiescent, so callers can surface an
|
|
554
|
+
* incomplete drain instead of losing writes silently.
|
|
555
|
+
*/
|
|
556
|
+
async restart(): Promise<boolean> {
|
|
557
|
+
return drainThenStop({
|
|
558
|
+
client: this.client(),
|
|
559
|
+
tiddlersDir: this.tiddlersDir,
|
|
560
|
+
stop: () => this.server.restart(),
|
|
561
|
+
log: this.log,
|
|
562
|
+
})
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
/** Drain the syncer queue, then stop the child. */
|
|
566
|
+
async drainStop(): Promise<boolean> {
|
|
567
|
+
return drainThenStop({
|
|
568
|
+
client: this.client(),
|
|
569
|
+
tiddlersDir: this.tiddlersDir,
|
|
570
|
+
stop: () => this.server.stop(),
|
|
571
|
+
log: this.log,
|
|
572
|
+
})
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/** Drain + stop + release the extras. */
|
|
576
|
+
async stop(): Promise<void> {
|
|
577
|
+
await this.drainStop()
|
|
578
|
+
await this.teardownExtras()
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Deterministic teardown. Idempotent: the plugin disposer and a rollback path
|
|
583
|
+
* may both call it.
|
|
584
|
+
*
|
|
585
|
+
* NOTE: this intentionally does NOT drain the syncer queue (the pre-v0.28
|
|
586
|
+
* teardown did not either) — it flushes the git committer and stops the child.
|
|
587
|
+
* Shutdown has a 5s grace in DSH, and a drain has its own bounded waits.
|
|
588
|
+
*/
|
|
589
|
+
async dispose(): Promise<void> {
|
|
590
|
+
if (this.disposed) return
|
|
591
|
+
this.disposed = true
|
|
592
|
+
await this.flushCommitter()
|
|
593
|
+
await this.teardownExtras()
|
|
594
|
+
await this.server.stop().catch(() => undefined)
|
|
595
|
+
}
|
|
596
|
+
}
|