@soffits/dsh-media-hub 0.15.3 → 0.15.4

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 (3) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/dist/index.js +230 -166
  3. package/package.json +2 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.15.4
4
+
5
+ - An open page's change stream now ends when the plugin is unloaded or updated, so the page reconnects to the new version; before, it stayed open and heard nothing more until reloaded.
6
+ - The locale reader, the change notices and the event stream come from the shared `@soffits/dsh-host-kit` (bundled into `dist/`) instead of copies kept here.
7
+
3
8
  ## 0.15.3
4
9
 
5
10
  - A saved show whose folder is no longer one of the library folders no longer keeps the hub from starting (every page said "starting"); it is left alone.
package/dist/index.js CHANGED
@@ -8972,6 +8972,156 @@ var require_build = __commonJS({
8972
8972
  // index.js
8973
8973
  import { join as join18, resolve as resolve7 } from "node:path";
8974
8974
 
8975
+ // node_modules/@soffits/dsh-host-kit/src/locales.js
8976
+ import { readdir, readFile } from "node:fs/promises";
8977
+ import { join } from "node:path";
8978
+ var BASE = "en";
8979
+ var TAG = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$/;
8980
+ async function readLocales(dir, { warn = () => {
8981
+ } } = {}) {
8982
+ const locales = {};
8983
+ for (const name2 of (await readdir(dir)).filter((file) => file.endsWith(".json")).sort()) {
8984
+ const tag = name2.slice(0, -".json".length);
8985
+ if (!TAG.test(tag)) {
8986
+ warn(`locale/${name2}: the name is not a language tag; skipped`);
8987
+ continue;
8988
+ }
8989
+ try {
8990
+ const { ui } = JSON.parse(await readFile(join(dir, name2), "utf8"));
8991
+ if (ui === null || typeof ui !== "object" || Array.isArray(ui)) throw new Error('no "ui" table');
8992
+ locales[tag] = Object.fromEntries(Object.entries(ui).filter(([, text3]) => typeof text3 === "string"));
8993
+ } catch (error) {
8994
+ warn(`locale/${name2}: ${error.message}; skipped`);
8995
+ }
8996
+ }
8997
+ if (locales[BASE] === void 0) warn(`locale/${BASE}.json is missing or unreadable; every language falls back to it`);
8998
+ return locales;
8999
+ }
9000
+
9001
+ // node_modules/@soffits/dsh-host-kit/src/notices.js
9002
+ function createNotices({ settleMs = 0, spacingMs = 0 } = {}) {
9003
+ const listeners = /* @__PURE__ */ new Set();
9004
+ let pending = [];
9005
+ let timer;
9006
+ let lastAt = -Infinity;
9007
+ function flush() {
9008
+ timer = void 0;
9009
+ lastAt = Date.now();
9010
+ const batch = pending;
9011
+ pending = [];
9012
+ for (const listener of [...listeners]) {
9013
+ const what = /* @__PURE__ */ new Set();
9014
+ for (const notice of batch) {
9015
+ if (notice.scope === void 0 || listener.accepts === void 0 || listener.accepts(notice.scope)) what.add(notice.what);
9016
+ }
9017
+ if (what.size > 0) listener.send([...what]);
9018
+ }
9019
+ }
9020
+ return {
9021
+ /**
9022
+ * Something of kind `what` changed, for `scope` (omit for everyone).
9023
+ * @param {string} what
9024
+ * @param {string} [scope]
9025
+ */
9026
+ notify(what, scope) {
9027
+ pending.push({ what, scope });
9028
+ if (timer !== void 0) return;
9029
+ timer = setTimeout(flush, Math.max(settleMs, lastAt + spacingMs - Date.now()));
9030
+ },
9031
+ /**
9032
+ * Hear batches of kinds (`send(['library', 'rooms'])`), only for the scopes `accepts` takes
9033
+ * (omit it to hear every scope).
9034
+ * @param {(what: string[]) => void} send
9035
+ * @param {(scope: string) => boolean} [accepts]
9036
+ * @returns {() => void} stop listening
9037
+ */
9038
+ listen(send, accepts) {
9039
+ const listener = { send, accepts };
9040
+ listeners.add(listener);
9041
+ return () => listeners.delete(listener);
9042
+ },
9043
+ /** Drop every listener and anything pending (the plugin is going away). */
9044
+ close() {
9045
+ clearTimeout(timer);
9046
+ timer = void 0;
9047
+ pending = [];
9048
+ listeners.clear();
9049
+ }
9050
+ };
9051
+ }
9052
+
9053
+ // node_modules/@soffits/dsh-host-kit/src/event-streams.js
9054
+ function createEventStreams({ heartbeatMs = 25e3, headers = {} } = {}) {
9055
+ const open4 = /* @__PURE__ */ new Set();
9056
+ function respond(request, start) {
9057
+ const encoder = new TextEncoder();
9058
+ let finish = () => {
9059
+ };
9060
+ const body2 = new ReadableStream({
9061
+ async start(controller) {
9062
+ let live = true;
9063
+ let stop = () => {
9064
+ };
9065
+ const write2 = (text3) => {
9066
+ if (!live) return;
9067
+ try {
9068
+ controller.enqueue(encoder.encode(text3));
9069
+ } catch {
9070
+ end();
9071
+ }
9072
+ };
9073
+ const beat = setInterval(() => write2(": beat\n\n"), heartbeatMs);
9074
+ finish = () => {
9075
+ if (!live) return;
9076
+ live = false;
9077
+ clearInterval(beat);
9078
+ open4.delete(end);
9079
+ request.signal?.removeEventListener?.("abort", end);
9080
+ stop();
9081
+ };
9082
+ const end = () => {
9083
+ finish();
9084
+ try {
9085
+ controller.close();
9086
+ } catch {
9087
+ }
9088
+ };
9089
+ open4.add(end);
9090
+ request.signal?.addEventListener?.("abort", end, { once: true });
9091
+ if (request.signal?.aborted) return end();
9092
+ write2("retry: 5000\n: open\n\n");
9093
+ let stopping;
9094
+ try {
9095
+ stopping = await start({ send: (value) => write2(`data: ${JSON.stringify(value)}
9096
+
9097
+ `), end });
9098
+ } catch (error) {
9099
+ finish();
9100
+ controller.error(error);
9101
+ return;
9102
+ }
9103
+ if (typeof stopping !== "function") return;
9104
+ if (live) stop = stopping;
9105
+ else stopping();
9106
+ },
9107
+ cancel() {
9108
+ finish();
9109
+ }
9110
+ });
9111
+ return new Response(body2, {
9112
+ status: 200,
9113
+ headers: { ...headers, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no", "x-content-type-options": "nosniff" }
9114
+ });
9115
+ }
9116
+ return {
9117
+ respond,
9118
+ /** End every open stream (the plugin is going away). */
9119
+ close() {
9120
+ for (const end of [...open4]) end();
9121
+ }
9122
+ };
9123
+ }
9124
+
8975
9125
  // node_modules/ws/wrapper.mjs
8976
9126
  var import_stream = __toESM(require_stream(), 1);
8977
9127
  var import_extension = __toESM(require_extension(), 1);
@@ -8985,7 +9135,7 @@ var import_websocket_server = __toESM(require_websocket_server(), 1);
8985
9135
  // src/config.js
8986
9136
  import { existsSync } from "node:fs";
8987
9137
  import { homedir } from "node:os";
8988
- import { join as join9 } from "node:path";
9138
+ import { join as join10 } from "node:path";
8989
9139
 
8990
9140
  // node_modules/@deepseek-ai/cosmokit/lib/index.js
8991
9141
  function isNullable(value) {
@@ -10458,7 +10608,7 @@ function omit2(obj, ...keys) {
10458
10608
  }
10459
10609
 
10460
10610
  // src/hosts.js
10461
- import { readFile, stat } from "node:fs/promises";
10611
+ import { readFile as readFile2, stat } from "node:fs/promises";
10462
10612
  function hostOf(url) {
10463
10613
  try {
10464
10614
  return new URL(url).hostname.toLowerCase().replace(/\.$/, "");
@@ -10474,7 +10624,7 @@ function hostMatches(host, pattern2) {
10474
10624
  return host === pattern2 || host.endsWith(`.${pattern2}`);
10475
10625
  }
10476
10626
  function createHostRules(rules = [], io = {}) {
10477
- const read = io.read ?? ((path) => readFile(path, "utf8"));
10627
+ const read = io.read ?? ((path) => readFile2(path, "utf8"));
10478
10628
  const version = io.version ?? (async (path) => (await stat(path)).mtimeMs);
10479
10629
  const files = /* @__PURE__ */ new Map();
10480
10630
  async function patternsOf(rule) {
@@ -10591,21 +10741,20 @@ function createProxies(rules = [], io = {}) {
10591
10741
 
10592
10742
  // src/sources/command.js
10593
10743
  import { mkdir, rm, stat as stat2 } from "node:fs/promises";
10594
- import { basename as basename2, join as join2 } from "node:path";
10744
+ import { basename as basename2, join as join3 } from "node:path";
10595
10745
 
10596
10746
  // src/i18n.js
10597
- var BASE = "en";
10598
- var TAG = /^[a-z]{2,3}(-[a-z0-9]{2,8})*$/i;
10599
- function chain(tag) {
10747
+ var BASE2 = "en";
10748
+ function chain2(tag) {
10600
10749
  const parts = String(tag ?? "").toLowerCase().split("-").filter(Boolean);
10601
10750
  const tags = parts.map((_, i) => parts.slice(0, parts.length - i).join("-"));
10602
- return tags.includes(BASE) ? tags : [...tags, BASE];
10751
+ return tags.includes(BASE2) ? tags : [...tags, BASE2];
10603
10752
  }
10604
10753
  function pick2(value, tag) {
10605
10754
  if (typeof value === "string") return value;
10606
10755
  if (value === null || typeof value !== "object") return "";
10607
10756
  const byTag = new Map(Object.entries(value).map(([key, text3]) => [key.toLowerCase(), text3]));
10608
- for (const candidate of chain(tag)) {
10757
+ for (const candidate of chain2(tag)) {
10609
10758
  const text3 = byTag.get(candidate);
10610
10759
  if (typeof text3 === "string" && text3 !== "") return text3;
10611
10760
  }
@@ -10656,10 +10805,10 @@ function sha256Of(path) {
10656
10805
  // src/sources/process.js
10657
10806
  import { spawn } from "node:child_process";
10658
10807
  import { access, constants } from "node:fs/promises";
10659
- import { delimiter, isAbsolute, join } from "node:path";
10808
+ import { delimiter, isAbsolute, join as join2 } from "node:path";
10660
10809
  var MAX_OUTPUT = 16 * 1024 * 1024;
10661
10810
  async function commandExists(command, path = process.env.PATH ?? "") {
10662
- const candidates = isAbsolute(command) ? [command] : path.split(delimiter).filter(Boolean).map((dir) => join(dir, command));
10811
+ const candidates = isAbsolute(command) ? [command] : path.split(delimiter).filter(Boolean).map((dir) => join2(dir, command));
10663
10812
  for (const candidate of candidates) {
10664
10813
  try {
10665
10814
  await access(candidate, constants.X_OK);
@@ -10863,7 +11012,7 @@ function parseComments(document2) {
10863
11012
  async function verify(dir, event, label, logger) {
10864
11013
  const name2 = typeof event.name === "string" ? event.name : "";
10865
11014
  if (name2 === "" || basename2(name2) !== name2 || name2.startsWith(".")) return { ok: false, name: name2 };
10866
- const path = join2(dir, name2);
11015
+ const path = join3(dir, name2);
10867
11016
  try {
10868
11017
  const intact = (await stat2(path)).size === event.bytes && (typeof event.sha256 !== "string" || await sha256Of(path) === event.sha256);
10869
11018
  if (intact) return { ok: true, name: name2 };
@@ -10889,7 +11038,7 @@ function filterArgs({ language = "", format = "", yearFrom = null, yearTo = null
10889
11038
  function createCommandSource(definition, { logger, cwd }) {
10890
11039
  const { id: sourceId, label, kinds, command, env = {}, filters: understood = [] } = definition;
10891
11040
  const kindIds = new Set(kinds.map((kind) => kind.id));
10892
- const name2 = () => pick2(label, BASE) || sourceId;
11041
+ const name2 = () => pick2(label, BASE2) || sourceId;
10893
11042
  async function workDir() {
10894
11043
  await mkdir(cwd, { recursive: true });
10895
11044
  return cwd;
@@ -10977,7 +11126,7 @@ function createCommandSource(definition, { logger, cwd }) {
10977
11126
  const names = Array.isArray(event.files) ? event.files.filter((file) => typeof file === "string" && file !== "" && basename2(file) === file) : [];
10978
11127
  if (names.length === 0) return;
10979
11128
  const until = new Promise((done) => growing.set(event.number, done));
10980
- onPartial?.(event.number, { files: names.map((file) => join2(dir, file)), subtitles: [], growing: until });
11129
+ onPartial?.(event.number, { files: names.map((file) => join3(dir, file)), subtitles: [], growing: until });
10981
11130
  } else if (event?.event === "done") {
10982
11131
  if (Number.isInteger(event.number)) settle2(event.number);
10983
11132
  checking = checking.then(() => verify(dir, event, name2(), logger)).then((file) => {
@@ -11025,21 +11174,21 @@ function createCommandSource(definition, { logger, cwd }) {
11025
11174
  const event = reported[reported.length - 1];
11026
11175
  const file = await verify(dir, event, name2(), logger);
11027
11176
  if (!file.ok) throw codedError("source_failed", `${name2()}: the file did not arrive whole`);
11028
- return { name: file.name, bytes: event.bytes, sha256: typeof event.sha256 === "string" ? event.sha256 : await sha256Of(join2(dir, file.name)) };
11177
+ return { name: file.name, bytes: event.bytes, sha256: typeof event.sha256 === "string" ? event.sha256 : await sha256Of(join3(dir, file.name)) };
11029
11178
  }
11030
11179
  };
11031
11180
  }
11032
11181
 
11033
11182
  // src/sources/index.js
11034
- import { join as join8 } from "node:path";
11183
+ import { join as join9 } from "node:path";
11035
11184
 
11036
11185
  // src/sources/link.js
11037
- import { mkdir as mkdir5, readdir as readdir3, rename as rename2, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
11038
- import { dirname as dirname2, extname as extname4, join as join7 } from "node:path";
11186
+ import { mkdir as mkdir5, readdir as readdir4, rename as rename2, rm as rm5, writeFile as writeFile2 } from "node:fs/promises";
11187
+ import { dirname as dirname2, extname as extname4, join as join8 } from "node:path";
11039
11188
 
11040
11189
  // src/captions.js
11041
11190
  var MARKS = Object.freeze(["auto", "original"]);
11042
- var known = new Intl.DisplayNames([BASE], { type: "language", fallback: "none" });
11191
+ var known = new Intl.DisplayNames([BASE2], { type: "language", fallback: "none" });
11043
11192
  function captionLanguage(tag) {
11044
11193
  try {
11045
11194
  const { language } = new Intl.Locale(tag);
@@ -11107,8 +11256,8 @@ function noteFor(entry, notes, name2) {
11107
11256
  }
11108
11257
 
11109
11258
  // src/library.js
11110
- import { open, readdir, stat as stat3 } from "node:fs/promises";
11111
- import { basename as basename4, dirname, extname as extname2, join as join3 } from "node:path";
11259
+ import { open, readdir as readdir2, stat as stat3 } from "node:fs/promises";
11260
+ import { basename as basename4, dirname, extname as extname2, join as join4 } from "node:path";
11112
11261
  import { execFile } from "node:child_process";
11113
11262
  import { promisify } from "node:util";
11114
11263
  var run2 = promisify(execFile);
@@ -11142,13 +11291,13 @@ var titleOf2 = (file) => basename4(file, extname2(file));
11142
11291
  async function scanSource(path) {
11143
11292
  const info = await stat3(path);
11144
11293
  const folder = info.isDirectory() ? path : dirname(path);
11145
- const names = await readdir(folder);
11294
+ const names = await readdir2(folder);
11146
11295
  const videos = info.isDirectory() ? naturalSort(names.filter(isMedia)) : [basename4(path)];
11147
11296
  if (videos.length === 0) throw codedError("empty", `no video or audio files in ${path}`);
11148
11297
  return videos.map((name2) => ({
11149
11298
  title: titleOf2(name2),
11150
- path: join3(folder, name2),
11151
- subtitles: matchSubtitles(name2, names).map((sub) => ({ path: join3(folder, sub.name), label: sub.label }))
11299
+ path: join4(folder, name2),
11300
+ subtitles: matchSubtitles(name2, names).map((sub) => ({ path: join4(folder, sub.name), label: sub.label }))
11152
11301
  }));
11153
11302
  }
11154
11303
  async function probe(path, { ffprobe = "ffprobe" } = {}) {
@@ -11211,7 +11360,7 @@ function planVideo(path, info, { fastStart, maxHeight }) {
11211
11360
  // src/cookies.js
11212
11361
  import { randomBytes } from "node:crypto";
11213
11362
  import { copyFile, chmod, mkdir as mkdir2, rm as rm2 } from "node:fs/promises";
11214
- import { join as join4 } from "node:path";
11363
+ import { join as join5 } from "node:path";
11215
11364
  var accountView = (account) => account === null ? null : { name: account.name || account.person || "" };
11216
11365
  function createCookies(rules = [], io = {}) {
11217
11366
  const hostRules = createHostRules(rules, io);
@@ -11233,7 +11382,7 @@ function createCookies(rules = [], io = {}) {
11233
11382
  if (account === null) return { args: [], done: async () => {
11234
11383
  } };
11235
11384
  await mkdir2(dir, { recursive: true });
11236
- const copy = join4(dir, `.cookies-${randomBytes(6).toString("hex")}.txt`);
11385
+ const copy = join5(dir, `.cookies-${randomBytes(6).toString("hex")}.txt`);
11237
11386
  try {
11238
11387
  await copyFile(account.file, copy);
11239
11388
  await chmod(copy, 384);
@@ -11250,14 +11399,14 @@ function createCookies(rules = [], io = {}) {
11250
11399
  // src/prepare.js
11251
11400
  import { spawn as spawn3 } from "node:child_process";
11252
11401
  import { createHash as createHash3 } from "node:crypto";
11253
- import { mkdir as mkdir4, readFile as readFile3, readdir as readdir2, rename, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
11254
- import { extname as extname3, join as join6 } from "node:path";
11402
+ import { mkdir as mkdir4, readFile as readFile4, readdir as readdir3, rename, rm as rm4, stat as stat5, writeFile } from "node:fs/promises";
11403
+ import { extname as extname3, join as join7 } from "node:path";
11255
11404
 
11256
11405
  // src/stream.js
11257
11406
  import { spawn as spawn2 } from "node:child_process";
11258
11407
  import { createHash as createHash2 } from "node:crypto";
11259
- import { mkdir as mkdir3, open as open2, readFile as readFile2, rm as rm3, stat as stat4 } from "node:fs/promises";
11260
- import { join as join5 } from "node:path";
11408
+ import { mkdir as mkdir3, open as open2, readFile as readFile3, rm as rm3, stat as stat4 } from "node:fs/promises";
11409
+ import { join as join6 } from "node:path";
11261
11410
  import { Readable } from "node:stream";
11262
11411
  var PLAYLIST = "index.m3u8";
11263
11412
  var READY_SEGMENTS = 3;
@@ -11352,8 +11501,8 @@ function hlsArgs(plan, inputs, dir, { maxHeight = 1080, threads = 2 } = {}) {
11352
11501
  "-hls_flags",
11353
11502
  "independent_segments+temp_file",
11354
11503
  "-hls_segment_filename",
11355
- join5(dir, "%05d.m4s"),
11356
- join5(dir, PLAYLIST)
11504
+ join6(dir, "%05d.m4s"),
11505
+ join6(dir, PLAYLIST)
11357
11506
  ];
11358
11507
  }
11359
11508
  async function probeGrowing(file, ended, { ffprobe, signal }) {
@@ -11375,8 +11524,8 @@ function playable(text3) {
11375
11524
  return text3.includes("#EXT-X-ENDLIST") || (text3.match(/#EXTINF:/g) ?? []).length >= READY_SEGMENTS;
11376
11525
  }
11377
11526
  async function finishedPlaylist(dir) {
11378
- const file = join5(dir, PLAYLIST);
11379
- const text3 = await readFile2(file, "utf8").catch(() => "");
11527
+ const file = join6(dir, PLAYLIST);
11528
+ const text3 = await readFile3(file, "utf8").catch(() => "");
11380
11529
  return text3.includes("#EXT-X-ENDLIST") ? file : null;
11381
11530
  }
11382
11531
  async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe = "ffprobe", maxHeight = 1080, threads = 2, onReady, signal }) {
@@ -11390,7 +11539,7 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11390
11539
  const duration = Math.max(0, ...infos.map((info) => info.duration ?? 0)) || null;
11391
11540
  const inputs = growing === void 0 ? files : files.map((_, n) => `pipe:${n + 3}`);
11392
11541
  const args = hlsArgs(plan, inputs, dir, { maxHeight, threads });
11393
- const playlist = join5(dir, PLAYLIST);
11542
+ const playlist = join6(dir, PLAYLIST);
11394
11543
  const child = spawn2("nice", ["-n", "10", ffmpeg, "-hide_banner", "-loglevel", "error", "-nostdin", ...args], {
11395
11544
  stdio: ["ignore", "ignore", "pipe", ...growing === void 0 ? [] : files.map(() => "pipe")],
11396
11545
  signal
@@ -11416,7 +11565,7 @@ async function streamEpisode({ files, growing, dir, ffmpeg = "ffmpeg", ffprobe =
11416
11565
  const running = settledFlag(exited);
11417
11566
  let told = false;
11418
11567
  while (!running.done && !told) {
11419
- if (playable(await readFile2(playlist, "utf8").catch(() => ""))) {
11568
+ if (playable(await readFile3(playlist, "utf8").catch(() => ""))) {
11420
11569
  told = true;
11421
11570
  onReady?.({ playlist, duration });
11422
11571
  } else {
@@ -11435,7 +11584,7 @@ function createStreams({ cacheDir, tools, need, ready, lost, logger, convert })
11435
11584
  function start(key, entry) {
11436
11585
  const { show, number, partial: { files, subtitles = [], growing } } = entry;
11437
11586
  const controller = new AbortController();
11438
- const dir = join5(cacheDir, `stream-${createHash2("sha256").update(`${key}\0${Date.now()}`).digest("hex").slice(0, 20)}`);
11587
+ const dir = join6(cacheDir, `stream-${createHash2("sha256").update(`${key}\0${Date.now()}`).digest("hex").slice(0, 20)}`);
11439
11588
  entry.controller = controller;
11440
11589
  entry.prepared = null;
11441
11590
  streamEpisode({
@@ -11541,12 +11690,12 @@ async function preparedBytes(cacheDir, path) {
11541
11690
  const key = await cacheKey(path).catch(() => null);
11542
11691
  if (key === null) return 0;
11543
11692
  let total = 0;
11544
- for (const name2 of await readdir2(join6(cacheDir, key)).catch(() => [])) total += (await stat5(join6(cacheDir, key, name2)).catch(() => null))?.size ?? 0;
11693
+ for (const name2 of await readdir3(join7(cacheDir, key)).catch(() => [])) total += (await stat5(join7(cacheDir, key, name2)).catch(() => null))?.size ?? 0;
11545
11694
  return total;
11546
11695
  }
11547
11696
  async function dropPrepared(cacheDir, path) {
11548
11697
  const key = await cacheKey(path).catch(() => null);
11549
- if (key !== null) await rm4(join6(cacheDir, key), { recursive: true, force: true });
11698
+ if (key !== null) await rm4(join7(cacheDir, key), { recursive: true, force: true });
11550
11699
  }
11551
11700
  function runFfmpeg(args, { ffmpeg, duration, onProgress, signal }) {
11552
11701
  return new Promise((resolve8, reject) => {
@@ -11570,14 +11719,14 @@ async function writeAtomic(path, data) {
11570
11719
  }
11571
11720
  var exists = (path) => stat5(path).then(() => true, () => false);
11572
11721
  async function convertSubtitle(source, dir, name2, { ffmpeg = "ffmpeg" } = {}) {
11573
- const out = join6(dir, `${name2}.vtt`);
11722
+ const out = join7(dir, `${name2}.vtt`);
11574
11723
  if (await exists(out)) return out;
11575
- const text3 = decodeText(await readFile3(source));
11724
+ const text3 = decodeText(await readFile4(source));
11576
11725
  const ext = extname3(source).toLowerCase();
11577
11726
  if (ext === ".srt") await writeAtomic(out, srtToVtt(text3));
11578
11727
  else if (ext === ".vtt" || isVtt(text3)) await writeAtomic(out, text3);
11579
11728
  else {
11580
- const utf8 = join6(dir, `${name2}.utf8${ext}`);
11729
+ const utf8 = join7(dir, `${name2}.utf8${ext}`);
11581
11730
  await writeFile(utf8, text3);
11582
11731
  try {
11583
11732
  await runFfmpeg(["-y", "-i", utf8, "-f", "webvtt", `${out}.part`], { ffmpeg, duration: null });
@@ -11593,7 +11742,7 @@ async function prepareEpisode(episode, options) {
11593
11742
  if (extname3(episode.path).toLowerCase() === ".m3u8") {
11594
11743
  return { file: episode.path, kind: "hls", duration: null, plan: "direct", subtitles: await externalSubtitles(episode, null, ffmpeg, cacheDir) };
11595
11744
  }
11596
- const dir = join6(cacheDir, await cacheKey(episode.path));
11745
+ const dir = join7(cacheDir, await cacheKey(episode.path));
11597
11746
  await mkdir4(dir, { recursive: true });
11598
11747
  const info = await probe(episode.path, { ffprobe });
11599
11748
  const mp4Family = [".mp4", ".m4v", ".mov", ".m4a"].includes(extname3(episode.path).toLowerCase());
@@ -11601,7 +11750,7 @@ async function prepareEpisode(episode, options) {
11601
11750
  const subtitles = await externalSubtitles(episode, dir, ffmpeg, cacheDir);
11602
11751
  await embeddedSubtitles(episode.path, info, dir, ffmpeg, subtitles);
11603
11752
  if (plan === "transcode") {
11604
- const hls = join6(dir, "hls");
11753
+ const hls = join7(dir, "hls");
11605
11754
  const prepared = (file2) => ({ file: file2, kind: "hls", duration: info.duration, plan, subtitles });
11606
11755
  const done = await finishedPlaylist(hls);
11607
11756
  if (done !== null) return prepared(done);
@@ -11610,7 +11759,7 @@ async function prepareEpisode(episode, options) {
11610
11759
  }
11611
11760
  let file = episode.path;
11612
11761
  if (plan === "remux") {
11613
- file = join6(dir, "video.mp4");
11762
+ file = join7(dir, "video.mp4");
11614
11763
  if (!await exists(file)) {
11615
11764
  await runFfmpeg(remuxArgs(episode.path, `${file}.part`), { ffmpeg, duration: info.duration, onProgress, signal });
11616
11765
  await rename(`${file}.part`, file);
@@ -11620,7 +11769,7 @@ async function prepareEpisode(episode, options) {
11620
11769
  }
11621
11770
  async function embeddedSubtitles(path, info, dir, ffmpeg, subtitles) {
11622
11771
  for (const stream of info.subtitles.filter((s) => isTextSubtitle(s.codec))) {
11623
- const out = join6(dir, `embedded-${stream.index}.vtt`);
11772
+ const out = join7(dir, `embedded-${stream.index}.vtt`);
11624
11773
  if (!await exists(out)) {
11625
11774
  try {
11626
11775
  await runFfmpeg(["-y", "-i", path, "-map", `0:s:${stream.index}`, "-f", "webvtt", `${out}.part`], { ffmpeg, duration: null });
@@ -11634,7 +11783,7 @@ async function embeddedSubtitles(path, info, dir, ffmpeg, subtitles) {
11634
11783
  }
11635
11784
  async function externalSubtitles(episode, dir, ffmpeg, cacheDir) {
11636
11785
  if (episode.subtitles.length === 0) return [];
11637
- const target = dir ?? join6(cacheDir, await cacheKey(episode.path));
11786
+ const target = dir ?? join7(cacheDir, await cacheKey(episode.path));
11638
11787
  await mkdir4(target, { recursive: true });
11639
11788
  const out = [];
11640
11789
  for (const [n, sub] of episode.subtitles.entries()) {
@@ -11647,10 +11796,10 @@ async function externalSubtitles(episode, dir, ffmpeg, cacheDir) {
11647
11796
  }
11648
11797
  async function pruneCache(cacheDir, used, days, now = Date.now()) {
11649
11798
  const keep = new Set(used.filter((file) => typeof file === "string" && file.startsWith(`${cacheDir}/`)).map((file) => file.slice(cacheDir.length + 1).split("/")[0]));
11650
- for (const name2 of await readdir2(cacheDir).catch(() => [])) {
11799
+ for (const name2 of await readdir3(cacheDir).catch(() => [])) {
11651
11800
  if (keep.has(name2)) continue;
11652
- const info = await stat5(join6(cacheDir, name2)).catch(() => null);
11653
- if (info !== null && now - info.mtimeMs > days * 864e5) await rm4(join6(cacheDir, name2), { recursive: true, force: true });
11801
+ const info = await stat5(join7(cacheDir, name2)).catch(() => null);
11802
+ if (info !== null && now - info.mtimeMs > days * 864e5) await rm4(join7(cacheDir, name2), { recursive: true, force: true });
11654
11803
  }
11655
11804
  }
11656
11805
 
@@ -11869,26 +12018,26 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11869
12018
  async function fetchCaptions(url, { entry, load, work, dir, stem, language, person, signal }) {
11870
12019
  const chosen = chooseCaptions(entry, language);
11871
12020
  if (chosen.length === 0) return [];
11872
- const result = await ytdlp(url, ["--skip-download", ...captionArgs(chosen), "-o", join7(work, "captions")], { person, load, signal });
12021
+ const result = await ytdlp(url, ["--skip-download", ...captionArgs(chosen), "-o", join8(work, "captions")], { person, load, signal });
11873
12022
  if (result.code !== 0) logger.warn("link %s: captions: %s", url, lastLine(result.stderr));
11874
12023
  const placed = [];
11875
12024
  for (const track of chosen) {
11876
12025
  const label = captionLabel(track);
11877
- const target = join7(dir, `${stem}.${label}.vtt`);
11878
- if (await rename2(join7(work, `captions.${track.tag}.vtt`), target).then(() => true, () => false)) placed.push({ path: target, label });
12026
+ const target = join8(dir, `${stem}.${label}.vtt`);
12027
+ if (await rename2(join8(work, `captions.${track.tag}.vtt`), target).then(() => true, () => false)) placed.push({ path: target, label });
11879
12028
  }
11880
12029
  return placed;
11881
12030
  }
11882
12031
  async function assemble(files, dir, stem) {
11883
12032
  if (files.length === 1) {
11884
- const target = join7(dir, `${stem}${extname4(files[0])}`);
12033
+ const target = join8(dir, `${stem}${extname4(files[0])}`);
11885
12034
  await rename2(files[0], target);
11886
12035
  return target;
11887
12036
  }
11888
12037
  let last = null;
11889
12038
  for (const ext of MERGED) {
11890
- const target = join7(dir, `${stem}.${ext}`);
11891
- const part = join7(dirname2(files[0]), `merged.${ext}`);
12039
+ const target = join8(dir, `${stem}.${ext}`);
12040
+ const part = join8(dirname2(files[0]), `merged.${ext}`);
11892
12041
  try {
11893
12042
  await runFfmpeg(["-y", ...files.flatMap((file) => ["-i", file]), ...files.flatMap((_, n) => ["-map", String(n)]), "-c", "copy", ...ext === "mp4" ? ["-movflags", "+faststart"] : [], part], { ffmpeg, duration: null });
11894
12043
  await rename2(part, target);
@@ -11930,9 +12079,9 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11930
12079
  const failed = [];
11931
12080
  let first = null;
11932
12081
  for (let number = from2; number <= to && !signal?.aborted; number++) {
11933
- if ((await readdir3(dir)).some((name2) => isMedia(name2) && episodeNumber(name2) === number)) continue;
12082
+ if ((await readdir4(dir)).some((name2) => isMedia(name2) && episodeNumber(name2) === number)) continue;
11934
12083
  onStart?.(number);
11935
- const work = join7(dir, INCOMING, String(number));
12084
+ const work = join8(dir, INCOMING, String(number));
11936
12085
  try {
11937
12086
  await fetchEpisode(number, work);
11938
12087
  } catch (error) {
@@ -11953,7 +12102,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11953
12102
  const { data } = await lookUp(url, [...formatArgs(quality, maxHeight), "--write-subs", "--playlist-items", String(number)], { person, signal, timeoutMs: INFO_TIMEOUT_MS });
11954
12103
  const entry = data._type === "playlist" ? (data.entries ?? []).find((item) => item !== null && typeof item === "object") : data;
11955
12104
  if (entry === void 0) throw failure("not_found");
11956
- const load = join7(work, "info.json");
12105
+ const load = join8(work, "info.json");
11957
12106
  await writeFile2(load, JSON.stringify(entry));
11958
12107
  const stem = episodeStem(number, entry.title);
11959
12108
  const captions = await fetchCaptions(url, { entry, load, work, dir, stem, language, person, signal });
@@ -11967,7 +12116,7 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11967
12116
  ...quality === AUDIO ? AUDIO_FILE : [],
11968
12117
  ...PROGRESS_ARGS,
11969
12118
  "-o",
11970
- join7(work, `part${n}.%(ext)s`)
12119
+ join8(work, `part${n}.%(ext)s`)
11971
12120
  ], { person, load, signal, onStdoutLine: (line) => {
11972
12121
  const event = parseLine(line);
11973
12122
  if (event !== null) progress.event(event);
@@ -11975,12 +12124,12 @@ function createLinkSource({ ytDlp, ffmpeg = "ffmpeg", proxies, cookies, maxHeigh
11975
12124
  if (result.code === 0) progress.finished(part.format_id);
11976
12125
  return result;
11977
12126
  }));
11978
- if (quality !== AUDIO) onPartial?.(number, { files: parts.map((part, n) => join7(work, `part${n}.${part.ext}`)), subtitles: captions, growing: Promise.allSettled(runs) });
12127
+ if (quality !== AUDIO) onPartial?.(number, { files: parts.map((part, n) => join8(work, `part${n}.${part.ext}`)), subtitles: captions, growing: Promise.allSettled(runs) });
11979
12128
  const results = await Promise.all(runs);
11980
12129
  const broken = results.find((result) => result.code !== 0);
11981
12130
  if (broken !== void 0) throw await reasonOf(url, broken);
11982
- const names = (await readdir3(work)).filter((name2) => /^part\d+\./.test(name2)).sort();
11983
- await assemble(names.map((name2) => join7(work, name2)), dir, stem);
12131
+ const names = (await readdir4(work)).filter((name2) => /^part\d+\./.test(name2)).sort();
12132
+ await assemble(names.map((name2) => join8(work, name2)), dir, stem);
11984
12133
  } catch (error) {
11985
12134
  for (const caption of captions) await rm5(caption.path, { force: true });
11986
12135
  throw error;
@@ -12004,8 +12153,8 @@ function createSources(definitions, { stateDir, logger, link }) {
12004
12153
  seen.add(id);
12005
12154
  }
12006
12155
  return [
12007
- ...definitions.map((definition) => createCommandSource(definition, { logger, cwd: join8(stateDir, definition.id) })),
12008
- createLinkSource({ ...link, logger, cwd: join8(stateDir, LINK_SOURCE) })
12156
+ ...definitions.map((definition) => createCommandSource(definition, { logger, cwd: join9(stateDir, definition.id) })),
12157
+ createLinkSource({ ...link, logger, cwd: join9(stateDir, LINK_SOURCE) })
12009
12158
  ];
12010
12159
  }
12011
12160
  async function describeSources(sources) {
@@ -12017,10 +12166,10 @@ async function describeSources(sources) {
12017
12166
  }
12018
12167
 
12019
12168
  // src/config.js
12020
- var DSH_HOME = process.env.DSH_HOME || join9(homedir(), ".dsh");
12169
+ var DSH_HOME = process.env.DSH_HOME || join10(homedir(), ".dsh");
12021
12170
  function defaultStateDir(home = DSH_HOME, exists2 = existsSync) {
12022
- const current = join9(home, "media-hub");
12023
- const earlier = join9(home, "videosync");
12171
+ const current = join10(home, "media-hub");
12172
+ const earlier = join10(home, "videosync");
12024
12173
  return !exists2(current) && exists2(earlier) ? earlier : current;
12025
12174
  }
12026
12175
  var DEFAULT_STATE_DIR = defaultStateDir();
@@ -12169,30 +12318,10 @@ function interleave(lists) {
12169
12318
  }
12170
12319
 
12171
12320
  // src/locales.js
12172
- import { readdir as readdir4, readFile as readFile4 } from "node:fs/promises";
12173
- import { dirname as dirname3, join as join10, resolve as resolve2 } from "node:path";
12321
+ import { dirname as dirname3, resolve as resolve2 } from "node:path";
12174
12322
  import { fileURLToPath } from "node:url";
12175
12323
  var LOCALE_DIR = resolve2(dirname3(fileURLToPath(import.meta.url)), "../locale");
12176
- async function readLocales(dir, logger) {
12177
- const names = (await readdir4(dir).catch(() => [])).filter((name2) => name2.endsWith(".json")).sort();
12178
- const locales = {};
12179
- for (const name2 of names) {
12180
- const tag = name2.slice(0, -".json".length);
12181
- if (!TAG.test(tag)) {
12182
- logger?.warn("locale/%s: the name is not a language tag; skipped", name2);
12183
- continue;
12184
- }
12185
- try {
12186
- const { ui } = JSON.parse(await readFile4(join10(dir, name2), "utf8"));
12187
- if (ui === null || typeof ui !== "object" || Array.isArray(ui)) throw new Error('no "ui" table');
12188
- locales[tag] = Object.fromEntries(Object.entries(ui).filter(([, text3]) => typeof text3 === "string"));
12189
- } catch (error) {
12190
- logger?.warn("locale/%s: %s; skipped", name2, error.message);
12191
- }
12192
- }
12193
- if (locales[BASE] === void 0) logger?.warn("locale/%s.json is missing; every other language falls back to it", BASE);
12194
- return locales;
12195
- }
12324
+ var readWords = (dir, logger) => readLocales(dir, { warn: (message) => logger?.warn(message) });
12196
12325
 
12197
12326
  // src/vendored.js
12198
12327
  var VENDORED = Object.freeze({
@@ -12353,7 +12482,7 @@ var API = Object.freeze([
12353
12482
  ["POST", "library/cancel", async ({ hub, body: body2 }) => hub.cancelDownload((await body2()).path)],
12354
12483
  ["POST", "follow", async ({ hub, body: body2 }) => hub.followWork(pick3(await body2(), ["source", "id", "follow"]))],
12355
12484
  ["GET", "settings", ({ settings }) => settings()],
12356
- ["GET", "locales", ({ localeDir, logger }) => readLocales(localeDir, logger)],
12485
+ ["GET", "locales", ({ localeDir, logger }) => readWords(localeDir, logger)],
12357
12486
  ["GET", "sources", async ({ hub }) => ({ sources: await hub.sources() })],
12358
12487
  ["GET", "trending", ({ hub, query }) => hub.trending(query("source"), query("kind"))],
12359
12488
  ["GET", "search", ({ hub, query }) => hub.search(query("source"), query("q"), query("kind") || void 0, Math.max(0, Number.parseInt(query("offset"), 10) || 0), parseFilters(query))]
@@ -12713,10 +12842,10 @@ function createDownloads({ stateDir, sources, have, hasSpace = async () => true,
12713
12842
 
12714
12843
  // src/cache.js
12715
12844
  function createCache({ library, downloads, rooms, window: size, logger }) {
12716
- let chain2 = Promise.resolve();
12845
+ let chain3 = Promise.resolve();
12717
12846
  const serial = (step) => {
12718
- const result = chain2.then(step);
12719
- chain2 = result.catch((error) => logger.warn("rolling cache: %s", error.message));
12847
+ const result = chain3.then(step);
12848
+ chain3 = result.catch((error) => logger.warn("rolling cache: %s", error.message));
12720
12849
  return result;
12721
12850
  };
12722
12851
  async function protectedEpisodes() {
@@ -14912,39 +15041,6 @@ function createExtras({ points, night, locales, now = Date.now }) {
14912
15041
  };
14913
15042
  }
14914
15043
 
14915
- // src/changes.js
14916
- function createChanges({ intervalMs = 300 } = {}) {
14917
- const listeners = /* @__PURE__ */ new Set();
14918
- let pending = /* @__PURE__ */ new Set();
14919
- let timer = null;
14920
- let lastAt = 0;
14921
- function flush() {
14922
- timer = null;
14923
- lastAt = Date.now();
14924
- const what = [...pending];
14925
- pending = /* @__PURE__ */ new Set();
14926
- for (const listener of listeners) listener(what);
14927
- }
14928
- return {
14929
- notify(kind) {
14930
- pending.add(kind);
14931
- if (timer !== null) return;
14932
- timer = setTimeout(flush, Math.max(0, lastAt + intervalMs - Date.now()));
14933
- timer.unref?.();
14934
- },
14935
- /** @returns {() => void} stop listening */
14936
- listen(listener) {
14937
- listeners.add(listener);
14938
- return () => listeners.delete(listener);
14939
- },
14940
- close() {
14941
- clearTimeout(timer);
14942
- timer = null;
14943
- listeners.clear();
14944
- }
14945
- };
14946
- }
14947
-
14948
15044
  // src/copies.js
14949
15045
  var DAY_MS4 = 864e5;
14950
15046
  var HOUR_MS2 = 36e5;
@@ -15100,8 +15196,8 @@ function createMediaHub(options) {
15100
15196
  const sources = new Map(options.sources.map((source2) => [source2.id, source2]));
15101
15197
  const covers = createCovers({ dir: join17(stateDir, "covers"), capBytes: options.coverCacheBytes, ffmpeg: options.tools.ffmpeg, logger }, (id) => sources.get(id));
15102
15198
  const log = createWatchLog({ file: join17(stateDir, LOG_NAME), now, logger });
15103
- const changes = createChanges({ intervalMs: options.changeIntervalMs });
15104
- const points = createExtras({ points: options.points ?? (() => void 0), night: options.bingeNight ?? { from: "01:00", to: "06:00" }, locales: () => readLocales(LOCALE_DIR, logger), now });
15199
+ const changes = createNotices({ spacingMs: options.changeIntervalMs ?? 300 });
15200
+ const points = createExtras({ points: options.points ?? (() => void 0), night: options.bingeNight ?? { from: "01:00", to: "06:00" }, locales: () => readWords(LOCALE_DIR, logger), now });
15105
15201
  const books = createBooks({ changed: () => changes.notify("shelf"), dir: join17(stateDir, "books"), sources, capBytes: options.books?.capBytes ?? 0, converter: options.books?.converter ?? NO_CONVERTER, covers, logger, now });
15106
15202
  let rooms;
15107
15203
  let cache;
@@ -15588,8 +15684,7 @@ function createPersonRoutes({ hub, identity }) {
15588
15684
 
15589
15685
  // src/events-route.js
15590
15686
  var EVENTS_PATH = "/api/media-hub/events";
15591
- var HEARTBEAT_MS = 25e3;
15592
- function createEventsRoute({ hub }) {
15687
+ function createEventsRoute({ hub, streams }) {
15593
15688
  return {
15594
15689
  path: EVENTS_PATH,
15595
15690
  methods: ["GET"],
@@ -15597,40 +15692,7 @@ function createEventsRoute({ hub }) {
15597
15692
  fetch: async (request) => {
15598
15693
  const current = hub();
15599
15694
  if (current === void 0) return json(503, { error: { code: "unavailable", message: "The media hub is starting." } });
15600
- const encoder = new TextEncoder();
15601
- let stop = () => {
15602
- };
15603
- const stream = new ReadableStream({
15604
- start(controller) {
15605
- const write2 = (chunk) => {
15606
- try {
15607
- controller.enqueue(encoder.encode(chunk));
15608
- } catch {
15609
- stop();
15610
- }
15611
- };
15612
- write2("retry: 5000\n: open\n\n");
15613
- const unlisten = current.listenChanges((what) => write2(`data: ${JSON.stringify({ type: "change", what })}
15614
-
15615
- `));
15616
- const beat = setInterval(() => write2(": beat\n\n"), HEARTBEAT_MS);
15617
- stop = () => {
15618
- unlisten();
15619
- clearInterval(beat);
15620
- };
15621
- request.signal?.addEventListener("abort", () => {
15622
- stop();
15623
- try {
15624
- controller.close();
15625
- } catch {
15626
- }
15627
- }, { once: true });
15628
- },
15629
- cancel() {
15630
- stop();
15631
- }
15632
- });
15633
- return new Response(stream, { status: 200, headers: { ...SECURITY_HEADERS, "content-type": "text/event-stream; charset=utf-8", "cache-control": "private, no-cache, no-transform", "x-accel-buffering": "no" } });
15695
+ return streams.respond(request, ({ send }) => current.listenChanges((what) => send({ type: "change", what })));
15634
15696
  }
15635
15697
  };
15636
15698
  }
@@ -15726,10 +15788,11 @@ function apply(ctx, config) {
15726
15788
  service.pruneCache(config.cacheDays).catch((error) => logger.warn("pruning the cache: %s", error.message));
15727
15789
  }, DAY_MS6);
15728
15790
  const identity = () => ctx.get("requestIdentity");
15791
+ const streams = createEventStreams({ headers: SECURITY_HEADERS });
15729
15792
  const fetchRoutes = [
15730
15793
  ...createShelfRoutes({ books: () => current?.books, identity }),
15731
15794
  ...createPersonRoutes({ hub: () => current, identity }),
15732
- createEventsRoute({ hub: () => current })
15795
+ createEventsRoute({ hub: () => current, streams })
15733
15796
  ].map((route) => ctx.connection.fetch.register(route));
15734
15797
  const sockets = new import_websocket_server.default({ noServer: true, maxPayload: 16 * 1024, perMessageDeflate: false });
15735
15798
  const disposeHttp = ctx.webServer.register({
@@ -15757,6 +15820,7 @@ function apply(ctx, config) {
15757
15820
  disposeUpgrade();
15758
15821
  disposeHttp();
15759
15822
  await Promise.all(fetchRoutes.map((dispose) => dispose()));
15823
+ streams.close();
15760
15824
  await loading;
15761
15825
  await service.dispose();
15762
15826
  sockets.close();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-media-hub",
3
- "version": "0.15.3",
3
+ "version": "0.15.4",
4
4
  "description": "A media hub for DeepSeek Harness: search shows, novels, ebooks and papers across sources, watch together in sync, and download books in the format you want onto your own shelf.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -75,6 +75,7 @@
75
75
  "devDependencies": {
76
76
  "@deepseek-ai/dsh-client-ui-primitives": "0.2.2-rc.1",
77
77
  "@deepseek-ai/schemastery": "^3.19.0",
78
+ "@soffits/dsh-host-kit": "^0.1.0",
78
79
  "@soffits/dsh-ui-kit": "0.2.0",
79
80
  "danmaku": "^2.0.10",
80
81
  "esbuild": "^0.28.2",