Public: anyone can read this; the crew can change it.

An M3U playlist plays as a numbered list of its tracks with durations #16540

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16026-an-m3u-playlist-plays-as-a-numbered-list → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/16026-an-m3u-playlist-plays-as-a-numbered-list was merged into main as dd6f251.

Review

Sign in to review this change.
15 files changed +318 −2
docs/examples/mix.m3u8 added +9
@@ -0,0 +1,9 @@
1 #EXTM3U
2 #EXTINF:215,Morning Light
3 tracks/morning-light.mp3
4 #EXTINF:187.5,Low Tide
5 tracks/low-tide.mp3
6 #EXTINF:-1,Live stream
7 https://radio.example.org/stream.mp3
8 #EXTINF:3601,Long Set
9 tracks/long-set.mp3
docs/features/file-kinds.md +1
@@ -49,6 +49,7 @@ The forge draws a file on its page when its kind is below and it is within the s
4949 - **Calendar**, drawn up to 5 MB: `.ics`
5050 - **OpenTimelineIO**, drawn up to 1 MB: `.otio`
5151 - **Edit list**, drawn up to 1 MB: `.edl`
52 - **Playlist**, drawn up to 1 MB: `.m3u`, `.m3u8`
5253 - **Final Cut XML**, drawn up to 1 MB: `.fcpxml`
5354 - **Kdenlive project**, drawn up to 1 MB: `.kdenlive`
5455 - **Contacts**, drawn up to 1 MB: `.vcf`, `.vcard`
docs/features/playlist.md added +16
@@ -0,0 +1,16 @@
1 ---
2 topic: Files in the browser
3 row: Playlists (.m3u, .m3u8) as a numbered track list
4 ---
5 # Playlists as a track list
6
7 Open a `.m3u` or `.m3u8` file in a repository's file view and read it as a numbered list: title, length and the path as written, with the total length.
8
9 - A track whose relative path is a file in the same repository links to its blob. A remote URL, an absolute path or a drive path is shown as text and never fetched.
10 - Tracks with no stated length (`#EXTINF:-1`, or no `#EXTINF`) show a dash and are not counted in the total; the page says how many.
11 - At most 2,000 tracks are drawn; the rest are counted and left to the raw file. **1 MB is the render cap**: a larger file shows its source.
12 - A file with no tracks keeps its source, with the reason above it.
13 - The terminal workspace opens the same file as a table: number, title, length and path, with a Total row last (`src/tui/screens/workspace_playlist.ts`). A refusal shows as a toast and the source stays.
14 - The MCP `read_file` tool answers the same facts for a playlist as `about: {kind: "playlist", tracks, seconds, unknownLengths}`.
15
16 Try it: open `docs/examples/mix.m3u8` in this repository's file view.
scripts/kinds-guide.ts +1 −1
@@ -13,7 +13,7 @@ export const NAMES: Readonly<Record<FileKind, string>> = {
1313 sqlite: "SQLite database", parquet: "Parquet", pcap: "Packet capture", torrent: "Torrent (BitTorrent metainfo)", pcd: "Point cloud (PCD)", midi: "MIDI file", model3d: "3D model", archive: "Archive", sheet: "Spreadsheet", document: "Word document",
1414 slides: "Slides", layers: "Layered image", font: "Font", psd: "Photoshop", xcf: "GIMP", cad: "CAD or 3D source (header facts)", cert: "PEM certificate", sbom: "Bill of materials (CycloneDX, SPDX)", wasm: "WebAssembly module", config: "Config", markdown: "Markdown",
1515 notebook: "Notebook", patch: "Patch", log: "Log", subtitles: "Subtitles", gpx: "GPS track", har: "HTTP archive",
16 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
16 geojson: "GeoJSON", kml: "KML", calendar: "Calendar", otio: "OpenTimelineIO", edl: "Edit list", playlist: "Playlist", fcpxml: "Final Cut XML", kdenlive: "Kdenlive project",
1717 contacts: "Contacts", mail: "Email", gcode: "G-code", dxf: "DXF drawing", gerber: "Gerber layer", kicad: "KiCad board", mermaid: "Mermaid diagram", drawio: "draw.io diagram",
1818 excalidraw: "Excalidraw", step: "STEP model", iges: "IGES drawing", ifc: "IFC building model", prproj: "Premiere project", sarif: "SARIF report", lcov: "Coverage (lcov)", junit: "JUnit report",
1919 opml: "OPML", feed: "RSS or Atom feed", env: "Env example", openapi: "OpenAPI", package: "package.json", manifest: "Dependency manifest", makefile: "Makefile",
src/http/mcp/tools/read_file.ts +3 −1
@@ -13,12 +13,13 @@ import { aboutTorrent } from "../../../web/render/torrent.ts";
1313 import { aboutPcd } from "../../../web/render/pcd.ts";
1414 import { describeMedia } from "../../../text/mp4.ts";
1515 import { readXcf } from "../../../web/render/xcf-read.ts";
16 import { aboutM3u } from "../../../web/render/m3u.ts";
1617 import { aboutTfstate } from "../../../web/render/tfstate.ts";
1718 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1819
1920 export const tool: Tool = {
2021 name: "read_file",
21 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}; .torrent {name, size, infoHash, trackers, files}",
22 doc: "`{ repo, path, ref? }`: a file (utf-8 or base64) or a directory listing at a ref, as GET …/contents; MP4/MOV/M4A files also carry about: {kind, seconds, width?, height?, says}, a .pcd {kind: pcd, points, width, height, data, fields, bounds?, says}; .mid {bpm, tracks}; .ifc {says}; .torrent {name, size, infoHash, trackers, files}; .m3u {tracks, seconds}",
2223 description:
2324 "No shell? Read a file or list a directory at a ref (default branch); over 5 MB: tooLarge.",
2425 inputSchema: {
@@ -97,6 +98,7 @@ function aboutFile(path: string, body: Uint8Array, text: string | undefined): Re
9798 if (/\.pcd$/i.test(path)) return aboutPcd(body);
9899 if (/\.xcf$/i.test(path)) return aboutXcf(body);
99100 if (text !== undefined && /\.tfstate$/i.test(path)) return aboutTfstate(text);
101 if (text !== undefined && /\.m3u8?$/i.test(path) && body.length <= RENDER_CAP.playlist) return aboutM3u(text);
100102 const media = describeMedia(path, body);
101103 if (media) return media;
102104 if (text === undefined) return undefined;
src/tui/screens/workspace.ts +6
@@ -104,6 +104,7 @@ import { officeView } from "./workspace_office.ts";
104104 import { parquetView } from "./workspace_parquet.ts";
105105 import { bibView } from "./workspace_bib.ts";
106106 import { tfstateView } from "./workspace_tfstate.ts";
107 import { playlistView } from "./workspace_playlist.ts";
107108 import { factsView } from "./workspace_facts.ts";
108109 import { depsView } from "./workspace_deps.ts";
109110 import { cadView } from "./workspace_cad.ts";
@@ -1654,6 +1655,11 @@ export function workspaceScreen(
16541655 }
16551656 const deps = depsView(t.path, read.value.body);
16561657 if (deps !== null && read.value.partial !== true) sheet = deps;
1658 // A playlist opens as its numbered tracks; a refusal is said as a toast and the source
1659 // stays.
1660 const list = read.value.partial === true ? null : playlistView(t.path, read.value.body);
1661 if (list !== null && typeof list !== "string") sheet = list;
1662 else if (typeof list === "string") cut = list;
16571663 // A big JSON file arrives cut: its first level is drawn, as the page draws it.
16581664 if (read.value.partial === true && isJsonPath(t.path)) {
16591665 raw = new TextEncoder().encode(jsonOutlineText(read.value.body, read.value.size, downloadAt(t.path)));
src/tui/screens/workspace_playlist.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * A playlist (`.m3u`, `.m3u8`) in the terminal workspace, read the way the page reads it: the
3 * same `parseM3u`, drawn as a numbered table of title, length and path with the total last.
4 * Same gate and cap as the page (`fileKind`, `RENDER_CAP.playlist`, `TRACK_CAP` rows). Nothing
5 * is fetched or linked; a path is only text, with control characters dropped.
6 *
7 * `playlistView(path, body)` answers a table, a sentence (shown above the source), or `null`
8 * for a file that is not a playlist.
9 */
10
11 import { fileKind, HEAD_BYTES, RENDER_CAP } from "../../web/render/kinds.ts";
12 import { parseM3u, TRACK_CAP } from "../../web/render/m3u.ts";
13 import { clock } from "../../text/mp4.ts";
14 import type { Table } from "../../text/csv.ts";
15
16 const plain = (s: string): string => s.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
17
18 export function playlistView(path: string, body: Uint8Array): Table | string | null {
19 if (fileKind(path, body.subarray(0, HEAD_BYTES)) !== "playlist") return null;
20 if (body.length > RENDER_CAP.playlist)
21 return `This file is over ${RENDER_CAP.playlist / 1_000_000} MB, too large to open here. Download it instead.`;
22 const p = parseM3u(new TextDecoder().decode(body));
23 if ("error" in p) return `This file is not drawn as a playlist: ${p.error}.`;
24 const header = ["#", "Title", "Length", "Path"];
25 const rows = p.tracks
26 .slice(0, TRACK_CAP)
27 .map((t, i) => [String(i + 1), plain(t.title), t.seconds === undefined ? "-" : clock(Math.round(t.seconds)), plain(t.path)]);
28 const unknown = p.unknown > 0 ? ` (${p.unknown} with no length, not counted)` : "";
29 rows.push(["", "Total", clock(Math.round(p.seconds)), `${p.tracks.length} ${p.tracks.length === 1 ? "track" : "tracks"}${unknown}`]);
30 return { header, rows, more: Math.max(0, p.tracks.length - TRACK_CAP), delimiter: ",", columns: header.length };
31 }
src/web/render/kinds.ts +5
@@ -61,6 +61,7 @@ export type FileKind =
6161 | "calendar"
6262 | "otio"
6363 | "edl"
64 | "playlist"
6465 | "fcpxml"
6566 | "kdenlive"
6667 | "contacts"
@@ -174,6 +175,8 @@ export const RENDER_CAP: Readonly<Record<FileKind, number>> = {
174175 // not drawn.
175176 otio: 1 * MB,
176177 edl: 1 * MB,
178 // A playlist is read whole and draws at most 2,000 rows; over 1 MB the source is kept.
179 playlist: 1 * MB,
177180 fcpxml: 1 * MB,
178181 kdenlive: 1 * MB,
179182 contacts: 1 * MB,
@@ -343,6 +346,8 @@ const TEXTUAL: Readonly<Record<string, FileKind>> = {
343346 ics: "calendar",
344347 otio: "otio",
345348 edl: "edl",
349 m3u: "playlist",
350 m3u8: "playlist",
346351 fcpxml: "fcpxml",
347352 kdenlive: "kdenlive",
348353 vcf: "contacts",
src/web/render/m3u.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * A playlist (`.m3u`, `.m3u8`) as a numbered track list: title, duration and
3 * the path as written, with the total length. A track whose relative path is a
4 * file in the same repository links to its blob; a remote URL, an absolute or
5 * a Windows path is shown as text and never fetched. `#EXTINF:<seconds>[ attrs],<title>`
6 * names the next entry; `-1` or a missing length is unknown and left out of the
7 * total. Other `#` lines (`#EXTM3U`, `#EXTGRP`, HLS tags) are ignored. The body is
8 * bounded by the render cap before this reads it, and at most `TRACK_CAP` rows draw.
9 * A file with no entries keeps its source.
10 */
11
12 import { escapeHtml, html, raw } from "../html.ts";
13 import { clock as wholeClock } from "../../text/mp4.ts";
14 import { fileSize } from "../ui.ts";
15 import type { Rendered, RenderInput } from "./renderers.ts";
16
17 /** Rows drawn, whatever the file holds. */
18 /** `m:ss` or `h:mm:ss`, to the nearest second; the one clock is `text/mp4.ts`. */
19 const clock = (seconds: number): string => wholeClock(Math.round(seconds));

Non-blocking: this doc comment describes TRACK_CAP, but it sits above clock. Move it down to the constant.

20
21 export const TRACK_CAP = 2_000;
22
23 export interface Track {
24 readonly title: string;
25 /** Seconds, when the file states a length. */
26 readonly seconds?: number;
27 readonly path: string;
28 }
29 export interface Playlist {
30 readonly tracks: Track[];
31 /** Sum of the stated lengths. */
32 readonly seconds: number;
33 /** Tracks with no stated length. */
34 readonly unknown: number;
35 }
36 export type Parsed = Playlist | { readonly error: string };
37
38 const EXTINF = /^#EXTINF:\s*(-?\d+(?:\.\d+)?)([^,]*),?(.*)$/i;
39
40 export function parseM3u(text: string): Parsed {
41 const tracks: Track[] = [];
42 let seconds = 0;
43 let unknown = 0;
44 let pending: { title: string; seconds: number | undefined } | undefined;
45 for (const raw of text.replace(/^/, "").split(/\r\n|\n|\r/)) {
46 const line = raw.trim();
47 if (line === "") continue;
48 if (line.startsWith("#")) {
49 const m = EXTINF.exec(line);
50 if (m) {
51 const n = Number(m[1]);
52 pending = { title: m[3]!.trim(), seconds: n >= 0 && n < 1e7 ? n : undefined };
53 }
54 continue;
55 }
56 const title = pending?.title || line.slice(line.lastIndexOf("/") + 1) || line;
57 const s = pending?.seconds;
58 tracks.push({ title, path: line, ...(s === undefined ? {} : { seconds: s }) });
59 if (s === undefined) unknown++;
60 else seconds += s;
61 pending = undefined;
62 }
63 if (tracks.length === 0) return { error: "it lists no tracks" };
64 return { tracks, seconds, unknown };
65 }
66
67 /**
68 * A path in the playlist's folder resolved to a repository path, or undefined for a remote URL,
69 * an absolute or drive path, or one that climbs out of the repository.
70 */
71 export function resolveTrack(playlist: string, written: string): string | undefined {
72 if (/^[a-z][a-z0-9+.-]*:/i.test(written) || written.startsWith("/") || written.startsWith("\\")) return undefined;
73 if (written.length > 4096 || /[\x00-\x1f\x7f?#]/.test(written)) return undefined;
74 const dir = playlist.split("/").slice(0, -1);
75 for (const part of written.replaceAll("\\", "/").split("/")) {
76 if (part === "" || part === ".") continue;
77 if (part === "..") {
78 if (dir.length === 0) return undefined;
79 dir.pop();
80 } else dir.push(part);
81 }
82 return dir.length === 0 ? undefined : dir.join("/");
83 }
84
85 const encodePath = (path: string): string => path.split("/").map(encodeURIComponent).join("/");
86
87 /**
88 * The repository path a track names when it is a file at the ref, as written or percent-decoded.
89 */
90 function localFile(input: RenderInput, written: string): string | undefined {
91 if (input.repo === undefined || input.exists === undefined) return undefined;
92 let decoded = written;
93 try {
94 decoded = decodeURIComponent(written);
95 } catch {
96 // keep as written
97 }
98 for (const w of decoded === written ? [written] : [written, decoded]) {
99 const p = resolveTrack(input.path, w);
100 if (p !== undefined && input.exists(p)) return p;
101 }
102 return undefined;
103 }
104
105 /** The facts the terminal and the MCP file tool read: counts and length, never the tracks. */
106 export function aboutM3u(text: string): Record<string, unknown> {
107 const p = parseM3u(text);
108 if ("error" in p) return { kind: "playlist", says: `Playlist, unreadable: ${p.error}` };
109 return {
110 kind: "playlist",
111 tracks: p.tracks.length,
112 seconds: Math.round(p.seconds),
113 unknownLengths: p.unknown,
114 says: `Playlist, ${p.tracks.length} tracks, ${clock(p.seconds)}`,
115 };
116 }
117
118 export function m3u(input: RenderInput): Rendered {
119 const p = parseM3u(new TextDecoder().decode(input.body));
120 if ("error" in p) return { content: html``, lines: 0, fallback: `This file is not drawn as a playlist: ${p.error}.` };
121 const shown = p.tracks.slice(0, TRACK_CAP);
122 let rows = "";
123 shown.forEach((t, i) => {
124 const file = localFile(input, t.path);
125 const where =
126 file !== undefined && input.repo !== undefined
127 ? `<a href="${escapeHtml(`${input.repo.base}/blob/${input.repo.ref}/${encodePath(file)}`)}">${escapeHtml(t.path)}</a>`
128 : escapeHtml(t.path);
129 rows += `<tr><td>${i + 1}</td><td>${escapeHtml(t.title)}</td><td>${t.seconds === undefined ? "-" : clock(t.seconds)}</td><td>${where}</td></tr>`;
130 });
131 const left = p.tracks.length - shown.length;
132 const more = left > 0 ? `<p class="muted small">Showing ${TRACK_CAP.toLocaleString()} of ${p.tracks.length.toLocaleString()} tracks. The other ${left.toLocaleString()} are in the raw file.</p>` : "";
133 const unknown = p.unknown > 0 ? ` (${p.unknown.toLocaleString()} with no length, not counted)` : "";
134 const head = `<tr><th scope="col">#</th><th scope="col">Title</th><th scope="col">Length</th><th scope="col">Path</th></tr>`;
135 const content = html`<div><p>${p.tracks.length.toLocaleString()} ${p.tracks.length === 1 ? "track" : "tracks"} · ${clock(p.seconds)} in total${unknown}</p><table class="table" data-dense aria-label="Tracks in order"><thead>${raw(head)}</thead><tbody>${raw(rows)}</tbody></table>${raw(more)}</div>`;
136 return { content, lines: 0, summary: `${p.tracks.length.toLocaleString()} ${p.tracks.length === 1 ? "track" : "tracks"} · ${clock(p.seconds)} · ${fileSize(input.size)}` };
137 }
src/web/render/renderers.ts +2
@@ -43,6 +43,7 @@ import { font } from "./font.ts";
4343 import { ics } from "./ics.ts";
4444 import { otio } from "./otio.ts";
4545 import { edl } from "./edl.ts";
46 import { m3u } from "./m3u.ts";
4647 import { fcpxml } from "./fcpxml.ts";
4748 import { kdenlive } from "./kdenlive.ts";
4849 import { junit } from "./junit.ts";
@@ -181,6 +182,7 @@ export const RENDERERS: Partial<Readonly<Record<FileKind, Renderer>>> = {
181182 calendar: ics,
182183 otio,
183184 edl,
185 playlist: m3u,
184186 fcpxml,
185187 kdenlive,
186188 contacts: vcf,
test/fuzz-renderers.test.ts +4
@@ -329,6 +329,10 @@ export const SAMPLES: Readonly<Record<string, { path: string; files: readonly st
329329 "TITLE: <b>T</b>\nFCM: NON-DROP FRAME\n\n001 AX V C 00:00:00:00 00:00:02:00 01:00:00:00 01:00:02:00\n* FROM CLIP NAME: a.mov\n",
330330 ],
331331 },
332 playlist: {
333 path: "list.m3u8",
334 files: ["#EXTM3U\n#EXTINF:12.5,<b>T</b>\nhttp://a.test/<i>x</i>.mp3\n#EXTINF:-1,B\n../a b.mp3\n"],
335 },
332336 ini: {
333337 path: "app.ini",
334338 files: ["; c\n[core]\nname = <b>x</b>\nurl=javascript:alert(1)\n[other]\nk: v\n"],
test/mcp-read-file.test.ts +12
@@ -98,6 +98,10 @@ beforeAll(async () => {
9898 files: [{ path: "infra/terraform.tfstate", content: JSON.stringify({ version: 4, serial: 2, resources: [{ mode: "managed", type: "aws_db_instance", name: "db", provider: "aws", instances: [{ attributes: { id: "db-1", password: "hunter2" } }] }] }) }],
9999 }),
100100 );
101 ok(await commitToBranch(app, owner, pub, { message: "lists", files: [
102 { path: "mix.m3u", content: "#EXTM3U\n#EXTINF:61,One\na.mp3\nb.mp3\n" },
103 { path: "big.m3u", content: "#EXTINF:1,x\na.mp3\n".padEnd(1_000_001, "\n") },
104 ] }));
101105 tok["owner"] = createToken(app.db, owner.id, "o", "ro").token;
102106 tok["stranger"] = createToken(app.db, stranger.id, "s", "ro").token;
103107 }, 30_000);
@@ -215,3 +219,11 @@ test("a .tfstate file carries about with its secrets masked", async () => {
215219 expect(file.about.total).toBe(1);
216220 expect(file.about.resources[0].attributes).toEqual({ id: "db-1", password: "••••••" });
217221 });
222
223 test("a .m3u carries about with its counts; one over the render cap carries none", async () => {
224 const file = (await read(tok["stranger"]!, { repo: "ada/pub", path: "mix.m3u" })).value;
225 expect(file.about).toMatchObject({ kind: "playlist", tracks: 2, seconds: 61, unknownLengths: 1, says: "Playlist, 2 tracks, 1:01" });
226 const big = (await read(tok["stranger"]!, { repo: "ada/pub", path: "big.m3u" })).value;
227 expect(big.size).toBeGreaterThan(1_000_000);
228 expect(big.about).toBeUndefined();
229 });
test/playlist-tui.test.ts added +22
@@ -0,0 +1,22 @@
1 import { expect, test } from "bun:test";
2 import { playlistView } from "../src/tui/screens/workspace_playlist.ts";
3
4 const enc = (s: string) => new TextEncoder().encode(s);
5
6 test("terminal draws numbered tracks with durations and the total last", () => {
7 const v = playlistView("mix.m3u8", enc("#EXTM3U\n#EXTINF:61,One\na.mp3\n#EXTINF:3600,Two\nb.mp3\nc.mp3\n"));
8 if (v === null || typeof v === "string") throw new Error("no table");
9 expect(v.rows).toEqual([
10 ["1", "One", "1:01", "a.mp3"],
11 ["2", "Two", "1:00:00", "b.mp3"],
12 ["3", "c.mp3", "-", "c.mp3"],
13 ["", "Total", "1:01:01", "3 tracks (1 with no length, not counted)"],
14 ]);
15 });
16
17 test("escape characters never reach the terminal; other files and empty lists are left", () => {
18 const v = playlistView("a.m3u", enc("#EXTINF:1,x\u001b[2Jy\na\u0007.mp3\n"));
19 expect(JSON.stringify(v)).not.toMatch(/\\u001b|\\u0007/);
20 expect(playlistView("a.txt", enc("a.mp3"))).toBeNull();
21 expect(playlistView("a.m3u", enc("#EXTM3U\n"))).toBe("This file is not drawn as a playlist: it lists no tracks.");
22 });
test/render-kinds.test.ts +2
@@ -102,6 +102,8 @@ const SAMPLES: Record<string, [Uint8Array, FileKind, string]> = {
102102 ics: [enc("BEGIN:VCALENDAR\nEND:VCALENDAR\n"), "calendar", "application/octet-stream"],
103103 otio: [enc('{"OTIO_SCHEMA":"Timeline.1"}'), "otio", "application/octet-stream"],
104104 edl: [enc("TITLE: a\n"), "edl", "application/octet-stream"],
105 m3u: [enc("#EXTM3U\n"), "playlist", "application/octet-stream"],
106 m3u8: [enc("#EXTM3U\n"), "playlist", "application/octet-stream"],
105107 fcpxml: [enc("<fcpxml/>"), "fcpxml", "application/octet-stream"],
106108 kdenlive: [enc("<mlt/>"), "kdenlive", "application/octet-stream"],
107109 gcode: [enc("G28\nG1 X1 E1\n"), "gcode", "application/octet-stream"],
test/render-playlist.test.ts added +67
@@ -0,0 +1,67 @@
1 /** Playlists (.m3u, .m3u8) as a numbered track list: parse, escape, cap, malformed, links. */
2 import { describe, expect, test } from "bun:test";
3 import { m3u, parseM3u, resolveTrack, TRACK_CAP, aboutM3u } from "../src/web/render/m3u.ts";
4 import { fileKind, RENDER_CAP } from "../src/web/render/kinds.ts";
5 import { playlistView } from "../src/tui/screens/workspace_playlist.ts";
6 import { RENDERERS } from "../src/web/render/renderers.ts";
7
8 const enc = (s: string): Uint8Array => new TextEncoder().encode(s);
9 const input = (text: string, extra = {}) => ({
10 path: "music/mix.m3u8", size: text.length, body: enc(text), media: "/m", download: "/d",
11 repo: { base: "/o/r", ref: "main" }, exists: (p: string) => p === "music/a b.mp3" || p === "x.mp3", ...extra,
12 });
13
14 describe("playlist", () => {
15 test("registered by extension", () => {
16 expect(fileKind("a/x.M3U", enc("#EXTM3U\n"))).toBe("playlist");
17 expect(fileKind("a/x.m3u8", enc("#EXTM3U\n"))).toBe("playlist");
18 expect(RENDERERS.playlist).toBe(m3u);
19 expect(RENDER_CAP.playlist).toBe(1_000_000);
20 });
21
22 test("parse: titles, lengths, total, unknown lengths", () => {
23 const p = parseM3u("#EXTM3U\n#EXTINF:61.5,One\na.mp3\n#EXTINF:-1,Two\nb.mp3\nsub/c.mp3\n#EXTINF:30 tvg-id=\"x\",Four, Five\nd.mp3\n");
24 if ("error" in p) throw new Error(p.error);
25 expect(p.tracks.map((t) => t.title)).toEqual(["One", "Two", "c.mp3", "Four, Five"]);
26 expect(p.seconds).toBe(91.5);
27 expect(p.unknown).toBe(2);
28 const out = String(m3u(input("#EXTINF:61,One\na.mp3\n")).content);
29 expect(out).toContain("<td>1</td><td>One</td><td>1:01</td>");
30 expect(out).toContain("1 track · 1:01 in total");
31 });
32
33 test("links a same-repository file, shows remote and escaping paths as text", () => {
34 const out = String(m3u(input("#EXTINF:1,<script>alert(1)</script>\na%20b.mp3\nhttp://evil.test/<i>.mp3\n../../up.mp3\n/abs.mp3\nC:\\x.mp3\n")).content);
35 expect(out).toContain('<a href="/o/r/blob/main/music/a%20b.mp3">a%20b.mp3</a>');
36 expect(out).toContain("http://evil.test/&lt;i&gt;.mp3");
37 expect(out).not.toContain("<script>");
38 expect(out).not.toContain("<i>");
39 expect(out.match(/<a /g)?.length).toBe(1);
40 expect(resolveTrack("music/mix.m3u", "../x.mp3")).toBe("x.mp3");
41 expect(resolveTrack("mix.m3u", "../x.mp3")).toBeUndefined();
42 });
43
44 test("cap: rows are bounded and counted", () => {
45 const text = Array.from({ length: TRACK_CAP + 5 }, (_, i) => `t${i}.mp3`).join("\n");
46 const out = String(m3u(input(text)).content);
47 expect(out.match(/<tr><td>\d+<\/td>/g)?.length).toBe(TRACK_CAP);
48 expect(out).toContain("Showing 2,000 of 2,005 tracks. The other 5 are in the raw file.");
49 });
50
51 test("a file over the render cap keeps its source", () => {
52 const body = enc("#EXTINF:1,x\na.mp3\n".padEnd(RENDER_CAP.playlist + 1, "\n"));
53 expect(fileKind("big.m3u", body.subarray(0, 4096))).toBe("playlist");
54 expect(body.length).toBeGreaterThan(RENDER_CAP.playlist);
55 expect(typeof playlistView("big.m3u", body)).toBe("string");
56 });
57
58 test("malformed: no tracks keeps the source and says why", () => {
59 const r = m3u(input("#EXTM3U\n#EXTINF:1,x\n"));
60 expect(r.fallback).toBe("This file is not drawn as a playlist: it lists no tracks.");
61 });
62
63 test("about: counts for the MCP file tool", () => {
64 expect(aboutM3u("#EXTINF:10,a\na.mp3\nb.mp3\n")).toMatchObject({ kind: "playlist", tracks: 2, seconds: 10, unknownLengths: 1 });
65 expect(aboutM3u("#EXTM3U\n")).toMatchObject({ kind: "playlist", says: expect.stringContaining("unreadable") });
66 });
67 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs