Skip to main content

devimg_core/
manifest.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::Path;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use serde::{Deserialize, Serialize};
7
8use crate::{DevimgError, Result};
9
10#[derive(Debug, Clone, Serialize, Deserialize)]
11pub struct Manifest {
12    #[serde(default = "default_version")]
13    pub version: u32,
14    #[serde(default = "unknown_generated_at")]
15    pub generated_at: String,
16    pub config_path: String,
17    pub config_hash: String,
18    pub outputs: Vec<ManifestOutput>,
19}
20
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub struct ManifestOutput {
23    pub source_path: String,
24    pub source_hash: String,
25    pub source_width: u32,
26    pub source_height: u32,
27    pub source_bytes: u64,
28    pub output_path: String,
29    pub preset: String,
30    #[serde(default = "unknown_fit")]
31    pub fit: String,
32    pub width: u32,
33    pub height: u32,
34    pub format: String,
35    pub bytes: u64,
36    pub hash: String,
37    pub operation_hash: String,
38}
39
40impl Manifest {
41    pub fn new(config_path: String, config_hash: String, outputs: Vec<ManifestOutput>) -> Self {
42        Self {
43            version: default_version(),
44            generated_at: generated_at(),
45            config_path,
46            config_hash,
47            outputs,
48        }
49    }
50
51    pub fn source_bytes_total(&self) -> u64 {
52        let mut seen = Vec::<(&str, u64)>::new();
53        for output in &self.outputs {
54            if !seen.iter().any(|(path, _)| *path == output.source_path) {
55                seen.push((&output.source_path, output.source_bytes));
56            }
57        }
58        seen.iter().map(|(_, bytes)| *bytes).sum()
59    }
60
61    pub fn output_bytes_total(&self) -> u64 {
62        self.outputs.iter().map(|output| output.bytes).sum()
63    }
64}
65
66#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
67pub struct ManifestExport {
68    pub version: u32,
69    pub generated_at: String,
70    pub config_hash: String,
71    pub sources: Vec<ManifestExportSource>,
72}
73
74#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
75pub struct ManifestExportSource {
76    pub source_path: String,
77    pub source_hash: String,
78    pub source_width: u32,
79    pub source_height: u32,
80    pub source_bytes: u64,
81    pub variants: Vec<ManifestExportVariant>,
82}
83
84#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
85pub struct ManifestExportVariant {
86    pub src: String,
87    pub output_path: String,
88    pub preset: String,
89    pub fit: String,
90    pub width: u32,
91    pub height: u32,
92    pub format: String,
93    pub bytes: u64,
94    pub hash: String,
95}
96
97#[derive(Debug, Clone, Default, PartialEq, Eq)]
98pub struct ManifestExportOptions {
99    pub strip_prefix: Option<String>,
100    pub url_prefix: String,
101}
102
103#[derive(Debug, Clone, Default, PartialEq, Eq)]
104pub struct ManifestTypescriptOptions {
105    pub include_helpers: bool,
106}
107
108pub fn export_manifest(manifest: &Manifest, options: &ManifestExportOptions) -> ManifestExport {
109    let mut sources = BTreeMap::<String, ManifestExportSource>::new();
110    for output in &manifest.outputs {
111        let source = sources
112            .entry(output.source_path.clone())
113            .or_insert_with(|| ManifestExportSource {
114                source_path: output.source_path.clone(),
115                source_hash: output.source_hash.clone(),
116                source_width: output.source_width,
117                source_height: output.source_height,
118                source_bytes: output.source_bytes,
119                variants: Vec::new(),
120            });
121        source.variants.push(ManifestExportVariant {
122            src: manifest_variant_src(&output.output_path, options),
123            output_path: output.output_path.clone(),
124            preset: output.preset.clone(),
125            fit: output.fit.clone(),
126            width: output.width,
127            height: output.height,
128            format: output.format.clone(),
129            bytes: output.bytes,
130            hash: output.hash.clone(),
131        });
132    }
133
134    ManifestExport {
135        version: manifest.version,
136        generated_at: manifest.generated_at.clone(),
137        config_hash: manifest.config_hash.clone(),
138        sources: sources.into_values().collect(),
139    }
140}
141
142pub fn manifest_export_to_json(manifest: &Manifest, options: &ManifestExportOptions) -> String {
143    let document = export_manifest(manifest, options);
144    serde_json::to_string_pretty(&document).expect("manifest export serialization cannot fail")
145        + "\n"
146}
147
148pub fn manifest_export_to_typescript(
149    manifest: &Manifest,
150    options: &ManifestExportOptions,
151) -> String {
152    manifest_export_to_typescript_with_options(
153        manifest,
154        options,
155        &ManifestTypescriptOptions::default(),
156    )
157}
158
159pub fn manifest_export_to_typescript_with_options(
160    manifest: &Manifest,
161    options: &ManifestExportOptions,
162    typescript_options: &ManifestTypescriptOptions,
163) -> String {
164    export_to_typescript(&export_manifest(manifest, options), typescript_options)
165}
166
167pub fn write_manifest(path: &Path, manifest: &Manifest) -> Result<()> {
168    if let Some(parent) = path.parent() {
169        fs::create_dir_all(parent).map_err(|source| DevimgError::io(parent, source))?;
170    }
171    fs::write(path, manifest_to_json(manifest)).map_err(|source| DevimgError::io(path, source))
172}
173
174pub fn read_manifest(path: &Path) -> Result<Manifest> {
175    let raw = fs::read_to_string(path).map_err(|source| DevimgError::io(path, source))?;
176    serde_json::from_str(&raw)
177        .map_err(|source| DevimgError::config(path, format!("invalid manifest JSON: {source}")))
178}
179
180pub fn manifest_to_json(manifest: &Manifest) -> String {
181    let document = ManifestDocument {
182        version: manifest.version,
183        generated_at: &manifest.generated_at,
184        config_path: &manifest.config_path,
185        config_hash: &manifest.config_hash,
186        outputs: &manifest.outputs,
187        totals: ManifestTotals {
188            source_bytes: manifest.source_bytes_total(),
189            output_bytes: manifest.output_bytes_total(),
190        },
191    };
192    serde_json::to_string_pretty(&document).expect("manifest serialization cannot fail") + "\n"
193}
194
195#[derive(Serialize)]
196struct ManifestDocument<'a> {
197    version: u32,
198    generated_at: &'a str,
199    config_path: &'a str,
200    config_hash: &'a str,
201    outputs: &'a [ManifestOutput],
202    totals: ManifestTotals,
203}
204
205#[derive(Serialize)]
206struct ManifestTotals {
207    source_bytes: u64,
208    output_bytes: u64,
209}
210
211fn default_version() -> u32 {
212    1
213}
214
215fn unknown_generated_at() -> String {
216    "unknown".to_string()
217}
218
219fn unknown_fit() -> String {
220    "unknown".to_string()
221}
222
223fn generated_at() -> String {
224    let seconds = SystemTime::now()
225        .duration_since(UNIX_EPOCH)
226        .map(|duration| duration.as_secs())
227        .unwrap_or(0);
228    format!("unix:{seconds}")
229}
230
231fn manifest_variant_src(output_path: &str, options: &ManifestExportOptions) -> String {
232    let path = output_path.replace('\\', "/");
233    let stripped = options
234        .strip_prefix
235        .as_deref()
236        .and_then(|prefix| strip_path_prefix(&path, prefix))
237        .unwrap_or(path);
238    join_url_prefix(&options.url_prefix, &stripped)
239}
240
241fn strip_path_prefix(path: &str, prefix: &str) -> Option<String> {
242    let prefix = prefix.replace('\\', "/");
243    let prefix = prefix.trim_matches('/');
244    if prefix.is_empty() {
245        return Some(path.trim_start_matches('/').to_string());
246    }
247    if path == prefix {
248        return Some(String::new());
249    }
250    path.strip_prefix(&format!("{prefix}/"))
251        .map(ToString::to_string)
252}
253
254fn join_url_prefix(url_prefix: &str, path: &str) -> String {
255    let prefix = url_prefix.replace('\\', "/");
256    let prefix = prefix.trim_end_matches('/');
257    let path = path.trim_start_matches('/');
258    if prefix.is_empty() {
259        if url_prefix.starts_with('/') {
260            format!("/{path}")
261        } else {
262            path.to_string()
263        }
264    } else if path.is_empty() {
265        prefix.to_string()
266    } else {
267        format!("{prefix}/{path}")
268    }
269}
270
271fn export_to_typescript(
272    export: &ManifestExport,
273    typescript_options: &ManifestTypescriptOptions,
274) -> String {
275    let mut out = String::new();
276    out.push_str("// Generated by devimg. Do not edit by hand.\n");
277    out.push_str("export const DEVIMG_MANIFEST = {\n");
278    push_ts_number_field(&mut out, 2, "version", u64::from(export.version), true);
279    push_ts_string_field(&mut out, 2, "generated_at", &export.generated_at, true);
280    push_ts_string_field(&mut out, 2, "config_hash", &export.config_hash, true);
281    out.push_str("  sources: [\n");
282    for (source_index, source) in export.sources.iter().enumerate() {
283        out.push_str("    {\n");
284        push_ts_string_field(&mut out, 6, "source_path", &source.source_path, true);
285        push_ts_string_field(&mut out, 6, "source_hash", &source.source_hash, true);
286        push_ts_number_field(
287            &mut out,
288            6,
289            "source_width",
290            u64::from(source.source_width),
291            true,
292        );
293        push_ts_number_field(
294            &mut out,
295            6,
296            "source_height",
297            u64::from(source.source_height),
298            true,
299        );
300        push_ts_number_field(&mut out, 6, "source_bytes", source.source_bytes, true);
301        out.push_str("      variants: [\n");
302        for (variant_index, variant) in source.variants.iter().enumerate() {
303            out.push_str("        {\n");
304            push_ts_string_field(&mut out, 10, "src", &variant.src, true);
305            push_ts_string_field(&mut out, 10, "output_path", &variant.output_path, true);
306            push_ts_string_field(&mut out, 10, "preset", &variant.preset, true);
307            push_ts_string_field(&mut out, 10, "fit", &variant.fit, true);
308            push_ts_number_field(&mut out, 10, "width", u64::from(variant.width), true);
309            push_ts_number_field(&mut out, 10, "height", u64::from(variant.height), true);
310            push_ts_string_field(&mut out, 10, "format", &variant.format, true);
311            push_ts_number_field(&mut out, 10, "bytes", variant.bytes, true);
312            push_ts_string_field(&mut out, 10, "hash", &variant.hash, false);
313            out.push_str("        }");
314            if variant_index + 1 != source.variants.len() {
315                out.push(',');
316            }
317            out.push('\n');
318        }
319        out.push_str("      ]\n");
320        out.push_str("    }");
321        if source_index + 1 != export.sources.len() {
322            out.push(',');
323        }
324        out.push('\n');
325    }
326    out.push_str("  ]\n");
327    out.push_str("} as const\n");
328    if typescript_options.include_helpers {
329        out.push_str(
330            r#"
331export type DevimgManifest = typeof DEVIMG_MANIFEST
332export type DevimgSource = DevimgManifest["sources"][number]
333export type DevimgVariant = DevimgSource["variants"][number]
334
335export type DevimgVariantSelector = {
336  source: string
337  preset?: string
338  format?: string
339  width?: number
340  minWidth?: number
341}
342
343export function findDevimgSource(sourcePath: string): DevimgSource | undefined {
344  return DEVIMG_MANIFEST.sources.find((source) => source.source_path === sourcePath)
345}
346
347export function listDevimgVariants(sourcePath: string): readonly DevimgVariant[] {
348  return findDevimgSource(sourcePath)?.variants ?? []
349}
350
351export function findDevimgVariant(selector: DevimgVariantSelector): DevimgVariant | undefined {
352  let best: DevimgVariant | undefined
353  for (const variant of listDevimgVariants(selector.source)) {
354    if (selector.preset !== undefined && variant.preset !== selector.preset) {
355      continue
356    }
357    if (selector.format !== undefined && variant.format !== selector.format) {
358      continue
359    }
360    if (selector.width !== undefined && variant.width !== selector.width) {
361      continue
362    }
363    if (selector.minWidth !== undefined && variant.width < selector.minWidth) {
364      continue
365    }
366    if (best === undefined || variant.width < best.width) {
367      best = variant
368    }
369  }
370  if (best !== undefined) {
371    return best
372  }
373  if (selector.minWidth === undefined || selector.width !== undefined) {
374    return undefined
375  }
376  for (const variant of listDevimgVariants(selector.source)) {
377    if (selector.preset !== undefined && variant.preset !== selector.preset) {
378      continue
379    }
380    if (selector.format !== undefined && variant.format !== selector.format) {
381      continue
382    }
383    if (best === undefined || variant.width > best.width) {
384      best = variant
385    }
386  }
387  return best
388}
389"#,
390        );
391    }
392    out
393}
394
395fn push_ts_string_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
396    let value = serde_json::to_string(value).expect("string serialization cannot fail");
397    push_ts_field(out, indent, key, &value, comma);
398}
399
400fn push_ts_number_field(out: &mut String, indent: usize, key: &str, value: u64, comma: bool) {
401    push_ts_field(out, indent, key, &value.to_string(), comma);
402}
403
404fn push_ts_field(out: &mut String, indent: usize, key: &str, value: &str, comma: bool) {
405    let prefix = " ".repeat(indent);
406    let suffix = if comma { "," } else { "" };
407    let line = format!("{prefix}{key}: {value}{suffix}");
408    if key == "output_path" && line.len() > 100 {
409        out.push_str(&format!("{prefix}{key}:\n{prefix}  {value}{suffix}\n"));
410    } else {
411        out.push_str(&line);
412        out.push('\n');
413    }
414}
415
416#[cfg(test)]
417mod tests {
418    use super::{
419        export_manifest, manifest_export_to_json, manifest_export_to_typescript,
420        manifest_export_to_typescript_with_options, manifest_to_json, Manifest,
421        ManifestExportOptions, ManifestOutput, ManifestTypescriptOptions,
422    };
423
424    #[test]
425    fn manifest_json_round_trips_and_ignores_totals() {
426        let manifest = Manifest {
427            version: 1,
428            generated_at: "unix:1".to_string(),
429            config_path: "dev\"img.toml".to_string(),
430            config_hash: "blake3:abc".to_string(),
431            outputs: vec![ManifestOutput {
432                source_path: "assets/images/card.png".to_string(),
433                source_hash: "blake3:source".to_string(),
434                source_width: 800,
435                source_height: 450,
436                source_bytes: 123,
437                output_path: "public/images/card.webp".to_string(),
438                preset: "project-card".to_string(),
439                fit: "cover".to_string(),
440                width: 640,
441                height: 360,
442                format: "webp".to_string(),
443                bytes: 45,
444                hash: "blake3:output".to_string(),
445                operation_hash: "blake3:operation".to_string(),
446            }],
447        };
448
449        let json = manifest_to_json(&manifest);
450        assert!(json.contains("\"totals\""));
451        let parsed: Manifest = serde_json::from_str(&json).expect("manifest parses");
452
453        assert_eq!(parsed.config_path, "dev\"img.toml");
454        assert_eq!(parsed.outputs[0].source_path, "assets/images/card.png");
455        assert_eq!(parsed.outputs[0].fit, "cover");
456        assert_eq!(parsed.source_bytes_total(), 123);
457        assert_eq!(parsed.output_bytes_total(), 45);
458    }
459
460    #[test]
461    fn older_manifest_outputs_without_fit_still_parse() {
462        let raw = r#"{
463  "version": 1,
464  "generated_at": "unix:1",
465  "config_path": "devimg.toml",
466  "config_hash": "blake3:config",
467  "outputs": [
468    {
469      "source_path": "assets/images/card.png",
470      "source_hash": "blake3:source",
471      "source_width": 800,
472      "source_height": 450,
473      "source_bytes": 123,
474      "output_path": "public/images/card.webp",
475      "preset": "project-card",
476      "width": 640,
477      "height": 360,
478      "format": "webp",
479      "bytes": 45,
480      "hash": "blake3:output",
481      "operation_hash": "blake3:operation"
482    }
483  ]
484}"#;
485
486        let parsed: Manifest = serde_json::from_str(raw).expect("old manifest parses");
487
488        assert_eq!(parsed.outputs[0].fit, "unknown");
489    }
490
491    #[test]
492    fn older_manifest_exports_with_defaulted_fields() {
493        let raw = r#"{
494  "config_path": "devimg.toml",
495  "config_hash": "blake3:config",
496  "outputs": [
497    {
498      "source_path": "assets/images/card.png",
499      "source_hash": "blake3:source",
500      "source_width": 800,
501      "source_height": 450,
502      "source_bytes": 123,
503      "output_path": "public/images/card.webp",
504      "preset": "project-card",
505      "width": 640,
506      "height": 360,
507      "format": "webp",
508      "bytes": 45,
509      "hash": "blake3:output",
510      "operation_hash": "blake3:operation"
511    }
512  ]
513}"#;
514        let parsed: Manifest = serde_json::from_str(raw).expect("older manifest parses");
515        let options = ManifestExportOptions {
516            strip_prefix: Some("public".to_string()),
517            url_prefix: "/".to_string(),
518        };
519
520        let exported = export_manifest(&parsed, &options);
521        let json = manifest_export_to_json(&parsed, &options);
522
523        assert_eq!(exported.version, 1);
524        assert_eq!(exported.generated_at, "unknown");
525        assert_eq!(exported.sources[0].variants[0].fit, "unknown");
526        assert_eq!(exported.sources[0].variants[0].src, "/images/card.webp");
527        assert!(json.contains("\"generated_at\": \"unknown\""));
528        assert!(json.contains("\"fit\": \"unknown\""));
529    }
530
531    #[test]
532    fn manifest_export_groups_sources_and_derives_urls() {
533        let manifest = sample_manifest();
534        let options = ManifestExportOptions {
535            strip_prefix: Some("public".to_string()),
536            url_prefix: "/".to_string(),
537        };
538
539        let exported = export_manifest(&manifest, &options);
540
541        assert_eq!(exported.sources.len(), 1);
542        assert_eq!(exported.sources[0].source_path, "assets/images/card.png");
543        assert_eq!(exported.sources[0].variants.len(), 2);
544        assert_eq!(exported.sources[0].variants[0].preset, "project-card");
545        assert_eq!(exported.sources[0].variants[0].fit, "cover");
546        assert_eq!(
547            exported.sources[0].variants[0].src,
548            "/images/generated/card.project-card.640.webp"
549        );
550    }
551
552    #[test]
553    fn manifest_export_renderers_are_app_consumable() {
554        let manifest = sample_manifest();
555        let options = ManifestExportOptions {
556            strip_prefix: Some("public".to_string()),
557            url_prefix: "/assets".to_string(),
558        };
559
560        let json = manifest_export_to_json(&manifest, &options);
561        let typescript = manifest_export_to_typescript(&manifest, &options);
562
563        assert!(json.contains("\"sources\""));
564        assert!(json.contains("\"src\": \"/assets/images/generated/card.project-card.640.webp\""));
565        assert!(typescript.starts_with("// Generated by devimg."));
566        assert!(typescript.contains("export const DEVIMG_MANIFEST = {"));
567        assert!(typescript.contains("src: \"/assets/images/generated/card.project-card.640.webp\""));
568        assert!(typescript.ends_with(" as const\n"));
569    }
570
571    #[test]
572    fn typescript_export_can_include_lookup_helpers() {
573        let manifest = sample_manifest();
574        let options = ManifestExportOptions {
575            strip_prefix: Some("public".to_string()),
576            url_prefix: "/".to_string(),
577        };
578
579        let default_typescript = manifest_export_to_typescript(&manifest, &options);
580        let helper_typescript = manifest_export_to_typescript_with_options(
581            &manifest,
582            &options,
583            &ManifestTypescriptOptions {
584                include_helpers: true,
585            },
586        );
587
588        assert!(!default_typescript.contains("findDevimgVariant"));
589        assert!(helper_typescript.contains("export type DevimgVariantSelector = {"));
590        assert!(helper_typescript.contains("export function findDevimgSource"));
591        assert!(helper_typescript.contains("export function listDevimgVariants"));
592        assert!(helper_typescript.contains("export function findDevimgVariant"));
593        assert!(helper_typescript.contains("variant.width < selector.minWidth"));
594    }
595
596    fn sample_manifest() -> Manifest {
597        Manifest {
598            version: 1,
599            generated_at: "unix:1".to_string(),
600            config_path: "devimg.toml".to_string(),
601            config_hash: "blake3:config".to_string(),
602            outputs: vec![
603                ManifestOutput {
604                    source_path: "assets/images/card.png".to_string(),
605                    source_hash: "blake3:source".to_string(),
606                    source_width: 800,
607                    source_height: 450,
608                    source_bytes: 123,
609                    output_path: "public/images/generated/card.project-card.640.webp".to_string(),
610                    preset: "project-card".to_string(),
611                    fit: "cover".to_string(),
612                    width: 640,
613                    height: 360,
614                    format: "webp".to_string(),
615                    bytes: 45,
616                    hash: "blake3:output-webp".to_string(),
617                    operation_hash: "blake3:operation-webp".to_string(),
618                },
619                ManifestOutput {
620                    source_path: "assets/images/card.png".to_string(),
621                    source_hash: "blake3:source".to_string(),
622                    source_width: 800,
623                    source_height: 450,
624                    source_bytes: 123,
625                    output_path: "public/images/generated/card.project-card.640.jpeg".to_string(),
626                    preset: "project-card".to_string(),
627                    fit: "cover".to_string(),
628                    width: 640,
629                    height: 360,
630                    format: "jpeg".to_string(),
631                    bytes: 67,
632                    hash: "blake3:output-jpeg".to_string(),
633                    operation_hash: "blake3:operation-jpeg".to_string(),
634                },
635            ],
636        }
637    }
638}