jpfun 0.4.0 → 0.5.0

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 (83) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +4 -4
  14. package/dist/functions/ASTtypes.js +5 -9
  15. package/dist/functions/adjust/index.js +16 -53
  16. package/dist/functions/arpeggio/index.js +27 -15
  17. package/dist/functions/bar/index.js +7 -8
  18. package/dist/functions/beam/index.js +6 -1
  19. package/dist/functions/beam/layout.d.ts +1 -1
  20. package/dist/functions/beam/layout.js +5 -3
  21. package/dist/functions/box/index.js +88 -82
  22. package/dist/functions/br/index.js +9 -5
  23. package/dist/functions/dash/index.js +24 -13
  24. package/dist/functions/div/index.d.ts +5 -2
  25. package/dist/functions/div/index.js +15 -14
  26. package/dist/functions/dot/index.js +13 -11
  27. package/dist/functions/dyn/index.js +35 -39
  28. package/dist/functions/grace/index.d.ts +19 -6
  29. package/dist/functions/grace/index.js +136 -121
  30. package/dist/functions/head/index.js +19 -14
  31. package/dist/functions/key/index.js +8 -4
  32. package/dist/functions/meter/index.js +22 -2
  33. package/dist/functions/note/index.d.ts +6 -1
  34. package/dist/functions/note/index.js +48 -30
  35. package/dist/functions/note/source-transform.d.ts +21 -0
  36. package/dist/functions/note/source-transform.js +164 -0
  37. package/dist/functions/page/index.d.ts +8 -1
  38. package/dist/functions/page/index.js +23 -13
  39. package/dist/functions/program/index.js +11 -2
  40. package/dist/functions/set/index.js +14 -8
  41. package/dist/functions/stack/index.js +7 -5
  42. package/dist/functions/symbol/index.d.ts +2 -0
  43. package/dist/functions/symbol/index.js +11 -7
  44. package/dist/functions/symbol/ornament.d.ts +3 -3
  45. package/dist/functions/symbol/ornament.js +21 -35
  46. package/dist/functions/symbol/symbols/accent.js +5 -5
  47. package/dist/functions/symbol/symbols/fermata.js +5 -4
  48. package/dist/functions/tempo/index.js +7 -1
  49. package/dist/functions/text/index.js +11 -3
  50. package/dist/functions/tie/index.js +28 -32
  51. package/dist/functions/tuplet/index.js +26 -24
  52. package/dist/functions/up/index.js +24 -21
  53. package/dist/functions/voice/index.js +36 -26
  54. package/dist/functions/volta/index.js +16 -17
  55. package/dist/jpfun.core.min.js +98 -129
  56. package/dist/jpfun.from-midi.min.js +5 -5
  57. package/dist/jpfun.from-musicxml.min.js +8 -8
  58. package/dist/jpfun.min.js +107 -138
  59. package/dist/layout/engine.d.ts +11 -1
  60. package/dist/layout/engine.js +299 -96
  61. package/dist/layout/page.js +2 -0
  62. package/dist/layout/range.d.ts +26 -0
  63. package/dist/layout/range.js +75 -0
  64. package/dist/layout/types.d.ts +33 -4
  65. package/dist/lowering/types.d.ts +5 -0
  66. package/dist/parser/parse-utils/length-utils.js +2 -0
  67. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  68. package/dist/parser/parse-utils/note-utils.js +6 -2
  69. package/dist/parser/parserContext.js +1 -1
  70. package/dist/playback/compile.d.ts +2 -9
  71. package/dist/playback/compile.js +297 -186
  72. package/dist/playback/event.d.ts +8 -16
  73. package/dist/playback/event.js +13 -3
  74. package/dist/playback/types.d.ts +76 -18
  75. package/dist/playback/types.js +1 -0
  76. package/dist/render/index.d.ts +1 -1
  77. package/dist/render/index.js +1 -1
  78. package/dist/render/recording.d.ts +1 -0
  79. package/dist/render/recording.js +21 -0
  80. package/dist/render/translate.d.ts +14 -0
  81. package/dist/render/translate.js +48 -0
  82. package/grammar.md +103 -78
  83. package/package.json +4 -4
package/README.md CHANGED
@@ -1,20 +1,15 @@
1
1
  # jpFun
2
2
 
3
- A functional numbered musical notation typesetting engine for TypeScript.
4
-
5
- jpFun compiles a compact numbered-notation DSL into a reusable document layout that can be rendered as SVG or Canvas.
3
+ A TypeScript engine that compiles a compact numbered-notation DSL into SVG or Canvas, with layout-independent playback.
6
4
 
7
5
  [Documentation](https://madderscientist.github.io/jpFun/)
8
6
 
9
7
  ## Features
10
8
 
11
- - Compact DSL with syntax sugar and function-based extensibility
12
- - Exact rational timing and composable score structures
13
- - Automatic spacing, explicit system breaks, and page-aware pagination
14
- - Shared layout model for SVG and Canvas rendering
15
- - Structured diagnostics and source locations
16
- - Zero runtime dependencies
17
- - Works in both Node.js and modern browsers
9
+ - Extensible music DSL with exact rational timing
10
+ - Automatic spacing and pagination, shared by SVG and Canvas
11
+ - Structured diagnostics and source-aware editing
12
+ - Zero runtime dependencies; works in Node.js and modern browsers
18
13
 
19
14
  ## Installation
20
15
 
@@ -22,17 +17,11 @@ jpFun compiles a compact numbered-notation DSL into a reusable document layout t
22
17
  npm install jpfun
23
18
  ```
24
19
 
25
- jpFun is ESM-only and requires Node.js 18 or later:
26
-
27
- ```ts
28
- import { compileScore } from "jpfun";
29
- ```
30
-
31
- CommonJS `require("jpfun")` is not supported.
20
+ jpFun is ESM-only, supports Node.js 18+ and modern browsers, and has no compiler DOM dependency.
32
21
 
33
22
  ## Browser via CDN
34
23
 
35
- A bundled, minified build ships with the package, so no build step is needed for a plain web page. Load it with a `<script>` tag and use the `jpfun` global:
24
+ Use the bundled `jpfun` global without a build step:
36
25
 
37
26
  ```html
38
27
  <script src="https://unpkg.com/jpfun"></script>
@@ -42,7 +31,7 @@ A bundled, minified build ships with the package, so no build step is needed for
42
31
  </script>
43
32
  ```
44
33
 
45
- For ES modules, jsDelivr bundles the package on the fly:
34
+ Or import an ES module:
46
35
 
47
36
  ```html
48
37
  <script type="module">
@@ -50,37 +39,17 @@ For ES modules, jsDelivr bundles the package on the fly:
50
39
  </script>
51
40
  ```
52
41
 
53
- Both URLs resolve to the latest published version. In production, append an exact version (`jpfun@x.y.z`) so that publishing a new release cannot change an existing page.
54
-
55
- The default URL is the complete build. Plain pages can instead load only the capabilities they use; every script extends the same `jpfun` global:
42
+ Pin `jpfun@x.y.z` in production; these URLs otherwise use the latest release.
56
43
 
57
- ```html
58
- <!-- Parse, layout, render, and playback without format converters. -->
59
- <script src="https://unpkg.com/jpfun/dist/jpfun.core.min.js"></script>
44
+ Optional bundles under `https://unpkg.com/jpfun/dist/` share the same global:
60
45
 
61
- <!-- MusicXML import works by itself. -->
62
- <script src="https://unpkg.com/jpfun/dist/jpfun.from-musicxml.min.js"></script>
63
- <script>
64
- const document = new DOMParser().parseFromString(musicXmlText, "application/xml");
65
- const musicXmlSource = jpfun.musicXmlToJpFun(document.documentElement);
66
- </script>
46
+ | Bundle | Capabilities |
47
+ | --- | --- |
48
+ | `jpfun.core.min.js` | Compilation, rendering, playback, and source editing |
49
+ | `jpfun.from-musicxml.min.js` | Standalone MusicXML import |
50
+ | `jpfun.from-midi.min.js` | MIDI JSON import; automatic line breaking also requires the core bundle |
67
51
 
68
- <!-- MIDI JSON import with a fixed measure count works by itself. -->
69
- <script src="https://unpkg.com/jpfun/dist/jpfun.from-midi.min.js"></script>
70
- <script>
71
- const midiSource = jpfun.midiJsonToJpFun(parsedMidiJson, { barsPerLine: 4 });
72
- </script>
73
- ```
74
-
75
- Measured automatic MIDI line breaking uses the layout engine. Load both scripts before calling the converter with an omitted or non-positive `barsPerLine`:
76
-
77
- ```html
78
- <script src="https://unpkg.com/jpfun/dist/jpfun.core.min.js"></script>
79
- <script src="https://unpkg.com/jpfun/dist/jpfun.from-midi.min.js"></script>
80
- <script>
81
- const source = jpfun.midiJsonToJpFun(parsedMidiJson);
82
- </script>
83
- ```
52
+ For standalone MIDI import, set a positive `barsPerLine`.
84
53
 
85
54
  ## Quick Start
86
55
 
@@ -98,41 +67,30 @@ const result = compileScore(source);
98
67
  const pages = renderLayoutPagesToSvg(result.layout);
99
68
  ```
100
69
 
101
- `renderLayoutPagesToSvg` returns one SVG string per page. Even an infinite-height document produces one natural-height page. Each SVG can be written to a file, sent in an HTTP response, or inserted into a browser page.
70
+ `renderLayoutPagesToSvg` returns one SVG string per page, ready to save or insert into a web page.
102
71
 
103
- ## Canvas Rendering
72
+ ## Note Source Transformations
104
73
 
105
- ```ts
106
- import { compileScore, renderLayoutPagesToCanvas } from "jpfun";
107
-
108
- const result = compileScore("1 2 3 | 4");
109
- const canvas = document.querySelector("canvas");
110
- const context = canvas.getContext("2d");
74
+ `transformNotes(source, lowering, operation, ranges?)` returns sorted `{ span, text }` edits for `to-absolute`, `to-relative`, `semitone-up`, or `semitone-down`. Use lowering from the same source and apply edits in one editor transaction or right to left.
111
75
 
112
- if (context) {
113
- renderLayoutPagesToCanvas(result.layout, [context]);
114
- }
115
- ```
76
+ Only notes fully covered by `ranges` are changed; omit it for the whole source, or pass `[]` for no changes. Conversion preserves pitch; semitone shifts preserve each note's representation. Key declarations, rests, spacers, percussion, and surrounding source are retained. Invalid note input throws a diagnostic.
116
77
 
117
- ## Text Measurement
78
+ ## Browser Rendering
118
79
 
119
- Layout depends on text widths, so `compileScore` needs a `TextMeasurer`. The default one estimates every character at a fixed fraction of the font size. That keeps results platform-independent, which is what tests and server-side rendering want, but it does not match the real glyph widths of a browser font — narrow letters are overestimated, so right-aligned text and `@box` bounds drift visibly.
120
-
121
- In a browser, pass `CanvasTextMeasurer` so that measurement agrees with what the renderer draws:
80
+ The default text measurer estimates glyph widths. For accurate browser layout, pass `CanvasTextMeasurer`, including when rendering SVG:
122
81
 
123
82
  ```ts
124
- import { compileScore, CanvasTextMeasurer } from "jpfun";
83
+ import { compileScore, CanvasTextMeasurer, renderLayoutPagesToCanvas } from "jpfun";
125
84
 
126
85
  const context = document.createElement("canvas").getContext("2d")!;
127
86
  const result = compileScore(source, { textMeasurer: new CanvasTextMeasurer(context) });
87
+ renderLayoutPagesToCanvas(result.layout, [context]);
128
88
  ```
129
89
 
130
- This applies to SVG output too, since measurement happens during layout rather than during painting. The context is only used for measuring and need not be the canvas you render into.
90
+ Canvas rendering takes one context per page. Measurement can use a separate canvas.
131
91
 
132
92
  ## Compilation Pipeline
133
93
 
134
- jpFun exposes the intermediate results of its compilation pipeline:
135
-
136
94
  ```text
137
95
  Source
138
96
  -> Parser -> AST
@@ -142,40 +100,19 @@ Source
142
100
  -> Renderer -> SVG or Canvas
143
101
  ```
144
102
 
145
- ```ts
146
- const result = compileScore("1 2 3 | 4");
147
-
148
- result.parser;
149
- result.ast;
150
- result.lowering;
151
- result.layout;
152
- ```
153
-
154
- Playback is compiled independently from layout:
103
+ `compileScore` exposes `parser`, `ast`, `lowering`, and `layout`. Compile playback separately:
155
104
 
156
105
  ```ts
157
106
  import { compilePlayback } from "jpfun";
158
107
 
159
108
  const playback = compilePlayback(result.lowering);
160
- playback.events;
161
- playback.scoreMap;
162
- playback.tracks;
163
- playback.durationSeconds;
164
109
  ```
165
110
 
166
- For scores with unusually large repeat expansion, raise the control-flow budget explicitly:
167
-
168
- ```ts
169
- const playback = compilePlayback(result.lowering, { maxFlowSteps: 200_000 });
170
- ```
171
-
172
- The default is 65,536 visited columns. Exceeding it throws instead of returning a partial playback plan.
173
-
174
- The plan stores device-independent `note-on`, `note-off`, `tempo`, `time-signature`, and `program-change` events. Its track number is the same channel identity used by the visual Track; Web Audio, Web MIDI, and Standard MIDI File adapters consume that identity and the exact `Fraction` timestamps at their boundary.
111
+ The plan contains device-independent `events`, `scoreMap`, `tracks`, and `durationSeconds`, with exact `Fraction` timestamps. Repeat expansion exceeding 65,536 visited columns throws; raise the limit with `{ maxFlowSteps: 200_000 }` when needed.
175
112
 
176
113
  ## MIDI JSON Conversion
177
114
 
178
- `midiJsonToJpFun` converts the JSON returned by madderscientist's [`midi.js`](https://madderscientist.github.io/noteDigger/lib/midi.js) `JSON()` method into jpFun source. MIDI byte parsing stays in the application boundary; the core converter only consumes structured data and has no runtime dependency on a MIDI parser.
115
+ `midiJsonToJpFun` accepts the JSON returned by [`midi.js`](https://madderscientist.github.io/noteDigger/lib/midi.js)'s `JSON()` method. Parse MIDI bytes in your application.
179
116
 
180
117
  ```ts
181
118
  import { midiJsonToJpFun } from "jpfun";
@@ -187,15 +124,13 @@ const source = midiJsonToJpFun(parsedMidiJson, {
187
124
  });
188
125
  ```
189
126
 
190
- `pitchMode` defaults to `"absolute"`; use `"relative"` for C-based numbered notation. `alignRate` controls adaptive binary quantization. Equal start/end groups become `@up` chords, overlapping lanes become `@stack`, and separate MIDI tracks become named voices. `barsPerLine` defaults to `0`; non-positive values select measured automatic breaks, while a positive value fixes the measures per system. `title` overrides the MIDI header name.
127
+ `pitchMode` defaults to `"absolute"`; `"relative"` uses C-based numbered notation. `alignRate` controls quantization. `barsPerLine` defaults to `0` for automatic breaks; positive values fix the measures per system.
191
128
 
192
- With classic scripts, measured automatic breaks require `jpfun.core.min.js`; a positive `barsPerLine` lets `jpfun.from-midi.min.js` run independently.
193
-
194
- The converter preserves notes, track names, tempo, time signatures, and MIDI programs, and recognizes standard 3:2 quarter-, eighth-, and sixteenth-note triplets. Other tuplets are unsupported. Percussion channel 10 is skipped; velocity, control changes, pitch bends, lyrics, and other MIDI metadata are ignored. Time-signature changes snap to measure boundaries, and continuations that cannot use `-` are emitted as tied notes.
129
+ Preserves notes, tracks, tempo, time signatures, programs, and standard 3:2 quarter-, eighth-, and sixteenth-note triplets. Other tuplets are unsupported. Percussion channel 10, velocity, controllers, pitch bends, and lyrics are omitted; time-signature changes snap to measure boundaries.
195
130
 
196
131
  ## MusicXML Conversion
197
132
 
198
- `musicXmlToJpFun` converts a parsed MusicXML root element into jpFun source. XML parsing stays at the application boundary, so the core package has no XML parser dependency. In a browser, use the native `DOMParser`:
133
+ `musicXmlToJpFun` accepts a parsed MusicXML root element. Use `DOMParser` in browsers or a compatible DOM implementation in Node.js:
199
134
 
200
135
  ```ts
201
136
  import { musicXmlToJpFun } from "jpfun";
@@ -204,14 +139,32 @@ const xml = await file.text();
204
139
  const document = new DOMParser().parseFromString(xml, "application/xml");
205
140
  if (document.querySelector("parsererror")) throw new SyntaxError("Invalid MusicXML");
206
141
 
207
- const source = musicXmlToJpFun(document.documentElement, {
142
+ const { script, diagnostics } = musicXmlToJpFun(document.documentElement, {
208
143
  barsPerLine: 4,
209
144
  });
210
145
  ```
211
146
 
212
- In Node.js, use any DOM implementation and pass a compatible root element. The converter supports partwise and timewise scores, parts/staves/voices, exact durations, rests, chords, arpeggios, grace notes, ties, tuplets, lyrics, score state, dynamics, repeats/endings, and basic system, page, and title metadata. `pitchMode` defaults to `"absolute"`; `"relative"` uses the active MusicXML key. Generated source uses compact jpFun syntax where unambiguous.
147
+ The result contains the generated `script` and a `MusicXmlDiagnostic[]`. Callers that previously used the return value as a string must now read `.script`. Each diagnostic is a plain object with `code`, `severity: "warning"`, `message`, and `location`; no diagnostics means an empty array. Conversion failures still throw instead of returning partial output.
148
+
149
+ | Code | Reported loss |
150
+ | --- | --- |
151
+ | `W_MUSICXML_PERCUSSION_SKIPPED` | Channel 10 notes omitted |
152
+ | `W_MUSICXML_APPROXIMATED` | Display pitches used for unpitched notes, after-grace fallback, or wedges mapped to note onsets with a fixed velocity change |
153
+ | `W_MUSICXML_UNSUPPORTED_ELEMENT` | Harmony and discarded children of supported notation or direction containers, including pedal, slur, unsupported articulations, ornaments, and dynamics |
154
+ | `W_MUSICXML_UNATTACHED_CONTENT` | Grace notes, text, or dynamics with no target |
155
+ | `W_MUSICXML_UNRESOLVED_RELATION` | Unmatched, replaced, unclosed, or unrenderable ties, wedges, and endings |
213
156
 
214
- Compressed `.mxl` archives are unsupported. Decompress them first or export `.musicxml`. Percussion channel 10 is skipped; pedal, cross-staff arpeggio grouping, detailed engraving coordinates, and other control information are ignored.
157
+ `location.element` is the XML tag name without its namespace prefix. Available context includes `partId`, `measureIndex` (1-based within the part), `measureNumber` (the original string), `staff`, and `voice`. These refer to the imported score, not offsets in `script`; XML line/column information is not available through the minimal DOM interface. Reports follow deterministic processing order, not necessarily XML document order.
158
+
159
+ Diagnostics cover the cases above, not the entire MusicXML specification. Empty diagnostics do not guarantee lossless conversion. Ordinary defaults and detailed engraving coordinates do not produce warnings. Diagnostic messages describe the loss; use `code` for programmatic classification.
160
+
161
+ Text, dynamics, and wedges target the matching part and staff. With no voice specified, dynamics and wedges apply to matching voices on that staff, while text is attached only once. Missing targets produce diagnostics instead of redirecting the marking to another staff or voice. Tuplet markers are confirmed only when the resulting event rhythm retains their boundaries, including equivalent declarations on chord members.
162
+
163
+ All `notations` containers on a note are inspected. Tempo and dynamic marks that never reach the generated script, including terminal marks, produce unattached-content warnings. Arpeggios that cannot be emitted after chord merging and voice splitting, such as cross-staff groups reduced to single-note events, produce unsupported-element warnings.
164
+
165
+ Supports partwise/timewise scores, multiple voices, rhythm, lyrics, dynamics, repeats, and basic layout metadata. `pitchMode` defaults to `"absolute"`; `"relative"` uses the active MusicXML key.
166
+
167
+ Decompress `.mxl` archives before parsing. Percussion channel 10, pedal, cross-staff arpeggio grouping, and detailed engraving coordinates are omitted.
215
168
 
216
169
  ## Syntax Example
217
170
 
@@ -227,14 +180,6 @@ L(Lyrics): do do so so la la so
227
180
 
228
181
  See the [language reference](grammar.md) for the complete syntax.
229
182
 
230
- ## Runtime Support
231
-
232
- - ESM only
233
- - Node.js 18 or later
234
- - Modern browsers and bundlers
235
- - No DOM dependency in the compiler
236
- - No runtime dependencies
237
-
238
183
  ## Development
239
184
 
240
185
  jpFun is maintained in a pnpm workspace. From the repository root:
@@ -243,15 +188,10 @@ jpFun is maintained in a pnpm workspace. From the repository root:
243
188
  pnpm install
244
189
  pnpm run build:core
245
190
  pnpm test
246
- ```
247
-
248
- The repository also includes a browser-based Playground with diagnostics and SVG/Canvas previews:
249
-
250
- ```sh
251
191
  pnpm run dev
252
192
  ```
253
193
 
254
- Then open <http://127.0.0.1:4173>.
194
+ The development server opens the Playground at <http://127.0.0.1:4173>.
255
195
 
256
196
  ## Documentation
257
197
 
@@ -1,5 +1,6 @@
1
1
  import { identifyTriplets } from "./triplet.js";
2
2
  import { attachAbove, quote, renderHead, renderPitch, renderSystems } from "../source.js";
3
+ import { SHARP_NOTE_NAMES as ABSOLUTE_NAMES } from "../../parser/parse-utils/note-utils.js";
3
4
  const DEFAULT_BPM = 120;
4
5
  const DEFAULT_TIME_SIGNATURE = [4, 4];
5
6
  const AUTO_LINE_TARGET_RATIO = 1.03;
@@ -7,7 +8,6 @@ const AUTO_LINE_LIMIT_RATIO = 1.25;
7
8
  const AUTO_LINE_UNDERFILL_PENALTY = 4;
8
9
  const AUTO_LINE_MAX_BARS = 8;
9
10
  const RELATIVE_NAMES = ["1", "1#", "2", "2#", "3", "4", "4#", "5", "5#", "6", "6#", "7"];
10
- const ABSOLUTE_NAMES = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];
11
11
  function expectSafeInteger(value, name, min = 0, max = Number.MAX_SAFE_INTEGER) {
12
12
  if (!Number.isSafeInteger(value) || value < min || value > max) {
13
13
  throw new RangeError(`${name} must be an integer in ${min}..${max}`);
@@ -354,7 +354,7 @@ function renderLane(lane, rangeStart, rangeEnd, rhythmScale, timeFactor, pitchMo
354
354
  if (at >= rangeStart && at < rangeEnd)
355
355
  points.add(at);
356
356
  }
357
- for (const at of programs?.keys() ?? []) {
357
+ for (const at of programs.keys()) {
358
358
  if (at >= rangeStart && at < rangeEnd)
359
359
  points.add(at);
360
360
  }
@@ -384,6 +384,14 @@ function renderLane(lane, rangeStart, rangeEnd, rhythmScale, timeFactor, pitchMo
384
384
  const outputs = Array.from({ length: lineBreaks.size + 1 }, () => []);
385
385
  let outputIndex = [...lineBreaks].filter(at => at <= rangeStart).length;
386
386
  let itemIndex = 0;
387
+ let initialProgram = programs.size ? 0 : undefined;
388
+ let programStart = -Infinity;
389
+ for (const [at, program] of programs) {
390
+ if (at <= rangeStart && at >= programStart) {
391
+ initialProgram = program;
392
+ programStart = at;
393
+ }
394
+ }
387
395
  // 沿时间片单向推进当前事件,依次输出控制项、音符或补齐休止
388
396
  for (let index = 0; index < timeline.length; index++) {
389
397
  const at = timeline[index];
@@ -396,7 +404,7 @@ function renderLane(lane, rangeStart, rangeEnd, rhythmScale, timeFactor, pitchMo
396
404
  const next = timeline[index + 1];
397
405
  if (next === undefined)
398
406
  continue;
399
- const program = programs?.get(at);
407
+ const program = at === rangeStart ? initialProgram : programs.get(at);
400
408
  if (program !== undefined)
401
409
  outputs[outputIndex].push(`@program(${program})`);
402
410
  const changes = adjustments?.get(at) ?? [];
@@ -630,13 +638,12 @@ export function convertMidiJsonToJpFun(input, options = {}, layoutCapability) {
630
638
  lastNoteEnd = Math.max(lastNoteEnd, end);
631
639
  return { ...note, start, end };
632
640
  });
633
- const programs = coalesceSorted(track.programs
634
- .filter(item => item.ticks === 0 || item.ticks < rawNoteEnd)
635
- .map(item => ({ at: binaryUnitAt(item.ticks), program: item.number })));
636
641
  convertedTracks.push({
637
642
  source: track.source,
638
643
  regions: splitRegions(groupTriplets(combineChords(notes))),
639
- programs: new Map(programs.map(item => [item.at, item.program])),
644
+ programs: new Map(track.programs
645
+ .filter(item => item.ticks === 0 || item.ticks < rawNoteEnd)
646
+ .map(item => [binaryUnitAt(item.ticks), item.number])),
640
647
  });
641
648
  }
642
649
  // 乐谱末尾补齐到当前拍号的完整小节边界
@@ -1,47 +1,87 @@
1
1
  import { type MusicXmlElement } from "./dom.js";
2
- import type { MusicXmlArpeggio } from "./model.js";
2
+ import type { MusicXmlArpeggio, MusicXmlDiagnostic, MusicXmlEvent, MusicXmlPitch, ParsedMusicXmlScore } from "./model.js";
3
3
  /** 统一两种 MusicXML 根结构中的小节内容与外层小节容器 */
4
4
  export interface MusicXmlMeasureSource {
5
5
  body: MusicXmlElement;
6
6
  container: MusicXmlElement;
7
7
  }
8
+ declare const DIAGNOSTICS: {
9
+ readonly percussion: readonly ["PERCUSSION_SKIPPED", "MIDI channel 10 percussion note was omitted."];
10
+ readonly displayPitch: readonly ["APPROXIMATED", "Unpitched note was converted to a melodic note using its display pitch."];
11
+ readonly afterGrace: readonly ["APPROXIMATED", "After-grace note has no preceding event and was treated as a before-grace note."];
12
+ readonly wedge: readonly ["APPROXIMATED", "Wedge was mapped to note onsets with a fixed velocity change of {value}."];
13
+ readonly unsupported: readonly ["UNSUPPORTED_ELEMENT", "MusicXML <{value}> was omitted."];
14
+ readonly gracePitch: readonly ["UNATTACHED_CONTENT", "Grace note without a pitch was omitted."];
15
+ readonly graceHost: readonly ["UNATTACHED_CONTENT", "Before-grace note has no following event and was omitted."];
16
+ readonly dynamicHost: readonly ["UNATTACHED_CONTENT", "Dynamic {value} has no target voice and was omitted."];
17
+ readonly directionOutput: readonly ["UNATTACHED_CONTENT", "Direction mark has no generated output position and was omitted."];
18
+ readonly tempoReplaced: readonly ["UNATTACHED_CONTENT", "Tempo {value} was replaced by a different tempo at the same time and was omitted."];
19
+ readonly arpeggioOutput: readonly ["UNSUPPORTED_ELEMENT", "Arpeggiate mark requires at least two pitches in one event and was omitted."];
20
+ readonly textHost: readonly ["UNATTACHED_CONTENT", "Text {value} has no target event and was omitted."];
21
+ readonly wedgeStart: readonly ["UNRESOLVED_RELATION", "Wedge stop has no matching start and was omitted."];
22
+ readonly wedgeReplaced: readonly ["UNRESOLVED_RELATION", "Wedge start was replaced before a matching stop and was omitted."];
23
+ readonly wedgeStop: readonly ["UNRESOLVED_RELATION", "Wedge start has no matching stop and was omitted."];
24
+ readonly wedgeVoice: readonly ["UNRESOLVED_RELATION", "Wedge has no target voice and was omitted."];
25
+ readonly wedgeEndpoints: readonly ["UNRESOLVED_RELATION", "Wedge has no two distinct note onsets to use as endpoints and was omitted."];
26
+ readonly endingStart: readonly ["UNRESOLVED_RELATION", "Ending stop has no matching start and was omitted."];
27
+ readonly endingReplaced: readonly ["UNRESOLVED_RELATION", "Ending start was replaced before a matching stop and was omitted."];
28
+ readonly endingStop: readonly ["UNRESOLVED_RELATION", "Ending start has no matching stop and was omitted."];
29
+ readonly endingEndpoints: readonly ["UNRESOLVED_RELATION", "Ending has no event endpoints in its interval and was omitted."];
30
+ readonly tieStart: readonly ["UNRESOLVED_RELATION", "Tie stop has no matching start and was omitted."];
31
+ readonly tieStop: readonly ["UNRESOLVED_RELATION", "Tie start has no matching stop in any ending branch and was omitted."];
32
+ };
33
+ export declare function reportDiagnostic(diagnostics: MusicXmlDiagnostic[], issue: keyof typeof DIAGNOSTICS, location: MusicXmlDiagnostic["location"], value?: string | number): void;
34
+ /** 查询不改变覆盖状态;解析结果写入语义模型后显式确认,未确认项按 XML 顺序报告 */
35
+ export declare class MusicXmlReader {
36
+ private readonly roots;
37
+ private readonly accepted;
38
+ constructor(roots: readonly MusicXmlElement[]);
39
+ read(name: string, deep?: boolean, parent?: MusicXmlElement): MusicXmlElement | undefined;
40
+ readAll(name: string, deep?: boolean): MusicXmlElement[];
41
+ accept(element: MusicXmlElement | undefined): void;
42
+ report(diagnostics: MusicXmlDiagnostic[], location: MusicXmlDiagnostic["location"], parent?: MusicXmlElement): void;
43
+ }
8
44
  /** 将 score-partwise 和 score-timewise 统一为每个 part 的小节序列 */
9
45
  export declare function partMeasures(root: MusicXmlElement): Map<string, MusicXmlMeasureSource[]>;
46
+ /** 校验 MIDI 乐器字段,并将一基 program 转为内部零基编号 */
47
+ export declare function readInstrument(midi: MusicXmlElement): {
48
+ channel?: number;
49
+ program?: number;
50
+ };
51
+ /** 文档元数据不参与时间推进;仅完整的页面声明覆盖默认页面 */
52
+ export declare function scoreMetadata(root: MusicXmlElement): Pick<ParsedMusicXmlScore, "title" | "subtitle" | "creator" | "page">;
10
53
  /** 解析书面音高及该和弦成员自己的 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;
54
+ export declare function parsePitch(note: MusicXmlElement, location: MusicXmlPitch["location"], notations?: MusicXmlReader): MusicXmlPitch | null;
55
+ export declare function transposePitch(pitch: MusicXmlPitch, chromatic: number, diatonic: number | undefined, octaves: number): void;
18
56
  /** 将支持的 fermata articulation 和 ornament 转成 jpFun 修饰符 */
19
- export declare function noteModifiers(note: MusicXmlElement): {
57
+ export declare function noteModifiers(notations: MusicXmlReader | undefined, diagnostics: MusicXmlDiagnostic[], location: MusicXmlDiagnostic["location"]): {
20
58
  name: string;
21
59
  placement: "above" | "below";
22
60
  }[];
23
61
  /** 无箭头不覆盖显式方向,两个相反的显式方向不能属于同一和弦。 */
24
62
  export declare function mergeArpeggio(current?: MusicXmlArpeggio, next?: MusicXmlArpeggio): MusicXmlArpeggio | undefined;
25
63
  /** 读取和弦成员上的琶音方向;none 表示无箭头但仍按自下而上演奏。 */
26
- export declare function noteArpeggio(note: MusicXmlElement): MusicXmlArpeggio | undefined;
64
+ export declare function noteArpeggio(notations: MusicXmlReader | undefined, location: MusicXmlPitch["location"]): MusicXmlArpeggio | undefined;
27
65
  /** 解析 tuplet 的实际音数与正常音数,并保留显式组边界 */
28
- export declare function timeModification(note: MusicXmlElement): {
66
+ export declare function timeModification(note: MusicXmlElement, tuplets: readonly MusicXmlElement[] | undefined): {
29
67
  actual: number;
30
68
  normal: number;
31
69
  start: boolean;
32
70
  stop: boolean;
33
71
  } | undefined;
72
+ /** 和弦成员可重复声明同一边界;仅确认最终事件确实持有的节奏标记 */
73
+ export declare function acceptTuplets(notations: MusicXmlReader | undefined, tuplets: readonly MusicXmlElement[] | undefined, rhythm: MusicXmlEvent["timeModification"]): void;
34
74
  /** 按 verse 收集歌词并用尾部连字符保留音节延续 */
35
75
  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): {
76
+ /** 返回 dynamics 中首个受支持的力度记号 */
77
+ export declare function directionDynamic(dynamics: MusicXmlElement | undefined, diagnostics: MusicXmlDiagnostic[], location: MusicXmlDiagnostic["location"]): string | undefined;
78
+ /** 收集排练标记与普通文字,排练标记保留方框语义;空白文字视为空内容 */
79
+ export declare function directionTexts(direction: MusicXmlReader): {
40
80
  text: string;
41
81
  boxed: boolean;
42
82
  }[];
43
83
  /** 将 metronome 的拍单位和附点折算成四分音符 BPM */
44
- export declare function metronomeBpm(direction: MusicXmlElement): number | undefined;
84
+ export declare function metronomeBpm(metronome: MusicXmlElement | undefined): number | undefined;
45
85
  /** 将单一或复合拍号归一成一个等值分数 */
46
86
  export declare function parseTimeSignature(time: MusicXmlElement): {
47
87
  numerator: number;
@@ -49,3 +89,4 @@ export declare function parseTimeSignature(time: MusicXmlElement): {
49
89
  };
50
90
  /** 展开逗号分隔的遍数与闭区间范围,并返回升序去重结果 */
51
91
  export declare function endingPasses(value: string): number[];
92
+ export {};