SLOPSHOPPER

plain-english

Catches stock AI phrases, vague claims and unexplained jargon before a reader sees them. In Claude Code it checks Markdown writes, commit and pull request…

paneguardcommandpromptmodel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · plain-english
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /plain-english ⎿ plain-english: clean (1 file) ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts
README

plain-english for Claude Code

A Claude Code plugin that checks prose the way a code linter checks source. It refuses a Markdown write, a commit or pull request message, or a tracker issue that breaks the ruleset, and holds a chat reply that does. Each refusal quotes the passage, names the rule and gives a rewrite hint. The ruleset and its exceptions are in the rule guide.

The plugin is a mod: TypeScript functions Claude Code runs on its own events. The settings-hook install that the command-line checker's init --agent claude-code writes does the same job from outside the agent. The agent guide says how the two differ.

Install

Install it from the Claude plugin directory. It is also in this repository's own marketplace, nordscope-fi/plain-english, for Claude Code 2.1.293 or later: open /plugin, add that marketplace, and choose plain-english.

The plugin carries the checker's core, bundled with its dependencies and the built-in ruleset, under skills/plain-english/scripts/core/. It sits inside the writing skill, so the mod and the skill share one copy. Installing it copies these files and nothing else. In Claude Code a check starts no program: the mod runs the checker inside Claude Code.

Each GitHub release also carries a ZIP copy of this folder with checksums. The repository marketplace already supplies the plugin. An Anthropic directory listing requires a separate account-owner submission; the release guide contains the prepared details. The event checks described here target Claude Code.

What each Claude app gets

  • Claude Code: the mod. It checks Markdown writes, commit and pull request messages and tracker issues before they are saved, and holds a chat reply with a clear tell for a rewrite.
  • Claude chat and Cowork: the writing skill, plain-english. Claude loads it when a request fits its description, such as drafting an email or a report. It gives Claude the reply rules and checks every document and any reply over about 100 words. The check runs in Claude's own code environment and sends nothing anywhere.

A skill loads only when the request fits, so an ordinary question may not load it. To have replies checked as a rule, add this sentence to your profile instructions: "Use the plain-english skill for any prose you write for me." You can also pick the skill by typing / in the message box. The plugin changes no settings itself.

What you see

The plugin checks writes and completed replies. Select Plain English under /config > Output style for writing guidance, then start a new session. Brief and full styles are also included. The bundled writing-a-document skill supplies document guidance when Claude invokes it.

  1. A save is questioned. Claude tries to save notes.md opening with Furthermore, the build is slow. Before the file is written, a dialog headed Prose check opens:
   plain-english found one passage in notes.md that breaks its rules:

   line 1: "Furthermore" (furthermore) Start the sentence with its own point.

   Refusing hands Claude the findings and a way to fix each. Save the file as it is?

Two answers: save it as it is, or refuse so Claude rewrites. A refusal hands Claude the finding and the ways to resolve it, and Claude rewrites. With failOn: error in the project config there is no dialog: the save is refused outright and Claude reads the finding.

  1. A reply is held. Claude ends a turn with a reply over the length limit, or one carrying a stock phrase. The turn does not end. Claude reads the finding and answers again, once.
  2. A commit message is questioned the same way. git commit -m "Leverage the new cache" waits on the dialog, which names the commit message and quotes "leverage" (leverage) Use 'use'. Under failOn: error the command is refused and Claude commits with a plainer message.

The example sentences above sit in code spans and a code block so this file passes its own check.

Commands you run yourself:

  • /plain-english docs/ checks files without an extra model call. Quote paths containing spaces.
  • /plain-english review opens the recent findings panel.
  • /plain-english status reports the session's repair setting and recent findings.
  • /plain-english repair on allows one automatic rewrite of an advisory write. A repeated attempt asks you before proceeding. /plain-english repair off restores the immediate question. Required checks still refuse the write.

What it hooks

EventWhat the hook does
tool.callOn Write, Edit and MultiEdit of a .md or .mdx file, on a supported Bash Markdown write or message command (git commit, gh pr, gh issue or gh release), and on the Linear MCP save tools: runs the checker on the call and returns its decision. A deny refuses the call with the reason. An ask opens a dialog headed Prose check that names the file or command and quotes one passage with its rule; a refusal there hands Claude the full finding, and where nobody can answer it refuses. Everything else passes through untouched.
classic.Stop, classic.SubagentStopRuns the reply check. A block holds the turn with the reason, in an interactive session and in Claude Code's non-interactive print mode alike.
session.startRegisters /plain-english.
prompt.contextAdds declared project vocabulary and loaded writing-profile observations to the conversation. The selected output style supplies general writing guidance.
command.run/plain-english [paths] lints the working tree and prints the findings. No model turn.

What it reads, writes and sends

  • Reads: proposed prose, its surrounding document when an edit needs context, the project config, configured writing-profile summaries, and files you request. Excluded documents and paths outside the project are skipped before extra model checks. Edits report findings only on changed prose.
  • Writes: nothing, unless you approve a project term: then, after you confirm it, an exception in the project config. The review panel and the reply checks keep recent findings, turn identifiers and small counters in session memory.
  • Sends: pattern matching stays on this machine. Extra checks ask the session's own model through Claude Code ($.model.complete), with your account and model service. Where Claude Code cannot make that call, the extra check is reported unavailable and the pattern result stands. Document checks receive the complete proposed document as context, including its code examples and quoted material, but judge changed prose. Chat checks can also include your last question. These calls use your plan or API usage. Set modelChecks: false to disable them.
  • Keeps: an extra check is one request with no conversation history. Provider retention follows your account and provider settings. The host conversation still follows Claude Code's normal storage behavior.

The checker runs inside the mod (ADR-008). When it needs a file or a model's answer, it hands the request back; the mod reads the file through Claude Code or asks the session's model, and the checker repeats the check with the answer. A check can ask two model questions at most. Asking through the session gave the same verdicts as a separate non-interactive Claude Code run on 16 test prompts, recorded in ADR-006.

A failed check produces a notice rather than a clean result, and the original action proceeds. If an extra model check cannot run, the pattern checks still apply. Document model calls share a 15-second deadline, and chat model calls share 45 seconds. A check starts no program, so cancelling a turn leaves nothing running.

For reviewers: what the plugin runs, reads, writes and sends

The mod starts no program. It runs the plain-english checker's core inside Claude Code's own process (ADR-008). skills/plain-english/scripts/core/ holds that core, bundled with its dependencies, and skills/plain-english/scripts/core/default-rules.mjs holds the built-in ruleset. Paths are relative to the plugin folder.

The submission statement about helper servers

A plugin can declare helper servers that Claude calls for it, through the Model Context Protocol (MCP). The submission form asks the publisher to confirm that "the plugin does not exfiltrate credentials or execute code outside its declared MCP servers." This plugin declares no MCP servers, reads no credential, starts no program and makes no network request of its own. Its only code is the mod, which Claude Code runs.

What the mod reads

  • Session facts: session.cwd, session.id and session.model.
  • The conversation: in tool.call, proposed file writes, shell commands and tracker-tool calls; in classic.Stop and classic.SubagentStop, finished replies.
  • Files, through fs.read, fs.stat and fs.list:
  • the project's .plain-english.yml, looked for in the folders above the project too, any config it extends, and a writing profile it names;
  • a message file a commit names with -F, and the current text of a file being edited, so an edit is judged in context;
  • the transcript a Stop event names, for your last question;
  • the files /plain-english checks.

fs.stat resolves links, so a write that lands outside the project is skipped.

What it sends, and where

Only the extra model checks send anything off the computer. Through model.complete, the session's own model and account receive the text being checked: a proposed document, a commit or issue text, or a finished reply and your last question. Nothing else leaves the computer. Set modelChecks: false to keep everything on it.

Files written

One, and only after you ask for it: the project's config, .plain-english.yml or .plain-english.yaml, written through fs.write at that fixed path. That happens when you approve a term in the review panel and confirm it in a dialog. Before writing, the checker repeats every check. It refuses when the file changed since the check, when it is a link, or when a config in a folder above would govern the project. The mod also refuses when Claude Code's working folder is not the project root the check named. It never writes Claude Code's own settings, instruction files or build files.

Events that see or change other content

  • tool.call: can refuse a call or ask you about it, and never changes its input.
  • classic.Stop and classic.SubagentStop: can hold a reply for a rewrite, and change nothing else.
  • prompt.context: adds one section with your project's declared vocabulary, and leaves the existing context in place.
  • command.run: answers /plain-english, which the mod registers on session.start, and no other command.

Uses a credential from the user's machine

Nothing in the plugin reads a credential: no environment variable and no key file, so there is no value to ask the person for in the plugin's settings. The plugin carries no web address. In its copy of the built-in ruleset, skills/plain-english/scripts/core/default-rules.mjs, each finding's link to this repository's guides is a path such as docs/writing-style.md#readability, and the rule source credits that only the CLI's policy page shows are left out. The rules themselves are the same.

The bundled code also avoids every form the directory reads as a credential or as sending one, so a reviewer has nothing to set aside:

  • No network host. The model answers the mod passes to the checker sit in a field called answered. The Markdown library's helper for file: addresses is replaced by one that accepts none, because the checker gives it paths only.
  • No name in capitals shaped like an environment variable: the YAML parser's error codes are written in lower case, such as unexpected-token.
  • No message built by dropping a key or token into a template: those messages, such as the YAML parser's "Key ... already set", are joined as plain text.
  • No variable named after a command that lists the environment: the ruleset's variable is ruleset, the environment's is environment, and the YAML parser's set type is setTag. No line begins with such a command either.

The word token in the bundled code belongs to the YAML and Markdown parsers, where it means a piece of parsed text. Tests fail if any of these forms comes back.

The writing skill's script

skills/plain-english/scripts/check.mjs is a script the skill's instructions ask Claude to call on a draft in chat or Cowork. No hook or event starts it, and in Claude Code the instructions say not to call it. It reads the draft from standard input, prints a JSON report and exits. It imports no Node module, reads no file, opens no connection and starts no program. It imports the same core the mod does, from the folder beside it.

Bundled code

skills/plain-english/scripts/core/ is the checker from this repository, built by scripts/build-plugin.mjs for a runtime without Node. These are the build's rules. Apart from the one config key named under plain data, the checker behaves as it does on the command line:

  • Stand-ins for Node-only parts. The parts that read files, start the command-line fallback or write evaluation receipts are replaced with stand-ins that do none of those things. The mod passes its own file access to every check, and the build fails if any Node import remains.
  • Readable files. The bundle is unminified, has no comments, and has no line over 1,000 characters. Long strings and regular expressions are split into pieces joined when the code runs, and each regular expression is checked identical as the build runs.
  • Size. Every file is under the directory's read limit of 262,144 bytes.
  • No eval. The bundled fault library's unused eval member is removed, and the format package is replaced with a ten-line formatter.
  • Plain data, no accessors. The bundled libraries' getters, setters, Object.defineProperty calls and prototype lookups are rewritten as plain properties and methods: the YAML library's node and schema fields, the Markdown parser's splice buffer and construct list, and the file object the sentence layer needs. The tree walker no longer names its visitor function for debugging. The YAML library's node clone, which nothing in the checker calls, refuses instead of copying through the prototype. One input reads differently from the command-line checker: a config key named __proto__ is refused, where the command-line checker stores it as an ordinary key.
  • No unused web addresses. The Markdown parser's http:// prefix for a bare www. link is dropped, since the checker never reads the address, and each rule's default source names the design notes by path.

Jira and Confluence HTML is read by the checker's own small reader, which decodes the entities that text uses, so no HTML library and no encoded entity table is bundled.

The same checker is published on npm with a signed record of the GitHub build that produced it.

Configuration

The checker reads .plain-english.yml in the project as it does everywhere else. With no file, a finding is advisory and the mod asks before the write. To make findings refuse outright, set failOn: error there. Chat has its own setting and blocks errors by default. Set chat.failOn: never to report chat findings without holding the reply. Extra model checks follow modelChecks: false disables them, true enables them, and omission retains the Claude Code default. The adoption guide walks through the file, and the vocabulary section of the main README covers project terms.

When it misfires

A term the ruleset flags that is ordinary in your field goes in the config under allow, or on the line itself as an HTML comment naming the rule and, after a colon, the reason. The rule guide shows the comment. A suppression without a reason is itself a finding. The review panel offers a one-use exception for the identical advisory attempt, approval of a term for one rule across the project, or a suppression comment copied with your reason. Paste that comment above the intended passage yourself. Inherited or linked configuration needs a manual edit. Term approval asks you to confirm: the named rule is waived on matching lines across the project. A required check must be fixed or resolved through the project config or a valid suppression comment. plain-english doctor prints the environment for a bug report.

Report a problem at <https://github.com/nordscope-fi/plain-english/issues>. Security concerns go to <peter@nordscope.fi>, not to the public tracker.

Develop and test

The repository's build writes the checker's core and the ruleset into skills/plain-english/scripts/core/, writes the writing skill's scripts/version.mjs, and copies the generated styles, the document skill, and the writing skill's SKILL.md and scripts/check.mjs. These files are committed, and CI fails when a build changes them and the change was not committed. The contributing guide lists the commands that build, load, validate and test the plugin. The manifest's version moves with each release.

Licence

MIT, as the rest of the repository.

Source 15 files
hooks/register.ts 464 lines
1import type { EngineInterface, Register } from 'claude-code'
2
3import { classifyShellCommand } from './shell.mjs'
4import { ISSUE_TOOLS } from './issue-tools.mjs'
5import {
6  approvalPlan, claudeCodeChat, claudeCodeHook, emptyFetched, formatText, hookCheck, lintTargets, lintText,
7  ModelRequest, NeedFiles, pathsFor, projectGuidance, replay, replayIo, resolveRuleSet, stalledNotes, suppressedLine,
8} from '../skills/plain-english/scripts/core/plugin-core.mjs'
9import DEFAULT_RULES from '../skills/plain-english/scripts/core/default-rules.mjs'
10import { askFor, noticeLine, oneLine, readChatVerdict, readPassages, readPaths, readToolVerdict, toolPayload } from './wire'
11
12/** Files the docs channel judges. The checker strips code and frontmatter itself. */
13const MARKDOWN = /\.(md|markdown|mdx)$/i
14
15
16/** Fixed checker diagnostics only; anything else can contain private text. */
17const SAFE_CHECK_NOTICES = new Set([
18  'plain-english: extra model check could not start; pattern checks still apply.',
19  'plain-english: extra model check timed out; pattern checks still apply.',
20  'plain-english: extra model check failed; pattern checks still apply.',
21  'plain-english: extra model check returned no usable answer; pattern checks still apply.',
22  'plain-english: configuration unavailable; using local built-in pattern checks as advice only.',
23])
24
25const COMMAND = 'plain-english'
26const PANE = 'plain-english-review'
27
28type Channel = 'docs' | 'github' | 'issue' | 'chat'
29
30interface ReviewFinding {
31  channel: Channel
32  reason: string
33  strict: boolean
34  event: Readonly<Record<string, unknown>>
35  cwd: string
36  key: string
37}
38
39/** What a file system answer from the checker's core looks like (ADR-008). */
40interface FileFacts { kind: 'file' | 'directory' | 'link' | 'other'; mtimeMs: number; realPath?: string }
41interface Fetched { reads: Map<string, string | null>; stats: Map<string, FileFacts | null>; lists: Map<string, string[] | null> }
42interface Needed { reads: string[]; stats: string[]; lists: string[] }
43
44/** One answer the mod got for a model question, keyed as the checker asked (ADR-006). */
45interface ModelAnswer { key: string; text?: string; unavailable?: 'timed out' | 'failed'; usage?: Record<string, number> }
46
47/** Values the checker keeps between checks, such as a turn's block state, for this session. */
48const kept = new Map<string, { value: string; at: number }>()
49
50/**
51 * Runs part of the checker's core in this process (ADR-008). The core reads
52 * files through a replay of what the mod has fetched; when it lacks a path it
53 * throws `NeedFiles`, and the mod fetches every path it named and runs the
54 * same work again. A model question comes back as `ModelRequest`; the mod asks
55 * the session's model and runs again with the answer, as ADR-006 did with the
56 * CLI. Notices are logged and kept values saved only from the run that
57 * finishes: an earlier run worked from missing files, and its block record
58 * would make the finishing run think the turn was already held.
59 */
60async function runCore<T>(
61  $: EngineInterface,
62  cwd: string,
63  work: (io: unknown, answers: { answers: ModelAnswer[]; deadline?: number }) => T,
64  signal: AbortSignal | undefined,
65  rounds = 12,
66): Promise<T> {
67  const fetched: Fetched = emptyFetched()
68  const answered: { answers: ModelAnswer[]; deadline?: number } = { answers: [] }
69  for (let round = 0; round < rounds; round++) {
70    signal?.throwIfAborted()
71    const notices: string[] = []
72    const pending = new Map<string, { value: string; at: number }>()
73    const io = replayIo({
74      cwd,
75      path: pathsFor(cwd), env: {}, home: undefined,
76      now: () => Date.now(),
77      notice: (text: string) => { notices.push(text) },
78      state: {
79        get: (key: string) => pending.get(key) ?? kept.get(key), set: (key: string, value: string) => {
80          pending.set(key, { value, at: Date.now() })
81          return true
82        },
83      },
84      defaultRules: () => DEFAULT_RULES as string,
85    }, fetched)
86    try {
87      const result = replay(io, (checked: unknown) => work(checked, answered))
88      for (const [key, value] of pending) kept.set(key, value)
89      for (const notice of new Set(notices)) if (SAFE_CHECK_NOTICES.has(notice)) log($, notice)
90      return result
91    } catch (error) {
92      if (error instanceof NeedFiles) {
93        await fetchAll($, error as unknown as Needed, fetched)
94        continue
95      }
96      if (error instanceof ModelRequest) {
97        const asked = (error as unknown as { request: { key: string; prompt: string; timeoutMs: number } }).request
98        answered.answers.push(await answerModel($, asked, signal))
99        continue
100      }
101      throw error
102    }
103  }
104  throw new Error('check unavailable: the checker kept asking for files or model answers.')
105}
106
107/** Fetches every path one run lacked, at once. A path that cannot be read is recorded as missing. */
108async function fetchAll($: EngineInterface, need: Needed, fetched: Fetched): Promise<void> {
109  await Promise.all([
110    ...need.reads.map(async path => {
111      fetched.reads.set(path, await $.fs.read(path).catch(() => null))
112    }),
113    ...need.stats.map(async path => {
114      const stat = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
115      fetched.stats.set(path, stat === undefined ? null : {
116        kind: stat.isLink ? 'link' : stat.kind === 'dir' ? 'directory' : stat.kind,
117        mtimeMs: stat.mtimeMs,
118        ...(stat.realPath === undefined ? {} : { realPath: stat.realPath }),
119      })
120    }),
121    ...need.lists.map(async path => {
122      fetched.lists.set(path, await $.fs.list(path).then(entries => entries.map(entry => entry.name)).catch(() => null))
123    }),
124  ])
125}
126
127/**
128 * Asks the session's model one question. A provider failure, and a call that
129 * cannot be made at all, become an answer the checker reads as unavailable,
130 * so the pattern result stands. A cancelled turn is not an answer: it ends the
131 * check.
132 */
133async function answerModel($: EngineInterface, asked: { key: string; prompt: string; timeoutMs: number }, signal: AbortSignal | undefined): Promise<ModelAnswer> {
134  try {
135    const model = await $.session.model()
136    const reply = await $.model.complete({ model, prompt: asked.prompt, timeoutMs: Math.max(1, Math.round(asked.timeoutMs)) }, signal ? { signal } : {})
137    if (reply.isAnswered) return { key: asked.key, text: reply.text, usage: { ...reply.usage } }
138    signal?.throwIfAborted()
139    return { key: asked.key, unavailable: reply.reason === 'aborted' ? 'timed out' : 'failed' }
140  } catch {
141    signal?.throwIfAborted()
142    return { key: asked.key, unavailable: 'failed' }
143  }
144}
145
146/** One hook check, run in this process. Returns what the hook adapter prints. */
147async function adapter(
148  $: EngineInterface,
149  channel: Channel,
150  payload: Record<string, unknown>,
151  cwd: string,
152  signal: AbortSignal,
153): Promise<string> {
154  return runCore($, cwd, (io, answered) => (hookCheck({
155    channel, payload, profile: claudeCodeHook, reader: claudeCodeChat, io, answered,
156  }) as { stdout: string }).stdout, signal)
157}
158
159/** One step of a term approval (ADR-007), as the checker's core decides it. */
160interface ApprovalStep { root: string; config: string; exists: boolean; hash: string; modelVocabulary: boolean }
161
162/**
163 * Runs one approval step. The checks run in the core against fresh file
164 * answers; a `write` step that passes them saves through `$.fs.write` at a
165 * fixed path, and only when Claude Code's working folder is the project root
166 * the check named.
167 */
168async function approvalStep($: EngineInterface, cwd: string, request: Record<string, unknown>): Promise<ApprovalStep> {
169  const plan = await runCore($, cwd, io => approvalPlan(cwd, request, (directory: string) => resolveRuleSet(directory, io), io) as {
170    result: { ok: true } & ApprovalStep | { ok: false; message: string }
171    write?: { path: string; exists: boolean; text: string }
172  }, undefined)
173  if (!plan.result.ok) throw new Error(plan.result.message)
174  if (plan.write !== undefined) {
175    // The write's path is fixed text, so it lands in Claude Code's own working
176    // folder. Save only when that is the project root the check approved.
177    const here = await $.fs.stat('.', { resolve: true }).catch(() => undefined)
178    if (here?.realPath !== plan.result.root) {
179      throw new Error(`Claude Code is working in a different folder from ${plan.result.root}, so nothing was saved. Add the term to ${plan.result.config} by hand.`)
180    }
181    if (plan.result.config === '.plain-english.yml') await $.fs.write('.plain-english.yml', plan.write.text)
182    else if (plan.result.config === '.plain-english.yaml') await $.fs.write('.plain-english.yaml', plan.write.text)
183    else throw new Error('This configuration cannot be written here.')
184  }
185  return plan.result
186}
187
188/** Only a deliberate, confirmed user action can save project vocabulary. */
189async function approveProjectTerm($: EngineInterface, finding: ReviewFinding, term: string, ruleId: string, reason: string): Promise<string> {
190  try {
191    const request = { term, rule: ruleId, reason }
192    const checked = await approvalStep($, finding.cwd, { ...request, phase: 'check' })
193    const modelVocabulary = checked.modelVocabulary ? ' The extra model check and writing guidance will also treat this term as known vocabulary.' : ''
194    const answer = await $.ui.ask(`Approve ${JSON.stringify(term)} project-wide for the ${ruleId} rule? This waives that rule on every line containing this exact term, across the project. Other rules still apply.${modelVocabulary} This saves an exception in ${checked.config}. Reason: ${reason}`, {
195      header: 'Approve term', options: ['Approve for this project', 'Cancel'],
196    })
197    if (answer !== 'Approve for this project') return 'Project vocabulary was not changed.'
198    await approvalStep($, finding.cwd, { ...request, phase: 'write', expect: checked })
199    $.ui.invalidate('prompt.context')
200    return `Approved ${JSON.stringify(term)} for ${ruleId} across this project. Other rules still apply. Retry the checked write.`
201  } catch (error) {
202    return `Project vocabulary was not changed: ${String(error)}`
203  }
204}
205
206/**
207 * What `plain-english lint` prints for these paths, run in this process: the
208 * findings as text, the line for what `allow` hid, and any rule that ran out
209 * of time. Linting waits for the round that lacks no file, since a run that
210 * lacked one is discarded.
211 */
212function lintReport(cwd: string, paths: string[], io: unknown): string {
213  const replay = io as { missing(): unknown }
214  const ruleSet = resolveRuleSet(cwd, io)
215  const empty = { findings: [], timedOut: [], suppressed: [] }
216  const linted = lintTargets(paths, cwd, ruleSet, (text: string) => replay.missing() ? empty : lintText(text, ruleSet), io)
217  if ('missing' in linted) return `plain-english: no such path: ${linted.missing}`
218  const report = formatText(linted.all, cwd, 'file', io) + suppressedLine(linted.suppressed)
219  const notes = stalledNotes(linted.stalled, cwd, io).join('\n')
220  return `${report}${notes}`.trim()
221}
222
223/**
224 * One transcript row. `$.ui.log` draws a single line: Claude Code 2.1.294
225 * shows a line break inside it as U+FFFD and puts the plugin's name in front
226 * of the row itself, so the text carries neither (issue #80).
227 */
228function log($: EngineInterface, text: string): void {
229  $.ui.log(oneLine(text).replace(/^plain-english: /, ''))
230}
231
232async function session($: EngineInterface): Promise<{ id: string; cwd: string }> {
233  const [id, cwd] = await Promise.all([$.session.id(), $.session.cwd()])
234  return { id, cwd }
235}
236
237/** Which write channel a tool call belongs to, or none. */
238function channelOf(e: Readonly<Record<string, unknown>>): 'docs' | 'github' | 'issue' | undefined {
239  const tool = String(e['tool'])
240  if (tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit') {
241    return MARKDOWN.test(String(e['file_path'] ?? '')) ? 'docs' : undefined
242  }
243  if (tool === 'Bash') {
244    return classifyShellCommand(String(e['command'] ?? ''))
245  }
246  return ISSUE_TOOLS.test(tool) ? 'issue' : undefined
247}
248
249/**
250 * The chat gate, shared by the two stop events: the reply as the event
251 * carries it goes to the chat adapter. A block holds the turn with the
252 * reason, as the settings hook's flat JSON does, and never runs the settings
253 * hooks beneath, so a project that also installed them is judged once. A
254 * pass hands on to them.
255 *
256 * Verified live on 2.1.293: the block holds the turn in an interactive
257 * session and under `claude -p`, where a settings `Stop` block is ignored.
258 */
259async function judgeReply<E extends { last_assistant_message?: string }, R extends { block?: string }>(
260  $: EngineInterface,
261  e: E,
262  next: ((e: E) => Promise<R>) & { readonly signal: AbortSignal },
263  record: (finding: ReviewFinding) => void,
264): Promise<R | { block: string }> {
265  const cwd = await $.session.cwd()
266  const payload = e as unknown as Record<string, unknown>
267  const stdout = await adapter($, 'chat', payload, cwd, next.signal)
268  const verdict = readChatVerdict(stdout)
269  if (verdict.notice !== undefined) log($, noticeLine(verdict.notice, verdict.kind === 'block'))
270  if (verdict.kind === 'block') {
271    record({ channel: 'chat', reason: verdict.reason, strict: true, event: payload, cwd, key: '' })
272    return { block: verdict.reason }
273  }
274  if (verdict.notice !== undefined) record({ channel: 'chat', reason: verdict.notice, strict: false, event: payload, cwd, key: '' })
275  return next(e)
276}
277
278export const register: Register = on => {
279  let repair = false
280  const repairAttempts = new Set<string>()
281  const keepOnce = new Set<string>()
282  let actionNotice = ''
283  let exceptionReason = ''
284  let current: ReviewFinding | undefined
285  /**
286   * One tool.call hook serves the three write channels, picked by tool name.
287   * Fail-open: a `.catch` that calls `next(e)` lets the write through when the
288   * adapter itself fails, which is the contract every plain-english hook has.
289   */
290  on('tool.call', async ($, e, next) => {
291    const channel = channelOf(e)
292    if (channel === undefined) return next(e)
293
294    const here = await session($)
295    const payload = toolPayload(e, here)
296    const key = JSON.stringify([here.id, channel, e['agentId'] ?? '', payload['tool_name'], payload['tool_input']])
297    const stdout = await adapter($, channel, payload, here.cwd, next.signal)
298    const verdict = readToolVerdict(stdout)
299    if (verdict.kind !== 'allow') {
300      current = { channel, reason: verdict.reason, strict: verdict.kind === 'deny', event: e, cwd: here.cwd, key }
301      $.ui.invalidate('ui.render')
302    }
303
304    const repairKey = `${channel}:${String(e['agentId'] ?? '')}:${String(e['file_path'] ?? e['tool'])}`
305    if (verdict.kind === 'allow') repairAttempts.delete(repairKey)
306
307    if (verdict.kind === 'deny') return { deny: verdict.reason }
308    if (verdict.kind === 'ask') {
309      if (keepOnce.delete(key)) {
310        repairAttempts.delete(repairKey)
311        return next(e)
312      }
313      if (repair && !repairAttempts.has(repairKey)) {
314        repairAttempts.add(repairKey)
315        return { deny: `Rewrite attempt 1 of 1. Correct the quoted passages and retry this write. If findings remain, the user decides.\n\n${verdict.reason}` }
316      }
317      // The settings hook's `ask` hands the decision to the person. So does
318      // this, in the engine's own dialog, with a question written for them;
319      // the model's guidance travels in the deny. Nobody to ask (a -p run)
320      // refuses.
321      const ask = askFor(channel, e, here.cwd, verdict.reason)
322      let answer: string | undefined
323      try {
324        answer = await $.ui.ask(ask.question, {
325          header: ask.header,
326          options: [ask.allow, ask.refuse],
327        })
328      } catch {
329        // dismissed, or no one to ask
330      }
331      if (answer !== ask.allow) {
332        const decision = answer === ask.refuse ? 'The user was asked and refused this write.'
333          : answer ? `The user answered instead of choosing: ${JSON.stringify(answer)}`
334          : 'No approval was received. The dialog was unavailable, dismissed, or unanswered.'
335        return { deny: `${decision}\n\n${verdict.reason}` }
336      }
337      repairAttempts.delete(repairKey)
338    }
339    return next(e)
340  }).catch(($, e, next) => {
341    log($, `check unavailable; the write was allowed. ${next.error.message ?? 'The checker did not finish.'}`)
342    return next(e)
343  })
344
345  // Two registrations, not a loop: the validator reads each event name off the
346  // source as a string literal, and a name held in a variable does not load.
347  on('classic.Stop', ($, e, next) => judgeReply($, e, next, finding => {
348    current = finding
349    $.ui.invalidate('ui.render')
350  })).catch(($, e, next) => {
351    log($, `reply check unavailable; the reply was allowed. ${next.error.message ?? 'The checker did not finish.'}`)
352    return next(e)
353  })
354  on('classic.SubagentStop', ($, e, next) => judgeReply($, e, next, finding => {
355    current = finding
356    $.ui.invalidate('ui.render')
357  })).catch(($, e, next) => {
358    log($, `reply check unavailable; the reply was allowed. ${next.error.message ?? 'The checker did not finish.'}`)
359    return next(e)
360  })
361
362  on('session.start', async ($, e, next) => {
363    await $.command.register({
364      name: COMMAND,
365      description: 'Lint the working tree with plain-english and show the findings',
366      argumentHint: '[paths | review | status | repair on/off]',
367    })
368    return next(e)
369  })
370
371  on('prompt.context', async ($, e, next) => {
372    const base = await next(e)
373    try {
374      const cwd = await $.session.cwd()
375      const text = (await runCore($, cwd, io => projectGuidance(resolveRuleSet(cwd, io), io) as string, undefined)).trim()
376      if (new TextEncoder().encode(text).length > 32_768) throw new Error('Project writing guidance is too large (over 32 KB). Reduce project vocabulary or writing observations before loading it.')
377      if (text === '') return base
378      return { ...base, blocks: [...base.blocks.filter(block => block.name !== 'plainEnglishProject'), { name: 'plainEnglishProject', text }] }
379    } catch (error) {
380      log($, `project writing guidance unavailable. ${String(error)}`)
381      return base
382    }
383  })
384
385  on('command.run', { command: COMMAND }, async ($, e) => {
386    const cwd = await $.session.cwd()
387    if (e.args.trim() === 'review') {
388      await $.ui.open({ id: PANE, title: 'Plain English findings', focus: true, closeOnEscape: true })
389      return {}
390    }
391    if (e.args.trim() === 'status') {
392      return { text: `repair ${repair ? 'on' : 'off'} for this session. ${current === undefined ? 'No recent findings.' : `${readPassages(current.reason).length} quoted findings in the most recent check.`} Extra model checks follow project configuration; this command does not change them.` }
393    }
394    if (e.args.trim() === 'repair on' || e.args.trim() === 'repair off') {
395      repair = e.args.trim() === 'repair on'
396      repairAttempts.clear()
397      return { text: `repair ${repair ? 'on' : 'off'} for this session. ${repair ? 'Advisory writes get one correction attempt before asking you. Required checks still refuse.' : 'Advisory writes ask you immediately.'}` }
398    }
399    let paths: string[]
400    try {
401      paths = readPaths(e.args)
402    } catch (error) {
403      return { text: String(error) }
404    }
405    try {
406      // Each round of a walk fetches one level of the tree; the lint itself runs
407      // once, in the round that lacks nothing.
408      const text = await runCore($, cwd, io => lintReport(cwd, paths, io), undefined, 64)
409      return { text: text === '' ? 'no findings.' : text }
410    } catch (error) {
411      return { text: `check unavailable. ${String(error)}` }
412    }
413  })
414
415  on('ui.render', { component: 'Pane' }, ($, e, next) => {
416    if (e.requestId !== PANE) return next(e)
417    const { Box, Text, Button, Input } = $.ui.resolve(e)
418    const displayed = current
419    const passages = current === undefined ? [] : readPassages(current.reason)
420    return Box({ flexDirection: 'column', children: [
421      Text({ bold: true, children: [passages.length === 0 && current !== undefined ? 'Latest finding' : `${passages.length} findings`] }),
422      Text({ children: [`Repair ${repair ? 'on' : 'off'} for this session.`] }),
423      Text({ children: [current === undefined ? 'No recent finding.' : `Most recent finding in ${String(current.event['file_path'] ?? current.channel)}.`] }),
424      ...passages.map(passage => Text({ children: [`line ${passage.line}: ${JSON.stringify(passage.match)} (${passage.ruleId})${passage.hint === undefined ? '' : ' ' + passage.hint}`] })),
425      ...(displayed === undefined ? [] : [Input({ key: 'exception-reason', label: 'Reason for an exception', value: exceptionReason, placeholder: 'Explain why this wording belongs here', onSubmit: text => {
426        exceptionReason = text.trim()
427        $.ui.invalidate('ui.render')
428      } })]),
429      ...passages.flatMap((passage, index) => {
430        if (displayed === undefined || !/^[A-Za-z][\w .-]{0,79}$/.test(passage.match) || /(?:length|count|paragraph|sentence|structure)/.test(passage.ruleId)) return []
431        return [Button({ key: `approve-term-${index}`, label: `Approve ${JSON.stringify(passage.match)} for this rule`, onPress: async () => {
432          if (exceptionReason === '') actionNotice = 'Enter a reason and press Enter before approving a project term.'
433          else actionNotice = await approveProjectTerm($, displayed, passage.match, passage.ruleId, exceptionReason)
434          $.ui.invalidate('ui.render')
435        } })]
436      }),
437      ...(displayed?.channel !== 'docs' ? [] : passages.map((passage, index) => Button({
438        key: `copy-exception-${index}`, label: `Copy next-line exception for ${passage.ruleId}`, onPress: async () => {
439          if (exceptionReason === '' || /[\r\n\x00-\x1f]|-->/.test(exceptionReason)) {
440            actionNotice = 'Enter a one-line reason without comment markup, then press Enter.'
441          } else {
442            const comment = `<!-- plain-english-disable-next-line ${passage.ruleId}: ${exceptionReason} -->`
443            const copied = await $.ui.copy({ text: comment })
444            actionNotice = copied.isCopied
445              ? `Copied ${comment}. Paste it immediately above the intended passage. This exempts one rule on the next line; no file was changed.`
446              : `Clipboard unavailable. Paste ${comment} immediately above the intended passage.`
447          }
448          $.ui.invalidate('ui.render')
449        },
450      }))),
451      Text({ children: [current?.channel === 'chat'
452        ? current.strict ? 'Required reply checks refuse this reply. Correct it or add a justified project exception.' : 'The reply was allowed with advice. No temporary reply waiver was created.'
453        : current?.strict ? 'Required checks refuse this write. Correct it or add a justified project exception.' : 'Keep this write once in the advisory decision dialog, or refuse so Claude rewrites.'] }),
454      ...(displayed === undefined || displayed.strict || displayed.channel === 'chat' ? [] : [Button({ key: 'keep-once', label: 'Keep this write once', onPress: () => {
455        keepOnce.add(displayed.key)
456        actionNotice = 'Approved the identical write once for this session. Ask Claude to retry it. Changed text still gets checked.'
457        $.ui.invalidate('ui.render')
458      } })]),
459      ...(actionNotice === '' ? [] : [Text({ children: [actionNotice] })]),
460      ...(passages.length === 0 && current !== undefined ? [Text({ children: [current.reason] })] : []),
461    ] })
462  })
463}
464
hooks/shell.mjs 380 lines
1// GENERATED by scripts/build-plugin.mjs from src/shell.ts. Do not edit.
2
3// src/shell.ts
4function windowsPathPrefix(text) {
5  return /^(?:-[FC]|--(?:file|body-file|notes-file)=)?(?:[A-Za-z]:|\\\\)/.test(text);
6}
7var SEPARATORS = /* @__PURE__ */ new Set([";", "\n", "&"]);
8function parseCommands(input) {
9  const commands = [];
10  let current = { words: [], redirects: [], heredocs: [], unterminated: false };
11  let word = "";
12  let quoted = false;
13  let expands = false;
14  let pendingRedirect = null;
15  const pendingHeredocs = [];
16  const endWord = () => {
17    if (!word && !quoted) return;
18    const w = { text: word, expands };
19    if (pendingRedirect) {
20      current.redirects.push({ target: w, exotic: pendingRedirect.exotic });
21      pendingRedirect = null;
22    } else {
23      current.words.push(w);
24    }
25    word = "";
26    quoted = false;
27    expands = false;
28  };
29  const endCommand = () => {
30    endWord();
31    if (current.words.length || current.redirects.length || current.heredocs.length) {
32      commands.push(current);
33    }
34    current = { words: [], redirects: [], heredocs: [], unterminated: false };
35  };
36  let i = 0;
37  while (i < input.length) {
38    const c = input[i];
39    if (c === "\n" && pendingHeredocs.length) {
40      endWord();
41      i++;
42      for (const h of pendingHeredocs.splice(0)) {
43        const body = [];
44        let closed = false;
45        while (i < input.length) {
46          let nl = input.indexOf("\n", i);
47          if (nl === -1) nl = input.length;
48          const line = input.slice(i, nl);
49          i = nl + 1;
50          if ((h.raw ? line.replace(/^\t+/, "") : line.trim()) === h.tag) {
51            closed = true;
52            break;
53          }
54          body.push(line);
55        }
56        if (!closed) current.unterminated = true;
57        current.heredocs.push(body.join("\n"));
58      }
59      continue;
60    }
61    if (c === "\\") {
62      if (/^(?:-[FC]|--(?:file|body-file|notes-file)=)?$/.test(word) && input[i + 1] === "\\" && /[A-Za-z0-9]/.test(input[i + 2] ?? "")) {
63        word += "\\\\";
64        i += 2;
65        continue;
66      }
67      if (windowsPathPrefix(word)) {
68        word += c;
69        i++;
70        continue;
71      }
72      if (input[i + 1] === "\n") {
73        i += 2;
74        continue;
75      }
76      if (i + 1 < input.length) {
77        word += input[i + 1];
78        quoted = true;
79        i += 2;
80        continue;
81      }
82      i++;
83      continue;
84    }
85    if (c === "'") {
86      const close = input.indexOf("'", i + 1);
87      if (close === -1) {
88        current.unterminated = true;
89        break;
90      }
91      word += input.slice(i + 1, close);
92      quoted = true;
93      i = close + 1;
94      continue;
95    }
96    if (c === '"') {
97      let j = i + 1;
98      let out = "";
99      let closed = false;
100      while (j < input.length) {
101        if (input[j] === "\\" && j + 1 < input.length) {
102          if (!out && input[j + 1] === "\\" && /[A-Za-z0-9]/.test(input[j + 2] ?? "")) {
103            out = "\\\\";
104            j += 2;
105          } else if (windowsPathPrefix(out)) {
106            out += "\\";
107            j++;
108          } else if ('\\"$`'.includes(input[j + 1])) {
109            out += input[j + 1];
110            j += 2;
111          } else if (input[j + 1] === "\n") {
112            j += 2;
113          } else {
114            out += "\\";
115            j++;
116          }
117          continue;
118        }
119        if (input[j] === '"') {
120          closed = true;
121          break;
122        }
123        if (input[j] === "$" || input[j] === "`") expands = true;
124        out += input[j];
125        j++;
126      }
127      if (!closed) {
128        current.unterminated = true;
129        break;
130      }
131      word += out;
132      quoted = true;
133      i = j + 1;
134      continue;
135    }
136    if (c === "`") {
137      expands = true;
138      let j = i + 1;
139      while (j < input.length && input[j] !== "`") {
140        if (input[j] === "\\") j++;
141        j++;
142      }
143      if (j >= input.length) {
144        current.unterminated = true;
145        break;
146      }
147      word += input.slice(i, j + 1);
148      i = j + 1;
149      continue;
150    }
151    if (c === "$") {
152      expands = true;
153      word += c;
154      i++;
155      continue;
156    }
157    if (c === "<" && input[i + 1] === "<") {
158      if (input[i + 2] === "<") {
159        endWord();
160        i += 3;
161        continue;
162      }
163      endWord();
164      let j = i + 2;
165      const raw = input[j] === "-";
166      if (raw) j++;
167      while (input[j] === " " || input[j] === "	") j++;
168      let tag = "";
169      let q = "";
170      if (input[j] === "'" || input[j] === '"') {
171        q = input[j];
172        j++;
173      }
174      while (j < input.length && /[A-Za-z0-9_]/.test(input[j])) tag += input[j++];
175      if (q && input[j] === q) j++;
176      if (tag) pendingHeredocs.push({ tag, raw });
177      i = j;
178      continue;
179    }
180    if (c === ">") {
181      endWord();
182      let j = i + 1;
183      let exotic = false;
184      if (input[j] === ">") j++;
185      if (input[j] === "&" || input[j] === "(") {
186        exotic = true;
187        j++;
188      }
189      const prev = current.words[current.words.length - 1];
190      if (prev && /^\d$/.test(prev.text) && !prev.expands) {
191        current.words.pop();
192        exotic = true;
193      }
194      pendingRedirect = { exotic };
195      i = j;
196      continue;
197    }
198    if (c === "<") {
199      endWord();
200      i++;
201      while (i < input.length && /\s/.test(input[i])) i++;
202      while (i < input.length && !/[\s;&|<>]/.test(input[i])) i++;
203      continue;
204    }
205    if (c === "|") {
206      endCommand();
207      i += input[i + 1] === "|" ? 2 : 1;
208      continue;
209    }
210    if (SEPARATORS.has(c)) {
211      endCommand();
212      i += input[i + 1] === c && c === "&" ? 2 : 1;
213      continue;
214    }
215    if (c === " " || c === "	" || c === "\r") {
216      endWord();
217      i++;
218      continue;
219    }
220    if (c === "(" || c === ")") {
221      endCommand();
222      i++;
223      continue;
224    }
225    word += c;
226    i++;
227  }
228  endCommand();
229  return commands;
230}
231var ECHO_FLAGS = /* @__PURE__ */ new Set(["-e", "-n", "-E"]);
232function printfContent(words) {
233  let args = words;
234  if (args[0]?.text === "--") args = args.slice(1);
235  else if (args[0]?.text.startsWith("-")) return "";
236  if (!args.length || args.some((word) => word.expands)) return "";
237  const format = args[0].text;
238  const tokens = [];
239  let literal = "";
240  let conversions = 0;
241  const escapes = {
242    n: "\n",
243    t: "	",
244    r: "\r",
245    a: "\x07",
246    b: "\b",
247    f: "\f",
248    v: "\v",
249    "\\": "\\"
250  };
251  for (let i = 0; i < format.length; i++) {
252    const char = format[i];
253    if (char === "%") {
254      const next = format[++i];
255      if (next === "%") literal += "%";
256      else if (next === "s") {
257        tokens.push(literal, null);
258        literal = "";
259        conversions++;
260      } else return "";
261    } else if (char === "\\") {
262      const escaped = escapes[format[++i] ?? ""];
263      if (escaped === void 0) return "";
264      literal += escaped;
265    } else literal += char;
266  }
267  tokens.push(literal);
268  let argument = 1;
269  let size = 0;
270  const result = [];
271  do {
272    for (const token of tokens) {
273      const text = token === null ? args[argument++]?.text ?? "" : token;
274      size += text.length;
275      if (size > 256 * 1024) return "";
276      result.push(text);
277    }
278  } while (conversions > 0 && argument < args.length);
279  return result.join("");
280}
281function contentOf(cmd) {
282  if (cmd.heredocs.length) return cmd.heredocs.join("\n");
283  const name = cmd.words[0]?.text ?? "";
284  if (name !== "printf" && name !== "echo") return "";
285  if (name === "printf") return printfContent(cmd.words.slice(1));
286  const args = cmd.words.slice(1).filter((w) => !ECHO_FLAGS.has(w.text));
287  if (args.some((a) => a.expands)) return "";
288  const texts = args.map((a) => a.text);
289  return texts.join(" ");
290}
291function shellFileWrites(input, baseDir) {
292  const out = [];
293  let cwd = baseDir;
294  for (const cmd of parseCommands(input)) {
295    if (cmd.unterminated) continue;
296    if (cmd.words[0]?.text === "cd" && cwd !== void 0) {
297      const target = cmd.words[1];
298      if (target && !target.expands && cmd.words.length === 2) cwd = resolveDirectory(cwd, target.text);
299      continue;
300    }
301    const targetPath = (path) => cwd === void 0 ? path : resolveDirectory(cwd, path);
302    const text = contentOf(cmd);
303    if (!text.trim()) continue;
304    const plain = cmd.redirects.filter((r) => !r.exotic && !r.target.expands && r.target.text);
305    if (plain.length === 1) {
306      out.push({ path: targetPath(plain[0].target.text), text });
307      continue;
308    }
309    if (plain.length > 1) continue;
310    if (cmd.redirects.length) continue;
311    if ((cmd.words[0]?.text ?? "") !== "tee") continue;
312    const targets = cmd.words.slice(1).filter((w) => !w.text.startsWith("-"));
313    if (targets.length !== 1 || targets[0].expands) continue;
314    out.push({ path: targetPath(targets[0].text), text });
315  }
316  return out;
317}
318function resolveDirectory(base, path) {
319  const windows = /^[A-Za-z]:[\\/]|^\\\\/.test(base) || /^[A-Za-z]:[\\/]|^\\\\/.test(path);
320  const slash = windows ? "\\" : "/";
321  const absolute = /^[A-Za-z]:[\\/]|^[\\/]/.test(path);
322  const joined = absolute ? path : base + slash + path;
323  const network = windows && joined.startsWith("\\\\");
324  const prefix = network ? slash + slash : windows ? (/^[A-Za-z]:/.exec(joined)?.[0] ?? "") + slash : joined.startsWith("/") ? "/" : "";
325  const parts = [];
326  for (const part of joined.replace(/^[A-Za-z]:/, "").split(/[\\/]+/)) {
327    if (!part || part === ".") continue;
328    if (part === "..") {
329      if (parts.length > (network ? 2 : 0)) parts.pop();
330    } else parts.push(part);
331  }
332  return prefix + parts.join(slash);
333}
334function gitCommand(cmd, cwd) {
335  let i = 1;
336  while (i < cmd.words.length) {
337    const option = cmd.words[i].text;
338    if (!option.startsWith("-")) return { subcommand: option, index: i, cwd };
339    if (option === "-C" || option === "-c" || option === "--git-dir" || option === "--work-tree") {
340      const value = cmd.words[++i];
341      if (!value || value.expands) return { subcommand: "", index: i, cwd };
342      if (option === "-C") cwd = resolveDirectory(cwd, value.text);
343    } else if (option.startsWith("-C") && option.length > 2) cwd = resolveDirectory(cwd, option.slice(2));
344    i++;
345  }
346  return { subcommand: "", index: i, cwd };
347}
348function publishingCommands(input, baseDir) {
349  const out = [];
350  let cwd = baseDir;
351  for (const cmd of parseCommands(input)) {
352    if (cmd.unterminated || cmd.words[0]?.expands) continue;
353    const name = cmd.words[0]?.text;
354    if (name === "cd") {
355      const target = cmd.words[1];
356      if (target && !target.expands && cmd.words.length === 2) cwd = resolveDirectory(cwd, target.text);
357      continue;
358    }
359    if (name === "git") {
360      const git = gitCommand(cmd, cwd);
361      if (git.subcommand === "commit") out.push({ args: cmd.words.slice(git.index + 1), cwd: git.cwd, heredocs: cmd.heredocs });
362    } else if (name === "gh") {
363      const kind = cmd.words[1]?.text;
364      const action = cmd.words[2]?.text;
365      const actions = kind === "pr" ? ["create", "edit", "comment", "review"] : kind === "issue" ? ["create", "edit", "comment"] : kind === "release" ? ["create", "edit"] : [];
366      if (action && actions.includes(action)) out.push({ args: cmd.words.slice(3), cwd, heredocs: cmd.heredocs });
367    }
368  }
369  return out;
370}
371function classifyShellCommand(input) {
372  if (input.length > 256 * 1024) return void 0;
373  if (publishingCommands(input, "").length) return "github";
374  if (input.includes("*** Begin Patch") || shellFileWrites(input).some((f) => /\.(md|markdown|mdx)$/i.test(f.path))) return "docs";
375  return void 0;
376}
377export {
378  classifyShellCommand
379};
380
hooks/issue-tools.mjs 9 lines
1// GENERATED by scripts/build-plugin.mjs from src/agents/issue-tools.ts. Do not edit.
2
3// src/agents/issue-tools.ts
4var ISSUE_TOOL_PATTERN = "^(?:.*[_:]|MCP:)?(?:save_(?:issue|comment)|createJiraIssue|editJiraIssue|addOrEditJiraIssueComment|createConfluenceContent|updateConfluenceContent|createConfluenceComment|updateConfluenceComment)$";
5var ISSUE_TOOLS = new RegExp(ISSUE_TOOL_PATTERN);
6export {
7  ISSUE_TOOLS
8};
9
skills/plain-english/scripts/core/plugin-core.mjs 3280 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2import {
3  chatRuleSet,
4  compile,
5  isShoutedWord,
6  jargonTerms,
7  loadDefault,
8  maskNonProse,
9  matchAllWithDeadline,
10  matchesAny,
11  nodeIo,
12  parseDocument,
13  resolveRuleSet,
14  sentences,
15  sha256
16} from "./chunk-JLXHTBYJ.mjs";
17import "./chunk-ZVATLAGB.mjs";
18import "./chunk-IKH6G3OL.mjs";
19import "./chunk-KWWQFVSE.mjs";
20import "./chunk-VC7IYITB.mjs";
21import "./chunk-OJMZKB7F.mjs";
22import "./chunk-UGEYTODJ.mjs";
23import "./chunk-NJUDQNQS.mjs";
24import {
25  isMap,
26  isSeq
27} from "./chunk-ZVNRIHJD.mjs";
28
29var ZERO_WIDTH = /[\u200b\u200c\u200d\u2060\ufeff]/g;
30var DASH_VARIANTS = {
31  "\u2014": "\u2014",
32  "\u2015": "\u2014",
33  "\uFF0D": "\u2014",
34  "\u2E3A": "\u2014",
35  "\u2E3B": "\u2014"
36};
37var HYPHEN_VARIANTS = {
38  "\u2011": "-",
39  "\u2012": "-",
40  "\uFE63": "-"
41};
42var DASH_ENTITIES = [
43  [/&mdash;/gi, "\u2014"],
44  [/&#8212;/g, "\u2014"],
45  [/&#x2014;/gi, "\u2014"],
46  [/&ndash;/gi, "\u2013"],
47  [/&#8211;/g, "\u2013"]
48];
49function normaliseForMatching(text) {
50  let out = text;
51  out = out.replace(/[―-⸺⸻]/g, (c) => DASH_VARIANTS[c] ?? c);
52  out = out.replace(/[‑‒﹣]/g, (c) => HYPHEN_VARIANTS[c] ?? c);
53  for (const [re, replacement] of DASH_ENTITIES) {
54    out = out.replace(re, (m) => replacement + " ".repeat(m.length - replacement.length));
55  }
56  if (out.length !== text.length) {
57    return text;
58  }
59  return out;
60}
61function stripZeroWidth(text) {
62  ZERO_WIDTH.lastIndex = 0;
63  if (!ZERO_WIDTH.test(text)) return { text, map: null };
64  let out = "";
65  const map = [];
66  for (let i = 0; i < text.length; i++) {
67    const ch = text[i];
68    if (/[\u200b\u200c\u200d\u2060\ufeff]/.test(ch)) continue;
69    map.push(i);
70    out += ch;
71  }
72  return { text: out, map };
73}
74
75var DEFAULT_BUDGET_MS = 2e3;
76var REASON = "(?:\\s*:\\s*([^>]*?))?";
77var SUPPRESS_NEXT = new RegExp(
78  `<!--\\s*plain-english-disable-next-line(?:\\s+([a-z0-9,\\s-]+?))?${(REASON)}\\s*-->`,
79  "i"
80);
81var SUPPRESS_FILE = new RegExp(
82  `<!--\\s*plain-english-disable-file${(REASON)}\\s*-->`,
83  "i"
84);
85var SUPPRESS_RANGE_OFF = new RegExp(
86  `<!--\\s*plain-english-disable(?:\\s+([a-z0-9,\\s-]+?))?${(REASON)}\\s*-->`,
87  "i"
88);
89var SUPPRESS_RANGE_ON = /<!--\s*plain-english-enable(?:\s+([a-z0-9,\s-]+?))?\s*-->/i;
90function lineIndex(text) {
91  const starts = [0];
92  for (let i = 0; i < text.length; i++) {
93    if (text[i] === "\n") starts.push(i + 1);
94  }
95  return starts;
96}
97function locate(starts, offset) {
98  let lo = 0;
99  let hi = starts.length - 1;
100  while (lo < hi) {
101    const mid = lo + hi + 1 >> 1;
102    if (starts[mid] <= offset) lo = mid;
103    else hi = mid - 1;
104  }
105  return { line: lo + 1, column: offset - starts[lo] + 1 };
106}
107function parseIds(raw) {
108  const ids = (raw ?? "").split(",").map((s) => s.trim()).filter(Boolean);
109  return ids.length ? new Set(ids) : "all";
110}
111function merge(a, b) {
112  if (a === void 0) return b;
113  if (a === "all" || b === "all") return "all";
114  return   new Set([...a, ...b]);
115}
116function allowedBy(ruleSet, ruleId, text) {
117  return ruleSet.allowRe?.find(
118    (a) => (!a.rules || a.rules.has(ruleId)) && a.re.test(text)
119  );
120}
121function suppressionsFor(sourceLines) {
122  const map =   new Map();
123  sourceLines.forEach((line, i) => {
124    const m = SUPPRESS_NEXT.exec(line);
125    if (!m) return;
126    map.set(i + 2, merge(map.get(i + 2), parseIds(m[1])));
127  });
128  let active = null;
129  sourceLines.forEach((line, i) => {
130    const isNext = SUPPRESS_NEXT.test(line);
131    const isFile = SUPPRESS_FILE.test(line);
132    const on = !isNext && !isFile ? SUPPRESS_RANGE_ON.exec(line) : null;
133    const off = !isNext && !isFile ? SUPPRESS_RANGE_OFF.exec(line) : null;
134    if (on) {
135      const ids = parseIds(on[1]);
136      if (ids === "all" || active === "all" || active === null) active = null;
137      else {
138        for (const id of ids) active.delete(id);
139        if (active.size === 0) active = null;
140      }
141      return;
142    }
143    if (off) {
144      active = merge(active ?? void 0, parseIds(off[1]));
145      return;
146    }
147    if (active !== null) map.set(i + 1, merge(map.get(i + 1), active));
148  });
149  return map;
150}
151function lintText(text, ruleSet, options = {}) {
152  const { allowInlineSuppression = true, budgetMs = DEFAULT_BUDGET_MS } = options;
153  const findings = [];
154  const timedOut = [];
155  const silenced = [];
156  const deadline = Date.now() + budgetMs;
157  const directiveView = maskNonProse(text);
158  const normalised = normaliseForMatching(maskNonProse(text, { maskComments: true }));
159  const compacted = stripZeroWidth(normalised);
160  const masked = compacted.text;
161  const toSource = (i) => compacted.map?.[i] ?? i;
162  const starts = lineIndex(text);
163  const sourceLines = text.split("\n");
164  const maskedLines = normalised.split("\n");
165  if (allowInlineSuppression) {
166    findings.push(
167      ...unexplainedSuppressions(text, directiveView, ruleSet, sourceLines, silenced)
168    );
169  }
170  if (allowInlineSuppression && SUPPRESS_FILE.test(directiveView)) {
171    return {
172      findings,
173      errorCount: findings.filter((f) => f.severity === "error").length,
174      warnCount: findings.filter((f) => f.severity === "warn").length,
175      suppressed: silenced,
176      timedOut
177    };
178  }
179  const suppressed = allowInlineSuppression ? suppressionsFor(directiveView.split("\n")) :   new Map();
180  const wordCount = (masked.match(/\b[\p{L}\p{N}'-]+\b/gu) ?? []).length;
181  for (const rule of ruleSet.rules) {
182    if (rule.severity === "off" || !rule.re) continue;
183    if (rule.perThousandWords !== void 0) {
184      const all = matchAllWithDeadline(rule.re, masked, deadline - Date.now());
185      if (all === null) {
186        timedOut.push(rule.id);
187        continue;
188      }
189      const hits = all.filter((d) => d[0].length > 0);
190      if (!hits.length || wordCount === 0) continue;
191      const rate = hits.length / wordCount * 1e3;
192      if (rate <= rule.perThousandWords) continue;
193      const first = hits[0];
194      const startAt = toSource(first.index);
195      const { line, column } = locate(starts, startAt);
196      const finding = {
197        ruleId: rule.id,
198        severity: rule.severity,
199        match: text.slice(startAt, toSource(first.index + first[0].length - 1) + 1),
200        line,
201        column,
202        lineText: sourceLines[line - 1] ?? "",
203        message: `${hits.length} in ${wordCount} words is ${rate.toFixed(1)} per 1,000, over the ${rule.perThousandWords} threshold` + (rule.message ? `. ${rule.message}` : "")
204      };
205      if (rule.link) finding.link = rule.link;
206      findings.push(finding);
207      continue;
208    }
209    const matches = matchAllWithDeadline(rule.re, masked, deadline - Date.now());
210    if (matches === null) {
211      timedOut.push(rule.id);
212      continue;
213    }
214    for (const m of matches) {
215      if (m[0].length === 0) continue;
216      const sourceStart = toSource(m.index);
217      const sourceEnd = toSource(m.index + m[0].length - 1) + 1;
218      const { line, column } = locate(starts, sourceStart);
219      const maskedLine = maskedLines[line - 1] ?? "";
220      const sourceLine = sourceLines[line - 1] ?? "";
221      if (rule.unlessRe?.some((re) => re.test(maskedLine))) continue;
222      const allowed = allowedBy(ruleSet, rule.id, maskedLine);
223      if (allowed) {
224        silenced.push({ pattern: allowed.entry.pattern, ruleId: rule.id, line });
225        continue;
226      }
227      const sup = suppressed.get(line);
228      if (sup === "all" || sup instanceof Set && sup.has(rule.id)) continue;
229      const finding = {
230        ruleId: rule.id,
231        severity: rule.severity,
232        match: text.slice(sourceStart, sourceEnd),
233        line,
234        column,
235        lineText: sourceLine
236      };
237      if (rule.message) finding.message = rule.message;
238      if (rule.link) finding.link = rule.link;
239      findings.push(finding);
240    }
241  }
242  findings.push(
243    ...readabilityFindings(text, ruleSet, starts, sourceLines, suppressed, silenced)
244  );
245  const familyByRule = new Map([
246    ...ruleSet.rules.map((rule) => [rule.id, rule.family]),
247    ...ruleSet.readability.map((rule) => [rule.id, rule.family])
248  ]);
249  const sentenceRows = sentences(text);
250  for (const family of ruleSet.families ?? []) {
251    if (family.severity === "off") continue;
252    const members = findings.filter((finding) => familyByRule.get(finding.ruleId) === family.id);
253    if (members.length < family.minFindings) continue;
254    const ruleIds = [...new Set(members.map((finding) => finding.ruleId))].sort();
255    if (ruleIds.length < family.minRules) continue;
256    const sentenceIds = new Set(members.map((finding) => {
257      const offset = (starts[finding.line - 1] ?? 0) + finding.column - 1;
258      return sentenceRows.findIndex((sentence) => offset >= sentence.start && offset < sentence.end);
259    }).filter((id) => id >= 0));
260    if (sentenceIds.size < family.minSentences) continue;
261    const first = [...members].sort((a, b) => a.line - b.line || a.column - b.column)[0];
262    const ruleId = `family-${family.id}`;
263    const sup = suppressed.get(first.line);
264    if (sup === "all" || sup instanceof Set && sup.has(ruleId)) continue;
265    findings.push({
266      ruleId,
267      severity: family.severity,
268      match: first.match,
269      line: first.line,
270      column: first.column,
271      lineText: first.lineText,
272      message: family.message ?? `${members.length} related findings form a repeated pattern.`,
273      family: family.id,
274      hitCount: members.length,
275      relatedRuleIds: ruleIds
276    });
277  }
278  findings.sort((a, b) => a.line - b.line || a.column - b.column || a.ruleId.localeCompare(b.ruleId));
279  return {
280    findings,
281    errorCount: findings.filter((f) => f.severity === "error").length,
282    warnCount: findings.filter((f) => f.severity === "warn").length,
283    suppressed: silenced,
284    timedOut
285  };
286}
287var OPENERS = [
288  { re: SUPPRESS_NEXT, scope: "line", idGroup: 1, reason: 2 },
289  { re: SUPPRESS_FILE, scope: "file", idGroup: 0, reason: 1 },
290  { re: SUPPRESS_RANGE_OFF, scope: "range", idGroup: 1, reason: 2 }
291];
292function directivesIn(text, view = maskNonProse(text)) {
293  const out = [];
294  view.split("\n").forEach((line, i) => {
295    for (const opener of OPENERS) {
296      const m = opener.re.exec(line);
297      if (!m) continue;
298      const reason = (m[opener.reason] ?? "").trim();
299      const directive = {
300        scope: opener.scope,
301        ids: opener.idGroup ? (m[opener.idGroup] ?? "").split(",").map((s) => s.trim()).filter(Boolean) : [],
302        line: i + 1,
303        column: m.index + 1,
304        text: m[0]
305      };
306      if (reason) directive.reason = reason;
307      out.push(directive);
308      return;
309    }
310  });
311  return out;
312}
313function unexplainedSuppressions(text, directiveView, ruleSet, sourceLines, silenced) {
314  const rule = (ruleSet.readability ?? []).find(
315    (r) => r.kind === "unexplained-suppression"
316  );
317  if (!rule || rule.severity === "off") return [];
318  const severity = rule.severity;
319  const findings = [];
320  for (const d of directivesIn(text, directiveView)) {
321    if (d.reason) continue;
322    const sourceLine = sourceLines[d.line - 1] ?? "";
323    const allowed = allowedBy(ruleSet, rule.id, sourceLine);
324    if (allowed) {
325      silenced.push({ pattern: allowed.entry.pattern, ruleId: rule.id, line: d.line });
326      continue;
327    }
328    const finding = {
329      ruleId: rule.id,
330      severity,
331      match: d.text,
332      line: d.line,
333      column: d.column,
334      lineText: sourceLine
335    };
336    if (rule.message) finding.message = rule.message;
337    if (rule.link) finding.link = rule.link;
338    findings.push(finding);
339  }
340  return findings;
341}
342function isGlossed(text, start, end) {
343  const before = text.slice(Math.max(0, start - 60), start);
344  const after = text.slice(end, end + 40);
345  return /\b(called|named|known as|termed|dubbed|abbreviated|short for|stands for|an acronym for)\s+[("'`]?$/i.test(before) || /^[)"'`]?\s*(stands for|means|is short for)\b/i.test(after) || /^[)"'`]?\s*,\s*(which|meaning)\b/i.test(after) || /^\s*\(/.test(after) ||  
346  /[a-z]\s*\(\s*$/.test(before);
347}
348function firstLineEnd(text) {
349  const nl = text.indexOf("\n");
350  return nl === -1 ? Math.min(text.length, 80) : Math.min(nl, 80);
351}
352function closingQuestion(masked) {
353  const end = masked.replace(/\s+$/, "").length;
354  if (end === 0 || masked[end - 1] !== "?") return null;
355  let start = 0;
356  for (let i = end - 2; i > 0; i--) {
357    const c = masked[i];
358    if (c === "." || c === "!" || c === "?" || c === "\n") {
359      start = i + 1;
360      break;
361    }
362  }
363  const text = masked.slice(start, end).trim();
364  if (!text) return null;
365  return { text, start: start + (masked.slice(start, end).length - masked.slice(start, end).trimStart().length), end };
366}
367var SUBORDINATORS = /\b(whether|which|that|because|while|unless|although|so that|rather than|instead of|the same|as the|when the)\b/gi;
368function subordinators(question) {
369  const body = question.replace(/^(which|what|who|whose|how)\b/i, "");
370  return (body.match(SUBORDINATORS) ?? []).length;
371}
372var IDENTIFIER_NAME = /(?:^|[\s"'(\[|`])((?:--?[a-z][a-z0-9-]{1,}|[a-z][a-z0-9]*(?:[-_][a-z0-9]+)+|[\w./~-]+\.[a-z]{2,4}|~?\/[\w./-]{3,}))(?=[\s"')\].,;:|`]|$)/gi;
373function readabilityFindings(text, ruleSet, starts, sourceLines, suppressed, silenced) {
374  const active = (ruleSet.readability ?? []).filter((r) => r.severity !== "off");
375  if (!active.length) return [];
376  const out = [];
377  const add = (rule, start, end, message) => {
378    const { line, column } = locate(starts, start);
379    const sup = suppressed.get(line);
380    if (sup === "all" || sup instanceof Set && sup.has(rule.id)) return;
381    const finding = {
382      ruleId: rule.id,
383      severity: rule.severity,
384      match: text.slice(start, end),
385      line,
386      column,
387      lineText: sourceLines[line - 1] ?? ""
388    };
389    const msg = message ?? rule.message;
390    if (msg) finding.message = msg;
391    if (rule.link) finding.link = rule.link;
392    out.push(finding);
393  };
394  for (const rule of active) {
395    if (rule.kind === "reply-length") {
396      const max = rule.maxWords ?? 250;
397      let words = 0;
398      for (const sentence of sentences(text)) words += sentence.words;
399      if (words > max) {
400        add(
401          rule,
402          0,
403          Math.min(text.length, firstLineEnd(text)),
404          `${words} words of prose, over ${max}.` + (rule.message ? ` ${rule.message}` : "")
405        );
406      }
407      continue;
408    }
409    if (rule.kind === "reader-load") {
410      const max = rule.maxTerms ?? 15;
411      const names =   new Set();
412      for (const declared of rule.names ?? []) {
413        const literal = declared.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
414        const pattern = new RegExp(`(?<![\\p{L}\\p{N}_])${literal}(?![\\p{L}\\p{N}_])`, "u");
415        if (pattern.test(text)) names.add(declared.toLowerCase());
416      }
417      for (const m of text.matchAll(/(?<!`)`([^`\n]{1,80})`(?!`)/g)) {
418        const name = (m[1] ?? "").trim();
419        if (name) names.add(name.toLowerCase());
420      }
421      for (const m of text.matchAll(IDENTIFIER_NAME)) {
422        const name = (m[1] ?? "").trim().toLowerCase().replace(/[.,;:]+$/, "");
423        if (name.length > 2) names.add(name);
424      }
425      if (names.size > max) {
426        add(
427          rule,
428          0,
429          Math.min(text.length, firstLineEnd(text)),
430          `${names.size} separate names, over ${max}.` + (rule.message ? ` ${rule.message}` : "")
431        );
432      }
433      continue;
434    }
435    if (rule.kind === "reply-pace") {
436      const floor = rule.minWords ?? 80;
437      const max = rule.maxMeanWords ?? 13;
438      let words = 0;
439      let count = 0;
440      for (const sentence of sentences(text)) {
441        words += sentence.words;
442        count++;
443      }
444      if (count > 0 && words >= floor) {
445        const mean = words / count;
446        if (mean > max) {
447          add(
448            rule,
449            0,
450            Math.min(text.length, firstLineEnd(text)),
451            `${mean.toFixed(1)} words a sentence on average, over ${max}.` + (rule.message ? ` ${rule.message}` : "")
452          );
453        }
454      }
455      continue;
456    }
457    if (rule.kind === "unreadable-ask") {
458      const max = rule.maxWords ?? 15;
459      const maxClauses = rule.maxClauses ?? 1;
460      const ask = closingQuestion(maskNonProse(text));
461      if (ask) {
462        const words = (ask.text.match(/\b[\p{L}\p{N}'-]+\b/gu) ?? []).length;
463        const clauses = subordinators(ask.text);
464        if (words > max || clauses > maxClauses) {
465          const why = words > max ? `${words} words, over ${max}.` : `${clauses} clauses to unpack before it can be answered.`;
466          add(rule, ask.start, ask.end, why + (rule.message ? ` ${rule.message}` : ""));
467        }
468      }
469      continue;
470    }
471    if (rule.kind === "long-sentence") {
472      const max = rule.maxWords ?? 35;
473      for (const sentence of sentences(text)) {
474        if (sentence.words <= max) continue;
475        add(
476          rule,
477          sentence.start,
478          sentence.end,
479          `${sentence.words} words, over ${max}.` + (rule.message ? ` ${rule.message}` : "")
480        );
481      }
482      continue;
483    }
484    if (rule.kind === "sentence-spread") {
485      const floor = rule.minSentences ?? 20;
486      const min = rule.minSpread ?? 0.45;
487      const words = sentences(text).map((s) => s.words).filter((n) => n >= 3);
488      if (words.length < floor) continue;
489      const mean = words.reduce((a, b) => a + b, 0) / words.length;
490      if (mean <= 0) continue;
491      const sd = Math.sqrt(
492        words.reduce((a, b) => a + (b - mean) ** 2, 0) / words.length
493      );
494      const spread = sd / mean;
495      if (spread >= min) continue;
496      add(
497        rule,
498        0,
499        Math.min(text.length, firstLineEnd(text)),
500        `sentence spread ${spread.toFixed(2)}, under ${min}.` + (rule.message ? ` ${rule.message}` : "")
501      );
502      continue;
503    }
504    if (rule.kind === "unglossed-term") {
505      const seen =   new Set();
506      const known = new Set((rule.known ?? []).map((k) => k.toLowerCase()));
507      const emphasis = new Set((rule.emphasis ?? []).map((k) => k.toLowerCase()));
508      for (const term of jargonTerms(text)) {
509        const key = term.text.toLowerCase();
510        if (known.has(key)) continue;
511        if (emphasis.has(key) || isShoutedWord(term.text)) continue;
512        if (seen.has(key)) continue;
513        seen.add(key);
514        const allowed = allowedBy(ruleSet, rule.id, term.text);
515        if (allowed) {
516          const { line } = locate(starts, term.start);
517          silenced.push({ pattern: allowed.entry.pattern, ruleId: rule.id, line });
518          continue;
519        }
520        if (isGlossed(text, term.start, term.end)) continue;
521        add(rule, term.start, term.end, `"${term.text}" is not explained.` + (rule.message ? ` ${rule.message}` : ""));
522      }
523    }
524  }
525  return out;
526}
527
528var LIMIT = 256 * 1024;
529var BLOCKS =   new Set(["p", "div", "li", "ul", "ol", "h1", "h2", "h3", "h4", "h5", "h6", "tr", "td", "th", "br", "hr"]);
530var OMIT =   new Set(["pre", "code", "script", "style", "blockquote", "ac:plain-text-body", "ac:parameter"]);
531var VOID =   new Set(["br", "hr", "img", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr"]);
532function record(value) {
533  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
534}
535var ENTITIES = {
536  amp: "&",
537  lt: "<",
538  gt: ">",
539  quot: '"',
540  apos: "'",
541  nbsp: "\xA0",
542  mdash: "\u2014",
543  ndash: "\u2013",
544  hellip: "\u2026",
545  lsquo: "\u2018",
546  rsquo: "\u2019",
547  ldquo: "\u201C",
548  rdquo: "\u201D",
549  laquo: "\xAB",
550  raquo: "\xBB",
551  bull: "\u2022",
552  middot: "\xB7",
553  copy: "\xA9",
554  reg: "\xAE",
555  trade: "\u2122",
556  deg: "\xB0",
557  times: "\xD7",
558  divide: "\xF7",
559  plusmn: "\xB1",
560  euro: "\u20AC",
561  pound: "\xA3",
562  yen: "\xA5",
563  cent: "\xA2",
564  sect: "\xA7",
565  para: "\xB6",
566  shy: "\xAD",
567  ensp: "\u2002",
568  emsp: "\u2003",
569  thinsp: "\u2009",
570  zwnj: "\u200C",
571  zwj: "\u200D"
572};
573function decodeEntities(text) {
574  return text.replace(/&(?:#(\d{1,7})|#[xX]([0-9a-fA-F]{1,6})|([A-Za-z][A-Za-z0-9]{1,31}));/g, (written, decimal, hex, name) => {
575    if (name !== void 0) return ENTITIES[name] ?? written;
576    const code = decimal !== void 0 ? Number.parseInt(decimal, 10) : Number.parseInt(hex, 16);
577    if (code === 0 || code > 1114111 || code >= 55296 && code <= 57343) return written;
578    return String.fromCodePoint(code);
579  });
580}
581var MAX_TAG = 4096;
582var TAG = /^<(\/?)([A-Za-z][\w:.-]*)((?:\s+[^\s=/<>]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s<>]+))?)*)\s*(\/?)>$/;
583var CODE_MACRO = /\sac:name\s*=\s*(["']?)code\1(?=[\s/>]|$)/i;
584function htmlText(value) {
585  const input = value.slice(0, LIMIT);
586  const skipping = [];
587  let text = "";
588  let at = 0;
589  let close = -1;
590  while (at < input.length && text.length < LIMIT) {
591    if (input.startsWith("<!--", at)) {
592      const end2 = input.indexOf("-->", at + 4);
593      at = end2 === -1 ? input.length : end2 + 3;
594      continue;
595    }
596    if (input.startsWith("<!", at) || input.startsWith("<?", at)) {
597      const end2 = input.indexOf(">", at + 2);
598      at = end2 === -1 ? input.length : end2 + 1;
599      continue;
600    }
601    if (input[at] === "<") {
602      if (close !== -2 && close < at) close = input.indexOf(">", at);
603      if (close === -1) close = -2;
604      const tag = close >= 0 && close - at < MAX_TAG ? TAG.exec(input.slice(at, close + 1)) : null;
605      if (tag === null) {
606        if (skipping.length === 0) text += "<";
607        at += 1;
608        continue;
609      }
610      at = close + 1;
611      const closing = tag[1] === "/";
612      const name = tag[2].toLowerCase();
613      const selfClosing = tag[4] === "/" || VOID.has(name);
614      if (skipping.length) {
615        if (name === skipping.at(-1)) {
616          if (closing) skipping.pop();
617          else if (!selfClosing) skipping.push(name);
618        }
619        continue;
620      }
621      const omitted = OMIT.has(name) || name === "ac:structured-macro" && CODE_MACRO.test(tag[3] ?? "");
622      if (omitted && !closing) {
623        text += " ";
624        if (!selfClosing) skipping.push(name);
625        continue;
626      }
627      if (BLOCKS.has(name)) text += selfClosing ? "\n\n" : "\n";
628      continue;
629    }
630    const next = input.indexOf("<", at);
631    const end = next === -1 ? input.length : next;
632    if (skipping.length === 0) text += decodeEntities(input.slice(at, end));
633    at = end;
634  }
635  return text.slice(0, LIMIT).trim();
636}
637function issueText(value) {
638  if (typeof value === "string") return value.slice(0, LIMIT);
639  const seen =   new WeakSet();
640  let budget = LIMIT;
641  const visit = (value2, depth) => {
642    if (depth > 64 || budget-- <= 0) return "";
643    if (typeof value2 === "string") return value2.slice(0, LIMIT);
644    if (!value2 || typeof value2 !== "object" || seen.has(value2)) return "";
645    seen.add(value2);
646    const node = record(value2);
647    const type = node["type"];
648    if (type === "codeBlock" || type === "blockquote") return "\n";
649    if (type === "text") {
650      if (Array.isArray(node["marks"]) && node["marks"].some((mark) => record(mark)["type"] === "code")) return " ";
651      return typeof node["text"] === "string" ? node["text"].slice(0, LIMIT) : "";
652    }
653    if (type === "hardBreak") return "\n";
654    if (typeof node["value"] === "string") {
655      const format = node["representation"];
656      if (format === "storage" || format === "view" || format === "html") return htmlText(node["value"]);
657      if (format === "atlas_doc_format") {
658        try {
659          return visit(JSON.parse(node["value"].slice(0, LIMIT)), depth + 1);
660        } catch {
661          return "";
662        }
663      }
664      if (format === "markdown" || format === "plain") return node["value"].slice(0, LIMIT);
665    }
666    if (Array.isArray(node["content"])) {
667      const children = node["content"].map((child) => visit(child, depth + 1)).join("");
668      return (children + (type === "paragraph" || type === "heading" || type === "listItem" ? "\n" : "")).slice(0, LIMIT);
669    }
670    for (const key of ["storage", "atlas_doc_format", "body", "content"]) {
671      if (node[key] !== void 0) return visit(node[key], depth + 1);
672    }
673    return "";
674  };
675  return visit(value, 0).trim();
676}
677function contentText(value, format) {
678  if (typeof value === "string" && (format === "adf" || format === "atlas_doc_format")) return issueText({ value, representation: "atlas_doc_format" });
679  if (typeof value === "string" && (format === "storage" || format === "html" || format === void 0 && /<\/?[a-z][^<>]{0,4096}>/i.test(value))) return htmlText(value);
680  return issueText(value);
681}
682
683function pick(input, ...keys) {
684  for (const k of keys) {
685    const v = input[k];
686    if (typeof v === "string" && v !== "") return v;
687  }
688  return "";
689}
690function pickArray(input, ...keys) {
691  for (const k of keys) {
692    const v = input[k];
693    if (Array.isArray(v)) return v;
694  }
695  return [];
696}
697function asRecord(v) {
698  return v && typeof v === "object" && !Array.isArray(v) ? v : {};
699}
700var MAX_ARGS_BYTES = 256 * 1024;
701function issueFields(input) {
702  const fields = asRecord(input["fields"]);
703  const description = [issueText(input["description"]), issueText(fields["description"])].filter(Boolean).join("\n\n");
704  const body = [issueText(input["body"]), issueText(input["commentBody"]), contentText(input["content"], input["contentFormat"])].filter(Boolean).join("\n\n");
705  return {
706    title: [pick(input, "title"), pick(input, "summary"), pick(fields, "summary")].filter(Boolean).join("\n\n"),
707    description,
708    body,
709    patch: pickArray(input, "patch").map((p) => {
710      const e = asRecord(p);
711      return { newString: pick(e, "newString", "new_string"), text: pick(e, "text") };
712    })
713  };
714}
715function editFields(input) {
716  return {
717    newString: pick(input, "new_string", "newString", "new_str", "replacement"),
718    oldString: pick(input, "old_string", "oldString", "old_str", "search"),
719    replaceAll: input["replace_all"] === true || input["replaceAll"] === true
720  };
721}
722function parseApplyPatch(patch) {
723  return patch.trimStart().startsWith("*** Begin Patch") ? parseEnvelope(patch) : parseUnifiedDiff(patch);
724}
725function parseEnvelope(patch) {
726  const files = [];
727  let current;
728  let removed = "";
729  let added = "";
730  let ranges = [];
731  const finishHunk = () => {
732    if (current?.sourcePath && (removed || added)) {
733      (current.edits ??= []).push({ oldString: removed, newString: added, changedRanges: ranges });
734    }
735    removed = "";
736    added = "";
737    ranges = [];
738  };
739  for (const line of patch.split(/\r?\n/)) {
740    const header = /^\*\*\* (Add|Update) File: (.+)$/.exec(line);
741    if (header?.[2]) {
742      finishHunk();
743      current = { path: header[2].trim(), text: "" };
744      if (header[1] === "Update") current.sourcePath = current.path;
745      files.push(current);
746      continue;
747    }
748    if (line.startsWith("*** Move to:") && current) {
749      current.path = line.slice("*** Move to:".length).trim();
750      continue;
751    }
752    if (line.startsWith("***") || line.startsWith("@@")) {
753      finishHunk();
754      if (/^\*\*\* (?:End Patch|Delete File)/.test(line)) current = void 0;
755      continue;
756    }
757    if (!current) continue;
758    if (line.startsWith("+")) {
759      const value = line.slice(1);
760      current.text += (current.text ? "\n" : "") + value;
761      ranges.push({ start: added.length, end: added.length + value.length });
762      added += value + "\n";
763    } else if (line.startsWith("-")) removed += line.slice(1) + "\n";
764    else if (line.startsWith(" ")) {
765      removed += line.slice(1) + "\n";
766      added += line.slice(1) + "\n";
767    }
768  }
769  finishHunk();
770  return files;
771}
772function parseUnifiedDiff(patch) {
773  const files = [];
774  let current;
775  let sourcePath;
776  let removed = "";
777  let added = "";
778  let ranges = [];
779  const finishHunk = () => {
780    if (current?.sourcePath && (removed || added)) {
781      (current.edits ??= []).push({ oldString: removed, newString: added, changedRanges: ranges });
782    }
783    removed = "";
784    added = "";
785    ranges = [];
786  };
787  for (const line of patch.split(/\r?\n/)) {
788    if (line.startsWith("--- ")) {
789      finishHunk();
790      const raw = line.slice(4).trim().split("	")[0] ?? "";
791      sourcePath = raw === "/dev/null" ? void 0 : raw.replace(/^[ab]\//, "");
792      continue;
793    }
794    if (line.startsWith("+++ ")) {
795      finishHunk();
796      const raw = line.slice(4).trim().split("	")[0] ?? "";
797      if (raw === "/dev/null") {
798        current = void 0;
799        continue;
800      }
801      current = { path: raw.replace(/^[ab]\//, ""), text: "" };
802      if (sourcePath) current.sourcePath = sourcePath;
803      files.push(current);
804      continue;
805    }
806    if (line.startsWith("@@") || line.startsWith("diff ") || line.startsWith("index ")) {
807      finishHunk();
808      continue;
809    }
810    if (line.startsWith("\\ ") || !current) continue;
811    if (line.startsWith("+")) {
812      const value = line.slice(1);
813      current.text += (current.text ? "\n" : "") + value;
814      ranges.push({ start: added.length, end: added.length + value.length });
815      added += value + "\n";
816    } else if (line.startsWith("-")) removed += line.slice(1) + "\n";
817    else if (line.startsWith(" ")) {
818      removed += line.slice(1) + "\n";
819      added += line.slice(1) + "\n";
820    }
821  }
822  finishHunk();
823  return files;
824}
825
826function windowsPathPrefix(text) {
827  return /^(?:-[FC]|--(?:file|body-file|notes-file)=)?(?:[A-Za-z]:|\\\\)/.test(text);
828}
829var SEPARATORS =   new Set([";", "\n", "&"]);
830function parseCommands(input) {
831  const commands = [];
832  let current = { words: [], redirects: [], heredocs: [], unterminated: false };
833  let word = "";
834  let quoted = false;
835  let expands = false;
836  let pendingRedirect = null;
837  const pendingHeredocs = [];
838  const endWord = () => {
839    if (!word && !quoted) return;
840    const w = { text: word, expands };
841    if (pendingRedirect) {
842      current.redirects.push({ target: w, exotic: pendingRedirect.exotic });
843      pendingRedirect = null;
844    } else {
845      current.words.push(w);
846    }
847    word = "";
848    quoted = false;
849    expands = false;
850  };
851  const endCommand = () => {
852    endWord();
853    if (current.words.length || current.redirects.length || current.heredocs.length) {
854      commands.push(current);
855    }
856    current = { words: [], redirects: [], heredocs: [], unterminated: false };
857  };
858  let i = 0;
859  while (i < input.length) {
860    const c = input[i];
861    if (c === "\n" && pendingHeredocs.length) {
862      endWord();
863      i++;
864      for (const h of pendingHeredocs.splice(0)) {
865        const body = [];
866        let closed = false;
867        while (i < input.length) {
868          let nl = input.indexOf("\n", i);
869          if (nl === -1) nl = input.length;
870          const line = input.slice(i, nl);
871          i = nl + 1;
872          if ((h.raw ? line.replace(/^\t+/, "") : line.trim()) === h.tag) {
873            closed = true;
874            break;
875          }
876          body.push(line);
877        }
878        if (!closed) current.unterminated = true;
879        current.heredocs.push(body.join("\n"));
880      }
881      continue;
882    }
883    if (c === "\\") {
884      if (/^(?:-[FC]|--(?:file|body-file|notes-file)=)?$/.test(word) && input[i + 1] === "\\" && /[A-Za-z0-9]/.test(input[i + 2] ?? "")) {
885        word += "\\\\";
886        i += 2;
887        continue;
888      }
889      if (windowsPathPrefix(word)) {
890        word += c;
891        i++;
892        continue;
893      }
894      if (input[i + 1] === "\n") {
895        i += 2;
896        continue;
897      }
898      if (i + 1 < input.length) {
899        word += input[i + 1];
900        quoted = true;
901        i += 2;
902        continue;
903      }
904      i++;
905      continue;
906    }
907    if (c === "'") {
908      const close = input.indexOf("'", i + 1);
909      if (close === -1) {
910        current.unterminated = true;
911        break;
912      }
913      word += input.slice(i + 1, close);
914      quoted = true;
915      i = close + 1;
916      continue;
917    }
918    if (c === '"') {
919      let j = i + 1;
920      let out = "";
921      let closed = false;
922      while (j < input.length) {
923        if (input[j] === "\\" && j + 1 < input.length) {
924          if (!out && input[j + 1] === "\\" && /[A-Za-z0-9]/.test(input[j + 2] ?? "")) {
925            out = "\\\\";
926            j += 2;
927          } else if (windowsPathPrefix(out)) {
928            out += "\\";
929            j++;
930          } else if ('\\"$`'.includes(input[j + 1])) {
931            out += input[j + 1];
932            j += 2;
933          } else if (input[j + 1] === "\n") {
934            j += 2;
935          } else {
936            out += "\\";
937            j++;
938          }
939          continue;
940        }
941        if (input[j] === '"') {
942          closed = true;
943          break;
944        }
945        if (input[j] === "$" || input[j] === "`") expands = true;
946        out += input[j];
947        j++;
948      }
949      if (!closed) {
950        current.unterminated = true;
951        break;
952      }
953      word += out;
954      quoted = true;
955      i = j + 1;
956      continue;
957    }
958    if (c === "`") {
959      expands = true;
960      let j = i + 1;
961      while (j < input.length && input[j] !== "`") {
962        if (input[j] === "\\") j++;
963        j++;
964      }
965      if (j >= input.length) {
966        current.unterminated = true;
967        break;
968      }
969      word += input.slice(i, j + 1);
970      i = j + 1;
971      continue;
972    }
973    if (c === "$") {
974      expands = true;
975      word += c;
976      i++;
977      continue;
978    }
979    if (c === "<" && input[i + 1] === "<") {
980      if (input[i + 2] === "<") {
981        endWord();
982        i += 3;
983        continue;
984      }
985      endWord();
986      let j = i + 2;
987      const raw = input[j] === "-";
988      if (raw) j++;
989      while (input[j] === " " || input[j] === "	") j++;
990      let tag = "";
991      let q = "";
992      if (input[j] === "'" || input[j] === '"') {
993        q = input[j];
994        j++;
995      }
996      while (j < input.length && /[A-Za-z0-9_]/.test(input[j])) tag += input[j++];
997      if (q && input[j] === q) j++;
998      if (tag) pendingHeredocs.push({ tag, raw });
999      i = j;
1000      continue;
1001    }
1002    if (c === ">") {
1003      endWord();
1004      let j = i + 1;
1005      let exotic = false;
1006      if (input[j] === ">") j++;
1007      if (input[j] === "&" || input[j] === "(") {
1008        exotic = true;
1009        j++;
1010      }
1011      const prev = current.words[current.words.length - 1];
1012      if (prev && /^\d$/.test(prev.text) && !prev.expands) {
1013        current.words.pop();
1014        exotic = true;
1015      }
1016      pendingRedirect = { exotic };
1017      i = j;
1018      continue;
1019    }
1020    if (c === "<") {
1021      endWord();
1022      i++;
1023      while (i < input.length && /\s/.test(input[i])) i++;
1024      while (i < input.length && !/[\s;&|<>]/.test(input[i])) i++;
1025      continue;
1026    }
1027    if (c === "|") {
1028      endCommand();
1029      i += input[i + 1] === "|" ? 2 : 1;
1030      continue;
1031    }
1032    if (SEPARATORS.has(c)) {
1033      endCommand();
1034      i += input[i + 1] === c && c === "&" ? 2 : 1;
1035      continue;
1036    }
1037    if (c === " " || c === "	" || c === "\r") {
1038      endWord();
1039      i++;
1040      continue;
1041    }
1042    if (c === "(" || c === ")") {
1043      endCommand();
1044      i++;
1045      continue;
1046    }
1047    word += c;
1048    i++;
1049  }
1050  endCommand();
1051  return commands;
1052}
1053var ECHO_FLAGS =   new Set(["-e", "-n", "-E"]);
1054function printfContent(words) {
1055  let args = words;
1056  if (args[0]?.text === "--") args = args.slice(1);
1057  else if (args[0]?.text.startsWith("-")) return "";
1058  if (!args.length || args.some((word) => word.expands)) return "";
1059  const format = args[0].text;
1060  const tokens = [];
1061  let literal = "";
1062  let conversions = 0;
1063  const escapes = {
1064    n: "\n",
1065    t: "	",
1066    r: "\r",
1067    a: "\x07",
1068    b: "\b",
1069    f: "\f",
1070    v: "\v",
1071    "\\": "\\"
1072  };
1073  for (let i = 0; i < format.length; i++) {
1074    const char = format[i];
1075    if (char === "%") {
1076      const next = format[++i];
1077      if (next === "%") literal += "%";
1078      else if (next === "s") {
1079        tokens.push(literal, null);
1080        literal = "";
1081        conversions++;
1082      } else return "";
1083    } else if (char === "\\") {
1084      const escaped = escapes[format[++i] ?? ""];
1085      if (escaped === void 0) return "";
1086      literal += escaped;
1087    } else literal += char;
1088  }
1089  tokens.push(literal);
1090  let argument = 1;
1091  let size = 0;
1092  const result = [];
1093  do {
1094    for (const token of tokens) {
1095      const text = token === null ? args[argument++]?.text ?? "" : token;
1096      size += text.length;
1097      if (size > 256 * 1024) return "";
1098      result.push(text);
1099    }
1100  } while (conversions > 0 && argument < args.length);
1101  return result.join("");
1102}
1103function contentOf(cmd) {
1104  if (cmd.heredocs.length) return cmd.heredocs.join("\n");
1105  const name = cmd.words[0]?.text ?? "";
1106  if (name !== "printf" && name !== "echo") return "";
1107  if (name === "printf") return printfContent(cmd.words.slice(1));
1108  const args = cmd.words.slice(1).filter((w) => !ECHO_FLAGS.has(w.text));
1109  if (args.some((a) => a.expands)) return "";
1110  const texts = args.map((a) => a.text);
1111  return texts.join(" ");
1112}
1113function shellFileWrites(input, baseDir) {
1114  const out = [];
1115  let cwd = baseDir;
1116  for (const cmd of parseCommands(input)) {
1117    if (cmd.unterminated) continue;
1118    if (cmd.words[0]?.text === "cd" && cwd !== void 0) {
1119      const target = cmd.words[1];
1120      if (target && !target.expands && cmd.words.length === 2) cwd = resolveDirectory(cwd, target.text);
1121      continue;
1122    }
1123    const targetPath = (path) => cwd === void 0 ? path : resolveDirectory(cwd, path);
1124    const text = contentOf(cmd);
1125    if (!text.trim()) continue;
1126    const plain = cmd.redirects.filter((r) => !r.exotic && !r.target.expands && r.target.text);
1127    if (plain.length === 1) {
1128      out.push({ path: targetPath(plain[0].target.text), text });
1129      continue;
1130    }
1131    if (plain.length > 1) continue;
1132    if (cmd.redirects.length) continue;
1133    if ((cmd.words[0]?.text ?? "") !== "tee") continue;
1134    const targets = cmd.words.slice(1).filter((w) => !w.text.startsWith("-"));
1135    if (targets.length !== 1 || targets[0].expands) continue;
1136    out.push({ path: targetPath(targets[0].text), text });
1137  }
1138  return out;
1139}
1140function resolveDirectory(base, path) {
1141  const windows = /^[A-Za-z]:[\\/]|^\\\\/.test(base) || /^[A-Za-z]:[\\/]|^\\\\/.test(path);
1142  const slash = windows ? "\\" : "/";
1143  const absolute = /^[A-Za-z]:[\\/]|^[\\/]/.test(path);
1144  const joined = absolute ? path : base + slash + path;
1145  const network = windows && joined.startsWith("\\\\");
1146  const prefix = network ? slash + slash : windows ? (/^[A-Za-z]:/.exec(joined)?.[0] ?? "") + slash : joined.startsWith("/") ? "/" : "";
1147  const parts = [];
1148  for (const part of joined.replace(/^[A-Za-z]:/, "").split(/[\\/]+/)) {
1149    if (!part || part === ".") continue;
1150    if (part === "..") {
1151      if (parts.length > (network ? 2 : 0)) parts.pop();
1152    } else parts.push(part);
1153  }
1154  return prefix + parts.join(slash);
1155}
1156function gitCommand(cmd, cwd) {
1157  let i = 1;
1158  while (i < cmd.words.length) {
1159    const option = cmd.words[i].text;
1160    if (!option.startsWith("-")) return { subcommand: option, index: i, cwd };
1161    if (option === "-C" || option === "-c" || option === "--git-dir" || option === "--work-tree") {
1162      const value = cmd.words[++i];
1163      if (!value || value.expands) return { subcommand: "", index: i, cwd };
1164      if (option === "-C") cwd = resolveDirectory(cwd, value.text);
1165    } else if (option.startsWith("-C") && option.length > 2) cwd = resolveDirectory(cwd, option.slice(2));
1166    i++;
1167  }
1168  return { subcommand: "", index: i, cwd };
1169}
1170function publishingCommands(input, baseDir) {
1171  const out = [];
1172  let cwd = baseDir;
1173  for (const cmd of parseCommands(input)) {
1174    if (cmd.unterminated || cmd.words[0]?.expands) continue;
1175    const name = cmd.words[0]?.text;
1176    if (name === "cd") {
1177      const target = cmd.words[1];
1178      if (target && !target.expands && cmd.words.length === 2) cwd = resolveDirectory(cwd, target.text);
1179      continue;
1180    }
1181    if (name === "git") {
1182      const git = gitCommand(cmd, cwd);
1183      if (git.subcommand === "commit") out.push({ args: cmd.words.slice(git.index + 1), cwd: git.cwd, heredocs: cmd.heredocs });
1184    } else if (name === "gh") {
1185      const kind = cmd.words[1]?.text;
1186      const action = cmd.words[2]?.text;
1187      const actions = kind === "pr" ? ["create", "edit", "comment", "review"] : kind === "issue" ? ["create", "edit", "comment"] : kind === "release" ? ["create", "edit"] : [];
1188      if (action && actions.includes(action)) out.push({ args: cmd.words.slice(3), cwd, heredocs: cmd.heredocs });
1189    }
1190  }
1191  return out;
1192}
1193
1194var HOOK_BUDGET_MS = 500;
1195var POST_BUDGET_MS = 5e3;
1196var MARKDOWN = /\.(md|markdown|mdx)$/i;
1197var HEREDOC = /<<-?[ \t]*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1\r?\n([\s\S]*?)\r?\n[ \t]*\2\b/g;
1198function expandHome(p, io) {
1199  if (p === "~") return io.home ?? p;
1200  if (p.startsWith("~/")) return io.home === void 0 ? p : io.path.resolve(io.home, p.slice(2));
skills/plain-english/scripts/core/default-rules.mjs 245 lines
1// GENERATED by scripts/build-plugin.mjs from rules/default.yml, without comments. Do not edit.
2export default [
3  "version: 1\nmeta:\n  title: \"Writing Style: AI-Tell Patterns to Cut\"\n  intro: \"Applies to everything written in or by this project: chat replies, docs, commit messages, PR descriptions, and issue ",
4  "text. Not just the channels a hook can check.\"\nfamilies:\n  - id: empty-framing\n    severity: warn\n    minFindings: 3\n    minRules: 2\n    minSentences: 2\n    message: Several framing phrases de",
5  "lay the substance. Remove the frame and keep each point.\n  - id: promotional-language\n    severity: warn\n    minFindings: 3\n    minRules: 2\n    minSentences: 2\n    message: Several promotional c",
6  "laims appear together. Replace them with facts or measurements.\n  - id: unsupported-authority\n    severity: warn\n    minFindings: 3\n    minRules: 2\n    minSentences: 2\n    message: Several claim",
7  "s borrow authority without giving evidence. Name the source or qualify the claim.\n  - id: assistant-debris\n    severity: warn\n    minFindings: 3\n    minRules: 2\n    minSentences: 2\n    message: ",
8  "Several provider artifacts or unfinished fields remain in the text.\n  - id: mechanical-transition\n    severity: warn\n    minFindings: 3\n    minRules: 2\n    minSentences: 2\n    message: Several s",
9  "tock hooks give the text a repeated scripted rhythm. Start those passages with their point.\npunctuation:\n  - id: em-dash\n    severity: error\n    match: —\n    message: No em dashes. Use a comma, p",
10  "arentheses, or a full stop.\n    link: docs/limitations.md#the-em-dash-rule\n  - id: em-dash-density\n    severity: off\n    match: —\n    perThousandWords: 6\n    message: Em dash rate is above the c",
11  "onfigured threshold.\n    link: docs/limitations.md#the-em-dash-rule\n  - id: en-dash-as-punctuation\n    severity: warn\n    match: \\s–\\s\n    message: An en dash used as a sentence break is the sa",
12  "me tell as an em dash.\nrules:\n  - id: furthermore\n    severity: error\n    family: empty-framing\n    match: \\bfurthermore\\b\n    message: Start the sentence with its own point.\n  - id: moreover",
13  "\n    severity: error\n    family: empty-framing\n    match: \\bmoreover\\b\n    message: Start the sentence with its own point.\n  - id: in-conclusion\n    severity: error\n    family: empty-framing",
14  "\n    match: \\bin conclusion\\b\n    message: State the conclusion. Do not announce it.\n  - id: worth-noting\n    severity: error\n    family: empty-framing\n    match: \\bit( is|'?s) worth (noting|",
15  "mentioning)\\b|\\bit( is|'?s) important to (note|understand|remember|consider|mention|highlight|realise|realize|recognise|recognize|emphasise|emphasize|point out|keep in mind|bear in mind)\\b\n    mes",
16  "sage: If it is worth noting, note it.\n  - id: at-the-end-of-the-day\n    severity: error\n    family: empty-framing\n    match: \\bat the end of the day,\n    message: Cut the phrase and state the po",
17  "int.\n  - id: lets-dive-in\n    severity: error\n    family: empty-framing\n    match: \\blet'?s dive in\\b\n    message: Start with the content.\n  - id: dive-into\n    severity: warn\n    match: \\b",
18  "div(e|es|ing) into\\b\n    unless:\n      - \\bdiv(e|es|ing) into (the )?(pool|water|sea|ocean|wreck)\\b\n    message: Usually 'read', 'look at', or just the verb for what you are doing.\n  - id: here",
19  "s-the-thing\n    severity: warn\n    family: mechanical-transition\n    match: \\bhere(?:'|’)s the thing\\b\n    message: State the thing directly.\n    provenance:\n      kind: quality\n      confide",
20  "nce: high\n      scope:\n        - chat\n        - docs\n        - repository\n      reviewed: 2026-09-13\n      sources: []\n  - id: real-question-hook\n    severity: warn\n    family: mechanical-tra",
21  "nsition\n    match: \\bthe real question is\\b\n    message: Ask the question directly.\n    provenance:\n      kind: quality\n      confidence: high\n      scope:\n        - chat\n        - docs\n   ",
22  "     - repository\n      reviewed: 2026-09-13\n      sources: []\n  - id: what-that-means-hook\n    severity: warn\n    family: mechanical-transition\n    match: \\bhere(?:'|’)s what that means in pra",
23  "ctice\\b\n    message: Give the practical effect directly.\n    provenance:\n      kind: quality\n      confidence: high\n      scope:\n        - chat\n        - docs\n        - repository\n      revi",
24  "ewed: 2026-09-13\n      sources: []\n  - id: leverage\n    severity: error\n    match: \\bleverag(e|es|ed|ing)\\b\n    unless:\n      - \\b(financial|operating|debt|net|balance.sheet)\\s+leverage\\b\n",
25  "      - \\bleverage\\s+(ratio|point|effect)\\b\n      - \\bleveraged\\s+(buyout|loan|finance|etf)\\b\n    message: Use 'use'.\n  - id: utilize\n    severity: error\n    match: \\butiliz(e|es|ed|ing)\\",
26  "b|\\butilis(e|es|ed|ing)\\b\n    message: Use 'use'.\n  - id: delve\n    severity: error\n    match: \\bdelv(e|es|ed|ing)\\b\n    message: Use 'look at', 'read', or 'go through'.\n  - id: showcase\n  ",
27  "  severity: error\n    match: \\bshowcas(e|es|ed|ing)\\b\n    unless:\n      - \\b(glass|display|trophy|museum)\\s+showcase\\b\n    message: Use 'show'.\n  - id: boasts\n    severity: error\n    match",
28  ": \\bboasts\\b\n    unless:\n      - \\bboasts?\\s+about\\b\n    message: \"State the number without the verb: 'uptime is 99.9%'.\"\n  - id: underscores-verb\n    severity: warn\n    match: \\bundersc",
29  "or(e|es|ed|ing)\\s+(the|that|this|these|those|a|an|how|why|just|again|its|our|their|his|her)\\b\n    unless:\n      - _\n    message: Use 'shows', 'proves', or drop the sentence.\n  - id: seamless\n  ",
30  "  severity: error\n    family: promotional-language\n    match: \\bseamless(ly)?\\b\n    unless:\n      - \\bseamless\\s+(pipe|tube|steel|garment|knit|weld)\\b\n    message: Say what actually happens,",
31  " or cut the word.\n  - id: cutting-edge\n    severity: error\n    family: promotional-language\n    match: \\bcutting[- ]edge\\b\n    message: Name the thing that is new.\n  - id: holistic\n    severi",
32  "ty: warn\n    family: promotional-language\n    match: \\bholistic(ally)?\\b\n    unless:\n      - \\bholistic\\s+(medicine|health|healing|therapy|wellness|practitioner|nutrition)\\b\n    message: Say",
33  " which parts you mean.\n  - id: synergy\n    severity: error\n    family: promotional-language\n    match: \\bsynerg(y|ies|istic|istically)\\b\n    message: Name the actual benefit.\n  - id: paradigm-",
34  "shift\n    severity: error\n    family: promotional-language\n    match: \\bparadigm shift\\b\n    message: Say what changed.\n  - id: game-changer\n    severity: error\n    family: promotional-langua",
35  "ge\n    match: \\bgame[- ]chang(er|ing)\\b\n    message: Say what it changes.\n  - id: unlock-the\n    severity: error\n    family: promotional-language\n    match: \\bunlock (the|your) (potential|pow",
36  "er|value|secret|secrets|full)\\b\n    message: Say what becomes possible.\n  - id: elevate-your\n    severity: error\n    family: promotional-language\n    match: \\belevate your\\b\n    message: Say ",
37  "what improves.\n  - id: in-todays-x\n    severity: error\n    match: \\bin today'?s (fast[- ]paced|digital|business|competitive|modern)\\b\n    message: Cut the opener and start with the point.\n  - i",
38  "d: as-an-ai\n    severity: error\n    match: \\bas an AI\\b|\\bas a large language model\\b\n    message: Cut it.\n  - id: assistant-citation-debris\n    severity: warn\n    family: assistant-debris\n",
39  "    match: \\bturn[0-9]+(?:search|fetch|view)[0-9]+\\b|\\b(?:oaicite|oai_citation|attributableIndex)\\b|\\[cite:\\s*[0-9]+\\]\n    message: Remove the provider's internal citation marker and add a rea",
40  "l source link if the claim needs one.\n    provenance:\n      kind: marker\n      confidence: high\n      scope:\n        - chat\n        - docs\n        - repository\n      reviewed: 2026-09-13\n    ",
41  "  sources: []\n  - id: assistant-service-residue\n    severity: warn\n    family: assistant-debris\n    match: \\bas of my (?:last )?(?:knowledge cutoff|training update)\\b|\\bin the provided search r",
42  "esults\\b\n    message: Remove the assistant's service note and state the supported fact or evidence gap.\n    provenance:\n      kind: marker\n      confidence: high\n      scope:\n        - chat\n  ",
43  "      - docs\n        - repository\n      reviewed: 2026-09-13\n      sources: []\n  - id: unresolved-placeholder\n    severity: warn\n    family: assistant-debris\n    match: \\[(?:Your Name|Company ",
44  "Name|Describe [^\\]\\n]{1,60}|Insert [^\\]\\n]{1,60})\\]|\\bYYYY-XX-XX\\b\n    message: Replace the unfinished field with its value or remove it.\n    provenance:\n      kind: marker\n      confidence",
45  ": high\n      scope:\n        - chat\n        - docs\n        - repository\n      reviewed: 2026-09-13\n      sources: []\n  - id: silently\n    severity: warn\n    match: \\bsilent(ly)?\\b\n    unles",
46  "s:\n      - \\bfails?\\s+silently\\b\n      - \\bfailed\\s+silently\\b\n      - \\bsilently\\s+(ignor|drop|discard|swallow|skip|truncat|overwrit|fail)\n      - \\bsilent\\s+(mode|install|failure|corru",
47  "ption|film|letter|partner)\\b\n    message: Say what happened and what it affected.\n  - id: quietly\n    severity: warn\n    match: \\bquietly\\b\n    message: Say what happened and what it affected.",
48  "\n  - id: mechanical\n    severity: warn\n    match: \\bmechanical(ly)?\\b\n    unless:\n      - \\bmechanical\\s+(keyboard|engineer|engineering|turk|advantage|ventilation|seal|watch|pencil|switch|fai",
49  "lure|load|part|component)\\b\n    message: Say what the process actually does.\n  - id: load-bearing\n    severity: error\n    match: \\bload[- ]bearing\\b\n    unless:\n      - \\bload[- ]bearing\\s+",
50  "(wall|walls|beam|column|member|structure|capacity|frame)\\b\n    message: Say what depends on it.\n  - id: the-fact-that\n    severity: warn\n    match: \\bthe fact that\\b\n    message: \"Cut it: 'de",
51  "spite the fact that' is 'though'.\"\n  - id: in-order-to\n    severity: warn\n    match: \\bin order to\\b\n    message: Use 'to'.\n  - id: in-terms-of\n    severity: warn\n    match: \\bin terms of\\",
52  "b\n    unless:\n      - \\b(express|expresses|expressed|defines?|defined|solves?|solved|writes?|written|rewritten|measures?|measured|states?|stated)\\s+in terms of\\b\n    message: Name the relation, ",
53  "or use 'in' or 'for'.\n  - id: able-to\n    severity: warn\n    match: \\b(is|are|was|were|be|been|being)\\s+able to\\b|\\bha(s|ve|d)\\s+the ability to\\b\n    message: Use 'can'.\n  - id: a-number-of",
54  "\n    severity: warn\n    match: \\ba (number|variety) of\\b\n    message: Say how many, or cut the phrase.\n  - id: in-a-manner\n    severity: warn\n    match: \\bin (a|an) [a-z]+ (manner|fashion)\\b",
55  "\n    message: \"Use the adverb: 'in a hasty manner' is 'hastily'.\"\n  - id: as-to-whether\n    severity: warn\n    match: \\b(the question )?as to whether\\b\n    message: Use 'whether'.\n  - id: no",
56  "t-un\n    severity: warn\n    match: \\bnot un[a-z]+\\b\n    unless:\n      - \\bnot un(der|do|less|til|animous|animity|iform|ilateral|ion|ique|ison|it|ivers)[a-z]*\\b\n      - \\bnot (unset|un(ique|d",
57  "efined|initialised|initialized|installed|available|mounted|locked|committed|staged|tracked|read|used|packed|zipped|reachable|supported))\\b\n    message: \"Say what it is: 'not uncommon' is 'common'.",
58  "\"\n  - id: prior-to\n    severity: warn\n    match: \\bprior to\\b\n    message: Use 'before'.\n  - id: with-respect-to\n    severity: warn\n    match: \\bwith (respect|regard|regards) to\\b\n    mes",
59  "sage: Use 'about', or name the relation.\n  - id: puffery-nouns\n    severity: error\n    match: \\b(tapestry|testament|indelible mark)\\b\n    unless:\n      - \\b(old|new)\\s+testament\\b\n      - ",
60  "\\blast will and testament\\b\n    message: Say what happened. A result is not a testament to anything.\n  - id: pivotal\n    severity: error\n    match: \\bpivotal\\b\n    message: Say what it change",
61  "d.\n  - id: promotional-adjectives\n    severity: error\n    family: promotional-language\n    match: \\b(vibrant|breathtaking|groundbreaking|stunning|nestled|must-visit)\\b\n    message: Describe it ",
62  "neutrally, or give the number.\n  - id: evolving-landscape\n    severity: error\n    match: \\b(ever-)?(evolving|changing|shifting)\\s+(landscape|world|field|environment)\\b\n    message: Name what ch",
63  "anged and when.\n  - id: abstract-landscape\n    severity: error\n    match: \\b(technology|technological|competitive|digital|business|security|threat|regulatory|marketing)\\s+landscape\\b\n    messag",
64  "e: Name the thing that changed, or the competitors.\n  - id: deeply-rooted\n    severity: error\n    match: \\bdeeply[- ]rooted\\b\n    message: Say where it comes from.\n  - id: inflated-significance",
65  "\n    severity: error\n    family: promotional-language\n    match: \\b(a stark reminder|unwavering commitment|transformative power|relentless pursuit|pav(e|es|ed|ing) the way for (the )?future|a sign",
66  "ificant step forward)\\b\n    message: State what changed or what the evidence shows.\n  - id: formulaic-importance\n    severity: warn\n    family: unsupported-authority\n    match: \\b(provid(e|es|e",
67  "d|ing)|offer(s|ed|ing)) (a )?valuable insights?\\b|\\b(significant role in shaping|play(s|ed|ing)? (a )?(crucial|significant) role)\\b|\\b(emphasi(s|z)(e|es|ed|ing)|highlight(s|ed|ing)?) (the )?(impor",
68  "tance|need|potential)\\b\n    message: Name the fact or consequence instead of announcing its importance.\n  - id: staged-progress\n    severity: warn\n    match: \\b(the journey begins|the path ahead",
69  "|la(y|id|ys|ying) the groundwork|mark(s|ed|ing) a turning point|a significant milestone|open(s|ed|ing) (up )?(a )?new avenues?)\\b\n    message: Name the next step or the change without turning it int",
70  "o a journey.\n  - id: academic-fog\n    severity: warn\n    match: \\b(a )?(nuanced|deeper|broad|comprehensive) understanding\\b|\\b(the )?complex interplay\\b|\\b(a )?delicate balance\\b|\\b(shed|she",
71  "ds|shedding) light on\\b|\\b(particularly noteworthy|far[- ]reaching implications?|profound implications?|a comprehensive (overview|framework)|an ongoing dialogue|stand(s|ing)? in stark contrast)\\b\n",
72  "    message: Replace the frame with the specific relationship, finding, or difference.\n  - id: abstract-metaphor-nouns\n    severity: warn\n    match: \\b(substrate|locus|vantage|nexus|bedrock|modali",
73  "ty|north star|flywheel|gold[- ]plating)\\b\n    unless:\n      - \\b(silicon|growth|culture|glass|ceramic|sapphire)\\s+substrate\\b\n      - \\bsubstrate\\s+(concentration|binding|specificity)\\b\n   ",
74  "   - \\bvantage\\s+point\\b\n      - \\blocus\\s+of\\s+control\\b\n      - \\b(imaging|treatment|sensory|input)\\s+modality\\b\n      - \\bmodality\\s+of\\s+(imaging|treatment)\\b\n    message: \"Pick",
75  " the concrete word: a base, a place, a link, a goal.\"\n  - id: borrowed-metaphors\n    severity: warn\n    match: \\b(footgun|blast radius|belt and suspenders|cargo[- ]cult|smoking gun|the quiet part",
76  " out loud)\\b\n    unless:\n      - \\bblast radius\\s+of\\s+(the\\s+)?(bomb|charge|explosion|blast|device)\\b\n    message: \"Say the plain thing: an easy mistake, how much it affects, a redundant se",
77  "cond check.\"\n  - id: figurative-placement\n    severity: warn\n    match: \\b(the|a)\\s+layer\\s+(underneath|beneath|below|under|behind)\\b|\\bhold(s|ing)?\\s+up\\s+(well|under|to\\s+scrutiny|agains",
78  "t)\\b|\\bsit(s|ting)?\\s+at\\s+the\\s+(intersection|core|centre|center|crux)\\s+of\\b|\\b(is|are)\\s+where\\s+[\\w-]+\\s+(go|goes|get|gets|break|breaks|fail|fails)\\b\n    message: Name the thing and ",
79  "say where it actually is.\n  - id: mic-drop\n    severity: warn\n    match: (?<=^|[.!?]\\s|\\n)(It|This|That)(?:'s| is| was)\\s+(key|crucial|critical|intentional|deliberate|elegant|subtle|telling|stri",
80  "king|by design|no accident)\\.|(?<=^|[.!?]\\s|\\n)(It|This|That)\\s+(matters|works|compounds|adds up|pays off)\\.\n    message: Fold the point into the sentence before it, or cut it.\n  - id: fancy-is",
81  "\n    severity: warn\n    match: \\b(serves|serve|stands|stand)\\s+as\\b\n    unless:\n      - \\b(serves|serve)\\s+as\\s+(a|an|the)\\s+(reverse\\s+)?(proxy|cache|fallback|gateway|relay|load[- ]balanc",
82  "er|mirror|backup)\\b\n      - \\bstands?\\s+as\\s+(a\\s+)?(candidate|nominee|witness)\\b\n    message: Just say 'is' or 'has'.\n  - id: vague-attribution\n    severity: warn\n    family: unsupported-a",
83  "uthority\n    match: \\b(experts|analysts|critics|researchers|observers|industry reports|some critics|some experts)\\s+(believe|say|says|agree|argue|argues|suggest|suggests|note|notes|claim|claims)\\b",
84  "\n    message: Name the source, or cut the claim.\nreadability:\n  - id: unglossed-term\n    severity: warn\n    kind: unglossed-term\n    message: Say what it does, then name it.\n    link: docs/writ",
85  "ing-style.md#readability\n    known:\n      - GitHub\n      - GitLab\n      - YouTube\n      - LinkedIn\n      - PayPal\n      - DeepMind\n      - OpenAI\n      - PostgreSQL\n      - MongoDB\n      - ",
86  "MySQL\n      - SQLite\n      - DynamoDB\n      - JetBrains\n      - WordPress\n      - SharePoint\n      - PowerPoint\n      - HubSpot\n      - MailChimp\n      - QuickBooks\n      - JavaScript\n     ",
87  " - TypeScript\n      - CoffeeScript\n      - PostScript\n      - JSON\n      - YAML\n      - TOML\n      - HTML\n      - CSS\n      - SQL\n      - XML\n      - CSV\n      - PDF\n      - PNG\n      - J",
88  "PEG\n      - SVG\n      - URL\n      - URI\n      - API\n      - CLI\n      - GUI\n      - IDE\n      - OS\n      - macOS\n      - iOS\n      - iPhone\n      - iPad\n      - NodeJS\n      - jQuery\n  ",
89  "    - GraphQL\n      - WebSocket\n      - WebAssembly\n      - OAuth\n      - HTTP\n      - HTTPS\n      - FTP\n      - SSH\n      - TLS\n      - SSL\n      - DNS\n      - IP\n      - CPU\n      - GPU",
90  "\n      - RAM\n      - USB\n      - PDF\n      - README\n      - CHANGELOG\n      - LICENSE\n      - CONTRIBUTING\n      - TODO\n      - MIT\n      - GPL\n      - BSD\n      - FAQ\n      - PDF\n      ",
91  "- CEO\n      - CTO\n      - VAT\n      - EU\n      - UK\n      - USA\n      - PhD\n    emphasis:\n      - ALL\n      - ALWAYS\n      - AMBER\n      - AND\n      - ANY\n      - BAD\n      - BEFORE\n   ",
92  "   - BEST\n      - BOTH\n      - BUT\n      - CLOSE\n      - DELETE\n      - DONE\n      - DOWN\n      - EACH\n      - EMPTY\n      - END\n      - ERROR\n      - EVER\n      - EVERY\n      - FAIL\n   ",
93  "   - \"FALSE\"\n      - FAST\n      - FIRST\n      - FIX\n      - FULL\n      - GOOD\n      - GREEN\n      - HALF\n      - HERE\n      - HIGH\n      - HOW\n      - ITERATE\n      - JUST\n      - KEEP",
94  "\n      - LAST\n      - LATER\n      - LEAST\n      - LESS\n      - LOW\n      - MAYBE\n      - MEDIUM\n      - MERGE\n      - MORE\n      - MOST\n      - MUST\n      - NEVER\n      - NEW\n      - NEX",
95  "T\n      - NONE\n      - NOT\n      - NOTE\n      - NOTHING\n      - NOW\n      - OFF\n      - OLD\n      - ONCE\n      - ONE\n      - ONLY\n      - OPEN\n      - PASS\n      - PLEASE\n      - RED\n  ",
96  "    - RETHINK\n      - REVIEW\n      - RIGHT\n      - SAFE\n      - SAME\n      - SHORT\n      - SKELETON\n      - SKIP\n      - SLOW\n      - SOME\n      - SOON\n      - STOP\n      - SURE\n      - T",
97  "EST\n      - THEN\n      - THIS\n      - TODAY\n      - \"TRUE\"\n      - TWICE\n      - UNDER\n      - UNTIL\n      - UPDATE\n      - USE\n      - VERY\n      - WAIT\n      - WARNING\n      - WHEN\n ",
98  "     - WHY\n      - WITH\n      - WITHOUT\n      - WRONG\n      - YES\n      - YET\n  - id: long-sentence\n    severity: warn\n    kind: long-sentence\n    maxWords: 35\n    message: Split this. One i",
99  "dea per sentence.\n    link: docs/writing-style.md#readability\n  - id: sentence-spread\n    severity: off\n    kind: sentence-spread\n    minSpread: 0.45\n    minSentences: 20\n    message: Let a sho",
100  "rt sentence land between the long ones.\n    link: docs/writing-style.md#readability\n  - id: unexplained-suppression\n    severity: warn\n    kind: unexplained-suppression\n    message: \"Say why aft",
101  "er a colon: `disable leverage: finance sense`.\"\n    link: docs/writing-style.md#suppressions\nstructures:\n  - id: binary-contrast\n    name: Binary contrast cliche\n    description: Stating what so",
102  "mething is not, then what it is, as a rhetorical flourish.\n    bad: This isn't just a bug. It's a trust problem.\n    good: This bug will make people distrust the report.\n  - id: short-clause-contra",
103  "st\n    name: Short-clause contrast (X rather than Y)\n    description: 'The same move compressed into one clause. Needs judgment: \"rather than\" is often perfectly ordinary (\"fix the cause rather t",
104  "han the symptom\"). Flag it only when it is a paired noun-vs-noun contrast added for effect.'\n    bad: Treat that as a floor rather than a rate.\n    good: \"Treat that as a floor: real usage is prob",
105  "ably higher, since the sample skews toward older records.\"\n  - id: throat-clearing\n    name: Throat-clearing opener\n    description: Stalling before the actual point.\n    bad: \"Here's the thing:",
106  " the deal stalled because...\"\n    good: The deal stalled because...\n  - id: faux-insight\n    name: Faux-insight setup\n    description: Manufactured suspense before a plain fact.\n    bad: What no",
107  "body tells you about churn is...\n    good: State the fact directly.\n  - id: abstract-physical-metaphor\n    name: Physical metaphor on an abstract thing\n    description: \"Giving a process, a claim",
108  " or a system a property only a physical object has: a position, a location, a weight it carries. The metaphor sounds like an explanation and names nothing. `figurative-placement` reaches a few fixed s",
109  "hapes of this; the rest needs a reader.\"\n    bad: Enrichment is where stacks go bad, and attribution only holds up if the layer underneath the reporting is clean.\n    good: Their enrichment step dr",
110  "ops 12% of records before scoring, so the attribution report counts fewer leads than the CRM does.\n  - id: weasel-attribution\n    name: Weasel attribution\n    description: A claim backed by an unna",
111  "med authority.\n    bad: Experts agree this is best practice.\n    good: Name the actual source, or drop the claim.\n  - id: fake-strong-verbs\n    name: Fake-strong verbs on weak claims\n    descript",
112  "ion: Inflating what something plainly does.\n    bad: This property serves as a centralized hub for deal stage.\n    good: This property stores the deal stage.\n  - id: meta-commentary\n    name: Meta",
113  "-commentary about the writing itself\n    description: Narrating that you are being clear or honest instead of just being clear or honest.\n    bad: To be transparent, I want to flag that...\n    good",
114  ": State the flag.\n  - id: synonym-cycling\n    name: Synonym cycling\n    description: Restating the same point across consecutive sentences in near-identical words to sound thorough.\n    bad: This ",
115  "is a major issue. It's a significant problem. This really matters.\n    good: Say it once.\n  - id: hedging-stacks\n    name: Hedging stacks\n    description: Piling up qualifiers instead of picking o",
116  "ne.\n    bad: It's possible that this might potentially cause...\n    good: This could cause...\n  - id: colon-reveal\n    name: Colon reveal\n    description: A noun phrase, a colon, then a lowercase",
117  " dramatic reveal that restates the phrase as a surprise. Use colons for lists, labels, and quotes, not fake drama. Rewrite as a plain sentence.\n    bad: \"The best part: it learns from every interact",
118  "ion.\"\n    good: It learns from every interaction, which is what makes it work.\n  - id: negative-listing\n    name: Negative listing\n    description: Defining something by what it is not, stacking ",
119  "negations before the actual claim.\n    bad: Not a tool. Not a platform. A partner.\n    good: A partner.\n  - id: dramatic-fragmentation\n    name: Dramatic fragmentation\n    description: Breaking a",
120  " single point into a staccato of sentence fragments for emphasis instead of clarity.\n    bad: That's it. That's the whole thing.\n    good: That is the entire mechanism.\n  - id: robotic-rhythm\n    ",
121  "name: Robotic rhythm\n    description: \"Repeated sentence shapes or identical paragraph structures across a piece, so every sentence lands the same way. Vary the shape only when it helps the point. N",
122  "eeds judgment: a list of short sentences is fine when each one carries a distinct fact.\"\n    bad: The system runs. The system checks. The system reports. The system logs. The system alerts.\n    goo",
123  "d: The system runs, checks, reports, logs, and alerts.\n  - id: rhetorical-setup\n    name: Rhetorical setup\n    description: A self-answered question or fake suspense that delays the point.\n    bad",
124  ": What if I told you the answer was right in front of you all along?\n    good: The answer was right in front of you all along.\n  - id: summary-recap\n    name: Summary-recap ending\n    description:",
125  " A final paragraph that restates the piece the reader just finished. End on the last concrete point or next action instead.\n    bad: In conclusion, we've seen that the system works and delivers value",
126  ".\n    good: The system cut deploy time from 40 minutes to 4.\n  - id: formatting-slop\n    name: Formatting as emphasis\n    description: \"Emoji in headings, bold sprinkled mid-sentence for emphasis",
127  ", bullet lists where two sentences of prose would read better, and headers over two-sentence sections. Format should follow the content, not decorate it. Needs judgment: a bullet list is correct when ",
128  "each item is a distinct fact or step.\"\n    bad: \"## Key Insight: **It's That Simple**\"\n    good: The key insight is simple.\nchat:\n  scope: Applies to what appears in the chat window. Not to cod",
129  "e, comments, or the docs, plans and memory files you write, which stay as precise as they need to be.\n  level: standard\n  levels:\n    - id: brief\n      name: Plain English (brief)\n      descripti",
130  "on: Lead with the answer. Explain a term before naming it.\n      form: bullets\n    - id: standard\n      name: Plain English\n      description: Plain language, named decisions, and when to expand i",
131  "nstead.\n      form: bullets\n    - id: full\n      name: Plain English (full)\n      description: Typed problem cards, running state, and time estimates.\n  shape:\n    name: The shape of a reply\n  ",
132  "  description: Three parts, and the third only when there is a choice. A reply that needs nothing from the reader ends at the second.\n    template: |\n      <the result, the problem, or the thing to ",
133  "do>\n\n      <the detail that supports it, and the line any claim rests on>\n\n      <what you need decided, and what each option costs>\n    levels:\n      - standard\n      - full\n  examples:\n    ",
134  "- id: a-result\n      name: A result, and nothing outstanding\n      ask: Why is my build slow?\n      bad: |\n        Great question. Let me start by looking at how your build is\n        configured.",
135  " There are a few pieces here: the CI cache, the dependency\n        install, and the compile step. Looking at the first of these, caching\n        is often where slowness comes from in projects like t",
136  "his one.\n      good: |\n        `node-sass` rebuilds from source on every CI run, because the\n        dependency cache misses. Replacing it with `sass` removes the native\n        build step.\n\n   ",
137  "     Want me to make the swap and run the stylesheet tests?\n      note: The first reply announces what it is about to do and arrives at no answer. The second names the cause in its first clause and e",
138  "nds with one thing to decide.\n      levels:\n        - standard\n        - full\n    - id: a-choice\n      name: A reply that needs a decision\n      ask: Should we cache the API responses?\n      ba",
139  "d: |\n        There are pros and cons to consider here. Caching would improve\n        performance, though it introduces staleness. It depends on your\n        requirements and your tolerance for out-",
140  "of-date data. Both approaches\n        are valid and it is worth thinking about which fits your case.\n      good: |\n        Yes, with a 60-second window. Your pricing endpoint is read 40 times\n    ",
141  "    for every write, so almost every read is currently redundant.\n\n        The cost is that a price change takes up to a minute to appear. If\n        that is too long, cache only the catalogue and ",
142  "leave pricing live.\n\n        Which of the two?\n      note: The first reply is even-handed and decides nothing, which leaves the work with the reader. The second recommends, prices the recommendatio",
143  "n, and asks one question.\n      levels:\n        - standard\n        - full\n    - id: length-that-was-asked-for\n      name: Length the reader asked for\n      ask: Walk me through how the gate deci",
144  "des to hold a turn.\n      good: |\n        Three checks run in order, and any one of them can hold the turn.\n\n        First the deterministic pass reads the reply for banned phrases. It is\n       ",
145  " instant and it never asks anything.\n\n        Then the counts run: length, how many names the reply carries, and its\n        average sentence. A count that fires does not block on its own.\n\n     ",
146  "   Last, a model reads the reply and the question that prompted it, and\n        decides whether the length was earned. Only then does the turn stop.\n      note: No ceiling applies here. The reader a",
147  "sked to be walked through it, which is the first of the overrides below, so the length is the answer rather than padding around it.\n      levels:\n        - full\n  guidance:\n    - id: lead-with-the",
148  "-outcome\n      name: Open with what this is\n      short: First line names the subject and says whether it is a result, a problem, or a question. No preamble.\n      description: The first line names",
149  " the subject and says whether this is a result, a problem, or a question. When there is something to do, it is the first line instead. No preamble, no restating the request.\n      bad: Let me look at",
150  " how your auth flow works. There are a few pieces here.\n      good: Run `npm install jsonwebtoken`, then edit `src/auth.ts:42`.\n      levels:\n        - brief\n        - standard\n        - full\n  ",
151  "  - id: explain-before-naming\n      name: Explain a thing before naming it\n      short: Plain description first, then the term, so the name lands on something already understood.\n      description:",
152  " Give the plain description first, then the technical term, so the name lands on something the reader already understands. An acronym introduced before its explanation makes the reader carry an unknow",
153  "n through the rest of the sentence.\n      bad: Provenance is attached at publish time.\n      good: GitHub signs a receipt proving where the code came from. That receipt is called provenance.\n      ",
154  "levels:\n        - brief\n        - standard\n        - full\n    - id: say-what-needs-a-decision\n      name: Say what needs a decision\n      short: When the reader must choose, end with the decisio",
155  "n and each option's cost. Otherwise stop without adding a status line.\n      description: When a reply contains a choice, end with what the reader has to decide and what each option costs. When nothi",
156  "ng is needed from them, end the reply. Do not add a sentence that merely announces that no decision or action remains.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: de",
157  "pth-is-welcome\n      name: Depth is welcome, unexplained depth is not\n      short: Keep the detail, explain the terms. Split a sentence past {{maxWords}} words.\n      description: Technical detail ",
158  "is the point of the conversation. Keep it. The failure mode is a term nobody defined, not a subject that is hard. Long sentences are fine when they carry one idea. Past about {{maxWords}} words they u",
159  "sually carry three, so split them.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: names-not-internals\n      name: Names, not internals\n      short: Name projects, fil",
160  "es and features. Leave signatures, traces and config keys out unless asked.\n      description: Refer to projects, files and features by name. Keep function signatures, stack traces, config keys and l",
161  "ine-by-line walkthroughs out of the reply unless the reader asks for them or they are the subject.\n      levels:\n        - standard\n        - full\n    - id: analogy-over-spec\n      name: Prefer a",
162  "n analogy to a specification\n      short: Say what happened in ordinary words, then name it.\n      description: One good comparison usually beats a paragraph of accurate detail. Say what happened in",
163  " ordinary words first, then name it.\n      bad: The fetch call returned 404.\n      good: The app asked for a page that is not there. That is a 404.\n      levels:\n        - standard\n        - full",
164  "\n    - id: offer-the-detail\n      name: Offer the detail, do not dump it\n      short: Say in one line that the deeper layer exists. Let the reader pull on it.\n      description: When a technical l",
165  "ayer is worth having, say in one line that it exists and let the reader pull on it.\n      levels:\n        - standard\n        - full\n    - id: quote-the-decisive-line\n      name: Quote the line a ",
166  "claim rests on\n      short: Verbatim, then what it means in plain words. This outranks brevity.\n      description: \"When a claim depends on real output, quote the decisive line verbatim, then say i",
167  "n plain words what it means. This outranks brevity: a short reply that asserts a result nobody can check is worse than a long one.\"\n      levels:\n        - standard\n        - full\n    - id: keep-",
168  "claims-grounded\n      name: Keep every claim tied to evidence\n      short: Preserve facts and qualifications. Label assumptions, judgments, and gaps instead of filling them in.\n      description: K",
169  "eep factual claims and qualifications from the source. Do not add a plausible detail to make an answer sound complete. Say when a statement is an assumption, a judgment, or a gap in the available evid",
170  "ence.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: preserve-the-requested-edit\n      name: Match the requested editing strength\n      short: For a light edit, fix o",
171  "nly clear faults. Preserve the requested form and useful structure.\n      description: Treat a light edit as a request to fix unambiguous faults while keeping meaning, form, and useful structure. Rem",
172  "ove empty repetition only when the reader did not ask for a close edit.\n      levels:\n        - standard\n        - full\n    - id: answer-before-qualifying\n      name: Answer before qualifying\n  ",
173  "    short: Answer, result or recommendation first. Only the caveats that change what the reader does.\n      description: Lead with the answer, the result or the recommendation. Caveats go after it, a",
174  "nd only the ones that change what the reader does.\n      levels:\n        - standard\n        - full\n    - id: raise-it-only-if-it-matters\n      name: Raise an objection only when it changes someth",
175  "ing\n      short: Only when it changes correctness, safety, cost or the ask. Otherwise it is noise.\n      description: Say it when it affects correctness, safety, cost, or what the reader has asked f",
176  "or. A true point that changes nothing is noise, and a downside raised to look even-handed is worse than noise.\n      levels:\n        - standard\n        - full\n    - id: rank-and-cap-lists\n      n",
177  "ame: Rank a list, and keep it short\n      short: Five ranked beats ten unranked. Split into now and later.\n      description: Past about five items a list stops being read. Split it into now and lat",
178  "er, or must and nice to have. Five ranked beats ten unranked.\n      levels:\n        - standard\n        - full\n    - id: one-thing-at-a-time\n      name: Finish one thing before raising the next\n ",
179  "     short: Answer the first, then offer the second as its own question.\n      description: \"When a second issue turns up, finish the first and then offer the second as its own question. A question ",
180  "you can answer yourself is not a second issue: answer it and fold the result in.\"\n      bad: Here is the fix. Also your dependency is stale, and the README is out of date, and...\n      good: \"Here",
181  " is the fix. Separately: there is a stale dependency. Want that next?\"\n      levels:\n        - standard\n        - full\n    - id: restate-where-we-are\n      name: Restate where we are\n      shor",
182  "t: Say what is done, what is next, and what you need. The reader cannot hold step 3 of 5.\n      description: The reader cannot hold \"step 3 of 5\" between messages. Say what is done, what is next, a",
183  "nd what you need from them. If the session has a task list, let it do the restating rather than narrating the plan twice.\n      bad: Done. Ready for the next part?\n      good: \"Step 3 of 5 done: sc",
184  "hema updated. Next: backfill the column. Run it?\"\n      levels:\n        - standard\n        - full\n    - id: time-estimates\n      name: Estimate in concrete units\n      short: Give a number and ",
185  "the condition it depends on.\n      description: A vague estimate carries no information. Give a number and the condition it depends on.\n      bad: This will take some work.\n      good: About 15 min",
186  "utes if tests already cover this. An afternoon if not.\n      levels:\n        - full\n    - id: typed-problem-cards\n      name: One card per distinct issue\n      short: \"One card per issue: a type",
187  " label, a short heading, one or two sentences.\"\n      description: When a reply covers several separate problems, give each one a type label (defect, question, blocker, improvement), a short heading",
188  ", and one or two sentences. Keep them visually separate so they can be scanned rather than read.\n      levels:\n        - full\n    - id: withdraw-the-whole-claim\n      name: Withdraw the whole clai",
189  "m, not the sentence\n      short: Name the wrong claim, state the corrected one, say what depended on it.\n      description: When something you said turns out to be wrong, name the wrong claim, state",
190  " the corrected one, and say which of your earlier conclusions depended on it. Then continue from the corrected position rather than defending a narrower version of the old one.\n      levels:\n       ",
191  " - full\n  failOn: error\n  limits:\n    - id: reply-length\n      kind: reply-length\n      severity: error\n      maxWords: 225\n      message: Lead with the answer and cut the scaffolding, or say i",
192  "n one line that the detail exists.\n      link: docs/writing-style.md#chat\n    - id: reader-load\n      kind: reader-load\n      severity: error\n      maxTerms: 12\n      message: Name the thing, no",
193  "t its configuration. Say what it does before you name it.\n      link: docs/writing-style.md#chat\n    - id: reply-pace\n      kind: reply-pace\n      severity: warn\n      maxMeanWords: 13\n      min",
194  "Words: 80\n      message: Let a short sentence land between the long ones.\n      link: docs/writing-style.md#chat\n    - id: unreadable-ask\n      kind: unreadable-ask\n      severity: error\n      m",
195  "axWords: 15\n      maxClauses: 1\n      message: Ask for one thing, in one clause. Put the detail in the sentence before it.\n      link: docs/writing-style.md#chat\n  tells:\n    - id: affirmation-op",
196  "ener\n      severity: error\n      at: start\n      phrases:\n        - Great question\n        - Good question\n        - Excellent question\n        - Excellent point\n        - You're absolutely ri",
197  "ght\n        - That's an excellent point\n      message: Start with the answer.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: announced-structure\n      severity: erro",
198  "r\n      at: anywhere\n      phrases:\n        - I'll start by\n        - I'll begin by\n        - Let me start by\n        - Let me begin by\n        - To answer your question\n        - I'll first e",
199  "xplain\n      message: Do it instead of announcing it.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: closing-pleasantry\n      severity: error\n      at: anywhere\n   ",
200  "   phrases:\n        - Hope this helps\n        - Hope that helps\n        - Let me know if you need anything else\n        - Feel free to ask\n        - Happy to clarify\n      message: End when the ",
201  "answer is done.\n      levels:\n        - brief\n        - standard\n        - full\n    - id: concession-formula\n      severity: warn\n      at: anywhere\n      phrases:\n        - fair point\n     ",
202  "   - fair hit\n        - what survives\n        - the pattern you're naming\n        - worth your attention\n      message: Name the error, the correction, and what it changes.\n      levels:\n       ",
203  " - standard\n        - full\n    - id: error-theatre\n      severity: warn\n      at: anywhere\n      phrases:\n        - Uh oh\n        - Oh no\n        - There seems to be a problem\n        - Somet",
204  "hing went wrong\n      message: State the cause and the fix.\n      levels:\n        - standard\n        - full\n  avoid:\n    - text: Open with a summary of what was just asked.\n      levels:\n     ",
205  "   - brief\n        - standard\n        - full\n    - text: Claim something is done without having checked.\n      levels:\n        - brief\n        - standard\n        - full\n    - text: Bury the de",
206  "cision in the middle of a paragraph.\n      levels:\n        - brief\n        - standard\n        - full\n    - text: Pad a hedge. Keep one that carries real uncertainty and cut the rest.\n      level",
207  "s:\n        - standard\n        - full\n    - text: Report whether somebody else's earlier answer was right, unless that is the question.\n      levels:\n        - standard\n        - full\n  readable",
208  ":\n    maxUnexplained: 2\n    description: \"List every term the reply NAMES but never EXPLAINS. A term counts as explained only if the reply says, in ordinary words, what that thing is. Names of rule",
209  "s, tools, files, flags, commands and version numbers all count, including ones inside a table or a fenced block. Do not credit a term as explained because you happen to know what it means. Quoted comm",
210  "and output does not count: a number or a path inside quoted output is evidence, not a name the reader has to carry.\"\n  judge:\n    - id: unexplained-terms\n      description: 'A term arrives doing w",
211  "ork in the sentence and nothing in the reply says what it is. Not an acronym only: \"the JSON merge\", \"by-name behaviour\" and \"the retry path\" are the shape that stops a reader. Refuse when the r",
212  "eply cannot be acted on without knowing one, and quote it.'\n    - id: no-let-up\n      description: Every sentence carries a full load for the whole reply. Refuse when breaking two or three of them i",
213  "n half would cost nothing.\n    - id: answers-a-question-nobody-asked\n      description: The reader asked something small and the reply answered something large. Refuse when the first sentence does n",
214  "ot answer the question as it was put, and say what the one-sentence answer was.\n  expand:\n    - The reader asked you to explain, or to walk them through it.\n    - The action is hard to reverse. Con",
215  "firm before acting.\n    - The options are the answer. Give two to four, ranked, one line of cost each.\n    - A claim rests on real output. Quote the line, then say what it means.\n    - Three turns ",
216  "have ended in 'still broken'. Name the assumption that might be wrong.\n    - A rule would delete the answer. The answer wins and the shape stays.\ndocs:\n  scope: \"Applies to markdown written into a",
217  " repository: READMEs, guides, reference pages and architecture decision records. Not to chat, which has its own rules, and not to a commit message or an issue body, which are shorter than anything her",
218  "e would make sense of.\"\n  skill:\n    name: writing-a-document\n    description: \"How to shape a markdown document in this project: what the first paragraph carries, what a heading promises, and wh",
219  "en to show a command instead of describing one. Use when writing or editing any .md file.\"\n  guidance:\n    - id: purpose-in-the-first-paragraph\n      name: Say what the document is for before you ",
220  "explain anything\n      short: \"First paragraph: who this is for and what they will be able to do.\"\n      description: A reader arrives at a document to find out whether it is the one they need. Th",
221  "at decision is made in the first paragraph or by closing the tab, so it is the one place background cannot go. Name the reader and what they will be able to do, then start explaining.\n      flag: The",
222  " document opens with background or history instead of saying what it is for and who it is for.\n      bad: Configuration in this project has evolved over several releases. Originally settings lived in",
223  " a single file.\n      good: This page is for anyone adding a rule to the ruleset. By the end you will have one rule shipping with a test.\n    - id: a-heading-is-a-promise\n      name: A heading is a",
224  " promise about what follows\n      short: Name the question the section answers, and answer it there.\n      description: Somebody scanning a document reads only the headings, so each one has to say w",
225  "hat its section settles. A heading that names a topic rather than a question leaves the reader to open every section to find out which one they wanted.\n      flag: A heading names a topic rather than",
226  " the question its section answers, or promises something the section does not deliver.\n      bad: \"## Configuration\"\n      good: \"## Where settings are read from, and which file wins\"\n    - id:",
227  " show-the-command\n      name: Show the command, do not describe it\n      short: A command, a path or real output beats a sentence about one.\n      description: A reader can copy a command. They can",
228  "not copy a description of one, and they will get it wrong reconstructing it. The same holds for a file path, a config snippet and the output somebody should expect to see.\n      flag: The document de",
229  "scribes a command, path or config in prose where showing it would be shorter and unambiguous.\n      bad: Install the package globally and then run the lint subcommand against your documentation direc",
230  "tory.\n      good: \"`npx plain-english lint docs/`\"\n    - id: name-the-reader\n      name: Write for one reader, not for everybody\n      short: Pick the reader. Assumed knowledge follows from that",
231  " choice.\n      description: What counts as too much detail is a fact about who is reading. A page that serves a first-time user and a maintainer at once explains what one of them already knows and sk",
232  "ips what the other needs. Pick one, and link to the page that serves the other.\n      flag: The document serves two audiences at once, explaining basics one reader already has while skipping detail t",
233  "he other needs.\n    - id: no-heading-without-content\n      name: No heading with nothing under it\n      short: Cut an empty section or a stub. A promise nobody kept costs trust.\n      description:",
234  " A heading followed by one sentence saying the section is coming later reads as an outline somebody stopped filling in, and it teaches the reader that the other headings may be empty too. Cut it, or w",
235  "rite it.\n      flag: A heading is followed by a placeholder, a stub, or a note that the section is not written yet.\n    - id: say-what-it-costs\n      name: When you recommend something, say what it",
236  " costs\n      short: Every recommendation carries its price and when to choose otherwise.\n      description: A recommendation with no cost attached reads as marketing, and a reader who later meets th",
237  "e cost stops trusting the page that hid it. Name the tradeoff and the case where the other choice is right.\n      flag: The document recommends an approach without naming its cost or the case where a",
238  " different choice is better.\n      bad: Use the blocking mode. It catches problems early.\n      good: Use the blocking mode when the repository is yours. It fails a build on a finding, so on a share",
239  "d repository start advisory.\n    - id: keep-claims-grounded\n      name: Keep claims tied to the supplied evidence\n      short: Preserve facts and qualifications. Label assumptions, judgments, and m",
240  "issing evidence.\n      description: Do not fill a missing fact with a plausible detail. Keep qualifications that affect the conclusion, and label an assumption or judgment where the evidence does not",
241  " settle the point.\n      flag: The document adds an unsupported factual claim, presents an assumption as fact, or removes a material qualification.\n    - id: preserve-the-requested-form\n      name:",
242  " Preserve the requested form when editing\n      short: A light edit keeps meaning, genre, and useful structure.\n      description: When the request asks for a light or careful edit, change only clea",
243  "r faults. Keep the document's meaning, genre, and useful structure.\n      flag: The edit changes the document's genre, scope, or useful structure without the request asking for that change.\n"
244].join("");
245
hooks/wire.ts 257 lines
1/**
2 * The wire between the mod and the bundled CLI.
3 *
4 * The CLI's `hook <channel> --agent claude-code` reads one settings-hook
5 * payload on stdin and prints Claude Code's own hook JSON: nothing when the
6 * write may go ahead, `hookSpecificOutput.permissionDecision` for a tool
7 * call, a flat `{ decision: "block", reason }` for a stop event. This file
8 * builds the payload and reads the answer back, so `register.ts` holds the
9 * hooks alone. Every reader here fails towards allowing: a linter is never
10 * the reason a write cannot happen.
11 */
12
13/** What a pre-tool answer comes to once read. */
14export type ToolVerdict =
15  | { kind: 'allow' }
16  | { kind: 'ask'; reason: string }
17  | { kind: 'deny'; reason: string }
18
19/** What a stop answer comes to once read. */
20export type ChatVerdict =
21  | { kind: 'pass'; notice?: string }
22  | { kind: 'block'; reason: string; notice?: string }
23
24/** Tokenize user paths without evaluating shell expressions or expanding variables. */
25export function readPaths(input: string): string[] {
26  const paths: string[] = []
27  let word = ''
28  let quote = ''
29  let active = false
30  for (let i = 0; i < input.length; i++) {
31    const char = input[i]!
32    if (char === '\\' && quote !== "'") {
33      if (++i >= input.length) throw new Error('A path ends with an unfinished escape.')
34      word += input[i]
35      active = true
36    } else if (quote !== '') {
37      if (char === quote) quote = ''
38      else word += char
39    } else if (char === '"' || char === "'") {
40      quote = char
41      active = true
42    } else if (/\s/.test(char)) {
43      if (active) paths.push(word)
44      word = ''
45      active = false
46    } else {
47      word += char
48      active = true
49    }
50  }
51  if (quote !== '') throw new Error('A quoted path is missing its closing quote.')
52  if (active) paths.push(word)
53  if (paths.some(path => path === '')) throw new Error('A path cannot be empty.')
54  return paths.length === 0 ? ['.'] : paths
55}
56
57/** The three keys `tool.call` carries beside the tool's own arguments. */
58const RESERVED = new Set(['tool', 'tool_use_id', 'agentId'])
59
60/**
61 * A PreToolUse payload as a settings hook would read it on stdin, built from
62 * a `tool.call` event: the tool's arguments are every field but the reserved.
63 */
64export function toolPayload(
65  e: Readonly<Record<string, unknown>>,
66  session: { id: string; cwd: string },
67): Record<string, unknown> {
68  const input: Record<string, unknown> = {}
69  for (const [key, value] of Object.entries(e)) {
70    if (!RESERVED.has(key)) input[key] = value
71  }
72  return {
73    hook_event_name: 'PreToolUse',
74    session_id: session.id,
75    cwd: session.cwd,
76    tool_name: String(e['tool']),
77    tool_use_id: e['tool_use_id'],
78    tool_input: input,
79  }
80}
81
82function parse(stdout: string): Record<string, unknown> | undefined {
83  const text = stdout.trim()
84  if (text === '') return undefined
85  try {
86    const value: unknown = JSON.parse(text)
87    return value !== null && typeof value === 'object'
88      ? (value as Record<string, unknown>)
89      : undefined
90  } catch {
91    return undefined
92  }
93}
94
95function asString(value: unknown): string | undefined {
96  return typeof value === 'string' && value.length > 0 ? value : undefined
97}
98
99/** Reads a pre-tool answer. Anything unreadable allows. */
100export function readToolVerdict(stdout: string): ToolVerdict {
101  const out = parse(stdout)
102  const specific = out?.['hookSpecificOutput']
103  if (specific === null || typeof specific !== 'object') return { kind: 'allow' }
104  const record = specific as Record<string, unknown>
105  const decision = asString(record['permissionDecision'])
106  const reason =
107    asString(record['permissionDecisionReason']) ?? 'plain-english refused this write.'
108  if (decision === 'deny') return { kind: 'deny', reason }
109  if (decision === 'ask') return { kind: 'ask', reason }
110  return { kind: 'allow' }
111}
112
113/** Reads a stop answer. Anything unreadable passes. */
114export function readChatVerdict(stdout: string): ChatVerdict {
115  const out = parse(stdout)
116  if (out === undefined) return { kind: 'pass' }
117  const notice = asString(out['systemMessage'])
118  if (out['decision'] === 'block') {
119    const reason = asString(out['reason']) ?? 'plain-english held this reply.'
120    return notice === undefined ? { kind: 'block', reason } : { kind: 'block', reason, notice }
121  }
122  return notice === undefined ? { kind: 'pass' } : { kind: 'pass', notice }
123}
124
125/** One quoted passage, as the CLI's reason lists them. */
126export interface Passage {
127  line: number
128  match: string
129  ruleId: string
130  hint?: string
131}
132
133/**
134 * A finding line as `formatReason` in the CLI prints it:
135 * `  line 3: "Furthermore" (furthermore) Start the sentence with its own point.`
136 * The CLI and this module ship in one bundle, so the shape cannot drift
137 * between them unseen; a line that does not match is simply not a passage.
138 */
139const PASSAGE = /^\s+line (\d+): ("(?:[^"\\]|\\.)*") \(([\w-]+)\)(?: (.*))?$/
140
141/** The passages quoted in a reason, in the order the CLI gave them. */
142export function readPassages(reason: string): Passage[] {
143  const passages: Passage[] = []
144  for (const line of reason.split('\n')) {
145    const m = PASSAGE.exec(line)
146    if (m === null) continue
147    let match = m[2] ?? '""'
148    try {
149      match = String(JSON.parse(match))
150    } catch {
151      // the quoted form is still readable
152    }
153    const passage: Passage = { line: Number(m[1]), match, ruleId: m[3] ?? '' }
154    if (m[4] !== undefined && m[4] !== '') passage.hint = m[4]
155    passages.push(passage)
156  }
157  return passages
158}
159
160/**
161 * Text fit for `$.ui.log`, which draws one transcript row: line breaks and
162 * other control characters become spaces. Claude Code 2.1.294 draws a line
163 * break inside a row as U+FFFD (issue #80).
164 */
165export function oneLine(text: string): string {
166  return text.replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/ {2,}/g, ' ').trim()
167}
168
169/**
170 * The transcript row for a reply check's notice. The engine hands a mod's
171 * block reason to the model and draws none of it, so this row is what the
172 * person sees of a held reply. It names up to three quoted passages, or the
173 * notice's first line when it quotes none, and points at the pane that holds
174 * the whole finding.
175 */
176export function noticeLine(notice: string, held: boolean): string {
177  const passages = readPassages(notice)
178  const shown = passages.slice(0, 3).map(passage => `${JSON.stringify(passage.match)} (${passage.ruleId})`)
179  const more = passages.length > shown.length ? ` and ${passages.length - shown.length} more` : ''
180  const what = shown.length > 0
181    ? `${shown.join(', ')}${more}.`
182    : notice.split('\n').find(line => line.trim() !== '') ?? notice
183  return oneLine(`${held ? 'held this reply for a rewrite' : 'advice on this reply'}: ${what} /plain-english review shows the full finding.`)
184}
185
186/** The dialog an advisory finding opens: its text, its chip and its two answers. */
187export interface Ask {
188  question: string
189  header: string
190  allow: string
191  refuse: string
192}
193
194/** The chip beside the question; the engine allows twelve characters. */
195const HEADER = 'Prose check'
196const REFUSE = 'Refuse so Claude rewrites'
197
198/** What was about to happen, and the thing it would have happened to. */
199function subjectOf(
200  channel: 'docs' | 'github' | 'issue',
201  e: Readonly<Record<string, unknown>>,
202  cwd: string,
203): { subject: string; verb: string; allow: string } {
204  if (channel === 'docs') {
205    let path = String(e['file_path'] ?? 'a file')
206    if (path.startsWith(`${cwd}/`)) path = path.slice(cwd.length + 1)
207    return { subject: path, verb: 'Save the file as it is?', allow: 'Save it as it is' }
208  }
209  if (channel === 'github') {
210    const command = String(e['command'] ?? '')
211    let subject = 'the commit message'
212    if (/\bgh\s+pr\b/i.test(command)) subject = 'the pull request text'
213    else if (/\bgh\s+issue\b/i.test(command)) subject = 'the issue text'
214    else if (/\bgh\s+release\b/i.test(command)) subject = 'the release notes'
215    return { subject, verb: 'Run the command as it is?', allow: 'Run it as it is' }
216  }
217  return { subject: 'the Linear issue', verb: 'Send it as it is?', allow: 'Send it as it is' }
218}
219
220/**
221 * The question a person sees when a finding is advisory.
222 *
223 * The CLI's reason is written for the model: how to rewrite, and the narrower
224 * ways to get past the check. Shown to a person it reads as instructions to
225 * somebody else, with the actual question tacked on at the end. This names the
226 * plugin, the file or command, one quoted passage with its rule, and asks a
227 * question the person can answer. The model's text stays in the deny reason.
228 */
229export function askFor(
230  channel: 'docs' | 'github' | 'issue',
231  e: Readonly<Record<string, unknown>>,
232  cwd: string,
233  reason: string,
234): Ask {
235  const { subject, verb, allow } = subjectOf(channel, e, cwd)
236  const passages = readPassages(reason)
237  const first = passages[0]
238  const lines: string[] = []
239
240  if (first === undefined) {
241    lines.push(`plain-english found writing in ${subject} that breaks its rules.`)
242  } else if (passages.length === 1) {
243    lines.push(`plain-english found one passage in ${subject} that breaks its rules:`)
244  } else {
245    lines.push(
246      `plain-english found ${passages.length} passages in ${subject} that break its rules. The first:`,
247    )
248  }
249  if (first !== undefined) {
250    const hint = first.hint === undefined ? '' : ` ${first.hint}`
251    lines.push('', `line ${first.line}: "${first.match}" (${first.ruleId})${hint}`)
252  }
253  lines.push('', `Refusing hands Claude the findings and a way to fix each. ${verb}`)
254
255  return { question: lines.join('\n'), header: HEADER, allow, refuse: REFUSE }
256}
257
skills/plain-english/scripts/core/chunk-JLXHTBYJ.mjs 5204 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2import {
3  Parser,
4  YAMLParseError,
5  YAMLWarning,
6  prettifyError,
7  resolveBlockScalar,
8  resolveEnd,
9  resolveFlowScalar
10} from "./chunk-ZVATLAGB.mjs";
11import {
12  blankLine,
13  classifyCharacter,
14  combineExtensions,
15  fromMarkdown,
16  normalizeIdentifier,
17  resolveAll,
18  splice
19} from "./chunk-IKH6G3OL.mjs";
20import {
21  affixSymbol,
22  digitStart,
23  lowerInitial,
24  newLine,
25  numerical,
26  punctuation,
27  surrogates,
28  terminalMarker,
29  whiteSpace,
30  word,
31  wordSymbolInner
32} from "./chunk-VC7IYITB.mjs";
33import {
34  gfmTable
35} from "./chunk-OJMZKB7F.mjs";
36import {
37  asciiAlpha,
38  asciiAlphanumeric,
39  asciiControl,
40  factorySpace,
41  markdownLineEnding,
42  markdownLineEndingOrSpace,
43  markdownSpace,
44  unicodePunctuation,
45  unicodeWhitespace
46} from "./chunk-UGEYTODJ.mjs";
47import {
48  Alias,
49  Directives,
50  Document,
51  Pair,
52  YAMLMap,
53  YAMLSeq,
54  warn
55} from "./chunk-NJUDQNQS.mjs";
56import {
57  SCALAR,
58  Scalar,
59  isCollection,
60  isNode,
61  isPair,
62  isScalar
63} from "./chunk-ZVNRIHJD.mjs";
64
65function resolveProps(tokens, { flow, indicator, next: next2, offset, onError, parentIndent, startOnNewline }) {
66  let spaceBefore = false;
67  let atNewline = startOnNewline;
68  let hasSpace = startOnNewline;
69  let comment = "";
70  let commentSep = "";
71  let hasNewline = false;
72  let reqSpace = false;
73  let tab = null;
74  let anchor = null;
75  let tag = null;
76  let newlineAfterProp = null;
77  let comma = null;
78  let found = null;
79  let start = null;
80  for (const token of tokens) {
81    if (reqSpace) {
82      if (token.type !== "space" && token.type !== "newline" && token.type !== "comma")
83        onError(token.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
84      reqSpace = false;
85    }
86    if (tab) {
87      if (atNewline && token.type !== "comment" && token.type !== "newline") {
88        onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
89      }
90      tab = null;
91    }
92    switch (token.type) {
93      case "space":
94        if (!flow && (indicator !== "doc-start" || next2?.type !== "flow-collection") && token.source.includes("	")) {
95          tab = token;
96        }
97        hasSpace = true;
98        break;
99      case "comment": {
100        if (!hasSpace)
101          onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
102        const cb = token.source.substring(1) || " ";
103        if (!comment)
104          comment = cb;
105        else
106          comment += commentSep + cb;
107        commentSep = "";
108        atNewline = false;
109        break;
110      }
111      case "newline":
112        if (atNewline) {
113          if (comment)
114            comment += token.source;
115          else if (!found || indicator !== "seq-item-ind")
116            spaceBefore = true;
117        } else
118          commentSep += token.source;
119        atNewline = true;
120        hasNewline = true;
121        if (anchor || tag)
122          newlineAfterProp = token;
123        hasSpace = true;
124        break;
125      case "anchor":
126        if (anchor)
127          onError(token, "MULTIPLE_ANCHORS", "A node can have at most one anchor");
128        if (token.source.endsWith(":"))
129          onError(token.offset + token.source.length - 1, "BAD_ALIAS", "Anchor ending in : is ambiguous", true);
130        anchor = token;
131        start ?? (start = token.offset);
132        atNewline = false;
133        hasSpace = false;
134        reqSpace = true;
135        break;
136      case "tag": {
137        if (tag)
138          onError(token, "MULTIPLE_TAGS", "A node can have at most one tag");
139        tag = token;
140        start ?? (start = token.offset);
141        atNewline = false;
142        hasSpace = false;
143        reqSpace = true;
144        break;
145      }
146      case indicator:
147        if (anchor || tag)
148          onError(token, "BAD_PROP_ORDER", "".concat("Anchors and tags must be after the ", token.source, " indicator"));
149        if (found)
150          onError(token, "unexpected-token", "".concat("Unexpected ", token.source, " in ", flow ?? "collection"));
151        found = token;
152        atNewline = indicator === "seq-item-ind" || indicator === "explicit-key-ind";
153        hasSpace = false;
154        break;
155      case "comma":
156        if (flow) {
157          if (comma)
158            onError(token, "unexpected-token", `Unexpected , in ${flow}`);
159          comma = token;
160          atNewline = false;
161          hasSpace = false;
162          break;
163        }
164      default:
165        onError(token, "unexpected-token", "".concat("Unexpected ", token.type, " token"));
166        atNewline = false;
167        hasSpace = false;
168    }
169  }
170  const last2 = tokens[tokens.length - 1];
171  const end = last2 ? last2.offset + last2.source.length : offset;
172  if (reqSpace && next2 && next2.type !== "space" && next2.type !== "newline" && next2.type !== "comma" && (next2.type !== "scalar" || next2.source !== "")) {
173    onError(next2.offset, "MISSING_CHAR", "Tags and anchors must be separated from the next token by white space");
174  }
175  if (tab && (atNewline && tab.indent <= parentIndent || next2?.type === "block-map" || next2?.type === "block-seq"))
176    onError(tab, "TAB_AS_INDENT", "Tabs are not allowed as indentation");
177  return {
178    comma,
179    found,
180    spaceBefore,
181    comment,
182    hasNewline,
183    anchor,
184    tag,
185    newlineAfterProp,
186    end,
187    start: start ?? end
188  };
189}
190
191function containsNewline(key) {
192  if (!key)
193    return null;
194  switch (key.type) {
195    case "alias":
196    case "scalar":
197    case "double-quoted-scalar":
198    case "single-quoted-scalar":
199      if (key.source.includes("\n"))
200        return true;
201      if (key.end) {
202        for (const st of key.end)
203          if (st.type === "newline")
204            return true;
205      }
206      return false;
207    case "flow-collection":
208      for (const it of key.items) {
209        for (const st of it.start)
210          if (st.type === "newline")
211            return true;
212        if (it.sep) {
213          for (const st of it.sep)
214            if (st.type === "newline")
215              return true;
216        }
217        if (containsNewline(it.key) || containsNewline(it.value))
218          return true;
219      }
220      return false;
221    default:
222      return true;
223  }
224}
225
226function flowIndentCheck(indent2, fc, onError) {
227  if (fc?.type === "flow-collection") {
228    const end = fc.end[0];
229    if (end.indent === indent2 && (end.source === "]" || end.source === "}") && containsNewline(fc)) {
230      const msg = "Flow end indicator should be more indented than parent";
231      onError(end, "BAD_INDENT", msg, true);
232    }
233  }
234}
235
236function mapIncludes(ctx, items, search) {
237  const { uniqueKeys } = ctx.options;
238  if (uniqueKeys === false)
239    return false;
240  const isEqual = typeof uniqueKeys === "function" ? uniqueKeys : (a, b) => a === b || isScalar(a) && isScalar(b) && a.value === b.value;
241  return items.some((pair) => isEqual(pair.key, search));
242}
243
244var startColMsg = "All mapping items must start at the same column";
245function resolveBlockMap({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bm, onError, tag) {
246  const NodeClass = tag?.nodeClass ?? YAMLMap;
247  const map = new NodeClass(ctx.schema);
248  if (ctx.atRoot)
249    ctx.atRoot = false;
250  let offset = bm.offset;
251  let commentEnd = null;
252  for (const collItem of bm.items) {
253    const { start, key, sep, value: value2 } = collItem;
254    const keyProps = resolveProps(start, {
255      indicator: "explicit-key-ind",
256      next: key ?? sep?.[0],
257      offset,
258      onError,
259      parentIndent: bm.indent,
260      startOnNewline: true
261    });
262    const implicitKey = !keyProps.found;
263    if (implicitKey) {
264      if (key) {
265        if (key.type === "block-seq")
266          onError(offset, "block-as-implicit-key", "A block sequence may not be used as an implicit map key");
267        else if ("indent" in key && key.indent !== bm.indent)
268          onError(offset, "BAD_INDENT", startColMsg);
269      }
270      if (!keyProps.anchor && !keyProps.tag && !sep) {
271        commentEnd = keyProps.end;
272        if (keyProps.comment) {
273          if (map.comment)
274            map.comment += "\n" + keyProps.comment;
275          else
276            map.comment = keyProps.comment;
277        }
278        continue;
279      }
280      if (keyProps.newlineAfterProp || containsNewline(key)) {
281        onError(key ?? start[start.length - 1], "multiline-implicit-key", "Implicit keys need to be on a single line");
282      }
283    } else if (keyProps.found?.indent !== bm.indent) {
284      onError(offset, "BAD_INDENT", startColMsg);
285    }
286    ctx.atKey = true;
287    const keyStart = keyProps.end;
288    const keyNode = key ? composeNode2(ctx, key, keyProps, onError) : composeEmptyNode2(ctx, keyStart, start, null, keyProps, onError);
289    if (ctx.schema.compat)
290      flowIndentCheck(bm.indent, key, onError);
291    ctx.atKey = false;
292    if (mapIncludes(ctx, map.items, keyNode))
293      onError(keyStart, "duplicate-key", "Map keys must be unique");
294    const valueProps = resolveProps(sep ?? [], {
295      indicator: "map-value-ind",
296      next: value2,
297      offset: keyNode.range[2],
298      onError,
299      parentIndent: bm.indent,
300      startOnNewline: !key || key.type === "block-scalar"
301    });
302    offset = valueProps.end;
303    if (valueProps.found) {
304      if (implicitKey) {
305        if (value2?.type === "block-map" && !valueProps.hasNewline)
306          onError(offset, "block-as-implicit-key", "Nested mappings are not allowed in compact mappings");
307        if (ctx.options.strict && keyProps.start < valueProps.found.offset - 1024)
308          onError(keyNode.range, "key-over-1024-chars", "The : indicator must be at most 1024 chars after the start of an implicit block mapping key");
309      }
310      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : composeEmptyNode2(ctx, offset, sep, null, valueProps, onError);
311      if (ctx.schema.compat)
312        flowIndentCheck(bm.indent, value2, onError);
313      offset = valueNode.range[2];
314      const pair = new Pair(keyNode, valueNode);
315      if (ctx.options.keepSourceTokens)
316        pair.srcToken = collItem;
317      map.items.push(pair);
318    } else {
319      if (implicitKey)
320        onError(keyNode.range, "MISSING_CHAR", "Implicit map keys need to be followed by map values");
321      if (valueProps.comment) {
322        if (keyNode.comment)
323          keyNode.comment += "\n" + valueProps.comment;
324        else
325          keyNode.comment = valueProps.comment;
326      }
327      const pair = new Pair(keyNode);
328      if (ctx.options.keepSourceTokens)
329        pair.srcToken = collItem;
330      map.items.push(pair);
331    }
332  }
333  if (commentEnd && commentEnd < offset)
334    onError(commentEnd, "IMPOSSIBLE", "Map comment with trailing content");
335  map.range = [bm.offset, offset, commentEnd ?? offset];
336  return map;
337}
338
339function resolveBlockSeq({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, bs, onError, tag) {
340  const NodeClass = tag?.nodeClass ?? YAMLSeq;
341  const seq = new NodeClass(ctx.schema);
342  if (ctx.atRoot)
343    ctx.atRoot = false;
344  if (ctx.atKey)
345    ctx.atKey = false;
346  let offset = bs.offset;
347  let commentEnd = null;
348  for (const { start, value: value2 } of bs.items) {
349    const props = resolveProps(start, {
350      indicator: "seq-item-ind",
351      next: value2,
352      offset,
353      onError,
354      parentIndent: bs.indent,
355      startOnNewline: true
356    });
357    if (!props.found) {
358      if (props.anchor || props.tag || value2) {
359        if (value2?.type === "block-seq")
360          onError(props.end, "BAD_INDENT", "All sequence items must start at the same column");
361        else
362          onError(offset, "MISSING_CHAR", "Sequence item without - indicator");
363      } else {
364        commentEnd = props.end;
365        if (props.comment)
366          seq.comment = props.comment;
367        continue;
368      }
369    }
370    const node = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, start, null, props, onError);
371    if (ctx.schema.compat)
372      flowIndentCheck(bs.indent, value2, onError);
373    offset = node.range[2];
374    seq.items.push(node);
375  }
376  seq.range = [bs.offset, offset, commentEnd ?? offset];
377  return seq;
378}
379
380var blockMsg = "Block collections are not allowed within flow collections";
381var isBlock = (token) => token && (token.type === "block-map" || token.type === "block-seq");
382function resolveFlowCollection({ composeNode: composeNode2, composeEmptyNode: composeEmptyNode2 }, ctx, fc, onError, tag) {
383  const isMap2 = fc.start.source === "{";
384  const fcName = isMap2 ? "flow map" : "flow sequence";
385  const NodeClass = tag?.nodeClass ?? (isMap2 ? YAMLMap : YAMLSeq);
386  const coll = new NodeClass(ctx.schema);
387  coll.flow = true;
388  const atRoot = ctx.atRoot;
389  if (atRoot)
390    ctx.atRoot = false;
391  if (ctx.atKey)
392    ctx.atKey = false;
393  let offset = fc.offset + fc.start.source.length;
394  for (let i = 0; i < fc.items.length; ++i) {
395    const collItem = fc.items[i];
396    const { start, key, sep, value: value2 } = collItem;
397    const props = resolveProps(start, {
398      flow: fcName,
399      indicator: "explicit-key-ind",
400      next: key ?? sep?.[0],
401      offset,
402      onError,
403      parentIndent: fc.indent,
404      startOnNewline: false
405    });
406    if (!props.found) {
407      if (!props.anchor && !props.tag && !sep && !value2) {
408        if (i === 0 && props.comma)
409          onError(props.comma, "unexpected-token", `Unexpected , in ${fcName}`);
410        else if (i < fc.items.length - 1)
411          onError(props.start, "unexpected-token", `Unexpected empty item in ${fcName}`);
412        if (props.comment) {
413          if (coll.comment)
414            coll.comment += "\n" + props.comment;
415          else
416            coll.comment = props.comment;
417        }
418        offset = props.end;
419        continue;
420      }
421      if (!isMap2 && ctx.options.strict && containsNewline(key))
422        onError(
423          key,
424          "multiline-implicit-key",
425          "Implicit keys of flow sequence pairs need to be on a single line"
426        );
427    }
428    if (i === 0) {
429      if (props.comma)
430        onError(props.comma, "unexpected-token", `Unexpected , in ${fcName}`);
431    } else {
432      if (!props.comma)
433        onError(props.start, "MISSING_CHAR", `Missing , between ${fcName} items`);
434      if (props.comment) {
435        let prevItemComment = "";
436        loop: for (const st of start) {
437          switch (st.type) {
438            case "comma":
439            case "space":
440              break;
441            case "comment":
442              prevItemComment = st.source.substring(1);
443              break loop;
444            default:
445              break loop;
446          }
447        }
448        if (prevItemComment) {
449          let prev = coll.items[coll.items.length - 1];
450          if (isPair(prev))
451            prev = prev.value ?? prev.key;
452          if (prev.comment)
453            prev.comment += "\n" + prevItemComment;
454          else
455            prev.comment = prevItemComment;
456          props.comment = props.comment.substring(prevItemComment.length + 1);
457        }
458      }
459    }
460    if (!isMap2 && !sep && !props.found) {
461      const valueNode = value2 ? composeNode2(ctx, value2, props, onError) : composeEmptyNode2(ctx, props.end, sep, null, props, onError);
462      coll.items.push(valueNode);
463      offset = valueNode.range[2];
464      if (isBlock(value2))
465        onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
466    } else {
467      ctx.atKey = true;
468      const keyStart = props.end;
469      const keyNode = key ? composeNode2(ctx, key, props, onError) : composeEmptyNode2(ctx, keyStart, start, null, props, onError);
470      if (isBlock(key))
471        onError(keyNode.range, "BLOCK_IN_FLOW", blockMsg);
472      ctx.atKey = false;
473      const valueProps = resolveProps(sep ?? [], {
474        flow: fcName,
475        indicator: "map-value-ind",
476        next: value2,
477        offset: keyNode.range[2],
478        onError,
479        parentIndent: fc.indent,
480        startOnNewline: false
481      });
482      if (valueProps.found) {
483        if (!isMap2 && !props.found && ctx.options.strict) {
484          if (sep)
485            for (const st of sep) {
486              if (st === valueProps.found)
487                break;
488              if (st.type === "newline") {
489                onError(st, "multiline-implicit-key", "Implicit keys of flow sequence pairs need to be on a single line");
490                break;
491              }
492            }
493          if (props.start < valueProps.found.offset - 1024)
494            onError(valueProps.found, "key-over-1024-chars", "The : indicator must be at most 1024 chars after the start of an implicit flow sequence key");
495        }
496      } else if (value2) {
497        if ("source" in value2 && value2.source?.[0] === ":")
498          onError(value2, "MISSING_CHAR", `Missing space after : in ${fcName}`);
499        else
500          onError(valueProps.start, "MISSING_CHAR", `Missing , or : between ${fcName} items`);
501      }
502      const valueNode = value2 ? composeNode2(ctx, value2, valueProps, onError) : valueProps.found ? composeEmptyNode2(ctx, valueProps.end, sep, null, valueProps, onError) : null;
503      if (valueNode) {
504        if (isBlock(value2))
505          onError(valueNode.range, "BLOCK_IN_FLOW", blockMsg);
506      } else if (valueProps.comment) {
507        if (keyNode.comment)
508          keyNode.comment += "\n" + valueProps.comment;
509        else
510          keyNode.comment = valueProps.comment;
511      }
512      const pair = new Pair(keyNode, valueNode);
513      if (ctx.options.keepSourceTokens)
514        pair.srcToken = collItem;
515      if (isMap2) {
516        const map = coll;
517        if (mapIncludes(ctx, map.items, keyNode))
518          onError(keyStart, "duplicate-key", "Map keys must be unique");
519        map.items.push(pair);
520      } else {
521        const map = new YAMLMap(ctx.schema);
522        map.flow = true;
523        map.items.push(pair);
524        const endRange = (valueNode ?? keyNode).range;
525        map.range = [keyNode.range[0], endRange[1], endRange[2]];
526        coll.items.push(map);
527      }
528      offset = valueNode ? valueNode.range[2] : valueProps.end;
529    }
530  }
531  const expectedEnd = isMap2 ? "}" : "]";
532  const [ce, ...ee] = fc.end;
533  let cePos = offset;
534  if (ce?.source === expectedEnd)
535    cePos = ce.offset + ce.source.length;
536  else {
537    const name = fcName[0].toUpperCase() + fcName.substring(1);
538    const msg = atRoot ? `${name} must end with a ${expectedEnd}` : `${name} in block collection must be sufficiently indented and end with a ${expectedEnd}`;
539    onError(offset, atRoot ? "MISSING_CHAR" : "BAD_INDENT", msg);
540    if (ce && ce.source.length !== 1)
541      ee.unshift(ce);
542  }
543  if (ee.length > 0) {
544    const end = resolveEnd(ee, cePos, ctx.options.strict, onError);
545    if (end.comment) {
546      if (coll.comment)
547        coll.comment += "\n" + end.comment;
548      else
549        coll.comment = end.comment;
550    }
551    coll.range = [fc.offset, cePos, end.offset];
552  } else {
553    coll.range = [fc.offset, cePos, cePos];
554  }
555  return coll;
556}
557
558function resolveCollection(CN2, ctx, token, onError, tagName, tag) {
559  const coll = token.type === "block-map" ? resolveBlockMap(CN2, ctx, token, onError, tag) : token.type === "block-seq" ? resolveBlockSeq(CN2, ctx, token, onError, tag) : resolveFlowCollection(CN2, ctx, token, onError, tag);
560  const Coll = tag?.nodeClass ?? (token.type === "block-map" || token.type !== "block-seq" && token.start.source === "{" ? YAMLMap : YAMLSeq);
561  if (tagName === "!" || tagName === Coll.tagName) {
562    coll.tag = Coll.tagName;
563    return coll;
564  }
565  if (tagName)
566    coll.tag = tagName;
567  return coll;
568}
569function composeCollection(CN2, ctx, token, props, onError) {
570  const tagToken = props.tag;
571  const tagName = !tagToken ? null : ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg));
572  if (token.type === "block-seq") {
573    const { anchor, newlineAfterProp: nl } = props;
574    const lastProp = anchor && tagToken ? anchor.offset > tagToken.offset ? anchor : tagToken : anchor ?? tagToken;
575    if (lastProp && (!nl || nl.offset < lastProp.offset)) {
576      const message = "Missing newline after block sequence props";
577      onError(lastProp, "MISSING_CHAR", message);
578    }
579  }
580  const expType = token.type === "block-map" ? "map" : token.type === "block-seq" ? "seq" : token.start.source === "{" ? "map" : "seq";
581  if (!tagToken || !tagName || tagName === "!" || tagName === YAMLMap.tagName && expType === "map" || tagName === YAMLSeq.tagName && expType === "seq") {
582    return resolveCollection(CN2, ctx, token, onError, tagName);
583  }
584  let tag = ctx.schema.tags.find((t) => t.tag === tagName && t.collection === expType);
585  if (!tag) {
586    const kt = ctx.schema.knownTags[tagName];
587    if (kt?.collection === expType) {
588      ctx.schema.tags.push(Object.assign({}, kt, { default: false }));
589      tag = kt;
590    } else {
591      if (kt) {
592        onError(tagToken, "BAD_COLLECTION_TYPE", `${kt.tag} used for ${expType} collection, but expects ${kt.collection ?? "scalar"}`, true);
593      } else {
594        onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, true);
595      }
596      return resolveCollection(CN2, ctx, token, onError, tagName);
597    }
598  }
599  const coll = resolveCollection(CN2, ctx, token, onError, tagName, tag);
600  const res = tag.resolve?.(coll, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg), ctx.options) ?? coll;
601  const node = isNode(res) ? res : new Scalar(res);
602  node.range = coll.range;
603  node.tag = tagName;
604  if (tag?.format)
605    node.format = tag.format;
606  return node;
607}
608
609function composeScalar(ctx, token, tagToken, onError) {
610  const { value: value2, type, comment, range } = token.type === "block-scalar" ? resolveBlockScalar(ctx, token, onError) : resolveFlowScalar(token, ctx.options.strict, onError);
611  const tagName = tagToken ? ctx.directives.tagName(tagToken.source, (msg) => onError(tagToken, "TAG_RESOLVE_FAILED", msg)) : null;
612  let tag;
613  if (ctx.options.stringKeys && ctx.atKey) {
614    tag = ctx.schema[SCALAR];
615  } else if (tagName)
616    tag = findScalarTagByName(ctx.schema, value2, tagName, tagToken, onError);
617  else if (token.type === "scalar")
618    tag = findScalarTagByTest(ctx, value2, token, onError);
619  else
620    tag = ctx.schema[SCALAR];
621  let scalar;
622  try {
623    const res = tag.resolve(value2, (msg) => onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg), ctx.options);
624    scalar = isScalar(res) ? res : new Scalar(res);
625  } catch (error) {
626    const msg = error instanceof Error ? error.message : String(error);
627    onError(tagToken ?? token, "TAG_RESOLVE_FAILED", msg);
628    scalar = new Scalar(value2);
629  }
630  scalar.range = range;
631  scalar.source = value2;
632  if (type)
633    scalar.type = type;
634  if (tagName)
635    scalar.tag = tagName;
636  if (tag.format)
637    scalar.format = tag.format;
638  if (comment)
639    scalar.comment = comment;
640  return scalar;
641}
642function findScalarTagByName(schema, value2, tagName, tagToken, onError) {
643  if (tagName === "!")
644    return schema[SCALAR];
645  const matchWithTest = [];
646  for (const tag of schema.tags) {
647    if (!tag.collection && tag.tag === tagName) {
648      if (tag.default && tag.test)
649        matchWithTest.push(tag);
650      else
651        return tag;
652    }
653  }
654  for (const tag of matchWithTest)
655    if (tag.test?.test(value2))
656      return tag;
657  const kt = schema.knownTags[tagName];
658  if (kt && !kt.collection) {
659    schema.tags.push(Object.assign({}, kt, { default: false, test: void 0 }));
660    return kt;
661  }
662  onError(tagToken, "TAG_RESOLVE_FAILED", `Unresolved tag: ${tagName}`, tagName !== "tag:yaml.org,2002:str");
663  return schema[SCALAR];
664}
665function findScalarTagByTest({ atKey, directives, schema }, value2, token, onError) {
666  const tag = schema.tags.find((tag2) => (tag2.default === true || atKey && tag2.default === "key") && tag2.test?.test(value2)) || schema[SCALAR];
667  if (schema.compat) {
668    const compat = schema.compat.find((tag2) => tag2.default && tag2.test?.test(value2)) ?? schema[SCALAR];
669    if (tag.tag !== compat.tag) {
670      const ts = directives.tagString(tag.tag);
671      const cs = directives.tagString(compat.tag);
672      const msg = `Value may be parsed as either ${ts} or ${cs}`;
673      onError(token, "TAG_RESOLVE_FAILED", msg, true);
674    }
675  }
676  return tag;
677}
678
679function emptyScalarPosition(offset, before, pos) {
680  if (before) {
681    pos ?? (pos = before.length);
682    for (let i = pos - 1; i >= 0; --i) {
683      let st = before[i];
684      switch (st.type) {
685        case "space":
686        case "comment":
687        case "newline":
688          offset -= st.source.length;
689          continue;
690      }
691      st = before[++i];
692      while (st?.type === "space") {
693        offset += st.source.length;
694        st = before[++i];
695      }
696      break;
697    }
698  }
699  return offset;
700}
701
702var CN = { composeNode, composeEmptyNode };
703function composeNode(ctx, token, props, onError) {
704  const atKey = ctx.atKey;
705  const { spaceBefore, comment, anchor, tag } = props;
706  let node;
707  let isSrcToken = true;
708  switch (token.type) {
709    case "alias":
710      node = composeAlias(ctx, token, onError);
711      if (anchor || tag)
712        onError(token, "ALIAS_PROPS", "An alias node must not specify any properties");
713      break;
714    case "scalar":
715    case "single-quoted-scalar":
716    case "double-quoted-scalar":
717    case "block-scalar":
718      node = composeScalar(ctx, token, tag, onError);
719      if (anchor)
720        node.anchor = anchor.source.substring(1);
721      break;
722    case "block-map":
723    case "block-seq":
724    case "flow-collection":
725      try {
726        node = composeCollection(CN, ctx, token, props, onError);
727        if (anchor)
728          node.anchor = anchor.source.substring(1);
729      } catch (error) {
730        const message = error instanceof Error ? error.message : String(error);
731        onError(token, "RESOURCE_EXHAUSTION", message);
732      }
733      break;
734    default: {
735      const message = token.type === "error" ? token.message : "".concat("Unsupported token (type: ", token.type, ")");
736      onError(token, "unexpected-token", message);
737      isSrcToken = false;
738    }
739  }
740  node ?? (node = composeEmptyNode(ctx, token.offset, void 0, null, props, onError));
741  if (anchor && node.anchor === "")
742    onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
743  if (atKey && ctx.options.stringKeys && (!isScalar(node) || typeof node.value !== "string" || node.tag && node.tag !== "tag:yaml.org,2002:str")) {
744    const msg = "With stringKeys, all keys must be strings";
745    onError(tag ?? token, "non-string-key", msg);
746  }
747  if (spaceBefore)
748    node.spaceBefore = true;
749  if (comment) {
750    if (token.type === "scalar" && token.source === "")
751      node.comment = comment;
752    else
753      node.commentBefore = comment;
754  }
755  if (ctx.options.keepSourceTokens && isSrcToken)
756    node.srcToken = token;
757  return node;
758}
759function composeEmptyNode(ctx, offset, before, pos, { spaceBefore, comment, anchor, tag, end }, onError) {
760  const token = {
761    type: "scalar",
762    offset: emptyScalarPosition(offset, before, pos),
763    indent: -1,
764    source: ""
765  };
766  const node = composeScalar(ctx, token, tag, onError);
767  if (anchor) {
768    node.anchor = anchor.source.substring(1);
769    if (node.anchor === "")
770      onError(anchor, "BAD_ALIAS", "Anchor cannot be an empty string");
771  }
772  if (spaceBefore)
773    node.spaceBefore = true;
774  if (comment) {
775    node.comment = comment;
776    node.range[2] = end;
777  }
778  return node;
779}
780function composeAlias({ options }, { offset, source, end }, onError) {
781  const alias = new Alias(source.substring(1));
782  if (alias.source === "")
783    onError(offset, "BAD_ALIAS", "Alias cannot be an empty string");
784  if (alias.source.endsWith(":"))
785    onError(offset + source.length - 1, "BAD_ALIAS", "Alias ending in : is ambiguous", true);
786  const valueEnd = offset + source.length;
787  const re = resolveEnd(end, valueEnd, options.strict, onError);
788  alias.range = [offset, valueEnd, re.offset];
789  if (re.comment)
790    alias.comment = re.comment;
791  return alias;
792}
793
794function composeDoc(options, directives, { offset, start, value: value2, end }, onError) {
795  const opts = Object.assign({ _directives: directives }, options);
796  const doc = new Document(void 0, opts);
797  const ctx = {
798    atKey: false,
799    atRoot: true,
800    directives: doc.directives,
801    options: doc.options,
802    schema: doc.schema
803  };
804  const props = resolveProps(start, {
805    indicator: "doc-start",
806    next: value2 ?? end?.[0],
807    offset,
808    onError,
809    parentIndent: 0,
810    startOnNewline: true
811  });
812  if (props.found) {
813    doc.directives.docStart = true;
814    if (value2 && (value2.type === "block-map" || value2.type === "block-seq") && !props.hasNewline)
815      onError(props.end, "MISSING_CHAR", "Block collection cannot start on same line with directives-end marker");
816  }
817  doc.contents = value2 ? composeNode(ctx, value2, props, onError) : composeEmptyNode(ctx, props.end, start, null, props, onError);
818  const contentEnd = doc.contents.range[2];
819  const re = resolveEnd(end, contentEnd, false, onError);
820  if (re.comment)
821    doc.comment = re.comment;
822  doc.range = [offset, contentEnd, re.offset];
823  return doc;
824}
825
826function getErrorPos(src) {
827  if (typeof src === "number")
828    return [src, src + 1];
829  if (Array.isArray(src))
830    return src.length === 2 ? src : [src[0], src[1]];
831  const { offset, source } = src;
832  return [offset, offset + (typeof source === "string" ? source.length : 1)];
833}
834function parsePrelude(prelude) {
835  let comment = "";
836  let atComment = false;
837  let afterEmptyLine = false;
838  for (let i = 0; i < prelude.length; ++i) {
839    const source = prelude[i];
840    switch (source[0]) {
841      case "#":
842        comment += (comment === "" ? "" : afterEmptyLine ? "\n\n" : "\n") + (source.substring(1) || " ");
843        atComment = true;
844        afterEmptyLine = false;
845        break;
846      case "%":
847        if (prelude[i + 1]?.[0] !== "#")
848          i += 1;
849        atComment = false;
850        break;
851      default:
852        if (!atComment)
853          afterEmptyLine = true;
854        atComment = false;
855    }
856  }
857  return { comment, afterEmptyLine };
858}
859var Composer = class {
860  constructor(options = {}) {
861    this.doc = null;
862    this.atDirectives = false;
863    this.prelude = [];
864    this.errors = [];
865    this.warnings = [];
866    this.onError = (source, code2, message, warning) => {
867      const pos = getErrorPos(source);
868      if (warning)
869        this.warnings.push(new YAMLWarning(pos, code2, message));
870      else
871        this.errors.push(new YAMLParseError(pos, code2, message));
872    };
873    this.directives = new Directives({ version: options.version || "1.2" });
874    this.options = options;
875  }
876  decorate(doc, afterDoc) {
877    const { comment, afterEmptyLine } = parsePrelude(this.prelude);
878    if (comment) {
879      const dc = doc.contents;
880      if (afterDoc) {
881        doc.comment = doc.comment ? `${doc.comment}
882${comment}` : comment;
883      } else if (afterEmptyLine || doc.directives.docStart || !dc) {
884        doc.commentBefore = comment;
885      } else if (isCollection(dc) && !dc.flow && dc.items.length > 0) {
886        let it = dc.items[0];
887        if (isPair(it))
888          it = it.key;
889        const cb = it.commentBefore;
890        it.commentBefore = cb ? `${comment}
891${cb}` : comment;
892      } else {
893        const cb = dc.commentBefore;
894        dc.commentBefore = cb ? `${comment}
895${cb}` : comment;
896      }
897    }
898    if (afterDoc) {
899      for (let i = 0; i < this.errors.length; ++i)
900        doc.errors.push(this.errors[i]);
901      for (let i = 0; i < this.warnings.length; ++i)
902        doc.warnings.push(this.warnings[i]);
903    } else {
904      doc.errors = this.errors;
905      doc.warnings = this.warnings;
906    }
907    this.prelude = [];
908    this.errors = [];
909    this.warnings = [];
910  }
911  streamInfo() {
912    return {
913      comment: parsePrelude(this.prelude).comment,
914      directives: this.directives,
915      errors: this.errors,
916      warnings: this.warnings
917    };
918  }
919  *compose(tokens, forceDoc = false, endOffset = -1) {
920    for (const token of tokens)
921      yield* this.next(token);
922    yield* this.end(forceDoc, endOffset);
923  }
924  *next(token) {
925    switch (token.type) {
926      case "directive":
927        this.directives.add(token.source, (offset, message, warning) => {
928          const pos = getErrorPos(token);
929          pos[0] += offset;
930          this.onError(pos, "BAD_DIRECTIVE", message, warning);
931        });
932        this.prelude.push(token.source);
933        this.atDirectives = true;
934        break;
935      case "document": {
936        const doc = composeDoc(this.options, this.directives, token, this.onError);
937        if (this.atDirectives && !doc.directives.docStart)
938          this.onError(token, "MISSING_CHAR", "Missing directives-end/doc-start indicator line");
939        this.decorate(doc, false);
940        if (this.doc)
941          yield this.doc;
942        this.doc = doc;
943        this.atDirectives = false;
944        break;
945      }
946      case "byte-order-mark":
947      case "space":
948        break;
949      case "comment":
950      case "newline":
951        this.prelude.push(token.source);
952        break;
953      case "error": {
954        const msg = token.source ? "".concat(token.message, ": ", JSON.stringify(token.source)) : token.message;
955        const error = new YAMLParseError(getErrorPos(token), "unexpected-token", msg);
956        if (this.atDirectives || !this.doc)
957          this.errors.push(error);
958        else
959          this.doc.errors.push(error);
960        break;
961      }
962      case "doc-end": {
963        if (!this.doc) {
964          const msg = "Unexpected doc-end without preceding document";
965          this.errors.push(new YAMLParseError(getErrorPos(token), "unexpected-token", msg));
966          break;
967        }
968        this.doc.directives.docEnd = true;
969        const end = resolveEnd(token.end, token.offset + token.source.length, this.doc.options.strict, this.onError);
970        this.decorate(this.doc, true);
971        if (end.comment) {
972          const dc = this.doc.comment;
973          this.doc.comment = dc ? `${dc}
974${end.comment}` : end.comment;
975        }
976        this.doc.range[2] = end.offset;
977        break;
978      }
979      default:
980        this.errors.push(new YAMLParseError(getErrorPos(token), "unexpected-token", "".concat("Unsupported token ", token.type)));
981    }
982  }
983  *end(forceDoc = false, endOffset = -1) {
984    if (this.doc) {
985      this.decorate(this.doc, true);
986      yield this.doc;
987      this.doc = null;
988    } else if (forceDoc) {
989      const opts = Object.assign({ _directives: this.directives }, this.options);
990      const doc = new Document(void 0, opts);
991      if (this.atDirectives)
992        this.onError(endOffset, "MISSING_CHAR", "Missing directives-end indicator line");
993      doc.range = [0, endOffset, endOffset];
994      this.decorate(doc, false);
995      yield doc;
996    }
997  }
998};
999
1000var LineCounter = class {
1001  constructor() {
1002    this.lineStarts = [];
1003    this.addNewLine = (offset) => this.lineStarts.push(offset);
1004    this.linePos = (offset) => {
1005      let low = 0;
1006      let high = this.lineStarts.length;
1007      while (low < high) {
1008        const mid = low + high >> 1;
1009        if (this.lineStarts[mid] < offset)
1010          low = mid + 1;
1011        else
1012          high = mid;
1013      }
1014      if (this.lineStarts[low] === offset)
1015        return { line: low + 1, col: 1 };
1016      if (low === 0)
1017        return { line: 0, col: offset };
1018      const start = this.lineStarts[low - 1];
1019      return { line: low, col: offset - start + 1 };
1020    };
1021  }
1022};
1023
1024function parseOptions(options) {
1025  const prettyErrors = options.prettyErrors !== false;
1026  const lineCounter = options.lineCounter || prettyErrors && new LineCounter() || null;
1027  return { lineCounter, prettyErrors };
1028}
1029function parseDocument(source, options = {}) {
1030  const { lineCounter, prettyErrors } = parseOptions(options);
1031  const parser = new Parser(lineCounter?.addNewLine);
1032  const composer = new Composer(options);
1033  let doc = null;
1034  for (const _doc of composer.compose(parser.parse(source), true, source.length)) {
1035    if (!doc)
1036      doc = _doc;
1037    else if (doc.options.logLevel !== "silent") {
1038      doc.errors.push(new YAMLParseError(_doc.range.slice(0, 2), "MULTIPLE_DOCS", "Source contains multiple documents; please use YAML.parseAllDocuments()"));
1039      break;
1040    }
1041  }
1042  if (prettyErrors && lineCounter) {
1043    doc.errors.forEach(prettifyError(source, lineCounter));
1044    doc.warnings.forEach(prettifyError(source, lineCounter));
1045  }
1046  return doc;
1047}
1048function parse(src, reviver, options) {
1049  let _reviver = void 0;
1050  if (typeof reviver === "function") {
1051    _reviver = reviver;
1052  } else if (options === void 0 && reviver && typeof reviver === "object") {
1053    options = reviver;
1054  }
1055  const doc = parseDocument(src, options);
1056  if (!doc)
1057    return null;
1058  doc.warnings.forEach((warning) => warn(doc.options.logLevel, warning));
1059  if (doc.errors.length > 0) {
1060    if (doc.options.logLevel !== "silent")
1061      throw doc.errors[0];
1062    else
1063      doc.errors = [];
1064  }
1065  return doc.toJS(Object.assign({ reviver: _reviver }, options));
1066}
1067
1068var nodeIo = void 0;
1069
1070var OPAQUE = "\0";
1071function skeleton(source) {
1072  let out = "";
1073  let inClass = false;
1074  for (let i = 0; i < source.length; i++) {
1075    const ch = source[i];
1076    if (ch === "\\") {
1077      out += i + 1 < source.length ? OPAQUE + OPAQUE : OPAQUE;
1078      i++;
1079      continue;
1080    }
1081    if (inClass) {
1082      if (ch === "]") {
1083        inClass = false;
1084        out += "]";
1085      } else out += OPAQUE;
1086      continue;
1087    }
1088    if (ch === "[") {
1089      inClass = true;
1090      out += "[";
1091      continue;
1092    }
1093    out += ch;
1094  }
1095  return out;
1096}
1097var QUANTIFIER = /[*+}]/;
1098function findNestedQuantifier(skel) {
1099  for (let i = 0; i < skel.length; i++) {
1100    if (skel[i] !== "(") continue;
1101    let depth = 0;
1102    let end = -1;
1103    for (let j = i; j < skel.length; j++) {
1104      if (skel[j] === "(") depth++;
1105      else if (skel[j] === ")") {
1106        depth--;
1107        if (depth === 0) {
1108          end = j;
1109          break;
1110        }
1111      }
1112    }
1113    if (end === -1) continue;
1114    const after = skel[end + 1];
1115    if (!after || !QUANTIFIER.test(after)) continue;
1116    const body = skel.slice(i + 1, end);
1117    let inner = 0;
1118    for (let k = 0; k < body.length; k++) {
1119      const c = body[k];
1120      if (c === "(") inner++;
1121      else if (c === ")") inner--;
1122      else if (inner === 0 && (c === "+" || c === "*")) {
1123        return {
1124          kind: "nested-quantifier",
1125          detail: `group (${body}) is quantified with '${after}' and its body already contains '${c}'`
1126        };
1127      } else if (inner === 0 && c === "{") {
1128        return {
1129          kind: "nested-quantifier",
1130          detail: `group (${body}) is quantified with '${after}' and its body already contains a {n,m} repeat`
1131        };
1132      }
1133    }
1134  }
1135  return null;
1136}
1137function findOverlappingAlternation(source, skel) {
1138  for (let i = 0; i < skel.length; i++) {
1139    if (skel[i] !== "(") continue;
1140    let depth = 0;
1141    let end = -1;
1142    for (let j = i; j < skel.length; j++) {
1143      if (skel[j] === "(") depth++;
1144      else if (skel[j] === ")") {
1145        depth--;
1146        if (depth === 0) {
1147          end = j;
1148          break;
1149        }
1150      }
1151    }
1152    if (end === -1) continue;
1153    const after = skel[end + 1];
1154    if (!after || !QUANTIFIER.test(after)) continue;
1155    const body = skel.slice(i + 1, end).replace(/^\?[:=!<]*/, "");
1156    if (!body.includes("|")) continue;
1157    const bodyStart = i + 1 + (skel.slice(i + 1, end).length - body.length);
1158    const spans = [];
1159    let d = 0;
1160    let from = bodyStart;
1161    for (let k = bodyStart; k < end; k++) {
1162      const c = skel[k];
1163      if (c === "(") d++;
1164      else if (c === ")") d--;
1165      else if (c === "|" && d === 0) {
1166        spans.push({ from, to: k });
1167        from = k + 1;
1168      }
1169    }
1170    spans.push({ from, to: end });
1171    if (spans.length < 2) continue;
1172    const firsts = spans.map((s) => firstSet(source, skel, s.from, s.to));
1173    for (let a = 0; a < firsts.length; a++) {
1174      for (let b = a + 1; b < firsts.length; b++) {
1175        if (!intersects(firsts[a], firsts[b])) continue;
1176        return {
1177          kind: "overlapping-alternation",
1178          detail: `quantified group (${body.replaceAll(OPAQUE, ".")}) has alternatives that can both start with the same character`
1179        };
1180      }
1181    }
1182  }
1183  return null;
1184}
1185function firstSet(source, skel, from, to) {
1186  let i = from;
1187  while (i < to && /\s/.test(skel[i])) i++;
1188  if (i >= to) return null;
1189  const ch = skel[i];
1190  if (ch === "[") {
1191    const close2 = skel.indexOf("]", i + 1);
1192    if (close2 === -1 || close2 >= to) return null;
1193    const inner = source.slice(i + 1, close2);
1194    if (inner.startsWith("^")) return null;
1195    const out =   new Set();
1196    for (let k = 0; k < inner.length; k++) {
1197      const c = inner[k];
1198      if (c === "\\") {
1199        return null;
1200      }
skills/plain-english/scripts/core/chunk-ZVATLAGB.mjs 2007 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2import {
3  Scalar
4} from "./chunk-ZVNRIHJD.mjs";
5
6function resolveBlockScalar(ctx, scalar, onError) {
7  const start = scalar.offset;
8  const header = parseBlockScalarHeader(scalar, ctx.options.strict, onError);
9  if (!header)
10    return { value: "", type: null, comment: "", range: [start, start, start] };
11  const type = header.mode === ">" ? Scalar.BLOCK_FOLDED : Scalar.BLOCK_LITERAL;
12  const lines = scalar.source ? splitLines(scalar.source) : [];
13  let chompStart = lines.length;
14  for (let i = lines.length - 1; i >= 0; --i) {
15    const content = lines[i][1];
16    if (content === "" || content === "\r")
17      chompStart = i;
18    else
19      break;
20  }
21  if (chompStart === 0) {
22    const value2 = header.chomp === "+" && lines.length > 0 ? "\n".repeat(Math.max(1, lines.length - 1)) : "";
23    let end2 = start + header.length;
24    if (scalar.source)
25      end2 += scalar.source.length;
26    return { value: value2, type, comment: header.comment, range: [start, end2, end2] };
27  }
28  let trimIndent = scalar.indent + header.indent;
29  let offset = scalar.offset + header.length;
30  let contentStart = 0;
31  for (let i = 0; i < chompStart; ++i) {
32    const [indent, content] = lines[i];
33    if (content === "" || content === "\r") {
34      if (header.indent === 0 && indent.length > trimIndent)
35        trimIndent = indent.length;
36    } else {
37      if (indent.length < trimIndent) {
38        const message = "Block scalars with more-indented leading empty lines must use an explicit indentation indicator";
39        onError(offset + indent.length, "MISSING_CHAR", message);
40      }
41      if (header.indent === 0)
42        trimIndent = indent.length;
43      contentStart = i;
44      if (trimIndent === 0 && !ctx.atRoot) {
45        const message = "Block scalar values in collections must be indented";
46        onError(offset, "BAD_INDENT", message);
47      }
48      break;
49    }
50    offset += indent.length + content.length + 1;
51  }
52  for (let i = lines.length - 1; i >= chompStart; --i) {
53    if (lines[i][0].length > trimIndent)
54      chompStart = i + 1;
55  }
56  let value = "";
57  let sep = "";
58  let prevMoreIndented = false;
59  for (let i = 0; i < contentStart; ++i)
60    value += lines[i][0].slice(trimIndent) + "\n";
61  for (let i = contentStart; i < chompStart; ++i) {
62    let [indent, content] = lines[i];
63    offset += indent.length + content.length + 1;
64    const crlf = content[content.length - 1] === "\r";
65    if (crlf)
66      content = content.slice(0, -1);
67    if (content && indent.length < trimIndent) {
68      const src = header.indent ? "explicit indentation indicator" : "first line";
69      const message = `Block scalar lines must not be less indented than their ${src}`;
70      onError(offset - content.length - (crlf ? 2 : 1), "BAD_INDENT", message);
71      indent = "";
72    }
73    if (type === Scalar.BLOCK_LITERAL) {
74      value += sep + indent.slice(trimIndent) + content;
75      sep = "\n";
76    } else if (indent.length > trimIndent || content[0] === "	") {
77      if (sep === " ")
78        sep = "\n";
79      else if (!prevMoreIndented && sep === "\n")
80        sep = "\n\n";
81      value += sep + indent.slice(trimIndent) + content;
82      sep = "\n";
83      prevMoreIndented = true;
84    } else if (content === "") {
85      if (sep === "\n")
86        value += "\n";
87      else
88        sep = "\n";
89    } else {
90      value += sep + content;
91      sep = " ";
92      prevMoreIndented = false;
93    }
94  }
95  switch (header.chomp) {
96    case "-":
97      break;
98    case "+":
99      for (let i = chompStart; i < lines.length; ++i)
100        value += "\n" + lines[i][0].slice(trimIndent);
101      if (value[value.length - 1] !== "\n")
102        value += "\n";
103      break;
104    default:
105      value += "\n";
106  }
107  const end = start + header.length + scalar.source.length;
108  return { value, type, comment: header.comment, range: [start, end, end] };
109}
110function parseBlockScalarHeader({ offset, props }, strict, onError) {
111  if (props[0].type !== "block-scalar-header") {
112    onError(props[0], "IMPOSSIBLE", "Block scalar header not found");
113    return null;
114  }
115  const { source } = props[0];
116  const mode = source[0];
117  let indent = 0;
118  let chomp = "";
119  let error = -1;
120  for (let i = 1; i < source.length; ++i) {
121    const ch = source[i];
122    if (!chomp && (ch === "-" || ch === "+"))
123      chomp = ch;
124    else {
125      const n = Number(ch);
126      if (!indent && n)
127        indent = n;
128      else if (error === -1)
129        error = offset + i;
130    }
131  }
132  if (error !== -1)
133    onError(error, "unexpected-token", `Block scalar header includes extra characters: ${source}`);
134  let hasSpace = false;
135  let comment = "";
136  let length = source.length;
137  for (let i = 1; i < props.length; ++i) {
138    const token = props[i];
139    switch (token.type) {
140      case "space":
141        hasSpace = true;
142      case "newline":
143        length += token.source.length;
144        break;
145      case "comment":
146        if (strict && !hasSpace) {
147          const message = "Comments must be separated from other tokens by white space characters";
148          onError(token, "MISSING_CHAR", message);
149        }
150        length += token.source.length;
151        comment = token.source.substring(1);
152        break;
153      case "error":
154        onError(token, "unexpected-token", token.message);
155        length += token.source.length;
156        break;
157      default: {
158        const message = "".concat("Unexpected token in block scalar header: ", token.type);
159        onError(token, "unexpected-token", message);
160        const ts = token.source;
161        if (ts && typeof ts === "string")
162          length += ts.length;
163      }
164    }
165  }
166  return { mode, indent, chomp, comment, length };
167}
168function splitLines(source) {
169  const split = source.split(/\n( *)/);
170  const first = split[0];
171  const m = first.match(/^( *)/);
172  const line0 = m?.[1] ? [m[1], first.slice(m[1].length)] : ["", first];
173  const lines = [line0];
174  for (let i = 1; i < split.length; i += 2)
175    lines.push([split[i], split[i + 1]]);
176  return lines;
177}
178
179function resolveEnd(end, offset, reqSpace, onError) {
180  let comment = "";
181  if (end) {
182    let hasSpace = false;
183    let sep = "";
184    for (const token of end) {
185      const { source, type } = token;
186      switch (type) {
187        case "space":
188          hasSpace = true;
189          break;
190        case "comment": {
191          if (reqSpace && !hasSpace)
192            onError(token, "MISSING_CHAR", "Comments must be separated from other tokens by white space characters");
193          const cb = source.substring(1) || " ";
194          if (!comment)
195            comment = cb;
196          else
197            comment += sep + cb;
198          sep = "";
199          break;
200        }
201        case "newline":
202          if (comment)
203            sep += source;
204          hasSpace = true;
205          break;
206        default:
207          onError(token, "unexpected-token", `Unexpected ${type} at node end`);
208      }
209      offset += source.length;
210    }
211  }
212  return { comment, offset };
213}
214
215function resolveFlowScalar(scalar, strict, onError) {
216  const { offset, type, source, end } = scalar;
217  let _type;
218  let value;
219  const _onError = (rel, code, msg) => onError(offset + rel, code, msg);
220  switch (type) {
221    case "scalar":
222      _type = Scalar.PLAIN;
223      value = plainValue(source, _onError);
224      break;
225    case "single-quoted-scalar":
226      _type = Scalar.QUOTE_SINGLE;
227      value = singleQuotedValue(source, _onError);
228      break;
229    case "double-quoted-scalar":
230      _type = Scalar.QUOTE_DOUBLE;
231      value = doubleQuotedValue(source, _onError);
232      break;
233    default:
234      onError(scalar, "unexpected-token", `Expected a flow scalar value, but found: ${type}`);
235      return {
236        value: "",
237        type: null,
238        comment: "",
239        range: [offset, offset + source.length, offset + source.length]
240      };
241  }
242  const valueEnd = offset + source.length;
243  const re = resolveEnd(end, valueEnd, strict, onError);
244  return {
245    value,
246    type: _type,
247    comment: re.comment,
248    range: [offset, valueEnd, re.offset]
249  };
250}
251function plainValue(source, onError) {
252  let badChar = "";
253  switch (source[0]) {
254    case "	":
255      badChar = "a tab character";
256      break;
257    case ",":
258      badChar = "flow indicator character ,";
259      break;
260    case "%":
261      badChar = "directive indicator character %";
262      break;
263    case "|":
264    case ">": {
265      badChar = `block scalar indicator ${source[0]}`;
266      break;
267    }
268    case "@":
269    case "`": {
270      badChar = `reserved character ${source[0]}`;
271      break;
272    }
273  }
274  if (badChar)
275    onError(0, "BAD_SCALAR_START", `Plain value cannot start with ${badChar}`);
276  return unfoldLines(source);
277}
278function singleQuotedValue(source, onError) {
279  if (source[source.length - 1] !== "'" || source.length === 1)
280    onError(source.length, "MISSING_CHAR", "Missing closing 'quote");
281  return unfoldLines(source.slice(1, -1)).replace(/''/g, "'");
282}
283function unfoldLines(source) {
284  const line = /(.*?)\r?\n/sy;
285  let match = line.exec(source);
286  if (!match)
287    return source;
288  let trimEnd, trimBoth;
289  try {
290    trimEnd = new RegExp("(?<![ 	])[ 	]+$");
291    trimBoth = new RegExp("^[ 	]+|(?<![ 	])[ 	]+$", "g");
292  } catch {
293    trimEnd = /[ \t]+$/;
294    trimBoth = /^[ \t]+|[ \t]+$/g;
295  }
296  let res = match[1].replace(trimEnd, "");
297  let sep = " ";
298  let pos = line.lastIndex;
299  while (match = line.exec(source)) {
300    const lm = match[1].replace(trimBoth, "");
301    if (lm === "") {
302      if (sep === "\n")
303        res += sep;
304      else
305        sep = "\n";
306    } else {
307      res += sep + lm;
308      sep = " ";
309    }
310    pos = line.lastIndex;
311  }
312  const last = /[ \t]*(.*)/sy;
313  last.lastIndex = pos;
314  match = last.exec(source);
315  return res + sep + (match?.[1] ?? "");
316}
317function doubleQuotedValue(source, onError) {
318  let res = "";
319  for (let i = 1; i < source.length - 1; ++i) {
320    const ch = source[i];
321    if (ch === "\r" && source[i + 1] === "\n")
322      continue;
323    if (ch === "\n") {
324      const { fold, offset } = foldNewline(source, i);
325      res += fold;
326      i = offset;
327    } else if (ch === "\\") {
328      let next = source[++i];
329      const cc = escapeCodes[next];
330      if (cc)
331        res += cc;
332      else if (next === "\n") {
333        next = source[i + 1];
334        while (next === " " || next === "	")
335          next = source[++i + 1];
336      } else if (next === "\r" && source[i + 1] === "\n") {
337        next = source[++i + 1];
338        while (next === " " || next === "	")
339          next = source[++i + 1];
340      } else if (next === "x" || next === "u" || next === "U") {
341        const length = next === "x" ? 2 : next === "u" ? 4 : 8;
342        res += parseCharCode(source, i + 1, length, onError);
343        i += length;
344      } else {
345        const raw = source.substr(i - 1, 2);
346        onError(i - 1, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
347        res += raw;
348      }
349    } else if (ch === " " || ch === "	") {
350      const wsStart = i;
351      let next = source[i + 1];
352      while (next === " " || next === "	")
353        next = source[++i + 1];
354      if (next !== "\n" && !(next === "\r" && source[i + 2] === "\n"))
355        res += i > wsStart ? source.slice(wsStart, i + 1) : ch;
356    } else {
357      res += ch;
358    }
359  }
360  if (source[source.length - 1] !== '"' || source.length === 1)
361    onError(source.length, "MISSING_CHAR", 'Missing closing "quote');
362  return res;
363}
364function foldNewline(source, offset) {
365  let fold = "";
366  let ch = source[offset + 1];
367  while (ch === " " || ch === "	" || ch === "\n" || ch === "\r") {
368    if (ch === "\r" && source[offset + 2] !== "\n")
369      break;
370    if (ch === "\n")
371      fold += "\n";
372    offset += 1;
373    ch = source[offset + 1];
374  }
375  if (!fold)
376    fold = " ";
377  return { fold, offset };
378}
379var escapeCodes = {
380  "0": "\0",
381  a: "\x07",
382  b: "\b",
383  e: "\x1B",
384  f: "\f",
385  n: "\n",
386  r: "\r",
387  t: "	",
388  v: "\v",
389  N: "\x85",
390  _: "\xA0",
391  L: "\u2028",
392  P: "\u2029",
393  " ": " ",
394  '"': '"',
395  "/": "/",
396  "\\": "\\",
397  "	": "	"
398};
399function parseCharCode(source, offset, length, onError) {
400  const cc = source.substr(offset, length);
401  const ok = cc.length === length && /^[0-9a-fA-F]+$/.test(cc);
402  const code = ok ? parseInt(cc, 16) : NaN;
403  try {
404    return String.fromCodePoint(code);
405  } catch {
406    const raw = source.substr(offset - 2, length + 2);
407    onError(offset - 2, "BAD_DQ_ESCAPE", `Invalid escape sequence ${raw}`);
408    return raw;
409  }
410}
411
412var YAMLError = class extends Error {
413  constructor(name, pos, code, message) {
414    super();
415    this.name = name;
416    this.code = code;
417    this.message = message;
418    this.pos = pos;
419  }
420};
421var YAMLParseError = class extends YAMLError {
422  constructor(pos, code, message) {
423    super("YAMLParseError", pos, code, message);
424  }
425};
426var YAMLWarning = class extends YAMLError {
427  constructor(pos, code, message) {
428    super("YAMLWarning", pos, code, message);
429  }
430};
431var prettifyError = (src, lc) => (error) => {
432  if (error.pos[0] === -1)
433    return;
434  error.linePos = error.pos.map((pos) => lc.linePos(pos));
435  const { line, col } = error.linePos[0];
436  error.message += ` at line ${line}, column ${col}`;
437  let ci = col - 1;
438  let lineStr = src.substring(lc.lineStarts[line - 1], lc.lineStarts[line]).replace(/[\n\r]+$/, "");
439  if (ci >= 60 && lineStr.length > 80) {
440    const trimStart = Math.min(ci - 39, lineStr.length - 79);
441    lineStr = "\u2026" + lineStr.substring(trimStart);
442    ci -= trimStart - 1;
443  }
444  if (lineStr.length > 80)
445    lineStr = lineStr.substring(0, 79) + "\u2026";
446  if (line > 1 && /^ *$/.test(lineStr.substring(0, ci))) {
447    let prev = src.substring(lc.lineStarts[line - 2], lc.lineStarts[line - 1]);
448    if (prev.length > 80)
449      prev = prev.substring(0, 79) + "\u2026\n";
450    lineStr = prev + lineStr;
451  }
452  if (/[^ ]/.test(lineStr)) {
453    let count = 1;
454    const end = error.linePos[1];
455    if (end?.line === line && end.col > col) {
456      count = Math.max(1, Math.min(end.col - col, 80 - ci));
457    }
458    const pointer = " ".repeat(ci) + "^".repeat(count);
459    error.message += `:
460
461${lineStr}
462${pointer}
463`;
464  }
465};
466
467var BREAK =   Symbol("break visit");
468var SKIP =   Symbol("skip children");
469var REMOVE =   Symbol("remove item");
470function visit(cst, visitor) {
471  if ("type" in cst && cst.type === "document")
472    cst = { start: cst.start, value: cst.value };
473  _visit(Object.freeze([]), cst, visitor);
474}
475visit.BREAK = BREAK;
476visit.SKIP = SKIP;
477visit.REMOVE = REMOVE;
478visit.itemAtPath = (cst, path) => {
479  let item = cst;
480  for (const [field, index] of path) {
481    const tok = item?.[field];
482    if (tok && "items" in tok) {
483      item = tok.items[index];
484    } else
485      return void 0;
486  }
487  return item;
488};
489visit.parentCollection = (cst, path) => {
490  const parent = visit.itemAtPath(cst, path.slice(0, -1));
491  const field = path[path.length - 1][0];
492  const coll = parent?.[field];
493  if (coll && "items" in coll)
494    return coll;
495  throw new Error("Parent collection not found");
496};
497function _visit(path, item, visitor) {
498  let ctrl = visitor(item, path);
499  if (typeof ctrl === "symbol")
500    return ctrl;
501  for (const field of ["key", "value"]) {
502    const token = item[field];
503    if (token && "items" in token) {
504      for (let i = 0; i < token.items.length; ++i) {
505        const ci = _visit(Object.freeze(path.concat([[field, i]])), token.items[i], visitor);
506        if (typeof ci === "number")
507          i = ci - 1;
508        else if (ci === BREAK)
509          return BREAK;
510        else if (ci === REMOVE) {
511          token.items.splice(i, 1);
512          i -= 1;
513        }
514      }
515      if (typeof ctrl === "function" && field === "key")
516        ctrl = ctrl(item, path);
517    }
518  }
519  return typeof ctrl === "function" ? ctrl(item, path) : ctrl;
520}
521
522var BOM = "\uFEFF";
523var DOCUMENT = "\u0002";
524var FLOW_END = "\u0018";
525var SCALAR = "\u001F";
526function tokenType(source) {
527  switch (source) {
528    case BOM:
529      return "byte-order-mark";
530    case DOCUMENT:
531      return "doc-mode";
532    case FLOW_END:
533      return "flow-error-end";
534    case SCALAR:
535      return "scalar";
536    case "---":
537      return "doc-start";
538    case "...":
539      return "doc-end";
540    case "":
541    case "\n":
542    case "\r\n":
543      return "newline";
544    case "-":
545      return "seq-item-ind";
546    case "?":
547      return "explicit-key-ind";
548    case ":":
549      return "map-value-ind";
550    case "{":
551      return "flow-map-start";
552    case "}":
553      return "flow-map-end";
554    case "[":
555      return "flow-seq-start";
556    case "]":
557      return "flow-seq-end";
558    case ",":
559      return "comma";
560  }
561  switch (source[0]) {
562    case " ":
563    case "	":
564      return "space";
565    case "#":
566      return "comment";
567    case "%":
568      return "directive-line";
569    case "*":
570      return "alias";
571    case "&":
572      return "anchor";
573    case "!":
574      return "tag";
575    case "'":
576      return "single-quoted-scalar";
577    case '"':
578      return "double-quoted-scalar";
579    case "|":
580    case ">":
581      return "block-scalar-header";
582  }
583  return null;
584}
585
586function isEmpty(ch) {
587  switch (ch) {
588    case void 0:
589    case " ":
590    case "\n":
591    case "\r":
592    case "	":
593      return true;
594    default:
595      return false;
596  }
597}
598var hexDigits = new Set("0123456789ABCDEFabcdef");
599var tagChars = new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
600var flowIndicatorChars = new Set(",[]{}");
601var invalidAnchorChars = new Set(" ,[]{}\n\r	");
602var isNotAnchorChar = (ch) => !ch || invalidAnchorChars.has(ch);
603var Lexer = class {
604  constructor() {
605    this.atEnd = false;
606    this.blockScalarIndent = -1;
607    this.blockScalarKeep = false;
608    this.buffer = "";
609    this.flowKey = false;
610    this.flowLevel = 0;
611    this.indentNext = 0;
612    this.indentValue = 0;
613    this.lineEndPos = null;
614    this.next = null;
615    this.pos = 0;
616  }
617  *lex(source, incomplete = false) {
618    if (source) {
619      if (typeof source !== "string")
620        throw TypeError("source is not a string");
621      this.buffer = this.buffer ? this.buffer + source : source;
622      this.lineEndPos = null;
623    }
624    this.atEnd = !incomplete;
625    let next = this.next ?? "stream";
626    while (next && (incomplete || this.hasChars(1)))
627      next = yield* this.parseNext(next);
628  }
629  atLineEnd() {
630    let i = this.pos;
631    let ch = this.buffer[i];
632    while (ch === " " || ch === "	")
633      ch = this.buffer[++i];
634    if (!ch || ch === "#" || ch === "\n")
635      return true;
636    if (ch === "\r")
637      return this.buffer[i + 1] === "\n";
638    return false;
639  }
640  charAt(n) {
641    return this.buffer[this.pos + n];
642  }
643  continueScalar(offset) {
644    let ch = this.buffer[offset];
645    if (this.indentNext > 0) {
646      let indent = 0;
647      while (ch === " ")
648        ch = this.buffer[++indent + offset];
649      if (ch === "\r") {
650        const next = this.buffer[indent + offset + 1];
651        if (next === "\n" || !next && !this.atEnd)
652          return offset + indent + 1;
653      }
654      return ch === "\n" || indent >= this.indentNext || !ch && !this.atEnd ? offset + indent : -1;
655    }
656    if (ch === "-" || ch === ".") {
657      const dt = this.buffer.substr(offset, 3);
658      if ((dt === "---" || dt === "...") && isEmpty(this.buffer[offset + 3]))
659        return -1;
660    }
661    return offset;
662  }
663  getLine() {
664    let end = this.lineEndPos;
665    if (typeof end !== "number" || end !== -1 && end < this.pos) {
666      end = this.buffer.indexOf("\n", this.pos);
667      this.lineEndPos = end;
668    }
669    if (end === -1)
670      return this.atEnd ? this.buffer.substring(this.pos) : null;
671    if (this.buffer[end - 1] === "\r")
672      end -= 1;
673    return this.buffer.substring(this.pos, end);
674  }
675  hasChars(n) {
676    return this.pos + n <= this.buffer.length;
677  }
678  setNext(state) {
679    this.buffer = this.buffer.substring(this.pos);
680    this.pos = 0;
681    this.lineEndPos = null;
682    this.next = state;
683    return null;
684  }
685  peek(n) {
686    return this.buffer.substr(this.pos, n);
687  }
688  *parseNext(next) {
689    switch (next) {
690      case "stream":
691        return yield* this.parseStream();
692      case "line-start":
693        return yield* this.parseLineStart();
694      case "block-start":
695        return yield* this.parseBlockStart();
696      case "doc":
697        return yield* this.parseDocument();
698      case "flow":
699        return yield* this.parseFlowCollection();
700      case "quoted-scalar":
701        return yield* this.parseQuotedScalar();
702      case "block-scalar":
703        return yield* this.parseBlockScalar();
704      case "plain-scalar":
705        return yield* this.parsePlainScalar();
706    }
707  }
708  *parseStream() {
709    let line = this.getLine();
710    if (line === null)
711      return this.setNext("stream");
712    if (line[0] === BOM) {
713      yield* this.pushCount(1);
714      line = line.substring(1);
715    }
716    if (line[0] === "%") {
717      let dirEnd = line.length;
718      let cs = line.indexOf("#");
719      while (cs !== -1) {
720        const ch = line[cs - 1];
721        if (ch === " " || ch === "	") {
722          dirEnd = cs - 1;
723          break;
724        } else {
725          cs = line.indexOf("#", cs + 1);
726        }
727      }
728      while (true) {
729        const ch = line[dirEnd - 1];
730        if (ch === " " || ch === "	")
731          dirEnd -= 1;
732        else
733          break;
734      }
735      const n = (yield* this.pushCount(dirEnd)) + (yield* this.pushSpaces(true));
736      yield* this.pushCount(line.length - n);
737      this.pushNewline();
738      return "stream";
739    }
740    if (this.atLineEnd()) {
741      const sp = yield* this.pushSpaces(true);
742      yield* this.pushCount(line.length - sp);
743      yield* this.pushNewline();
744      return "stream";
745    }
746    yield DOCUMENT;
747    return yield* this.parseLineStart();
748  }
749  *parseLineStart() {
750    const ch = this.charAt(0);
751    if (!ch && !this.atEnd)
752      return this.setNext("line-start");
753    if (ch === "-" || ch === ".") {
754      if (!this.atEnd && !this.hasChars(4))
755        return this.setNext("line-start");
756      const s = this.peek(3);
757      if ((s === "---" || s === "...") && isEmpty(this.charAt(3))) {
758        yield* this.pushCount(3);
759        this.indentValue = 0;
760        this.indentNext = 0;
761        return s === "---" ? "doc" : "stream";
762      }
763    }
764    this.indentValue = yield* this.pushSpaces(false);
765    if (this.indentNext > this.indentValue && !isEmpty(this.charAt(1)))
766      this.indentNext = this.indentValue;
767    return yield* this.parseBlockStart();
768  }
769  *parseBlockStart() {
770    const [ch0, ch1] = this.peek(2);
771    if (!ch1 && !this.atEnd)
772      return this.setNext("block-start");
773    if ((ch0 === "-" || ch0 === "?" || ch0 === ":") && isEmpty(ch1)) {
774      const n = (yield* this.pushCount(1)) + (yield* this.pushSpaces(true));
775      this.indentNext = this.indentValue + 1;
776      this.indentValue += n;
777      return "block-start";
778    }
779    return "doc";
780  }
781  *parseDocument() {
782    yield* this.pushSpaces(true);
783    const line = this.getLine();
784    if (line === null)
785      return this.setNext("doc");
786    let n = yield* this.pushIndicators();
787    switch (line[n]) {
788      case "#":
789        yield* this.pushCount(line.length - n);
790      case void 0:
791        yield* this.pushNewline();
792        return yield* this.parseLineStart();
793      case "{":
794      case "[":
795        yield* this.pushCount(1);
796        this.flowKey = false;
797        this.flowLevel = 1;
798        return "flow";
799      case "}":
800      case "]":
801        yield* this.pushCount(1);
802        return "doc";
803      case "*":
804        yield* this.pushUntil(isNotAnchorChar);
805        return "doc";
806      case '"':
807      case "'":
808        return yield* this.parseQuotedScalar();
809      case "|":
810      case ">":
811        n += yield* this.parseBlockScalarHeader();
812        n += yield* this.pushSpaces(true);
813        yield* this.pushCount(line.length - n);
814        yield* this.pushNewline();
815        return yield* this.parseBlockScalar();
816      default:
817        return yield* this.parsePlainScalar();
818    }
819  }
820  *parseFlowCollection() {
821    let nl, sp;
822    let indent = -1;
823    do {
824      nl = yield* this.pushNewline();
825      if (nl > 0) {
826        sp = yield* this.pushSpaces(false);
827        this.indentValue = indent = sp;
828      } else {
829        sp = 0;
830      }
831      sp += yield* this.pushSpaces(true);
832    } while (nl + sp > 0);
833    const line = this.getLine();
834    if (line === null)
835      return this.setNext("flow");
836    if (indent !== -1 && indent < this.indentNext && line[0] !== "#" || indent === 0 && (line.startsWith("---") || line.startsWith("...")) && isEmpty(line[3])) {
837      const atFlowEndMarker = indent === this.indentNext - 1 && this.flowLevel === 1 && (line[0] === "]" || line[0] === "}");
838      if (!atFlowEndMarker) {
839        this.flowLevel = 0;
840        yield FLOW_END;
841        return yield* this.parseLineStart();
842      }
843    }
844    let n = 0;
845    while (line[n] === ",") {
846      n += yield* this.pushCount(1);
847      n += yield* this.pushSpaces(true);
848      this.flowKey = false;
849    }
850    n += yield* this.pushIndicators();
851    switch (line[n]) {
852      case void 0:
853        return "flow";
854      case "#":
855        yield* this.pushCount(line.length - n);
856        return "flow";
857      case "{":
858      case "[":
859        yield* this.pushCount(1);
860        this.flowKey = false;
861        this.flowLevel += 1;
862        return "flow";
863      case "}":
864      case "]":
865        yield* this.pushCount(1);
866        this.flowKey = true;
867        this.flowLevel -= 1;
868        return this.flowLevel ? "flow" : "doc";
869      case "*":
870        yield* this.pushUntil(isNotAnchorChar);
871        return "flow";
872      case '"':
873      case "'":
874        this.flowKey = true;
875        return yield* this.parseQuotedScalar();
876      case ":": {
877        const next = this.charAt(1);
878        if (this.flowKey || isEmpty(next) || next === ",") {
879          this.flowKey = false;
880          yield* this.pushCount(1);
881          yield* this.pushSpaces(true);
882          return "flow";
883        }
884      }
885      default:
886        this.flowKey = false;
887        return yield* this.parsePlainScalar();
888    }
889  }
890  *parseQuotedScalar() {
891    const quote = this.charAt(0);
892    let end = this.buffer.indexOf(quote, this.pos + 1);
893    if (quote === "'") {
894      while (end !== -1 && this.buffer[end + 1] === "'")
895        end = this.buffer.indexOf("'", end + 2);
896    } else {
897      while (end !== -1) {
898        let n = 0;
899        while (this.buffer[end - 1 - n] === "\\")
900          n += 1;
901        if (n % 2 === 0)
902          break;
903        end = this.buffer.indexOf('"', end + 1);
904      }
905    }
906    const qb = this.buffer.substring(0, end);
907    let nl = qb.indexOf("\n", this.pos);
908    if (nl !== -1) {
909      while (nl !== -1) {
910        const cs = this.continueScalar(nl + 1);
911        if (cs === -1)
912          break;
913        nl = qb.indexOf("\n", cs);
914      }
915      if (nl !== -1) {
916        end = nl - (qb[nl - 1] === "\r" ? 2 : 1);
917      }
918    }
919    if (end === -1) {
920      if (!this.atEnd)
921        return this.setNext("quoted-scalar");
922      end = this.buffer.length;
923    }
924    yield* this.pushToIndex(end + 1, false);
925    return this.flowLevel ? "flow" : "doc";
926  }
927  *parseBlockScalarHeader() {
928    this.blockScalarIndent = -1;
929    this.blockScalarKeep = false;
930    let i = this.pos;
931    while (true) {
932      const ch = this.buffer[++i];
933      if (ch === "+")
934        this.blockScalarKeep = true;
935      else if (ch > "0" && ch <= "9")
936        this.blockScalarIndent = Number(ch) - 1;
937      else if (ch !== "-")
938        break;
939    }
940    return yield* this.pushUntil((ch) => isEmpty(ch) || ch === "#");
941  }
942  *parseBlockScalar() {
943    let nl = this.pos - 1;
944    let indent = 0;
945    let ch;
946    loop: for (let i2 = this.pos; ch = this.buffer[i2]; ++i2) {
947      switch (ch) {
948        case " ":
949          indent += 1;
950          break;
951        case "\n":
952          nl = i2;
953          indent = 0;
954          break;
955        case "\r": {
956          const next = this.buffer[i2 + 1];
957          if (!next && !this.atEnd)
958            return this.setNext("block-scalar");
959          if (next === "\n")
960            break;
961        }
962        default:
963          break loop;
964      }
965    }
966    if (!ch && !this.atEnd)
967      return this.setNext("block-scalar");
968    if (indent >= this.indentNext) {
969      if (this.blockScalarIndent === -1)
970        this.indentNext = indent;
971      else {
972        this.indentNext = this.blockScalarIndent + (this.indentNext === 0 ? 1 : this.indentNext);
973      }
974      do {
975        const cs = this.continueScalar(nl + 1);
976        if (cs === -1)
977          break;
978        nl = this.buffer.indexOf("\n", cs);
979      } while (nl !== -1);
980      if (nl === -1) {
981        if (!this.atEnd)
982          return this.setNext("block-scalar");
983        nl = this.buffer.length;
984      }
985    }
986    let i = nl + 1;
987    ch = this.buffer[i];
988    while (ch === " ")
989      ch = this.buffer[++i];
990    if (ch === "	") {
991      while (ch === "	" || ch === " " || ch === "\r" || ch === "\n")
992        ch = this.buffer[++i];
993      nl = i - 1;
994    } else if (!this.blockScalarKeep) {
995      do {
996        let i2 = nl - 1;
997        let ch2 = this.buffer[i2];
998        if (ch2 === "\r")
999          ch2 = this.buffer[--i2];
1000        const lastChar = i2;
1001        while (ch2 === " ")
1002          ch2 = this.buffer[--i2];
1003        if (ch2 === "\n" && i2 >= this.pos && i2 + 1 + indent > lastChar)
1004          nl = i2;
1005        else
1006          break;
1007      } while (true);
1008    }
1009    yield SCALAR;
1010    yield* this.pushToIndex(nl + 1, true);
1011    return yield* this.parseLineStart();
1012  }
1013  *parsePlainScalar() {
1014    const inFlow = this.flowLevel > 0;
1015    let end = this.pos - 1;
1016    let i = this.pos - 1;
1017    let ch;
1018    while (ch = this.buffer[++i]) {
1019      if (ch === ":") {
1020        const next = this.buffer[i + 1];
1021        if (isEmpty(next) || inFlow && flowIndicatorChars.has(next))
1022          break;
1023        end = i;
1024      } else if (isEmpty(ch)) {
1025        let next = this.buffer[i + 1];
1026        if (ch === "\r") {
1027          if (next === "\n") {
1028            i += 1;
1029            ch = "\n";
1030            next = this.buffer[i + 1];
1031          } else
1032            end = i;
1033        }
1034        if (next === "#" || inFlow && flowIndicatorChars.has(next))
1035          break;
1036        if (ch === "\n") {
1037          const cs = this.continueScalar(i + 1);
1038          if (cs === -1)
1039            break;
1040          i = Math.max(i, cs - 2);
1041        }
1042      } else {
1043        if (inFlow && flowIndicatorChars.has(ch))
1044          break;
1045        end = i;
1046      }
1047    }
1048    if (!ch && !this.atEnd)
1049      return this.setNext("plain-scalar");
1050    yield SCALAR;
1051    yield* this.pushToIndex(end + 1, true);
1052    return inFlow ? "flow" : "doc";
1053  }
1054  *pushCount(n) {
1055    if (n > 0) {
1056      yield this.buffer.substr(this.pos, n);
1057      this.pos += n;
1058      return n;
1059    }
1060    return 0;
1061  }
1062  *pushToIndex(i, allowEmpty) {
1063    const s = this.buffer.slice(this.pos, i);
1064    if (s) {
1065      yield s;
1066      this.pos += s.length;
1067      return s.length;
1068    } else if (allowEmpty)
1069      yield "";
1070    return 0;
1071  }
1072  *pushIndicators() {
1073    let n = 0;
1074    loop: while (true) {
1075      switch (this.charAt(0)) {
1076        case "!":
1077          n += yield* this.pushTag();
1078          n += yield* this.pushSpaces(true);
1079          continue loop;
1080        case "&":
1081          n += yield* this.pushUntil(isNotAnchorChar);
1082          n += yield* this.pushSpaces(true);
1083          continue loop;
1084        case "-":
1085        case "?":
1086        case ":": {
1087          const inFlow = this.flowLevel > 0;
1088          const ch1 = this.charAt(1);
1089          if (isEmpty(ch1) || inFlow && flowIndicatorChars.has(ch1)) {
1090            if (!inFlow)
1091              this.indentNext = this.indentValue + 1;
1092            else if (this.flowKey)
1093              this.flowKey = false;
1094            n += yield* this.pushCount(1);
1095            n += yield* this.pushSpaces(true);
1096            continue loop;
1097          }
1098        }
1099      }
1100      break loop;
1101    }
1102    return n;
1103  }
1104  *pushTag() {
1105    if (this.charAt(1) === "<") {
1106      let i = this.pos + 2;
1107      let ch = this.buffer[i];
1108      while (!isEmpty(ch) && ch !== ">")
1109        ch = this.buffer[++i];
1110      return yield* this.pushToIndex(ch === ">" ? i + 1 : i, false);
1111    } else {
1112      let i = this.pos + 1;
1113      let ch = this.buffer[i];
1114      while (ch) {
1115        if (tagChars.has(ch))
1116          ch = this.buffer[++i];
1117        else if (ch === "%" && hexDigits.has(this.buffer[i + 1]) && hexDigits.has(this.buffer[i + 2])) {
1118          ch = this.buffer[i += 3];
1119        } else
1120          break;
1121      }
1122      return yield* this.pushToIndex(i, false);
1123    }
1124  }
1125  *pushNewline() {
1126    const ch = this.buffer[this.pos];
1127    if (ch === "\n")
1128      return yield* this.pushCount(1);
1129    else if (ch === "\r" && this.charAt(1) === "\n")
1130      return yield* this.pushCount(2);
1131    else
1132      return 0;
1133  }
1134  *pushSpaces(allowTabs) {
1135    let i = this.pos - 1;
1136    let ch;
1137    do {
1138      ch = this.buffer[++i];
1139    } while (ch === " " || allowTabs && ch === "	");
1140    const n = i - this.pos;
1141    if (n > 0) {
1142      yield this.buffer.substr(this.pos, n);
1143      this.pos = i;
1144    }
1145    return n;
1146  }
1147  *pushUntil(test) {
1148    let i = this.pos;
1149    let ch = this.buffer[i];
1150    while (!test(ch))
1151      ch = this.buffer[++i];
1152    return yield* this.pushToIndex(i, false);
1153  }
1154};
1155
1156function includesToken(list, type) {
1157  for (let i = 0; i < list.length; ++i)
1158    if (list[i].type === type)
1159      return true;
1160  return false;
1161}
1162function findNonEmptyIndex(list) {
1163  for (let i = 0; i < list.length; ++i) {
1164    switch (list[i].type) {
1165      case "space":
1166      case "comment":
1167      case "newline":
1168        break;
1169      default:
1170        return i;
1171    }
1172  }
1173  return -1;
1174}
1175function isFlowToken(token) {
1176  switch (token?.type) {
1177    case "alias":
1178    case "scalar":
1179    case "single-quoted-scalar":
1180    case "double-quoted-scalar":
1181    case "flow-collection":
1182      return true;
1183    default:
1184      return false;
1185  }
1186}
1187function getPrevProps(parent) {
1188  switch (parent.type) {
1189    case "document":
1190      return parent.start;
1191    case "block-map": {
1192      const it = parent.items[parent.items.length - 1];
1193      return it.sep ?? it.start;
1194    }
1195    case "block-seq":
1196      return parent.items[parent.items.length - 1].start;
1197    default:
1198      return [];
1199  }
1200}
skills/plain-english/scripts/core/chunk-IKH6G3OL.mjs 4639 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2import {
3  characterEntities
4} from "./chunk-KWWQFVSE.mjs";
5import {
6  asciiAlpha,
7  asciiAlphanumeric,
8  asciiAtext,
9  asciiControl,
10  asciiDigit,
11  asciiHexDigit,
12  asciiPunctuation,
13  factorySpace,
14  markdownLineEnding,
15  markdownLineEndingOrSpace,
16  markdownSpace,
17  unicodePunctuation,
18  unicodeWhitespace
19} from "./chunk-UGEYTODJ.mjs";
20
21var emptyOptions = {};
22function toString(value, options) {
23  const settings = options || emptyOptions;
24  const includeImageAlt = typeof settings.includeImageAlt === "boolean" ? settings.includeImageAlt : true;
25  const includeHtml = typeof settings.includeHtml === "boolean" ? settings.includeHtml : true;
26  return one(value, includeImageAlt, includeHtml);
27}
28function one(value, includeImageAlt, includeHtml) {
29  if (node(value)) {
30    if ("value" in value) {
31      return value.type === "html" && !includeHtml ? "" : value.value;
32    }
33    if (includeImageAlt && "alt" in value && value.alt) {
34      return value.alt;
35    }
36    if ("children" in value) {
37      return all(value.children, includeImageAlt, includeHtml);
38    }
39  }
40  if (Array.isArray(value)) {
41    return all(value, includeImageAlt, includeHtml);
42  }
43  return "";
44}
45function all(values, includeImageAlt, includeHtml) {
46  const result = [];
47  let index2 = -1;
48  while (++index2 < values.length) {
49    result[index2] = one(values[index2], includeImageAlt, includeHtml);
50  }
51  return result.join("");
52}
53function node(value) {
54  return Boolean(value && typeof value === "object");
55}
56
57var own = {}.hasOwnProperty;
58function decodeNamedCharacterReference(value) {
59  return own.call(characterEntities, value) ? characterEntities[value] : false;
60}
61
62function splice(list2, start, remove, items) {
63  const end = list2.length;
64  let chunkStart = 0;
65  let parameters;
66  if (start < 0) {
67    start = -start > end ? 0 : end + start;
68  } else {
69    start = start > end ? end : start;
70  }
71  remove = remove > 0 ? remove : 0;
72  if (items.length < 1e4) {
73    parameters = Array.from(items);
74    parameters.unshift(start, remove);
75    list2.splice(...parameters);
76  } else {
77    if (remove) list2.splice(start, remove);
78    while (chunkStart < items.length) {
79      parameters = items.slice(chunkStart, chunkStart + 1e4);
80      parameters.unshift(start, 0);
81      list2.splice(...parameters);
82      chunkStart += 1e4;
83      start += 1e4;
84    }
85  }
86}
87function push(list2, items) {
88  if (list2.length > 0) {
89    splice(list2, list2.length, 0, items);
90    return list2;
91  }
92  return items;
93}
94
95var hasOwnProperty = {}.hasOwnProperty;
96function combineExtensions(extensions) {
97  const all2 = {};
98  let index2 = -1;
99  while (++index2 < extensions.length) {
100    syntaxExtension(all2, extensions[index2]);
101  }
102  return all2;
103}
104function syntaxExtension(all2, extension2) {
105  let hook;
106  for (hook in extension2) {
107    const maybe = hasOwnProperty.call(all2, hook) ? all2[hook] : void 0;
108    const left = maybe || (all2[hook] = {});
109    const right = extension2[hook];
110    let code;
111    if (right) {
112      for (code in right) {
113        if (!hasOwnProperty.call(left, code)) left[code] = [];
114        const value = right[code];
115        constructs(
116          left[code],
117          Array.isArray(value) ? value : value ? [value] : []
118        );
119      }
120    }
121  }
122}
123function constructs(existing, list2) {
124  let index2 = -1;
125  const before = [];
126  while (++index2 < list2.length) {
127    ;
128    (list2[index2].add === "after" ? existing : before).push(list2[index2]);
129  }
130  splice(existing, 0, 0, before);
131}
132
133function decodeNumericCharacterReference(value, base) {
134  const code = Number.parseInt(value, base);
135  if (
136    code < 9 || code === 11 || code > 13 && code < 32 ||  
137    code > 126 && code < 160 ||  
138    code > 55295 && code < 57344 ||  
139    code > 64975 && code < 65008 ||  
140    (code & 65535) === 65535 || (code & 65535) === 65534 ||  
141    code > 1114111
142  ) {
143    return "\uFFFD";
144  }
145  return String.fromCodePoint(code);
146}
147
148function normalizeIdentifier(value) {
149  return value.replace(/[\t\n\r ]+/g, " ").replace(/^ | $/g, "").toLowerCase().toUpperCase();
150}
151
152var content = {
153  tokenize: initializeContent
154};
155function initializeContent(effects) {
156  const contentStart = effects.attempt(this.parser.constructs.contentInitial, afterContentStartConstruct, paragraphInitial);
157  let previous2;
158  return contentStart;
159  function afterContentStartConstruct(code) {
160    if (code === null) {
161      effects.consume(code);
162      return;
163    }
164    effects.enter("lineEnding");
165    effects.consume(code);
166    effects.exit("lineEnding");
167    return factorySpace(effects, contentStart, "linePrefix");
168  }
169  function paragraphInitial(code) {
170    effects.enter("paragraph");
171    return lineStart(code);
172  }
173  function lineStart(code) {
174    const token = effects.enter("chunkText", {
175      contentType: "text",
176      previous: previous2
177    });
178    if (previous2) {
179      previous2.next = token;
180    }
181    previous2 = token;
182    return data(code);
183  }
184  function data(code) {
185    if (code === null) {
186      effects.exit("chunkText");
187      effects.exit("paragraph");
188      effects.consume(code);
189      return;
190    }
191    if (markdownLineEnding(code)) {
192      effects.consume(code);
193      effects.exit("chunkText");
194      return lineStart;
195    }
196    effects.consume(code);
197    return data;
198  }
199}
200
201var document = {
202  tokenize: initializeDocument
203};
204var containerConstruct = {
205  tokenize: tokenizeContainer
206};
207function initializeDocument(effects) {
208  const self = this;
209  const stack = [];
210  let continued = 0;
211  let childFlow;
212  let childToken;
213  let lineStartOffset;
214  return start;
215  function start(code) {
216    if (continued < stack.length) {
217      const item = stack[continued];
218      self.containerState = item[1];
219      return effects.attempt(item[0].continuation, documentContinue, checkNewContainers)(code);
220    }
221    return checkNewContainers(code);
222  }
223  function documentContinue(code) {
224    continued++;
225    if (self.containerState._closeFlow) {
226      self.containerState._closeFlow = void 0;
227      if (childFlow) {
228        closeFlow();
229      }
230      const indexBeforeExits = self.events.length;
231      let indexBeforeFlow = indexBeforeExits;
232      let point3;
233      while (indexBeforeFlow--) {
234        if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") {
235          point3 = self.events[indexBeforeFlow][1].end;
236          break;
237        }
238      }
239      exitContainers(continued);
240      let index2 = indexBeforeExits;
241      while (index2 < self.events.length) {
242        self.events[index2][1].end = {
243          ...point3
244        };
245        index2++;
246      }
247      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));
248      self.events.length = index2;
249      return checkNewContainers(code);
250    }
251    return start(code);
252  }
253  function checkNewContainers(code) {
254    if (continued === stack.length) {
255      if (!childFlow) {
256        return documentContinued(code);
257      }
258      if (childFlow.currentConstruct && childFlow.currentConstruct.concrete) {
259        return flowStart(code);
260      }
261      self.interrupt = Boolean(childFlow.currentConstruct && !childFlow._gfmTableDynamicInterruptHack);
262    }
263    self.containerState = {};
264    return effects.check(containerConstruct, thereIsANewContainer, thereIsNoNewContainer)(code);
265  }
266  function thereIsANewContainer(code) {
267    if (childFlow) closeFlow();
268    exitContainers(continued);
269    return documentContinued(code);
270  }
271  function thereIsNoNewContainer(code) {
272    self.parser.lazy[self.now().line] = continued !== stack.length;
273    lineStartOffset = self.now().offset;
274    return flowStart(code);
275  }
276  function documentContinued(code) {
277    self.containerState = {};
278    return effects.attempt(containerConstruct, containerContinue, flowStart)(code);
279  }
280  function containerContinue(code) {
281    continued++;
282    stack.push([self.currentConstruct, self.containerState]);
283    return documentContinued(code);
284  }
285  function flowStart(code) {
286    if (code === null) {
287      if (childFlow) closeFlow();
288      exitContainers(0);
289      effects.consume(code);
290      return;
291    }
292    childFlow = childFlow || self.parser.flow(self.now());
293    effects.enter("chunkFlow", {
294      _tokenizer: childFlow,
295      contentType: "flow",
296      previous: childToken
297    });
298    return flowContinue(code);
299  }
300  function flowContinue(code) {
301    if (code === null) {
302      writeToChild(effects.exit("chunkFlow"), true);
303      exitContainers(0);
304      effects.consume(code);
305      return;
306    }
307    if (markdownLineEnding(code)) {
308      effects.consume(code);
309      writeToChild(effects.exit("chunkFlow"));
310      continued = 0;
311      self.interrupt = void 0;
312      return start;
313    }
314    effects.consume(code);
315    return flowContinue;
316  }
317  function writeToChild(token, endOfFile) {
318    const stream = self.sliceStream(token);
319    if (endOfFile) stream.push(null);
320    token.previous = childToken;
321    if (childToken) childToken.next = token;
322    childToken = token;
323    childFlow.defineSkip(token.start);
324    childFlow.write(stream);
325    if (self.parser.lazy[token.start.line]) {
326      let index2 = childFlow.events.length;
327      while (index2--) {
328        if (
329          childFlow.events[index2][1].start.offset < lineStartOffset &&  
330          (!childFlow.events[index2][1].end ||  
331          childFlow.events[index2][1].end.offset > lineStartOffset)
332        ) {
333          return;
334        }
335      }
336      const indexBeforeExits = self.events.length;
337      let indexBeforeFlow = indexBeforeExits;
338      let seen;
339      let point3;
340      while (indexBeforeFlow--) {
341        if (self.events[indexBeforeFlow][0] === "exit" && self.events[indexBeforeFlow][1].type === "chunkFlow") {
342          if (seen) {
343            point3 = self.events[indexBeforeFlow][1].end;
344            break;
345          }
346          seen = true;
347        }
348      }
349      exitContainers(continued);
350      index2 = indexBeforeExits;
351      while (index2 < self.events.length) {
352        self.events[index2][1].end = {
353          ...point3
354        };
355        index2++;
356      }
357      splice(self.events, indexBeforeFlow + 1, 0, self.events.slice(indexBeforeExits));
358      self.events.length = index2;
359    }
360  }
361  function exitContainers(size) {
362    let index2 = stack.length;
363    while (index2-- > size) {
364      const entry = stack[index2];
365      self.containerState = entry[1];
366      entry[0].exit.call(self, effects);
367    }
368    stack.length = size;
369  }
370  function closeFlow() {
371    childFlow.write([null]);
372    childToken = void 0;
373    childFlow = void 0;
374    self.containerState._closeFlow = void 0;
375  }
376}
377function tokenizeContainer(effects, ok, nok) {
378  return factorySpace(effects, effects.attempt(this.parser.constructs.document, ok, nok), "linePrefix", this.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4);
379}
380
381function classifyCharacter(code) {
382  if (code === null || markdownLineEndingOrSpace(code) || unicodeWhitespace(code)) {
383    return 1;
384  }
385  if (unicodePunctuation(code)) {
386    return 2;
387  }
388}
389
390function resolveAll(constructs2, events, context) {
391  const called = [];
392  let index2 = -1;
393  while (++index2 < constructs2.length) {
394    const resolve = constructs2[index2].resolveAll;
395    if (resolve && !called.includes(resolve)) {
396      events = resolve(events, context);
397      called.push(resolve);
398    }
399  }
400  return events;
401}
402
403var attention = {
404  name: "attention",
405  resolveAll: resolveAllAttention,
406  tokenize: tokenizeAttention
407};
408function resolveAllAttention(events, context) {
409  let index2 = -1;
410  let open;
411  let group;
412  let text3;
413  let openingSequence;
414  let closingSequence;
415  let use;
416  let nextEvents;
417  let offset;
418  while (++index2 < events.length) {
419    if (events[index2][0] === "enter" && events[index2][1].type === "attentionSequence" && events[index2][1]._close) {
420      open = index2;
421      while (open--) {
422        if (events[open][0] === "exit" && events[open][1].type === "attentionSequence" && events[open][1]._open &&  
423        context.sliceSerialize(events[open][1]).charCodeAt(0) === context.sliceSerialize(events[index2][1]).charCodeAt(0)) {
424          if ((events[open][1]._close || events[index2][1]._open) && (events[index2][1].end.offset - events[index2][1].start.offset) % 3 && !((events[open][1].end.offset - events[open][1].start.offset + events[index2][1].end.offset - events[index2][1].start.offset) % 3)) {
425            continue;
426          }
427          use = events[open][1].end.offset - events[open][1].start.offset > 1 && events[index2][1].end.offset - events[index2][1].start.offset > 1 ? 2 : 1;
428          const start = {
429            ...events[open][1].end
430          };
431          const end = {
432            ...events[index2][1].start
433          };
434          movePoint(start, -use);
435          movePoint(end, use);
436          openingSequence = {
437            type: use > 1 ? "strongSequence" : "emphasisSequence",
438            start,
439            end: {
440              ...events[open][1].end
441            }
442          };
443          closingSequence = {
444            type: use > 1 ? "strongSequence" : "emphasisSequence",
445            start: {
446              ...events[index2][1].start
447            },
448            end
449          };
450          text3 = {
451            type: use > 1 ? "strongText" : "emphasisText",
452            start: {
453              ...events[open][1].end
454            },
455            end: {
456              ...events[index2][1].start
457            }
458          };
459          group = {
460            type: use > 1 ? "strong" : "emphasis",
461            start: {
462              ...openingSequence.start
463            },
464            end: {
465              ...closingSequence.end
466            }
467          };
468          events[open][1].end = {
469            ...openingSequence.start
470          };
471          events[index2][1].start = {
472            ...closingSequence.end
473          };
474          nextEvents = [];
475          if (events[open][1].end.offset - events[open][1].start.offset) {
476            nextEvents = push(nextEvents, [["enter", events[open][1], context], ["exit", events[open][1], context]]);
477          }
478          nextEvents = push(nextEvents, [["enter", group, context], ["enter", openingSequence, context], ["exit", openingSequence, context], ["enter", text3, context]]);
479          nextEvents = push(nextEvents, resolveAll(context.parser.constructs.insideSpan.null, events.slice(open + 1, index2), context));
480          nextEvents = push(nextEvents, [["exit", text3, context], ["enter", closingSequence, context], ["exit", closingSequence, context], ["exit", group, context]]);
481          if (events[index2][1].end.offset - events[index2][1].start.offset) {
482            offset = 2;
483            nextEvents = push(nextEvents, [["enter", events[index2][1], context], ["exit", events[index2][1], context]]);
484          } else {
485            offset = 0;
486          }
487          splice(events, open - 1, index2 - open + 3, nextEvents);
488          index2 = open + nextEvents.length - offset - 2;
489          break;
490        }
491      }
492    }
493  }
494  index2 = -1;
495  while (++index2 < events.length) {
496    if (events[index2][1].type === "attentionSequence") {
497      events[index2][1].type = "data";
498    }
499  }
500  return events;
501}
502function tokenizeAttention(effects, ok) {
503  const attentionMarkers2 = this.parser.constructs.attentionMarkers.null;
504  const previous2 = this.previous;
505  const before = classifyCharacter(previous2);
506  let marker;
507  return start;
508  function start(code) {
509    marker = code;
510    effects.enter("attentionSequence");
511    return inside(code);
512  }
513  function inside(code) {
514    if (code === marker) {
515      effects.consume(code);
516      return inside;
517    }
518    const token = effects.exit("attentionSequence");
519    const after = classifyCharacter(code);
520    const open = !after || after === 2 && before || attentionMarkers2.includes(code);
521    const close = !before || before === 2 && after || attentionMarkers2.includes(previous2);
522    token._open = Boolean(marker === 42 ? open : open && (before || !close));
523    token._close = Boolean(marker === 42 ? close : close && (after || !open));
524    return ok(code);
525  }
526}
527function movePoint(point3, offset) {
528  point3.column += offset;
529  point3.offset += offset;
530  point3._bufferIndex += offset;
531}
532
533var autolink = {
534  name: "autolink",
535  tokenize: tokenizeAutolink
536};
537function tokenizeAutolink(effects, ok, nok) {
538  let size = 0;
539  return start;
540  function start(code) {
541    effects.enter("autolink");
542    effects.enter("autolinkMarker");
543    effects.consume(code);
544    effects.exit("autolinkMarker");
545    effects.enter("autolinkProtocol");
546    return open;
547  }
548  function open(code) {
549    if (asciiAlpha(code)) {
550      effects.consume(code);
551      return schemeOrEmailAtext;
552    }
553    if (code === 64) {
554      return nok(code);
555    }
556    return emailAtext(code);
557  }
558  function schemeOrEmailAtext(code) {
559    if (code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) {
560      size = 1;
561      return schemeInsideOrEmailAtext(code);
562    }
563    return emailAtext(code);
564  }
565  function schemeInsideOrEmailAtext(code) {
566    if (code === 58) {
567      effects.consume(code);
568      size = 0;
569      return urlInside;
570    }
571    if ((code === 43 || code === 45 || code === 46 || asciiAlphanumeric(code)) && size++ < 32) {
572      effects.consume(code);
573      return schemeInsideOrEmailAtext;
574    }
575    size = 0;
576    return emailAtext(code);
577  }
578  function urlInside(code) {
579    if (code === 62) {
580      effects.exit("autolinkProtocol");
581      effects.enter("autolinkMarker");
582      effects.consume(code);
583      effects.exit("autolinkMarker");
584      effects.exit("autolink");
585      return ok;
586    }
587    if (code === null || code === 32 || code === 60 || asciiControl(code)) {
588      return nok(code);
589    }
590    effects.consume(code);
591    return urlInside;
592  }
593  function emailAtext(code) {
594    if (code === 64) {
595      effects.consume(code);
596      return emailAtSignOrDot;
597    }
598    if (asciiAtext(code)) {
599      effects.consume(code);
600      return emailAtext;
601    }
602    return nok(code);
603  }
604  function emailAtSignOrDot(code) {
605    return asciiAlphanumeric(code) ? emailLabel(code) : nok(code);
606  }
607  function emailLabel(code) {
608    if (code === 46) {
609      effects.consume(code);
610      size = 0;
611      return emailAtSignOrDot;
612    }
613    if (code === 62) {
614      effects.exit("autolinkProtocol").type = "autolinkEmail";
615      effects.enter("autolinkMarker");
616      effects.consume(code);
617      effects.exit("autolinkMarker");
618      effects.exit("autolink");
619      return ok;
620    }
621    return emailValue(code);
622  }
623  function emailValue(code) {
624    if ((code === 45 || asciiAlphanumeric(code)) && size++ < 63) {
625      const next = code === 45 ? emailValue : emailLabel;
626      effects.consume(code);
627      return next;
628    }
629    return nok(code);
630  }
631}
632
633var blankLine = {
634  partial: true,
635  tokenize: tokenizeBlankLine
636};
637function tokenizeBlankLine(effects, ok, nok) {
638  return start;
639  function start(code) {
640    return markdownSpace(code) ? factorySpace(effects, after, "linePrefix")(code) : after(code);
641  }
642  function after(code) {
643    return code === null || markdownLineEnding(code) ? ok(code) : nok(code);
644  }
645}
646
647var blockQuote = {
648  continuation: {
649    tokenize: tokenizeBlockQuoteContinuation
650  },
651  exit,
652  name: "blockQuote",
653  tokenize: tokenizeBlockQuoteStart
654};
655function tokenizeBlockQuoteStart(effects, ok, nok) {
656  const self = this;
657  return start;
658  function start(code) {
659    if (code === 62) {
660      const state = self.containerState;
661      if (!state.open) {
662        effects.enter("blockQuote", {
663          _container: true
664        });
665        state.open = true;
666      }
667      effects.enter("blockQuotePrefix");
668      effects.enter("blockQuoteMarker");
669      effects.consume(code);
670      effects.exit("blockQuoteMarker");
671      return after;
672    }
673    return nok(code);
674  }
675  function after(code) {
676    if (markdownSpace(code)) {
677      effects.enter("blockQuotePrefixWhitespace");
678      effects.consume(code);
679      effects.exit("blockQuotePrefixWhitespace");
680      effects.exit("blockQuotePrefix");
681      return ok;
682    }
683    effects.exit("blockQuotePrefix");
684    return ok(code);
685  }
686}
687function tokenizeBlockQuoteContinuation(effects, ok, nok) {
688  const self = this;
689  return contStart;
690  function contStart(code) {
691    if (markdownSpace(code)) {
692      return factorySpace(effects, contBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code);
693    }
694    return contBefore(code);
695  }
696  function contBefore(code) {
697    return effects.attempt(blockQuote, ok, nok)(code);
698  }
699}
700function exit(effects) {
701  effects.exit("blockQuote");
702}
703
704var characterEscape = {
705  name: "characterEscape",
706  tokenize: tokenizeCharacterEscape
707};
708function tokenizeCharacterEscape(effects, ok, nok) {
709  return start;
710  function start(code) {
711    effects.enter("characterEscape");
712    effects.enter("escapeMarker");
713    effects.consume(code);
714    effects.exit("escapeMarker");
715    return inside;
716  }
717  function inside(code) {
718    if (asciiPunctuation(code)) {
719      effects.enter("characterEscapeValue");
720      effects.consume(code);
721      effects.exit("characterEscapeValue");
722      effects.exit("characterEscape");
723      return ok;
724    }
725    return nok(code);
726  }
727}
728
729var characterReference = {
730  name: "characterReference",
731  tokenize: tokenizeCharacterReference
732};
733function tokenizeCharacterReference(effects, ok, nok) {
734  const self = this;
735  let size = 0;
736  let max;
737  let test;
738  return start;
739  function start(code) {
740    effects.enter("characterReference");
741    effects.enter("characterReferenceMarker");
742    effects.consume(code);
743    effects.exit("characterReferenceMarker");
744    return open;
745  }
746  function open(code) {
747    if (code === 35) {
748      effects.enter("characterReferenceMarkerNumeric");
749      effects.consume(code);
750      effects.exit("characterReferenceMarkerNumeric");
751      return numeric;
752    }
753    effects.enter("characterReferenceValue");
754    max = 31;
755    test = asciiAlphanumeric;
756    return value(code);
757  }
758  function numeric(code) {
759    if (code === 88 || code === 120) {
760      effects.enter("characterReferenceMarkerHexadecimal");
761      effects.consume(code);
762      effects.exit("characterReferenceMarkerHexadecimal");
763      effects.enter("characterReferenceValue");
764      max = 6;
765      test = asciiHexDigit;
766      return value;
767    }
768    effects.enter("characterReferenceValue");
769    max = 7;
770    test = asciiDigit;
771    return value(code);
772  }
773  function value(code) {
774    if (code === 59 && size) {
775      const token = effects.exit("characterReferenceValue");
776      if (test === asciiAlphanumeric && !decodeNamedCharacterReference(self.sliceSerialize(token))) {
777        return nok(code);
778      }
779      effects.enter("characterReferenceMarker");
780      effects.consume(code);
781      effects.exit("characterReferenceMarker");
782      effects.exit("characterReference");
783      return ok;
784    }
785    if (test(code) && size++ < max) {
786      effects.consume(code);
787      return value;
788    }
789    return nok(code);
790  }
791}
792
793var nonLazyContinuation = {
794  partial: true,
795  tokenize: tokenizeNonLazyContinuation
796};
797var codeFenced = {
798  concrete: true,
799  name: "codeFenced",
800  tokenize: tokenizeCodeFenced
801};
802function tokenizeCodeFenced(effects, ok, nok) {
803  const self = this;
804  const closeStart = {
805    partial: true,
806    tokenize: tokenizeCloseStart
807  };
808  let initialPrefix = 0;
809  let sizeOpen = 0;
810  let marker;
811  return start;
812  function start(code) {
813    return beforeSequenceOpen(code);
814  }
815  function beforeSequenceOpen(code) {
816    const tail = self.events[self.events.length - 1];
817    initialPrefix = tail && tail[1].type === "linePrefix" ? tail[2].sliceSerialize(tail[1], true).length : 0;
818    marker = code;
819    effects.enter("codeFenced");
820    effects.enter("codeFencedFence");
821    effects.enter("codeFencedFenceSequence");
822    return sequenceOpen(code);
823  }
824  function sequenceOpen(code) {
825    if (code === marker) {
826      sizeOpen++;
827      effects.consume(code);
828      return sequenceOpen;
829    }
830    if (sizeOpen < 3) {
831      return nok(code);
832    }
833    effects.exit("codeFencedFenceSequence");
834    return markdownSpace(code) ? factorySpace(effects, infoBefore, "whitespace")(code) : infoBefore(code);
835  }
836  function infoBefore(code) {
837    if (code === null || markdownLineEnding(code)) {
838      effects.exit("codeFencedFence");
839      return self.interrupt ? ok(code) : effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);
840    }
841    effects.enter("codeFencedFenceInfo");
842    effects.enter("chunkString", {
843      contentType: "string"
844    });
845    return info(code);
846  }
847  function info(code) {
848    if (code === null || markdownLineEnding(code)) {
849      effects.exit("chunkString");
850      effects.exit("codeFencedFenceInfo");
851      return infoBefore(code);
852    }
853    if (markdownSpace(code)) {
854      effects.exit("chunkString");
855      effects.exit("codeFencedFenceInfo");
856      return factorySpace(effects, metaBefore, "whitespace")(code);
857    }
858    if (code === 96 && code === marker) {
859      return nok(code);
860    }
861    effects.consume(code);
862    return info;
863  }
864  function metaBefore(code) {
865    if (code === null || markdownLineEnding(code)) {
866      return infoBefore(code);
867    }
868    effects.enter("codeFencedFenceMeta");
869    effects.enter("chunkString", {
870      contentType: "string"
871    });
872    return meta(code);
873  }
874  function meta(code) {
875    if (code === null || markdownLineEnding(code)) {
876      effects.exit("chunkString");
877      effects.exit("codeFencedFenceMeta");
878      return infoBefore(code);
879    }
880    if (code === 96 && code === marker) {
881      return nok(code);
882    }
883    effects.consume(code);
884    return meta;
885  }
886  function atNonLazyBreak(code) {
887    return effects.attempt(closeStart, after, contentBefore)(code);
888  }
889  function contentBefore(code) {
890    effects.enter("lineEnding");
891    effects.consume(code);
892    effects.exit("lineEnding");
893    return contentStart;
894  }
895  function contentStart(code) {
896    return initialPrefix > 0 && markdownSpace(code) ? factorySpace(effects, beforeContentChunk, "linePrefix", initialPrefix + 1)(code) : beforeContentChunk(code);
897  }
898  function beforeContentChunk(code) {
899    if (code === null || markdownLineEnding(code)) {
900      return effects.check(nonLazyContinuation, atNonLazyBreak, after)(code);
901    }
902    effects.enter("codeFlowValue");
903    return contentChunk(code);
904  }
905  function contentChunk(code) {
906    if (code === null || markdownLineEnding(code)) {
907      effects.exit("codeFlowValue");
908      return beforeContentChunk(code);
909    }
910    effects.consume(code);
911    return contentChunk;
912  }
913  function after(code) {
914    effects.exit("codeFenced");
915    return ok(code);
916  }
917  function tokenizeCloseStart(effects2, ok2, nok2) {
918    let size = 0;
919    return startBefore;
920    function startBefore(code) {
921      effects2.enter("lineEnding");
922      effects2.consume(code);
923      effects2.exit("lineEnding");
924      return start2;
925    }
926    function start2(code) {
927      effects2.enter("codeFencedFence");
928      return markdownSpace(code) ? factorySpace(effects2, beforeSequenceClose, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code) : beforeSequenceClose(code);
929    }
930    function beforeSequenceClose(code) {
931      if (code === marker) {
932        effects2.enter("codeFencedFenceSequence");
933        return sequenceClose(code);
934      }
935      return nok2(code);
936    }
937    function sequenceClose(code) {
938      if (code === marker) {
939        size++;
940        effects2.consume(code);
941        return sequenceClose;
942      }
943      if (size >= sizeOpen) {
944        effects2.exit("codeFencedFenceSequence");
945        return markdownSpace(code) ? factorySpace(effects2, sequenceCloseAfter, "whitespace")(code) : sequenceCloseAfter(code);
946      }
947      return nok2(code);
948    }
949    function sequenceCloseAfter(code) {
950      if (code === null || markdownLineEnding(code)) {
951        effects2.exit("codeFencedFence");
952        return ok2(code);
953      }
954      return nok2(code);
955    }
956  }
957}
958function tokenizeNonLazyContinuation(effects, ok, nok) {
959  const self = this;
960  return start;
961  function start(code) {
962    if (code === null) {
963      return nok(code);
964    }
965    effects.enter("lineEnding");
966    effects.consume(code);
967    effects.exit("lineEnding");
968    return lineStart;
969  }
970  function lineStart(code) {
971    return self.parser.lazy[self.now().line] ? nok(code) : ok(code);
972  }
973}
974
975var codeIndented = {
976  name: "codeIndented",
977  tokenize: tokenizeCodeIndented
978};
979var furtherStart = {
980  partial: true,
981  tokenize: tokenizeFurtherStart
982};
983function tokenizeCodeIndented(effects, ok, nok) {
984  const self = this;
985  return start;
986  function start(code) {
987    effects.enter("codeIndented");
988    return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code);
989  }
990  function afterPrefix(code) {
991    const tail = self.events[self.events.length - 1];
992    return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? atBreak(code) : nok(code);
993  }
994  function atBreak(code) {
995    if (code === null) {
996      return after(code);
997    }
998    if (markdownLineEnding(code)) {
999      return effects.attempt(furtherStart, atBreak, after)(code);
1000    }
1001    effects.enter("codeFlowValue");
1002    return inside(code);
1003  }
1004  function inside(code) {
1005    if (code === null || markdownLineEnding(code)) {
1006      effects.exit("codeFlowValue");
1007      return atBreak(code);
1008    }
1009    effects.consume(code);
1010    return inside;
1011  }
1012  function after(code) {
1013    effects.exit("codeIndented");
1014    return ok(code);
1015  }
1016}
1017function tokenizeFurtherStart(effects, ok, nok) {
1018  const self = this;
1019  return furtherStart2;
1020  function furtherStart2(code) {
1021    if (self.parser.lazy[self.now().line]) {
1022      return nok(code);
1023    }
1024    if (markdownLineEnding(code)) {
1025      effects.enter("lineEnding");
1026      effects.consume(code);
1027      effects.exit("lineEnding");
1028      return furtherStart2;
1029    }
1030    return factorySpace(effects, afterPrefix, "linePrefix", 4 + 1)(code);
1031  }
1032  function afterPrefix(code) {
1033    const tail = self.events[self.events.length - 1];
1034    return tail && tail[1].type === "linePrefix" && tail[2].sliceSerialize(tail[1], true).length >= 4 ? ok(code) : markdownLineEnding(code) ? furtherStart2(code) : nok(code);
1035  }
1036}
1037
1038var codeText = {
1039  name: "codeText",
1040  previous,
1041  resolve: resolveCodeText,
1042  tokenize: tokenizeCodeText
1043};
1044function resolveCodeText(events) {
1045  let tailExitIndex = events.length - 4;
1046  let headEnterIndex = 3;
1047  let index2;
1048  let enter;
1049  if ((events[headEnterIndex][1].type === "lineEnding" || events[headEnterIndex][1].type === "space") && (events[tailExitIndex][1].type === "lineEnding" || events[tailExitIndex][1].type === "space")) {
1050    index2 = headEnterIndex;
1051    while (++index2 < tailExitIndex) {
1052      if (events[index2][1].type === "codeTextData") {
1053        events[headEnterIndex][1].type = "codeTextPadding";
1054        events[tailExitIndex][1].type = "codeTextPadding";
1055        headEnterIndex += 2;
1056        tailExitIndex -= 2;
1057        break;
1058      }
1059    }
1060  }
1061  index2 = headEnterIndex - 1;
1062  tailExitIndex++;
1063  while (++index2 <= tailExitIndex) {
1064    if (enter === void 0) {
1065      if (index2 !== tailExitIndex && events[index2][1].type !== "lineEnding") {
1066        enter = index2;
1067      }
1068    } else if (index2 === tailExitIndex || events[index2][1].type === "lineEnding") {
1069      events[enter][1].type = "codeTextData";
1070      if (index2 !== enter + 2) {
1071        events[enter][1].end = events[index2 - 1][1].end;
1072        events.splice(enter + 2, index2 - enter - 2);
1073        tailExitIndex -= index2 - enter - 2;
1074        index2 = enter + 2;
1075      }
1076      enter = void 0;
1077    }
1078  }
1079  return events;
1080}
1081function previous(code) {
1082  return code !== 96 || this.events[this.events.length - 1][1].type === "characterEscape";
1083}
1084function tokenizeCodeText(effects, ok, nok) {
1085  const self = this;
1086  let sizeOpen = 0;
1087  let size;
1088  let token;
1089  return start;
1090  function start(code) {
1091    effects.enter("codeText");
1092    effects.enter("codeTextSequence");
1093    return sequenceOpen(code);
1094  }
1095  function sequenceOpen(code) {
1096    if (code === 96) {
1097      effects.consume(code);
1098      sizeOpen++;
1099      return sequenceOpen;
1100    }
1101    effects.exit("codeTextSequence");
1102    return between(code);
1103  }
1104  function between(code) {
1105    if (code === null) {
1106      return nok(code);
1107    }
1108    if (code === 32) {
1109      effects.enter("space");
1110      effects.consume(code);
1111      effects.exit("space");
1112      return between;
1113    }
1114    if (code === 96) {
1115      token = effects.enter("codeTextSequence");
1116      size = 0;
1117      return sequenceClose(code);
1118    }
1119    if (markdownLineEnding(code)) {
1120      effects.enter("lineEnding");
1121      effects.consume(code);
1122      effects.exit("lineEnding");
1123      return between;
1124    }
1125    effects.enter("codeTextData");
1126    return data(code);
1127  }
1128  function data(code) {
1129    if (code === null || code === 32 || code === 96 || markdownLineEnding(code)) {
1130      effects.exit("codeTextData");
1131      return between(code);
1132    }
1133    effects.consume(code);
1134    return data;
1135  }
1136  function sequenceClose(code) {
1137    if (code === 96) {
1138      effects.consume(code);
1139      size++;
1140      return sequenceClose;
1141    }
1142    if (size === sizeOpen) {
1143      effects.exit("codeTextSequence");
1144      effects.exit("codeText");
1145      return ok(code);
1146    }
1147    token.type = "codeTextData";
1148    return data(code);
1149  }
1150}
1151
1152var SpliceBuffer = class {
1153  constructor(initial) {
1154    this.left = initial ? [...initial] : [];
1155    this.right = [];
1156  }
1157  get(index2) {
1158    if (index2 < 0 || index2 >= this.left.length + this.right.length) {
1159      throw new RangeError("Cannot access index `" + index2 + "` in a splice buffer of size `" + (this.left.length + this.right.length) + "`");
1160    }
1161    if (index2 < this.left.length) return this.left[index2];
1162    return this.right[this.right.length - index2 + this.left.length - 1];
1163  }
1164  size() {
1165    return this.left.length + this.right.length;
1166  }
1167  shift() {
1168    this.setCursor(0);
1169    return this.right.pop();
1170  }
1171  slice(start, end) {
1172    const stop = end === null || end === void 0 ? Number.POSITIVE_INFINITY : end;
1173    if (stop < this.left.length) {
1174      return this.left.slice(start, stop);
1175    }
1176    if (start > this.left.length) {
1177      return this.right.slice(this.right.length - stop + this.left.length, this.right.length - start + this.left.length).reverse();
1178    }
1179    return this.left.slice(start).concat(this.right.slice(this.right.length - stop + this.left.length).reverse());
1180  }
1181  splice(start, deleteCount, items) {
1182    const count = deleteCount || 0;
1183    this.setCursor(Math.trunc(start));
1184    const removed = this.right.splice(this.right.length - count, Number.POSITIVE_INFINITY);
1185    if (items) chunkedPush(this.left, items);
1186    return removed.reverse();
1187  }
1188  pop() {
1189    this.setCursor(Number.POSITIVE_INFINITY);
1190    return this.left.pop();
1191  }
1192  push(item) {
1193    this.setCursor(Number.POSITIVE_INFINITY);
1194    this.left.push(item);
1195  }
1196  pushMany(items) {
1197    this.setCursor(Number.POSITIVE_INFINITY);
1198    chunkedPush(this.left, items);
1199  }
1200  unshift(item) {
skills/plain-english/scripts/core/chunk-KWWQFVSE.mjs 2133 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2var characterEntities = {
3  AElig: "\xC6",
4  AMP: "&",
5  Aacute: "\xC1",
6  Abreve: "\u0102",
7  Acirc: "\xC2",
8  Acy: "\u0410",
9  Afr: "\u{1D504}",
10  Agrave: "\xC0",
11  Alpha: "\u0391",
12  Amacr: "\u0100",
13  And: "\u2A53",
14  Aogon: "\u0104",
15  Aopf: "\u{1D538}",
16  ApplyFunction: "\u2061",
17  Aring: "\xC5",
18  Ascr: "\u{1D49C}",
19  Assign: "\u2254",
20  Atilde: "\xC3",
21  Auml: "\xC4",
22  Backslash: "\u2216",
23  Barv: "\u2AE7",
24  Barwed: "\u2306",
25  Bcy: "\u0411",
26  Because: "\u2235",
27  Bernoullis: "\u212C",
28  Beta: "\u0392",
29  Bfr: "\u{1D505}",
30  Bopf: "\u{1D539}",
31  Breve: "\u02D8",
32  Bscr: "\u212C",
33  Bumpeq: "\u224E",
34  CHcy: "\u0427",
35  COPY: "\xA9",
36  Cacute: "\u0106",
37  Cap: "\u22D2",
38  CapitalDifferentialD: "\u2145",
39  Cayleys: "\u212D",
40  Ccaron: "\u010C",
41  Ccedil: "\xC7",
42  Ccirc: "\u0108",
43  Cconint: "\u2230",
44  Cdot: "\u010A",
45  Cedilla: "\xB8",
46  CenterDot: "\xB7",
47  Cfr: "\u212D",
48  Chi: "\u03A7",
49  CircleDot: "\u2299",
50  CircleMinus: "\u2296",
51  CirclePlus: "\u2295",
52  CircleTimes: "\u2297",
53  ClockwiseContourIntegral: "\u2232",
54  CloseCurlyDoubleQuote: "\u201D",
55  CloseCurlyQuote: "\u2019",
56  Colon: "\u2237",
57  Colone: "\u2A74",
58  Congruent: "\u2261",
59  Conint: "\u222F",
60  ContourIntegral: "\u222E",
61  Copf: "\u2102",
62  Coproduct: "\u2210",
63  CounterClockwiseContourIntegral: "\u2233",
64  Cross: "\u2A2F",
65  Cscr: "\u{1D49E}",
66  Cup: "\u22D3",
67  CupCap: "\u224D",
68  DD: "\u2145",
69  DDotrahd: "\u2911",
70  DJcy: "\u0402",
71  DScy: "\u0405",
72  DZcy: "\u040F",
73  Dagger: "\u2021",
74  Darr: "\u21A1",
75  Dashv: "\u2AE4",
76  Dcaron: "\u010E",
77  Dcy: "\u0414",
78  Del: "\u2207",
79  Delta: "\u0394",
80  Dfr: "\u{1D507}",
81  DiacriticalAcute: "\xB4",
82  DiacriticalDot: "\u02D9",
83  DiacriticalDoubleAcute: "\u02DD",
84  DiacriticalGrave: "`",
85  DiacriticalTilde: "\u02DC",
86  Diamond: "\u22C4",
87  DifferentialD: "\u2146",
88  Dopf: "\u{1D53B}",
89  Dot: "\xA8",
90  DotDot: "\u20DC",
91  DotEqual: "\u2250",
92  DoubleContourIntegral: "\u222F",
93  DoubleDot: "\xA8",
94  DoubleDownArrow: "\u21D3",
95  DoubleLeftArrow: "\u21D0",
96  DoubleLeftRightArrow: "\u21D4",
97  DoubleLeftTee: "\u2AE4",
98  DoubleLongLeftArrow: "\u27F8",
99  DoubleLongLeftRightArrow: "\u27FA",
100  DoubleLongRightArrow: "\u27F9",
101  DoubleRightArrow: "\u21D2",
102  DoubleRightTee: "\u22A8",
103  DoubleUpArrow: "\u21D1",
104  DoubleUpDownArrow: "\u21D5",
105  DoubleVerticalBar: "\u2225",
106  DownArrow: "\u2193",
107  DownArrowBar: "\u2913",
108  DownArrowUpArrow: "\u21F5",
109  DownBreve: "\u0311",
110  DownLeftRightVector: "\u2950",
111  DownLeftTeeVector: "\u295E",
112  DownLeftVector: "\u21BD",
113  DownLeftVectorBar: "\u2956",
114  DownRightTeeVector: "\u295F",
115  DownRightVector: "\u21C1",
116  DownRightVectorBar: "\u2957",
117  DownTee: "\u22A4",
118  DownTeeArrow: "\u21A7",
119  Downarrow: "\u21D3",
120  Dscr: "\u{1D49F}",
121  Dstrok: "\u0110",
122  ENG: "\u014A",
123  ETH: "\xD0",
124  Eacute: "\xC9",
125  Ecaron: "\u011A",
126  Ecirc: "\xCA",
127  Ecy: "\u042D",
128  Edot: "\u0116",
129  Efr: "\u{1D508}",
130  Egrave: "\xC8",
131  Element: "\u2208",
132  Emacr: "\u0112",
133  EmptySmallSquare: "\u25FB",
134  EmptyVerySmallSquare: "\u25AB",
135  Eogon: "\u0118",
136  Eopf: "\u{1D53C}",
137  Epsilon: "\u0395",
138  Equal: "\u2A75",
139  EqualTilde: "\u2242",
140  Equilibrium: "\u21CC",
141  Escr: "\u2130",
142  Esim: "\u2A73",
143  Eta: "\u0397",
144  Euml: "\xCB",
145  Exists: "\u2203",
146  ExponentialE: "\u2147",
147  Fcy: "\u0424",
148  Ffr: "\u{1D509}",
149  FilledSmallSquare: "\u25FC",
150  FilledVerySmallSquare: "\u25AA",
151  Fopf: "\u{1D53D}",
152  ForAll: "\u2200",
153  Fouriertrf: "\u2131",
154  Fscr: "\u2131",
155  GJcy: "\u0403",
156  GT: ">",
157  Gamma: "\u0393",
158  Gammad: "\u03DC",
159  Gbreve: "\u011E",
160  Gcedil: "\u0122",
161  Gcirc: "\u011C",
162  Gcy: "\u0413",
163  Gdot: "\u0120",
164  Gfr: "\u{1D50A}",
165  Gg: "\u22D9",
166  Gopf: "\u{1D53E}",
167  GreaterEqual: "\u2265",
168  GreaterEqualLess: "\u22DB",
169  GreaterFullEqual: "\u2267",
170  GreaterGreater: "\u2AA2",
171  GreaterLess: "\u2277",
172  GreaterSlantEqual: "\u2A7E",
173  GreaterTilde: "\u2273",
174  Gscr: "\u{1D4A2}",
175  Gt: "\u226B",
176  HARDcy: "\u042A",
177  Hacek: "\u02C7",
178  Hat: "^",
179  Hcirc: "\u0124",
180  Hfr: "\u210C",
181  HilbertSpace: "\u210B",
182  Hopf: "\u210D",
183  HorizontalLine: "\u2500",
184  Hscr: "\u210B",
185  Hstrok: "\u0126",
186  HumpDownHump: "\u224E",
187  HumpEqual: "\u224F",
188  IEcy: "\u0415",
189  IJlig: "\u0132",
190  IOcy: "\u0401",
191  Iacute: "\xCD",
192  Icirc: "\xCE",
193  Icy: "\u0418",
194  Idot: "\u0130",
195  Ifr: "\u2111",
196  Igrave: "\xCC",
197  Im: "\u2111",
198  Imacr: "\u012A",
199  ImaginaryI: "\u2148",
200  Implies: "\u21D2",
201  Int: "\u222C",
202  Integral: "\u222B",
203  Intersection: "\u22C2",
204  InvisibleComma: "\u2063",
205  InvisibleTimes: "\u2062",
206  Iogon: "\u012E",
207  Iopf: "\u{1D540}",
208  Iota: "\u0399",
209  Iscr: "\u2110",
210  Itilde: "\u0128",
211  Iukcy: "\u0406",
212  Iuml: "\xCF",
213  Jcirc: "\u0134",
214  Jcy: "\u0419",
215  Jfr: "\u{1D50D}",
216  Jopf: "\u{1D541}",
217  Jscr: "\u{1D4A5}",
218  Jsercy: "\u0408",
219  Jukcy: "\u0404",
220  KHcy: "\u0425",
221  KJcy: "\u040C",
222  Kappa: "\u039A",
223  Kcedil: "\u0136",
224  Kcy: "\u041A",
225  Kfr: "\u{1D50E}",
226  Kopf: "\u{1D542}",
227  Kscr: "\u{1D4A6}",
228  LJcy: "\u0409",
229  LT: "<",
230  Lacute: "\u0139",
231  Lambda: "\u039B",
232  Lang: "\u27EA",
233  Laplacetrf: "\u2112",
234  Larr: "\u219E",
235  Lcaron: "\u013D",
236  Lcedil: "\u013B",
237  Lcy: "\u041B",
238  LeftAngleBracket: "\u27E8",
239  LeftArrow: "\u2190",
240  LeftArrowBar: "\u21E4",
241  LeftArrowRightArrow: "\u21C6",
242  LeftCeiling: "\u2308",
243  LeftDoubleBracket: "\u27E6",
244  LeftDownTeeVector: "\u2961",
245  LeftDownVector: "\u21C3",
246  LeftDownVectorBar: "\u2959",
247  LeftFloor: "\u230A",
248  LeftRightArrow: "\u2194",
249  LeftRightVector: "\u294E",
250  LeftTee: "\u22A3",
251  LeftTeeArrow: "\u21A4",
252  LeftTeeVector: "\u295A",
253  LeftTriangle: "\u22B2",
254  LeftTriangleBar: "\u29CF",
255  LeftTriangleEqual: "\u22B4",
256  LeftUpDownVector: "\u2951",
257  LeftUpTeeVector: "\u2960",
258  LeftUpVector: "\u21BF",
259  LeftUpVectorBar: "\u2958",
260  LeftVector: "\u21BC",
261  LeftVectorBar: "\u2952",
262  Leftarrow: "\u21D0",
263  Leftrightarrow: "\u21D4",
264  LessEqualGreater: "\u22DA",
265  LessFullEqual: "\u2266",
266  LessGreater: "\u2276",
267  LessLess: "\u2AA1",
268  LessSlantEqual: "\u2A7D",
269  LessTilde: "\u2272",
270  Lfr: "\u{1D50F}",
271  Ll: "\u22D8",
272  Lleftarrow: "\u21DA",
273  Lmidot: "\u013F",
274  LongLeftArrow: "\u27F5",
275  LongLeftRightArrow: "\u27F7",
276  LongRightArrow: "\u27F6",
277  Longleftarrow: "\u27F8",
278  Longleftrightarrow: "\u27FA",
279  Longrightarrow: "\u27F9",
280  Lopf: "\u{1D543}",
281  LowerLeftArrow: "\u2199",
282  LowerRightArrow: "\u2198",
283  Lscr: "\u2112",
284  Lsh: "\u21B0",
285  Lstrok: "\u0141",
286  Lt: "\u226A",
287  Map: "\u2905",
288  Mcy: "\u041C",
289  MediumSpace: "\u205F",
290  Mellintrf: "\u2133",
291  Mfr: "\u{1D510}",
292  MinusPlus: "\u2213",
293  Mopf: "\u{1D544}",
294  Mscr: "\u2133",
295  Mu: "\u039C",
296  NJcy: "\u040A",
297  Nacute: "\u0143",
298  Ncaron: "\u0147",
299  Ncedil: "\u0145",
300  Ncy: "\u041D",
301  NegativeMediumSpace: "\u200B",
302  NegativeThickSpace: "\u200B",
303  NegativeThinSpace: "\u200B",
304  NegativeVeryThinSpace: "\u200B",
305  NestedGreaterGreater: "\u226B",
306  NestedLessLess: "\u226A",
307  NewLine: "\n",
308  Nfr: "\u{1D511}",
309  NoBreak: "\u2060",
310  NonBreakingSpace: "\xA0",
311  Nopf: "\u2115",
312  Not: "\u2AEC",
313  NotCongruent: "\u2262",
314  NotCupCap: "\u226D",
315  NotDoubleVerticalBar: "\u2226",
316  NotElement: "\u2209",
317  NotEqual: "\u2260",
318  NotEqualTilde: "\u2242\u0338",
319  NotExists: "\u2204",
320  NotGreater: "\u226F",
321  NotGreaterEqual: "\u2271",
322  NotGreaterFullEqual: "\u2267\u0338",
323  NotGreaterGreater: "\u226B\u0338",
324  NotGreaterLess: "\u2279",
325  NotGreaterSlantEqual: "\u2A7E\u0338",
326  NotGreaterTilde: "\u2275",
327  NotHumpDownHump: "\u224E\u0338",
328  NotHumpEqual: "\u224F\u0338",
329  NotLeftTriangle: "\u22EA",
330  NotLeftTriangleBar: "\u29CF\u0338",
331  NotLeftTriangleEqual: "\u22EC",
332  NotLess: "\u226E",
333  NotLessEqual: "\u2270",
334  NotLessGreater: "\u2278",
335  NotLessLess: "\u226A\u0338",
336  NotLessSlantEqual: "\u2A7D\u0338",
337  NotLessTilde: "\u2274",
338  NotNestedGreaterGreater: "\u2AA2\u0338",
339  NotNestedLessLess: "\u2AA1\u0338",
340  NotPrecedes: "\u2280",
341  NotPrecedesEqual: "\u2AAF\u0338",
342  NotPrecedesSlantEqual: "\u22E0",
343  NotReverseElement: "\u220C",
344  NotRightTriangle: "\u22EB",
345  NotRightTriangleBar: "\u29D0\u0338",
346  NotRightTriangleEqual: "\u22ED",
347  NotSquareSubset: "\u228F\u0338",
348  NotSquareSubsetEqual: "\u22E2",
349  NotSquareSuperset: "\u2290\u0338",
350  NotSquareSupersetEqual: "\u22E3",
351  NotSubset: "\u2282\u20D2",
352  NotSubsetEqual: "\u2288",
353  NotSucceeds: "\u2281",
354  NotSucceedsEqual: "\u2AB0\u0338",
355  NotSucceedsSlantEqual: "\u22E1",
356  NotSucceedsTilde: "\u227F\u0338",
357  NotSuperset: "\u2283\u20D2",
358  NotSupersetEqual: "\u2289",
359  NotTilde: "\u2241",
360  NotTildeEqual: "\u2244",
361  NotTildeFullEqual: "\u2247",
362  NotTildeTilde: "\u2249",
363  NotVerticalBar: "\u2224",
364  Nscr: "\u{1D4A9}",
365  Ntilde: "\xD1",
366  Nu: "\u039D",
367  OElig: "\u0152",
368  Oacute: "\xD3",
369  Ocirc: "\xD4",
370  Ocy: "\u041E",
371  Odblac: "\u0150",
372  Ofr: "\u{1D512}",
373  Ograve: "\xD2",
374  Omacr: "\u014C",
375  Omega: "\u03A9",
376  Omicron: "\u039F",
377  Oopf: "\u{1D546}",
378  OpenCurlyDoubleQuote: "\u201C",
379  OpenCurlyQuote: "\u2018",
380  Or: "\u2A54",
381  Oscr: "\u{1D4AA}",
382  Oslash: "\xD8",
383  Otilde: "\xD5",
384  Otimes: "\u2A37",
385  Ouml: "\xD6",
386  OverBar: "\u203E",
387  OverBrace: "\u23DE",
388  OverBracket: "\u23B4",
389  OverParenthesis: "\u23DC",
390  PartialD: "\u2202",
391  Pcy: "\u041F",
392  Pfr: "\u{1D513}",
393  Phi: "\u03A6",
394  Pi: "\u03A0",
395  PlusMinus: "\xB1",
396  Poincareplane: "\u210C",
397  Popf: "\u2119",
398  Pr: "\u2ABB",
399  Precedes: "\u227A",
400  PrecedesEqual: "\u2AAF",
401  PrecedesSlantEqual: "\u227C",
402  PrecedesTilde: "\u227E",
403  Prime: "\u2033",
404  Product: "\u220F",
405  Proportion: "\u2237",
406  Proportional: "\u221D",
407  Pscr: "\u{1D4AB}",
408  Psi: "\u03A8",
409  QUOT: '"',
410  Qfr: "\u{1D514}",
411  Qopf: "\u211A",
412  Qscr: "\u{1D4AC}",
413  RBarr: "\u2910",
414  REG: "\xAE",
415  Racute: "\u0154",
416  Rang: "\u27EB",
417  Rarr: "\u21A0",
418  Rarrtl: "\u2916",
419  Rcaron: "\u0158",
420  Rcedil: "\u0156",
421  Rcy: "\u0420",
422  Re: "\u211C",
423  ReverseElement: "\u220B",
424  ReverseEquilibrium: "\u21CB",
425  ReverseUpEquilibrium: "\u296F",
426  Rfr: "\u211C",
427  Rho: "\u03A1",
428  RightAngleBracket: "\u27E9",
429  RightArrow: "\u2192",
430  RightArrowBar: "\u21E5",
431  RightArrowLeftArrow: "\u21C4",
432  RightCeiling: "\u2309",
433  RightDoubleBracket: "\u27E7",
434  RightDownTeeVector: "\u295D",
435  RightDownVector: "\u21C2",
436  RightDownVectorBar: "\u2955",
437  RightFloor: "\u230B",
438  RightTee: "\u22A2",
439  RightTeeArrow: "\u21A6",
440  RightTeeVector: "\u295B",
441  RightTriangle: "\u22B3",
442  RightTriangleBar: "\u29D0",
443  RightTriangleEqual: "\u22B5",
444  RightUpDownVector: "\u294F",
445  RightUpTeeVector: "\u295C",
446  RightUpVector: "\u21BE",
447  RightUpVectorBar: "\u2954",
448  RightVector: "\u21C0",
449  RightVectorBar: "\u2953",
450  Rightarrow: "\u21D2",
451  Ropf: "\u211D",
452  RoundImplies: "\u2970",
453  Rrightarrow: "\u21DB",
454  Rscr: "\u211B",
455  Rsh: "\u21B1",
456  RuleDelayed: "\u29F4",
457  SHCHcy: "\u0429",
458  SHcy: "\u0428",
459  SOFTcy: "\u042C",
460  Sacute: "\u015A",
461  Sc: "\u2ABC",
462  Scaron: "\u0160",
463  Scedil: "\u015E",
464  Scirc: "\u015C",
465  Scy: "\u0421",
466  Sfr: "\u{1D516}",
467  ShortDownArrow: "\u2193",
468  ShortLeftArrow: "\u2190",
469  ShortRightArrow: "\u2192",
470  ShortUpArrow: "\u2191",
471  Sigma: "\u03A3",
472  SmallCircle: "\u2218",
473  Sopf: "\u{1D54A}",
474  Sqrt: "\u221A",
475  Square: "\u25A1",
476  SquareIntersection: "\u2293",
477  SquareSubset: "\u228F",
478  SquareSubsetEqual: "\u2291",
479  SquareSuperset: "\u2290",
480  SquareSupersetEqual: "\u2292",
481  SquareUnion: "\u2294",
482  Sscr: "\u{1D4AE}",
483  Star: "\u22C6",
484  Sub: "\u22D0",
485  Subset: "\u22D0",
486  SubsetEqual: "\u2286",
487  Succeeds: "\u227B",
488  SucceedsEqual: "\u2AB0",
489  SucceedsSlantEqual: "\u227D",
490  SucceedsTilde: "\u227F",
491  SuchThat: "\u220B",
492  Sum: "\u2211",
493  Sup: "\u22D1",
494  Superset: "\u2283",
495  SupersetEqual: "\u2287",
496  Supset: "\u22D1",
497  THORN: "\xDE",
498  TRADE: "\u2122",
499  TSHcy: "\u040B",
500  TScy: "\u0426",
501  Tab: "	",
502  Tau: "\u03A4",
503  Tcaron: "\u0164",
504  Tcedil: "\u0162",
505  Tcy: "\u0422",
506  Tfr: "\u{1D517}",
507  Therefore: "\u2234",
508  Theta: "\u0398",
509  ThickSpace: "\u205F\u200A",
510  ThinSpace: "\u2009",
511  Tilde: "\u223C",
512  TildeEqual: "\u2243",
513  TildeFullEqual: "\u2245",
514  TildeTilde: "\u2248",
515  Topf: "\u{1D54B}",
516  TripleDot: "\u20DB",
517  Tscr: "\u{1D4AF}",
518  Tstrok: "\u0166",
519  Uacute: "\xDA",
520  Uarr: "\u219F",
521  Uarrocir: "\u2949",
522  Ubrcy: "\u040E",
523  Ubreve: "\u016C",
524  Ucirc: "\xDB",
525  Ucy: "\u0423",
526  Udblac: "\u0170",
527  Ufr: "\u{1D518}",
528  Ugrave: "\xD9",
529  Umacr: "\u016A",
530  UnderBar: "_",
531  UnderBrace: "\u23DF",
532  UnderBracket: "\u23B5",
533  UnderParenthesis: "\u23DD",
534  Union: "\u22C3",
535  UnionPlus: "\u228E",
536  Uogon: "\u0172",
537  Uopf: "\u{1D54C}",
538  UpArrow: "\u2191",
539  UpArrowBar: "\u2912",
540  UpArrowDownArrow: "\u21C5",
541  UpDownArrow: "\u2195",
542  UpEquilibrium: "\u296E",
543  UpTee: "\u22A5",
544  UpTeeArrow: "\u21A5",
545  Uparrow: "\u21D1",
546  Updownarrow: "\u21D5",
547  UpperLeftArrow: "\u2196",
548  UpperRightArrow: "\u2197",
549  Upsi: "\u03D2",
550  Upsilon: "\u03A5",
551  Uring: "\u016E",
552  Uscr: "\u{1D4B0}",
553  Utilde: "\u0168",
554  Uuml: "\xDC",
555  VDash: "\u22AB",
556  Vbar: "\u2AEB",
557  Vcy: "\u0412",
558  Vdash: "\u22A9",
559  Vdashl: "\u2AE6",
560  Vee: "\u22C1",
561  Verbar: "\u2016",
562  Vert: "\u2016",
563  VerticalBar: "\u2223",
564  VerticalLine: "|",
565  VerticalSeparator: "\u2758",
566  VerticalTilde: "\u2240",
567  VeryThinSpace: "\u200A",
568  Vfr: "\u{1D519}",
569  Vopf: "\u{1D54D}",
570  Vscr: "\u{1D4B1}",
571  Vvdash: "\u22AA",
572  Wcirc: "\u0174",
573  Wedge: "\u22C0",
574  Wfr: "\u{1D51A}",
575  Wopf: "\u{1D54E}",
576  Wscr: "\u{1D4B2}",
577  Xfr: "\u{1D51B}",
578  Xi: "\u039E",
579  Xopf: "\u{1D54F}",
580  Xscr: "\u{1D4B3}",
581  YAcy: "\u042F",
582  YIcy: "\u0407",
583  YUcy: "\u042E",
584  Yacute: "\xDD",
585  Ycirc: "\u0176",
586  Ycy: "\u042B",
587  Yfr: "\u{1D51C}",
588  Yopf: "\u{1D550}",
589  Yscr: "\u{1D4B4}",
590  Yuml: "\u0178",
591  ZHcy: "\u0416",
592  Zacute: "\u0179",
593  Zcaron: "\u017D",
594  Zcy: "\u0417",
595  Zdot: "\u017B",
596  ZeroWidthSpace: "\u200B",
597  Zeta: "\u0396",
598  Zfr: "\u2128",
599  Zopf: "\u2124",
600  Zscr: "\u{1D4B5}",
601  aacute: "\xE1",
602  abreve: "\u0103",
603  ac: "\u223E",
604  acE: "\u223E\u0333",
605  acd: "\u223F",
606  acirc: "\xE2",
607  acute: "\xB4",
608  acy: "\u0430",
609  aelig: "\xE6",
610  af: "\u2061",
611  afr: "\u{1D51E}",
612  agrave: "\xE0",
613  alefsym: "\u2135",
614  aleph: "\u2135",
615  alpha: "\u03B1",
616  amacr: "\u0101",
617  amalg: "\u2A3F",
618  amp: "&",
619  and: "\u2227",
620  andand: "\u2A55",
621  andd: "\u2A5C",
622  andslope: "\u2A58",
623  andv: "\u2A5A",
624  ang: "\u2220",
625  ange: "\u29A4",
626  angle: "\u2220",
627  angmsd: "\u2221",
628  angmsdaa: "\u29A8",
629  angmsdab: "\u29A9",
630  angmsdac: "\u29AA",
631  angmsdad: "\u29AB",
632  angmsdae: "\u29AC",
633  angmsdaf: "\u29AD",
634  angmsdag: "\u29AE",
635  angmsdah: "\u29AF",
636  angrt: "\u221F",
637  angrtvb: "\u22BE",
638  angrtvbd: "\u299D",
639  angsph: "\u2222",
640  angst: "\xC5",
641  angzarr: "\u237C",
642  aogon: "\u0105",
643  aopf: "\u{1D552}",
644  ap: "\u2248",
645  apE: "\u2A70",
646  apacir: "\u2A6F",
647  ape: "\u224A",
648  apid: "\u224B",
649  apos: "'",
650  approx: "\u2248",
651  approxeq: "\u224A",
652  aring: "\xE5",
653  ascr: "\u{1D4B6}",
654  ast: "*",
655  asymp: "\u2248",
656  asympeq: "\u224D",
657  atilde: "\xE3",
658  auml: "\xE4",
659  awconint: "\u2233",
660  awint: "\u2A11",
661  bNot: "\u2AED",
662  backcong: "\u224C",
663  backepsilon: "\u03F6",
664  backprime: "\u2035",
665  backsim: "\u223D",
666  backsimeq: "\u22CD",
667  barvee: "\u22BD",
668  barwed: "\u2305",
669  barwedge: "\u2305",
670  bbrk: "\u23B5",
671  bbrktbrk: "\u23B6",
672  bcong: "\u224C",
673  bcy: "\u0431",
674  bdquo: "\u201E",
675  becaus: "\u2235",
676  because: "\u2235",
677  bemptyv: "\u29B0",
678  bepsi: "\u03F6",
679  bernou: "\u212C",
680  beta: "\u03B2",
681  beth: "\u2136",
682  between: "\u226C",
683  bfr: "\u{1D51F}",
684  bigcap: "\u22C2",
685  bigcirc: "\u25EF",
686  bigcup: "\u22C3",
687  bigodot: "\u2A00",
688  bigoplus: "\u2A01",
689  bigotimes: "\u2A02",
690  bigsqcup: "\u2A06",
691  bigstar: "\u2605",
692  bigtriangledown: "\u25BD",
693  bigtriangleup: "\u25B3",
694  biguplus: "\u2A04",
695  bigvee: "\u22C1",
696  bigwedge: "\u22C0",
697  bkarow: "\u290D",
698  blacklozenge: "\u29EB",
699  blacksquare: "\u25AA",
700  blacktriangle: "\u25B4",
701  blacktriangledown: "\u25BE",
702  blacktriangleleft: "\u25C2",
703  blacktriangleright: "\u25B8",
704  blank: "\u2423",
705  blk12: "\u2592",
706  blk14: "\u2591",
707  blk34: "\u2593",
708  block: "\u2588",
709  bne: "=\u20E5",
710  bnequiv: "\u2261\u20E5",
711  bnot: "\u2310",
712  bopf: "\u{1D553}",
713  bot: "\u22A5",
714  bottom: "\u22A5",
715  bowtie: "\u22C8",
716  boxDL: "\u2557",
717  boxDR: "\u2554",
718  boxDl: "\u2556",
719  boxDr: "\u2553",
720  boxH: "\u2550",
721  boxHD: "\u2566",
722  boxHU: "\u2569",
723  boxHd: "\u2564",
724  boxHu: "\u2567",
725  boxUL: "\u255D",
726  boxUR: "\u255A",
727  boxUl: "\u255C",
728  boxUr: "\u2559",
729  boxV: "\u2551",
730  boxVH: "\u256C",
731  boxVL: "\u2563",
732  boxVR: "\u2560",
733  boxVh: "\u256B",
734  boxVl: "\u2562",
735  boxVr: "\u255F",
736  boxbox: "\u29C9",
737  boxdL: "\u2555",
738  boxdR: "\u2552",
739  boxdl: "\u2510",
740  boxdr: "\u250C",
741  boxh: "\u2500",
742  boxhD: "\u2565",
743  boxhU: "\u2568",
744  boxhd: "\u252C",
745  boxhu: "\u2534",
746  boxminus: "\u229F",
747  boxplus: "\u229E",
748  boxtimes: "\u22A0",
749  boxuL: "\u255B",
750  boxuR: "\u2558",
751  boxul: "\u2518",
752  boxur: "\u2514",
753  boxv: "\u2502",
754  boxvH: "\u256A",
755  boxvL: "\u2561",
756  boxvR: "\u255E",
757  boxvh: "\u253C",
758  boxvl: "\u2524",
759  boxvr: "\u251C",
760  bprime: "\u2035",
761  breve: "\u02D8",
762  brvbar: "\xA6",
763  bscr: "\u{1D4B7}",
764  bsemi: "\u204F",
765  bsim: "\u223D",
766  bsime: "\u22CD",
767  bsol: "\\",
768  bsolb: "\u29C5",
769  bsolhsub: "\u27C8",
770  bull: "\u2022",
771  bullet: "\u2022",
772  bump: "\u224E",
773  bumpE: "\u2AAE",
774  bumpe: "\u224F",
775  bumpeq: "\u224F",
776  cacute: "\u0107",
777  cap: "\u2229",
778  capand: "\u2A44",
779  capbrcup: "\u2A49",
780  capcap: "\u2A4B",
781  capcup: "\u2A47",
782  capdot: "\u2A40",
783  caps: "\u2229\uFE00",
784  caret: "\u2041",
785  caron: "\u02C7",
786  ccaps: "\u2A4D",
787  ccaron: "\u010D",
788  ccedil: "\xE7",
789  ccirc: "\u0109",
790  ccups: "\u2A4C",
791  ccupssm: "\u2A50",
792  cdot: "\u010B",
793  cedil: "\xB8",
794  cemptyv: "\u29B2",
795  cent: "\xA2",
796  centerdot: "\xB7",
797  cfr: "\u{1D520}",
798  chcy: "\u0447",
799  check: "\u2713",
800  checkmark: "\u2713",
801  chi: "\u03C7",
802  cir: "\u25CB",
803  cirE: "\u29C3",
804  circ: "\u02C6",
805  circeq: "\u2257",
806  circlearrowleft: "\u21BA",
807  circlearrowright: "\u21BB",
808  circledR: "\xAE",
809  circledS: "\u24C8",
810  circledast: "\u229B",
811  circledcirc: "\u229A",
812  circleddash: "\u229D",
813  cire: "\u2257",
814  cirfnint: "\u2A10",
815  cirmid: "\u2AEF",
816  cirscir: "\u29C2",
817  clubs: "\u2663",
818  clubsuit: "\u2663",
819  colon: ":",
820  colone: "\u2254",
821  coloneq: "\u2254",
822  comma: ",",
823  commat: "@",
824  comp: "\u2201",
825  compfn: "\u2218",
826  complement: "\u2201",
827  complexes: "\u2102",
828  cong: "\u2245",
829  congdot: "\u2A6D",
830  conint: "\u222E",
831  copf: "\u{1D554}",
832  coprod: "\u2210",
833  copy: "\xA9",
834  copysr: "\u2117",
835  crarr: "\u21B5",
836  cross: "\u2717",
837  cscr: "\u{1D4B8}",
838  csub: "\u2ACF",
839  csube: "\u2AD1",
840  csup: "\u2AD0",
841  csupe: "\u2AD2",
842  ctdot: "\u22EF",
843  cudarrl: "\u2938",
844  cudarrr: "\u2935",
845  cuepr: "\u22DE",
846  cuesc: "\u22DF",
847  cularr: "\u21B6",
848  cularrp: "\u293D",
849  cup: "\u222A",
850  cupbrcap: "\u2A48",
851  cupcap: "\u2A46",
852  cupcup: "\u2A4A",
853  cupdot: "\u228D",
854  cupor: "\u2A45",
855  cups: "\u222A\uFE00",
856  curarr: "\u21B7",
857  curarrm: "\u293C",
858  curlyeqprec: "\u22DE",
859  curlyeqsucc: "\u22DF",
860  curlyvee: "\u22CE",
861  curlywedge: "\u22CF",
862  curren: "\xA4",
863  curvearrowleft: "\u21B6",
864  curvearrowright: "\u21B7",
865  cuvee: "\u22CE",
866  cuwed: "\u22CF",
867  cwconint: "\u2232",
868  cwint: "\u2231",
869  cylcty: "\u232D",
870  dArr: "\u21D3",
871  dHar: "\u2965",
872  dagger: "\u2020",
873  daleth: "\u2138",
874  darr: "\u2193",
875  dash: "\u2010",
876  dashv: "\u22A3",
877  dbkarow: "\u290F",
878  dblac: "\u02DD",
879  dcaron: "\u010F",
880  dcy: "\u0434",
881  dd: "\u2146",
882  ddagger: "\u2021",
883  ddarr: "\u21CA",
884  ddotseq: "\u2A77",
885  deg: "\xB0",
886  delta: "\u03B4",
887  demptyv: "\u29B1",
888  dfisht: "\u297F",
889  dfr: "\u{1D521}",
890  dharl: "\u21C3",
891  dharr: "\u21C2",
892  diam: "\u22C4",
893  diamond: "\u22C4",
894  diamondsuit: "\u2666",
895  diams: "\u2666",
896  die: "\xA8",
897  digamma: "\u03DD",
898  disin: "\u22F2",
899  div: "\xF7",
900  divide: "\xF7",
901  divideontimes: "\u22C7",
902  divonx: "\u22C7",
903  djcy: "\u0452",
904  dlcorn: "\u231E",
905  dlcrop: "\u230D",
906  dollar: "$",
907  dopf: "\u{1D555}",
908  dot: "\u02D9",
909  doteq: "\u2250",
910  doteqdot: "\u2251",
911  dotminus: "\u2238",
912  dotplus: "\u2214",
913  dotsquare: "\u22A1",
914  doublebarwedge: "\u2306",
915  downarrow: "\u2193",
916  downdownarrows: "\u21CA",
917  downharpoonleft: "\u21C3",
918  downharpoonright: "\u21C2",
919  drbkarow: "\u2910",
920  drcorn: "\u231F",
921  drcrop: "\u230C",
922  dscr: "\u{1D4B9}",
923  dscy: "\u0455",
924  dsol: "\u29F6",
925  dstrok: "\u0111",
926  dtdot: "\u22F1",
927  dtri: "\u25BF",
928  dtrif: "\u25BE",
929  duarr: "\u21F5",
930  duhar: "\u296F",
931  dwangle: "\u29A6",
932  dzcy: "\u045F",
933  dzigrarr: "\u27FF",
934  eDDot: "\u2A77",
935  eDot: "\u2251",
936  eacute: "\xE9",
937  easter: "\u2A6E",
938  ecaron: "\u011B",
939  ecir: "\u2256",
940  ecirc: "\xEA",
941  ecolon: "\u2255",
942  ecy: "\u044D",
943  edot: "\u0117",
944  ee: "\u2147",
945  efDot: "\u2252",
946  efr: "\u{1D522}",
947  eg: "\u2A9A",
948  egrave: "\xE8",
949  egs: "\u2A96",
950  egsdot: "\u2A98",
951  el: "\u2A99",
952  elinters: "\u23E7",
953  ell: "\u2113",
954  els: "\u2A95",
955  elsdot: "\u2A97",
956  emacr: "\u0113",
957  empty: "\u2205",
958  emptyset: "\u2205",
959  emptyv: "\u2205",
960  emsp13: "\u2004",
961  emsp14: "\u2005",
962  emsp: "\u2003",
963  eng: "\u014B",
964  ensp: "\u2002",
965  eogon: "\u0119",
966  eopf: "\u{1D556}",
967  epar: "\u22D5",
968  eparsl: "\u29E3",
969  eplus: "\u2A71",
970  epsi: "\u03B5",
971  epsilon: "\u03B5",
972  epsiv: "\u03F5",
973  eqcirc: "\u2256",
974  eqcolon: "\u2255",
975  eqsim: "\u2242",
976  eqslantgtr: "\u2A96",
977  eqslantless: "\u2A95",
978  equals: "=",
979  equest: "\u225F",
980  equiv: "\u2261",
981  equivDD: "\u2A78",
982  eqvparsl: "\u29E5",
983  erDot: "\u2253",
984  erarr: "\u2971",
985  escr: "\u212F",
986  esdot: "\u2250",
987  esim: "\u2242",
988  eta: "\u03B7",
989  eth: "\xF0",
990  euml: "\xEB",
991  euro: "\u20AC",
992  excl: "!",
993  exist: "\u2203",
994  expectation: "\u2130",
995  exponentiale: "\u2147",
996  fallingdotseq: "\u2252",
997  fcy: "\u0444",
998  female: "\u2640",
999  ffilig: "\uFB03",
1000  fflig: "\uFB00",
1001  ffllig: "\uFB04",
1002  ffr: "\u{1D523}",
1003  filig: "\uFB01",
1004  fjlig: "fj",
1005  flat: "\u266D",
1006  fllig: "\uFB02",
1007  fltns: "\u25B1",
1008  fnof: "\u0192",
1009  fopf: "\u{1D557}",
1010  forall: "\u2200",
1011  fork: "\u22D4",
1012  forkv: "\u2AD9",
1013  fpartint: "\u2A0D",
1014  frac12: "\xBD",
1015  frac13: "\u2153",
1016  frac14: "\xBC",
1017  frac15: "\u2155",
1018  frac16: "\u2159",
1019  frac18: "\u215B",
1020  frac23: "\u2154",
1021  frac25: "\u2156",
1022  frac34: "\xBE",
1023  frac35: "\u2157",
1024  frac38: "\u215C",
1025  frac45: "\u2158",
1026  frac56: "\u215A",
1027  frac58: "\u215D",
1028  frac78: "\u215E",
1029  frasl: "\u2044",
1030  frown: "\u2322",
1031  fscr: "\u{1D4BB}",
1032  gE: "\u2267",
1033  gEl: "\u2A8C",
1034  gacute: "\u01F5",
1035  gamma: "\u03B3",
1036  gammad: "\u03DD",
1037  gap: "\u2A86",
1038  gbreve: "\u011F",
1039  gcirc: "\u011D",
1040  gcy: "\u0433",
1041  gdot: "\u0121",
1042  ge: "\u2265",
1043  gel: "\u22DB",
1044  geq: "\u2265",
1045  geqq: "\u2267",
1046  geqslant: "\u2A7E",
1047  ges: "\u2A7E",
1048  gescc: "\u2AA9",
1049  gesdot: "\u2A80",
1050  gesdoto: "\u2A82",
1051  gesdotol: "\u2A84",
1052  gesl: "\u22DB\uFE00",
1053  gesles: "\u2A94",
1054  gfr: "\u{1D524}",
1055  gg: "\u226B",
1056  ggg: "\u22D9",
1057  gimel: "\u2137",
1058  gjcy: "\u0453",
1059  gl: "\u2277",
1060  glE: "\u2A92",
1061  gla: "\u2AA5",
1062  glj: "\u2AA4",
1063  gnE: "\u2269",
1064  gnap: "\u2A8A",
1065  gnapprox: "\u2A8A",
1066  gne: "\u2A88",
1067  gneq: "\u2A88",
1068  gneqq: "\u2269",
1069  gnsim: "\u22E7",
1070  gopf: "\u{1D558}",
1071  grave: "`",
1072  gscr: "\u210A",
1073  gsim: "\u2273",
1074  gsime: "\u2A8E",
1075  gsiml: "\u2A90",
1076  gt: ">",
1077  gtcc: "\u2AA7",
1078  gtcir: "\u2A7A",
1079  gtdot: "\u22D7",
1080  gtlPar: "\u2995",
1081  gtquest: "\u2A7C",
1082  gtrapprox: "\u2A86",
1083  gtrarr: "\u2978",
1084  gtrdot: "\u22D7",
1085  gtreqless: "\u22DB",
1086  gtreqqless: "\u2A8C",
1087  gtrless: "\u2277",
1088  gtrsim: "\u2273",
1089  gvertneqq: "\u2269\uFE00",
1090  gvnE: "\u2269\uFE00",
1091  hArr: "\u21D4",
1092  hairsp: "\u200A",
1093  half: "\xBD",
1094  hamilt: "\u210B",
1095  hardcy: "\u044A",
1096  harr: "\u2194",
1097  harrcir: "\u2948",
1098  harrw: "\u21AD",
1099  hbar: "\u210F",
1100  hcirc: "\u0125",
1101  hearts: "\u2665",
1102  heartsuit: "\u2665",
1103  hellip: "\u2026",
1104  hercon: "\u22B9",
1105  hfr: "\u{1D525}",
1106  hksearow: "\u2925",
1107  hkswarow: "\u2926",
1108  hoarr: "\u21FF",
1109  homtht: "\u223B",
1110  hookleftarrow: "\u21A9",
1111  hookrightarrow: "\u21AA",
1112  hopf: "\u{1D559}",
1113  horbar: "\u2015",
1114  hscr: "\u{1D4BD}",
1115  hslash: "\u210F",
1116  hstrok: "\u0127",
1117  hybull: "\u2043",
1118  hyphen: "\u2010",
1119  iacute: "\xED",
1120  ic: "\u2063",
1121  icirc: "\xEE",
1122  icy: "\u0438",
1123  iecy: "\u0435",
1124  iexcl: "\xA1",
1125  iff: "\u21D4",
1126  ifr: "\u{1D526}",
1127  igrave: "\xEC",
1128  ii: "\u2148",
1129  iiiint: "\u2A0C",
1130  iiint: "\u222D",
1131  iinfin: "\u29DC",
1132  iiota: "\u2129",
1133  ijlig: "\u0133",
1134  imacr: "\u012B",
1135  image: "\u2111",
1136  imagline: "\u2110",
1137  imagpart: "\u2111",
1138  imath: "\u0131",
1139  imof: "\u22B7",
1140  imped: "\u01B5",
1141  in: "\u2208",
1142  incare: "\u2105",
1143  infin: "\u221E",
1144  infintie: "\u29DD",
1145  inodot: "\u0131",
1146  int: "\u222B",
1147  intcal: "\u22BA",
1148  integers: "\u2124",
1149  intercal: "\u22BA",
1150  intlarhk: "\u2A17",
1151  intprod: "\u2A3C",
1152  iocy: "\u0451",
1153  iogon: "\u012F",
1154  iopf: "\u{1D55A}",
1155  iota: "\u03B9",
1156  iprod: "\u2A3C",
1157  iquest: "\xBF",
1158  iscr: "\u{1D4BE}",
1159  isin: "\u2208",
1160  isinE: "\u22F9",
1161  isindot: "\u22F5",
1162  isins: "\u22F4",
1163  isinsv: "\u22F3",
1164  isinv: "\u2208",
1165  it: "\u2062",
1166  itilde: "\u0129",
1167  iukcy: "\u0456",
1168  iuml: "\xEF",
1169  jcirc: "\u0135",
1170  jcy: "\u0439",
1171  jfr: "\u{1D527}",
1172  jmath: "\u0237",
1173  jopf: "\u{1D55B}",
1174  jscr: "\u{1D4BF}",
1175  jsercy: "\u0458",
1176  jukcy: "\u0454",
1177  kappa: "\u03BA",
1178  kappav: "\u03F0",
1179  kcedil: "\u0137",
1180  kcy: "\u043A",
1181  kfr: "\u{1D528}",
1182  kgreen: "\u0138",
1183  khcy: "\u0445",
1184  kjcy: "\u045C",
1185  kopf: "\u{1D55C}",
1186  kscr: "\u{1D4C0}",
1187  lAarr: "\u21DA",
1188  lArr: "\u21D0",
1189  lAtail: "\u291B",
1190  lBarr: "\u290E",
1191  lE: "\u2266",
1192  lEg: "\u2A8B",
1193  lHar: "\u2962",
1194  lacute: "\u013A",
1195  laemptyv: "\u29B4",
1196  lagran: "\u2112",
1197  lambda: "\u03BB",
1198  lang: "\u27E8",
1199  langd: "\u2991",
1200  langle: "\u27E8",
skills/plain-english/scripts/core/chunk-VC7IYITB.mjs 132 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2var affixSymbol = new RegExp([
3  "^([!\"').?\\u0F3B\\u0F3D\\u169C\\u2019\\u201D\\u2026\\u203A\\u203D\\u2046\\u207E\\u208E\\u2309\\u230B\\u232A\\u2769\\u276B\\u276D\\u276F\\u2771\\u2773\\u2775\\u27C6\\u27E7\\u27E9\\u27EB\\u27ED\\u27EF\\u2984\\u2986\\u2988\\u298A",
4  "\\u298C\\u298E\\u2990\\u2992\\u2994\\u2996\\u2998\\u29D9\\u29DB\\u29FD\\u2E03\\u2E05\\u2E0A\\u2E0D\\u2E1D\\u2E21\\u2E23\\u2E25\\u2E27\\u2E29\\u2E56\\u2E58\\u2E5A\\u2E5C\\u3009\\u300B\\u300D\\u300F\\u3011\\u3015\\u3017\\u3019\\u301B",
5  "\\u301E\\u301F\\uFD3E\\uFE18\\uFE36\\uFE38\\uFE3A\\uFE3C\\uFE3E\\uFE40\\uFE42\\uFE44\\uFE48\\uFE5A\\uFE5C\\uFE5E\\uFF09\\uFF3D\\uFF5D\\uFF60\\uFF63\\u00BB\\]}])\\1*$"
6].join(""), "");
7var newLine = /^[ \t]*((\r?\n|\r)[\t ]*)+$/;
8var terminalMarker = /^([!.?\u2026\u203D]+)$/;
9var wordSymbolInner = /^([&'\-.:=?@\u00AD\u00B7\u2010\u2011\u2019\u2027]|_+)$/;
10var numerical = new RegExp([
11  "^(?:[\\d\\u00B2\\u00B3\\u00B9\\u00BC-\\u00BE\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u09F4-\\u09F9\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0B72-\\u0B77\\u0BE6-\\u0BF2\\u0C66-\\u0C6F\\u0C78",
12  "-\\u0C7E\\u0CE6-\\u0CEF\\u0D58-\\u0D5E\\u0D66-\\u0D78\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F33\\u1040-\\u1049\\u1090-\\u1099\\u1369-\\u137C\\u16EE-\\u16F0\\u17E0-\\u17E9\\u17F0-\\u17F9\\u1810-\\u1819\\u1946-",
13  "\\u194F\\u19D0-\\u19DA\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\u2070\\u2074-\\u2079\\u2080-\\u2089\\u2150-\\u2182\\u2185-\\u2189\\u2460-\\u249B\\u24EA-\\u24FF\\u2776-\\u2793\\u2CFD",
14  "\\u3007\\u3021-\\u3029\\u3038-\\u303A\\u3192-\\u3195\\u3220-\\u3229\\u3248-\\u324F\\u3251-\\u325F\\u3280-\\u3289\\u32B1-\\u32BF\\uA620-\\uA629\\uA6E6-\\uA6EF\\uA830-\\uA835\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-",
15  "\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]|\\uD800[\\uDD07-\\uDD33\\uDD40-\\uDD78\\uDD8A\\uDD8B\\uDEE1-\\uDEFB\\uDF20-\\uDF23\\uDF41\\uDF4A\\uDFD1-\\uDFD5]|\\uD801[\\uDCA0-\\uDCA9]|\\uD802[\\uDC58-\\uDC5F\\uDC79-\\uDC7F",
16  "\\uDCA7-\\uDCAF\\uDCFB-\\uDCFF\\uDD16-\\uDD1B\\uDDBC\\uDDBD\\uDDC0-\\uDDCF\\uDDD2-\\uDDFF\\uDE40-\\uDE48\\uDE7D\\uDE7E\\uDE9D-\\uDE9F\\uDEEB-\\uDEEF\\uDF58-\\uDF5F\\uDF78-\\uDF7F\\uDFA9-\\uDFAF]|\\uD803[\\uDCFA-\\uDCFF\\uDD30-",
17  "\\uDD39\\uDE60-\\uDE7E\\uDF1D-\\uDF26\\uDF51-\\uDF54\\uDFC5-\\uDFCB]|\\uD804[\\uDC52-\\uDC6F\\uDCF0-\\uDCF9\\uDD36-\\uDD3F\\uDDD0-\\uDDD9\\uDDE1-\\uDDF4\\uDEF0-\\uDEF9]|\\uD805[\\uDC50-\\uDC59\\uDCD0-\\uDCD9\\uDE50-\\uDE59\\uDEC0-",
18  "\\uDEC9\\uDF30-\\uDF3B]|\\uD806[\\uDCE0-\\uDCF2\\uDD50-\\uDD59]|\\uD807[\\uDC50-\\uDC6C\\uDD50-\\uDD59\\uDDA0-\\uDDA9\\uDF50-\\uDF59\\uDFC0-\\uDFD4]|\\uD809[\\uDC00-\\uDC6E]|\\uD81A[\\uDE60-\\uDE69\\uDEC0-\\uDEC9\\uDF50-\\uDF59",
19  "\\uDF5B-\\uDF61]|\\uD81B[\\uDE80-\\uDE96]|\\uD834[\\uDEC0-\\uDED3\\uDEE0-\\uDEF3\\uDF60-\\uDF78]|\\uD835[\\uDFCE-\\uDFFF]|\\uD838[\\uDD40-\\uDD49\\uDEF0-\\uDEF9]|\\uD839[\\uDCF0-\\uDCF9]|\\uD83A[\\uDCC7-\\uDCCF\\uDD50-\\uDD59]|",
20  "\\uD83B[\\uDC71-\\uDCAB\\uDCAD-\\uDCAF\\uDCB1-\\uDCB4\\uDD01-\\uDD2D\\uDD2F-\\uDD3D]|\\uD83C[\\uDD00-\\uDD0C]|\\uD83E[\\uDFF0-\\uDFF9])+$"
21].join(""), "");
22var digitStart = /^\d/;
23var lowerInitial = new RegExp([
24  "^(?:[a-z\\u00B5\\u00DF-\\u00F6\\u00F8-\\u00FF\\u0101\\u0103\\u0105\\u0107\\u0109\\u010B\\u010D\\u010F\\u0111\\u0113\\u0115\\u0117\\u0119\\u011B\\u011D\\u011F\\u0121\\u0123\\u0125\\u0127\\u0129\\u012B\\u012D\\u012F\\u0131\\u0133",
25  "\\u0135\\u0137\\u0138\\u013A\\u013C\\u013E\\u0140\\u0142\\u0144\\u0146\\u0148\\u0149\\u014B\\u014D\\u014F\\u0151\\u0153\\u0155\\u0157\\u0159\\u015B\\u015D\\u015F\\u0161\\u0163\\u0165\\u0167\\u0169\\u016B\\u016D\\u016F\\u0171\\u0173",
26  "\\u0175\\u0177\\u017A\\u017C\\u017E-\\u0180\\u0183\\u0185\\u0188\\u018C\\u018D\\u0192\\u0195\\u0199-\\u019B\\u019E\\u01A1\\u01A3\\u01A5\\u01A8\\u01AA\\u01AB\\u01AD\\u01B0\\u01B4\\u01B6\\u01B9\\u01BA\\u01BD-\\u01BF\\u01C6\\u01C9",
27  "\\u01CC\\u01CE\\u01D0\\u01D2\\u01D4\\u01D6\\u01D8\\u01DA\\u01DC\\u01DD\\u01DF\\u01E1\\u01E3\\u01E5\\u01E7\\u01E9\\u01EB\\u01ED\\u01EF\\u01F0\\u01F3\\u01F5\\u01F9\\u01FB\\u01FD\\u01FF\\u0201\\u0203\\u0205\\u0207\\u0209\\u020B\\u020D",
28  "\\u020F\\u0211\\u0213\\u0215\\u0217\\u0219\\u021B\\u021D\\u021F\\u0221\\u0223\\u0225\\u0227\\u0229\\u022B\\u022D\\u022F\\u0231\\u0233-\\u0239\\u023C\\u023F\\u0240\\u0242\\u0247\\u0249\\u024B\\u024D\\u024F-\\u0293\\u0295-\\u02AF",
29  "\\u0371\\u0373\\u0377\\u037B-\\u037D\\u0390\\u03AC-\\u03CE\\u03D0\\u03D1\\u03D5-\\u03D7\\u03D9\\u03DB\\u03DD\\u03DF\\u03E1\\u03E3\\u03E5\\u03E7\\u03E9\\u03EB\\u03ED\\u03EF-\\u03F3\\u03F5\\u03F8\\u03FB\\u03FC\\u0430-\\u045F\\u0461",
30  "\\u0463\\u0465\\u0467\\u0469\\u046B\\u046D\\u046F\\u0471\\u0473\\u0475\\u0477\\u0479\\u047B\\u047D\\u047F\\u0481\\u048B\\u048D\\u048F\\u0491\\u0493\\u0495\\u0497\\u0499\\u049B\\u049D\\u049F\\u04A1\\u04A3\\u04A5\\u04A7\\u04A9\\u04AB",
31  "\\u04AD\\u04AF\\u04B1\\u04B3\\u04B5\\u04B7\\u04B9\\u04BB\\u04BD\\u04BF\\u04C2\\u04C4\\u04C6\\u04C8\\u04CA\\u04CC\\u04CE\\u04CF\\u04D1\\u04D3\\u04D5\\u04D7\\u04D9\\u04DB\\u04DD\\u04DF\\u04E1\\u04E3\\u04E5\\u04E7\\u04E9\\u04EB\\u04ED",
32  "\\u04EF\\u04F1\\u04F3\\u04F5\\u04F7\\u04F9\\u04FB\\u04FD\\u04FF\\u0501\\u0503\\u0505\\u0507\\u0509\\u050B\\u050D\\u050F\\u0511\\u0513\\u0515\\u0517\\u0519\\u051B\\u051D\\u051F\\u0521\\u0523\\u0525\\u0527\\u0529\\u052B\\u052D\\u052F",
33  "\\u0560-\\u0588\\u10D0-\\u10FA\\u10FD-\\u10FF\\u13F8-\\u13FD\\u1C80-\\u1C88\\u1D00-\\u1D2B\\u1D6B-\\u1D77\\u1D79-\\u1D9A\\u1E01\\u1E03\\u1E05\\u1E07\\u1E09\\u1E0B\\u1E0D\\u1E0F\\u1E11\\u1E13\\u1E15\\u1E17\\u1E19\\u1E1B\\u1E1D\\u1E1F",
34  "\\u1E21\\u1E23\\u1E25\\u1E27\\u1E29\\u1E2B\\u1E2D\\u1E2F\\u1E31\\u1E33\\u1E35\\u1E37\\u1E39\\u1E3B\\u1E3D\\u1E3F\\u1E41\\u1E43\\u1E45\\u1E47\\u1E49\\u1E4B\\u1E4D\\u1E4F\\u1E51\\u1E53\\u1E55\\u1E57\\u1E59\\u1E5B\\u1E5D\\u1E5F\\u1E61",
35  "\\u1E63\\u1E65\\u1E67\\u1E69\\u1E6B\\u1E6D\\u1E6F\\u1E71\\u1E73\\u1E75\\u1E77\\u1E79\\u1E7B\\u1E7D\\u1E7F\\u1E81\\u1E83\\u1E85\\u1E87\\u1E89\\u1E8B\\u1E8D\\u1E8F\\u1E91\\u1E93\\u1E95-\\u1E9D\\u1E9F\\u1EA1\\u1EA3\\u1EA5\\u1EA7\\u1EA9",
36  "\\u1EAB\\u1EAD\\u1EAF\\u1EB1\\u1EB3\\u1EB5\\u1EB7\\u1EB9\\u1EBB\\u1EBD\\u1EBF\\u1EC1\\u1EC3\\u1EC5\\u1EC7\\u1EC9\\u1ECB\\u1ECD\\u1ECF\\u1ED1\\u1ED3\\u1ED5\\u1ED7\\u1ED9\\u1EDB\\u1EDD\\u1EDF\\u1EE1\\u1EE3\\u1EE5\\u1EE7\\u1EE9\\u1EEB",
37  "\\u1EED\\u1EEF\\u1EF1\\u1EF3\\u1EF5\\u1EF7\\u1EF9\\u1EFB\\u1EFD\\u1EFF-\\u1F07\\u1F10-\\u1F15\\u1F20-\\u1F27\\u1F30-\\u1F37\\u1F40-\\u1F45\\u1F50-\\u1F57\\u1F60-\\u1F67\\u1F70-\\u1F7D\\u1F80-\\u1F87\\u1F90-\\u1F97\\u1FA0-\\u1FA7",
38  "\\u1FB0-\\u1FB4\\u1FB6\\u1FB7\\u1FBE\\u1FC2-\\u1FC4\\u1FC6\\u1FC7\\u1FD0-\\u1FD3\\u1FD6\\u1FD7\\u1FE0-\\u1FE7\\u1FF2-\\u1FF4\\u1FF6\\u1FF7\\u210A\\u210E\\u210F\\u2113\\u212F\\u2134\\u2139\\u213C\\u213D\\u2146-\\u2149\\u214E\\u2184",
39  "\\u2C30-\\u2C5F\\u2C61\\u2C65\\u2C66\\u2C68\\u2C6A\\u2C6C\\u2C71\\u2C73\\u2C74\\u2C76-\\u2C7B\\u2C81\\u2C83\\u2C85\\u2C87\\u2C89\\u2C8B\\u2C8D\\u2C8F\\u2C91\\u2C93\\u2C95\\u2C97\\u2C99\\u2C9B\\u2C9D\\u2C9F\\u2CA1\\u2CA3\\u2CA5\\u2CA7",
40  "\\u2CA9\\u2CAB\\u2CAD\\u2CAF\\u2CB1\\u2CB3\\u2CB5\\u2CB7\\u2CB9\\u2CBB\\u2CBD\\u2CBF\\u2CC1\\u2CC3\\u2CC5\\u2CC7\\u2CC9\\u2CCB\\u2CCD\\u2CCF\\u2CD1\\u2CD3\\u2CD5\\u2CD7\\u2CD9\\u2CDB\\u2CDD\\u2CDF\\u2CE1\\u2CE3\\u2CE4\\u2CEC\\u2CEE",
41  "\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\uA641\\uA643\\uA645\\uA647\\uA649\\uA64B\\uA64D\\uA64F\\uA651\\uA653\\uA655\\uA657\\uA659\\uA65B\\uA65D\\uA65F\\uA661\\uA663\\uA665\\uA667\\uA669\\uA66B\\uA66D\\uA681\\uA683\\uA685\\uA687\\uA689",
42  "\\uA68B\\uA68D\\uA68F\\uA691\\uA693\\uA695\\uA697\\uA699\\uA69B\\uA723\\uA725\\uA727\\uA729\\uA72B\\uA72D\\uA72F-\\uA731\\uA733\\uA735\\uA737\\uA739\\uA73B\\uA73D\\uA73F\\uA741\\uA743\\uA745\\uA747\\uA749\\uA74B\\uA74D\\uA74F\\uA751",
43  "\\uA753\\uA755\\uA757\\uA759\\uA75B\\uA75D\\uA75F\\uA761\\uA763\\uA765\\uA767\\uA769\\uA76B\\uA76D\\uA76F\\uA771-\\uA778\\uA77A\\uA77C\\uA77F\\uA781\\uA783\\uA785\\uA787\\uA78C\\uA78E\\uA791\\uA793-\\uA795\\uA797\\uA799\\uA79B\\uA79D",
44  "\\uA79F\\uA7A1\\uA7A3\\uA7A5\\uA7A7\\uA7A9\\uA7AF\\uA7B5\\uA7B7\\uA7B9\\uA7BB\\uA7BD\\uA7BF\\uA7C1\\uA7C3\\uA7C8\\uA7CA\\uA7D1\\uA7D3\\uA7D5\\uA7D7\\uA7D9\\uA7F6\\uA7FA\\uAB30-\\uAB5A\\uAB60-\\uAB68\\uAB70-\\uABBF\\uFB00-\\uFB06",
45  "\\uFB13-\\uFB17\\uFF41-\\uFF5A]|\\uD801[\\uDC28-\\uDC4F\\uDCD8-\\uDCFB\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC]|\\uD803[\\uDCC0-\\uDCF2]|\\uD806[\\uDCC0-\\uDCDF]|\\uD81B[\\uDE60-\\uDE7F]|\\uD835[\\uDC1A-\\uDC33",
46  "\\uDC4E-\\uDC54\\uDC56-\\uDC67\\uDC82-\\uDC9B\\uDCB6-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDCCF\\uDCEA-\\uDD03\\uDD1E-\\uDD37\\uDD52-\\uDD6B\\uDD86-\\uDD9F\\uDDBA-\\uDDD3\\uDDEE-\\uDE07\\uDE22-\\uDE3B\\uDE56-\\uDE6F\\uDE8A-",
47  "\\uDEA5\\uDEC2-\\uDEDA\\uDEDC-\\uDEE1\\uDEFC-\\uDF14\\uDF16-\\uDF1B\\uDF36-\\uDF4E\\uDF50-\\uDF55\\uDF70-\\uDF88\\uDF8A-\\uDF8F\\uDFAA-\\uDFC2\\uDFC4-\\uDFC9\\uDFCB]|\\uD837[\\uDF00-\\uDF09\\uDF0B-\\uDF1E\\uDF25-\\uDF2A]|\\uD83A[",
48  "\\uDD22-\\uDD43])"
49].join(""), "");
50var surrogates = /[\uD800-\uDFFF]/;
51var punctuation = new RegExp([
52  "[!\"'-),-/:;?[-\\]_{}\\u00A1\\u00A7\\u00AB\\u00B6\\u00B7\\u00BB\\u00BF\\u037E\\u0387\\u055A-\\u055F\\u0589\\u058A\\u05BE\\u05C0\\u05C3\\u05C6\\u05F3\\u05F4\\u0609\\u060A\\u060C\\u060D\\u061B\\u061D-\\u061F\\u066A-\\u066D\\u06D4",
53  "\\u0700-\\u070D\\u07F7-\\u07F9\\u0830-\\u083E\\u085E\\u0964\\u0965\\u0970\\u09FD\\u0A76\\u0AF0\\u0C77\\u0C84\\u0DF4\\u0E4F\\u0E5A\\u0E5B\\u0F04-\\u0F12\\u0F14\\u0F3A-\\u0F3D\\u0F85\\u0FD0-\\u0FD4\\u0FD9\\u0FDA\\u104A-\\u104F\\u10FB",
54  "\\u1360-\\u1368\\u1400\\u166E\\u169B\\u169C\\u16EB-\\u16ED\\u1735\\u1736\\u17D4-\\u17D6\\u17D8-\\u17DA\\u1800-\\u180A\\u1944\\u1945\\u1A1E\\u1A1F\\u1AA0-\\u1AA6\\u1AA8-\\u1AAD\\u1B5A-\\u1B60\\u1B7D\\u1B7E\\u1BFC-\\u1BFF\\u1C3B-",
55  "\\u1C3F\\u1C7E\\u1C7F\\u1CC0-\\u1CC7\\u1CD3\\u2010-\\u201F\\u2022-\\u2027\\u2032-\\u203A\\u203C-\\u2043\\u2045-\\u2051\\u2053-\\u205E\\u207D\\u207E\\u208D\\u208E\\u2308-\\u230B\\u2329\\u232A\\u2768-\\u2775\\u27C5\\u27C6\\u27E6-",
56  "\\u27EF\\u2983-\\u2998\\u29D8-\\u29DB\\u29FC\\u29FD\\u2CF9-\\u2CFC\\u2CFE\\u2CFF\\u2D70\\u2E00-\\u2E2E\\u2E30-\\u2E4F\\u2E52-\\u2E5D\\u3001-\\u3003\\u3008-\\u3011\\u3014-\\u301F\\u3030\\u303D\\u30A0\\u30FB\\uA4FE\\uA4FF\\uA60D-",
57  "\\uA60F\\uA673\\uA67E\\uA6F2-\\uA6F7\\uA874-\\uA877\\uA8CE\\uA8CF\\uA8F8-\\uA8FA\\uA8FC\\uA92E\\uA92F\\uA95F\\uA9C1-\\uA9CD\\uA9DE\\uA9DF\\uAA5C-\\uAA5F\\uAADE\\uAADF\\uAAF0\\uAAF1\\uABEB\\uFD3E\\uFD3F\\uFE10-\\uFE19\\uFE30-\\uFE52",
58  "\\uFE54-\\uFE61\\uFE63\\uFE68\\uFE6A\\uFE6B\\uFF01-\\uFF03\\uFF05-\\uFF0A\\uFF0C-\\uFF0F\\uFF1A\\uFF1B\\uFF1F\\uFF20\\uFF3B-\\uFF3D\\uFF3F\\uFF5B\\uFF5D\\uFF5F-\\uFF65]|\\uD800[\\uDD00-\\uDD02\\uDF9F\\uDFD0]|\\uD801\\uDD6F|\\uD802[",
59  "\\uDC57\\uDD1F\\uDD3F\\uDE50-\\uDE58\\uDE7F\\uDEF0-\\uDEF6\\uDF39-\\uDF3F\\uDF99-\\uDF9C]|\\uD803[\\uDEAD\\uDF55-\\uDF59\\uDF86-\\uDF89]|\\uD804[\\uDC47-\\uDC4D\\uDCBB\\uDCBC\\uDCBE-\\uDCC1\\uDD40-\\uDD43\\uDD74\\uDD75\\uDDC5-",
60  "\\uDDC8\\uDDCD\\uDDDB\\uDDDD-\\uDDDF\\uDE38-\\uDE3D\\uDEA9]|\\uD805[\\uDC4B-\\uDC4F\\uDC5A\\uDC5B\\uDC5D\\uDCC6\\uDDC1-\\uDDD7\\uDE41-\\uDE43\\uDE60-\\uDE6C\\uDEB9\\uDF3C-\\uDF3E]|\\uD806[\\uDC3B\\uDD44-\\uDD46\\uDDE2\\uDE3F-",
61  "\\uDE46\\uDE9A-\\uDE9C\\uDE9E-\\uDEA2\\uDF00-\\uDF09]|\\uD807[\\uDC41-\\uDC45\\uDC70\\uDC71\\uDEF7\\uDEF8\\uDF43-\\uDF4F\\uDFFF]|\\uD809[\\uDC70-\\uDC74]|\\uD80B[\\uDFF1\\uDFF2]|\\uD81A[\\uDE6E\\uDE6F\\uDEF5\\uDF37-\\uDF3B\\uDF44]",
62  "|\\uD81B[\\uDE97-\\uDE9A\\uDFE2]|\\uD82F\\uDC9F|\\uD836[\\uDE87-\\uDE8B]|\\uD83A[\\uDD5E\\uDD5F]"
63].join(""), "");
64var word = new RegExp([
65  "[\\dA-Za-z\\u00AA\\u00B2\\u00B3\\u00B5\\u00B9\\u00BA\\u00BC-\\u00BE\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0300-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A",
66  "\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u0483-\\u052F\\u0531-\\u0556\\u0559\\u0560-\\u0588\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u05D0-\\u05EA\\u05EF-\\u05F2\\u0610-\\u061A\\u0620-\\u0669\\u066E-",
67  "\\u06D3\\u06D5-\\u06DC\\u06DF-\\u06E8\\u06EA-\\u06FC\\u06FF\\u0710-\\u074A\\u074D-\\u07B1\\u07C0-\\u07F5\\u07FA\\u07FD\\u0800-\\u082D\\u0840-\\u085B\\u0860-\\u086A\\u0870-\\u0887\\u0889-\\u088E\\u0898-\\u08E1\\u08E3-\\u0963\\u0966-",
68  "\\u096F\\u0971-\\u0983\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BC-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CE\\u09D7\\u09DC\\u09DD\\u09DF-\\u09E3\\u09E6-\\u09F1\\u09F4-\\u09F9\\u09FC\\u09FE",
69  "\\u0A01-\\u0A03\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A59-\\u0A5C\\u0A5E\\u0A66-\\u0A75\\u0A81-\\u0A83",
70  "\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABC-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AD0\\u0AE0-\\u0AE3\\u0AE6-\\u0AEF\\u0AF9-\\u0AFF\\u0B01-\\u0B03\\u0B05-\\u0B0C\\u0B0F\\u0B10",
71  "\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3C-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B55-\\u0B57\\u0B5C\\u0B5D\\u0B5F-\\u0B63\\u0B66-\\u0B6F\\u0B71-\\u0B77\\u0B82\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-",
72  "\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD0\\u0BD7\\u0BE6-\\u0BF2\\u0C00-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3C-",
73  "\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C58-\\u0C5A\\u0C5D\\u0C60-\\u0C63\\u0C66-\\u0C6F\\u0C78-\\u0C7E\\u0C80-\\u0C83\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBC-\\u0CC4\\u0CC6-",
74  "\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CDD\\u0CDE\\u0CE0-\\u0CE3\\u0CE6-\\u0CEF\\u0CF1-\\u0CF3\\u0D00-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4E\\u0D54-\\u0D63\\u0D66-\\u0D78\\u0D7A-\\u0D7F\\u0D81-\\u0D83",
75  "\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DE6-\\u0DEF\\u0DF2\\u0DF3\\u0E01-\\u0E3A\\u0E40-\\u0E4E\\u0E50-\\u0E59\\u0E81\\u0E82\\u0E84\\u0E86-\\u0E8A\\u0E8C-",
76  "\\u0EA3\\u0EA5\\u0EA7-\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EC8-\\u0ECE\\u0ED0-\\u0ED9\\u0EDC-\\u0EDF\\u0F00\\u0F18\\u0F19\\u0F20-\\u0F33\\u0F35\\u0F37\\u0F39\\u0F3E-\\u0F47\\u0F49-\\u0F6C\\u0F71-\\u0F84\\u0F86-\\u0F97\\u0F99-\\u0FBC",
77  "\\u0FC6\\u1000-\\u1049\\u1050-\\u109D\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0",
78  "\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u135D-\\u135F\\u1369-\\u137C\\u1380-\\u138F\\u13A0-\\u13F5\\u13F8-\\u13FD\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8",
79  "\\u1700-\\u1715\\u171F-\\u1734\\u1740-\\u1753\\u1760-\\u176C\\u176E-\\u1770\\u1772\\u1773\\u1780-\\u17D3\\u17D7\\u17DC\\u17DD\\u17E0-\\u17E9\\u17F0-\\u17F9\\u180B-\\u180D\\u180F-\\u1819\\u1820-\\u1878\\u1880-\\u18AA\\u18B0-\\u18F5",
80  "\\u1900-\\u191E\\u1920-\\u192B\\u1930-\\u193B\\u1946-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19B0-\\u19C9\\u19D0-\\u19DA\\u1A00-\\u1A1B\\u1A20-\\u1A5E\\u1A60-\\u1A7C\\u1A7F-\\u1A89\\u1A90-\\u1A99\\u1AA7\\u1AB0-\\u1ACE\\u1B00-",
81  "\\u1B4C\\u1B50-\\u1B59\\u1B6B-\\u1B73\\u1B80-\\u1BF3\\u1C00-\\u1C37\\u1C40-\\u1C49\\u1C4D-\\u1C7D\\u1C80-\\u1C88\\u1C90-\\u1CBA\\u1CBD-\\u1CBF\\u1CD0-\\u1CD2\\u1CD4-\\u1CFA\\u1D00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-",
82  "\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2070\\u2071\\u2074-\\u2079",
83  "\\u207F-\\u2089\\u2090-\\u209C\\u20D0-\\u20F0\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2150-\\u2189\\u2460-\\u249B\\u24EA-\\u24FF",
84  "\\u2776-\\u2793\\u2C00-\\u2CE4\\u2CEB-\\u2CF3\\u2CFD\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D7F-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-",
85  "\\u2DDE\\u2DE0-\\u2DFF\\u2E2F\\u3005-\\u3007\\u3021-\\u302F\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u3099\\u309A\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312F\\u3131-\\u318E\\u3192-\\u3195\\u31A0-\\u31BF\\u31F0-",
86  "\\u31FF\\u3220-\\u3229\\u3248-\\u324F\\u3251-\\u325F\\u3280-\\u3289\\u32B1-\\u32BF\\u3400-\\u4DBF\\u4E00-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA62B\\uA640-\\uA672\\uA674-\\uA67D\\uA67F-\\uA6F1\\uA717-\\uA71F\\uA722-",
87  "\\uA788\\uA78B-\\uA7CA\\uA7D0\\uA7D1\\uA7D3\\uA7D5-\\uA7D9\\uA7F2-\\uA827\\uA82C\\uA830-\\uA835\\uA840-\\uA873\\uA880-\\uA8C5\\uA8D0-\\uA8D9\\uA8E0-\\uA8F7\\uA8FB\\uA8FD-\\uA92D\\uA930-\\uA953\\uA960-\\uA97C\\uA980-\\uA9C0\\uA9CF-",
88  "\\uA9D9\\uA9E0-\\uA9FE\\uAA00-\\uAA36\\uAA40-\\uAA4D\\uAA50-\\uAA59\\uAA60-\\uAA76\\uAA7A-\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEF\\uAAF2-\\uAAF6\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-",
89  "\\uAB5A\\uAB5C-\\uAB69\\uAB70-\\uABEA\\uABEC\\uABED\\uABF0-\\uABF9\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40",
90  "\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE00-\\uFE0F\\uFE20-\\uFE2F\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF10-\\uFF19\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7",
91  "\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]|\\uD800[\\uDC00-\\uDC0B\\uDC0D-\\uDC26\\uDC28-\\uDC3A\\uDC3C\\uDC3D\\uDC3F-\\uDC4D\\uDC50-\\uDC5D\\uDC80-\\uDCFA\\uDD07-\\uDD33\\uDD40-\\uDD78\\uDD8A\\uDD8B\\uDDFD\\uDE80-\\uDE9C",
92  "\\uDEA0-\\uDED0\\uDEE0-\\uDEFB\\uDF00-\\uDF23\\uDF2D-\\uDF4A\\uDF50-\\uDF7A\\uDF80-\\uDF9D\\uDFA0-\\uDFC3\\uDFC8-\\uDFCF\\uDFD1-\\uDFD5]|\\uD801[\\uDC00-\\uDC9D\\uDCA0-\\uDCA9\\uDCB0-\\uDCD3\\uDCD8-\\uDCFB\\uDD00-\\uDD27\\uDD30-",
93  "\\uDD63\\uDD70-\\uDD7A\\uDD7C-\\uDD8A\\uDD8C-\\uDD92\\uDD94\\uDD95\\uDD97-\\uDDA1\\uDDA3-\\uDDB1\\uDDB3-\\uDDB9\\uDDBB\\uDDBC\\uDE00-\\uDF36\\uDF40-\\uDF55\\uDF60-\\uDF67\\uDF80-\\uDF85\\uDF87-\\uDFB0\\uDFB2-\\uDFBA]|\\uD802[",
94  "\\uDC00-\\uDC05\\uDC08\\uDC0A-\\uDC35\\uDC37\\uDC38\\uDC3C\\uDC3F-\\uDC55\\uDC58-\\uDC76\\uDC79-\\uDC9E\\uDCA7-\\uDCAF\\uDCE0-\\uDCF2\\uDCF4\\uDCF5\\uDCFB-\\uDD1B\\uDD20-\\uDD39\\uDD80-\\uDDB7\\uDDBC-\\uDDCF\\uDDD2-\\uDE03\\uDE05",
95  "\\uDE06\\uDE0C-\\uDE13\\uDE15-\\uDE17\\uDE19-\\uDE35\\uDE38-\\uDE3A\\uDE3F-\\uDE48\\uDE60-\\uDE7E\\uDE80-\\uDE9F\\uDEC0-\\uDEC7\\uDEC9-\\uDEE6\\uDEEB-\\uDEEF\\uDF00-\\uDF35\\uDF40-\\uDF55\\uDF58-\\uDF72\\uDF78-\\uDF91\\uDFA9-",
96  "\\uDFAF]|\\uD803[\\uDC00-\\uDC48\\uDC80-\\uDCB2\\uDCC0-\\uDCF2\\uDCFA-\\uDD27\\uDD30-\\uDD39\\uDE60-\\uDE7E\\uDE80-\\uDEA9\\uDEAB\\uDEAC\\uDEB0\\uDEB1\\uDEFD-\\uDF27\\uDF30-\\uDF54\\uDF70-\\uDF85\\uDFB0-\\uDFCB\\uDFE0-\\uDFF6]|",
97  "\\uD804[\\uDC00-\\uDC46\\uDC52-\\uDC75\\uDC7F-\\uDCBA\\uDCC2\\uDCD0-\\uDCE8\\uDCF0-\\uDCF9\\uDD00-\\uDD34\\uDD36-\\uDD3F\\uDD44-\\uDD47\\uDD50-\\uDD73\\uDD76\\uDD80-\\uDDC4\\uDDC9-\\uDDCC\\uDDCE-\\uDDDA\\uDDDC\\uDDE1-\\uDDF4\\uDE00",
98  "-\\uDE11\\uDE13-\\uDE37\\uDE3E-\\uDE41\\uDE80-\\uDE86\\uDE88\\uDE8A-\\uDE8D\\uDE8F-\\uDE9D\\uDE9F-\\uDEA8\\uDEB0-\\uDEEA\\uDEF0-\\uDEF9\\uDF00-\\uDF03\\uDF05-\\uDF0C\\uDF0F\\uDF10\\uDF13-\\uDF28\\uDF2A-\\uDF30\\uDF32\\uDF33\\uDF35-",
99  "\\uDF39\\uDF3B-\\uDF44\\uDF47\\uDF48\\uDF4B-\\uDF4D\\uDF50\\uDF57\\uDF5D-\\uDF63\\uDF66-\\uDF6C\\uDF70-\\uDF74]|\\uD805[\\uDC00-\\uDC4A\\uDC50-\\uDC59\\uDC5E-\\uDC61\\uDC80-\\uDCC5\\uDCC7\\uDCD0-\\uDCD9\\uDD80-\\uDDB5\\uDDB8-",
100  "\\uDDC0\\uDDD8-\\uDDDD\\uDE00-\\uDE40\\uDE44\\uDE50-\\uDE59\\uDE80-\\uDEB8\\uDEC0-\\uDEC9\\uDF00-\\uDF1A\\uDF1D-\\uDF2B\\uDF30-\\uDF3B\\uDF40-\\uDF46]|\\uD806[\\uDC00-\\uDC3A\\uDCA0-\\uDCF2\\uDCFF-\\uDD06\\uDD09\\uDD0C-\\uDD13",
101  "\\uDD15\\uDD16\\uDD18-\\uDD35\\uDD37\\uDD38\\uDD3B-\\uDD43\\uDD50-\\uDD59\\uDDA0-\\uDDA7\\uDDAA-\\uDDD7\\uDDDA-\\uDDE1\\uDDE3\\uDDE4\\uDE00-\\uDE3E\\uDE47\\uDE50-\\uDE99\\uDE9D\\uDEB0-\\uDEF8]|\\uD807[\\uDC00-\\uDC08\\uDC0A-\\uDC36",
102  "\\uDC38-\\uDC40\\uDC50-\\uDC6C\\uDC72-\\uDC8F\\uDC92-\\uDCA7\\uDCA9-\\uDCB6\\uDD00-\\uDD06\\uDD08\\uDD09\\uDD0B-\\uDD36\\uDD3A\\uDD3C\\uDD3D\\uDD3F-\\uDD47\\uDD50-\\uDD59\\uDD60-\\uDD65\\uDD67\\uDD68\\uDD6A-\\uDD8E\\uDD90\\uDD91",
103  "\\uDD93-\\uDD98\\uDDA0-\\uDDA9\\uDEE0-\\uDEF6\\uDF00-\\uDF10\\uDF12-\\uDF3A\\uDF3E-\\uDF42\\uDF50-\\uDF59\\uDFB0\\uDFC0-\\uDFD4]|\\uD808[\\uDC00-\\uDF99]|\\uD809[\\uDC00-\\uDC6E\\uDC80-\\uDD43]|\\uD80B[\\uDF90-\\uDFF0]|[\\uD80C",
104  "\\uD81C-\\uD820\\uD822\\uD840-\\uD868\\uD86A-\\uD86C\\uD86F-\\uD872\\uD874-\\uD879\\uD880-\\uD883\\uD885-\\uD887][\\uDC00-\\uDFFF]|\\uD80D[\\uDC00-\\uDC2F\\uDC40-\\uDC55]|\\uD811[\\uDC00-\\uDE46]|\\uD81A[\\uDC00-\\uDE38\\uDE40-",
105  "\\uDE5E\\uDE60-\\uDE69\\uDE70-\\uDEBE\\uDEC0-\\uDEC9\\uDED0-\\uDEED\\uDEF0-\\uDEF4\\uDF00-\\uDF36\\uDF40-\\uDF43\\uDF50-\\uDF59\\uDF5B-\\uDF61\\uDF63-\\uDF77\\uDF7D-\\uDF8F]|\\uD81B[\\uDE40-\\uDE96\\uDF00-\\uDF4A\\uDF4F-\\uDF87",
106  "\\uDF8F-\\uDF9F\\uDFE0\\uDFE1\\uDFE3\\uDFE4\\uDFF0\\uDFF1]|\\uD821[\\uDC00-\\uDFF7]|\\uD823[\\uDC00-\\uDCD5\\uDD00-\\uDD08]|\\uD82B[\\uDFF0-\\uDFF3\\uDFF5-\\uDFFB\\uDFFD\\uDFFE]|\\uD82C[\\uDC00-\\uDD22\\uDD32\\uDD50-\\uDD52\\uDD55",
107  "\\uDD64-\\uDD67\\uDD70-\\uDEFB]|\\uD82F[\\uDC00-\\uDC6A\\uDC70-\\uDC7C\\uDC80-\\uDC88\\uDC90-\\uDC99\\uDC9D\\uDC9E]|\\uD833[\\uDF00-\\uDF2D\\uDF30-\\uDF46]|\\uD834[\\uDD65-\\uDD69\\uDD6D-\\uDD72\\uDD7B-\\uDD82\\uDD85-\\uDD8B",
108  "\\uDDAA-\\uDDAD\\uDE42-\\uDE44\\uDEC0-\\uDED3\\uDEE0-\\uDEF3\\uDF60-\\uDF78]|\\uD835[\\uDC00-\\uDC54\\uDC56-\\uDC9C\\uDC9E\\uDC9F\\uDCA2\\uDCA5\\uDCA6\\uDCA9-\\uDCAC\\uDCAE-\\uDCB9\\uDCBB\\uDCBD-\\uDCC3\\uDCC5-\\uDD05\\uDD07-",
109  "\\uDD0A\\uDD0D-\\uDD14\\uDD16-\\uDD1C\\uDD1E-\\uDD39\\uDD3B-\\uDD3E\\uDD40-\\uDD44\\uDD46\\uDD4A-\\uDD50\\uDD52-\\uDEA5\\uDEA8-\\uDEC0\\uDEC2-\\uDEDA\\uDEDC-\\uDEFA\\uDEFC-\\uDF14\\uDF16-\\uDF34\\uDF36-\\uDF4E\\uDF50-\\uDF6E\\uDF70",
110  "-\\uDF88\\uDF8A-\\uDFA8\\uDFAA-\\uDFC2\\uDFC4-\\uDFCB\\uDFCE-\\uDFFF]|\\uD836[\\uDE00-\\uDE36\\uDE3B-\\uDE6C\\uDE75\\uDE84\\uDE9B-\\uDE9F\\uDEA1-\\uDEAF]|\\uD837[\\uDF00-\\uDF1E\\uDF25-\\uDF2A]|\\uD838[\\uDC00-\\uDC06\\uDC08-",
111  "\\uDC18\\uDC1B-\\uDC21\\uDC23\\uDC24\\uDC26-\\uDC2A\\uDC30-\\uDC6D\\uDC8F\\uDD00-\\uDD2C\\uDD30-\\uDD3D\\uDD40-\\uDD49\\uDD4E\\uDE90-\\uDEAE\\uDEC0-\\uDEF9]|\\uD839[\\uDCD0-\\uDCF9\\uDFE0-\\uDFE6\\uDFE8-\\uDFEB\\uDFED\\uDFEE\\uDFF0",
112  "-\\uDFFE]|\\uD83A[\\uDC00-\\uDCC4\\uDCC7-\\uDCD6\\uDD00-\\uDD4B\\uDD50-\\uDD59]|\\uD83B[\\uDC71-\\uDCAB\\uDCAD-\\uDCAF\\uDCB1-\\uDCB4\\uDD01-\\uDD2D\\uDD2F-\\uDD3D\\uDE00-\\uDE03\\uDE05-\\uDE1F\\uDE21\\uDE22\\uDE24\\uDE27\\uDE29-",
113  "\\uDE32\\uDE34-\\uDE37\\uDE39\\uDE3B\\uDE42\\uDE47\\uDE49\\uDE4B\\uDE4D-\\uDE4F\\uDE51\\uDE52\\uDE54\\uDE57\\uDE59\\uDE5B\\uDE5D\\uDE5F\\uDE61\\uDE62\\uDE64\\uDE67-\\uDE6A\\uDE6C-\\uDE72\\uDE74-\\uDE77\\uDE79-\\uDE7C\\uDE7E\\uDE80-",
114  "\\uDE89\\uDE8B-\\uDE9B\\uDEA1-\\uDEA3\\uDEA5-\\uDEA9\\uDEAB-\\uDEBB]|\\uD83C[\\uDD00-\\uDD0C]|\\uD83E[\\uDFF0-\\uDFF9]|\\uD869[\\uDC00-\\uDEDF\\uDF00-\\uDFFF]|\\uD86D[\\uDC00-\\uDF39\\uDF40-\\uDFFF]|\\uD86E[\\uDC00-\\uDC1D\\uDC20",
115  "-\\uDFFF]|\\uD873[\\uDC00-\\uDEA1\\uDEB0-\\uDFFF]|\\uD87A[\\uDC00-\\uDFE0]|\\uD87E[\\uDC00-\\uDE1D]|\\uD884[\\uDC00-\\uDF4A\\uDF50-\\uDFFF]|\\uD888[\\uDC00-\\uDFAF]|\\uDB40[\\uDD00-\\uDDEF]"
116].join(""), "");
117var whiteSpace = /[\t-\r \u0085\u00A0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
118
119export {
120  affixSymbol,
121  newLine,
122  terminalMarker,
123  wordSymbolInner,
124  numerical,
125  digitStart,
126  lowerInitial,
127  surrogates,
128  punctuation,
129  word,
130  whiteSpace
131};
132
skills/plain-english/scripts/core/chunk-OJMZKB7F.mjs 469 lines
1// GENERATED by scripts/build-plugin.mjs from src/plugin-core.ts, without comments. Do not edit.
2import {
3  factorySpace,
4  markdownLineEnding,
5  markdownLineEndingOrSpace,
6  markdownSpace
7} from "./chunk-UGEYTODJ.mjs";
8
9var EditMap = class {
10  constructor() {
11    this.map = [];
12  }
13  add(index, remove, add) {
14    addImplementation(this, index, remove, add);
15  }
16  consume(events) {
17    this.map.sort(function(a, b) {
18      return a[0] - b[0];
19    });
20    if (this.map.length === 0) {
21      return;
22    }
23    let index = this.map.length;
24    const vecs = [];
25    while (index > 0) {
26      index -= 1;
27      vecs.push(events.slice(this.map[index][0] + this.map[index][1]), this.map[index][2]);
28      events.length = this.map[index][0];
29    }
30    vecs.push(events.slice());
31    events.length = 0;
32    let slice = vecs.pop();
33    while (slice) {
34      for (const element of slice) {
35        events.push(element);
36      }
37      slice = vecs.pop();
38    }
39    this.map.length = 0;
40  }
41};
42function addImplementation(editMap, at, remove, add) {
43  let index = 0;
44  if (remove === 0 && add.length === 0) {
45    return;
46  }
47  while (index < editMap.map.length) {
48    if (editMap.map[index][0] === at) {
49      editMap.map[index][1] += remove;
50      editMap.map[index][2].push(...add);
51      return;
52    }
53    index += 1;
54  }
55  editMap.map.push([at, remove, add]);
56}
57
58function gfmTableAlign(events, index) {
59  let inDelimiterRow = false;
60  const align = [];
61  while (index < events.length) {
62    const event = events[index];
63    if (inDelimiterRow) {
64      if (event[0] === "enter") {
65        if (event[1].type === "tableContent") {
66          align.push(events[index + 1][1].type === "tableDelimiterMarker" ? "left" : "none");
67        }
68      } else if (event[1].type === "tableContent") {
69        if (events[index - 1][1].type === "tableDelimiterMarker") {
70          const alignIndex = align.length - 1;
71          align[alignIndex] = align[alignIndex] === "left" ? "center" : "right";
72        }
73      } else if (event[1].type === "tableDelimiterRow") {
74        break;
75      }
76    } else if (event[0] === "enter" && event[1].type === "tableDelimiterRow") {
77      inDelimiterRow = true;
78    }
79    index += 1;
80  }
81  return align;
82}
83
84function gfmTable() {
85  return {
86    flow: {
87      null: {
88        name: "table",
89        tokenize: tokenizeTable,
90        resolveAll: resolveTable
91      }
92    }
93  };
94}
95function tokenizeTable(effects, ok, nok) {
96  const self = this;
97  let size = 0;
98  let sizeB = 0;
99  let seen;
100  return start;
101  function start(code) {
102    let index = self.events.length - 1;
103    while (index > -1) {
104      const type = self.events[index][1].type;
105      if (type === "lineEnding" ||  
106      type === "linePrefix") index--;
107      else break;
108    }
109    const tail = index > -1 ? self.events[index][1].type : null;
110    const next = tail === "tableHead" || tail === "tableRow" ? bodyRowStart : headRowBefore;
111    if (next === bodyRowStart && self.parser.lazy[self.now().line]) {
112      return nok(code);
113    }
114    return next(code);
115  }
116  function headRowBefore(code) {
117    effects.enter("tableHead");
118    effects.enter("tableRow");
119    return headRowStart(code);
120  }
121  function headRowStart(code) {
122    if (code === 124) {
123      return headRowBreak(code);
124    }
125    seen = true;
126    sizeB += 1;
127    return headRowBreak(code);
128  }
129  function headRowBreak(code) {
130    if (code === null) {
131      return nok(code);
132    }
133    if (markdownLineEnding(code)) {
134      if (sizeB > 1) {
135        sizeB = 0;
136        self.interrupt = true;
137        effects.exit("tableRow");
138        effects.enter("lineEnding");
139        effects.consume(code);
140        effects.exit("lineEnding");
141        return headDelimiterStart;
142      }
143      return nok(code);
144    }
145    if (markdownSpace(code)) {
146      return factorySpace(effects, headRowBreak, "whitespace")(code);
147    }
148    sizeB += 1;
149    if (seen) {
150      seen = false;
151      size += 1;
152    }
153    if (code === 124) {
154      effects.enter("tableCellDivider");
155      effects.consume(code);
156      effects.exit("tableCellDivider");
157      seen = true;
158      return headRowBreak;
159    }
160    effects.enter("data");
161    return headRowData(code);
162  }
163  function headRowData(code) {
164    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {
165      effects.exit("data");
166      return headRowBreak(code);
167    }
168    effects.consume(code);
169    return code === 92 ? headRowEscape : headRowData;
170  }
171  function headRowEscape(code) {
172    if (code === 92 || code === 124) {
173      effects.consume(code);
174      return headRowData;
175    }
176    return headRowData(code);
177  }
178  function headDelimiterStart(code) {
179    self.interrupt = false;
180    if (self.parser.lazy[self.now().line]) {
181      return nok(code);
182    }
183    effects.enter("tableDelimiterRow");
184    seen = false;
185    if (markdownSpace(code)) {
186      return factorySpace(effects, headDelimiterBefore, "linePrefix", self.parser.constructs.disable.null.includes("codeIndented") ? void 0 : 4)(code);
187    }
188    return headDelimiterBefore(code);
189  }
190  function headDelimiterBefore(code) {
191    if (code === 45 || code === 58) {
192      return headDelimiterValueBefore(code);
193    }
194    if (code === 124) {
195      seen = true;
196      effects.enter("tableCellDivider");
197      effects.consume(code);
198      effects.exit("tableCellDivider");
199      return headDelimiterCellBefore;
200    }
201    return headDelimiterNok(code);
202  }
203  function headDelimiterCellBefore(code) {
204    if (markdownSpace(code)) {
205      return factorySpace(effects, headDelimiterValueBefore, "whitespace")(code);
206    }
207    return headDelimiterValueBefore(code);
208  }
209  function headDelimiterValueBefore(code) {
210    if (code === 58) {
211      sizeB += 1;
212      seen = true;
213      effects.enter("tableDelimiterMarker");
214      effects.consume(code);
215      effects.exit("tableDelimiterMarker");
216      return headDelimiterLeftAlignmentAfter;
217    }
218    if (code === 45) {
219      sizeB += 1;
220      return headDelimiterLeftAlignmentAfter(code);
221    }
222    if (code === null || markdownLineEnding(code)) {
223      return headDelimiterCellAfter(code);
224    }
225    return headDelimiterNok(code);
226  }
227  function headDelimiterLeftAlignmentAfter(code) {
228    if (code === 45) {
229      effects.enter("tableDelimiterFiller");
230      return headDelimiterFiller(code);
231    }
232    return headDelimiterNok(code);
233  }
234  function headDelimiterFiller(code) {
235    if (code === 45) {
236      effects.consume(code);
237      return headDelimiterFiller;
238    }
239    if (code === 58) {
240      seen = true;
241      effects.exit("tableDelimiterFiller");
242      effects.enter("tableDelimiterMarker");
243      effects.consume(code);
244      effects.exit("tableDelimiterMarker");
245      return headDelimiterRightAlignmentAfter;
246    }
247    effects.exit("tableDelimiterFiller");
248    return headDelimiterRightAlignmentAfter(code);
249  }
250  function headDelimiterRightAlignmentAfter(code) {
251    if (markdownSpace(code)) {
252      return factorySpace(effects, headDelimiterCellAfter, "whitespace")(code);
253    }
254    return headDelimiterCellAfter(code);
255  }
256  function headDelimiterCellAfter(code) {
257    if (code === 124) {
258      return headDelimiterBefore(code);
259    }
260    if (code === null || markdownLineEnding(code)) {
261      if (!seen || size !== sizeB) {
262        return headDelimiterNok(code);
263      }
264      effects.exit("tableDelimiterRow");
265      effects.exit("tableHead");
266      return ok(code);
267    }
268    return headDelimiterNok(code);
269  }
270  function headDelimiterNok(code) {
271    return nok(code);
272  }
273  function bodyRowStart(code) {
274    effects.enter("tableRow");
275    return bodyRowBreak(code);
276  }
277  function bodyRowBreak(code) {
278    if (code === 124) {
279      effects.enter("tableCellDivider");
280      effects.consume(code);
281      effects.exit("tableCellDivider");
282      return bodyRowBreak;
283    }
284    if (code === null || markdownLineEnding(code)) {
285      effects.exit("tableRow");
286      return ok(code);
287    }
288    if (markdownSpace(code)) {
289      return factorySpace(effects, bodyRowBreak, "whitespace")(code);
290    }
291    effects.enter("data");
292    return bodyRowData(code);
293  }
294  function bodyRowData(code) {
295    if (code === null || code === 124 || markdownLineEndingOrSpace(code)) {
296      effects.exit("data");
297      return bodyRowBreak(code);
298    }
299    effects.consume(code);
300    return code === 92 ? bodyRowEscape : bodyRowData;
301  }
302  function bodyRowEscape(code) {
303    if (code === 92 || code === 124) {
304      effects.consume(code);
305      return bodyRowData;
306    }
307    return bodyRowData(code);
308  }
309}
310function resolveTable(events, context) {
311  let index = -1;
312  let inFirstCellAwaitingPipe = true;
313  let rowKind = 0;
314  let lastCell = [0, 0, 0, 0];
315  let cell = [0, 0, 0, 0];
316  let afterHeadAwaitingFirstBodyRow = false;
317  let lastTableEnd = 0;
318  let currentTable;
319  let currentBody;
320  let currentCell;
321  const map = new EditMap();
322  while (++index < events.length) {
323    const event = events[index];
324    const token = event[1];
325    if (event[0] === "enter") {
326      if (token.type === "tableHead") {
327        afterHeadAwaitingFirstBodyRow = false;
328        if (lastTableEnd !== 0) {
329          flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);
330          currentBody = void 0;
331          lastTableEnd = 0;
332        }
333        currentTable = {
334          type: "table",
335          start: Object.assign({}, token.start),
336          end: Object.assign({}, token.end)
337        };
338        map.add(index, 0, [["enter", currentTable, context]]);
339      } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
340        inFirstCellAwaitingPipe = true;
341        currentCell = void 0;
342        lastCell = [0, 0, 0, 0];
343        cell = [0, index + 1, 0, 0];
344        if (afterHeadAwaitingFirstBodyRow) {
345          afterHeadAwaitingFirstBodyRow = false;
346          currentBody = {
347            type: "tableBody",
348            start: Object.assign({}, token.start),
349            end: Object.assign({}, token.end)
350          };
351          map.add(index, 0, [["enter", currentBody, context]]);
352        }
353        rowKind = token.type === "tableDelimiterRow" ? 2 : currentBody ? 3 : 1;
354      } else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
355        inFirstCellAwaitingPipe = false;
356        if (cell[2] === 0) {
357          if (lastCell[1] !== 0) {
358            cell[0] = cell[1];
359            currentCell = flushCell(map, context, lastCell, rowKind, void 0, currentCell);
360            lastCell = [0, 0, 0, 0];
361          }
362          cell[2] = index;
363        }
364      } else if (token.type === "tableCellDivider") {
365        if (inFirstCellAwaitingPipe) {
366          inFirstCellAwaitingPipe = false;
367        } else {
368          if (lastCell[1] !== 0) {
369            cell[0] = cell[1];
370            currentCell = flushCell(map, context, lastCell, rowKind, void 0, currentCell);
371          }
372          lastCell = cell;
373          cell = [lastCell[1], index, 0, 0];
374        }
375      }
376    } else if (token.type === "tableHead") {
377      afterHeadAwaitingFirstBodyRow = true;
378      lastTableEnd = index;
379    } else if (token.type === "tableRow" || token.type === "tableDelimiterRow") {
380      lastTableEnd = index;
381      if (lastCell[1] !== 0) {
382        cell[0] = cell[1];
383        currentCell = flushCell(map, context, lastCell, rowKind, index, currentCell);
384      } else if (cell[1] !== 0) {
385        currentCell = flushCell(map, context, cell, rowKind, index, currentCell);
386      }
387      rowKind = 0;
388    } else if (rowKind && (token.type === "data" || token.type === "tableDelimiterMarker" || token.type === "tableDelimiterFiller")) {
389      cell[3] = index;
390    }
391  }
392  if (lastTableEnd !== 0) {
393    flushTableEnd(map, context, lastTableEnd, currentTable, currentBody);
394  }
395  map.consume(context.events);
396  index = -1;
397  while (++index < context.events.length) {
398    const event = context.events[index];
399    if (event[0] === "enter" && event[1].type === "table") {
400      event[1]._align = gfmTableAlign(context.events, index);
401    }
402  }
403  return events;
404}
405function flushCell(map, context, range, rowKind, rowEnd, previousCell) {
406  const groupName = rowKind === 1 ? "tableHeader" : rowKind === 2 ? "tableDelimiter" : "tableData";
407  const valueName = "tableContent";
408  if (range[0] !== 0) {
409    previousCell.end = Object.assign({}, getPoint(context.events, range[0]));
410    map.add(range[0], 0, [["exit", previousCell, context]]);
411  }
412  const now = getPoint(context.events, range[1]);
413  previousCell = {
414    type: groupName,
415    start: Object.assign({}, now),
416    end: Object.assign({}, now)
417  };
418  map.add(range[1], 0, [["enter", previousCell, context]]);
419  if (range[2] !== 0) {
420    const relatedStart = getPoint(context.events, range[2]);
421    const relatedEnd = getPoint(context.events, range[3]);
422    const valueToken = {
423      type: valueName,
424      start: Object.assign({}, relatedStart),
425      end: Object.assign({}, relatedEnd)
426    };
427    map.add(range[2], 0, [["enter", valueToken, context]]);
428    if (rowKind !== 2) {
429      const start = context.events[range[2]];
430      const end = context.events[range[3]];
431      start[1].end = Object.assign({}, end[1].end);
432      start[1].type = "chunkText";
433      start[1].contentType = "text";
434      if (range[3] > range[2] + 1) {
435        const a = range[2] + 1;
436        const b = range[3] - range[2] - 1;
437        map.add(a, b, []);
438      }
439    }
440    map.add(range[3] + 1, 0, [["exit", valueToken, context]]);
441  }
442  if (rowEnd !== void 0) {
443    previousCell.end = Object.assign({}, getPoint(context.events, rowEnd));
444    map.add(rowEnd, 0, [["exit", previousCell, context]]);
445    previousCell = void 0;
446  }
447  return previousCell;
448}
449function flushTableEnd(map, context, index, table, tableBody) {
450  const exits = [];
451  const related = getPoint(context.events, index);
452  if (tableBody) {
453    tableBody.end = Object.assign({}, related);
454    exits.push(["exit", tableBody, context]);
455  }
456  table.end = Object.assign({}, related);
457  exits.push(["exit", table, context]);
458  map.add(index + 1, 0, exits);
459}
460function getPoint(events, index) {
461  const event = events[index];
462  const side = event[0] === "enter" ? "start" : "end";
463  return event[1][side];
464}
465
466export {
467  gfmTable
468};
469