@shing.wong/sure-factor 0.1.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 (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +317 -0
  3. package/catalog/assets/audio/error-bell.js +34 -0
  4. package/catalog/assets/audio/success-chime.js +38 -0
  5. package/catalog/assets/audio/voice-help.js +48 -0
  6. package/catalog/assets/data/icd10-codes.json +22 -0
  7. package/catalog/assets/data/us-zip-codes.json +22 -0
  8. package/catalog/assets/i18n/en.json +236 -0
  9. package/catalog/assets/i18n/es.json +236 -0
  10. package/catalog/assets/i18n/fr.json +236 -0
  11. package/catalog/assets/themes/dracula.css +295 -0
  12. package/catalog/assets/themes/forest.css +295 -0
  13. package/catalog/assets/themes/nord.css +295 -0
  14. package/catalog/components/auth-login.yaml +49 -0
  15. package/catalog/components/auth-register.yaml +45 -0
  16. package/catalog/components/auth-reset-password.yaml +38 -0
  17. package/catalog/components/crud-resource.yaml +59 -0
  18. package/catalog/components/data-table.yaml +54 -0
  19. package/catalog/components/dialog.yaml +80 -0
  20. package/catalog/components/form-modal.yaml +51 -0
  21. package/catalog/components/form.yaml +47 -0
  22. package/catalog/components/horizontal-icon-menu.yaml +39 -0
  23. package/catalog/components/markdown.yaml +33 -0
  24. package/catalog/components/message-actions.yaml +23 -0
  25. package/catalog/components/preview-panel.yaml +24 -0
  26. package/catalog/components/search-filter.yaml +50 -0
  27. package/catalog/components/session-list.yaml +36 -0
  28. package/catalog/types/credit-card.yaml +55 -0
  29. package/catalog/types/date-iso.yaml +52 -0
  30. package/catalog/types/date-us.yaml +52 -0
  31. package/catalog/types/ein.yaml +54 -0
  32. package/catalog/types/email.yaml +56 -0
  33. package/catalog/types/full-name.yaml +55 -0
  34. package/catalog/types/icd10.yaml +57 -0
  35. package/catalog/types/intl-phone.yaml +52 -0
  36. package/catalog/types/password.yaml +57 -0
  37. package/catalog/types/ssn.yaml +56 -0
  38. package/catalog/types/text.yaml +55 -0
  39. package/catalog/types/url.yaml +56 -0
  40. package/catalog/types/us-address.yaml +54 -0
  41. package/catalog/types/us-phone.yaml +52 -0
  42. package/catalog/types/zip5.yaml +53 -0
  43. package/catalog/types/zip9.yaml +52 -0
  44. package/dist/format.d.ts +15 -0
  45. package/dist/format.d.ts.map +1 -0
  46. package/dist/format.js +46 -0
  47. package/dist/format.js.map +1 -0
  48. package/dist/generate-store.d.ts +20 -0
  49. package/dist/generate-store.d.ts.map +1 -0
  50. package/dist/generate-store.js +128 -0
  51. package/dist/generate-store.js.map +1 -0
  52. package/dist/generate.d.ts +19 -0
  53. package/dist/generate.d.ts.map +1 -0
  54. package/dist/generate.js +145 -0
  55. package/dist/generate.js.map +1 -0
  56. package/dist/index.d.ts +11 -0
  57. package/dist/index.d.ts.map +1 -0
  58. package/dist/index.js +17 -0
  59. package/dist/index.js.map +1 -0
  60. package/dist/introspect.d.ts +23 -0
  61. package/dist/introspect.d.ts.map +1 -0
  62. package/dist/introspect.js +40 -0
  63. package/dist/introspect.js.map +1 -0
  64. package/dist/match.d.ts +10 -0
  65. package/dist/match.d.ts.map +1 -0
  66. package/dist/match.js +136 -0
  67. package/dist/match.js.map +1 -0
  68. package/dist/parse-yaml.d.ts +2 -0
  69. package/dist/parse-yaml.d.ts.map +1 -0
  70. package/dist/parse-yaml.js +152 -0
  71. package/dist/parse-yaml.js.map +1 -0
  72. package/dist/sanitize.d.ts +15 -0
  73. package/dist/sanitize.d.ts.map +1 -0
  74. package/dist/sanitize.js +101 -0
  75. package/dist/sanitize.js.map +1 -0
  76. package/dist/serialize.d.ts +15 -0
  77. package/dist/serialize.d.ts.map +1 -0
  78. package/dist/serialize.js +256 -0
  79. package/dist/serialize.js.map +1 -0
  80. package/dist/types.d.ts +83 -0
  81. package/dist/types.d.ts.map +1 -0
  82. package/dist/types.js +2 -0
  83. package/dist/types.js.map +1 -0
  84. package/package.json +80 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ShingWong
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,317 @@
1
+ # sure-factor
2
+
3
+ **Database schema → production-grade UI components.** A code generation framework that introspects SQL schemas, matches columns to a typed catalog, and generates validated, sanitized, internationalized form UIs at three tiers — vibe, prototype, and production.
4
+
5
+ ```ts
6
+ import { introspectSchemaFromDdl } from '@shing.wong/sure-factor/introspect'
7
+ import { matchColumnToTypeSync, loadAllTypesSync } from '@shing.wong/sure-factor'
8
+ import { generateForTier } from '@shing.wong/sure-factor/generate'
9
+
10
+ const schema = introspectSchemaFromDdl(`CREATE TABLE patients (
11
+ id UUID PRIMARY KEY,
12
+ email VARCHAR(255) NOT NULL,
13
+ full_name VARCHAR(100),
14
+ zip VARCHAR(5)
15
+ );`)
16
+
17
+ const output = generateForTier(schema, { tier: 'production', component: 'form' })
18
+ // → { routes, template, i18n, styles, validation, sanitization, ... }
19
+ ```
20
+
21
+ ### Why sure-factor?
22
+
23
+ | Problem | How sure-factor solves it |
24
+ |---------|--------------------------|
25
+ | **Forms are repetitive** | SQL schema → full form UI in one step. Introspect, match, generate — no hand-written forms. |
26
+ | **Validation is scattered** | Type definitions encode regex, length, and lookup validation per tier. Same validation for vibe (quick) and production (strict). |
27
+ | **Sanitization is an afterthought** | Declarative pipeline per type: `[trim, lowercase, normalize(NFKC), slice(0, 254)]`. Input and output pipelines are separate. |
28
+ | **i18n is tedious** | Type hints include English, Spanish, and French placeholders, help text, and error messages. Generated forms are multi-language from day one. |
29
+ | **Code quality varies by stage** | Three tiers: vibe (quick regex), prototype (full validation + 2-3 languages), production (lookup datasets + encryption + audit). |
30
+ | **No standard type catalog** | 15 built-in types (email, zip5, icd10, ssn, phone, url, ...) with match rules, validation, sanitization, i18n, and security policies. |
31
+
32
+ ### How it compares
33
+
34
+ | | sure-factor | QuickDBD / dbdiagram | Prisma | Low-Code platforms |
35
+ |---|---|---|---|---|
36
+ | SQL schema → UI | ✅ Full pipeline | ❌ Diagram only | ⚠️ Schema only | ❌ Proprietary DSL |
37
+ | Type catalog | ✅ 15 types, YAML-defined | ❌ | ⚠️ Native types only | ❌ |
38
+ | Tiered generation | ✅ vibe / prototype / production | ❌ | ❌ | ❌ |
39
+ | i18n built-in | ✅ en/es/fr per type | ❌ | ❌ | ❌ |
40
+ | Sanitization pipeline | ✅ Declarative input + output steps | ❌ | ❌ | ❌ |
41
+ | Lookup datasets | ✅ ICD-10, ZIP codes | ❌ | ❌ | ❌ |
42
+ | Audio feedback | ✅ Error bell, success chime, voice help | ❌ | ❌ | ❌ |
43
+ | Export formats | ✅ HTML + CSS + JS + YAML + JSON + XML | ❌ | ❌ | ❌ |
44
+ | Framework | Agnostic (generates HTML/CSS/JS) | ❌ | ❌ | ❌ |
45
+ | File size | ~1 MB (catalog + engine) | N/A | ~15 MB | N/A |
46
+
47
+ ## Architecture
48
+
49
+ ```
50
+ ┌──────────┐
51
+ DDL or SQL ─────▶│introspect│
52
+ │DDL→Schema│
53
+ └────┬─────┘
54
+ │ SchemaInfo
55
+ ▼
56
+ ┌──────────┐ ┌─────────────┐
57
+ │ match │◀───│catalog/types │
58
+ │ col→type │ │15 YAML defs │
59
+ └────┬─────┘ └─────────────┘
60
+ │ TypeMatchResult
61
+ ▼
62
+ ┌──────────┐ ┌────────────────┐
63
+ │ generate │◀───│catalog/components│
64
+ │ tiered │ │5 templates │
65
+ │ output │ └────────────────┘
66
+ └────┬─────┘
67
+ │ routes, template, i18n, styles,
68
+ │ validation, sanitization, scripts
69
+ ▼
70
+ ┌──────────┐
71
+ │ format │
72
+ │(Prettier)│
73
+ └──────────┘
74
+ ```
75
+
76
+ **Three phases:**
77
+
78
+ 1. **Introspect** — Parse DDL or query `information_schema` → `SchemaInfo` (tables, columns, types, constraints, foreign keys)
79
+ 2. **Match** — Match each column to catalog type definitions using name patterns + data type rules → `TypeMatchResult` with confidence scoring
80
+ 3. **Generate** — Produce tier-aware output: routes, templates, i18n, sanitization pipeline, validation rules, theme CSS, and sure-state stores
81
+
82
+ ## Quick Start
83
+
84
+ ```ts
85
+ import { introspectSchemaFromDdl } from '@shing.wong/sure-factor/introspect'
86
+ import { loadAllTypesSync, matchColumnToTypeSync } from '@shing.wong/sure-factor'
87
+ import { generateForTier } from '@shing.wong/sure-factor/generate'
88
+ import { generateStore } from '@shing.wong/sure-factor/generate-store'
89
+ import { sanitize } from '@shing.wong/sure-factor/sanitize'
90
+ import { convert } from '@shing.wong/sure-factor/serialize'
91
+
92
+ // 1. Introspect — parse DDL into typed schema
93
+ const schema = introspectSchemaFromDdl(`
94
+ CREATE TABLE patients (
95
+ id UUID PRIMARY KEY,
96
+ email VARCHAR(255) NOT NULL,
97
+ full_name VARCHAR(100) NOT NULL,
98
+ diagnosis VARCHAR(8),
99
+ zip VARCHAR(5)
100
+ );
101
+ `)
102
+
103
+ // 2. Match — match columns to catalog types
104
+ const allTypes = loadAllTypesSync()
105
+ const emailCol = schema.tables[0]!.columns.find(c => c.columnName === 'email')!
106
+ const result = matchColumnToTypeSync(emailCol, allTypes)
107
+ // → { type: { name: 'email', confidence: 1 }, confidence: 1 }
108
+
109
+ // 3. Generate — produce tiered UI output
110
+ const output = generateForTier(schema, { tier: 'production', component: 'form' })
111
+ // → {
112
+ // routes: "app.post('/patients', ...)",
113
+ // template: "<form class='sure-form'>...",
114
+ // i18n: { email_placeholder: 'user@example.com', ... },
115
+ // styles: ".sure-form { max-width: 480px; }...",
116
+ // validation: "z.string().regex(/^[a-zA-Z0-9.../).max(254)",
117
+ // sanitization: "[trim, lowercase, normalize(NFKC), ...]"
118
+ // }
119
+
120
+ // 4. Generate a sure-state store
121
+ const store = generateStore({
122
+ tableName: 'patients',
123
+ columns: schema.tables[0]!.columns,
124
+ tier: 'production',
125
+ })
126
+ // → { interfaceCode, apiCode, storeCode, fullCode }
127
+
128
+ // 5. Sanitize input
129
+ sanitize(' user@Example.COM ', ['trim', 'lowercase', 'normalize(NFKC)'])
130
+ // → 'user@example.com'
131
+
132
+ // 6. Serialize between formats
133
+ convert(yamlString, 'yaml', 'json') // YAML → JSON
134
+ convert(jsonString, 'json', 'md') // JSON → Markdown
135
+ ```
136
+
137
+ ## Type Catalog
138
+
139
+ 15 built-in type definitions in `catalog/types/`:
140
+
141
+ | Type | Match patterns | Validation | Sanitization | Security |
142
+ |------|---------------|------------|--------------|----------|
143
+ | `email` | `%email%`, `%mail%` | RFC 5322 regex | trim, lowercase, normalize(NFKC) | Unicode normalization |
144
+ | `zip5` | `%zip%`, `%postal%` | `^\d{5}$` | stripNonDigits, slice(5) | — |
145
+ | `zip9` | `%zip9%`, `%zip+4%` | `^\d{5}-\d{4}$` | format to 5+4 | — |
146
+ | `ssn` | `%ssn%`, `%social%` | `^\d{3}-\d{2}-\d{4}$` | stripNonDigits, format | Encrypt at rest |
147
+ | `ein` | `%ein%` | `^\d{2}-\d{7}$` | stripNonDigits, format | Encrypt at rest |
148
+ | `full-name` | `%name%`, `%full_name%` | 2-100 chars | collapseWhitespace, title case | — |
149
+ | `icd10` | `%diagnosis%`, `%icd%`, `%code%` | `^[A-Z]\d{2}\.\d{1,2}$` | uppercase | Lookup dataset |
150
+ | `intl-phone` | `%phone%` | E.164 | stripNonDigits | — |
151
+ | `us-phone` | `%phone%` with US hint | `^\d{10}$` | format (XXX) XXX-XXXX | — |
152
+ | `us-address` | `%address%`, `%street%` | Multi-line | collapseWhitespace | — |
153
+ | `date-iso` | `%date%`, `%created%` | ISO 8601 | trim | — |
154
+ | `date-us` | `%date%` with US hint | MM/DD/YYYY | format | — |
155
+ | `password` | `%password%`, `%pwd%` | 8+ chars, complexity | N/A (hash server-side) | Bcrypt |
156
+ | `credit-card` | `%card%`, `%cc%` | Luhn check | stripNonDigits | Encrypt at rest |
157
+ | `url` | `%url%`, `%website%` | URL regex | trim, lowercase | — |
158
+
159
+ ### Example type definition
160
+
161
+ ```yaml
162
+ # catalog/types/email.yaml
163
+ name: email
164
+ description: Email address conforming to RFC 5322
165
+ match:
166
+ sql: column_name LIKE '%email%' OR column_name LIKE '%mail%'
167
+ regex: ^[^@]+@[^@]+\.[^@]+$
168
+ maxLength: 254
169
+ validation:
170
+ regex: ^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$
171
+ maxLength: 254
172
+ sanitize:
173
+ input: [trim, lowercase, normalize(NFKC), slice(0, 254)]
174
+ output: [htmlEscape]
175
+ hints:
176
+ en: { placeholder: 'user@example.com', help: 'Email address' }
177
+ es: { placeholder: 'usuario@ejemplo.com', help: 'Dirección de correo' }
178
+ fr: { placeholder: 'utilisateur@example.com', help: 'Adresse e-mail' }
179
+ tiers:
180
+ vibe:
181
+ validation: { regex: ^[^@]+@[^@]+\.[^@]+$ }
182
+ sanitize: [trim, lowercase]
183
+ prototype:
184
+ validation: { regex: [full RFC], maxLength: 254 }
185
+ sanitize: [trim, lowercase, normalize(NFKC), slice(254)]
186
+ hints: { en, es }
187
+ production:
188
+ validation: { regex: [full RFC], maxLength: 254, lookup: null }
189
+ sanitize: [trim, lowercase, normalize(NFKC), slice(254)]
190
+ hints: { en, es, fr }
191
+ security:
192
+ encrypt: false
193
+ notes:
194
+ - 'Normalize Unicode NFKC to prevent homoglyph attacks'
195
+ - 'Lowercase to ensure case-insensitive matching'
196
+ ```
197
+
198
+ ## Component Catalog
199
+
200
+ 5 component templates in `catalog/components/`:
201
+
202
+ | Component | Description | Notification Modes | CSS Classes |
203
+ |-----------|-------------|-------------------|-------------|
204
+ | `form` | Single-column create/edit form | inline, toast, statusBar, sidePanel | `.sure-form__*` |
205
+ | `form-modal` | Modal dialog form | inline, toast, statusBar | `.sure-modal__*` |
206
+ | `data-table` | Read-only data table | toast | `.sure-table__*` |
207
+ | `crud-resource` | Full CRUD with table + modal | inline, toast, statusBar, sidePanel | `.sure-crud__*` |
208
+ | `search-filter` | Search with filter controls | inline, toast | `.sure-search__*` |
209
+
210
+ ## Tiers
211
+
212
+ Generation progresses through three quality tiers — same schema, different output depth:
213
+
214
+ | Feature | Vibe | Prototype | Production |
215
+ |---------|------|-----------|------------|
216
+ | Validation | Basic regex | Type + regex + DB constraints | Full + lookup datasets |
217
+ | Sanitization | Trim + escape | Full input pipeline | + DOMPurify for rich text |
218
+ | i18n | English | en + es | en + es + fr |
219
+ | Notifications | Inline | inline + toast + statusBar | All 4 modes |
220
+ | Audio | None | Error bell | Chime + speech |
221
+ | Security | Param queries | + CSRF | + Encryption + audit |
222
+ | State sync | — | — | sure-state + versioning |
223
+ | CSS themes | None | Pure CSS | Nord / Forest / Dracula |
224
+
225
+ ## Sanitization Pipeline
226
+
227
+ Declarative step functions that compose into input and output pipelines:
228
+
229
+ ```ts
230
+ import { sanitize, sanitizeInput, sanitizeOutput } from '@shing.wong/sure-factor/sanitize'
231
+
232
+ // Available steps: trim, lowercase, uppercase, stripNonDigits,
233
+ // stripDirectionOverrides, stripZeroWidth, stripControl,
234
+ // collapseWhitespace, htmlEscape, normalize(form), slice(n)
235
+
236
+ sanitize(' user@Example.COM ', ['trim', 'lowercase', 'normalize(NFKC)'])
237
+ // → 'user@example.com'
238
+
239
+ sanitize('<script>alert("xss")</script>', ['htmlEscape'])
240
+ // → '&lt;script&gt;alert(&quot;xss&quot;)&lt;&#x2F;script&gt;'
241
+ ```
242
+
243
+ ## Serialization
244
+
245
+ Convert between YAML, JSON, XML, and Markdown — useful for exporting catalog definitions:
246
+
247
+ ```ts
248
+ import { convert, toYaml, toJson, fromJson, toMarkdown, toXml, fromXml } from '@shing.wong/sure-factor/serialize'
249
+
250
+ convert(yamlString, 'yaml', 'json') // YAML → JSON
251
+ convert(jsonString, 'json', 'yaml') // JSON → YAML
252
+ convert(yamlString, 'yaml', 'xml') // YAML → XML
253
+ convert(xmlString, 'xml', 'md') // XML → Markdown
254
+ ```
255
+
256
+ ## Store Generation
257
+
258
+ Generate a sure-state compatible store from a schema:
259
+
260
+ ```ts
261
+ import { generateStore } from '@shing.wong/sure-factor/generate-store'
262
+
263
+ const store = generateStore({
264
+ tableName: 'patients',
265
+ columns: schema.tables[0]!.columns,
266
+ tier: 'production',
267
+ sync: 'server-first',
268
+ versioning: true,
269
+ })
270
+
271
+ // store.interfaceCode — TypeScript interface
272
+ // store.apiCode — API client methods
273
+ // store.storeCode — sure-state createEntityStore call
274
+ // store.fullCode — complete file
275
+ ```
276
+
277
+ ## Formatting
278
+
279
+ Generated output can be formatted via Prettier:
280
+
281
+ ```ts
282
+ import { formatCode, formatGeneratedOutput, formatGeneratedStoreOutput } from '@shing.wong/sure-factor/format'
283
+
284
+ const formatted = await formatGeneratedOutput(output)
285
+ // → same as output, but with formattedRoutes, formattedTemplate, etc.
286
+ ```
287
+
288
+ ## Assets
289
+
290
+ | Asset | Path | Description |
291
+ |-------|------|-------------|
292
+ | i18n | `catalog/assets/i18n/{en,es,fr}.json` | Locale strings for components |
293
+ | Audio | `catalog/assets/audio/` | Error bell, success chime, voice help (JS audio generators) |
294
+ | Themes | `catalog/assets/themes/{nord,forest,dracula}.css` | Production CSS themes |
295
+ | Lookup data | `catalog/assets/data/{icd10-codes,us-zip-codes}.json` | Validation datasets |
296
+
297
+ ## Related Projects
298
+
299
+ | Project | Role |
300
+ |---------|------|
301
+ | **sure-ui** | Theme CSS + notification runtime for generated output |
302
+ | **sure-state** | Client-server state sync (Zustand + WebSocket) |
303
+ | **sure-gentic** | Agent framework for LLM-powered code generation |
304
+ | **sure-web-testing** | Browser testing via MCP for generated UIs |
305
+
306
+ ## Development
307
+
308
+ ```bash
309
+ git clone git@github.com:ShingWong/sure-factor.git
310
+ cd sure-factor
311
+ npm install
312
+ npm run build
313
+ npm test # 132 tests (unit + integration)
314
+ npm run test:unit # unit only
315
+ npm run test:e2e # Playwright E2E
316
+ npm run lint # tsc --noEmit
317
+ ```
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Synthesize an error bell sound using the Web Audio API.
3
+ *
4
+ * Usage:
5
+ * import { playErrorBell } from './error-bell.js';
6
+ * playErrorBell();
7
+ *
8
+ * The sound is a square wave at A4 (440 Hz) dropping to A3 (220 Hz)
9
+ * after 100 ms, with a gain envelope from 0.3 fading to 0.01 over 300 ms.
10
+ * No external dependencies required.
11
+ */
12
+ export function playErrorBell() {
13
+ try {
14
+ const ctx = new (window.AudioContext || window.webkitAudioContext)();
15
+
16
+ const osc = ctx.createOscillator();
17
+ const gain = ctx.createGain();
18
+
19
+ osc.type = 'square';
20
+ osc.frequency.setValueAtTime(440, ctx.currentTime);
21
+ osc.frequency.setValueAtTime(220, ctx.currentTime + 0.1);
22
+
23
+ gain.gain.setValueAtTime(0.3, ctx.currentTime);
24
+ gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.3);
25
+
26
+ osc.connect(gain);
27
+ gain.connect(ctx.destination);
28
+
29
+ osc.start(ctx.currentTime);
30
+ osc.stop(ctx.currentTime + 0.3);
31
+ } catch {
32
+ // Audio not available — fail silently
33
+ }
34
+ }
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Synthesize a success chime using the Web Audio API.
3
+ *
4
+ * Usage:
5
+ * import { playSuccessChime } from './success-chime.js';
6
+ * playSuccessChime();
7
+ *
8
+ * The sound is a C5-E5-G5 major-triad arpeggio (sine wave) with a gain
9
+ * envelope from 0.2 fading to 0.01 over 400 ms. Three notes are played
10
+ * sequentially, each 100 ms apart, using a single oscillator whose
11
+ * frequency steps up through the chord tones.
12
+ * No external dependencies required.
13
+ */
14
+ export function playSuccessChime() {
15
+ try {
16
+ const ctx = new (window.AudioContext || window.webkitAudioContext)();
17
+
18
+ const osc = ctx.createOscillator();
19
+ const gain = ctx.createGain();
20
+
21
+ osc.type = 'sine';
22
+ osc.frequency.setValueAtTime(523.25, ctx.currentTime); // C5
23
+ osc.frequency.setValueAtTime(659.25, ctx.currentTime + 0.1); // E5
24
+ osc.frequency.setValueAtTime(783.99, ctx.currentTime + 0.2); // G5
25
+
26
+ gain.gain.setValueAtTime(0.2, ctx.currentTime);
27
+ gain.gain.setValueAtTime(0.2, ctx.currentTime + 0.2);
28
+ gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.4);
29
+
30
+ osc.connect(gain);
31
+ gain.connect(ctx.destination);
32
+
33
+ osc.start(ctx.currentTime);
34
+ osc.stop(ctx.currentTime + 0.4);
35
+ } catch {
36
+ // Audio not available — fail silently
37
+ }
38
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Speak validation-error guidance via the browser SpeechSynthesis API.
3
+ *
4
+ * Usage:
5
+ * import { speakError } from './voice-help.js';
6
+ * speakError('Email', 'Enter a valid email address', 'en');
7
+ * speakError('Email', 'Enter a valid email address', 'en', { rate: 0.9, pitch: 1.1 });
8
+ *
9
+ * Builds a natural-language phrase in English, Spanish, or French:
10
+ * en — "{fieldLabel}: {errorMessage}"
11
+ * es — "{fieldLabel}: {errorMessage}"
12
+ * fr — "{fieldLabel} : {errorMessage}"
13
+ *
14
+ * Selects the first voice matching the given locale. Rate (0.1–10) and
15
+ * pitch (0–2) are tunable via the optional third argument. Errors are
16
+ * caught silently — the function never throws.
17
+ *
18
+ * @param {string} fieldLabel Translated label of the field (e.g. "Email").
19
+ * @param {string} errorMessage Translated error description.
20
+ * @param {string} [locale='en'] BCP 47 tag: 'en', 'es', or 'fr'.
21
+ * @param {{ rate?: number, pitch?: number }} [opts] Speech parameters.
22
+ */
23
+ export function speakError(fieldLabel, errorMessage, locale = 'en', opts = {}) {
24
+ if (typeof window === 'undefined' || !window.speechSynthesis) return;
25
+
26
+ try {
27
+ const utter = new SpeechSynthesisUtterance();
28
+
29
+ const phrases = {
30
+ en: `${fieldLabel}: ${errorMessage}`,
31
+ es: `${fieldLabel}: ${errorMessage}`,
32
+ fr: `${fieldLabel} : ${errorMessage}`,
33
+ };
34
+
35
+ utter.text = phrases[locale] ?? phrases.en;
36
+ utter.lang = locale;
37
+ utter.rate = opts.rate ?? 1.0;
38
+ utter.pitch = opts.pitch ?? 1.0;
39
+
40
+ const voices = window.speechSynthesis.getVoices();
41
+ const match = voices.find((v) => v.lang.startsWith(locale));
42
+ if (match) utter.voice = match;
43
+
44
+ window.speechSynthesis.speak(utter);
45
+ } catch {
46
+ // Speech synthesis unavailable — fail silently
47
+ }
48
+ }
@@ -0,0 +1,22 @@
1
+ [
2
+ { "code": "J45.901", "description": "Asthma" },
3
+ { "code": "I10", "description": "Hypertension" },
4
+ { "code": "E11.9", "description": "Type 2 diabetes" },
5
+ { "code": "F32.9", "description": "Major depression" },
6
+ { "code": "M54.5", "description": "Low back pain" },
7
+ { "code": "J06.9", "description": "Upper respiratory infection" },
8
+ { "code": "N39.0", "description": "UTI" },
9
+ { "code": "E78.5", "description": "Hyperlipidemia" },
10
+ { "code": "Z23", "description": "Immunization" },
11
+ { "code": "R51", "description": "Headache" },
12
+ { "code": "K21.9", "description": "GERD" },
13
+ { "code": "J44.9", "description": "COPD" },
14
+ { "code": "G47.00", "description": "Insomnia" },
15
+ { "code": "M25.50", "description": "Joint pain" },
16
+ { "code": "R10.9", "description": "Abdominal pain" },
17
+ { "code": "L20.9", "description": "Atopic dermatitis" },
18
+ { "code": "H52.101", "description": "Myopia" },
19
+ { "code": "Z00.00", "description": "Wellness exam" },
20
+ { "code": "F41.1", "description": "Generalized anxiety" },
21
+ { "code": "M17.9", "description": "Osteoarthritis of knee" }
22
+ ]
@@ -0,0 +1,22 @@
1
+ [
2
+ { "code": "90210", "city": "Beverly Hills", "state": "CA" },
3
+ { "code": "10001", "city": "New York", "state": "NY" },
4
+ { "code": "60601", "city": "Chicago", "state": "IL" },
5
+ { "code": "77001", "city": "Houston", "state": "TX" },
6
+ { "code": "33101", "city": "Miami", "state": "FL" },
7
+ { "code": "98101", "city": "Seattle", "state": "WA" },
8
+ { "code": "02101", "city": "Boston", "state": "MA" },
9
+ { "code": "20001", "city": "Washington", "state": "DC" },
10
+ { "code": "75201", "city": "Dallas", "state": "TX" },
11
+ { "code": "30301", "city": "Atlanta", "state": "GA" },
12
+ { "code": "94101", "city": "San Francisco", "state": "CA" },
13
+ { "code": "90001", "city": "Los Angeles", "state": "CA" },
14
+ { "code": "85001", "city": "Phoenix", "state": "AZ" },
15
+ { "code": "19101", "city": "Philadelphia", "state": "PA" },
16
+ { "code": "48201", "city": "Detroit", "state": "MI" },
17
+ { "code": "55401", "city": "Minneapolis", "state": "MN" },
18
+ { "code": "63101", "city": "St. Louis", "state": "MO" },
19
+ { "code": "80201", "city": "Denver", "state": "CO" },
20
+ { "code": "97201", "city": "Portland", "state": "OR" },
21
+ { "code": "21201", "city": "Baltimore", "state": "MD" }
22
+ ]