@blogmcp/mdx-schema 0.1.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/dist/checkPin.d.ts +48 -0
- package/dist/checkPin.js +139 -0
- package/dist/checkPin.js.map +1 -0
- package/dist/composables/useMdxParsing.d.ts +71 -0
- package/dist/composables/useMdxParsing.js +239 -0
- package/dist/composables/useMdxParsing.js.map +1 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +22 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata/customComponents.d.ts +128 -0
- package/dist/metadata/customComponents.js +301 -0
- package/dist/metadata/customComponents.js.map +1 -0
- package/dist/metadata/index.d.ts +24 -0
- package/dist/metadata/index.js +427 -0
- package/dist/metadata/index.js.map +1 -0
- package/dist/metadata/validate.d.ts +46 -0
- package/dist/metadata/validate.js +95 -0
- package/dist/metadata/validate.js.map +1 -0
- package/dist/prepareProps.d.ts +42 -0
- package/dist/prepareProps.js +177 -0
- package/dist/prepareProps.js.map +1 -0
- package/dist/styles/index.d.ts +203 -0
- package/dist/styles/index.js +162 -0
- package/dist/styles/index.js.map +1 -0
- package/dist/types/index.d.ts +421 -0
- package/dist/types/index.js +25 -0
- package/dist/types/index.js.map +1 -0
- package/dist/version.d.ts +23 -0
- package/dist/version.js +23 -0
- package/dist/version.js.map +1 -0
- package/package.json +80 -0
- package/src/checkPin.ts +163 -0
- package/src/composables/useMdxParsing.ts +248 -0
- package/src/index.ts +22 -0
- package/src/metadata/customComponents.ts +360 -0
- package/src/metadata/index.ts +437 -0
- package/src/metadata/validate.ts +153 -0
- package/src/prepareProps.ts +219 -0
- package/src/styles/index.ts +196 -0
- package/src/types/index.ts +469 -0
- package/src/version.ts +24 -0
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tenant Custom Component Manifests
|
|
3
|
+
*
|
|
4
|
+
* Per-tenant custom MDX components are stored in `kb_blog_config.config.customComponents`
|
|
5
|
+
* (one entry per PascalCase tag name). Historically an entry was Liquid-template-only
|
|
6
|
+
* (`{ template, description? }`). This module extends an entry to optionally carry a full
|
|
7
|
+
* **manifest** — the same shape as a built-in `ComponentMetadata` — so that:
|
|
8
|
+
*
|
|
9
|
+
* - `editor_list_mdx_components` can return built-in ∪ tenant components (the AI agent
|
|
10
|
+
* discovers the customer's own components + their prop schemas), and
|
|
11
|
+
* - `validateComponent` / `validateMarkdownComponents` accept them on save instead of
|
|
12
|
+
* rejecting every custom tag as "Unknown component".
|
|
13
|
+
*
|
|
14
|
+
* Pure TypeScript — no zod, no framework deps (mirrors the rest of `@blogmcp/mdx-schema`).
|
|
15
|
+
* Validation returns plain error strings so the KB API's `BlogConfigService` (which owns the
|
|
16
|
+
* Liquid-template parse) can reuse it without pulling in a validation library.
|
|
17
|
+
*
|
|
18
|
+
* Rendering is NOT a concern here. A manifest may be template-less (its rendering is delegated
|
|
19
|
+
* to the customer's headless renderer); the Liquid `template` remains the built-in blog's
|
|
20
|
+
* fallback render path and stays optional + backward compatible.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
import type { ComponentMetadata, PropMetadata } from '../types/index.js'
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A tenant-authored custom component entry. All manifest fields are optional — an entry may be
|
|
27
|
+
* Liquid-only (legacy), manifest-only (rendering delegated), or both.
|
|
28
|
+
*/
|
|
29
|
+
export interface CustomComponentEntry {
|
|
30
|
+
/** Agent-facing one-line description. */
|
|
31
|
+
description?: string
|
|
32
|
+
/** Emoji shown in pickers. */
|
|
33
|
+
icon?: string
|
|
34
|
+
/** Grouping category (defaults to 'custom'). */
|
|
35
|
+
category?: string
|
|
36
|
+
/** Alternative tag names / search aliases. */
|
|
37
|
+
aliases?: string[]
|
|
38
|
+
/** Typed prop schema (mirrors built-in `PropMetadata`). */
|
|
39
|
+
props?: PropMetadata[]
|
|
40
|
+
/** Whether the tag wraps children (`<X>…</X>`). */
|
|
41
|
+
hasChildren?: boolean
|
|
42
|
+
/** Whether the tag is self-closing (`<X />`). */
|
|
43
|
+
selfClosing?: boolean
|
|
44
|
+
/** JSX prop string used to seed an editor insert (e.g. `productId=""`). */
|
|
45
|
+
defaultProps?: string
|
|
46
|
+
/** Default children text for an editor insert. */
|
|
47
|
+
defaultChildren?: string
|
|
48
|
+
/** A complete MDX usage example. */
|
|
49
|
+
example?: string
|
|
50
|
+
/** Liquid template body — the built-in blog's fallback render path. Optional. */
|
|
51
|
+
template?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// PascalCase, LETTERS ONLY — must match the MDX parser's component-name grammar
|
|
55
|
+
// (`HAS_MDX_RE`/`MDX_COMPONENT_PATTERN` in composables/useMdxParsing are `[A-Z][a-zA-Z]*`). A
|
|
56
|
+
// digit-bearing name (e.g. `Product3D`) would register here but be mis-parsed/unrecognized at
|
|
57
|
+
// author time, so digits are rejected. Mirrors the admin UI + the legacy blog-config regex.
|
|
58
|
+
const COMPONENT_NAME_RE = /^[A-Z][a-zA-Z]+$/
|
|
59
|
+
const PROP_TYPES = new Set(['string', 'number', 'boolean', 'array', 'object'])
|
|
60
|
+
|
|
61
|
+
/** Hard caps (anti-abuse; mirrors the existing 100KB Liquid cap). */
|
|
62
|
+
export const MAX_CUSTOM_COMPONENTS = 200
|
|
63
|
+
export const MAX_TEMPLATE_BYTES = 100_000
|
|
64
|
+
export const MAX_PROPS_PER_COMPONENT = 64
|
|
65
|
+
|
|
66
|
+
/** `addedIn` stamp for tenant components — never part of the built-in CI compat baseline. */
|
|
67
|
+
export const CUSTOM_COMPONENT_ADDED_IN = '0.0.0'
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* UTF-8 byte length. `TextEncoder` exists in Node ≥11 and every browser, so the package stays
|
|
71
|
+
* runtime-agnostic (no Node `Buffer`). Used for the template byte cap — `String.length` counts
|
|
72
|
+
* UTF-16 code units, which under-counts multibyte (accented/CJK) templates by 2-3×.
|
|
73
|
+
*/
|
|
74
|
+
const byteLength = (s: string): number => new TextEncoder().encode(s).length
|
|
75
|
+
|
|
76
|
+
function validatePropMetadata(componentName: string, index: number, prop: unknown): string[] {
|
|
77
|
+
const errors: string[] = []
|
|
78
|
+
const where = `Custom component "${componentName}" prop #${index + 1}`
|
|
79
|
+
if (!prop || typeof prop !== 'object') {
|
|
80
|
+
errors.push(`${where}: must be an object`)
|
|
81
|
+
return errors
|
|
82
|
+
}
|
|
83
|
+
const p = prop as Record<string, unknown>
|
|
84
|
+
if (typeof p.name !== 'string' || !p.name) errors.push(`${where}: "name" is required`)
|
|
85
|
+
if (typeof p.type !== 'string' || !PROP_TYPES.has(p.type)) {
|
|
86
|
+
errors.push(`${where}: "type" must be one of ${[...PROP_TYPES].join(', ')}`)
|
|
87
|
+
}
|
|
88
|
+
if (p.required !== undefined && typeof p.required !== 'boolean') {
|
|
89
|
+
errors.push(`${where}: "required" must be a boolean`)
|
|
90
|
+
}
|
|
91
|
+
if (p.description !== undefined && typeof p.description !== 'string') {
|
|
92
|
+
errors.push(`${where}: "description" must be a string`)
|
|
93
|
+
}
|
|
94
|
+
if (p.default !== undefined && typeof p.default !== 'string') {
|
|
95
|
+
errors.push(`${where}: "default" must be a string (JSX-serialized)`)
|
|
96
|
+
}
|
|
97
|
+
// Reject an EMPTY enum too — `[].includes(x)` is false for every value, so an empty enum makes the
|
|
98
|
+
// prop impossible to satisfy at author time (validateComponent would reject every value).
|
|
99
|
+
if (p.enum !== undefined && (!Array.isArray(p.enum) || p.enum.length === 0 || p.enum.some(v => typeof v !== 'string'))) {
|
|
100
|
+
errors.push(`${where}: "enum" must be a non-empty array of strings`)
|
|
101
|
+
}
|
|
102
|
+
if (p.numericRange !== undefined) {
|
|
103
|
+
const r = p.numericRange
|
|
104
|
+
if (!Array.isArray(r) || r.length !== 2 || r.some(n => typeof n !== 'number' || !Number.isFinite(n))) {
|
|
105
|
+
// `!Number.isFinite` also rejects NaN/±Infinity, which otherwise compare falsely and would
|
|
106
|
+
// accept or reject every value at author time.
|
|
107
|
+
errors.push(`${where}: "numericRange" must be [min, max] finite numbers`)
|
|
108
|
+
} else if (r[0] > r[1]) {
|
|
109
|
+
// An inverted range (min > max) rejects EVERY value in validateComponent — un-satisfiable prop.
|
|
110
|
+
errors.push(`${where}: "numericRange" min must be ≤ max`)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return errors
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Validate a single tenant custom-component entry. Returns plain error strings (empty = valid).
|
|
118
|
+
* Does NOT validate the Liquid template body — that stays in `BlogConfigService` (owns `liquidjs`).
|
|
119
|
+
*/
|
|
120
|
+
export function validateCustomComponentEntry(name: string, entry: unknown): string[] {
|
|
121
|
+
const errors: string[] = []
|
|
122
|
+
if (!COMPONENT_NAME_RE.test(name)) {
|
|
123
|
+
errors.push(`Invalid custom component name "${name}": must be PascalCase`)
|
|
124
|
+
}
|
|
125
|
+
if (!entry || typeof entry !== 'object') {
|
|
126
|
+
errors.push(`Custom component "${name}": entry must be an object`)
|
|
127
|
+
return errors
|
|
128
|
+
}
|
|
129
|
+
const e = entry as Record<string, unknown>
|
|
130
|
+
|
|
131
|
+
if (e.template !== undefined) {
|
|
132
|
+
if (typeof e.template !== 'string') {
|
|
133
|
+
errors.push(`Custom component "${name}": template must be a string`)
|
|
134
|
+
} else if (byteLength(e.template) > MAX_TEMPLATE_BYTES) {
|
|
135
|
+
errors.push(`Custom component "${name}": template too large (max 100KB)`)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
for (const key of ['description', 'icon', 'category', 'defaultProps', 'defaultChildren', 'example'] as const) {
|
|
139
|
+
if (e[key] !== undefined && typeof e[key] !== 'string') {
|
|
140
|
+
errors.push(`Custom component "${name}": "${key}" must be a string`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
for (const key of ['hasChildren', 'selfClosing'] as const) {
|
|
144
|
+
if (e[key] !== undefined && typeof e[key] !== 'boolean') {
|
|
145
|
+
errors.push(`Custom component "${name}": "${key}" must be a boolean`)
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
if (e.aliases !== undefined && (!Array.isArray(e.aliases) || e.aliases.some(a => typeof a !== 'string'))) {
|
|
149
|
+
errors.push(`Custom component "${name}": "aliases" must be an array of strings`)
|
|
150
|
+
}
|
|
151
|
+
if (e.hasChildren === true && e.selfClosing === true) {
|
|
152
|
+
errors.push(`Custom component "${name}": cannot be both hasChildren and selfClosing`)
|
|
153
|
+
}
|
|
154
|
+
if (e.props !== undefined) {
|
|
155
|
+
if (!Array.isArray(e.props)) {
|
|
156
|
+
errors.push(`Custom component "${name}": "props" must be an array`)
|
|
157
|
+
} else {
|
|
158
|
+
if (e.props.length > MAX_PROPS_PER_COMPONENT) {
|
|
159
|
+
errors.push(`Custom component "${name}": too many props (max ${MAX_PROPS_PER_COMPONENT})`)
|
|
160
|
+
}
|
|
161
|
+
e.props.forEach((p, i) => errors.push(...validatePropMetadata(name, i, p)))
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
return errors
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Validate the whole `customComponents` map. Returns plain error strings (empty = valid).
|
|
169
|
+
* Enforces the component-count cap. Liquid template syntax is validated by the caller.
|
|
170
|
+
*/
|
|
171
|
+
export function validateCustomComponents(customComponents: unknown): string[] {
|
|
172
|
+
if (customComponents === undefined || customComponents === null) return []
|
|
173
|
+
// Messages start with "Custom component" so the KB API route maps them to HTTP 400 (its
|
|
174
|
+
// allowlist matches that prefix) rather than an opaque 500.
|
|
175
|
+
if (typeof customComponents !== 'object' || Array.isArray(customComponents)) {
|
|
176
|
+
return ['Custom components must be an object keyed by PascalCase component name']
|
|
177
|
+
}
|
|
178
|
+
const entries = Object.entries(customComponents as Record<string, unknown>)
|
|
179
|
+
const errors: string[] = []
|
|
180
|
+
if (entries.length > MAX_CUSTOM_COMPONENTS) {
|
|
181
|
+
errors.push(`Custom components: too many (max ${MAX_CUSTOM_COMPONENTS})`)
|
|
182
|
+
}
|
|
183
|
+
for (const [name, entry] of entries) {
|
|
184
|
+
errors.push(...validateCustomComponentEntry(name, entry))
|
|
185
|
+
}
|
|
186
|
+
return errors
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function buildExample(name: string, defaultProps: string, selfClosing: boolean, defaultChildren: string): string {
|
|
190
|
+
const open = defaultProps ? `<${name} ${defaultProps}` : `<${name}`
|
|
191
|
+
// Emit the self-closing form ONLY when the component is actually self-closing, so a non-self-closing
|
|
192
|
+
// component (selfClosing:false) never advertises a contradictory `<X />` example to the agent.
|
|
193
|
+
if (selfClosing) return `${open} />`
|
|
194
|
+
return `${open}>\n${defaultChildren || ' …'}\n</${name}>`
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Map one tenant entry → a full `ComponentMetadata` (fills sensible defaults) so it can be
|
|
199
|
+
* merged with the built-in `componentMetadata` for agent discovery + validation.
|
|
200
|
+
*/
|
|
201
|
+
export function customComponentToMetadata(name: string, entry: CustomComponentEntry): ComponentMetadata {
|
|
202
|
+
// selfClosing/hasChildren are complementary; honor an explicit value, else infer.
|
|
203
|
+
const selfClosing = entry.selfClosing ?? (entry.hasChildren === undefined ? false : !entry.hasChildren)
|
|
204
|
+
const hasChildren = entry.hasChildren ?? !selfClosing
|
|
205
|
+
// Harden against a malformed/legacy entry (props not an array, or null/garbage prop items):
|
|
206
|
+
// discovery must never throw (see buildCustomComponentsMetadata) AND the resulting metadata.props
|
|
207
|
+
// must stay a clean array of objects so a downstream validateComponent loop can't crash on a null.
|
|
208
|
+
const props = (Array.isArray(entry.props) ? entry.props : []).filter(p => p && typeof p === 'object') as PropMetadata[]
|
|
209
|
+
const defaultProps =
|
|
210
|
+
entry.defaultProps ??
|
|
211
|
+
props
|
|
212
|
+
.filter(p => p.required)
|
|
213
|
+
.map(p => `${p.name}=""`)
|
|
214
|
+
.join(' ')
|
|
215
|
+
const defaultChildren = entry.defaultChildren ?? ''
|
|
216
|
+
return {
|
|
217
|
+
name,
|
|
218
|
+
description: entry.description ?? `Custom component ${name}`,
|
|
219
|
+
icon: entry.icon ?? '🧩',
|
|
220
|
+
category: entry.category ?? 'custom',
|
|
221
|
+
// Coerce like `props`: a malformed/legacy entry with a non-array `aliases` must not produce a
|
|
222
|
+
// ComponentMetadata whose `aliases` violates the `string[]` contract (a future alias iterator
|
|
223
|
+
// would `.some`/`.map` on it and crash, AFTER this function returns — past the try/catch backstop).
|
|
224
|
+
aliases: Array.isArray(entry.aliases) ? entry.aliases.filter(a => typeof a === 'string') : [name.toLowerCase()],
|
|
225
|
+
props,
|
|
226
|
+
hasChildren,
|
|
227
|
+
selfClosing,
|
|
228
|
+
defaultProps,
|
|
229
|
+
defaultChildren,
|
|
230
|
+
example: entry.example ?? buildExample(name, defaultProps, selfClosing, defaultChildren),
|
|
231
|
+
addedIn: CUSTOM_COMPONENT_ADDED_IN,
|
|
232
|
+
deprecated: [],
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Map a `customComponents` config object → `ComponentMetadata[]`. Invalid/non-object input
|
|
238
|
+
* yields `[]` (fail-soft — discovery must never throw).
|
|
239
|
+
*/
|
|
240
|
+
export function buildCustomComponentsMetadata(
|
|
241
|
+
customComponents: Record<string, CustomComponentEntry> | undefined | null,
|
|
242
|
+
): ComponentMetadata[] {
|
|
243
|
+
if (!customComponents || typeof customComponents !== 'object') return []
|
|
244
|
+
const out: ComponentMetadata[] = []
|
|
245
|
+
for (const [name, entry] of Object.entries(customComponents)) {
|
|
246
|
+
try {
|
|
247
|
+
out.push(customComponentToMetadata(name, (entry ?? {}) as CustomComponentEntry))
|
|
248
|
+
} catch {
|
|
249
|
+
// A single malformed entry (e.g. a legacy/direct-SQL row predating validateCustomComponents)
|
|
250
|
+
// must not break discovery for the whole tenant. Skip it — discovery never throws.
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
return out
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Result of resolving the tenant custom-component set from a blog-config fetch. */
|
|
257
|
+
export interface CustomComponentsResolution {
|
|
258
|
+
metadata: ComponentMetadata[]
|
|
259
|
+
/**
|
|
260
|
+
* Whether the set is authoritative. `true` → validation may treat an unrecognized component
|
|
261
|
+
* as an error. `false` → the config couldn't be resolved (transient failure), so unknown
|
|
262
|
+
* components must degrade to warnings and the result must NOT be cached.
|
|
263
|
+
*/
|
|
264
|
+
resolved: boolean
|
|
265
|
+
/** Safe to cache (404 = no config row, and any 2xx). Transient errors are NOT cacheable. */
|
|
266
|
+
cacheable: boolean
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Centralized status policy shared by every consumer (md-editor HTTP + stdio + the editor store)
|
|
271
|
+
* so the subtle 404-vs-2xx-vs-error decision can't drift between transports:
|
|
272
|
+
* - 404 → no blog-config row → DEFINITIVELY no custom components (resolved, cacheable).
|
|
273
|
+
* - 2xx → use the config's customComponents (resolved, cacheable).
|
|
274
|
+
* - anything else / network error (`'error'`) → unresolved + NOT cacheable, so the next call
|
|
275
|
+
* retries and a single transient blip can't poison discovery/validation for the cache TTL.
|
|
276
|
+
*/
|
|
277
|
+
export function resolveCustomComponentsFromStatus(
|
|
278
|
+
status: number | 'error',
|
|
279
|
+
customComponents: Record<string, CustomComponentEntry> | undefined | null,
|
|
280
|
+
): CustomComponentsResolution {
|
|
281
|
+
if (status === 404) return { metadata: [], resolved: true, cacheable: true }
|
|
282
|
+
if (typeof status === 'number' && status >= 200 && status < 300) {
|
|
283
|
+
return { metadata: buildCustomComponentsMetadata(customComponents), resolved: true, cacheable: true }
|
|
284
|
+
}
|
|
285
|
+
return { metadata: [], resolved: false, cacheable: false }
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export interface CachedCustomComponents {
|
|
289
|
+
/** Resolve the tenant custom components (cached, fail-soft, status-aware). */
|
|
290
|
+
get(): Promise<{ metadata: ComponentMetadata[]; resolved: boolean }>
|
|
291
|
+
/** Drop the cache (tests / explicit refresh). */
|
|
292
|
+
reset(): void
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Build a TTL-cached resolver for tenant custom components, shared by every consumer (md-editor's
|
|
297
|
+
* HTTP + stdio paths, the editor store) so the cache/TTL/keying/status policy lives in ONE tested
|
|
298
|
+
* place instead of being copy-pasted per transport. The caller supplies the two pieces that
|
|
299
|
+
* genuinely differ per environment:
|
|
300
|
+
* - `keyFn()`: a cheap, no-I/O cache key (e.g. the KB API base URL) so a process that ever serves
|
|
301
|
+
* more than one tenant can't bleed one tenant's components into another. Must not need the
|
|
302
|
+
* network — it's evaluated before the cache check.
|
|
303
|
+
* - `fetchStatus()`: performs the blog-config fetch, returning the HTTP status (or `'error'` on a
|
|
304
|
+
* network failure) + the raw `customComponents`. Transient failures are NOT cached (so the next
|
|
305
|
+
* call retries and a single blip can't poison discovery/validation for the TTL).
|
|
306
|
+
* `now` is injectable for deterministic TTL tests; defaults to `Date.now`.
|
|
307
|
+
*/
|
|
308
|
+
export function makeCustomComponentsResolver(opts: {
|
|
309
|
+
keyFn: () => string
|
|
310
|
+
fetchStatus: () => Promise<{ status: number | 'error'; customComponents?: Record<string, CustomComponentEntry> | null }>
|
|
311
|
+
ttlMs?: number
|
|
312
|
+
now?: () => number
|
|
313
|
+
}): CachedCustomComponents {
|
|
314
|
+
const ttlMs = opts.ttlMs ?? 30_000
|
|
315
|
+
const now = opts.now ?? (() => Date.now())
|
|
316
|
+
let cache: { key: string; at: number; metadata: ComponentMetadata[]; resolved: boolean } | null = null
|
|
317
|
+
let inflight: { key: string; promise: Promise<{ metadata: ComponentMetadata[]; resolved: boolean }> } | null = null
|
|
318
|
+
return {
|
|
319
|
+
async get() {
|
|
320
|
+
let key = ''
|
|
321
|
+
try {
|
|
322
|
+
key = opts.keyFn()
|
|
323
|
+
} catch {
|
|
324
|
+
key = ''
|
|
325
|
+
}
|
|
326
|
+
if (cache && cache.key === key && now() - cache.at < ttlMs) {
|
|
327
|
+
return { metadata: cache.metadata, resolved: cache.resolved }
|
|
328
|
+
}
|
|
329
|
+
// Coalesce concurrent misses for the same key into ONE fetch, so a burst of list/validate calls
|
|
330
|
+
// right after start or TTL-expiry can't stampede the blog-config endpoint.
|
|
331
|
+
if (inflight && inflight.key === key) return inflight.promise
|
|
332
|
+
const promise = (async () => {
|
|
333
|
+
let status: number | 'error' = 'error'
|
|
334
|
+
let customComponents: Record<string, CustomComponentEntry> | null | undefined
|
|
335
|
+
try {
|
|
336
|
+
const r = await opts.fetchStatus()
|
|
337
|
+
status = r.status
|
|
338
|
+
customComponents = r.customComponents
|
|
339
|
+
} catch {
|
|
340
|
+
status = 'error' // network failure
|
|
341
|
+
}
|
|
342
|
+
const res = resolveCustomComponentsFromStatus(status, customComponents)
|
|
343
|
+
// Stamp the cache time AFTER the fetch resolves (not at get() entry) so a fetch slower than
|
|
344
|
+
// ttlMs doesn't land already-expired and silently defeat the cache (re-fetch every call).
|
|
345
|
+
if (res.cacheable) cache = { key, at: now(), metadata: res.metadata, resolved: res.resolved }
|
|
346
|
+
return { metadata: res.metadata, resolved: res.resolved }
|
|
347
|
+
})()
|
|
348
|
+
inflight = { key, promise }
|
|
349
|
+
try {
|
|
350
|
+
return await promise
|
|
351
|
+
} finally {
|
|
352
|
+
if (inflight && inflight.promise === promise) inflight = null
|
|
353
|
+
}
|
|
354
|
+
},
|
|
355
|
+
reset() {
|
|
356
|
+
cache = null
|
|
357
|
+
inflight = null
|
|
358
|
+
},
|
|
359
|
+
}
|
|
360
|
+
}
|