active-window-sessions 0.0.0-stage → 0.1.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.
- package/CHANGELOG.md +10 -0
- package/LICENSE +21 -0
- package/README.md +215 -2
- package/dist/aggregate.d.ts +6 -0
- package/dist/aggregate.js +29 -0
- package/dist/engine.d.ts +31 -0
- package/dist/engine.js +170 -0
- package/dist/host.d.ts +11 -0
- package/dist/host.js +22 -0
- package/dist/ignore.d.ts +8 -0
- package/dist/ignore.js +43 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +7 -0
- package/dist/macos.d.ts +118 -0
- package/dist/macos.js +218 -0
- package/dist/platform.d.ts +25 -0
- package/dist/platform.js +53 -0
- package/dist/sessionize.d.ts +6 -0
- package/dist/sessionize.js +15 -0
- package/dist/tracker.d.ts +8 -0
- package/dist/tracker.js +130 -0
- package/dist/types.d.ts +132 -0
- package/dist/types.js +1 -0
- package/dist/windows.d.ts +29 -0
- package/dist/windows.js +99 -0
- package/package.json +75 -4
package/dist/macos.d.ts
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** A browser whose tabs can be read through macOS Automation (Apple Events). */
|
|
2
|
+
export interface MacBrowser {
|
|
3
|
+
name: string;
|
|
4
|
+
bundleId: string;
|
|
5
|
+
/** App bundle file name, such as `Safari.app`. */
|
|
6
|
+
appFile: string;
|
|
7
|
+
}
|
|
8
|
+
/** Browsers that are probed for Automation permission by default. */
|
|
9
|
+
export declare const MAC_BROWSERS: readonly MacBrowser[];
|
|
10
|
+
/** Which macOS permission. */
|
|
11
|
+
export type PermissionKind = 'accessibility' | 'screen' | 'automation';
|
|
12
|
+
/** Accessibility is either trusted or not; `unknown` when Electron could not tell. */
|
|
13
|
+
export type AccessibilityState = 'granted' | 'denied' | 'unknown';
|
|
14
|
+
/**
|
|
15
|
+
* Screen Recording. Electron reports `denied` both before the first prompt and after a refusal,
|
|
16
|
+
* so `not_determined` is only seen when macOS says so.
|
|
17
|
+
*/
|
|
18
|
+
export type ScreenState = 'granted' | 'denied' | 'not_determined' | 'restricted' | 'unknown';
|
|
19
|
+
/** Automation for one browser. `not_running` is returned by a probe only; snapshots fall back to the last real answer. */
|
|
20
|
+
export type AutomationState = 'granted' | 'denied' | 'not_running' | 'unknown';
|
|
21
|
+
/** The parts of Electron's `systemPreferences` that are used. Pass the real one in your app. */
|
|
22
|
+
export interface SystemPreferencesLike {
|
|
23
|
+
isTrustedAccessibilityClient(prompt: boolean): boolean;
|
|
24
|
+
getMediaAccessStatus(mediaType: 'screen'): string;
|
|
25
|
+
}
|
|
26
|
+
/** Output of a finished command. */
|
|
27
|
+
export interface CommandResult {
|
|
28
|
+
stdout: string;
|
|
29
|
+
stderr: string;
|
|
30
|
+
exitCode: number;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Runs a command and resolves with its output, even for a non-zero exit code. Reject only when the
|
|
34
|
+
* command could not run or timed out.
|
|
35
|
+
*/
|
|
36
|
+
export type CommandRunner = (command: string, args: readonly string[], options: {
|
|
37
|
+
timeoutMs: number;
|
|
38
|
+
}) => Promise<CommandResult>;
|
|
39
|
+
/** Runs commands with `child_process.execFile`. This is the default runner; it really runs the command. */
|
|
40
|
+
export declare const execFileRunner: CommandRunner;
|
|
41
|
+
/** Options for `createMacPermissions`. */
|
|
42
|
+
export interface MacPermissionsOptions {
|
|
43
|
+
/** Electron's `systemPreferences`. */
|
|
44
|
+
systemPreferences: SystemPreferencesLike;
|
|
45
|
+
/** Runs `osascript` for Automation probes. Defaults to `execFileRunner`. */
|
|
46
|
+
runCommand?: CommandRunner;
|
|
47
|
+
/** Platform to assume. Defaults to `process.platform`; everything is a no-op unless it is `'darwin'`. */
|
|
48
|
+
platform?: string;
|
|
49
|
+
/** Time source in milliseconds, for the probe cache. Defaults to `Date.now`. */
|
|
50
|
+
now?: () => number;
|
|
51
|
+
/** Browsers to probe. When omitted, the entries of `MAC_BROWSERS` that `isInstalled` accepts. */
|
|
52
|
+
browsers?: readonly MacBrowser[];
|
|
53
|
+
/** Tells whether a browser is installed. Defaults to a check of `/Applications` and `~/Applications`; Safari always counts. */
|
|
54
|
+
isInstalled?: (browser: MacBrowser) => boolean;
|
|
55
|
+
/** How long an Automation answer is reused, so a 2 s re-check does not repeat the prompt. Default 10000. */
|
|
56
|
+
automationCacheMs?: number;
|
|
57
|
+
/** How long an Automation probe may take. Default 2000. */
|
|
58
|
+
probeTimeoutMs?: number;
|
|
59
|
+
/** Triggers the Screen Recording prompt, for example `() => desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 1, height: 1 } })`. */
|
|
60
|
+
requestScreenRecording?: () => unknown;
|
|
61
|
+
/** Opens a System Settings URL, for example `shell.openExternal`. */
|
|
62
|
+
openExternal?: (url: string) => unknown;
|
|
63
|
+
/** Restarts the app, for example `() => { app.relaunch(); app.quit(); }`. */
|
|
64
|
+
relaunch?: () => void;
|
|
65
|
+
/** Receives errors from the injected callbacks. Without it they are ignored. */
|
|
66
|
+
onError?: (error: unknown) => void;
|
|
67
|
+
}
|
|
68
|
+
/** Permission states at one moment. */
|
|
69
|
+
export interface PermissionsSnapshot {
|
|
70
|
+
accessibility: AccessibilityState;
|
|
71
|
+
screen: ScreenState;
|
|
72
|
+
/** Automation state by browser bundle id. */
|
|
73
|
+
automation: Record<string, AutomationState>;
|
|
74
|
+
}
|
|
75
|
+
/** Options for `getPermissions` and `getView`. */
|
|
76
|
+
export interface PermissionsReadOptions {
|
|
77
|
+
/** Run Automation probes. When `false`, only answers from earlier probes are used. Default `true`. */
|
|
78
|
+
probe?: boolean;
|
|
79
|
+
/** Ignore cached probe answers and probe again. Default `false`. */
|
|
80
|
+
fresh?: boolean;
|
|
81
|
+
}
|
|
82
|
+
/** What a permissions screen needs. `supported` is `false` off macOS. */
|
|
83
|
+
export type PermissionsView = {
|
|
84
|
+
supported: false;
|
|
85
|
+
} | {
|
|
86
|
+
supported: true;
|
|
87
|
+
permissions: PermissionsSnapshot;
|
|
88
|
+
browsers: Array<{
|
|
89
|
+
name: string;
|
|
90
|
+
bundleId: string;
|
|
91
|
+
}>;
|
|
92
|
+
/** A Screen Recording grant only applies after the app restarts. */
|
|
93
|
+
needsRelaunch: boolean;
|
|
94
|
+
};
|
|
95
|
+
/** The macOS permission helpers. */
|
|
96
|
+
export interface MacPermissions {
|
|
97
|
+
/** Accessibility state. `granted` on other platforms, where no permission is needed. */
|
|
98
|
+
accessibilityState(): AccessibilityState;
|
|
99
|
+
/** Screen Recording state. `granted` on other platforms. */
|
|
100
|
+
screenState(): ScreenState;
|
|
101
|
+
/** All permission states, or `null` off macOS. */
|
|
102
|
+
getPermissions(options?: PermissionsReadOptions): Promise<PermissionsSnapshot | null>;
|
|
103
|
+
/** Permission states plus browser names and whether a relaunch is due. */
|
|
104
|
+
getView(options?: PermissionsReadOptions): Promise<PermissionsView>;
|
|
105
|
+
/** Shows the macOS prompt where one exists, then returns the view (without probing). A refusal needs System Settings. */
|
|
106
|
+
request(kind: PermissionKind, bundleId?: string): Promise<PermissionsView>;
|
|
107
|
+
/** Opens the System Settings pane for a permission. Returns `false` when it could not. */
|
|
108
|
+
openSettings(kind: PermissionKind): boolean;
|
|
109
|
+
/** Calls the injected `relaunch`. */
|
|
110
|
+
relaunch(): void;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Creates the macOS permission helpers: Accessibility, Screen Recording, and Automation per browser.
|
|
114
|
+
* Create it once the app is ready: the Screen Recording state at that moment decides whether a
|
|
115
|
+
* later grant needs a relaunch. Nothing here runs a command unless `getPermissions`, `getView` or
|
|
116
|
+
* `request` is asked to probe Automation.
|
|
117
|
+
*/
|
|
118
|
+
export declare function createMacPermissions(options: MacPermissionsOptions): MacPermissions;
|
package/dist/macos.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { existsSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
/** Browsers that are probed for Automation permission by default. */
|
|
6
|
+
export const MAC_BROWSERS = [
|
|
7
|
+
{ name: 'Safari', bundleId: 'com.apple.Safari', appFile: 'Safari.app' },
|
|
8
|
+
{ name: 'Google Chrome', bundleId: 'com.google.Chrome', appFile: 'Google Chrome.app' },
|
|
9
|
+
{ name: 'Microsoft Edge', bundleId: 'com.microsoft.edgemac', appFile: 'Microsoft Edge.app' },
|
|
10
|
+
{ name: 'Brave', bundleId: 'com.brave.Browser', appFile: 'Brave Browser.app' },
|
|
11
|
+
{ name: 'Arc', bundleId: 'company.thebrowser.Browser', appFile: 'Arc.app' },
|
|
12
|
+
{ name: 'Opera', bundleId: 'com.operasoftware.Opera', appFile: 'Opera.app' },
|
|
13
|
+
{ name: 'Vivaldi', bundleId: 'com.vivaldi.Vivaldi', appFile: 'Vivaldi.app' },
|
|
14
|
+
];
|
|
15
|
+
/** Runs commands with `child_process.execFile`. This is the default runner; it really runs the command. */
|
|
16
|
+
export const execFileRunner = (command, args, { timeoutMs }) => new Promise((resolve, reject) => {
|
|
17
|
+
execFile(command, [...args], { timeout: timeoutMs }, (error, stdout, stderr) => {
|
|
18
|
+
if (!error)
|
|
19
|
+
return resolve({ stdout: String(stdout), stderr: String(stderr), exitCode: 0 });
|
|
20
|
+
const failure = error;
|
|
21
|
+
if (typeof failure.code === 'number' && !failure.killed) {
|
|
22
|
+
return resolve({ stdout: String(stdout), stderr: String(stderr), exitCode: failure.code });
|
|
23
|
+
}
|
|
24
|
+
reject(error);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
27
|
+
const SETTINGS_PANES = {
|
|
28
|
+
accessibility: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility',
|
|
29
|
+
screen: 'x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture',
|
|
30
|
+
automation: 'x-apple.systempreferences:com.apple.preference.security?Privacy_Automation',
|
|
31
|
+
};
|
|
32
|
+
const BUNDLE_ID = /^[A-Za-z0-9][A-Za-z0-9.-]*$/;
|
|
33
|
+
function defaultIsInstalled(browser) {
|
|
34
|
+
if (browser.bundleId === 'com.apple.Safari')
|
|
35
|
+
return true;
|
|
36
|
+
return ['/Applications', join(homedir(), 'Applications')].some((dir) => existsSync(join(dir, browser.appFile)));
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Creates the macOS permission helpers: Accessibility, Screen Recording, and Automation per browser.
|
|
40
|
+
* Create it once the app is ready: the Screen Recording state at that moment decides whether a
|
|
41
|
+
* later grant needs a relaunch. Nothing here runs a command unless `getPermissions`, `getView` or
|
|
42
|
+
* `request` is asked to probe Automation.
|
|
43
|
+
*/
|
|
44
|
+
export function createMacPermissions(options) {
|
|
45
|
+
const { systemPreferences } = options;
|
|
46
|
+
const isMac = (options.platform ?? process.platform) === 'darwin';
|
|
47
|
+
const run = options.runCommand ?? execFileRunner;
|
|
48
|
+
const now = options.now ?? Date.now;
|
|
49
|
+
const cacheMs = options.automationCacheMs ?? 10_000;
|
|
50
|
+
const timeoutMs = options.probeTimeoutMs ?? 2000;
|
|
51
|
+
const report = (error) => {
|
|
52
|
+
try {
|
|
53
|
+
options.onError?.(error);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
// An error handler that throws must not break the helpers.
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
let installed = null;
|
|
60
|
+
const listBrowsers = () => {
|
|
61
|
+
if (installed)
|
|
62
|
+
return installed;
|
|
63
|
+
const isInstalled = options.isInstalled ?? defaultIsInstalled;
|
|
64
|
+
installed = options.browsers ?? MAC_BROWSERS.filter((browser) => isInstalled(browser));
|
|
65
|
+
return installed;
|
|
66
|
+
};
|
|
67
|
+
/** Last probe per browser. */
|
|
68
|
+
const probes = new Map();
|
|
69
|
+
/** Last real (granted or denied) answer, kept while the browser is closed. */
|
|
70
|
+
const known = new Map();
|
|
71
|
+
const inFlight = new Map();
|
|
72
|
+
let screenRequested = false;
|
|
73
|
+
const accessibilityState = () => {
|
|
74
|
+
if (!isMac)
|
|
75
|
+
return 'granted';
|
|
76
|
+
try {
|
|
77
|
+
return systemPreferences.isTrustedAccessibilityClient(false) ? 'granted' : 'denied';
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
return 'unknown';
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
const screenState = () => {
|
|
84
|
+
if (!isMac)
|
|
85
|
+
return 'granted';
|
|
86
|
+
try {
|
|
87
|
+
const status = systemPreferences.getMediaAccessStatus('screen');
|
|
88
|
+
if (status === 'not-determined')
|
|
89
|
+
return 'not_determined';
|
|
90
|
+
if (status === 'granted' || status === 'denied' || status === 'restricted')
|
|
91
|
+
return status;
|
|
92
|
+
return 'unknown';
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return 'unknown';
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
const screenAtLaunch = screenState();
|
|
99
|
+
async function runProbe(bundleId) {
|
|
100
|
+
// `is running` never launches the browser; `count windows` is the Apple Event that needs consent.
|
|
101
|
+
const script = [
|
|
102
|
+
`if application id "${bundleId}" is running then`,
|
|
103
|
+
`tell application id "${bundleId}" to count windows`,
|
|
104
|
+
'return "granted"',
|
|
105
|
+
'end if',
|
|
106
|
+
'return "not_running"',
|
|
107
|
+
].join('\n');
|
|
108
|
+
try {
|
|
109
|
+
const result = await run('osascript', ['-e', script], { timeoutMs });
|
|
110
|
+
if (result.exitCode === 0)
|
|
111
|
+
return result.stdout.trim() === 'not_running' ? 'not_running' : 'granted';
|
|
112
|
+
return /-1743\b/.test(result.stderr) ? 'denied' : 'unknown';
|
|
113
|
+
}
|
|
114
|
+
catch (error) {
|
|
115
|
+
return /-1743\b/.test(error instanceof Error ? error.message : String(error)) ? 'denied' : 'unknown';
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
function automationState(bundleId, fresh) {
|
|
119
|
+
const cached = probes.get(bundleId);
|
|
120
|
+
if (!fresh && cached && now() - cached.at < cacheMs)
|
|
121
|
+
return Promise.resolve(cached.state);
|
|
122
|
+
const pending = inFlight.get(bundleId);
|
|
123
|
+
if (pending)
|
|
124
|
+
return pending;
|
|
125
|
+
const probe = runProbe(bundleId)
|
|
126
|
+
.then((state) => {
|
|
127
|
+
probes.set(bundleId, { state, at: now() });
|
|
128
|
+
if (state === 'granted' || state === 'denied')
|
|
129
|
+
known.set(bundleId, state);
|
|
130
|
+
return state;
|
|
131
|
+
})
|
|
132
|
+
.finally(() => inFlight.delete(bundleId));
|
|
133
|
+
inFlight.set(bundleId, probe);
|
|
134
|
+
return probe;
|
|
135
|
+
}
|
|
136
|
+
async function getPermissions({ probe = true, fresh = false } = {}) {
|
|
137
|
+
if (!isMac)
|
|
138
|
+
return null;
|
|
139
|
+
const automation = {};
|
|
140
|
+
await Promise.all(listBrowsers().map(async ({ bundleId }) => {
|
|
141
|
+
if (!BUNDLE_ID.test(bundleId)) {
|
|
142
|
+
automation[bundleId] = 'unknown';
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
if (!probe) {
|
|
146
|
+
automation[bundleId] = known.get(bundleId) ?? 'unknown';
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
const state = await automationState(bundleId, fresh);
|
|
150
|
+
// A closed browser or a probe that timed out keeps the last real answer.
|
|
151
|
+
automation[bundleId] = state === 'not_running' || state === 'unknown' ? (known.get(bundleId) ?? state) : state;
|
|
152
|
+
}));
|
|
153
|
+
return { accessibility: accessibilityState(), screen: screenState(), automation };
|
|
154
|
+
}
|
|
155
|
+
async function getView(readOptions) {
|
|
156
|
+
const permissions = await getPermissions(readOptions);
|
|
157
|
+
if (!permissions)
|
|
158
|
+
return { supported: false };
|
|
159
|
+
const needsRelaunch = (permissions.screen === 'granted' && screenAtLaunch !== 'granted') ||
|
|
160
|
+
(screenRequested && screenAtLaunch !== 'granted');
|
|
161
|
+
return {
|
|
162
|
+
supported: true,
|
|
163
|
+
permissions,
|
|
164
|
+
browsers: listBrowsers().map(({ name, bundleId }) => ({ name, bundleId })),
|
|
165
|
+
needsRelaunch,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
async function request(kind, bundleId) {
|
|
169
|
+
if (!isMac)
|
|
170
|
+
return { supported: false };
|
|
171
|
+
if (kind === 'accessibility') {
|
|
172
|
+
try {
|
|
173
|
+
systemPreferences.isTrustedAccessibilityClient(true);
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
report(error);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else if (kind === 'screen') {
|
|
180
|
+
screenRequested = true;
|
|
181
|
+
try {
|
|
182
|
+
await options.requestScreenRecording?.();
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
report(error);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
else if (kind === 'automation' && bundleId && listBrowsers().some((b) => b.bundleId === bundleId)) {
|
|
189
|
+
if (BUNDLE_ID.test(bundleId))
|
|
190
|
+
await automationState(bundleId, true);
|
|
191
|
+
}
|
|
192
|
+
return getView({ probe: false });
|
|
193
|
+
}
|
|
194
|
+
function openSettings(kind) {
|
|
195
|
+
const url = isMac ? SETTINGS_PANES[kind] : undefined;
|
|
196
|
+
if (!url || !options.openExternal)
|
|
197
|
+
return false;
|
|
198
|
+
if (kind === 'screen')
|
|
199
|
+
screenRequested = true;
|
|
200
|
+
try {
|
|
201
|
+
Promise.resolve(options.openExternal(url)).catch(report);
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
report(error);
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
return true;
|
|
208
|
+
}
|
|
209
|
+
return {
|
|
210
|
+
accessibilityState,
|
|
211
|
+
screenState,
|
|
212
|
+
getPermissions,
|
|
213
|
+
getView,
|
|
214
|
+
request,
|
|
215
|
+
openSettings,
|
|
216
|
+
relaunch: () => options.relaunch?.(),
|
|
217
|
+
};
|
|
218
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/** Whether active-window reading is expected to work on this machine. */
|
|
2
|
+
export interface PlatformSupport {
|
|
3
|
+
supported: boolean;
|
|
4
|
+
/** Why it is not supported. */
|
|
5
|
+
reason?: string;
|
|
6
|
+
}
|
|
7
|
+
/** Options for `checkPlatformSupport` and `defaultIdleThresholdSeconds`. All default to the current process. */
|
|
8
|
+
export interface PlatformOptions {
|
|
9
|
+
platform?: string;
|
|
10
|
+
env?: Record<string, string | undefined>;
|
|
11
|
+
/** Tells whether a command exists on PATH. Defaults to a lookup that does not run anything. */
|
|
12
|
+
commandExists?: (name: string) => boolean;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Checks the one known unsupported setup: Linux without X11 (Wayland has no active-window API, and
|
|
16
|
+
* get-windows needs `xprop` and `xwininfo`). macOS and Windows are reported as supported.
|
|
17
|
+
*/
|
|
18
|
+
export declare function checkPlatformSupport(options?: PlatformOptions): PlatformSupport;
|
|
19
|
+
/** Whether this looks like a remote desktop (RDP) or SSH session. */
|
|
20
|
+
export declare function isRemoteSession(options?: PlatformOptions): boolean;
|
|
21
|
+
/**
|
|
22
|
+
* A reasonable `idleAfterSeconds`: 50 on a local session, 30 on a remote one, where the system
|
|
23
|
+
* idle counter is less reliable.
|
|
24
|
+
*/
|
|
25
|
+
export declare function defaultIdleThresholdSeconds(options?: PlatformOptions): number;
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { accessSync, constants } from 'node:fs';
|
|
2
|
+
import { delimiter, join } from 'node:path';
|
|
3
|
+
function onPath(name, env) {
|
|
4
|
+
for (const dir of (env.PATH ?? '').split(delimiter)) {
|
|
5
|
+
if (!dir)
|
|
6
|
+
continue;
|
|
7
|
+
try {
|
|
8
|
+
accessSync(join(dir, name), constants.X_OK);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
// Not in this directory.
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Checks the one known unsupported setup: Linux without X11 (Wayland has no active-window API, and
|
|
19
|
+
* get-windows needs `xprop` and `xwininfo`). macOS and Windows are reported as supported.
|
|
20
|
+
*/
|
|
21
|
+
export function checkPlatformSupport(options = {}) {
|
|
22
|
+
const platform = options.platform ?? process.platform;
|
|
23
|
+
if (platform !== 'linux')
|
|
24
|
+
return { supported: true };
|
|
25
|
+
const env = options.env ?? process.env;
|
|
26
|
+
const wayland = env.XDG_SESSION_TYPE === 'wayland' || (Boolean(env.WAYLAND_DISPLAY) && !env.DISPLAY);
|
|
27
|
+
if (wayland)
|
|
28
|
+
return { supported: false, reason: 'Wayland sessions have no active-window API; use an X11 session.' };
|
|
29
|
+
const exists = options.commandExists ?? ((name) => onPath(name, env));
|
|
30
|
+
const missing = ['xprop', 'xwininfo'].filter((name) => !exists(name));
|
|
31
|
+
if (missing.length > 0)
|
|
32
|
+
return { supported: false, reason: `Missing X11 tools: ${missing.join(', ')}.` };
|
|
33
|
+
return { supported: true };
|
|
34
|
+
}
|
|
35
|
+
/** Whether this looks like a remote desktop (RDP) or SSH session. */
|
|
36
|
+
export function isRemoteSession(options = {}) {
|
|
37
|
+
const platform = options.platform ?? process.platform;
|
|
38
|
+
const env = options.env ?? process.env;
|
|
39
|
+
if (platform === 'win32') {
|
|
40
|
+
const name = env.SESSIONNAME ?? '';
|
|
41
|
+
return name.startsWith('RDP') || name.includes('Remote');
|
|
42
|
+
}
|
|
43
|
+
if (platform === 'darwin' || platform === 'linux')
|
|
44
|
+
return env.SSH_CONNECTION != null || env.SSH_CLIENT != null;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* A reasonable `idleAfterSeconds`: 50 on a local session, 30 on a remote one, where the system
|
|
49
|
+
* idle counter is less reliable.
|
|
50
|
+
*/
|
|
51
|
+
export function defaultIdleThresholdSeconds(options = {}) {
|
|
52
|
+
return isRemoteSession(options) ? 30 : 50;
|
|
53
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { Sample, Segment, SessionizeOptions } from './types.ts';
|
|
2
|
+
/**
|
|
3
|
+
* Turns timestamped samples into segments: merges short gaps, drops blips, cuts at the last input
|
|
4
|
+
* when idle starts, and skips system UI. Samples may arrive in any order; they are sorted by time.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sessionize(samples: readonly Sample[], options?: SessionizeOptions): Segment[];
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { resolveSegmentation, SegmentBuilder } from "./engine.js";
|
|
2
|
+
/**
|
|
3
|
+
* Turns timestamped samples into segments: merges short gaps, drops blips, cuts at the last input
|
|
4
|
+
* when idle starts, and skips system UI. Samples may arrive in any order; they are sorted by time.
|
|
5
|
+
*/
|
|
6
|
+
export function sessionize(samples, options = {}) {
|
|
7
|
+
const builder = new SegmentBuilder(resolveSegmentation(options));
|
|
8
|
+
const ordered = samples.filter((sample) => Number.isFinite(sample.at)).sort((a, b) => a.at - b.at);
|
|
9
|
+
const last = ordered.at(-1);
|
|
10
|
+
if (!last)
|
|
11
|
+
return [];
|
|
12
|
+
for (const sample of ordered)
|
|
13
|
+
builder.push(sample.at, sample.window ?? null, sample.idleSeconds ?? null);
|
|
14
|
+
return builder.finish(options.endAt ?? last.at);
|
|
15
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Clock, Tracker, TrackerOptions } from './types.ts';
|
|
2
|
+
/** The system clock. */
|
|
3
|
+
export declare const systemClock: Clock;
|
|
4
|
+
/**
|
|
5
|
+
* Polls `sample` on an interval and turns the readings into segments, delivered to `onSegments`.
|
|
6
|
+
* Create it, call `start()`, and call `stop()` to deliver what is left.
|
|
7
|
+
*/
|
|
8
|
+
export declare function createTracker(options: TrackerOptions): Tracker;
|
package/dist/tracker.js
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { resolveSegmentation, SegmentBuilder } from "./engine.js";
|
|
2
|
+
/** The system clock. */
|
|
3
|
+
export const systemClock = {
|
|
4
|
+
now: () => Date.now(),
|
|
5
|
+
setTimeout: (callback, ms) => setTimeout(callback, ms),
|
|
6
|
+
clearTimeout: (handle) => clearTimeout(handle),
|
|
7
|
+
setInterval: (callback, ms) => setInterval(callback, ms),
|
|
8
|
+
clearInterval: (handle) => clearInterval(handle),
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Polls `sample` on an interval and turns the readings into segments, delivered to `onSegments`.
|
|
12
|
+
* Create it, call `start()`, and call `stop()` to deliver what is left.
|
|
13
|
+
*/
|
|
14
|
+
export function createTracker(options) {
|
|
15
|
+
const { sample, getIdleSeconds, onSegments, onError } = options;
|
|
16
|
+
if (typeof sample !== 'function')
|
|
17
|
+
throw new TypeError('sample must be a function');
|
|
18
|
+
if (typeof onSegments !== 'function')
|
|
19
|
+
throw new TypeError('onSegments must be a function');
|
|
20
|
+
const intervalMs = options.intervalMs ?? 2000;
|
|
21
|
+
if (!(intervalMs > 0) || !Number.isFinite(intervalMs))
|
|
22
|
+
throw new RangeError('intervalMs must be greater than 0');
|
|
23
|
+
const sampleTimeoutMs = options.sampleTimeoutMs ?? 4000;
|
|
24
|
+
if (!(sampleTimeoutMs > 0))
|
|
25
|
+
throw new RangeError('sampleTimeoutMs must be greater than 0');
|
|
26
|
+
const clock = options.clock ?? systemClock;
|
|
27
|
+
const builder = new SegmentBuilder(resolveSegmentation({ ...options, maxSampleGapMs: options.maxSampleGapMs ?? Math.max(60_000, intervalMs * 3) }));
|
|
28
|
+
let timer = null;
|
|
29
|
+
let running = false;
|
|
30
|
+
let inFlight = false;
|
|
31
|
+
/** Bumped on every start so a poll that began before a restart cannot write into the new run. */
|
|
32
|
+
let run = 0;
|
|
33
|
+
const report = (error) => {
|
|
34
|
+
try {
|
|
35
|
+
onError?.(error);
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
// An error handler that throws must not break polling.
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
const deliver = (segments) => {
|
|
42
|
+
if (segments.length > 0) {
|
|
43
|
+
try {
|
|
44
|
+
onSegments(segments);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
report(error);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return segments;
|
|
51
|
+
};
|
|
52
|
+
async function readWindow() {
|
|
53
|
+
let timeoutHandle = null;
|
|
54
|
+
const timeout = new Promise((resolve) => {
|
|
55
|
+
timeoutHandle = clock.setTimeout(() => resolve('timeout'), sampleTimeoutMs);
|
|
56
|
+
});
|
|
57
|
+
try {
|
|
58
|
+
const result = await Promise.race([Promise.resolve().then(sample), timeout]);
|
|
59
|
+
if (result === 'timeout') {
|
|
60
|
+
report(new Error(`sample took longer than ${sampleTimeoutMs} ms`));
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
return result ?? null;
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
report(error);
|
|
67
|
+
return null;
|
|
68
|
+
}
|
|
69
|
+
finally {
|
|
70
|
+
clock.clearTimeout(timeoutHandle);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async function readIdle() {
|
|
74
|
+
if (!getIdleSeconds)
|
|
75
|
+
return null;
|
|
76
|
+
try {
|
|
77
|
+
return (await getIdleSeconds()) ?? null;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
report(error);
|
|
81
|
+
return null;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function poll() {
|
|
85
|
+
if (!running || inFlight)
|
|
86
|
+
return;
|
|
87
|
+
inFlight = true;
|
|
88
|
+
const thisRun = run;
|
|
89
|
+
try {
|
|
90
|
+
const window = await readWindow();
|
|
91
|
+
if (!running || thisRun !== run)
|
|
92
|
+
return;
|
|
93
|
+
const idleSeconds = await readIdle();
|
|
94
|
+
if (!running || thisRun !== run)
|
|
95
|
+
return;
|
|
96
|
+
builder.push(clock.now(), window, idleSeconds);
|
|
97
|
+
deliver(builder.drain());
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
report(error);
|
|
101
|
+
}
|
|
102
|
+
finally {
|
|
103
|
+
inFlight = false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return {
|
|
107
|
+
start() {
|
|
108
|
+
if (running)
|
|
109
|
+
return;
|
|
110
|
+
running = true;
|
|
111
|
+
run += 1;
|
|
112
|
+
builder.reset();
|
|
113
|
+
timer = clock.setInterval(() => void poll(), intervalMs);
|
|
114
|
+
void poll();
|
|
115
|
+
},
|
|
116
|
+
stop(endMs) {
|
|
117
|
+
if (!running)
|
|
118
|
+
return [];
|
|
119
|
+
running = false;
|
|
120
|
+
clock.clearInterval(timer);
|
|
121
|
+
timer = null;
|
|
122
|
+
const now = clock.now();
|
|
123
|
+
return deliver(builder.finish(Math.min(endMs ?? now, now)));
|
|
124
|
+
},
|
|
125
|
+
flush(flushOptions = {}) {
|
|
126
|
+
return deliver(builder.flush(clock.now(), Boolean(flushOptions.cut) && running));
|
|
127
|
+
},
|
|
128
|
+
isRunning: () => running,
|
|
129
|
+
};
|
|
130
|
+
}
|