@libraz/libcantus 0.9.1 → 0.9.2

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 (154) hide show
  1. package/README.md +15 -0
  2. package/dist/analyze/index.cjs +1697 -0
  3. package/dist/analyze/index.cjs.map +1 -0
  4. package/dist/analyze/index.d.cts +429 -0
  5. package/dist/analyze/index.d.ts +429 -0
  6. package/dist/analyze/index.js +51 -0
  7. package/dist/analyze/index.js.map +1 -0
  8. package/dist/chunk-5HTNMQW4.js +653 -0
  9. package/dist/chunk-5HTNMQW4.js.map +1 -0
  10. package/dist/chunk-7Y7WF64D.js +410 -0
  11. package/dist/chunk-7Y7WF64D.js.map +1 -0
  12. package/dist/chunk-A4532ZFR.js +259 -0
  13. package/dist/chunk-A4532ZFR.js.map +1 -0
  14. package/dist/chunk-BHUT2S5G.js +22 -0
  15. package/dist/chunk-BHUT2S5G.js.map +1 -0
  16. package/dist/chunk-CCBLVAPK.js +42 -0
  17. package/dist/chunk-CCBLVAPK.js.map +1 -0
  18. package/dist/chunk-COKTX2G5.js +907 -0
  19. package/dist/chunk-COKTX2G5.js.map +1 -0
  20. package/dist/chunk-DYWFNC4A.js +152 -0
  21. package/dist/chunk-DYWFNC4A.js.map +1 -0
  22. package/dist/chunk-GQKN5KDT.js +159 -0
  23. package/dist/chunk-GQKN5KDT.js.map +1 -0
  24. package/dist/chunk-LN7ZZMD2.js +530 -0
  25. package/dist/chunk-LN7ZZMD2.js.map +1 -0
  26. package/dist/chunk-MSWFZF7J.js +118 -0
  27. package/dist/chunk-MSWFZF7J.js.map +1 -0
  28. package/dist/chunk-R3S2LUBH.js +2722 -0
  29. package/dist/chunk-R3S2LUBH.js.map +1 -0
  30. package/dist/chunk-SDM3VJJ5.js +41 -0
  31. package/dist/chunk-SDM3VJJ5.js.map +1 -0
  32. package/dist/chunk-XTC3X6MS.js +816 -0
  33. package/dist/chunk-XTC3X6MS.js.map +1 -0
  34. package/dist/chunk-ZXW5YIWK.js +55 -0
  35. package/dist/chunk-ZXW5YIWK.js.map +1 -0
  36. package/dist/core/index.cjs +432 -0
  37. package/dist/core/index.cjs.map +1 -0
  38. package/dist/core/index.d.cts +210 -0
  39. package/dist/core/index.d.ts +210 -0
  40. package/dist/core/index.js +73 -0
  41. package/dist/core/index.js.map +1 -0
  42. package/dist/function-2bJW1Zp_.d.ts +187 -0
  43. package/dist/function-r2sh-jOO.d.cts +187 -0
  44. package/dist/generate/index.cjs +3787 -0
  45. package/dist/generate/index.cjs.map +1 -0
  46. package/dist/generate/index.d.cts +980 -0
  47. package/dist/generate/index.d.ts +980 -0
  48. package/dist/generate/index.js +52 -0
  49. package/dist/generate/index.js.map +1 -0
  50. package/dist/index-BMPxwjwV.d.ts +151 -0
  51. package/dist/index-BOBXBNwP.d.cts +157 -0
  52. package/dist/index-BdeQ1r_p.d.cts +56 -0
  53. package/dist/index-BreoJRw0.d.ts +127 -0
  54. package/dist/index-CGMZNCx6.d.cts +140 -0
  55. package/dist/index-CGMZNCx6.d.ts +140 -0
  56. package/dist/index-CM5W4rcm.d.ts +157 -0
  57. package/dist/index-CP3wAfEH.d.ts +56 -0
  58. package/dist/index-Cl7mhOFM.d.cts +164 -0
  59. package/dist/index-Cl7mhOFM.d.ts +164 -0
  60. package/dist/index-DZ1M21do.d.cts +127 -0
  61. package/dist/index-D_ZTUNKp.d.cts +151 -0
  62. package/dist/index.cjs +3016 -2984
  63. package/dist/index.cjs.map +1 -1
  64. package/dist/index.d.cts +14 -3982
  65. package/dist/index.d.ts +14 -3982
  66. package/dist/index.js +170 -6504
  67. package/dist/index.js.map +1 -1
  68. package/dist/model/index.cjs +2435 -0
  69. package/dist/model/index.cjs.map +1 -0
  70. package/dist/model/index.d.cts +630 -0
  71. package/dist/model/index.d.ts +630 -0
  72. package/dist/model/index.js +21 -0
  73. package/dist/model/index.js.map +1 -0
  74. package/dist/styled-BjXtOFNk.d.cts +282 -0
  75. package/dist/styled-D7BAx3S3.d.ts +282 -0
  76. package/dist/theory/index.cjs +1677 -0
  77. package/dist/theory/index.cjs.map +1 -0
  78. package/dist/theory/index.d.cts +535 -0
  79. package/dist/theory/index.d.ts +535 -0
  80. package/dist/theory/index.js +149 -0
  81. package/dist/theory/index.js.map +1 -0
  82. package/dist/types-MGP29r3t.d.cts +30 -0
  83. package/dist/types-MGP29r3t.d.ts +30 -0
  84. package/package.json +27 -2
  85. package/src/analyze/arrange/index.ts +21 -0
  86. package/src/analyze/arrange/internal.ts +125 -0
  87. package/src/analyze/arrange/tension.ts +187 -0
  88. package/src/analyze/arrange/tracks.ts +279 -0
  89. package/src/{detect → analyze/detect}/index.ts +4 -4
  90. package/src/analyze/functional/borrowed.ts +84 -0
  91. package/src/analyze/functional/cadence.ts +66 -0
  92. package/src/analyze/functional/function.ts +184 -0
  93. package/src/analyze/functional/index.ts +23 -0
  94. package/src/analyze/functional/internal.ts +29 -0
  95. package/src/{functional/index.ts → analyze/functional/roman.ts} +9 -327
  96. package/src/analyze/index.ts +49 -0
  97. package/src/{timeline → analyze/timeline}/index.ts +7 -11
  98. package/src/{analysis → analyze/voice}/index.ts +8 -5
  99. package/src/core/index.ts +47 -0
  100. package/src/{bass → generate/bass}/index.ts +5 -5
  101. package/src/{countermelody → generate/countermelody}/index.ts +11 -11
  102. package/src/{drums → generate/drums}/index.ts +2 -2
  103. package/src/{drums → generate/drums}/rng.ts +2 -2
  104. package/src/{groove → generate/groove}/index.ts +3 -3
  105. package/src/{harmonize → generate/harmonize}/index.ts +13 -13
  106. package/src/generate/index.ts +59 -0
  107. package/src/{motif → generate/motif}/index.ts +7 -7
  108. package/src/{progression → generate/progression}/index.ts +11 -25
  109. package/src/{reharmony → generate/reharmony}/index.ts +11 -11
  110. package/src/{rhythm → generate/rhythm}/index.ts +2 -2
  111. package/src/index.ts +130 -117
  112. package/src/model/chord.ts +423 -0
  113. package/src/model/index.ts +5 -1096
  114. package/src/model/interval.ts +82 -0
  115. package/src/model/key.ts +266 -0
  116. package/src/model/note.ts +176 -0
  117. package/src/model/progression.ts +161 -0
  118. package/src/model/shared.ts +12 -0
  119. package/src/{chord → theory/chord}/index.ts +19 -1
  120. package/src/{counterpoint → theory/counterpoint}/index.ts +2 -2
  121. package/src/theory/index.ts +107 -0
  122. package/src/{safety → theory/safety}/index.ts +1 -1
  123. package/src/theory/scale/degrees.ts +123 -0
  124. package/src/theory/scale/index.ts +28 -0
  125. package/src/theory/scale/key.ts +56 -0
  126. package/src/theory/scale/masks.ts +153 -0
  127. package/src/{spelling → theory/spelling}/index.ts +3 -3
  128. package/src/{symbol → theory/symbol}/index.ts +8 -1
  129. package/src/theory/voicing/index.ts +5 -0
  130. package/src/theory/voicing/internal.ts +168 -0
  131. package/src/theory/voicing/leading.ts +112 -0
  132. package/src/theory/voicing/satb.ts +195 -0
  133. package/src/theory/voicing/styled.ts +176 -0
  134. package/src/arrange/index.ts +0 -571
  135. package/src/scale/index.ts +0 -331
  136. package/src/voicing/index.ts +0 -623
  137. /package/src/{interval → core/interval}/index.ts +0 -0
  138. /package/src/{meter → core/meter}/index.ts +0 -0
  139. /package/src/{pitch → core/pitch}/index.ts +0 -0
  140. /package/src/{random → core/random}/index.ts +0 -0
  141. /package/src/{tuning → core/tuning}/index.ts +0 -0
  142. /package/src/{types.ts → core/types.ts} +0 -0
  143. /package/src/{drums → generate/drums}/beat.ts +0 -0
  144. /package/src/{drums → generate/drums}/euclid.ts +0 -0
  145. /package/src/{drums → generate/drums}/fills.ts +0 -0
  146. /package/src/{drums → generate/drums}/ghost.ts +0 -0
  147. /package/src/{drums → generate/drums}/hihat.ts +0 -0
  148. /package/src/{drums → generate/drums}/hit.ts +0 -0
  149. /package/src/{drums → generate/drums}/internal.ts +0 -0
  150. /package/src/{drums → generate/drums}/kick.ts +0 -0
  151. /package/src/{drums → generate/drums}/percussion.ts +0 -0
  152. /package/src/{drums → generate/drums}/swing.ts +0 -0
  153. /package/src/{chordscale → theory/chordscale}/index.ts +0 -0
  154. /package/src/{harmony → theory/harmony}/index.ts +0 -0
@@ -8,1099 +8,8 @@
8
8
  * mutable data.
9
9
  */
10
10
 
11
- import {
12
- type Chord as ChordData,
13
- type ChordQuality,
14
- chordFromDegree,
15
- chordPitchClasses,
16
- diatonicSeventh,
17
- diatonicTriad,
18
- makeChord,
19
- } from '../chord/index.js';
20
- import {
21
- availableTensions,
22
- avoidNotes,
23
- type ChordScaleMatch,
24
- chordScales,
25
- } from '../chordscale/index.js';
26
- import { detectChord, detectChordBest } from '../detect/index.js';
27
- import {
28
- analyzeChord,
29
- type BorrowedSource,
30
- borrowedSource,
31
- type Cadence,
32
- type ChordAnalysis,
33
- chordToRoman,
34
- detectCadence,
35
- functionOf,
36
- type HarmonicFunction,
37
- isBorrowedChord,
38
- isMinorKey,
39
- romanToChord,
40
- } from '../functional/index.js';
41
- import {
42
- formatNote,
43
- midiToNote,
44
- type Note as NoteData,
45
- noteToMidi,
46
- noteToPitchClass,
47
- parseNote,
48
- type SpelledInterval,
49
- spelledInterval,
50
- } from '../pitch/index.js';
51
- import { negativeHarmonyMirror } from '../reharmony/index.js';
52
- import {
53
- isScaleTone,
54
- majorKey,
55
- minorKey,
56
- scaleByName,
57
- scaleTonesInDegreeOrder,
58
- } from '../scale/index.js';
59
- import { spellChord, spellScale } from '../spelling/index.js';
60
- import { formatChordSymbol, parseChordSymbol } from '../symbol/index.js';
61
- import type { KeyScale } from '../types.js';
62
- import {
63
- type StyledVoicingOptions,
64
- type VoicingOptions,
65
- voiceChord,
66
- voiceChordStyled,
67
- voiceProgression,
68
- } from '../voicing/index.js';
69
-
70
- /** Reduce any integer to a pitch class in [0, 11]. */
71
- function mod12(n: number): number {
72
- return ((n % 12) + 12) % 12;
73
- }
74
-
75
- /** Defensive copy of a plain note. */
76
- function copyNote(data: NoteData): NoteData {
77
- const copy: NoteData = { letter: data.letter, alter: data.alter };
78
- if (data.octave !== undefined) {
79
- copy.octave = data.octave;
80
- }
81
- return copy;
82
- }
83
-
84
- /**
85
- * Defensive copy of a plain chord.
86
- *
87
- * Any enharmonic spelling hints (`rootSpelling`/`bassSpelling`, populated by
88
- * `parseChordSymbol`) are carried through so a flat-named chord round-trips
89
- * through the class API; a hint that no longer matches its pitch class is
90
- * simply ignored by the formatter.
91
- */
92
- function copyChord(data: ChordData): ChordData {
93
- const copy: ChordData = {
94
- rootPc: data.rootPc,
95
- quality: data.quality,
96
- intervals: [...data.intervals],
97
- };
98
- if (data.bassPc !== undefined) {
99
- copy.bassPc = data.bassPc;
100
- }
101
- if (data.rootSpelling !== undefined) {
102
- copy.rootSpelling = { letter: data.rootSpelling.letter, alter: data.rootSpelling.alter };
103
- }
104
- if (data.bassSpelling !== undefined) {
105
- copy.bassSpelling = { letter: data.bassSpelling.letter, alter: data.bassSpelling.alter };
106
- }
107
- return copy;
108
- }
109
-
110
- /** Spell a bare pitch class as an octave-less note with a sharp/flat preference. */
111
- function spellPitchClassBare(pc: number, spelling: 'sharp' | 'flat'): NoteData {
112
- const spelled = midiToNote(60 + mod12(pc), spelling);
113
- return { letter: spelled.letter, alter: spelled.alter };
114
- }
115
-
116
- /**
117
- * An immutable spelled note: a diatonic letter plus a chromatic alteration and
118
- * an optional octave. Wraps the plain note object and delegates to the pitch
119
- * module; every transformation returns a new instance.
120
- *
121
- * @category Class API
122
- * @example
123
- * ```ts
124
- * import { Note } from '@libraz/libcantus';
125
- * Note.of('C4').transpose(7).name; // 'G4'
126
- * ```
127
- */
128
- export class Note {
129
- readonly #data: NoteData;
130
-
131
- /**
132
- * Wrap a plain note object.
133
- *
134
- * @param data The spelled note; it is copied, never retained or mutated.
135
- */
136
- constructor(data: NoteData) {
137
- this.#data = copyNote(data);
138
- }
139
-
140
- /**
141
- * Parse scientific pitch notation (e.g. `'C#4'`, `'Bb'`, `'F##3'`).
142
- *
143
- * @param name The note text.
144
- * @returns The parsed note.
145
- * @throws If the text is not a valid note.
146
- */
147
- static of(name: string): Note {
148
- return new Note(parseNote(name));
149
- }
150
-
151
- /**
152
- * Name a MIDI number (middle C = C4 = 60) as a note.
153
- *
154
- * @param midi The MIDI number.
155
- * @param spelling Whether to prefer sharps or flats for black keys.
156
- * @returns The spelled note, with octave.
157
- */
158
- static fromMidi(midi: number, spelling: 'sharp' | 'flat' = 'sharp'): Note {
159
- return new Note(midiToNote(midi, spelling));
160
- }
161
-
162
- /**
163
- * Wrap an existing plain note object.
164
- *
165
- * @param data The plain note.
166
- * @returns The wrapped note.
167
- */
168
- static fromData(data: NoteData): Note {
169
- return new Note(data);
170
- }
171
-
172
- /** The note rendered as scientific pitch notation, e.g. `'G4'` or `'Bb'`. */
173
- get name(): string {
174
- return formatNote(this.#data);
175
- }
176
-
177
- /** The pitch class (0..11), ignoring octave. */
178
- get pitchClass(): number {
179
- return noteToPitchClass(this.#data);
180
- }
181
-
182
- /**
183
- * The MIDI number (middle C = C4 = 60).
184
- *
185
- * @throws If the note has no octave and therefore no fixed pitch.
186
- */
187
- get midi(): number {
188
- if (this.#data.octave === undefined) {
189
- throw new Error(`note ${this.name} has no octave, so it has no MIDI number`);
190
- }
191
- return noteToMidi(this.#data);
192
- }
193
-
194
- /** The diatonic letter number: 0..6 for C..B. */
195
- get letter(): number {
196
- return this.#data.letter;
197
- }
198
-
199
- /** The chromatic alteration in semitones: -1 flat, 0 natural, +1 sharp, ... */
200
- get alter(): number {
201
- return this.#data.alter;
202
- }
203
-
204
- /** The octave (scientific pitch notation), or undefined for a bare pitch class. */
205
- get octave(): number | undefined {
206
- return this.#data.octave;
207
- }
208
-
209
- /** A copy of the underlying plain note object. */
210
- get data(): NoteData {
211
- return copyNote(this.#data);
212
- }
213
-
214
- /**
215
- * Transpose by a signed number of semitones.
216
- *
217
- * When the note carries an octave the transposition happens in MIDI space and
218
- * the result is spelled with a sharp preference. An octave-less note stays
219
- * octave-less: only its pitch class is moved. Transposing by zero is the
220
- * identity: the original spelling is preserved (no enharmonic respelling).
221
- *
222
- * @param semitones The signed semitone offset.
223
- * @returns The transposed note.
224
- */
225
- transpose(semitones: number): Note {
226
- if (semitones === 0) {
227
- return new Note(this.#data);
228
- }
229
- if (this.#data.octave !== undefined) {
230
- return Note.fromMidi(this.midi + semitones);
231
- }
232
- return new Note(spellPitchClassBare(this.pitchClass + semitones, 'sharp'));
233
- }
234
-
235
- /**
236
- * The spelled interval from this note to another.
237
- *
238
- * @param other The second note.
239
- * @returns The diatonic number, quality, and semitone span.
240
- */
241
- intervalTo(other: Note): SpelledInterval {
242
- return spelledInterval(this.#data, other.#data);
243
- }
244
-
245
- /**
246
- * Whether another note has the same letter, alteration, and octave.
247
- *
248
- * @param other The note to compare.
249
- * @returns True if the spellings are identical.
250
- */
251
- equals(other: Note): boolean {
252
- return (
253
- this.#data.letter === other.#data.letter &&
254
- this.#data.alter === other.#data.alter &&
255
- this.#data.octave === other.#data.octave
256
- );
257
- }
258
-
259
- /**
260
- * The plain note data, for JSON serialization.
261
- *
262
- * Private class fields do not serialize, so an explicit `toJSON` keeps
263
- * `JSON.stringify(note)` from collapsing to `{}`.
264
- *
265
- * @returns A copy of the underlying plain note object.
266
- */
267
- toJSON(): NoteData {
268
- return this.data;
269
- }
270
- }
271
-
272
- /**
273
- * An immutable spelled interval value: a diatonic number, a quality label, and
274
- * a signed semitone span. A thin convenience wrapper over the pitch module's
275
- * plain interval result.
276
- *
277
- * @category Class API
278
- * @example
279
- * ```ts
280
- * import { Interval, Note } from '@libraz/libcantus';
281
- * Interval.between(Note.of('C4'), Note.of('G4')).name; // 'P5'
282
- * ```
283
- */
284
- export class Interval {
285
- readonly #number: number;
286
- readonly #quality: string;
287
- readonly #semitones: number;
288
-
289
- private constructor(numberValue: number, quality: string, semitones: number) {
290
- this.#number = numberValue;
291
- this.#quality = quality;
292
- this.#semitones = semitones;
293
- }
294
-
295
- /**
296
- * The spelled interval between two notes.
297
- *
298
- * @param a The first note.
299
- * @param b The second note.
300
- * @returns The interval from `a` to `b`.
301
- */
302
- static between(a: Note, b: Note): Interval {
303
- const spelled = a.intervalTo(b);
304
- return new Interval(spelled.number, spelled.quality, spelled.semitones);
305
- }
306
-
307
- /**
308
- * Build an interval from explicit components.
309
- *
310
- * @param numberValue Diatonic size: 1 = unison, 2 = second, ... 8 = octave.
311
- * @param quality Quality label: `'P'`, `'M'`, `'m'`, or repeated `'A'`/`'d'`.
312
- * @param semitones Signed semitone span.
313
- * @returns The interval.
314
- */
315
- static of(numberValue: number, quality: string, semitones: number): Interval {
316
- return new Interval(numberValue, quality, semitones);
317
- }
318
-
319
- /** Diatonic size: 1 = unison, 2 = second, ... 8 = octave, and beyond. */
320
- get number(): number {
321
- return this.#number;
322
- }
323
-
324
- /** Quality label: `'P'`, `'M'`, `'m'`, or repeated `'A'`/`'d'`. */
325
- get quality(): string {
326
- return this.#quality;
327
- }
328
-
329
- /** Signed semitone span. */
330
- get semitones(): number {
331
- return this.#semitones;
332
- }
333
-
334
- /** A readable label composed of quality and number, e.g. `'P5'` or `'M3'`. */
335
- get name(): string {
336
- return `${this.#quality}${this.#number}`;
337
- }
338
-
339
- /**
340
- * The plain interval data, for JSON serialization.
341
- *
342
- * Private class fields do not serialize, so an explicit `toJSON` keeps
343
- * `JSON.stringify(interval)` from collapsing to `{}`.
344
- *
345
- * @returns The diatonic number, quality, and semitone span.
346
- */
347
- toJSON(): SpelledInterval {
348
- return { number: this.#number, quality: this.#quality, semitones: this.#semitones };
349
- }
350
- }
351
-
352
- /** Resolve a string or numeric key root into a spelled tonic note. */
353
- function resolveTonic(root: string | number, spelling: 'sharp' | 'flat'): Note {
354
- return typeof root === 'string' ? Note.of(root) : new Note(spellPitchClassBare(root, spelling));
355
- }
356
-
357
- /** Total accidentals a spelled tonic produces across a key's whole scale. */
358
- function accidentalLoad(tonic: NoteData, scale: KeyScale): number {
359
- return spellScale(tonic, scale).reduce((sum, note) => sum + Math.abs(note.alter), 0);
360
- }
361
-
362
- /**
363
- * Choose the tonic spelling (sharp- or flat-side) that spells `scale` with the
364
- * fewest accidentals, so a numeric root never yields a double-flat/double-sharp
365
- * scale (e.g. pitch class 6 minor spells as F# minor, not Gb minor with Bbb).
366
- */
367
- function bestTonicForScale(rootPc: number, scale: KeyScale): Note {
368
- const sharp = spellPitchClassBare(rootPc, 'sharp');
369
- const flat = spellPitchClassBare(rootPc, 'flat');
370
- if (sharp.letter === flat.letter && sharp.alter === flat.alter) {
371
- return new Note(sharp);
372
- }
373
- return accidentalLoad(flat, scale) <= accidentalLoad(sharp, scale)
374
- ? new Note(flat)
375
- : new Note(sharp);
376
- }
377
-
378
- /**
379
- * An immutable key/scale: a `KeyScale` (root pitch class plus mode mask) paired
380
- * with a spelled tonic that anchors letter-name spelling. Acts as the factory
381
- * for key-aware chords.
382
- *
383
- * @category Class API
384
- * @example
385
- * ```ts
386
- * import { Key } from '@libraz/libcantus';
387
- * Key.major('C').chord(4).symbol(); // 'G' (the diatonic triad on scale degree 4)
388
- * ```
389
- */
390
- export class Key {
391
- readonly #scale: KeyScale;
392
- readonly #tonic: Note;
393
-
394
- /**
395
- * Wrap a key/scale and its spelled tonic.
396
- *
397
- * @param scale The key/scale; its root is normalized to a pitch class.
398
- * @param tonic The spelled tonic anchoring letter-name spelling.
399
- */
400
- constructor(scale: KeyScale, tonic: Note) {
401
- this.#scale = { rootPc: mod12(scale.rootPc), modeMask12: scale.modeMask12 };
402
- this.#tonic = tonic;
403
- }
404
-
405
- /**
406
- * A major key.
407
- *
408
- * @param root Tonic as a note name (e.g. `'Eb'`) or a pitch class; a numeric
409
- * root is spelled with whichever accidental side yields the fewest
410
- * accidentals across the scale.
411
- * @returns The major key.
412
- */
413
- static major(root: string | number): Key {
414
- if (typeof root === 'string') {
415
- const tonic = Note.of(root);
416
- return new Key(majorKey(tonic.pitchClass), tonic);
417
- }
418
- const scale = majorKey(root);
419
- return new Key(scale, bestTonicForScale(root, scale));
420
- }
421
-
422
- /**
423
- * A natural-minor key.
424
- *
425
- * @param root Tonic as a note name or a pitch class; a numeric root is
426
- * spelled with whichever accidental side yields the fewest accidentals
427
- * across the scale.
428
- * @returns The minor key.
429
- */
430
- static minor(root: string | number): Key {
431
- if (typeof root === 'string') {
432
- const tonic = Note.of(root);
433
- return new Key(minorKey(tonic.pitchClass), tonic);
434
- }
435
- const scale = minorKey(root);
436
- return new Key(scale, bestTonicForScale(root, scale));
437
- }
438
-
439
- /**
440
- * A key on a named scale (e.g. `'dorian'`, `'harmonicMinor'`).
441
- *
442
- * @param name The scale name, a key of the scale module's named-scale table.
443
- * @param root Tonic as a note name or a pitch class.
444
- * @returns The key.
445
- * @throws If the name is not a known scale.
446
- */
447
- static named(name: string, root: string | number): Key {
448
- const tonic = resolveTonic(root, 'sharp');
449
- return new Key(scaleByName(name, tonic.pitchClass), tonic);
450
- }
451
-
452
- /**
453
- * Wrap an existing `KeyScale`, synthesizing a spelled tonic when none is
454
- * given (flat-preferred for minor-third scales, sharp-preferred otherwise).
455
- *
456
- * @param scale The key/scale to wrap.
457
- * @param tonic Optional spelled tonic.
458
- * @returns The key.
459
- */
460
- static of(scale: KeyScale, tonic?: Note): Key {
461
- const spelled =
462
- tonic ?? new Note(spellPitchClassBare(scale.rootPc, isMinorKey(scale) ? 'flat' : 'sharp'));
463
- return new Key(scale, spelled);
464
- }
465
-
466
- /** A copy of the underlying plain `KeyScale`. */
467
- get scale(): KeyScale {
468
- return { rootPc: this.#scale.rootPc, modeMask12: this.#scale.modeMask12 };
469
- }
470
-
471
- /** The spelled tonic. */
472
- get tonic(): Note {
473
- return this.#tonic;
474
- }
475
-
476
- /** The tonic pitch class (0..11). */
477
- get rootPc(): number {
478
- return this.#scale.rootPc;
479
- }
480
-
481
- /** Whether the scale has a minor third and no major third. */
482
- get isMinor(): boolean {
483
- return isMinorKey(this.#scale);
484
- }
485
-
486
- /**
487
- * The scale's pitch classes in ascending scale-degree order (degree 0 first).
488
- *
489
- * @returns One pitch class per scale degree.
490
- */
491
- pitchClasses(): number[] {
492
- return scaleTonesInDegreeOrder(this.#scale);
493
- }
494
-
495
- /**
496
- * The spelled scale, one note per degree (e.g. C D E F G A B for C major).
497
- *
498
- * @returns Spelled octave-less notes in scale-degree order.
499
- */
500
- notes(): Note[] {
501
- return spellScale(this.#tonic.data, this.#scale).map((note) => new Note(note));
502
- }
503
-
504
- /**
505
- * Alias of {@link Key.notes}.
506
- *
507
- * @returns Spelled octave-less notes in scale-degree order.
508
- */
509
- spell(): Note[] {
510
- return this.notes();
511
- }
512
-
513
- /**
514
- * The spelled scale as letter-name strings.
515
- *
516
- * @returns One name per scale degree.
517
- */
518
- noteNames(): string[] {
519
- return this.notes().map((note) => note.name);
520
- }
521
-
522
- /**
523
- * Build a chord on a scale degree, carrying this key as context.
524
- *
525
- * With an explicit quality the quality's interval template is attached to the
526
- * degree's diatonic root; without one the scale-correct diatonic triad is
527
- * stacked (e.g. a diminished triad on the leading tone of a major key).
528
- *
529
- * @param degree 0-based scale degree of the chord root.
530
- * @param quality Optional chord quality.
531
- * @returns The chord, with this key attached.
532
- */
533
- chord(degree: number, quality?: ChordQuality): Chord {
534
- const data =
535
- quality === undefined
536
- ? diatonicTriad(degree, this.#scale)
537
- : chordFromDegree(degree, quality, this.#scale);
538
- return new Chord(data, this);
539
- }
540
-
541
- /**
542
- * The diatonic triad on a scale degree, carrying this key as context.
543
- *
544
- * @param degree 0-based scale degree of the chord root.
545
- * @returns The triad, with this key attached.
546
- */
547
- diatonicTriad(degree: number): Chord {
548
- return new Chord(diatonicTriad(degree, this.#scale), this);
549
- }
550
-
551
- /**
552
- * The diatonic seventh chord on a scale degree, carrying this key as context.
553
- *
554
- * @param degree 0-based scale degree of the chord root.
555
- * @returns The seventh chord, with this key attached.
556
- */
557
- diatonicSeventh(degree: number): Chord {
558
- return new Chord(diatonicSeventh(degree, this.#scale), this);
559
- }
560
-
561
- /**
562
- * Build the chord denoted by a Roman numeral in this key (including applied
563
- * chords such as `'V7/V'`), carrying this key as context.
564
- *
565
- * @param text The Roman numeral.
566
- * @returns The chord, with this key attached.
567
- * @throws If the numeral is not valid.
568
- */
569
- roman(text: string): Chord {
570
- return new Chord(romanToChord(text, this.#scale), this);
571
- }
572
-
573
- /**
574
- * Whether a pitch belongs to the scale.
575
- *
576
- * @param x A MIDI pitch, bare pitch class, or note.
577
- * @returns True if the pitch class is a scale tone.
578
- */
579
- contains(x: number | Note): boolean {
580
- return isScaleTone(typeof x === 'number' ? x : x.pitchClass, this.#scale);
581
- }
582
-
583
- /**
584
- * The plain key data, for JSON serialization.
585
- *
586
- * Private class fields do not serialize, so an explicit `toJSON` keeps
587
- * `JSON.stringify(key)` from collapsing to `{}`. The result pairs the
588
- * `KeyScale` with the spelled tonic, enough to reconstruct the key via
589
- * {@link Key.of}.
590
- *
591
- * @returns The key/scale and its spelled tonic.
592
- */
593
- toJSON(): { scale: KeyScale; tonic: NoteData } {
594
- return { scale: this.scale, tonic: this.#tonic.data };
595
- }
596
- }
597
-
598
- /**
599
- * An immutable chord: a root pitch class, quality, interval template, and
600
- * optional slash bass, optionally carrying a {@link Key} context. Analysis
601
- * methods (`roman`, `function`, `analyze`, ...) use an explicitly passed key
602
- * first and fall back to the carried context.
603
- *
604
- * @category Class API
605
- * @example
606
- * ```ts
607
- * import { Chord } from '@libraz/libcantus';
608
- * Chord.parse('Cmaj7').invert(1).symbol(); // 'Cmaj7/E' (third in the bass)
609
- * ```
610
- */
611
- export class Chord {
612
- readonly #data: ChordData;
613
- readonly #key: Key | undefined;
614
-
615
- /**
616
- * Wrap a plain chord object.
617
- *
618
- * @param data The chord; it is copied, never retained or mutated.
619
- * @param key Optional key context for analysis methods.
620
- */
621
- constructor(data: ChordData, key?: Key) {
622
- this.#data = copyChord(data);
623
- this.#key = key;
624
- }
625
-
626
- /**
627
- * Build a chord from a root and quality.
628
- *
629
- * @param root Root as a note name (e.g. `'Eb'`) or a pitch class.
630
- * @param quality The chord quality.
631
- * @param bass Optional slash-chord bass pitch class.
632
- * @returns The chord (without key context).
633
- */
634
- static of(root: string | number, quality: ChordQuality, bass?: number): Chord {
635
- const rootPc = typeof root === 'string' ? Note.of(root).pitchClass : root;
636
- return new Chord(makeChord(rootPc, quality, bass));
637
- }
638
-
639
- /**
640
- * Wrap an existing plain chord object.
641
- *
642
- * @param data The plain chord.
643
- * @returns The wrapped chord (without key context).
644
- */
645
- static from(data: ChordData): Chord {
646
- return new Chord(data);
647
- }
648
-
649
- /**
650
- * Parse a lead-sheet chord symbol (e.g. `'Cmaj7'`, `'F#m7b5'`, `'C/G'`).
651
- *
652
- * @param symbol The chord symbol.
653
- * @returns The chord (without key context).
654
- * @throws If the root or quality is not recognized.
655
- */
656
- static parse(symbol: string): Chord {
657
- return new Chord(parseChordSymbol(symbol));
658
- }
659
-
660
- /**
661
- * Identify the chords matching a set of pitches, best interpretation first.
662
- *
663
- * @param pitches MIDI pitches or bare pitch classes.
664
- * @returns Ranked chord interpretations (may be empty).
665
- */
666
- static detect(pitches: number[]): Chord[] {
667
- return detectChord(pitches).map(
668
- (match) => new Chord(makeChord(match.rootPc, match.quality, match.bassPc)),
669
- );
670
- }
671
-
672
- /**
673
- * The single best chord interpretation of a pitch set.
674
- *
675
- * @param pitches MIDI pitches or bare pitch classes.
676
- * @returns The top-ranked chord, or null when nothing matches.
677
- */
678
- static detectBest(pitches: number[]): Chord | null {
679
- const best = detectChordBest(pitches);
680
- return best === null ? null : new Chord(best);
681
- }
682
-
683
- /** The root pitch class (0..11). */
684
- get rootPc(): number {
685
- return this.#data.rootPc;
686
- }
687
-
688
- /** The chord quality. */
689
- get quality(): ChordQuality {
690
- return this.#data.quality;
691
- }
692
-
693
- /** A copy of the semitone offsets above the root. */
694
- get intervals(): number[] {
695
- return [...this.#data.intervals];
696
- }
697
-
698
- /** The slash-chord bass pitch class, or undefined in root position. */
699
- get bassPc(): number | undefined {
700
- return this.#data.bassPc;
701
- }
702
-
703
- /** A copy of the underlying plain chord object. */
704
- get data(): ChordData {
705
- return copyChord(this.#data);
706
- }
707
-
708
- /** The carried key context, if any. */
709
- get key(): Key | undefined {
710
- return this.#key;
711
- }
712
-
713
- /**
714
- * A copy of this chord carrying the given key context.
715
- *
716
- * @param key The key context to attach.
717
- * @returns The new chord.
718
- */
719
- withKey(key: Key): Chord {
720
- return new Chord(this.#data, key);
721
- }
722
-
723
- /**
724
- * The chord's sorted, deduplicated pitch classes.
725
- *
726
- * @returns Pitch classes ascending in [0, 11].
727
- */
728
- pitchClasses(): number[] {
729
- return chordPitchClasses(this.#data);
730
- }
731
-
732
- /**
733
- * The chord's Roman numeral in a key.
734
- *
735
- * @param key Key to analyze in; falls back to the carried context.
736
- * @returns The Roman numeral string.
737
- * @throws If no key is given and none is carried.
738
- */
739
- roman(key?: Key): string {
740
- return chordToRoman(this.#data, this.#resolveKey(key).scale);
741
- }
742
-
743
- /**
744
- * The chord's harmonic function (tonic / subdominant / dominant) in a key.
745
- *
746
- * @param key Key to analyze in; falls back to the carried context.
747
- * @returns The harmonic function.
748
- * @throws If no key is given and none is carried.
749
- */
750
- function(key?: Key): HarmonicFunction {
751
- return functionOf(this.#data, this.#resolveKey(key).scale);
752
- }
753
-
754
- /**
755
- * Full functional analysis: function, borrowing, and Roman numeral.
756
- *
757
- * @param key Key to analyze in; falls back to the carried context.
758
- * @returns The chord analysis.
759
- * @throws If no key is given and none is carried.
760
- */
761
- analyze(key?: Key): ChordAnalysis {
762
- return analyzeChord(this.#data, this.#resolveKey(key).scale);
763
- }
764
-
765
- /**
766
- * Whether the chord is borrowed from the parallel mode (modal interchange).
767
- *
768
- * @param key Key to analyze in; falls back to the carried context.
769
- * @returns True if the chord is borrowed.
770
- * @throws If no key is given and none is carried.
771
- */
772
- isBorrowed(key?: Key): boolean {
773
- return isBorrowedChord(this.#data, this.#resolveKey(key).scale);
774
- }
775
-
776
- /**
777
- * The origin of a non-diatonic chord (parallel mode or Neapolitan), or null.
778
- *
779
- * @param key Key to analyze in; falls back to the carried context.
780
- * @returns The borrowing source, or null.
781
- * @throws If no key is given and none is carried.
782
- */
783
- borrowedSource(key?: Key): BorrowedSource {
784
- return borrowedSource(this.#data, this.#resolveKey(key).scale);
785
- }
786
-
787
- /**
788
- * The chord rendered as a lead-sheet symbol (e.g. `'Cmaj7'`, `'F#m7'`, `'C/G'`).
789
- *
790
- * @param opts Set `flats: true` to spell the root/bass with flats.
791
- * @returns The chord symbol.
792
- */
793
- symbol(opts?: { flats?: boolean }): string {
794
- return formatChordSymbol(this.#data, opts);
795
- }
796
-
797
- /**
798
- * Realize the chord as one MIDI pitch per voice, ascending.
799
- *
800
- * @param opts Voicing options; defaults to four SATB voices.
801
- * @returns MIDI pitches, ascending, one per voice.
802
- * @throws If no voicing fits the given ranges.
803
- */
804
- voice(opts?: VoicingOptions): number[] {
805
- return voiceChord(this.#data, opts);
806
- }
807
-
808
- /**
809
- * Realize the chord as a single styled voicing (`close`, `drop2`, `drop3`,
810
- * `shell`, or `rootless`), optionally constraining the top voice.
811
- *
812
- * @param opts Styled-voicing options; defaults to a close-position voicing.
813
- * @returns MIDI pitches, ascending.
814
- */
815
- styledVoicing(opts?: StyledVoicingOptions): number[] {
816
- return voiceChordStyled(this.#data, opts);
817
- }
818
-
819
- /**
820
- * The negative-harmony mirror of the chord about the key's tonic–dominant
821
- * axis (major becomes minor and vice versa).
822
- *
823
- * @param key Key providing the reflection axis; falls back to the carried
824
- * context.
825
- * @returns The mirrored chord, keeping any key context.
826
- * @throws If no key is given and none is carried.
827
- */
828
- negativeHarmony(key?: Key): Chord {
829
- const resolved = this.#resolveKey(key);
830
- // Retain the key that anchored the reflection (explicit first, then carried)
831
- // so a later no-arg analysis method still has a key context.
832
- return new Chord(negativeHarmonyMirror(this.#data, resolved.scale), key ?? this.#key);
833
- }
834
-
835
- /**
836
- * The n-th inversion: a copy whose bass is the chord tone `n` steps above the
837
- * root in the interval template (`invert(1)` puts the third in the bass).
838
- * `n` wraps around the template length; negative values count backwards.
839
- *
840
- * `invert(0)` (and any `n` that wraps to it) is root position, so it carries
841
- * no slash bass and equals the original chord.
842
- *
843
- * @param n The inversion number.
844
- * @returns The inverted chord, keeping any key context.
845
- * @throws If the chord has no intervals.
846
- */
847
- invert(n: number): Chord {
848
- const intervals = this.#data.intervals;
849
- const length = intervals.length;
850
- if (length === 0) {
851
- throw new Error('cannot invert a chord with no intervals');
852
- }
853
- const index = ((n % length) + length) % length;
854
- const data = copyChord(this.#data);
855
- if (index === 0) {
856
- delete data.bassPc;
857
- } else {
858
- data.bassPc = mod12(this.#data.rootPc + (intervals[index] ?? 0));
859
- }
860
- return new Chord(data, this.#key);
861
- }
862
-
863
- /**
864
- * The named scales that fit over this chord, best fit first, rooted on the
865
- * chord root.
866
- *
867
- * @returns The matching scales.
868
- */
869
- scales(): ChordScaleMatch[] {
870
- return chordScales(this.#data);
871
- }
872
-
873
- /**
874
- * The available tensions (usable non-chord, non-avoid scale tones) of a
875
- * scale over this chord.
876
- *
877
- * @param scaleName A named scale, rooted on the chord root.
878
- * @returns Tension pitch classes, ascending in [0, 11].
879
- */
880
- tensions(scaleName: string): number[] {
881
- return availableTensions(this.#data, scaleName);
882
- }
883
-
884
- /**
885
- * The avoid notes (scale tones a semitone above a chord tone) of a scale
886
- * over this chord.
887
- *
888
- * @param scaleName A named scale, rooted on the chord root.
889
- * @returns Avoid-note pitch classes, ascending in [0, 11].
890
- */
891
- avoidNotes(scaleName: string): number[] {
892
- return avoidNotes(this.#data, scaleName);
893
- }
894
-
895
- /**
896
- * Spell the chord tones with letter names, root first, in the key's spelling.
897
- *
898
- * @param key Key providing the spelled tonic; falls back to the carried
899
- * context.
900
- * @returns Spelled octave-less notes in the chord's own (tertian) order.
901
- * @throws If no key is given and none is carried.
902
- */
903
- spell(key?: Key): Note[] {
904
- const resolved = this.#resolveKey(key);
905
- return spellChord(this.#data, resolved.tonic.data, resolved.scale).map(
906
- (note) => new Note(note),
907
- );
908
- }
909
-
910
- /**
911
- * Start a progression with this chord followed by others, carrying this
912
- * chord's key context (if any).
913
- *
914
- * @param others The chords following this one.
915
- * @returns The progression.
916
- */
917
- progressionTo(...others: Chord[]): Progression {
918
- return new Progression([this, ...others], this.#key);
919
- }
920
-
921
- /**
922
- * Whether another chord has the same root, quality, intervals, and bass.
923
- * Key context is not compared.
924
- *
925
- * @param other The chord to compare.
926
- * @returns True if the chord data is identical.
927
- */
928
- equals(other: Chord): boolean {
929
- const a = this.#data;
930
- const b = other.#data;
931
- return (
932
- a.rootPc === b.rootPc &&
933
- a.quality === b.quality &&
934
- a.bassPc === b.bassPc &&
935
- a.intervals.length === b.intervals.length &&
936
- a.intervals.every((interval, i) => interval === b.intervals[i])
937
- );
938
- }
939
-
940
- /**
941
- * The plain chord data, for JSON serialization.
942
- *
943
- * @returns A copy of the underlying plain chord object.
944
- */
945
- toJSON(): ChordData {
946
- return this.data;
947
- }
948
-
949
- /** Resolve the key for an analysis method: explicit first, then carried. */
950
- #resolveKey(key?: Key): Key {
951
- const resolved = key ?? this.#key;
952
- if (resolved === undefined) {
953
- throw new Error('chord has no key context; pass a Key or attach one with withKey()');
954
- }
955
- return resolved;
956
- }
957
- }
958
-
959
- /**
960
- * An immutable ordered sequence of chords, optionally carrying a {@link Key}
961
- * context shared by its analysis methods.
962
- *
963
- * @category Class API
964
- * @example
965
- * ```ts
966
- * import { Key } from '@libraz/libcantus';
967
- * const key = Key.major('C');
968
- * key.chord(1).progressionTo(key.chord(4), key.chord(0)).roman();
969
- * // ['ii', 'V', 'I']
970
- * ```
971
- */
972
- export class Progression {
973
- readonly #chords: readonly Chord[];
974
- readonly #key: Key | undefined;
975
-
976
- /**
977
- * Wrap a chord sequence.
978
- *
979
- * @param chords The chords in order; the array is copied.
980
- * @param key Optional key context for analysis methods.
981
- */
982
- constructor(chords: readonly Chord[], key?: Key) {
983
- this.#chords = [...chords];
984
- this.#key = key;
985
- }
986
-
987
- /** A copy of the chord sequence. */
988
- get chords(): readonly Chord[] {
989
- return [...this.#chords];
990
- }
991
-
992
- /** The carried key context, if any. */
993
- get key(): Key | undefined {
994
- return this.#key;
995
- }
996
-
997
- /** The number of chords. */
998
- get length(): number {
999
- return this.#chords.length;
1000
- }
1001
-
1002
- /**
1003
- * A copy of this progression with a chord appended.
1004
- *
1005
- * @param chord The chord to append.
1006
- * @returns The new progression.
1007
- */
1008
- add(chord: Chord): Progression {
1009
- return new Progression([...this.#chords, chord], this.#key);
1010
- }
1011
-
1012
- /**
1013
- * A copy of this progression carrying the given key context.
1014
- *
1015
- * @param key The key context to attach.
1016
- * @returns The new progression.
1017
- */
1018
- withKey(key: Key): Progression {
1019
- return new Progression(this.#chords, key);
1020
- }
1021
-
1022
- /**
1023
- * Voice the progression with smooth voice leading.
1024
- *
1025
- * @param opts Voicing options; defaults to four SATB voices.
1026
- * @returns One ascending voicing (MIDI pitches) per chord.
1027
- * @throws If any chord admits no voicing within the given ranges.
1028
- */
1029
- voice(opts?: VoicingOptions): number[][] {
1030
- return voiceProgression(
1031
- this.#chords.map((chord) => chord.data),
1032
- opts,
1033
- );
1034
- }
1035
-
1036
- /**
1037
- * The Roman numeral of each chord in a key.
1038
- *
1039
- * @param key Key to analyze in; falls back to the carried context.
1040
- * @returns One numeral per chord.
1041
- * @throws If no key is given and none is carried.
1042
- */
1043
- roman(key?: Key): string[] {
1044
- const resolved = this.#resolveKey(key);
1045
- return this.#chords.map((chord) => chord.roman(resolved));
1046
- }
1047
-
1048
- /**
1049
- * The harmonic function of each chord in a key.
1050
- *
1051
- * @param key Key to analyze in; falls back to the carried context.
1052
- * @returns One function per chord.
1053
- * @throws If no key is given and none is carried.
1054
- */
1055
- functions(key?: Key): HarmonicFunction[] {
1056
- const resolved = this.#resolveKey(key);
1057
- return this.#chords.map((chord) => chord.function(resolved));
1058
- }
1059
-
1060
- /**
1061
- * Analyze every chord and classify the closing cadence.
1062
- *
1063
- * The cadence is detected on the final chord pair and is null when the
1064
- * progression has fewer than two chords.
1065
- *
1066
- * @param key Key to analyze in; falls back to the carried context.
1067
- * @returns Per-chord analyses and the closing cadence.
1068
- * @throws If no key is given and none is carried.
1069
- */
1070
- analyze(key?: Key): { chords: ChordAnalysis[]; cadence: Cadence } {
1071
- const resolved = this.#resolveKey(key);
1072
- const chords = this.#chords.map((chord) => chord.analyze(resolved));
1073
- const from = this.#chords[this.#chords.length - 2];
1074
- const to = this.#chords[this.#chords.length - 1];
1075
- const cadence =
1076
- from !== undefined && to !== undefined
1077
- ? detectCadence(from.data, to.data, resolved.scale)
1078
- : null;
1079
- return { chords, cadence };
1080
- }
1081
-
1082
- /**
1083
- * The plain progression data, for JSON serialization.
1084
- *
1085
- * Private class fields do not serialize, so an explicit `toJSON` keeps
1086
- * `JSON.stringify(progression)` from collapsing to `{}`. The chords are
1087
- * emitted as plain data and the carried key, when present, as its own data.
1088
- *
1089
- * @returns The chord data sequence and the carried key, if any.
1090
- */
1091
- toJSON(): { chords: ChordData[]; key: { scale: KeyScale; tonic: NoteData } | undefined } {
1092
- return {
1093
- chords: this.#chords.map((chord) => chord.data),
1094
- key: this.#key?.toJSON(),
1095
- };
1096
- }
1097
-
1098
- /** Resolve the key for an analysis method: explicit first, then carried. */
1099
- #resolveKey(key?: Key): Key {
1100
- const resolved = key ?? this.#key;
1101
- if (resolved === undefined) {
1102
- throw new Error('progression has no key context; pass a Key or attach one with withKey()');
1103
- }
1104
- return resolved;
1105
- }
1106
- }
11
+ export { Chord } from './chord.js';
12
+ export { Interval } from './interval.js';
13
+ export { Key } from './key.js';
14
+ export { Note } from './note.js';
15
+ export { Progression } from './progression.js';