@coderline/alphatab 1.2.2 → 1.3.0-alpha.1005

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 (36) hide show
  1. package/README.md +39 -32
  2. package/dist/alphaTab.core.min.mjs +2 -0
  3. package/dist/alphaTab.core.min.mjs.map +1 -0
  4. package/dist/alphaTab.core.mjs +45998 -0
  5. package/dist/alphaTab.core.mjs.map +1 -0
  6. package/dist/alphaTab.d.ts +7571 -6449
  7. package/dist/alphaTab.js +45614 -42133
  8. package/dist/alphaTab.js.map +1 -0
  9. package/dist/alphaTab.min.js +2 -17
  10. package/dist/alphaTab.min.js.map +1 -0
  11. package/dist/alphaTab.min.mjs +2 -0
  12. package/dist/alphaTab.min.mjs.map +1 -0
  13. package/dist/alphaTab.mjs +63 -0
  14. package/dist/alphaTab.mjs.map +1 -0
  15. package/dist/alphaTab.vite.d.ts +38 -0
  16. package/dist/alphaTab.vite.js +782 -0
  17. package/dist/alphaTab.vite.js.map +1 -0
  18. package/dist/alphaTab.vite.mjs +758 -0
  19. package/dist/alphaTab.vite.mjs.map +1 -0
  20. package/dist/alphaTab.webpack.d.ts +43 -0
  21. package/dist/alphaTab.webpack.js +478 -0
  22. package/dist/alphaTab.webpack.js.map +1 -0
  23. package/dist/alphaTab.webpack.mjs +453 -0
  24. package/dist/alphaTab.webpack.mjs.map +1 -0
  25. package/dist/alphaTab.worker.min.mjs +2 -0
  26. package/dist/alphaTab.worker.min.mjs.map +1 -0
  27. package/dist/alphaTab.worker.mjs +21 -0
  28. package/dist/alphaTab.worker.mjs.map +1 -0
  29. package/dist/alphaTab.worklet.min.mjs +2 -0
  30. package/dist/alphaTab.worklet.min.mjs.map +1 -0
  31. package/dist/alphaTab.worklet.mjs +21 -0
  32. package/dist/alphaTab.worklet.mjs.map +1 -0
  33. package/package.json +108 -82
  34. /package/dist/font/{FONTLOG.txt → Bravura-FONTLOG.txt} +0 -0
  35. /package/dist/font/{OFL-FAQ.txt → Bravura-OFL-FAQ.txt} +0 -0
  36. /package/dist/font/{OFL.txt → Bravura-OFL.txt} +0 -0
@@ -0,0 +1,758 @@
1
+ /**
2
+ * alphaTab v1.3.0-alpha.1005 (develop, build 1005)
3
+ *
4
+ * Copyright © 2024, 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
+ * SoundFont loading and Audio Synthesis based on TinySoundFont (licensed under MIT)
11
+ * Copyright (C) 2017, 2018 Bernhard Schelling (https://github.com/schellingb/TinySoundFont)
12
+ *
13
+ * TinySoundFont is based on SFZero (licensed under MIT)
14
+ * Copyright (C) 2012 Steve Folta (https://github.com/stevefolta/SFZero)
15
+ */
16
+
17
+ import MagicString from 'magic-string';
18
+ import * as path from 'path';
19
+ import path__default from 'path';
20
+ import * as fs from 'fs';
21
+ import { createHash } from 'node:crypto';
22
+ import { normalizePath } from 'vite';
23
+
24
+ /**@target web */
25
+ // index.ts for more details on contents and license of this file
26
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1302
27
+ function evalValue(rawValue) {
28
+ const fn = new Function(`
29
+ var console, exports, global, module, process, require
30
+ return (\n${rawValue}\n)
31
+ `);
32
+ return fn();
33
+ }
34
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L31-L34
35
+ const postfixRE = /[?#].*$/;
36
+ function cleanUrl(url) {
37
+ return url.replace(postfixRE, '');
38
+ }
39
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L393
40
+ function tryStatSync(file) {
41
+ try {
42
+ // The "throwIfNoEntry" is a performance optimization for cases where the file does not exist
43
+ return fs.statSync(file, { throwIfNoEntry: false });
44
+ }
45
+ catch {
46
+ // Ignore errors
47
+ }
48
+ return;
49
+ }
50
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1030
51
+ function getHash(text, length = 8) {
52
+ const h = createHash('sha256').update(text).digest('hex').substring(0, length);
53
+ if (length <= 64)
54
+ return h;
55
+ return h.padEnd(length, '_');
56
+ }
57
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/shared/utils.ts#L40
58
+ function withTrailingSlash(path) {
59
+ if (path[path.length - 1] !== '/') {
60
+ return `${path}/`;
61
+ }
62
+ return path;
63
+ }
64
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1268
65
+ function joinUrlSegments(a, b) {
66
+ if (!a || !b) {
67
+ return a || b || '';
68
+ }
69
+ if (a[a.length - 1] === '/') {
70
+ a = a.substring(0, a.length - 1);
71
+ }
72
+ if (b[0] !== '/') {
73
+ b = '/' + b;
74
+ }
75
+ return a + b;
76
+ }
77
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1281
78
+ function removeLeadingSlash(str) {
79
+ return str[0] === '/' ? str.slice(1) : str;
80
+ }
81
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L319
82
+ function injectQuery(builtUrl, query) {
83
+ const queryIndex = builtUrl.indexOf('?');
84
+ return builtUrl + (queryIndex === -1 ? '?' : '&') + query;
85
+ }
86
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1435
87
+ function partialEncodeURIPath(uri) {
88
+ if (uri.startsWith('data:'))
89
+ return uri;
90
+ const filePath = cleanUrl(uri);
91
+ const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
92
+ return filePath.replaceAll('%', '%25') + postfix;
93
+ }
94
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/utils.ts#L1424
95
+ function encodeURIPath(uri) {
96
+ if (uri.startsWith('data:'))
97
+ return uri;
98
+ const filePath = cleanUrl(uri);
99
+ const postfix = filePath !== uri ? uri.slice(filePath.length) : '';
100
+ return encodeURI(filePath) + postfix;
101
+ }
102
+
103
+ /**@target web */
104
+ const FS_PREFIX = `/@fs/`;
105
+ async function fileToUrl(id, config) {
106
+ let rtn;
107
+ if (id.startsWith(withTrailingSlash(config.root))) {
108
+ // in project root, infer short public path
109
+ rtn = '/' + path.posix.relative(config.root, id);
110
+ }
111
+ else {
112
+ // outside of project root, use absolute fs path
113
+ // (this is special handled by the serve static middleware
114
+ rtn = path.posix.join(FS_PREFIX, id);
115
+ }
116
+ const base = joinUrlSegments(config.server?.origin ?? '', config.base);
117
+ return joinUrlSegments(base, removeLeadingSlash(rtn));
118
+ }
119
+
120
+ /**@target web */
121
+ const needsEscapeRegEx = /[\n\r'\\\u2028\u2029]/;
122
+ const quoteNewlineRegEx = /([\n\r'\u2028\u2029])/g;
123
+ const backSlashRegEx = /\\/g;
124
+ function escapeId(id) {
125
+ if (!needsEscapeRegEx.test(id))
126
+ return id;
127
+ return id.replace(backSlashRegEx, '\\\\').replace(quoteNewlineRegEx, '\\$1');
128
+ }
129
+ const getResolveUrl = (path, URL = 'URL') => `new ${URL}(${path}).href`;
130
+ const getRelativeUrlFromDocument = (relativePath, umd = false) => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', ${umd ? `typeof document === 'undefined' ? location.href : ` : ''}document.currentScript && document.currentScript.src || document.baseURI`);
131
+ const getFileUrlFromFullPath = (path) => `require('u' + 'rl').pathToFileURL(${path}).href`;
132
+ const getFileUrlFromRelativePath = (path) => getFileUrlFromFullPath(`__dirname + '/${escapeId(path)}'`);
133
+ const relativeUrlMechanisms = {
134
+ amd: relativePath => {
135
+ if (relativePath[0] !== '.')
136
+ relativePath = './' + relativePath;
137
+ return getResolveUrl(`require.toUrl('${escapeId(relativePath)}'), document.baseURI`);
138
+ },
139
+ cjs: relativePath => `(typeof document === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath)})`,
140
+ es: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', import.meta.url`),
141
+ iife: relativePath => getRelativeUrlFromDocument(relativePath),
142
+ // NOTE: make sure rollup generate `module` params
143
+ system: relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', module.meta.url`),
144
+ umd: relativePath => `(typeof document === 'undefined' && typeof location === 'undefined' ? ${getFileUrlFromRelativePath(relativePath)} : ${getRelativeUrlFromDocument(relativePath, true)})`
145
+ };
146
+ const customRelativeUrlMechanisms = {
147
+ ...relativeUrlMechanisms,
148
+ 'worker-iife': relativePath => getResolveUrl(`'${escapeId(partialEncodeURIPath(relativePath))}', self.location.href`)
149
+ };
150
+ function createToImportMetaURLBasedRelativeRuntime(format, isWorker) {
151
+ const formatLong = isWorker && format === 'iife' ? 'worker-iife' : format;
152
+ const toRelativePath = customRelativeUrlMechanisms[formatLong];
153
+ return (filename, importer) => ({
154
+ runtime: toRelativePath(path.posix.relative(path.dirname(importer), filename))
155
+ });
156
+ }
157
+ function toOutputFilePathInJS(filename, type, hostId, hostType, config, toRelative) {
158
+ const { renderBuiltUrl } = config.experimental;
159
+ let relative = config.base === '' || config.base === './';
160
+ if (renderBuiltUrl) {
161
+ const result = renderBuiltUrl(filename, {
162
+ hostId,
163
+ hostType,
164
+ type,
165
+ ssr: !!config.build.ssr
166
+ });
167
+ if (typeof result === 'object') {
168
+ if (result.runtime) {
169
+ return { runtime: result.runtime };
170
+ }
171
+ if (typeof result.relative === 'boolean') {
172
+ relative = result.relative;
173
+ }
174
+ }
175
+ else if (result) {
176
+ return result;
177
+ }
178
+ }
179
+ if (relative && !config.build.ssr) {
180
+ return toRelative(filename, hostId);
181
+ }
182
+ return joinUrlSegments(config.base, filename);
183
+ }
184
+
185
+ /**@target web */
186
+ // index.ts for more details on contents and license of this file
187
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L143
188
+ const METADATA_FILENAME = '_metadata.json';
189
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/constants.ts#L63
190
+ const ENV_PUBLIC_PATH = `/@vite/env`;
191
+
192
+ /**@target web */
193
+ // index.ts for more details on contents and license of this file
194
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/fsUtils.ts#L388
195
+ function tryResolveRealFile(file, preserveSymlinks) {
196
+ const fileStat = tryStatSync(file);
197
+ if (fileStat?.isFile()) {
198
+ return file;
199
+ }
200
+ else if (fileStat?.isSymbolicLink()) {
201
+ return preserveSymlinks ? file : fs.realpathSync(file);
202
+ }
203
+ return undefined;
204
+ }
205
+
206
+ /**@target web */
207
+ // index.ts for more details on contents and license of this file
208
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L534
209
+ function splitFileAndPostfix(path) {
210
+ const file = cleanUrl(path);
211
+ return { file, postfix: path.slice(file.length) };
212
+ }
213
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L566-L574
214
+ function tryFsResolve(fsPath, preserveSymlinks) {
215
+ const { file, postfix } = splitFileAndPostfix(fsPath);
216
+ const res = tryCleanFsResolve(file, preserveSymlinks);
217
+ if (res)
218
+ return res + postfix;
219
+ return;
220
+ }
221
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/resolve.ts#L580
222
+ function tryCleanFsResolve(file, preserveSymlinks) {
223
+ if (file.includes('node_modules')) {
224
+ return tryResolveRealFile(file, preserveSymlinks);
225
+ }
226
+ const normalizedResolved = tryResolveRealFile(normalizePath(file));
227
+ if (!normalizedResolved) {
228
+ return tryResolveRealFile(file, preserveSymlinks);
229
+ }
230
+ return normalizedResolved;
231
+ }
232
+
233
+ /**@target web */
234
+ // index.ts for more details on contents and license of this file
235
+ // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/index.ts#L1356
236
+ function tryOptimizedDepResolve(config, ssr, url, depId, preserveSymlinks) {
237
+ const optimizer = getDepsOptimizer(config, ssr);
238
+ if (optimizer?.isOptimizedDepFile(depId)) {
239
+ const depFile = cleanUrl(depId);
240
+ const info = optimizedDepInfoFromFile(optimizer.metadata, depFile);
241
+ const depSrc = info?.src;
242
+ if (depSrc) {
243
+ const resolvedFile = path.resolve(path.dirname(depSrc), url);
244
+ return tryFsResolve(resolvedFile, preserveSymlinks);
245
+ }
246
+ }
247
+ return undefined;
248
+ }
249
+ // https://github.com/Danielku15/vite/blob/88b7def341f12d07d7d4f83cbe3dc73cc8c6b7be/packages/vite/src/node/optimizer/optimizer.ts#L32-L40
250
+ const depsOptimizerMap = new WeakMap();
251
+ const devSsrDepsOptimizerMap = new WeakMap();
252
+ function getDepsOptimizer(config, ssr) {
253
+ const map = ssr ? devSsrDepsOptimizerMap : depsOptimizerMap;
254
+ let optimizer = map.get(config);
255
+ if (!optimizer) {
256
+ optimizer = createDepsOptimizer(config);
257
+ map.set(config, optimizer);
258
+ }
259
+ return optimizer;
260
+ }
261
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/optimizer.ts#L79
262
+ function createDepsOptimizer(config) {
263
+ const depsCacheDirPrefix = normalizePath(path.resolve(config.cacheDir, 'deps'));
264
+ const metadata = parseDepsOptimizerMetadata(fs.readFileSync(path.join(depsCacheDirPrefix, METADATA_FILENAME), 'utf8'), depsCacheDirPrefix);
265
+ const notImplemented = () => {
266
+ throw new Error('not implemented');
267
+ };
268
+ const depsOptimizer = {
269
+ metadata,
270
+ registerMissingImport: notImplemented,
271
+ run: notImplemented,
272
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L916
273
+ isOptimizedDepFile: id => id.startsWith(depsCacheDirPrefix),
274
+ isOptimizedDepUrl: notImplemented,
275
+ getOptimizedDepId: notImplemented,
276
+ close: notImplemented,
277
+ options: {}
278
+ };
279
+ return depsOptimizer;
280
+ }
281
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L944
282
+ function parseDepsOptimizerMetadata(jsonMetadata, depsCacheDir) {
283
+ const { hash, lockfileHash, configHash, browserHash, optimized, chunks } = JSON.parse(jsonMetadata, (key, value) => {
284
+ if (key === 'file' || key === 'src') {
285
+ return normalizePath(path.resolve(depsCacheDir, value));
286
+ }
287
+ return value;
288
+ });
289
+ if (!chunks || Object.values(optimized).some(depInfo => !depInfo.fileHash)) {
290
+ // outdated _metadata.json version, ignore
291
+ return;
292
+ }
293
+ const metadata = {
294
+ hash,
295
+ lockfileHash,
296
+ configHash,
297
+ browserHash,
298
+ optimized: {},
299
+ discovered: {},
300
+ chunks: {},
301
+ depInfoList: []
302
+ };
303
+ for (const id of Object.keys(optimized)) {
304
+ addOptimizedDepInfo(metadata, 'optimized', {
305
+ ...optimized[id],
306
+ id,
307
+ browserHash
308
+ });
309
+ }
310
+ for (const id of Object.keys(chunks)) {
311
+ addOptimizedDepInfo(metadata, 'chunks', {
312
+ ...chunks[id],
313
+ id,
314
+ browserHash,
315
+ needsInterop: false
316
+ });
317
+ }
318
+ return metadata;
319
+ }
320
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L322
321
+ function addOptimizedDepInfo(metadata, type, depInfo) {
322
+ metadata[type][depInfo.id] = depInfo;
323
+ metadata.depInfoList.push(depInfo);
324
+ return depInfo;
325
+ }
326
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/optimizer/index.ts#L1248
327
+ function optimizedDepInfoFromFile(metadata, file) {
328
+ return metadata.depInfoList.find(depInfo => depInfo.file === file);
329
+ }
330
+
331
+ /**@target web */
332
+ const workerCache = new WeakMap();
333
+ const WORKER_FILE_ID = 'alphatab_worker';
334
+ const WORKER_ASSET_ID = '__ALPHATAB_WORKER_ASSET__';
335
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L47
336
+ function saveEmitWorkerAsset(config, asset) {
337
+ const workerMap = workerCache.get(config.mainConfig || config);
338
+ workerMap.assets.set(asset.fileName, asset);
339
+ }
340
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L161
341
+ async function workerFileToUrl(config, id) {
342
+ const workerMap = workerCache.get(config.mainConfig || config);
343
+ let fileName = workerMap.bundle.get(id);
344
+ if (!fileName) {
345
+ const outputChunk = await bundleWorkerEntry(config, id);
346
+ fileName = outputChunk.fileName;
347
+ saveEmitWorkerAsset(config, {
348
+ fileName,
349
+ source: outputChunk.code
350
+ });
351
+ workerMap.bundle.set(id, fileName);
352
+ }
353
+ return encodeWorkerAssetFileName(fileName, workerMap);
354
+ }
355
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L149
356
+ function encodeWorkerAssetFileName(fileName, workerCache) {
357
+ const { fileNameHash } = workerCache;
358
+ const hash = getHash(fileName);
359
+ if (!fileNameHash.get(hash)) {
360
+ fileNameHash.set(hash, fileName);
361
+ }
362
+ return `${WORKER_ASSET_ID}${hash}__`;
363
+ }
364
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L55
365
+ async function bundleWorkerEntry(config, id) {
366
+ const input = cleanUrl(id);
367
+ const bundleChain = config.bundleChain ?? [];
368
+ const newBundleChain = [...bundleChain, input];
369
+ if (bundleChain.includes(input)) {
370
+ throw new Error('Circular worker imports detected. Vite does not support it. ' +
371
+ `Import chain: ${newBundleChain.join(' -> ')}`);
372
+ }
373
+ // bundle the file as entry to support imports
374
+ const { rollup } = await import('rollup');
375
+ const { plugins, rollupOptions, format } = config.worker;
376
+ const bundle = await rollup({
377
+ ...rollupOptions,
378
+ input,
379
+ plugins: await plugins(newBundleChain),
380
+ preserveEntrySignatures: false
381
+ });
382
+ let chunk;
383
+ try {
384
+ const workerOutputConfig = config.worker.rollupOptions.output;
385
+ const workerConfig = workerOutputConfig
386
+ ? Array.isArray(workerOutputConfig)
387
+ ? workerOutputConfig[0] || {}
388
+ : workerOutputConfig
389
+ : {};
390
+ const { output: [outputChunk, ...outputChunks] } = await bundle.generate({
391
+ entryFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].js'),
392
+ chunkFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].js'),
393
+ assetFileNames: path.posix.join(config.build.assetsDir, '[name]-[hash].[ext]'),
394
+ ...workerConfig,
395
+ format,
396
+ sourcemap: config.build.sourcemap
397
+ });
398
+ chunk = outputChunk;
399
+ outputChunks.forEach(outputChunk => {
400
+ if (outputChunk.type === 'asset') {
401
+ saveEmitWorkerAsset(config, outputChunk);
402
+ }
403
+ else if (outputChunk.type === 'chunk') {
404
+ saveEmitWorkerAsset(config, {
405
+ fileName: outputChunk.fileName,
406
+ source: outputChunk.code
407
+ });
408
+ }
409
+ });
410
+ }
411
+ finally {
412
+ await bundle.close();
413
+ }
414
+ return emitSourcemapForWorkerEntry(config, chunk);
415
+ }
416
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L124
417
+ function emitSourcemapForWorkerEntry(config, chunk) {
418
+ const { map: sourcemap } = chunk;
419
+ if (sourcemap) {
420
+ if (config.build.sourcemap === 'hidden' || config.build.sourcemap === true) {
421
+ const data = sourcemap.toString();
422
+ const mapFileName = chunk.fileName + '.map';
423
+ saveEmitWorkerAsset(config, {
424
+ fileName: mapFileName,
425
+ source: data
426
+ });
427
+ }
428
+ }
429
+ return chunk;
430
+ }
431
+ // https://github.com/vitejs/vite/blob/b7ddfae5f852c2948fab03e94751ce56f5f31ce0/packages/vite/src/node/plugins/worker.ts#L458
432
+ function isSameContent(a, b) {
433
+ if (typeof a === 'string') {
434
+ if (typeof b === 'string') {
435
+ return a === b;
436
+ }
437
+ return Buffer.from(a).equals(b);
438
+ }
439
+ return Buffer.from(b).equals(a);
440
+ }
441
+
442
+ /**@target web */
443
+ const alphaTabWorkerPatterns = [
444
+ ['alphaTabWorker', 'new URL', 'import.meta.url'],
445
+ ['alphaTabWorklet.addModule', 'new URL', 'import.meta.url']
446
+ ];
447
+ function includesAlphaTabWorker(code) {
448
+ for (const pattern of alphaTabWorkerPatterns) {
449
+ let position = 0;
450
+ for (const match of pattern) {
451
+ position = code.indexOf(match, position);
452
+ if (position === -1) {
453
+ break;
454
+ }
455
+ }
456
+ if (position !== -1) {
457
+ return true;
458
+ }
459
+ }
460
+ return false;
461
+ }
462
+ function getWorkerType(code, match) {
463
+ if (match[1].includes('.addModule')) {
464
+ return "audio_worklet" /* AlphaTabWorkerTypes.AudioWorklet */;
465
+ }
466
+ const endOfMatch = match.indices[0][1];
467
+ const startOfOptions = code.indexOf('{', endOfMatch);
468
+ if (startOfOptions === -1) {
469
+ return "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */;
470
+ }
471
+ const endOfOptions = code.indexOf('}', endOfMatch);
472
+ if (endOfOptions === -1) {
473
+ return "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */;
474
+ }
475
+ const endOfWorkerCreate = code.indexOf(')', endOfMatch);
476
+ if (startOfOptions > endOfWorkerCreate || endOfOptions > endOfWorkerCreate) {
477
+ return "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */;
478
+ }
479
+ let workerOptions = code.slice(startOfOptions, endOfOptions + 1);
480
+ try {
481
+ workerOptions = evalValue(workerOptions);
482
+ }
483
+ catch (e) {
484
+ return "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */;
485
+ }
486
+ if (typeof workerOptions === 'object' && workerOptions?.type === 'module') {
487
+ return "worker_module" /* AlphaTabWorkerTypes.WorkerModule */;
488
+ }
489
+ return "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */;
490
+ }
491
+ function importMetaUrlPlugin(options) {
492
+ let resolvedConfig;
493
+ let isBuild;
494
+ let preserveSymlinks;
495
+ const isWorkerActive = options.webWorkers !== false;
496
+ const isWorkletActive = options.audioWorklets !== false;
497
+ const isActive = isWorkerActive || isWorkletActive;
498
+ return {
499
+ name: 'vite-plugin-alphatab-url',
500
+ enforce: 'pre',
501
+ configResolved(config) {
502
+ resolvedConfig = config;
503
+ isBuild = config.command === 'build';
504
+ preserveSymlinks = config.resolve.preserveSymlinks;
505
+ },
506
+ shouldTransformCachedModule({ code }) {
507
+ if (isActive && isBuild && resolvedConfig.build.watch && includesAlphaTabWorker(code)) {
508
+ return true;
509
+ }
510
+ return;
511
+ },
512
+ async transform(code, id, options) {
513
+ if (!isActive || options?.ssr || !includesAlphaTabWorker(code)) {
514
+ return;
515
+ }
516
+ let s;
517
+ const alphaTabWorkerPattern = /\b(alphaTabWorker|alphaTabWorklet\.addModule)\s*\(\s*(new\s+URL\s*\(\s*('[^']+'|"[^"]+"|`[^`]+`)\s*,\s*import\.meta\.url\s*\))/dg;
518
+ let match;
519
+ while ((match = alphaTabWorkerPattern.exec(code))) {
520
+ const workerType = getWorkerType(code, match);
521
+ let typeActive = false;
522
+ switch (workerType) {
523
+ case "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */:
524
+ case "worker_module" /* AlphaTabWorkerTypes.WorkerModule */:
525
+ typeActive = isWorkerActive;
526
+ break;
527
+ case "audio_worklet" /* AlphaTabWorkerTypes.AudioWorklet */:
528
+ typeActive = isWorkletActive;
529
+ break;
530
+ }
531
+ if (!typeActive) {
532
+ continue;
533
+ }
534
+ s ?? (s = new MagicString(code));
535
+ const url = code.slice(match.indices[3][0] + 1, match.indices[3][1] - 1);
536
+ let file = path__default.resolve(path__default.dirname(id), url);
537
+ file =
538
+ tryFsResolve(file, preserveSymlinks) ??
539
+ tryOptimizedDepResolve(resolvedConfig, options?.ssr === true, url, id, preserveSymlinks) ??
540
+ file;
541
+ let builtUrl;
542
+ if (isBuild) {
543
+ builtUrl = await workerFileToUrl(resolvedConfig, file);
544
+ }
545
+ else {
546
+ builtUrl = await fileToUrl(cleanUrl(file), resolvedConfig);
547
+ builtUrl = injectQuery(builtUrl, `${WORKER_FILE_ID}&type=${workerType}`);
548
+ }
549
+ s.update(match.indices[3][0], match.indices[3][1],
550
+ // add `'' +` to skip vite:asset-import-meta-url plugin
551
+ `new URL('' + ${JSON.stringify(builtUrl)}, import.meta.url)`);
552
+ }
553
+ if (s) {
554
+ return {
555
+ code: s.toString(),
556
+ map: resolvedConfig.command === 'build' && resolvedConfig.build.sourcemap
557
+ ? s.generateMap({ hires: 'boundary', source: id })
558
+ : null
559
+ };
560
+ }
561
+ return null;
562
+ }
563
+ };
564
+ }
565
+
566
+ /**@target web */
567
+ function copyAssetsPlugin(options) {
568
+ let resolvedConfig;
569
+ let output = false;
570
+ return {
571
+ name: 'vite-plugin-alphatab-copy',
572
+ enforce: 'pre',
573
+ configResolved(config) {
574
+ resolvedConfig = config;
575
+ },
576
+ buildEnd() {
577
+ // reset for watch mode
578
+ output = false;
579
+ },
580
+ async buildStart() {
581
+ // run copy only once even if multiple bundles are generated
582
+ if (output) {
583
+ return;
584
+ }
585
+ output = true;
586
+ let alphaTabSourceDir = options.alphaTabSourceDir;
587
+ if (!alphaTabSourceDir) {
588
+ alphaTabSourceDir = path.join(resolvedConfig.root, 'node_modules/@coderline/alphatab/dist/');
589
+ }
590
+ if (!alphaTabSourceDir ||
591
+ !fs.promises.access(path.join(alphaTabSourceDir, 'alphaTab.mjs'), fs.constants.F_OK)) {
592
+ resolvedConfig.logger.error('Could not find alphaTab, please ensure it is installed into node_modules or configure alphaTabSourceDir');
593
+ return;
594
+ }
595
+ const outputPath = (options.assetOutputDir ?? resolvedConfig.publicDir);
596
+ if (!outputPath) {
597
+ return;
598
+ }
599
+ async function copyFiles(subdir) {
600
+ const fullDir = path.join(alphaTabSourceDir, subdir);
601
+ const files = await fs.promises.readdir(fullDir, {
602
+ withFileTypes: true
603
+ });
604
+ await fs.promises.mkdir(path.join(outputPath, subdir), {
605
+ recursive: true
606
+ });
607
+ await Promise.all(files
608
+ .filter(f => f.isFile())
609
+ .map(async (file) => {
610
+ const sourceFilename = path.join(file.path, file.name);
611
+ await fs.promises.copyFile(sourceFilename, path.join(outputPath, subdir, file.name));
612
+ }));
613
+ }
614
+ await Promise.all([copyFiles('font'), copyFiles('soundfont')]);
615
+ }
616
+ };
617
+ }
618
+
619
+ /**@target web */
620
+ const workerFileRE = new RegExp(`(?:\\?|&)${WORKER_FILE_ID}&type=(\\w+)(?:&|$)`);
621
+ const workerAssetUrlRE = new RegExp(`${WORKER_ASSET_ID}([a-z\\d]{8})__`, 'g');
622
+ function workerPlugin(options) {
623
+ let resolvedConfig;
624
+ let isBuild;
625
+ let isWorker;
626
+ const isWorkerActive = options.webWorkers !== false;
627
+ const isWorkletActive = options.audioWorklets !== false;
628
+ const isActive = isWorkerActive || isWorkletActive;
629
+ return {
630
+ name: 'vite-plugin-alphatab-worker',
631
+ configResolved(config) {
632
+ resolvedConfig = config;
633
+ isBuild = config.command === 'build';
634
+ isWorker = config.isWorker;
635
+ },
636
+ buildStart() {
637
+ if (!isActive || isWorker) {
638
+ return;
639
+ }
640
+ workerCache.set(resolvedConfig, {
641
+ assets: new Map(),
642
+ bundle: new Map(),
643
+ fileNameHash: new Map()
644
+ });
645
+ },
646
+ load(id) {
647
+ if (isActive && isBuild && id.includes(WORKER_FILE_ID)) {
648
+ return '';
649
+ }
650
+ return;
651
+ },
652
+ shouldTransformCachedModule({ id }) {
653
+ if (isActive && isBuild && resolvedConfig.build.watch && id.includes(WORKER_FILE_ID)) {
654
+ return true;
655
+ }
656
+ return;
657
+ },
658
+ async transform(raw, id) {
659
+ if (!isActive) {
660
+ return;
661
+ }
662
+ const match = workerFileRE.exec(id);
663
+ if (!match) {
664
+ return;
665
+ }
666
+ // inject env to worker file, might be needed by imported scripts
667
+ const envScriptPath = JSON.stringify(path.posix.join(resolvedConfig.base, ENV_PUBLIC_PATH));
668
+ const workerType = match[1];
669
+ let injectEnv = '';
670
+ switch (workerType) {
671
+ case "worker_classic" /* AlphaTabWorkerTypes.WorkerClassic */:
672
+ injectEnv = `importScripts(${envScriptPath})\n`;
673
+ break;
674
+ case "worker_module" /* AlphaTabWorkerTypes.WorkerModule */:
675
+ case "audio_worklet" /* AlphaTabWorkerTypes.AudioWorklet */:
676
+ injectEnv = `import ${envScriptPath}\n`;
677
+ break;
678
+ }
679
+ if (injectEnv) {
680
+ const s = new MagicString(raw);
681
+ s.prepend(injectEnv);
682
+ return {
683
+ code: s.toString(),
684
+ map: s.generateMap({ hires: 'boundary' })
685
+ };
686
+ }
687
+ return;
688
+ },
689
+ renderChunk(code, chunk, outputOptions) {
690
+ // when building the worker URLs are replaced with some placeholders
691
+ // here we replace those placeholders with the final file names respecting chunks
692
+ let s;
693
+ const result = () => {
694
+ return (s && {
695
+ code: s.toString(),
696
+ map: resolvedConfig.build.sourcemap ? s.generateMap({ hires: 'boundary' }) : null
697
+ });
698
+ };
699
+ workerAssetUrlRE.lastIndex = 0;
700
+ if (workerAssetUrlRE.test(code)) {
701
+ const toRelativeRuntime = createToImportMetaURLBasedRelativeRuntime(outputOptions.format, resolvedConfig.isWorker);
702
+ let match;
703
+ s = new MagicString(code);
704
+ workerAssetUrlRE.lastIndex = 0;
705
+ // Replace "__VITE_WORKER_ASSET__5aa0ddc0__" using relative paths
706
+ const workerMap = workerCache.get(resolvedConfig.mainConfig || resolvedConfig);
707
+ const { fileNameHash } = workerMap;
708
+ while ((match = workerAssetUrlRE.exec(code))) {
709
+ const [full, hash] = match;
710
+ const filename = fileNameHash.get(hash);
711
+ const replacement = toOutputFilePathInJS(filename, 'asset', chunk.fileName, 'js', resolvedConfig, toRelativeRuntime);
712
+ const replacementString = typeof replacement === 'string'
713
+ ? JSON.stringify(encodeURIPath(replacement)).slice(1, -1)
714
+ : `"+${replacement.runtime}+"`;
715
+ s.update(match.index, match.index + full.length, replacementString);
716
+ }
717
+ }
718
+ return result();
719
+ },
720
+ generateBundle(_, bundle) {
721
+ if (isWorker) {
722
+ return;
723
+ }
724
+ const workerMap = workerCache.get(resolvedConfig);
725
+ workerMap.assets.forEach(asset => {
726
+ const duplicateAsset = bundle[asset.fileName];
727
+ if (duplicateAsset) {
728
+ const content = duplicateAsset.type === 'asset' ? duplicateAsset.source : duplicateAsset.code;
729
+ // don't emit if the file name and the content is same
730
+ if (isSameContent(content, asset.source)) {
731
+ return;
732
+ }
733
+ }
734
+ this.emitFile({
735
+ type: 'asset',
736
+ fileName: asset.fileName,
737
+ source: asset.source
738
+ });
739
+ });
740
+ workerMap.assets.clear();
741
+ }
742
+ };
743
+ }
744
+
745
+ /**@target web */
746
+ function alphaTab(options) {
747
+ const plugins = [];
748
+ options ?? (options = {});
749
+ plugins.push(importMetaUrlPlugin(options));
750
+ plugins.push(workerPlugin(options));
751
+ plugins.push(copyAssetsPlugin(options));
752
+ return plugins;
753
+ }
754
+
755
+ /**@target web */
756
+
757
+ export { alphaTab, alphaTab as default };
758
+ //# sourceMappingURL=alphaTab.vite.mjs.map