deictic 0.0.1 → 0.1.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 -0
- package/README.md +144 -0
- package/dist/annotations/client.d.ts +4 -0
- package/dist/annotations/client.d.ts.map +1 -0
- package/dist/annotations/client.js +497 -0
- package/dist/annotations/client.js.map +1 -0
- package/dist/annotations/index.d.ts +110 -0
- package/dist/annotations/index.d.ts.map +1 -0
- package/dist/annotations/index.js +22 -0
- package/dist/annotations/index.js.map +1 -0
- package/dist/astro.d.ts +29 -0
- package/dist/astro.d.ts.map +1 -0
- package/dist/astro.js +24 -0
- package/dist/astro.js.map +1 -0
- package/dist/bun.d.ts +12 -0
- package/dist/bun.d.ts.map +1 -0
- package/dist/bun.js +67 -0
- package/dist/bun.js.map +1 -0
- package/dist/client/index.d.ts +93 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +1329 -0
- package/dist/client/index.js.map +1 -0
- package/dist/endpoints.js +354 -0
- package/dist/endpoints.js.map +1 -0
- package/dist/index.d.ts +220 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +10 -0
- package/dist/index.js.map +1 -0
- package/dist/index2.d.ts +23 -0
- package/dist/index3.d.ts +98 -0
- package/dist/index3.d.ts.map +1 -0
- package/dist/index4.d.ts +74 -0
- package/dist/index4.d.ts.map +1 -0
- package/dist/index5.d.ts +70 -0
- package/dist/index5.d.ts.map +1 -0
- package/dist/integration.d.ts +19 -0
- package/dist/integration.d.ts.map +1 -0
- package/dist/integration.js +277 -0
- package/dist/integration.js.map +1 -0
- package/dist/kept.js +23 -0
- package/dist/kept.js.map +1 -0
- package/dist/loader.d.ts +15 -0
- package/dist/loader.d.ts.map +1 -0
- package/dist/loader.js +17 -0
- package/dist/loader.js.map +1 -0
- package/dist/marks.js +14 -0
- package/dist/marks.js.map +1 -0
- package/dist/next.d.ts +17 -0
- package/dist/next.d.ts.map +1 -0
- package/dist/next.js +150 -0
- package/dist/next.js.map +1 -0
- package/dist/playwright.js +105 -0
- package/dist/playwright.js.map +1 -0
- package/dist/recommended/index.d.ts +25 -0
- package/dist/recommended/index.d.ts.map +1 -0
- package/dist/recommended/index.js +19 -0
- package/dist/recommended/index.js.map +1 -0
- package/dist/recordings/client.d.ts +4 -0
- package/dist/recordings/client.d.ts.map +1 -0
- package/dist/recordings/client.js +376 -0
- package/dist/recordings/client.js.map +1 -0
- package/dist/recordings/index.d.ts +2 -0
- package/dist/recordings/index.js +3 -0
- package/dist/recordings.js +235 -0
- package/dist/recordings.js.map +1 -0
- package/dist/screenshots/client.d.ts +23 -0
- package/dist/screenshots/client.d.ts.map +1 -0
- package/dist/screenshots/client.js +76 -0
- package/dist/screenshots/client.js.map +1 -0
- package/dist/screenshots/dom.d.ts +4 -0
- package/dist/screenshots/dom.d.ts.map +1 -0
- package/dist/screenshots/dom.js +92 -0
- package/dist/screenshots/dom.js.map +1 -0
- package/dist/screenshots/index.d.ts +2 -0
- package/dist/screenshots/index.js +98 -0
- package/dist/screenshots/index.js.map +1 -0
- package/dist/screenshots/rrweb.d.ts +9 -0
- package/dist/screenshots/rrweb.d.ts.map +1 -0
- package/dist/screenshots/rrweb.js +60 -0
- package/dist/screenshots/rrweb.js.map +1 -0
- package/dist/shortcut.js +63 -0
- package/dist/shortcut.js.map +1 -0
- package/dist/tailwind/client.d.ts +4 -0
- package/dist/tailwind/client.d.ts.map +1 -0
- package/dist/tailwind/client.js +613 -0
- package/dist/tailwind/client.js.map +1 -0
- package/dist/tailwind/index.d.ts +2 -0
- package/dist/tailwind/index.js +557 -0
- package/dist/tailwind/index.js.map +1 -0
- package/dist/tasks/client.d.ts +6 -0
- package/dist/tasks/client.d.ts.map +1 -0
- package/dist/tasks/client.js +642 -0
- package/dist/tasks/client.js.map +1 -0
- package/dist/tasks/index.d.ts +159 -0
- package/dist/tasks/index.d.ts.map +1 -0
- package/dist/tasks/index.js +348 -0
- package/dist/tasks/index.js.map +1 -0
- package/dist/vite.d.ts +17 -0
- package/dist/vite.d.ts.map +1 -0
- package/dist/vite.js +44 -0
- package/dist/vite.js.map +1 -0
- package/dist/voice/client.d.ts +4 -0
- package/dist/voice/client.d.ts.map +1 -0
- package/dist/voice/client.js +66 -0
- package/dist/voice/client.js.map +1 -0
- package/dist/voice/index.d.ts +47 -0
- package/dist/voice/index.d.ts.map +1 -0
- package/dist/voice/index.js +74 -0
- package/dist/voice/index.js.map +1 -0
- package/dist/waveform.js +93 -0
- package/dist/waveform.js.map +1 -0
- package/dist/webpack.d.ts +50 -0
- package/dist/webpack.d.ts.map +1 -0
- package/dist/webpack.js +78 -0
- package/dist/webpack.js.map +1 -0
- package/package.json +307 -7
- package/skills/deictic/SKILL.md +47 -0
- package/skills/deictic/references/install.md +81 -0
- package/skills/deictic/references/recordings.md +83 -0
- package/skills/deictic/references/tasks.md +79 -0
- package/skills/deictic/references/watch.md +43 -0
- package/skills/deictic/scripts/frame.mjs +62 -0
- package/skills/deictic/scripts/lib.mjs +193 -0
- package/skills/deictic/scripts/recording.mjs +186 -0
- package/skills/deictic/scripts/task.mjs +84 -0
- package/skills/deictic/scripts/transcribe.mjs +93 -0
- package/skills/deictic/scripts/voice.mjs +50 -0
- package/skills/deictic/scripts/watch.mjs +51 -0
- package/src/astro.ts +34 -0
- package/src/bun.ts +79 -0
- package/src/client/index.ts +833 -0
- package/src/client/lightbox.ts +256 -0
- package/src/client/style.ts +243 -0
- package/src/client/tooltip.ts +78 -0
- package/src/client/waveform.ts +98 -0
- package/src/index.ts +240 -0
- package/src/loader.ts +28 -0
- package/src/next.ts +133 -0
- package/src/plugins/annotations/client.ts +301 -0
- package/src/plugins/annotations/draw.ts +169 -0
- package/src/plugins/annotations/index.ts +105 -0
- package/src/plugins/annotations/svg.ts +61 -0
- package/src/plugins/recommended/index.ts +35 -0
- package/src/plugins/recordings/client.ts +315 -0
- package/src/plugins/recordings/index.ts +174 -0
- package/src/plugins/recordings/marks.ts +11 -0
- package/src/plugins/recordings/ours.ts +70 -0
- package/src/plugins/recordings/replay.ts +139 -0
- package/src/plugins/screenshots/client.ts +63 -0
- package/src/plugins/screenshots/dom.ts +79 -0
- package/src/plugins/screenshots/index.ts +194 -0
- package/src/plugins/screenshots/playwright.ts +119 -0
- package/src/plugins/screenshots/rrweb.ts +45 -0
- package/src/plugins/tailwind/catalog.ts +396 -0
- package/src/plugins/tailwind/client.ts +669 -0
- package/src/plugins/tailwind/index.ts +267 -0
- package/src/plugins/tasks/client.ts +622 -0
- package/src/plugins/tasks/index.ts +513 -0
- package/src/plugins/voice/client.ts +57 -0
- package/src/plugins/voice/index.ts +114 -0
- package/src/shortcut.ts +83 -0
- package/src/tools/astro.ts +81 -0
- package/src/tools/editor.ts +22 -0
- package/src/tools/endpoints.ts +163 -0
- package/src/tools/history.ts +203 -0
- package/src/tools/integration.ts +106 -0
- package/src/tools/kept.ts +21 -0
- package/src/tools/locate.ts +94 -0
- package/src/tools/plugins.ts +41 -0
- package/src/tools/source.ts +72 -0
- package/src/vite.ts +62 -0
- package/src/webpack.ts +107 -0
- package/index.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/plugins/tasks/index.ts"],"sourcesContent":["/**\n * `deictic/tasks`: open its tab on an element to add a task about it to a Vercel Board\n * (`@vercel/board`). The task says what to change, in the words typed, and where: the element's file,\n * line and tag, the page and the project, all as labels beside the short facts (viewport, how many, where\n * it is in the shot). Whatever works the board's tasks (a person, or an agent of theirs claiming them) takes it\n * from there; deictic only adds them.\n *\n * Adding one is a change like any other: undo cancels the task, while no one has claimed it, and redo\n * adds it again, as a new task. Each task carries `deictic.at=<file:line:column>`, so the panel\n * lists the ones about the element clicked, until its line moves.\n */\nimport { readFileSync } from 'node:fs';\nimport { join } from 'node:path';\n\nimport type { Board } from '@vercel/board';\n\nimport { definePlugin, Refusal, type ServerContext, type Shortcut, type Source, type Target } from '#src/index.ts';\n// For `use('screenshots')`'s type: the plugin may not be loaded, and nothing of it runs here.\nimport type { Recordings } from '#src/plugins/recordings/index.ts';\nimport type { Box } from '#src/plugins/screenshots/index.ts';\nimport type { Clips } from '#src/plugins/voice/index.ts';\n\n/** What the plugin uses of a board: `board()` from `@vercel/board` is one. */\nexport type TaskBoard = Pick<Board, 'tasks' | 'thread' | 'discovery' | 'upload' | 'edit'>;\n\nexport interface TasksOptions {\n /**\n * The board, as `@vercel/board`'s `board()` answers it: by default the one `BOARD_URL` names (`npx vb serve`\n * runs one on this machine), or your team's default board, through `vercel login`.\n */\n board?: TaskBoard;\n /** The channel tasks go to: `deictic` by default. */\n channel?: string;\n /**\n * The project the tasks are about, as the `deictic.project` label, to tell them apart on a board several\n * projects share: by default the `name` in the root's `package.json`, and no label where it has none.\n */\n project?: string;\n /** Labels every task gets besides deictic's own, for whoever works them to filter by (`vb tail --label`). None by default. */\n labels?: Record<string, string>;\n /**\n * Where the panel links the channel to, for a person to see its tasks, and with `task`, where it links\n * that task's ID to. By default the board's own pages when it's one `vb serve` runs on this machine\n * (`http://127.0.0.1:4100/c/deictic`, and `?thread=<id>` on it), and none for another board, whose pages\n * deictic can't know.\n */\n link?: (channel: string, task?: string) => string | undefined;\n /** What opens its tab directly, beside deictic's own shortcut, which opens any: none by default. */\n shortcut?: Shortcut;\n}\n\nexport interface Task {\n id: string;\n /** The first line of what was typed. */\n title: string;\n /** What was typed, whole: what an edit changes. */\n text: string;\n state: string;\n /** Whether it can still be edited or deleted: no one has claimed it. */\n open: boolean;\n /** Its page on the board, when there's one to link to. */\n link?: string;\n}\n\nexport interface Model {\n channel: string;\n /** The channel's page, when there's one to link to. */\n link?: string;\n /** Tasks about this element, oldest first, canceled ones left out. */\n tasks: Task[];\n}\n\n/**\n * What the Task tab asks for: a new task (an `Op`), other words for one it lists (`edit` is its ID), or\n * that one deleted (`remove` is its ID), which cancels it on the board.\n */\nexport type Change = Op | { edit: string; text: string } | { remove: string };\n\n/** A new task: what the page knows and the source doesn't. */\nexport interface Op {\n text: string;\n /** The page's URL. */\n page: string;\n viewport: { width: number; height: number };\n /**\n * What was under the pointer inside the element, where nothing marked it (a dependency's markup, or a\n * shadow root's): its path from the element, and its HTML, cut short.\n */\n pointed?: { path: string; html: string };\n /** How many elements on the page come from the same place in the source. */\n count: number;\n /**\n * Shots the screenshots plugin took of it, to attach, where that plugin is loaded: each with where the\n * element is in it, and the marks drawn on it in the panel, where there are any.\n */\n screenshots?: { id: string; box: Box; marks?: Marks }[];\n /**\n * Recordings the recordings plugin made, to attach, where that plugin is loaded: how long each ran,\n * where it plays back, and the voice plugin's clips of the mic in it, attached too.\n */\n recordings?: { id: string; duration: number; replay: string; voice?: string[] }[];\n /** Voice notes the voice plugin kept, to attach, where that plugin is loaded, and how long each runs. */\n voice?: { id: string; duration: number }[];\n /** The page's annotations, where that plugin is loaded and there are any: how many, and their notes' text. */\n annotations?: Marks;\n}\n\n/**\n * A task the Task tab just added, as the page hears of it: the `detail` of a `deictic:task` event on `window`, for a\n * page that shows its own tasks (deictic's playground lists them as a board does).\n */\nexport interface TaskAdded {\n id: string;\n /** The first line of what was typed. */\n title: string;\n state: string;\n channel: string;\n /** The element: its file, line and column, and its tag. */\n target: Target;\n /** The page's URL. */\n page: string;\n /** How many of each were attached; `marks` counts those drawn on shots and on the page. */\n attached: { screenshots: number; recordings: number; voice: number; marks: number };\n}\n\n/** Marks, as a task tells of them: how many, and what the notes among them say. */\nexport interface Marks {\n count: number;\n notes: string[];\n}\n\nexport interface Added {\n channel: string;\n id: string;\n text: string;\n labels: Record<string, string>;\n /** What's attached, by the board's IDs: kept, so a redo attaches the same without uploading it again. */\n attachments?: string[];\n}\n\n/** A task's words changed: its message's whole text before and after. */\nexport interface Edited {\n kind: 'edited';\n id: string;\n before: string;\n after: string;\n}\n\n/**\n * A task deleted in the panel: canceled on the board, for good, as a board has it. So it's kept whole, and\n * an undo adds it again, as a new task whose ID the record then has.\n */\nexport interface Removed extends Added {\n kind: 'removed';\n}\n\n/** What the history keeps of a change: a task added has no `kind`, as it had none before there were others. */\nexport type Kept = Added | Edited | Removed;\n\nconst AT = 'deictic.at';\n/** What parts what was typed from the rest of a task's text. */\nconst REST = '\\n---\\n';\nconst OPEN = new Set(['waiting', 'ready', 'blocked']);\n\nexport function tasks(options: TasksOptions = {}) {\n const channel = options.channel ?? 'deictic';\n let team: Promise<TaskBoard> | undefined;\n // Loaded when first used, so a project that doesn't add this plugin needn't install the SDK.\n const boardOf = () => (team ??= options.board ? Promise.resolve(options.board) : import('@vercel/board').then((m) => m.board()));\n let link: Promise<string | undefined> | undefined;\n // Asked once, unless asking failed: no link is no reason to keep the panel from showing the tasks.\n const linkOf = () =>\n (link ??= (options.link ? Promise.resolve(options.link(channel)) : boardOf().then((b) => localPage(b, channel))).catch(() => {\n link = undefined;\n return undefined;\n }));\n /** A task's page: what `link` says, or its thread on the channel's own page on this machine. */\n const taskLink = (page: string | undefined, id: string) =>\n options.link ? options.link(channel, id) : page === undefined ? undefined : `${page}?thread=${encodeURIComponent(id)}`;\n /**\n * One of this channel's tasks about an element, while it's still open: the page names it by ID, so\n * nothing else on the board is its to change, nor a task someone has taken up.\n */\n const openTask = async (team: TaskBoard, id: string, verb: string) => {\n const { message } = await team.thread(id);\n if (message.channel !== channel || message.labels[AT] === undefined)\n throw new Refusal(`#${id} isn't a task of deictic's in #${channel}: reload the page for the ones that are`);\n\n const { task } = message;\n if (task !== undefined && !OPEN.has(task.state)) {\n throw new Refusal(\n `task ${id} is ${task.state}${task.claim ? ` by ${task.claim.actor}` : ''} now: ${verb} it on the board if you still mean to`,\n );\n }\n return message;\n };\n /** Cancels an open task of ours, and answers it as it was. */\n const cancel = async (id: string, reason: string) => {\n const team = await boardOf();\n const message = await openTask(team, id, 'cancel');\n await team.tasks.cancel(id, reason);\n return message;\n };\n /** Puts a task's text from one to the other, unless it reads as neither any more. */\n const rewrite = async (id: string, from: string, to: string) => {\n const team = await boardOf();\n const message = await openTask(team, id, 'edit');\n if (message.text === to) return;\n if (message.text !== from) throw new Refusal(`task ${id} has been edited since: change it on the board`);\n await team.edit(id, to, { revision: message.revision });\n };\n const create = async (record: Omit<Added, 'id'>): Promise<Added> => {\n const { task } = await (\n await boardOf()\n ).tasks.create(record.channel, {\n text: record.text,\n labels: record.labels,\n ...(record.attachments === undefined ? {} : { attachments: record.attachments }),\n });\n return { ...record, id: task.id };\n };\n\n // Kept from `setup`, to `use` another plugin when an op asks for it.\n let context: ServerContext | undefined;\n let project = options.project;\n /** The screenshots and recordings to attach, uploaded to the board, or nothing when there are none. */\n const attach = async (op: Op): Promise<string[] | undefined> => {\n // All read first, so one no longer kept uploads none.\n const files = [\n ...(op.screenshots ?? []).map(({ id }) => {\n const shot = context?.use('screenshots')?.read(id);\n if (shot === undefined) throw new Refusal(`screenshot ${id} isn't kept any more: take it again`);\n return shot;\n }),\n ...(op.recordings ?? []).map(({ id }) => {\n const recording: ReturnType<Recordings['read']> = context?.use('recordings')?.read(id);\n if (recording === undefined) throw new Refusal(`recording ${id} isn't kept any more: record it again`);\n return recording;\n }),\n ...[...(op.recordings ?? []).flatMap((r) => r.voice ?? []), ...(op.voice ?? []).map((v) => v.id)].map((id) => {\n const clip: ReturnType<Clips['read']> = context?.use('voice')?.read(id);\n if (clip === undefined) throw new Refusal(`voice clip ${id} isn't kept any more: record it again`);\n return clip;\n }),\n ];\n if (files.length === 0) return undefined;\n const team = await boardOf();\n return Promise.all(files.map(async (file) => (await team.upload(file)).id));\n };\n\n return definePlugin<Model, Change, Kept>({\n name: 'tasks',\n client: 'deictic/tasks/client',\n shortcut: options.shortcut,\n setup: (given) => {\n context = given;\n project ??= nameOf(given.root);\n },\n read: (_source, target) =>\n asked(async () => {\n const [{ tasks: found }, page] = await Promise.all([\n (await boardOf()).tasks.list({ channel, label: { [AT]: atOf(target) }, state: 'all' }),\n linkOf(),\n ]);\n return {\n channel,\n ...(page === undefined ? {} : { link: page }),\n tasks: found\n .map(({ message }) => {\n const text = message.text.split(REST, 1)[0]!;\n const state = message.task?.state ?? 'ready';\n const to = taskLink(page, message.id);\n return {\n id: message.id,\n title: text.split('\\n', 1)[0]!,\n text,\n state,\n open: OPEN.has(state),\n ...(to === undefined ? {} : { link: to }),\n };\n })\n .filter((t) => t.state !== 'canceled'),\n };\n }),\n apply: (source, target, op) => {\n if ('remove' in op) {\n return asked(async () => {\n const message = await cancel(op.remove, 'deleted in deictic');\n // The board's own labels (`board.task`) are its to set on the task an undo adds.\n const labels = Object.fromEntries(Object.entries(message.labels).filter(([key]) => !key.startsWith('board.')));\n const attachments = message.attachments.map((a) => a.id);\n const kept = { channel, id: op.remove, text: message.text, labels, ...(attachments.length === 0 ? {} : { attachments }) };\n return { done: { kind: 'removed' as const, ...kept } };\n });\n }\n // A new task may go without words where something attached says it; a task's words are never changed to none.\n if (op.text.trim() === '' && ('edit' in op || shown(op) === undefined)) throw new Refusal('say what should change first');\n if ('edit' in op) {\n return asked(async () => {\n const before = (await openTask(await boardOf(), op.edit, 'edit')).text;\n // What follows the words (what's attached, what was pointed at) stays as it was.\n const rest = before.includes(REST) ? before.slice(before.indexOf(REST)) : '';\n const after = clip(op.text.trim(), 10_000 - rest.length) + rest;\n await rewrite(op.edit, before, after);\n return { done: { kind: 'edited' as const, id: op.edit, before, after } };\n });\n }\n const labels = {\n ...options.labels,\n ...(project === undefined ? {} : { 'deictic.project': clip(project, LABEL) }),\n ...labelsOf(source, target, op),\n };\n return asked(async () => {\n const attachments = await attach(op);\n return {\n done: await create({ channel, text: textOf(op), labels, ...(attachments === undefined ? {} : { attachments }) }),\n };\n });\n },\n undo: (record) =>\n asked(async () => {\n if (!('kind' in record)) {\n await cancel(record.id, 'undone in deictic');\n return undefined;\n }\n if (record.kind === 'edited') {\n await rewrite(record.id, record.after, record.before);\n return undefined;\n }\n const { kind, id: _, ...task } = record;\n return { kind, ...(await create(task)) };\n }),\n redo: (record) =>\n asked(async () => {\n if (!('kind' in record)) {\n const { id: _, ...added } = record;\n return create(added);\n }\n if (record.kind === 'edited') {\n await rewrite(record.id, record.before, record.after);\n return record;\n }\n await cancel(record.id, 'deleted in deictic');\n return record;\n }),\n describe: (op, before) => {\n const named = (id: string) => `task \"${clip(before.tasks.find((t) => t.id === id)?.title ?? `#${id}`, 60)}\"`;\n if ('remove' in op) return `delete ${named(op.remove)}`;\n if ('edit' in op) return `edit ${named(op.edit)}`;\n return `task \"${clip(wordsOf(op).split('\\n', 1)[0]!, 60)}\"`;\n },\n });\n}\n\n/**\n * The channel's page on a board `vb serve` runs on this machine, which serves its pages beside its API:\n * `/api/board` there, `/c/<channel>` beside it. Nothing for any other board.\n */\nasync function localPage(team: TaskBoard, channel: string): Promise<string | undefined> {\n const url = new URL((await team.discovery()).url);\n if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname) || !url.pathname.endsWith('/api/board')) return undefined;\n return `${url.origin}${url.pathname.slice(0, -'/api/board'.length)}/c/${channel.split('/').map(encodeURIComponent).join('/')}`;\n}\n\nconst plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`;\nconst said = (notes: string[]) => (notes.length === 0 ? '' : `; the notes say: ${notes.map((n) => JSON.stringify(n)).join(', ')}`);\n\n/** What was marked on the page: how many marks, and what the notes say. */\nfunction annotated({ count, notes }: Marks, shots: number, recordings: number): string {\n const where = [\n ...(shots === 0 ? [] : [shots === 1 ? 'the screenshot' : 'the screenshots']),\n ...(recordings === 0 ? [] : [recordings === 1 ? 'the recording' : 'the recordings']),\n ];\n const drawn = where.length === 0 ? '' : `, drawn in ${where.join(' and ')}`;\n return `${plural(count, 'mark')} on the page${drawn}${said(notes)}`;\n}\n\n/** How long each recording ran, and where it plays back, while the dev server keeps it. */\nfunction recordingsOf(recordings: NonNullable<Op['recordings']>): string[] {\n return recordings.map(({ duration, replay, voice }, i) => {\n const name = recordings.length === 1 ? 'A recording' : `Recording ${i + 1}`;\n const spoken = voice === undefined || voice.length === 0 ? '' : `, with the voice (${voice.map((id) => `voice-${id}`).join(', ')})`;\n return `${name}, ${clock(duration)} long, attached as rrweb events${spoken}; it replays at ${replay}`;\n });\n}\n\n/** How long each voice note runs, and the attachment it's in. */\nfunction voicesOf(voice: NonNullable<Op['voice']>): string[] {\n return voice.map(({ id, duration }, i) => {\n const name = voice.length === 1 ? 'A voice note' : `Voice note ${i + 1}`;\n return `${name}, ${clock(duration)} long, attached as voice-${id}`;\n });\n}\n\nconst clock = (ms: number) => {\n const s = Math.round(ms / 1000);\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;\n};\n\n/**\n * What was drawn on each shot, and with several, where the element is in each: nothing marks it there. One\n * shot's place is the `deictic.position` and `deictic.size` labels, so a shot with no marks has no line.\n */\nfunction shotsOf(shots: NonNullable<Op['screenshots']>): string[] {\n const [only] = shots;\n if (shots.length === 1 && only !== undefined) {\n const { marks } = only;\n return marks === undefined || marks.count === 0\n ? []\n : [`The screenshot has ${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`];\n }\n return shots.map(({ box, marks }, i) => {\n const drawn = marks === undefined || marks.count === 0 ? '' : `, with ${plural(marks.count, 'mark')} drawn on it${said(marks.notes)}`;\n const [x, y, width, height] = boxOf(box);\n return `In screenshot ${i + 1} at x ${x}, y ${y}, ${width}×${height}${drawn}`;\n });\n}\n\n/** A box as `x,y,width,height`, in whole CSS pixels from the shot's top left. */\nconst boxOf = ({ x, y, width, height }: Box) => [x, y, width, height].map(Math.round);\n\n/** A label's value: a board holds 256 characters. */\nconst LABEL = 256;\n\n/** The project's name: the `name` in the root's `package.json`, or nothing where it has none. */\nfunction nameOf(root: string): string | undefined {\n try {\n const { name } = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: unknown };\n return typeof name === 'string' && name !== '' ? name : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The facts about the element, as labels: short values a script reads without parsing the text, and a watch\n * filters by. `deictic.line` is the opening tag's first line as the task saw it, to tell later that it moved.\n * `deictic.url` is the page's whole URL, where a label holds it: `textOf` says a longer one.\n */\nfunction labelsOf({ code, element }: Source, target: Target, op: Op): Record<string, string> {\n const [shot] = op.screenshots ?? [];\n return {\n [AT]: atOf(target),\n 'deictic.tag': target.tag,\n 'deictic.line': clip(code.slice(element.start, element.end).split('\\n', 1)[0]!.trim(), LABEL),\n 'deictic.page': clip(new URL(op.page).pathname, LABEL),\n ...(op.page.length <= LABEL ? { 'deictic.url': op.page } : {}),\n 'deictic.viewport': `${op.viewport.width}x${op.viewport.height}`,\n 'deictic.count': String(op.count),\n ...(op.screenshots?.length === 1 && shot !== undefined ? placeOf(shot.box) : {}),\n };\n}\n\n/** Where the element is in the one shot, from its top left, and how big: `87,387` and `138x32`, as the viewport is written. */\nfunction placeOf(box: Box): Record<string, string> {\n const [x, y, width, height] = boxOf(box);\n return { 'deictic.position': `${x},${y}`, 'deictic.size': `${width}x${height}` };\n}\n\nconst atOf = ({ loc }: Target) => `${loc.file}:${loc.line}:${loc.column}`;\n\n/**\n * The task's text: what was typed, and after a `---` only what no label holds: what's attached and drawn, what\n * was pointed at inside the element, and a URL too long for one. A board holds 10,000 characters.\n */\nfunction textOf(op: Op): string {\n const more = [\n ...(op.page.length <= LABEL ? [] : [op.page]),\n ...shotsOf(op.screenshots ?? []),\n ...recordingsOf(op.recordings ?? []),\n ...voicesOf(op.voice ?? []),\n ...(op.annotations === undefined ? [] : [annotated(op.annotations, op.screenshots?.length ?? 0, op.recordings?.length ?? 0)]),\n ...(op.pointed === undefined ? [] : [`Pointed at, inside it: \\`${op.pointed.path}\\``, fence(op.pointed.html, 'html')]),\n ];\n const tail = more.length === 0 ? '' : REST + more.join('\\n');\n return clip(wordsOf(op), 10_000 - tail.length) + tail;\n}\n\n/** The task's words: what was typed, or where nothing was, a line that sends the reader to what's attached. */\nconst wordsOf = (op: Op) => (op.text.trim() === '' ? (shown(op) ?? '') : op.text.trim());\n\n/** `See the recording and the voice note`: what stands for the words of a task sent with none, where something is attached. */\nfunction shown(op: Op): string | undefined {\n const named = (count: number | undefined, word: string) =>\n count === undefined || count === 0 ? [] : [`the ${word}${count === 1 ? '' : 's'}`];\n const attached = [\n ...named(op.screenshots?.length, 'screenshot'),\n ...named(op.recordings?.length, 'recording'),\n ...named(op.voice?.length, 'voice note'),\n ];\n return attached.length === 0 ? undefined : `See ${new Intl.ListFormat('en', { type: 'conjunction' }).format(attached)}`;\n}\n\nconst fence = (text: string, lang: string) => `\\`\\`\\`\\`${lang}\\n${clip(text, 1500)}\\n\\`\\`\\`\\``;\n\nconst clip = (text: string, max: number) => (text.length <= max ? text : `${text.slice(0, max - 1)}…`);\n\n/** The board's answer, or a `Refusal` saying what to do when there's no board to ask or it said no. */\nasync function asked<T>(ask: () => Promise<T>): Promise<T> {\n try {\n return await ask();\n } catch (e) {\n if (e instanceof Refusal) throw e;\n const { code, message, hint } = e as { code?: unknown; message?: string; hint?: string };\n if (typeof code === 'string') throw new Refusal(`the board says: ${message}${hint === undefined ? '' : ` (${hint})`}`, { cause: e });\n throw new Refusal(\n `can't reach the board (${message ?? String(e)}): run \\`npx vb serve\\` and set BOARD_URL for the dev server, or \\`vercel login\\``,\n { cause: e },\n );\n }\n}\n\nexport default tasks;\n"],"mappings":";;;;;;;;;;;;;;;AA+JA,MAAM,KAAK;;AAEX,MAAM,OAAO;AACb,MAAM,uBAAO,IAAI,IAAI;CAAC;CAAW;CAAS;AAAS,CAAC;AAEpD,SAAgB,MAAM,UAAwB,CAAC,GAAG;CAChD,MAAM,UAAU,QAAQ,WAAW;CACnC,IAAI;CAEJ,MAAM,gBAAiB,SAAS,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,KAAK,IAAI,OAAO,gBAAgB,CAAC,MAAM,MAAM,EAAE,MAAM,CAAC;CAC9H,IAAI;CAEJ,MAAM,eACH,UAAU,QAAQ,OAAO,QAAQ,QAAQ,QAAQ,KAAK,OAAO,CAAC,IAAI,QAAQ,CAAC,CAAC,MAAM,MAAM,UAAU,GAAG,OAAO,CAAC,EAAA,CAAG,YAAY;EAC3H,OAAO,KAAA;CAET,CAAC;;CAEH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4B;CACzC,MAAM,SAAS,OAA2B,SACxC,UAAU,KAAA,KAAa,UAAU,IAAI,CAAC,IAAI,CAAC,OAAO,OAAO,UAAU,IAAI,KAAK,KAAK;CACnF,MAAM,WAAW;EACf,GAAG,MAAM,GAAG,aAAa,QAAQ,YAAY;EAC7C,GAAG,MAAM,GAAG,YAAY,QAAQ,WAAW;EAC3C,GAAG,MAAM,GAAG,OAAO,QAAQ,YAAY;CACzC;CACA,OAAO,SAAS,WAAW,IAAI,KAAA,IAAY,OAAO,IAAI,KAAK,WAAW,MAAM,EAAE,MAAM,cAAc,CAAC,CAAC,CAAC,OAAO,QAAQ;AACtH;AAEA,MAAM,SAAS,MAAc,SAAiB,WAAW,KAAK,IAAI,KAAK,MAAM,IAAI,EAAE;AAEnF,MAAM,QAAQ,MAAc,QAAiB,KAAK,UAAU,MAAM,OAAO,GAAG,KAAK,MAAM,GAAG,MAAM,CAAC,EAAE;;AAGnG,eAAe,MAAS,KAAmC;CACzD,IAAI;EACF,OAAO,MAAM,IAAI;CACnB,SAAS,GAAG;EACV,IAAI,aAAa,SAAS,MAAM;EAChC,MAAM,EAAE,MAAM,SAAS,SAAS;EAChC,IAAI,OAAO,SAAS,UAAU,MAAM,IAAI,QAAQ,mBAAmB,UAAU,SAAS,KAAA,IAAY,KAAK,KAAK,KAAK,MAAM,EAAE,OAAO,EAAE,CAAC;EACnI,MAAM,IAAI,QACR,0BAA0B,WAAW,OAAO,CAAC,EAAE,oFAC/C,EAAE,OAAO,EAAE,CACb;CACF;AACF"}
|
package/dist/vite.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `deictic/vite`: deictic in Vite's dev server. Nothing runs in a build.
|
|
3
|
+
*
|
|
4
|
+
* Its transform runs `pre`, so each JSX module's host elements are marked with their place in the
|
|
5
|
+
* source as written (`tools/locate.ts`). In the browser each marked module also imports the client
|
|
6
|
+
* module, which starts the overlay with every plugin's panel: imports run first and only once, so no
|
|
7
|
+
* line moves and frameworks that render their own HTML get it too. The endpoints are middleware on
|
|
8
|
+
* Vite's server, and a place opens through Vite's own `/__open-in-editor`, so the editor is whichever
|
|
9
|
+
* Vite already launches. A write reaches the page through Vite's usual update for the file.
|
|
10
|
+
*/
|
|
11
|
+
import { Plugin } from "vite";
|
|
12
|
+
import { n as clientModule, t as DeicticOptions } from "./integration.js";
|
|
13
|
+
/** The client module's ID, which a page can import itself where nothing it bundles is JSX (Astro's pages). */
|
|
14
|
+
export declare const CLIENT = "virtual:deictic/client";
|
|
15
|
+
export declare function deictic(options?: DeicticOptions): Plugin;
|
|
16
|
+
export { type DeicticOptions, clientModule, deictic as default };
|
|
17
|
+
//# sourceMappingURL=vite.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.d.ts","names":[],"sources":["../src/vite.ts"],"mappings":";;;;;;;;;;;;;qBAkBa;wBAGG,QAAQ,UAAS,iBAAsB"}
|
package/dist/vite.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { n as nodeMiddleware, r as redirect, t as endpoints } from "./endpoints.js";
|
|
2
|
+
import { a as markAstro, i as mark, n as clientModule, o as prepare } from "./integration.js";
|
|
3
|
+
// src/vite.ts
|
|
4
|
+
/** The client module's ID, which a page can import itself where nothing it bundles is JSX (Astro's pages). */
|
|
5
|
+
const CLIENT = "virtual:deictic/client";
|
|
6
|
+
const CLIENT_ID = "\0deictic/client";
|
|
7
|
+
function deictic(options = {}) {
|
|
8
|
+
const { plugins, shortcut } = prepare(options);
|
|
9
|
+
let root = "";
|
|
10
|
+
let base = "/";
|
|
11
|
+
return {
|
|
12
|
+
name: "deictic",
|
|
13
|
+
enforce: "pre",
|
|
14
|
+
apply: "serve",
|
|
15
|
+
config: () => ({ optimizeDeps: { exclude: ["deictic"] } }),
|
|
16
|
+
configResolved(config) {
|
|
17
|
+
root = config.root;
|
|
18
|
+
base = config.base;
|
|
19
|
+
},
|
|
20
|
+
configureServer(server) {
|
|
21
|
+
const handle = endpoints({
|
|
22
|
+
root,
|
|
23
|
+
plugins,
|
|
24
|
+
base,
|
|
25
|
+
open: (path, { line, column }) => redirect(`${base}__open-in-editor?${new URLSearchParams({ file: `${path}:${line}:${column}` })}`)
|
|
26
|
+
});
|
|
27
|
+
server.middlewares.use(nodeMiddleware(handle));
|
|
28
|
+
},
|
|
29
|
+
resolveId: (id) => id === "virtual:deictic/client" ? CLIENT_ID : void 0,
|
|
30
|
+
load: (id) => id === CLIENT_ID ? clientModule(plugins, base, shortcut) : void 0,
|
|
31
|
+
transform: {
|
|
32
|
+
order: "pre",
|
|
33
|
+
handler(code, id) {
|
|
34
|
+
const [path = ""] = id.split("?");
|
|
35
|
+
if (path.endsWith(".astro")) return id === path ? markAstro(code, path, root) : void 0;
|
|
36
|
+
const browser = this.environment.config.consumer === "client";
|
|
37
|
+
return mark(code, path, root, browser ? `\nimport ${JSON.stringify(CLIENT)};\n` : "");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
export { CLIENT, clientModule, deictic as default, deictic };
|
|
43
|
+
|
|
44
|
+
//# sourceMappingURL=vite.js.map
|
package/dist/vite.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"vite.js","names":[],"sources":["../src/vite.ts"],"sourcesContent":["/**\n * `deictic/vite`: deictic in Vite's dev server. Nothing runs in a build.\n *\n * Its transform runs `pre`, so each JSX module's host elements are marked with their place in the\n * source as written (`tools/locate.ts`). In the browser each marked module also imports the client\n * module, which starts the overlay with every plugin's panel: imports run first and only once, so no\n * line moves and frameworks that render their own HTML get it too. The endpoints are middleware on\n * Vite's server, and a place opens through Vite's own `/__open-in-editor`, so the editor is whichever\n * Vite already launches. A write reaches the page through Vite's usual update for the file.\n */\nimport type { Plugin } from 'vite';\n\nimport { endpoints, nodeMiddleware, redirect } from './tools/endpoints.ts';\nimport { clientModule, type DeicticOptions, mark, markAstro, prepare } from './tools/integration.ts';\n\nexport { clientModule, type DeicticOptions };\n\n/** The client module's ID, which a page can import itself where nothing it bundles is JSX (Astro's pages). */\nexport const CLIENT = 'virtual:deictic/client';\nconst CLIENT_ID = '\\0deictic/client';\n\nexport function deictic(options: DeicticOptions = {}): Plugin {\n const { plugins, shortcut } = prepare(options);\n let root = '';\n let base = '/';\n return {\n name: 'deictic',\n enforce: 'pre',\n apply: 'serve',\n // The client is the app's to bundle as it changes, not a dependency to prebundle once.\n config: () => ({ optimizeDeps: { exclude: ['deictic'] } }),\n configResolved(config) {\n root = config.root;\n base = config.base;\n },\n configureServer(server) {\n const handle = endpoints({\n root,\n plugins,\n base,\n open: (path, { line, column }) => redirect(`${base}__open-in-editor?${new URLSearchParams({ file: `${path}:${line}:${column}` })}`),\n });\n server.middlewares.use(nodeMiddleware(handle));\n },\n resolveId: (id) => (id === CLIENT ? CLIENT_ID : undefined),\n load: (id) => (id === CLIENT_ID ? clientModule(plugins, base, shortcut) : undefined),\n transform: {\n // First of all, not only first of the `pre` plugins: the React Compiler (`react({ compiler: true })`) is\n // `pre` too and compiles the JSX away, so after it there'd be no element to mark, wherever deictic is listed.\n order: 'pre',\n handler(code, id) {\n const [path = ''] = id.split('?');\n // An `.astro` component itself, not the styles and scripts Astro loads from it by a query.\n if (path.endsWith('.astro')) return id === path ? markAstro(code, path, root) : undefined;\n const browser = this.environment.config.consumer === 'client';\n return mark(code, path, root, browser ? `\\nimport ${JSON.stringify(CLIENT)};\\n` : '');\n },\n },\n };\n}\n\nexport default deictic;\n"],"mappings":";;;;AAkBA,MAAa,SAAS;AACtB,MAAM,YAAY;AAElB,SAAgB,QAAQ,UAA0B,CAAC,GAAW;CAC5D,MAAM,EAAE,SAAS,aAAa,QAAQ,OAAO;CAC7C,IAAI,OAAO;CACX,IAAI,OAAO;CACX,OAAO;EACL,MAAM;EACN,SAAS;EACT,OAAO;EAEP,eAAe,EAAE,cAAc,EAAE,SAAS,CAAC,SAAS,EAAE,EAAE;EACxD,eAAe,QAAQ;GACrB,OAAO,OAAO;GACd,OAAO,OAAO;EAChB;EACA,gBAAgB,QAAQ;GACtB,MAAM,SAAS,UAAU;IACvB;IACA;IACA;IACA,OAAO,MAAM,EAAE,MAAM,aAAa,SAAS,GAAG,KAAK,mBAAmB,IAAI,gBAAgB,EAAE,MAAM,GAAG,KAAK,GAAG,KAAK,GAAG,SAAS,CAAC,GAAG;GACpI,CAAC;GACD,OAAO,YAAY,IAAI,eAAe,MAAM,CAAC;EAC/C;EACA,YAAY,OAAQ,OAAA,2BAAgB,YAAY,KAAA;EAChD,OAAO,OAAQ,OAAO,YAAY,aAAa,SAAS,MAAM,QAAQ,IAAI,KAAA;EAC1E,WAAW;GAGT,OAAO;GACP,QAAQ,MAAM,IAAI;IAChB,MAAM,CAAC,OAAO,MAAM,GAAG,MAAM,GAAG;IAEhC,IAAI,KAAK,SAAS,QAAQ,GAAG,OAAO,OAAO,OAAO,UAAU,MAAM,MAAM,IAAI,IAAI,KAAA;IAChF,MAAM,UAAU,KAAK,YAAY,OAAO,aAAa;IACrD,OAAO,KAAK,MAAM,MAAM,MAAM,UAAU,YAAY,KAAK,UAAU,MAAM,EAAE,OAAO,EAAE;GACtF;EACF;CACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","names":[],"sources":["../../src/plugins/voice/client.ts"],"mappings":";cAYA,4B"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { defineClientPlugin } from "../index.js";
|
|
2
|
+
// src/plugins/voice/client.ts
|
|
3
|
+
/**
|
|
4
|
+
* The voice plugin's page half: `start()` asks for the mic (the browser asks the user the first time) and
|
|
5
|
+
* records it with `MediaRecorder`. `stop` sends the take to the `add` route and lets the mic go, so the
|
|
6
|
+
* browser's recording light goes out between takes.
|
|
7
|
+
*/
|
|
8
|
+
/** What the browser can record, best first: Opus in WebM where it can (Chrome, Firefox), else MP4 (Safari). */
|
|
9
|
+
const TYPES = [
|
|
10
|
+
"audio/webm;codecs=opus",
|
|
11
|
+
"audio/webm",
|
|
12
|
+
"audio/ogg;codecs=opus",
|
|
13
|
+
"audio/mp4"
|
|
14
|
+
];
|
|
15
|
+
var client_default = defineClientPlugin({
|
|
16
|
+
name: "voice",
|
|
17
|
+
setup: ({ base, request }) => ({ start: async () => {
|
|
18
|
+
if (typeof MediaRecorder === "undefined" || navigator.mediaDevices?.getUserMedia === void 0) 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) => {
|
|
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 === void 0 ? {} : { mimeType });
|
|
24
|
+
const chunks = [];
|
|
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 = () => new Promise((done) => {
|
|
32
|
+
if (recorder.state === "inactive") return done();
|
|
33
|
+
recorder.addEventListener("stop", () => done(), { once: true });
|
|
34
|
+
recorder.stop();
|
|
35
|
+
});
|
|
36
|
+
return {
|
|
37
|
+
started,
|
|
38
|
+
stream,
|
|
39
|
+
cancel: () => {
|
|
40
|
+
ended().then(release);
|
|
41
|
+
},
|
|
42
|
+
stop: async () => {
|
|
43
|
+
await ended();
|
|
44
|
+
release();
|
|
45
|
+
const duration = Date.now() - started;
|
|
46
|
+
const type = (recorder.mimeType || mimeType || "audio/webm").split(";")[0];
|
|
47
|
+
const res = await request("add", {
|
|
48
|
+
method: "POST",
|
|
49
|
+
headers: { "content-type": type },
|
|
50
|
+
body: new Blob(chunks, { type })
|
|
51
|
+
});
|
|
52
|
+
const { id, problem } = await res.json();
|
|
53
|
+
if (id === void 0) throw new Error(`voice: ${problem ?? res.statusText}`);
|
|
54
|
+
return {
|
|
55
|
+
id,
|
|
56
|
+
url: `${base}__deictic/plugins/voice/clip/${id}`,
|
|
57
|
+
duration,
|
|
58
|
+
type
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
} })
|
|
63
|
+
});
|
|
64
|
+
export { client_default as default };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","names":[],"sources":["../../src/plugins/voice/client.ts"],"sourcesContent":["/**\n * The voice plugin's page half: `start()` asks for the mic (the browser asks the user the first time) and\n * records it with `MediaRecorder`. `stop` sends the take to the `add` route and lets the mic go, so the\n * browser's recording light goes out between takes.\n */\nimport { defineClientPlugin } from '#src/index.ts';\n\nimport type { Clip, Voice } from './index.ts';\n\n/** What the browser can record, best first: Opus in WebM where it can (Chrome, Firefox), else MP4 (Safari). */\nconst TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/ogg;codecs=opus', 'audio/mp4'];\n\nexport default defineClientPlugin<never, never, Voice>({\n name: 'voice',\n setup: ({ base, request }) => ({\n start: async () => {\n if (typeof MediaRecorder === 'undefined' || navigator.mediaDevices?.getUserMedia === undefined)\n throw new Error(\"voice: this browser can't record the mic here: it needs a secure page (https or localhost)\");\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((e: unknown) => {\n throw new Error(`voice: the mic isn't available: ${e instanceof Error ? e.message : String(e)}`, { cause: e });\n });\n const mimeType = TYPES.find((t) => MediaRecorder.isTypeSupported(t));\n const recorder = new MediaRecorder(stream, mimeType === undefined ? {} : { mimeType });\n const chunks: Blob[] = [];\n recorder.addEventListener('dataavailable', (e) => chunks.push(e.data));\n const started = Date.now();\n recorder.start();\n const release = () => {\n for (const track of stream.getTracks()) track.stop();\n };\n const ended = () =>\n new Promise<void>((done) => {\n if (recorder.state === 'inactive') return done();\n recorder.addEventListener('stop', () => done(), { once: true });\n recorder.stop();\n });\n\n return {\n started,\n stream,\n cancel: () => {\n void ended().then(release);\n },\n stop: async (): Promise<Clip> => {\n await ended();\n release();\n const duration = Date.now() - started;\n const type = (recorder.mimeType || mimeType || 'audio/webm').split(';')[0]!;\n const res = await request('add', { method: 'POST', headers: { 'content-type': type }, body: new Blob(chunks, { type }) });\n const { id, problem } = (await res.json()) as { id?: string; problem?: string };\n if (id === undefined) throw new Error(`voice: ${problem ?? res.statusText}`);\n return { id, url: `${base}__deictic/plugins/voice/clip/${id}`, duration, type };\n },\n };\n },\n }),\n});\n"],"mappings":";;;;;;;;AAUA,MAAM,QAAQ;CAAC;CAA0B;CAAc;CAAyB;AAAW;AAE3F,IAAA,iBAAe,mBAAwC;CACrD,MAAM;CACN,QAAQ,EAAE,MAAM,eAAe,EAC7B,OAAO,YAAY;EACjB,IAAI,OAAO,kBAAkB,eAAe,UAAU,cAAc,iBAAiB,KAAA,GACnF,MAAM,IAAI,MAAM,4FAA4F;EAC9G,MAAM,SAAS,MAAM,UAAU,aAAa,aAAa,EAAE,OAAO,KAAK,CAAC,CAAC,CAAC,OAAO,MAAe;GAC9F,MAAM,IAAI,MAAM,mCAAmC,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,KAAK,EAAE,OAAO,EAAE,CAAC;EAC/G,CAAC;EACD,MAAM,WAAW,MAAM,MAAM,MAAM,cAAc,gBAAgB,CAAC,CAAC;EACnE,MAAM,WAAW,IAAI,cAAc,QAAQ,aAAa,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,CAAC;EACrF,MAAM,SAAiB,CAAC;EACxB,SAAS,iBAAiB,kBAAkB,MAAM,OAAO,KAAK,EAAE,IAAI,CAAC;EACrE,MAAM,UAAU,KAAK,IAAI;EACzB,SAAS,MAAM;EACf,MAAM,gBAAgB;GACpB,KAAK,MAAM,SAAS,OAAO,UAAU,GAAG,MAAM,KAAK;EACrD;EACA,MAAM,cACJ,IAAI,SAAe,SAAS;GAC1B,IAAI,SAAS,UAAU,YAAY,OAAO,KAAK;GAC/C,SAAS,iBAAiB,cAAc,KAAK,GAAG,EAAE,MAAM,KAAK,CAAC;GAC9D,SAAS,KAAK;EAChB,CAAC;EAEH,OAAO;GACL;GACA;GACA,cAAc;IACP,MAAM,CAAC,CAAC,KAAK,OAAO;GAC3B;GACA,MAAM,YAA2B;IAC/B,MAAM,MAAM;IACZ,QAAQ;IACR,MAAM,WAAW,KAAK,IAAI,IAAI;IAC9B,MAAM,QAAQ,SAAS,YAAY,YAAY,aAAA,CAAc,MAAM,GAAG,CAAC,CAAC;IACxE,MAAM,MAAM,MAAM,QAAQ,OAAO;KAAE,QAAQ;KAAQ,SAAS,EAAE,gBAAgB,KAAK;KAAG,MAAM,IAAI,KAAK,QAAQ,EAAE,KAAK,CAAC;IAAE,CAAC;IACxH,MAAM,EAAE,IAAI,YAAa,MAAM,IAAI,KAAK;IACxC,IAAI,OAAO,KAAA,GAAW,MAAM,IAAI,MAAM,UAAU,WAAW,IAAI,YAAY;IAC3E,OAAO;KAAE;KAAI,KAAK,GAAG,KAAK,+BAA+B;KAAM;KAAU;IAAK;GAChF;EACF;CACF,EACF;AACF,CAAC"}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/** A clip as the page knows it: its ID, where it plays from, how long it runs in milliseconds, and its type. */
|
|
2
|
+
export interface Clip {
|
|
3
|
+
id: string;
|
|
4
|
+
url: string;
|
|
5
|
+
duration: number;
|
|
6
|
+
type: string;
|
|
7
|
+
}
|
|
8
|
+
/** A take going on: `stop` ends it and keeps it, `cancel` ends it and keeps nothing. */
|
|
9
|
+
export interface Take {
|
|
10
|
+
/** When it started, as `Date.now()`. */
|
|
11
|
+
started: number;
|
|
12
|
+
/** The mic, while it's recorded: to show it's heard (`liveWaveform` from `deictic/client`). */
|
|
13
|
+
stream: MediaStream;
|
|
14
|
+
stop(): Promise<Clip>;
|
|
15
|
+
cancel(): void;
|
|
16
|
+
}
|
|
17
|
+
/** The page's half, for other plugins' page halves. */
|
|
18
|
+
export interface Voice {
|
|
19
|
+
/** Starts recording the mic, asking for it the first time: rejects when it's refused or there's none. */
|
|
20
|
+
start(): Promise<Take>;
|
|
21
|
+
}
|
|
22
|
+
/** The server's half, for other plugins' server halves. */
|
|
23
|
+
export interface Clips {
|
|
24
|
+
/** A clip's audio, or nothing for one not kept (any more). */
|
|
25
|
+
read(id: string): {
|
|
26
|
+
data: Uint8Array<ArrayBuffer>;
|
|
27
|
+
name: string;
|
|
28
|
+
type: string;
|
|
29
|
+
} | undefined;
|
|
30
|
+
}
|
|
31
|
+
declare module 'deictic' {
|
|
32
|
+
interface ServerApis {
|
|
33
|
+
voice: Clips;
|
|
34
|
+
}
|
|
35
|
+
interface ClientApis {
|
|
36
|
+
voice: Voice;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export interface VoiceOptions {
|
|
40
|
+
/** How many clips to keep, the latest: 50 by default. */
|
|
41
|
+
keep?: number;
|
|
42
|
+
/** Where they're kept, from the project's root: `.deictic/voice` by default. */
|
|
43
|
+
dir?: string;
|
|
44
|
+
}
|
|
45
|
+
export declare function voice(options?: VoiceOptions): import("deictic").ServerPlugin<never, never, never, Clips>;
|
|
46
|
+
export { voice as default };
|
|
47
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/plugins/voice/index.ts"],"mappings":";iBAaiB;EACf;EACA;EACA;EACA;;;iBAIe;;EAEf;;EAEA,QAAQ;EACR,QAAQ,QAAQ;EAChB;;;iBAIe;;EAEf,SAAS,QAAQ;;;iBAIF;;EAEf,KAAK;IAAe,MAAM,WAAW;IAAc;IAAc;;;;YAIvD;IACR,OAAO;;YAEC;IACR,OAAO;;;iBAIM;;EAEf;;EAEA;;wBASc,MAAM,UAAS,iCAAiB,kCAAA"}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { definePlugin } from "../index.js";
|
|
4
|
+
import { t as keptIn } from "../kept.js";
|
|
5
|
+
// src/plugins/voice/index.ts
|
|
6
|
+
/**
|
|
7
|
+
* `deictic/voice`: records the mic, for other plugins to attach (tasks does) or play along with
|
|
8
|
+
* something (a recording does). No tab of its own. The page half asks for the mic the first time, records
|
|
9
|
+
* with `MediaRecorder` and sends each take to the `add` route; the server half keeps the latest `keep`
|
|
10
|
+
* clips under `.deictic/voice` and serves them at `clip/<id>`.
|
|
11
|
+
*/
|
|
12
|
+
const ID = /^[a-z0-9]+-[a-z0-9]+$/;
|
|
13
|
+
/** What one clip may weigh: minutes of speech in Opus are well under a MB. */
|
|
14
|
+
const MAX = 26214400;
|
|
15
|
+
/** The audio a browser's `MediaRecorder` makes, by the extension it's kept under. */
|
|
16
|
+
const TYPES = {
|
|
17
|
+
webm: "audio/webm",
|
|
18
|
+
ogg: "audio/ogg",
|
|
19
|
+
mp4: "audio/mp4"
|
|
20
|
+
};
|
|
21
|
+
function voice(options = {}) {
|
|
22
|
+
const keep = options.keep ?? 50;
|
|
23
|
+
let dir = "";
|
|
24
|
+
let taken = 0;
|
|
25
|
+
const fileOf = (id) => ID.test(id) && existsSync(dir) ? readdirSync(dir).find((f) => f.startsWith(`${id}.`)) : void 0;
|
|
26
|
+
const read = (id) => {
|
|
27
|
+
const file = fileOf(id);
|
|
28
|
+
if (file === void 0) return void 0;
|
|
29
|
+
const ext = file.slice(id.length + 1);
|
|
30
|
+
return {
|
|
31
|
+
data: new Uint8Array(readFileSync(join(dir, file))),
|
|
32
|
+
name: `voice-${file}`,
|
|
33
|
+
type: TYPES[ext] ?? "application/octet-stream"
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const keepClip = (data, ext) => {
|
|
37
|
+
const id = `${Date.now().toString(36).padStart(9, "0")}${(taken++ % 1296).toString(36).padStart(2, "0")}-${crypto.randomUUID().slice(0, 8)}`;
|
|
38
|
+
mkdirSync(dir, { recursive: true });
|
|
39
|
+
writeFileSync(join(dir, `${id}.${ext}`), data);
|
|
40
|
+
const kept = readdirSync(dir).toSorted();
|
|
41
|
+
for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));
|
|
42
|
+
return id;
|
|
43
|
+
};
|
|
44
|
+
return definePlugin({
|
|
45
|
+
name: "voice",
|
|
46
|
+
client: "deictic/voice/client",
|
|
47
|
+
setup: ({ root }) => {
|
|
48
|
+
dir = options.dir === void 0 ? keptIn(root, "voice") : resolve(root, options.dir);
|
|
49
|
+
return { read };
|
|
50
|
+
},
|
|
51
|
+
routes: {
|
|
52
|
+
add: async (req) => {
|
|
53
|
+
const type = (req.headers.get("content-type") ?? "").split(";")[0].trim();
|
|
54
|
+
const ext = Object.keys(TYPES).find((e) => TYPES[e] === type);
|
|
55
|
+
if (ext === void 0) return Response.json({ problem: `send the clip as ${Object.values(TYPES).join(", ")}` }, { status: 415 });
|
|
56
|
+
const body = new Uint8Array(await req.arrayBuffer());
|
|
57
|
+
if (body.byteLength === 0) return Response.json({ problem: "the clip is empty: speak for a moment longer" }, { status: 400 });
|
|
58
|
+
if (body.byteLength > MAX) return Response.json({ problem: `a clip may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });
|
|
59
|
+
return Response.json({ id: keepClip(body, ext) });
|
|
60
|
+
},
|
|
61
|
+
clip: (req) => {
|
|
62
|
+
const found = read(new URL(req.url).pathname.split("/").at(-1) ?? "");
|
|
63
|
+
if (found === void 0) return new Response("no such clip, or not kept any more", { status: 404 });
|
|
64
|
+
return new Response(found.data, { headers: {
|
|
65
|
+
"content-type": found.type,
|
|
66
|
+
"cache-control": "no-store"
|
|
67
|
+
} });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
export { voice as default, voice };
|
|
73
|
+
|
|
74
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/plugins/voice/index.ts"],"sourcesContent":["/**\n * `deictic/voice`: records the mic, for other plugins to attach (tasks does) or play along with\n * something (a recording does). No tab of its own. The page half asks for the mic the first time, records\n * with `MediaRecorder` and sends each take to the `add` route; the server half keeps the latest `keep`\n * clips under `.deictic/voice` and serves them at `clip/<id>`.\n */\nimport { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { join, resolve } from 'node:path';\n\nimport { definePlugin } from '#src/index.ts';\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** A clip as the page knows it: its ID, where it plays from, how long it runs in milliseconds, and its type. */\nexport interface Clip {\n id: string;\n url: string;\n duration: number;\n type: string;\n}\n\n/** A take going on: `stop` ends it and keeps it, `cancel` ends it and keeps nothing. */\nexport interface Take {\n /** When it started, as `Date.now()`. */\n started: number;\n /** The mic, while it's recorded: to show it's heard (`liveWaveform` from `deictic/client`). */\n stream: MediaStream;\n stop(): Promise<Clip>;\n cancel(): void;\n}\n\n/** The page's half, for other plugins' page halves. */\nexport interface Voice {\n /** Starts recording the mic, asking for it the first time: rejects when it's refused or there's none. */\n start(): Promise<Take>;\n}\n\n/** The server's half, for other plugins' server halves. */\nexport interface Clips {\n /** A clip's audio, or nothing for one not kept (any more). */\n read(id: string): { data: Uint8Array<ArrayBuffer>; name: string; type: string } | undefined;\n}\n\ndeclare module 'deictic' {\n interface ServerApis {\n voice: Clips;\n }\n interface ClientApis {\n voice: Voice;\n }\n}\n\nexport interface VoiceOptions {\n /** How many clips to keep, the latest: 50 by default. */\n keep?: number;\n /** Where they're kept, from the project's root: `.deictic/voice` by default. */\n dir?: string;\n}\n\nconst ID = /^[a-z0-9]+-[a-z0-9]+$/;\n/** What one clip may weigh: minutes of speech in Opus are well under a MB. */\nconst MAX = 25 * 1024 * 1024;\n/** The audio a browser's `MediaRecorder` makes, by the extension it's kept under. */\nconst TYPES: Record<string, string> = { webm: 'audio/webm', ogg: 'audio/ogg', mp4: 'audio/mp4' };\n\nexport function voice(options: VoiceOptions = {}) {\n const keep = options.keep ?? 50;\n let dir = '';\n let taken = 0;\n const fileOf = (id: string) => (ID.test(id) && existsSync(dir) ? readdirSync(dir).find((f) => f.startsWith(`${id}.`)) : undefined);\n const read: Clips['read'] = (id) => {\n const file = fileOf(id);\n if (file === undefined) return undefined;\n const ext = file.slice(id.length + 1);\n return { data: new Uint8Array(readFileSync(join(dir, file))), name: `voice-${file}`, type: TYPES[ext] ?? 'application/octet-stream' };\n };\n const keepClip = (data: Uint8Array, ext: string) => {\n // Sorts by when it was made, which is what pruning keeps by: the count orders two in one millisecond.\n const id = `${Date.now().toString(36).padStart(9, '0')}${(taken++ % 1296).toString(36).padStart(2, '0')}-${crypto.randomUUID().slice(0, 8)}`;\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(dir, `${id}.${ext}`), data);\n const kept = readdirSync(dir).toSorted();\n for (const old of kept.slice(0, Math.max(0, kept.length - keep))) rmSync(join(dir, old));\n return id;\n };\n\n return definePlugin<never, never, never, Clips>({\n name: 'voice',\n client: 'deictic/voice/client',\n setup: ({ root }) => {\n dir = options.dir === undefined ? keptIn(root, 'voice') : resolve(root, options.dir);\n return { read };\n },\n routes: {\n // A take the page recorded, as the audio type its `MediaRecorder` made.\n add: async (req) => {\n const type = (req.headers.get('content-type') ?? '').split(';')[0]!.trim();\n const ext = Object.keys(TYPES).find((e) => TYPES[e] === type);\n if (ext === undefined) return Response.json({ problem: `send the clip as ${Object.values(TYPES).join(', ')}` }, { status: 415 });\n const body = new Uint8Array(await req.arrayBuffer());\n if (body.byteLength === 0) return Response.json({ problem: 'the clip is empty: speak for a moment longer' }, { status: 400 });\n if (body.byteLength > MAX) return Response.json({ problem: `a clip may weigh ${MAX / 1024 / 1024} MB at most` }, { status: 413 });\n return Response.json({ id: keepClip(body, ext) });\n },\n // `clip/<id>`: the audio, to play back.\n clip: (req) => {\n const found = read(new URL(req.url).pathname.split('/').at(-1) ?? '');\n if (found === undefined) return new Response('no such clip, or not kept any more', { status: 404 });\n return new Response(found.data, { headers: { 'content-type': found.type, 'cache-control': 'no-store' } });\n },\n },\n });\n}\n\nexport default voice;\n"],"mappings":";;;;;;;;;;;AA0DA,MAAM,KAAK;;AAEX,MAAM,MAAM;;AAEZ,MAAM,QAAgC;CAAE,MAAM;CAAc,KAAK;CAAa,KAAK;AAAY;AAE/F,SAAgB,MAAM,UAAwB,CAAC,GAAG;CAChD,MAAM,OAAO,QAAQ,QAAQ;CAC7B,IAAI,MAAM;CACV,IAAI,QAAQ;CACZ,MAAM,UAAU,OAAgB,GAAG,KAAK,EAAE,KAAK,WAAW,GAAG,IAAI,YAAY,GAAG,CAAC,CAAC,MAAM,MAAM,EAAE,WAAW,GAAG,GAAG,EAAE,CAAC,IAAI,KAAA;CACxH,MAAM,QAAuB,OAAO;EAClC,MAAM,OAAO,OAAO,EAAE;EACtB,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;EAC/B,MAAM,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;EACpC,OAAO;GAAE,MAAM,IAAI,WAAW,aAAa,KAAK,KAAK,IAAI,CAAC,CAAC;GAAG,MAAM,SAAS;GAAQ,MAAM,MAAM,QAAQ;EAA2B;CACtI;CACA,MAAM,YAAY,MAAkB,QAAgB;EAElD,MAAM,KAAK,GAAG,KAAK,IAAI,CAAC,CAAC,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,KAAK,UAAU,KAAA,CAAM,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,EAAE,GAAG,OAAO,WAAW,CAAC,CAAC,MAAM,GAAG,CAAC;EACzI,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;EAClC,cAAc,KAAK,KAAK,GAAG,GAAG,GAAG,KAAK,GAAG,IAAI;EAC7C,MAAM,OA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,KAAA,GAAW,OAAO,IAAI,SAAS,sCAAsC,EAAE,QAAQ,IAAI,CAAC;IAClG,OAAO,IAAI,SAAS,MAAM,MAAM,EAAE,SAAS;KAAE,gBAAgB,MAAM;KAAM,iBAAiB;IAAW,EAAE,CAAC;GAC1G;EACF;CACF,CAAC;AACH"}
|
package/dist/waveform.js
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// src/client/waveform.ts
|
|
2
|
+
/**
|
|
3
|
+
* Waveforms: a clip's, read off its audio, drawn as bars with what's played in the accent; and a mic's live,
|
|
4
|
+
* a meter scrolling left as it hears. For the lightbox's player and whatever records the mic (the task
|
|
5
|
+
* panel's Voice, the recording toolbar's mic). Bars, not a line: they read at any size, and at a glance.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* How loud each of `bars` stretches of the clip at `url` is, from 0 to 1, the loudest 1, and how long it is in
|
|
9
|
+
* seconds: MediaRecorder's webm doesn't say until it's played through.
|
|
10
|
+
*/
|
|
11
|
+
async function peaksOf(url, bars) {
|
|
12
|
+
const data = await (await fetch(url)).arrayBuffer();
|
|
13
|
+
const context = new AudioContext();
|
|
14
|
+
try {
|
|
15
|
+
const audio = await context.decodeAudioData(data);
|
|
16
|
+
const samples = audio.getChannelData(0);
|
|
17
|
+
const size = Math.max(1, Math.floor(samples.length / bars));
|
|
18
|
+
const peaks = [];
|
|
19
|
+
for (let b = 0; b < bars; b++) {
|
|
20
|
+
let sum = 0;
|
|
21
|
+
const from = b * size;
|
|
22
|
+
for (let i = from; i < Math.min(samples.length, from + size); i++) sum += samples[i] * samples[i];
|
|
23
|
+
peaks.push(Math.sqrt(sum / size));
|
|
24
|
+
}
|
|
25
|
+
const top = Math.max(...peaks, 1e-6);
|
|
26
|
+
return {
|
|
27
|
+
peaks: peaks.map((p) => p / top),
|
|
28
|
+
duration: audio.duration
|
|
29
|
+
};
|
|
30
|
+
} finally {
|
|
31
|
+
context.close();
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** Draws `peaks` as bars across `canvas`, centred on its middle, the share `progress` (0–1) of them played. */
|
|
35
|
+
function drawBars(canvas, peaks, progress, colors) {
|
|
36
|
+
const { width, height } = fit(canvas);
|
|
37
|
+
const g = canvas.getContext("2d");
|
|
38
|
+
if (g === null) return;
|
|
39
|
+
g.clearRect(0, 0, width, height);
|
|
40
|
+
const step = width / Math.max(1, peaks.length);
|
|
41
|
+
const bar = Math.max(1, step * .6);
|
|
42
|
+
const dpr = devicePixelRatio;
|
|
43
|
+
peaks.forEach((p, i) => {
|
|
44
|
+
const h = Math.max(2 * dpr, p * height * .9);
|
|
45
|
+
g.fillStyle = (i + .5) / peaks.length <= progress ? colors.played : colors.rest;
|
|
46
|
+
g.fillRect(i * step + (step - bar) / 2, (height - h) / 2, bar, h);
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The mic's level, live, as bars scrolling in from the right, drawn on `canvas` until the answer's called.
|
|
51
|
+
* It listens to `stream` on its own; the recording goes on as it was.
|
|
52
|
+
*/
|
|
53
|
+
function liveWaveform(canvas, stream, colors) {
|
|
54
|
+
const context = new AudioContext();
|
|
55
|
+
const analyser = context.createAnalyser();
|
|
56
|
+
analyser.fftSize = 1024;
|
|
57
|
+
context.createMediaStreamSource(stream).connect(analyser);
|
|
58
|
+
const samples = new Float32Array(analyser.fftSize);
|
|
59
|
+
const levels = [];
|
|
60
|
+
let frame = 0;
|
|
61
|
+
let last = 0;
|
|
62
|
+
const tick = (now) => {
|
|
63
|
+
frame = requestAnimationFrame(tick);
|
|
64
|
+
if (now - last < 50) return;
|
|
65
|
+
last = now;
|
|
66
|
+
analyser.getFloatTimeDomainData(samples);
|
|
67
|
+
let sum = 0;
|
|
68
|
+
for (const s of samples) sum += s * s;
|
|
69
|
+
levels.push(Math.min(1, Math.sqrt(sum / samples.length) * 4));
|
|
70
|
+
const room = Math.max(8, Math.floor(canvas.clientWidth / 4));
|
|
71
|
+
if (levels.length > room) levels.splice(0, levels.length - room);
|
|
72
|
+
drawBars(canvas, [...Array(room - levels.length).fill(0), ...levels], 1, colors);
|
|
73
|
+
};
|
|
74
|
+
frame = requestAnimationFrame(tick);
|
|
75
|
+
return () => {
|
|
76
|
+
cancelAnimationFrame(frame);
|
|
77
|
+
context.close();
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/** Sizes the canvas's pixels to its box, at the display's density: what it draws stays sharp. */
|
|
81
|
+
function fit(canvas) {
|
|
82
|
+
const width = Math.max(1, Math.round(canvas.clientWidth * devicePixelRatio));
|
|
83
|
+
const height = Math.max(1, Math.round(canvas.clientHeight * devicePixelRatio));
|
|
84
|
+
if (canvas.width !== width) canvas.width = width;
|
|
85
|
+
if (canvas.height !== height) canvas.height = height;
|
|
86
|
+
return {
|
|
87
|
+
width,
|
|
88
|
+
height
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
export { liveWaveform as n, peaksOf as r, drawBars as t };
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=waveform.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"waveform.js","names":[],"sources":["../src/client/waveform.ts"],"sourcesContent":["/**\n * Waveforms: a clip's, read off its audio, drawn as bars with what's played in the accent; and a mic's live,\n * a meter scrolling left as it hears. For the lightbox's player and whatever records the mic (the task\n * panel's Voice, the recording toolbar's mic). Bars, not a line: they read at any size, and at a glance.\n */\n\n/**\n * How loud each of `bars` stretches of the clip at `url` is, from 0 to 1, the loudest 1, and how long it is in\n * seconds: MediaRecorder's webm doesn't say until it's played through.\n */\nexport async function peaksOf(url: string, bars: number): Promise<{ peaks: number[]; duration: number }> {\n const data = await (await fetch(url)).arrayBuffer();\n const context = new AudioContext();\n try {\n const audio = await context.decodeAudioData(data);\n const samples = audio.getChannelData(0);\n const size = Math.max(1, Math.floor(samples.length / bars));\n const peaks: number[] = [];\n for (let b = 0; b < bars; b++) {\n // The stretch's loudness as its RMS: a peak would make every click a wall.\n let sum = 0;\n const from = b * size;\n for (let i = from; i < Math.min(samples.length, from + size); i++) sum += samples[i]! * samples[i]!;\n peaks.push(Math.sqrt(sum / size));\n }\n const top = Math.max(...peaks, 1e-6);\n return { peaks: peaks.map((p) => p / top), duration: audio.duration };\n } finally {\n void context.close();\n }\n}\n\nexport interface Colors {\n /** What's played. */\n played: string;\n /** What isn't, yet. */\n rest: string;\n}\n\n/** Draws `peaks` as bars across `canvas`, centred on its middle, the share `progress` (0–1) of them played. */\nexport function drawBars(canvas: HTMLCanvasElement, peaks: readonly number[], progress: number, colors: Colors): void {\n const { width, height } = fit(canvas);\n const g = canvas.getContext('2d');\n if (g === null) return;\n g.clearRect(0, 0, width, height);\n const step = width / Math.max(1, peaks.length);\n const bar = Math.max(1, step * 0.6);\n const dpr = devicePixelRatio;\n peaks.forEach((p, i) => {\n // Silence still shows as a sliver, so the clip's length reads from end to end.\n const h = Math.max(2 * dpr, p * height * 0.9);\n g.fillStyle = (i + 0.5) / peaks.length <= progress ? colors.played : colors.rest;\n g.fillRect(i * step + (step - bar) / 2, (height - h) / 2, bar, h);\n });\n}\n\n/**\n * The mic's level, live, as bars scrolling in from the right, drawn on `canvas` until the answer's called.\n * It listens to `stream` on its own; the recording goes on as it was.\n */\nexport function liveWaveform(canvas: HTMLCanvasElement, stream: MediaStream, colors: Colors): () => void {\n const context = new AudioContext();\n const analyser = context.createAnalyser();\n analyser.fftSize = 1024;\n context.createMediaStreamSource(stream).connect(analyser);\n const samples = new Float32Array(analyser.fftSize);\n const levels: number[] = [];\n let frame = 0;\n let last = 0;\n const tick = (now: number) => {\n frame = requestAnimationFrame(tick);\n // About 20 bars a second, whatever the display's rate.\n if (now - last < 50) return;\n last = now;\n analyser.getFloatTimeDomainData(samples);\n let sum = 0;\n for (const s of samples) sum += s * s;\n // Speech sits low in the range: lifted so a normal voice fills most of the height.\n levels.push(Math.min(1, Math.sqrt(sum / samples.length) * 4));\n const room = Math.max(8, Math.floor(canvas.clientWidth / 4));\n if (levels.length > room) levels.splice(0, levels.length - room);\n drawBars(canvas, [...Array<number>(room - levels.length).fill(0), ...levels], 1, colors);\n };\n frame = requestAnimationFrame(tick);\n return () => {\n cancelAnimationFrame(frame);\n void context.close();\n };\n}\n\n/** Sizes the canvas's pixels to its box, at the display's density: what it draws stays sharp. */\nfunction fit(canvas: HTMLCanvasElement): { width: number; height: number } {\n const width = Math.max(1, Math.round(canvas.clientWidth * devicePixelRatio));\n const height = Math.max(1, Math.round(canvas.clientHeight * devicePixelRatio));\n if (canvas.width !== width) canvas.width = width;\n if (canvas.height !== height) canvas.height = height;\n return { width, height };\n}\n"],"mappings":";;;;;;;;;;AAUA,eAAsB,QAAQ,KAAa,MAA8D;CACvG,MAAM,OAAO,OAAO,MAAM,MAAM,GAAG,EAAA,CAAG,YAAY;CAClD,MAAM,UAAU,IAAI,aAAa;CACjC,IAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,gBAAgB,IAAI;EAChD,MAAM,UAAU,MAAM,eAAe,CAAC;EACtC,MAAM,OAAO,KAAK,IAAI,GAAG,KAAK,MAAM,QAAQ,SAAS,IAAI,CAAC;EAC1D,MAAM,QAAkB,CAAC;EACzB,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,KAAK;GAE7B,IAAI,MAAM;GACV,MAAM,OAAO,IAAI;GACjB,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,IAAI,QAAQ,QAAQ,OAAO,IAAI,GAAG,KAAK,OAAO,QAAQ,KAAM,QAAQ;GAChG,MAAM,KAAK,KAAK,KAAK,MAAM,IAAI,CAAC;EAClC;EACA,MAAM,MAAM,KAAK,IAAI,GAAG,OAAO,IAAI;EACnC,OAAO;GAAE,OAAO,MAAM,KAAK,MAAM,IAAI,GAAG;GAAG,UAAU,MAAM;EAAS;CACtE,UAAU;EACH,QAAQ,MAAM;CACrB;AACF;;AAUA,SAAgB,SAAS,QAA2B,OAA0B,UAAkB,QAAsB;CACpH,MAAM,EAAE,OAAO,WAAW,IAAI,MA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AM,CAAC,CAAC,KAAK,CAAC,GAAG,GAAG,MAAM,GAAG,GAAG,MAAM;CACzF;CACA,QAAQ,sBAAsB,IAAI;CAClC,aAAa;EACX,qBAAqB,KAAK;EACrB,QAAQ,MAAM;CACrB;AACF;;AAGA,SAAS,IAAI,QAA8D;CACzE,MAAM,QAAQ,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,cAAc,gBAAgB,CAAC;CAC3E,MAAM,SAAS,KAAK,IAAI,GAAG,KAAK,MAAM,OAAO,eAAe,gBAAgB,CAAC;CAC7E,IAAI,OAAO,UAAU,OAAO,OAAO,QAAQ;CAC3C,IAAI,OAAO,WAAW,QAAQ,OAAO,SAAS;CAC9C,OAAO;EAAE;EAAO;CAAO;AACzB"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `deictic/webpack`: deictic in webpack's dev server, or Rspack's (`@rspack/core` takes the same
|
|
3
|
+
* plugin). Nothing runs out of development mode.
|
|
4
|
+
*
|
|
5
|
+
* A loader (`loader.ts`) runs `pre` on the project's JSX modules, marking each host element with its
|
|
6
|
+
* place in the source as written, and in a build for the browser appending the import of the client
|
|
7
|
+
* module, which webpack has no virtual module for, so it's written to `.deictic/client.js`. The
|
|
8
|
+
* endpoints go in front of the dev server's own middleware (`devServer.setupMiddlewares`, which
|
|
9
|
+
* webpack-dev-server and Rspack's both read), and a place opens with `launch-editor`, as webpack has no
|
|
10
|
+
* launcher of its own. Where the dev server is started by hand, or by Rsbuild, `middleware` is the
|
|
11
|
+
* endpoints to mount there.
|
|
12
|
+
*/
|
|
13
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
14
|
+
import { t as DeicticOptions } from "./integration.js";
|
|
15
|
+
export interface DeicticWebpackOptions extends DeicticOptions {
|
|
16
|
+
/** The project's root, which marks and edits are from: the compiler's `context` by default. */
|
|
17
|
+
root?: string;
|
|
18
|
+
/** The path the page is served under, ending in `/`: `/` by default. */
|
|
19
|
+
base?: string;
|
|
20
|
+
}
|
|
21
|
+
type Middleware = (req: IncomingMessage, res: ServerResponse, next: () => void) => void;
|
|
22
|
+
type Middlewares = ({
|
|
23
|
+
name: string;
|
|
24
|
+
middleware: Middleware;
|
|
25
|
+
} | Middleware)[];
|
|
26
|
+
/** What the plugin reads and sets of a webpack or Rspack compiler. */
|
|
27
|
+
interface Compiler {
|
|
28
|
+
context: string;
|
|
29
|
+
options: {
|
|
30
|
+
mode?: string;
|
|
31
|
+
target?: string | string[] | false;
|
|
32
|
+
module: {
|
|
33
|
+
rules: unknown[];
|
|
34
|
+
};
|
|
35
|
+
devServer?: {
|
|
36
|
+
setupMiddlewares?: (middlewares: Middlewares, server: unknown) => Middlewares;
|
|
37
|
+
} & Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
export declare class DeicticPlugin {
|
|
41
|
+
#private;
|
|
42
|
+
constructor(options?: DeicticWebpackOptions);
|
|
43
|
+
/** The endpoints as Node middleware, once the plugin is applied: for a dev server started by hand. */
|
|
44
|
+
get middleware(): Middleware;
|
|
45
|
+
apply(compiler: Compiler): void;
|
|
46
|
+
}
|
|
47
|
+
/** The plugin, as a function: `plugins: [deictic({ plugins: [tailwind()] })]`. */
|
|
48
|
+
export declare const deictic: (options?: DeicticWebpackOptions) => DeicticPlugin;
|
|
49
|
+
export { deictic as default };
|
|
50
|
+
//# sourceMappingURL=webpack.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webpack.d.ts","names":[],"sources":["../src/webpack.ts"],"mappings":";;;;;;;;;;;;;;iBAsBiB,8BAA8B;;EAE7C;;EAEA;;KAGG,cAAc,KAAK,iBAAiB,KAAK,gBAAgB;KACzD;EAAiB;EAAc,YAAY;IAAe;;UAGrD;EACR;EACA;IACE;IACA;IACA;MAAU;;IACV;MAAc,oBAAoB,aAAa,aAAa,oBAAoB;QAAgB;;;qBAUvF;;EAOX,YAAY,UAAS;;MAOjB,cAAc;EAalB,MAAM,UAAU;;;qBA4BL,UAAO,UAAa,0BAAqB"}
|
package/dist/webpack.js
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { n as nodeMiddleware, t as endpoints } from "./endpoints.js";
|
|
2
|
+
import { d as JSX, o as prepare, s as writeClient, t as beside } from "./integration.js";
|
|
3
|
+
// src/tools/editor.ts
|
|
4
|
+
async function openInEditor(path, { line, column }) {
|
|
5
|
+
const launcher = await import("launch-editor").catch(() => void 0);
|
|
6
|
+
if (launcher === void 0) return new Response("deictic opens files with launch-editor here: add it to your devDependencies", { status: 501 });
|
|
7
|
+
return new Promise((done) => {
|
|
8
|
+
let failed = false;
|
|
9
|
+
launcher.default(`${path}:${line}:${column}`, (_, message) => {
|
|
10
|
+
failed = true;
|
|
11
|
+
done(new Response(`${message ?? "the editor didn't open"}: set EDITOR to your editor's command`, { status: 500 }));
|
|
12
|
+
});
|
|
13
|
+
setTimeout(() => failed || done(new Response(null, { status: 204 })), 50);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
// src/webpack.ts
|
|
17
|
+
const loaderPath = beside(import.meta.url, "loader");
|
|
18
|
+
/** Whether a target runs in a browser: webpack's default does, as do `web` and `browserslist`; Node's and Electron's main don't. */
|
|
19
|
+
const forBrowser = (target) => target === void 0 || [target].flat().some((t) => t !== false && !/^(async-)?node|^electron-main|^electron-preload/.test(t));
|
|
20
|
+
var DeicticPlugin = class {
|
|
21
|
+
#options;
|
|
22
|
+
#plugins;
|
|
23
|
+
#shortcut;
|
|
24
|
+
#middleware;
|
|
25
|
+
#root = "";
|
|
26
|
+
constructor(options = {}) {
|
|
27
|
+
this.#options = options;
|
|
28
|
+
({plugins: this.#plugins, shortcut: this.#shortcut} = prepare(options));
|
|
29
|
+
}
|
|
30
|
+
/** The endpoints as Node middleware, once the plugin is applied: for a dev server started by hand. */
|
|
31
|
+
get middleware() {
|
|
32
|
+
if (this.#middleware !== void 0) return this.#middleware;
|
|
33
|
+
if (this.#root === "") throw new Error("deictic: give the plugin to the compiler before mounting its middleware");
|
|
34
|
+
const root = this.#root;
|
|
35
|
+
const handle = endpoints({
|
|
36
|
+
root,
|
|
37
|
+
plugins: this.#plugins,
|
|
38
|
+
base: this.#options.base ?? "/",
|
|
39
|
+
open: (path, loc) => openInEditor(path, loc)
|
|
40
|
+
});
|
|
41
|
+
return this.#middleware = nodeMiddleware(handle);
|
|
42
|
+
}
|
|
43
|
+
apply(compiler) {
|
|
44
|
+
if (compiler.options.mode !== "development") return;
|
|
45
|
+
this.#root = this.#options.root ?? compiler.context;
|
|
46
|
+
const browser = forBrowser(compiler.options.target);
|
|
47
|
+
const client = browser ? writeClient(this.#root, this.#plugins, this.#options.base ?? "/", this.#shortcut) : void 0;
|
|
48
|
+
const options = {
|
|
49
|
+
root: this.#root,
|
|
50
|
+
...client === void 0 ? {} : { client }
|
|
51
|
+
};
|
|
52
|
+
compiler.options.module.rules.unshift({
|
|
53
|
+
test: JSX,
|
|
54
|
+
exclude: /[\\/]node_modules[\\/]/,
|
|
55
|
+
enforce: "pre",
|
|
56
|
+
use: [{
|
|
57
|
+
loader: loaderPath,
|
|
58
|
+
options
|
|
59
|
+
}]
|
|
60
|
+
});
|
|
61
|
+
if (!browser) return;
|
|
62
|
+
const devServer = compiler.options.devServer ??= {};
|
|
63
|
+
const theirs = devServer.setupMiddlewares;
|
|
64
|
+
devServer.setupMiddlewares = (middlewares, server) => {
|
|
65
|
+
const all = theirs === void 0 ? middlewares : theirs(middlewares, server);
|
|
66
|
+
all.unshift({
|
|
67
|
+
name: "deictic",
|
|
68
|
+
middleware: this.middleware
|
|
69
|
+
});
|
|
70
|
+
return all;
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
};
|
|
74
|
+
/** The plugin, as a function: `plugins: [deictic({ plugins: [tailwind()] })]`. */
|
|
75
|
+
const deictic = (options = {}) => new DeicticPlugin(options);
|
|
76
|
+
export { DeicticPlugin, deictic as default, deictic };
|
|
77
|
+
|
|
78
|
+
//# sourceMappingURL=webpack.js.map
|