@manablox/api-public 0.2.0 → 0.4.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/index.d.ts +190 -0
- package/dist/index.js +435 -0
- package/package.json +17 -10
- package/src/context.ts +0 -23
- package/src/index.ts +0 -3
- package/src/router.ts +0 -365
- package/src/serialize.ts +0 -346
- package/test/serialize.test.ts +0 -178
- package/tsconfig.json +0 -1
- package/vitest.config.ts +0 -5
package/src/index.ts
DELETED
package/src/router.ts
DELETED
|
@@ -1,365 +0,0 @@
|
|
|
1
|
-
import { ManabloxError, resolveGraphQL, TRANSPORT_CODE } from '@manablox/core';
|
|
2
|
-
import type { ContentRow } from '@manablox/db';
|
|
3
|
-
import { type PublicMenuItem, toPublicListQuery } from '@manablox/services';
|
|
4
|
-
import { ORPCError, os } from '@orpc/server';
|
|
5
|
-
import { z } from 'zod';
|
|
6
|
-
import type { PublicContext } from './context.js';
|
|
7
|
-
import {
|
|
8
|
-
type PublicAsset,
|
|
9
|
-
type PublicContent,
|
|
10
|
-
parseExpand,
|
|
11
|
-
serializeAsset,
|
|
12
|
-
serializeContent,
|
|
13
|
-
serializeContents,
|
|
14
|
-
} from './serialize.js';
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* The base procedure.
|
|
18
|
-
*
|
|
19
|
-
* There is no `authed` and no `scoped` sibling here, and that is the point: a public
|
|
20
|
-
* procedure has no principal to check, so the only middleware is the error mapping.
|
|
21
|
-
*/
|
|
22
|
-
const base = os.$context<PublicContext>().use(async ({ next }) => {
|
|
23
|
-
try {
|
|
24
|
-
return await next();
|
|
25
|
-
} catch (error) {
|
|
26
|
-
if (!ManabloxError.is(error)) throw error;
|
|
27
|
-
throw new ORPCError(TRANSPORT_CODE[error.kind], {
|
|
28
|
-
message: error.key,
|
|
29
|
-
data: { key: error.key },
|
|
30
|
-
});
|
|
31
|
-
}
|
|
32
|
-
});
|
|
33
|
-
|
|
34
|
-
const uuid = z.string().uuid();
|
|
35
|
-
const expandArg = z
|
|
36
|
-
.string()
|
|
37
|
-
.max(200)
|
|
38
|
-
.optional()
|
|
39
|
-
.describe('Comma-separated relation fields to inline, e.g. `hero,author`.');
|
|
40
|
-
|
|
41
|
-
const contentSchema: z.ZodType<PublicContent> = z.object({
|
|
42
|
-
id: z.string(),
|
|
43
|
-
type: z.string(),
|
|
44
|
-
title: z.string(),
|
|
45
|
-
slug: z.string(),
|
|
46
|
-
permalink: z.string().nullable(),
|
|
47
|
-
locale: z.string(),
|
|
48
|
-
parentId: z.string().nullable(),
|
|
49
|
-
publishedAt: z.string().nullable(),
|
|
50
|
-
updatedAt: z.string(),
|
|
51
|
-
fields: z.record(z.string(), z.unknown()),
|
|
52
|
-
});
|
|
53
|
-
|
|
54
|
-
const assetSchema: z.ZodType<PublicAsset> = z.object({
|
|
55
|
-
id: z.string(),
|
|
56
|
-
url: z.string(),
|
|
57
|
-
filename: z.string(),
|
|
58
|
-
mimeType: z.string(),
|
|
59
|
-
size: z.number(),
|
|
60
|
-
width: z.number().nullable(),
|
|
61
|
-
height: z.number().nullable(),
|
|
62
|
-
alt: z.string().nullable(),
|
|
63
|
-
title: z.string().nullable(),
|
|
64
|
-
focalPoint: z.object({ x: z.number(), y: z.number() }).nullable(),
|
|
65
|
-
crop: z
|
|
66
|
-
.object({ left: z.number(), top: z.number(), width: z.number(), height: z.number() })
|
|
67
|
-
.nullable(),
|
|
68
|
-
variants: z.record(z.string(), z.string()),
|
|
69
|
-
});
|
|
70
|
-
|
|
71
|
-
/** A menu entry for REST: the document inlined, sub-entries nested. */
|
|
72
|
-
interface PublicMenuEntry {
|
|
73
|
-
id: string;
|
|
74
|
-
label: string;
|
|
75
|
-
url: string | null;
|
|
76
|
-
content: PublicContent | null;
|
|
77
|
-
children: PublicMenuEntry[];
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
const menuItemSchema: z.ZodType<PublicMenuEntry> = z.lazy(() =>
|
|
81
|
-
z.object({
|
|
82
|
-
id: z.string(),
|
|
83
|
-
label: z.string(),
|
|
84
|
-
url: z.string().nullable(),
|
|
85
|
-
content: contentSchema.nullable(),
|
|
86
|
-
children: z.array(menuItemSchema),
|
|
87
|
-
}),
|
|
88
|
-
);
|
|
89
|
-
|
|
90
|
-
const menuSchema = z.object({
|
|
91
|
-
id: z.string(),
|
|
92
|
-
name: z.string(),
|
|
93
|
-
machineName: z.string(),
|
|
94
|
-
items: z.array(menuItemSchema),
|
|
95
|
-
});
|
|
96
|
-
|
|
97
|
-
const listSchema = z.object({
|
|
98
|
-
items: z.array(contentSchema),
|
|
99
|
-
total: z.number(),
|
|
100
|
-
limit: z.number(),
|
|
101
|
-
offset: z.number(),
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
/**
|
|
105
|
-
* The public delivery API: one definition yielding REST, an OpenAPI document and the
|
|
106
|
-
* SDK's types. No `spaceId` appears anywhere — the space is pinned in the context.
|
|
107
|
-
*/
|
|
108
|
-
export const publicRouter = {
|
|
109
|
-
list: base
|
|
110
|
-
.route({
|
|
111
|
-
method: 'GET',
|
|
112
|
-
path: '/content',
|
|
113
|
-
summary: 'List published documents',
|
|
114
|
-
tags: ['content'],
|
|
115
|
-
})
|
|
116
|
-
.input(
|
|
117
|
-
z.object({
|
|
118
|
-
type: z.string().max(100).optional(),
|
|
119
|
-
parentId: uuid.optional(),
|
|
120
|
-
under: uuid.optional(),
|
|
121
|
-
search: z.string().max(200).optional(),
|
|
122
|
-
locale: z.string().max(10).optional(),
|
|
123
|
-
limit: z.coerce.number().int().min(1).max(100).default(25),
|
|
124
|
-
offset: z.coerce.number().int().min(0).default(0),
|
|
125
|
-
expand: expandArg,
|
|
126
|
-
}),
|
|
127
|
-
)
|
|
128
|
-
.output(listSchema)
|
|
129
|
-
.handler(async ({ input, context }) => {
|
|
130
|
-
const query = toPublicListQuery(context.manablox.contentTypes, input, {
|
|
131
|
-
spaceId: context.spaceId,
|
|
132
|
-
locale: context.locale,
|
|
133
|
-
});
|
|
134
|
-
// The published projection, always. There is no other option on this router.
|
|
135
|
-
const page = await context.repos.content.list(
|
|
136
|
-
query.filter,
|
|
137
|
-
query.pagination,
|
|
138
|
-
query.sorts,
|
|
139
|
-
true,
|
|
140
|
-
);
|
|
141
|
-
|
|
142
|
-
return {
|
|
143
|
-
items: await serializeContents(page.items, context, parseExpand(input.expand)),
|
|
144
|
-
total: page.total,
|
|
145
|
-
limit: page.limit,
|
|
146
|
-
offset: page.offset,
|
|
147
|
-
};
|
|
148
|
-
}),
|
|
149
|
-
|
|
150
|
-
get: base
|
|
151
|
-
.route({
|
|
152
|
-
method: 'GET',
|
|
153
|
-
path: '/content/{id}',
|
|
154
|
-
summary: 'Fetch one published document by id',
|
|
155
|
-
tags: ['content'],
|
|
156
|
-
})
|
|
157
|
-
.input(z.object({ id: uuid, expand: expandArg }))
|
|
158
|
-
.output(contentSchema)
|
|
159
|
-
.handler(async ({ input, context }) => {
|
|
160
|
-
// The loader is space-scoped, so an id from another tenant simply does not resolve.
|
|
161
|
-
const row = await context.loaders.publishedContent.load(input.id);
|
|
162
|
-
if (!row) throw ManabloxError.notFound('content.notFound', { id: input.id });
|
|
163
|
-
return serializeContent(row, context, parseExpand(input.expand));
|
|
164
|
-
}),
|
|
165
|
-
|
|
166
|
-
byPermalink: base
|
|
167
|
-
.route({
|
|
168
|
-
method: 'GET',
|
|
169
|
-
path: '/permalink/{+path}',
|
|
170
|
-
summary: 'Resolve a URL path to a document',
|
|
171
|
-
tags: ['content'],
|
|
172
|
-
})
|
|
173
|
-
.input(
|
|
174
|
-
z.object({
|
|
175
|
-
path: z.string().max(2000),
|
|
176
|
-
locale: z.string().max(10).optional(),
|
|
177
|
-
expand: expandArg,
|
|
178
|
-
}),
|
|
179
|
-
)
|
|
180
|
-
.output(contentSchema)
|
|
181
|
-
.handler(({ input, context }) => resolvePermalink(input.path, input, context)),
|
|
182
|
-
|
|
183
|
-
// `{+path}` needs at least one character, so the empty path — the space's home page,
|
|
184
|
-
// which the repository resolves through `settings.homeContentId` — gets a route of
|
|
185
|
-
// its own. The SDK calls it for `byPermalink('/')`.
|
|
186
|
-
home: base
|
|
187
|
-
.route({
|
|
188
|
-
method: 'GET',
|
|
189
|
-
path: '/permalink',
|
|
190
|
-
summary: "Resolve the space's home page",
|
|
191
|
-
tags: ['content'],
|
|
192
|
-
})
|
|
193
|
-
.input(z.object({ locale: z.string().max(10).optional(), expand: expandArg }))
|
|
194
|
-
.output(contentSchema)
|
|
195
|
-
.handler(({ input, context }) => resolvePermalink('', input, context)),
|
|
196
|
-
|
|
197
|
-
menu: base
|
|
198
|
-
.route({
|
|
199
|
-
method: 'GET',
|
|
200
|
-
path: '/menus/{name}',
|
|
201
|
-
summary: 'A navigation menu by name',
|
|
202
|
-
tags: ['content'],
|
|
203
|
-
})
|
|
204
|
-
.input(
|
|
205
|
-
z.object({
|
|
206
|
-
name: z
|
|
207
|
-
.string()
|
|
208
|
-
.regex(/^[a-z][a-z0-9_-]*$/)
|
|
209
|
-
.max(64),
|
|
210
|
-
locale: z.string().max(10).optional(),
|
|
211
|
-
expand: expandArg,
|
|
212
|
-
}),
|
|
213
|
-
)
|
|
214
|
-
.output(menuSchema)
|
|
215
|
-
.handler(async ({ input, context }) => {
|
|
216
|
-
const menu = await context.menus.resolve(
|
|
217
|
-
context.spaceId,
|
|
218
|
-
input.name,
|
|
219
|
-
input.locale ?? context.locale,
|
|
220
|
-
true,
|
|
221
|
-
);
|
|
222
|
-
if (!menu) throw ManabloxError.notFound('menu.notFound', { id: input.name });
|
|
223
|
-
|
|
224
|
-
// One batch for every document in the tree, then the tree is rebuilt around them.
|
|
225
|
-
const rows = collectMenuRows(menu.items);
|
|
226
|
-
const serialised = await serializeContents(rows, context, parseExpand(input.expand));
|
|
227
|
-
const byId = new Map(rows.map((row, index) => [row.id, serialised[index] as PublicContent]));
|
|
228
|
-
const toEntry = (item: PublicMenuItem): PublicMenuEntry => ({
|
|
229
|
-
id: item.id,
|
|
230
|
-
label: item.label,
|
|
231
|
-
url: item.url,
|
|
232
|
-
content: item.content ? (byId.get(item.content.id) ?? null) : null,
|
|
233
|
-
children: item.children.map(toEntry),
|
|
234
|
-
});
|
|
235
|
-
return {
|
|
236
|
-
id: menu.id,
|
|
237
|
-
name: menu.name,
|
|
238
|
-
machineName: menu.machineName,
|
|
239
|
-
items: menu.items.map(toEntry),
|
|
240
|
-
};
|
|
241
|
-
}),
|
|
242
|
-
|
|
243
|
-
asset: base
|
|
244
|
-
.route({
|
|
245
|
-
method: 'GET',
|
|
246
|
-
path: '/assets/{id}',
|
|
247
|
-
summary: 'Fetch asset metadata',
|
|
248
|
-
tags: ['media'],
|
|
249
|
-
})
|
|
250
|
-
.input(z.object({ id: uuid }))
|
|
251
|
-
.output(assetSchema)
|
|
252
|
-
.handler(async ({ input, context }) => {
|
|
253
|
-
// Space-scoped and publication-gated by the loader the public instance builds.
|
|
254
|
-
const asset = await context.loaders.asset.load(input.id);
|
|
255
|
-
if (!asset) throw ManabloxError.notFound('asset.notFound', { id: input.id });
|
|
256
|
-
return serializeAsset(asset, context);
|
|
257
|
-
}),
|
|
258
|
-
|
|
259
|
-
types: base
|
|
260
|
-
.route({
|
|
261
|
-
method: 'GET',
|
|
262
|
-
path: '/types',
|
|
263
|
-
summary: 'The space content model, for SDK type generation',
|
|
264
|
-
tags: ['schema'],
|
|
265
|
-
})
|
|
266
|
-
.input(z.object({}).optional())
|
|
267
|
-
.output(
|
|
268
|
-
z.object({
|
|
269
|
-
types: z.array(
|
|
270
|
-
z.object({
|
|
271
|
-
name: z.string(),
|
|
272
|
-
label: z.string(),
|
|
273
|
-
kind: z.enum(['content', 'block']),
|
|
274
|
-
fields: z.array(
|
|
275
|
-
z.object({
|
|
276
|
-
name: z.string(),
|
|
277
|
-
type: z.string(),
|
|
278
|
-
required: z.boolean(),
|
|
279
|
-
list: z.boolean(),
|
|
280
|
-
/** `scalar` carries a GraphQL scalar name, `ref` a target, `block` neither. */
|
|
281
|
-
kind: z.enum(['scalar', 'ref', 'block']),
|
|
282
|
-
scalar: z.string().optional(),
|
|
283
|
-
target: z.enum(['content', 'asset', 'user']).optional(),
|
|
284
|
-
blockTypes: z.array(z.string()).optional(),
|
|
285
|
-
}),
|
|
286
|
-
),
|
|
287
|
-
}),
|
|
288
|
-
),
|
|
289
|
-
}),
|
|
290
|
-
)
|
|
291
|
-
.handler(({ context }) => {
|
|
292
|
-
const registry = context.manablox.contentTypes;
|
|
293
|
-
|
|
294
|
-
return {
|
|
295
|
-
types: registry.all
|
|
296
|
-
.filter((type) => type.spaceId === null || type.spaceId === context.spaceId)
|
|
297
|
-
.map((type) => ({
|
|
298
|
-
name: type.name,
|
|
299
|
-
label: type.label,
|
|
300
|
-
kind: type.kind,
|
|
301
|
-
fields: type.fields
|
|
302
|
-
// Role-gated fields are absent from every public surface, so they must be
|
|
303
|
-
// absent from the generated types too — otherwise the SDK promises a field
|
|
304
|
-
// that never arrives.
|
|
305
|
-
.filter((field) => !field.readRoles?.length)
|
|
306
|
-
.flatMap((field) => {
|
|
307
|
-
const fieldType = registry.fieldTypes.tryGet(field.type);
|
|
308
|
-
if (!fieldType) return [];
|
|
309
|
-
const spec = resolveGraphQL(fieldType, field.settings);
|
|
310
|
-
const blockTypes = blockTypeNames(context, field.settings);
|
|
311
|
-
|
|
312
|
-
return [
|
|
313
|
-
{
|
|
314
|
-
name: field.name,
|
|
315
|
-
type: field.type,
|
|
316
|
-
required: field.required ?? false,
|
|
317
|
-
list: spec.list ?? false,
|
|
318
|
-
kind: spec.type.kind,
|
|
319
|
-
...(spec.type.kind === 'scalar' ? { scalar: spec.type.name } : {}),
|
|
320
|
-
...(spec.type.kind === 'ref' ? { target: spec.type.target } : {}),
|
|
321
|
-
...(spec.type.kind === 'block' && blockTypes ? { blockTypes } : {}),
|
|
322
|
-
},
|
|
323
|
-
];
|
|
324
|
-
}),
|
|
325
|
-
})),
|
|
326
|
-
};
|
|
327
|
-
}),
|
|
328
|
-
};
|
|
329
|
-
|
|
330
|
-
export type PublicRouter = typeof publicRouter;
|
|
331
|
-
|
|
332
|
-
/** A `blocks` field names its allowed types by id; the SDK needs their names. */
|
|
333
|
-
function blockTypeNames(context: PublicContext, settings: unknown): string[] | undefined {
|
|
334
|
-
const types = (settings as { types?: unknown } | undefined)?.types;
|
|
335
|
-
if (!Array.isArray(types)) return undefined;
|
|
336
|
-
return types
|
|
337
|
-
.filter((id): id is string => typeof id === 'string')
|
|
338
|
-
.map((id) => context.manablox.contentTypes.tryGet(id)?.name)
|
|
339
|
-
.filter((name): name is string => Boolean(name));
|
|
340
|
-
}
|
|
341
|
-
|
|
342
|
-
function collectMenuRows(items: PublicMenuItem[]): ContentRow[] {
|
|
343
|
-
const out: ContentRow[] = [];
|
|
344
|
-
for (const item of items) {
|
|
345
|
-
if (item.content) out.push(item.content);
|
|
346
|
-
out.push(...collectMenuRows(item.children));
|
|
347
|
-
}
|
|
348
|
-
return out;
|
|
349
|
-
}
|
|
350
|
-
|
|
351
|
-
async function resolvePermalink(
|
|
352
|
-
path: string,
|
|
353
|
-
input: { locale?: string | undefined; expand?: string | undefined },
|
|
354
|
-
context: PublicContext,
|
|
355
|
-
): Promise<PublicContent> {
|
|
356
|
-
const permalink = path.replace(/^\/+|\/+$/g, '');
|
|
357
|
-
const row = await context.repos.content.findByPermalink(
|
|
358
|
-
context.spaceId,
|
|
359
|
-
input.locale ?? context.locale,
|
|
360
|
-
permalink,
|
|
361
|
-
true,
|
|
362
|
-
);
|
|
363
|
-
if (!row) throw ManabloxError.notFound('content.notFound', { permalink });
|
|
364
|
-
return serializeContent(row, context, parseExpand(input.expand));
|
|
365
|
-
}
|
package/src/serialize.ts
DELETED
|
@@ -1,346 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
type AssetCrop,
|
|
3
|
-
type ContentTypeDefinition,
|
|
4
|
-
type FocalPoint,
|
|
5
|
-
fieldBlocks,
|
|
6
|
-
type Manablox,
|
|
7
|
-
resolveGraphQL,
|
|
8
|
-
} from '@manablox/core';
|
|
9
|
-
import type { AssetRow, ContentRow, UserRow } from '@manablox/db';
|
|
10
|
-
import { absoluteMediaUrl, readImageEdits } from '@manablox/media';
|
|
11
|
-
import type { PublicContext } from './context.js';
|
|
12
|
-
|
|
13
|
-
export interface PublicAsset {
|
|
14
|
-
id: string;
|
|
15
|
-
url: string;
|
|
16
|
-
filename: string;
|
|
17
|
-
mimeType: string;
|
|
18
|
-
size: number;
|
|
19
|
-
width: number | null;
|
|
20
|
-
height: number | null;
|
|
21
|
-
alt: string | null;
|
|
22
|
-
title: string | null;
|
|
23
|
-
/**
|
|
24
|
-
* Where the subject is, as fractions of the (cropped) image, or `null` for centred.
|
|
25
|
-
* Variants already honour it; it is here for a frontend that renders the original
|
|
26
|
-
* itself, e.g. as CSS `object-position`.
|
|
27
|
-
*/
|
|
28
|
-
focalPoint: FocalPoint | null;
|
|
29
|
-
/** The editor's crop in the original's pixels, or `null`. Variants are cut to it. */
|
|
30
|
-
crop: AssetCrop | null;
|
|
31
|
-
/**
|
|
32
|
-
* Signed transform URLs, keyed by preset name.
|
|
33
|
-
*
|
|
34
|
-
* The signature is an HMAC of the instance's media secret, so a client cannot mint
|
|
35
|
-
* one — an unsigned transform request is a resize amplifier and is refused. That is
|
|
36
|
-
* why the URLs are served rather than constructed in the SDK.
|
|
37
|
-
*/
|
|
38
|
-
variants: Record<string, string>;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
export interface PublicUser {
|
|
42
|
-
id: string;
|
|
43
|
-
name: string;
|
|
44
|
-
image: string | null;
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
export interface PublicContent {
|
|
48
|
-
id: string;
|
|
49
|
-
type: string;
|
|
50
|
-
title: string;
|
|
51
|
-
slug: string;
|
|
52
|
-
permalink: string | null;
|
|
53
|
-
locale: string;
|
|
54
|
-
parentId: string | null;
|
|
55
|
-
publishedAt: string | null;
|
|
56
|
-
updatedAt: string;
|
|
57
|
-
/**
|
|
58
|
-
* A plain map keyed by field name — `{ title, summary, components: [...] }`.
|
|
59
|
-
*
|
|
60
|
-
* GraphQL's per-type object is richer; REST's job is to be pleasant to consume with
|
|
61
|
-
* no schema knowledge, which a keyed map is and a tagged union is not.
|
|
62
|
-
*/
|
|
63
|
-
fields: Record<string, unknown>;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
export interface PublicBlock {
|
|
67
|
-
blockId: string;
|
|
68
|
-
type: string;
|
|
69
|
-
fields: Record<string, unknown>;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
/** Which relation fields to inline rather than leave as ids. */
|
|
73
|
-
export type ExpandSet = ReadonlySet<string>;
|
|
74
|
-
|
|
75
|
-
export function parseExpand(raw: string | undefined): ExpandSet {
|
|
76
|
-
if (!raw) return new Set();
|
|
77
|
-
return new Set(
|
|
78
|
-
raw
|
|
79
|
-
.split(',')
|
|
80
|
-
.map((name) => name.trim())
|
|
81
|
-
.filter(Boolean),
|
|
82
|
-
);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
interface Collected {
|
|
86
|
-
content: Set<string>;
|
|
87
|
-
asset: Set<string>;
|
|
88
|
-
user: Set<string>;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
interface Resolved {
|
|
92
|
-
content: Map<string, ContentRow>;
|
|
93
|
-
asset: Map<string, AssetRow>;
|
|
94
|
-
user: Map<string, UserRow>;
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/**
|
|
98
|
-
* Serialises rows for the REST surface.
|
|
99
|
-
*
|
|
100
|
-
* Three passes, not one: collect every id the expansion will need, load each target in
|
|
101
|
-
* a single batch, then build the output synchronously. Serialising and loading in one
|
|
102
|
-
* pass would still be correct — DataLoader batches within a tick — but it would depend
|
|
103
|
-
* on nothing in the walk ever awaiting, which is exactly the kind of invariant that
|
|
104
|
-
* quietly breaks and reintroduces the N+1 this whole layer exists to avoid.
|
|
105
|
-
*/
|
|
106
|
-
export async function serializeContents(
|
|
107
|
-
rows: ContentRow[],
|
|
108
|
-
ctx: PublicContext,
|
|
109
|
-
expand: ExpandSet,
|
|
110
|
-
): Promise<PublicContent[]> {
|
|
111
|
-
const collected: Collected = { content: new Set(), asset: new Set(), user: new Set() };
|
|
112
|
-
for (const row of rows) collectRow(row, ctx.manablox, expand, collected);
|
|
113
|
-
|
|
114
|
-
const resolved = await resolveAll(collected, ctx);
|
|
115
|
-
return rows.map((row) => buildContent(row, ctx, expand, resolved));
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
export async function serializeContent(
|
|
119
|
-
row: ContentRow,
|
|
120
|
-
ctx: PublicContext,
|
|
121
|
-
expand: ExpandSet,
|
|
122
|
-
): Promise<PublicContent> {
|
|
123
|
-
const [only] = await serializeContents([row], ctx, expand);
|
|
124
|
-
// `serializeContents` maps one-to-one, so this is total; the assertion documents it.
|
|
125
|
-
return only as PublicContent;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
export function serializeAsset(asset: AssetRow, ctx: PublicContext): PublicAsset {
|
|
129
|
-
// Absolute: a delivery consumer is on its own origin, and a root-relative `/media/…`
|
|
130
|
-
// would resolve against the *frontend* rather than the API.
|
|
131
|
-
const base = ctx.manablox.config.server.publicUrl;
|
|
132
|
-
const edits = readImageEdits(asset.meta);
|
|
133
|
-
|
|
134
|
-
return {
|
|
135
|
-
id: asset.id,
|
|
136
|
-
url: absoluteMediaUrl(ctx.media.urlFor(asset), base),
|
|
137
|
-
variants: buildVariants(asset, ctx),
|
|
138
|
-
filename: asset.filename,
|
|
139
|
-
mimeType: asset.mimeType,
|
|
140
|
-
size: asset.size,
|
|
141
|
-
width: asset.width,
|
|
142
|
-
height: asset.height,
|
|
143
|
-
alt: asset.alt,
|
|
144
|
-
title: asset.title,
|
|
145
|
-
focalPoint: edits.focalPoint ?? null,
|
|
146
|
-
crop: edits.crop ?? null,
|
|
147
|
-
};
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
/** Each configured preset, at the format the preset itself declares. */
|
|
151
|
-
function buildVariants(asset: AssetRow, ctx: PublicContext): Record<string, string> {
|
|
152
|
-
if (!asset.mimeType.startsWith('image/')) return {};
|
|
153
|
-
|
|
154
|
-
const presets = ctx.manablox.config.media.presets;
|
|
155
|
-
const base = ctx.manablox.config.server.publicUrl;
|
|
156
|
-
|
|
157
|
-
const out: Record<string, string> = {};
|
|
158
|
-
for (const [name, preset] of Object.entries(presets)) {
|
|
159
|
-
out[name] = absoluteMediaUrl(ctx.media.urlFor(asset, name, preset.format ?? 'webp'), base);
|
|
160
|
-
}
|
|
161
|
-
return out;
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// ---------------------------------------------------------------------------
|
|
165
|
-
// Pass 1 — collect
|
|
166
|
-
// ---------------------------------------------------------------------------
|
|
167
|
-
|
|
168
|
-
function collectRow(row: ContentRow, manablox: Manablox, expand: ExpandSet, into: Collected): void {
|
|
169
|
-
const type = manablox.contentTypes.tryGet(row.typeId);
|
|
170
|
-
if (!type) return;
|
|
171
|
-
collectFields(type, row.fields, manablox, expand, into, 0);
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
function collectFields(
|
|
175
|
-
type: ContentTypeDefinition,
|
|
176
|
-
values: Record<string, unknown>,
|
|
177
|
-
manablox: Manablox,
|
|
178
|
-
expand: ExpandSet,
|
|
179
|
-
into: Collected,
|
|
180
|
-
depth: number,
|
|
181
|
-
): void {
|
|
182
|
-
if (depth > 16) return;
|
|
183
|
-
|
|
184
|
-
for (const field of type.fields) {
|
|
185
|
-
if (field.readRoles?.length) continue;
|
|
186
|
-
const fieldType = manablox.fieldTypes.tryGet(field.type);
|
|
187
|
-
if (!fieldType) continue;
|
|
188
|
-
|
|
189
|
-
const value = values[field.name];
|
|
190
|
-
const spec = resolveGraphQL(fieldType, field.settings);
|
|
191
|
-
|
|
192
|
-
if (spec.type.kind === 'ref' && expand.has(field.name)) {
|
|
193
|
-
for (const id of toIds(value)) into[spec.type.target].add(id);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
if (fieldType.nested) {
|
|
197
|
-
for (const block of fieldBlocks(fieldType, value, field.settings)) {
|
|
198
|
-
const blockType = manablox.contentTypes.tryGet(block.type);
|
|
199
|
-
if (blockType) {
|
|
200
|
-
collectFields(blockType, block.fields, manablox, expand, into, depth + 1);
|
|
201
|
-
}
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// ---------------------------------------------------------------------------
|
|
208
|
-
// Pass 2 — load
|
|
209
|
-
// ---------------------------------------------------------------------------
|
|
210
|
-
|
|
211
|
-
async function resolveAll(collected: Collected, ctx: PublicContext): Promise<Resolved> {
|
|
212
|
-
const [contents, assets, users] = await Promise.all([
|
|
213
|
-
loadMany(ctx.loaders.publishedContent, collected.content),
|
|
214
|
-
loadMany(ctx.loaders.asset, collected.asset),
|
|
215
|
-
loadMany(ctx.loaders.user, collected.user),
|
|
216
|
-
]);
|
|
217
|
-
|
|
218
|
-
return { content: contents, asset: assets, user: users };
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async function loadMany<T extends { id: string }>(
|
|
222
|
-
loader: { loadMany: (ids: string[]) => Promise<Array<T | null | Error>> },
|
|
223
|
-
ids: Set<string>,
|
|
224
|
-
): Promise<Map<string, T>> {
|
|
225
|
-
if (ids.size === 0) return new Map();
|
|
226
|
-
const rows = await loader.loadMany([...ids]);
|
|
227
|
-
const map = new Map<string, T>();
|
|
228
|
-
for (const row of rows) {
|
|
229
|
-
if (row && !(row instanceof Error)) map.set(row.id, row);
|
|
230
|
-
}
|
|
231
|
-
return map;
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
// ---------------------------------------------------------------------------
|
|
235
|
-
// Pass 3 — build
|
|
236
|
-
// ---------------------------------------------------------------------------
|
|
237
|
-
|
|
238
|
-
function buildContent(
|
|
239
|
-
row: ContentRow,
|
|
240
|
-
ctx: PublicContext,
|
|
241
|
-
expand: ExpandSet,
|
|
242
|
-
resolved: Resolved,
|
|
243
|
-
): PublicContent {
|
|
244
|
-
const type = ctx.manablox.contentTypes.tryGet(row.typeId);
|
|
245
|
-
return {
|
|
246
|
-
id: row.id,
|
|
247
|
-
type: type?.name ?? 'unknown',
|
|
248
|
-
title: row.title,
|
|
249
|
-
slug: row.slug,
|
|
250
|
-
permalink: row.permalink,
|
|
251
|
-
locale: row.locale,
|
|
252
|
-
parentId: row.parentId,
|
|
253
|
-
publishedAt: row.publishedAt ? row.publishedAt.toISOString() : null,
|
|
254
|
-
updatedAt: row.updatedAt.toISOString(),
|
|
255
|
-
fields: type ? buildFields(type, row.fields, ctx, expand, resolved, 0) : {},
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
function buildFields(
|
|
260
|
-
type: ContentTypeDefinition,
|
|
261
|
-
values: Record<string, unknown>,
|
|
262
|
-
ctx: PublicContext,
|
|
263
|
-
expand: ExpandSet,
|
|
264
|
-
resolved: Resolved,
|
|
265
|
-
depth: number,
|
|
266
|
-
): Record<string, unknown> {
|
|
267
|
-
const out: Record<string, unknown> = {};
|
|
268
|
-
if (depth > 16) return out;
|
|
269
|
-
|
|
270
|
-
for (const field of type.fields) {
|
|
271
|
-
// Role-gated fields are omitted entirely, exactly as in the GraphQL schema — a
|
|
272
|
-
// surface that returned them would make the two views disagree.
|
|
273
|
-
if (field.readRoles?.length) continue;
|
|
274
|
-
|
|
275
|
-
const fieldType = ctx.manablox.fieldTypes.tryGet(field.type);
|
|
276
|
-
if (!fieldType) continue;
|
|
277
|
-
|
|
278
|
-
const value = values[field.name];
|
|
279
|
-
const spec = resolveGraphQL(fieldType, field.settings);
|
|
280
|
-
|
|
281
|
-
if (fieldType.nested) {
|
|
282
|
-
const blocks = fieldBlocks(fieldType, value, field.settings).map((block) => {
|
|
283
|
-
const blockType = ctx.manablox.contentTypes.tryGet(block.type);
|
|
284
|
-
return {
|
|
285
|
-
blockId: block.blockId,
|
|
286
|
-
type: blockType?.name ?? 'unknown',
|
|
287
|
-
fields: blockType
|
|
288
|
-
? buildFields(blockType, block.fields, ctx, expand, resolved, depth + 1)
|
|
289
|
-
: {},
|
|
290
|
-
} satisfies PublicBlock;
|
|
291
|
-
});
|
|
292
|
-
out[field.name] = spec.list === false ? (blocks[0] ?? null) : blocks;
|
|
293
|
-
continue;
|
|
294
|
-
}
|
|
295
|
-
|
|
296
|
-
if (spec.type.kind === 'ref' && expand.has(field.name)) {
|
|
297
|
-
const ids = toIds(value);
|
|
298
|
-
const inlined = ids
|
|
299
|
-
.map((id) =>
|
|
300
|
-
inline(spec.type.kind === 'ref' ? spec.type.target : 'content', id, ctx, resolved),
|
|
301
|
-
)
|
|
302
|
-
.filter((entry) => entry !== null);
|
|
303
|
-
out[field.name] = spec.list ? inlined : (inlined[0] ?? null);
|
|
304
|
-
continue;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
out[field.name] = value ?? null;
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
return out;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
function inline(
|
|
314
|
-
target: 'content' | 'asset' | 'user',
|
|
315
|
-
id: string,
|
|
316
|
-
ctx: PublicContext,
|
|
317
|
-
resolved: Resolved,
|
|
318
|
-
): unknown {
|
|
319
|
-
if (target === 'asset') {
|
|
320
|
-
const asset = resolved.asset.get(id);
|
|
321
|
-
return asset ? serializeAsset(asset, ctx) : null;
|
|
322
|
-
}
|
|
323
|
-
if (target === 'user') {
|
|
324
|
-
const user = resolved.user.get(id);
|
|
325
|
-
return user ? ({ id: user.id, name: user.name, image: user.image } satisfies PublicUser) : null;
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
const row = resolved.content.get(id);
|
|
329
|
-
if (!row) return null;
|
|
330
|
-
// A one-level summary, not a recursive expansion: `?expand=` inlining its own
|
|
331
|
-
// relations is how a cheap parameter becomes an unbounded traversal.
|
|
332
|
-
return {
|
|
333
|
-
id: row.id,
|
|
334
|
-
type: ctx.manablox.contentTypes.tryGet(row.typeId)?.name ?? 'unknown',
|
|
335
|
-
title: row.title,
|
|
336
|
-
permalink: row.permalink,
|
|
337
|
-
locale: row.locale,
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
function toIds(value: unknown): string[] {
|
|
342
|
-
if (typeof value === 'string') return [value];
|
|
343
|
-
if (Array.isArray(value))
|
|
344
|
-
return value.filter((entry): entry is string => typeof entry === 'string');
|
|
345
|
-
return [];
|
|
346
|
-
}
|