@tschk/moonshine-astro 0.4.4 → 0.4.80
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/README.md +176 -7
- package/package.json +18 -5
- package/src/actions.ts +556 -0
- package/src/assets.ts +710 -0
- package/src/config.ts +269 -0
- package/src/container.ts +560 -0
- package/src/content.ts +1523 -0
- package/src/context.ts +756 -0
- package/src/env.ts +361 -0
- package/src/i18n.ts +420 -0
- package/src/index.ts +264 -0
- package/src/loaders.ts +888 -0
- package/src/middleware.ts +206 -0
- package/src/routing.ts +239 -0
- package/src/ssr.ts +439 -0
- package/src/transitions.ts +496 -0
package/src/assets.ts
ADDED
|
@@ -0,0 +1,710 @@
|
|
|
1
|
+
/** Independent host-free Astro assets & image optimization helpers (`astro:assets`). */
|
|
2
|
+
import type { ImageMetadata } from "./content";
|
|
3
|
+
import { classList, h, type SSRChild } from "./ssr";
|
|
4
|
+
|
|
5
|
+
export type ImageInputFormat =
|
|
6
|
+
"jpeg" | "jpg" | "png" | "tiff" | "webp" | "gif" | "svg" | "avif";
|
|
7
|
+
|
|
8
|
+
export type ImageOutputFormat =
|
|
9
|
+
"avif" | "png" | "webp" | "jpeg" | "jpg" | "svg" | "gif";
|
|
10
|
+
|
|
11
|
+
export type ImageQualityPreset = "low" | "mid" | "high" | "max";
|
|
12
|
+
export type ImageQuality = ImageQualityPreset | number;
|
|
13
|
+
|
|
14
|
+
export type ImageFit =
|
|
15
|
+
"fill" | "contain" | "cover" | "none" | "scale-down" | (string & {});
|
|
16
|
+
|
|
17
|
+
export interface UnresolvedImageTransform {
|
|
18
|
+
src:
|
|
19
|
+
| string
|
|
20
|
+
| ImageMetadata
|
|
21
|
+
| Promise<ImageMetadata | { default: ImageMetadata }>;
|
|
22
|
+
width?: number | `${number}`;
|
|
23
|
+
height?: number | `${number}`;
|
|
24
|
+
widths?: number[];
|
|
25
|
+
densities?: (number | `${number}x`)[];
|
|
26
|
+
sizes?: string;
|
|
27
|
+
format?: ImageOutputFormat;
|
|
28
|
+
quality?: ImageQuality;
|
|
29
|
+
fit?: ImageFit;
|
|
30
|
+
position?: string;
|
|
31
|
+
alt?: string;
|
|
32
|
+
loading?: "lazy" | "eager" | null;
|
|
33
|
+
decoding?: "async" | "sync" | "auto" | null;
|
|
34
|
+
priority?: boolean;
|
|
35
|
+
[key: string]: any;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface ImageProps extends Omit<UnresolvedImageTransform, "src"> {
|
|
39
|
+
src: string | ImageMetadata | { default: ImageMetadata };
|
|
40
|
+
alt: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface PictureProps extends ImageProps {
|
|
44
|
+
formats?: ImageOutputFormat[];
|
|
45
|
+
fallbackFormat?: ImageOutputFormat;
|
|
46
|
+
pictureAttributes?: Record<string, any>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface ResolvedImageTransform extends Omit<
|
|
50
|
+
UnresolvedImageTransform,
|
|
51
|
+
"src" | "width" | "height"
|
|
52
|
+
> {
|
|
53
|
+
src: string | ImageMetadata;
|
|
54
|
+
width?: number;
|
|
55
|
+
height?: number;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface SrcSetValue {
|
|
59
|
+
transform: ResolvedImageTransform;
|
|
60
|
+
url: string;
|
|
61
|
+
descriptor?: string;
|
|
62
|
+
attributes: Record<string, any>;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface GetImageResult {
|
|
66
|
+
rawOptions: ResolvedImageTransform;
|
|
67
|
+
options: ResolvedImageTransform;
|
|
68
|
+
src: string;
|
|
69
|
+
srcSet: {
|
|
70
|
+
values: SrcSetValue[];
|
|
71
|
+
attribute: string;
|
|
72
|
+
};
|
|
73
|
+
attributes: Record<string, any>;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface AstroAssetsConfig {
|
|
77
|
+
endpoint?: string;
|
|
78
|
+
domains?: string[];
|
|
79
|
+
remotePatterns?: {
|
|
80
|
+
protocol?: string;
|
|
81
|
+
hostname?: string;
|
|
82
|
+
port?: string;
|
|
83
|
+
pathname?: string;
|
|
84
|
+
}[];
|
|
85
|
+
defaultFormat?: ImageOutputFormat;
|
|
86
|
+
service?: (transform: ResolvedImageTransform) => string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const DEFAULT_ASSETS_CONFIG: Required<
|
|
90
|
+
Pick<AstroAssetsConfig, "endpoint" | "defaultFormat">
|
|
91
|
+
> &
|
|
92
|
+
AstroAssetsConfig = {
|
|
93
|
+
endpoint: "/_image",
|
|
94
|
+
defaultFormat: "webp",
|
|
95
|
+
domains: [],
|
|
96
|
+
remotePatterns: [],
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
let currentAssetsConfig: typeof DEFAULT_ASSETS_CONFIG = {
|
|
100
|
+
...DEFAULT_ASSETS_CONFIG,
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
export function configureAssets(
|
|
104
|
+
config: AstroAssetsConfig,
|
|
105
|
+
): Readonly<AstroAssetsConfig> {
|
|
106
|
+
currentAssetsConfig = {
|
|
107
|
+
...DEFAULT_ASSETS_CONFIG,
|
|
108
|
+
...config,
|
|
109
|
+
domains: config.domains ? [...config.domains] : [],
|
|
110
|
+
remotePatterns: config.remotePatterns ? [...config.remotePatterns] : [],
|
|
111
|
+
};
|
|
112
|
+
return currentAssetsConfig;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function getAssetsConfig(): Readonly<AstroAssetsConfig> {
|
|
116
|
+
return currentAssetsConfig;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function resetAssetsConfig(): void {
|
|
120
|
+
currentAssetsConfig = { ...DEFAULT_ASSETS_CONFIG };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const QUALITY_PRESETS: Record<ImageQualityPreset, number> = {
|
|
124
|
+
low: 25,
|
|
125
|
+
mid: 50,
|
|
126
|
+
high: 80,
|
|
127
|
+
max: 100,
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
function normalizeDimension(
|
|
131
|
+
value: number | `${number}` | undefined,
|
|
132
|
+
name: "width" | "height",
|
|
133
|
+
): number | undefined {
|
|
134
|
+
if (value === undefined) return undefined;
|
|
135
|
+
const num = typeof value === "number" ? value : Number(value);
|
|
136
|
+
if (!Number.isFinite(num) || num <= 0) {
|
|
137
|
+
throw new Error(`Invalid image ${name}: ${String(value)}`);
|
|
138
|
+
}
|
|
139
|
+
return Math.round(num);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function normalizeQuality(
|
|
143
|
+
quality: ImageQuality | undefined,
|
|
144
|
+
): number | string | undefined {
|
|
145
|
+
if (quality === undefined) return undefined;
|
|
146
|
+
if (typeof quality === "string") {
|
|
147
|
+
return QUALITY_PRESETS[quality] ?? quality;
|
|
148
|
+
}
|
|
149
|
+
return quality;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function defaultTransformUrl(transform: ResolvedImageTransform): string {
|
|
153
|
+
const rawSrc =
|
|
154
|
+
typeof transform.src === "string" ? transform.src : transform.src.src;
|
|
155
|
+
const format =
|
|
156
|
+
transform.format ??
|
|
157
|
+
(typeof transform.src === "object" && transform.src.format === "svg"
|
|
158
|
+
? "svg"
|
|
159
|
+
: currentAssetsConfig.defaultFormat);
|
|
160
|
+
if (format === "svg") {
|
|
161
|
+
return rawSrc;
|
|
162
|
+
}
|
|
163
|
+
const params = new URLSearchParams();
|
|
164
|
+
params.set("href", rawSrc);
|
|
165
|
+
if (transform.width !== undefined) {
|
|
166
|
+
params.set("w", String(transform.width));
|
|
167
|
+
}
|
|
168
|
+
if (transform.height !== undefined) {
|
|
169
|
+
params.set("h", String(transform.height));
|
|
170
|
+
}
|
|
171
|
+
const q = normalizeQuality(transform.quality);
|
|
172
|
+
if (q !== undefined) {
|
|
173
|
+
params.set("q", String(q));
|
|
174
|
+
}
|
|
175
|
+
if (format) {
|
|
176
|
+
params.set("f", format);
|
|
177
|
+
}
|
|
178
|
+
if (transform.fit) {
|
|
179
|
+
params.set("fit", transform.fit);
|
|
180
|
+
}
|
|
181
|
+
if (transform.position) {
|
|
182
|
+
params.set("pos", transform.position);
|
|
183
|
+
}
|
|
184
|
+
return `${currentAssetsConfig.endpoint}?${params.toString()}`;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function buildTransformUrl(transform: ResolvedImageTransform): string {
|
|
188
|
+
if (currentAssetsConfig.service) {
|
|
189
|
+
return currentAssetsConfig.service(transform);
|
|
190
|
+
}
|
|
191
|
+
return defaultTransformUrl(transform);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function unwrapMetadata(
|
|
195
|
+
resolved: string | ImageMetadata | { default: ImageMetadata },
|
|
196
|
+
): string | ImageMetadata {
|
|
197
|
+
if (typeof resolved === "string") return resolved;
|
|
198
|
+
if (
|
|
199
|
+
resolved &&
|
|
200
|
+
typeof resolved === "object" &&
|
|
201
|
+
"default" in resolved &&
|
|
202
|
+
resolved.default
|
|
203
|
+
) {
|
|
204
|
+
return resolved.default;
|
|
205
|
+
}
|
|
206
|
+
return resolved as ImageMetadata;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
function resolveSrcSync(
|
|
210
|
+
src: UnresolvedImageTransform["src"] | { default: ImageMetadata },
|
|
211
|
+
): string | ImageMetadata {
|
|
212
|
+
if (!src) {
|
|
213
|
+
throw new Error("getImage() requires a non-empty `src` option.");
|
|
214
|
+
}
|
|
215
|
+
if (typeof src === "string") return src;
|
|
216
|
+
if (typeof (src as Promise<any>).then === "function") {
|
|
217
|
+
throw new Error(
|
|
218
|
+
"Synchronous image rendering does not accept a Promise `src`; pass resolved ImageMetadata or a URL string.",
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
return unwrapMetadata(src as ImageMetadata | { default: ImageMetadata });
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function resolveSrc(
|
|
225
|
+
src: UnresolvedImageTransform["src"],
|
|
226
|
+
): Promise<string | ImageMetadata> {
|
|
227
|
+
if (!src) {
|
|
228
|
+
throw new Error("getImage() requires a non-empty `src` option.");
|
|
229
|
+
}
|
|
230
|
+
if (typeof src === "string") return src;
|
|
231
|
+
if (typeof (src as Promise<any>).then === "function") {
|
|
232
|
+
const resolved = await (src as Promise<
|
|
233
|
+
ImageMetadata | { default: ImageMetadata }
|
|
234
|
+
>);
|
|
235
|
+
return unwrapMetadata(resolved);
|
|
236
|
+
}
|
|
237
|
+
return unwrapMetadata(src as ImageMetadata | { default: ImageMetadata });
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const TRANSFORM_ONLY_KEYS = /* @__PURE__ */ new Set([
|
|
241
|
+
"src",
|
|
242
|
+
"width",
|
|
243
|
+
"height",
|
|
244
|
+
"widths",
|
|
245
|
+
"densities",
|
|
246
|
+
"format",
|
|
247
|
+
"quality",
|
|
248
|
+
"fit",
|
|
249
|
+
"position",
|
|
250
|
+
"priority",
|
|
251
|
+
"formats",
|
|
252
|
+
"fallbackFormat",
|
|
253
|
+
"pictureAttributes",
|
|
254
|
+
]);
|
|
255
|
+
|
|
256
|
+
function computeImageResult(
|
|
257
|
+
options: UnresolvedImageTransform,
|
|
258
|
+
resolvedSrc: string | ImageMetadata,
|
|
259
|
+
): GetImageResult {
|
|
260
|
+
let width = normalizeDimension(options.width, "width");
|
|
261
|
+
let height = normalizeDimension(options.height, "height");
|
|
262
|
+
|
|
263
|
+
const metaWidth =
|
|
264
|
+
typeof resolvedSrc === "object" ? resolvedSrc.width : undefined;
|
|
265
|
+
const metaHeight =
|
|
266
|
+
typeof resolvedSrc === "object" ? resolvedSrc.height : undefined;
|
|
267
|
+
const aspectRatio =
|
|
268
|
+
metaWidth && metaHeight && metaWidth > 0 && metaHeight > 0
|
|
269
|
+
? metaWidth / metaHeight
|
|
270
|
+
: undefined;
|
|
271
|
+
|
|
272
|
+
if (width !== undefined && height === undefined && aspectRatio) {
|
|
273
|
+
height = Math.round(width / aspectRatio);
|
|
274
|
+
} else if (height !== undefined && width === undefined && aspectRatio) {
|
|
275
|
+
width = Math.round(height * aspectRatio);
|
|
276
|
+
} else if (width === undefined && height === undefined) {
|
|
277
|
+
if (metaWidth !== undefined) width = metaWidth;
|
|
278
|
+
if (metaHeight !== undefined) height = metaHeight;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const rawOptions: ResolvedImageTransform = {
|
|
282
|
+
...options,
|
|
283
|
+
src: resolvedSrc,
|
|
284
|
+
width,
|
|
285
|
+
height,
|
|
286
|
+
};
|
|
287
|
+
|
|
288
|
+
const resolvedFormat: ImageOutputFormat =
|
|
289
|
+
options.format ??
|
|
290
|
+
(typeof resolvedSrc === "object" && resolvedSrc.format === "svg"
|
|
291
|
+
? "svg"
|
|
292
|
+
: currentAssetsConfig.defaultFormat);
|
|
293
|
+
|
|
294
|
+
const validatedOptions: ResolvedImageTransform = {
|
|
295
|
+
...rawOptions,
|
|
296
|
+
format: resolvedFormat,
|
|
297
|
+
};
|
|
298
|
+
|
|
299
|
+
const src = buildTransformUrl(validatedOptions);
|
|
300
|
+
const srcSetValues: SrcSetValue[] = [];
|
|
301
|
+
|
|
302
|
+
if (
|
|
303
|
+
options.densities &&
|
|
304
|
+
options.densities.length > 0 &&
|
|
305
|
+
width !== undefined
|
|
306
|
+
) {
|
|
307
|
+
const baseWidth = width;
|
|
308
|
+
const baseHeight = height;
|
|
309
|
+
for (const rawDensity of options.densities) {
|
|
310
|
+
const factor =
|
|
311
|
+
typeof rawDensity === "number"
|
|
312
|
+
? rawDensity
|
|
313
|
+
: Number.parseFloat(rawDensity.slice(0, -1));
|
|
314
|
+
if (!Number.isFinite(factor) || factor <= 0) continue;
|
|
315
|
+
let targetWidth = Math.round(baseWidth * factor);
|
|
316
|
+
if (metaWidth !== undefined && targetWidth > metaWidth) {
|
|
317
|
+
targetWidth = metaWidth;
|
|
318
|
+
}
|
|
319
|
+
const targetHeight =
|
|
320
|
+
baseHeight !== undefined
|
|
321
|
+
? Math.round((targetWidth / baseWidth) * baseHeight)
|
|
322
|
+
: undefined;
|
|
323
|
+
const variantTransform: ResolvedImageTransform = {
|
|
324
|
+
...validatedOptions,
|
|
325
|
+
width: targetWidth,
|
|
326
|
+
height: targetHeight,
|
|
327
|
+
};
|
|
328
|
+
srcSetValues.push({
|
|
329
|
+
transform: variantTransform,
|
|
330
|
+
url: buildTransformUrl(variantTransform),
|
|
331
|
+
descriptor: `${factor}x`,
|
|
332
|
+
attributes: {
|
|
333
|
+
type: `image/${resolvedFormat === "jpg" ? "jpeg" : resolvedFormat}`,
|
|
334
|
+
},
|
|
335
|
+
});
|
|
336
|
+
}
|
|
337
|
+
} else if (options.widths && options.widths.length > 0) {
|
|
338
|
+
for (const requestedWidth of options.widths) {
|
|
339
|
+
if (!Number.isFinite(requestedWidth) || requestedWidth <= 0) continue;
|
|
340
|
+
const targetWidth =
|
|
341
|
+
metaWidth !== undefined && requestedWidth > metaWidth
|
|
342
|
+
? metaWidth
|
|
343
|
+
: Math.round(requestedWidth);
|
|
344
|
+
const targetHeight =
|
|
345
|
+
aspectRatio !== undefined
|
|
346
|
+
? Math.round(targetWidth / aspectRatio)
|
|
347
|
+
: height !== undefined && width !== undefined
|
|
348
|
+
? Math.round((targetWidth / width) * height)
|
|
349
|
+
: undefined;
|
|
350
|
+
const variantTransform: ResolvedImageTransform = {
|
|
351
|
+
...validatedOptions,
|
|
352
|
+
width: targetWidth,
|
|
353
|
+
height: targetHeight,
|
|
354
|
+
};
|
|
355
|
+
const descriptor = `${targetWidth}w`;
|
|
356
|
+
if (srcSetValues.some((v) => v.descriptor === descriptor)) continue;
|
|
357
|
+
srcSetValues.push({
|
|
358
|
+
transform: variantTransform,
|
|
359
|
+
url: buildTransformUrl(variantTransform),
|
|
360
|
+
descriptor,
|
|
361
|
+
attributes: {
|
|
362
|
+
type: `image/${resolvedFormat === "jpg" ? "jpeg" : resolvedFormat}`,
|
|
363
|
+
},
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const srcSetAttribute = srcSetValues
|
|
369
|
+
.map((entry) =>
|
|
370
|
+
entry.descriptor ? `${entry.url} ${entry.descriptor}` : entry.url,
|
|
371
|
+
)
|
|
372
|
+
.join(", ");
|
|
373
|
+
|
|
374
|
+
const attributes: Record<string, any> = {};
|
|
375
|
+
for (const [key, value] of Object.entries(options)) {
|
|
376
|
+
if (TRANSFORM_ONLY_KEYS.has(key) || value === undefined || value === null) {
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
attributes[key] = value;
|
|
380
|
+
}
|
|
381
|
+
if (attributes["class:list"] !== undefined) {
|
|
382
|
+
const list = attributes["class:list"];
|
|
383
|
+
delete attributes["class:list"];
|
|
384
|
+
const normalized = classList([attributes.class, list]);
|
|
385
|
+
if (normalized) attributes.class = normalized;
|
|
386
|
+
else delete attributes.class;
|
|
387
|
+
}
|
|
388
|
+
if (width !== undefined) attributes.width = width;
|
|
389
|
+
if (height !== undefined) attributes.height = height;
|
|
390
|
+
if (options.priority) {
|
|
391
|
+
if (options.loading !== null) {
|
|
392
|
+
attributes.loading = options.loading ?? "eager";
|
|
393
|
+
}
|
|
394
|
+
if (options.decoding !== null) {
|
|
395
|
+
attributes.decoding = options.decoding ?? "sync";
|
|
396
|
+
}
|
|
397
|
+
if (options.fetchpriority !== null) {
|
|
398
|
+
attributes.fetchpriority = options.fetchpriority ?? "high";
|
|
399
|
+
}
|
|
400
|
+
} else {
|
|
401
|
+
if (options.decoding !== null) {
|
|
402
|
+
attributes.decoding = options.decoding ?? "async";
|
|
403
|
+
}
|
|
404
|
+
if (options.loading !== null) {
|
|
405
|
+
attributes.loading = options.loading ?? "lazy";
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
return {
|
|
410
|
+
rawOptions,
|
|
411
|
+
options: validatedOptions,
|
|
412
|
+
src,
|
|
413
|
+
srcSet: {
|
|
414
|
+
values: srcSetValues,
|
|
415
|
+
attribute: srcSetAttribute,
|
|
416
|
+
},
|
|
417
|
+
attributes,
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export function getImageSync(
|
|
422
|
+
options: UnresolvedImageTransform,
|
|
423
|
+
): GetImageResult {
|
|
424
|
+
if (!options || typeof options !== "object") {
|
|
425
|
+
throw new Error("getImage() requires an options object.");
|
|
426
|
+
}
|
|
427
|
+
if (options.widths && options.densities) {
|
|
428
|
+
throw new Error(
|
|
429
|
+
"getImage() cannot use both `widths` and `densities` at the same time.",
|
|
430
|
+
);
|
|
431
|
+
}
|
|
432
|
+
const resolvedSrc = resolveSrcSync(options.src);
|
|
433
|
+
return computeImageResult(options, resolvedSrc);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
export async function getImage(
|
|
437
|
+
options: UnresolvedImageTransform,
|
|
438
|
+
): Promise<GetImageResult> {
|
|
439
|
+
if (!options || typeof options !== "object") {
|
|
440
|
+
throw new Error("getImage() requires an options object.");
|
|
441
|
+
}
|
|
442
|
+
if (options.widths && options.densities) {
|
|
443
|
+
throw new Error(
|
|
444
|
+
"getImage() cannot use both `widths` and `densities` at the same time.",
|
|
445
|
+
);
|
|
446
|
+
}
|
|
447
|
+
const resolvedSrc = await resolveSrc(options.src);
|
|
448
|
+
return computeImageResult(options, resolvedSrc);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
export function Image(props: ImageProps): SSRChild {
|
|
452
|
+
if (!props || typeof props !== "object") {
|
|
453
|
+
throw new Error("<Image> requires props.");
|
|
454
|
+
}
|
|
455
|
+
if (props.alt === undefined || props.alt === null) {
|
|
456
|
+
throw new Error("<Image> requires an `alt` attribute.");
|
|
457
|
+
}
|
|
458
|
+
const resolved = getImageSync(props as UnresolvedImageTransform);
|
|
459
|
+
const imgAttrs: Record<string, any> = {
|
|
460
|
+
src: resolved.src,
|
|
461
|
+
...(resolved.srcSet.attribute ? { srcset: resolved.srcSet.attribute } : {}),
|
|
462
|
+
...resolved.attributes,
|
|
463
|
+
alt: props.alt,
|
|
464
|
+
};
|
|
465
|
+
return h("img", imgAttrs);
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
export function Picture(props: PictureProps): SSRChild {
|
|
469
|
+
if (!props || typeof props !== "object") {
|
|
470
|
+
throw new Error("<Picture> requires props.");
|
|
471
|
+
}
|
|
472
|
+
if (props.alt === undefined || props.alt === null) {
|
|
473
|
+
throw new Error("<Picture> requires an `alt` attribute.");
|
|
474
|
+
}
|
|
475
|
+
const {
|
|
476
|
+
formats = ["webp"],
|
|
477
|
+
fallbackFormat,
|
|
478
|
+
pictureAttributes = {},
|
|
479
|
+
...imageProps
|
|
480
|
+
} = props;
|
|
481
|
+
const resolvedSrc = resolveSrcSync(imageProps.src);
|
|
482
|
+
const defaultFallback: ImageOutputFormat =
|
|
483
|
+
fallbackFormat ??
|
|
484
|
+
imageProps.format ??
|
|
485
|
+
(typeof resolvedSrc === "object"
|
|
486
|
+
? resolvedSrc.format === "jpg"
|
|
487
|
+
? "jpg"
|
|
488
|
+
: resolvedSrc.format === "svg"
|
|
489
|
+
? "svg"
|
|
490
|
+
: "png"
|
|
491
|
+
: "png");
|
|
492
|
+
|
|
493
|
+
const sources: SSRChild[] = formats.map((fmt) => {
|
|
494
|
+
const sourceImage = computeImageResult(
|
|
495
|
+
{ ...imageProps, src: resolvedSrc, format: fmt },
|
|
496
|
+
resolvedSrc,
|
|
497
|
+
);
|
|
498
|
+
const srcset = sourceImage.srcSet.attribute || sourceImage.src;
|
|
499
|
+
const mime = `image/${fmt === "jpg" ? "jpeg" : fmt === "svg" ? "svg+xml" : fmt}`;
|
|
500
|
+
return h("source", {
|
|
501
|
+
srcset,
|
|
502
|
+
type: mime,
|
|
503
|
+
...(sourceImage.attributes.sizes
|
|
504
|
+
? { sizes: sourceImage.attributes.sizes }
|
|
505
|
+
: {}),
|
|
506
|
+
});
|
|
507
|
+
});
|
|
508
|
+
|
|
509
|
+
const fallbackImage = computeImageResult(
|
|
510
|
+
{ ...imageProps, src: resolvedSrc, format: defaultFallback },
|
|
511
|
+
resolvedSrc,
|
|
512
|
+
);
|
|
513
|
+
const imgAttrs: Record<string, any> = {
|
|
514
|
+
src: fallbackImage.src,
|
|
515
|
+
...(fallbackImage.srcSet.attribute
|
|
516
|
+
? { srcset: fallbackImage.srcSet.attribute }
|
|
517
|
+
: {}),
|
|
518
|
+
...fallbackImage.attributes,
|
|
519
|
+
alt: props.alt,
|
|
520
|
+
};
|
|
521
|
+
|
|
522
|
+
return h("picture", pictureAttributes, ...sources, h("img", imgAttrs));
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
function readUint16BE(bytes: Uint8Array, offset: number): number {
|
|
526
|
+
return (bytes[offset]! << 8) | bytes[offset + 1]!;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
function readUint16LE(bytes: Uint8Array, offset: number): number {
|
|
530
|
+
return bytes[offset]! | (bytes[offset + 1]! << 8);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
function readUint32BE(bytes: Uint8Array, offset: number): number {
|
|
534
|
+
return (
|
|
535
|
+
((bytes[offset]! << 24) |
|
|
536
|
+
(bytes[offset + 1]! << 16) |
|
|
537
|
+
(bytes[offset + 2]! << 8) |
|
|
538
|
+
bytes[offset + 3]!) >>>
|
|
539
|
+
0
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
function readUint24LE(bytes: Uint8Array, offset: number): number {
|
|
544
|
+
return (
|
|
545
|
+
bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16)
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** Inspect image header bytes for dimensions and format (PNG, GIF, JPEG, WebP, SVG). */
|
|
550
|
+
export function inferImageDimensions(bytes: Uint8Array): {
|
|
551
|
+
width: number;
|
|
552
|
+
height: number;
|
|
553
|
+
format: ImageInputFormat;
|
|
554
|
+
orientation?: number;
|
|
555
|
+
} {
|
|
556
|
+
// PNG: 89 50 4E 47 0D 0A 1A 0A + IHDR at offset 16..24
|
|
557
|
+
if (
|
|
558
|
+
bytes.length >= 24 &&
|
|
559
|
+
bytes[0] === 0x89 &&
|
|
560
|
+
bytes[1] === 0x50 &&
|
|
561
|
+
bytes[2] === 0x4e &&
|
|
562
|
+
bytes[3] === 0x47
|
|
563
|
+
) {
|
|
564
|
+
return {
|
|
565
|
+
width: readUint32BE(bytes, 16),
|
|
566
|
+
height: readUint32BE(bytes, 20),
|
|
567
|
+
format: "png",
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
// GIF: "GIF87a" or "GIF89a"
|
|
572
|
+
if (
|
|
573
|
+
bytes.length >= 10 &&
|
|
574
|
+
bytes[0] === 0x47 &&
|
|
575
|
+
bytes[1] === 0x49 &&
|
|
576
|
+
bytes[2] === 0x46 &&
|
|
577
|
+
bytes[3] === 0x38 &&
|
|
578
|
+
(bytes[4] === 0x37 || bytes[4] === 0x39) &&
|
|
579
|
+
bytes[5] === 0x61
|
|
580
|
+
) {
|
|
581
|
+
return {
|
|
582
|
+
width: readUint16LE(bytes, 6),
|
|
583
|
+
height: readUint16LE(bytes, 8),
|
|
584
|
+
format: "gif",
|
|
585
|
+
};
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// WebP: "RIFF" .... "WEBP"
|
|
589
|
+
if (
|
|
590
|
+
bytes.length >= 30 &&
|
|
591
|
+
bytes[0] === 0x52 &&
|
|
592
|
+
bytes[1] === 0x49 &&
|
|
593
|
+
bytes[2] === 0x46 &&
|
|
594
|
+
bytes[3] === 0x46 &&
|
|
595
|
+
bytes[8] === 0x57 &&
|
|
596
|
+
bytes[9] === 0x45 &&
|
|
597
|
+
bytes[10] === 0x42 &&
|
|
598
|
+
bytes[11] === 0x50
|
|
599
|
+
) {
|
|
600
|
+
const chunk = String.fromCharCode(
|
|
601
|
+
bytes[12]!,
|
|
602
|
+
bytes[13]!,
|
|
603
|
+
bytes[14]!,
|
|
604
|
+
bytes[15]!,
|
|
605
|
+
);
|
|
606
|
+
if (chunk === "VP8 ") {
|
|
607
|
+
return {
|
|
608
|
+
width: readUint16LE(bytes, 26) & 0x3fff,
|
|
609
|
+
height: readUint16LE(bytes, 28) & 0x3fff,
|
|
610
|
+
format: "webp",
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
if (chunk === "VP8L" && bytes.length >= 25) {
|
|
614
|
+
const b0 = bytes[21]!;
|
|
615
|
+
const b1 = bytes[22]!;
|
|
616
|
+
const b2 = bytes[23]!;
|
|
617
|
+
const b3 = bytes[24]!;
|
|
618
|
+
return {
|
|
619
|
+
width: 1 + (((b1 & 0x3f) << 8) | b0),
|
|
620
|
+
height: 1 + (((b3 & 0xf) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6)),
|
|
621
|
+
format: "webp",
|
|
622
|
+
};
|
|
623
|
+
}
|
|
624
|
+
if (chunk === "VP8X") {
|
|
625
|
+
return {
|
|
626
|
+
width: 1 + readUint24LE(bytes, 24),
|
|
627
|
+
height: 1 + readUint24LE(bytes, 27),
|
|
628
|
+
format: "webp",
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// JPEG: FF D8
|
|
634
|
+
if (bytes.length >= 4 && bytes[0] === 0xff && bytes[1] === 0xd8) {
|
|
635
|
+
let offset = 2;
|
|
636
|
+
while (offset + 8 < bytes.length) {
|
|
637
|
+
if (bytes[offset] !== 0xff) {
|
|
638
|
+
offset++;
|
|
639
|
+
continue;
|
|
640
|
+
}
|
|
641
|
+
const marker = bytes[offset + 1]!;
|
|
642
|
+
if (marker === 0xff) {
|
|
643
|
+
offset++;
|
|
644
|
+
continue;
|
|
645
|
+
}
|
|
646
|
+
if (
|
|
647
|
+
(marker >= 0xc0 && marker <= 0xc3) ||
|
|
648
|
+
(marker >= 0xc5 && marker <= 0xc7) ||
|
|
649
|
+
(marker >= 0xc9 && marker <= 0xcb) ||
|
|
650
|
+
(marker >= 0xcd && marker <= 0xcf)
|
|
651
|
+
) {
|
|
652
|
+
const height = readUint16BE(bytes, offset + 5);
|
|
653
|
+
const width = readUint16BE(bytes, offset + 7);
|
|
654
|
+
return { width, height, format: "jpg" };
|
|
655
|
+
}
|
|
656
|
+
if (offset + 4 >= bytes.length) break;
|
|
657
|
+
const segmentLength = readUint16BE(bytes, offset + 2);
|
|
658
|
+
if (segmentLength < 2) break;
|
|
659
|
+
offset += 2 + segmentLength;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// SVG text fallback
|
|
664
|
+
const text = new TextDecoder().decode(bytes.subarray(0, 4096)).trim();
|
|
665
|
+
if (text.includes("<svg")) {
|
|
666
|
+
const svgTagMatch = text.match(/<svg\b[^>]*>/i);
|
|
667
|
+
if (svgTagMatch) {
|
|
668
|
+
const tag = svgTagMatch[0];
|
|
669
|
+
const widthMatch = tag.match(/\bwidth=["'](\d+(?:\.\d+)?)(?:px)?["']/i);
|
|
670
|
+
const heightMatch = tag.match(/\bheight=["'](\d+(?:\.\d+)?)(?:px)?["']/i);
|
|
671
|
+
const viewBoxMatch = tag.match(
|
|
672
|
+
/\bviewBox=["']\s*-?\d+(?:\.\d+)?[\s,]+-?\d+(?:\.\d+)?[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)\s*["']/i,
|
|
673
|
+
);
|
|
674
|
+
const width = widthMatch
|
|
675
|
+
? Math.round(Number(widthMatch[1]))
|
|
676
|
+
: viewBoxMatch
|
|
677
|
+
? Math.round(Number(viewBoxMatch[1]))
|
|
678
|
+
: 0;
|
|
679
|
+
const height = heightMatch
|
|
680
|
+
? Math.round(Number(heightMatch[1]))
|
|
681
|
+
: viewBoxMatch
|
|
682
|
+
? Math.round(Number(viewBoxMatch[2]))
|
|
683
|
+
: 0;
|
|
684
|
+
if (width > 0 && height > 0) {
|
|
685
|
+
return { width, height, format: "svg" };
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
throw new Error("Unsupported or corrupted image buffer.");
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
export async function inferRemoteSize(
|
|
694
|
+
url: string | URL,
|
|
695
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
696
|
+
): Promise<{
|
|
697
|
+
width: number;
|
|
698
|
+
height: number;
|
|
699
|
+
format: ImageInputFormat;
|
|
700
|
+
orientation?: number;
|
|
701
|
+
}> {
|
|
702
|
+
const response = await fetchImpl(url);
|
|
703
|
+
if (!response.ok) {
|
|
704
|
+
throw new Error(
|
|
705
|
+
`Failed to fetch remote image ${String(url)}: ${response.status} ${response.statusText}`,
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
const buffer = new Uint8Array(await response.arrayBuffer());
|
|
709
|
+
return inferImageDimensions(buffer);
|
|
710
|
+
}
|