-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorm.mjs
More file actions
2097 lines (1844 loc) · 71.7 KB
/
storm.mjs
File metadata and controls
2097 lines (1844 loc) · 71.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// Storm CLI - AI assistant configuration tool
// https://orm.st
//
// Zero dependencies. Requires Node.js 18+.
import { writeFileSync, appendFileSync, mkdirSync, existsSync, readFileSync, readdirSync, unlinkSync, rmdirSync, statSync } from 'fs';
import { basename, join, dirname } from 'path';
import { homedir } from 'os';
import { execSync } from 'child_process';
const VERSION = '1.11.1';
// ─── ANSI ────────────────────────────────────────────────────────────────────
const RESET = '\x1b[0m';
const BOLD = '\x1b[1m';
const DIM = '\x1b[2m';
const HIDE_CURSOR = '\x1b[?25l';
const SHOW_CURSOR = '\x1b[?25h';
const CLEAR = '\x1b[2J';
const HOME = '\x1b[H';
const CLEAR_DOWN = '\x1b[J';
const DB = '\x1b[38;5;244m';
const DB_DIM = '\x1b[38;5;242m';
const DB_GLOW = '\x1b[38;5;247m';
const DB_DIM_GLOW = '\x1b[38;5;243m';
const BOLT_BASE = '\x1b[38;5;226m';
const BOLT_WARM = '\x1b[38;5;227m';
const BOLT_HOT = '\x1b[38;5;229m';
const BOLT_CORE = '\x1b[38;5;230m';
const BOLT_WHITE = '\x1b[38;5;231m';
const WHITE = '\x1b[97m';
const GRAY = '\x1b[38;5;245m';
const YELLOW_228 = '\x1b[38;5;228m';
function bold(text) { return `${BOLD}${text}${RESET}`; }
function dimText(text) { return `${DIM}${text}${RESET}`; }
function boltYellow(text) { return `${YELLOW_228}${text}${RESET}`; }
// Ensure terminal cursor is always restored on exit.
process.on('exit', () => process.stdout.write(SHOW_CURSOR));
// ─── Welcome screen ─────────────────────────────────────────────────────────
const BODY_SOURCE = `
@@@@@@@@@@@@@@@@@@@@
@@@@ @@@@
@@@ # @@@
@@@@@ ### @@@@
@@@@@@@@@@@@@@ ### @@@@@@@@@
@@@@@@@@@@@@ ### @@@@@@@@@
@ @@@@@@@@ ### @@@@@@@ @
@@@@ #### @@@@
@@@@@@@@@ #### @@@@@@@@@
@@@@@@@ ########## @@@@@@@
@ @@ ######### @@@ @
@@@@@ #### @@@@@
@@@@@@@@@@ #### @@@@@@@@@@@@
@@@@@@@@@ ### @@@@@@@@@@@@@
@@@@@ ### @@@@@@@@@@@
###
##
`.trimEnd();
const bodyLines = BODY_SOURCE.replace(/^\n/, '').split('\n');
const artWidth = Math.max(...bodyLines.map(s => s.length));
const artHeight = bodyLines.length;
const paddedLines = Array.from({ length: artHeight }, (_, i) =>
(bodyLines[i] || '').padEnd(artWidth, ' '),
);
function hasBody(x, y) {
if (y < 0 || y >= artHeight || x < 0 || x >= artWidth) return false;
const ch = paddedLines[y][x];
return ch === '@' || ch === '#';
}
function hasBolt(x, y) {
if (y < 0 || y >= artHeight || x < 0 || x >= artWidth) return false;
return paddedLines[y][x] === '#';
}
const boltCells = [];
for (let y = 0; y < artHeight; y++)
for (let x = 0; x < artWidth; x++)
if (hasBolt(x, y)) boltCells.push({ x, y });
const minBoltY = Math.min(...boltCells.map(c => c.y));
const maxBoltY = Math.max(...boltCells.map(c => c.y));
const boltSpan = Math.max(1, maxBoltY - minBoltY);
const boltProgress = new Map();
for (const { x, y } of boltCells)
boltProgress.set(`${x},${y}`, (y - minBoltY) / boltSpan);
const visibleRows = [];
for (let y = 0; y < artHeight; y++)
if ([...paddedLines[y]].some(ch => ch === '@' || ch === '#')) visibleRows.push(y);
const firstVisibleRow = visibleRows[0];
const secondVisibleRow = visibleRows[1];
const penultimateVisibleRow = visibleRows[visibleRows.length - 2];
const lastVisibleRow = visibleRows[visibleRows.length - 1];
function isDimDbRow(y) {
return y === firstVisibleRow || y === secondVisibleRow ||
y === penultimateVisibleRow || y === lastVisibleRow;
}
function dbColor(y, glowing) {
const dimRow = isDimDbRow(y);
if (glowing) return BOLD + (dimRow ? DB_DIM_GLOW : DB_GLOW);
return BOLD + (dimRow ? DB_DIM : DB);
}
// --- Strike (lightning pulse) logic ---
let strikeActive = false;
let strikeStart = 0;
let strikeDuration = 0;
let nextStrike = 0;
let strikeTail = 0.18;
function scheduleStrike(now) { nextStrike = now + 400 + Math.random() * 3600; }
function startStrike(now) {
strikeActive = true;
strikeStart = now;
strikeDuration = 200 + Math.random() * 280;
strikeTail = 0.14 + Math.random() * 0.1;
}
function clamp01(v) { return Math.max(0, Math.min(1, v)); }
function pulseIntensity(x, y, now) {
if (!strikeActive) return 0;
const p = boltProgress.get(`${x},${y}`) ?? 0;
const t = clamp01((now - strikeStart) / strikeDuration);
const head = clamp01(Math.pow(t, 2.25));
const tail = Math.max(0, head - strikeTail);
const jitter = Math.sin(x * 0.9 + y * 1.7 + now * 0.018) * 0.006
+ Math.sin(x * 0.35 + now * 0.011) * 0.004;
const sparkle = (x * 17 + y * 31 + Math.floor(now / 30)) % 37 === 0;
const hd = Math.max(0, Math.abs(p - head) - jitter);
const td = Math.max(0, Math.abs(p - tail) - jitter * 0.5);
if (hd < 0.012) return 5;
if (hd < 0.024) return 4;
if (hd < 0.042) return 3;
if (hd < 0.07) return 2;
if (hd < 0.1) return 1;
if (td < 0.016) return 4;
if (td < 0.034) return 3;
if (td < 0.058) return 2;
if (td < 0.085) return 1;
if (sparkle && p <= head && p >= Math.max(0, head - 0.1)) return 3;
return 0;
}
function expandedPulseIntensity(x, y, now) {
let best = pulseIntensity(x, y, now);
for (let yy = y - 1; yy <= y + 1; yy++)
for (let xx = x - 1; xx <= x + 1; xx++) {
if (xx === x && yy === y) continue;
if (!hasBolt(xx, yy)) continue;
const n = pulseIntensity(xx, yy, now);
if (n >= 3) best = Math.max(best, n - 1);
}
return best;
}
function boltColorCode(x, y, now) {
const intensity = expandedPulseIntensity(x, y, now);
if (intensity === 0) return DIM + BOLT_BASE;
if (intensity === 1) return BOLD + BOLT_BASE;
if (intensity === 2) return BOLD + BOLT_WARM;
if (intensity === 3) return BOLD + BOLT_HOT;
if (intensity === 4) return BOLD + BOLT_CORE;
return BOLD + BOLT_WHITE;
}
function ringGlow(x, y, now) {
for (let yy = y - 1; yy <= y + 1; yy++)
for (let xx = x - 2; xx <= x + 2; xx++) {
if (!hasBolt(xx, yy)) continue;
if (expandedPulseIntensity(xx, yy, now) >= 3) return true;
}
return false;
}
// --- Matrix rain (demo mode) ---
let demoMode = false;
const matrixColumns = [];
const MATRIX_MARGIN = 12;
function newDrop() {
return {
y: -1 - Math.random() * artHeight * 0.6,
speed: 0.06 + Math.random() * 0.14,
trailLength: 3 + Math.floor(Math.random() * 7),
};
}
function initMatrixRain() {
matrixColumns.length = 0;
const totalWidth = artWidth + 2 * MATRIX_MARGIN;
for (let x = 0; x < totalWidth; x++) {
const drops = [];
const count = 1 + Math.floor(Math.random() * 3);
for (let i = 0; i < count; i++) {
const drop = newDrop();
drop.y = Math.random() * artHeight * 2 - artHeight;
drops.push(drop);
}
matrixColumns.push(drops);
}
}
const MATRIX_GLYPHS = 'ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン';
function matrixGlyph(x, y, now) {
const idx = (x * 17 + y * 31 + Math.floor(now / 80)) % MATRIX_GLYPHS.length;
return MATRIX_GLYPHS[idx];
}
function updateMatrixRain() {
for (const drops of matrixColumns) {
for (const drop of drops) {
drop.y += drop.speed;
if (drop.y - drop.trailLength > artHeight + 3) {
drop.y = -1 - Math.random() * artHeight * 0.6;
drop.speed = 0.06 + Math.random() * 0.14;
drop.trailLength = 3 + Math.floor(Math.random() * 7);
}
}
}
}
function matrixIntensityAt(x, y) {
const drops = matrixColumns[x];
if (!drops) return 0;
let best = 0;
for (const drop of drops) {
const dist = drop.y - y;
if (dist < -0.5 || dist > drop.trailLength) continue;
const t = Math.max(0, dist) / drop.trailLength;
let intensity;
if (dist < 0.5) intensity = 5;
else if (t < 0.15) intensity = 4;
else if (t < 0.35) intensity = 3;
else if (t < 0.6) intensity = 2;
else intensity = 1;
if (intensity > best) best = intensity;
}
return best;
}
function matrixColor(intensity) {
if (intensity === 1) return DIM + BOLT_BASE;
if (intensity === 2) return BOLD + BOLT_BASE;
if (intensity === 3) return BOLD + BOLT_WARM;
if (intensity === 4) return BOLD + BOLT_HOT;
return BOLD + BOLT_WHITE;
}
function matrixDbColor(intensity) {
if (intensity === 1) return '\x1b[38;5;244m';
if (intensity === 2) return '\x1b[38;5;245m';
if (intensity === 3) return '\x1b[38;5;247m';
if (intensity === 4) return '\x1b[38;5;248m';
return '\x1b[38;5;249m';
}
// --- Text overlay ---
function stripAnsi(s) { return s.replace(/\x1b\[[0-9;]*m/g, ''); }
function centerLine(line, cols) {
const pad = Math.max(0, Math.floor((cols - stripAnsi(line).length) / 2));
return ' '.repeat(pad) + line;
}
const INIT_TEXT_LINES = [
'',
`${GRAY}Bootstrap your project for Storm ORM${RESET}`,
'',
`${BOLD}${BOLT_HOT}\u2022${WHITE} Install Storm rules and skills${RESET}`,
`${BOLD}${BOLT_HOT}\u2022${WHITE} Storm MCP for database awareness and validation (optional)${RESET}`,
'',
`${GRAY}Press Enter to select tools${RESET}`,
];
const DEMO_TEXT_LINES = [
'',
`${GRAY}Storm Fu - Training Program${RESET}`,
'',
`${BOLD}${BOLT_HOT}\u2022${WHITE} Live demo of building an app with the Storm AI workflow${RESET}`,
`${BOLD}${BOLT_HOT}\u2022${WHITE} Storm MCP enables database awareness and validation${RESET}`,
'',
`${GRAY}Press Enter to follow the white rabbit${RESET}`,
];
let activeTextLines = INIT_TEXT_LINES;
// --- Render ---
function renderFrame(now) {
const cols = process.stdout.columns || 120;
const rows = process.stdout.rows || 40;
const rendered = [];
if (demoMode) updateMatrixRain();
const startX = demoMode ? -MATRIX_MARGIN : 0;
const endX = demoMode ? artWidth + MATRIX_MARGIN : artWidth;
for (let y = 0; y < artHeight; y++) {
let out = '';
for (let x = startX; x < endX; x++) {
const inArt = x >= 0 && x < artWidth;
if (!inArt || !hasBody(x, y)) {
if (demoMode) {
const mx = x + MATRIX_MARGIN;
const mi = matrixIntensityAt(mx, y);
if (mi >= 4) out += '\x1b[38;5;237m' + matrixGlyph(mx, y, now) + RESET;
else if (mi >= 2) out += '\x1b[38;5;235m' + matrixGlyph(mx, y, now) + RESET;
else out += '\x1b[38;5;233m' + matrixGlyph(mx, y, now) + RESET;
} else out += ' ';
continue;
}
if (demoMode) {
const mx = x + MATRIX_MARGIN;
const mi = matrixIntensityAt(mx, y);
if (hasBolt(x, y)) {
if (mi >= 3) out += matrixColor(mi) + matrixGlyph(mx, y, now) + RESET;
else out += dbColor(y, false) + '#' + RESET;
} else {
out += dbColor(y, false) + '@' + RESET;
}
} else {
if (hasBolt(x, y)) out += boltColorCode(x, y, now) + '#' + RESET;
else out += dbColor(y, ringGlow(x, y, now)) + '@' + RESET;
}
}
if (out.trim().length > 0) rendered.push(centerLine(out, cols));
}
for (const tl of activeTextLines) rendered.push(centerLine(tl, cols));
const topPad = Math.max(0, Math.floor((rows - rendered.length) / 3));
const blankLine = ' '.repeat(cols);
let frame = '';
for (let r = 0; r < rows; r++) {
const ci = r - topPad;
frame += (ci >= 0 && ci < rendered.length) ? rendered[ci] : blankLine;
if (r < rows - 1) frame += '\n';
}
return frame;
}
async function printWelcome(customTextLines) {
activeTextLines = customTextLines || INIT_TEXT_LINES;
demoMode = customTextLines === DEMO_TEXT_LINES;
if (demoMode) {
initMatrixRain();
} else {
nextStrike = Date.now() + Math.random() * 100;
}
process.stdout.write(HIDE_CURSOR + CLEAR);
const onResize = () => process.stdout.write(CLEAR);
process.stdout.on('resize', onResize);
const timer = setInterval(() => {
const now = Date.now();
if (!demoMode) {
if (!strikeActive && now > nextStrike) startStrike(now);
if (strikeActive && now > strikeStart + strikeDuration) {
strikeActive = false;
scheduleStrike(now);
}
}
process.stdout.write(HOME);
process.stdout.write(renderFrame(now));
}, 20);
await new Promise(resolve => {
const { stdin } = process;
const wasRaw = stdin.isRaw;
if (stdin.isTTY) stdin.setRawMode(true);
stdin.resume();
stdin.once('data', data => {
if (stdin.isTTY) stdin.setRawMode(wasRaw ?? false);
stdin.pause();
if (data[0] === 3) {
clearInterval(timer);
process.stdout.removeListener('resize', onResize);
process.stdout.write(RESET + SHOW_CURSOR + CLEAR + HOME);
process.exit(0);
}
resolve();
});
});
clearInterval(timer);
process.stdout.removeListener('resize', onResize);
process.stdout.write(RESET + SHOW_CURSOR + CLEAR + HOME);
}
// ─── Prompts ─────────────────────────────────────────────────────────────────
async function checkbox({ message, choices }) {
const { stdin, stdout } = process;
if (!stdin.isTTY) {
return choices.filter(c => c.checked).map(c => c.value);
}
return new Promise((resolve, reject) => {
const selected = new Set();
choices.forEach((c, i) => { if (c.checked) selected.add(i); });
let cursor = 0;
let linesWritten = 0;
function render(final) {
let out = '';
if (linesWritten > 0) out += `\x1b[${linesWritten}A`;
if (final) {
out += CLEAR_DOWN;
const names = choices.filter((_, i) => selected.has(i)).map(c => c.name).join(', ');
out += `${boltYellow('\u2714')} ${bold(message)} ${boltYellow(names)}\n`;
linesWritten = 1;
stdout.write(out);
return;
}
out += `\x1b[2K${boltYellow('?')} ${bold(message)}\n`;
for (let i = 0; i < choices.length; i++) {
const atCursor = i === cursor;
const isChecked = selected.has(i);
const prefix = atCursor ? boltYellow('\u276f') : ' ';
const check = isChecked ? boltYellow('\u25c9') : dimText('\u25cb');
const label = atCursor ? boltYellow(choices[i].name) : choices[i].name;
out += `\x1b[2K ${prefix} ${check} ${label}\n`;
}
out += `\x1b[2K${dimText(' Space to toggle, Enter to confirm')}\n`;
linesWritten = choices.length + 2;
stdout.write(out);
}
const wasRaw = stdin.isRaw;
stdin.setRawMode(true);
stdin.resume();
stdout.write(HIDE_CURSOR);
const onData = (data) => {
const key = data.toString();
if (key === '\x03') { // Ctrl+C
cleanup();
reject(Object.assign(new Error('User cancelled'), { name: 'ExitPromptError' }));
return;
}
if (key === '\x1b[A') cursor = Math.max(0, cursor - 1);
else if (key === '\x1b[B') cursor = Math.min(choices.length - 1, cursor + 1);
else if (key === ' ') {
if (selected.has(cursor)) selected.delete(cursor);
else selected.add(cursor);
} else if (key === '\r') {
render(true);
cleanup();
resolve(choices.filter((_, i) => selected.has(i)).map(c => c.value));
return;
}
render(false);
};
function cleanup() {
stdin.removeListener('data', onData);
stdin.setRawMode(wasRaw ?? false);
stdin.pause();
stdout.write(SHOW_CURSOR);
}
render(false);
stdin.on('data', onData);
});
}
async function confirm({ message, defaultValue = true }) {
const { stdin, stdout } = process;
if (!stdin.isTTY) {
stdout.write(`${boltYellow('\u2714')} ${bold(message)} ${boltYellow(defaultValue ? 'Yes' : 'No')}\n`);
return defaultValue;
}
return new Promise((resolve, reject) => {
const hint = defaultValue ? 'Y/n' : 'y/N';
function render(answer) {
let out = '\r\x1b[2K';
if (answer !== undefined) {
out += `${boltYellow('\u2714')} ${bold(message)} ${boltYellow(answer ? 'Yes' : 'No')}\n`;
} else {
out += `${boltYellow('?')} ${bold(message)} ${dimText(`(${hint})`)} `;
}
stdout.write(out);
}
const wasRaw = stdin.isRaw;
stdin.setRawMode(true);
stdin.resume();
const onData = (data) => {
const key = data.toString().toLowerCase();
if (key === '\x03') {
cleanup();
stdout.write('\n');
reject(Object.assign(new Error('User cancelled'), { name: 'ExitPromptError' }));
return;
}
let answer;
if (key === 'y') answer = true;
else if (key === 'n') answer = false;
else if (key === '\r') answer = defaultValue;
else return;
render(answer);
cleanup();
resolve(answer);
};
function cleanup() {
stdin.removeListener('data', onData);
stdin.setRawMode(wasRaw ?? false);
stdin.pause();
}
render(undefined);
stdin.on('data', onData);
});
}
async function select({ message, choices }) {
const { stdin, stdout } = process;
if (!stdin.isTTY) return choices[0].value;
return new Promise((resolve, reject) => {
let cursor = 0;
let linesWritten = 0;
function render(final) {
let out = '';
if (linesWritten > 0) out += `\x1b[${linesWritten}A`;
if (final) {
out += CLEAR_DOWN;
out += `${boltYellow('\u2714')} ${bold(message)} ${boltYellow(choices[cursor].name)}\n`;
linesWritten = 1;
stdout.write(out);
return;
}
out += `\x1b[2K${boltYellow('?')} ${bold(message)}\n`;
for (let i = 0; i < choices.length; i++) {
const atCursor = i === cursor;
const prefix = atCursor ? boltYellow('\u276f') : ' ';
const label = atCursor ? boltYellow(choices[i].name) : choices[i].name;
out += `\x1b[2K ${prefix} ${label}\n`;
}
linesWritten = choices.length + 1;
stdout.write(out);
}
const wasRaw = stdin.isRaw;
stdin.setRawMode(true);
stdin.resume();
stdout.write(HIDE_CURSOR);
const onData = (data) => {
const key = data.toString();
if (key === '\x03') {
cleanup();
reject(Object.assign(new Error('User cancelled'), { name: 'ExitPromptError' }));
return;
}
if (key === '\x1b[A') cursor = Math.max(0, cursor - 1);
else if (key === '\x1b[B') cursor = Math.min(choices.length - 1, cursor + 1);
else if (key === '\r') {
render(true);
cleanup();
resolve(choices[cursor].value);
return;
}
render(false);
};
function cleanup() {
stdin.removeListener('data', onData);
stdin.setRawMode(wasRaw ?? false);
stdin.pause();
stdout.write(SHOW_CURSOR);
}
render(false);
stdin.on('data', onData);
});
}
async function textInput({ message, defaultValue = '', mask = false }) {
const { stdin, stdout } = process;
if (!stdin.isTTY) return defaultValue;
return new Promise((resolve, reject) => {
let buffer = '';
function render(final) {
let out = '\r\x1b[2K';
if (final) {
const value = buffer || defaultValue;
const display = mask ? '\u2022'.repeat(value.length) : value;
out += `${boltYellow('\u2714')} ${bold(message)} ${boltYellow(display)}\n`;
} else {
const display = mask ? '\u2022'.repeat(buffer.length) : buffer;
const hint = defaultValue && !buffer ? dimText(` (${defaultValue})`) : '';
out += `${boltYellow('?')} ${bold(message)}${hint} ${display}`;
}
stdout.write(out);
}
const wasRaw = stdin.isRaw;
stdin.setRawMode(true);
stdin.resume();
const onData = (data) => {
const key = data.toString();
if (key === '\x03') {
cleanup();
stdout.write('\n');
reject(Object.assign(new Error('User cancelled'), { name: 'ExitPromptError' }));
return;
}
if (key === '\r') {
render(true);
cleanup();
resolve(buffer || defaultValue);
return;
}
if (key === '\x7f' || key === '\b') {
buffer = buffer.slice(0, -1);
} else if (key.length === 1 && key.charCodeAt(0) >= 32) {
buffer += key;
}
render(false);
};
function cleanup() {
stdin.removeListener('data', onData);
stdin.setRawMode(wasRaw ?? false);
stdin.pause();
}
render(false);
stdin.on('data', onData);
});
}
// ─── Project config (.storm.json) ────────────────────────────────────────────
const CONFIG_FILE = '.storm.json';
function readProjectConfig() {
const configPath = join(process.cwd(), CONFIG_FILE);
try {
return JSON.parse(readFileSync(configPath, 'utf-8'));
} catch {
return null;
}
}
function writeProjectConfig(tools, languages) {
const configPath = join(process.cwd(), CONFIG_FILE);
writeFileSync(configPath, JSON.stringify({ tools, languages }, null, 2) + '\n');
}
// ─── Content (fetched from orm.st at runtime) ───────────────────────────────
const SKILLS_BASE_URL = 'https://orm.st/skills';
const STORM_SKILL_MARKER = '<!-- storm-managed: storm-docs -->';
// --dev <dir> flag: read skills from a local directory instead of orm.st.
let devSkillsDir = null;
{
const devIdx = process.argv.indexOf('--dev');
if (devIdx !== -1 && process.argv[devIdx + 1]) {
devSkillsDir = process.argv[devIdx + 1];
}
}
async function fetchRules() {
try {
if (devSkillsDir) {
return readFileSync(join(devSkillsDir, 'storm-rules.md'), 'utf-8');
}
const res = await fetch(`${SKILLS_BASE_URL}/storm-rules.md`);
if (!res.ok) throw new Error(`${res.status}`);
return await res.text();
} catch {
return null;
}
}
async function fetchSkillIndex(language) {
try {
if (devSkillsDir) {
return JSON.parse(readFileSync(join(devSkillsDir, `index-${language}.json`), 'utf-8'));
}
const res = await fetch(`${SKILLS_BASE_URL}/index-${language}.json`);
if (!res.ok) throw new Error(`${res.status}`);
return await res.json();
} catch {
return null;
}
}
const DEV_SETUP_APPEND = `
## Development Mode
This project uses a local (unpublished) version of Storm. Add \`mavenLocal()\` as the first repository in Gradle so it resolves Storm artifacts from the local Maven cache (\`~/.m2/repository\`):
\`\`\`kotlin
repositories {
mavenLocal()
mavenCentral()
}
\`\`\`
`;
async function fetchSkill(name) {
try {
if (devSkillsDir) {
let content = readFileSync(join(devSkillsDir, `${name}.md`), 'utf-8');
if (name === 'storm-setup') content = content.trimEnd() + '\n' + DEV_SETUP_APPEND;
return content.trimEnd() + '\n\n' + STORM_SKILL_MARKER + '\n';
}
const url = `${SKILLS_BASE_URL}/${name}.md`;
const res = await fetch(url);
if (!res.ok) throw new Error(`${res.status}`);
const content = await res.text();
return content.trimEnd() + '\n\n' + STORM_SKILL_MARKER + '\n';
} catch {
return null;
}
}
function installSkill(name, content, toolConfig, created) {
const cwd = process.cwd();
const fullPath = join(cwd, toolConfig.skillPath(name));
if (existsSync(fullPath) && readFileSync(fullPath, 'utf-8') === content) return;
mkdirSync(dirname(fullPath), { recursive: true });
writeFileSync(fullPath, content);
created.push(toolConfig.skillPath(name));
}
function cleanStaleSkills(toolConfigs, installedSkillNames, skipped) {
const cwd = process.cwd();
const installed = new Set(installedSkillNames);
for (const config of toolConfigs) {
if (!config.skillDirs) continue;
for (const dir of config.skillDirs) {
const fullDir = join(cwd, dir);
if (!existsSync(fullDir)) continue;
let entries;
try { entries = readdirSync(fullDir); } catch { continue; }
for (const entry of entries) {
// Check files directly in this directory.
const filePath = join(fullDir, entry);
const candidates = [];
try {
const stat = statSync(filePath);
if (stat.isFile()) {
candidates.push(filePath);
} else if (stat.isDirectory()) {
// Check nested SKILL.md (Claude/Windsurf skills layout).
const nested = join(filePath, 'SKILL.md');
if (existsSync(nested)) candidates.push(nested);
}
} catch { continue; }
for (const candidate of candidates) {
try {
const content = readFileSync(candidate, 'utf-8');
const isStormManaged = content.trimEnd().endsWith(STORM_SKILL_MARKER)
|| /^<!-- storm-managed: \S+ -->/.test(content);
if (!isStormManaged) continue;
// Derive skill name from path.
const name = candidate.endsWith('SKILL.md')
? basename(dirname(candidate))
: basename(candidate).replace(/\.(instructions\.)?md$/, '');
if (!installed.has(name)) {
unlinkSync(candidate);
// Remove empty parent directory for nested layout.
const parentDir = dirname(candidate);
if (parentDir !== fullDir) {
try {
const remaining = readdirSync(parentDir);
if (remaining.length === 0) rmdirSync(parentDir);
} catch {}
}
skipped.push(`${name} (removed, no longer available)`);
}
} catch {}
}
}
}
}
}
// ─── Tool configs ────────────────────────────────────────────────────────────
const TOOL_CONFIGS = {
claude: {
name: 'Claude Code',
rulesFile: 'CLAUDE.md',
mcpFile: '.mcp.json',
mcpFormat: 'claude',
skillPath: (name) => `.claude/skills/${name}/SKILL.md`,
skillDirs: ['.claude/skills', '.claude/commands'],
},
cursor: {
name: 'Cursor',
rulesFile: '.cursor/rules/storm.md',
mcpFile: '.cursor/mcp.json',
mcpFormat: 'claude',
skillPath: (name) => `.cursor/rules/${name}.md`,
skillDirs: ['.cursor/rules'],
},
copilot: {
name: 'GitHub Copilot',
rulesFile: '.github/copilot-instructions.md',
skillPath: (name) => `.github/instructions/${name}.instructions.md`,
skillDirs: ['.github/instructions'],
},
windsurf: {
name: 'Windsurf',
rulesFile: '.windsurf/rules/storm.md',
mcpFormat: 'windsurf',
skillPath: (name) => `.windsurf/rules/${name}.md`,
skillDirs: ['.windsurf/rules'],
},
codex: {
name: 'Codex',
rulesFile: 'AGENTS.md',
mcpFormat: 'codex',
},
};
// Schema rules fetched from orm.st/skills/storm-schema-rules.md at runtime.
const DIALECTS = {
postgresql: { name: 'PostgreSQL', driver: 'pg', defaultPort: 5432 },
mysql: { name: 'MySQL', driver: 'mysql2', defaultPort: 3306 },
mariadb: { name: 'MariaDB', driver: 'mysql2', defaultPort: 3306 },
oracle: { name: 'Oracle', driver: 'oracledb', defaultPort: 1521 },
mssqlserver: { name: 'SQL Server', driver: 'mssql', defaultPort: 1433 },
sqlite: { name: 'SQLite', driver: 'better-sqlite3', defaultPort: 0, fileBased: true },
h2: { name: 'H2', driver: 'pg', defaultPort: 5435 },
};
const MCP_SERVER_SOURCE = `#!/usr/bin/env node
// Storm Schema MCP Server
// Generated by storm cli v${VERSION}
//
// Exposes database schema metadata via MCP. Read-only, no data access.
import { createRequire } from 'module';
import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { createInterface } from 'readline';
import { fileURLToPath } from 'url';
var __dirname = dirname(fileURLToPath(import.meta.url));
var require = createRequire(import.meta.url);
var configPath = process.argv[2] || join(__dirname, 'connection.json');
var config = JSON.parse(readFileSync(configPath, 'utf-8'));
// ─── Database ────────────────────────────────────────────
var db, dbType;
var dbReady = connectDatabase();
async function connectDatabase() {
if (config.dialect === 'postgresql' || config.dialect === 'h2') {
var pg = require('pg');
db = new pg.Pool({
host: config.host, port: config.port, database: config.database,
user: config.username, password: config.password,
});
dbType = 'pg';
} else if (config.dialect === 'mysql' || config.dialect === 'mariadb') {
var mysql = require('mysql2/promise');
db = mysql.createPool({
host: config.host, port: config.port, database: config.database,
user: config.username, password: config.password,
});
dbType = 'mysql';
} else if (config.dialect === 'mssqlserver') {
var mssql = require('mssql');
db = await mssql.connect({
server: config.host, port: config.port, database: config.database,
user: config.username, password: config.password,
options: { encrypt: false, trustServerCertificate: true },
});
dbType = 'mssql';
} else if (config.dialect === 'oracle') {
var oracledb = require('oracledb');
oracledb.outFormat = oracledb.OUT_FORMAT_OBJECT;
db = await oracledb.getConnection({
user: config.username, password: config.password,
connectString: config.host + ':' + config.port + '/' + config.database,
});
dbType = 'oracle';
} else if (config.dialect === 'sqlite') {
var Database = require('better-sqlite3');
db = new Database(config.database, { readonly: true });
dbType = 'sqlite';
}
}
async function dbQuery(sql, params) {
await dbReady;
if (dbType === 'pg') {
var result = await db.query(sql, params);
return result.rows;
} else if (dbType === 'mysql') {
var response = await db.execute(sql, params);
return response[0];
} else if (dbType === 'mssql') {
var request = db.request();
params.forEach(function(p, i) { request.input('p' + i, p); });
var result = await request.query(sql);
return result.recordset;
} else if (dbType === 'oracle') {
var result = await db.execute(sql, params);
return result.rows;
} else if (dbType === 'sqlite') {
return params.length > 0 ? db.prepare(sql).all(params) : db.prepare(sql).all();
}
}
var schemaName;
if (config.dialect === 'postgresql') schemaName = 'public';
else if (config.dialect === 'h2') schemaName = 'PUBLIC';
else if (config.dialect === 'mssqlserver') schemaName = 'dbo';
else if (config.dialect === 'oracle') schemaName = (config.username || '').toUpperCase();
else if (config.dialect !== 'sqlite') schemaName = config.database;
function ph(n) {
if (dbType === 'pg') return '$' + n;
if (dbType === 'mssql') return '@p' + (n - 1);
if (dbType === 'oracle') return ':' + n;
return '?';
}
// ─── Schema queries ──────────────────────────────────────
async function listTables() {
await dbReady;
if (dbType === 'sqlite') {
return db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name")
.all().map(function(r) { return r.name; });
}
if (dbType === 'oracle') {
var rows = await dbQuery(
'SELECT table_name FROM all_tables WHERE owner = ' + ph(1) + ' ORDER BY table_name',
[schemaName]);
return rows.map(function(r) { return r.TABLE_NAME; });
}
var sql = 'SELECT table_name FROM information_schema.tables'
+ ' WHERE table_schema = ' + ph(1)
+ " AND table_type = 'BASE TABLE'"
+ ' ORDER BY table_name';
var rows = await dbQuery(sql, [schemaName]);
return rows.map(function(r) { return r.table_name || r.TABLE_NAME; });
}
async function describeTable(tableName) {