patch-spectrum-mixed-attachments.mjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. #!/usr/bin/env node
  2. // Patch spectrum-ts' iMessage inbound mapper until upstream preserves mixed
  3. // text + attachment Apple events. The mapper returns only
  4. // buildAttachmentMessage(...) whenever attachments are present, which drops
  5. // `message.content.text` before Hermes can see it. We rewrite the two inbound
  6. // mappers — `rebuildFromAppleMessage` (used by `space.getMessage`) and
  7. // `toInboundMessages` (used by the live stream) — so a bubble carrying both
  8. // text and attachment(s) surfaces as a group whose first child is the typed
  9. // text. Paths with no text are rewritten to byte-identical behavior, so only
  10. // mixed text+attachment messages change shape.
  11. //
  12. // Since spectrum-ts 5.x split the SDK into scoped packages, the iMessage mapper
  13. // lives in `@spectrum-ts/imessage/dist/index.js` (it used to be a chunk under
  14. // `spectrum-ts/dist`). The published output is tab-indented and uses
  15. // `const ... = async` declarations; the anchors below match that exactly and
  16. // fail loudly if a future spectrum-ts reshapes the mapper.
  17. import fs from "node:fs";
  18. import path from "node:path";
  19. import { fileURLToPath, pathToFileURL } from "node:url";
  20. const MARKER = "Hermes patch: Preserve mixed text + attachment iMessage payloads";
  21. function scriptDir() {
  22. return path.dirname(fileURLToPath(import.meta.url));
  23. }
  24. function replaceOnce(source, from, to, label) {
  25. const count = source.split(from).length - 1;
  26. if (count !== 1) {
  27. throw new Error(`expected exactly one ${label} match, found ${count}`);
  28. }
  29. return source.replace(from, to);
  30. }
  31. function replaceExactly(source, from, to, expected, label) {
  32. const count = source.split(from).length - 1;
  33. if (count !== expected) {
  34. throw new Error(
  35. `expected exactly ${expected} ${label} matches, found ${count}`
  36. );
  37. }
  38. return source.split(from).join(to);
  39. }
  40. // The text-first child of a mixed text+attachment group, indented `tabs` deep
  41. // (the object's closing brace sits at `tabs`; its properties one level in).
  42. function textChild(tabs) {
  43. const t = "\t".repeat(tabs);
  44. return (
  45. `{\n${t}\t...base,\n${t}\tid: formatChildId(0, messageGuidStr),` +
  46. `\n${t}\tcontent: asText(text2),\n${t}\tpartIndex: 0,` +
  47. `\n${t}\tparentId: messageGuidStr\n${t}}`
  48. );
  49. }
  50. function patchRebuild(source) {
  51. // Capture the bubble text before the attachment branches consume it. The
  52. // existing no-attachment branch keeps its own `const text` declaration, so a
  53. // distinct name avoids a redeclaration.
  54. source = replaceOnce(
  55. source,
  56. `\tconst attachments = messageAttachments(message);\n\tif (attachments.length === 1) {`,
  57. `\tconst attachments = messageAttachments(message);\n\tconst text2 = message.content.text;\n\tif (attachments.length === 1) {`,
  58. "rebuild text capture"
  59. );
  60. // Single attachment: when text is present, push it to slot 0 and the
  61. // attachment to slot 1, then wrap both in a group.
  62. source = replaceOnce(
  63. source,
  64. `\t\treturn buildAttachmentMessage(client, base, info, messageGuidStr, 0);`,
  65. `\t\tconst msg2 = await buildAttachmentMessage(client, base, info, text2 ? formatChildId(1, messageGuidStr) : messageGuidStr, text2 ? 1 : 0, text2 ? messageGuidStr : void 0);\n\t\tif (text2) {\n\t\t\tconst textMsg = ${textChild(3)};\n\t\t\treturn {\n\t\t\t\t...base,\n\t\t\t\tid: messageGuidStr,\n\t\t\t\tcontent: asProviderGroup([textMsg, msg2])\n\t\t\t};\n\t\t}\n\t\treturn msg2;`,
  66. "rebuild single attachment"
  67. );
  68. // Multi attachment: prepend the text child to the group's items.
  69. source = replaceOnce(
  70. source,
  71. `\t\treturn {\n\t\t\t...base,\n\t\t\tid: messageGuidStr,\n\t\t\tcontent: asProviderGroup(items)\n\t\t};`,
  72. `\t\tif (text2) {\n\t\t\titems.unshift(${textChild(3)});\n\t\t}\n\t\treturn {\n\t\t\t...base,\n\t\t\tid: messageGuidStr,\n\t\t\tcontent: asProviderGroup(items)\n\t\t};`,
  73. "rebuild multi attachment text child"
  74. );
  75. return source;
  76. }
  77. function patchInbound(source) {
  78. source = replaceOnce(
  79. source,
  80. `\tconst attachments = messageAttachments(event.message);\n\tif (attachments.length === 1) {`,
  81. `\tconst attachments = messageAttachments(event.message);\n\tconst text2 = event.message.content.text;\n\tif (attachments.length === 1) {`,
  82. "inbound text capture"
  83. );
  84. source = replaceOnce(
  85. source,
  86. `\t\tconst msg = await buildAttachmentMessage(client, base, info, messageGuidStr, 0);\n\t\tcacheMessage(cache, msg);\n\t\treturn [msg];`,
  87. `\t\tconst msg = await buildAttachmentMessage(client, base, info, text2 ? formatChildId(1, messageGuidStr) : messageGuidStr, text2 ? 1 : 0, text2 ? messageGuidStr : void 0);\n\t\tif (text2) {\n\t\t\tconst textMsg = ${textChild(3)};\n\t\t\tconst parent = {\n\t\t\t\t...base,\n\t\t\t\tid: messageGuidStr,\n\t\t\t\tcontent: asProviderGroup([textMsg, msg])\n\t\t\t};\n\t\t\tcacheMessage(cache, parent);\n\t\t\treturn [parent];\n\t\t}\n\t\tcacheMessage(cache, msg);\n\t\treturn [msg];`,
  88. "inbound single attachment"
  89. );
  90. source = replaceOnce(
  91. source,
  92. `\t\tconst parent = {\n\t\t\t...base,\n\t\t\tid: messageGuidStr,\n\t\t\tcontent: asProviderGroup(items)\n\t\t};`,
  93. `\t\tif (text2) {\n\t\t\titems.unshift(${textChild(3)});\n\t\t}\n\t\tconst parent = {\n\t\t\t...base,\n\t\t\tid: messageGuidStr,\n\t\t\tcontent: asProviderGroup(items)\n\t\t};`,
  94. "inbound multi attachment text child"
  95. );
  96. return source;
  97. }
  98. // Shift attachment part indices by one when a text child occupies slot 0. The
  99. // push line is byte-identical in both mappers, so patch both occurrences.
  100. function patchChildIndices(source) {
  101. return replaceExactly(
  102. source,
  103. `items.push(await buildAttachmentMessage(client, base, info, formatChildId(i, messageGuidStr), i, messageGuidStr));`,
  104. `items.push(await buildAttachmentMessage(client, base, info, formatChildId(text2 ? i + 1 : i, messageGuidStr), text2 ? i + 1 : i, messageGuidStr));`,
  105. 2,
  106. "multi attachment child index"
  107. );
  108. }
  109. export function patchSpectrumTs(root = scriptDir()) {
  110. const dist = path.join(
  111. root,
  112. "node_modules",
  113. "@spectrum-ts",
  114. "imessage",
  115. "dist"
  116. );
  117. if (!fs.existsSync(dist)) {
  118. throw new Error(`@spectrum-ts/imessage dist not found: ${dist}`);
  119. }
  120. const files = fs.readdirSync(dist)
  121. .filter((name) => name.endsWith(".js"))
  122. .map((name) => path.join(dist, name));
  123. for (const file of files) {
  124. const raw = fs.readFileSync(file, "utf8");
  125. if (raw.includes(MARKER)) {
  126. return { patched: false, file, reason: "already patched" };
  127. }
  128. // Normalize to LF for matching so the patch works regardless of the
  129. // checkout's line-ending style (Windows git autocrlf produces CRLF,
  130. // which would otherwise defeat the \n-based search strings). The
  131. // original EOL style is restored on write. Indentation in the published
  132. // tarball is tabs; the anchors match that directly.
  133. const CR = String.fromCharCode(13);
  134. const CRLF = CR + "\n";
  135. const usedCRLF = raw.includes(CRLF);
  136. const original = usedCRLF ? raw.split(CRLF).join("\n") : raw;
  137. if (!original.includes("const toInboundMessages = async") ||
  138. !original.includes("const rebuildFromAppleMessage = async")) {
  139. continue;
  140. }
  141. // spectrum-ts 12.x replaced the attachment-only branches with
  142. // `buildUnwrappedContentMessage` + `toOrderedParts`, which already emits a
  143. // group containing both text and attachments. There is nothing left for
  144. // Hermes to patch; keep the legacy v8 path below for older pinned installs.
  145. if (
  146. original.includes("const buildUnwrappedContentMessage = async") &&
  147. original.includes("const parts = toOrderedParts(message.content.text, attachments);")
  148. ) {
  149. return { patched: false, file, reason: "upstream preserves mixed payloads" };
  150. }
  151. let patched = original;
  152. patched = patchRebuild(patched);
  153. patched = patchInbound(patched);
  154. patched = patchChildIndices(patched);
  155. patched = `// ${MARKER}\n${patched}`;
  156. if (usedCRLF) {
  157. patched = patched.split("\n").join(CRLF);
  158. }
  159. fs.writeFileSync(file, patched, "utf8");
  160. return { patched: true, file };
  161. }
  162. throw new Error("could not find @spectrum-ts/imessage iMessage inbound chunk to patch");
  163. }
  164. const _invokedDirectly =
  165. process.argv[1] &&
  166. import.meta.url === pathToFileURL(process.argv[1]).href;
  167. if (_invokedDirectly) {
  168. try {
  169. const root = process.argv[2] ? path.resolve(process.argv[2]) : scriptDir();
  170. const result = patchSpectrumTs(root);
  171. const action = result.patched ? "patched" : "ok";
  172. console.error(`photon-sidecar: spectrum mixed attachment patch ${action}: ${result.file}`);
  173. } catch (err) {
  174. console.error(`photon-sidecar: spectrum mixed attachment patch failed: ${err?.stack || err}`);
  175. process.exit(1);
  176. }
  177. }