import { runJxa } from "../apple-events.js"; const CONTACTS_SEARCH_SCRIPT = String.raw` function text(value) { try { return value ? String(value) : ""; } catch (_) { return ""; } } function run(argv) { const input = JSON.parse(argv[0]); const app = Application("Contacts"); const query = (input.query || "").toLowerCase(); const people = app.people(); const found = []; for (let i = 0; i < people.length && found.length < input.limit; i++) { const person = people[i]; const name = text(person.name()); const organization = text(person.organization()); if (query && (name + "\n" + organization).toLowerCase().indexOf(query) === -1) continue; found.push({ id: String(person.id()), name: name, organization: organization, modifiedAt: person.modificationDate().toISOString() }); } return JSON.stringify(found); }`; const CONTACTS_READ_SCRIPT = String.raw` function text(value) { try { return value ? String(value) : ""; } catch (_) { return ""; } } function items(values) { return values.map(function (value) { return { label: text(value.label()), value: text(value.value()) }; }); } function run(argv) { const input = JSON.parse(argv[0]); const app = Application("Contacts"); const people = app.people(); for (let i = 0; i < people.length; i++) { const person = people[i]; if (String(person.id()) !== input.id) continue; return JSON.stringify({ id: String(person.id()), name: text(person.name()), firstName: text(person.firstName()), lastName: text(person.lastName()), organization: text(person.organization()), jobTitle: text(person.jobTitle()), emails: items(person.emails()), phones: items(person.phones()), modifiedAt: person.modificationDate().toISOString() }); } throw new Error("Contact not found"); }`; const CONTACTS_CREATE_SCRIPT = String.raw` function run(argv) { const input = JSON.parse(argv[0]); const app = Application("Contacts"); const person = app.Person({ firstName: input.firstName || "", lastName: input.lastName || "", organization: input.organization || "", jobTitle: input.jobTitle || "", note: input.note || "" }); app.people.push(person); if (input.email) { person.emails.push(app.Email({label: input.email.label, value: input.email.value})); } if (input.phone) { person.phones.push(app.Phone({label: input.phone.label, value: input.phone.value})); } app.save(); return JSON.stringify({ id: String(person.id()), name: String(person.name()), organization: input.organization || "" }); }`; export function searchContacts(input) { return runJxa(CONTACTS_SEARCH_SCRIPT, input); } export function readContact(id) { return runJxa(CONTACTS_READ_SCRIPT, { id }); } export function createContact(input) { return runJxa(CONTACTS_CREATE_SCRIPT, input); }