deictic 0.4.0 → 0.6.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 (69) hide show
  1. package/API.md +19 -8
  2. package/dist/cli.js +34 -28
  3. package/dist/cli.js.map +1 -1
  4. package/dist/shared/board.js +8 -19
  5. package/dist/shared/board.js.map +1 -1
  6. package/dist/shared/clean.js +105 -0
  7. package/dist/shared/clean.js.map +1 -0
  8. package/dist/shared/endpoints.js +35 -9
  9. package/dist/shared/endpoints.js.map +1 -1
  10. package/dist/shared/find.js +3 -2
  11. package/dist/shared/find.js.map +1 -1
  12. package/dist/shared/frame.js +4 -18
  13. package/dist/shared/frame.js.map +1 -1
  14. package/dist/shared/index.d.ts +8 -4
  15. package/dist/shared/index.d.ts.map +1 -1
  16. package/dist/shared/index7.d.ts +2 -0
  17. package/dist/shared/index7.d.ts.map +1 -1
  18. package/dist/shared/init.js +17 -24
  19. package/dist/shared/init.js.map +1 -1
  20. package/dist/shared/local.js +2 -1
  21. package/dist/shared/local.js.map +1 -1
  22. package/dist/shared/packages.js +9 -2
  23. package/dist/shared/packages.js.map +1 -1
  24. package/dist/shared/recording.js +4 -27
  25. package/dist/shared/recording.js.map +1 -1
  26. package/dist/shared/src.js.map +1 -1
  27. package/dist/shared/task.js +43 -10
  28. package/dist/shared/task.js.map +1 -1
  29. package/dist/shared/tasks.js +109 -115
  30. package/dist/shared/tasks.js.map +1 -1
  31. package/dist/shared/transcribe.js +1 -128
  32. package/dist/shared/transcribe2.js +119 -0
  33. package/dist/shared/transcribe2.js.map +1 -0
  34. package/dist/shared/vb.js +2 -3
  35. package/dist/shared/vb.js.map +1 -1
  36. package/dist/shared/voice2.js +4 -17
  37. package/dist/shared/voice2.js.map +1 -1
  38. package/dist/shared/watch.js +56 -39
  39. package/dist/shared/watch.js.map +1 -1
  40. package/dist/tailwind/index.js +6 -2
  41. package/dist/tailwind/index.js.map +1 -1
  42. package/dist/tasks/client.d.ts.map +1 -1
  43. package/dist/tasks/client.js +4 -5
  44. package/dist/tasks/client.js.map +1 -1
  45. package/dist/tasks/index.js +1 -1
  46. package/package.json +2 -1
  47. package/skills/deictic/SKILL.md +5 -3
  48. package/skills/deictic/references/tasks.md +6 -5
  49. package/src/cli/board.ts +7 -13
  50. package/src/cli/clean.ts +104 -0
  51. package/src/cli/find.ts +3 -1
  52. package/src/cli/frame.ts +3 -13
  53. package/src/cli/init.ts +16 -20
  54. package/src/cli/recording.ts +15 -21
  55. package/src/cli/task.ts +49 -10
  56. package/src/cli/transcribe.ts +13 -16
  57. package/src/cli/vb.ts +0 -2
  58. package/src/cli/voice.ts +3 -12
  59. package/src/cli/watch.ts +58 -29
  60. package/src/cli.ts +130 -31
  61. package/src/index.ts +8 -4
  62. package/src/plugins/tailwind/index.ts +6 -2
  63. package/src/plugins/tasks/client.ts +4 -5
  64. package/src/plugins/tasks/index.ts +113 -124
  65. package/src/plugins/tasks/local.ts +2 -1
  66. package/src/tools/endpoints.ts +18 -7
  67. package/src/tools/packages.ts +3 -0
  68. package/src/tools/source.ts +25 -5
  69. package/dist/shared/transcribe.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"init.js","names":[],"sources":["../../src/cli/edit.ts","../../src/cli/bun.ts","../../src/cli/init.ts"],"sourcesContent":["/**\n * Editing a project's own source the way it's written: its quotes, semicolons, line endings and indentation. What\n * `init` adds to a bundler's config and to a Bun server goes through here.\n */\nimport type MagicString from 'magic-string';\nimport type { Program } from 'oxc-parser';\n\n/** The file's line ending. */\nexport const eolOf = (code: string) => (code.includes('\\r\\n') ? '\\r\\n' : '\\n');\n\n/** The whitespace a line starts with, for the line `offset` is on. */\nexport function indentAt(code: string, offset: number): string {\n const start = code.lastIndexOf('\\n', offset - 1) + 1;\n return /^[ \\t]*/.exec(code.slice(start))![0];\n}\n\n/**\n * Adds import lines after the module's last import (or `require`, in CommonJS), or at its top: written in the quotes\n * and semicolons of its first import. Each line is `[what, from]`: `import ${what} from '${from}'`, or as a `require`.\n */\nexport function addImports(out: MagicString, program: Program, code: string, lines: [string, string][], commonjs = false): void {\n const eol = eolOf(code);\n const imports = program.body.filter((s) => s.type === 'ImportDeclaration');\n const first = imports[0];\n const quote = first === undefined ? \"'\" : code[first.source.start]!;\n const semi = first === undefined || code.slice(first.start, first.end).trimEnd().endsWith(';') ? ';' : '';\n const q = (s: string) => `${quote}${s}${quote}`;\n const text = lines\n .map(([what, from]) => (commonjs ? `const ${what} = require(${q(from)})${semi}` : `import ${what} from ${q(from)}${semi}`))\n .join(eol);\n const after = imports.at(-1) ?? requiresOf(program).at(-1);\n if (after === undefined) out.prepend(`${text}${eol}${eol}`);\n else out.appendLeft(after.end, `${eol}${text}`);\n}\n\n/** The top-level `const … = require(…)` statements of a CommonJS module, to put new ones after. */\nfunction requiresOf(program: Program) {\n return program.body.filter(\n (s) =>\n s.type === 'VariableDeclaration' &&\n s.declarations.some(\n (d) => d.init?.type === 'CallExpression' && d.init.callee.type === 'Identifier' && d.init.callee.name === 'require',\n ),\n );\n}\n\n/** Inserts `text` as the first property of the object literal that starts at `open` (its `{`), as the object is laid out. */\nexport function addFirst(out: MagicString, code: string, open: number, first: { start: number } | undefined, text: string): void {\n const eol = eolOf(code);\n if (first === undefined) {\n out.appendLeft(open + 1, ` ${text} `);\n return;\n }\n const multiline = code.slice(open, first.start).includes('\\n');\n out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);\n}\n","/**\n * `init` for Bun's own dev server: `Bun.serve` with HTML imports, which bundles the page with the plugins bunfig.toml\n * names. Only that: a Bun project that runs Vite, Next.js or another bundler is that bundler's, and one with no HTML\n * imports has no page of Bun's for deictic to be in. Three steps, as the API has them: the plugin's module, bunfig's\n * `[serve.static] plugins`, and its routes spread into `Bun.serve`'s.\n */\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\n\nimport MagicString from 'magic-string';\nimport { type CallExpression, parseSync, Visitor } from 'oxc-parser';\n\nimport { addFirst, addImports, eolOf } from './edit.ts';\n\n/** The plugin's module, from the root, which bunfig names and the server imports. */\nexport const MODULE = 'deictic.plugin.ts';\n\nexport const PLUGIN = `import { deictic } from 'deictic/bun';\nimport { recommended } from 'deictic/recommended';\n\n// One module for both: bunfig.toml names it as the dev server's bundler plugin, and the server spreads its routes,\n// deictic's endpoints, into its own.\nexport default deictic({ plugins: recommended() });\n`;\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\nconst SKIP = new Set(['node_modules', 'dist', 'build', 'out']);\nconst SERVE = /\\bBun\\.serve\\s*\\(/;\nconst HTML = /\\bfrom\\s*['\"][^'\"]+\\.html['\"]/;\n\n/**\n * The module that serves the page with Bun's bundler: it calls `Bun.serve` and imports an HTML file. Looked for under\n * the root, not in dependencies, builds or dot folders, a few folders deep.\n */\nexport function serverOf(root: string): string | undefined {\n const walk = (dir: string, depth: number): string | undefined => {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const e of entries) {\n if (!e.isFile() || !SOURCE.test(e.name)) continue;\n const path = join(dir, e.name);\n const code = readFileSync(path, 'utf8');\n if (SERVE.test(code) && HTML.test(code)) return path;\n }\n if (depth === 0) return undefined;\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;\n const found = walk(join(dir, e.name), depth - 1);\n if (found !== undefined) return found;\n }\n return undefined;\n };\n return walk(root, 3);\n}\n\n/**\n * bunfig.toml with the plugin's module first in `[serve.static] plugins` (first, so it sees the source as written),\n * made where there's none; unchanged where it's there already, and nothing where bunfig says it another way (a dotted\n * key, an inline table) and it can't tell where.\n */\nexport function addToBunfig(text: string | undefined, entry = `./${MODULE}`): string | undefined {\n const quoted = JSON.stringify(entry);\n if (text === undefined) return `[serve.static]\\nplugins = [${quoted}]\\n`;\n if (text.includes(entry)) return text;\n if (/serve\\.static\\.|static\\s*=\\s*\\{/.test(text)) return undefined;\n const eol = eolOf(text);\n const header = /^[ \\t]*\\[serve\\.static\\][ \\t]*(#.*)?$/m.exec(text);\n if (header === null)\n return `${text}${text === '' || text.endsWith('\\n') ? '' : eol}${eol}[serve.static]${eol}plugins = [${quoted}]${eol}`;\n const bodyStart = header.index + header[0].length;\n const next = /^[ \\t]*\\[/m.exec(text.slice(bodyStart));\n const body = text.slice(bodyStart, next === null ? text.length : bodyStart + next.index);\n const list = /^[ \\t]*plugins[ \\t]*=[ \\t]*\\[/m.exec(body);\n if (list === null) return `${text.slice(0, bodyStart)}${eol}plugins = [${quoted}]${text.slice(bodyStart)}`;\n const open = bodyStart + list.index + list[0].length;\n const rest = text.slice(open);\n const empty = /^\\s*\\]/.test(rest);\n const lineBreak = /^[ \\t]*\\r?\\n([ \\t]*)/.exec(rest);\n if (empty) return `${text.slice(0, open)}${quoted}${rest.trimStart()}`;\n if (lineBreak !== null) return `${text.slice(0, open)}${eol}${lineBreak[1]}${quoted},${rest}`;\n return `${text.slice(0, open)}${quoted}, ${rest.trimStart()}`;\n}\n\n/**\n * The server with the plugin's routes first in `Bun.serve`'s `routes`, or `routes` with them where it has none, and\n * the module imported: nothing where `Bun.serve` isn't given an object it can see, or its routes aren't one.\n */\nexport function addToServer(file: string, code: string, root: string): string | undefined {\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const calls: CallExpression[] = [];\n new Visitor({\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type === 'MemberExpression' &&\n callee.object.type === 'Identifier' &&\n callee.object.name === 'Bun' &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'serve'\n )\n calls.push(node);\n },\n }).visit(program);\n const options = calls.length === 1 ? calls[0]!.arguments[0] : undefined;\n if (options?.type !== 'ObjectExpression') return undefined;\n\n // `tools`, as the API names it, unless the module has a `tools` of its own.\n const name = /\\btools\\b/.test(code) ? 'deicticTools' : 'tools';\n const out = new MagicString(code);\n const routes = options.properties.find(\n (p) => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'routes',\n );\n if (routes === undefined) {\n addFirst(out, code, options.start, options.properties[0], `routes: { ...${name}.routes }`);\n } else {\n if (routes.type !== 'Property' || routes.value.type !== 'ObjectExpression') return undefined;\n addFirst(out, code, routes.value.start, routes.value.properties[0], `...${name}.routes`);\n }\n const from = relative(dirname(file), join(root, MODULE)).replaceAll('\\\\', '/');\n addImports(out, program, code, [[name, from.startsWith('.') ? from : `./${from}`]]);\n return out.toString();\n}\n\n/** What to add by hand, for a server or a bunfig it can't edit. */\nexport const BY_HAND = {\n bunfig: `[serve.static]\\nplugins = [\"./${MODULE}\"]`,\n server: `import tools from './${MODULE}';\\nBun.serve({ routes: { ...tools.routes, '/*': index } });`,\n};\n","/**\n * `deictic init`: the recommended setup in a project, in one step. It installs deictic and what the recommended\n * plugins import, with the project's package manager and as the project's own dev dependencies (deictic, the\n * page's bundle and the skill all find them from the project, so they can't come in through another package), adds\n * deictic to the bundler's config where it can find the place, and offers the agent skill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport MagicString from 'magic-string';\nimport { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';\n\nimport { recommended } from '#src/plugins/recommended/index.ts';\n\nimport { installCommand, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';\n\nimport { fail, parseArgs } from './board.ts';\nimport { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';\nimport { addFirst, addImports, eolOf, indentAt } from './edit.ts';\n\nexport type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';\n\ninterface Setup {\n /** The config files it looks for, in order. */\n files: string[];\n /** The module deictic's integration comes from, and its name there. */\n from: string;\n name: string;\n /** What goes in the config: in its `list`, or wrapped around the whole of it with `wrap`. */\n list?: string;\n value: string;\n wrap?: boolean;\n /** The snippet for a config it can't edit. */\n snippet: string;\n}\n\nconst extensions = (base: string) => ['ts', 'mts', 'js', 'mjs', 'cts', 'cjs'].map((e) => `${base}.${e}`);\nconst PLUGINS = '{ plugins: recommended() }';\n\nconst SETUPS: Record<Exclude<Bundler, 'bun'>, Setup> = {\n next: {\n files: extensions('next.config'),\n from: 'deictic/next',\n name: 'withDeictic',\n value: PLUGINS,\n wrap: true,\n snippet: `export default withDeictic(nextConfig, ${PLUGINS});`,\n },\n astro: {\n files: extensions('astro.config'),\n from: 'deictic/astro',\n name: 'deictic',\n list: 'integrations',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ integrations: [deictic(${PLUGINS})] });`,\n },\n vite: {\n files: extensions('vite.config'),\n from: 'deictic/vite',\n name: 'deictic',\n list: 'plugins',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ plugins: [react(), deictic(${PLUGINS})] });`,\n },\n rspack: {\n files: extensions('rspack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n webpack: {\n files: extensions('webpack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n};\n\n/** The project's root: the nearest folder with a package.json, from `dir` up. */\nexport function rootOf(dir: string): string | undefined {\n for (let at = dir; ; at = dirname(at)) {\n if (existsSync(join(at, 'package.json'))) return at;\n if (dirname(at) === at) return undefined;\n }\n}\n\n/** The project's dependencies and dev dependencies, by name. */\nfunction dependenciesOf(root: string): Set<string> {\n const manifest = readJson(join(root, 'package.json')) ?? {};\n return new Set([manifest.dependencies, manifest.devDependencies].flatMap((d) => Object.keys((d as object | undefined) ?? {})));\n}\n\n/** The bundler the project runs its dev server with, from its dependencies, or none deictic knows. */\nexport function bundlerOf(root: string): Bundler | undefined {\n const has = dependenciesOf(root);\n if (has.has('next')) return 'next';\n if (has.has('astro')) return 'astro';\n if (has.has('vite') || SETUPS.vite.files.some((f) => existsSync(join(root, f)))) return 'vite';\n if (has.has('@rspack/core') || has.has('@rspack/cli')) return 'rspack';\n if (has.has('webpack')) return 'webpack';\n // Bun's own bundler only where a server of the project's has it bundle a page: not every project Bun runs.\n if (serverOf(root) !== undefined) return 'bun';\n return undefined;\n}\n\n/** What the recommended setup imports, for the bundler: launch-editor opens files under webpack, which has no launcher. */\nexport function packagesFor(bundler: Bundler | undefined): string[] {\n const plugins = recommended().flatMap((p) => p.packages ?? []);\n return ['deictic', ...plugins, ...(bundler === 'webpack' || bundler === 'rspack' ? ['launch-editor'] : [])];\n}\n\ntype Node = Expression | ObjectExpression;\n\n/**\n * The object an expression comes to: through `defineConfig(…)`, `(…)`, `satisfies`, a function's return and a top-level\n * `const`. Not through another call: in `mergeConfig(base, {…})` or webpack-merge's `merge(common, {…})` the first\n * argument is a base the project may build with too, and the plugin isn't the base's.\n */\nfunction objectOf(node: Node | null | undefined, program: Program, depth = 0): ObjectExpression | undefined {\n if (node == null || depth > 8) return undefined;\n const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);\n if (node.type === 'ObjectExpression') return node;\n if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')\n return next(node.expression);\n if (node.type === 'CallExpression') {\n const { callee } = node;\n const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as\n { type: string; name?: string } | undefined;\n const [first] = node.arguments;\n if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;\n return next(first);\n }\n if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {\n const body = node.body;\n if (body === null) return undefined;\n if (body.type !== 'BlockStatement') return next(body);\n const returned = body.body.findLast((s) => s.type === 'ReturnStatement');\n return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;\n }\n if (node.type !== 'Identifier') return undefined;\n for (const statement of program.body) {\n const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);\n if (found !== undefined) return next(found.init);\n }\n return undefined;\n}\n\n/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */\nfunction exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'\n ? undefined\n : { value: value as Expression, commonjs: false };\n }\n if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;\n const { left, right } = statement.expression;\n const exports =\n left.type === 'MemberExpression' &&\n left.object.type === 'Identifier' &&\n left.object.name === 'module' &&\n left.property.type === 'Identifier' &&\n left.property.name === 'exports';\n if (exports) return { value: right, commonjs: true };\n }\n return undefined;\n}\n\n/**\n * The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its\n * plugin last in the list (`plugins`, `integrations`), or the config wrapped (Next's). Written in the config's quotes,\n * semicolons and line endings.\n */\nexport function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {\n const setup = SETUPS[bundler];\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const exported = exportedOf(program);\n if (exported === undefined) return undefined;\n const eol = eolOf(code);\n const out = new MagicString(code);\n\n if (setup.wrap) {\n out.appendLeft(exported.value.start, `${setup.name}(`);\n out.appendRight(exported.value.end, `, ${setup.value})`);\n } else {\n const object = objectOf(exported.value, program);\n if (object === undefined || !addTo(out, code, object, setup.list!, setup.value, eol)) return undefined;\n }\n\n const lines: [string, string][] = [\n ['{ recommended }', 'deictic/recommended'],\n [`{ ${setup.name} }`, setup.from],\n ];\n addImports(out, program, code, lines, exported.commonjs);\n return out.toString();\n}\n\n/** Adds `value` last in the object's array `list`, or the list with it, as the object is laid out. False where `list` isn't an array. */\nfunction addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string, eol: string): boolean {\n const property = object.properties.find(\n (p) =>\n p.type === 'Property' &&\n !p.computed &&\n ((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),\n );\n if (property !== undefined) {\n if (property.type !== 'Property') return false;\n let array = property.value;\n while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;\n if (array.type !== 'ArrayExpression') return false;\n const last = array.elements.findLast((e) => e !== null);\n if (last == null) {\n out.appendLeft(array.start + 1, value);\n return true;\n }\n const multiline = code.slice(array.start, array.end).includes('\\n');\n out.appendLeft(last.end, multiline ? `,${eol}${indentAt(code, last.start)}${value}` : `, ${value}`);\n return true;\n }\n addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);\n return true;\n}\n\nexport interface InitOptions {\n /** Where it runs: the project is the nearest folder with a package.json. */\n cwd: string;\n /** Installs the packages; false only says the command. */\n install?: boolean;\n /** Adds the skill (true), says how (false), or asks (undefined, on a terminal; says how elsewhere). */\n skill?: boolean;\n /** Says what it would do, and does none of it. */\n dryRun?: boolean;\n log?: (line: string) => void;\n /** Runs a command in the project, and answers whether it succeeded. */\n run?: (command: string, cwd: string) => boolean;\n ask?: (question: string) => Promise<boolean>;\n}\n\nconst runIn = (command: string, cwd: string) => spawnSync(command, { cwd, stdio: 'inherit', shell: true }).status === 0;\n\n/** Sets the project up; throws what to do where it can't. */\nexport async function init(options: InitOptions): Promise<void> {\n const { install = true, dryRun = false, log = console.log, run = runIn } = options;\n const root = rootOf(options.cwd);\n if (root === undefined) throw new Error('deictic: no package.json here or above: run it in your project');\n const manager = packageManager(root);\n const bundler = bundlerOf(root);\n const has = dependenciesOf(root);\n\n const wanted = packagesFor(bundler).filter((p) => !has.has(p));\n const command = installCommand(manager, wanted, root);\n if (wanted.length === 0) {\n log('deictic: its packages are installed');\n } else if (!install || dryRun) {\n log(`deictic: install them with ${command}`);\n } else {\n log(`deictic: ${command}`);\n if (!run(command, root)) throw new Error(`deictic: the install failed: run ${command} yourself, then this again`);\n }\n\n configure(root, bundler, dryRun, log);\n\n const skill = `${runnerOf(manager)} skills add ${existsSync(join(root, 'node_modules', 'deictic')) ? './node_modules/deictic' : 'gkurt/deictic'}`;\n const add =\n options.skill ?? (options.ask === undefined ? false : await options.ask('deictic: add the skill, so your agent works the tasks?'));\n if (!add || dryRun) {\n log(`deictic: to have your agent work the tasks, add the skill: ${skill}`);\n } else {\n log(`deictic: ${skill}`);\n if (!run(skill, root)) log(`deictic: adding the skill failed: run ${skill} yourself`);\n }\n\n log(`deictic: screenshots render in Playwright's Chromium (${runnerOf(manager)} playwright install chromium), else Chrome or Edge`);\n log('deictic: start your dev server and Alt-click an element');\n}\n\n/** Adds deictic to the bundler's config, or says what to add where it can't. */\nfunction configure(root: string, bundler: Bundler | undefined, dryRun: boolean, log: (line: string) => void): void {\n if (bundler === undefined) {\n log('deictic: no bundler it knows in package.json (Vite, Next.js, Astro, webpack, Rspack, Bun): see API.md#bundlers to add it');\n return;\n }\n if (bundler === 'bun') {\n configureBun(root, dryRun, log);\n return;\n }\n const setup = SETUPS[bundler];\n const file = setup.files.map((f) => join(root, f)).find((f) => existsSync(f));\n const imports = `import { recommended } from 'deictic/recommended';\\nimport { ${setup.name} } from '${setup.from}';`;\n if (file === undefined) {\n log(`deictic: no ${setup.files[0]} here: add deictic to your ${bundler} config:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n const name = relative(root, file).replaceAll('\\\\', '/');\n const code = readFileSync(file, 'utf8');\n if (/['\"]deictic\\//.test(code)) {\n log(`deictic: ${name} has it already`);\n return;\n }\n const added = addToConfig(bundler, file, code);\n if (added === undefined) {\n log(`deictic: couldn't tell where it goes in ${name}: add it yourself:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n if (!dryRun) writeFileSync(file, added);\n log(`deictic: ${dryRun ? 'would add' : 'added'} it to ${name}`);\n}\n\n/** Bun's three steps: the plugin's module, bunfig.toml, and its routes in the server. Each says what to add where it can't. */\nfunction configureBun(root: string, dryRun: boolean, log: (line: string) => void): void {\n const write = (file: string, text: string) => !dryRun && writeFileSync(file, text);\n const did = dryRun ? 'would add' : 'added';\n const plugin = join(root, MODULE);\n if (!existsSync(plugin)) {\n write(plugin, PLUGIN);\n log(`deictic: ${dryRun ? 'would write' : 'wrote'} ${MODULE}`);\n } else if (!readFileSync(plugin, 'utf8').includes('deictic/bun')) {\n log(`deictic: ${MODULE} is a module of yours: add deictic by hand, as API.md#bundlers says for Bun`);\n return;\n }\n\n const bunfig = join(root, 'bunfig.toml');\n const before = existsSync(bunfig) ? readFileSync(bunfig, 'utf8') : undefined;\n const after = addToBunfig(before);\n if (after === undefined) {\n log(`deictic: couldn't tell where it goes in bunfig.toml: add it yourself:\\n\\n${BY_HAND.bunfig}\\n`);\n } else if (after === before) {\n log('deictic: bunfig.toml has it already');\n } else {\n write(bunfig, after);\n log(`deictic: ${did} it to bunfig.toml`);\n }\n\n const server = serverOf(root)!;\n const name = relative(root, server).replaceAll('\\\\', '/');\n const code = readFileSync(server, 'utf8');\n if (code.includes(MODULE.replace(/\\.ts$/, ''))) {\n log(`deictic: ${name} has its routes already`);\n return;\n }\n const added = addToServer(server, code, root);\n if (added === undefined) {\n log(`deictic: couldn't tell where its routes go in ${name}: add them yourself:\\n\\n${BY_HAND.server}\\n`);\n return;\n }\n write(server, added);\n log(`deictic: ${did} its routes to ${name}`);\n}\n\nexport const usage = `init [--dry-run] [--no-install] [--skill | --no-skill] sets deictic up in this project\n --dry-run says what it would do, and does none of it\n --no-install doesn't install: says the command instead\n --skill adds the agent skill without asking; --no-skill says the command instead`;\n\n/** Asks a yes-or-no question on the terminal, yes by default. */\nasync function ask(question: string): Promise<boolean> {\n const lines = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return !/^n/i.test((await lines.question(`${question} (Y/n) `)).trim());\n } finally {\n lines.close();\n }\n}\n\nexport async function run(args: string[]): Promise<void> {\n const { values } = parseArgs(args, { 'dry-run': { type: 'boolean' }, install: { type: 'boolean' }, skill: { type: 'boolean' } });\n try {\n await init({\n cwd: process.cwd(),\n install: values.install,\n skill: values.skill,\n dryRun: values['dry-run'],\n ask: process.stdin.isTTY && process.stdout.isTTY ? ask : undefined,\n });\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n }\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,SAAS,SAAkB,KAAK,SAAS,MAAM,IAAI,SAAS;;AAGzE,SAAgB,SAAS,MAAc,QAAwB;CAC7D,MAAM,QAAQ,KAAK,YAAY,MAAM,SAAS,CAAC,IAAI;CACnD,OAAO,UAAU,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,CAAE;AAC5C;;;;;AAMA,SAAgB,WAAW,KAAkB,SAAkB,MAAc,OAA2B,WAAW,OAAa;CAC9H,MAAM,MAAM,MAAM,IAAI;CACtB,MAAM,UAAU,QAAQ,KAAK,QAAQ,MAAM,EAAE,SAAS,mBAAmB;CACzE,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,UAAU,KAAA,IAAY,MAAM,KAAK,MAAM,OAAO;CAC5D,MAAM,OAAO,UAAU,KAAA,KAAa,KAAK,MAAM,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,GAAG,IAAI,MAAM;CACvG,MAAM,KAAK,MAAc,GAAG,QAAQ,IAAI;CACxC,MAAM,OAAO,MACV,KAAK,CAAC,MAAM,UAAW,WAAW,SAAS,KAAK,aAAa,EAAE,IAAI,EAAE,GAAG,SAAS,UAAU,KAAK,QAAQ,EAAE,IAAI,IAAI,MAAO,CAAC,CAC1H,KAAK,GAAG;CACX,MAAM,QAAQ,QAAQ,GAAG,EAAE,KAAK,WAAW,OAAO,CAAC,CAAC,GAAG,EAAE;CACzD,IAAI,UAAU,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AC,GAAG;EAC9C,IAAI,YAAY,KAAK,wBAAwB;EAC7C;CACF;CACA,MAAM,QAAQ,YAAY,QAAQ,MAAM,IAAI;CAC5C,IAAI,UAAU,KAAA,GAAW;EACvB,IAAI,iDAAiD,KAAK,0BAA0B,QAAQ,OAAO,GAAG;EACtG;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,IAAI,YAAY,IAAI,iBAAiB,MAAM;AAC7C;AAEA,MAAa,QAAQ;;;;;AAMrB,eAAe,IAAI,UAAoC;CACrD,MAAM,QAAQ,gBAAgB;EAAE,OAAO,QAAQ;EAAO,QAAQ,QAAQ;CAAO,CAAC;CAC9E,IAAI;EACF,OAAO,CAAC,MAAM,MAAM,MAAM,MAAM,SAAS,GAAG,SAAS,QAAQ,EAAA,CAAG,KAAK,CAAC;CACxE,UAAU;EACR,MAAM,MAAM;CACd;AACF;AAEA,eAAsB,IAAI,MAA+B;CACvD,MAAM,EAAE,WAAW,UAAU,MAAM;EAAE,WAAW,EAAE,MAAM,UAAU;EAAG,SAAS,EAAE,MAAM,UAAU;EAAG,OAAO,EAAE,MAAM,UAAU;CAAE,CAAC;CAC/H,IAAI;EACF,MAAM,KAAK;GACT,KAAK,QAAQ,IAAI;GACjB,SAAS,OAAO;GAChB,OAAO,OAAO;GACd,QAAQ,OAAO;GACf,KAAK,QAAQ,MAAM,SAAS,QAAQ,OAAO,QAAQ,MAAM,KAAA;EAC3D,CAAC;CACH,SAAS,GAAG;EACV,KAAK,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CACjD;AACF"}
1
+ {"version":3,"file":"init.js","names":[],"sources":["../../src/cli/edit.ts","../../src/cli/bun.ts","../../src/cli/init.ts"],"sourcesContent":["/**\n * Editing a project's own source the way it's written: its quotes, semicolons, line endings and indentation. What\n * `init` adds to a bundler's config and to a Bun server goes through here.\n */\nimport type MagicString from 'magic-string';\nimport type { Program } from 'oxc-parser';\n\n/** The file's line ending. */\nexport const eolOf = (code: string) => (code.includes('\\r\\n') ? '\\r\\n' : '\\n');\n\n/** The whitespace a line starts with, for the line `offset` is on. */\nexport function indentAt(code: string, offset: number): string {\n const start = code.lastIndexOf('\\n', offset - 1) + 1;\n return /^[ \\t]*/.exec(code.slice(start))![0];\n}\n\n/**\n * Adds import lines after the module's last import (or `require`, in CommonJS), or at its top: written in the quotes\n * and semicolons of its first import. Each line is `[what, from]`: `import ${what} from '${from}'`, or as a `require`.\n */\nexport function addImports(out: MagicString, program: Program, code: string, lines: [string, string][], commonjs = false): void {\n const eol = eolOf(code);\n const imports = program.body.filter((s) => s.type === 'ImportDeclaration');\n const first = imports[0];\n const quote = first === undefined ? \"'\" : code[first.source.start]!;\n const semi = first === undefined || code.slice(first.start, first.end).trimEnd().endsWith(';') ? ';' : '';\n const q = (s: string) => `${quote}${s}${quote}`;\n const text = lines\n .map(([what, from]) => (commonjs ? `const ${what} = require(${q(from)})${semi}` : `import ${what} from ${q(from)}${semi}`))\n .join(eol);\n const after = imports.at(-1) ?? requiresOf(program).at(-1);\n if (after === undefined) out.prepend(`${text}${eol}${eol}`);\n else out.appendLeft(after.end, `${eol}${text}`);\n}\n\n/** The top-level `const … = require(…)` statements of a CommonJS module, to put new ones after. */\nfunction requiresOf(program: Program) {\n return program.body.filter(\n (s) =>\n s.type === 'VariableDeclaration' &&\n s.declarations.some(\n (d) => d.init?.type === 'CallExpression' && d.init.callee.type === 'Identifier' && d.init.callee.name === 'require',\n ),\n );\n}\n\n/** Inserts `text` as the first property of the object literal that starts at `open` (its `{`), as the object is laid out. */\nexport function addFirst(out: MagicString, code: string, open: number, first: { start: number } | undefined, text: string): void {\n const eol = eolOf(code);\n if (first === undefined) {\n out.appendLeft(open + 1, ` ${text} `);\n return;\n }\n const multiline = code.slice(open, first.start).includes('\\n');\n out.appendLeft(first.start, multiline ? `${text},${eol}${indentAt(code, first.start)}` : `${text}, `);\n}\n","/**\n * `init` for Bun's own dev server: `Bun.serve` with HTML imports, which bundles the page with the plugins bunfig.toml\n * names. Only that: a Bun project that runs Vite, Next.js or another bundler is that bundler's, and one with no HTML\n * imports has no page of Bun's for deictic to be in. Three steps, as the API has them: the plugin's module, bunfig's\n * `[serve.static] plugins`, and its routes spread into `Bun.serve`'s.\n */\nimport { readdirSync, readFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\n\nimport MagicString from 'magic-string';\nimport { type CallExpression, parseSync, Visitor } from 'oxc-parser';\n\nimport { addFirst, addImports, eolOf } from './edit.ts';\n\n/** The plugin's module, from the root, which bunfig names and the server imports. */\nexport const MODULE = 'deictic.plugin.ts';\n\nexport const PLUGIN = `import { deictic } from 'deictic/bun';\nimport { recommended } from 'deictic/recommended';\n\n// One module for both: bunfig.toml names it as the dev server's bundler plugin, and the server spreads its routes,\n// deictic's endpoints, into its own.\nexport default deictic({ plugins: recommended() });\n`;\n\nconst SOURCE = /\\.[cm]?[jt]sx?$/;\nconst SKIP = new Set(['node_modules', 'dist', 'build', 'out']);\nconst SERVE = /\\bBun\\.serve\\s*\\(/;\nconst HTML = /\\bfrom\\s*['\"][^'\"]+\\.html['\"]/;\n\n/**\n * The module that serves the page with Bun's bundler: it calls `Bun.serve` and imports an HTML file. Looked for under\n * the root, not in dependencies, builds or dot folders, a few folders deep.\n */\nexport function serverOf(root: string): string | undefined {\n const walk = (dir: string, depth: number): string | undefined => {\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return undefined;\n }\n for (const e of entries) {\n if (!e.isFile() || !SOURCE.test(e.name)) continue;\n const path = join(dir, e.name);\n const code = readFileSync(path, 'utf8');\n if (SERVE.test(code) && HTML.test(code)) return path;\n }\n if (depth === 0) return undefined;\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.') || SKIP.has(e.name)) continue;\n const found = walk(join(dir, e.name), depth - 1);\n if (found !== undefined) return found;\n }\n return undefined;\n };\n return walk(root, 3);\n}\n\n/**\n * bunfig.toml with the plugin's module first in `[serve.static] plugins` (first, so it sees the source as written),\n * made where there's none; unchanged where it's there already, and nothing where bunfig says it another way (a dotted\n * key, an inline table) and it can't tell where.\n */\nexport function addToBunfig(text: string | undefined, entry = `./${MODULE}`): string | undefined {\n const quoted = JSON.stringify(entry);\n if (text === undefined) return `[serve.static]\\nplugins = [${quoted}]\\n`;\n if (text.includes(entry)) return text;\n if (/serve\\.static\\.|static\\s*=\\s*\\{/.test(text)) return undefined;\n const eol = eolOf(text);\n const header = /^[ \\t]*\\[serve\\.static\\][ \\t]*(#.*)?$/m.exec(text);\n if (header === null)\n return `${text}${text === '' || text.endsWith('\\n') ? '' : eol}${eol}[serve.static]${eol}plugins = [${quoted}]${eol}`;\n const bodyStart = header.index + header[0].length;\n const next = /^[ \\t]*\\[/m.exec(text.slice(bodyStart));\n const body = text.slice(bodyStart, next === null ? text.length : bodyStart + next.index);\n const list = /^[ \\t]*plugins[ \\t]*=[ \\t]*\\[/m.exec(body);\n if (list === null) return `${text.slice(0, bodyStart)}${eol}plugins = [${quoted}]${text.slice(bodyStart)}`;\n const open = bodyStart + list.index + list[0].length;\n const rest = text.slice(open);\n const empty = /^\\s*\\]/.test(rest);\n const lineBreak = /^[ \\t]*\\r?\\n([ \\t]*)/.exec(rest);\n if (empty) return `${text.slice(0, open)}${quoted}${rest.trimStart()}`;\n if (lineBreak !== null) return `${text.slice(0, open)}${eol}${lineBreak[1]}${quoted},${rest}`;\n return `${text.slice(0, open)}${quoted}, ${rest.trimStart()}`;\n}\n\n/**\n * The server with the plugin's routes first in `Bun.serve`'s `routes`, or `routes` with them where it has none, and\n * the module imported: nothing where `Bun.serve` isn't given an object it can see, or its routes aren't one.\n */\nexport function addToServer(file: string, code: string, root: string): string | undefined {\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const calls: CallExpression[] = [];\n new Visitor({\n CallExpression(node) {\n const { callee } = node;\n if (\n callee.type === 'MemberExpression' &&\n callee.object.type === 'Identifier' &&\n callee.object.name === 'Bun' &&\n callee.property.type === 'Identifier' &&\n callee.property.name === 'serve'\n )\n calls.push(node);\n },\n }).visit(program);\n const options = calls.length === 1 ? calls[0]!.arguments[0] : undefined;\n if (options?.type !== 'ObjectExpression') return undefined;\n\n // `tools`, as the API names it, unless the module has a `tools` of its own.\n const name = /\\btools\\b/.test(code) ? 'deicticTools' : 'tools';\n const out = new MagicString(code);\n const routes = options.properties.find(\n (p) => p.type === 'Property' && !p.computed && p.key.type === 'Identifier' && p.key.name === 'routes',\n );\n if (routes === undefined) {\n addFirst(out, code, options.start, options.properties[0], `routes: { ...${name}.routes }`);\n } else {\n if (routes.type !== 'Property' || routes.value.type !== 'ObjectExpression') return undefined;\n addFirst(out, code, routes.value.start, routes.value.properties[0], `...${name}.routes`);\n }\n const from = relative(dirname(file), join(root, MODULE)).replaceAll('\\\\', '/');\n addImports(out, program, code, [[name, from.startsWith('.') ? from : `./${from}`]]);\n return out.toString();\n}\n\n/** What to add by hand, for a server or a bunfig it can't edit. */\nexport const BY_HAND = {\n bunfig: `[serve.static]\\nplugins = [\"./${MODULE}\"]`,\n server: `import tools from './${MODULE}';\\nBun.serve({ routes: { ...tools.routes, '/*': index } });`,\n};\n","/**\n * `deictic init`: the recommended setup in a project, in one step. It installs deictic and what the recommended\n * plugins import, with the project's package manager and as the project's own dev dependencies (deictic, the\n * page's bundle and the skill all find them from the project, so they can't come in through another package), adds\n * deictic to the bundler's config where it can find the place, and offers the agent skill.\n */\nimport { spawnSync } from 'node:child_process';\nimport { existsSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, join, relative } from 'node:path';\nimport { createInterface } from 'node:readline/promises';\n\nimport MagicString from 'magic-string';\nimport { type Expression, type ObjectExpression, parseSync, type Program } from 'oxc-parser';\n\nimport { recommended } from '#src/plugins/recommended/index.ts';\n\nimport { installCommand, packageManager, readJson, runnerOf } from '#src/tools/packages.ts';\n\nimport { fail } from './board.ts';\nimport { addToBunfig, addToServer, BY_HAND, MODULE, PLUGIN, serverOf } from './bun.ts';\nimport { addFirst, addImports } from './edit.ts';\n\nexport type Bundler = 'next' | 'astro' | 'vite' | 'rspack' | 'webpack' | 'bun';\n\ninterface Setup {\n /** The config files it looks for, in order. */\n files: string[];\n /** The module deictic's integration comes from, and its name there. */\n from: string;\n name: string;\n /** What goes in the config: in its `list`, or wrapped around the whole of it with `wrap`. */\n list?: string;\n value: string;\n wrap?: boolean;\n /** The snippet for a config it can't edit. */\n snippet: string;\n}\n\nconst extensions = (base: string) => ['ts', 'mts', 'js', 'mjs', 'cts', 'cjs'].map((e) => `${base}.${e}`);\nconst PLUGINS = '{ plugins: recommended() }';\n\nconst SETUPS: Record<Exclude<Bundler, 'bun'>, Setup> = {\n next: {\n files: extensions('next.config'),\n from: 'deictic/next',\n name: 'withDeictic',\n value: PLUGINS,\n wrap: true,\n snippet: `export default withDeictic(nextConfig, ${PLUGINS});`,\n },\n astro: {\n files: extensions('astro.config'),\n from: 'deictic/astro',\n name: 'deictic',\n list: 'integrations',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ integrations: [deictic(${PLUGINS})] });`,\n },\n vite: {\n files: extensions('vite.config'),\n from: 'deictic/vite',\n name: 'deictic',\n list: 'plugins',\n value: `deictic(${PLUGINS})`,\n snippet: `export default defineConfig({ plugins: [deictic(${PLUGINS}), react()] });`,\n },\n rspack: {\n files: extensions('rspack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n webpack: {\n files: extensions('webpack.config'),\n from: 'deictic/webpack',\n name: 'DeicticPlugin',\n list: 'plugins',\n value: `new DeicticPlugin(${PLUGINS})`,\n snippet: `export default { plugins: [new DeicticPlugin(${PLUGINS})] };`,\n },\n};\n\n/** The project's root: the nearest folder with a package.json, from `dir` up. */\nexport function rootOf(dir: string): string | undefined {\n for (let at = dir; ; at = dirname(at)) {\n if (existsSync(join(at, 'package.json'))) return at;\n if (dirname(at) === at) return undefined;\n }\n}\n\n/** The project's dependencies and dev dependencies, by name. */\nfunction dependenciesOf(root: string): Set<string> {\n const manifest = readJson(join(root, 'package.json')) ?? {};\n return new Set([manifest.dependencies, manifest.devDependencies].flatMap((d) => Object.keys((d as object | undefined) ?? {})));\n}\n\n/** The bundler the project runs its dev server with, from its dependencies, or none deictic knows. */\nexport function bundlerOf(root: string): Bundler | undefined {\n const has = dependenciesOf(root);\n if (has.has('next')) return 'next';\n if (has.has('astro')) return 'astro';\n if (has.has('vite') || SETUPS.vite.files.some((f) => existsSync(join(root, f)))) return 'vite';\n if (has.has('@rspack/core') || has.has('@rspack/cli')) return 'rspack';\n if (has.has('webpack')) return 'webpack';\n // Bun's own bundler only where a server of the project's has it bundle a page: not every project Bun runs.\n if (serverOf(root) !== undefined) return 'bun';\n return undefined;\n}\n\n/** What the recommended setup imports, for the bundler: launch-editor opens files under webpack, which has no launcher. */\nexport function packagesFor(bundler: Bundler | undefined): string[] {\n const plugins = recommended().flatMap((p) => p.packages ?? []);\n return ['deictic', ...plugins, ...(bundler === 'webpack' || bundler === 'rspack' ? ['launch-editor'] : [])];\n}\n\ntype Node = Expression | ObjectExpression;\n\n/**\n * The object an expression comes to: through `defineConfig(…)`, `(…)`, `satisfies`, a function's return and a top-level\n * `const`. Not through another call: in `mergeConfig(base, {…})` or webpack-merge's `merge(common, {…})` the first\n * argument is a base the project may build with too, and the plugin isn't the base's.\n */\nfunction objectOf(node: Node | null | undefined, program: Program, depth = 0): ObjectExpression | undefined {\n if (node == null || depth > 8) return undefined;\n const next = (n: Node | null | undefined) => objectOf(n, program, depth + 1);\n if (node.type === 'ObjectExpression') return node;\n if (node.type === 'ParenthesizedExpression' || node.type === 'TSAsExpression' || node.type === 'TSSatisfiesExpression')\n return next(node.expression);\n if (node.type === 'CallExpression') {\n const { callee } = node;\n const named = (callee.type === 'Identifier' ? callee : callee.type === 'MemberExpression' ? callee.property : undefined) as\n { type: string; name?: string } | undefined;\n const [first] = node.arguments;\n if (named?.name !== 'defineConfig' || first === undefined || first.type === 'SpreadElement') return undefined;\n return next(first);\n }\n if (node.type === 'ArrowFunctionExpression' || node.type === 'FunctionExpression') {\n const body = node.body;\n if (body === null) return undefined;\n if (body.type !== 'BlockStatement') return next(body);\n const returned = body.body.findLast((s) => s.type === 'ReturnStatement');\n return returned?.type === 'ReturnStatement' ? next(returned.argument) : undefined;\n }\n if (node.type !== 'Identifier') return undefined;\n for (const statement of program.body) {\n const declaration = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;\n if (declaration?.type !== 'VariableDeclaration') continue;\n const found = declaration.declarations.find((d) => d.id.type === 'Identifier' && d.id.name === node.name);\n if (found !== undefined) return next(found.init);\n }\n return undefined;\n}\n\n/** The config's exported value: `export default …` or `module.exports = …`, and whether it's CommonJS. */\nfunction exportedOf(program: Program): { value: Expression; commonjs: boolean } | undefined {\n for (const statement of program.body) {\n if (statement.type === 'ExportDefaultDeclaration') {\n const value = statement.declaration;\n return value.type.endsWith('Declaration') && value.type !== 'FunctionDeclaration'\n ? undefined\n : { value: value as Expression, commonjs: false };\n }\n if (statement.type !== 'ExpressionStatement' || statement.expression.type !== 'AssignmentExpression') continue;\n const { left, right } = statement.expression;\n const exports =\n left.type === 'MemberExpression' &&\n left.object.type === 'Identifier' &&\n left.object.name === 'module' &&\n left.property.type === 'Identifier' &&\n left.property.name === 'exports';\n if (exports) return { value: right, commonjs: true };\n }\n return undefined;\n}\n\n/**\n * The config with deictic added, or nothing where it can't tell where: deictic's import beside the config's, and its\n * plugin first in the list (`plugins`, `integrations`), as its marks count lines and columns in the code it's given, or the config wrapped (Next's). Written in the config's quotes,\n * semicolons and line endings.\n */\nexport function addToConfig(bundler: Exclude<Bundler, 'bun'>, file: string, code: string): string | undefined {\n const setup = SETUPS[bundler];\n const { program, errors } = parseSync(file, code, { preserveParens: false });\n if (errors.length > 0) return undefined;\n const exported = exportedOf(program);\n if (exported === undefined) return undefined;\n const out = new MagicString(code);\n\n if (setup.wrap) {\n out.appendLeft(exported.value.start, `${setup.name}(`);\n out.appendRight(exported.value.end, `, ${setup.value})`);\n } else {\n const object = objectOf(exported.value, program);\n if (object === undefined || !addTo(out, code, object, setup.list!, setup.value)) return undefined;\n }\n\n const lines: [string, string][] = [\n ['{ recommended }', 'deictic/recommended'],\n [`{ ${setup.name} }`, setup.from],\n ];\n addImports(out, program, code, lines, exported.commonjs);\n return out.toString();\n}\n\n/**\n * Adds `value` first in the object's array `list`, or the list with it, as the object is laid out. False where `list`\n * isn't an array. First, since a plugin before deictic's that changes a module (both `pre` under Vite) leaves the\n * page's marks pointing at its code, not the file.\n */\nfunction addTo(out: MagicString, code: string, object: ObjectExpression, list: string, value: string): boolean {\n const property = object.properties.find(\n (p) =>\n p.type === 'Property' &&\n !p.computed &&\n ((p.key.type === 'Identifier' && p.key.name === list) || (p.key.type === 'Literal' && p.key.value === list)),\n );\n if (property !== undefined) {\n if (property.type !== 'Property') return false;\n let array = property.value;\n while (array.type === 'TSAsExpression' || array.type === 'TSSatisfiesExpression') array = array.expression;\n if (array.type !== 'ArrayExpression') return false;\n const first = array.elements.find((e) => e !== null);\n if (first == null) {\n out.appendLeft(array.start + 1, value);\n return true;\n }\n addFirst(out, code, array.start, first, value);\n return true;\n }\n addFirst(out, code, object.start, object.properties[0], `${list}: [${value}]`);\n return true;\n}\n\nexport interface InitOptions {\n /** Where it runs: the project is the nearest folder with a package.json. */\n cwd: string;\n /** Installs the packages; false only says the command. */\n install?: boolean;\n /** Adds the skill (true), says how (false), or asks (undefined, on a terminal; says how elsewhere). */\n skill?: boolean;\n /** Says what it would do, and does none of it. */\n dryRun?: boolean;\n log?: (line: string) => void;\n /** Runs a command in the project, and answers whether it succeeded. */\n run?: (command: string, cwd: string) => boolean;\n ask?: (question: string) => Promise<boolean>;\n}\n\nconst runIn = (command: string, cwd: string) => spawnSync(command, { cwd, stdio: 'inherit', shell: true }).status === 0;\n\n/** Sets the project up; throws what to do where it can't. */\nexport async function init(options: InitOptions): Promise<void> {\n const { install = true, dryRun = false, log = console.log, run = runIn } = options;\n const root = rootOf(options.cwd);\n if (root === undefined) throw new Error('deictic: no package.json here or above: run it in your project');\n const manager = packageManager(root);\n const bundler = bundlerOf(root);\n const has = dependenciesOf(root);\n\n const wanted = packagesFor(bundler).filter((p) => !has.has(p));\n const command = installCommand(manager, wanted, root);\n if (wanted.length === 0) {\n log('deictic: its packages are installed');\n } else if (!install || dryRun) {\n log(`deictic: install them with ${command}`);\n } else {\n log(`deictic: ${command}`);\n if (!run(command, root)) throw new Error(`deictic: the install failed: run ${command} yourself, then this again`);\n }\n\n configure(root, bundler, dryRun, log);\n\n const skill = `${runnerOf(manager)} skills add ${existsSync(join(root, 'node_modules', 'deictic')) ? './node_modules/deictic' : 'gkurt/deictic'}`;\n const add =\n options.skill ?? (options.ask === undefined ? false : await options.ask('deictic: add the skill, so your agent works the tasks?'));\n if (!add || dryRun) {\n log(`deictic: to have your agent work the tasks, add the skill: ${skill}`);\n } else {\n log(`deictic: ${skill}`);\n if (!run(skill, root)) log(`deictic: adding the skill failed: run ${skill} yourself`);\n }\n\n log(`deictic: screenshots render in Playwright's Chromium (${runnerOf(manager)} playwright install chromium), else Chrome or Edge`);\n log('deictic: start your dev server and Alt-click an element');\n}\n\n/** Adds deictic to the bundler's config, or says what to add where it can't. */\nfunction configure(root: string, bundler: Bundler | undefined, dryRun: boolean, log: (line: string) => void): void {\n if (bundler === undefined) {\n log('deictic: no bundler it knows in package.json (Vite, Next.js, Astro, webpack, Rspack, Bun): see API.md#bundlers to add it');\n return;\n }\n if (bundler === 'bun') {\n configureBun(root, dryRun, log);\n return;\n }\n const setup = SETUPS[bundler];\n const file = setup.files.map((f) => join(root, f)).find((f) => existsSync(f));\n const imports = `import { recommended } from 'deictic/recommended';\\nimport { ${setup.name} } from '${setup.from}';`;\n if (file === undefined) {\n log(`deictic: no ${setup.files[0]} here: add deictic to your ${bundler} config:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n const name = relative(root, file).replaceAll('\\\\', '/');\n const code = readFileSync(file, 'utf8');\n if (/['\"]deictic\\//.test(code)) {\n log(`deictic: ${name} has it already`);\n return;\n }\n const added = addToConfig(bundler, file, code);\n if (added === undefined) {\n log(`deictic: couldn't tell where it goes in ${name}: add it yourself:\\n\\n${imports}\\n${setup.snippet}\\n`);\n return;\n }\n if (!dryRun) writeFileSync(file, added);\n log(`deictic: ${dryRun ? 'would add' : 'added'} it to ${name}`);\n}\n\n/** Bun's three steps: the plugin's module, bunfig.toml, and its routes in the server. Each says what to add where it can't. */\nfunction configureBun(root: string, dryRun: boolean, log: (line: string) => void): void {\n const write = (file: string, text: string) => !dryRun && writeFileSync(file, text);\n const did = dryRun ? 'would add' : 'added';\n const plugin = join(root, MODULE);\n if (!existsSync(plugin)) {\n write(plugin, PLUGIN);\n log(`deictic: ${dryRun ? 'would write' : 'wrote'} ${MODULE}`);\n } else if (!readFileSync(plugin, 'utf8').includes('deictic/bun')) {\n log(`deictic: ${MODULE} is a module of yours: add deictic by hand, as API.md#bundlers says for Bun`);\n return;\n }\n\n const bunfig = join(root, 'bunfig.toml');\n const before = existsSync(bunfig) ? readFileSync(bunfig, 'utf8') : undefined;\n const after = addToBunfig(before);\n if (after === undefined) {\n log(`deictic: couldn't tell where it goes in bunfig.toml: add it yourself:\\n\\n${BY_HAND.bunfig}\\n`);\n } else if (after === before) {\n log('deictic: bunfig.toml has it already');\n } else {\n write(bunfig, after);\n log(`deictic: ${did} it to bunfig.toml`);\n }\n\n const server = serverOf(root)!;\n const name = relative(root, server).replaceAll('\\\\', '/');\n const code = readFileSync(server, 'utf8');\n if (code.includes(MODULE.replace(/\\.ts$/, ''))) {\n log(`deictic: ${name} has its routes already`);\n return;\n }\n const added = addToServer(server, code, root);\n if (added === undefined) {\n log(`deictic: couldn't tell where its routes go in ${name}: add them yourself:\\n\\n${BY_HAND.server}\\n`);\n return;\n }\n write(server, added);\n log(`deictic: ${did} its routes to ${name}`);\n}\n\n/** Asks a yes-or-no question on the terminal, yes by default. */\nasync function ask(question: string): Promise<boolean> {\n const lines = createInterface({ input: process.stdin, output: process.stdout });\n try {\n return !/^n/i.test((await lines.question(`${question} (Y/n) `)).trim());\n } finally {\n lines.close();\n }\n}\n\nexport async function run(values: { dryRun?: boolean; install: boolean; skill?: boolean }): Promise<void> {\n try {\n await init({\n cwd: process.cwd(),\n install: values.install,\n skill: values.skill,\n dryRun: values.dryRun,\n ask: process.stdin.isTTY && process.stdout.isTTY ? ask : undefined,\n });\n } catch (e) {\n fail(e instanceof Error ? e.message : String(e));\n }\n}\n"],"mappings":";;;;;;;;;;;AAQA,MAAa,SAAS,SAAkB,KAAK,SAAS,MAAM,IAAI,SAAS;;AAGzE,SAAgB,SAAS,MAAc,QAAwB;CAC7D,MAAM,QAAQ,KAAK,YAAY,MAAM,SAAS,CAAC,IAAI;CACnD,OAAO,UAAU,KAAK,KAAK,MAAM,KAAK,CAAC,CAAC,CAAE;AAC5C;;;;;AAMA,SAAgB,WAAW,KAAkB,SAAkB,MAAc,OAA2B,WAAW,OAAa;CAC9H,MAAM,MAAM,MAAM,IAAI;CACtB,MAAM,UAAU,QAAQ,KAAK,QAAQ,MAAM,EAAE,SAAS,mBAAmB;CACzE,MAAM,QAAQ,QAAQ;CACtB,MAAM,QAAQ,UAAU,KAAA,IAAY,MAAM,KAAK,MAAM,OAAO;CAC5D,MAAM,OAAO,UAAU,KAAA,KAAa,KAAK,MAAM,MAAM,OAAO,MAAM,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,SAAS,GAAG,IAAI,MAAM;CACvG,MAAM,KAAK,MAAc,GAAG,QAAQ,IAAI;CACxC,MAAM,OAAO,MACV,KAAK,CAAC,MAAM,UAAW,WAAW,SAAS,KAAK,aAAa,EAAE,IAAI,EAAE,GAAG,SAAS,UAAU,KAAK,QAAQ,EAAE,IAAI,IAAI,MAAO,CAAC,CAC1H,KAAK,GAAG;CACX,MAAM,QAAQ,QAAQ,GAAG,EAAE,KAAK,WAAW,OAA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AAA,GAAW;EACvB,IAAI,iDAAiD,KAAK,0BAA0B,QAAQ,OAAO,GAAG;EACtG;CACF;CACA,MAAM,QAAQ,KAAK;CACnB,IAAI,YAAY,IAAI,iBAAiB,MAAM;AAC7C;;AAGA,eAAe,IAAI,UAAoC;CACrD,MAAM,QAAQ,gBAAgB;EAAE,OAAO,QAAQ;EAAO,QAAQ,QAAQ;CAAO,CAAC;CAC9E,IAAI;EACF,OAAO,CAAC,MAAM,MAAM,MAAM,MAAM,SAAS,GAAG,SAAS,QAAQ,EAAA,CAAG,KAAK,CAAC;CACxE,UAAU;EACR,MAAM,MAAM;CACd;AACF;AAEA,eAAsB,IAAI,QAAgF;CACxG,IAAI;EACF,MAAM,KAAK;GACT,KAAK,QAAQ,IAAI;GACjB,SAAS,OAAO;GAChB,OAAO,OAAO;GACd,QAAQ,OAAO;GACf,KAAK,QAAQ,MAAM,SAAS,QAAQ,OAAO,QAAQ,MAAM,KAAA;EAC3D,CAAC;CACH,SAAS,GAAG;EACV,KAAK,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,CAAC;CACjD;AACF"}
@@ -114,6 +114,7 @@ function runningAt(file) {
114
114
  return;
115
115
  }
116
116
  }
117
+ /** Whether the process is running. */
117
118
  function alive(pid) {
118
119
  try {
119
120
  process.kill(pid, 0);
@@ -160,6 +161,6 @@ async function gone(url) {
160
161
  for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) if (!await answers(url)) return;
161
162
  throw new Error(`the board at ${url} is still running: stop it, then restart the dev server`);
162
163
  }
163
- export { vbScript as i, localBoard as n, runningAt as r, local as t };
164
+ export { vbScript as a, runningAt as i, local as n, localBoard as r, alive as t };
164
165
 
165
166
  //# sourceMappingURL=local.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"local.js","names":[],"sources":["../../src/plugins/tasks/local.ts"],"sourcesContent":["/**\n * The board tasks go to when nothing names one: `vb serve`, `@vercel/board`'s own, started with the dev server\n * and stopped with it, its log in `.deictic/board`. So Alt-click adds a task with nothing else to run, and\n * whoever works the tasks reaches the same board at the URL `.deictic/board.json` holds.\n */\nimport { type ChildProcess, spawn } from 'node:child_process';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { createServer } from 'node:net';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** `vb serve`'s own default, so `http://127.0.0.1:4100/api/board` is the board wherever it's free. */\nconst PORT = 4100;\n/** How long a board may take to answer after it's started, or to be gone after it's stopped. */\nconst PATIENCE = 20_000;\n\nexport interface LocalOptions {\n /**\n * 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\n * the only one tried: taken, the board doesn't start.\n */\n port?: number;\n /** Where its log is kept, from the project's root: `.deictic/board` by default. */\n dir?: string;\n /** `false` for no pages of the board's own (its inspector): the panel then links its tasks nowhere. */\n inspect?: boolean;\n /** More arguments for `vb serve`, as it takes them: `['--tailscale', 'box.tailnet.ts.net']`. */\n args?: string[];\n}\n\n/** What `local()` answers, for the tasks plugin's `board` option. */\nexport interface LocalBoard {\n local: LocalOptions;\n}\n\n/**\n * The project's own board on this machine, as the tasks plugin's `board`: what it uses anyway with no\n * `BOARD_URL`, here whatever the environment says, and with options.\n */\nexport const local = (options: LocalOptions = {}): LocalBoard => ({ local: options });\n\n/** What `.deictic/board.json` holds: the board the dev server started, for whoever works its tasks. */\nexport interface Running {\n url: string;\n pid: number;\n /** The options it was started with, as one string to compare: other ones need another board. */\n as: string;\n}\n\nexport interface Local {\n url: string;\n /** Whether this call started it, rather than found it running. */\n fresh: boolean;\n /** Where its log is. */\n dir: string;\n /** Stops the board, where this call started it: one found running is left to what started it. */\n stop: () => void;\n}\n\n/**\n * The project's own board, started unless it's running: a dev server that restarts in its process (Vite, when\n * its config changes) asks again, and so does a second dev server of the same project, and two boards mustn't\n * write one log. One running with other options is stopped first, for the same reason.\n */\nexport async function localBoard(root: string, options: LocalOptions = {}): Promise<Local> {\n const file = keptIn(root, 'board.json');\n const dir = options.dir === undefined ? keptIn(root, 'board') : resolve(root, options.dir);\n const flags = [...(options.inspect === false ? ['--no-inspect'] : []), ...(options.args ?? [])];\n const as = JSON.stringify([options.port ?? null, dir, flags]);\n\n const running = runningAt(file);\n if (running !== undefined && alive(running.pid) && (await answers(running.url))) {\n if (running.as === as) return { url: running.url, fresh: false, dir, stop: () => {} };\n process.kill(running.pid);\n await gone(running.url);\n }\n\n const port = options.port ?? (await free(PORT));\n const url = `http://127.0.0.1:${port}/api/board`;\n const script = vbScript();\n if (script === undefined) throw new Error('@vercel/board is missing: add it to your devDependencies');\n const child = spawn(process.execPath, [script, 'serve', '--port', String(port), '--no-open', '--dir', dir, ...flags], {\n stdio: ['ignore', 'ignore', 'pipe'],\n });\n let said = '';\n child.stderr.on('data', (chunk: Buffer) => (said += chunk.toString()));\n const stop = () => void child.kill();\n process.once('exit', stop);\n\n try {\n await started(child, url);\n } catch (e) {\n stop();\n const fix = options.port === undefined ? 'set BOARD_URL to a board of your own' : `is port ${port} taken? name another, or none`;\n throw new Error(`the board didn't start (${said.trim() || (e as Error).message}): ${fix}`, { cause: e });\n }\n writeFileSync(file, `${JSON.stringify({ url, pid: child.pid, as }, null, 2)}\\n`);\n // The board ends with this process, and mustn't be what keeps it from ending.\n child.unref();\n (child.stderr as { unref?: () => void }).unref?.();\n return { url, fresh: true, dir, stop };\n}\n\n/**\n * `vb`'s script in the project's `@vercel/board`, by its `bin`, to run with this process's own runtime: no shim, no\n * shell. Nothing where it isn't installed.\n */\nexport function vbScript(): string | undefined {\n try {\n const manifest = createRequire(import.meta.url).resolve('@vercel/board/package.json');\n const { bin } = JSON.parse(readFileSync(manifest, 'utf8')) as { bin?: string | { vb?: string } };\n const entry = typeof bin === 'string' ? bin : bin?.vb;\n return entry === undefined ? undefined : join(dirname(manifest), entry);\n } catch {\n return undefined;\n }\n}\n\n/** What a `.deictic/board.json` says, where it says it. */\nexport function runningAt(file: string): Running | undefined {\n try {\n const { url, pid, as } = JSON.parse(readFileSync(file, 'utf8')) as Partial<Running>;\n return typeof url === 'string' && typeof pid === 'number' ? { url, pid, as: as ?? '' } : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Whether a board answers there: its discovery, which names its own URL. */\nasync function answers(url: string): Promise<boolean> {\n try {\n const res = await fetch(url, { signal: AbortSignal.timeout(2000) });\n return res.ok && ((await res.json()) as { url?: unknown }).url === url;\n } catch {\n return false;\n }\n}\n\n/** `wanted` where nothing listens on it (another project's board may), or else a port the system picks. */\nasync function free(wanted: number): Promise<number> {\n const listen = (port: number) =>\n new Promise<number>((done, failed) => {\n const server = createServer();\n server.once('error', failed);\n server.listen(port, '127.0.0.1', () => {\n const { port: got } = server.address() as { port: number };\n server.close(() => done(got));\n });\n });\n return listen(wanted).catch(() => listen(0));\n}\n\nconst nap = () => new Promise((wake) => setTimeout(wake, 100));\n\n/** Waits for the board to answer, or for its process to end without having. */\nasync function started(child: ChildProcess, url: string): Promise<void> {\n let ended: string | undefined;\n child.once('error', (e) => (ended = e.message));\n child.once('exit', (code) => (ended ??= `exit ${code}`));\n for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) {\n if (ended !== undefined) throw new Error(ended);\n if (await answers(url)) return;\n }\n throw new Error(`no answer at ${url} after ${PATIENCE / 1000}s`);\n}\n\n/** Waits for a stopped board to let go of its port and its log. */\nasync function gone(url: string): Promise<void> {\n for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) if (!(await answers(url))) return;\n\n throw new Error(`the board at ${url} is still running: stop it, then restart the dev server`);\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,OAAO;;AAEb,MAAM,WAAW;;;;;AAyBjB,MAAa,SAAS,UAAwB,CAAC,OAAmB,EAAE,OAAO,QAAQ;;;;;;AAyBnF,eAAsB,WAAW,MAAc,UAAwB,CAAC,GAAmB;CACzF,MAAM,OAAO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,WAAW;EACpC,MAAM,SAAS,aAAa;EAC5B,OAAO,KAAK,SAAS,MAAM;EAC3B,OAAO,OAAO,MAAM,mBAAmB;GACrC,MAAM,EAAE,MAAM,QAAQ,OAAO,QAAQ;GACrC,OAAO,YAAY,KAAK,GAAG,CAAC;EAC9B,CAAC;CACH,CAAC;CACH,OAAO,OAAO,MAAM,CAAC,CAAC,YAAY,OAAO,CAAC,CAAC;AAC7C;AAEA,MAAM,YAAY,IAAI,SAAS,SAAS,WAAW,MAAM,GAAG,CAAC;;AAG7D,eAAe,QAAQ,OAAqB,KAA4B;CACtE,IAAI;CACJ,MAAM,KAAK,UAAU,MAAO,QAAQ,EAAE,OAAQ;CAC9C,MAAM,KAAK,SAAS,SAAU,UAAU,QAAQ,MAAO;CACvD,KAAK,MAAM,QAAQ,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,GAAG;EACzE,IAAI,UAAU,KAAA,GAAW,MAAM,IAAI,MAAM,KAAK;EAC9C,IAAI,MAAM,QAAQ,GAAG,GAAG;CAC1B;CACA,MAAM,IAAI,MAAM,gBAAgB,IAAI,SAAS,WAAW,IAAK,EAAE;AACjE;;AAGA,eAAe,KAAK,KAA4B;CAC9C,KAAK,MAAM,QAAQ,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,GAAG,IAAI,CAAE,MAAM,QAAQ,GAAG,GAAI;CAEtG,MAAM,IAAI,MAAM,gBAAgB,IAAI,wDAAwD;AAC9F"}
1
+ {"version":3,"file":"local.js","names":[],"sources":["../../src/plugins/tasks/local.ts"],"sourcesContent":["/**\n * The board tasks go to when nothing names one: `vb serve`, `@vercel/board`'s own, started with the dev server\n * and stopped with it, its log in `.deictic/board`. So Alt-click adds a task with nothing else to run, and\n * whoever works the tasks reaches the same board at the URL `.deictic/board.json` holds.\n */\nimport { type ChildProcess, spawn } from 'node:child_process';\nimport { readFileSync, writeFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { createServer } from 'node:net';\nimport { dirname, join, resolve } from 'node:path';\n\nimport { keptIn } from '#src/tools/kept.ts';\n\n/** `vb serve`'s own default, so `http://127.0.0.1:4100/api/board` is the board wherever it's free. */\nconst PORT = 4100;\n/** How long a board may take to answer after it's started, or to be gone after it's stopped. */\nconst PATIENCE = 20_000;\n\nexport interface LocalOptions {\n /**\n * 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\n * the only one tried: taken, the board doesn't start.\n */\n port?: number;\n /** Where its log is kept, from the project's root: `.deictic/board` by default. */\n dir?: string;\n /** `false` for no pages of the board's own (its inspector): the panel then links its tasks nowhere. */\n inspect?: boolean;\n /** More arguments for `vb serve`, as it takes them: `['--tailscale', 'box.tailnet.ts.net']`. */\n args?: string[];\n}\n\n/** What `local()` answers, for the tasks plugin's `board` option. */\nexport interface LocalBoard {\n local: LocalOptions;\n}\n\n/**\n * The project's own board on this machine, as the tasks plugin's `board`: what it uses anyway with no\n * `BOARD_URL`, here whatever the environment says, and with options.\n */\nexport const local = (options: LocalOptions = {}): LocalBoard => ({ local: options });\n\n/** What `.deictic/board.json` holds: the board the dev server started, for whoever works its tasks. */\nexport interface Running {\n url: string;\n pid: number;\n /** The options it was started with, as one string to compare: other ones need another board. */\n as: string;\n}\n\nexport interface Local {\n url: string;\n /** Whether this call started it, rather than found it running. */\n fresh: boolean;\n /** Where its log is. */\n dir: string;\n /** Stops the board, where this call started it: one found running is left to what started it. */\n stop: () => void;\n}\n\n/**\n * The project's own board, started unless it's running: a dev server that restarts in its process (Vite, when\n * its config changes) asks again, and so does a second dev server of the same project, and two boards mustn't\n * write one log. One running with other options is stopped first, for the same reason.\n */\nexport async function localBoard(root: string, options: LocalOptions = {}): Promise<Local> {\n const file = keptIn(root, 'board.json');\n const dir = options.dir === undefined ? keptIn(root, 'board') : resolve(root, options.dir);\n const flags = [...(options.inspect === false ? ['--no-inspect'] : []), ...(options.args ?? [])];\n const as = JSON.stringify([options.port ?? null, dir, flags]);\n\n const running = runningAt(file);\n if (running !== undefined && alive(running.pid) && (await answers(running.url))) {\n if (running.as === as) return { url: running.url, fresh: false, dir, stop: () => {} };\n process.kill(running.pid);\n await gone(running.url);\n }\n\n const port = options.port ?? (await free(PORT));\n const url = `http://127.0.0.1:${port}/api/board`;\n const script = vbScript();\n if (script === undefined) throw new Error('@vercel/board is missing: add it to your devDependencies');\n const child = spawn(process.execPath, [script, 'serve', '--port', String(port), '--no-open', '--dir', dir, ...flags], {\n stdio: ['ignore', 'ignore', 'pipe'],\n });\n let said = '';\n child.stderr.on('data', (chunk: Buffer) => (said += chunk.toString()));\n const stop = () => void child.kill();\n process.once('exit', stop);\n\n try {\n await started(child, url);\n } catch (e) {\n stop();\n const fix = options.port === undefined ? 'set BOARD_URL to a board of your own' : `is port ${port} taken? name another, or none`;\n throw new Error(`the board didn't start (${said.trim() || (e as Error).message}): ${fix}`, { cause: e });\n }\n writeFileSync(file, `${JSON.stringify({ url, pid: child.pid, as }, null, 2)}\\n`);\n // The board ends with this process, and mustn't be what keeps it from ending.\n child.unref();\n (child.stderr as { unref?: () => void }).unref?.();\n return { url, fresh: true, dir, stop };\n}\n\n/**\n * `vb`'s script in the project's `@vercel/board`, by its `bin`, to run with this process's own runtime: no shim, no\n * shell. Nothing where it isn't installed.\n */\nexport function vbScript(): string | undefined {\n try {\n const manifest = createRequire(import.meta.url).resolve('@vercel/board/package.json');\n const { bin } = JSON.parse(readFileSync(manifest, 'utf8')) as { bin?: string | { vb?: string } };\n const entry = typeof bin === 'string' ? bin : bin?.vb;\n return entry === undefined ? undefined : join(dirname(manifest), entry);\n } catch {\n return undefined;\n }\n}\n\n/** What a `.deictic/board.json` says, where it says it. */\nexport function runningAt(file: string): Running | undefined {\n try {\n const { url, pid, as } = JSON.parse(readFileSync(file, 'utf8')) as Partial<Running>;\n return typeof url === 'string' && typeof pid === 'number' ? { url, pid, as: as ?? '' } : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Whether the process is running. */\nexport function alive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/** Whether a board answers there: its discovery, which names its own URL. */\nasync function answers(url: string): Promise<boolean> {\n try {\n const res = await fetch(url, { signal: AbortSignal.timeout(2000) });\n return res.ok && ((await res.json()) as { url?: unknown }).url === url;\n } catch {\n return false;\n }\n}\n\n/** `wanted` where nothing listens on it (another project's board may), or else a port the system picks. */\nasync function free(wanted: number): Promise<number> {\n const listen = (port: number) =>\n new Promise<number>((done, failed) => {\n const server = createServer();\n server.once('error', failed);\n server.listen(port, '127.0.0.1', () => {\n const { port: got } = server.address() as { port: number };\n server.close(() => done(got));\n });\n });\n return listen(wanted).catch(() => listen(0));\n}\n\nconst nap = () => new Promise((wake) => setTimeout(wake, 100));\n\n/** Waits for the board to answer, or for its process to end without having. */\nasync function started(child: ChildProcess, url: string): Promise<void> {\n let ended: string | undefined;\n child.once('error', (e) => (ended = e.message));\n child.once('exit', (code) => (ended ??= `exit ${code}`));\n for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) {\n if (ended !== undefined) throw new Error(ended);\n if (await answers(url)) return;\n }\n throw new Error(`no answer at ${url} after ${PATIENCE / 1000}s`);\n}\n\n/** Waits for a stopped board to let go of its port and its log. */\nasync function gone(url: string): Promise<void> {\n for (const until = Date.now() + PATIENCE; Date.now() < until; await nap()) if (!(await answers(url))) return;\n\n throw new Error(`the board at ${url} is still running: stop it, then restart the dev server`);\n}\n"],"mappings":";;;;;;;;;;;;;AAcA,MAAM,OAAO;;AAEb,MAAM,WAAW;;;;;AAyBjB,MAAa,SAAS,UAAwB,CAAC,OAAmB,EAAE,OAAO,QAAQ;;;;;;AAyBnF,eAAsB,WAAW,MAAc,UAAwB,CAAC,GAAmB;CACzF,MAAM,OAAO,OAAO,MAAM,YAAY;CACtC,MAAM,MAAM,QAAQ,QAAQ,KAAA,IAAY,OAAO,MAAM,OAAO,IAAI,QAAQ,MAAM,QAAQ,GAAG;CAC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,MAAM,QAAQ,OAAO,QAAQ;GACrC,OAAO,YAAY,KAAK,GAAG,CAAC;EAC9B,CAAC;CACH,CAAC;CACH,OAAO,OAAO,MAAM,CAAC,CAAC,YAAY,OAAO,CAAC,CAAC;AAC7C;AAEA,MAAM,YAAY,IAAI,SAAS,SAAS,WAAW,MAAM,GAAG,CAAC;;AAG7D,eAAe,QAAQ,OAAqB,KAA4B;CACtE,IAAI;CACJ,MAAM,KAAK,UAAU,MAAO,QAAQ,EAAE,OAAQ;CAC9C,MAAM,KAAK,SAAS,SAAU,UAAU,QAAQ,MAAO;CACvD,KAAK,MAAM,QAAQ,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,GAAG;EACzE,IAAI,UAAU,KAAA,GAAW,MAAM,IAAI,MAAM,KAAK;EAC9C,IAAI,MAAM,QAAQ,GAAG,GAAG;CAC1B;CACA,MAAM,IAAI,MAAM,gBAAgB,IAAI,SAAS,WAAW,IAAK,EAAE;AACjE;;AAGA,eAAe,KAAK,KAA4B;CAC9C,KAAK,MAAM,QAAQ,KAAK,IAAI,IAAI,UAAU,KAAK,IAAI,IAAI,OAAO,MAAM,IAAI,GAAG,IAAI,CAAE,MAAM,QAAQ,GAAG,GAAI;CAEtG,MAAM,IAAI,MAAM,gBAAgB,IAAI,wDAAwD;AAC9F"}
@@ -3,7 +3,7 @@ import { createRequire } from "node:module";
3
3
  import { dirname, join } from "node:path";
4
4
  // package.json
5
5
  var name = "deictic";
6
- var version = "0.4.0";
6
+ var version = "0.6.0";
7
7
  var peerDependencies = {
8
8
  "@rrweb/rrweb-plugin-console-record": "^2.2.2",
9
9
  "@rrweb/rrweb-plugin-network-record": "^2.2.2",
@@ -93,6 +93,13 @@ const runnerOf = (manager) => ({
93
93
  yarn: "npx",
94
94
  bun: "bunx"
95
95
  })[manager];
96
+ /** What runs a CLI the project installed, for the manager: `npx`, `bunx`, each the project's own version. */
97
+ const execOf = (manager) => ({
98
+ npm: "npx",
99
+ pnpm: "pnpm exec",
100
+ yarn: "yarn",
101
+ bun: "bunx"
102
+ })[manager];
96
103
  /** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */
97
104
  function installed(root, name) {
98
105
  try {
@@ -120,6 +127,6 @@ function missingMessage(root, plugins) {
120
127
  const which = gone.map((g) => g.plugin);
121
128
  return `deictic: install what ${which.length === 1 ? which[0] : `${which.slice(0, -1).join(", ")} and ${which.at(-1)}`} ${which.length === 1 ? "needs" : "need"}: ${installCommand(packageManager(root), names, root)}`;
122
129
  }
123
- export { runnerOf as a, readJson as i, missingMessage as n, packageManager as r, installCommand as t };
130
+ export { readJson as a, packageManager as i, installCommand as n, runnerOf as o, missingMessage as r, execOf as t };
124
131
 
125
132
  //# sourceMappingURL=packages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"packages.js","names":["name","manifest.name","manifest.version","manifest.peerDependencies"],"sources":["../../package.json","../../src/tools/packages.ts"],"sourcesContent":["","/**\n * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,\n * or a plugin's own), and how to install them with the project's package manager. A missing one is said as the dev\n * server starts, with the command that installs it, not on the first shot or recording, where it would fail.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nimport manifest from '#package.json' with { type: 'json' };\nimport type { ServerPlugin } from '#src/index.ts';\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';\n\n/** Each package manager's lockfiles, in the order they're looked for in a folder. */\nconst LOCKS: [string, PackageManager][] = [\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['package-lock.json', 'npm'],\n];\nconst MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];\n\n/**\n * The project's package manager: its `packageManager` field, or the lockfile nearest the root (a workspace's is\n * above it), or the one running this (`npm_config_user_agent`), or npm. The lockfile wins over what runs this,\n * as `npx deictic init` runs under npm in a project of any manager's.\n */\nexport function packageManager(root: string, agent = process.env.npm_config_user_agent): PackageManager {\n for (let dir = root; ; dir = dirname(dir)) {\n const field = fieldOf(dir);\n if (field !== undefined) return field;\n const lock = LOCKS.find(([file]) => existsSync(join(dir, file)));\n if (lock !== undefined) return lock[1];\n if (dirname(dir) === dir) break;\n }\n const running = agent?.split('/')[0];\n return MANAGERS.find((m) => m === running) ?? 'npm';\n}\n\n/** A package.json's `packageManager` (`pnpm@9.1.0`), by its manager's name. */\nfunction fieldOf(dir: string): PackageManager | undefined {\n const field = readJson(join(dir, 'package.json'))?.packageManager;\n const name = typeof field === 'string' ? field.split('@')[0] : undefined;\n return MANAGERS.find((m) => m === name);\n}\n\nexport function readJson(path: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A package as the install command names it: with deictic's range for it where it's one of deictic's peers (rrweb's\n * packages must agree), or deictic's own version for deictic. Quoted, as `>` and `^` are a shell's.\n */\nexport function specOf(name: string): string {\n const range = name === manifest.name ? `^${manifest.version}` : (manifest.peerDependencies as Record<string, string>)[name];\n return range === undefined ? name : `\"${name}@${range}\"`;\n}\n\n/** The command that adds `names` to the project's dev dependencies. A pnpm workspace's root takes them only with `-w`. */\nexport function installCommand(manager: PackageManager, names: readonly string[], root: string): string {\n const add = {\n npm: 'npm install -D',\n pnpm: existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm add -D -w' : 'pnpm add -D',\n yarn: 'yarn add -D',\n bun: 'bun add -d',\n }[manager];\n return [add, ...names.map(specOf)].join(' ');\n}\n\n/** What runs a package's CLI without installing it, for the manager: `npx`, `bunx`. */\nexport const runnerOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm dlx', yarn: 'npx', bun: 'bunx' })[manager];\n\n/** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */\nexport function installed(root: string, name: string): boolean {\n try {\n createRequire(join(root, 'package.json')).resolve(`${name}/package.json`);\n return true;\n } catch (e) {\n // There, but its `exports` don't name its package.json: only \"not found\" means it's missing.\n return (e as { code?: string }).code !== 'MODULE_NOT_FOUND';\n }\n}\n\n/** Each plugin with the packages it imports that the project hasn't installed, where it has any. */\nexport function missing(root: string, plugins: readonly ServerPlugin[]): { plugin: string; packages: string[] }[] {\n return plugins.flatMap(({ name, packages = [] }) => {\n const gone = packages.filter((p) => !installed(root, p));\n return gone.length === 0 ? [] : [{ plugin: name, packages: gone }];\n });\n}\n\n/** What to say as the dev server starts when plugins' packages are missing: which, and the command that installs them. */\nexport function missingMessage(root: string, plugins: readonly ServerPlugin[]): string | undefined {\n const gone = missing(root, plugins);\n if (gone.length === 0) return undefined;\n const names = [...new Set(gone.flatMap((g) => g.packages))];\n const which = gone.map((g) => g.plugin);\n const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(', ')} and ${which.at(-1)}`;\n return `deictic: install what ${who} ${which.length === 1 ? 'needs' : 'need'}: ${installCommand(packageManager(root), names, root)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACeA,MAAM,QAAoC;CACxC,CAAC,YAAY,KAAK;CAClB,CAAC,aAAa,KAAK;CACnB,CAAC,kBAAkB,MAAM;CACzB,CAAC,aAAa,MAAM;CACpB,CAAC,qBAAqB,KAAK;AAC7B;AACA,MAAM,WAA6B;CAAC;CAAO;CAAQ;CAAQ;AAAK;;;;;;AAOhE,SAAgB,eAAe,MAAc,QAAQ,QAAQ,IAAI,uBAAuC;CACtG,KAAK,IAAI,MAAM,OAAQ,MAAM,QAAQ,GAAG,GAAG;EACzC,MAAM,QAAQ,QAAQ,GAAG;EACzB,IAAI,UAAU,KAAA,GAAW,OAAO;EAChC,MAAM,OAAO,MAAM,MAAM,CAAC,UAAU,WAAW,KAAK,KAAK,IAAI,CAAC,CAAC;EAC/D,IAAI,SAAS,KAAA,GAAW,OAAO,KAA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,QAAQ;EAClD,MAAM,OAAO,SAAS,QAAQ,MAAM,CAAC,UAAU,MAAM,CAAC,CAAC;EACvD,OAAO,KAAK,WAAW,IAAI,CAAC,IAAI,CAAC;GAAE,QAAQ;GAAM,UAAU;EAAK,CAAC;CACnE,CAAC;AACH;;AAGA,SAAgB,eAAe,MAAc,SAAsD;CACjG,MAAM,OAAO,QAAQ,MAAM,OAAO;CAClC,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAC9B,MAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,KAAK,SAAS,MAAM,EAAE,QAAQ,CAAC,CAAC;CAC1D,MAAM,QAAQ,KAAK,KAAK,MAAM,EAAE,MAAM;CAEtC,OAAO,yBADK,MAAM,WAAW,IAAI,MAAM,KAAK,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,MAAM,GAAG,EAAE,IAC3D,GAAG,MAAM,WAAW,IAAI,UAAU,OAAO,IAAI,eAAe,eAAe,IAAI,GAAG,OAAO,IAAI;AACnI"}
1
+ {"version":3,"file":"packages.js","names":["name","manifest.name","manifest.version","manifest.peerDependencies"],"sources":["../../package.json","../../src/tools/packages.ts"],"sourcesContent":["","/**\n * The packages plugins import that the project installs itself (`ServerPlugin.packages`: deictic's optional peers,\n * or a plugin's own), and how to install them with the project's package manager. A missing one is said as the dev\n * server starts, with the command that installs it, not on the first shot or recording, where it would fail.\n */\nimport { existsSync, readFileSync } from 'node:fs';\nimport { createRequire } from 'node:module';\nimport { dirname, join } from 'node:path';\n\nimport manifest from '#package.json' with { type: 'json' };\nimport type { ServerPlugin } from '#src/index.ts';\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn' | 'bun';\n\n/** Each package manager's lockfiles, in the order they're looked for in a folder. */\nconst LOCKS: [string, PackageManager][] = [\n ['bun.lock', 'bun'],\n ['bun.lockb', 'bun'],\n ['pnpm-lock.yaml', 'pnpm'],\n ['yarn.lock', 'yarn'],\n ['package-lock.json', 'npm'],\n];\nconst MANAGERS: PackageManager[] = ['npm', 'pnpm', 'yarn', 'bun'];\n\n/**\n * The project's package manager: its `packageManager` field, or the lockfile nearest the root (a workspace's is\n * above it), or the one running this (`npm_config_user_agent`), or npm. The lockfile wins over what runs this,\n * as `npx deictic init` runs under npm in a project of any manager's.\n */\nexport function packageManager(root: string, agent = process.env.npm_config_user_agent): PackageManager {\n for (let dir = root; ; dir = dirname(dir)) {\n const field = fieldOf(dir);\n if (field !== undefined) return field;\n const lock = LOCKS.find(([file]) => existsSync(join(dir, file)));\n if (lock !== undefined) return lock[1];\n if (dirname(dir) === dir) break;\n }\n const running = agent?.split('/')[0];\n return MANAGERS.find((m) => m === running) ?? 'npm';\n}\n\n/** A package.json's `packageManager` (`pnpm@9.1.0`), by its manager's name. */\nfunction fieldOf(dir: string): PackageManager | undefined {\n const field = readJson(join(dir, 'package.json'))?.packageManager;\n const name = typeof field === 'string' ? field.split('@')[0] : undefined;\n return MANAGERS.find((m) => m === name);\n}\n\nexport function readJson(path: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(readFileSync(path, 'utf8')) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/**\n * A package as the install command names it: with deictic's range for it where it's one of deictic's peers (rrweb's\n * packages must agree), or deictic's own version for deictic. Quoted, as `>` and `^` are a shell's.\n */\nexport function specOf(name: string): string {\n const range = name === manifest.name ? `^${manifest.version}` : (manifest.peerDependencies as Record<string, string>)[name];\n return range === undefined ? name : `\"${name}@${range}\"`;\n}\n\n/** The command that adds `names` to the project's dev dependencies. A pnpm workspace's root takes them only with `-w`. */\nexport function installCommand(manager: PackageManager, names: readonly string[], root: string): string {\n const add = {\n npm: 'npm install -D',\n pnpm: existsSync(join(root, 'pnpm-workspace.yaml')) ? 'pnpm add -D -w' : 'pnpm add -D',\n yarn: 'yarn add -D',\n bun: 'bun add -d',\n }[manager];\n return [add, ...names.map(specOf)].join(' ');\n}\n\n/** What runs a package's CLI without installing it, for the manager: `npx`, `bunx`. */\nexport const runnerOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm dlx', yarn: 'npx', bun: 'bunx' })[manager];\n\n/** What runs a CLI the project installed, for the manager: `npx`, `bunx`, each the project's own version. */\nexport const execOf = (manager: PackageManager) => ({ npm: 'npx', pnpm: 'pnpm exec', yarn: 'yarn', bun: 'bunx' })[manager];\n\n/** Whether the project can import `name`: it's found from the root, as the bundler and deictic's own imports find it. */\nexport function installed(root: string, name: string): boolean {\n try {\n createRequire(join(root, 'package.json')).resolve(`${name}/package.json`);\n return true;\n } catch (e) {\n // There, but its `exports` don't name its package.json: only \"not found\" means it's missing.\n return (e as { code?: string }).code !== 'MODULE_NOT_FOUND';\n }\n}\n\n/** Each plugin with the packages it imports that the project hasn't installed, where it has any. */\nexport function missing(root: string, plugins: readonly ServerPlugin[]): { plugin: string; packages: string[] }[] {\n return plugins.flatMap(({ name, packages = [] }) => {\n const gone = packages.filter((p) => !installed(root, p));\n return gone.length === 0 ? [] : [{ plugin: name, packages: gone }];\n });\n}\n\n/** What to say as the dev server starts when plugins' packages are missing: which, and the command that installs them. */\nexport function missingMessage(root: string, plugins: readonly ServerPlugin[]): string | undefined {\n const gone = missing(root, plugins);\n if (gone.length === 0) return undefined;\n const names = [...new Set(gone.flatMap((g) => g.packages))];\n const which = gone.map((g) => g.plugin);\n const who = which.length === 1 ? which[0] : `${which.slice(0, -1).join(', ')} and ${which.at(-1)}`;\n return `deictic: install what ${who} ${which.length === 1 ? 'needs' : 'need'}: ${installCommand(packageManager(root), names, root)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACeA,MAAM,QAAoC;CACxC,CAAC,YAAY,KAAK;CAClB,CAAC,aAAa,KAAK;CACnB,CAAC,kBAAkB,MAAM;CACzB,CAAC,aAAa,MAAM;CACpB,CAAC,qBAAqB,KAAK;AAC7B;AACA,MAAM,WAA6B;CAAC;CAAO;CAAQ;CAAQ;AAAK;;;;;;AAOhE,S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K;AAAO,EAAA,CAAG;;AAGlH,MAAa,UAAU,aAA6B;CAAE,KAAK;CAAO,MAAM;CAAa,MAAM;CAAQ,KAAK;AAAO,EAAA,CAAG;;AAGlH,SAAgB,UAAU,MAAc,MAAuB;CAC7D,IAAI;EACF,cAAc,KAAK,MAAM,cAAc,CAAC,CAAC,CAAC,QAAQ,GAAG,KAAK,cAAc;EACxE,OAAO;CACT,SAAS,GAAG;EAEV,OAAQ,EAAwB,SAAS;CAC3C;AACF;;AAGA,SAAgB,QAAQ,MAAc,SAA4E;CAChH,OAAO,QAAQ,SAAS,EAAE,MAAM,WAAW,CAAC,QAAQ;EAClD,MAAM,OAAO,SAAS,QAAQ,MAAM,CAAC,UAAU,MAAM,CAAC,CAAC;EACvD,OAAO,KAAK,WAAW,IAAI,CAAC,IAAI,CAAC;GAAE,QAAQ;GAAM,UAAU;EAAK,CAAC;CACnE,CAAC;AACH;;AAGA,SAAgB,eAAe,MAAc,SAAsD;CACjG,MAAM,OAAO,QAAQ,MAAM,OAAO;CAClC,IAAI,KAAK,WAAW,GAAG,OAAO,KAAA;CAC9B,MAAM,QAAQ,CAAC,GAAG,IAAI,IAAI,KAAK,SAAS,MAAM,EAAE,QAAQ,CAAC,CAAC;CAC1D,MAAM,QAAQ,KAAK,KAAK,MAAM,EAAE,MAAM;CAEtC,OAAO,yBADK,MAAM,WAAW,IAAI,MAAM,KAAK,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,OAAO,MAAM,GAAG,EAAE,IAC3D,GAAG,MAAM,WAAW,IAAI,UAAU,OAAO,IAAI,eAAe,eAAe,IAAI,GAAG,OAAO,IAAI;AACnI"}
@@ -1,12 +1,6 @@
1
- import { a as clock, l as fail, t as ME, u as parseArgs } from "./board.js";
1
+ import { a as clock, l as fail, t as ME } from "./board.js";
2
2
  import { r as loadRecording } from "./find.js";
3
3
  // src/cli/recording.ts
4
- const usage = `recording <task | replay URL | recording ID | file> [--nth 2] [--json] a recording as a timeline
5
- --only console,request these kinds of line (also page, click, input, scroll, resize, marks, voice)
6
- --problems errors, warnings and requests that failed
7
- --from 10 --to 15 a stretch, in seconds; --around 12 is the 3 seconds either side
8
- --grep text lines with this in them, in any case
9
- --full all of each line: where it was logged from, a request's headers and bodies`;
10
4
  const round = Math.round;
11
5
  /** The marks, as data where the recording has it. */
12
6
  function shapeOf({ shape }) {
@@ -233,25 +227,8 @@ function timelineOf(events, voice) {
233
227
  for (const c of voice) push(c.at, "voice", `clip ${c.id}, ${clock(c.duration)} long, until ${clock(c.at + c.duration)}`);
234
228
  return timeline.sort((a, b) => a.t - b.t);
235
229
  }
236
- async function run(args) {
237
- const { values, positionals } = parseArgs(args, {
238
- nth: {
239
- type: "string",
240
- default: "1"
241
- },
242
- json: { type: "boolean" },
243
- only: {
244
- type: "string",
245
- multiple: true
246
- },
247
- problems: { type: "boolean" },
248
- from: { type: "string" },
249
- to: { type: "string" },
250
- around: { type: "string" },
251
- grep: { type: "string" },
252
- full: { type: "boolean" }
253
- });
254
- const { kept, id, replay, task } = await loadRecording(positionals[0], Number(values.nth));
230
+ async function run(named, values) {
231
+ const { kept, id, replay, task } = await loadRecording(named, Number(values.nth));
255
232
  const events = kept.events;
256
233
  if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);
257
234
  const timeline = timelineOf(events, kept.voice ?? []);
@@ -311,6 +288,6 @@ async function run(args) {
311
288
  const ref = task?.id ?? id;
312
289
  console.log(`\n${problems} problem${problems === 1 ? "" : "s"}: --problems lists them, --around <seconds> shows what led to one, and ${ME} frame ${ref} --at <seconds> the page then.`);
313
290
  }
314
- export { run, usage };
291
+ export { run };
315
292
 
316
293
  //# sourceMappingURL=recording.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"recording.js","names":[],"sources":["../../src/cli/recording.ts"],"sourcesContent":["/**\n * `deictic recording`: a recording as a timeline: the page, each click and field typed in (with the element's place\n * in the source), scrolls, resizes, each change to the marks (what was drawn, where, and the notes' text), the voice\n * clips, the page's console and its requests where the project records them, and the end. Or the part of it asked\n * for: `--only`, `--problems`, `--from`, `--to`, `--around`, `--grep`, and `--full` for all of each line.\n */\nimport type { Shape } from '#src/plugins/annotations/index.ts';\n\nimport { clock, fail, ME, parseArgs } from './board.ts';\nimport { loadRecording } from './find.ts';\n\nexport const usage = `recording <task | replay URL | recording ID | file> [--nth 2] [--json] a recording as a timeline\n --only console,request these kinds of line (also page, click, input, scroll, resize, marks, voice)\n --problems errors, warnings and requests that failed\n --from 10 --to 15 a stretch, in seconds; --around 12 is the 3 seconds either side\n --grep text lines with this in them, in any case\n --full all of each line: where it was logged from, a request's headers and bodies`;\n\n/** A node of rrweb's snapshot. */\ninterface SnapNode {\n id: number;\n type: number;\n tagName?: string;\n textContent?: string;\n attributes?: Record<string, string>;\n childNodes?: SnapNode[];\n}\n\ninterface Known extends Omit<SnapNode, 'childNodes'> {\n parent: number | undefined;\n kids: number[];\n}\n\n/** A request rrweb's network plugin kept. */\ninterface Request {\n name: string;\n method?: string;\n initiatorType?: string;\n status?: number;\n duration?: number;\n requestHeaders?: Record<string, string>;\n responseHeaders?: Record<string, string>;\n requestBody?: string;\n responseBody?: string;\n}\n\n/** What rrweb's events carry that the timeline reads: each kind has some of it. */\ninterface Data {\n href?: string;\n width?: number;\n height?: number;\n node?: SnapNode;\n tag?: string;\n plugin?: string;\n payload?: {\n annotations?: Annotation[];\n svg?: string;\n href?: string;\n level?: string;\n payload?: string[];\n trace?: string[];\n requests?: Request[];\n isInitial?: boolean;\n };\n source?: number;\n type?: number;\n id?: number;\n x?: number;\n y?: number;\n adds?: { node: SnapNode; parentId: number }[];\n attributes?: { id: number; attributes: Record<string, string> }[];\n texts?: { id: number; value: string }[];\n isChecked?: boolean;\n text?: string;\n}\n\ninterface Event {\n type: number;\n timestamp: number;\n data: Data;\n}\n\ninterface Annotation {\n id?: string;\n shape: Shape;\n}\n\ninterface Line {\n t: number;\n at: string;\n kind: string;\n text: string;\n problem?: boolean;\n trace?: string[];\n request?: Request;\n before?: string;\n marks?: Shape[];\n node?: number;\n}\n\ntype Point = { x: number; y: number };\n\nconst round = Math.round;\n\n/** The marks, as data where the recording has it. */\nfunction shapeOf({ shape }: Annotation): string {\n const bounds = (points: Point[]) => {\n const xs = points.map((p) => p.x);\n const ys = points.map((p) => p.y);\n return `(${round(Math.min(...xs))},${round(Math.min(...ys))})–(${round(Math.max(...xs))},${round(Math.max(...ys))})`;\n };\n if (shape.kind === 'box') return `box ${bounds([shape, { x: shape.x + shape.width, y: shape.y + shape.height }])}`;\n if (shape.kind === 'arrow')\n return `arrow from (${round(shape.from.x)},${round(shape.from.y)}) to (${round(shape.to.x)},${round(shape.to.y)})`;\n if (shape.kind === 'pen') return `pen stroke over ${bounds(shape.points)}`;\n return `note at (${round(shape.at.x)},${round(shape.at.y)}): ${JSON.stringify(shape.text)}`;\n}\n\nconst pairs = (s: string): Point[] => [...s.matchAll(/(-?[\\d.]+)[ ,](-?[\\d.]+)/g)].map((m) => ({ x: Number(m[1]), y: Number(m[2]) }));\n\n/** The marks read off the SVG, for a recording older than the marks as data. */\nfunction shapesInSvg(svg: string): Annotation[] {\n const out: Annotation[] = [];\n const unescape = (t: string) => t.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '\"').replaceAll('&amp;', '&');\n for (const [, tag, attrs = '', inner = ''] of svg.matchAll(/<(rect|path|polyline|text)\\b([^>]*)>(?:(.*?)<\\/text>)?/g)) {\n const num = (name: string) => Number(new RegExp(`\\\\b${name}=\"(-?[\\\\d.]+)\"`).exec(attrs)?.[1]);\n if (tag === 'rect' && attrs.includes('fill=\"none\"'))\n out.push({ shape: { kind: 'box', x: num('x'), y: num('y'), width: num('width'), height: num('height') } });\n if (tag === 'path') {\n const [from, to] = pairs(/d=\"([^\"]*)\"/.exec(attrs)?.[1] ?? '');\n if (from !== undefined && to !== undefined) out.push({ shape: { kind: 'arrow', from, to } });\n }\n if (tag === 'polyline') out.push({ shape: { kind: 'pen', points: pairs(/points=\"([^\"]*)\"/.exec(attrs)?.[1] ?? '') } });\n if (tag === 'text') {\n const lines = [...inner.matchAll(/<tspan[^>]*>(.*?)<\\/tspan>/g)].map((l) => unescape(l[1] ?? ''));\n const xy = /x=\"(-?[\\d.]+)\" y=\"(-?[\\d.]+)\"/.exec(inner);\n out.push({ shape: { kind: 'note', at: { x: Number(xy?.[1] ?? 0), y: Number(xy?.[2] ?? 0) }, text: lines.join('\\n') } });\n }\n }\n return out;\n}\n\n/** The page's nodes by rrweb's IDs, from the full snapshot and each mutation: enough to name an element. */\nclass Nodes {\n #nodes = new Map<number, Known>();\n\n clear(): void {\n this.#nodes.clear();\n }\n\n add(node: SnapNode, parent: number | undefined): void {\n const { childNodes = [], ...rest } = node;\n this.#nodes.set(node.id, { ...rest, parent, kids: childNodes.map((c) => c.id) });\n for (const c of childNodes) this.add(c, node.id);\n }\n\n get(id: number): Known | undefined {\n return this.#nodes.get(id);\n }\n\n text(id: number, max = 60): string {\n let out = '';\n const walk = (n: number) => {\n const node = this.#nodes.get(n);\n if (node === undefined || out.length > max) return;\n if (node.type === 3) out += node.textContent ?? '';\n for (const k of node.kids) walk(k);\n };\n walk(id);\n const text = out.replace(/\\s+/g, ' ').trim();\n return text.length > max ? `${text.slice(0, max)}…` : text;\n }\n\n /** `<button> \"Save\" at src/App.tsx:9:7`: the element, its text, and the nearest place deictic marked. */\n describe(id: number | undefined): string {\n const node = id === undefined ? undefined : this.#nodes.get(id);\n if (id === undefined || node === undefined) return `node ${id}`;\n if (node.type === 0) return 'the page';\n let at: string | undefined;\n for (\n let n: Known | undefined = node;\n n !== undefined && at === undefined;\n n = n.parent === undefined ? undefined : this.#nodes.get(n.parent)\n )\n at = n.attributes?.['data-deictic'];\n const tag = node.tagName === undefined ? 'text' : `<${node.tagName}>`;\n const text = this.text(id);\n return `${tag}${text ? ` \"${text}\"` : ''}${at === undefined ? '' : ` at ${at}`}`;\n }\n}\n\n/** The page's console's arguments, each as JSON: a string without its quotes. */\nconst plain = (arg: string) => {\n try {\n const value: unknown = JSON.parse(arg);\n return typeof value === 'string' ? value : arg;\n } catch {\n return arg;\n }\n};\n\n/** Every line of the recording, in time. */\nfunction timelineOf(events: Event[], voice: { id: string; at: number; duration: number }[]): Line[] {\n const t0 = events[0]!.timestamp;\n const timeline: Line[] = [];\n const nodes = new Nodes();\n const push = (t: number, kind: string, text: string, extra: Partial<Line> = {}) =>\n timeline.push({ t, at: clock(t), kind, text, ...extra });\n let marks: Annotation[] = [];\n let scroll: { t: number; id: number | undefined; x: number; y: number } | undefined;\n let typing: { t: number; id: number | undefined; value: string } | undefined;\n const flushScroll = () => {\n if (scroll) push(scroll.t, 'scroll', `${nodes.describe(scroll.id)} to (${scroll.x},${scroll.y})`);\n scroll = undefined;\n };\n const flushTyping = () => {\n if (typing) push(typing.t, 'input', `${nodes.describe(typing.id)}: ${typing.value}`);\n typing = undefined;\n };\n\n for (const e of events) {\n const t = e.timestamp - t0;\n const d = e.data;\n const payload = d.payload ?? {};\n if (e.type === 4) push(t, 'page', `${d.href} at ${d.width}×${d.height}`);\n if (e.type === 2 && d.node !== undefined) {\n nodes.clear();\n nodes.add(d.node, undefined);\n }\n if (e.type === 5 && d.tag === 'deictic.annotations') {\n const now = payload.annotations ?? shapesInSvg(payload.svg ?? '');\n const key = (a: Annotation) => a.id ?? JSON.stringify(a.shape);\n const before = new Set(marks.map(key));\n const after = new Set(now.map(key));\n const added = now.filter((a) => !before.has(key(a)));\n const removed = marks.filter((a) => !after.has(key(a)));\n if (added.length > 0 || removed.length > 0) {\n const text = [...added.map((a) => `+ ${shapeOf(a)}`), ...removed.map((a) => `− ${shapeOf(a)}`)].join('; ');\n push(t, 'marks', text, { marks: now.map((a) => a.shape) });\n }\n marks = now;\n }\n // The address changed with no load: a route of the app's.\n if (e.type === 5 && d.tag === 'deictic.page') push(t, 'page', `${payload.href} (a route change, no load)`);\n // The page's console, and errors nothing caught (rrweb's console plugin), and where it was logged from, which goes\n // under a warning or an error.\n if (e.type === 6 && d.plugin === 'rrweb/console@1') {\n const level = payload.level ?? 'log';\n push(t, `console.${level}`, (payload.payload ?? []).map(plain).join(' '), {\n trace: payload.trace ?? [],\n ...(['error', 'assert', 'warn'].includes(level) ? { problem: true } : {}),\n });\n }\n // The page's requests (rrweb's network plugin), masked as they were kept: each as it ended. One the browser\n // reported of itself has no method; headers and bodies, where kept, are in `--json`.\n if (e.type === 6 && d.plugin === 'rrweb/network@1') {\n for (const r of payload.requests ?? []) {\n const took = r.duration !== undefined && Number.isFinite(r.duration) ? ` in ${round(r.duration)} ms` : '';\n const status = r.status === undefined || r.status === 0 ? 'no status (failed, blocked, or another origin’s)' : r.status;\n push(t, 'request', `${r.method ?? r.initiatorType ?? ''} ${r.name} → ${status}${took}`.trim(), {\n request: r,\n ...((r.status ?? 0) >= 400 ? { problem: true } : {}),\n ...(payload.isInitial === true ? { before: 'made as the page loaded, before this moment' } : {}),\n });\n }\n }\n if (e.type === 5 && d.tag === 'deictic.end') push(t, 'end', 'recording stopped');\n if (e.type !== 3) continue;\n if (d.source === 0) {\n for (const a of d.adds ?? []) nodes.add(a.node, a.parentId);\n for (const a of d.attributes ?? []) {\n const node = nodes.get(a.id);\n if (node) node.attributes = { ...node.attributes, ...a.attributes };\n }\n for (const x of d.texts ?? []) {\n const node = nodes.get(x.id);\n if (node) node.textContent = x.value;\n }\n }\n if (d.source === 2 && (d.type === 2 || d.type === 3 || d.type === 4)) {\n flushScroll();\n flushTyping();\n const what = { 2: 'click', 3: 'right-click', 4: 'double-click' }[d.type];\n // A click a key made (Enter on a button) has no position.\n const where = d.x === 0 && d.y === 0 ? ' by keyboard' : ` at (${round(d.x ?? 0)},${round(d.y ?? 0)}) in the viewport`;\n push(t, what, `${nodes.describe(d.id)}${where}`, { node: d.id });\n }\n if (d.source === 3) {\n if (scroll && scroll.id !== d.id) flushScroll();\n scroll = { t: scroll?.t ?? t, id: d.id, x: round(d.x ?? 0), y: round(d.y ?? 0) };\n }\n if (d.source === 4) push(t, 'resize', `viewport ${d.width}×${d.height}`);\n if (d.source === 5) {\n if (typing && typing.id !== d.id) flushTyping();\n const value = d.isChecked !== undefined && d.text === undefined ? String(d.isChecked) : JSON.stringify(d.text);\n typing = { t: typing?.t ?? t, id: d.id, value };\n }\n }\n flushScroll();\n flushTyping();\n for (const c of voice) push(c.at, 'voice', `clip ${c.id}, ${clock(c.duration)} long, until ${clock(c.at + c.duration)}`);\n return timeline.sort((a, b) => a.t - b.t);\n}\n\nexport async function run(args: string[]): Promise<void> {\n const { values, positionals } = parseArgs(args, {\n nth: { type: 'string', default: '1' },\n json: { type: 'boolean' },\n only: { type: 'string', multiple: true },\n problems: { type: 'boolean' },\n from: { type: 'string' },\n to: { type: 'string' },\n around: { type: 'string' },\n grep: { type: 'string' },\n full: { type: 'boolean' },\n });\n const { kept, id, replay, task } = await loadRecording(positionals[0], Number(values.nth));\n const events = kept.events as Event[];\n if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);\n const timeline = timelineOf(events, kept.voice ?? []);\n\n // The part asked for. Seconds, as the replay's `?t=` and `frame --at` take them.\n const seconds = (name: 'from' | 'to' | 'around') => {\n const given = values[name];\n if (given === undefined) return undefined;\n const value = Number(given);\n if (!Number.isFinite(value)) fail(`--${name} takes seconds from the recording's start, as 12 or 4.5: not ${given}`);\n return value * 1000;\n };\n const around = seconds('around');\n const from = seconds('from') ?? (around === undefined ? undefined : around - 3000);\n const to = seconds('to') ?? (around === undefined ? undefined : around + 3000);\n const only = (values.only ?? []).flatMap((list) => list.split(',')).filter(Boolean);\n const grep = values.grep?.toLowerCase();\n // `console` is every level's lines, `click` a right or a double one too.\n const isKind = (kind: string, asked: string) => kind === asked || kind.startsWith(`${asked}.`) || kind.endsWith(`-${asked}`);\n const shown = timeline.filter(\n (e) =>\n (only.length === 0 || only.some((asked) => isKind(e.kind, asked))) &&\n (values.problems !== true || e.problem === true) &&\n (from === undefined || e.t >= from) &&\n (to === undefined || e.t <= to) &&\n (grep === undefined || `${e.kind} ${e.text}`.toLowerCase().includes(grep)),\n );\n\n const colorScheme = kept.colorScheme ?? 'light';\n const startedAt = new Date(kept.startedAt ?? events[0]!.timestamp).toISOString();\n if (values.json) {\n const head = { id, page: kept.page, viewport: kept.viewport, colorScheme, startedAt, duration: kept.duration, replay, task: task?.id };\n console.log(JSON.stringify({ ...head, lines: timeline.length, timeline: shown }, null, 2));\n return;\n }\n console.log(`Recording ${id}${task ? ` on task #${task.id}` : ''}: ${clock(kept.duration)} of ${kept.page}`);\n console.log(`viewport ${kept.viewport.width}×${kept.viewport.height}, ${colorScheme}, started ${startedAt}`);\n if (replay !== undefined) console.log(`replays at ${replay} (add ?t=<seconds> to open it paused there)`);\n if (shown.length < timeline.length) console.log(`${shown.length} of its ${timeline.length} lines, as asked`);\n console.log();\n const under = (line: string) => console.log(`${' '.repeat(22)}${line}`);\n for (const e of shown) {\n console.log(`${e.at.padStart(6)} ${e.kind.padEnd(13)} ${e.text}`);\n // Where a warning or an error came from, its nearest few places: all of them, and every line's, with `--full`.\n if (e.trace && (values.full === true || e.problem === true))\n for (const line of values.full ? e.trace : e.trace.slice(0, 5)) under(`at ${line}`);\n if (values.full !== true || e.request === undefined) continue;\n const r = e.request;\n if (e.before !== undefined) under(e.before);\n for (const [title, held] of [\n ['request headers', r.requestHeaders],\n ['response headers', r.responseHeaders],\n ] as const)\n for (const [name, value] of Object.entries(held ?? {})) under(`${title} ${name}: ${value}`);\n if (r.requestBody !== undefined) under(`request body ${r.requestBody}`);\n if (r.responseBody !== undefined) under(`response body ${r.responseBody}`);\n }\n if (shown.length === 0) console.log(timeline.length === 0 ? 'Nothing in it.' : 'No line of it is what was asked for.');\n // Where something went wrong, how to get to it: what led up to it, and what the page looked like.\n const problems = timeline.filter((e) => e.problem === true).length;\n if (problems === 0 || shown.length < timeline.length) return;\n const ref = task?.id ?? id;\n console.log(\n `\\n${problems} problem${problems === 1 ? '' : 's'}: --problems lists them, --around <seconds> shows what led to one, and ${ME}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SAAS,QAAQ,EAAE,YAAY,OACpD,KAAK,MAAM,QAAQ,OAAO,OAAO,EAAE,QAAQ,EAAE,MAAM,MAAM,GAAG,CAAC,GAAG,MAAM,MAAM,MAAM;EACpF,IAAI,OAAO,SAAS,QAAQ,EAAE,YAAY,KAAA,GAAW;EACrD,MAAM,IAAI,EAAE;EACZ,IAAI,EAAE,WAAW,KAAA,GAAW,MAAM,EAAE,MAAM;EAC1C,KAAK,MAAM,CAAC,OAAO,SAAS,CAC1B,CAAC,mBAAmB,EAAE,cAAc,GACpC,CAAC,oBAAoB,EAAE,eAAe,CACxC,GACE,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,QAAQ,CAAC,CAAC,GAAG,MAAM,GAAG,MAAM,IAAI,KAAK,IAAI,OAAO;EAC7F,IAAI,EAAE,gBAAgB,KAAA,GAAW,MAAM,iBAAiB,EAAE,aAAa;EACvE,IAAI,EAAE,iBAAiB,KAAA,GAAW,MAAM,kBAAkB,EAAE,cAAc;CAC5E;CACA,IAAI,MAAM,WAAW,GAAG,QAAQ,IAAI,SAAS,WAAW,IAAI,mBAAmB,sCAAsC;CAErH,MAAM,WAAW,SAAS,QAAQ,MAAM,EAAE,YAAY,IAAI,CAAC,CAAC;CAC5D,IAAI,aAAa,KAAK,MAAM,SAAS,SAAS,QAAQ;CACtD,MAAM,MAAM,MAAM,MAAM;CACxB,QAAQ,IACN,KAAK,SAAS,UAAU,aAAa,IAAI,KAAK,IAAI,yEAAyE,GAAG,SAAS,IAAI,+BAC7I;AACF"}
1
+ {"version":3,"file":"recording.js","names":[],"sources":["../../src/cli/recording.ts"],"sourcesContent":["/**\n * `deictic recording`: a recording as a timeline: the page, each click and field typed in (with the element's place\n * in the source), scrolls, resizes, each change to the marks (what was drawn, where, and the notes' text), the voice\n * clips, the page's console and its requests where the project records them, and the end. Or the part of it asked\n * for: `--only`, `--problems`, `--from`, `--to`, `--around`, `--grep`, and `--full` for all of each line.\n */\nimport type { Shape } from '#src/plugins/annotations/index.ts';\n\nimport { clock, fail, ME } from './board.ts';\nimport { loadRecording } from './find.ts';\n\n/** A node of rrweb's snapshot. */\ninterface SnapNode {\n id: number;\n type: number;\n tagName?: string;\n textContent?: string;\n attributes?: Record<string, string>;\n childNodes?: SnapNode[];\n}\n\ninterface Known extends Omit<SnapNode, 'childNodes'> {\n parent: number | undefined;\n kids: number[];\n}\n\n/** A request rrweb's network plugin kept. */\ninterface Request {\n name: string;\n method?: string;\n initiatorType?: string;\n status?: number;\n duration?: number;\n requestHeaders?: Record<string, string>;\n responseHeaders?: Record<string, string>;\n requestBody?: string;\n responseBody?: string;\n}\n\n/** What rrweb's events carry that the timeline reads: each kind has some of it. */\ninterface Data {\n href?: string;\n width?: number;\n height?: number;\n node?: SnapNode;\n tag?: string;\n plugin?: string;\n payload?: {\n annotations?: Annotation[];\n svg?: string;\n href?: string;\n level?: string;\n payload?: string[];\n trace?: string[];\n requests?: Request[];\n isInitial?: boolean;\n };\n source?: number;\n type?: number;\n id?: number;\n x?: number;\n y?: number;\n adds?: { node: SnapNode; parentId: number }[];\n attributes?: { id: number; attributes: Record<string, string> }[];\n texts?: { id: number; value: string }[];\n isChecked?: boolean;\n text?: string;\n}\n\ninterface Event {\n type: number;\n timestamp: number;\n data: Data;\n}\n\ninterface Annotation {\n id?: string;\n shape: Shape;\n}\n\ninterface Line {\n t: number;\n at: string;\n kind: string;\n text: string;\n problem?: boolean;\n trace?: string[];\n request?: Request;\n before?: string;\n marks?: Shape[];\n node?: number;\n}\n\ntype Point = { x: number; y: number };\n\nconst round = Math.round;\n\n/** The marks, as data where the recording has it. */\nfunction shapeOf({ shape }: Annotation): string {\n const bounds = (points: Point[]) => {\n const xs = points.map((p) => p.x);\n const ys = points.map((p) => p.y);\n return `(${round(Math.min(...xs))},${round(Math.min(...ys))})–(${round(Math.max(...xs))},${round(Math.max(...ys))})`;\n };\n if (shape.kind === 'box') return `box ${bounds([shape, { x: shape.x + shape.width, y: shape.y + shape.height }])}`;\n if (shape.kind === 'arrow')\n return `arrow from (${round(shape.from.x)},${round(shape.from.y)}) to (${round(shape.to.x)},${round(shape.to.y)})`;\n if (shape.kind === 'pen') return `pen stroke over ${bounds(shape.points)}`;\n return `note at (${round(shape.at.x)},${round(shape.at.y)}): ${JSON.stringify(shape.text)}`;\n}\n\nconst pairs = (s: string): Point[] => [...s.matchAll(/(-?[\\d.]+)[ ,](-?[\\d.]+)/g)].map((m) => ({ x: Number(m[1]), y: Number(m[2]) }));\n\n/** The marks read off the SVG, for a recording older than the marks as data. */\nfunction shapesInSvg(svg: string): Annotation[] {\n const out: Annotation[] = [];\n const unescape = (t: string) => t.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '\"').replaceAll('&amp;', '&');\n for (const [, tag, attrs = '', inner = ''] of svg.matchAll(/<(rect|path|polyline|text)\\b([^>]*)>(?:(.*?)<\\/text>)?/g)) {\n const num = (name: string) => Number(new RegExp(`\\\\b${name}=\"(-?[\\\\d.]+)\"`).exec(attrs)?.[1]);\n if (tag === 'rect' && attrs.includes('fill=\"none\"'))\n out.push({ shape: { kind: 'box', x: num('x'), y: num('y'), width: num('width'), height: num('height') } });\n if (tag === 'path') {\n const [from, to] = pairs(/d=\"([^\"]*)\"/.exec(attrs)?.[1] ?? '');\n if (from !== undefined && to !== undefined) out.push({ shape: { kind: 'arrow', from, to } });\n }\n if (tag === 'polyline') out.push({ shape: { kind: 'pen', points: pairs(/points=\"([^\"]*)\"/.exec(attrs)?.[1] ?? '') } });\n if (tag === 'text') {\n const lines = [...inner.matchAll(/<tspan[^>]*>(.*?)<\\/tspan>/g)].map((l) => unescape(l[1] ?? ''));\n const xy = /x=\"(-?[\\d.]+)\" y=\"(-?[\\d.]+)\"/.exec(inner);\n out.push({ shape: { kind: 'note', at: { x: Number(xy?.[1] ?? 0), y: Number(xy?.[2] ?? 0) }, text: lines.join('\\n') } });\n }\n }\n return out;\n}\n\n/** The page's nodes by rrweb's IDs, from the full snapshot and each mutation: enough to name an element. */\nclass Nodes {\n #nodes = new Map<number, Known>();\n\n clear(): void {\n this.#nodes.clear();\n }\n\n add(node: SnapNode, parent: number | undefined): void {\n const { childNodes = [], ...rest } = node;\n this.#nodes.set(node.id, { ...rest, parent, kids: childNodes.map((c) => c.id) });\n for (const c of childNodes) this.add(c, node.id);\n }\n\n get(id: number): Known | undefined {\n return this.#nodes.get(id);\n }\n\n text(id: number, max = 60): string {\n let out = '';\n const walk = (n: number) => {\n const node = this.#nodes.get(n);\n if (node === undefined || out.length > max) return;\n if (node.type === 3) out += node.textContent ?? '';\n for (const k of node.kids) walk(k);\n };\n walk(id);\n const text = out.replace(/\\s+/g, ' ').trim();\n return text.length > max ? `${text.slice(0, max)}…` : text;\n }\n\n /** `<button> \"Save\" at src/App.tsx:9:7`: the element, its text, and the nearest place deictic marked. */\n describe(id: number | undefined): string {\n const node = id === undefined ? undefined : this.#nodes.get(id);\n if (id === undefined || node === undefined) return `node ${id}`;\n if (node.type === 0) return 'the page';\n let at: string | undefined;\n for (\n let n: Known | undefined = node;\n n !== undefined && at === undefined;\n n = n.parent === undefined ? undefined : this.#nodes.get(n.parent)\n )\n at = n.attributes?.['data-deictic'];\n const tag = node.tagName === undefined ? 'text' : `<${node.tagName}>`;\n const text = this.text(id);\n return `${tag}${text ? ` \"${text}\"` : ''}${at === undefined ? '' : ` at ${at}`}`;\n }\n}\n\n/** The page's console's arguments, each as JSON: a string without its quotes. */\nconst plain = (arg: string) => {\n try {\n const value: unknown = JSON.parse(arg);\n return typeof value === 'string' ? value : arg;\n } catch {\n return arg;\n }\n};\n\n/** Every line of the recording, in time. */\nfunction timelineOf(events: Event[], voice: { id: string; at: number; duration: number }[]): Line[] {\n const t0 = events[0]!.timestamp;\n const timeline: Line[] = [];\n const nodes = new Nodes();\n const push = (t: number, kind: string, text: string, extra: Partial<Line> = {}) =>\n timeline.push({ t, at: clock(t), kind, text, ...extra });\n let marks: Annotation[] = [];\n let scroll: { t: number; id: number | undefined; x: number; y: number } | undefined;\n let typing: { t: number; id: number | undefined; value: string } | undefined;\n const flushScroll = () => {\n if (scroll) push(scroll.t, 'scroll', `${nodes.describe(scroll.id)} to (${scroll.x},${scroll.y})`);\n scroll = undefined;\n };\n const flushTyping = () => {\n if (typing) push(typing.t, 'input', `${nodes.describe(typing.id)}: ${typing.value}`);\n typing = undefined;\n };\n\n for (const e of events) {\n const t = e.timestamp - t0;\n const d = e.data;\n const payload = d.payload ?? {};\n if (e.type === 4) push(t, 'page', `${d.href} at ${d.width}×${d.height}`);\n if (e.type === 2 && d.node !== undefined) {\n nodes.clear();\n nodes.add(d.node, undefined);\n }\n if (e.type === 5 && d.tag === 'deictic.annotations') {\n const now = payload.annotations ?? shapesInSvg(payload.svg ?? '');\n const key = (a: Annotation) => a.id ?? JSON.stringify(a.shape);\n const before = new Set(marks.map(key));\n const after = new Set(now.map(key));\n const added = now.filter((a) => !before.has(key(a)));\n const removed = marks.filter((a) => !after.has(key(a)));\n if (added.length > 0 || removed.length > 0) {\n const text = [...added.map((a) => `+ ${shapeOf(a)}`), ...removed.map((a) => `− ${shapeOf(a)}`)].join('; ');\n push(t, 'marks', text, { marks: now.map((a) => a.shape) });\n }\n marks = now;\n }\n // The address changed with no load: a route of the app's.\n if (e.type === 5 && d.tag === 'deictic.page') push(t, 'page', `${payload.href} (a route change, no load)`);\n // The page's console, and errors nothing caught (rrweb's console plugin), and where it was logged from, which goes\n // under a warning or an error.\n if (e.type === 6 && d.plugin === 'rrweb/console@1') {\n const level = payload.level ?? 'log';\n push(t, `console.${level}`, (payload.payload ?? []).map(plain).join(' '), {\n trace: payload.trace ?? [],\n ...(['error', 'assert', 'warn'].includes(level) ? { problem: true } : {}),\n });\n }\n // The page's requests (rrweb's network plugin), masked as they were kept: each as it ended. One the browser\n // reported of itself has no method; headers and bodies, where kept, are in `--json`.\n if (e.type === 6 && d.plugin === 'rrweb/network@1') {\n for (const r of payload.requests ?? []) {\n const took = r.duration !== undefined && Number.isFinite(r.duration) ? ` in ${round(r.duration)} ms` : '';\n const status = r.status === undefined || r.status === 0 ? 'no status (failed, blocked, or another origin’s)' : r.status;\n push(t, 'request', `${r.method ?? r.initiatorType ?? ''} ${r.name} → ${status}${took}`.trim(), {\n request: r,\n ...((r.status ?? 0) >= 400 ? { problem: true } : {}),\n ...(payload.isInitial === true ? { before: 'made as the page loaded, before this moment' } : {}),\n });\n }\n }\n if (e.type === 5 && d.tag === 'deictic.end') push(t, 'end', 'recording stopped');\n if (e.type !== 3) continue;\n if (d.source === 0) {\n for (const a of d.adds ?? []) nodes.add(a.node, a.parentId);\n for (const a of d.attributes ?? []) {\n const node = nodes.get(a.id);\n if (node) node.attributes = { ...node.attributes, ...a.attributes };\n }\n for (const x of d.texts ?? []) {\n const node = nodes.get(x.id);\n if (node) node.textContent = x.value;\n }\n }\n if (d.source === 2 && (d.type === 2 || d.type === 3 || d.type === 4)) {\n flushScroll();\n flushTyping();\n const what = { 2: 'click', 3: 'right-click', 4: 'double-click' }[d.type];\n // A click a key made (Enter on a button) has no position.\n const where = d.x === 0 && d.y === 0 ? ' by keyboard' : ` at (${round(d.x ?? 0)},${round(d.y ?? 0)}) in the viewport`;\n push(t, what, `${nodes.describe(d.id)}${where}`, { node: d.id });\n }\n if (d.source === 3) {\n if (scroll && scroll.id !== d.id) flushScroll();\n scroll = { t: scroll?.t ?? t, id: d.id, x: round(d.x ?? 0), y: round(d.y ?? 0) };\n }\n if (d.source === 4) push(t, 'resize', `viewport ${d.width}×${d.height}`);\n if (d.source === 5) {\n if (typing && typing.id !== d.id) flushTyping();\n const value = d.isChecked !== undefined && d.text === undefined ? String(d.isChecked) : JSON.stringify(d.text);\n typing = { t: typing?.t ?? t, id: d.id, value };\n }\n }\n flushScroll();\n flushTyping();\n for (const c of voice) push(c.at, 'voice', `clip ${c.id}, ${clock(c.duration)} long, until ${clock(c.at + c.duration)}`);\n return timeline.sort((a, b) => a.t - b.t);\n}\n\nexport interface Options {\n nth: string;\n json?: boolean;\n only?: string[];\n problems?: boolean;\n from?: string;\n to?: string;\n around?: string;\n grep?: string;\n full?: boolean;\n}\n\nexport async function run(named: string, values: Options): Promise<void> {\n const { kept, id, replay, task } = await loadRecording(named, Number(values.nth));\n const events = kept.events as Event[];\n if (!Array.isArray(events) || events.length === 0) fail(`Recording ${id} has no events.`);\n const timeline = timelineOf(events, kept.voice ?? []);\n\n // The part asked for. Seconds, as the replay's `?t=` and `frame --at` take them.\n const seconds = (name: 'from' | 'to' | 'around') => {\n const given = values[name];\n if (given === undefined) return undefined;\n const value = Number(given);\n if (!Number.isFinite(value)) fail(`--${name} takes seconds from the recording's start, as 12 or 4.5: not ${given}`);\n return value * 1000;\n };\n const around = seconds('around');\n const from = seconds('from') ?? (around === undefined ? undefined : around - 3000);\n const to = seconds('to') ?? (around === undefined ? undefined : around + 3000);\n const only = (values.only ?? []).flatMap((list) => list.split(',')).filter(Boolean);\n const grep = values.grep?.toLowerCase();\n // `console` is every level's lines, `click` a right or a double one too.\n const isKind = (kind: string, asked: string) => kind === asked || kind.startsWith(`${asked}.`) || kind.endsWith(`-${asked}`);\n const shown = timeline.filter(\n (e) =>\n (only.length === 0 || only.some((asked) => isKind(e.kind, asked))) &&\n (values.problems !== true || e.problem === true) &&\n (from === undefined || e.t >= from) &&\n (to === undefined || e.t <= to) &&\n (grep === undefined || `${e.kind} ${e.text}`.toLowerCase().includes(grep)),\n );\n\n const colorScheme = kept.colorScheme ?? 'light';\n const startedAt = new Date(kept.startedAt ?? events[0]!.timestamp).toISOString();\n if (values.json) {\n const head = { id, page: kept.page, viewport: kept.viewport, colorScheme, startedAt, duration: kept.duration, replay, task: task?.id };\n console.log(JSON.stringify({ ...head, lines: timeline.length, timeline: shown }, null, 2));\n return;\n }\n console.log(`Recording ${id}${task ? ` on task #${task.id}` : ''}: ${clock(kept.duration)} of ${kept.page}`);\n console.log(`viewport ${kept.viewport.width}×${kept.viewport.height}, ${colorScheme}, started ${startedAt}`);\n if (replay !== undefined) console.log(`replays at ${replay} (add ?t=<seconds> to open it paused there)`);\n if (shown.length < timeline.length) console.log(`${shown.length} of its ${timeline.length} lines, as asked`);\n console.log();\n const under = (line: string) => console.log(`${' '.repeat(22)}${line}`);\n for (const e of shown) {\n console.log(`${e.at.padStart(6)} ${e.kind.padEnd(13)} ${e.text}`);\n // Where a warning or an error came from, its nearest few places: all of them, and every line's, with `--full`.\n if (e.trace && (values.full === true || e.problem === true))\n for (const line of values.full ? e.trace : e.trace.slice(0, 5)) under(`at ${line}`);\n if (values.full !== true || e.request === undefined) continue;\n const r = e.request;\n if (e.before !== undefined) under(e.before);\n for (const [title, held] of [\n ['request headers', r.requestHeaders],\n ['response headers', r.responseHeaders],\n ] as const)\n for (const [name, value] of Object.entries(held ?? {})) under(`${title} ${name}: ${value}`);\n if (r.requestBody !== undefined) under(`request body ${r.requestBody}`);\n if (r.responseBody !== undefined) under(`response body ${r.responseBody}`);\n }\n if (shown.length === 0) console.log(timeline.length === 0 ? 'Nothing in it.' : 'No line of it is what was asked for.');\n // Where something went wrong, how to get to it: what led up to it, and what the page looked like.\n const problems = timeline.filter((e) => e.problem === true).length;\n if (problems === 0 || shown.length < timeline.length) return;\n const ref = task?.id ?? id;\n console.log(\n `\\n${problems} problem${problems === 1 ? '' : 's'}: --problems lists them, --around <seconds> shows what led to one, and ${ME} frame ${ref} --at <seconds> the page then.`,\n );\n}\n"],"mappings":";;;AA+FA,MAAM,QAAQ,KAAK;;AAGnB,SAAS,QAAQ,EAAE,SAA6B;CAC9C,MAAM,UAAU,WAAoB;EAClC,MAAM,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC;EAChC,MAAM,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC;EAChC,OAAO,IAAI,MAAM,KAAK,IAAI,GAAG,EAAE,CAAC,EAAE,GAAG,MAAM,KAAK,IAAI,GAAG,EAAE,CAAC,EAAE,KAAK,MAAM,KAAK,IAAI,GAAG,EAAE,CAAC,EAAE,GAAG,MAAM,KAAK,IAAI,GAAG,EAAE,CAA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SAAS,QAAQ;CACtD,MAAM,MAAM,MAAM,MAAM;CACxB,QAAQ,IACN,KAAK,SAAS,UAAU,aAAa,IAAI,KAAK,IAAI,yEAAyE,GAAG,SAAS,IAAI,+BAC7I;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded. One the plugin\n * `needs` always is; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /** The model its panel shows for an element. Without it, the panel gets none. */\n read?(source: Source, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, or a change the plugin made itself. */\n apply?(source: Source, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would: after a recording, say. An\n * element rendered again since stands in for one no longer on the page. False when there's no such tab\n * or no such element any more. Not from `setup`, which runs before the popup can open.\n */\n open: (plugin: string, element: Element) => boolean;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /** Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows. */\n apply(op: Op): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AA6EA,MAAa,gBACX,WACyC;AAiH3C,MAAa,sBAAgD,WAAuE"}
1
+ {"version":3,"file":"src.js","names":[],"sources":["../../src/index.ts"],"sourcesContent":["/**\n * `deictic`: what a plugin is. Every plugin is optional: deictic itself is the glue (the\n * transform that ties elements to source, the dev server's endpoints, the history, shortcuts and the\n * overlay's panel), and each plugin adds what it does on top.\n *\n * A plugin has two halves, each optional that meet over the dev server's endpoints (`tools/endpoints.ts`). The\n * server half runs beside the bundler and is the only one that reads source: it turns the element\n * under the pointer into a model its panel can show, and an op from that panel into text edits. It\n * never writes files; deictic does, so every plugin's changes land in one history and undo the\n * same way. A change that isn't to a file (a task added to a board) the plugin makes itself and\n * answers with what it did (`Done`): the history keeps that beside the files' changes and hands it\n * back to the plugin's own `undo` and `redo`.\n * The client half is a module the page loads, named by the server half's `client`, which draws the\n * panel and previews an op on the page before it is applied.\n *\n * A plugin may have no panel at all, only an API for others (screenshots, a recording) and routes of\n * its own on the dev server. Each half's `setup` answers its API, and `use(name)` reaches another\n * plugin's, on the same side; `needs` names the plugins it can't do without.\n *\n * Both halves import from here, so the parser is imported for its types only: the browser must not load it.\n */\nimport type { JSXOpeningElement, Program } from 'oxc-parser';\n\nimport type { Shortcut } from './shortcut.ts';\n\nexport type { Modifier, Shortcut } from './shortcut.ts';\n\n/** A place in the source: the file from the project's root, with `/`, and the line and column, from 1. */\nexport interface Loc {\n file: string;\n line: number;\n column: number;\n}\n\n/** An element the pointer picked: where its opening tag starts, and the tag, which the server checks is still there. */\nexport interface Target {\n loc: Loc;\n tag: string;\n}\n\n/** Text in a file to replace, by UTF-16 offsets. `file` is the target's unless named, from the project's root. */\nexport interface TextEdit {\n file?: string;\n start: number;\n end: number;\n text: string;\n}\n\n/** What a server half reads: the target's file, parsed, and its element. */\nexport interface Source {\n /** The target's file, from the project's root. */\n file: string;\n code: string;\n /** The file's module; for an `.astro` component, its frontmatter's. */\n program: Program;\n /** The target's opening tag. */\n element: JSXOpeningElement;\n /** Another file under the project's root, for plugins whose edits go elsewhere (a locale's messages). */\n read(file: string): string;\n}\n\n/**\n * What answers the overlay's requests in a page with no dev server behind it (`deictic/vite`'s `standalone`): the\n * default export of a module of the page's. A request is one the endpoints would get, under `<base>__deictic/`;\n * the answer is theirs too (`{ model }`, `{ model, change }`, `{ problem }` with a status that isn't ok).\n */\nexport type Standalone = (request: Request) => Response | Promise<Response>;\n\n/** An op a plugin won't make. The message says why and what to do instead; the panel shows it. */\nexport class Refusal extends Error {\n override name = 'Refusal';\n}\n\n/**\n * A change the plugin made itself, not to a file: what its `undo` and `redo` need to take it back and\n * make it again. JSON, since the history keeps it on disk across restarts of the dev server.\n */\nexport interface Done<Record = unknown> {\n done: Record;\n}\n\ntype Maybe<T> = T | Promise<T>;\n\n/**\n * Each plugin's API to the others on the server, by name. A plugin adds its own, so `use` knows its type:\n * `declare module 'deictic' { interface ServerApis { screenshots: Screenshots } }`.\n */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ServerApis {}\n\n/** The same, in the page: `declare module 'deictic' { interface ClientApis { screenshots: Capture } }`. */\n// oxlint-disable-next-line typescript/no-empty-interface -- filled by declaration merging\nexport interface ClientApis {}\n\n/** A plugin's API, by its name: what its package declared, or `unknown` for one that declared none. */\nexport type ApiOf<Apis, Name extends string> = Name extends keyof Apis ? Apis[Name] : unknown;\n\nexport interface ServerContext {\n /** The project's root, as an absolute path. */\n root: string;\n /**\n * Another plugin's API, as its `setup` answered it, or nothing when it isn't loaded. One the plugin\n * `needs` always is; any other may not be, so check.\n */\n use: <Name extends string>(name: Name) => ApiOf<ServerApis, Name> | undefined;\n}\n\n/**\n * A route of the plugin's own, at `/__deictic/plugins/<name>/<route>`, and below it. A `GET` must\n * change nothing: anything else reaches it only from the page itself, which deictic checks.\n */\nexport type Route = (request: Request, context: ServerContext) => Maybe<Response>;\n\nexport interface ServerPlugin<Model = unknown, Op = unknown, Record = unknown, Api = unknown> {\n /** Ties the halves together; also the label of its changes in the history, and its routes' path. Lowercase, with `-`. */\n name: string;\n /** The module the page loads for this plugin's half there, which default-exports its `ClientPlugin`. */\n client?: string;\n /** What the page half gets as `context.options`: the user's options it needs there, as JSON. */\n clientOptions?: unknown;\n /** What opens its panel: its own default, which its options let the user change. A plugin with no panel has none. */\n shortcut?: Shortcut;\n /** The plugins it can't do without, by name: the dev server won't start without them. */\n needs?: string[];\n /**\n * The packages it imports that the project installs itself (optional peers), by name: as the dev server starts,\n * it says how to install any that's missing, rather than failing when first used.\n */\n packages?: string[];\n /** Runs once, as the dev server starts and before it answers anything. Answers the plugin's API to the others. */\n setup?(context: ServerContext): Maybe<Api>;\n /** Routes of its own, by their first segment under `/__deictic/plugins/<name>/`. */\n routes?: { [route: string]: Route };\n /**\n * The model its panel shows for an element. Without it, the panel gets none. `source` is a `Refusal` where the\n * element isn't to be found in its file (it doesn't parse, or the page runs other code than it has): throw it where\n * the plugin needs the source, or go on without it, as a task does.\n */\n read?(source: Source | Refusal, target: Target): Maybe<Model>;\n /** Text edits for deictic to write, which it refuses without the source, or a change the plugin made itself. */\n apply?(source: Source | Refusal, target: Target, op: Op): Maybe<TextEdit[] | Done<Record>>;\n /**\n * Takes back a change `apply` made itself, or throws a `Refusal` saying why it can't any more. It may\n * answer what the next redo needs, where that differs (what it put back has a new ID).\n */\n undo?(record: Record): Maybe<void | Record>;\n /** Makes it again after an undo, and answers what the next undo needs, which may differ (a new ID). */\n redo?(record: Record): Maybe<Record>;\n /** Says what an op does, for the history: `className: px-2 → px-4`. */\n describe?(op: Op, before: Model): string;\n}\n\nexport const definePlugin = <Model, Op, Record = unknown, Api = unknown>(\n plugin: ServerPlugin<Model, Op, Record, Api>,\n): ServerPlugin<Model, Op, Record, Api> => plugin;\n\nexport interface ClientContext {\n /** The dev server's base URL, ending in `/`. */\n base: string;\n /** deictic's shadow root, to draw in: neither the page's styles nor the overlay's cross over. */\n root: ShadowRoot;\n /** The server half's `clientOptions`, or nothing. */\n options: unknown;\n /** Another plugin's API in the page, as its `setup` answered it, or nothing when it isn't loaded. */\n use: <Name extends string>(name: Name) => ApiOf<ClientApis, Name> | undefined;\n /** Asks one of this plugin's own routes, from the page: `request('shots', { method: 'POST', body: blob })`. */\n request: (route: string, init?: RequestInit) => Promise<Response>;\n /**\n * Opens the popup on an element at a plugin's tab, as its shortcut would: after a recording, say. An\n * element rendered again since stands in for one no longer on the page. False when there's no such tab\n * or no such element any more. Not from `setup`, which runs before the popup can open.\n */\n open: (plugin: string, element: Element) => boolean;\n /**\n * Shows `items` in the lightbox over everything, at `at` (the first by default), stepping between them with\n * ← and →. With `from`, it grows out of that element (the chip clicked) and shrinks back into it on close.\n */\n lightbox: (items: LightboxItem[], options?: LightboxOptions) => { close: () => void };\n}\n\n/** What the lightbox shows: a picture, a page in a frame (a recording's replay), or a sound with its waveform. */\nexport type LightboxItem = {\n /** Its name, over it. */\n title: string;\n /** Buttons beside the name: each closes the lightbox and runs. */\n actions?: LightboxAction[];\n} & ({ kind: 'image'; url: string } | { kind: 'page'; url: string } | { kind: 'audio'; url: string });\n\nexport interface LightboxAction {\n label: string;\n title?: string;\n run: () => void;\n}\n\nexport interface LightboxOptions {\n /** The item it opens at. */\n at?: number;\n /** The element it grows out of, and goes back into. */\n from?: Element;\n}\n\nexport interface PanelContext<Model, Op> extends ClientContext {\n /**\n * The element clicked: the one the source marked, under the pointer or around what is. Back from `away`\n * it may be off the page (`isConnected` is false), where the page moved on without it: the element as it\n * was left, or after a page load an empty one of its tag and mark. `elements` is then empty.\n */\n element: Element;\n /**\n * What was under the pointer, where it isn't `element` but inside it: markup nothing marked, as a\n * dependency's, or in an open shadow root, as the popup's own on a page that shows it (`popupIn`).\n */\n pointed?: Element;\n /** Every element on the page from the same place in the source, the clicked one among them: the rows of a list. */\n elements: Element[];\n target: Target;\n model: Model;\n /** Applies an op on disk, and reads the model again. Rejects with the server's reason, which the panel also shows. */\n apply(op: Op): Promise<Model>;\n close: () => void;\n /**\n * Says there's something here that leaving would lose (words typed, a change tried on the page), and the button\n * that keeps it: a click outside the popup then shakes that button, where it would have closed the popup.\n * `undefined` once there's nothing to lose. Forgotten as the panel unmounts.\n */\n unsaved: (action: HTMLElement | undefined) => void;\n /**\n * Leaves the popup to do something on the page, then comes back: closes it, runs `task` (a recording, a\n * pick of another element), and opens it again at this tab on this element. The next mount gets\n * `resumed`: the `state` kept now (what was typed, what's attached), and what `task` answered, or why\n * it failed. The state stays in the page, as it is: no need for JSON. It's also kept for the tab's next\n * page, as a structured clone, where it can be one: after a page load, the plugin's `resume` says whether\n * the task carries on, and the popup comes back there.\n */\n away: <T>(state: unknown, task: () => Promise<T>) => void;\n /** Set when this mount is the panel coming back from `away`. */\n resumed?: Resumed;\n}\n\n/** What a panel coming back from `away` gets: the state it kept, and the task's result or problem. */\nexport interface Resumed {\n state: unknown;\n result?: unknown;\n /** Why the task failed: its error's message. */\n problem?: string;\n}\n\nexport interface ClientPlugin<Model = unknown, Op = unknown, Api = unknown> {\n /** The server half's `name`. */\n name: string;\n /** Shown over the element while its shortcut's keys are held, and atop the panel. */\n label?: string;\n /**\n * Runs once, as the page starts, before any panel opens (a recording starts here). Answers the\n * plugin's API to the others in the page, at once: one that needs time keeps its promises inside it.\n */\n setup?(context: ClientContext): Api;\n /**\n * Asked as a page starts where the page before it left this plugin's panel `away`: the task it left for,\n * where that carries on in this page (a recording does), or nothing where it ended with the page. When it's\n * done the popup opens at this tab with `resumed`, on the element where this page has it and without where not.\n */\n resume?(context: ClientContext): Promise<unknown> | undefined;\n /** Draws into `panel`, inside deictic's shadow root. Returns what to undo on the page when the panel closes. */\n mount?: (panel: HTMLElement, context: PanelContext<Model, Op>) => (() => void) | void;\n}\n\nexport const defineClientPlugin = <Model, Op, Api = unknown>(plugin: ClientPlugin<Model, Op, Api>): ClientPlugin<Model, Op, Api> => plugin;\n"],"mappings":";;AAqEA,IAAa,UAAb,cAA6B,MAAM;CACxB,OAAO;AAClB;AAiFA,MAAa,gBACX,WACyC;AAiH3C,MAAa,sBAAgD,WAAuE"}