dsh-client-ui-skin-tianlight 2.1.6 → 2.1.7

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.
package/build-info.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "product": "dsh-client-ui-skin-tianlight",
4
- "version": "2.1.6",
5
- "commit": "9436c6c87a02c44cc1626e1fdf14f718dca863af",
6
- "builtAt": "2026-11-15T19:03:39+08:00",
4
+ "version": "2.1.7",
5
+ "commit": "0d5d29db3f98c62cd3396e1ab3d6203cad5a7528",
6
+ "builtAt": "2026-11-15T19:18:06+08:00",
7
7
  "source": "pack"
8
8
  }
package/lib/client.js CHANGED
@@ -34,7 +34,7 @@ window.__ModuleLoader__.load({
34
34
  * must equal `package.json` `version`; tools/test.mjs fails the chain when the
35
35
  * two drift (the 2.1.0-2.1.3 builds printed a stale "2.0.4").
36
36
  */
37
- const TL_BUILD_VERSION = "2.1.6";
37
+ const TL_BUILD_VERSION = "2.1.7";
38
38
 
39
39
  /**
40
40
  * Host identity last reported by `_engines`: `build` is the host's
@@ -147,7 +147,6 @@ window.__ModuleLoader__.load({
147
147
  * TL5_DIAG 运行时诊断命名空间,供 `__dshTianlightInstance` 与
148
148
  * 面板“工程”分区读取,不写进产品 DOM。
149
149
  */
150
- const TL5_VERSION = "0.5.0";
151
150
  const TL5_MODULES_ATTR = "data-tl-modules";
152
151
  const MODULES_KEY = "tianlight.modules";
153
152
 
@@ -23732,8 +23731,6 @@ const LIFE_PAUSE_REPLAY_MS = 60 * 1000;
23732
23731
  let petAgentPending = false;
23733
23732
  let petAgentAbort = null;
23734
23733
 
23735
- const petAgentDoc = () => (typeof document === "undefined" ? null : document);
23736
-
23737
23734
  function petAgentReadState() {
23738
23735
  const dayKey = petAgentDayKey();
23739
23736
  let stored = null;
@@ -26155,14 +26152,17 @@ body[data-dsh-tianlight][data-tl-legibility="boost"] [data-tl-font-panel] {
26155
26152
  return false;
26156
26153
  }
26157
26154
 
26158
- /** One session decision. The session marker is written even when the splash is skipped. */
26155
+ /**
26156
+ * One session decision for the compact splash, expressed through the single
26157
+ * planner so the guard order lives in exactly one place.
26158
+ * The session marker is written even when the splash is skipped.
26159
+ */
26159
26160
  function splashDecision() {
26160
- const enabled = readSplashEnabled();
26161
- if (splashSeenThisSession()) return { play: false, reason: "seen", enabled };
26161
+ const plan = splashPlan();
26162
+ const enabled = plan.style !== "off";
26163
+ if (plan.reason === "seen") return { play: false, reason: "seen", enabled };
26162
26164
  splashMarkSession();
26163
- if (enabled === false) return { play: false, reason: "disabled", enabled };
26164
- if (splashReducedMotion() && readSplashForceMotion() !== true) return { play: false, reason: "reduced-motion", enabled };
26165
- if (splashLowPowerActive()) return { play: false, reason: "low-power", enabled };
26165
+ if (plan.mode === "none") return { play: false, reason: plan.reason, enabled };
26166
26166
  return { play: true, reason: "playing", enabled };
26167
26167
  }
26168
26168
 
@@ -26577,7 +26577,11 @@ body[data-dsh-tianlight][data-tl-legibility="boost"] [data-tl-font-panel] {
26577
26577
  * which implementation runs.
26578
26578
  */
26579
26579
  function installSplashEntry() {
26580
- const style = readSplashStyle();
26580
+ // The whole guard chain lives in splashPlan: style, session marker, reduced
26581
+ // motion (with the explicit override) and low power are evaluated in one
26582
+ // place, and this function only turns the plan into an implementation.
26583
+ const plan = splashPlan();
26584
+ const style = plan.style;
26581
26585
  const finishStatus = (reason, mode) => {
26582
26586
  splashRuntime.active = false;
26583
26587
  splashRuntime.reason = reason;
@@ -26585,13 +26589,13 @@ body[data-dsh-tianlight][data-tl-legibility="boost"] [data-tl-font-panel] {
26585
26589
  tl5Diag("splash", splashStatus());
26586
26590
  return () => {};
26587
26591
  };
26588
- if (splashSeenThisSession()) return finishStatus("seen", style === "long" || style === "long-once" ? "long" : "simple");
26589
- if (style === "off") return finishStatus("disabled", "simple");
26590
- if (splashReducedMotion() && readSplashForceMotion() !== true) return finishStatus("reduced-motion", "simple");
26591
- if (splashLowPowerActive()) return finishStatus("low-power", "simple");
26592
-
26593
- if (style === "simple") return installSplash();
26594
- if (style === "long-once" && readSplashLastFull() === splashLocalDate()) return installSplash();
26592
+ if (plan.mode === "none") {
26593
+ // A seen session historically reported the long mode for the styles that
26594
+ // would have played the film; the other skips reported the compact mode.
26595
+ const seenMode = plan.reason === "seen" && (style === "long" || style === "long-once") ? "long" : "simple";
26596
+ return finishStatus(plan.reason, seenMode);
26597
+ }
26598
+ if (plan.mode === "simple") return installSplash();
26595
26599
 
26596
26600
  const body = document.body;
26597
26601
  if (body === null || body === undefined) return finishStatus("no-body", "long");
package/lib/index.js CHANGED
@@ -5,36 +5,28 @@
5
5
  // module carrier only serves bundles, so this host half owns one prefix route
6
6
  // and streams files out of `assets/` with byte-range support, which is what lets
7
7
  // `<video>` start playing before the whole file has arrived.
8
-
9
- import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
10
- import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
8
+ //
9
+ // v2.1.8: `handle()` used to be one 255-line if-chain. The route bodies now live in
10
+ // `lib/routes/<domain>.js` (each exports `{ exact, prefix }`), and this file owns only
11
+ // the pieces that must not move: the two same-origin fences, the identity constants
12
+ // (`HOST_API`, `BUILD`), the persistent-data bootstrap, and one ordered dispatch table.
13
+ // The order of that table is the order the old if-chain evaluated, including the
14
+ // GET/HEAD gate that sits between the write routes and the read routes.
15
+
16
+ import { dirname, resolve } from 'node:path'
11
17
  import { fileURLToPath } from 'node:url'
12
- import { ASSET_DIR, IMAGE_EXT, ROUTE, SAFE_NAME, VIDEO_EXT, fileSize, mediaKindFromName, safeJoin } from './media-types.js'
18
+ import { IMAGE_EXT, ROUTE, SAFE_NAME, VIDEO_EXT, fileSize, safeJoin } from './media-types.js'
13
19
  import {
14
20
  DATA_ROOT,
15
21
  DATA_ROOT_DISPLAY,
16
22
  STATE_DIR,
17
- WE_ROOTS_FILE,
18
23
  configureHostPaths,
19
- dataRootForProfile,
20
24
  hasLegacyData,
21
25
  migrateLegacyHostData,
22
26
  } from './host-paths.js'
23
- import { parseRange, sendJson, sendText, servePath, serveTextFile } from './http-media.js'
24
- import { listUploads, receiveUpload, uploadPath, uploadStatus } from './upload.js'
25
- import { listSceneProjects, resolveSceneDir, sceneFilePath } from './scene-project.js'
26
- import { handleSettings, readSettings } from './settings-store.js'
27
- import { handleBundle, handleImport } from './bundle.js'
28
- import { frameCacheStatus, handleFrameCache, handleFrameCacheStatus } from './media-cache.js'
29
- import { derivedPath, ffmpegStatus, handleTranscode, handleTranscodeStatus, listDerived } from './transcode.js'
30
- import { handleWebProject, listWebProjects } from './web-project.js'
31
- import { buildFingerprint, formatFingerprintLine } from './fingerprint.js'
32
- import { handleWeatherProxy } from './weather-proxy.js'
33
- import {
34
- PET_CHAT_CODES,
35
- computePetLlmCapability,
36
- petChat,
37
- } from './pet-chat.js'
27
+ import { parseRange, sendText } from './http-media.js'
28
+ import { readSettings } from './settings-store.js'
29
+ import { PET_CHAT_CODES, computePetLlmCapability, petChat } from './pet-chat.js'
38
30
  import {
39
31
  disposeSceneVideoCapture,
40
32
  isAllowedLocalHost,
@@ -43,6 +35,15 @@ import {
43
35
  weLibraryStatus,
44
36
  WE_API_PREFIX,
45
37
  } from './we-wallpaper/host.mjs'
38
+ import * as wallpaperRoutes from './routes/wallpaper.js'
39
+ import * as mediaRoutes from './routes/media.js'
40
+ import * as engineRoutes from './routes/engine.js'
41
+ import * as settingsRoutes from './routes/settings.js'
42
+ import * as framesRoutes from './routes/frames.js'
43
+ import * as petRoutes from './routes/pet.js'
44
+ import * as weatherRoutes from './routes/weather.js'
45
+ import * as sceneRoutes from './routes/scene.js'
46
+ import * as webprojectRoutes from './routes/webproject.js'
46
47
 
47
48
  const HERE = dirname(fileURLToPath(import.meta.url))
48
49
 
@@ -53,19 +54,13 @@ const WE_HANDLER = makeWeWallpaperHandler()
53
54
  const ENGINE_FILE = resolve(HERE, '..', 'vendor', 'webwallgl', 'webwallgl.global.min.js')
54
55
  const SCENE_FRAME = resolve(HERE, 'scene-frame.html')
55
56
 
56
- /**
57
- * Optional list of extra wallpaper directories (e.g. Wallpaper Engine projects).
58
- * v2.0.1: lives in the persistent data root (host-paths.js) so it survives plugin
59
- * uninstall/upgrade; the legacy `<plugin>/we-roots.json` is copied once at startup.
60
- */
61
-
62
57
  /**
63
58
  * Host side of the `/skin-tianlight` route-contract handshake. The browser half
64
59
  * sends the value it expects (`_engines?api=`) and gets `stale: true` back when
65
60
  * this process speaks a different contract — the one case a Ctrl+F5 refresh cannot
66
- * fix by itself. Change it ONLY when a route in `handle()` changes shape; bumping
67
- * it with every release brought back the needless "restart DSH" hint. Keep in sync
68
- * with `HOST_API` in `src/10-constants.js`.
61
+ * fix by itself. Change it ONLY when a route in the dispatch table changes shape;
62
+ * bumping it with every release brought back the needless "restart DSH" hint. Keep
63
+ * in sync with `HOST_API` in `src/10-constants.js`.
69
64
  */
70
65
  const HOST_API = '2'
71
66
 
@@ -74,201 +69,61 @@ const HOST_API = '2'
74
69
  * manifest is stamped with it. The handshake no longer compares it, so a
75
70
  * browser-half-only update can run against an unchanged host process.
76
71
  */
77
- const BUILD = '2.1.6'
78
-
79
- function readRoots() {
80
- try {
81
- const value = JSON.parse(readFileSync(WE_ROOTS_FILE, 'utf8'))
82
- if (!Array.isArray(value)) return []
83
- // Absolute paths only: a relative entry would silently resolve against the DSH
84
- // process working directory, which is not the directory the user pointed at.
85
- return value
86
- .filter((entry) => typeof entry === 'string' && entry.trim() !== '' && isAbsolute(entry.trim()))
87
- .map((entry) => resolve(entry.trim()))
88
- } catch {
89
- return []
90
- }
91
- }
92
-
93
- /** Media files in the configured roots, addressed through the ext route. */
94
- function listExternalWallpapers() {
95
- const items = []
96
- readRoots().forEach((root, index) => {
97
- let names = []
98
- try {
99
- names = readdirSync(root)
100
- } catch {
101
- return
102
- }
103
- for (const name of names) {
104
- if (SAFE_NAME.test(name) === false) continue
105
- const kind = mediaKindFromName(name)
106
- if (kind === null) continue
107
- // The root index is part of the id: two roots can hold the same file name, and a
108
- // duplicate React key silently drops a card from the grid.
109
- items.push({ id: 'ext:' + index + ':' + name, kind, url: ROUTE + '/ext/' + index + '/' + name, bytes: fileSize(join(root, name)) })
110
- }
111
- })
112
- return items
113
- }
114
-
115
- function listAssets() {
116
- try {
117
- return readdirSync(ASSET_DIR).filter((name) => SAFE_NAME.test(name))
118
- } catch {
119
- return []
120
- }
121
- }
122
-
123
- /** The companion art is not a wallpaper candidate. */
124
- const COMPANION = 'cat.png'
72
+ const BUILD = '2.1.7'
125
73
 
126
74
  /**
127
- * Every file in `assets/` a user could reasonably drop in as a wallpaper. Drop a
128
- * file, reload, it appears in the list: no config, no manifest edit. Videos rank
129
- * first because the skin is built around a moving picture, stills are the fallback.
75
+ * Identity handed to the route modules that need it. `HOST_API`/`BUILD` stay in this
76
+ * file on purpose (release.mjs and audit.mjs grep them here); the getters keep the
77
+ * live persistent-data diagnostic reachable without moving its state out.
130
78
  */
131
- function listWallpapers() {
132
- const items = []
133
- for (const name of listAssets()) {
134
- if (name === COMPANION) continue
135
- const kind = mediaKindFromName(name)
136
- if (kind === null) continue
137
- items.push({ id: name, kind, url: ROUTE + '/' + name, bytes: fileSize(join(ASSET_DIR, name)) })
138
- }
139
- // Uploads are ordinary wallpapers once they land, so they share one sorted
140
- // catalog instead of a second list the panel would have to merge.
141
- const combined = [...items, ...listUploads()]
142
- combined.sort((a, b) => (a.kind === b.kind ? a.id.localeCompare(b.id) : a.kind === 'video' ? -1 : 1))
143
- return combined
79
+ const HOST = {
80
+ hostApi: HOST_API,
81
+ build: BUILD,
82
+ engineFile: ENGINE_FILE,
83
+ sceneFrame: SCENE_FRAME,
84
+ dataDiagnostic: () => dataDiagnostic,
85
+ activeProfile: () => activeProfile,
144
86
  }
145
87
 
146
88
  /**
147
- * Stores the extra wallpaper roots. Accepts only absolute paths that currently
148
- * resolve to a directory, capped at 20 entries: the file is a configuration, not a
149
- * filesystem browser, so a bad payload is rejected instead of written.
150
- * Relative entries are dropped (not resolved against the process CWD), a body over
151
- * the cap gets a 413 instead of a dropped connection, and the request must be JSON.
89
+ * The dispatch table. Three ordered lookups plus the final asset fallback:
90
+ * 1. write routes run BEFORE the GET/HEAD gate (they are POST/PUT and own framing),
91
+ * 2. the gate rejects every other non-read method with the historical 405,
92
+ * 3. read routes run after it,
93
+ * 4. prefixes are matched in the original order,
94
+ * 5. anything left is a package-local asset name.
95
+ * Order inside each map is insertion order, i.e. the order of the old if-chain.
152
96
  */
153
- function writeRoots(req, res) {
154
- const contentType = String(req.headers['content-type'] ?? '').toLowerCase()
155
- if (contentType.includes('application/json') === false) {
156
- sendText(res, 415, 'expected application/json')
157
- req.resume()
158
- return
159
- }
160
- const chunks = []
161
- let size = 0
162
- let oversized = false
163
- req.on('data', (chunk) => {
164
- if (oversized) return
165
- size += chunk.length
166
- if (size > 8192) {
167
- oversized = true
168
- sendText(res, 413, 'roots payload too large')
169
- req.resume()
170
- return
171
- }
172
- chunks.push(chunk)
173
- })
174
- req.on('end', () => {
175
- if (oversized) return
176
- let roots
177
- let skipped = 0
178
- try {
179
- const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
180
- if (!Array.isArray(value)) throw new Error('expected an array')
181
- const accepted = []
182
- for (const entry of value) {
183
- if (typeof entry !== 'string' || entry.trim() === '') continue
184
- const candidate = entry.trim()
185
- if (isAbsolute(candidate) === false) {
186
- skipped += 1
187
- continue
188
- }
189
- try {
190
- if (statSync(candidate).isDirectory()) accepted.push(resolve(candidate))
191
- else skipped += 1
192
- } catch {
193
- skipped += 1
194
- }
195
- }
196
- roots = accepted.slice(0, 20)
197
- writeFileSync(WE_ROOTS_FILE, JSON.stringify(roots, null, 2), 'utf8')
198
- } catch {
199
- sendText(res, 400, 'invalid roots payload')
200
- return
201
- }
202
- sendJson(res, 200, { roots, skipped })
203
- })
204
- req.on('error', () => {
205
- try {
206
- res.destroy()
207
- } catch {
208
- // ignore
209
- }
210
- })
211
- }
212
-
213
- /**
214
- * `_engines` payload. The capabilities block is how the browser half decides
215
- * whether to render settings sync, bundle import/export, the frame cache and the
216
- * optional transcode action at all: nothing is advertised that is not mounted.
217
- */
218
- async function buildEngineStatus(url, ctx) {
219
- const expectedApi = url.searchParams.get('api')
220
- // Legacy fallback: clients shipped before HOST_API still send their build number.
221
- const expectedBuild = url.searchParams.get('build')
222
- // R4B: async ffmpeg probe — a cache miss must not block the host's event loop.
223
- const ffmpeg = await ffmpegStatus()
224
- const roots = readRoots()
225
- return {
226
- build: BUILD,
227
- api: HOST_API,
228
- // A new client states the route contract it speaks; only a contract mismatch
229
- // means it must not talk to this host. A client with no `api` (an old build)
230
- // keeps the historical build-number comparison; no handshake parameter at all
231
- // (curl, the diagnostics panel) is answered without a verdict.
232
- stale:
233
- expectedApi !== null
234
- ? expectedApi !== HOST_API
235
- : expectedBuild === null
236
- ? undefined
237
- : expectedBuild !== BUILD,
238
- webwallgl: existsSync(ENGINE_FILE),
239
- adapter: existsSync(SCENE_FRAME),
240
- sceneProjects: listSceneProjects(roots).length,
241
- webProjects: listWebProjects(roots).length,
242
- upload: uploadStatus(),
243
- ffmpeg: ffmpeg.ffmpeg,
244
- cache: frameCacheStatus(),
245
- settings: { revision: readSettings().revision },
246
- // v2.0.1 (additive): where user data lives — symbolic, never an absolute machine
247
- // path. `mode: legacy` only happens when the host exposes no profileContext
248
- // (test harness/old host); a tarball upgrade then simply stays on the old layout.
249
- data: {
250
- mode: dataDiagnostic.mode,
251
- dir: dataDiagnostic.dir,
252
- legacyDataPending: dataDiagnostic.legacyDataPending === true,
253
- migratedFromLegacy: dataDiagnostic.migrated ?? 0,
254
- },
255
- // v0.6.0 (additive): local Wallpaper Engine library discovery. `found:false`
256
- // with `count:0` is the honest answer for a machine without WE.
257
- weLibrary: weLibraryStatus(),
258
- capabilities: {
259
- settings: true,
260
- bundle: true,
261
- frameCache: true,
262
- transcode: ffmpeg.ffmpeg,
263
- webWallpapers: true,
264
- weLibrary: true,
265
- // v2.0.0: the companion AI chat bridge. Synchronous availability only:
266
- // provider/model come from the Host's current default selection, and the
267
- // browser auto-registers its built-in adapter only when `available` is true.
268
- petLlm: computePetLlmCapability(ctx),
269
- },
270
- }
271
- }
97
+ const EXACT_BEFORE_GATE = new Map([
98
+ ['_we-roots', wallpaperRoutes.exact['_we-roots']],
99
+ ['_settings', settingsRoutes.exact._settings],
100
+ ['_bundle', settingsRoutes.exact._bundle],
101
+ ['_import', settingsRoutes.exact._import],
102
+ ['_frame-cache', framesRoutes.exact['_frame-cache']],
103
+ ['_frame-cache/status', framesRoutes.exact['_frame-cache/status']],
104
+ ['_transcode', framesRoutes.exact._transcode],
105
+ ['_transcode/status', framesRoutes.exact['_transcode/status']],
106
+ ['_pet-chat', petRoutes.exact['_pet-chat']],
107
+ ['_upload', mediaRoutes.exact._upload],
108
+ ])
109
+
110
+ const EXACT_AFTER_GATE = new Map([
111
+ ['_manifest', mediaRoutes.exact._manifest],
112
+ ['_wallpapers', wallpaperRoutes.exact._wallpapers],
113
+ ['_engines', engineRoutes.exact._engines],
114
+ ['_weather', weatherRoutes.exact._weather],
115
+ ['_fingerprint', settingsRoutes.exact._fingerprint],
116
+ ['_engine/webwallgl.js', engineRoutes.exact['_engine/webwallgl.js']],
117
+ ['_scene-frame', engineRoutes.exact['_scene-frame']],
118
+ ])
119
+
120
+ const PREFIX_ROUTES = [
121
+ ...sceneRoutes.prefix,
122
+ ...webprojectRoutes.prefix,
123
+ ...mediaRoutes.prefix,
124
+ ...framesRoutes.prefix,
125
+ ...wallpaperRoutes.prefix,
126
+ ]
272
127
 
273
128
  /**
274
129
  * Same-origin fence for this plugin's host routes. The skin page itself is the
@@ -353,256 +208,33 @@ function handle(ctx, req, res) {
353
208
  if (rest.startsWith(ROUTE)) rest = rest.slice(ROUTE.length)
354
209
  rest = rest.replace(/^\/+/, '')
355
210
 
356
- if (rest === '_we-roots') {
357
- if (req.method === 'POST') writeRoots(req, res)
358
- else sendJson(res, 200, { roots: readRoots() })
359
- return
360
- }
361
-
362
- // ---- v0.5.0 host routes (contract §6 order) ----
363
- // Each module owns its method gate and its own failure status: the shared
364
- // GET/HEAD gate below would turn every write route into a blanket 405.
365
- if (rest === '_settings') {
366
- handleSettings(req, res)
367
- return
368
- }
369
- if (rest === '_bundle') {
370
- handleBundle(req, res, { build: BUILD })
371
- return
372
- }
373
- if (rest === '_import') {
374
- handleImport(req, res)
375
- return
376
- }
377
- if (rest === '_frame-cache') {
378
- handleFrameCache(req, res, url)
379
- return
380
- }
381
- if (rest === '_frame-cache/status') {
382
- handleFrameCacheStatus(req, res)
383
- return
384
- }
385
- if (rest === '_transcode') {
386
- // R4B: async handler (ffmpeg probe/run). The route writes its own response.
387
- void handleTranscode(req, res, url).catch(() => {
388
- try {
389
- sendJson(res, 500, { ok: false, error: 'transcode failed' })
390
- } catch {
391
- // response already gone
392
- }
393
- })
394
- return
395
- }
396
- if (rest === '_transcode/status') {
397
- void handleTranscodeStatus(req, res).catch(() => {
398
- try {
399
- sendJson(res, 500, { ok: false, error: 'transcode-status-failed' })
400
- } catch {
401
- // response already gone
402
- }
403
- })
404
- return
405
- }
406
-
407
- // v2.0.0: the companion AI chat bridge. It owns method/body/response framing and
408
- // resolves the optional Host `llm` / `agentDefaultModel` services per request, so
409
- // a non-Web or older Host simply reports `{ ok:false, code }` instead of failing
410
- // the plugin fibre. Must stay before the generic GET/HEAD gate (it is a POST).
411
- if (rest === '_pet-chat') {
412
- petChat.handle(ctx, req, res)
413
- return
414
- }
415
-
416
- // Upload is the one write endpoint that is not JSON. It has to run before the
417
- // GET/HEAD gate, and it owns its own body limits and response framing.
418
- if (rest === '_upload') {
419
- if (req.method !== 'POST') {
420
- sendText(res, 405, 'method not allowed')
421
- return
422
- }
423
- receiveUpload(req, res, url.searchParams.get('name'), sendJson)
211
+ const early = EXACT_BEFORE_GATE.get(rest)
212
+ if (early !== undefined) {
213
+ early(ctx, req, res, url, rest, HOST)
424
214
  return
425
215
  }
426
216
 
217
+ // Each write route above owns its method gate and its own failure status: this
218
+ // shared gate would turn every write route into a blanket 405.
427
219
  if (req.method !== 'GET' && req.method !== 'HEAD') {
428
220
  sendText(res, 405, 'method not allowed')
429
221
  return
430
222
  }
431
223
 
432
- if (rest === '_manifest') {
433
- sendJson(res, 200, { assets: listAssets() })
434
- return
435
- }
436
-
437
- if (rest === '_wallpapers') {
438
- sendJson(res, 200, {
439
- items: [
440
- ...listWallpapers(),
441
- ...listExternalWallpapers(),
442
- ...listSceneProjects(readRoots()),
443
- ...listWebProjects(readRoots()),
444
- ...listDerived(),
445
- // v0.6.0: the real Wallpaper Engine library, appended so every existing
446
- // source keeps its position/id even when WE is absent (then: no items).
447
- ...listWeSkinItems(),
448
- ],
449
- })
450
- return
451
- }
452
-
453
- // ---- optional WebWallGL scene engine ----
454
- if (rest === '_engines') {
455
- // R4B: async because the ffmpeg probe no longer blocks the event loop.
456
- // v2.0.0: the Context rides along so `capabilities.petLlm` can read the optional
457
- // `llm` / `agentDefaultModel` services synchronously.
458
- void buildEngineStatus(url, ctx).then(
459
- (body) => {
460
- try {
461
- sendJson(res, 200, body)
462
- } catch {
463
- // response already gone
464
- }
465
- },
466
- () => {
467
- try {
468
- sendText(res, 500, 'engine status failed')
469
- } catch {
470
- // response already gone
471
- }
472
- },
473
- )
474
- return
475
- }
476
- if (rest === '_weather') {
477
- // v2.0.5: transport shim for networks where the renderer's TLS handshake to
478
- // Open-Meteo is dropped. Read-only, no state, no caching. GET only: a HEAD has
479
- // no body to return but would still spend an outbound request.
480
- if (req.method !== 'GET') {
481
- sendText(res, 405, 'method not allowed')
482
- return
483
- }
484
- void handleWeatherProxy(url, res).catch(() => {
485
- try {
486
- sendJson(res, 502, { ok: false, error: 'network' })
487
- } catch {
488
- // response already gone
489
- }
490
- })
491
- return
492
- }
493
- if (rest === '_fingerprint') {
494
- // v2.0.1: exact installed-build identity for the hub's self-test / feedback panels.
495
- // Additive route; it carries versions, hashes and the install method only — never a
496
- // machine path (the profile dir is reported symbolically at most by `dataMode`).
497
- if (req.method !== 'GET') {
498
- sendText(res, 405, 'method not allowed')
499
- return
500
- }
501
- const fingerprint = buildFingerprint({ hostApi: HOST_API, profile: activeProfile, dataMode: dataDiagnostic.mode })
502
- sendJson(res, 200, { ...fingerprint, line: formatFingerprintLine(fingerprint) })
503
- return
504
- }
505
- if (rest === '_engine/webwallgl.js') {
506
- serveTextFile(req, res, ENGINE_FILE, 'text/javascript; charset=utf-8')
507
- return
508
- }
509
- if (rest === '_scene-frame') {
510
- // The iframe itself is sandboxed by the client; the CSP is the second lock:
511
- // opaque origin, no framing, no top navigation, no form posts.
512
- serveTextFile(req, res, SCENE_FRAME, 'text/html; charset=utf-8', {
513
- 'content-security-policy':
514
- "default-src 'none'; script-src * 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; connect-src *; img-src * data: blob:; media-src * blob:; font-src * data:; worker-src * blob:; frame-src 'none'; object-src 'none'; base-uri 'none'; sandbox allow-scripts",
515
- 'referrer-policy': 'no-referrer',
516
- })
517
- return
518
- }
519
- // Scene project files. Each path segment is validated again; only media/asset
520
- // extensions are served, and CORS is open because the adapter is opaque-origin.
521
- if (rest.startsWith('_scene-project/')) {
522
- const parts = rest.split('/')
523
- const index = Number(parts[1])
524
- const dirName = parts[2]
525
- const projectDir = resolveSceneDir(readRoots(), index, dirName)
526
- const filePath = projectDir === null ? null : sceneFilePath(projectDir, parts.slice(3))
527
- if (filePath === null) {
528
- sendText(res, 404, 'not found')
529
- return
530
- }
531
- servePath(req, res, filePath, basename(filePath), {
532
- 'access-control-allow-origin': '*',
533
- 'cross-origin-resource-policy': 'cross-origin',
534
- })
535
- return
536
- }
537
-
538
- // Wallpaper Engine web projects (A3): an opaque-origin page plus its assets.
539
- // Segment validation happens inside the module again; discovery is not a gate.
540
- if (rest.startsWith('_web-project/')) {
541
- handleWebProject(req, res, rest, readRoots())
542
- return
543
- }
544
-
545
- // User uploads: uploads/<fileName>, served through the same Range pipeline.
546
- if (rest.startsWith('uploads/')) {
547
- const parts = rest.split('/')
548
- if (parts.length !== 2) {
549
- sendText(res, 404, 'not found')
550
- return
551
- }
552
- const filePath = uploadPath(parts[1])
553
- if (filePath === null) {
554
- sendText(res, 404, 'not found')
555
- return
556
- }
557
- servePath(req, res, filePath, parts[1])
558
- return
559
- }
560
-
561
- // ffmpeg derivatives: derived/<fileName>. Written only by `_transcode`.
562
- if (rest.startsWith('derived/')) {
563
- const parts = rest.split('/')
564
- if (parts.length !== 2) {
565
- sendText(res, 404, 'not found')
566
- return
567
- }
568
- const filePath = derivedPath(parts[1])
569
- if (filePath === null) {
570
- sendText(res, 404, 'not found')
571
- return
572
- }
573
- servePath(req, res, filePath, parts[1])
224
+ const late = EXACT_AFTER_GATE.get(rest)
225
+ if (late !== undefined) {
226
+ late(ctx, req, res, url, rest, HOST)
574
227
  return
575
228
  }
576
229
 
577
- // Extra wallpaper roots, addressed as ext/<rootIndex>/<fileName>.
578
- if (rest.startsWith('ext/')) {
579
- const parts = rest.split('/')
580
- const index = Number(parts[1])
581
- const roots = readRoots()
582
- if (parts.length !== 3 || Number.isInteger(index) === false || index < 0 || index >= roots.length) {
583
- sendText(res, 404, 'not found')
230
+ for (const [prefix, handler] of PREFIX_ROUTES) {
231
+ if (rest.startsWith(prefix)) {
232
+ handler(ctx, req, res, rest, url, HOST)
584
233
  return
585
234
  }
586
- const filePath = safeJoin(roots[index], parts[2])
587
- if (filePath === null) {
588
- sendText(res, 404, 'not found')
589
- return
590
- }
591
- servePath(req, res, filePath, parts[2])
592
- return
593
- }
594
-
595
- if (rest === '' || rest.includes('/') || SAFE_NAME.test(rest) === false) {
596
- sendText(res, 404, 'not found')
597
- return
598
235
  }
599
236
 
600
- serveAsset(req, res, rest)
601
- }
602
-
603
- /** Package-local assets: identical serving, path rooted at assets/. */
604
- function serveAsset(req, res, name) {
605
- servePath(req, res, join(ASSET_DIR, name), name)
237
+ mediaRoutes.fallback(req, res, rest)
606
238
  }
607
239
 
608
240
  /**
@@ -704,10 +336,10 @@ export { apply }
704
336
  */
705
337
  export const __test = {
706
338
  parseRange,
707
- listWallpapers,
708
- listAssets,
339
+ listWallpapers: wallpaperRoutes.listWallpapers,
340
+ listAssets: wallpaperRoutes.listAssets,
709
341
  safeJoin,
710
- readRoots,
342
+ readRoots: wallpaperRoutes.readRoots,
711
343
  SAFE_NAME,
712
344
  VIDEO_EXT,
713
345
  IMAGE_EXT,
@@ -715,7 +347,7 @@ export const __test = {
715
347
  // v2.0.0 companion AI chat bridge (see lib/pet-chat.js).
716
348
  // `engineStatus(url)` keeps its old one-argument form; pass a fake Context as the
717
349
  // second argument to exercise `capabilities.petLlm` (tests do exactly that).
718
- engineStatus: (url, ctx) => buildEngineStatus(url, ctx),
350
+ engineStatus: (url, ctx) => engineRoutes.engineStatus(url, ctx, HOST),
719
351
  petChat: petChat.handle,
720
352
  petChatStatus: petChat.status,
721
353
  petLlmCapability: computePetLlmCapability,
@@ -0,0 +1,116 @@
1
+ // Host routes: engine status (`_engines`), the optional WebWallGL script and the
2
+ // sandboxed scene iframe. Extracted from lib/index.js in v2.1.8.
3
+ //
4
+ // These handlers need identity owned by index.js (HOST_API / BUILD / the data
5
+ // diagnostic / the running profile), so the dispatch table passes a `host` object;
6
+ // the pure filesystem paths are passed the same way to keep the module relocatable.
7
+ import { existsSync } from 'node:fs'
8
+ import { frameCacheStatus } from '../media-cache.js'
9
+ import { sendJson, sendText, serveTextFile } from '../http-media.js'
10
+ import { computePetLlmCapability } from '../pet-chat.js'
11
+ import { listSceneProjects } from '../scene-project.js'
12
+ import { readSettings } from '../settings-store.js'
13
+ import { uploadStatus } from '../upload.js'
14
+ import { listWebProjects } from '../web-project.js'
15
+ import { ffmpegStatus } from '../transcode.js'
16
+ import { weLibraryStatus } from '../we-wallpaper/host.mjs'
17
+ import { readRoots } from './wallpaper.js'
18
+
19
+ /**
20
+ * `_engines` payload. The capabilities block is how the browser half decides
21
+ * whether to render settings sync, bundle import/export, the frame cache and the
22
+ * optional transcode action at all: nothing is advertised that is not mounted.
23
+ */
24
+ export async function engineStatus(url, ctx, host) {
25
+ const expectedApi = url.searchParams.get('api')
26
+ // Legacy fallback: clients shipped before HOST_API still send their build number.
27
+ const expectedBuild = url.searchParams.get('build')
28
+ // R4B: async ffmpeg probe — a cache miss must not block the host's event loop.
29
+ const ffmpeg = await ffmpegStatus()
30
+ const roots = readRoots()
31
+ const diagnostic = host.dataDiagnostic()
32
+ return {
33
+ build: host.build,
34
+ api: host.hostApi,
35
+ // A new client states the route contract it speaks; only a contract mismatch
36
+ // means it must not talk to this host. A client with no `api` (an old build)
37
+ // keeps the historical build-number comparison; no handshake parameter at all
38
+ // (curl, the diagnostics panel) is answered without a verdict.
39
+ stale:
40
+ expectedApi !== null
41
+ ? expectedApi !== host.hostApi
42
+ : expectedBuild === null
43
+ ? undefined
44
+ : expectedBuild !== host.build,
45
+ webwallgl: existsSync(host.engineFile),
46
+ adapter: existsSync(host.sceneFrame),
47
+ sceneProjects: listSceneProjects(roots).length,
48
+ webProjects: listWebProjects(roots).length,
49
+ upload: uploadStatus(),
50
+ ffmpeg: ffmpeg.ffmpeg,
51
+ cache: frameCacheStatus(),
52
+ settings: { revision: readSettings().revision },
53
+ // v2.0.1 (additive): where user data lives — symbolic, never an absolute machine
54
+ // path. `mode: legacy` only happens when the host exposes no profileContext
55
+ // (test harness/old host); a tarball upgrade then simply stays on the old layout.
56
+ data: {
57
+ mode: diagnostic.mode,
58
+ dir: diagnostic.dir,
59
+ legacyDataPending: diagnostic.legacyDataPending === true,
60
+ migratedFromLegacy: diagnostic.migrated ?? 0,
61
+ },
62
+ // v0.6.0 (additive): local Wallpaper Engine library discovery. `found:false`
63
+ // with `count:0` is the honest answer for a machine without WE.
64
+ weLibrary: weLibraryStatus(),
65
+ capabilities: {
66
+ settings: true,
67
+ bundle: true,
68
+ frameCache: true,
69
+ transcode: ffmpeg.ffmpeg,
70
+ webWallpapers: true,
71
+ weLibrary: true,
72
+ // v2.0.0: the companion AI chat bridge. Synchronous availability only:
73
+ // provider/model come from the Host's current default selection, and the
74
+ // browser auto-registers its built-in adapter only when `available` is true.
75
+ petLlm: computePetLlmCapability(ctx),
76
+ },
77
+ }
78
+ }
79
+
80
+ export const exact = {
81
+ // R4B: async because the ffmpeg probe no longer blocks the event loop.
82
+ // v2.0.0: the Context rides along so `capabilities.petLlm` can read the optional
83
+ // `llm` / `agentDefaultModel` services synchronously.
84
+ _engines: (ctx, req, res, url, rest, host) => {
85
+ void engineStatus(url, ctx, host).then(
86
+ (body) => {
87
+ try {
88
+ sendJson(res, 200, body)
89
+ } catch {
90
+ // response already gone
91
+ }
92
+ },
93
+ () => {
94
+ try {
95
+ sendText(res, 500, 'engine status failed')
96
+ } catch {
97
+ // response already gone
98
+ }
99
+ },
100
+ )
101
+ },
102
+ '_engine/webwallgl.js': (ctx, req, res, url, rest, host) => {
103
+ serveTextFile(req, res, host.engineFile, 'text/javascript; charset=utf-8')
104
+ },
105
+ '_scene-frame': (ctx, req, res, url, rest, host) => {
106
+ // The iframe itself is sandboxed by the client; the CSP is the second lock:
107
+ // opaque origin, no framing, no top navigation, no form posts.
108
+ serveTextFile(req, res, host.sceneFrame, 'text/html; charset=utf-8', {
109
+ 'content-security-policy':
110
+ "default-src 'none'; script-src * 'unsafe-inline' 'unsafe-eval'; style-src 'unsafe-inline'; connect-src *; img-src * data: blob:; media-src * blob:; font-src * data:; worker-src * blob:; frame-src 'none'; object-src 'none'; base-uri 'none'; sandbox allow-scripts",
111
+ 'referrer-policy': 'no-referrer',
112
+ })
113
+ },
114
+ }
115
+
116
+ export const prefix = []
@@ -0,0 +1,53 @@
1
+ // Host routes: the frame cache, ffmpeg transcoding and the `derived/` media prefix.
2
+ // Extracted from lib/index.js in v2.1.8.
3
+ import { sendJson, sendText, servePath } from '../http-media.js'
4
+ import { derivedPath, handleTranscode, handleTranscodeStatus } from '../transcode.js'
5
+ import { handleFrameCache, handleFrameCacheStatus } from '../media-cache.js'
6
+
7
+ export const exact = {
8
+ '_frame-cache': (ctx, req, res, url) => {
9
+ handleFrameCache(req, res, url)
10
+ },
11
+ '_frame-cache/status': (ctx, req, res) => {
12
+ handleFrameCacheStatus(req, res)
13
+ },
14
+ _transcode: (ctx, req, res, url) => {
15
+ // R4B: async handler (ffmpeg probe/run). The route writes its own response.
16
+ void handleTranscode(req, res, url).catch(() => {
17
+ try {
18
+ sendJson(res, 500, { ok: false, error: 'transcode failed' })
19
+ } catch {
20
+ // response already gone
21
+ }
22
+ })
23
+ },
24
+ '_transcode/status': (ctx, req, res) => {
25
+ void handleTranscodeStatus(req, res).catch(() => {
26
+ try {
27
+ sendJson(res, 500, { ok: false, error: 'transcode-status-failed' })
28
+ } catch {
29
+ // response already gone
30
+ }
31
+ })
32
+ },
33
+ }
34
+
35
+ export const prefix = [
36
+ [
37
+ 'derived/',
38
+ (ctx, req, res, rest) => {
39
+ // ffmpeg derivatives: derived/<fileName>. Written only by `_transcode`.
40
+ const parts = rest.split('/')
41
+ if (parts.length !== 2) {
42
+ sendText(res, 404, 'not found')
43
+ return
44
+ }
45
+ const filePath = derivedPath(parts[1])
46
+ if (filePath === null) {
47
+ sendText(res, 404, 'not found')
48
+ return
49
+ }
50
+ servePath(req, res, filePath, parts[1])
51
+ },
52
+ ],
53
+ ]
@@ -0,0 +1,54 @@
1
+ // Host routes: the `assets/` manifest, upload intake (POST `_upload`), the
2
+ // `uploads/` media prefix and the final asset fallback.
3
+ //
4
+ // Extracted from lib/index.js in v2.1.8. The fallback is exported separately because
5
+ // it is the last resort of the dispatch table, not a prefix route.
6
+ import { join } from 'node:path'
7
+ import { ASSET_DIR, SAFE_NAME } from '../media-types.js'
8
+ import { sendJson, sendText, servePath } from '../http-media.js'
9
+ import { receiveUpload, uploadPath } from '../upload.js'
10
+ import { listAssets } from './wallpaper.js'
11
+
12
+ export const exact = {
13
+ _manifest: (ctx, req, res) => {
14
+ sendJson(res, 200, { assets: listAssets() })
15
+ },
16
+ // Upload is the one write endpoint that is not JSON. It runs before the generic
17
+ // GET/HEAD gate and owns its own body limits and response framing.
18
+ _upload: (ctx, req, res, url) => {
19
+ if (req.method !== 'POST') {
20
+ sendText(res, 405, 'method not allowed')
21
+ return
22
+ }
23
+ receiveUpload(req, res, url.searchParams.get('name'), sendJson)
24
+ },
25
+ }
26
+
27
+ export const prefix = [
28
+ [
29
+ 'uploads/',
30
+ (ctx, req, res, rest) => {
31
+ // User uploads: uploads/<fileName>, served through the same Range pipeline.
32
+ const parts = rest.split('/')
33
+ if (parts.length !== 2) {
34
+ sendText(res, 404, 'not found')
35
+ return
36
+ }
37
+ const filePath = uploadPath(parts[1])
38
+ if (filePath === null) {
39
+ sendText(res, 404, 'not found')
40
+ return
41
+ }
42
+ servePath(req, res, filePath, parts[1])
43
+ },
44
+ ],
45
+ ]
46
+
47
+ /** Package-local assets: identical serving, path rooted at assets/. */
48
+ export function fallback(req, res, rest) {
49
+ if (rest === '' || rest.includes('/') || SAFE_NAME.test(rest) === false) {
50
+ sendText(res, 404, 'not found')
51
+ return
52
+ }
53
+ servePath(req, res, join(ASSET_DIR, rest), rest)
54
+ }
@@ -0,0 +1,14 @@
1
+ // Host route: the companion AI chat bridge. Extracted from lib/index.js in v2.1.8.
2
+ import { petChat } from '../pet-chat.js'
3
+
4
+ export const exact = {
5
+ // v2.0.0: the companion AI chat bridge. It owns method/body/response framing and
6
+ // resolves the optional Host `llm` / `agentDefaultModel` services per request, so
7
+ // a non-Web or older Host simply reports `{ ok:false, code }` instead of failing
8
+ // the plugin fibre. Must stay before the generic GET/HEAD gate (it is a POST).
9
+ '_pet-chat': (ctx, req, res) => {
10
+ petChat.handle(ctx, req, res)
11
+ },
12
+ }
13
+
14
+ export const prefix = []
@@ -0,0 +1,31 @@
1
+ // Host route: Wallpaper Engine scene project files. Extracted from lib/index.js in
2
+ // v2.1.8.
3
+ import { basename } from 'node:path'
4
+ import { sendText, servePath } from '../http-media.js'
5
+ import { resolveSceneDir, sceneFilePath } from '../scene-project.js'
6
+ import { readRoots } from './wallpaper.js'
7
+
8
+ export const exact = {}
9
+
10
+ export const prefix = [
11
+ [
12
+ '_scene-project/',
13
+ (ctx, req, res, rest) => {
14
+ // Scene project files. Each path segment is validated again; only media/asset
15
+ // extensions are served, and CORS is open because the adapter is opaque-origin.
16
+ const parts = rest.split('/')
17
+ const index = Number(parts[1])
18
+ const dirName = parts[2]
19
+ const projectDir = resolveSceneDir(readRoots(), index, dirName)
20
+ const filePath = projectDir === null ? null : sceneFilePath(projectDir, parts.slice(3))
21
+ if (filePath === null) {
22
+ sendText(res, 404, 'not found')
23
+ return
24
+ }
25
+ servePath(req, res, filePath, basename(filePath), {
26
+ 'access-control-allow-origin': '*',
27
+ 'cross-origin-resource-policy': 'cross-origin',
28
+ })
29
+ },
30
+ ],
31
+ ]
@@ -0,0 +1,34 @@
1
+ // Host routes: settings persistence, bundle import/export and the installed-build
2
+ // fingerprint. Extracted from lib/index.js in v2.1.8.
3
+ import { buildFingerprint, formatFingerprintLine } from '../fingerprint.js'
4
+ import { sendJson, sendText } from '../http-media.js'
5
+ import { handleBundle, handleImport } from '../bundle.js'
6
+ import { handleSettings } from '../settings-store.js'
7
+
8
+ export const exact = {
9
+ // v0.5.0 host routes (contract §6 order). Each module owns its method gate and its
10
+ // own failure status: the shared GET/HEAD gate would turn every write route into a
11
+ // blanket 405.
12
+ _settings: (ctx, req, res) => {
13
+ handleSettings(req, res)
14
+ },
15
+ _bundle: (ctx, req, res, url, rest, host) => {
16
+ handleBundle(req, res, { build: host.build })
17
+ },
18
+ _import: (ctx, req, res) => {
19
+ handleImport(req, res)
20
+ },
21
+ _fingerprint: (ctx, req, res, url, rest, host) => {
22
+ // v2.0.1: exact installed-build identity for the hub's self-test / feedback panels.
23
+ // Additive route; it carries versions, hashes and the install method only — never a
24
+ // machine path (the profile dir is reported symbolically at most by `dataMode`).
25
+ if (req.method !== 'GET') {
26
+ sendText(res, 405, 'method not allowed')
27
+ return
28
+ }
29
+ const fingerprint = buildFingerprint({ hostApi: host.hostApi, profile: host.activeProfile(), dataMode: host.dataDiagnostic().mode })
30
+ sendJson(res, 200, { ...fingerprint, line: formatFingerprintLine(fingerprint) })
31
+ },
32
+ }
33
+
34
+ export const prefix = []
@@ -0,0 +1,195 @@
1
+ // Host routes: the wallpaper catalog, the extra wallpaper roots file, and the
2
+ // `ext/<rootIndex>/<fileName>` media prefix.
3
+ //
4
+ // Extracted from lib/index.js in v2.1.8 (the handle() split). Route handlers keep the
5
+ // dispatch signature `(ctx, req, res, url, rest, host)`; the exact/prefix maps are
6
+ // assembled by lib/index.js's dispatch table in its original order.
7
+ import { readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
8
+ import { isAbsolute, join, resolve } from 'node:path'
9
+ import { ASSET_DIR, ROUTE, SAFE_NAME, fileSize, mediaKindFromName, safeJoin } from '../media-types.js'
10
+ import { WE_ROOTS_FILE } from '../host-paths.js'
11
+ import { sendJson, sendText, servePath } from '../http-media.js'
12
+ import { listUploads } from '../upload.js'
13
+ import { listSceneProjects } from '../scene-project.js'
14
+ import { listWebProjects } from '../web-project.js'
15
+ import { listDerived } from '../transcode.js'
16
+ import { listWeSkinItems } from '../we-wallpaper/host.mjs'
17
+
18
+ /** The companion art is not a wallpaper candidate. */
19
+ const COMPANION = 'cat.png'
20
+
21
+ function readRoots() {
22
+ try {
23
+ const value = JSON.parse(readFileSync(WE_ROOTS_FILE, 'utf8'))
24
+ if (!Array.isArray(value)) return []
25
+ // Absolute paths only: a relative entry would silently resolve against the DSH
26
+ // process working directory, which is not the directory the user pointed at.
27
+ return value
28
+ .filter((entry) => typeof entry === 'string' && entry.trim() !== '' && isAbsolute(entry.trim()))
29
+ .map((entry) => resolve(entry.trim()))
30
+ } catch {
31
+ return []
32
+ }
33
+ }
34
+
35
+ /** Media files in the configured roots, addressed through the ext route. */
36
+ function listExternalWallpapers() {
37
+ const items = []
38
+ readRoots().forEach((root, index) => {
39
+ let names = []
40
+ try {
41
+ names = readdirSync(root)
42
+ } catch {
43
+ return
44
+ }
45
+ for (const name of names) {
46
+ if (SAFE_NAME.test(name) === false) continue
47
+ const kind = mediaKindFromName(name)
48
+ if (kind === null) continue
49
+ // The root index is part of the id: two roots can hold the same file name, and a
50
+ // duplicate React key silently drops a card from the grid.
51
+ items.push({ id: 'ext:' + index + ':' + name, kind, url: ROUTE + '/ext/' + index + '/' + name, bytes: fileSize(join(root, name)) })
52
+ }
53
+ })
54
+ return items
55
+ }
56
+
57
+ function listAssets() {
58
+ try {
59
+ return readdirSync(ASSET_DIR).filter((name) => SAFE_NAME.test(name))
60
+ } catch {
61
+ return []
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Every file in `assets/` a user could reasonably drop in as a wallpaper. Drop a
67
+ * file, reload, it appears in the list: no config, no manifest edit. Videos rank
68
+ * first because the skin is built around a moving picture, stills are the fallback.
69
+ */
70
+ function listWallpapers() {
71
+ const items = []
72
+ for (const name of listAssets()) {
73
+ if (name === COMPANION) continue
74
+ const kind = mediaKindFromName(name)
75
+ if (kind === null) continue
76
+ items.push({ id: name, kind, url: ROUTE + '/' + name, bytes: fileSize(join(ASSET_DIR, name)) })
77
+ }
78
+ // Uploads are ordinary wallpapers once they land, so they share one sorted
79
+ // catalog instead of a second list the panel would have to merge.
80
+ const combined = [...items, ...listUploads()]
81
+ combined.sort((a, b) => (a.kind === b.kind ? a.id.localeCompare(b.id) : a.kind === 'video' ? -1 : 1))
82
+ return combined
83
+ }
84
+
85
+ /**
86
+ * Stores the extra wallpaper roots. Accepts only absolute paths that currently
87
+ * resolve to a directory, capped at 20 entries: the file is a configuration, not a
88
+ * filesystem browser, so a bad payload is rejected instead of written.
89
+ * Relative entries are dropped (not resolved against the process CWD), a body over
90
+ * the cap gets a 413 instead of a dropped connection, and the request must be JSON.
91
+ */
92
+ function writeRoots(req, res) {
93
+ const contentType = String(req.headers['content-type'] ?? '').toLowerCase()
94
+ if (contentType.includes('application/json') === false) {
95
+ sendText(res, 415, 'expected application/json')
96
+ req.resume()
97
+ return
98
+ }
99
+ const chunks = []
100
+ let size = 0
101
+ let oversized = false
102
+ req.on('data', (chunk) => {
103
+ if (oversized) return
104
+ size += chunk.length
105
+ if (size > 8192) {
106
+ oversized = true
107
+ sendText(res, 413, 'roots payload too large')
108
+ req.resume()
109
+ return
110
+ }
111
+ chunks.push(chunk)
112
+ })
113
+ req.on('end', () => {
114
+ if (oversized) return
115
+ let roots
116
+ let skipped = 0
117
+ try {
118
+ const value = JSON.parse(Buffer.concat(chunks).toString('utf8'))
119
+ if (!Array.isArray(value)) throw new Error('expected an array')
120
+ const accepted = []
121
+ for (const entry of value) {
122
+ if (typeof entry !== 'string' || entry.trim() === '') continue
123
+ const candidate = entry.trim()
124
+ if (isAbsolute(candidate) === false) {
125
+ skipped += 1
126
+ continue
127
+ }
128
+ try {
129
+ if (statSync(candidate).isDirectory()) accepted.push(resolve(candidate))
130
+ else skipped += 1
131
+ } catch {
132
+ skipped += 1
133
+ }
134
+ }
135
+ roots = accepted.slice(0, 20)
136
+ writeFileSync(WE_ROOTS_FILE, JSON.stringify(roots, null, 2), 'utf8')
137
+ } catch {
138
+ sendText(res, 400, 'invalid roots payload')
139
+ return
140
+ }
141
+ sendJson(res, 200, { roots, skipped })
142
+ })
143
+ req.on('error', () => {
144
+ try {
145
+ res.destroy()
146
+ } catch {
147
+ // ignore
148
+ }
149
+ })
150
+ }
151
+
152
+ export const exact = {
153
+ '_we-roots': (ctx, req, res) => {
154
+ if (req.method === 'POST') writeRoots(req, res)
155
+ else sendJson(res, 200, { roots: readRoots() })
156
+ },
157
+ _wallpapers: (ctx, req, res) => {
158
+ sendJson(res, 200, {
159
+ items: [
160
+ ...listWallpapers(),
161
+ ...listExternalWallpapers(),
162
+ ...listSceneProjects(readRoots()),
163
+ ...listWebProjects(readRoots()),
164
+ ...listDerived(),
165
+ // v0.6.0: the real Wallpaper Engine library, appended so every existing
166
+ // source keeps its position/id even when WE is absent (then: no items).
167
+ ...listWeSkinItems(),
168
+ ],
169
+ })
170
+ },
171
+ }
172
+
173
+ export const prefix = [
174
+ [
175
+ 'ext/',
176
+ (ctx, req, res, rest) => {
177
+ // Extra wallpaper roots, addressed as ext/<rootIndex>/<fileName>.
178
+ const parts = rest.split('/')
179
+ const index = Number(parts[1])
180
+ const roots = readRoots()
181
+ if (parts.length !== 3 || Number.isInteger(index) === false || index < 0 || index >= roots.length) {
182
+ sendText(res, 404, 'not found')
183
+ return
184
+ }
185
+ const filePath = safeJoin(roots[index], parts[2])
186
+ if (filePath === null) {
187
+ sendText(res, 404, 'not found')
188
+ return
189
+ }
190
+ servePath(req, res, filePath, parts[2])
191
+ },
192
+ ],
193
+ ]
194
+
195
+ export { listAssets, listExternalWallpapers, listWallpapers, readRoots }
@@ -0,0 +1,24 @@
1
+ // Host route: the weather proxy. Extracted from lib/index.js in v2.1.8.
2
+ import { sendJson, sendText } from '../http-media.js'
3
+ import { handleWeatherProxy } from '../weather-proxy.js'
4
+
5
+ export const exact = {
6
+ _weather: (ctx, req, res, url) => {
7
+ // v2.0.5: transport shim for networks where the renderer's TLS handshake to
8
+ // Open-Meteo is dropped. Read-only, no state, no caching. GET only: a HEAD has
9
+ // no body to return but would still spend an outbound request.
10
+ if (req.method !== 'GET') {
11
+ sendText(res, 405, 'method not allowed')
12
+ return
13
+ }
14
+ void handleWeatherProxy(url, res).catch(() => {
15
+ try {
16
+ sendJson(res, 502, { ok: false, error: 'network' })
17
+ } catch {
18
+ // response already gone
19
+ }
20
+ })
21
+ },
22
+ }
23
+
24
+ export const prefix = []
@@ -0,0 +1,17 @@
1
+ // Host route: Wallpaper Engine web projects (`_web-project/`). Extracted from
2
+ // lib/index.js in v2.1.8.
3
+ import { handleWebProject } from '../web-project.js'
4
+ import { readRoots } from './wallpaper.js'
5
+
6
+ export const exact = {}
7
+
8
+ export const prefix = [
9
+ [
10
+ '_web-project/',
11
+ (ctx, req, res, rest) => {
12
+ // Wallpaper Engine web projects (A3): an opaque-origin page plus its assets.
13
+ // Segment validation happens inside the module again; discovery is not a gate.
14
+ handleWebProject(req, res, rest, readRoots())
15
+ },
16
+ ],
17
+ ]
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-client-ui-skin-tianlight",
3
3
  "description": "Tianlight skin for the dsh web GUI: Makoto Shinkai daylight skies, an 18.5s cinematic opening film / compact splash with a 0.4x low-end tier, delayed performance fallback, optional reduced-motion override and explicit hint/Esc skip, a looping video wallpaper, a wallpaper library with upload/rotation, optional WebWallGL scene support, and a draggable Mint chibi-cat desktop companion",
4
- "version": "2.1.6",
4
+ "version": "2.1.7",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
7
7
  "bin": {
@@ -54,7 +54,7 @@
54
54
  "scripts": {
55
55
  "build": "node tools/build.mjs",
56
56
  "build:check": "node tools/build.mjs --check",
57
- "check": "node tools/build.mjs --check && node tools/test.mjs && node tools/structure.mjs --strict && node tools/audit.mjs && node tools/check-css.mjs && node tools/verify.mjs && node tools/i18n-audit.mjs",
57
+ "check": "node tools/build.mjs --check && node tools/test.mjs && node tools/structure.mjs --strict && node tools/deps.mjs --check && node tools/audit.mjs && node tools/check-css.mjs && node tools/verify.mjs && node tools/i18n-audit.mjs",
58
58
  "upgrade": "node tools/upgrade-check.mjs && node tools/hook-scan.mjs --self-check",
59
59
  "hook-scan": "node tools/hook-scan.mjs",
60
60
  "compat": "node tools/compat-matrix.mjs",
package/skin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "id": "tianlight",
3
3
  "name": "天光",
4
4
  "nameEn": "TIANLIGHT",
5
- "version": "2.1.6",
5
+ "version": "2.1.7",
6
6
  "author": "local",
7
7
  "tagline": "新海诚式天光 ・ 18.5 秒长片开机动画/简洁版(可选减少动态效果覆盖;仅提示/Esc 跳过) ・ 动态壁纸与可上传壁纸库 ・ 可选 WebWallGL 场景 ・ 薄荷小猫桌宠 ・ 职责通道(role pack → 桌宠气泡/选择) ・ 生活节奏与主动开口预算 ・ 可替换图片/≤32MiB 视频形象 ・ 液态玻璃三档 ・ AI 桌宠(严格权限) ・ 接入 DSH Agent(受控) ・ 桌宠即入口 ・ 兼容 DSH 0.2.0–0.2.2",
8
8
  "description": "天光是一套新海诚式日光天空主题:全屏循环视频壁纸与半透明天光玻璃面板,可选 18.5 秒长片或简洁版开机动画。壁纸库支持上传、轮播、标签与画面滤镜,并可接入 Wallpaper Engine 场景;桌宠「薄荷小猫」会陪你看时间、记事情、聊两句,角色中枢集中管理外观、生活节奏与权限。同一份构建适配 DSH 0.2.0 / 0.2.1 / 0.2.2。",