@mark1russell7/layout-contract 0.3.7 → 0.3.9

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/build/index.js CHANGED
@@ -638,7 +638,7 @@ function toLayoutRecord(input, run) {
638
638
  ...onlyRect ? {} : { shapes }
639
639
  };
640
640
  }
641
- const isFields = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
641
+ const isFields$1 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
642
642
  const STAGES = [
643
643
  "pack",
644
644
  "route",
@@ -674,7 +674,7 @@ const ENV_STRINGS = [
674
674
  const ENV_OPTIONAL_STRINGS = ["mode", "context"];
675
675
  /** This function adds a problem for each value of a map that is not a number. */
676
676
  function numberMap(out, v, name) {
677
- if (!isFields(v)) {
677
+ if (!isFields$1(v)) {
678
678
  out.push(`${name} is not an object`);
679
679
  return;
680
680
  }
@@ -682,7 +682,7 @@ function numberMap(out, v, name) {
682
682
  }
683
683
  /** This function gives the problems of the field `env` of a record. */
684
684
  function envProblems(env) {
685
- if (!isFields(env)) return ["env is not an object"];
685
+ if (!isFields$1(env)) return ["env is not an object"];
686
686
  const out = [];
687
687
  for (const key of ENV_STRINGS) if (typeof env[key] !== "string") out.push(`env.${key} is not a string`);
688
688
  if (typeof env["cpus"] !== "number") out.push("env.cpus is not a number");
@@ -695,7 +695,7 @@ function envProblems(env) {
695
695
  * A record without `skipped` has a boolean. The check accepts fields that the format does not know.
696
696
  */
697
697
  function checkLayoutRecord(value) {
698
- if (!isFields(value)) return ["the record is not an object"];
698
+ if (!isFields$1(value)) return ["the record is not an object"];
699
699
  const out = [];
700
700
  const v = value;
701
701
  if (v["schema"] !== "layout-record/1") out.push("schema is not layout-record/1");
@@ -703,7 +703,7 @@ function checkLayoutRecord(value) {
703
703
  for (const key of RECORD_STRINGS) if (typeof v[key] !== "string") out.push(`${key} is not a string`);
704
704
  for (const key of RECORD_NUMBERS) if (typeof v[key] !== "number") out.push(`${key} is not a number`);
705
705
  for (const key of RECORD_OPTIONAL_STRINGS) if (v[key] !== void 0 && typeof v[key] !== "string") out.push(`${key} is not a string`);
706
- if (!isFields(v["options"])) out.push("options is not an object");
706
+ if (!isFields$1(v["options"])) out.push("options is not an object");
707
707
  numberMap(out, v["measures"], "measures");
708
708
  numberMap(out, v["hard"], "hard");
709
709
  if (v["tolerance"] !== void 0) numberMap(out, v["tolerance"], "tolerance");
@@ -3022,6 +3022,19 @@ function* gridParams(params, levels, i = 0, values = {}) {
3022
3022
  }
3023
3023
  const optionIds = (choices) => new Map([...choices].map(([k, o]) => [k, o?.id ?? null]));
3024
3024
  const keeps = (space, choices) => (space.constraints ?? []).every((c) => holds(c, optionIds(choices)));
3025
+ /**
3026
+ * This function gives the constraints of a space for each stage: a constraint goes to the last stage that it names.
3027
+ * The last list holds each constraint that names a stage outside the space, so a walk examines it at the end.
3028
+ */
3029
+ function constraintsByStage(space) {
3030
+ const place = new Map(space.stages.map((s, i) => [s.name, i]));
3031
+ const lists = Array.from({ length: space.stages.length + 1 }, () => []);
3032
+ for (const c of space.constraints ?? []) {
3033
+ const named = [c.if.stage, "not" in c.then ? c.then.not.stage : c.then.stage];
3034
+ lists[Math.max(...named.map((name) => place.get(name) ?? space.stages.length))].push(c);
3035
+ }
3036
+ return lists;
3037
+ }
3025
3038
  /** This function gives the count of the member lists of a meta option without a pool from `base` base configs, or `null` above `limit`. */
3026
3039
  function memberLists(base, rule, limit) {
3027
3040
  let sum = 0n;
@@ -3075,9 +3088,11 @@ function combos(space, levels, meta, limit) {
3075
3088
  };
3076
3089
  const out = [];
3077
3090
  const stages = space.stages;
3091
+ const checks = constraintsByStage(space);
3092
+ const ids = /* @__PURE__ */ new Map();
3078
3093
  const walk = (i, choices, weight) => {
3079
3094
  if (i === stages.length) {
3080
- if (keeps(space, choices)) out.push({
3095
+ if (checks[i].every((c) => holds(c, ids))) out.push({
3081
3096
  choices: new Map(choices),
3082
3097
  base: true,
3083
3098
  weight
@@ -3089,9 +3104,11 @@ function combos(space, levels, meta, limit) {
3089
3104
  if (s.optional) list.push(null);
3090
3105
  for (const o of list) {
3091
3106
  choices.set(s.name, o);
3092
- walk(i + 1, choices, o === null ? weight : weight * countOf(o));
3107
+ ids.set(s.name, o?.id ?? null);
3108
+ if (checks[i].every((c) => holds(c, ids))) walk(i + 1, choices, o === null ? weight : weight * countOf(o));
3093
3109
  }
3094
3110
  choices.delete(s.name);
3111
+ ids.delete(s.name);
3095
3112
  };
3096
3113
  walk(0, /* @__PURE__ */ new Map(), 1n);
3097
3114
  if (!meta) return out;
@@ -3458,6 +3475,928 @@ function productSpace(a, b, name) {
3458
3475
  parts: [a, b]
3459
3476
  };
3460
3477
  }
3478
+ // src/strategy-options.ts
3479
+ /** The number of values of a sweep on a range when the call and the declaration give no number. */
3480
+ const SWEEP_COUNT = 5;
3481
+ /** This function gives the declarations of a strategy as a record. A strategy without a schema gives an empty record. */
3482
+ function schemaOf(strategy) {
3483
+ return strategy.schema ?? {};
3484
+ }
3485
+ /** This function gives the declared options of a strategy, in the order of its schema, with the effective default of each one. */
3486
+ function listOptions(strategy) {
3487
+ const defaults = optionDefaults(strategy);
3488
+ return Object.entries(schemaOf(strategy)).map(([key, declaration]) => ({
3489
+ key,
3490
+ declaration,
3491
+ value: defaults[key]
3492
+ }));
3493
+ }
3494
+ /**
3495
+ * This function gives the effective default of each declared option: the value of `defaults`, else the `default` of the declaration.
3496
+ * An option without either value stays out. The strategy gives the same output with this object as with no options.
3497
+ */
3498
+ function optionDefaults(strategy) {
3499
+ const out = {};
3500
+ const defaults = strategy.defaults;
3501
+ for (const [key, declaration] of Object.entries(schemaOf(strategy))) if (key in defaults) out[key] = defaults[key];
3502
+ else if (declaration.default !== void 0) out[key] = declaration.default;
3503
+ for (const key of Object.keys(defaults)) if (!(key in out)) out[key] = defaults[key];
3504
+ return out;
3505
+ }
3506
+ /** This function gives `true` if the number is one of the special values of the declaration. */
3507
+ const isSpecial = (d, v) => (d.special ?? []).some((s) => Object.is(s, v) || s === v);
3508
+ /** This function gives the problem of one value against its declaration, or `undefined` when the value fits. */
3509
+ function optionIssue(key, value, d) {
3510
+ const issue = (problem, message) => ({
3511
+ key,
3512
+ value,
3513
+ problem,
3514
+ message
3515
+ });
3516
+ if (value === void 0) return void 0;
3517
+ switch (d.type) {
3518
+ case "number":
3519
+ case "integer":
3520
+ if (typeof value !== "number" || Number.isNaN(value)) return issue("type", `The option "${key}" takes a number.`);
3521
+ if (isSpecial(d, value)) return void 0;
3522
+ if (d.values !== void 0 && !d.values.includes(value)) return issue("value", `The option "${key}" takes ${d.values.join(", ")}, not ${value}.`);
3523
+ if (value < d.min || value > d.max) return issue("range", `The option "${key}" is ${value}, out of the range ${d.min} to ${d.max}.`);
3524
+ if (d.type === "integer" && !Number.isInteger(value)) return issue("integer", `The option "${key}" takes a whole number, not ${value}.`);
3525
+ return;
3526
+ case "boolean": return typeof value === "boolean" ? void 0 : issue("type", `The option "${key}" takes true or false.`);
3527
+ case "enum":
3528
+ if (d.custom === "function" && typeof value === "function") return void 0;
3529
+ return d.values.includes(value) ? void 0 : issue("value", `The option "${key}" takes ${d.values.join(", ")}, not ${String(value)}.`);
3530
+ case "function": return typeof value === "function" ? void 0 : issue("type", `The option "${key}" takes a function.`);
3531
+ case "list": return Array.isArray(value) ? void 0 : issue("type", `The option "${key}" takes a list.`);
3532
+ default: return typeof value === "object" && value !== null ? void 0 : issue("type", `The option "${key}" takes an object.`);
3533
+ }
3534
+ }
3535
+ /**
3536
+ * This function examines option values against the schema of a strategy. It gives one issue for each key without a declaration.
3537
+ * It also gives one issue for each value of the wrong type, out of the range, not whole or not one of the values.
3538
+ * It changes no value.
3539
+ * A strategy without a schema gives no issue.
3540
+ */
3541
+ function checkOptions(strategy, options) {
3542
+ if (strategy.schema === void 0) return [];
3543
+ const schema = schemaOf(strategy);
3544
+ const out = [];
3545
+ for (const [key, value] of Object.entries(options)) {
3546
+ const d = schema[key];
3547
+ const issue = d ? optionIssue(key, value, d) : {
3548
+ key,
3549
+ value,
3550
+ problem: "unknown",
3551
+ message: `The strategy "${strategy.name}" has no option "${key}".`
3552
+ };
3553
+ if (issue) out.push(issue);
3554
+ }
3555
+ return out;
3556
+ }
3557
+ /**
3558
+ * This function moves each number option into the range of its declaration, for a control. An integer option gets the nearest whole number.
3559
+ * An option with a list of `values` gets the nearest value of the list. A special value stays. The function keeps each other value as it is. `checkOptions` reports the values that this function cannot correct.
3560
+ */
3561
+ function clampOptions(strategy, options) {
3562
+ const schema = schemaOf(strategy);
3563
+ const out = { ...options };
3564
+ for (const [key, value] of Object.entries(options)) {
3565
+ const d = schema[key];
3566
+ if (!d || d.type !== "number" && d.type !== "integer" || typeof value !== "number" || Number.isNaN(value) || isSpecial(d, value)) continue;
3567
+ if (d.values !== void 0 && d.values.length > 0) {
3568
+ out[key] = d.values.reduce((best, v) => Math.abs(v - value) < Math.abs(best - value) ? v : best);
3569
+ continue;
3570
+ }
3571
+ const v = Math.min(d.max, Math.max(d.min, value));
3572
+ out[key] = d.type === "integer" ? Math.min(d.max, Math.max(d.min, Math.round(v))) : v;
3573
+ }
3574
+ return out;
3575
+ }
3576
+ /** This function gives `count` values from `min` to `max` on the scale, on the grain of the step, without repeats. */
3577
+ function rangeValues(d, count) {
3578
+ const n = Math.max(1, Math.floor(count));
3579
+ const log = d.scale === "log" && d.min > 0;
3580
+ const at = (t) => log ? d.min * (d.max / d.min) ** t : d.min + (d.max - d.min) * t;
3581
+ const step = d.step ?? (d.type === "integer" ? 1 : void 0);
3582
+ const snap = (v) => {
3583
+ const s = step === void 0 ? v : d.min + Math.round((v - d.min) / step) * step;
3584
+ const r = Number(s.toPrecision(12));
3585
+ return Math.min(d.max, Math.max(d.min, d.type === "integer" ? Math.round(r) : r));
3586
+ };
3587
+ const out = [];
3588
+ for (let i = 0; i < n; i++) {
3589
+ const v = snap(at(n === 1 ? 0 : i / (n - 1)));
3590
+ if (!out.includes(v)) out.push(v);
3591
+ }
3592
+ return out;
3593
+ }
3594
+ /**
3595
+ * This function gives the values of a sweep of one option declaration.
3596
+ * A number option gives its `marks`, or its list of `values`, or `count` values on its range and its scale. A boolean gives `false` and `true`. An enum gives its values.
3597
+ * An option of another type has no sweep, so the function throws an error.
3598
+ */
3599
+ function sweepValues(declaration, options = {}) {
3600
+ switch (declaration.type) {
3601
+ case "number":
3602
+ case "integer": {
3603
+ if (options.count === void 0 && declaration.marks !== void 0) return [...declaration.marks];
3604
+ if (declaration.values !== void 0) return [...declaration.values];
3605
+ const values = rangeValues(declaration, options.count ?? SWEEP_COUNT);
3606
+ return options.special ? [...values, ...(declaration.special ?? []).filter((s) => !values.includes(s))] : values;
3607
+ }
3608
+ case "boolean": return [false, true];
3609
+ case "enum": return [...declaration.values];
3610
+ default: throw new Error(`An option of the type "${declaration.type}" has no sweep. A sweep takes a number, an integer, a boolean or an enum.`);
3611
+ }
3612
+ }
3613
+ /** This function gives the declaration of one option of a strategy. When the strategy has no such declaration, the function throws an error. */
3614
+ function declarationOf(strategy, key) {
3615
+ const d = schemaOf(strategy)[key];
3616
+ if (!d) throw new Error(`The strategy "${strategy.name}" has no declaration of the option "${key}".`);
3617
+ return d;
3618
+ }
3619
+ /**
3620
+ * This function gives the settings of a sweep of one option of a strategy, from its declaration only.
3621
+ * The name of each setting is the key and the value, for example `stretch 1.5`.
3622
+ */
3623
+ function sweepOf(strategy, key, options = {}) {
3624
+ return sweepValues(declarationOf(strategy, key), options).map((value) => ({
3625
+ name: `${key} ${String(value)}`,
3626
+ options: { [key]: value }
3627
+ }));
3628
+ }
3629
+ /**
3630
+ * This function gives the settings of a grid of options: each combination of the values of the sweeps of the keys.
3631
+ * The name of a setting joins the names of its values with commas, in the order of the keys.
3632
+ */
3633
+ function sweepGrid(strategy, keys, options = {}) {
3634
+ let out = [{
3635
+ name: "",
3636
+ options: {}
3637
+ }];
3638
+ for (const key of keys) {
3639
+ const sweep = sweepOf(strategy, key, options);
3640
+ out = out.flatMap((s) => sweep.map((t) => ({
3641
+ name: s.name === "" ? t.name : `${s.name}, ${t.name}`,
3642
+ options: {
3643
+ ...s.options,
3644
+ ...t.options
3645
+ }
3646
+ })));
3647
+ }
3648
+ return keys.length === 0 ? [] : out;
3649
+ }
3650
+ /** This function gives the problems of one declaration: a bad range, a bad step, or marks and a default that do not fit. */
3651
+ function declarationIssues(key, d) {
3652
+ const out = [];
3653
+ if (d.describe.trim().length === 0) out.push(`The option "${key}" has no description.`);
3654
+ if (d.type === "number" || d.type === "integer") {
3655
+ if (!Number.isFinite(d.min) || !Number.isFinite(d.max) || d.min > d.max) out.push(`The option "${key}" has the bad range ${d.min} to ${d.max}.`);
3656
+ if (d.type === "integer" && (!Number.isInteger(d.min) || !Number.isInteger(d.max))) out.push(`The integer option "${key}" has a range that is not whole.`);
3657
+ if (d.step !== void 0 && !(d.step > 0)) out.push(`The option "${key}" has the step ${d.step}. A step is more than 0.`);
3658
+ if (d.scale === "log" && !(d.min > 0)) out.push(`The option "${key}" has the scale log and the min ${d.min}. The scale log needs a min above 0.`);
3659
+ if (d.values !== void 0 && d.values.length === 0) out.push(`The number option "${key}" has an empty list of values.`);
3660
+ for (const v of d.values ?? []) if (v < d.min || v > d.max || d.type === "integer" && !Number.isInteger(v)) out.push(`The value ${v} of the option "${key}" is not on its range ${d.min} to ${d.max}.`);
3661
+ for (const v of [...d.marks ?? [], ...d.default === void 0 ? [] : [d.default]]) {
3662
+ const issue = optionIssue(key, v, d);
3663
+ if (issue) out.push(issue.message);
3664
+ }
3665
+ } else if (d.type === "enum") {
3666
+ if (d.values.length === 0) out.push(`The enum option "${key}" has no values.`);
3667
+ if (d.default !== void 0 && !d.values.includes(d.default)) out.push(`The default of the option "${key}" is not one of its values.`);
3668
+ } else if (d.type === "boolean") {
3669
+ if (d.default !== void 0 && typeof d.default !== "boolean") out.push(`The default of the option "${key}" is not true or false.`);
3670
+ }
3671
+ return out;
3672
+ }
3673
+ /**
3674
+ * This function examines the schema of a strategy. It gives one message for each option of `defaults` without a declaration.
3675
+ * It also gives one message for each bad declaration, and for each value of `defaults` that does not fit its declaration.
3676
+ * A good schema gives an empty list.
3677
+ */
3678
+ function checkSchema(strategy) {
3679
+ const schema = schemaOf(strategy);
3680
+ const out = [];
3681
+ for (const key of Object.keys(strategy.defaults)) if (!(key in schema)) out.push(`The strategy "${strategy.name}" has the option "${key}" in its defaults, without a declaration.`);
3682
+ for (const [key, d] of Object.entries(schema)) out.push(...declarationIssues(key, d).map((m) => `The strategy "${strategy.name}": ${m}`));
3683
+ out.push(...checkOptions(strategy, strategy.defaults).filter((i) => i.problem !== "unknown").map((i) => `The strategy "${strategy.name}": ${i.message}`));
3684
+ return out;
3685
+ }
3686
+ // src/strategy-catalog.ts
3687
+ /** The schema of a strategy catalog. A new field is a new version of the schema. */
3688
+ const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/1";
3689
+ /**
3690
+ * The dimension of `supports` that tells who owns the positions of the nodes. The value `host` means that the strategy keeps the positions that the host gives.
3691
+ * The value `engine` means that the strategy can set them. A strategy that moves nodes has only `engine`. A `SupportProbe` tests the claim with a run.
3692
+ */
3693
+ const NODE_POSITIONS_DIMENSION = "nodePositions";
3694
+ const STRATEGY_KINDS = [
3695
+ "single",
3696
+ "composite",
3697
+ "shape"
3698
+ ];
3699
+ const NO_DEFAULT_REASONS = [
3700
+ "unset",
3701
+ "required",
3702
+ "derived",
3703
+ "function"
3704
+ ];
3705
+ const SCALES = ["linear", "log"];
3706
+ const TOP_FIELDS = [
3707
+ "schema",
3708
+ "engine",
3709
+ "version",
3710
+ "strategies"
3711
+ ];
3712
+ const ENTRY_FIELDS = [
3713
+ "key",
3714
+ "id",
3715
+ "step",
3716
+ "family",
3717
+ "kind",
3718
+ "describe",
3719
+ "supports",
3720
+ "limits",
3721
+ "deterministic",
3722
+ "determinismNote",
3723
+ "optIn",
3724
+ "baseline",
3725
+ "options"
3726
+ ];
3727
+ const COMMON_FIELDS = [
3728
+ "type",
3729
+ "describe",
3730
+ "default",
3731
+ "noDefault",
3732
+ "when"
3733
+ ];
3734
+ const NUMBER_FIELDS = [
3735
+ ...COMMON_FIELDS,
3736
+ "min",
3737
+ "max",
3738
+ "step",
3739
+ "scale",
3740
+ "special",
3741
+ "marks",
3742
+ "values"
3743
+ ];
3744
+ const ENUM_FIELDS = [
3745
+ ...COMMON_FIELDS,
3746
+ "values",
3747
+ "custom"
3748
+ ];
3749
+ const STRATEGY_FIELDS = [
3750
+ ...COMMON_FIELDS,
3751
+ "step",
3752
+ "kinds",
3753
+ "optionsKey",
3754
+ "inlineOptions",
3755
+ "optIn"
3756
+ ];
3757
+ const MEMBER_FIELDS = [
3758
+ "strategy",
3759
+ "options",
3760
+ "id"
3761
+ ];
3762
+ const LIST_FIELDS = [
3763
+ ...COMMON_FIELDS,
3764
+ "of",
3765
+ "min",
3766
+ "max"
3767
+ ];
3768
+ /** The fields of a declaration, in the order of the file. */
3769
+ const OPTION_ORDER = [
3770
+ "type",
3771
+ "describe",
3772
+ "min",
3773
+ "max",
3774
+ "step",
3775
+ "scale",
3776
+ "special",
3777
+ "marks",
3778
+ "values",
3779
+ "custom",
3780
+ "kinds",
3781
+ "optionsKey",
3782
+ "inlineOptions",
3783
+ "optIn",
3784
+ "of",
3785
+ "default",
3786
+ "noDefault",
3787
+ "when"
3788
+ ];
3789
+ const isFields = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3790
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
3791
+ const isTextList = (v) => Array.isArray(v) && v.every(isText);
3792
+ const isFiniteNumber = (v) => typeof v === "number" && Number.isFinite(v);
3793
+ const isMember = (v) => isFields(v) && isText(v["strategy"]) && (v["options"] === void 0 || isFields(v["options"])) && (v["id"] === void 0 || isText(v["id"])) && Object.keys(v).every((k) => MEMBER_FIELDS.includes(k));
3794
+ /** This function gives the key of a strategy from its step and its id. */
3795
+ function catalogKey(id, step) {
3796
+ return step === void 0 ? id : `${step}/${id}`;
3797
+ }
3798
+ /** This function adds one fault for each field of `o` that is not in `allowed`. */
3799
+ function refuseUnknown(at, o, allowed, faults) {
3800
+ for (const key of Object.keys(o)) if (!allowed.includes(key)) faults.push(`${at}: the field "${key}" is unknown.`);
3801
+ }
3802
+ /** This function restores a number field of a file. It gives `undefined` for each value that is not a finite number, `"Infinity"` or `"-Infinity"`. */
3803
+ function readNumber(v) {
3804
+ if (v === "Infinity") return Infinity;
3805
+ if (v === "-Infinity") return -Infinity;
3806
+ return isFiniteNumber(v) ? v : void 0;
3807
+ }
3808
+ /** This function restores a list of number fields, with one fault for each bad value. */
3809
+ function readNumbers(at, v, faults) {
3810
+ if (!Array.isArray(v)) {
3811
+ faults.push(`${at} is not a list.`);
3812
+ return;
3813
+ }
3814
+ const out = [];
3815
+ for (const x of v) {
3816
+ const n = readNumber(x);
3817
+ if (n === void 0) faults.push(`${at} holds a value that is not a number.`);
3818
+ else out.push(n);
3819
+ }
3820
+ return out;
3821
+ }
3822
+ /** This function gives the fields of a number declaration, restored from a file. */
3823
+ function readNumberFields(at, raw, faults) {
3824
+ const out = {};
3825
+ for (const f of ["min", "max"]) if (isFiniteNumber(raw[f])) out[f] = raw[f];
3826
+ else faults.push(`${at}: "${f}" is not a finite number.`);
3827
+ if (raw["step"] !== void 0) {
3828
+ if (isFiniteNumber(raw["step"])) out["step"] = raw["step"];
3829
+ else faults.push(`${at}: "step" is not a finite number.`);
3830
+ }
3831
+ if (raw["scale"] !== void 0) {
3832
+ if (SCALES.includes(raw["scale"])) out["scale"] = raw["scale"];
3833
+ else faults.push(`${at}: "scale" is not linear or log.`);
3834
+ }
3835
+ for (const f of ["special", "marks"]) {
3836
+ if (raw[f] === void 0) continue;
3837
+ const list = readNumbers(`${at}: "${f}"`, raw[f], faults);
3838
+ if (list !== void 0) out[f] = list;
3839
+ }
3840
+ if (raw["values"] !== void 0) {
3841
+ if (Array.isArray(raw["values"]) && raw["values"].every(isFiniteNumber)) out["values"] = raw["values"];
3842
+ else faults.push(`${at}: "values" is not a list of finite numbers.`);
3843
+ }
3844
+ if (raw["default"] !== void 0) {
3845
+ const n = readNumber(raw["default"]);
3846
+ if (n === void 0) faults.push(`${at}: the default is not a number.`);
3847
+ else out["default"] = n;
3848
+ }
3849
+ return out;
3850
+ }
3851
+ /** This function gives the fields of a list declaration, restored from a file. */
3852
+ function readListFields(at, raw, faults) {
3853
+ const out = {};
3854
+ if (raw["of"] !== void 0) {
3855
+ const item = readOption(`${at}: "of"`, raw["of"], true, faults);
3856
+ if (item !== void 0) out["of"] = item;
3857
+ if (isFields(raw["of"]) && raw["of"]["optionsKey"] !== void 0) faults.push(`${at}: an item of a list has no sibling for "optionsKey". Use "inlineOptions".`);
3858
+ }
3859
+ for (const f of ["min", "max"]) {
3860
+ if (raw[f] === void 0) continue;
3861
+ if (Number.isInteger(raw[f]) && raw[f] >= 0) out[f] = raw[f];
3862
+ else faults.push(`${at}: "${f}" is not a whole number.`);
3863
+ }
3864
+ if (raw["default"] !== void 0) {
3865
+ if (Array.isArray(raw["default"])) out["default"] = raw["default"];
3866
+ else faults.push(`${at}: the default is not a list.`);
3867
+ }
3868
+ if (typeof out["min"] === "number" && typeof out["max"] === "number" && out["min"] > out["max"]) faults.push(`${at}: "min" is more than "max".`);
3869
+ return out;
3870
+ }
3871
+ /** This function gives the fields of a `strategy` declaration, restored from a file. */
3872
+ function readStrategyFields(at, raw, faults) {
3873
+ const out = {};
3874
+ if (raw["step"] !== void 0) {
3875
+ if (isText(raw["step"])) out["step"] = raw["step"];
3876
+ else faults.push(`${at}: "step" is not a text.`);
3877
+ }
3878
+ if (raw["kinds"] !== void 0) {
3879
+ if (isTextList(raw["kinds"]) && raw["kinds"].every((k) => STRATEGY_KINDS.includes(k))) out["kinds"] = raw["kinds"];
3880
+ else faults.push(`${at}: "kinds" is not a list of strategy kinds.`);
3881
+ }
3882
+ if (raw["optionsKey"] !== void 0) {
3883
+ if (isText(raw["optionsKey"])) out["optionsKey"] = raw["optionsKey"];
3884
+ else faults.push(`${at}: "optionsKey" is not a text.`);
3885
+ }
3886
+ for (const f of ["inlineOptions", "optIn"]) {
3887
+ if (raw[f] === void 0) continue;
3888
+ if (typeof raw[f] === "boolean") out[f] = raw[f];
3889
+ else faults.push(`${at}: "${f}" is not true or false.`);
3890
+ }
3891
+ if (raw["inlineOptions"] === true && raw["optionsKey"] !== void 0) faults.push(`${at}: "inlineOptions" and "optionsKey" give two places for the options.`);
3892
+ if (raw["default"] !== void 0) {
3893
+ if (isText(raw["default"]) || raw["inlineOptions"] === true && isMember(raw["default"])) out["default"] = raw["default"];
3894
+ else faults.push(`${at}: the default is not the key of a strategy.`);
3895
+ }
3896
+ return out;
3897
+ }
3898
+ /** This function gives the fields that belong only to the type of a declaration, restored from a file. */
3899
+ function readTypeFields(at, type, raw, faults) {
3900
+ switch (type) {
3901
+ case "number":
3902
+ case "integer":
3903
+ refuseUnknown(at, raw, NUMBER_FIELDS, faults);
3904
+ return readNumberFields(at, raw, faults);
3905
+ case "boolean":
3906
+ refuseUnknown(at, raw, COMMON_FIELDS, faults);
3907
+ if (raw["default"] !== void 0 && typeof raw["default"] !== "boolean") faults.push(`${at}: the default is not true or false.`);
3908
+ return raw["default"] === void 0 ? {} : { default: raw["default"] };
3909
+ case "enum":
3910
+ refuseUnknown(at, raw, ENUM_FIELDS, faults);
3911
+ if (!isTextList(raw["values"])) faults.push(`${at}: "values" is not a list of texts.`);
3912
+ if (raw["custom"] !== void 0 && raw["custom"] !== "function") faults.push(`${at}: "custom" is not "function".`);
3913
+ return {
3914
+ values: raw["values"],
3915
+ ...raw["custom"] === void 0 ? {} : { custom: raw["custom"] },
3916
+ ...raw["default"] === void 0 ? {} : { default: raw["default"] }
3917
+ };
3918
+ case "strategy":
3919
+ refuseUnknown(at, raw, STRATEGY_FIELDS, faults);
3920
+ return readStrategyFields(at, raw, faults);
3921
+ case "list":
3922
+ refuseUnknown(at, raw, LIST_FIELDS, faults);
3923
+ return readListFields(at, raw, faults);
3924
+ case "object":
3925
+ refuseUnknown(at, raw, COMMON_FIELDS, faults);
3926
+ return raw["default"] === void 0 ? {} : { default: raw["default"] };
3927
+ case "function":
3928
+ refuseUnknown(at, raw, COMMON_FIELDS, faults);
3929
+ if (raw["default"] !== void 0) faults.push(`${at}: a function option has no default in JSON.`);
3930
+ return {};
3931
+ default:
3932
+ faults.push(`${at}: the type "${type}" is unknown.`);
3933
+ return {};
3934
+ }
3935
+ }
3936
+ /** This function adds the faults of the statement of an absent default, and gives the statement. */
3937
+ function readNoDefault(at, raw, faults) {
3938
+ if (!isFields(raw)) {
3939
+ faults.push(`${at}: "noDefault" is not an object.`);
3940
+ return;
3941
+ }
3942
+ refuseUnknown(`${at}: "noDefault"`, raw, ["reason", "describe"], faults);
3943
+ if (!NO_DEFAULT_REASONS.includes(raw["reason"])) faults.push(`${at}: the reason of "noDefault" is unknown.`);
3944
+ if (!isText(raw["describe"])) faults.push(`${at}: "noDefault" has no description.`);
3945
+ return {
3946
+ reason: raw["reason"],
3947
+ describe: raw["describe"]
3948
+ };
3949
+ }
3950
+ /** This function restores one declaration of a file. An item of a list has only the fields of its type. */
3951
+ function readOption(at, raw, item, faults) {
3952
+ if (!isFields(raw)) {
3953
+ faults.push(`${at} is not an object.`);
3954
+ return;
3955
+ }
3956
+ const type = raw["type"];
3957
+ if (typeof type !== "string") {
3958
+ faults.push(`${at} has no type.`);
3959
+ return;
3960
+ }
3961
+ const before = faults.length;
3962
+ const out = {
3963
+ type,
3964
+ ...readTypeFields(at, type, raw, faults)
3965
+ };
3966
+ if (item) {
3967
+ for (const f of [
3968
+ "describe",
3969
+ "default",
3970
+ "noDefault",
3971
+ "when"
3972
+ ]) if (raw[f] !== void 0) faults.push(`${at}: an item of a list has no "${f}".`);
3973
+ } else {
3974
+ if (isText(raw["describe"])) out["describe"] = raw["describe"];
3975
+ else faults.push(`${at} has no description.`);
3976
+ const hasDefault = raw["default"] !== void 0;
3977
+ const hasNoDefault = raw["noDefault"] !== void 0;
3978
+ if (hasDefault === hasNoDefault) faults.push(`${at} has ${hasDefault ? "both" : "neither"} of "default" and "noDefault".`);
3979
+ if (hasNoDefault) out["noDefault"] = readNoDefault(at, raw["noDefault"], faults);
3980
+ if (raw["when"] !== void 0) out["when"] = raw["when"];
3981
+ }
3982
+ return faults.length === before ? out : void 0;
3983
+ }
3984
+ /** This function adds the faults of the condition of an option, against the options before it. */
3985
+ function checkWhen(at, when, earlier, faults) {
3986
+ if (!isFields(when) || !isText(when["param"]) || !Array.isArray(when["in"])) {
3987
+ faults.push(`${at}: "when" has no "param" and "in".`);
3988
+ return;
3989
+ }
3990
+ refuseUnknown(`${at}: "when"`, when, ["param", "in"], faults);
3991
+ if (!earlier.includes(when["param"])) faults.push(`${at}: "when" names "${when["param"]}", which is not an earlier option.`);
3992
+ }
3993
+ /** This function adds the faults of the limits of an entry. */
3994
+ function checkLimits(at, limits, faults) {
3995
+ if (!isFields(limits)) {
3996
+ faults.push(`${at}: "limits" is not an object.`);
3997
+ return;
3998
+ }
3999
+ for (const [name, raw] of Object.entries(limits)) {
4000
+ const place = `${at}: the limit "${name}"`;
4001
+ if (!isFields(raw)) {
4002
+ faults.push(`${place} is not an object.`);
4003
+ continue;
4004
+ }
4005
+ refuseUnknown(place, raw, [
4006
+ "min",
4007
+ "max",
4008
+ "describe"
4009
+ ], faults);
4010
+ if (!isText(raw["describe"])) faults.push(`${place} has no description.`);
4011
+ if (raw["min"] === void 0 && raw["max"] === void 0) faults.push(`${place} has no "min" and no "max".`);
4012
+ for (const f of ["min", "max"]) if (raw[f] !== void 0 && !isFiniteNumber(raw[f])) faults.push(`${place}: "${f}" is not a finite number.`);
4013
+ if (isFiniteNumber(raw["min"]) && isFiniteNumber(raw["max"]) && raw["min"] > raw["max"]) faults.push(`${place}: "min" is more than "max".`);
4014
+ }
4015
+ }
4016
+ /** This function restores one entry of a file. */
4017
+ function readEntry(at, raw, faults) {
4018
+ if (!isFields(raw)) {
4019
+ faults.push(`${at} is not an object.`);
4020
+ return;
4021
+ }
4022
+ const before = faults.length;
4023
+ refuseUnknown(at, raw, ENTRY_FIELDS, faults);
4024
+ for (const f of [
4025
+ "key",
4026
+ "id",
4027
+ "family",
4028
+ "describe"
4029
+ ]) if (!isText(raw[f])) faults.push(`${at}: "${f}" is not a text.`);
4030
+ if (raw["step"] !== void 0 && !isText(raw["step"])) faults.push(`${at}: "step" is not a text.`);
4031
+ if (raw["determinismNote"] !== void 0 && !isText(raw["determinismNote"])) faults.push(`${at}: "determinismNote" is not a text.`);
4032
+ if (!STRATEGY_KINDS.includes(raw["kind"])) faults.push(`${at}: "kind" is unknown.`);
4033
+ for (const f of ["deterministic", "optIn"]) if (typeof raw[f] !== "boolean") faults.push(`${at}: "${f}" is not true or false.`);
4034
+ if (raw["baseline"] !== void 0 && raw["baseline"] !== true) faults.push(`${at}: "baseline" is not true.`);
4035
+ if (raw["baseline"] === true && raw["optIn"] !== true) faults.push(`${at}: a baseline has "optIn" true.`);
4036
+ if (!isFields(raw["supports"]) || !Object.values(raw["supports"]).every(isTextList)) faults.push(`${at}: "supports" is not a record of text lists.`);
4037
+ checkLimits(at, raw["limits"], faults);
4038
+ if (isText(raw["id"]) && raw["key"] !== catalogKey(raw["id"], raw["step"])) faults.push(`${at}: the key does not follow from "step" and "id".`);
4039
+ if (!isFields(raw["options"])) {
4040
+ faults.push(`${at}: "options" is not an object.`);
4041
+ return;
4042
+ }
4043
+ const options = {};
4044
+ const earlier = [];
4045
+ for (const [key, value] of Object.entries(raw["options"])) {
4046
+ const place = `${at}: the option "${key}"`;
4047
+ const option = readOption(place, value, false, faults);
4048
+ if (option !== void 0) {
4049
+ options[key] = option;
4050
+ for (const message of declarationIssues(key, option)) faults.push(`${at}: ${message}`);
4051
+ if (option.when !== void 0) checkWhen(place, option.when, earlier, faults);
4052
+ }
4053
+ earlier.push(key);
4054
+ }
4055
+ if (faults.length !== before) return void 0;
4056
+ const { step, determinismNote } = raw;
4057
+ return {
4058
+ key: raw["key"],
4059
+ id: raw["id"],
4060
+ ...step === void 0 ? {} : { step },
4061
+ family: raw["family"],
4062
+ kind: raw["kind"],
4063
+ describe: raw["describe"],
4064
+ supports: raw["supports"],
4065
+ limits: raw["limits"],
4066
+ deterministic: raw["deterministic"],
4067
+ ...determinismNote === void 0 ? {} : { determinismNote },
4068
+ optIn: raw["optIn"],
4069
+ ...raw["baseline"] === true ? { baseline: true } : {},
4070
+ options
4071
+ };
4072
+ }
4073
+ /**
4074
+ * This function gives the strategies that a chooser offers, by the `step`, `kinds` and `optIn` of an option. Thus no chooser keeps a copy of this rule.
4075
+ * A baseline is not in the result. A list gives the strategies of its items. An option of each other type gives nothing.
4076
+ * Without a declaration, the function gives each strategy that is not a baseline.
4077
+ */
4078
+ function catalogChoices(strategies, declaration) {
4079
+ const offered = strategies.filter((e) => e.baseline !== true);
4080
+ if (declaration === void 0) return offered;
4081
+ const d = declaration.type === "list" ? declaration.of : declaration;
4082
+ if (d?.type !== "strategy") return [];
4083
+ return offered.filter((e) => (d.step === void 0 || e.step === d.step) && (d.kinds === void 0 || d.kinds.includes(e.kind)) && (d.optIn === void 0 || d.optIn === e.optIn));
4084
+ }
4085
+ /** This function adds one fault for each option of a member that its chosen strategy does not take. */
4086
+ function checkMember(at, member, chosen, faults) {
4087
+ for (const [key, value] of Object.entries(member.options ?? {})) {
4088
+ const declaration = chosen.options[key];
4089
+ if (declaration === void 0) {
4090
+ faults.push(`${at}: the default gives "${key}", and ${chosen.key} has no such option.`);
4091
+ continue;
4092
+ }
4093
+ const issue = declaration.type === "strategy" ? void 0 : optionIssue(key, decodeOptionValue(value, declaration), declaration);
4094
+ if (issue !== void 0) faults.push(`${at}: ${issue.message}`);
4095
+ }
4096
+ }
4097
+ /** This function adds one fault for each reference that names no strategy of the catalog, or a strategy that the option does not take. */
4098
+ function checkReferences(entries, faults) {
4099
+ const check = (at, o, values) => {
4100
+ const choices = catalogChoices(entries, o);
4101
+ if (choices.length === 0) faults.push(`${at} takes no strategy of the catalog.`);
4102
+ for (const value of values) {
4103
+ const inline = (o.type === "list" ? o.of : o).inlineOptions === true && isMember(value);
4104
+ const key = inline ? value.strategy : value;
4105
+ const chosen = choices.find((e) => e.key === key);
4106
+ if (chosen === void 0) faults.push(`${at}: the default ${JSON.stringify(key)} is not a strategy that the option takes.`);
4107
+ else if (inline) checkMember(at, value, chosen, faults);
4108
+ }
4109
+ };
4110
+ for (const entry of entries) for (const [key, o] of Object.entries(entry.options)) {
4111
+ const at = `${entry.key}: the option "${key}"`;
4112
+ if (o.type === "strategy") {
4113
+ check(at, o, o.default === void 0 ? [] : [o.default]);
4114
+ if (o.optionsKey !== void 0 && (o.optionsKey === key || entry.options[o.optionsKey]?.type !== "object")) faults.push(`${at}: "optionsKey" does not name an object option.`);
4115
+ } else if (o.type === "list" && o.of?.type === "strategy") check(at, o, Array.isArray(o.default) ? o.default : []);
4116
+ if (o.type === "list" && Array.isArray(o.default)) {
4117
+ if (o.min !== void 0 && o.default.length < o.min) faults.push(`${at}: the default has fewer than ${o.min} items.`);
4118
+ if (o.max !== void 0 && o.default.length > o.max) faults.push(`${at}: the default has more than ${o.max} items.`);
4119
+ }
4120
+ }
4121
+ }
4122
+ /**
4123
+ * This function reads a catalog from parsed JSON. It refuses each unknown field and each other schema.
4124
+ * It gives the catalog with its `Infinity` values restored, or the list of all faults.
4125
+ */
4126
+ function parseStrategyCatalog(value) {
4127
+ const faults = [];
4128
+ if (!isFields(value)) return {
4129
+ ok: false,
4130
+ faults: ["The catalog is not an object."]
4131
+ };
4132
+ refuseUnknown("The catalog", value, TOP_FIELDS, faults);
4133
+ if (value["schema"] !== "strategy-catalog/1") faults.push(`The schema is not ${STRATEGY_CATALOG_SCHEMA}.`);
4134
+ if (!isText(value["engine"])) faults.push(`"engine" is not a text.`);
4135
+ if (!isText(value["version"])) faults.push(`"version" is not a text.`);
4136
+ if (!Array.isArray(value["strategies"])) return {
4137
+ ok: false,
4138
+ faults: [...faults, `"strategies" is not a list.`]
4139
+ };
4140
+ const entries = [];
4141
+ value["strategies"].forEach((raw, i) => {
4142
+ const entry = readEntry(`The strategy ${isFields(raw) && isText(raw["key"]) ? raw["key"] : i}`, raw, faults);
4143
+ if (entry !== void 0) entries.push(entry);
4144
+ });
4145
+ for (let i = 1; i < entries.length; i++) {
4146
+ const [a, b] = [entries[i - 1].key, entries[i].key];
4147
+ if (a === b) faults.push(`The key ${a} is not unique.`);
4148
+ else if (a > b) faults.push(`The key ${b} is out of order.`);
4149
+ }
4150
+ if (faults.length === 0) checkReferences(entries, faults);
4151
+ if (faults.length > 0) return {
4152
+ ok: false,
4153
+ faults
4154
+ };
4155
+ return {
4156
+ ok: true,
4157
+ catalog: {
4158
+ schema: STRATEGY_CATALOG_SCHEMA,
4159
+ engine: value["engine"],
4160
+ version: value["version"],
4161
+ strategies: entries
4162
+ }
4163
+ };
4164
+ }
4165
+ /** This function gives the file form of a number. A value that is not finite becomes its name, and `NaN` stays for the writer to refuse. */
4166
+ const writeNumber = (v) => v === Infinity ? "Infinity" : v === -Infinity ? "-Infinity" : v;
4167
+ /**
4168
+ * This function gives the value of an option for a call of the engine, from its JSON form.
4169
+ * The strings `"Infinity"` and `"-Infinity"` become numbers in a number option, and in a list of numbers. Each other value stays as it is.
4170
+ */
4171
+ function decodeOptionValue(value, declaration) {
4172
+ if (declaration.type === "number" || declaration.type === "integer") return readNumber(value) ?? value;
4173
+ if (declaration.type === "list" && declaration.of !== void 0 && Array.isArray(value)) {
4174
+ const item = declaration.of;
4175
+ return value.map((v) => decodeOptionValue(v, item));
4176
+ }
4177
+ return value;
4178
+ }
4179
+ /** This function gives the JSON form of the value of an option. It is the inverse of `decodeOptionValue`. */
4180
+ function encodeOptionValue(value, declaration) {
4181
+ if (declaration.type === "number" || declaration.type === "integer") return writeNumber(value);
4182
+ if (declaration.type === "list" && declaration.of !== void 0 && Array.isArray(value)) {
4183
+ const item = declaration.of;
4184
+ return value.map((v) => encodeOptionValue(v, item));
4185
+ }
4186
+ return value;
4187
+ }
4188
+ /** This function gives the file form of a declaration, with its fields in the order of the file. */
4189
+ function writeOption(option) {
4190
+ const o = option;
4191
+ for (const key of Object.keys(o)) if (!OPTION_ORDER.includes(key) && o[key] !== void 0) throw new Error(`The field "${key}" is not a field of a declaration.`);
4192
+ const numeric = o["type"] === "number" || o["type"] === "integer";
4193
+ const out = {};
4194
+ for (const f of OPTION_ORDER) {
4195
+ const v = o[f];
4196
+ if (v === void 0) continue;
4197
+ if (f === "of") out[f] = writeOption(v);
4198
+ else if (numeric && f === "default") out[f] = writeNumber(v);
4199
+ else if (numeric && (f === "special" || f === "marks")) out[f] = v.map(writeNumber);
4200
+ else out[f] = v;
4201
+ }
4202
+ return out;
4203
+ }
4204
+ /** This function gives the file form of an entry, with its fields in the order of the file. */
4205
+ function writeEntry(e) {
4206
+ const options = Object.fromEntries(Object.entries(e.options).map(([key, o]) => [key, writeOption(o)]));
4207
+ return {
4208
+ key: e.key,
4209
+ id: e.id,
4210
+ ...e.step === void 0 ? {} : { step: e.step },
4211
+ family: e.family,
4212
+ kind: e.kind,
4213
+ describe: e.describe,
4214
+ supports: e.supports,
4215
+ limits: e.limits,
4216
+ deterministic: e.deterministic,
4217
+ ...e.determinismNote === void 0 ? {} : { determinismNote: e.determinismNote },
4218
+ optIn: e.optIn,
4219
+ ...e.baseline === true ? { baseline: true } : {},
4220
+ options
4221
+ };
4222
+ }
4223
+ /** This function gives the place of each value that JSON cannot hold: a function, `undefined` in a list, or a number that is not finite. */
4224
+ function unsafeValues(v, at) {
4225
+ if (typeof v === "function") return [`${at} is a function.`];
4226
+ if (typeof v === "number") return Number.isFinite(v) ? [] : [`${at} is ${v}.`];
4227
+ if (Array.isArray(v)) return v.flatMap((x, i) => x === void 0 ? [`${at}[${i}] is undefined.`] : unsafeValues(x, `${at}[${i}]`));
4228
+ if (isFields(v)) return Object.entries(v).flatMap(([k, x]) => unsafeValues(x, `${at}.${k}`));
4229
+ return [];
4230
+ }
4231
+ /**
4232
+ * This function gives the text of the catalog file, sorted by key. The same source and version give the same bytes.
4233
+ * The caller gives the version from `package.json`. The function throws an error if the file breaks a rule of the format.
4234
+ */
4235
+ function writeStrategyCatalog(source, version) {
4236
+ const strategies = [...source.strategies].sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0).map(writeEntry);
4237
+ const doc = {
4238
+ schema: STRATEGY_CATALOG_SCHEMA,
4239
+ engine: source.engine,
4240
+ version,
4241
+ strategies
4242
+ };
4243
+ const unsafe = unsafeValues(doc, "catalog");
4244
+ if (unsafe.length > 0) throw new Error(`The catalog of ${source.engine} has values that JSON cannot hold: ${unsafe.join(" ")}`);
4245
+ const text = `${JSON.stringify(doc, null, 2)}\n`;
4246
+ const parsed = parseStrategyCatalog(JSON.parse(text));
4247
+ if (!parsed.ok) throw new Error(`The catalog of ${source.engine} breaks the format: ${parsed.faults.join(" ")}`);
4248
+ return text;
4249
+ }
4250
+ /** This function gives the default of each option of an entry that has a default. */
4251
+ function catalogDefaults(entry) {
4252
+ return Object.fromEntries(Object.entries(entry.options).flatMap(([key, o]) => o.default === void 0 ? [] : [[key, o.default]]));
4253
+ }
4254
+ /**
4255
+ * This function gives the catalog declarations of a strategy from its live `defaults` and its schema. Thus each engine has no copy of this rule.
4256
+ * A live default goes on its declaration. A function stays out, so the declaration needs its own `noDefault`.
4257
+ */
4258
+ function catalogOptions(defaults, schema, options = {}) {
4259
+ const out = {};
4260
+ for (const [key, declaration] of Object.entries(schema)) {
4261
+ const live = key in defaults ? defaults[key] : declaration.default;
4262
+ const value = declaration.type === "strategy" && typeof live === "object" && live !== null && !(declaration.inlineOptions === true && isMember(live)) ? options.strategyKey?.(live) : live;
4263
+ const { default: _unused, ...rest } = declaration;
4264
+ out[key] = value === void 0 || typeof value === "function" ? rest : {
4265
+ ...rest,
4266
+ default: value
4267
+ };
4268
+ }
4269
+ return out;
4270
+ }
4271
+ /** This function adds the faults of one entry against its live facts. */
4272
+ function checkLive(entry, live, faults) {
4273
+ const defaults = catalogDefaults(entry);
4274
+ if (entry.optIn !== live.optIn) faults.push(`${entry.key}: "optIn" is ${entry.optIn}, and the engine gives ${live.optIn}.`);
4275
+ if (entry.baseline === true !== (live.baseline === true)) faults.push(`${entry.key}: "baseline" differs from the engine.`);
4276
+ if (canonicalJson(Object.fromEntries(Object.entries(entry.limits).map(([name, { min, max }]) => [name, {
4277
+ min,
4278
+ max
4279
+ }]))) !== canonicalJson(live.limits ?? {})) faults.push(`${entry.key}: "limits" differ from the limits of the engine.`);
4280
+ for (const [key, value] of Object.entries(live.defaults)) {
4281
+ const option = entry.options[key];
4282
+ if (option === void 0) faults.push(`${entry.key}: the default "${key}" has no declaration.`);
4283
+ else if (typeof value === "function") {
4284
+ if (option.noDefault?.reason !== "function") faults.push(`${entry.key}: the default "${key}" is code, and its "noDefault" does not say it.`);
4285
+ } else if (option.type !== "strategy" || typeof value === "string" || option.inlineOptions === true && isMember(value)) {
4286
+ if (!(Object.is(value, defaults[key]) || canonicalJson(value) === canonicalJson(defaults[key]))) faults.push(`${entry.key}: the default "${key}" differs from the live default.`);
4287
+ }
4288
+ }
4289
+ }
4290
+ /** This function runs each entry that claims determinism two times, and compares the bytes. */
4291
+ function checkDeterminism(entry, live, faults, notRun) {
4292
+ if (!entry.deterministic) return;
4293
+ if (live.run === void 0) {
4294
+ notRun.push(`${entry.key}: the engine gives no fixture.`);
4295
+ return;
4296
+ }
4297
+ try {
4298
+ if (live.run() !== live.run()) faults.push(`${entry.key}: "deterministic" is true, and two runs differ.`);
4299
+ } catch (error) {
4300
+ notRun.push(`${entry.key}: ${error instanceof Error ? error.message : String(error)}`);
4301
+ }
4302
+ }
4303
+ /** This function runs each probe on an entry, and compares the refusal with `supports`. */
4304
+ function checkProbes(entry, probes, faults, notRun) {
4305
+ for (const probe of probes) {
4306
+ const name = `${entry.key} on ${probe.field} ${probe.value}`;
4307
+ const declared = entry.supports[probe.field];
4308
+ const takes = declared === void 0 || declared.includes(probe.value);
4309
+ let refused;
4310
+ try {
4311
+ refused = probe.refuses(entry.key);
4312
+ } catch (error) {
4313
+ notRun.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
4314
+ continue;
4315
+ }
4316
+ if (refused === void 0) notRun.push(`${name}: the input cannot go to this strategy.`);
4317
+ else if (refused === takes) faults.push(`${name}: "supports" ${takes ? "takes" : "refuses"} the value, and the engine ${refused ? "refuses" : "takes"} it.`);
4318
+ }
4319
+ }
4320
+ /** This function runs each strategy that an option of an entry offers, because a chooser must not offer a strategy that fails. */
4321
+ function checkChoices(entry, strategies, refuses, faults, notRun) {
4322
+ for (const [key, declaration] of Object.entries(entry.options)) for (const choice of catalogChoices(strategies, declaration)) {
4323
+ const name = `${entry.key}: the option "${key}" with ${choice.key}`;
4324
+ let refused;
4325
+ try {
4326
+ refused = refuses(entry.key, key, choice.key);
4327
+ } catch (error) {
4328
+ notRun.push(`${name}: ${error instanceof Error ? error.message : String(error)}`);
4329
+ continue;
4330
+ }
4331
+ if (refused === void 0) notRun.push(`${name}: the input cannot go to this strategy.`);
4332
+ else if (refused) faults.push(`${name}: the option offers this strategy, and the engine refuses it.`);
4333
+ }
4334
+ }
4335
+ /** This function examines each param of a space against the declaration of its option. */
4336
+ function checkSpaceParams(space, entries, faults, notMatched) {
4337
+ for (const stage of space.stages) for (const option of stage.options) {
4338
+ const entry = entries.get(`${stage.name}/${option.id}`) ?? entries.get(option.id);
4339
+ if (entry === void 0) {
4340
+ notMatched.push(`${stage.name}/${option.id}`);
4341
+ continue;
4342
+ }
4343
+ for (const param of option.params) {
4344
+ const declaration = entry.options[param.name];
4345
+ if (declaration === void 0) {
4346
+ notMatched.push(`${stage.name}/${option.id}.${param.name}`);
4347
+ continue;
4348
+ }
4349
+ const values = [
4350
+ param.min,
4351
+ param.max,
4352
+ ...param.values ?? [],
4353
+ param.default
4354
+ ].filter((v) => v !== void 0);
4355
+ for (const value of values) {
4356
+ const issue = optionIssue(param.name, value, declaration);
4357
+ if (issue !== void 0) faults.push(`${entry.key}: the space ${space.engine} is outside the declaration. ${issue.message}`);
4358
+ }
4359
+ }
4360
+ }
4361
+ }
4362
+ /**
4363
+ * This function examines a catalog against its engine: the live defaults, the set of strategies and a round trip through JSON.
4364
+ * It also examines the claims of determinism, `supports`, `limits`, the choices of each strategy option and the spaces.
4365
+ * A claim that no run can examine goes to `notRun`, by key, so a test can state their count.
4366
+ */
4367
+ function checkCatalog(source, registry, options = {}) {
4368
+ const faults = [];
4369
+ const notRun = [];
4370
+ const notMatched = [];
4371
+ let text;
4372
+ try {
4373
+ text = writeStrategyCatalog(source, "0.0.0");
4374
+ } catch (error) {
4375
+ faults.push(error instanceof Error ? error.message : String(error));
4376
+ }
4377
+ if (text !== void 0) {
4378
+ const parsed = parseStrategyCatalog(JSON.parse(text));
4379
+ if (!parsed.ok || writeStrategyCatalog(parsed.catalog, "0.0.0") !== text) faults.push("A round trip through JSON changes the catalog.");
4380
+ }
4381
+ const entries = new Map(source.strategies.map((e) => [e.key, e]));
4382
+ const live = new Map(registry.map((e) => [e.key, e]));
4383
+ for (const key of live.keys()) if (!entries.has(key)) faults.push(`${key} is in the engine, and not in the catalog.`);
4384
+ for (const key of entries.keys()) if (!live.has(key)) faults.push(`${key} is in the catalog, and not in the engine.`);
4385
+ for (const [key, entry] of entries) {
4386
+ const facts = live.get(key);
4387
+ if (facts === void 0) continue;
4388
+ checkLive(entry, facts, faults);
4389
+ checkDeterminism(entry, facts, faults, notRun);
4390
+ checkProbes(entry, options.probes ?? [], faults, notRun);
4391
+ if (options.refusesChoice !== void 0) checkChoices(entry, source.strategies, options.refusesChoice, faults, notRun);
4392
+ }
4393
+ for (const space of options.spaces ?? []) checkSpaceParams(space, entries, faults, notMatched);
4394
+ return {
4395
+ faults,
4396
+ notRun,
4397
+ notMatched
4398
+ };
4399
+ }
3461
4400
  // src/verdict.ts
3462
4401
  /**
3463
4402
  * The largest count of inputs for the exact permutation test. Up to this count, the test enumerates all `2^n` sign sets.
@@ -4088,7 +5027,7 @@ function activeValues(dimensions, full) {
4088
5027
  return active;
4089
5028
  }
4090
5029
  /** This function gives the active values of each cell of a sweep, in the order of the dimensions. The last dimension changes first. */
4091
- function* sweepOf(dimensions, levels, i = 0, values = {}) {
5030
+ function* sweepOf$1(dimensions, levels, i = 0, values = {}) {
4092
5031
  if (i === dimensions.length) {
4093
5032
  yield { ...values };
4094
5033
  return;
@@ -4096,13 +5035,13 @@ function* sweepOf(dimensions, levels, i = 0, values = {}) {
4096
5035
  const d = dimensions[i];
4097
5036
  const lv = levels[i];
4098
5037
  if (lv === void 0 || !paramActive(d, values)) {
4099
- yield* sweepOf(dimensions, levels, i + 1, paramActive(d, values) ? {
5038
+ yield* sweepOf$1(dimensions, levels, i + 1, paramActive(d, values) ? {
4100
5039
  ...values,
4101
5040
  [d.name]: paramValue(d, d.default)
4102
5041
  } : values);
4103
5042
  return;
4104
5043
  }
4105
- for (const v of lv) yield* sweepOf(dimensions, levels, i + 1, {
5044
+ for (const v of lv) yield* sweepOf$1(dimensions, levels, i + 1, {
4106
5045
  ...values,
4107
5046
  [d.name]: paramValue(d, v)
4108
5047
  });
@@ -4260,7 +5199,7 @@ function createFamilyRegistry(families = []) {
4260
5199
  },
4261
5200
  *cells(name, options = {}) {
4262
5201
  const f = find(name, options.version);
4263
- for (const values of sweepOf(f.dimensions, sweepLevels(f.dimensions, options, label(f), familyKind(f.name, f.version)))) yield resolveIn(f, values);
5202
+ for (const values of sweepOf$1(f.dimensions, sweepLevels(f.dimensions, options, label(f), familyKind(f.name, f.version)))) yield resolveIn(f, values);
4264
5203
  },
4265
5204
  cellCount(name, options = {}) {
4266
5205
  const f = find(name, options.version);
@@ -4475,6 +5414,6 @@ const RECT_SCATTERED = /* @__PURE__ */ Object.freeze({
4475
5414
  };
4476
5415
  }
4477
5416
  });
4478
- export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_STEP_VERSION, EPS, FAMILY_ANY_KIND, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkShapes, checkSpace, checkSplit, compareMeasure, composeFamily, configId, corpusHashOf, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, declaredClaimOf, declaredCounts, dimensionAt, dimensionSupports, dimensionUnit, documentHash, edgeStep, enumerateSpace, exercised, familyKind, familyOf, fnv1a32, grow, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, marginSides, minEffectOf, mulberry32, nearestGaps, outputGroups, outputHash, overlapOf, ownerDimension, packHard, packLinks, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, perChange, pickMoves, placedRect, pointSegmentDistance, portPoint, portfolio, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict };
5417
+ export { BALANCE_MEASURE_SUFFIXES, BALANCE_SIDE_DEPTH, CORPUS_DIMENSIONS, DEFAULT_FAMILY_BY, DEFAULT_RNG, DEFAULT_SHAPES, DEFAULT_TOLERANCE, EDGES_STEP, EDGE_DENSITY, EDGE_STEP_VERSION, EPS, FAMILY_ANY_KIND, INVALIDATED_FIELD, JOINT_MEASURES, JOINT_MOVED_MIN, NODE_POSITIONS_DIMENSION, PACK_HARD_RULES, RECORD_EPS, RECORD_SCALE, RECT_SCATTERED, SHAPE_KINDS, SHAPE_KIND_IDS, SIDES, SPLIT_SCHEMA, STRATEGY_CATALOG_SCHEMA, STRATEGY_SPACE_SCHEMA, VERDICT_DRAWS, VERDICT_EXACT_CAP, VERDICT_EXACT_MAX, VERDICT_RUNS, VERDICT_SEED, applyPack, balanceMeasureSpecs, balanceMeasures, balanceOf, boundsOf, boxArea, canonicalConfig, canonicalInput, canonicalJson, catalogChoices, catalogDefaults, catalogKey, catalogOptions, checkCatalog, checkConfig, checkDeclared, checkInput, checkLayoutRecord, checkOptions, checkSchema, checkShapes, checkSpace, checkSplit, clampOptions, compareMeasure, composeFamily, configId, corpusHashOf, countObstacleHits, countOutside, countOverlaps, countPortsOffBorder, createFamilyRegistry, declarationIssues, declaredClaimOf, declaredCounts, decodeOptionValue, dimensionAt, dimensionSupports, dimensionUnit, documentHash, edgeStep, encodeOptionValue, enumerateSpace, exercised, familyKind, familyOf, fnv1a32, grow, isShapeKind, itemShapeOf, joinConfigs, leaveOneSeedOut, levelsOf, listOptions, marginSides, minEffectOf, mulberry32, nearestGaps, optionDefaults, optionIssue, outputGroups, outputHash, overlapOf, ownerDimension, packHard, packLinks, paramActive, paramLevels, paramProblem, paramValue, parseLayoutRecord, parseStrategyCatalog, perChange, pickMoves, placedRect, pointSegmentDistance, portPoint, portfolio, procrustesOf, productSpace, randomInt, rectInRegion, regionArea, regionHitsRect, resolveDimensions, ruleLevel, segmentsCross, selectBest, sha256Hex, shapeKindOf, shapeKindProblem, shapeKindsOf, shapeLevel, shapeSupportProblems, shapesOf, sharedDimension, spaceShapeKinds, spaceSize, splitConfig, splitFileName, splitFolds, stepRandom, sweepGrid, sweepOf, sweepValues, toLayoutRecord, toPackInput, toRect, toSizedRect, translate, turnBox, turnMargin, turnPoint, turnPort, turnRegion, turnSide, verdict, writeStrategyCatalog };
4479
5418
 
4480
5419
  //# sourceMappingURL=index.js.map