deictic 0.0.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -0
  3. package/dist/annotations/client.d.ts +4 -0
  4. package/dist/annotations/client.d.ts.map +1 -0
  5. package/dist/annotations/client.js +497 -0
  6. package/dist/annotations/client.js.map +1 -0
  7. package/dist/annotations/index.d.ts +110 -0
  8. package/dist/annotations/index.d.ts.map +1 -0
  9. package/dist/annotations/index.js +22 -0
  10. package/dist/annotations/index.js.map +1 -0
  11. package/dist/astro.d.ts +29 -0
  12. package/dist/astro.d.ts.map +1 -0
  13. package/dist/astro.js +24 -0
  14. package/dist/astro.js.map +1 -0
  15. package/dist/bun.d.ts +12 -0
  16. package/dist/bun.d.ts.map +1 -0
  17. package/dist/bun.js +67 -0
  18. package/dist/bun.js.map +1 -0
  19. package/dist/client/index.d.ts +95 -0
  20. package/dist/client/index.d.ts.map +1 -0
  21. package/dist/client/index.js +1333 -0
  22. package/dist/client/index.js.map +1 -0
  23. package/dist/index.d.ts +23 -0
  24. package/dist/index.js +10 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/loader.d.ts +15 -0
  27. package/dist/loader.d.ts.map +1 -0
  28. package/dist/loader.js +17 -0
  29. package/dist/loader.js.map +1 -0
  30. package/dist/next.d.ts +17 -0
  31. package/dist/next.d.ts.map +1 -0
  32. package/dist/next.js +150 -0
  33. package/dist/next.js.map +1 -0
  34. package/dist/recommended/index.d.ts +25 -0
  35. package/dist/recommended/index.d.ts.map +1 -0
  36. package/dist/recommended/index.js +19 -0
  37. package/dist/recommended/index.js.map +1 -0
  38. package/dist/recordings/client.d.ts +4 -0
  39. package/dist/recordings/client.d.ts.map +1 -0
  40. package/dist/recordings/client.js +376 -0
  41. package/dist/recordings/client.js.map +1 -0
  42. package/dist/recordings/index.d.ts +2 -0
  43. package/dist/recordings/index.js +3 -0
  44. package/dist/screenshots/client.d.ts +23 -0
  45. package/dist/screenshots/client.d.ts.map +1 -0
  46. package/dist/screenshots/client.js +76 -0
  47. package/dist/screenshots/client.js.map +1 -0
  48. package/dist/screenshots/dom.d.ts +4 -0
  49. package/dist/screenshots/dom.d.ts.map +1 -0
  50. package/dist/screenshots/dom.js +92 -0
  51. package/dist/screenshots/dom.js.map +1 -0
  52. package/dist/screenshots/index.d.ts +2 -0
  53. package/dist/screenshots/index.js +98 -0
  54. package/dist/screenshots/index.js.map +1 -0
  55. package/dist/screenshots/rrweb.d.ts +9 -0
  56. package/dist/screenshots/rrweb.d.ts.map +1 -0
  57. package/dist/screenshots/rrweb.js +60 -0
  58. package/dist/screenshots/rrweb.js.map +1 -0
  59. package/dist/shared/endpoints.js +354 -0
  60. package/dist/shared/endpoints.js.map +1 -0
  61. package/dist/shared/index.d.ts +226 -0
  62. package/dist/shared/index.d.ts.map +1 -0
  63. package/dist/shared/index2.d.ts +98 -0
  64. package/dist/shared/index2.d.ts.map +1 -0
  65. package/dist/shared/index3.d.ts +86 -0
  66. package/dist/shared/index3.d.ts.map +1 -0
  67. package/dist/shared/index4.d.ts +184 -0
  68. package/dist/shared/index4.d.ts.map +1 -0
  69. package/dist/shared/index5.d.ts +70 -0
  70. package/dist/shared/index5.d.ts.map +1 -0
  71. package/dist/shared/integration.d.ts +20 -0
  72. package/dist/shared/integration.d.ts.map +1 -0
  73. package/dist/shared/integration.js +279 -0
  74. package/dist/shared/integration.js.map +1 -0
  75. package/dist/shared/kept.js +23 -0
  76. package/dist/shared/kept.js.map +1 -0
  77. package/dist/shared/marks.js +14 -0
  78. package/dist/shared/marks.js.map +1 -0
  79. package/dist/shared/playwright.js +105 -0
  80. package/dist/shared/playwright.js.map +1 -0
  81. package/dist/shared/recordings.js +246 -0
  82. package/dist/shared/recordings.js.map +1 -0
  83. package/dist/shared/shortcut.js +63 -0
  84. package/dist/shared/shortcut.js.map +1 -0
  85. package/dist/shared/tasks.js +521 -0
  86. package/dist/shared/tasks.js.map +1 -0
  87. package/dist/shared/waveform.js +93 -0
  88. package/dist/shared/waveform.js.map +1 -0
  89. package/dist/tailwind/client.d.ts +4 -0
  90. package/dist/tailwind/client.d.ts.map +1 -0
  91. package/dist/tailwind/client.js +613 -0
  92. package/dist/tailwind/client.js.map +1 -0
  93. package/dist/tailwind/index.d.ts +2 -0
  94. package/dist/tailwind/index.js +557 -0
  95. package/dist/tailwind/index.js.map +1 -0
  96. package/dist/tasks/client.d.ts +6 -0
  97. package/dist/tasks/client.d.ts.map +1 -0
  98. package/dist/tasks/client.js +642 -0
  99. package/dist/tasks/client.js.map +1 -0
  100. package/dist/tasks/index.d.ts +2 -0
  101. package/dist/tasks/index.js +1 -0
  102. package/dist/vite.d.ts +16 -0
  103. package/dist/vite.d.ts.map +1 -0
  104. package/dist/vite.js +61 -0
  105. package/dist/vite.js.map +1 -0
  106. package/dist/voice/client.d.ts +4 -0
  107. package/dist/voice/client.d.ts.map +1 -0
  108. package/dist/voice/client.js +66 -0
  109. package/dist/voice/client.js.map +1 -0
  110. package/dist/voice/index.d.ts +47 -0
  111. package/dist/voice/index.d.ts.map +1 -0
  112. package/dist/voice/index.js +74 -0
  113. package/dist/voice/index.js.map +1 -0
  114. package/dist/webpack.d.ts +50 -0
  115. package/dist/webpack.d.ts.map +1 -0
  116. package/dist/webpack.js +78 -0
  117. package/dist/webpack.js.map +1 -0
  118. package/package.json +307 -7
  119. package/skills/deictic/SKILL.md +47 -0
  120. package/skills/deictic/references/install.md +96 -0
  121. package/skills/deictic/references/recordings.md +83 -0
  122. package/skills/deictic/references/tasks.md +79 -0
  123. package/skills/deictic/references/watch.md +43 -0
  124. package/skills/deictic/scripts/frame.mjs +62 -0
  125. package/skills/deictic/scripts/lib.mjs +211 -0
  126. package/skills/deictic/scripts/recording.mjs +186 -0
  127. package/skills/deictic/scripts/task.mjs +84 -0
  128. package/skills/deictic/scripts/transcribe.mjs +93 -0
  129. package/skills/deictic/scripts/voice.mjs +50 -0
  130. package/skills/deictic/scripts/watch.mjs +51 -0
  131. package/src/astro.ts +34 -0
  132. package/src/bun.ts +79 -0
  133. package/src/client/index.ts +846 -0
  134. package/src/client/lightbox.ts +256 -0
  135. package/src/client/style.ts +243 -0
  136. package/src/client/tooltip.ts +78 -0
  137. package/src/client/waveform.ts +98 -0
  138. package/src/index.ts +247 -0
  139. package/src/loader.ts +28 -0
  140. package/src/next.ts +133 -0
  141. package/src/plugins/annotations/client.ts +301 -0
  142. package/src/plugins/annotations/draw.ts +169 -0
  143. package/src/plugins/annotations/index.ts +105 -0
  144. package/src/plugins/annotations/svg.ts +61 -0
  145. package/src/plugins/recommended/index.ts +35 -0
  146. package/src/plugins/recordings/client.ts +316 -0
  147. package/src/plugins/recordings/index.ts +175 -0
  148. package/src/plugins/recordings/marks.ts +11 -0
  149. package/src/plugins/recordings/ours.ts +70 -0
  150. package/src/plugins/recordings/replay.ts +165 -0
  151. package/src/plugins/screenshots/client.ts +64 -0
  152. package/src/plugins/screenshots/dom.ts +79 -0
  153. package/src/plugins/screenshots/index.ts +194 -0
  154. package/src/plugins/screenshots/playwright.ts +119 -0
  155. package/src/plugins/screenshots/rrweb.ts +45 -0
  156. package/src/plugins/tailwind/catalog.ts +396 -0
  157. package/src/plugins/tailwind/client.ts +669 -0
  158. package/src/plugins/tailwind/index.ts +267 -0
  159. package/src/plugins/tasks/client.ts +622 -0
  160. package/src/plugins/tasks/index.ts +557 -0
  161. package/src/plugins/tasks/local.ts +170 -0
  162. package/src/plugins/voice/client.ts +58 -0
  163. package/src/plugins/voice/index.ts +114 -0
  164. package/src/shortcut.ts +83 -0
  165. package/src/tools/astro.ts +81 -0
  166. package/src/tools/editor.ts +22 -0
  167. package/src/tools/endpoints.ts +163 -0
  168. package/src/tools/history.ts +203 -0
  169. package/src/tools/integration.ts +108 -0
  170. package/src/tools/kept.ts +21 -0
  171. package/src/tools/locate.ts +94 -0
  172. package/src/tools/plugins.ts +41 -0
  173. package/src/tools/source.ts +72 -0
  174. package/src/vite.ts +81 -0
  175. package/src/webpack.ts +107 -0
  176. package/index.js +0 -1
@@ -0,0 +1,170 @@
1
+ /**
2
+ * The board tasks go to when nothing names one: `vb serve`, `@vercel/board`'s own, started with the dev server
3
+ * and stopped with it, its log in `.deictic/board`. So Alt-click adds a task with nothing else to run, and
4
+ * whoever works the tasks reaches the same board at the URL `.deictic/board.json` holds.
5
+ */
6
+ import { type ChildProcess, spawn } from 'node:child_process';
7
+ import { readFileSync, writeFileSync } from 'node:fs';
8
+ import { createRequire } from 'node:module';
9
+ import { createServer } from 'node:net';
10
+ import { dirname, join, resolve } from 'node:path';
11
+
12
+ import { keptIn } from '#src/tools/kept.ts';
13
+
14
+ /** `vb serve`'s own default, so `http://127.0.0.1:4100/api/board` is the board wherever it's free. */
15
+ const PORT = 4100;
16
+ /** How long a board may take to answer after it's started, or to be gone after it's stopped. */
17
+ const PATIENCE = 20_000;
18
+
19
+ export interface LocalOptions {
20
+ /**
21
+ * The port it listens on, on 127.0.0.1. By default 4100, or a free one where that's taken. One named here is
22
+ * the only one tried: taken, the board doesn't start.
23
+ */
24
+ port?: number;
25
+ /** Where its log is kept, from the project's root: `.deictic/board` by default. */
26
+ dir?: string;
27
+ /** `false` for no pages of the board's own (its inspector): the panel then links its tasks nowhere. */
28
+ inspect?: boolean;
29
+ /** More arguments for `vb serve`, as it takes them: `['--tailscale', 'box.tailnet.ts.net']`. */
30
+ args?: string[];
31
+ }
32
+
33
+ /** What `local()` answers, for the tasks plugin's `board` option. */
34
+ export interface LocalBoard {
35
+ local: LocalOptions;
36
+ }
37
+
38
+ /**
39
+ * The project's own board on this machine, as the tasks plugin's `board`: what it uses anyway with no
40
+ * `BOARD_URL`, here whatever the environment says, and with options.
41
+ */
42
+ export const local = (options: LocalOptions = {}): LocalBoard => ({ local: options });
43
+
44
+ /** What `.deictic/board.json` holds: the board the dev server started, for whoever works its tasks. */
45
+ export interface Running {
46
+ url: string;
47
+ pid: number;
48
+ /** The options it was started with, as one string to compare: other ones need another board. */
49
+ as: string;
50
+ }
51
+
52
+ export interface Local {
53
+ url: string;
54
+ /** Whether this call started it, rather than found it running. */
55
+ fresh: boolean;
56
+ /** Where its log is. */
57
+ dir: string;
58
+ /** Stops the board, where this call started it: one found running is left to what started it. */
59
+ stop: () => void;
60
+ }
61
+
62
+ /**
63
+ * The project's own board, started unless it's running: a dev server that restarts in its process (Vite, when
64
+ * its config changes) asks again, and so does a second dev server of the same project, and two boards mustn't
65
+ * write one log. One running with other options is stopped first, for the same reason.
66
+ */
67
+ export async function localBoard(root: string, options: LocalOptions = {}): Promise<Local> {
68
+ const file = keptIn(root, 'board.json');
69
+ const dir = options.dir === undefined ? keptIn(root, 'board') : resolve(root, options.dir);
70
+ const flags = [...(options.inspect === false ? ['--no-inspect'] : []), ...(options.args ?? [])];
71
+ const as = JSON.stringify([options.port ?? null, dir, flags]);
72
+
73
+ const running = read(file);
74
+ if (running !== undefined && alive(running.pid) && (await answers(running.url))) {
75
+ if (running.as === as) return { url: running.url, fresh: false, dir, stop: () => {} };
76
+ process.kill(running.pid);
77
+ await gone(running.url);
78
+ }
79
+
80
+ const port = options.port ?? (await free(PORT));
81
+ const url = `http://127.0.0.1:${port}/api/board`;
82
+ const child = spawn(process.execPath, [cli(), 'serve', '--port', String(port), '--no-open', '--dir', dir, ...flags], {
83
+ stdio: ['ignore', 'ignore', 'pipe'],
84
+ });
85
+ let said = '';
86
+ child.stderr.on('data', (chunk: Buffer) => (said += chunk.toString()));
87
+ const stop = () => void child.kill();
88
+ process.once('exit', stop);
89
+
90
+ try {
91
+ await started(child, url);
92
+ } catch (e) {
93
+ stop();
94
+ const fix = options.port === undefined ? 'set BOARD_URL to a board of your own' : `is port ${port} taken? name another, or none`;
95
+ throw new Error(`the board didn't start (${said.trim() || (e as Error).message}): ${fix}`, { cause: e });
96
+ }
97
+ writeFileSync(file, `${JSON.stringify({ url, pid: child.pid, as }, null, 2)}\n`);
98
+ // The board ends with this process, and mustn't be what keeps it from ending.
99
+ child.unref();
100
+ (child.stderr as { unref?: () => void }).unref?.();
101
+ return { url, fresh: true, dir, stop };
102
+ }
103
+
104
+ /** `vb`'s script in the project's `@vercel/board`, run with this process's own runtime: no shim, no shell. */
105
+ function cli(): string {
106
+ return join(dirname(createRequire(import.meta.url).resolve('@vercel/board/package.json')), 'dist', 'cli.mjs');
107
+ }
108
+
109
+ function read(file: string): Running | undefined {
110
+ try {
111
+ const { url, pid, as } = JSON.parse(readFileSync(file, 'utf8')) as Partial<Running>;
112
+ return typeof url === 'string' && typeof pid === 'number' ? { url, pid, as: as ?? '' } : undefined;
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
117
+
118
+ function alive(pid: number): boolean {
119
+ try {
120
+ process.kill(pid, 0);
121
+ return true;
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+
127
+ /** Whether a board answers there: its discovery, which names its own URL. */
128
+ async function answers(url: string): Promise<boolean> {
129
+ try {
130
+ const res = await fetch(url, { signal: AbortSignal.timeout(2000) });
131
+ return res.ok && ((await res.json()) as { url?: unknown }).url === url;
132
+ } catch {
133
+ return false;
134
+ }
135
+ }
136
+
137
+ /** `wanted` where nothing listens on it (another project's board may), or else a port the system picks. */
138
+ async function free(wanted: number): Promise<number> {
139
+ const listen = (port: number) =>
140
+ new Promise<number>((done, failed) => {
141
+ const server = createServer();
142
+ server.once('error', failed);
143
+ server.listen(port, '127.0.0.1', () => {
144
+ const { port: got } = server.address() as { port: number };
145
+ server.close(() => done(got));
146
+ });
147
+ });
148
+ return listen(wanted).catch(() => listen(0));
149
+ }
150
+
151
+ const nap = () => new Promise((wake) => setTimeout(wake, 100));
152
+
153
+ /** Waits for the board to answer, or for its process to end without having. */
154
+ async function started(child: ChildProcess, url: string): Promise<void> {
155
+ let ended: string | undefined;
156
+ child.once('error', (e) => (ended = e.message));
157
+ child.once('exit', (code) => (ended ??= `exit ${code}`));
158
+ for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) {
159
+ if (ended !== undefined) throw new Error(ended);
160
+ if (await answers(url)) return;
161
+ }
162
+ throw new Error(`no answer at ${url} after ${PATIENCE / 1000}s`);
163
+ }
164
+
165
+ /** Waits for a stopped board to let go of its port and its log. */
166
+ async function gone(url: string): Promise<void> {
167
+ for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) if (!(await answers(url))) return;
168
+
169
+ throw new Error(`the board at ${url} is still running: stop it, then restart the dev server`);
170
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * The voice plugin's page half: `start()` asks for the mic (the browser asks the user the first time) and
3
+ * records it with `MediaRecorder`. `stop` sends the take to the `add` route and lets the mic go, so the
4
+ * browser's recording light goes out between takes.
5
+ */
6
+ import { defineClientPlugin } from '#src/index.ts';
7
+
8
+ import type { Clip, Voice } from './index.ts';
9
+
10
+ /** What the browser can record, best first: Opus in WebM where it can (Chrome, Firefox), else MP4 (Safari). */
11
+ const TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];
12
+
13
+ export default defineClientPlugin<never, never, Voice>({
14
+ name: 'voice',
15
+ setup: ({ base, request }) => ({
16
+ start: async () => {
17
+ if (typeof MediaRecorder === 'undefined' || navigator.mediaDevices?.getUserMedia === undefined)
18
+ throw new Error("voice: this browser can't record the mic here: it needs a secure page (https or localhost)");
19
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((e: unknown) => {
20
+ throw new Error(`voice: the mic isn't available: ${e instanceof Error ? e.message : String(e)}`, { cause: e });
21
+ });
22
+ const mimeType = TYPES.find((t) => MediaRecorder.isTypeSupported(t));
23
+ const recorder = new MediaRecorder(stream, mimeType === undefined ? {} : { mimeType });
24
+ const chunks: Blob[] = [];
25
+ recorder.addEventListener('dataavailable', (e) => chunks.push(e.data));
26
+ const started = Date.now();
27
+ recorder.start();
28
+ const release = () => {
29
+ for (const track of stream.getTracks()) track.stop();
30
+ };
31
+ const ended = () =>
32
+ new Promise<void>((done) => {
33
+ if (recorder.state === 'inactive') return done();
34
+ recorder.addEventListener('stop', () => done(), { once: true });
35
+ recorder.stop();
36
+ });
37
+
38
+ return {
39
+ started,
40
+ stream,
41
+ cancel: () => {
42
+ void ended().then(release);
43
+ },
44
+ stop: async (): Promise<Clip> => {
45
+ await ended();
46
+ release();
47
+ const duration = Date.now() - started;
48
+ const type = (recorder.mimeType || mimeType || 'audio/webm').split(';')[0]!;
49
+ const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body: new Blob(chunks, { type }) });
50
+ // `url`: where the clip is, said by what keeps it with no server to serve it from (a `standalone` build).
51
+ const { id, url, problem } = (await res.json()) as { id?: string; url?: string; problem?: string };
52
+ if (id === undefined) throw new Error(`voice: ${problem ?? res.statusText}`);
53
+ return { id, url: url ?? `${base}__deictic/plugins/voice/clip/${id}`, duration, type };
54
+ },
55
+ };
56
+ },
57
+ }),
58
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * `deictic/voice`: records the mic, for other plugins to attach (tasks does) or play along with
3
+ * something (a recording does). No tab of its own. The page half asks for the mic the first time, records
4
+ * with `MediaRecorder` and sends each take to the `add` route; the server half keeps the latest `keep`
5
+ * clips under `.deictic/voice` and serves them at `clip/<id>`.
6
+ */
7
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { join, resolve } from 'node:path';
9
+
10
+ import { definePlugin } from '#src/index.ts';
11
+ import { keptIn } from '#src/tools/kept.ts';
12
+
13
+ /** A clip as the page knows it: its ID, where it plays from, how long it runs in milliseconds, and its type. */
14
+ export interface Clip {
15
+ id: string;
16
+ url: string;
17
+ duration: number;
18
+ type: string;
19
+ }
20
+
21
+ /** A take going on: `stop` ends it and keeps it, `cancel` ends it and keeps nothing. */
22
+ export interface Take {
23
+ /** When it started, as `Date.now()`. */
24
+ started: number;
25
+ /** The mic, while it's recorded: to show it's heard (`liveWaveform` from `deictic/client`). */
26
+ stream: MediaStream;
27
+ stop(): Promise<Clip>;
28
+ cancel(): void;
29
+ }
30
+
31
+ /** The page's half, for other plugins' page halves. */
32
+ export interface Voice {
33
+ /** Starts recording the mic, asking for it the first time: rejects when it's refused or there's none. */
34
+ start(): Promise<Take>;
35
+ }
36
+
37
+ /** The server's half, for other plugins' server halves. */
38
+ export interface Clips {
39
+ /** A clip's audio, or nothing for one not kept (any more). */
40
+ read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: string } | undefined;
41
+ }
42
+
43
+ declare module 'deictic' {
44
+ interface ServerApis {
45
+ voice: Clips;
46
+ }
47
+ interface ClientApis {
48
+ voice: Voice;
49
+ }
50
+ }
51
+
52
+ export interface VoiceOptions {
53
+ /** How many clips to keep, the latest: 50 by default. */
54
+ keep?: number;
55
+ /** Where they're kept, from the project's root: `.deictic/voice` by default. */
56
+ dir?: string;
57
+ }
58
+
59
+ const ID = /^[a-z0-9]+-[a-z0-9]+$/;
60
+ /** What one clip may weigh: minutes of speech in Opus are well under a MB. */
61
+ const MAX = 25 * 1024 * 1024;
62
+ /** The audio a browser's `MediaRecorder` makes, by the extension it's kept under. */
63
+ const TYPES: Record<string, string> = { webm: 'audio/webm', ogg: 'audio/ogg', mp4: 'audio/mp4' };
64
+
65
+ export function voice(options: VoiceOptions = {}) {
66
+ const keep = options.keep ?? 50;
67
+ let dir = '';
68
+ let taken = 0;
69
+ const fileOf = (id: string) => (ID.test(id) && existsSync(dir) ? readdirSync(dir).find((f) => f.startsWith(`${id}.`)) : undefined);
70
+ const read: Clips['read'] = (id) => {
71
+ const file = fileOf(id);
72
+ if (file === undefined) return undefined;
73
+ const ext = file.slice(id.length + 1);
74
+ return { data: new Uint8Array(readFileSync(join(dir, file))), name: `voice-${file}`, type: TYPES[ext] ?? 'application/octet-stream' };
75
+ };
76
+ const keepClip = (data: Uint8Array, ext: string) => {
77
+ // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.
78
+ const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;
79
+ mkdirSync(dir, { recursive: true });
80
+ writeFileSync(join(dir, `${id}.${ext}`), data);
81
+ const kept = readdirSync(dir).toSorted();
82
+ for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
83
+ return id;
84
+ };
85
+
86
+ return definePlugin<never, never, never, Clips>({
87
+ name: 'voice',
88
+ client: 'deictic/voice/client',
89
+ setup: ({ root }) => {
90
+ dir = options.dir === undefined ? keptIn(root, 'voice') : resolve(root, options.dir);
91
+ return { read };
92
+ },
93
+ routes: {
94
+ // A take the page recorded, as the audio type its `MediaRecorder` made.
95
+ add: async (req) => {
96
+ const type = (req.headers.get('content-type') ?? '').split(';')[0]!.trim();
97
+ const ext = Object.keys(TYPES).find((e) => TYPES[e] === type);
98
+ if (ext === undefined) return Response.json({ problem: `send the clip as ${Object.values(TYPES).join(', ')}` }, { status: 415 });
99
+ const body = new Uint8Array(await req.arrayBuffer());
100
+ if (body.byteLength === 0) return Response.json({ problem: 'the clip is empty: speak for a moment longer' }, { status: 400 });
101
+ if (body.byteLength > MAX) return Response.json({ problem: `a clip may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
102
+ return Response.json({ id: keepClip(body, ext) });
103
+ },
104
+ // `clip/<id>`: the audio, to play back.
105
+ clip: (req) => {
106
+ const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');
107
+ if (found === undefined) return new Response('no such clip, or not kept any more', { status: 404 });
108
+ return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });
109
+ },
110
+ },
111
+ });
112
+ }
113
+
114
+ export default voice;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * A gesture: the keys held to outline the element under the pointer, and the button that, with them
3
+ * held, opens the popup there. deictic's own (`MASTER` by default) opens the tab used last; a
4
+ * plugin's, which it takes as its `shortcut` option and has none by default, opens its tab. The
5
+ * bundler's plugin checks them all as it starts, so a wrong one, or two alike, fails the dev server,
6
+ * not the page. Both halves import it: it must
7
+ * stay dependency-free.
8
+ */
9
+
10
+ /** A modifier key, as `KeyboardEvent.key` names it. */
11
+ export type Modifier = 'Alt' | 'Control' | 'Meta' | 'Shift';
12
+
13
+ export interface Shortcut {
14
+ /** Held, and no other, to outline elements. */
15
+ modifiers?: Modifier[];
16
+ /** Pressed with them to open the panel. `'left'` unset. */
17
+ button?: 'left' | 'middle' | 'right';
18
+ }
19
+
20
+ const FLAGS = { Alt: 'altKey', Control: 'ctrlKey', Meta: 'metaKey', Shift: 'shiftKey' } as const;
21
+ const BUTTONS = { left: 0, middle: 1, right: 2 } as const;
22
+
23
+ /** deictic's own shortcut, unless `deictic({ shortcut })` names another or `false`. */
24
+ export const MASTER: Required<Shortcut> = { modifiers: ['Alt'], button: 'left' };
25
+
26
+ /** The name deictic's own shortcut goes by in a problem. */
27
+ export const OWN = 'deictic';
28
+
29
+ /** deictic's own shortcut as given, with its default, before it's checked. */
30
+ export const ownShortcut = (given: Shortcut | false | undefined) => (given === false ? undefined : (given ?? MASTER));
31
+
32
+ /** The shortcut with its button's default and its modifiers in one order, or an error saying what to write instead. */
33
+ export function checkShortcut(plugin: string, shortcut: Shortcut): Required<Shortcut> {
34
+ const { modifiers = [], button = 'left' } = shortcut;
35
+ const named = Object.keys(FLAGS).join("', '");
36
+ if (!Array.isArray(modifiers) || modifiers.length === 0) {
37
+ throw new Error(
38
+ `deictic: ${plugin}'s shortcut.modifiers is empty: hold at least one of '${named}', or every click would open the popup`,
39
+ );
40
+ }
41
+ for (const m of modifiers)
42
+ if (!Object.hasOwn(FLAGS, m)) throw new Error(`deictic: ${plugin}'s shortcut.modifiers has '${m}': name one of '${named}'`);
43
+
44
+ if (!Object.hasOwn(BUTTONS, button))
45
+ throw new Error(`deictic: ${plugin}'s shortcut.button is '${button}': name one of '${Object.keys(BUTTONS).join("', '")}'`);
46
+
47
+ const order = Object.keys(FLAGS);
48
+ return { modifiers: [...new Set(modifiers)].toSorted((a, b) => order.indexOf(a) - order.indexOf(b)), button };
49
+ }
50
+
51
+ /**
52
+ * Each shortcut checked, in order, or nothing where there's none: none may be another's, or only the
53
+ * first would ever open. deictic's own goes first, named `OWN`.
54
+ */
55
+ export function checkShortcuts(plugins: readonly { name: string; shortcut?: Shortcut }[]): (Required<Shortcut> | undefined)[] {
56
+ const taken = new Map<string, string>();
57
+ return plugins.map(({ name, shortcut }) => {
58
+ if (shortcut === undefined) return undefined;
59
+ const checked = checkShortcut(name, shortcut);
60
+ const key = nameOf(checked);
61
+ const other = taken.get(key);
62
+ if (other !== undefined) throw new Error(`deictic: ${name} and ${other} both open on ${key}: give one of them another \`shortcut\``);
63
+ taken.set(key, name);
64
+ return checked;
65
+ });
66
+ }
67
+
68
+ /** How a shortcut reads, for a problem or a label: `Alt+Shift`, `Control+right-click`. */
69
+ export const nameOf = ({ modifiers = [], button = 'left' }: Shortcut) =>
70
+ [...modifiers, ...(button === 'left' ? [] : [`${button}-click`])].join('+');
71
+
72
+ export interface Gesture {
73
+ /** Whether exactly the shortcut's modifiers are down: AltGr, which is Control and Alt, isn't Alt. */
74
+ held: (e: MouseEvent | KeyboardEvent) => boolean;
75
+ /** The shortcut's button, as `MouseEvent.button` numbers it. */
76
+ button: number;
77
+ }
78
+
79
+ export function gestureOf(shortcut: Required<Shortcut>): Gesture {
80
+ const on = new Set<string>(shortcut.modifiers);
81
+ const flags = Object.entries(FLAGS);
82
+ return { held: (e) => flags.every(([key, flag]) => e[flag] === on.has(key)), button: BUTTONS[shortcut.button] };
83
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `.astro` components. They aren't JSX modules, but Astro 7's own parser reads a template as JSX, into the
3
+ * tree oxc makes (offsets in UTF-16, as ours are), so its host elements are marked as a JSX module's are,
4
+ * before Astro compiles the file. The parser is the project's own Astro's (`@astrojs/compiler-rs`, found
5
+ * through `astro`), so it reads a file exactly as the compiler will; an Astro before 7 has none like it,
6
+ * and its `.astro` files are left unmarked.
7
+ */
8
+ import { createRequire } from 'node:module';
9
+ import { join } from 'node:path';
10
+
11
+ import type { JSXOpeningElement, Program } from 'oxc-parser';
12
+
13
+ import { type Located, marked } from './locate.ts';
14
+
15
+ export const ASTRO = /\.astro$/;
16
+
17
+ /** A file parsed: its module (an `.astro` file's frontmatter), and each opening tag in it, in the file's order. */
18
+ export interface Parsed {
19
+ program: Program;
20
+ elements: JSXOpeningElement[];
21
+ }
22
+
23
+ interface Tree {
24
+ ast: { frontmatter: { program: Program }; body: unknown };
25
+ diagnostics: { severity: string; text: string }[];
26
+ }
27
+ type Parse = (code: string) => Tree;
28
+
29
+ const parsers = new Map<string, Parse | undefined>();
30
+
31
+ /** The parser of the Astro installed for the project at `root`, loaded once; nothing without Astro 7. */
32
+ function parserOf(root: string): Parse | undefined {
33
+ if (!parsers.has(root)) parsers.set(root, load(root));
34
+ return parsers.get(root);
35
+ }
36
+
37
+ function load(root: string): Parse | undefined {
38
+ try {
39
+ // Astro's own dependency, which a strict package manager doesn't put where the project could import it.
40
+ const astro = createRequire(createRequire(join(root, 'package.json')).resolve('astro/package.json'));
41
+ // An ES module, required: every Node that runs Astro 7 can, and reading a source stays synchronous.
42
+ const compiler: { parse?: Parse } = astro('@astrojs/compiler-rs');
43
+ return compiler.parse;
44
+ } catch {
45
+ return undefined;
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Astro gives a `<script>` or `<style>` with an attribute it doesn't know to the page as it is, unbundled and
51
+ * unscoped, and a `<slot>` isn't an element at all: none of them can be pointed at, so none is marked.
52
+ */
53
+ const OWN = new Set(['script', 'style', 'slot']);
54
+
55
+ const isOpening = (node: object): node is JSXOpeningElement => 'type' in node && node.type === 'JSXOpeningElement';
56
+
57
+ /** An `.astro` file's text parsed, or the `problem` with it: no parser (an older Astro), or text that doesn't parse. */
58
+ export function parseAstro(root: string, code: string): Parsed | { problem: string } {
59
+ const parse = parserOf(root);
60
+ if (parse === undefined) return { problem: 'reading an .astro file takes Astro 7 or later, so update astro' };
61
+ const { ast, diagnostics } = parse(code);
62
+ const error = diagnostics.find((d) => d.severity === 'error');
63
+ if (error !== undefined) return { problem: `fix it first (${error.text})` };
64
+ const elements: JSXOpeningElement[] = [];
65
+ const walk = (node: unknown): void => {
66
+ if (Array.isArray(node)) return node.forEach(walk);
67
+ if (node === null || typeof node !== 'object') return;
68
+ if (isOpening(node) && !(node.name.type === 'JSXIdentifier' && OWN.has(node.name.name))) elements.push(node);
69
+ Object.values(node).forEach(walk);
70
+ };
71
+ walk(ast.body);
72
+ return { program: ast.frontmatter.program, elements };
73
+ }
74
+
75
+ /** An `.astro` file's text with every host element marked, as `locate` marks a JSX module; nothing where it can't be read. */
76
+ export function locateAstro(code: string, file: string, root: string): Located | undefined {
77
+ // No tag, no parse.
78
+ if (!/<[a-z]/.test(code)) return undefined;
79
+ const parsed = parseAstro(root, code);
80
+ return 'problem' in parsed ? undefined : marked(code, file, parsed.elements);
81
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Opens a place in the editor, for a dev server without a launcher of its own (webpack's, Rspack's):
3
+ * `launch-editor`, which Vite's own launcher uses, finds the editor that's running or the one `EDITOR`
4
+ * names. An optional peer, imported when first asked.
5
+ */
6
+
7
+ import type { Loc } from '#src/index.ts';
8
+
9
+ export async function openInEditor(path: string, { line, column }: Loc): Promise<Response> {
10
+ const launcher = await import('launch-editor').catch(() => undefined);
11
+ if (launcher === undefined)
12
+ return new Response('deictic opens files with launch-editor here: add it to your devDependencies', { status: 501 });
13
+ return new Promise((done) => {
14
+ let failed = false;
15
+ launcher.default(`${path}:${line}:${column}`, (_, message) => {
16
+ failed = true;
17
+ done(new Response(`${message ?? "the editor didn't open"}: set EDITOR to your editor's command`, { status: 500 }));
18
+ });
19
+ // launch-editor reports a failure as it happens, and nothing on success.
20
+ setTimeout(() => failed || done(new Response(null, { status: 204 })), 50);
21
+ });
22
+ }