@yaks/mail 0.0.0-stage → 0.2.36

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 (131) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +676 -2
  3. package/_dist/addr.d.ts +40 -0
  4. package/_dist/addr.d.ts.map +1 -0
  5. package/_dist/answers.d.ts +18 -0
  6. package/_dist/answers.d.ts.map +1 -0
  7. package/_dist/arrive.d.ts +64 -0
  8. package/_dist/arrive.d.ts.map +1 -0
  9. package/_dist/capture.d.ts +22 -0
  10. package/_dist/capture.d.ts.map +1 -0
  11. package/_dist/comp.d.ts +27 -0
  12. package/_dist/comp.d.ts.map +1 -0
  13. package/_dist/effects.d.ts +9 -0
  14. package/_dist/effects.d.ts.map +1 -0
  15. package/_dist/gmail.d.ts +16 -0
  16. package/_dist/gmail.d.ts.map +1 -0
  17. package/_dist/graph.d.ts +9 -0
  18. package/_dist/graph.d.ts.map +1 -0
  19. package/_dist/inbound.d.ts +105 -0
  20. package/_dist/inbound.d.ts.map +1 -0
  21. package/_dist/invite.d.ts +69 -0
  22. package/_dist/invite.d.ts.map +1 -0
  23. package/_dist/md.d.ts +34 -0
  24. package/_dist/md.d.ts.map +1 -0
  25. package/_dist/mod.d.ts +109 -0
  26. package/_dist/mod.d.ts.map +1 -0
  27. package/_dist/options.d.ts +38 -0
  28. package/_dist/options.d.ts.map +1 -0
  29. package/_dist/plugin.d.ts +38 -0
  30. package/_dist/plugin.d.ts.map +1 -0
  31. package/_dist/pull.d.ts +99 -0
  32. package/_dist/pull.d.ts.map +1 -0
  33. package/_dist/receipts.d.ts +8 -0
  34. package/_dist/receipts.d.ts.map +1 -0
  35. package/_dist/recipient.d.ts +24 -0
  36. package/_dist/recipient.d.ts.map +1 -0
  37. package/_dist/routes.d.ts +19 -0
  38. package/_dist/routes.d.ts.map +1 -0
  39. package/_dist/send.d.ts +80 -0
  40. package/_dist/send.d.ts.map +1 -0
  41. package/_dist/service.d.ts +14 -0
  42. package/_dist/service.d.ts.map +1 -0
  43. package/_dist/stash.d.ts +23 -0
  44. package/_dist/stash.d.ts.map +1 -0
  45. package/_dist/tools.d.ts +27 -0
  46. package/_dist/tools.d.ts.map +1 -0
  47. package/_dist/transport.d.ts +6 -0
  48. package/_dist/transport.d.ts.map +1 -0
  49. package/_dist/vocab.d.ts +7 -0
  50. package/_dist/vocab.d.ts.map +1 -0
  51. package/addr.js +92 -0
  52. package/addr.js.map +1 -0
  53. package/addr.ts +106 -0
  54. package/answers.js +71 -0
  55. package/answers.js.map +1 -0
  56. package/answers.ts +95 -0
  57. package/arrive.js +122 -0
  58. package/arrive.js.map +1 -0
  59. package/arrive.ts +198 -0
  60. package/capture.js +21 -0
  61. package/capture.js.map +1 -0
  62. package/capture.ts +43 -0
  63. package/comp.js +76 -0
  64. package/comp.js.map +1 -0
  65. package/comp.ts +91 -0
  66. package/deno.json +1 -0
  67. package/effects.js +90 -0
  68. package/effects.js.map +1 -0
  69. package/effects.ts +90 -0
  70. package/gmail.js +262 -0
  71. package/gmail.js.map +1 -0
  72. package/gmail.ts +314 -0
  73. package/graph.js +26 -0
  74. package/graph.js.map +1 -0
  75. package/graph.ts +30 -0
  76. package/inbound.js +206 -0
  77. package/inbound.js.map +1 -0
  78. package/inbound.ts +238 -0
  79. package/invite.js +102 -0
  80. package/invite.js.map +1 -0
  81. package/invite.ts +143 -0
  82. package/md.js +188 -0
  83. package/md.js.map +1 -0
  84. package/md.ts +245 -0
  85. package/mod.js +109 -0
  86. package/mod.js.map +1 -0
  87. package/mod.ts +111 -0
  88. package/options.js +24 -0
  89. package/options.js.map +1 -0
  90. package/options.ts +83 -0
  91. package/package.json +66 -4
  92. package/plugin.js +97 -0
  93. package/plugin.js.map +1 -0
  94. package/plugin.ts +88 -0
  95. package/pull.js +344 -0
  96. package/pull.js.map +1 -0
  97. package/pull.ts +443 -0
  98. package/readings.js +24 -0
  99. package/readings.js.map +1 -0
  100. package/readings.ts +34 -0
  101. package/receipts.js +45 -0
  102. package/receipts.js.map +1 -0
  103. package/receipts.ts +45 -0
  104. package/recipient.js +92 -0
  105. package/recipient.js.map +1 -0
  106. package/recipient.ts +89 -0
  107. package/routes.js +103 -0
  108. package/routes.js.map +1 -0
  109. package/routes.ts +125 -0
  110. package/send.js +284 -0
  111. package/send.js.map +1 -0
  112. package/send.ts +325 -0
  113. package/service.js +64 -0
  114. package/service.js.map +1 -0
  115. package/service.ts +75 -0
  116. package/stash.js +29 -0
  117. package/stash.js.map +1 -0
  118. package/stash.ts +49 -0
  119. package/tools.js +343 -0
  120. package/tools.js.map +1 -0
  121. package/tools.ts +416 -0
  122. package/transport.js +23 -0
  123. package/transport.js.map +1 -0
  124. package/transport.ts +24 -0
  125. package/vocab.js +14 -0
  126. package/vocab.js.map +1 -0
  127. package/vocab.json +415 -0
  128. package/vocab.ts +16 -0
  129. package/work.js +121 -0
  130. package/work.js.map +1 -0
  131. package/work.ts +134 -0
package/inbound.ts ADDED
@@ -0,0 +1,238 @@
1
+ // The other direction: a letter that arrived, as bundles to write.
2
+ //
3
+ // The shape it takes is the one Cloudflare's Email Workers hand a worker (a
4
+ // `ForwardableEmailMessage`), named structurally so nothing here imports a
5
+ // Cloudflare type — ./conform.ts is where that claim is checked against the
6
+ // runtime's own types. Any other source that can say from, to and headers
7
+ // works the same way.
8
+ //
9
+ // Two things this deliberately does not do:
10
+ //
11
+ // It does not parse MIME. The body arrives as a stream of RFC 5322 and
12
+ // turning that into text is a parser's job, not this package's — so pass the
13
+ // text in (`postal-mime` is the usual choice in a Worker) and this composes
14
+ // the entity around it.
15
+ //
16
+ // It does not query the graph. It is pure: a message in, bundles out. Whom
17
+ // the letter is for, and which earlier letter it answers, are lookups — see
18
+ // below — and a pure function is what makes this testable without a storage
19
+ // adapter anywhere.
20
+ //
21
+ // An arrival carries no `deliver`, which is exactly why it can never echo back
22
+ // out: ./send.ts sends the letters that ask to be sent, and an arrival never
23
+ // asks to be sent.
24
+
25
+ import type { Bundle, Eid } from 'jsr:@yaks/graph@0.2.36'
26
+ import { DOC } from '@yaks/doc'
27
+ import { MAIL } from './comp.js'
28
+
29
+ /** The head of a received message — a web `Headers` satisfies this. */
30
+ export type Head = { get: (name: string) => string | null }
31
+
32
+ /** A received message: the slice of an Email Workers message this reads. */
33
+ export type Received = {
34
+ /** the envelope sender — SMTP plumbing, often a bounce address */
35
+ from: string
36
+ /** the address it was delivered to */
37
+ to: string
38
+ /** its headers */
39
+ headers: Head
40
+ }
41
+
42
+ /** What the caller knows and the message does not. */
43
+ export type Arrival = {
44
+ /** the body as text, once something has parsed the MIME */
45
+ text?: string
46
+ /** the id to record it under (default: a fresh uuid) */
47
+ eid?: Eid
48
+ /** the entity the letter is about — the recipient, a thread, a task */
49
+ target?: Eid
50
+ /** the letter this one answers, once something has looked up which letter
51
+ * the `in-reply-to` header names (./arrive.ts `known`) */
52
+ reply?: Eid
53
+ /** when it arrived (default: the Date header, else now) */
54
+ at?: string
55
+ /**
56
+ * whether the sending domain signed for it — the receiving MTA's verdict,
57
+ * which only the caller has. Left out, the letter records none; `false` is
58
+ * recorded and never a reason to drop the letter (see {@link verdict}).
59
+ */
60
+ verified?: boolean
61
+ /** the receiving edge authenticated the From address itself: DMARC, or
62
+ * DKIM by the From domain, aligned with it. Only this names the letter's
63
+ * author (./arrive.ts); a From header alone is anyone's to write. */
64
+ vouched?: boolean
65
+ }
66
+
67
+ /**
68
+ * The DKIM verdict off an `Authentication-Results` header, as every receiving
69
+ * MTA writes one: `true` only where the header says `dkim=pass`, `null` where
70
+ * there is no header to read at all — nobody checked, which is not the same as
71
+ * a check that failed.
72
+ *
73
+ * ```ts
74
+ * import { verdict } from '@yaks/mail'
75
+ * let head = (v: string | null) => ({ get: () => v })
76
+ * verdict(head('mx.example; dkim=pass header.i=@books.example; spf=pass')) // true
77
+ * verdict(head('mx.example; dkim=fail; spf=pass')) // false
78
+ * verdict(head(null)) // null
79
+ * ```
80
+ */
81
+ export let verdict = (m: Head): boolean | null => {
82
+ let said = m.get('authentication-results')
83
+ return said == null ? null : /\bdkim\s*=\s*pass\b/i.test(said)
84
+ }
85
+
86
+ /**
87
+ * Who wrote the letter, from the `From:` header.
88
+ *
89
+ * The envelope `from` is not the author: a relay stamps its own bounce address
90
+ * there, so a reply aimed at it reaches a bounce sink rather than a person.
91
+ * The header is the author, in either of its two shapes — `Ana <ana@x.example>`
92
+ * or a bare address — and the envelope is the fallback when there is no header
93
+ * at all.
94
+ */
95
+ export let author = (m: Received): string =>
96
+ addressIn(m.headers.get('from')) || m.from
97
+
98
+ /**
99
+ * Whom an answer goes to, from the `Reply-To:` header: the first address it
100
+ * names, or `''` when it names none. A relay (a feedback form, a list) writes
101
+ * for somebody else, so its `From:` is the relay and this is the person. A
102
+ * list's first reader is enough, the way a mail client's Reply answers one.
103
+ *
104
+ * ```ts
105
+ * import { answerer } from '@yaks/mail'
106
+ * let said = (v: string | null) => ({ from: '', to: '', headers: { get: () => v } })
107
+ * answerer(said('Ana <ana@x.example>, bo@x.example')) // 'ana@x.example'
108
+ * answerer(said('ana@x.example')) // 'ana@x.example'
109
+ * answerer(said(null)) // ''
110
+ * ```
111
+ */
112
+ export let answerer = (m: Received): string =>
113
+ addressIn(m.headers.get('reply-to')?.split(',')[0])
114
+
115
+ // One address out of a header's either shape, `Ana <ana@x.example>` or bare.
116
+ let addressIn = (said: string | null | undefined): string => {
117
+ let head = (said ?? '').trim()
118
+ let angled = /<([^<>\s]+@[^<>\s]+)>/.exec(head)
119
+ return angled?.[1] ?? (/^\S+@\S+$/.test(head) ? head : '')
120
+ }
121
+
122
+ /**
123
+ * The words a letter's author wrote: its text without the quote of somebody
124
+ * else's letter, which a mail client sets below a reply (or between its
125
+ * lines). A person's letter then never carries another's words as theirs; the
126
+ * letter it quotes is the one its `in-reply-to` names, kept where it was.
127
+ *
128
+ * A quote is known by the line a client introduces it with: `On <date>,
129
+ * <name> <address> wrote:` (which some clients wrap over two lines), or an
130
+ * Outlook header block, `From:` then `Sent:` or `Date:`, or `-----Original
131
+ * Message-----`. Where that line names the author, the quote is their own
132
+ * earlier letter and stays. Otherwise the quote goes: its `>` lines, wherever
133
+ * they fall after it, or everything after it where its lines carry no `>` (an
134
+ * html letter read as text, an Outlook reply). A letter with no such line is
135
+ * its author's, `>` lines and all.
136
+ *
137
+ * ```ts
138
+ * import { own } from '@yaks/mail'
139
+ * own('ok\n\nOn Fri, Bo <bo@x.example> wrote:\n> Send the keys.', 'ana@x.example')
140
+ * // 'ok'
141
+ * own('ok\n\nOn Fri, Ana <ana@x.example> wrote:\n> My list.', 'ana@x.example')
142
+ * // 'ok\n\nOn Fri, Ana <ana@x.example> wrote:\n> My list.'
143
+ * ```
144
+ */
145
+ export let own = (text: string, author: string): string => {
146
+ let lines = text.split(/\r?\n/)
147
+ let me = author.trim().toLowerCase()
148
+ for (let i = 0; i < lines.length; i++) {
149
+ let span = introduces(lines, i)
150
+ if (!span) continue
151
+ let said = lines.slice(i, i + span.lines).join(' ')
152
+ if (said.match(ADDRESS)?.[0].toLowerCase() == me) {
153
+ i += span.lines - 1
154
+ continue
155
+ }
156
+ let rest = lines.slice(i + span.lines)
157
+ let first = rest.find((l) => l.trim())
158
+ let kept = span.whole || !first?.startsWith('>')
159
+ ? []
160
+ : rest.filter((l) => !l.startsWith('>'))
161
+ return [...lines.slice(0, i), ...kept].join('\n')
162
+ .replace(/\n{3,}/g, '\n\n').trim()
163
+ }
164
+ return text
165
+ }
166
+
167
+ // An address as a quote's introduction writes it: bare, in angles, or
168
+ // after `mailto:`.
169
+ let ADDRESS = /[^\s<>[\]"'(),;:]+@[^\s<>[\]"'(),;:]+/
170
+
171
+ // Whether line `i` introduces a quote, and over how many lines, the last of
172
+ // them naming who wrote it; `whole` where what follows is the quoted letter
173
+ // to its end, `>` or not.
174
+ let introduces = (
175
+ lines: string[],
176
+ i: number,
177
+ ): { lines: number; whole?: boolean } | null => {
178
+ let at = (n: number) => lines[i + n]?.trim() ?? ''
179
+ if (/^-{2,}\s*original message\s*-{2,}$/i.test(at(0))) {
180
+ let from = [1, 2, 3].find((n) => /^from:\s/i.test(at(n)))
181
+ return { lines: (from ?? 0) + 1, whole: true }
182
+ }
183
+ if (/^from:\s/i.test(at(0)) && /^(sent|date):\s/i.test(at(1))) {
184
+ return { lines: 1, whole: true }
185
+ }
186
+ if (!/^on\s/i.test(at(0))) return null
187
+ if (/\swrote:$/i.test(at(0))) return { lines: 1 }
188
+ if (/\swrote:$/i.test(at(1))) return { lines: 2 }
189
+ return null
190
+ }
191
+
192
+ /** The unbracketed Message-ID of a received letter, or `''`. */
193
+ export let messageId = (m: Received): string =>
194
+ (m.headers.get('message-id') ?? '').replace(/[<>]/g, '').trim()
195
+
196
+ /**
197
+ * A received message → the bundles that record it: one entity carrying the
198
+ * envelope it arrived in (`mail`) and the words it carried
199
+ * ({@link https://jsr.io/@yaks/doc | @yaks/doc}'s `doc{title, body}`).
200
+ *
201
+ * ```ts
202
+ * import { inbound } from '@yaks/mail'
203
+ * // in a Worker's email() handler:
204
+ * // let text = await parse(message.raw)
205
+ * // await graph.apply(inbound(message, { text, target: club }))
206
+ * ```
207
+ *
208
+ * Threading is a lookup, so the caller passes in the answer rather than the
209
+ * question: read the `in-reply-to` header, find the letter whose `message_id`
210
+ * matches, and pass it as `reply`. Same for `target` when the recipient
211
+ * address names an entity — query `email.address`, and pass what you find.
212
+ * Both lookups live in ./arrive.ts, which has a graph to query.
213
+ */
214
+ export let inbound = (m: Received, arrival: Arrival = {}): Bundle[] => {
215
+ let at = arrival.at ?? m.headers.get('date') ?? new Date().toISOString()
216
+ let answers = m.headers.get('in-reply-to')
217
+ let answer = answerer(m)
218
+ return [{
219
+ entity: { eid: arrival.eid ?? crypto.randomUUID() },
220
+ [DOC]: {
221
+ title: m.headers.get('subject') || '(no subject)',
222
+ body: arrival.text ?? '',
223
+ },
224
+ [MAIL]: {
225
+ from: author(m),
226
+ to: m.to,
227
+ at,
228
+ message_id: messageId(m),
229
+ ...(arrival.target ? { target: arrival.target } : {}),
230
+ ...(arrival.reply ? { reply_to: arrival.reply } : {}),
231
+ // The header as written, beside `reply_to`: a reply to a letter this
232
+ // graph never kept still says what it answers.
233
+ ...(answers ? { in_reply_to: answers } : {}),
234
+ ...(answer ? { reply_address: answer } : {}),
235
+ ...(arrival.verified == null ? {} : { verified: arrival.verified }),
236
+ },
237
+ }]
238
+ }
package/invite.js ADDED
@@ -0,0 +1,102 @@
1
+ // The worked example: somebody joins, and a letter goes out.
2
+ //
3
+ // This is the handler slot @yaks/member documents and leaves empty. Adding a
4
+ // person to a roster usually means writing to them, but a roster package must
5
+ // not know what a mail server is — so the roster row is written by one package,
6
+ // and the letter about it by this one, joined by nothing but a component name.
7
+ //
8
+ // What makes it worth reading is what it does not do: it does not send
9
+ // anything. It writes a letter into the graph, through the graph's own
10
+ // `apply()`, and the `created(mail)` effect in ./send.ts sends it like any
11
+ // other. So one mechanism carries invitations, receipts, reminders and
12
+ // replies, and an invitation that could not be delivered leaves the same
13
+ // `bounced` component on the same kind of entity as everything else.
14
+ //
15
+ // It refers to the `member` component by name, so this file imports nothing
16
+ // from @yaks/member — the two packages meet at a component name.
17
+ import { DOC } from "@yaks/doc";
18
+ import { DELIVER, MAIL } from "./comp.js";
19
+ let str = (c, k)=>c[k] == null ? '' : String(c[k]);
20
+ /**
21
+ * The `created(member)` handler: write an invitation to whoever just joined.
22
+ *
23
+ * ```ts
24
+ * import { assertEquals } from '@std/assert'
25
+ * import { effects } from '@yaks/effects'
26
+ * import { graph } from '@yaks/graph'
27
+ * import { ram } from '@yaks/ram'
28
+ * import { loadVocab } from '@yaks/vocab'
29
+ * import { docDoc, docs } from '@yaks/doc'
30
+ * import { memberDoc } from '@yaks/member'
31
+ * import { invited, mailbox, mailDoc, stash } from '@yaks/mail'
32
+ *
33
+ * let vocab = loadVocab([docDoc, mailDoc, memberDoc])
34
+ * let fx = effects(vocab, { write: (b) => club.apply(b, { trusted: true }) })
35
+ * let post = stash()
36
+ * let club = graph({
37
+ * storage: ram(vocab),
38
+ * vocab,
39
+ * plugins: [fx, docs(), mailbox({ sender: post, effects: fx })],
40
+ * })
41
+ * fx.created('member', invited({
42
+ * apply: (bundles) => club.apply(bundles),
43
+ * welcome: () => ({
44
+ * from: 'hello@books.example',
45
+ * subject: 'You are in the book club',
46
+ * body: 'Welcome. We meet Thursdays.',
47
+ * }),
48
+ * }))
49
+ *
50
+ * await club.apply([
51
+ * { entity: { eid: 'club' }, doc: { title: 'Book club' } },
52
+ * { entity: { eid: 'ana' }, email: { address: 'ana@books.example' } },
53
+ * {
54
+ * entity: { eid: 'm1' },
55
+ * member: { space: 'club', person: 'ana', role: 'member' },
56
+ * },
57
+ * ])
58
+ * assertEquals(post.last()?.to, 'ana@books.example')
59
+ * ```
60
+ *
61
+ * The letter is addressed to the person as an entity (`deliver.to`), not to a
62
+ * string, so the address it actually goes to is whatever their `email`
63
+ * component holds at the moment it leaves — and a person with no address on
64
+ * file gets a letter stamped `bounced` saying exactly that, rather than
65
+ * silence.
66
+ */ export let invited = ({ welcome, apply, eid = ()=>crypto.randomUUID(), now = ()=>new Date().toISOString() })=>(event)=>{
67
+ let member = event.comp;
68
+ if (!member) return;
69
+ let person = str(member, 'person');
70
+ if (!person) return;
71
+ let letter = welcome({
72
+ eid: event.entity.eid,
73
+ person,
74
+ space: str(member, 'space'),
75
+ role: str(member, 'role'),
76
+ member
77
+ });
78
+ if (!letter) return;
79
+ return apply([
80
+ {
81
+ entity: {
82
+ eid: eid()
83
+ },
84
+ // The words, in the component every readable thing has (@yaks/doc).
85
+ [DOC]: {
86
+ title: letter.subject,
87
+ body: letter.body
88
+ },
89
+ [MAIL]: {
90
+ from: letter.from,
91
+ at: now(),
92
+ // The letter is about the roster row: correspondence hangs off the thing
93
+ // it concerns, so the roster row reads back with its own invitation.
94
+ target: event.entity.eid
95
+ },
96
+ [DELIVER]: {
97
+ to: person
98
+ }
99
+ }
100
+ ]);
101
+ };
102
+ //# sourceMappingURL=invite.js.map
package/invite.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invite.js","sources":["./invite.ts"],"names":[],"mappings":"AAAA,6DAA6D;AAC7D,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,gFAAgF;AAChF,+EAA+E;AAC/E,EAAE;AACF,uEAAuE;AACvE,uEAAuE;AACvE,2EAA2E;AAC3E,uEAAuE;AACvE,yEAAyE;AACzE,qEAAqE;AACrE,EAAE;AACF,4EAA4E;AAC5E,iEAAiE;AAIjE,SAAS,GAAG,yBAA8B;AAC1C,SAAS,OAAO,EAAE,IAAI,oBAAmB;AAuCzC,IAAI,MAAM,CAAC,GAAS,IAAsB,CAAC,CAAC,EAAE,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,EAAE;AAEzE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8CC,GACD,OAAO,IAAI,UAAU,CACnB,EACE,OAAO,EACP,KAAK,EACL,MAAM,IAAM,OAAO,UAAU,EAAE,EAC/B,MAAM,IAAM,IAAI,OAAO,WAAW,EAAE,EAC7B,GAEX,CAAC;IACC,IAAI,SAAS,MAAM,IAAI;IACvB,IAAI,CAAC,QAAQ;IACb,IAAI,SAAS,IAAI,QAAQ;IACzB,IAAI,CAAC,QAAQ;IACb,IAAI,SAAS,QAAQ;MACnB,KAAK,MAAM,MAAM,CAAC,GAAG;MACrB;MACA,OAAO,IAAI,QAAQ;MACnB,MAAM,IAAI,QAAQ;MAClB;IACF;IACA,IAAI,CAAC,QAAQ;IACb,OAAO,MAAM;MAAC;QACZ,QAAQ;UAAE,KAAK;QAAM;QACrB,oEAAoE;QACpE,CAAC,IAAI,EAAE;UAAE,OAAO,OAAO,OAAO;UAAE,MAAM,OAAO,IAAI;QAAC;QAClD,CAAC,KAAK,EAAE;UACN,MAAM,OAAO,IAAI;UACjB,IAAI;UACJ,yEAAyE;UACzE,qEAAqE;UACrE,QAAQ,MAAM,MAAM,CAAC,GAAG;QAC1B;QACA,CAAC,QAAQ,EAAE;UAAE,IAAI;QAAO;MAC1B;KAAE;EACJ,EAAC"}
package/invite.ts ADDED
@@ -0,0 +1,143 @@
1
+ // The worked example: somebody joins, and a letter goes out.
2
+ //
3
+ // This is the handler slot @yaks/member documents and leaves empty. Adding a
4
+ // person to a roster usually means writing to them, but a roster package must
5
+ // not know what a mail server is — so the roster row is written by one package,
6
+ // and the letter about it by this one, joined by nothing but a component name.
7
+ //
8
+ // What makes it worth reading is what it does not do: it does not send
9
+ // anything. It writes a letter into the graph, through the graph's own
10
+ // `apply()`, and the `created(mail)` effect in ./send.ts sends it like any
11
+ // other. So one mechanism carries invitations, receipts, reminders and
12
+ // replies, and an invitation that could not be delivered leaves the same
13
+ // `bounced` component on the same kind of entity as everything else.
14
+ //
15
+ // It refers to the `member` component by name, so this file imports nothing
16
+ // from @yaks/member — the two packages meet at a component name.
17
+
18
+ import type { Bundle, Comp, Eid } from 'jsr:@yaks/graph@0.2.36'
19
+ import type { Handler } from 'jsr:@yaks/effects@0.2.36'
20
+ import { DOC } from '@yaks/doc'
21
+ import { DELIVER, MAIL } from './comp.js'
22
+
23
+ /** The roster row that was just written, as the letter's author sees it. */
24
+ export type Seat = {
25
+ /** the roster row's own entity id */
26
+ eid: Eid
27
+ /** who joined */
28
+ person: Eid
29
+ /** what they joined */
30
+ space: Eid
31
+ /** what they joined as — whatever your roster's role property holds */
32
+ role: string
33
+ /** the whole `member` component, for a roster with more properties than
34
+ * these */
35
+ member: Comp
36
+ }
37
+
38
+ /** The letter to send about a new roster row, or `null` to send none. */
39
+ export type Welcome = (seat: Seat) => {
40
+ /** the address it comes from */
41
+ from: string
42
+ /** the subject line */
43
+ subject: string
44
+ /** the body, as markdown */
45
+ body: string
46
+ } | null
47
+
48
+ /** How the handler is built. */
49
+ export type Invite = {
50
+ /** compose the letter (or decline to) */
51
+ welcome: Welcome
52
+ /** the graph's own `apply` — the letter goes through the full pipeline */
53
+ apply: (bundles: Bundle[]) => unknown
54
+ /** the id for the new letter (default: a fresh uuid) */
55
+ eid?: () => Eid
56
+ /** the clock, passed in so a test can hold it still (default: now) */
57
+ now?: () => string
58
+ }
59
+
60
+ let str = (c: Comp, k: string): string => c[k] == null ? '' : String(c[k])
61
+
62
+ /**
63
+ * The `created(member)` handler: write an invitation to whoever just joined.
64
+ *
65
+ * ```ts
66
+ * import { assertEquals } from '@std/assert'
67
+ * import { effects } from '@yaks/effects'
68
+ * import { graph } from '@yaks/graph'
69
+ * import { ram } from '@yaks/ram'
70
+ * import { loadVocab } from '@yaks/vocab'
71
+ * import { docDoc, docs } from '@yaks/doc'
72
+ * import { memberDoc } from '@yaks/member'
73
+ * import { invited, mailbox, mailDoc, stash } from '@yaks/mail'
74
+ *
75
+ * let vocab = loadVocab([docDoc, mailDoc, memberDoc])
76
+ * let fx = effects(vocab, { write: (b) => club.apply(b, { trusted: true }) })
77
+ * let post = stash()
78
+ * let club = graph({
79
+ * storage: ram(vocab),
80
+ * vocab,
81
+ * plugins: [fx, docs(), mailbox({ sender: post, effects: fx })],
82
+ * })
83
+ * fx.created('member', invited({
84
+ * apply: (bundles) => club.apply(bundles),
85
+ * welcome: () => ({
86
+ * from: 'hello@books.example',
87
+ * subject: 'You are in the book club',
88
+ * body: 'Welcome. We meet Thursdays.',
89
+ * }),
90
+ * }))
91
+ *
92
+ * await club.apply([
93
+ * { entity: { eid: 'club' }, doc: { title: 'Book club' } },
94
+ * { entity: { eid: 'ana' }, email: { address: 'ana@books.example' } },
95
+ * {
96
+ * entity: { eid: 'm1' },
97
+ * member: { space: 'club', person: 'ana', role: 'member' },
98
+ * },
99
+ * ])
100
+ * assertEquals(post.last()?.to, 'ana@books.example')
101
+ * ```
102
+ *
103
+ * The letter is addressed to the person as an entity (`deliver.to`), not to a
104
+ * string, so the address it actually goes to is whatever their `email`
105
+ * component holds at the moment it leaves — and a person with no address on
106
+ * file gets a letter stamped `bounced` saying exactly that, rather than
107
+ * silence.
108
+ */
109
+ export let invited = (
110
+ {
111
+ welcome,
112
+ apply,
113
+ eid = () => crypto.randomUUID(),
114
+ now = () => new Date().toISOString(),
115
+ }: Invite,
116
+ ): Handler =>
117
+ (event) => {
118
+ let member = event.comp
119
+ if (!member) return
120
+ let person = str(member, 'person')
121
+ if (!person) return
122
+ let letter = welcome({
123
+ eid: event.entity.eid,
124
+ person,
125
+ space: str(member, 'space'),
126
+ role: str(member, 'role'),
127
+ member,
128
+ })
129
+ if (!letter) return
130
+ return apply([{
131
+ entity: { eid: eid() },
132
+ // The words, in the component every readable thing has (@yaks/doc).
133
+ [DOC]: { title: letter.subject, body: letter.body },
134
+ [MAIL]: {
135
+ from: letter.from,
136
+ at: now(),
137
+ // The letter is about the roster row: correspondence hangs off the thing
138
+ // it concerns, so the roster row reads back with its own invitation.
139
+ target: event.entity.eid,
140
+ },
141
+ [DELIVER]: { to: person },
142
+ }])
143
+ }
package/md.js ADDED
@@ -0,0 +1,188 @@
1
+ // A letter's body is markdown, and it goes out twice: once as the plain text
2
+ // part and once as HTML. This file is both renderings, from one small reader.
3
+ //
4
+ // It is deliberately minimal — paragraphs, headings, bullets, tables, an image
5
+ // on a line of its own, links, bold, italic, code — because a mail client renders a small subset of HTML anyway
6
+ // and because a markdown library is a dependency this package would otherwise
7
+ // not need. If you already have a renderer you trust, hand its output in as
8
+ // the message's `html` and none of this runs.
9
+ //
10
+ // Two rules are not negotiable, and they are why this is not `escape()` plus a
11
+ // regex:
12
+ //
13
+ // Markup A body wrote is text, never markup. Every character a letter
14
+ // carries is escaped; the only tags in the output are the ones this file
15
+ // generates. A letter from a stranger cannot ship a <script> to your reader.
16
+ //
17
+ // An href is tested by its shape, never by A list of bad schemes. A browser
18
+ // decodes entities inside an attribute, so `javascript&colon;alert(1)` is a
19
+ // scheme by the time it parses one and no denylist sees it coming. Only an
20
+ // absolute http, https, mailto or tel link becomes an anchor; anything else
21
+ // renders as its own text. Relative links are rejected too — a mail client
22
+ // has no base document to resolve `/potluck` against, so it would reach the
23
+ // reader as a broken address rather than a link.
24
+ //
25
+ // A body a graph stores holds the eid of each entity it names (@yaks/graph
26
+ // `Prose`), and a reader never reads a whole uuid: given what the sender calls
27
+ // each one ({@link Names}), an eid written bare reads as its id, linked to its
28
+ // page, and a link written to one goes to that page. A uuid it does not name
29
+ // is left as written.
30
+ /** One piece of a body: a run of words, or the markup that decorates it. */ let EID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31
+ // Links first (their text may hold anything), then code (which consumes its
32
+ // content whole), then the two emphases, then an eid standing as a word of its
33
+ // own, then an address written bare. An underscore inside a word is never
34
+ // emphasis, so `session_token=nango_connect` keeps its underscores, and a bare
35
+ // address is one run of text, so a token in it keeps every character (a
36
+ // base64url `-_x_-` is not emphasis).
37
+ let INLINE = /\[([^\]]*)\]\(([^)\s]+)\)|`([^`]+)`|\*\*([^*]+)\*\*|\*([^*\n]+)\*|(?<![\p{L}\p{N}_])_([^_\n]+)_(?![\p{L}\p{N}_])|(?<![\w#\/-])([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})(?![\w-])|(https?:\/\/\S+)/giu;
38
+ /** A line of markdown → the tokens it is made of, in order. */ export let tokens = (line)=>{
39
+ let out = [];
40
+ let at = 0;
41
+ for (let m of line.matchAll(INLINE)){
42
+ if (m.index > at) out.push({
43
+ kind: 'text',
44
+ text: line.slice(at, m.index)
45
+ });
46
+ if (m[2] != null) out.push({
47
+ kind: 'link',
48
+ text: m[1],
49
+ href: m[2]
50
+ });
51
+ else if (m[3] != null) out.push({
52
+ kind: 'code',
53
+ text: m[3]
54
+ });
55
+ else if (m[4] != null) out.push({
56
+ kind: 'strong',
57
+ text: m[4]
58
+ });
59
+ else if (m[7] != null) out.push({
60
+ kind: 'ref',
61
+ text: m[7]
62
+ });
63
+ else if (m[8] != null) out.push({
64
+ kind: 'text',
65
+ text: m[8]
66
+ });
67
+ else out.push({
68
+ kind: 'em',
69
+ text: m[5] ?? m[6]
70
+ });
71
+ at = m.index + m[0].length;
72
+ }
73
+ if (at < line.length) out.push({
74
+ kind: 'text',
75
+ text: line.slice(at)
76
+ });
77
+ return out;
78
+ };
79
+ /** The eids a body names, written bare or as a link's target, once each and
80
+ * in lower case: what the sender is asked to name. Code keeps its ids literal,
81
+ * so none in it is listed. */ export let eids = (body)=>[
82
+ ...new Set(body.split('\n').flatMap(tokens).flatMap((t)=>t.kind == 'ref' ? [
83
+ t.text.toLowerCase()
84
+ ] : t.kind == 'link' && EID.test(t.href.trim()) ? [
85
+ t.href.trim().toLowerCase()
86
+ ] : []))
87
+ ];
88
+ // A line's tokens with each eid the sender names as its reader reads it: a
89
+ // bare one is its id, a link where it has a page; a link to one goes to that
90
+ // page, or is its words. An eid it does not name is a uuid like any other.
91
+ let drawn = (line, names)=>tokens(line).map((t)=>{
92
+ let eid = t.kind == 'ref' ? t.text : t.kind == 'link' && EID.test(t.href.trim()) ? t.href.trim() : undefined;
93
+ let named = eid ? names?.(eid.toLowerCase()) : undefined;
94
+ if (t.kind == 'ref') {
95
+ return named?.href ? {
96
+ kind: 'link',
97
+ text: named.id,
98
+ href: named.href
99
+ } : {
100
+ kind: 'text',
101
+ text: named?.id ?? t.text
102
+ };
103
+ }
104
+ return named ? {
105
+ ...t,
106
+ href: named.href ?? ''
107
+ } : t;
108
+ });
109
+ /** Whether an href may become an anchor: absolute, and one of four schemes. */ export let linkable = (href)=>/^(?:https?:\/\/|mailto:|tel:)\S+$/i.test(href.trim());
110
+ /** `&` first, or the escapes escape. */ export let escape = (s)=>s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
111
+ let inline = (line, names)=>drawn(line, names).map((t)=>t.kind == 'link' && linkable(t.href) ? `<a href="${escape(t.href.trim())}">${escape(t.text)}</a>` : t.kind == 'code' ? `<code>${escape(t.text)}</code>` : t.kind == 'strong' ? `<strong>${escape(t.text)}</strong>` : t.kind == 'em' ? `<em>${escape(t.text)}</em>` : escape(t.text)).join('');
112
+ let flat = (line, names)=>drawn(line, names).map((t)=>t.kind == 'link' && linkable(t.href) && t.text.trim() != t.href.trim() ? `${t.text} (${t.href.trim()})` : t.text).join('');
113
+ // An image stands on a line of its own, at an absolute http(s) address: a mail
114
+ // client fetches it from there, and has no other way to show one.
115
+ let IMAGE = /^!\[([^\]]*)\]\((https?:\/\/[^)\s]+)\)$/i;
116
+ // A table is a run of lines that start with a pipe; a row of dashes under the
117
+ // first makes it the head. A cell holds a pipe written `\|`.
118
+ let ROW = /^\s*\|/;
119
+ let RULE = /^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-*:?\s*$/;
120
+ let cells = (line)=>line.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '').split(/(?<!\\)\|/).map((c)=>c.trim().replace(/\\\|/g, '|'));
121
+ let table = (lines)=>{
122
+ let ruled = lines.length > 1 && RULE.test(lines[1]);
123
+ return {
124
+ head: ruled ? cells(lines[0]) : undefined,
125
+ rows: lines.slice(ruled ? 2 : 0).map(cells)
126
+ };
127
+ };
128
+ // Mail clients drop a stylesheet, so a table's few rules ride on its cells.
129
+ let CELL = 'padding:2px 10px 2px 0;text-align:left;vertical-align:top';
130
+ // Quoted correspondence carries the sender's text verbatim, including markup.
131
+ let quotation = (lines)=>lines.every((line)=>line.startsWith('> '));
132
+ // A block is a run of lines between blank ones. Its first line determines what
133
+ // kind of block it is.
134
+ let block = (lines, names)=>{
135
+ if (quotation(lines)) {
136
+ return '<blockquote style="white-space:pre-wrap">' + escape(lines.map((line)=>line.slice(2)).join('\n')) + '</blockquote>';
137
+ }
138
+ let head = /^(#{1,6})\s+(.*)$/.exec(lines[0]);
139
+ if (head) {
140
+ let n = head[1].length;
141
+ return `<h${n}>${inline(head[2], names)}</h${n}>`;
142
+ }
143
+ let image = lines.length == 1 && IMAGE.exec(lines[0].trim());
144
+ if (image) {
145
+ return `<p><img src="${escape(image[2])}" alt="${escape(image[1])}" style="max-width:100%"></p>`;
146
+ }
147
+ if (lines.every((l)=>ROW.test(l))) {
148
+ let t = table(lines);
149
+ let row = (cs, tag)=>`<tr>${cs.map((c)=>`<${tag} style="${CELL}">${inline(c, names)}</${tag}>`).join('')}</tr>`;
150
+ return `<table style="border-collapse:collapse">${t.head ? `<thead>${row(t.head, 'th')}</thead>` : ''}<tbody>${t.rows.map((r)=>row(r, 'td')).join('')}</tbody></table>`;
151
+ }
152
+ if (lines.every((l)=>/^\s*[-*]\s+/.test(l))) {
153
+ let items = lines.map((l)=>`<li>${inline(l.replace(/^\s*[-*]\s+/, ''), names)}</li>`);
154
+ return `<ul>${items.join('')}</ul>`;
155
+ }
156
+ return `<p>${lines.map((l)=>inline(l, names)).join('<br>')}</p>`;
157
+ };
158
+ let blocks = (body)=>body.replace(/\r\n?/g, '\n').split(/\n\s*\n/).map((b)=>b.split('\n').filter((l)=>l.trim())).filter((b)=>b.length);
159
+ /**
160
+ * A markdown body → safe HTML for the message's HTML part. Everything the body
161
+ * wrote is escaped; the only markup in the result is this file's own.
162
+ *
163
+ * ```ts
164
+ * import { html } from '@yaks/mail'
165
+ * html('Potluck **Friday** — [sign up](https://books.example/potluck)')
166
+ * // '<p>Potluck <strong>Friday</strong> — <a href="…">sign up</a></p>'
167
+ * ```
168
+ */ export let html = (body, names)=>blocks(body).map((lines)=>block(lines, names)).join('\n');
169
+ /**
170
+ * The same body as plain text, for the message's text part: the markup goes,
171
+ * the words stay, and a link keeps its address in parentheses so a reader with
172
+ * no HTML can still follow it.
173
+ */ export let text = (body, names)=>blocks(body).map((lines)=>{
174
+ if (quotation(lines)) return lines.join('\n');
175
+ let image = lines.length == 1 && IMAGE.exec(lines[0].trim());
176
+ if (image) return `${image[1]} (${image[2]})`;
177
+ if (lines.every((l)=>ROW.test(l))) {
178
+ let t = table(lines);
179
+ return [
180
+ ...t.head ? [
181
+ t.head
182
+ ] : [],
183
+ ...t.rows
184
+ ].map((r)=>r.map((c)=>flat(c, names)).join(' · ')).join('\n');
185
+ }
186
+ return lines.map((l)=>flat(l.replace(/^(#{1,6})\s+/, '').replace(/^\s*[-*]\s+/, '- '), names)).join('\n');
187
+ }).join('\n\n');
188
+ //# sourceMappingURL=md.js.map