@effect/chat-telegram 0.0.0-stage → 4.1.5

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 (157) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +121 -2
  5. package/ai-docs/README.md +44 -0
  6. package/ai-docs/package.json +36 -0
  7. package/ai-docs/src/01_effect/01_basics/01_effect-gen.ts +30 -0
  8. package/ai-docs/src/01_effect/01_basics/02_effect-fn.ts +52 -0
  9. package/ai-docs/src/01_effect/01_basics/10_creating-effects.ts +74 -0
  10. package/ai-docs/src/01_effect/01_basics/index.md +7 -0
  11. package/ai-docs/src/01_effect/02_schema/10_schema-basics.ts +43 -0
  12. package/ai-docs/src/01_effect/02_schema/index.md +7 -0
  13. package/ai-docs/src/01_effect/03_services/01_service.ts +45 -0
  14. package/ai-docs/src/01_effect/03_services/10_reference.ts +10 -0
  15. package/ai-docs/src/01_effect/03_services/20_layer-composition.ts +70 -0
  16. package/ai-docs/src/01_effect/03_services/20_layer-unwrap.ts +66 -0
  17. package/ai-docs/src/01_effect/03_services/index.md +5 -0
  18. package/ai-docs/src/01_effect/04_errors/01_error-handling.ts +30 -0
  19. package/ai-docs/src/01_effect/04_errors/10_catch-tags.ts +24 -0
  20. package/ai-docs/src/01_effect/04_errors/20_reason-errors.ts +64 -0
  21. package/ai-docs/src/01_effect/04_errors/index.md +1 -0
  22. package/ai-docs/src/01_effect/05_resources/10_acquire-release.ts +105 -0
  23. package/ai-docs/src/01_effect/05_resources/20_layer-side-effects.ts +31 -0
  24. package/ai-docs/src/01_effect/05_resources/30_layer-map.ts +86 -0
  25. package/ai-docs/src/01_effect/05_resources/index.md +3 -0
  26. package/ai-docs/src/01_effect/06_running/10_run-main.ts +30 -0
  27. package/ai-docs/src/01_effect/06_running/20_layer-launch.ts +27 -0
  28. package/ai-docs/src/01_effect/06_running/index.md +1 -0
  29. package/ai-docs/src/01_effect/07_pubsub/10_pubsub.ts +56 -0
  30. package/ai-docs/src/01_effect/07_pubsub/index.md +3 -0
  31. package/ai-docs/src/03_stream/10_creating-streams.ts +103 -0
  32. package/ai-docs/src/03_stream/20_consuming-streams.ts +137 -0
  33. package/ai-docs/src/03_stream/30_encoding.ts +163 -0
  34. package/ai-docs/src/03_stream/index.md +4 -0
  35. package/ai-docs/src/04_integration/10_managed-runtime.ts +129 -0
  36. package/ai-docs/src/04_integration/index.md +5 -0
  37. package/ai-docs/src/05_batching/10_request-resolver.ts +89 -0
  38. package/ai-docs/src/05_batching/index.md +3 -0
  39. package/ai-docs/src/06_schedule/10_schedules.ts +111 -0
  40. package/ai-docs/src/06_schedule/index.md +3 -0
  41. package/ai-docs/src/07_datetime/10_creating-and-formatting.ts +30 -0
  42. package/ai-docs/src/07_datetime/20_time-zones.ts +44 -0
  43. package/ai-docs/src/07_datetime/index.md +5 -0
  44. package/ai-docs/src/08_observability/10_logging.ts +66 -0
  45. package/ai-docs/src/08_observability/20_otlp-tracing.ts +95 -0
  46. package/ai-docs/src/08_observability/index.md +7 -0
  47. package/ai-docs/src/09_testing/10_effect-tests.ts +55 -0
  48. package/ai-docs/src/09_testing/20_layer-tests.ts +138 -0
  49. package/ai-docs/src/09_testing/index.md +1 -0
  50. package/ai-docs/src/10_predicate/01_basics.ts +14 -0
  51. package/ai-docs/src/10_predicate/index.md +9 -0
  52. package/ai-docs/src/40_sql/10_basics.ts +175 -0
  53. package/ai-docs/src/40_sql/index.md +6 -0
  54. package/ai-docs/src/50_http-client/10_basics.ts +102 -0
  55. package/ai-docs/src/50_http-client/index.md +3 -0
  56. package/ai-docs/src/51_http-server/10_basics.ts +118 -0
  57. package/ai-docs/src/51_http-server/20_testing.ts +100 -0
  58. package/ai-docs/src/51_http-server/fixtures/api/Api.ts +14 -0
  59. package/ai-docs/src/51_http-server/fixtures/api/Authorization.ts +36 -0
  60. package/ai-docs/src/51_http-server/fixtures/api/System.ts +10 -0
  61. package/ai-docs/src/51_http-server/fixtures/api/Users.ts +107 -0
  62. package/ai-docs/src/51_http-server/fixtures/domain/User.ts +21 -0
  63. package/ai-docs/src/51_http-server/fixtures/domain/UserErrors.ts +22 -0
  64. package/ai-docs/src/51_http-server/fixtures/server/Authorization.ts +37 -0
  65. package/ai-docs/src/51_http-server/fixtures/server/Users/http.ts +80 -0
  66. package/ai-docs/src/51_http-server/fixtures/server/Users.ts +183 -0
  67. package/ai-docs/src/51_http-server/index.md +3 -0
  68. package/ai-docs/src/52_graphql/10_basics.ts +117 -0
  69. package/ai-docs/src/52_graphql/20_testing.ts +45 -0
  70. package/ai-docs/src/52_graphql/30_batching.ts +118 -0
  71. package/ai-docs/src/52_graphql/40_aliased-batching.ts +124 -0
  72. package/ai-docs/src/52_graphql/50_errors-and-retries.ts +74 -0
  73. package/ai-docs/src/52_graphql/index.md +6 -0
  74. package/ai-docs/src/60_child-process/10_working-with-child-processes.ts +117 -0
  75. package/ai-docs/src/60_child-process/index.md +3 -0
  76. package/ai-docs/src/70_cli/10_basics.ts +162 -0
  77. package/ai-docs/src/70_cli/index.md +5 -0
  78. package/ai-docs/src/71_ai/10_language-model.ts +156 -0
  79. package/ai-docs/src/71_ai/20_tools.ts +226 -0
  80. package/ai-docs/src/71_ai/30_chat.ts +158 -0
  81. package/ai-docs/src/71_ai/fixtures/domain/LaunchPlan.ts +9 -0
  82. package/ai-docs/src/71_ai/index.md +5 -0
  83. package/ai-docs/src/80_cluster/10_entities.ts +97 -0
  84. package/ai-docs/src/80_cluster/index.md +4 -0
  85. package/ai-docs/src/index.md +10 -0
  86. package/ai-docs/tsconfig.json +28 -0
  87. package/dist/TelegramBotApi.d.ts +153 -0
  88. package/dist/TelegramBotApi.d.ts.map +1 -0
  89. package/dist/TelegramBotApi.js +219 -0
  90. package/dist/TelegramBotApi.js.map +1 -0
  91. package/dist/TelegramChat.d.ts +390 -0
  92. package/dist/TelegramChat.d.ts.map +1 -0
  93. package/dist/TelegramChat.js +359 -0
  94. package/dist/TelegramChat.js.map +1 -0
  95. package/dist/index.d.ts +15 -0
  96. package/dist/index.d.ts.map +1 -0
  97. package/dist/index.js +16 -0
  98. package/dist/index.js.map +1 -0
  99. package/dist/internal/actions.d.ts +2 -0
  100. package/dist/internal/actions.d.ts.map +1 -0
  101. package/dist/internal/actions.js +88 -0
  102. package/dist/internal/actions.js.map +1 -0
  103. package/dist/internal/adapter.d.ts +2 -0
  104. package/dist/internal/adapter.d.ts.map +1 -0
  105. package/dist/internal/adapter.js +309 -0
  106. package/dist/internal/adapter.js.map +1 -0
  107. package/dist/internal/address.d.ts +2 -0
  108. package/dist/internal/address.d.ts.map +1 -0
  109. package/dist/internal/address.js +26 -0
  110. package/dist/internal/address.js.map +1 -0
  111. package/dist/internal/commands.d.ts +2 -0
  112. package/dist/internal/commands.d.ts.map +1 -0
  113. package/dist/internal/commands.js +30 -0
  114. package/dist/internal/commands.js.map +1 -0
  115. package/dist/internal/errors.d.ts +2 -0
  116. package/dist/internal/errors.d.ts.map +1 -0
  117. package/dist/internal/errors.js +136 -0
  118. package/dist/internal/errors.js.map +1 -0
  119. package/dist/internal/markdown.d.ts +9 -0
  120. package/dist/internal/markdown.d.ts.map +1 -0
  121. package/dist/internal/markdown.js +708 -0
  122. package/dist/internal/markdown.js.map +1 -0
  123. package/dist/internal/normalize.d.ts +2 -0
  124. package/dist/internal/normalize.d.ts.map +1 -0
  125. package/dist/internal/normalize.js +276 -0
  126. package/dist/internal/normalize.js.map +1 -0
  127. package/dist/internal/options.d.ts +2 -0
  128. package/dist/internal/options.d.ts.map +1 -0
  129. package/dist/internal/options.js +6 -0
  130. package/dist/internal/options.js.map +1 -0
  131. package/dist/internal/polling.d.ts +2 -0
  132. package/dist/internal/polling.d.ts.map +1 -0
  133. package/dist/internal/polling.js +68 -0
  134. package/dist/internal/polling.js.map +1 -0
  135. package/dist/internal/receive.d.ts +2 -0
  136. package/dist/internal/receive.d.ts.map +1 -0
  137. package/dist/internal/receive.js +183 -0
  138. package/dist/internal/receive.js.map +1 -0
  139. package/dist/internal/webhook.d.ts +2 -0
  140. package/dist/internal/webhook.d.ts.map +1 -0
  141. package/dist/internal/webhook.js +61 -0
  142. package/dist/internal/webhook.js.map +1 -0
  143. package/package.json +62 -3
  144. package/src/TelegramBotApi.ts +282 -0
  145. package/src/TelegramChat.ts +542 -0
  146. package/src/index.ts +18 -0
  147. package/src/internal/actions.ts +95 -0
  148. package/src/internal/adapter.ts +319 -0
  149. package/src/internal/address.ts +33 -0
  150. package/src/internal/commands.ts +37 -0
  151. package/src/internal/errors.ts +148 -0
  152. package/src/internal/markdown.ts +805 -0
  153. package/src/internal/normalize.ts +283 -0
  154. package/src/internal/options.ts +12 -0
  155. package/src/internal/polling.ts +86 -0
  156. package/src/internal/receive.ts +268 -0
  157. package/src/internal/webhook.ts +85 -0
@@ -0,0 +1,805 @@
1
+ /**
2
+ * Rich Markdown for `sendRichMessage`: the escaping that keeps consumer
3
+ * Markdown from reaching Telegram's raw HTML, images, math, spoilers and
4
+ * non-web links, and the `measure` that bounds what it costs.
5
+ *
6
+ * @internal
7
+ */
8
+
9
+ /** What one line break or block marker costs, so that a message in budget stays under 500 blocks. @internal */
10
+ export const block = 65
11
+
12
+ /** Telegram's rich message limit. It counts rendered characters, which UTF-8 bytes of the source bound. @internal */
13
+ export const richLimit = 32_768
14
+
15
+ /** Files one post may carry. @internal */
16
+ export const filesPerMessage = 10
17
+
18
+ /** The most nesting and table columns Telegram renders. @internal */
19
+ export const maxDepth = 16
20
+
21
+ /** @internal */
22
+ export const maxColumns = 20
23
+
24
+ /** The reference to the `n`th file of a post, at the end of the Markdown. @internal */
25
+ export const mediaReference = (n: number): string => `\n\n![](tg://document?id=f${n})`
26
+
27
+ /**
28
+ * What the budget keeps back for media references and the fence a post
29
+ * with files may need to close: each reference's bytes and its block, one
30
+ * block for the message's first, which `measure` does not charge, and 8
31
+ * bytes for the fence.
32
+ *
33
+ * @internal
34
+ */
35
+ export const reservation = filesPerMessage * (32 + block) + block + 8
36
+
37
+ /** @internal */
38
+ export const messageLength = richLimit - reservation
39
+
40
+ const twoByteEscapes = new Set(["$", "=", "|", "!", "[", "]", "*", "_", "~", "`"])
41
+ const blockMarkers = new Set([">", "-", "+", "*", ".", ")"])
42
+
43
+ const isDigit = (c: string) => c >= "0" && c <= "9"
44
+
45
+ /**
46
+ * A sum of per-character costs, each fixed or depending only on what comes
47
+ * before the character on its own line, which makes it subadditive:
48
+ *
49
+ * - a code point in the Basic Multilingual Plane costs its UTF-8 length,
50
+ * and each UTF-16 surrogate 3, enough for the U+FFFD a lone one becomes.
51
+ * NUL costs 3 too, as Markdown turns it into U+FFFD.
52
+ * - `<` costs 4, a backslash 5 (the numeric reference, such as `&#93;`,
53
+ * that an escape Telegram ignores becomes), and
54
+ * `$ = | ! [ ] * _ ~` and the backtick 2, their escaped length or more,
55
+ * whether or not they are escaped in context.
56
+ * - `\n` and `\r` cost `block`, as does a block marker (`>`, a bullet,
57
+ * the dot or parenthesis of a number) before any other text on its line.
58
+ *
59
+ * @internal
60
+ */
61
+ export const measure = (markdown: string): number => {
62
+ let cost = 0
63
+ let prefix = true
64
+ for (let i = 0; i < markdown.length; i++) {
65
+ const code = markdown.charCodeAt(i)
66
+ if (code === 10 || code === 13) {
67
+ cost += block
68
+ prefix = true
69
+ continue
70
+ }
71
+ if (code >= 0xd800 && code <= 0xdfff) {
72
+ cost += 3
73
+ prefix = false
74
+ continue
75
+ }
76
+ const c = markdown[i]
77
+ if (prefix) {
78
+ if (c === " " || c === "\t" || isDigit(c)) {
79
+ cost += 1
80
+ continue
81
+ }
82
+ if (blockMarkers.has(c)) {
83
+ cost += block
84
+ continue
85
+ }
86
+ prefix = false
87
+ }
88
+ cost += c === "\\"
89
+ ? 5
90
+ : code === 0
91
+ ? 3
92
+ : c === "<"
93
+ ? 4
94
+ : twoByteEscapes.has(c)
95
+ ? 2
96
+ : code < 0x80
97
+ ? 1
98
+ : code < 0x800
99
+ ? 2
100
+ : 3
101
+ }
102
+ return cost
103
+ }
104
+
105
+ const punctuation = /[!-/:-@[-`{-~]/
106
+
107
+ /** A line that opens a fence: up to three spaces, then three or more backticks or tildes. */
108
+ const fenceOpen = /^( {0,3})(`{3,}|~{3,})(.*)$/
109
+
110
+ interface Fence {
111
+ readonly char: string
112
+ readonly length: number
113
+ readonly indent: number
114
+ }
115
+
116
+ const opens = (line: string): Fence | undefined => {
117
+ const match = fenceOpen.exec(line)
118
+ if (match === null || (match[2][0] === "`" && match[3].includes("`"))) return undefined
119
+ return { char: match[2][0], length: match[2].length, indent: match[1].length }
120
+ }
121
+
122
+ const closes = (line: string, fence: Fence): boolean => {
123
+ const match = /^ {0,3}(`+|~+)[ \t]*$/.exec(line)
124
+ return match !== null && match[1][0] === fence.char && match[1].length >= fence.length
125
+ }
126
+
127
+ /** A line that may open a list item or footnote, which an indented fence could belong to. */
128
+ const container = /^[ \t>]*(?:[-+*]|\d{1,9}[.)])(?:[ \t]|$)|^[ \t>]*\[\^/
129
+
130
+ /** A line GFM may read as the start of another block, which ends a table and is no paragraph. */
131
+ const blockStart = /^(?: {0,3}[#>\-*+_~`<=[]| {0,3}\d{1,9}[.)]| {4}| {0,3}\t)/
132
+
133
+ /** Where a line's container markers end, as far as `startsBlock` needs to know. */
134
+ const quotes = /^(?: {0,3}> ?)* {0,3}/
135
+
136
+ /**
137
+ * Whether a line starts a block wherever it is, so that it can be no
138
+ * paragraph's continuation: an ATX heading, or a list item with content
139
+ * that may interrupt a paragraph (a bullet, or an ordered item numbered 1
140
+ * or following one of its list). Tabs and other lines say no, which is
141
+ * safe: the inline count goes on.
142
+ */
143
+ const startsBlock = (line: string, previousItem: string | undefined): string | undefined | true => {
144
+ const rest = line.slice(quotes.exec(line)![0].length)
145
+ if (/^(?:#{1,6}(?: |$)|[-+*] +\S)/.test(rest)) return true
146
+ const item = /^(\d{1,9})([.)]) +\S/.exec(rest)
147
+ if (item === null) return undefined
148
+ const key = line.slice(0, line.length - rest.length) + item[2]
149
+ return item[1] === "1" || key === previousItem ? key : undefined
150
+ }
151
+
152
+ const delimiterRow = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/
153
+
154
+ /** The cells of a table row, split at unescaped pipes as GFM does, even inside code. */
155
+ const cellCount = (line: string): number => {
156
+ let count = 1
157
+ for (let i = 0; i < line.length; i++) {
158
+ if (line[i] === "\\") i++
159
+ else if (line[i] === "|") count++
160
+ }
161
+ const trimmed = line.trim()
162
+ if (trimmed.startsWith("|")) count--
163
+ if (trimmed.length > 1 && trimmed.endsWith("|") && !trimmed.endsWith("\\|")) count--
164
+ return count
165
+ }
166
+
167
+ /**
168
+ * A blank line as CommonMark defines it: only spaces and tabs. Other
169
+ * whitespace, such as U+00A0, is paragraph text and ends nothing.
170
+ */
171
+ const isBlank = (line: string): boolean => /^[ \t]*$/.test(line)
172
+
173
+ /** Whether a line can head a table: GFM reads no cell in a lone `|`. */
174
+ const hasPipe = (line: string) => (cellCount(line) > 1 || line.trim().startsWith("|")) && line.trim() !== "|"
175
+
176
+ /** The decoded form of a link destination, as a Markdown parser and then a URL parser read it. */
177
+ const decodeDestination = (raw: string): { readonly unescaped: string; readonly decoded: string } | undefined => {
178
+ let unescaped = raw.replace(/\\([!-/:-@[-`{-~])/g, "$1")
179
+ unescaped = unescaped.replace(/&#(\d{1,7});/g, (_, n: string) => String.fromCodePoint(Math.min(Number(n), 0x10ffff)))
180
+ .replace(/&#[xX]([0-9a-fA-F]{1,6});/g, (_, n: string) => String.fromCodePoint(Math.min(parseInt(n, 16), 0x10ffff)))
181
+ .replace(
182
+ /&(amp|lt|gt|quot|apos);/g,
183
+ (_, name: string) =>
184
+ name === "amp" ? "&" : name === "lt" ? "<" : name === "gt" ? ">" : name === "quot" ? "\"" : "'"
185
+ )
186
+ // Any other named reference could be one of HTML's many, such as `&colon;`.
187
+ if (/&[A-Za-z][A-Za-z0-9]*;/.test(unescaped)) return undefined
188
+ try {
189
+ return { unescaped, decoded: decodeURIComponent(unescaped) }
190
+ } catch {
191
+ return undefined
192
+ }
193
+ }
194
+
195
+ const allowedScheme = /^(?:https?:\/\/|mailto:)/i
196
+
197
+ /** Whether a link to `raw` may stay: http, https and mailto, or a mention the post allows. */
198
+ const allowedDestination = (raw: string, mentions: ReadonlySet<string>): boolean => {
199
+ const destination = decodeDestination(raw)
200
+ if (destination === undefined) return false
201
+ if (allowedScheme.test(destination.unescaped) && allowedScheme.test(destination.decoded)) return true
202
+ const mention = /^tg:\/\/user\?id=(\d{1,20})$/.exec(destination.decoded)
203
+ return mention !== null && destination.unescaped === destination.decoded && mentions.has(mention[1])
204
+ }
205
+
206
+ const blank = (c: string | undefined): boolean => c === " " || c === "\t"
207
+
208
+ /**
209
+ * The deepest parentheses a kept destination may nest. CommonMark lets a
210
+ * parser refuse deeper ones once it supports three, and GFM refuses past
211
+ * 32 in a link, which would leave the rest of the link as Markdown.
212
+ */
213
+ const maxDestinationDepth = 3
214
+
215
+ /**
216
+ * The destination and optional title from `start`, as CommonMark reads
217
+ * them when they are on this line: a destination not in angle brackets, up
218
+ * to a space, a control character or a `)` it did not open, with its
219
+ * parentheses balanced and at most three deep, then a title after a space. `end` is past the
220
+ * title and the blanks after it.
221
+ */
222
+ const destinationAndTitle = (
223
+ line: string,
224
+ start: number
225
+ ): { readonly destination: string; readonly end: number } | undefined => {
226
+ let i = start
227
+ while (blank(line[i])) i++
228
+ if (line[i] === "<") return undefined
229
+ const from = i
230
+ let depth = 0
231
+ for (; i < line.length; i++) {
232
+ const c = line[i]
233
+ if (c === "\\" && punctuation.test(line[i + 1] ?? "")) {
234
+ i++
235
+ continue
236
+ }
237
+ const code = c.charCodeAt(0)
238
+ if (code <= 0x20 || code === 0x7f) break
239
+ if (c === "(") {
240
+ if (++depth > maxDestinationDepth) return undefined
241
+ } else if (c === ")") {
242
+ if (depth === 0) break
243
+ depth--
244
+ }
245
+ }
246
+ if (depth > 0) return undefined
247
+ const destination = line.slice(from, i)
248
+ const spaced = blank(line[i])
249
+ while (blank(line[i])) i++
250
+ const open = line[i]
251
+ if (spaced && (open === "\"" || open === "'" || open === "(")) {
252
+ const close = open === "(" ? ")" : open
253
+ for (i++; i < line.length && line[i] !== close; i++) {
254
+ if (line[i] === "\\" && punctuation.test(line[i + 1] ?? "")) i++
255
+ else if (open === "(" && line[i] === "(") return undefined
256
+ }
257
+ if (i >= line.length) return undefined
258
+ i++
259
+ while (blank(line[i])) i++
260
+ }
261
+ return { destination, end: i }
262
+ }
263
+
264
+ /**
265
+ * A link's `(destination "title")` from the `(` at `start`, when all of it
266
+ * is on this line. A tail that goes on to the next line, as CommonMark
267
+ * allows, is not one: the link is then refused.
268
+ */
269
+ const linkTail = (line: string, start: number): { readonly destination: string; readonly end: number } | undefined => {
270
+ const tail = destinationAndTitle(line, start + 1)
271
+ return tail !== undefined && line[tail.end] === ")" ? { destination: tail.destination, end: tail.end + 1 } : undefined
272
+ }
273
+
274
+ /**
275
+ * The punctuation whose backslash escape Telegram honors. Before any other
276
+ * punctuation the backslash stays as text and the character is read as
277
+ * syntax: `\<b>` is bold. `\]` hides the bracket from emphasis but still
278
+ * closes a link or a definition label, so it is not here either.
279
+ */
280
+ const honored = new Set("!#$()*+-.=>[\\_`{|}~")
281
+
282
+ /** A consumer's escape of `c` as Telegram reads it: kept, or a numeric character reference. */
283
+ const escapeOf = (c: string): string => honored.has(c) ? "\\" + c : `&#${c.charCodeAt(0)};`
284
+
285
+ /**
286
+ * A kept destination as Telegram needs it. Telegram reads a destination
287
+ * verbatim, with no escapes, so they are decoded, a parenthesis or
288
+ * backslash percent-encoded, and a `<` too, which would end the link.
289
+ */
290
+ const destinationOf = (raw: string): string =>
291
+ raw.replace(/\\([!-/:-@[-`{-~])|</g, (match, escaped: string | undefined) => {
292
+ const c = escaped ?? match
293
+ return percentEncoded[c] ?? c
294
+ })
295
+
296
+ const percentEncoded: Readonly<Record<string, string>> = {
297
+ "(": "%28",
298
+ ")": "%29",
299
+ "\\": "%5C",
300
+ "<": "%3C",
301
+ ">": "%3E"
302
+ }
303
+
304
+ /**
305
+ * The destination of a reference definition after `]:`, when the rest of
306
+ * the line is a nonempty destination and an optional title. Anything else
307
+ * after it, a title that goes on to the next line, or a destination there,
308
+ * makes it no definition here.
309
+ */
310
+ const definitionDestination = (line: string, start: number): string | undefined => {
311
+ const tail = destinationAndTitle(line, start)
312
+ return tail !== undefined && tail.end === line.length ? tail.destination : undefined
313
+ }
314
+
315
+ /** The most characters CommonMark reads between a label's brackets. */
316
+ const maxLabelLength = 999
317
+
318
+ /**
319
+ * The most characters the renderer can make of a simple label: an escape
320
+ * becomes at most `%5C&lt;`, and each of `$ = | * _ ~` at most two. The
321
+ * label it sends, not the consumer's, must fit in 999.
322
+ */
323
+ const renderedLabelBound = (text: string): number => {
324
+ let n = 0
325
+ for (let i = 0; i < text.length; i++) {
326
+ if (text[i] === "\\") {
327
+ n += 7
328
+ i++
329
+ } else n += "$=|*_~".includes(text[i]) ? 2 : 1
330
+ }
331
+ return n
332
+ }
333
+
334
+ /**
335
+ * A label CommonMark and the renderer both close at its first `]`: no
336
+ * other bracket, code span or autolink in it, and no escape at its end.
337
+ */
338
+ const simpleLabel = /^(?:[^\\[\]`<]|\\.)*$/
339
+
340
+ /**
341
+ * The reference definition the line whose first `[` is at `start` may
342
+ * keep: a simple label, not blank, not a footnote's and at most 999
343
+ * characters once rendered, closed by `]:`, then a destination it allows.
344
+ */
345
+ const keptDefinition = (
346
+ line: string,
347
+ start: number,
348
+ mentions: ReadonlySet<string>
349
+ ): { readonly close: number; readonly destination: string } | undefined => {
350
+ const close = line.indexOf("]", start)
351
+ const text = line.slice(start + 1, close)
352
+ if (
353
+ close < 0 || line[close + 1] !== ":" || !simpleLabel.test(text) || isBlank(text) || text[0] === "^" ||
354
+ renderedLabelBound(text) > maxLabelLength
355
+ ) return undefined
356
+ const destination = definitionDestination(line, close + 2)
357
+ return destination !== undefined && allowedDestination(destination, mentions) ? { close, destination } : undefined
358
+ }
359
+
360
+ /**
361
+ * The end of the code span whose opening backticks are at `start`, found as
362
+ * CommonMark finds it: the next run of as many backticks on the line. A
363
+ * run with no partner on the line opens no span: the renderer escapes it,
364
+ * so no span can pair across lines. In a table row a span holding a pipe
365
+ * is refused, since GFM splits cells before it reads code.
366
+ */
367
+ const codeSpanEnd = (line: string, start: number, tableRow: boolean): number | undefined => {
368
+ let length = 0
369
+ while (line[start + length] === "`") length++
370
+ for (let j = start + length; j < line.length;) {
371
+ if (line[j] !== "`") {
372
+ j++
373
+ continue
374
+ }
375
+ let run = 0
376
+ while (line[j + run] === "`") run++
377
+ if (run === length) return tableRow && line.slice(start, j).includes("|") ? undefined : j + run
378
+ j += run
379
+ }
380
+ return undefined
381
+ }
382
+
383
+ /**
384
+ * Where GFM starts a bare URL link. It runs to the next space, taking
385
+ * backslashes and backticks with it, so inside one an escape is not
386
+ * needed and a backtick opens no span.
387
+ */
388
+ const bareUrl = /^(?:https?:\/\/|www\.)/i
389
+
390
+ /** A thematic break, whose delimiters stand alone. */
391
+ const thematicBreak = /^ {0,3}([-*_])(?:[ \t]*\1){2,}[ \t]*$/
392
+
393
+ const autolink = /^<([A-Za-z][A-Za-z0-9+.-]{1,31}):[^\s<>`\p{Cc}]*>/u
394
+
395
+ /**
396
+ * What one paragraph may already nest. `open` counts every delimiter that
397
+ * could open emphasis, and none is taken back for one that may close it:
398
+ * whether a run closes, and what, depends on flanking rules and links that
399
+ * this renderer does not follow, and a node needs at least one opener.
400
+ * `containers` is the most container depth of the paragraph's lines, as a
401
+ * lazy continuation line stays in containers it does not repeat. `nodes`
402
+ * counts the code spans, links and footnote references, which Telegram
403
+ * caps per paragraph.
404
+ */
405
+ interface Inline {
406
+ open: number
407
+ containers: number
408
+ nodes: number
409
+ }
410
+
411
+ /** The inline nodes one paragraph may hold. Telegram refuses a paragraph past about 4,387. @internal */
412
+ export const maxInlineNodes = 4000
413
+
414
+ /** What one footnote reference costs against `maxInlineNodes`: its superscript, anchor and link. */
415
+ const footnoteNodes = 3
416
+
417
+ /** The footnote references one message may hold. Telegram refuses about 774 to one footnote. @internal */
418
+ export const maxFootnoteReferences = 700
419
+
420
+ interface LineContext {
421
+ readonly tableRow: boolean
422
+ /** Whether GFM may read the line as a table row, which splits code spans at pipes. */
423
+ readonly cells: boolean
424
+ readonly widePipes: boolean
425
+ readonly setext: boolean
426
+ readonly inline: Inline
427
+ readonly mentions: ReadonlySet<string>
428
+ /** Footnote references so far in the message. */
429
+ readonly footnotes: { count: number }
430
+ /**
431
+ * Whether a definition may start this line: after a blank line, the
432
+ * start of the text or another definition, outside containers. Set to
433
+ * whether this line kept one.
434
+ */
435
+ readonly definitions: { allowed: boolean }
436
+ }
437
+
438
+ /**
439
+ * The container markers at the start of a line, with those past the depth
440
+ * limit escaped, and where the line's text starts.
441
+ */
442
+ const renderPrefix = (line: string): { readonly text: string; readonly rest: number; readonly depth: number } => {
443
+ let out = ""
444
+ let i = 0
445
+ let depth = 0
446
+ let indent = 0
447
+ for (;;) {
448
+ const space = /^[ \t]*/.exec(line.slice(i))![0]
449
+ indent += space.length
450
+ out += space
451
+ i += space.length
452
+ const marker = /^(?:>|[-+*](?=[ \t]|$)|\d{1,9}[.)](?=[ \t]|$))/.exec(line.slice(i))
453
+ if (marker === null) break
454
+ depth++
455
+ const token = marker[0]
456
+ const escape = depth + Math.floor(indent / 2) >= maxDepth
457
+ out += escape ? token.slice(0, -1) + "\\" + token.slice(-1) : token
458
+ i += token.length
459
+ }
460
+ return { text: out, rest: i, depth: depth + Math.floor(indent / 2) }
461
+ }
462
+
463
+ const renderLine = (line: string, context: LineContext): string => {
464
+ const prefix = renderPrefix(line)
465
+ // A footnote definition opens a block, so not behind a tab or four
466
+ // spaces: there, after a definition, GFM reads one with a label `^a`.
467
+ const indent = /[ \t]*$/.exec(line.slice(0, prefix.rest))![0]
468
+ const footnote = !indent.includes("\t") && indent.length < 4 && /^\[\^[\w-]+\]:/.test(line.slice(prefix.rest))
469
+ const inline = context.inline
470
+ inline.containers = Math.max(inline.containers, prefix.depth)
471
+ const limit = Math.max(0, maxDepth - 1 - inline.containers)
472
+ /** Counts `n` inline nodes, or says no when the paragraph has no room left. */
473
+ const node = (n: number): boolean => {
474
+ if (inline.nodes + n > maxInlineNodes) return false
475
+ inline.nodes += n
476
+ return true
477
+ }
478
+ // Telegram reads a definition wherever the line's first `[` closes at a
479
+ // `]:`, also past other brackets, code or autolinks, and GFM reads one
480
+ // at the start of a footnote's text. One is kept only where CommonMark
481
+ // reads the same, with a label and destination both accept. Otherwise
482
+ // the line's `[` is escaped before it is read, so no raw destination is
483
+ // sent behind a label that is text.
484
+ const shaped = line[prefix.rest] === "[" &&
485
+ line.includes("]:", footnote ? line.indexOf("]:", prefix.rest) + 2 : prefix.rest)
486
+ const definition = shaped && context.definitions.allowed && prefix.depth === 0 ?
487
+ keptDefinition(line, prefix.rest, context.mentions) :
488
+ undefined
489
+ context.definitions.allowed = false
490
+ // Where the line's opening `[` is in `out`, while it may close on a later line.
491
+ const label = line[prefix.rest] === "[" ? prefix.text.length : undefined
492
+ // Where the `[` of a label with no other bracket in it is, until a `]`
493
+ // closes it. Only such a label keeps its destination: around a nested
494
+ // label, a reference or a footnote, whether the outer brackets make a
495
+ // link depends on definitions and on Telegram's precedence, and a raw
496
+ // tail would be read as Markdown.
497
+ let opener: number | undefined
498
+ // Where each `[` not yet closed on this line is in `out`.
499
+ const unclosed: Array<number> = []
500
+ let out = prefix.text
501
+ let urlEnd = -1
502
+ let i = prefix.rest
503
+ if (shaped && definition === undefined) {
504
+ out += "\\["
505
+ i++
506
+ }
507
+ while (i < line.length) {
508
+ const c = line[i]
509
+ const next = line[i + 1]
510
+ if (i >= urlEnd && bareUrl.test(line.slice(i, i + 8))) {
511
+ urlEnd = i
512
+ while (urlEnd < line.length && line[urlEnd] !== " " && line[urlEnd] !== "\t") urlEnd++
513
+ }
514
+ const inUrl = i < urlEnd
515
+ // In a bare URL a backslash escapes nothing, outside one it does: as
516
+ // `%5C` it is the same character to a browser and inert to both.
517
+ if (c === "\\" && inUrl && next !== undefined && punctuation.test(next)) {
518
+ out += "%5C"
519
+ i++
520
+ continue
521
+ }
522
+ if (c === "\\" && next !== undefined && punctuation.test(next)) {
523
+ out += escapeOf(next)
524
+ i += 2
525
+ continue
526
+ }
527
+ switch (c) {
528
+ case "`": {
529
+ const end = inUrl ? undefined : codeSpanEnd(line, i, context.cells)
530
+ if (end !== undefined && node(1)) {
531
+ out += line.slice(i, end)
532
+ i = end
533
+ continue
534
+ }
535
+ while (line[i] === "`") {
536
+ out += "\\`"
537
+ i++
538
+ }
539
+ continue
540
+ }
541
+ case "<": {
542
+ const match = inUrl ? null : autolink.exec(line.slice(i))
543
+ if (match !== null && /^(?:https?|mailto)$/i.test(match[1]) && node(1)) {
544
+ out += match[0]
545
+ i += match[0].length
546
+ } else {
547
+ out += "&lt;"
548
+ i++
549
+ }
550
+ continue
551
+ }
552
+ case "$":
553
+ out += "\\$"
554
+ i++
555
+ continue
556
+ case "=":
557
+ out += context.setext ? "=" : "\\="
558
+ i++
559
+ continue
560
+ case "|":
561
+ out += context.tableRow && !context.widePipes ? "|" : "\\|"
562
+ i++
563
+ continue
564
+ case "!":
565
+ out += next === "[" ? "\\!" : "!"
566
+ i++
567
+ continue
568
+ case "[":
569
+ // A footnote reference, unless it opens the line's footnote definition.
570
+ if (next === "^" && !(footnote && i === prefix.rest)) {
571
+ if (context.footnotes.count >= maxFootnoteReferences || !node(footnoteNodes)) {
572
+ out += "\\["
573
+ i++
574
+ continue
575
+ }
576
+ context.footnotes.count++
577
+ opener = undefined
578
+ } else if (!inUrl) {
579
+ // Each `[` that could open a link or a reference counts as a node.
580
+ if (!node(1)) {
581
+ out += "\\["
582
+ i++
583
+ continue
584
+ }
585
+ opener = i
586
+ }
587
+ unclosed.push(out.length)
588
+ out += "["
589
+ i++
590
+ continue
591
+ case "]": {
592
+ // Telegram closes a link at `]` even when it is escaped, so a refused
593
+ // link loses its `(`. A kept destination is sent verbatim, which is
594
+ // inert only if it is read as one: a link needs an opener on its
595
+ // line, and not `[a][b](…)` or `[a][](…)`, where `[a]` may be the link.
596
+ const plain = opener !== undefined && line[opener - 1] !== "]"
597
+ const labelOpener = opener
598
+ opener = undefined
599
+ unclosed.pop()
600
+ if (next === "(") {
601
+ const tail = linkTail(line, i + 1)
602
+ if (plain && tail !== undefined && allowedDestination(tail.destination, context.mentions)) {
603
+ out += "](" + destinationOf(tail.destination) + ")"
604
+ i = tail.end
605
+ continue
606
+ }
607
+ out += "]\\("
608
+ i += 2
609
+ continue
610
+ }
611
+ // The `[` at the line's start counted as a node, so it is still a label.
612
+ if (definition !== undefined && i === definition.close && labelOpener === prefix.rest) {
613
+ context.definitions.allowed = true
614
+ return out + "]: " + destinationOf(definition.destination)
615
+ }
616
+ out += "]"
617
+ i++
618
+ continue
619
+ }
620
+ case "*":
621
+ case "_":
622
+ case "~": {
623
+ let end = i
624
+ while (line[end] === c) end++
625
+ const run = line.slice(i, end)
626
+ const after = line[end]
627
+ const spaced = (ch: string | undefined) => ch === undefined || ch === " " || ch === "\t"
628
+ // A run with space on both sides is text to CommonMark, but Telegram
629
+ // opens emphasis with it: `2 * 3 * 4` (live check 2).
630
+ if (spaced(i === prefix.rest ? undefined : line[i - 1]) && spaced(after) && !thematicBreak.test(line)) {
631
+ out += run.split("").map((char) => "\\" + char).join("")
632
+ i = end
633
+ continue
634
+ }
635
+ // A run of n delimiters can open n levels: `***a*b*c*` is three.
636
+ // One followed by a space or the line's end can't open.
637
+ if (!spaced(after)) {
638
+ if (inline.open + run.length > limit) {
639
+ out += run.split("").map((char) => "\\" + char).join("")
640
+ i = end
641
+ continue
642
+ }
643
+ inline.open += run.length
644
+ }
645
+ out += run
646
+ i = end
647
+ continue
648
+ }
649
+ default:
650
+ out += c
651
+ i++
652
+ }
653
+ }
654
+ // A label left open at the start of a line could close on a later one,
655
+ // as a definition's.
656
+ if (label !== undefined && unclosed[0] === label) out = out.slice(0, label) + "\\" + out.slice(label)
657
+ return out
658
+ }
659
+
660
+ /** @internal */
661
+ export interface RenderOptions {
662
+ /** User ids whose `[name](tg://user?id=…)` links may stay. */
663
+ readonly mentions?: ReadonlySet<string> | undefined
664
+ /** How many files the post references at the end. */
665
+ readonly files?: number | undefined
666
+ }
667
+
668
+ /**
669
+ * Consumer Markdown as rich Markdown that keeps to what `measure` charged:
670
+ *
671
+ * - Fences pass verbatim, as do code spans, which are found left to right
672
+ * as CommonMark finds them. A fence indented by one to three spaces after
673
+ * a list item could belong to it, so from such a fence on nothing is
674
+ * verbatim. Inside a bare URL a backtick opens no span.
675
+ * - `<` becomes `&lt;` unless it opens an http, https or mailto autolink,
676
+ * so there is no raw HTML, also after a bare URL, which would take a
677
+ * backslash with it. `$` and `=` are escaped (math, marks), except `=`
678
+ * under a paragraph of plain top-level lines (a setext heading), as is `|` outside tables
679
+ * (spoilers), and `!` before `[` (images).
680
+ * - A backslash escape Telegram ignores becomes a numeric character
681
+ * reference, so `\<` is no HTML and `\]` closes no link.
682
+ * - A link or reference definition whose destination, decoded as a
683
+ * Markdown parser and then a URL parser would, is not http, https or
684
+ * mailto is text: a link loses its `(`, a definition its opening `[`.
685
+ * A `tg://user` link stays for an id in `mentions`. A kept link needs its
686
+ * `[` and its whole tail on its line, a label with no other bracket in
687
+ * it, and no `]` right before it. A line whose first `[` meets a `]:`
688
+ * is a definition to Telegram, and is kept only at the top level after
689
+ * a blank line or another definition, with a label that starts the
690
+ * line, holds no other bracket, code span, autolink or escaped `]`, is
691
+ * not blank or a footnote's and is at most 999 characters, and with
692
+ * nothing after its destination but a title. Otherwise its `[` is
693
+ * escaped. Either needs balanced parentheses and no control character
694
+ * in its destination. Its destination is sent as Telegram reads it,
695
+ * verbatim, and its title is dropped.
696
+ * - A `*`, `_` or `~` run with space on both sides is escaped, outside a
697
+ * thematic break: Telegram would open emphasis with it.
698
+ * - Code spans, `[` that could open a link or reference, and footnote
699
+ * references past `maxInlineNodes` in a paragraph, or footnote
700
+ * references past `maxFootnoteReferences` in the message, are text. A
701
+ * `[` that starts a line and is not closed on it is escaped, as it could
702
+ * open a definition whose label ends on a later line.
703
+ * - Container markers and emphasis past 16 levels are escaped. Every
704
+ * delimiter that could open emphasis counts as a level until the
705
+ * paragraph ends, at a blank line or a line that surely starts a block,
706
+ * and a lazy continuation line keeps the paragraph's container depth.
707
+ * - A table keeps its pipes only when its header is at the start of a line
708
+ * after a blank line, a heading or the start of the text, where it can
709
+ * be no paragraph's continuation. A table wider than 20 columns has its
710
+ * pipes escaped. A table ends at a line that may start another block.
711
+ * - `files` references are added at the end, after closing a fence left
712
+ * open.
713
+ *
714
+ * @internal
715
+ */
716
+ export const render = (markdown: string, options: RenderOptions = {}): string => {
717
+ const mentions = options.mentions ?? new Set<string>()
718
+ const lines = markdown.replace(/\r\n?/g, "\n").replace(/\0/g, "\ufffd").split("\n")
719
+ const fenced: Array<boolean> = []
720
+ let fence: Fence | undefined
721
+ let containers = false
722
+ let verbatim = true
723
+ for (const line of lines) {
724
+ if (fence !== undefined) {
725
+ fenced.push(true)
726
+ if (closes(line, fence)) fence = undefined
727
+ continue
728
+ }
729
+ const opened = verbatim ? opens(line) : undefined
730
+ if (opened !== undefined && opened.indent > 0 && containers) verbatim = false
731
+ else if (opened !== undefined) {
732
+ fence = opened
733
+ fenced.push(true)
734
+ continue
735
+ }
736
+ if (container.test(line)) containers = true
737
+ fenced.push(false)
738
+ }
739
+ const tableRows = new Map<number, boolean>()
740
+ const cellLines = new Set<number>()
741
+ for (let i = 0; i + 1 < lines.length; i++) {
742
+ if (fenced[i] || fenced[i + 1] || tableRows.has(i) || blockStart.test(lines[i])) continue
743
+ // Neither row indented, nor the header after a line it could continue.
744
+ if (/^\s/.test(lines[i]) || /^\s/.test(lines[i + 1])) continue
745
+ const above = i === 0 ? "" : lines[i - 1]
746
+ if (!isBlank(above) && !/^#{1,6}(?: |$)/.test(above)) continue
747
+ if (!delimiterRow.test(lines[i + 1]) || !lines[i + 1].includes("|") || !hasPipe(lines[i])) continue
748
+ // A delimiter row that is also a list item ends the paragraph first.
749
+ if (/^ {0,3}-[ \t]+\S/.test(lines[i + 1])) continue
750
+ const columns = cellCount(lines[i])
751
+ if (columns !== cellCount(lines[i + 1])) continue
752
+ let end = i + 2
753
+ while (end < lines.length && !fenced[end] && !isBlank(lines[end]) && !blockStart.test(lines[end])) end++
754
+ const rows = Array.from({ length: end - i }, (_, k) => i + k)
755
+ for (const row of rows) tableRows.set(row, columns > maxColumns || cellCount(lines[row]) > maxColumns)
756
+ // GFM ends a table at fewer lines than `blockStart` names, so a line
757
+ // past its rows here may still be one of its rows there.
758
+ for (let k = end; k < lines.length && !fenced[k] && !isBlank(lines[k]); k++) cellLines.add(k)
759
+ i = end - 1
760
+ }
761
+ const inline: Inline = { open: 0, containers: 0, nodes: 0 }
762
+ const footnotes = { count: 0 }
763
+ const definitions = { allowed: true }
764
+ let item: string | undefined
765
+ // Whether every line since the last blank one is plain text at the top
766
+ // level: no container, definition, table or other block that a `=` under
767
+ // it could be the lazy continuation of.
768
+ let plain = true
769
+ const out = lines.map((line, i) => {
770
+ const blank = isBlank(line)
771
+ const setext = plain && i > 0 && !isBlank(lines[i - 1]) && /^ {0,3}=+[ \t]*$/.test(line)
772
+ plain = !fenced[i] && (blank || (plain && !/^\s/.test(line) && !blockStart.test(line) && !line.includes("|")))
773
+ if (fenced[i]) {
774
+ definitions.allowed = false
775
+ return line
776
+ }
777
+ const wide = tableRows.get(i)
778
+ const starts = blank ? undefined : startsBlock(line, item)
779
+ item = typeof starts === "string" ? starts : undefined
780
+ if (blank || starts !== undefined || wide !== undefined) {
781
+ inline.open = 0
782
+ inline.containers = 0
783
+ inline.nodes = 0
784
+ }
785
+ const rendered = renderLine(line, {
786
+ tableRow: wide !== undefined,
787
+ cells: wide !== undefined || cellLines.has(i),
788
+ widePipes: wide === true,
789
+ setext,
790
+ inline,
791
+ mentions,
792
+ footnotes,
793
+ definitions
794
+ })
795
+ if (blank) definitions.allowed = true
796
+ return rendered
797
+ })
798
+ let text = out.join("\n")
799
+ const files = options.files ?? 0
800
+ if (files > 0) {
801
+ if (fence !== undefined) text += "\n" + fence.char.repeat(fence.length)
802
+ for (let n = 1; n <= files; n++) text += mediaReference(n)
803
+ }
804
+ return text
805
+ }