@inkeep/open-knowledge 0.0.0-dev-20260421165805

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/banner-BxlLKtcG.mjs +3 -0
  2. package/dist/chokidar-7l0uFWrj.mjs +4 -0
  3. package/dist/cli.d.mts +1 -0
  4. package/dist/cli.mjs +595 -0
  5. package/dist/colors-BNvy_pwG.mjs +1 -0
  6. package/dist/colors-eCHTjaBL.mjs +2 -0
  7. package/dist/constants-Dx_MrCyB.mjs +2 -0
  8. package/dist/git-handle-B3_Ztqi2.mjs +1 -0
  9. package/dist/git-handle-CQtGq94I.mjs +2 -0
  10. package/dist/index.d.mts +86 -0
  11. package/dist/index.mjs +1 -0
  12. package/dist/init-8JV3QQNU.mjs +230 -0
  13. package/dist/init-B0G3IY-y.mjs +1 -0
  14. package/dist/init-DihXGBlf.mjs +1 -0
  15. package/dist/init-UYi5s8Q6.mjs +5 -0
  16. package/dist/is-object-DVVYT5oa.mjs +2 -0
  17. package/dist/keepalive-D-FSaNO6.mjs +2 -0
  18. package/dist/loader-DqrtMiNp.mjs +3 -0
  19. package/dist/loader-oJkH9tG6.mjs +1 -0
  20. package/dist/open-browser-DhlJOpN3.mjs +2 -0
  21. package/dist/paths-DRfvViD6.mjs +1 -0
  22. package/dist/paths-vKL8Dnp_.mjs +2 -0
  23. package/dist/preview-2OHXLW85.mjs +1 -0
  24. package/dist/preview-DsPtfetJ.mjs +3 -0
  25. package/dist/public/assets/dist-4KUZ8qw_.js +1 -0
  26. package/dist/public/assets/dist-Bvlmbwcy.js +1 -0
  27. package/dist/public/assets/dist-CWsgPYc6.js +13 -0
  28. package/dist/public/assets/dist-D5yBWykF.js +1 -0
  29. package/dist/public/assets/dist-DcQNS1eS.js +1 -0
  30. package/dist/public/assets/dist-DvCIPVI0.js +9 -0
  31. package/dist/public/assets/dist-csWIvcml.js +1 -0
  32. package/dist/public/assets/dist-saWP7AQm.js +1 -0
  33. package/dist/public/assets/go-B8kgVkyB.js +1 -0
  34. package/dist/public/assets/index-Cm78wxqN.js +381 -0
  35. package/dist/public/assets/index-cpkNCk7-.css +1 -0
  36. package/dist/public/assets/inter-cyrillic-ext-wght-normal-BOeWTOD4.woff2 +0 -0
  37. package/dist/public/assets/inter-cyrillic-wght-normal-DqGufNeO.woff2 +0 -0
  38. package/dist/public/assets/inter-greek-ext-wght-normal-DlzME5K_.woff2 +0 -0
  39. package/dist/public/assets/inter-greek-wght-normal-CkhJZR-_.woff2 +0 -0
  40. package/dist/public/assets/inter-latin-ext-wght-normal-DO1Apj_S.woff2 +0 -0
  41. package/dist/public/assets/inter-latin-wght-normal-Dx4kXJAl.woff2 +0 -0
  42. package/dist/public/assets/inter-vietnamese-wght-normal-CBcvBZtf.woff2 +0 -0
  43. package/dist/public/assets/jetbrains-mono-cyrillic-wght-normal-D73BlboJ.woff2 +0 -0
  44. package/dist/public/assets/jetbrains-mono-greek-wght-normal-Bw9x6K1M.woff2 +0 -0
  45. package/dist/public/assets/jetbrains-mono-latin-ext-wght-normal-DBQx-q_a.woff2 +0 -0
  46. package/dist/public/assets/jetbrains-mono-latin-wght-normal-B9CIFXIH.woff2 +0 -0
  47. package/dist/public/assets/jetbrains-mono-vietnamese-wght-normal-Bt-aOZkq.woff2 +0 -0
  48. package/dist/public/assets/shell-BsPlf5L6.js +1 -0
  49. package/dist/public/favicon.svg +5 -0
  50. package/dist/public/index.html +21 -0
  51. package/dist/server-lock-ChItwD14.mjs +2 -0
  52. package/dist/server-lock-nls6eoZ5.mjs +1 -0
  53. package/dist/src-9qc50QcN.mjs +93 -0
  54. package/dist/src-ByMiIIub.mjs +1 -0
  55. package/dist/src-Ds19hvLH.mjs +161 -0
  56. package/dist/src-DvkXxOes.mjs +1 -0
  57. package/dist/start-CfpWFTzI.mjs +2 -0
  58. package/dist/start-DsMb_t62.mjs +1 -0
  59. package/package.json +74 -0
@@ -0,0 +1 @@
1
+ import{i as e,n as t,o as n,r}from"./colors-eCHTjaBL.mjs";export{t as dim,r as error,e as info,n as warning};
@@ -0,0 +1,2 @@
1
+ import e from"picocolors";const t=t=>e.red(t),n=t=>e.yellow(t),r=t=>e.cyan(t),i=t=>e.gray(t),a=t=>e.bold(t);function o(t,n){return e.isColorSupported?`\u001B]8;;${n}\u0007${t}\u001B]8;;\u0007`:t}export{o as a,r as i,i as n,n as o,t as r,a as t};
2
+ //# sourceMappingURL=colors-eCHTjaBL.mjs.map
@@ -0,0 +1,2 @@
1
+ import"./src-Ds19hvLH.mjs";var e=`0.0.0-dev-20260421165805`;const t=`AGENTS.md`,n=`config.yml`,r=`cache`,i=e,a=`open-knowledge`;export{i as a,a as i,r as n,n as r,t};
2
+ //# sourceMappingURL=constants-Dx_MrCyB.mjs.map
@@ -0,0 +1 @@
1
+ import{t as e}from"./git-handle-CQtGq94I.mjs";export{e as createGitInstance};
@@ -0,0 +1,2 @@
1
+ import{resolve as e}from"node:path";import t from"simple-git";const n=new class{_tail=Promise.resolve();enqueue(e){let t=this._tail.then(()=>e());return this._tail=t.catch(()=>void 0),t}};function r(e){return n.enqueue(e)}function i(n,r={}){let{credentialArgs:i=[],gitIndexFile:a}=r,o={};return a&&(o.GIT_INDEX_FILE=e(n,a)),{git:t({baseDir:n,config:i.length>=2?[i[1]]:[],unsafe:{allowUnsafeCredentialHelper:!0}}).env(o),projectDir:n,credentialArgs:i}}export{r as n,i as t};
2
+ //# sourceMappingURL=git-handle-CQtGq94I.mjs.map
@@ -0,0 +1,86 @@
1
+ import { z } from "zod";
2
+
3
+ //#region src/config/schema.d.ts
4
+ declare const ConfigSchema: z.ZodObject<{
5
+ content: z.ZodDefault<z.ZodObject<{
6
+ dir: z.ZodDefault<z.ZodString>;
7
+ include: z.ZodDefault<z.ZodArray<z.ZodString>>;
8
+ exclude: z.ZodDefault<z.ZodArray<z.ZodString>>;
9
+ }, z.core.$strip>>;
10
+ github: z.ZodDefault<z.ZodObject<{
11
+ oauthAppClientId: z.ZodDefault<z.ZodString>;
12
+ }, z.core.$strip>>;
13
+ sync: z.ZodDefault<z.ZodObject<{
14
+ enabled: z.ZodOptional<z.ZodBoolean>;
15
+ pushIntervalSeconds: z.ZodDefault<z.ZodNumber>;
16
+ pullIntervalSeconds: z.ZodDefault<z.ZodNumber>;
17
+ autoCommit: z.ZodDefault<z.ZodBoolean>;
18
+ autoPush: z.ZodDefault<z.ZodBoolean>;
19
+ autoPull: z.ZodDefault<z.ZodBoolean>;
20
+ commitMessage: z.ZodDefault<z.ZodString>;
21
+ }, z.core.$strip>>;
22
+ server: z.ZodDefault<z.ZodObject<{
23
+ port: z.ZodDefault<z.ZodNumber>;
24
+ host: z.ZodDefault<z.ZodString>;
25
+ openOnAgentEdit: z.ZodDefault<z.ZodBoolean>;
26
+ }, z.core.$strip>>;
27
+ persistence: z.ZodDefault<z.ZodObject<{
28
+ debounceMs: z.ZodDefault<z.ZodNumber>;
29
+ maxDebounceMs: z.ZodDefault<z.ZodNumber>;
30
+ }, z.core.$strip>>;
31
+ preview: z.ZodDefault<z.ZodObject<{
32
+ baseUrl: z.ZodOptional<z.ZodURL>;
33
+ }, z.core.$strip>>;
34
+ folders: z.ZodDefault<z.ZodArray<z.ZodObject<{
35
+ match: z.ZodString;
36
+ frontmatter: z.ZodObject<{
37
+ title: z.ZodOptional<z.ZodString>;
38
+ description: z.ZodOptional<z.ZodString>;
39
+ tags: z.ZodOptional<z.ZodArray<z.ZodString>>;
40
+ }, z.core.$strict>;
41
+ }, z.core.$strict>>>;
42
+ mcp: z.ZodDefault<z.ZodObject<{
43
+ autoStart: z.ZodDefault<z.ZodBoolean>;
44
+ tools: z.ZodDefault<z.ZodObject<{
45
+ read_document: z.ZodDefault<z.ZodObject<{
46
+ historyDepth: z.ZodDefault<z.ZodNumber>;
47
+ }, z.core.$strip>>;
48
+ search: z.ZodDefault<z.ZodObject<{
49
+ maxResults: z.ZodDefault<z.ZodNumber>;
50
+ }, z.core.$strip>>;
51
+ }, z.core.$strip>>;
52
+ }, z.core.$strip>>;
53
+ }, z.core.$strip>;
54
+ type Config = z.infer<typeof ConfigSchema>;
55
+ //#endregion
56
+ //#region src/config/loader.d.ts
57
+ interface LoadConfigResult {
58
+ config: Config;
59
+ sources: string[];
60
+ }
61
+ declare function loadConfig(cwd?: string): LoadConfigResult;
62
+ //#endregion
63
+ //#region src/mcp/agent-identity.d.ts
64
+ /**
65
+ * Agent identity — captured from the MCP initialize handshake.
66
+ *
67
+ * Long-lived identity (who is this agent?) is derived from MCP clientInfo
68
+ * and a server-generated connectionId. Per architectural precedent #8:
69
+ * long-lived identity is separate from short-lived session concerns.
70
+ */
71
+ interface AgentIdentity {
72
+ connectionId: string;
73
+ clientInfo?: {
74
+ name: string;
75
+ version: string;
76
+ };
77
+ /** User-provided via AGENT_LABEL env var in .mcp.json */
78
+ label?: string;
79
+ /** Derived: label || clientInfo.name || "Agent" */
80
+ displayName: string;
81
+ /** Derived: label ?? clientInfo?.name ?? connectionId — stable seed hierarchy */
82
+ colorSeed: string;
83
+ }
84
+ //#endregion
85
+ export { type AgentIdentity, type Config, ConfigSchema, type LoadConfigResult, loadConfig };
86
+ //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs ADDED
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./loader-DqrtMiNp.mjs";import"./src-DvkXxOes.mjs";export{e as ConfigSchema,t as loadConfig};
@@ -0,0 +1,230 @@
1
+ import{E as e}from"./src-Ds19hvLH.mjs";import{n as t,r as n,t as r}from"./constants-Dx_MrCyB.mjs";import{existsSync as i,mkdirSync as a,readFileSync as o,realpathSync as s,writeFileSync as c}from"node:fs";import{join as l,resolve as u}from"node:path";const d=`<!-- open-knowledge:begin -->`,f=`<!-- open-knowledge:end -->`,p=/<!-- open-knowledge:begin -->[\s\S]*?<!-- open-knowledge:end -->/,m=`# ${e}/ — Open Knowledge config
2
+
3
+ This directory holds Open Knowledge's configuration for this project. It's **not** where content lives — content lives wherever \`content.dir\` + \`content.include\` in \`config.yml\` point. The default is the repo root with \`**/*.md\`, so any markdown file in the project is fair game. Inspect \`config.yml\` for the actual setting.
4
+
5
+ ## What's in here
6
+
7
+ - \`config.yml\` — workspace config (content dir, include/exclude globs, MCP tool settings)
8
+ - \`AGENTS.md\` — this file
9
+ - \`cache/\` — derived data (gitignored)
10
+
11
+ No scaffolded content directories. Organize knowledge wherever makes sense for the project — existing docs trees, topic-grouped subfolders, whatever. \`exec("ls <dir>")\` + per-file enrichment gives you a live overview of any directory on demand; there's no INDEX.md catalog to maintain.
12
+
13
+ ## Navigation — prefer \`exec\` for all reads
14
+
15
+ \`exec\` is the primary MCP read surface. It runs a read-only bash command (cat, ls, grep, find, head, tail, wc, sort, uniq, cut — pipes OK) and returns raw stdout plus enriched metadata per file: title, description, tags, backlink count, recent shadow-repo activity with agent-vs-human attribution, and project git history.
16
+
17
+ Examples (adapt paths to this project's layout):
18
+
19
+ - Read a file: \`exec("cat <path>.md")\` — contents + full rich enrichment
20
+ - List a directory: \`exec("ls <dir>")\` — names + slim per-file enrichment
21
+ - Search: \`exec("grep -rn <term> <dir> | head -5")\` — matches + enrichment on matched files
22
+
23
+ Typed tools (\`read_document\`, \`search\`, \`list_documents\`, etc.) remain available as "Typed call sites (advanced)" — use them when you need the typed \`structuredContent\` shape for programmatic parsing.
24
+
25
+ ## Suggested lifecycle (optional pattern)
26
+
27
+ Projects that want an explicit knowledge-maturation flow can organize as three tiers **relative to the content directory** — create the subfolders only when you need them:
28
+
29
+ 1. **External sources** (e.g., \`external-sources/\` under \`content.dir\`) — raw content fetched from URLs, PDFs. No analysis, just preservation. Use the \`ingest\` MCP tool.
30
+ 2. **Research** (e.g., \`research/\` under \`content.dir\`) — analysis and synthesis. Provisional findings, trade-offs, open questions. Use the \`research\` MCP tool.
31
+ 3. **Articles** (e.g., \`articles/\` under \`content.dir\`) — canonical knowledge. Use the \`consolidate\` MCP tool to promote research → articles once decisions are made.
32
+
33
+ This is a pattern, not a requirement. Projects with existing layouts (\`specs/\`, \`reports/\`, \`docs/\`, etc.) should use those; the lifecycle exists as mental scaffolding, not as enforced filesystem structure.
34
+
35
+ ## Linking — use \`[[wiki-links]]\` aggressively
36
+
37
+ **When writing or editing any document, link liberally to every other document it relates to.** Open Knowledge's value compounds with link density: backlinks surface cross-document context in every read, graph queries (\`get_hubs\` / \`get_orphans\`) reveal structure, and agents navigate the knowledge base by following links. A document with no outbound links is an island.
38
+
39
+ **Defaults when writing:**
40
+
41
+ - Every noun-phrase that names another document is a link. Write \`[[Page Title]]\` instead of plain prose when mentioning concepts, projects, decisions, or entities that have (or should have) their own page. Redlinks are fine — they signal "this should exist."
42
+ - Cross-link siblings: when creating a document in a folder, link to the 2–3 most related neighbors.
43
+ - Link back to sources instead of re-summarizing — the reader can follow.
44
+ - Prefer \`[[Page]]\` over Markdown \`[text](./page.md)\`. Wiki-links resolve by docName and participate in the backlinks index; Markdown links to other wiki files don't.
45
+
46
+ **Rule of thumb:** if a human reader would want to click a term to learn more, make it a link. Err on the side of too many links.
47
+
48
+ ## Frontmatter Conventions
49
+
50
+ Open Knowledge has two metadata surfaces that merge at read time:
51
+
52
+ **Per-file frontmatter.** Every \`.md\` file that's part of the knowledge base should have YAML frontmatter:
53
+
54
+ \`\`\`yaml
55
+ ---
56
+ title: Article Title (required)
57
+ description: Brief summary (required)
58
+ tags:
59
+ - relevant
60
+ - tags
61
+ ---
62
+ \`\`\`
63
+
64
+ **Folder-level defaults via \`config.yml\` \`folders:\`.** Declare per-folder title/description/tags keyed by glob \`match:\` — see \`config.yml\` for the commented example. Rules apply in declaration order (later matches override earlier scalars), tags concat + dedup across all matching rules, and the file's own frontmatter always wins per-scalar. Folder defaults fill in blanks.
65
+
66
+ Folder metadata lives in \`config.yml\`, **not** in content files — this is intentionally different from the rejected \`INDEX.md\`-inside-content pattern. The merge is computed on every \`exec("ls <dir>")\` / \`read_document\` / \`search\` call and is never written back to disk.
67
+
68
+ ## Scaffolding (first-time setup)
69
+
70
+ This directory was scaffolded by running \`open-knowledge init\` (or \`npx @inkeep/open-knowledge init\`) in the project root. That command:
71
+
72
+ 1. Creates \`${e}/\` (config-only — no content subdirs)
73
+ 2. Writes \`AGENTS.md\`, \`.gitignore\`, and \`config.yml\`
74
+ 3. Registers the Open Knowledge MCP server in \`.mcp.json\` at the repo root
75
+
76
+ If you're onboarding a new project and \`${e}/\` doesn't exist yet, run \`open-knowledge init\` from a terminal.
77
+
78
+ ## Tools
79
+
80
+ - **\`exec\`** — primary read surface (cat / ls / grep / find / pipes) with enriched output
81
+ - **\`init-content\`** — bootstrap this knowledge base from the codebase
82
+ - **\`ingest\`** — capture an external source as raw reference material
83
+ - **\`research\`** — gather sources + write provisional findings
84
+ - **\`consolidate\`** — promote research into canonical articles
85
+ - **Writes** via \`write_document\` / \`edit_document\` — route through the server so shadow-repo attribution (agent vs human) is captured
86
+ - **Graph queries** via \`get_backlinks\`, \`get_forward_links\`, \`get_orphans\`, \`get_hubs\`
87
+
88
+ These tools are discovered via the standard MCP \`tools/list\` handshake and work in any MCP client (Claude Code, Claude Desktop, Cursor, VS Code, Windsurf, Codex, etc.). \`open-knowledge init\` registers the MCP server in every editor's config for you — Claude Desktop and Windsurf use project-qualified keys like \`open-knowledge-<project>\` so one config file can serve multiple projects on the same machine. Claude Desktop requires a full quit + relaunch to pick up new MCP servers; Windsurf hot-reloads.
89
+ `,h=`# Open Knowledge — workspace configuration
90
+ #
91
+ # This file overrides built-in defaults for this workspace. Every key below
92
+ # is commented out and shows its current default value. Uncomment any key
93
+ # to override it.
94
+ #
95
+ # Precedence (lowest -> highest):
96
+ # Built-in defaults
97
+ # -> ~/${e}/config.yml (user defaults)
98
+ # -> ./${e}/config.yml (this file)
99
+ #
100
+ # Schema reference: packages/cli/src/config/schema.ts
101
+
102
+
103
+ # --- Content ---------------------------------------------------------------
104
+ # dir: where the CRDT editor reads/writes documents. Relative to the project
105
+ # root (the directory containing ${e}/), NOT to this file.
106
+ #
107
+ # include/exclude: glob patterns for tracked content files. Relative to the
108
+ # content directory (content.dir).
109
+ #
110
+ # content:
111
+ # dir: .
112
+ # include:
113
+ # - "**/*.md"
114
+ # exclude: []
115
+
116
+
117
+ # --- Server ----------------------------------------------------------------
118
+ # HTTP/WebSocket listener for the Hocuspocus server + static React app.
119
+ #
120
+ # openOnAgentEdit: when true, the browser opens automatically the first time
121
+ # an agent writes to the knowledge base in this server session. Debounced to
122
+ # one open per boot. Useful for pairing with Claude Code — you see the edit
123
+ # land live. Leave false for headless/CI.
124
+ #
125
+ # server:
126
+ # port: 3000
127
+ # host: localhost
128
+ # openOnAgentEdit: false
129
+
130
+
131
+ # --- Persistence -----------------------------------------------------------
132
+ # How aggressively CRDT updates are flushed to disk.
133
+ # persistence:
134
+ # debounceMs: 2000
135
+ # maxDebounceMs: 10000
136
+
137
+
138
+ # --- Folders: per-folder frontmatter defaults -------------------------------
139
+ #
140
+ # TL;DR glob gotcha: \`**\` is ONLY a multi-segment wildcard when it is a
141
+ # standalone path segment. \`foo-**\` behaves like \`foo-*\` (single segment, NOT
142
+ # descendants). Use \`foo/**\` or \`foo-*/**\` to match descendants.
143
+ #
144
+ # Declare title/description/tags defaults keyed by glob \`match:\`. Rules merge
145
+ # with a file's own frontmatter at read time:
146
+ # - Per scalar (title, description): the FILE wins when declared; folder
147
+ # rule fills in blanks.
148
+ # - Tags: concatenated across ALL matching rules (in declaration order) with
149
+ # file tags last; first-occurrence preserved on dedup.
150
+ # - Evaluation is positional — LATER rules in this array override earlier
151
+ # rules for scalars. Put general rules first, specific rules last.
152
+ #
153
+ # Picomatch glob cheatsheet:
154
+ # \`match: 'foo'\` — matches ONLY the folder \`foo\` itself
155
+ # \`match: 'foo/**'\` — matches \`foo\` AND all descendants (files + dirs)
156
+ # \`match: 'foo-*'\` — matches \`foo-1\`, \`foo-bar\` (single segment)
157
+ # \`match: 'foo-**'\` — behaves like \`foo-*\` (NOT multi-segment); see
158
+ # TL;DR above. Use \`foo-*/**\` if you want
159
+ # \`foo-X\` plus its descendants.
160
+ #
161
+ # Example:
162
+ # folders:
163
+ # - match: 'specs/**'
164
+ # frontmatter:
165
+ # title: Specifications
166
+ # description: Feature specifications and design documents
167
+ # tags: [spec]
168
+ # - match: 'specs/2026-*/**'
169
+ # frontmatter:
170
+ # title: 2026 Specifications
171
+ # tags: [2026]
172
+ `,g="**Preview before edit (REQUIRED).** You MUST follow this sequence every time you call `write_document` or `edit_document`:\n1. Call `get_preview_url` to obtain the browser URL for the target doc.\n - If it returns `null`, the UI isn't running yet. Start it with `open-knowledge ui` from a terminal — or in Claude Code, call `preview_start(\"open-knowledge-ui\")` (the `open-knowledge init` command scaffolds this `.claude/launch.json` entry, so it's ready to go). `open-knowledge ui` auto-spawns the collab server in the background; you don't need to run `open-knowledge start` separately. Then call `get_preview_url` again — the UI writes a lock file that this tool reads.\n - NEVER guess or manually construct the preview URL — always use the URL returned by `get_preview_url`.\n2. Open that URL in your preview browser so the user can see the document.\n3. Only then call `write_document` / `edit_document` — the CRDT edit will stream live into the already-open editor.\n\nNEVER call `write_document` or `edit_document` without first navigating the preview browser to the doc. The user expects to watch every edit land in real time. Write-tool responses include `previewUrl` (when resolvable) and a `warning` when no client is currently attached to the doc.",_=`${d}
173
+ ## Open Knowledge
174
+
175
+ This repo uses Open Knowledge — collaborative markdown via MCP. **\`${e}/config.yml\`** (with optional \`~/${e}/config.yml\`; CLI/env may override) is the **path contract**: \`content.dir\` is the root for relative paths; \`content.include\` lists globs that **add** markdown; \`content.exclude\` lists globs that **remove** paths. Nothing else defines scope — not folder names, not "docs vs code." \`.gitignore\` still applies. When MCP is connected, the server's instructions echo the **resolved** \`dir\` / \`include\` / \`exclude\` for this session — treat that table and the YAML as two views of the same rules.
176
+
177
+ **Default mental model (no jargon):** unless this project narrowed \`content.include\`, **every \`.md\` and \`.mdx\` under \`content.dir\`** is an Open Knowledge document — including under \`specs/\`, \`reports/\`, \`docs/\`, etc. If \`content.include\` is non-default, read \`config.yml\` once per turn so you do not mis-classify paths.
178
+
179
+ **STOP — your host's built-in file tools on in-scope \`.md\` / \`.mdx\`.** When this workspace has Open Knowledge MCP configured (for example via root \`.mcp.json\`), you **must not** reach for native tools on in-scope markdown. Same failure mode as native \`Edit\` on them: no frontmatter, no backlinks, no shadow-repo activity, no recent-edit signal. The ban is broader than just \`Read\` / \`Grep\` / \`Glob\` — it names every common rationalization:
180
+
181
+ - **Native \`Read\` / \`Grep\` / \`Glob\` on in-scope \`.md\` / \`.mdx\`** — the original case.
182
+ - **\`Bash ls\` / \`Bash find\` / \`Bash cat\` on dirs containing in-scope markdown** — use \`exec("ls …")\` / \`exec("find … -name '*.md'")\` / \`exec("cat …")\` instead. Native returns bare names; \`exec\` returns frontmatter, backlink counts, and recent-activity per child.
183
+ - **Glob patterns that target markdown** (\`**/*.md\`, \`**/SPEC.md\`, or any dir known to be markdown-heavy like \`specs/**\`, \`reports/**\`, \`stories/**\`, \`projects/**\`, \`docs/**\`) — use \`exec\` with \`find\`, or \`list_documents({ dir })\`.
184
+ - **Dispatching the Explore / general-purpose subagent for markdown-heavy exploration** — subagents use native \`Read\` / \`Grep\` / \`Glob\` internally and bypass Open Knowledge entirely. Do markdown exploration yourself via \`exec\` / \`search\`. Subagents remain appropriate for **source-code** exploration (\`.ts\`, \`.py\`, configs, etc.).
185
+
186
+ **MCP wiring varies by client:** Claude Code, Codex, Cursor, Windsurf, VS Code–class clients, and others surface MCP differently — server labels are user-defined; tools may not appear as a top-level symbol named \`exec\`. **If Open Knowledge is registered**, route markdown reads through its \`exec\` / \`search\` / \`read_document\` tools using **your client's documented MCP invocation** (including any generic "call MCP tool" flow). **That counts as available.** Not seeing \`exec\` in a flat tool list is **not** the escape hatch.
187
+
188
+ **Escape hatch (narrow).** Native \`Read\` / \`Grep\` / \`Glob\` on \`.md\` / \`.mdx\` is allowed **only** when no Open Knowledge MCP server is registered for this project, **or** immediately after you **tried** an MCP call and it failed — then start a user-visible sentence with \`Open Knowledge MCP unavailable:\`. Never use the hatch because you skipped your client's MCP path.
189
+
190
+ **Reads and searches on markdown:** Open Knowledge \`exec\` (or \`read_document\` / \`search\`) — same payloads whether your client invokes them directly or through MCP. Examples: \`exec("cat docs/auth.md")\`, \`exec("ls reports/")\`, \`exec("grep -rn karpathy specs/ | head -10")\`.
191
+
192
+ **Listings too.** \`exec("ls <dir>/")\` is how you list a directory — it returns per-child frontmatter, recursive markdown counts, and the most-recently-updated doc per subdir. Plain \`Bash ls\` returns just names.
193
+
194
+ **Anti-patterns at a glance:**
195
+
196
+ | Task | Don't | Do |
197
+ | -------------------------------- | ---------------------------- | ----------------------------------------------- |
198
+ | List a markdown-heavy dir | \`Bash: ls specs/\` | \`exec("ls specs/")\` |
199
+ | Find all SPEC.md files | \`Glob: **/SPEC.md\` | \`exec("find specs -name SPEC.md")\` |
200
+ | Summarize specs across the repo | \`Agent(Explore): "…"\` | \`exec("head -25 specs/*/SPEC.md")\` + \`search\` |
201
+ | Search a phrase across markdown | \`Grep: "pattern" *.md\` | \`search({ query: "pattern" })\` |
202
+ | Read an individual spec | \`Read: specs/foo/SPEC.md\` | \`read_document({ path: "specs/foo/SPEC.md" })\` |
203
+
204
+ **Source code and everything else** (\`.ts\`, \`.py\`, \`package.json\`, …): native \`Read\` / \`Grep\` / \`Glob\`.
205
+
206
+ **Writing.** Edits to in-scope \`.md\` / \`.mdx\` go through \`write_document\` / \`edit_document\` only. Native \`Edit\` / \`sed\` land as anonymous \`upstream\` imports — you lose agent attribution in the shadow repo.
207
+
208
+ ${g}
209
+
210
+ **No screenshots after edits.** Do NOT take \`preview_screenshot\` after every \`edit_document\` / \`write_document\`. Trust the CRDT tool response as confirmation the edit landed. Only screenshot when debugging a visual issue or when explicitly asked.
211
+
212
+ **Linking.** Link liberally with \`[[wiki-links]]\` — every noun-phrase naming another document should be a link; redlinks are fine and signal "this should exist." Backlink density is how this knowledge base stays navigable for the next agent.
213
+
214
+ - **What goes in the brackets:** the target's **docName** — folder path + filename without \`.md\` / \`.mdx\` (e.g. the file \`guides/auth-setup.md\` is linked as \`[[guides/auth-setup]]\`). NOT the human-readable title, NOT \`title:\` frontmatter, NOT \`aliases:\`. Wiki-links are absolute from the content root, never relative — \`[[foo]]\` means root-level \`foo.md\`, never \`guides/foo.md\` from inside \`guides/\`. Cross-folder links always need the full path.
215
+ - **Display text different from the key:** \`[[guides/auth-setup|Auth Setup]]\` — pipe separator, target on the left, rendered label on the right. Anchors work the same way: \`[[guides/auth-setup#quickstart]]\`, or combined: \`[[guides/auth-setup#quickstart|see the quickstart]]\`.
216
+ - **Verify before walking away:** after writing a doc, call \`get_dead_links({ sourceDocNames: ['your/doc/name'] })\` — every unresolved bracket-target in that doc is listed. Fix or accept the redlinks deliberately. The editor's red-underline visual tolerates a slug fallback (\`[[Auth Setup]]\` may look resolved if \`auth-setup.md\` exists at root), but the backlink graph is strict-exact — trust \`get_dead_links\`, not the visual.
217
+
218
+ **Organize by folders, not hub files.** Folders are the organizational unit — group related docs in a shared folder and let the directory listing do the cataloging. Per-folder metadata (title, description, tags) lives in \`.open-knowledge/config.yml\` under the \`folders:\` key (glob \`match:\` + frontmatter defaults that merge with each file's own frontmatter at read time). Don't maintain an \`INDEX.md\` / \`README.md\` hub file inside a folder solely to catalog its children — \`exec("ls <folder>")\` returns the same view live, with per-file frontmatter + backlink counts.
219
+
220
+ **Server must be running.** If \`write_document\` or \`edit_document\` returns a "Hocuspocus server is not running" error, start it with \`open-knowledge start\` (via Bash) and retry. NEVER fall back to native \`Edit\` / \`Write\` for in-scope markdown — always use the MCP write tools so edits go through the CRDT layer with proper attribution.
221
+
222
+ **Non-markdown files.** Use native \`Read\` / \`Edit\` / \`Grep\` / \`Bash\` for source code, configs, and anything outside the path contract in \`config.yml\`: under \`content.dir\`, matching \`content.include\`, not removed by \`content.exclude\` or \`.gitignore\`.
223
+ ${f}`;function v(e,t,n){let a=[r,...n??[]],u=new Set,d=[];for(let n of a){let r=l(e,n),a=i(r),f=a?s(r):r;if(u.has(f)){d.push({file:n,path:r,action:`skipped-symlink`});continue}if(u.add(f),!a){c(r,`${_}\n`,`utf-8`),d.push({file:n,path:r,action:`created`});continue}let m=o(r,`utf-8`),h=p.test(m);if(h&&!t){d.push({file:n,path:r,action:`skipped-existing`});continue}if(h){c(r,m.replace(p,_),`utf-8`),d.push({file:n,path:r,action:`replaced`});continue}c(r,`${m.replace(/\n*$/,``)}\n\n${_}\n`,`utf-8`),d.push({file:n,path:r,action:`appended`})}return d}function y(e,t){return i(e)?!1:(c(e,t,`utf-8`),!0)}function b(t){let n=l(t,`.gitignore`),r=`# Open Knowledge — local editor config (not tracked upstream)\n${e}/\n`;if(!i(n))return c(n,r,`utf-8`),`created`;let a=o(n,`utf-8`),s=new Set([e,`${e}/`,`/${e}`,`/${e}/`]);return a.split(`
224
+ `).map(e=>e.trim()).some(e=>s.has(e))?`already-present`:(c(n,`${a}${a.length===0||a.endsWith(`
225
+ `)?``:`
226
+ `}${a.length>0&&!a.endsWith(`
227
+
228
+ `)?`
229
+ `:``}${r}`,`utf-8`),`appended`)}const x=[{name:r,content:m},{name:`.gitignore`,content:`${t}/\nserver.lock\nui.lock\nsync-state.json\n`},{name:n,content:h}];function S(n){let r=u(n,e),i=[],o=[];a(r,{recursive:!0}),a(l(r,t),{recursive:!0});for(let e of x)y(l(r,e.name),e.content)?i.push(e.name):o.push(e.name);return{created:i,skipped:o}}export{b as a,g as i,d as n,S as o,f as r,v as s,_ as t};
230
+ //# sourceMappingURL=init-8JV3QQNU.mjs.map
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./init-8JV3QQNU.mjs";export{o as CLAUDE_MD_SECTION,n as OK_MARKER_BEGIN,i as OK_MARKER_END,t as PREVIEW_GUIDANCE,e as ensureOkGitignoredAtRoot,r as initContent,a as upsertRootInstructions};
@@ -0,0 +1 @@
1
+ import{a as e,i as t,n,r,t as i}from"./init-UYi5s8Q6.mjs";export{i as detectInstalledEditors,n as formatInitResult,r as initCommand,t as parseEditorFlag,e as runInit};
@@ -0,0 +1,5 @@
1
+ import{E as e}from"./src-Ds19hvLH.mjs";import"./constants-Dx_MrCyB.mjs";import{o as t,s as n}from"./init-8JV3QQNU.mjs";import{t as r}from"./preview-DsPtfetJ.mjs";import{o as i}from"./colors-eCHTjaBL.mjs";import{t as a}from"./is-object-DVVYT5oa.mjs";import{Command as o}from"commander";import{existsSync as s,mkdirSync as c,readFileSync as l,realpathSync as u,writeFileSync as d}from"node:fs";import{homedir as f}from"node:os";import{basename as p,dirname as m,isAbsolute as h,join as g,relative as _,resolve as v}from"node:path";import{parse as y,stringify as b}from"smol-toml";const x=`open-knowledge`,S=`open-knowledge`,C=1e3;function w(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``);return t===``?`project`:t}function T(e){if(Array.isArray(e)){for(let t=0;t<e.length-1;t++)if(e[t]===`--cwd`){let n=e[t+1];return typeof n==`string`?n:void 0}}}function E(e){try{return u(e)}catch(t){if(t instanceof Error&&`code`in t&&t.code===`ENOENT`)return e;throw t}}function D(e){return a(e)?T(e.args)===void 0:!1}function O(e,t,n={}){let r=n.detectLegacy===!0,i=E(t);for(let[t,n]of Object.entries(e)){if(!t.startsWith(x)||!a(n))continue;let e=T(n.args);if(e!==void 0&&E(e)===i)return{key:t,existingEntry:n}}let o=`${x}-${w(p(i))}`;if(r){let t=e[S];if(t!==void 0&&D(t)){let n=k(e,o);return{key:n.key,existingEntry:t,migratedFromKey:S,...n.disambiguatedFrom===void 0?{}:{disambiguatedFrom:n.disambiguatedFrom}}}}if(e[o]===void 0)return{key:o,existingEntry:void 0};let s=k(e,o);return{key:s.key,existingEntry:void 0,...s.disambiguatedFrom===void 0?{}:{disambiguatedFrom:s.disambiguatedFrom}}}function k(e,t){if(e[t]===void 0)return{key:t};for(let n=2;n<=C;n++){let r=`${t}-${n}`;if(e[r]===void 0)return{key:r,disambiguatedFrom:t}}throw Error(`Unable to pick a unique server key: ${C} suffixes of ${t} are all taken.`)}const A=[`claude`,`cursor`,`vscode`,`codex`,`windsurf`,`claude-desktop`],j=[`@inkeep/open-knowledge`,`mcp`],M={claude:{id:`claude`,label:`Claude Code`,configPath:e=>g(e,`.mcp.json`),format:`json`,topLevelKey:`mcpServers`,buildEntry:e=>({command:`npx`,args:j}),scope:`project`,instructionsPath:e=>g(e,`CLAUDE.md`)},cursor:{id:`cursor`,label:`Cursor`,configPath:e=>g(e,`.cursor`,`mcp.json`),format:`json`,topLevelKey:`mcpServers`,buildEntry:e=>({command:`npx`,args:j}),scope:`project`},vscode:{id:`vscode`,label:`VS Code`,configPath:e=>g(e,`.vscode`,`mcp.json`),format:`json`,topLevelKey:`servers`,buildEntry:e=>({type:`stdio`,command:`npx`,args:j}),scope:`project`},codex:{id:`codex`,label:`Codex`,configPath:e=>g(e,`.codex`,`config.toml`),format:`toml`,topLevelKey:`mcp_servers`,buildEntry:e=>({command:`npx`,args:j}),scope:`project`},windsurf:{id:`windsurf`,label:`Windsurf`,configPath:(e,t)=>g(t??f(),`.codeium`,`windsurf`,`mcp_config.json`),format:`json`,topLevelKey:`mcpServers`,buildEntry:e=>({command:`npx`,args:[...j,`--cwd`,e]}),resolveServerKey:(e,t)=>O(e,t,{detectLegacy:!0}),scope:`global`},"claude-desktop":{id:`claude-desktop`,label:`Claude Desktop`,configPath:(e,t)=>{let n=process.platform;if(n===`darwin`)return g(t??f(),`Library`,`Application Support`,`Claude`,`claude_desktop_config.json`);if(n===`win32`)return g(process.env.APPDATA??g(t??f(),`AppData`,`Roaming`),`Claude`,`claude_desktop_config.json`);throw Error(`Claude Desktop is not available on ${n}. Supported: macOS, Windows.`)},format:`json`,topLevelKey:`mcpServers`,buildEntry:e=>({command:`npx`,args:[...j,`--cwd`,e]}),resolveServerKey:(e,t)=>O(e,t,{detectLegacy:!1}),scope:`global`}};function N(e){let t=e.filter(e=>!(e in M));if(t.length>0)throw Error(`Unknown editor(s): ${t.join(`, `)}. Valid options: ${A.join(`, `)}`);return e.map(e=>M[e])}function P(e){if(!s(e))return{};let t=l(e,`utf-8`).trim();if(t===``)return{};try{let n=JSON.parse(t);if(a(n))return n;throw Error(`${e} root must be a JSON object`)}catch(t){throw t instanceof SyntaxError?Error(`${e} contains invalid JSON: ${t.message}`):t}}function F(e){if(!s(e))return{};let t=l(e,`utf-8`).trim();if(t===``)return{};try{let n=y(t);if(a(n))return n;throw Error(`${e} root must be a TOML table`)}catch(t){throw Error(`${e} contains invalid TOML: ${t instanceof Error?t.message:String(t)}`)}}function I(e,t){c(m(e),{recursive:!0}),d(e,`${JSON.stringify(t,null,2)}\n`,`utf-8`)}function L(e,t){c(m(e),{recursive:!0});let n=b(t);d(e,n.endsWith(`
2
+ `)?n:`${n}\n`,`utf-8`)}const R=`0.0.1`,z=`open-knowledge-ui`;function B(e,t){let n=[];e.runtimeExecutable!==t.runtimeExecutable&&n.push(`runtimeExecutable`);let r=e.runtimeArgs;return Array.isArray(r)&&r.length===t.runtimeArgs.length&&r.every((e,n)=>e===t.runtimeArgs[n])||n.push(`runtimeArgs`),e.port!==t.port&&n.push(`port`),n}function V(e,t){let n=g(e,`.claude`,`launch.json`),r={name:z,runtimeExecutable:`npx`,runtimeArgs:[`@inkeep/open-knowledge`,`ui`],port:3e3};try{if(!s(n))return c(m(n),{recursive:!0}),d(n,`${JSON.stringify({version:R,configurations:[r]},null,2)}\n`,`utf-8`),{action:`created`,configPath:n};let e=l(n,`utf-8`).trim(),i=e?JSON.parse(e):{};if(!a(i))return{action:`failed`,configPath:n,error:`launch.json root is not an object`};let o=Array.isArray(i.configurations)?i.configurations:[],u=o.findIndex(e=>a(e)&&e.name===z);if(u>=0&&!t){let e=o[u],t=B(e,r);return t.length>0?{action:`skipped-stale`,configPath:n,staleFields:t}:{action:`skipped-existing`,configPath:n}}u>=0?o[u]=r:o.push(r);let f={...i,version:i.version??R,configurations:o};return d(n,`${JSON.stringify(f,null,2)}\n`,`utf-8`),{action:`merged`,configPath:n}}catch(e){return{action:`failed`,configPath:n,error:e instanceof Error?e.message:String(e)}}}function H(e,t,n,r){let i;try{i=e.configPath(t,r)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:``,error:t instanceof Error?t.message:String(t)}}let a;try{a=e.format===`toml`?F(i):P(i)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:i,error:t instanceof Error?t.message:String(t)}}let o=a[e.topLevelKey]??{},s;try{s=e.resolveServerKey?.(o,t)??{key:`open-knowledge`,existingEntry:o[`open-knowledge`]}}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:i,error:t instanceof Error?t.message:String(t)}}let{key:c,existingEntry:l,disambiguatedFrom:u,migratedFromKey:d}=s;if(l!==void 0&&!n&&d===void 0)return{editorId:e.id,label:e.label,action:`skipped-existing`,configPath:i,serverKey:c};let f={...o};d!==void 0&&d!==c&&delete f[d],f[c]=e.buildEntry(t);let p={...a,[e.topLevelKey]:f};try{e.format===`toml`?L(i,p):I(i,p)}catch(t){return{editorId:e.id,label:e.label,action:`failed`,configPath:i,error:t instanceof Error?t.message:String(t)}}let m=d===void 0&&l===void 0?`written`:`overwritten`;return{editorId:e.id,label:e.label,action:m,configPath:i,serverKey:c,...u===void 0?{}:{disambiguatedFrom:u},...d===void 0?{}:{migratedFromKey:d}}}function U(e={}){let r=v(e.cwd??process.cwd()),i;try{i=t(r)}catch(e){return{contentCreated:[],contentSkipped:[],editors:[],rootInstructions:[],mcpAction:`failed`,mcpPath:g(r,`.mcp.json`),mcpError:`Content scaffolding failed: ${e instanceof Error?e.message:String(e)}`}}let a=e.editors??[`claude`],o=N(a),s=[];for(let t of o){if(e.mcp===!1){let n=``;try{n=t.configPath(r,e.home)}catch{}s.push({editorId:t.id,label:t.label,action:`skipped-flag`,configPath:n});continue}s.push(H(t,r,e.force??!1,e.home))}let c=a.includes(`claude`)&&e.mcp!==!1?V(r,e.force??!1):void 0,l=o.map(e=>e.instructionsPath?.(r)).filter(e=>e!==void 0).map(e=>h(e)?_(r,e):e),u=e.rootInstructions===!1?[]:n(r,e.force??!1,l),d=s.find(e=>e.editorId===`claude`)??s[0]??{action:`skipped-flag`,configPath:g(r,`.mcp.json`)};return{contentCreated:i.created,contentSkipped:i.skipped,editors:s,rootInstructions:u,launchJson:c,mcpAction:d.action,mcpPath:d.configPath,mcpError:`error`in d?d.error:void 0}}function W(e,t){try{let n=l(e.configPath,`utf-8`).trim();if(n===``)return;let r=JSON.parse(n);if(!a(r))return;let i=r.mcpServers;if(!a(i))return;let o=i[t];if(!a(o))return;let s=o.args;if(!Array.isArray(s))return;let c=s.indexOf(`--cwd`);if(c<0||c===s.length-1)return;let u=s[c+1];return typeof u==`string`?u:void 0}catch{return}}function G(t,n){let a=[],o=g(n,e);if(t.contentCreated.length>0?(a.push(`Content scaffolded at ${o}/`),a.push(` Created: ${t.contentCreated.join(`, `)}`)):a.push(`Content already present at ${o}/`),t.contentSkipped.length>0&&a.push(` Skipped (already exist): ${t.contentSkipped.join(`, `)}`),a.push(``),t.editors.length===0)t.mcpError&&a.push(`Warning: ${t.mcpError}`);else{let e=t.editors.some(e=>e.action===`written`||e.action===`overwritten`),o=t.editors.some(e=>e.action===`failed`);if(t.editors.every(e=>e.action===`skipped-flag`))a.push(`MCP config not written — use without --no-mcp to configure editors`);else{a.push(`MCP server configuration:`);for(let e of t.editors){let t=e.configPath.startsWith(n)?_(n,e.configPath):e.configPath.replace(/^\/Users\/[^/]+/,`~`),r=` `.repeat(Math.max(1,14-e.label.length)),i=e.editorId===`claude-desktop`&&(e.action===`written`||e.action===`overwritten`)?` — quit and relaunch Claude Desktop to activate`:``;switch(e.action){case`written`:if(a.push(` ${e.label}${r}${t} registered${i}`),e.disambiguatedFrom!==void 0){let t=W(e,e.disambiguatedFrom),n=t?`(${e.disambiguatedFrom} is already registered for ${t})`:`(${e.disambiguatedFrom} is already registered for a different project)`;a.push(` ${` `.repeat(e.label.length)}${r}${n}`)}break;case`overwritten`:e.migratedFromKey===void 0?a.push(` ${e.label}${r}${t} overwritten (--force)${i}`):a.push(` ${e.label}${r}${t} overwritten — migrated legacy ${e.migratedFromKey} → ${e.serverKey??``}${i}`);break;case`skipped-existing`:{let n=e.serverKey,i=n!==void 0&&n!==`open-knowledge`?` (${n})`:``;a.push(` ${e.label}${r}${t} already configured${i}`);break}case`failed`:a.push(` ${e.label}${r}${t} FAILED: ${e.error}`);break;case`skipped-flag`:break}}}if(o&&(a.push(``),a.push(`For failed editors, add the MCP server entry manually. See:`),a.push(` https://github.com/inkeep/open-knowledge#mcp-setup`)),t.launchJson){let e=t.launchJson,r=e.configPath.startsWith(n)?_(n,e.configPath):e.configPath;switch(e.action){case`created`:a.push(` launch.json ${r} created (preview_start("${z}") ready)`);break;case`merged`:a.push(` launch.json ${r} merged open-knowledge entry`);break;case`skipped-existing`:a.push(` launch.json ${r} already has open-knowledge entry`);break;case`skipped-stale`:a.push(` launch.json ${r} ${i(`⚠ existing open-knowledge entry is out of date`)}`),e.staleFields&&e.staleFields.length>0&&a.push(` ${i(`${e.staleFields.join(`, `)} differ from current defaults`)}`),a.push(` ${i(`re-run with --force to update`)}`);break;case`failed`:a.push(` launch.json ${r} FAILED: ${e.error}`);break}}if(t.rootInstructions.length>0){let e=t.rootInstructions.filter(e=>e.action!==`skipped-symlink`);if(e.length>0){a.push(``),a.push(`Root instructions:`);for(let t of e){let e=t.path.startsWith(n)?_(n,t.path):t.path,r=` `.repeat(Math.max(1,14-t.file.length));switch(t.action){case`created`:a.push(` ${t.file}${r}${e} created`);break;case`appended`:a.push(` ${t.file}${r}${e} appended Open Knowledge section`);break;case`replaced`:a.push(` ${t.file}${r}${e} replaced Open Knowledge section (--force)`);break;case`skipped-existing`:a.push(` ${t.file}${r}${e} already has Open Knowledge section`);break}}}}if(t.preview?(a.push(``),a.push(r(t.preview,n))):t.previewWarning&&(a.push(``),a.push(`Content preview unavailable: ${t.previewWarning}`)),e){let e=t.editors.filter(e=>e.action===`written`||e.action===`overwritten`).map(e=>e.label);a.push(``),a.push(`Next steps:`),a.push(` 1. Open your editor (${e.join(` / `)})`),a.push(` 2. Approve the MCP server when prompted`),a.push(` 3. The knowledge base is ready — use the three workflow tools:`),a.push(` - mcp__open-knowledge__init-content — bootstrap articles from the codebase`),a.push(` - mcp__open-knowledge__ingest — capture an external source`),a.push(` - mcp__open-knowledge__research — gather sources and write findings`)}}return a.join(`
3
+ `)}function K(e){switch(e){case`claude_desktop`:return`claude-desktop`;default:return e}}function q(e){if(e===`all`)return[...A];let t=e.split(`,`).map(e=>e.trim()).map(K);return N(t),t}function J(e,t){let n=[];for(let r of A){let i=M[r],a;try{a=i.configPath(e,t)}catch{continue}s(m(a))&&n.push(r)}return n}function Y(){return new o(`init`).description(`Scaffold ${e}/ in the current directory and register the MCP server for your editor(s)`).option(`--mcp`,`Register the MCP server for selected editors (default: true)`,!0).option(`--no-mcp`,`Scaffold the ${e}/ directory but do not touch MCP config`).option(`--force`,`Overwrite existing open-knowledge MCP entries (default: skip)`).option(`--editor <editors>`,`Target editor(s): ${A.join(`, `)}, all (comma-separated) — default: all detected editors (non-TTY) / preselects detected editors (TTY)`).action(async e=>{let t=process.cwd(),n;if(e.editor)try{n=q(e.editor)}catch(e){process.stderr.write(`${e instanceof Error?e.message:String(e)}\n`),process.exitCode=1;return}else if(e.mcp!==!1&&process.stdin.isTTY){let{multiselect:e,isCancel:r}=await import(`@clack/prompts`),i=new Set(J(t));i.size===0&&process.stdout.write(`No MCP-capable editors detected — select manually, or cancel and use --editor <all|${A.join(`|`)}>.\n`);let a=await e({message:`Which tools do you use? (space to toggle, enter to confirm)`,options:A.flatMap(e=>{let n=M[e],r;try{r=n.scope===`global`?n.configPath(t).replace(/^\/Users\/[^/]+/,`~`):_(t,n.configPath(t))}catch{return[]}return[{value:e,label:n.label,hint:r,initialValue:i.has(e)}]}),required:!0});if(r(a)){process.stdout.write(`Init cancelled.
4
+ `);return}n=a}else if(n=J(t),n.length===0){process.stderr.write(`No MCP-capable editors detected. Use --editor <all|${A.join(`|`)}> to force.\n`),process.exitCode=1;return}let r=U({cwd:t,mcp:e.mcp,force:e.force,editors:n});try{let{previewContent:e}=await import(`./preview-2OHXLW85.mjs`),{loadConfig:n}=await import(`./loader-oJkH9tG6.mjs`),{resolveContentDir:i}=await import(`./paths-DRfvViD6.mjs`),{config:a}=n(t);r.preview=e({projectDir:t,contentDir:i(a,t),include:a.content.include,exclude:a.content.exclude})}catch(e){r.previewWarning=e instanceof Error?e.message:String(e)}process.stdout.write(`${G(r,t)}\n`),(r.editors.some(e=>e.action===`failed`)||r.mcpAction===`failed`)&&(process.exitCode=1)})}export{U as a,q as i,G as n,Y as r,J as t};
5
+ //# sourceMappingURL=init-UYi5s8Q6.mjs.map
@@ -0,0 +1,2 @@
1
+ function e(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{e as t};
2
+ //# sourceMappingURL=is-object-DVVYT5oa.mjs.map
@@ -0,0 +1,2 @@
1
+ function e(e){let t=e.scheduler??{setTimeout:(e,t)=>globalThis.setTimeout(e,t),clearTimeout:e=>globalThis.clearTimeout(e)},n=e.initialBackoffMs??1e3,r=e.maxBackoffMs??3e4,i=e.createWebSocket??(e=>new WebSocket(e)),a=null,o=null,s=!1,c=n,l=t=>{try{e.log?.(t)}catch{}};function u(){if(s)return;o!==null&&t.clearTimeout(o);let e=c;c=Math.min(c*2,r),o=t.setTimeout(()=>{o=null,d().catch(e=>l(`keepalive reconnect failed: ${String(e)}`))},e)}async function d(){if(s)return;let t;try{t=await e.resolveWsUrl()}catch(e){l(`keepalive resolveWsUrl threw: ${String(e)}`),u();return}if(!t){u();return}let r=`${t}/collab/keepalive?pid=${process.pid}`;try{a=i(r)}catch(e){l(`keepalive ctor failed (${r}): ${String(e)}`),a=null,u();return}a.addEventListener(`open`,()=>{l(`keepalive connected: ${t}`),c=n}),a.addEventListener(`close`,()=>{s||(l(`keepalive disconnected — scheduling reconnect`),a=null,u())}),a.addEventListener(`error`,()=>{})}return queueMicrotask(()=>{d().catch(e=>l(`keepalive initial connect failed: ${String(e)}`))}),{close:()=>{if(!s&&(s=!0,o!==null&&(t.clearTimeout(o),o=null),a)){try{a.close()}catch{}a=null}},isConnected:()=>a!==null&&a.readyState===1}}export{e as startKeepalive};
2
+ //# sourceMappingURL=keepalive-D-FSaNO6.mjs.map
@@ -0,0 +1,3 @@
1
+ import{E as e}from"./src-Ds19hvLH.mjs";import{r as t}from"./constants-Dx_MrCyB.mjs";import{t as n}from"./is-object-DVVYT5oa.mjs";import{existsSync as r,readFileSync as i}from"node:fs";import{homedir as a}from"node:os";import{resolve as o}from"node:path";import{parse as s}from"yaml";import{z as c}from"zod";const l=c.object({title:c.string().optional(),description:c.string().optional(),tags:c.array(c.string()).optional()}).strict(),u=c.object({match:c.string().min(1,"`match` must be a non-empty glob pattern (e.g. 'specs/**' or 'reports/*/**')"),frontmatter:l}).strict(),d=c.object({content:c.object({dir:c.string().default(`.`),include:c.array(c.string()).min(1).default([`**/*.md`,`**/*.mdx`]),exclude:c.array(c.string()).default([])}).default({dir:`.`,include:[`**/*.md`,`**/*.mdx`],exclude:[]}),github:c.object({oauthAppClientId:c.string().default(`Ov23liqlSd0V1MwR6rhI`)}).default({oauthAppClientId:`Ov23liqlSd0V1MwR6rhI`}),sync:c.object({enabled:c.boolean().optional(),pushIntervalSeconds:c.number().int().min(1).default(60),pullIntervalSeconds:c.number().int().min(1).default(30),autoCommit:c.boolean().default(!0),autoPush:c.boolean().default(!0),autoPull:c.boolean().default(!0),commitMessage:c.string().default(`auto`)}).default({pushIntervalSeconds:60,pullIntervalSeconds:30,autoCommit:!0,autoPush:!0,autoPull:!0,commitMessage:`auto`}),server:c.object({port:c.number().int().min(0).max(65535).default(0),host:c.string().regex(/^[\w.\-:]+$/,`Invalid hostname`).default(`localhost`),openOnAgentEdit:c.boolean().default(!1)}).default({port:0,host:`localhost`,openOnAgentEdit:!1}),persistence:c.object({debounceMs:c.number().int().min(0).default(2e3),maxDebounceMs:c.number().int().min(0).default(1e4)}).default({debounceMs:2e3,maxDebounceMs:1e4}),preview:c.object({baseUrl:c.url().optional()}).default({}),folders:c.array(u).default([]),mcp:c.object({autoStart:c.boolean().default(!0),tools:c.object({read_document:c.object({historyDepth:c.number().int().min(0).default(5)}).default({historyDepth:5}),search:c.object({maxResults:c.number().int().min(1).default(50)}).default({maxResults:50})}).default({read_document:{historyDepth:5},search:{maxResults:50}})}).default({autoStart:!0,tools:{read_document:{historyDepth:5},search:{maxResults:50}}})});function f(e,t){let r={...e};for(let i of Object.keys(t)){let a=e[i],o=t[i];n(o)&&n(a)?r[i]=f(a,o):o!==void 0&&(r[i]=o)}return r}function p(e){if(!r(e))return null;try{let t=s(i(e,`utf-8`));return n(t)?t:null}catch(t){return console.warn(`[config] Failed to parse ${e}: ${t instanceof Error?t.message:t}`),null}}function m(n){let r=n??process.cwd(),i=[],s=o(a(),e,t),c={},l=p(s);l&&(c=f(c,l),i.push(s));let u=o(r,e,t),m=p(u);m&&(c=f(c,m),i.push(u));let h=d.safeParse(c);if(!h.success){let e=h.error.issues.map(e=>` ${e.path.join(`.`)}: ${e.message}`);throw Error(`Invalid configuration:\n${e.join(`
2
+ `)}`)}return{config:h.data,sources:i}}export{d as n,m as t};
3
+ //# sourceMappingURL=loader-DqrtMiNp.mjs.map
@@ -0,0 +1 @@
1
+ import{t as e}from"./loader-DqrtMiNp.mjs";export{e as loadConfig};
@@ -0,0 +1,2 @@
1
+ import{execFile as e}from"node:child_process";function t(t){e(process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,process.platform===`win32`?[`/c`,`start`,``,t]:[t],e=>{e&&console.warn(`Could not auto-open browser (${e.message}); visit ${t} manually`)})}export{t as openBrowser};
2
+ //# sourceMappingURL=open-browser-DhlJOpN3.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./paths-vKL8Dnp_.mjs";export{t as resolveContentDir,e as resolveLockDir};
@@ -0,0 +1,2 @@
1
+ import{E as e}from"./src-Ds19hvLH.mjs";import"./constants-Dx_MrCyB.mjs";import{resolve as t}from"node:path";function n(e,n){return t(n,e.content.dir)}function r(n){return t(n,e)}export{r as n,n as t};
2
+ //# sourceMappingURL=paths-vKL8Dnp_.mjs.map
@@ -0,0 +1 @@
1
+ import{n as e,t}from"./preview-DsPtfetJ.mjs";export{t as formatPreviewBlock,e as previewContent};
@@ -0,0 +1,3 @@
1
+ import{E as e}from"./src-Ds19hvLH.mjs";import"./constants-Dx_MrCyB.mjs";import{l as t}from"./src-9qc50QcN.mjs";import{existsSync as n,lstatSync as r,readdirSync as i,realpathSync as a,statSync as o}from"node:fs";import{join as s,relative as c}from"node:path";function l(e){let{projectDir:n,contentDir:l,include:u,exclude:d,sampleCap:f=5}=e,p=[],m=[];try{r(l)}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[`cannot access content directory ${l}: ${e instanceof Error?e.message:String(e)}`]}}let h;try{h=t({projectDir:n,contentDir:l,includePatterns:u,excludePatterns:d})}catch(e){return{totalCount:0,sample:[],contentDir:l,include:u,exclude:d,warnings:[e instanceof Error?e.message:String(e)]}}function g(e){let t;try{t=i(e,{withFileTypes:!0})}catch(t){let n=t instanceof Error?t.message:String(t);p.push(`could not read directory ${c(l,e)||`.`}: ${n}`);return}for(let n of t){let t=s(e,n.name);if(n.isSymbolicLink()){let e;try{e=a(t)}catch(e){let n=e.code;n===`ENOENT`||n===`ELOOP`?p.push(`broken or cyclic symlink: ${c(l,t)}`):p.push(`cannot resolve symlink ${c(l,t)}: ${n??`unknown error`}`);continue}let n;try{n=o(e)}catch{continue}if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}else if(n.isDirectory()){let e=c(l,t);if(h.isDirExcluded(e))continue;g(t)}else if(n.isFile()){let e=c(l,t);if(h.isExcluded(e))continue;m.push(e)}}}return g(l),{totalCount:m.length,sample:m.slice(0,f),contentDir:l,include:u,exclude:d,warnings:p}}function u(t,r){let i=[],a=c(r,t.contentDir),o=a===``?`./`:`./${a}`;i.push(`Content:`),i.push(` Found ${t.totalCount} markdown files in ${o}`);let l=t.include.join(`, `),u=t.exclude.length>0?t.exclude.join(`, `):`(none)`;if(i.push(` Scope: include=${l} exclude=${u}`),t.sample.length>0){let e=t.sample.join(`, `),n=t.totalCount>t.sample.length?`, …`:``;i.push(` Sample: ${e}${n}`)}if(t.warnings.length>0)for(let e of t.warnings)i.push(` Warning: ${e}`);return i.push(``),n(s(r,`.open-knowledge`,`config.yml`))?(i.push(` To adjust, edit ${e}/config.yml:`),i.push(` content:`),i.push(` include: ${JSON.stringify(t.include)}`),i.push(` exclude: ${JSON.stringify(t.exclude)}`)):(i.push(" Run `open-knowledge init` to scaffold config, then adjust:"),i.push(` ${e}/config.yml → content.include / content.exclude`)),i.push(``),i.push(` Re-check anytime: open-knowledge preview`),i.join(`
2
+ `)}export{l as n,u as t};
3
+ //# sourceMappingURL=preview-DsPtfetJ.mjs.map
@@ -0,0 +1 @@
1
+ import{$t as e,At as t,H as n,Jt as r,Kt as i,Mt as a,Rt as o,Vt as s,Wt as c,Xt as l,Y as u,Yt as d,Zt as f,an as p,en as m,gt as h,ht as ee,in as g,ln as _,mt as v,nn as y,on as b,rn as x,tn as S,vt as te,wt as C,yt as ne}from"./dist-CWsgPYc6.js";var w=class{constructor(e,t,n,r){this.state=e,this.pos=t,this.explicit=n,this.view=r,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=u(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),n=Math.max(t.from,this.pos-250),r=t.text.slice(n-t.from,this.pos-t.from),i=r.search(ce(e,!1));return i<0?null:{from:n+i,to:this.pos,text:r.slice(i)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,n){e==`abort`&&this.abortListeners&&(this.abortListeners.push(t),n&&n.onDocChange&&(this.abortOnDocChange=!0))}};function re(e){let t=Object.keys(e).join(``),n=/\w/.test(t);return n&&(t=t.replace(/\w/g,``)),`[${n?`\\w`:``}${t.replace(/[^\w\s]/g,`\\$&`)}]`}function ie(e){let t=Object.create(null),n=Object.create(null);for(let{label:r}of e){t[r[0]]=!0;for(let e=1;e<r.length;e++)n[r[e]]=!0}let r=re(t)+re(n)+`*$`;return[RegExp(`^`+r),new RegExp(r)]}function ae(e){let t=e.map(e=>typeof e==`string`?{label:e}:e),[n,r]=t.every(e=>/^\w+$/.test(e.label))?[/\w*$/,/\w+$/]:ie(t);return e=>{let i=e.matchBefore(r);return i||e.explicit?{from:i?i.from:e.pos,options:t,validFor:n}:null}}function oe(e,t){return n=>{for(let t=u(n.state).resolveInner(n.pos,-1);t;t=t.parent){if(e.indexOf(t.name)>-1)return null;if(t.type.isTop)break}return t(n)}}var se=class{constructor(e,t,n,r){this.completion=e,this.source=t,this.match=n,this.score=r}};function T(e){return e.selection.main.from}function ce(e,t){let{source:n}=e,r=t&&n[0]!=`^`,i=n[n.length-1]!=`$`;return!r&&!i?e:RegExp(`${r?`^`:``}(?:${n})${i?`$`:``}`,e.flags??(e.ignoreCase?`i`:``))}var E=s.define();function le(e,t,n,r){let{main:a}=e.selection,o=n-a.from,s=r-a.from;return{...e.changeByRange(c=>{if(c!=a&&n!=r&&e.sliceDoc(c.from+o,c.from+s)!=e.sliceDoc(n,r))return{range:c};let l=e.toText(t);return{changes:{from:c.from+o,to:r==a.from?c.to:c.from+s,insert:l},range:i.cursor(c.from+o+l.length)}}),scrollIntoView:!0,userEvent:`input.complete`}}var D=new WeakMap;function ue(e){if(!Array.isArray(e))return e;let t=D.get(e);return t||D.set(e,t=ae(e)),t}var O=m.define(),k=m.define(),de=class{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t<e.length;){let n=g(e,t),r=p(n);this.chars.push(n);let i=e.slice(t,t+r),a=i.toUpperCase();this.folded.push(g(a==i?i.toLowerCase():a,0)),t+=r}this.astral=e.length!=this.chars.length}ret(e,t){return this.score=e,this.matched=t,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:t,folded:n,any:r,precise:i,byWord:a}=this;if(t.length==1){let r=g(e,0),i=p(r),a=i==e.length?0:-100;if(r!=t[0])if(r==n[0])a+=-200;else return null;return this.ret(a,[0,i])}let o=e.indexOf(this.pattern);if(o==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let s=t.length,c=0;if(o<0){for(let i=0,a=Math.min(e.length,200);i<a&&c<s;){let a=g(e,i);(a==t[c]||a==n[c])&&(r[c++]=i),i+=p(a)}if(c<s)return null}let l=0,u=0,d=!1,f=0,m=-1,h=-1,ee=/[a-z]/.test(e),v=!0;for(let r=0,c=Math.min(e.length,200),y=0;r<c&&u<s;){let c=g(e,r);o<0&&(l<s&&c==t[l]&&(i[l++]=r),f<s&&(c==t[f]||c==n[f]?(f==0&&(m=r),h=r+1,f++):f=0));let b,x=c<255?c>=48&&c<=57||c>=97&&c<=122?2:+(c>=65&&c<=90):(b=_(c))==b.toLowerCase()?b==b.toUpperCase()?0:2:1;(!r||x==1&&ee||y==0&&x!=0)&&(t[u]==c||n[u]==c&&(d=!0)?a[u++]=r:a.length&&(v=!1)),y=x,r+=p(c)}return u==s&&a[0]==0&&v?this.result(-100+(d?-200:0),a,e):f==s&&m==0?this.ret(-200-e.length+(h==e.length?0:-100),[0,h]):o>-1?this.ret(-700-e.length,[o,o+this.pattern.length]):f==s?this.ret(-900-e.length,[m,h]):u==s?this.result(-100+(d?-200:0)+-700+(v?0:-1100),a,e):t.length==2?null:this.result((r[0]?-700:0)+-200+-1100,r,e)}result(e,t,n){let r=[],i=0;for(let e of t){let t=e+(this.astral?p(g(n,e)):1);i&&r[i-1]==e?r[i-1]=t:(r[i++]=e,r[i++]=t)}return this.ret(e-n.length,r)}},fe=class{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let t=e.slice(0,this.pattern.length),n=t==this.pattern?0:t.toLowerCase()==this.folded?-200:null;return n==null?null:(this.matched=[0,t.length],this.score=n+(e.length==this.pattern.length?0:-100),this)}},A=r.define({combine(e){return b(e,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>``,optionClass:()=>``,aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:pe,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>n=>j(e(n),t(n)),optionClass:(e,t)=>n=>j(e(n),t(n)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function j(e,t){return e?t?e+` `+t:e:t}function pe(e,t,n,r,i,a){let o=e.textDirection==ee.RTL,s=o,c=!1,l=`top`,u,d,f=t.left-i.left,p=i.right-t.right,m=r.right-r.left,h=r.bottom-r.top;if(s&&f<Math.min(m,p)?s=!1:!s&&p<Math.min(m,f)&&(s=!0),m<=(s?f:p))u=Math.max(i.top,Math.min(n.top,i.bottom-h))-t.top,d=Math.min(400,s?f:p);else{c=!0,d=Math.min(400,(o?t.right:i.right-t.left)-30);let e=i.bottom-t.bottom;e>=h||e>t.top?u=n.bottom-t.top:(l=`bottom`,u=t.bottom-n.top)}let g=(t.bottom-t.top)/a.offsetHeight,_=(t.right-t.left)/a.offsetWidth;return{style:`${l}: ${u/g}px; max-width: ${d/_}px`,class:`cm-completionInfo-`+(c?o?`left-narrow`:`right-narrow`:s?`left`:`right`)}}var M=m.define();function me(e){let t=e.addToOptions.slice();return e.icons&&t.push({render(e){let t=document.createElement(`div`);return t.classList.add(`cm-completionIcon`),e.type&&t.classList.add(...e.type.split(/\s+/g).map(e=>`cm-completionIcon-`+e)),t.setAttribute(`aria-hidden`,`true`),t},position:20}),t.push({render(e,t,n,r){let i=document.createElement(`span`);i.className=`cm-completionLabel`;let a=e.displayLabel||e.label,o=0;for(let e=0;e<r.length;){let t=r[e++],n=r[e++];t>o&&i.appendChild(document.createTextNode(a.slice(o,t)));let s=i.appendChild(document.createElement(`span`));s.appendChild(document.createTextNode(a.slice(t,n))),s.className=`cm-completionMatchedText`,o=n}return o<a.length&&i.appendChild(document.createTextNode(a.slice(o))),i},position:50},{render(e){if(!e.detail)return null;let t=document.createElement(`span`);return t.className=`cm-completionDetail`,t.textContent=e.detail,t},position:80}),t.sort((e,t)=>e.position-t.position).map(e=>e.render)}function N(e,t,n){if(e<=n)return{from:0,to:e};if(t<0&&(t=0),t<=e>>1){let e=Math.floor(t/n);return{from:e*n,to:(e+1)*n}}let r=Math.floor((e-t)/n);return{from:e-(r+1)*n,to:e-r*n}}var he=class{constructor(e,t,n){this.view=e,this.stateField=t,this.applyCompletion=n,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:e=>this.placeInfo(e),key:this},this.space=null,this.currentClass=``;let r=e.state.field(t),{options:i,selected:a}=r.open,o=e.state.facet(A);this.optionContent=me(o),this.optionClass=o.optionClass,this.tooltipClass=o.tooltipClass,this.range=N(i.length,a,o.maxRenderedOptions),this.dom=document.createElement(`div`),this.dom.className=`cm-tooltip-autocomplete`,this.updateTooltipClass(e.state),this.dom.addEventListener(`mousedown`,n=>{let{options:r}=e.state.field(t).open;for(let t=n.target,i;t&&t!=this.dom;t=t.parentNode)if(t.nodeName==`LI`&&(i=/-(\d+)$/.exec(t.id))&&+i[1]<r.length){this.applyCompletion(e,r[+i[1]]),n.preventDefault();return}if(n.target==this.list){let t=this.list.classList.contains(`cm-completionListIncompleteTop`)&&n.clientY<this.list.firstChild.getBoundingClientRect().top?this.range.from-1:this.list.classList.contains(`cm-completionListIncompleteBottom`)&&n.clientY>this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;t!=null&&(e.dispatch({effects:M.of(t)}),n.preventDefault())}}),this.dom.addEventListener(`focusout`,t=>{let n=e.state.field(this.stateField,!1);n&&n.tooltip&&e.state.facet(A).closeOnBlur&&t.relatedTarget!=e.contentDOM&&e.dispatch({effects:k.of(null)})}),this.showOptions(i,r.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener(`scroll`,()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){let t=e.state.field(this.stateField),n=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),t!=n){let{options:r,selected:i,disabled:a}=t.open;(!n.open||n.open.options!=r)&&(this.range=N(r.length,i,e.state.facet(A).maxRenderedOptions),this.showOptions(r,t.id)),this.updateSel(),a!=n.open?.disabled&&this.dom.classList.toggle(`cm-tooltip-autocomplete-disabled`,!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let e of this.currentClass.split(` `))e&&this.dom.classList.remove(e);for(let e of t.split(` `))e&&this.dom.classList.add(e);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected<this.range.from||t.selected>=this.range.to)&&(this.range=N(t.options.length,t.selected,this.view.state.facet(A).maxRenderedOptions),this.showOptions(t.options,e.id));let n=this.updateSelectedOption(t.selected);if(n){this.destroyInfo();let{completion:r}=t.options[t.selected],{info:i}=r;if(!i)return;let o=typeof i==`string`?document.createTextNode(i):i(r);if(!o)return;`then`in o?o.then(t=>{t&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(t,r)}).catch(e=>a(this.view.state,e,`completion info`)):(this.addInfoPane(o,r),n.setAttribute(`aria-describedby`,this.info.id))}}addInfoPane(e,t){this.destroyInfo();let n=this.info=document.createElement(`div`);if(n.className=`cm-tooltip cm-completionInfo`,n.id=`cm-completionInfo-`+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)n.appendChild(e),this.infoDestroy=null;else{let{dom:t,destroy:r}=e;n.appendChild(t),this.infoDestroy=r||null}this.dom.appendChild(n),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let n=this.list.firstChild,r=this.range.from;n;n=n.nextSibling,r++)n.nodeName!=`LI`||!n.id?r--:r==e?n.hasAttribute(`aria-selected`)||(n.setAttribute(`aria-selected`,`true`),t=n):n.hasAttribute(`aria-selected`)&&(n.removeAttribute(`aria-selected`),n.removeAttribute(`aria-describedby`));return t&&_e(this.list,t),t}measureInfo(){let e=this.dom.querySelector(`[aria-selected]`);if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),n=this.info.getBoundingClientRect(),r=e.getBoundingClientRect(),i=this.space;if(!i){let e=this.dom.ownerDocument.documentElement;i={left:0,top:0,right:e.clientWidth,bottom:e.clientHeight}}return r.top>Math.min(i.bottom,t.bottom)-10||r.bottom<Math.max(i.top,t.top)+10?null:this.view.state.facet(A).positionInfo(this.view,t,r,n,i,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className=`cm-tooltip cm-completionInfo `+(e.class||``)):this.info.style.cssText=`top: -1e6px`)}createListBox(e,t,n){let r=document.createElement(`ul`);r.id=t,r.setAttribute(`role`,`listbox`),r.setAttribute(`aria-expanded`,`true`),r.setAttribute(`aria-label`,this.view.state.phrase(`Completions`)),r.addEventListener(`mousedown`,e=>{e.target==r&&e.preventDefault()});let i=null;for(let a=n.from;a<n.to;a++){let{completion:o,match:s}=e[a],{section:c}=o;if(c){let e=typeof c==`string`?c:c.name;if(e!=i&&(a>n.from||n.from==0))if(i=e,typeof c!=`string`&&c.header)r.appendChild(c.header(c));else{let t=r.appendChild(document.createElement(`completion-section`));t.textContent=e}}let l=r.appendChild(document.createElement(`li`));l.id=t+`-`+a,l.setAttribute(`role`,`option`);let u=this.optionClass(o);u&&(l.className=u);for(let e of this.optionContent){let t=e(o,this.view.state,this.view,s);t&&l.appendChild(t)}}return n.from&&r.classList.add(`cm-completionListIncompleteTop`),n.to<e.length&&r.classList.add(`cm-completionListIncompleteBottom`),r}destroyInfo(){this.info&&=(this.infoDestroy&&this.infoDestroy(),this.info.remove(),null)}destroy(){this.destroyInfo()}};function ge(e,t){return n=>new he(n,e,t)}function _e(e,t){let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=n.height/e.offsetHeight;r.top<n.top?e.scrollTop-=(n.top-r.top)/i:r.bottom>n.bottom&&(e.scrollTop+=(r.bottom-n.bottom)/i)}function P(e){return(e.boost||0)*100+(e.apply?10:0)+(e.info?5:0)+ +!!e.type}function ve(e,t){let n=[],r=null,i=null,a=e=>{n.push(e);let{section:t}=e.completion;if(t){r||=[];let e=typeof t==`string`?t:t.name;r.some(t=>t.name==e)||r.push(typeof t==`string`?{name:e}:t)}},o=t.facet(A);for(let r of e)if(r.hasResult()){let e=r.result.getMatch;if(r.result.filter===!1)for(let t of r.result.options)a(new se(t,r.source,e?e(t):[],1e9-n.length));else{let n=t.sliceDoc(r.from,r.to),s,c=o.filterStrict?new fe(n):new de(n);for(let t of r.result.options)if(s=c.match(t.label)){let n=t.displayLabel?e?e(t,s.matched):[]:s.matched,o=s.score+(t.boost||0);if(a(new se(t,r.source,n,o)),typeof t.section==`object`&&t.section.rank===`dynamic`){let{name:e}=t.section;i||=Object.create(null),i[e]=Math.max(o,i[e]||-1e9)}}}}if(r){let e=Object.create(null),t=0,a=(e,t)=>(e.rank===`dynamic`&&t.rank===`dynamic`?i[t.name]-i[e.name]:0)||(typeof e.rank==`number`?e.rank:1e9)-(typeof t.rank==`number`?t.rank:1e9)||(e.name<t.name?-1:1);for(let n of r.sort(a))t-=1e5,e[n.name]=t;for(let t of n){let{section:n}=t.completion;n&&(t.score+=e[typeof n==`string`?n:n.name])}}let s=[],c=null,l=o.compareCompletions;for(let e of n.sort((e,t)=>t.score-e.score||l(e.completion,t.completion))){let t=e.completion;!c||c.label!=t.label||c.detail!=t.detail||c.type!=null&&t.type!=null&&c.type!=t.type||c.apply!=t.apply||c.boost!=t.boost?s.push(e):P(e.completion)>P(c)&&(s[s.length-1]=e),c=e.completion}return s}var ye=class e{constructor(e,t,n,r,i,a){this.options=e,this.attrs=t,this.tooltip=n,this.timestamp=r,this.selected=i,this.disabled=a}setSelected(t,n){return t==this.selected||t>=this.options.length?this:new e(this.options,F(n,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,n,r,i,a,o){if(i&&!o&&t.some(e=>e.isPending))return i.setDisabled();let s=ve(t,n);if(!s.length)return i&&t.some(e=>e.isPending)?i.setDisabled():null;let c=n.facet(A).selectOnOpen?0:-1;if(i&&i.selected!=c&&i.selected!=-1){let e=i.options[i.selected].completion;for(let t=0;t<s.length;t++)if(s[t].completion==e){c=t;break}}return new e(s,F(r,c),{pos:t.reduce((e,t)=>t.hasResult()?Math.min(e,t.from):e,1e8),create:De,above:a.aboveCursor},i?i.timestamp:Date.now(),c,!1)}map(t){return new e(this.options,this.attrs,{...this.tooltip,pos:t.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new e(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}},be=class e{constructor(e,t,n){this.active=e,this.id=t,this.open=n}static start(){return new e(we,`cm-ac-`+Math.floor(Math.random()*2e6).toString(36),null)}update(t){let{state:n}=t,r=n.facet(A),i=(r.override||n.languageDataAt(`autocomplete`,T(n)).map(ue)).map(e=>(this.active.find(t=>t.source==e)||new I(e,+!!this.active.some(e=>e.state!=0))).update(t,r));i.length==this.active.length&&i.every((e,t)=>e==this.active[t])&&(i=this.active);let a=this.open,o=t.effects.some(e=>e.is(R));a&&t.docChanged&&(a=a.map(t.changes)),t.selection||i.some(e=>e.hasResult()&&t.changes.touchesRange(e.from,e.to))||!xe(i,this.active)||o?a=ye.build(i,n,this.id,a,r,o):a&&a.disabled&&!i.some(e=>e.isPending)&&(a=null),!a&&i.every(e=>!e.isPending)&&i.some(e=>e.hasResult())&&(i=i.map(e=>e.hasResult()?new I(e.source,0):e));for(let e of t.effects)e.is(M)&&(a&&=a.setSelected(e.value,this.id));return i==this.active&&a==this.open?this:new e(i,this.id,a)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Se:Ce}};function xe(e,t){if(e==t)return!0;for(let n=0,r=0;;){for(;n<e.length&&!e[n].hasResult();)n++;for(;r<t.length&&!t[r].hasResult();)r++;let i=n==e.length,a=r==t.length;if(i||a)return i==a;if(e[n++].result!=t[r++].result)return!1}}var Se={"aria-autocomplete":`list`},Ce={};function F(e,t){let n={"aria-autocomplete":`list`,"aria-haspopup":`listbox`,"aria-controls":e};return t>-1&&(n[`aria-activedescendant`]=e+`-`+t),n}var we=[];function Te(e,t){if(e.isUserEvent(`input.complete`)){let n=e.annotation(E);if(n&&t.activateOnCompletion(n))return 12}let n=e.isUserEvent(`input.type`);return n&&t.activateOnTyping?5:n?1:e.isUserEvent(`delete.backward`)?2:e.selection?8:e.docChanged?16:0}var I=class e{constructor(e,t,n=!1){this.source=e,this.state=t,this.explicit=n}hasResult(){return!1}get isPending(){return this.state==1}update(t,n){let r=Te(t,n),i=this;(r&8||r&16&&this.touches(t))&&(i=new e(i.source,0)),r&4&&i.state==0&&(i=new e(this.source,1)),i=i.updateFor(t,r);for(let n of t.effects)if(n.is(O))i=new e(i.source,1,n.value);else if(n.is(k))i=new e(i.source,0);else if(n.is(R))for(let e of n.value)e.source==i.source&&(i=e);return i}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(T(e.state))}},L=class e extends I{constructor(e,t,n,r,i,a){super(e,3,t),this.limit=n,this.result=r,this.from=i,this.to=a}hasResult(){return!0}updateFor(t,n){if(!(n&3))return this.map(t.changes);let r=this.result;r.map&&!t.changes.empty&&(r=r.map(r,t.changes));let i=t.changes.mapPos(this.from),a=t.changes.mapPos(this.to,1),o=T(t.state);if(o>a||!r||n&2&&(T(t.startState)==this.from||o<this.limit))return new I(this.source,n&4?1:0);let s=t.changes.mapPos(this.limit);return Ee(r.validFor,t.state,i,a)?new e(this.source,this.explicit,s,r,i,a):r.update&&(r=r.update(r,i,a,new w(t.state,o,!1)))?new e(this.source,this.explicit,s,r,r.from,r.to??T(t.state)):new I(this.source,1,this.explicit)}map(t){return t.empty?this:(this.result.map?this.result.map(this.result,t):this.result)?new e(this.source,this.explicit,t.mapPos(this.limit),this.result,t.mapPos(this.from),t.mapPos(this.to,1)):new I(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}};function Ee(e,t,n,r){if(!e)return!1;let i=t.sliceDoc(n,r);return typeof e==`function`?e(i,n,r,t):ce(e,!0).test(i)}var R=m.define({map(e,t){return e.map(e=>e.map(t))}}),z=S.define({create(){return be.start()},update(e,t){return e.update(t)},provide:e=>[o.from(e,e=>e.tooltip),h.contentAttributes.from(e,e=>e.attrs)]});function B(e,t){let n=t.completion.apply||t.completion.label,r=e.state.field(z).active.find(e=>e.source==t.source);return r instanceof L?(typeof n==`string`?e.dispatch({...le(e.state,n,r.from,r.to),annotations:E.of(t.completion)}):n(e,t.completion,r.from,r.to),!0):!1}var De=ge(z,B);function V(e,t=`option`){return n=>{let r=n.state.field(z,!1);if(!r||!r.open||r.open.disabled||Date.now()-r.open.timestamp<n.state.facet(A).interactionDelay)return!1;let i=1,a;t==`page`&&(a=C(n,r.open.tooltip))&&(i=Math.max(2,Math.floor(a.dom.offsetHeight/a.dom.querySelector(`li`).offsetHeight)-1));let{length:o}=r.open.options,s=r.open.selected>-1?r.open.selected+i*(e?1:-1):e?0:o-1;return s<0?s=t==`page`?0:o-1:s>=o&&(s=t==`page`?o-1:0),n.dispatch({effects:M.of(s)}),!0}}var Oe=e=>{let t=e.state.field(z,!1);return e.state.readOnly||!t||!t.open||t.open.selected<0||t.open.disabled||Date.now()-t.open.timestamp<e.state.facet(A).interactionDelay?!1:B(e,t.open.options[t.open.selected])},H=e=>e.state.field(z,!1)?(e.dispatch({effects:O.of(!0)}),!0):!1,ke=e=>{let t=e.state.field(z,!1);return!t||!t.active.some(e=>e.state!=0)?!1:(e.dispatch({effects:k.of(null)}),!0)},Ae=class{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}},je=50,Me=1e3,Ne=te.fromClass(class{constructor(e){this.view=e,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let t of e.state.field(z).active)t.isPending&&this.startQuery(t)}update(e){let t=e.state.field(z),n=e.state.facet(A);if(!e.selectionSet&&!e.docChanged&&e.startState.field(z)==t)return;let r=e.transactions.some(e=>{let t=Te(e,n);return t&8||(e.selection||e.docChanged)&&!(t&3)});for(let t=0;t<this.running.length;t++){let n=this.running[t];if(r||n.context.abortOnDocChange&&e.docChanged||n.updates.length+e.transactions.length>je&&Date.now()-n.time>Me){for(let e of n.context.abortListeners)try{e()}catch(e){a(this.view.state,e)}n.context.abortListeners=null,this.running.splice(t--,1)}else n.updates.push(...e.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),e.transactions.some(e=>e.effects.some(e=>e.is(O)))&&(this.pendingStart=!0);let i=this.pendingStart?50:n.activateOnTypingDelay;if(this.debounceUpdate=t.active.some(e=>e.isPending&&!this.running.some(t=>t.active.source==e.source))?setTimeout(()=>this.startUpdate(),i):-1,this.composing!=0)for(let t of e.transactions)t.isUserEvent(`input.type`)?this.composing=2:this.composing==2&&t.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:e}=this.view,t=e.field(z);for(let e of t.active)e.isPending&&!this.running.some(t=>t.active.source==e.source)&&this.startQuery(e);this.running.length&&t.open&&t.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(A).updateSyncTime))}startQuery(e){let{state:t}=this.view,n=new w(t,T(t),e.explicit,this.view),r=new Ae(e,n);this.running.push(r),Promise.resolve(e.source(n)).then(e=>{r.context.aborted||(r.done=e||null,this.scheduleAccept())},e=>{this.view.dispatch({effects:k.of(null)}),a(this.view.state,e)})}scheduleAccept(){this.running.every(e=>e.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(A).updateSyncTime))}accept(){this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(A),n=this.view.state.field(z);for(let r=0;r<this.running.length;r++){let i=this.running[r];if(i.done===void 0)continue;if(this.running.splice(r--,1),i.done){let n=T(i.updates.length?i.updates[0].startState:this.view.state),r=Math.min(n,i.done.from+ +!i.active.explicit),a=new L(i.active.source,i.active.explicit,r,i.done,i.done.from,i.done.to??n);for(let e of i.updates)a=a.update(e,t);if(a.hasResult()){e.push(a);continue}}let a=n.active.find(e=>e.source==i.active.source);if(a&&a.isPending)if(i.done==null){let n=new I(i.active.source,0);for(let e of i.updates)n=n.update(e,t);n.isPending||e.push(n)}else this.startQuery(a)}(e.length||n.open&&n.open.disabled)&&this.view.dispatch({effects:R.of(e)})}},{eventHandlers:{blur(e){let t=this.view.state.field(z,!1);if(t&&t.tooltip&&this.view.state.facet(A).closeOnBlur){let n=t.open&&C(this.view,t.open.tooltip);(!n||!n.dom.contains(e.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:k.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:O.of(!1)}),20),this.composing=0}}}),Pe=typeof navigator==`object`&&/Win/.test(navigator.platform),Fe=l.highest(h.domEventHandlers({keydown(e,t){let n=t.state.field(z,!1);if(!n||!n.open||n.open.disabled||n.open.selected<0||e.key.length>1||e.ctrlKey&&!(Pe&&e.altKey)||e.metaKey)return!1;let r=n.open.options[n.open.selected],i=n.active.find(e=>e.source==r.source),a=r.completion.commitCharacters||i.result.commitCharacters;return a&&a.indexOf(e.key)>-1&&B(t,r),!1}})),U=h.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:`monospace`,whiteSpace:`nowrap`,overflow:`hidden auto`,maxWidth_fallback:`700px`,maxWidth:`min(700px, 95vw)`,minWidth:`250px`,maxHeight:`10em`,height:`100%`,listStyle:`none`,margin:0,padding:0,"& > li, & > completion-section":{padding:`1px 3px`,lineHeight:1.2},"& > li":{overflowX:`hidden`,textOverflow:`ellipsis`,cursor:`pointer`},"& > completion-section":{display:`list-item`,borderBottom:`1px solid silver`,paddingLeft:`0.5em`,opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:`#17c`,color:`white`},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:`#777`},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:`#347`,color:`white`},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:`#444`},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:`"···"`,opacity:.5,display:`block`,textAlign:`center`},".cm-tooltip.cm-completionInfo":{position:`absolute`,padding:`3px 9px`,width:`max-content`,maxWidth:`400px`,boxSizing:`border-box`,whiteSpace:`pre-line`},".cm-completionInfo.cm-completionInfo-left":{right:`100%`},".cm-completionInfo.cm-completionInfo-right":{left:`100%`},".cm-completionInfo.cm-completionInfo-left-narrow":{right:`30px`},".cm-completionInfo.cm-completionInfo-right-narrow":{left:`30px`},"&light .cm-snippetField":{backgroundColor:`#00000022`},"&dark .cm-snippetField":{backgroundColor:`#ffffff22`},".cm-snippetFieldPosition":{verticalAlign:`text-top`,width:0,height:`1.15em`,display:`inline-block`,margin:`0 -0.7px -.7em`,borderLeft:`1.4px dotted #888`},".cm-completionMatchedText":{textDecoration:`underline`},".cm-completionDetail":{marginLeft:`0.5em`,fontStyle:`italic`},".cm-completionIcon":{fontSize:`90%`,width:`.8em`,display:`inline-block`,textAlign:`center`,paddingRight:`.6em`,opacity:`0.6`,boxSizing:`content-box`},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:`'ƒ'`}},".cm-completionIcon-class":{"&:after":{content:`'○'`}},".cm-completionIcon-interface":{"&:after":{content:`'◌'`}},".cm-completionIcon-variable":{"&:after":{content:`'𝑥'`}},".cm-completionIcon-constant":{"&:after":{content:`'𝐶'`}},".cm-completionIcon-type":{"&:after":{content:`'𝑡'`}},".cm-completionIcon-enum":{"&:after":{content:`'∪'`}},".cm-completionIcon-property":{"&:after":{content:`'□'`}},".cm-completionIcon-keyword":{"&:after":{content:`'🔑︎'`}},".cm-completionIcon-namespace":{"&:after":{content:`'▢'`}},".cm-completionIcon-text":{"&:after":{content:`'abc'`,fontSize:`50%`,verticalAlign:`middle`}}}),Ie=class{constructor(e,t,n,r){this.field=e,this.line=t,this.from=n,this.to=r}},Le=class e{constructor(e,t,n){this.field=e,this.from=t,this.to=n}map(t){let n=t.mapPos(this.from,-1,d.TrackDel),r=t.mapPos(this.to,1,d.TrackDel);return n==null||r==null?null:new e(this.field,n,r)}},Re=class e{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let r=[],i=[t],a=e.doc.lineAt(t),o=/^\s*/.exec(a.text)[0];for(let a of this.lines){if(r.length){let r=o,s=/^\t*/.exec(a)[0].length;for(let t=0;t<s;t++)r+=e.facet(n);i.push(t+r.length-s),a=r+a.slice(s)}r.push(a),t+=a.length+1}return{text:r,ranges:this.fieldPositions.map(e=>new Le(e.field,i[e.line]+e.from,i[e.line]+e.to))}}static parse(t){let n=[],r=[],i=[],a;for(let e of t.split(/\r\n?|\n/)){for(;a=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(e);){let t=a[1]?+a[1]:null,o=a[2]||a[3]||``,s=-1,c=o.replace(/\\[{}]/g,e=>e[1]);for(let e=0;e<n.length;e++)(t==null?c&&n[e].name==c:n[e].seq==t)&&(s=e);if(s<0){let e=0;for(;e<n.length&&(t==null||n[e].seq!=null&&n[e].seq<t);)e++;n.splice(e,0,{seq:t,name:c}),s=e;for(let e of i)e.field>=s&&e.field++}for(let e of i)if(e.line==r.length&&e.from>a.index){let t=a[2]?3+(a[1]||``).length:2;e.from-=t,e.to-=t}i.push(new Ie(s,r.length,a.index,a.index+c.length)),e=e.slice(0,a.index)+o+e.slice(a.index+a[0].length)}e=e.replace(/\\([{}])/g,(e,t,n)=>{for(let e of i)e.line==r.length&&e.from>n&&(e.from--,e.to--);return t}),r.push(e)}return new e(r,i)}},ze=v.widget({widget:new class extends ne{toDOM(){let e=document.createElement(`span`);return e.className=`cm-snippetFieldPosition`,e}ignoreEvent(){return!1}}}),Be=v.mark({class:`cm-snippetField`}),W=class e{constructor(e,t){this.ranges=e,this.active=t,this.deco=v.set(e.map(e=>(e.from==e.to?ze:Be).range(e.from,e.to)),!0)}map(t){let n=[];for(let e of this.ranges){let r=e.map(t);if(!r)return null;n.push(r)}return new e(n,this.active)}selectionInsideField(e){return e.ranges.every(e=>this.ranges.some(t=>t.field==this.active&&t.from<=e.from&&t.to>=e.to))}},G=m.define({map(e,t){return e&&e.map(t)}}),Ve=m.define(),K=S.define({create(){return null},update(e,t){for(let n of t.effects){if(n.is(G))return n.value;if(n.is(Ve)&&e)return new W(e.ranges,n.value)}return e&&t.docChanged&&(e=e.map(t.changes)),e&&t.selection&&!e.selectionInsideField(t.selection)&&(e=null),e},provide:e=>h.decorations.from(e,e=>e?e.deco:v.none)});function q(e,t){return i.create(e.filter(e=>e.field==t).map(e=>i.range(e.from,e.to)))}function He(e){let t=Re.parse(e);return(e,n,r,i)=>{let{text:a,ranges:o}=t.instantiate(e.state,r),{main:s}=e.state.selection,c={changes:{from:r,to:i==s.from?s.to:i,insert:y.of(a)},scrollIntoView:!0,annotations:n?[E.of(n),x.userEvent.of(`input.complete`)]:void 0};if(o.length&&(c.selection=q(o,0)),o.some(e=>e.field>0)){let t=new W(o,0),n=c.effects=[G.of(t)];e.state.field(K,!1)===void 0&&n.push(m.appendConfig.of([K,Ge,qe,U]))}e.dispatch(e.state.update(c))}}function J(e){return({state:t,dispatch:n})=>{let r=t.field(K,!1);if(!r||e<0&&r.active==0)return!1;let i=r.active+e,a=e>0&&!r.ranges.some(t=>t.field==i+e);return n(t.update({selection:q(r.ranges,i),effects:G.of(a?null:new W(r.ranges,i)),scrollIntoView:!0})),!0}}var Ue=[{key:`Tab`,run:J(1),shift:J(-1)},{key:`Escape`,run:({state:e,dispatch:t})=>e.field(K,!1)?(t(e.update({effects:G.of(null)})),!0):!1}],We=r.define({combine(e){return e.length?e[0]:Ue}}),Ge=l.highest(t.compute([We],e=>e.facet(We)));function Ke(e,t){return{...t,apply:He(e)}}var qe=h.domEventHandlers({mousedown(e,t){let n=t.state.field(K,!1),r;if(!n||(r=t.posAtCoords({x:e.clientX,y:e.clientY}))==null)return!1;let i=n.ranges.find(e=>e.from<=r&&e.to>=r);return!i||i.field==n.active?!1:(t.dispatch({selection:q(n.ranges,i.field),effects:G.of(n.ranges.some(e=>e.field>i.field)?new W(n.ranges,i.field):null),scrollIntoView:!0}),!0)}}),Y={brackets:[`(`,`[`,`{`,`'`,`"`],before:`)]}:;>`,stringPrefixes:[]},X=m.define({map(e,t){return t.mapPos(e,-1,d.TrackAfter)??void 0}}),Z=new class extends e{};Z.startSide=1,Z.endSide=-1;var Je=S.define({create(){return f.empty},update(e,t){if(e=e.map(t.changes),t.selection){let n=t.state.doc.lineAt(t.selection.main.head);e=e.update({filter:e=>e>=n.from&&e<=n.to})}for(let n of t.effects)n.is(X)&&(e=e.update({add:[Z.range(n.value,n.value+1)]}));return e}});function Ye(){return[et,Je]}var Xe=`()[]{}<>«»»«[]{}`;function Ze(e){for(let t=0;t<16;t+=2)if(Xe.charCodeAt(t)==e)return Xe.charAt(t+1);return _(e<128?e:e+1)}function Qe(e,t){return e.languageDataAt(`closeBrackets`,t)[0]||Y}var $e=typeof navigator==`object`&&/Android\b/.test(navigator.userAgent),et=h.inputHandler.of((e,t,n,r)=>{if(($e?e.composing:e.compositionStarted)||e.state.readOnly)return!1;let i=e.state.selection.main;if(r.length>2||r.length==2&&p(g(r,0))==1||t!=i.from||n!=i.to)return!1;let a=nt(e.state,r);return a?(e.dispatch(a),!0):!1}),tt=[{key:`Backspace`,run:({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Qe(e,e.selection.main.head).brackets||Y.brackets,r=null,a=e.changeByRange(t=>{if(t.empty){let r=rt(e.doc,t.head);for(let a of n)if(a==r&&$(e.doc,t.head)==Ze(g(a,0)))return{changes:{from:t.head-a.length,to:t.head+a.length},range:i.cursor(t.head-a.length)}}return{range:r=t}});return r||t(e.update(a,{scrollIntoView:!0,userEvent:`delete.backward`})),!r}}];function nt(e,t){let n=Qe(e,e.selection.main.head),r=n.brackets||Y.brackets;for(let i of r){let a=Ze(g(i,0));if(t==i)return a==i?ot(e,i,r.indexOf(i+i+i)>-1,n):it(e,i,a,n.before||Y.before);if(t==a&&Q(e,e.selection.main.from))return at(e,i,a)}return null}function Q(e,t){let n=!1;return e.field(Je).between(0,e.doc.length,e=>{e==t&&(n=!0)}),n}function $(e,t){let n=e.sliceString(t,t+2);return n.slice(0,p(g(n,0)))}function rt(e,t){let n=e.sliceString(t-2,t);return p(g(n,0))==n.length?n:n.slice(1)}function it(e,t,n,r){let a=null,o=e.changeByRange(o=>{if(!o.empty)return{changes:[{insert:t,from:o.from},{insert:n,from:o.to}],effects:X.of(o.to+t.length),range:i.range(o.anchor+t.length,o.head+t.length)};let s=$(e.doc,o.head);return!s||/\s/.test(s)||r.indexOf(s)>-1?{changes:{insert:t+n,from:o.head},effects:X.of(o.head+t.length),range:i.cursor(o.head+t.length)}:{range:a=o}});return a?null:e.update(o,{scrollIntoView:!0,userEvent:`input.type`})}function at(e,t,n){let r=null,a=e.changeByRange(t=>t.empty&&$(e.doc,t.head)==n?{changes:{from:t.head,to:t.head+n.length,insert:n},range:i.cursor(t.head+n.length)}:r={range:t});return r?null:e.update(a,{scrollIntoView:!0,userEvent:`input.type`})}function ot(e,t,n,r){let a=r.stringPrefixes||Y.stringPrefixes,o=null,s=e.changeByRange(r=>{if(!r.empty)return{changes:[{insert:t,from:r.from},{insert:t,from:r.to}],effects:X.of(r.to+t.length),range:i.range(r.anchor+t.length,r.head+t.length)};let s=r.head,l=$(e.doc,s),u;if(l==t){if(st(e,s))return{changes:{insert:t+t,from:s},effects:X.of(s+t.length),range:i.cursor(s+t.length)};if(Q(e,s)){let r=n&&e.sliceDoc(s,s+t.length*3)==t+t+t?t+t+t:t;return{changes:{from:s,to:s+r.length,insert:r},range:i.cursor(s+r.length)}}}else if(n&&e.sliceDoc(s-2*t.length,s)==t+t&&(u=lt(e,s-2*t.length,a))>-1&&st(e,u))return{changes:{insert:t+t+t+t,from:s},effects:X.of(s+t.length),range:i.cursor(s+t.length)};else if(e.charCategorizer(s)(l)!=c.Word&&lt(e,s,a)>-1&&!ct(e,s,t,a))return{changes:{insert:t+t,from:s},effects:X.of(s+t.length),range:i.cursor(s+t.length)};return{range:o=r}});return o?null:e.update(s,{scrollIntoView:!0,userEvent:`input.type`})}function st(e,t){let n=u(e).resolveInner(t+1);return n.parent&&n.from==t}function ct(e,t,n,r){let i=u(e).resolveInner(t,-1),a=r.reduce((e,t)=>Math.max(e,t.length),0);for(let o=0;o<5;o++){let o=e.sliceDoc(i.from,Math.min(i.to,i.from+n.length+a)),s=o.indexOf(n);if(!s||s>-1&&r.indexOf(o.slice(0,s))>-1){let t=i.firstChild;for(;t&&t.from==i.from&&t.to-t.from>n.length+s;){if(e.sliceDoc(t.to-n.length,t.to)==n)return!1;t=t.firstChild}return!0}let c=i.to==t&&i.parent;if(!c)break;i=c}return!1}function lt(e,t,n){let r=e.charCategorizer(t);if(r(e.sliceDoc(t-1,t))!=c.Word)return t;for(let i of n){let n=t-i.length;if(e.sliceDoc(n,t)==i&&r(e.sliceDoc(n-1,n))!=c.Word)return n}return-1}function ut(e={}){return[Fe,z,A.of(e),Ne,ft,U]}var dt=[{key:`Ctrl-Space`,run:H},{mac:"Alt-`",run:H},{mac:`Alt-i`,run:H},{key:`Escape`,run:ke},{key:`ArrowDown`,run:V(!0)},{key:`ArrowUp`,run:V(!1)},{key:`PageDown`,run:V(!0,`page`)},{key:`PageUp`,run:V(!1,`page`)},{key:`Enter`,run:Oe}],ft=l.highest(t.computeN([A],e=>e.facet(A).defaultKeymap?[dt]:[]));export{ae as a,Ke as c,tt as i,ut as n,dt as o,Ye as r,oe as s,w as t};
@@ -0,0 +1 @@
1
+ import{E as e,L as t,O as n,g as r,i,it as a,rt as o,s}from"./dist-CWsgPYc6.js";import{r as c}from"./dist-saWP7AQm.js";var l=o({String:a.string,Number:a.number,"True False":a.bool,PropertyName:a.propertyName,Null:a.null,", :":a.separator,"[ ]":a.squareBracket,"{ }":a.brace}),u=c.deserialize({version:14,states:"$bOVQPOOOOQO'#Cb'#CbOnQPO'#CeOvQPO'#ClOOQO'#Cr'#CrQOQPOOOOQO'#Cg'#CgO}QPO'#CfO!SQPO'#CtOOQO,59P,59PO![QPO,59PO!aQPO'#CuOOQO,59W,59WO!iQPO,59WOVQPO,59QOqQPO'#CmO!nQPO,59`OOQO1G.k1G.kOVQPO'#CnO!vQPO,59aOOQO1G.r1G.rOOQO1G.l1G.lOOQO,59X,59XOOQO-E6k-E6kOOQO,59Y,59YOOQO-E6l-E6l",stateData:`#O~OeOS~OQSORSOSSOTSOWQO_ROgPO~OVXOgUO~O^[O~PVO[^O~O]_OVhX~OVaO~O]bO^iX~O^dO~O]_OVha~O]bO^ia~O`,goto:"!kjPPPPPPkPPkqwPPPPk{!RPPP!XP!e!hXSOR^bQWQRf_TVQ_Q`WRg`QcZRicQTOQZRQe^RhbRYQR]R",nodeNames:`⚠ JsonText True False Null Number String } { Object Property PropertyName : , ] [ Array`,maxTerm:25,nodeProps:[[`isolate`,-2,6,11,``],[`openedBy`,7,`{`,14,`[`],[`closedBy`,8,`}`,15,`]`]],propSources:[l],skippedNodes:[0],repeatNodeCount:2,tokenData:"(|~RaXY!WYZ!W]^!Wpq!Wrs!]|}$u}!O$z!Q!R%T!R![&c![!]&t!}#O&y#P#Q'O#Y#Z'T#b#c'r#h#i(Z#o#p(r#q#r(w~!]Oe~~!`Wpq!]qr!]rs!xs#O!]#O#P!}#P;'S!];'S;=`$o<%lO!]~!}Og~~#QXrs!]!P!Q!]#O#P!]#U#V!]#Y#Z!]#b#c!]#f#g!]#h#i!]#i#j#m~#pR!Q![#y!c!i#y#T#Z#y~#|R!Q![$V!c!i$V#T#Z$V~$YR!Q![$c!c!i$c#T#Z$c~$fR!Q![!]!c!i!]#T#Z!]~$rP;=`<%l!]~$zO]~~$}Q!Q!R%T!R![&c~%YRT~!O!P%c!g!h%w#X#Y%w~%fP!Q![%i~%nRT~!Q![%i!g!h%w#X#Y%w~%zR{|&T}!O&T!Q![&Z~&WP!Q![&Z~&`PT~!Q![&Z~&hST~!O!P%c!Q![&c!g!h%w#X#Y%w~&yO[~~'OO_~~'TO^~~'WP#T#U'Z~'^P#`#a'a~'dP#g#h'g~'jP#X#Y'm~'rOR~~'uP#i#j'x~'{P#`#a(O~(RP#`#a(U~(ZOS~~(^P#f#g(a~(dP#i#j(g~(jP#X#Y(m~(rOQ~~(wOW~~(|OV~",tokenizers:[0],topRules:{JsonText:[0,1]},tokenPrec:0}),d=i.define({name:`json`,parser:u.configure({props:[t.add({Object:r({except:/^\s*\}/}),Array:r({except:/^\s*\]/})}),n.add({"Object Array":e})]}),languageData:{closeBrackets:{brackets:[`[`,`{`,`"`]},indentOnInput:/^\s*[\}\]]$/}});function f(){return new s(d)}export{f as json};