jpfun 0.3.0 → 0.4.1

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 (129) hide show
  1. package/README.md +73 -1
  2. package/dist/converter/midi/convert.d.ts +50 -0
  3. package/dist/converter/midi/convert.js +700 -0
  4. package/dist/converter/midi/index.d.ts +5 -0
  5. package/dist/converter/midi/index.js +11 -0
  6. package/dist/converter/midi/json.d.ts +38 -0
  7. package/dist/converter/midi/json.js +1 -0
  8. package/dist/converter/midi/triplet.d.ts +30 -0
  9. package/dist/converter/midi/triplet.js +75 -0
  10. package/dist/converter/musicxml/dom.d.ts +25 -0
  11. package/dist/converter/musicxml/dom.js +65 -0
  12. package/dist/converter/musicxml/features.d.ts +51 -0
  13. package/dist/converter/musicxml/features.js +232 -0
  14. package/dist/converter/musicxml/index.d.ts +9 -0
  15. package/dist/converter/musicxml/index.js +1140 -0
  16. package/dist/converter/musicxml/model.d.ts +123 -0
  17. package/dist/converter/musicxml/model.js +1 -0
  18. package/dist/converter/source.d.ts +22 -0
  19. package/dist/converter/source.js +51 -0
  20. package/dist/core.d.ts +22 -0
  21. package/dist/core.js +22 -0
  22. package/dist/functions/ASTtypes.d.ts +30 -26
  23. package/dist/functions/ASTtypes.js +25 -23
  24. package/dist/functions/adjust/index.js +13 -6
  25. package/dist/functions/arpeggio/index.d.ts +2 -0
  26. package/dist/functions/arpeggio/index.js +184 -0
  27. package/dist/functions/arpeggio/shape.d.ts +7 -0
  28. package/dist/functions/arpeggio/shape.js +122 -0
  29. package/dist/functions/bar/index.js +30 -23
  30. package/dist/functions/beam/auto.d.ts +1 -1
  31. package/dist/functions/beam/auto.js +1 -1
  32. package/dist/functions/beam/index.js +6 -1
  33. package/dist/functions/beam/layout.d.ts +3 -3
  34. package/dist/functions/beam/layout.js +5 -3
  35. package/dist/functions/box/index.js +10 -3
  36. package/dist/functions/br/index.js +10 -6
  37. package/dist/functions/dash/index.js +12 -9
  38. package/dist/functions/default.js +6 -2
  39. package/dist/functions/div/index.d.ts +4 -1
  40. package/dist/functions/div/index.js +8 -7
  41. package/dist/functions/dot/index.js +18 -25
  42. package/dist/functions/dyn/index.d.ts +2 -0
  43. package/dist/functions/dyn/index.js +242 -0
  44. package/dist/functions/grace/index.d.ts +1 -1
  45. package/dist/functions/grace/index.js +17 -11
  46. package/dist/functions/head/index.js +168 -159
  47. package/dist/functions/key/index.js +12 -7
  48. package/dist/functions/meter/index.js +14 -6
  49. package/dist/functions/note/index.js +73 -31
  50. package/dist/functions/note/noteNameFSM.js +52 -63
  51. package/dist/functions/page/index.d.ts +5 -1
  52. package/dist/functions/page/index.js +38 -16
  53. package/dist/functions/program/index.d.ts +2 -0
  54. package/dist/functions/program/index.js +39 -0
  55. package/dist/functions/set/index.js +13 -8
  56. package/dist/functions/stack/index.js +7 -5
  57. package/dist/functions/symbol/index.d.ts +13 -3
  58. package/dist/functions/symbol/index.js +71 -22
  59. package/dist/functions/symbol/shape.d.ts +2 -0
  60. package/dist/functions/symbol/shape.js +14 -10
  61. package/dist/functions/symbol/symbols/dc.d.ts +4 -0
  62. package/dist/functions/symbol/symbols/dc.js +82 -0
  63. package/dist/functions/symbol/symbols/{f.d.ts → ds.d.ts} +1 -1
  64. package/dist/functions/symbol/symbols/ds.js +93 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +3 -0
  66. package/dist/functions/symbol/symbols/dynamics.js +168 -0
  67. package/dist/functions/symbol/symbols/{p.d.ts → fine.d.ts} +1 -1
  68. package/dist/functions/symbol/symbols/fine.js +12 -0
  69. package/dist/functions/symbol/symbols/mordent.js +44 -31
  70. package/dist/functions/symbol/symbols/prall.d.ts +2 -0
  71. package/dist/functions/symbol/symbols/prall.js +42 -0
  72. package/dist/functions/symbol/symbols/segno.d.ts +4 -0
  73. package/dist/functions/symbol/symbols/segno.js +82 -0
  74. package/dist/functions/symbol/symbols/tr.js +0 -4
  75. package/dist/functions/tempo/index.js +12 -4
  76. package/dist/functions/temporal.d.ts +138 -0
  77. package/dist/functions/temporal.js +101 -0
  78. package/dist/functions/text/index.js +25 -10
  79. package/dist/functions/tie/index.js +45 -30
  80. package/dist/functions/tuplet/index.js +21 -8
  81. package/dist/functions/up/index.js +38 -33
  82. package/dist/functions/voice/index.js +153 -68
  83. package/dist/functions/volta/index.js +62 -55
  84. package/dist/iife/core.d.ts +1 -0
  85. package/dist/iife/core.js +3 -0
  86. package/dist/iife/from-midi.d.ts +1 -0
  87. package/dist/iife/from-midi.js +15 -0
  88. package/dist/iife/from-musicxml.d.ts +1 -0
  89. package/dist/iife/from-musicxml.js +3 -0
  90. package/dist/iife/full.d.ts +1 -0
  91. package/dist/iife/full.js +3 -0
  92. package/dist/index.d.ts +3 -21
  93. package/dist/index.js +3 -21
  94. package/dist/jpfun.core.min.js +119 -0
  95. package/dist/jpfun.from-midi.min.js +9 -0
  96. package/dist/jpfun.from-musicxml.min.js +12 -0
  97. package/dist/jpfun.min.js +111 -122
  98. package/dist/layout/default.js +2 -3
  99. package/dist/layout/engine.d.ts +2 -1
  100. package/dist/layout/engine.js +71 -26
  101. package/dist/layout/model.d.ts +4 -4
  102. package/dist/layout/model.js +15 -12
  103. package/dist/layout/page.js +5 -4
  104. package/dist/layout/path.js +3 -3
  105. package/dist/layout/types.d.ts +20 -2
  106. package/dist/lowering/loweringContext.d.ts +3 -1
  107. package/dist/lowering/loweringContext.js +28 -14
  108. package/dist/lowering/track.d.ts +4 -8
  109. package/dist/lowering/track.js +6 -1
  110. package/dist/lowering/types.d.ts +5 -128
  111. package/dist/lowering/types.js +1 -98
  112. package/dist/parser/parse-utils/string-utils.d.ts +2 -0
  113. package/dist/parser/parse-utils/string-utils.js +4 -0
  114. package/dist/parser/parserContext.d.ts +7 -8
  115. package/dist/parser/parserContext.js +41 -36
  116. package/dist/pipeline.d.ts +6 -5
  117. package/dist/pipeline.js +4 -5
  118. package/dist/playback/compile.d.ts +1 -1
  119. package/dist/playback/compile.js +15 -2
  120. package/dist/playback/event.d.ts +17 -3
  121. package/dist/playback/event.js +30 -12
  122. package/dist/playback/time.js +1 -1
  123. package/dist/playback/types.d.ts +5 -4
  124. package/dist/render/text.d.ts +6 -1
  125. package/dist/render/text.js +8 -1
  126. package/grammar.md +111 -57
  127. package/package.json +11 -2
  128. package/dist/functions/symbol/symbols/f.js +0 -55
  129. package/dist/functions/symbol/symbols/p.js +0 -61
@@ -0,0 +1,5 @@
1
+ import { type MidiToJpFunOptions } from "./convert.js";
2
+ import type { MidiJson } from "./json.js";
3
+ export type * from "./json.js";
4
+ export type { MidiToJpFunOptions } from "./convert.js";
5
+ export declare function midiJsonToJpFun(input: MidiJson, options?: MidiToJpFunOptions): string;
@@ -0,0 +1,11 @@
1
+ import { ANCHOR_KEY } from "../../functions/temporal.js";
2
+ import { DEFAULT_PAGE_CONFIG } from "../../layout/page.js";
3
+ import { compileScore } from "../../pipeline.js";
4
+ import { convertMidiJsonToJpFun, } from "./convert.js";
5
+ export function midiJsonToJpFun(input, options = {}) {
6
+ return convertMidiJsonToJpFun(input, options, {
7
+ compileScore,
8
+ anchorKey: ANCHOR_KEY,
9
+ page: DEFAULT_PAGE_CONFIG,
10
+ });
11
+ }
@@ -0,0 +1,38 @@
1
+ /** midi.js JSON() 返回值的输入契约,转换器只依赖这些字段 */
2
+ export interface MidiJsonNote {
3
+ ticks: number;
4
+ durationTicks: number;
5
+ midi: number;
6
+ intensity: number;
7
+ }
8
+ export interface MidiJsonControlChange {
9
+ ticks: number;
10
+ controller: number;
11
+ value: number;
12
+ }
13
+ export interface MidiJsonInstrument {
14
+ ticks: number;
15
+ number: number;
16
+ }
17
+ export interface MidiJsonTrack {
18
+ channel: number;
19
+ name: string;
20
+ controlChanges: readonly MidiJsonControlChange[];
21
+ instruments: readonly MidiJsonInstrument[];
22
+ notes: readonly MidiJsonNote[];
23
+ }
24
+ export interface MidiJson {
25
+ header: {
26
+ name: string;
27
+ tick: number;
28
+ tempos: readonly {
29
+ ticks: number;
30
+ bpm: number;
31
+ }[];
32
+ timeSignatures: readonly {
33
+ ticks: number;
34
+ timeSignature: readonly [number, number];
35
+ }[];
36
+ };
37
+ tracks: readonly MidiJsonTrack[];
38
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * MIDI 3:2 三连音识别器
3
+ *
4
+ * 本模块只在原始 tick 时间线上标记三连音,不负责二进制量化或 jpFun 输出。
5
+ * 调用方随后把三个槽折叠成一个 QuantizedTriplet,并输出 @tuplet(..., 2)。
6
+ */
7
+ export interface TripletMark {
8
+ group: number;
9
+ slot: number;
10
+ startTicks: number;
11
+ spanTicks: number;
12
+ }
13
+ interface TripletNote {
14
+ ticks: number;
15
+ durationTicks: number;
16
+ triplet?: TripletMark;
17
+ }
18
+ /**
19
+ * 标记四分、八分和十六分的 3:2 三连音。
20
+ *
21
+ * 每个候选必须同时满足:三个槽都有音符、起点和时值都接近三分网格、
22
+ * 三分网格明显优于四等分网格,并且整组不跨小节、拍号或速度变化。
23
+ * 和弦按一个槽评分,不会因为某个槽音符更多而改变判断。
24
+ *
25
+ * 返回 true 表示至少命中一组;命中的 note 会原地写入 triplet 标记。
26
+ */
27
+ export declare function identifyTriplets<T extends TripletNote>(tracks: readonly {
28
+ notes: T[];
29
+ }[], ticksPerQuarter: number, blockers: readonly number[]): boolean;
30
+ export {};
@@ -0,0 +1,75 @@
1
+ function lowerBound(items, target, valueOf) {
2
+ let left = 0;
3
+ let right = items.length;
4
+ while (left < right) {
5
+ const middle = Math.floor((left + right) / 2);
6
+ if (valueOf(items[middle]) < target)
7
+ left = middle + 1;
8
+ else
9
+ right = middle;
10
+ }
11
+ return left;
12
+ }
13
+ /**
14
+ * 标记四分、八分和十六分的 3:2 三连音。
15
+ *
16
+ * 每个候选必须同时满足:三个槽都有音符、起点和时值都接近三分网格、
17
+ * 三分网格明显优于四等分网格,并且整组不跨小节、拍号或速度变化。
18
+ * 和弦按一个槽评分,不会因为某个槽音符更多而改变判断。
19
+ *
20
+ * 返回 true 表示至少命中一组;命中的 note 会原地写入 triplet 标记。
21
+ */
22
+ export function identifyTriplets(tracks, ticksPerQuarter, blockers) {
23
+ // 人工演奏容差随 PPQ 缩放,但不会超过单个三连槽宽的 1/8。
24
+ const performanceTolerance = Math.max(1, Math.round(ticksPerQuarter / 48));
25
+ const candidates = [];
26
+ const orderedBlockers = [...blockers].sort((left, right) => left - right);
27
+ for (const track of tracks) {
28
+ const notes = [...track.notes].sort((left, right) => left.ticks - right.ticks);
29
+ for (const span of [ticksPerQuarter / 2, ticksPerQuarter, ticksPerQuarter * 2]) {
30
+ const unit = span / 3;
31
+ const tolerance = Math.min(performanceTolerance, unit / 8);
32
+ const startStep = span / 2;
33
+ const starts = new Set(notes.map(note => Math.round(note.ticks / startStep) * startStep)
34
+ .filter((start, index) => Math.abs(notes[index].ticks - start) <= tolerance));
35
+ for (const start of starts) {
36
+ const end = start + span;
37
+ let blockerIndex = lowerBound(orderedBlockers, start, value => value);
38
+ while (orderedBlockers[blockerIndex] === start)
39
+ blockerIndex++;
40
+ if (orderedBlockers[blockerIndex] < end)
41
+ continue;
42
+ const slots = [0, 1, 2].map(slot => {
43
+ const target = start + slot * unit;
44
+ const from = lowerBound(notes, target - tolerance, note => note.ticks);
45
+ const to = lowerBound(notes, target + tolerance + 1, note => note.ticks);
46
+ return notes.slice(from, to).filter(note => Math.abs(note.ticks - target) <= tolerance
47
+ && Math.abs(note.durationTicks - unit) <= tolerance);
48
+ });
49
+ if (slots.some(slot => slot.length === 0))
50
+ continue;
51
+ const onsets = slots.map(slot => slot.reduce((sum, note) => sum + note.ticks, 0) / slot.length);
52
+ const tripletError = onsets.reduce((sum, onset, slot) => sum + Math.abs(onset - (start + slot * unit)), 0) / 3;
53
+ const binaryStep = span / 4;
54
+ const binaryError = onsets.reduce((sum, onset) => sum + Math.abs(onset - (start + Math.round((onset - start) / binaryStep) * binaryStep)), 0) / 3;
55
+ if (binaryError - tripletError >= tolerance) {
56
+ candidates.push({ notes: slots, start, span, advantage: binaryError - tripletError });
57
+ }
58
+ }
59
+ }
60
+ }
61
+ // 重叠候选先采用相对普通网格优势更大的那一组,每个 note 最多归属一组。
62
+ candidates.sort((left, right) => right.advantage - left.advantage);
63
+ let group = 0;
64
+ for (const candidate of candidates) {
65
+ if (candidate.notes.some(slot => slot.some(note => note.triplet)))
66
+ continue;
67
+ for (let slot = 0; slot < 3; slot++) {
68
+ for (const note of candidate.notes[slot]) {
69
+ note.triplet = { group, slot, startTicks: candidate.start, spanTicks: candidate.span };
70
+ }
71
+ }
72
+ group++;
73
+ }
74
+ return group > 0;
75
+ }
@@ -0,0 +1,25 @@
1
+ export interface MusicXmlNode {
2
+ readonly nodeType: number;
3
+ }
4
+ /** 浏览器 Element 与第三方 XML DOM 都能满足的最小读取接口 */
5
+ export interface MusicXmlElement extends MusicXmlNode {
6
+ readonly localName: string | null;
7
+ readonly tagName: string;
8
+ readonly childNodes: ArrayLike<MusicXmlNode>;
9
+ readonly textContent: string | null;
10
+ getAttribute(name: string): string | null;
11
+ }
12
+ /** 读取忽略命名空间前缀的元素名 */
13
+ export declare function nameOf(element: MusicXmlElement): string;
14
+ /** 返回全部直接子元素,可按元素名筛选 */
15
+ export declare function children(parent: MusicXmlElement, name?: string): MusicXmlElement[];
16
+ /** 返回第一个同名直接子元素 */
17
+ export declare function child(parent: MusicXmlElement, name: string): MusicXmlElement | undefined;
18
+ /** 按文档顺序深度优先查找第一个同名后代元素 */
19
+ export declare function descendant(parent: MusicXmlElement, name: string): MusicXmlElement | undefined;
20
+ /** 按文档顺序收集全部同名后代元素 */
21
+ export declare function descendants(parent: MusicXmlElement, name: string): MusicXmlElement[];
22
+ /** 读取自身或同名直接子元素的去空白文本 */
23
+ export declare function text(parent: MusicXmlElement | undefined, name?: string): string;
24
+ /** 读取有限数值,缺失时使用显式 fallback 或抛错 */
25
+ export declare function number(parent: MusicXmlElement | undefined, name: string, fallback?: number): number;
@@ -0,0 +1,65 @@
1
+ /** 读取忽略命名空间前缀的元素名 */
2
+ export function nameOf(element) {
3
+ return element.localName || element.tagName.split(":").at(-1);
4
+ }
5
+ /** 返回全部直接子元素,可按元素名筛选 */
6
+ export function children(parent, name) {
7
+ const result = [];
8
+ for (let index = 0; index < parent.childNodes.length; index++) {
9
+ const node = parent.childNodes[index];
10
+ if (node.nodeType !== 1)
11
+ continue;
12
+ const element = node;
13
+ if (name === undefined || nameOf(element) === name)
14
+ result.push(element);
15
+ }
16
+ return result;
17
+ }
18
+ /** 返回第一个同名直接子元素 */
19
+ export function child(parent, name) {
20
+ for (let index = 0; index < parent.childNodes.length; index++) {
21
+ const node = parent.childNodes[index];
22
+ if (node.nodeType === 1 && nameOf(node) === name)
23
+ return node;
24
+ }
25
+ return void 0;
26
+ }
27
+ /** 按文档顺序深度优先查找第一个同名后代元素 */
28
+ export function descendant(parent, name) {
29
+ for (const item of children(parent)) {
30
+ if (nameOf(item) === name)
31
+ return item;
32
+ const nested = descendant(item, name);
33
+ if (nested)
34
+ return nested;
35
+ }
36
+ return void 0;
37
+ }
38
+ /** 按文档顺序收集全部同名后代元素 */
39
+ export function descendants(parent, name) {
40
+ const result = [];
41
+ for (const item of children(parent)) {
42
+ if (nameOf(item) === name)
43
+ result.push(item);
44
+ result.push(...descendants(item, name));
45
+ }
46
+ return result;
47
+ }
48
+ /** 读取自身或同名直接子元素的去空白文本 */
49
+ export function text(parent, name) {
50
+ const element = name === undefined ? parent : parent && child(parent, name);
51
+ return element?.textContent?.trim() ?? "";
52
+ }
53
+ /** 读取有限数值,缺失时使用显式 fallback 或抛错 */
54
+ export function number(parent, name, fallback) {
55
+ const source = text(parent, name);
56
+ if (source === "") {
57
+ if (fallback !== undefined)
58
+ return fallback;
59
+ throw new RangeError(`MusicXML <${name}> must contain a finite number`);
60
+ }
61
+ const value = Number(source);
62
+ if (Number.isFinite(value))
63
+ return value;
64
+ throw new RangeError(`MusicXML <${name}> must contain a finite number`);
65
+ }
@@ -0,0 +1,51 @@
1
+ import { type MusicXmlElement } from "./dom.js";
2
+ import type { MusicXmlArpeggio } from "./model.js";
3
+ /** 统一两种 MusicXML 根结构中的小节内容与外层小节容器 */
4
+ export interface MusicXmlMeasureSource {
5
+ body: MusicXmlElement;
6
+ container: MusicXmlElement;
7
+ }
8
+ /** 将 score-partwise 和 score-timewise 统一为每个 part 的小节序列 */
9
+ export declare function partMeasures(root: MusicXmlElement): Map<string, MusicXmlMeasureSource[]>;
10
+ /** 解析书面音高及该和弦成员自己的 tie 起止标记 */
11
+ export declare function parsePitch(note: MusicXmlElement): {
12
+ step: string;
13
+ alter: number;
14
+ octave: number;
15
+ tieStart: boolean;
16
+ tieStop: boolean;
17
+ } | null;
18
+ /** 将支持的 fermata articulation 和 ornament 转成 jpFun 修饰符 */
19
+ export declare function noteModifiers(note: MusicXmlElement): {
20
+ name: string;
21
+ placement: "above" | "below";
22
+ }[];
23
+ /** 无箭头不覆盖显式方向,两个相反的显式方向不能属于同一和弦。 */
24
+ export declare function mergeArpeggio(current?: MusicXmlArpeggio, next?: MusicXmlArpeggio): MusicXmlArpeggio | undefined;
25
+ /** 读取和弦成员上的琶音方向;none 表示无箭头但仍按自下而上演奏。 */
26
+ export declare function noteArpeggio(note: MusicXmlElement): MusicXmlArpeggio | undefined;
27
+ /** 解析 tuplet 的实际音数与正常音数,并保留显式组边界 */
28
+ export declare function timeModification(note: MusicXmlElement): {
29
+ actual: number;
30
+ normal: number;
31
+ start: boolean;
32
+ stop: boolean;
33
+ } | undefined;
34
+ /** 按 verse 收集歌词并用尾部连字符保留音节延续 */
35
+ export declare function noteLyrics(note: MusicXmlElement): Map<string, string>;
36
+ /** 返回 direction 中首个受支持的力度记号 */
37
+ export declare function directionDynamic(direction: MusicXmlElement): string | undefined;
38
+ /** 收集排练标记与普通文字,排练标记保留方框语义 */
39
+ export declare function directionTexts(direction: MusicXmlElement): {
40
+ text: string;
41
+ boxed: boolean;
42
+ }[];
43
+ /** 将 metronome 的拍单位和附点折算成四分音符 BPM */
44
+ export declare function metronomeBpm(direction: MusicXmlElement): number | undefined;
45
+ /** 将单一或复合拍号归一成一个等值分数 */
46
+ export declare function parseTimeSignature(time: MusicXmlElement): {
47
+ numerator: number;
48
+ denominator: number;
49
+ };
50
+ /** 展开逗号分隔的遍数与闭区间范围,并返回升序去重结果 */
51
+ export declare function endingPasses(value: string): number[];
@@ -0,0 +1,232 @@
1
+ import { child, children, descendant, descendants, nameOf, number, text, } from "./dom.js";
2
+ const DYNAMIC_NAMES = new Set(["ppp", "pp", "p", "mp", "mf", "f", "ff", "fff"]);
3
+ const MAX_ENDING_PASS = 256;
4
+ /** 读取上下方位置,非法或缺失值回落到调用方默认值 */
5
+ function placementOf(element, fallback) {
6
+ const placement = element.getAttribute("placement");
7
+ return placement === "above" || placement === "below" ? placement : fallback;
8
+ }
9
+ /** 将 score-partwise 和 score-timewise 统一为每个 part 的小节序列 */
10
+ export function partMeasures(root) {
11
+ const result = new Map();
12
+ const rootName = nameOf(root);
13
+ if (rootName === "score-partwise") {
14
+ for (const part of children(root, "part"))
15
+ result.set(part.getAttribute("id") ?? "", children(part, "measure").map(measure => ({ body: measure, container: measure })));
16
+ return result;
17
+ }
18
+ if (rootName === "score-timewise") {
19
+ for (const measure of children(root, "measure")) {
20
+ for (const part of children(measure, "part")) {
21
+ const id = part.getAttribute("id") ?? "";
22
+ const list = result.get(id) ?? [];
23
+ list.push({ body: part, container: measure });
24
+ result.set(id, list);
25
+ }
26
+ }
27
+ return result;
28
+ }
29
+ throw new TypeError(`Unsupported MusicXML root <${rootName}>`);
30
+ }
31
+ /** 解析书面音高及该和弦成员自己的 tie 起止标记 */
32
+ export function parsePitch(note) {
33
+ const pitched = child(note, "pitch");
34
+ const pitch = pitched ?? child(note, "unpitched");
35
+ if (!pitch)
36
+ return null;
37
+ const step = text(pitch, pitched ? "step" : "display-step").toUpperCase();
38
+ const alter = pitched ? number(pitch, "alter", 0) : 0;
39
+ const octave = number(pitch, pitched ? "octave" : "display-octave");
40
+ if (!/^[A-G]$/.test(step) || !Number.isInteger(alter) || !Number.isInteger(octave)) {
41
+ throw new RangeError("jpFun requires MusicXML pitches with integer step alterations and octaves");
42
+ }
43
+ const tieTypes = new Set();
44
+ for (const tie of children(note, "tie"))
45
+ tieTypes.add(tie.getAttribute("type") ?? "");
46
+ const notations = child(note, "notations");
47
+ if (notations)
48
+ for (const tied of children(notations, "tied"))
49
+ tieTypes.add(tied.getAttribute("type") ?? "");
50
+ return {
51
+ step,
52
+ alter,
53
+ octave,
54
+ tieStart: tieTypes.has("start") || tieTypes.has("continue"),
55
+ tieStop: tieTypes.has("stop") || tieTypes.has("continue"),
56
+ };
57
+ }
58
+ /** 将支持的 fermata articulation 和 ornament 转成 jpFun 修饰符 */
59
+ export function noteModifiers(note) {
60
+ const result = [];
61
+ const notations = child(note, "notations");
62
+ if (!notations)
63
+ return result;
64
+ const fermata = child(notations, "fermata");
65
+ if (fermata)
66
+ result.push({
67
+ name: "fermata",
68
+ placement: placementOf(fermata, fermata.getAttribute("type") === "inverted" ? "below" : "above"),
69
+ });
70
+ const articulations = child(notations, "articulations");
71
+ const accent = articulations && child(articulations, "accent");
72
+ if (accent)
73
+ result.push({ name: "accent", placement: placementOf(accent, "above") });
74
+ const ornaments = child(notations, "ornaments");
75
+ if (ornaments) {
76
+ const names = [
77
+ ["trill-mark", "tr"],
78
+ ["mordent", "mordent"],
79
+ ["inverted-mordent", "prall"],
80
+ ];
81
+ for (const [tag, name] of names) {
82
+ const ornament = child(ornaments, tag);
83
+ if (ornament)
84
+ result.push({ name, placement: placementOf(ornament, "above") });
85
+ }
86
+ }
87
+ return result;
88
+ }
89
+ /** 无箭头不覆盖显式方向,两个相反的显式方向不能属于同一和弦。 */
90
+ export function mergeArpeggio(current, next) {
91
+ if (!next || next === "none")
92
+ return current ?? next;
93
+ if (current && current !== "none" && current !== next) {
94
+ throw new RangeError("Conflicting MusicXML arpeggiate directions in one chord");
95
+ }
96
+ return next;
97
+ }
98
+ /** 读取和弦成员上的琶音方向;none 表示无箭头但仍按自下而上演奏。 */
99
+ export function noteArpeggio(note) {
100
+ const notations = child(note, "notations");
101
+ if (!notations)
102
+ return undefined;
103
+ let result;
104
+ for (const arpeggiate of children(notations, "arpeggiate")) {
105
+ const attribute = arpeggiate.getAttribute("direction");
106
+ const value = attribute === null || attribute === "" ? "none" : attribute;
107
+ if (value !== "none" && value !== "up" && value !== "down") {
108
+ throw new RangeError(`Unsupported MusicXML arpeggiate direction: ${value}`);
109
+ }
110
+ result = mergeArpeggio(result, value);
111
+ }
112
+ return result;
113
+ }
114
+ /** 解析 tuplet 的实际音数与正常音数,并保留显式组边界 */
115
+ export function timeModification(note) {
116
+ const modification = child(note, "time-modification");
117
+ if (!modification)
118
+ return undefined;
119
+ const actual = number(modification, "actual-notes");
120
+ const normal = number(modification, "normal-notes");
121
+ if (!Number.isSafeInteger(actual) || actual < 2 || !Number.isSafeInteger(normal) || normal <= 0) {
122
+ throw new RangeError("MusicXML time-modification requires positive integer actual-notes and normal-notes");
123
+ }
124
+ const notations = child(note, "notations");
125
+ const tuplets = notations ? children(notations, "tuplet") : [];
126
+ return {
127
+ actual,
128
+ normal,
129
+ start: tuplets.some(item => item.getAttribute("type") === "start"),
130
+ stop: tuplets.some(item => item.getAttribute("type") === "stop"),
131
+ };
132
+ }
133
+ /** 按 verse 收集歌词并用尾部连字符保留音节延续 */
134
+ export function noteLyrics(note) {
135
+ const result = new Map();
136
+ for (const lyric of children(note, "lyric")) {
137
+ const verse = lyric.getAttribute("number") || lyric.getAttribute("name") || "1";
138
+ const words = children(lyric)
139
+ .filter(item => ["text", "elision"].includes(nameOf(item)))
140
+ .map(item => nameOf(item) === "elision" ? "~" : text(item))
141
+ .join("");
142
+ const syllabic = text(lyric, "syllabic");
143
+ result.set(verse, words && (syllabic === "begin" || syllabic === "middle") ? `${words}-` : words);
144
+ }
145
+ return result;
146
+ }
147
+ /** 返回 direction 中首个受支持的力度记号 */
148
+ export function directionDynamic(direction) {
149
+ const dynamics = descendant(direction, "dynamics");
150
+ if (!dynamics)
151
+ return undefined;
152
+ return children(dynamics).map(nameOf).find(name => DYNAMIC_NAMES.has(name));
153
+ }
154
+ /** 收集排练标记与普通文字,排练标记保留方框语义 */
155
+ export function directionTexts(direction) {
156
+ const result = [];
157
+ for (const name of ["rehearsal", "words"]) {
158
+ for (const node of descendants(direction, name)) {
159
+ const value = node.textContent?.trim();
160
+ if (value)
161
+ result.push({ text: value, boxed: name === "rehearsal" });
162
+ }
163
+ }
164
+ return result;
165
+ }
166
+ /** 将 metronome 的拍单位和附点折算成四分音符 BPM */
167
+ export function metronomeBpm(direction) {
168
+ const metronome = descendant(direction, "metronome");
169
+ if (!metronome)
170
+ return undefined;
171
+ const perMinute = Number(text(metronome, "per-minute"));
172
+ const unit = text(metronome, "beat-unit");
173
+ const quarterLengths = {
174
+ maxima: 32, long: 16, breve: 8, whole: 4, half: 2, quarter: 1,
175
+ eighth: 0.5, "16th": 0.25, "32nd": 0.125, "64th": 0.0625,
176
+ "128th": 0.03125, "256th": 0.015625, "512th": 0.0078125, "1024th": 0.00390625,
177
+ };
178
+ let length = quarterLengths[unit];
179
+ if (!Number.isFinite(perMinute) || length === undefined)
180
+ return undefined;
181
+ let addition = length / 2;
182
+ for (const _dot of children(metronome, "beat-unit-dot")) {
183
+ length += addition;
184
+ addition /= 2;
185
+ }
186
+ return perMinute * length;
187
+ }
188
+ /** 将单一或复合拍号归一成一个等值分数 */
189
+ export function parseTimeSignature(time) {
190
+ const pairs = [];
191
+ let beats;
192
+ // beats 与紧随其后的 beat-type 组成一组,多个组表示复合拍号
193
+ for (const item of children(time)) {
194
+ const tag = nameOf(item);
195
+ if (tag === "beats") {
196
+ beats = text(item).split("+").reduce((sum, value) => sum + Number(value), 0);
197
+ }
198
+ else if (tag === "beat-type" && beats !== undefined) {
199
+ pairs.push({ beats, beatType: Number(text(item)) });
200
+ beats = undefined;
201
+ }
202
+ }
203
+ if (pairs.length === 0 || pairs.some(pair => !Number.isSafeInteger(pair.beats) || pair.beats <= 0
204
+ || !Number.isSafeInteger(pair.beatType) || pair.beatType <= 0)) {
205
+ throw new RangeError("MusicXML time signature must contain positive integer beats/beat-type pairs");
206
+ }
207
+ const gcd = (left, right) => right === 0 ? left : gcd(right, left % right);
208
+ const denominator = pairs.reduce((result, pair) => result / gcd(result, pair.beatType) * pair.beatType, 1);
209
+ const numerator = pairs.reduce((sum, pair) => sum + pair.beats * denominator / pair.beatType, 0);
210
+ if (!Number.isSafeInteger(numerator) || !Number.isSafeInteger(denominator)) {
211
+ throw new RangeError("MusicXML time signature exceeds the supported integer range");
212
+ }
213
+ return { numerator, denominator };
214
+ }
215
+ /** 展开逗号分隔的遍数与闭区间范围,并返回升序去重结果 */
216
+ export function endingPasses(value) {
217
+ const result = new Set();
218
+ for (const part of value.split(/\s*,\s*/)) {
219
+ const match = part.match(/^(\d+)(?:\s*-\s*(\d+))?$/);
220
+ if (!match)
221
+ throw new RangeError("MusicXML ending number must contain positive integers or ascending ranges");
222
+ const from = Number(match[1]);
223
+ const to = Number(match[2] ?? match[1]);
224
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
225
+ || from < 1 || to < from || to > MAX_ENDING_PASS) {
226
+ throw new RangeError(`MusicXML ending passes must be ascending integers in 1..${MAX_ENDING_PASS}`);
227
+ }
228
+ for (let pass = from; pass <= to; pass++)
229
+ result.add(pass);
230
+ }
231
+ return [...result].sort((left, right) => left - right);
232
+ }
@@ -0,0 +1,9 @@
1
+ import { type MusicXmlElement } from "./dom.js";
2
+ import { type PitchMode } from "../source.js";
3
+ export type { MusicXmlElement, MusicXmlNode } from "./dom.js";
4
+ export interface MusicXmlToJpFunOptions {
5
+ pitchMode?: PitchMode;
6
+ barsPerLine?: number;
7
+ }
8
+ /** 将解析好的 MusicXML 根元素同步转换为可重新解析的 jpFun 源码 */
9
+ export declare function musicXmlToJpFun(root: MusicXmlElement, options?: MusicXmlToJpFunOptions): string;