opencode-github-sync 3.1.0 → 3.2.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/README.md +340 -219
- package/README.zh-CN.md +242 -198
- package/dist/cli/app.d.ts +39 -0
- package/dist/cli/app.d.ts.map +1 -0
- package/dist/cli/app.js +179 -0
- package/dist/cli/app.js.map +1 -0
- package/dist/cli/args.d.ts +10 -0
- package/dist/cli/args.d.ts.map +1 -0
- package/dist/cli/args.js +39 -0
- package/dist/cli/args.js.map +1 -0
- package/dist/cli/i18n.d.ts +368 -0
- package/dist/cli/i18n.d.ts.map +1 -0
- package/dist/cli/i18n.js +773 -0
- package/dist/cli/i18n.js.map +1 -0
- package/dist/cli/index.js +312 -114
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/menu.d.ts +52 -0
- package/dist/cli/menu.d.ts.map +1 -0
- package/dist/cli/menu.js +1126 -0
- package/dist/cli/menu.js.map +1 -0
- package/dist/cli/render.d.ts +3 -0
- package/dist/cli/render.d.ts.map +1 -1
- package/dist/cli/render.js +6 -1
- package/dist/cli/render.js.map +1 -1
- package/dist/cli/ui.d.ts +62 -0
- package/dist/cli/ui.d.ts.map +1 -0
- package/dist/cli/ui.js +383 -0
- package/dist/cli/ui.js.map +1 -0
- package/dist/core/autosync.d.ts +134 -0
- package/dist/core/autosync.d.ts.map +1 -0
- package/dist/core/autosync.js +507 -0
- package/dist/core/autosync.js.map +1 -0
- package/dist/core/bundle.d.ts +11 -0
- package/dist/core/bundle.d.ts.map +1 -0
- package/dist/core/bundle.js +87 -0
- package/dist/core/bundle.js.map +1 -0
- package/dist/core/categories.d.ts +37 -0
- package/dist/core/categories.d.ts.map +1 -0
- package/dist/core/categories.js +115 -0
- package/dist/core/categories.js.map +1 -0
- package/dist/core/compare.d.ts +21 -0
- package/dist/core/compare.d.ts.map +1 -0
- package/dist/core/compare.js +124 -0
- package/dist/core/compare.js.map +1 -0
- package/dist/core/env.d.ts +16 -0
- package/dist/core/env.d.ts.map +1 -0
- package/dist/core/env.js +47 -0
- package/dist/core/env.js.map +1 -0
- package/dist/core/git.d.ts +6 -0
- package/dist/core/git.d.ts.map +1 -1
- package/dist/core/git.js +44 -4
- package/dist/core/git.js.map +1 -1
- package/dist/core/guard.d.ts +36 -0
- package/dist/core/guard.d.ts.map +1 -0
- package/dist/core/guard.js +65 -0
- package/dist/core/guard.js.map +1 -0
- package/dist/core/history.d.ts +38 -0
- package/dist/core/history.d.ts.map +1 -0
- package/dist/core/history.js +98 -0
- package/dist/core/history.js.map +1 -0
- package/dist/core/index.d.ts +11 -0
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +11 -0
- package/dist/core/index.js.map +1 -1
- package/dist/core/notify.d.ts +9 -0
- package/dist/core/notify.d.ts.map +1 -0
- package/dist/core/notify.js +69 -0
- package/dist/core/notify.js.map +1 -0
- package/dist/core/recovery.d.ts +26 -0
- package/dist/core/recovery.d.ts.map +1 -0
- package/dist/core/recovery.js +56 -0
- package/dist/core/recovery.js.map +1 -0
- package/dist/core/repo.d.ts +19 -1
- package/dist/core/repo.d.ts.map +1 -1
- package/dist/core/repo.js +61 -2
- package/dist/core/repo.js.map +1 -1
- package/dist/core/scheduler.d.ts +138 -0
- package/dist/core/scheduler.d.ts.map +1 -0
- package/dist/core/scheduler.js +531 -0
- package/dist/core/scheduler.js.map +1 -0
- package/dist/core/settings.d.ts +61 -0
- package/dist/core/settings.d.ts.map +1 -1
- package/dist/core/settings.js +44 -2
- package/dist/core/settings.js.map +1 -1
- package/dist/core/setup.d.ts +20 -0
- package/dist/core/setup.d.ts.map +1 -1
- package/dist/core/setup.js +87 -4
- package/dist/core/setup.js.map +1 -1
- package/dist/core/stage.d.ts +5 -0
- package/dist/core/stage.d.ts.map +1 -1
- package/dist/core/stage.js +94 -8
- package/dist/core/stage.js.map +1 -1
- package/dist/core/sync.d.ts +25 -0
- package/dist/core/sync.d.ts.map +1 -1
- package/dist/core/sync.js +295 -37
- package/dist/core/sync.js.map +1 -1
- package/dist/core/update.d.ts +21 -0
- package/dist/core/update.d.ts.map +1 -0
- package/dist/core/update.js +75 -0
- package/dist/core/update.js.map +1 -0
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +4 -3
- package/dist/plugin/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Operating-system scheduler definitions.
|
|
3
|
+
*
|
|
4
|
+
* Every definition is produced by a pure function from a `ScheduleSpec`, so the
|
|
5
|
+
* exact XML, plist and unit text can be snapshot-tested on any platform. The
|
|
6
|
+
* installers below are thin wrappers that write those strings and call the
|
|
7
|
+
* platform tool.
|
|
8
|
+
*
|
|
9
|
+
* Paths are resolved once, at install time, from the running Node binary and
|
|
10
|
+
* this package's own location. They are never rebuilt from a user name: the
|
|
11
|
+
* account name and the profile folder name differ on many machines.
|
|
12
|
+
*/
|
|
13
|
+
export declare const TASK_NAME = "opencode-github-sync";
|
|
14
|
+
export declare const LAUNCHD_LABEL = "com.opencode-github-sync.autosync";
|
|
15
|
+
export declare const SYSTEMD_UNIT = "opencode-github-sync";
|
|
16
|
+
export declare const VBS_NAME = "opencode-sync-autosync.vbs";
|
|
17
|
+
export interface ScheduleSpec {
|
|
18
|
+
/** Absolute path of the Node binary. */
|
|
19
|
+
node: string;
|
|
20
|
+
/** Absolute path of the CLI entry script. */
|
|
21
|
+
cli: string;
|
|
22
|
+
intervalMinutes: number;
|
|
23
|
+
/** Extra environment for the job (root overrides used by tests and CI). */
|
|
24
|
+
env?: Record<string, string>;
|
|
25
|
+
/** Directory for scheduler-level stdout/stderr logs. */
|
|
26
|
+
logDir: string;
|
|
27
|
+
}
|
|
28
|
+
export declare function runArgs(spec: ScheduleSpec): string[];
|
|
29
|
+
/** Quote one argument for the Windows command line (CommandLineToArgvW rules). */
|
|
30
|
+
export declare function quoteWindowsArg(arg: string): string;
|
|
31
|
+
export type WindowsLauncher = {
|
|
32
|
+
kind: "conhost";
|
|
33
|
+
conhost: string;
|
|
34
|
+
} | {
|
|
35
|
+
kind: "wscript";
|
|
36
|
+
wscript: string;
|
|
37
|
+
vbs: string;
|
|
38
|
+
};
|
|
39
|
+
export interface WindowsTaskOptions {
|
|
40
|
+
/** `DOMAIN\user` or `MACHINE\user` of the account the task runs as. */
|
|
41
|
+
userId: string;
|
|
42
|
+
/** S4U runs while logged off; requires an elevated registration. */
|
|
43
|
+
logonType: "InteractiveToken" | "S4U";
|
|
44
|
+
launcher: WindowsLauncher;
|
|
45
|
+
/** Start boundary for the time trigger, local ISO without offset is fine. */
|
|
46
|
+
startBoundary: string;
|
|
47
|
+
}
|
|
48
|
+
/** The command and arguments the task's Exec action runs. */
|
|
49
|
+
export declare function windowsAction(spec: ScheduleSpec, launcher: WindowsLauncher): {
|
|
50
|
+
command: string;
|
|
51
|
+
args: string;
|
|
52
|
+
};
|
|
53
|
+
/**
|
|
54
|
+
* Task Scheduler XML.
|
|
55
|
+
*
|
|
56
|
+
* - A time trigger repeating every N minutes carries the steady cadence. A
|
|
57
|
+
* logon trigger's repetition only starts counting after a real logon, so a
|
|
58
|
+
* task registered mid-session would otherwise never fire on schedule.
|
|
59
|
+
* - Logon (+30 s), session unlock and remote connect (+15 s) cover returning
|
|
60
|
+
* to the machine.
|
|
61
|
+
* - IgnoreNew, a 10-minute limit and no network gate: a roaming laptop is
|
|
62
|
+
* offline often, and the job handles an unreachable remote itself.
|
|
63
|
+
*/
|
|
64
|
+
export declare function windowsTaskXml(spec: ScheduleSpec, options: WindowsTaskOptions): string;
|
|
65
|
+
/**
|
|
66
|
+
* The VBScript fallback launcher, used where `conhost --headless` is not
|
|
67
|
+
* available. `Run ..., 0, True` starts Node with no window and waits, so the
|
|
68
|
+
* task's own run time and exit code are meaningful.
|
|
69
|
+
*/
|
|
70
|
+
export declare function windowsVbs(spec: ScheduleSpec): string;
|
|
71
|
+
/** UTF-16LE with BOM: wscript reads anything else in the ANSI code page. */
|
|
72
|
+
export declare function encodeVbs(text: string): Buffer;
|
|
73
|
+
/** schtasks expects the same encoding for an XML that declares UTF-16. */
|
|
74
|
+
export declare const encodeTaskXml: typeof encodeVbs;
|
|
75
|
+
export declare function launchdPlist(spec: ScheduleSpec): string;
|
|
76
|
+
/**
|
|
77
|
+
* Quote one word for a systemd `ExecStart=` / `Environment=` line. `%` is a
|
|
78
|
+
* specifier and `$` an environment expansion there, so both are doubled.
|
|
79
|
+
*/
|
|
80
|
+
export declare function systemdQuote(arg: string): string;
|
|
81
|
+
export declare function systemdService(spec: ScheduleSpec): string;
|
|
82
|
+
export declare function systemdTimer(spec: ScheduleSpec): string;
|
|
83
|
+
/** Single-quote for POSIX sh. */
|
|
84
|
+
export declare function shQuote(arg: string): string;
|
|
85
|
+
export declare const CRON_MARKER = "# opencode-github-sync autosync";
|
|
86
|
+
export declare function crontabLine(spec: ScheduleSpec): string;
|
|
87
|
+
/** Replace (or remove, with `line` undefined) our entry in a crontab text. */
|
|
88
|
+
export declare function editCrontab(current: string, line: string | undefined): string;
|
|
89
|
+
/** The Node binary to schedule: the one running this CLI, unless it is Bun or OpenCode. */
|
|
90
|
+
export declare function resolveNode(execPath?: string): string;
|
|
91
|
+
/** The CLI entry script of this installation. */
|
|
92
|
+
export declare function resolveCli(moduleDir: string): string;
|
|
93
|
+
export type Platform = "win32" | "darwin" | "linux";
|
|
94
|
+
export interface Runner {
|
|
95
|
+
run: (cmd: string, args: string[], input?: string) => {
|
|
96
|
+
ok: boolean;
|
|
97
|
+
stdout: string;
|
|
98
|
+
stderr: string;
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
export declare const realRunner: Runner;
|
|
102
|
+
export interface InstallContext {
|
|
103
|
+
platform: Platform;
|
|
104
|
+
spec: ScheduleSpec;
|
|
105
|
+
home: string;
|
|
106
|
+
runner: Runner;
|
|
107
|
+
/**
|
|
108
|
+
* Directory for generated launcher files. Must be outside the sync
|
|
109
|
+
* worktree: a launcher there would be committed, overwritten by other
|
|
110
|
+
* machines and deleted by a forced pull's `git clean`.
|
|
111
|
+
*/
|
|
112
|
+
launcherDir: string;
|
|
113
|
+
runWhenLoggedOff: boolean;
|
|
114
|
+
elevated: boolean;
|
|
115
|
+
}
|
|
116
|
+
export interface InstallResult {
|
|
117
|
+
ok: boolean;
|
|
118
|
+
kind: "schtasks" | "launchd" | "systemd" | "cron";
|
|
119
|
+
detail: string[];
|
|
120
|
+
warnings: string[];
|
|
121
|
+
}
|
|
122
|
+
export declare function installScheduler(ctx: InstallContext): InstallResult;
|
|
123
|
+
export interface SchedulerStatus {
|
|
124
|
+
installed: boolean;
|
|
125
|
+
kind: InstallResult["kind"] | "none";
|
|
126
|
+
nextRun?: string;
|
|
127
|
+
detail?: string;
|
|
128
|
+
}
|
|
129
|
+
export declare function schedulerStatus(ctx: Pick<InstallContext, "platform" | "runner" | "home">): SchedulerStatus;
|
|
130
|
+
export type UninstallContext = Pick<InstallContext, "platform" | "runner" | "home" | "launcherDir">;
|
|
131
|
+
export declare function uninstallScheduler(ctx: UninstallContext): {
|
|
132
|
+
removed: boolean;
|
|
133
|
+
detail: string[];
|
|
134
|
+
};
|
|
135
|
+
/** True when this process runs with administrator rights (Windows only). */
|
|
136
|
+
export declare function isElevated(runner?: Runner): boolean;
|
|
137
|
+
export declare function windowsPowerShell(): string;
|
|
138
|
+
//# sourceMappingURL=scheduler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scheduler.d.ts","sourceRoot":"","sources":["../../src/core/scheduler.ts"],"names":[],"mappings":"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"}
|
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
/**
|
|
6
|
+
* Operating-system scheduler definitions.
|
|
7
|
+
*
|
|
8
|
+
* Every definition is produced by a pure function from a `ScheduleSpec`, so the
|
|
9
|
+
* exact XML, plist and unit text can be snapshot-tested on any platform. The
|
|
10
|
+
* installers below are thin wrappers that write those strings and call the
|
|
11
|
+
* platform tool.
|
|
12
|
+
*
|
|
13
|
+
* Paths are resolved once, at install time, from the running Node binary and
|
|
14
|
+
* this package's own location. They are never rebuilt from a user name: the
|
|
15
|
+
* account name and the profile folder name differ on many machines.
|
|
16
|
+
*/
|
|
17
|
+
export const TASK_NAME = "opencode-github-sync";
|
|
18
|
+
export const LAUNCHD_LABEL = "com.opencode-github-sync.autosync";
|
|
19
|
+
export const SYSTEMD_UNIT = "opencode-github-sync";
|
|
20
|
+
export const VBS_NAME = "opencode-sync-autosync.vbs";
|
|
21
|
+
export function runArgs(spec) {
|
|
22
|
+
return [spec.cli, "autosync", "run"];
|
|
23
|
+
}
|
|
24
|
+
// ── Windows ─────────────────────────────────────────────────────────────────
|
|
25
|
+
function xmlEscape(text) {
|
|
26
|
+
return text
|
|
27
|
+
.replace(/&/g, "&")
|
|
28
|
+
.replace(/</g, "<")
|
|
29
|
+
.replace(/>/g, ">")
|
|
30
|
+
.replace(/"/g, """)
|
|
31
|
+
.replace(/'/g, "'");
|
|
32
|
+
}
|
|
33
|
+
/** Quote one argument for the Windows command line (CommandLineToArgvW rules). */
|
|
34
|
+
export function quoteWindowsArg(arg) {
|
|
35
|
+
if (arg !== "" && !/[\s"]/.test(arg))
|
|
36
|
+
return arg;
|
|
37
|
+
let out = '"';
|
|
38
|
+
let backslashes = 0;
|
|
39
|
+
for (const ch of arg) {
|
|
40
|
+
if (ch === "\\") {
|
|
41
|
+
backslashes++;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (ch === '"') {
|
|
45
|
+
out += "\\".repeat(backslashes * 2 + 1) + '"';
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
out += "\\".repeat(backslashes) + ch;
|
|
49
|
+
}
|
|
50
|
+
backslashes = 0;
|
|
51
|
+
}
|
|
52
|
+
return `${out}${"\\".repeat(backslashes * 2)}"`;
|
|
53
|
+
}
|
|
54
|
+
/** The command and arguments the task's Exec action runs. */
|
|
55
|
+
export function windowsAction(spec, launcher) {
|
|
56
|
+
if (launcher.kind === "conhost") {
|
|
57
|
+
return {
|
|
58
|
+
command: launcher.conhost,
|
|
59
|
+
args: ["--headless", spec.node, ...runArgs(spec)].map(quoteWindowsArg).join(" "),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
return { command: launcher.wscript, args: `//B //Nologo ${quoteWindowsArg(launcher.vbs)}` };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Task Scheduler XML.
|
|
66
|
+
*
|
|
67
|
+
* - A time trigger repeating every N minutes carries the steady cadence. A
|
|
68
|
+
* logon trigger's repetition only starts counting after a real logon, so a
|
|
69
|
+
* task registered mid-session would otherwise never fire on schedule.
|
|
70
|
+
* - Logon (+30 s), session unlock and remote connect (+15 s) cover returning
|
|
71
|
+
* to the machine.
|
|
72
|
+
* - IgnoreNew, a 10-minute limit and no network gate: a roaming laptop is
|
|
73
|
+
* offline often, and the job handles an unreachable remote itself.
|
|
74
|
+
*/
|
|
75
|
+
export function windowsTaskXml(spec, options) {
|
|
76
|
+
const action = windowsAction(spec, options.launcher);
|
|
77
|
+
const user = xmlEscape(options.userId);
|
|
78
|
+
const interval = `PT${Math.max(2, Math.floor(spec.intervalMinutes))}M`;
|
|
79
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
80
|
+
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
81
|
+
<RegistrationInfo>
|
|
82
|
+
<Description>Keeps OpenCode configuration in sync with its GitHub repository (opencode-github-sync).</Description>
|
|
83
|
+
<URI>\\${TASK_NAME}</URI>
|
|
84
|
+
</RegistrationInfo>
|
|
85
|
+
<Triggers>
|
|
86
|
+
<TimeTrigger>
|
|
87
|
+
<StartBoundary>${xmlEscape(options.startBoundary)}</StartBoundary>
|
|
88
|
+
<Enabled>true</Enabled>
|
|
89
|
+
<Repetition>
|
|
90
|
+
<Interval>${interval}</Interval>
|
|
91
|
+
<StopAtDurationEnd>false</StopAtDurationEnd>
|
|
92
|
+
</Repetition>
|
|
93
|
+
</TimeTrigger>
|
|
94
|
+
<LogonTrigger>
|
|
95
|
+
<Enabled>true</Enabled>
|
|
96
|
+
<UserId>${user}</UserId>
|
|
97
|
+
<Delay>PT30S</Delay>
|
|
98
|
+
</LogonTrigger>
|
|
99
|
+
<SessionStateChangeTrigger>
|
|
100
|
+
<Enabled>true</Enabled>
|
|
101
|
+
<UserId>${user}</UserId>
|
|
102
|
+
<Delay>PT15S</Delay>
|
|
103
|
+
<StateChange>SessionUnlock</StateChange>
|
|
104
|
+
</SessionStateChangeTrigger>
|
|
105
|
+
<SessionStateChangeTrigger>
|
|
106
|
+
<Enabled>true</Enabled>
|
|
107
|
+
<UserId>${user}</UserId>
|
|
108
|
+
<Delay>PT15S</Delay>
|
|
109
|
+
<StateChange>RemoteConnect</StateChange>
|
|
110
|
+
</SessionStateChangeTrigger>
|
|
111
|
+
</Triggers>
|
|
112
|
+
<Principals>
|
|
113
|
+
<Principal id="Author">
|
|
114
|
+
<UserId>${user}</UserId>
|
|
115
|
+
<LogonType>${options.logonType}</LogonType>
|
|
116
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
117
|
+
</Principal>
|
|
118
|
+
</Principals>
|
|
119
|
+
<Settings>
|
|
120
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
121
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
122
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
123
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
124
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
125
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
126
|
+
<IdleSettings>
|
|
127
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
128
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
129
|
+
</IdleSettings>
|
|
130
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
131
|
+
<Enabled>true</Enabled>
|
|
132
|
+
<Hidden>false</Hidden>
|
|
133
|
+
<RunOnlyIfIdle>false</RunOnlyIfIdle>
|
|
134
|
+
<WakeToRun>false</WakeToRun>
|
|
135
|
+
<ExecutionTimeLimit>PT10M</ExecutionTimeLimit>
|
|
136
|
+
<Priority>7</Priority>
|
|
137
|
+
</Settings>
|
|
138
|
+
<Actions Context="Author">
|
|
139
|
+
<Exec>
|
|
140
|
+
<Command>${xmlEscape(action.command)}</Command>
|
|
141
|
+
<Arguments>${xmlEscape(action.args)}</Arguments>
|
|
142
|
+
</Exec>
|
|
143
|
+
</Actions>
|
|
144
|
+
</Task>
|
|
145
|
+
`;
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* The VBScript fallback launcher, used where `conhost --headless` is not
|
|
149
|
+
* available. `Run ..., 0, True` starts Node with no window and waits, so the
|
|
150
|
+
* task's own run time and exit code are meaningful.
|
|
151
|
+
*/
|
|
152
|
+
export function windowsVbs(spec) {
|
|
153
|
+
const vbQuote = (s) => `""${s.replace(/"/g, '""""')}""`;
|
|
154
|
+
const command = [spec.node, ...runArgs(spec)].map(vbQuote).join(" ");
|
|
155
|
+
const envLines = Object.entries(spec.env ?? {}).map(([k, v]) => `env("${k.replace(/"/g, "")}") = "${v.replace(/"/g, '""')}"`);
|
|
156
|
+
return [
|
|
157
|
+
"' Generated by opencode-github-sync. Starts the autosync job with no window.",
|
|
158
|
+
"' Rewritten on every `opencode-sync autosync install`.",
|
|
159
|
+
"Dim shell, env, code",
|
|
160
|
+
'Set shell = CreateObject("WScript.Shell")',
|
|
161
|
+
'Set env = shell.Environment("PROCESS")',
|
|
162
|
+
...envLines,
|
|
163
|
+
`code = shell.Run("${command}", 0, True)`,
|
|
164
|
+
"WScript.Quit code",
|
|
165
|
+
"",
|
|
166
|
+
].join("\r\n");
|
|
167
|
+
}
|
|
168
|
+
/** UTF-16LE with BOM: wscript reads anything else in the ANSI code page. */
|
|
169
|
+
export function encodeVbs(text) {
|
|
170
|
+
return Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, "utf16le")]);
|
|
171
|
+
}
|
|
172
|
+
/** schtasks expects the same encoding for an XML that declares UTF-16. */
|
|
173
|
+
export const encodeTaskXml = encodeVbs;
|
|
174
|
+
// ── macOS ───────────────────────────────────────────────────────────────────
|
|
175
|
+
export function launchdPlist(spec) {
|
|
176
|
+
const esc = xmlEscape;
|
|
177
|
+
const args = [spec.node, ...runArgs(spec)].map((a) => ` <string>${esc(a)}</string>`);
|
|
178
|
+
const envEntries = Object.entries(spec.env ?? {});
|
|
179
|
+
const env = envEntries.length === 0
|
|
180
|
+
? ""
|
|
181
|
+
: ` <key>EnvironmentVariables</key>
|
|
182
|
+
<dict>
|
|
183
|
+
${envEntries.map(([k, v]) => ` <key>${esc(k)}</key>\n <string>${esc(v)}</string>`).join("\n")}
|
|
184
|
+
</dict>
|
|
185
|
+
`;
|
|
186
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
187
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
188
|
+
<plist version="1.0">
|
|
189
|
+
<dict>
|
|
190
|
+
<key>Label</key>
|
|
191
|
+
<string>${LAUNCHD_LABEL}</string>
|
|
192
|
+
<key>ProgramArguments</key>
|
|
193
|
+
<array>
|
|
194
|
+
${args.join("\n")}
|
|
195
|
+
</array>
|
|
196
|
+
${env} <key>RunAtLoad</key>
|
|
197
|
+
<true/>
|
|
198
|
+
<key>StartInterval</key>
|
|
199
|
+
<integer>${Math.max(2, Math.floor(spec.intervalMinutes)) * 60}</integer>
|
|
200
|
+
<key>ProcessType</key>
|
|
201
|
+
<string>Background</string>
|
|
202
|
+
<key>StandardOutPath</key>
|
|
203
|
+
<string>${esc(path.posix.join(toPosix(spec.logDir), "autosync-launchd.log"))}</string>
|
|
204
|
+
<key>StandardErrorPath</key>
|
|
205
|
+
<string>${esc(path.posix.join(toPosix(spec.logDir), "autosync-launchd.log"))}</string>
|
|
206
|
+
</dict>
|
|
207
|
+
</plist>
|
|
208
|
+
`;
|
|
209
|
+
}
|
|
210
|
+
function toPosix(p) {
|
|
211
|
+
return p.replace(/\\/g, "/");
|
|
212
|
+
}
|
|
213
|
+
// ── Linux ───────────────────────────────────────────────────────────────────
|
|
214
|
+
/**
|
|
215
|
+
* Quote one word for a systemd `ExecStart=` / `Environment=` line. `%` is a
|
|
216
|
+
* specifier and `$` an environment expansion there, so both are doubled.
|
|
217
|
+
*/
|
|
218
|
+
export function systemdQuote(arg) {
|
|
219
|
+
if (/^[A-Za-z0-9_@+=:,./-]+$/.test(arg))
|
|
220
|
+
return arg;
|
|
221
|
+
return `"${arg
|
|
222
|
+
.replace(/\\/g, "\\\\")
|
|
223
|
+
.replace(/"/g, '\\"')
|
|
224
|
+
.replace(/%/g, "%%")
|
|
225
|
+
.replace(/\$/g, "$$$$")}"`;
|
|
226
|
+
}
|
|
227
|
+
export function systemdService(spec) {
|
|
228
|
+
const exec = [spec.node, ...runArgs(spec)].map(systemdQuote).join(" ");
|
|
229
|
+
const env = Object.entries(spec.env ?? {}).map(([k, v]) => `Environment=${systemdQuote(`${k}=${v}`)}`);
|
|
230
|
+
return [
|
|
231
|
+
"[Unit]",
|
|
232
|
+
"Description=opencode-github-sync autosync",
|
|
233
|
+
"",
|
|
234
|
+
"[Service]",
|
|
235
|
+
"Type=oneshot",
|
|
236
|
+
`ExecStart=${exec}`,
|
|
237
|
+
...env,
|
|
238
|
+
"TimeoutStartSec=600",
|
|
239
|
+
"",
|
|
240
|
+
].join("\n");
|
|
241
|
+
}
|
|
242
|
+
export function systemdTimer(spec) {
|
|
243
|
+
const minutes = Math.max(2, Math.floor(spec.intervalMinutes));
|
|
244
|
+
return [
|
|
245
|
+
"[Unit]",
|
|
246
|
+
"Description=Run opencode-github-sync autosync periodically",
|
|
247
|
+
"",
|
|
248
|
+
"[Timer]",
|
|
249
|
+
"OnBootSec=1min",
|
|
250
|
+
`OnUnitActiveSec=${minutes}min`,
|
|
251
|
+
"Persistent=true",
|
|
252
|
+
`Unit=${SYSTEMD_UNIT}.service`,
|
|
253
|
+
"",
|
|
254
|
+
"[Install]",
|
|
255
|
+
"WantedBy=timers.target",
|
|
256
|
+
"",
|
|
257
|
+
].join("\n");
|
|
258
|
+
}
|
|
259
|
+
/** Single-quote for POSIX sh. */
|
|
260
|
+
export function shQuote(arg) {
|
|
261
|
+
return `'${arg.replace(/'/g, `'\\''`)}'`;
|
|
262
|
+
}
|
|
263
|
+
export const CRON_MARKER = "# opencode-github-sync autosync";
|
|
264
|
+
export function crontabLine(spec) {
|
|
265
|
+
// The minute field cannot express more than 59; longer intervals become
|
|
266
|
+
// hourly steps (rounded down), which `*/N` would silently turn into hourly.
|
|
267
|
+
const minutes = Math.max(2, Math.floor(spec.intervalMinutes));
|
|
268
|
+
const schedule = minutes < 60 ? `*/${minutes} * * * *` : `0 */${Math.min(23, Math.floor(minutes / 60))} * * *`;
|
|
269
|
+
// cron turns an unescaped `%` into a newline.
|
|
270
|
+
const cronQuote = (v) => shQuote(v).replace(/%/g, "\\%");
|
|
271
|
+
const env = Object.entries(spec.env ?? {})
|
|
272
|
+
.map(([k, v]) => `${k}=${cronQuote(v)}`)
|
|
273
|
+
.join(" ");
|
|
274
|
+
const cmd = [spec.node, ...runArgs(spec)].map(cronQuote).join(" ");
|
|
275
|
+
const log = cronQuote(path.posix.join(toPosix(spec.logDir), "autosync-cron.log"));
|
|
276
|
+
return `${schedule} ${env ? `${env} ` : ""}${cmd} >> ${log} 2>&1 ${CRON_MARKER}`;
|
|
277
|
+
}
|
|
278
|
+
/** Replace (or remove, with `line` undefined) our entry in a crontab text. */
|
|
279
|
+
export function editCrontab(current, line) {
|
|
280
|
+
const kept = current.split("\n").filter((l) => l.trim() && !l.includes(CRON_MARKER));
|
|
281
|
+
if (line)
|
|
282
|
+
kept.push(line);
|
|
283
|
+
return kept.length > 0 ? `${kept.join("\n")}\n` : "";
|
|
284
|
+
}
|
|
285
|
+
// ── Resolution of absolute paths ────────────────────────────────────────────
|
|
286
|
+
/** The Node binary to schedule: the one running this CLI, unless it is Bun or OpenCode. */
|
|
287
|
+
export function resolveNode(execPath = process.execPath) {
|
|
288
|
+
if (process.env.OPENCODE_SYNC_NODE)
|
|
289
|
+
return process.env.OPENCODE_SYNC_NODE;
|
|
290
|
+
const base = path.basename(execPath).toLowerCase();
|
|
291
|
+
if (base === "node" || base === "node.exe")
|
|
292
|
+
return execPath;
|
|
293
|
+
const candidates = process.platform === "win32"
|
|
294
|
+
? [path.join(process.env.ProgramFiles || "C:\\Program Files", "nodejs", "node.exe")]
|
|
295
|
+
: ["/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"];
|
|
296
|
+
return candidates.find((c) => fs.existsSync(c)) ?? execPath;
|
|
297
|
+
}
|
|
298
|
+
/** The CLI entry script of this installation. */
|
|
299
|
+
export function resolveCli(moduleDir) {
|
|
300
|
+
return path.resolve(moduleDir, "..", "cli", "index.js");
|
|
301
|
+
}
|
|
302
|
+
export const realRunner = {
|
|
303
|
+
run(cmd, args, input) {
|
|
304
|
+
try {
|
|
305
|
+
const stdout = execFileSync(cmd, args, {
|
|
306
|
+
encoding: "utf8",
|
|
307
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
308
|
+
input,
|
|
309
|
+
windowsHide: true,
|
|
310
|
+
timeout: 60_000,
|
|
311
|
+
});
|
|
312
|
+
return { ok: true, stdout: String(stdout), stderr: "" };
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
return {
|
|
316
|
+
ok: false,
|
|
317
|
+
stdout: String(e.stdout ?? ""),
|
|
318
|
+
stderr: String(e.stderr ?? e.message ?? ""),
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
},
|
|
322
|
+
};
|
|
323
|
+
function windowsUser(runner) {
|
|
324
|
+
const who = runner.run("whoami", []);
|
|
325
|
+
return who.ok && who.stdout.trim()
|
|
326
|
+
? who.stdout.trim()
|
|
327
|
+
: `${os.hostname()}\\${os.userInfo().username}`;
|
|
328
|
+
}
|
|
329
|
+
function windowsLauncher(ctx) {
|
|
330
|
+
const systemRoot = process.env.SystemRoot || "C:\\Windows";
|
|
331
|
+
const conhost = path.join(systemRoot, "System32", "conhost.exe");
|
|
332
|
+
// `--headless` exists from Windows 10 1809 (build 17763). It cannot carry
|
|
333
|
+
// environment variables, so a job that needs any uses the VBScript launcher.
|
|
334
|
+
const build = Number(os.release().split(".")[2] ?? 0);
|
|
335
|
+
const needsEnv = Object.keys(ctx.spec.env ?? {}).length > 0;
|
|
336
|
+
if (!needsEnv &&
|
|
337
|
+
process.env.OPENCODE_SYNC_LAUNCHER !== "wscript" &&
|
|
338
|
+
fs.existsSync(conhost) &&
|
|
339
|
+
build >= 17763) {
|
|
340
|
+
return { kind: "conhost", conhost };
|
|
341
|
+
}
|
|
342
|
+
const vbs = path.join(ctx.launcherDir, VBS_NAME);
|
|
343
|
+
fs.mkdirSync(path.dirname(vbs), { recursive: true });
|
|
344
|
+
fs.writeFileSync(vbs, encodeVbs(windowsVbs(ctx.spec)));
|
|
345
|
+
return { kind: "wscript", wscript: path.join(systemRoot, "System32", "wscript.exe"), vbs };
|
|
346
|
+
}
|
|
347
|
+
function localIsoNow() {
|
|
348
|
+
const d = new Date(Date.now() - 60_000);
|
|
349
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
350
|
+
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}:00`;
|
|
351
|
+
}
|
|
352
|
+
export function installScheduler(ctx) {
|
|
353
|
+
const warnings = [];
|
|
354
|
+
fs.mkdirSync(ctx.spec.logDir, { recursive: true });
|
|
355
|
+
if (ctx.platform === "win32") {
|
|
356
|
+
let logonType = "InteractiveToken";
|
|
357
|
+
if (ctx.runWhenLoggedOff) {
|
|
358
|
+
if (ctx.elevated) {
|
|
359
|
+
logonType = "S4U";
|
|
360
|
+
// S4U has no network credentials and cannot unlock DPAPI, so Git
|
|
361
|
+
// Credential Manager cannot hand out a saved HTTPS login.
|
|
362
|
+
warnings.push("while signed out, saved HTTPS logins from Windows Credential Manager are unavailable; use an SSH remote for unattended runs");
|
|
363
|
+
}
|
|
364
|
+
else
|
|
365
|
+
warnings.push("not elevated: registered to run only while you are signed in");
|
|
366
|
+
}
|
|
367
|
+
const launcher = windowsLauncher(ctx);
|
|
368
|
+
const xml = windowsTaskXml(ctx.spec, {
|
|
369
|
+
userId: windowsUser(ctx.runner),
|
|
370
|
+
logonType,
|
|
371
|
+
launcher,
|
|
372
|
+
startBoundary: localIsoNow(),
|
|
373
|
+
});
|
|
374
|
+
const xmlFile = path.join(os.tmpdir(), `ogs-task-${process.pid}.xml`);
|
|
375
|
+
fs.writeFileSync(xmlFile, encodeTaskXml(xml));
|
|
376
|
+
try {
|
|
377
|
+
const created = ctx.runner.run("schtasks", [
|
|
378
|
+
"/Create",
|
|
379
|
+
"/TN",
|
|
380
|
+
TASK_NAME,
|
|
381
|
+
"/XML",
|
|
382
|
+
xmlFile,
|
|
383
|
+
"/F",
|
|
384
|
+
]);
|
|
385
|
+
if (!created.ok) {
|
|
386
|
+
return { ok: false, kind: "schtasks", detail: [created.stderr.trim()], warnings };
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
finally {
|
|
390
|
+
fs.rmSync(xmlFile, { force: true });
|
|
391
|
+
}
|
|
392
|
+
const check = schedulerStatus(ctx);
|
|
393
|
+
if (!check.installed) {
|
|
394
|
+
return { ok: false, kind: "schtasks", detail: ["task missing after registration"], warnings };
|
|
395
|
+
}
|
|
396
|
+
if (!check.nextRun) {
|
|
397
|
+
return { ok: false, kind: "schtasks", detail: ["task has no next run time"], warnings };
|
|
398
|
+
}
|
|
399
|
+
return {
|
|
400
|
+
ok: true,
|
|
401
|
+
kind: "schtasks",
|
|
402
|
+
detail: [`launcher ${launcher.kind}`, `logon ${logonType}`, `next run ${check.nextRun}`],
|
|
403
|
+
warnings,
|
|
404
|
+
};
|
|
405
|
+
}
|
|
406
|
+
if (ctx.platform === "darwin") {
|
|
407
|
+
const plistPath = path.join(ctx.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
408
|
+
fs.mkdirSync(path.dirname(plistPath), { recursive: true });
|
|
409
|
+
fs.writeFileSync(plistPath, launchdPlist(ctx.spec));
|
|
410
|
+
const uid = String(process.getuid?.() ?? "");
|
|
411
|
+
ctx.runner.run("launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
|
|
412
|
+
const boot = ctx.runner.run("launchctl", ["bootstrap", `gui/${uid}`, plistPath]);
|
|
413
|
+
if (!boot.ok) {
|
|
414
|
+
// A headless CI session has no GUI domain; the per-user domain still works.
|
|
415
|
+
const alt = ctx.runner.run("launchctl", ["bootstrap", `user/${uid}`, plistPath]);
|
|
416
|
+
if (!alt.ok)
|
|
417
|
+
return { ok: false, kind: "launchd", detail: [boot.stderr.trim()], warnings };
|
|
418
|
+
warnings.push("loaded into the user domain (no GUI session)");
|
|
419
|
+
}
|
|
420
|
+
return { ok: true, kind: "launchd", detail: [plistPath], warnings };
|
|
421
|
+
}
|
|
422
|
+
// Linux: systemd --user when it answers, otherwise cron. Whichever is
|
|
423
|
+
// chosen, the other one is cleared, or switching would run the job twice.
|
|
424
|
+
const probe = ctx.runner.run("systemctl", ["--user", "show-environment"]);
|
|
425
|
+
const unitDir = path.join(process.env.XDG_CONFIG_HOME || path.join(ctx.home, ".config"), "systemd", "user");
|
|
426
|
+
if (probe.ok) {
|
|
427
|
+
const dir = unitDir;
|
|
428
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
429
|
+
fs.writeFileSync(path.join(dir, `${SYSTEMD_UNIT}.service`), systemdService(ctx.spec));
|
|
430
|
+
fs.writeFileSync(path.join(dir, `${SYSTEMD_UNIT}.timer`), systemdTimer(ctx.spec));
|
|
431
|
+
ctx.runner.run("systemctl", ["--user", "daemon-reload"]);
|
|
432
|
+
const enabled = ctx.runner.run("systemctl", [
|
|
433
|
+
"--user",
|
|
434
|
+
"enable",
|
|
435
|
+
"--now",
|
|
436
|
+
`${SYSTEMD_UNIT}.timer`,
|
|
437
|
+
]);
|
|
438
|
+
if (!enabled.ok)
|
|
439
|
+
return { ok: false, kind: "systemd", detail: [enabled.stderr.trim()], warnings };
|
|
440
|
+
const cron = ctx.runner.run("crontab", ["-l"]);
|
|
441
|
+
if (cron.ok && cron.stdout.includes(CRON_MARKER)) {
|
|
442
|
+
ctx.runner.run("crontab", ["-"], editCrontab(cron.stdout, undefined));
|
|
443
|
+
}
|
|
444
|
+
warnings.push("headless host: run `loginctl enable-linger` so the timer runs while logged out");
|
|
445
|
+
return { ok: true, kind: "systemd", detail: [dir], warnings };
|
|
446
|
+
}
|
|
447
|
+
const current = ctx.runner.run("crontab", ["-l"]);
|
|
448
|
+
const next = editCrontab(current.ok ? current.stdout : "", crontabLine(ctx.spec));
|
|
449
|
+
const written = ctx.runner.run("crontab", ["-"], next);
|
|
450
|
+
if (!written.ok)
|
|
451
|
+
return { ok: false, kind: "cron", detail: [written.stderr.trim()], warnings };
|
|
452
|
+
for (const unit of [`${SYSTEMD_UNIT}.timer`, `${SYSTEMD_UNIT}.service`]) {
|
|
453
|
+
fs.rmSync(path.join(unitDir, unit), { force: true });
|
|
454
|
+
}
|
|
455
|
+
return { ok: true, kind: "cron", detail: ["crontab entry added"], warnings };
|
|
456
|
+
}
|
|
457
|
+
export function schedulerStatus(ctx) {
|
|
458
|
+
if (ctx.platform === "win32") {
|
|
459
|
+
const q = ctx.runner.run("schtasks", ["/Query", "/TN", TASK_NAME]);
|
|
460
|
+
if (!q.ok)
|
|
461
|
+
return { installed: false, kind: "none" };
|
|
462
|
+
// schtasks' own output is localized; the cmdlet returns a real DateTime.
|
|
463
|
+
const info = ctx.runner.run(windowsPowerShell(), [
|
|
464
|
+
"-NoProfile",
|
|
465
|
+
"-NonInteractive",
|
|
466
|
+
"-Command",
|
|
467
|
+
`$i = Get-ScheduledTaskInfo -TaskName '${TASK_NAME}'; if ($i.NextRunTime) { $i.NextRunTime.ToString('s') }`,
|
|
468
|
+
]);
|
|
469
|
+
const next = info.ok ? info.stdout.trim() : "";
|
|
470
|
+
return { installed: true, kind: "schtasks", nextRun: next || undefined };
|
|
471
|
+
}
|
|
472
|
+
if (ctx.platform === "darwin") {
|
|
473
|
+
const plistPath = path.join(ctx.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
474
|
+
if (!fs.existsSync(plistPath))
|
|
475
|
+
return { installed: false, kind: "none" };
|
|
476
|
+
const listed = ctx.runner.run("launchctl", ["list", LAUNCHD_LABEL]);
|
|
477
|
+
return { installed: true, kind: "launchd", detail: listed.ok ? "loaded" : "not loaded" };
|
|
478
|
+
}
|
|
479
|
+
const timer = ctx.runner.run("systemctl", ["--user", "is-enabled", `${SYSTEMD_UNIT}.timer`]);
|
|
480
|
+
if (timer.ok && /enabled/.test(timer.stdout)) {
|
|
481
|
+
return { installed: true, kind: "systemd" };
|
|
482
|
+
}
|
|
483
|
+
const cron = ctx.runner.run("crontab", ["-l"]);
|
|
484
|
+
if (cron.ok && cron.stdout.includes(CRON_MARKER))
|
|
485
|
+
return { installed: true, kind: "cron" };
|
|
486
|
+
return { installed: false, kind: "none" };
|
|
487
|
+
}
|
|
488
|
+
export function uninstallScheduler(ctx) {
|
|
489
|
+
const detail = [];
|
|
490
|
+
let removed = false;
|
|
491
|
+
if (ctx.platform === "win32") {
|
|
492
|
+
const del = ctx.runner.run("schtasks", ["/Delete", "/TN", TASK_NAME, "/F"]);
|
|
493
|
+
removed = del.ok;
|
|
494
|
+
fs.rmSync(path.join(ctx.launcherDir, VBS_NAME), { force: true });
|
|
495
|
+
return { removed, detail };
|
|
496
|
+
}
|
|
497
|
+
if (ctx.platform === "darwin") {
|
|
498
|
+
const uid = String(process.getuid?.() ?? "");
|
|
499
|
+
ctx.runner.run("launchctl", ["bootout", `gui/${uid}/${LAUNCHD_LABEL}`]);
|
|
500
|
+
ctx.runner.run("launchctl", ["bootout", `user/${uid}/${LAUNCHD_LABEL}`]);
|
|
501
|
+
const plistPath = path.join(ctx.home, "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
|
|
502
|
+
removed = fs.existsSync(plistPath);
|
|
503
|
+
fs.rmSync(plistPath, { force: true });
|
|
504
|
+
return { removed, detail };
|
|
505
|
+
}
|
|
506
|
+
const dir = path.join(process.env.XDG_CONFIG_HOME || path.join(ctx.home, ".config"), "systemd", "user");
|
|
507
|
+
const timer = path.join(dir, `${SYSTEMD_UNIT}.timer`);
|
|
508
|
+
if (fs.existsSync(timer)) {
|
|
509
|
+
ctx.runner.run("systemctl", ["--user", "disable", "--now", `${SYSTEMD_UNIT}.timer`]);
|
|
510
|
+
fs.rmSync(timer, { force: true });
|
|
511
|
+
fs.rmSync(path.join(dir, `${SYSTEMD_UNIT}.service`), { force: true });
|
|
512
|
+
ctx.runner.run("systemctl", ["--user", "daemon-reload"]);
|
|
513
|
+
removed = true;
|
|
514
|
+
}
|
|
515
|
+
const cron = ctx.runner.run("crontab", ["-l"]);
|
|
516
|
+
if (cron.ok && cron.stdout.includes(CRON_MARKER)) {
|
|
517
|
+
ctx.runner.run("crontab", ["-"], editCrontab(cron.stdout, undefined));
|
|
518
|
+
removed = true;
|
|
519
|
+
}
|
|
520
|
+
return { removed, detail };
|
|
521
|
+
}
|
|
522
|
+
/** True when this process runs with administrator rights (Windows only). */
|
|
523
|
+
export function isElevated(runner = realRunner) {
|
|
524
|
+
if (process.platform !== "win32")
|
|
525
|
+
return process.getuid?.() === 0;
|
|
526
|
+
return runner.run("net", ["session"]).ok;
|
|
527
|
+
}
|
|
528
|
+
export function windowsPowerShell() {
|
|
529
|
+
return path.join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
530
|
+
}
|
|
531
|
+
//# sourceMappingURL=scheduler.js.map
|