@mapomodule/mcp 0.0.0-stage → 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +479 -2
- package/bin/mapo-mcp.mjs +3 -0
- package/dist/build.d.mts +18 -0
- package/dist/build.d.ts +18 -0
- package/dist/build.mjs +351 -0
- package/dist/cli.d.mts +7 -0
- package/dist/cli.d.ts +7 -0
- package/dist/cli.mjs +263 -0
- package/dist/index.d.mts +68 -0
- package/dist/index.d.ts +68 -0
- package/dist/index.mjs +1 -0
- package/dist/knowledge/api.json +1 -0
- package/dist/knowledge/docs.json +1 -0
- package/dist/module.d.mts +16 -0
- package/dist/module.d.ts +16 -0
- package/dist/module.json +9 -0
- package/dist/module.mjs +121 -0
- package/dist/runtime/core/doctor.d.ts +0 -0
- package/dist/runtime/core/doctor.js +128 -0
- package/dist/runtime/core/indexer.d.ts +0 -0
- package/dist/runtime/core/indexer.js +193 -0
- package/dist/runtime/core/knowledge.d.ts +0 -0
- package/dist/runtime/core/knowledge.js +76 -0
- package/dist/runtime/core/openapi.d.ts +0 -0
- package/dist/runtime/core/openapi.js +229 -0
- package/dist/runtime/core/prompts.d.ts +0 -0
- package/dist/runtime/core/prompts.js +108 -0
- package/dist/runtime/core/recipes.d.ts +0 -0
- package/dist/runtime/core/recipes.js +297 -0
- package/dist/runtime/core/resources.d.ts +0 -0
- package/dist/runtime/core/resources.js +88 -0
- package/dist/runtime/core/scaffold/fields.d.ts +0 -0
- package/dist/runtime/core/scaffold/fields.js +64 -0
- package/dist/runtime/core/scaffold/index.d.ts +0 -0
- package/dist/runtime/core/scaffold/index.js +74 -0
- package/dist/runtime/core/scaffold/templates.d.ts +0 -0
- package/dist/runtime/core/scaffold/templates.js +349 -0
- package/dist/runtime/core/schema-source.d.ts +0 -0
- package/dist/runtime/core/schema-source.js +70 -0
- package/dist/runtime/core/search.d.ts +0 -0
- package/dist/runtime/core/search.js +173 -0
- package/dist/runtime/core/tokenize.d.ts +0 -0
- package/dist/runtime/core/tokenize.js +96 -0
- package/dist/runtime/core/tool-spec.d.ts +0 -0
- package/dist/runtime/core/tool-spec.js +3 -0
- package/dist/runtime/core/tools/api.d.ts +0 -0
- package/dist/runtime/core/tools/api.js +192 -0
- package/dist/runtime/core/tools/app.d.ts +0 -0
- package/dist/runtime/core/tools/app.js +141 -0
- package/dist/runtime/core/tools/backend.d.ts +0 -0
- package/dist/runtime/core/tools/backend.js +143 -0
- package/dist/runtime/core/tools/docs.d.ts +0 -0
- package/dist/runtime/core/tools/docs.js +150 -0
- package/dist/runtime/core/tools/scaffold.d.ts +0 -0
- package/dist/runtime/core/tools/scaffold.js +127 -0
- package/dist/runtime/core/types.d.ts +0 -0
- package/dist/runtime/core/types.js +0 -0
- package/dist/runtime/core/write.d.ts +0 -0
- package/dist/runtime/core/write.js +53 -0
- package/dist/runtime/mcp/handlers/mapo/index.js +13 -0
- package/dist/runtime/mcp/handlers/mapo/prompts/crud-page.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/prompts/custom-field.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/prompts/debug-form.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/prompts/migrate-v1.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/prompts/theme.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/resources/app-manifest.js +19 -0
- package/dist/runtime/mcp/handlers/mapo/resources/docs.js +34 -0
- package/dist/runtime/mcp/handlers/mapo/resources/fields.js +34 -0
- package/dist/runtime/mcp/handlers/mapo/resources/knowledge-index.js +22 -0
- package/dist/runtime/mcp/handlers/mapo/tools/backend-schema.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/component-api.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/composable-api.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/doctor.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/get-doc.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/inspect-app.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/list-field-types.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/list-recipes.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/scaffold.js +3 -0
- package/dist/runtime/mcp/handlers/mapo/tools/search-docs.js +3 -0
- package/dist/runtime/nitro/context.d.ts +0 -0
- package/dist/runtime/nitro/context.js +21 -0
- package/dist/runtime/nitro/to-mcp-prompt.d.ts +0 -0
- package/dist/runtime/nitro/to-mcp-prompt.js +23 -0
- package/dist/runtime/nitro/to-mcp-tool.d.ts +0 -0
- package/dist/runtime/nitro/to-mcp-tool.js +28 -0
- package/dist/runtime/types/virtual-modules.d.ts +6 -0
- package/dist/types.d.mts +9 -0
- package/package.json +73 -4
- package/src/__tests__/cli.test.ts +121 -0
- package/src/__tests__/doctor.test.ts +145 -0
- package/src/__tests__/fixtures/drf-schema.json +142 -0
- package/src/__tests__/fixtures.ts +198 -0
- package/src/__tests__/indexer.test.ts +114 -0
- package/src/__tests__/knowledge.test.ts +209 -0
- package/src/__tests__/openapi.test.ts +256 -0
- package/src/__tests__/recipes.test.ts +44 -0
- package/src/__tests__/resources.test.ts +69 -0
- package/src/__tests__/scaffold.test.ts +153 -0
- package/src/__tests__/search.test.ts +105 -0
- package/src/__tests__/tools.test.ts +226 -0
- package/src/__tests__/write.test.ts +134 -0
- package/src/build/extract-components.ts +135 -0
- package/src/build/extract-composables.ts +125 -0
- package/src/build/extract-fields.ts +250 -0
- package/src/build/index.ts +103 -0
- package/src/cli.ts +364 -0
- package/src/index.ts +65 -0
- package/src/module.ts +214 -0
- package/src/runtime/core/doctor.ts +204 -0
- package/src/runtime/core/indexer.ts +279 -0
- package/src/runtime/core/knowledge.ts +121 -0
- package/src/runtime/core/openapi.ts +417 -0
- package/src/runtime/core/prompts.ts +150 -0
- package/src/runtime/core/recipes.ts +361 -0
- package/src/runtime/core/resources.ts +144 -0
- package/src/runtime/core/scaffold/fields.ts +127 -0
- package/src/runtime/core/scaffold/index.ts +120 -0
- package/src/runtime/core/scaffold/templates.ts +394 -0
- package/src/runtime/core/schema-source.ts +123 -0
- package/src/runtime/core/search.ts +282 -0
- package/src/runtime/core/tokenize.ts +146 -0
- package/src/runtime/core/tool-spec.ts +74 -0
- package/src/runtime/core/tools/api.ts +300 -0
- package/src/runtime/core/tools/app.ts +200 -0
- package/src/runtime/core/tools/backend.ts +197 -0
- package/src/runtime/core/tools/docs.ts +215 -0
- package/src/runtime/core/tools/scaffold.ts +176 -0
- package/src/runtime/core/types.ts +133 -0
- package/src/runtime/core/write.ts +119 -0
- package/src/runtime/mcp/handlers/mapo/index.ts +22 -0
- package/src/runtime/mcp/handlers/mapo/prompts/crud-page.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/prompts/custom-field.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/prompts/debug-form.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/prompts/migrate-v1.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/prompts/theme.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/resources/app-manifest.ts +28 -0
- package/src/runtime/mcp/handlers/mapo/resources/docs.ts +41 -0
- package/src/runtime/mcp/handlers/mapo/resources/fields.ts +37 -0
- package/src/runtime/mcp/handlers/mapo/resources/knowledge-index.ts +24 -0
- package/src/runtime/mcp/handlers/mapo/tools/backend-schema.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/component-api.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/composable-api.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/doctor.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/get-doc.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/inspect-app.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/list-field-types.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/list-recipes.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/scaffold.ts +4 -0
- package/src/runtime/mcp/handlers/mapo/tools/search-docs.ts +4 -0
- package/src/runtime/nitro/context.ts +41 -0
- package/src/runtime/nitro/to-mcp-prompt.ts +30 -0
- package/src/runtime/nitro/to-mcp-tool.ts +35 -0
- package/src/runtime/types/virtual-modules.d.ts +6 -0
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagnostic rules over the app snapshot.
|
|
3
|
+
*
|
|
4
|
+
* Pure and transport-agnostic so the whole rule set is unit-testable against a
|
|
5
|
+
* crafted manifest. Every finding must be *actionable*: what is wrong, why it
|
|
6
|
+
* matters, and the exact change to make.
|
|
7
|
+
*/
|
|
8
|
+
import type { MapoAppManifest } from "../../index.js";
|
|
9
|
+
|
|
10
|
+
export type DoctorSeverity = "error" | "warning" | "info";
|
|
11
|
+
|
|
12
|
+
export interface DoctorFinding {
|
|
13
|
+
rule: string;
|
|
14
|
+
severity: DoctorSeverity;
|
|
15
|
+
message: string;
|
|
16
|
+
/** Concrete change to apply. */
|
|
17
|
+
fix?: string;
|
|
18
|
+
/** Documentation path that explains the topic. */
|
|
19
|
+
doc?: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Mirrors `MAPO_DEFAULTS` in `@mapomodule/core`. */
|
|
23
|
+
const AUTH_DEFAULTS: Record<string, string> = {
|
|
24
|
+
authLoginUrl: "/api/auth/login",
|
|
25
|
+
userInfoApi: "/api/profiles/me/",
|
|
26
|
+
logoutUrl: "/api/auth/logout",
|
|
27
|
+
loginUrl: "/login",
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
/** Mirrors `MAPO_MEDIA_DEFAULTS.endpoints` in `@mapomodule/uikit`. */
|
|
31
|
+
const MEDIA_ENDPOINT_DEFAULTS = {
|
|
32
|
+
media: "/api/media",
|
|
33
|
+
folders: "/api/media-folders",
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Locales Mapo ships UI catalogs for. */
|
|
37
|
+
const BUNDLED_LOCALES = new Set(["en", "it"]);
|
|
38
|
+
|
|
39
|
+
const MEDIA_FIELD_TYPES = new Set(["media", "media-m2m", "enhanced-media"]);
|
|
40
|
+
|
|
41
|
+
function section(
|
|
42
|
+
manifest: MapoAppManifest,
|
|
43
|
+
key: string,
|
|
44
|
+
): Record<string, unknown> {
|
|
45
|
+
const value = manifest.config[key];
|
|
46
|
+
return value && typeof value === "object"
|
|
47
|
+
? (value as Record<string, unknown>)
|
|
48
|
+
: {};
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Runs every rule and returns the findings, most severe first. */
|
|
52
|
+
export function runDoctor(manifest: MapoAppManifest): DoctorFinding[] {
|
|
53
|
+
const findings: DoctorFinding[] = [];
|
|
54
|
+
const core = section(manifest, "mapoCore");
|
|
55
|
+
const media = section(manifest, "mapoMedia");
|
|
56
|
+
const moduleNames = new Set(manifest.modules.map((module) => module.name));
|
|
57
|
+
|
|
58
|
+
// 1. Module order. `@nuxt/ui` must be registered before Mapo: installing it
|
|
59
|
+
// from inside another module makes @nuxt/icon's SSR component loop.
|
|
60
|
+
const order = manifest.moduleOrder;
|
|
61
|
+
const uiIndex = order.indexOf("@nuxt/ui");
|
|
62
|
+
const mapoIndex = order.findIndex(
|
|
63
|
+
(name) => name === "mapomodule" || name.startsWith("@mapomodule/"),
|
|
64
|
+
);
|
|
65
|
+
|
|
66
|
+
if (mapoIndex !== -1 && uiIndex === -1) {
|
|
67
|
+
findings.push({
|
|
68
|
+
rule: "nuxt-ui-missing",
|
|
69
|
+
severity: "error",
|
|
70
|
+
message:
|
|
71
|
+
"`@nuxt/ui` is not declared in `modules[]`, but Mapo's UI layer requires it.",
|
|
72
|
+
fix: 'Add "@nuxt/ui" as the first entry of `modules[]`.',
|
|
73
|
+
doc: "guide/getting-started.md",
|
|
74
|
+
});
|
|
75
|
+
} else if (mapoIndex !== -1 && uiIndex > mapoIndex) {
|
|
76
|
+
findings.push({
|
|
77
|
+
rule: "nuxt-ui-order",
|
|
78
|
+
severity: "error",
|
|
79
|
+
message:
|
|
80
|
+
`\`@nuxt/ui\` is declared after \`${order[mapoIndex]}\` in modules[]. ` +
|
|
81
|
+
"Icons break during SSR when Nuxt UI is initialised after Mapo.",
|
|
82
|
+
fix: 'Move "@nuxt/ui" before the Mapo entry in `modules[]`.',
|
|
83
|
+
doc: "guide/compatibility.md",
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// 2. Mapo itself must be there. A partial install is worth catching early.
|
|
88
|
+
if (!moduleNames.has("@mapomodule/core")) {
|
|
89
|
+
findings.push({
|
|
90
|
+
rule: "core-missing",
|
|
91
|
+
severity: "error",
|
|
92
|
+
message:
|
|
93
|
+
"`@mapomodule/core` is not installed — auth, `useCrud` and route middleware are unavailable.",
|
|
94
|
+
fix: 'Add "mapomodule" to `modules[]`.',
|
|
95
|
+
doc: "guide/getting-started.md",
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// 3. The login route must exist, or the auth middleware redirects to a 404.
|
|
100
|
+
const loginUrl =
|
|
101
|
+
typeof core.loginUrl === "string" ? core.loginUrl : AUTH_DEFAULTS.loginUrl!;
|
|
102
|
+
const hasLoginRoute = manifest.routes.some(
|
|
103
|
+
(route) => route.path === loginUrl,
|
|
104
|
+
);
|
|
105
|
+
|
|
106
|
+
if (!hasLoginRoute && manifest.routes.length > 0) {
|
|
107
|
+
findings.push({
|
|
108
|
+
rule: "login-route-missing",
|
|
109
|
+
severity: "error",
|
|
110
|
+
message: `No page matches \`loginUrl\` (\`${loginUrl}\`); the auth middleware would redirect to a missing route.`,
|
|
111
|
+
fix: `Create \`pages${loginUrl}.vue\` rendering <MapoLogin /> with \`definePageMeta({ layout: false })\`, or change \`mapo.loginUrl\`.`,
|
|
112
|
+
doc: "howto/auth-permissions.md",
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// 4. Untouched auth configuration: fine for a demo, wrong against a backend.
|
|
117
|
+
const authKeys = ["authLoginUrl", "userInfoApi", "logoutUrl"];
|
|
118
|
+
const allDefault = authKeys.every(
|
|
119
|
+
(key) => (core[key] ?? AUTH_DEFAULTS[key]) === AUTH_DEFAULTS[key],
|
|
120
|
+
);
|
|
121
|
+
|
|
122
|
+
if (allDefault) {
|
|
123
|
+
findings.push({
|
|
124
|
+
rule: "auth-endpoints-default",
|
|
125
|
+
severity: "info",
|
|
126
|
+
message:
|
|
127
|
+
"Auth endpoints are still the Mapo defaults — fine for a mock backend, not for a real one.",
|
|
128
|
+
fix: "Set `mapo.authLoginUrl`, `mapo.userInfoApi` and `mapo.logoutUrl` to your backend routes.",
|
|
129
|
+
doc: "howto/backend-integration.md",
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// 5. Nothing built yet.
|
|
134
|
+
const adminRoutes = manifest.routes.filter(
|
|
135
|
+
(route) => route.path !== loginUrl,
|
|
136
|
+
);
|
|
137
|
+
if (adminRoutes.length === 0) {
|
|
138
|
+
findings.push({
|
|
139
|
+
rule: "no-admin-pages",
|
|
140
|
+
severity: "warning",
|
|
141
|
+
message:
|
|
142
|
+
"The app has no admin page yet (only the login route was found).",
|
|
143
|
+
fix: 'Create a page with `definePageMeta({ layout: "mapo-default", middleware: ["auth"] })`.',
|
|
144
|
+
doc: "howto/first-admin-page.md",
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 6. Locales without a Mapo catalog fall back to the default locale for
|
|
149
|
+
// framework strings; app strings are unaffected.
|
|
150
|
+
const uncovered = manifest.locales.filter(
|
|
151
|
+
(locale) => !BUNDLED_LOCALES.has(locale),
|
|
152
|
+
);
|
|
153
|
+
if (uncovered.length) {
|
|
154
|
+
findings.push({
|
|
155
|
+
rule: "locale-without-catalog",
|
|
156
|
+
severity: "warning",
|
|
157
|
+
message: `Mapo ships UI catalogs for en and it only; ${uncovered.join(", ")} will fall back for framework strings.`,
|
|
158
|
+
fix: "Add the missing `mapo.*` keys to your own `i18n/locales/<code>.json`.",
|
|
159
|
+
doc: "howto/i18n.md",
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// 7. Media fields registered while the endpoints are untouched and no
|
|
164
|
+
// integration provides them.
|
|
165
|
+
const usesMedia = manifest.fieldTypes.some((field) =>
|
|
166
|
+
MEDIA_FIELD_TYPES.has(field.type),
|
|
167
|
+
);
|
|
168
|
+
const endpoints = (media.endpoints ?? {}) as Record<string, string>;
|
|
169
|
+
const mediaDefaults =
|
|
170
|
+
(endpoints.media ?? MEDIA_ENDPOINT_DEFAULTS.media) ===
|
|
171
|
+
MEDIA_ENDPOINT_DEFAULTS.media &&
|
|
172
|
+
(endpoints.folders ?? MEDIA_ENDPOINT_DEFAULTS.folders) ===
|
|
173
|
+
MEDIA_ENDPOINT_DEFAULTS.folders;
|
|
174
|
+
|
|
175
|
+
if (
|
|
176
|
+
usesMedia &&
|
|
177
|
+
mediaDefaults &&
|
|
178
|
+
!moduleNames.has("mapo-integrations-camomilla")
|
|
179
|
+
) {
|
|
180
|
+
findings.push({
|
|
181
|
+
rule: "media-endpoints-default",
|
|
182
|
+
severity: "info",
|
|
183
|
+
message:
|
|
184
|
+
"Media field types are registered but the media endpoints are still the defaults " +
|
|
185
|
+
`(\`${MEDIA_ENDPOINT_DEFAULTS.media}\`, \`${MEDIA_ENDPOINT_DEFAULTS.folders}\`) and no integration provides them.`,
|
|
186
|
+
fix: "Set `mapo.uikit.media.endpoints`, or install an integration that serves them.",
|
|
187
|
+
doc: "howto/media-manager.md",
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const rank: Record<DoctorSeverity, number> = {
|
|
192
|
+
error: 0,
|
|
193
|
+
warning: 1,
|
|
194
|
+
info: 2,
|
|
195
|
+
};
|
|
196
|
+
return findings.sort((a, b) => rank[a.severity] - rank[b.severity]);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** What the build-time snapshot structurally cannot see. */
|
|
200
|
+
export const DOCTOR_BLIND_SPOTS = [
|
|
201
|
+
"field types registered at runtime by `defineFormField()` inside a plugin",
|
|
202
|
+
"`definePageMeta` values (layout, middleware, permissions) of your pages",
|
|
203
|
+
"anything that depends on a request, such as the logged-in user's permissions",
|
|
204
|
+
];
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Build-time knowledge indexer.
|
|
3
|
+
*
|
|
4
|
+
* Turns the repository's markdown docs into heading-sized chunks plus a BM25
|
|
5
|
+
* inverted index, so `mapo_search_docs` can answer with the relevant section
|
|
6
|
+
* instead of dumping whole files into the model's context.
|
|
7
|
+
*
|
|
8
|
+
* Runs from `scripts/build-knowledge.mjs` after the package build.
|
|
9
|
+
*/
|
|
10
|
+
import { readdirSync, readFileSync, statSync } from "node:fs";
|
|
11
|
+
import { join, relative, sep } from "node:path";
|
|
12
|
+
import { tokenize } from "./tokenize.js";
|
|
13
|
+
import type { Bm25Index, DocChunk, DocsKnowledge } from "./types.js";
|
|
14
|
+
|
|
15
|
+
export const KNOWLEDGE_VERSION = 1;
|
|
16
|
+
|
|
17
|
+
/** Chunks larger than this are split further (H3, then paragraphs). */
|
|
18
|
+
const MAX_CHUNK_CHARS = 3500;
|
|
19
|
+
|
|
20
|
+
/** Directories under the docs root that are internal planning, not user docs. */
|
|
21
|
+
const EXCLUDED_DIRS = new Set([
|
|
22
|
+
"node_modules",
|
|
23
|
+
"roadmap",
|
|
24
|
+
".vitepress",
|
|
25
|
+
"dist",
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Internal pages that are not user documentation. `DECISIONS.md` is an
|
|
30
|
+
* Italian-language decision log for maintainers; surfacing it to assistants
|
|
31
|
+
* only pollutes results.
|
|
32
|
+
*/
|
|
33
|
+
const EXCLUDED_FILES = new Set(["DECISIONS.md"]);
|
|
34
|
+
|
|
35
|
+
/** Field boosts baked into the term frequencies. */
|
|
36
|
+
const BOOST = { heading: 3, title: 2, tags: 3, text: 1 } as const;
|
|
37
|
+
|
|
38
|
+
const PKG_BY_PREFIX: Array<[string, string]> = [
|
|
39
|
+
["uikit/form", "@mapomodule/form"],
|
|
40
|
+
["uikit", "@mapomodule/uikit"],
|
|
41
|
+
["modules/core", "@mapomodule/core"],
|
|
42
|
+
["modules/store", "@mapomodule/store"],
|
|
43
|
+
["modules/utils", "@mapomodule/utils"],
|
|
44
|
+
["modules/i18n", "@mapomodule/i18n"],
|
|
45
|
+
["modules/api", "@mapomodule/core"],
|
|
46
|
+
["modules/camomilla", "mapo-integrations-camomilla"],
|
|
47
|
+
];
|
|
48
|
+
|
|
49
|
+
/** Pages that are pure API reference rather than task-oriented docs. */
|
|
50
|
+
const REFERENCE_PATH = /(?:^|\/)api\.md$/;
|
|
51
|
+
/** Headings that introduce a props/slots/emits table inside any page. */
|
|
52
|
+
const REFERENCE_HEADING = /^(props|slots|emits|events|exposed|api)\b/i;
|
|
53
|
+
|
|
54
|
+
/** GitHub-compatible heading slug (matches VitePress anchors). */
|
|
55
|
+
export function slugify(heading: string): string {
|
|
56
|
+
return heading
|
|
57
|
+
.toLowerCase()
|
|
58
|
+
.replace(/`/g, "")
|
|
59
|
+
.replace(/[^\w\s-]/g, "")
|
|
60
|
+
.trim()
|
|
61
|
+
.replace(/\s+/g, "-");
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function toPosix(path: string): string {
|
|
65
|
+
return sep === "/" ? path : path.split(sep).join("/");
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Recursively collects `*.md` files, skipping internal directories. */
|
|
69
|
+
export function collectMarkdownFiles(root: string): string[] {
|
|
70
|
+
const files: string[] = [];
|
|
71
|
+
|
|
72
|
+
const walk = (dir: string) => {
|
|
73
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
74
|
+
if (entry.name.startsWith(".") && entry.name !== ".vitepress") continue;
|
|
75
|
+
const full = join(dir, entry.name);
|
|
76
|
+
if (entry.isDirectory()) {
|
|
77
|
+
if (EXCLUDED_DIRS.has(entry.name)) continue;
|
|
78
|
+
walk(full);
|
|
79
|
+
} else if (
|
|
80
|
+
entry.isFile() &&
|
|
81
|
+
entry.name.endsWith(".md") &&
|
|
82
|
+
!EXCLUDED_FILES.has(entry.name)
|
|
83
|
+
) {
|
|
84
|
+
files.push(full);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
walk(root);
|
|
90
|
+
return files.sort();
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Symbols worth boosting: components, composables, field types, page meta keys. */
|
|
94
|
+
export function extractTags(text: string): string[] {
|
|
95
|
+
const tags = new Set<string>();
|
|
96
|
+
|
|
97
|
+
for (const match of text.matchAll(/\bMapo[A-Z][A-Za-z0-9]*/g))
|
|
98
|
+
tags.add(match[0]);
|
|
99
|
+
for (const match of text.matchAll(/\buse[A-Z][A-Za-z0-9]*/g))
|
|
100
|
+
tags.add(match[0]);
|
|
101
|
+
for (const match of text.matchAll(/\btype:\s*["']([a-z0-9-]+)["']/g)) {
|
|
102
|
+
if (match[1]) tags.add(match[1]);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return [...tags];
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
interface RawSection {
|
|
109
|
+
heading: string;
|
|
110
|
+
level: number;
|
|
111
|
+
lines: string[];
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Splits markdown at H2 (and H3 when a section is too long), ignoring headings
|
|
116
|
+
* that appear inside fenced code blocks.
|
|
117
|
+
*/
|
|
118
|
+
export function splitSections(markdown: string): {
|
|
119
|
+
title: string;
|
|
120
|
+
sections: RawSection[];
|
|
121
|
+
} {
|
|
122
|
+
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
|
|
123
|
+
const sections: RawSection[] = [];
|
|
124
|
+
let title = "";
|
|
125
|
+
let current: RawSection = { heading: "", level: 1, lines: [] };
|
|
126
|
+
let fence: string | null = null;
|
|
127
|
+
|
|
128
|
+
for (const line of lines) {
|
|
129
|
+
const fenceMatch = /^\s*(```|~~~)/.exec(line);
|
|
130
|
+
if (fenceMatch) {
|
|
131
|
+
if (fence && line.trimStart().startsWith(fence)) fence = null;
|
|
132
|
+
else if (!fence) fence = fenceMatch[1]!;
|
|
133
|
+
current.lines.push(line);
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (!fence) {
|
|
138
|
+
const heading = /^(#{1,3})\s+(.*)$/.exec(line);
|
|
139
|
+
if (heading) {
|
|
140
|
+
const level = heading[1]!.length;
|
|
141
|
+
const text = heading[2]!.trim();
|
|
142
|
+
if (level === 1 && !title) {
|
|
143
|
+
title = text;
|
|
144
|
+
current.heading ||= text;
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (level >= 2) {
|
|
148
|
+
if (current.lines.some((l) => l.trim())) sections.push(current);
|
|
149
|
+
current = { heading: text, level, lines: [] };
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
current.lines.push(line);
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (current.lines.some((l) => l.trim())) sections.push(current);
|
|
159
|
+
return { title, sections };
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/** Breaks an oversized section body into paragraph-aligned windows. */
|
|
163
|
+
function splitLongText(text: string): string[] {
|
|
164
|
+
if (text.length <= MAX_CHUNK_CHARS) return [text];
|
|
165
|
+
|
|
166
|
+
const parts: string[] = [];
|
|
167
|
+
let buffer = "";
|
|
168
|
+
for (const paragraph of text.split(/\n{2,}/)) {
|
|
169
|
+
if (buffer && buffer.length + paragraph.length > MAX_CHUNK_CHARS) {
|
|
170
|
+
parts.push(buffer.trim());
|
|
171
|
+
buffer = "";
|
|
172
|
+
}
|
|
173
|
+
buffer += `${paragraph}\n\n`;
|
|
174
|
+
}
|
|
175
|
+
if (buffer.trim()) parts.push(buffer.trim());
|
|
176
|
+
return parts;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Chunks a single markdown file. `path` is relative to the docs root. */
|
|
180
|
+
export function chunkMarkdown(path: string, markdown: string): DocChunk[] {
|
|
181
|
+
const posixPath = toPosix(path);
|
|
182
|
+
const segments = posixPath.split("/");
|
|
183
|
+
const section = segments.length > 1 ? segments[0]! : "root";
|
|
184
|
+
const group = segments.length > 2 ? segments[1] : undefined;
|
|
185
|
+
const pkg = PKG_BY_PREFIX.find(([prefix]) =>
|
|
186
|
+
posixPath.startsWith(prefix),
|
|
187
|
+
)?.[1];
|
|
188
|
+
|
|
189
|
+
const { title, sections } = splitSections(markdown);
|
|
190
|
+
const docTitle = title || segments.at(-1)!.replace(/\.md$/, "");
|
|
191
|
+
const isReferencePage = REFERENCE_PATH.test(posixPath);
|
|
192
|
+
const chunks: DocChunk[] = [];
|
|
193
|
+
const seenAnchors = new Map<string, number>();
|
|
194
|
+
|
|
195
|
+
for (const rawSection of sections) {
|
|
196
|
+
const heading = rawSection.heading || docTitle;
|
|
197
|
+
const body = rawSection.lines.join("\n").trim();
|
|
198
|
+
if (!body) continue;
|
|
199
|
+
|
|
200
|
+
const parts = splitLongText(body);
|
|
201
|
+
parts.forEach((text, partIndex) => {
|
|
202
|
+
const baseAnchor = rawSection.heading ? slugify(rawSection.heading) : "";
|
|
203
|
+
const seen = seenAnchors.get(baseAnchor) ?? 0;
|
|
204
|
+
seenAnchors.set(baseAnchor, seen + 1);
|
|
205
|
+
// Duplicate headings inside one page get `-1`, `-2`… like VitePress does.
|
|
206
|
+
const anchor = `${baseAnchor}${seen > 0 ? `-${seen}` : ""}`;
|
|
207
|
+
|
|
208
|
+
chunks.push({
|
|
209
|
+
id: `${posixPath}#${anchor}${partIndex > 0 ? `~${partIndex}` : ""}`,
|
|
210
|
+
path: posixPath,
|
|
211
|
+
section,
|
|
212
|
+
...(group ? { group } : {}),
|
|
213
|
+
...(pkg ? { pkg } : {}),
|
|
214
|
+
title: docTitle,
|
|
215
|
+
heading,
|
|
216
|
+
anchor,
|
|
217
|
+
level: rawSection.heading ? rawSection.level : 1,
|
|
218
|
+
...(isReferencePage || REFERENCE_HEADING.test(heading)
|
|
219
|
+
? { kind: "reference" as const }
|
|
220
|
+
: {}),
|
|
221
|
+
text,
|
|
222
|
+
tags: extractTags(text),
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
return chunks;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Builds the BM25 inverted index over already-chunked docs. */
|
|
231
|
+
export function buildIndex(chunks: DocChunk[]): Bm25Index {
|
|
232
|
+
const terms: Record<string, Array<[number, number]>> = {};
|
|
233
|
+
const lengths: number[] = [];
|
|
234
|
+
|
|
235
|
+
chunks.forEach((chunk, chunkIndex) => {
|
|
236
|
+
const counts = new Map<string, number>();
|
|
237
|
+
const add = (input: string, boost: number) => {
|
|
238
|
+
for (const token of tokenize(input)) {
|
|
239
|
+
counts.set(token, (counts.get(token) ?? 0) + boost);
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
add(chunk.text, BOOST.text);
|
|
244
|
+
add(chunk.heading, BOOST.heading);
|
|
245
|
+
add(chunk.title, BOOST.title);
|
|
246
|
+
add(chunk.tags.join(" "), BOOST.tags);
|
|
247
|
+
|
|
248
|
+
let length = 0;
|
|
249
|
+
for (const [term, frequency] of counts) {
|
|
250
|
+
(terms[term] ??= []).push([chunkIndex, frequency]);
|
|
251
|
+
length += frequency;
|
|
252
|
+
}
|
|
253
|
+
lengths.push(length);
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
const total = chunks.length;
|
|
257
|
+
const avgLength = total ? lengths.reduce((a, b) => a + b, 0) / total : 0;
|
|
258
|
+
return { terms, lengths, avgLength, total };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Reads every doc under `docsRoot` and returns the full knowledge payload. */
|
|
262
|
+
export function buildDocsKnowledge(docsRoot: string): DocsKnowledge {
|
|
263
|
+
const files = collectMarkdownFiles(docsRoot);
|
|
264
|
+
const chunks: DocChunk[] = [];
|
|
265
|
+
|
|
266
|
+
for (const file of files) {
|
|
267
|
+
if (!statSync(file).isFile()) continue;
|
|
268
|
+
const markdown = readFileSync(file, "utf-8");
|
|
269
|
+
chunks.push(...chunkMarkdown(relative(docsRoot, file), markdown));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
return {
|
|
273
|
+
version: KNOWLEDGE_VERSION,
|
|
274
|
+
generatedAt: new Date().toISOString(),
|
|
275
|
+
docsRoot: "docs",
|
|
276
|
+
chunks,
|
|
277
|
+
index: buildIndex(chunks),
|
|
278
|
+
};
|
|
279
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Loads the knowledge base generated at package build time.
|
|
3
|
+
*
|
|
4
|
+
* The Nitro side is handed an absolute directory (computed by the module, which
|
|
5
|
+
* knows where the package lives); the CLI resolves it from its own location.
|
|
6
|
+
*/
|
|
7
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join, resolve } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { KNOWLEDGE_VERSION } from "./indexer.js";
|
|
11
|
+
import type { ApiKnowledge, DocsKnowledge } from "./types.js";
|
|
12
|
+
|
|
13
|
+
export const DOCS_KNOWLEDGE_FILE = "docs.json";
|
|
14
|
+
export const API_KNOWLEDGE_FILE = "api.json";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Bumped whenever the shape of `api.json` changes. Lives here, not in the
|
|
18
|
+
* build entry, so the writer imports it from the reader and the two can never
|
|
19
|
+
* disagree about what version means.
|
|
20
|
+
*/
|
|
21
|
+
export const API_KNOWLEDGE_VERSION = 1;
|
|
22
|
+
|
|
23
|
+
const cache = new Map<string, DocsKnowledge>();
|
|
24
|
+
const apiCache = new Map<string, ApiKnowledge>();
|
|
25
|
+
|
|
26
|
+
/** Directory layouts we may be imported from: `dist/`, `dist/runtime/core/`, `src/…`. */
|
|
27
|
+
const CANDIDATE_SUFFIXES = [
|
|
28
|
+
"knowledge",
|
|
29
|
+
"../knowledge",
|
|
30
|
+
"../../knowledge",
|
|
31
|
+
"../../../knowledge",
|
|
32
|
+
"../dist/knowledge",
|
|
33
|
+
"../../dist/knowledge",
|
|
34
|
+
"../../../dist/knowledge",
|
|
35
|
+
"../../../../dist/knowledge",
|
|
36
|
+
];
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Finds `knowledge/docs.json`, starting from `fromUrl` (defaults to this file).
|
|
40
|
+
* `MAPO_MCP_KNOWLEDGE_DIR` wins when set — used by tests and by the CLI when it
|
|
41
|
+
* runs against a source checkout.
|
|
42
|
+
*/
|
|
43
|
+
export function resolveKnowledgeDir(
|
|
44
|
+
fromUrl: string = import.meta.url,
|
|
45
|
+
): string | null {
|
|
46
|
+
const override = process.env.MAPO_MCP_KNOWLEDGE_DIR;
|
|
47
|
+
if (override && existsSync(join(override, DOCS_KNOWLEDGE_FILE)))
|
|
48
|
+
return override;
|
|
49
|
+
|
|
50
|
+
const base = dirname(fileURLToPath(fromUrl));
|
|
51
|
+
for (const suffix of CANDIDATE_SUFFIXES) {
|
|
52
|
+
const candidate = resolve(base, suffix);
|
|
53
|
+
if (existsSync(join(candidate, DOCS_KNOWLEDGE_FILE))) return candidate;
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export class KnowledgeNotBuiltError extends Error {
|
|
59
|
+
constructor(searchedFrom: string) {
|
|
60
|
+
super(
|
|
61
|
+
`Mapo knowledge base not found (looked around ${searchedFrom}). ` +
|
|
62
|
+
`Build it with \`pnpm --filter @mapomodule/mcp knowledge\`.`,
|
|
63
|
+
);
|
|
64
|
+
this.name = "KnowledgeNotBuiltError";
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Reads and caches `docs.json`. Throws a directive error when it is missing. */
|
|
69
|
+
export function loadDocsKnowledge(dir?: string | null): DocsKnowledge {
|
|
70
|
+
const directory = dir ?? resolveKnowledgeDir();
|
|
71
|
+
if (!directory)
|
|
72
|
+
throw new KnowledgeNotBuiltError(fileURLToPath(import.meta.url));
|
|
73
|
+
|
|
74
|
+
const cached = cache.get(directory);
|
|
75
|
+
if (cached) return cached;
|
|
76
|
+
|
|
77
|
+
const file = join(directory, DOCS_KNOWLEDGE_FILE);
|
|
78
|
+
if (!existsSync(file)) throw new KnowledgeNotBuiltError(directory);
|
|
79
|
+
|
|
80
|
+
const knowledge = JSON.parse(readFileSync(file, "utf-8")) as DocsKnowledge;
|
|
81
|
+
if (knowledge.version !== KNOWLEDGE_VERSION) {
|
|
82
|
+
throw new Error(
|
|
83
|
+
`Mapo knowledge base version mismatch: found ${knowledge.version}, expected ${KNOWLEDGE_VERSION}. Rebuild it.`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
cache.set(directory, knowledge);
|
|
88
|
+
return knowledge;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Reads and caches `api.json` — the component, field and composable surface
|
|
93
|
+
* extracted from source at build time.
|
|
94
|
+
*/
|
|
95
|
+
export function loadApiKnowledge(dir?: string | null): ApiKnowledge {
|
|
96
|
+
const directory = dir ?? resolveKnowledgeDir();
|
|
97
|
+
if (!directory)
|
|
98
|
+
throw new KnowledgeNotBuiltError(fileURLToPath(import.meta.url));
|
|
99
|
+
|
|
100
|
+
const cached = apiCache.get(directory);
|
|
101
|
+
if (cached) return cached;
|
|
102
|
+
|
|
103
|
+
const file = join(directory, API_KNOWLEDGE_FILE);
|
|
104
|
+
if (!existsSync(file)) throw new KnowledgeNotBuiltError(directory);
|
|
105
|
+
|
|
106
|
+
const api = JSON.parse(readFileSync(file, "utf-8")) as ApiKnowledge;
|
|
107
|
+
if (api.version !== API_KNOWLEDGE_VERSION) {
|
|
108
|
+
throw new Error(
|
|
109
|
+
`Mapo API surface version mismatch: found ${api.version}, expected ${API_KNOWLEDGE_VERSION}. Rebuild it.`,
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
apiCache.set(directory, api);
|
|
114
|
+
return api;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Test helper — drops the in-process cache. */
|
|
118
|
+
export function clearKnowledgeCache(): void {
|
|
119
|
+
cache.clear();
|
|
120
|
+
apiCache.clear();
|
|
121
|
+
}
|