@willwade/aac-processors 0.0.3

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 (89) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +787 -0
  3. package/dist/cli/index.d.ts +2 -0
  4. package/dist/cli/index.js +189 -0
  5. package/dist/cli/prettyPrint.d.ts +2 -0
  6. package/dist/cli/prettyPrint.js +28 -0
  7. package/dist/core/analyze.d.ts +6 -0
  8. package/dist/core/analyze.js +49 -0
  9. package/dist/core/baseProcessor.d.ts +94 -0
  10. package/dist/core/baseProcessor.js +208 -0
  11. package/dist/core/fileProcessor.d.ts +7 -0
  12. package/dist/core/fileProcessor.js +51 -0
  13. package/dist/core/stringCasing.d.ts +37 -0
  14. package/dist/core/stringCasing.js +174 -0
  15. package/dist/core/treeStructure.d.ts +190 -0
  16. package/dist/core/treeStructure.js +223 -0
  17. package/dist/index.d.ts +23 -0
  18. package/dist/index.js +96 -0
  19. package/dist/optional/symbolTools.d.ts +28 -0
  20. package/dist/optional/symbolTools.js +126 -0
  21. package/dist/processors/applePanelsProcessor.d.ts +23 -0
  22. package/dist/processors/applePanelsProcessor.js +521 -0
  23. package/dist/processors/astericsGridProcessor.d.ts +49 -0
  24. package/dist/processors/astericsGridProcessor.js +1427 -0
  25. package/dist/processors/dotProcessor.d.ts +21 -0
  26. package/dist/processors/dotProcessor.js +191 -0
  27. package/dist/processors/excelProcessor.d.ts +145 -0
  28. package/dist/processors/excelProcessor.js +556 -0
  29. package/dist/processors/gridset/helpers.d.ts +4 -0
  30. package/dist/processors/gridset/helpers.js +48 -0
  31. package/dist/processors/gridset/resolver.d.ts +8 -0
  32. package/dist/processors/gridset/resolver.js +100 -0
  33. package/dist/processors/gridsetProcessor.d.ts +28 -0
  34. package/dist/processors/gridsetProcessor.js +1339 -0
  35. package/dist/processors/index.d.ts +14 -0
  36. package/dist/processors/index.js +42 -0
  37. package/dist/processors/obfProcessor.d.ts +21 -0
  38. package/dist/processors/obfProcessor.js +278 -0
  39. package/dist/processors/opmlProcessor.d.ts +21 -0
  40. package/dist/processors/opmlProcessor.js +235 -0
  41. package/dist/processors/snap/helpers.d.ts +4 -0
  42. package/dist/processors/snap/helpers.js +27 -0
  43. package/dist/processors/snapProcessor.d.ts +44 -0
  44. package/dist/processors/snapProcessor.js +586 -0
  45. package/dist/processors/touchchat/helpers.d.ts +4 -0
  46. package/dist/processors/touchchat/helpers.js +27 -0
  47. package/dist/processors/touchchatProcessor.d.ts +27 -0
  48. package/dist/processors/touchchatProcessor.js +768 -0
  49. package/dist/types/aac.d.ts +47 -0
  50. package/dist/types/aac.js +2 -0
  51. package/docs/.keep +1 -0
  52. package/docs/ApplePanels.md +309 -0
  53. package/docs/Grid3-XML-Format.md +1788 -0
  54. package/docs/TobiiDynavox-Snap-Details.md +394 -0
  55. package/docs/asterics-Grid-fileformat-details.md +443 -0
  56. package/docs/obf_.obz Open Board File Formats.md +432 -0
  57. package/docs/touchchat.md +520 -0
  58. package/examples/.coverage +0 -0
  59. package/examples/.keep +1 -0
  60. package/examples/README.md +31 -0
  61. package/examples/communikate.dot +2637 -0
  62. package/examples/demo.js +143 -0
  63. package/examples/example-images.gridset +0 -0
  64. package/examples/example.ce +0 -0
  65. package/examples/example.dot +14 -0
  66. package/examples/example.grd +1 -0
  67. package/examples/example.gridset +0 -0
  68. package/examples/example.obf +27 -0
  69. package/examples/example.obz +0 -0
  70. package/examples/example.opml +18 -0
  71. package/examples/example.spb +0 -0
  72. package/examples/example.sps +0 -0
  73. package/examples/example2.grd +1 -0
  74. package/examples/gemini_response.txt +845 -0
  75. package/examples/image-map.js +45 -0
  76. package/examples/package-lock.json +1326 -0
  77. package/examples/package.json +10 -0
  78. package/examples/styled-output/converted-snap-to-touchchat.ce +0 -0
  79. package/examples/styled-output/styled-example.ce +0 -0
  80. package/examples/styled-output/styled-example.gridset +0 -0
  81. package/examples/styled-output/styled-example.obf +37 -0
  82. package/examples/styled-output/styled-example.spb +0 -0
  83. package/examples/styling-example.ts +316 -0
  84. package/examples/translate.js +39 -0
  85. package/examples/translate_demo.js +254 -0
  86. package/examples/translation_cache.json +44894 -0
  87. package/examples/typescript-demo.ts +251 -0
  88. package/examples/unified-interface-demo.ts +183 -0
  89. package/package.json +106 -0
@@ -0,0 +1,768 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TouchChatProcessor = void 0;
7
+ const baseProcessor_1 = require("../core/baseProcessor");
8
+ const treeStructure_1 = require("../core/treeStructure");
9
+ const stringCasing_1 = require("../core/stringCasing");
10
+ const adm_zip_1 = __importDefault(require("adm-zip"));
11
+ const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const fs_1 = __importDefault(require("fs"));
14
+ const os_1 = __importDefault(require("os"));
15
+ function intToHex(colorInt) {
16
+ if (colorInt === null || typeof colorInt === 'undefined') {
17
+ return undefined;
18
+ }
19
+ // Assuming the color is in ARGB format, we mask out the alpha channel
20
+ return `#${(colorInt & 0x00ffffff).toString(16).padStart(6, '0')}`;
21
+ }
22
+ class TouchChatProcessor extends baseProcessor_1.BaseProcessor {
23
+ constructor(options) {
24
+ super(options);
25
+ this.tree = null;
26
+ this.sourceFile = null;
27
+ }
28
+ extractTexts(filePathOrBuffer) {
29
+ // Extracts all button labels/texts from TouchChat .ce file
30
+ if (!this.tree && filePathOrBuffer) {
31
+ this.tree = this.loadIntoTree(filePathOrBuffer);
32
+ }
33
+ if (!this.tree) {
34
+ throw new Error('No tree available - call loadIntoTree first');
35
+ }
36
+ const texts = [];
37
+ for (const pageId in this.tree.pages) {
38
+ const page = this.tree.pages[pageId];
39
+ page.buttons.forEach((btn) => {
40
+ if (btn.label)
41
+ texts.push(btn.label);
42
+ if (btn.message && btn.message !== btn.label)
43
+ texts.push(btn.message);
44
+ });
45
+ }
46
+ return texts;
47
+ }
48
+ loadIntoTree(filePathOrBuffer) {
49
+ // Unzip .ce file, extract the .c4v SQLite DB, and parse pages/buttons
50
+ let tmpDir = null;
51
+ let db = null;
52
+ try {
53
+ // Store source file path or buffer
54
+ this.sourceFile = filePathOrBuffer;
55
+ // Step 1: Unzip
56
+ tmpDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'touchchat-'));
57
+ const zip = new adm_zip_1.default(typeof filePathOrBuffer === 'string' ? filePathOrBuffer : Buffer.from(filePathOrBuffer));
58
+ zip.extractAllTo(tmpDir, true);
59
+ // Step 2: Find and open SQLite DB
60
+ const files = fs_1.default.readdirSync(tmpDir);
61
+ const vocabFile = files.find((f) => f.endsWith('.c4v'));
62
+ if (!vocabFile) {
63
+ throw new Error('No .c4v vocab DB found in TouchChat export');
64
+ }
65
+ const dbPath = path_1.default.join(tmpDir, vocabFile);
66
+ db = new better_sqlite3_1.default(dbPath, { readonly: true });
67
+ // Step 3: Create tree and load pages
68
+ const tree = new treeStructure_1.AACTree();
69
+ // Set root ID to the first page ID (will be updated if we find a better root)
70
+ let rootPageId = null;
71
+ // Load ID mappings first
72
+ const idMappings = new Map();
73
+ try {
74
+ const mappingQuery = 'SELECT numeric_id, string_id FROM page_id_mapping';
75
+ const mappings = db.prepare(mappingQuery).all();
76
+ mappings.forEach((mapping) => {
77
+ idMappings.set(mapping.numeric_id, mapping.string_id);
78
+ });
79
+ }
80
+ catch (e) {
81
+ // No mapping table, use numeric IDs as strings
82
+ }
83
+ // Load styles
84
+ const buttonStyles = new Map();
85
+ const pageStyles = new Map();
86
+ try {
87
+ const buttonStyleRows = db.prepare('SELECT * FROM button_styles').all();
88
+ buttonStyleRows.forEach((style) => {
89
+ buttonStyles.set(style.id, style);
90
+ });
91
+ const pageStyleRows = db.prepare('SELECT * FROM page_styles').all();
92
+ pageStyleRows.forEach((style) => {
93
+ pageStyles.set(style.id, style);
94
+ });
95
+ }
96
+ catch (e) {
97
+ // console.log('No styles found:', e);
98
+ }
99
+ // First, load all pages and get their names from resources
100
+ const pageQuery = `
101
+ SELECT p.*, r.name
102
+ FROM pages p
103
+ JOIN resources r ON r.id = p.resource_id
104
+ `;
105
+ const pages = db.prepare(pageQuery).all();
106
+ pages.forEach((pageRow) => {
107
+ // Use mapped string ID if available, otherwise use numeric ID as string
108
+ const pageId = idMappings.get(pageRow.id) || String(pageRow.id);
109
+ const style = pageStyles.get(pageRow.page_style_id);
110
+ const page = new treeStructure_1.AACPage({
111
+ id: pageId,
112
+ name: pageRow.name || '',
113
+ grid: [],
114
+ buttons: [],
115
+ parentId: null,
116
+ style: {
117
+ backgroundColor: intToHex(style?.bg_color),
118
+ },
119
+ });
120
+ tree.addPage(page);
121
+ // Set the first page as root if no root is set
122
+ if (!rootPageId) {
123
+ rootPageId = pageId;
124
+ }
125
+ });
126
+ // Load button boxes and their cells
127
+ const buttonBoxQuery = `
128
+ SELECT bbc.*, b.*, bb.id as box_id
129
+ FROM button_box_cells bbc
130
+ JOIN buttons b ON b.resource_id = bbc.resource_id
131
+ JOIN button_boxes bb ON bb.id = bbc.button_box_id
132
+ `;
133
+ try {
134
+ const buttonBoxCells = db.prepare(buttonBoxQuery).all();
135
+ const buttonBoxes = new Map();
136
+ buttonBoxCells.forEach((cell) => {
137
+ if (!buttonBoxes.has(cell.box_id)) {
138
+ buttonBoxes.set(cell.box_id, []);
139
+ }
140
+ const style = buttonStyles.get(cell.button_style_id);
141
+ // Create semantic action for TouchChat button
142
+ const semanticAction = {
143
+ category: treeStructure_1.AACSemanticCategory.COMMUNICATION,
144
+ intent: treeStructure_1.AACSemanticIntent.SPEAK_TEXT,
145
+ text: cell.message || cell.label || '',
146
+ platformData: {
147
+ touchChat: {
148
+ actionCode: 0, // Default speak action
149
+ actionData: cell.message || cell.label || '',
150
+ },
151
+ },
152
+ fallback: {
153
+ type: 'SPEAK',
154
+ message: cell.message || cell.label || '',
155
+ },
156
+ };
157
+ const button = new treeStructure_1.AACButton({
158
+ id: String(cell.id),
159
+ label: cell.label || '',
160
+ message: cell.message || '',
161
+ semanticAction: semanticAction,
162
+ style: {
163
+ backgroundColor: intToHex(style?.body_color),
164
+ borderColor: intToHex(style?.border_color),
165
+ borderWidth: style?.border_width,
166
+ fontColor: intToHex(style?.font_color),
167
+ fontSize: style?.font_height,
168
+ fontFamily: style?.font_name,
169
+ fontWeight: style?.font_bold ? 'bold' : 'normal',
170
+ fontStyle: style?.font_italic ? 'italic' : 'normal',
171
+ textUnderline: style?.font_underline,
172
+ transparent: style?.transparent,
173
+ labelOnTop: style?.label_on_top,
174
+ },
175
+ });
176
+ buttonBoxes.get(cell.box_id)?.push({
177
+ button,
178
+ location: cell.location,
179
+ spanX: cell.span_x,
180
+ spanY: cell.span_y,
181
+ });
182
+ });
183
+ // Map button boxes to pages
184
+ const boxInstances = db.prepare('SELECT * FROM button_box_instances').all();
185
+ // Create a map to track page grid layouts
186
+ const pageGrids = new Map();
187
+ boxInstances.forEach((instance) => {
188
+ // Use mapped string ID if available, otherwise use numeric ID as string
189
+ const pageId = idMappings.get(instance.page_id) || String(instance.page_id);
190
+ const page = tree.getPage(pageId);
191
+ const buttons = buttonBoxes.get(instance.button_box_id);
192
+ if (page && buttons) {
193
+ // Initialize page grid if not exists (assume max 10x10 grid)
194
+ if (!pageGrids.has(pageId)) {
195
+ const grid = [];
196
+ for (let r = 0; r < 10; r++) {
197
+ grid[r] = new Array(10).fill(null);
198
+ }
199
+ pageGrids.set(pageId, grid);
200
+ }
201
+ const pageGrid = pageGrids.get(pageId);
202
+ if (!pageGrid)
203
+ return;
204
+ const boxX = Number(instance.position_x) || 0;
205
+ const boxY = Number(instance.position_y) || 0;
206
+ const boxWidth = Number(instance.size_x) || 1;
207
+ // boxHeight not currently used but kept for future span calculations
208
+ // const boxHeight = Number(instance.size_y) || 1;
209
+ buttons.forEach(({ button, location, spanX, spanY }) => {
210
+ const safeLocation = Number(location) || 0;
211
+ const safeSpanX = Number(spanX) || 1;
212
+ const safeSpanY = Number(spanY) || 1;
213
+ // Add button to page
214
+ page.addButton(button);
215
+ // Calculate button position within the button box
216
+ // location is a linear index, convert to grid coordinates
217
+ const buttonX = safeLocation % boxWidth;
218
+ const buttonY = Math.floor(safeLocation / boxWidth);
219
+ // Calculate absolute position on page
220
+ const absoluteX = boxX + buttonX;
221
+ const absoluteY = boxY + buttonY;
222
+ // Place button in grid (handle span)
223
+ for (let r = absoluteY; r < absoluteY + safeSpanY && r < 10; r++) {
224
+ for (let c = absoluteX; c < absoluteX + safeSpanX && c < 10; c++) {
225
+ if (pageGrid && pageGrid[r] && pageGrid[r][c] === null) {
226
+ pageGrid[r][c] = button;
227
+ }
228
+ }
229
+ }
230
+ });
231
+ }
232
+ });
233
+ // Set grid layouts for all pages
234
+ pageGrids.forEach((grid, pageId) => {
235
+ const page = tree.getPage(pageId);
236
+ if (page) {
237
+ page.grid = grid;
238
+ }
239
+ });
240
+ }
241
+ catch (e) {
242
+ // console.log('No button box cells found:', e);
243
+ }
244
+ // Load buttons directly linked to pages via resources
245
+ const pageButtonsQuery = `
246
+ SELECT b.*, r.*
247
+ FROM buttons b
248
+ JOIN resources r ON r.id = b.resource_id
249
+ WHERE r.type = 7
250
+ `;
251
+ try {
252
+ const pageButtons = db.prepare(pageButtonsQuery).all();
253
+ pageButtons.forEach((btnRow) => {
254
+ const style = buttonStyles.get(btnRow.button_style_id);
255
+ // Create semantic action for TouchChat button
256
+ const semanticAction = {
257
+ category: treeStructure_1.AACSemanticCategory.COMMUNICATION,
258
+ intent: treeStructure_1.AACSemanticIntent.SPEAK_TEXT,
259
+ text: btnRow.message || btnRow.label || '',
260
+ platformData: {
261
+ touchChat: {
262
+ actionCode: 0, // Default speak action
263
+ actionData: btnRow.message || btnRow.label || '',
264
+ },
265
+ },
266
+ fallback: {
267
+ type: 'SPEAK',
268
+ message: btnRow.message || btnRow.label || '',
269
+ },
270
+ };
271
+ const button = new treeStructure_1.AACButton({
272
+ id: String(btnRow.id),
273
+ label: btnRow.label || '',
274
+ message: btnRow.message || '',
275
+ semanticAction: semanticAction,
276
+ style: {
277
+ backgroundColor: intToHex(style?.body_color),
278
+ borderColor: intToHex(style?.border_color),
279
+ borderWidth: style?.border_width,
280
+ fontColor: intToHex(style?.font_color),
281
+ fontSize: style?.font_height,
282
+ fontFamily: style?.font_name,
283
+ fontWeight: style?.font_bold ? 'bold' : 'normal',
284
+ fontStyle: style?.font_italic ? 'italic' : 'normal',
285
+ textUnderline: style?.font_underline,
286
+ transparent: style?.transparent,
287
+ labelOnTop: style?.label_on_top,
288
+ },
289
+ });
290
+ // Find the page that references this resource
291
+ const page = Object.values(tree.pages).find((p) => p.id === String(btnRow.id));
292
+ if (page)
293
+ page.addButton(button);
294
+ });
295
+ }
296
+ catch (e) {
297
+ // console.log('No direct page buttons found:', e);
298
+ }
299
+ // Load navigation actions
300
+ const navActionsQuery = `
301
+ SELECT b.id as button_id, ad.value as target_page_id
302
+ FROM buttons b
303
+ JOIN actions a ON a.resource_id = b.resource_id
304
+ JOIN action_data ad ON ad.action_id = a.id
305
+ WHERE a.code = 1
306
+ `;
307
+ try {
308
+ const navActions = db.prepare(navActionsQuery).all();
309
+ navActions.forEach((nav) => {
310
+ // Find button in any page
311
+ for (const pageId in tree.pages) {
312
+ const page = tree.pages[pageId];
313
+ const button = page.buttons.find((b) => b.id === String(nav.button_id));
314
+ if (button) {
315
+ // Use mapped string ID for target page if available
316
+ const targetPageId = idMappings.get(parseInt(nav.target_page_id)) || nav.target_page_id;
317
+ button.targetPageId = String(targetPageId);
318
+ // Create semantic action for navigation
319
+ button.semanticAction = {
320
+ category: treeStructure_1.AACSemanticCategory.NAVIGATION,
321
+ intent: treeStructure_1.AACSemanticIntent.NAVIGATE_TO,
322
+ targetId: String(targetPageId),
323
+ platformData: {
324
+ touchChat: {
325
+ actionCode: 1, // TouchChat navigation code
326
+ actionData: String(targetPageId),
327
+ },
328
+ },
329
+ fallback: {
330
+ type: 'NAVIGATE',
331
+ targetPageId: String(targetPageId),
332
+ },
333
+ };
334
+ break;
335
+ }
336
+ }
337
+ });
338
+ }
339
+ catch (e) {
340
+ // console.log('No navigation actions found:', e);
341
+ }
342
+ // Try to load root ID from metadata, fallback to first page
343
+ try {
344
+ const metadataQuery = "SELECT value FROM tree_metadata WHERE key = 'rootId'";
345
+ const rootIdRow = db.prepare(metadataQuery).get();
346
+ if (rootIdRow && tree.getPage(rootIdRow.value)) {
347
+ tree.rootId = rootIdRow.value;
348
+ }
349
+ else if (rootPageId) {
350
+ tree.rootId = rootPageId;
351
+ }
352
+ }
353
+ catch (e) {
354
+ // No metadata table, use first page as root
355
+ if (rootPageId) {
356
+ tree.rootId = rootPageId;
357
+ }
358
+ }
359
+ return tree;
360
+ }
361
+ finally {
362
+ // Clean up
363
+ if (db) {
364
+ db.close();
365
+ }
366
+ if (tmpDir && fs_1.default.existsSync(tmpDir)) {
367
+ try {
368
+ fs_1.default.rmSync(tmpDir, { recursive: true, force: true });
369
+ }
370
+ catch (e) {
371
+ console.warn('Failed to clean up temp directory:', e);
372
+ }
373
+ }
374
+ }
375
+ }
376
+ processTexts(filePathOrBuffer, translations, outputPath) {
377
+ // Load the tree, apply translations, and save to new file
378
+ const tree = this.loadIntoTree(filePathOrBuffer);
379
+ // Apply translations to all text content
380
+ Object.values(tree.pages).forEach((page) => {
381
+ // Translate page names
382
+ if (page.name && translations.has(page.name)) {
383
+ page.name = translations.get(page.name);
384
+ }
385
+ // Translate button labels and messages
386
+ page.buttons.forEach((button) => {
387
+ if (button.label && translations.has(button.label)) {
388
+ button.label = translations.get(button.label);
389
+ }
390
+ if (button.message && translations.has(button.message)) {
391
+ button.message = translations.get(button.message);
392
+ }
393
+ });
394
+ });
395
+ // Save the translated tree and return its content
396
+ this.saveFromTree(tree, outputPath);
397
+ return fs_1.default.readFileSync(outputPath);
398
+ }
399
+ saveFromTree(tree, outputPath) {
400
+ // Create a TouchChat database that matches the expected schema for loading
401
+ const tmpDir = fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'touchchat-export-'));
402
+ const dbPath = path_1.default.join(tmpDir, 'vocab.c4v');
403
+ try {
404
+ const db = new better_sqlite3_1.default(dbPath);
405
+ // Create schema that matches what loadIntoTree expects
406
+ db.exec(`
407
+ CREATE TABLE IF NOT EXISTS resources (
408
+ id INTEGER PRIMARY KEY,
409
+ name TEXT,
410
+ type INTEGER DEFAULT 0
411
+ );
412
+
413
+ CREATE TABLE IF NOT EXISTS pages (
414
+ id INTEGER PRIMARY KEY,
415
+ resource_id INTEGER,
416
+ name TEXT,
417
+ symbol_link_id INTEGER,
418
+ page_style_id INTEGER DEFAULT 1,
419
+ button_style_id INTEGER DEFAULT 1,
420
+ feature INTEGER,
421
+ FOREIGN KEY (resource_id) REFERENCES resources (id)
422
+ );
423
+
424
+ CREATE TABLE IF NOT EXISTS buttons (
425
+ id INTEGER PRIMARY KEY,
426
+ resource_id INTEGER,
427
+ label TEXT,
428
+ message TEXT,
429
+ symbol_link_id INTEGER,
430
+ visible INTEGER DEFAULT 1,
431
+ button_style_id INTEGER DEFAULT 1,
432
+ pronunciation TEXT,
433
+ skin_tone_override INTEGER,
434
+ FOREIGN KEY (resource_id) REFERENCES resources (id)
435
+ );
436
+
437
+ CREATE TABLE IF NOT EXISTS button_boxes (
438
+ id INTEGER PRIMARY KEY
439
+ );
440
+
441
+ CREATE TABLE IF NOT EXISTS button_box_cells (
442
+ id INTEGER PRIMARY KEY,
443
+ button_box_id INTEGER,
444
+ resource_id INTEGER,
445
+ location INTEGER,
446
+ span_x INTEGER DEFAULT 1,
447
+ span_y INTEGER DEFAULT 1,
448
+ button_style_id INTEGER DEFAULT 1,
449
+ label TEXT,
450
+ message TEXT,
451
+ box_id INTEGER,
452
+ FOREIGN KEY (button_box_id) REFERENCES button_boxes (id),
453
+ FOREIGN KEY (resource_id) REFERENCES resources (id),
454
+ FOREIGN KEY (button_style_id) REFERENCES button_styles (id)
455
+ );
456
+
457
+ CREATE TABLE IF NOT EXISTS button_box_instances (
458
+ id INTEGER PRIMARY KEY,
459
+ page_id INTEGER,
460
+ button_box_id INTEGER,
461
+ position_x INTEGER DEFAULT 0,
462
+ position_y INTEGER DEFAULT 0,
463
+ size_x INTEGER DEFAULT 1,
464
+ size_y INTEGER DEFAULT 1,
465
+ FOREIGN KEY (page_id) REFERENCES pages (id),
466
+ FOREIGN KEY (button_box_id) REFERENCES button_boxes (id)
467
+ );
468
+
469
+ CREATE TABLE IF NOT EXISTS actions (
470
+ id INTEGER PRIMARY KEY,
471
+ resource_id INTEGER,
472
+ code INTEGER,
473
+ FOREIGN KEY (resource_id) REFERENCES resources (id)
474
+ );
475
+
476
+ CREATE TABLE IF NOT EXISTS action_data (
477
+ id INTEGER PRIMARY KEY,
478
+ action_id INTEGER,
479
+ value TEXT,
480
+ FOREIGN KEY (action_id) REFERENCES actions (id)
481
+ );
482
+
483
+ CREATE TABLE IF NOT EXISTS tree_metadata (
484
+ key TEXT PRIMARY KEY,
485
+ value TEXT
486
+ );
487
+
488
+ CREATE TABLE IF NOT EXISTS page_id_mapping (
489
+ numeric_id INTEGER PRIMARY KEY,
490
+ string_id TEXT UNIQUE
491
+ );
492
+
493
+ CREATE TABLE IF NOT EXISTS button_styles (
494
+ id INTEGER PRIMARY KEY,
495
+ label_on_top INTEGER DEFAULT 0,
496
+ force_label_on_top INTEGER DEFAULT 0,
497
+ transparent INTEGER DEFAULT 0,
498
+ force_transparent INTEGER DEFAULT 0,
499
+ font_color INTEGER,
500
+ force_font_color INTEGER DEFAULT 0,
501
+ body_color INTEGER,
502
+ force_body_color INTEGER DEFAULT 0,
503
+ border_color INTEGER,
504
+ force_border_color INTEGER DEFAULT 0,
505
+ border_width REAL,
506
+ force_border_width INTEGER DEFAULT 0,
507
+ font_name TEXT,
508
+ font_bold INTEGER DEFAULT 0,
509
+ font_underline INTEGER DEFAULT 0,
510
+ font_italic INTEGER DEFAULT 0,
511
+ font_height REAL,
512
+ force_font INTEGER DEFAULT 0
513
+ );
514
+
515
+ CREATE TABLE IF NOT EXISTS page_styles (
516
+ id INTEGER PRIMARY KEY,
517
+ bg_color INTEGER,
518
+ force_bg_color INTEGER DEFAULT 0,
519
+ bg_alignment INTEGER DEFAULT 0,
520
+ force_bg_alignment INTEGER DEFAULT 0
521
+ );
522
+ `);
523
+ // Insert default styles
524
+ db.prepare('INSERT INTO button_styles (id) VALUES (1)').run();
525
+ db.prepare('INSERT INTO page_styles (id) VALUES (1)').run();
526
+ // Helper function to convert hex color to integer
527
+ const hexToInt = (hexColor) => {
528
+ if (!hexColor)
529
+ return null;
530
+ const hex = hexColor.replace('#', '');
531
+ return parseInt(hex, 16);
532
+ };
533
+ // Insert pages and buttons using the proper schema
534
+ let resourceIdCounter = 1;
535
+ let pageIdCounter = 1;
536
+ let buttonIdCounter = 1;
537
+ let buttonBoxIdCounter = 1;
538
+ let buttonBoxInstanceIdCounter = 1;
539
+ let actionIdCounter = 1;
540
+ let buttonStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
541
+ let pageStyleIdCounter = 2; // Start from 2 since 1 is reserved for default
542
+ // Create mapping from string IDs to numeric IDs
543
+ const pageIdMap = new Map();
544
+ const insertedButtonIds = new Set();
545
+ const buttonStyleMap = new Map();
546
+ const pageStyleMap = new Map();
547
+ // First pass: create pages and map IDs
548
+ Object.values(tree.pages).forEach((page) => {
549
+ // Try to use numeric ID if possible, otherwise assign sequential ID
550
+ const numericPageId = /^\d+$/.test(page.id) ? parseInt(page.id) : pageIdCounter++;
551
+ pageIdMap.set(page.id, numericPageId);
552
+ // Create page style if needed
553
+ let pageStyleId = 1; // default style
554
+ if (page.style && page.style.backgroundColor) {
555
+ const styleKey = JSON.stringify(page.style);
556
+ if (!pageStyleMap.has(styleKey)) {
557
+ pageStyleId = pageStyleIdCounter++;
558
+ pageStyleMap.set(styleKey, pageStyleId);
559
+ const insertPageStyle = db.prepare('INSERT INTO page_styles (id, bg_color, force_bg_color) VALUES (?, ?, ?)');
560
+ insertPageStyle.run(pageStyleId, hexToInt(page.style.backgroundColor), page.style.backgroundColor ? 1 : 0);
561
+ }
562
+ else {
563
+ pageStyleId = pageStyleMap.get(styleKey);
564
+ }
565
+ }
566
+ // Insert resource for page name
567
+ const pageResourceId = resourceIdCounter++;
568
+ const insertResource = db.prepare('INSERT INTO resources (id, name, type) VALUES (?, ?, ?)');
569
+ insertResource.run(pageResourceId, page.name || 'Page', 0);
570
+ // Insert page with original ID preserved and style
571
+ const insertPage = db.prepare('INSERT INTO pages (id, resource_id, name, page_style_id) VALUES (?, ?, ?, ?)');
572
+ insertPage.run(numericPageId, pageResourceId, page.name || 'Page', pageStyleId);
573
+ // Store ID mapping
574
+ const insertIdMapping = db.prepare('INSERT INTO page_id_mapping (numeric_id, string_id) VALUES (?, ?)');
575
+ insertIdMapping.run(numericPageId, page.id);
576
+ });
577
+ // Second pass: create buttons and their relationships
578
+ Object.values(tree.pages).forEach((page) => {
579
+ const numericPageId = pageIdMap.get(page.id);
580
+ if (page.buttons.length > 0) {
581
+ // Calculate grid dimensions from page.grid or use fallback
582
+ let gridWidth = 4; // Default fallback
583
+ let gridHeight = Math.ceil(page.buttons.length / gridWidth);
584
+ if (page.grid && page.grid.length > 0) {
585
+ gridHeight = page.grid.length;
586
+ gridWidth = page.grid[0] ? page.grid[0].length : gridWidth;
587
+ }
588
+ // Create a button box for this page's buttons
589
+ const buttonBoxId = buttonBoxIdCounter++;
590
+ const insertButtonBox = db.prepare('INSERT INTO button_boxes (id) VALUES (?)');
591
+ insertButtonBox.run(buttonBoxId);
592
+ // Create button box instance with calculated dimensions
593
+ const insertButtonBoxInstance = db.prepare('INSERT INTO button_box_instances (id, page_id, button_box_id, position_x, position_y, size_x, size_y) VALUES (?, ?, ?, ?, ?, ?, ?)');
594
+ insertButtonBoxInstance.run(buttonBoxInstanceIdCounter++, numericPageId, buttonBoxId, 0, // Box starts at origin
595
+ 0, gridWidth, gridHeight);
596
+ // Insert buttons
597
+ page.buttons.forEach((button, index) => {
598
+ // Find button position in grid layout
599
+ let buttonLocation = index; // Default fallback
600
+ let buttonSpanX = 1;
601
+ let buttonSpanY = 1;
602
+ if (page.grid && page.grid.length > 0) {
603
+ // Search for button in grid layout
604
+ for (let y = 0; y < page.grid.length; y++) {
605
+ for (let x = 0; x < page.grid[y].length; x++) {
606
+ const gridButton = page.grid[y][x];
607
+ if (gridButton && gridButton.id === button.id) {
608
+ // Convert grid coordinates to linear location
609
+ buttonLocation = y * gridWidth + x;
610
+ // Calculate span (find how many consecutive cells this button occupies)
611
+ // For now, assume 1x1 span (can be enhanced later for multi-cell buttons)
612
+ buttonSpanX = 1;
613
+ buttonSpanY = 1;
614
+ break;
615
+ }
616
+ }
617
+ }
618
+ }
619
+ const buttonResourceId = resourceIdCounter++;
620
+ const insertResource = db.prepare('INSERT INTO resources (id, name, type) VALUES (?, ?, ?)');
621
+ insertResource.run(buttonResourceId, button.label || 'Button', 7);
622
+ const numericButtonId = parseInt(button.id) || buttonIdCounter++;
623
+ // Create button style if needed
624
+ let buttonStyleId = 1; // default style
625
+ if (button.style) {
626
+ const styleKey = JSON.stringify(button.style);
627
+ if (!buttonStyleMap.has(styleKey)) {
628
+ buttonStyleId = buttonStyleIdCounter++;
629
+ buttonStyleMap.set(styleKey, buttonStyleId);
630
+ const insertButtonStyle = db.prepare('INSERT INTO button_styles (id, label_on_top, transparent, font_color, body_color, border_color, border_width, font_name, font_bold, font_underline, font_italic, font_height) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)');
631
+ insertButtonStyle.run(buttonStyleId, button.style.labelOnTop ? 1 : 0, button.style.transparent ? 1 : 0, hexToInt(button.style.fontColor), hexToInt(button.style.backgroundColor), hexToInt(button.style.borderColor), button.style.borderWidth, button.style.fontFamily, button.style.fontWeight === 'bold' ? 1 : 0, button.style.textUnderline ? 1 : 0, button.style.fontStyle === 'italic' ? 1 : 0, button.style.fontSize);
632
+ }
633
+ else {
634
+ buttonStyleId = buttonStyleMap.get(styleKey);
635
+ }
636
+ }
637
+ if (!insertedButtonIds.has(numericButtonId)) {
638
+ const insertButton = db.prepare('INSERT INTO buttons (id, resource_id, label, message, visible, button_style_id) VALUES (?, ?, ?, ?, ?, ?)');
639
+ insertButton.run(numericButtonId, buttonResourceId, button.label || '', button.message || button.label || '', 1, buttonStyleId);
640
+ insertedButtonIds.add(numericButtonId);
641
+ }
642
+ // Insert button box cell with styling
643
+ const insertButtonBoxCell = db.prepare('INSERT INTO button_box_cells (button_box_id, resource_id, location, span_x, span_y, button_style_id, label, message, box_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
644
+ insertButtonBoxCell.run(buttonBoxId, buttonResourceId, buttonLocation, buttonSpanX, buttonSpanY, buttonStyleId, button.label || '', button.message || button.label || '', buttonLocation);
645
+ // Handle actions - prefer semantic actions
646
+ if (button.semanticAction?.intent === treeStructure_1.AACSemanticIntent.NAVIGATE_TO) {
647
+ const targetId = button.semanticAction.targetId || button.targetPageId;
648
+ const targetPageId = targetId ? pageIdMap.get(targetId) : null;
649
+ if (targetPageId) {
650
+ // Insert navigation action
651
+ const insertAction = db.prepare('INSERT INTO actions (id, resource_id, code) VALUES (?, ?, ?)');
652
+ const actionCode = button.semanticAction.platformData?.touchChat?.actionCode || 1;
653
+ insertAction.run(actionIdCounter, buttonResourceId, actionCode);
654
+ // Insert action data
655
+ const insertActionData = db.prepare('INSERT INTO action_data (action_id, value) VALUES (?, ?)');
656
+ const actionData = button.semanticAction.platformData?.touchChat?.actionData || String(targetPageId);
657
+ insertActionData.run(actionIdCounter, actionData);
658
+ actionIdCounter++;
659
+ }
660
+ }
661
+ });
662
+ }
663
+ });
664
+ // Save tree metadata (root ID)
665
+ if (tree.rootId) {
666
+ const insertMetadata = db.prepare('INSERT INTO tree_metadata (key, value) VALUES (?, ?)');
667
+ insertMetadata.run('rootId', tree.rootId);
668
+ }
669
+ db.close();
670
+ // Create zip file with the database
671
+ const zip = new adm_zip_1.default();
672
+ zip.addLocalFile(dbPath, '', 'vocab.c4v');
673
+ zip.writeZip(outputPath);
674
+ }
675
+ finally {
676
+ // Clean up
677
+ if (fs_1.default.existsSync(tmpDir)) {
678
+ fs_1.default.rmSync(tmpDir, { recursive: true, force: true });
679
+ }
680
+ }
681
+ }
682
+ /**
683
+ * Alias method for aac-tools-platform compatibility
684
+ * Extracts strings with TouchChat-specific metadata required for database storage
685
+ * @param filePath - Path to the TouchChat .ce file
686
+ * @returns Promise with extracted strings and any errors
687
+ */
688
+ extractStringsWithMetadata(filePath) {
689
+ try {
690
+ const tree = this.loadIntoTree(filePath);
691
+ const extractedMap = new Map();
692
+ // Process all pages and buttons with TouchChat-specific logic
693
+ Object.values(tree.pages).forEach((page) => {
694
+ page.buttons.forEach((button) => {
695
+ // Process button labels
696
+ if (button.label && button.label.trim().length > 1 && !(0, stringCasing_1.isNumericOrEmpty)(button.label)) {
697
+ const key = button.label.trim().toLowerCase();
698
+ const vocabLocation = {
699
+ table: 'buttons',
700
+ id: parseInt(button.id) || 0,
701
+ column: 'LABEL',
702
+ casing: (0, stringCasing_1.detectCasing)(button.label),
703
+ };
704
+ this.addToExtractedMap(extractedMap, key, button.label.trim(), vocabLocation);
705
+ }
706
+ // Process button messages (if different from label)
707
+ if (button.message &&
708
+ button.message !== button.label &&
709
+ button.message.trim().length > 1 &&
710
+ !(0, stringCasing_1.isNumericOrEmpty)(button.message)) {
711
+ const key = button.message.trim().toLowerCase();
712
+ const vocabLocation = {
713
+ table: 'buttons',
714
+ id: parseInt(button.id) || 0,
715
+ column: 'MESSAGE',
716
+ casing: (0, stringCasing_1.detectCasing)(button.message),
717
+ };
718
+ this.addToExtractedMap(extractedMap, key, button.message.trim(), vocabLocation);
719
+ }
720
+ });
721
+ });
722
+ const extractedStrings = Array.from(extractedMap.values());
723
+ return Promise.resolve({ errors: [], extractedStrings });
724
+ }
725
+ catch (error) {
726
+ return Promise.resolve({
727
+ errors: [
728
+ {
729
+ message: error instanceof Error ? error.message : 'Unknown extraction error',
730
+ step: 'EXTRACT',
731
+ },
732
+ ],
733
+ extractedStrings: [],
734
+ });
735
+ }
736
+ }
737
+ /**
738
+ * Alias method for generating translated TouchChat downloads compatible with aac-tools-platform
739
+ * @param filePath - Path to the original TouchChat .ce file
740
+ * @param translatedStrings - Array of translated string data
741
+ * @param sourceStrings - Array of source string data with metadata
742
+ * @returns Promise with path to the generated translated file
743
+ */
744
+ generateTranslatedDownload(filePath, translatedStrings, sourceStrings) {
745
+ try {
746
+ // Build translation map from the provided data
747
+ const translations = new Map();
748
+ sourceStrings.forEach((sourceString) => {
749
+ const translated = translatedStrings.find((ts) => ts.sourcestringid.toString() === sourceString.id.toString());
750
+ if (translated) {
751
+ const translatedText = translated.overridestring.length > 0
752
+ ? translated.overridestring
753
+ : translated.translatedstring;
754
+ translations.set(sourceString.sourcestring, translatedText);
755
+ }
756
+ });
757
+ // Generate output path for TouchChat files
758
+ const outputPath = filePath.replace(/\.ce$/, '_translated.ce');
759
+ // Use existing processTexts method
760
+ this.processTexts(filePath, translations, outputPath);
761
+ return Promise.resolve(outputPath);
762
+ }
763
+ catch (error) {
764
+ return Promise.reject(new Error(`Failed to generate translated download: ${error instanceof Error ? error.message : 'Unknown error'}`));
765
+ }
766
+ }
767
+ }
768
+ exports.TouchChatProcessor = TouchChatProcessor;