From 05b34c9922a74df4f728b5c809e4ccdf264ca616 Mon Sep 17 00:00:00 2001 From: fregante Date: Sun, 22 Nov 2026 03:46:02 +0000 Subject: [PATCH 01/13] Meta: Read examples from JSDoc instead of `addTests` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Dragon 🐉 --- add-examples-to-dts.ts | 144 ------ collector.ts | 24 +- demo/Detections.svelte | 4 +- demo/Index.svelte | 4 +- demo/virtual.d.ts | 4 + demo/vite.config.ts | 12 +- index.test.ts | 22 +- index.ts | 1086 ++++++++++++++++++++-------------------- package.json | 3 +- xo.config.js | 2 - 10 files changed, 612 insertions(+), 693 deletions(-) delete mode 100644 add-examples-to-dts.ts create mode 100644 demo/virtual.d.ts diff --git a/add-examples-to-dts.ts b/add-examples-to-dts.ts deleted file mode 100644 index 42c98fe7..00000000 --- a/add-examples-to-dts.ts +++ /dev/null @@ -1,144 +0,0 @@ -/* eslint-disable n/prefer-global/process, unicorn/no-process-exit, @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-argument */ -import {readFileSync, writeFileSync} from 'node:fs'; -import {execSync} from 'node:child_process'; -import {Project, type JSDocableNode} from 'ts-morph'; -// Import index.ts to populate the test data via side effect -// eslint-disable-next-line import-x/no-unassigned-import -import './index.ts'; -import {getTests} from './collector.ts'; - -// Read the generated .d.ts file -const dtsPath = './distribution/index.d.ts'; -const dtsContent = readFileSync(dtsPath, 'utf8'); - -// Check if script has already been run -const marker = '/* Examples added by add-examples-to-dts.ts */'; -if (dtsContent.includes(marker)) { - console.error('❌ Error: Examples have already been added to this file'); - process.exit(1); -} - -// Create a ts-morph project and load the file -const project = new Project(); -const sourceFile = project.createSourceFile(dtsPath, dtsContent, {overwrite: true}); - -let examplesAdded = 0; - -/** - * Add example URLs to a JSDocable node (e.g., variable statement or type alias) - */ -function addExamplesToNode(node: JSDocableNode, urlExamples: string[]): void { - const jsDoc = node.getJsDocs().at(0); - - if (jsDoc) { - // Add @example tags to existing JSDoc - const existingTags = jsDoc.getTags(); - const description = jsDoc.getDescription().trim(); - - // Build new JSDoc content - const newJsDocLines: string[] = []; - if (description) { - newJsDocLines.push(description); - } - - // Add existing tags (that aren't @example tags) - for (const tag of existingTags) { - if (tag.getTagName() !== 'example') { - newJsDocLines.push(tag.getText()); - } - } - - // Add new @example tags - for (const url of urlExamples) { - newJsDocLines.push(`@example ${url}`); - } - - // Replace the JSDoc - jsDoc.remove(); - node.addJsDoc(newJsDocLines.join('\n')); - } else { - // Create new JSDoc with examples - const jsDocLines: string[] = []; - for (const url of urlExamples) { - jsDocLines.push(`@example ${url}`); - } - - node.addJsDoc(jsDocLines.join('\n')); - } -} - -// Process each exported variable declaration (these are the function declarations) -for (const statement of sourceFile.getVariableStatements()) { - // Only process exported statements - if (!statement.isExported()) { - continue; - } - - for (const declaration of statement.getDeclarations()) { - const functionName = declaration.getName(); - - // Get the tests/examples for this function - const examples = getTests(functionName); - - // Only add examples if they exist and aren't the special 'combinedTestOnly' marker - if (examples && examples.length > 0 && examples[0] !== 'combinedTestOnly') { - // Filter to only include actual URLs (not references to other functions) - const urlExamples = examples.filter((url: string) => url.startsWith('http')); - - if (urlExamples.length > 0) { - addExamplesToNode(statement, urlExamples); - examplesAdded += urlExamples.length; - } - } - } -} - -// Also process exported type aliases (like RepoExplorerInfo) -for (const typeAlias of sourceFile.getTypeAliases()) { - if (!typeAlias.isExported()) { - continue; - } - - const typeName = typeAlias.getName(); - - // Get the tests/examples for this type (unlikely but keeping consistency) - const examples = getTests(typeName); - - if (examples && examples.length > 0 && examples[0] !== 'combinedTestOnly') { - const urlExamples = examples.filter((url: string) => url.startsWith('http')); - - if (urlExamples.length > 0) { - addExamplesToNode(typeAlias, urlExamples); - examplesAdded += urlExamples.length; - } - } -} - -// Validate that we added some examples -if (examplesAdded === 0) { - console.error('❌ Error: No examples were added. This likely indicates a problem with the script.'); - process.exit(1); -} - -// Get the modified content and add marker -const modifiedContent = sourceFile.getFullText(); -const finalContent = `${marker}\n${modifiedContent}`; - -// Write the modified content back -writeFileSync(dtsPath, finalContent, 'utf8'); - -console.log(`✓ Added ${examplesAdded} example URLs to index.d.ts`); - -// Validate with TypeScript -try { - execSync('npx tsc --noEmit distribution/index.d.ts', { - cwd: process.cwd(), - stdio: 'pipe', - }); - console.log('✓ TypeScript validation passed'); -} catch (error: unknown) { - console.error('❌ TypeScript validation failed:'); - const execError = error as {stdout?: Uint8Array; stderr?: Uint8Array; message?: string}; - console.error(execError.stdout?.toString() ?? execError.stderr?.toString() ?? execError.message); - process.exit(1); -} diff --git a/collector.ts b/collector.ts index 8bf17e2b..8ccf3c0c 100644 --- a/collector.ts +++ b/collector.ts @@ -1,9 +1,27 @@ -/** @file This needs to be in a separate file so it can bee tree-shaken before being published, while still being importable by tests */ +/** @file Reads the example URLs from the JSDoc of each detection in `index.ts` */ +import {fileURLToPath} from 'node:url'; +import {Project} from 'ts-morph'; +// `@example` is a URL, `@see` is another detection, `@combinedTestOnly` skips the URL checks export const testableUrls = new Map(); -export function addTests(test: string, urls: string[]): void { - TEST: testableUrls.set(test, urls); +const source = new Project({skipAddingFilesFromTsConfig: true}) + .addSourceFileAtPath(fileURLToPath(new URL('index.ts', import.meta.url))); + +for (const statement of source.getVariableStatements()) { + const entries: string[] = []; + for (const tag of statement.getJsDocs().flatMap(doc => doc.getTags())) { + const [, name, value] = /^@(\w+)\s*(\S*)/.exec(tag.getText()) ?? []; + if (name === 'combinedTestOnly') { + entries.push('combinedTestOnly'); + } else if ((name === 'example' || name === 'see') && value) { + entries.push(value); + } + } + + if (statement.isExported() && entries.length > 0) { + testableUrls.set(statement.getDeclarations()[0]!.getName(), entries); + } } export function getTests(detectName: string): string[] { diff --git a/demo/Detections.svelte b/demo/Detections.svelte index 3145c685..efc1b86a 100644 --- a/demo/Detections.svelte +++ b/demo/Detections.svelte @@ -1,6 +1,6 @@