taglib-wasm 2.4.0 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/LICENSE +0 -29
  2. package/NOTICE +35 -0
  3. package/README.md +42 -36
  4. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/assertClassBrand.js +1 -1
  5. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/checkPrivateRedeclaration.js +1 -1
  6. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/classPrivateFieldGet2.js +1 -1
  7. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/classPrivateFieldInitSpec.js +1 -1
  8. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/classPrivateFieldSet2.js +1 -1
  9. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/defineProperty.js +1 -1
  10. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPrimitive.js +1 -1
  11. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/toPropertyKey.js +1 -1
  12. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/typeof.js +1 -1
  13. package/dist/_virtual/{_@oxc-project_runtime@0.152.0 → _@oxc-project_runtime@0.154.0}/helpers/esm/usingCtx.js +1 -1
  14. package/dist/bwf/bext.d.ts.map +1 -1
  15. package/dist/bwf/bext.js +25 -16
  16. package/dist/constants/complex-properties.d.ts.map +1 -1
  17. package/dist/constants/general-extended-properties.d.ts +2 -1
  18. package/dist/constants/general-extended-properties.d.ts.map +1 -1
  19. package/dist/constants/general-extended-properties.js +5 -2
  20. package/dist/constants/properties.js +4 -2
  21. package/dist/constants/specialized-properties.d.ts +14 -0
  22. package/dist/constants/specialized-properties.d.ts.map +1 -1
  23. package/dist/constants/specialized-properties.js +21 -0
  24. package/dist/disc-folder.js +79 -45
  25. package/dist/folder-api/album-corroborate.d.ts.map +1 -1
  26. package/dist/folder-api/album-corroborate.js +25 -11
  27. package/dist/folder-api/album-discs.d.ts.map +1 -1
  28. package/dist/folder-api/album-discs.js +2 -5
  29. package/dist/folder-api/album-grouping.d.ts.map +1 -1
  30. package/dist/folder-api/album-grouping.js +27 -15
  31. package/dist/folder-api/album-identity.js +1 -1
  32. package/dist/folder-api/folder-disc.d.ts.map +1 -1
  33. package/dist/folder-api/folder-disc.js +24 -13
  34. package/dist/index.browser.d.ts +1 -1
  35. package/dist/index.browser.d.ts.map +1 -1
  36. package/dist/index.browser.js +2 -4453
  37. package/dist/index.d.ts +1 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/msgpack/encoder.d.ts.map +1 -1
  40. package/dist/msgpack/encoder.js +3 -1
  41. package/dist/rating.js +1 -2
  42. package/dist/runtime/module-loader.d.ts.map +1 -1
  43. package/dist/runtime/module-loader.js +43 -33
  44. package/dist/runtime/platform-io.d.ts.map +1 -1
  45. package/dist/runtime/platform-io.js +4 -2
  46. package/dist/runtime/unified-loader/module-loading.d.ts.map +1 -1
  47. package/dist/runtime/unified-loader/module-loading.js +3 -2
  48. package/dist/runtime/wasi-adapter/adapter.js +1 -1
  49. package/dist/runtime/wasi-adapter/audio-properties.d.ts.map +1 -1
  50. package/dist/runtime/wasi-adapter/audio-properties.js +8 -2
  51. package/dist/runtime/wasi-adapter/file-handle.d.ts +3 -1
  52. package/dist/runtime/wasi-adapter/file-handle.d.ts.map +1 -1
  53. package/dist/runtime/wasi-adapter/file-handle.js +17 -5
  54. package/dist/runtime/wasi-adapter/handle-state.d.ts.map +1 -1
  55. package/dist/runtime/wasi-adapter/handle-state.js +7 -1
  56. package/dist/runtime/wasi-adapter/index.js +1 -2
  57. package/dist/runtime/wasi-adapter/mp4-items.d.ts +24 -0
  58. package/dist/runtime/wasi-adapter/mp4-items.d.ts.map +1 -1
  59. package/dist/runtime/wasi-adapter/mp4-items.js +119 -2
  60. package/dist/runtime/wasi-adapter/property-surface.d.ts.map +1 -1
  61. package/dist/runtime/wasi-adapter/property-surface.js +15 -6
  62. package/dist/runtime/wasi-adapter/structured-fields.js +1 -1
  63. package/dist/runtime/wasi-adapter/tag-keys.d.ts.map +1 -1
  64. package/dist/runtime/wasi-adapter/tag-keys.js +3 -1
  65. package/dist/runtime/wasi-adapter/wasm-io.d.ts.map +1 -1
  66. package/dist/runtime/wasi-adapter/wasm-io.js +1 -1
  67. package/dist/runtime/wasi-memory.js +3 -3
  68. package/dist/simple/batch-operations.d.ts.map +1 -1
  69. package/dist/simple/batch-operations.js +5 -1
  70. package/dist/simple/picture-operations.d.ts +6 -0
  71. package/dist/simple/picture-operations.d.ts.map +1 -1
  72. package/dist/simple/picture-operations.js +6 -0
  73. package/dist/simple/tag-operations.d.ts +7 -0
  74. package/dist/simple/tag-operations.d.ts.map +1 -1
  75. package/dist/simple/tag-operations.js +7 -0
  76. package/dist/simple/with-audio-file.d.ts.map +1 -1
  77. package/dist/simple/with-audio-file.js +2 -1
  78. package/dist/simple.browser.js +2 -3670
  79. package/dist/taglib/audio-file-base.d.ts +35 -1
  80. package/dist/taglib/audio-file-base.d.ts.map +1 -1
  81. package/dist/taglib/audio-file-base.js +91 -21
  82. package/dist/taglib/audio-file-checksum.d.ts.map +1 -1
  83. package/dist/taglib/audio-file-checksum.js +17 -13
  84. package/dist/taglib/audio-file-impl.d.ts.map +1 -1
  85. package/dist/taglib/audio-file-impl.js +1 -1
  86. package/dist/taglib/audio-file-interface.d.ts +18 -1
  87. package/dist/taglib/audio-file-interface.d.ts.map +1 -1
  88. package/dist/taglib/embind-adapter.d.ts +3 -0
  89. package/dist/taglib/embind-adapter.d.ts.map +1 -1
  90. package/dist/taglib/embind-adapter.js +6 -0
  91. package/dist/taglib/extra-state-registry.d.ts.map +1 -1
  92. package/dist/taglib/extra-state-registry.js +15 -0
  93. package/dist/taglib/load-audio-data.d.ts +11 -8
  94. package/dist/taglib/load-audio-data.d.ts.map +1 -1
  95. package/dist/taglib/load-audio-data.js +39 -43
  96. package/dist/taglib/metadata-extent.d.ts.map +1 -1
  97. package/dist/taglib/metadata-extent.js +59 -32
  98. package/dist/taglib/mutable-tag-impl.d.ts.map +1 -1
  99. package/dist/taglib/mutable-tag-impl.js +72 -69
  100. package/dist/taglib/taglib-class.d.ts.map +1 -1
  101. package/dist/taglib/taglib-class.js +16 -6
  102. package/dist/taglib-wasi.wasm +0 -0
  103. package/dist/taglib-web.wasm +0 -0
  104. package/dist/taglib-wrapper.js +1 -1
  105. package/dist/types/metadata-mappings.d.ts.map +1 -1
  106. package/dist/types/metadata-mappings.js +8 -0
  107. package/dist/types/tags.d.ts +48 -0
  108. package/dist/types/tags.d.ts.map +1 -1
  109. package/dist/utils/mp4-freeform.d.ts +20 -0
  110. package/dist/utils/mp4-freeform.d.ts.map +1 -0
  111. package/dist/utils/mp4-freeform.js +111 -0
  112. package/dist/utils/path.d.ts.map +1 -1
  113. package/dist/utils/path.js +3 -1
  114. package/dist/utils/tag-mapping.d.ts.map +1 -1
  115. package/dist/utils/tag-mapping.js +30 -18
  116. package/dist/version.d.ts +1 -1
  117. package/dist/version.js +1 -1
  118. package/dist/wasm.d.ts +3 -0
  119. package/dist/wasm.d.ts.map +1 -1
  120. package/dist/web-utils/data-url.js +1 -1
  121. package/dist/web.browser.js +2 -3388
  122. package/legal/COPYING.LGPL +502 -0
  123. package/package.json +17 -10
@@ -1,4453 +1,2 @@
1
- //#region \0rolldown/runtime.js
2
- var __defProp = Object.defineProperty;
3
- var __esmMin = (fn, res, err) => () => {
4
- if (err) throw err[0];
5
- try {
6
- return fn && (res = fn(fn = 0)), res;
7
- } catch (e) {
8
- throw err = [e], e;
9
- }
10
- };
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
13
- for (var name in all) __defProp(target, name, {
14
- get: all[name],
15
- enumerable: true
16
- });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
19
- };
20
- //#endregion
21
- //#region src/types/audio-formats.ts
22
- function isNamedAudioInput(input) {
23
- return typeof input === "object" && input !== null && "name" in input && "data" in input && !(input instanceof File) && !(input instanceof Uint8Array) && !(input instanceof ArrayBuffer);
24
- }
25
- var init_audio_formats = __esmMin((() => {}));
26
- //#endregion
27
- //#region src/types/tags.ts
28
- var init_tags = __esmMin((() => {}));
29
- //#endregion
30
- //#region src/types/metadata-mappings.ts
31
- var init_metadata_mappings = __esmMin((() => {}));
32
- //#endregion
33
- //#region src/types/pictures.ts
34
- var PICTURE_TYPE_VALUES, PICTURE_TYPE_NAMES, BITRATE_CONTROL_MODE_VALUES, BITRATE_CONTROL_MODE_NAMES;
35
- var init_pictures = __esmMin((() => {
36
- PICTURE_TYPE_VALUES = {
37
- Other: 0,
38
- FileIcon: 1,
39
- OtherFileIcon: 2,
40
- FrontCover: 3,
41
- BackCover: 4,
42
- LeafletPage: 5,
43
- Media: 6,
44
- LeadArtist: 7,
45
- Artist: 8,
46
- Conductor: 9,
47
- Band: 10,
48
- Composer: 11,
49
- Lyricist: 12,
50
- RecordingLocation: 13,
51
- DuringRecording: 14,
52
- DuringPerformance: 15,
53
- MovieScreenCapture: 16,
54
- ColouredFish: 17,
55
- Illustration: 18,
56
- BandLogo: 19,
57
- PublisherLogo: 20
58
- };
59
- PICTURE_TYPE_NAMES = {
60
- 0: "Other",
61
- 1: "FileIcon",
62
- 2: "OtherFileIcon",
63
- 3: "FrontCover",
64
- 4: "BackCover",
65
- 5: "LeafletPage",
66
- 6: "Media",
67
- 7: "LeadArtist",
68
- 8: "Artist",
69
- 9: "Conductor",
70
- 10: "Band",
71
- 11: "Composer",
72
- 12: "Lyricist",
73
- 13: "RecordingLocation",
74
- 14: "DuringRecording",
75
- 15: "DuringPerformance",
76
- 16: "MovieScreenCapture",
77
- 17: "ColouredFish",
78
- 18: "Illustration",
79
- 19: "BandLogo",
80
- 20: "PublisherLogo"
81
- };
82
- BITRATE_CONTROL_MODE_VALUES = {
83
- Constant: 0,
84
- LongTermAverage: 1,
85
- VariableConstrained: 2,
86
- Variable: 3
87
- };
88
- BITRATE_CONTROL_MODE_NAMES = {
89
- 0: "Constant",
90
- 1: "LongTermAverage",
91
- 2: "VariableConstrained",
92
- 3: "Variable"
93
- };
94
- }));
95
- //#endregion
96
- //#region src/types/chapters.ts
97
- var init_chapters = __esmMin((() => {}));
98
- //#endregion
99
- //#region src/types/bwf.ts
100
- var init_bwf = __esmMin((() => {}));
101
- //#endregion
102
- //#region src/types/config.ts
103
- var init_config = __esmMin((() => {}));
104
- //#endregion
105
- //#region src/types/format-property-keys.ts
106
- var init_format_property_keys = __esmMin((() => {}));
107
- //#endregion
108
- //#region src/types/index.ts
109
- var init_types$1 = __esmMin((() => {
110
- init_audio_formats();
111
- init_tags();
112
- init_metadata_mappings();
113
- init_pictures();
114
- init_chapters();
115
- init_bwf();
116
- init_config();
117
- init_format_property_keys();
118
- }));
119
- //#endregion
120
- //#region src/types.ts
121
- var init_types = __esmMin((() => {
122
- init_types$1();
123
- }));
124
- //#endregion
125
- //#region src/bwf/bext.ts
126
- var bext_exports = /* @__PURE__ */ __exportAll({
127
- decodeBext: () => decodeBext,
128
- encodeBext: () => encodeBext
129
- });
130
- function readFixedString(bytes, offset, len) {
131
- let end = offset;
132
- const max = Math.min(offset + len, bytes.length);
133
- while (end < max && bytes[end] !== 0) end++;
134
- let s = "";
135
- for (let i = offset; i < end; i++) s += String.fromCharCode(bytes[i]);
136
- return s;
137
- }
138
- function writeFixedString(bytes, offset, len, value) {
139
- for (let i = 0; i < len; i++) bytes[offset + i] = i < value.length ? value.charCodeAt(i) & 255 : 0;
140
- }
141
- function clampInt16(n) {
142
- return Math.max(-32768, Math.min(32767, Math.round(n)));
143
- }
144
- function loudnessRaw(v) {
145
- return v === void 0 ? LOUDNESS_UNSET : clampInt16(v * 100);
146
- }
147
- function loudnessFromRaw(raw) {
148
- return raw === LOUDNESS_UNSET ? void 0 : raw / 100;
149
- }
150
- function bytesToHex(bytes) {
151
- let s = "";
152
- for (const b of bytes) s += b.toString(16).padStart(2, "0");
153
- return s;
154
- }
155
- function hexToBytes(hex, outLen) {
156
- const clean = hex.replace(/[^0-9a-fA-F]/g, "");
157
- const out = new Uint8Array(outLen);
158
- for (let i = 0; i + 1 < clean.length + 1 && i / 2 < outLen; i += 2) {
159
- const pair = clean.slice(i, i + 2);
160
- if (pair.length === 2) out[i / 2] = parseInt(pair, 16);
161
- }
162
- return out;
163
- }
164
- function decodeBext(bytes) {
165
- if (bytes.length < 348) return void 0;
166
- const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
167
- const timeRefLow = dv.getUint32(338, true);
168
- const timeRefHigh = dv.getUint32(342, true);
169
- const version = dv.getUint16(VERSION_OFFSET, true);
170
- const result = {
171
- description: readFixedString(bytes, 0, 256),
172
- originator: readFixedString(bytes, 256, 32),
173
- originatorReference: readFixedString(bytes, 288, 32),
174
- originationDate: readFixedString(bytes, 320, 10),
175
- originationTime: readFixedString(bytes, 330, 8),
176
- timeReferenceSamples: BigInt(timeRefHigh) << 32n | BigInt(timeRefLow),
177
- version,
178
- codingHistory: bytes.length > FIXED_PREFIX_LEN ? readFixedString(bytes, FIXED_PREFIX_LEN, bytes.length - FIXED_PREFIX_LEN) : ""
179
- };
180
- if (version >= 1 && bytes.length >= 412) result.umid = bytesToHex(bytes.subarray(UMID_OFFSET, 412));
181
- if (version >= 2 && bytes.length >= 422) {
182
- const lv = loudnessFromRaw(dv.getInt16(LOUDNESS_OFFSET, true));
183
- const lr = loudnessFromRaw(dv.getInt16(414, true));
184
- const mtp = loudnessFromRaw(dv.getInt16(416, true));
185
- const mml = loudnessFromRaw(dv.getInt16(418, true));
186
- const msl = loudnessFromRaw(dv.getInt16(420, true));
187
- if (lv !== void 0) result.loudnessValueDb = lv;
188
- if (lr !== void 0) result.loudnessRangeDb = lr;
189
- if (mtp !== void 0) result.maxTruePeakLevelDbtp = mtp;
190
- if (mml !== void 0) result.maxMomentaryLoudnessDb = mml;
191
- if (msl !== void 0) result.maxShortTermLoudnessDb = msl;
192
- }
193
- return result;
194
- }
195
- function encodeBext(b) {
196
- const codingHistory = b.codingHistory ?? "";
197
- const bytes = new Uint8Array(FIXED_PREFIX_LEN + codingHistory.length);
198
- const dv = new DataView(bytes.buffer);
199
- const hasLoudness = b.loudnessValueDb !== void 0 || b.loudnessRangeDb !== void 0 || b.maxTruePeakLevelDbtp !== void 0 || b.maxMomentaryLoudnessDb !== void 0 || b.maxShortTermLoudnessDb !== void 0;
200
- const version = Number.isInteger(b.version) ? b.version : hasLoudness ? 2 : b.umid ? 1 : 0;
201
- writeFixedString(bytes, 0, 256, b.description ?? "");
202
- writeFixedString(bytes, 256, 32, b.originator ?? "");
203
- writeFixedString(bytes, 288, 32, b.originatorReference ?? "");
204
- writeFixedString(bytes, 320, 10, b.originationDate ?? "");
205
- writeFixedString(bytes, 330, 8, b.originationTime ?? "");
206
- const tr = b.timeReferenceSamples ?? 0n;
207
- dv.setUint32(338, Number(tr & 4294967295n), true);
208
- dv.setUint32(342, Number(tr >> 32n & 4294967295n), true);
209
- dv.setUint16(VERSION_OFFSET, version, true);
210
- if (version >= 1 && b.umid) bytes.set(hexToBytes(b.umid, UMID_LEN), UMID_OFFSET);
211
- if (version >= 2) {
212
- dv.setInt16(LOUDNESS_OFFSET, loudnessRaw(b.loudnessValueDb), true);
213
- dv.setInt16(414, loudnessRaw(b.loudnessRangeDb), true);
214
- dv.setInt16(416, loudnessRaw(b.maxTruePeakLevelDbtp), true);
215
- dv.setInt16(418, loudnessRaw(b.maxMomentaryLoudnessDb), true);
216
- dv.setInt16(420, loudnessRaw(b.maxShortTermLoudnessDb), true);
217
- }
218
- writeFixedString(bytes, FIXED_PREFIX_LEN, codingHistory.length, codingHistory);
219
- return bytes;
220
- }
221
- var FIXED_PREFIX_LEN, VERSION_OFFSET, UMID_OFFSET, UMID_LEN, LOUDNESS_OFFSET, LOUDNESS_UNSET;
222
- var init_bext = __esmMin((() => {
223
- FIXED_PREFIX_LEN = 602;
224
- VERSION_OFFSET = 346;
225
- UMID_OFFSET = 348;
226
- UMID_LEN = 64;
227
- LOUDNESS_OFFSET = 412;
228
- LOUDNESS_UNSET = 32767;
229
- }));
230
- //#endregion
231
- //#region src/errors/base.ts
232
- var SUPPORTED_FORMATS, TagLibError;
233
- var init_base = __esmMin((() => {
234
- SUPPORTED_FORMATS = [
235
- "MP3",
236
- "AAC",
237
- "MP4",
238
- "M4A",
239
- "FLAC",
240
- "OGG",
241
- "OPUS",
242
- "OggFLAC",
243
- "SPEEX",
244
- "WAV",
245
- "AIFF",
246
- "ASF",
247
- "APE",
248
- "DSF",
249
- "DSDIFF",
250
- "WV",
251
- "MPC",
252
- "TTA",
253
- "SHN",
254
- "MOD",
255
- "S3M",
256
- "IT",
257
- "XM",
258
- "MATROSKA",
259
- "MKA"
260
- ];
261
- TagLibError = class TagLibError extends Error {
262
- constructor(code, message, details) {
263
- super(message);
264
- this.code = code;
265
- this.details = details;
266
- this.name = "TagLibError";
267
- Object.setPrototypeOf(this, TagLibError.prototype);
268
- }
269
- };
270
- }));
271
- //#endregion
272
- //#region src/errors/classes.ts
273
- function errorMessage(error) {
274
- return error instanceof Error ? error.message : String(error);
275
- }
276
- function createErrorMessage(prefix, details) {
277
- return `${prefix}: ${details}`;
278
- }
279
- function formatFileSize(bytes) {
280
- if (bytes < 1024) return `${bytes} bytes`;
281
- if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
282
- return `${(bytes / 1048576).toFixed(1)} MB`;
283
- }
284
- var TagLibInitializationError, InvalidFormatError, UnsupportedFormatError, FileOperationError, MetadataError, MemoryError, EnvironmentError;
285
- var init_classes = __esmMin((() => {
286
- init_base();
287
- TagLibInitializationError = class TagLibInitializationError extends TagLibError {
288
- constructor(message, details) {
289
- super("INITIALIZATION", createErrorMessage("Failed to initialize TagLib Wasm module", message), details);
290
- this.name = "TagLibInitializationError";
291
- Object.setPrototypeOf(this, TagLibInitializationError.prototype);
292
- }
293
- };
294
- InvalidFormatError = class InvalidFormatError extends TagLibError {
295
- constructor(message, bufferSize, details) {
296
- const errorDetails = [`Invalid audio file format: ${message}`];
297
- if (bufferSize !== void 0) {
298
- errorDetails.push(`Buffer size: ${formatFileSize(bufferSize)}`);
299
- if (bufferSize < 1024) errorDetails.push("Audio files must be at least 1KB to contain valid headers.");
300
- }
301
- super("INVALID_FORMAT", errorDetails.join(". "), {
302
- ...details,
303
- bufferSize
304
- });
305
- this.bufferSize = bufferSize;
306
- this.name = "InvalidFormatError";
307
- Object.setPrototypeOf(this, InvalidFormatError.prototype);
308
- }
309
- };
310
- UnsupportedFormatError = class UnsupportedFormatError extends TagLibError {
311
- constructor(format, supportedFormats = SUPPORTED_FORMATS, details) {
312
- super("UNSUPPORTED_FORMAT", `Unsupported audio format: ${format}. Supported formats: ${supportedFormats.join(", ")}`, {
313
- ...details,
314
- format,
315
- supportedFormats
316
- });
317
- this.format = format;
318
- this.supportedFormats = supportedFormats;
319
- this.name = "UnsupportedFormatError";
320
- Object.setPrototypeOf(this, UnsupportedFormatError.prototype);
321
- }
322
- };
323
- FileOperationError = class FileOperationError extends TagLibError {
324
- constructor(operation, message, path, details) {
325
- const errorDetails = [`Failed to ${operation} file`];
326
- if (path) errorDetails.push(`Path: ${path}`);
327
- errorDetails.push(message);
328
- super("FILE_OPERATION", errorDetails.join(". "), {
329
- ...details,
330
- operation,
331
- path
332
- });
333
- this.operation = operation;
334
- this.path = path;
335
- this.name = "FileOperationError";
336
- Object.setPrototypeOf(this, FileOperationError.prototype);
337
- }
338
- };
339
- MetadataError = class MetadataError extends TagLibError {
340
- constructor(operation, message, field, details) {
341
- const errorDetails = [`Failed to ${operation} metadata`];
342
- if (field) errorDetails.push(`Field: ${field}`);
343
- errorDetails.push(message);
344
- super("METADATA", errorDetails.join(". "), {
345
- ...details,
346
- operation,
347
- field
348
- });
349
- this.operation = operation;
350
- this.field = field;
351
- this.name = "MetadataError";
352
- Object.setPrototypeOf(this, MetadataError.prototype);
353
- }
354
- };
355
- MemoryError = class MemoryError extends TagLibError {
356
- constructor(message, details) {
357
- super("MEMORY", createErrorMessage("Memory allocation failed", message), details);
358
- this.name = "MemoryError";
359
- Object.setPrototypeOf(this, MemoryError.prototype);
360
- }
361
- };
362
- EnvironmentError = class EnvironmentError extends TagLibError {
363
- constructor(environment, reason, requiredFeature) {
364
- const message = requiredFeature ? `Environment '${environment}' ${reason}. Required feature: ${requiredFeature}.` : `Environment '${environment}' ${reason}.`;
365
- super("ENVIRONMENT", message);
366
- this.environment = environment;
367
- this.reason = reason;
368
- this.requiredFeature = requiredFeature;
369
- this.name = "EnvironmentError";
370
- Object.setPrototypeOf(this, EnvironmentError.prototype);
371
- }
372
- };
373
- }));
374
- //#endregion
375
- //#region src/errors/guards.ts
376
- function isTagLibError(error) {
377
- return error instanceof TagLibError;
378
- }
379
- function isInvalidFormatError(error) {
380
- return error instanceof InvalidFormatError;
381
- }
382
- function isUnsupportedFormatError(error) {
383
- return error instanceof UnsupportedFormatError;
384
- }
385
- function isFileOperationError(error) {
386
- return error instanceof FileOperationError;
387
- }
388
- function isMetadataError(error) {
389
- return error instanceof MetadataError;
390
- }
391
- function isMemoryError(error) {
392
- return error instanceof MemoryError;
393
- }
394
- function isEnvironmentError(error) {
395
- return error instanceof EnvironmentError;
396
- }
397
- var init_guards = __esmMin((() => {
398
- init_base();
399
- init_classes();
400
- }));
401
- //#endregion
402
- //#region src/errors/index.ts
403
- var init_errors$1 = __esmMin((() => {
404
- init_base();
405
- init_classes();
406
- init_guards();
407
- }));
408
- //#endregion
409
- //#region src/errors.ts
410
- var init_errors = __esmMin((() => {
411
- init_errors$1();
412
- }));
413
- //#endregion
414
- //#region src/taglib/audio-file-bwf.ts
415
- function requireBwf(format) {
416
- if (!BWF_FORMATS.has(format)) throw new UnsupportedFormatError(format, ["WAV", "FLAC"], { operation: "BWF metadata" });
417
- }
418
- function getBextData(handle) {
419
- const raw = handle.getBextData();
420
- return raw && raw.length > 0 ? raw : void 0;
421
- }
422
- function setBextData(handle, format, data) {
423
- requireBwf(format);
424
- handle.setBextData(data);
425
- }
426
- function getBext(handle) {
427
- const raw = handle.getBextData();
428
- return raw && raw.length > 0 ? decodeBext(raw) : void 0;
429
- }
430
- function setBext(handle, format, bext) {
431
- requireBwf(format);
432
- handle.setBextData(encodeBext(bext));
433
- }
434
- function getIxml(handle) {
435
- return handle.getIxml();
436
- }
437
- function setIxml(handle, format, data) {
438
- requireBwf(format);
439
- handle.setIxml(data);
440
- }
441
- var BWF_FORMATS;
442
- var init_audio_file_bwf = __esmMin((() => {
443
- init_bext();
444
- init_errors();
445
- BWF_FORMATS = /* @__PURE__ */ new Set(["WAV", "FLAC"]);
446
- }));
447
- //#endregion
448
- //#region src/taglib/id3v2-frames.ts
449
- function assertMp3(format) {
450
- if (format !== "MP3" && format !== "AAC") throw new UnsupportedFormatError(format, ["MP3", "AAC"], { operation: "id3v2Frames" });
451
- }
452
- function assertFrameId(id, operation) {
453
- if (!FRAME_ID_PATTERN.test(id)) throw new MetadataError(operation, `Invalid ID3v2 frame ID: "${id}". Frame IDs must match [A-Z0-9]{4}`, id);
454
- }
455
- function assertFrameBodies(id, data) {
456
- for (const body of data) if (body.length === 0) throw new MetadataError("write", "Frame data must not be empty: zero-size ID3v2 frames are invalid", id);
457
- }
458
- function toPublicFrame(frame) {
459
- return {
460
- id: frame.id,
461
- data: frame.data,
462
- ...frame.flags ? { flags: frame.flags } : {}
463
- };
464
- }
465
- var FRAME_ID_PATTERN;
466
- var init_id3v2_frames = __esmMin((() => {
467
- init_classes();
468
- FRAME_ID_PATTERN = /^[A-Z0-9]{4}$/;
469
- }));
470
- //#endregion
471
- //#region \0taglib:platform-io-stub
472
- function getPlatformIO() {
473
- throw new Error("Filesystem operations are not available in the browser.");
474
- }
475
- var init__taglib_platform_io_stub = __esmMin((() => {}));
476
- //#endregion
477
- //#region src/utils/write.ts
478
- async function writeFileData(path, data) {
479
- try {
480
- await getPlatformIO().writeFile(path, data);
481
- } catch (error) {
482
- if (error instanceof EnvironmentError) throw error;
483
- throw new FileOperationError("write", error.message, path);
484
- }
485
- }
486
- var init_write = __esmMin((() => {
487
- init_errors();
488
- init__taglib_platform_io_stub();
489
- }));
490
- //#endregion
491
- //#region \0taglib:node-fs-stub
492
- function getNodeFsSync() {
493
- return null;
494
- }
495
- var init__taglib_node_fs_stub = __esmMin((() => {}));
496
- //#endregion
497
- //#region src/utils/rating.ts
498
- function normalized(value) {
499
- return value;
500
- }
501
- function popm(value) {
502
- return value;
503
- }
504
- function toNormalized(value) {
505
- return value / 255;
506
- }
507
- function fromNormalized(value) {
508
- return Math.round(value * 255);
509
- }
510
- function toStars(value, maxStars = 5) {
511
- return Math.round(value * maxStars);
512
- }
513
- function fromStars(stars, maxStars = 5) {
514
- return stars / maxStars;
515
- }
516
- function toPopm(value) {
517
- const stars = Math.round(value * 5);
518
- return POPM_STAR_VALUES[stars] ?? 0;
519
- }
520
- function fromPopm(value) {
521
- if (value === 0) return 0;
522
- if (value <= 1) return .2;
523
- if (value <= 64) return .4;
524
- if (value <= 128) return .6;
525
- if (value <= 196) return .8;
526
- return 1;
527
- }
528
- function toPercent(value) {
529
- return value * 100;
530
- }
531
- function fromPercent(percent) {
532
- return percent / 100;
533
- }
534
- function clamp(rating) {
535
- return Math.max(0, Math.min(1, rating));
536
- }
537
- function isValid(rating) {
538
- return typeof rating === "number" && !Number.isNaN(rating) && rating >= 0 && rating <= 1;
539
- }
540
- var POPM_STAR_VALUES, RatingUtils;
541
- var init_rating = __esmMin((() => {
542
- POPM_STAR_VALUES = [
543
- 0,
544
- 1,
545
- 64,
546
- 128,
547
- 196,
548
- 255
549
- ];
550
- RatingUtils = {
551
- normalized,
552
- popm,
553
- toNormalized,
554
- fromNormalized,
555
- toStars,
556
- fromStars,
557
- toPopm,
558
- fromPopm,
559
- toPercent,
560
- fromPercent,
561
- clamp,
562
- isValid,
563
- POPM_STAR_VALUES
564
- };
565
- }));
566
- //#endregion
567
- //#region src/runtime/detector.ts
568
- function isDeno() {
569
- return g.Deno !== void 0;
570
- }
571
- var g;
572
- var init_detector = __esmMin((() => {
573
- g = globalThis;
574
- new Uint8Array([
575
- 0,
576
- 97,
577
- 115,
578
- 109,
579
- 1,
580
- 0,
581
- 0,
582
- 0,
583
- 6,
584
- 6,
585
- 1,
586
- 105,
587
- 0,
588
- 208,
589
- 105,
590
- 11
591
- ]);
592
- }));
593
- //#endregion
594
- //#region src/constants/additional-properties.ts
595
- var ADDITIONAL_PROPERTIES;
596
- var init_additional_properties = __esmMin((() => {
597
- ADDITIONAL_PROPERTIES = {
598
- albumArtistSort: {
599
- key: "ALBUMARTISTSORT",
600
- description: "Sort name for album artist (for alphabetization)",
601
- type: "string",
602
- supportedFormats: [
603
- "ID3v2",
604
- "MP4",
605
- "Vorbis"
606
- ],
607
- mappings: {
608
- id3v2: { frame: "TSO2" },
609
- vorbis: "ALBUMARTISTSORT",
610
- mp4: "soaa"
611
- }
612
- },
613
- composerSort: {
614
- key: "COMPOSERSORT",
615
- description: "Sort name for composer (for alphabetization)",
616
- type: "string",
617
- supportedFormats: [
618
- "ID3v2",
619
- "MP4",
620
- "Vorbis"
621
- ],
622
- mappings: {
623
- id3v2: { frame: "TSOC" },
624
- vorbis: "COMPOSERSORT",
625
- mp4: "soco"
626
- }
627
- },
628
- subtitle: {
629
- key: "SUBTITLE",
630
- description: "Subtitle or description refinement",
631
- type: "string",
632
- supportedFormats: [
633
- "ID3v2",
634
- "MP4",
635
- "Vorbis"
636
- ],
637
- mappings: {
638
- id3v2: { frame: "TIT3" },
639
- vorbis: "SUBTITLE",
640
- mp4: "----:com.apple.iTunes:SUBTITLE"
641
- }
642
- },
643
- label: {
644
- key: "LABEL",
645
- description: "Record label name",
646
- type: "string",
647
- supportedFormats: [
648
- "ID3v2",
649
- "MP4",
650
- "Vorbis",
651
- "WAV"
652
- ],
653
- mappings: {
654
- id3v2: { frame: "TPUB" },
655
- vorbis: "LABEL",
656
- mp4: "----:com.apple.iTunes:LABEL",
657
- wav: "IPUB"
658
- }
659
- },
660
- producer: {
661
- key: "PRODUCER",
662
- description: "Producer of the recording",
663
- type: "string",
664
- supportedFormats: [
665
- "ID3v2",
666
- "MP4",
667
- "Vorbis"
668
- ],
669
- mappings: {
670
- id3v2: {
671
- frame: "TXXX",
672
- description: "PRODUCER"
673
- },
674
- vorbis: "PRODUCER",
675
- mp4: "----:com.apple.iTunes:PRODUCER"
676
- }
677
- },
678
- radioStationOwner: {
679
- key: "RADIOSTATIONOWNER",
680
- description: "Owner of the radio station",
681
- type: "string",
682
- supportedFormats: ["ID3v2"],
683
- mappings: { id3v2: { frame: "TRSO" } }
684
- },
685
- asin: {
686
- key: "ASIN",
687
- description: "Amazon Standard Identification Number",
688
- type: "string",
689
- supportedFormats: [
690
- "ID3v2",
691
- "MP4",
692
- "Vorbis"
693
- ],
694
- mappings: {
695
- id3v2: {
696
- frame: "TXXX",
697
- description: "ASIN"
698
- },
699
- vorbis: "ASIN",
700
- mp4: "----:com.apple.iTunes:ASIN"
701
- }
702
- },
703
- musicbrainzReleaseArtistId: {
704
- key: "MUSICBRAINZ_ALBUMARTISTID",
705
- description: "MusicBrainz Release Artist ID (UUID)",
706
- type: "string",
707
- supportedFormats: [
708
- "ID3v2",
709
- "MP4",
710
- "Vorbis"
711
- ],
712
- mappings: {
713
- id3v2: {
714
- frame: "TXXX",
715
- description: "MusicBrainz Album Artist Id"
716
- },
717
- vorbis: "MUSICBRAINZ_ALBUMARTISTID",
718
- mp4: "----:com.apple.iTunes:MusicBrainz Album Artist Id"
719
- }
720
- },
721
- musicbrainzWorkId: {
722
- key: "MUSICBRAINZ_WORKID",
723
- description: "MusicBrainz Work ID (UUID)",
724
- type: "string",
725
- supportedFormats: [
726
- "ID3v2",
727
- "MP4",
728
- "Vorbis"
729
- ],
730
- mappings: {
731
- id3v2: {
732
- frame: "TXXX",
733
- description: "MusicBrainz Work Id"
734
- },
735
- vorbis: "MUSICBRAINZ_WORKID",
736
- mp4: "----:com.apple.iTunes:MusicBrainz Work Id"
737
- }
738
- },
739
- musicbrainzReleaseTrackId: {
740
- key: "MUSICBRAINZ_RELEASETRACKID",
741
- description: "MusicBrainz Release Track ID (UUID)",
742
- type: "string",
743
- supportedFormats: [
744
- "ID3v2",
745
- "MP4",
746
- "Vorbis"
747
- ],
748
- mappings: {
749
- id3v2: {
750
- frame: "TXXX",
751
- description: "MusicBrainz Release Track Id"
752
- },
753
- vorbis: "MUSICBRAINZ_RELEASETRACKID",
754
- mp4: "----:com.apple.iTunes:MusicBrainz Release Track Id"
755
- }
756
- },
757
- podcastId: {
758
- key: "PODCASTID",
759
- description: "Podcast episode identifier",
760
- type: "string",
761
- supportedFormats: [
762
- "ID3v2",
763
- "MP4",
764
- "Vorbis"
765
- ],
766
- mappings: {
767
- id3v2: { frame: "TGID" },
768
- vorbis: "PODCASTID",
769
- mp4: "egid"
770
- }
771
- },
772
- podcastUrl: {
773
- key: "PODCASTURL",
774
- description: "Podcast feed URL",
775
- type: "string",
776
- supportedFormats: [
777
- "ID3v2",
778
- "MP4",
779
- "Vorbis"
780
- ],
781
- mappings: {
782
- id3v2: { frame: "WFED" },
783
- vorbis: "PODCASTURL",
784
- mp4: "purl"
785
- }
786
- },
787
- originalArtist: {
788
- key: "ORIGINALARTIST",
789
- description: "Original artist of a cover or remix",
790
- type: "string",
791
- supportedFormats: ["ID3v2", "Vorbis"],
792
- mappings: {
793
- id3v2: { frame: "TOPE" },
794
- vorbis: "ORIGINALARTIST"
795
- }
796
- },
797
- originalAlbum: {
798
- key: "ORIGINALALBUM",
799
- description: "Original album of a cover or remix",
800
- type: "string",
801
- supportedFormats: ["ID3v2", "Vorbis"],
802
- mappings: {
803
- id3v2: { frame: "TOAL" },
804
- vorbis: "ORIGINALALBUM"
805
- }
806
- },
807
- originalDate: {
808
- key: "ORIGINALDATE",
809
- description: "Original release date",
810
- type: "string",
811
- supportedFormats: [
812
- "ID3v2",
813
- "MP4",
814
- "Vorbis"
815
- ],
816
- mappings: {
817
- id3v2: { frame: "TDOR" },
818
- vorbis: "ORIGINALDATE",
819
- mp4: "----:com.apple.iTunes:ORIGINALDATE"
820
- }
821
- },
822
- script: {
823
- key: "SCRIPT",
824
- description: "Writing script used for text (e.g., Latn, Jpan)",
825
- type: "string",
826
- supportedFormats: ["MP4", "Vorbis"],
827
- mappings: {
828
- vorbis: "SCRIPT",
829
- mp4: "----:com.apple.iTunes:SCRIPT"
830
- }
831
- },
832
- involvedPeople: {
833
- key: "INVOLVEDPEOPLE",
834
- description: "List of involved people and their roles",
835
- type: "string",
836
- supportedFormats: ["ID3v2"],
837
- mappings: { id3v2: { frame: "TIPL" } }
838
- },
839
- encoding: {
840
- key: "ENCODING",
841
- description: "Encoding software or settings",
842
- type: "string",
843
- supportedFormats: [
844
- "ID3v2",
845
- "MP4",
846
- "Vorbis",
847
- "WAV"
848
- ],
849
- mappings: {
850
- id3v2: { frame: "TSSE" },
851
- vorbis: "ENCODING",
852
- mp4: "©too",
853
- wav: "ISFT"
854
- }
855
- }
856
- };
857
- }));
858
- //#endregion
859
- //#region src/constants/basic-properties.ts
860
- var BASIC_PROPERTIES;
861
- var init_basic_properties = __esmMin((() => {
862
- BASIC_PROPERTIES = {
863
- title: {
864
- key: "TITLE",
865
- description: "The title of the track",
866
- type: "string",
867
- supportedFormats: [
868
- "ID3v2",
869
- "MP4",
870
- "Vorbis",
871
- "WAV"
872
- ],
873
- mappings: {
874
- id3v2: { frame: "TIT2" },
875
- vorbis: "TITLE",
876
- mp4: "©nam",
877
- wav: "INAM"
878
- }
879
- },
880
- artist: {
881
- key: "ARTIST",
882
- description: "The primary performer(s) of the track",
883
- type: "string",
884
- supportedFormats: [
885
- "ID3v2",
886
- "MP4",
887
- "Vorbis",
888
- "WAV"
889
- ],
890
- mappings: {
891
- id3v2: { frame: "TPE1" },
892
- vorbis: "ARTIST",
893
- mp4: "©ART",
894
- wav: "IART"
895
- }
896
- },
897
- album: {
898
- key: "ALBUM",
899
- description: "The album/collection name",
900
- type: "string",
901
- supportedFormats: [
902
- "ID3v2",
903
- "MP4",
904
- "Vorbis",
905
- "WAV"
906
- ],
907
- mappings: {
908
- id3v2: { frame: "TALB" },
909
- vorbis: "ALBUM",
910
- mp4: "©alb",
911
- wav: "IPRD"
912
- }
913
- },
914
- date: {
915
- key: "DATE",
916
- description: "The date of recording (typically year)",
917
- type: "string",
918
- supportedFormats: [
919
- "ID3v2",
920
- "MP4",
921
- "Vorbis",
922
- "WAV"
923
- ],
924
- mappings: {
925
- id3v2: { frame: "TDRC" },
926
- vorbis: "DATE",
927
- mp4: "©day",
928
- wav: "ICRD"
929
- }
930
- },
931
- trackNumber: {
932
- key: "TRACKNUMBER",
933
- description: "The track number within the album",
934
- type: "string",
935
- supportedFormats: [
936
- "ID3v2",
937
- "MP4",
938
- "Vorbis",
939
- "WAV"
940
- ],
941
- mappings: {
942
- id3v2: { frame: "TRCK" },
943
- vorbis: "TRACKNUMBER",
944
- mp4: "trkn",
945
- wav: "ITRK"
946
- }
947
- },
948
- genre: {
949
- key: "GENRE",
950
- description: "The musical genre",
951
- type: "string",
952
- supportedFormats: [
953
- "ID3v2",
954
- "MP4",
955
- "Vorbis",
956
- "WAV"
957
- ],
958
- mappings: {
959
- id3v2: { frame: "TCON" },
960
- vorbis: "GENRE",
961
- mp4: "©gen",
962
- wav: "IGNR"
963
- }
964
- },
965
- comment: {
966
- key: "COMMENT",
967
- description: "Comments or notes about the track",
968
- type: "string",
969
- supportedFormats: [
970
- "ID3v2",
971
- "MP4",
972
- "Vorbis",
973
- "WAV"
974
- ],
975
- mappings: {
976
- id3v2: { frame: "COMM" },
977
- vorbis: "COMMENT",
978
- mp4: "©cmt",
979
- wav: "ICMT"
980
- }
981
- }
982
- };
983
- }));
984
- //#endregion
985
- //#region src/constants/general-extended-properties.ts
986
- var GENERAL_EXTENDED_PROPERTIES;
987
- var init_general_extended_properties = __esmMin((() => {
988
- GENERAL_EXTENDED_PROPERTIES = {
989
- albumArtist: {
990
- key: "ALBUMARTIST",
991
- description: "The album artist (band/orchestra/ensemble)",
992
- type: "string",
993
- supportedFormats: [
994
- "ID3v2",
995
- "MP4",
996
- "Vorbis"
997
- ],
998
- mappings: {
999
- id3v2: { frame: "TPE2" },
1000
- vorbis: "ALBUMARTIST",
1001
- mp4: "aART"
1002
- }
1003
- },
1004
- composer: {
1005
- key: "COMPOSER",
1006
- description: "The original composer(s) of the track",
1007
- type: "string",
1008
- supportedFormats: [
1009
- "ID3v2",
1010
- "MP4",
1011
- "Vorbis"
1012
- ],
1013
- mappings: {
1014
- id3v2: { frame: "TCOM" },
1015
- vorbis: "COMPOSER",
1016
- mp4: "©wrt"
1017
- }
1018
- },
1019
- copyright: {
1020
- key: "COPYRIGHT",
1021
- description: "Copyright information",
1022
- type: "string",
1023
- supportedFormats: ["ID3v2", "Vorbis"],
1024
- mappings: { vorbis: "COPYRIGHT" }
1025
- },
1026
- encodedBy: {
1027
- key: "ENCODEDBY",
1028
- description: "The encoding software or person",
1029
- type: "string",
1030
- supportedFormats: ["ID3v2", "Vorbis"],
1031
- mappings: { vorbis: "ENCODEDBY" }
1032
- },
1033
- discNumber: {
1034
- key: "DISCNUMBER",
1035
- description: "The disc number for multi-disc sets",
1036
- type: "string",
1037
- supportedFormats: [
1038
- "ID3v2",
1039
- "MP4",
1040
- "Vorbis"
1041
- ],
1042
- mappings: {
1043
- id3v2: { frame: "TPOS" },
1044
- vorbis: "DISCNUMBER",
1045
- mp4: "disk"
1046
- }
1047
- },
1048
- bpm: {
1049
- key: "BPM",
1050
- description: "Beats per minute",
1051
- type: "string",
1052
- supportedFormats: [
1053
- "ID3v2",
1054
- "MP4",
1055
- "Vorbis"
1056
- ],
1057
- mappings: {
1058
- id3v2: { frame: "TBPM" },
1059
- vorbis: "BPM",
1060
- mp4: "tmpo"
1061
- }
1062
- },
1063
- totalTracks: {
1064
- key: "TRACKTOTAL",
1065
- description: "Total number of tracks on the album",
1066
- type: "string",
1067
- supportedFormats: [
1068
- "ID3v2",
1069
- "MP4",
1070
- "Vorbis"
1071
- ],
1072
- mappings: {
1073
- id3v2: { frame: "TRCK" },
1074
- vorbis: "TRACKTOTAL",
1075
- mp4: "trkn"
1076
- }
1077
- },
1078
- totalDiscs: {
1079
- key: "DISCTOTAL",
1080
- description: "Total number of discs in the set",
1081
- type: "string",
1082
- supportedFormats: [
1083
- "ID3v2",
1084
- "MP4",
1085
- "Vorbis"
1086
- ],
1087
- mappings: {
1088
- id3v2: { frame: "TPOS" },
1089
- vorbis: "DISCTOTAL",
1090
- mp4: "disk"
1091
- }
1092
- },
1093
- compilation: {
1094
- key: "COMPILATION",
1095
- description: "Whether the album is a compilation (various artists)",
1096
- type: "boolean",
1097
- supportedFormats: [
1098
- "ID3v2",
1099
- "MP4",
1100
- "Vorbis"
1101
- ],
1102
- mappings: {
1103
- id3v2: { frame: "TCMP" },
1104
- vorbis: "COMPILATION",
1105
- mp4: "cpil"
1106
- }
1107
- },
1108
- titleSort: {
1109
- key: "TITLESORT",
1110
- description: "Sort name for title (for alphabetization)",
1111
- type: "string",
1112
- supportedFormats: [
1113
- "ID3v2",
1114
- "MP4",
1115
- "Vorbis"
1116
- ],
1117
- mappings: {
1118
- id3v2: { frame: "TSOT" },
1119
- vorbis: "TITLESORT",
1120
- mp4: "sonm"
1121
- }
1122
- },
1123
- artistSort: {
1124
- key: "ARTISTSORT",
1125
- description: "Sort name for artist (for alphabetization)",
1126
- type: "string",
1127
- supportedFormats: [
1128
- "ID3v2",
1129
- "MP4",
1130
- "Vorbis"
1131
- ],
1132
- mappings: {
1133
- id3v2: { frame: "TSOP" },
1134
- vorbis: "ARTISTSORT",
1135
- mp4: "soar"
1136
- }
1137
- },
1138
- albumSort: {
1139
- key: "ALBUMSORT",
1140
- description: "Sort name for album (for alphabetization)",
1141
- type: "string",
1142
- supportedFormats: [
1143
- "ID3v2",
1144
- "MP4",
1145
- "Vorbis"
1146
- ],
1147
- mappings: {
1148
- id3v2: { frame: "TSOA" },
1149
- vorbis: "ALBUMSORT",
1150
- mp4: "soal"
1151
- }
1152
- },
1153
- lyricist: {
1154
- key: "LYRICIST",
1155
- description: "The lyrics/text writer(s)",
1156
- type: "string",
1157
- supportedFormats: ["Vorbis"],
1158
- mappings: { vorbis: "LYRICIST" }
1159
- },
1160
- conductor: {
1161
- key: "CONDUCTOR",
1162
- description: "The conductor",
1163
- type: "string",
1164
- supportedFormats: ["Vorbis"],
1165
- mappings: { vorbis: "CONDUCTOR" }
1166
- },
1167
- remixedBy: {
1168
- key: "REMIXER",
1169
- description: "Person who remixed the track",
1170
- type: "string",
1171
- supportedFormats: [
1172
- "ID3v2",
1173
- "MP4",
1174
- "Vorbis"
1175
- ],
1176
- mappings: {
1177
- id3v2: { frame: "TPE4" },
1178
- vorbis: "REMIXER",
1179
- mp4: "----:com.apple.iTunes:REMIXER"
1180
- }
1181
- },
1182
- language: {
1183
- key: "LANGUAGE",
1184
- description: "Language of vocals/lyrics",
1185
- type: "string",
1186
- supportedFormats: ["Vorbis"],
1187
- mappings: { vorbis: "LANGUAGE" }
1188
- },
1189
- publisher: {
1190
- key: "PUBLISHER",
1191
- description: "The publisher",
1192
- type: "string",
1193
- supportedFormats: ["Vorbis"],
1194
- mappings: { vorbis: "PUBLISHER" }
1195
- },
1196
- mood: {
1197
- key: "MOOD",
1198
- description: "The mood/atmosphere of the track",
1199
- type: "string",
1200
- supportedFormats: ["Vorbis"],
1201
- mappings: { vorbis: "MOOD" }
1202
- },
1203
- media: {
1204
- key: "MEDIA",
1205
- description: "Media type (CD, vinyl, etc.)",
1206
- type: "string",
1207
- supportedFormats: ["Vorbis"],
1208
- mappings: { vorbis: "MEDIA" }
1209
- },
1210
- grouping: {
1211
- key: "GROUPING",
1212
- description: "Content group/work",
1213
- type: "string",
1214
- supportedFormats: ["Vorbis"],
1215
- mappings: { vorbis: "GROUPING" }
1216
- },
1217
- work: {
1218
- key: "WORK",
1219
- description: "Work name",
1220
- type: "string",
1221
- supportedFormats: ["Vorbis"],
1222
- mappings: { vorbis: "WORK" }
1223
- },
1224
- lyrics: {
1225
- key: "LYRICS",
1226
- description: "Lyrics content",
1227
- type: "string",
1228
- supportedFormats: ["Vorbis"],
1229
- mappings: { vorbis: "LYRICS" }
1230
- },
1231
- isrc: {
1232
- key: "ISRC",
1233
- description: "International Standard Recording Code",
1234
- type: "string",
1235
- supportedFormats: ["Vorbis"],
1236
- mappings: { vorbis: "ISRC" }
1237
- },
1238
- catalogNumber: {
1239
- key: "CATALOGNUMBER",
1240
- description: "Catalog number",
1241
- type: "string",
1242
- supportedFormats: ["Vorbis"],
1243
- mappings: { vorbis: "CATALOGNUMBER" }
1244
- },
1245
- barcode: {
1246
- key: "BARCODE",
1247
- description: "Barcode (EAN/UPC)",
1248
- type: "string",
1249
- supportedFormats: ["Vorbis"],
1250
- mappings: { vorbis: "BARCODE" }
1251
- }
1252
- };
1253
- }));
1254
- //#endregion
1255
- //#region src/constants/specialized-properties.ts
1256
- var SPECIALIZED_PROPERTIES;
1257
- var init_specialized_properties = __esmMin((() => {
1258
- SPECIALIZED_PROPERTIES = {
1259
- musicbrainzArtistId: {
1260
- key: "MUSICBRAINZ_ARTISTID",
1261
- description: "MusicBrainz Artist ID (UUID)",
1262
- type: "string",
1263
- supportedFormats: [
1264
- "ID3v2",
1265
- "MP4",
1266
- "Vorbis"
1267
- ],
1268
- mappings: {
1269
- id3v2: {
1270
- frame: "TXXX",
1271
- description: "MusicBrainz Artist Id"
1272
- },
1273
- vorbis: "MUSICBRAINZ_ARTISTID",
1274
- mp4: "----:com.apple.iTunes:MusicBrainz Artist Id"
1275
- }
1276
- },
1277
- musicbrainzReleaseId: {
1278
- key: "MUSICBRAINZ_ALBUMID",
1279
- description: "MusicBrainz Release ID (UUID)",
1280
- type: "string",
1281
- supportedFormats: [
1282
- "ID3v2",
1283
- "MP4",
1284
- "Vorbis"
1285
- ],
1286
- mappings: {
1287
- id3v2: {
1288
- frame: "TXXX",
1289
- description: "MusicBrainz Album Id"
1290
- },
1291
- vorbis: "MUSICBRAINZ_ALBUMID",
1292
- mp4: "----:com.apple.iTunes:MusicBrainz Album Id"
1293
- }
1294
- },
1295
- musicbrainzTrackId: {
1296
- key: "MUSICBRAINZ_TRACKID",
1297
- description: "MusicBrainz Recording ID (UUID)",
1298
- type: "string",
1299
- supportedFormats: [
1300
- "ID3v2",
1301
- "MP4",
1302
- "Vorbis"
1303
- ],
1304
- mappings: {
1305
- id3v2: {
1306
- frame: "UFID",
1307
- description: "http://musicbrainz.org"
1308
- },
1309
- vorbis: "MUSICBRAINZ_TRACKID",
1310
- mp4: "----:com.apple.iTunes:MusicBrainz Track Id"
1311
- }
1312
- },
1313
- musicbrainzReleaseGroupId: {
1314
- key: "MUSICBRAINZ_RELEASEGROUPID",
1315
- description: "MusicBrainz Release Group ID (UUID)",
1316
- type: "string",
1317
- supportedFormats: [
1318
- "ID3v2",
1319
- "MP4",
1320
- "Vorbis"
1321
- ],
1322
- mappings: {
1323
- id3v2: {
1324
- frame: "TXXX",
1325
- description: "MusicBrainz Release Group Id"
1326
- },
1327
- vorbis: "MUSICBRAINZ_RELEASEGROUPID",
1328
- mp4: "----:com.apple.iTunes:MusicBrainz Release Group Id"
1329
- }
1330
- },
1331
- releaseType: {
1332
- key: "RELEASETYPE",
1333
- description: "Release type (album, single, EP, compilation, ...). Multi-value (e.g. 'album' + 'EP'). TagLib 2.3.2 translates the RELEASETYPE key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM TYPE' (TagLib's description casing), MP4 freeform atom, APEv2 MUSICBRAINZ_ALBUMTYPE, ASF 'MusicBrainz/Album Type', Vorbis/Matroska raw RELEASETYPE",
1334
- type: "string",
1335
- supportedFormats: [
1336
- "ID3v2",
1337
- "MP4",
1338
- "Vorbis",
1339
- "APE",
1340
- "ASF",
1341
- "Matroska"
1342
- ],
1343
- mappings: {
1344
- id3v2: {
1345
- frame: "TXXX",
1346
- description: "MusicBrainz Album Type"
1347
- },
1348
- vorbis: "RELEASETYPE",
1349
- mp4: "----:com.apple.iTunes:MusicBrainz Album Type"
1350
- }
1351
- },
1352
- releaseCountry: {
1353
- key: "RELEASECOUNTRY",
1354
- description: "Release country (ISO 3166-1 code, e.g. 'US'). TagLib 2.3.2 translates the RELEASECOUNTRY key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM RELEASE COUNTRY' (TagLib's description casing; an uppercase TXXX:RELEASECOUNTRY description also reads back), MP4 freeform atom 'MusicBrainz Album Release Country', APEv2 raw RELEASECOUNTRY, ASF 'MusicBrainz/Album Release Country', WAV ICNT, Vorbis/Matroska raw RELEASECOUNTRY",
1355
- type: "string",
1356
- supportedFormats: [
1357
- "ID3v2",
1358
- "MP4",
1359
- "Vorbis",
1360
- "APE",
1361
- "ASF",
1362
- "Matroska",
1363
- "WAV"
1364
- ],
1365
- mappings: {
1366
- id3v2: {
1367
- frame: "TXXX",
1368
- description: "MusicBrainz Album Release Country"
1369
- },
1370
- vorbis: "RELEASECOUNTRY",
1371
- mp4: "----:com.apple.iTunes:MusicBrainz Album Release Country"
1372
- }
1373
- },
1374
- itunesAdvisory: {
1375
- key: "ITUNESADVISORY",
1376
- description: "Content advisory in the ITUNESADVISORY convention ('1' = explicit, '2' = clean, '0' = unspecified). On MP4 the value is stored in the native rtng atom and surfaced here. The typed tri-state lives on ExtendedTag.advisory; aliases CONTENTADVISORY and EXPLICIT resolve here",
1377
- type: "string",
1378
- supportedFormats: [
1379
- "ID3v2",
1380
- "MP4",
1381
- "Vorbis",
1382
- "APE",
1383
- "ASF"
1384
- ],
1385
- mappings: {
1386
- id3v2: {
1387
- frame: "TXXX",
1388
- description: "ITUNESADVISORY"
1389
- },
1390
- vorbis: "ITUNESADVISORY",
1391
- mp4: "----:com.apple.iTunes:ITUNESADVISORY"
1392
- }
1393
- },
1394
- replayGainTrackGain: {
1395
- key: "REPLAYGAIN_TRACK_GAIN",
1396
- description: "ReplayGain track gain in dB (e.g., '-6.54 dB')",
1397
- type: "string",
1398
- supportedFormats: [
1399
- "ID3v2",
1400
- "MP4",
1401
- "Vorbis"
1402
- ],
1403
- mappings: {
1404
- id3v2: {
1405
- frame: "TXXX",
1406
- description: "ReplayGain_Track_Gain"
1407
- },
1408
- vorbis: "REPLAYGAIN_TRACK_GAIN",
1409
- mp4: "----:com.apple.iTunes:replaygain_track_gain"
1410
- }
1411
- },
1412
- replayGainTrackPeak: {
1413
- key: "REPLAYGAIN_TRACK_PEAK",
1414
- description: "ReplayGain track peak value (0.0-1.0)",
1415
- type: "string",
1416
- supportedFormats: [
1417
- "ID3v2",
1418
- "MP4",
1419
- "Vorbis"
1420
- ],
1421
- mappings: {
1422
- id3v2: {
1423
- frame: "TXXX",
1424
- description: "ReplayGain_Track_Peak"
1425
- },
1426
- vorbis: "REPLAYGAIN_TRACK_PEAK",
1427
- mp4: "----:com.apple.iTunes:replaygain_track_peak"
1428
- }
1429
- },
1430
- replayGainAlbumGain: {
1431
- key: "REPLAYGAIN_ALBUM_GAIN",
1432
- description: "ReplayGain album gain in dB",
1433
- type: "string",
1434
- supportedFormats: [
1435
- "ID3v2",
1436
- "MP4",
1437
- "Vorbis"
1438
- ],
1439
- mappings: {
1440
- id3v2: {
1441
- frame: "TXXX",
1442
- description: "ReplayGain_Album_Gain"
1443
- },
1444
- vorbis: "REPLAYGAIN_ALBUM_GAIN",
1445
- mp4: "----:com.apple.iTunes:replaygain_album_gain"
1446
- }
1447
- },
1448
- replayGainAlbumPeak: {
1449
- key: "REPLAYGAIN_ALBUM_PEAK",
1450
- description: "ReplayGain album peak value (0.0-1.0)",
1451
- type: "string",
1452
- supportedFormats: [
1453
- "ID3v2",
1454
- "MP4",
1455
- "Vorbis"
1456
- ],
1457
- mappings: {
1458
- id3v2: {
1459
- frame: "TXXX",
1460
- description: "ReplayGain_Album_Peak"
1461
- },
1462
- vorbis: "REPLAYGAIN_ALBUM_PEAK",
1463
- mp4: "----:com.apple.iTunes:replaygain_album_peak"
1464
- }
1465
- },
1466
- r128TrackGain: {
1467
- key: "R128_TRACK_GAIN",
1468
- description: "EBU R128 track loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256, e.g. '-573' = -2.23828125 dB). readTags() converts to a decibel number (see ExtendedTag.r128TrackGain)",
1469
- type: "string",
1470
- supportedFormats: [
1471
- "ID3v2",
1472
- "MP4",
1473
- "Vorbis",
1474
- "ASF"
1475
- ],
1476
- mappings: {
1477
- id3v2: {
1478
- frame: "TXXX",
1479
- description: "R128_TRACK_GAIN"
1480
- },
1481
- vorbis: "R128_TRACK_GAIN",
1482
- mp4: "----:com.apple.iTunes:R128_TRACK_GAIN"
1483
- }
1484
- },
1485
- r128AlbumGain: {
1486
- key: "R128_ALBUM_GAIN",
1487
- description: "EBU R128 album loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256). readTags() converts to a decibel number",
1488
- type: "string",
1489
- supportedFormats: [
1490
- "ID3v2",
1491
- "MP4",
1492
- "Vorbis",
1493
- "ASF"
1494
- ],
1495
- mappings: {
1496
- id3v2: {
1497
- frame: "TXXX",
1498
- description: "R128_ALBUM_GAIN"
1499
- },
1500
- vorbis: "R128_ALBUM_GAIN",
1501
- mp4: "----:com.apple.iTunes:R128_ALBUM_GAIN"
1502
- }
1503
- },
1504
- acoustidFingerprint: {
1505
- key: "ACOUSTID_FINGERPRINT",
1506
- description: "AcoustID fingerprint (Chromaprint)",
1507
- type: "string",
1508
- supportedFormats: [
1509
- "ID3v2",
1510
- "MP4",
1511
- "Vorbis"
1512
- ],
1513
- mappings: {
1514
- id3v2: {
1515
- frame: "TXXX",
1516
- description: "Acoustid Fingerprint"
1517
- },
1518
- vorbis: "ACOUSTID_FINGERPRINT",
1519
- mp4: "----:com.apple.iTunes:Acoustid Fingerprint"
1520
- }
1521
- },
1522
- acoustidId: {
1523
- key: "ACOUSTID_ID",
1524
- description: "AcoustID UUID",
1525
- type: "string",
1526
- supportedFormats: [
1527
- "ID3v2",
1528
- "MP4",
1529
- "Vorbis"
1530
- ],
1531
- mappings: {
1532
- id3v2: {
1533
- frame: "TXXX",
1534
- description: "Acoustid Id"
1535
- },
1536
- vorbis: "ACOUSTID_ID",
1537
- mp4: "----:com.apple.iTunes:Acoustid Id"
1538
- }
1539
- },
1540
- appleSoundCheck: {
1541
- key: "ITUNNORM",
1542
- description: "Apple Sound Check normalization data",
1543
- type: "string",
1544
- supportedFormats: [
1545
- "ID3v2",
1546
- "MP4",
1547
- "Vorbis"
1548
- ],
1549
- mappings: {
1550
- id3v2: {
1551
- frame: "TXXX",
1552
- description: "iTunNORM"
1553
- },
1554
- vorbis: "ITUNNORM",
1555
- mp4: "----:com.apple.iTunes:iTunNORM"
1556
- }
1557
- },
1558
- appleGaplessInfo: {
1559
- key: "ITUNSMPB",
1560
- description: "Apple gapless playback data (encoder delay and padding)",
1561
- type: "string",
1562
- supportedFormats: [
1563
- "ID3v2",
1564
- "MP4",
1565
- "Vorbis"
1566
- ],
1567
- mappings: {
1568
- id3v2: {
1569
- frame: "TXXX",
1570
- description: "iTunSMPB"
1571
- },
1572
- vorbis: "ITUNSMPB",
1573
- mp4: "----:com.apple.iTunes:iTunSMPB"
1574
- }
1575
- }
1576
- };
1577
- }));
1578
- //#endregion
1579
- //#region src/constants/properties.ts
1580
- function toTagLibKey(key) {
1581
- return _toTagLib[key] ?? key;
1582
- }
1583
- function mp4AtomWireKey(atom) {
1584
- return _mp4AtomToWireKey[atom];
1585
- }
1586
- function mp4FreeformAtomNames(wireKeys) {
1587
- const names = [];
1588
- for (const key of wireKeys) {
1589
- const atom = _mp4FreeformAtoms[key];
1590
- if (atom !== void 0) names.push(atom);
1591
- }
1592
- return names;
1593
- }
1594
- function fromTagLibKey(key) {
1595
- return _fromTagLib[key] ?? key;
1596
- }
1597
- function remapKeysFromTagLib(obj) {
1598
- const result = {};
1599
- for (const [key, value] of Object.entries(obj)) {
1600
- const canonical = READ_ALIASES[key];
1601
- if (canonical !== void 0 && canonical in obj) continue;
1602
- result[fromTagLibKey(key)] = value;
1603
- }
1604
- return result;
1605
- }
1606
- var PROPERTIES, _toTagLib, _fromTagLib, READ_ALIASES, _mp4FreeformAtoms, _mp4AtomToWireKey;
1607
- var init_properties = __esmMin((() => {
1608
- init_additional_properties();
1609
- init_basic_properties();
1610
- init_general_extended_properties();
1611
- init_specialized_properties();
1612
- PROPERTIES = {
1613
- ...BASIC_PROPERTIES,
1614
- ...GENERAL_EXTENDED_PROPERTIES,
1615
- ...SPECIALIZED_PROPERTIES,
1616
- ...ADDITIONAL_PROPERTIES
1617
- };
1618
- _toTagLib = {};
1619
- _fromTagLib = {};
1620
- for (const [camelKey, meta] of Object.entries(PROPERTIES)) {
1621
- const wireKey = meta.key;
1622
- _toTagLib[camelKey] = wireKey;
1623
- _fromTagLib[wireKey] = camelKey;
1624
- }
1625
- _toTagLib["year"] = "DATE";
1626
- _toTagLib["track"] = "TRACKNUMBER";
1627
- _fromTagLib["disc"] = "discNumber";
1628
- READ_ALIASES = {
1629
- "ALBUM ARTIST": "ALBUMARTIST",
1630
- ALBUM_ARTIST: "ALBUMARTIST",
1631
- ORGANIZATION: "LABEL",
1632
- PUBLISHER: "LABEL",
1633
- UPC: "BARCODE",
1634
- EAN: "BARCODE",
1635
- GTIN: "BARCODE",
1636
- TOTALTRACKS: "TRACKTOTAL",
1637
- TOTALDISCS: "DISCTOTAL",
1638
- MUSICBRAINZ_ALBUMTYPE: "RELEASETYPE",
1639
- "MusicBrainz Album Type": "RELEASETYPE",
1640
- CONTENTADVISORY: "ITUNESADVISORY",
1641
- EXPLICIT: "ITUNESADVISORY"
1642
- };
1643
- for (const [alias, canonical] of Object.entries(READ_ALIASES)) if (_fromTagLib[alias] === void 0) _fromTagLib[alias] = _fromTagLib[canonical];
1644
- _mp4FreeformAtoms = {};
1645
- for (const meta of Object.values(PROPERTIES)) {
1646
- const { key, mappings } = meta;
1647
- const atom = mappings?.mp4;
1648
- if (typeof atom !== "string" || !atom.startsWith("----:")) continue;
1649
- const bare = atom.slice(atom.lastIndexOf(":") + 1);
1650
- if (bare === bare.toUpperCase()) continue;
1651
- _mp4FreeformAtoms[key] = atom;
1652
- const readKey = bare.toUpperCase();
1653
- const camel = _fromTagLib[key];
1654
- if (camel !== void 0 && _fromTagLib[readKey] === void 0) _fromTagLib[readKey] = camel;
1655
- }
1656
- _mp4AtomToWireKey = {};
1657
- for (const meta of Object.values(PROPERTIES)) {
1658
- const { key, mappings } = meta;
1659
- const atom = mappings?.mp4;
1660
- if (typeof atom !== "string" || atom.startsWith("----:")) continue;
1661
- if (_mp4AtomToWireKey[atom] === void 0) _mp4AtomToWireKey[atom] = key;
1662
- }
1663
- }));
1664
- //#endregion
1665
- //#region src/taglib/mp4-item-names.ts
1666
- var MP4_ITEM_NAMES_KEY;
1667
- var init_mp4_item_names = __esmMin((() => {
1668
- MP4_ITEM_NAMES_KEY = "_mp4ItemNames";
1669
- }));
1670
- //#endregion
1671
- //#region src/taglib/mutable-tag-impl.ts
1672
- function buildMutableTag(handle) {
1673
- let data = handle.getTagData();
1674
- const tag = {
1675
- get title() {
1676
- return data.title;
1677
- },
1678
- get artist() {
1679
- return data.artist;
1680
- },
1681
- get album() {
1682
- return data.album;
1683
- },
1684
- get comment() {
1685
- return data.comment;
1686
- },
1687
- get genre() {
1688
- return data.genre;
1689
- },
1690
- get year() {
1691
- return data.year;
1692
- },
1693
- get track() {
1694
- return data.track;
1695
- },
1696
- get date() {
1697
- return handle.getProperty("DATE") || void 0;
1698
- },
1699
- setTitle: (value) => {
1700
- handle.setTagData({ title: value });
1701
- data = handle.getTagData();
1702
- return tag;
1703
- },
1704
- setArtist: (value) => {
1705
- handle.setTagData({ artist: value });
1706
- data = handle.getTagData();
1707
- return tag;
1708
- },
1709
- setAlbum: (value) => {
1710
- handle.setTagData({ album: value });
1711
- data = handle.getTagData();
1712
- return tag;
1713
- },
1714
- setComment: (value) => {
1715
- handle.setTagData({ comment: value });
1716
- data = handle.getTagData();
1717
- return tag;
1718
- },
1719
- setGenre: (value) => {
1720
- handle.setTagData({ genre: value });
1721
- data = handle.getTagData();
1722
- return tag;
1723
- },
1724
- setYear: (value) => {
1725
- handle.setTagData({ year: value });
1726
- data = handle.getTagData();
1727
- return tag;
1728
- },
1729
- setTrack: (value) => {
1730
- const existing = value > 0 ? handle.getProperty(RAW_TRACK_WIRE_KEY) : "";
1731
- const slash = existing.indexOf("/");
1732
- if (slash !== -1) handle.setProperty(RAW_TRACK_WIRE_KEY, `${value}${existing.slice(slash)}`);
1733
- else handle.setTagData({ track: value });
1734
- data = handle.getTagData();
1735
- return tag;
1736
- },
1737
- setDate: (value) => {
1738
- if (value === "") handle.setTagData({ year: 0 });
1739
- else handle.setProperty("DATE", value);
1740
- data = handle.getTagData();
1741
- return tag;
1742
- }
1743
- };
1744
- return tag;
1745
- }
1746
- var RAW_TRACK_WIRE_KEY;
1747
- var init_mutable_tag_impl = __esmMin((() => {
1748
- init_properties();
1749
- RAW_TRACK_WIRE_KEY = toTagLibKey("trackNumber");
1750
- }));
1751
- //#endregion
1752
- //#region src/taglib/auto-dispose.ts
1753
- function registerAutoDispose(target, handle) {
1754
- registry.register(target, handle, target);
1755
- }
1756
- function unregisterAutoDispose(target) {
1757
- registry.unregister(target);
1758
- }
1759
- var registry;
1760
- var init_auto_dispose = __esmMin((() => {
1761
- registry = new FinalizationRegistry((handle) => {
1762
- handle.destroy();
1763
- });
1764
- }));
1765
- //#endregion
1766
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/typeof.js
1767
- function _typeof(o) {
1768
- "@babel/helpers - typeof";
1769
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
1770
- return typeof o;
1771
- } : function(o) {
1772
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
1773
- }, _typeof(o);
1774
- }
1775
- var init_typeof = __esmMin((() => {}));
1776
- //#endregion
1777
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPrimitive.js
1778
- function toPrimitive(t, r) {
1779
- if ("object" != _typeof(t) || !t) return t;
1780
- var e = t[Symbol.toPrimitive];
1781
- if (void 0 !== e) {
1782
- var i = e.call(t, r || "default");
1783
- if ("object" != _typeof(i)) return i;
1784
- throw new TypeError("@@toPrimitive must return a primitive value.");
1785
- }
1786
- return ("string" === r ? String : Number)(t);
1787
- }
1788
- var init_toPrimitive = __esmMin((() => {
1789
- init_typeof();
1790
- }));
1791
- //#endregion
1792
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/toPropertyKey.js
1793
- function toPropertyKey(t) {
1794
- var i = toPrimitive(t, "string");
1795
- return "symbol" == _typeof(i) ? i : i + "";
1796
- }
1797
- var init_toPropertyKey = __esmMin((() => {
1798
- init_typeof();
1799
- init_toPrimitive();
1800
- }));
1801
- //#endregion
1802
- //#region \0@oxc-project+runtime@0.152.0/helpers/esm/defineProperty.js
1803
- function _defineProperty(e, r, t) {
1804
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
1805
- value: t,
1806
- enumerable: !0,
1807
- configurable: !0,
1808
- writable: !0
1809
- }) : e[r] = t, e;
1810
- }
1811
- var init_defineProperty = __esmMin((() => {
1812
- init_toPropertyKey();
1813
- }));
1814
- //#endregion
1815
- //#region src/taglib/audio-file-base.ts
1816
- var _Symbol$dispose, LYRICS_PROPERTY_KEY, LYRICS_WIRE_KEY, EMPTY_KEY_SET, BaseAudioFileImpl;
1817
- var init_audio_file_base = __esmMin((() => {
1818
- init_properties();
1819
- init_errors();
1820
- init_mp4_item_names();
1821
- init_mutable_tag_impl();
1822
- init_auto_dispose();
1823
- init_defineProperty();
1824
- LYRICS_PROPERTY_KEY = "lyrics";
1825
- LYRICS_WIRE_KEY = toTagLibKey(LYRICS_PROPERTY_KEY);
1826
- EMPTY_KEY_SET = /* @__PURE__ */ new Set();
1827
- _Symbol$dispose = Symbol.dispose;
1828
- BaseAudioFileImpl = class {
1829
- constructor(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded = false, partialLoadOptions) {
1830
- this.module = module;
1831
- _defineProperty(this, "fileHandle", void 0);
1832
- _defineProperty(this, "cachedAudioProperties", null);
1833
- _defineProperty(this, "sourcePath", void 0);
1834
- _defineProperty(this, "originalSource", void 0);
1835
- _defineProperty(this, "isPartiallyLoaded", false);
1836
- _defineProperty(this, "partialLoadOptions", void 0);
1837
- _defineProperty(this, "partialKeysAtLoad", void 0);
1838
- this.fileHandle = fileHandle;
1839
- this.sourcePath = sourcePath;
1840
- this.originalSource = originalSource;
1841
- this.isPartiallyLoaded = isPartiallyLoaded;
1842
- this.partialLoadOptions = partialLoadOptions;
1843
- this.partialKeysAtLoad = isPartiallyLoaded ? new Set(Object.keys(fileHandle.getProperties())) : void 0;
1844
- registerAutoDispose(this, fileHandle);
1845
- }
1846
- partialDeletedPropertyKeys() {
1847
- if (!this.partialKeysAtLoad) return EMPTY_KEY_SET;
1848
- const current = new Set(Object.keys(this.handle.getProperties()));
1849
- const deleted = /* @__PURE__ */ new Set();
1850
- for (const key of this.partialKeysAtLoad) if (key !== LYRICS_WIRE_KEY && !current.has(key)) deleted.add(key);
1851
- return deleted;
1852
- }
1853
- get handle() {
1854
- if (!this.fileHandle) throw new MetadataError("read", "File handle has been disposed");
1855
- return this.fileHandle;
1856
- }
1857
- getFormat() {
1858
- return this.handle.getFormat();
1859
- }
1860
- isFormat(format) {
1861
- return this.getFormat() === format;
1862
- }
1863
- tag() {
1864
- return buildMutableTag(this.handle);
1865
- }
1866
- audioProperties() {
1867
- if (!this.cachedAudioProperties) this.cachedAudioProperties = this.handle.getAudioProperties() ?? null;
1868
- return this.cachedAudioProperties ?? void 0;
1869
- }
1870
- properties() {
1871
- const remapped = remapKeysFromTagLib(this.handle.getProperties());
1872
- delete remapped[LYRICS_PROPERTY_KEY];
1873
- return remapped;
1874
- }
1875
- setProperties(properties) {
1876
- const translated = {};
1877
- for (const [key, values] of Object.entries(properties)) if (values !== void 0) translated[toTagLibKey(fromTagLibKey(key))] = values;
1878
- if (!(LYRICS_WIRE_KEY in translated)) {
1879
- const existing = this.handle.getProperties()[LYRICS_WIRE_KEY];
1880
- if (existing !== void 0) translated[LYRICS_WIRE_KEY] = existing;
1881
- }
1882
- const atomNames = mp4FreeformAtomNames(Object.keys(translated));
1883
- if (atomNames.length > 0) translated[MP4_ITEM_NAMES_KEY] = atomNames;
1884
- this.handle.setProperties(translated);
1885
- }
1886
- getProperty(key) {
1887
- const wireKey = toTagLibKey(fromTagLibKey(key));
1888
- const values = this.handle.getProperties()[wireKey]?.filter((v) => v !== "");
1889
- if (values !== void 0 && values.length > 0) return values;
1890
- if (!this.isMP4()) return void 0;
1891
- const remapped = this.properties()[key]?.filter((v) => v !== "");
1892
- return remapped !== void 0 && remapped.length > 0 ? remapped : void 0;
1893
- }
1894
- setProperty(key, value) {
1895
- const wireKey = toTagLibKey(fromTagLibKey(key));
1896
- const atomNames = mp4FreeformAtomNames([wireKey]);
1897
- if (atomNames.length > 0 && this.isMP4()) {
1898
- if (value === "") {
1899
- const prior = this.handle.getMp4ItemRemovals?.() ?? [];
1900
- this.handle.setMp4ItemRemovals?.([.../* @__PURE__ */ new Set([...prior, ...atomNames])]);
1901
- if (this.module.isWasi) this.handle.setProperties({
1902
- ...this.handle.getProperties(),
1903
- [wireKey]: []
1904
- });
1905
- else {
1906
- const rest = { ...this.handle.getProperties() };
1907
- delete rest[wireKey];
1908
- this.handle.setProperties(rest);
1909
- }
1910
- return;
1911
- }
1912
- this.handle.setProperties({
1913
- ...this.handle.getProperties(),
1914
- [wireKey]: [value],
1915
- [MP4_ITEM_NAMES_KEY]: atomNames
1916
- });
1917
- return;
1918
- }
1919
- this.handle.setProperty(wireKey, value);
1920
- }
1921
- removeProperty(key) {
1922
- this.setProperty(key, "");
1923
- }
1924
- isMP4() {
1925
- return this.handle.isMP4();
1926
- }
1927
- getMP4Item(key) {
1928
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1929
- const wireKey = mp4AtomWireKey(key);
1930
- const value = wireKey !== void 0 ? this.handle.getProperty(wireKey) : this.handle.getMP4Item(key);
1931
- return value === "" ? void 0 : value;
1932
- }
1933
- setMP4Item(key, value) {
1934
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1935
- const wireKey = mp4AtomWireKey(key);
1936
- if (wireKey !== void 0) {
1937
- this.handle.setProperty(wireKey, value);
1938
- return;
1939
- }
1940
- this.handle.setMP4Item(key, value);
1941
- }
1942
- removeMP4Item(key) {
1943
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1944
- this.handle.removeMP4Item(key);
1945
- }
1946
- isValid() {
1947
- return this.handle.isValid();
1948
- }
1949
- dispose() {
1950
- unregisterAutoDispose(this);
1951
- if (this.fileHandle) {
1952
- this.fileHandle.destroy();
1953
- this.fileHandle = null;
1954
- this.cachedAudioProperties = null;
1955
- }
1956
- }
1957
- [_Symbol$dispose]() {
1958
- this.dispose();
1959
- }
1960
- };
1961
- }));
1962
- //#endregion
1963
- //#region src/taglib/metadata-extent.ts
1964
- function be32(b, offset) {
1965
- return (b[offset] << 24 | b[offset + 1] << 16 | b[offset + 2] << 8 | b[offset + 3]) >>> 0;
1966
- }
1967
- function startsWith(bytes, magic, at = 0) {
1968
- if (bytes.length < at + magic.length) return false;
1969
- for (let i = 0; i < magic.length; i++) if (bytes[at + i] !== magic.charCodeAt(i)) return false;
1970
- return true;
1971
- }
1972
- function id3v2End(bytes) {
1973
- if (!startsWith(bytes, "ID3") || bytes.length < 10) return void 0;
1974
- const size = bytes[6] << 21 | bytes[7] << 14 | bytes[8] << 7 | bytes[9];
1975
- const hasFooter = (bytes[5] & 16) !== 0;
1976
- return 10 + size + (hasFooter ? 10 : 0);
1977
- }
1978
- function flacEnd(bytes, limit, start) {
1979
- let offset = start + 4;
1980
- for (;;) {
1981
- if (offset + 4 > bytes.length) return void 0;
1982
- const isLast = (bytes[offset] & 128) !== 0;
1983
- const length = bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3];
1984
- offset += 4 + length;
1985
- if (offset > limit) return offset;
1986
- if (isLast) return offset;
1987
- }
1988
- }
1989
- function flacMarkerOffset(bytes) {
1990
- const at = startsWith(bytes, "ID3") ? id3v2End(bytes) : 0;
1991
- if (at === void 0) return void 0;
1992
- return startsWith(bytes, "fLaC", at) ? at : void 0;
1993
- }
1994
- function flacAudioStart(bytes) {
1995
- const at = flacMarkerOffset(bytes);
1996
- if (at === void 0) return void 0;
1997
- return flacEnd(bytes, bytes.length, at);
1998
- }
1999
- function mp4MoovEnd(bytes, limit, start) {
2000
- let offset = start;
2001
- const readable = Math.min(bytes.length, limit);
2002
- while (offset + 8 <= readable) {
2003
- const size = be32(bytes, offset);
2004
- const type = String.fromCharCode(bytes[offset + 4], bytes[offset + 5], bytes[offset + 6], bytes[offset + 7]);
2005
- if (size < 8) return void 0;
2006
- if (type === "moov") return offset + size;
2007
- offset += size;
2008
- }
2009
- }
2010
- function oggMetadataEnd(bytes, limit, start) {
2011
- let offset = start;
2012
- let packetsCompleted = 0;
2013
- let first = true;
2014
- for (;;) {
2015
- if (offset + 27 > bytes.length || !startsWith(bytes, "OggS", offset)) return;
2016
- const segmentCount = bytes[offset + 26];
2017
- const tableStart = offset + 27;
2018
- if (tableStart + segmentCount > bytes.length) return void 0;
2019
- let payload = 0;
2020
- for (let i = 0; i < segmentCount; i++) {
2021
- const segment = bytes[tableStart + i];
2022
- payload += segment;
2023
- if (segment < 255) packetsCompleted++;
2024
- }
2025
- if (first) {
2026
- const payloadStart = tableStart + segmentCount;
2027
- if (payloadStart + 5 > bytes.length) return void 0;
2028
- if (bytes[payloadStart] === 127 && startsWith(bytes, "FLAC", payloadStart + 1)) return;
2029
- first = false;
2030
- }
2031
- offset = tableStart + segmentCount + payload;
2032
- if (packetsCompleted >= 2 || offset > limit) return offset;
2033
- }
2034
- }
2035
- function mpegFrameLength(bytes, at) {
2036
- if (bytes.length < at + 4) return 0;
2037
- if (bytes[at] !== 255 || (bytes[at + 1] & 224) !== 224) return 0;
2038
- const version = bytes[at + 1] >> 3 & 3;
2039
- const layer = bytes[at + 1] >> 1 & 3;
2040
- if (version === 1 || layer === 0) return 0;
2041
- const bitrateIndex = bytes[at + 2] >> 4 & 15;
2042
- const sampleRateIndex = bytes[at + 2] >> 2 & 3;
2043
- if (bitrateIndex === 0 || bitrateIndex === 15 || sampleRateIndex === 3) return 0;
2044
- const mpeg1 = version === 3;
2045
- const layerIndex = layer ^ 3;
2046
- const bitrate = MPEG_BITRATES[mpeg1 ? 0 : 1][layerIndex][bitrateIndex];
2047
- const sampleRate = MPEG_SAMPLE_RATES[mpeg1 ? 0 : version === 2 ? 1 : 2][sampleRateIndex];
2048
- let frameLength = Math.floor((layerIndex === 2 ? mpeg1 ? 1152 : 576 : layerIndex === 1 ? 1152 : 384) * bitrate * 125 / sampleRate);
2049
- if ((bytes[at + 2] & 2) !== 0) frameLength += layerIndex === 0 ? 4 : 1;
2050
- return frameLength === 0 ? 0 : frameLength;
2051
- }
2052
- function isMpegFrameSync(bytes, at = 0) {
2053
- const frameLength = mpegFrameLength(bytes, at);
2054
- if (frameLength === 0) return false;
2055
- const next = at + frameLength;
2056
- if (bytes.length < next + 4) return false;
2057
- const mask = 4294839296;
2058
- return ((bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0 & mask) >>> 0 === ((bytes[next] << 24 | bytes[next + 1] << 16 | bytes[next + 2] << 8 | bytes[next + 3]) >>> 0 & mask) >>> 0;
2059
- }
2060
- function containerEnd(bytes, at, limit) {
2061
- if (at >= bytes.length) return bytes.length < limit ? null : void 0;
2062
- if (at + 8 > bytes.length) return void 0;
2063
- if (startsWith(bytes, "fLaC", at)) return flacEnd(bytes, limit, at);
2064
- if (startsWith(bytes, "ftyp", at + 4)) return mp4MoovEnd(bytes, limit, at);
2065
- if (startsWith(bytes, "OggS", at)) return oggMetadataEnd(bytes, limit, at);
2066
- return null;
2067
- }
2068
- function metadataFitsInHeader(header, limit) {
2069
- let end;
2070
- if (startsWith(header, "ID3")) {
2071
- const tagEnd = id3v2End(header);
2072
- if (tagEnd === void 0) return false;
2073
- end = tagEnd;
2074
- if (tagEnd <= limit) {
2075
- const behind = containerEnd(header, tagEnd, limit);
2076
- if (behind === void 0) return false;
2077
- if (behind !== null) end = behind;
2078
- }
2079
- } else {
2080
- const container = containerEnd(header, 0, limit);
2081
- if (container === null) end = isMpegFrameSync(header) ? 0 : void 0;
2082
- else end = container;
2083
- }
2084
- if (end === void 0 || end > header.length) return false;
2085
- return end <= limit;
2086
- }
2087
- function trailerFitsInFooter(tail, footerSize) {
2088
- if (tail.length < Math.min(footerSize, 32)) return false;
2089
- for (const offsetFromEnd of [32, 160]) {
2090
- const at = tail.length - offsetFromEnd;
2091
- if (at < 0 || !startsWith(tail, "APETAGEX", at)) continue;
2092
- const size = (tail[at + 12] | tail[at + 13] << 8 | tail[at + 14] << 16 | tail[at + 15] << 24) >>> 0;
2093
- const trailing = offsetFromEnd === 32 ? 0 : 128;
2094
- if (size + 32 + trailing > footerSize) return false;
2095
- }
2096
- return true;
2097
- }
2098
- var MPEG_BITRATES, MPEG_SAMPLE_RATES;
2099
- var init_metadata_extent = __esmMin((() => {
2100
- MPEG_BITRATES = [[
2101
- [
2102
- 0,
2103
- 32,
2104
- 64,
2105
- 96,
2106
- 128,
2107
- 160,
2108
- 192,
2109
- 224,
2110
- 256,
2111
- 288,
2112
- 320,
2113
- 352,
2114
- 384,
2115
- 416,
2116
- 448,
2117
- 0
2118
- ],
2119
- [
2120
- 0,
2121
- 32,
2122
- 48,
2123
- 56,
2124
- 64,
2125
- 80,
2126
- 96,
2127
- 112,
2128
- 128,
2129
- 160,
2130
- 192,
2131
- 224,
2132
- 256,
2133
- 320,
2134
- 384,
2135
- 0
2136
- ],
2137
- [
2138
- 0,
2139
- 32,
2140
- 40,
2141
- 48,
2142
- 56,
2143
- 64,
2144
- 80,
2145
- 96,
2146
- 112,
2147
- 128,
2148
- 160,
2149
- 192,
2150
- 224,
2151
- 256,
2152
- 320,
2153
- 0
2154
- ]
2155
- ], [
2156
- [
2157
- 0,
2158
- 32,
2159
- 48,
2160
- 56,
2161
- 64,
2162
- 80,
2163
- 96,
2164
- 112,
2165
- 128,
2166
- 144,
2167
- 160,
2168
- 176,
2169
- 192,
2170
- 224,
2171
- 256,
2172
- 0
2173
- ],
2174
- [
2175
- 0,
2176
- 8,
2177
- 16,
2178
- 24,
2179
- 32,
2180
- 40,
2181
- 48,
2182
- 56,
2183
- 64,
2184
- 80,
2185
- 96,
2186
- 112,
2187
- 128,
2188
- 144,
2189
- 160,
2190
- 0
2191
- ],
2192
- [
2193
- 0,
2194
- 8,
2195
- 16,
2196
- 24,
2197
- 32,
2198
- 40,
2199
- 48,
2200
- 56,
2201
- 64,
2202
- 80,
2203
- 96,
2204
- 112,
2205
- 128,
2206
- 144,
2207
- 160,
2208
- 0
2209
- ]
2210
- ]];
2211
- MPEG_SAMPLE_RATES = [
2212
- [
2213
- 44100,
2214
- 48e3,
2215
- 32e3
2216
- ],
2217
- [
2218
- 22050,
2219
- 24e3,
2220
- 16e3
2221
- ],
2222
- [
2223
- 11025,
2224
- 12e3,
2225
- 8e3
2226
- ]
2227
- ];
2228
- }));
2229
- //#endregion
2230
- //#region src/taglib/media-ranges.ts
2231
- function adtsFrameLength(bytes, at) {
2232
- if (bytes.length < at + 7) return 0;
2233
- if (bytes[at] !== 255 || (bytes[at + 1] & 246) !== 240) return 0;
2234
- const length = (bytes[at + 3] & 3) << 11 | bytes[at + 4] << 3 | bytes[at + 5] >> 5;
2235
- return length >= 7 ? length : 0;
2236
- }
2237
- function trailingTagStart(bytes, end = bytes.length) {
2238
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2239
- let at = Math.max(0, Math.min(end, bytes.length));
2240
- for (;;) {
2241
- if (at >= 128 && text(bytes, at - 128, 3) === "TAG") {
2242
- at -= 128;
2243
- continue;
2244
- }
2245
- if (at >= 32 && text(bytes, at - 32, 8) === "APETAGEX") {
2246
- const size = view.getUint32(at - 32 + 12, true);
2247
- const flags = view.getUint32(at - 32 + 20, true);
2248
- const start = at - size - ((flags & 2147483648) !== 0 ? 32 : 0);
2249
- if (start < 0 || start >= at) return at;
2250
- at = start;
2251
- continue;
2252
- }
2253
- return at;
2254
- }
2255
- }
2256
- function firstFrame(bytes) {
2257
- const from = id3v2End(bytes) ?? 0;
2258
- const limit = Math.min(bytes.length - 6, from + MPEG_SCAN_LIMIT);
2259
- for (let o = from; o < limit; o++) {
2260
- const len = frameLengthAt(bytes, o);
2261
- if (len > 0 && frameLengthAt(bytes, o + len) > 0) return o;
2262
- }
2263
- return -1;
2264
- }
2265
- function forwardLastFrame(bytes, from, end) {
2266
- let o = from;
2267
- let start = -1;
2268
- let length = 0;
2269
- let frames = 0;
2270
- while (o + 6 <= end) {
2271
- const len = frameLengthAt(bytes, o);
2272
- if (len === 0 || o + len > end) break;
2273
- start = o;
2274
- length = len;
2275
- frames++;
2276
- o += len;
2277
- }
2278
- return {
2279
- start,
2280
- length,
2281
- frames
2282
- };
2283
- }
2284
- function walkMpeg(bytes) {
2285
- const from = firstFrame(bytes);
2286
- if (from < 0) return fallback("no valid first frame");
2287
- const last = forwardLastFrame(bytes, from, trailingTagStart(bytes));
2288
- if (last.start < 0) return fallback("no valid frames");
2289
- return {
2290
- kind: "ranges",
2291
- ranges: [{
2292
- offset: from,
2293
- length: last.start + last.length - from
2294
- }],
2295
- detail: `first=${from} last=${last.start}+${last.length} frames=${last.frames}`
2296
- };
2297
- }
2298
- function flacStreamInfoMd5(bytes) {
2299
- const marker = flacMarkerOffset(bytes);
2300
- if (marker === void 0) return void 0;
2301
- const header = marker + 4;
2302
- if (header + 4 > bytes.length) return void 0;
2303
- if ((bytes[header] & 127) !== 0) return void 0;
2304
- if ((bytes[header + 1] << 16 | bytes[header + 2] << 8 | bytes[header + 3]) < 34) return void 0;
2305
- const payload = header + 4;
2306
- if (payload + 34 > bytes.length) return void 0;
2307
- let hex = "";
2308
- for (const byte of bytes.subarray(payload + 18, payload + 34)) hex += byte.toString(16).padStart(2, "0");
2309
- return hex;
2310
- }
2311
- function walkFlac(bytes) {
2312
- const start = flacAudioStart(bytes);
2313
- if (start === void 0) return fallback("no fLaC marker");
2314
- const end = trailingTagStart(bytes);
2315
- if (end <= start) return fallback("no audio bytes");
2316
- return {
2317
- kind: "ranges",
2318
- ranges: [{
2319
- offset: start,
2320
- length: end - start
2321
- }],
2322
- detail: `audioStart=${start} end=${end}`
2323
- };
2324
- }
2325
- function atomLength(bytes, view, o) {
2326
- const size = view.getUint32(o, false);
2327
- if (size === 0) return {
2328
- length: bytes.length - o,
2329
- headerSize: 8
2330
- };
2331
- if (size === 1) {
2332
- if (o + 16 > bytes.length) return void 0;
2333
- const big = view.getBigUint64(o + 8, false);
2334
- if (big > BigInt(Number.MAX_SAFE_INTEGER)) return void 0;
2335
- return {
2336
- length: Number(big),
2337
- headerSize: 16
2338
- };
2339
- }
2340
- return {
2341
- length: size,
2342
- headerSize: 8
2343
- };
2344
- }
2345
- function walkMp4(bytes) {
2346
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2347
- const ranges = [];
2348
- let o = 0;
2349
- while (o + 8 <= bytes.length) {
2350
- const type = text(bytes, o + 4, 4);
2351
- const atom = atomLength(bytes, view, o);
2352
- if (atom === void 0) return fallback(`malformed ${type} size`);
2353
- if (atom.length < atom.headerSize) return fallback(`malformed ${type} size`);
2354
- if (o + atom.length > bytes.length) return fallback(`oversized ${type}`);
2355
- if (type === "mdat" && atom.length > atom.headerSize) ranges.push({
2356
- offset: o + atom.headerSize,
2357
- length: atom.length - atom.headerSize
2358
- });
2359
- o += atom.length;
2360
- }
2361
- if (o !== bytes.length) return fallback("trailing bytes after the last atom");
2362
- if (ranges.length === 0) return fallback("no non-empty mdat");
2363
- return {
2364
- kind: "ranges",
2365
- ranges,
2366
- detail: `${ranges.length} mdat(s)`
2367
- };
2368
- }
2369
- function walkWav(bytes) {
2370
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2371
- if (text(bytes, 0, 4) !== "RIFF") return fallback("not RIFF");
2372
- if (text(bytes, 8, 4) !== "WAVE") return fallback("not WAVE");
2373
- const ranges = [];
2374
- let o = 12;
2375
- while (o + 8 <= bytes.length) {
2376
- const id = text(bytes, o, 4);
2377
- const size = view.getUint32(o + 4, true);
2378
- const dataStart = o + 8;
2379
- if (dataStart + size > bytes.length) return fallback(`truncated ${id}`);
2380
- if (id === "data" && size > 0) ranges.push({
2381
- offset: dataStart,
2382
- length: size
2383
- });
2384
- o = dataStart + size + size % 2;
2385
- }
2386
- if (ranges.length === 0) return fallback("no data chunk");
2387
- return {
2388
- kind: "ranges",
2389
- ranges,
2390
- detail: `${ranges.length} data chunk(s)`
2391
- };
2392
- }
2393
- function mediaRanges(format, bytes) {
2394
- const walked = (() => {
2395
- switch (format.toUpperCase()) {
2396
- case "MP3":
2397
- case "AAC": return walkMpeg(bytes);
2398
- case "FLAC": return walkFlac(bytes);
2399
- case "MP4":
2400
- case "M4A": return walkMp4(bytes);
2401
- case "WAV": return walkWav(bytes);
2402
- default: return {
2403
- kind: "fallback",
2404
- ranges: [],
2405
- detail: "format not covered"
2406
- };
2407
- }
2408
- })();
2409
- if (walked.kind === "fallback") return {
2410
- kind: "fallback",
2411
- ranges: [{
2412
- offset: 0,
2413
- length: bytes.length
2414
- }],
2415
- detail: `${walked.detail} → whole file`
2416
- };
2417
- return walked;
2418
- }
2419
- var decoder, text, fallback, frameLengthAt, MPEG_SCAN_LIMIT;
2420
- var init_media_ranges = __esmMin((() => {
2421
- init_metadata_extent();
2422
- decoder = new TextDecoder();
2423
- text = (b, o, n) => decoder.decode(b.subarray(o, o + n));
2424
- fallback = (detail) => ({
2425
- kind: "fallback",
2426
- ranges: [],
2427
- detail
2428
- });
2429
- frameLengthAt = (bytes, at) => mpegFrameLength(bytes, at) || adtsFrameLength(bytes, at);
2430
- MPEG_SCAN_LIMIT = 65536;
2431
- }));
2432
- //#endregion
2433
- //#region src/taglib/audio-file-checksum.ts
2434
- async function fileBytes(source, io) {
2435
- if (source.path) return await io.readFile(source.path);
2436
- if (source.blob) return new Uint8Array(await source.blob.arrayBuffer());
2437
- if (!source.partiallyLoaded && source.bytes.length > 0) return source.bytes;
2438
- throw new MetadataError("read", "the handle holds no file bytes and has no readable source; a partial handle that has been saved drops its source — checksum the saved path instead");
2439
- }
2440
- function joinRanges(bytes, ranges) {
2441
- const total = ranges.reduce((n, r) => n + r.length, 0);
2442
- const overrun = ranges.find((r) => r.offset + r.length > bytes.length);
2443
- if (overrun || total > bytes.length) throw new MetadataError("read", `range walk overran the buffer (${overrun ? `range ${overrun.offset}+${overrun.length}` : `${total} bytes`} past the ${bytes.length}-byte buffer)`);
2444
- if (ranges.length === 1) {
2445
- const only = ranges[0];
2446
- const view = bytes.subarray(only.offset, only.offset + only.length);
2447
- return view.buffer instanceof ArrayBuffer ? view : new Uint8Array(view);
2448
- }
2449
- const out = new Uint8Array(total);
2450
- let at = 0;
2451
- for (const r of ranges) {
2452
- out.set(bytes.subarray(r.offset, r.offset + r.length), at);
2453
- at += r.length;
2454
- }
2455
- return out;
2456
- }
2457
- async function mediaChecksum(source, format, io, options = {}) {
2458
- if (options.basis === "pcm") {
2459
- if (format.toUpperCase() !== "FLAC") throw new UnsupportedFormatError(format, ["FLAC"], { operation: "media checksum (basis: pcm)" });
2460
- const windowed = source.bytes.length > 0 ? source.bytes : source.path && io.readPartial ? await io.readPartial(source.path, STREAMINFO_WINDOW, 0) : void 0;
2461
- let md5 = windowed === void 0 ? void 0 : flacStreamInfoMd5(windowed);
2462
- if (md5 === void 0 && windowed !== source.bytes) md5 = flacStreamInfoMd5(await fileBytes(source, io));
2463
- if (md5 === void 0) throw new MetadataError("read", "STREAMINFO digest unavailable");
2464
- return {
2465
- source: "flac-streaminfo-md5",
2466
- algorithm: "md5",
2467
- hex: md5,
2468
- bytesHashed: 16
2469
- };
2470
- }
2471
- const bytes = await fileBytes(source, io);
2472
- const walk = mediaRanges(format, bytes);
2473
- const payload = joinRanges(bytes, walk.ranges);
2474
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", payload));
2475
- let hex = "";
2476
- for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
2477
- return {
2478
- source: walk.kind === "ranges" ? "audio-payload" : "file",
2479
- algorithm: "sha256",
2480
- hex,
2481
- bytesHashed: payload.length
2482
- };
2483
- }
2484
- var STREAMINFO_WINDOW;
2485
- var init_audio_file_checksum = __esmMin((() => {
2486
- init_media_ranges();
2487
- init_errors();
2488
- STREAMINFO_WINDOW = 65536;
2489
- }));
2490
- //#endregion
2491
- //#region src/utils/file.ts
2492
- async function readFileData(file) {
2493
- if (file instanceof Uint8Array) return file;
2494
- if (file instanceof ArrayBuffer) return new Uint8Array(file);
2495
- if (typeof File !== "undefined" && file instanceof File) return new Uint8Array(await file.arrayBuffer());
2496
- if (typeof file === "string") try {
2497
- return await getPlatformIO().readFile(file);
2498
- } catch (error) {
2499
- if (error instanceof EnvironmentError) throw error;
2500
- throw new FileOperationError("read", error.message, file);
2501
- }
2502
- const inputType = Object.prototype.toString.call(file);
2503
- throw new FileOperationError("read", `Invalid file input type: ${inputType}. Expected string path, Uint8Array, ArrayBuffer, or File object.`);
2504
- }
2505
- async function getFileSize(path) {
2506
- try {
2507
- return (await getPlatformIO().stat(path)).size;
2508
- } catch (error) {
2509
- if (error instanceof EnvironmentError) throw error;
2510
- throw new FileOperationError("stat", error.message, path);
2511
- }
2512
- }
2513
- async function readPartialFileData(path, headerSize, footerSize) {
2514
- const io = getPlatformIO();
2515
- if (!io.readPartial) throw new EnvironmentError("current runtime", "does not support partial file reading", "filesystem access with seek support");
2516
- try {
2517
- return await io.readPartial(path, headerSize, footerSize);
2518
- } catch (error) {
2519
- if (error instanceof EnvironmentError) throw error;
2520
- throw new FileOperationError("read", error.message, path);
2521
- }
2522
- }
2523
- var init_file = __esmMin((() => {
2524
- init_errors();
2525
- init__taglib_platform_io_stub();
2526
- }));
2527
- //#endregion
2528
- //#region src/taglib/embind-adapter.ts
2529
- function isValidBitrateMode(value) {
2530
- return value === "CBR" || value === "VBR" || value === "ABR";
2531
- }
2532
- function wrapEmbindHandle(raw) {
2533
- const stagedId3v2Frames = {};
2534
- let destroyed = false;
2535
- const overrides = {
2536
- getTagData() {
2537
- const tw = raw.getTag();
2538
- return {
2539
- title: tw.title(),
2540
- artist: tw.artist(),
2541
- album: tw.album(),
2542
- comment: tw.comment(),
2543
- genre: tw.genre(),
2544
- year: tw.year(),
2545
- track: tw.track()
2546
- };
2547
- },
2548
- setTagData(data) {
2549
- const tw = raw.getTag();
2550
- if (data.title !== void 0) tw.setTitle(data.title);
2551
- if (data.artist !== void 0) tw.setArtist(data.artist);
2552
- if (data.album !== void 0) tw.setAlbum(data.album);
2553
- if (data.comment !== void 0) tw.setComment(data.comment);
2554
- if (data.genre !== void 0) tw.setGenre(data.genre);
2555
- if (data.year !== void 0) tw.setYear(data.year);
2556
- if (data.track !== void 0) tw.setTrack(data.track);
2557
- },
2558
- getBextData() {
2559
- const v = raw.getBextData();
2560
- if (v === void 0 || v === null) return void 0;
2561
- const u8 = v instanceof Uint8Array ? v : new Uint8Array(v);
2562
- return u8.length > 0 ? u8 : void 0;
2563
- },
2564
- setBextData(data) {
2565
- raw.setBextData(data ?? null);
2566
- },
2567
- getIxml() {
2568
- const v = raw.getIxml();
2569
- return typeof v === "string" && v.length > 0 ? v : void 0;
2570
- },
2571
- setIxml(data) {
2572
- raw.setIxml(data ?? null);
2573
- },
2574
- getLyrics() {
2575
- return (raw.getProperties()["LYRICS"] ?? []).map((text) => ({
2576
- text,
2577
- description: "",
2578
- language: ""
2579
- }));
2580
- },
2581
- setLyrics(lyrics) {
2582
- const handle = raw;
2583
- const props = handle.getProperties();
2584
- if (lyrics.length > 0) props["LYRICS"] = lyrics.map((l) => l.text);
2585
- else delete props["LYRICS"];
2586
- handle.setProperties(props);
2587
- },
2588
- setId3v2Frames(id, data) {
2589
- stagedId3v2Frames[id] = data.map((d) => new Uint8Array(d));
2590
- raw.setId3v2Frames(id, data);
2591
- },
2592
- removeId3v2Frames(id) {
2593
- stagedId3v2Frames[id] = [];
2594
- raw.removeId3v2Frames(id);
2595
- },
2596
- getStagedId3v2Frames() {
2597
- return Object.keys(stagedId3v2Frames).length > 0 ? { ...stagedId3v2Frames } : void 0;
2598
- },
2599
- hasId3Tags() {
2600
- const v = raw.hasId3Tags();
2601
- if (!v || typeof v !== "object") return {
2602
- v1: false,
2603
- v2: false
2604
- };
2605
- const o = v;
2606
- return {
2607
- v1: o.v1 === true,
2608
- v2: o.v2 === true
2609
- };
2610
- },
2611
- stripId3Tags(opts) {
2612
- raw.stripId3Tags(opts);
2613
- },
2614
- destroy() {
2615
- if (destroyed) return;
2616
- destroyed = true;
2617
- raw.destroy();
2618
- },
2619
- get destroyed() {
2620
- return destroyed;
2621
- },
2622
- setMp4ItemRemovals(removals) {
2623
- const handle = raw;
2624
- for (const name of removals) handle.removeMP4Item(name);
2625
- },
2626
- getAudioProperties() {
2627
- const pw = raw.getAudioProperties();
2628
- if (!pw) return null;
2629
- const containerFormat = pw.containerFormat() || "unknown";
2630
- const codec = pw.codec() || "unknown";
2631
- const mpegVersion = pw.mpegVersion();
2632
- const formatVersion = pw.formatVersion();
2633
- const bitrateMode = pw.bitrateMode();
2634
- const isEncrypted = pw.isEncrypted();
2635
- return {
2636
- duration: pw.lengthInSeconds(),
2637
- durationMs: pw.lengthInMilliseconds(),
2638
- bitrate: pw.bitrate(),
2639
- sampleRate: pw.sampleRate(),
2640
- channels: pw.channels(),
2641
- bitsPerSample: pw.bitsPerSample(),
2642
- codec,
2643
- containerFormat,
2644
- isLossless: pw.isLossless(),
2645
- ...mpegVersion > 0 ? {
2646
- mpegVersion,
2647
- mpegLayer: pw.mpegLayer()
2648
- } : {},
2649
- ...isEncrypted || containerFormat === "MP4" || containerFormat === "ASF" ? { isEncrypted } : {},
2650
- ...formatVersion > 0 ? { formatVersion } : {},
2651
- ...isValidBitrateMode(bitrateMode) ? { bitrateMode } : {},
2652
- ...containerFormat === "OGG" && codec === "Opus" ? { outputGainDb: pw.outputGainDb() } : {}
2653
- };
2654
- }
2655
- };
2656
- return new Proxy(raw, { get(target, prop, receiver) {
2657
- if (prop in overrides) return overrides[prop];
2658
- const value = Reflect.get(target, prop, receiver);
2659
- return typeof value === "function" ? value.bind(target) : value;
2660
- } });
2661
- }
2662
- var init_embind_adapter = __esmMin((() => {}));
2663
- //#endregion
2664
- //#region src/taglib/extra-state-registry.ts
2665
- function chapterStyle(chapters) {
2666
- const s = chapters[0]?.source;
2667
- return s === "nero" || s === "both" ? s : "quicktime";
2668
- }
2669
- function copyExtraState(target, source, sourceComplete) {
2670
- for (const field of EXTRA_FIELDS) field.copy(target, source, sourceComplete);
2671
- }
2672
- var EXTRA_FIELDS;
2673
- var init_extra_state_registry = __esmMin((() => {
2674
- EXTRA_FIELDS = [
2675
- {
2676
- name: "pictures",
2677
- copy(target, source, complete) {
2678
- const v = source.getPictures();
2679
- if (complete || v.length > 0) target.setPictures(v);
2680
- }
2681
- },
2682
- {
2683
- name: "ratings",
2684
- copy(target, source, complete) {
2685
- const v = source.getRatings();
2686
- if (complete || v.length > 0) target.setRatings(v);
2687
- }
2688
- },
2689
- {
2690
- name: "lyrics",
2691
- copy(target, source, complete) {
2692
- const v = source.getLyrics();
2693
- if (complete || v.length > 0) target.setLyrics(v);
2694
- }
2695
- },
2696
- {
2697
- name: "chapters",
2698
- copy(target, source, complete) {
2699
- const v = source.getChapters();
2700
- if (complete || v.length > 0) target.setChapters(v, chapterStyle(v));
2701
- }
2702
- },
2703
- {
2704
- name: "bextData",
2705
- copy(target, source, complete) {
2706
- const v = source.getBextData();
2707
- if (v !== void 0) target.setBextData(v);
2708
- else if (complete) target.setBextData(null);
2709
- }
2710
- },
2711
- {
2712
- name: "ixml",
2713
- copy(target, source, complete) {
2714
- const v = source.getIxml();
2715
- if (v !== void 0) target.setIxml(v);
2716
- else if (complete) target.setIxml(null);
2717
- }
2718
- },
2719
- {
2720
- name: "_mp4ItemRemovals",
2721
- copy(target, source, complete) {
2722
- const v = source.getMp4ItemRemovals?.();
2723
- if (complete || v !== void 0 && v.length > 0) target.setMp4ItemRemovals?.(v ?? []);
2724
- }
2725
- },
2726
- {
2727
- name: "id3v2Frames",
2728
- copy(target, source) {
2729
- const staged = source.getStagedId3v2Frames?.();
2730
- if (!staged) return;
2731
- for (const [id, bodies] of Object.entries(staged)) target.setId3v2Frames(id, bodies);
2732
- }
2733
- }
2734
- ];
2735
- }));
2736
- //#endregion
2737
- //#region src/taglib/save-reconstruct.ts
2738
- function copyEditedState(target, source, sourceComplete, deletedKeys) {
2739
- target.setTagData(source.getTagData());
2740
- const merged = sourceComplete ? source.getProperties() : {
2741
- ...target.getProperties(),
2742
- ...source.getProperties()
2743
- };
2744
- for (const key of deletedKeys) delete merged[key];
2745
- const atomNames = mp4FreeformAtomNames(Object.keys(merged));
2746
- if (atomNames.length > 0) merged[MP4_ITEM_NAMES_KEY] = atomNames;
2747
- target.setProperties(merged);
2748
- copyExtraState(target, source, sourceComplete);
2749
- }
2750
- async function saveViaFreshHandle(module, editing, source, targetPath, sourceComplete, deletedKeys = /* @__PURE__ */ new Set()) {
2751
- const rawFullHandle = module.createFileHandle();
2752
- const fullFileHandle = module.isWasi ? rawFullHandle : wrapEmbindHandle(rawFullHandle);
2753
- try {
2754
- {
2755
- const data = await readFileData(source);
2756
- if (!fullFileHandle.loadFromBuffer(data)) throw new InvalidFormatError("Failed to load full audio file for saving");
2757
- }
2758
- copyEditedState(fullFileHandle, editing, sourceComplete, deletedKeys);
2759
- if (!fullFileHandle.save()) throw new FileOperationError("save", "Failed to save changes to full file");
2760
- await writeFileData(targetPath, fullFileHandle.getBuffer());
2761
- } finally {
2762
- fullFileHandle.destroy();
2763
- }
2764
- }
2765
- var init_save_reconstruct = __esmMin((() => {
2766
- init_errors();
2767
- init_file();
2768
- init_write();
2769
- init_embind_adapter();
2770
- init_extra_state_registry();
2771
- init_properties();
2772
- init_mp4_item_names();
2773
- }));
2774
- //#endregion
2775
- //#region src/taglib/audio-file-impl.ts
2776
- function sortChapters(list) {
2777
- return [...list].sort((a, b) => a.startTimeMs - b.startTimeMs);
2778
- }
2779
- function inferEndTimeMs(sorted, index, trackEndMs) {
2780
- const own = sorted[index].endTimeMs;
2781
- if (own !== void 0) return own;
2782
- const next = sorted[index + 1];
2783
- return next ? next.startTimeMs : trackEndMs;
2784
- }
2785
- function readFileSync(path) {
2786
- if (isDeno()) return Deno.readFileSync(path);
2787
- const fs = getNodeFsSync();
2788
- if (fs) return new Uint8Array(fs.readFileSync(path));
2789
- throw new FileOperationError("read", "node:fs is unavailable in this runtime: cannot read file data from disk", path);
2790
- }
2791
- var AudioFileImpl;
2792
- var init_audio_file_impl = __esmMin((() => {
2793
- init_types();
2794
- init_audio_file_bwf();
2795
- init_id3v2_frames();
2796
- init_errors();
2797
- init_write();
2798
- init__taglib_node_fs_stub();
2799
- init_rating();
2800
- init_detector();
2801
- init_audio_file_base();
2802
- init_audio_file_checksum();
2803
- init__taglib_platform_io_stub();
2804
- init_save_reconstruct();
2805
- init_defineProperty();
2806
- AudioFileImpl = class extends BaseAudioFileImpl {
2807
- constructor(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded = false, partialLoadOptions) {
2808
- super(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded, partialLoadOptions);
2809
- _defineProperty(this, "pathModeBuffer", null);
2810
- _defineProperty(this, "partiallyLoadedAtConstruction", void 0);
2811
- this.partiallyLoadedAtConstruction = isPartiallyLoaded;
2812
- }
2813
- save() {
2814
- if (this.isPartiallyLoaded && this.originalSource) throw new FileOperationError("save", "Cannot save partially loaded file directly. Use saveToFile() instead");
2815
- this.cachedAudioProperties = null;
2816
- this.pathModeBuffer = null;
2817
- return this.handle.save();
2818
- }
2819
- getFileBuffer() {
2820
- const buffer = this.handle.getBuffer();
2821
- if (buffer.length > 0) return buffer;
2822
- if (this.pathModeBuffer) return this.pathModeBuffer;
2823
- if (this.sourcePath) try {
2824
- this.pathModeBuffer = readFileSync(this.sourcePath);
2825
- return this.pathModeBuffer;
2826
- } catch (error) {
2827
- if (error instanceof FileOperationError) throw error;
2828
- throw new FileOperationError("read", `Cannot return file data: ${errorMessage(error)}`, this.sourcePath, { cause: error });
2829
- }
2830
- throw new FileOperationError("read", "No file data available: in-memory buffer is empty and no source path is set");
2831
- }
2832
- mediaChecksum(options) {
2833
- return mediaChecksum({
2834
- bytes: this.handle.getBuffer(),
2835
- ...this.sourcePath !== void 0 ? { path: this.sourcePath } : {},
2836
- ...this.originalSource instanceof Blob ? { blob: this.originalSource } : {},
2837
- partiallyLoaded: this.partiallyLoadedAtConstruction
2838
- }, this.getFormat(), getPlatformIO(), options);
2839
- }
2840
- async saveToFile(path) {
2841
- const targetPath = path ?? this.sourcePath;
2842
- if (!targetPath) throw new FileOperationError("save", "No file path available. Provide a path or open the file from a path");
2843
- if (this.isPartiallyLoaded && this.originalSource) {
2844
- await saveViaFreshHandle(this.module, this.handle, this.originalSource, targetPath, false, this.partialDeletedPropertyKeys());
2845
- this.isPartiallyLoaded = false;
2846
- this.originalSource = void 0;
2847
- } else if (this.module.isWasi && this.sourcePath && targetPath !== this.sourcePath) await saveViaFreshHandle(this.module, this.handle, this.sourcePath, targetPath, true);
2848
- else {
2849
- if (!this.save()) throw new FileOperationError("save", "Failed to save changes to in-memory buffer");
2850
- const buffer = this.handle.getBuffer();
2851
- if (buffer.length > 0) await writeFileData(targetPath, buffer);
2852
- }
2853
- this.pathModeBuffer = null;
2854
- }
2855
- getPictures() {
2856
- return this.handle.getPictures().map((pic) => ({
2857
- mimeType: pic.mimeType,
2858
- data: pic.data,
2859
- type: PICTURE_TYPE_NAMES[pic.type] ?? "Other",
2860
- ...pic.description !== void 0 ? { description: pic.description } : {}
2861
- }));
2862
- }
2863
- setPictures(pictures) {
2864
- this.handle.setPictures(pictures.map((pic) => ({
2865
- mimeType: pic.mimeType,
2866
- data: pic.data,
2867
- type: PICTURE_TYPE_VALUES[pic.type] ?? 0,
2868
- description: pic.description ?? ""
2869
- })));
2870
- }
2871
- addPicture(picture) {
2872
- this.handle.addPicture({
2873
- mimeType: picture.mimeType,
2874
- data: picture.data,
2875
- type: PICTURE_TYPE_VALUES[picture.type] ?? 0,
2876
- description: picture.description ?? ""
2877
- });
2878
- }
2879
- removePictures() {
2880
- this.handle.removePictures();
2881
- }
2882
- getChapters() {
2883
- const sorted = sortChapters(this.handle.getChapters());
2884
- const trackEndMs = this.audioProperties()?.durationMs;
2885
- return sorted.map((c, i) => {
2886
- const endTimeMs = inferEndTimeMs(sorted, i, trackEndMs);
2887
- return {
2888
- startTimeMs: c.startTimeMs,
2889
- ...endTimeMs !== void 0 ? { endTimeMs } : {},
2890
- ...c.title ? { title: c.title } : {},
2891
- ...c.id ? { id: c.id } : {},
2892
- ...c.source !== void 0 ? { source: c.source } : {}
2893
- };
2894
- });
2895
- }
2896
- setChapters(chapters, options) {
2897
- const fmt = this.getFormat();
2898
- if (fmt !== "MP3" && fmt !== "AAC" && fmt !== "MP4") throw new UnsupportedFormatError(fmt, [
2899
- "MP3",
2900
- "AAC",
2901
- "MP4"
2902
- ], { operation: "setChapters" });
2903
- const sorted = sortChapters(chapters);
2904
- const trackEndMs = this.audioProperties()?.durationMs;
2905
- const style = options?.mp4ChapterStyle ?? "quicktime";
2906
- const source = fmt === "MP4" ? style : "id3";
2907
- const raw = sorted.map((c, i) => ({
2908
- ...c.id !== void 0 ? { id: c.id } : {},
2909
- startTimeMs: c.startTimeMs,
2910
- endTimeMs: inferEndTimeMs(sorted, i, trackEndMs) ?? c.startTimeMs,
2911
- ...c.title !== void 0 ? { title: c.title } : {},
2912
- source
2913
- }));
2914
- this.handle.setChapters(raw, style);
2915
- }
2916
- getBext() {
2917
- return getBext(this.handle);
2918
- }
2919
- setBext(bext) {
2920
- setBext(this.handle, this.getFormat(), bext);
2921
- }
2922
- getBextData() {
2923
- return getBextData(this.handle);
2924
- }
2925
- setBextData(data) {
2926
- setBextData(this.handle, this.getFormat(), data);
2927
- }
2928
- getIxml() {
2929
- return getIxml(this.handle);
2930
- }
2931
- setIxml(data) {
2932
- setIxml(this.handle, this.getFormat(), data);
2933
- }
2934
- getRatings() {
2935
- return this.handle.getRatings().map((r) => ({
2936
- rating: r.rating,
2937
- ...r.email !== void 0 && r.email !== "" ? { email: r.email } : {},
2938
- ...r.counter !== 0 ? { counter: r.counter } : {}
2939
- }));
2940
- }
2941
- setRatings(ratings) {
2942
- this.handle.setRatings(ratings.map((r) => ({
2943
- rating: r.rating,
2944
- email: r.email ?? "",
2945
- counter: r.counter ?? 0
2946
- })));
2947
- }
2948
- getLyrics() {
2949
- return this.handle.getLyrics().map((l) => {
2950
- const out = { text: l.text };
2951
- if (l.description) out.description = l.description;
2952
- if (l.language) out.language = l.language;
2953
- return out;
2954
- });
2955
- }
2956
- setLyrics(lyrics) {
2957
- this.handle.setLyrics(lyrics.map((l) => ({
2958
- text: l.text,
2959
- description: l.description ?? "",
2960
- language: l.language ?? ""
2961
- })));
2962
- }
2963
- getRating() {
2964
- const ratings = this.getRatings();
2965
- return ratings.length > 0 ? normalized(ratings[0].rating) : void 0;
2966
- }
2967
- setRating(rating, email) {
2968
- this.setRatings([{
2969
- rating,
2970
- ...email !== void 0 ? { email } : {},
2971
- counter: 0
2972
- }]);
2973
- }
2974
- getId3v2Frames(id) {
2975
- assertMp3(this.getFormat());
2976
- if (id !== void 0) assertFrameId(id, "read");
2977
- return this.handle.getId3v2Frames(id ?? "").map(toPublicFrame);
2978
- }
2979
- setId3v2Frames(id, data) {
2980
- assertMp3(this.getFormat());
2981
- assertFrameId(id, "write");
2982
- assertFrameBodies(id, data);
2983
- this.handle.setId3v2Frames(id, data);
2984
- }
2985
- removeId3v2Frames(id) {
2986
- assertMp3(this.getFormat());
2987
- assertFrameId(id, "write");
2988
- this.handle.removeId3v2Frames(id);
2989
- }
2990
- hasId3Tags() {
2991
- return this.handle.hasId3Tags();
2992
- }
2993
- stripId3Tags(opts) {
2994
- this.handle.stripId3Tags({
2995
- v1: opts?.v1 ?? true,
2996
- v2: opts?.v2 ?? true
2997
- });
2998
- }
2999
- };
3000
- }));
3001
- //#endregion
3002
- //#region src/taglib/load-audio-data.ts
3003
- async function loadAudioData(input, opts) {
3004
- if (opts.partial && typeof File !== "undefined" && input instanceof File) {
3005
- const headerSize = Math.min(opts.maxHeaderSize, input.size);
3006
- const footerSize = Math.min(opts.maxFooterSize, input.size);
3007
- if (input.size <= headerSize + footerSize) return {
3008
- data: await readFileData(input),
3009
- isPartiallyLoaded: false
3010
- };
3011
- const header = new Uint8Array(await input.slice(0, headerSize).arrayBuffer());
3012
- if (!metadataFitsInHeader(header, headerSize)) return {
3013
- data: await readFileData(input),
3014
- isPartiallyLoaded: false
3015
- };
3016
- const footerStart = Math.max(0, input.size - footerSize);
3017
- const footer = new Uint8Array(await input.slice(footerStart).arrayBuffer());
3018
- if (!trailerFitsInFooter(footer, footerSize)) return {
3019
- data: await readFileData(input),
3020
- isPartiallyLoaded: false
3021
- };
3022
- const combined = new Uint8Array(header.byteLength + footer.byteLength);
3023
- combined.set(header, 0);
3024
- combined.set(footer, header.byteLength);
3025
- return {
3026
- data: combined,
3027
- isPartiallyLoaded: true
3028
- };
3029
- }
3030
- if (opts.partial && typeof input === "string") {
3031
- if (await getFileSize(input) > opts.maxHeaderSize + opts.maxFooterSize) {
3032
- const data = await readPartialFileData(input, opts.maxHeaderSize, opts.maxFooterSize);
3033
- if (metadataFitsInHeader(data, opts.maxHeaderSize) && trailerFitsInFooter(data, opts.maxFooterSize)) return {
3034
- data,
3035
- isPartiallyLoaded: true
3036
- };
3037
- }
3038
- return {
3039
- data: await readFileData(input),
3040
- isPartiallyLoaded: false
3041
- };
3042
- }
3043
- return {
3044
- data: await readFileData(input),
3045
- isPartiallyLoaded: false
3046
- };
3047
- }
3048
- var init_load_audio_data = __esmMin((() => {
3049
- init_file();
3050
- init_metadata_extent();
3051
- }));
3052
- //#endregion
3053
- //#region src/utils/mirror-fields.ts
3054
- function parseLeadingInt(raw) {
3055
- const parsed = Number.parseInt(raw, 10);
3056
- return Number.isNaN(parsed) ? void 0 : parsed;
3057
- }
3058
- var MIRROR_FIELDS;
3059
- var init_mirror_fields = __esmMin((() => {
3060
- MIRROR_FIELDS = [{
3061
- raw: "date",
3062
- numeric: "year"
3063
- }, {
3064
- raw: "trackNumber",
3065
- numeric: "track"
3066
- }];
3067
- MIRROR_FIELDS[0];
3068
- MIRROR_FIELDS[1];
3069
- }));
3070
- //#endregion
3071
- //#region src/utils/tag-mapping.ts
3072
- function readExtendedTag(audioFile, includeProperties) {
3073
- const props = audioFile.properties();
3074
- const tag = mapPropertiesToExtendedTag(props);
3075
- const pictures = audioFile.getPictures();
3076
- if (pictures.length > 0) tag.pictures = pictures;
3077
- const ratings = audioFile.getRatings();
3078
- if (ratings.length > 0) tag.ratings = ratings;
3079
- const lyrics = audioFile.getLyrics();
3080
- if (lyrics.length > 0) tag.lyrics = lyrics;
3081
- const chapters = audioFile.getChapters();
3082
- if (chapters.length > 0) tag.chapters = chapters;
3083
- const bext = audioFile.getBext();
3084
- if (bext !== void 0) tag.bext = bext;
3085
- const bextData = audioFile.getBextData();
3086
- if (bextData !== void 0) tag.bextData = bextData;
3087
- const ixml = audioFile.getIxml();
3088
- if (ixml !== void 0) tag.ixml = ixml;
3089
- if (includeProperties !== void 0 && includeProperties.length > 0) {
3090
- const extraProperties = {};
3091
- for (const wireKey of includeProperties) {
3092
- const values = props[fromTagLibKey(wireKey)]?.filter((v) => v !== "");
3093
- if (values !== void 0 && values.length > 0) extraProperties[wireKey] = values;
3094
- }
3095
- if (Object.keys(extraProperties).length > 0) tag.extraProperties = extraProperties;
3096
- }
3097
- return tag;
3098
- }
3099
- function mapPropertiesToExtendedTag(props) {
3100
- const tag = {};
3101
- for (const [propKey, tagField] of Object.entries(BASIC_PROPERTY_KEYS)) {
3102
- const values = props[propKey];
3103
- if (!values || values.length === 0) continue;
3104
- if (tagField === "year" || tagField === "track") {
3105
- const num = parseLeadingInt(values[0]);
3106
- if (num !== void 0) tag[tagField] = num;
3107
- if (propKey === "date") tag.date = values.length === 1 ? values[0] : values;
3108
- if (propKey === "trackNumber") tag.trackNumber = values.length === 1 ? values[0] : values;
3109
- } else tag[tagField] = values;
3110
- }
3111
- for (const [propKey, totalField] of [["trackNumber", "totalTracks"], ["discNumber", "totalDiscs"]]) {
3112
- if (tag[totalField] !== void 0) continue;
3113
- const raw = props[propKey]?.[0];
3114
- const slash = raw?.indexOf("/") ?? -1;
3115
- if (raw === void 0 || slash === -1) continue;
3116
- const total = parseLeadingInt(raw.slice(slash + 1));
3117
- if (total !== void 0) tag[totalField] = total;
3118
- }
3119
- if (tag.date === void 0) {
3120
- const yearValues = props["YEAR"];
3121
- if (yearValues !== void 0 && yearValues.length > 0) {
3122
- const y = parseLeadingInt(yearValues[0]);
3123
- if (y !== void 0) tag.year = y;
3124
- tag.date = yearValues.length === 1 ? yearValues[0] : yearValues;
3125
- }
3126
- }
3127
- for (const [key, values] of Object.entries(props)) {
3128
- if (BASIC_PROPERTY_KEYS[key]) continue;
3129
- if (key === "YEAR") continue;
3130
- if (!values || values.length === 0) continue;
3131
- const camelKey = fromTagLibKey(key);
3132
- if (NUMERIC_FIELDS.has(camelKey)) {
3133
- const num = parseLeadingInt(values[0]);
3134
- if (num !== void 0) tag[camelKey] = num;
3135
- } else if (camelKey === "compilation") tag[camelKey] = values[0] === "1" || values[0] === "true";
3136
- else if (camelKey === "itunesAdvisory") {
3137
- tag[camelKey] = values;
3138
- if (values[0] === "1") tag.advisory = "explicit";
3139
- else if (values[0] === "2") tag.advisory = "clean";
3140
- else if (values[0] === "0") tag.advisory = "unspecified";
3141
- } else if (camelKey === "r128TrackGain" || camelKey === "r128AlbumGain") {
3142
- const raw = parseLeadingInt(values[0]);
3143
- if (raw !== void 0) tag[camelKey] = raw / 256;
3144
- } else tag[camelKey] = values;
3145
- }
3146
- return tag;
3147
- }
3148
- function mergeTagUpdatesInto(currentProps, tags) {
3149
- const newProps = normalizeTagInput(tags);
3150
- reconcilePairFields(currentProps, newProps, tags);
3151
- if (newProps.date !== void 0 || newProps.year !== void 0) currentProps.YEAR = [];
3152
- return {
3153
- ...currentProps,
3154
- ...newProps
3155
- };
3156
- }
3157
- function mergeTagUpdates(file, tags) {
3158
- file.setProperties(mergeTagUpdatesInto(file.properties(), tags));
3159
- }
3160
- function reconcilePairFields(currentProps, newProps, input) {
3161
- for (const [rawKey, totalKey, numericKey] of [[
3162
- "trackNumber",
3163
- "totalTracks",
3164
- "track"
3165
- ], [
3166
- "discNumber",
3167
- "totalDiscs",
3168
- "discNumber"
3169
- ]]) {
3170
- const incoming = newProps[rawKey]?.[0];
3171
- if (incoming?.includes("/")) {
3172
- newProps[totalKey] = [];
3173
- continue;
3174
- }
3175
- if (!(input[numericKey] !== void 0 && input[rawKey] === void 0) || incoming === void 0) continue;
3176
- const existing = currentProps[rawKey]?.[0];
3177
- const slash = existing?.indexOf("/") ?? -1;
3178
- if (existing !== void 0 && slash !== -1) newProps[rawKey] = [`${incoming}${existing.slice(slash)}`];
3179
- }
3180
- }
3181
- function normalizeTagInput(input) {
3182
- const props = {};
3183
- for (const field of [
3184
- "title",
3185
- "artist",
3186
- "album",
3187
- "comment",
3188
- "genre"
3189
- ]) {
3190
- const val = input[field];
3191
- if (val === void 0) continue;
3192
- props[field] = Array.isArray(val) ? val : [val];
3193
- }
3194
- if (input.year !== void 0) props.date = [String(input.year)];
3195
- if (input.date !== void 0) props.date = Array.isArray(input.date) ? input.date : [input.date];
3196
- if (input.track !== void 0) props.trackNumber = [String(input.track)];
3197
- if (input.trackNumber !== void 0) props.trackNumber = Array.isArray(input.trackNumber) ? input.trackNumber : [input.trackNumber];
3198
- for (const [field, val] of Object.entries(input)) {
3199
- if (BASIC_FIELDS.has(field) || val === void 0) continue;
3200
- if (field === "extraProperties") continue;
3201
- if (field === "compilation") props[field] = [val ? "1" : "0"];
3202
- else if (field === "advisory") {
3203
- if (val === "explicit") props.itunesAdvisory = ["1"];
3204
- else if (val === "clean") props.itunesAdvisory = ["2"];
3205
- else if (val === "unspecified") props.itunesAdvisory = [];
3206
- } else if (field === "bpm") props[field] = [String(Math.trunc(val))];
3207
- else if (NUMERIC_FIELDS.has(field)) props[field] = [String(val)];
3208
- else if (field === "r128TrackGain" || field === "r128AlbumGain") props[field] = Array.isArray(val) ? val : [String(Math.round(val * 256))];
3209
- else if (typeof val === "string") props[field] = [val];
3210
- else if (Array.isArray(val)) props[field] = val;
3211
- }
3212
- for (const [rawField, totalField] of [["trackNumber", "totalTracks"], ["discNumber", "totalDiscs"]]) if (props[rawField]?.[0]?.includes("/")) delete props[totalField];
3213
- return props;
3214
- }
3215
- var BASIC_PROPERTY_KEYS, BASIC_FIELDS, NUMERIC_FIELDS;
3216
- var init_tag_mapping = __esmMin((() => {
3217
- init_properties();
3218
- init_mirror_fields();
3219
- BASIC_PROPERTY_KEYS = {
3220
- title: "title",
3221
- artist: "artist",
3222
- album: "album",
3223
- comment: "comment",
3224
- genre: "genre",
3225
- date: "year",
3226
- trackNumber: "track"
3227
- };
3228
- BASIC_FIELDS = /* @__PURE__ */ new Set([
3229
- "title",
3230
- "artist",
3231
- "album",
3232
- "comment",
3233
- "genre",
3234
- "year",
3235
- "date",
3236
- "track",
3237
- "trackNumber"
3238
- ]);
3239
- NUMERIC_FIELDS = /* @__PURE__ */ new Set([
3240
- "year",
3241
- "track",
3242
- "discNumber",
3243
- "totalTracks",
3244
- "totalDiscs",
3245
- "bpm"
3246
- ]);
3247
- }));
3248
- //#endregion
3249
- //#region src/version.ts
3250
- var VERSION;
3251
- var init_version = __esmMin((() => {
3252
- VERSION = "2.4.0";
3253
- }));
3254
- //#endregion
3255
- //#region src/runtime/module-loader-browser.ts
3256
- var module_loader_browser_exports = /* @__PURE__ */ __exportAll({ loadTagLibModule: () => loadTagLibModule });
3257
- async function loadTagLibModule(options) {
3258
- let createTagLibModule;
3259
- try {
3260
- createTagLibModule = (await import("./taglib-wrapper.js")).default;
3261
- } catch {
3262
- try {
3263
- createTagLibModule = (await import("./taglib-wrapper.js")).default;
3264
- } catch {
3265
- throw new TagLibInitializationError("Could not load taglib-wrapper.js. Ensure it is co-located with the browser bundle.");
3266
- }
3267
- }
3268
- const moduleConfig = {};
3269
- if (options?.wasmBinary) moduleConfig.wasmBinary = options.wasmBinary;
3270
- if (options?.wasmUrl) moduleConfig.locateFile = (path) => {
3271
- if (path.endsWith(".wasm")) return options.wasmUrl;
3272
- return path;
3273
- };
3274
- else if (!options?.wasmBinary) {
3275
- const wasmUrl = new URL("./taglib-web.wasm", import.meta.url);
3276
- moduleConfig.locateFile = (path) => path.endsWith(".wasm") ? wasmUrl.href : path;
3277
- }
3278
- return await createTagLibModule(moduleConfig);
3279
- }
3280
- var init_module_loader_browser = __esmMin((() => {
3281
- init_classes();
3282
- }));
3283
- //#endregion
3284
- //#region src/taglib/taglib-class.ts
3285
- function toWasiPath(osPath) {
3286
- if (osPath.startsWith("\\\\") || osPath.startsWith("//")) throw new FileOperationError("read", `UNC paths are not supported. Path: ${osPath}`);
3287
- let p = osPath;
3288
- if (!p.startsWith("/") && !/^[A-Za-z]:/.test(p)) {
3289
- const g = globalThis;
3290
- const cwd = isDeno() ? Deno.cwd() : g.process?.cwd?.();
3291
- if (cwd) p = cwd.replace(/[/\\]+$/, "") + "/" + p;
3292
- }
3293
- p = p.replaceAll("\\", "/");
3294
- const driveMatch = p.match(/^([A-Za-z]):\//);
3295
- if (driveMatch) p = `/${driveMatch[1].toUpperCase()}${p.slice(2)}`;
3296
- p = p.replace(/\/\.\//g, "/").replace(/\/+/g, "/");
3297
- if (!p.startsWith("/")) p = "/" + p;
3298
- return p;
3299
- }
3300
- async function createTagLib(module) {
3301
- return new TagLib(module);
3302
- }
3303
- var TagLib;
3304
- var init_taglib_class = __esmMin((() => {
3305
- init_audio_formats();
3306
- init_errors();
3307
- init_detector();
3308
- init_audio_file_impl();
3309
- init_load_audio_data();
3310
- init_tag_mapping();
3311
- init_version();
3312
- init_embind_adapter();
3313
- init_defineProperty();
3314
- TagLib = class TagLib {
3315
- constructor(module) {
3316
- _defineProperty(this, "module", void 0);
3317
- this.module = module;
3318
- }
3319
- static async initialize(options) {
3320
- const { loadTagLibModule } = await Promise.resolve().then(() => (init_module_loader_browser(), module_loader_browser_exports));
3321
- const module = await loadTagLibModule(options);
3322
- return new TagLib(module);
3323
- }
3324
- async open(input, options) {
3325
- if (!this.module.createFileHandle) throw new TagLibInitializationError("TagLib module not properly initialized: createFileHandle not found. Make sure the module is fully loaded before calling open.");
3326
- const actualInput = isNamedAudioInput(input) ? input.data : input;
3327
- const sourcePath = typeof actualInput === "string" ? actualInput : void 0;
3328
- if (typeof actualInput === "string" && this.module.isWasi) {
3329
- const wasiPath = toWasiPath(actualInput);
3330
- if (this.module.loadAudioPath) {
3331
- const fileHandle = await this.module.loadAudioPath(wasiPath, actualInput);
3332
- return new AudioFileImpl(this.module, fileHandle, sourcePath, actualInput, false);
3333
- }
3334
- }
3335
- const opts = {
3336
- partial: true,
3337
- maxHeaderSize: 1048576,
3338
- maxFooterSize: 131072,
3339
- ...options
3340
- };
3341
- const { data: audioData, isPartiallyLoaded } = await loadAudioData(actualInput, opts);
3342
- const uint8Array = actualInput instanceof Uint8Array && audioData.buffer === actualInput.buffer ? new Uint8Array(audioData.buffer.slice(audioData.byteOffset, audioData.byteOffset + audioData.byteLength)) : audioData;
3343
- const rawHandle = this.module.createFileHandle();
3344
- const fileHandle = this.module.isWasi ? rawHandle : wrapEmbindHandle(rawHandle);
3345
- try {
3346
- if (!fileHandle.loadFromBuffer(uint8Array)) throw new InvalidFormatError("Failed to load audio file. File may be corrupted or in an unsupported format", uint8Array.byteLength);
3347
- return new AudioFileImpl(this.module, fileHandle, sourcePath, actualInput, isPartiallyLoaded, opts);
3348
- } catch (error) {
3349
- if (typeof fileHandle.destroy === "function") fileHandle.destroy();
3350
- throw error;
3351
- }
3352
- }
3353
- async edit(input, fn) {
3354
- const file = await this.open(input);
3355
- try {
3356
- await fn(file);
3357
- if (typeof input === "string") await file.saveToFile();
3358
- else {
3359
- file.save();
3360
- return file.getFileBuffer();
3361
- }
3362
- } finally {
3363
- file.dispose();
3364
- }
3365
- }
3366
- async updateFile(path, tags) {
3367
- const file = await this.open(path);
3368
- try {
3369
- mergeTagUpdates(file, tags);
3370
- await file.saveToFile();
3371
- } finally {
3372
- file.dispose();
3373
- }
3374
- }
3375
- async copyWithTags(sourcePath, destPath, tags) {
3376
- const file = await this.open(sourcePath);
3377
- try {
3378
- mergeTagUpdates(file, tags);
3379
- await file.saveToFile(destPath);
3380
- } finally {
3381
- file.dispose();
3382
- }
3383
- }
3384
- version() {
3385
- return `${VERSION} (TagLib ${this.taglibVersion()})`;
3386
- }
3387
- taglibVersion() {
3388
- if (this.module.getVersion) return this.module.getVersion();
3389
- if (this.module.version) return this.module.version();
3390
- return "unknown";
3391
- }
3392
- };
3393
- }));
3394
- //#endregion
3395
- //#region src/taglib/index.ts
3396
- var init_taglib$1 = __esmMin((() => {
3397
- init_audio_file_impl();
3398
- init_taglib_class();
3399
- init_errors();
3400
- }));
3401
- //#endregion
3402
- //#region src/taglib.ts
3403
- var taglib_exports = /* @__PURE__ */ __exportAll({
3404
- AudioFileImpl: () => AudioFileImpl,
3405
- EnvironmentError: () => EnvironmentError,
3406
- FileOperationError: () => FileOperationError,
3407
- InvalidFormatError: () => InvalidFormatError,
3408
- MemoryError: () => MemoryError,
3409
- MetadataError: () => MetadataError,
3410
- SUPPORTED_FORMATS: () => SUPPORTED_FORMATS,
3411
- TagLib: () => TagLib,
3412
- TagLibError: () => TagLibError,
3413
- TagLibInitializationError: () => TagLibInitializationError,
3414
- UnsupportedFormatError: () => UnsupportedFormatError,
3415
- createTagLib: () => createTagLib,
3416
- isEnvironmentError: () => isEnvironmentError,
3417
- isFileOperationError: () => isFileOperationError,
3418
- isInvalidFormatError: () => isInvalidFormatError,
3419
- isMemoryError: () => isMemoryError,
3420
- isMetadataError: () => isMetadataError,
3421
- isTagLibError: () => isTagLibError,
3422
- isUnsupportedFormatError: () => isUnsupportedFormatError
3423
- });
3424
- var init_taglib = __esmMin((() => {
3425
- init_taglib$1();
3426
- }));
3427
- //#endregion
3428
- //#region src/runtime/deno-detect.ts
3429
- init_taglib();
3430
- function isDenoCompiled() {
3431
- if (typeof Deno === "undefined") return false;
3432
- const build = Deno.build;
3433
- if (typeof build?.standalone === "boolean") return build.standalone;
3434
- return typeof Deno.mainModule === "string" && (Deno.mainModule.includes("deno-compile://") || Deno.mainModule.includes("/deno-compile-"));
3435
- }
3436
- //#endregion
3437
- //#region src/simple/config.ts
3438
- let cachedTagLib = null;
3439
- let bufferModeEnabled = false;
3440
- function setBufferMode(enabled) {
3441
- bufferModeEnabled = enabled;
3442
- cachedTagLib = null;
3443
- }
3444
- async function getTagLib() {
3445
- if (!cachedTagLib) {
3446
- const { TagLib } = await Promise.resolve().then(() => (init_taglib(), taglib_exports));
3447
- const initOptions = bufferModeEnabled ? { forceWasmType: "emscripten" } : void 0;
3448
- cachedTagLib = await TagLib.initialize(initOptions);
3449
- }
3450
- return cachedTagLib;
3451
- }
3452
- //#endregion
3453
- //#region src/simple/with-audio-file.ts
3454
- init_errors();
3455
- async function withAudioFile(file, fn, options) {
3456
- const audioFile = await (await getTagLib()).open(file, options);
3457
- try {
3458
- if (!audioFile.isValid()) throw new InvalidFormatError("File may be corrupted or in an unsupported format");
3459
- return await fn(audioFile);
3460
- } finally {
3461
- audioFile.dispose();
3462
- }
3463
- }
3464
- async function withAudioFileSave(file, fn) {
3465
- return withAudioFile(file, (audioFile) => {
3466
- fn(audioFile);
3467
- if (!audioFile.save()) throw new FileOperationError("save", "Failed to save metadata changes. The file may be read-only or corrupted.");
3468
- return audioFile.getFileBuffer();
3469
- }, { partial: false });
3470
- }
3471
- async function withAudioFileSaveToFile(file, fn) {
3472
- return withAudioFile(file, async (audioFile) => {
3473
- fn(audioFile);
3474
- await audioFile.saveToFile(file);
3475
- });
3476
- }
3477
- //#endregion
3478
- //#region src/simple/tag-operations.ts
3479
- init_errors();
3480
- init_tag_mapping();
3481
- async function readTags(file, options = {}) {
3482
- return withAudioFile(file, (audioFile) => readExtendedTag(audioFile, options.includeProperties));
3483
- }
3484
- async function applyTags(file, tags) {
3485
- return withAudioFileSave(file, (audioFile) => {
3486
- mergeTagUpdates(audioFile, tags);
3487
- });
3488
- }
3489
- async function applyTagsToFile(file, tags) {
3490
- if (typeof file !== "string") throw new FileOperationError("save", "applyTagsToFile requires a file path string to save changes");
3491
- await withAudioFileSaveToFile(file, (audioFile) => {
3492
- mergeTagUpdates(audioFile, tags);
3493
- });
3494
- }
3495
- async function readProperties(file) {
3496
- return withAudioFile(file, (audioFile) => {
3497
- const props = audioFile.audioProperties();
3498
- if (!props) throw new MetadataError("read", "File may not contain valid audio data", "audioProperties");
3499
- return props;
3500
- });
3501
- }
3502
- async function isValidAudioFile(file) {
3503
- try {
3504
- const audioFile = await (await getTagLib()).open(file);
3505
- try {
3506
- return audioFile.isValid();
3507
- } finally {
3508
- audioFile.dispose();
3509
- }
3510
- } catch {
3511
- return false;
3512
- }
3513
- }
3514
- async function readFormat(file) {
3515
- const audioFile = await (await getTagLib()).open(file);
3516
- try {
3517
- if (!audioFile.isValid()) return;
3518
- return audioFile.getFormat();
3519
- } finally {
3520
- audioFile.dispose();
3521
- }
3522
- }
3523
- async function clearTags(file) {
3524
- return withAudioFileSave(file, (audioFile) => {
3525
- const cleared = {};
3526
- for (const key of Object.keys(audioFile.properties())) cleared[key] = [];
3527
- audioFile.setProperties(cleared);
3528
- audioFile.removePictures();
3529
- audioFile.setLyrics([]);
3530
- audioFile.setRatings([]);
3531
- if (audioFile.getChapters().length > 0) audioFile.setChapters([]);
3532
- if (audioFile.getBextData() !== void 0) audioFile.setBextData(null);
3533
- if (audioFile.getIxml() !== void 0) audioFile.setIxml(null);
3534
- });
3535
- }
3536
- //#endregion
3537
- //#region src/simple/picture-operations.ts
3538
- async function readPictures(file) {
3539
- return withAudioFile(file, (audioFile) => audioFile.getPictures());
3540
- }
3541
- async function applyPictures(file, pictures) {
3542
- return withAudioFileSave(file, (audioFile) => {
3543
- audioFile.setPictures(pictures);
3544
- });
3545
- }
3546
- async function addPicture(file, picture) {
3547
- return withAudioFileSave(file, (audioFile) => {
3548
- audioFile.addPicture(picture);
3549
- });
3550
- }
3551
- async function clearPictures(file) {
3552
- return applyPictures(file, []);
3553
- }
3554
- async function readCoverArt(file) {
3555
- const pictures = await readPictures(file);
3556
- if (pictures.length === 0) return;
3557
- const frontCover = pictures.find((pic) => pic.type === "FrontCover");
3558
- if (frontCover) return frontCover.data;
3559
- return pictures[0].data;
3560
- }
3561
- async function applyCoverArt(file, imageData, mimeType) {
3562
- return applyPictures(file, [{
3563
- mimeType,
3564
- data: imageData,
3565
- type: "FrontCover",
3566
- description: "Front Cover"
3567
- }]);
3568
- }
3569
- function findPictureByType(pictures, type) {
3570
- return pictures.find((pic) => pic.type === type);
3571
- }
3572
- async function replacePictureByType(file, newPicture) {
3573
- const filteredPictures = (await readPictures(file)).filter((pic) => pic.type !== newPicture.type);
3574
- filteredPictures.push(newPicture);
3575
- return applyPictures(file, filteredPictures);
3576
- }
3577
- async function readPictureMetadata(file) {
3578
- return (await readPictures(file)).map((pic) => ({
3579
- type: pic.type,
3580
- mimeType: pic.mimeType,
3581
- ...pic.description !== void 0 ? { description: pic.description } : {},
3582
- size: pic.data.length
3583
- }));
3584
- }
3585
- //#endregion
3586
- //#region src/simple/batch-operations.ts
3587
- init_audio_formats();
3588
- init_errors();
3589
- init_tag_mapping();
3590
- async function executeBatch(files, options, processor) {
3591
- if (files.length === 0) return {
3592
- items: [],
3593
- duration: 0
3594
- };
3595
- const startTime = Date.now();
3596
- const { concurrency = 4, continueOnError = true, onProgress, signal } = options;
3597
- const items = new Array(files.length);
3598
- const taglib = await getTagLib();
3599
- let processed = 0;
3600
- const total = files.length;
3601
- for (let i = 0; i < files.length; i += concurrency) {
3602
- signal?.throwIfAborted();
3603
- const chunkPromises = files.slice(i, i + concurrency).map(async (file, idx) => {
3604
- const index = i + idx;
3605
- const fileName = typeof file === "string" ? file : file instanceof File ? file.name : isNamedAudioInput(file) ? file.name : `buffer-${index}`;
3606
- try {
3607
- const audioFile = await taglib.open(file);
3608
- try {
3609
- if (!audioFile.isValid()) throw new InvalidFormatError("File may be corrupted or in an unsupported format");
3610
- items[index] = {
3611
- status: "ok",
3612
- path: fileName,
3613
- data: processor(audioFile)
3614
- };
3615
- } finally {
3616
- audioFile.dispose();
3617
- }
3618
- } catch (error) {
3619
- const err = error instanceof Error ? error : new Error(String(error));
3620
- items[index] = {
3621
- status: "error",
3622
- path: fileName,
3623
- error: err
3624
- };
3625
- if (!continueOnError) throw err;
3626
- }
3627
- processed++;
3628
- onProgress?.(processed, total, fileName);
3629
- });
3630
- await Promise.all(chunkPromises);
3631
- }
3632
- return {
3633
- items,
3634
- duration: Date.now() - startTime
3635
- };
3636
- }
3637
- async function readTagsBatch(files, options = {}) {
3638
- return executeBatch(files, options, (audioFile) => readExtendedTag(audioFile, options.includeProperties));
3639
- }
3640
- async function readPropertiesBatch(files, options = {}) {
3641
- return executeBatch(files, options, (audioFile) => audioFile.audioProperties());
3642
- }
3643
- function extractDynamics(audioFile) {
3644
- const dynamics = {};
3645
- for (const field of [
3646
- "replayGainTrackGain",
3647
- "replayGainTrackPeak",
3648
- "replayGainAlbumGain",
3649
- "replayGainAlbumPeak"
3650
- ]) {
3651
- const val = audioFile.getProperty(field)?.[0];
3652
- if (val !== void 0) dynamics[field] = val;
3653
- }
3654
- let appleSoundCheck = audioFile.getProperty("appleSoundCheck")?.[0];
3655
- if (!appleSoundCheck && audioFile.isMP4()) appleSoundCheck = audioFile.getMP4Item("----:com.apple.iTunes:iTunNORM");
3656
- if (appleSoundCheck) dynamics.appleSoundCheck = appleSoundCheck;
3657
- return Object.keys(dynamics).length > 0 ? dynamics : void 0;
3658
- }
3659
- async function readMetadata(file, options = {}) {
3660
- const audioFile = await (await getTagLib()).open(file);
3661
- try {
3662
- if (!audioFile.isValid()) {
3663
- let name;
3664
- if (typeof file === "string") name = file;
3665
- else if (file instanceof File) name = file.name;
3666
- else if (isNamedAudioInput(file)) name = file.name;
3667
- else name = `buffer (${file.byteLength} bytes)`;
3668
- throw new InvalidFormatError(`File may be corrupted or in an unsupported format. File: ${name}`);
3669
- }
3670
- const dynamics = extractDynamics(audioFile);
3671
- return {
3672
- tags: readExtendedTag(audioFile, options.includeProperties),
3673
- properties: audioFile.audioProperties(),
3674
- hasCoverArt: audioFile.getPictures().length > 0,
3675
- ...dynamics !== void 0 ? { dynamics } : {}
3676
- };
3677
- } finally {
3678
- audioFile.dispose();
3679
- }
3680
- }
3681
- async function readMetadataBatch(files, options = {}) {
3682
- return executeBatch(files, options, (audioFile) => {
3683
- const dynamics = extractDynamics(audioFile);
3684
- return {
3685
- tags: readExtendedTag(audioFile, options.includeProperties),
3686
- properties: audioFile.audioProperties(),
3687
- hasCoverArt: audioFile.getPictures().length > 0,
3688
- ...dynamics !== void 0 ? { dynamics } : {}
3689
- };
3690
- });
3691
- }
3692
- //#endregion
3693
- //#region src/simple/checksum-operations.ts
3694
- async function readMediaChecksum(file, options) {
3695
- return withAudioFile(file, (audioFile) => audioFile.mediaChecksum(options));
3696
- }
3697
- //#endregion
3698
- //#region src/constants/format-mappings.ts
3699
- const FormatMappings = {
3700
- Title: {
3701
- id3v2: "TIT2",
3702
- mp4: "©nam",
3703
- vorbis: "TITLE",
3704
- ape: "Title",
3705
- riff: "INAM"
3706
- },
3707
- Artist: {
3708
- id3v2: "TPE1",
3709
- mp4: "©ART",
3710
- vorbis: "ARTIST",
3711
- ape: "Artist",
3712
- riff: "IART"
3713
- },
3714
- Album: {
3715
- id3v2: "TALB",
3716
- mp4: "©alb",
3717
- vorbis: "ALBUM",
3718
- ape: "Album",
3719
- riff: "IPRD"
3720
- },
3721
- Date: {
3722
- id3v2: "TDRC",
3723
- mp4: "©day",
3724
- vorbis: "DATE",
3725
- ape: "Year",
3726
- riff: "ICRD"
3727
- },
3728
- Genre: {
3729
- id3v2: "TCON",
3730
- mp4: "©gen",
3731
- vorbis: "GENRE",
3732
- ape: "Genre",
3733
- riff: "IGNR"
3734
- },
3735
- Comment: {
3736
- id3v2: "COMM",
3737
- mp4: "©cmt",
3738
- vorbis: "COMMENT",
3739
- ape: "Comment",
3740
- riff: "ICMT"
3741
- },
3742
- TrackNumber: {
3743
- id3v2: "TRCK",
3744
- mp4: "trkn",
3745
- vorbis: "TRACKNUMBER",
3746
- ape: "Track",
3747
- riff: "ITRK"
3748
- }
3749
- };
3750
- //#endregion
3751
- //#region src/constants/utilities.ts
3752
- init_properties();
3753
- function isValidProperty(key) {
3754
- return key in PROPERTIES;
3755
- }
3756
- function getPropertyMetadata(key) {
3757
- return PROPERTIES[key];
3758
- }
3759
- function getAllPropertyKeys() {
3760
- return Object.keys(PROPERTIES);
3761
- }
3762
- function getAllProperties() {
3763
- return Object.entries(PROPERTIES);
3764
- }
3765
- function getPropertiesByFormat(format) {
3766
- return getAllPropertyKeys().filter((key) => PROPERTIES[key].supportedFormats.includes(format));
3767
- }
3768
- function propertyValues(props, key) {
3769
- return props[key] ?? [];
3770
- }
3771
- function propertyValue(props, key) {
3772
- return props[key]?.[0];
3773
- }
3774
- //#endregion
3775
- //#region src/folder-api/folder-disc.ts
3776
- function dirname(path) {
3777
- const i = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
3778
- return i === -1 ? path : path.slice(0, i);
3779
- }
3780
- const UNCONDITIONAL_MARKERS = [
3781
- "cd",
3782
- "disc",
3783
- "disk",
3784
- "dvd",
3785
- "sacd",
3786
- "blu-ray",
3787
- "bd",
3788
- "digital media"
3789
- ];
3790
- const GATED_MARKERS = [
3791
- "tape",
3792
- "vinyl",
3793
- "cassette",
3794
- "lp",
3795
- "record"
3796
- ];
3797
- const MARKERS = [...UNCONDITIONAL_MARKERS, ...GATED_MARKERS];
3798
- const GATED_MARKER_SET = new Set(GATED_MARKERS);
3799
- const WORD_NUMBERS = {
3800
- one: 1,
3801
- two: 2,
3802
- three: 3,
3803
- four: 4,
3804
- five: 5,
3805
- six: 6,
3806
- seven: 7,
3807
- eight: 8,
3808
- nine: 9,
3809
- ten: 10,
3810
- eleven: 11,
3811
- twelve: 12
3812
- };
3813
- function romanToInt(s) {
3814
- const values = {
3815
- i: 1,
3816
- v: 5,
3817
- x: 10,
3818
- l: 50,
3819
- c: 100,
3820
- d: 500,
3821
- m: 1e3
3822
- };
3823
- let total = 0;
3824
- let prev = 0;
3825
- for (let i = s.length - 1; i >= 0; i--) {
3826
- const v = values[s[i]];
3827
- if (v === void 0) return NaN;
3828
- total += v < prev ? -v : v;
3829
- prev = v;
3830
- }
3831
- return total;
3832
- }
3833
- function parseNumberToken(token) {
3834
- if (/^\d+$/.test(token)) return parseInt(token, 10);
3835
- const word = WORD_NUMBERS[token.toLowerCase()];
3836
- if (word) return word;
3837
- const roman = romanToInt(token.toLowerCase());
3838
- return Number.isFinite(roman) ? roman : void 0;
3839
- }
3840
- const SEP = String.raw`[\s._#-]*`;
3841
- const NUM = String.raw`(?:\d+|(?:[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|[a-z])(?![a-z]))`;
3842
- function parseDiscName(name) {
3843
- const trimmed = name.trim();
3844
- if (/^(?:extras?|bonus)$/i.test(trimmed)) return void 0;
3845
- for (const marker of MARKERS) {
3846
- const left = String.raw`(?:^|[^a-z0-9])`;
3847
- const esc = marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3848
- const re = new RegExp(left + String.raw`(${esc})(?![a-z])${SEP}(${NUM})`, "i");
3849
- const m = trimmed.match(re);
3850
- if (!m) continue;
3851
- const sideLetter = /^[a-z]$/i.test(m[2]);
3852
- const number = sideLetter ? void 0 : parseNumberToken(m[2]);
3853
- if (number === void 0 && !sideLetter) continue;
3854
- if (!sideLetter && /^[ivxlcdm]{2,}$/i.test(m[2]) && (number ?? 0) > 100) continue;
3855
- const isGated = GATED_MARKER_SET.has(marker.toLowerCase()) || sideLetter;
3856
- const markerStart = m.index + m[1].length - marker.length;
3857
- const title = trimmed.slice(0, markerStart).trim().replace(/[()[\]]/g, "").replace(/[\s._#-]+$/, "") || void 0;
3858
- const isExact = title === void 0;
3859
- const after = trimmed.slice(m.index + m[0].length).trim();
3860
- const discTitle = after.replace(/^[()[\],:;\-–—\s]+/, "").replace(/[)\]\[,:;\-–—\s]+$/, "").trim() || void 0;
3861
- const ofMatch = after.trim().match(/^of\s+(\d+)\b/i);
3862
- const total = ofMatch ? parseInt(ofMatch[1], 10) : void 0;
3863
- return {
3864
- kind: isExact ? "exact" : "embedded",
3865
- number: sideLetter ? void 0 : number,
3866
- total,
3867
- title,
3868
- discTitle,
3869
- gated: isGated,
3870
- sideLetter,
3871
- digit: /^\d+$/.test(m[2])
3872
- };
3873
- }
3874
- const volume = trimmed.match(/^(?:volume|vol\.?|part|pt\.?)\s*(\d+)(?:\s*of\s*(\d+))?$/i);
3875
- if (volume) return {
3876
- kind: "volume",
3877
- number: parseInt(volume[1], 10),
3878
- total: volume[2] ? parseInt(volume[2], 10) : void 0,
3879
- title: void 0,
3880
- discTitle: void 0,
3881
- gated: false,
3882
- sideLetter: false,
3883
- digit: true
3884
- };
3885
- if (/^bonus\s+disc$/i.test(trimmed)) return {
3886
- kind: "bonus",
3887
- number: void 0,
3888
- total: void 0,
3889
- title: void 0,
3890
- discTitle: void 0,
3891
- gated: true,
3892
- sideLetter: false,
3893
- digit: false
3894
- };
3895
- if (/^(?:\d+|v\d+|p\d+|[ab])$/i.test(trimmed)) return {
3896
- kind: "bare",
3897
- number: /^\d+$/i.test(trimmed) ? parseInt(trimmed, 10) : void 0,
3898
- total: void 0,
3899
- title: void 0,
3900
- discTitle: void 0,
3901
- gated: true,
3902
- sideLetter: false,
3903
- digit: false
3904
- };
3905
- }
3906
- function baseConfidence(parse) {
3907
- switch (parse.kind) {
3908
- case "exact": return parse.digit ? "high" : "low";
3909
- case "embedded": return "medium";
3910
- case "volume": return "medium";
3911
- case "bonus":
3912
- case "bare": return "low";
3913
- }
3914
- }
3915
- function discFolderInfo(name) {
3916
- const parse = parseDiscName(name);
3917
- if (!parse) return void 0;
3918
- return {
3919
- kind: parse.kind,
3920
- gated: parse.gated,
3921
- number: parse.number,
3922
- total: parse.total,
3923
- title: parse.title,
3924
- discTitle: parse.discTitle,
3925
- confidence: parse.gated ? "low" : baseConfidence(parse)
3926
- };
3927
- }
3928
- //#endregion
3929
- //#region src/utils/path.ts
3930
- function basename(path) {
3931
- const i = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
3932
- return i === -1 ? path : path.slice(i + 1);
3933
- }
3934
- //#endregion
3935
- //#region src/folder-api/album-corroborate.ts
3936
- const CONFIDENCE_RANK = {
3937
- low: 0,
3938
- medium: 1,
3939
- high: 2
3940
- };
3941
- function corroborated(parse, siblings) {
3942
- if (!parse.gated && parse.kind === "exact") return true;
3943
- if (siblings.length === 0) return false;
3944
- const siblingParses = siblings.map((s) => parseDiscName(basename(s))).filter((p) => p !== void 0);
3945
- const hasExactSibling = siblingParses.some((p) => !p.gated && p.kind === "exact");
3946
- const hasNumberedSibling = siblingParses.some((p) => p.number !== void 0);
3947
- if (parse.number !== void 0 && hasNumberedSibling) return true;
3948
- if (!parse.gated && parse.kind === "embedded" && hasExactSibling) return true;
3949
- if (!parse.gated && parse.kind === "volume" && hasNumberedSibling) return true;
3950
- if (parse.sideLetter) return siblingParses.some((p) => p.sideLetter);
3951
- if (parse.kind === "bonus" || parse.kind === "bare") {
3952
- if (siblingParses.filter((p) => p.number !== void 0).length >= 2) return true;
3953
- if (parse.number !== void 0 && hasNumberedSibling) return true;
3954
- }
3955
- return false;
3956
- }
3957
- //#endregion
3958
- //#region src/folder-api/album-identity.ts
3959
- function normalizeKey(s) {
3960
- return s.trim().toLowerCase().replace(/\s+/g, " ");
3961
- }
3962
- function isGenericAlbumArtist(albumArtist) {
3963
- if (!albumArtist || albumArtist.trim() === "") return true;
3964
- const n = normalizeKey(albumArtist);
3965
- return n === "various artists" || n === "va";
3966
- }
3967
- function evidenceFor(item, confirmedDiscs, flatSubdivisions) {
3968
- const dir = dirname(item.path);
3969
- const own = confirmedDiscs.get(dir);
3970
- if (own) return {
3971
- folderDiscNumber: own.parse.number,
3972
- total: own.parse.total,
3973
- folderDiscTitle: own.parse.discTitle,
3974
- confidence: own.confidence,
3975
- albumDir: dirname(dir)
3976
- };
3977
- let cursor = dirname(dir);
3978
- while (cursor !== void 0) {
3979
- const entry = confirmedDiscs.get(cursor);
3980
- if (entry) return {
3981
- folderDiscNumber: entry.parse.number,
3982
- total: entry.parse.total,
3983
- folderDiscTitle: entry.parse.discTitle,
3984
- confidence: entry.confidence,
3985
- albumDir: dirname(cursor)
3986
- };
3987
- const parent = dirname(cursor);
3988
- if (parent === cursor) break;
3989
- cursor = parent;
3990
- }
3991
- const flat = flatSubdivisions.get(dir)?.get(item.path);
3992
- if (flat !== void 0) return {
3993
- folderDiscNumber: flat,
3994
- total: void 0,
3995
- folderDiscTitle: void 0,
3996
- confidence: "medium",
3997
- albumDir: dir
3998
- };
3999
- }
4000
- function folderIdentity(dir, confirmedDiscs, scanRoot) {
4001
- const own = confirmedDiscs.get(dir);
4002
- if (!own) {
4003
- const title = basename(dir);
4004
- return title ? {
4005
- title,
4006
- titleSource: dir
4007
- } : void 0;
4008
- }
4009
- if (own.parse.title !== void 0) return {
4010
- title: own.parse.title,
4011
- titleSource: dirname(dir)
4012
- };
4013
- const source = dirname(dir);
4014
- if (source === scanRoot || source === dir) return void 0;
4015
- const title = basename(source);
4016
- return title ? {
4017
- title,
4018
- titleSource: source
4019
- } : void 0;
4020
- }
4021
- function buildAlbumIdentity(okItems, confirmedDiscs, flatSubdivisions, options) {
4022
- const albums = /* @__PURE__ */ new Map();
4023
- const unmatched = [];
4024
- for (const item of okItems) {
4025
- const dir = dirname(item.path);
4026
- const albumTag = item.tags.album?.[0]?.trim();
4027
- const albumArtistTag = item.tags.albumArtist?.[0]?.trim();
4028
- if (albumTag) {
4029
- const key = `${isGenericAlbumArtist(albumArtistTag) ? "" : normalizeKey(albumArtistTag ?? "")}::${normalizeKey(albumTag)}`;
4030
- let acc = albums.get(key);
4031
- if (!acc) {
4032
- acc = {
4033
- key,
4034
- album: albumTag,
4035
- albumArtist: isGenericAlbumArtist(albumArtistTag) ? void 0 : albumArtistTag,
4036
- source: "tags",
4037
- directory: void 0,
4038
- items: [],
4039
- evidence: /* @__PURE__ */ new Map()
4040
- };
4041
- albums.set(key, acc);
4042
- }
4043
- const evidence = evidenceFor(item, confirmedDiscs, flatSubdivisions);
4044
- acc.evidence.set(item.path, evidence);
4045
- acc.items.push({
4046
- ...item.metadata,
4047
- albumDir: evidence?.albumDir ?? dir,
4048
- discNumber: evidence?.folderDiscNumber
4049
- });
4050
- continue;
4051
- }
4052
- if (!options.useFolderFallback) {
4053
- unmatched.push(item.metadata);
4054
- continue;
4055
- }
4056
- const identity = folderIdentity(dir, confirmedDiscs, options.scanRoot);
4057
- if (!identity) {
4058
- unmatched.push(item.metadata);
4059
- continue;
4060
- }
4061
- const key = `${identity.titleSource}::${normalizeKey(identity.title)}`;
4062
- let acc = albums.get(key);
4063
- if (!acc) {
4064
- acc = {
4065
- key,
4066
- album: identity.title,
4067
- albumArtist: void 0,
4068
- source: "folder",
4069
- directory: identity.titleSource,
4070
- items: [],
4071
- evidence: /* @__PURE__ */ new Map()
4072
- };
4073
- albums.set(key, acc);
4074
- }
4075
- const evidence = evidenceFor(item, confirmedDiscs, flatSubdivisions);
4076
- acc.evidence.set(item.path, evidence);
4077
- acc.items.push({
4078
- ...item.metadata,
4079
- albumDir: evidence?.albumDir ?? dir,
4080
- discNumber: evidence?.folderDiscNumber
4081
- });
4082
- }
4083
- for (const [key, acc] of [...albums]) {
4084
- if (acc.source === "tags") continue;
4085
- for (const other of albums.values()) {
4086
- if (other === acc || other.source !== "tags") continue;
4087
- if (normalizeKey(other.album) !== normalizeKey(acc.album)) continue;
4088
- const albumDir = acc.directory;
4089
- if (!(albumDir !== void 0 && other.items.some((o) => {
4090
- const od = dirname(o.path);
4091
- return od === albumDir || od.startsWith(albumDir + "/");
4092
- }))) continue;
4093
- for (const item of acc.items) {
4094
- other.items.push(item);
4095
- other.evidence.set(item.path, acc.evidence.get(item.path));
4096
- }
4097
- albums.delete(key);
4098
- break;
4099
- }
4100
- }
4101
- return {
4102
- albums,
4103
- unmatched
4104
- };
4105
- }
4106
- //#endregion
4107
- //#region src/folder-api/album-discs.ts
4108
- function assembleDiscs(albums) {
4109
- const groups = [];
4110
- for (const acc of albums.values()) {
4111
- const dirTagCommon = /* @__PURE__ */ new Map();
4112
- const resolvedByFile = /* @__PURE__ */ new Map();
4113
- for (const item of acc.items) {
4114
- const dir = dirname(item.path);
4115
- if (!dirTagCommon.has(dir)) {
4116
- const tagged = acc.items.filter((i) => dirname(i.path) === dir).map((i) => i.tags.discNumber).filter((d) => d !== void 0 && d > 0);
4117
- dirTagCommon.set(dir, tagged.length > 0 && tagged.every((d) => d === tagged[0]) ? tagged[0] : void 0);
4118
- }
4119
- const evidence = acc.evidence.get(item.path);
4120
- const tagCommon = dirTagCommon.get(dir);
4121
- resolvedByFile.set(item.path, tagCommon ?? evidence?.folderDiscNumber);
4122
- }
4123
- const discs = /* @__PURE__ */ new Map();
4124
- const order = [];
4125
- const noEvidenceItems = [];
4126
- for (const item of acc.items) {
4127
- const evidence = acc.evidence.get(item.path);
4128
- if (evidence === void 0) {
4129
- noEvidenceItems.push(item);
4130
- continue;
4131
- }
4132
- const resolved = resolvedByFile.get(item.path);
4133
- const discKey = resolved === void 0 ? `dir:${dirname(item.path)}` : String(resolved);
4134
- let disc = discs.get(discKey);
4135
- if (!disc) {
4136
- disc = {
4137
- discNumber: resolved,
4138
- totalDiscs: evidence.total,
4139
- folderDiscNumber: evidence.folderDiscNumber,
4140
- folderDiscTitle: evidence.folderDiscTitle,
4141
- tagDiscNumber: void 0,
4142
- confidence: evidence.confidence,
4143
- items: []
4144
- };
4145
- discs.set(discKey, disc);
4146
- order.push(discKey);
4147
- }
4148
- disc.items.push(item);
4149
- }
4150
- if (noEvidenceItems.length > 0) {
4151
- const numbered = [...discs.values()].filter((d) => d.folderDiscNumber !== void 0).sort((a, b) => a.folderDiscNumber - b.folderDiscNumber);
4152
- if (numbered.length > 0) numbered[0].items.push(...noEvidenceItems);
4153
- else {
4154
- const key = "dir:__none__";
4155
- let disc = discs.get(key);
4156
- if (!disc) {
4157
- disc = {
4158
- discNumber: void 0,
4159
- totalDiscs: void 0,
4160
- folderDiscNumber: void 0,
4161
- folderDiscTitle: void 0,
4162
- tagDiscNumber: void 0,
4163
- confidence: "high",
4164
- items: []
4165
- };
4166
- discs.set(key, disc);
4167
- order.push(key);
4168
- }
4169
- disc.items.push(...noEvidenceItems);
4170
- }
4171
- }
4172
- for (const disc of discs.values()) {
4173
- const tagged = disc.items.map((i) => i.tags.discNumber).filter((d) => d !== void 0 && d > 0);
4174
- const common = tagged.length > 0 && tagged.every((d) => d === tagged[0]) ? tagged[0] : void 0;
4175
- disc.tagDiscNumber = common;
4176
- disc.discNumber = common ?? disc.folderDiscNumber;
4177
- for (const item of disc.items) item.discNumber = disc.discNumber;
4178
- }
4179
- const albumTaggedTotals = acc.items.map((i) => i.tags.totalDiscs).filter((t) => t !== void 0 && t > 0);
4180
- const commonTotal = albumTaggedTotals.length > 0 && albumTaggedTotals.every((t) => t === albumTaggedTotals[0]) ? albumTaggedTotals[0] : void 0;
4181
- const ofN = [...discs.values()].map((d) => d.totalDiscs).find((t) => t !== void 0);
4182
- const maxSibling = [...discs.values()].map((d) => d.discNumber).filter((n) => n !== void 0).reduce((a, b) => Math.max(a, b), 0) || void 0;
4183
- for (const disc of discs.values()) disc.totalDiscs = commonTotal ?? ofN ?? maxSibling;
4184
- const sortedDiscs = [...discs.values()].sort((a, b) => {
4185
- const an = a.discNumber === void 0 ? -1 : a.discNumber;
4186
- const bn = b.discNumber === void 0 ? -1 : b.discNumber;
4187
- if (an !== bn) return an - bn;
4188
- return (a.folderDiscTitle ?? "").localeCompare(b.folderDiscTitle ?? "");
4189
- });
4190
- for (const disc of sortedDiscs) disc.items.sort((a, b) => {
4191
- const at = a.tags.track ?? Infinity;
4192
- const bt = b.tags.track ?? Infinity;
4193
- if (at !== bt) return at - bt;
4194
- return a.path.localeCompare(b.path);
4195
- });
4196
- const flags = acc.items.map((i) => i.tags.compilation).filter((c) => c !== void 0);
4197
- const compilation = flags.length > 0 && flags.every((f) => f === flags[0]) ? flags[0] : void 0;
4198
- const albumDirs = new Set(acc.items.map((i) => i.albumDir));
4199
- const directory = albumDirs.size === 1 ? [...albumDirs][0] : acc.directory;
4200
- groups.push({
4201
- key: acc.key,
4202
- albumArtist: acc.albumArtist,
4203
- album: acc.album,
4204
- source: acc.source,
4205
- compilation,
4206
- directory,
4207
- discs: sortedDiscs,
4208
- items: sortedDiscs.flatMap((d) => d.items)
4209
- });
4210
- }
4211
- return groups;
4212
- }
4213
- //#endregion
4214
- //#region src/folder-api/album-grouping.ts
4215
- function flatPrefix(filename) {
4216
- const separated = filename.match(/^(\d{1,2})[\s._-](\d{1,2})/);
4217
- if (separated) return {
4218
- disc: parseInt(separated[1], 10),
4219
- form: "separated"
4220
- };
4221
- const compact = filename.match(/^(\d)(\d{2})(?:\D|$)/);
4222
- if (compact) return {
4223
- disc: parseInt(compact[1], 10),
4224
- form: "compact"
4225
- };
4226
- }
4227
- function normalizeOk(result) {
4228
- const okItems = [];
4229
- const errors = [];
4230
- for (const item of result.items) if (item.status === "ok") okItems.push({
4231
- path: item.path,
4232
- tags: item.tags,
4233
- metadata: item
4234
- });
4235
- else errors.push({
4236
- path: item.path,
4237
- error: item.error
4238
- });
4239
- return {
4240
- okItems,
4241
- errors
4242
- };
4243
- }
4244
- function buildTree(okItems) {
4245
- const tree = /* @__PURE__ */ new Map();
4246
- for (const item of okItems) {
4247
- const dir = dirname(item.path);
4248
- let node = tree.get(dir);
4249
- if (!node) {
4250
- node = {
4251
- files: [],
4252
- parent: dirname(dir)
4253
- };
4254
- tree.set(dir, node);
4255
- }
4256
- node.files.push(item);
4257
- }
4258
- return tree;
4259
- }
4260
- function confirmDiscs(tree, minRank) {
4261
- const confirmedDiscs = /* @__PURE__ */ new Map();
4262
- for (const [dir, node] of tree) {
4263
- if (node.files.length === 0) continue;
4264
- const parse = parseDiscName(basename(dir));
4265
- if (!parse) continue;
4266
- const corroboratedBySiblings = corroborated(parse, [...tree.keys()].filter((d) => d !== dir && dirname(d) === dirname(dir)));
4267
- let confidence = parse.gated ? "low" : baseConfidence(parse);
4268
- if (parse.gated) {
4269
- if (!corroboratedBySiblings) continue;
4270
- } else if (parse.kind === "bonus" || parse.kind === "bare") {
4271
- if (!corroboratedBySiblings) continue;
4272
- } else if (corroboratedBySiblings) confidence = "high";
4273
- if (CONFIDENCE_RANK[confidence] < minRank) continue;
4274
- confirmedDiscs.set(dir, {
4275
- parse,
4276
- confidence
4277
- });
4278
- }
4279
- return confirmedDiscs;
4280
- }
4281
- function flatSubdivisions(tree, confirmedDiscs, useFlatPrefixes) {
4282
- const flat = /* @__PURE__ */ new Map();
4283
- if (!useFlatPrefixes) return flat;
4284
- for (const [dir, node] of tree) {
4285
- if (node.files.length === 0 || confirmedDiscs.has(dir)) continue;
4286
- const byFile = /* @__PURE__ */ new Map();
4287
- const forms = /* @__PURE__ */ new Set();
4288
- for (const item of node.files) {
4289
- const prefix = flatPrefix(basename(item.path));
4290
- if (prefix) {
4291
- byFile.set(item.path, prefix.disc);
4292
- forms.add(prefix.form);
4293
- }
4294
- }
4295
- if (byFile.size < 2) continue;
4296
- const distinct = [...new Set(byFile.values())].sort((a, b) => a - b);
4297
- if (forms.size === 1 && forms.has("compact") ? distinct.every((d) => d >= 1 && d <= distinct.length) : true) flat.set(dir, byFile);
4298
- }
4299
- return flat;
4300
- }
4301
- function groupAlbums(result, options = {}) {
4302
- const minRank = CONFIDENCE_RANK[options.minFolderConfidence ?? "low"];
4303
- const useFlatPrefixes = options.flatDiscPrefixes ?? true;
4304
- const useFolderFallback = options.folderFallback ?? true;
4305
- const { okItems, errors } = normalizeOk(result);
4306
- if (okItems.length === 0) return {
4307
- albums: [],
4308
- singles: [],
4309
- unmatched: [],
4310
- errors
4311
- };
4312
- const tree = buildTree(okItems);
4313
- const confirmedDiscs = confirmDiscs(tree, minRank);
4314
- const { albums, unmatched } = buildAlbumIdentity(okItems, confirmedDiscs, flatSubdivisions(tree, confirmedDiscs, useFlatPrefixes), {
4315
- scanRoot: options.scanRoot,
4316
- useFolderFallback
4317
- });
4318
- const groups = assembleDiscs(albums);
4319
- const albumsOut = [];
4320
- const singles = [];
4321
- for (const group of groups) if (group.items.length === 1) singles.push(group.items[0]);
4322
- else albumsOut.push(group);
4323
- albumsOut.sort((a, b) => (a.albumArtist ?? "").localeCompare(b.albumArtist ?? "") || (a.album ?? "").localeCompare(b.album ?? ""));
4324
- return {
4325
- albums: albumsOut,
4326
- singles,
4327
- unmatched,
4328
- errors
4329
- };
4330
- }
4331
- //#endregion
4332
- //#region src/web-utils/data-url.ts
4333
- init_classes();
4334
- function pictureToDataURL(picture) {
4335
- const data = picture.data;
4336
- const CHUNK = 32768;
4337
- let binary = "";
4338
- for (let i = 0; i < data.length; i += CHUNK) binary += String.fromCharCode(...data.subarray(i, i + CHUNK));
4339
- const base64 = btoa(binary);
4340
- return `data:${picture.mimeType};base64,${base64}`;
4341
- }
4342
- function dataURLToPicture(dataURL, type = "FrontCover", description) {
4343
- const matches = /^data:([^;]+);base64,(.+)$/.exec(dataURL);
4344
- if (!matches) throw new InvalidFormatError("Invalid data URL format");
4345
- const [, mimeType, base64] = matches;
4346
- const binaryString = atob(base64);
4347
- const data = new Uint8Array(binaryString.length);
4348
- for (let i = 0; i < binaryString.length; i++) data[i] = binaryString.codePointAt(i);
4349
- return {
4350
- mimeType,
4351
- data,
4352
- type,
4353
- ...description !== void 0 ? { description } : {}
4354
- };
4355
- }
4356
- //#endregion
4357
- //#region src/web-utils/canvas.ts
4358
- async function setCoverArtFromCanvas(file, canvas, options = {}) {
4359
- const { format = "image/jpeg", quality = .92, type = "FrontCover", description = "Front Cover" } = options;
4360
- return applyPictures(file, [dataURLToPicture(canvas.toDataURL(format, quality), type, description)]);
4361
- }
4362
- async function canvasToPicture(canvas, options = {}) {
4363
- const { format = "image/jpeg", quality = .92, type = "FrontCover", description } = options;
4364
- return new Promise((resolve, reject) => {
4365
- canvas.toBlob((blob) => {
4366
- if (!blob) {
4367
- reject(/* @__PURE__ */ new Error("Failed to convert canvas to blob"));
4368
- return;
4369
- }
4370
- blob.arrayBuffer().then((arrayBuffer) => {
4371
- const data = new Uint8Array(arrayBuffer);
4372
- resolve({
4373
- mimeType: format,
4374
- data,
4375
- type,
4376
- ...description !== void 0 ? { description } : {}
4377
- });
4378
- }, reject);
4379
- }, format, quality);
4380
- });
4381
- }
4382
- async function imageFileToPicture(file, type = "FrontCover", description) {
4383
- const arrayBuffer = await file.arrayBuffer();
4384
- const data = new Uint8Array(arrayBuffer);
4385
- return {
4386
- mimeType: file.type,
4387
- data,
4388
- type,
4389
- description: description ?? file.name
4390
- };
4391
- }
4392
- //#endregion
4393
- //#region src/web-utils/dom-integration.ts
4394
- function ensureArrayBufferBacked(data) {
4395
- if (data.buffer instanceof ArrayBuffer) return data;
4396
- const copy = new Uint8Array(data.length);
4397
- copy.set(data);
4398
- return copy;
4399
- }
4400
- function displayPicture(picture, imgElement) {
4401
- if (imgElement.src.startsWith("blob:")) URL.revokeObjectURL(imgElement.src);
4402
- const data = ensureArrayBufferBacked(picture.data);
4403
- const blob = new Blob([data], { type: picture.mimeType });
4404
- const objectURL = URL.createObjectURL(blob);
4405
- imgElement.src = objectURL;
4406
- imgElement.addEventListener("load", () => {
4407
- setTimeout(() => URL.revokeObjectURL(objectURL), 100);
4408
- }, { once: true });
4409
- }
4410
- function createPictureDownloadURL(picture, filename = "cover") {
4411
- const data = ensureArrayBufferBacked(picture.data);
4412
- const blob = new Blob([data], { type: picture.mimeType });
4413
- return URL.createObjectURL(blob);
4414
- }
4415
- async function createPictureGallery(file, container, options = {}) {
4416
- const pictures = await readPictures(file);
4417
- container.innerHTML = "";
4418
- pictures.forEach((picture, index) => {
4419
- const wrapper = document.createElement("div");
4420
- wrapper.className = options.className ?? "picture-item";
4421
- const img = document.createElement("img");
4422
- displayPicture(picture, img);
4423
- img.alt = picture.description ?? `Picture ${index + 1}`;
4424
- if (options.onClick) {
4425
- img.style.cursor = "pointer";
4426
- img.addEventListener("click", () => options.onClick(picture, index));
4427
- }
4428
- wrapper.appendChild(img);
4429
- if (options.includeDescription && picture.description) {
4430
- const caption = document.createElement("p");
4431
- caption.textContent = picture.description;
4432
- wrapper.appendChild(caption);
4433
- }
4434
- container.appendChild(wrapper);
4435
- });
4436
- }
4437
- //#endregion
4438
- //#region src/index.browser.ts
4439
- init_audio_formats();
4440
- init_errors();
4441
- init_properties();
4442
- init_types();
4443
- init_bext();
4444
- init_rating();
4445
- init_module_loader_browser();
4446
- init_pictures();
4447
- init_base();
4448
- init_classes();
4449
- init_guards();
4450
- init_audio_file_impl();
4451
- init_taglib_class();
4452
- //#endregion
4453
- export { AudioFileImpl, BITRATE_CONTROL_MODE_NAMES, BITRATE_CONTROL_MODE_VALUES, EnvironmentError, FileOperationError, FormatMappings, InvalidFormatError, MemoryError, MetadataError, PICTURE_TYPE_NAMES, PICTURE_TYPE_VALUES, PROPERTIES, RatingUtils, SUPPORTED_FORMATS, TagLib, TagLibError, TagLibInitializationError, UnsupportedFormatError, addPicture, applyCoverArt, applyPictures, applyTags, applyTagsToFile, bext_exports as bwf, canvasToPicture, clearPictures, clearTags, createPictureDownloadURL, createPictureGallery, createTagLib, dataURLToPicture, discFolderInfo, displayPicture, findPictureByType, getAllProperties, getAllPropertyKeys, getPropertiesByFormat, getPropertyMetadata, groupAlbums, imageFileToPicture, isDenoCompiled, isEnvironmentError, isFileOperationError, isInvalidFormatError, isMemoryError, isMetadataError, isNamedAudioInput, isTagLibError, isUnsupportedFormatError, isValidAudioFile, isValidProperty, loadTagLibModule, pictureToDataURL, propertyValue, propertyValues, readCoverArt, readFormat, readMediaChecksum, readMetadata, readMetadataBatch, readPictureMetadata, readPictures, readProperties, readPropertiesBatch, readTags, readTagsBatch, replacePictureByType, setBufferMode, setCoverArtFromCanvas };
1
+ var __defProp=Object.defineProperty;var __esmMin=(fn,res,err)=>()=>{if(err)throw err[0];try{return fn&&(res=fn(fn=0)),res}catch(e){throw err=[e],e}};var __exportAll=(all,no_symbols)=>{let target={};for(var name in all){__defProp(target,name,{get:all[name],enumerable:true})}if(!no_symbols){__defProp(target,Symbol.toStringTag,{value:`Module`})}return target};function isNamedAudioInput(input){return typeof input===`object`&&input!==null&&`name`in input&&`data`in input&&!(input instanceof File)&&!(input instanceof Uint8Array)&&!(input instanceof ArrayBuffer)}var init_audio_formats=__esmMin((()=>{}));var init_tags=__esmMin((()=>{}));var init_metadata_mappings=__esmMin((()=>{}));var PICTURE_TYPE_VALUES,PICTURE_TYPE_NAMES,BITRATE_CONTROL_MODE_VALUES,BITRATE_CONTROL_MODE_NAMES;var init_pictures=__esmMin((()=>{PICTURE_TYPE_VALUES={Other:0,FileIcon:1,OtherFileIcon:2,FrontCover:3,BackCover:4,LeafletPage:5,Media:6,LeadArtist:7,Artist:8,Conductor:9,Band:10,Composer:11,Lyricist:12,RecordingLocation:13,DuringRecording:14,DuringPerformance:15,MovieScreenCapture:16,ColouredFish:17,Illustration:18,BandLogo:19,PublisherLogo:20};PICTURE_TYPE_NAMES={0:`Other`,1:`FileIcon`,2:`OtherFileIcon`,3:`FrontCover`,4:`BackCover`,5:`LeafletPage`,6:`Media`,7:`LeadArtist`,8:`Artist`,9:`Conductor`,10:`Band`,11:`Composer`,12:`Lyricist`,13:`RecordingLocation`,14:`DuringRecording`,15:`DuringPerformance`,16:`MovieScreenCapture`,17:`ColouredFish`,18:`Illustration`,19:`BandLogo`,20:`PublisherLogo`};BITRATE_CONTROL_MODE_VALUES={Constant:0,LongTermAverage:1,VariableConstrained:2,Variable:3};BITRATE_CONTROL_MODE_NAMES={0:`Constant`,1:`LongTermAverage`,2:`VariableConstrained`,3:`Variable`}}));var init_chapters=__esmMin((()=>{}));var init_bwf=__esmMin((()=>{}));var init_config=__esmMin((()=>{}));var init_format_property_keys=__esmMin((()=>{}));var init_types$1=__esmMin((()=>{init_audio_formats();init_tags();init_metadata_mappings();init_pictures();init_chapters();init_bwf();init_config();init_format_property_keys()}));var init_types=__esmMin((()=>{init_types$1()}));var bext_exports=/* @__PURE__ */ __exportAll({decodeBext:()=>decodeBext,encodeBext:()=>encodeBext});function readFixedString(bytes,offset,len){let end=offset;const max=Math.min(offset+len,bytes.length);while(end<max&&bytes[end]!==0)end++;let s=``;for(let i=offset;i<end;i++)s+=String.fromCodePoint(bytes[i]);return s}function writeFixedString(bytes,offset,len,value){for(let i=0;i<len;i++)bytes[offset+i]=i<value.length?(value.codePointAt(i)??0)&255:0}function clampInt16(n){return Math.max(-32768,Math.min(32767,Math.round(n)))}function loudnessRaw(v){return v===void 0?LOUDNESS_UNSET:clampInt16(v*100)}function loudnessFromRaw(raw){return raw===LOUDNESS_UNSET?void 0:raw/100}function bytesToHex(bytes){let s=``;for(const b of bytes)s+=b.toString(16).padStart(2,`0`);return s}function hexToBytes(hex,outLen){const clean=hex.replace(/[^0-9a-fA-F]/g,``);const out=new Uint8Array(outLen);for(let i=0;i+1<clean.length+1&&i/2<outLen;i+=2){const pair=clean.slice(i,i+2);if(pair.length===2)out[i/2]=Number.parseInt(pair,16)}return out}function decodeLoudnessFields(dv){const result={};for(const[field,offset]of LOUDNESS_FIELDS){const value=loudnessFromRaw(dv.getInt16(LOUDNESS_OFFSET+offset,true));if(value!==void 0)result[field]=value}return result}function decodeBext(bytes){if(bytes.length<348)return void 0;const dv=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const timeRefLow=dv.getUint32(338,true);const timeRefHigh=dv.getUint32(342,true);const version=dv.getUint16(VERSION_OFFSET,true);const result={description:readFixedString(bytes,0,256),originator:readFixedString(bytes,256,32),originatorReference:readFixedString(bytes,288,32),originationDate:readFixedString(bytes,320,10),originationTime:readFixedString(bytes,330,8),timeReferenceSamples:BigInt(timeRefHigh)<<32n|BigInt(timeRefLow),version,codingHistory:bytes.length>FIXED_PREFIX_LEN?readFixedString(bytes,FIXED_PREFIX_LEN,bytes.length-FIXED_PREFIX_LEN):``};if(version>=1&&bytes.length>=412)result.umid=bytesToHex(bytes.subarray(UMID_OFFSET,412));if(version>=2&&bytes.length>=422)Object.assign(result,decodeLoudnessFields(dv));return result}function encodeBext(b){const codingHistory=b.codingHistory??``;const bytes=new Uint8Array(FIXED_PREFIX_LEN+codingHistory.length);const dv=new DataView(bytes.buffer);const hasLoudness=b.loudnessValueDb!==void 0||b.loudnessRangeDb!==void 0||b.maxTruePeakLevelDbtp!==void 0||b.maxMomentaryLoudnessDb!==void 0||b.maxShortTermLoudnessDb!==void 0;let version;if(Number.isInteger(b.version))version=b.version;else if(hasLoudness)version=2;else if(b.umid)version=1;else version=0;writeFixedString(bytes,0,256,b.description??``);writeFixedString(bytes,256,32,b.originator??``);writeFixedString(bytes,288,32,b.originatorReference??``);writeFixedString(bytes,320,10,b.originationDate??``);writeFixedString(bytes,330,8,b.originationTime??``);const tr=b.timeReferenceSamples??0n;dv.setUint32(338,Number(tr&4294967295n),true);dv.setUint32(342,Number(tr>>32n&4294967295n),true);dv.setUint16(VERSION_OFFSET,version,true);if(version>=1&&b.umid)bytes.set(hexToBytes(b.umid,UMID_LEN),UMID_OFFSET);if(version>=2){dv.setInt16(LOUDNESS_OFFSET,loudnessRaw(b.loudnessValueDb),true);dv.setInt16(414,loudnessRaw(b.loudnessRangeDb),true);dv.setInt16(416,loudnessRaw(b.maxTruePeakLevelDbtp),true);dv.setInt16(418,loudnessRaw(b.maxMomentaryLoudnessDb),true);dv.setInt16(420,loudnessRaw(b.maxShortTermLoudnessDb),true)}writeFixedString(bytes,FIXED_PREFIX_LEN,codingHistory.length,codingHistory);return bytes}var FIXED_PREFIX_LEN,VERSION_OFFSET,UMID_OFFSET,UMID_LEN,LOUDNESS_OFFSET,LOUDNESS_UNSET,LOUDNESS_FIELDS;var init_bext=__esmMin((()=>{FIXED_PREFIX_LEN=602;VERSION_OFFSET=346;UMID_OFFSET=348;UMID_LEN=64;LOUDNESS_OFFSET=412;LOUDNESS_UNSET=32767;LOUDNESS_FIELDS=[[`loudnessValueDb`,0],[`loudnessRangeDb`,2],[`maxTruePeakLevelDbtp`,4],[`maxMomentaryLoudnessDb`,6],[`maxShortTermLoudnessDb`,8]]}));var SUPPORTED_FORMATS,TagLibError;var init_base=__esmMin((()=>{SUPPORTED_FORMATS=[`MP3`,`AAC`,`MP4`,`M4A`,`FLAC`,`OGG`,`OPUS`,`OggFLAC`,`SPEEX`,`WAV`,`AIFF`,`ASF`,`APE`,`DSF`,`DSDIFF`,`WV`,`MPC`,`TTA`,`SHN`,`MOD`,`S3M`,`IT`,`XM`,`MATROSKA`,`MKA`];TagLibError=class TagLibError extends Error{constructor(code,message,details){super(message);this.code=code;this.details=details;this.name=`TagLibError`;Object.setPrototypeOf(this,TagLibError.prototype)}}}));function errorMessage(error){return error instanceof Error?error.message:String(error)}function createErrorMessage(prefix,details){return`${prefix}: ${details}`}function formatFileSize(bytes){if(bytes<1024)return`${bytes} bytes`;if(bytes<1048576)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/1048576).toFixed(1)} MB`}var TagLibInitializationError,InvalidFormatError,UnsupportedFormatError,FileOperationError,MetadataError,MemoryError,EnvironmentError;var init_classes=__esmMin((()=>{init_base();TagLibInitializationError=class TagLibInitializationError extends TagLibError{constructor(message,details){super(`INITIALIZATION`,createErrorMessage(`Failed to initialize TagLib Wasm module`,message),details);this.name=`TagLibInitializationError`;Object.setPrototypeOf(this,TagLibInitializationError.prototype)}};InvalidFormatError=class InvalidFormatError extends TagLibError{constructor(message,bufferSize,details){const errorDetails=[`Invalid audio file format: ${message}`];if(bufferSize!==void 0){errorDetails.push(`Buffer size: ${formatFileSize(bufferSize)}`);if(bufferSize<1024)errorDetails.push(`Audio files must be at least 1KB to contain valid headers.`)}super(`INVALID_FORMAT`,errorDetails.join(`. `),{...details,bufferSize});this.bufferSize=bufferSize;this.name=`InvalidFormatError`;Object.setPrototypeOf(this,InvalidFormatError.prototype)}};UnsupportedFormatError=class UnsupportedFormatError extends TagLibError{constructor(format,supportedFormats=SUPPORTED_FORMATS,details){super(`UNSUPPORTED_FORMAT`,`Unsupported audio format: ${format}. Supported formats: ${supportedFormats.join(`, `)}`,{...details,format,supportedFormats});this.format=format;this.supportedFormats=supportedFormats;this.name=`UnsupportedFormatError`;Object.setPrototypeOf(this,UnsupportedFormatError.prototype)}};FileOperationError=class FileOperationError extends TagLibError{constructor(operation,message,path,details){const errorDetails=[`Failed to ${operation} file`];if(path)errorDetails.push(`Path: ${path}`);errorDetails.push(message);super(`FILE_OPERATION`,errorDetails.join(`. `),{...details,operation,path});this.operation=operation;this.path=path;this.name=`FileOperationError`;Object.setPrototypeOf(this,FileOperationError.prototype)}};MetadataError=class MetadataError extends TagLibError{constructor(operation,message,field,details){const errorDetails=[`Failed to ${operation} metadata`];if(field)errorDetails.push(`Field: ${field}`);errorDetails.push(message);super(`METADATA`,errorDetails.join(`. `),{...details,operation,field});this.operation=operation;this.field=field;this.name=`MetadataError`;Object.setPrototypeOf(this,MetadataError.prototype)}};MemoryError=class MemoryError extends TagLibError{constructor(message,details){super(`MEMORY`,createErrorMessage(`Memory allocation failed`,message),details);this.name=`MemoryError`;Object.setPrototypeOf(this,MemoryError.prototype)}};EnvironmentError=class EnvironmentError extends TagLibError{constructor(environment,reason,requiredFeature){const message=requiredFeature?`Environment '${environment}' ${reason}. Required feature: ${requiredFeature}.`:`Environment '${environment}' ${reason}.`;super(`ENVIRONMENT`,message);this.environment=environment;this.reason=reason;this.requiredFeature=requiredFeature;this.name=`EnvironmentError`;Object.setPrototypeOf(this,EnvironmentError.prototype)}}}));function isTagLibError(error){return error instanceof TagLibError}function isInvalidFormatError(error){return error instanceof InvalidFormatError}function isUnsupportedFormatError(error){return error instanceof UnsupportedFormatError}function isFileOperationError(error){return error instanceof FileOperationError}function isMetadataError(error){return error instanceof MetadataError}function isMemoryError(error){return error instanceof MemoryError}function isEnvironmentError(error){return error instanceof EnvironmentError}var init_guards=__esmMin((()=>{init_base();init_classes()}));var init_errors$1=__esmMin((()=>{init_base();init_classes();init_guards()}));var init_errors=__esmMin((()=>{init_errors$1()}));function requireBwf(format){if(!BWF_FORMATS.has(format))throw new UnsupportedFormatError(format,[`WAV`,`FLAC`],{operation:`BWF metadata`})}function getBextData(handle){const raw=handle.getBextData();return raw&&raw.length>0?raw:void 0}function setBextData(handle,format,data){requireBwf(format);handle.setBextData(data)}function getBext(handle){const raw=handle.getBextData();return raw&&raw.length>0?decodeBext(raw):void 0}function setBext(handle,format,bext){requireBwf(format);handle.setBextData(encodeBext(bext))}function getIxml(handle){return handle.getIxml()}function setIxml(handle,format,data){requireBwf(format);handle.setIxml(data)}var BWF_FORMATS;var init_audio_file_bwf=__esmMin((()=>{init_bext();init_errors();BWF_FORMATS=/* @__PURE__ */ new Set([`WAV`,`FLAC`])}));function assertMp3(format){if(format!==`MP3`&&format!==`AAC`)throw new UnsupportedFormatError(format,[`MP3`,`AAC`],{operation:`id3v2Frames`})}function assertFrameId(id,operation){if(!FRAME_ID_PATTERN.test(id))throw new MetadataError(operation,`Invalid ID3v2 frame ID: "${id}". Frame IDs must match [A-Z0-9]{4}`,id)}function assertFrameBodies(id,data){for(const body of data)if(body.length===0)throw new MetadataError(`write`,`Frame data must not be empty: zero-size ID3v2 frames are invalid`,id)}function toPublicFrame(frame){return{id:frame.id,data:frame.data,...frame.flags?{flags:frame.flags}:{}}}var FRAME_ID_PATTERN;var init_id3v2_frames=__esmMin((()=>{init_classes();FRAME_ID_PATTERN=/^[A-Z0-9]{4}$/}));function getPlatformIO(){throw new Error(`Filesystem operations are not available in the browser.`)}var init__taglib_platform_io_stub=__esmMin((()=>{}));async function writeFileData(path,data){try{await getPlatformIO().writeFile(path,data)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`write`,error.message,path)}}var init_write=__esmMin((()=>{init_errors();init__taglib_platform_io_stub()}));function getNodeFsSync(){return null}var init__taglib_node_fs_stub=__esmMin((()=>{}));function normalized(value){return value}function popm(value){return value}function toNormalized(value){return value/255}function fromNormalized(value){return Math.round(value*255)}function toStars(value,maxStars=5){return Math.round(value*maxStars)}function fromStars(stars,maxStars=5){return stars/maxStars}function toPopm(value){const stars=Math.round(value*5);return POPM_STAR_VALUES[stars]??0}function fromPopm(value){if(value===0)return 0;if(value<=1)return .2;if(value<=64)return .4;if(value<=128)return .6;if(value<=196)return .8;return 1}function toPercent(value){return value*100}function fromPercent(percent){return percent/100}function clamp(rating){return Math.max(0,Math.min(1,rating))}function isValid(rating){return typeof rating===`number`&&!Number.isNaN(rating)&&rating>=0&&rating<=1}var POPM_STAR_VALUES,RatingUtils;var init_rating=__esmMin((()=>{POPM_STAR_VALUES=[0,1,64,128,196,255];RatingUtils={normalized,popm,toNormalized,fromNormalized,toStars,fromStars,toPopm,fromPopm,toPercent,fromPercent,clamp,isValid,POPM_STAR_VALUES}}));function isDeno(){return g.Deno!==void 0}var g,EXNREF_PROBE;var init_detector=__esmMin((()=>{g=globalThis;EXNREF_PROBE=new Uint8Array([0,97,115,109,1,0,0,0,6,6,1,105,0,208,105,11])}));function freeformTypeFromCode(code){return CODE_TO_TYPE[code]??`other`}function freeformCode(type,typeCode){if(type===`other`){if(typeCode===void 0||!Number.isInteger(typeCode)||typeCode<0||typeCode>255)throw new MetadataError(`write`,`MP4 freeform type "other" requires typeCode 0..255`);return typeCode}return TYPE_TO_CODE[type]}function validateAtomPart(label,value){if(value.length===0)throw new MetadataError(`write`,`MP4 freeform ${label} must not be empty`);if(value.includes(`:`))throw new MetadataError(`write`,`MP4 freeform ${label} must not contain ":"`)}function encodeFreeformValue(type,value){if(type===`utf8`){if(typeof value!==`string`)throw new MetadataError(`write`,`MP4 freeform type "utf8" requires a string value`);return new TextEncoder().encode(value)}if(type===`integer`){if(typeof value!==`number`||!Number.isInteger(value)||value<INT32_MIN||value>INT32_MAX)throw new MetadataError(`write`,`MP4 freeform type "integer" requires an int32 value`);const bytes=/* @__PURE__ */ new Uint8Array(4);new DataView(bytes.buffer).setInt32(0,value,false);return bytes}if(!(value instanceof Uint8Array))throw new MetadataError(`write`,`MP4 freeform type "${type}" requires a Uint8Array value`);return new Uint8Array(value)}function decodeFreeformValue(type,bytes){if(type===`utf8`)return new TextDecoder().decode(bytes);if(type===`integer`&&bytes.byteLength===4)return new DataView(bytes.buffer,bytes.byteOffset,4).getInt32(0,false);return new Uint8Array(bytes)}function validateFreeformItems(items){const types=/* @__PURE__ */ new Map;for(const item of items){const atom=`${item.mean}\u0000${item.name}`;const signature=item.type===`other`?`other:${item.typeCode??`missing`}`:item.type;const previous=types.get(atom);if(previous!==void 0&&previous!==signature)throw new MetadataError(`write`,`MP4 freeform atom "${item.mean}:${item.name}" cannot mix types "${previous}" and "${signature}"`);types.set(atom,signature)}}function toRawFreeformItem(item){validateAtomPart(`mean`,item.mean);validateAtomPart(`name`,item.name);return{mean:item.mean,name:item.name,type:freeformCode(item.type,item.typeCode),value:encodeFreeformValue(item.type,item.value)}}function fromRawFreeformItem(raw){const type=freeformTypeFromCode(raw.type);if(type===`integer`&&raw.value.byteLength!==4)return{mean:raw.mean,name:raw.name,type:`other`,typeCode:raw.type,value:new Uint8Array(raw.value)};const value=decodeFreeformValue(type,raw.value);return type===`other`?{mean:raw.mean,name:raw.name,type,typeCode:raw.type,value}:{mean:raw.mean,name:raw.name,type,value}}var TYPE_TO_CODE,CODE_TO_TYPE,INT32_MIN,INT32_MAX;var init_mp4_freeform=__esmMin((()=>{init_errors();TYPE_TO_CODE={implicit:0,utf8:1,utf16:2,jpeg:13,png:14,integer:21,bmp:27,undefined:255};CODE_TO_TYPE={0:`implicit`,1:`utf8`,2:`utf16`,13:`jpeg`,14:`png`,21:`integer`,27:`bmp`,255:`undefined`};INT32_MIN=-2147483648;INT32_MAX=2147483647}));var ADDITIONAL_PROPERTIES;var init_additional_properties=__esmMin((()=>{ADDITIONAL_PROPERTIES={albumArtistSort:{key:`ALBUMARTISTSORT`,description:`Sort name for album artist (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSO2`},vorbis:`ALBUMARTISTSORT`,mp4:`soaa`}},composerSort:{key:`COMPOSERSORT`,description:`Sort name for composer (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOC`},vorbis:`COMPOSERSORT`,mp4:`soco`}},subtitle:{key:`SUBTITLE`,description:`Subtitle or description refinement`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TIT3`},vorbis:`SUBTITLE`,mp4:`----:com.apple.iTunes:SUBTITLE`}},label:{key:`LABEL`,description:`Record label name`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TPUB`},vorbis:`LABEL`,mp4:`----:com.apple.iTunes:LABEL`,wav:`IPUB`}},producer:{key:`PRODUCER`,description:`Producer of the recording`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`PRODUCER`},vorbis:`PRODUCER`,mp4:`----:com.apple.iTunes:PRODUCER`}},radioStationOwner:{key:`RADIOSTATIONOWNER`,description:`Owner of the radio station`,type:`string`,supportedFormats:[`ID3v2`],mappings:{id3v2:{frame:`TRSO`}}},asin:{key:`ASIN`,description:`Amazon Standard Identification Number`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ASIN`},vorbis:`ASIN`,mp4:`----:com.apple.iTunes:ASIN`}},musicbrainzReleaseArtistId:{key:`MUSICBRAINZ_ALBUMARTISTID`,description:`MusicBrainz Release Artist ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Artist Id`},vorbis:`MUSICBRAINZ_ALBUMARTISTID`,mp4:`----:com.apple.iTunes:MusicBrainz Album Artist Id`}},musicbrainzWorkId:{key:`MUSICBRAINZ_WORKID`,description:`MusicBrainz Work ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Work Id`},vorbis:`MUSICBRAINZ_WORKID`,mp4:`----:com.apple.iTunes:MusicBrainz Work Id`}},musicbrainzReleaseTrackId:{key:`MUSICBRAINZ_RELEASETRACKID`,description:`MusicBrainz Release Track ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Release Track Id`},vorbis:`MUSICBRAINZ_RELEASETRACKID`,mp4:`----:com.apple.iTunes:MusicBrainz Release Track Id`}},podcastId:{key:`PODCASTID`,description:`Podcast episode identifier`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TGID`},vorbis:`PODCASTID`,mp4:`egid`}},podcastUrl:{key:`PODCASTURL`,description:`Podcast feed URL`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`WFED`},vorbis:`PODCASTURL`,mp4:`purl`}},originalArtist:{key:`ORIGINALARTIST`,description:`Original artist of a cover or remix`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{id3v2:{frame:`TOPE`},vorbis:`ORIGINALARTIST`}},originalAlbum:{key:`ORIGINALALBUM`,description:`Original album of a cover or remix`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{id3v2:{frame:`TOAL`},vorbis:`ORIGINALALBUM`}},originalDate:{key:`ORIGINALDATE`,description:`Original release date`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TDOR`},vorbis:`ORIGINALDATE`,mp4:`----:com.apple.iTunes:ORIGINALDATE`}},script:{key:`SCRIPT`,description:`Writing script used for text (e.g., Latn, Jpan)`,type:`string`,supportedFormats:[`MP4`,`Vorbis`],mappings:{vorbis:`SCRIPT`,mp4:`----:com.apple.iTunes:SCRIPT`}},involvedPeople:{key:`INVOLVEDPEOPLE`,description:`List of involved people and their roles`,type:`string`,supportedFormats:[`ID3v2`],mappings:{id3v2:{frame:`TIPL`}}},encoding:{key:`ENCODING`,description:`Encoding software or settings`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TSSE`},vorbis:`ENCODING`,mp4:`©too`,wav:`ISFT`}}}}));var BASIC_PROPERTIES;var init_basic_properties=__esmMin((()=>{BASIC_PROPERTIES={title:{key:`TITLE`,description:`The title of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TIT2`},vorbis:`TITLE`,mp4:`©nam`,wav:`INAM`}},artist:{key:`ARTIST`,description:`The primary performer(s) of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TPE1`},vorbis:`ARTIST`,mp4:`©ART`,wav:`IART`}},album:{key:`ALBUM`,description:`The album/collection name`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TALB`},vorbis:`ALBUM`,mp4:`©alb`,wav:`IPRD`}},date:{key:`DATE`,description:`The date of recording (typically year)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TDRC`},vorbis:`DATE`,mp4:`©day`,wav:`ICRD`}},trackNumber:{key:`TRACKNUMBER`,description:`The track number within the album`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TRCK`},vorbis:`TRACKNUMBER`,mp4:`trkn`,wav:`ITRK`}},genre:{key:`GENRE`,description:`The musical genre`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TCON`},vorbis:`GENRE`,mp4:`©gen`,wav:`IGNR`}},comment:{key:`COMMENT`,description:`Comments or notes about the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`COMM`},vorbis:`COMMENT`,mp4:`©cmt`,wav:`ICMT`}}}}));var GENERAL_EXTENDED_PROPERTIES;var init_general_extended_properties=__esmMin((()=>{GENERAL_EXTENDED_PROPERTIES={albumArtist:{key:`ALBUMARTIST`,description:`The album artist (band/orchestra/ensemble)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPE2`},vorbis:`ALBUMARTIST`,mp4:`aART`}},composer:{key:`COMPOSER`,description:`The original composer(s) of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TCOM`},vorbis:`COMPOSER`,mp4:`©wrt`}},copyright:{key:`COPYRIGHT`,description:`Copyright information`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{vorbis:`COPYRIGHT`}},encodedBy:{key:`ENCODEDBY`,description:`The encoding software or person`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{vorbis:`ENCODEDBY`}},discNumber:{key:`DISCNUMBER`,description:`The disc number for multi-disc sets`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPOS`},vorbis:`DISCNUMBER`,mp4:`disk`}},bpm:{key:`BPM`,description:`Beats per minute`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TBPM`},vorbis:`BPM`,mp4:`tmpo`}},totalTracks:{key:`TRACKTOTAL`,description:`Total number of tracks on the album`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TRCK`},vorbis:`TRACKTOTAL`,mp4:`trkn`}},totalDiscs:{key:`DISCTOTAL`,description:`Total number of discs in the set`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPOS`},vorbis:`DISCTOTAL`,mp4:`disk`}},compilation:{key:`COMPILATION`,description:`Whether the album is a compilation (various artists)`,type:`boolean`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TCMP`},vorbis:`COMPILATION`,mp4:`cpil`}},titleSort:{key:`TITLESORT`,description:`Sort name for title (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOT`},vorbis:`TITLESORT`,mp4:`sonm`}},artistSort:{key:`ARTISTSORT`,description:`Sort name for artist (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOP`},vorbis:`ARTISTSORT`,mp4:`soar`}},albumSort:{key:`ALBUMSORT`,description:`Sort name for album (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOA`},vorbis:`ALBUMSORT`,mp4:`soal`}},lyricist:{key:`LYRICIST`,description:`The lyrics/text writer(s)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LYRICIST`}},conductor:{key:`CONDUCTOR`,description:`The conductor`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`CONDUCTOR`}},remixedBy:{key:`REMIXER`,description:`Person who remixed the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPE4`},vorbis:`REMIXER`,mp4:`----:com.apple.iTunes:REMIXER`}},language:{key:`LANGUAGE`,description:`Language of vocals/lyrics`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LANGUAGE`}},publisher:{key:`PUBLISHER`,description:`The publisher`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`PUBLISHER`}},mood:{key:`MOOD`,description:`The mood/atmosphere of the track`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`MOOD`}},media:{key:`MEDIA`,description:`Media type (CD, vinyl, etc.)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`MEDIA`}},grouping:{key:`GROUPING`,description:`Content group/work`,type:`string`,supportedFormats:[`MP4`,`Vorbis`],mappings:{vorbis:`GROUPING`,mp4:`©grp`}},work:{key:`WORK`,description:`Work name`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`WORK`}},lyrics:{key:`LYRICS`,description:`Lyrics content`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LYRICS`}},isrc:{key:`ISRC`,description:`International Standard Recording Code`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`ISRC`}},catalogNumber:{key:`CATALOGNUMBER`,description:`Catalog number`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`CATALOGNUMBER`}},barcode:{key:`BARCODE`,description:`Barcode (EAN/UPC)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`BARCODE`}}}}));var SPECIALIZED_PROPERTIES;var init_specialized_properties=__esmMin((()=>{SPECIALIZED_PROPERTIES={musicbrainzArtistId:{key:`MUSICBRAINZ_ARTISTID`,description:`MusicBrainz Artist ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Artist Id`},vorbis:`MUSICBRAINZ_ARTISTID`,mp4:`----:com.apple.iTunes:MusicBrainz Artist Id`}},musicbrainzReleaseId:{key:`MUSICBRAINZ_ALBUMID`,description:`MusicBrainz Release ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Id`},vorbis:`MUSICBRAINZ_ALBUMID`,mp4:`----:com.apple.iTunes:MusicBrainz Album Id`}},musicbrainzTrackId:{key:`MUSICBRAINZ_TRACKID`,description:`MusicBrainz Recording ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`UFID`,description:`http://musicbrainz.org`},vorbis:`MUSICBRAINZ_TRACKID`,mp4:`----:com.apple.iTunes:MusicBrainz Track Id`}},musicbrainzReleaseGroupId:{key:`MUSICBRAINZ_RELEASEGROUPID`,description:`MusicBrainz Release Group ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Release Group Id`},vorbis:`MUSICBRAINZ_RELEASEGROUPID`,mp4:`----:com.apple.iTunes:MusicBrainz Release Group Id`}},releaseType:{key:`RELEASETYPE`,description:`Release type (album, single, EP, compilation, ...). Multi-value (e.g. 'album' + 'EP'). TagLib 2.3.2 translates the RELEASETYPE key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM TYPE' (TagLib's description casing), MP4 freeform atom, APEv2 MUSICBRAINZ_ALBUMTYPE, ASF 'MusicBrainz/Album Type', Vorbis/Matroska raw RELEASETYPE`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Type`},vorbis:`RELEASETYPE`,mp4:`----:com.apple.iTunes:MusicBrainz Album Type`}},releaseCountry:{key:`RELEASECOUNTRY`,description:`Release country (ISO 3166-1 code, e.g. 'US'). TagLib 2.3.2 translates the RELEASECOUNTRY key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM RELEASE COUNTRY' (TagLib's description casing; an uppercase TXXX:RELEASECOUNTRY description also reads back), MP4 freeform atom 'MusicBrainz Album Release Country', APEv2 raw RELEASECOUNTRY, ASF 'MusicBrainz/Album Release Country', WAV ICNT, Vorbis/Matroska raw RELEASECOUNTRY`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`,`WAV`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Release Country`},vorbis:`RELEASECOUNTRY`,mp4:`----:com.apple.iTunes:MusicBrainz Album Release Country`}},releaseStatus:{key:`RELEASESTATUS`,description:`Release status (official, promotion, bootleg, ...). TagLib 2.3.2 translates the RELEASESTATUS key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM STATUS' (TagLib's description casing), MP4 freeform atom 'MusicBrainz Album Status', APEv2 MUSICBRAINZ_ALBUMSTATUS, ASF 'MusicBrainz/Album Status', Vorbis/Matroska raw RELEASESTATUS`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Status`},vorbis:`RELEASESTATUS`,mp4:`----:com.apple.iTunes:MusicBrainz Album Status`}},itunesAdvisory:{key:`ITUNESADVISORY`,description:`Content advisory in the ITUNESADVISORY convention ('1' = explicit, '2' = clean, '0' = unspecified). On MP4 the value is stored in the native rtng atom and surfaced here. The typed tri-state lives on ExtendedTag.advisory; aliases CONTENTADVISORY and EXPLICIT resolve here`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`ITUNESADVISORY`},vorbis:`ITUNESADVISORY`,mp4:`----:com.apple.iTunes:ITUNESADVISORY`}},replayGainTrackGain:{key:`REPLAYGAIN_TRACK_GAIN`,description:`ReplayGain track gain in dB (e.g., '-6.54 dB')`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Track_Gain`},vorbis:`REPLAYGAIN_TRACK_GAIN`,mp4:`----:com.apple.iTunes:replaygain_track_gain`}},replayGainTrackPeak:{key:`REPLAYGAIN_TRACK_PEAK`,description:`ReplayGain track peak value (0.0-1.0)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Track_Peak`},vorbis:`REPLAYGAIN_TRACK_PEAK`,mp4:`----:com.apple.iTunes:replaygain_track_peak`}},replayGainAlbumGain:{key:`REPLAYGAIN_ALBUM_GAIN`,description:`ReplayGain album gain in dB`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Album_Gain`},vorbis:`REPLAYGAIN_ALBUM_GAIN`,mp4:`----:com.apple.iTunes:replaygain_album_gain`}},replayGainAlbumPeak:{key:`REPLAYGAIN_ALBUM_PEAK`,description:`ReplayGain album peak value (0.0-1.0)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Album_Peak`},vorbis:`REPLAYGAIN_ALBUM_PEAK`,mp4:`----:com.apple.iTunes:replaygain_album_peak`}},r128TrackGain:{key:`R128_TRACK_GAIN`,description:`EBU R128 track loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256, e.g. '-573' = -2.23828125 dB). readTags() converts to a decibel number (see ExtendedTag.r128TrackGain)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`R128_TRACK_GAIN`},vorbis:`R128_TRACK_GAIN`,mp4:`----:com.apple.iTunes:R128_TRACK_GAIN`}},r128AlbumGain:{key:`R128_ALBUM_GAIN`,description:`EBU R128 album loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256). readTags() converts to a decibel number`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`R128_ALBUM_GAIN`},vorbis:`R128_ALBUM_GAIN`,mp4:`----:com.apple.iTunes:R128_ALBUM_GAIN`}},acoustidFingerprint:{key:`ACOUSTID_FINGERPRINT`,description:`AcoustID fingerprint (Chromaprint)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`Acoustid Fingerprint`},vorbis:`ACOUSTID_FINGERPRINT`,mp4:`----:com.apple.iTunes:Acoustid Fingerprint`}},acoustidId:{key:`ACOUSTID_ID`,description:`AcoustID UUID`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`Acoustid Id`},vorbis:`ACOUSTID_ID`,mp4:`----:com.apple.iTunes:Acoustid Id`}},appleSoundCheck:{key:`ITUNNORM`,description:`Apple Sound Check normalization data`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`iTunNORM`},vorbis:`ITUNNORM`,mp4:`----:com.apple.iTunes:iTunNORM`}},appleGaplessInfo:{key:`ITUNSMPB`,description:`Apple gapless playback data (encoder delay and padding)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`iTunSMPB`},vorbis:`ITUNSMPB`,mp4:`----:com.apple.iTunes:iTunSMPB`}}}}));function toTagLibKey(key){return _toTagLib[key]??key}function mp4AtomWireKey(atom){return _mp4AtomToWireKey[atom]}function mp4FreeformAtomNames(wireKeys){const names=[];for(const key of wireKeys){const atom=_mp4FreeformAtoms[key];if(atom!==void 0)names.push(atom)}return names}function fromTagLibKey(key){return _fromTagLib[key]??key}function remapKeysFromTagLib(obj){const result={};for(const[key,value]of Object.entries(obj)){const canonical=READ_ALIASES[key];if(canonical!==void 0&&canonical in obj)continue;result[fromTagLibKey(key)]=value}return result}var PROPERTIES,_toTagLib,_fromTagLib,READ_ALIASES,_mp4FreeformAtoms,_mp4AtomToWireKey;var init_properties=__esmMin((()=>{init_additional_properties();init_basic_properties();init_general_extended_properties();init_specialized_properties();PROPERTIES={...BASIC_PROPERTIES,...GENERAL_EXTENDED_PROPERTIES,...SPECIALIZED_PROPERTIES,...ADDITIONAL_PROPERTIES};_toTagLib={};_fromTagLib={};for(const[camelKey,meta]of Object.entries(PROPERTIES)){const wireKey=meta.key;_toTagLib[camelKey]=wireKey;_fromTagLib[wireKey]=camelKey}_toTagLib[`year`]=`DATE`;_toTagLib[`track`]=`TRACKNUMBER`;_fromTagLib[`disc`]=`discNumber`;READ_ALIASES={"ALBUM ARTIST":`ALBUMARTIST`,ALBUM_ARTIST:`ALBUMARTIST`,ORGANIZATION:`LABEL`,PUBLISHER:`LABEL`,UPC:`BARCODE`,EAN:`BARCODE`,GTIN:`BARCODE`,TOTALTRACKS:`TRACKTOTAL`,TOTALDISCS:`DISCTOTAL`,MUSICBRAINZ_ALBUMTYPE:`RELEASETYPE`,"MusicBrainz Album Type":`RELEASETYPE`,MUSICBRAINZ_ALBUMSTATUS:`RELEASESTATUS`,"MusicBrainz Album Status":`RELEASESTATUS`,CONTENTADVISORY:`ITUNESADVISORY`,EXPLICIT:`ITUNESADVISORY`};for(const[alias,canonical]of Object.entries(READ_ALIASES))_fromTagLib[alias]??(_fromTagLib[alias]=_fromTagLib[canonical]);_mp4FreeformAtoms={};for(const meta of Object.values(PROPERTIES)){const{key,mappings}=meta;const atom=mappings?.mp4;if(typeof atom!==`string`||!atom.startsWith(`----:`))continue;const bare=atom.slice(atom.lastIndexOf(`:`)+1);if(bare===bare.toUpperCase())continue;_mp4FreeformAtoms[key]=atom;const readKey=bare.toUpperCase();const camel=_fromTagLib[key];if(camel!==void 0&&_fromTagLib[readKey]===void 0)_fromTagLib[readKey]=camel}_mp4AtomToWireKey={};for(const meta of Object.values(PROPERTIES)){const{key,mappings}=meta;const atom=mappings?.mp4;if(typeof atom!==`string`||atom.startsWith(`----:`))continue;_mp4AtomToWireKey[atom]??(_mp4AtomToWireKey[atom]=key)}}));var MP4_ITEM_NAMES_KEY;var init_mp4_item_names=__esmMin((()=>{MP4_ITEM_NAMES_KEY=`_mp4ItemNames`}));function buildGetters(state,handle){const tag={};for(const field of TAG_GETTER_FIELDS)Object.defineProperty(tag,field,{enumerable:true,configurable:true,get:()=>state.data[field]});Object.defineProperties(tag,{year:{enumerable:true,configurable:true,get:()=>state.data.year},track:{enumerable:true,configurable:true,get:()=>state.data.track},date:{enumerable:true,configurable:true,get:()=>handle.getProperty(`DATE`)||void 0}});return tag}function stageTrackWrite(handle,value){const existing=value>0?handle.getProperty(RAW_TRACK_WIRE_KEY):``;const slash=existing.indexOf(`/`);if(slash!==-1)handle.setProperty(RAW_TRACK_WIRE_KEY,`${value}${existing.slice(slash)}`);else handle.setTagData({track:value})}function stageDateWrite(handle,value){if(value===``)handle.setTagData({year:0});else handle.setProperty(`DATE`,value)}function buildMutableTag(handle){const state={data:handle.getTagData()};const tag=buildGetters(state,handle);const refresh=()=>{state.data=handle.getTagData();return tag};const setBasic=(field,value)=>{handle.setTagData({[field]:value});return refresh()};tag.setTitle=value=>setBasic(`title`,value);tag.setArtist=value=>setBasic(`artist`,value);tag.setAlbum=value=>setBasic(`album`,value);tag.setComment=value=>setBasic(`comment`,value);tag.setGenre=value=>setBasic(`genre`,value);tag.setYear=value=>setBasic(`year`,value);tag.setTrack=value=>{stageTrackWrite(handle,value);return refresh()};tag.setDate=value=>{stageDateWrite(handle,value);return refresh()};return tag}var RAW_TRACK_WIRE_KEY,TAG_GETTER_FIELDS;var init_mutable_tag_impl=__esmMin((()=>{init_properties();RAW_TRACK_WIRE_KEY=toTagLibKey(`trackNumber`);TAG_GETTER_FIELDS=[`title`,`artist`,`album`,`comment`,`genre`]}));function registerAutoDispose(target,handle){registry.register(target,handle,target)}function unregisterAutoDispose(target){registry.unregister(target)}var registry;var init_auto_dispose=__esmMin((()=>{registry=new FinalizationRegistry(handle=>{handle.destroy()})}));function _typeof(o){"@babel/helpers - typeof";return _typeof=`function`==typeof Symbol&&`symbol`==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&`function`==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?`symbol`:typeof o},_typeof(o)}var init_typeof=__esmMin((()=>{}));function toPrimitive(t,r){if(`object`!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||`default`);if(`object`!=_typeof(i))return i;throw new TypeError(`@@toPrimitive must return a primitive value.`)}return(`string`===r?String:Number)(t)}var init_toPrimitive=__esmMin((()=>{init_typeof()}));function toPropertyKey(t){var i=toPrimitive(t,`string`);return`symbol`==_typeof(i)?i:i+``}var init_toPropertyKey=__esmMin((()=>{init_typeof();init_toPrimitive()}));function _defineProperty(e,r,t){return(r=toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var init_defineProperty=__esmMin((()=>{init_toPropertyKey()}));var _Symbol$dispose,LYRICS_PROPERTY_KEY,LYRICS_WIRE_KEY,EMPTY_KEY_SET,BaseAudioFileImpl;var init_audio_file_base=__esmMin((()=>{init_mp4_freeform();init_properties();init_errors();init_mp4_item_names();init_mutable_tag_impl();init_auto_dispose();init_defineProperty();;LYRICS_PROPERTY_KEY=`lyrics`;LYRICS_WIRE_KEY=toTagLibKey(LYRICS_PROPERTY_KEY);EMPTY_KEY_SET=/* @__PURE__ */ new Set;_Symbol$dispose=Symbol.dispose;BaseAudioFileImpl=class{constructor(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded=false,partialLoadOptions){this.module=module;_defineProperty(this,`fileHandle`,void 0);_defineProperty(this,`cachedAudioProperties`,null);_defineProperty(this,`sourcePath`,void 0);_defineProperty(this,`originalSource`,void 0);_defineProperty(this,`isPartiallyLoaded`,false);_defineProperty(this,`partialLoadOptions`,void 0);_defineProperty(this,`partialKeysAtLoad`,void 0);this.fileHandle=fileHandle;this.sourcePath=sourcePath;this.originalSource=originalSource;this.isPartiallyLoaded=isPartiallyLoaded;this.partialLoadOptions=partialLoadOptions;this.partialKeysAtLoad=isPartiallyLoaded?new Set(Object.keys(fileHandle.getProperties())):void 0;registerAutoDispose(this,fileHandle)}partialDeletedPropertyKeys(){if(!this.partialKeysAtLoad)return EMPTY_KEY_SET;const current=new Set(Object.keys(this.handle.getProperties()));const deleted=/* @__PURE__ */ new Set;for(const key of this.partialKeysAtLoad)if(key!==LYRICS_WIRE_KEY&&!current.has(key))deleted.add(key);return deleted}get handle(){if(!this.fileHandle)throw new MetadataError(`read`,`File handle has been disposed`);return this.fileHandle}getFormat(){return this.handle.getFormat()}isFormat(format){return this.getFormat()===format}tag(){return buildMutableTag(this.handle)}audioProperties(){this.cachedAudioProperties??(this.cachedAudioProperties=this.handle.getAudioProperties()??null);return this.cachedAudioProperties??void 0}properties(){const remapped=remapKeysFromTagLib(this.handle.getProperties());delete remapped[LYRICS_PROPERTY_KEY];return remapped}setProperties(properties){const translated={};for(const[key,values]of Object.entries(properties))if(values!==void 0){const wireKey=toTagLibKey(fromTagLibKey(key));const emptyTotal=(wireKey===`TRACKTOTAL`||wireKey===`DISCTOTAL`)&&values.every(v=>v===``);if(emptyTotal&&!this.module.isWasi)continue;translated[wireKey]=emptyTotal?[]:values}if(!(LYRICS_WIRE_KEY in translated)){const existing=this.handle.getProperties()[LYRICS_WIRE_KEY];if(existing!==void 0)translated[LYRICS_WIRE_KEY]=existing}const atomNames=mp4FreeformAtomNames(Object.keys(translated));if(atomNames.length>0)translated[MP4_ITEM_NAMES_KEY]=atomNames;this.handle.setProperties(translated)}getProperty(key){const wireKey=toTagLibKey(fromTagLibKey(key));const values=this.handle.getProperties()[wireKey]?.filter(v=>v!==``);if(values!==void 0&&values.length>0)return values;if(!this.isMP4())return void 0;const remapped=this.properties()[key]?.filter(v=>v!==``);return remapped!==void 0&&remapped.length>0?remapped:void 0}setProperty(key,value){const wireKey=toTagLibKey(fromTagLibKey(key));if((wireKey===`TRACKTOTAL`||wireKey===`DISCTOTAL`)&&value===``){this.clearTotal(wireKey);return}const nextValue=this.preserveIntPairTotal(wireKey,value);const atomNames=mp4FreeformAtomNames([wireKey]);if(atomNames.length>0&&this.isMP4()){this.writeMp4FreeformProperty(wireKey,value,atomNames);return}this.handle.setProperty(wireKey,nextValue)}clearTotal(wireKey){const rest={...this.handle.getProperties()};if(this.module.isWasi)rest[wireKey]=[];else delete rest[wireKey];this.handle.setProperties(rest)}preserveIntPairTotal(wireKey,value){if(wireKey!==`TRACKNUMBER`&&wireKey!==`DISCNUMBER`||value===``||value.includes(`/`))return value;const existing=this.handle.getProperty(wireKey);const slash=existing.indexOf(`/`);return slash===-1?value:`${value}${existing.slice(slash)}`}writeMp4FreeformProperty(wireKey,value,atomNames){if(value===``){const prior=this.handle.getMp4ItemRemovals?.()??[];this.handle.setMp4ItemRemovals?.([.../* @__PURE__ */ new Set([...prior,...atomNames])]);if(this.module.isWasi)this.handle.setProperties({...this.handle.getProperties(),[wireKey]:[]});else{const rest={...this.handle.getProperties()};delete rest[wireKey];this.handle.setProperties(rest)}return}this.handle.setProperties({...this.handle.getProperties(),[wireKey]:[value],[MP4_ITEM_NAMES_KEY]:[...atomNames]})}removeProperty(key){this.setProperty(key,``)}isMP4(){return this.handle.isMP4()}getMP4Item(key){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);const wireKey=mp4AtomWireKey(key);const value=wireKey!==void 0?this.handle.getProperty(wireKey):this.handle.getMP4Item(key);return value===``?void 0:value}setMP4Item(key,value){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);const wireKey=mp4AtomWireKey(key);if(wireKey!==void 0){this.handle.setProperty(wireKey,value);return}if(value===``){this.handle.removeMP4Item(key);return}this.handle.setMP4Item(key,value)}removeMP4Item(key){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);this.handle.removeMP4Item(key)}getMP4FreeformItems(){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);if(!this.handle.getMP4FreeformItems)throw new MetadataError(`read`,`MP4 freeform items are unavailable on this backend`);return this.handle.getMP4FreeformItems().map(fromRawFreeformItem)}setMP4FreeformItems(items){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);if(!this.handle.setMP4FreeformItems)throw new MetadataError(`write`,`MP4 freeform items are unavailable on this backend`);validateFreeformItems(items);this.handle.setMP4FreeformItems(items.map(toRawFreeformItem))}isValid(){return this.handle.isValid()}dispose(){unregisterAutoDispose(this);if(this.fileHandle){this.fileHandle.destroy();this.fileHandle=null;this.cachedAudioProperties=null}}[_Symbol$dispose](){this.dispose()}}}));function be32(b,offset){return(b[offset]<<24|b[offset+1]<<16|b[offset+2]<<8|b[offset+3])>>>0}function startsWith(bytes,magic,at=0){if(bytes.length<at+magic.length)return false;for(let i=0;i<magic.length;i++)if(bytes[at+i]!==magic.codePointAt(i))return false;return true}function id3v2End(bytes){if(!startsWith(bytes,`ID3`)||bytes.length<10)return void 0;const size=bytes[6]<<21|bytes[7]<<14|bytes[8]<<7|bytes[9];const hasFooter=(bytes[5]&16)!==0;return 10+size+(hasFooter?10:0)}function flacEnd(bytes,limit,start){let offset=start+4;for(;;){if(offset+4>bytes.length)return void 0;const isLast=(bytes[offset]&128)!==0;const length=bytes[offset+1]<<16|bytes[offset+2]<<8|bytes[offset+3];offset+=4+length;if(offset>limit)return offset;if(isLast)return offset}}function flacMarkerOffset(bytes){const at=startsWith(bytes,`ID3`)?id3v2End(bytes):0;if(at===void 0)return void 0;return startsWith(bytes,`fLaC`,at)?at:void 0}function flacAudioStart(bytes){const at=flacMarkerOffset(bytes);if(at===void 0)return void 0;return flacEnd(bytes,bytes.length,at)}function mp4MoovEnd(bytes,limit,start){let offset=start;const readable=Math.min(bytes.length,limit);while(offset+8<=readable){const size=be32(bytes,offset);const type=String.fromCodePoint(bytes[offset+4],bytes[offset+5],bytes[offset+6],bytes[offset+7]);if(size<8)return void 0;if(type===`moov`)return offset+size;offset+=size}}function oggMetadataEnd(bytes,limit,start){let offset=start;let packetsCompleted=0;let first=true;for(;;){if(offset+27>bytes.length||!startsWith(bytes,`OggS`,offset))return;const segmentCount=bytes[offset+26];const tableStart=offset+27;if(tableStart+segmentCount>bytes.length)return void 0;let payload=0;for(let i=0;i<segmentCount;i++){const segment=bytes[tableStart+i];payload+=segment;if(segment<255)packetsCompleted++}if(first){const payloadStart=tableStart+segmentCount;if(payloadStart+5>bytes.length)return void 0;if(bytes[payloadStart]===127&&startsWith(bytes,`FLAC`,payloadStart+1))return;first=false}offset=tableStart+segmentCount+payload;if(packetsCompleted>=2||offset>limit)return offset}}function parseMpegFrameHeader(bytes,at){if(bytes.length<at+4)return void 0;if(bytes[at]!==255||(bytes[at+1]&224)!==224)return void 0;const version=bytes[at+1]>>3&3;const layer=bytes[at+1]>>1&3;if(version===1||layer===0)return void 0;const bitrateIndex=bytes[at+2]>>4&15;const sampleRateIndex=bytes[at+2]>>2&3;if(bitrateIndex===0||bitrateIndex===15||sampleRateIndex===3)return;let sampleRateTable=2;if(version===3)sampleRateTable=0;else if(version===2)sampleRateTable=1;return{mpeg1:version===3,layerIndex:layer^3,bitrateIndex,sampleRateIndex,sampleRateTable}}function mpegFrameLength(bytes,at){const header=parseMpegFrameHeader(bytes,at);if(!header)return 0;const{mpeg1,layerIndex,bitrateIndex,sampleRateIndex,sampleRateTable}=header;const bitrate=MPEG_BITRATES[mpeg1?0:1][layerIndex][bitrateIndex];const sampleRate=MPEG_SAMPLE_RATES[sampleRateTable][sampleRateIndex];let samplesPerFrame;if(layerIndex===2)samplesPerFrame=mpeg1?1152:576;else if(layerIndex===1)samplesPerFrame=1152;else samplesPerFrame=384;let frameLength=Math.floor(samplesPerFrame*bitrate*125/sampleRate);if((bytes[at+2]&2)!==0)frameLength+=layerIndex===0?4:1;return frameLength===0?0:frameLength}function isMpegFrameSync(bytes,at=0){const frameLength=mpegFrameLength(bytes,at);if(frameLength===0)return false;const next=at+frameLength;if(bytes.length<next+4)return false;const mask=4294839296;return((bytes[at]<<24|bytes[at+1]<<16|bytes[at+2]<<8|bytes[at+3])>>>0&mask)>>>0===((bytes[next]<<24|bytes[next+1]<<16|bytes[next+2]<<8|bytes[next+3])>>>0&mask)>>>0}function containerEnd(bytes,at,limit){if(at>=bytes.length)return bytes.length<limit?null:void 0;if(at+8>bytes.length)return void 0;if(startsWith(bytes,`fLaC`,at))return flacEnd(bytes,limit,at);if(startsWith(bytes,`ftyp`,at+4))return mp4MoovEnd(bytes,limit,at);if(startsWith(bytes,`OggS`,at))return oggMetadataEnd(bytes,limit,at);return null}function id3MetadataEnd(header,limit){const tagEnd=id3v2End(header);if(tagEnd===void 0)return void 0;if(tagEnd>limit)return tagEnd;const behind=containerEnd(header,tagEnd,limit);if(behind===void 0)return void 0;return behind??tagEnd}function headerMetadataEnd(header,limit){if(startsWith(header,`ID3`))return id3MetadataEnd(header,limit);const container=containerEnd(header,0,limit);if(container!==null)return container;return isMpegFrameSync(header)?0:void 0}function metadataFitsInHeader(header,limit){const end=headerMetadataEnd(header,limit);if(end===void 0||end>header.length)return false;return end<=limit}function apeFooterSize(tail,at){if(at<0||!startsWith(tail,`APETAGEX`,at))return void 0;return(tail[at+12]|tail[at+13]<<8|tail[at+14]<<16|tail[at+15]<<24)>>>0}function trailerFitsInFooter(tail,footerSize){if(tail.length<Math.min(footerSize,32))return false;for(const offsetFromEnd of[32,160]){const size=apeFooterSize(tail,tail.length-offsetFromEnd);if(size===void 0)continue;const trailing=offsetFromEnd===32?0:128;if(size+32+trailing>footerSize)return false}return true}var MPEG_BITRATES,MPEG_SAMPLE_RATES;var init_metadata_extent=__esmMin((()=>{MPEG_BITRATES=[[[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0],[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,0],[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0]],[[0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0],[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0]]];MPEG_SAMPLE_RATES=[[44100,48e3,32e3],[22050,24e3,16e3],[11025,12e3,8e3]]}));function adtsFrameLength(bytes,at){if(bytes.length<at+7)return 0;if(bytes[at]!==255||(bytes[at+1]&246)!==240)return 0;const length=(bytes[at+3]&3)<<11|bytes[at+4]<<3|bytes[at+5]>>5;return length>=7?length:0}function trailingTagStart(bytes,end=bytes.length){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let at=Math.max(0,Math.min(end,bytes.length));for(;;){if(at>=128&&text(bytes,at-128,3)===`TAG`){at-=128;continue}if(at>=32&&text(bytes,at-32,8)===`APETAGEX`){const size=view.getUint32(at-32+12,true);const flags=view.getUint32(at-32+20,true);const start=at-size-((flags&2147483648)!==0?32:0);if(start<0||start>=at)return at;at=start;continue}return at}}function firstFrame(bytes){const from=id3v2End(bytes)??0;const limit=Math.min(bytes.length-6,from+MPEG_SCAN_LIMIT);for(let o=from;o<limit;o++){const len=frameLengthAt(bytes,o);if(len>0&&frameLengthAt(bytes,o+len)>0)return o}return-1}function forwardLastFrame(bytes,from,end){let o=from;let start=-1;let length=0;let frames=0;while(o+6<=end){const len=frameLengthAt(bytes,o);if(len===0||o+len>end)break;start=o;length=len;frames++;o+=len}return{start,length,frames}}function walkMpeg(bytes){const from=firstFrame(bytes);if(from<0)return fallback(`no valid first frame`);const last=forwardLastFrame(bytes,from,trailingTagStart(bytes));if(last.start<0)return fallback(`no valid frames`);return{kind:`ranges`,ranges:[{offset:from,length:last.start+last.length-from}],detail:`first=${from} last=${last.start}+${last.length} frames=${last.frames}`}}function flacStreamInfoMd5(bytes){const marker=flacMarkerOffset(bytes);if(marker===void 0)return void 0;const header=marker+4;if(header+4>bytes.length)return void 0;if((bytes[header]&127)!==0)return void 0;if((bytes[header+1]<<16|bytes[header+2]<<8|bytes[header+3])<34)return void 0;const payload=header+4;if(payload+34>bytes.length)return void 0;let hex=``;for(const byte of bytes.subarray(payload+18,payload+34))hex+=byte.toString(16).padStart(2,`0`);return hex}function walkFlac(bytes){const start=flacAudioStart(bytes);if(start===void 0)return fallback(`no fLaC marker`);const end=trailingTagStart(bytes);if(end<=start)return fallback(`no audio bytes`);return{kind:`ranges`,ranges:[{offset:start,length:end-start}],detail:`audioStart=${start} end=${end}`}}function atomLength(bytes,view,o){const size=view.getUint32(o,false);if(size===0)return{length:bytes.length-o,headerSize:8};if(size===1){if(o+16>bytes.length)return void 0;const big=view.getBigUint64(o+8,false);if(big>BigInt(Number.MAX_SAFE_INTEGER))return void 0;return{length:Number(big),headerSize:16}}return{length:size,headerSize:8}}function walkMp4(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const ranges=[];let o=0;while(o+8<=bytes.length){const type=text(bytes,o+4,4);const atom=atomLength(bytes,view,o);if(atom===void 0)return fallback(`malformed ${type} size`);if(atom.length<atom.headerSize)return fallback(`malformed ${type} size`);if(o+atom.length>bytes.length)return fallback(`oversized ${type}`);if(type===`mdat`&&atom.length>atom.headerSize)ranges.push({offset:o+atom.headerSize,length:atom.length-atom.headerSize});o+=atom.length}if(o!==bytes.length)return fallback(`trailing bytes after the last atom`);if(ranges.length===0)return fallback(`no non-empty mdat`);return{kind:`ranges`,ranges,detail:`${ranges.length} mdat(s)`}}function walkWav(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);if(text(bytes,0,4)!==`RIFF`)return fallback(`not RIFF`);if(text(bytes,8,4)!==`WAVE`)return fallback(`not WAVE`);const ranges=[];let o=12;while(o+8<=bytes.length){const id=text(bytes,o,4);const size=view.getUint32(o+4,true);const dataStart=o+8;if(dataStart+size>bytes.length)return fallback(`truncated ${id}`);if(id===`data`&&size>0)ranges.push({offset:dataStart,length:size});o=dataStart+size+size%2}if(ranges.length===0)return fallback(`no data chunk`);return{kind:`ranges`,ranges,detail:`${ranges.length} data chunk(s)`}}function mediaRanges(format,bytes){const walked=(()=>{switch(format.toUpperCase()){case`MP3`:case`AAC`:return walkMpeg(bytes);case`FLAC`:return walkFlac(bytes);case`MP4`:case`M4A`:return walkMp4(bytes);case`WAV`:return walkWav(bytes);default:return{kind:`fallback`,ranges:[],detail:`format not covered`}}})();if(walked.kind===`fallback`)return{kind:`fallback`,ranges:[{offset:0,length:bytes.length}],detail:`${walked.detail} → whole file`};return walked}var decoder,text,fallback,frameLengthAt,MPEG_SCAN_LIMIT;var init_media_ranges=__esmMin((()=>{init_metadata_extent();decoder=new TextDecoder;text=(b,o,n)=>decoder.decode(b.subarray(o,o+n));fallback=detail=>({kind:`fallback`,ranges:[],detail});frameLengthAt=(bytes,at)=>mpegFrameLength(bytes,at)||adtsFrameLength(bytes,at);MPEG_SCAN_LIMIT=65536}));async function fileBytes(source,io){if(source.path)return await io.readFile(source.path);if(source.blob)return new Uint8Array(await source.blob.arrayBuffer());if(!source.partiallyLoaded&&source.bytes.length>0)return source.bytes;throw new MetadataError(`read`,`the handle holds no file bytes and has no readable source; a partial handle that has been saved drops its source — checksum the saved path instead`)}function joinRanges(bytes,ranges){const total=ranges.reduce((n,r)=>n+r.length,0);const overrun=ranges.find(r=>r.offset+r.length>bytes.length);if(overrun||total>bytes.length)throw new MetadataError(`read`,`range walk overran the buffer (${overrun?`range ${overrun.offset}+${overrun.length}`:`${total} bytes`} past the ${bytes.length}-byte buffer)`);if(ranges.length===1){const only=ranges[0];const view=bytes.subarray(only.offset,only.offset+only.length);return view.buffer instanceof ArrayBuffer?view:new Uint8Array(view)}const out=new Uint8Array(total);let at=0;for(const r of ranges){out.set(bytes.subarray(r.offset,r.offset+r.length),at);at+=r.length}return out}async function pcmChecksum(source,format,io){if(format.toUpperCase()!==`FLAC`)throw new UnsupportedFormatError(format,[`FLAC`],{operation:`media checksum (basis: pcm)`});let windowed;if(source.bytes.length>0)windowed=source.bytes;else if(source.path&&io.readPartial)windowed=await io.readPartial(source.path,STREAMINFO_WINDOW,0);let md5=windowed===void 0?void 0:flacStreamInfoMd5(windowed);if(md5===void 0&&windowed!==source.bytes)md5=flacStreamInfoMd5(await fileBytes(source,io));if(md5===void 0)throw new MetadataError(`read`,`STREAMINFO digest unavailable`);return{source:`flac-streaminfo-md5`,algorithm:`md5`,hex:md5,bytesHashed:16}}async function mediaChecksum(source,format,io,options={}){if(options.basis===`pcm`)return pcmChecksum(source,format,io);const bytes=await fileBytes(source,io);const walk=mediaRanges(format,bytes);const payload=joinRanges(bytes,walk.ranges);const digest=new Uint8Array(await crypto.subtle.digest(`SHA-256`,payload));let hex=``;for(const byte of digest)hex+=byte.toString(16).padStart(2,`0`);return{source:walk.kind===`ranges`?`audio-payload`:`file`,algorithm:`sha256`,hex,bytesHashed:payload.length}}var STREAMINFO_WINDOW;var init_audio_file_checksum=__esmMin((()=>{init_media_ranges();init_errors();STREAMINFO_WINDOW=65536}));async function readFileData(file){if(file instanceof Uint8Array)return file;if(file instanceof ArrayBuffer)return new Uint8Array(file);if(typeof File!==`undefined`&&file instanceof File)return new Uint8Array(await file.arrayBuffer());if(typeof file===`string`)try{return await getPlatformIO().readFile(file)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`read`,error.message,file)}const inputType=Object.prototype.toString.call(file);throw new FileOperationError(`read`,`Invalid file input type: ${inputType}. Expected string path, Uint8Array, ArrayBuffer, or File object.`)}async function getFileSize(path){try{return(await getPlatformIO().stat(path)).size}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`stat`,error.message,path)}}async function readPartialFileData(path,headerSize,footerSize){const io=getPlatformIO();if(!io.readPartial)throw new EnvironmentError(`current runtime`,`does not support partial file reading`,`filesystem access with seek support`);try{return await io.readPartial(path,headerSize,footerSize)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`read`,error.message,path)}}var init_file=__esmMin((()=>{init_errors();init__taglib_platform_io_stub()}));function isValidBitrateMode(value){return value===`CBR`||value===`VBR`||value===`ABR`}function wrapEmbindHandle(raw){const stagedId3v2Frames={};let destroyed=false;const overrides={getTagData(){const tw=raw.getTag();return{title:tw.title(),artist:tw.artist(),album:tw.album(),comment:tw.comment(),genre:tw.genre(),year:tw.year(),track:tw.track()}},setTagData(data){const tw=raw.getTag();if(data.title!==void 0)tw.setTitle(data.title);if(data.artist!==void 0)tw.setArtist(data.artist);if(data.album!==void 0)tw.setAlbum(data.album);if(data.comment!==void 0)tw.setComment(data.comment);if(data.genre!==void 0)tw.setGenre(data.genre);if(data.year!==void 0)tw.setYear(data.year);if(data.track!==void 0)tw.setTrack(data.track)},getBextData(){const v=raw.getBextData();if(v===void 0||v===null)return void 0;const u8=v instanceof Uint8Array?v:new Uint8Array(v);return u8.length>0?u8:void 0},setBextData(data){raw.setBextData(data??null)},getIxml(){const v=raw.getIxml();return typeof v===`string`&&v.length>0?v:void 0},setIxml(data){raw.setIxml(data??null)},getLyrics(){return(raw.getProperties()[`LYRICS`]??[]).map(text=>({text,description:``,language:``}))},setLyrics(lyrics){const handle=raw;const props=handle.getProperties();if(lyrics.length>0)props[`LYRICS`]=lyrics.map(l=>l.text);else delete props[`LYRICS`];handle.setProperties(props)},setId3v2Frames(id,data){stagedId3v2Frames[id]=data.map(d=>new Uint8Array(d));raw.setId3v2Frames(id,data)},removeId3v2Frames(id){stagedId3v2Frames[id]=[];raw.removeId3v2Frames(id)},getStagedId3v2Frames(){return Object.keys(stagedId3v2Frames).length>0?{...stagedId3v2Frames}:void 0},hasId3Tags(){const v=raw.hasId3Tags();if(!v||typeof v!==`object`)return{v1:false,v2:false};const o=v;return{v1:o.v1===true,v2:o.v2===true}},stripId3Tags(opts){raw.stripId3Tags(opts)},destroy(){if(destroyed)return;destroyed=true;raw.destroy()},get destroyed(){return destroyed},setMp4ItemRemovals(removals){const handle=raw;for(const name of removals)handle.removeMP4Item(name)},getMP4FreeformItems(){return raw.getMP4FreeformItems()},setMP4FreeformItems(items){raw.setMP4FreeformItems(items)},getAudioProperties(){const pw=raw.getAudioProperties();if(!pw)return null;const containerFormat=pw.containerFormat()||`unknown`;const codec=pw.codec()||`unknown`;const mpegVersion=pw.mpegVersion();const formatVersion=pw.formatVersion();const bitrateMode=pw.bitrateMode();const isEncrypted=pw.isEncrypted();return{duration:pw.lengthInSeconds(),durationMs:pw.lengthInMilliseconds(),bitrate:pw.bitrate(),sampleRate:pw.sampleRate(),channels:pw.channels(),bitsPerSample:pw.bitsPerSample(),codec,containerFormat,isLossless:pw.isLossless(),...mpegVersion>0?{mpegVersion,mpegLayer:pw.mpegLayer()}:{},...isEncrypted||containerFormat===`MP4`||containerFormat===`ASF`?{isEncrypted}:{},...formatVersion>0?{formatVersion}:{},...isValidBitrateMode(bitrateMode)?{bitrateMode}:{},...containerFormat===`OGG`&&codec===`Opus`?{outputGainDb:pw.outputGainDb()}:{}}}};return new Proxy(raw,{get(target,prop,receiver){if(prop in overrides)return overrides[prop];const value=Reflect.get(target,prop,receiver);return typeof value===`function`?value.bind(target):value}})}var init_embind_adapter=__esmMin((()=>{}));function chapterStyle(chapters){const s=chapters[0]?.source;return s===`nero`||s===`both`?s:`quicktime`}function freeformSignature(items){return items.map(item=>`${item.mean}\u0000${item.name}\u0000${item.type}\u0000`+Array.from(item.value).join(`,`)).sort((a,b)=>a.localeCompare(b)).join(`
2
+ `)}function copyExtraState(target,source,sourceComplete){for(const field of EXTRA_FIELDS)field.copy(target,source,sourceComplete)}var EXTRA_FIELDS;var init_extra_state_registry=__esmMin((()=>{EXTRA_FIELDS=[{name:`pictures`,copy(target,source,complete){const v=source.getPictures();if(complete||v.length>0)target.setPictures(v)}},{name:`ratings`,copy(target,source,complete){const v=source.getRatings();if(complete||v.length>0)target.setRatings(v)}},{name:`lyrics`,copy(target,source,complete){const v=source.getLyrics();if(complete||v.length>0)target.setLyrics(v)}},{name:`chapters`,copy(target,source,complete){const v=source.getChapters();if(complete||v.length>0)target.setChapters(v,chapterStyle(v))}},{name:`bextData`,copy(target,source,complete){const v=source.getBextData();if(v!==void 0)target.setBextData(v);else if(complete)target.setBextData(null)}},{name:`ixml`,copy(target,source,complete){const v=source.getIxml();if(v!==void 0)target.setIxml(v);else if(complete)target.setIxml(null)}},{name:`_mp4Freeform`,copy(target,source,complete){const items=source.getMP4FreeformItems?.();if(items===void 0)return;if(!complete&&items.length===0)return;const targetItems=target.getMP4FreeformItems?.()??[];if(freeformSignature(items)===freeformSignature(targetItems))return;target.setMP4FreeformItems?.(items)}},{name:`_mp4ItemRemovals`,copy(target,source,complete){const v=source.getMp4ItemRemovals?.();if(complete||v!==void 0&&v.length>0)target.setMp4ItemRemovals?.(v??[])}},{name:`id3v2Frames`,copy(target,source){const staged=source.getStagedId3v2Frames?.();if(!staged)return;for(const[id,bodies]of Object.entries(staged))target.setId3v2Frames(id,bodies)}}]}));function copyEditedState(target,source,sourceComplete,deletedKeys){target.setTagData(source.getTagData());const merged=sourceComplete?source.getProperties():{...target.getProperties(),...source.getProperties()};for(const key of deletedKeys)delete merged[key];const atomNames=mp4FreeformAtomNames(Object.keys(merged));if(atomNames.length>0)merged[MP4_ITEM_NAMES_KEY]=atomNames;target.setProperties(merged);copyExtraState(target,source,sourceComplete)}async function saveViaFreshHandle(module,editing,source,targetPath,sourceComplete,deletedKeys=/* @__PURE__ */ new Set){const rawFullHandle=module.createFileHandle();const fullFileHandle=module.isWasi?rawFullHandle:wrapEmbindHandle(rawFullHandle);try{{const data=await readFileData(source);if(!fullFileHandle.loadFromBuffer(data))throw new InvalidFormatError(`Failed to load full audio file for saving`)}copyEditedState(fullFileHandle,editing,sourceComplete,deletedKeys);if(!fullFileHandle.save())throw new FileOperationError(`save`,`Failed to save changes to full file`);await writeFileData(targetPath,fullFileHandle.getBuffer())}finally{fullFileHandle.destroy()}}var init_save_reconstruct=__esmMin((()=>{init_errors();init_file();init_write();init_embind_adapter();init_extra_state_registry();init_properties();init_mp4_item_names()}));function sortChapters(list){return[...list].sort((a,b)=>a.startTimeMs-b.startTimeMs)}function inferEndTimeMs(sorted,index,trackEndMs){const own=sorted[index].endTimeMs;if(own!==void 0)return own;const next=sorted[index+1];return next?next.startTimeMs:trackEndMs}function readFileSync(path){if(isDeno())return Deno.readFileSync(path);const fs=getNodeFsSync();if(fs)return new Uint8Array(fs.readFileSync(path));throw new FileOperationError(`read`,`node:fs is unavailable in this runtime: cannot read file data from disk`,path)}var AudioFileImpl;var init_audio_file_impl=__esmMin((()=>{init_types();init_audio_file_bwf();init_id3v2_frames();init_errors();init_write();init__taglib_node_fs_stub();init_rating();init_detector();init_audio_file_base();init_audio_file_checksum();init__taglib_platform_io_stub();init_save_reconstruct();init_defineProperty();AudioFileImpl=class extends BaseAudioFileImpl{constructor(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded=false,partialLoadOptions){super(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded,partialLoadOptions);_defineProperty(this,`pathModeBuffer`,null);_defineProperty(this,`partiallyLoadedAtConstruction`,void 0);this.partiallyLoadedAtConstruction=isPartiallyLoaded}save(){if(this.isPartiallyLoaded&&this.originalSource)throw new FileOperationError(`save`,`Cannot save partially loaded file directly. Use saveToFile() instead`);this.cachedAudioProperties=null;this.pathModeBuffer=null;return this.handle.save()}getFileBuffer(){const buffer=this.handle.getBuffer();if(buffer.length>0)return buffer;if(this.pathModeBuffer)return this.pathModeBuffer;if(this.sourcePath)try{this.pathModeBuffer=readFileSync(this.sourcePath);return this.pathModeBuffer}catch(error){if(error instanceof FileOperationError)throw error;throw new FileOperationError(`read`,`Cannot return file data: ${errorMessage(error)}`,this.sourcePath,{cause:error})}throw new FileOperationError(`read`,`No file data available: in-memory buffer is empty and no source path is set`)}mediaChecksum(options){return mediaChecksum({bytes:this.handle.getBuffer(),...this.sourcePath!==void 0?{path:this.sourcePath}:{},...this.originalSource instanceof Blob?{blob:this.originalSource}:{},partiallyLoaded:this.partiallyLoadedAtConstruction},this.getFormat(),getPlatformIO(),options)}async saveToFile(path){const targetPath=path??this.sourcePath;if(!targetPath)throw new FileOperationError(`save`,`No file path available. Provide a path or open the file from a path`);if(this.isPartiallyLoaded&&this.originalSource){await saveViaFreshHandle(this.module,this.handle,this.originalSource,targetPath,false,this.partialDeletedPropertyKeys());this.isPartiallyLoaded=false;this.originalSource=void 0}else if(this.module.isWasi&&this.sourcePath&&targetPath!==this.sourcePath)await saveViaFreshHandle(this.module,this.handle,this.sourcePath,targetPath,true);else{if(!this.save())throw new FileOperationError(`save`,`Failed to save changes to in-memory buffer`);const buffer=this.handle.getBuffer();if(buffer.length>0)await writeFileData(targetPath,buffer)}this.pathModeBuffer=null}getPictures(){return this.handle.getPictures().map(pic=>({mimeType:pic.mimeType,data:pic.data,type:PICTURE_TYPE_NAMES[pic.type]??`Other`,...pic.description!==void 0?{description:pic.description}:{}}))}setPictures(pictures){this.handle.setPictures(pictures.map(pic=>({mimeType:pic.mimeType,data:pic.data,type:PICTURE_TYPE_VALUES[pic.type]??0,description:pic.description??``})))}addPicture(picture){this.handle.addPicture({mimeType:picture.mimeType,data:picture.data,type:PICTURE_TYPE_VALUES[picture.type]??0,description:picture.description??``})}removePictures(){this.handle.removePictures()}getChapters(){const sorted=sortChapters(this.handle.getChapters());const trackEndMs=this.audioProperties()?.durationMs;return sorted.map((c,i)=>{const endTimeMs=inferEndTimeMs(sorted,i,trackEndMs);return{startTimeMs:c.startTimeMs,...endTimeMs!==void 0?{endTimeMs}:{},...c.title?{title:c.title}:{},...c.id?{id:c.id}:{},...c.source!==void 0?{source:c.source}:{}}})}setChapters(chapters,options){const fmt=this.getFormat();if(fmt!==`MP3`&&fmt!==`AAC`&&fmt!==`MP4`)throw new UnsupportedFormatError(fmt,[`MP3`,`AAC`,`MP4`],{operation:`setChapters`});const sorted=sortChapters(chapters);const trackEndMs=this.audioProperties()?.durationMs;const style=options?.mp4ChapterStyle??`quicktime`;const source=fmt===`MP4`?style:`id3`;const raw=sorted.map((c,i)=>({...c.id!==void 0?{id:c.id}:{},startTimeMs:c.startTimeMs,endTimeMs:inferEndTimeMs(sorted,i,trackEndMs)??c.startTimeMs,...c.title!==void 0?{title:c.title}:{},source}));this.handle.setChapters(raw,style)}getBext(){return getBext(this.handle)}setBext(bext){setBext(this.handle,this.getFormat(),bext)}getBextData(){return getBextData(this.handle)}setBextData(data){setBextData(this.handle,this.getFormat(),data)}getIxml(){return getIxml(this.handle)}setIxml(data){setIxml(this.handle,this.getFormat(),data)}getRatings(){return this.handle.getRatings().map(r=>({rating:r.rating,...r.email!==void 0&&r.email!==``?{email:r.email}:{},...r.counter!==0?{counter:r.counter}:{}}))}setRatings(ratings){this.handle.setRatings(ratings.map(r=>({rating:r.rating,email:r.email??``,counter:r.counter??0})))}getLyrics(){return this.handle.getLyrics().map(l=>{const out={text:l.text};if(l.description)out.description=l.description;if(l.language)out.language=l.language;return out})}setLyrics(lyrics){this.handle.setLyrics(lyrics.map(l=>({text:l.text,description:l.description??``,language:l.language??``})))}getRating(){const ratings=this.getRatings();return ratings.length>0?normalized(ratings[0].rating):void 0}setRating(rating,email){this.setRatings([{rating,...email!==void 0?{email}:{},counter:0}])}getId3v2Frames(id){assertMp3(this.getFormat());if(id!==void 0)assertFrameId(id,`read`);return this.handle.getId3v2Frames(id??``).map(toPublicFrame)}setId3v2Frames(id,data){assertMp3(this.getFormat());assertFrameId(id,`write`);assertFrameBodies(id,data);this.handle.setId3v2Frames(id,data)}removeId3v2Frames(id){assertMp3(this.getFormat());assertFrameId(id,`write`);this.handle.removeId3v2Frames(id)}hasId3Tags(){return this.handle.hasId3Tags()}stripId3Tags(opts){this.handle.stripId3Tags({v1:opts?.v1??true,v2:opts?.v2??true})}}}));async function loadFull(input){return{data:await readFileData(input),isPartiallyLoaded:false}}async function loadPartialFile(input,opts){const headerSize=Math.min(opts.maxHeaderSize,input.size);const footerSize=Math.min(opts.maxFooterSize,input.size);if(input.size<=headerSize+footerSize)return loadFull(input);const header=new Uint8Array(await input.slice(0,headerSize).arrayBuffer());if(!metadataFitsInHeader(header,headerSize))return loadFull(input);const footerStart=Math.max(0,input.size-footerSize);const footer=new Uint8Array(await input.slice(footerStart).arrayBuffer());if(!trailerFitsInFooter(footer,footerSize))return loadFull(input);const combined=new Uint8Array(header.byteLength+footer.byteLength);combined.set(header,0);combined.set(footer,header.byteLength);return{data:combined,isPartiallyLoaded:true}}async function loadPartialPath(input,opts){if(await getFileSize(input)>opts.maxHeaderSize+opts.maxFooterSize){const data=await readPartialFileData(input,opts.maxHeaderSize,opts.maxFooterSize);if(metadataFitsInHeader(data,opts.maxHeaderSize)&&trailerFitsInFooter(data,opts.maxFooterSize))return{data,isPartiallyLoaded:true}}return loadFull(input)}async function loadAudioData(input,opts){if(!opts.partial)return loadFull(input);if(typeof File!==`undefined`&&input instanceof File)return loadPartialFile(input,opts);if(typeof input===`string`)return loadPartialPath(input,opts);return loadFull(input)}var init_load_audio_data=__esmMin((()=>{init_file();init_metadata_extent()}));function parseLeadingInt(raw){const parsed=Number.parseInt(raw,10);return Number.isNaN(parsed)?void 0:parsed}var MIRROR_FIELDS,DATE_MIRROR,TRACK_MIRROR;var init_mirror_fields=__esmMin((()=>{MIRROR_FIELDS=[{raw:`date`,numeric:`year`},{raw:`trackNumber`,numeric:`track`}];DATE_MIRROR=MIRROR_FIELDS[0];TRACK_MIRROR=MIRROR_FIELDS[1]}));function attachStructuredFields(audioFile,tag){const pictures=audioFile.getPictures();if(pictures.length>0)tag.pictures=pictures;const ratings=audioFile.getRatings();if(ratings.length>0)tag.ratings=ratings;const lyrics=audioFile.getLyrics();if(lyrics.length>0)tag.lyrics=lyrics;const chapters=audioFile.getChapters();if(chapters.length>0)tag.chapters=chapters;const bext=audioFile.getBext();if(bext!==void 0)tag.bext=bext;const bextData=audioFile.getBextData();if(bextData!==void 0)tag.bextData=bextData;const ixml=audioFile.getIxml();if(ixml!==void 0)tag.ixml=ixml}function attachExtraProperties(props,tag,includeProperties){if(includeProperties===void 0||includeProperties.length===0)return;const extraProperties={};for(const wireKey of includeProperties){const values=props[fromTagLibKey(wireKey)]?.filter(v=>v!==``);if(values!==void 0&&values.length>0)extraProperties[wireKey]=values}if(Object.keys(extraProperties).length>0)tag.extraProperties=extraProperties}function readExtendedTag(audioFile,includeProperties){const props=audioFile.properties();const tag=mapPropertiesToExtendedTag(props);attachStructuredFields(audioFile,tag);attachExtraProperties(props,tag,includeProperties);return tag}function mapPropertiesToExtendedTag(props){const tag={};for(const[propKey,tagField]of Object.entries(BASIC_PROPERTY_KEYS)){const values=props[propKey];if(!values||values.length===0)continue;if(tagField===`year`||tagField===`track`){const num=parseLeadingInt(values[0]);if(num!==void 0)tag[tagField]=num;if(propKey===`date`)tag.date=values.length===1?values[0]:values;if(propKey===`trackNumber`)tag.trackNumber=values.length===1?values[0]:values}else tag[tagField]=values}for(const[propKey,totalField]of[[`trackNumber`,`totalTracks`],[`discNumber`,`totalDiscs`]]){if(tag[totalField]!==void 0)continue;const raw=props[propKey]?.[0];const slash=raw?.indexOf(`/`)??-1;if(raw===void 0||slash===-1)continue;const total=parseLeadingInt(raw.slice(slash+1));if(total!==void 0)tag[totalField]=total}if(tag.date===void 0){const yearValues=props[`YEAR`];if(yearValues!==void 0&&yearValues.length>0){const y=parseLeadingInt(yearValues[0]);if(y!==void 0)tag.year=y;tag.date=yearValues.length===1?yearValues[0]:yearValues}}for(const[key,values]of Object.entries(props)){if(BASIC_PROPERTY_KEYS[key])continue;if(key===`YEAR`)continue;if(!values||values.length===0)continue;const camelKey=fromTagLibKey(key);if(NUMERIC_FIELDS.has(camelKey)){const num=parseLeadingInt(values[0]);if(num!==void 0)tag[camelKey]=num}else if(camelKey===`compilation`)tag[camelKey]=values[0]===`1`||values[0]===`true`;else if(camelKey===`itunesAdvisory`){tag[camelKey]=values;if(values[0]===`1`)tag.advisory=`explicit`;else if(values[0]===`2`)tag.advisory=`clean`;else if(values[0]===`0`)tag.advisory=`unspecified`}else if(camelKey===`r128TrackGain`||camelKey===`r128AlbumGain`){const raw=parseLeadingInt(values[0]);if(raw!==void 0)tag[camelKey]=raw/256}else tag[camelKey]=values}return tag}function mergeTagUpdatesInto(currentProps,tags){const newProps=normalizeTagInput(tags);reconcilePairFields(currentProps,newProps,tags);if(newProps.date!==void 0||newProps.year!==void 0)currentProps.YEAR=[];return{...currentProps,...newProps}}function mergeTagUpdates(file,tags){file.setProperties(mergeTagUpdatesInto(file.properties(),tags))}function reconcilePairFields(currentProps,newProps,input){for(const[rawKey,totalKey,numericKey]of[[`trackNumber`,`totalTracks`,`track`],[`discNumber`,`totalDiscs`,`discNumber`]]){const incoming=newProps[rawKey]?.[0];if(incoming?.includes(`/`)){newProps[totalKey]=[];continue}if(!(input[numericKey]!==void 0&&input[rawKey]===void 0)||incoming===void 0)continue;const existing=currentProps[rawKey]?.[0];const slash=existing?.indexOf(`/`)??-1;if(existing!==void 0&&slash!==-1)newProps[rawKey]=[`${incoming}${existing.slice(slash)}`]}}function normalizeTagInput(input){const props={};for(const field of[`title`,`artist`,`album`,`comment`,`genre`]){const val=input[field];if(val===void 0)continue;props[field]=Array.isArray(val)?val:[val]}if(input.year!==void 0)props.date=[String(input.year)];if(input.date!==void 0)props.date=Array.isArray(input.date)?input.date:[input.date];if(input.track!==void 0)props.trackNumber=[String(input.track)];if(input.trackNumber!==void 0)props.trackNumber=Array.isArray(input.trackNumber)?input.trackNumber:[input.trackNumber];for(const[field,val]of Object.entries(input)){if(BASIC_FIELDS.has(field)||val===void 0)continue;if(field===`extraProperties`)continue;if(field===`compilation`)props[field]=[val?`1`:`0`];else if(field===`advisory`){if(val===`explicit`)props.itunesAdvisory=[`1`];else if(val===`clean`)props.itunesAdvisory=[`2`];else if(val===`unspecified`)props.itunesAdvisory=[]}else if(field===`bpm`)props[field]=[String(Math.trunc(val))];else if(NUMERIC_FIELDS.has(field))props[field]=[String(val)];else if(field===`r128TrackGain`||field===`r128AlbumGain`)props[field]=Array.isArray(val)?val:[String(Math.round(val*256))];else if(typeof val===`string`)props[field]=[val];else if(Array.isArray(val))props[field]=val}for(const[rawField,totalField]of[[`trackNumber`,`totalTracks`],[`discNumber`,`totalDiscs`]])if(props[rawField]?.[0]?.includes(`/`))delete props[totalField];return props}var BASIC_PROPERTY_KEYS,BASIC_FIELDS,NUMERIC_FIELDS;var init_tag_mapping=__esmMin((()=>{init_properties();init_mirror_fields();BASIC_PROPERTY_KEYS={title:`title`,artist:`artist`,album:`album`,comment:`comment`,genre:`genre`,date:`year`,trackNumber:`track`};BASIC_FIELDS=/* @__PURE__ */ new Set([`title`,`artist`,`album`,`comment`,`genre`,`year`,`date`,`track`,`trackNumber`]);NUMERIC_FIELDS=/* @__PURE__ */ new Set([`year`,`track`,`discNumber`,`totalTracks`,`totalDiscs`,`bpm`])}));var VERSION;var init_version=__esmMin((()=>{VERSION=`2.5.0`}));var module_loader_browser_exports=/* @__PURE__ */ __exportAll({loadTagLibModule:()=>loadTagLibModule});async function loadTagLibModule(options){let createTagLibModule;try{createTagLibModule=(await import(`./taglib-wrapper.js`)).default}catch{try{createTagLibModule=(await import(`./taglib-wrapper.js`)).default}catch{throw new TagLibInitializationError(`Could not load taglib-wrapper.js. Ensure it is co-located with the browser bundle.`)}}const moduleConfig={};if(options?.wasmBinary)moduleConfig.wasmBinary=options.wasmBinary;if(options?.wasmUrl)moduleConfig.locateFile=path=>{if(path.endsWith(`.wasm`))return options.wasmUrl;return path};else if(!options?.wasmBinary){const wasmUrl=new URL(`./taglib-web.wasm`,import.meta.url);moduleConfig.locateFile=path=>path.endsWith(`.wasm`)?wasmUrl.href:path}return await createTagLibModule(moduleConfig)}var init_module_loader_browser=__esmMin((()=>{init_classes()}));function trimTrailingSeparators(p){let end=p.length;while(end>0){const c=p.charAt(end-1);if(c!==`/`&&c!==`\\`)break;end--}return p.slice(0,end)}function toWasiPath(osPath){if(osPath.startsWith(`\\\\`)||osPath.startsWith(`//`))throw new FileOperationError(`read`,`UNC paths are not supported. Path: ${osPath}`);let p=osPath;if(!p.startsWith(`/`)&&!/^[A-Za-z]:/.test(p)){const g=globalThis;const cwd=isDeno()?Deno.cwd():g.process?.cwd?.();if(cwd)p=trimTrailingSeparators(cwd)+`/`+p}p=p.replaceAll(`\\`,`/`);const driveMatch=/^([A-Za-z]):\//.exec(p);if(driveMatch)p=`/${driveMatch[1].toUpperCase()}${p.slice(2)}`;p=p.replaceAll(`/./`,`/`).replace(/\/+/g,`/`);if(!p.startsWith(`/`))p=`/`+p;return p}function createTagLib(module){return Promise.resolve(new TagLib(module))}var TagLib;var init_taglib_class=__esmMin((()=>{init_audio_formats();init_errors();init_detector();init_audio_file_impl();init_load_audio_data();init_tag_mapping();init_version();init_embind_adapter();init_defineProperty();TagLib=class TagLib{constructor(module){_defineProperty(this,`module`,void 0);this.module=module}static async initialize(options){const{loadTagLibModule}=await Promise.resolve().then(()=>(init_module_loader_browser(),module_loader_browser_exports));const module=await loadTagLibModule(options);return new TagLib(module)}async open(input,options){if(!this.module.createFileHandle)throw new TagLibInitializationError(`TagLib module not properly initialized: createFileHandle not found. Make sure the module is fully loaded before calling open.`);const actualInput=isNamedAudioInput(input)?input.data:input;const sourcePath=typeof actualInput===`string`?actualInput:void 0;if(typeof actualInput===`string`&&this.module.isWasi){const wasiPath=toWasiPath(actualInput);if(this.module.loadAudioPath){const fileHandle=await this.module.loadAudioPath(wasiPath,actualInput);return new AudioFileImpl(this.module,fileHandle,sourcePath,actualInput,false)}}const opts={partial:true,maxHeaderSize:1048576,maxFooterSize:131072,...options};const{data:audioData,isPartiallyLoaded}=await loadAudioData(actualInput,opts);const uint8Array=actualInput instanceof Uint8Array&&audioData.buffer===actualInput.buffer?new Uint8Array(audioData.buffer.slice(audioData.byteOffset,audioData.byteOffset+audioData.byteLength)):audioData;const rawHandle=this.module.createFileHandle();const fileHandle=this.module.isWasi?rawHandle:wrapEmbindHandle(rawHandle);try{if(!fileHandle.loadFromBuffer(uint8Array))throw new InvalidFormatError(`Failed to load audio file. File may be corrupted or in an unsupported format`,uint8Array.byteLength);return new AudioFileImpl(this.module,fileHandle,sourcePath,actualInput,isPartiallyLoaded,opts)}catch(error){if(typeof fileHandle.destroy===`function`)fileHandle.destroy();throw error}}async edit(input,fn){const file=await this.open(input);try{await fn(file);if(typeof input===`string`)await file.saveToFile();else{file.save();return file.getFileBuffer()}}finally{file.dispose()}}async updateFile(path,tags){const file=await this.open(path);try{mergeTagUpdates(file,tags);await file.saveToFile()}finally{file.dispose()}}async copyWithTags(sourcePath,destPath,tags){const file=await this.open(sourcePath);try{mergeTagUpdates(file,tags);await file.saveToFile(destPath)}finally{file.dispose()}}version(){return`${VERSION} (TagLib ${this.taglibVersion()})`}taglibVersion(){if(this.module.getVersion)return this.module.getVersion();if(this.module.version)return this.module.version();return`unknown`}}}));var init_taglib$1=__esmMin((()=>{init_audio_file_impl();init_taglib_class();init_errors()}));var taglib_exports=/* @__PURE__ */ __exportAll({AudioFileImpl:()=>AudioFileImpl,EnvironmentError:()=>EnvironmentError,FileOperationError:()=>FileOperationError,InvalidFormatError:()=>InvalidFormatError,MemoryError:()=>MemoryError,MetadataError:()=>MetadataError,SUPPORTED_FORMATS:()=>SUPPORTED_FORMATS,TagLib:()=>TagLib,TagLibError:()=>TagLibError,TagLibInitializationError:()=>TagLibInitializationError,UnsupportedFormatError:()=>UnsupportedFormatError,createTagLib:()=>createTagLib,isEnvironmentError:()=>isEnvironmentError,isFileOperationError:()=>isFileOperationError,isInvalidFormatError:()=>isInvalidFormatError,isMemoryError:()=>isMemoryError,isMetadataError:()=>isMetadataError,isTagLibError:()=>isTagLibError,isUnsupportedFormatError:()=>isUnsupportedFormatError});var init_taglib=__esmMin((()=>{init_taglib$1()}));init_taglib();function isDenoCompiled(){if(typeof Deno===`undefined`)return false;const build=Deno.build;if(typeof build?.standalone===`boolean`)return build.standalone;return typeof Deno.mainModule===`string`&&(Deno.mainModule.includes(`deno-compile://`)||Deno.mainModule.includes(`/deno-compile-`))}let cachedTagLib=null;let bufferModeEnabled=false;function setBufferMode(enabled){bufferModeEnabled=enabled;cachedTagLib=null}async function getTagLib(){if(!cachedTagLib){const{TagLib}=await Promise.resolve().then(()=>(init_taglib(),taglib_exports));const initOptions=bufferModeEnabled?{forceWasmType:`emscripten`}:void 0;cachedTagLib=await TagLib.initialize(initOptions)}return cachedTagLib}init_errors();init_file();async function withAudioFile(file,fn,options){const audioFile=await(await getTagLib()).open(file,options);try{if(!audioFile.isValid())throw new InvalidFormatError(`File may be corrupted or in an unsupported format`);return await fn(audioFile)}finally{audioFile.dispose()}}async function withAudioFileSave(file,fn){return withAudioFile(typeof file===`string`?await readFileData(file):file,audioFile=>{fn(audioFile);if(!audioFile.save())throw new FileOperationError(`save`,`Failed to save metadata changes. The file may be read-only or corrupted.`);return audioFile.getFileBuffer()},{partial:false})}async function withAudioFileSaveToFile(file,fn){return withAudioFile(file,async audioFile=>{fn(audioFile);await audioFile.saveToFile(file)})}init_errors();init_tag_mapping();async function readTags(file,options={}){return withAudioFile(file,audioFile=>readExtendedTag(audioFile,options.includeProperties))}async function applyTags(file,tags){return withAudioFileSave(file,audioFile=>{mergeTagUpdates(audioFile,tags)})}async function applyTagsToFile(file,tags){if(typeof file!==`string`)throw new FileOperationError(`save`,`applyTagsToFile requires a file path string to save changes`);await withAudioFileSaveToFile(file,audioFile=>{mergeTagUpdates(audioFile,tags)})}async function readProperties(file){return withAudioFile(file,audioFile=>{const props=audioFile.audioProperties();if(!props)throw new MetadataError(`read`,`File may not contain valid audio data`,`audioProperties`);return props})}async function isValidAudioFile(file){try{const audioFile=await(await getTagLib()).open(file);try{return audioFile.isValid()}finally{audioFile.dispose()}}catch{return false}}async function readFormat(file){const audioFile=await(await getTagLib()).open(file);try{if(!audioFile.isValid())return;return audioFile.getFormat()}finally{audioFile.dispose()}}async function clearTags(file){return withAudioFileSave(file,audioFile=>{const cleared={};for(const key of Object.keys(audioFile.properties()))cleared[key]=[];audioFile.setProperties(cleared);audioFile.removePictures();audioFile.setLyrics([]);audioFile.setRatings([]);if(audioFile.getChapters().length>0)audioFile.setChapters([]);if(audioFile.getBextData()!==void 0)audioFile.setBextData(null);if(audioFile.getIxml()!==void 0)audioFile.setIxml(null)})}async function readPictures(file){return withAudioFile(file,audioFile=>audioFile.getPictures())}async function applyPictures(file,pictures){return withAudioFileSave(file,audioFile=>{audioFile.setPictures(pictures)})}async function addPicture(file,picture){return withAudioFileSave(file,audioFile=>{audioFile.addPicture(picture)})}async function clearPictures(file){return applyPictures(file,[])}async function readCoverArt(file){const pictures=await readPictures(file);if(pictures.length===0)return;const frontCover=pictures.find(pic=>pic.type===`FrontCover`);if(frontCover)return frontCover.data;return pictures[0].data}async function applyCoverArt(file,imageData,mimeType){return applyPictures(file,[{mimeType,data:imageData,type:`FrontCover`,description:`Front Cover`}])}function findPictureByType(pictures,type){return pictures.find(pic=>pic.type===type)}async function replacePictureByType(file,newPicture){const filteredPictures=(await readPictures(file)).filter(pic=>pic.type!==newPicture.type);filteredPictures.push(newPicture);return applyPictures(file,filteredPictures)}async function readPictureMetadata(file){return(await readPictures(file)).map(pic=>({type:pic.type,mimeType:pic.mimeType,...pic.description!==void 0?{description:pic.description}:{},size:pic.data.length}))}init_audio_formats();init_errors();init_tag_mapping();async function executeBatch(files,options,processor){if(files.length===0)return{items:[],duration:0};const startTime=Date.now();const{concurrency=4,continueOnError=true,onProgress,signal}=options;const items=new Array(files.length);const taglib=await getTagLib();let processed=0;const total=files.length;for(let i=0;i<files.length;i+=concurrency){signal?.throwIfAborted();const chunkPromises=files.slice(i,i+concurrency).map(async(file,idx)=>{const index=i+idx;let fileName;if(typeof file===`string`)fileName=file;else if(file instanceof File)fileName=file.name;else if(isNamedAudioInput(file))fileName=file.name;else fileName=`buffer-${index}`;try{const audioFile=await taglib.open(file);try{if(!audioFile.isValid())throw new InvalidFormatError(`File may be corrupted or in an unsupported format`);items[index]={status:`ok`,path:fileName,data:processor(audioFile)}}finally{audioFile.dispose()}}catch(error){const err=error instanceof Error?error:new Error(String(error));items[index]={status:`error`,path:fileName,error:err};if(!continueOnError)throw err}processed++;onProgress?.(processed,total,fileName)});await Promise.all(chunkPromises)}return{items,duration:Date.now()-startTime}}async function readTagsBatch(files,options={}){return executeBatch(files,options,audioFile=>readExtendedTag(audioFile,options.includeProperties))}async function readPropertiesBatch(files,options={}){return executeBatch(files,options,audioFile=>audioFile.audioProperties())}function extractDynamics(audioFile){const dynamics={};for(const field of[`replayGainTrackGain`,`replayGainTrackPeak`,`replayGainAlbumGain`,`replayGainAlbumPeak`]){const val=audioFile.getProperty(field)?.[0];if(val!==void 0)dynamics[field]=val}let appleSoundCheck=audioFile.getProperty(`appleSoundCheck`)?.[0];if(!appleSoundCheck&&audioFile.isMP4())appleSoundCheck=audioFile.getMP4Item(`----:com.apple.iTunes:iTunNORM`);if(appleSoundCheck)dynamics.appleSoundCheck=appleSoundCheck;return Object.keys(dynamics).length>0?dynamics:void 0}async function readMetadata(file,options={}){const audioFile=await(await getTagLib()).open(file);try{if(!audioFile.isValid()){let name;if(typeof file===`string`)name=file;else if(file instanceof File)name=file.name;else if(isNamedAudioInput(file))name=file.name;else name=`buffer (${file.byteLength} bytes)`;throw new InvalidFormatError(`File may be corrupted or in an unsupported format. File: ${name}`)}const dynamics=extractDynamics(audioFile);return{tags:readExtendedTag(audioFile,options.includeProperties),properties:audioFile.audioProperties(),hasCoverArt:audioFile.getPictures().length>0,...dynamics!==void 0?{dynamics}:{}}}finally{audioFile.dispose()}}async function readMetadataBatch(files,options={}){return executeBatch(files,options,audioFile=>{const dynamics=extractDynamics(audioFile);return{tags:readExtendedTag(audioFile,options.includeProperties),properties:audioFile.audioProperties(),hasCoverArt:audioFile.getPictures().length>0,...dynamics!==void 0?{dynamics}:{}}})}async function readMediaChecksum(file,options){return withAudioFile(file,audioFile=>audioFile.mediaChecksum(options))}const FormatMappings={Title:{id3v2:`TIT2`,mp4:`©nam`,vorbis:`TITLE`,ape:`Title`,riff:`INAM`},Artist:{id3v2:`TPE1`,mp4:`©ART`,vorbis:`ARTIST`,ape:`Artist`,riff:`IART`},Album:{id3v2:`TALB`,mp4:`©alb`,vorbis:`ALBUM`,ape:`Album`,riff:`IPRD`},Date:{id3v2:`TDRC`,mp4:`©day`,vorbis:`DATE`,ape:`Year`,riff:`ICRD`},Genre:{id3v2:`TCON`,mp4:`©gen`,vorbis:`GENRE`,ape:`Genre`,riff:`IGNR`},Comment:{id3v2:`COMM`,mp4:`©cmt`,vorbis:`COMMENT`,ape:`Comment`,riff:`ICMT`},TrackNumber:{id3v2:`TRCK`,mp4:`trkn`,vorbis:`TRACKNUMBER`,ape:`Track`,riff:`ITRK`}};init_properties();function isValidProperty(key){return key in PROPERTIES}function getPropertyMetadata(key){return PROPERTIES[key]}function getAllPropertyKeys(){return Object.keys(PROPERTIES)}function getAllProperties(){return Object.entries(PROPERTIES)}function getPropertiesByFormat(format){return getAllPropertyKeys().filter(key=>PROPERTIES[key].supportedFormats.includes(format))}function propertyValues(props,key){return props[key]??[]}function propertyValue(props,key){return props[key]?.[0]}function dirname(path){const i=Math.max(path.lastIndexOf(`/`),path.lastIndexOf(`\\`));return i===-1?path:path.slice(0,i)}const UNCONDITIONAL_MARKERS=[`cd`,`disc`,`disk`,`dvd`,`sacd`,`blu-ray`,`bd`,`digital media`];const GATED_MARKERS=[`tape`,`vinyl`,`cassette`,`lp`,`record`];const MARKERS=[...UNCONDITIONAL_MARKERS,...GATED_MARKERS];const GATED_MARKER_SET=new Set(GATED_MARKERS);const WORD_NUMBERS={one:1,two:2,three:3,four:4,five:5,six:6,seven:7,eight:8,nine:9,ten:10,eleven:11,twelve:12};function romanToInt(s){const values={i:1,v:5,x:10,l:50,c:100,d:500,m:1e3};let total=0;let prev=0;for(let i=s.length-1;i>=0;i--){const v=values[s[i]];if(v===void 0)return NaN;total+=v<prev?-v:v;prev=v}return total}function parseNumberToken(token){if(/^\d+$/.test(token))return Number.parseInt(token,10);const word=WORD_NUMBERS[token.toLowerCase()];if(word)return word;const roman=romanToInt(token.toLowerCase());return Number.isFinite(roman)?roman:void 0}const SEP=String.raw`[\s._#-]*`;const NUM=String.raw`(?:\d+|(?:[ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|[a-z])(?![a-z]))`;function trimTrailingChars(s,chars){let end=s.length;while(end>0){const c=s.charAt(end-1);if(!chars.includes(c)&&!/\s/.test(c))break;end--}return s.slice(0,end)}function parseDiscName(name){const trimmed=name.trim();if(/^(?:extras?|bonus)$/i.test(trimmed))return void 0;for(const marker of MARKERS){const esc=marker.replace(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`);const m=new RegExp(`(?:^|[^a-z0-9])(${esc})(?![a-z])${SEP}(${NUM})`,`i`).exec(trimmed);if(!m)continue;const sideLetter=/^[a-z]$/i.test(m[2]);const number=sideLetter?void 0:parseNumberToken(m[2]);if(number===void 0&&!sideLetter)continue;if(!sideLetter&&/^[ivxlcdm]{2,}$/i.test(m[2])&&(number??0)>100)continue;const isGated=GATED_MARKER_SET.has(marker.toLowerCase())||sideLetter;const markerStart=m.index+m[1].length-marker.length;const title=trimTrailingChars(trimmed.slice(0,markerStart).trim().replace(/[()[\]]/g,``),`._#-`)||void 0;const isExact=title===void 0;const after=trimmed.slice(m.index+m[0].length).trim();const discTitle=trimTrailingChars(after.replace(/^[()[\],:;\-–—\s]+/,``),`])[,:;-–—`).trim()||void 0;const ofMatch=/^of\s+(\d+)\b/i.exec(after.trim());const total=ofMatch?Number.parseInt(ofMatch[1],10):void 0;return{kind:isExact?`exact`:`embedded`,number:sideLetter?void 0:number,total,title,discTitle,gated:isGated,sideLetter,digit:/^\d+$/.test(m[2])}}const volume=/^(?:volume|vol\.?|part|pt\.?)\s*(\d+)(?:\s*of\s*(\d+))?$/i.exec(trimmed);if(volume)return{kind:`volume`,number:Number.parseInt(volume[1],10),total:volume[2]?Number.parseInt(volume[2],10):void 0,title:void 0,discTitle:void 0,gated:false,sideLetter:false,digit:true};if(/^bonus\s+disc$/i.test(trimmed))return{kind:`bonus`,number:void 0,total:void 0,title:void 0,discTitle:void 0,gated:true,sideLetter:false,digit:false};if(/^(?:\d+|v\d+|p\d+|[ab])$/i.test(trimmed))return{kind:`bare`,number:/^\d+$/i.test(trimmed)?Number.parseInt(trimmed,10):void 0,total:void 0,title:void 0,discTitle:void 0,gated:true,sideLetter:false,digit:false}}function baseConfidence(parse){switch(parse.kind){case`exact`:return parse.digit?`high`:`low`;case`embedded`:return`medium`;case`volume`:return`medium`;case`bonus`:case`bare`:return`low`}}function discFolderInfo(name){const parse=parseDiscName(name);if(!parse)return void 0;return{kind:parse.kind,gated:parse.gated,number:parse.number,total:parse.total,title:parse.title,discTitle:parse.discTitle,confidence:parse.gated?`low`:baseConfidence(parse)}}function basename(path){const i=Math.max(path.lastIndexOf(`/`),path.lastIndexOf(`\\`));return i===-1?path:path.slice(i+1)}const CONFIDENCE_RANK={low:0,medium:1,high:2};function summarizeSiblings(siblings){const facts={hasExact:false,hasNumbered:false,numberedCount:0,hasSideLetter:false};for(const sibling of siblings){const parsed=parseDiscName(basename(sibling));if(!parsed)continue;if(!parsed.gated&&parsed.kind===`exact`)facts.hasExact=true;if(parsed.number!==void 0){facts.hasNumbered=true;facts.numberedCount++}if(parsed.sideLetter)facts.hasSideLetter=true}return facts}function corroborated(parse,siblings){if(!parse.gated&&parse.kind===`exact`)return true;if(siblings.length===0)return false;const facts=summarizeSiblings(siblings);if(parse.number!==void 0&&facts.hasNumbered)return true;if(!parse.gated&&parse.kind===`embedded`&&facts.hasExact)return true;if(!parse.gated&&parse.kind===`volume`&&facts.hasNumbered)return true;if(parse.sideLetter)return facts.hasSideLetter;if(parse.kind===`bonus`||parse.kind===`bare`)return facts.numberedCount>=2;return false}function normalizeKey(s){return s.trim().toLowerCase().replace(/\s+/g,` `)}function isGenericAlbumArtist(albumArtist){if(!albumArtist||albumArtist.trim()===``)return true;const n=normalizeKey(albumArtist);return n===`various artists`||n===`va`}function evidenceFor(item,confirmedDiscs,flatSubdivisions){const dir=dirname(item.path);const own=confirmedDiscs.get(dir);if(own)return{folderDiscNumber:own.parse.number,total:own.parse.total,folderDiscTitle:own.parse.discTitle,confidence:own.confidence,albumDir:dirname(dir)};let cursor=dirname(dir);while(cursor!==void 0){const entry=confirmedDiscs.get(cursor);if(entry)return{folderDiscNumber:entry.parse.number,total:entry.parse.total,folderDiscTitle:entry.parse.discTitle,confidence:entry.confidence,albumDir:dirname(cursor)};const parent=dirname(cursor);if(parent===cursor)break;cursor=parent}const flat=flatSubdivisions.get(dir)?.get(item.path);if(flat!==void 0)return{folderDiscNumber:flat,total:void 0,folderDiscTitle:void 0,confidence:`medium`,albumDir:dir}}function folderIdentity(dir,confirmedDiscs,scanRoot){const own=confirmedDiscs.get(dir);if(!own){const title=basename(dir);return title?{title,titleSource:dir}:void 0}if(own.parse.title!==void 0)return{title:own.parse.title,titleSource:dirname(dir)};const source=dirname(dir);if(source===scanRoot||source===dir)return void 0;const title=basename(source);return title?{title,titleSource:source}:void 0}function buildAlbumIdentity(okItems,confirmedDiscs,flatSubdivisions,options){const albums=/* @__PURE__ */ new Map;const unmatched=[];for(const item of okItems){const dir=dirname(item.path);const albumTag=item.tags.album?.[0]?.trim();const albumArtistTag=item.tags.albumArtist?.[0]?.trim();if(albumTag){const key=`${isGenericAlbumArtist(albumArtistTag)?``:normalizeKey(albumArtistTag??``)}::${normalizeKey(albumTag)}`;let acc=albums.get(key);if(!acc){acc={key,album:albumTag,albumArtist:isGenericAlbumArtist(albumArtistTag)?void 0:albumArtistTag,source:`tags`,directory:void 0,items:[],evidence:/* @__PURE__ */ new Map};albums.set(key,acc)}const evidence=evidenceFor(item,confirmedDiscs,flatSubdivisions);acc.evidence.set(item.path,evidence);acc.items.push({...item.metadata,albumDir:evidence?.albumDir??dir,discNumber:evidence?.folderDiscNumber});continue}if(!options.useFolderFallback){unmatched.push(item.metadata);continue}const identity=folderIdentity(dir,confirmedDiscs,options.scanRoot);if(!identity){unmatched.push(item.metadata);continue}const key=`${identity.titleSource}::${normalizeKey(identity.title)}`;let acc=albums.get(key);if(!acc){acc={key,album:identity.title,albumArtist:void 0,source:`folder`,directory:identity.titleSource,items:[],evidence:/* @__PURE__ */ new Map};albums.set(key,acc)}const evidence=evidenceFor(item,confirmedDiscs,flatSubdivisions);acc.evidence.set(item.path,evidence);acc.items.push({...item.metadata,albumDir:evidence?.albumDir??dir,discNumber:evidence?.folderDiscNumber})}for(const[key,acc]of albums){if(acc.source===`tags`)continue;for(const other of albums.values()){if(other===acc||other.source!==`tags`)continue;if(normalizeKey(other.album)!==normalizeKey(acc.album))continue;const albumDir=acc.directory;if(!(albumDir!==void 0&&other.items.some(o=>{const od=dirname(o.path);return od===albumDir||od.startsWith(albumDir+`/`)})))continue;for(const item of acc.items){other.items.push(item);other.evidence.set(item.path,acc.evidence.get(item.path))}albums.delete(key);break}}return{albums,unmatched}}function assembleDiscs(albums){const groups=[];for(const acc of albums.values()){const dirTagCommon=/* @__PURE__ */ new Map;const resolvedByFile=/* @__PURE__ */ new Map;for(const item of acc.items){const dir=dirname(item.path);if(!dirTagCommon.has(dir)){const tagged=acc.items.filter(i=>dirname(i.path)===dir).map(i=>i.tags.discNumber).filter(d=>d!==void 0&&d>0);dirTagCommon.set(dir,tagged.length>0&&tagged.every(d=>d===tagged[0])?tagged[0]:void 0)}const evidence=acc.evidence.get(item.path);const tagCommon=dirTagCommon.get(dir);resolvedByFile.set(item.path,tagCommon??evidence?.folderDiscNumber)}const discs=/* @__PURE__ */ new Map;const noEvidenceItems=[];for(const item of acc.items){const evidence=acc.evidence.get(item.path);if(evidence===void 0){noEvidenceItems.push(item);continue}const resolved=resolvedByFile.get(item.path);const discKey=resolved===void 0?`dir:${dirname(item.path)}`:String(resolved);let disc=discs.get(discKey);if(!disc){disc={discNumber:resolved,totalDiscs:evidence.total,folderDiscNumber:evidence.folderDiscNumber,folderDiscTitle:evidence.folderDiscTitle,tagDiscNumber:void 0,confidence:evidence.confidence,items:[]};discs.set(discKey,disc)}disc.items.push(item)}if(noEvidenceItems.length>0){const numbered=[...discs.values()].filter(d=>d.folderDiscNumber!==void 0).sort((a,b)=>a.folderDiscNumber-b.folderDiscNumber);if(numbered.length>0)numbered[0].items.push(...noEvidenceItems);else{const key=`dir:__none__`;let disc=discs.get(key);if(!disc){disc={discNumber:void 0,totalDiscs:void 0,folderDiscNumber:void 0,folderDiscTitle:void 0,tagDiscNumber:void 0,confidence:`high`,items:[]};discs.set(key,disc)}disc.items.push(...noEvidenceItems)}}for(const disc of discs.values()){const tagged=disc.items.map(i=>i.tags.discNumber).filter(d=>d!==void 0&&d>0);const common=tagged.length>0&&tagged.every(d=>d===tagged[0])?tagged[0]:void 0;disc.tagDiscNumber=common;disc.discNumber=common??disc.folderDiscNumber;for(const item of disc.items)item.discNumber=disc.discNumber}const albumTaggedTotals=acc.items.map(i=>i.tags.totalDiscs).filter(t=>t!==void 0&&t>0);const commonTotal=albumTaggedTotals.length>0&&albumTaggedTotals.every(t=>t===albumTaggedTotals[0])?albumTaggedTotals[0]:void 0;const ofN=[...discs.values()].map(d=>d.totalDiscs).find(t=>t!==void 0);const maxSibling=[...discs.values()].map(d=>d.discNumber).filter(n=>n!==void 0).reduce((a,b)=>Math.max(a,b),0)||void 0;for(const disc of discs.values())disc.totalDiscs=commonTotal??ofN??maxSibling;const sortedDiscs=[...discs.values()].sort((a,b)=>{const an=a.discNumber??-1;const bn=b.discNumber??-1;if(an!==bn)return an-bn;return(a.folderDiscTitle??``).localeCompare(b.folderDiscTitle??``)});for(const disc of sortedDiscs)disc.items.sort((a,b)=>{const at=a.tags.track??Infinity;const bt=b.tags.track??Infinity;if(at!==bt)return at-bt;return a.path.localeCompare(b.path)});const flags=acc.items.map(i=>i.tags.compilation).filter(c=>c!==void 0);const compilation=flags.length>0&&flags.every(f=>f===flags[0])?flags[0]:void 0;const albumDirs=new Set(acc.items.map(i=>i.albumDir));const directory=albumDirs.size===1?[...albumDirs][0]:acc.directory;groups.push({key:acc.key,albumArtist:acc.albumArtist,album:acc.album,source:acc.source,compilation,directory,discs:sortedDiscs,items:sortedDiscs.flatMap(d=>d.items)})}return groups}function flatPrefix(filename){const separated=/^(\d{1,2})[\s._-](\d{1,2})/.exec(filename);if(separated)return{disc:Number.parseInt(separated[1],10),form:`separated`};const compact=/^(\d)(\d{2})(?:\D|$)/.exec(filename);if(compact)return{disc:Number.parseInt(compact[1],10),form:`compact`}}function normalizeOk(result){const okItems=[];const errors=[];for(const item of result.items)if(item.status===`ok`)okItems.push({path:item.path,tags:item.tags,metadata:item});else errors.push({path:item.path,error:item.error});return{okItems,errors}}function buildTree(okItems){const tree=/* @__PURE__ */ new Map;for(const item of okItems){const dir=dirname(item.path);let node=tree.get(dir);if(!node){node={files:[],parent:dirname(dir)};tree.set(dir,node)}node.files.push(item)}return tree}function resolveDiscConfidence(parse,corroboratedBySiblings){if(parse.gated)return corroboratedBySiblings?`low`:void 0;if(parse.kind===`bonus`||parse.kind===`bare`)return corroboratedBySiblings?baseConfidence(parse):void 0;return corroboratedBySiblings?`high`:baseConfidence(parse)}function confirmDiscs(tree,minRank){const confirmedDiscs=/* @__PURE__ */ new Map;for(const[dir,node]of tree){if(node.files.length===0)continue;const parse=parseDiscName(basename(dir));if(!parse)continue;const siblings=[...tree.keys()].filter(d=>d!==dir&&dirname(d)===dirname(dir));const confidence=resolveDiscConfidence(parse,corroborated(parse,siblings));if(confidence===void 0)continue;if(CONFIDENCE_RANK[confidence]<minRank)continue;confirmedDiscs.set(dir,{parse,confidence})}return confirmedDiscs}function flatSetIsPlausible(forms,distinct){if(!(forms.size===1&&forms.has(`compact`)))return true;return distinct.every(d=>d>=1&&d<=distinct.length)}function flatSubdivisions(tree,confirmedDiscs,useFlatPrefixes){const flat=/* @__PURE__ */ new Map;if(!useFlatPrefixes)return flat;for(const[dir,node]of tree){if(node.files.length===0||confirmedDiscs.has(dir))continue;const byFile=/* @__PURE__ */ new Map;const forms=/* @__PURE__ */ new Set;for(const item of node.files){const prefix=flatPrefix(basename(item.path));if(prefix){byFile.set(item.path,prefix.disc);forms.add(prefix.form)}}if(byFile.size<2)continue;if(flatSetIsPlausible(forms,[...new Set(byFile.values())].sort((a,b)=>a-b)))flat.set(dir,byFile)}return flat}function groupAlbums(result,options={}){const minRank=CONFIDENCE_RANK[options.minFolderConfidence??`low`];const useFlatPrefixes=options.flatDiscPrefixes??true;const useFolderFallback=options.folderFallback??true;const{okItems,errors}=normalizeOk(result);if(okItems.length===0)return{albums:[],singles:[],unmatched:[],errors};const tree=buildTree(okItems);const confirmedDiscs=confirmDiscs(tree,minRank);const flat=flatSubdivisions(tree,confirmedDiscs,useFlatPrefixes);const{albums,unmatched}=buildAlbumIdentity(okItems,confirmedDiscs,flat,{scanRoot:options.scanRoot,useFolderFallback});const groups=assembleDiscs(albums);const albumsOut=[];const singles=[];for(const group of groups)if(group.items.length===1)singles.push(group.items[0]);else albumsOut.push(group);albumsOut.sort((a,b)=>(a.albumArtist??``).localeCompare(b.albumArtist??``)||(a.album??``).localeCompare(b.album??``));return{albums:albumsOut,singles,unmatched,errors}}init_classes();function pictureToDataURL(picture){const data=picture.data;const CHUNK=32768;let binary=``;for(let i=0;i<data.length;i+=CHUNK)binary+=String.fromCodePoint(...data.subarray(i,i+CHUNK));const base64=btoa(binary);return`data:${picture.mimeType};base64,${base64}`}function dataURLToPicture(dataURL,type=`FrontCover`,description){const matches=/^data:([^;]+);base64,(.+)$/.exec(dataURL);if(!matches)throw new InvalidFormatError(`Invalid data URL format`);const[,mimeType,base64]=matches;const binaryString=atob(base64);const data=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)data[i]=binaryString.codePointAt(i);return{mimeType,data,type,...description!==void 0?{description}:{}}}async function setCoverArtFromCanvas(file,canvas,options={}){const{format=`image/jpeg`,quality=.92,type=`FrontCover`,description=`Front Cover`}=options;const dataURL=canvas.toDataURL(format,quality);const picture=dataURLToPicture(dataURL,type,description);return applyPictures(file,[picture])}async function canvasToPicture(canvas,options={}){const{format=`image/jpeg`,quality=.92,type=`FrontCover`,description}=options;return new Promise((resolve,reject)=>{canvas.toBlob(blob=>{if(!blob){reject(/* @__PURE__ */ new Error(`Failed to convert canvas to blob`));return}blob.arrayBuffer().then(arrayBuffer=>{const data=new Uint8Array(arrayBuffer);resolve({mimeType:format,data,type,...description!==void 0?{description}:{}})},reject)},format,quality)})}async function imageFileToPicture(file,type=`FrontCover`,description){const arrayBuffer=await file.arrayBuffer();const data=new Uint8Array(arrayBuffer);return{mimeType:file.type,data,type,description:description??file.name}}function ensureArrayBufferBacked(data){if(data.buffer instanceof ArrayBuffer)return data;const copy=new Uint8Array(data.length);copy.set(data);return copy}function displayPicture(picture,imgElement){if(imgElement.src.startsWith(`blob:`))URL.revokeObjectURL(imgElement.src);const data=ensureArrayBufferBacked(picture.data);const blob=new Blob([data],{type:picture.mimeType});const objectURL=URL.createObjectURL(blob);imgElement.src=objectURL;imgElement.addEventListener(`load`,()=>{setTimeout(()=>URL.revokeObjectURL(objectURL),100)},{once:true})}function createPictureDownloadURL(picture,filename=`cover`){const data=ensureArrayBufferBacked(picture.data);const blob=new Blob([data],{type:picture.mimeType});return URL.createObjectURL(blob)}async function createPictureGallery(file,container,options={}){const pictures=await readPictures(file);container.innerHTML=``;pictures.forEach((picture,index)=>{const wrapper=document.createElement(`div`);wrapper.className=options.className??`picture-item`;const img=document.createElement(`img`);displayPicture(picture,img);img.alt=picture.description??`Picture ${index+1}`;if(options.onClick){img.style.cursor=`pointer`;img.addEventListener(`click`,()=>options.onClick(picture,index))}wrapper.appendChild(img);if(options.includeDescription&&picture.description){const caption=document.createElement(`p`);caption.textContent=picture.description;wrapper.appendChild(caption)}container.appendChild(wrapper)})}init_audio_formats();init_errors();init_properties();init_types();init_bext();init_rating();init_module_loader_browser();init_pictures();init_base();init_classes();init_guards();init_audio_file_impl();init_taglib_class();export{AudioFileImpl,BITRATE_CONTROL_MODE_NAMES,BITRATE_CONTROL_MODE_VALUES,EnvironmentError,FileOperationError,FormatMappings,InvalidFormatError,MemoryError,MetadataError,PICTURE_TYPE_NAMES,PICTURE_TYPE_VALUES,PROPERTIES,RatingUtils,SUPPORTED_FORMATS,TagLib,TagLibError,TagLibInitializationError,UnsupportedFormatError,addPicture,applyCoverArt,applyPictures,applyTags,applyTagsToFile,bext_exports as bwf,canvasToPicture,clearPictures,clearTags,createPictureDownloadURL,createPictureGallery,createTagLib,dataURLToPicture,discFolderInfo,displayPicture,findPictureByType,getAllProperties,getAllPropertyKeys,getPropertiesByFormat,getPropertyMetadata,groupAlbums,imageFileToPicture,isDenoCompiled,isEnvironmentError,isFileOperationError,isInvalidFormatError,isMemoryError,isMetadataError,isNamedAudioInput,isTagLibError,isUnsupportedFormatError,isValidAudioFile,isValidProperty,loadTagLibModule,pictureToDataURL,propertyValue,propertyValues,readCoverArt,readFormat,readMediaChecksum,readMetadata,readMetadataBatch,readPictureMetadata,readPictures,readProperties,readPropertiesBatch,readTags,readTagsBatch,replacePictureByType,setBufferMode,setCoverArtFromCanvas};