vexflow 5.1.2 → 5.2.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 (89) hide show
  1. package/README.md +7 -6
  2. package/build/cjs/vexflow-bravura.js +2 -2
  3. package/build/cjs/vexflow-bravura.js.map +1 -1
  4. package/build/cjs/vexflow-core.js +2 -2
  5. package/build/cjs/vexflow-core.js.map +1 -1
  6. package/build/cjs/vexflow-debug-with-tests.js +2633 -415
  7. package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
  8. package/build/cjs/vexflow-debug.js +2478 -382
  9. package/build/cjs/vexflow-debug.js.map +1 -1
  10. package/build/cjs/vexflow.js +2 -2
  11. package/build/cjs/vexflow.js.map +1 -1
  12. package/build/esm/src/accidental.js +3 -0
  13. package/build/esm/src/articulation.js +27 -14
  14. package/build/esm/src/beam.js +12 -2
  15. package/build/esm/src/clef.js +3 -0
  16. package/build/esm/src/clefnote.js +5 -1
  17. package/build/esm/src/dot.js +1 -1
  18. package/build/esm/src/easyscore/composition.js +297 -0
  19. package/build/esm/src/easyscore/elementindex.js +81 -0
  20. package/build/esm/src/easyscore/elements.js +324 -0
  21. package/build/esm/src/easyscore/policies.js +69 -0
  22. package/build/esm/src/easyscore/rhythm.js +42 -0
  23. package/build/esm/src/easyscore.js +448 -26
  24. package/build/esm/src/element.js +13 -2
  25. package/build/esm/src/factory.js +256 -60
  26. package/build/esm/src/formatter.js +32 -4
  27. package/build/esm/src/keysignature.js +9 -1
  28. package/build/esm/src/keysignote.js +2 -2
  29. package/build/esm/src/note.js +5 -0
  30. package/build/esm/src/parenthesis.js +1 -1
  31. package/build/esm/src/parser.js +6 -1
  32. package/build/esm/src/proportionalformatter.js +186 -0
  33. package/build/esm/src/registry.js +27 -0
  34. package/build/esm/src/sheet.js +20 -3
  35. package/build/esm/src/stave.js +9 -2
  36. package/build/esm/src/stavenote.js +12 -12
  37. package/build/esm/src/stemmablenote.js +6 -1
  38. package/build/esm/src/tickable.js +5 -0
  39. package/build/esm/src/tuplet.js +3 -2
  40. package/build/esm/src/version.js +3 -3
  41. package/build/esm/src/vexflow.js +2 -1
  42. package/build/esm/tests/beam_tests.js +35 -0
  43. package/build/esm/tests/easyscore_tests.js +40 -0
  44. package/build/esm/tests/easyscore_types.js +65 -0
  45. package/build/esm/tests/formatter_tests.js +41 -0
  46. package/build/esm/tests/node/easyscore-rendering-tests.mjs +332 -0
  47. package/build/esm/tests/node/easyscore-tests.mjs +953 -0
  48. package/build/esm/tests/node/proportional-spacing-tests.mjs +214 -0
  49. package/build/esm/tools/easyscore-api-audit.mjs +58 -0
  50. package/build/esm/tools/easyscore-composition.mjs +62 -0
  51. package/build/esm/tools/easyscore-example.mjs +16 -0
  52. package/build/esm/tools/easyscore-families.mjs +61 -0
  53. package/build/esm/tools/easyscore-references-example.mjs +26 -0
  54. package/build/esm/tools/easyscore-rhythm.mjs +58 -0
  55. package/build/esm/tools/easyscore-structure.mjs +88 -0
  56. package/build/esm/tools/explorer/catalog/entries.mjs +6 -0
  57. package/build/esm/tools/explorer/catalog/expression.mjs +68 -0
  58. package/build/esm/tools/explorer/catalog/helpers.mjs +29 -0
  59. package/build/esm/tools/explorer/catalog/layout.mjs +109 -0
  60. package/build/esm/tools/explorer/catalog/notes.mjs +61 -0
  61. package/build/esm/tools/explorer/catalog/staves.mjs +85 -0
  62. package/build/esm/tools/explorer/catalog/strings.mjs +25 -0
  63. package/build/esm/tools/explorer/catalog.mjs +14 -0
  64. package/build/types/src/accidental.d.ts +2 -0
  65. package/build/types/src/articulation.d.ts +6 -0
  66. package/build/types/src/beam.d.ts +2 -0
  67. package/build/types/src/clef.d.ts +2 -0
  68. package/build/types/src/easyscore/composition.d.ts +107 -0
  69. package/build/types/src/easyscore/elementindex.d.ts +30 -0
  70. package/build/types/src/easyscore/elements.d.ts +156 -0
  71. package/build/types/src/easyscore/policies.d.ts +12 -0
  72. package/build/types/src/easyscore/rhythm.d.ts +9 -0
  73. package/build/types/src/easyscore.d.ts +153 -11
  74. package/build/types/src/element.d.ts +5 -1
  75. package/build/types/src/factory.d.ts +91 -8
  76. package/build/types/src/formatter.d.ts +7 -1
  77. package/build/types/src/keysignature.d.ts +3 -0
  78. package/build/types/src/keysignote.d.ts +1 -1
  79. package/build/types/src/note.d.ts +2 -0
  80. package/build/types/src/parser.d.ts +5 -0
  81. package/build/types/src/proportionalformatter.d.ts +30 -0
  82. package/build/types/src/registry.d.ts +4 -0
  83. package/build/types/src/stave.d.ts +2 -0
  84. package/build/types/src/stavenote.d.ts +1 -1
  85. package/build/types/src/stemmablenote.d.ts +6 -1
  86. package/build/types/src/tickable.d.ts +2 -0
  87. package/build/types/src/vexflow.d.ts +2 -1
  88. package/changelog/CHANGELOG.md +35 -0
  89. package/package.json +7 -2
@@ -0,0 +1,953 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import assert from 'node:assert/strict';
11
+ import { readFileSync } from 'node:fs';
12
+ import test from 'node:test';
13
+ import { createCanvas, registerFont } from 'canvas';
14
+ const VF = await import(new URL('../../build/esm/entry/vexflow-core.js', import.meta.url));
15
+ for (const [family, file] of [
16
+ ['Bravura', 'bravura/bravura'],
17
+ ['Academico', 'academico/academico'],
18
+ ]) {
19
+ registerFont(new URL(`../../node_modules/@vexflow-fonts/${file}.otf`, import.meta.url).pathname, { family });
20
+ }
21
+ VF.Element.setTextMeasurementCanvas(createCanvas(1, 1));
22
+ const renderer = { elementId: null, width: 500, height: 240 };
23
+ const create = (options) => VF.EasyScore.create({ renderer }, options);
24
+ const queued = (score) => score.factory.renderQ.length;
25
+ const registered = (registry) => Object.values(registry.index.id).flatMap(Object.values);
26
+ test('pure parsing returns source spans and diagnostics without rendering or hooks', () => {
27
+ const score = new VF.EasyScore();
28
+ let calls = 0;
29
+ score.addCommitHook(() => calls++);
30
+ const source = 'C4/q,\n D4[articulations="fermata"]';
31
+ const parsed = score.parseNotation(source);
32
+ assert.equal(parsed.success, true);
33
+ assert.equal(calls, 0);
34
+ assert.equal(score.builder.getElements().notes.length, 0);
35
+ assert.deepEqual(parsed.pieces.map((p) => p.duration), ['q', 'q']);
36
+ assert.equal(source.slice(parsed.pieces[1].source.start, parsed.pieces[1].source.end), 'D4[articulations="fermata"]');
37
+ for (const line of ['C4/q, invalid', 'C4/999', 'C4/q[stem="sideways"]', 'C4/q[articulations="notAMark"]']) {
38
+ const result = score.parseNotation(line);
39
+ assert.equal(result.success, false, line);
40
+ assert.deepEqual(result.pieces, []);
41
+ assert.ok(result.diagnostics[0].code);
42
+ assert.ok(result.diagnostics[0].end >= result.diagnostics[0].start);
43
+ }
44
+ const bad = score.parseNotation('C4/q,\n X4');
45
+ assert.equal(bad.diagnostics[0].line, 2);
46
+ assert.equal(bad.diagnostics[0].column, 2);
47
+ });
48
+ test('legacy parse results and custom builders remain supported', () => {
49
+ const factory = new VF.Factory({ renderer });
50
+ class CustomBuilder extends VF.Builder {
51
+ constructor() {
52
+ super(...arguments);
53
+ this.commits = 0;
54
+ }
55
+ commitPiece(source) {
56
+ this.commits++;
57
+ super.commitPiece(source);
58
+ }
59
+ }
60
+ const builder = new CustomBuilder(factory);
61
+ const score = factory.EasyScore({ builder });
62
+ assert.equal(score.parse('C4/q, invalid').success, false);
63
+ assert.equal(builder.commits, 1);
64
+ assert.equal(queued(score), 1, 'legacy non-throwing parse retains its partial result');
65
+ assert.equal(new VF.EasyScore().parse('C4/q[application="value"]').success, true);
66
+ const strict = factory.EasyScore({ builder, throwOnError: true });
67
+ let hooks = 0;
68
+ strict.addCommitHook(() => hooks++);
69
+ strict.notes('D4/q, E4');
70
+ assert.equal(builder.commits, 3, 'preflight does not execute the custom builder');
71
+ assert.equal(hooks, 2, 'hooks execute once per note');
72
+ });
73
+ test('validation respects replaced hooks and preserves legacy parse defaults', () => {
74
+ const factory = new VF.Factory({ renderer });
75
+ let custom = '';
76
+ const score = factory.EasyScore({
77
+ throwOnError: true,
78
+ commitHooks: [
79
+ (options) => {
80
+ custom = options.articulations;
81
+ },
82
+ ],
83
+ });
84
+ score.notes('C4/q[articulations="application-specific"]');
85
+ assert.equal(custom, 'application-specific');
86
+ score.set({ clef: 'bass', stem: 'down' });
87
+ score.parse('C4/q');
88
+ assert.equal(score.builder.getElements().notes[0].getKeyProps()[0].line, new VF.StaveNote({ keys: ['c/4'], duration: 'q', clef: 'treble' }).getKeyProps()[0].line, 'parse retains Builder defaults');
89
+ assert.equal(score.notes('C4/q')[0].getKeyProps()[0].line, new VF.StaveNote({ keys: ['c/4'], duration: 'q', clef: 'bass' }).getKeyProps()[0].line, 'notes applies score defaults');
90
+ assert.equal(score.parseNotation('C4/q', { durationOverride: new VF.Fraction(-1, 1) }).success, false);
91
+ });
92
+ test('strict failures preserve prior notes, Factory queues, and the ambient registry', () => {
93
+ const registry = new VF.Registry();
94
+ VF.Registry.enableDefaultRegistry(registry);
95
+ try {
96
+ const score = create();
97
+ const existing = score.notes('C4/w[id="keep"]');
98
+ const initial = registered(registry);
99
+ for (const line of ['D4/q, invalid', 'D4/9', 'D4/q[typo="oops"]']) {
100
+ assert.throws(() => score.notes(line), VF.EasyScoreError);
101
+ assert.equal(queued(score), 1);
102
+ assert.deepEqual(registered(registry), initial);
103
+ assert.equal(score.builder.getElements().notes, existing);
104
+ }
105
+ let leaked;
106
+ score.addCommitHook((options, note) => {
107
+ leaked = note;
108
+ if (options.id === 'fail')
109
+ throw new Error('application hook failed');
110
+ });
111
+ assert.throws(() => score.notes('D4/q, E4[id="fail"]'), /application hook failed/);
112
+ assert.equal(queued(score), 1);
113
+ assert.deepEqual(registered(registry), initial);
114
+ assert.equal(registry.getElementById('keep'), existing[0]);
115
+ assert.equal(VF.Factory.getOwner(leaked), undefined);
116
+ leaked.setAttribute('id', 'after-failure');
117
+ assert.equal(registry.getElementById('after-failure'), undefined, 'failed objects are detached from registry');
118
+ assert.equal(VF.Registry.getDefaultRegistry(), registry, 'ambient registry is not replaced');
119
+ }
120
+ finally {
121
+ VF.Registry.disableDefaultRegistry();
122
+ }
123
+ });
124
+ test('measure validation is atomic and diagnostics use the complete source', () => {
125
+ const score = create({ extensions: ['label'] });
126
+ const good = score.measures('C4/h[label="a|b"], D4, |, E4, F4');
127
+ assert.deepEqual(good.map((notes) => notes.map((n) => n.getDuration())), [
128
+ ['h', 'h'],
129
+ ['h', 'h'],
130
+ ]);
131
+ const before = queued(score);
132
+ assert.throws(() => score.measures('C4/w |\n invalid'), (error) => {
133
+ assert.equal(error.diagnostics[0].measure, 2);
134
+ assert.equal(error.diagnostics[0].line, 2);
135
+ assert.equal(error.diagnostics[0].column, 2);
136
+ return true;
137
+ });
138
+ assert.equal(queued(score), before);
139
+ score.addCommitHook((options) => {
140
+ if (options.id === 'fail')
141
+ throw new Error('measure hook');
142
+ });
143
+ assert.throws(() => score.measures('C4/w | D4/w[id="fail"]'), /measure hook/);
144
+ assert.equal(queued(score), before);
145
+ assert.equal(score.builder.getElements().notes, good[1]);
146
+ const legacy = new VF.Factory({ renderer }).EasyScore();
147
+ assert.throws(() => legacy.measures('C4/w | invalid'), VF.EasyScoreError);
148
+ assert.equal(queued(legacy), 0);
149
+ });
150
+ test('native note options and explicit articulation vocabulary reach the constructed objects', () => {
151
+ const score = create();
152
+ const shifted = score.notes('C4/q', { octaveShift: 1, alignCenter: true })[0];
153
+ const native = new VF.StaveNote({ keys: ['c/4'], duration: 'q', octaveShift: 1, alignCenter: true });
154
+ assert.equal(shifted.getKeyProps()[0].line, native.getKeyProps()[0].line);
155
+ assert.equal(shifted.isCenterAligned(), true);
156
+ const inline = score.notes('C4/q[octaveShift="1"]')[0];
157
+ assert.equal(inline.getKeyProps()[0].line, native.getKeyProps()[0].line);
158
+ for (const [name, code] of [
159
+ ['staccato', 'a.'],
160
+ ['fermata', 'a@'],
161
+ ['a.', 'a.'],
162
+ ['fermataAbove', VF.VexFlow.Glyphs.fermataAbove],
163
+ ]) {
164
+ const note = score.notes(`C4/q[articulations="${name}"]`)[0];
165
+ assert.equal(note.getModifiers()[0].type, code);
166
+ }
167
+ assert.equal(VF.Articulation.parseEasyScore('a,.below')[0].type, 'a,');
168
+ const below = score.notes('C4/q[articulations="fermata.below"]')[0].getModifiers()[0];
169
+ assert.equal(below.getPosition(), VF.Modifier.Position.BELOW);
170
+ assert.throws(() => score.notes('C4/q[articulations="typo"]'), /Unknown EasyScore articulation/);
171
+ });
172
+ test('voice modes, native meter, spacing options, and rational tuplets work before insertion', () => {
173
+ const score = create();
174
+ const notes = score.notes('C4/h, D4/q, E4');
175
+ const voice = score.voice(notes, {
176
+ time: { numBeats: 4, beatValue: 4, resolution: VF.VexFlow.RESOLUTION },
177
+ options: { softmaxFactor: 1 },
178
+ });
179
+ assert.deepEqual(notes.map((n) => voice.softmax(n.getTicks().value())), [1 / 3, 1 / 3, 1 / 3]);
180
+ const soft = score.voice(score.notes('C4/w, D4/w'), { mode: 'soft' });
181
+ assert.equal(soft.getMode(), VF.VoiceMode.SOFT);
182
+ const full = score.voice(score.notes('C4/q'), { mode: 'full' });
183
+ assert.equal(full.getMode(), VF.VoiceMode.FULL);
184
+ const before = score.factory.getVoices().length;
185
+ assert.throws(() => score.voice(notes, { time: '1/4' }), /Too many ticks/);
186
+ assert.equal(score.factory.getVoices().length, before);
187
+ assert.equal(notes[0].getVoice(), voice, 'overflow does not reassign already-owned notes');
188
+ const odd = score.notes('C5/8, D5, E5, F5, G5, A5, B5');
189
+ assert.equal(score.voice(odd, { time: '7/8' }).isComplete(), true);
190
+ const nested = score.notes('C5/8, D5, E5');
191
+ assert.equal(score.tuplet(nested), nested);
192
+ assert.equal(score.tuplet(nested), nested);
193
+ const expected = nested.reduce((ticks, note) => ticks.add(note.getTicks()), new VF.Fraction(0, 1));
194
+ assert.equal(score.voice(nested, { mode: 'soft' }).getTicksUsed().equals(expected), true);
195
+ });
196
+ test('annotation attachment and ties have validated ownership and no duplicate queue entries', () => {
197
+ const score = create();
198
+ const notes = score.notes('(C4 E4 G4)/h, (C4 F4 A4)');
199
+ const annotation = score.make.annotation({ text: 'dolce' });
200
+ assert.equal(score.attach(notes[0], annotation), notes[0]);
201
+ score.attach(notes[0], annotation);
202
+ assert.equal(notes[0].getModifiers().length, 1);
203
+ assert.equal(queued(score), 2, 'attached annotation has no independent draw step');
204
+ const tie = score.make.tie({ from: notes[0], to: notes[1], firstIndexes: [0], lastIndexes: [0] });
205
+ assert.ok(tie instanceof VF.StaveTie);
206
+ assert.equal(queued(score), 3);
207
+ for (const indices of [[-1], [3], [0.5], []]) {
208
+ assert.throws(() => score.make.tie({ from: notes[0], to: notes[1], firstIndexes: indices, lastIndexes: indices }));
209
+ }
210
+ assert.equal(queued(score), 3);
211
+ const foreign = create();
212
+ assert.throws(() => score.make.tie({ from: notes[0], to: foreign.notes('C4/h')[0] }), /Factory/);
213
+ assert.throws(() => score.attach(notes[0], foreign.make.annotation({ text: 'wrong' })), /Factory/);
214
+ assert.throws(() => score.attach(notes[1], annotation), /already attached/);
215
+ class BrokenModifier extends VF.Annotation {
216
+ getNote() {
217
+ throw new Error('custom getter failed');
218
+ }
219
+ }
220
+ assert.throws(() => score.attach(notes[0], new BrokenModifier('broken')), /custom getter failed/);
221
+ const native = new VF.Annotation('custom');
222
+ score.attach(notes[1], native);
223
+ assert.equal(native.getNote(), notes[1]);
224
+ score.reset();
225
+ assert.equal(queued(score), 0);
226
+ assert.deepEqual(score.builder.getElements().notes, []);
227
+ });
228
+ test('public modules and implemented contracts have coverage entries', () => __awaiter(void 0, void 0, void 0, function* () {
229
+ const manifest = JSON.parse(readFileSync(new URL('../../docs/easyscore-coverage.json', import.meta.url), 'utf8'));
230
+ const source = readFileSync(new URL('../../src/index.ts', import.meta.url), 'utf8');
231
+ const modules = [...source.matchAll(/^export \* from '\.\/([^']+)';/gm)].map((m) => m[1]);
232
+ const classified = Object.values(manifest.modules).flat();
233
+ assert.equal(new Set(classified).size, classified.length, 'each module has one classification');
234
+ assert.deepEqual([...classified].sort(), modules.sort());
235
+ const guide = readFileSync(new URL('../../docs/easyscore.md', import.meta.url), 'utf8');
236
+ const testSources = ['easyscore-tests.mjs', 'easyscore-rendering-tests.mjs']
237
+ .map((file) => readFileSync(new URL(file, import.meta.url), 'utf8'))
238
+ .join('\n');
239
+ const { examples } = yield import('../../tools/explorer/catalog.mjs');
240
+ const { nativeSurface } = yield import('../../tools/easyscore-api-audit.mjs');
241
+ const helpers = nativeSurface()['easyscore/elements'].EasyScoreElements.filter((signature) => !signature.startsWith('constructor('))
242
+ .map((signature) => `make.${signature.split('(')[0]}()`);
243
+ assert.deepEqual(manifest.implemented
244
+ .filter((feature) => feature.api.startsWith('make.'))
245
+ .map((feature) => feature.api)
246
+ .sort(), helpers.sort(), 'every named helper needs a coverage row');
247
+ assert.equal(new Set(manifest.implemented.map((feature) => feature.api)).size, manifest.implemented.length);
248
+ for (const feature of manifest.implemented) {
249
+ if (feature.api.startsWith('make.'))
250
+ assert.ok(feature.example, `${feature.api} needs an executable example`);
251
+ if (feature.example)
252
+ assert.ok(examples.some((example) => example.id === feature.example), feature.example);
253
+ assert.ok(guide.includes(feature.api), feature.api);
254
+ assert.ok(testSources.includes(feature.test), feature.api);
255
+ }
256
+ }));
257
+ test('score-local IDs follow renames and reject collisions before mutation', () => {
258
+ const score = create();
259
+ const other = create();
260
+ const [a, b] = score.notes('C4/h[id="a"], D4[id="b"]');
261
+ const [independent] = other.notes('E4/w[id="a"]');
262
+ assert.equal(score.getElement('a'), a);
263
+ assert.equal(other.getElement('a'), independent);
264
+ assert.equal(score.getElement('missing'), undefined);
265
+ assert.throws(() => score.getNote('missing'), /No note with ID/);
266
+ const label = score.make.annotation({ text: 'test' });
267
+ assert.equal(score.getElement(label.getAttribute('id')), label);
268
+ assert.throws(() => score.getNote(label.getAttribute('id')), /No note with ID/);
269
+ a.setAttribute('id', 'renamed');
270
+ assert.equal(score.getElement('a'), undefined);
271
+ assert.equal(score.getNote('renamed'), a);
272
+ assert.throws(() => a.setAttribute('id', 'b'), /Duplicate score element ID/);
273
+ assert.throws(() => a.setAttribute('id', undefined), /nonempty ID/);
274
+ assert.equal(a.getAttribute('id'), 'renamed');
275
+ assert.equal(score.getNote('b'), b);
276
+ score.reset();
277
+ assert.equal(score.getElement('renamed'), undefined);
278
+ a.setAttribute('id', 'b');
279
+ assert.equal(other.getNote('a'), independent);
280
+ });
281
+ test('source mapping preserves complete measure input and survives native ID changes', () => {
282
+ const score = create();
283
+ const input = ' C4/h[id="a"], D4 |\n E4[articulations="staccato"], F4 ';
284
+ const measures = score.measures(input);
285
+ const note = measures[1][0];
286
+ const source = score.getSource(note);
287
+ assert.equal(source.input, input);
288
+ assert.equal(source.measure, 2);
289
+ assert.equal(input.slice(source.start, source.end), 'E4[articulations="staccato"]');
290
+ assert.deepEqual(score.getSource(note.getModifiers()[0]), source);
291
+ assert.deepEqual(VF.EasyScore.getSource(note), source);
292
+ assert.equal(create().getSource(note), undefined);
293
+ note.setAttribute('id', 'changed');
294
+ assert.deepEqual(score.getSource(note), source);
295
+ source.start = 999;
296
+ assert.notEqual(score.getSource(note).start, 999);
297
+ const native = score.adopt(new VF.StaveNote({ keys: ['g/4'], duration: 'q' }), 'note');
298
+ assert.equal(score.getSource(native), undefined);
299
+ score.reset();
300
+ assert.equal(score.getSource(note), undefined);
301
+ assert.equal(VF.EasyScore.getSource(note), undefined);
302
+ });
303
+ test('failed construction rolls back references, source metadata, and ID subscriptions', () => {
304
+ const score = create();
305
+ const [keep] = score.notes('C4/w[id="keep"]');
306
+ let escaped;
307
+ score.addCommitHook((options, note) => {
308
+ if (options.id === 'temporary')
309
+ escaped = note;
310
+ });
311
+ const registry = new VF.Registry();
312
+ registry.register(keep);
313
+ VF.Registry.enableDefaultRegistry(registry);
314
+ try {
315
+ assert.throws(() => score.measures('D4/w[id="temporary"] | E4/w[id="keep"]'), /Duplicate score element ID/);
316
+ assert.equal(score.getElement('temporary'), undefined);
317
+ assert.equal(score.getNote('keep'), keep);
318
+ assert.equal(queued(score), 1);
319
+ assert.equal(VF.Factory.getOwner(escaped), undefined);
320
+ assert.equal(VF.EasyScore.getSource(escaped), undefined);
321
+ assert.deepEqual(registered(registry), [keep]);
322
+ escaped.setAttribute('id', 'keep');
323
+ keep.setAttribute('id', 'retained');
324
+ assert.equal(registry.getElementById('retained'), keep);
325
+ assert.equal(score.getNote('retained'), keep);
326
+ }
327
+ finally {
328
+ VF.Registry.disableDefaultRegistry();
329
+ }
330
+ const legacy = new VF.Factory({ renderer }).EasyScore();
331
+ assert.equal(legacy.parse('C4/q[id="partial"], invalid').success, false);
332
+ assert.equal(legacy.getNote('partial'), legacy.builder.elements.notes[0]);
333
+ assert.equal(legacy.getSource(legacy.getNote('partial')).input, 'C4/q[id="partial"], invalid');
334
+ });
335
+ test('native adoption validates roles and ownership without duplicate drawing entries', () => {
336
+ const score = create();
337
+ const note = new VF.StaveNote({ keys: ['c/4'], duration: 'w' });
338
+ const label = new VF.Annotation('native');
339
+ const other = create();
340
+ assert.throws(() => score.adopt(note, 'modifier'), /Invalid adopted element role/);
341
+ assert.throws(() => score.adopt(label, 'drawable'), /Invalid adopted element role/);
342
+ assert.throws(() => score.adopt(new VF.Clef('treble'), 'drawable'), /Invalid adopted element role/);
343
+ assert.throws(() => score.adopt(null, 'drawable'), /Invalid adopted element role/);
344
+ assert.equal(score.getElement(note.getAttribute('id')), undefined);
345
+ assert.equal(VF.Factory.getOwner(note), undefined);
346
+ assert.equal(score.adopt(note, 'note'), note);
347
+ score.adopt(note, 'note');
348
+ assert.equal(queued(score), 1);
349
+ assert.equal(score.getNote(note.getAttribute('id')), note);
350
+ assert.throws(() => other.adopt(note, 'note'), /another Factory/);
351
+ assert.equal(other.getElement(note.getAttribute('id')), undefined);
352
+ score.adopt(label, 'modifier');
353
+ score.attach(note, label);
354
+ score.attach(note, label);
355
+ assert.equal(queued(score), 1);
356
+ assert.equal(note.getModifiers().length, 1);
357
+ assert.equal(VF.Factory.getOwner(label), score.factory);
358
+ const voice = score.voice([note]);
359
+ assert.throws(() => score.adopt(voice, 'drawable'), /Invalid adopted element role/);
360
+ assert.equal(score.getElement(voice.getAttribute('id')), voice);
361
+ const conflict = new VF.Annotation('conflict').setAttribute('id', note.getAttribute('id'));
362
+ assert.throws(() => score.adopt(conflict, 'modifier'), /Duplicate score element ID/);
363
+ assert.equal(VF.Factory.getOwner(conflict), undefined);
364
+ assert.throws(() => score.factory.transaction(() => {
365
+ score.factory.adopt(note, 'note');
366
+ throw new Error('later failure');
367
+ }), /later failure/);
368
+ assert.equal(VF.Factory.getOwner(note), score.factory, 'rollback preserves prior ownership');
369
+ score.reset();
370
+ assert.equal(queued(score), 0);
371
+ score.adopt(note, 'note');
372
+ assert.equal(queued(score), 1, 'explicit readoption queues a note after reset');
373
+ });
374
+ test('failed native attachment releases newly adopted ownership and references', () => {
375
+ const score = create();
376
+ class RefusingNote extends VF.StaveNote {
377
+ addModifier() {
378
+ throw new Error('custom attachment failed');
379
+ }
380
+ }
381
+ const note = score.adopt(new RefusingNote({ keys: ['c/4'], duration: 'w' }), 'note');
382
+ const label = new VF.Annotation('custom');
383
+ assert.throws(() => score.attach(note, label), /custom attachment failed/);
384
+ assert.equal(VF.Factory.getOwner(label), undefined);
385
+ assert.equal(score.getElement(label.getAttribute('id')), undefined);
386
+ assert.equal(VF.Factory.getOwner(note), score.factory);
387
+ assert.equal(queued(score), 1);
388
+ label.setAttribute('id', note.getAttribute('id'));
389
+ });
390
+ test('native public option families match the reviewed coverage snapshot', () => __awaiter(void 0, void 0, void 0, function* () {
391
+ const { checkNativeSurface } = yield import('../../tools/easyscore-api-audit.mjs');
392
+ checkNativeSurface();
393
+ }));
394
+ test('pure typed validators reject custom options before construction and preserve caller settings', () => {
395
+ let commits = 0;
396
+ const score = create({
397
+ extensions: ['label'],
398
+ validate: ({ piece, options }) => {
399
+ assert.equal(typeof piece.source.start, 'number');
400
+ if (options.label && options.label !== 'melody')
401
+ throw new Error('Unknown label');
402
+ piece.chord[0].key = 'Z';
403
+ },
404
+ });
405
+ score.addCommitHook(() => commits++);
406
+ const parsed = score.parseNotation('C4/q[label="melody"]');
407
+ assert.equal(parsed.pieces[0].chord[0].key, 'C');
408
+ assert.equal(score.parseNotation('D4/q[label="bad"]').diagnostics[0].message, 'Unknown label');
409
+ assert.throws(() => score.notes('C4/q[label="bad"]'), /Unknown label/);
410
+ assert.equal(commits, 0);
411
+ assert.equal(queued(score), 0);
412
+ score.notes('C4/w[label="melody"]');
413
+ assert.equal(commits, 1);
414
+ const factory = score.factory;
415
+ const options = Object.freeze({ throwOnError: true });
416
+ assert.doesNotThrow(() => factory.EasyScore(options));
417
+ assert.doesNotThrow(() => factory.System(Object.freeze({ x: 20, y: 20, width: 400 })));
418
+ const note = score.builder.elements.notes[0];
419
+ assert.equal(factory.TextBracket({ from: note, to: note, text: '8', options: { superscript: 'va', position: 'top', line: 0 } })
420
+ .line, 0);
421
+ assert.equal(factory.VibratoBracket({ from: note, to: note, options: { line: 0 } }).line, 0);
422
+ });
423
+ test('facade sheets and nested build groups share ownership and rollback', () => {
424
+ const score = create();
425
+ score.setContext(new VF.CanvasContext(createCanvas(500, 240).getContext('2d')));
426
+ const [keep] = score.notes('C4/w[id="keep"]');
427
+ const original = score.builder.elements;
428
+ let discarded;
429
+ assert.throws(() => score.build(() => {
430
+ score.notes('D4/w[id="temporary"]');
431
+ score.build(() => {
432
+ discarded = score.make.annotation({ text: 'temporary' });
433
+ });
434
+ score.sheet({ width: 500 }).addSystem();
435
+ throw new Error('cancel group');
436
+ }), /cancel group/);
437
+ assert.equal(score.getElement('temporary'), undefined);
438
+ assert.equal(score.getElement(discarded.getAttribute('id')), undefined);
439
+ assert.equal(VF.Factory.getOwner(discarded), undefined);
440
+ assert.equal(score.factory.sheets.length, 0);
441
+ assert.equal(score.factory.systems.length, 0);
442
+ assert.equal(score.builder.elements, original);
443
+ assert.equal(score.getNote('keep'), keep);
444
+ const sheet = score.build((builder) => builder.sheet({ width: 500 }));
445
+ const system = sheet.addSystem();
446
+ const voice = score.voice([keep]);
447
+ system.addStave({ voices: [voice] }).addClef('treble');
448
+ assert.equal(VF.Factory.getOwner(system), score.factory);
449
+ assert.deepEqual(sheet.getSystems(), [system]);
450
+ assert.equal(score.factory.sheets.length, 1);
451
+ score.draw({ retain: true });
452
+ assert.equal(sheet.getRows().length, 1);
453
+ assert.throws(() => score.build(() => Promise.resolve()), /synchronous callback/);
454
+ score.reset();
455
+ assert.equal(score.factory.sheets.length, 0);
456
+ });
457
+ test('typed sequences and modifier constructors preserve native fields and ownership', () => {
458
+ const score = create().set({ clef: 'bass', stem: 'down' });
459
+ const note = score.make.note({
460
+ keys: ['c/3/x'],
461
+ duration: 'q',
462
+ octaveShift: 1,
463
+ strokePx: 4,
464
+ stemDirection: VF.Stem.UP,
465
+ });
466
+ assert.equal(note.getStemDirection(), VF.Stem.UP);
467
+ assert.equal(note.isAutoStem(), false);
468
+ assert.equal(note.getKeyProps()[0].code, new VF.StaveNote({ keys: ['c/3/x'], duration: 'q', clef: 'bass', octaveShift: 1 }).getKeyProps()[0].code);
469
+ const constructors = [
470
+ ['accidental', [{ type: '++' }], VF.Accidental],
471
+ ['articulation', [{ type: 'fermata.below' }], VF.Articulation],
472
+ ['ornament', ['tr', { delayed: true, upperAccidental: '#' }], VF.Ornament],
473
+ ['dot', [], VF.Dot],
474
+ ['parenthesis', [VF.Modifier.Position.LEFT], VF.Parenthesis],
475
+ ['stroke', [VF.Stroke.Type.ROLL_UP, { allVoices: false }], VF.Stroke],
476
+ ['tremolo', [3], VF.Tremolo],
477
+ ['vibrato', [], VF.Vibrato],
478
+ ['chordSymbol', [{ fontSize: 14 }], VF.ChordSymbol],
479
+ ['fingering', [{ number: '2', position: 'left' }], VF.FretHandFinger],
480
+ ['stringNumber', [{ number: '4', position: 'above' }, false], VF.StringNumber],
481
+ ];
482
+ for (const [name, args, Native] of constructors) {
483
+ const modifier = score.make[name](...args);
484
+ assert.ok(modifier instanceof Native, name);
485
+ assert.equal(VF.Factory.getOwner(modifier), score.factory, name);
486
+ score.attach(note, modifier);
487
+ assert.equal(modifier.getNote(), note, name);
488
+ }
489
+ assert.throws(() => score.make.articulation({ type: 'no-such-mark' }), /Unknown EasyScore articulation/);
490
+ const ghost = score.make.ghostNote('q');
491
+ const text = score.make.textNote({ text: 'rit.', duration: 'q', line: 2, smooth: true });
492
+ const sequence = score.sequence([note, ghost, text, { keys: ['d/3'], duration: 'q' }]);
493
+ assert.equal(score.voice(sequence).getTicksUsed().value(), VF.VexFlow.RESOLUTION);
494
+ const count = queued(score);
495
+ assert.throws(() => score.sequence(['C4/q[id="rolled-back"]', create().notes('D4/q')[0]]), /another Factory/);
496
+ assert.equal(score.getElement('rolled-back'), undefined);
497
+ assert.equal(queued(score), count);
498
+ });
499
+ test('grace and subnote groups own children exactly once and restore them after failed batches', () => {
500
+ const score = create();
501
+ const [parent, child] = score.notes('C4/h, D4');
502
+ const grace = score.make.graceNote({ keys: ['e/4'], duration: '16', slash: true });
503
+ assert.throws(() => score.build(() => {
504
+ score.make.noteSubGroup({ notes: [child] });
505
+ throw new Error('cancel group');
506
+ }), /cancel group/);
507
+ assert.equal(VF.Factory.getGroup(child), undefined);
508
+ assert.throws(() => child.getVoice(), /NoVoice/);
509
+ assert.equal(queued(score), 2, 'batch rollback restores standalone drawing');
510
+ const group = score.make.graceNoteGroup({ notes: [grace], slur: true });
511
+ score.attach(parent, group);
512
+ assert.equal(VF.Factory.getGroup(grace), group);
513
+ assert.throws(() => score.make.graceNoteGroup({ notes: [grace] }), /already belongs to a group/);
514
+ assert.throws(() => score.voice([grace]), /Grouped notes/);
515
+ assert.throws(() => score.adopt(grace, 'note'), /grouped note/);
516
+ const sub = score.make.noteSubGroup({ notes: [child] });
517
+ score.attach(parent, sub);
518
+ assert.equal(queued(score), 1, 'subnotes are removed from the standalone queue');
519
+ const foreign = create().make.graceNote({ keys: ['c/4'], duration: '16' });
520
+ assert.throws(() => score.make.graceNoteGroup({ notes: [foreign] }), /another Factory/);
521
+ const voiced = score.notes('F4/w')[0];
522
+ score.voice([voiced]);
523
+ assert.throws(() => score.make.noteSubGroup({ notes: [voiced] }), /voiced note/);
524
+ });
525
+ test('automatic beams preserve explicit stems, rational ticks, and native grouping options', () => {
526
+ const score = create().set({ time: '7/8' });
527
+ const notes = score.notes('C4/8[stem="down"], D4, E4, F4, G4, A4, B4');
528
+ const ticks = notes.map((note) => note.getTicks().toString());
529
+ const groups = [new VF.Fraction(2, 8), new VF.Fraction(2, 8), new VF.Fraction(3, 8)];
530
+ const beams = score.autoBeam(notes, { groups, flatBeams: true, flatBeamOffset: 20 });
531
+ assert.deepEqual(beams.map((beam) => beam.getNotes().length), [2, 2, 3]);
532
+ assert.deepEqual(notes.map((note) => note.getTicks().toString()), ticks);
533
+ assert.deepEqual(groups.map((group) => group.toString()), ['2/8', '2/8', '3/8']);
534
+ assert.equal(notes[1].getStemDirection(), VF.Stem.DOWN);
535
+ assert.equal(beams[0].renderOptions.flatBeamOffset, 20);
536
+ assert.ok(beams.every((beam) => VF.Factory.getOwner(beam) === score.factory));
537
+ score.voice(notes, { time: '7/8' });
538
+ assert.throws(() => score.autoBeam(notes), /already belongs/);
539
+ const mixed = score.notes('C4/8[stem="down"], D4[stem="up"]');
540
+ score.autoBeam(mixed);
541
+ assert.deepEqual(mixed.map((note) => note.getStemDirection()), [VF.Stem.DOWN, VF.Stem.UP]);
542
+ const preserve = score.notes('C4/8, C6');
543
+ const before = preserve.map((note) => note.getStemDirection());
544
+ score.autoBeam(preserve, { autoStem: false });
545
+ assert.deepEqual(preserve.map((note) => note.getStemDirection()), before);
546
+ const override = score.notes('C4/8[stem="down"], D4[stem="down"]');
547
+ score.autoBeam(override, { autoStem: true });
548
+ assert.deepEqual(override.map((note) => note.getStemDirection()), [VF.Stem.UP, VF.Stem.UP]);
549
+ const rests = score.notes('C4/8, B4/8/r, D4/8, E4/8');
550
+ assert.equal(score.autoBeam(rests, {
551
+ groups: [new VF.Fraction(4, 8)],
552
+ beamRests: true,
553
+ beamMiddleOnly: true,
554
+ showStemlets: true,
555
+ }).length, 1);
556
+ const untouched = score.notes('C4/8, D4');
557
+ assert.throws(() => score.autoBeam(untouched, { groups: [new VF.Fraction(0, 1)] }), /positive finite/);
558
+ assert.ok(untouched.every((note) => !note.hasBeam()));
559
+ assert.throws(() => score.autoBeam([create().notes('C4/8')[0]]), /this Factory/);
560
+ });
561
+ test('tuplet handles preserve nested ratios and reject invalid late timing changes', () => {
562
+ const score = create();
563
+ const notes = score.notes('C4/8, D4, E4, F4, G4, A4');
564
+ const inner = score.make.tuplet({
565
+ notes: notes.slice(0, 3),
566
+ options: { numNotes: 3, notesOccupied: 2, yOffset: 0, textYOffset: 0 },
567
+ });
568
+ const outer = score.make.tuplet({ notes, options: { numNotes: 5, notesOccupied: 4, ratioed: true } });
569
+ assert.ok(inner instanceof VF.Tuplet && outer instanceof VF.Tuplet);
570
+ assert.equal(inner.options.yOffset, 0);
571
+ const eighth = new VF.Fraction(VF.VexFlow.RESOLUTION, 8);
572
+ assert.ok(notes[0].getTicks().equals(eighth.clone().multiply(2, 3).multiply(4, 5)));
573
+ score.autoBeam(notes, { groups: [new VF.Fraction(1, 4)] });
574
+ score.voice(notes, { mode: 'soft' });
575
+ assert.throws(() => score.make.tuplet({ notes }), /before inserting/);
576
+ const fresh = score.notes('C4/8, D4, E4');
577
+ const ticks = fresh.map((note) => note.getTicks().toString());
578
+ assert.throws(() => score.make.tuplet({ notes: fresh, options: { notesOccupied: 0 } }), /positive integers/);
579
+ assert.deepEqual(fresh.map((note) => note.getTicks().toString()), ticks);
580
+ });
581
+ test('relationship helpers reject foreign or invalid endpoints and preserve native customization', () => {
582
+ const score = create();
583
+ const [from, to] = score.notes('(C4 E4)/h, (C5 E5)');
584
+ const spans = [
585
+ score.make.curve({ from, to, options: { thickness: 3 } }),
586
+ score.make.hairpin({ from, to, type: 1, options: { height: 14, yShift: 0 } }),
587
+ score.make.line({ from, to, firstIndexes: [1], lastIndexes: [0], options: { text: 'gliss.' } }),
588
+ score.make.textBracket({ from, to, text: '8', options: { superscript: 'va', position: 'top', line: 0 } }),
589
+ score.make.vibratoBracket({ from, to, options: { line: 0 } }),
590
+ score.make.pedalMarking({ notes: [from, to], options: { style: 'mixed' } }),
591
+ ];
592
+ assert.ok(spans.every((span) => VF.Factory.getOwner(span) === score.factory));
593
+ assert.equal(spans[0].renderOptions.thickness, 3);
594
+ assert.equal(spans[1].renderOptions.height, 14);
595
+ const count = queued(score);
596
+ const foreign = create().notes('C4/w')[0];
597
+ for (const build of [
598
+ () => score.make.curve({ from, to: foreign }),
599
+ () => score.make.hairpin({ type: 1 }),
600
+ () => score.make.line({ from, to, firstIndexes: [2], lastIndexes: [0] }),
601
+ () => score.make.textBracket({ from, text: '8', options: { superscript: 'va', position: 'top' } }),
602
+ () => score.make.pedalMarking({ notes: [foreign] }),
603
+ () => score.make.tie({ from: score.make.annotation({ text: 'not a note' }) }),
604
+ ])
605
+ assert.throws(build);
606
+ assert.equal(queued(score), count);
607
+ assert.ok(score.make.curve({ from }) instanceof VF.Curve);
608
+ assert.throws(() => score.make.hairpin({ to, type: 2 }), /endpoint/);
609
+ assert.ok(score.make.vibratoBracket({ from: null, to, options: { line: 1 } }) instanceof VF.VibratoBracket);
610
+ const duration = new VF.Fraction(1, 8);
611
+ const dynamics = score.make.textDynamics({ text: 'sfz', duration: 'q', durationOverride: duration, line: 2 });
612
+ assert.ok(dynamics.getTicks().equals(duration.clone().multiply(VF.VexFlow.RESOLUTION, 1)));
613
+ assert.ok(score.make.crescendo({ duration: 'q' }).setDecrescendo(true) instanceof VF.Crescendo);
614
+ assert.throws(() => score.make.textDynamics({ text: 'bad' }), /dynamics glyph/);
615
+ });
616
+ test('tab helpers preserve native options and validate span heads and grace ownership', () => {
617
+ const score = create();
618
+ const options = {
619
+ positions: [
620
+ { str: 7, fret: 'X' },
621
+ { str: 2, fret: 12 },
622
+ ],
623
+ duration: 'q',
624
+ stemDirection: -1,
625
+ };
626
+ const from = score.make.tabNote(options, true);
627
+ const to = score.make.tabNote(Object.assign(Object.assign({}, options), { positions: [
628
+ { str: 7, fret: 5 },
629
+ { str: 2, fret: 14 },
630
+ ] }));
631
+ assert.deepEqual(from.getPositions(), options.positions);
632
+ assert.equal(from.renderOptions.drawStem, true);
633
+ assert.equal(from.getStemDirection(), -1);
634
+ const bend = score.make.bend([{ type: VF.Bend.UP, text: '1/2', width: 25 }]);
635
+ score.attach(from, bend, 1);
636
+ assert.equal(bend.getIndex(), 1);
637
+ const tie = score.make.tabTie({ firstNote: from, lastNote: to, firstIndexes: [1], lastIndexes: [1] }, 'P');
638
+ assert.ok(tie instanceof VF.TabTie);
639
+ assert.ok(score.make.tabSlide({ firstNote: from, lastNote: to }, -1) instanceof VF.TabSlide);
640
+ assert.ok(score.make.tabSlide({ firstNote: from }, 1) instanceof VF.TabSlide);
641
+ const grace = score.make.graceTabNote({ positions: [{ str: 1, fret: 2 }], duration: '16' });
642
+ const group = score.make.graceNoteGroup({ notes: [grace], slur: true });
643
+ score.attach(to, group);
644
+ assert.equal(VF.Factory.getGroup(grace), group);
645
+ assert.throws(() => score.voice([grace], { mode: 'soft' }), /group/i);
646
+ const count = queued(score);
647
+ assert.throws(() => score.make.tabNote({ positions: [{ str: 0, fret: 2 }], duration: 'q' }), /position/i);
648
+ assert.throws(() => score.make.tabSlide({ firstNote: from }), /direction/i);
649
+ assert.throws(() => score.make.tabTie({ firstNote: from, firstIndexes: [2] }), /index/i);
650
+ assert.throws(() => score.make.tabTie({ firstNote: create().make.tabNote(options) }), /Factory/i);
651
+ assert.throws(() => score.make.bend([{ type: 5, text: 'x' }]), /direction/i);
652
+ assert.equal(queued(score), count);
653
+ });
654
+ test('staff helpers attach once and preserve native options without standalone drawing', () => {
655
+ const score = create();
656
+ const stave = score.make.stave({ x: 10, y: 20, width: 400 });
657
+ const count = queued(score);
658
+ const modifiers = [
659
+ score.make.clef('bass', 'small', '8vb'),
660
+ score.make.keySignature('D', 'C'),
661
+ score.make.timeSignature('7/8', 0),
662
+ score.make.barline(VF.Barline.type.DOUBLE),
663
+ score.make.repetition(VF.Repetition.type.DC, 0, 0),
664
+ score.make.volta(VF.Volta.type.BEGIN, '1.', 0, 0),
665
+ score.make.section('A', 0, 0, false),
666
+ score.make.tempo({ bpm: 100, duration: 'q', dots: 1 }, 0, 0),
667
+ score.make.staveText('text', VF.StaveModifier.Position.ABOVE, { shiftX: 0, shiftY: 0 }),
668
+ ];
669
+ for (const mark of modifiers) {
670
+ score.attachToStave(stave, mark);
671
+ score.attachToStave(stave, mark);
672
+ assert.equal(mark.getStave(), stave);
673
+ assert.equal(stave.getModifiers().filter((m) => m === mark).length, 1);
674
+ assert.equal(VF.Factory.getOwner(mark), score.factory);
675
+ assert.equal(score.getElement(mark.getAttribute('id')), mark);
676
+ }
677
+ assert.equal(queued(score), count);
678
+ const other = score.make.tabStave();
679
+ assert.throws(() => score.attachToStave(other, modifiers[0]), /already attached/i);
680
+ assert.throws(() => score.attachToStave(stave, create().make.clef('treble')), /Factory/i);
681
+ assert.throws(() => score.attachToStave(stave, score.make.clef('treble'), 99), /position/i);
682
+ assert.ok(score.make.connector({ topStave: stave, bottomStave: other, type: 'single' }) instanceof VF.StaveConnector);
683
+ assert.throws(() => score.make.multiMeasureRest({ numberOfMeasures: 0 }), /positive/i);
684
+ assert.ok(score.make.multiMeasureRest({ numberOfMeasures: 3 }).setStave(stave) instanceof VF.MultiMeasureRest);
685
+ const inline = [
686
+ score.make.barNote(),
687
+ score.make.clefNote({ options: undefined }),
688
+ score.make.keySigNote({ key: 'G' }),
689
+ score.make.timeSigNote({ time: '3/4' }),
690
+ ];
691
+ assert.ok(inline.every((note) => note.shouldIgnoreTicks()));
692
+ assert.equal(score
693
+ .voice([...inline, ...score.notes('C4/w')])
694
+ .getTicksUsed()
695
+ .value(), VF.VexFlow.RESOLUTION);
696
+ assert.ok(score.make.glyphNote('\uE047', { duration: 'q' }) instanceof VF.GlyphNote);
697
+ assert.ok(score.make.repeatNote('2', { duration: 'w' }) instanceof VF.RepeatNote);
698
+ });
699
+ test('composition scopes defaults, validates pickups and rational voices, and resolves forward spans', () => {
700
+ const score = create();
701
+ const defaults = score.defaults;
702
+ const note = score.withDefaults({ clef: 'bass', stem: 'down' }, (builder) => builder.notes('C3/q')[0]);
703
+ assert.equal(note.getStemDirection(), -1);
704
+ assert.equal(score.defaults, defaults);
705
+ assert.throws(() => score.withDefaults({ clef: 'bass' }, () => {
706
+ throw Error('stop');
707
+ }), /stop/);
708
+ assert.equal(score.defaults, defaults);
709
+ const result = score.compose({
710
+ staves: [
711
+ {
712
+ id: 'right',
713
+ measures: [
714
+ { span: '1/4', voices: [{ notes: 'C5/q[id="pickup"]' }] },
715
+ {
716
+ time: '2/4',
717
+ voices: [
718
+ {
719
+ notes: 'C5/8[id="start"], D5, E5, F5, G5, A5[id="end"]',
720
+ tuplets: [
721
+ { start: 0, count: 3 },
722
+ { start: 3, count: 3 },
723
+ ],
724
+ autoBeam: true,
725
+ stem: 'up',
726
+ },
727
+ { notes: 'G4/h', stem: 'down' },
728
+ ],
729
+ },
730
+ ],
731
+ },
732
+ {
733
+ id: 'left',
734
+ clef: 'bass',
735
+ measures: [
736
+ { span: '1/4', voices: [{ notes: 'C3/q' }] },
737
+ { time: '2/4', voices: [{ notes: 'C3/h' }] },
738
+ ],
739
+ },
740
+ ],
741
+ spans: [{ kind: 'curve', from: 'start', to: 'end' }],
742
+ });
743
+ assert.equal(result.systems.length, 2);
744
+ assert.equal(result.voices[1][0].length, 2);
745
+ assert.ok(result.voices.flat(2).every((voice) => voice.isComplete()));
746
+ assert.ok(result.voices[1][0][0].getTicksUsed().equals(new VF.Fraction(VF.VexFlow.RESOLUTION, 2)));
747
+ assert.equal(result.getNote('start'), result.notes[1][0][0][0]);
748
+ assert.ok(result.spans[0] instanceof VF.Curve);
749
+ assert.equal(score.defaults, defaults);
750
+ });
751
+ test('composition failures roll back IDs and queues and enforce shared staff state', () => {
752
+ const score = create();
753
+ const original = score.notes('A4/q[id="keep"]')[0];
754
+ const count = queued(score);
755
+ const specs = [
756
+ { staves: [{ id: 'a', measures: [{ voices: [{ notes: 'C4/q[id="new"]' }] }] }] },
757
+ {
758
+ staves: [{ id: 'a', measures: [{ voices: [{ notes: 'C4/w[id="new"]' }] }] }],
759
+ spans: [{ kind: 'tie', from: 'new', to: 'missing' }],
760
+ },
761
+ {
762
+ staves: [
763
+ { id: 'a', measures: [{ voices: [{ notes: 'C4/w' }] }] },
764
+ { id: 'b', measures: [] },
765
+ ],
766
+ },
767
+ {
768
+ staves: [
769
+ { id: 'a', measures: [{ voices: [{ notes: 'C4/w' }] }] },
770
+ { id: 'b', measures: [{ time: '3/4', voices: [{ notes: 'C3/h.' }] }] },
771
+ ],
772
+ },
773
+ {
774
+ staves: [
775
+ { id: 'a', measures: [{ voices: [{ notes: ['C4/h', { change: { key: 'G' } }, 'C4/h'] }, { notes: 'C4/w' }] }] },
776
+ ],
777
+ },
778
+ {
779
+ staves: [
780
+ {
781
+ id: 'a',
782
+ measures: [{ voices: [{ notes: [{ note: { keys: ['c/4'], duration: 'w' }, stave: 'missing' }] }] }],
783
+ },
784
+ ],
785
+ },
786
+ ];
787
+ for (const spec of specs) {
788
+ assert.throws(() => score.compose(spec));
789
+ assert.equal(queued(score), count);
790
+ assert.equal(score.getElement('new'), undefined);
791
+ assert.equal(score.getNote('keep'), original);
792
+ assert.equal(score.factory.sheets.length, 0);
793
+ }
794
+ const native = score.make.note({ keys: ['c/4'], duration: 'w' });
795
+ assert.throws(() => score.compose({
796
+ staves: [{ id: 'a', measures: [{ voices: [{ notes: [native] }] }] }],
797
+ spans: [{ kind: 'tie', from: 'missing' }],
798
+ }));
799
+ assert.throws(() => native.getVoice(), /No voice/i);
800
+ assert.equal(native.getStave(), undefined);
801
+ const result = score.compose({ staves: [{ id: 'a', measures: [{ voices: [{ notes: [native] }] }] }] });
802
+ assert.equal(result.notes[0][0][0][0], native);
803
+ });
804
+ test('key-aware composition preserves literal pitches and explicit marks across rational onsets and key changes', () => {
805
+ const marks = (note) => note
806
+ .getModifiers()
807
+ .filter((mark) => mark instanceof VF.Accidental)
808
+ .map((mark) => mark.type);
809
+ const score = create();
810
+ const result = score.compose({
811
+ accidentals: 'key-aware',
812
+ staves: [
813
+ {
814
+ id: 'a',
815
+ key: 'G',
816
+ measures: [
817
+ { voices: [{ notes: 'F#4/q, F#4, F4, F4' }] },
818
+ { voices: [{ notes: 'F#4/q, F4, F#4, F4' }, { notes: 'F4/q, F#4, F4, F#4' }] },
819
+ { voices: [{ notes: ['F#4/h', { change: { key: 'C' } }, 'F#4/q, F#4'] }] },
820
+ ],
821
+ },
822
+ ],
823
+ });
824
+ assert.deepEqual(result.notes[0][0][0].map(marks), [[], [], ['n'], []]);
825
+ assert.equal(result.notes[0][0][0][0].getKeys()[0], 'F#/4');
826
+ assert.deepEqual(result.notes[1][0][0].map(marks), [['#'], ['n'], ['#'], ['n']]);
827
+ assert.deepEqual(result.notes[1][0][1].map(marks), [['n'], ['#'], ['n'], ['#']]);
828
+ assert.deepEqual(result.notes[2][0][0].filter((n) => !n.shouldIgnoreTicks()).map(marks), [[], ['#'], []]);
829
+ const caution = create({
830
+ commitHooks: [
831
+ (options, note) => {
832
+ var _a;
833
+ if (options.id === 'caution')
834
+ note.getModifiers()[0].setAsCautionary();
835
+ note.setAttribute('id', (_a = options.id) !== null && _a !== void 0 ? _a : note.getAttribute('id'));
836
+ },
837
+ ],
838
+ });
839
+ const preserved = caution.compose({
840
+ accidentals: 'key-aware',
841
+ staves: [{ id: 'a', key: 'G', measures: [{ voices: [{ notes: 'F#4/q[id="caution"], F++4, F4, F4' }] }] }],
842
+ });
843
+ const notes = preserved.notes[0][0][0];
844
+ assert.equal(notes[0].getModifiers()[0].isCautionary(), true);
845
+ assert.deepEqual(notes.map(marks), [['#'], ['++'], ['n'], []]);
846
+ const rational = create().compose({
847
+ accidentals: 'key-aware',
848
+ staves: [
849
+ {
850
+ id: 'a',
851
+ measures: [
852
+ {
853
+ time: '2/4',
854
+ voices: [
855
+ {
856
+ notes: 'F#4/8, F4, F#4, F4, F#4, F4',
857
+ tuplets: [
858
+ { start: 0, count: 3 },
859
+ { start: 3, count: 3 },
860
+ ],
861
+ },
862
+ { notes: 'C4/q, F4' },
863
+ ],
864
+ },
865
+ ],
866
+ },
867
+ ],
868
+ });
869
+ assert.deepEqual(marks(rational.notes[0][0][1][1]), ['n']);
870
+ });
871
+ test('composition spans and signature repetition require explicit layout policies', () => {
872
+ const spec = {
873
+ staves: [
874
+ { id: 'a', measures: [{ voices: [{ notes: 'C4/w[id="first"]' }] }, { voices: [{ notes: 'C4/w[id="last"]' }] }] },
875
+ ],
876
+ spans: [{ kind: 'tie', from: 'first', to: 'last' }],
877
+ };
878
+ assert.throws(() => create().compose(spec), /manual segmentation/i);
879
+ const manual = create().compose(Object.assign(Object.assign({}, spec), { crossMeasureSpans: 'manual', signatures: 'every-measure' }));
880
+ assert.equal(manual.diagnostics.length, 1);
881
+ assert.equal(manual.diagnostics[0].code, 'ManualSpan');
882
+ assert.ok(manual.staves.every(([stave]) => stave.getModifiers().some((mark) => mark instanceof VF.Clef)));
883
+ });
884
+ test('composition keeps cross-staff placement and applies accidentals on the target stave', () => {
885
+ const score = create();
886
+ const result = score.compose({
887
+ accidentals: 'key-aware',
888
+ staves: [
889
+ {
890
+ id: 'upper',
891
+ measures: [
892
+ {
893
+ voices: [
894
+ { notes: [{ note: { keys: ['f/3'], duration: 'w', clef: 'bass' }, id: 'cross', stave: 'lower' }] },
895
+ ],
896
+ },
897
+ ],
898
+ },
899
+ { id: 'lower', key: 'G', clef: 'bass', measures: [{ voices: [{ notes: 'G2/w' }] }] },
900
+ ],
901
+ });
902
+ const note = result.getNote('cross');
903
+ assert.equal(note.getStave(), result.staves[0][1]);
904
+ assert.deepEqual(note
905
+ .getModifiers()
906
+ .filter((mark) => mark instanceof VF.Accidental)
907
+ .map((mark) => mark.type), ['n']);
908
+ result.sheet.format();
909
+ result.sheet.setWidth(220).format();
910
+ assert.equal(note.getStave(), result.staves[0][1]);
911
+ assert.ok(Number.isFinite(note.getYs()[0]));
912
+ });
913
+ test('composition carries clef state and cancels inline key signatures on the correct staff lines', () => {
914
+ const score = create();
915
+ const result = score.compose({
916
+ staves: [
917
+ {
918
+ id: 'bass',
919
+ clef: 'bass',
920
+ key: 'G',
921
+ measures: [
922
+ { voices: [{ notes: 'G3/w' }] },
923
+ { key: 'D', voices: [{ notes: ['D3/h', { change: { clef: 'treble', key: 'C' } }, 'C5/h'] }] },
924
+ ],
925
+ },
926
+ ],
927
+ });
928
+ assert.equal(result.staves[0][0].getClef(), 'bass');
929
+ assert.equal(result.staves[1][0].getClef(), 'bass');
930
+ const inline = result.notes[1][0][0].find((note) => note instanceof VF.KeySigNote);
931
+ inline.preFormat();
932
+ assert.equal(inline.keySignature.accList.length, 2, 'D major is cancelled with two naturals');
933
+ const native = new VF.KeySignature('C', 'D').setStave(new VF.Stave(0, 0, 200).addClef('treble'));
934
+ native.format();
935
+ assert.deepEqual(inline.keySignature.accList, native.accList, 'inline cancellation follows the new clef');
936
+ const attached = score.make.stave();
937
+ score.attachToStave(attached, score.make.clef('alto'));
938
+ assert.equal(attached.getClef(), 'alto');
939
+ });
940
+ test('non-pitched timed notes accept native modifiers at their single attachment index', () => {
941
+ const score = create();
942
+ const note = score.make.glyphNote('\uE047', { duration: 'w' });
943
+ const label = score.make.annotation({ text: 'sim.' });
944
+ score.attach(note, label);
945
+ assert.equal(label.getNote(), note);
946
+ assert.equal(label.getIndex(), 0);
947
+ assert.throws(() => score.attach(note, score.make.annotation({ text: 'bad' }), 1), /index/i);
948
+ });
949
+ test('typed grace notes retain explicit stem direction over automatic defaults', () => {
950
+ const grace = create().make.graceNote({ keys: ['c/4'], duration: '16', stemDirection: -1 });
951
+ assert.equal(grace.getStemDirection(), -1);
952
+ assert.equal(grace.isAutoStem(), false);
953
+ });