@yaks/connections 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 (184) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +609 -2
  3. package/_dist/authorize.d.ts +38 -0
  4. package/_dist/authorize.d.ts.map +1 -0
  5. package/_dist/authorize_cli.d.ts +12 -0
  6. package/_dist/authorize_cli.d.ts.map +1 -0
  7. package/_dist/brokers.d.ts +66 -0
  8. package/_dist/brokers.d.ts.map +1 -0
  9. package/_dist/catalog.d.ts +33 -0
  10. package/_dist/catalog.d.ts.map +1 -0
  11. package/_dist/cli.d.ts +3 -0
  12. package/_dist/cli.d.ts.map +1 -0
  13. package/_dist/clients.d.ts +18 -0
  14. package/_dist/clients.d.ts.map +1 -0
  15. package/_dist/connections.d.ts +296 -0
  16. package/_dist/connections.d.ts.map +1 -0
  17. package/_dist/effects.d.ts +15 -0
  18. package/_dist/effects.d.ts.map +1 -0
  19. package/_dist/field.d.ts +17 -0
  20. package/_dist/field.d.ts.map +1 -0
  21. package/_dist/form.d.ts +49 -0
  22. package/_dist/form.d.ts.map +1 -0
  23. package/_dist/given.d.ts +10 -0
  24. package/_dist/given.d.ts.map +1 -0
  25. package/_dist/graph.d.ts +15 -0
  26. package/_dist/graph.d.ts.map +1 -0
  27. package/_dist/history.d.ts +4 -0
  28. package/_dist/history.d.ts.map +1 -0
  29. package/_dist/identity.d.ts +9 -0
  30. package/_dist/identity.d.ts.map +1 -0
  31. package/_dist/integrations.d.ts +196 -0
  32. package/_dist/integrations.d.ts.map +1 -0
  33. package/_dist/loopback.d.ts +7 -0
  34. package/_dist/loopback.d.ts.map +1 -0
  35. package/_dist/mcp-retirement.d.ts +33 -0
  36. package/_dist/mcp-retirement.d.ts.map +1 -0
  37. package/_dist/mcp.d.ts +179 -0
  38. package/_dist/mcp.d.ts.map +1 -0
  39. package/_dist/mod.d.ts +70 -0
  40. package/_dist/mod.d.ts.map +1 -0
  41. package/_dist/paste.d.ts +13 -0
  42. package/_dist/paste.d.ts.map +1 -0
  43. package/_dist/requests.d.ts +30 -0
  44. package/_dist/requests.d.ts.map +1 -0
  45. package/_dist/services.d.ts +25 -0
  46. package/_dist/services.d.ts.map +1 -0
  47. package/_dist/sign-in.d.ts +9 -0
  48. package/_dist/sign-in.d.ts.map +1 -0
  49. package/_dist/signin-mail.d.ts +12 -0
  50. package/_dist/signin-mail.d.ts.map +1 -0
  51. package/_dist/signin.d.ts +19 -0
  52. package/_dist/signin.d.ts.map +1 -0
  53. package/_dist/sources.d.ts +61 -0
  54. package/_dist/sources.d.ts.map +1 -0
  55. package/_dist/tools.d.ts +3 -0
  56. package/_dist/tools.d.ts.map +1 -0
  57. package/_dist/views.d.ts +3 -0
  58. package/_dist/views.d.ts.map +1 -0
  59. package/_dist/vocab.d.ts +6 -0
  60. package/_dist/vocab.d.ts.map +1 -0
  61. package/_dist/yaks-app.d.ts +29 -0
  62. package/_dist/yaks-app.d.ts.map +1 -0
  63. package/anthropic.json +12 -0
  64. package/auth_command.js +69 -0
  65. package/auth_command.js.map +1 -0
  66. package/auth_command.ts +74 -0
  67. package/authorize.js +89 -0
  68. package/authorize.js.map +1 -0
  69. package/authorize.ts +138 -0
  70. package/authorize_cli.js +167 -0
  71. package/authorize_cli.js.map +1 -0
  72. package/authorize_cli.ts +211 -0
  73. package/brokers.js +318 -0
  74. package/brokers.js.map +1 -0
  75. package/brokers.ts +423 -0
  76. package/canva.json +32 -0
  77. package/catalog.js +178 -0
  78. package/catalog.js.map +1 -0
  79. package/catalog.ts +216 -0
  80. package/cli.js +30 -0
  81. package/cli.js.map +1 -0
  82. package/cli.ts +26 -0
  83. package/clients.js +34 -0
  84. package/clients.js.map +1 -0
  85. package/clients.ts +65 -0
  86. package/connections.js +1961 -0
  87. package/connections.js.map +1 -0
  88. package/connections.ts +2561 -0
  89. package/deno.json +1 -0
  90. package/discord-account.json +22 -0
  91. package/discord-bot.json +20 -0
  92. package/discord.json +26 -0
  93. package/effects.js +168 -0
  94. package/effects.js.map +1 -0
  95. package/effects.ts +160 -0
  96. package/elevenlabs.json +18 -0
  97. package/facebook.json +18 -0
  98. package/field.js +19 -0
  99. package/field.js.map +1 -0
  100. package/field.ts +31 -0
  101. package/form.js +112 -0
  102. package/form.js.map +1 -0
  103. package/form.ts +178 -0
  104. package/git-config.js +44 -0
  105. package/git-config.js.map +1 -0
  106. package/git-config.ts +26 -0
  107. package/given.js +83 -0
  108. package/given.js.map +1 -0
  109. package/given.ts +88 -0
  110. package/gmail-mailbox.json +29 -0
  111. package/gmail.json +31 -0
  112. package/google-calendar.json +31 -0
  113. package/google-drive.json +31 -0
  114. package/google-search-console.json +29 -0
  115. package/graph.js +36 -0
  116. package/graph.js.map +1 -0
  117. package/graph.ts +52 -0
  118. package/history.js +31 -0
  119. package/history.js.map +1 -0
  120. package/history.ts +32 -0
  121. package/identity.js +15 -0
  122. package/identity.js.map +1 -0
  123. package/identity.ts +18 -0
  124. package/integrations.js +493 -0
  125. package/integrations.js.map +1 -0
  126. package/integrations.ts +725 -0
  127. package/loopback.js +72 -0
  128. package/loopback.js.map +1 -0
  129. package/loopback.ts +89 -0
  130. package/lulu.json +32 -0
  131. package/mcp-retirement.js +133 -0
  132. package/mcp-retirement.js.map +1 -0
  133. package/mcp-retirement.ts +200 -0
  134. package/mcp-signin.js +14 -0
  135. package/mcp-signin.js.map +1 -0
  136. package/mcp-signin.ts +13 -0
  137. package/mcp.js +1036 -0
  138. package/mcp.js.map +1 -0
  139. package/mcp.ts +1283 -0
  140. package/mod.js +70 -0
  141. package/mod.js.map +1 -0
  142. package/mod.ts +216 -0
  143. package/openai-api.json +12 -0
  144. package/openai.json +25 -0
  145. package/openrouter.json +14 -0
  146. package/package.json +89 -4
  147. package/paste.js +36 -0
  148. package/paste.js.map +1 -0
  149. package/paste.ts +55 -0
  150. package/requests.js +137 -0
  151. package/requests.js.map +1 -0
  152. package/requests.ts +200 -0
  153. package/services.js +84 -0
  154. package/services.js.map +1 -0
  155. package/services.ts +111 -0
  156. package/sign-in.js +36 -0
  157. package/sign-in.js.map +1 -0
  158. package/sign-in.ts +53 -0
  159. package/signin-mail.js +29 -0
  160. package/signin-mail.js.map +1 -0
  161. package/signin-mail.ts +56 -0
  162. package/signin.js +68 -0
  163. package/signin.js.map +1 -0
  164. package/signin.ts +109 -0
  165. package/slack.json +90 -0
  166. package/sources.js +178 -0
  167. package/sources.js.map +1 -0
  168. package/sources.ts +237 -0
  169. package/tools.js +39 -0
  170. package/tools.js.map +1 -0
  171. package/tools.ts +46 -0
  172. package/views.js +85 -0
  173. package/views.js.map +1 -0
  174. package/views.ts +89 -0
  175. package/visitor-defaults.json +8 -0
  176. package/vocab.js +17 -0
  177. package/vocab.js.map +1 -0
  178. package/vocab.json +863 -0
  179. package/vocab.ts +18 -0
  180. package/voipms.json +32 -0
  181. package/yaks-app.js +159 -0
  182. package/yaks-app.js.map +1 -0
  183. package/yaks-app.ts +177 -0
  184. package/youtube.json +26 -0
@@ -0,0 +1,725 @@
1
+ // Integrations: the outside services a connection can go through, as data.
2
+ //
3
+ // An integration says where a person signs in to a service and where its codes
4
+ // are exchanged, for one reached by OAuth, which hosts its credential may be
5
+ // sent to, and how a page shows it: its name, a line about it, its site and its
6
+ // logo. One with no token endpoint is reached with a pasted key instead, or
7
+ // with the several fields it names (`fields`): S3's access key ID, secret key
8
+ // and region. One key is the case of one field, named `key`.
9
+ //
10
+ // Every integration is an entity in the graph wearing `integration`, and one
11
+ // name is one entity. The ones this package builds ship as seed data, one JSON
12
+ // file each, which a host installs into its graph at start-up (`install`),
13
+ // trusted, since only the host may mark one `built`. Nothing reads the files
14
+ // after that: every lookup is a read of the graph. A custom one is a key for a
15
+ // service nobody built, or a builder's own OAuth client, made by `need` only
16
+ // where no integration holds the name yet — so no verb a space can reach
17
+ // writes over a built integration, or changes where its tokens are sent.
18
+
19
+ import { joined, line, sub } from '@yaks/query'
20
+ import { after, cmp } from '@yaks/fp'
21
+ import type { Bundle, Eid, Reads } from 'jsr:@yaks/graph@0.2.36'
22
+ import { token } from '@yaks/graph/sha256'
23
+ import type { Scheme } from 'jsr:@yaks/hook@0.2.36'
24
+ import { CallError } from '@yaks/tools/errors'
25
+ import { INTEGRATION, integrationEid } from './identity.js'
26
+ import { type Field, fieldsOf, KEY, loginFields } from './field.js'
27
+
28
+ export { type Field, fieldsOf, KEY }
29
+ import anthropic from './anthropic.json' with { type: 'json' }
30
+ import canva from './canva.json' with { type: 'json' }
31
+ import gmail from './gmail.json' with { type: 'json' }
32
+ import gmailMailbox from './gmail-mailbox.json' with { type: 'json' }
33
+ import discord from './discord.json' with { type: 'json' }
34
+ import discordAccount from './discord-account.json' with { type: 'json' }
35
+ import discordBot from './discord-bot.json' with { type: 'json' }
36
+ import slack from './slack.json' with { type: 'json' }
37
+ import elevenlabs from './elevenlabs.json' with { type: 'json' }
38
+ import facebook from './facebook.json' with { type: 'json' }
39
+ import googleCalendar from './google-calendar.json' with { type: 'json' }
40
+ import googleDrive from './google-drive.json' with { type: 'json' }
41
+ import googleSearchConsole from './google-search-console.json' with {
42
+ type: 'json',
43
+ }
44
+ import lulu from './lulu.json' with { type: 'json' }
45
+ import openrouter from './openrouter.json' with { type: 'json' }
46
+ import openai from './openai.json' with { type: 'json' }
47
+ import openaiApi from './openai-api.json' with { type: 'json' }
48
+ import voipms from './voipms.json' with { type: 'json' }
49
+ import visitorDefaults from './visitor-defaults.json' with { type: 'json' }
50
+ import youtube from './youtube.json' with { type: 'json' }
51
+
52
+ export type VisitorPolicy = 'never' | 'off' | 'on'
53
+
54
+ /** An outside service, as data. */
55
+ export type Integration = {
56
+ name: string
57
+ /** A hosted service; operation declarations stay with the app release. */
58
+ service?: { app: string }
59
+ /** what a person calls it: OpenRouter, Google Calendar */
60
+ title?: string
61
+ /** one line saying what it is, written for a person */
62
+ tagline?: string
63
+ /** its address on the web */
64
+ site?: string
65
+ description?: string
66
+ details?: string
67
+ docs?: string
68
+ connects?: 'key' | 'signin' | 'client'
69
+ visitors?: VisitorPolicy
70
+ categories?: string[]
71
+ image?: string
72
+ /** its mark, as an SVG document, drawn as an image */
73
+ logo?: string
74
+ /** where a person grants access (OAuth) */
75
+ authorize?: string
76
+ /** where codes and refresh tokens are exchanged; none means a pasted key */
77
+ token?: string
78
+ /** OpenID endpoint naming the account when no id_token is returned. */
79
+ userinfo?: string
80
+ /** the field that names the account, as a dotted path, where it is not an
81
+ * email address: of the token endpoint's answer (Discord's `guild.id`, the
82
+ * server its bot was added to; @yaks/oauth `Provider.account`), else of
83
+ * the `userinfo` answer (a Discord user's `id`) */
84
+ account?: string
85
+ /** the field that names that account for people, as a dotted path of the
86
+ * same answer: the server's name (`guild.name`), a Discord user's
87
+ * `global_name` */
88
+ account_title?: string
89
+ /** another integration naming the person who signs in through this one,
90
+ * whose own connection the same sign-in makes: Discord's bot added with
91
+ * `identify` granted also links the Discord account of whoever added it
92
+ * (`discord-account`) */
93
+ links?: string
94
+ /** a person's own account at the service (a Discord user), which says who
95
+ * they are there: a connection through it is its connector's, never the
96
+ * space's */
97
+ personal?: boolean
98
+ /** the chat platform its connections talk through (@yaks/chat), by name:
99
+ * connecting it is all it takes for the Operator and the space's apps to
100
+ * hear and answer there */
101
+ chat?: string
102
+ /** The OAuth grant itself is the bot credential for this installation. */
103
+ chat_grant?: boolean
104
+ /** what a connection asks for when nothing narrower was needed */
105
+ scopes?: string[]
106
+ /** The provider separates OAuth scopes with commas. */
107
+ scope_separator?: ' ' | ','
108
+ /** Whether the OAuth provider accepts PKCE for this client. */
109
+ pkce?: boolean
110
+ /** extra authorize parameters, such as Google's `access_type: 'offline'` */
111
+ params?: Record<string, string>
112
+ /** how the client authenticates at the token endpoint (@yaks/oauth) */
113
+ auth?: 'basic' | 'post'
114
+ /** how refresh grants are sent when a provider requires JSON */
115
+ refresh_encoding?: 'form' | 'json'
116
+ /** what the exchange answers: tokens, or a key, as OpenRouter's does */
117
+ answers?: 'tokens' | 'key'
118
+ /** the resource a grant is for (RFC 8707), as an MCP server asks */
119
+ resource?: string
120
+ /** the issuer its returns name (RFC 9207), where it says it names one */
121
+ issuer?: string
122
+ /** the OAuth client it signs in as, by name (./clients.ts): one registration
123
+ * several integrations can share */
124
+ client?: string
125
+ /** a public OAuth client's id; no secret or registration is needed */
126
+ client_id?: string
127
+ /** the broker new connections through it are made through (./brokers.ts),
128
+ * and what the broker calls it; none is direct */
129
+ broker?: {
130
+ name: string
131
+ integration: string
132
+ managed?: boolean
133
+ scoped?: boolean
134
+ }
135
+ /** the API hosts its credential may be sent to, and no others */
136
+ hosts: string[]
137
+ /** A credential was saved through this custom integration. */
138
+ credentialed?: boolean
139
+ /** its API: the address its paths are under, its reference, and the calls
140
+ * that only read though their method is not GET (`POST /freeBusy`, `*` for
141
+ * one segment); none is reached at its first host */
142
+ api?: { base: string; docs?: string; reads?: string[] }
143
+ /** the only API methods a connection through it may ask for, where the
144
+ * service names one in each request (voip.ms's `method`); none limits
145
+ * nothing */
146
+ methods?: string[]
147
+ /** what a person gives to connect a pasted-key one, when it is more than
148
+ * one key; none is one key */
149
+ fields?: Field[]
150
+ /** how the service signs the webhooks it sends */
151
+ signature?: Scheme
152
+ /** still in the service's testing mode, where only the people it lists may
153
+ * sign in: offered only on a page opened with `?enable=<name>` */
154
+ testing?: boolean
155
+ /** installed from this package's seed data; only the host writes it */
156
+ built?: boolean
157
+ /** how a person gets the credential, in markdown, for them and their agent */
158
+ instructions?: string
159
+ /** what its one key looks like, shown in the box it is pasted in:
160
+ * ElevenLabs' `sk_••••••••` */
161
+ example?: string
162
+ /** its own hosted MCP server's address, which a person connects by signing
163
+ * in to their account there (./mcp.ts), as well as or instead of a key */
164
+ mcp?: string
165
+ /** a call that answers 2xx once its credential works, `METHOD url` on one
166
+ * of its hosts: Cloudflare's `GET …/user/tokens/verify` */
167
+ check?: string
168
+ /** the space or person that made a custom one, who alone may change its
169
+ * text; none for a built one */
170
+ owner?: string
171
+ }
172
+
173
+ /** A read of the graph: what a tool's context and a graph both offer. */
174
+ export type Read = Reads<Bundle[] | Promise<Bundle[]>, []>
175
+
176
+ // The integrations this package builds, as their seed files say them. The JSON
177
+ // types `answers` as any string, so OpenRouter's is said again as the word it
178
+ // is.
179
+ let SEEDS: Integration[] = [
180
+ anthropic,
181
+ canva,
182
+ discord,
183
+ discordAccount,
184
+ discordBot,
185
+ elevenlabs,
186
+ { ...facebook, connects: 'signin' as const },
187
+ gmail,
188
+ gmailMailbox,
189
+ googleCalendar,
190
+ googleDrive,
191
+ googleSearchConsole,
192
+ lulu,
193
+ { ...openai, refresh_encoding: 'json' as const },
194
+ openaiApi,
195
+ { ...openrouter, answers: 'key' as const },
196
+ { ...slack, scope_separator: slack.scope_separator as ',' },
197
+ voipms,
198
+ youtube,
199
+ ].map((seed): Integration => ({
200
+ ...seed,
201
+ visitors: seed.visitors as VisitorPolicy,
202
+ }))
203
+
204
+ /** The integrations this package builds, as shipped: what `install` writes,
205
+ * read here with no graph, for a host that only needs to know them. */
206
+ export let seeds = (): Integration[] => SEEDS
207
+
208
+ /** Whether a person connects it by pasting a key rather than signing in:
209
+ * one with no token endpoint and no broker to sign in through. */
210
+ export let keyed = (i: Integration): boolean => !i.token && !i.broker
211
+
212
+ /** The policy for older rows and catalog entries before they are added. */
213
+ export let visitorPolicy = (i?: Integration): VisitorPolicy => {
214
+ if (!i) return 'off'
215
+ if (i.visitors) return i.visitors
216
+ if (
217
+ !keyed(i) || i.connects == 'signin' || i.connects == 'client' ||
218
+ loginFields(fieldsOf(i))
219
+ ) return 'never'
220
+ return (visitorDefaults as Record<string, VisitorPolicy>)[i.name] ?? 'off'
221
+ }
222
+
223
+ /** Whether visitors may call out through a link. The integration sets the
224
+ * default for an unset `anyone`. A policy of `never` bars visitor access.
225
+ *
226
+ * ```ts
227
+ * visitorsAllowed('on', undefined) // true
228
+ * visitorsAllowed('on', false) // false
229
+ * visitorsAllowed('off', undefined) // false
230
+ * visitorsAllowed('never', true) // false
231
+ * ``` */
232
+ export let visitorsAllowed = (
233
+ policy: VisitorPolicy,
234
+ anyone: unknown,
235
+ ): boolean =>
236
+ policy != 'never' && (typeof anyone == 'boolean' ? anyone : policy == 'on')
237
+
238
+ /** Whether a person can connect it here: by pasting a key, through a sign-in
239
+ * that answers a key to any caller (OpenRouter), or through what it signs in
240
+ * with once that is kept (`kept`): its broker, when it names one
241
+ * (./brokers.ts), else the OAuth client it names (./clients.ts). */
242
+ export let connectable = (i: Integration, kept?: unknown): boolean =>
243
+ i.broker ? !!kept : keyed(i) || i.answers == 'key' || !!i.client_id || !!kept
244
+
245
+ /** An integration by name, as the graph holds it. */
246
+ export let known = async (
247
+ read: Read,
248
+ name: string,
249
+ ): Promise<Integration | undefined> => {
250
+ let [b] = await read(
251
+ line`.entity.eid=${integrationEid(name)}&.${INTEGRATION}`,
252
+ )
253
+ return b?.[INTEGRATION] as Integration | undefined
254
+ }
255
+
256
+ /** The integrations of these names, as the graph holds them, in one read:
257
+ * each found among them by `knownIn`. */
258
+ export let knownAll = (read: Read, names: string[]): Promise<Bundle[]> =>
259
+ Promise.resolve(
260
+ names.length
261
+ ? read(line`.entity.eid=${names.map(integrationEid)}&.${INTEGRATION}`)
262
+ : [],
263
+ )
264
+
265
+ /** The built integration that stands in for the service `name`: the one of
266
+ * that name, else one signing in through a broker's listing of it (Gmail for
267
+ * Nango's google-mail). The catalog offers, the directory lists and the
268
+ * connections page adds that one in the listing's place. */
269
+ export let standIn = <I extends Integration>(
270
+ built: I[],
271
+ name: string,
272
+ broker?: string,
273
+ ): I | undefined =>
274
+ built.find((i) => i.built && i.name == name) ??
275
+ built.find((i) =>
276
+ i.built && i.broker?.integration == name &&
277
+ (!broker || i.broker.name == broker)
278
+ )
279
+
280
+ /** An integration by name, among rows already read: what `list` and
281
+ * `borrowed` return beside their connections. */
282
+ export let knownIn = (
283
+ rows: Bundle[],
284
+ name: string,
285
+ ): Integration | undefined =>
286
+ rows.find((b) => b[INTEGRATION] && b.entity.eid == integrationEid(name))
287
+ ?.[INTEGRATION] as Integration | undefined
288
+
289
+ /** The built integrations a graph holds. */
290
+ export let installed = async (read: Read): Promise<Integration[]> =>
291
+ (await read(line`.${INTEGRATION}.built`)).map((b) =>
292
+ b[INTEGRATION] as Integration
293
+ )
294
+
295
+ /** The platform's mark that an integration is featured (@yaks/platform). */
296
+ export let FEATURED = 'featured'
297
+
298
+ /** An integration as the catalog and the directory read it: with whether the
299
+ * platform featured it, which is the platform's mark rather than its own. */
300
+ export type Marked = Integration & { featured?: boolean }
301
+
302
+ let marked = (b: Bundle): Marked => ({
303
+ ...b[INTEGRATION] as Integration,
304
+ ...b[FEATURED] ? { featured: true } : {},
305
+ })
306
+
307
+ /** What a person reads at length about an integration: drawn only for the
308
+ * one a page opens, read by name (`known`), and for those built here. */
309
+ export type Prose = 'description' | 'details' | 'docs' | 'instructions'
310
+
311
+ // Only fields that describe an offer. A connection reads the full integration.
312
+ let CARRIED = [
313
+ 'name',
314
+ 'title',
315
+ 'tagline',
316
+ 'site',
317
+ 'connects',
318
+ 'visitors',
319
+ 'categories',
320
+ 'image',
321
+ 'logo',
322
+ 'token',
323
+ 'broker',
324
+ 'hosts',
325
+ 'fields',
326
+ 'example',
327
+ 'mcp',
328
+ 'testing',
329
+ ] satisfies (keyof Integration)[]
330
+ let CATALOGUED = [
331
+ ...CARRIED.map((p) => `${INTEGRATION}.${p}`),
332
+ FEATURED,
333
+ ]
334
+
335
+ /** The host catalog's rows, including integrations not connected yet: those
336
+ * built here whole, the rest without their prose (`Prose`), which is half of
337
+ * each and drawn only for the one a page opens. */
338
+ export let catalogued = async (read: Read): Promise<Marked[]> => {
339
+ let [whole, rest] = await Promise.all([
340
+ read(line`.${INTEGRATION}.built=true&?${FEATURED}`),
341
+ read(
342
+ line`.${INTEGRATION}.categories&!${INTEGRATION}.built&!${INTEGRATION}.owner&.fields=${CATALOGUED}`,
343
+ ),
344
+ ])
345
+ let built = new Map(whole.map((b) => [b.entity.eid, b]))
346
+ return [...whole, ...rest.filter((b) => !built.has(b.entity.eid))]
347
+ .map(marked)
348
+ .filter((i) => !i.owner && (i.built || Array.isArray(i.categories)))
349
+ }
350
+
351
+ // What moves whenever the catalog does: its newest integration, its newest
352
+ // edit, and which ones are featured, a few dozen rows. A custom integration
353
+ // is its owner's and no catalog's, and nothing deletes one (an owner's death
354
+ // detaches it), so these see every change the catalog makes, while the rest
355
+ // of the store moves none of them.
356
+ let SHOWN = line`.${INTEGRATION}&!${INTEGRATION}.owner`
357
+ let STAMP = [
358
+ line`${sub(SHOWN)}&.order=-created.at&.limit=1&.fields=created.at`,
359
+ line`${sub(SHOWN)}&.order=-updated.at&.limit=1&.fields=updated.at`,
360
+ line`${sub(SHOWN)}&.${FEATURED}&.fields=${FEATURED}.at`,
361
+ ]
362
+
363
+ /** What reads the host catalog without its prose: `catalogued`, or one
364
+ * `catalogHeld` keeps. */
365
+ export type Catalog = (read: Read) => Promise<Marked[]>
366
+
367
+ /** A catalog as it was read, and the stamp it was read at. */
368
+ export type HeldCatalog = { stamp: string; rows: Marked[] }
369
+
370
+ /** Where a catalog is kept beyond the one that holds it, such as a cache
371
+ * every process in a place shares. */
372
+ export type CatalogKept = {
373
+ get(): Promise<HeldCatalog | undefined>
374
+ put(catalog: HeldCatalog): void
375
+ }
376
+
377
+ /** The host catalog (`catalogued`), read again only once it changed: each
378
+ * call reads a stamp of a few rows beside the rest of its moment, and the
379
+ * whole only when the stamp moved. With none held yet, it reads the one
380
+ * `kept` holds beside the stamp, and the whole only where that is not the
381
+ * stamp's; with nothing kept, the whole beside the stamp. The rows are
382
+ * shared by every caller, so none changes them.
383
+ *
384
+ * ```ts
385
+ * import { assertEquals } from '@std/assert'
386
+ * import { catalogHeld } from '@yaks/connections'
387
+ * let asked: string[] = []
388
+ * let read = (q: unknown) => (asked.push(String(q)), Promise.resolve([]))
389
+ * let stamp = '[[],[],[]]'
390
+ * let kept = { get: () => Promise.resolve({ stamp, rows: [] }), put() {} }
391
+ * assertEquals(await catalogHeld(kept)(read), [])
392
+ * assertEquals(asked.length, 3, 'the stamp alone')
393
+ * ```
394
+ */
395
+ export let catalogHeld = (
396
+ kept?: CatalogKept,
397
+ ): Catalog => {
398
+ // Values, never the reads' promises, which settle only in the request that
399
+ // made them (@yaks/fp `Scope`).
400
+ let held: HeldCatalog | undefined
401
+ let whole = async (read: Read, stamp: string) => {
402
+ held = { stamp, rows: await catalogued(read) }
403
+ kept?.put(held)
404
+ return held.rows
405
+ }
406
+ return async (read: Read): Promise<Marked[]> => {
407
+ let stamping = Promise.all(STAMP.map((q) => read(q))).then(JSON.stringify)
408
+ if (held) {
409
+ let stamp = await stamping
410
+ return held.stamp == stamp ? held.rows : await whole(read, stamp)
411
+ }
412
+ if (kept) {
413
+ let [stamp, was] = await Promise.all([
414
+ stamping,
415
+ kept.get().catch(() => undefined),
416
+ ])
417
+ if (was?.stamp != stamp) return await whole(read, stamp)
418
+ held = was
419
+ return held.rows
420
+ }
421
+ let [stamp, rows] = await Promise.all([stamping, catalogued(read)])
422
+ held = { stamp, rows }
423
+ return rows
424
+ }
425
+ }
426
+
427
+ /** What is said about an integration, which its owner may change: never
428
+ * where its credential is sent. */
429
+ export type About = Pick<
430
+ Integration,
431
+ 'title' | 'tagline' | 'site' | 'instructions' | 'example' | 'check' | 'image'
432
+ >
433
+ /** The properties of {@link About}, in the order a page shows them. */
434
+ export let ABOUT = [
435
+ 'title',
436
+ 'tagline',
437
+ 'site',
438
+ 'instructions',
439
+ 'example',
440
+ 'check',
441
+ ] as const
442
+
443
+ let CHECK = /^(GET|HEAD|POST) https:\/\/[^\s/]+\S*$/
444
+
445
+ /** What was said about an integration, as it is written: each property given,
446
+ * trimmed, and an empty one cleared. A site is an https address, the only
447
+ * kind a page links, and a check a method and an https address. */
448
+ export let told = (
449
+ a: Record<string, unknown>,
450
+ ): Record<string, string | null> => {
451
+ let out: Record<string, string | null> = {}
452
+ for (let k of ABOUT) {
453
+ if (a[k] == null) continue
454
+ let v = String(a[k]).trim()
455
+ if (k == 'site' && v && !/^https:\/\/[^\s/]+\S*$/.test(v)) {
456
+ throw new CallError('site', `a site is an https address, not ${v}`)
457
+ }
458
+ if (k == 'check' && v && !CHECK.test(v)) {
459
+ throw new CallError(
460
+ 'check',
461
+ `a check is a method and an https address, GET https://…, not ${v}`,
462
+ )
463
+ }
464
+ out[k] = v || null
465
+ }
466
+ if (a.image != null) {
467
+ if (typeof a.image != 'string' || !/^[a-f0-9]{64}$/.test(a.image)) {
468
+ throw new CallError(
469
+ 'image',
470
+ 'The host must store the integration icon first.',
471
+ )
472
+ }
473
+ out.image = a.image
474
+ }
475
+ return out
476
+ }
477
+
478
+ /** What a custom integration shown in the integration directory wears:
479
+ * @yaks/platform's `published{at}`, as anything shared on a platform does. */
480
+ export let PUBLISHED = 'published'
481
+
482
+ /** The patch publishing a shared thing now, or taking it out. */
483
+ export let publishing = (on: boolean): { at: string } | null =>
484
+ on ? { at: new Date().toISOString() } : null
485
+
486
+ /** An integration's owner changing what is said about it, or publishing it in
487
+ * the integration directory (`listed`) or taking it out. A built one is the
488
+ * host's, and one with no owner (made before owners were kept, or whose owner
489
+ * is gone) is nobody's to change. */
490
+ export let set = async (
491
+ read: Read,
492
+ a: About & { owner: Eid; integration: string; listed?: boolean },
493
+ ): Promise<Bundle[]> => {
494
+ let name = a.integration
495
+ let [held] = await read(
496
+ line`.entity.eid=${integrationEid(name)}&.${INTEGRATION}&?${PUBLISHED}`,
497
+ )
498
+ let i = held?.[INTEGRATION] as Integration | undefined
499
+ if (!i) {
500
+ throw new CallError('integration', `no integration is named ${name}`)
501
+ }
502
+ if (i.built) {
503
+ throw new CallError(
504
+ 'integration',
505
+ `${name} is built, and only the host changes it`,
506
+ )
507
+ }
508
+ if (i.owner != a.owner) {
509
+ throw new CallError('owner', `only the space that made ${name} changes it`)
510
+ }
511
+ let patch = told(a)
512
+ // Published again, it keeps the moment it was first published.
513
+ let listing = a.listed == null || a.listed == !!held[PUBLISHED]
514
+ ? {}
515
+ : { [PUBLISHED]: publishing(a.listed) }
516
+ return Object.keys(patch).length || Object.keys(listing).length
517
+ ? [{
518
+ entity: { eid: integrationEid(name) },
519
+ ...Object.keys(patch).length ? { [INTEGRATION]: patch } : {},
520
+ ...listing,
521
+ $was: { [INTEGRATION]: { owner: token(i.owner) } },
522
+ }]
523
+ : []
524
+ }
525
+
526
+ /** An integration in the integration directory, and since when a custom one
527
+ * is published there. */
528
+ export type Listed = Marked & { published?: string; unchecked?: boolean }
529
+
530
+ // What the directory's words are matched against: an integration's text, and
531
+ // the app a service is.
532
+ let WORDED = [
533
+ 'name',
534
+ 'title',
535
+ 'tagline',
536
+ 'site',
537
+ 'hosts',
538
+ 'instructions',
539
+ 'description',
540
+ 'details',
541
+ 'docs',
542
+ 'connects',
543
+ 'service',
544
+ 'categories',
545
+ ] satisfies (keyof Integration)[]
546
+
547
+ // A property's words: each of a list, each value of an object.
548
+ let spoken = (v: unknown): string =>
549
+ Array.isArray(v)
550
+ ? v.join(' ')
551
+ : v && typeof v == 'object'
552
+ ? Object.values(v).join(' ')
553
+ : String(v ?? '')
554
+
555
+ // The prose a held catalog is without (`catalogued`), which the store
556
+ // searches.
557
+ let PROSE = [
558
+ 'description',
559
+ 'details',
560
+ 'docs',
561
+ 'instructions',
562
+ ] satisfies Prose[]
563
+
564
+ let text = (i: Integration) =>
565
+ WORDED.map((p) => spoken(i[p])).join(' ').toLowerCase()
566
+
567
+ // What a listing reads of a row: the row, and the platform's marks on it.
568
+ let MARKS = line`&?${PUBLISHED}&?unchecked&?${FEATURED}`
569
+
570
+ // What a listing is drawn from: the rows it may list, and the built
571
+ // integrations, which decide what a described row stands in for (`standIn`).
572
+ type Drawn = { rows: Bundle[]; built: Marked[] }
573
+
574
+ // Every row, read whole.
575
+ let every = async (read: Read): Promise<Drawn> => {
576
+ let rows = await read(line`.${INTEGRATION}${sub(MARKS)}`)
577
+ return { rows, built: rows.map(marked).filter((i) => i.built) }
578
+ }
579
+
580
+ // The rows a search reads whole: each one listed by its owner, and those of
581
+ // the catalog holding every word, in what `catalog` holds of it or in its
582
+ // prose, which the store searches. The catalog is a thousand rows of prose,
583
+ // never read whole to find a few.
584
+ let searched = async (
585
+ read: Read,
586
+ terms: string[],
587
+ catalog: Catalog,
588
+ ): Promise<Drawn> => {
589
+ let [held, custom, ...prose] = await Promise.all([
590
+ catalog(read),
591
+ read(line`.${INTEGRATION}.owner&.${PUBLISHED}${sub(MARKS)}`),
592
+ ...terms.map((t) =>
593
+ read(
594
+ line`.${INTEGRATION}&!${INTEGRATION}.owner&(${
595
+ sub(joined(PROSE.map((p) => line`.${INTEGRATION}.${p}~=${t}`), '|'))
596
+ })&.fields=${INTEGRATION}.name`,
597
+ )
598
+ ),
599
+ ])
600
+ let inProse = prose.map((rows) => new Set(rows.map((b) => b.entity.eid)))
601
+ let eids = held.filter((i) =>
602
+ terms.every((t, n) =>
603
+ text(i).includes(t) || inProse[n].has(integrationEid(i.name))
604
+ )
605
+ ).map((i) => integrationEid(i.name))
606
+ let whole = eids.length
607
+ ? await read(line`.entity.eid=${eids}&.${INTEGRATION}${sub(MARKS)}`)
608
+ : []
609
+ let got = new Set(whole.map((b) => b.entity.eid))
610
+ return {
611
+ rows: [...whole, ...custom.filter((b) => !got.has(b.entity.eid))],
612
+ built: held.filter((i) => i.built),
613
+ }
614
+ }
615
+
616
+ /**
617
+ * The integration directory: host catalog services outside testing and custom
618
+ * integrations their owner listed, by title. Words match every part of the
619
+ * service and integration descriptions, including categories and docs. A
620
+ * search takes the catalog without its prose from `catalog`, such as one
621
+ * `catalogHeld` keeps.
622
+ */
623
+ export let listing = async (
624
+ read: Read,
625
+ words = '',
626
+ catalog: Catalog = catalogued,
627
+ ): Promise<Listed[]> => {
628
+ let terms = words.toLowerCase().split(/\s+/).filter(Boolean)
629
+ let { rows, built } = terms.length
630
+ ? await searched(read, terms, catalog)
631
+ : await every(read)
632
+ let all = rows.flatMap(
633
+ (b) => {
634
+ let i = marked(b)
635
+ let at = (b[PUBLISHED] as { at?: string } | undefined)?.at
636
+ // A listing whose owner is gone is nobody's to keep, or take down; one
637
+ // a built integration stands in for is that one.
638
+ return (!i.testing && !i.owner &&
639
+ (i.built ||
640
+ Array.isArray(i.categories) && !standIn(built, i.name))) ||
641
+ (b[PUBLISHED] && i.owner)
642
+ ? [{
643
+ ...i,
644
+ ...at ? { published: at } : {},
645
+ ...b.unchecked ? { unchecked: true } : {},
646
+ }]
647
+ : []
648
+ },
649
+ )
650
+ return all.filter((i) => terms.every((t) => text(i).includes(t)))
651
+ .sort((a, b) =>
652
+ cmp((a.title || a.name).toLowerCase(), (b.title || b.name).toLowerCase())
653
+ )
654
+ }
655
+
656
+ // A value in one order, so two that say the same thing compare equal: every
657
+ // object's properties sorted, and an absent one the same as a cleared one.
658
+ let canon = (v: unknown): unknown =>
659
+ Array.isArray(v)
660
+ ? v.map(canon)
661
+ : v && typeof v == 'object'
662
+ ? Object.entries(v).filter(([, x]) => x != null)
663
+ .sort(([a], [b]) => cmp(a, b)).map(([k, x]) => [k, canon(x)])
664
+ : v
665
+ let said = (v: unknown) => JSON.stringify(canon(v))
666
+
667
+ // Catalog descriptions are maintained in the graph, independently of the
668
+ // operational seed definitions shipped by this package.
669
+ let EDITORIAL = [
670
+ 'title',
671
+ 'tagline',
672
+ 'site',
673
+ 'description',
674
+ 'details',
675
+ 'docs',
676
+ 'categories',
677
+ 'image',
678
+ ]
679
+
680
+ /**
681
+ * The batch that installs built integrations in a graph: each one missing
682
+ * there, or held otherwise than its seed says, with operational seed fields
683
+ * current and graph-authored catalog descriptions preserved, and marked `built`. Nothing, where every one
684
+ * already matches. A host applies it trusted, since `built` is server-owned,
685
+ * once at start-up. `seeds` defaults to this package's own.
686
+ */
687
+ export let install = (
688
+ read: Read,
689
+ seeds: Integration[] = SEEDS,
690
+ ): Bundle[] | Promise<Bundle[]> =>
691
+ after(
692
+ seeds.length
693
+ ? read(
694
+ line`.entity.eid=${
695
+ seeds.map((i) => integrationEid(i.name))
696
+ }&.${INTEGRATION}`,
697
+ )
698
+ : [],
699
+ (found: Bundle[]) => {
700
+ let held = new Map(found.map((b) => [
701
+ b.entity.eid,
702
+ b[INTEGRATION] as Record<string, unknown>,
703
+ ]))
704
+ return seeds.flatMap((seed) => {
705
+ let eid = integrationEid(seed.name)
706
+ let was = held.get(eid) ?? {}
707
+ let editorial = Object.fromEntries(
708
+ EDITORIAL.filter((k) => was[k] != null).map((k) => [k, was[k]]),
709
+ )
710
+ let now: Record<string, unknown> = {
711
+ ...seed,
712
+ ...editorial,
713
+ built: true,
714
+ }
715
+ let gone = Object.keys(was).filter((k) => now[k] == null)
716
+ return said(was) == said(now) ? [] : [{
717
+ entity: { eid },
718
+ [INTEGRATION]: {
719
+ ...Object.fromEntries(gone.map((k) => [k, null])),
720
+ ...now,
721
+ },
722
+ }]
723
+ })
724
+ },
725
+ )