@crombolo/server 0.35.2 → 0.37.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +13 -12
- package/src/adapters/health.ts +23 -0
- package/src/adapters/template-files.ts +6 -1
- package/src/bundles.ts +137 -406
- package/src/components.ts +42 -6
- package/src/config.ts +81 -2
- package/src/index.ts +4 -0
- package/src/islands.ts +197 -0
- package/src/media-access.ts +21 -3
- package/src/middleware.ts +236 -0
- package/src/ports.ts +3 -0
- package/src/routes.ts +420 -0
- package/src/server.ts +562 -60
- package/src/settings.ts +31 -0
- package/src/site-services.ts +99 -0
- package/src/status-pages.ts +128 -0
- package/src/webhook-files.ts +17 -0
- package/src/webhooks.ts +70 -10
package/src/settings.ts
CHANGED
|
@@ -433,6 +433,30 @@ const DECLARED = [
|
|
|
433
433
|
description:
|
|
434
434
|
'How long a page may take to render, layouts included, before it fails, in milliseconds. `0` for no limit.',
|
|
435
435
|
},
|
|
436
|
+
{
|
|
437
|
+
env: 'CROMBOLO_ROUTE_RATE_LIMIT_PER_MINUTE',
|
|
438
|
+
kind: 'number',
|
|
439
|
+
default: '2000',
|
|
440
|
+
section: 'Components',
|
|
441
|
+
description:
|
|
442
|
+
"Requests a minute each caller may make to the site's route handlers, on each server, before a 429. High enough to stop only a flood. `0` for no limit.",
|
|
443
|
+
},
|
|
444
|
+
{
|
|
445
|
+
env: 'CROMBOLO_ROUTE_TIMEOUT_MS',
|
|
446
|
+
kind: 'number',
|
|
447
|
+
default: '10000',
|
|
448
|
+
section: 'Components',
|
|
449
|
+
description:
|
|
450
|
+
'How long a route handler may take before it answers 504, in milliseconds. `0` for no limit.',
|
|
451
|
+
},
|
|
452
|
+
{
|
|
453
|
+
env: 'CROMBOLO_MIDDLEWARE_TIMEOUT_MS',
|
|
454
|
+
kind: 'number',
|
|
455
|
+
default: '2000',
|
|
456
|
+
section: 'Components',
|
|
457
|
+
description:
|
|
458
|
+
"How long a site's whole middleware chain may take, in milliseconds, not counting the page it renders. `0` for no limit.",
|
|
459
|
+
},
|
|
436
460
|
|
|
437
461
|
// Media
|
|
438
462
|
{
|
|
@@ -702,6 +726,13 @@ const DECLARED = [
|
|
|
702
726
|
description:
|
|
703
727
|
'Where visitors see the site, when that is an app on another address, such as https://www.example.com. Used for preferred addresses, the sitemap and robots.txt.',
|
|
704
728
|
},
|
|
729
|
+
{
|
|
730
|
+
env: 'CROMBOLO_SHOW_ERROR_DETAILS',
|
|
731
|
+
kind: 'boolean',
|
|
732
|
+
section: 'Public site',
|
|
733
|
+
description:
|
|
734
|
+
"Shows a server error's message, the template file and line, and the stack on the error page. On in development, off otherwise; with it off a visitor sees only the error's reference, which the log carries too.",
|
|
735
|
+
},
|
|
705
736
|
{
|
|
706
737
|
env: 'CROMBOLO_SITEMAP',
|
|
707
738
|
kind: 'boolean',
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `site()` for a page render (story 206): the site's services acting as
|
|
3
|
+
* whoever is asking. Media the visitor may not read answers `notFound`, never
|
|
4
|
+
* `forbidden`, as `/media/` answers 404. docs/rendering.md, "Server code".
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
type MediaMember,
|
|
8
|
+
type MediaRule,
|
|
9
|
+
memberMay,
|
|
10
|
+
nearestMediaRule,
|
|
11
|
+
ObjectTypes,
|
|
12
|
+
Outcome,
|
|
13
|
+
ok,
|
|
14
|
+
type Result,
|
|
15
|
+
} from '@crombolo/core'
|
|
16
|
+
import { type Db, MediaAccessRepository } from '@crombolo/data'
|
|
17
|
+
import {
|
|
18
|
+
markPersonal,
|
|
19
|
+
type PublishedCache,
|
|
20
|
+
type PublishedMedia,
|
|
21
|
+
type RequestMember,
|
|
22
|
+
type SiteMembers,
|
|
23
|
+
type SiteServices,
|
|
24
|
+
type SiteSql,
|
|
25
|
+
unavailableServices,
|
|
26
|
+
} from '@crombolo/render'
|
|
27
|
+
|
|
28
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
|
29
|
+
|
|
30
|
+
export interface SiteServicesDeps {
|
|
31
|
+
db: Db
|
|
32
|
+
cache: PublishedCache
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Builds `site()`'s services for one request; undefined `member` is a visitor or a previewing editor. */
|
|
36
|
+
export function createSiteServices(deps: SiteServicesDeps) {
|
|
37
|
+
const { db, cache } = deps
|
|
38
|
+
const access = new MediaAccessRepository(db)
|
|
39
|
+
|
|
40
|
+
return (
|
|
41
|
+
member: RequestMember | undefined | (() => Promise<RequestMember | undefined>),
|
|
42
|
+
): (() => SiteServices) => {
|
|
43
|
+
// Middleware asks for the member only when it reads something personal (story 210).
|
|
44
|
+
let reader: Promise<MediaMember | undefined> | undefined
|
|
45
|
+
const readerOf = () => {
|
|
46
|
+
reader ??= (typeof member === 'function' ? member() : Promise.resolve(member)).then(
|
|
47
|
+
(found) => (found ? { key: found.key, groups: found.roles } : undefined),
|
|
48
|
+
)
|
|
49
|
+
return reader
|
|
50
|
+
}
|
|
51
|
+
let rules: Promise<Map<number, MediaRule>> | undefined
|
|
52
|
+
const ruleAt = async (path: string) => {
|
|
53
|
+
rules ??= access.allRules().then((all) => new Map(all.map((r) => [r.nodeId, r])))
|
|
54
|
+
return nearestMediaRule(path, await rules)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Whether the visitor may read it; reading anything closed to strangers makes the page personal. */
|
|
58
|
+
const readable = async (item: PublishedMedia): Promise<boolean> => {
|
|
59
|
+
const rule = await ruleAt(item.path)
|
|
60
|
+
if (memberMay('read', item.access, rule, undefined)) return true
|
|
61
|
+
markPersonal()
|
|
62
|
+
return memberMay('read', item.access, rule, await readerOf())
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const notFound = Outcome.notFound()
|
|
66
|
+
|
|
67
|
+
const media: SiteServices['media'] = {
|
|
68
|
+
async get(key: string): Promise<Result<PublishedMedia, 404>> {
|
|
69
|
+
if (!UUID.test(key)) return notFound
|
|
70
|
+
const item = await cache.media?.byKey(key)
|
|
71
|
+
if (!item || !(await readable(item))) return notFound
|
|
72
|
+
return ok(item)
|
|
73
|
+
},
|
|
74
|
+
async children(folderKey: string): Promise<Result<PublishedMedia[], 404>> {
|
|
75
|
+
if (!UUID.test(folderKey)) return notFound
|
|
76
|
+
const folder = await cache.media?.byKey(folderKey)
|
|
77
|
+
if (!folder || !(await readable(folder))) return notFound
|
|
78
|
+
const rows = await db.query<{ unique_id: string }>(
|
|
79
|
+
'SELECT unique_id FROM node WHERE parent_id = ? AND node_object_type = ? AND trashed = ? ORDER BY sort_order, id',
|
|
80
|
+
[folder.id, ObjectTypes.Media, db.dialect.boolValue(false)],
|
|
81
|
+
)
|
|
82
|
+
const found = (await cache.media?.byKeys(rows.map((row) => row.unique_id))) ?? new Map()
|
|
83
|
+
const items: PublishedMedia[] = []
|
|
84
|
+
for (const row of rows) {
|
|
85
|
+
const item = found.get(row.unique_id.toLowerCase())
|
|
86
|
+
if (item && (await readable(item))) items.push(item)
|
|
87
|
+
}
|
|
88
|
+
return ok(items)
|
|
89
|
+
},
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const services: SiteServices = {
|
|
93
|
+
media,
|
|
94
|
+
sql: unavailableServices<SiteSql>('sql'),
|
|
95
|
+
members: unavailableServices<SiteMembers>('members'),
|
|
96
|
+
}
|
|
97
|
+
return () => services
|
|
98
|
+
}
|
|
99
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The pages that answer a status a page's code ends with (story 206): a page in
|
|
3
|
+
* the content tree named by path in `pages`, rendered at the address asked for,
|
|
4
|
+
* else a generic page for the status. docs/rendering.md, "Status pages".
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
escapeHtml,
|
|
8
|
+
type PageOutcome,
|
|
9
|
+
type PublishedCache,
|
|
10
|
+
type PublishedContent,
|
|
11
|
+
} from '@crombolo/render'
|
|
12
|
+
import type { StatusPage, StatusPageRule, StatusPagesConfig } from './config.ts'
|
|
13
|
+
|
|
14
|
+
export type StatusPageKind = keyof StatusPagesConfig
|
|
15
|
+
|
|
16
|
+
/** Which configured page answers a status: 404 and 401 their own, the rest the error page. */
|
|
17
|
+
export function statusPageKind(status: number): StatusPageKind {
|
|
18
|
+
if (status === 404) return 'notFound'
|
|
19
|
+
if (status === 401) return 'unauthorized'
|
|
20
|
+
return 'error'
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A configured page as rules, the bare path standing for one that matches everything. Pure. */
|
|
24
|
+
export function statusPageRules(page: StatusPage | undefined): StatusPageRule[] {
|
|
25
|
+
if (page === undefined) return []
|
|
26
|
+
if (typeof page === 'string') return page.trim() ? [{ path: page.trim() }] : []
|
|
27
|
+
return page.filter((rule) => typeof rule?.path === 'string' && rule.path.trim())
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The most specific rule for a request: hostname and language, then either, then neither. Pure. */
|
|
31
|
+
export function chooseStatusPageRule(
|
|
32
|
+
rules: readonly StatusPageRule[],
|
|
33
|
+
host: string,
|
|
34
|
+
culture: string | null,
|
|
35
|
+
): StatusPageRule | undefined {
|
|
36
|
+
const bare = host.toLowerCase().replace(/:\d+$/, '')
|
|
37
|
+
const hostMatches = (r: StatusPageRule) =>
|
|
38
|
+
r.host === undefined || [bare, host.toLowerCase()].includes(r.host.trim().toLowerCase())
|
|
39
|
+
const cultureMatches = (r: StatusPageRule) =>
|
|
40
|
+
r.culture === undefined || r.culture.toLowerCase() === (culture ?? '').toLowerCase()
|
|
41
|
+
const score = (r: StatusPageRule) => (r.host ? 2 : 0) + (r.culture ? 1 : 0)
|
|
42
|
+
return rules
|
|
43
|
+
.filter((r) => hostMatches(r) && cultureMatches(r))
|
|
44
|
+
.sort((a, b) => score(b) - score(a))[0]
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* The configured page for a status on this request, in the request's culture;
|
|
49
|
+
* undefined when none is configured or its path resolves to nothing.
|
|
50
|
+
*/
|
|
51
|
+
export async function resolveStatusPage(
|
|
52
|
+
cache: PublishedCache,
|
|
53
|
+
pages: StatusPagesConfig | undefined,
|
|
54
|
+
kind: StatusPageKind,
|
|
55
|
+
host: string,
|
|
56
|
+
pathname: string,
|
|
57
|
+
): Promise<{ content: PublishedContent; culture: string | null } | undefined> {
|
|
58
|
+
const rules = statusPageRules(pages?.[kind])
|
|
59
|
+
if (rules.length === 0) return undefined
|
|
60
|
+
const culture = await cache.cultureFor(host, pathname)
|
|
61
|
+
const rule = chooseStatusPageRule(rules, host, culture)
|
|
62
|
+
if (!rule) return undefined
|
|
63
|
+
const resolved = await cache.resolve(host, rule.path)
|
|
64
|
+
if (!resolved) return undefined
|
|
65
|
+
const localised = culture ? await cache.byKey(resolved.content.key, culture) : undefined
|
|
66
|
+
return localised
|
|
67
|
+
? { content: localised, culture }
|
|
68
|
+
: { content: resolved.content, culture: resolved.culture }
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Each configured path that resolves to nothing on any hostname, for the boot to warn about. */
|
|
72
|
+
export async function unresolvedStatusPages(
|
|
73
|
+
cache: PublishedCache,
|
|
74
|
+
pages: StatusPagesConfig | undefined,
|
|
75
|
+
): Promise<Array<{ kind: StatusPageKind; path: string }>> {
|
|
76
|
+
const missing: Array<{ kind: StatusPageKind; path: string }> = []
|
|
77
|
+
for (const kind of ['notFound', 'unauthorized', 'error'] as const)
|
|
78
|
+
for (const rule of statusPageRules(pages?.[kind]))
|
|
79
|
+
if (!(await cache.resolve(rule.host ?? '', rule.path)))
|
|
80
|
+
missing.push({ kind, path: rule.path })
|
|
81
|
+
return missing
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const HEADINGS: Record<number, string> = {
|
|
85
|
+
400: 'This request could not be used',
|
|
86
|
+
401: 'Please sign in',
|
|
87
|
+
403: 'You do not have access to this page',
|
|
88
|
+
404: 'Page not found',
|
|
89
|
+
410: 'This page is no longer available',
|
|
90
|
+
422: 'Some details need correcting',
|
|
91
|
+
500: 'Something went wrong',
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A page for a status when the site has none of its own, or its own failed. Pure. */
|
|
95
|
+
export function genericStatusPage(outcome: PageOutcome): string {
|
|
96
|
+
const heading = HEADINGS[outcome.status] ?? 'Something went wrong'
|
|
97
|
+
const parts = [`<h1>${escapeHtml(heading)}</h1>`]
|
|
98
|
+
if (outcome.message) parts.push(`<p>${escapeHtml(outcome.message)}</p>`)
|
|
99
|
+
if (outcome.errors.length > 0)
|
|
100
|
+
parts.push(
|
|
101
|
+
`<ul>${outcome.errors
|
|
102
|
+
.map((e) => `<li><strong>${escapeHtml(e.field)}</strong>: ${escapeHtml(e.message)}</li>`)
|
|
103
|
+
.join('')}</ul>`,
|
|
104
|
+
)
|
|
105
|
+
if (outcome.details) {
|
|
106
|
+
parts.push(`<p>${escapeHtml(outcome.details.message)}</p>`)
|
|
107
|
+
if (outcome.details.location)
|
|
108
|
+
parts.push(`<p><code>${escapeHtml(outcome.details.location)}</code></p>`)
|
|
109
|
+
if (outcome.details.stack) parts.push(`<pre>${escapeHtml(outcome.details.stack)}</pre>`)
|
|
110
|
+
}
|
|
111
|
+
if (outcome.reference)
|
|
112
|
+
parts.push(`<p>Reference: <code>${escapeHtml(outcome.reference)}</code></p>`)
|
|
113
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(heading)}</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5;color:#222}pre{overflow:auto;background:#f4f4f4;padding:1rem;font-size:.85rem}</style></head><body><main>${parts.join('')}</main></body></html>`
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const REDIRECT_NAMES: Record<number, string> = {
|
|
117
|
+
301: 'Moved Permanently',
|
|
118
|
+
302: 'Found',
|
|
119
|
+
303: 'See Other',
|
|
120
|
+
307: 'Temporary Redirect',
|
|
121
|
+
308: 'Permanent Redirect',
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** What an editor previewing a page that redirects sees, rather than the frame navigating away. Pure. */
|
|
125
|
+
export function previewRedirectNotice(status: number, location: string): string {
|
|
126
|
+
const name = REDIRECT_NAMES[status] ?? 'Redirect'
|
|
127
|
+
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>This page redirects</title><style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;line-height:1.5}</style></head><body><main><h1>This page redirects</h1><p>Visitors are sent to <a href="${escapeHtml(location)}" target="_top">${escapeHtml(location)}</a> with ${status} ${escapeHtml(name)}.</p></main></body></html>`
|
|
128
|
+
}
|
package/src/webhook-files.ts
CHANGED
|
@@ -25,8 +25,15 @@ export interface WebhookDefinition {
|
|
|
25
25
|
contentTypeKeys: string[]
|
|
26
26
|
/** A value is either `env:NAME` or, kept in the database only, the secret itself. */
|
|
27
27
|
headers: Record<string, string>
|
|
28
|
+
/**
|
|
29
|
+
* What is posted: Umbraco's Minimal `{ Id }`, or `crombolo`, which adds the
|
|
30
|
+
* item's content type and its ancestors' keys (story 208). Set in the file only.
|
|
31
|
+
*/
|
|
32
|
+
payload?: WebhookPayload
|
|
28
33
|
}
|
|
29
34
|
|
|
35
|
+
export type WebhookPayload = 'minimal' | 'crombolo'
|
|
36
|
+
|
|
30
37
|
const ENV_REFERENCE = /^env:([A-Za-z_][A-Za-z0-9_]*)$/
|
|
31
38
|
const HEADER_NAME = /^[A-Za-z0-9!#$%&'*+.^_`|~-]+$/
|
|
32
39
|
/** Set on every delivery, so a webhook may not set them itself. */
|
|
@@ -51,6 +58,10 @@ export function webhookProblems(webhook: WebhookDefinition, store: WebhookStore)
|
|
|
51
58
|
if (!/^https?:\/\/[^\s/]+/.test(webhook.url))
|
|
52
59
|
problems.push('The URL must be a web address starting http:// or https://.')
|
|
53
60
|
if (webhook.events.length === 0) problems.push('Choose at least one event.')
|
|
61
|
+
if (webhook.payload === 'crombolo' && store === 'database')
|
|
62
|
+
problems.push(
|
|
63
|
+
"This webhook sends Crombolo's payload, which is set in its file, so it stays with the site's files.",
|
|
64
|
+
)
|
|
54
65
|
for (const event of webhook.events)
|
|
55
66
|
if (!WEBHOOK_EVENT_ALIASES.has(event))
|
|
56
67
|
problems.push(`"${event}" is not an event this site raises.`)
|
|
@@ -102,6 +113,7 @@ export function writeWebhookFile(
|
|
|
102
113
|
if (!webhook.enabled) out.push('enabled = false')
|
|
103
114
|
out.push(`events = ${list(webhook.events)}`)
|
|
104
115
|
if (contentTypes.length > 0) out.push(`content-types = ${list(contentTypes)}`)
|
|
116
|
+
if (webhook.payload === 'crombolo') out.push('payload = "crombolo"')
|
|
105
117
|
const headers = Object.keys(webhook.headers).sort()
|
|
106
118
|
if (headers.length > 0) {
|
|
107
119
|
out.push('', '[webhook.headers]')
|
|
@@ -120,6 +132,7 @@ const KEYS = new Set([
|
|
|
120
132
|
'events',
|
|
121
133
|
'content-types',
|
|
122
134
|
'headers',
|
|
135
|
+
'payload',
|
|
123
136
|
])
|
|
124
137
|
|
|
125
138
|
/** A file back to a webhook, or what is wrong with it. Unknown keys are refused, as in every schema file. */
|
|
@@ -151,6 +164,9 @@ export function parseWebhookFile(
|
|
|
151
164
|
for (const [name, value] of Object.entries(table.headers as Record<string, unknown>))
|
|
152
165
|
if (typeof value === 'string') headers[name] = value
|
|
153
166
|
else problems.push(`${file}: webhook.headers.${name} must be text`)
|
|
167
|
+
const payload = text('payload')
|
|
168
|
+
if (table.payload !== undefined && payload !== 'minimal' && payload !== 'crombolo')
|
|
169
|
+
problems.push(`${file}: webhook.payload must be "minimal" or "crombolo"`)
|
|
154
170
|
const webhookAlias = text('alias') ?? undefined
|
|
155
171
|
const written = text('key')
|
|
156
172
|
if (written !== null && !/^[0-9a-f-]{36}$/i.test(written))
|
|
@@ -169,6 +185,7 @@ export function parseWebhookFile(
|
|
|
169
185
|
/^[0-9a-f-]{36}$/i.test(value) ? value.toLowerCase() : value,
|
|
170
186
|
),
|
|
171
187
|
headers,
|
|
188
|
+
...(payload === 'crombolo' ? { payload } : {}),
|
|
172
189
|
}
|
|
173
190
|
problems.push(...webhookProblems(webhook, 'files').map((message) => `${file}: ${message}`))
|
|
174
191
|
return problems.length > 0 ? { problems } : { webhook, problems }
|
package/src/webhooks.ts
CHANGED
|
@@ -144,9 +144,25 @@ export interface WebhookServiceOptions {
|
|
|
144
144
|
now?: () => Date
|
|
145
145
|
}
|
|
146
146
|
|
|
147
|
-
/** An event as a webhook delivers it, with the item's type as
|
|
147
|
+
/** An event as a webhook delivers it, with the item's type and place as they were when it happened. */
|
|
148
148
|
export interface WebhookFacts extends RaisedWebhookEvent {
|
|
149
149
|
contentTypeKey?: string
|
|
150
|
+
contentTypeAlias?: string
|
|
151
|
+
/** Its ancestors' keys, nearest first, for Crombolo's payload (story 208). */
|
|
152
|
+
ancestors?: string[]
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** What a webhook is posted. Pure. */
|
|
156
|
+
export function webhookPayload(
|
|
157
|
+
facts: WebhookFacts,
|
|
158
|
+
payload: WebhookDefinition['payload'],
|
|
159
|
+
): Record<string, unknown> {
|
|
160
|
+
if (payload !== 'crombolo') return { Id: facts.key }
|
|
161
|
+
return {
|
|
162
|
+
Id: facts.key,
|
|
163
|
+
ContentType: facts.contentTypeAlias ?? null,
|
|
164
|
+
Ancestors: facts.ancestors ?? [],
|
|
165
|
+
}
|
|
150
166
|
}
|
|
151
167
|
|
|
152
168
|
export interface WebhookService {
|
|
@@ -498,6 +514,10 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
|
|
|
498
514
|
...definition,
|
|
499
515
|
key: existing.key,
|
|
500
516
|
headers: unmask(definition.headers, existing.headers),
|
|
517
|
+
// The back office has no field for it, so an edit there keeps the file's choice.
|
|
518
|
+
...((definition.payload ?? existing.payload)
|
|
519
|
+
? { payload: definition.payload ?? existing.payload }
|
|
520
|
+
: {}),
|
|
501
521
|
}
|
|
502
522
|
return store(next, existing.store)
|
|
503
523
|
},
|
|
@@ -522,17 +542,20 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
|
|
|
522
542
|
return written
|
|
523
543
|
},
|
|
524
544
|
async factsFor(db, event) {
|
|
525
|
-
const
|
|
526
|
-
return
|
|
545
|
+
const item = await itemFacts(db, event.key)
|
|
546
|
+
return item ? { ...event, ...item } : { ...event }
|
|
527
547
|
},
|
|
528
548
|
async enqueueFor(db, eventId, facts) {
|
|
529
|
-
const
|
|
549
|
+
const webhooks = await all()
|
|
550
|
+
const subscribers = subscribersFor(facts, facts.contentTypeKey, webhooks, bundles)
|
|
530
551
|
if (subscribers.length === 0) return 0
|
|
552
|
+
const payloadOf = (subscriber: string) =>
|
|
553
|
+
webhookPayload(facts, webhooks.find((webhook) => webhook.key === subscriber)?.payload)
|
|
531
554
|
const queued = await new WebhookDeliveryRepository(db).enqueue(
|
|
532
555
|
subscribers.map((subscriber) => ({
|
|
533
556
|
subscriber,
|
|
534
557
|
eventAlias: facts.alias,
|
|
535
|
-
payload:
|
|
558
|
+
payload: payloadOf(subscriber),
|
|
536
559
|
eventId,
|
|
537
560
|
})),
|
|
538
561
|
now(),
|
|
@@ -579,13 +602,50 @@ export function createWebhookService(options: WebhookServiceOptions): WebhookSer
|
|
|
579
602
|
}
|
|
580
603
|
|
|
581
604
|
/** An item's type, while it still exists. */
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
605
|
+
/** The item's type and ancestors, read in the change's transaction so a delete still knows them. */
|
|
606
|
+
async function itemFacts(
|
|
607
|
+
db: Db,
|
|
608
|
+
key: string,
|
|
609
|
+
): Promise<Pick<WebhookFacts, 'contentTypeKey' | 'contentTypeAlias' | 'ancestors'> | undefined> {
|
|
610
|
+
const rows = await db.query<{
|
|
611
|
+
type_key: string
|
|
612
|
+
type_alias: string | null
|
|
613
|
+
path: string
|
|
614
|
+
original_path: string | null
|
|
615
|
+
original_parent_id: number | null
|
|
616
|
+
}>(
|
|
617
|
+
`SELECT tn.unique_id AS type_key, ct.alias AS type_alias, n.path AS path,
|
|
618
|
+
op.path AS original_path, d.original_parent_id AS original_parent_id
|
|
619
|
+
FROM node n
|
|
585
620
|
JOIN content c ON c.node_id = n.id
|
|
586
621
|
JOIN node tn ON tn.id = c.content_type_id
|
|
622
|
+
LEFT JOIN content_type ct ON ct.node_id = tn.id
|
|
623
|
+
LEFT JOIN document d ON d.node_id = n.id AND n.trashed = ?
|
|
624
|
+
LEFT JOIN node op ON op.id = d.original_parent_id
|
|
587
625
|
WHERE n.unique_id = ?`,
|
|
588
|
-
[key],
|
|
626
|
+
[db.dialect.boolValue(true), key],
|
|
589
627
|
)
|
|
590
|
-
|
|
628
|
+
const row = rows[0]
|
|
629
|
+
if (!row) return undefined
|
|
630
|
+
// In the recycle bin its path is the bin's, so its ancestors are where it was.
|
|
631
|
+
const chain = row.original_path
|
|
632
|
+
? String(row.original_path).split(',')
|
|
633
|
+
: String(row.path).split(',').slice(0, -1)
|
|
634
|
+
const ids = chain.map(Number).filter((id) => id > 0)
|
|
635
|
+
const found =
|
|
636
|
+
ids.length === 0
|
|
637
|
+
? []
|
|
638
|
+
: await db.query<{ id: number; unique_id: string }>(
|
|
639
|
+
`SELECT id, unique_id FROM node WHERE id IN (${ids.map(() => '?').join(', ')})`,
|
|
640
|
+
ids,
|
|
641
|
+
)
|
|
642
|
+
const keyOf = new Map(found.map((r) => [Number(r.id), String(r.unique_id).toLowerCase()]))
|
|
643
|
+
return {
|
|
644
|
+
contentTypeKey: String(row.type_key).toLowerCase(),
|
|
645
|
+
...(row.type_alias ? { contentTypeAlias: String(row.type_alias) } : {}),
|
|
646
|
+
ancestors: ids
|
|
647
|
+
.reverse()
|
|
648
|
+
.map((id) => keyOf.get(id))
|
|
649
|
+
.filter((k): k is string => Boolean(k)),
|
|
650
|
+
}
|
|
591
651
|
}
|