alpha2-model 0.10.0

Versioned project and timeline model for alpha2.
Documentation
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! The published JSON Schema of the project document.
//!
//! The schema describes shape only: JSON types, required fields, tags and unknown-field
//! rejection. Meaning (ranges, limits, references, keyframe order, transition coverage) is
//! decided by [`crate::Project::validate`]. A document the schema rejects is never valid; one
//! it accepts may still be invalid.
//!
//! The parser also refuses what a schema cannot express: ill-formed Unicode, duplicated struct
//! fields, integers with a fraction or exponent, and frame rates past one frame per tick.

use crate::project::ProjectWire;
use serde_json::{Value, json};

/// The JSON Schema (draft 2020-12) of the current project document.
#[must_use]
pub fn project_json_schema() -> Value {
    let mut schema = schemars::generate::SchemaSettings::draft2020_12()
        .for_deserialize()
        .into_generator()
        .into_root_schema_for::<ProjectWire>();
    schema.insert(
        "$id".to_owned(),
        Value::String(PROJECT_SCHEMA_ID.to_owned()),
    );
    schema.insert(
        "title".to_owned(),
        Value::String(format!(
            "alpha2 project document, schema version {}",
            crate::CURRENT_SCHEMA_VERSION
        )),
    );
    let mut value = schema.to_value();
    finish_json_schema(&mut value);
    value
}

/// The project schema without its prose (`description`, `title`, `examples`, `$schema`), as
/// the engine embeds it to walk documents for diagnostics.
#[must_use]
pub fn project_shape_json() -> Value {
    let mut value = project_json_schema();
    strip_json_schema_prose(&mut value);
    value
}

/// Removes `description`, `title`, `examples`, `$schema` and `$comment` from every schema in
/// `schema`; data keywords and property names stay.
pub fn strip_json_schema_prose(schema: &mut Value) {
    let Value::Object(map) = schema else {
        return;
    };
    for keyword in ["description", "title", "examples", "$schema", "$comment"] {
        map.remove(keyword);
    }
    for (keyword, child) in map.iter_mut() {
        match keyword.as_str() {
            "properties" | "$defs" => {
                if let Value::Object(named) = child {
                    named.values_mut().for_each(strip_json_schema_prose);
                }
            }
            "enum" | "const" | "default" => {}
            _ => strip_nested(child),
        }
    }
}

fn strip_nested(value: &mut Value) {
    match value {
        Value::Object(_) => strip_json_schema_prose(value),
        Value::Array(items) => items.iter_mut().for_each(strip_nested),
        _ => {}
    }
}

/// Where the project schema is published.
pub const PROJECT_SCHEMA_ID: &str = "https://alpha2.sh/schema/project.v1.json";

/// Post-processes a schemars schema the way the project schema is: every `uint32` bounded and
/// every default spelled as the engine writes it. Used by schemas that embed model types.
pub fn finish_json_schema(value: &mut Value) {
    bound_unsigned_integers(value);
    shortest_defaults(value);
}

/// Removes the `data` variant from an `Animated` schema whose value type takes no data.
pub(crate) fn drop_data_mode(schema: &mut schemars::Schema) {
    drop_variant(schema, "mode", "data");
}

pub(crate) fn drop_variant(schema: &mut schemars::Schema, tag: &str, name: &str) {
    let named = |variant: &Value| {
        variant
            .get("properties")
            .and_then(|properties| properties.get(tag))
            .and_then(|tag| tag.get("const"))
            .and_then(Value::as_str)
            == Some(name)
    };
    for union in ["oneOf", "anyOf"] {
        if let Some(variants) = schema.get_mut(union).and_then(Value::as_array_mut) {
            variants.retain(|variant| !named(variant));
        }
    }
}

pub(crate) fn bound_split_channels(schema: &mut schemars::Schema, least: usize, most: usize) {
    for union in ["oneOf", "anyOf"] {
        let Some(variants) = schema.get_mut(union).and_then(Value::as_array_mut) else {
            continue;
        };
        for variant in variants {
            let split = variant
                .pointer("/properties/mode/const")
                .and_then(Value::as_str)
                == Some("split");
            if let Some(channels) = variant
                .pointer_mut("/properties/channels")
                .filter(|_| split)
                .and_then(Value::as_object_mut)
            {
                channels.insert("minItems".to_owned(), least.into());
                channels.insert("maxItems".to_owned(), most.into());
            }
        }
    }
}

pub(crate) fn drop_word(schema: &mut schemars::Schema, word: &str) {
    let named = |variant: &Value| variant.get("const").and_then(Value::as_str) == Some(word);
    for union in ["oneOf", "anyOf"] {
        if let Some(variants) = schema.get_mut(union).and_then(Value::as_array_mut) {
            variants.retain(|variant| !named(variant));
        }
    }
    if let Some(words) = schema.get_mut("enum").and_then(Value::as_array_mut) {
        words.retain(|other| other.as_str() != Some(word));
    }
}

/// What a CSS hex color string looks like.
const HEX_COLOR_PATTERN: &str = "^#([0-9a-fA-F]{3}|[0-9a-fA-F]{4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$";

/// `Rgba` as written: its object, or a CSS hex string.
pub(crate) fn with_hex_form(schema: &mut schemars::Schema) {
    let object = std::mem::take(schema);
    let mut object = object.to_value();
    let description = object
        .as_object_mut()
        .and_then(|map| map.remove("description"));
    let mut both = json!({
        "anyOf": [object, { "type": "string", "pattern": HEX_COLOR_PATTERN }],
    });
    if let Some(description) = description {
        both["description"] = description;
    }
    *schema = schemars::Schema::try_from(both).expect("a schema object");
}

/// `Paint` as written: tagged, or a color painting solid.
pub(crate) fn with_color_form(schema: &mut schemars::Schema) {
    let color = json!({ "$ref": "#/$defs/Rgba" });
    let union = if schema.get("oneOf").is_some() {
        "oneOf"
    } else {
        "anyOf"
    };
    let variants = schema
        .get_mut(union)
        .and_then(Value::as_array_mut)
        .expect("a paint is a union of its kinds");
    variants.push(color);
}

/// Writes each `default` the way the engine writes the document ([`shortest_floats`]), since
/// schemars widens a 32-bit default to 64 bits.
fn shortest_defaults(node: &mut Value) {
    match node {
        Value::Object(map) => {
            for (key, value) in map.iter_mut() {
                if key == "default" {
                    shortest_floats(value);
                } else {
                    shortest_defaults(value);
                }
            }
        }
        Value::Array(items) => items.iter_mut().for_each(shortest_defaults),
        _ => {}
    }
}

/// Gives every `uint32` the upper bound the parser enforces. schemars states only the lower
/// bound, plus a `format` that validators do not check.
fn bound_unsigned_integers(node: &mut Value) {
    match node {
        Value::Object(map) => {
            if map.get("format").and_then(Value::as_str) == Some("uint32") {
                map.entry("maximum").or_insert_with(|| u32::MAX.into());
            }
            map.values_mut().for_each(bound_unsigned_integers);
        }
        Value::Array(items) => items.iter_mut().for_each(bound_unsigned_integers),
        _ => {}
    }
}

/// Every named easing ([`crate::easing_presets::named`]) by its name, as the JSON object the
/// TypeScript and Python constants are generated from.
///
/// # Panics
/// Never; an easing is written as JSON and read back.
#[must_use]
pub fn easing_presets_json() -> Value {
    let presets: serde_json::Map<String, Value> = crate::easing_presets::easing_names()
        .into_iter()
        .filter_map(|name| {
            let easing = crate::easing_presets::named(&name)?;
            let text = serde_json::to_string(&easing).expect("an easing is JSON");
            Some((name, serde_json::from_str(&text).expect("JSON reads back")))
        })
        .collect();
    Value::Object(presets)
}

/// The portable document limits, as the JSON object the TypeScript constants are generated
/// from. 32-bit float limits are written as their shortest decimal.
#[must_use]
#[allow(clippy::too_many_lines)]
pub fn project_limits_json() -> Value {
    let limits = [
        (
            "CURRENT_SCHEMA_VERSION",
            json!(crate::CURRENT_SCHEMA_VERSION),
        ),
        (
            "MAX_PROJECT_JSON_BYTES",
            json!(crate::MAX_PROJECT_JSON_BYTES),
        ),
        ("MAX_CANVAS_DIMENSION", json!(crate::MAX_CANVAS_DIMENSION)),
        ("MAX_CANVAS_PIXELS", json!(crate::MAX_CANVAS_PIXELS)),
        ("MIN_SAMPLE_RATE", json!(crate::SAMPLE_RATE_RANGE.start())),
        ("MAX_SAMPLE_RATE", json!(crate::SAMPLE_RATE_RANGE.end())),
        (
            "MIN_HDR_PEAK_NITS",
            json!(crate::HDR_PEAK_NITS_RANGE.start()),
        ),
        ("MAX_HDR_PEAK_NITS", json!(crate::HDR_PEAK_NITS_RANGE.end())),
        ("MIN_SHUTTER_SAMPLES", json!(crate::MIN_SHUTTER_SAMPLES)),
        ("MAX_SHUTTER_SAMPLES", json!(crate::MAX_SHUTTER_SAMPLES)),
        (
            "MAX_SHUTTER_ANGLE_DEGREES",
            json!(crate::MAX_SHUTTER_ANGLE_DEGREES),
        ),
        (
            "MAX_SHUTTER_PHASE_DEGREES",
            json!(crate::MAX_SHUTTER_PHASE_DEGREES),
        ),
        ("MAX_TRACKS", json!(crate::MAX_TRACKS)),
        ("MAX_CLIPS", json!(crate::MAX_CLIPS)),
        ("MAX_CLIPS_PER_TRACK", json!(crate::MAX_CLIPS_PER_TRACK)),
        ("MAX_COMPOSITIONS", json!(crate::MAX_COMPOSITIONS)),
        ("MAX_EFFECT_RESOURCES", json!(crate::MAX_EFFECT_RESOURCES)),
        ("MAX_KEYFRAMES", json!(crate::MAX_KEYFRAMES)),
        (
            "MAX_MOTION_PATH_VERTICES",
            json!(crate::MAX_MOTION_PATH_VERTICES),
        ),
        ("MAX_EASING_STEPS", json!(crate::MAX_EASING_STEPS)),
        ("MAX_EASING_POINTS", json!(crate::MAX_EASING_POINTS)),
        ("MAX_COMPOSITION_NODES", json!(crate::MAX_COMPOSITION_NODES)),
        ("MAX_GROUP_INPUTS", json!(crate::MAX_GROUP_INPUTS)),
        ("MAX_EFFECT_INPUTS", json!(crate::MAX_EFFECT_INPUTS)),
        (
            "MAX_COMPOSITION_CONTROLS",
            json!(crate::MAX_COMPOSITION_CONTROLS),
        ),
        ("MAX_COMPOSITION_DEPTH", json!(crate::MAX_COMPOSITION_DEPTH)),
        ("MAX_INLINED_NODES", json!(crate::MAX_INLINED_NODES)),
        (
            "MAX_FRAME_INLINED_NODES",
            json!(crate::MAX_FRAME_INLINED_NODES),
        ),
        ("MAX_MERGE_LAYERS", json!(crate::MAX_MERGE_LAYERS)),
        ("MAX_CLIP_MASKS", json!(crate::MAX_CLIP_MASKS)),
        ("MAX_GRADIENT_STOPS", json!(crate::MAX_GRADIENT_STOPS)),
        ("MAX_SHAPE_ITEMS", json!(crate::MAX_SHAPE_ITEMS)),
        ("MAX_SHAPE_DEPTH", json!(crate::MAX_SHAPE_DEPTH)),
        ("MAX_PATH_VERTICES", json!(crate::MAX_PATH_VERTICES)),
        ("MAX_PATH_SUBPATHS", json!(crate::MAX_PATH_SUBPATHS)),
        ("MAX_DASH_ENTRIES", json!(crate::MAX_DASH_ENTRIES)),
        ("MAX_LAYOUT_NODES", json!(crate::MAX_LAYOUT_NODES)),
        ("MAX_LAYOUT_DEPTH", json!(crate::MAX_LAYOUT_DEPTH)),
        ("MAX_LAYOUT_TEXTS", json!(crate::MAX_LAYOUT_TEXTS)),
        ("MAX_LAYOUT_ISOLATED", json!(crate::MAX_LAYOUT_ISOLATED)),
        ("MAX_LAYOUT_FONT_SIZE", json!(crate::MAX_LAYOUT_FONT_SIZE)),
        ("MAX_GRID_TRACKS", json!(crate::MAX_GRID_TRACKS)),
        ("MAX_LAYOUT_FRACTION", json!(crate::MAX_LAYOUT_FRACTION)),
        ("MAX_LAYOUT_PX", json!(crate::MAX_LAYOUT_PX)),
        ("MAX_LAYOUT_PERCENT", json!(crate::MAX_LAYOUT_PERCENT)),
        ("MAX_FLEX_FACTOR", json!(crate::MAX_FLEX_FACTOR)),
        ("MIN_ASPECT_RATIO", json!(crate::ASPECT_RATIO_RANGE.start())),
        ("MAX_ASPECT_RATIO", json!(crate::ASPECT_RATIO_RANGE.end())),
        ("MAX_TEXT_POSITION", json!(crate::MAX_TEXT_POSITION)),
        ("MAX_ANIMATOR_OFFSET", json!(crate::MAX_ANIMATOR_OFFSET)),
        ("MAX_REVEAL_FEATHER", json!(crate::MAX_REVEAL_FEATHER)),
        ("MIN_POLYSTAR_POINTS", json!(crate::MIN_POLYSTAR_POINTS)),
        ("MAX_POLYSTAR_POINTS", json!(crate::MAX_POLYSTAR_POINTS)),
        (
            "MAX_TEXT_CONTENT_BYTES",
            json!(crate::MAX_TEXT_CONTENT_BYTES),
        ),
        (
            "MAX_CAPTION_FILE_BYTES",
            json!(crate::MAX_CAPTION_FILE_BYTES),
        ),
        ("MAX_CAPTION_FILE_CUES", json!(crate::MAX_CAPTION_FILE_CUES)),
        ("MAX_DERIVED_CUES", json!(crate::MAX_DERIVED_CUES)),
        ("MAX_FONT_FAMILY_BYTES", json!(crate::MAX_FONT_FAMILY_BYTES)),
        (
            "MAX_TRANSITIONS_PER_TRACK",
            json!(crate::MAX_TRANSITIONS_PER_TRACK),
        ),
        ("MAX_GAIN", json!(crate::MAX_GAIN)),
        ("MAX_AUDIO_EFFECTS", json!(crate::MAX_AUDIO_EFFECTS)),
        ("MAX_AUDIO_DELAY_MS", json!(crate::MAX_AUDIO_DELAY_MS)),
        ("REVERB_DELAY_MS", json!(crate::REVERB_DELAY_MS)),
        (
            "AUDIO_EFFECT_STATE_MARGIN_MS",
            json!(crate::AUDIO_EFFECT_STATE_MARGIN_MS),
        ),
        ("MAX_EQ_GAIN_DB", json!(crate::MAX_EQ_GAIN_DB)),
        ("MIN_EQ_Q", json!(crate::EQ_Q_RANGE.start())),
        ("MAX_EQ_Q", json!(crate::EQ_Q_RANGE.end())),
        (
            "MIN_EQ_FREQUENCY_HZ",
            json!(crate::EQ_FREQUENCY_RANGE_HZ.start()),
        ),
        (
            "MAX_EQ_FREQUENCY_HZ",
            json!(crate::EQ_FREQUENCY_RANGE_HZ.end()),
        ),
        ("MAX_COMPRESSOR_RATIO", json!(crate::MAX_COMPRESSOR_RATIO)),
        ("MAX_CHAIN_EFFECTS", json!(crate::MAX_CHAIN_EFFECTS)),
        ("MAX_AUDIO_BUSES", json!(crate::MAX_AUDIO_BUSES)),
        ("MAX_AUDIO_SENDS", json!(crate::MAX_AUDIO_SENDS)),
        ("MAX_EQ_BANDS", json!(crate::MAX_EQ_BANDS)),
        ("MIN_LEVEL_DB", json!(crate::MIN_LEVEL_DB)),
        ("MAX_LOOKAHEAD_MS", json!(crate::MAX_LOOKAHEAD_MS)),
        ("MAX_KNEE_DB", json!(crate::MAX_KNEE_DB)),
        ("MAX_MAKEUP_DB", json!(crate::MAX_MAKEUP_DB)),
        ("MAX_EXPANDER_RANGE_DB", json!(crate::MAX_EXPANDER_RANGE_DB)),
        ("MAX_HOLD_MS", json!(crate::MAX_HOLD_MS)),
        ("MAX_DELAY_MS", json!(crate::MAX_DELAY_MS)),
        ("MAX_DELAY_FEEDBACK", json!(crate::MAX_DELAY_FEEDBACK)),
        ("MAX_MATRIX_GAIN", json!(crate::MAX_MATRIX_GAIN)),
        ("MAX_ENVELOPE_MS", json!(crate::MAX_ENVELOPE_MS)),
        ("MAX_CAPTION_FONT_SIZE", json!(crate::MAX_CAPTION_FONT_SIZE)),
        (
            "MAX_TEXT_GENERATOR_FONT_SIZE",
            json!(crate::MAX_TEXT_GENERATOR_FONT_SIZE),
        ),
        ("MIN_LINE_HEIGHT", json!(crate::LINE_HEIGHT_RANGE.start())),
        ("MAX_LINE_HEIGHT", json!(crate::LINE_HEIGHT_RANGE.end())),
        (
            "MIN_LETTER_SPACING",
            json!(crate::LETTER_SPACING_RANGE.start()),
        ),
        (
            "MAX_LETTER_SPACING",
            json!(crate::LETTER_SPACING_RANGE.end()),
        ),
        ("MIN_FONT_WEIGHT", json!(crate::FONT_WEIGHT_RANGE.start())),
        ("MAX_FONT_WEIGHT", json!(crate::FONT_WEIGHT_RANGE.end())),
        ("MAX_TEXT_STROKES", json!(crate::MAX_TEXT_STROKES)),
        (
            "MAX_TEXT_STROKE_EXTENT",
            json!(crate::MAX_TEXT_STROKE_EXTENT),
        ),
        ("MAX_TEXT_SHADOWS", json!(crate::MAX_TEXT_SHADOWS)),
        (
            "MAX_TEXT_SHADOW_OFFSET",
            json!(crate::MAX_TEXT_SHADOW_OFFSET),
        ),
        ("MAX_TEXT_SHADOW_BLUR", json!(crate::MAX_TEXT_SHADOW_BLUR)),
        ("MAX_TEXT_RUNS", json!(crate::MAX_TEXT_RUNS)),
        (
            "MAX_TEXT_FONT_SELECTIONS",
            json!(crate::MAX_TEXT_FONT_SELECTIONS),
        ),
        ("MIN_FONT_SCALE", json!(crate::FONT_SCALE_RANGE.start())),
        ("MAX_FONT_SCALE", json!(crate::FONT_SCALE_RANGE.end())),
        ("MAX_CAPTION_STYLES", json!(crate::MAX_CAPTION_STYLES)),
        (
            "MAX_CAPTION_NAME_BYTES",
            json!(crate::MAX_CAPTION_NAME_BYTES),
        ),
        ("MAX_RUN_CLASSES", json!(crate::MAX_RUN_CLASSES)),
        ("MAX_CLASS_NAME_BYTES", json!(crate::MAX_CLASS_NAME_BYTES)),
        ("MAX_TEXT_ANIMATORS", json!(crate::MAX_TEXT_ANIMATORS)),
        ("MAX_RANGE_INDEX", json!(crate::MAX_RANGE_INDEX)),
        ("MIN_RANGE_PERCENT", json!(crate::RANGE_PERCENT.start())),
        ("MAX_RANGE_PERCENT", json!(crate::RANGE_PERCENT.end())),
        (
            "MAX_ANIMATOR_SCALE",
            json!(crate::ANIMATOR_SCALE_RANGE.end()),
        ),
        ("MAX_TEXT_PADDING", json!(crate::MAX_TEXT_PADDING)),
        ("MAX_TEXT_BORDER_WIDTH", json!(crate::MAX_TEXT_BORDER_WIDTH)),
        ("MAX_TEXT_DASH_ENTRY", json!(crate::MAX_TEXT_DASH_ENTRY)),
        ("MAX_TEXT_DASH_OFFSET", json!(crate::MAX_TEXT_DASH_OFFSET)),
        (
            "MAX_HIGHLIGHT_TRANSITION",
            json!(crate::MAX_HIGHLIGHT_TRANSITION.ticks()),
        ),
        ("MAX_SEQUENCE_FRAMES", json!(crate::MAX_SEQUENCE_FRAMES)),
        ("MAX_CHANNEL_GAIN", json!(crate::MAX_CHANNEL_GAIN)),
        ("MAX_PITCH_CENTS", json!(crate::MAX_PITCH_CENTS)),
        (
            "MAX_AUDIO_CHANNELS",
            json!(alpha2_media::MAX_AUDIO_CHANNELS),
        ),
        (
            "MAX_PROVIDER_DOCUMENT_BYTES",
            json!(crate::MAX_PROVIDER_DOCUMENT_BYTES),
        ),
        (
            "MAX_LOTTIE_DOCUMENT_BYTES",
            json!(crate::MAX_LOTTIE_DOCUMENT_BYTES),
        ),
        (
            "MAX_SVG_DOCUMENT_BYTES",
            json!(crate::MAX_SVG_DOCUMENT_BYTES),
        ),
        ("MAX_LATEX_BYTES", json!(crate::MAX_LATEX_BYTES)),
        ("MAX_LATEX_FONT_SIZE", json!(crate::MAX_LATEX_FONT_SIZE)),
        (
            "MAX_PDF_DOCUMENT_BYTES",
            json!(crate::MAX_PDF_DOCUMENT_BYTES),
        ),
        ("MAX_PDF_PAGES", json!(crate::MAX_PDF_PAGES)),
        ("TICKS_PER_SECOND", json!(alpha2_time::TICKS_PER_SECOND)),
        ("MAX_DATA_SETS", json!(crate::MAX_DATA_SETS)),
        ("MAX_DATA_CHANNELS", json!(crate::MAX_DATA_CHANNELS)),
        ("MAX_DATA_VALUES", json!(crate::MAX_DATA_VALUES)),
        ("MAX_DATA_WORDS", json!(crate::MAX_DATA_WORDS)),
        ("MAX_DATA_INTERVALS", json!(crate::MAX_DATA_INTERVALS)),
        ("MAX_DATA_LABEL_BYTES", json!(crate::MAX_DATA_LABEL_BYTES)),
        ("MAX_DATA_ID_BYTES", json!(crate::MAX_DATA_ID_BYTES)),
        ("MAX_SUPPLIED_FILES", json!(crate::MAX_SUPPLIED_FILES)),
        (
            "MAX_SUPPLIED_NAME_BYTES",
            json!(crate::MAX_SUPPLIED_NAME_BYTES),
        ),
        ("MAX_DATA_COORDINATE", json!(crate::MAX_DATA_COORDINATE)),
        ("MAX_DATA_SCALAR", json!(crate::MAX_DATA_SCALAR)),
        (
            "MAX_DATA_ROTATION_DEGREES",
            json!(crate::MAX_DATA_ROTATION_DEGREES),
        ),
        ("MAX_DATA_SCALE", json!(crate::MAX_DATA_SCALE)),
        ("MAX_FOLLOW_DEPTH", json!(crate::MAX_FOLLOW_DEPTH)),
        ("MAX_LOOP_PASSES", json!(crate::MAX_LOOP_PASSES)),
    ];
    let mut value = Value::Object(
        limits
            .into_iter()
            .map(|(name, limit)| (name.to_owned(), limit))
            .collect(),
    );
    shortest_floats(&mut value);
    value
}

/// Writes every number that is exactly a 32-bit float as that float's shortest decimal
/// (`0.05`, not `0.05000000074505806`), as the engine writes the model's 32-bit values.
/// Values that are not exactly a 32-bit float are unchanged.
#[allow(clippy::cast_possible_truncation)]
fn shortest_floats(node: &mut Value) {
    match node {
        Value::Number(number) if number.is_f64() => {
            if let Some(wide) = number.as_f64()
                && f64::from(wide as f32).to_bits() == wide.to_bits()
                && let Ok(short) = (wide as f32).to_string().parse::<f64>()
                && let Some(short) = serde_json::Number::from_f64(short)
            {
                *number = short;
            }
        }
        Value::Array(items) => items.iter_mut().for_each(shortest_floats),
        Value::Object(map) => map.values_mut().for_each(shortest_floats),
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use serde_json::Value;

    /// Every float in `node` spelled with more digits than its 32-bit value needs, which the
    /// engine would never write.
    #[allow(clippy::cast_possible_truncation)]
    fn widened(node: &Value, path: &str, found: &mut Vec<String>) {
        match node {
            Value::Number(number) => {
                if let Some(wide) = number.as_f64().filter(|_| number.is_f64())
                    && f64::from(wide as f32).to_bits() == wide.to_bits()
                    && number.to_string().len() > (wide as f32).to_string().len() + 2
                {
                    found.push(format!("{path} = {number}"));
                }
            }
            Value::Array(items) => {
                for (index, item) in items.iter().enumerate() {
                    widened(item, &format!("{path}[{index}]"), found);
                }
            }
            Value::Object(map) => {
                for (key, value) in map {
                    widened(value, &format!("{path}.{key}"), found);
                }
            }
            _ => {}
        }
    }

    #[test]
    fn floats_are_published_as_the_engine_writes_them() {
        let mut found = Vec::new();
        widened(&super::project_json_schema(), "schema", &mut found);
        widened(&super::project_limits_json(), "limits", &mut found);
        assert!(found.is_empty(), "{found:#?}");
        let limits = super::project_limits_json();
        assert_eq!(limits["MIN_EQ_Q"].to_string(), "0.05");
        let schema = super::project_json_schema().to_string();
        assert!(schema.contains("\"default\":0.05"), "caption font size");
    }
}