-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgenerateAltText.ts
More file actions
160 lines (137 loc) · 4.83 KB
/
generateAltText.ts
File metadata and controls
160 lines (137 loc) · 4.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import type { PayloadHandler, PayloadRequest } from 'payload'
import { z, ZodError } from 'zod'
import type { AltTextPluginConfig } from '../types/AltTextPluginConfig.js'
import { matchesMimeType } from '../utilities/mimeTypes.js'
/**
* Generates alt text for a single image using the configured resolver.
*
* By default, returns the result without updating the document (preview mode).
* Pass `update: true` in the request body to also persist the generated alt text
* and keywords to the document — useful for programmatic/agent workflows.
*
* The response always includes the `id` and `collection` for easy correlation.
*/
export const generateAltTextEndpoint =
(access: AltTextPluginConfig['access']): PayloadHandler =>
async (req: PayloadRequest) => {
try {
if (!(await access({ req }))) {
return Response.json({ error: 'Unauthorized' }, { status: 401 })
}
const data = 'json' in req && typeof req.json === 'function' ? await req.json() : null
const requestSchema = z.object({
id: z.union([z.string(), z.number()]),
collection: z.string(),
locale: z.string().nullable(),
update: z.boolean().optional().default(false),
})
const { id, collection, locale, update } = requestSchema.parse(data)
const imageDoc = await req.payload.findByID({
id,
collection,
depth: 0,
})
if (!imageDoc) {
return Response.json({ error: 'Image not found' }, { status: 404 })
}
const pluginConfig = req.payload.config.custom?.altTextPluginConfig as
| AltTextPluginConfig
| undefined
if (!pluginConfig) {
return Response.json({ error: 'Plugin config not found' }, { status: 500 })
}
if (!pluginConfig.getImageThumbnail) {
return Response.json(
{ error: 'getImageThumbnail function not configured' },
{ status: 500 },
)
}
if (!pluginConfig.resolver) {
return Response.json({ error: 'No alt text resolver configured' }, { status: 500 })
}
const mimeType =
'mimeType' in imageDoc && typeof imageDoc.mimeType === 'string'
? imageDoc.mimeType
: undefined
const collectionConfig = pluginConfig.collections.find((entry) => entry.slug === collection)
if (mimeType && collectionConfig && !matchesMimeType(mimeType, collectionConfig.mimeTypes)) {
return Response.json(
{
error: `Alt text is not tracked for files of type "${mimeType}" in the "${collection}" collection. Tracked types: ${collectionConfig.mimeTypes.join(', ')}.`,
},
{ status: 400 },
)
}
if (
mimeType &&
pluginConfig.resolver.supportedMimeTypes &&
!pluginConfig.resolver.supportedMimeTypes.includes(mimeType)
) {
return Response.json(
{
error: `Alt text generation is not supported for files of type "${mimeType}". Supported types: ${pluginConfig.resolver.supportedMimeTypes.join(', ')}.`,
},
{ status: 400 },
)
}
// determine target locale
const targetLocale = locale ?? pluginConfig.locale
if (!targetLocale) {
return Response.json(
{
error:
'Could not determine target locale for alt text generation. Please check your plugin configuration.',
},
{ status: 500 },
)
}
const imageThumbnailUrl = pluginConfig.getImageThumbnail(imageDoc)
const result = await pluginConfig.resolver.resolve({
filename:
'filename' in imageDoc && typeof imageDoc.filename === 'string'
? imageDoc.filename
: undefined,
imageThumbnailUrl,
locale: targetLocale,
req,
})
if (!result.success) {
return Response.json(
{ error: result.error || 'Failed to generate alt text' },
{ status: 500 },
)
}
if (update) {
await req.payload.update({
id,
collection,
data: {
alt: result.result.altText,
keywords: result.result.keywords,
},
locale: targetLocale,
})
}
return Response.json({ id, collection, ...result.result })
} catch (error) {
if (error instanceof ZodError) {
return Response.json(
{
details: error.issues.map((e) => ({
message: e.message,
path: e.path.join('.'),
})),
error: 'Validation failed',
},
{ status: 400 },
)
}
console.error('Error generating alt text:', error)
return Response.json(
{
error: `Error generating alt text: ${error instanceof Error ? error.message : 'Unknown error'}`,
},
{ status: 500 },
)
}
}