@bascik/language-server 0.1.0-rc.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.
Files changed (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +101 -0
  3. package/dist/analyzer.d.ts +29 -0
  4. package/dist/analyzer.d.ts.map +1 -0
  5. package/dist/analyzer.js +1160 -0
  6. package/dist/analyzer.js.map +1 -0
  7. package/dist/api-rules.d.ts +12 -0
  8. package/dist/api-rules.d.ts.map +1 -0
  9. package/dist/api-rules.js +62 -0
  10. package/dist/api-rules.js.map +1 -0
  11. package/dist/bin.d.ts +3 -0
  12. package/dist/bin.d.ts.map +1 -0
  13. package/dist/bin.js +15 -0
  14. package/dist/bin.js.map +1 -0
  15. package/dist/cli.d.ts +3 -0
  16. package/dist/cli.d.ts.map +1 -0
  17. package/dist/cli.js +122 -0
  18. package/dist/cli.js.map +1 -0
  19. package/dist/compatibility-rules.json +50 -0
  20. package/dist/component-metadata.d.ts +24 -0
  21. package/dist/component-metadata.d.ts.map +1 -0
  22. package/dist/component-metadata.js +158 -0
  23. package/dist/component-metadata.js.map +1 -0
  24. package/dist/config.d.ts +13 -0
  25. package/dist/config.d.ts.map +1 -0
  26. package/dist/config.js +29 -0
  27. package/dist/config.js.map +1 -0
  28. package/dist/ignore-comments.d.ts +8 -0
  29. package/dist/ignore-comments.d.ts.map +1 -0
  30. package/dist/ignore-comments.js +65 -0
  31. package/dist/ignore-comments.js.map +1 -0
  32. package/dist/index.d.ts +12 -0
  33. package/dist/index.d.ts.map +1 -0
  34. package/dist/index.js +12 -0
  35. package/dist/index.js.map +1 -0
  36. package/dist/module-specifiers.d.ts +7 -0
  37. package/dist/module-specifiers.d.ts.map +1 -0
  38. package/dist/module-specifiers.js +197 -0
  39. package/dist/module-specifiers.js.map +1 -0
  40. package/dist/project.d.ts +20 -0
  41. package/dist/project.d.ts.map +1 -0
  42. package/dist/project.js +133 -0
  43. package/dist/project.js.map +1 -0
  44. package/dist/rules.d.ts +9 -0
  45. package/dist/rules.d.ts.map +1 -0
  46. package/dist/rules.js +15 -0
  47. package/dist/rules.js.map +1 -0
  48. package/dist/server-script-rules.d.ts +13 -0
  49. package/dist/server-script-rules.d.ts.map +1 -0
  50. package/dist/server-script-rules.js +253 -0
  51. package/dist/server-script-rules.js.map +1 -0
  52. package/dist/server.d.ts +18 -0
  53. package/dist/server.d.ts.map +1 -0
  54. package/dist/server.js +156 -0
  55. package/dist/server.js.map +1 -0
  56. package/dist/types.d.ts +18 -0
  57. package/dist/types.d.ts.map +1 -0
  58. package/dist/types.js +2 -0
  59. package/dist/types.js.map +1 -0
  60. package/package.json +57 -0
@@ -0,0 +1,1160 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { DiagnosticSeverity, CompletionItemKind, MarkupKind, } from 'vscode-languageserver';
4
+ import { isInsideComponentRoots, normalizeComponentName, htmlSuppliesComponentProp, } from './project.js';
5
+ import { matchCompatibilityRules } from './rules.js';
6
+ import { analyzeApiRouteSource } from './api-rules.js';
7
+ import { findModuleSpecifiers } from './module-specifiers.js';
8
+ import { analyzeServerScriptSource } from './server-script-rules.js';
9
+ import { analyzeComponentSource, } from './component-metadata.js';
10
+ import { parseIgnoreDirectives, isDiagnosticIgnored } from './ignore-comments.js';
11
+ import { loadExtensionConfig } from './config.js';
12
+ export const BUILT_IN_HTML_ELEMENTS = new Set([
13
+ 'a',
14
+ 'abbr',
15
+ 'address',
16
+ 'area',
17
+ 'article',
18
+ 'aside',
19
+ 'audio',
20
+ 'b',
21
+ 'base',
22
+ 'bdi',
23
+ 'bdo',
24
+ 'blockquote',
25
+ 'body',
26
+ 'br',
27
+ 'button',
28
+ 'canvas',
29
+ 'caption',
30
+ 'cite',
31
+ 'code',
32
+ 'col',
33
+ 'colgroup',
34
+ 'data',
35
+ 'datalist',
36
+ 'dd',
37
+ 'del',
38
+ 'details',
39
+ 'dfn',
40
+ 'dialog',
41
+ 'div',
42
+ 'dl',
43
+ 'dt',
44
+ 'em',
45
+ 'embed',
46
+ 'fieldset',
47
+ 'figcaption',
48
+ 'figure',
49
+ 'footer',
50
+ 'form',
51
+ 'h1',
52
+ 'h2',
53
+ 'h3',
54
+ 'h4',
55
+ 'h5',
56
+ 'h6',
57
+ 'head',
58
+ 'header',
59
+ 'hgroup',
60
+ 'hr',
61
+ 'html',
62
+ 'i',
63
+ 'iframe',
64
+ 'img',
65
+ 'input',
66
+ 'ins',
67
+ 'kbd',
68
+ 'label',
69
+ 'legend',
70
+ 'li',
71
+ 'link',
72
+ 'main',
73
+ 'map',
74
+ 'mark',
75
+ 'meta',
76
+ 'meter',
77
+ 'nav',
78
+ 'noscript',
79
+ 'object',
80
+ 'ol',
81
+ 'optgroup',
82
+ 'option',
83
+ 'output',
84
+ 'p',
85
+ 'picture',
86
+ 'pre',
87
+ 'progress',
88
+ 'q',
89
+ 'rp',
90
+ 'rt',
91
+ 'ruby',
92
+ 's',
93
+ 'samp',
94
+ 'script',
95
+ 'search',
96
+ 'section',
97
+ 'select',
98
+ 'slot',
99
+ 'small',
100
+ 'source',
101
+ 'span',
102
+ 'strong',
103
+ 'style',
104
+ 'sub',
105
+ 'summary',
106
+ 'sup',
107
+ 'table',
108
+ 'tbody',
109
+ 'td',
110
+ 'template',
111
+ 'textarea',
112
+ 'tfoot',
113
+ 'th',
114
+ 'thead',
115
+ 'time',
116
+ 'title',
117
+ 'tr',
118
+ 'track',
119
+ 'u',
120
+ 'ul',
121
+ 'var',
122
+ 'video',
123
+ 'wbr',
124
+ ]);
125
+ export const SCRIPT_DIRECTIVES = [
126
+ {
127
+ name: 'data-bascik-build',
128
+ detail: 'Bascik build-time script',
129
+ documentation: 'Executes in Node.js at build time. Standard output from console.log() replaces this script tag in the generated HTML.',
130
+ },
131
+ {
132
+ name: 'data-bascik-routes',
133
+ detail: 'Bascik dynamic routes script',
134
+ documentation: 'Executes in Node.js at build time. Outputs a JSON array of dynamic route parameters to generate multiple pages from a template.',
135
+ },
136
+ {
137
+ name: 'data-bascik-server',
138
+ detail: 'Bascik server-side request script',
139
+ documentation: 'Executes in Node.js per request on production and dev servers. The default exported handler function replaces this script tag.',
140
+ },
141
+ {
142
+ name: 'data-bascik-stream',
143
+ detail: 'Bascik server-side streaming script',
144
+ documentation: 'Executes in Node.js per request on production servers. Streams chunked HTML responses to the client as data becomes available.',
145
+ },
146
+ ];
147
+ export const SCRIPT_BLOCK_RE = /(<script\b(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/script\s*>/gi;
148
+ export function maskHtmlRawTextContents(html) {
149
+ return html.replace(/(<(script|style|textarea)\b(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)(<\/\2\s*>)/gi, (_match, openTag, _tagName, content, closeTag) => `${openTag}${' '.repeat(content.length)}${closeTag}`);
150
+ }
151
+ export function escapeRegExp(value) {
152
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
153
+ }
154
+ export function findMatchingClose(html, tagName, contentStart) {
155
+ const tn = tagName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
156
+ const openRe = new RegExp(`<${tn}[\\s>]`, 'gi');
157
+ const closeRe = new RegExp(`<\\/${tn}>`, 'gi');
158
+ let depth = 1;
159
+ let pos = contentStart;
160
+ while (pos < html.length) {
161
+ openRe.lastIndex = pos;
162
+ closeRe.lastIndex = pos;
163
+ const openMatch = openRe.exec(html);
164
+ const closeMatch = closeRe.exec(html);
165
+ if (!closeMatch)
166
+ return -1;
167
+ if (!openMatch || closeMatch.index < openMatch.index) {
168
+ depth--;
169
+ if (depth === 0)
170
+ return closeMatch.index;
171
+ pos = closeMatch.index + closeMatch[0].length;
172
+ }
173
+ else {
174
+ let inDoubleQuote = false;
175
+ let inSingleQuote = false;
176
+ let tagEnd = -1;
177
+ for (let i = openMatch.index; i < html.length; i++) {
178
+ const char = html[i];
179
+ if (char === '"' && !inSingleQuote) {
180
+ inDoubleQuote = !inDoubleQuote;
181
+ }
182
+ else if (char === "'" && !inDoubleQuote) {
183
+ inSingleQuote = !inSingleQuote;
184
+ }
185
+ else if (char === '>' && !inDoubleQuote && !inSingleQuote) {
186
+ tagEnd = i + 1;
187
+ break;
188
+ }
189
+ }
190
+ if (tagEnd !== -1) {
191
+ const fullOpenTag = html.slice(openMatch.index, tagEnd);
192
+ if (/\/\s*>$/.test(fullOpenTag)) {
193
+ pos = tagEnd;
194
+ continue;
195
+ }
196
+ depth++;
197
+ pos = tagEnd;
198
+ }
199
+ else {
200
+ depth++;
201
+ pos = openMatch.index + openMatch[0].length;
202
+ }
203
+ }
204
+ }
205
+ return -1;
206
+ }
207
+ export function findNearestParentComponent(source, componentMap) {
208
+ const stack = [];
209
+ const tagRegex = /<\/?([A-Za-z][\w-]*)(?:[^>"']|"[^"]*"|'[^']*')*>/g;
210
+ for (const match of source.matchAll(tagRegex)) {
211
+ const name = match[1].toLowerCase();
212
+ if (match[0].startsWith('</')) {
213
+ const matchingIndex = stack.lastIndexOf(name);
214
+ if (matchingIndex >= 0)
215
+ stack.splice(matchingIndex);
216
+ }
217
+ else if (!/\/\s*>$/.test(match[0])) {
218
+ stack.push(name);
219
+ }
220
+ }
221
+ return stack.reverse().find((name) => componentMap.has(name));
222
+ }
223
+ export function parseScriptOpenTagAttributes(openTag) {
224
+ const attrs = new Map();
225
+ const insideTag = openTag.replace(/^<script\b/i, '').replace(/>$/, '');
226
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
227
+ let match;
228
+ while ((match = attrRe.exec(insideTag)) !== null) {
229
+ const name = match[1]?.toLowerCase();
230
+ if (!name)
231
+ continue;
232
+ const value = match[2] ?? match[3] ?? match[4];
233
+ attrs.set(name, value === undefined ? true : value);
234
+ }
235
+ return attrs;
236
+ }
237
+ export function resolveScriptTarget(value, documentDir, importRootAbs, kind) {
238
+ if (value.startsWith('./') || value.startsWith('../'))
239
+ return path.resolve(documentDir, value);
240
+ if (value.startsWith('@/'))
241
+ return path.resolve(importRootAbs, value.slice(2));
242
+ if (value.startsWith('/'))
243
+ return undefined;
244
+ if (kind === 'src') {
245
+ if (/^[a-z][a-z\d+.-]*:/i.test(value))
246
+ return undefined;
247
+ return path.resolve(documentDir, value);
248
+ }
249
+ return undefined;
250
+ }
251
+ export function leadingSlashSpecifierMessage(specifier) {
252
+ const rest = specifier.replace(/^\/+/, '');
253
+ return (`Leading-slash specifier '${specifier}' is not supported in Bascik scripts. ` +
254
+ `A bare '/' is ambiguous (filesystem root vs. site root). ` +
255
+ `Use '@/${rest}' to resolve against scripts.importRoot, ` +
256
+ `or './${rest}' to resolve relative to this file.`);
257
+ }
258
+ export function collectLeadingSlashDiagnostics(document, openTag, scriptBody, blockStart, attrs) {
259
+ if (!attrs.has('data-bascik-build') &&
260
+ !attrs.has('data-bascik-server') &&
261
+ !attrs.has('data-bascik-routes') &&
262
+ !attrs.has('data-bascik-stream')) {
263
+ return [];
264
+ }
265
+ const out = [];
266
+ const push = (start, end, specifier) => {
267
+ out.push({
268
+ range: {
269
+ start: document.positionAt(start),
270
+ end: document.positionAt(end),
271
+ },
272
+ message: leadingSlashSpecifierMessage(specifier),
273
+ severity: DiagnosticSeverity.Error,
274
+ source: 'bascik',
275
+ code: 'leading-slash-specifier',
276
+ });
277
+ };
278
+ const srcMatch = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(openTag);
279
+ if (srcMatch) {
280
+ const srcValue = srcMatch[1] ?? srcMatch[2] ?? srcMatch[3] ?? '';
281
+ if (srcValue.startsWith('/')) {
282
+ const valueStart = blockStart + (srcMatch.index ?? 0) + srcMatch[0].indexOf(srcValue);
283
+ push(valueStart, valueStart + srcValue.length, srcValue);
284
+ }
285
+ }
286
+ const bodyStart = blockStart + openTag.length;
287
+ for (const { start, end, value } of findModuleSpecifiers(scriptBody)) {
288
+ if (value.startsWith('/'))
289
+ push(bodyStart + start, bodyStart + end, value);
290
+ }
291
+ return out;
292
+ }
293
+ export function createComponentDocumentationMarkdown(relativePath, metadata) {
294
+ const parts = [];
295
+ if (metadata?.description) {
296
+ parts.push(metadata.description, '\n\n');
297
+ }
298
+ parts.push(`Bascik component from \`${relativePath}\`.`);
299
+ if (metadata) {
300
+ parts.push('\n\n');
301
+ appendMetadataMembersMarkdown(parts, 'Props', metadata.props);
302
+ appendMetadataMembersMarkdown(parts, 'Slots', [
303
+ ...metadata.slots,
304
+ ...(metadata.defaultSlot ? [metadata.defaultSlot] : []),
305
+ ]);
306
+ }
307
+ return parts.join('');
308
+ }
309
+ function appendMetadataMembersMarkdown(parts, label, members) {
310
+ if (members.length === 0)
311
+ return;
312
+ parts.push(`**${label}:**\n\n`);
313
+ for (const member of members) {
314
+ parts.push(`- \`${member.name}\``);
315
+ if (member.description) {
316
+ parts.push(`: ${member.description}`);
317
+ }
318
+ parts.push('\n');
319
+ }
320
+ parts.push('\n');
321
+ }
322
+ export function completionReplacementRange(document, position) {
323
+ const offset = document.offsetAt(position);
324
+ const prefix = /[^\s<>"'=]*$/.exec(document.getText().slice(0, offset))?.[0] ?? '';
325
+ return {
326
+ start: document.positionAt(offset - prefix.length),
327
+ end: position,
328
+ };
329
+ }
330
+ export function createDiagnostics(document, fsPath, snapshot, openDocumentTexts = []) {
331
+ const { languageId } = document;
332
+ if (languageId !== 'css' &&
333
+ languageId !== 'javascript' &&
334
+ languageId !== 'typescript' &&
335
+ languageId !== 'html') {
336
+ return [];
337
+ }
338
+ const normalizedDocumentPath = fsPath.replace(/\\/g, '/');
339
+ if (/\.(test|spec)\.[a-z0-9]+$/i.test(normalizedDocumentPath)) {
340
+ return [];
341
+ }
342
+ const text = document.getText();
343
+ const diagnostics = [];
344
+ const isComponentDocument = snapshot !== undefined &&
345
+ isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots);
346
+ const isApiRouteDocument = normalizedDocumentPath.includes('/src/api/') &&
347
+ (languageId === 'typescript' || languageId === 'javascript');
348
+ if (isApiRouteDocument) {
349
+ const apiDiags = analyzeApiRouteSource(text);
350
+ for (const diag of apiDiags) {
351
+ let severity = DiagnosticSeverity.Warning;
352
+ if (diag.severity === 'error') {
353
+ severity = DiagnosticSeverity.Error;
354
+ }
355
+ else if (diag.severity === 'info') {
356
+ severity = DiagnosticSeverity.Information;
357
+ }
358
+ diagnostics.push({
359
+ range: {
360
+ start: { line: 0, character: 0 },
361
+ end: { line: 0, character: Math.min(text.length, 10) },
362
+ },
363
+ message: diag.message,
364
+ severity,
365
+ source: 'bascik',
366
+ });
367
+ }
368
+ }
369
+ if (languageId === 'html' && fsPath.startsWith('/')) {
370
+ if (snapshot && isInsideComponentRoots(normalizedDocumentPath, snapshot.componentRoots)) {
371
+ const fileName = path.basename(normalizedDocumentPath);
372
+ const nameWithoutExt = fileName.replace(/\.html$/i, '').toLowerCase();
373
+ if (!nameWithoutExt.includes('-') &&
374
+ !BUILT_IN_HTML_ELEMENTS.has(nameWithoutExt)) {
375
+ diagnostics.push({
376
+ range: {
377
+ start: { line: 0, character: 0 },
378
+ end: { line: 0, character: Math.min(text.length, 10) },
379
+ },
380
+ message: `Component "${nameWithoutExt}" is not hyphenated. Under WHATWG HTML §4.13, custom elements should include a hyphen (e.g. "my-${nameWithoutExt}") to avoid collisions with future HTML standards.`,
381
+ severity: DiagnosticSeverity.Warning,
382
+ source: 'bascik',
383
+ });
384
+ }
385
+ }
386
+ }
387
+ const addCompatibilityDiagnostics = (sourceText, kind, offset) => {
388
+ for (const rule of matchCompatibilityRules(sourceText, kind)) {
389
+ const flags = rule.regex.flags.includes('g')
390
+ ? rule.regex.flags
391
+ : `${rule.regex.flags}g`;
392
+ const regex = new RegExp(rule.regex.source, flags);
393
+ const match = regex.exec(sourceText);
394
+ if (!match || typeof match.index !== 'number')
395
+ continue;
396
+ const start = document.positionAt(offset + match.index);
397
+ const end = document.positionAt(offset + match.index + Math.max(match[0].length, 1));
398
+ diagnostics.push({
399
+ range: { start, end },
400
+ message: `${rule.message} ${rule.suggestion}`,
401
+ severity: DiagnosticSeverity.Warning,
402
+ source: 'bascik',
403
+ });
404
+ }
405
+ };
406
+ const isJavaScriptScriptTag = (openTag) => {
407
+ const attrs = parseScriptOpenTagAttributes(openTag);
408
+ const typeValue = attrs.get('type');
409
+ if (!typeValue || typeValue === true)
410
+ return true;
411
+ const normalized = String(typeValue).trim().toLowerCase();
412
+ return (normalized === 'module' ||
413
+ normalized === 'text/javascript' ||
414
+ normalized === 'application/javascript' ||
415
+ normalized === 'text/ecmascript' ||
416
+ normalized === 'application/ecmascript');
417
+ };
418
+ const scriptBlockRe = new RegExp(SCRIPT_BLOCK_RE.source, SCRIPT_BLOCK_RE.flags);
419
+ const styleBlockRe = /(<style\b(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)<\/style\s*>/gi;
420
+ if (languageId === 'html') {
421
+ if (isComponentDocument) {
422
+ const metadata = analyzeComponentSource(text, {
423
+ hasCompanionStyles: fs.existsSync(fsPath.replace(/\.html$/i, '.css')),
424
+ });
425
+ for (const metadataDiagnostic of metadata.diagnostics) {
426
+ diagnostics.push({
427
+ range: {
428
+ start: document.positionAt(metadataDiagnostic.start),
429
+ end: document.positionAt(metadataDiagnostic.end),
430
+ },
431
+ message: metadataDiagnostic.message,
432
+ severity: DiagnosticSeverity.Warning,
433
+ source: 'bascik',
434
+ code: metadataDiagnostic.code,
435
+ });
436
+ }
437
+ const referenceScanText = maskHtmlRawTextContents(text).replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) => ' '.repeat(comment.length));
438
+ const declaredIds = new Set(Array.from(referenceScanText.matchAll(/\sid\s*=\s*(?:"([^"]+)"|'([^']+)')/gi))
439
+ .map((match) => match[1] ?? match[2])
440
+ .filter((id) => Boolean(id)));
441
+ const idReferenceAttributeRegex = /\s(for|itemref|aria-activedescendant|aria-details|aria-errormessage|aria-labelledby|aria-describedby|aria-controls|aria-owns|aria-flowto)\s*=\s*(?:"([^"]*)"|'([^']*)')/gi;
442
+ let idReferenceMatch;
443
+ while ((idReferenceMatch =
444
+ idReferenceAttributeRegex.exec(referenceScanText)) !== null) {
445
+ const value = idReferenceMatch[2] ?? idReferenceMatch[3] ?? '';
446
+ for (const id of value.trim().split(/\s+/).filter(Boolean)) {
447
+ if (declaredIds.has(id))
448
+ continue;
449
+ const valueOffset = idReferenceMatch[0].indexOf(id);
450
+ const start = document.positionAt(idReferenceMatch.index + Math.max(valueOffset, 0));
451
+ const end = document.positionAt(idReferenceMatch.index + Math.max(valueOffset, 0) + id.length);
452
+ diagnostics.push({
453
+ range: { start, end },
454
+ message: `ID reference "${id}" is not declared in this component and will be left unscoped.`,
455
+ severity: DiagnosticSeverity.Information,
456
+ source: 'bascik',
457
+ });
458
+ }
459
+ }
460
+ const fragmentReferenceRegex = /\shref\s*=\s*(?:"#([^"]+)"|'#([^']+)')/gi;
461
+ let fragmentReferenceMatch;
462
+ while ((fragmentReferenceMatch =
463
+ fragmentReferenceRegex.exec(referenceScanText)) !== null) {
464
+ const id = fragmentReferenceMatch[1] ?? fragmentReferenceMatch[2];
465
+ if (!id || declaredIds.has(id))
466
+ continue;
467
+ const idOffset = fragmentReferenceMatch[0].indexOf(id);
468
+ const start = document.positionAt(fragmentReferenceMatch.index + Math.max(idOffset, 0));
469
+ const end = document.positionAt(fragmentReferenceMatch.index + Math.max(idOffset, 0) + id.length);
470
+ diagnostics.push({
471
+ range: { start, end },
472
+ message: `ID reference "${id}" is not declared in this component and will be left unscoped.`,
473
+ severity: DiagnosticSeverity.Information,
474
+ source: 'bascik',
475
+ });
476
+ }
477
+ }
478
+ const preserveDirectiveRegex = /data-bascik-preserve(?:\s*=\s*("([^"]*)"|'([^']*)'))?/gi;
479
+ let preserveMatch;
480
+ while ((preserveMatch = preserveDirectiveRegex.exec(text)) !== null) {
481
+ if (preserveMatch[1] === undefined)
482
+ continue;
483
+ const value = preserveMatch[2] ?? preserveMatch[3] ?? '';
484
+ for (const preserveToken of value.trim().split(/\s+/).filter(Boolean)) {
485
+ if (preserveToken === 'id' ||
486
+ preserveToken === 'name' ||
487
+ preserveToken === 'class')
488
+ continue;
489
+ const tokenOffset = preserveMatch[0].indexOf(preserveToken);
490
+ const start = document.positionAt(preserveMatch.index + Math.max(tokenOffset, 0));
491
+ const end = document.positionAt(preserveMatch.index + Math.max(tokenOffset, 0) + preserveToken.length);
492
+ diagnostics.push({
493
+ range: { start, end },
494
+ message: `Unknown data-bascik-preserve token "${preserveToken}". Valid tokens are id, name, and class.`,
495
+ severity: DiagnosticSeverity.Warning,
496
+ source: 'bascik',
497
+ });
498
+ }
499
+ }
500
+ const formOpenTagRegex = /<form\b(?:[^>"']|"[^"]*"|'[^']*')*>/gi;
501
+ let formMatch;
502
+ while (isComponentDocument &&
503
+ (formMatch = formOpenTagRegex.exec(text)) !== null) {
504
+ const actionMatch = formMatch[0].match(/\saction\s*=\s*(?:"([^"]*)"|'([^']*)')/i);
505
+ const action = actionMatch?.[1] ?? actionMatch?.[2];
506
+ if (!action || !/^(?:https?:)?\/\//i.test(action))
507
+ continue;
508
+ const preserveMatch = formMatch[0].match(/\sdata-bascik-preserve(?:\s*=\s*(?:"([^"]*)"|'([^']*)'))?/i);
509
+ const preservesName = preserveMatch !== null &&
510
+ (preserveMatch[1] === undefined ||
511
+ (preserveMatch[1] ?? preserveMatch[2] ?? '')
512
+ .trim()
513
+ .split(/\s+/)
514
+ .includes('name'));
515
+ if (preservesName)
516
+ continue;
517
+ const start = document.positionAt(formMatch.index);
518
+ const end = document.positionAt(formMatch.index + formMatch[0].length);
519
+ diagnostics.push({
520
+ range: { start, end },
521
+ message: 'External form actions require data-bascik-preserve="name" so submitted field names remain literal.',
522
+ severity: DiagnosticSeverity.Warning,
523
+ source: 'bascik',
524
+ });
525
+ }
526
+ if (snapshot && isComponentDocument) {
527
+ const componentName = normalizeComponentName(fsPath);
528
+ const directiveRegex = /data-bascik-attr-([A-Za-z_:][\w:.-]*)\s*=\s*(?:"([\w-]+)"|'([\w-]+)')/gi;
529
+ let directiveMatch;
530
+ while ((directiveMatch = directiveRegex.exec(text)) !== null) {
531
+ const targetName = directiveMatch[1];
532
+ const propName = directiveMatch[2] ?? directiveMatch[3];
533
+ const suppliedInOpen = openDocumentTexts.some(({ text }) => htmlSuppliesComponentProp(text, componentName, propName));
534
+ const suppliedInDisk = Array.from(snapshot.htmlUsageByFile.values()).some((usageHtml) => htmlSuppliesComponentProp(usageHtml, componentName, propName));
535
+ if (suppliedInOpen || suppliedInDisk)
536
+ continue;
537
+ const start = document.positionAt(directiveMatch.index);
538
+ const end = document.positionAt(directiveMatch.index + directiveMatch[0].length);
539
+ diagnostics.push({
540
+ range: { start, end },
541
+ message: `data-bascik-attr-${targetName} references prop "${propName}", but no <${componentName}> usage supplies data-bascik-prop-${propName}.`,
542
+ severity: DiagnosticSeverity.Warning,
543
+ source: 'bascik',
544
+ });
545
+ }
546
+ }
547
+ let scriptMatch;
548
+ while ((scriptMatch = scriptBlockRe.exec(text)) !== null) {
549
+ const openTag = scriptMatch[1];
550
+ const scriptBody = scriptMatch[2] ?? '';
551
+ const scriptBodyOffset = (scriptMatch.index ?? 0) + openTag.length;
552
+ const attrs = parseScriptOpenTagAttributes(openTag);
553
+ const directiveAttrs = [
554
+ 'data-bascik-build',
555
+ 'data-bascik-server',
556
+ 'data-bascik-routes',
557
+ 'data-bascik-stream',
558
+ ];
559
+ const presentDirectives = directiveAttrs.filter((d) => attrs.has(d));
560
+ for (let i = 0; i < presentDirectives.length; i++) {
561
+ for (let j = i + 1; j < presentDirectives.length; j++) {
562
+ const d1 = presentDirectives[i];
563
+ const d2 = presentDirectives[j];
564
+ let message;
565
+ if ((d1 === 'data-bascik-build' && d2 === 'data-bascik-server') ||
566
+ (d1 === 'data-bascik-server' && d2 === 'data-bascik-build')) {
567
+ message =
568
+ 'data-bascik-build and data-bascik-server cannot both appear on the same <script> tag. Remove one - a script runs at build time or at request time, not both.';
569
+ }
570
+ else if ((d1 === 'data-bascik-routes' && d2 === 'data-bascik-server') ||
571
+ (d1 === 'data-bascik-server' && d2 === 'data-bascik-routes')) {
572
+ message =
573
+ 'data-bascik-routes and data-bascik-server cannot both appear on the same <script> tag. Remove one - a routes script runs at build time, while a server script runs at request time.';
574
+ }
575
+ else if ((d1 === 'data-bascik-routes' && d2 === 'data-bascik-build') ||
576
+ (d1 === 'data-bascik-build' && d2 === 'data-bascik-routes')) {
577
+ message =
578
+ 'data-bascik-routes and data-bascik-build cannot both appear on the same <script> tag. Remove one.';
579
+ }
580
+ else {
581
+ message = `${d1} and ${d2} cannot both appear on the same <script> tag. Remove one.`;
582
+ }
583
+ const start = document.positionAt(scriptMatch.index ?? 0);
584
+ const end = document.positionAt((scriptMatch.index ?? 0) + openTag.length);
585
+ diagnostics.push({
586
+ range: { start, end },
587
+ message,
588
+ severity: DiagnosticSeverity.Error,
589
+ source: 'bascik',
590
+ });
591
+ }
592
+ }
593
+ if (attrs.has('data-bascik-server') || attrs.has('data-bascik-stream')) {
594
+ const directive = attrs.has('data-bascik-stream') ? 'stream' : 'server';
595
+ const hasSrcAttribute = /\ssrc\s*=/i.test(openTag);
596
+ const serverDiags = analyzeServerScriptSource(scriptBody, {
597
+ hasSrcAttribute,
598
+ directive,
599
+ });
600
+ for (const sd of serverDiags) {
601
+ const start = document.positionAt(scriptBodyOffset + sd.start);
602
+ const end = document.positionAt(scriptBodyOffset + sd.end);
603
+ let severity = DiagnosticSeverity.Error;
604
+ if (sd.severity === 'warning') {
605
+ severity = DiagnosticSeverity.Warning;
606
+ }
607
+ else if (sd.severity === 'info') {
608
+ severity = DiagnosticSeverity.Information;
609
+ }
610
+ diagnostics.push({
611
+ range: { start, end },
612
+ message: sd.message,
613
+ severity,
614
+ source: 'bascik',
615
+ code: sd.code,
616
+ });
617
+ }
618
+ }
619
+ diagnostics.push(...collectLeadingSlashDiagnostics(document, openTag, scriptBody, scriptMatch.index ?? 0, attrs));
620
+ if (isJavaScriptScriptTag(openTag)) {
621
+ addCompatibilityDiagnostics(scriptBody, 'js', scriptBodyOffset);
622
+ }
623
+ }
624
+ let styleMatch;
625
+ const hasCompanionCss = fsPath.toLowerCase().endsWith('.html') &&
626
+ fs.existsSync(fsPath.replace(/\.html$/i, '.css'));
627
+ const maskedText = text
628
+ .replace(/(<(style|textarea|script)\b(?:[^>"']|"[^"]*"|'[^']*')*>)([\s\S]*?)(<\/\2\s*>)/gi, (_m, open, _tag, content, close) => open + ' '.repeat(content.length) + close)
629
+ .replace(/<!--([\s\S]*?)-->/g, (_m, content) => '<!--' + ' '.repeat(content.length) + '-->');
630
+ const componentMap = snapshot?.componentMap ?? new Map();
631
+ const componentNames = Array.from(componentMap.keys());
632
+ // 1. Diagnose script directives on non-script tags
633
+ const elementOpenTagRe = /<([A-Za-z][\w-]*)(?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?\/?>/gi;
634
+ let elementMatch;
635
+ while ((elementMatch = elementOpenTagRe.exec(maskedText)) !== null) {
636
+ const tagName = elementMatch[1].toLowerCase();
637
+ if (tagName === 'script')
638
+ continue;
639
+ const openTag = elementMatch[0];
640
+ const matchStart = elementMatch.index;
641
+ const scriptDirectives = new Set([
642
+ 'data-bascik-build',
643
+ 'data-bascik-server',
644
+ 'data-bascik-routes',
645
+ 'data-bascik-stream',
646
+ ]);
647
+ const insideTag = openTag
648
+ .replace(/^<[A-Za-z][\w-]*\s*/i, '')
649
+ .replace(/\/?>$/, '');
650
+ const baseOffset = openTag.length - insideTag.length - (openTag.endsWith('/>') ? 2 : 1);
651
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
652
+ let attrMatch;
653
+ while ((attrMatch = attrRe.exec(insideTag)) !== null) {
654
+ const attrName = attrMatch[1].toLowerCase();
655
+ if (scriptDirectives.has(attrName)) {
656
+ const start = document.positionAt(matchStart + baseOffset + attrMatch.index);
657
+ const end = document.positionAt(matchStart + baseOffset + attrMatch.index + attrMatch[1].length);
658
+ diagnostics.push({
659
+ range: { start, end },
660
+ message: `\`${attrMatch[1]}\` is only valid on <script> tags. It has no effect on <${tagName}>.`,
661
+ severity: DiagnosticSeverity.Error,
662
+ source: 'bascik',
663
+ });
664
+ }
665
+ }
666
+ }
667
+ // 2. Diagnose data-bascik-slot outside of components, on the component itself, or targeting undeclared slots
668
+ const slotTagRe = /<([A-Za-z][\w-]*)(?:\s+(?:[^>"']|"[^"]*"|'[^']*')*?)?\/?>/gi;
669
+ let slotMatch;
670
+ while ((slotMatch = slotTagRe.exec(maskedText)) !== null) {
671
+ const openTag = slotMatch[0];
672
+ const matchStart = slotMatch.index;
673
+ const insideTag = openTag
674
+ .replace(/^<[A-Za-z][\w-]*\s*/i, '')
675
+ .replace(/\/?>$/, '');
676
+ const baseOffset = openTag.length - insideTag.length - (openTag.endsWith('/>') ? 2 : 1);
677
+ const attrRe = /([^\s"'=<>`/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/gi;
678
+ let attrMatch;
679
+ let slotAttr = null;
680
+ while ((attrMatch = attrRe.exec(insideTag)) !== null) {
681
+ if (attrMatch[1].toLowerCase() === 'data-bascik-slot') {
682
+ slotAttr = {
683
+ name: attrMatch[1],
684
+ value: attrMatch[2] ?? attrMatch[3] ?? attrMatch[4],
685
+ index: attrMatch.index,
686
+ };
687
+ break;
688
+ }
689
+ }
690
+ if (!slotAttr)
691
+ continue;
692
+ const tagOffset = slotMatch.index;
693
+ const slotName = slotAttr.value;
694
+ const parentName = findNearestParentComponent(maskedText.slice(0, tagOffset), componentMap);
695
+ const isInsideComponentDefinition = isComponentDocument;
696
+ if (!parentName && !isInsideComponentDefinition) {
697
+ const start = document.positionAt(matchStart + baseOffset + slotAttr.index);
698
+ const end = document.positionAt(matchStart + baseOffset + slotAttr.index + slotAttr.name.length);
699
+ diagnostics.push({
700
+ range: { start, end },
701
+ message: '`data-bascik-slot` is only valid inside a Bascik component body.',
702
+ severity: DiagnosticSeverity.Error,
703
+ source: 'bascik',
704
+ });
705
+ }
706
+ else if (parentName) {
707
+ const parentMeta = snapshot?.componentMetadata.get(parentName);
708
+ if (slotName !== undefined && parentMeta) {
709
+ const declaredSlot = parentMeta.slots.some((s) => s.name.toLowerCase() === slotName.toLowerCase());
710
+ if (!declaredSlot) {
711
+ const start = document.positionAt(matchStart + baseOffset + slotAttr.index);
712
+ const end = document.positionAt(matchStart + baseOffset + slotAttr.index + slotAttr.name.length);
713
+ diagnostics.push({
714
+ range: { start, end },
715
+ message: `Component <${parentName}> does not declare slot "${slotName}".`,
716
+ severity: DiagnosticSeverity.Error,
717
+ source: 'bascik',
718
+ });
719
+ }
720
+ }
721
+ }
722
+ }
723
+ if (componentNames.length > 0) {
724
+ componentNames.sort((a, b) => b.length - a.length);
725
+ const escapedNames = componentNames.map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
726
+ const componentTagRe = new RegExp(`<(${escapedNames.join('|')})\\b`, 'gi');
727
+ let compMatch;
728
+ while ((compMatch = componentTagRe.exec(maskedText)) !== null) {
729
+ const tagStartIndex = compMatch.index;
730
+ const tagName = compMatch[1].toLowerCase();
731
+ let inDoubleQuote = false;
732
+ let inSingleQuote = false;
733
+ let openTagEndIndex = -1;
734
+ for (let i = tagStartIndex; i < maskedText.length; i++) {
735
+ const char = maskedText[i];
736
+ if (char === '"' && !inSingleQuote) {
737
+ inDoubleQuote = !inDoubleQuote;
738
+ }
739
+ else if (char === "'" && !inDoubleQuote) {
740
+ inSingleQuote = !inSingleQuote;
741
+ }
742
+ else if (char === '>' && !inDoubleQuote && !inSingleQuote) {
743
+ openTagEndIndex = i + 1;
744
+ break;
745
+ }
746
+ }
747
+ if (openTagEndIndex !== -1) {
748
+ const openTagText = maskedText.slice(tagStartIndex, openTagEndIndex);
749
+ const compMeta = snapshot?.componentMetadata.get(tagName);
750
+ if (compMeta) {
751
+ const propRe = /\b(data-bascik-prop-([\w-]+))\b/gi;
752
+ let propMatch;
753
+ while ((propMatch = propRe.exec(openTagText)) !== null) {
754
+ const fullPropAttr = propMatch[1];
755
+ const propName = propMatch[2];
756
+ const isDeclared = compMeta.props.some((p) => p.name.toLowerCase() === propName.toLowerCase());
757
+ if (!isDeclared) {
758
+ const start = document.positionAt(tagStartIndex + propMatch.index);
759
+ const end = document.positionAt(tagStartIndex + propMatch.index + fullPropAttr.length);
760
+ diagnostics.push({
761
+ range: { start, end },
762
+ message: `Component <${tagName}> does not declare prop "${propName}".`,
763
+ severity: DiagnosticSeverity.Warning,
764
+ source: 'bascik',
765
+ });
766
+ }
767
+ }
768
+ }
769
+ const isSelfClosing = /\/\s*>$/.test(openTagText);
770
+ if (!isSelfClosing) {
771
+ const closeIndex = findMatchingClose(maskedText, tagName, openTagEndIndex);
772
+ if (closeIndex === -1) {
773
+ const start = document.positionAt(tagStartIndex);
774
+ const end = document.positionAt(openTagEndIndex);
775
+ diagnostics.push({
776
+ range: { start, end },
777
+ message: `Component tag <${tagName}> is unclosed. It will be treated as self-closing (<${tagName}/>), but an explicit closing tag is recommended to avoid layout or scoping issues.`,
778
+ severity: DiagnosticSeverity.Warning,
779
+ source: 'bascik',
780
+ code: 'unclosed-component-tag',
781
+ });
782
+ }
783
+ else if (compMeta) {
784
+ const hasZeroSlots = !compMeta.defaultSlot && compMeta.slots.length === 0;
785
+ if (hasZeroSlots) {
786
+ const start = document.positionAt(tagStartIndex);
787
+ const end = document.positionAt(closeIndex + `</${tagName}>`.length);
788
+ diagnostics.push({
789
+ range: { start, end },
790
+ message: `Component <${tagName}> defines no slots and accepts no children. Use self-closing tag <${tagName} /> instead of paired <${tagName}></${tagName}>.`,
791
+ severity: DiagnosticSeverity.Warning,
792
+ source: 'bascik',
793
+ code: 'prefer-self-closing-component',
794
+ });
795
+ }
796
+ }
797
+ }
798
+ }
799
+ }
800
+ }
801
+ const styleMatches = [];
802
+ while ((styleMatch = styleBlockRe.exec(maskedText)) !== null) {
803
+ styleMatches.push(styleMatch);
804
+ }
805
+ for (const match of styleMatches) {
806
+ const openTag = match[1];
807
+ const styleBody = match[2] ?? '';
808
+ const styleBodyOffset = (match.index ?? 0) + openTag.length;
809
+ if (hasCompanionCss) {
810
+ const start = document.positionAt(match.index ?? 0);
811
+ const end = document.positionAt((match.index ?? 0) + openTag.length);
812
+ diagnostics.push({
813
+ range: { start, end },
814
+ message: 'Component has both a companion .css file and an inline <style> tag. They will be combined at build time, but mixing both is not recommended for readability and maintainability.',
815
+ severity: DiagnosticSeverity.Warning,
816
+ source: 'bascik',
817
+ });
818
+ }
819
+ addCompatibilityDiagnostics(styleBody, 'css', styleBodyOffset);
820
+ }
821
+ }
822
+ else if (languageId === 'css') {
823
+ addCompatibilityDiagnostics(text, 'css', 0);
824
+ }
825
+ else {
826
+ addCompatibilityDiagnostics(text, 'js', 0);
827
+ }
828
+ const ignoreRanges = parseIgnoreDirectives(text, languageId);
829
+ const extConfig = snapshot ? loadExtensionConfig(snapshot.projectRoot) : {};
830
+ const disabledRules = new Set(extConfig.diagnostics?.disabledRules?.map((r) => r.toLowerCase()) ?? []);
831
+ if (extConfig.diagnostics?.enabled === false) {
832
+ return [];
833
+ }
834
+ return diagnostics.filter((diag) => {
835
+ const line = diag.range.start.line;
836
+ const code = typeof diag.code === 'string' ? diag.code : undefined;
837
+ if (code && disabledRules.has(code.toLowerCase())) {
838
+ return false;
839
+ }
840
+ if (code === 'prefer-self-closing-component' &&
841
+ extConfig.diagnostics?.selfClosingComponents === false) {
842
+ return false;
843
+ }
844
+ if (code === 'unclosed-component-tag' &&
845
+ extConfig.diagnostics?.unclosedComponents === false) {
846
+ return false;
847
+ }
848
+ return !isDiagnosticIgnored(line, code, ignoreRanges);
849
+ });
850
+ }
851
+ export function createCompletions(document, position, snapshot) {
852
+ if (document.languageId !== 'html')
853
+ return undefined;
854
+ const offset = document.offsetAt(position);
855
+ const maskedSource = maskHtmlRawTextContents(document.getText()).replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) => ' '.repeat(comment.length));
856
+ const sourceBeforeCursor = maskedSource.slice(0, offset);
857
+ const tagMatch = /<([A-Za-z][\w-]*)?$/.exec(sourceBeforeCursor);
858
+ if (!tagMatch) {
859
+ const openTagMatch = /<([A-Za-z][\w-]*)(?:[^>"']|"[^"]*"|'[^']*')*$/.exec(sourceBeforeCursor);
860
+ if (!openTagMatch)
861
+ return undefined;
862
+ const currentTagName = openTagMatch[1].toLowerCase();
863
+ const openTagText = openTagMatch[0];
864
+ const currentTagStart = offset - openTagText.length;
865
+ if (currentTagName === 'script') {
866
+ const hasAnyDirective = SCRIPT_DIRECTIVES.some((dir) => new RegExp(`\\b${dir.name}\\b`, 'i').test(openTagText));
867
+ if (hasAnyDirective)
868
+ return [];
869
+ const range = completionReplacementRange(document, position);
870
+ return SCRIPT_DIRECTIVES.map((dir) => ({
871
+ label: dir.name,
872
+ kind: CompletionItemKind.Property,
873
+ textEdit: {
874
+ range,
875
+ newText: dir.name,
876
+ },
877
+ sortText: `0_${dir.name}`,
878
+ detail: dir.detail,
879
+ documentation: {
880
+ kind: MarkupKind.Markdown,
881
+ value: dir.documentation,
882
+ },
883
+ }));
884
+ }
885
+ const currentComponentMetadata = snapshot.componentMetadata.get(currentTagName);
886
+ if (currentComponentMetadata) {
887
+ const range = completionReplacementRange(document, position);
888
+ return currentComponentMetadata.props
889
+ .filter(({ name }) => !new RegExp(`\\bdata-bascik-prop-${escapeRegExp(name)}\\s*=`, 'i').test(openTagText))
890
+ .map((prop) => {
891
+ const attribute = `data-bascik-prop-${prop.name}`;
892
+ const item = {
893
+ label: attribute,
894
+ kind: CompletionItemKind.Property,
895
+ textEdit: {
896
+ range,
897
+ newText: `${attribute}="$1"`,
898
+ },
899
+ insertTextFormat: 2, // Snippet
900
+ sortText: `0_${attribute}`,
901
+ detail: 'Bascik component prop',
902
+ };
903
+ if (prop.description) {
904
+ item.documentation = {
905
+ kind: MarkupKind.Markdown,
906
+ value: prop.description,
907
+ };
908
+ }
909
+ return item;
910
+ });
911
+ }
912
+ const parentComponentName = findNearestParentComponent(maskedSource.slice(0, currentTagStart), snapshot.componentMap);
913
+ if (!parentComponentName)
914
+ return undefined;
915
+ const parentMetadata = snapshot.componentMetadata.get(parentComponentName);
916
+ if (!parentMetadata)
917
+ return undefined;
918
+ if (/\bdata-bascik-slot(?:\s*=|\s|\/?>|$)/i.test(openTagText))
919
+ return [];
920
+ const range = completionReplacementRange(document, position);
921
+ return parentMetadata.slots.map((slot) => {
922
+ const item = {
923
+ label: `data-bascik-slot="${slot.name}"`,
924
+ kind: CompletionItemKind.Property,
925
+ textEdit: {
926
+ range,
927
+ newText: `data-bascik-slot="${slot.name}"`,
928
+ },
929
+ filterText: `data-bascik-slot ${slot.name}`,
930
+ sortText: `0_data-bascik-slot_${slot.name}`,
931
+ detail: 'Bascik named slot',
932
+ };
933
+ if (slot.description) {
934
+ item.documentation = {
935
+ kind: MarkupKind.Markdown,
936
+ value: slot.description,
937
+ };
938
+ }
939
+ return item;
940
+ });
941
+ }
942
+ const tagStart = offset - tagMatch[0].length;
943
+ const sourceBeforeTag = sourceBeforeCursor.slice(0, tagStart);
944
+ const previousTagStart = sourceBeforeTag.lastIndexOf('<');
945
+ const previousTagEnd = sourceBeforeTag.lastIndexOf('>');
946
+ if (previousTagStart > previousTagEnd)
947
+ return undefined;
948
+ const prefix = (tagMatch[1] ?? '').toLowerCase();
949
+ const start = document.positionAt(offset - prefix.length);
950
+ const replacementRange = { start, end: position };
951
+ return Array.from(snapshot.componentMap)
952
+ .filter(([componentName]) => componentName.startsWith(prefix))
953
+ .sort(([left], [right]) => left.localeCompare(right))
954
+ .map(([componentName, componentPath]) => {
955
+ const metadata = snapshot.componentMetadata.get(componentName);
956
+ const relativePath = path
957
+ .relative(snapshot.projectRoot, componentPath)
958
+ .replace(/\\/g, '/');
959
+ return {
960
+ label: componentName,
961
+ kind: CompletionItemKind.Class,
962
+ sortText: `0_${componentName}`,
963
+ range: {
964
+ start: document.positionAt(tagStart),
965
+ end: replacementRange.end,
966
+ },
967
+ insertText: metadata?.defaultSlot
968
+ ? `<${componentName}>$0</${componentName}>`
969
+ : `<${componentName} />$0`,
970
+ insertTextFormat: 2, // Snippet
971
+ filterText: componentName,
972
+ detail: 'Bascik component',
973
+ documentation: {
974
+ kind: MarkupKind.Markdown,
975
+ value: createComponentDocumentationMarkdown(relativePath, metadata),
976
+ },
977
+ };
978
+ });
979
+ }
980
+ export function createHover(document, position, snapshot) {
981
+ const line = document.getText({
982
+ start: { line: position.line, character: 0 },
983
+ end: { line: position.line + 1, character: 0 },
984
+ });
985
+ const wordRegex = /[A-Za-z0-9-]+/g;
986
+ let wordMatch;
987
+ let targetWord;
988
+ let wordRange;
989
+ while ((wordMatch = wordRegex.exec(line)) !== null) {
990
+ const start = wordMatch.index;
991
+ const end = start + wordMatch[0].length;
992
+ if (position.character >= start && position.character <= end) {
993
+ targetWord = wordMatch[0];
994
+ wordRange = {
995
+ start: { line: position.line, character: start },
996
+ end: { line: position.line, character: end },
997
+ };
998
+ break;
999
+ }
1000
+ }
1001
+ if (!targetWord || !wordRange)
1002
+ return undefined;
1003
+ const componentName = targetWord.toLowerCase();
1004
+ if (BUILT_IN_HTML_ELEMENTS.has(componentName))
1005
+ return undefined;
1006
+ const componentPath = snapshot.componentMap.get(componentName);
1007
+ if (!componentPath)
1008
+ return undefined;
1009
+ const metadata = snapshot.componentMetadata.get(componentName);
1010
+ if (!metadata)
1011
+ return undefined;
1012
+ const relativePath = path
1013
+ .relative(snapshot.projectRoot, componentPath)
1014
+ .replace(/\\/g, '/');
1015
+ const details = [`### \`<${componentName}>\`\n\n`];
1016
+ if (metadata.description) {
1017
+ details.push(metadata.description, '\n\n');
1018
+ }
1019
+ details.push(`**Source:** [\`${relativePath}\`](file://${componentPath})\n\n`);
1020
+ appendMetadataMembersMarkdown(details, 'Props', metadata.props);
1021
+ appendMetadataMembersMarkdown(details, 'Slots', [
1022
+ ...metadata.slots,
1023
+ ...(metadata.defaultSlot ? [metadata.defaultSlot] : []),
1024
+ ]);
1025
+ const features = [
1026
+ metadata.hasStyles ? 'styles' : '',
1027
+ metadata.hasScripts ? 'scripts' : '',
1028
+ ].filter(Boolean);
1029
+ if (features.length > 0) {
1030
+ details.push(`**Includes:** ${features.join(', ')}`);
1031
+ }
1032
+ return {
1033
+ contents: {
1034
+ kind: MarkupKind.Markdown,
1035
+ value: details.join(''),
1036
+ },
1037
+ range: wordRange,
1038
+ };
1039
+ }
1040
+ export function createDefinition(document, position, snapshot, fsPath) {
1041
+ if (document.languageId !== 'html')
1042
+ return undefined;
1043
+ // 1. Check for script import definition
1044
+ const text = document.getText();
1045
+ const offset = document.offsetAt(position);
1046
+ SCRIPT_BLOCK_RE.lastIndex = 0;
1047
+ let scriptMatch;
1048
+ while ((scriptMatch = SCRIPT_BLOCK_RE.exec(text)) !== null) {
1049
+ const openTag = scriptMatch[1];
1050
+ const scriptBody = scriptMatch[2] ?? '';
1051
+ const blockStart = scriptMatch.index ?? 0;
1052
+ const openTagEnd = blockStart + openTag.length;
1053
+ const blockEnd = blockStart + scriptMatch[0].length;
1054
+ if (offset < blockStart || offset > blockEnd)
1055
+ continue;
1056
+ const attrs = parseScriptOpenTagAttributes(openTag);
1057
+ if (!attrs.has('data-bascik-build') &&
1058
+ !attrs.has('data-bascik-server') &&
1059
+ !attrs.has('data-bascik-routes')) {
1060
+ return undefined;
1061
+ }
1062
+ const baseDir = path.dirname(fsPath);
1063
+ const importRootAbs = snapshot.importRoot;
1064
+ if (offset >= blockStart && offset <= openTagEnd) {
1065
+ const srcMatch = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(openTag);
1066
+ if (!srcMatch)
1067
+ return undefined;
1068
+ const srcValue = srcMatch[1] ?? srcMatch[2] ?? srcMatch[3] ?? '';
1069
+ if (!srcValue)
1070
+ return undefined;
1071
+ const valueStart = blockStart + (srcMatch.index ?? 0) + srcMatch[0].indexOf(srcValue);
1072
+ const valueEnd = valueStart + srcValue.length;
1073
+ if (offset < valueStart || offset > valueEnd)
1074
+ return undefined;
1075
+ const resolved = resolveScriptTarget(srcValue, baseDir, importRootAbs, 'src');
1076
+ if (!resolved || !fs.existsSync(resolved))
1077
+ return undefined;
1078
+ return [
1079
+ {
1080
+ originSelectionRange: {
1081
+ start: document.positionAt(valueStart),
1082
+ end: document.positionAt(valueEnd),
1083
+ },
1084
+ targetUri: `file://${resolved}`,
1085
+ targetRange: {
1086
+ start: { line: 0, character: 0 },
1087
+ end: { line: 0, character: 0 },
1088
+ },
1089
+ targetSelectionRange: {
1090
+ start: { line: 0, character: 0 },
1091
+ end: { line: 0, character: 0 },
1092
+ },
1093
+ },
1094
+ ];
1095
+ }
1096
+ const bodyOffset = offset - openTagEnd;
1097
+ for (const { start, end, value: specifier } of findModuleSpecifiers(scriptBody)) {
1098
+ if (bodyOffset < start || bodyOffset > end)
1099
+ continue;
1100
+ const resolved = resolveScriptTarget(specifier, baseDir, importRootAbs, 'specifier');
1101
+ if (!resolved || !fs.existsSync(resolved))
1102
+ return undefined;
1103
+ return [
1104
+ {
1105
+ originSelectionRange: {
1106
+ start: document.positionAt(openTagEnd + start),
1107
+ end: document.positionAt(openTagEnd + end),
1108
+ },
1109
+ targetUri: `file://${resolved}`,
1110
+ targetRange: {
1111
+ start: { line: 0, character: 0 },
1112
+ end: { line: 0, character: 0 },
1113
+ },
1114
+ targetSelectionRange: {
1115
+ start: { line: 0, character: 0 },
1116
+ end: { line: 0, character: 0 },
1117
+ },
1118
+ },
1119
+ ];
1120
+ }
1121
+ }
1122
+ // 2. Check for component tag jump-to-definition
1123
+ const line = document.getText({
1124
+ start: { line: position.line, character: 0 },
1125
+ end: { line: position.line + 1, character: 0 },
1126
+ });
1127
+ const wordRegex = /[A-Za-z0-9-]+/g;
1128
+ let wordMatch;
1129
+ while ((wordMatch = wordRegex.exec(line)) !== null) {
1130
+ const start = wordMatch.index;
1131
+ const end = start + wordMatch[0].length;
1132
+ if (position.character >= start && position.character <= end) {
1133
+ const word = wordMatch[0].toLowerCase();
1134
+ if (BUILT_IN_HTML_ELEMENTS.has(word))
1135
+ return undefined;
1136
+ const componentPath = snapshot.componentMap.get(word);
1137
+ if (!componentPath)
1138
+ return undefined;
1139
+ return [
1140
+ {
1141
+ originSelectionRange: {
1142
+ start: { line: position.line, character: start },
1143
+ end: { line: position.line, character: end },
1144
+ },
1145
+ targetUri: `file://${componentPath}`,
1146
+ targetRange: {
1147
+ start: { line: 0, character: 0 },
1148
+ end: { line: 0, character: 0 },
1149
+ },
1150
+ targetSelectionRange: {
1151
+ start: { line: 0, character: 0 },
1152
+ end: { line: 0, character: 0 },
1153
+ },
1154
+ },
1155
+ ];
1156
+ }
1157
+ }
1158
+ return undefined;
1159
+ }
1160
+ //# sourceMappingURL=analyzer.js.map