@effect/chat-teams 0.0.0 → 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 (162) hide show
  1. package/AGENTS.md +434 -0
  2. package/CLAUDE.md +434 -0
  3. package/LICENSE +21 -0
  4. package/README.md +116 -0
  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/TeamsChat.d.ts +318 -0
  88. package/dist/TeamsChat.d.ts.map +1 -0
  89. package/dist/TeamsChat.js +316 -0
  90. package/dist/TeamsChat.js.map +1 -0
  91. package/dist/index.d.ts +10 -0
  92. package/dist/index.d.ts.map +1 -0
  93. package/dist/index.js +11 -0
  94. package/dist/index.js.map +1 -0
  95. package/dist/internal/adapter.d.ts +2 -0
  96. package/dist/internal/adapter.d.ts.map +1 -0
  97. package/dist/internal/adapter.js +300 -0
  98. package/dist/internal/adapter.js.map +1 -0
  99. package/dist/internal/address.d.ts +2 -0
  100. package/dist/internal/address.d.ts.map +1 -0
  101. package/dist/internal/address.js +52 -0
  102. package/dist/internal/address.js.map +1 -0
  103. package/dist/internal/auth.d.ts +2 -0
  104. package/dist/internal/auth.d.ts.map +1 -0
  105. package/dist/internal/auth.js +142 -0
  106. package/dist/internal/auth.js.map +1 -0
  107. package/dist/internal/connector.d.ts +2 -0
  108. package/dist/internal/connector.d.ts.map +1 -0
  109. package/dist/internal/connector.js +173 -0
  110. package/dist/internal/connector.js.map +1 -0
  111. package/dist/internal/download.d.ts +5 -0
  112. package/dist/internal/download.d.ts.map +1 -0
  113. package/dist/internal/download.js +183 -0
  114. package/dist/internal/download.js.map +1 -0
  115. package/dist/internal/envelope.d.ts +2 -0
  116. package/dist/internal/envelope.d.ts.map +1 -0
  117. package/dist/internal/envelope.js +337 -0
  118. package/dist/internal/envelope.js.map +1 -0
  119. package/dist/internal/errors.d.ts +2 -0
  120. package/dist/internal/errors.d.ts.map +1 -0
  121. package/dist/internal/errors.js +113 -0
  122. package/dist/internal/errors.js.map +1 -0
  123. package/dist/internal/interactions.d.ts +2 -0
  124. package/dist/internal/interactions.d.ts.map +1 -0
  125. package/dist/internal/interactions.js +288 -0
  126. package/dist/internal/interactions.js.map +1 -0
  127. package/dist/internal/length.d.ts +2 -0
  128. package/dist/internal/length.d.ts.map +1 -0
  129. package/dist/internal/length.js +147 -0
  130. package/dist/internal/length.js.map +1 -0
  131. package/dist/internal/normalize.d.ts +2 -0
  132. package/dist/internal/normalize.d.ts.map +1 -0
  133. package/dist/internal/normalize.js +224 -0
  134. package/dist/internal/normalize.js.map +1 -0
  135. package/dist/internal/parse.d.ts +2 -0
  136. package/dist/internal/parse.d.ts.map +1 -0
  137. package/dist/internal/parse.js +33 -0
  138. package/dist/internal/parse.js.map +1 -0
  139. package/dist/internal/render.d.ts +2 -0
  140. package/dist/internal/render.d.ts.map +1 -0
  141. package/dist/internal/render.js +316 -0
  142. package/dist/internal/render.js.map +1 -0
  143. package/dist/internal/webhook.d.ts +2 -0
  144. package/dist/internal/webhook.d.ts.map +1 -0
  145. package/dist/internal/webhook.js +88 -0
  146. package/dist/internal/webhook.js.map +1 -0
  147. package/package.json +61 -1
  148. package/src/TeamsChat.ts +470 -0
  149. package/src/index.ts +12 -0
  150. package/src/internal/adapter.ts +351 -0
  151. package/src/internal/address.ts +67 -0
  152. package/src/internal/auth.ts +192 -0
  153. package/src/internal/connector.ts +253 -0
  154. package/src/internal/download.ts +277 -0
  155. package/src/internal/envelope.ts +427 -0
  156. package/src/internal/errors.ts +94 -0
  157. package/src/internal/interactions.ts +294 -0
  158. package/src/internal/length.ts +170 -0
  159. package/src/internal/normalize.ts +232 -0
  160. package/src/internal/parse.ts +41 -0
  161. package/src/internal/render.ts +318 -0
  162. package/src/internal/webhook.ts +117 -0
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Readers for untrusted input: fields of parsed JSON, and URLs.
3
+ */
4
+ import * as Predicate from "effect/Predicate"
5
+ import type * as Schema from "effect/Schema"
6
+
7
+ /** @internal */
8
+ export type JsonObject = { readonly [key: string]: Schema.Json }
9
+
10
+ /** @internal */
11
+ export const isObject = (u: unknown): u is JsonObject => Predicate.isObject(u)
12
+
13
+ /** A non-empty string field of `value`, when `value` is an object. @internal */
14
+ export const string = (value: unknown, key: string): string | undefined => {
15
+ const field = isObject(value) ? value[key] : undefined
16
+ return typeof field === "string" && field.length > 0 ? field : undefined
17
+ }
18
+
19
+ /** An object field of `value`, when `value` is an object. @internal */
20
+ export const object = (value: unknown, key: string): JsonObject | undefined => {
21
+ const field = isObject(value) ? value[key] : undefined
22
+ return isObject(field) ? field : undefined
23
+ }
24
+
25
+ /** The JSON value of `text`, or `undefined` when it is not JSON. @internal */
26
+ export const parseJson = (text: string): unknown => {
27
+ try {
28
+ return JSON.parse(text)
29
+ } catch {
30
+ return undefined
31
+ }
32
+ }
33
+
34
+ /** @internal */
35
+ export const parseUrl = (input: string, base?: string): URL | undefined => {
36
+ try {
37
+ return new URL(input, base)
38
+ } catch {
39
+ return undefined
40
+ }
41
+ }
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Renders Markdown as a Bot Framework activity for Teams. A message is sent
3
+ * in one of two forms, never mixed: text, when it has no actions, and an
4
+ * Adaptive Card, when it has.
5
+ *
6
+ * The renderer keeps to the rules that make `Length.measure` an upper
7
+ * bound: a source line gives at most one element, a table row has at most
8
+ * one cell more than it has pipes, each source unit is sent at most once,
9
+ * and nothing is sent beyond the templates below and the source text.
10
+ */
11
+ import type { Action, Button, LinkButton } from "effect/chat/ChatUi"
12
+ import { toWellFormed } from "effect/String"
13
+
14
+ /** @internal */
15
+ export const cardContentType = "application/vnd.microsoft.card.adaptive"
16
+
17
+ /**
18
+ * The most actions in one `ActionSet` row: the number of actions Teams
19
+ * shows in a row before it moves the rest into an overflow menu.
20
+ *
21
+ * @internal
22
+ */
23
+ export const actionsPerRow = 6
24
+
25
+ /**
26
+ * Escapes `<` and `&`, so that no HTML tag, `<at>` mention or entity
27
+ * forms in text Teams reads as Markdown.
28
+ *
29
+ * @internal
30
+ */
31
+ export const escapeText = (text: string): string => text.replace(/[<&]/g, (c) => c === "<" ? "&lt;" : "&amp;")
32
+
33
+ /** @internal */
34
+ export const textActivity = (markdown: string): Record<string, unknown> => ({
35
+ type: "message",
36
+ text: escapeDollars(escapeText(toWellFormed(markdown))),
37
+ textFormat: "extendedmarkdown"
38
+ })
39
+
40
+ /** @internal */
41
+ export const textBlock = (text: string) => ({ type: "TextBlock", text, wrap: true })
42
+
43
+ /** @internal */
44
+ export const codeBlock = (codeSnippet: string, language: string) => ({ type: "CodeBlock", codeSnippet, language })
45
+
46
+ /** @internal */
47
+ export const column = { width: 1 }
48
+
49
+ /** @internal */
50
+ export const tableCell = (text: string) => ({ type: "TableCell", items: [textBlock(text)] })
51
+
52
+ /** @internal */
53
+ export const tableRow = (cells: ReadonlyArray<string>) => ({ type: "TableRow", cells: cells.map(tableCell) })
54
+
55
+ /** A table with one column for each cell of its widest row. @internal */
56
+ export const table = (rows: ReadonlyArray<ReadonlyArray<string>>) => ({
57
+ type: "Table",
58
+ firstRowAsHeaders: true,
59
+ columns: Array.from({ length: Math.max(0, ...rows.map((row) => row.length)) }, () => column),
60
+ rows: rows.map(tableRow)
61
+ })
62
+
63
+ /** @internal */
64
+ export const actionSet = (actions: ReadonlyArray<unknown>) => ({ type: "ActionSet", actions })
65
+
66
+ /** @internal */
67
+ export const card = (body: ReadonlyArray<unknown>) => ({
68
+ type: "AdaptiveCard",
69
+ version: "1.5",
70
+ body,
71
+ msteams: { width: "Full" }
72
+ })
73
+
74
+ /** @internal */
75
+ export const cardActivityOf = (body: ReadonlyArray<unknown>): Record<string, unknown> => ({
76
+ type: "message",
77
+ attachments: [{ contentType: cardContentType, content: card(body) }]
78
+ })
79
+
80
+ const styles = { primary: "positive", danger: "destructive" } as const
81
+
82
+ /**
83
+ * `Action.Execute`, with `Action.Submit` as the fallback for clients
84
+ * without Universal Actions. `token` carries the button's id and value.
85
+ *
86
+ * @internal
87
+ */
88
+ export const buttonAction = (button: Button, token: string) => {
89
+ const title = toWellFormed(button.label)
90
+ const style = button.style === "primary" || button.style === "danger" ? { style: styles[button.style] } : {}
91
+ return {
92
+ type: "Action.Execute",
93
+ title,
94
+ verb: "effect",
95
+ data: { effect: token },
96
+ ...style,
97
+ fallback: { type: "Action.Submit", title, data: { effect: token } }
98
+ }
99
+ }
100
+
101
+ /**
102
+ * A button that opens a dialog: an `Action.Submit` with `task/fetch`,
103
+ * smaller than the `Action.Execute` and fallback the measure prices.
104
+ *
105
+ * @internal
106
+ */
107
+ export const dialogAction = (button: Button, token: string) => ({
108
+ type: "Action.Submit",
109
+ title: toWellFormed(button.label),
110
+ data: { msteams: { type: "task/fetch" }, effect: token }
111
+ })
112
+
113
+ /** @internal */
114
+ export const linkAction = (link: LinkButton) => ({
115
+ type: "Action.OpenUrl",
116
+ title: toWellFormed(link.label),
117
+ url: toWellFormed(link.url)
118
+ })
119
+
120
+ /**
121
+ * The card form. Selects are not rendered: the adapter refuses them first.
122
+ *
123
+ * @internal
124
+ */
125
+ export const cardActivity = (
126
+ markdown: string,
127
+ actions: ReadonlyArray<Action>,
128
+ encode: (button: Button) => string,
129
+ opensDialog: (button: Button) => boolean = () => false
130
+ ): Record<string, unknown> => {
131
+ const body: Array<unknown> = blocks(markdown)
132
+ const rendered: Array<unknown> = []
133
+ for (const action of actions) {
134
+ if (action._tag === "Button") {
135
+ rendered.push(opensDialog(action) ? dialogAction(action, encode(action)) : buttonAction(action, encode(action)))
136
+ } else if (action._tag === "LinkButton") rendered.push(linkAction(action))
137
+ }
138
+ for (let i = 0; i < rendered.length; i += actionsPerRow) {
139
+ body.push(actionSet(rendered.slice(i, i + actionsPerRow)))
140
+ }
141
+ return cardActivityOf(body)
142
+ }
143
+
144
+ interface Fence {
145
+ readonly indent: number
146
+ readonly marker: string
147
+ readonly language: string
148
+ }
149
+
150
+ const fenceOpen = (line: string): Fence | undefined => {
151
+ const match = /^( {0,3})(`{3,}|~{3,})(.*)$/.exec(line)
152
+ if (match === null) return undefined
153
+ const [, spaces, marker, info] = match
154
+ if (marker[0] === "`" && info.includes("`")) return undefined
155
+ const word = info.trim().split(/\s+/)[0]
156
+ return { indent: spaces.length, marker, language: word === "" ? "PlainText" : word }
157
+ }
158
+
159
+ const stripFenceIndent = (line: string, indent: number): string => {
160
+ let i = 0
161
+ while (i < indent && line[i] === " ") i++
162
+ // An opening fence is at most three columns in, so a tab crossed here ends at column four.
163
+ if (i < indent && line[i] === "\t") return " ".repeat(4 - indent) + line.slice(i + 1)
164
+ return line.slice(i)
165
+ }
166
+
167
+ const fenceCloses = (fence: Fence, line: string): boolean => {
168
+ const match = /^ {0,3}(`{3,}|~{3,})[ \t]*$/.exec(line)
169
+ return match !== null && match[1][0] === fence.marker[0] && match[1].length >= fence.marker.length
170
+ }
171
+
172
+ /**
173
+ * Escapes each `$` outside code as `\$`, so that Teams reads no math in
174
+ * the text form. A `$` the Markdown already escapes, after an odd run of
175
+ * backslashes, is left alone, and so is code: fenced blocks and code spans
176
+ * on one line. One unit per `$` at most, as `Length.weight` prices it.
177
+ *
178
+ * @internal
179
+ */
180
+ export const escapeDollars = (markdown: string): string => {
181
+ const parts = markdown.split(/(\r\n|\r|\n)/)
182
+ let fence: Fence | undefined
183
+ for (let i = 0; i < parts.length; i += 2) {
184
+ const line = parts[i]
185
+ if (fence !== undefined) {
186
+ if (fenceCloses(fence, line)) fence = undefined
187
+ continue
188
+ }
189
+ fence = fenceOpen(line)
190
+ if (fence === undefined) parts[i] = escapeLine(line)
191
+ }
192
+ return parts.join("")
193
+ }
194
+
195
+ const escapeLine = (line: string): string => {
196
+ let out = ""
197
+ let i = 0
198
+ while (i < line.length) {
199
+ const char = line[i]
200
+ if (char === "`") {
201
+ let run = 1
202
+ while (line[i + run] === "`") run++
203
+ const ticks = "`".repeat(run)
204
+ const close = findRun(line, ticks, i + run)
205
+ const end = close === -1 ? i + run : close + run
206
+ out += line.slice(i, end)
207
+ i = end
208
+ continue
209
+ }
210
+ if (char === "$") {
211
+ let backslashes = 0
212
+ while (line[i - 1 - backslashes] === "\\") backslashes++
213
+ out += backslashes % 2 === 0 ? "\\$" : "$"
214
+ } else out += char
215
+ i++
216
+ }
217
+ return out
218
+ }
219
+
220
+ /** The index of a run of exactly `ticks` from `from`, or -1. */
221
+ const findRun = (line: string, ticks: string, from: number): number => {
222
+ for (let at = line.indexOf(ticks, from); at !== -1; at = line.indexOf(ticks, at + 1)) {
223
+ if (line[at - 1] !== "`" && line[at + ticks.length] !== "`") return at
224
+ }
225
+ return -1
226
+ }
227
+
228
+ const delimiterRow = /^[ \t]*\|?(?:[ \t]*:?-+:?[ \t]*\|)*[ \t]*:?-+:?[ \t]*\|?[ \t]*$/
229
+
230
+ const isDelimiter = (line: string): boolean => line.includes("|") && delimiterRow.test(line)
231
+
232
+ /** The cells of a table row. There are never more than its pipes plus one. */
233
+ const cells = (line: string): Array<string> => {
234
+ let row = line.trim()
235
+ if (row.startsWith("|")) row = row.slice(1)
236
+ if (row.endsWith("|") && !row.endsWith("\\|")) row = row.slice(0, -1)
237
+ return row.split(/(?<!\\)\|/).map((cell) => escapeText(cell.trim().replace(/\\\|/g, "|")))
238
+ }
239
+
240
+ /**
241
+ * One line of a paragraph, with the block syntax a TextBlock cannot show
242
+ * taken off: quote markers and heading markers are dropped, and the first
243
+ * list marker is kept. `> - # x` becomes `- x`.
244
+ */
245
+ const flatten = (line: string): string => {
246
+ let rest = line
247
+ let marker = ""
248
+ for (;;) {
249
+ const quote = /^ {0,3}> ?/.exec(rest)
250
+ if (quote !== null) {
251
+ rest = rest.slice(quote[0].length)
252
+ continue
253
+ }
254
+ if (marker === "") {
255
+ const list = /^[ \t]*(?:[-*+]|\d{1,9}[.)])(?:[ \t]+|$)/.exec(rest)
256
+ if (list !== null) {
257
+ marker = list[0]
258
+ rest = rest.slice(marker.length)
259
+ continue
260
+ }
261
+ }
262
+ const heading = /^ {0,3}#{1,6}(?:[ \t]+|$)/.exec(rest)
263
+ if (heading !== null) {
264
+ rest = rest.slice(heading[0].length)
265
+ continue
266
+ }
267
+ return marker + rest
268
+ }
269
+ }
270
+
271
+ /**
272
+ * The card body for Markdown: `TextBlock`, `CodeBlock` and `Table`
273
+ * elements in the order of the source. Consecutive lines of text share one
274
+ * `TextBlock`, joined by `\n`.
275
+ *
276
+ * @internal
277
+ */
278
+ export const blocks = (markdown: string): Array<unknown> => {
279
+ const lines = toWellFormed(markdown).split(/\r\n|\r|\n/)
280
+ const body: Array<unknown> = []
281
+ let text: Array<string> = []
282
+ const flush = () => {
283
+ let start = 0
284
+ let end = text.length
285
+ while (start < end && text[start].trim() === "") start++
286
+ while (end > start && text[end - 1].trim() === "") end--
287
+ if (start < end) body.push(textBlock(escapeText(text.slice(start, end).join("\n"))))
288
+ text = []
289
+ }
290
+ let i = 0
291
+ while (i < lines.length) {
292
+ const line = lines[i]
293
+ const fence = fenceOpen(line)
294
+ if (fence !== undefined) {
295
+ flush()
296
+ const code: Array<string> = []
297
+ i++
298
+ while (i < lines.length && !fenceCloses(fence, lines[i])) code.push(stripFenceIndent(lines[i++], fence.indent))
299
+ i++
300
+ body.push(codeBlock(code.join("\n"), fence.language))
301
+ continue
302
+ }
303
+ if (line.includes("|") && i + 1 < lines.length && isDelimiter(lines[i + 1])) {
304
+ flush()
305
+ const rows = [cells(line)]
306
+ i += 2
307
+ while (i < lines.length && lines[i].includes("|") && fenceOpen(lines[i]) === undefined) {
308
+ rows.push(cells(lines[i++]))
309
+ }
310
+ body.push(table(rows))
311
+ continue
312
+ }
313
+ text.push(flatten(line))
314
+ i++
315
+ }
316
+ flush()
317
+ return body
318
+ }
@@ -0,0 +1,117 @@
1
+ import * as ByteSize from "effect/ByteSize"
2
+ import type * as ChatEvent from "effect/chat/ChatEvent"
3
+ import type { NotAccepted } from "effect/chat/ChatHandler"
4
+ import type * as Duration from "effect/Duration"
5
+ import * as Effect from "effect/Effect"
6
+ import * as HttpIncomingMessage from "effect/http/HttpIncomingMessage"
7
+ import type * as HttpServerRequest from "effect/http/HttpServerRequest"
8
+ import * as HttpServerResponse from "effect/http/HttpServerResponse"
9
+ import * as Option from "effect/Option"
10
+ import * as Result from "effect/Result"
11
+ import { type Activity, tenantOf, type Verdict } from "./auth.ts"
12
+ import type { InvokeResponse } from "./interactions.ts"
13
+ import { isSubmitFallback } from "./interactions.ts"
14
+ import { type Context, isTargeted, normalize } from "./normalize.ts"
15
+ import { isObject, type JsonObject, parseJson } from "./parse.ts"
16
+
17
+ const status = (code: number) => HttpServerResponse.empty({ status: code })
18
+
19
+ /**
20
+ * What is logged with each 503 of the route.
21
+ *
22
+ * @internal
23
+ */
24
+ export const unavailable = {
25
+ keys: "teams webhook: the signing keys could not be read, answered 503",
26
+ normalize: "teams webhook: the activity could not be normalised, answered 503",
27
+ notAccepted: "teams webhook: the handler refused the event, answered 503",
28
+ deadline: "teams webhook: the request passed its deadline, answered 503"
29
+ } as const
30
+
31
+ /** @internal */
32
+ export interface Options {
33
+ readonly verify: (authorization: string | undefined, activity: Activity) => Effect.Effect<Verdict>
34
+ readonly context: Context
35
+ readonly handle: (event: ChatEvent.ChatEvent) => Effect.Effect<void, NotAccepted>
36
+ readonly onUnhandled: (activity: JsonObject) => Effect.Effect<void>
37
+ readonly invoke: (activity: JsonObject) => Effect.Effect<InvokeResponse>
38
+ readonly command: (activity: JsonObject) => Effect.Effect<void>
39
+ readonly deadline: Duration.Input
40
+ readonly maxBodySize: ByteSize.ByteSize
41
+ }
42
+
43
+ const decoder = new TextDecoder()
44
+
45
+ const respond = (response: InvokeResponse) =>
46
+ response.body === undefined
47
+ ? status(response.status)
48
+ : HttpServerResponse.jsonUnsafe(response.body, { status: response.status })
49
+
50
+ /**
51
+ * One Bot Framework activity.
52
+ *
53
+ * - 413 past the body limit, 400 for a body that is not a JSON object.
54
+ * - 403 when the token, its `serviceurl`, the channel or the tenant does
55
+ * not check out, and 503 when the signing keys can't be read.
56
+ * - A targeted activity is classified first, whatever its type: a message
57
+ * takes the command path, an invoke goes to the interaction handler, and
58
+ * anything else is answered 200 and dropped. None reaches `ChatHandler`
59
+ * or `onUnhandled`.
60
+ * - An invoke, or a card's submit fallback, goes to the interaction
61
+ * handler, whose answer is the response.
62
+ * - Every other activity is normalised and handed to the `ChatHandler`
63
+ * one event at a time: 200 when all succeed, 503 when one fails
64
+ * `NotAccepted`, or when a `message` can't be normalised. Any other
65
+ * activity that gives no event goes to `onUnhandled` and is answered 200.
66
+ * - 503 past `deadline`, the handler interrupted. Each 503 is logged with
67
+ * its own message.
68
+ *
69
+ * @internal
70
+ */
71
+ export const handleRequest = (
72
+ request: HttpServerRequest.HttpServerRequest,
73
+ options: Options
74
+ ): Effect.Effect<HttpServerResponse.HttpServerResponse> =>
75
+ Effect.gen(function*() {
76
+ const read = yield* request.arrayBuffer.pipe(
77
+ Effect.provideService(HttpIncomingMessage.MaxBodySize, options.maxBodySize),
78
+ Effect.result
79
+ )
80
+ if (Result.isFailure(read)) {
81
+ const { reason } = read.failure
82
+ return status(reason._tag === "RequestParseError" && reason.reason === "BodyTooLarge" ? 413 : 400)
83
+ }
84
+ // Measured again: the request caches its body, so one read earlier under a larger limit comes back whole.
85
+ if (read.success.byteLength > ByteSize.toNumberUnsafe(options.maxBodySize)) return status(413)
86
+ const activity = parseJson(decoder.decode(read.success))
87
+ if (!isObject(activity)) return status(400)
88
+ const verdict = yield* options.verify(request.headers.authorization, {
89
+ serviceUrl: activity.serviceUrl,
90
+ channelId: activity.channelId,
91
+ tenantId: tenantOf(activity)
92
+ })
93
+ if (verdict === "forbidden") return status(403)
94
+ if (verdict === "unavailable") return yield* Effect.as(Effect.logWarning(unavailable.keys), status(503))
95
+ if (isTargeted(activity)) {
96
+ if (activity.type === "message") return yield* Effect.as(options.command(activity), status(200))
97
+ if (activity.type === "invoke") return respond(yield* options.invoke(activity))
98
+ return status(200)
99
+ }
100
+ if (activity.type === "invoke") return respond(yield* options.invoke(activity))
101
+ if (isSubmitFallback(activity)) return respond(yield* options.invoke(activity))
102
+ const events = normalize(activity, options.context)
103
+ if (events.length === 0 && activity.type === "message") {
104
+ return yield* Effect.as(Effect.logWarning(unavailable.normalize), status(503))
105
+ }
106
+ if (events.length === 0) return yield* Effect.as(options.onUnhandled(activity), status(200))
107
+ return yield* Effect.forEach(events, options.handle, { discard: true }).pipe(
108
+ Effect.as(status(200)),
109
+ Effect.catchTag("NotAccepted", () => Effect.as(Effect.logWarning(unavailable.notAccepted), status(503)))
110
+ )
111
+ }).pipe(
112
+ Effect.timeoutOption(options.deadline),
113
+ Effect.flatMap(Option.match({
114
+ onNone: () => Effect.as(Effect.logWarning(unavailable.deadline), status(503)),
115
+ onSome: Effect.succeed
116
+ }))
117
+ )