-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathindex.js
More file actions
748 lines (645 loc) · 22.2 KB
/
Copy pathindex.js
File metadata and controls
748 lines (645 loc) · 22.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
const nativeBinding = require('./js-bindings.js');
const { EventEmitter } = require('events');
// ── Notifications ───────────────────────────────────────────────────────────
class Notification {
#emitter = new EventEmitter();
#native;
#handlers = new Map();
#options;
#title;
constructor(title, options = {}) {
if (options.image !== undefined && typeof options.image !== 'string' && !Buffer.isBuffer(options.image)) {
throw new TypeError('Notification image must be a file path string or Buffer');
}
if (options.actions !== undefined && !Array.isArray(options.actions)) {
throw new TypeError('Notification actions must be an array');
}
const persistent = options.persistent ?? false;
const actions = (options.actions ?? []).map((action) => ({
action: String(action.action),
title: String(action.title),
icon: action.icon === undefined ? '' : String(action.icon),
}));
if (actions.length > 0 && !persistent) {
throw new TypeError('Notification actions require persistent: true');
}
this.#title = String(title);
this.#options = {
body: options.body ?? '',
icon: options.icon ?? '',
image: options.image ?? '',
badge: options.badge ?? '',
tag: options.tag ?? '',
data: options.data,
dir: options.dir ?? 'auto',
lang: options.lang ?? '',
renotify: options.renotify ?? false,
requireInteraction: options.requireInteraction ?? false,
persistent,
actions,
silent: options.silent ?? false,
timestamp: options.timestamp ?? Date.now(),
vibrate: options.vibrate ?? [],
};
this.#native = new nativeBinding.NativeNotification(
{
title: this.#title,
body: this.#options.body || undefined,
icon: this.#options.icon || undefined,
imagePath: typeof this.#options.image === 'string' ? this.#options.image || undefined : undefined,
imageData: Buffer.isBuffer(this.#options.image) ? this.#options.image : undefined,
requireInteraction: this.#options.requireInteraction,
persistent: this.#options.persistent,
actions: this.#options.actions.map(({ action, title, icon }) => ({
action,
title,
icon: icon || undefined,
})),
},
(error, payload) => {
if (error) {
this.#dispatch({ event: 'error', error: error.message });
} else {
this.#dispatch(payload);
}
},
);
}
static get permission() {
return 'granted';
}
static requestPermission() {
return Promise.resolve('granted');
}
#dispatch(payload) {
const type = payload.event;
const event = {
type,
target: this,
action: payload.action,
error: payload.error === undefined ? undefined : new Error(payload.error),
};
this.#emitter.emit(type, event);
this.#handlers.get(type)?.call(this, event);
}
close() {
this.#native.close();
}
on(event, listener) {
this.#emitter.on(event, listener);
return this;
}
once(event, listener) {
this.#emitter.once(event, listener);
return this;
}
off(event, listener) {
this.#emitter.off(event, listener);
return this;
}
addListener(event, listener) {
this.#emitter.addListener(event, listener);
return this;
}
removeListener(event, listener) {
this.#emitter.removeListener(event, listener);
return this;
}
removeAllListeners(event) {
this.#emitter.removeAllListeners(event);
return this;
}
listenerCount(event, listener) {
return this.#emitter.listenerCount(event, listener);
}
listeners(event) {
return this.#emitter.listeners(event);
}
rawListeners(event) {
return this.#emitter.rawListeners(event);
}
emit(event, ...args) {
return this.#emitter.emit(event, ...args);
}
eventNames() {
return this.#emitter.eventNames();
}
get title() {
return this.#title;
}
get body() {
return this.#options.body;
}
get icon() {
return this.#options.icon;
}
get image() {
return this.#options.image;
}
get badge() {
return this.#options.badge;
}
get tag() {
return this.#options.tag;
}
get data() {
return this.#options.data;
}
get dir() {
return this.#options.dir;
}
get lang() {
return this.#options.lang;
}
get renotify() {
return this.#options.renotify;
}
get requireInteraction() {
return this.#options.requireInteraction;
}
get persistent() {
return this.#options.persistent;
}
get actions() {
return this.#options.actions;
}
get silent() {
return this.#options.silent;
}
get timestamp() {
return this.#options.timestamp;
}
get vibrate() {
return this.#options.vibrate;
}
get onclick() {
return this.#handlers.get('click') ?? null;
}
set onclick(listener) {
this.#setHandler('click', listener);
}
get onclose() {
return this.#handlers.get('close') ?? null;
}
set onclose(listener) {
this.#setHandler('close', listener);
}
get onerror() {
return this.#handlers.get('error') ?? null;
}
set onerror(listener) {
this.#setHandler('error', listener);
}
get onshow() {
return this.#handlers.get('show') ?? null;
}
set onshow(listener) {
this.#setHandler('show', listener);
}
#setHandler(type, listener) {
if (listener == null) {
this.#handlers.delete(type);
return;
}
if (typeof listener !== 'function') {
throw new TypeError(`on${type} must be a function or null`);
}
this.#handlers.set(type, listener);
}
}
// Patch the native Application prototype with non-blocking run/stop.
// A WeakMap stores each instance's timer so no extra class wrapper is needed.
const _timers = new WeakMap();
nativeBinding.Application.prototype.run = function run(options = {}) {
const interval = options.interval ?? 16;
const shouldRef = options.ref ?? true;
if (_timers.has(this)) return;
const timer = setInterval(() => {
if (!this.pumpEvents()) this.stop();
}, interval);
if (!shouldRef) timer.unref();
_timers.set(this, timer);
};
nativeBinding.Application.prototype.stop = function stop() {
const timer = _timers.get(this);
if (timer === undefined) return;
clearInterval(timer);
_timers.delete(this);
};
const _nativeExit = nativeBinding.Application.prototype.exit;
nativeBinding.Application.prototype.exit = function exit() {
this.stop();
return _nativeExit.call(this);
};
nativeBinding.Application.prototype[Symbol.dispose] = function dispose() {
this.exit();
};
for (const Type of [
nativeBinding.BrowserWindow,
nativeBinding.Webview,
nativeBinding.WebContext,
nativeBinding.TrayIcon,
]) {
if (Type?.prototype?.dispose) {
Type.prototype[Symbol.dispose] = function dispose() {
this.dispose();
};
}
}
for (const Type of [
nativeBinding.BrowserWindow,
nativeBinding.Webview,
nativeBinding.WebContext,
nativeBinding.TrayIcon,
]) {
if (!Type?.prototype?.isDisposed) continue;
for (const name of Object.getOwnPropertyNames(Type.prototype)) {
if (name === 'constructor' || name === 'dispose' || name === 'isDisposed') continue;
const descriptor = Object.getOwnPropertyDescriptor(Type.prototype, name);
if (typeof descriptor?.value !== 'function') continue;
const nativeMethod = descriptor.value;
Type.prototype[name] = function (...args) {
if (this.isDisposed()) {
throw new Error(`${Type.name} has been disposed`);
}
return nativeMethod.apply(this, args);
};
}
}
// ── TrayIcon EventEmitter ────────────────────────────────────────────────────
const _trayEmitters = new WeakMap();
function _getTrayEmitter(tray) {
if (!_trayEmitters.has(tray)) {
const emitter = new EventEmitter();
_trayEmitters.set(tray, emitter);
tray._onTrayEvent(function (payload) {
emitter.emit(payload.event, payload);
});
}
return _trayEmitters.get(tray);
}
[
'on',
'once',
'off',
'addListener',
'removeListener',
'removeAllListeners',
'listenerCount',
'listeners',
'rawListeners',
'emit',
'eventNames',
].forEach((method) => {
nativeBinding.TrayIcon.prototype[method] = function (...args) {
const emitter = _getTrayEmitter(this);
const result = emitter[method](...args);
return result === emitter ? this : result;
};
});
// ── Application EventEmitter ─────────────────────────────────────────────────
// Maps WebviewApplicationEvent numeric values (from Rust enum order) to names.
const _applicationEventNames = [
'window-close-requested', // 0 WindowCloseRequested
'application-close-requested', // 1 ApplicationCloseRequested
'custom-menu-click', // 2 CustomMenuClick
'ready', // 3 Ready
];
const _applicationEmitters = new WeakMap();
function _getApplicationEmitter(app) {
if (!_applicationEmitters.has(app)) {
const emitter = new EventEmitter();
_applicationEmitters.set(app, emitter);
app.onEvent(function (payload) {
const name = _applicationEventNames[payload.event];
if (name !== undefined) emitter.emit(name, payload);
});
}
return _applicationEmitters.get(app);
}
nativeBinding.Application.prototype.whenReady = function whenReady(options = {}) {
const { autoRun = true, interval, ref } = options;
if (!autoRun) {
if (Object.prototype.hasOwnProperty.call(options, 'interval')) {
throw new TypeError('interval is not supported when autoRun is false');
}
if (Object.prototype.hasOwnProperty.call(options, 'ref')) {
throw new TypeError('ref is not supported when autoRun is false');
}
}
const ready = this.isReady()
? Promise.resolve()
: new Promise((resolve) => {
nativeBinding.Application.prototype.once.call(this, 'ready', resolve);
});
if (autoRun) {
const runOptions = {};
if (interval !== undefined) runOptions.interval = interval;
if (ref !== undefined) runOptions.ref = ref;
this.run(runOptions);
}
return ready;
};
[
'on',
'once',
'off',
'addListener',
'removeListener',
'removeAllListeners',
'listenerCount',
'listeners',
'rawListeners',
'emit',
'eventNames',
].forEach((method) => {
nativeBinding.Application.prototype[method] = function (...args) {
const emitter = _getApplicationEmitter(this);
const result = emitter[method](...args);
return result === emitter ? this : result;
};
});
// ── BrowserWindow EventEmitter ────────────────────────────────────────────────
// Maps WindowEventType numeric values (from Rust enum order) to event names.
const _windowEventNames = [
'move', // 0 Moved
'resize', // 1 Resized
'close', // 2 CloseRequested
'focus', // 3 Focused
'blur', // 4 Blurred
'mouse-enter', // 5 MouseEnter
'mouse-leave', // 6 MouseLeave
'mouse-move', // 7 MouseMove
'mouse-down', // 8 MouseDown
'mouse-up', // 9 MouseUp
'scroll', // 10 Scroll
'key-down', // 11 KeyDown
'key-up', // 12 KeyUp
'file-drop', // 13 FileDrop
'file-hover', // 14 FileHover
'file-hover-cancelled', // 15 FileHoverCancelled
'scale-factor-changed', // 16 ScaleFactorChanged
'theme-changed', // 17 ThemeChanged
'ime', // 18 Ime
'touch', // 19 Touch
];
const _windowEmitters = new WeakMap();
function _getWindowEmitter(win) {
if (!_windowEmitters.has(win)) {
const emitter = new EventEmitter();
_windowEmitters.set(win, emitter);
win._onWindowEvent(function (payload) {
const name = _windowEventNames[payload.event];
if (name !== undefined) emitter.emit(name, payload);
});
}
return _windowEmitters.get(win);
}
[
'on',
'once',
'off',
'addListener',
'removeListener',
'removeAllListeners',
'listenerCount',
'listeners',
'rawListeners',
'emit',
'eventNames',
].forEach((method) => {
nativeBinding.BrowserWindow.prototype[method] = function (...args) {
const result = _getWindowEmitter(this)[method](...args);
// Return `this` for chainable methods, otherwise the emitter's return value.
return result === _getWindowEmitter(this) ? this : result;
};
});
// ── BrowserWindow.registerProtocol ───────────────────────────────────────────
// Wraps the low-level `_registerProtocol(name, (payloadJson) => void)` native
// API with a clean async handler: `(request: Request) => Promise<Response>`.
// The handler receives a global `Request` object and should return a global
// `Response` (or a legacy `CustomProtocolResponse` plain object for compat).
// This allows frameworks like Hono to be used directly:
// win.registerProtocol('app', (req) => honoApp.fetch(req));
nativeBinding.BrowserWindow.prototype.registerProtocol = function registerProtocol(name, asyncHandler) {
const win = this;
win._registerProtocol(name, function (payloadJson) {
let parsed;
try {
parsed = JSON.parse(payloadJson);
} catch {
return;
}
const { id, url, method, headers: rawHeaders, body: bodyArr } = parsed;
// Build a global Headers object
const headersObj = new Headers();
for (const { key, value } of rawHeaders ?? []) {
if (value != null) headersObj.set(key, value);
}
// Build a global Request — GET/HEAD cannot carry a body
const canHaveBody = !['GET', 'HEAD'].includes(method.toUpperCase());
const reqInit = { method, headers: headersObj };
if (canHaveBody && Array.isArray(bodyArr) && bodyArr.length > 0) {
reqInit.body = Buffer.from(bodyArr);
}
const request = new Request(url, reqInit);
Promise.resolve(asyncHandler(request))
.then(async (resp) => {
// Accept a global Response object (from Hono / fetch-compatible handlers)
if (typeof Response !== 'undefined' && resp instanceof Response) {
const bodyBuf = Buffer.from(await resp.arrayBuffer());
const contentType = resp.headers.get('content-type') ?? 'application/octet-stream';
const extraHeaders = [];
resp.headers.forEach((value, key) => {
if (key.toLowerCase() !== 'content-type') extraHeaders.push({ key, value });
});
return win._completeProtocol(id, {
statusCode: resp.status,
body: bodyBuf,
mimeType: contentType,
headers: extraHeaders,
});
}
// Legacy CustomProtocolResponse plain object
return win._completeProtocol(id, resp);
})
.catch((err) =>
win._completeProtocol(id, {
statusCode: 500,
body: Buffer.from(String(err?.message ?? err)),
mimeType: 'text/plain',
}),
);
});
};
// ── Webview EventEmitter ──────────────────────────────────────────────────────
// Maps WebviewEventType numeric values (Rust enum order) to JS event names.
const _webviewEventNames = [
'page-load-started', // 0 PageLoadStarted
'page-load-finished', // 1 PageLoadFinished
'title-changed', // 2 TitleChanged
'download-started', // 3 DownloadStarted
'download-completed', // 4 DownloadCompleted
'navigation', // 5 NavigationStarted
'new-window', // 6 NewWindowRequested
];
const _webviewEmitters = new WeakMap();
function _attachWebviewEmitter(webview, emitter) {
[
'on',
'once',
'off',
'addListener',
'removeListener',
'removeAllListeners',
'listenerCount',
'listeners',
'rawListeners',
'emit',
'eventNames',
].forEach((method) => {
webview[method] = function (...args) {
const result = emitter[method](...args);
return result === emitter ? webview : result;
};
});
_webviewEmitters.set(webview, emitter);
}
// ── BrowserWindow.createWebview wrapper ──────────────────────────────────────
// Intercepts `createWebview(options)` to:
// - Extract `webContext` and `navigationHandler` from options
// - Pre-register event dispatch and sync guard callbacks before the native build
// - Attach an EventEmitter to the returned Webview
const _nativeCreateWebview = nativeBinding.BrowserWindow.prototype.createWebview;
nativeBinding.BrowserWindow.prototype.createWebview = function createWebview(opts) {
const { webContext = null, navigationHandler = null, ...rustOpts } = opts ?? {};
const emitter = new EventEmitter();
// Always pre-register the event dispatch; the wry handlers call it for every
// page-load / title / download / navigation event.
this._setPendingWebviewEventCallback(function (error, payload) {
if (error) throw error;
const name = _webviewEventNames[payload.event];
if (name !== undefined) emitter.emit(name, payload);
});
if (typeof navigationHandler === 'function') {
this._setPendingWebviewNavigationHandler(navigationHandler);
}
const webview = _nativeCreateWebview.call(this, rustOpts, webContext);
// Clear so subsequent createWebview calls start with a clean slate.
this._clearPendingWebviewHandlers();
_attachWebviewEmitter(webview, emitter);
return webview;
};
// ── Webview.expose ────────────────────────────────────────────────────────────
// Injects a proxy object at `window[name]` in the page.
// Static (non-function) properties are serialised once at call time.
// Every function call from the page side is async (returns a Promise).
// Throws SerializationError for non-JSON-serialisable args or return values.
class SerializationError extends Error {
constructor(msg) {
super(msg);
this.name = 'SerializationError';
}
}
const _exposedNamespaces = new WeakMap();
function jsonValue(value, context) {
try {
const json = JSON.stringify(value);
if (json === undefined) throw new TypeError('JSON.stringify returned undefined');
return json;
} catch {
throw new SerializationError(`${context} is not JSON-serialisable`);
}
}
function sendExposeError(webview, id, message, name = 'Error') {
webview.evaluateScript(
`window.__webviewjs__&&window.__webviewjs__.reject(${Number(id)},${JSON.stringify(String(message))},${JSON.stringify(name)})`,
);
}
nativeBinding.Webview.prototype.expose = function expose(name, target) {
const self = this;
if (!/^[A-Za-z_$][\w$]*$/u.test(name)) {
throw new TypeError('expose(): name must be a valid JavaScript identifier');
}
if (target === null || (typeof target !== 'object' && typeof target !== 'function')) {
throw new TypeError('expose(): target must be an object');
}
const namespaces = _exposedNamespaces.get(self) ?? new Set();
if (namespaces.has(name)) {
throw new Error(`expose(): namespace "${name}" is already registered`);
}
const statics = {};
const functions = new Map();
for (const [k, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(target))) {
if (!descriptor.enumerable || !Object.hasOwn(descriptor, 'value')) continue;
const { value: v } = descriptor;
if (typeof v === 'function') {
functions.set(k, v);
} else {
JSON.parse(jsonValue(v, `expose(): value for property "${k}"`));
statics[k] = v;
}
}
self._exposeInternal(name, jsonValue(statics, 'expose(): static properties'), [...functions.keys()], function (call) {
const { ns: _ns, method, id, argsJson } = call;
const fn = functions.get(method);
if (fn === undefined) {
sendExposeError(self, id, `No such method: ${method}`);
return;
}
let args;
try {
args = JSON.parse(argsJson);
} catch {
sendExposeError(self, id, 'Argument parse error', 'SerializationError');
return;
}
Promise.resolve(fn.apply(target, args))
.then((result) => {
try {
const resultJson = jsonValue(result, 'Return value');
self.evaluateScript(`window.__webviewjs__&&window.__webviewjs__.resolve(${Number(id)},${resultJson})`);
} catch {
sendExposeError(self, id, 'Return value is not JSON-serialisable', 'SerializationError');
}
})
.catch((err) => {
sendExposeError(
self,
id,
String(err?.message ?? err),
err?.name === 'SerializationError' ? 'SerializationError' : 'Error',
);
});
});
namespaces.add(name);
_exposedNamespaces.set(self, namespaces);
};
module.exports = nativeBinding;
module.exports.SerializationError = SerializationError;
module.exports.Notification = Notification;
// Auto-generated exports by postbuild.js. Do not edit directly.
module.exports.Application = nativeBinding.Application;
module.exports.BrowserWindow = nativeBinding.BrowserWindow;
module.exports.NativeNotification = nativeBinding.NativeNotification;
module.exports.JsNotification = nativeBinding.JsNotification;
module.exports.TrayIcon = nativeBinding.TrayIcon;
module.exports.JsTrayIcon = nativeBinding.JsTrayIcon;
module.exports.WebContext = nativeBinding.WebContext;
module.exports.JsWebContext = nativeBinding.JsWebContext;
module.exports.Webview = nativeBinding.Webview;
module.exports.JsWebview = nativeBinding.JsWebview;
module.exports.ControlFlow = nativeBinding.ControlFlow;
module.exports.JsControlFlow = nativeBinding.JsControlFlow;
module.exports.CursorType = nativeBinding.CursorType;
module.exports.FullscreenType = nativeBinding.FullscreenType;
module.exports.getWebviewVersion = nativeBinding.getWebviewVersion;
module.exports.IosValidOrientations = nativeBinding.IosValidOrientations;
module.exports.ProgressBarState = nativeBinding.ProgressBarState;
module.exports.JsProgressBarState = nativeBinding.JsProgressBarState;
module.exports.Theme = nativeBinding.Theme;
module.exports.VERSION = nativeBinding.VERSION;
module.exports.WebviewApplicationEvent = nativeBinding.WebviewApplicationEvent;
module.exports.WebviewEventType = nativeBinding.WebviewEventType;
module.exports.WindowCommand = nativeBinding.WindowCommand;
module.exports.WindowEventType = nativeBinding.WindowEventType;