dsh-ccx 0.8.9 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/LICENSE +21 -21
  2. package/NOTICE +23 -23
  3. package/README.md +151 -143
  4. package/assets/icon.svg +27 -27
  5. package/cordis.patch.yml +16 -16
  6. package/lib/client.js +1481 -2244
  7. package/lib/index.js +716 -449
  8. package/lib/vendor/code-codex/ascii-tiles.js +145 -0
  9. package/lib/vendor/code-codex/aurora-ionosphere.js +7 -6
  10. package/lib/vendor/code-codex/black-hole.js +10 -7
  11. package/lib/vendor/code-codex/blinking-squares.js +6 -13
  12. package/lib/vendor/code-codex/cloud-train.js +9 -8
  13. package/lib/vendor/code-codex/galleries.json +100 -100
  14. package/lib/vendor/code-codex/glow-horizon.js +1 -1
  15. package/lib/vendor/code-codex/heavenly-cloud.js +5 -4
  16. package/lib/vendor/code-codex/milky-way.js +3 -2
  17. package/lib/vendor/code-codex/mountain.js +5 -4
  18. package/lib/vendor/code-codex/particle-image.js +435 -14
  19. package/lib/vendor/code-codex/pixel-sculpt.js +85 -5
  20. package/lib/vendor/code-codex/scene-defaults.json +94 -1
  21. package/lib/vendor/code-codex/scene-schemas.json +1008 -0
  22. package/lib/vendor/code-codex/shallow-ocean-thumbnails.json +12 -0
  23. package/lib/vendor/code-codex/shallow-ocean.js +5094 -0
  24. package/lib/vendor/code-codex/spectral-drape.js +172 -0
  25. package/package.json +70 -59
  26. package/src/client/api.ts +90 -0
  27. package/src/client/background/layer.ts +187 -0
  28. package/src/client/background/pixel-sculpt.ts +167 -0
  29. package/src/client/background/scene-runner.ts +317 -0
  30. package/src/client/background/shallow-ocean.ts +344 -0
  31. package/src/client/background/vendor-loader.ts +297 -0
  32. package/src/client/background/wallpaper.ts +87 -0
  33. package/src/client/index.ts +247 -0
  34. package/src/client/surfaces/corner-patch.ts +100 -0
  35. package/src/client/surfaces/surface-css.ts +155 -0
  36. package/src/client/ui/draft.ts +105 -0
  37. package/src/client/ui/icons.ts +47 -0
  38. package/src/client/ui/panel.ts +1524 -0
  39. package/src/client/ui/shallow-ocean-panel.ts +376 -0
  40. package/src/client/ui/styles.ts +1471 -0
  41. package/src/host/fence.ts +78 -0
  42. package/src/host/index.ts +26 -0
  43. package/src/host/routes.ts +367 -0
  44. package/src/host/storage.ts +109 -0
  45. package/src/host/window-chrome.ts +53 -0
  46. package/src/shared/constants.ts +239 -0
  47. package/src/shared/sanitize.ts +110 -0
  48. package/src/shared/types.ts +145 -0
  49. package/tsconfig.json +16 -0
@@ -0,0 +1,78 @@
1
+ import type { IncomingMessage } from 'node:http';
2
+
3
+ export interface ConnectionFenceLike {
4
+ requestRejection: (req: IncomingMessage) => number | null | undefined;
5
+ }
6
+
7
+ export interface HostContextLike {
8
+ get?: (name: string) => unknown;
9
+ connection?: unknown;
10
+ }
11
+
12
+ export function isLoopbackHostname(hn: string | undefined): boolean {
13
+ const h = String(hn || '')
14
+ .toLowerCase()
15
+ .replace(/^\[/, '')
16
+ .replace(/\]$/, '');
17
+ if (!h) return false;
18
+ if (h === 'localhost' || h.endsWith('.localhost')) return true;
19
+ if (h === '::1') return true;
20
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(h);
21
+ if (!m) return false;
22
+ if (Number(m[1]) !== 127) return false;
23
+ return [m[2], m[3], m[4]].every((x) => Number(x) <= 255);
24
+ }
25
+
26
+ function getConnectionFence(ctx: HostContextLike): ConnectionFenceLike | null {
27
+ try {
28
+ const conn = (typeof ctx.get === 'function' ? ctx.get('connection') : null) || ctx.connection;
29
+ if (
30
+ conn &&
31
+ typeof conn === 'object' &&
32
+ 'requestRejection' in conn &&
33
+ typeof (conn as ConnectionFenceLike).requestRejection === 'function'
34
+ ) {
35
+ return conn as ConnectionFenceLike;
36
+ }
37
+ return null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ }
42
+
43
+ export function selfRejection(req: IncomingMessage, ctx: HostContextLike): number | null {
44
+ try {
45
+ const headers = req?.headers || {};
46
+ let hostUrl: URL;
47
+ try {
48
+ hostUrl = new URL(`http://${String(headers.host || '')}`);
49
+ } catch {
50
+ return 403;
51
+ }
52
+
53
+ const fence = getConnectionFence(ctx);
54
+ if (fence) {
55
+ const delegated = fence.requestRejection(req);
56
+ if (delegated) return delegated;
57
+ } else if (!isLoopbackHostname(hostUrl.hostname)) {
58
+ return 403;
59
+ }
60
+
61
+ const site = String(headers['sec-fetch-site'] || '').toLowerCase();
62
+ if (site === 'cross-site') return 403;
63
+
64
+ const origin = headers.origin;
65
+ if (typeof origin === 'string' && origin && origin !== 'null') {
66
+ let originUrl: URL;
67
+ try {
68
+ originUrl = new URL(origin);
69
+ } catch {
70
+ return 403;
71
+ }
72
+ if (originUrl.host.toLowerCase() !== hostUrl.host.toLowerCase()) return 403;
73
+ }
74
+ return null;
75
+ } catch {
76
+ return 403;
77
+ }
78
+ }
@@ -0,0 +1,26 @@
1
+ import { DEFAULT_SETTINGS, PLUGIN_ID } from '../shared/constants';
2
+ import { sanitizeSettings, sanitizeSurfaces } from '../shared/sanitize';
3
+ import type { HostContextLike } from './fence';
4
+ import { registerAppearanceRoutes, type WebServerServiceLike } from './routes';
5
+ import { hideNativeMenuBar } from './window-chrome';
6
+
7
+ export { DEFAULT_SETTINGS, sanitizeSettings, sanitizeSurfaces };
8
+
9
+ export interface CordisRootLike {
10
+ inject: (
11
+ services: string[],
12
+ cb: (ctx: HostContextLike & { webServer: WebServerServiceLike }) => void,
13
+ ) => void;
14
+ effect: (fn: () => () => void, label?: string) => void;
15
+ }
16
+
17
+ export default {
18
+ name: PLUGIN_ID,
19
+ apply(root: CordisRootLike): void {
20
+ hideNativeMenuBar();
21
+ root.inject(['webServer'], (ctx) => {
22
+ const dispose = registerAppearanceRoutes(ctx);
23
+ root.effect(() => dispose, `${PLUGIN_ID}: routes`);
24
+ });
25
+ },
26
+ };
@@ -0,0 +1,367 @@
1
+ import fs from 'node:fs';
2
+ import fsp from 'node:fs/promises';
3
+ import type { IncomingMessage, ServerResponse } from 'node:http';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import {
7
+ API_BASE,
8
+ DEFAULT_SETTINGS,
9
+ MEDIA_FILE_RE,
10
+ SCENE_IDS,
11
+ WALLPAPER_MAX_BYTES,
12
+ WALLPAPER_MIMES,
13
+ } from '../shared/constants';
14
+ import { sanitizeSettings } from '../shared/sanitize';
15
+ import { selfRejection, type HostContextLike } from './fence';
16
+ import {
17
+ clearAllWallpapers,
18
+ deleteWallpaperById,
19
+ listWallpapers,
20
+ readSettings,
21
+ saveWallpaperBytes,
22
+ wallpapersDir,
23
+ writeSettings,
24
+ } from './storage';
25
+ import { menuBarDebugInfo } from './window-chrome';
26
+
27
+ export interface RouteDef {
28
+ kind: 'exact';
29
+ path: string;
30
+ handler: (req: IncomingMessage, res: ServerResponse) => unknown;
31
+ }
32
+
33
+ export interface WebServerServiceLike {
34
+ register: (route: RouteDef) => () => void;
35
+ }
36
+
37
+ function sendJson(res: ServerResponse, status: number, payload: unknown): void {
38
+ const body = JSON.stringify(payload);
39
+ res.writeHead(status, {
40
+ 'Content-Type': 'application/json; charset=utf-8',
41
+ 'Cache-Control': 'no-store',
42
+ 'Content-Length': String(Buffer.byteLength(body)),
43
+ });
44
+ res.end(body);
45
+ }
46
+
47
+ function readBody(req: IncomingMessage, maxBytes: number): Promise<Buffer> {
48
+ return new Promise((resolve, reject) => {
49
+ const chunks: Buffer[] = [];
50
+ let total = 0;
51
+ let done = false;
52
+ req.on('data', (chunk: Buffer) => {
53
+ if (done) return;
54
+ total += chunk.length;
55
+ if (total > maxBytes) {
56
+ done = true;
57
+ reject(new Error('payload too large'));
58
+ req.destroy?.();
59
+ return;
60
+ }
61
+ chunks.push(chunk);
62
+ });
63
+ req.on('end', () => {
64
+ if (!done) resolve(Buffer.concat(chunks));
65
+ });
66
+ req.on('error', (err) => {
67
+ if (!done) reject(err);
68
+ });
69
+ });
70
+ }
71
+
72
+ function resolveVendorDir(): string {
73
+ const here = path.dirname(fileURLToPath(import.meta.url));
74
+ // Bundled output sits in lib/index.js; source tests may run from src/host/routes.ts
75
+ const direct = path.join(here, 'vendor', 'code-codex');
76
+ if (fs.existsSync(direct)) return direct;
77
+ return path.resolve(here, '../../lib/vendor/code-codex');
78
+ }
79
+
80
+ function parseByteRange(rangeHeader: string | undefined, size: number): { start: number; end: number } | 'invalid' | null {
81
+ if (!rangeHeader) return null;
82
+ const m = /^bytes=(\d*)-(\d*)$/i.exec(rangeHeader.trim());
83
+ if (!m) return 'invalid';
84
+ const rawStart = m[1];
85
+ const rawEnd = m[2];
86
+ if (rawStart === '' && rawEnd === '') return 'invalid';
87
+ let start: number;
88
+ let end: number;
89
+ if (rawStart === '') {
90
+ const suffixLen = Number(rawEnd);
91
+ if (!Number.isFinite(suffixLen) || suffixLen <= 0) return 'invalid';
92
+ start = Math.max(0, size - suffixLen);
93
+ end = size - 1;
94
+ } else {
95
+ start = Number(rawStart);
96
+ end = rawEnd === '' ? size - 1 : Math.min(size - 1, Number(rawEnd));
97
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 0 || start > end || start >= size) {
98
+ return 'invalid';
99
+ }
100
+ }
101
+ return { start, end };
102
+ }
103
+
104
+ async function sendFileRangeAware(
105
+ req: IncomingMessage,
106
+ res: ServerResponse,
107
+ filePath: string,
108
+ mime: string,
109
+ ): Promise<void> {
110
+ const st = await fsp.stat(filePath);
111
+ const size = st.size;
112
+ const range = parseByteRange(req.headers?.range, size);
113
+ if (range === 'invalid') {
114
+ res.writeHead(416, { 'Content-Range': `bytes */${size}`, 'Content-Length': '0' });
115
+ res.end();
116
+ return;
117
+ }
118
+ const canPipe = typeof (res as unknown as { write?: unknown }).write === 'function' && typeof res.on === 'function';
119
+ if (range) {
120
+ const len = range.end - range.start + 1;
121
+ res.writeHead(206, {
122
+ 'Content-Type': mime,
123
+ 'Accept-Ranges': 'bytes',
124
+ 'Content-Range': `bytes ${range.start}-${range.end}/${size}`,
125
+ 'Content-Length': String(len),
126
+ 'Cache-Control': 'no-store',
127
+ });
128
+ if (canPipe) {
129
+ fs.createReadStream(filePath, { start: range.start, end: range.end }).pipe(res);
130
+ } else {
131
+ const fh = await fsp.open(filePath, 'r');
132
+ try {
133
+ const buf = Buffer.allocUnsafe(len);
134
+ await fh.read(buf, 0, len, range.start);
135
+ res.end(buf);
136
+ } finally {
137
+ await fh.close();
138
+ }
139
+ }
140
+ return;
141
+ }
142
+
143
+ res.writeHead(200, {
144
+ 'Content-Type': mime,
145
+ 'Accept-Ranges': 'bytes',
146
+ 'Content-Length': String(size),
147
+ 'Cache-Control': 'no-store',
148
+ });
149
+ if (canPipe) {
150
+ fs.createReadStream(filePath).pipe(res);
151
+ } else {
152
+ res.end(await fsp.readFile(filePath));
153
+ }
154
+ }
155
+
156
+ export function registerAppearanceRoutes(
157
+ ctx: HostContextLike & { webServer: WebServerServiceLike },
158
+ ): () => void {
159
+ const disposers: Array<() => void> = [];
160
+ const vendorDir = resolveVendorDir();
161
+
162
+ function registerRoute(route: RouteDef): void {
163
+ const inner = route.handler;
164
+ disposers.push(
165
+ ctx.webServer.register({
166
+ kind: route.kind,
167
+ path: route.path,
168
+ handler: async (req, res) => {
169
+ const code = selfRejection(req, ctx);
170
+ if (code) {
171
+ sendJson(res, code, { ok: false, error: 'rejected by trust fence' });
172
+ return;
173
+ }
174
+ return inner(req, res);
175
+ },
176
+ }),
177
+ );
178
+ }
179
+
180
+ const serveVendorFile = (file: string, contentType: string) => async (_req: IncomingMessage, res: ServerResponse) => {
181
+ try {
182
+ const bytes = await fsp.readFile(path.join(vendorDir, file));
183
+ res.writeHead(200, {
184
+ 'Content-Type': contentType,
185
+ 'Cache-Control': 'no-store',
186
+ 'Content-Length': String(bytes.length),
187
+ });
188
+ res.end(bytes);
189
+ } catch (err) {
190
+ const msg = err instanceof Error ? err.message : String(err);
191
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 120) });
192
+ }
193
+ };
194
+
195
+ registerRoute({
196
+ kind: 'exact',
197
+ path: `${API_BASE}/wininfo.json`,
198
+ handler: (_req, res) => sendJson(res, 200, { ok: true, win: menuBarDebugInfo() }),
199
+ });
200
+
201
+ for (const sceneId of SCENE_IDS) {
202
+ registerRoute({
203
+ kind: 'exact',
204
+ path: `${API_BASE}/vendor/${sceneId}.js`,
205
+ handler: serveVendorFile(`${sceneId}.js`, 'text/javascript; charset=utf-8'),
206
+ });
207
+ }
208
+
209
+ registerRoute({
210
+ kind: 'exact',
211
+ path: `${API_BASE}/vendor-galleries.json`,
212
+ handler: serveVendorFile('galleries.json', 'application/json; charset=utf-8'),
213
+ });
214
+
215
+ registerRoute({
216
+ kind: 'exact',
217
+ path: `${API_BASE}/vendor-shallow-ocean-thumbs.json`,
218
+ handler: serveVendorFile('shallow-ocean-thumbnails.json', 'application/json; charset=utf-8'),
219
+ });
220
+
221
+ registerRoute({
222
+ kind: 'exact',
223
+ path: `${API_BASE}/vendor-media`,
224
+ handler: async (req, res) => {
225
+ try {
226
+ const u = new URL(req.url || '/', 'http://localhost');
227
+ const name = u.searchParams.get('file') || '';
228
+ const match = MEDIA_FILE_RE.exec(name);
229
+ if (!match) throw new Error('bad media file');
230
+ const bytes = await fsp.readFile(path.join(vendorDir, match[1], 'media', name));
231
+ res.writeHead(200, {
232
+ 'Content-Type': 'image/png',
233
+ 'Cache-Control': 'no-store',
234
+ 'Content-Length': String(bytes.length),
235
+ });
236
+ res.end(bytes);
237
+ } catch (err) {
238
+ const msg = err instanceof Error ? err.message : String(err);
239
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 120) });
240
+ }
241
+ },
242
+ });
243
+
244
+ registerRoute({
245
+ kind: 'exact',
246
+ path: `${API_BASE}/scene-schemas.json`,
247
+ handler: serveVendorFile('scene-schemas.json', 'application/json; charset=utf-8'),
248
+ });
249
+
250
+ registerRoute({
251
+ kind: 'exact',
252
+ path: `${API_BASE}/state.json`,
253
+ handler: (_req, res) => {
254
+ const settings = readSettings();
255
+ const wallpapers = listWallpapers();
256
+ sendJson(res, 200, {
257
+ ok: true,
258
+ settings,
259
+ defaults: DEFAULT_SETTINGS,
260
+ scenes: SCENE_IDS,
261
+ wallpapers,
262
+ });
263
+ },
264
+ });
265
+
266
+ registerRoute({
267
+ kind: 'exact',
268
+ path: `${API_BASE}/state-save.json`,
269
+ handler: async (req, res) => {
270
+ try {
271
+ const raw = await readBody(req, 64 * 1024);
272
+ const parsed = JSON.parse(raw.toString('utf8')) as { settings?: unknown };
273
+ const settings = sanitizeSettings(parsed?.settings ?? parsed);
274
+ settings.savedAt = Date.now();
275
+ writeSettings(settings);
276
+ sendJson(res, 200, { ok: true, settings });
277
+ } catch (err) {
278
+ const msg = err instanceof Error ? err.message : String(err);
279
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
280
+ }
281
+ },
282
+ });
283
+
284
+ registerRoute({
285
+ kind: 'exact',
286
+ path: `${API_BASE}/wallpaper-upload`,
287
+ handler: async (req, res) => {
288
+ try {
289
+ if (req.method !== 'POST') throw new Error('method not allowed');
290
+ const u = new URL(req.url || '/', 'http://localhost');
291
+ const rawName = String(u.searchParams.get('name') || '');
292
+ const ext = path.extname(rawName).toLowerCase();
293
+ if (!WALLPAPER_MIMES[ext]) throw new Error(`unsupported file type: ${ext || '(none)'}`);
294
+ const bytes = await readBody(req, WALLPAPER_MAX_BYTES);
295
+ if (!bytes.length) throw new Error('empty body');
296
+ const item = await saveWallpaperBytes(ext, bytes);
297
+ sendJson(res, 200, {
298
+ ok: true,
299
+ wallpaper: item,
300
+ wallpapers: listWallpapers(),
301
+ });
302
+ } catch (err) {
303
+ const msg = err instanceof Error ? err.message : String(err);
304
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
305
+ }
306
+ },
307
+ });
308
+
309
+ registerRoute({
310
+ kind: 'exact',
311
+ path: `${API_BASE}/wallpaper-delete.json`,
312
+ handler: async (req, res) => {
313
+ try {
314
+ const raw = await readBody(req, 4 * 1024);
315
+ const parsed = JSON.parse(raw.toString('utf8')) as { id?: unknown };
316
+ const id = String(parsed?.id ?? '');
317
+ if (!/^[\w-]+$/.test(id)) throw new Error('bad wallpaper id');
318
+ await deleteWallpaperById(id);
319
+ sendJson(res, 200, { ok: true, wallpapers: listWallpapers() });
320
+ } catch (err) {
321
+ const msg = err instanceof Error ? err.message : String(err);
322
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
323
+ }
324
+ },
325
+ });
326
+
327
+ registerRoute({
328
+ kind: 'exact',
329
+ path: `${API_BASE}/wallpaper-clear.json`,
330
+ handler: async (_req, res) => {
331
+ try {
332
+ await clearAllWallpapers();
333
+ sendJson(res, 200, { ok: true, wallpapers: [] });
334
+ } catch (err) {
335
+ const msg = err instanceof Error ? err.message : String(err);
336
+ sendJson(res, 400, { ok: false, error: msg.slice(0, 200) });
337
+ }
338
+ },
339
+ });
340
+
341
+ const serveWallpaper = async (req: IncomingMessage, res: ServerResponse) => {
342
+ try {
343
+ const u = new URL(req.url || '/', 'http://localhost');
344
+ const id = String(u.searchParams.get('id') || '');
345
+ if (!/^[\w-]+$/.test(id)) throw new Error('bad wallpaper id');
346
+ const item = listWallpapers().find((w) => w.id === id);
347
+ if (!item) throw new Error('wallpaper not found');
348
+ await sendFileRangeAware(req, res, path.join(wallpapersDir(), item.name), item.mime);
349
+ } catch (err) {
350
+ const msg = err instanceof Error ? err.message : String(err);
351
+ sendJson(res, 404, { ok: false, error: msg.slice(0, 200) });
352
+ }
353
+ };
354
+
355
+ registerRoute({ kind: 'exact', path: `${API_BASE}/wallpaper`, handler: serveWallpaper });
356
+ registerRoute({ kind: 'exact', path: `${API_BASE}/wallpaper.png`, handler: serveWallpaper });
357
+
358
+ return () => {
359
+ for (const d of disposers) {
360
+ try {
361
+ d();
362
+ } catch {
363
+ /* ignore cleanup errors */
364
+ }
365
+ }
366
+ };
367
+ }
@@ -0,0 +1,109 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import fsp from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+ import { API_BASE, DEFAULT_SETTINGS, WALLPAPER_MIMES } from '../shared/constants';
7
+ import { sanitizeSettings } from '../shared/sanitize';
8
+ import type { AppearanceSettings, WallpaperItem } from '../shared/types';
9
+
10
+ export function dshHome(): string {
11
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh');
12
+ }
13
+
14
+ export function dataDir(): string {
15
+ return path.join(dshHome(), 'appearances');
16
+ }
17
+
18
+ export function wallpapersDir(): string {
19
+ return path.join(dataDir(), 'wallpapers');
20
+ }
21
+
22
+ export function settingsPath(): string {
23
+ return path.join(dataDir(), 'settings.json');
24
+ }
25
+
26
+ export function wallpaperUrl(id: string): string {
27
+ return `${API_BASE}/wallpaper?id=${encodeURIComponent(id)}`;
28
+ }
29
+
30
+ export function cloneDefaultSettings(): AppearanceSettings {
31
+ return {
32
+ ...DEFAULT_SETTINGS,
33
+ surfaces: { ...DEFAULT_SETTINGS.surfaces },
34
+ sceneParams: {},
35
+ };
36
+ }
37
+
38
+ export function readSettings(): AppearanceSettings {
39
+ try {
40
+ return sanitizeSettings(JSON.parse(fs.readFileSync(settingsPath(), 'utf8')));
41
+ } catch {
42
+ return cloneDefaultSettings();
43
+ }
44
+ }
45
+
46
+ export function writeSettings(value: AppearanceSettings): void {
47
+ fs.mkdirSync(dataDir(), { recursive: true });
48
+ const target = settingsPath();
49
+ const tmp = `${target}.tmp-${process.pid}-${Date.now()}`;
50
+ fs.writeFileSync(tmp, JSON.stringify(value, null, 2));
51
+ fs.renameSync(tmp, target);
52
+ }
53
+
54
+ export function listWallpapers(): WallpaperItem[] {
55
+ const dir = wallpapersDir();
56
+ let entries: string[];
57
+ try {
58
+ entries = fs.readdirSync(dir);
59
+ } catch {
60
+ return [];
61
+ }
62
+ const items: WallpaperItem[] = [];
63
+ for (const name of entries) {
64
+ const ext = path.extname(name).toLowerCase();
65
+ const mime = WALLPAPER_MIMES[ext];
66
+ if (!mime) continue;
67
+ const id = name.slice(0, name.length - ext.length);
68
+ try {
69
+ const st = fs.statSync(path.join(dir, name));
70
+ if (!st.isFile()) continue;
71
+ items.push({ id, name, mime, size: st.size, mtimeMs: st.mtimeMs, url: wallpaperUrl(id) });
72
+ } catch {
73
+ /* ignore vanishing file */
74
+ }
75
+ }
76
+ items.sort((a, b) => (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0));
77
+ return items;
78
+ }
79
+
80
+ export async function saveWallpaperBytes(ext: string, bytes: Buffer): Promise<WallpaperItem> {
81
+ const dir = wallpapersDir();
82
+ await fsp.mkdir(dir, { recursive: true });
83
+ const id = crypto.randomBytes(8).toString('hex');
84
+ const name = id + ext;
85
+ const file = path.join(dir, name);
86
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
87
+ await fsp.writeFile(tmp, bytes);
88
+ await fsp.rename(tmp, file);
89
+ return {
90
+ id,
91
+ name,
92
+ mime: WALLPAPER_MIMES[ext],
93
+ size: bytes.length,
94
+ url: wallpaperUrl(id),
95
+ };
96
+ }
97
+
98
+ export async function deleteWallpaperById(id: string): Promise<void> {
99
+ const item = listWallpapers().find((w) => w.id === id);
100
+ if (!item) return;
101
+ await fsp.rm(path.join(wallpapersDir(), item.name), { force: true });
102
+ }
103
+
104
+ export async function clearAllWallpapers(): Promise<void> {
105
+ const items = listWallpapers();
106
+ await Promise.all(
107
+ items.map((w) => fsp.rm(path.join(wallpapersDir(), w.name), { force: true })),
108
+ );
109
+ }
@@ -0,0 +1,53 @@
1
+ import { createRequire } from 'node:module';
2
+
3
+ const require = createRequire(import.meta.url);
4
+
5
+ interface ElectronBrowserWindowLike {
6
+ setAutoHideMenuBar?: (hide: boolean) => void;
7
+ setMenuBarVisibility?: (visible: boolean) => void;
8
+ isMenuBarVisible?: () => boolean;
9
+ isMenuBarAutoHide?: () => boolean;
10
+ getBounds?: () => unknown;
11
+ getContentBounds?: () => unknown;
12
+ }
13
+
14
+ export function withWindows(fn: (win: ElectronBrowserWindowLike) => void): void {
15
+ try {
16
+ const electron = require('electron') as {
17
+ BrowserWindow?: { getAllWindows: () => ElectronBrowserWindowLike[] };
18
+ };
19
+ const windows = electron?.BrowserWindow ? electron.BrowserWindow.getAllWindows() : [];
20
+ for (const win of windows) {
21
+ try {
22
+ fn(win);
23
+ } catch {
24
+ /* single window failure must not break remaining windows */
25
+ }
26
+ }
27
+ } catch {
28
+ /* electron unavailable (headless / non-main process / unit test) */
29
+ }
30
+ }
31
+
32
+ export function hideNativeMenuBar(): void {
33
+ // Windows DSH 0.2.2-rc.5+ uses custom in-renderer titleBarStyle:'hidden';
34
+ // Linux and legacy 0.2.1 windows still benefit from auto-hiding the native menu bar.
35
+ withWindows((win) => {
36
+ if (typeof win.setAutoHideMenuBar === 'function') win.setAutoHideMenuBar(true);
37
+ if (typeof win.setMenuBarVisibility === 'function') win.setMenuBarVisibility(false);
38
+ });
39
+ }
40
+
41
+ export function menuBarDebugInfo(): Record<string, unknown> {
42
+ let out: Record<string, unknown> = { error: 'no-window', platform: process.platform };
43
+ withWindows((win) => {
44
+ out = {
45
+ platform: process.platform,
46
+ menuBarVisible: typeof win.isMenuBarVisible === 'function' ? win.isMenuBarVisible() : null,
47
+ menuBarAutoHide: typeof win.isMenuBarAutoHide === 'function' ? win.isMenuBarAutoHide() : null,
48
+ bounds: typeof win.getBounds === 'function' ? win.getBounds() : null,
49
+ contentBounds: typeof win.getContentBounds === 'function' ? win.getContentBounds() : null,
50
+ };
51
+ });
52
+ return out;
53
+ }