@k-l-lambda/lilylet 0.1.30

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.
@@ -0,0 +1,789 @@
1
+ /**
2
+ * LilyPond to Lilylet Decoder
3
+ *
4
+ * Converts LilyPond notation files to Lilylet document format using the lotus parser.
5
+ * This module is browser-compatible - it uses pre-compiled parser from lotus.
6
+ */
7
+
8
+ // Import directly from the compiled lib directory to avoid ESM issues
9
+ import * as lilyParser from "@k-l-lambda/lotus/lib/inc/lilyParser/index.js";
10
+
11
+ // Import pre-compiled LilyPond parser (browser-compatible)
12
+ // @ts-ignore - CommonJS module
13
+ import * as lilypondParser from "@k-l-lambda/lotus/lib.browser/lib/lilyParser.js";
14
+
15
+ import {
16
+ LilyletDoc,
17
+ Measure,
18
+ Event,
19
+ NoteEvent,
20
+ RestEvent,
21
+ ContextChange,
22
+ MarkupEvent,
23
+ Pitch,
24
+ Duration,
25
+ Mark,
26
+ KeySignature,
27
+ Clef,
28
+ StemDirection,
29
+ Accidental,
30
+ Phonet,
31
+ Fraction,
32
+ ArticulationType,
33
+ OrnamentType,
34
+ DynamicType,
35
+ HairpinType,
36
+ PedalType,
37
+ NavigationMarkType,
38
+ Placement,
39
+ Metadata,
40
+ Tempo,
41
+ } from "./types";
42
+
43
+
44
+ // Phonet names mapping
45
+ const PHONET_NAMES: Record<number, Phonet> = {
46
+ 0: Phonet.c,
47
+ 1: Phonet.d,
48
+ 2: Phonet.e,
49
+ 3: Phonet.f,
50
+ 4: Phonet.g,
51
+ 5: Phonet.a,
52
+ 6: Phonet.b,
53
+ };
54
+
55
+
56
+ // Alter value to accidental
57
+ const ALTER_TO_ACCIDENTAL: Record<number, Accidental> = {
58
+ [-2]: Accidental.doubleFlat,
59
+ [-1]: Accidental.flat,
60
+ [0]: Accidental.natural,
61
+ [1]: Accidental.sharp,
62
+ [2]: Accidental.doubleSharp,
63
+ };
64
+
65
+
66
+ // LilyPond clef names to Lilylet clef
67
+ const LILYPOND_CLEF_MAP: Record<string, Clef> = {
68
+ treble: Clef.treble,
69
+ G: Clef.treble,
70
+ bass: Clef.bass,
71
+ F: Clef.bass,
72
+ alto: Clef.alto,
73
+ C: Clef.alto,
74
+ };
75
+
76
+
77
+ // Key signature fifths to pitch/accidental mapping
78
+ const KEY_FIFTHS_MAP: Record<number, { pitch: Phonet; accidental?: Accidental; mode: 'major' | 'minor' }> = {
79
+ [-7]: { pitch: Phonet.c, accidental: Accidental.flat, mode: 'major' },
80
+ [-6]: { pitch: Phonet.g, accidental: Accidental.flat, mode: 'major' },
81
+ [-5]: { pitch: Phonet.d, accidental: Accidental.flat, mode: 'major' },
82
+ [-4]: { pitch: Phonet.a, accidental: Accidental.flat, mode: 'major' },
83
+ [-3]: { pitch: Phonet.e, accidental: Accidental.flat, mode: 'major' },
84
+ [-2]: { pitch: Phonet.b, accidental: Accidental.flat, mode: 'major' },
85
+ [-1]: { pitch: Phonet.f, mode: 'major' },
86
+ [0]: { pitch: Phonet.c, mode: 'major' },
87
+ [1]: { pitch: Phonet.g, mode: 'major' },
88
+ [2]: { pitch: Phonet.d, mode: 'major' },
89
+ [3]: { pitch: Phonet.a, mode: 'major' },
90
+ [4]: { pitch: Phonet.e, mode: 'major' },
91
+ [5]: { pitch: Phonet.b, mode: 'major' },
92
+ [6]: { pitch: Phonet.f, accidental: Accidental.sharp, mode: 'major' },
93
+ [7]: { pitch: Phonet.c, accidental: Accidental.sharp, mode: 'major' },
94
+ };
95
+
96
+
97
+ // Articulation mapping from LilyPond
98
+ const ARTICULATION_MAP: Record<string, ArticulationType> = {
99
+ staccato: ArticulationType.staccato,
100
+ staccatissimo: ArticulationType.staccatissimo,
101
+ tenuto: ArticulationType.tenuto,
102
+ marcato: ArticulationType.marcato,
103
+ accent: ArticulationType.accent,
104
+ portato: ArticulationType.portato,
105
+ };
106
+
107
+
108
+ // Ornament mapping from LilyPond
109
+ const ORNAMENT_MAP: Record<string, OrnamentType> = {
110
+ trill: OrnamentType.trill,
111
+ turn: OrnamentType.turn,
112
+ mordent: OrnamentType.mordent,
113
+ prall: OrnamentType.prall,
114
+ fermata: OrnamentType.fermata,
115
+ shortfermata: OrnamentType.shortFermata,
116
+ arpeggio: OrnamentType.arpeggio,
117
+ };
118
+
119
+
120
+ // Dynamic regex and mapping
121
+ const DYNAMIC_REGEX = /^[fpmrsz]+$/;
122
+ const DYNAMIC_MAP: Record<string, DynamicType> = {
123
+ ppp: DynamicType.ppp,
124
+ pp: DynamicType.pp,
125
+ p: DynamicType.p,
126
+ mp: DynamicType.mp,
127
+ mf: DynamicType.mf,
128
+ f: DynamicType.f,
129
+ ff: DynamicType.ff,
130
+ fff: DynamicType.fff,
131
+ sfz: DynamicType.sfz,
132
+ rfz: DynamicType.rfz,
133
+ };
134
+
135
+
136
+ // Common tempo text words (from fprod corpus analysis)
137
+ // Single words, lowercase for case-insensitive matching
138
+ const TEMPO_WORDS = new Set([
139
+ // Basic tempo markings (Italian) - very slow to very fast
140
+ 'grave', 'largo', 'larghetto', 'lento', 'adagio', 'adagietto',
141
+ 'andante', 'andantino', 'moderato', 'allegretto', 'allegro',
142
+ 'vivace', 'presto', 'prestissimo',
143
+ // Tempo modifiers
144
+ 'molto', 'poco', 'più', 'meno', 'assai', 'con', 'moto', 'brio',
145
+ 'ma', 'non', 'troppo', 'cantabile', 'sostenuto', 'espressivo',
146
+ 'grazioso', 'maestoso', 'agitato', 'animato', 'tranquillo',
147
+ // Tempo changes
148
+ 'tempo', 'primo',
149
+ 'rit', 'ritard', 'ritardando', 'riten', 'ritenuto',
150
+ 'rall', 'rallentando',
151
+ 'accel', 'accelerando',
152
+ 'allarg', 'allargando',
153
+ 'calando', 'morendo', 'smorzando', 'smorz',
154
+ 'rubato',
155
+ ]);
156
+
157
+
158
+ // Check if text contains any tempo-related word (case-insensitive)
159
+ const containsTempoWord = (text: string): boolean => {
160
+ // Remove punctuation and split into words
161
+ const words = text.toLowerCase().replace(/[.,!?]/g, '').split(/\s+/);
162
+ return words.some(word => TEMPO_WORDS.has(word));
163
+ };
164
+
165
+
166
+ // Convert lotus Tempo to Lilylet Tempo
167
+ const convertTempo = (lotusTempo: any): Tempo | undefined => {
168
+ if (!lotusTempo) return undefined;
169
+
170
+ const tempo: Tempo = {};
171
+
172
+ // Text (e.g., "Allegro")
173
+ if (lotusTempo.text) {
174
+ tempo.text = typeof lotusTempo.text === 'string'
175
+ ? lotusTempo.text
176
+ : extractTextFromObject(lotusTempo.text);
177
+ }
178
+
179
+ // Metronome mark (e.g., ♩ = 120)
180
+ if (lotusTempo.beatsPerMinute !== undefined && Number.isFinite(lotusTempo.beatsPerMinute)) {
181
+ tempo.bpm = lotusTempo.beatsPerMinute;
182
+
183
+ // Beat unit (note value)
184
+ if (lotusTempo.unit) {
185
+ tempo.beat = convertDuration(lotusTempo.unit);
186
+ }
187
+ }
188
+
189
+ // Return undefined if no meaningful tempo data
190
+ if (!tempo.text && !tempo.bpm) {
191
+ return undefined;
192
+ }
193
+
194
+ return tempo;
195
+ };
196
+
197
+
198
+ // Internal measure representation during parsing
199
+ interface ParsedMeasure {
200
+ key: number | null;
201
+ timeSig: Fraction | null;
202
+ voices: ParsedVoice[];
203
+ partial: boolean;
204
+ }
205
+
206
+
207
+ interface ParsedVoice {
208
+ staff: number;
209
+ events: Event[];
210
+ }
211
+
212
+
213
+ // Convert LilyPond pitch to Lilylet pitch
214
+ const convertPitch = (phonetStep: number, alterValue: number, octave: number): Pitch => {
215
+ const phonet = PHONET_NAMES[phonetStep % 7];
216
+ const accidental = alterValue !== 0 ? ALTER_TO_ACCIDENTAL[alterValue] : undefined;
217
+
218
+ // Lotus parser absolute octave: 0 = C3, 1 = C4, 2 = C5
219
+ // Lilylet octave: 0 = C4, 1 = C5, -1 = C3
220
+ // Conversion: lilyletOctave = lotusAbsoluteOctave - 1
221
+ const lilyletOctave = octave - 1;
222
+
223
+ return {
224
+ phonet,
225
+ accidental,
226
+ octave: lilyletOctave,
227
+ };
228
+ };
229
+
230
+
231
+ // Convert LilyPond duration to Lilylet duration
232
+ const convertDuration = (duration: any): Duration => {
233
+ return {
234
+ division: Math.pow(2, duration.division),
235
+ dots: duration.dots || 0,
236
+ };
237
+ };
238
+
239
+
240
+ // Convert key fifths to KeySignature
241
+ const convertKeySignature = (fifths: number): KeySignature | undefined => {
242
+ const mapping = KEY_FIFTHS_MAP[fifths];
243
+ if (mapping) {
244
+ return {
245
+ pitch: mapping.pitch,
246
+ accidental: mapping.accidental,
247
+ mode: mapping.mode,
248
+ };
249
+ }
250
+ return undefined;
251
+ };
252
+
253
+
254
+ // Parse post-events to marks
255
+ const parsePostEvents = (postEvents: any[]): Mark[] => {
256
+ const marks: Mark[] = [];
257
+
258
+ if (!postEvents) return marks;
259
+
260
+ for (const event of postEvents) {
261
+ // String events
262
+ if (typeof event === 'string') {
263
+ if (event === '~') {
264
+ marks.push({ markType: 'tie', start: true });
265
+ } else if (event === '(') {
266
+ marks.push({ markType: 'slur', start: true });
267
+ } else if (event === ')') {
268
+ marks.push({ markType: 'slur', start: false });
269
+ }
270
+ continue;
271
+ }
272
+
273
+ // PostEvent objects
274
+ if (event && typeof event === 'object') {
275
+ const arg = event.arg;
276
+
277
+ // String articulation/ornament
278
+ if (typeof arg === 'string') {
279
+ const cleanArg = arg.replace(/^-/, '');
280
+ if (ARTICULATION_MAP[cleanArg]) {
281
+ marks.push({ markType: 'articulation', type: ARTICULATION_MAP[cleanArg] });
282
+ } else if (ORNAMENT_MAP[cleanArg]) {
283
+ marks.push({ markType: 'ornament', type: ORNAMENT_MAP[cleanArg] });
284
+ }
285
+ }
286
+
287
+ // Fingering (number 1-5)
288
+ if (typeof arg === 'number' && arg >= 1 && arg <= 5) {
289
+ marks.push({ markType: 'fingering', finger: arg });
290
+ }
291
+
292
+ // Command (dynamics, hairpins, etc.)
293
+ if (arg && typeof arg === 'object' && 'cmd' in arg) {
294
+ const cmd = arg.cmd;
295
+ if (DYNAMIC_REGEX.test(cmd) && DYNAMIC_MAP[cmd]) {
296
+ marks.push({ markType: 'dynamic', type: DYNAMIC_MAP[cmd] });
297
+ } else if (cmd === '<') {
298
+ marks.push({ markType: 'hairpin', type: HairpinType.crescendoStart });
299
+ } else if (cmd === '>') {
300
+ marks.push({ markType: 'hairpin', type: HairpinType.diminuendoStart });
301
+ } else if (cmd === '!') {
302
+ marks.push({ markType: 'hairpin', type: HairpinType.crescendoEnd }); // or diminuendoEnd
303
+ } else if (cmd === 'sustainOn') {
304
+ marks.push({ markType: 'pedal', type: PedalType.sustainOn });
305
+ } else if (cmd === 'sustainOff') {
306
+ marks.push({ markType: 'pedal', type: PedalType.sustainOff });
307
+ } else if (cmd === 'coda') {
308
+ marks.push({ markType: 'navigation', type: NavigationMarkType.coda });
309
+ } else if (cmd === 'segno') {
310
+ marks.push({ markType: 'navigation', type: NavigationMarkType.segno });
311
+ } else if (cmd === '\\markup' || cmd === 'markup') {
312
+ // Markup attached to note
313
+ const text = extractTextFromObject(arg.args);
314
+ if (text && !containsTempoWord(text)) {
315
+ const direction = event.direction;
316
+ const placement: Placement | undefined =
317
+ direction === 'up' ? Placement.above :
318
+ direction === 'down' ? Placement.below : undefined;
319
+ marks.push({ markType: 'markup', content: text, placement });
320
+ }
321
+ }
322
+ }
323
+
324
+ // Handle markup command directly (proto: 'Command' with \\markup)
325
+ if (arg && typeof arg === 'object' && arg.proto === 'Command' && arg.cmd === '\\markup') {
326
+ const text = extractTextFromObject(arg.args);
327
+ if (text && !containsTempoWord(text)) {
328
+ const direction = event.direction;
329
+ const placement: Placement | undefined =
330
+ direction === 'up' ? Placement.above :
331
+ direction === 'down' ? Placement.below : undefined;
332
+ marks.push({ markType: 'markup', content: text, placement });
333
+ }
334
+ }
335
+ }
336
+ }
337
+
338
+ return marks;
339
+ };
340
+
341
+
342
+ // Parse a LilyPond document to measures
343
+ const parseLilyDocument = (lilyDocument: lilyParser.LilyDocument): ParsedMeasure[] => {
344
+ const measureMap = new Map<number, ParsedMeasure>();
345
+ const staffNames: string[] = [];
346
+
347
+ const interpreter = lilyDocument.interpret();
348
+
349
+ interpreter.layoutMusic.musicTracks.forEach((track, vi) => {
350
+ const appendStaff = (staffName: string): void => {
351
+ if (!staffNames.includes(staffName)) {
352
+ staffNames.push(staffName);
353
+ }
354
+ };
355
+
356
+ const staffName = track.contextDict?.Staff;
357
+ if (staffName) {
358
+ appendStaff(staffName);
359
+ }
360
+ let staff = staffName ? staffNames.indexOf(staffName) + 1 : 1;
361
+
362
+ const context = new lilyParser.TrackContext(undefined, {
363
+ listener: (term: lilyParser.BaseTerm, context: lilyParser.TrackContext) => {
364
+ const mi = term._measure;
365
+ if (mi === undefined) return;
366
+
367
+ if (!measureMap.has(mi)) {
368
+ measureMap.set(mi, {
369
+ key: null,
370
+ timeSig: null,
371
+ voices: [],
372
+ partial: false,
373
+ });
374
+ }
375
+
376
+ // Update staff from context
377
+ if (context.staffName) {
378
+ appendStaff(context.staffName);
379
+ staff = staffNames.indexOf(context.staffName) + 1;
380
+ }
381
+
382
+ const measure = measureMap.get(mi)!;
383
+
384
+ // Initialize voice for this track
385
+ if (!measure.voices[vi]) {
386
+ measure.voices[vi] = {
387
+ staff,
388
+ events: [],
389
+ };
390
+ }
391
+ const voice = measure.voices[vi];
392
+
393
+ // Update key/time from context on music events
394
+ if (term instanceof lilyParser.MusicEvent ||
395
+ term instanceof lilyParser.LilyTerms.StemDirection ||
396
+ term instanceof lilyParser.LilyTerms.OctaveShift) {
397
+
398
+ if (context.key && measure.key === null) {
399
+ measure.key = context.key.key;
400
+ }
401
+ if (context.time && measure.timeSig === null) {
402
+ measure.timeSig = {
403
+ numerator: context.time.value.numerator,
404
+ denominator: context.time.value.denominator,
405
+ };
406
+ }
407
+ if (context.partialDuration) {
408
+ measure.partial = true;
409
+ }
410
+ }
411
+
412
+ // Handle music events
413
+ if (term instanceof lilyParser.MusicEvent) {
414
+ // Update staff from voice events
415
+ voice.staff = staff;
416
+
417
+ // Handle clef context change
418
+ if (context.clef && !voice.events.some(e => e.type === 'context' && (e as ContextChange).clef)) {
419
+ const clef = LILYPOND_CLEF_MAP[context.clef.clefName];
420
+ if (clef) {
421
+ voice.events.push({
422
+ type: 'context',
423
+ clef,
424
+ });
425
+ }
426
+ }
427
+
428
+ // Handle ottava
429
+ if (context.octave?.value && !voice.events.some(e => e.type === 'context' && (e as ContextChange).ottava !== undefined)) {
430
+ voice.events.push({
431
+ type: 'context',
432
+ ottava: context.octave.value,
433
+ });
434
+ }
435
+
436
+ // Handle stem direction context
437
+ if (context.stemDirection && !voice.events.some(e => e.type === 'context' && (e as ContextChange).stemDirection)) {
438
+ const stemDir = context.stemDirection === 'Up' ? StemDirection.up :
439
+ context.stemDirection === 'Down' ? StemDirection.down : undefined;
440
+ if (stemDir) {
441
+ voice.events.push({
442
+ type: 'context',
443
+ stemDirection: stemDir,
444
+ });
445
+ }
446
+ }
447
+
448
+ // Process Chord (note or chord)
449
+ if (term instanceof lilyParser.LilyTerms.Chord) {
450
+ const pitches: Pitch[] = [];
451
+
452
+ for (const pitch of term.pitchesValue) {
453
+ if (pitch instanceof lilyParser.LilyTerms.ChordElement) {
454
+ pitches.push(convertPitch(
455
+ pitch.phonetStep,
456
+ pitch.alterValue || 0,
457
+ pitch.absolutePitch.octave
458
+ ));
459
+ }
460
+ }
461
+
462
+ if (pitches.length > 0) {
463
+ const marks = parsePostEvents(term.post_events);
464
+
465
+ // Add beam marks
466
+ if (term.beamOn) {
467
+ marks.push({ markType: 'beam', start: true });
468
+ } else if (term.beamOff) {
469
+ marks.push({ markType: 'beam', start: false });
470
+ }
471
+
472
+ // Add tie
473
+ if (term.isTying) {
474
+ marks.push({ markType: 'tie', start: true });
475
+ }
476
+
477
+ const noteEvent: NoteEvent = {
478
+ type: 'note',
479
+ pitches,
480
+ duration: convertDuration(term.durationValue),
481
+ grace: context.inGrace || undefined,
482
+ };
483
+
484
+ if (marks.length > 0) {
485
+ noteEvent.marks = marks;
486
+ }
487
+
488
+ voice.events.push(noteEvent);
489
+ }
490
+ }
491
+ // Process Rest
492
+ else if (term instanceof lilyParser.LilyTerms.Rest) {
493
+ const restEvent: RestEvent = {
494
+ type: 'rest',
495
+ duration: convertDuration(term.durationValue),
496
+ invisible: term.isSpacer || undefined,
497
+ };
498
+
499
+ // Positioned rest
500
+ if (!term.isSpacer && context.pitch) {
501
+ restEvent.pitch = convertPitch(
502
+ context.pitch.phonetStep,
503
+ 0,
504
+ context.pitch.octave
505
+ );
506
+ }
507
+
508
+ voice.events.push(restEvent);
509
+ }
510
+ }
511
+ // Handle standalone stem direction
512
+ else if (term instanceof lilyParser.LilyTerms.StemDirection) {
513
+ const stemDir = term.direction === 'Up' ? StemDirection.up :
514
+ term.direction === 'Down' ? StemDirection.down : undefined;
515
+ if (stemDir) {
516
+ voice.events.push({
517
+ type: 'context',
518
+ stemDirection: stemDir,
519
+ });
520
+ }
521
+ }
522
+ // Handle standalone clef
523
+ else if (term instanceof lilyParser.LilyTerms.Clef) {
524
+ const clef = LILYPOND_CLEF_MAP[term.clefName];
525
+ if (clef) {
526
+ voice.events.push({
527
+ type: 'context',
528
+ clef,
529
+ });
530
+ }
531
+ }
532
+ // Handle ottava shift
533
+ else if (term instanceof lilyParser.LilyTerms.OctaveShift) {
534
+ voice.events.push({
535
+ type: 'context',
536
+ ottava: term.value,
537
+ });
538
+ }
539
+ // Handle staff change
540
+ else if (term instanceof lilyParser.LilyTerms.Change) {
541
+ if (term.args?.[0]?.key === 'Staff') {
542
+ // Staff change mid-voice
543
+ voice.staff = staff;
544
+ }
545
+ }
546
+ // Handle tempo
547
+ else if (term instanceof lilyParser.LilyTerms.Tempo) {
548
+ const tempo = convertTempo(term);
549
+ if (tempo) {
550
+ voice.events.push({
551
+ type: 'context',
552
+ tempo,
553
+ });
554
+ }
555
+ }
556
+ // Handle standalone markup command
557
+ else {
558
+ const termAny = term as any;
559
+ if (termAny.proto === 'Command' && (termAny.cmd === '\\markup' || termAny.cmd === 'markup')) {
560
+ const text = extractTextFromObject(termAny.args);
561
+ if (text && !containsTempoWord(text)) {
562
+ const markupEvent: MarkupEvent = {
563
+ type: 'markup',
564
+ content: text,
565
+ };
566
+ voice.events.push(markupEvent);
567
+ }
568
+ }
569
+ }
570
+ },
571
+ });
572
+
573
+ context.execute(track.music);
574
+ });
575
+
576
+ // Filter out empty voices and convert to array, sorted by measure number
577
+ const measures = Array.from(measureMap.entries())
578
+ .sort(([a], [b]) => a - b)
579
+ .map(([, measure]) => measure);
580
+ for (const measure of measures) {
581
+ measure.voices = measure.voices.filter(Boolean);
582
+ }
583
+
584
+ return measures;
585
+ };
586
+
587
+
588
+ // Check if a voice has real music content (not just spacer rests and context changes)
589
+ const hasRealContent = (events: Event[]): boolean => {
590
+ return events.some(e => {
591
+ if (e.type === 'note') return true;
592
+ if (e.type === 'rest' && !(e as RestEvent).invisible) return true;
593
+ return false;
594
+ });
595
+ };
596
+
597
+
598
+ // Remove quotes from string literal
599
+ const unquoteString = (str: string): string => {
600
+ if (str.startsWith('"') && str.endsWith('"')) {
601
+ return str.slice(1, -1);
602
+ }
603
+ return str;
604
+ };
605
+
606
+
607
+ // Extract text from lotus parser objects recursively
608
+ const extractTextFromObject = (obj: any): string | undefined => {
609
+ if (!obj) return undefined;
610
+
611
+ // Simple string
612
+ if (typeof obj === 'string') {
613
+ return obj;
614
+ }
615
+
616
+ // Array - concatenate all text
617
+ if (Array.isArray(obj)) {
618
+ const texts: string[] = [];
619
+ for (const item of obj) {
620
+ const text = extractTextFromObject(item);
621
+ if (text) texts.push(text);
622
+ }
623
+ return texts.join(' ').trim() || undefined;
624
+ }
625
+
626
+ // Object with proto property (lotus parser objects)
627
+ if (obj && typeof obj === 'object' && obj.proto) {
628
+ switch (obj.proto) {
629
+ case 'LiteralString':
630
+ // exp contains quoted string like '"Hello"'
631
+ if (obj.exp) {
632
+ return unquoteString(obj.exp);
633
+ }
634
+ break;
635
+
636
+ case 'MarkupCommand':
637
+ case 'Command':
638
+ // Recursively extract from args
639
+ if (obj.args) {
640
+ return extractTextFromObject(obj.args);
641
+ }
642
+ break;
643
+
644
+ case 'InlineBlock':
645
+ // Extract from body, skip primitive commands
646
+ if (obj.body) {
647
+ const texts: string[] = [];
648
+ for (const item of obj.body) {
649
+ if (item.proto !== 'Primitive') {
650
+ const text = extractTextFromObject(item);
651
+ if (text) texts.push(text);
652
+ }
653
+ }
654
+ return texts.join(' ').trim() || undefined;
655
+ }
656
+ break;
657
+
658
+ case 'String':
659
+ if (obj.value) {
660
+ return obj.value;
661
+ }
662
+ break;
663
+ }
664
+ }
665
+
666
+ // Fallback: try value property
667
+ if (obj.value !== undefined) {
668
+ return extractTextFromObject(obj.value);
669
+ }
670
+
671
+ return undefined;
672
+ };
673
+
674
+
675
+ // Extract string value from header field
676
+ const extractStringValue = (value: any): string | undefined => {
677
+ const text = extractTextFromObject(value);
678
+ return text ? text.trim() : undefined;
679
+ };
680
+
681
+
682
+ // Extract metadata from LilyDocument
683
+ const extractMetadata = (lilyDocument: lilyParser.LilyDocument): Metadata | undefined => {
684
+ try {
685
+ const attrs = lilyDocument.globalAttributesReadOnly();
686
+
687
+ const metadata: Metadata = {};
688
+
689
+ // Extract each field, handling markup structures
690
+ if (attrs.title) {
691
+ metadata.title = extractStringValue(attrs.title);
692
+ }
693
+ if (attrs.subtitle) {
694
+ metadata.subtitle = extractStringValue(attrs.subtitle);
695
+ }
696
+ if (attrs.composer) {
697
+ metadata.composer = extractStringValue(attrs.composer);
698
+ }
699
+ if (attrs.arranger) {
700
+ metadata.arranger = extractStringValue(attrs.arranger);
701
+ }
702
+ if (attrs.poet) {
703
+ metadata.lyricist = extractStringValue(attrs.poet);
704
+ }
705
+ if (attrs.opus) {
706
+ metadata.opus = extractStringValue(attrs.opus);
707
+ }
708
+ if (attrs.instrument) {
709
+ metadata.instrument = extractStringValue(attrs.instrument);
710
+ }
711
+
712
+ // Return undefined if no metadata fields were populated
713
+ if (Object.keys(metadata).length === 0) {
714
+ return undefined;
715
+ }
716
+
717
+ return metadata;
718
+ } catch (e) {
719
+ // If metadata extraction fails, continue without it
720
+ return undefined;
721
+ }
722
+ };
723
+
724
+
725
+ // Convert parsed measures to LilyletDoc
726
+ const parsedMeasuresToDoc = (parsedMeasures: ParsedMeasure[], metadata?: Metadata): LilyletDoc => {
727
+ const measures: Measure[] = parsedMeasures.map(pm => {
728
+ // Filter out voices that only contain spacer rests and context changes
729
+ const voices = pm.voices
730
+ .filter(v => hasRealContent(v.events))
731
+ .map(v => ({
732
+ staff: v.staff,
733
+ events: v.events,
734
+ }));
735
+
736
+ const measure: Measure = {
737
+ parts: [{
738
+ voices,
739
+ }],
740
+ };
741
+
742
+ if (pm.key !== null) {
743
+ measure.key = convertKeySignature(pm.key);
744
+ }
745
+ if (pm.timeSig) {
746
+ measure.timeSig = pm.timeSig;
747
+ }
748
+ if (pm.partial) {
749
+ measure.partial = true;
750
+ }
751
+
752
+ return measure;
753
+ });
754
+
755
+ const doc: LilyletDoc = { measures };
756
+ if (metadata) {
757
+ doc.metadata = metadata;
758
+ }
759
+ return doc;
760
+ };
761
+
762
+
763
+ /**
764
+ * Decode a LilyPond string to LilyletDoc (synchronous, browser-compatible)
765
+ */
766
+ const decode = (lilypondSource: string): LilyletDoc => {
767
+ const rawData = lilypondParser.parse(lilypondSource);
768
+ const lilyDocument = new lilyParser.LilyDocument(rawData);
769
+ const parsedMeasures = parseLilyDocument(lilyDocument);
770
+ const metadata = extractMetadata(lilyDocument);
771
+ return parsedMeasuresToDoc(parsedMeasures, metadata);
772
+ };
773
+
774
+
775
+ /**
776
+ * Decode from pre-parsed LilyDocument (synchronous, for when you already have parsed data)
777
+ */
778
+ const decodeFromDocument = (lilyDocument: lilyParser.LilyDocument): LilyletDoc => {
779
+ const parsedMeasures = parseLilyDocument(lilyDocument);
780
+ const metadata = extractMetadata(lilyDocument);
781
+ return parsedMeasuresToDoc(parsedMeasures, metadata);
782
+ };
783
+
784
+
785
+ export {
786
+ decode,
787
+ decodeFromDocument,
788
+ parseLilyDocument,
789
+ };