@black-studio/plugin 0.0.0-stage → 1.0.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.
Files changed (5) hide show
  1. package/README.md +807 -2
  2. package/build.mjs +118 -0
  3. package/cli.mjs +28 -0
  4. package/index.d.ts +911 -0
  5. package/package.json +18 -4
package/index.d.ts ADDED
@@ -0,0 +1,911 @@
1
+ /**
2
+ * @black-studio/plugin: the API that Bläck Studio plugins are written against.
3
+ *
4
+ * import { Plugin } from '@black-studio/plugin'
5
+ *
6
+ * export default class WordOfTheDay extends Plugin {
7
+ * onload() {
8
+ * this.addCommand({ id: 'hello', name: 'Say hello', run: () => this.app.ui.notify('Hello') })
9
+ * }
10
+ * }
11
+ *
12
+ * A plugin runs in one of two places:
13
+ * - In the app's window, where it can draw its own interface with React. It
14
+ * shares the app's copy of React: import React from 'react'.
15
+ * - In a separate worker, if its manifest has "sandboxed": true. It can use
16
+ * everything here except what draws its own interface (views, inspector
17
+ * tabs, sidebar panels, dashboard cards, settings panels, its own dialogs and
18
+ * editor extensions), editor.active, editor.anchor and app.speech.
19
+ *
20
+ * Code that avoids those features works in both places.
21
+ *
22
+ * Everything a plugin adds through these methods is removed when the plugin is
23
+ * turned off or reloaded. A plugin can access the book only through `this.app`,
24
+ * and the internet only through `this.app.net`, limited to the hosts its
25
+ * manifest names (or addresses the writer entered) and the writer allowed.
26
+ */
27
+
28
+ import type { ReactNode, ComponentType } from 'react'
29
+ import type { AnyExtension } from '@tiptap/core'
30
+ import type { Editor } from '@tiptap/core'
31
+
32
+ /** A project folder, as returned by app.folder. */
33
+ export interface ProjectFolder {
34
+ key: string
35
+ name: string
36
+ /** The open book's folder, relative to the project: `books/<id>`. Empty for a folder from folder.create. */
37
+ book: string
38
+ }
39
+
40
+ /** One version in a plugin's version history (see addVersionHistory). */
41
+ export interface VersionEntry {
42
+ /** The plugin's identifier for the version. The app passes it back to `read`. */
43
+ id: string
44
+ label: string
45
+ /** When it was saved, as an ISO date. */
46
+ at: string
47
+ }
48
+
49
+ /** What a `during` handler is told about the moment the app is waiting at. */
50
+ export interface WaitInfo {
51
+ /** The number of words in the whole project. */
52
+ words: number
53
+ /** Whether the project has changed since plugins were last told of a 'copy-due' or 'project-closing'. Always true for a new book. */
54
+ changed: boolean
55
+ /**
56
+ * Only for 'project-closing': true when the window is closing, or the app is going to the background on a phone or
57
+ * tablet. Finish all work in the handler; don't leave anything for later.
58
+ */
59
+ quitting?: boolean
60
+ /** Only for 'copy-due': 'timer' when the writing timer runs out and something has changed, 'new-book' when a book was just made. */
61
+ reason?: 'timer' | 'new-book'
62
+ }
63
+
64
+ export interface Manifest {
65
+ /** 2 to 64 lower-case letters, digits and dashes, starting with a letter or digit. It's also the name of the plugin's folder. */
66
+ id: string
67
+ name: string
68
+ version: string
69
+ description: string
70
+ author: string
71
+ /**
72
+ * The plugin API version the plugin needs. Defaults to 1.
73
+ */
74
+ apiVersion: number
75
+ /** The plugin's script, relative to its folder. Defaults to main.js. */
76
+ main: string
77
+ /** Runs the plugin in a separate worker instead of the app's window. */
78
+ sandboxed: boolean
79
+ /** The plugin's name and description in other languages, keyed by language code: { "sv": { "name": "…", "description": "…" } }. */
80
+ locales?: Record<string, { name?: string; description?: string }>
81
+ /**
82
+ * Permissions the plugin can request later with app.permissions.request, when the writer uses a feature that
83
+ * needs them (such as sending text to a service). They take the same values as `permissions`, but the writer
84
+ * isn't asked for them when the plugin is turned on. API 5.
85
+ *
86
+ * "network:ask" lets the plugin request access to an address the writer entered (such as a repository URL), which
87
+ * it can't list in advance. Request `address:https://host/path`: the writer is asked to allow that exact address,
88
+ * and the plugin can then reach that address and the paths under it. API 10.
89
+ */
90
+ optionalPermissions?: string[]
91
+ /**
92
+ * Why the plugin needs each permission in `permissions` or `optionalPermissions`, keyed by permission. The
93
+ * writer sees the reason when asked to allow the permission, under "it needs to:" and above the app's own
94
+ * description. Write it to complete the sentence "it needs to …", and say what is sent where, and why. Give
95
+ * one string, or one per language code, each up to 300 characters. API 8.
96
+ *
97
+ * "permissionReasons": {
98
+ * "network:api.example.com": {
99
+ * "en": "fetch today's word from Example (api.example.com)",
100
+ * "sv": "hämta dagens ord från Example (api.example.com)"
101
+ * }
102
+ * }
103
+ */
104
+ permissionReasons?: Record<string, string | Record<string, string>>
105
+ /**
106
+ * The group the plugin is listed under in Manage Plugins:
107
+ * - "writing": tools for the text while writing
108
+ * - "planning": the binder, cards and views
109
+ * - "welcome": the welcome screen
110
+ * - "import-export": importing and exporting books
111
+ * - "other": anything else
112
+ *
113
+ * Without a category, the plugin is grouped by what it adds while it's turned on, and under "other" while it's off. API 8.
114
+ */
115
+ category?: 'writing' | 'planning' | 'welcome' | 'import-export' | 'other'
116
+ /**
117
+ * What the plugin needs beyond reading the book. The writer is asked to allow each one:
118
+ * - "project:write": change the book.
119
+ * - "library:read": see the writer's recent books and their series (app.library), for the dashboard.
120
+ * - "project:folder": read and change every file in the open project's folder, including hidden ones such as a
121
+ * version history (app.folder). Nothing outside that folder is accessible. API 10.
122
+ * - "microphone": record audio with navigator.mediaDevices.getUserMedia, in the window. API 3.
123
+ * - "network:<host>": connect to that host. Use "network:*.<host>" to include its subdomains, or "network:*" for any
124
+ * public host. "network:*" never covers this computer or the local network: name those hosts explicitly.
125
+ * - "files:read", "files:write": read or change files and folders the writer chooses for the plugin.
126
+ * - "exec:<program>": run that program, found by name on the PATH, without a shell.
127
+ */
128
+ permissions: string[]
129
+ }
130
+
131
+ export type NodeType = 'text' | 'folder' | 'character' | 'place' | 'note' | 'research' | 'file'
132
+
133
+ export interface NodeInfo {
134
+ id: string
135
+ title: string
136
+ type: NodeType
137
+ parentId: string | null
138
+ children: string[]
139
+ inTrash: boolean
140
+ }
141
+
142
+ export interface MetaInfo {
143
+ synopsis: string
144
+ notes: string
145
+ keywords: string[]
146
+ /** The fields on a character's or place's sheet: "Age", "Born"… */
147
+ fields: Record<string, string>
148
+ /** When the scene happens, as written on its card: "Day 3", "1888-05-01"… */
149
+ when: string
150
+ words: number
151
+ }
152
+
153
+ export interface Label {
154
+ id: string
155
+ name: string
156
+ color: string
157
+ }
158
+
159
+ export interface Status {
160
+ id: string
161
+ name: string
162
+ /** The colour on the corkboard (#rrggbb) when cards are coloured by status. */
163
+ color?: string
164
+ }
165
+
166
+ export interface FileEntry {
167
+ name: string
168
+ path: string
169
+ folder: boolean
170
+ size: number
171
+ modified: string
172
+ }
173
+
174
+ export interface ExecOutput {
175
+ /** The exit code, or null if the program was stopped. */
176
+ code: number | null
177
+ stdout: Uint8Array
178
+ stderr: string
179
+ timedOut: boolean
180
+ /** stdout as text. */
181
+ text(): string
182
+ }
183
+
184
+ export interface FetchResult {
185
+ ok: boolean
186
+ status: number
187
+ statusText: string
188
+ headers: Record<string, string>
189
+ text(): string
190
+ json(): unknown
191
+ bytes(): Uint8Array
192
+ }
193
+
194
+ /** A summary of one of the writer's books, read from its files, for the welcome screen's dashboard. */
195
+ export interface LibraryBook {
196
+ /** The book's folder. Pass this to app.library.open. */
197
+ path: string
198
+ title: string
199
+ author: string
200
+ /** When it was last opened in the app (ISO), or '' for a book in a series that's never been opened. */
201
+ opened: string
202
+ /** When anything in the book last changed (ISO). */
203
+ modified: string
204
+ /** The book's series: its name and folder, the book's zero-based position in it, and the number of books. Null if it isn't in one. */
205
+ series: { name: string; path: string; index: number; books: number } | null
206
+ /** The number of words and scenes in the manuscript. */
207
+ words: number
208
+ scenes: number
209
+ /** The word target (0 for none) and the deadline (YYYY-MM-DD, or '' for none). */
210
+ target: number
211
+ deadline: string
212
+ /** The daily writing goal (0 for none). */
213
+ sessionTarget: number
214
+ /** Words written per day, keyed by date (YYYY-MM-DD, in the writer's time zone). Empty for a book that isn't counted. */
215
+ history: Record<string, number>
216
+ /**
217
+ * Whether the book counts in the writer's statistics. It's false for a sample, or for a book or series
218
+ * the writer left out, so leave those out of totals and goals. Older versions of the app don't set it, so
219
+ * treat a missing value as true.
220
+ */
221
+ counted?: boolean
222
+ /** The number of scenes with each status, in the order the book lists its statuses. */
223
+ statuses: { name: string; count: number }[]
224
+ /** The scene most recently written in, with the last few hundred characters of its text (as plain text). */
225
+ last: { id: string; title: string; modified: string; excerpt: string } | null
226
+ }
227
+
228
+ /** Recent activity across the writer's books. */
229
+ export interface LibraryActivity {
230
+ /** The latest saved versions (git commits), newest first. */
231
+ versions: { book: string; title: string; message: string; date: string }[]
232
+ /** The latest zip backups, newest first. */
233
+ backups: { file: string; date: string; size: number }[]
234
+ /** The most recent push of each book's version history, newest first. */
235
+ pushes: { book: string; title: string; ok: boolean; at: string; message: string }[]
236
+ }
237
+
238
+ export interface App {
239
+ readonly apiVersion: number
240
+ /** The language of the app's interface: 'en', 'sv'… */
241
+ readonly language: string
242
+
243
+ /**
244
+ * The open book. Changing it needs "project:write". Every change can be undone, and the app takes a snapshot
245
+ * of a document before a plugin first rewrites it.
246
+ */
247
+ project: {
248
+ isOpen(): Promise<boolean>
249
+ info(): Promise<{ title: string; author: string; language: string; series: string | null } | null>
250
+ nodes(): Promise<NodeInfo[]>
251
+ node(id: string): Promise<NodeInfo | null>
252
+ /** The manuscript's documents, in reading order. */
253
+ manuscript(): Promise<string[]>
254
+ selected(): Promise<string | null>
255
+ select(id: string): Promise<void>
256
+ /** A document's text as HTML. */
257
+ read(id: string): Promise<string>
258
+ /** A document's text as plain text. */
259
+ readText(id: string): Promise<string>
260
+ write(id: string, html: string): Promise<void>
261
+ create(type: 'text' | 'folder' | 'character' | 'place' | 'note' | 'research', title: string, parentId?: string): Promise<string>
262
+ meta(id: string): Promise<MetaInfo | null>
263
+ setMeta(id: string, patch: Partial<Pick<MetaInfo, 'synopsis' | 'notes' | 'keywords' | 'fields' | 'when'>>): Promise<void>
264
+ /** Moves an item to the trash, where the writer can restore it. */
265
+ trash(id: string): Promise<void>
266
+ rename(id: string, title: string): Promise<void>
267
+ /** Moves an item into a folder, at `index` among its children, or at the end if there's no index. */
268
+ move(id: string, parentId: string, index?: number): Promise<void>
269
+ labels(): Promise<Label[]>
270
+ statuses(): Promise<Status[]>
271
+ /** Sets an item's label by the label's id, or '' to clear it. setStatus works the same way. */
272
+ setLabel(id: string, labelId: string): Promise<void>
273
+ setStatus(id: string, statusId: string): Promise<void>
274
+ comments(id: string): Promise<{ id: string; text: string; created: string; resolved: boolean }[]>
275
+ resolveComment(id: string, commentId: string, resolved?: boolean): Promise<void>
276
+ snapshots(id: string): Promise<{ label: string; taken: string; html: string }[]>
277
+ /** Saves a snapshot of a document as it is now. This needs no permission. */
278
+ snapshot(id: string, label: string): Promise<void>
279
+ /** Searches the book, like Find in Project. */
280
+ search(
281
+ query: string,
282
+ opts?: { wholeWord?: boolean; caseSensitive?: boolean; regex?: boolean },
283
+ ): Promise<{ id: string; title: string; line: number; excerpt: string }[]>
284
+ /** The book's series and its books in order, or null if the book isn't in a series. */
285
+ series(): Promise<{ name: string; books: { id: string; title: string; current: boolean }[] } | null>
286
+ /** Resolves once every pending change is saved to disk. API 10: check that it exists. */
287
+ flush?(): Promise<void>
288
+ /**
289
+ * This plugin's data for the whole project, or undefined. It's stored in the project's project.json on this device,
290
+ * and isn't shared on Bläck Sync. If the project.json can't be read, getProjectData returns undefined and
291
+ * setProjectData throws. API 10: check that it exists.
292
+ */
293
+ getProjectData?(): Promise<unknown>
294
+ setProjectData?(value: unknown): Promise<void>
295
+ /** Opens a project that this plugin created with folder.create, by its key. Returns false if it couldn't be opened. API 10: check that it exists. */
296
+ open?(key: string): Promise<boolean>
297
+ /** This plugin's data for this book, saved in the book. */
298
+ getData(): Promise<unknown>
299
+ setData(value: unknown): Promise<void>
300
+ }
301
+
302
+ editor: {
303
+ /** The TipTap editor the writer is using. Window only: it's null in a sandboxed plugin. */
304
+ active(): Editor | null
305
+ selection(): Promise<{ text: string; from: number; to: number } | null>
306
+ /** Types text at the caret, replacing any selection. Returns false if no editor is active. Needs "project:write". */
307
+ insertText(text: string): Promise<boolean>
308
+ /** Adds a margin comment on the selection. Returns false if nothing is selected. Needs "project:write". */
309
+ comment(text: string): Promise<boolean>
310
+ /**
311
+ * Returns a position for inserting text as it arrives, as dictation does: the writer's cursor, or where it was
312
+ * before they clicked a button, or else the end of the open document. The position moves with edits around it.
313
+ * Returns null if no document is open. Needs "project:write". Window only. API 4.
314
+ */
315
+ anchor(): Promise<EditorAnchor | null>
316
+ }
317
+
318
+ ui: {
319
+ /** Shows a notice, with a button if you pass an action. A sandboxed plugin's notice has no button. */
320
+ notify(message: string, action?: { label: string; run: () => void }): void
321
+ /** Asks a yes-or-no question in an app dialog. `confirmLabel` defaults to "OK". Resolves to true if the writer confirms. */
322
+ confirm(title: string, detail?: string, confirmLabel?: string): Promise<boolean>
323
+ /** Shows one of this plugin's views. Window only. */
324
+ openView(viewId: string): void
325
+ /** Shows this plugin's settings. */
326
+ openSettings(): void
327
+ /** Opens a dialog that the plugin draws itself. Returns a function that closes it. Window only. */
328
+ openModal(modal: {
329
+ title: string
330
+ render: (close: () => void) => ReactNode
331
+ wide?: boolean
332
+ /** Called when the dialog closes: 'closed' if the writer closed it (Escape, ✕) or `close` was called, 'replaced' if another dialog took its place. */
333
+ onClose?: (how: 'closed' | 'replaced') => void
334
+ }): () => void
335
+ /** Asks for a line of text. Returns null if the writer cancels. */
336
+ prompt(opts: { title: string; label?: string; value?: string; placeholder?: string }): Promise<string | null>
337
+ /** Asks the writer to choose one option. Returns null if they cancel. */
338
+ choose(opts: { title: string; options: { value: string; label: string; detail?: string }[] }): Promise<string | null>
339
+ /** Starts a writing sprint of 1 to 600 minutes in the open book, like the status bar's sprint. Throws if no book is open. API 2. */
340
+ startSprint(minutes: number): void
341
+ /**
342
+ * Shows a list of the marks from one of this plugin's highlighters in the current document, each with its
343
+ * surrounding text. The app selects the mark the writer picks. Resolves to false if there are no marks or
344
+ * the writer picks none. API 6: check that it exists before calling it.
345
+ */
346
+ listMarks?(opts: {
347
+ highlighter: string
348
+ title: string
349
+ /** The heading for quiet marks (HighlightRange.quiet), which are listed last, each with its actions. API 9. */
350
+ quietTitle?: string
351
+ }): Promise<boolean>
352
+ }
353
+
354
+ /**
355
+ * The open project's folder, which holds its books. Needs "project:folder". API 10: check that it exists before using it.
356
+ *
357
+ * Paths are relative to the project's folder and use "/" as the separator. A path is refused if it's absolute, contains
358
+ * "..", goes through a symbolic link, has a name that isn't valid on every system, or names `.sync` (at any level) or
359
+ * `.git` (below the top level). Every call takes the project's key from current() instead of a path, so work started on one project can't
360
+ * end up in the next one opened. A key stops working two minutes after its project closes.
361
+ */
362
+ folder?: {
363
+ /** Returns the open project's key, name and book folder (`books/<id>`), or null if no project is open. */
364
+ current(): Promise<ProjectFolder | null>
365
+ /**
366
+ * Asks the writer where to create a new project and creates its folder, for a plugin that brings in a project from
367
+ * elsewhere. `title` is the dialog's title and `name` the suggested folder name. Returns null if the writer cancels.
368
+ */
369
+ create(title: string, name: string): Promise<ProjectFolder | null>
370
+ /** Deletes a folder made by create() that the plugin couldn't finish. This works only before the project is opened. */
371
+ discard(key: string): Promise<void>
372
+ /** Returns the file's bytes, or null if it doesn't exist. */
373
+ read(key: string, path: string): Promise<Uint8Array | null>
374
+ /** Writes the whole file, creating any missing parent folders. */
375
+ write(key: string, path: string, data: string | Uint8Array): Promise<void>
376
+ /** Deletes a file permanently (it doesn't go to the trash). Returns false if there was no such file. */
377
+ remove(key: string, path: string): Promise<boolean>
378
+ /** Lists a folder's contents ('' for the project's folder itself), or returns null if the folder doesn't exist. */
379
+ list(key: string, path: string): Promise<{ name: string; folder: boolean; link: boolean }[] | null>
380
+ /** Returns information about a file or folder, without following symbolic links, or null if nothing is there. */
381
+ stat(key: string, path: string): Promise<{ folder: boolean; link: boolean; size: number; mode: number; mtimeMs: number; ctimeMs: number; ino: number; uid: number; gid: number; dev: number } | null>
382
+ mkdir(key: string, path: string): Promise<void>
383
+ /** Deletes an empty folder. Returns false if the folder isn't empty or doesn't exist. */
384
+ rmdir(key: string, path: string): Promise<boolean>
385
+ /** Tells the app that these files were changed from outside the app: they're marked as downloaded, and the open book reloads them. */
386
+ arrived(key: string, paths: string[]): Promise<void>
387
+ /** Reports a new version or the result of a push, so the dashboard can list it for the project. */
388
+ note(key: string, note: { version?: { message: string; date: string }; push?: { ok: boolean; message: string } }): Promise<void>
389
+ }
390
+
391
+ /**
392
+ * The writer's books: those on the recent list, and every book in their series. Needs "library:read". API 2.
393
+ */
394
+ library: {
395
+ books(): Promise<LibraryBook[]>
396
+ activity(): Promise<LibraryActivity>
397
+ /** Opens a book, closing the current one, optionally at a given document. Returns false if that fails. */
398
+ open(path: string, opts?: { select?: string }): Promise<boolean>
399
+ }
400
+
401
+ net: {
402
+ /**
403
+ * Makes an https request to a host the plugin may reach, and returns the whole response (on a computer, up to
404
+ * 20 MB within 30 seconds). Plain http works only for localhost and 127.0.0.1. Redirects aren't followed.
405
+ */
406
+ fetch(
407
+ url: string,
408
+ init?: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array },
409
+ ): Promise<FetchResult>
410
+ /**
411
+ * Like fetch, but passes the response body to onChunk as text while it arrives, for example an AI model's reply.
412
+ * Resolves with the status and headers once the response is complete. Up to 200 MB and ten minutes. On a phone,
413
+ * the whole body arrives as one chunk. Chromium buffers the first 512 bytes of a text/plain response to detect
414
+ * its type, so they may arrive together unless the response has "X-Content-Type-Options: nosniff". Event
415
+ * streams and JSON aren't affected.
416
+ */
417
+ stream(
418
+ url: string,
419
+ init: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array } | undefined,
420
+ onChunk: (text: string) => void,
421
+ ): Promise<{ ok: boolean; status: number; statusText: string; headers: Record<string, string> }>
422
+ /** Like stream, but passes each chunk as raw bytes, for binary data. Up to 200 MB and ten minutes. API 10: check that it exists. */
423
+ streamBytes?(
424
+ url: string,
425
+ init: { method?: string; headers?: Record<string, string>; body?: string | Uint8Array } | undefined,
426
+ onChunk: (chunk: Uint8Array) => void,
427
+ ): Promise<{ ok: boolean; status: number; statusText: string; headers: Record<string, string> }>
428
+ }
429
+
430
+ /**
431
+ * Files on the computer. The plugin can access only what the writer chose for it (with pickFolder and pickFile),
432
+ * and its own temporary folder. Needs "files:read" or "files:write". All paths are absolute.
433
+ */
434
+ files: {
435
+ /**
436
+ * Asks the writer to choose a folder, and returns its path or null. The plugin can then read what's in it, and
437
+ * change it if `write` is set and the plugin has "files:write".
438
+ */
439
+ pickFolder(opts?: { write?: boolean; title?: string }): Promise<string | null>
440
+ /** Asks the writer to choose a file to open, or where to save one if `save` is set. Returns the path, or null if they cancel. */
441
+ pickFile(opts?: { save?: boolean; name?: string; extensions?: string[]; title?: string }): Promise<string | null>
442
+ granted(): Promise<{ path: string; write: boolean; file?: boolean }[]>
443
+ /** The plugin's temporary folder, for passing files to programs. */
444
+ temp(): Promise<string>
445
+ read(path: string): Promise<Uint8Array>
446
+ readText(path: string): Promise<string>
447
+ write(path: string, data: string | Uint8Array): Promise<void>
448
+ list(path: string): Promise<FileEntry[]>
449
+ stat(path: string): Promise<{ folder: boolean; size: number; modified: string } | null>
450
+ mkdir(path: string): Promise<void>
451
+ /** Moves a file to the system's trash. */
452
+ trash(path: string): Promise<void>
453
+ }
454
+
455
+ /**
456
+ * Runs programs that the manifest lists as "exec:<program>". Each is found by name on the PATH and runs without a
457
+ * shell. `timeout` is in milliseconds: one minute by default, ten minutes at most.
458
+ */
459
+ exec: {
460
+ run(
461
+ program: string,
462
+ args?: string[],
463
+ opts?: { input?: string | Uint8Array; cwd?: string; timeout?: number },
464
+ ): Promise<ExecOutput>
465
+ }
466
+
467
+ /** The plugin's optional permissions (see the manifest's optionalPermissions). API 5: check that this exists before using it. */
468
+ permissions?: {
469
+ /** Asks the writer to allow the permission, in the app's own window. Resolves to true if it's allowed, whether now or earlier. */
470
+ request(permission: string | string[]): Promise<boolean>
471
+ /** Whether the plugin has the permission now. In a sandboxed plugin, the answer comes as a promise. */
472
+ has(permission: string): boolean | Promise<boolean>
473
+ }
474
+
475
+ /**
476
+ * Speech recognition on the device: nothing is sent anywhere. On a computer it uses Whisper, whose model is
477
+ * downloaded once the writer agrees. On a phone or tablet it uses the system's recogniser. Needs "microphone",
478
+ * and isn't available to sandboxed plugins. API 4.
479
+ *
480
+ * `language` is a code like "sv" or "en". Use '' to let a computer detect the language from the speech.
481
+ *
482
+ * `model` selects the Whisper model on a computer. Each model is downloaded once:
483
+ * - For every language: "tiny", "base", "small" (the default), "medium", "large-v3-turbo" or "large-v3".
484
+ * - For English only: "tiny.en" to "medium.en".
485
+ * - For Swedish only: "kb-tiny" to "kb-large" (KB-Whisper), or "pianissimo" (Klang's Pianissimo, API 5).
486
+ *
487
+ * Each model is used with Silero voice activity detection, which detects where a phrase ends. A phone uses these
488
+ * models only when it uses Whisper instead of the system's recogniser (see SpeechChoice.engine).
489
+ */
490
+ speech: {
491
+ /** Reports whether recognition is ready. If not, says what's missing: a download (`size` bytes, if known), or that it's unavailable here. */
492
+ status(language: string, opts?: SpeechChoice): Promise<SpeechStatus>
493
+ /**
494
+ * Loads the model ahead of time, such as when a book opens, so the first dictation is as fast as the rest.
495
+ * It only loads a model already on the device, and never downloads one. The model is unloaded after ten
496
+ * minutes without use. Returns true if it's ready. API 5: check that it exists before calling it.
497
+ */
498
+ preload?(language: string, opts?: SpeechChoice): Promise<boolean>
499
+ /** Downloads what's needed, after asking the writer. Returns false if they decline. */
500
+ prepare(language: string, opts?: SpeechChoice & { onProgress?: (fraction: number) => void }): Promise<boolean>
501
+ /** Starts listening and resolves with a session. The session's stop() returns the recognised text. On a phone, onPartial receives words as they're heard. */
502
+ listen(opts: SpeechChoice & {
503
+ /** Use '' to detect the language among `languages`, the app's language, the system's language and English. */
504
+ language: string
505
+ languages?: string[]
506
+ /** The current phrase, as recognised so far. */
507
+ onPartial?: (text: string) => void
508
+ /** Receives each finished phrase when the writer pauses. With onSegment, stop() returns only the text not yet passed to it. */
509
+ onSegment?: (text: string) => void
510
+ /** Called when something goes wrong. No more text will arrive. */
511
+ onError?: (message: string) => void
512
+ /** Receives the input level (0 to 1) several times a second, for showing that the microphone hears something. Older versions of the app don't call this. */
513
+ onLevel?: (level: number) => void
514
+ /** How long a pause ends a phrase: 'quick', 'balanced' (the default), 'patient', or a number of seconds. API 5. */
515
+ pause?: 'quick' | 'balanced' | 'patient' | number
516
+ /** The microphone to use, by its id from microphones(). Without one, the system's default is used. API 5. */
517
+ microphone?: string
518
+ }): Promise<SpeechSession>
519
+ /** The available microphones. Their names appear once the writer has allowed the app to use one. API 5. */
520
+ microphones?(): Promise<{ id: string; name: string }[]>
521
+ }
522
+ }
523
+
524
+ /** Options for how speech is recognised. Pass the same options to status, prepare and listen. */
525
+ export interface SpeechChoice {
526
+ /** The Whisper model (see app.speech). */
527
+ model?: string
528
+ /** Runs Whisper on the CPU, even if a GPU is available. */
529
+ processor?: boolean
530
+ /** On a phone: 'system' uses the system's recogniser, 'whisper' uses Whisper, and 'auto' uses the system's where it supports the language. */
531
+ engine?: 'auto' | 'system' | 'whisper'
532
+ }
533
+
534
+ /** A position in the text for inserting text over time. See app.editor.anchor. */
535
+ export interface EditorAnchor {
536
+ docId: string
537
+ /** The character just before the position, to decide whether new text needs a space first. */
538
+ before(): string
539
+ /** The character just after the position, to decide whether new text needs a space after it. API 5: check that it exists. */
540
+ after?(): string
541
+ /** Shows greyed-out words at the position, as dictation does. They aren't part of the text. Use '' to clear them. API 5: check that it exists. */
542
+ draft?(text: string): void
543
+ /** Inserts plain text at the position, after anything inserted earlier. Returns false if the document is no longer open in an editor. */
544
+ insert(text: string): boolean
545
+ /** Call this when you're finished with the anchor. It also clears any draft. */
546
+ release(): void
547
+ }
548
+
549
+ export interface SpeechStatus {
550
+ ready: boolean
551
+ /** The number of bytes still to download, if known. */
552
+ size: number
553
+ /**
554
+ * On a computer, the parts of that download: the model itself (`model: true`) and the voice detection model.
555
+ * API 7: check that it exists.
556
+ */
557
+ parts?: { title: string; size: number; model: boolean }[]
558
+ /** Why it can't work on this device: there's no recogniser, or it doesn't support this language. */
559
+ unavailable?: 'device' | 'language'
560
+ }
561
+
562
+ export interface SpeechSession {
563
+ /** Stops listening and returns what was said. */
564
+ stop(): Promise<string>
565
+ /** Stops listening and discards what was heard. */
566
+ cancel(): void
567
+ /** Pauses listening and releases the microphone until resume() is called. Text recognised so far is kept. Older versions of the app don't have this, so check that it exists. */
568
+ pause?(): void
569
+ resume?(): void
570
+ }
571
+
572
+ /** What the writer right-clicked on in the text. */
573
+ export interface EditorContext {
574
+ docId: string
575
+ /** The selected text, or '' if there's none. */
576
+ selection: string
577
+ /** The word at the caret, when nothing is selected. */
578
+ word: string
579
+ }
580
+
581
+ /** A part of a paragraph to mark, given as character offsets in its text. */
582
+ export interface HighlightRange {
583
+ from: number
584
+ to: number
585
+ /** Shown as a tooltip when the pointer hovers over the mark, and in its right-click menu. */
586
+ message?: string
587
+ /** Actions for the mark's right-click menu, such as "Ignore". The highlighter's onAction gets the chosen one. API 6. */
588
+ actions?: { id: string; label: string }[]
589
+ /**
590
+ * Hides the mark from the text and the right-click menu. ui.listMarks still lists it separately, with its
591
+ * actions. Use this for something the writer ignored, with an action to show it again. API 9: older versions
592
+ * of the app draw it like any other mark, so only use this when app.apiVersion is 9 or higher.
593
+ */
594
+ quiet?: boolean
595
+ }
596
+
597
+ /** The mark that an action was chosen for. API 6. */
598
+ export interface MarkInfo {
599
+ /** The marked text. */
600
+ text: string
601
+ /** The text of the paragraph it's in, as passed to `find`, and the mark's offsets in it. */
602
+ paragraph: string
603
+ from: number
604
+ to: number
605
+ /** The document it's in. */
606
+ docId: string
607
+ }
608
+
609
+ /** The compiled book, passed to an export format. */
610
+ export interface ExportInput {
611
+ title: string
612
+ author: string
613
+ language: string
614
+ /** The whole manuscript as one HTML document, the same as the app's own HTML export. */
615
+ html: string
616
+ /** Each part in reading order: a folder's title, or a scene's title and text as HTML. */
617
+ items: { id: string; title: string; depth: number; isFolder: boolean; section: 'front' | 'body' | 'back'; html: string }[]
618
+ }
619
+
620
+ export interface SettingField {
621
+ key: string
622
+ label: string
623
+ /** 'secret' is text shown as dots, for an API key or password (API 3). */
624
+ type: 'text' | 'secret' | 'textarea' | 'number' | 'toggle' | 'select'
625
+ description?: string
626
+ default?: unknown
627
+ options?: { value: string; label: string }[]
628
+ /** Shows the field only while other settings have one of these values: { source: ['web', 'feed'] }. API 5. */
629
+ showWhen?: Record<string, string[]>
630
+ /** Puts the field in a collapsed section with this heading, with any other fields that use the same heading. API 5. */
631
+ folded?: string
632
+ }
633
+
634
+ export type PluginEvent = 'project-open' | 'project-close' | 'selection-change' | 'doc-change' | 'nodes-change'
635
+
636
+ /** A suggestion offered as the writer types after a trigger. */
637
+ export interface Suggestion {
638
+ label: string
639
+ /** The text that replaces the trigger and everything typed after it. Defaults to `label`. */
640
+ insert?: string
641
+ detail?: string
642
+ }
643
+
644
+ /** A file the writer picked to import. */
645
+ export interface ImportFile {
646
+ name: string
647
+ /** The extension in lower case, without the dot. */
648
+ ext: string
649
+ data: Uint8Array
650
+ /** The contents as text (UTF-8). */
651
+ text: string
652
+ }
653
+
654
+ /** The file or folder the writer picked for a book importer. API 7. */
655
+ export interface ImportSource {
656
+ /** Its name: "Sample.scriv", "outline.pltr". */
657
+ name: string
658
+ /** The extension in lower case, without the dot. */
659
+ ext: string
660
+ /** True for a folder. On a phone, this is the folder inside the zip the writer chose. */
661
+ folder: boolean
662
+ /** A file's contents as bytes and as text (UTF-8). Not set for a folder. */
663
+ data?: Uint8Array
664
+ text?: string
665
+ /** Every file in a folder, at any depth, with paths using "/". Empty for a single file. */
666
+ files: { path: string; size: number }[]
667
+ /** Reads a file in the folder, by its path in `files`. */
668
+ read(path: string): Promise<Uint8Array>
669
+ readText(path: string): Promise<string>
670
+ }
671
+
672
+ /**
673
+ * An item in an imported book's binder. `id` is only for other items in the import to refer to it, such as a
674
+ * scene's cast or a beat's scene. The app assigns its own id. API 7.
675
+ */
676
+ export interface ImportedItem {
677
+ id?: string
678
+ /**
679
+ * The item's type. Without one, an item with children is a folder. Any other item takes the type of the binder
680
+ * section it's in: a scene in the manuscript, a sheet in characters, a note in Notes, a document in Research.
681
+ */
682
+ type?: NodeType
683
+ title: string
684
+ /** The text as HTML: paragraphs, headings, emphasis, lists, quotes, and <hr> for a scene break. */
685
+ html?: string
686
+ synopsis?: string
687
+ notes?: string
688
+ keywords?: string[]
689
+ /** The label and status, by their ids in the book's `labels` and `statuses`. */
690
+ label?: string
691
+ status?: string
692
+ /** Whether Compile includes the item. Defaults to true. */
693
+ includeInCompile?: boolean
694
+ /** Fields for a sheet ("Age", "Born"…), added to the fields the book already has. */
695
+ fields?: Record<string, string>
696
+ /** When the scene happens, as written on its card. */
697
+ when?: string
698
+ /** The characters in a scene, and where it's set, by their item ids. */
699
+ cast?: string[]
700
+ place?: string
701
+ /** For a "file" item: its path in the picked folder, and the name to save it under. */
702
+ file?: { path: string; name: string }
703
+ children?: ImportedItem[]
704
+ }
705
+
706
+ /**
707
+ * The book that a book importer returns. The writer can make it a new book or add it to the open one.
708
+ *
709
+ * As a new book, its labels and statuses, if any, replace the writer's defaults.
710
+ *
711
+ * When it's added to the open book:
712
+ * - The manuscript and research each go in a new folder.
713
+ * - Characters and places are merged with the existing sheets, matching sheets by name.
714
+ * - Labels, statuses and storylines are matched by name.
715
+ * - The trash is left out.
716
+ *
717
+ * API 7.
718
+ */
719
+ export interface ImportedBook {
720
+ title: string
721
+ author?: string
722
+ /** A summary of what was imported, shown in the dialog before the writer chooses. */
723
+ about?: string
724
+ /** The name of the new folders when adding to the open book: "From Scrivener — Sample". */
725
+ folder?: string
726
+ labels?: { id: string; name: string; color?: string }[]
727
+ statuses?: { id: string; name: string; color?: string }[]
728
+ storylines?: { id: string; name: string; color?: string; description?: string }[]
729
+ manuscript?: ImportedItem[]
730
+ characters?: ImportedItem[]
731
+ places?: ImportedItem[]
732
+ notes?: ImportedItem[]
733
+ research?: ImportedItem[]
734
+ trash?: ImportedItem[]
735
+ /** Beats (cards on the plot grid). Each names its storyline by id, and its scene by id if it belongs to one. */
736
+ beats?: { storyline: string; scene?: string; title: string; description?: string }[]
737
+ }
738
+
739
+ export declare class Plugin {
740
+ readonly app: App
741
+ readonly manifest: Manifest
742
+ /** The current values of the settings declared with `addSettings`. */
743
+ settings: Record<string, unknown>
744
+
745
+ /** Called when the plugin starts. Add commands, views and so on here. */
746
+ onload(): void | Promise<void>
747
+ /** Called when the plugin is turned off. Clean up anything the app doesn't remove itself. */
748
+ onunload(): void
749
+ /*
750
+ * Every add… method returns a function that removes what it added (the text form of addStatusBarItem returns an
751
+ * object instead), which is useful when a setting changes what a plugin offers. Anything still there is removed
752
+ * when the plugin is turned off.
753
+ */
754
+
755
+ /** Registers something to clean up when the plugin is turned off, such as a timer or a listener. */
756
+ register(dispose: () => void): void
757
+
758
+ /** Adds a command to the command palette (Ctrl+K) and, unless `menu` is false, the Plugins menu. `hotkey` looks like "Mod+Shift+F", where Mod is Ctrl or ⌘. */
759
+ addCommand(command: {
760
+ id: string
761
+ name: string
762
+ hotkey?: string
763
+ menu?: boolean
764
+ when?: () => boolean
765
+ run: () => void | Promise<void>
766
+ }): () => void
767
+ /** Adds a view beside the corkboard and outliner. Window only. */
768
+ addView(view: { id: string; name: string; icon?: ComponentType<{ size?: number }>; render: () => ReactNode }): () => void
769
+ /** Adds a tab to the inspector, for items where `when` returns true. Window only. */
770
+ addInspectorTab(tab: {
771
+ id: string
772
+ name: string | ((nodeId: string) => string)
773
+ when?: (nodeId: string, node: { type: NodeType; title: string }) => boolean
774
+ render: (nodeId: string) => ReactNode
775
+ }): () => void
776
+ /** Adds a status bar item. Either draw it with `render` (window only), or give it `text` and change that with setText, which also works in a sandboxed plugin. */
777
+ addStatusBarItem(item: { id: string; render: () => ReactNode }): () => void
778
+ addStatusBarItem(item: { id: string; text: string; title?: string; onClick?: () => unknown }): {
779
+ setText(text: string, title?: string): void
780
+ }
781
+ /** Adds an item to the editor's right-click menu. `show` defaults to 'always'. In a sandboxed plugin, the label must be a string and `when` isn't available, so use `show`. */
782
+ addEditorMenuItem(item: {
783
+ id: string
784
+ label: string | ((ctx: EditorContext) => string)
785
+ show?: 'selection' | 'no-selection' | 'always'
786
+ when?: (ctx: EditorContext) => boolean
787
+ run: (ctx: EditorContext) => void | Promise<void>
788
+ }): () => void
789
+ /** Adds an item to the binder's right-click menu. */
790
+ addBinderMenuItem(item: {
791
+ id: string
792
+ label: string | ((nodeId: string) => string)
793
+ when?: (nodeId: string) => boolean
794
+ run: (nodeId: string) => void | Promise<void>
795
+ }): () => void
796
+ /** Adds a format to Compile. Return text, or bytes for a binary format. */
797
+ addExporter(exporter: {
798
+ id: string
799
+ name: string
800
+ description?: string
801
+ extension: string
802
+ export: (book: ExportInput) => string | Uint8Array | Promise<string | Uint8Array>
803
+ }): () => void
804
+ /** Adds marks to the text, found one paragraph at a time. The app draws them, and they're never saved. */
805
+ addHighlighter(highlighter: {
806
+ id: string
807
+ color?: string
808
+ find: (text: string) => HighlightRange[] | Promise<HighlightRange[]>
809
+ /** Called when the writer chooses one of a mark's `actions` from its right-click menu. API 6. */
810
+ onAction?: (action: string, mark: MarkInfo) => unknown
811
+ }): () => void
812
+ /** Runs every highlighter again, for example after a setting that affects them changes. */
813
+ refreshHighlights(): void
814
+ /** Adds TipTap extensions to every editor. Window only. */
815
+ registerEditorExtension(extension: AnyExtension | AnyExtension[]): () => void
816
+ /** Adds a panel to the sidebar, beside the binder. Window only. */
817
+ addSidebarPanel(panel: { id: string; name: string; render: () => ReactNode }): () => void
818
+ /** Adds a button to the editor's toolbar. In a sandboxed plugin, the icon is text, such as an emoji. */
819
+ addToolbarButton(button: {
820
+ id: string
821
+ title: string
822
+ icon?: ComponentType<{ size?: number }> | string
823
+ active?: () => boolean
824
+ run: () => void | Promise<void>
825
+ }): () => void
826
+ /** Shows suggestions under the caret as the writer types after `trigger` ("@", "#"…) at the start of a word. `trigger` must be a single character. */
827
+ addSuggester(suggester: {
828
+ id: string
829
+ trigger: string
830
+ find: (query: string, ctx: { docId: string }) => Suggestion[] | Promise<Suggestion[]>
831
+ }): () => void
832
+ /** Adds a file type the app can't read itself to File → Import Documents. Each file becomes one or more documents. */
833
+ addImporter(importer: {
834
+ id: string
835
+ name: string
836
+ extensions: string[]
837
+ import: (file: ImportFile) => { title: string; html: string }[] | Promise<{ title: string; html: string }[]>
838
+ }): () => void
839
+ /**
840
+ * Imports a whole book from another app's file or folder, such as a Scrivener project or a Plottr outline. It
841
+ * appears in File → Import, and on the welcome screen while the plugin is on.
842
+ *
843
+ * The app asks for the file or folder, passes it to `import`, and shows the writer the result. The writer can
844
+ * then make it a new book or add it to the open one. To explain why a file can't be read, throw an Error: the
845
+ * writer sees its message. This needs no permission, because it reads only what the writer picked. API 7.
846
+ */
847
+ addBookImporter(importer: {
848
+ id: string
849
+ /** The name in File → Import: "Scrivener Project". */
850
+ name: string
851
+ /** The app name for "Import from …" on the welcome screen: "Scrivener". Defaults to `name`. */
852
+ from?: string
853
+ /** The file extensions without the dot: ["pltr"]. For a folder, use the folder's extension: ["scriv"]. */
854
+ extensions: string[]
855
+ /** True if it reads a folder (a .scriv), not a file. Phones can't choose folders, so the writer chooses a zip of it. */
856
+ folder?: boolean
857
+ import: (source: ImportSource) => ImportedBook | Promise<ImportedBook>
858
+ }): () => void
859
+ /**
860
+ * Adds a card to the welcome screen's dashboard, shown while no book is open. `size` is 'half' (the default) or
861
+ * 'full' width. Cards are sorted by `order`, lowest first (default 100). These only set where a card starts: the
862
+ * writer can move it and change its width later. Window only. API 2.
863
+ */
864
+ addDashboardWidget(widget: {
865
+ id: string
866
+ name: string
867
+ size?: 'half' | 'full'
868
+ order?: number
869
+ render: () => ReactNode
870
+ }): () => void
871
+ /** Adds settings that the app draws in Settings → Plugins. Read their values from `this.settings`. */
872
+ addSettings(fields: SettingField[]): () => void
873
+ /** Adds a settings panel that the plugin draws itself. Window only. */
874
+ addSettingsPanel(render: () => ReactNode): () => void
875
+ onSettingsChange(listener: (settings: Record<string, unknown>) => void): void
876
+ updateSettings(patch: Record<string, unknown>): Promise<void>
877
+ on(event: PluginEvent, handler: (arg: string | null) => void): void
878
+ /**
879
+ * Registers a handler for a moment when the app waits for plugins:
880
+ * - 'session-end': a writing session ended, after 30 minutes without writing or because the book is closing.
881
+ * - 'copy-due': the writing timer is due and something has changed, or a new book was created.
882
+ * - 'project-closing': a book is closing, or the app is quitting.
883
+ *
884
+ * If the handler returns a promise, the app waits for it for up to 30 seconds (10 for 'session-end'), then carries
885
+ * on. A plugin has one handler per event: calling `during` again for the same event replaces it. API 10.
886
+ */
887
+ during(event: 'session-end' | 'copy-due' | 'project-closing', handler: (info: WaitInfo) => unknown): () => void
888
+ /**
889
+ * Provides a version history of the project, which the app shows in Book → Versions & Backups and in a document's
890
+ * history. The app does the drawing, so this works in a sandboxed plugin. The plugin implements:
891
+ * - `list`: the versions, newest first. With `file` (a path in the project's folder), only those that changed it.
892
+ * - `read`: a file's text in a version.
893
+ * - `save`: saves a version with the writer's message. Returns false if nothing has changed since the last one.
894
+ * - `status` (optional): a message for the writer, such as a failed backup, or null.
895
+ *
896
+ * The app handles restoring, and always takes a snapshot of the document first. If more than one plugin provides a
897
+ * history, the app shows the first. API 10.
898
+ */
899
+ addVersionHistory(history: {
900
+ id: string
901
+ list(file?: string): Promise<VersionEntry[]>
902
+ read(version: string, file: string): Promise<string>
903
+ save(message: string): Promise<boolean>
904
+ status?(): Promise<{ text: string; problem?: boolean } | null>
905
+ }): () => void
906
+ /** Tells the app that the list of versions changed, so it reloads what it shows. API 10. */
907
+ versionsChanged(): void
908
+ /** The plugin's own data on this computer. For data stored in the book, see app.project.getData. */
909
+ loadData(): Promise<unknown>
910
+ saveData(data: unknown): Promise<void>
911
+ }