@coderline/alphatab 1.7.0-alpha.1527 → 1.7.0-alpha.1536

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.
@@ -1,2723 +1,3 @@
1
- /*!
2
- * alphaTab v1.7.0-alpha.1527 (develop, build 1527)
3
- *
4
- * Copyright © 2025, Daniel Kuschny and Contributors, All rights reserved.
5
- *
6
- * This Source Code Form is subject to the terms of the Mozilla Public
7
- * License, v. 2.0. If a copy of the MPL was not distributed with this
8
- * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
- *
10
- * Integrated Libraries:
11
- *
12
- * Library: TinySoundFont
13
- * License: MIT
14
- * Copyright: Copyright (C) 2017, 2018 Bernhard Schelling
15
- * URL: https://github.com/schellingb/TinySoundFont
16
- * Purpose: SoundFont loading and Audio Synthesis
17
- *
18
- * Library: SFZero
19
- * License: MIT
20
- * Copyright: Copyright (C) 2012 Steve Folta ()
21
- * URL: https://github.com/stevefolta/SFZero
22
- * Purpose: TinySoundFont is based on SFZEro
23
- *
24
- * Library: Haxe Standard Library
25
- * License: MIT
26
- * Copyright: Copyright (C)2005-2025 Haxe Foundation
27
- * URL: https://github.com/HaxeFoundation/haxe/tree/development/std
28
- * Purpose: XML Parser & Zip Inflate Algorithm
29
- *
30
- * Library: SharpZipLib
31
- * License: MIT
32
- * Copyright: Copyright © 2000-2018 SharpZipLib Contributors
33
- * URL: https://github.com/icsharpcode/SharpZipLib
34
- * Purpose: Zip Deflate Algorithm for writing compressed Zips
35
- *
36
- * Library: NVorbis
37
- * License: MIT
38
- * Copyright: Copyright (c) 2020 Andrew Ward
39
- * URL: https://github.com/NVorbis/NVorbis
40
- * Purpose: Vorbis Stream Decoding
41
- *
42
- * Library: libvorbis
43
- * License: BSD-3-Clause
44
- * Copyright: Copyright (c) 2002-2020 Xiph.org Foundation
45
- * URL: https://github.com/xiph/vorbis
46
- * Purpose: NVorbis adopted some code from libvorbis.
47
- *
48
- * @preserve
49
- * @license
50
- */
51
-
52
- 'use strict';
53
-
54
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
55
-
56
- const path = require('node:path');
57
- const fs = require('node:fs');
58
- const node_crypto = require('node:crypto');
59
- const vite = require('vite');
60
- const url = require('node:url');
61
-
62
- function _interopNamespaceDefault(e) {
63
- const n = Object.create(null, { [Symbol.toStringTag]: { value: 'Module' } });
64
- if (e) {
65
- for (const k in e) {
66
- if (k !== 'default') {
67
- const d = Object.getOwnPropertyDescriptor(e, k);
68
- Object.defineProperty(n, k, d.get ? d : {
69
- enumerable: true,
70
- get: () => e[k]
71
- });
72
- }
73
- }
74
- }
75
- n.default = e;
76
- return Object.freeze(n);
77
- }
78
-
79
- const path__namespace = /*#__PURE__*/_interopNamespaceDefault(path);
80
- const fs__namespace = /*#__PURE__*/_interopNamespaceDefault(fs);
81
- const url__namespace = /*#__PURE__*/_interopNamespaceDefault(url);
82
-
83
- var sourcemapCodec_umd$1 = {exports: {}};
84
-
85
- var sourcemapCodec_umd = sourcemapCodec_umd$1.exports;
86
-
87
- var hasRequiredSourcemapCodec_umd;
88
-
89
- function requireSourcemapCodec_umd () {
90
- if (hasRequiredSourcemapCodec_umd) return sourcemapCodec_umd$1.exports;
91
- hasRequiredSourcemapCodec_umd = 1;
92
- (function (module, exports) {
93
- (function (global, factory) {
94
- factory(exports) ;
95
- })(sourcemapCodec_umd, (function (exports) {
96
- const comma = ','.charCodeAt(0);
97
- const semicolon = ';'.charCodeAt(0);
98
- const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
99
- const intToChar = new Uint8Array(64); // 64 possible chars.
100
- const charToInt = new Uint8Array(128); // z is 122 in ASCII
101
- for (let i = 0; i < chars.length; i++) {
102
- const c = chars.charCodeAt(i);
103
- intToChar[i] = c;
104
- charToInt[c] = i;
105
- }
106
- function decodeInteger(reader, relative) {
107
- let value = 0;
108
- let shift = 0;
109
- let integer = 0;
110
- do {
111
- const c = reader.next();
112
- integer = charToInt[c];
113
- value |= (integer & 31) << shift;
114
- shift += 5;
115
- } while (integer & 32);
116
- const shouldNegate = value & 1;
117
- value >>>= 1;
118
- if (shouldNegate) {
119
- value = -2147483648 | -value;
120
- }
121
- return relative + value;
122
- }
123
- function encodeInteger(builder, num, relative) {
124
- let delta = num - relative;
125
- delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
126
- do {
127
- let clamped = delta & 0b011111;
128
- delta >>>= 5;
129
- if (delta > 0)
130
- clamped |= 0b100000;
131
- builder.write(intToChar[clamped]);
132
- } while (delta > 0);
133
- return num;
134
- }
135
- function hasMoreVlq(reader, max) {
136
- if (reader.pos >= max)
137
- return false;
138
- return reader.peek() !== comma;
139
- }
140
-
141
- const bufLength = 1024 * 16;
142
- // Provide a fallback for older environments.
143
- const td = typeof TextDecoder !== 'undefined'
144
- ? /* #__PURE__ */ new TextDecoder()
145
- : typeof Buffer !== 'undefined'
146
- ? {
147
- decode(buf) {
148
- const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
149
- return out.toString();
150
- },
151
- }
152
- : {
153
- decode(buf) {
154
- let out = '';
155
- for (let i = 0; i < buf.length; i++) {
156
- out += String.fromCharCode(buf[i]);
157
- }
158
- return out;
159
- },
160
- };
161
- class StringWriter {
162
- constructor() {
163
- this.pos = 0;
164
- this.out = '';
165
- this.buffer = new Uint8Array(bufLength);
166
- }
167
- write(v) {
168
- const { buffer } = this;
169
- buffer[this.pos++] = v;
170
- if (this.pos === bufLength) {
171
- this.out += td.decode(buffer);
172
- this.pos = 0;
173
- }
174
- }
175
- flush() {
176
- const { buffer, out, pos } = this;
177
- return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
178
- }
179
- }
180
- class StringReader {
181
- constructor(buffer) {
182
- this.pos = 0;
183
- this.buffer = buffer;
184
- }
185
- next() {
186
- return this.buffer.charCodeAt(this.pos++);
187
- }
188
- peek() {
189
- return this.buffer.charCodeAt(this.pos);
190
- }
191
- indexOf(char) {
192
- const { buffer, pos } = this;
193
- const idx = buffer.indexOf(char, pos);
194
- return idx === -1 ? buffer.length : idx;
195
- }
196
- }
197
-
198
- const EMPTY = [];
199
- function decodeOriginalScopes(input) {
200
- const { length } = input;
201
- const reader = new StringReader(input);
202
- const scopes = [];
203
- const stack = [];
204
- let line = 0;
205
- for (; reader.pos < length; reader.pos++) {
206
- line = decodeInteger(reader, line);
207
- const column = decodeInteger(reader, 0);
208
- if (!hasMoreVlq(reader, length)) {
209
- const last = stack.pop();
210
- last[2] = line;
211
- last[3] = column;
212
- continue;
213
- }
214
- const kind = decodeInteger(reader, 0);
215
- const fields = decodeInteger(reader, 0);
216
- const hasName = fields & 0b0001;
217
- const scope = (hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]);
218
- let vars = EMPTY;
219
- if (hasMoreVlq(reader, length)) {
220
- vars = [];
221
- do {
222
- const varsIndex = decodeInteger(reader, 0);
223
- vars.push(varsIndex);
224
- } while (hasMoreVlq(reader, length));
225
- }
226
- scope.vars = vars;
227
- scopes.push(scope);
228
- stack.push(scope);
229
- }
230
- return scopes;
231
- }
232
- function encodeOriginalScopes(scopes) {
233
- const writer = new StringWriter();
234
- for (let i = 0; i < scopes.length;) {
235
- i = _encodeOriginalScopes(scopes, i, writer, [0]);
236
- }
237
- return writer.flush();
238
- }
239
- function _encodeOriginalScopes(scopes, index, writer, state) {
240
- const scope = scopes[index];
241
- const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
242
- if (index > 0)
243
- writer.write(comma);
244
- state[0] = encodeInteger(writer, startLine, state[0]);
245
- encodeInteger(writer, startColumn, 0);
246
- encodeInteger(writer, kind, 0);
247
- const fields = scope.length === 6 ? 0b0001 : 0;
248
- encodeInteger(writer, fields, 0);
249
- if (scope.length === 6)
250
- encodeInteger(writer, scope[5], 0);
251
- for (const v of vars) {
252
- encodeInteger(writer, v, 0);
253
- }
254
- for (index++; index < scopes.length;) {
255
- const next = scopes[index];
256
- const { 0: l, 1: c } = next;
257
- if (l > endLine || (l === endLine && c >= endColumn)) {
258
- break;
259
- }
260
- index = _encodeOriginalScopes(scopes, index, writer, state);
261
- }
262
- writer.write(comma);
263
- state[0] = encodeInteger(writer, endLine, state[0]);
264
- encodeInteger(writer, endColumn, 0);
265
- return index;
266
- }
267
- function decodeGeneratedRanges(input) {
268
- const { length } = input;
269
- const reader = new StringReader(input);
270
- const ranges = [];
271
- const stack = [];
272
- let genLine = 0;
273
- let definitionSourcesIndex = 0;
274
- let definitionScopeIndex = 0;
275
- let callsiteSourcesIndex = 0;
276
- let callsiteLine = 0;
277
- let callsiteColumn = 0;
278
- let bindingLine = 0;
279
- let bindingColumn = 0;
280
- do {
281
- const semi = reader.indexOf(';');
282
- let genColumn = 0;
283
- for (; reader.pos < semi; reader.pos++) {
284
- genColumn = decodeInteger(reader, genColumn);
285
- if (!hasMoreVlq(reader, semi)) {
286
- const last = stack.pop();
287
- last[2] = genLine;
288
- last[3] = genColumn;
289
- continue;
290
- }
291
- const fields = decodeInteger(reader, 0);
292
- const hasDefinition = fields & 0b0001;
293
- const hasCallsite = fields & 0b0010;
294
- const hasScope = fields & 0b0100;
295
- let callsite = null;
296
- let bindings = EMPTY;
297
- let range;
298
- if (hasDefinition) {
299
- const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
300
- definitionScopeIndex = decodeInteger(reader, definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0);
301
- definitionSourcesIndex = defSourcesIndex;
302
- range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
303
- }
304
- else {
305
- range = [genLine, genColumn, 0, 0];
306
- }
307
- range.isScope = !!hasScope;
308
- if (hasCallsite) {
309
- const prevCsi = callsiteSourcesIndex;
310
- const prevLine = callsiteLine;
311
- callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
312
- const sameSource = prevCsi === callsiteSourcesIndex;
313
- callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
314
- callsiteColumn = decodeInteger(reader, sameSource && prevLine === callsiteLine ? callsiteColumn : 0);
315
- callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
316
- }
317
- range.callsite = callsite;
318
- if (hasMoreVlq(reader, semi)) {
319
- bindings = [];
320
- do {
321
- bindingLine = genLine;
322
- bindingColumn = genColumn;
323
- const expressionsCount = decodeInteger(reader, 0);
324
- let expressionRanges;
325
- if (expressionsCount < -1) {
326
- expressionRanges = [[decodeInteger(reader, 0)]];
327
- for (let i = -1; i > expressionsCount; i--) {
328
- const prevBl = bindingLine;
329
- bindingLine = decodeInteger(reader, bindingLine);
330
- bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
331
- const expression = decodeInteger(reader, 0);
332
- expressionRanges.push([expression, bindingLine, bindingColumn]);
333
- }
334
- }
335
- else {
336
- expressionRanges = [[expressionsCount]];
337
- }
338
- bindings.push(expressionRanges);
339
- } while (hasMoreVlq(reader, semi));
340
- }
341
- range.bindings = bindings;
342
- ranges.push(range);
343
- stack.push(range);
344
- }
345
- genLine++;
346
- reader.pos = semi + 1;
347
- } while (reader.pos < length);
348
- return ranges;
349
- }
350
- function encodeGeneratedRanges(ranges) {
351
- if (ranges.length === 0)
352
- return '';
353
- const writer = new StringWriter();
354
- for (let i = 0; i < ranges.length;) {
355
- i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
356
- }
357
- return writer.flush();
358
- }
359
- function _encodeGeneratedRanges(ranges, index, writer, state) {
360
- const range = ranges[index];
361
- const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, isScope, callsite, bindings, } = range;
362
- if (state[0] < startLine) {
363
- catchupLine(writer, state[0], startLine);
364
- state[0] = startLine;
365
- state[1] = 0;
366
- }
367
- else if (index > 0) {
368
- writer.write(comma);
369
- }
370
- state[1] = encodeInteger(writer, range[1], state[1]);
371
- const fields = (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
372
- encodeInteger(writer, fields, 0);
373
- if (range.length === 6) {
374
- const { 4: sourcesIndex, 5: scopesIndex } = range;
375
- if (sourcesIndex !== state[2]) {
376
- state[3] = 0;
377
- }
378
- state[2] = encodeInteger(writer, sourcesIndex, state[2]);
379
- state[3] = encodeInteger(writer, scopesIndex, state[3]);
380
- }
381
- if (callsite) {
382
- const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
383
- if (sourcesIndex !== state[4]) {
384
- state[5] = 0;
385
- state[6] = 0;
386
- }
387
- else if (callLine !== state[5]) {
388
- state[6] = 0;
389
- }
390
- state[4] = encodeInteger(writer, sourcesIndex, state[4]);
391
- state[5] = encodeInteger(writer, callLine, state[5]);
392
- state[6] = encodeInteger(writer, callColumn, state[6]);
393
- }
394
- if (bindings) {
395
- for (const binding of bindings) {
396
- if (binding.length > 1)
397
- encodeInteger(writer, -binding.length, 0);
398
- const expression = binding[0][0];
399
- encodeInteger(writer, expression, 0);
400
- let bindingStartLine = startLine;
401
- let bindingStartColumn = startColumn;
402
- for (let i = 1; i < binding.length; i++) {
403
- const expRange = binding[i];
404
- bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
405
- bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
406
- encodeInteger(writer, expRange[0], 0);
407
- }
408
- }
409
- }
410
- for (index++; index < ranges.length;) {
411
- const next = ranges[index];
412
- const { 0: l, 1: c } = next;
413
- if (l > endLine || (l === endLine && c >= endColumn)) {
414
- break;
415
- }
416
- index = _encodeGeneratedRanges(ranges, index, writer, state);
417
- }
418
- if (state[0] < endLine) {
419
- catchupLine(writer, state[0], endLine);
420
- state[0] = endLine;
421
- state[1] = 0;
422
- }
423
- else {
424
- writer.write(comma);
425
- }
426
- state[1] = encodeInteger(writer, endColumn, state[1]);
427
- return index;
428
- }
429
- function catchupLine(writer, lastLine, line) {
430
- do {
431
- writer.write(semicolon);
432
- } while (++lastLine < line);
433
- }
434
-
435
- function decode(mappings) {
436
- const { length } = mappings;
437
- const reader = new StringReader(mappings);
438
- const decoded = [];
439
- let genColumn = 0;
440
- let sourcesIndex = 0;
441
- let sourceLine = 0;
442
- let sourceColumn = 0;
443
- let namesIndex = 0;
444
- do {
445
- const semi = reader.indexOf(';');
446
- const line = [];
447
- let sorted = true;
448
- let lastCol = 0;
449
- genColumn = 0;
450
- while (reader.pos < semi) {
451
- let seg;
452
- genColumn = decodeInteger(reader, genColumn);
453
- if (genColumn < lastCol)
454
- sorted = false;
455
- lastCol = genColumn;
456
- if (hasMoreVlq(reader, semi)) {
457
- sourcesIndex = decodeInteger(reader, sourcesIndex);
458
- sourceLine = decodeInteger(reader, sourceLine);
459
- sourceColumn = decodeInteger(reader, sourceColumn);
460
- if (hasMoreVlq(reader, semi)) {
461
- namesIndex = decodeInteger(reader, namesIndex);
462
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
463
- }
464
- else {
465
- seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
466
- }
467
- }
468
- else {
469
- seg = [genColumn];
470
- }
471
- line.push(seg);
472
- reader.pos++;
473
- }
474
- if (!sorted)
475
- sort(line);
476
- decoded.push(line);
477
- reader.pos = semi + 1;
478
- } while (reader.pos <= length);
479
- return decoded;
480
- }
481
- function sort(line) {
482
- line.sort(sortComparator);
483
- }
484
- function sortComparator(a, b) {
485
- return a[0] - b[0];
486
- }
487
- function encode(decoded) {
488
- const writer = new StringWriter();
489
- let sourcesIndex = 0;
490
- let sourceLine = 0;
491
- let sourceColumn = 0;
492
- let namesIndex = 0;
493
- for (let i = 0; i < decoded.length; i++) {
494
- const line = decoded[i];
495
- if (i > 0)
496
- writer.write(semicolon);
497
- if (line.length === 0)
498
- continue;
499
- let genColumn = 0;
500
- for (let j = 0; j < line.length; j++) {
501
- const segment = line[j];
502
- if (j > 0)
503
- writer.write(comma);
504
- genColumn = encodeInteger(writer, segment[0], genColumn);
505
- if (segment.length === 1)
506
- continue;
507
- sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
508
- sourceLine = encodeInteger(writer, segment[2], sourceLine);
509
- sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
510
- if (segment.length === 4)
511
- continue;
512
- namesIndex = encodeInteger(writer, segment[4], namesIndex);
513
- }
514
- }
515
- return writer.flush();
516
- }
517
-
518
- exports.decode = decode;
519
- exports.decodeGeneratedRanges = decodeGeneratedRanges;
520
- exports.decodeOriginalScopes = decodeOriginalScopes;
521
- exports.encode = encode;
522
- exports.encodeGeneratedRanges = encodeGeneratedRanges;
523
- exports.encodeOriginalScopes = encodeOriginalScopes;
524
-
525
- Object.defineProperty(exports, '__esModule', { value: true });
526
-
527
- }));
528
-
529
- } (sourcemapCodec_umd$1, sourcemapCodec_umd$1.exports));
530
- return sourcemapCodec_umd$1.exports;
531
- }
532
-
533
- var sourcemapCodec_umdExports = requireSourcemapCodec_umd();
534
-
535
- class BitSet {
536
- constructor(arg) {
537
- this.bits = arg instanceof BitSet ? arg.bits.slice() : [];
538
- }
539
-
540
- add(n) {
541
- this.bits[n >> 5] |= 1 << (n & 31);
542
- }
543
-
544
- has(n) {
545
- return !!(this.bits[n >> 5] & (1 << (n & 31)));
546
- }
547
- }
548
-
549
- class Chunk {
550
- constructor(start, end, content) {
551
- this.start = start;
552
- this.end = end;
553
- this.original = content;
554
-
555
- this.intro = '';
556
- this.outro = '';
557
-
558
- this.content = content;
559
- this.storeName = false;
560
- this.edited = false;
561
-
562
- {
563
- this.previous = null;
564
- this.next = null;
565
- }
566
- }
567
-
568
- appendLeft(content) {
569
- this.outro += content;
570
- }
571
-
572
- appendRight(content) {
573
- this.intro = this.intro + content;
574
- }
575
-
576
- clone() {
577
- const chunk = new Chunk(this.start, this.end, this.original);
578
-
579
- chunk.intro = this.intro;
580
- chunk.outro = this.outro;
581
- chunk.content = this.content;
582
- chunk.storeName = this.storeName;
583
- chunk.edited = this.edited;
584
-
585
- return chunk;
586
- }
587
-
588
- contains(index) {
589
- return this.start < index && index < this.end;
590
- }
591
-
592
- eachNext(fn) {
593
- let chunk = this;
594
- while (chunk) {
595
- fn(chunk);
596
- chunk = chunk.next;
597
- }
598
- }
599
-
600
- eachPrevious(fn) {
601
- let chunk = this;
602
- while (chunk) {
603
- fn(chunk);
604
- chunk = chunk.previous;
605
- }
606
- }
607
-
608
- edit(content, storeName, contentOnly) {
609
- this.content = content;
610
- if (!contentOnly) {
611
- this.intro = '';
612
- this.outro = '';
613
- }
614
- this.storeName = storeName;
615
-
616
- this.edited = true;
617
-
618
- return this;
619
- }
620
-
621
- prependLeft(content) {
622
- this.outro = content + this.outro;
623
- }
624
-
625
- prependRight(content) {
626
- this.intro = content + this.intro;
627
- }
628
-
629
- reset() {
630
- this.intro = '';
631
- this.outro = '';
632
- if (this.edited) {
633
- this.content = this.original;
634
- this.storeName = false;
635
- this.edited = false;
636
- }
637
- }
638
-
639
- split(index) {
640
- const sliceIndex = index - this.start;
641
-
642
- const originalBefore = this.original.slice(0, sliceIndex);
643
- const originalAfter = this.original.slice(sliceIndex);
644
-
645
- this.original = originalBefore;
646
-
647
- const newChunk = new Chunk(index, this.end, originalAfter);
648
- newChunk.outro = this.outro;
649
- this.outro = '';
650
-
651
- this.end = index;
652
-
653
- if (this.edited) {
654
- // after split we should save the edit content record into the correct chunk
655
- // to make sure sourcemap correct
656
- // For example:
657
- // ' test'.trim()
658
- // split -> ' ' + 'test'
659
- // ✔️ edit -> '' + 'test'
660
- // ✖️ edit -> 'test' + ''
661
- // TODO is this block necessary?...
662
- newChunk.edit('', false);
663
- this.content = '';
664
- } else {
665
- this.content = originalBefore;
666
- }
667
-
668
- newChunk.next = this.next;
669
- if (newChunk.next) newChunk.next.previous = newChunk;
670
- newChunk.previous = this;
671
- this.next = newChunk;
672
-
673
- return newChunk;
674
- }
675
-
676
- toString() {
677
- return this.intro + this.content + this.outro;
678
- }
679
-
680
- trimEnd(rx) {
681
- this.outro = this.outro.replace(rx, '');
682
- if (this.outro.length) return true;
683
-
684
- const trimmed = this.content.replace(rx, '');
685
-
686
- if (trimmed.length) {
687
- if (trimmed !== this.content) {
688
- this.split(this.start + trimmed.length).edit('', undefined, true);
689
- if (this.edited) {
690
- // save the change, if it has been edited
691
- this.edit(trimmed, this.storeName, true);
692
- }
693
- }
694
- return true;
695
- } else {
696
- this.edit('', undefined, true);
697
-
698
- this.intro = this.intro.replace(rx, '');
699
- if (this.intro.length) return true;
700
- }
701
- }
702
-
703
- trimStart(rx) {
704
- this.intro = this.intro.replace(rx, '');
705
- if (this.intro.length) return true;
706
-
707
- const trimmed = this.content.replace(rx, '');
708
-
709
- if (trimmed.length) {
710
- if (trimmed !== this.content) {
711
- const newChunk = this.split(this.end - trimmed.length);
712
- if (this.edited) {
713
- // save the change, if it has been edited
714
- newChunk.edit(trimmed, this.storeName, true);
715
- }
716
- this.edit('', undefined, true);
717
- }
718
- return true;
719
- } else {
720
- this.edit('', undefined, true);
721
-
722
- this.outro = this.outro.replace(rx, '');
723
- if (this.outro.length) return true;
724
- }
725
- }
726
- }
727
-
728
- function getBtoa() {
729
- if (typeof globalThis !== 'undefined' && typeof globalThis.btoa === 'function') {
730
- return (str) => globalThis.btoa(unescape(encodeURIComponent(str)));
731
- } else if (typeof Buffer === 'function') {
732
- return (str) => Buffer.from(str, 'utf-8').toString('base64');
733
- } else {
734
- return () => {
735
- throw new Error('Unsupported environment: `window.btoa` or `Buffer` should be supported.');
736
- };
737
- }
738
- }
739
-
740
- const btoa = /*#__PURE__*/ getBtoa();
741
-
742
- class SourceMap {
743
- constructor(properties) {
744
- this.version = 3;
745
- this.file = properties.file;
746
- this.sources = properties.sources;
747
- this.sourcesContent = properties.sourcesContent;
748
- this.names = properties.names;
749
- this.mappings = sourcemapCodec_umdExports.encode(properties.mappings);
750
- if (typeof properties.x_google_ignoreList !== 'undefined') {
751
- this.x_google_ignoreList = properties.x_google_ignoreList;
752
- }
753
- if (typeof properties.debugId !== 'undefined') {
754
- this.debugId = properties.debugId;
755
- }
756
- }
757
-
758
- toString() {
759
- return JSON.stringify(this);
760
- }
761
-
762
- toUrl() {
763
- return 'data:application/json;charset=utf-8;base64,' + btoa(this.toString());
764
- }
765
- }
766
-
767
- function guessIndent(code) {
768
- const lines = code.split('\n');
769
-
770
- const tabbed = lines.filter((line) => /^\t+/.test(line));
771
- const spaced = lines.filter((line) => /^ {2,}/.test(line));
772
-
773
- if (tabbed.length === 0 && spaced.length === 0) {
774
- return null;
775
- }
776
-
777
- // More lines tabbed than spaced? Assume tabs, and
778
- // default to tabs in the case of a tie (or nothing
779
- // to go on)
780
- if (tabbed.length >= spaced.length) {
781
- return '\t';
782
- }
783
-
784
- // Otherwise, we need to guess the multiple
785
- const min = spaced.reduce((previous, current) => {
786
- const numSpaces = /^ +/.exec(current)[0].length;
787
- return Math.min(numSpaces, previous);
788
- }, Infinity);
789
-
790
- return new Array(min + 1).join(' ');
791
- }
792
-
793
- function getRelativePath(from, to) {
794
- const fromParts = from.split(/[/\\]/);
795
- const toParts = to.split(/[/\\]/);
796
-
797
- fromParts.pop(); // get dirname
798
-
799
- while (fromParts[0] === toParts[0]) {
800
- fromParts.shift();
801
- toParts.shift();
802
- }
803
-
804
- if (fromParts.length) {
805
- let i = fromParts.length;
806
- while (i--) fromParts[i] = '..';
807
- }
808
-
809
- return fromParts.concat(toParts).join('/');
810
- }
811
-
812
- const toString = Object.prototype.toString;
813
-
814
- function isObject(thing) {
815
- return toString.call(thing) === '[object Object]';
816
- }
817
-
818
- function getLocator(source) {
819
- const originalLines = source.split('\n');
820
- const lineOffsets = [];
821
-
822
- for (let i = 0, pos = 0; i < originalLines.length; i++) {
823
- lineOffsets.push(pos);
824
- pos += originalLines[i].length + 1;
825
- }
826
-
827
- return function locate(index) {
828
- let i = 0;
829
- let j = lineOffsets.length;
830
- while (i < j) {
831
- const m = (i + j) >> 1;
832
- if (index < lineOffsets[m]) {
833
- j = m;
834
- } else {
835
- i = m + 1;
836
- }
837
- }
838
- const line = i - 1;
839
- const column = index - lineOffsets[line];
840
- return { line, column };
841
- };
842
- }
843
-
844
- const wordRegex = /\w/;
845
-
846
- class Mappings {
847
- constructor(hires) {
848
- this.hires = hires;
849
- this.generatedCodeLine = 0;
850
- this.generatedCodeColumn = 0;
851
- this.raw = [];
852
- this.rawSegments = this.raw[this.generatedCodeLine] = [];
853
- this.pending = null;
854
- }
855
-
856
- addEdit(sourceIndex, content, loc, nameIndex) {
857
- if (content.length) {
858
- const contentLengthMinusOne = content.length - 1;
859
- let contentLineEnd = content.indexOf('\n', 0);
860
- let previousContentLineEnd = -1;
861
- // Loop through each line in the content and add a segment, but stop if the last line is empty,
862
- // else code afterwards would fill one line too many
863
- while (contentLineEnd >= 0 && contentLengthMinusOne > contentLineEnd) {
864
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
865
- if (nameIndex >= 0) {
866
- segment.push(nameIndex);
867
- }
868
- this.rawSegments.push(segment);
869
-
870
- this.generatedCodeLine += 1;
871
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
872
- this.generatedCodeColumn = 0;
873
-
874
- previousContentLineEnd = contentLineEnd;
875
- contentLineEnd = content.indexOf('\n', contentLineEnd + 1);
876
- }
877
-
878
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
879
- if (nameIndex >= 0) {
880
- segment.push(nameIndex);
881
- }
882
- this.rawSegments.push(segment);
883
-
884
- this.advance(content.slice(previousContentLineEnd + 1));
885
- } else if (this.pending) {
886
- this.rawSegments.push(this.pending);
887
- this.advance(content);
888
- }
889
-
890
- this.pending = null;
891
- }
892
-
893
- addUneditedChunk(sourceIndex, chunk, original, loc, sourcemapLocations) {
894
- let originalCharIndex = chunk.start;
895
- let first = true;
896
- // when iterating each char, check if it's in a word boundary
897
- let charInHiresBoundary = false;
898
-
899
- while (originalCharIndex < chunk.end) {
900
- if (original[originalCharIndex] === '\n') {
901
- loc.line += 1;
902
- loc.column = 0;
903
- this.generatedCodeLine += 1;
904
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
905
- this.generatedCodeColumn = 0;
906
- first = true;
907
- charInHiresBoundary = false;
908
- } else {
909
- if (this.hires || first || sourcemapLocations.has(originalCharIndex)) {
910
- const segment = [this.generatedCodeColumn, sourceIndex, loc.line, loc.column];
911
-
912
- if (this.hires === 'boundary') {
913
- // in hires "boundary", group segments per word boundary than per char
914
- if (wordRegex.test(original[originalCharIndex])) {
915
- // for first char in the boundary found, start the boundary by pushing a segment
916
- if (!charInHiresBoundary) {
917
- this.rawSegments.push(segment);
918
- charInHiresBoundary = true;
919
- }
920
- } else {
921
- // for non-word char, end the boundary by pushing a segment
922
- this.rawSegments.push(segment);
923
- charInHiresBoundary = false;
924
- }
925
- } else {
926
- this.rawSegments.push(segment);
927
- }
928
- }
929
-
930
- loc.column += 1;
931
- this.generatedCodeColumn += 1;
932
- first = false;
933
- }
934
-
935
- originalCharIndex += 1;
936
- }
937
-
938
- this.pending = null;
939
- }
940
-
941
- advance(str) {
942
- if (!str) return;
943
-
944
- const lines = str.split('\n');
945
-
946
- if (lines.length > 1) {
947
- for (let i = 0; i < lines.length - 1; i++) {
948
- this.generatedCodeLine++;
949
- this.raw[this.generatedCodeLine] = this.rawSegments = [];
950
- }
951
- this.generatedCodeColumn = 0;
952
- }
953
-
954
- this.generatedCodeColumn += lines[lines.length - 1].length;
955
- }
956
- }
957
-
958
- const n = '\n';
959
-
960
- const warned = {
961
- insertLeft: false,
962
- insertRight: false,
963
- storeName: false,
964
- };
965
-
966
- class MagicString {
967
- constructor(string, options = {}) {
968
- const chunk = new Chunk(0, string.length, string);
969
-
970
- Object.defineProperties(this, {
971
- original: { writable: true, value: string },
972
- outro: { writable: true, value: '' },
973
- intro: { writable: true, value: '' },
974
- firstChunk: { writable: true, value: chunk },
975
- lastChunk: { writable: true, value: chunk },
976
- lastSearchedChunk: { writable: true, value: chunk },
977
- byStart: { writable: true, value: {} },
978
- byEnd: { writable: true, value: {} },
979
- filename: { writable: true, value: options.filename },
980
- indentExclusionRanges: { writable: true, value: options.indentExclusionRanges },
981
- sourcemapLocations: { writable: true, value: new BitSet() },
982
- storedNames: { writable: true, value: {} },
983
- indentStr: { writable: true, value: undefined },
984
- ignoreList: { writable: true, value: options.ignoreList },
985
- offset: { writable: true, value: options.offset || 0 },
986
- });
987
-
988
- this.byStart[0] = chunk;
989
- this.byEnd[string.length] = chunk;
990
- }
991
-
992
- addSourcemapLocation(char) {
993
- this.sourcemapLocations.add(char);
994
- }
995
-
996
- append(content) {
997
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
998
-
999
- this.outro += content;
1000
- return this;
1001
- }
1002
-
1003
- appendLeft(index, content) {
1004
- index = index + this.offset;
1005
-
1006
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1007
-
1008
- this._split(index);
1009
-
1010
- const chunk = this.byEnd[index];
1011
-
1012
- if (chunk) {
1013
- chunk.appendLeft(content);
1014
- } else {
1015
- this.intro += content;
1016
- }
1017
- return this;
1018
- }
1019
-
1020
- appendRight(index, content) {
1021
- index = index + this.offset;
1022
-
1023
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1024
-
1025
- this._split(index);
1026
-
1027
- const chunk = this.byStart[index];
1028
-
1029
- if (chunk) {
1030
- chunk.appendRight(content);
1031
- } else {
1032
- this.outro += content;
1033
- }
1034
- return this;
1035
- }
1036
-
1037
- clone() {
1038
- const cloned = new MagicString(this.original, { filename: this.filename, offset: this.offset });
1039
-
1040
- let originalChunk = this.firstChunk;
1041
- let clonedChunk = (cloned.firstChunk = cloned.lastSearchedChunk = originalChunk.clone());
1042
-
1043
- while (originalChunk) {
1044
- cloned.byStart[clonedChunk.start] = clonedChunk;
1045
- cloned.byEnd[clonedChunk.end] = clonedChunk;
1046
-
1047
- const nextOriginalChunk = originalChunk.next;
1048
- const nextClonedChunk = nextOriginalChunk && nextOriginalChunk.clone();
1049
-
1050
- if (nextClonedChunk) {
1051
- clonedChunk.next = nextClonedChunk;
1052
- nextClonedChunk.previous = clonedChunk;
1053
-
1054
- clonedChunk = nextClonedChunk;
1055
- }
1056
-
1057
- originalChunk = nextOriginalChunk;
1058
- }
1059
-
1060
- cloned.lastChunk = clonedChunk;
1061
-
1062
- if (this.indentExclusionRanges) {
1063
- cloned.indentExclusionRanges = this.indentExclusionRanges.slice();
1064
- }
1065
-
1066
- cloned.sourcemapLocations = new BitSet(this.sourcemapLocations);
1067
-
1068
- cloned.intro = this.intro;
1069
- cloned.outro = this.outro;
1070
-
1071
- return cloned;
1072
- }
1073
-
1074
- generateDecodedMap(options) {
1075
- options = options || {};
1076
-
1077
- const sourceIndex = 0;
1078
- const names = Object.keys(this.storedNames);
1079
- const mappings = new Mappings(options.hires);
1080
-
1081
- const locate = getLocator(this.original);
1082
-
1083
- if (this.intro) {
1084
- mappings.advance(this.intro);
1085
- }
1086
-
1087
- this.firstChunk.eachNext((chunk) => {
1088
- const loc = locate(chunk.start);
1089
-
1090
- if (chunk.intro.length) mappings.advance(chunk.intro);
1091
-
1092
- if (chunk.edited) {
1093
- mappings.addEdit(
1094
- sourceIndex,
1095
- chunk.content,
1096
- loc,
1097
- chunk.storeName ? names.indexOf(chunk.original) : -1,
1098
- );
1099
- } else {
1100
- mappings.addUneditedChunk(sourceIndex, chunk, this.original, loc, this.sourcemapLocations);
1101
- }
1102
-
1103
- if (chunk.outro.length) mappings.advance(chunk.outro);
1104
- });
1105
-
1106
- return {
1107
- file: options.file ? options.file.split(/[/\\]/).pop() : undefined,
1108
- sources: [
1109
- options.source ? getRelativePath(options.file || '', options.source) : options.file || '',
1110
- ],
1111
- sourcesContent: options.includeContent ? [this.original] : undefined,
1112
- names,
1113
- mappings: mappings.raw,
1114
- x_google_ignoreList: this.ignoreList ? [sourceIndex] : undefined,
1115
- };
1116
- }
1117
-
1118
- generateMap(options) {
1119
- return new SourceMap(this.generateDecodedMap(options));
1120
- }
1121
-
1122
- _ensureindentStr() {
1123
- if (this.indentStr === undefined) {
1124
- this.indentStr = guessIndent(this.original);
1125
- }
1126
- }
1127
-
1128
- _getRawIndentString() {
1129
- this._ensureindentStr();
1130
- return this.indentStr;
1131
- }
1132
-
1133
- getIndentString() {
1134
- this._ensureindentStr();
1135
- return this.indentStr === null ? '\t' : this.indentStr;
1136
- }
1137
-
1138
- indent(indentStr, options) {
1139
- const pattern = /^[^\r\n]/gm;
1140
-
1141
- if (isObject(indentStr)) {
1142
- options = indentStr;
1143
- indentStr = undefined;
1144
- }
1145
-
1146
- if (indentStr === undefined) {
1147
- this._ensureindentStr();
1148
- indentStr = this.indentStr || '\t';
1149
- }
1150
-
1151
- if (indentStr === '') return this; // noop
1152
-
1153
- options = options || {};
1154
-
1155
- // Process exclusion ranges
1156
- const isExcluded = {};
1157
-
1158
- if (options.exclude) {
1159
- const exclusions =
1160
- typeof options.exclude[0] === 'number' ? [options.exclude] : options.exclude;
1161
- exclusions.forEach((exclusion) => {
1162
- for (let i = exclusion[0]; i < exclusion[1]; i += 1) {
1163
- isExcluded[i] = true;
1164
- }
1165
- });
1166
- }
1167
-
1168
- let shouldIndentNextCharacter = options.indentStart !== false;
1169
- const replacer = (match) => {
1170
- if (shouldIndentNextCharacter) return `${indentStr}${match}`;
1171
- shouldIndentNextCharacter = true;
1172
- return match;
1173
- };
1174
-
1175
- this.intro = this.intro.replace(pattern, replacer);
1176
-
1177
- let charIndex = 0;
1178
- let chunk = this.firstChunk;
1179
-
1180
- while (chunk) {
1181
- const end = chunk.end;
1182
-
1183
- if (chunk.edited) {
1184
- if (!isExcluded[charIndex]) {
1185
- chunk.content = chunk.content.replace(pattern, replacer);
1186
-
1187
- if (chunk.content.length) {
1188
- shouldIndentNextCharacter = chunk.content[chunk.content.length - 1] === '\n';
1189
- }
1190
- }
1191
- } else {
1192
- charIndex = chunk.start;
1193
-
1194
- while (charIndex < end) {
1195
- if (!isExcluded[charIndex]) {
1196
- const char = this.original[charIndex];
1197
-
1198
- if (char === '\n') {
1199
- shouldIndentNextCharacter = true;
1200
- } else if (char !== '\r' && shouldIndentNextCharacter) {
1201
- shouldIndentNextCharacter = false;
1202
-
1203
- if (charIndex === chunk.start) {
1204
- chunk.prependRight(indentStr);
1205
- } else {
1206
- this._splitChunk(chunk, charIndex);
1207
- chunk = chunk.next;
1208
- chunk.prependRight(indentStr);
1209
- }
1210
- }
1211
- }
1212
-
1213
- charIndex += 1;
1214
- }
1215
- }
1216
-
1217
- charIndex = chunk.end;
1218
- chunk = chunk.next;
1219
- }
1220
-
1221
- this.outro = this.outro.replace(pattern, replacer);
1222
-
1223
- return this;
1224
- }
1225
-
1226
- insert() {
1227
- throw new Error(
1228
- 'magicString.insert(...) is deprecated. Use prependRight(...) or appendLeft(...)',
1229
- );
1230
- }
1231
-
1232
- insertLeft(index, content) {
1233
- if (!warned.insertLeft) {
1234
- console.warn(
1235
- 'magicString.insertLeft(...) is deprecated. Use magicString.appendLeft(...) instead',
1236
- );
1237
- warned.insertLeft = true;
1238
- }
1239
-
1240
- return this.appendLeft(index, content);
1241
- }
1242
-
1243
- insertRight(index, content) {
1244
- if (!warned.insertRight) {
1245
- console.warn(
1246
- 'magicString.insertRight(...) is deprecated. Use magicString.prependRight(...) instead',
1247
- );
1248
- warned.insertRight = true;
1249
- }
1250
-
1251
- return this.prependRight(index, content);
1252
- }
1253
-
1254
- move(start, end, index) {
1255
- start = start + this.offset;
1256
- end = end + this.offset;
1257
- index = index + this.offset;
1258
-
1259
- if (index >= start && index <= end) throw new Error('Cannot move a selection inside itself');
1260
-
1261
- this._split(start);
1262
- this._split(end);
1263
- this._split(index);
1264
-
1265
- const first = this.byStart[start];
1266
- const last = this.byEnd[end];
1267
-
1268
- const oldLeft = first.previous;
1269
- const oldRight = last.next;
1270
-
1271
- const newRight = this.byStart[index];
1272
- if (!newRight && last === this.lastChunk) return this;
1273
- const newLeft = newRight ? newRight.previous : this.lastChunk;
1274
-
1275
- if (oldLeft) oldLeft.next = oldRight;
1276
- if (oldRight) oldRight.previous = oldLeft;
1277
-
1278
- if (newLeft) newLeft.next = first;
1279
- if (newRight) newRight.previous = last;
1280
-
1281
- if (!first.previous) this.firstChunk = last.next;
1282
- if (!last.next) {
1283
- this.lastChunk = first.previous;
1284
- this.lastChunk.next = null;
1285
- }
1286
-
1287
- first.previous = newLeft;
1288
- last.next = newRight || null;
1289
-
1290
- if (!newLeft) this.firstChunk = first;
1291
- if (!newRight) this.lastChunk = last;
1292
- return this;
1293
- }
1294
-
1295
- overwrite(start, end, content, options) {
1296
- options = options || {};
1297
- return this.update(start, end, content, { ...options, overwrite: !options.contentOnly });
1298
- }
1299
-
1300
- update(start, end, content, options) {
1301
- start = start + this.offset;
1302
- end = end + this.offset;
1303
-
1304
- if (typeof content !== 'string') throw new TypeError('replacement content must be a string');
1305
-
1306
- if (this.original.length !== 0) {
1307
- while (start < 0) start += this.original.length;
1308
- while (end < 0) end += this.original.length;
1309
- }
1310
-
1311
- if (end > this.original.length) throw new Error('end is out of bounds');
1312
- if (start === end)
1313
- throw new Error(
1314
- 'Cannot overwrite a zero-length range – use appendLeft or prependRight instead',
1315
- );
1316
-
1317
- this._split(start);
1318
- this._split(end);
1319
-
1320
- if (options === true) {
1321
- if (!warned.storeName) {
1322
- console.warn(
1323
- 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
1324
- );
1325
- warned.storeName = true;
1326
- }
1327
-
1328
- options = { storeName: true };
1329
- }
1330
- const storeName = options !== undefined ? options.storeName : false;
1331
- const overwrite = options !== undefined ? options.overwrite : false;
1332
-
1333
- if (storeName) {
1334
- const original = this.original.slice(start, end);
1335
- Object.defineProperty(this.storedNames, original, {
1336
- writable: true,
1337
- value: true,
1338
- enumerable: true,
1339
- });
1340
- }
1341
-
1342
- const first = this.byStart[start];
1343
- const last = this.byEnd[end];
1344
-
1345
- if (first) {
1346
- let chunk = first;
1347
- while (chunk !== last) {
1348
- if (chunk.next !== this.byStart[chunk.end]) {
1349
- throw new Error('Cannot overwrite across a split point');
1350
- }
1351
- chunk = chunk.next;
1352
- chunk.edit('', false);
1353
- }
1354
-
1355
- first.edit(content, storeName, !overwrite);
1356
- } else {
1357
- // must be inserting at the end
1358
- const newChunk = new Chunk(start, end, '').edit(content, storeName);
1359
-
1360
- // TODO last chunk in the array may not be the last chunk, if it's moved...
1361
- last.next = newChunk;
1362
- newChunk.previous = last;
1363
- }
1364
- return this;
1365
- }
1366
-
1367
- prepend(content) {
1368
- if (typeof content !== 'string') throw new TypeError('outro content must be a string');
1369
-
1370
- this.intro = content + this.intro;
1371
- return this;
1372
- }
1373
-
1374
- prependLeft(index, content) {
1375
- index = index + this.offset;
1376
-
1377
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1378
-
1379
- this._split(index);
1380
-
1381
- const chunk = this.byEnd[index];
1382
-
1383
- if (chunk) {
1384
- chunk.prependLeft(content);
1385
- } else {
1386
- this.intro = content + this.intro;
1387
- }
1388
- return this;
1389
- }
1390
-
1391
- prependRight(index, content) {
1392
- index = index + this.offset;
1393
-
1394
- if (typeof content !== 'string') throw new TypeError('inserted content must be a string');
1395
-
1396
- this._split(index);
1397
-
1398
- const chunk = this.byStart[index];
1399
-
1400
- if (chunk) {
1401
- chunk.prependRight(content);
1402
- } else {
1403
- this.outro = content + this.outro;
1404
- }
1405
- return this;
1406
- }
1407
-
1408
- remove(start, end) {
1409
- start = start + this.offset;
1410
- end = end + this.offset;
1411
-
1412
- if (this.original.length !== 0) {
1413
- while (start < 0) start += this.original.length;
1414
- while (end < 0) end += this.original.length;
1415
- }
1416
-
1417
- if (start === end) return this;
1418
-
1419
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1420
- if (start > end) throw new Error('end must be greater than start');
1421
-
1422
- this._split(start);
1423
- this._split(end);
1424
-
1425
- let chunk = this.byStart[start];
1426
-
1427
- while (chunk) {
1428
- chunk.intro = '';
1429
- chunk.outro = '';
1430
- chunk.edit('');
1431
-
1432
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1433
- }
1434
- return this;
1435
- }
1436
-
1437
- reset(start, end) {
1438
- start = start + this.offset;
1439
- end = end + this.offset;
1440
-
1441
- if (this.original.length !== 0) {
1442
- while (start < 0) start += this.original.length;
1443
- while (end < 0) end += this.original.length;
1444
- }
1445
-
1446
- if (start === end) return this;
1447
-
1448
- if (start < 0 || end > this.original.length) throw new Error('Character is out of bounds');
1449
- if (start > end) throw new Error('end must be greater than start');
1450
-
1451
- this._split(start);
1452
- this._split(end);
1453
-
1454
- let chunk = this.byStart[start];
1455
-
1456
- while (chunk) {
1457
- chunk.reset();
1458
-
1459
- chunk = end > chunk.end ? this.byStart[chunk.end] : null;
1460
- }
1461
- return this;
1462
- }
1463
-
1464
- lastChar() {
1465
- if (this.outro.length) return this.outro[this.outro.length - 1];
1466
- let chunk = this.lastChunk;
1467
- do {
1468
- if (chunk.outro.length) return chunk.outro[chunk.outro.length - 1];
1469
- if (chunk.content.length) return chunk.content[chunk.content.length - 1];
1470
- if (chunk.intro.length) return chunk.intro[chunk.intro.length - 1];
1471
- } while ((chunk = chunk.previous));
1472
- if (this.intro.length) return this.intro[this.intro.length - 1];
1473
- return '';
1474
- }
1475
-
1476
- lastLine() {
1477
- let lineIndex = this.outro.lastIndexOf(n);
1478
- if (lineIndex !== -1) return this.outro.substr(lineIndex + 1);
1479
- let lineStr = this.outro;
1480
- let chunk = this.lastChunk;
1481
- do {
1482
- if (chunk.outro.length > 0) {
1483
- lineIndex = chunk.outro.lastIndexOf(n);
1484
- if (lineIndex !== -1) return chunk.outro.substr(lineIndex + 1) + lineStr;
1485
- lineStr = chunk.outro + lineStr;
1486
- }
1487
-
1488
- if (chunk.content.length > 0) {
1489
- lineIndex = chunk.content.lastIndexOf(n);
1490
- if (lineIndex !== -1) return chunk.content.substr(lineIndex + 1) + lineStr;
1491
- lineStr = chunk.content + lineStr;
1492
- }
1493
-
1494
- if (chunk.intro.length > 0) {
1495
- lineIndex = chunk.intro.lastIndexOf(n);
1496
- if (lineIndex !== -1) return chunk.intro.substr(lineIndex + 1) + lineStr;
1497
- lineStr = chunk.intro + lineStr;
1498
- }
1499
- } while ((chunk = chunk.previous));
1500
- lineIndex = this.intro.lastIndexOf(n);
1501
- if (lineIndex !== -1) return this.intro.substr(lineIndex + 1) + lineStr;
1502
- return this.intro + lineStr;
1503
- }
1504
-
1505
- slice(start = 0, end = this.original.length - this.offset) {
1506
- start = start + this.offset;
1507
- end = end + this.offset;
1508
-
1509
- if (this.original.length !== 0) {
1510
- while (start < 0) start += this.original.length;
1511
- while (end < 0) end += this.original.length;
1512
- }
1513
-
1514
- let result = '';
1515
-
1516
- // find start chunk
1517
- let chunk = this.firstChunk;
1518
- while (chunk && (chunk.start > start || chunk.end <= start)) {
1519
- // found end chunk before start
1520
- if (chunk.start < end && chunk.end >= end) {
1521
- return result;
1522
- }
1523
-
1524
- chunk = chunk.next;
1525
- }
1526
-
1527
- if (chunk && chunk.edited && chunk.start !== start)
1528
- throw new Error(`Cannot use replaced character ${start} as slice start anchor.`);
1529
-
1530
- const startChunk = chunk;
1531
- while (chunk) {
1532
- if (chunk.intro && (startChunk !== chunk || chunk.start === start)) {
1533
- result += chunk.intro;
1534
- }
1535
-
1536
- const containsEnd = chunk.start < end && chunk.end >= end;
1537
- if (containsEnd && chunk.edited && chunk.end !== end)
1538
- throw new Error(`Cannot use replaced character ${end} as slice end anchor.`);
1539
-
1540
- const sliceStart = startChunk === chunk ? start - chunk.start : 0;
1541
- const sliceEnd = containsEnd ? chunk.content.length + end - chunk.end : chunk.content.length;
1542
-
1543
- result += chunk.content.slice(sliceStart, sliceEnd);
1544
-
1545
- if (chunk.outro && (!containsEnd || chunk.end === end)) {
1546
- result += chunk.outro;
1547
- }
1548
-
1549
- if (containsEnd) {
1550
- break;
1551
- }
1552
-
1553
- chunk = chunk.next;
1554
- }
1555
-
1556
- return result;
1557
- }
1558
-
1559
- // TODO deprecate this? not really very useful
1560
- snip(start, end) {
1561
- const clone = this.clone();
1562
- clone.remove(0, start);
1563
- clone.remove(end, clone.original.length);
1564
-
1565
- return clone;
1566
- }
1567
-
1568
- _split(index) {
1569
- if (this.byStart[index] || this.byEnd[index]) return;
1570
-
1571
- let chunk = this.lastSearchedChunk;
1572
- const searchForward = index > chunk.end;
1573
-
1574
- while (chunk) {
1575
- if (chunk.contains(index)) return this._splitChunk(chunk, index);
1576
-
1577
- chunk = searchForward ? this.byStart[chunk.end] : this.byEnd[chunk.start];
1578
- }
1579
- }
1580
-
1581
- _splitChunk(chunk, index) {
1582
- if (chunk.edited && chunk.content.length) {
1583
- // zero-length edited chunks are a special case (overlapping replacements)
1584
- const loc = getLocator(this.original)(index);
1585
- throw new Error(
1586
- `Cannot split a chunk that has already been edited (${loc.line}:${loc.column} – "${chunk.original}")`,
1587
- );
1588
- }
1589
-
1590
- const newChunk = chunk.split(index);
1591
-
1592
- this.byEnd[index] = chunk;
1593
- this.byStart[index] = newChunk;
1594
- this.byEnd[newChunk.end] = newChunk;
1595
-
1596
- if (chunk === this.lastChunk) this.lastChunk = newChunk;
1597
-
1598
- this.lastSearchedChunk = chunk;
1599
- return true;
1600
- }
1601
-
1602
- toString() {
1603
- let str = this.intro;
1604
-
1605
- let chunk = this.firstChunk;
1606
- while (chunk) {
1607
- str += chunk.toString();
1608
- chunk = chunk.next;
1609
- }
1610
-
1611
- return str + this.outro;
1612
- }
1613
-
1614
- isEmpty() {
1615
- let chunk = this.firstChunk;
1616
- do {
1617
- if (
1618
- (chunk.intro.length && chunk.intro.trim()) ||
1619
- (chunk.content.length && chunk.content.trim()) ||
1620
- (chunk.outro.length && chunk.outro.trim())
1621
- )
1622
- return false;
1623
- } while ((chunk = chunk.next));
1624
- return true;
1625
- }
1626
-
1627
- length() {
1628
- let chunk = this.firstChunk;
1629
- let length = 0;
1630
- do {
1631
- length += chunk.intro.length + chunk.content.length + chunk.outro.length;
1632
- } while ((chunk = chunk.next));
1633
- return length;
1634
- }
1635
-
1636
- trimLines() {
1637
- return this.trim('[\\r\\n]');
1638
- }
1639
-
1640
- trim(charType) {
1641
- return this.trimStart(charType).trimEnd(charType);
1642
- }
1643
-
1644
- trimEndAborted(charType) {
1645
- const rx = new RegExp((charType || '\\s') + '+$');
1646
-
1647
- this.outro = this.outro.replace(rx, '');
1648
- if (this.outro.length) return true;
1649
-
1650
- let chunk = this.lastChunk;
1651
-
1652
- do {
1653
- const end = chunk.end;
1654
- const aborted = chunk.trimEnd(rx);
1655
-
1656
- // if chunk was trimmed, we have a new lastChunk
1657
- if (chunk.end !== end) {
1658
- if (this.lastChunk === chunk) {
1659
- this.lastChunk = chunk.next;
1660
- }
1661
-
1662
- this.byEnd[chunk.end] = chunk;
1663
- this.byStart[chunk.next.start] = chunk.next;
1664
- this.byEnd[chunk.next.end] = chunk.next;
1665
- }
1666
-
1667
- if (aborted) return true;
1668
- chunk = chunk.previous;
1669
- } while (chunk);
1670
-
1671
- return false;
1672
- }
1673
-
1674
- trimEnd(charType) {
1675
- this.trimEndAborted(charType);
1676
- return this;
1677
- }
1678
- trimStartAborted(charType) {
1679
- const rx = new RegExp('^' + (charType || '\\s') + '+');
1680
-
1681
- this.intro = this.intro.replace(rx, '');
1682
- if (this.intro.length) return true;
1683
-
1684
- let chunk = this.firstChunk;
1685
-
1686
- do {
1687
- const end = chunk.end;
1688
- const aborted = chunk.trimStart(rx);
1689
-
1690
- if (chunk.end !== end) {
1691
- // special case...
1692
- if (chunk === this.lastChunk) this.lastChunk = chunk.next;
1693
-
1694
- this.byEnd[chunk.end] = chunk;
1695
- this.byStart[chunk.next.start] = chunk.next;
1696
- this.byEnd[chunk.next.end] = chunk.next;
1697
- }
1698
-
1699
- if (aborted) return true;
1700
- chunk = chunk.next;
1701
- } while (chunk);
1702
-
1703
- return false;
1704
- }
1705
-
1706
- trimStart(charType) {
1707
- this.trimStartAborted(charType);
1708
- return this;
1709
- }
1710
-
1711
- hasChanged() {
1712
- return this.original !== this.toString();
1713
- }
1714
-
1715
- _replaceRegexp(searchValue, replacement) {
1716
- function getReplacement(match, str) {
1717
- if (typeof replacement === 'string') {
1718
- return replacement.replace(/\$(\$|&|\d+)/g, (_, i) => {
1719
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#specifying_a_string_as_a_parameter
1720
- if (i === '$') return '$';
1721
- if (i === '&') return match[0];
1722
- const num = +i;
1723
- if (num < match.length) return match[+i];
1724
- return `$${i}`;
1725
- });
1726
- } else {
1727
- return replacement(...match, match.index, str, match.groups);
1728
- }
1729
- }
1730
- function matchAll(re, str) {
1731
- let match;
1732
- const matches = [];
1733
- while ((match = re.exec(str))) {
1734
- matches.push(match);
1735
- }
1736
- return matches;
1737
- }
1738
- if (searchValue.global) {
1739
- const matches = matchAll(searchValue, this.original);
1740
- matches.forEach((match) => {
1741
- if (match.index != null) {
1742
- const replacement = getReplacement(match, this.original);
1743
- if (replacement !== match[0]) {
1744
- this.overwrite(match.index, match.index + match[0].length, replacement);
1745
- }
1746
- }
1747
- });
1748
- } else {
1749
- const match = this.original.match(searchValue);
1750
- if (match && match.index != null) {
1751
- const replacement = getReplacement(match, this.original);
1752
- if (replacement !== match[0]) {
1753
- this.overwrite(match.index, match.index + match[0].length, replacement);
1754
- }
1755
- }
1756
- }
1757
- return this;
1758
- }
1759
-
1760
- _replaceString(string, replacement) {
1761
- const { original } = this;
1762
- const index = original.indexOf(string);
1763
-
1764
- if (index !== -1) {
1765
- this.overwrite(index, index + string.length, replacement);
1766
- }
1767
-
1768
- return this;
1769
- }
1770
-
1771
- replace(searchValue, replacement) {
1772
- if (typeof searchValue === 'string') {
1773
- return this._replaceString(searchValue, replacement);
1774
- }
1775
-
1776
- return this._replaceRegexp(searchValue, replacement);
1777
- }
1778
-
1779
- _replaceAllString(string, replacement) {
1780
- const { original } = this;
1781
- const stringLength = string.length;
1782
- for (
1783
- let index = original.indexOf(string);
1784
- index !== -1;
1785
- index = original.indexOf(string, index + stringLength)
1786
- ) {
1787
- const previous = original.slice(index, index + stringLength);
1788
- if (previous !== replacement) this.overwrite(index, index + stringLength, replacement);
1789
- }
1790
-
1791
- return this;
1792
- }
1793
-
1794
- replaceAll(searchValue, replacement) {
1795
- if (typeof searchValue === 'string') {
1796
- return this._replaceAllString(searchValue, replacement);
1797
- }
1798
-
1799
- if (!searchValue.global) {
1800
- throw new TypeError(
1801
- 'MagicString.prototype.replaceAll called with a non-global RegExp argument',
1802
- );
1803
- }
1804
-
1805
- return this._replaceRegexp(searchValue, replacement);
1806
- }
1807
- }
1808
-
1809
- /**@target web */
1810
- // index.ts for more details on contents and license of this file
1811
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1302
1812
- function evalValue(rawValue) {
1813
- const fn = new Function(`
1814
- var console, exports, global, module, process, require
1815
- return (\n${rawValue}\n)
1816
- `);
1817
- return fn();
1818
- }
1819
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L31-L34
1820
- const postfixRE = /[?#].*$/;
1821
- function cleanUrl(url) {
1822
- return url.replace(postfixRE, '');
1823
- }
1824
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L393
1825
- function tryStatSync(file) {
1826
- try {
1827
- // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
1828
- return fs__namespace.statSync(file, { throwIfNoEntry: false });
1829
- }
1830
- catch {
1831
- }
1832
- return;
1833
- }
1834
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1030
1835
- function getHash(text, length = 8) {
1836
- const h = node_crypto.createHash('sha256').update(text).digest('hex').substring(0, length);
1837
- if (length <= 64) {
1838
- return h;
1839
- }
1840
- return h.padEnd(length, '_');
1841
- }
1842
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L40
1843
- function withTrailingSlash(path) {
1844
- if (path[path.length - 1] !== '/') {
1845
- return `${path}/`;
1846
- }
1847
- return path;
1848
- }
1849
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1268
1850
- function joinUrlSegments(a, b) {
1851
- if (!a || !b) {
1852
- return a || b || '';
1853
- }
1854
- if (a[a.length - 1] === '/') {
1855
- a = a.substring(0, a.length - 1);
1856
- }
1857
- if (b[0] !== '/') {
1858
- b = `/${b}`;
1859
- }
1860
- return a + b;
1861
- }
1862
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1281
1863
- function removeLeadingSlash(str) {
1864
- return str[0] === '/' ? str.slice(1) : str;
1865
- }
1866
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L319
1867
- function injectQuery(builtUrl, query) {
1868
- const queryIndex = builtUrl.indexOf('?');
1869
- return builtUrl + (queryIndex === -1 ? '?' : '&') + query;
1870
- }
1871
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1435
1872
- function partialEncodeURIPath(uri) {
1873
- if (uri.startsWith('data:')) {
1874
- return uri;
1875
- }
1876
- const filePath = cleanUrl(uri);
1877
- const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
1878
- return filePath.replaceAll('%', '%25') + postfix;
1879
- }
1880
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1424
1881
- function encodeURIPath(uri) {
1882
- if (uri.startsWith('data:')) {
1883
- return uri;
1884
- }
1885
- const filePath = cleanUrl(uri);
1886
- const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
1887
- return encodeURI(filePath) + postfix;
1888
- }
1889
-
1890
- /**@target web */
1891
- const FS_PREFIX = '/@fs/';
1892
- async function fileToUrl(id, config) {
1893
- let rtn;
1894
- if (id.startsWith(withTrailingSlash(config.root))) {
1895
- // in project root, infer short public path
1896
- rtn = `/${path__namespace.posix.relative(config.root, id)}`;
1897
- }
1898
- else {
1899
- // outside of project root, use absolute fs path
1900
- // (this is special handled by the serve static middleware
1901
- rtn = path__namespace.posix.join(FS_PREFIX, id);
1902
- }
1903
- const base = joinUrlSegments(config.server?.origin ?? '', config.base);
1904
- return joinUrlSegments(base, removeLeadingSlash(rtn));
1905
- }
1906
-
1907
- /**@target web */
1908
- // index.ts for more details on contents and license of this file
1909
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L143
1910
- const METADATA_FILENAME = '_metadata.json';
1911
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L63
1912
- const ENV_PUBLIC_PATH = '/@vite/env';
1913
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/constants.ts#L10C1-L38C32
1914
- const ROLLUP_HOOKS = [
1915
- 'options',
1916
- 'buildStart',
1917
- 'buildEnd',
1918
- 'renderStart',
1919
- 'renderError',
1920
- 'renderChunk',
1921
- 'writeBundle',
1922
- 'generateBundle',
1923
- 'banner',
1924
- 'footer',
1925
- 'augmentChunkHash',
1926
- 'outputOptions',
1927
- 'renderDynamicImport',
1928
- 'resolveFileUrl',
1929
- 'resolveImportMeta',
1930
- 'intro',
1931
- 'outro',
1932
- 'closeBundle',
1933
- 'closeWatcher',
1934
- 'load',
1935
- 'moduleParsed',
1936
- 'watchChange',
1937
- 'resolveDynamicImport',
1938
- 'resolveId',
1939
- 'shouldTransformCachedModule',
1940
- 'transform',
1941
- 'onLog'
1942
- ];
1943
-
1944
- /**@target web */
1945
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/plugins/index.ts#L161
1946
- // biome-ignore lint/complexity/noBannedTypes: Function type needed here
1947
- function getHookHandler(hook) {
1948
- return (typeof hook === 'object' ? hook.handler : hook);
1949
- }
1950
-
1951
- /**@target web */
1952
- const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
1953
- const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
1954
- const backSlashRegEx = /\\/g;
1955
- function escapeId(id) {
1956
- if (!needsEscapeRegEx.test(id)) {
1957
- return id;
1958
- }
1959
- return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
1960
- }
1961
- const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
1962
- const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
1963
- const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
1964
- const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
1965
- const relativeUrlMechanisms = {
1966
- amd: relativePath => {
1967
- if (relativePath[0] !== '.') {
1968
- relativePath = `./${relativePath}`;
1969
- }
1970
- return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
1971
- },
1972
- cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
1973
- es: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
1974
- iife: relativePath => getRelativeUrlFromDocument(relativePath),
1975
- // NOTE: make sure rollup generate `module` params
1976
- system: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`),
1977
- umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
1978
- };
1979
- const customRelativeUrlMechanisms = {
1980
- ...relativeUrlMechanisms,
1981
- 'worker-iife': relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
1982
- };
1983
- function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
1984
- const formatLong = isWorker && format === 'iife' ? 'worker-iife' : format;
1985
- const toRelativePath = customRelativeUrlMechanisms[formatLong];
1986
- return (filename, importer) => ({
1987
- runtime: toRelativePath(path__namespace.posix.relative(path__namespace.dirname(importer), filename))
1988
- });
1989
- }
1990
- function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
1991
- const { renderBuiltUrl } = config.experimental;
1992
- let relative = config.base === '' || config.base === '@src/vite/bridge/';
1993
- if (renderBuiltUrl) {
1994
- const result = renderBuiltUrl(filename, {
1995
- hostId,
1996
- hostType,
1997
- type,
1998
- ssr: !!config.build.ssr
1999
- });
2000
- if (typeof result === 'object') {
2001
- if (result.runtime) {
2002
- return { runtime: result.runtime };
2003
- }
2004
- if (typeof result.relative === 'boolean') {
2005
- relative = result.relative;
2006
- }
2007
- }
2008
- else if (result) {
2009
- return result;
2010
- }
2011
- }
2012
- if (relative && !config.build.ssr) {
2013
- return toRelative(filename, hostId);
2014
- }
2015
- return joinUrlSegments(config.base, filename);
2016
- }
2017
- // https://github.com/vitejs/vite/blob/v6.1.1/packages/vite/src/node/build.ts#L1131
2018
- function injectEnvironmentToHooks(environment, plugin) {
2019
- const { resolveId, load, transform } = plugin;
2020
- const clone = { ...plugin };
2021
- for (const hook of Object.keys(clone)) {
2022
- switch (hook) {
2023
- case 'resolveId':
2024
- clone[hook] = wrapEnvironmentResolveId(environment, resolveId);
2025
- break;
2026
- case 'load':
2027
- clone[hook] = wrapEnvironmentLoad(environment, load);
2028
- break;
2029
- case 'transform':
2030
- clone[hook] = wrapEnvironmentTransform(environment, transform);
2031
- break;
2032
- default:
2033
- if (ROLLUP_HOOKS.includes(hook)) {
2034
- clone[hook] = wrapEnvironmentHook(environment, clone[hook]);
2035
- }
2036
- break;
2037
- }
2038
- }
2039
- return clone;
2040
- }
2041
- function wrapEnvironmentResolveId(environment, hook) {
2042
- if (!hook) {
2043
- return;
2044
- }
2045
- const fn = getHookHandler(hook);
2046
- const handler = function (id, importer, options) {
2047
- return fn.call(injectEnvironmentInContext(this, environment), id, importer, injectSsrFlag(options, environment));
2048
- };
2049
- if ('handler' in hook) {
2050
- return {
2051
- ...hook,
2052
- handler
2053
- };
2054
- }
2055
- return handler;
2056
- }
2057
- function wrapEnvironmentLoad(environment, hook) {
2058
- if (!hook) {
2059
- return;
2060
- }
2061
- const fn = getHookHandler(hook);
2062
- const handler = function (id, ...args) {
2063
- return fn.call(injectEnvironmentInContext(this, environment), id, injectSsrFlag(args[0], environment));
2064
- };
2065
- if ('handler' in hook) {
2066
- return {
2067
- ...hook,
2068
- handler
2069
- };
2070
- }
2071
- return handler;
2072
- }
2073
- function wrapEnvironmentTransform(environment, hook) {
2074
- if (!hook) {
2075
- return;
2076
- }
2077
- const fn = getHookHandler(hook);
2078
- const handler = function (code, importer, ...args) {
2079
- return fn.call(injectEnvironmentInContext(this, environment), code, importer, injectSsrFlag(args[0], environment));
2080
- };
2081
- if ('handler' in hook) {
2082
- return {
2083
- ...hook,
2084
- handler
2085
- };
2086
- }
2087
- return handler;
2088
- }
2089
- function wrapEnvironmentHook(environment, hook) {
2090
- if (!hook) {
2091
- return;
2092
- }
2093
- const fn = getHookHandler(hook);
2094
- if (typeof fn !== 'function') {
2095
- return hook;
2096
- }
2097
- const handler = function (...args) {
2098
- return fn.call(injectEnvironmentInContext(this, environment), ...args);
2099
- };
2100
- if ('handler' in hook) {
2101
- return {
2102
- ...hook,
2103
- handler
2104
- };
2105
- }
2106
- return handler;
2107
- }
2108
- function injectEnvironmentInContext(context, environment) {
2109
- context.environment ?? (context.environment = environment);
2110
- return context;
2111
- }
2112
- function injectSsrFlag(options, environment) {
2113
- const ssr = environment ? environment.config.consumer === 'server' : true;
2114
- return { ...(options ?? {}), ssr };
2115
- }
2116
-
2117
- /**@target web */
2118
- // index.ts for more details on contents and license of this file
2119
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/fsUtils.ts#L388
2120
- function tryResolveRealFile(file, preserveSymlinks) {
2121
- const fileStat = tryStatSync(file);
2122
- if (fileStat?.isFile()) {
2123
- return file;
2124
- }
2125
- if (fileStat?.isSymbolicLink()) {
2126
- return preserveSymlinks ? file : fs__namespace.realpathSync(file);
2127
- }
2128
- return undefined;
2129
- }
2130
-
2131
- /**@target web */
2132
- // index.ts for more details on contents and license of this file
2133
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L534
2134
- function splitFileAndPostfix(path) {
2135
- const file = cleanUrl(path);
2136
- return { file, postfix: path.slice(file.length) };
2137
- }
2138
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L566-L574
2139
- function tryFsResolve(fsPath, preserveSymlinks) {
2140
- const { file, postfix } = splitFileAndPostfix(fsPath);
2141
- const res = tryCleanFsResolve(file, preserveSymlinks);
2142
- if (res) {
2143
- return res + postfix;
2144
- }
2145
- return;
2146
- }
2147
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L580
2148
- function tryCleanFsResolve(file, preserveSymlinks) {
2149
- if (file.includes('node_modules')) {
2150
- return tryResolveRealFile(file, preserveSymlinks);
2151
- }
2152
- const normalizedResolved = tryResolveRealFile(vite.normalizePath(file));
2153
- if (!normalizedResolved) {
2154
- return tryResolveRealFile(file, preserveSymlinks);
2155
- }
2156
- return normalizedResolved;
2157
- }
2158
-
2159
- /**@target web */
2160
- // index.ts for more details on contents and license of this file
2161
- // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/index.ts#L1356
2162
- function tryOptimizedDepResolve(config, ssr, url, depId, preserveSymlinks) {
2163
- const optimizer = getDepsOptimizer(config, ssr);
2164
- if (optimizer?.isOptimizedDepFile(depId)) {
2165
- const depFile = cleanUrl(depId);
2166
- const info = optimizedDepInfoFromFile(optimizer.metadata, depFile);
2167
- const depSrc = info?.src;
2168
- if (depSrc) {
2169
- const resolvedFile = path__namespace.resolve(path__namespace.dirname(depSrc), url);
2170
- return tryFsResolve(resolvedFile, preserveSymlinks);
2171
- }
2172
- }
2173
- return undefined;
2174
- }
2175
- // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/optimizer.ts#L32-L40
2176
- const depsOptimizerMap = new WeakMap();
2177
- const devSsrDepsOptimizerMap = new WeakMap();
2178
- function getDepsOptimizer(config, ssr) {
2179
- const map = ssr ? devSsrDepsOptimizerMap : depsOptimizerMap;
2180
- let optimizer = map.get(config);
2181
- if (!optimizer) {
2182
- optimizer = createDepsOptimizer(config);
2183
- map.set(config, optimizer);
2184
- }
2185
- return optimizer;
2186
- }
2187
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/optimizer.ts#L79
2188
- function createDepsOptimizer(config) {
2189
- const depsCacheDirPrefix = vite.normalizePath(path__namespace.resolve(config.cacheDir, 'deps'));
2190
- const metadata = parseDepsOptimizerMetadata(fs__namespace.readFileSync(path__namespace.join(depsCacheDirPrefix, METADATA_FILENAME), 'utf8'), depsCacheDirPrefix);
2191
- const notImplemented = () => {
2192
- throw new Error('not implemented');
2193
- };
2194
- const depsOptimizer = {
2195
- async init() {
2196
- },
2197
- metadata,
2198
- registerMissingImport: notImplemented,
2199
- run: notImplemented,
2200
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L916
2201
- isOptimizedDepFile: id => id.startsWith(depsCacheDirPrefix),
2202
- isOptimizedDepUrl: notImplemented,
2203
- getOptimizedDepId: notImplemented,
2204
- close: notImplemented,
2205
- options: {}
2206
- };
2207
- return depsOptimizer;
2208
- }
2209
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L944
2210
- function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
2211
- const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
2212
- if (key === 'file' || key === 'src') {
2213
- return vite.normalizePath(path__namespace.resolve(depsCacheDir, value));
2214
- }
2215
- return value;
2216
- });
2217
- if (!chunks || Object.values(optimized).some(depInfo => !depInfo.fileHash)) {
2218
- // outdated _metadata.json version, ignore
2219
- return;
2220
- }
2221
- const metadata = {
2222
- hash,
2223
- lockfileHash,
2224
- configHash,
2225
- browserHash,
2226
- optimized: {},
2227
- discovered: {},
2228
- chunks: {},
2229
- depInfoList: []
2230
- };
2231
- for (const id of Object.keys(optimized)) {
2232
- addOptimizedDepInfo(metadata, 'optimized', {
2233
- ...optimized[id],
2234
- id,
2235
- browserHash
2236
- });
2237
- }
2238
- for (const id of Object.keys(chunks)) {
2239
- addOptimizedDepInfo(metadata, 'chunks', {
2240
- ...chunks[id],
2241
- id,
2242
- browserHash,
2243
- needsInterop: false
2244
- });
2245
- }
2246
- return metadata;
2247
- }
2248
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L322
2249
- function addOptimizedDepInfo(metadata, type, depInfo) {
2250
- metadata[type][depInfo.id] = depInfo;
2251
- metadata.depInfoList.push(depInfo);
2252
- return depInfo;
2253
- }
2254
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L1248
2255
- function optimizedDepInfoFromFile(metadata, file) {
2256
- return metadata.depInfoList.find(depInfo => depInfo.file === file);
2257
- }
2258
-
2259
- /**@target web */
2260
- // biome-ignore lint/suspicious/noConstEnum: Exception where we use them
2261
- var AlphaTabWorkerTypes;
2262
- (function (AlphaTabWorkerTypes) {
2263
- AlphaTabWorkerTypes["WorkerClassic"] = "worker_classic";
2264
- AlphaTabWorkerTypes["WorkerModule"] = "worker_module";
2265
- AlphaTabWorkerTypes["AudioWorklet"] = "audio_worklet";
2266
- })(AlphaTabWorkerTypes || (AlphaTabWorkerTypes = {}));
2267
- const workerCache = new WeakMap();
2268
- const WORKER_FILE_ID = 'alphatab_worker';
2269
- const WORKER_ASSET_ID = '__ALPHATAB_WORKER_ASSET__';
2270
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L47
2271
- function saveEmitWorkerAsset(config, asset) {
2272
- const workerMap = workerCache.get(config.mainConfig || config);
2273
- workerMap.assets.set(asset.fileName, asset);
2274
- }
2275
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L161
2276
- async function workerFileToUrl(config, id) {
2277
- const workerMap = workerCache.get(config.mainConfig || config);
2278
- let fileName = workerMap.bundle.get(id);
2279
- if (!fileName) {
2280
- const outputChunk = await bundleWorkerEntry(config, id);
2281
- fileName = outputChunk.fileName;
2282
- saveEmitWorkerAsset(config, {
2283
- fileName,
2284
- source: outputChunk.code
2285
- });
2286
- workerMap.bundle.set(id, fileName);
2287
- }
2288
- return encodeWorkerAssetFileName(fileName, workerMap);
2289
- }
2290
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L149
2291
- function encodeWorkerAssetFileName(fileName, workerCache) {
2292
- const { fileNameHash } = workerCache;
2293
- const hash = getHash(fileName);
2294
- if (!fileNameHash.get(hash)) {
2295
- fileNameHash.set(hash, fileName);
2296
- }
2297
- return `${WORKER_ASSET_ID}${hash}__`;
2298
- }
2299
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L55
2300
- async function bundleWorkerEntry(config, id) {
2301
- const input = cleanUrl(id);
2302
- const bundleChain = config.bundleChain ?? [];
2303
- const newBundleChain = [...bundleChain, input];
2304
- if (bundleChain.includes(input)) {
2305
- throw new Error(`Circular worker imports detected. Vite does not support it. Import chain: ${newBundleChain.join(' -> ')}`);
2306
- }
2307
- // bundle the file as entry to support imports
2308
- const { rollup } = await import('rollup');
2309
- const { plugins, rollupOptions, format } = config.worker;
2310
- const workerConfig = await plugins(newBundleChain);
2311
- const workerEnvironment = new vite.BuildEnvironment('client', workerConfig); // TODO: should this be 'worker'?
2312
- await workerEnvironment.init();
2313
- const bundle = await rollup({
2314
- ...rollupOptions,
2315
- input,
2316
- plugins: workerEnvironment.plugins.map(p => injectEnvironmentToHooks(workerEnvironment, p)),
2317
- preserveEntrySignatures: false
2318
- });
2319
- let chunk;
2320
- try {
2321
- const workerOutputConfig = config.worker.rollupOptions.output;
2322
- const workerConfig = workerOutputConfig
2323
- ? Array.isArray(workerOutputConfig)
2324
- ? workerOutputConfig[0] || {}
2325
- : workerOutputConfig
2326
- : {};
2327
- const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
2328
- entryFileNames: path__namespace.posix.join(config.build.assetsDir, '[name]-[hash].js'),
2329
- chunkFileNames: path__namespace.posix.join(config.build.assetsDir, '[name]-[hash].js'),
2330
- assetFileNames: path__namespace.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
2331
- ...workerConfig,
2332
- format,
2333
- sourcemap: config.build.sourcemap
2334
- });
2335
- chunk = outputChunk;
2336
- for (const outputChunk of outputChunks) {
2337
- if (outputChunk.type === 'asset') {
2338
- saveEmitWorkerAsset(config, outputChunk);
2339
- }
2340
- else if (outputChunk.type === 'chunk') {
2341
- saveEmitWorkerAsset(config, {
2342
- fileName: outputChunk.fileName,
2343
- source: outputChunk.code
2344
- });
2345
- }
2346
- }
2347
- }
2348
- finally {
2349
- await bundle.close();
2350
- }
2351
- return emitSourcemapForWorkerEntry(config, chunk);
2352
- }
2353
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L124
2354
- function emitSourcemapForWorkerEntry(config, chunk) {
2355
- const { map: sourcemap } = chunk;
2356
- if (sourcemap) {
2357
- if (config.build.sourcemap === 'hidden' || config.build.sourcemap === true) {
2358
- const data = sourcemap.toString();
2359
- const mapFileName = `${chunk.fileName}.map`;
2360
- saveEmitWorkerAsset(config, {
2361
- fileName: mapFileName,
2362
- source: data
2363
- });
2364
- }
2365
- }
2366
- return chunk;
2367
- }
2368
- // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L458
2369
- function isSameContent(a, b) {
2370
- if (typeof a === 'string') {
2371
- if (typeof b === 'string') {
2372
- return a === b;
2373
- }
2374
- return Buffer.from(a).equals(b);
2375
- }
2376
- return Buffer.from(b).equals(a);
2377
- }
2378
-
2379
- /**@target web */
2380
- const alphaTabWorkerPatterns = [
2381
- ['alphaTabWorker', 'new', 'alphaTabUrl', 'import.meta.url'],
2382
- ['alphaTabWorklet.addModule', 'new', 'alphaTabUrl', 'import.meta.url']
2383
- ];
2384
- function includesAlphaTabWorker(code) {
2385
- for (const pattern of alphaTabWorkerPatterns) {
2386
- let position = 0;
2387
- for (const match of pattern) {
2388
- position = code.indexOf(match, position);
2389
- if (position === -1) {
2390
- break;
2391
- }
2392
- }
2393
- if (position !== -1) {
2394
- return true;
2395
- }
2396
- }
2397
- return false;
2398
- }
2399
- function getWorkerType(code, match) {
2400
- if (match[1].includes('.addModule')) {
2401
- return AlphaTabWorkerTypes.AudioWorklet;
2402
- }
2403
- const endOfMatch = match.indices[0][1];
2404
- const startOfOptions = code.indexOf('{', endOfMatch);
2405
- if (startOfOptions === -1) {
2406
- return AlphaTabWorkerTypes.WorkerClassic;
2407
- }
2408
- const endOfOptions = code.indexOf('}', endOfMatch);
2409
- if (endOfOptions === -1) {
2410
- return AlphaTabWorkerTypes.WorkerClassic;
2411
- }
2412
- const endOfWorkerCreate = code.indexOf(')', endOfMatch);
2413
- if (startOfOptions > endOfWorkerCreate || endOfOptions > endOfWorkerCreate) {
2414
- return AlphaTabWorkerTypes.WorkerClassic;
2415
- }
2416
- let workerOptions = code.slice(startOfOptions, endOfOptions + 1);
2417
- try {
2418
- workerOptions = evalValue(workerOptions);
2419
- }
2420
- catch {
2421
- return AlphaTabWorkerTypes.WorkerClassic;
2422
- }
2423
- if (typeof workerOptions === 'object' && workerOptions?.type === 'module') {
2424
- return AlphaTabWorkerTypes.WorkerModule;
2425
- }
2426
- return AlphaTabWorkerTypes.WorkerClassic;
2427
- }
2428
- function importMetaUrlPlugin(options) {
2429
- let resolvedConfig;
2430
- let isBuild;
2431
- let preserveSymlinks;
2432
- const isWorkerActive = options.webWorkers !== false;
2433
- const isWorkletActive = options.audioWorklets !== false;
2434
- const isActive = isWorkerActive || isWorkletActive;
2435
- return {
2436
- name: 'vite-plugin-alphatab-url',
2437
- enforce: 'pre',
2438
- configResolved(config) {
2439
- resolvedConfig = config;
2440
- isBuild = config.command === 'build';
2441
- preserveSymlinks = config.resolve.preserveSymlinks;
2442
- },
2443
- shouldTransformCachedModule({ code }) {
2444
- if (isActive && isBuild && resolvedConfig.build.watch && includesAlphaTabWorker(code)) {
2445
- return true;
2446
- }
2447
- return;
2448
- },
2449
- async transform(code, id, options) {
2450
- if (!isActive || options?.ssr || !includesAlphaTabWorker(code)) {
2451
- return;
2452
- }
2453
- let s;
2454
- const alphaTabWorkerPattern =
2455
- // @ts-expect-error For the Vite plugin we expect newer node than for alphaTab itself (-> migrate to monorepo)
2456
- /\b(alphaTabWorker|alphaTabWorklet\.addModule)\s*\(\s*(new\s+[^ (]+alphaTabUrl\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
2457
- let match = alphaTabWorkerPattern.exec(code);
2458
- while (match) {
2459
- const workerType = getWorkerType(code, match);
2460
- let typeActive = false;
2461
- switch (workerType) {
2462
- case AlphaTabWorkerTypes.WorkerClassic:
2463
- case AlphaTabWorkerTypes.WorkerModule:
2464
- typeActive = isWorkerActive;
2465
- break;
2466
- case AlphaTabWorkerTypes.AudioWorklet:
2467
- typeActive = isWorkletActive;
2468
- break;
2469
- }
2470
- if (!typeActive) {
2471
- match = alphaTabWorkerPattern.exec(code);
2472
- continue;
2473
- }
2474
- s ?? (s = new MagicString(code));
2475
- const url = code.slice(match.indices[3][0] + 1, match.indices[3][1] - 1);
2476
- let file = path.resolve(path.dirname(id), url);
2477
- file =
2478
- tryFsResolve(file, preserveSymlinks) ??
2479
- tryOptimizedDepResolve(resolvedConfig, options?.ssr === true, url, id, preserveSymlinks) ??
2480
- file;
2481
- let builtUrl;
2482
- if (isBuild) {
2483
- builtUrl = await workerFileToUrl(resolvedConfig, file);
2484
- }
2485
- else {
2486
- builtUrl = await fileToUrl(cleanUrl(file), resolvedConfig);
2487
- builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
2488
- }
2489
- s.update(match.indices[3][0], match.indices[3][1],
2490
- // add `'' +` to skip vite:asset-import-meta-url plugin
2491
- `new URL('' + ${JSON.stringify(builtUrl)}, import.meta.url)`);
2492
- match = alphaTabWorkerPattern.exec(code);
2493
- }
2494
- if (s) {
2495
- return {
2496
- code: s.toString(),
2497
- map: resolvedConfig.command === 'build' && resolvedConfig.build.sourcemap
2498
- ? s.generateMap({ hires: 'boundary', source: id })
2499
- : null
2500
- };
2501
- }
2502
- return null;
2503
- }
2504
- };
2505
- }
2506
-
2507
- /**@target web */
2508
- function copyAssetsPlugin(options) {
2509
- let resolvedConfig;
2510
- let output = false;
2511
- return {
2512
- name: 'vite-plugin-alphatab-copy',
2513
- enforce: 'pre',
2514
- configResolved(config) {
2515
- resolvedConfig = config;
2516
- },
2517
- buildEnd() {
2518
- // reset for watch mode
2519
- output = false;
2520
- },
2521
- async buildStart() {
2522
- // run copy only once even if multiple bundles are generated
2523
- if (output) {
2524
- return;
2525
- }
2526
- output = true;
2527
- let alphaTabSourceDir = options.alphaTabSourceDir;
2528
- if (!alphaTabSourceDir) {
2529
- try {
2530
- const isEsm = typeof {} === 'string';
2531
- if (isEsm) {
2532
- alphaTabSourceDir = url__namespace.fileURLToPath({}('@coderline/alphatab'));
2533
- }
2534
- else {
2535
- alphaTabSourceDir = require.resolve('@coderline/alphatab');
2536
- }
2537
- alphaTabSourceDir = path__namespace.resolve(alphaTabSourceDir, '..');
2538
- }
2539
- catch {
2540
- alphaTabSourceDir = path__namespace.join(resolvedConfig.root, 'node_modules/@coderline/alphatab/dist/');
2541
- }
2542
- }
2543
- let isValidAlphaTabSourceDir;
2544
- if (alphaTabSourceDir) {
2545
- try {
2546
- await fs__namespace.promises.access(path__namespace.join(alphaTabSourceDir, 'alphaTab.mjs'), fs__namespace.constants.F_OK);
2547
- isValidAlphaTabSourceDir = true;
2548
- }
2549
- catch {
2550
- isValidAlphaTabSourceDir = false;
2551
- }
2552
- }
2553
- else {
2554
- isValidAlphaTabSourceDir = false;
2555
- }
2556
- if (!isValidAlphaTabSourceDir) {
2557
- resolvedConfig.logger.error('Could not find alphaTab, please ensure it is installed into node_modules or configure alphaTabSourceDir');
2558
- return;
2559
- }
2560
- const outputPath = (options.assetOutputDir ?? resolvedConfig.publicDir);
2561
- if (!outputPath) {
2562
- return;
2563
- }
2564
- async function copyFiles(subdir) {
2565
- const fullDir = path__namespace.join(alphaTabSourceDir, subdir);
2566
- const files = await fs__namespace.promises.readdir(fullDir, {
2567
- withFileTypes: true
2568
- });
2569
- await fs__namespace.promises.mkdir(path__namespace.join(outputPath, subdir), {
2570
- recursive: true
2571
- });
2572
- await Promise.all(files
2573
- .filter(f => f.isFile())
2574
- .map(async (file) => {
2575
- // node v20.12.0 has parentPath pointing to the path (not the file)
2576
- // see https://github.com/nodejs/node/pull/50976
2577
- const sourceFilename = path__namespace.join(file.parentPath ?? file.path, file.name);
2578
- await fs__namespace.promises.copyFile(sourceFilename, path__namespace.join(outputPath, subdir, file.name));
2579
- }));
2580
- }
2581
- await Promise.all([copyFiles('font'), copyFiles('soundfont')]);
2582
- }
2583
- };
2584
- }
2585
-
2586
- /**@target web */
2587
- const workerFileRE = new RegExp(`(?:\\?|&)${WORKER_FILE_ID}&type=(\\w+)(?:&|$)`);
2588
- const workerAssetUrlRE = new RegExp(`${WORKER_ASSET_ID}([a-z\\d]{8})__`, 'g');
2589
- function workerPlugin(options) {
2590
- let resolvedConfig;
2591
- let isBuild;
2592
- let isWorker;
2593
- const isWorkerActive = options.webWorkers !== false;
2594
- const isWorkletActive = options.audioWorklets !== false;
2595
- const isActive = isWorkerActive || isWorkletActive;
2596
- return {
2597
- name: 'vite-plugin-alphatab-worker',
2598
- configResolved(config) {
2599
- resolvedConfig = config;
2600
- isBuild = config.command === 'build';
2601
- isWorker = config.isWorker;
2602
- },
2603
- buildStart() {
2604
- if (!isActive || isWorker) {
2605
- return;
2606
- }
2607
- workerCache.set(resolvedConfig, {
2608
- assets: new Map(),
2609
- bundle: new Map(),
2610
- fileNameHash: new Map()
2611
- });
2612
- },
2613
- load(id) {
2614
- if (isActive && isBuild && id.includes(WORKER_FILE_ID)) {
2615
- return '';
2616
- }
2617
- return;
2618
- },
2619
- shouldTransformCachedModule({ id }) {
2620
- if (isActive && isBuild && resolvedConfig.build.watch && id.includes(WORKER_FILE_ID)) {
2621
- return true;
2622
- }
2623
- return;
2624
- },
2625
- async transform(raw, id) {
2626
- if (!isActive) {
2627
- return;
2628
- }
2629
- const match = workerFileRE.exec(id);
2630
- if (!match) {
2631
- return;
2632
- }
2633
- // inject env to worker file, might be needed by imported scripts
2634
- const envScriptPath = JSON.stringify(path__namespace.posix.join(resolvedConfig.base, ENV_PUBLIC_PATH));
2635
- const workerType = match[1];
2636
- let injectEnv = '';
2637
- switch (workerType) {
2638
- case AlphaTabWorkerTypes.WorkerClassic:
2639
- injectEnv = `importScripts(${envScriptPath})\n`;
2640
- break;
2641
- case AlphaTabWorkerTypes.WorkerModule:
2642
- case AlphaTabWorkerTypes.AudioWorklet:
2643
- injectEnv = `import ${envScriptPath}\n`;
2644
- break;
2645
- }
2646
- if (injectEnv) {
2647
- const s = new MagicString(raw);
2648
- s.prepend(injectEnv);
2649
- return {
2650
- code: s.toString(),
2651
- map: s.generateMap({ hires: 'boundary' })
2652
- };
2653
- }
2654
- return;
2655
- },
2656
- renderChunk(code, chunk, outputOptions) {
2657
- // when building the worker URLs are replaced with some placeholders
2658
- // here we replace those placeholders with the final file names respecting chunks
2659
- let s;
2660
- const result = () => {
2661
- return (s && {
2662
- code: s.toString(),
2663
- map: resolvedConfig.build.sourcemap ? s.generateMap({ hires: 'boundary' }) : null
2664
- });
2665
- };
2666
- workerAssetUrlRE.lastIndex = 0;
2667
- if (workerAssetUrlRE.test(code)) {
2668
- const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, resolvedConfig.isWorker);
2669
- s = new MagicString(code);
2670
- workerAssetUrlRE.lastIndex = 0;
2671
- // Replace "/" using relative paths
2672
- const workerMap = workerCache.get(resolvedConfig.mainConfig || resolvedConfig);
2673
- const { fileNameHash } = workerMap;
2674
- let match = workerAssetUrlRE.exec(code);
2675
- while (match) {
2676
- const [full, hash] = match;
2677
- const filename = fileNameHash.get(hash);
2678
- const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', resolvedConfig, toRelativeRuntime);
2679
- const replacementString = typeof replacement === 'string'
2680
- ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
2681
- : `"+${replacement.runtime}+"`;
2682
- s.update(match.index, match.index + full.length, replacementString);
2683
- match = workerAssetUrlRE.exec(code);
2684
- }
2685
- }
2686
- return result();
2687
- },
2688
- generateBundle(_, bundle) {
2689
- if (isWorker) {
2690
- return;
2691
- }
2692
- const workerMap = workerCache.get(resolvedConfig);
2693
- for (const asset of workerMap.assets.values()) {
2694
- const duplicateAsset = bundle[asset.fileName];
2695
- if (duplicateAsset) {
2696
- const content = duplicateAsset.type === 'asset' ? duplicateAsset.source : duplicateAsset.code;
2697
- // don't emit if the file name and the content is same
2698
- if (isSameContent(content, asset.source)) {
2699
- return;
2700
- }
2701
- }
2702
- this.emitFile({
2703
- type: 'asset',
2704
- fileName: asset.fileName,
2705
- source: asset.source
2706
- });
2707
- }
2708
- workerMap.assets.clear();
2709
- }
2710
- };
2711
- }
2712
-
2713
- /**@target web */
2714
- function alphaTab(options) {
2715
- const plugins = [];
2716
- options ?? (options = {});
2717
- plugins.push(importMetaUrlPlugin(options));
2718
- plugins.push(workerPlugin(options));
2719
- plugins.push(copyAssetsPlugin(options));
2720
- return plugins;
2721
- }
2722
-
2723
- exports.alphaTab = alphaTab;
1
+ const plugin = require('./alphaTab.vite.core.js');
2
+ console.warn('[alphaTab] The use of alphaTab.vite.js via @coderline/alphatab is deprecated. Please use the new @coderline/alphatab-vite npm package.');
3
+ module.exports = plugin;