( recipientName: string, message: Omit<TeammateMessage, 'read'>, teamName?: string, )
| 132 | * @param teamName - Optional team name |
| 133 | */ |
| 134 | export async function writeToMailbox( |
| 135 | recipientName: string, |
| 136 | message: Omit<TeammateMessage, 'read'>, |
| 137 | teamName?: string, |
| 138 | ): Promise<void> { |
| 139 | await ensureInboxDir(teamName) |
| 140 | |
| 141 | const inboxPath = getInboxPath(recipientName, teamName) |
| 142 | const lockFilePath = `${inboxPath}.lock` |
| 143 | |
| 144 | logForDebugging( |
| 145 | `[TeammateMailbox] writeToMailbox: recipient=${recipientName}, from=${message.from}, path=${inboxPath}`, |
| 146 | ) |
| 147 | |
| 148 | // Ensure the inbox file exists before locking (proper-lockfile requires the file to exist) |
| 149 | try { |
| 150 | await writeFile(inboxPath, '[]', { encoding: 'utf-8', flag: 'wx' }) |
| 151 | logForDebugging(`[TeammateMailbox] writeToMailbox: created new inbox file`) |
| 152 | } catch (error) { |
| 153 | const code = getErrnoCode(error) |
| 154 | if (code !== 'EEXIST') { |
| 155 | logForDebugging( |
| 156 | `[TeammateMailbox] writeToMailbox: failed to create inbox file: ${error}`, |
| 157 | ) |
| 158 | logError(error) |
| 159 | return |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | let release: (() => Promise<void>) | undefined |
| 164 | try { |
| 165 | release = await lockfile.lock(inboxPath, { |
| 166 | lockfilePath: lockFilePath, |
| 167 | ...LOCK_OPTIONS, |
| 168 | }) |
| 169 | |
| 170 | // Re-read messages after acquiring lock to get the latest state |
| 171 | const messages = await readMailbox(recipientName, teamName) |
| 172 | |
| 173 | const newMessage: TeammateMessage = { |
| 174 | ...message, |
| 175 | read: false, |
| 176 | } |
| 177 | |
| 178 | messages.push(newMessage) |
| 179 | |
| 180 | await writeFile(inboxPath, jsonStringify(messages, null, 2), 'utf-8') |
| 181 | logForDebugging( |
| 182 | `[TeammateMailbox] Wrote message to ${recipientName}'s inbox from ${message.from}`, |
| 183 | ) |
| 184 | } catch (error) { |
| 185 | logForDebugging(`Failed to write to inbox for ${recipientName}: ${error}`) |
| 186 | logError(error) |
| 187 | } finally { |
| 188 | if (release) { |
| 189 | await release() |
| 190 | } |
| 191 | } |
no test coverage detected