@trismegisto/media 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +56 -0
  2. package/MIGRATION.md +831 -0
  3. package/NOTICE +14 -0
  4. package/README.md +87 -2
  5. package/dist/announce.d.ts +60 -0
  6. package/dist/announce.js +124 -0
  7. package/dist/announce.js.map +1 -0
  8. package/dist/archive.d.ts +121 -0
  9. package/dist/archive.js +413 -0
  10. package/dist/archive.js.map +1 -0
  11. package/dist/captions.d.ts +180 -0
  12. package/dist/captions.js +468 -0
  13. package/dist/captions.js.map +1 -0
  14. package/dist/controls.d.ts +79 -0
  15. package/dist/controls.js +153 -0
  16. package/dist/controls.js.map +1 -0
  17. package/dist/csv.d.ts +43 -0
  18. package/dist/csv.js +197 -0
  19. package/dist/csv.js.map +1 -0
  20. package/dist/detect.d.ts +86 -0
  21. package/dist/detect.js +597 -0
  22. package/dist/detect.js.map +1 -0
  23. package/dist/file-source.d.ts +72 -0
  24. package/dist/file-source.js +19 -0
  25. package/dist/file-source.js.map +1 -0
  26. package/dist/file-view.d.ts +77 -0
  27. package/dist/file-view.js +124 -0
  28. package/dist/file-view.js.map +1 -0
  29. package/dist/format.d.ts +29 -0
  30. package/dist/format.js +122 -0
  31. package/dist/format.js.map +1 -0
  32. package/dist/gallery.d.ts +40 -0
  33. package/dist/gallery.js +53 -0
  34. package/dist/gallery.js.map +1 -0
  35. package/dist/html-preview.d.ts +24 -0
  36. package/dist/html-preview.js +30 -0
  37. package/dist/html-preview.js.map +1 -0
  38. package/dist/image-view.d.ts +71 -0
  39. package/dist/image-view.js +158 -0
  40. package/dist/image-view.js.map +1 -0
  41. package/dist/image.d.ts +101 -0
  42. package/dist/image.js +146 -0
  43. package/dist/image.js.map +1 -0
  44. package/dist/index.d.ts +25 -0
  45. package/dist/index.js +28 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/keyboard.d.ts +101 -0
  48. package/dist/keyboard.js +144 -0
  49. package/dist/keyboard.js.map +1 -0
  50. package/dist/markdown-html.d.ts +12 -0
  51. package/dist/markdown-html.js +32 -0
  52. package/dist/markdown-html.js.map +1 -0
  53. package/dist/media-i18n.d.ts +17 -0
  54. package/dist/media-i18n.js +27 -0
  55. package/dist/media-i18n.js.map +1 -0
  56. package/dist/media-messages.d.ts +249 -0
  57. package/dist/media-messages.en.d.ts +2 -0
  58. package/dist/media-messages.en.js +218 -0
  59. package/dist/media-messages.en.js.map +1 -0
  60. package/dist/media-messages.es.d.ts +2 -0
  61. package/dist/media-messages.es.js +218 -0
  62. package/dist/media-messages.es.js.map +1 -0
  63. package/dist/media-messages.js +218 -0
  64. package/dist/media-messages.js.map +1 -0
  65. package/dist/player-view.d.ts +104 -0
  66. package/dist/player-view.js +171 -0
  67. package/dist/player-view.js.map +1 -0
  68. package/dist/player.d.ts +324 -0
  69. package/dist/player.js +1146 -0
  70. package/dist/player.js.map +1 -0
  71. package/dist/range.d.ts +75 -0
  72. package/dist/range.js +185 -0
  73. package/dist/range.js.map +1 -0
  74. package/dist/registry.d.ts +55 -0
  75. package/dist/registry.js +81 -0
  76. package/dist/registry.js.map +1 -0
  77. package/dist/text.d.ts +103 -0
  78. package/dist/text.js +192 -0
  79. package/dist/text.js.map +1 -0
  80. package/dist/thumbnail.d.ts +113 -0
  81. package/dist/thumbnail.js +332 -0
  82. package/dist/thumbnail.js.map +1 -0
  83. package/package.json +55 -6
package/dist/detect.js ADDED
@@ -0,0 +1,597 @@
1
+ /**
2
+ * Detecção do tipo de um arquivo, pura (sem I/O): MIME declarado, extensão do nome e assinatura dos primeiros bytes.
3
+ * Quem lê os bytes é o `range` (ou o app). A ordem de decisão está em `detectFileKind`; a tabela de assinaturas segue a
4
+ * norma de MIME Sniffing do WHATWG e as estruturas públicas de cada formato (caixa `ftyp` do ISO BMFF, RIFF, EBML).
5
+ *
6
+ * Regra de segurança: a detecção nunca promove um arquivo a tipo que executa script. SVG, HTML, XHTML e XML saem com
7
+ * `risky: true` e só são mostrados como `<img>` (SVG declarado como imagem) ou como código-fonte.
8
+ */
9
+ /** Quantos bytes do início a detecção usa (a assinatura mais longa da tabela cabe aqui). */
10
+ export const DETECT_HEAD_BYTES = 64;
11
+ /** MIMEs que não dizem nada do conteúdo: quem decide é a extensão. */
12
+ const GENERIC_MIMES = new Set(['', 'application/octet-stream', 'binary/octet-stream', 'application/unknown', 'application/binary', 'unknown/unknown']);
13
+ const e = (kind, mime, language, extra = {}) => ({
14
+ kind,
15
+ mime,
16
+ ...(language ? { language } : {}),
17
+ ...extra,
18
+ });
19
+ /** Uma entrada por extensão, com o MIME canônico. */
20
+ const EXTENSIONS = {
21
+ // vídeo
22
+ mp4: e('video', 'video/mp4'),
23
+ m4v: e('video', 'video/mp4'),
24
+ webm: e('video', 'video/webm'),
25
+ mov: e('video', 'video/quicktime'),
26
+ mkv: e('video', 'video/x-matroska'),
27
+ ogv: e('video', 'video/ogg'),
28
+ avi: e('video', 'video/x-msvideo'),
29
+ '3gp': e('video', 'video/3gpp'),
30
+ m3u8: e('video', 'application/vnd.apple.mpegurl', undefined, { streaming: 'hls' }),
31
+ mpd: e('video', 'application/dash+xml', undefined, { streaming: 'dash' }),
32
+ // áudio
33
+ mp3: e('audio', 'audio/mpeg'),
34
+ m4a: e('audio', 'audio/mp4'),
35
+ aac: e('audio', 'audio/aac'),
36
+ oga: e('audio', 'audio/ogg'),
37
+ ogg: e('audio', 'audio/ogg'),
38
+ opus: e('audio', 'audio/ogg'),
39
+ wav: e('audio', 'audio/wav'),
40
+ flac: e('audio', 'audio/flac'),
41
+ weba: e('audio', 'audio/webm'),
42
+ // imagem
43
+ png: e('image', 'image/png'),
44
+ apng: e('image', 'image/apng'),
45
+ jpg: e('image', 'image/jpeg'),
46
+ jpeg: e('image', 'image/jpeg'),
47
+ jfif: e('image', 'image/jpeg'),
48
+ gif: e('image', 'image/gif'),
49
+ webp: e('image', 'image/webp'),
50
+ avif: e('image', 'image/avif'),
51
+ svg: e('image', 'image/svg+xml', undefined, { risky: true }),
52
+ bmp: e('image', 'image/bmp'),
53
+ ico: e('image', 'image/x-icon'),
54
+ cur: e('image', 'image/x-icon'),
55
+ heic: e('image', 'image/heic'),
56
+ heif: e('image', 'image/heif'),
57
+ tif: e('image', 'image/tiff'),
58
+ tiff: e('image', 'image/tiff'),
59
+ // documentos
60
+ pdf: e('pdf', 'application/pdf'),
61
+ md: e('markdown', 'text/markdown', 'markdown'),
62
+ markdown: e('markdown', 'text/markdown', 'markdown'),
63
+ json: e('json', 'application/json', 'json'),
64
+ jsonl: e('json', 'application/jsonl', 'json'),
65
+ ndjson: e('json', 'application/x-ndjson', 'json'),
66
+ geojson: e('json', 'application/geo+json', 'json'),
67
+ csv: e('csv', 'text/csv'),
68
+ tsv: e('csv', 'text/tab-separated-values'),
69
+ // texto
70
+ txt: e('text', 'text/plain', 'text'),
71
+ log: e('text', 'text/plain', 'text'),
72
+ text: e('text', 'text/plain', 'text'),
73
+ vtt: e('text', 'text/vtt', 'text'),
74
+ srt: e('text', 'application/x-subrip', 'text'),
75
+ // código
76
+ ts: e('code', 'text/x-typescript', 'typescript'),
77
+ tsx: e('code', 'text/x-typescript', 'typescript'),
78
+ mts: e('code', 'text/x-typescript', 'typescript'),
79
+ cts: e('code', 'text/x-typescript', 'typescript'),
80
+ js: e('code', 'text/javascript', 'javascript'),
81
+ mjs: e('code', 'text/javascript', 'javascript'),
82
+ cjs: e('code', 'text/javascript', 'javascript'),
83
+ jsx: e('code', 'text/javascript', 'javascript'),
84
+ css: e('code', 'text/css', 'css'),
85
+ scss: e('code', 'text/x-scss', 'scss'),
86
+ html: e('code', 'text/html', 'html', { risky: true }),
87
+ htm: e('code', 'text/html', 'html', { risky: true }),
88
+ xhtml: e('code', 'application/xhtml+xml', 'html', { risky: true }),
89
+ xml: e('code', 'application/xml', 'xml', { risky: true }),
90
+ xsd: e('code', 'application/xml', 'xml', { risky: true }),
91
+ xsl: e('code', 'application/xml', 'xml', { risky: true }),
92
+ plist: e('code', 'application/xml', 'xml', { risky: true }),
93
+ yaml: e('code', 'application/yaml', 'yaml'),
94
+ yml: e('code', 'application/yaml', 'yaml'),
95
+ toml: e('code', 'application/toml', 'toml'),
96
+ ini: e('code', 'text/plain', 'ini'),
97
+ cfg: e('code', 'text/plain', 'ini'),
98
+ conf: e('code', 'text/plain', 'ini'),
99
+ properties: e('code', 'text/plain', 'ini'),
100
+ env: e('code', 'text/plain', 'ini'),
101
+ sql: e('code', 'application/sql', 'sql'),
102
+ sh: e('code', 'application/x-sh', 'bash'),
103
+ bash: e('code', 'application/x-sh', 'bash'),
104
+ zsh: e('code', 'application/x-sh', 'bash'),
105
+ py: e('code', 'text/x-python', 'python'),
106
+ java: e('code', 'text/x-java', 'java'),
107
+ kt: e('code', 'text/x-kotlin', 'kotlin'),
108
+ kts: e('code', 'text/x-kotlin', 'kotlin'),
109
+ cs: e('code', 'text/x-csharp', 'csharp'),
110
+ go: e('code', 'text/x-go', 'go'),
111
+ rs: e('code', 'text/x-rust', 'rust'),
112
+ php: e('code', 'application/x-php', 'php'),
113
+ graphql: e('code', 'application/graphql', 'graphql'),
114
+ gql: e('code', 'application/graphql', 'graphql'),
115
+ dockerfile: e('code', 'text/plain', 'dockerfile'),
116
+ c: e('code', 'text/x-c', 'text'),
117
+ h: e('code', 'text/x-c', 'text'),
118
+ cpp: e('code', 'text/x-c++', 'text'),
119
+ hpp: e('code', 'text/x-c++', 'text'),
120
+ rb: e('code', 'text/x-ruby', 'text'),
121
+ swift: e('code', 'text/x-swift', 'text'),
122
+ // compactados
123
+ zip: e('archive', 'application/zip'),
124
+ gz: e('archive', 'application/gzip'),
125
+ tgz: e('archive', 'application/gzip'),
126
+ tar: e('archive', 'application/x-tar'),
127
+ '7z': e('archive', 'application/x-7z-compressed'),
128
+ rar: e('archive', 'application/vnd.rar'),
129
+ bz2: e('archive', 'application/x-bzip2'),
130
+ xz: e('archive', 'application/x-xz'),
131
+ // sem visualizador (ícone e metadados): documentos de escritório e pacotes que são ZIP por dentro
132
+ docx: e('unsupported', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'),
133
+ xlsx: e('unsupported', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
134
+ pptx: e('unsupported', 'application/vnd.openxmlformats-officedocument.presentationml.presentation'),
135
+ doc: e('unsupported', 'application/msword'),
136
+ xls: e('unsupported', 'application/vnd.ms-excel'),
137
+ ppt: e('unsupported', 'application/vnd.ms-powerpoint'),
138
+ odt: e('unsupported', 'application/vnd.oasis.opendocument.text'),
139
+ ods: e('unsupported', 'application/vnd.oasis.opendocument.spreadsheet'),
140
+ odp: e('unsupported', 'application/vnd.oasis.opendocument.presentation'),
141
+ epub: e('unsupported', 'application/epub+zip'),
142
+ jar: e('unsupported', 'application/java-archive'),
143
+ apk: e('unsupported', 'application/vnd.android.package-archive'),
144
+ };
145
+ /** Extensões de formatos que são ZIP por dentro: a assinatura ZIP não os rebaixa a "compactado". */
146
+ const ZIP_BASED = new Set(['docx', 'xlsx', 'pptx', 'odt', 'ods', 'odp', 'epub', 'jar', 'apk']);
147
+ /** Formato que é ZIP por dentro (.docx, .epub, .jar...): o app pode pedir a listagem no lugar do cartão. */
148
+ export function isZipPackage(name) {
149
+ return ZIP_BASED.has(fileNameParts(name).extension);
150
+ }
151
+ /** Compressores de um arquivo só (a extensão de antes diz o que está dentro: `.tar.gz`). */
152
+ const COMPRESSORS = new Set(['gz', 'bz2', 'xz']);
153
+ /** Nomes sem extensão conhecidos. */
154
+ const KNOWN_NAMES = {
155
+ dockerfile: e('code', 'text/plain', 'dockerfile'),
156
+ containerfile: e('code', 'text/plain', 'dockerfile'),
157
+ makefile: e('code', 'text/plain', 'text'),
158
+ gnumakefile: e('code', 'text/plain', 'text'),
159
+ jenkinsfile: e('code', 'text/plain', 'text'),
160
+ procfile: e('code', 'text/plain', 'text'),
161
+ license: e('text', 'text/plain', 'text'),
162
+ licence: e('text', 'text/plain', 'text'),
163
+ copying: e('text', 'text/plain', 'text'),
164
+ notice: e('text', 'text/plain', 'text'),
165
+ readme: e('text', 'text/plain', 'text'),
166
+ changelog: e('text', 'text/plain', 'text'),
167
+ authors: e('text', 'text/plain', 'text'),
168
+ contributing: e('text', 'text/plain', 'text'),
169
+ '.gitignore': e('code', 'text/plain', 'ini'),
170
+ '.gitattributes': e('code', 'text/plain', 'ini'),
171
+ '.dockerignore': e('code', 'text/plain', 'ini'),
172
+ '.editorconfig': e('code', 'text/plain', 'ini'),
173
+ '.npmrc': e('code', 'text/plain', 'ini'),
174
+ '.env': e('code', 'text/plain', 'ini'),
175
+ };
176
+ /** Linguagem pelo MIME de código (quando a extensão não diz). */
177
+ const LANGUAGE_BY_MIME = {
178
+ 'text/html': 'html',
179
+ 'application/xhtml+xml': 'html',
180
+ 'text/xml': 'xml',
181
+ 'application/xml': 'xml',
182
+ 'text/javascript': 'javascript',
183
+ 'application/javascript': 'javascript',
184
+ 'application/x-javascript': 'javascript',
185
+ 'text/css': 'css',
186
+ 'text/x-python': 'python',
187
+ 'application/x-python': 'python',
188
+ 'application/x-sh': 'bash',
189
+ 'text/x-shellscript': 'bash',
190
+ 'application/sql': 'sql',
191
+ 'application/yaml': 'yaml',
192
+ 'application/x-yaml': 'yaml',
193
+ 'text/yaml': 'yaml',
194
+ 'text/x-yaml': 'yaml',
195
+ 'application/toml': 'toml',
196
+ 'application/graphql': 'graphql',
197
+ 'text/x-java': 'java',
198
+ 'text/x-java-source': 'java',
199
+ 'application/x-php': 'php',
200
+ 'text/x-go': 'go',
201
+ 'text/x-rust': 'rust',
202
+ 'text/x-typescript': 'typescript',
203
+ 'application/typescript': 'typescript',
204
+ };
205
+ /** MIMEs de código que podem executar script se renderizados. */
206
+ const RISKY_CODE_MIMES = new Set(['text/html', 'application/xhtml+xml', 'text/xml', 'application/xml']);
207
+ const ARCHIVE_MIMES = new Set([
208
+ 'application/zip',
209
+ 'application/x-zip-compressed',
210
+ 'application/x-zip',
211
+ 'application/gzip',
212
+ 'application/x-gzip',
213
+ 'application/x-tar',
214
+ 'application/x-gtar',
215
+ 'application/x-7z-compressed',
216
+ 'application/vnd.rar',
217
+ 'application/x-rar-compressed',
218
+ 'application/x-bzip2',
219
+ 'application/x-xz',
220
+ ]);
221
+ const HLS_MIMES = new Set(['application/vnd.apple.mpegurl', 'application/x-mpegurl', 'audio/mpegurl', 'audio/x-mpegurl']);
222
+ /** Rótulo de formato pelo MIME, quando a extensão não existe (`video/mp4` → `MP4`). */
223
+ const FORMAT_BY_MIME = {
224
+ 'video/quicktime': 'MOV',
225
+ 'video/x-matroska': 'MKV',
226
+ 'video/x-msvideo': 'AVI',
227
+ 'audio/mpeg': 'MP3',
228
+ 'audio/mp4': 'M4A',
229
+ 'audio/x-m4a': 'M4A',
230
+ 'audio/wav': 'WAV',
231
+ 'audio/x-wav': 'WAV',
232
+ 'audio/wave': 'WAV',
233
+ 'image/jpeg': 'JPEG',
234
+ 'image/svg+xml': 'SVG',
235
+ 'image/x-icon': 'ICO',
236
+ 'image/vnd.microsoft.icon': 'ICO',
237
+ 'application/pdf': 'PDF',
238
+ 'application/json': 'JSON',
239
+ 'text/markdown': 'MD',
240
+ 'text/csv': 'CSV',
241
+ 'text/tab-separated-values': 'TSV',
242
+ 'text/plain': 'TXT',
243
+ 'text/html': 'HTML',
244
+ 'application/xhtml+xml': 'XHTML',
245
+ 'text/xml': 'XML',
246
+ 'application/xml': 'XML',
247
+ 'application/zip': 'ZIP',
248
+ 'application/x-zip-compressed': 'ZIP',
249
+ 'application/gzip': 'GZ',
250
+ 'application/x-gzip': 'GZ',
251
+ 'application/x-tar': 'TAR',
252
+ 'application/x-7z-compressed': '7Z',
253
+ 'application/vnd.rar': 'RAR',
254
+ 'application/x-rar-compressed': 'RAR',
255
+ 'application/x-bzip2': 'BZ2',
256
+ 'application/x-xz': 'XZ',
257
+ 'application/vnd.apple.mpegurl': 'HLS',
258
+ 'application/x-mpegurl': 'HLS',
259
+ 'application/dash+xml': 'DASH',
260
+ 'text/vtt': 'VTT',
261
+ };
262
+ /** `Content-Type` decomposto: tipo em minúsculas sem parâmetros e o `charset`, se houver. */
263
+ export function parseMime(value) {
264
+ const [type = '', ...params] = (value ?? '').split(';');
265
+ const mime = type.trim().toLowerCase();
266
+ for (const param of params) {
267
+ const [key, raw] = param.split('=');
268
+ if (key?.trim().toLowerCase() === 'charset' && raw) {
269
+ const charset = raw.trim().replace(/^"|"$/g, '').toLowerCase();
270
+ if (charset)
271
+ return { mime, charset };
272
+ }
273
+ }
274
+ return { mime };
275
+ }
276
+ /** Partes do nome: a base sem caminho, a extensão final e a de antes (`a/b.tar.gz` → `gz`, `tar`). */
277
+ export function fileNameParts(name) {
278
+ const base = (name ?? '').trim().split(/[\\/]/).pop() ?? '';
279
+ const parts = base.toLowerCase().split('.');
280
+ if (parts.length < 2 || (parts.length === 2 && parts[0] === ''))
281
+ return { base, extension: '', previous: '' };
282
+ const extension = parts[parts.length - 1];
283
+ const previous = parts.length > 2 && parts[parts.length - 2] ? parts[parts.length - 2] : '';
284
+ return { base, extension, previous };
285
+ }
286
+ function bytesOf(head) {
287
+ if (!head)
288
+ return null;
289
+ return head instanceof Uint8Array ? head : new Uint8Array(head);
290
+ }
291
+ function ascii(bytes, start, length) {
292
+ let out = '';
293
+ for (let i = start; i < start + length && i < bytes.length; i++)
294
+ out += String.fromCharCode(bytes[i]);
295
+ return out;
296
+ }
297
+ function startsWith(bytes, signature, offset = 0) {
298
+ if (bytes.length < offset + signature.length)
299
+ return false;
300
+ return signature.every((byte, i) => bytes[offset + i] === byte);
301
+ }
302
+ /** Marcação que um navegador renderizaria como documento ativo (procurada no começo, depois de BOM e espaço). */
303
+ function markupSignature(bytes) {
304
+ let start = 0;
305
+ if (startsWith(bytes, [0xef, 0xbb, 0xbf]))
306
+ start = 3;
307
+ while (start < bytes.length && [0x09, 0x0a, 0x0c, 0x0d, 0x20].includes(bytes[start]))
308
+ start++;
309
+ const text = ascii(bytes, start, bytes.length - start).toLowerCase();
310
+ if (text.startsWith('<svg'))
311
+ return { kind: 'code', mime: 'image/svg+xml', format: 'SVG', risky: true, language: 'xml' };
312
+ if (text.startsWith('<?xml')) {
313
+ return text.includes('<svg')
314
+ ? { kind: 'code', mime: 'image/svg+xml', format: 'SVG', risky: true, language: 'xml' }
315
+ : { kind: 'code', mime: 'application/xml', format: 'XML', risky: true, language: 'xml' };
316
+ }
317
+ for (const tag of ['<!doctype html', '<html', '<head', '<body', '<script', '<iframe', '<title', '<style', '<div', '<a ', '<p>', '<br', '<table', '<h1', '<font', '<b>', '<!--']) {
318
+ if (text.startsWith(tag))
319
+ return { kind: 'code', mime: 'text/html', format: 'HTML', risky: true, language: 'html' };
320
+ }
321
+ return null;
322
+ }
323
+ /** Marca principal e compatíveis de uma caixa `ftyp` (ISO BMFF: MP4, MOV, M4A, AVIF, HEIC). */
324
+ function ftypSignature(bytes) {
325
+ if (ascii(bytes, 4, 4) !== 'ftyp')
326
+ return null;
327
+ const size = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0;
328
+ const brands = [ascii(bytes, 8, 4)];
329
+ for (let offset = 16; offset + 4 <= Math.min(size || bytes.length, bytes.length); offset += 4)
330
+ brands.push(ascii(bytes, offset, 4));
331
+ const has = (...names) => brands.some((b) => names.includes(b));
332
+ const major = brands[0];
333
+ if (major === 'avif' || major === 'avis')
334
+ return { kind: 'image', mime: 'image/avif', format: 'AVIF' };
335
+ if (['heic', 'heix', 'hevc', 'heim', 'heis'].includes(major))
336
+ return { kind: 'image', mime: 'image/heic', format: 'HEIC' };
337
+ if (['mif1', 'msf1'].includes(major)) {
338
+ if (has('avif', 'avis'))
339
+ return { kind: 'image', mime: 'image/avif', format: 'AVIF' };
340
+ return { kind: 'image', mime: 'image/heif', format: 'HEIF' };
341
+ }
342
+ if (major === 'M4A ' || major === 'M4B ' || major === 'M4P ')
343
+ return { kind: 'audio', mime: 'audio/mp4', format: 'M4A' };
344
+ if (major === 'qt ')
345
+ return { kind: 'video', mime: 'video/quicktime', format: 'MOV' };
346
+ if (major.startsWith('3g'))
347
+ return { kind: 'video', mime: 'video/3gpp', format: '3GP' };
348
+ return { kind: 'video', mime: 'video/mp4', format: 'MP4' };
349
+ }
350
+ /**
351
+ * Família pela assinatura dos primeiros bytes, ou `null` se nenhuma casa. Cobre as imagens raster, PDF, os
352
+ * compactados, os contêineres de áudio e vídeo e a marcação ativa (SVG, HTML, XML).
353
+ */
354
+ export function sniffSignature(head) {
355
+ const bytes = bytesOf(head);
356
+ if (!bytes || bytes.length < 2)
357
+ return null;
358
+ if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))
359
+ return { kind: 'image', mime: 'image/png', format: 'PNG' };
360
+ if (startsWith(bytes, [0xff, 0xd8, 0xff]))
361
+ return { kind: 'image', mime: 'image/jpeg', format: 'JPEG' };
362
+ const head6 = ascii(bytes, 0, 6);
363
+ if (head6 === 'GIF87a' || head6 === 'GIF89a')
364
+ return { kind: 'image', mime: 'image/gif', format: 'GIF' };
365
+ if (ascii(bytes, 0, 4) === 'RIFF') {
366
+ const form = ascii(bytes, 8, 4);
367
+ if (form === 'WEBP')
368
+ return { kind: 'image', mime: 'image/webp', format: 'WEBP' };
369
+ if (form === 'WAVE')
370
+ return { kind: 'audio', mime: 'audio/wav', format: 'WAV' };
371
+ if (form === 'AVI ')
372
+ return { kind: 'video', mime: 'video/x-msvideo', format: 'AVI' };
373
+ }
374
+ if (ascii(bytes, 0, 2) === 'BM' && bytes.length >= 14)
375
+ return { kind: 'image', mime: 'image/bmp', format: 'BMP' };
376
+ if (startsWith(bytes, [0x00, 0x00, 0x01, 0x00]) || startsWith(bytes, [0x00, 0x00, 0x02, 0x00])) {
377
+ return { kind: 'image', mime: 'image/x-icon', format: 'ICO' };
378
+ }
379
+ if (ascii(bytes, 0, 5) === '%PDF-')
380
+ return { kind: 'pdf', mime: 'application/pdf', format: 'PDF' };
381
+ if (startsWith(bytes, [0x50, 0x4b, 0x03, 0x04]) || startsWith(bytes, [0x50, 0x4b, 0x05, 0x06]) || startsWith(bytes, [0x50, 0x4b, 0x07, 0x08])) {
382
+ return { kind: 'archive', mime: 'application/zip', format: 'ZIP' };
383
+ }
384
+ if (startsWith(bytes, [0x1f, 0x8b]))
385
+ return { kind: 'archive', mime: 'application/gzip', format: 'GZ' };
386
+ if (startsWith(bytes, [0x37, 0x7a, 0xbc, 0xaf, 0x27, 0x1c]))
387
+ return { kind: 'archive', mime: 'application/x-7z-compressed', format: '7Z' };
388
+ if (ascii(bytes, 0, 6) === 'Rar!\x1a\x07')
389
+ return { kind: 'archive', mime: 'application/vnd.rar', format: 'RAR' };
390
+ if (ascii(bytes, 0, 3) === 'BZh')
391
+ return { kind: 'archive', mime: 'application/x-bzip2', format: 'BZ2' };
392
+ if (startsWith(bytes, [0xfd, 0x37, 0x7a, 0x58, 0x5a, 0x00]))
393
+ return { kind: 'archive', mime: 'application/x-xz', format: 'XZ' };
394
+ if (ascii(bytes, 0, 4) === 'OggS')
395
+ return { kind: 'audio', mime: 'audio/ogg', format: 'OGG' };
396
+ if (ascii(bytes, 0, 4) === 'fLaC')
397
+ return { kind: 'audio', mime: 'audio/flac', format: 'FLAC' };
398
+ if (startsWith(bytes, [0x1a, 0x45, 0xdf, 0xa3])) {
399
+ const isWebm = ascii(bytes, 0, bytes.length).includes('webm');
400
+ return isWebm ? { kind: 'video', mime: 'video/webm', format: 'WEBM' } : { kind: 'video', mime: 'video/x-matroska', format: 'MKV' };
401
+ }
402
+ const ftyp = ftypSignature(bytes);
403
+ if (ftyp)
404
+ return ftyp;
405
+ if (ascii(bytes, 0, 3) === 'ID3')
406
+ return { kind: 'audio', mime: 'audio/mpeg', format: 'MP3' };
407
+ // Cabeçalho de quadro de áudio MPEG: 11 bits de sincronismo. Camada 00 é o ADTS do AAC; as demais, MP3.
408
+ if (bytes[0] === 0xff && (bytes[1] & 0xe0) === 0xe0) {
409
+ const layer = (bytes[1] >> 1) & 0x03;
410
+ if ((bytes[1] & 0xf6) === 0xf0)
411
+ return { kind: 'audio', mime: 'audio/aac', format: 'AAC' };
412
+ if (layer !== 0)
413
+ return { kind: 'audio', mime: 'audio/mpeg', format: 'MP3' };
414
+ }
415
+ return markupSignature(bytes);
416
+ }
417
+ /** O começo parece texto: sem byte nulo e decodificável como UTF-8 (um caractere cortado no fim não conta). */
418
+ export function looksLikeText(head) {
419
+ const bytes = bytesOf(head);
420
+ if (!bytes || !bytes.length)
421
+ return false;
422
+ if (bytes.includes(0))
423
+ return false;
424
+ try {
425
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes, { stream: true });
426
+ return true;
427
+ }
428
+ catch {
429
+ return false;
430
+ }
431
+ }
432
+ function formatFromExtension(extension) {
433
+ return extension ? extension.toUpperCase() : '';
434
+ }
435
+ function formatFor(mime, extension) {
436
+ return formatFromExtension(extension) || FORMAT_BY_MIME[mime] || mime.split('/')[1]?.replace(/^x-/, '').split('+')[0]?.toUpperCase() || '';
437
+ }
438
+ /** Decisão pelo MIME declarado (regra 1), ou `null` se o MIME não decide a família. */
439
+ function fromDeclared(mime, extension) {
440
+ const entry = EXTENSIONS[extension];
441
+ if (HLS_MIMES.has(mime))
442
+ return { kind: 'video', mime, risky: false, streaming: 'hls' };
443
+ if (mime === 'application/dash+xml')
444
+ return { kind: 'video', mime, risky: false, streaming: 'dash' };
445
+ if (mime.startsWith('video/'))
446
+ return { kind: 'video', mime, risky: false };
447
+ if (mime.startsWith('audio/'))
448
+ return { kind: 'audio', mime, risky: false };
449
+ if (mime === 'image/svg+xml')
450
+ return { kind: 'image', mime, risky: true };
451
+ if (mime.startsWith('image/'))
452
+ return { kind: 'image', mime, risky: false };
453
+ if (mime === 'application/pdf')
454
+ return { kind: 'pdf', mime, risky: false };
455
+ if (mime === 'application/json' || mime === 'text/json' || mime.endsWith('+json') || mime === 'application/x-ndjson' || mime === 'application/jsonl') {
456
+ return { kind: 'json', mime, risky: false, language: 'json' };
457
+ }
458
+ if (mime === 'text/markdown' || mime === 'text/x-markdown')
459
+ return { kind: 'markdown', mime, risky: false, language: 'markdown' };
460
+ if (mime === 'text/csv' || mime === 'text/tab-separated-values')
461
+ return { kind: 'csv', mime, risky: false };
462
+ if (ARCHIVE_MIMES.has(mime))
463
+ return { kind: 'archive', mime, risky: false };
464
+ if (mime === 'text/vtt')
465
+ return { kind: 'text', mime, risky: false, language: 'text' };
466
+ if (RISKY_CODE_MIMES.has(mime) || (mime.endsWith('+xml') && mime !== 'image/svg+xml')) {
467
+ return { kind: 'code', mime, risky: true, language: LANGUAGE_BY_MIME[mime] ?? 'xml' };
468
+ }
469
+ if (mime === 'text/plain') {
470
+ // `text/plain` é o que muito servidor manda para qualquer texto: a extensão refina (código, Markdown, JSON, CSV).
471
+ if (entry && ['code', 'markdown', 'json', 'csv'].includes(entry.kind)) {
472
+ return { kind: entry.kind, mime: entry.mime, risky: !!entry.risky, ...(entry.language ? { language: entry.language } : {}) };
473
+ }
474
+ return { kind: 'text', mime, risky: false, language: entry?.language ?? 'text' };
475
+ }
476
+ const language = LANGUAGE_BY_MIME[mime];
477
+ if (language)
478
+ return { kind: 'code', mime, risky: false, language: entry?.language ?? language };
479
+ if (mime.startsWith('text/')) {
480
+ if (entry && entry.kind === 'code')
481
+ return { kind: 'code', mime, risky: !!entry.risky, language: entry.language };
482
+ return { kind: 'text', mime, risky: false, language: 'text' };
483
+ }
484
+ if (mime.startsWith('application/vnd.openxmlformats') || mime.startsWith('application/vnd.oasis') || mime.startsWith('application/vnd.ms-') || mime === 'application/msword') {
485
+ return { kind: 'unsupported', mime, risky: false };
486
+ }
487
+ return null;
488
+ }
489
+ /** Decisão pela extensão (regra 2): nome conhecido, extensão da tabela ou `null`. */
490
+ function fromExtension(base, extension) {
491
+ const known = KNOWN_NAMES[base.toLowerCase()] ?? KNOWN_NAMES[base.toLowerCase().split('.')[0]];
492
+ if (!extension && known)
493
+ return { ...known, risky: !!known.risky };
494
+ if (base.startsWith('.') && KNOWN_NAMES[base.toLowerCase()])
495
+ return { ...KNOWN_NAMES[base.toLowerCase()], risky: false };
496
+ const entry = EXTENSIONS[extension];
497
+ if (entry)
498
+ return { ...entry, risky: !!entry.risky };
499
+ if (known)
500
+ return { ...known, risky: !!known.risky };
501
+ return null;
502
+ }
503
+ /**
504
+ * Tipo do arquivo. A primeira regra que decide vence:
505
+ *
506
+ * 1. MIME declarado específico decide a família (`video/*`, `audio/*`, `image/*`, PDF, JSON, Markdown, CSV/TSV,
507
+ * compactados, manifestos HLS/DASH, WebVTT, marcação).
508
+ * 2. MIME genérico ou ausente: a extensão (ou um nome conhecido, como `Dockerfile`).
509
+ * 3. Assinatura (com `head`): confirma ou corrige. Marcação ativa (`<svg`, `<html`, `<?xml`) achada em arquivo
510
+ * declarado de outra família vira `code` com `risky: true`: o conteúdo é mostrado como fonte, nunca renderizado.
511
+ * Um formato binário reconhecido corrige o MIME (um `.png` que é JPEG continua imagem, com o MIME certo).
512
+ * 4. Sem nada acima e com `head` que parece texto: `text`.
513
+ * 5. Senão, `unsupported`.
514
+ */
515
+ export function detectFileKind(input) {
516
+ const { mime: declaredMime, charset } = parseMime(input.mime);
517
+ const { base, extension, previous } = fileNameParts(input.name);
518
+ const innerFormat = COMPRESSORS.has(extension) && previous && EXTENSIONS[previous] ? previous.toUpperCase() : undefined;
519
+ const charsetPart = charset ? { charset } : {};
520
+ const innerPart = innerFormat ? { innerFormat } : {};
521
+ let result = null;
522
+ if (!GENERIC_MIMES.has(declaredMime)) {
523
+ const declared = fromDeclared(declaredMime, extension);
524
+ if (declared)
525
+ result = { ...declared, ...charsetPart, ...innerPart, confidence: 'declared', format: formatFor(declared.mime, extension) };
526
+ }
527
+ if (!result) {
528
+ const byExtension = fromExtension(base, extension);
529
+ if (byExtension) {
530
+ const { kind, mime, language, risky, streaming } = byExtension;
531
+ result = {
532
+ kind,
533
+ mime,
534
+ risky,
535
+ ...(language ? { language } : {}),
536
+ ...(streaming ? { streaming } : {}),
537
+ ...charsetPart,
538
+ ...innerPart,
539
+ confidence: 'extension',
540
+ format: formatFor(mime, extension),
541
+ };
542
+ }
543
+ }
544
+ // Manifesto de transmissão é texto (ou XML) por natureza: não há assinatura binária a confirmar.
545
+ if (result?.streaming)
546
+ return result;
547
+ const head = bytesOf(input.head);
548
+ const signature = head ? sniffSignature(head) : null;
549
+ if (signature) {
550
+ if (!result)
551
+ return { ...signature, risky: !!signature.risky, ...charsetPart, confidence: 'signature' };
552
+ if (signature.risky) {
553
+ // Marcação ativa: só fica como está se já for mostrada com segurança (código arriscado ou SVG por <img>).
554
+ const safeAlready = (result.kind === 'code' && result.risky) || (result.kind === 'image' && result.mime === 'image/svg+xml');
555
+ if (!safeAlready)
556
+ return { ...signature, risky: true, ...charsetPart, confidence: 'signature' };
557
+ return { ...result, confidence: 'signature' };
558
+ }
559
+ if (signature.kind === result.kind) {
560
+ // Mesma família: confirma. Contêiner de áudio e vídeo é o mesmo (WebM, MP4, Ogg): o MIME declarado continua.
561
+ const mime = result.confidence === 'declared' ? result.mime : signature.mime;
562
+ return { ...result, mime, confidence: 'signature', format: result.format || signature.format };
563
+ }
564
+ const sameContainer = (result.kind === 'audio' && signature.kind === 'video') || (result.kind === 'video' && signature.kind === 'audio');
565
+ if (sameContainer)
566
+ return { ...result, confidence: 'signature' };
567
+ if (signature.mime === 'application/zip' && ZIP_BASED.has(extension))
568
+ return { ...result, confidence: 'signature' };
569
+ // Formato binário reconhecido que contradiz o declarado: os bytes vencem (nenhum deles executa script).
570
+ return { ...signature, risky: false, ...charsetPart, confidence: 'signature' };
571
+ }
572
+ if (result)
573
+ return result;
574
+ if (head && looksLikeText(head)) {
575
+ return { kind: 'text', mime: 'text/plain', language: 'text', risky: false, ...charsetPart, confidence: 'signature', format: formatFor('text/plain', extension) };
576
+ }
577
+ return {
578
+ kind: 'unsupported',
579
+ mime: declaredMime || 'application/octet-stream',
580
+ risky: false,
581
+ ...charsetPart,
582
+ confidence: declaredMime && !GENERIC_MIMES.has(declaredMime) ? 'declared' : 'extension',
583
+ format: formatFor(declaredMime, extension),
584
+ };
585
+ }
586
+ /**
587
+ * A detecção precisa dos primeiros bytes? Só quando o tipo declarado é genérico (ou ausente): com um MIME específico
588
+ * a família já está decidida e o visualizador poupa o pedido. Manifesto de transmissão nunca precisa.
589
+ */
590
+ export function needsSignature(input) {
591
+ const { mime } = parseMime(input.mime);
592
+ if (!GENERIC_MIMES.has(mime))
593
+ return false;
594
+ const { base, extension } = fileNameParts(input.name);
595
+ return !fromExtension(base, extension)?.streaming;
596
+ }
597
+ //# sourceMappingURL=detect.js.map