@libraz/libcantus 0.9.3 → 0.9.4

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 (198) hide show
  1. package/README.md +2 -2
  2. package/dist/analyze/index.cjs +39 -1947
  3. package/dist/analyze/index.cjs.map +1 -1
  4. package/dist/analyze/index.d.cts +197 -37
  5. package/dist/analyze/index.d.ts +197 -37
  6. package/dist/analyze/index.js +19 -8
  7. package/dist/chunk-36N73KZ3.cjs +246 -0
  8. package/dist/chunk-36N73KZ3.cjs.map +1 -0
  9. package/dist/chunk-4HLLZPXT.cjs +3077 -0
  10. package/dist/chunk-4HLLZPXT.cjs.map +1 -0
  11. package/dist/chunk-7MGZ7D62.cjs +498 -0
  12. package/dist/chunk-7MGZ7D62.cjs.map +1 -0
  13. package/dist/{chunk-4MHA432G.js → chunk-7NKDPF74.js} +403 -180
  14. package/dist/chunk-7NKDPF74.js.map +1 -0
  15. package/dist/chunk-CAN76NCU.cjs +679 -0
  16. package/dist/chunk-CAN76NCU.cjs.map +1 -0
  17. package/dist/{chunk-MIWO425M.js → chunk-D2FAJBYL.js} +101 -34
  18. package/dist/chunk-D2FAJBYL.js.map +1 -0
  19. package/dist/{chunk-SGU7SPLK.js → chunk-EHVEBWM5.js} +1056 -531
  20. package/dist/chunk-EHVEBWM5.js.map +1 -0
  21. package/dist/chunk-FCANXBAT.cjs +30 -0
  22. package/dist/chunk-FCANXBAT.cjs.map +1 -0
  23. package/dist/chunk-FNDWXRRI.cjs +479 -0
  24. package/dist/chunk-FNDWXRRI.cjs.map +1 -0
  25. package/dist/{chunk-IT2O4XFE.js → chunk-GQSGS2N4.js} +43 -24
  26. package/dist/chunk-GQSGS2N4.js.map +1 -0
  27. package/dist/{chunk-62QZKCJQ.js → chunk-HKGYCQ34.js} +10 -6
  28. package/dist/chunk-HKGYCQ34.js.map +1 -0
  29. package/dist/{chunk-AKLYPWIN.js → chunk-I24MV65U.js} +29 -6
  30. package/dist/chunk-I24MV65U.js.map +1 -0
  31. package/dist/{chunk-CHMXELDS.js → chunk-KMHOICIY.js} +311 -181
  32. package/dist/chunk-KMHOICIY.js.map +1 -0
  33. package/dist/chunk-LW53AHQU.cjs +1117 -0
  34. package/dist/chunk-LW53AHQU.cjs.map +1 -0
  35. package/dist/{chunk-2ZWMSJH6.js → chunk-NKIBQ6PT.js} +2 -2
  36. package/dist/chunk-NKIBQ6PT.js.map +1 -0
  37. package/dist/chunk-NP4NA2FB.cjs +106 -0
  38. package/dist/chunk-NP4NA2FB.cjs.map +1 -0
  39. package/dist/chunk-NVE34YGZ.cjs +1449 -0
  40. package/dist/chunk-NVE34YGZ.cjs.map +1 -0
  41. package/dist/{chunk-EH6EM37U.js → chunk-NYYWMV2C.js} +61 -49
  42. package/dist/chunk-NYYWMV2C.js.map +1 -0
  43. package/dist/{chunk-GOAW4VYL.js → chunk-Q2XUP227.js} +243 -117
  44. package/dist/chunk-Q2XUP227.js.map +1 -0
  45. package/dist/chunk-Q6OP4U43.cjs +327 -0
  46. package/dist/chunk-Q6OP4U43.cjs.map +1 -0
  47. package/dist/chunk-RC6GBMCD.cjs +845 -0
  48. package/dist/chunk-RC6GBMCD.cjs.map +1 -0
  49. package/dist/{chunk-C5XYKUVG.js → chunk-RK35RIN7.js} +370 -157
  50. package/dist/chunk-RK35RIN7.js.map +1 -0
  51. package/dist/chunk-RUMU3UA6.cjs +53 -0
  52. package/dist/chunk-RUMU3UA6.cjs.map +1 -0
  53. package/dist/chunk-T64C7ZD7.cjs +1 -0
  54. package/dist/chunk-T64C7ZD7.cjs.map +1 -0
  55. package/dist/chunk-XEBG3G53.js +498 -0
  56. package/dist/chunk-XEBG3G53.js.map +1 -0
  57. package/dist/{chunk-I5R7ZBJS.js → chunk-YLEMGEFH.js} +103 -59
  58. package/dist/chunk-YLEMGEFH.js.map +1 -0
  59. package/dist/chunk-ZEJR4TKL.cjs +173 -0
  60. package/dist/chunk-ZEJR4TKL.cjs.map +1 -0
  61. package/dist/core/index.cjs +130 -647
  62. package/dist/core/index.cjs.map +1 -1
  63. package/dist/core/index.d.cts +301 -39
  64. package/dist/core/index.d.ts +301 -39
  65. package/dist/core/index.js +54 -16
  66. package/dist/{function-DYt4iKsn.d.cts → function-BtiZb9i9.d.ts} +28 -7
  67. package/dist/{function-DVH4Eusr.d.ts → function-DNugAOrt.d.cts} +28 -7
  68. package/dist/generate/index.cjs +28 -4085
  69. package/dist/generate/index.cjs.map +1 -1
  70. package/dist/generate/index.d.cts +370 -62
  71. package/dist/generate/index.d.ts +370 -62
  72. package/dist/generate/index.js +23 -9
  73. package/dist/{index-CxqBQtH1.d.cts → index-6VR8-kit.d.ts} +19 -4
  74. package/dist/index-70p168VM.d.ts +192 -0
  75. package/dist/{index-CpOsP1y9.d.cts → index-Be74mcon.d.cts} +18 -17
  76. package/dist/index-BtXT6UQ0.d.cts +192 -0
  77. package/dist/{index-DxvARIP2.d.ts → index-C5UBbQ4G.d.ts} +18 -17
  78. package/dist/{index-Bt4tOUD9.d.ts → index-C83mZI1P.d.ts} +93 -8
  79. package/dist/{index-Bg5dYMmZ.d.ts → index-D6b6na69.d.cts} +14 -11
  80. package/dist/{index-Cl7mhOFM.d.cts → index-DXd9JikN.d.cts} +92 -10
  81. package/dist/{index-Cl7mhOFM.d.ts → index-DXd9JikN.d.ts} +92 -10
  82. package/dist/index-OG65ocOr.d.cts +272 -0
  83. package/dist/index-OG65ocOr.d.ts +272 -0
  84. package/dist/{index-Jc0Ryi79.d.ts → index-tJhkmQgE.d.cts} +19 -4
  85. package/dist/{index-Dikst44v.d.cts → index-tSQh-xwY.d.ts} +14 -11
  86. package/dist/{index-BNlGP86A.d.cts → index-y_ak9_Hi.d.cts} +93 -8
  87. package/dist/index.cjs +419 -7383
  88. package/dist/index.cjs.map +1 -1
  89. package/dist/index.d.cts +14 -14
  90. package/dist/index.d.ts +14 -14
  91. package/dist/index.js +111 -27
  92. package/dist/model/index.cjs +8 -2562
  93. package/dist/model/index.cjs.map +1 -1
  94. package/dist/model/index.d.cts +433 -75
  95. package/dist/model/index.d.ts +433 -75
  96. package/dist/model/index.js +6 -7
  97. package/dist/styled-DIRkk9Uz.d.ts +506 -0
  98. package/dist/styled-DJbkJQfj.d.cts +506 -0
  99. package/dist/theory/index.cjs +172 -1822
  100. package/dist/theory/index.cjs.map +1 -1
  101. package/dist/theory/index.d.cts +151 -233
  102. package/dist/theory/index.d.ts +151 -233
  103. package/dist/theory/index.js +30 -7
  104. package/dist/{types-MGP29r3t.d.cts → types-BN6_Q9Kl.d.cts} +11 -2
  105. package/dist/{types-MGP29r3t.d.ts → types-BN6_Q9Kl.d.ts} +11 -2
  106. package/package.json +24 -6
  107. package/dist/chunk-2ZWMSJH6.js.map +0 -1
  108. package/dist/chunk-4MHA432G.js.map +0 -1
  109. package/dist/chunk-62QZKCJQ.js.map +0 -1
  110. package/dist/chunk-AKLYPWIN.js.map +0 -1
  111. package/dist/chunk-C5XYKUVG.js.map +0 -1
  112. package/dist/chunk-CHMXELDS.js.map +0 -1
  113. package/dist/chunk-DYWFNC4A.js +0 -152
  114. package/dist/chunk-DYWFNC4A.js.map +0 -1
  115. package/dist/chunk-EH6EM37U.js.map +0 -1
  116. package/dist/chunk-FBQK3ZQN.js +0 -131
  117. package/dist/chunk-FBQK3ZQN.js.map +0 -1
  118. package/dist/chunk-GOAW4VYL.js.map +0 -1
  119. package/dist/chunk-I5R7ZBJS.js.map +0 -1
  120. package/dist/chunk-IT2O4XFE.js.map +0 -1
  121. package/dist/chunk-MIWO425M.js.map +0 -1
  122. package/dist/chunk-SGU7SPLK.js.map +0 -1
  123. package/dist/index-CGMZNCx6.d.cts +0 -140
  124. package/dist/index-CGMZNCx6.d.ts +0 -140
  125. package/dist/index-CnZCo29u.d.cts +0 -108
  126. package/dist/index-JnF4v9bx.d.ts +0 -108
  127. package/dist/styled-DZ7GjShb.d.ts +0 -282
  128. package/dist/styled-ZTbdaVFM.d.cts +0 -282
  129. package/src/analyze/arrange/index.ts +0 -21
  130. package/src/analyze/arrange/internal.ts +0 -127
  131. package/src/analyze/arrange/tension.ts +0 -199
  132. package/src/analyze/arrange/tracks.ts +0 -312
  133. package/src/analyze/detect/index.ts +0 -272
  134. package/src/analyze/functional/borrowed.ts +0 -84
  135. package/src/analyze/functional/cadence.ts +0 -66
  136. package/src/analyze/functional/function.ts +0 -184
  137. package/src/analyze/functional/index.ts +0 -23
  138. package/src/analyze/functional/internal.ts +0 -29
  139. package/src/analyze/functional/roman.ts +0 -402
  140. package/src/analyze/index.ts +0 -49
  141. package/src/analyze/timeline/index.ts +0 -451
  142. package/src/analyze/voice/index.ts +0 -339
  143. package/src/core/event-index/index.ts +0 -104
  144. package/src/core/index.ts +0 -61
  145. package/src/core/interval/index.ts +0 -81
  146. package/src/core/meter/index.ts +0 -302
  147. package/src/core/pitch/index.ts +0 -311
  148. package/src/core/random/index.ts +0 -76
  149. package/src/core/tuning/index.ts +0 -186
  150. package/src/core/types.ts +0 -29
  151. package/src/core/validation/index.ts +0 -119
  152. package/src/generate/bass/index.ts +0 -373
  153. package/src/generate/countermelody/index.ts +0 -470
  154. package/src/generate/drums/beat.ts +0 -266
  155. package/src/generate/drums/euclid.ts +0 -65
  156. package/src/generate/drums/fills.ts +0 -356
  157. package/src/generate/drums/ghost.ts +0 -119
  158. package/src/generate/drums/hihat.ts +0 -285
  159. package/src/generate/drums/hit.ts +0 -31
  160. package/src/generate/drums/index.ts +0 -361
  161. package/src/generate/drums/internal.ts +0 -257
  162. package/src/generate/drums/kick.ts +0 -160
  163. package/src/generate/drums/percussion.ts +0 -121
  164. package/src/generate/drums/rng.ts +0 -7
  165. package/src/generate/drums/swing.ts +0 -71
  166. package/src/generate/groove/index.ts +0 -351
  167. package/src/generate/harmonize/index.ts +0 -451
  168. package/src/generate/index.ts +0 -58
  169. package/src/generate/motif/index.ts +0 -422
  170. package/src/generate/progression/index.ts +0 -362
  171. package/src/generate/reharmony/index.ts +0 -323
  172. package/src/generate/rhythm/index.ts +0 -175
  173. package/src/index.ts +0 -13
  174. package/src/model/chord.ts +0 -442
  175. package/src/model/index.ts +0 -15
  176. package/src/model/interval.ts +0 -82
  177. package/src/model/key.ts +0 -266
  178. package/src/model/note.ts +0 -176
  179. package/src/model/progression.ts +0 -161
  180. package/src/model/shared.ts +0 -12
  181. package/src/theory/chord/index.ts +0 -375
  182. package/src/theory/chordscale/index.ts +0 -374
  183. package/src/theory/counterpoint/index.ts +0 -230
  184. package/src/theory/harmony/index.ts +0 -77
  185. package/src/theory/index.ts +0 -112
  186. package/src/theory/safety/index.ts +0 -488
  187. package/src/theory/scale/degrees.ts +0 -123
  188. package/src/theory/scale/index.ts +0 -28
  189. package/src/theory/scale/key.ts +0 -56
  190. package/src/theory/scale/masks.ts +0 -153
  191. package/src/theory/spelling/index.ts +0 -249
  192. package/src/theory/symbol/index.ts +0 -268
  193. package/src/theory/voicing/index.ts +0 -5
  194. package/src/theory/voicing/internal.ts +0 -168
  195. package/src/theory/voicing/leading.ts +0 -112
  196. package/src/theory/voicing/satb.ts +0 -216
  197. package/src/theory/voicing/styled.ts +0 -199
  198. package/tsconfig.json +0 -23
@@ -1,2574 +1,20 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true});
19
2
 
20
- // src/model/index.ts
21
- var model_exports = {};
22
- __export(model_exports, {
23
- Chord: () => Chord,
24
- Interval: () => Interval,
25
- Key: () => Key,
26
- Note: () => Note,
27
- Progression: () => Progression
28
- });
29
- module.exports = __toCommonJS(model_exports);
30
3
 
31
- // src/core/validation/index.ts
32
- var DEFAULT_GENERATION_BUDGET = 1e6;
33
- function assertFiniteNumber(value, name) {
34
- if (!Number.isFinite(value)) {
35
- throw new RangeError(`${name} must be finite; received ${value}`);
36
- }
37
- return value;
38
- }
39
- function assertInteger(value, name, min = Number.MIN_SAFE_INTEGER, max = Number.MAX_SAFE_INTEGER) {
40
- assertFiniteNumber(value, name);
41
- if (!Number.isSafeInteger(value) || value < min || value > max) {
42
- throw new RangeError(`${name} must be an integer in [${min}, ${max}]; received ${value}`);
43
- }
44
- return value;
45
- }
46
- function assertPositiveInt(value, name, max = DEFAULT_GENERATION_BUDGET) {
47
- return assertInteger(value, name, 1, max);
48
- }
49
- function assertGenerationBudget(estimated, name, limit = DEFAULT_GENERATION_BUDGET) {
50
- assertFiniteNumber(estimated, name);
51
- assertPositiveInt(limit, `${name} limit`, Number.MAX_SAFE_INTEGER);
52
- if (estimated < 0 || estimated > limit) {
53
- throw new RangeError(`${name} exceeds the generation budget ${limit}; received ${estimated}`);
54
- }
55
- return estimated;
56
- }
57
4
 
58
- // src/theory/scale/degrees.ts
59
- function pitchClass(pitch) {
60
- return (Math.trunc(pitch) % 12 + 12) % 12;
61
- }
62
- function scaleOffset(pitch, key) {
63
- return (pitchClass(pitch) - pitchClass(key.rootPc) + 12) % 12;
64
- }
65
- function isScaleTone(pitch, key) {
66
- return (key.modeMask12 >> scaleOffset(pitch, key) & 1) === 1;
67
- }
68
- function scaleTonesInDegreeOrder(key) {
69
- const root = pitchClass(key.rootPc);
70
- const pcs = [];
71
- for (let n = 0; n < 12; n += 1) {
72
- if ((key.modeMask12 >> n & 1) === 1) {
73
- pcs.push((root + n) % 12);
74
- }
75
- }
76
- return pcs;
77
- }
78
5
 
79
- // src/theory/scale/masks.ts
80
- function maskFromOffsets(offsets) {
81
- let mask = 1;
82
- for (const offset of offsets) {
83
- mask |= 1 << (offset % 12 + 12) % 12;
84
- }
85
- return mask;
86
- }
87
- var MAJOR_MASK = 2741;
88
- var NATURAL_MINOR_MASK = 1453;
89
- var HARMONIC_MINOR_MASK = maskFromOffsets([0, 2, 3, 5, 7, 8, 11]);
90
- var MELODIC_MINOR_MASK = maskFromOffsets([0, 2, 3, 5, 7, 9, 11]);
91
- var DORIAN_MASK = maskFromOffsets([0, 2, 3, 5, 7, 9, 10]);
92
- var PHRYGIAN_MASK = maskFromOffsets([0, 1, 3, 5, 7, 8, 10]);
93
- var LYDIAN_MASK = maskFromOffsets([0, 2, 4, 6, 7, 9, 11]);
94
- var MIXOLYDIAN_MASK = maskFromOffsets([0, 2, 4, 5, 7, 9, 10]);
95
- var LOCRIAN_MASK = maskFromOffsets([0, 1, 3, 5, 6, 8, 10]);
96
- var MAJOR_PENTATONIC_MASK = maskFromOffsets([0, 2, 4, 7, 9]);
97
- var MINOR_PENTATONIC_MASK = maskFromOffsets([0, 3, 5, 7, 10]);
98
- var BLUES_MASK = maskFromOffsets([0, 3, 5, 6, 7, 10]);
99
- var WHOLE_TONE_MASK = maskFromOffsets([0, 2, 4, 6, 8, 10]);
100
- var OCTATONIC_HALF_WHOLE_MASK = maskFromOffsets([0, 1, 3, 4, 6, 7, 9, 10]);
101
- var OCTATONIC_WHOLE_HALF_MASK = maskFromOffsets([0, 2, 3, 5, 6, 8, 9, 11]);
102
- var CHROMATIC_MASK = 4095;
103
- var NAMED_SCALES = {
104
- major: MAJOR_MASK,
105
- ionian: MAJOR_MASK,
106
- naturalMinor: NATURAL_MINOR_MASK,
107
- aeolian: NATURAL_MINOR_MASK,
108
- harmonicMinor: HARMONIC_MINOR_MASK,
109
- melodicMinor: MELODIC_MINOR_MASK,
110
- dorian: DORIAN_MASK,
111
- phrygian: PHRYGIAN_MASK,
112
- lydian: LYDIAN_MASK,
113
- mixolydian: MIXOLYDIAN_MASK,
114
- locrian: LOCRIAN_MASK,
115
- majorPentatonic: MAJOR_PENTATONIC_MASK,
116
- minorPentatonic: MINOR_PENTATONIC_MASK,
117
- blues: BLUES_MASK,
118
- wholeTone: WHOLE_TONE_MASK,
119
- octatonicHalfWhole: OCTATONIC_HALF_WHOLE_MASK,
120
- octatonicWholeHalf: OCTATONIC_WHOLE_HALF_MASK,
121
- chromatic: CHROMATIC_MASK
122
- };
123
6
 
124
- // src/theory/scale/key.ts
125
- function majorKey(rootPc) {
126
- return { rootPc: (rootPc % 12 + 12) % 12, modeMask12: MAJOR_MASK };
127
- }
128
- function minorKey(rootPc) {
129
- return { rootPc: (rootPc % 12 + 12) % 12, modeMask12: NATURAL_MINOR_MASK };
130
- }
131
- function scaleByName(name, rootPc) {
132
- const mask = NAMED_SCALES[name];
133
- if (mask === void 0) {
134
- throw new Error(`Unknown scale: ${name}`);
135
- }
136
- return { rootPc: (rootPc % 12 + 12) % 12, modeMask12: mask };
137
- }
7
+ var _chunkNVE34YGZcjs = require('../chunk-NVE34YGZ.cjs');
8
+ require('../chunk-ZEJR4TKL.cjs');
9
+ require('../chunk-CAN76NCU.cjs');
10
+ require('../chunk-LW53AHQU.cjs');
11
+ require('../chunk-FNDWXRRI.cjs');
12
+ require('../chunk-7MGZ7D62.cjs');
138
13
 
139
- // src/theory/chord/index.ts
140
- var QUALITY_INTERVALS = {
141
- maj: [0, 4, 7],
142
- min: [0, 3, 7],
143
- dim: [0, 3, 6],
144
- aug: [0, 4, 8],
145
- majb5: [0, 4, 6],
146
- maj7: [0, 4, 7, 11],
147
- min7: [0, 3, 7, 10],
148
- dom7: [0, 4, 7, 10],
149
- dim7: [0, 3, 6, 9],
150
- m7b5: [0, 3, 6, 10],
151
- minMaj7: [0, 3, 7, 11],
152
- aug7: [0, 4, 8, 10],
153
- augMaj7: [0, 4, 8, 11],
154
- "6": [0, 4, 7, 9],
155
- min6: [0, 3, 7, 9],
156
- "6/9": [0, 4, 7, 9, 14],
157
- sus2: [0, 2, 7],
158
- sus4: [0, 5, 7],
159
- add9: [0, 4, 7, 14],
160
- add11: [0, 4, 7, 17],
161
- maj9: [0, 4, 7, 11, 14],
162
- min9: [0, 3, 7, 10, 14],
163
- dom9: [0, 4, 7, 10, 14],
164
- "7b9": [0, 4, 7, 10, 13],
165
- "7#9": [0, 4, 7, 10, 15],
166
- "7#11": [0, 4, 7, 10, 18],
167
- "7b13": [0, 4, 7, 10, 20],
168
- "11": [0, 7, 10, 14, 17],
169
- "13": [0, 4, 7, 10, 14, 21],
170
- "5": [0, 7]
171
- };
172
- function pitchClass2(value) {
173
- return (Math.trunc(value) % 12 + 12) % 12;
174
- }
175
- function chordQualities() {
176
- return Object.keys(QUALITY_INTERVALS);
177
- }
178
- function chordFromDegree(degree, ext, key) {
179
- const tones = scaleTonesInDegreeOrder(key);
180
- const length = tones.length;
181
- const index = length > 0 ? (degree % length + length) % length : 0;
182
- const rootPc = tones[index] ?? pitchClass2(key.rootPc);
183
- return { rootPc, quality: ext, intervals: [...QUALITY_INTERVALS[ext]] };
184
- }
185
- function makeChord(rootPc, quality, bassPc) {
186
- const chord = {
187
- rootPc: pitchClass2(rootPc),
188
- quality,
189
- intervals: [...QUALITY_INTERVALS[quality]]
190
- };
191
- if (bassPc !== void 0) {
192
- chord.bassPc = pitchClass2(bassPc);
193
- }
194
- return chord;
195
- }
196
- function chordPitchClasses(chord) {
197
- const set = /* @__PURE__ */ new Set();
198
- for (const interval of chord.intervals) {
199
- set.add(pitchClass2(chord.rootPc + interval));
200
- }
201
- return [...set].sort((a, b) => a - b);
202
- }
203
- function chordToneOffsets(chord) {
204
- return new Set(chord.intervals.map((i) => (i % 12 + 12) % 12));
205
- }
206
- function chordToneRole(pitch, chord) {
207
- const interval = (pitchClass2(pitch) - pitchClass2(chord.rootPc) + 12) % 12;
208
- const tones = chordToneOffsets(chord);
209
- if (interval === 0) {
210
- return "root";
211
- }
212
- if (interval === 3 || interval === 4) {
213
- return tones.has(interval) ? "third" : null;
214
- }
215
- if (interval === 7) {
216
- return tones.has(7) ? "fifth" : null;
217
- }
218
- if (interval === 6) {
219
- return tones.has(6) && !tones.has(7) ? "fifth" : null;
220
- }
221
- if (interval === 8) {
222
- return tones.has(8) && !tones.has(7) ? "fifth" : null;
223
- }
224
- if (interval === 9) {
225
- const hasHigherSeventh = tones.has(10) || tones.has(11);
226
- const isDiminishedSeventh = tones.has(3) && tones.has(6) && !hasHigherSeventh;
227
- if (isDiminishedSeventh) {
228
- return "seventh";
229
- }
230
- if (tones.has(9) && !hasHigherSeventh) {
231
- return "sixth";
232
- }
233
- return null;
234
- }
235
- if (interval === 10 || interval === 11) {
236
- return tones.has(interval) ? "seventh" : null;
237
- }
238
- return null;
239
- }
240
- function classifyTriad(thirdIc, fifthIc) {
241
- if (thirdIc === 4 && fifthIc === 8) {
242
- return "aug";
243
- }
244
- if (thirdIc === 4 && fifthIc === 6) {
245
- return "majb5";
246
- }
247
- if (thirdIc === 3 && fifthIc === 6) {
248
- return "dim";
249
- }
250
- if (thirdIc === 3) {
251
- return "min";
252
- }
253
- return "maj";
254
- }
255
- function classifySeventh(thirdIc, fifthIc, seventhIc) {
256
- if (thirdIc === 3 && fifthIc === 6 && seventhIc === 9) {
257
- return "dim7";
258
- }
259
- if (thirdIc === 3 && fifthIc === 6 && seventhIc === 10) {
260
- return "m7b5";
261
- }
262
- if (thirdIc === 3 && seventhIc === 11) {
263
- return "minMaj7";
264
- }
265
- if (thirdIc === 3) {
266
- return "min7";
267
- }
268
- if (fifthIc === 8 && seventhIc === 10) {
269
- return "aug7";
270
- }
271
- if (fifthIc === 8 && seventhIc === 11) {
272
- return "augMaj7";
273
- }
274
- if (seventhIc === 11) {
275
- return "maj7";
276
- }
277
- return "dom7";
278
- }
279
- function stackThirds(degree, key, size) {
280
- const tones = scaleTonesInDegreeOrder(key);
281
- const length = tones.length;
282
- if (length !== 7) {
283
- throw new Error(
284
- `diatonic chord stacking requires a heptatonic scale (received ${length} tones)`
285
- );
286
- }
287
- const idx = (step) => ((degree + step) % length + length) % length;
288
- const rootPc = tones[idx(0)] ?? pitchClass2(key.rootPc);
289
- const offsets = [0, 2, 4, 6].slice(0, size).map((step) => {
290
- const pc = tones[idx(step)] ?? rootPc;
291
- return ((pc - rootPc) % 12 + 12) % 12;
292
- });
293
- const thirdIc = offsets[1] ?? 4;
294
- const fifthIc = offsets[2] ?? 7;
295
- const quality = size === 3 ? classifyTriad(thirdIc, fifthIc) : classifySeventh(thirdIc, fifthIc, offsets[3] ?? 11);
296
- return { rootPc, quality, intervals: offsets };
297
- }
298
- function diatonicTriad(degree, key) {
299
- return stackThirds(degree, key, 3);
300
- }
301
- function diatonicSeventh(degree, key) {
302
- return stackThirds(degree, key, 4);
303
- }
304
14
 
305
- // src/analyze/detect/index.ts
306
- function pitchClass3(value) {
307
- return (Math.trunc(value) % 12 + 12) % 12;
308
- }
309
- function uniquePitchClasses(pitches) {
310
- return [...new Set(pitches.map(pitchClass3))].sort((a, b) => a - b);
311
- }
312
- function assertPitches(pitches) {
313
- assertGenerationBudget(pitches.length, "detection pitches");
314
- for (let index = 0; index < pitches.length; index += 1) {
315
- assertFiniteNumber(pitches[index] ?? Number.NaN, `pitches[${index}]`);
316
- }
317
- }
318
- function detectChord(pitches, opts = {}) {
319
- assertPitches(pitches);
320
- if (opts.bassPc !== void 0) assertFiniteNumber(opts.bassPc, "bassPc");
321
- const input = uniquePitchClasses(pitches);
322
- if (input.length === 0) {
323
- return [];
324
- }
325
- const inputKind = opts.input === void 0 || opts.input === "auto" ? pitches.every((pitch) => Number.isInteger(pitch) && pitch >= 0 && pitch <= 11) ? "pitchClass" : "midi" : opts.input;
326
- const bassPc = opts.bassPc !== void 0 ? pitchClass3(opts.bassPc) : inputKind === "midi" ? pitchClass3(pitches.reduce((lowest, pitch) => Math.min(lowest, pitch), Infinity)) : void 0;
327
- const inputSet = new Set(input);
328
- const matches = [];
329
- const qualities = chordQualities();
330
- for (const rootPc of input) {
331
- for (const quality of qualities) {
332
- const chord = makeChord(rootPc, quality);
333
- const tones = chordPitchClasses(chord);
334
- const toneSet = new Set(tones);
335
- const missingPcs = tones.filter((pc) => !inputSet.has(pc));
336
- const fifthPc = pitchClass3(rootPc + 7);
337
- if (missingPcs.length > 1 || missingPcs.length === 1 && missingPcs[0] !== fifthPc) {
338
- continue;
339
- }
340
- const extraPcs = input.filter((pc) => !toneSet.has(pc));
341
- const bassIndex = bassPc === void 0 ? -1 : chord.intervals.findIndex((iv) => pitchClass3(rootPc + iv) === bassPc);
342
- const inversion = bassPc === void 0 ? null : bassIndex > 0 ? bassIndex : 0;
343
- const match = {
344
- rootPc,
345
- quality,
346
- missingPcs,
347
- extraPcs,
348
- exact: extraPcs.length === 0 && missingPcs.length === 0,
349
- inversion
350
- };
351
- if (bassPc !== void 0 && bassPc !== rootPc) {
352
- match.bassPc = bassPc;
353
- }
354
- matches.push(match);
355
- }
356
- }
357
- matches.sort((a, b) => {
358
- if (a.extraPcs.length !== b.extraPcs.length) {
359
- return a.extraPcs.length - b.extraPcs.length;
360
- }
361
- if (a.missingPcs.length !== b.missingPcs.length) {
362
- return a.missingPcs.length - b.missingPcs.length;
363
- }
364
- if (a.inversion === 0 !== (b.inversion === 0)) {
365
- return a.inversion === 0 ? -1 : 1;
366
- }
367
- const aSize = chordPitchClasses(makeChord(a.rootPc, a.quality)).length;
368
- const bSize = chordPitchClasses(makeChord(b.rootPc, b.quality)).length;
369
- return bSize - aSize;
370
- });
371
- return matches;
372
- }
373
- function detectChordBest(pitches, opts = {}) {
374
- const best = detectChord(pitches, opts)[0];
375
- if (!best) {
376
- return null;
377
- }
378
- return makeChord(best.rootPc, best.quality, best.bassPc);
379
- }
380
15
 
381
- // src/analyze/functional/internal.ts
382
- function mod12(n) {
383
- return (n % 12 + 12) % 12;
384
- }
385
- function degreeRootPc(degreeNumber, key) {
386
- const tones = scaleTonesInDegreeOrder(key);
387
- if (tones.length === 0) {
388
- return mod12(key.rootPc);
389
- }
390
- return tones[(degreeNumber - 1) % tones.length] ?? mod12(key.rootPc);
391
- }
392
- function isNeapolitan(chord, key) {
393
- return mod12(chord.rootPc - key.rootPc) === 1 && chord.quality === "maj";
394
- }
395
16
 
396
- // src/analyze/functional/roman.ts
397
- var ROMAN = ["I", "II", "III", "IV", "V", "VI", "VII"];
398
- var ROMAN_TO_DEGREE = {
399
- I: 1,
400
- II: 2,
401
- III: 3,
402
- IV: 4,
403
- V: 5,
404
- VI: 6,
405
- VII: 7
406
- };
407
- var OFFSET_SPELLING = [
408
- [1, ""],
409
- [2, "b"],
410
- [2, ""],
411
- [3, "b"],
412
- [3, ""],
413
- [4, ""],
414
- [4, "#"],
415
- [5, ""],
416
- [6, "b"],
417
- [6, ""],
418
- [7, "b"],
419
- [7, ""]
420
- ];
421
- function seventhQuality(base, halfDim) {
422
- if (halfDim) {
423
- return "m7b5";
424
- }
425
- if (base === "dim") {
426
- return "dim7";
427
- }
428
- if (base === "aug") {
429
- return "aug7";
430
- }
431
- return base === "maj" ? "dom7" : "min7";
432
- }
433
- var INVERSION_FIGURES = /* @__PURE__ */ new Set(["6", "64", "65", "43", "42", "2", "7"]);
434
- var ROMAN_STYLE = {
435
- maj: { lower: false, suffix: "" },
436
- min: { lower: true, suffix: "" },
437
- dim: { lower: true, suffix: "o" },
438
- aug: { lower: false, suffix: "+" },
439
- maj7: { lower: false, suffix: "maj7" },
440
- min7: { lower: true, suffix: "7" },
441
- dom7: { lower: false, suffix: "7" },
442
- dim7: { lower: true, suffix: "o7" },
443
- m7b5: { lower: true, suffix: "\xF87" },
444
- minMaj7: { lower: true, suffix: "maj7" },
445
- aug7: { lower: false, suffix: "+7" },
446
- augMaj7: { lower: false, suffix: "+maj7" },
447
- majb5: { lower: false, suffix: "b5" },
448
- "6": { lower: false, suffix: "add6" },
449
- min6: { lower: true, suffix: "add6" },
450
- "6/9": { lower: false, suffix: "69" },
451
- sus2: { lower: false, suffix: "sus2" },
452
- sus4: { lower: false, suffix: "sus4" },
453
- add9: { lower: false, suffix: "add9" },
454
- add11: { lower: false, suffix: "add11" },
455
- maj9: { lower: false, suffix: "maj9" },
456
- min9: { lower: true, suffix: "9" },
457
- dom9: { lower: false, suffix: "9" },
458
- "7b9": { lower: false, suffix: "7b9" },
459
- "7#9": { lower: false, suffix: "7#9" },
460
- "7#11": { lower: false, suffix: "7#11" },
461
- "7b13": { lower: false, suffix: "7b13" },
462
- "11": { lower: false, suffix: "11" },
463
- "13": { lower: false, suffix: "13" },
464
- "5": { lower: false, suffix: "5" }
465
- };
466
- var SUFFIX_QUALITY = new Map(
467
- Object.entries(ROMAN_STYLE).map(
468
- ([quality, style]) => [`${style.lower ? "l" : "u"}:${style.suffix}`, quality]
469
- )
470
- );
471
- function parseInversion(figures) {
472
- if (figures === "65") {
473
- return { inversion: 1, seventh: true };
474
- }
475
- if (figures === "43") {
476
- return { inversion: 2, seventh: true };
477
- }
478
- if (figures === "42" || figures === "2") {
479
- return { inversion: 3, seventh: true };
480
- }
481
- if (figures === "7") {
482
- return { inversion: 0, seventh: true };
483
- }
484
- if (figures === "64") {
485
- return { inversion: 2, seventh: false };
486
- }
487
- if (figures === "6") {
488
- return { inversion: 1, seventh: false };
489
- }
490
- return { inversion: 0, seventh: false };
491
- }
492
- function parseSimpleRoman(text, key) {
493
- const match = /^([b#]?)([iIvV]+)(.*)$/.exec(text.trim());
494
- if (!match) {
495
- throw new Error(`Invalid Roman numeral: ${text}`);
496
- }
497
- const accidental = match[1] === "b" ? -1 : match[1] === "#" ? 1 : 0;
498
- const glyph = (match[2] ?? "").toUpperCase();
499
- const degreeNumber = ROMAN_TO_DEGREE[glyph];
500
- if (degreeNumber === void 0) {
501
- throw new Error(`Invalid Roman numeral: ${text}`);
502
- }
503
- const isUpper = (match[2] ?? "")[0] === (match[2] ?? "")[0]?.toUpperCase();
504
- const suffix = match[3] ?? "";
505
- const rootPc = mod12(degreeRootPc(degreeNumber, key) + accidental);
506
- const canonical = SUFFIX_QUALITY.get(`${isUpper ? "u" : "l"}:${suffix}`);
507
- if (canonical !== void 0) {
508
- return { rootPc, quality: canonical, inversion: 0 };
509
- }
510
- const parsedSuffix = /^(o|°|dim|ø|\+|aug)?(maj7|M7)?(65|64|43|42|7|6|2)?$/.exec(suffix);
511
- if (!parsedSuffix) {
512
- throw new Error(`Unsupported suffix "${suffix}" in Roman numeral: ${text}`);
513
- }
514
- const qualityMarker = parsedSuffix[1] ?? "";
515
- const isDim = qualityMarker === "o" || qualityMarker === "\xB0" || qualityMarker === "dim";
516
- const isAug = qualityMarker === "+" || qualityMarker === "aug";
517
- const isHalfDim = qualityMarker === "\xF8";
518
- const explicitMaj7 = parsedSuffix[2] !== void 0;
519
- const figures = parsedSuffix[3] ?? "";
520
- if (figures !== "" && !INVERSION_FIGURES.has(figures)) {
521
- throw new Error(`Unsupported figured-bass or extension "${figures}" in Roman numeral: ${text}`);
522
- }
523
- const { inversion, seventh } = parseInversion(figures);
524
- const hasSeventh = explicitMaj7 || seventh || isHalfDim;
525
- let base;
526
- if (isDim || isHalfDim) {
527
- base = "dim";
528
- } else if (isAug) {
529
- base = "aug";
530
- } else {
531
- base = isUpper ? "maj" : "min";
532
- }
533
- let quality;
534
- if (explicitMaj7) {
535
- quality = base === "min" ? "minMaj7" : base === "aug" ? "augMaj7" : "maj7";
536
- } else if (hasSeventh) {
537
- quality = seventhQuality(base, isHalfDim);
538
- } else if (base === "dim") {
539
- quality = "dim";
540
- } else if (base === "aug") {
541
- quality = "aug";
542
- } else {
543
- quality = base;
544
- }
545
- return { rootPc, quality, inversion };
546
- }
547
- function chordFromParsed(parsed) {
548
- const chord = makeChord(parsed.rootPc, parsed.quality);
549
- if (parsed.inversion > 0 && parsed.inversion < chord.intervals.length) {
550
- chord.bassPc = mod12(parsed.rootPc + (chord.intervals[parsed.inversion] ?? 0));
551
- }
552
- return chord;
553
- }
554
- function romanToChord(text, key) {
555
- const trimmed = text.trim();
556
- const slash = trimmed.indexOf("/");
557
- if (slash >= 0) {
558
- const applied = trimmed.slice(0, slash);
559
- const target = trimmed.slice(slash + 1);
560
- const targetRoot = parseSimpleRoman(target, key).rootPc;
561
- const localKey = majorKey(targetRoot);
562
- return chordFromParsed(parseSimpleRoman(applied, localKey));
563
- }
564
- return chordFromParsed(parseSimpleRoman(trimmed, key));
565
- }
566
- function romanStyle(quality) {
567
- return ROMAN_STYLE[quality];
568
- }
569
- function romanSpelling(rootPc, key) {
570
- const tones = scaleTonesInDegreeOrder(key);
571
- const diatonic = tones.indexOf(mod12(rootPc));
572
- if (diatonic >= 0) {
573
- return { degreeNumber: diatonic + 1, accidental: "" };
574
- }
575
- for (let i = 0; i < tones.length; i += 1) {
576
- const degreeNumber2 = i + 1;
577
- if (degreeNumber2 === 1 || degreeNumber2 === 5) {
578
- continue;
579
- }
580
- if (mod12((tones[i] ?? 0) - 1) === mod12(rootPc)) {
581
- return { degreeNumber: degreeNumber2, accidental: "b" };
582
- }
583
- }
584
- for (let i = 0; i < tones.length; i += 1) {
585
- if (mod12((tones[i] ?? 0) + 1) === mod12(rootPc)) {
586
- return { degreeNumber: i + 1, accidental: "#" };
587
- }
588
- }
589
- const [degreeNumber, accidental] = OFFSET_SPELLING[mod12(rootPc - key.rootPc)] ?? [1, ""];
590
- return { degreeNumber, accidental };
591
- }
592
- function baseMarker(quality) {
593
- if (quality === "dim" || quality === "dim7") {
594
- return "o";
595
- }
596
- if (quality === "m7b5") {
597
- return "\xF8";
598
- }
599
- if (quality === "aug" || quality === "aug7") {
600
- return "+";
601
- }
602
- if (quality === "augMaj7") {
603
- return "+maj7";
604
- }
605
- if (quality === "maj7" || quality === "minMaj7") {
606
- return "maj7";
607
- }
608
- return "";
609
- }
610
- var TRIAD_FIGURES = { 1: "6", 2: "64" };
611
- var SEVENTH_FIGURES = { 1: "65", 2: "43", 3: "42" };
612
- var TRIAD_FIGURE_QUALITIES = /* @__PURE__ */ new Set(["maj", "min", "dim", "aug"]);
613
- var SEVENTH_FIGURE_QUALITIES = /* @__PURE__ */ new Set([
614
- "maj7",
615
- "min7",
616
- "dom7",
617
- "dim7",
618
- "m7b5",
619
- "minMaj7",
620
- "aug7",
621
- "augMaj7"
622
- ]);
623
- function chordToRoman(chord, key) {
624
- const { degreeNumber, accidental } = romanSpelling(chord.rootPc, key);
625
- const { lower, suffix } = romanStyle(chord.quality);
626
- const numeral = ROMAN[degreeNumber - 1] ?? "I";
627
- const cased = lower ? numeral.toLowerCase() : numeral;
628
- let inversion = 0;
629
- if (chord.bassPc !== void 0) {
630
- const idx = chord.intervals.findIndex((iv) => mod12(chord.rootPc + iv) === chord.bassPc);
631
- if (idx > 0) {
632
- inversion = idx;
633
- }
634
- }
635
- if (inversion > 0) {
636
- const figure = SEVENTH_FIGURE_QUALITIES.has(chord.quality) ? SEVENTH_FIGURES[inversion] : TRIAD_FIGURE_QUALITIES.has(chord.quality) ? TRIAD_FIGURES[inversion] : void 0;
637
- if (figure !== void 0) {
638
- return `${accidental}${cased}${baseMarker(chord.quality)}${figure}`;
639
- }
640
- }
641
- return `${accidental}${cased}${suffix}`;
642
- }
643
17
 
644
- // src/analyze/functional/function.ts
645
- var FUNCTION_BY_OFFSET = [
646
- "tonic",
647
- // 0 I
648
- "subdominant",
649
- // 1 bII (Neapolitan)
650
- "subdominant",
651
- // 2 ii
652
- "tonic",
653
- // 3 bIII
654
- "tonic",
655
- // 4 iii
656
- "subdominant",
657
- // 5 IV
658
- "dominant",
659
- // 6 #IV / bV
660
- "dominant",
661
- // 7 V
662
- "subdominant",
663
- // 8 bVI
664
- "tonic",
665
- // 9 vi
666
- "subdominant",
667
- // 10 bVII
668
- "dominant"
669
- // 11 vii
670
- ];
671
- function isMinorKey(key) {
672
- const hasMinorThird = key.modeMask12 >> 3 & 1;
673
- const hasMajorThird2 = key.modeMask12 >> 4 & 1;
674
- return Boolean(hasMinorThird) && !hasMajorThird2;
675
- }
676
- function functionOf(chord, key) {
677
- return FUNCTION_BY_OFFSET[mod12(chord.rootPc - key.rootPc)] ?? "tonic";
678
- }
679
- function isDiatonic(chord, key) {
680
- return chordPitchClasses(chord).every((pc) => isScaleTone(pc, key));
681
- }
682
- function parallelKey(key) {
683
- return {
684
- rootPc: mod12(key.rootPc),
685
- modeMask12: isMinorKey(key) ? MAJOR_MASK : NATURAL_MINOR_MASK
686
- };
687
- }
688
- function isDiminishedQuality(quality) {
689
- return quality === "dim" || quality === "dim7" || quality === "m7b5";
690
- }
691
- function hasMajorThird(chord) {
692
- return chord.intervals.some((interval) => mod12(interval) === 4);
693
- }
694
- function qualityAwareFunction(chord, key) {
695
- const offset = mod12(chord.rootPc - key.rootPc);
696
- if (isDiminishedQuality(chord.quality) && (offset === 11 || offset === 6)) {
697
- return "dominant";
698
- }
699
- if (isNeapolitan(chord, key)) {
700
- return "subdominant";
701
- }
702
- if (!isMinorKey(key) && hasMajorThird(chord) && (offset === 8 || offset === 10)) {
703
- return "subdominant";
704
- }
705
- return functionOf(chord, key);
706
- }
707
- function analyzeChord(chord, key) {
708
- const source = borrowedSource(chord, key);
709
- return {
710
- function: qualityAwareFunction(chord, key),
711
- borrowed: source !== null,
712
- source,
713
- roman: chordToRoman(chord, key)
714
- };
715
- }
716
18
 
717
- // src/analyze/functional/borrowed.ts
718
- function isHarmonicMinorAlteration(chord, key) {
719
- return isMinorKey(key) && isDiatonic(chord, { rootPc: mod12(key.rootPc), modeMask12: HARMONIC_MINOR_MASK });
720
- }
721
- function isBorrowedChord(chord, key) {
722
- if (isDiatonic(chord, key)) {
723
- return false;
724
- }
725
- if (isHarmonicMinorAlteration(chord, key)) {
726
- return false;
727
- }
728
- return isDiatonic(chord, parallelKey(key));
729
- }
730
- function borrowedSource(chord, key) {
731
- if (isDiatonic(chord, key)) {
732
- return null;
733
- }
734
- if (isNeapolitan(chord, key)) {
735
- return "neapolitan";
736
- }
737
- if (isBorrowedChord(chord, key)) {
738
- return isMinorKey(key) ? "parallel-major" : "parallel-minor";
739
- }
740
- return null;
741
- }
742
-
743
- // src/analyze/functional/cadence.ts
744
- function detectCadence(from, to, key) {
745
- const tonic = mod12(key.rootPc);
746
- const fromOffset = mod12(from.rootPc - tonic);
747
- const toOffset = mod12(to.rootPc - tonic);
748
- const deceptiveTargets = isMinorKey(key) ? [8] : [8, 9];
749
- if (fromOffset === 7 && toOffset === 0) {
750
- return "authentic";
751
- }
752
- if (fromOffset === 5 && toOffset === 0) {
753
- return "plagal";
754
- }
755
- if (fromOffset === 7 && deceptiveTargets.includes(toOffset)) {
756
- return "deceptive";
757
- }
758
- if (toOffset === 7 && fromOffset !== 7) {
759
- return "half";
760
- }
761
- return null;
762
- }
763
-
764
- // src/generate/reharmony/index.ts
765
- function mod122(n) {
766
- return (n % 12 + 12) % 12;
767
- }
768
- function negativeHarmonyMirror(chord, key) {
769
- const tonic = mod122(key.rootPc);
770
- const mirror = (p) => mod122(2 * tonic + 7 - p);
771
- const pcs = chordPitchClasses(chord).map(mirror);
772
- const bassPc = chord.bassPc !== void 0 ? mirror(chord.bassPc) : void 0;
773
- const pitches = bassPc !== void 0 ? [bassPc - 12, ...pcs] : pcs;
774
- const detected = detectChordBest(pitches);
775
- if (detected) {
776
- if (bassPc === void 0 && detected.bassPc !== void 0) {
777
- return makeChord(detected.rootPc, detected.quality);
778
- }
779
- return detected;
780
- }
781
- const quality = chord.quality;
782
- return makeChord(mirror(chord.rootPc), quality, bassPc);
783
- }
784
-
785
- // src/theory/chordscale/index.ts
786
- function pitchClass4(value) {
787
- return (Math.trunc(value) % 12 + 12) % 12;
788
- }
789
- function popcount12(mask) {
790
- let count = 0;
791
- for (let n = 0; n < 12; n += 1) {
792
- count += mask >> n & 1;
793
- }
794
- return count;
795
- }
796
- function maskHasPitchClass(mask, scaleRootPc, pc) {
797
- const offset = pitchClass4(pc - scaleRootPc);
798
- return (mask >> offset & 1) === 1;
799
- }
800
- function scaleMatchesChord(chordPcs, scaleMask, scaleRootPc) {
801
- for (const pc of chordPcs) {
802
- if (!maskHasPitchClass(scaleMask, scaleRootPc, pc)) {
803
- return false;
804
- }
805
- }
806
- return true;
807
- }
808
- var ALIASED_SCALE_NAMES = /* @__PURE__ */ new Set(["major", "naturalMinor"]);
809
- var HEPTATONIC_SIZE = 7;
810
- function chordScales(chord) {
811
- const chordPcs = chordPitchClasses(chord);
812
- const rootPc = pitchClass4(chord.rootPc);
813
- const ranked = [];
814
- const seenMasks = /* @__PURE__ */ new Set();
815
- for (const name of Object.keys(NAMED_SCALES)) {
816
- if (name === "chromatic" || ALIASED_SCALE_NAMES.has(name)) {
817
- continue;
818
- }
819
- const mask = NAMED_SCALES[name];
820
- if (mask === void 0 || seenMasks.has(mask)) {
821
- continue;
822
- }
823
- seenMasks.add(mask);
824
- if (scaleMatchesChord(chordPcs, mask, rootPc)) {
825
- const size = popcount12(mask);
826
- ranked.push({ name, extra: size - chordPcs.length, size });
827
- }
828
- }
829
- if (ranked.length === 0) {
830
- if (NAMED_SCALES.chromatic !== void 0) {
831
- return [{ name: "chromatic", rootPc }];
832
- }
833
- return [];
834
- }
835
- const preferHeptatonic = chordPcs.length <= 3;
836
- ranked.sort((a, b) => {
837
- if (preferHeptatonic && a.size === HEPTATONIC_SIZE !== (b.size === HEPTATONIC_SIZE)) {
838
- return a.size === HEPTATONIC_SIZE ? -1 : 1;
839
- }
840
- if (a.extra !== b.extra) {
841
- return a.extra - b.extra;
842
- }
843
- if (a.size !== b.size) {
844
- return a.size - b.size;
845
- }
846
- return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
847
- });
848
- return ranked.map((entry) => ({ name: entry.name, rootPc }));
849
- }
850
- function avoidNotes(chord, scaleName) {
851
- const mask = NAMED_SCALES[scaleName];
852
- if (mask === void 0) {
853
- return [];
854
- }
855
- const rootPc = pitchClass4(chord.rootPc);
856
- const chordPcs = chordPitchClasses(chord);
857
- if (!scaleMatchesChord(chordPcs, mask, rootPc)) {
858
- return [];
859
- }
860
- const chordSet = new Set(chordPcs);
861
- const avoid = [];
862
- for (let pc = 0; pc < 12; pc += 1) {
863
- if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc)) {
864
- continue;
865
- }
866
- if (chordSet.has(pitchClass4(pc - 1))) {
867
- avoid.push(pc);
868
- }
869
- }
870
- return avoid.sort((a, b) => a - b);
871
- }
872
- function availableTensions(chord, scaleName) {
873
- const mask = NAMED_SCALES[scaleName];
874
- if (mask === void 0) {
875
- return [];
876
- }
877
- const rootPc = pitchClass4(chord.rootPc);
878
- const chordPcs = chordPitchClasses(chord);
879
- if (!scaleMatchesChord(chordPcs, mask, rootPc)) {
880
- return [];
881
- }
882
- const chordSet = new Set(chordPcs);
883
- const avoidSet = new Set(avoidNotes(chord, scaleName));
884
- const tensions = [];
885
- for (let pc = 0; pc < 12; pc += 1) {
886
- if (!maskHasPitchClass(mask, rootPc, pc) || chordSet.has(pc) || avoidSet.has(pc)) {
887
- continue;
888
- }
889
- tensions.push(pc);
890
- }
891
- return tensions.sort((a, b) => a - b);
892
- }
893
-
894
- // src/core/pitch/index.ts
895
- var LETTER_SEMITONES = [0, 2, 4, 5, 7, 9, 11];
896
- var LETTER_NAMES = ["C", "D", "E", "F", "G", "A", "B"];
897
- function mod123(n) {
898
- return (n % 12 + 12) % 12;
899
- }
900
- function mod7(n) {
901
- return (n % 7 + 7) % 7;
902
- }
903
- function parseNote(text) {
904
- const match = /^([A-Ga-g])([#x]*|b*)(-?\d+)?$/.exec(text.trim());
905
- if (!match) {
906
- throw new Error(`Invalid note: ${text}`);
907
- }
908
- const letterGlyph = (match[1] ?? "").toUpperCase();
909
- const letter = LETTER_NAMES.indexOf(letterGlyph);
910
- let alter = 0;
911
- for (const ch of match[2] ?? "") {
912
- if (ch === "#") {
913
- alter += 1;
914
- } else if (ch === "x") {
915
- alter += 2;
916
- } else if (ch === "b") {
917
- alter -= 1;
918
- }
919
- }
920
- const note = { letter, alter };
921
- if (match[3] !== void 0) {
922
- note.octave = Number.parseInt(match[3], 10);
923
- }
924
- return note;
925
- }
926
- function formatAlter(alter) {
927
- if (alter > 0) {
928
- return "#".repeat(alter);
929
- }
930
- if (alter < 0) {
931
- return "b".repeat(-alter);
932
- }
933
- return "";
934
- }
935
- function formatNote(note) {
936
- const glyph = LETTER_NAMES[mod7(note.letter)] ?? "C";
937
- const octave = note.octave === void 0 ? "" : String(note.octave);
938
- return `${glyph}${formatAlter(note.alter)}${octave}`;
939
- }
940
- function noteToPitchClass(note) {
941
- const natural = LETTER_SEMITONES[mod7(note.letter)] ?? 0;
942
- return mod123(natural + note.alter);
943
- }
944
- function noteToMidi(note) {
945
- if (note.octave === void 0) {
946
- throw new Error("noteToMidi requires an octave");
947
- }
948
- const natural = LETTER_SEMITONES[mod7(note.letter)] ?? 0;
949
- return (note.octave + 1) * 12 + natural + note.alter;
950
- }
951
- var SHARP_SPELLING = [
952
- [0, 0],
953
- [0, 1],
954
- [1, 0],
955
- [1, 1],
956
- [2, 0],
957
- [3, 0],
958
- [3, 1],
959
- [4, 0],
960
- [4, 1],
961
- [5, 0],
962
- [5, 1],
963
- [6, 0]
964
- ];
965
- var FLAT_SPELLING = [
966
- [0, 0],
967
- [1, -1],
968
- [1, 0],
969
- [2, -1],
970
- [2, 0],
971
- [3, 0],
972
- [4, -1],
973
- [4, 0],
974
- [5, -1],
975
- [5, 0],
976
- [6, -1],
977
- [6, 0]
978
- ];
979
- function midiToNote(midi, spelling = "sharp") {
980
- const rounded = Math.round(midi);
981
- const pc = mod123(rounded);
982
- const octave = Math.floor(rounded / 12) - 1;
983
- const table = spelling === "sharp" ? SHARP_SPELLING : FLAT_SPELLING;
984
- const entry = table[pc] ?? [0, 0];
985
- return { letter: entry[0], alter: entry[1], octave };
986
- }
987
- var SIMPLE_REFERENCE = [0, 0, 2, 4, 5, 7, 9, 11];
988
- function isPerfectNumber(simpleNumber) {
989
- return simpleNumber === 1 || simpleNumber === 4 || simpleNumber === 5;
990
- }
991
- function qualityFromSpan(numberValue, semitones) {
992
- const octaves = Math.floor((numberValue - 1) / 7);
993
- const simple = numberValue - 7 * octaves;
994
- const reference = (SIMPLE_REFERENCE[simple] ?? 0) + 12 * octaves;
995
- const delta = semitones - reference;
996
- if (isPerfectNumber(simple)) {
997
- if (delta === 0) {
998
- return "P";
999
- }
1000
- return delta > 0 ? "A".repeat(delta) : "d".repeat(-delta);
1001
- }
1002
- if (delta === 0) {
1003
- return "M";
1004
- }
1005
- if (delta === -1) {
1006
- return "m";
1007
- }
1008
- return delta > 0 ? "A".repeat(delta) : "d".repeat(-delta - 1);
1009
- }
1010
- function diatonicIndex(note) {
1011
- return mod7(note.letter) + 7 * (note.octave ?? 0);
1012
- }
1013
- function spelledInterval(a, b) {
1014
- const octaved = a.octave !== void 0 && b.octave !== void 0;
1015
- let letterSteps;
1016
- let semitones;
1017
- if (octaved) {
1018
- letterSteps = diatonicIndex(b) - diatonicIndex(a);
1019
- semitones = noteToMidi(b) - noteToMidi(a);
1020
- } else {
1021
- letterSteps = mod7(b.letter - a.letter);
1022
- let rawSemis = mod123(noteToPitchClass(b) - noteToPitchClass(a));
1023
- const reference = SIMPLE_REFERENCE[letterSteps + 1] ?? 0;
1024
- if (reference - rawSemis > 6) {
1025
- rawSemis += 12;
1026
- } else if (rawSemis - reference > 6) {
1027
- rawSemis -= 12;
1028
- }
1029
- semitones = rawSemis;
1030
- }
1031
- const absSteps = Math.abs(letterSteps);
1032
- const number = absSteps + 1;
1033
- const quality = qualityFromSpan(number, Math.abs(semitones));
1034
- return { number, quality, semitones };
1035
- }
1036
-
1037
- // src/theory/spelling/index.ts
1038
- var LETTER_SEMITONES2 = [0, 2, 4, 5, 7, 9, 11];
1039
- var CHROMATIC_SPELLING = {
1040
- 1: { degreeOffset: 1, alter: -1 },
1041
- // b2
1042
- 3: { degreeOffset: 2, alter: -1 },
1043
- // b3
1044
- 6: { degreeOffset: 3, alter: 1 },
1045
- // #4
1046
- 8: { degreeOffset: 5, alter: -1 },
1047
- // b6
1048
- 9: { degreeOffset: 5, alter: 1 },
1049
- // #6 (raised sixth of a minor key)
1050
- 10: { degreeOffset: 6, alter: -1 },
1051
- // b7
1052
- 11: { degreeOffset: 6, alter: 1 }
1053
- // #7 (raised leading tone of a minor key)
1054
- };
1055
- function mod124(n) {
1056
- return (n % 12 + 12) % 12;
1057
- }
1058
- function mod72(n) {
1059
- return (n % 7 + 7) % 7;
1060
- }
1061
- function naturalPc(letter) {
1062
- return LETTER_SEMITONES2[mod72(letter)] ?? 0;
1063
- }
1064
- function alterFor(letter, pc) {
1065
- let d = mod124(pc - naturalPc(letter));
1066
- if (d > 6) {
1067
- d -= 12;
1068
- }
1069
- return d;
1070
- }
1071
- function isHeptatonic(key) {
1072
- return scaleTonesInDegreeOrder(key).length === 7;
1073
- }
1074
- function spellPitchClass(pc, tonic, key) {
1075
- const tonicPc = mod124(naturalPc(tonic.letter) + tonic.alter);
1076
- const offset = mod124(pc - tonicPc);
1077
- const tones = scaleTonesInDegreeOrder(key);
1078
- if (isHeptatonic(key)) {
1079
- const degree = tones.indexOf(mod124(pc));
1080
- if (degree >= 0) {
1081
- const letter = mod72(tonic.letter + degree);
1082
- return { letter, alter: alterFor(letter, pc) };
1083
- }
1084
- const chromatic = CHROMATIC_SPELLING[offset];
1085
- if (chromatic) {
1086
- const letter = mod72(tonic.letter + chromatic.degreeOffset);
1087
- return { letter, alter: alterFor(letter, pc) };
1088
- }
1089
- }
1090
- for (let letter = 0; letter < 7; letter += 1) {
1091
- if (naturalPc(letter) === mod124(pc)) {
1092
- return { letter, alter: 0 };
1093
- }
1094
- }
1095
- const belowLetter = mod72([0, 0, 1, 1, 2, 3, 3, 4, 4, 5, 5, 6][mod124(pc)] ?? 0);
1096
- return { letter: belowLetter, alter: alterFor(belowLetter, pc) };
1097
- }
1098
- function spellScale(tonic, key) {
1099
- return scaleTonesInDegreeOrder(key).map((pc) => spellPitchClass(pc, tonic, key));
1100
- }
1101
- function chordLetterOffset(interval, chord) {
1102
- switch (interval) {
1103
- case 0:
1104
- case 12:
1105
- return 0;
1106
- case 1:
1107
- case 2:
1108
- case 13:
1109
- case 14:
1110
- return 1;
1111
- case 3:
1112
- case 4:
1113
- case 15:
1114
- case 16:
1115
- return 2;
1116
- case 5:
1117
- case 17:
1118
- case 18:
1119
- return 3;
1120
- case 6:
1121
- case 7:
1122
- case 8:
1123
- case 19:
1124
- return 4;
1125
- case 9:
1126
- return chord.quality === "dim7" ? 6 : 5;
1127
- case 20:
1128
- case 21:
1129
- return 5;
1130
- case 10:
1131
- case 11:
1132
- case 22:
1133
- case 23:
1134
- return 6;
1135
- default: {
1136
- const octaves = Math.floor(Math.max(0, interval) / 12);
1137
- const simple = mod124(interval);
1138
- const simpleOffset = [0, 1, 1, 2, 2, 3, 4, 4, 4, 5, 6, 6][simple] ?? 0;
1139
- return octaves * 7 + simpleOffset;
1140
- }
1141
- }
1142
- }
1143
- function spellChordFromRoot(chord, root) {
1144
- return chord.intervals.map((interval) => {
1145
- const letter = mod72(root.letter + chordLetterOffset(interval, chord));
1146
- const pc = mod124(chord.rootPc + interval);
1147
- return { letter, alter: alterFor(letter, pc) };
1148
- });
1149
- }
1150
- function spellChord(chord, tonic, key) {
1151
- const root = spellPitchClass(chord.rootPc, tonic, key);
1152
- return spellChordFromRoot(chord, root);
1153
- }
1154
-
1155
- // src/theory/symbol/index.ts
1156
- var ROOT_RE = /^[A-Ga-g](?:#{1,2}|b{1,2})?/;
1157
- var BASS_RE = /^[A-Ga-g](?:#{1,2}|b{1,2})?$/;
1158
- var QUALITY_MAP = {
1159
- "": "maj",
1160
- m: "min",
1161
- min: "min",
1162
- "-": "min",
1163
- dim: "dim",
1164
- "\xB0": "dim",
1165
- aug: "aug",
1166
- "+": "aug",
1167
- maj7: "maj7",
1168
- M7: "maj7",
1169
- \u0394: "maj7",
1170
- \u03947: "maj7",
1171
- m7: "min7",
1172
- min7: "min7",
1173
- "-7": "min7",
1174
- "7": "dom7",
1175
- dim7: "dim7",
1176
- "\xB07": "dim7",
1177
- m7b5: "m7b5",
1178
- \u00F8: "m7b5",
1179
- \u00F87: "m7b5",
1180
- min7b5: "m7b5",
1181
- mMaj7: "minMaj7",
1182
- mM7: "minMaj7",
1183
- minMaj7: "minMaj7",
1184
- aug7: "aug7",
1185
- "+7": "aug7",
1186
- "7#5": "aug7",
1187
- augMaj7: "augMaj7",
1188
- augM7: "augMaj7",
1189
- "+maj7": "augMaj7",
1190
- "+M7": "augMaj7",
1191
- majb5: "majb5",
1192
- "maj(b5)": "majb5",
1193
- "(b5)": "majb5",
1194
- "6": "6",
1195
- m6: "min6",
1196
- min6: "min6",
1197
- "6/9": "6/9",
1198
- "69": "6/9",
1199
- sus2: "sus2",
1200
- sus: "sus4",
1201
- sus4: "sus4",
1202
- add9: "add9",
1203
- add11: "add11",
1204
- maj9: "maj9",
1205
- M9: "maj9",
1206
- m9: "min9",
1207
- min9: "min9",
1208
- "9": "dom9",
1209
- "7b9": "7b9",
1210
- "7#9": "7#9",
1211
- "7#11": "7#11",
1212
- "7b13": "7b13",
1213
- "11": "11",
1214
- "13": "13",
1215
- "5": "5"
1216
- };
1217
- var CANONICAL_SUFFIX = {
1218
- maj: "",
1219
- min: "m",
1220
- dim: "dim",
1221
- aug: "aug",
1222
- maj7: "maj7",
1223
- min7: "m7",
1224
- dom7: "7",
1225
- dim7: "dim7",
1226
- m7b5: "m7b5",
1227
- minMaj7: "mMaj7",
1228
- aug7: "aug7",
1229
- augMaj7: "augMaj7",
1230
- majb5: "maj(b5)",
1231
- "6": "6",
1232
- min6: "m6",
1233
- "6/9": "6/9",
1234
- sus2: "sus2",
1235
- sus4: "sus4",
1236
- add9: "add9",
1237
- add11: "add11",
1238
- maj9: "maj9",
1239
- min9: "m9",
1240
- dom9: "9",
1241
- "7b9": "7b9",
1242
- "7#9": "7#9",
1243
- "7#11": "7#11",
1244
- "7b13": "7b13",
1245
- "11": "11",
1246
- "13": "13",
1247
- "5": "5"
1248
- };
1249
- function pitchClass5(value) {
1250
- return (Math.trunc(value) % 12 + 12) % 12;
1251
- }
1252
- function makeSpelledChord(root, quality, bass) {
1253
- const chord = makeChord(
1254
- noteToPitchClass(root),
1255
- quality,
1256
- bass === void 0 ? void 0 : noteToPitchClass(bass)
1257
- );
1258
- chord.rootSpelling = { letter: root.letter, alter: root.alter };
1259
- if (bass !== void 0) {
1260
- chord.bassSpelling = { letter: bass.letter, alter: bass.alter };
1261
- }
1262
- return chord;
1263
- }
1264
- function parseChordSymbol(text) {
1265
- const trimmed = text.trim();
1266
- const rootMatch = ROOT_RE.exec(trimmed);
1267
- if (!rootMatch) {
1268
- throw new Error(`Invalid chord symbol: ${text}`);
1269
- }
1270
- const rootToken = rootMatch[0];
1271
- const rootNote = parseNote(rootToken);
1272
- const rest = trimmed.slice(rootToken.length);
1273
- const slashIndex = rest.lastIndexOf("/");
1274
- if (slashIndex !== -1) {
1275
- const before = rest.slice(0, slashIndex);
1276
- const after = rest.slice(slashIndex + 1);
1277
- const beforeQuality = QUALITY_MAP[before];
1278
- if (beforeQuality !== void 0 && BASS_RE.test(after)) {
1279
- return makeSpelledChord(rootNote, beforeQuality, parseNote(after));
1280
- }
1281
- }
1282
- const quality = QUALITY_MAP[rest];
1283
- if (quality === void 0) {
1284
- throw new Error(`Unrecognized chord quality: ${text}`);
1285
- }
1286
- return makeSpelledChord(rootNote, quality);
1287
- }
1288
- function pitchClassName(pc, hint, flats) {
1289
- if (flats === void 0 && hint !== void 0 && noteToPitchClass(hint) === pc) {
1290
- return formatNote(hint);
1291
- }
1292
- const note = midiToNote(60 + pc, flats ? "flat" : "sharp");
1293
- return formatNote({ letter: note.letter, alter: note.alter });
1294
- }
1295
- function formatChordSymbol(chord, opts) {
1296
- const rootPc = pitchClass5(chord.rootPc);
1297
- const rootName = pitchClassName(rootPc, chord.rootSpelling, opts?.flats);
1298
- const suffix = CANONICAL_SUFFIX[chord.quality];
1299
- let symbol = `${rootName}${suffix}`;
1300
- if (chord.bassPc !== void 0 && pitchClass5(chord.bassPc) !== rootPc) {
1301
- symbol += `/${pitchClassName(pitchClass5(chord.bassPc), chord.bassSpelling, opts?.flats)}`;
1302
- }
1303
- return symbol;
1304
- }
1305
-
1306
- // src/theory/counterpoint/index.ts
1307
- function createsVoiceCrossing(upperPitch, lowerPitch) {
1308
- return upperPitch < lowerPitch;
1309
- }
1310
- function simpleClass(semitones) {
1311
- return Math.abs(semitones) % 12;
1312
- }
1313
- function isPerfectClass(cls) {
1314
- return cls === 0 || cls === 7;
1315
- }
1316
- function similarMotion(aMove, bMove) {
1317
- return aMove !== 0 && bMove !== 0 && aMove > 0 === bMove > 0;
1318
- }
1319
- function bothVoicesMove(aMove, bMove) {
1320
- return aMove !== 0 && bMove !== 0;
1321
- }
1322
- function createsParallelPerfect(aPrev, aCur, bPrev, bCur) {
1323
- if (!bothVoicesMove(aCur - aPrev, bCur - bPrev)) {
1324
- return false;
1325
- }
1326
- const nowClass = simpleClass(aCur - bCur);
1327
- const prevClass = simpleClass(aPrev - bPrev);
1328
- return isPerfectClass(nowClass) && nowClass === prevClass;
1329
- }
1330
- function createsHiddenParallelPerfect(aPrev, aCur, bPrev, bCur) {
1331
- const aMove = aCur - aPrev;
1332
- const bMove = bCur - bPrev;
1333
- if (!similarMotion(aMove, bMove)) {
1334
- return false;
1335
- }
1336
- const nowClass = simpleClass(aCur - bCur);
1337
- const prevClass = simpleClass(aPrev - bPrev);
1338
- if (!isPerfectClass(nowClass) || prevClass === nowClass) {
1339
- return false;
1340
- }
1341
- const upperMove = aCur >= bCur ? aMove : bMove;
1342
- if (Math.abs(upperMove) <= 2) {
1343
- return false;
1344
- }
1345
- return true;
1346
- }
1347
- function createsVoiceOverlap(upperPrev, upperCur, lowerPrev, lowerCur) {
1348
- return upperCur < lowerPrev || lowerCur > upperPrev;
1349
- }
1350
- function exceedsSpacing(upperPitch, lowerPitch, maxSemitones = 12) {
1351
- return Math.abs(upperPitch - lowerPitch) > maxSemitones;
1352
- }
1353
-
1354
- // src/theory/voicing/internal.ts
1355
- var DEFAULT_MAX_SPACING = 12;
1356
- var VIOLATION_PENALTY = 1e3;
1357
- var MISSING_TONE_PENALTY = 500;
1358
- var POOR_DOUBLING_PENALTY = 4;
1359
- var MAX_CANDIDATES = 4e3;
1360
- function pitchClass6(value) {
1361
- return (Math.trunc(value) % 12 + 12) % 12;
1362
- }
1363
- function pitchesForPc(pc, range) {
1364
- const result = [];
1365
- for (let midi = Math.ceil(range.min); midi <= range.max; midi += 1) {
1366
- if (pitchClass6(midi) === pc) {
1367
- result.push(midi);
1368
- }
1369
- }
1370
- const center = (range.min + range.max) / 2;
1371
- return result.sort((a, b) => {
1372
- const da = Math.abs(a - center);
1373
- const db = Math.abs(b - center);
1374
- return da === db ? a - b : da - db;
1375
- });
1376
- }
1377
- function enumerateVoicings(chord, ranges, maxSpacing) {
1378
- const chordPcs = chordPitchClasses(chord);
1379
- const bassPc = pitchClass6(chord.bassPc ?? chord.rootPc);
1380
- const results = [];
1381
- const current = [];
1382
- const build = (voice) => {
1383
- if (results.length >= MAX_CANDIDATES) {
1384
- return;
1385
- }
1386
- if (voice === ranges.length) {
1387
- results.push([...current]);
1388
- return;
1389
- }
1390
- const range = ranges[voice];
1391
- if (range === void 0) {
1392
- return;
1393
- }
1394
- const pcs = voice === 0 ? [bassPc] : chordPcs;
1395
- const prev = current[voice - 1];
1396
- for (const pc of pcs) {
1397
- for (const pitch of pitchesForPc(pc, range)) {
1398
- if (prev !== void 0) {
1399
- if (pitch < prev) {
1400
- continue;
1401
- }
1402
- const spacingLimit = voice === 1 ? maxSpacing + 12 : maxSpacing;
1403
- if (pitch - prev > spacingLimit) {
1404
- continue;
1405
- }
1406
- }
1407
- current.push(pitch);
1408
- build(voice + 1);
1409
- current.pop();
1410
- }
1411
- }
1412
- };
1413
- build(0);
1414
- return results;
1415
- }
1416
- function structuralPenalty(pitches, chord) {
1417
- const counts = /* @__PURE__ */ new Map();
1418
- for (const pitch of pitches) {
1419
- const pc = pitchClass6(pitch);
1420
- counts.set(pc, (counts.get(pc) ?? 0) + 1);
1421
- }
1422
- let penalty = 0;
1423
- for (const pc of chordPitchClasses(chord)) {
1424
- if (!counts.has(pc)) {
1425
- penalty += MISSING_TONE_PENALTY;
1426
- }
1427
- }
1428
- const rootPc = pitchClass6(chord.rootPc);
1429
- const fifthPc = pitchClass6(chord.rootPc + 7);
1430
- for (const [pc, count] of counts) {
1431
- if (count > 1 && pc !== rootPc && pc !== fifthPc) {
1432
- penalty += (count - 1) * POOR_DOUBLING_PENALTY;
1433
- }
1434
- }
1435
- return penalty;
1436
- }
1437
- function violationCount(prev, cur, maxSpacing) {
1438
- let count = 0;
1439
- for (let lower = 0; lower < cur.length; lower += 1) {
1440
- for (let upper = lower + 1; upper < cur.length; upper += 1) {
1441
- const prevLower = prev[lower];
1442
- const prevUpper = prev[upper];
1443
- const curLower = cur[lower];
1444
- const curUpper = cur[upper];
1445
- if (prevLower === void 0 || prevUpper === void 0 || curLower === void 0 || curUpper === void 0) {
1446
- continue;
1447
- }
1448
- if (createsParallelPerfect(prevUpper, curUpper, prevLower, curLower)) {
1449
- count += 1;
1450
- }
1451
- if (createsVoiceCrossing(curUpper, curLower)) {
1452
- count += 1;
1453
- }
1454
- if (upper === lower + 1) {
1455
- if (createsVoiceOverlap(prevUpper, curUpper, prevLower, curLower)) {
1456
- count += 1;
1457
- }
1458
- if (lower > 0 && exceedsSpacing(curUpper, curLower, maxSpacing)) {
1459
- count += 1;
1460
- }
1461
- }
1462
- }
1463
- }
1464
- return count;
1465
- }
1466
-
1467
- // src/theory/voicing/satb.ts
1468
- var SATB_RANGES = [
1469
- { min: 40, max: 60 },
1470
- { min: 48, max: 67 },
1471
- { min: 55, max: 74 },
1472
- { min: 60, max: 79 }
1473
- ];
1474
- var DERIVED_LOW = 40;
1475
- var DERIVED_HIGH = 79;
1476
- var DERIVED_SPAN = 19;
1477
- function resolveRanges(opts) {
1478
- if (opts?.ranges !== void 0) {
1479
- if (opts.ranges.length === 0) {
1480
- throw new Error("ranges must contain at least one voice range");
1481
- }
1482
- assertGenerationBudget(opts.ranges.length, "voice ranges", 128);
1483
- return opts.ranges.map((range, index) => {
1484
- assertFiniteNumber(range.min, `ranges[${index}].min`);
1485
- assertFiniteNumber(range.max, `ranges[${index}].max`);
1486
- if (range.min > range.max) {
1487
- throw new RangeError(`ranges[${index}].min must not exceed max`);
1488
- }
1489
- assertGenerationBudget(
1490
- Math.floor(range.max) - Math.ceil(range.min) + 1,
1491
- `ranges[${index}] span`,
1492
- 4096
1493
- );
1494
- return { ...range };
1495
- });
1496
- }
1497
- const voices = opts?.voices ?? 4;
1498
- assertPositiveInt(voices, "voices", 128);
1499
- if (voices === 4) {
1500
- return SATB_RANGES.map((range) => ({ ...range }));
1501
- }
1502
- if (voices === 1) {
1503
- return [{ min: DERIVED_LOW, max: DERIVED_HIGH }];
1504
- }
1505
- const ranges = [];
1506
- for (let i = 0; i < voices; i += 1) {
1507
- const min = Math.round(
1508
- DERIVED_LOW + i * (DERIVED_HIGH - DERIVED_SPAN - DERIVED_LOW) / (voices - 1)
1509
- );
1510
- ranges.push({ min, max: min + DERIVED_SPAN });
1511
- }
1512
- return ranges;
1513
- }
1514
- function voiceChord(chord, opts) {
1515
- const ranges = resolveRanges(opts);
1516
- const maxSpacing = opts?.maxSpacing ?? DEFAULT_MAX_SPACING;
1517
- assertFiniteNumber(maxSpacing, "maxSpacing");
1518
- if (maxSpacing < 0) throw new RangeError("maxSpacing must be non-negative");
1519
- const candidates = enumerateVoicings(chord, ranges, maxSpacing);
1520
- let best;
1521
- let bestScore = Number.POSITIVE_INFINITY;
1522
- for (const candidate of candidates) {
1523
- let score = structuralPenalty(candidate, chord);
1524
- for (let i = 0; i < candidate.length; i += 1) {
1525
- const pitch = candidate[i];
1526
- const range = ranges[i];
1527
- if (pitch === void 0 || range === void 0) {
1528
- continue;
1529
- }
1530
- score += Math.abs(pitch - (range.min + range.max) / 2);
1531
- }
1532
- if (score < bestScore) {
1533
- bestScore = score;
1534
- best = candidate;
1535
- }
1536
- }
1537
- if (best === void 0) {
1538
- throw new Error("no voicing satisfies the given ranges");
1539
- }
1540
- return best;
1541
- }
1542
- function voiceProgression(chords, opts) {
1543
- assertGenerationBudget(chords.length * 4e3, "voiced progression search");
1544
- const ranges = resolveRanges(opts);
1545
- const maxSpacing = opts?.maxSpacing ?? DEFAULT_MAX_SPACING;
1546
- assertFiniteNumber(maxSpacing, "maxSpacing");
1547
- if (maxSpacing < 0) throw new RangeError("maxSpacing must be non-negative");
1548
- const result = [];
1549
- let prev;
1550
- for (const chord of chords) {
1551
- if (prev === void 0) {
1552
- prev = voiceChord(chord, opts);
1553
- result.push(prev);
1554
- continue;
1555
- }
1556
- const candidates = enumerateVoicings(chord, ranges, maxSpacing);
1557
- let best;
1558
- let bestScore = Number.POSITIVE_INFINITY;
1559
- for (const candidate of candidates) {
1560
- const score = structuralPenalty(candidate, chord) + voiceLeadingCost(prev, candidate) + VIOLATION_PENALTY * violationCount(prev, candidate, maxSpacing);
1561
- if (score < bestScore) {
1562
- bestScore = score;
1563
- best = candidate;
1564
- }
1565
- }
1566
- if (best === void 0) {
1567
- throw new Error("no voicing satisfies the given ranges");
1568
- }
1569
- result.push(best);
1570
- prev = best;
1571
- }
1572
- return result;
1573
- }
1574
-
1575
- // src/theory/voicing/leading.ts
1576
- var HIDDEN_PERFECT_PENALTY = 6;
1577
- function voiceLeadingCost(from, to) {
1578
- if (from.length !== to.length) {
1579
- return Number.POSITIVE_INFINITY;
1580
- }
1581
- let total = 0;
1582
- for (let i = 0; i < from.length; i += 1) {
1583
- const a = from[i];
1584
- const b = to[i];
1585
- if (a === void 0 || b === void 0) {
1586
- continue;
1587
- }
1588
- total += Math.abs(b - a);
1589
- }
1590
- if (from.length >= 2) {
1591
- const bassPrev = from[0];
1592
- const bassCur = to[0];
1593
- const sopPrev = from[from.length - 1];
1594
- const sopCur = to[to.length - 1];
1595
- if (bassPrev !== void 0 && bassCur !== void 0 && sopPrev !== void 0 && sopCur !== void 0 && createsHiddenParallelPerfect(bassPrev, bassCur, sopPrev, sopCur)) {
1596
- total += HIDDEN_PERFECT_PENALTY;
1597
- }
1598
- }
1599
- return total;
1600
- }
1601
-
1602
- // src/theory/voicing/styled.ts
1603
- var DEFAULT_STYLE_OCTAVE = 4;
1604
- function dedupePcs(pcs) {
1605
- const seen = /* @__PURE__ */ new Set();
1606
- const result = [];
1607
- for (const pc of pcs) {
1608
- if (!seen.has(pc)) {
1609
- seen.add(pc);
1610
- result.push(pc);
1611
- }
1612
- }
1613
- return result;
1614
- }
1615
- function lowestPitchAtOrAbove(pc, floor) {
1616
- return floor + ((pc - pitchClass6(floor)) % 12 + 12) % 12;
1617
- }
1618
- function nearestPc(target, pcs) {
1619
- let best = pcs[0] ?? target;
1620
- let bestDist = 12;
1621
- for (const pc of pcs) {
1622
- const dist = Math.min(((pc - target) % 12 + 12) % 12, ((target - pc) % 12 + 12) % 12);
1623
- if (dist < bestDist) {
1624
- bestDist = dist;
1625
- best = pc;
1626
- }
1627
- }
1628
- return best;
1629
- }
1630
- function voiceChordStyled(chord, opts) {
1631
- const style = opts?.style ?? "close";
1632
- const octave = opts?.octave ?? DEFAULT_STYLE_OCTAVE;
1633
- assertInteger(octave, "styled voicing octave", -10, 10);
1634
- if (opts?.topNote !== void 0) {
1635
- assertFiniteNumber(opts.topNote, "styled voicing topNote");
1636
- }
1637
- const base = 12 * (octave + 1);
1638
- const rootPc = pitchClass6(chord.rootPc);
1639
- const bassPc = pitchClass6(chord.bassPc ?? chord.rootPc);
1640
- const omitRoot = style === "rootless" || opts?.rootless === true;
1641
- let order = dedupePcs(chord.intervals.map((interval) => pitchClass6(chord.rootPc + interval)));
1642
- const bassIndex = order.indexOf(bassPc);
1643
- if (bassIndex > 0) {
1644
- order = [...order.slice(bassIndex), ...order.slice(0, bassIndex)];
1645
- } else if (bassIndex < 0) {
1646
- order = [bassPc, ...order];
1647
- }
1648
- if (style === "shell") {
1649
- const roles = order.map((pc) => chordToneRole(pc, chord));
1650
- const guide = roles.includes("seventh") ? "seventh" : roles.includes("sixth") ? "sixth" : "fifth";
1651
- order = order.filter((_pc, i) => {
1652
- const role = roles[i];
1653
- return _pc === bassPc || role === "root" || role === "third" || role === guide;
1654
- });
1655
- }
1656
- if (omitRoot) {
1657
- order = order.filter((pc) => pc !== rootPc || chord.bassPc !== void 0 && pc === bassPc);
1658
- }
1659
- if (order.length === 0) {
1660
- return [];
1661
- }
1662
- if (opts?.topNote !== void 0) {
1663
- const target = order.includes(pitchClass6(opts.topNote)) ? pitchClass6(opts.topNote) : nearestPc(pitchClass6(opts.topNote), order);
1664
- const targetIndex = order.indexOf(target);
1665
- order = [...order.slice(targetIndex + 1), ...order.slice(0, targetIndex + 1)];
1666
- }
1667
- const stack = [];
1668
- let prev;
1669
- for (const pc of order) {
1670
- if (prev === void 0) {
1671
- prev = lowestPitchAtOrAbove(pc, base);
1672
- } else {
1673
- let delta = ((pc - pitchClass6(prev)) % 12 + 12) % 12;
1674
- if (delta === 0) {
1675
- delta = 12;
1676
- }
1677
- prev += delta;
1678
- }
1679
- stack.push(prev);
1680
- }
1681
- if (style === "drop2" && stack.length >= 2) {
1682
- stack[stack.length - 2] = (stack[stack.length - 2] ?? 0) - 12;
1683
- } else if (style === "drop3" && stack.length >= 3) {
1684
- stack[stack.length - 3] = (stack[stack.length - 3] ?? 0) - 12;
1685
- }
1686
- if (chord.bassPc !== void 0) {
1687
- const bassIndexInStack = stack.findIndex((pitch) => pitchClass6(pitch) === bassPc);
1688
- if (bassIndexInStack >= 0) {
1689
- const otherLowest = Math.min(
1690
- ...stack.filter((_pitch, index) => index !== bassIndexInStack),
1691
- Number.POSITIVE_INFINITY
1692
- );
1693
- while ((stack[bassIndexInStack] ?? 0) >= otherLowest) {
1694
- stack[bassIndexInStack] = (stack[bassIndexInStack] ?? 0) - 12;
1695
- }
1696
- }
1697
- }
1698
- return stack.sort((a, b) => a - b);
1699
- }
1700
-
1701
- // src/model/shared.ts
1702
- function mod125(n) {
1703
- return (n % 12 + 12) % 12;
1704
- }
1705
- function spellPitchClassBare(pc, spelling) {
1706
- const spelled = midiToNote(60 + mod125(pc), spelling);
1707
- return { letter: spelled.letter, alter: spelled.alter };
1708
- }
1709
-
1710
- // src/model/note.ts
1711
- function copyNote(data) {
1712
- const copy = { letter: data.letter, alter: data.alter };
1713
- if (data.octave !== void 0) {
1714
- copy.octave = data.octave;
1715
- }
1716
- return copy;
1717
- }
1718
- var Note = class _Note {
1719
- #data;
1720
- /**
1721
- * Wrap a plain note object.
1722
- *
1723
- * @param data The spelled note; it is copied, never retained or mutated.
1724
- */
1725
- constructor(data) {
1726
- this.#data = copyNote(data);
1727
- }
1728
- /**
1729
- * Parse scientific pitch notation (e.g. `'C#4'`, `'Bb'`, `'F##3'`).
1730
- *
1731
- * @param name The note text.
1732
- * @returns The parsed note.
1733
- * @throws If the text is not a valid note.
1734
- */
1735
- static of(name) {
1736
- return new _Note(parseNote(name));
1737
- }
1738
- /**
1739
- * Name a MIDI number (middle C = C4 = 60) as a note.
1740
- *
1741
- * @param midi The MIDI number.
1742
- * @param spelling Whether to prefer sharps or flats for black keys.
1743
- * @returns The spelled note, with octave.
1744
- */
1745
- static fromMidi(midi, spelling = "sharp") {
1746
- return new _Note(midiToNote(midi, spelling));
1747
- }
1748
- /**
1749
- * Wrap an existing plain note object.
1750
- *
1751
- * @param data The plain note.
1752
- * @returns The wrapped note.
1753
- */
1754
- static fromData(data) {
1755
- return new _Note(data);
1756
- }
1757
- /** The note rendered as scientific pitch notation, e.g. `'G4'` or `'Bb'`. */
1758
- get name() {
1759
- return formatNote(this.#data);
1760
- }
1761
- /** The pitch class (0..11), ignoring octave. */
1762
- get pitchClass() {
1763
- return noteToPitchClass(this.#data);
1764
- }
1765
- /**
1766
- * The MIDI number (middle C = C4 = 60).
1767
- *
1768
- * @throws If the note has no octave and therefore no fixed pitch.
1769
- */
1770
- get midi() {
1771
- if (this.#data.octave === void 0) {
1772
- throw new Error(`note ${this.name} has no octave, so it has no MIDI number`);
1773
- }
1774
- return noteToMidi(this.#data);
1775
- }
1776
- /** The diatonic letter number: 0..6 for C..B. */
1777
- get letter() {
1778
- return this.#data.letter;
1779
- }
1780
- /** The chromatic alteration in semitones: -1 flat, 0 natural, +1 sharp, ... */
1781
- get alter() {
1782
- return this.#data.alter;
1783
- }
1784
- /** The octave (scientific pitch notation), or undefined for a bare pitch class. */
1785
- get octave() {
1786
- return this.#data.octave;
1787
- }
1788
- /** A copy of the underlying plain note object. */
1789
- get data() {
1790
- return copyNote(this.#data);
1791
- }
1792
- /**
1793
- * Transpose by a signed number of semitones.
1794
- *
1795
- * When the note carries an octave the transposition happens in MIDI space and
1796
- * the result is spelled with a sharp preference. An octave-less note stays
1797
- * octave-less: only its pitch class is moved. Transposing by zero is the
1798
- * identity: the original spelling is preserved (no enharmonic respelling).
1799
- *
1800
- * @param semitones The signed semitone offset.
1801
- * @returns The transposed note.
1802
- */
1803
- transpose(semitones) {
1804
- if (semitones === 0) {
1805
- return new _Note(this.#data);
1806
- }
1807
- if (this.#data.octave !== void 0) {
1808
- return _Note.fromMidi(this.midi + semitones);
1809
- }
1810
- return new _Note(spellPitchClassBare(this.pitchClass + semitones, "sharp"));
1811
- }
1812
- /**
1813
- * The spelled interval from this note to another.
1814
- *
1815
- * @param other The second note.
1816
- * @returns The diatonic number, quality, and semitone span.
1817
- */
1818
- intervalTo(other) {
1819
- return spelledInterval(this.#data, other.#data);
1820
- }
1821
- /**
1822
- * Whether another note has the same letter, alteration, and octave.
1823
- *
1824
- * @param other The note to compare.
1825
- * @returns True if the spellings are identical.
1826
- */
1827
- equals(other) {
1828
- return this.#data.letter === other.#data.letter && this.#data.alter === other.#data.alter && this.#data.octave === other.#data.octave;
1829
- }
1830
- /**
1831
- * The plain note data, for JSON serialization.
1832
- *
1833
- * Private class fields do not serialize, so an explicit `toJSON` keeps
1834
- * `JSON.stringify(note)` from collapsing to `{}`.
1835
- *
1836
- * @returns A copy of the underlying plain note object.
1837
- */
1838
- toJSON() {
1839
- return this.data;
1840
- }
1841
- };
1842
-
1843
- // src/model/progression.ts
1844
- var Progression = class _Progression {
1845
- #chords;
1846
- #key;
1847
- /**
1848
- * Wrap a chord sequence.
1849
- *
1850
- * @param chords The chords in order; the array is copied.
1851
- * @param key Optional key context for analysis methods.
1852
- */
1853
- constructor(chords, key) {
1854
- this.#chords = [...chords];
1855
- this.#key = key;
1856
- }
1857
- /** A copy of the chord sequence. */
1858
- get chords() {
1859
- return [...this.#chords];
1860
- }
1861
- /** The carried key context, if any. */
1862
- get key() {
1863
- return this.#key;
1864
- }
1865
- /** The number of chords. */
1866
- get length() {
1867
- return this.#chords.length;
1868
- }
1869
- /**
1870
- * A copy of this progression with a chord appended.
1871
- *
1872
- * @param chord The chord to append.
1873
- * @returns The new progression.
1874
- */
1875
- add(chord) {
1876
- return new _Progression([...this.#chords, chord], this.#key);
1877
- }
1878
- /**
1879
- * A copy of this progression carrying the given key context.
1880
- *
1881
- * @param key The key context to attach.
1882
- * @returns The new progression.
1883
- */
1884
- withKey(key) {
1885
- return new _Progression(this.#chords, key);
1886
- }
1887
- /**
1888
- * Voice the progression with smooth voice leading.
1889
- *
1890
- * @param opts Voicing options; defaults to four SATB voices.
1891
- * @returns One ascending voicing (MIDI pitches) per chord.
1892
- * @throws If any chord admits no voicing within the given ranges.
1893
- */
1894
- voice(opts) {
1895
- return voiceProgression(
1896
- this.#chords.map((chord) => chord.data),
1897
- opts
1898
- );
1899
- }
1900
- /**
1901
- * The Roman numeral of each chord in a key.
1902
- *
1903
- * @param key Key to analyze in; falls back to the carried context.
1904
- * @returns One numeral per chord.
1905
- * @throws If no key is given and none is carried.
1906
- */
1907
- roman(key) {
1908
- const resolved = this.#resolveKey(key);
1909
- return this.#chords.map((chord) => chord.roman(resolved));
1910
- }
1911
- /**
1912
- * The harmonic function of each chord in a key.
1913
- *
1914
- * @param key Key to analyze in; falls back to the carried context.
1915
- * @returns One function per chord.
1916
- * @throws If no key is given and none is carried.
1917
- */
1918
- functions(key) {
1919
- const resolved = this.#resolveKey(key);
1920
- return this.#chords.map((chord) => chord.function(resolved));
1921
- }
1922
- /**
1923
- * Analyze every chord and classify the closing cadence.
1924
- *
1925
- * The cadence is detected on the final chord pair and is null when the
1926
- * progression has fewer than two chords.
1927
- *
1928
- * @param key Key to analyze in; falls back to the carried context.
1929
- * @returns Per-chord analyses and the closing cadence.
1930
- * @throws If no key is given and none is carried.
1931
- */
1932
- analyze(key) {
1933
- const resolved = this.#resolveKey(key);
1934
- const chords = this.#chords.map((chord) => chord.analyze(resolved));
1935
- const from = this.#chords[this.#chords.length - 2];
1936
- const to = this.#chords[this.#chords.length - 1];
1937
- const cadence = from !== void 0 && to !== void 0 ? detectCadence(from.data, to.data, resolved.scale) : null;
1938
- return { chords, cadence };
1939
- }
1940
- /**
1941
- * The plain progression data, for JSON serialization.
1942
- *
1943
- * Private class fields do not serialize, so an explicit `toJSON` keeps
1944
- * `JSON.stringify(progression)` from collapsing to `{}`. The chords are
1945
- * emitted as plain data and the carried key, when present, as its own data.
1946
- *
1947
- * @returns The chord data sequence and the carried key, if any.
1948
- */
1949
- toJSON() {
1950
- return {
1951
- chords: this.#chords.map((chord) => chord.data),
1952
- key: this.#key?.toJSON()
1953
- };
1954
- }
1955
- /** Resolve the key for an analysis method: explicit first, then carried. */
1956
- #resolveKey(key) {
1957
- const resolved = key ?? this.#key;
1958
- if (resolved === void 0) {
1959
- throw new Error("progression has no key context; pass a Key or attach one with withKey()");
1960
- }
1961
- return resolved;
1962
- }
1963
- };
1964
-
1965
- // src/model/chord.ts
1966
- function copyChord(data) {
1967
- const copy = {
1968
- rootPc: data.rootPc,
1969
- quality: data.quality,
1970
- intervals: [...data.intervals]
1971
- };
1972
- if (data.bassPc !== void 0) {
1973
- copy.bassPc = data.bassPc;
1974
- }
1975
- if (data.rootSpelling !== void 0) {
1976
- copy.rootSpelling = { letter: data.rootSpelling.letter, alter: data.rootSpelling.alter };
1977
- }
1978
- if (data.bassSpelling !== void 0) {
1979
- copy.bassSpelling = { letter: data.bassSpelling.letter, alter: data.bassSpelling.alter };
1980
- }
1981
- return copy;
1982
- }
1983
- var Chord = class _Chord {
1984
- #data;
1985
- #key;
1986
- /**
1987
- * Wrap a plain chord object.
1988
- *
1989
- * @param data The chord; it is copied, never retained or mutated.
1990
- * @param key Optional key context for analysis methods.
1991
- */
1992
- constructor(data, key) {
1993
- const copy = copyChord(data);
1994
- if (copy.rootSpelling === void 0 && key !== void 0) {
1995
- copy.rootSpelling = spellPitchClass(copy.rootPc, key.tonic.data, key.scale);
1996
- }
1997
- this.#data = copy;
1998
- this.#key = key;
1999
- }
2000
- /**
2001
- * Build a chord from a root and quality.
2002
- *
2003
- * @param root Root as a note name (e.g. `'Eb'`) or a pitch class.
2004
- * @param quality The chord quality.
2005
- * @param bass Optional slash-chord bass pitch class.
2006
- * @returns The chord (without key context).
2007
- */
2008
- static of(root, quality, bass) {
2009
- if (typeof root === "string") {
2010
- const rootNote = Note.of(root);
2011
- const data = makeChord(rootNote.pitchClass, quality, bass);
2012
- data.rootSpelling = { letter: rootNote.letter, alter: rootNote.alter };
2013
- return new _Chord(data);
2014
- }
2015
- return new _Chord(makeChord(root, quality, bass));
2016
- }
2017
- /**
2018
- * Wrap an existing plain chord object.
2019
- *
2020
- * @param data The plain chord.
2021
- * @returns The wrapped chord (without key context).
2022
- */
2023
- static from(data) {
2024
- return new _Chord(data);
2025
- }
2026
- /**
2027
- * Parse a lead-sheet chord symbol (e.g. `'Cmaj7'`, `'F#m7b5'`, `'C/G'`).
2028
- *
2029
- * @param symbol The chord symbol.
2030
- * @returns The chord (without key context).
2031
- * @throws If the root or quality is not recognized.
2032
- */
2033
- static parse(symbol) {
2034
- return new _Chord(parseChordSymbol(symbol));
2035
- }
2036
- /**
2037
- * Identify the chords matching a set of pitches, best interpretation first.
2038
- *
2039
- * @param pitches MIDI pitches or bare pitch classes.
2040
- * @returns Ranked chord interpretations (may be empty).
2041
- */
2042
- static detect(pitches, opts) {
2043
- return detectChord(pitches, opts).map(
2044
- (match) => new _Chord(makeChord(match.rootPc, match.quality, match.bassPc))
2045
- );
2046
- }
2047
- /**
2048
- * The single best chord interpretation of a pitch set.
2049
- *
2050
- * @param pitches MIDI pitches or bare pitch classes.
2051
- * @returns The top-ranked chord, or null when nothing matches.
2052
- */
2053
- static detectBest(pitches, opts) {
2054
- const best = detectChordBest(pitches, opts);
2055
- return best === null ? null : new _Chord(best);
2056
- }
2057
- /** The root pitch class (0..11). */
2058
- get rootPc() {
2059
- return this.#data.rootPc;
2060
- }
2061
- /** The chord quality. */
2062
- get quality() {
2063
- return this.#data.quality;
2064
- }
2065
- /** A copy of the semitone offsets above the root. */
2066
- get intervals() {
2067
- return [...this.#data.intervals];
2068
- }
2069
- /** The slash-chord bass pitch class, or undefined in root position. */
2070
- get bassPc() {
2071
- return this.#data.bassPc;
2072
- }
2073
- /** A copy of the underlying plain chord object. */
2074
- get data() {
2075
- return copyChord(this.#data);
2076
- }
2077
- /** The carried key context, if any. */
2078
- get key() {
2079
- return this.#key;
2080
- }
2081
- /**
2082
- * A copy of this chord carrying the given key context.
2083
- *
2084
- * @param key The key context to attach.
2085
- * @returns The new chord.
2086
- */
2087
- withKey(key) {
2088
- return new _Chord(this.#data, key);
2089
- }
2090
- /**
2091
- * The chord's sorted, deduplicated pitch classes.
2092
- *
2093
- * @returns Pitch classes ascending in [0, 11].
2094
- */
2095
- pitchClasses() {
2096
- return chordPitchClasses(this.#data);
2097
- }
2098
- /**
2099
- * The chord's Roman numeral in a key.
2100
- *
2101
- * @param key Key to analyze in; falls back to the carried context.
2102
- * @returns The Roman numeral string.
2103
- * @throws If no key is given and none is carried.
2104
- */
2105
- roman(key) {
2106
- return chordToRoman(this.#data, this.#resolveKey(key).scale);
2107
- }
2108
- /**
2109
- * The chord's harmonic function (tonic / subdominant / dominant) in a key.
2110
- *
2111
- * @param key Key to analyze in; falls back to the carried context.
2112
- * @returns The harmonic function.
2113
- * @throws If no key is given and none is carried.
2114
- */
2115
- function(key) {
2116
- return functionOf(this.#data, this.#resolveKey(key).scale);
2117
- }
2118
- /**
2119
- * Full functional analysis: function, borrowing, and Roman numeral.
2120
- *
2121
- * @param key Key to analyze in; falls back to the carried context.
2122
- * @returns The chord analysis.
2123
- * @throws If no key is given and none is carried.
2124
- */
2125
- analyze(key) {
2126
- return analyzeChord(this.#data, this.#resolveKey(key).scale);
2127
- }
2128
- /**
2129
- * Whether the chord is borrowed from the parallel mode (modal interchange).
2130
- *
2131
- * @param key Key to analyze in; falls back to the carried context.
2132
- * @returns True if the chord is borrowed.
2133
- * @throws If no key is given and none is carried.
2134
- */
2135
- isBorrowed(key) {
2136
- return isBorrowedChord(this.#data, this.#resolveKey(key).scale);
2137
- }
2138
- /**
2139
- * The origin of a non-diatonic chord (parallel mode or Neapolitan), or null.
2140
- *
2141
- * @param key Key to analyze in; falls back to the carried context.
2142
- * @returns The borrowing source, or null.
2143
- * @throws If no key is given and none is carried.
2144
- */
2145
- borrowedSource(key) {
2146
- return borrowedSource(this.#data, this.#resolveKey(key).scale);
2147
- }
2148
- /**
2149
- * The chord rendered as a lead-sheet symbol (e.g. `'Cmaj7'`, `'F#m7'`, `'C/G'`).
2150
- *
2151
- * @param opts Set `flats: true` to spell the root/bass with flats.
2152
- * @returns The chord symbol.
2153
- */
2154
- symbol(opts) {
2155
- return formatChordSymbol(this.#data, opts);
2156
- }
2157
- /**
2158
- * Realize the chord as one MIDI pitch per voice, ascending.
2159
- *
2160
- * @param opts Voicing options; defaults to four SATB voices.
2161
- * @returns MIDI pitches, ascending, one per voice.
2162
- * @throws If no voicing fits the given ranges.
2163
- */
2164
- voice(opts) {
2165
- return voiceChord(this.#data, opts);
2166
- }
2167
- /**
2168
- * Realize the chord as a single styled voicing (`close`, `drop2`, `drop3`,
2169
- * `shell`, or `rootless`), optionally constraining the top voice.
2170
- *
2171
- * @param opts Styled-voicing options; defaults to a close-position voicing.
2172
- * @returns MIDI pitches, ascending.
2173
- */
2174
- styledVoicing(opts) {
2175
- return voiceChordStyled(this.#data, opts);
2176
- }
2177
- /**
2178
- * The negative-harmony mirror of the chord about the key's tonic–dominant
2179
- * axis (major becomes minor and vice versa).
2180
- *
2181
- * @param key Key providing the reflection axis; falls back to the carried
2182
- * context.
2183
- * @returns The mirrored chord, keeping any key context.
2184
- * @throws If no key is given and none is carried.
2185
- */
2186
- negativeHarmony(key) {
2187
- const resolved = this.#resolveKey(key);
2188
- return new _Chord(negativeHarmonyMirror(this.#data, resolved.scale), key ?? this.#key);
2189
- }
2190
- /**
2191
- * The n-th inversion: a copy whose bass is the chord tone `n` steps above the
2192
- * root in the interval template (`invert(1)` puts the third in the bass).
2193
- * `n` wraps around the template length; negative values count backwards.
2194
- *
2195
- * `invert(0)` (and any `n` that wraps to it) is root position, so it carries
2196
- * no slash bass and equals the original chord.
2197
- *
2198
- * @param n The inversion number.
2199
- * @returns The inverted chord, keeping any key context.
2200
- * @throws If the chord has no intervals.
2201
- */
2202
- invert(n) {
2203
- const intervals = this.#data.intervals;
2204
- const length = intervals.length;
2205
- if (length === 0) {
2206
- throw new Error("cannot invert a chord with no intervals");
2207
- }
2208
- const index = (n % length + length) % length;
2209
- const data = copyChord(this.#data);
2210
- if (index === 0) {
2211
- delete data.bassPc;
2212
- delete data.bassSpelling;
2213
- } else {
2214
- data.bassPc = mod125(this.#data.rootPc + (intervals[index] ?? 0));
2215
- const rootSpelling = data.rootSpelling ?? (this.#key ? spellPitchClass(data.rootPc, this.#key.tonic.data, this.#key.scale) : spellPitchClassBare(data.rootPc, "sharp"));
2216
- const bassSpelling = spellChordFromRoot(data, rootSpelling)[index];
2217
- if (bassSpelling !== void 0) {
2218
- data.bassSpelling = bassSpelling;
2219
- }
2220
- }
2221
- return new _Chord(data, this.#key);
2222
- }
2223
- /**
2224
- * The named scales that fit over this chord, best fit first, rooted on the
2225
- * chord root.
2226
- *
2227
- * @returns The matching scales.
2228
- */
2229
- scales() {
2230
- return chordScales(this.#data);
2231
- }
2232
- /**
2233
- * The available tensions (usable non-chord, non-avoid scale tones) of a
2234
- * scale over this chord.
2235
- *
2236
- * @param scaleName A named scale, rooted on the chord root.
2237
- * @returns Tension pitch classes, ascending in [0, 11].
2238
- */
2239
- tensions(scaleName) {
2240
- return availableTensions(this.#data, scaleName);
2241
- }
2242
- /**
2243
- * The avoid notes (scale tones a semitone above a chord tone) of a scale
2244
- * over this chord.
2245
- *
2246
- * @param scaleName A named scale, rooted on the chord root.
2247
- * @returns Avoid-note pitch classes, ascending in [0, 11].
2248
- */
2249
- avoidNotes(scaleName) {
2250
- return avoidNotes(this.#data, scaleName);
2251
- }
2252
- /**
2253
- * Spell the chord tones with letter names, root first, in the key's spelling.
2254
- *
2255
- * @param key Key providing the spelled tonic; falls back to the carried
2256
- * context.
2257
- * @returns Spelled octave-less notes in the chord's own (tertian) order.
2258
- * @throws If no key is given and none is carried.
2259
- */
2260
- spell(key) {
2261
- const resolved = this.#resolveKey(key);
2262
- return spellChord(this.#data, resolved.tonic.data, resolved.scale).map(
2263
- (note) => new Note(note)
2264
- );
2265
- }
2266
- /**
2267
- * Start a progression with this chord followed by others, carrying this
2268
- * chord's key context (if any).
2269
- *
2270
- * @param others The chords following this one.
2271
- * @returns The progression.
2272
- */
2273
- progressionTo(...others) {
2274
- return new Progression([this, ...others], this.#key);
2275
- }
2276
- /**
2277
- * Whether another chord has the same root, quality, intervals, and bass.
2278
- * Key context is not compared.
2279
- *
2280
- * @param other The chord to compare.
2281
- * @returns True if the chord data is identical.
2282
- */
2283
- equals(other) {
2284
- const a = this.#data;
2285
- const b = other.#data;
2286
- return a.rootPc === b.rootPc && a.quality === b.quality && a.bassPc === b.bassPc && a.intervals.length === b.intervals.length && a.intervals.every((interval, i) => interval === b.intervals[i]);
2287
- }
2288
- /**
2289
- * The plain chord data, for JSON serialization.
2290
- *
2291
- * @returns A copy of the underlying plain chord object.
2292
- */
2293
- toJSON() {
2294
- return this.data;
2295
- }
2296
- /** Resolve the key for an analysis method: explicit first, then carried. */
2297
- #resolveKey(key) {
2298
- const resolved = key ?? this.#key;
2299
- if (resolved === void 0) {
2300
- throw new Error("chord has no key context; pass a Key or attach one with withKey()");
2301
- }
2302
- return resolved;
2303
- }
2304
- };
2305
-
2306
- // src/model/interval.ts
2307
- var Interval = class _Interval {
2308
- #number;
2309
- #quality;
2310
- #semitones;
2311
- constructor(numberValue, quality, semitones) {
2312
- this.#number = numberValue;
2313
- this.#quality = quality;
2314
- this.#semitones = semitones;
2315
- }
2316
- /**
2317
- * The spelled interval between two notes.
2318
- *
2319
- * @param a The first note.
2320
- * @param b The second note.
2321
- * @returns The interval from `a` to `b`.
2322
- */
2323
- static between(a, b) {
2324
- const spelled = a.intervalTo(b);
2325
- return new _Interval(spelled.number, spelled.quality, spelled.semitones);
2326
- }
2327
- /**
2328
- * Build an interval from explicit components.
2329
- *
2330
- * @param numberValue Diatonic size: 1 = unison, 2 = second, ... 8 = octave.
2331
- * @param quality Quality label: `'P'`, `'M'`, `'m'`, or repeated `'A'`/`'d'`.
2332
- * @param semitones Signed semitone span.
2333
- * @returns The interval.
2334
- */
2335
- static of(numberValue, quality, semitones) {
2336
- return new _Interval(numberValue, quality, semitones);
2337
- }
2338
- /** Diatonic size: 1 = unison, 2 = second, ... 8 = octave, and beyond. */
2339
- get number() {
2340
- return this.#number;
2341
- }
2342
- /** Quality label: `'P'`, `'M'`, `'m'`, or repeated `'A'`/`'d'`. */
2343
- get quality() {
2344
- return this.#quality;
2345
- }
2346
- /** Signed semitone span. */
2347
- get semitones() {
2348
- return this.#semitones;
2349
- }
2350
- /** A readable label composed of quality and number, e.g. `'P5'` or `'M3'`. */
2351
- get name() {
2352
- return `${this.#quality}${this.#number}`;
2353
- }
2354
- /**
2355
- * The plain interval data, for JSON serialization.
2356
- *
2357
- * Private class fields do not serialize, so an explicit `toJSON` keeps
2358
- * `JSON.stringify(interval)` from collapsing to `{}`.
2359
- *
2360
- * @returns The diatonic number, quality, and semitone span.
2361
- */
2362
- toJSON() {
2363
- return { number: this.#number, quality: this.#quality, semitones: this.#semitones };
2364
- }
2365
- };
2366
-
2367
- // src/model/key.ts
2368
- function resolveTonic(root, spelling) {
2369
- return typeof root === "string" ? Note.of(root) : new Note(spellPitchClassBare(root, spelling));
2370
- }
2371
- function accidentalLoad(tonic, scale) {
2372
- return spellScale(tonic, scale).reduce((sum, note) => sum + Math.abs(note.alter), 0);
2373
- }
2374
- function bestTonicForScale(rootPc, scale) {
2375
- const sharp = spellPitchClassBare(rootPc, "sharp");
2376
- const flat = spellPitchClassBare(rootPc, "flat");
2377
- if (sharp.letter === flat.letter && sharp.alter === flat.alter) {
2378
- return new Note(sharp);
2379
- }
2380
- return accidentalLoad(flat, scale) <= accidentalLoad(sharp, scale) ? new Note(flat) : new Note(sharp);
2381
- }
2382
- var Key = class _Key {
2383
- #scale;
2384
- #tonic;
2385
- /**
2386
- * Wrap a key/scale and its spelled tonic.
2387
- *
2388
- * @param scale The key/scale; its root is normalized to a pitch class.
2389
- * @param tonic The spelled tonic anchoring letter-name spelling.
2390
- */
2391
- constructor(scale, tonic) {
2392
- this.#scale = { rootPc: mod125(scale.rootPc), modeMask12: scale.modeMask12 };
2393
- this.#tonic = tonic;
2394
- }
2395
- /**
2396
- * A major key.
2397
- *
2398
- * @param root Tonic as a note name (e.g. `'Eb'`) or a pitch class; a numeric
2399
- * root is spelled with whichever accidental side yields the fewest
2400
- * accidentals across the scale.
2401
- * @returns The major key.
2402
- */
2403
- static major(root) {
2404
- if (typeof root === "string") {
2405
- const tonic = Note.of(root);
2406
- return new _Key(majorKey(tonic.pitchClass), tonic);
2407
- }
2408
- const scale = majorKey(root);
2409
- return new _Key(scale, bestTonicForScale(root, scale));
2410
- }
2411
- /**
2412
- * A natural-minor key.
2413
- *
2414
- * @param root Tonic as a note name or a pitch class; a numeric root is
2415
- * spelled with whichever accidental side yields the fewest accidentals
2416
- * across the scale.
2417
- * @returns The minor key.
2418
- */
2419
- static minor(root) {
2420
- if (typeof root === "string") {
2421
- const tonic = Note.of(root);
2422
- return new _Key(minorKey(tonic.pitchClass), tonic);
2423
- }
2424
- const scale = minorKey(root);
2425
- return new _Key(scale, bestTonicForScale(root, scale));
2426
- }
2427
- /**
2428
- * A key on a named scale (e.g. `'dorian'`, `'harmonicMinor'`).
2429
- *
2430
- * @param name The scale name, a key of the scale module's named-scale table.
2431
- * @param root Tonic as a note name or a pitch class.
2432
- * @returns The key.
2433
- * @throws If the name is not a known scale.
2434
- */
2435
- static named(name, root) {
2436
- const tonic = resolveTonic(root, "sharp");
2437
- return new _Key(scaleByName(name, tonic.pitchClass), tonic);
2438
- }
2439
- /**
2440
- * Wrap an existing `KeyScale`, synthesizing a spelled tonic when none is
2441
- * given (flat-preferred for minor-third scales, sharp-preferred otherwise).
2442
- *
2443
- * @param scale The key/scale to wrap.
2444
- * @param tonic Optional spelled tonic.
2445
- * @returns The key.
2446
- */
2447
- static of(scale, tonic) {
2448
- const spelled = tonic ?? new Note(spellPitchClassBare(scale.rootPc, isMinorKey(scale) ? "flat" : "sharp"));
2449
- return new _Key(scale, spelled);
2450
- }
2451
- /** A copy of the underlying plain `KeyScale`. */
2452
- get scale() {
2453
- return { rootPc: this.#scale.rootPc, modeMask12: this.#scale.modeMask12 };
2454
- }
2455
- /** The spelled tonic. */
2456
- get tonic() {
2457
- return this.#tonic;
2458
- }
2459
- /** The tonic pitch class (0..11). */
2460
- get rootPc() {
2461
- return this.#scale.rootPc;
2462
- }
2463
- /** Whether the scale has a minor third and no major third. */
2464
- get isMinor() {
2465
- return isMinorKey(this.#scale);
2466
- }
2467
- /**
2468
- * The scale's pitch classes in ascending scale-degree order (degree 0 first).
2469
- *
2470
- * @returns One pitch class per scale degree.
2471
- */
2472
- pitchClasses() {
2473
- return scaleTonesInDegreeOrder(this.#scale);
2474
- }
2475
- /**
2476
- * The spelled scale, one note per degree (e.g. C D E F G A B for C major).
2477
- *
2478
- * @returns Spelled octave-less notes in scale-degree order.
2479
- */
2480
- notes() {
2481
- return spellScale(this.#tonic.data, this.#scale).map((note) => new Note(note));
2482
- }
2483
- /**
2484
- * Alias of {@link Key.notes}.
2485
- *
2486
- * @returns Spelled octave-less notes in scale-degree order.
2487
- */
2488
- spell() {
2489
- return this.notes();
2490
- }
2491
- /**
2492
- * The spelled scale as letter-name strings.
2493
- *
2494
- * @returns One name per scale degree.
2495
- */
2496
- noteNames() {
2497
- return this.notes().map((note) => note.name);
2498
- }
2499
- /**
2500
- * Build a chord on a scale degree, carrying this key as context.
2501
- *
2502
- * With an explicit quality the quality's interval template is attached to the
2503
- * degree's diatonic root; without one the scale-correct diatonic triad is
2504
- * stacked (e.g. a diminished triad on the leading tone of a major key).
2505
- *
2506
- * @param degree 0-based scale degree of the chord root.
2507
- * @param quality Optional chord quality.
2508
- * @returns The chord, with this key attached.
2509
- */
2510
- chord(degree, quality) {
2511
- const data = quality === void 0 ? diatonicTriad(degree, this.#scale) : chordFromDegree(degree, quality, this.#scale);
2512
- return new Chord(data, this);
2513
- }
2514
- /**
2515
- * The diatonic triad on a scale degree, carrying this key as context.
2516
- *
2517
- * @param degree 0-based scale degree of the chord root.
2518
- * @returns The triad, with this key attached.
2519
- */
2520
- diatonicTriad(degree) {
2521
- return new Chord(diatonicTriad(degree, this.#scale), this);
2522
- }
2523
- /**
2524
- * The diatonic seventh chord on a scale degree, carrying this key as context.
2525
- *
2526
- * @param degree 0-based scale degree of the chord root.
2527
- * @returns The seventh chord, with this key attached.
2528
- */
2529
- diatonicSeventh(degree) {
2530
- return new Chord(diatonicSeventh(degree, this.#scale), this);
2531
- }
2532
- /**
2533
- * Build the chord denoted by a Roman numeral in this key (including applied
2534
- * chords such as `'V7/V'`), carrying this key as context.
2535
- *
2536
- * @param text The Roman numeral.
2537
- * @returns The chord, with this key attached.
2538
- * @throws If the numeral is not valid.
2539
- */
2540
- roman(text) {
2541
- return new Chord(romanToChord(text, this.#scale), this);
2542
- }
2543
- /**
2544
- * Whether a pitch belongs to the scale.
2545
- *
2546
- * @param x A MIDI pitch, bare pitch class, or note.
2547
- * @returns True if the pitch class is a scale tone.
2548
- */
2549
- contains(x) {
2550
- return isScaleTone(typeof x === "number" ? x : x.pitchClass, this.#scale);
2551
- }
2552
- /**
2553
- * The plain key data, for JSON serialization.
2554
- *
2555
- * Private class fields do not serialize, so an explicit `toJSON` keeps
2556
- * `JSON.stringify(key)` from collapsing to `{}`. The result pairs the
2557
- * `KeyScale` with the spelled tonic, enough to reconstruct the key via
2558
- * {@link Key.of}.
2559
- *
2560
- * @returns The key/scale and its spelled tonic.
2561
- */
2562
- toJSON() {
2563
- return { scale: this.scale, tonic: this.#tonic.data };
2564
- }
2565
- };
2566
- // Annotate the CommonJS export names for ESM import in node:
2567
- 0 && (module.exports = {
2568
- Chord,
2569
- Interval,
2570
- Key,
2571
- Note,
2572
- Progression
2573
- });
19
+ exports.Chord = _chunkNVE34YGZcjs.Chord; exports.Interval = _chunkNVE34YGZcjs.Interval; exports.Key = _chunkNVE34YGZcjs.Key; exports.Note = _chunkNVE34YGZcjs.Note; exports.Progression = _chunkNVE34YGZcjs.Progression;
2574
20
  //# sourceMappingURL=index.cjs.map