@hyperfixi/patterns-reference 2.0.0

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 ADDED
@@ -0,0 +1,311 @@
1
+ # @hyperfixi/patterns-reference
2
+
3
+ Queryable patterns database for hyperscript with multilingual translations and LLM few-shot learning support.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @hyperfixi/patterns-reference
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ The package ships with a **pre-populated SQLite database** containing:
14
+
15
+ - 106 code examples covering hyperscript commands and real-world UI patterns
16
+ - 1,378 translations (106 patterns × 13 languages)
17
+ - 414 LLM few-shot examples for code generation
18
+
19
+ No setup required - just install and use:
20
+
21
+ ### Use the API
22
+
23
+ ```typescript
24
+ import { createPatternsReference } from '@hyperfixi/patterns-reference';
25
+
26
+ // Create a patterns reference instance
27
+ const ref = createPatternsReference({
28
+ dbPath: './data/patterns.db',
29
+ readonly: true,
30
+ });
31
+
32
+ // Query patterns
33
+ const pattern = await ref.getPatternById('toggle-class-basic');
34
+ console.log(pattern?.rawCode); // 'on click toggle .active'
35
+
36
+ // Search patterns
37
+ const results = await ref.searchPatterns('toggle');
38
+
39
+ // Get LLM examples for few-shot learning
40
+ const examples = await ref.getLLMExamples('toggle a class on click');
41
+
42
+ // Get statistics
43
+ const stats = await ref.getStats();
44
+ console.log(`Total patterns: ${stats.totalPatterns}`);
45
+
46
+ // Clean up
47
+ ref.close();
48
+ ```
49
+
50
+ ## API Reference
51
+
52
+ ### Pattern Queries
53
+
54
+ ```typescript
55
+ // Get pattern by ID
56
+ getPatternById(id: string): Promise<Pattern | null>
57
+
58
+ // Get patterns by category (e.g., 'class-manipulation', 'visibility')
59
+ getPatternsByCategory(category: string): Promise<Pattern[]>
60
+
61
+ // Get patterns containing a specific command
62
+ getPatternsByCommand(command: string): Promise<Pattern[]>
63
+
64
+ // Full-text search across title, code, and description
65
+ searchPatterns(query: string, options?: SearchOptions): Promise<Pattern[]>
66
+
67
+ // Get all patterns (paginated)
68
+ getAllPatterns(options?: SearchOptions): Promise<Pattern[]>
69
+
70
+ // Get pattern statistics
71
+ getPatternStats(): Promise<PatternStats>
72
+ ```
73
+
74
+ ### Translations
75
+
76
+ ```typescript
77
+ // Get translation for a specific language
78
+ getTranslation(patternId: string, language: string): Promise<Translation | null>
79
+
80
+ // Get all translations for a pattern
81
+ getAllTranslations(patternId: string): Promise<Translation[]>
82
+
83
+ // Verify a translation parses correctly
84
+ verifyTranslation(translation: Translation): Promise<VerificationResult>
85
+ ```
86
+
87
+ ### LLM Support
88
+
89
+ ```typescript
90
+ // Get examples matching a prompt (for few-shot learning)
91
+ getLLMExamples(prompt: string, language?: string, limit?: number): Promise<LLMExample[]>
92
+
93
+ // Get examples by command type
94
+ getExamplesByCommand(command: string, language?: string, limit?: number): Promise<LLMExample[]>
95
+
96
+ // Get high-quality examples
97
+ getHighQualityExamples(language?: string, minQuality?: number, limit?: number): Promise<LLMExample[]>
98
+
99
+ // Build formatted context for LLM prompting
100
+ buildFewShotContext(prompt: string, language?: string, numExamples?: number): Promise<string>
101
+
102
+ // Get LLM example statistics
103
+ getLLMStats(): Promise<{ total: number; byLanguage: Record<string, number>; avgQuality: number; totalUsage: number }>
104
+ ```
105
+
106
+ ## Configuration
107
+
108
+ ### Database Path
109
+
110
+ The database path can be configured via:
111
+
112
+ 1. **Constructor option:**
113
+
114
+ ```typescript
115
+ createPatternsReference({ dbPath: '/path/to/db.sqlite' });
116
+ ```
117
+
118
+ 2. **Environment variables:**
119
+
120
+ ```bash
121
+ export LSP_DB_PATH="/path/to/db.sqlite"
122
+ # or
123
+ export HYPERSCRIPT_LSP_DB="/path/to/db.sqlite"
124
+ ```
125
+
126
+ ### Scripts (Development Only)
127
+
128
+ These scripts are for contributors regenerating the database. **End users don't need these** - the database ships pre-populated.
129
+
130
+ | Script | Description |
131
+ | --------------------------- | -------------------------------------------------------- |
132
+ | `npm run populate` | Full database setup (init + translations + LLM examples) |
133
+ | `npm run db:init` | Initialize database with seed patterns |
134
+ | `npm run db:init:force` | Reinitialize database (overwrites existing) |
135
+ | `npm run sync:translations` | Generate translations for all 13 languages |
136
+ | `npm run seed:llm` | Generate LLM few-shot examples |
137
+ | `npm run validate` | Validate all patterns parse correctly |
138
+ | `npm run validate:fix` | Validate and update verified_parses flag |
139
+ | `npm run build` | Build the package |
140
+ | `npm test` | Run tests in watch mode |
141
+ | `npm run test:run` | Run tests once |
142
+
143
+ ## Database Schema
144
+
145
+ ### code_examples
146
+
147
+ Pattern source code from the hyperscript cookbook.
148
+
149
+ | Column | Type | Description |
150
+ | ----------- | ---- | ------------------------------------- |
151
+ | id | TEXT | Unique identifier |
152
+ | title | TEXT | Human-readable title |
153
+ | raw_code | TEXT | Hyperscript code |
154
+ | description | TEXT | Pattern description |
155
+ | feature | TEXT | Category (e.g., 'class-manipulation') |
156
+ | created_at | TEXT | Creation timestamp |
157
+
158
+ ### pattern_translations
159
+
160
+ Multilingual translations of patterns.
161
+
162
+ | Column | Type | Description |
163
+ | --------------- | ------- | -------------------------------- |
164
+ | id | INTEGER | Auto-increment ID |
165
+ | code_example_id | TEXT | Foreign key to code_examples |
166
+ | language | TEXT | Language code (en, ja, es, etc.) |
167
+ | hyperscript | TEXT | Translated code |
168
+ | word_order | TEXT | SVO, SOV, VSO, or V2 |
169
+ | confidence | REAL | Translation confidence (0-1) |
170
+ | verified_parses | INTEGER | Whether translation parses (0/1) |
171
+
172
+ ### llm_examples
173
+
174
+ Prompt/completion pairs for few-shot learning.
175
+
176
+ | Column | Type | Description |
177
+ | --------------- | ------- | ---------------------------- |
178
+ | id | INTEGER | Auto-increment ID |
179
+ | code_example_id | TEXT | Foreign key to code_examples |
180
+ | language | TEXT | Language code |
181
+ | prompt | TEXT | Natural language prompt |
182
+ | completion | TEXT | Hyperscript code |
183
+ | quality_score | REAL | Quality rating (0-1) |
184
+ | usage_count | INTEGER | Retrieval count |
185
+
186
+ ## Supported Languages
187
+
188
+ The database supports 13 languages with different word orders:
189
+
190
+ | Language | Code | Word Order |
191
+ | ---------- | ---- | ---------- |
192
+ | English | en | SVO |
193
+ | Spanish | es | SVO |
194
+ | French | fr | SVO |
195
+ | Portuguese | pt | SVO |
196
+ | Indonesian | id | SVO |
197
+ | Swahili | sw | SVO |
198
+ | Chinese | zh | SVO |
199
+ | Japanese | ja | SOV |
200
+ | Korean | ko | SOV |
201
+ | Turkish | tr | SOV |
202
+ | Quechua | qu | SOV |
203
+ | Arabic | ar | VSO |
204
+ | German | de | V2 |
205
+
206
+ ## Integration with @lokascript/semantic
207
+
208
+ The patterns-reference package integrates with @lokascript/semantic to provide runtime pattern matching from the database.
209
+
210
+ ### Semantic Bridge
211
+
212
+ ```typescript
213
+ import { initializeSemanticIntegration } from '@hyperfixi/patterns-reference';
214
+
215
+ // Initialize integration (registers database as pattern source)
216
+ const result = await initializeSemanticIntegration();
217
+
218
+ if (result.success) {
219
+ console.log(`Registered with: ${result.registeredWith}`);
220
+ // 'semantic' if @lokascript/semantic is available
221
+ // 'standalone' if running without semantic package
222
+ }
223
+
224
+ // Query patterns directly
225
+ import { queryPatterns, getSupportedLanguages } from '@hyperfixi/patterns-reference';
226
+
227
+ const jaPatterns = await queryPatterns('ja');
228
+ const languages = await getSupportedLanguages();
229
+ ```
230
+
231
+ ### LLM Adapter (for @lokascript/core)
232
+
233
+ The package provides a unified LLM adapter that replaces the deprecated `llm-examples-query.ts`:
234
+
235
+ ```typescript
236
+ import { findRelevantExamples, buildFewShotContextSync } from '@hyperfixi/patterns-reference';
237
+
238
+ // Find examples matching a prompt
239
+ const examples = findRelevantExamples('toggle a class on click', 'en', 5);
240
+
241
+ // Build formatted context for LLM prompting
242
+ const context = buildFewShotContextSync('show a modal', 'en', 3);
243
+ ```
244
+
245
+ ## Development
246
+
247
+ ```bash
248
+ # Install dependencies
249
+ npm install
250
+
251
+ # Full database setup
252
+ npm run populate
253
+
254
+ # Run tests
255
+ npm test
256
+
257
+ # Validate translations
258
+ npm run validate
259
+
260
+ # Build
261
+ npm run build
262
+ ```
263
+
264
+ ## Troubleshooting
265
+
266
+ ### Native Module Installation
267
+
268
+ This package uses `better-sqlite3`, a native Node.js module. If you encounter installation errors:
269
+
270
+ **macOS:**
271
+
272
+ ```bash
273
+ xcode-select --install # Install Xcode command line tools
274
+ ```
275
+
276
+ **Linux (Debian/Ubuntu):**
277
+
278
+ ```bash
279
+ sudo apt-get install build-essential python3
280
+ ```
281
+
282
+ **Windows:**
283
+
284
+ ```bash
285
+ npm install --global windows-build-tools
286
+ ```
287
+
288
+ `better-sqlite3` ships with prebuilt binaries for most platforms, so compilation is usually not required. If you encounter issues, ensure you're using a supported Node.js version (18, 20, or 22 LTS).
289
+
290
+ ### Database Not Found
291
+
292
+ If you get "database not found" errors, the database path may not be resolving correctly. Set it explicitly:
293
+
294
+ ```typescript
295
+ import { createPatternsReference } from '@hyperfixi/patterns-reference';
296
+ import { join } from 'path';
297
+
298
+ const ref = createPatternsReference({
299
+ dbPath: join(__dirname, 'node_modules/@hyperfixi/patterns-reference/data/patterns.db'),
300
+ });
301
+ ```
302
+
303
+ Or use environment variables:
304
+
305
+ ```bash
306
+ export LSP_DB_PATH="/absolute/path/to/patterns.db"
307
+ ```
308
+
309
+ ## License
310
+
311
+ MIT
@@ -0,0 +1,106 @@
1
+ {
2
+ "$schema": "./hyperfixi-extensions.schema.json",
3
+ "version": "1.0.0",
4
+ "lastUpdated": "2026-01-19",
5
+ "description": "Tracks HyperFixi-specific syntax extensions that may not be available in official _hyperscript",
6
+ "extensions": [
7
+ {
8
+ "id": "possessive-dot-notation",
9
+ "name": "Possessive Dot Notation",
10
+ "description": "JavaScript-style dot notation with possessive pronouns (my.value, its.value, your.value)",
11
+ "status": "stable",
12
+ "addedVersion": "1.0.0",
13
+ "officialHyperscript": false,
14
+ "syntax": {
15
+ "hyperfixi": ["my.property", "its.property", "your.property", "my?.property"],
16
+ "standard": ["my property", "its property", "your property"],
17
+ "equivalent": ["me.property", "it.property", "you.property", "me?.property"]
18
+ },
19
+ "examples": [
20
+ {
21
+ "hyperfixi": "set my.textContent to \"Done!\"",
22
+ "standard": "set my textContent to \"Done!\"",
23
+ "description": "Set element text content"
24
+ },
25
+ {
26
+ "hyperfixi": "put my.value.toUpperCase() into #preview",
27
+ "standard": null,
28
+ "description": "Method chaining on property access"
29
+ },
30
+ {
31
+ "hyperfixi": "log my?.dataset?.customValue",
32
+ "standard": null,
33
+ "description": "Optional chaining for safe access"
34
+ }
35
+ ],
36
+ "testFile": "packages/core/src/parser/possessive-dot-notation.test.ts",
37
+ "documentationFile": "packages/core/docs/EXTENSIONS.md"
38
+ },
39
+ {
40
+ "id": "multilingual-keywords",
41
+ "name": "Multilingual Keyword Support",
42
+ "description": "Write hyperscript in 13 languages with automatic grammar transformation",
43
+ "status": "stable",
44
+ "addedVersion": "1.0.0",
45
+ "officialHyperscript": false,
46
+ "supportedLanguages": [
47
+ "en",
48
+ "es",
49
+ "fr",
50
+ "pt",
51
+ "de",
52
+ "ja",
53
+ "ko",
54
+ "zh",
55
+ "ar",
56
+ "tr",
57
+ "id",
58
+ "sw",
59
+ "qu"
60
+ ],
61
+ "examples": [
62
+ {
63
+ "hyperfixi": "クリック で .active を 切り替え",
64
+ "standard": "on click toggle .active",
65
+ "description": "Japanese (SOV word order)"
66
+ },
67
+ {
68
+ "hyperfixi": "en clic alternar .active",
69
+ "standard": "on click toggle .active",
70
+ "description": "Spanish"
71
+ }
72
+ ],
73
+ "documentationFile": "packages/semantic/README.md"
74
+ },
75
+ {
76
+ "id": "enhanced-type-conversion",
77
+ "name": "Enhanced Type Conversion",
78
+ "description": "Extended 'as' keyword support for additional types",
79
+ "status": "stable",
80
+ "addedVersion": "1.0.0",
81
+ "officialHyperscript": "partial",
82
+ "additionalTypes": ["FormData", "JSON", "Object", "Date"],
83
+ "examples": [
84
+ {
85
+ "hyperfixi": "form as FormData",
86
+ "standard": null,
87
+ "description": "Convert form element to FormData"
88
+ },
89
+ {
90
+ "hyperfixi": "obj as JSON",
91
+ "standard": null,
92
+ "description": "Serialize object to JSON string"
93
+ }
94
+ ]
95
+ }
96
+ ],
97
+ "compatibilityNotes": {
98
+ "overallCompatibility": "~85%",
99
+ "testedAgainst": "hyperscript.org v0.9.x",
100
+ "knownDifferences": [
101
+ "HyperFixi extensions are additive - standard _hyperscript syntax always works",
102
+ "Some edge cases in event handling may differ",
103
+ "Behavior definitions have minor syntax variations"
104
+ ]
105
+ }
106
+ }
@@ -0,0 +1,59 @@
1
+ export { r as addLLMExample, q as buildFewShotContext, c as getAllPatterns, f as getAllTranslations, n as getExamplesByCommand, j as getHighConfidenceTranslations, o as getHighQualityExamples, m as getLLMExamples, t as getLLMStats, p as getMostUsedExamples, g as getPatternById, d as getPatternStats, a as getPatternsByCategory, b as getPatternsByCommand, e as getTranslation, k as getTranslationStats, h as getTranslationsByLanguage, i as getVerifiedTranslations, l as getWordOrder, s as searchPatterns, u as updateQualityScore, v as verifyTranslation } from '../llm-UOOBXwj3.mjs';
2
+ import { C as ConnectionOptions, r as PatternRole, e as Pattern, R as RoleType } from '../index-CBoczxz7.mjs';
3
+ import { SemanticRole } from '@lokascript/semantic';
4
+
5
+ /**
6
+ * Pattern Roles API
7
+ *
8
+ * Provides functions to query semantic roles extracted from patterns.
9
+ */
10
+
11
+ /**
12
+ * Get all semantic roles for a pattern.
13
+ */
14
+ declare function getPatternRoles(patternId: string, options?: ConnectionOptions): Promise<PatternRole[]>;
15
+ /**
16
+ * Get all patterns that contain a specific semantic role.
17
+ */
18
+ declare function getPatternsByRole(role: SemanticRole, options?: ConnectionOptions): Promise<Pattern[]>;
19
+ /**
20
+ * Get patterns that contain all specified roles.
21
+ */
22
+ declare function getPatternsByRoles(roles: SemanticRole[], matchMode?: 'all' | 'any', options?: ConnectionOptions): Promise<Pattern[]>;
23
+ /**
24
+ * Get patterns by role value (e.g., all patterns that target ".active").
25
+ */
26
+ declare function getPatternsByRoleValue(role: SemanticRole, value: string, options?: ConnectionOptions): Promise<Pattern[]>;
27
+ /**
28
+ * Get statistics about role usage across all patterns.
29
+ */
30
+ declare function getRoleStats(options?: ConnectionOptions): Promise<{
31
+ totalRoles: number;
32
+ byRole: Record<SemanticRole, number>;
33
+ byRoleType: Record<RoleType, number>;
34
+ topRoleValues: Array<{
35
+ role: SemanticRole;
36
+ value: string;
37
+ count: number;
38
+ }>;
39
+ patternsWithRoles: number;
40
+ patternsWithoutRoles: number;
41
+ }>;
42
+ /**
43
+ * Get role distribution for a specific command.
44
+ */
45
+ declare function getRolesByCommand(command: string, options?: ConnectionOptions): Promise<Record<SemanticRole, number>>;
46
+ /**
47
+ * Insert a pattern role into the database.
48
+ */
49
+ declare function insertPatternRole(role: Omit<PatternRole, 'id'>, options?: ConnectionOptions): Promise<number>;
50
+ /**
51
+ * Delete all roles for a pattern.
52
+ */
53
+ declare function deletePatternRoles(patternId: string, options?: ConnectionOptions): Promise<number>;
54
+ /**
55
+ * Delete all roles from the database.
56
+ */
57
+ declare function clearAllRoles(options?: ConnectionOptions): Promise<number>;
58
+
59
+ export { clearAllRoles, deletePatternRoles, getPatternRoles, getPatternsByRole, getPatternsByRoleValue, getPatternsByRoles, getRoleStats, getRolesByCommand, insertPatternRole };
@@ -0,0 +1,59 @@
1
+ export { r as addLLMExample, q as buildFewShotContext, c as getAllPatterns, f as getAllTranslations, n as getExamplesByCommand, j as getHighConfidenceTranslations, o as getHighQualityExamples, m as getLLMExamples, t as getLLMStats, p as getMostUsedExamples, g as getPatternById, d as getPatternStats, a as getPatternsByCategory, b as getPatternsByCommand, e as getTranslation, k as getTranslationStats, h as getTranslationsByLanguage, i as getVerifiedTranslations, l as getWordOrder, s as searchPatterns, u as updateQualityScore, v as verifyTranslation } from '../llm-DMR6tmkM.js';
2
+ import { C as ConnectionOptions, r as PatternRole, e as Pattern, R as RoleType } from '../index-CBoczxz7.js';
3
+ import { SemanticRole } from '@lokascript/semantic';
4
+
5
+ /**
6
+ * Pattern Roles API
7
+ *
8
+ * Provides functions to query semantic roles extracted from patterns.
9
+ */
10
+
11
+ /**
12
+ * Get all semantic roles for a pattern.
13
+ */
14
+ declare function getPatternRoles(patternId: string, options?: ConnectionOptions): Promise<PatternRole[]>;
15
+ /**
16
+ * Get all patterns that contain a specific semantic role.
17
+ */
18
+ declare function getPatternsByRole(role: SemanticRole, options?: ConnectionOptions): Promise<Pattern[]>;
19
+ /**
20
+ * Get patterns that contain all specified roles.
21
+ */
22
+ declare function getPatternsByRoles(roles: SemanticRole[], matchMode?: 'all' | 'any', options?: ConnectionOptions): Promise<Pattern[]>;
23
+ /**
24
+ * Get patterns by role value (e.g., all patterns that target ".active").
25
+ */
26
+ declare function getPatternsByRoleValue(role: SemanticRole, value: string, options?: ConnectionOptions): Promise<Pattern[]>;
27
+ /**
28
+ * Get statistics about role usage across all patterns.
29
+ */
30
+ declare function getRoleStats(options?: ConnectionOptions): Promise<{
31
+ totalRoles: number;
32
+ byRole: Record<SemanticRole, number>;
33
+ byRoleType: Record<RoleType, number>;
34
+ topRoleValues: Array<{
35
+ role: SemanticRole;
36
+ value: string;
37
+ count: number;
38
+ }>;
39
+ patternsWithRoles: number;
40
+ patternsWithoutRoles: number;
41
+ }>;
42
+ /**
43
+ * Get role distribution for a specific command.
44
+ */
45
+ declare function getRolesByCommand(command: string, options?: ConnectionOptions): Promise<Record<SemanticRole, number>>;
46
+ /**
47
+ * Insert a pattern role into the database.
48
+ */
49
+ declare function insertPatternRole(role: Omit<PatternRole, 'id'>, options?: ConnectionOptions): Promise<number>;
50
+ /**
51
+ * Delete all roles for a pattern.
52
+ */
53
+ declare function deletePatternRoles(patternId: string, options?: ConnectionOptions): Promise<number>;
54
+ /**
55
+ * Delete all roles from the database.
56
+ */
57
+ declare function clearAllRoles(options?: ConnectionOptions): Promise<number>;
58
+
59
+ export { clearAllRoles, deletePatternRoles, getPatternRoles, getPatternsByRole, getPatternsByRoleValue, getPatternsByRoles, getRoleStats, getRolesByCommand, insertPatternRole };