Skip to content

Commit 6ae89b5

Browse files
authored
fix(imessage): preserve dunder reference links (#130547)
* fix(imessage): preserve dunder reference links * docs(plugin-sdk): define dunder parser option
1 parent 3cb0dd4 commit 6ae89b5

5 files changed

Lines changed: 231 additions & 68 deletions

File tree

‎extensions/imessage/src/markdown-format.test.ts‎

Lines changed: 32 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,17 +144,47 @@ describe("extractMarkdownFormatRuns", () => {
144144
});
145145
});
146146

147-
it("does not confuse an earlier matching bold span with a protected dunder", () => {
147+
it("does not confuse an earlier matching bold span with a dunder call", () => {
148148
expect(extractMarkdownFormatRuns("**init**() then __init__()")).toEqual({
149149
text: "init() then __init__()",
150150
ranges: [{ start: 0, length: 4, styles: ["bold"] }],
151151
});
152152
});
153153

154-
it("searches past unrelated declarations for the matching dunder range", () => {
154+
it("keeps dunder declarations literal after ordinary declarations", () => {
155155
expect(extractMarkdownFormatRuns("def init():\ndef __init__(self):")).toEqual({
156156
text: "def init():\ndef __init__(self):",
157157
ranges: [],
158158
});
159159
});
160+
161+
it("resolves reference labels that contain different dunder identifiers", () => {
162+
expect(
163+
extractMarkdownFormatRuns(
164+
"[Class][obj.__class__]\n\n[obj.__class__]: https://example.org/python",
165+
),
166+
).toEqual({
167+
text: "Class (https://example.org/python)",
168+
ranges: [],
169+
});
170+
});
171+
172+
it("preserves every repeated destination containing a dunder identifier", () => {
173+
expect(
174+
extractMarkdownFormatRuns(
175+
[
176+
"[Class][docs] and [Type][docs] **done**",
177+
"",
178+
"[docs]: https://docs.python.org/3/library/stdtypes.html#instance.__class__",
179+
].join("\n"),
180+
),
181+
).toEqual({
182+
text: [
183+
"Class (https://docs.python.org/3/library/stdtypes.html#instance.__class__)",
184+
"and Type (https://docs.python.org/3/library/stdtypes.html#instance.__class__)",
185+
"done",
186+
].join(" "),
187+
ranges: [{ start: 153, length: 4, styles: ["bold"] }],
188+
});
189+
});
160190
});

‎extensions/imessage/src/markdown-format.ts‎

Lines changed: 3 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -50,39 +50,6 @@ function codeDelimiter(content: string): string {
5050
}
5151

5252
type TextEdit = { start: number; end: number; text: string };
53-
type DunderProtection = { token: string; identifier: string };
54-
55-
function protectDunderIdentifiers(input: string): {
56-
markdown: string;
57-
protections: DunderProtection[];
58-
} {
59-
const protections: DunderProtection[] = [];
60-
let markdown = "";
61-
let cursor = 0;
62-
for (const match of input.matchAll(/__[\p{L}_][\p{L}\p{N}_]*__/gu)) {
63-
const identifier = match[0];
64-
const start = match.index ?? 0;
65-
const end = start + identifier.length;
66-
const before = input[start - 1];
67-
const beforeBefore = input[start - 2];
68-
const after = input[end];
69-
const member = before === ".";
70-
const call = after === "(";
71-
const functionArgument = before === "(" && /[\p{L}\p{N}_]/u.test(beforeBefore ?? "");
72-
const index = after === "[";
73-
if (!member && !call && !functionArgument && !index) {
74-
continue;
75-
}
76-
let token = `OCdunder${protections.length}token`;
77-
while (input.includes(token)) {
78-
token += "x";
79-
}
80-
markdown += input.slice(cursor, start) + token;
81-
protections.push({ token, identifier });
82-
cursor = end;
83-
}
84-
return { markdown: markdown + input.slice(cursor), protections };
85-
}
8653

8754
function applyTextEdits(text: string, edits: TextEdit[]) {
8855
const ordered = edits.toSorted((left, right) => left.start - right.start);
@@ -105,31 +72,6 @@ function applyTextEdits(text: string, edits: TextEdit[]) {
10572
};
10673
}
10774

108-
function restoreDunderIdentifiers(
109-
text: string,
110-
ranges: IMessageFormatRange[],
111-
codeRanges: Array<{ start: number; length: number }>,
112-
protections: DunderProtection[],
113-
) {
114-
const edits = protections.flatMap((protection) => {
115-
const start = text.indexOf(protection.token);
116-
return start === -1
117-
? []
118-
: [{ start, end: start + protection.token.length, text: protection.identifier }];
119-
});
120-
const edited = applyTextEdits(text, edits);
121-
const mapRange = <T extends { start: number; length: number }>(range: T): T => ({
122-
...range,
123-
start: edited.mapOffset(range.start),
124-
length: edited.mapOffset(range.start + range.length) - edited.mapOffset(range.start),
125-
});
126-
return {
127-
text: edited.text,
128-
ranges: ranges.map(mapRange),
129-
codeRanges: codeRanges.map(mapRange),
130-
};
131-
}
132-
13375
function restoreCodeMarkers(
13476
text: string,
13577
ranges: Array<{ start: number; length: number; styles: IMessageFormatStyle[] }>,
@@ -157,12 +99,12 @@ export function extractMarkdownFormatRuns(input: string): {
15799
text: string;
158100
ranges: IMessageFormatRange[];
159101
} {
160-
const protectedDunders = protectDunderIdentifiers(input);
161-
const ir = markdownToIR(protectedDunders.markdown, {
102+
const ir = markdownToIR(input, {
162103
autolink: false,
163104
enableHtmlUnderline: true,
164105
headingStyle: "rich",
165106
linkify: false,
107+
preserveDunderIdentifiers: true,
166108
preserveSourceBlockSpacing: true,
167109
});
168110
const rendered = renderMarkdownWithAttributedRanges(
@@ -175,15 +117,13 @@ export function extractMarkdownFormatRuns(input: string): {
175117
{ styleMap: { code: "code" } },
176118
IMESSAGE_CODE_PROFILE,
177119
);
178-
const dunders = restoreDunderIdentifiers(
120+
return restoreCodeMarkers(
179121
rendered.text,
180122
rendered.ranges.map(({ start, length, style }) => ({
181123
start,
182124
length,
183125
styles: [style],
184126
})),
185127
code.ranges,
186-
protectedDunders.protections,
187128
);
188-
return restoreCodeMarkers(dunders.text, dunders.ranges, dunders.codeRanges);
189129
}

‎extensions/imessage/src/send.test.ts‎

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -639,6 +639,17 @@ describe("sendMessageIMessage receipts", () => {
639639
}
640640
}
641641

642+
const dunderReferenceRequestIndex = countNativeRequests();
643+
await sendMessageIMessage(
644+
"chat_id:10",
645+
[
646+
"[Class][docs] and [Type][docs] **done**",
647+
"",
648+
"[docs]: https://docs.python.org/3/library/stdtypes.html#instance.__class__",
649+
].join("\n"),
650+
{ config: cfg },
651+
);
652+
642653
const oversizedYaml = [
643654
"```yaml",
644655
...Array.from({ length: 6 }, (_, index) =>
@@ -678,7 +689,7 @@ describe("sendMessageIMessage receipts", () => {
678689
);
679690
const requests = readRequests();
680691
const expectedFixedRequestCount =
681-
1 + disguisedCases.length + 1 + channelContractRequestCount + embeddedRequestCount;
692+
1 + disguisedCases.length + 1 + channelContractRequestCount + embeddedRequestCount + 1;
682693
expect(fixedRequestCount).toBe(expectedFixedRequestCount);
683694
const monitorRequests = requests.slice(
684695
expectedFixedRequestCount,
@@ -735,10 +746,27 @@ describe("sendMessageIMessage receipts", () => {
735746
(boldRange?.start ?? 0) + (boldRange?.length ?? 0),
736747
),
737748
).toBe("😀 styled");
749+
expect(requests[dunderReferenceRequestIndex]?.params).toMatchObject({
750+
text: [
751+
"Class (https://docs.python.org/3/library/stdtypes.html#instance.__class__)",
752+
"and Type (https://docs.python.org/3/library/stdtypes.html#instance.__class__)",
753+
"done",
754+
].join(" "),
755+
formatting: [{ start: 153, length: 4, styles: ["bold"] }],
756+
});
738757

739758
const { imessageActionsRuntime } = await import("./actions.runtime.js");
740759
const actionOptions = { cliPath, chatGuid: "iMessage;+;chat0000" };
741760
const fencedYaml = ["```yaml", ...roles.map((role) => `${role}:`), "```"].join("\n");
761+
await imessageActionsRuntime.sendRichMessage({
762+
chatGuid: actionOptions.chatGuid,
763+
text: [
764+
"[Class][obj.__class__] **done**",
765+
"",
766+
"[obj.__class__]: https://example.org/python",
767+
].join("\n"),
768+
options: actionOptions,
769+
});
742770
await imessageActionsRuntime.sendRichMessage({
743771
chatGuid: actionOptions.chatGuid,
744772
text: [
@@ -862,8 +890,9 @@ describe("sendMessageIMessage receipts", () => {
862890
.map((line) => JSON.parse(line) as string[]);
863891
const actionValue = (args: string[], flag: string) => args[args.indexOf(flag) + 1] ?? "";
864892
const actions = readActions();
865-
expect(actions).toHaveLength(6);
893+
expect(actions).toHaveLength(7);
866894
const [
895+
dunderReferenceAction,
867896
replyAction,
868897
effectAction,
869898
attachmentAction,
@@ -872,15 +901,22 @@ describe("sendMessageIMessage receipts", () => {
872901
pollAction,
873902
] = actions;
874903
if (
904+
!dunderReferenceAction ||
875905
!replyAction ||
876906
!effectAction ||
877907
!attachmentAction ||
878908
!emptyAttachmentAction ||
879909
!editAction ||
880910
!pollAction
881911
) {
882-
throw new Error("Expected all six native iMessage action subprocesses");
912+
throw new Error("Expected all seven native iMessage action subprocesses");
883913
}
914+
expect(actionValue(dunderReferenceAction, "--text")).toBe(
915+
"Class (https://example.org/python) done",
916+
);
917+
expect(JSON.parse(actionValue(dunderReferenceAction, "--format"))).toEqual([
918+
{ start: 35, length: 4, styles: ["bold"] },
919+
]);
884920
expect(replyAction).toContain("--reply-to");
885921
expect(actionValue(replyAction, "--reply-to")).toBe("reply-message-guid");
886922
expect(actionValue(effectAction, "--effect")).toBe("com.apple.MobileSMS.expressivesend.loud");
Lines changed: 119 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,119 @@
1+
import { describe, expect, it } from "vitest";
2+
import { markdownToIR } from "./ir.js";
3+
4+
const DUNDER_OPTIONS = {
5+
autolink: false,
6+
linkify: false,
7+
preserveDunderIdentifiers: true,
8+
} as const;
9+
10+
describe("markdownToIR preserveDunderIdentifiers", () => {
11+
it("leaves CommonMark emphasis unchanged by default", () => {
12+
expect(markdownToIR("obj.__class__", { autolink: false, linkify: false })).toEqual({
13+
text: "obj.class",
14+
styles: [{ start: 4, end: 9, style: "bold" }],
15+
links: [],
16+
});
17+
});
18+
19+
it("keeps ordinary parenthesized bold unchanged when enabled", () => {
20+
expect(markdownToIR("(__warning__)", DUNDER_OPTIONS)).toEqual({
21+
text: "(warning)",
22+
styles: [{ start: 1, end: 8, style: "bold" }],
23+
links: [],
24+
});
25+
});
26+
27+
it.each([
28+
["member access", "obj.__class__"],
29+
["call", "__init__()"],
30+
["function argument", "print(__name__)"],
31+
["index", '__dict__["key"]'],
32+
])("preserves %s identifiers", (_name, source) => {
33+
expect(markdownToIR(source, DUNDER_OPTIONS)).toEqual({
34+
text: source,
35+
styles: [],
36+
links: [],
37+
});
38+
});
39+
40+
it.each([
41+
{
42+
name: "full",
43+
source: "[Class][obj.__class__]\n\n[obj.__class__]: https://example.org/python",
44+
text: "Class",
45+
end: 5,
46+
},
47+
{
48+
name: "collapsed",
49+
source: "[obj.__class__][]\n\n[obj.__class__]: https://example.org/python",
50+
text: "obj.__class__",
51+
end: 13,
52+
},
53+
{
54+
name: "shortcut",
55+
source: "[obj.__class__]\n\n[obj.__class__]: https://example.org/python",
56+
text: "obj.__class__",
57+
end: 13,
58+
},
59+
{
60+
name: "case-normalized",
61+
source: "[Class][OBJ.__CLASS__]\n\n[obj.__class__]: https://example.org/python",
62+
text: "Class",
63+
end: 5,
64+
},
65+
{
66+
name: "whitespace-normalized",
67+
source: "[Class][obj. __class__]\n\n[obj.\t__class__]: https://example.org/python",
68+
text: "Class",
69+
end: 5,
70+
},
71+
])("preserves $name reference links", ({ source, text, end }) => {
72+
expect(markdownToIR(source, DUNDER_OPTIONS)).toEqual({
73+
text,
74+
styles: [],
75+
links: [{ start: 0, end, href: "https://example.org/python" }],
76+
});
77+
});
78+
79+
it("preserves repeated reference destinations", () => {
80+
const href = "https://docs.python.org/3/library/stdtypes.html#instance.__class__";
81+
expect(
82+
markdownToIR(`[Class][docs] and [Type][docs]\n\n[docs]: ${href}`, DUNDER_OPTIONS),
83+
).toEqual({
84+
text: "Class and Type",
85+
styles: [],
86+
links: [
87+
{ start: 0, end: 5, href },
88+
{ start: 10, end: 14, href },
89+
],
90+
});
91+
});
92+
93+
it.each([
94+
{
95+
name: "inline",
96+
source: "`obj.__class__`",
97+
text: "obj.__class__",
98+
styles: [{ start: 0, end: 13, style: "code" }],
99+
},
100+
{
101+
name: "fenced",
102+
source: "```python\nobj.__class__\n```",
103+
text: "obj.__class__\n",
104+
styles: [{ start: 0, end: 14, style: "code_block", language: "python" }],
105+
},
106+
{
107+
name: "indented",
108+
source: " obj.__class__",
109+
text: "obj.__class__\n",
110+
styles: [{ start: 0, end: 14, style: "code_block" }],
111+
},
112+
])("leaves $name code handling unchanged", ({ source, text, styles }) => {
113+
expect(markdownToIR(source, DUNDER_OPTIONS)).toEqual({
114+
text,
115+
styles,
116+
links: [],
117+
});
118+
});
119+
});

0 commit comments

Comments
 (0)