Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions packages/loop-js/src/cli/cron/schtasks.encoding.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { expect, test } from "bun:test"
import { buildTaskXml, taskXmlBytes, wrapperCommand } from "./schtasks.ts"

test("Task Scheduler XML declaration and bytes agree on UTF-16", () => {
const xml = buildTaskXml({
expr: "0 8 * * *",
dir: "C:\\proj",
command: wrapperCommand("C:\\proj\\.loop\\cron\\abc123.cmd"),
until: { settled: false },
})
const bytes = taskXmlBytes(xml)

expect(xml.startsWith('<?xml version="1.0" encoding="UTF-16"?>')).toBe(true)
expect([...bytes.subarray(0, 2)]).toEqual([0xff, 0xfe])
expect(bytes.toString("utf16le").startsWith('\uFEFF<?xml version="1.0" encoding="UTF-16"?>')).toBe(true)
})
9 changes: 7 additions & 2 deletions packages/loop-js/src/cli/cron/schtasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export function wrapperCommand(wrapper: string): TaskCommand {
export function buildTaskXml(opts: { expr: string; dir: string; command: TaskCommand; until: Until }): string {
const trigger = triggersXml(expr.schtasks.schedule(opts.expr)) // a refused expr throws before anything is installed
const desc = `${DESC}${opts.expr} ${formatUntil(opts.until)}`
return `<?xml version="1.0" encoding="UTF-8"?>
return `<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo><Description>${xmlEscape(desc)}</Description></RegistrationInfo>
${trigger}
Expand All @@ -126,6 +126,11 @@ export function buildTaskXml(opts: { expr: string; dir: string; command: TaskCom
</Task>`
}

/** The exact bytes `schtasks /Create /XML` receives: UTF-16LE plus an explicit byte-order mark. */
export function taskXmlBytes(xml: string): Buffer {
return Buffer.from(`\uFEFF${xml}`, "utf16le")
}

/** Recover `{ expr, dir, until }` from a task XML we wrote; null if it is not one of ours. */
export function parseTaskXml(xml: string): Pick<Entry, "expr" | "dir" | "until"> | null {
const desc = firstMatch(xml, /<Description>([\s\S]*?)<\/Description>/)
Expand Down Expand Up @@ -176,7 +181,7 @@ export function systemSchtasks(): Schtasks {
const dir = mkdtempSync(join(tmpdir(), "loop-cron-"))
const file = join(dir, "task.xml")
try {
writeFileSync(file, xml, "utf8")
writeFileSync(file, taskXmlBytes(xml))
const r = run(["/Create", "/F", "/TN", taskPath, "/XML", file])
if (r.status !== 0) throw bin.failure("schtasks create", r)
} finally {
Expand Down