170 lines
7.7 KiB
JavaScript
170 lines
7.7 KiB
JavaScript
// Run the installed JXA resolver against a pasteboard shared by shell fixture processes.
|
|
const fs = require('node:fs')
|
|
const vm = require('node:vm')
|
|
const {posix} = require('node:path')
|
|
const {pathToFileURL} = require('node:url')
|
|
|
|
const [resolver, ...argv] = process.argv.slice(2)
|
|
const stateFile = 'test-pasteboard.json'
|
|
const readFixture = (path, fallback) => fs.existsSync(path) ? JSON.parse(fs.readFileSync(path)) : fallback
|
|
const state = readFixture(stateFile, {changeCount: 0, items: []})
|
|
const missingReference = 'test-missing-file-reference'
|
|
const nil = {isNil: () => true}
|
|
const wrap = js => js == null ? nil : {
|
|
js, isNil: () => false, dataUsingEncoding: () => js,
|
|
get stringByStandardizingPath() { return wrap(posix.normalize(js)) },
|
|
get stringByResolvingSymlinksInPath() {
|
|
return wrap(posix.normalize(js).replace(/^\/Volumes\/DropAlias(?=\/|$)/, '/private/guest/DropMount'))
|
|
}
|
|
}
|
|
const unwrap = value => value?.js ?? value
|
|
const array = values => ({
|
|
count: values.length, isNil: () => false, objectAtIndex: i => values[i],
|
|
containsObject: v => values.some(entry => unwrap(entry) === unwrap(v))
|
|
})
|
|
const item = (flavors = {}) => ({
|
|
flavors,
|
|
get types() { return array(Object.keys(flavors).map(wrap)) },
|
|
dataForType: type => wrap(flavors[unwrap(type)]),
|
|
stringForType: type => wrap(flavors[unwrap(type)]),
|
|
setDataForType(value, type) { flavors[unwrap(type)] = unwrap(value); return true },
|
|
setStringForType(value, type) { flavors[unwrap(type)] = unwrap(value); return true }
|
|
})
|
|
|
|
const pasteboard = {
|
|
get pasteboardItems() {
|
|
const items = state.items.map(item)
|
|
if (fs.existsSync('test-reverse-file-readback')) items.reverse()
|
|
return array(items)
|
|
},
|
|
get changeCount() { return state.changeCount },
|
|
get clearContents() { state.items = []; return ++state.changeCount },
|
|
writeObjects(items) {
|
|
const incomingFiles = items.every(i => i.flavors['public.file-url'])
|
|
if (incomingFiles && fs.existsSync('test-fail-file-write')) return false
|
|
state.items = items.map(i => i.flavors)
|
|
if (incomingFiles && fs.existsSync('test-partial-file-write')) state.items.pop()
|
|
state.changeCount++
|
|
return true
|
|
}
|
|
}
|
|
|
|
class FixtureTask {
|
|
get waitUntilExit() {
|
|
if (this.launchPath === '/usr/bin/perl') {
|
|
const [, , , ...paths] = this.arguments
|
|
fs.writeFileSync('test-hosted-probe.json', JSON.stringify(paths))
|
|
const unreadable = readFixture('test-hosted-probe-denied.json', [])
|
|
const errors = readFixture('test-hosted-probe-errors.json', {})
|
|
try {
|
|
for (const path of paths) {
|
|
if (errors[path]) throw Object.assign(Error('Cannot read hosted clipboard source'), {code: errors[path]})
|
|
if (unreadable.includes(path)) throw Error('Cannot read hosted clipboard source')
|
|
const info = fs.statSync(path)
|
|
if (info.isDirectory()) {
|
|
const dir = fs.opendirSync(path)
|
|
try { dir.readSync() } finally { dir.closeSync() }
|
|
} else if (info.isFile()) {
|
|
const fd = fs.openSync(path, 'r')
|
|
try { fs.readSync(fd, Buffer.alloc(1)) } finally { fs.closeSync(fd) }
|
|
} else {
|
|
throw Error('Cannot read hosted clipboard source')
|
|
}
|
|
}
|
|
this.terminationStatus = 0
|
|
} catch (err) { this.terminationStatus = ['EPERM', 'EACCES'].includes(err.code) ? 2 : 1 }
|
|
return
|
|
}
|
|
// The host reads the staged clipboard and may allow a new user copy before it releases the ACK.
|
|
fs.writeFileSync('test-ack.json', JSON.stringify({
|
|
path: this.launchPath, args: this.arguments, config: this.standardInput.config, items: state.items
|
|
}))
|
|
if (fs.existsSync('test-user-copy.json')) {
|
|
state.items = JSON.parse(fs.readFileSync('test-user-copy.json'))
|
|
state.changeCount++
|
|
}
|
|
this.terminationStatus = fs.existsSync('test-fail-ack') ? 22 : 0
|
|
}
|
|
}
|
|
|
|
const errorPointers = new WeakSet()
|
|
const underlyingErrorKey = 'NSUnderlyingError'
|
|
function nativeError({domain, code, underlying}) {
|
|
return {
|
|
domain: wrap(domain), code,
|
|
userInfo: {objectForKey: key => key === underlyingErrorKey && underlying ? nativeError(underlying) : nil}
|
|
}
|
|
}
|
|
|
|
const $ = Object.assign(value => {
|
|
if (value !== undefined) return typeof value === 'string' ? wrap(value) : value
|
|
const error = {isNil() { return !this.domain }}
|
|
errorPointers.add(error)
|
|
return error
|
|
}, {
|
|
NSPasteboard: {generalPasteboard: pasteboard},
|
|
NSPasteboardItem: {alloc: {get init() { return item() }}},
|
|
NSPasteboardTypeFileURL: 'public.file-url',
|
|
NSPasteboardTypeString: 'public.utf8-plain-text',
|
|
NSUnderlyingErrorKey: underlyingErrorKey,
|
|
NSData: {data: wrap('')},
|
|
NSString: {stringWithContentsOfFileEncodingError: path => wrap(fs.readFileSync(path, 'utf8'))},
|
|
NSURL: {
|
|
fileURLWithPath: path => ({
|
|
absoluteString: wrap(pathToFileURL(path).href),
|
|
get fileReferenceURL() {
|
|
fs.appendFileSync('test-mount-reference-probe.log', `${path}\n`)
|
|
if (fs.existsSync(missingReference) && fs.readFileSync(missingReference, 'utf8') === path) return nil
|
|
return fs.existsSync(path) ? wrap(path) : nil
|
|
}
|
|
}),
|
|
URLWithString: raw => {
|
|
const url = new URL(raw)
|
|
return {
|
|
isFileURL: url.protocol === 'file:', isNil: () => false,
|
|
host: wrap(url.host), path: wrap(decodeURIComponent(url.pathname)),
|
|
filePathURL: {isNil: () => false, path: wrap('/private/guest/DropMount/readback')}
|
|
}
|
|
}
|
|
},
|
|
NSFileManager: {defaultManager: {
|
|
fileExistsAtPathIsDirectory(path, dir) {
|
|
dir[0] = fs.statSync(path, {throwIfNoEntry: false})?.isDirectory() ?? false
|
|
return fs.existsSync(path)
|
|
},
|
|
contentsOfDirectoryAtPathError(path, err) {
|
|
const boxed = errorPointers.has(err)
|
|
fs.appendFileSync('test-mount-directory-probe.log', `${path}\t${boxed ? '$()' : 'invalid'}\n`)
|
|
if (!boxed) throw Error('Directory enumeration requires a boxed NSError')
|
|
const errors = readFixture('test-mount-directory-errors.json', {})
|
|
if (Object.hasOwn(errors, path)) {
|
|
if (errors[path]) Object.assign(err, nativeError(errors[path]))
|
|
return nil
|
|
}
|
|
try {
|
|
return array(fs.readdirSync(path).map(wrap))
|
|
} catch (failure) {
|
|
const code = failure.code === 'ENOENT' ? 260 : 256
|
|
Object.assign(err, nativeError({domain: 'NSCocoaErrorDomain', code}))
|
|
return nil
|
|
}
|
|
},
|
|
fileExistsAtPath: fs.existsSync
|
|
}},
|
|
NSDate: {dateWithTimeIntervalSinceNow: seconds => seconds},
|
|
NSRunLoop: {currentRunLoop: {runUntilDate: () => fs.writeFileSync('test-pasteboard-flush', String(state.changeCount))}},
|
|
NSProcessInfo: {processInfo: {environment: {objectForKey: key => wrap(process.env[unwrap(key)])}}},
|
|
NSTask: {alloc: {get init() { return new FixtureTask() }}},
|
|
NSPipe: {get pipe() {
|
|
const pipe = {fileHandleForWriting: {writeData(data) { pipe.config = data }}}
|
|
return pipe
|
|
}},
|
|
NSFileHandle: {fileHandleWithNullDevice: null}
|
|
})
|
|
const context = {ObjC: {import() {}, unwrap, deepUnwrap: unwrap}, $, argv, Ref: () => []}
|
|
try {
|
|
console.log(vm.runInNewContext(fs.readFileSync(resolver, 'utf8') + '\nrun(argv)', context))
|
|
} finally {
|
|
fs.writeFileSync(stateFile, JSON.stringify(state))
|
|
}
|