@photon-ai/imessage-kit3.0.083.6 kB
import { homedir, release } from 'os';
import { join, extname, resolve, basename, dirname } from 'path';
import { Unarchiver, NSAttributedString } from '@parseaple/typedstream';
import { createRequire } from 'module';
import { existsSync, readdirSync, lstatSync, rmSync, watch, statSync } from 'fs';
import { execFile, spawn } from 'child_process';
import { promisify } from 'util';
import { access } from 'fs/promises';
// src/domain/errors.ts
var IMessageError = class _IMessageError extends Error {
code;
constructor(code, message, options) {
super(message, options);
this.code = code;
this.name = "IMessageError";
if (Error.captureStackTrace) {
Error.captureStackTrace(this, _IMessageError);
}
}
};
function PlatformError(message = "Only macOS is supported", cause) {
return new IMessageError("PLATFORM", message, { cause });
}
function DatabaseError(message, cause) {
return new IMessageError("DATABASE", message, { cause });
}
function SendError(message, cause) {
return new IMessageError("SEND", message, { cause });
}
function ConfigError(message, cause) {
return new IMessageError("CONFIG", message, { cause });
}
function toError(value) {
return value instanceof Error ? value : new Error(String(value));
}
function toErrorMessage(value) {
return value instanceof Error ? value.message : String(value);
}
// src/application/message-dispatcher.ts
var MessageDispatcher = class {
events;
sink;
debug;
constructor(options = {}) {
this.events = options.events ?? {};
this.sink = options.sink;
this.debug = options.debug ?? false;
}
/**
* Process a batch of messages from the watch source.
*
* Pipeline: partition by `isFromMe` → dispatch each branch in parallel.
* Within a branch, messages are processed sequentially so ordering
* inside the user's callback is preserved; the two branches are
* independent, so a slow from-me handler never blocks incoming
* delivery (and vice-versa).
*
* Serialization of batches is the watcher's contract — the consumer loop
* awaits one dispatch before producing the next batch.
*/
async dispatch(messages) {
const incoming = [];
const fromMe = [];
for (const message of messages) {
if (message.isFromMe) fromMe.push(message);
else incoming.push(message);
}
await Promise.all([this.dispatchIncoming(incoming), this.dispatchFromMe(fromMe)]);
}
/** Forward an external error to the sink and user callback. */
handleError(error, context) {
const err = toError(error);
if (this.debug) {
console.error(`[MessageDispatcher] ${context}:`, err);
}
this.sink?.onError(err, context);
this.events.onError?.(err);
}
// -----------------------------------------------
// Internal
// -----------------------------------------------
async dispatchIncoming(messages) {
for (const message of messages) {
try {
await this.dispatchOneIncoming(message);
} catch (error) {
this.handleError(error, "dispatch-message");
}
}
}
async dispatchOneIncoming(message) {
await this.sink?.onIncomingMessage(message);
await this.events.onIncomingMessage?.(message);
switch (message.chatKind) {
case "group":
await this.events.onGroupMessage?.(message);
break;
case "dm":
await this.events.onDirectMessage?.(message);
break;
}
}
async dispatchFromMe(messages) {
for (const message of messages) {
try {
await this.sink?.onFromMe(message);
await this.events.onFromMeMessage?.(message);
} catch (error) {
this.handleError(error, "dispatch-from-me");
}
}
}
};
// src/utils/async.ts
function delay(ms, signal) {
return new Promise((resolve2, reject) => {
if (signal?.aborted) {
reject(signal.reason ?? new Error("Aborted"));
return;
}
const cleanup = () => {
clearTimeout(id);
signal?.removeEventListener("abort", onAbort);
};
const onAbort = () => {
cleanup();
reject(signal?.reason ?? new Error("Aborted"));
};
const id = setTimeout(() => {
cleanup();
resolve2();
}, ms);
signal?.addEventListener("abort", onAbort, { once: true });
});
}
async function retry(fn, options = {}) {
const attempts = Math.max(1, Math.trunc(options.attempts ?? 3));
const baseDelay = Math.max(0, options.delay ?? 1e3);
const backoff = options.backoff ?? true;
const maxDelay = Math.max(baseDelay, options.maxDelay ?? 3e4);
const { signal } = options;
let lastError;
for (let attempt = 0; attempt < attempts; attempt++) {
if (signal?.aborted) throw signal.reason ?? new Error("Aborted");
try {
return await fn();
} catch (err) {
lastError = err instanceof Error ? err : new Error(String(err));
if (signal?.aborted) throw signal.reason ?? new Error("Aborted");
if (attempt < attempts - 1) {
const exponential = backoff ? baseDelay * 2 ** attempt : baseDelay;
const capped = Math.min(exponential, maxDelay);
await delay(Math.random() * capped, signal);
}
}
}
throw lastError;
}
var Semaphore = class {
constructor(limit) {
this.limit = limit;
if (limit <= 0) throw new Error("Concurrency limit must be greater than 0");
}
running = 0;
waiting = [];
/**
* Acquire a slot. Returns a release function.
*
* Slot-transfer semantics guarantee strict FIFO fairness:
* a waiter that is woken up has had the slot handed to it directly,
* so there is no re-check race where a late-arriving caller could
* jump ahead. The release function either transfers the slot to the
* next waiter (running unchanged) or decrements the counter.
*/
async acquire(signal) {
if (signal?.aborted) throw signal.reason ?? new Error("Aborted");
if (this.running >= this.limit) {
await new Promise((resolve2, reject) => {
const onAbort = () => {
const idx = this.waiting.indexOf(wrappedResolve);
if (idx !== -1) this.waiting.splice(idx, 1);
reject(signal?.reason ?? new Error("Aborted"));
};
const wrappedResolve = () => {
signal?.removeEventListener("abort", onAbort);
resolve2();
};
signal?.addEventListener("abort", onAbort, { once: true });
this.waiting.push(wrappedResolve);
});
} else {
this.running++;
}
let released = false;
return () => {
if (released) return;
released = true;
const next = this.waiting.shift();
if (next) {
next();
} else {
this.running--;
}
};
}
/** Execute fn within a concurrency slot. */
async run(fn, signal) {
const release2 = await this.acquire(signal);
try {
return await fn();
} finally {
release2();
}
}
};
// src/domain/chat.ts
var CHAT_STYLE_GROUP = 43;
var CHAT_STYLE_DM = 45;
function resolveChatKind(style) {
switch (style) {
case CHAT_STYLE_GROUP:
return "group";
case CHAT_STYLE_DM:
return "dm";
default:
return "unknown";
}
}
// src/domain/timestamp.ts
var MAC_EPOCH = (/* @__PURE__ */ new Date("2001-01-01T00:00:00Z")).getTime();
function toMacTimestampNs(date) {
return (date.getTime() - MAC_EPOCH) * 1e6;
}
function fromMacTimestampNs(ns) {
return new Date(MAC_EPOCH + ns / 1e6);
}
// src/domain/chat-id.ts
var GROUP_SEPARATOR = ";+;";
var DM_SEPARATOR = ";-;";
var CHAT_SERVICE_PREFIX_PATTERN = /^[A-Za-z][A-Za-z0-9._-]*$/;
var BARE_GROUP_GUID_PATTERN = /^chat[A-Za-z0-9-]+$/;
function parseChatServicePrefix(value) {
if (value == null || value === "") return null;
return CHAT_SERVICE_PREFIX_PATTERN.test(value) ? value : null;
}
function isValidPrefixedFormat(raw, separator) {
const index = raw.indexOf(separator);
if (index === -1) return false;
const prefix = raw.slice(0, index);
const suffix = raw.slice(index + separator.length);
return parseChatServicePrefix(prefix) != null && suffix !== "";
}
var ChatId = class _ChatId {
/** The raw chat identifier string. */
raw;
/** Whether this identifies a group conversation. */
isGroup;
constructor(raw, isGroup) {
this.raw = raw;
this.isGroup = isGroup;
}
// -----------------------------------------------
// Factory methods
// -----------------------------------------------
/**
* Construct from a raw identifier string. Whitespace is trimmed —
* the name signals the input may be untrusted.
*/
static fromUserInput(raw) {
const trimmed = raw.trim();
return new _ChatId(trimmed, _ChatId.detectGroup(trimmed));
}
/** Construct a DM chat id from a recipient address and optional service prefix. */
static fromDMRecipient(recipient, prefix = "iMessage") {
return new _ChatId(`${prefix}${DM_SEPARATOR}${recipient}`, false);
}
// -----------------------------------------------
// Computed properties
// -----------------------------------------------
/**
* Core identifier with all service prefixes stripped.
*
* iMessage;-;pilot@photon.codes → pilot@photon.codes
* iMessage;+;chat613ABF → chat613ABF
* chat613ABF → chat613ABF
*/
get coreIdentifier() {
return this.extractAfter(GROUP_SEPARATOR) ?? this.extractAfter(DM_SEPARATOR) ?? this.raw;
}
// -----------------------------------------------
// Methods
// -----------------------------------------------
/**
* Extract the recipient address from a `service;-;address` DM chat id.
*
* Returns `null` for any other form (bare address, group, etc.).
*/
extractRecipient() {
return this.extractAfter(DM_SEPARATOR);
}
/**
* Validate the chat id format.
*
* Throws `IMessageError` (code `CONFIG`) for malformed inputs. Accepts the
* three documented formats: `service;+;guid`, `service;-;address`, and any
* non-empty bare identifier (no semicolons).
*/
validate() {
if (this.raw.trim() === "") {
throw ConfigError("ChatId cannot be empty");
}
if (!this.raw.includes(";")) return;
if (isValidPrefixedFormat(this.raw, GROUP_SEPARATOR) || isValidPrefixedFormat(this.raw, DM_SEPARATOR)) {
return;
}
throw ConfigError(`Malformed chat id: "${this.raw}" (expected service;+;guid or service;-;address)`);
}
/**
* Build a full Messages.app guid with a service prefix.
*
* chat613ABF + `iMessage` → iMessage;+;chat613ABF
*
* Group-only: throws `IMessageError` (code `CONFIG`) on DM instances —
* calling on a DM would produce a malformed id like `any;+;+1234567890`.
*/
buildGroupGuid(prefix) {
if (!this.isGroup) {
throw ConfigError(`buildGroupGuid is group-only; "${this.raw}" is not a group chat id`);
}
return `${prefix}${GROUP_SEPARATOR}${this.coreIdentifier}`;
}
toString() {
return this.raw;
}
// -----------------------------------------------
// Internal
// -----------------------------------------------
/**
* Extract everything after the first occurrence of separator, or `null`
* if the separator is absent OR the suffix is empty (e.g. `iMessage;-;`).
* Empty-suffix inputs are malformed; treating them as "not found" keeps
* callers from receiving `""` as if it were a valid identifier.
*/
extractAfter(separator) {
const index = this.raw.indexOf(separator);
if (index === -1) return null;
const suffix = this.raw.slice(index + separator.length);
return suffix === "" ? null : suffix;
}
static detectGroup(raw) {
if (raw.includes(GROUP_SEPARATOR)) return true;
if (!raw.includes(";") && BARE_GROUP_GUID_PATTERN.test(raw)) return true;
return false;
}
};
// src/infra/db/contract.ts
function buildChatIdMatchSql(userInput, columns) {
const core = ChatId.fromUserInput(userInput).coreIdentifier;
const values = core === userInput ? [userInput] : [userInput, core];
const placeholders = values.map(() => "?").join(", ");
return {
sql: `(${columns.identifier} IN (${placeholders}) OR ${columns.guid} IN (${placeholders}))`,
params: [...values, ...values]
};
}
// src/infra/db/macos26.ts
var MESSAGE_FIELDS = [
"message.ROWID as id",
"message.guid",
"message.text",
"message.attributedBody",
"message.service",
"message.is_from_me",
"message.is_read",
"message.is_sent",
"message.is_delivered",
"message.was_downgraded",
"message.did_notify_recipient",
"message.is_auto_reply",
"message.is_system_message",
"message.is_forward",
"message.is_audio_message",
"message.is_played",
"message.is_expirable",
"message.error",
"message.is_spam",
"message.is_kt_verified",
"message.has_unseen_mention",
"message.was_delivered_quietly",
"message.is_sos",
"message.is_critical",
"message.sent_or_received_off_grid",
"message.date",
"message.date_delivered",
"message.date_read",
"message.date_played",
"message.date_edited",
"message.date_retracted",
"message.date_recovered",
"message.is_empty",
"message.message_summary_info",
"message.reply_to_guid",
"message.thread_originator_guid",
"message.group_title",
"message.expressive_send_style_id",
"message.balloon_bundle_id",
"message.destination_caller_id",
"message.ck_chat_id as ck_chat_id",
"message.was_detonated",
"message.expire_state",
"message.share_status",
"message.share_direction",
"message.schedule_type",
"message.schedule_state",
"message.part_count",
"message.cache_has_attachments",
"message.associated_message_type",
"message.associated_message_guid",
"message.associated_message_emoji",
"message.associated_message_range_location",
"message.associated_message_range_length",
"message.item_type",
"message.group_action_type",
"handle.id as participant",
"other_handle.id as affected_participant",
"chat.chat_identifier as chat_id",
"chat.guid as chat_guid",
"chat.style as chat_style"
];
var CHAT_FIELDS = [
"chat.guid",
"chat.chat_identifier",
"chat.service_name",
"chat.style",
"chat.account_login",
"chat.is_archived",
"chat.is_filtered",
"chat.is_blackholed",
"chat.is_deleting_incoming_messages",
"chat.last_read_message_timestamp",
"chat.display_name",
"chat_stats.last_date",
"COALESCE(chat_stats.unread_count, 0) AS unread_count"
];
var ATTACHMENT_FIELDS = [
"message_attachment_join.message_id as msg_id",
"attachment.guid",
"attachment.created_date",
"attachment.filename",
"attachment.uti",
"attachment.mime_type",
"attachment.transfer_state",
"attachment.is_outgoing",
"attachment.transfer_name",
"attachment.total_bytes",
"attachment.is_sticker",
"attachment.is_commsafety_sensitive",
"attachment.emoji_image_short_description"
];
function escapeLikePattern(input) {
return input.replace(/[%_\\]/g, (ch) => `\\${ch}`);
}
var macos26Queries = {
buildMessageQuery(filter) {
const conditions = [];
const params = [];
if (filter.isRead === true) {
conditions.push("message.is_read = 1");
} else if (filter.isRead === false) {
conditions.push("message.is_read = 0");
}
if (filter.isFromMe === true) {
conditions.push("message.is_from_me = 1");
} else if (filter.isFromMe === false) {
conditions.push("message.is_from_me = 0");
}
if (filter.participant) {
conditions.push("handle.id = ?");
params.push(filter.participant);
}
if (filter.chatId) {
const match = buildChatIdMatchSql(filter.chatId, {
identifier: "chat.chat_identifier",
guid: "chat.guid"
});
conditions.push(match.sql);
params.push(...match.params);
}
if (filter.service) {
conditions.push("message.service = ?");
params.push(filter.service);
}
if (filter.hasAttachments === true) {
conditions.push(
"EXISTS (SELECT 1 FROM message_attachment_join WHERE message_attachment_join.message_id = message.ROWID)"
);
} else if (filter.hasAttachments === false) {
conditions.push(
"NOT EXISTS (SELECT 1 FROM message_attachment_join WHERE message_attachment_join.message_id = message.ROWID)"
);
}
if (filter.excludeReactions) {
conditions.push("(message.associated_message_type IS NULL OR message.associated_message_type = 0)");
}
if (filter.sinceRowId != null) {
conditions.push("message.ROWID > ?");
params.push(filter.sinceRowId);
}
if (filter.since) {
conditions.push("message.date >= ?");
params.push(toMacTimestampNs(filter.since));
}
if (filter.before) {
conditions.push("message.date < ?");
params.push(toMacTimestampNs(filter.before));
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
const hasLimit = filter.limit != null && filter.limit > 0;
const hasOffset = filter.offset != null && filter.offset > 0;
let limitClause = "";
if (hasLimit) {
limitClause = "LIMIT ?";
params.push(filter.limit);
} else if (hasOffset) {
limitClause = "LIMIT -1";
}
const offsetClause = hasOffset ? "OFFSET ?" : "";
if (hasOffset) {
params.push(filter.offset);
}
const orderBy = filter.orderByRowIdAsc ? "ORDER BY message.ROWID ASC" : "ORDER BY message.date DESC";
return {
sql: `
SELECT
${MESSAGE_FIELDS.join(",\n ")}
FROM message
LEFT JOIN handle ON message.handle_id = handle.ROWID
LEFT JOIN handle AS other_handle ON message.other_handle = other_handle.ROWID
-- A message can appear in multiple chat_message_join rows (rare,
-- e.g. cross-posted group messages). MIN(chat_id) picks the
-- lowest-ROWID chat deterministically so repeated queries
-- return the same chat_guid/chat_identifier for the message.
LEFT JOIN chat ON chat.ROWID = (
SELECT MIN(chat_message_join.chat_id)
FROM chat_message_join
WHERE chat_message_join.message_id = message.ROWID
)
${where}
${orderBy}
${limitClause}
${offsetClause}
`,
params
};
},
buildChatQuery(query) {
const conditions = [];
const params = [];
if (query.chatId) {
const match = buildChatIdMatchSql(query.chatId, {
identifier: "chat_identifier",
guid: "guid"
});
conditions.push(match.sql);
params.push(...match.params);
}
if (query.kind === "group") {
conditions.push("style = ?");
params.push(CHAT_STYLE_GROUP);
} else if (query.kind === "dm") {
conditions.push("style = ?");
params.push(CHAT_STYLE_DM);
}
if (query.service) {
conditions.push("service_name = ?");
params.push(query.service);
}
if (query.isArchived === true) {
conditions.push("is_archived = 1");
} else if (query.isArchived === false) {
conditions.push("is_archived = 0");
}
if (query.hasUnread === true) {
conditions.push("unread_count > 0");
} else if (query.hasUnread === false) {
conditions.push("unread_count = 0");
}
if (query.search) {
const escaped = escapeLikePattern(query.search);
conditions.push("(display_name LIKE ? ESCAPE '\\' OR chat_identifier LIKE ? ESCAPE '\\')");
params.push(`%${escaped}%`, `%${escaped}%`);
}
const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
let orderBy = "";
if (query.sortBy === "recent") {
orderBy = "ORDER BY (last_date IS NULL), last_date DESC";
} else if (query.sortBy === "name") {
orderBy = "ORDER BY (display_name IS NULL), display_name ASC";
}
const hasLimit = query.limit != null && query.limit > 0;
const hasOffset = query.offset != null && query.offset > 0;
let limitClause = "";
if (hasLimit) {
limitClause = "LIMIT ?";
params.push(query.limit);
} else if (hasOffset) {
limitClause = "LIMIT -1";
}
const offsetClause = hasOffset ? "OFFSET ?" : "";
if (hasOffset) {
params.push(query.offset);
}
return {
sql: `
WITH chat_stats AS (
SELECT
chat_message_join.chat_id,
MAX(message.date) AS last_date,
SUM(
CASE
WHEN message.is_read = 0 AND message.is_from_me = 0 THEN 1
ELSE 0
END
) AS unread_count
FROM chat_message_join
INNER JOIN message ON message.ROWID = chat_message_join.message_id
GROUP BY chat_message_join.chat_id
),
enriched AS (
SELECT
${CHAT_FIELDS.join(",\n ")}
FROM chat
LEFT JOIN chat_stats ON chat_stats.chat_id = chat.ROWID
)
SELECT *
FROM enriched
${where}
${orderBy}
${limitClause}
${offsetClause}
`,
params
};
},
buildAttachmentQuery(messageIds) {
const placeholders = messageIds.map(() => "?").join(",");
return {
sql: `
SELECT
${ATTACHMENT_FIELDS.join(",\n ")}
FROM attachment
INNER JOIN message_attachment_join ON attachment.ROWID = message_attachment_join.attachment_id
WHERE message_attachment_join.message_id IN (
${placeholders}
)
AND (attachment.hide_attachment IS NULL OR attachment.hide_attachment = 0)
ORDER BY message_attachment_join.message_id ASC, message_attachment_join.attachment_id ASC
`,
params: messageIds
};
},
buildMaxRowIdQuery() {
return { sql: "SELECT MAX(ROWID) AS max_id FROM message", params: [] };
},
buildChatBackfillQuery(messageIds) {
const placeholders = messageIds.map(() => "?").join(",");
return {
sql: `
SELECT
chat_message_join.message_id AS message_rowid,
chat.chat_identifier AS chat_id,
chat.guid AS chat_guid,
chat.style AS chat_style
FROM chat_message_join
INNER JOIN chat ON chat.ROWID = chat_message_join.chat_id
WHERE chat_message_join.message_id IN (${placeholders})
AND chat_message_join.chat_id = (
SELECT MIN(inner_join.chat_id)
FROM chat_message_join inner_join
WHERE inner_join.message_id = chat_message_join.message_id
)
`,
params: messageIds
};
}
};
// src/domain/attachment.ts
function resolveTransferStatus(code) {
switch (code) {
case -1:
case 0:
return "pending";
case 1:
case 2:
case 3:
case 4:
return "transferring";
case 5:
return "complete";
case 6:
case 7:
return "failed";
default:
return "unknown";
}
}
// src/domain/message.ts
function resolveMessageKind(itemType, groupActionType) {
switch (itemType) {
case 0:
return "text";
case 1:
return groupActionType === 1 ? "memberRemoved" : "memberAdded";
case 2:
return "nameChanged";
case 3:
return "groupAction";
default:
return "unknown";
}
}
function resolveExpireStatus(code) {
switch (code) {
case 1:
return "willExpire";
case 2:
return "expired";
default:
return "active";
}
}
function resolveShareActivity(code) {
switch (code) {
case 0:
return "none";
case 1:
return "pending";
case 2:
return "active";
default:
return "unknown";
}
}
function resolveShareDirection(code) {
switch (code) {
case 0:
return "none";
case 1:
return "incoming";
case 2:
return "outgoing";
default:
return "unknown";
}
}
function resolveScheduleKind(code) {
switch (code) {
case 0:
return "none";
case 1:
case 2:
return "sendLater";
default:
return "unknown";
}
}
function resolveScheduleStatus(code) {
switch (code) {
case 0:
return "none";
case 1:
return "pending";
case 2:
return "sent";
case 3:
return "failed";
default:
return "unknown";
}
}
// src/domain/reaction.ts
var REACTION_KIND_MAP = {
2e3: "love",
2001: "like",
2002: "dislike",
2003: "laugh",
2004: "emphasize",
2005: "question",
2006: "emoji",
2007: "sticker"
};
var STANDALONE_REACTION_MAP = {
1e3: "sticker",
4e3: "pollVote"
};
function resolveReactionMeta(type) {
if (type == null || type === 0) {
return { kind: null, isRemoved: false };
}
const standalone = STANDALONE_REACTION_MAP[type];
if (standalone != null) {
return { kind: standalone, isRemoved: false };
}
const isAdd = type >= 2e3 && type <= 2007;
const isRemove = type >= 3e3 && type <= 3007;
if (!isAdd && !isRemove) {
return { kind: null, isRemoved: false };
}
const baseType = isRemove ? type - 1e3 : type;
const kind = REACTION_KIND_MAP[baseType] ?? null;
return { kind, isRemoved: isRemove };
}
// src/domain/service.ts
var SERVICE_MAP = {
imessage: "iMessage",
sms: "SMS",
rcs: "RCS"
};
function resolveService(raw) {
if (raw == null) return null;
return SERVICE_MAP[raw.toLowerCase()] ?? null;
}
function extractTextFromAttributedBody(blob) {
try {
const buffer = Buffer.isBuffer(blob) ? blob : Buffer.from(blob);
if (buffer.length === 0) return null;
const root = Unarchiver.open(buffer, Unarchiver.BinaryDecoding.decodable).decodeSingleRoot();
if (root instanceof NSAttributedString && root.string) {
return root.string;
}
return null;
} catch {
return null;
}
}
// src/infra/db/mapper.ts
var HOME_DIR = homedir();
function parseNumber(value) {
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
if (typeof value === "bigint") {
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
if (typeof value === "string" && value.trim() !== "") {
const parsed = Number(value);
return Number.isFinite(parsed) ? parsed : null;
}
return null;
}
function optionalNumber(value, fieldName) {
if (value == null) return null;
const parsed = parseNumber(value);
if (parsed != null) return parsed;
throw new Error(`Invalid numeric field: ${fieldName}`);
}
function requireNumber(value, fieldName) {
const parsed = optionalNumber(value, fieldName);
if (parsed != null) return parsed;
throw new Error(`Missing numeric field: ${fieldName}`);
}
function optionalString(value, fieldName) {
if (value == null) return null;
if (typeof value === "string") return value;
throw new Error(`Invalid string field: ${fieldName}`);
}
function optionalNonEmptyString(value, fieldName) {
const parsed = optionalString(value, fieldName);
return parsed == null || parsed === "" ? null : parsed;
}
function requireNonEmptyString(value, fieldName) {
const parsed = optionalNonEmptyString(value, fieldName);
if (parsed != null) return parsed;
throw new Error(`Missing string field: ${fieldName}`);
}
function flag(value, fieldName) {
if (typeof value === "boolean") return value;
if (value == null) return false;
const parsed = parseNumber(value);
if (parsed != null) return parsed !== 0;
throw new Error(`Invalid boolean field: ${fieldName}`);
}
function optionalDate(value, fieldName) {
const parsed = optionalNumber(value, fieldName);
if (parsed == null || parsed === 0) return null;
return fromMacTimestampNs(parsed);
}
function requireDate(value, fieldName) {
return fromMacTimestampNs(requireNumber(value, fieldName));
}
function optionalParticipant(value, fieldName) {
const str = optionalString(value, fieldName);
if (str == null) return null;
const trimmed = str.trim();
return trimmed === "" ? null : trimmed;
}
function resolveMessageChatId(row) {
const primary = resolvePrimaryChatId(row.chat_guid, row.chat_id) ?? resolveCloudKitChatId(row.ck_chat_id);
if (primary != null) return primary;
if (!flag(row.is_from_me, "message.is_from_me")) return null;
return resolveRecipientChatId(row.destination_caller_id, row.service, "message.destination_caller_id");
}
function resolveRecipientChatId(recipient, service, fieldName) {
const value = optionalParticipant(recipient, fieldName);
if (value == null) return null;
const servicePrefix = parseChatServicePrefix(optionalNonEmptyString(service, "message.service"));
return servicePrefix ? ChatId.fromDMRecipient(value, servicePrefix) : ChatId.fromUserInput(value);
}
function resolvePrimaryChatId(guid, identifier) {
const raw = optionalNonEmptyString(guid, "message.chat_guid") ?? optionalNonEmptyString(identifier, "message.chat_id");
return raw == null ? null : ChatId.fromUserInput(raw);
}
function resolveCloudKitChatId(value) {
const raw = optionalParticipant(value, "message.ck_chat_id");
return raw == null ? null : ChatId.fromUserInput(raw);
}
function resolveMessageText(row) {
const text = optionalString(row.text, "message.text");
if (text != null && text !== "") {
return text;
}
if (row.attributedBody == null) {
return null;
}
if (!Buffer.isBuffer(row.attributedBody) && !(row.attributedBody instanceof Uint8Array)) {
return null;
}
const value = extractTextFromAttributedBody(row.attributedBody);
return value === "" ? null : value;
}
function mapReaction(row) {
const meta = resolveReactionMeta(optionalNumber(row.associated_message_type, "message.associated_message_type"));
if (meta.kind == null) {
return null;
}
return {
kind: meta.kind,
targetMessageId: optionalNonEmptyString(row.associated_message_guid, "message.associated_message_guid"),
emoji: optionalNonEmptyString(row.associated_message_emoji, "message.associated_message_emoji"),
textRange: {
location: optionalNumber(row.associated_message_range_location, "message.associated_message_range_location") ?? 0,
length: optionalNumber(row.associated_message_range_length, "message.associated_message_range_length") ?? 0
},
isRemoved: meta.isRemoved
};
}
function mapChatId(row) {
const guid = requireNonEmptyString(row.guid, "chat.guid");
return ChatId.fromUserInput(guid).toString();
}
function rowToChat(row) {
return {
chatId: mapChatId(row),
name: optionalNonEmptyString(row.display_name, "chat.display_name"),
service: resolveService(optionalNonEmptyString(row.service_name, "chat.service_name")),
kind: resolveChatKind(optionalNumber(row.style, "chat.style")),
account: optionalNonEmptyString(row.account_login, "chat.account_login"),
isArchived: flag(row.is_archived, "chat.is_archived"),
isFiltered: flag(row.is_filtered, "chat.is_filtered"),
dropsIncomingMessages: flag(row.is_blackholed, "chat.is_blackholed"),
autoDeletesIncomingMessages: flag(row.is_deleting_incoming_messages, "chat.is_deleting_incoming_messages"),
lastReadAt: optionalDate(row.last_read_message_timestamp, "chat.last_read_message_timestamp"),
unreadCount: requireNumber(row.unread_count, "chat.unread_count"),
lastMessageAt: optionalDate(row.last_date, "chat.last_date")
};
}
function resolveMessageChatKind(chatStyle, resolved) {
if (chatStyle != null) return resolveChatKind(chatStyle);
if (resolved == null) return "unknown";
return resolved.isGroup ? "group" : "dm";
}
function detectTahoeRetract(row) {
const isEmpty = optionalNumber(row.is_empty, "message.is_empty") === 1;
if (!isEmpty) return false;
const summary = row.message_summary_info;
if (!summary) return false;
let buf = null;
if (Buffer.isBuffer(summary)) buf = summary;
else if (summary instanceof Uint8Array) buf = Buffer.from(summary);
if (!buf || buf.length < 6) return false;
return buf.includes(Buffer.from([82, 114, 112]));
}
function patchMessageChatInfo(message, chatRow) {
const resolved = resolvePrimaryChatId(chatRow.chat_guid, chatRow.chat_id);
const chatId = resolved?.toString() ?? message.chatId;
const chatKind = resolveMessageChatKind(optionalNumber(chatRow.chat_style, "chat.style"), resolved);
if (chatId === message.chatId && chatKind === message.chatKind) return message;
return { ...message, chatId, chatKind };
}
function rowToMessage(row, attachments) {
const resolved = resolveMessageChatId(row);
const chatId = resolved?.toString() ?? null;
const chatKind = resolveMessageChatKind(optionalNumber(row.chat_style, "message.chat_style"), resolved);
const errorCode = optionalNumber(row.error, "message.error") ?? 0;
const reaction = mapReaction(row);
const directRetract = optionalDate(row.date_retracted, "message.date_retracted");
const retractedAt = directRetract ?? (detectTahoeRetract(row) ? optionalDate(row.date_edited, "message.date_edited") ?? optionalDate(row.date, "message.date") : null);
return {
rowId: requireNumber(row.id, "message.id"),
id: requireNonEmptyString(row.guid, "message.guid"),
chatId,
chatKind,
participant: optionalParticipant(row.participant, "message.participant"),
service: resolveService(optionalNonEmptyString(row.service, "message.service")),
text: resolveMessageText(row),
kind: resolveMessageKind(
optionalNumber(row.item_type, "message.item_type"),
optionalNumber(row.group_action_type, "message.group_action_type")
),
isFromMe: flag(row.is_from_me, "message.is_from_me"),
isRead: flag(row.is_read, "message.is_read"),
isSent: flag(row.is_sent, "message.is_sent"),
isDelivered: flag(row.is_delivered, "message.is_delivered"),
isDowngraded: flag(row.was_downgraded, "message.was_downgraded"),
didNotifyRecipient: flag(row.did_notify_recipient, "message.did_notify_recipient"),
isAutoReply: flag(row.is_auto_reply, "message.is_auto_reply"),
isSystem: flag(row.is_system_message, "message.is_system_message"),
isForwarded: flag(row.is_forward, "message.is_forward"),
isAudioMessage: flag(row.is_audio_message, "message.is_audio_message"),
isPlayed: flag(row.is_played, "message.is_played"),
isExpirable: flag(row.is_expirable, "message.is_expirable"),
hasError: errorCode !== 0,
errorCode,
isSpam: flag(row.is_spam, "message.is_spam"),
isContactKeyVerified: flag(row.is_kt_verified, "message.is_kt_verified"),
hasUnseenMention: flag(row.has_unseen_mention, "message.has_unseen_mention"),
wasDeliveredQuietly: flag(row.was_delivered_quietly, "message.was_delivered_quietly"),
isEmergencySos: flag(row.is_sos, "message.is_sos"),
isCriticalAlert: flag(row.is_critical, "message.is_critical"),
isOffGrid: flag(row.sent_or_received_off_grid, "message.sent_or_received_off_grid"),
createdAt: requireDate(row.date, "message.date"),
deliveredAt: optionalDate(row.date_delivered, "message.date_delivered"),
readAt: optionalDate(row.date_read, "message.date_read"),
playedAt: optionalDate(row.date_played, "message.date_played"),
editedAt: optionalDate(row.date_edited, "message.date_edited"),
retractedAt,
recoveredAt: optionalDate(row.date_recovered, "message.date_recovered"),
replyToMessageId: optionalNonEmptyString(row.reply_to_guid, "message.reply_to_guid"),
threadRootMessageId: optionalNonEmptyString(row.thread_originator_guid, "message.thread_originator_guid"),
affectedParticipant: optionalParticipant(row.affected_participant, "message.affected_participant"),
newGroupName: optionalNonEmptyString(row.group_title, "message.group_title"),
sendEffect: optionalNonEmptyString(row.expressive_send_style_id, "message.expressive_send_style_id"),
appBundleId: optionalNonEmptyString(row.balloon_bundle_id, "message.balloon_bundle_id"),
isInvisibleInkRevealed: flag(row.was_detonated, "message.was_detonated"),
expireStatus: resolveExpireStatus(optionalNumber(row.expire_state, "message.expire_state")),
shareActivity: resolveShareActivity(optionalNumber(row.share_status, "message.share_status")),
shareDirection: resolveShareDirection(optionalNumber(row.share_direction, "message.share_direction")),
scheduleKind: resolveScheduleKind(optionalNumber(row.schedule_type, "message.schedule_type")),
scheduleStatus: resolveScheduleStatus(optionalNumber(row.schedule_state, "message.schedule_state")),
segmentCount: optionalNumber(row.part_count, "message.part_count") ?? 0,
hasAttachments: flag(row.cache_has_attachments, "message.cache_has_attachments"),
reaction,
attachments
};
}
function resolveAttachmentLocalPath(rawFilename) {
const filename = optionalNonEmptyString(rawFilename, "attachment.filename");
if (filename == null) return null;
if (filename.startsWith("~")) {
return filename.replace(/^~/, HOME_DIR);
}
if (!filename.startsWith("/")) {
return join(HOME_DIR, "Library/Messages/Attachments", filename);
}
return filename;
}
function resolveAttachmentFileName(rawTransferName, localPath) {
const transferName = optionalNonEmptyString(rawTransferName, "attachment.transfer_name");
if (transferName != null) return transferName;
if (!localPath) return null;
const name = basename(localPath);
return name === "" ? null : name;
}
function rowToAttachment(row) {
const localPath = resolveAttachmentLocalPath(row.filename);
return {
id: requireNonEmptyString(row.guid, "attachment.guid"),
fileName: resolveAttachmentFileName(row.transfer_name, localPath),
localPath,
mimeType: optionalNonEmptyString(row.mime_type, "attachment.mime_type") ?? "application/octet-stream",
uti: optionalNonEmptyString(row.uti, "attachment.uti"),
sizeBytes: optionalNumber(row.total_bytes, "attachment.total_bytes") ?? 0,
transferStatus: resolveTransferStatus(optionalNumber(row.transfer_state, "attachment.transfer_state")),
isFromMe: flag(row.is_outgoing, "attachment.is_outgoing"),
isSticker: flag(row.is_sticker, "attachment.is_sticker"),
isSensitiveContent: flag(row.is_commsafety_sensitive, "attachment.is_commsafety_sensitive"),
altText: optionalNonEmptyString(row.emoji_image_short_description, "attachment.emoji_image_short_description"),
createdAt: requireDate(row.created_date, "attachment.created_date")
};
}
var require2 = createRequire(import.meta.url);
var cachedCtor;
function loadModule(specifier, extract) {
try {
return extract(require2(specifier));
} catch (error) {
const cause = toError(error);
throw DatabaseError(`Failed to load ${specifier}: ${cause.message}`, cause);
}
}
function resolveCtor() {
if (cachedCtor) return cachedCtor;
cachedCtor = typeof Bun !== "undefined" ? loadModule("bun:sqlite", (m) => m.Database) : loadModule("better-sqlite3", (m) => {
const mod = m;
return typeof mod === "function" ? mod : mod.default;
});
return cachedCtor;
}
var SqliteClient = class {
db;
closed = false;
/**
* @param path SQLite database file path.
* @param readOnly Open the database read-only. Defaults to `true` — writes to
* `chat.db` would corrupt Messages.app state, so only flip this
* when running against a test/fixture database.
*/
constructor(path, readOnly = true) {
const Ctor = resolveCtor();
try {
this.db = new Ctor(path, { readonly: readOnly });
} catch (error) {
const cause = toError(error);
throw DatabaseError(`Failed to open database: ${cause.message}`, cause);
}
}
all(sql, params = []) {
if (this.closed) throw DatabaseError("Database is closed");
try {
return this.db.prepare(sql).all(...params);
} catch (error) {
const cause = toError(error);
throw DatabaseError(`Query failed: ${cause.message}`, cause);
}
}
close() {
if (this.closed) return;
try {
this.db.close();
} catch (error) {
const cause = toError(error);
throw DatabaseError(`Failed to close database: ${cause.message}`, cause);
}
this.closed = true;
}
};
// src/infra/db/reader.ts
var ATTACHMENT_QUERY_CHUNK = 500;
var SEARCH_PAGE_SIZE = 200;
var CHAT_BACKFILL_RETRY_DELAY_MS = 200;
var CHAT_BACKFILL_MAX_RETRIES = 2;
var MessagesDatabaseReader = class extends SqliteClient {
queries;
exec;
constructor(path) {
super(path, true);
this.exec = (sql, params) => this.all(sql, params ?? []);
this.queries = macos26Queries;
}
/** Get the current maximum message ROWID. */
async getMaxRowId() {
return queryMaxRowId(this.exec, this.queries);
}
/** Query messages with optional filters. */
async getMessages(query = {}) {
return queryMessages(this.exec, this.queries, query);
}
/** Query messages newer than the given ROWID, ordered ascending. */
async getMessagesSinceRowId(sinceRowId, query = {}) {
const messages = queryMessages(this.exec, this.queries, {
...query,
sinceRowId,
orderByRowIdAsc: true
});
return backfillMissingChatInfo(this.exec, this.queries, messages);
}
/** List chats with optional filters and sorting. */
async listChats(query = {}) {
return queryChats(this.exec, this.queries, query);
}
};
function queryMessages(exec, queries, input) {
const { search } = input;
if (search) {
return searchMessages(exec, queries, { ...input, search });
}
return executeMessageQuery(exec, queries, queries.buildMessageQuery(input));
}
function executeMessageQuery(exec, queries, sqlQuery, includeAttachments = true) {
let messages;
try {
const rows = exec(sqlQuery.sql, sqlQuery.params);
messages = rows.map((row) => rowToMessage(row, []));
} catch (error) {
throw DatabaseError(`Failed to query messages: ${toErrorMessage(error)}`, error);
}
if (!includeAttachments) {
return messages;
}
return mergeAttachments(exec, queries, messages);
}
function searchMessages(exec, queries, filter) {
const { search: rawSearch, ...sqlFilter } = filter;
const search = rawSearch.toLowerCase();
const requestedOffset = filter.offset ?? 0;
const requestedLimit = filter.limit ?? Number.POSITIVE_INFINITY;
const requiredMatches = requestedOffset + requestedLimit;
const pageSize = Math.max(SEARCH_PAGE_SIZE, filter.limit ?? 0);
const matches = [];
let scanOffset = 0;
while (matches.length < requiredMatches) {
const page = executeMessageQuery(
exec,
queries,
queries.buildMessageQuery({ ...sqlFilter, limit: pageSize, offset: scanOffset }),
false
);
if (page.length === 0) break;
for (const message of page) {
if (message.text?.toLowerCase().includes(search) === true) {
matches.push(message);
}
}
if (page.length < pageSize) break;
scanOffset += pageSize;
}
const end = Number.isFinite(requestedLimit) ? requestedOffset + requestedLimit : void 0;
return mergeAttachments(exec, queries, matches.slice(requestedOffset, end));
}
async function backfillMissingChatInfo(exec, queries, messages) {
const collectMissing = (list) => {
const ids = [];
for (const message of list) {
if (message.chatId == null) ids.push(message.rowId);
}
return ids;
};
let current = messages;
let missing = collectMissing(current);
if (missing.length === 0) return current;
for (let attempt = 0; attempt <= CHAT_BACKFILL_MAX_RETRIES; attempt++) {
if (attempt > 0) {
await delay(CHAT_BACKFILL_RETRY_DELAY_MS);
}
current = runChatBackfillOnce(exec, queries, current, missing);
missing = collectMissing(current);
if (missing.length === 0) break;
}
return current;
}
function runChatBackfillOnce(exec, queries, messages, missingIds) {
const query = queries.buildChatBackfillQuery(missingIds);
const byRowId = /* @__PURE__ */ new Map();
try {
const rows = exec(query.sql, query.params);
for (const row of rows) {
const id = parseNumber(row.message_rowid);
if (id != null) byRowId.set(id, row);
}
} catch (error) {
throw DatabaseError(`Failed to backfill chat info: ${toErrorMessage(error)}`, error);
}
if (byRowId.size === 0) return messages;
return messages.map((message) => {
if (message.chatId != null) return message;
const row = byRowId.get(message.rowId);
return row ? patchMessageChatInfo(message, row) : message;
});
}
function queryChats(exec, queries, input) {
const sqlQuery = queries.buildChatQuery({
...input,
sortBy: input.sortBy ?? "recent"
});
try {
const rows = exec(sqlQuery.sql, sqlQuery.params);
return rows.map((row) => rowToChat(row));
} catch (error) {
throw DatabaseError(`Failed to list chats: ${toErrorMessage(error)}`, error);
}
}
function mergeAttachments(exec, queries, messages) {
if (messages.length === 0) return messages;
const attachmentMap = batchGetAttachments(
exec,
queries,
messages.map((message) => message.rowId)
);
return messages.map((message) => ({
...message,
attachments: attachmentMap.get(message.rowId) ?? []
}));
}
function batchGetAttachments(exec, queries, messageIds) {
const result = /* @__PURE__ */ new Map();
if (messageIds.length === 0) return result;
for (let i = 0; i < messageIds.length; i += ATTACHMENT_QUERY_CHUNK) {
const chunk = messageIds.slice(i, i + ATTACHMENT_QUERY_CHUNK);
const query = queries.buildAttachmentQuery(chunk);
try {
const rows = exec(query.sql, query.params);
for (const row of rows) {
const messageId = requireNumber(row.msg_id, "attachment.msg_id");
const attachment = rowToAttachment(row);
const existing = result.get(messageId);
if (existing) {
existing.push(attachment);
} else {
result.set(messageId, [attachment]);
}
}
} catch (error) {
throw DatabaseError(`Failed to query attachments: ${toErrorMessage(error)}`, error);
}
}
return result;
}
function queryMaxRowId(exec, queries) {
const { sql, params } = queries.buildMaxRowIdQuery();
try {
const rows = exec(sql, params);
return parseNumber(rows[0]?.max_id) ?? 0;
} catch (error) {
throw DatabaseError(`Failed to read max ROWID: ${toErrorMessage(error)}`, error);
}
}
var BATCH_LIMIT = 100;
var MessageWatchSource = class {
database;
databasePath;
walPath;
walFilename;
watchFactory;
onBatch;
onError;
debug;
isRunning = false;
lastRowId = -1;
triggerResolve = null;
hasPendingTrigger = false;
walWatcher = null;
dirWatcher = null;
/**
* Handle to the running consumer loop. `stop()` awaits this to guarantee
* that no `onBatch` (= plugin dispatch) is in flight after stop resolves —
* otherwise plugin `onIncomingMessage` could race with SDK shutdown's
* `onDestroy`, violating the documented lifecycle contract.
*/
consumePromise = null;
constructor(options) {
this.database = options.database;
this.databasePath = options.databasePath;
this.walPath = `${this.databasePath}-wal`;
this.walFilename = `${basename(this.databasePath)}-wal`;
this.watchFactory = options.watchFactory ?? ((path, listener) => watch(path, listener));
this.onBatch = options.onBatch;
this.onError = options.onError;
this.debug = options.debug ?? false;
}
// -----------------------------------------------
// Lifecycle
// -----------------------------------------------
/** Start watching for new messages. */
async start() {
if (this.isRunning) return;
this.lastRowId = await this.database.getMaxRowId();
this.isRunning = true;
try {
this.ensureWatching();
this.trigger();
this.consumePromise = this.consumeLoop();
} catch (error) {
this.isRunning = false;
this.detachWALWatcher();
this.detachDirWatcher();
throw error;
}
}
/**
* Stop watching and release all resources.
*
* Resolves only after the consumer loop has actually exited — any
* `onBatch` in flight runs to completion first. This is the property
* the SDK's `close()` relies on to avoid dispatching to plugins after
* their `onDestroy` has already fired.
*/
async stop() {
if (!this.isRunning && !this.consumePromise) return;
this.isRunning = false;
this.detachWALWatcher();
this.detachDirWatcher();
if (this.triggerResolve) {
this.triggerResolve();
this.triggerResolve = null;
}
this.hasPendingTrigger = false;
const pending = this.consumePromise;
this.consumePromise = null;
if (pending) await pending;
}
// -----------------------------------------------
// Single-slot semaphore
// -----------------------------------------------
trigger() {
if (this.triggerResolve) {
this.triggerResolve();
this.triggerResolve = null;
return;
}
this.hasPendingTrigger = true;
}
waitForTrigger() {
if (this.hasPendingTrigger) {
this.hasPendingTrigger = false;
return Promise.resolve();
}
return new Promise((resolve2) => {
this.triggerResolve = resolve2;
});
}
// -----------------------------------------------
// Consumer loop
// -----------------------------------------------
async consumeLoop() {
while (this.isRunning) {
await this.waitForTrigger();
if (!this.isRunning) break;
try {
while (await this.processBatch()) {
if (!this.isRunning) break;
}
} catch (error) {
this.handleError(error);
}
}
}
async processBatch() {
const messages = await this.database.getMessagesSinceRowId(this.lastRowId, { limit: BATCH_LIMIT });
if (messages.length > 0) {
if (!this.isRunning) return false;
await this.onBatch?.(messages);
const last = messages[messages.length - 1];
if (last) this.lastRowId = last.rowId;
}
return messages.length === BATCH_LIMIT;
}
// -----------------------------------------------
// WAL / directory watcher state machine
// -----------------------------------------------
ensureWatching() {
this.attachWALWatcher();
if (this.walWatcher) return;
try {
this.attachDirWatcher();
} catch (error) {
const cause = toError(error);
throw new Error(`Failed to start watcher: WAL missing and directory watch failed \u2014 ${cause.message}`, {
cause
});
}
}
attachWALWatcher() {
if (this.walWatcher) return;
try {
const watcher = this.watchFactory(this.walPath, (eventType) => {
if (eventType === "change") {
this.trigger();
} else if (eventType === "rename") {
this.detachWALWatcher();
this.recoverOrStop("WAL file rotated");
}
});
watcher.on("error", () => {
this.detachWALWatcher();
this.recoverOrStop("WAL watcher failed");
});
this.walWatcher = watcher;
this.detachDirWatcher();
} catch (error) {
if (!isMissingFileError(error)) throw error;
if (this.debug) {
console.warn("[WatchSource] WAL missing, falling back to dir watch");
}
}
}
detachWALWatcher() {
if (!this.walWatcher) return;
this.walWatcher.close();
this.walWatcher = null;
}
attachDirWatcher() {
if (this.dirWatcher) return;
const dir = dirname(this.databasePath);
const watcher = this.watchFactory(dir, (_eventType, filename) => {
const name = typeof filename === "string" ? filename : Buffer.isBuffer(filename) ? filename.toString("utf8") : null;
if (name !== this.walFilename) return;
try {
this.attachWALWatcher();
this.trigger();
} catch (error) {
this.handleError(error);
}
});
watcher.on("error", () => {
this.detachDirWatcher();
this.recoverOrStop("Directory watcher failed");
});
this.dirWatcher = watcher;
}
detachDirWatcher() {
if (!this.dirWatcher) return;
this.dirWatcher.close();
this.dirWatcher = null;
}
// -----------------------------------------------
// Error handling
// -----------------------------------------------
recoverOrStop(context) {
try {
this.ensureWatching();
} catch (error) {
void this.stop();
this.handleError(new Error(`${context}: ${toError(error).message}`));
}
}
handleError(error) {
const err = toError(error);
if (this.debug) {
console.error("[WatchSource] Error:", err);
}
try {
this.onError?.(err);
} catch (callbackError) {
if (this.debug) {
console.error("[WatchSource] Error handler failed:", toError(callbackError));
}
}
}
};
function isMissingFileError(error) {
return typeof error === "object" && error !== null && error.code === "ENOENT";
}
// src/domain/routing.ts
function resolveTarget(input) {
const chatId = ChatId.fromUserInput(input);
chatId.validate();
if (chatId.isGroup) {
return { kind: "group", chatId };
}
return { kind: "dm", recipient: chatId.extractRecipient() ?? chatId.raw };
}
// src/domain/validate.ts
function isURL(value) {
return value.startsWith("http://") || value.startsWith("https://");
}
function validateMessageContent(text, attachments) {
const hasText = text != null && text !== "";
const hasAttachments = attachments != null && attachments.length > 0;
if (!hasText && !hasAttachments) {
throw SendError("Message must have text or at least one attachment");
}
}
function requireMacOS() {
if (process.platform !== "darwin") {
throw PlatformError("Only macOS is supported");
}
}
function getDefaultDatabasePath() {
let home;
try {
home = homedir();
} catch (cause) {
throw PlatformError("Unable to resolve user home directory", toError(cause));
}
return join(home, "Library", "Messages", "chat.db");
}
function getDarwinMajorVersion(osRelease = release()) {
const value = Number.parseInt(osRelease.split(".")[0] ?? "", 10);
return Number.isFinite(value) ? value : 0;
}
function detectChatServicePrefix(darwinMajor = getDarwinMajorVersion()) {
return darwinMajor >= 25 ? "any" : "iMessage";
}
// src/domain/messages-app.ts
var MESSAGES_APP_SANDBOX_SAFE_DIRS = ["Pictures", "Downloads", "Documents"];
var MESSAGES_APP_TEMP_FILE_PREFIX = "imsg_temp_";
var MESSAGES_APP_TEMP_WRITE_DIR = "Pictures";
// src/infra/outgoing/applescript-builder.ts
var SANDBOX_SAFE_DIRS_ABS = MESSAGES_APP_SANDBOX_SAFE_DIRS.map((dir) => join(homedir(), dir));
var TEMP_WRITE_DIR_ABS = join(homedir(), MESSAGES_APP_TEMP_WRITE_DIR);
function escapeAppleScriptString(str) {
const escapeMap = {
"\\": "\\\\",
'"': '\\"',
"\n": "\\n",
"\r": "\\r",
" ": "\\t"
};
return str.replace(/\0/g, "").replace(/[\\\n\r\t"]/g, (char) => escapeMap[char] || char);
}
function inspectAttachment(localPath) {
const stats = statSync(localPath);
if (!stats.isFile()) {
throw new Error(`Attachment is not a regular file: ${localPath}`);
}
const needsBypass = !SANDBOX_SAFE_DIRS_ABS.some((dir) => localPath.startsWith(`${dir}/`) || localPath === dir);
return { localPath, needsBypass };
}
function buildSendScript(params) {
const { method, identifier, text, attachment } = params;
const escapedId = escapeAppleScriptString(identifier);
const targetSetup = method === "buddy" ? ` set targetService to 1st service whose service type = iMessage
set targetBuddy to buddy "${escapedId}" of targetService` : ` set targetChat to chat id "${escapedId}"`;
const targetVar = method === "buddy" ? "targetBuddy" : "targetChat";
const bodyLines = [];
if (text) {
const escapedText = escapeAppleScriptString(text);
bodyLines.push(` send "${escapedText}" to ${targetVar}`);
}
if (attachment) {
bodyLines.push(buildAttachmentSnippet(attachment, targetVar));
}
const body = bodyLines.join("\n\n");
return `tell application "Messages"
${targetSetup}
${body}
end tell`;
}
function buildAttachmentSnippet(attachment, targetVar) {
return attachment.needsBypass ? buildSandboxBypassSnippet(attachment, targetVar) : buildDirectSendSnippet(attachment, targetVar);
}
function buildSandboxBypassSnippet(attachment, targetVar) {
const { localPath } = attachment;
const escapedFilePath = escapeAppleScriptString(localPath);
const escapedTempDir = escapeAppleScriptString(TEMP_WRITE_DIR_ABS);
const escapedBasename = escapeAppleScriptString(basename(localPath));
return ` set tmpDir to do shell script "mktemp -d " & quoted form of "${escapedTempDir}/${MESSAGES_APP_TEMP_FILE_PREFIX}XXXXXXXXXX"
set targetPath to tmpDir & "/${escapedBasename}"
do shell script "cat " & quoted form of "${escapedFilePath}" & " > " & quoted form of targetPath & " && chmod 600 " & quoted form of targetPath & " || { rm -rf " & quoted form of tmpDir & "; exit 1; }"
set theFile to (POSIX file targetPath) as alias
send theFile to ${targetVar}`;
}
function buildDirectSendSnippet(attachment, targetVar) {
const escapedPath = escapeAppleScriptString(attachment.localPath);
return ` send POSIX file "${escapedPath}" to ${targetVar}`;
}
var execFileAsync = promisify(execFile);
var DEFAULT_TIMEOUT_MS = 3e4;
var PROBE_TIMEOUT_MS = 2e3;
async function execAppleScript(script, options) {
const debug = options?.debug ?? false;
const timeoutMs = options?.timeout ?? DEFAULT_TIMEOUT_MS;
if (debug) {
console.log("[AppleScript] Executing script:\n", script);
}
try {
const { stdout, stderr } = await runViaStdin(script, timeoutMs, options?.signal);
if (stderr && debug) {
console.warn("[AppleScript] Warning:", stderr);
}
if (debug) {
console.log("[AppleScript] Success:", stdout || "(no output)");
}
return stdout.trim();
} catch (error) {
const err = error instanceof Error ? error : new Error(String(error));
const msg = err.message;
if (options?.signal?.aborted) {
throw new Error("AppleScript execution aborted", { cause: err });
}
if ("killed" in err && err.killed) {
throw new Error(`AppleScript execution timeout (${timeoutMs}ms) - may be slow network or large file`, {
cause: err
});
}
if (msg.includes("Can't get buddy")) {
throw new Error("Recipient not found or not added to iMessage contacts", { cause: err });
}
if (msg.includes("Can't send")) {
throw new Error(
"Send failed - please check: 1) Is Messages signed in to iMessage, 2) Is recipient correct, 3) Network connection",
{ cause: err }
);
}
if (debug) {
console.error("[AppleScript] Error details:", err);
}
throw new Error(`AppleScript execution failed: ${msg}`, { cause: err });
}
}
function runViaStdin(script, timeoutMs, signal) {
return new Promise((resolve2, reject) => {
if (signal?.aborted) {
reject(new Error("AppleScript execution aborted"));
return;
}
const child = spawn("osascript", ["-"], {
stdio: ["pipe", "pipe", "pipe"],
timeout: timeoutMs
});
let stdout = "";
let stderr = "";
let killed = false;
const onAbort = () => {
killed = true;
child.kill("SIGTERM");
};
signal?.addEventListener("abort", onAbort, { once: true });
child.stdout?.on("data", (data) => {
stdout += data.toString();
});
child.stderr?.on("data", (data) => {
stderr += data.toString();
});
child.stdin?.on("error", () => {
});
child.on("error", (err) => {
signal?.removeEventListener("abort", onAbort);
reject(err);
});
child.on("close", (code, sig) => {
signal?.removeEventListener("abort", onAbort);
if (sig === "SIGTERM") killed = true;
if (code === 0) {
resolve2({ stdout, stderr });
} else {
const err = new Error(stderr || `osascript exited with code ${code}`);
err.killed = killed;
reject(err);
}
});
child.stdin?.write(script);
child.stdin?.end();
});
}
var MessagesAppProbe = class _MessagesAppProbe {
static CACHE_TTL_MS = 2e3;
cache = null;
async isRunning() {
const now = Date.now();
if (this.cache && this.cache.expires > now) return this.cache.value;
let value;
try {
await execFileAsync("pgrep", ["-x", "Messages"], { timeout: PROBE_TIMEOUT_MS });
value = true;
} catch {
value = false;
}
this.cache = { value, expires: now + _MessagesAppProbe.CACHE_TTL_MS };
return value;
}
};
// src/infra/outgoing/sender.ts
var SEND_TIMEOUT_MS = 3e4;
var RETRY_ATTEMPTS = 3;
var RETRY_DELAY_MS = 1500;
var INTER_ATTACHMENT_DELAY_MS = 500;
var MessageSender = class {
debug;
retryAttempts;
retryDelay;
sendTimeoutMs;
chatServicePrefix;
semaphore;
signal;
messagesApp = new MessagesAppProbe();
constructor({
debug = false,
retryAttempts = RETRY_ATTEMPTS,
retryDelay = RETRY_DELAY_MS,
timeout = SEND_TIMEOUT_MS,
semaphore,
signal
} = {}) {
this.debug = debug;
this.retryAttempts = retryAttempts;
this.retryDelay = retryDelay;
this.sendTimeoutMs = timeout;
this.semaphore = semaphore;
this.signal = signal;
this.chatServicePrefix = detectChatServicePrefix();
}
/** Implements `SendPort.send`. */
async send(request) {
const job = this.createSendJob(request);
const task = () => this.runPipeline(job);
try {
return await (this.semaphore ? this.semaphore.run(task, this.signal) : task());
} catch (error) {
if (error instanceof IMessageError) throw error;
throw SendError("Send cancelled", error instanceof Error ? error : void 0);
}
}
// -----------------------------------------------
// Pipeline
// -----------------------------------------------
async runPipeline(job) {
this.assertNotAborted();
try {
validateMessageContent(job.text, job.attachments);
await this.assertMessagesAppRunning();
const attachments = job.attachments.map((a) => this.resolveAttachment(a));
await this.dispatch(job.target, job.text, attachments);
} catch (error) {
if (error instanceof IMessageError) throw error;
throw SendError(`Send failed: ${toErrorMessage(error)}`, error instanceof Error ? error : void 0);
}
}
createSendJob(request) {
const { to, text, attachments = [] } = request;
const resolved = resolveTarget(to);
if (resolved.kind === "group") {
const identifier = resolved.chatId.buildGroupGuid(this.chatServicePrefix);
return { target: { method: "chat", identifier }, text, attachments };
}
return { target: { method: "buddy", identifier: resolved.recipient }, text, attachments };
}
async dispatch(target, text, attachments) {
const { method, identifier } = target;
const prefix = method === "chat" ? `group ${identifier}` : identifier;
const total = attachments.length;
const hasText = text != null && text !== "";
const firstLabel = total === 0 ? "text" : hasText ? `text + attachment 1/${total}` : `attachment 1/${total}`;
const firstScript = buildSendScript({
method,
identifier,
text: hasText ? text : void 0,
attachment: attachments[0]
});
await this.executeWithRetry(firstScript, `Send ${firstLabel} to ${prefix}`);
for (let i = 1; i < total; i++) {
await delay(INTER_ATTACHMENT_DELAY_MS, this.signal);
const script = buildSendScript({ method, identifier, attachment: attachments[i] });
await this.executeWithRetry(script, `Send attachment ${i + 1}/${total} to ${prefix}`);
}
}
// -----------------------------------------------
// Helpers
// -----------------------------------------------
async executeWithRetry(script, description) {
try {
await retry(
() => execAppleScript(script, { debug: this.debug, timeout: this.sendTimeoutMs, signal: this.signal }),
{
attempts: this.retryAttempts,
delay: this.retryDelay,
signal: this.signal
}
);
} catch (error) {
throw SendError(
`${description} failed after ${this.retryAttempts} attempts: ${toErrorMessage(error)}`,
error instanceof Error ? error : void 0
);
}
}
resolveAttachment(path) {
if (isURL(path)) {
throw SendError(
`URLs are not supported as attachments. Download the file yourself and pass a local path instead: ${path.slice(0, 120)}`
);
}
const localPath = resolve(path);
try {
return inspectAttachment(localPath);
} catch (error) {
const cause = error instanceof Error ? error : new Error(String(error));
throw SendError(`Attachment unreadable: ${basename(path) || "unknown"}: ${cause.message}`, cause);
}
}
assertNotAborted() {
if (this.signal?.aborted) throw SendError("Send cancelled");
}
async assertMessagesAppRunning() {
if (!await this.messagesApp.isRunning()) {
throw SendError("Messages app is not running");
}
}
};
var TEMP_DIR = join(homedir(), MESSAGES_APP_TEMP_WRITE_DIR);
var DEFAULTS = {
maxAge: 10 * 60 * 1e3,
cleanupInterval: 5 * 60 * 1e3
};
var TempFileManager = class {
config;
cleanupTimer = null;
destroyPromise = null;
constructor(config = {}) {
this.config = {
maxAge: config.maxAge ?? DEFAULTS.maxAge,
cleanupInterval: config.cleanupInterval ?? DEFAULTS.cleanupInterval,
debug: config.debug ?? false
};
}
// -----------------------------------------------
// Lifecycle
// -----------------------------------------------
/** Start the periodic cleanup timer. */
start() {
if (this.destroyPromise) {
throw ConfigError("TempFileManager is destroyed or destroying, cannot start");
}
if (this.cleanupTimer) return;
this.removeExpiredFiles();
this.cleanupTimer = setInterval(() => {
if (this.destroyPromise) return;
this.removeExpiredFiles();
}, this.config.cleanupInterval);
this.cleanupTimer.unref();
if (this.config.debug) {
const intervalSec = this.config.cleanupInterval / 1e3;
const maxAgeSec = this.config.maxAge / 1e3;
console.log(`[TempFileManager] Started, interval: ${intervalSec}s, maxAge: ${maxAgeSec}s`);
}
}
/** Stop the timer and remove expired files. */
async destroy() {
if (this.destroyPromise) return this.destroyPromise;
this.destroyPromise = this.doDestroy();
return this.destroyPromise;
}
// -----------------------------------------------
// Internal
// -----------------------------------------------
async doDestroy() {
if (this.cleanupTimer) {
clearInterval(this.cleanupTimer);
this.cleanupTimer = null;
}
this.removeExpiredFiles();
if (this.config.debug) {
console.log("[TempFileManager] Destroyed");
}
}
removeExpiredFiles() {
const now = Date.now();
try {
if (!existsSync(TEMP_DIR)) return;
const entries = readdirSync(TEMP_DIR);
for (const entry of entries) {
if (!entry.startsWith(MESSAGES_APP_TEMP_FILE_PREFIX)) continue;
const entryPath = join(TEMP_DIR, entry);
try {
const stats = lstatSync(entryPath);
const age = now - stats.mtimeMs;
if (age <= this.config.maxAge) continue;
rmSync(entryPath, { recursive: true, force: true });
if (this.config.debug) {
console.log(`[TempFileManager] Removed: ${entry}`);
}
} catch (error) {
if (this.config.debug) {
console.error(`[TempFileManager] Failed to remove: ${entry}`, error);
}
}
}
} catch (error) {
if (this.config.debug) {
console.error("[TempFileManager] Cleanup process error:", error);
}
}
}
};
// src/infra/plugin.ts
var SEQUENTIAL_HOOKS = /* @__PURE__ */ new Set(["onInit", "onError", "onDestroy"]);
var PluginManager = class {
plugins = [];
/**
* Plugins whose `onInit` is still running. They are deliberately excluded
* from hook dispatch until init completes — otherwise a plugin could
* receive `onIncomingMessage` / `onBeforeSend` before its `onInit` had a chance
* to run, violating the documented lifecycle contract.
*/
pendingPlugins = [];
pendingInits = [];
destroying = false;
destroyPromise = null;
/** Shared promise for concurrent `init()` callers; `_initialized` is an observation flag, not a gate. */
initPromise = null;
_initialized = false;
get initialized() {
return this._initialized;
}
// -----------------------------------------------
// Registration
// -----------------------------------------------
/** Register a plugin. Deduplicates by name; late registrations auto-init. */
use(plugin) {
if (this.destroying) {
throw ConfigError("PluginManager is destroying, cannot register new plugins");
}
const isDuplicate = this.plugins.some((current) => current.name === plugin.name) || this.pendingPlugins.some((current) => current.name === plugin.name);
if (isDuplicate) {
throw ConfigError(`Plugin "${plugin.name}" is already registered`);
}
if (this.initPromise && plugin.onInit) {
this.pendingPlugins.push(plugin);
const initPromise = (async () => {
let initError = null;
try {
await plugin.onInit?.();
} catch (error) {
initError = error;
}
const idx = this.pendingPlugins.indexOf(plugin);
if (idx !== -1) this.pendingPlugins.splice(idx, 1);
this.plugins.push(plugin);
if (initError !== null) {
await this.reportHookError(plugin.name, "onInit", initError);
}
})();
this.pendingInits.push(initPromise);
} else {
this.plugins.push(plugin);
}
return this;
}
// -----------------------------------------------
// Lifecycle
// -----------------------------------------------
/** Initialize all registered plugins. Idempotent — subsequent calls flush late registrations. */
async init() {
if (this.initPromise) {
await this.initPromise;
await this.flushPendingInits();
return;
}
this.initPromise = this.callHook("onInit").then(() => {
this._initialized = true;
});
await this.initPromise;
await this.flushPendingInits();
}
/**
* Destroy all plugins and reset state. Concurrent callers await the
* same in-flight destroy; sequential callers can re-register and
* destroy again.
*/
async destroy() {
if (this.destroyPromise) return this.destroyPromise;
this.destroyPromise = (async () => {
this.destroying = true;
try {
await this.flushPendingInits();
await this.callHook("onDestroy");
this.plugins = [];
this.pendingPlugins = [];
this._initialized = false;
this.initPromise = null;
} finally {
this.destroying = false;
this.destroyPromise = null;
}
})();
return this.destroyPromise;
}
// -----------------------------------------------
// Hook Dispatch
// -----------------------------------------------
/**
* Dispatch a hook to all plugins that implement it.
*
* Collects errors without interrupting the dispatch — each plugin runs
* regardless of its peers' failures. Use `callInterruptingHook` for
* hooks whose failure must abort the surrounding operation (e.g.
* `onBeforeSend` acting as an authorisation gate).
*/
async callHook(hookName, ...args) {
const pluginsWithHook = this.sortedPluginsWithHook(hookName);
if (pluginsWithHook.length === 0) return [];
const errors = SEQUENTIAL_HOOKS.has(hookName) ? await this.dispatchSequential(pluginsWithHook, hookName, args) : await this.dispatchParallel(pluginsWithHook, hookName, args);
if (errors.length > 0 && hookName !== "onError") {
for (const { plugin, error } of errors) {
await this.reportHookError(plugin, hookName, error);
}
}
return errors;
}
/**
* Fail-fast dispatch for interception-style hooks (`onBefore*`). The
* first plugin that throws aborts dispatch; remaining plugins are NOT
* invoked, and the throw is re-raised as `IMessageError(code, ...)`
* with the original error as `cause`. Designed so a single plugin can
* gate auth / rate-limit / policy by throwing.
*
* Deliberately does NOT route the rejection through `onError`: a gate
* plugin rejecting a send is intended behaviour, not an unexpected
* error, and logging every rejection as a plugin failure is noise.
*/
async callInterruptingHook(hookName, code, ...args) {
const plugins = this.sortedPluginsWithHook(hookName);
if (plugins.length === 0) return;
for (const plugin of plugins) {
try {
const hookFn = plugin[hookName];
await Promise.resolve(hookFn(...args));
} catch (error) {
const cause = toError(error);
throw new IMessageError(
code,
`Plugin "${plugin.name}" ${String(hookName)} rejected: ${cause.message}`,
{ cause }
);
}
}
}
// -----------------------------------------------
// Dispatch Strategies
// -----------------------------------------------
async dispatchSequential(plugins, hookName, args) {
const errors = [];
for (const plugin of plugins) {
try {
const hookFn = plugin[hookName];
await Promise.resolve(hookFn(...args));
} catch (error) {
errors.push({ plugin: plugin.name, error: toError(error) });
}
}
return errors;
}
async dispatchParallel(plugins, hookName, args) {
const outcomes = await Promise.all(
plugins.map(async (plugin) => {
try {
const hookFn = plugin[hookName];
await Promise.resolve(hookFn(...args));
return { plugin: plugin.name, error: null };
} catch (error) {
return { plugin: plugin.name, error: toError(error) };
}
})
);
const errors = [];
for (const outcome of outcomes) {
if (outcome.error !== null) {
errors.push({ plugin: outcome.plugin, error: outcome.error });
}
}
return errors;
}
// -----------------------------------------------
// Ordering
// -----------------------------------------------
sortedPluginsWithHook(hookName) {
const withHook = this.plugins.filter((p) => p[hookName]);
if (withHook.length <= 1) return withHook;
const pre = [];
const normal = [];
const post = [];
for (const plugin of withHook) {
if (plugin.order === "pre") pre.push(plugin);
else if (plugin.order === "post") post.push(plugin);
else normal.push(plugin);
}
return [...pre, ...normal, ...post];
}
// -----------------------------------------------
// Internal Helpers
// -----------------------------------------------
async flushPendingInits() {
while (this.pendingInits.length > 0) {
const toFlush = this.pendingInits;
this.pendingInits = [];
await Promise.all(toFlush);
}
}
async reportHookError(plugin, hookName, error) {
const normalizedError = toError(error);
console.error(`[Plugin ${plugin}] ${hookName} failed:`, normalizedError);
try {
await this.callHook("onError", {
error: normalizedError,
context: `Plugin ${plugin} - ${String(hookName)}`
});
} catch (hookError) {
console.error(
`[Plugin ${plugin}] onError hook failed (suppressed to prevent recursion):`,
toError(hookError)
);
}
}
};
var definePlugin = (plugin) => plugin;
function createPluginMessageSink(manager) {
return {
async onIncomingMessage(message) {
await manager.callHook("onIncomingMessage", { message });
},
async onFromMe(message) {
await manager.callHook("onFromMe", { message });
},
onError(error, context) {
const ctx = { error, context };
void manager.callHook("onError", ctx);
}
};
}
// src/sdk-bounds.ts
var BOUNDS = {
maxConcurrentSends: { default: 10, min: 1, max: 50 },
sendTimeout: { default: 3e4, min: 1e3, max: 3e5 }
};
// src/sdk.ts
var ERROR_SDK_DESTROYED = "SDK is destroyed";
var ERROR_WATCHER_RUNNING = "Watcher is already running";
var IMessageSDK = class {
databasePath;
debug;
database;
tempFiles;
sender;
plugins;
abortController = new AbortController();
watchSource = null;
destroyed = false;
closePromise = null;
constructor(config = {}) {
requireMacOS();
this.databasePath = config.databasePath ?? getDefaultDatabasePath();
this.debug = config.debug ?? false;
const maxConcurrentSends = validateBound(
config.maxConcurrentSends,
BOUNDS.maxConcurrentSends,
"maxConcurrentSends"
);
const sendTimeout = validateBound(config.sendTimeout, BOUNDS.sendTimeout, "sendTimeout");
this.database = new MessagesDatabaseReader(this.databasePath);
this.plugins = new PluginManager();
const semaphore = new Semaphore(maxConcurrentSends);
this.sender = new MessageSender({
semaphore,
debug: this.debug,
timeout: sendTimeout,
signal: this.abortController.signal
});
this.tempFiles = new TempFileManager({ debug: this.debug });
this.tempFiles.start();
if (config.plugins) {
for (const plugin of config.plugins) {
this.plugins.use(plugin);
}
}
if (this.debug) {
const pluginCount = config.plugins?.length ?? 0;
console.log(
`[SDK] Initialized: db=${this.databasePath} plugins=${pluginCount} maxConcurrentSends=${maxConcurrentSends} sendTimeout=${sendTimeout}ms`
);
}
}
// -----------------------------------------------
// Plugin Management
// -----------------------------------------------
/** Register a plugin. Late registrations are auto-initialized. */
use(plugin) {
this.assertNotDestroyed();
this.plugins.use(plugin);
return this;
}
// -----------------------------------------------
// Message Queries
// -----------------------------------------------
/** Query messages with optional filters. */
async getMessages(query = {}) {
this.assertNotDestroyed();
await this.plugins.init();
await this.plugins.callInterruptingHook("onBeforeMessageQuery", "DATABASE", { query });
const messages = await this.database.getMessages(query);
await this.plugins.callHook("onAfterMessageQuery", { query, messages });
return messages;
}
/** List chats with optional filters and sorting. */
async listChats(query = {}) {
this.assertNotDestroyed();
await this.plugins.init();
await this.plugins.callInterruptingHook("onBeforeChatQuery", "DATABASE", { query });
const chats = await this.database.listChats(query);
await this.plugins.callHook("onAfterChatQuery", { query, chats });
return chats;
}
// -----------------------------------------------
// Message Sending
// -----------------------------------------------
/**
* Resolves when Messages.app accepts the AppleScript dispatch — acceptance,
* not delivery. For the chat.db row or later `isDelivered` transitions
* observe the watcher (`onFromMeMessage` callback on `startWatching`, or
* plugin hook `onFromMe`); for "accepted" only, `onAfterSend` is lighter.
*
* The first `onBeforeSend` to throw aborts dispatch with `IMessageError`
* (code `SEND`, thrown error as `cause`); `onAfterSend` does not fire.
* Also throws `IMessageError` on validation, AppleScript dispatch, or
* shutdown cancellation.
*/
async send(request) {
this.assertNotDestroyed();
await this.plugins.init();
await this.plugins.callInterruptingHook("onBeforeSend", "SEND", { request });
await this.sender.send(request);
await this.plugins.callHook("onAfterSend", { request });
}
// -----------------------------------------------
// Watcher
// -----------------------------------------------
/**
* Start watching for new messages in real time.
*
* Independent of `sdk.send()` — sends do not require a watcher.
* A running watcher gives you:
* - `onIncomingMessage` / `onDirectMessage` / `onGroupMessage` for peers' messages
* - `onFromMeMessage` for your own sends (including reads of
* `isDelivered`, edits, retractions as they land in chat.db)
*
* Throws `IMessageError` (code `CONFIG`) if a watcher is already
* running on this SDK instance — stop the existing one first.
*/
async startWatching(events = {}) {
this.assertNotDestroyed();
if (this.watchSource) throw ConfigError(ERROR_WATCHER_RUNNING);
const dispatcher = new MessageDispatcher({
events,
sink: createPluginMessageSink(this.plugins),
debug: this.debug
});
const watcher = new MessageWatchSource({
database: this.database,
databasePath: this.databasePath,
onBatch: (messages) => dispatcher.dispatch(messages),
onError: (error) => dispatcher.handleError(error, "watch-source"),
debug: this.debug
});
this.watchSource = watcher;
try {
await this.plugins.init();
await watcher.start();
} catch (error) {
if (this.watchSource === watcher) {
this.watchSource = null;
}
throw error;
}
}
/**
* Stop watching for new messages.
*
* Resolves only after any in-flight batch dispatch has finished, so
* callers chaining `await sdk.stopWatching()` observe a truly quiet SDK.
*/
async stopWatching() {
await this.teardownWatcher();
}
// -----------------------------------------------
// Lifecycle
// -----------------------------------------------
/** Gracefully shut down the SDK and release all resources. */
async close() {
if (this.closePromise) return this.closePromise;
this.closePromise = this.doClose();
return this.closePromise;
}
async doClose() {
this.destroyed = true;
const errors = [];
this.abortController.abort(new Error("SDK closed"));
await safeRun(errors, "watcher", () => this.teardownWatcher());
await safeRun(errors, "pluginManager", () => this.plugins.destroy());
await safeRun(errors, "tempFileManager", () => this.tempFiles.destroy());
await safeRun(errors, "database", () => this.database.close());
if (errors.length > 0) {
if (this.debug) {
const summary = errors.map((e) => `${e.component}: ${e.error.message}`).join("; ");
console.error(`[SDK] Shutdown failed \u2014 ${summary}`);
}
throw new AggregateError(
errors.map((e) => e.error),
`SDK shutdown failed: ${errors.map((e) => e.component).join(", ")}`
);
}
}
async [Symbol.asyncDispose]() {
await this.close();
}
// -----------------------------------------------
// Internal
// -----------------------------------------------
assertNotDestroyed() {
if (this.destroyed) throw ConfigError(ERROR_SDK_DESTROYED);
}
/**
* Single path for tearing down the watcher.
*
* Awaits `watchSource.stop()` so that any in-flight `onBatch` dispatch
* has completed before we return to the caller — this is what
* prevents plugin `onIncomingMessage` from racing with `onDestroy` during
* SDK shutdown.
*/
async teardownWatcher() {
const watcher = this.watchSource;
this.watchSource = null;
if (watcher) await watcher.stop();
}
};
function validateBound(value, bound, name) {
const resolved = value ?? bound.default;
if (resolved < bound.min || resolved > bound.max) {
throw ConfigError(`${name} must be between ${bound.min} and ${bound.max}, got ${resolved}`);
}
return resolved;
}
async function safeRun(errors, component, fn) {
try {
await fn();
} catch (error) {
errors.push({ component, error: toError(error) });
}
}
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set(["jpg", "jpeg", "png", "gif", "heic", "heif", "webp", "bmp", "tiff", "svg"]);
var VIDEO_EXTENSIONS = /* @__PURE__ */ new Set(["mp4", "mov", "avi", "mkv", "m4v", "wmv", "flv", "webm"]);
var AUDIO_EXTENSIONS = /* @__PURE__ */ new Set(["mp3", "m4a", "wav", "aac", "flac", "ogg", "wma"]);
async function attachmentExists(attachment) {
if (!attachment.localPath) return false;
try {
await access(attachment.localPath);
return true;
} catch {
return false;
}
}
function getAttachmentExtension(attachment) {
const ext = extname(attachment.fileName ?? attachment.localPath ?? "");
return ext ? ext.slice(1).toLowerCase() : "";
}
function isImageAttachment(attachment) {
return IMAGE_EXTENSIONS.has(getAttachmentExtension(attachment));
}
function isVideoAttachment(attachment) {
return VIDEO_EXTENSIONS.has(getAttachmentExtension(attachment));
}
function isAudioAttachment(attachment) {
return AUDIO_EXTENSIONS.has(getAttachmentExtension(attachment));
}
export { BOUNDS, ChatId, ConfigError, DatabaseError, IMessageError, IMessageSDK, PlatformError, SendError, attachmentExists, definePlugin, getAttachmentExtension, getDefaultDatabasePath, isAudioAttachment, isImageAttachment, isVideoAttachment, requireMacOS, resolveTarget };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map
Shown as plain text from the published tarball, after apm checked it against the version's checksum. Nothing in it runs on this page.