@gitkraken/core-gitlens 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (255) hide show
  1. package/CHANGELOG.md +34 -1
  2. package/dist/git/models/remote.js +2 -2
  3. package/dist/git/models/remote.js.map +1 -1
  4. package/dist/git/remotes/matcher.js +25 -3
  5. package/dist/git/remotes/matcher.js.map +1 -1
  6. package/dist/git/utils/branchLanded.utils.d.ts +7 -0
  7. package/dist/git/utils/branchLanded.utils.js +10 -1
  8. package/dist/git/utils/branchLanded.utils.js.map +1 -1
  9. package/dist/git/utils/remote.utils.d.ts +1 -0
  10. package/dist/git/utils/remote.utils.js +14 -5
  11. package/dist/git/utils/remote.utils.js.map +1 -1
  12. package/dist/git-cli/parsers/logParser.js +227 -468
  13. package/dist/git-cli/parsers/logParser.js.map +1 -1
  14. package/dist/git-cli/parsers/refParser.js +4 -4
  15. package/dist/git-cli/parsers/refParser.js.map +1 -1
  16. package/dist/git-cli/providers/branches.d.ts +5 -0
  17. package/dist/git-cli/providers/branches.js +25 -21
  18. package/dist/git-cli/providers/branches.js.map +1 -1
  19. package/dist/git-cli/providers/config.js +2 -2
  20. package/dist/git-cli/providers/pausedOperations.js +2 -2
  21. package/dist/git-cli/providers/pausedOperations.js.map +1 -1
  22. package/dist/git-cli/providers/staging.js +1 -1
  23. package/dist/ipc/discovery.js +1 -1
  24. package/dist/plus/agents/providers/claudeCodeTranscript.js +6 -6
  25. package/dist/plus/agents/providers/claudeCodeTranscript.js.map +1 -1
  26. package/dist/plus/ai/providers/openAICompatibleProviderBase.js +1 -1
  27. package/dist/plus/git-github/api/github.d.ts +13 -1
  28. package/dist/plus/git-github/api/github.js +99 -30
  29. package/dist/plus/git-github/api/github.js.map +1 -1
  30. package/dist/plus/git-github/api/issueWrites.d.ts +9 -2
  31. package/dist/plus/git-github/api/issueWrites.js +61 -31
  32. package/dist/plus/git-github/api/issueWrites.js.map +1 -1
  33. package/dist/plus/git-github/api/pullRequestWrites.d.ts +95 -0
  34. package/dist/plus/git-github/api/pullRequestWrites.js +469 -0
  35. package/dist/plus/git-github/api/pullRequestWrites.js.map +1 -0
  36. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.d.ts +44 -0
  37. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js +199 -0
  38. package/dist/plus/integrations/authentication/cloudIntegrationAuthenticationProvider.js.map +1 -0
  39. package/dist/plus/integrations/authentication/configuredIntegrationService.d.ts +17 -9
  40. package/dist/plus/integrations/authentication/configuredIntegrationService.js +71 -19
  41. package/dist/plus/integrations/authentication/configuredIntegrationService.js.map +1 -1
  42. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.d.ts +9 -40
  43. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.js +0 -182
  44. package/dist/plus/integrations/authentication/integrationAuthenticationService.d.ts +5 -2
  45. package/dist/plus/integrations/authentication/integrationAuthenticationService.js +15 -1
  46. package/dist/plus/integrations/authentication/integrationAuthenticationService.js.map +1 -1
  47. package/dist/plus/integrations/authentication/models.d.ts +0 -1
  48. package/dist/plus/integrations/authentication/models.js +1 -2
  49. package/dist/plus/integrations/authentication/models.js.map +1 -1
  50. package/dist/plus/integrations/authentication/observedAuthenticationProvider.d.ts +1 -0
  51. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js +14 -4
  52. package/dist/plus/integrations/authentication/observedAuthenticationProvider.js.map +1 -1
  53. package/dist/plus/integrations/authentication/rejectedTokenTracker.d.ts +2 -2
  54. package/dist/plus/integrations/authentication/rejectedTokenTracker.js +19 -5
  55. package/dist/plus/integrations/authentication/rejectedTokenTracker.js.map +1 -1
  56. package/dist/plus/integrations/constants.d.ts +0 -10
  57. package/dist/plus/integrations/constants.js +1 -95
  58. package/dist/plus/integrations/constants.js.map +1 -1
  59. package/dist/plus/integrations/context.d.ts +13 -13
  60. package/dist/plus/integrations/index.d.ts +41 -25
  61. package/dist/plus/integrations/index.js +40 -8
  62. package/dist/plus/integrations/index.js.map +1 -1
  63. package/dist/plus/integrations/integrationService.d.ts +20 -22
  64. package/dist/plus/integrations/integrationService.js +80 -9
  65. package/dist/plus/integrations/integrationService.js.map +1 -1
  66. package/dist/plus/integrations/lite.js +1 -1
  67. package/dist/plus/integrations/lite.js.map +1 -1
  68. package/dist/plus/integrations/manager.d.ts +70 -15
  69. package/dist/plus/integrations/models/actionablePullRequest.d.ts +213 -0
  70. package/dist/plus/integrations/models/actionablePullRequest.js +25 -0
  71. package/dist/plus/integrations/models/actionablePullRequest.js.map +1 -0
  72. package/dist/plus/integrations/models/gitHostIntegration.d.ts +13 -46
  73. package/dist/plus/integrations/models/gitHostIntegration.js +15 -4
  74. package/dist/plus/integrations/models/gitHostIntegration.js.map +1 -1
  75. package/dist/plus/integrations/models/integration.d.ts +12 -177
  76. package/dist/plus/integrations/models/integration.js +21 -77
  77. package/dist/plus/integrations/models/integration.js.map +1 -1
  78. package/dist/plus/integrations/models/issuesIntegration.d.ts +9 -5
  79. package/dist/plus/integrations/models/issuesIntegration.js +5 -3
  80. package/dist/plus/integrations/models/issuesIntegration.js.map +1 -1
  81. package/dist/plus/integrations/models/publicIntegration.d.ts +252 -0
  82. package/dist/plus/integrations/models/publicIntegration.js +21 -0
  83. package/dist/plus/integrations/models/publicIntegration.js.map +1 -0
  84. package/dist/plus/integrations/providerFilters.d.ts +58 -0
  85. package/dist/plus/integrations/providerFilters.js.map +1 -1
  86. package/dist/plus/integrations/providers/actionablePullRequests.d.ts +19 -0
  87. package/dist/plus/integrations/providers/actionablePullRequests.js +32 -0
  88. package/dist/plus/integrations/providers/actionablePullRequests.js.map +1 -0
  89. package/dist/plus/integrations/providers/apiClients.d.ts +1 -2
  90. package/dist/plus/integrations/providers/apiClients.js.map +1 -1
  91. package/dist/plus/integrations/providers/asana.d.ts +3 -2
  92. package/dist/plus/integrations/providers/asana.js +2 -1
  93. package/dist/plus/integrations/providers/asana.js.map +1 -1
  94. package/dist/plus/integrations/providers/azure/azure.d.ts +1 -1
  95. package/dist/plus/integrations/providers/azure/azure.js +1 -1
  96. package/dist/plus/integrations/providers/azure/azure.utils.d.ts +10 -3
  97. package/dist/plus/integrations/providers/azure/azure.utils.js +5 -1
  98. package/dist/plus/integrations/providers/azure/azure.utils.js.map +1 -1
  99. package/dist/plus/integrations/providers/azure/models.d.ts +1 -5
  100. package/dist/plus/integrations/providers/azure/models.js +1 -1
  101. package/dist/plus/integrations/providers/azure/models.js.map +1 -1
  102. package/dist/plus/integrations/providers/azureDevOps.d.ts +8 -5
  103. package/dist/plus/integrations/providers/azureDevOps.js +2 -1
  104. package/dist/plus/integrations/providers/azureDevOps.js.map +1 -1
  105. package/dist/plus/integrations/providers/azureDevOpsServer.d.ts +5 -4
  106. package/dist/plus/integrations/providers/azureDevOpsServer.js +3 -1
  107. package/dist/plus/integrations/providers/azureDevOpsServer.js.map +1 -1
  108. package/dist/plus/integrations/providers/bitbucket/bitbucket.d.ts +2 -2
  109. package/dist/plus/integrations/providers/bitbucket/bitbucket.js.map +1 -1
  110. package/dist/plus/integrations/providers/bitbucket/models.d.ts +1 -1
  111. package/dist/plus/integrations/providers/bitbucket/models.js.map +1 -1
  112. package/dist/plus/integrations/providers/bitbucket-server.d.ts +5 -4
  113. package/dist/plus/integrations/providers/bitbucket-server.js +2 -1
  114. package/dist/plus/integrations/providers/bitbucket-server.js.map +1 -1
  115. package/dist/plus/integrations/providers/bitbucket.d.ts +4 -3
  116. package/dist/plus/integrations/providers/bitbucket.js +2 -1
  117. package/dist/plus/integrations/providers/bitbucket.js.map +1 -1
  118. package/dist/plus/integrations/providers/github/github.d.ts +0 -1
  119. package/dist/plus/integrations/providers/github/github.js +1 -1
  120. package/dist/plus/integrations/providers/github/github.js.map +1 -1
  121. package/dist/plus/integrations/providers/github.d.ts +16 -6
  122. package/dist/plus/integrations/providers/github.js +109 -12
  123. package/dist/plus/integrations/providers/github.js.map +1 -1
  124. package/dist/plus/integrations/providers/gitlab/gitlab.d.ts +2 -2
  125. package/dist/plus/integrations/providers/gitlab/gitlab.js +1 -2
  126. package/dist/plus/integrations/providers/gitlab/gitlab.js.map +1 -1
  127. package/dist/plus/integrations/providers/gitlab/gitlab.utils.d.ts +14 -1
  128. package/dist/plus/integrations/providers/gitlab/gitlab.utils.js.map +1 -1
  129. package/dist/plus/integrations/providers/gitlab/models.d.ts +2 -10
  130. package/dist/plus/integrations/providers/gitlab/models.js.map +1 -1
  131. package/dist/plus/integrations/providers/gitlab.d.ts +7 -5
  132. package/dist/plus/integrations/providers/gitlab.js +2 -1
  133. package/dist/plus/integrations/providers/gitlab.js.map +1 -1
  134. package/dist/plus/integrations/providers/issueSorts.d.ts +0 -1
  135. package/dist/plus/integrations/providers/jira-server.d.ts +4 -4
  136. package/dist/plus/integrations/providers/jira-server.js +3 -2
  137. package/dist/plus/integrations/providers/jira-server.js.map +1 -1
  138. package/dist/plus/integrations/providers/jira.d.ts +3 -3
  139. package/dist/plus/integrations/providers/jira.js +3 -2
  140. package/dist/plus/integrations/providers/jira.js.map +1 -1
  141. package/dist/plus/integrations/providers/jiraIssueByKey.d.ts +1 -1
  142. package/dist/plus/integrations/providers/jiraIssueByKey.js.map +1 -1
  143. package/dist/plus/integrations/providers/linear.d.ts +4 -3
  144. package/dist/plus/integrations/providers/linear.js +3 -2
  145. package/dist/plus/integrations/providers/linear.js.map +1 -1
  146. package/dist/plus/integrations/providers/linearIssuesEtag.d.ts +1 -1
  147. package/dist/plus/integrations/providers/linearIssuesEtag.js +1 -1
  148. package/dist/plus/integrations/providers/linearIssuesEtag.js.map +1 -1
  149. package/dist/plus/integrations/providers/metadata.d.ts +136 -0
  150. package/dist/plus/integrations/providers/metadata.js +513 -0
  151. package/dist/plus/integrations/providers/metadata.js.map +1 -0
  152. package/dist/plus/integrations/providers/models.d.ts +10 -206
  153. package/dist/plus/integrations/providers/models.js +8 -539
  154. package/dist/plus/integrations/providers/models.js.map +1 -1
  155. package/dist/plus/integrations/providers/providersApi.d.ts +3 -2
  156. package/dist/plus/integrations/providers/providersApi.js +2 -1
  157. package/dist/plus/integrations/providers/providersApi.js.map +1 -1
  158. package/dist/plus/integrations/providers/trello.d.ts +1 -1
  159. package/dist/plus/integrations/providers/trello.js +2 -1
  160. package/dist/plus/integrations/providers/trello.js.map +1 -1
  161. package/dist/plus/integrations/providers/utils/providerPaging.d.ts +2 -0
  162. package/dist/plus/integrations/providers/utils/providerPaging.js +3 -2
  163. package/dist/plus/integrations/providers/utils/providerPaging.js.map +1 -1
  164. package/dist/plus/integrations/providers/utils.d.ts +119 -10
  165. package/dist/plus/integrations/providers/utils.js +57 -3
  166. package/dist/plus/integrations/providers/utils.js.map +1 -1
  167. package/dist/plus/integrations/reads/autolinks.d.ts +1 -1
  168. package/dist/plus/integrations/reads/autolinks.js +1 -1
  169. package/dist/plus/integrations/reads/autolinks.js.map +1 -1
  170. package/dist/plus/integrations/reads/broaden.d.ts +1 -1
  171. package/dist/plus/integrations/reads/broaden.js +3 -2
  172. package/dist/plus/integrations/reads/broaden.js.map +1 -1
  173. package/dist/plus/integrations/reads/context.d.ts +1 -1
  174. package/dist/plus/integrations/reads/counts.d.ts +1 -88
  175. package/dist/plus/integrations/reads/counts.js +4 -2
  176. package/dist/plus/integrations/reads/counts.js.map +1 -1
  177. package/dist/plus/integrations/reads/currentAccount.d.ts +1 -18
  178. package/dist/plus/integrations/reads/currentAccount.js.map +1 -1
  179. package/dist/plus/integrations/reads/drains.d.ts +3 -4
  180. package/dist/plus/integrations/reads/drains.js +1 -1
  181. package/dist/plus/integrations/reads/drains.js.map +1 -1
  182. package/dist/plus/integrations/reads/etag.d.ts +174 -3
  183. package/dist/plus/integrations/reads/etag.js +69 -14
  184. package/dist/plus/integrations/reads/etag.js.map +1 -1
  185. package/dist/plus/integrations/reads/filters.d.ts +3 -61
  186. package/dist/plus/integrations/reads/filters.js +1 -1
  187. package/dist/plus/integrations/reads/filters.js.map +1 -1
  188. package/dist/plus/integrations/reads/hierarchy.d.ts +1 -1
  189. package/dist/plus/integrations/reads/hierarchy.js +4 -2
  190. package/dist/plus/integrations/reads/hierarchy.js.map +1 -1
  191. package/dist/plus/integrations/reads/issueBatch.d.ts +2 -102
  192. package/dist/plus/integrations/reads/issueBatch.js +3 -4
  193. package/dist/plus/integrations/reads/issueBatch.js.map +1 -1
  194. package/dist/plus/integrations/reads/issueTracker.d.ts +1 -1
  195. package/dist/plus/integrations/reads/issueTracker.js +4 -3
  196. package/dist/plus/integrations/reads/issueTracker.js.map +1 -1
  197. package/dist/plus/integrations/reads/issues.d.ts +1 -1
  198. package/dist/plus/integrations/reads/issues.js +4 -2
  199. package/dist/plus/integrations/reads/issues.js.map +1 -1
  200. package/dist/plus/integrations/reads/paging.d.ts +1 -1
  201. package/dist/plus/integrations/reads/paging.js +1 -1
  202. package/dist/plus/integrations/reads/paging.js.map +1 -1
  203. package/dist/plus/integrations/reads/pullRequestActivity.d.ts +1 -24
  204. package/dist/plus/integrations/reads/pullRequestActivity.js +2 -1
  205. package/dist/plus/integrations/reads/pullRequestActivity.js.map +1 -1
  206. package/dist/plus/integrations/reads/pullRequestBatch.d.ts +2 -56
  207. package/dist/plus/integrations/reads/pullRequestBatch.js +23 -3
  208. package/dist/plus/integrations/reads/pullRequestBatch.js.map +1 -1
  209. package/dist/plus/integrations/reads/pullRequestBranches.d.ts +1 -47
  210. package/dist/plus/integrations/reads/pullRequestBranches.js +2 -1
  211. package/dist/plus/integrations/reads/pullRequestBranches.js.map +1 -1
  212. package/dist/plus/integrations/reads/pullRequestCheckLogs.d.ts +1 -15
  213. package/dist/plus/integrations/reads/pullRequestCheckLogs.js +2 -1
  214. package/dist/plus/integrations/reads/pullRequestCheckLogs.js.map +1 -1
  215. package/dist/plus/integrations/reads/pullRequests.js +4 -2
  216. package/dist/plus/integrations/reads/pullRequests.js.map +1 -1
  217. package/dist/plus/integrations/reads/pullRequestsForCommits.d.ts +1 -16
  218. package/dist/plus/integrations/reads/pullRequestsForCommits.js +2 -1
  219. package/dist/plus/integrations/reads/pullRequestsForCommits.js.map +1 -1
  220. package/dist/plus/integrations/reads/resolveRepository.js +10 -5
  221. package/dist/plus/integrations/reads/resolveRepository.js.map +1 -1
  222. package/dist/plus/integrations/reads/searchIssues.js +2 -1
  223. package/dist/plus/integrations/reads/searchIssues.js.map +1 -1
  224. package/dist/plus/integrations/reads/searchPullRequests.js +2 -1
  225. package/dist/plus/integrations/reads/searchPullRequests.js.map +1 -1
  226. package/dist/plus/integrations/reads/sweeps.d.ts +1 -1
  227. package/dist/plus/integrations/reads/sweeps.js +3 -2
  228. package/dist/plus/integrations/reads/sweeps.js.map +1 -1
  229. package/dist/plus/integrations/reads/warnings.d.ts +1 -1
  230. package/dist/plus/integrations/reads/warnings.js +1 -1
  231. package/dist/plus/integrations/reads/warnings.js.map +1 -1
  232. package/dist/plus/integrations/results.d.ts +324 -2
  233. package/dist/plus/integrations/results.js.map +1 -1
  234. package/dist/plus/integrations/telemetry.d.ts +0 -10
  235. package/dist/plus/integrations/telemetry.js +0 -11
  236. package/dist/plus/integrations/utils/domain.utils.d.ts +1 -0
  237. package/dist/plus/integrations/utils/domain.utils.js +10 -2
  238. package/dist/plus/integrations/utils/domain.utils.js.map +1 -1
  239. package/dist/plus/integrations/utils/integration.utils.d.ts +1 -6
  240. package/dist/plus/integrations/utils/integration.utils.js +2 -9
  241. package/dist/plus/integrations/utils/integration.utils.js.map +1 -1
  242. package/dist/utils/env/node/exec.js +2 -2
  243. package/dist/utils/keys/chord.d.ts +13 -2
  244. package/dist/utils/keys/chord.js +76 -17
  245. package/dist/utils/keys/chord.js.map +1 -1
  246. package/dist/utils/keys/keybinding.d.ts +12 -0
  247. package/dist/utils/keys/keybinding.js +52 -2
  248. package/dist/utils/keys/keybinding.js.map +1 -1
  249. package/dist/utils/markdown.d.ts +21 -0
  250. package/dist/utils/markdown.js +33 -1
  251. package/dist/utils/markdown.js.map +1 -1
  252. package/docs/integrations.md +135 -16
  253. package/package.json +5 -1
  254. package/dist/plus/integrations/authentication/integrationAuthenticationProvider.js.map +0 -1
  255. package/dist/plus/integrations/telemetry.js.map +0 -1
@@ -1,5 +1,49 @@
1
1
  //#region ../utils/src/keys/chord.ts
2
2
  const codeTokenPattern = /^(?:Key[A-Z]|Digit[0-9])$/;
3
+ const keyTokenPattern = /^key([a-z])$/i;
4
+ const digitTokenPattern = /^digit([0-9])$/i;
5
+ /**
6
+ * Thrown by {@link parseChord} for malformed input. `message` is the full diagnostic; `reason` is a
7
+ * short phrase that reads after the quoted input (`'<input>' <reason>`) for user-facing reports.
8
+ */
9
+ var ChordParseError = class extends Error {
10
+ input;
11
+ reason;
12
+ constructor(input, reason, detail) {
13
+ super(`Invalid key chord '${input}': ${detail}`);
14
+ this.input = input;
15
+ this.reason = reason;
16
+ this.name = "ChordParseError";
17
+ }
18
+ };
19
+ /**
20
+ * Multi-character `KeyboardEvent.key` values a chord token may name (anything else could never match),
21
+ * keyed by lowercased name so lookups are case-insensitive and resolve to the canonical spelling.
22
+ */
23
+ const namedKeyTokens = new Map([
24
+ "ArrowUp",
25
+ "ArrowDown",
26
+ "ArrowLeft",
27
+ "ArrowRight",
28
+ "Backspace",
29
+ "BrowserBack",
30
+ "BrowserForward",
31
+ "Clear",
32
+ "ContextMenu",
33
+ "Delete",
34
+ "End",
35
+ "Enter",
36
+ "Escape",
37
+ "Help",
38
+ "Home",
39
+ "Insert",
40
+ "PageDown",
41
+ "PageUp",
42
+ "Pause",
43
+ "ScrollLock",
44
+ "Tab",
45
+ ...Array.from({ length: 24 }, (_, i) => `F${i + 1}`)
46
+ ].map((name) => [name.toLowerCase(), name]));
3
47
  const readableTokens = /* @__PURE__ */ new Map([
4
48
  ["ArrowUp", "↑"],
5
49
  ["ArrowDown", "↓"],
@@ -12,54 +56,69 @@ const readableTokens = /* @__PURE__ */ new Map([
12
56
  ]);
13
57
  /**
14
58
  * Parses a `+`-separated key combination such as `'mod+c'` or `'alt+KeyM'` into a {@link Chord}.
15
- * Throws on malformed input. `isMac` resolves the `'mod'` modifier (`meta` on mac, `ctrl` otherwise).
59
+ * Modifier and multi-character key names are case-insensitive (`'Alt+keym'` is `'alt+KeyM'`); a
60
+ * single-character token is matched exactly. Throws on malformed input. `isMac` resolves the `'mod'`
61
+ * modifier (`meta` on mac, `ctrl` otherwise).
16
62
  */
17
63
  function parseChord(input, isMac) {
18
- if (!input) throw new Error(`Invalid key chord '${input}': empty input`);
64
+ if (!input) throw new ChordParseError(input, "is empty", "empty input");
19
65
  const parts = input.split("+");
20
- if (parts.length > 1 && parts.at(-1) === "") throw new Error(`Invalid key chord '${input}': trailing '+'`);
66
+ if (parts.length > 1 && parts.at(-1) === "") throw new ChordParseError(input, "ends with '+' (a literal '+' can't be bound)", "trailing '+'");
21
67
  const modifiers = parts.slice(0, -1);
22
- const token = parts.at(-1);
23
- if (token === "") throw new Error(`Invalid key chord '${input}': empty token`);
68
+ const rawToken = parts.at(-1);
69
+ if (rawToken === "") throw new ChordParseError(input, "has no key", "empty token");
24
70
  let mod = false;
25
71
  let ctrl = false;
26
72
  let alt = false;
27
73
  let shift = false;
28
74
  let meta = false;
29
- for (const modifier of modifiers) switch (modifier) {
75
+ for (const modifier of modifiers) switch (modifier.toLowerCase()) {
30
76
  case "mod":
31
- if (mod) throw new Error(`Invalid key chord '${input}': duplicate modifier 'mod'`);
77
+ if (mod) throw new ChordParseError(input, `repeats the modifier 'mod'`, "duplicate modifier 'mod'");
32
78
  mod = true;
33
79
  break;
34
80
  case "ctrl":
35
- if (ctrl) throw new Error(`Invalid key chord '${input}': duplicate modifier 'ctrl'`);
81
+ if (ctrl) throw new ChordParseError(input, `repeats the modifier 'ctrl'`, "duplicate modifier 'ctrl'");
36
82
  ctrl = true;
37
83
  break;
38
84
  case "alt":
39
- if (alt) throw new Error(`Invalid key chord '${input}': duplicate modifier 'alt'`);
85
+ if (alt) throw new ChordParseError(input, `repeats the modifier 'alt'`, "duplicate modifier 'alt'");
40
86
  alt = true;
41
87
  break;
42
88
  case "shift":
43
- if (shift) throw new Error(`Invalid key chord '${input}': duplicate modifier 'shift'`);
89
+ if (shift) throw new ChordParseError(input, `repeats the modifier 'shift'`, "duplicate modifier 'shift'");
44
90
  shift = true;
45
91
  break;
46
92
  case "meta":
47
- if (meta) throw new Error(`Invalid key chord '${input}': duplicate modifier 'meta'`);
93
+ if (meta) throw new ChordParseError(input, `repeats the modifier 'meta'`, "duplicate modifier 'meta'");
48
94
  meta = true;
49
95
  break;
50
- default: throw new Error(`Invalid key chord '${input}': unknown modifier '${modifier}'`);
96
+ default: throw new ChordParseError(input, `has an unknown modifier '${modifier}'`, `unknown modifier '${modifier}'`);
51
97
  }
52
- if (mod && ctrl) throw new Error(`Invalid key chord '${input}': 'mod' conflicts with explicit 'ctrl'`);
53
- if (mod && meta) throw new Error(`Invalid key chord '${input}': 'mod' conflicts with explicit 'meta'`);
98
+ if (mod && ctrl) throw new ChordParseError(input, "combines 'mod' with 'ctrl' ('mod' already means Ctrl, or ⌘ on macOS)", "'mod' conflicts with explicit 'ctrl'");
99
+ if (mod && meta) throw new ChordParseError(input, "combines 'mod' with 'meta' ('mod' already means Ctrl, or ⌘ on macOS)", "'mod' conflicts with explicit 'meta'");
54
100
  if (mod) {
55
101
  if (isMac) meta = true;
56
102
  else ctrl = true;
57
103
  }
104
+ const isSingleChar = [...rawToken].length === 1;
105
+ let token = rawToken;
106
+ if (!isSingleChar) {
107
+ const keyMatch = keyTokenPattern.exec(rawToken);
108
+ const digitMatch = digitTokenPattern.exec(rawToken);
109
+ if (keyMatch != null) token = `Key${keyMatch[1].toUpperCase()}`;
110
+ else if (digitMatch != null) token = `Digit${digitMatch[1]}`;
111
+ else {
112
+ const named = namedKeyTokens.get(rawToken.toLowerCase());
113
+ if (named == null) throw new ChordParseError(input, `has an unknown key '${rawToken}'`, `unknown key '${rawToken}'`);
114
+ token = named;
115
+ }
116
+ }
58
117
  const matchOn = codeTokenPattern.test(token) ? "code" : "key";
59
118
  let resolvedShift;
60
119
  if (matchOn === "code") resolvedShift = shift;
61
- else if ([...token].length === 1) {
62
- if (shift) throw new Error(`Invalid key chord '${input}': 'shift' cannot combine with a single-character token`);
120
+ else if (isSingleChar) {
121
+ if (shift) throw new ChordParseError(input, `combines shift with a single character (use '${rawToken}' alone)`, "'shift' cannot combine with a single-character token");
63
122
  resolvedShift = "implicit";
64
123
  } else resolvedShift = shift;
65
124
  return {
@@ -116,6 +175,6 @@ function formatToken(chord) {
116
175
  return readableTokens.get(chord.token) ?? chord.token;
117
176
  }
118
177
  //#endregion
119
- export { formatChord, formatChordParts, matchesChord, parseChord };
178
+ export { ChordParseError, formatChord, formatChordParts, matchesChord, parseChord };
120
179
 
121
180
  //# sourceMappingURL=chord.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chord.js","names":[],"sources":["../../../../utils/src/keys/chord.ts"],"sourcesContent":["/** Structural subset of a keyboard event; lets this module stay DOM-free. */\nexport type KeyEventLike = {\n\tkey: string;\n\tcode: string;\n\tctrlKey: boolean;\n\taltKey: boolean;\n\tshiftKey: boolean;\n\tmetaKey: boolean;\n};\n\nexport type ChordModifier = 'mod' | 'ctrl' | 'alt' | 'shift' | 'meta';\n\n/** A single parsed key combination, ready to match against key events. */\nexport type Chord = {\n\t/** The original token, e.g. `'ArrowUp'`, `'c'`, `'KeyM'`. */\n\ttoken: string;\n\t/** Whether the token is matched against `event.code` (layout-independent) or `event.key`. */\n\tmatchOn: 'key' | 'code';\n\tctrl: boolean;\n\talt: boolean;\n\tmeta: boolean;\n\t/**\n\t * `true`/`false` when shift is a declared part of the chord; `'implicit'` when the token is a\n\t * single printable character whose shifted form already encodes the shift state (e.g. `'?'`),\n\t * so `event.shiftKey` is ignored at match time.\n\t */\n\tshift: boolean | 'implicit';\n};\n\nconst codeTokenPattern = /^(?:Key[A-Z]|Digit[0-9])$/;\n\nconst readableTokens = new Map<string, string>([\n\t['ArrowUp', '↑'],\n\t['ArrowDown', '↓'],\n\t['ArrowLeft', '←'],\n\t['ArrowRight', '→'],\n\t['Escape', 'Esc'],\n\t[' ', 'Space'],\n\t['PageUp', 'PgUp'],\n\t['PageDown', 'PgDn'],\n]);\n\n/**\n * Parses a `+`-separated key combination such as `'mod+c'` or `'alt+KeyM'` into a {@link Chord}.\n * Throws on malformed input. `isMac` resolves the `'mod'` modifier (`meta` on mac, `ctrl` otherwise).\n */\nexport function parseChord(input: string, isMac: boolean): Chord {\n\tif (!input) throw new Error(`Invalid key chord '${input}': empty input`);\n\n\tconst parts = input.split('+');\n\n\t// A trailing/leading '+' (literal plus as the token) produces an empty part adjacent to a\n\t// non-empty one; a lone '+' would split to ['', ''] and is handled by the empty-token check below.\n\tif (parts.length > 1 && parts.at(-1) === '') {\n\t\tthrow new Error(`Invalid key chord '${input}': trailing '+'`);\n\t}\n\n\tconst modifiers = parts.slice(0, -1);\n\tconst token = parts.at(-1)!;\n\n\tif (token === '') throw new Error(`Invalid key chord '${input}': empty token`);\n\n\tlet mod = false;\n\tlet ctrl = false;\n\tlet alt = false;\n\tlet shift = false;\n\tlet meta = false;\n\n\tfor (const modifier of modifiers) {\n\t\tswitch (modifier) {\n\t\t\tcase 'mod':\n\t\t\t\tif (mod) throw new Error(`Invalid key chord '${input}': duplicate modifier 'mod'`);\n\n\t\t\t\tmod = true;\n\t\t\t\tbreak;\n\t\t\tcase 'ctrl':\n\t\t\t\tif (ctrl) throw new Error(`Invalid key chord '${input}': duplicate modifier 'ctrl'`);\n\n\t\t\t\tctrl = true;\n\t\t\t\tbreak;\n\t\t\tcase 'alt':\n\t\t\t\tif (alt) throw new Error(`Invalid key chord '${input}': duplicate modifier 'alt'`);\n\n\t\t\t\talt = true;\n\t\t\t\tbreak;\n\t\t\tcase 'shift':\n\t\t\t\tif (shift) throw new Error(`Invalid key chord '${input}': duplicate modifier 'shift'`);\n\n\t\t\t\tshift = true;\n\t\t\t\tbreak;\n\t\t\tcase 'meta':\n\t\t\t\tif (meta) throw new Error(`Invalid key chord '${input}': duplicate modifier 'meta'`);\n\n\t\t\t\tmeta = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new Error(`Invalid key chord '${input}': unknown modifier '${modifier}'`);\n\t\t}\n\t}\n\n\tif (mod && ctrl) throw new Error(`Invalid key chord '${input}': 'mod' conflicts with explicit 'ctrl'`);\n\n\tif (mod && meta) throw new Error(`Invalid key chord '${input}': 'mod' conflicts with explicit 'meta'`);\n\n\tif (mod) {\n\t\tif (isMac) {\n\t\t\tmeta = true;\n\t\t} else {\n\t\t\tctrl = true;\n\t\t}\n\t}\n\n\tconst matchOn: Chord['matchOn'] = codeTokenPattern.test(token) ? 'code' : 'key';\n\n\tlet resolvedShift: Chord['shift'];\n\tif (matchOn === 'code') {\n\t\tresolvedShift = shift;\n\t} else if ([...token].length === 1) {\n\t\tif (shift) {\n\t\t\tthrow new Error(`Invalid key chord '${input}': 'shift' cannot combine with a single-character token`);\n\t\t}\n\n\t\tresolvedShift = 'implicit';\n\t} else {\n\t\tresolvedShift = shift;\n\t}\n\n\treturn { token: token, matchOn: matchOn, ctrl: ctrl, alt: alt, meta: meta, shift: resolvedShift };\n}\n\n/** Tests whether a key event matches a parsed chord — all declared modifiers must match exactly. */\nexport function matchesChord(chord: Chord, e: KeyEventLike): boolean {\n\tif (chord.ctrl !== e.ctrlKey) return false;\n\tif (chord.alt !== e.altKey) return false;\n\tif (chord.meta !== e.metaKey) return false;\n\n\tif (chord.shift !== 'implicit' && chord.shift !== e.shiftKey) return false;\n\n\treturn chord.matchOn === 'code' ? e.code === chord.token : e.key === chord.token;\n}\n\nexport type ChordSymbols = { ctrl: string; alt: string; shift: string; meta: string };\n\n/** One display chip: a modifier (renderers style these differently) or the chord's own key. */\nexport type ChordPart = { text: string; kind: 'mod' | 'key' };\n\n/**\n * Formats a chord into an ordered list of typed display chips (ctrl → alt → shift → meta → token).\n * An implicit-shift chord contributes no shift chip — its token already spells the shifted form.\n */\nexport function formatChordParts(chord: Chord, symbols: ChordSymbols): ChordPart[] {\n\tconst parts: ChordPart[] = [];\n\n\tif (chord.ctrl) {\n\t\tparts.push({ text: symbols.ctrl, kind: 'mod' });\n\t}\n\n\tif (chord.alt) {\n\t\tparts.push({ text: symbols.alt, kind: 'mod' });\n\t}\n\n\tif (chord.shift === true) {\n\t\tparts.push({ text: symbols.shift, kind: 'mod' });\n\t}\n\n\tif (chord.meta) {\n\t\tparts.push({ text: symbols.meta, kind: 'mod' });\n\t}\n\n\tparts.push({ text: formatToken(chord), kind: 'key' });\n\n\treturn parts;\n}\n\n/** Formats a chord into an ordered list of display chips (ctrl → alt → shift → meta → token). */\nexport function formatChord(chord: Chord, symbols: ChordSymbols): string[] {\n\treturn formatChordParts(chord, symbols).map(part => part.text);\n}\n\nfunction formatToken(chord: Chord): string {\n\tif (chord.matchOn === 'code') return chord.token.replace(/^(?:Key|Digit)/, '');\n\n\treturn readableTokens.get(chord.token) ?? chord.token;\n}\n"],"mappings":";AA6BA,MAAM,mBAAmB;AAEzB,MAAM,iCAAiB,IAAI,IAAoB;CAC9C,CAAC,WAAW,GAAG;CACf,CAAC,aAAa,GAAG;CACjB,CAAC,aAAa,GAAG;CACjB,CAAC,cAAc,GAAG;CAClB,CAAC,UAAU,KAAK;CAChB,CAAC,KAAK,OAAO;CACb,CAAC,UAAU,MAAM;CACjB,CAAC,YAAY,MAAM;AACpB,CAAC;;;;;AAMD,SAAgB,WAAW,OAAe,OAAuB;CAChE,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,sBAAsB,MAAM,eAAe;CAEvE,MAAM,QAAQ,MAAM,MAAM,GAAG;CAI7B,IAAI,MAAM,SAAS,KAAK,MAAM,GAAG,EAAE,MAAM,IACxC,MAAM,IAAI,MAAM,sBAAsB,MAAM,gBAAgB;CAG7D,MAAM,YAAY,MAAM,MAAM,GAAG,EAAE;CACnC,MAAM,QAAQ,MAAM,GAAG,EAAE;CAEzB,IAAI,UAAU,IAAI,MAAM,IAAI,MAAM,sBAAsB,MAAM,eAAe;CAE7E,IAAI,MAAM;CACV,IAAI,OAAO;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,MAAM,SAAS,EAAE,SAAS,OAAO;CAErC,IAAI,MAAM,UAAU,cAAc,MAAM,UAAU,EAAE,UAAU,OAAO;CAErE,OAAO,MAAM,YAAY,SAAS,EAAE,SAAS,MAAM,QAAQ,EAAE,QAAQ,MAAM;AAC5E;;;;;AAWA,SAAgB,iBAAiB,OAAc,SAAoC;CAClF,MAAM,QAAqB,CAAC;CAE5B,IAAI,MAAM,MACT,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAM,MAAM;CAAM,CAAC;CAG/C,IAAI,MAAM,KACT,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAK,MAAM;CAAM,CAAC;CAG9C,IAAI,MAAM,UAAU,MACnB,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAO,MAAM;CAAM,CAAC;CAGhD,IAAI,MAAM,MACT,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAM,MAAM;CAAM,CAAC;CAG/C,MAAM,KAAK;EAAE,MAAM,YAAY,KAAK;EAAG,MAAM;CAAM,CAAC;CAEpD,OAAO;AACR;;AAGA,SAAgB,YAAY,OAAc,SAAiC;CAC1E,OAAO,iBAAiB,OAAO,OAAO,CAAC,CAAC,KAAI,SAAQ,KAAK,IAAI;AAC9D;AAEA,SAAS,YAAY,OAAsB;CAC1C,IAAI,MAAM,YAAY,QAAQ,OAAO,MAAM,MAAM,QAAQ,kBAAkB,EAAE;CAE7E,OAAO,eAAe,IAAI,MAAM,KAAK,KAAK,MAAM;AACjD"}
1
+ {"version":3,"file":"chord.js","names":[],"sources":["../../../../utils/src/keys/chord.ts"],"sourcesContent":["/** Structural subset of a keyboard event; lets this module stay DOM-free. */\nexport type KeyEventLike = {\n\tkey: string;\n\tcode: string;\n\tctrlKey: boolean;\n\taltKey: boolean;\n\tshiftKey: boolean;\n\tmetaKey: boolean;\n};\n\nexport type ChordModifier = 'mod' | 'ctrl' | 'alt' | 'shift' | 'meta';\n\n/** A single parsed key combination, ready to match against key events. */\nexport type Chord = {\n\t/** The canonical token spelling, e.g. `'ArrowUp'`, `'c'`, `'KeyM'`. */\n\ttoken: string;\n\t/** Whether the token is matched against `event.code` (layout-independent) or `event.key`. */\n\tmatchOn: 'key' | 'code';\n\tctrl: boolean;\n\talt: boolean;\n\tmeta: boolean;\n\t/**\n\t * `true`/`false` when shift is a declared part of the chord; `'implicit'` when the token is a\n\t * single printable character whose shifted form already encodes the shift state (e.g. `'?'`),\n\t * so `event.shiftKey` is ignored at match time.\n\t */\n\tshift: boolean | 'implicit';\n};\n\nconst codeTokenPattern = /^(?:Key[A-Z]|Digit[0-9])$/;\nconst keyTokenPattern = /^key([a-z])$/i;\nconst digitTokenPattern = /^digit([0-9])$/i;\n\n/**\n * Thrown by {@link parseChord} for malformed input. `message` is the full diagnostic; `reason` is a\n * short phrase that reads after the quoted input (`'<input>' <reason>`) for user-facing reports.\n */\nexport class ChordParseError extends Error {\n\tconstructor(\n\t\treadonly input: string,\n\t\treadonly reason: string,\n\t\tdetail: string,\n\t) {\n\t\tsuper(`Invalid key chord '${input}': ${detail}`);\n\t\tthis.name = 'ChordParseError';\n\t}\n}\n\n/**\n * Multi-character `KeyboardEvent.key` values a chord token may name (anything else could never match),\n * keyed by lowercased name so lookups are case-insensitive and resolve to the canonical spelling.\n */\nconst namedKeyTokens = new Map<string, string>(\n\t[\n\t\t'ArrowUp',\n\t\t'ArrowDown',\n\t\t'ArrowLeft',\n\t\t'ArrowRight',\n\t\t'Backspace',\n\t\t'BrowserBack',\n\t\t'BrowserForward',\n\t\t'Clear',\n\t\t'ContextMenu',\n\t\t'Delete',\n\t\t'End',\n\t\t'Enter',\n\t\t'Escape',\n\t\t'Help',\n\t\t'Home',\n\t\t'Insert',\n\t\t'PageDown',\n\t\t'PageUp',\n\t\t'Pause',\n\t\t'ScrollLock',\n\t\t'Tab',\n\t\t...Array.from({ length: 24 }, (_, i) => `F${i + 1}`),\n\t].map(name => [name.toLowerCase(), name]),\n);\n\nconst readableTokens = new Map<string, string>([\n\t['ArrowUp', '↑'],\n\t['ArrowDown', '↓'],\n\t['ArrowLeft', '←'],\n\t['ArrowRight', '→'],\n\t['Escape', 'Esc'],\n\t[' ', 'Space'],\n\t['PageUp', 'PgUp'],\n\t['PageDown', 'PgDn'],\n]);\n\n/**\n * Parses a `+`-separated key combination such as `'mod+c'` or `'alt+KeyM'` into a {@link Chord}.\n * Modifier and multi-character key names are case-insensitive (`'Alt+keym'` is `'alt+KeyM'`); a\n * single-character token is matched exactly. Throws on malformed input. `isMac` resolves the `'mod'`\n * modifier (`meta` on mac, `ctrl` otherwise).\n */\nexport function parseChord(input: string, isMac: boolean): Chord {\n\tif (!input) throw new ChordParseError(input, 'is empty', 'empty input');\n\n\tconst parts = input.split('+');\n\n\t// A literal '+' can't be a token: it splits to an empty last part, so a lone '+' and 'ctrl++' are\n\t// both rejected here as a trailing '+'.\n\tif (parts.length > 1 && parts.at(-1) === '') {\n\t\tthrow new ChordParseError(input, \"ends with '+' (a literal '+' can't be bound)\", \"trailing '+'\");\n\t}\n\n\tconst modifiers = parts.slice(0, -1);\n\tconst rawToken = parts.at(-1)!;\n\n\tif (rawToken === '') throw new ChordParseError(input, 'has no key', 'empty token');\n\n\tlet mod = false;\n\tlet ctrl = false;\n\tlet alt = false;\n\tlet shift = false;\n\tlet meta = false;\n\n\tfor (const modifier of modifiers) {\n\t\tswitch (modifier.toLowerCase()) {\n\t\t\tcase 'mod':\n\t\t\t\tif (mod) throw new ChordParseError(input, `repeats the modifier 'mod'`, \"duplicate modifier 'mod'\");\n\n\t\t\t\tmod = true;\n\t\t\t\tbreak;\n\t\t\tcase 'ctrl':\n\t\t\t\tif (ctrl) throw new ChordParseError(input, `repeats the modifier 'ctrl'`, \"duplicate modifier 'ctrl'\");\n\n\t\t\t\tctrl = true;\n\t\t\t\tbreak;\n\t\t\tcase 'alt':\n\t\t\t\tif (alt) throw new ChordParseError(input, `repeats the modifier 'alt'`, \"duplicate modifier 'alt'\");\n\n\t\t\t\talt = true;\n\t\t\t\tbreak;\n\t\t\tcase 'shift':\n\t\t\t\tif (shift) {\n\t\t\t\t\tthrow new ChordParseError(input, `repeats the modifier 'shift'`, \"duplicate modifier 'shift'\");\n\t\t\t\t}\n\n\t\t\t\tshift = true;\n\t\t\t\tbreak;\n\t\t\tcase 'meta':\n\t\t\t\tif (meta) throw new ChordParseError(input, `repeats the modifier 'meta'`, \"duplicate modifier 'meta'\");\n\n\t\t\t\tmeta = true;\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tthrow new ChordParseError(\n\t\t\t\t\tinput,\n\t\t\t\t\t`has an unknown modifier '${modifier}'`,\n\t\t\t\t\t`unknown modifier '${modifier}'`,\n\t\t\t\t);\n\t\t}\n\t}\n\n\tif (mod && ctrl) {\n\t\tthrow new ChordParseError(\n\t\t\tinput,\n\t\t\t\"combines 'mod' with 'ctrl' ('mod' already means Ctrl, or ⌘ on macOS)\",\n\t\t\t\"'mod' conflicts with explicit 'ctrl'\",\n\t\t);\n\t}\n\n\tif (mod && meta) {\n\t\tthrow new ChordParseError(\n\t\t\tinput,\n\t\t\t\"combines 'mod' with 'meta' ('mod' already means Ctrl, or ⌘ on macOS)\",\n\t\t\t\"'mod' conflicts with explicit 'meta'\",\n\t\t);\n\t}\n\n\tif (mod) {\n\t\tif (isMac) {\n\t\t\tmeta = true;\n\t\t} else {\n\t\t\tctrl = true;\n\t\t}\n\t}\n\n\tconst isSingleChar = [...rawToken].length === 1;\n\n\t// Single characters stay case-sensitive (`h` and `H` are distinct bindings); multi-character names are\n\t// resolved to their canonical spelling, since that is what `matchesChord` and the display compare on.\n\tlet token = rawToken;\n\tif (!isSingleChar) {\n\t\tconst keyMatch = keyTokenPattern.exec(rawToken);\n\t\tconst digitMatch = digitTokenPattern.exec(rawToken);\n\t\tif (keyMatch != null) {\n\t\t\ttoken = `Key${keyMatch[1].toUpperCase()}`;\n\t\t} else if (digitMatch != null) {\n\t\t\ttoken = `Digit${digitMatch[1]}`;\n\t\t} else {\n\t\t\tconst named = namedKeyTokens.get(rawToken.toLowerCase());\n\t\t\tif (named == null) {\n\t\t\t\tthrow new ChordParseError(input, `has an unknown key '${rawToken}'`, `unknown key '${rawToken}'`);\n\t\t\t}\n\n\t\t\ttoken = named;\n\t\t}\n\t}\n\n\tconst matchOn: Chord['matchOn'] = codeTokenPattern.test(token) ? 'code' : 'key';\n\n\tlet resolvedShift: Chord['shift'];\n\tif (matchOn === 'code') {\n\t\tresolvedShift = shift;\n\t} else if (isSingleChar) {\n\t\tif (shift) {\n\t\t\tthrow new ChordParseError(\n\t\t\t\tinput,\n\t\t\t\t`combines shift with a single character (use '${rawToken}' alone)`,\n\t\t\t\t\"'shift' cannot combine with a single-character token\",\n\t\t\t);\n\t\t}\n\n\t\tresolvedShift = 'implicit';\n\t} else {\n\t\tresolvedShift = shift;\n\t}\n\n\treturn { token: token, matchOn: matchOn, ctrl: ctrl, alt: alt, meta: meta, shift: resolvedShift };\n}\n\n/** Tests whether a key event matches a parsed chord — all declared modifiers must match exactly. */\nexport function matchesChord(chord: Chord, e: KeyEventLike): boolean {\n\tif (chord.ctrl !== e.ctrlKey) return false;\n\tif (chord.alt !== e.altKey) return false;\n\tif (chord.meta !== e.metaKey) return false;\n\n\tif (chord.shift !== 'implicit' && chord.shift !== e.shiftKey) return false;\n\n\treturn chord.matchOn === 'code' ? e.code === chord.token : e.key === chord.token;\n}\n\nexport type ChordSymbols = { ctrl: string; alt: string; shift: string; meta: string };\n\n/** One display chip: a modifier (renderers style these differently) or the chord's own key. */\nexport type ChordPart = { text: string; kind: 'mod' | 'key' };\n\n/**\n * Formats a chord into an ordered list of typed display chips (ctrl → alt → shift → meta → token).\n * An implicit-shift chord contributes no shift chip — its token already spells the shifted form.\n */\nexport function formatChordParts(chord: Chord, symbols: ChordSymbols): ChordPart[] {\n\tconst parts: ChordPart[] = [];\n\n\tif (chord.ctrl) {\n\t\tparts.push({ text: symbols.ctrl, kind: 'mod' });\n\t}\n\n\tif (chord.alt) {\n\t\tparts.push({ text: symbols.alt, kind: 'mod' });\n\t}\n\n\tif (chord.shift === true) {\n\t\tparts.push({ text: symbols.shift, kind: 'mod' });\n\t}\n\n\tif (chord.meta) {\n\t\tparts.push({ text: symbols.meta, kind: 'mod' });\n\t}\n\n\tparts.push({ text: formatToken(chord), kind: 'key' });\n\n\treturn parts;\n}\n\n/** Formats a chord into an ordered list of display chips (ctrl → alt → shift → meta → token). */\nexport function formatChord(chord: Chord, symbols: ChordSymbols): string[] {\n\treturn formatChordParts(chord, symbols).map(part => part.text);\n}\n\nfunction formatToken(chord: Chord): string {\n\tif (chord.matchOn === 'code') return chord.token.replace(/^(?:Key|Digit)/, '');\n\n\treturn readableTokens.get(chord.token) ?? chord.token;\n}\n"],"mappings":";AA6BA,MAAM,mBAAmB;AACzB,MAAM,kBAAkB;AACxB,MAAM,oBAAoB;;;;;AAM1B,IAAa,kBAAb,cAAqC,MAAM;CAEhC;CACA;CAFV,YACC,OACA,QACA,QACC;EACD,MAAM,sBAAsB,MAAM,KAAK,QAAQ;EAJtC,KAAA,QAAA;EACA,KAAA,SAAA;EAIT,KAAK,OAAO;CACb;AACD;;;;;AAMA,MAAM,iBAAiB,IAAI,IAC1B;CACC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG,MAAM,KAAK,EAAE,QAAQ,GAAG,IAAI,GAAG,MAAM,IAAI,IAAI,GAAG;AACpD,CAAC,CAAC,KAAI,SAAQ,CAAC,KAAK,YAAY,GAAG,IAAI,CAAC,CACzC;AAEA,MAAM,iCAAiB,IAAI,IAAoB;CAC9C,CAAC,WAAW,GAAG;CACf,CAAC,aAAa,GAAG;CACjB,CAAC,aAAa,GAAG;CACjB,CAAC,cAAc,GAAG;CAClB,CAAC,UAAU,KAAK;CAChB,CAAC,KAAK,OAAO;CACb,CAAC,UAAU,MAAM;CACjB,CAAC,YAAY,MAAM;AACpB,CAAC;;;;;;;AAQD,SAAgB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AAM,CAAC;CAG9C,IAAI,MAAM,UAAU,MACnB,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAO,MAAM;CAAM,CAAC;CAGhD,IAAI,MAAM,MACT,MAAM,KAAK;EAAE,MAAM,QAAQ;EAAM,MAAM;CAAM,CAAC;CAG/C,MAAM,KAAK;EAAE,MAAM,YAAY,KAAK;EAAG,MAAM;CAAM,CAAC;CAEpD,OAAO;AACR;;AAGA,SAAgB,YAAY,OAAc,SAAiC;CAC1E,OAAO,iBAAiB,OAAO,OAAO,CAAC,CAAC,KAAI,SAAQ,KAAK,IAAI;AAC9D;AAEA,SAAS,YAAY,OAAsB;CAC1C,IAAI,MAAM,YAAY,QAAQ,OAAO,MAAM,MAAM,QAAQ,kBAAkB,EAAE;CAE7E,OAAO,eAAe,IAAI,MAAM,KAAK,KAAK,MAAM;AACjD"}
@@ -125,5 +125,17 @@ export declare function withShiftTwins(chords: readonly Chord[]): Chord[];
125
125
  * (used for matching) gain the twin.
126
126
  */
127
127
  export declare function registerBinding<TScope extends string, TEvent extends KeyEventLike = KeyEventLike>(descriptor: KeyBindingDescriptor<TScope, TEvent>, isMac: boolean, overrides?: KeyBindingOverrides, onWarn?: (message: string) => void): KeyBinding<TScope, TEvent> | undefined;
128
+ /** One bad entry in a user override map, with a readable reason. */
129
+ export type ShortcutOverrideProblem = {
130
+ id: string;
131
+ problem: string;
132
+ wildcard: boolean;
133
+ };
134
+ /**
135
+ * Validates a raw (freeform, e.g. settings.json) override map the way {@link registerBinding} and
136
+ * {@link resolveOverride} would treat it, returning one problem per ignored entry in key order.
137
+ * An exact id with several bad keys reports only the first, since one bad key rejects the override.
138
+ */
139
+ export declare function getShortcutOverrideProblems(overrides: Readonly<Record<string, unknown>>): ShortcutOverrideProblem[];
128
140
  //#endregion
129
141
  //# sourceMappingURL=keybinding.d.ts.map
@@ -1,4 +1,4 @@
1
- import { matchesChord, parseChord } from "./chord.js";
1
+ import { ChordParseError, matchesChord, parseChord } from "./chord.js";
2
2
  //#region ../utils/src/keys/keybinding.ts
3
3
  /**
4
4
  * Pure candidate selection: which bindings could handle this event, in resolution order —
@@ -150,7 +150,57 @@ function registerBinding(descriptor, isMac, overrides, onWarn) {
150
150
  overridden: false
151
151
  };
152
152
  }
153
+ /**
154
+ * Validates a raw (freeform, e.g. settings.json) override map the way {@link registerBinding} and
155
+ * {@link resolveOverride} would treat it, returning one problem per ignored entry in key order.
156
+ * An exact id with several bad keys reports only the first, since one bad key rejects the override.
157
+ */
158
+ function getShortcutOverrideProblems(overrides) {
159
+ const problems = [];
160
+ for (const [id, value] of Object.entries(overrides)) {
161
+ let keys;
162
+ if (value === false) continue;
163
+ else if (typeof value === "string") keys = [value];
164
+ else if (Array.isArray(value) && value.every((v) => typeof v === "string")) keys = value;
165
+ else {
166
+ problems.push({
167
+ id,
168
+ problem: `expected a key combination, a list of them, or false, but got ${describeValue(value)}`,
169
+ wildcard: isWildcardKey(id)
170
+ });
171
+ continue;
172
+ }
173
+ if (!keys.length) continue;
174
+ if (isWildcardKey(id)) {
175
+ problems.push({
176
+ id,
177
+ problem: "a wildcard can only be false (disable), not a key combination",
178
+ wildcard: true
179
+ });
180
+ continue;
181
+ }
182
+ for (const key of keys) try {
183
+ parseChord(key, false);
184
+ } catch (ex) {
185
+ if (!(ex instanceof ChordParseError)) throw ex;
186
+ problems.push({
187
+ id,
188
+ problem: `'${key}' ${ex.reason}`,
189
+ wildcard: false
190
+ });
191
+ break;
192
+ }
193
+ }
194
+ return problems;
195
+ }
196
+ function isWildcardKey(key) {
197
+ return key === "*" || key.endsWith(".*");
198
+ }
199
+ function describeValue(value) {
200
+ const text = JSON.stringify(value) ?? String(value);
201
+ return text.length > 60 ? `${text.slice(0, 60)}…` : text;
202
+ }
153
203
  //#endregion
154
- export { isShiftClosed, registerBinding, resolveKeydown, resolveOverlayClose, resolveOverride, withShiftTwins };
204
+ export { getShortcutOverrideProblems, isShiftClosed, registerBinding, resolveKeydown, resolveOverlayClose, resolveOverride, withShiftTwins };
155
205
 
156
206
  //# sourceMappingURL=keybinding.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"keybinding.js","names":[],"sources":["../../../../utils/src/keys/keybinding.ts"],"sourcesContent":["import type { Chord, KeyEventLike } from './chord.js';\nimport { matchesChord, parseChord } from './chord.js';\n\n/**\n * One item in a sheet row's key rail or subline, in a mini-grammar the renderer resolves:\n * - a bare chord (`'mod+KeyC'`, `'ArrowUp'`) — parsed and formatted into chips\n * - `'raw:X'` — literal `X` in a key chip\n * - `'mod:X'` — literal `X` in a modifier chip\n * - `'text:X'` — literal `X` as plain inline text, verbatim (leading/trailing spaces included)\n * - `'sep:X'` — literal `X` as a muted separator glyph\n */\nexport type SheetDisplayEntry = string;\n\n/** Whole localized prose with named key-chip groups; never passed to the keybinding parser. */\nexport type SheetDisplayText = {\n\tmessage: string;\n\tkeys: Readonly<Record<string, readonly SheetDisplayEntry[]>>;\n};\n\n/**\n * Another binding this row also presents keys for — typically the `sheet: 'hidden'` partner of a\n * \"previous / next\" pair, so overriding either half's keys still shows up here.\n */\nexport type SheetPartner = {\n\tid: string;\n\t/** Display entries for this partner when it is NOT overridden — defaults to its keys. */\n\tkeys?: readonly SheetDisplayEntry[];\n};\n\nexport type SheetEntry = {\n\tgroup: string;\n\tlabel: string;\n\torder?: number;\n\t/** The visible binding's OWN keys — a partner's keys are never included here, see `with`. */\n\tkeysOverride?: readonly SheetDisplayEntry[];\n\t/** Second line rendered under the label, with optional whole-message localization. */\n\tsubline?: readonly SheetDisplayEntry[];\n\t/** Whole localized subline; takes precedence over legacy display entries. */\n\tsublineText?: SheetDisplayText;\n\twith?: readonly SheetPartner[];\n};\n\nexport type KeyBindingDescriptor<TScope extends string, TEvent extends KeyEventLike = KeyEventLike> = {\n\t/**\n\t * Stable dotted identifier, e.g. `'rows.stepPrevious'` — the key overrides are keyed by this.\n\t * Present only on customizable bindings (those a user could collide with or reasonably want to\n\t * change); user overrides key on it and the sheet shows it. Absent = fixed widget key: never\n\t * overridden, never disabled.\n\t */\n\tid?: string;\n\tkeys: readonly string[];\n\tscope: TScope;\n\torder?: number;\n\twhen?: readonly ((e: TEvent) => boolean)[];\n\t/**\n\t * `chordIndex` is the index into this binding's effective `keys`/`chords` of the chord that\n\t * matched the event — e.g. for `keys: ['Digit1', …, 'Digit0']`, pressing `Digit3` runs with\n\t * `chordIndex === 2`.\n\t */\n\trun: (e: TEvent, chordIndex: number) => boolean;\n\tsheet: SheetEntry | 'hidden';\n};\n\n/** A registered binding: descriptor + parsed chords (parse once at registration). */\nexport type KeyBinding<TScope extends string, TEvent extends KeyEventLike = KeyEventLike> = KeyBindingDescriptor<\n\tTScope,\n\tTEvent\n> & { chords: readonly Chord[]; /** True when the effective keys came from an override. */ overridden: boolean };\n\n/**\n * User overrides keyed by binding id: a replacement key list, or `false` to disable. A key ending in\n * `.*` matches every id with that prefix (e.g. `'panels.*'`); an exact id wins over a wildcard, and a\n * longer wildcard wins over a shorter one. `'*'` matches everything. A wildcard can only disable — a\n * wildcard entry with a non-empty key list is ignored (see {@link resolveOverride}); only an exact id\n * can rebind.\n */\nexport type KeyBindingOverrides = Readonly<Record<string, readonly string[] | false>>;\n\nexport type OverlayEntry = {\n\tid: string;\n\t/**\n\t * Close the surface. Returns false to decline (surface decides it wasn't actually open/closable),\n\t * letting resolution continue to the next overlay down, then the focus chain.\n\t */\n\tonClose: () => boolean;\n};\n\n/**\n * Pure candidate selection: which bindings could handle this event, in resolution order —\n * scope chain innermost→outermost (chain[0] = innermost), `order` ascending within a scope\n * (undefined order sorts last), registration (array) order as the final tiebreak. Does NOT\n * evaluate `when` guards or call `run` — the dispatcher does that so scope guards can sit between.\n */\nexport function resolveKeydown<TScope extends string, TEvent extends KeyEventLike>(\n\tbindings: readonly KeyBinding<TScope, TEvent>[],\n\tscopeChain: readonly TScope[],\n\te: KeyEventLike,\n): KeyBinding<TScope, TEvent>[] {\n\tconst matches: { binding: KeyBinding<TScope, TEvent>; scopeIndex: number; registrationIndex: number }[] = [];\n\n\tfor (let i = 0; i < bindings.length; i++) {\n\t\tconst binding = bindings[i];\n\n\t\tconst scopeIndex = scopeChain.indexOf(binding.scope);\n\t\tif (scopeIndex === -1) continue;\n\n\t\tif (!binding.chords.some(chord => matchesChord(chord, e))) continue;\n\n\t\tmatches.push({ binding: binding, scopeIndex: scopeIndex, registrationIndex: i });\n\t}\n\n\tmatches.sort((a, b) => {\n\t\tif (a.scopeIndex !== b.scopeIndex) return a.scopeIndex - b.scopeIndex;\n\n\t\tconst orderA = a.binding.order;\n\t\tconst orderB = b.binding.order;\n\t\tif (orderA !== orderB) {\n\t\t\tif (orderA == null) return 1;\n\t\t\tif (orderB == null) return -1;\n\n\t\t\treturn orderA - orderB;\n\t\t}\n\n\t\treturn a.registrationIndex - b.registrationIndex;\n\t});\n\n\treturn matches.map(m => m.binding);\n}\n\n/**\n * Pure overlay resolution for a close request (Esc): returns the entries to try, top of stack\n * first. The dispatcher calls onClose top-down until one returns true.\n */\nexport function resolveOverlayClose(stack: readonly OverlayEntry[]): OverlayEntry[] {\n\treturn [...stack].reverse();\n}\n\n/**\n * Resolves what a binding's effective keys should be given an override map: the replacement key\n * list, `false` if disabled, or `undefined` if nothing in `overrides` applies. An exact id match\n * always wins (and may rebind or disable); otherwise the longest matching `'<prefix>.*'` wildcard\n * wins, with bare `'*'` (an empty prefix) matching everything as the fallback — but a wildcard can\n * ONLY disable: a wildcard entry whose value is a non-empty key list is ignored entirely (it never\n * becomes a candidate), falling through to the next matching wildcard, then `undefined`. An override\n * value that is an empty array is treated the same as `false`.\n */\nexport function resolveOverride(\n\tid: string,\n\toverrides: KeyBindingOverrides | undefined,\n): readonly string[] | false | undefined {\n\tif (!overrides) return undefined;\n\n\tif (Object.hasOwn(overrides, id)) return normalizeOverrideValue(overrides[id]);\n\n\tlet bestPrefixLength: number | undefined;\n\tlet bestValue: readonly string[] | false | undefined;\n\n\tfor (const key of Object.keys(overrides)) {\n\t\tlet prefix: string;\n\t\tif (key === '*') {\n\t\t\tprefix = '';\n\t\t} else if (key.endsWith('.*')) {\n\t\t\tprefix = key.slice(0, -2);\n\t\t\tif (!id.startsWith(`${prefix}.`)) continue;\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst raw = overrides[key];\n\t\t// Wildcards can only disable — one with a non-empty key list can't rebind, so it's ignored.\n\t\tif (raw !== false && raw.length > 0) continue;\n\n\t\tif (bestPrefixLength === undefined || prefix.length > bestPrefixLength) {\n\t\t\tbestPrefixLength = prefix.length;\n\t\t\tbestValue = normalizeOverrideValue(raw);\n\t\t}\n\t}\n\n\treturn bestValue;\n}\n\nfunction normalizeOverrideValue(value: readonly string[] | false): readonly string[] | false {\n\treturn value === false || value.length === 0 ? false : value;\n}\n\n/**\n * True when every chord in `chords` that has `shift === false` has a twin elsewhere in the list\n * identical in `token`/`matchOn`/`ctrl`/`alt`/`meta` with `shift === true` — e.g. `['ArrowUp',\n * 'shift+ArrowUp']`. Chords with `shift === 'implicit'` (a single printable-character token, whose\n * shifted form already encodes the shift state) are ignored, both as candidates needing a twin and\n * as candidate twins.\n */\nexport function isShiftClosed(chords: readonly Chord[]): boolean {\n\tfor (const chord of chords) {\n\t\tif (chord.shift !== false) continue;\n\n\t\tconst hasTwin = chords.some(\n\t\t\tother =>\n\t\t\t\tother !== chord &&\n\t\t\t\tother.shift === true &&\n\t\t\t\tother.token === chord.token &&\n\t\t\t\tother.matchOn === chord.matchOn &&\n\t\t\t\tother.ctrl === chord.ctrl &&\n\t\t\t\tother.alt === chord.alt &&\n\t\t\t\tother.meta === chord.meta,\n\t\t);\n\t\tif (!hasTwin) return false;\n\t}\n\n\treturn true;\n}\n\n/** Appends a `shift: true` twin right after every `shift: false` chord in `chords`; chords with\n * `shift === true` or `'implicit'` pass through unchanged with no twin added. */\nexport function withShiftTwins(chords: readonly Chord[]): Chord[] {\n\tconst result: Chord[] = [];\n\tfor (const chord of chords) {\n\t\tresult.push(chord);\n\t\tif (chord.shift === false) {\n\t\t\tresult.push({ ...chord, shift: true });\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/** Parses a list of keys into chords, throwing on the first malformed key. */\nfunction parseKeys(keys: readonly string[], errorContext: string, isMac: boolean): Chord[] {\n\tconst chords: Chord[] = [];\n\n\tfor (const key of keys) {\n\t\ttry {\n\t\t\tchords.push(parseChord(key, isMac));\n\t\t} catch (ex) {\n\t\t\tconst reason = ex instanceof Error ? ex.message : String(ex);\n\t\t\tthrow new Error(`${errorContext}, key '${key}': ${reason}`, { cause: ex });\n\t\t}\n\t}\n\n\treturn chords;\n}\n\n/**\n * Parses a descriptor's keys into chords, applying `overrides` (keyed by {@link KeyBindingDescriptor.id})\n * first. A binding with no `id` is fixed — it never consults `overrides` at all, so it can't be\n * rebound or disabled (not even by a `'*'` wildcard). A disabled binding (`false`) is never\n * registered — this returns `undefined` and the caller skips it. A malformed replacement chord is\n * reported to `onWarn` (naming the id and the bad key) and the descriptor's default keys are used\n * instead. Malformed default keys still throw, as before.\n *\n * When an override applies and the descriptor's DEFAULT chords are \"Shift-closed\" (see\n * {@link isShiftClosed}) — e.g. `['ArrowUp', 'shift+ArrowUp']`, where Shift extends the selection\n * along the same axis — every `shift: false` chord in the override gets a `shift: true` twin added\n * to the parsed chords (see {@link withShiftTwins}), so rebinding the plain key preserves the\n * Shift-extend variant. The displayed `keys` stay exactly what the user specified; only `chords`\n * (used for matching) gain the twin.\n */\nexport function registerBinding<TScope extends string, TEvent extends KeyEventLike = KeyEventLike>(\n\tdescriptor: KeyBindingDescriptor<TScope, TEvent>,\n\tisMac: boolean,\n\toverrides?: KeyBindingOverrides,\n\tonWarn?: (message: string) => void,\n): KeyBinding<TScope, TEvent> | undefined {\n\t// Defaults are parsed first so malformed defaults still throw as before, and so an override can\n\t// inherit their Shift-closure.\n\tconst defaultChords = parseKeys(descriptor.keys, `Invalid key binding for scope '${descriptor.scope}'`, isMac);\n\n\tif (descriptor.id != null) {\n\t\tconst resolved = resolveOverride(descriptor.id, overrides);\n\n\t\tif (resolved === false) return undefined;\n\n\t\tif (resolved !== undefined) {\n\t\t\ttry {\n\t\t\t\tlet chords = parseKeys(resolved, `Invalid key override for id '${descriptor.id}'`, isMac);\n\t\t\t\tif (isShiftClosed(defaultChords)) {\n\t\t\t\t\tchords = withShiftTwins(chords);\n\t\t\t\t}\n\n\t\t\t\treturn { ...descriptor, keys: resolved, chords: chords, overridden: true };\n\t\t\t} catch (ex) {\n\t\t\t\tconst reason = ex instanceof Error ? ex.message : String(ex);\n\t\t\t\tonWarn?.(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ...descriptor, chords: defaultChords, overridden: false };\n}\n"],"mappings":";;;;;;;;AA6FA,SAAgB,eACf,UACA,YACA,GAC+B;CAC/B,MAAM,UAAoG,CAAC;CAE3G,KAAK,IAAI,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;EACzC,MAAM,UAAU,SAAS;EAEzB,MAAM,aAAa,WAAW,QAAQ,QAAQ,KAAK;EACnD,IAAI,eAAe,IAAI;EAEvB,IAAI,CAAC,QAAQ,OAAO,MAAK,UAAS,aAAa,OAAO,CAAC,CAAC,GAAG;EAE3D,QAAQ,KAAK;GAAW;GAAqB;GAAY,mBAAmB;EAAE,CAAC;CAChF;CAEA,QAAQ,MAAM,GAAG,MAAM;EACtB,IAAI,EAAE,eAAe,EAAE,YAAY,OAAO,EAAE,aAAa,EAAE;EAE3D,MAAM,SAAS,EAAE,QAAQ;EACzB,MAAM,SAAS,EAAE,QAAQ;EACzB,IAAI,WAAW,QAAQ;GACtB,IAAI,UAAU,MAAM,OAAO;GAC3B,IAAI,UAAU,MAAM,OAAO;GAE3B,OAAO,SAAS;EACjB;EAEA,OAAO,EAAE,oBAAoB,EAAE;CAChC,CAAC;CAED,OAAO,QAAQ,KAAI,MAAK,EAAE,OAAO;AAClC;;;;;AAMA,SAAgB,oBAAoB,OAAgD;CACnF,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,QAAQ;AAC3B;;;;;;;;;;AAWA,SAAgB,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AC1F,MAAM,SAAkB,CAAC;CAEzB,KAAK,MAAM,OAAO,MACjB,IAAI;EACH,OAAO,KAAK,WAAW,KAAK,KAAK,CAAC;CACnC,SAAS,IAAI;EACZ,MAAM,SAAS,cAAc,QAAQ,GAAG,UAAU,OAAO,EAAE;EAC3D,MAAM,IAAI,MAAM,GAAG,aAAa,SAAS,IAAI,KAAK,UAAU,EAAE,OAAO,GAAG,CAAC;CAC1E;CAGD,OAAO;AACR;;;;;;;;;;;;;;;;AAiBA,SAAgB,gBACf,YACA,OACA,WACA,QACyC;CAGzC,MAAM,gBAAgB,UAAU,WAAW,MAAM,kCAAkC,WAAW,MAAM,IAAI,KAAK;CAE7G,IAAI,WAAW,MAAM,MAAM;EAC1B,MAAM,WAAW,gBAAgB,WAAW,IAAI,SAAS;EAEzD,IAAI,aAAa,OAAO,OAAO,KAAA;EAE/B,IAAI,aAAa,KAAA,GAChB,IAAI;GACH,IAAI,SAAS,UAAU,UAAU,gCAAgC,WAAW,GAAG,IAAI,KAAK;GACxF,IAAI,cAAc,aAAa,GAC9B,SAAS,eAAe,MAAM;GAG/B,OAAO;IAAE,GAAG;IAAY,MAAM;IAAkB;IAAQ,YAAY;GAAK;EAC1E,SAAS,IAAI;GACZ,MAAM,SAAS,cAAc,QAAQ,GAAG,UAAU,OAAO,EAAE;GAC3D,SAAS,MAAM;EAChB;CAEF;CAEA,OAAO;EAAE,GAAG;EAAY,QAAQ;EAAe,YAAY;CAAM;AAClE"}
1
+ {"version":3,"file":"keybinding.js","names":[],"sources":["../../../../utils/src/keys/keybinding.ts"],"sourcesContent":["import type { Chord, KeyEventLike } from './chord.js';\nimport { ChordParseError, matchesChord, parseChord } from './chord.js';\n\n/**\n * One item in a sheet row's key rail or subline, in a mini-grammar the renderer resolves:\n * - a bare chord (`'mod+KeyC'`, `'ArrowUp'`) — parsed and formatted into chips\n * - `'raw:X'` — literal `X` in a key chip\n * - `'mod:X'` — literal `X` in a modifier chip\n * - `'text:X'` — literal `X` as plain inline text, verbatim (leading/trailing spaces included)\n * - `'sep:X'` — literal `X` as a muted separator glyph\n */\nexport type SheetDisplayEntry = string;\n\n/** Whole localized prose with named key-chip groups; never passed to the keybinding parser. */\nexport type SheetDisplayText = {\n\tmessage: string;\n\tkeys: Readonly<Record<string, readonly SheetDisplayEntry[]>>;\n};\n\n/**\n * Another binding this row also presents keys for — typically the `sheet: 'hidden'` partner of a\n * \"previous / next\" pair, so overriding either half's keys still shows up here.\n */\nexport type SheetPartner = {\n\tid: string;\n\t/** Display entries for this partner when it is NOT overridden — defaults to its keys. */\n\tkeys?: readonly SheetDisplayEntry[];\n};\n\nexport type SheetEntry = {\n\tgroup: string;\n\tlabel: string;\n\torder?: number;\n\t/** The visible binding's OWN keys — a partner's keys are never included here, see `with`. */\n\tkeysOverride?: readonly SheetDisplayEntry[];\n\t/** Second line rendered under the label, with optional whole-message localization. */\n\tsubline?: readonly SheetDisplayEntry[];\n\t/** Whole localized subline; takes precedence over legacy display entries. */\n\tsublineText?: SheetDisplayText;\n\twith?: readonly SheetPartner[];\n};\n\nexport type KeyBindingDescriptor<TScope extends string, TEvent extends KeyEventLike = KeyEventLike> = {\n\t/**\n\t * Stable dotted identifier, e.g. `'rows.stepPrevious'` — the key overrides are keyed by this.\n\t * Present only on customizable bindings (those a user could collide with or reasonably want to\n\t * change); user overrides key on it and the sheet shows it. Absent = fixed widget key: never\n\t * overridden, never disabled.\n\t */\n\tid?: string;\n\tkeys: readonly string[];\n\tscope: TScope;\n\torder?: number;\n\twhen?: readonly ((e: TEvent) => boolean)[];\n\t/**\n\t * `chordIndex` is the index into this binding's effective `keys`/`chords` of the chord that\n\t * matched the event — e.g. for `keys: ['Digit1', …, 'Digit0']`, pressing `Digit3` runs with\n\t * `chordIndex === 2`.\n\t */\n\trun: (e: TEvent, chordIndex: number) => boolean;\n\tsheet: SheetEntry | 'hidden';\n};\n\n/** A registered binding: descriptor + parsed chords (parse once at registration). */\nexport type KeyBinding<TScope extends string, TEvent extends KeyEventLike = KeyEventLike> = KeyBindingDescriptor<\n\tTScope,\n\tTEvent\n> & { chords: readonly Chord[]; /** True when the effective keys came from an override. */ overridden: boolean };\n\n/**\n * User overrides keyed by binding id: a replacement key list, or `false` to disable. A key ending in\n * `.*` matches every id with that prefix (e.g. `'panels.*'`); an exact id wins over a wildcard, and a\n * longer wildcard wins over a shorter one. `'*'` matches everything. A wildcard can only disable — a\n * wildcard entry with a non-empty key list is ignored (see {@link resolveOverride}); only an exact id\n * can rebind.\n */\nexport type KeyBindingOverrides = Readonly<Record<string, readonly string[] | false>>;\n\nexport type OverlayEntry = {\n\tid: string;\n\t/**\n\t * Close the surface. Returns false to decline (surface decides it wasn't actually open/closable),\n\t * letting resolution continue to the next overlay down, then the focus chain.\n\t */\n\tonClose: () => boolean;\n};\n\n/**\n * Pure candidate selection: which bindings could handle this event, in resolution order —\n * scope chain innermost→outermost (chain[0] = innermost), `order` ascending within a scope\n * (undefined order sorts last), registration (array) order as the final tiebreak. Does NOT\n * evaluate `when` guards or call `run` — the dispatcher does that so scope guards can sit between.\n */\nexport function resolveKeydown<TScope extends string, TEvent extends KeyEventLike>(\n\tbindings: readonly KeyBinding<TScope, TEvent>[],\n\tscopeChain: readonly TScope[],\n\te: KeyEventLike,\n): KeyBinding<TScope, TEvent>[] {\n\tconst matches: { binding: KeyBinding<TScope, TEvent>; scopeIndex: number; registrationIndex: number }[] = [];\n\n\tfor (let i = 0; i < bindings.length; i++) {\n\t\tconst binding = bindings[i];\n\n\t\tconst scopeIndex = scopeChain.indexOf(binding.scope);\n\t\tif (scopeIndex === -1) continue;\n\n\t\tif (!binding.chords.some(chord => matchesChord(chord, e))) continue;\n\n\t\tmatches.push({ binding: binding, scopeIndex: scopeIndex, registrationIndex: i });\n\t}\n\n\tmatches.sort((a, b) => {\n\t\tif (a.scopeIndex !== b.scopeIndex) return a.scopeIndex - b.scopeIndex;\n\n\t\tconst orderA = a.binding.order;\n\t\tconst orderB = b.binding.order;\n\t\tif (orderA !== orderB) {\n\t\t\tif (orderA == null) return 1;\n\t\t\tif (orderB == null) return -1;\n\n\t\t\treturn orderA - orderB;\n\t\t}\n\n\t\treturn a.registrationIndex - b.registrationIndex;\n\t});\n\n\treturn matches.map(m => m.binding);\n}\n\n/**\n * Pure overlay resolution for a close request (Esc): returns the entries to try, top of stack\n * first. The dispatcher calls onClose top-down until one returns true.\n */\nexport function resolveOverlayClose(stack: readonly OverlayEntry[]): OverlayEntry[] {\n\treturn [...stack].reverse();\n}\n\n/**\n * Resolves what a binding's effective keys should be given an override map: the replacement key\n * list, `false` if disabled, or `undefined` if nothing in `overrides` applies. An exact id match\n * always wins (and may rebind or disable); otherwise the longest matching `'<prefix>.*'` wildcard\n * wins, with bare `'*'` (an empty prefix) matching everything as the fallback — but a wildcard can\n * ONLY disable: a wildcard entry whose value is a non-empty key list is ignored entirely (it never\n * becomes a candidate), falling through to the next matching wildcard, then `undefined`. An override\n * value that is an empty array is treated the same as `false`.\n */\nexport function resolveOverride(\n\tid: string,\n\toverrides: KeyBindingOverrides | undefined,\n): readonly string[] | false | undefined {\n\tif (!overrides) return undefined;\n\n\tif (Object.hasOwn(overrides, id)) return normalizeOverrideValue(overrides[id]);\n\n\tlet bestPrefixLength: number | undefined;\n\tlet bestValue: readonly string[] | false | undefined;\n\n\tfor (const key of Object.keys(overrides)) {\n\t\tlet prefix: string;\n\t\tif (key === '*') {\n\t\t\tprefix = '';\n\t\t} else if (key.endsWith('.*')) {\n\t\t\tprefix = key.slice(0, -2);\n\t\t\tif (!id.startsWith(`${prefix}.`)) continue;\n\t\t} else {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst raw = overrides[key];\n\t\t// Wildcards can only disable — one with a non-empty key list can't rebind, so it's ignored.\n\t\tif (raw !== false && raw.length > 0) continue;\n\n\t\tif (bestPrefixLength === undefined || prefix.length > bestPrefixLength) {\n\t\t\tbestPrefixLength = prefix.length;\n\t\t\tbestValue = normalizeOverrideValue(raw);\n\t\t}\n\t}\n\n\treturn bestValue;\n}\n\nfunction normalizeOverrideValue(value: readonly string[] | false): readonly string[] | false {\n\treturn value === false || value.length === 0 ? false : value;\n}\n\n/**\n * True when every chord in `chords` that has `shift === false` has a twin elsewhere in the list\n * identical in `token`/`matchOn`/`ctrl`/`alt`/`meta` with `shift === true` — e.g. `['ArrowUp',\n * 'shift+ArrowUp']`. Chords with `shift === 'implicit'` (a single printable-character token, whose\n * shifted form already encodes the shift state) are ignored, both as candidates needing a twin and\n * as candidate twins.\n */\nexport function isShiftClosed(chords: readonly Chord[]): boolean {\n\tfor (const chord of chords) {\n\t\tif (chord.shift !== false) continue;\n\n\t\tconst hasTwin = chords.some(\n\t\t\tother =>\n\t\t\t\tother !== chord &&\n\t\t\t\tother.shift === true &&\n\t\t\t\tother.token === chord.token &&\n\t\t\t\tother.matchOn === chord.matchOn &&\n\t\t\t\tother.ctrl === chord.ctrl &&\n\t\t\t\tother.alt === chord.alt &&\n\t\t\t\tother.meta === chord.meta,\n\t\t);\n\t\tif (!hasTwin) return false;\n\t}\n\n\treturn true;\n}\n\n/** Appends a `shift: true` twin right after every `shift: false` chord in `chords`; chords with\n * `shift === true` or `'implicit'` pass through unchanged with no twin added. */\nexport function withShiftTwins(chords: readonly Chord[]): Chord[] {\n\tconst result: Chord[] = [];\n\tfor (const chord of chords) {\n\t\tresult.push(chord);\n\t\tif (chord.shift === false) {\n\t\t\tresult.push({ ...chord, shift: true });\n\t\t}\n\t}\n\n\treturn result;\n}\n\n/** Parses a list of keys into chords, throwing on the first malformed key. */\nfunction parseKeys(keys: readonly string[], errorContext: string, isMac: boolean): Chord[] {\n\tconst chords: Chord[] = [];\n\n\tfor (const key of keys) {\n\t\ttry {\n\t\t\tchords.push(parseChord(key, isMac));\n\t\t} catch (ex) {\n\t\t\tconst reason = ex instanceof Error ? ex.message : String(ex);\n\t\t\tthrow new Error(`${errorContext}, key '${key}': ${reason}`, { cause: ex });\n\t\t}\n\t}\n\n\treturn chords;\n}\n\n/**\n * Parses a descriptor's keys into chords, applying `overrides` (keyed by {@link KeyBindingDescriptor.id})\n * first. A binding with no `id` is fixed — it never consults `overrides` at all, so it can't be\n * rebound or disabled (not even by a `'*'` wildcard). A disabled binding (`false`) is never\n * registered — this returns `undefined` and the caller skips it. A malformed replacement chord is\n * reported to `onWarn` (naming the id and the bad key) and the descriptor's default keys are used\n * instead. Malformed default keys still throw, as before.\n *\n * When an override applies and the descriptor's DEFAULT chords are \"Shift-closed\" (see\n * {@link isShiftClosed}) — e.g. `['ArrowUp', 'shift+ArrowUp']`, where Shift extends the selection\n * along the same axis — every `shift: false` chord in the override gets a `shift: true` twin added\n * to the parsed chords (see {@link withShiftTwins}), so rebinding the plain key preserves the\n * Shift-extend variant. The displayed `keys` stay exactly what the user specified; only `chords`\n * (used for matching) gain the twin.\n */\nexport function registerBinding<TScope extends string, TEvent extends KeyEventLike = KeyEventLike>(\n\tdescriptor: KeyBindingDescriptor<TScope, TEvent>,\n\tisMac: boolean,\n\toverrides?: KeyBindingOverrides,\n\tonWarn?: (message: string) => void,\n): KeyBinding<TScope, TEvent> | undefined {\n\t// Defaults are parsed first so malformed defaults still throw as before, and so an override can\n\t// inherit their Shift-closure.\n\tconst defaultChords = parseKeys(descriptor.keys, `Invalid key binding for scope '${descriptor.scope}'`, isMac);\n\n\tif (descriptor.id != null) {\n\t\tconst resolved = resolveOverride(descriptor.id, overrides);\n\n\t\tif (resolved === false) return undefined;\n\n\t\tif (resolved !== undefined) {\n\t\t\ttry {\n\t\t\t\tlet chords = parseKeys(resolved, `Invalid key override for id '${descriptor.id}'`, isMac);\n\t\t\t\tif (isShiftClosed(defaultChords)) {\n\t\t\t\t\tchords = withShiftTwins(chords);\n\t\t\t\t}\n\n\t\t\t\treturn { ...descriptor, keys: resolved, chords: chords, overridden: true };\n\t\t\t} catch (ex) {\n\t\t\t\tconst reason = ex instanceof Error ? ex.message : String(ex);\n\t\t\t\tonWarn?.(reason);\n\t\t\t}\n\t\t}\n\t}\n\n\treturn { ...descriptor, chords: defaultChords, overridden: false };\n}\n\n/** One bad entry in a user override map, with a readable reason. */\nexport type ShortcutOverrideProblem = { id: string; problem: string; wildcard: boolean };\n\n/**\n * Validates a raw (freeform, e.g. settings.json) override map the way {@link registerBinding} and\n * {@link resolveOverride} would treat it, returning one problem per ignored entry in key order.\n * An exact id with several bad keys reports only the first, since one bad key rejects the override.\n */\nexport function getShortcutOverrideProblems(overrides: Readonly<Record<string, unknown>>): ShortcutOverrideProblem[] {\n\tconst problems: ShortcutOverrideProblem[] = [];\n\n\tfor (const [id, value] of Object.entries(overrides)) {\n\t\tlet keys: readonly string[];\n\t\tif (value === false) {\n\t\t\tcontinue;\n\t\t} else if (typeof value === 'string') {\n\t\t\tkeys = [value];\n\t\t} else if (Array.isArray(value) && value.every(v => typeof v === 'string')) {\n\t\t\tkeys = value;\n\t\t} else {\n\t\t\tproblems.push({\n\t\t\t\tid: id,\n\t\t\t\tproblem: `expected a key combination, a list of them, or false, but got ${describeValue(value)}`,\n\t\t\t\twildcard: isWildcardKey(id),\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (!keys.length) continue;\n\n\t\tif (isWildcardKey(id)) {\n\t\t\tproblems.push({\n\t\t\t\tid: id,\n\t\t\t\tproblem: 'a wildcard can only be false (disable), not a key combination',\n\t\t\t\twildcard: true,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor (const key of keys) {\n\t\t\ttry {\n\t\t\t\t// `isMac` only resolves `mod`; it never changes whether a chord is valid\n\t\t\t\tparseChord(key, false);\n\t\t\t} catch (ex) {\n\t\t\t\tif (!(ex instanceof ChordParseError)) throw ex;\n\n\t\t\t\tproblems.push({ id: id, problem: `'${key}' ${ex.reason}`, wildcard: false });\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn problems;\n}\n\nfunction isWildcardKey(key: string): boolean {\n\treturn key === '*' || key.endsWith('.*');\n}\n\nfunction describeValue(value: unknown): string {\n\tconst json = JSON.stringify(value)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AkB,MAAM;GAE5C,SAAS,KAAK;IAAM;IAAI,SAAS,IAAI,IAAI,IAAI,GAAG;IAAU,UAAU;GAAM,CAAC;GAC3E;EACD;CAEF;CAEA,OAAO;AACR;AAEA,SAAS,cAAc,KAAsB;CAC5C,OAAO,QAAQ,OAAO,IAAI,SAAS,IAAI;AACxC;AAEA,SAAS,cAAc,OAAwB;CAE9C,MAAM,OADO,KAAK,UAAU,KACZ,KAAK,OAAO,KAAK;CAEjC,OAAO,KAAK,SAAS,KAAK,GAAG,KAAK,MAAM,GAAG,EAAE,EAAE,KAAK;AACrD"}
@@ -6,6 +6,27 @@ export declare function escapeMarkdown(s: string, options?: {
6
6
  }): string;
7
7
  /** escapes markdown code blocks */
8
8
  export declare function escapeMarkdownCodeBlocks(s: string): string;
9
+ /**
10
+ * Restricts links in externally-sourced Markdown text (e.g. commit messages) to web and mail destinations
11
+ * (`http:`, `https:`, `mailto:`), leaving the visible text unchanged.
12
+ *
13
+ * Inline links (`[text](dest)`) and reference definitions (`[ref]: dest`) whose destination isn't a literal
14
+ * http(s)/mailto URL are broken by inserting a zero-width space between the `]` and the `(`/`:` (CommonMark
15
+ * requires them to be adjacent). Destinations that are obfuscated in any way (entity-encoded, escaped,
16
+ * angle-bracketed) fail closed.
17
+ *
18
+ * Expects text that has already been HTML-encoded (see `encodeHtmlWeak`), which neutralizes raw HTML and
19
+ * `<scheme:...>` autolinks, and must run before any trusted links are added to the text. Idempotent.
20
+ */
21
+ export declare function defuseMarkdownLinks(s: string): string;
22
+ /** Escapes text for use inside a Markdown link title (`[text](url "title")`) */
23
+ export declare function escapeMarkdownLinkTitle(s: string): string;
24
+ /**
25
+ * Returns `url` ready to use as a Markdown link destination when it's a web (http/https) URL, otherwise `undefined`
26
+ * so the caller renders its text unlinked. Characters that could end or escape the destination are percent-encoded;
27
+ * the rest is left as is.
28
+ */
29
+ export declare function getMarkdownWebLinkDestination(url: string | undefined): string | undefined;
9
30
  export declare function unescapeMarkdown(s: string): string;
10
31
  //#endregion
11
32
  //# sourceMappingURL=markdown.d.ts.map
@@ -55,10 +55,42 @@ function escapeMarkdownCodeBlocks(s) {
55
55
  if (quotesOpened) result += allowed ? tripleBackticks + buffer : escapedTripleBackticks + buffer;
56
56
  return result;
57
57
  }
58
+ const defuseMarkdownLinksRegex = /\]([(:])(?![ \t\r\n]*(?:https?:\/\/|mailto:))/gi;
59
+ /**
60
+ * Restricts links in externally-sourced Markdown text (e.g. commit messages) to web and mail destinations
61
+ * (`http:`, `https:`, `mailto:`), leaving the visible text unchanged.
62
+ *
63
+ * Inline links (`[text](dest)`) and reference definitions (`[ref]: dest`) whose destination isn't a literal
64
+ * http(s)/mailto URL are broken by inserting a zero-width space between the `]` and the `(`/`:` (CommonMark
65
+ * requires them to be adjacent). Destinations that are obfuscated in any way (entity-encoded, escaped,
66
+ * angle-bracketed) fail closed.
67
+ *
68
+ * Expects text that has already been HTML-encoded (see `encodeHtmlWeak`), which neutralizes raw HTML and
69
+ * `<scheme:...>` autolinks, and must run before any trusted links are added to the text. Idempotent.
70
+ */
71
+ function defuseMarkdownLinks(s) {
72
+ if (!s.includes("]")) return s;
73
+ return s.replace(defuseMarkdownLinksRegex, "]​$1");
74
+ }
75
+ /** Escapes text for use inside a Markdown link title (`[text](url "title")`) */
76
+ function escapeMarkdownLinkTitle(s) {
77
+ return s.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
78
+ }
79
+ const webUrlRegex = /^https?:\/\//i;
80
+ const markdownLinkDestinationUnsafeRegex = /[\s()<>"\\]/g;
81
+ /**
82
+ * Returns `url` ready to use as a Markdown link destination when it's a web (http/https) URL, otherwise `undefined`
83
+ * so the caller renders its text unlinked. Characters that could end or escape the destination are percent-encoded;
84
+ * the rest is left as is.
85
+ */
86
+ function getMarkdownWebLinkDestination(url) {
87
+ if (!url || !webUrlRegex.test(url)) return void 0;
88
+ return url.replace(markdownLinkDestinationUnsafeRegex, (c) => c === "(" ? "%28" : c === ")" ? "%29" : encodeURIComponent(c));
89
+ }
58
90
  function unescapeMarkdown(s) {
59
91
  return s.replace(unescapeMarkdownRegex, "$1").replace(unescapeMarkdownHeaderRegex, "===");
60
92
  }
61
93
  //#endregion
62
- export { escapeMarkdown, escapeMarkdownCodeBlocks, unescapeMarkdown };
94
+ export { defuseMarkdownLinks, escapeMarkdown, escapeMarkdownCodeBlocks, escapeMarkdownLinkTitle, getMarkdownWebLinkDestination, unescapeMarkdown };
63
95
 
64
96
  //# sourceMappingURL=markdown.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"markdown.js","names":[],"sources":["../../../utils/src/markdown.ts"],"sourcesContent":["const escapeMarkdownRegex = /[\\\\*_{}[\\]()#+\\-.!<>]/g;\nconst unescapeMarkdownRegex = /\\\\([\\\\`*_{}[\\]()#+\\-.!<>])/g;\n// Regex to find markdown links: [text](url) allowing for escaped brackets/parens within text/url\nconst markdownLinkRegex = /(\\[((?:\\\\.|[^[\\]\\\\])+)\\]\\(((?:\\\\.|[^()\\\\])+)\\))/g;\n\nconst escapeMarkdownHeaderRegex = /^===/gm;\nconst unescapeMarkdownHeaderRegex = /^\\u200b===/gm;\n\n// const sampleMarkdown = '## message `not code` *not important* _no underline_ \\n> don\\'t quote me \\n- don\\'t list me \\n+ don\\'t list me \\n1. don\\'t list me \\nnot h1 \\n=== \\nnot h2 \\n---\\n***\\n---\\n___';\nconst markdownQuotedRegex = /\\r?\\n/g;\nconst markdownBacktickRegex = /`/g;\n\nexport function escapeMarkdown(\n\ts: string,\n\toptions?: { quoted?: boolean; inlineBackticks?: boolean; preserveLinks?: boolean },\n): string {\n\t// If preserving links, replace them with placeholders first\n\tif (options?.preserveLinks) {\n\t\tconst links = new Map<string, string>();\n\t\tlet linkIndex = 0;\n\n\t\ts = s.replace(markdownLinkRegex, match => {\n\t\t\t// Create a unique, unlikely-to-occur placeholder\n\t\t\tconst placeholder = `$$$GLLINK${linkIndex++}GLLINK$$$`;\n\t\t\tlinks.set(placeholder, match);\n\t\t\treturn placeholder;\n\t\t});\n\n\t\t// Escape markdown characters\n\t\ts = s.replace(escapeMarkdownRegex, '\\\\$&');\n\n\t\t// Restore the original links if they were preserved\n\t\tif (options?.preserveLinks && links.size) {\n\t\t\tfor (const [placeholder, originalLink] of links) {\n\t\t\t\ts = s.replace(placeholder, originalLink);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Escape markdown characters\n\t\ts = s.replace(escapeMarkdownRegex, '\\\\$&');\n\t}\n\n\t// Escape markdown header (since the above regex won't match it)\n\ts = s.replace(escapeMarkdownHeaderRegex, '\\u200b===');\n\n\tif (options?.inlineBackticks) {\n\t\ts = escapeMarkdownCodeBlocks(s);\n\t} else {\n\t\ts = s.replace(markdownBacktickRegex, '\\\\$&');\n\t}\n\n\tif (!options?.quoted) return s;\n\n\t// Keep under the same block-quote but with line breaks\n\treturn s.trim().replace(markdownQuotedRegex, '\\t\\\\\\n> ');\n}\n\n/** escapes markdown code blocks */\nexport function escapeMarkdownCodeBlocks(s: string): string {\n\tconst tripleBackticks = '```';\n\tconst escapedTripleBackticks = '\\\\`\\\\`\\\\`';\n\n\tlet result = '';\n\tlet allowed = true;\n\tlet quotesOpened = false;\n\tlet buffer = '';\n\n\tfor (let i = 0; i < s.length; i += 1) {\n\t\tconst char = s[i];\n\t\tconst chain = s.substring(i, i + 3);\n\t\tif (char === '\\n' && quotesOpened) {\n\t\t\tallowed = false;\n\t\t}\n\t\tif (chain === tripleBackticks) {\n\t\t\tif (quotesOpened) {\n\t\t\t\tquotesOpened = false;\n\t\t\t\tif (allowed) {\n\t\t\t\t\tresult += `${tripleBackticks}${buffer}${tripleBackticks}`;\n\t\t\t\t} else {\n\t\t\t\t\tresult += `${escapedTripleBackticks}${buffer}${escapedTripleBackticks}`;\n\t\t\t\t\tallowed = true;\n\t\t\t\t}\n\t\t\t\tbuffer = '';\n\t\t\t} else {\n\t\t\t\tquotesOpened = true;\n\t\t\t}\n\t\t\t// skip chain\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (quotesOpened) {\n\t\t\tbuffer += char;\n\t\t} else {\n\t\t\tresult += char;\n\t\t}\n\t}\n\n\tif (quotesOpened) {\n\t\t// Handle unclosed code block\n\t\tresult += allowed ? tripleBackticks + buffer : escapedTripleBackticks + buffer;\n\t}\n\n\treturn result;\n}\n\nexport function unescapeMarkdown(s: string): string {\n\treturn (\n\t\ts\n\t\t\t// Unescape markdown\n\t\t\t.replace(unescapeMarkdownRegex, '$1')\n\t\t\t// Unescape markdown header\n\t\t\t.replace(unescapeMarkdownHeaderRegex, '===')\n\t);\n}\n"],"mappings":";AAAA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAE9B,MAAM,oBAAoB;AAE1B,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AAGpC,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAE9B,SAAgB,eACf,GACA,SACS;CAET,IAAI,SAAS,eAAe;EAC3B,MAAM,wBAAQ,IAAI,IAAoB;EACtC,IAAI,YAAY;EAEhB,IAAI,EAAE,QAAQ,oBAAmB,UAAS;GAEzC,MAAM,cAAc,YAAY,YAAY;GAC5C,MAAM,IAAI,aAAa,KAAK;GAC5B,OAAO;EACR,CAAC;EAGD,IAAI,EAAE,QAAQ,qBAAqB,MAAM;EAGzC,IAAI,SAAS,iBAAiB,MAAM,MACnC,KAAK,MAAM,CAAC,aAAa,iBAAiB,OACzC,IAAI,EAAE,QAAQ,aAAa,YAAY;CAG1C,OAEC,IAAI,EAAE,QAAQ,qBAAqB,MAAM;CAI1C,IAAI,EAAE,QAAQ,2BAA2B,MAAW;CAEpD,IAAI,SAAS,iBACZ,IAAI,yBAAyB,CAAC;MAE9B,IAAI,EAAE,QAAQ,uBAAuB,MAAM;CAG5C,IAAI,CAAC,SAAS,QAAQ,OAAO;CAG7B,OAAO,EAAE,KAAK,CAAC,CAAC,QAAQ,qBAAqB,UAAW;AACzD;;AAGA,SAAgB,yBAAyB,GAAmB;CAC3D,MAAM,kBAAkB;CACxB,MAAM,yBAAyB;CAE/B,IAAI,SAAS;CACb,IAAI,UAAU;CACd,IAAI,eAAe;CACnB,IAAI,SAAS;CAEb,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GAAG;EACrC,MAAM,OAAO,EAAE;EACf,MAAM,QAAQ,EAAE,UAAU,GAAG,IAAI,CAAC;EAClC,IAAI,SAAS,QAAQ,cACpB,UAAU;EAEX,IAAI,UAAU,iBAAiB;GAC9B,IAAI,cAAc;IACjB,eAAe;IACf,IAAI,SACH,UAAU,GAAG,kBAAkB,SAAS;SAClC;KACN,UAAU,GAAG,yBAAyB,SAAS;KAC/C,UAAU;IACX;IACA,SAAS;GACV,OACC,eAAe;GAGhB,KAAK;GACL;EACD;EAEA,IAAI,cACH,UAAU;OAEV,UAAU;CAEZ;CAEA,IAAI,cAEH,UAAU,UAAU,kBAAkB,SAAS,yBAAyB;CAGzE,OAAO;AACR;AAEA,SAAgB,iBAAiB,GAAmB;CACnD,OACC,EAEE,QAAQ,uBAAuB,IAAI,CAAC,CAEpC,QAAQ,6BAA6B,KAAK;AAE9C"}
1
+ {"version":3,"file":"markdown.js","names":[],"sources":["../../../utils/src/markdown.ts"],"sourcesContent":["const escapeMarkdownRegex = /[\\\\*_{}[\\]()#+\\-.!<>]/g;\nconst unescapeMarkdownRegex = /\\\\([\\\\`*_{}[\\]()#+\\-.!<>])/g;\n// Regex to find markdown links: [text](url) allowing for escaped brackets/parens within text/url\nconst markdownLinkRegex = /(\\[((?:\\\\.|[^[\\]\\\\])+)\\]\\(((?:\\\\.|[^()\\\\])+)\\))/g;\n\nconst escapeMarkdownHeaderRegex = /^===/gm;\nconst unescapeMarkdownHeaderRegex = /^\\u200b===/gm;\n\n// const sampleMarkdown = '## message `not code` *not important* _no underline_ \\n> don\\'t quote me \\n- don\\'t list me \\n+ don\\'t list me \\n1. don\\'t list me \\nnot h1 \\n=== \\nnot h2 \\n---\\n***\\n---\\n___';\nconst markdownQuotedRegex = /\\r?\\n/g;\nconst markdownBacktickRegex = /`/g;\n\nexport function escapeMarkdown(\n\ts: string,\n\toptions?: { quoted?: boolean; inlineBackticks?: boolean; preserveLinks?: boolean },\n): string {\n\t// If preserving links, replace them with placeholders first\n\tif (options?.preserveLinks) {\n\t\tconst links = new Map<string, string>();\n\t\tlet linkIndex = 0;\n\n\t\ts = s.replace(markdownLinkRegex, match => {\n\t\t\t// Create a unique, unlikely-to-occur placeholder\n\t\t\tconst placeholder = `$$$GLLINK${linkIndex++}GLLINK$$$`;\n\t\t\tlinks.set(placeholder, match);\n\t\t\treturn placeholder;\n\t\t});\n\n\t\t// Escape markdown characters\n\t\ts = s.replace(escapeMarkdownRegex, '\\\\$&');\n\n\t\t// Restore the original links if they were preserved\n\t\tif (options?.preserveLinks && links.size) {\n\t\t\tfor (const [placeholder, originalLink] of links) {\n\t\t\t\ts = s.replace(placeholder, originalLink);\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Escape markdown characters\n\t\ts = s.replace(escapeMarkdownRegex, '\\\\$&');\n\t}\n\n\t// Escape markdown header (since the above regex won't match it)\n\ts = s.replace(escapeMarkdownHeaderRegex, '\\u200b===');\n\n\tif (options?.inlineBackticks) {\n\t\ts = escapeMarkdownCodeBlocks(s);\n\t} else {\n\t\ts = s.replace(markdownBacktickRegex, '\\\\$&');\n\t}\n\n\tif (!options?.quoted) return s;\n\n\t// Keep under the same block-quote but with line breaks\n\treturn s.trim().replace(markdownQuotedRegex, '\\t\\\\\\n> ');\n}\n\n/** escapes markdown code blocks */\nexport function escapeMarkdownCodeBlocks(s: string): string {\n\tconst tripleBackticks = '```';\n\tconst escapedTripleBackticks = '\\\\`\\\\`\\\\`';\n\n\tlet result = '';\n\tlet allowed = true;\n\tlet quotesOpened = false;\n\tlet buffer = '';\n\n\tfor (let i = 0; i < s.length; i += 1) {\n\t\tconst char = s[i];\n\t\tconst chain = s.substring(i, i + 3);\n\t\tif (char === '\\n' && quotesOpened) {\n\t\t\tallowed = false;\n\t\t}\n\t\tif (chain === tripleBackticks) {\n\t\t\tif (quotesOpened) {\n\t\t\t\tquotesOpened = false;\n\t\t\t\tif (allowed) {\n\t\t\t\t\tresult += `${tripleBackticks}${buffer}${tripleBackticks}`;\n\t\t\t\t} else {\n\t\t\t\t\tresult += `${escapedTripleBackticks}${buffer}${escapedTripleBackticks}`;\n\t\t\t\t\tallowed = true;\n\t\t\t\t}\n\t\t\t\tbuffer = '';\n\t\t\t} else {\n\t\t\t\tquotesOpened = true;\n\t\t\t}\n\t\t\t// skip chain\n\t\t\ti += 2;\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (quotesOpened) {\n\t\t\tbuffer += char;\n\t\t} else {\n\t\t\tresult += char;\n\t\t}\n\t}\n\n\tif (quotesOpened) {\n\t\t// Handle unclosed code block\n\t\tresult += allowed ? tripleBackticks + buffer : escapedTripleBackticks + buffer;\n\t}\n\n\treturn result;\n}\n\n// Matches the `](` of an inline link or the `]:` of a reference definition whose destination isn't a literal\n// http(s)/mailto URL (the only whitespace skipped is what CommonMark allows before a destination, so anything\n// unusual fails closed)\nconst defuseMarkdownLinksRegex = /\\]([(:])(?![ \\t\\r\\n]*(?:https?:\\/\\/|mailto:))/gi;\n\n/**\n * Restricts links in externally-sourced Markdown text (e.g. commit messages) to web and mail destinations\n * (`http:`, `https:`, `mailto:`), leaving the visible text unchanged.\n *\n * Inline links (`[text](dest)`) and reference definitions (`[ref]: dest`) whose destination isn't a literal\n * http(s)/mailto URL are broken by inserting a zero-width space between the `]` and the `(`/`:` (CommonMark\n * requires them to be adjacent). Destinations that are obfuscated in any way (entity-encoded, escaped,\n * angle-bracketed) fail closed.\n *\n * Expects text that has already been HTML-encoded (see `encodeHtmlWeak`), which neutralizes raw HTML and\n * `<scheme:...>` autolinks, and must run before any trusted links are added to the text. Idempotent.\n */\nexport function defuseMarkdownLinks(s: string): string {\n\tif (!s.includes(']')) return s;\n\n\treturn s.replace(defuseMarkdownLinksRegex, ']\\u200b$1');\n}\n\n/** Escapes text for use inside a Markdown link title (`[text](url \"title\")`) */\nexport function escapeMarkdownLinkTitle(s: string): string {\n\treturn s.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"');\n}\n\nconst webUrlRegex = /^https?:\\/\\//i;\nconst markdownLinkDestinationUnsafeRegex = /[\\s()<>\"\\\\]/g;\n\n/**\n * Returns `url` ready to use as a Markdown link destination when it's a web (http/https) URL, otherwise `undefined`\n * so the caller renders its text unlinked. Characters that could end or escape the destination are percent-encoded;\n * the rest is left as is.\n */\nexport function getMarkdownWebLinkDestination(url: string | undefined): string | undefined {\n\tif (!url || !webUrlRegex.test(url)) return undefined;\n\n\treturn url.replace(markdownLinkDestinationUnsafeRegex, c =>\n\t\tc === '(' ? '%28' : c === ')' ? '%29' : encodeURIComponent(c),\n\t);\n}\n\nexport function unescapeMarkdown(s: string): string {\n\treturn (\n\t\ts\n\t\t\t// Unescape markdown\n\t\t\t.replace(unescapeMarkdownRegex, '$1')\n\t\t\t// Unescape markdown header\n\t\t\t.replace(unescapeMarkdownHeaderRegex, '===')\n\t);\n}\n"],"mappings":";AAAA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAE9B,MAAM,oBAAoB;AAE1B,MAAM,4BAA4B;AAClC,MAAM,8BAA8B;AAGpC,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAE9B,SAAgB,eACf,GACA,SACS;CAET,IAAI,SAAS,eAAe;EAC3B,MAAM,wBAAQ,IAAI,IAAoB;EACtC,IAAI,YAAY;EAEhB,IAAI,EAAE,QAAQ,oBAAmB,UAAS;GAEzC,MAAM,cAAc,YAAY,YAAY;GAC5C,MAAM,IAAI,aAAa,KAAK;GAC5B,OAAO;EACR,CAAC;EAGD,IAAI,EAAE,QAAQ,qBAAqB,MAAM;EAGzC,IAAI,SAAS,iBAAiB,MAAM,MACnC,KAAK,MAAM,CAAC,aAAa,iBAAiB,OACzC,IAAI,EAAE,QAAQ,aAAa,YAAY;CAG1C,OAEC,IAAI,EAA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