@mark1russell7/layout-contract 0.3.12 → 0.5.0

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.
@@ -4,8 +4,14 @@ import type { Supports } from "./record.ts";
4
4
  import { type AnyOption, declarationIssues, type ListItem, type NoDefaultReason, optionIssue, type OptionScale, type ValueOption } from "./strategy-options.ts";
5
5
  import type { ParamValue, StrategySpace } from "./strategy-space.ts";
6
6
 
7
- /** The schema of a strategy catalog. A new field is a new version of the schema. */
8
- export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/1";
7
+ /** The newest schema of a strategy catalog. A new field is a new version of the schema. */
8
+ export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/2";
9
+
10
+ /** The schemas that `parseStrategyCatalog` reads, oldest first. Schema 2 adds the field `output` of an entry. */
11
+ export const STRATEGY_CATALOG_SCHEMAS: readonly ["strategy-catalog/1", "strategy-catalog/2"] = ["strategy-catalog/1", STRATEGY_CATALOG_SCHEMA];
12
+
13
+ /** The name of one schema of a strategy catalog. */
14
+ export type StrategyCatalogSchema = (typeof STRATEGY_CATALOG_SCHEMAS)[number];
9
15
 
10
16
  /**
11
17
  * 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.
@@ -26,6 +32,60 @@ export interface CatalogLimit {
26
32
  /** The kind of a strategy: it places on its own, it wraps other strategies, or it is for one shape of item. */
27
33
  export type StrategyKind = "single" | "composite" | "shape";
28
34
 
35
+ /** The output properties that tell if the numbers of a result are whole: the positions and the sizes. The parser examines the class of these properties. */
36
+ export const OUTPUT_GRID_PROPERTIES: readonly string[] = ["position-grid", "size-grid"];
37
+
38
+ /** The class of a grid property of an output. */
39
+ export type OutputGridClass = "whole" | "near-whole" | "fractional" | "untested";
40
+
41
+ /** The largest distance from a whole number for a near-whole value. A value at a larger distance is fractional. */
42
+ export const OUTPUT_NEAR_WHOLE = 1e-9;
43
+
44
+ /** The fewest packed inputs for the class `whole` or `near-whole`. A fraction needs no such count, because one counterexample is a proof. */
45
+ export const OUTPUT_CLASS_MIN_INPUTS = 30;
46
+
47
+ /** What one read of an output covers. The row states no promise beyond this evidence. */
48
+ export interface OutputEvidence {
49
+ /** The count of inputs that the strategy packed in this read. */
50
+ readonly inputs: number;
51
+ /** The count of inputs with a fractional value of the property. A grid property must have this field. */
52
+ readonly fractionalInputs?: number;
53
+ /** The count of inputs with a near-whole value and no fractional value of the property. A grid property must have this field. */
54
+ readonly nearWholeInputs?: number;
55
+ /** The input family or the study of the read. */
56
+ readonly source: string;
57
+ /** The name of the options of the read, for example `default`. */
58
+ readonly optionSet: string;
59
+ /** The version of the catalog that the read used. */
60
+ readonly catalogVersion: string;
61
+ }
62
+
63
+ /** One property of the output of a strategy, as a read found it. An entry has one row for each pair of `property` and `optionSet`. */
64
+ export interface OutputRow {
65
+ /** The property, for example `position-grid`. */
66
+ readonly property: string;
67
+ /** The class of the property. For a grid property, `outputGridClass` gives the only class that the evidence permits. */
68
+ readonly class: string;
69
+ readonly evidence: OutputEvidence;
70
+ }
71
+
72
+ /** The counts that decide the class of a grid property. */
73
+ export interface OutputGridCounts {
74
+ readonly inputs: number;
75
+ readonly fractionalInputs: number;
76
+ readonly nearWholeInputs: number;
77
+ }
78
+
79
+ /**
80
+ * This function gives the class of a grid property from its counts. One fractional input gives `fractional` at any count.
81
+ * With no fraction, fewer than `OUTPUT_CLASS_MIN_INPUTS` inputs give `untested`. Each other read gives `near-whole` or `whole`.
82
+ */
83
+ export function outputGridClass(counts: OutputGridCounts): OutputGridClass {
84
+ if (counts.fractionalInputs > 0) return "fractional";
85
+ if (counts.inputs < OUTPUT_CLASS_MIN_INPUTS) return "untested";
86
+ return counts.nearWholeInputs > 0 ? "near-whole" : "whole";
87
+ }
88
+
29
89
  /** One strategy of a catalog. */
30
90
  export interface CatalogEntry {
31
91
  /** The key is unique in the catalog: `<step>/<id>` with a step, else `id`. */
@@ -51,6 +111,8 @@ export interface CatalogEntry {
51
111
  readonly optIn: boolean;
52
112
  /** The value `true` tells that the strategy is a baseline of a bench. It has `optIn` true, and a chooser does not offer it. */
53
113
  readonly baseline?: true;
114
+ /** The reads of the output of the strategy. A file with this field has the schema 2. */
115
+ readonly output?: readonly OutputRow[];
54
116
  /** The declarations of the options, in the order of a form. */
55
117
  readonly options: Readonly<Record<string, AnyOption>>;
56
118
  }
@@ -64,7 +126,7 @@ export interface StrategyCatalogSource {
64
126
 
65
127
  /** A catalog document: the form that `writeStrategyCatalog` writes and `parseStrategyCatalog` reads. */
66
128
  export interface StrategyCatalog extends StrategyCatalogSource {
67
- readonly schema: typeof STRATEGY_CATALOG_SCHEMA;
129
+ readonly schema: StrategyCatalogSchema;
68
130
  /** The npm version of the engine. */
69
131
  readonly version: string;
70
132
  }
@@ -148,13 +210,15 @@ const STRATEGY_KINDS: readonly string[] = ["single", "composite", "shape"];
148
210
  const NO_DEFAULT_REASONS: readonly NoDefaultReason[] = ["unset", "required", "derived", "function"];
149
211
  const SCALES: readonly OptionScale[] = ["linear", "log"];
150
212
  const TOP_FIELDS: readonly string[] = ["schema", "engine", "version", "strategies"];
151
- const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "options"];
213
+ const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "output", "options"];
152
214
  const COMMON_FIELDS: readonly string[] = ["type", "describe", "default", "noDefault", "when"];
153
215
  const NUMBER_FIELDS: readonly string[] = [...COMMON_FIELDS, "min", "max", "step", "scale", "special", "marks", "values"];
154
216
  const ENUM_FIELDS: readonly string[] = [...COMMON_FIELDS, "values", "custom"];
155
217
  const STRATEGY_FIELDS: readonly string[] = [...COMMON_FIELDS, "step", "kinds", "optionsKey", "inlineOptions", "optIn", "needs"];
156
218
  const MEMBER_FIELDS: readonly string[] = ["strategy", "options", "id"];
157
219
  const LIST_FIELDS: readonly string[] = [...COMMON_FIELDS, "of", "min", "max"];
220
+ const ROW_FIELDS: readonly string[] = ["property", "class", "evidence"];
221
+ const EVIDENCE_FIELDS: readonly string[] = ["inputs", "fractionalInputs", "nearWholeInputs", "source", "optionSet", "catalogVersion"];
158
222
  /** The fields of a declaration, in the order of the file. */
159
223
  const OPTION_ORDER: readonly string[] = ["type", "describe", "min", "max", "step", "scale", "special", "marks", "values", "custom", "kinds", "optionsKey", "inlineOptions", "optIn", "needs", "of", "default", "noDefault", "when"];
160
224
 
@@ -394,8 +458,51 @@ function checkLimits(at: string, limits: unknown, faults: string[]): void {
394
458
  }
395
459
  }
396
460
 
461
+ /** This function adds the faults of the evidence of one output row. */
462
+ function checkEvidence(at: string, property: unknown, rowClass: unknown, raw: unknown, faults: string[]): void {
463
+ if (!isFields(raw)) {
464
+ faults.push(`${at}: "evidence" is not an object.`);
465
+ return;
466
+ }
467
+ refuseUnknown(`${at}: the evidence`, raw, EVIDENCE_FIELDS, faults);
468
+ for (const f of ["source", "optionSet", "catalogVersion"]) if (!isText(raw[f])) faults.push(`${at}: the evidence field "${f}" is not a text.`);
469
+ const count = (v: unknown): v is number => Number.isInteger(v) && (v as number) >= 0;
470
+ if (!count(raw["inputs"])) faults.push(`${at}: the evidence field "inputs" is not a count.`);
471
+ const grid = OUTPUT_GRID_PROPERTIES.includes(property as string);
472
+ for (const f of ["fractionalInputs", "nearWholeInputs"]) if (grid ? !count(raw[f]) : raw[f] !== undefined && !count(raw[f])) faults.push(`${at}: the evidence field "${f}" is not a count.`);
473
+ const [inputs, fractionalInputs, nearWholeInputs] = [raw["inputs"], raw["fractionalInputs"], raw["nearWholeInputs"]];
474
+ if (!grid || !count(inputs) || !count(fractionalInputs) || !count(nearWholeInputs)) return;
475
+ if (fractionalInputs + nearWholeInputs > inputs) faults.push(`${at}: the fractional and near-whole counts are more than the inputs.`);
476
+ const expected = outputGridClass({ inputs, fractionalInputs, nearWholeInputs });
477
+ if (rowClass !== expected) faults.push(`${at}: the evidence gives the class "${expected}".`);
478
+ }
479
+
480
+ /** This function adds the faults of the field `output` of one entry. */
481
+ function checkOutput(at: string, raw: unknown, schema: unknown, faults: string[]): void {
482
+ if (schema === STRATEGY_CATALOG_SCHEMAS[0]) faults.push(`${at}: the field "output" needs the schema ${STRATEGY_CATALOG_SCHEMA}.`);
483
+ if (!Array.isArray(raw) || raw.length === 0) {
484
+ faults.push(`${at}: "output" is not a list with rows.`);
485
+ return;
486
+ }
487
+ const seen = new Set<string>();
488
+ (raw as readonly unknown[]).forEach((row, i) => {
489
+ const place = `${at}: the output row ${i}`;
490
+ if (!isFields(row)) {
491
+ faults.push(`${place} is not an object.`);
492
+ return;
493
+ }
494
+ refuseUnknown(place, row, ROW_FIELDS, faults);
495
+ for (const f of ["property", "class"]) if (!isText(row[f])) faults.push(`${place}: "${f}" is not a text.`);
496
+ checkEvidence(place, row["property"], row["class"], row["evidence"], faults);
497
+ const optionSet = isFields(row["evidence"]) ? row["evidence"]["optionSet"] : undefined;
498
+ const name = JSON.stringify([row["property"], optionSet]);
499
+ if (seen.has(name)) faults.push(`${place}: the property and the option set are not unique.`);
500
+ seen.add(name);
501
+ });
502
+ }
503
+
397
504
  /** This function restores one entry of a file. */
398
- function readEntry(at: string, raw: unknown, faults: string[]): CatalogEntry | undefined {
505
+ function readEntry(at: string, raw: unknown, schema: unknown, faults: string[]): CatalogEntry | undefined {
399
506
  if (!isFields(raw)) {
400
507
  faults.push(`${at} is not an object.`);
401
508
  return undefined;
@@ -411,6 +518,7 @@ function readEntry(at: string, raw: unknown, faults: string[]): CatalogEntry | u
411
518
  if (raw["baseline"] === true && raw["optIn"] !== true) faults.push(`${at}: a baseline has "optIn" true.`);
412
519
  if (!isFields(raw["supports"]) || !Object.values(raw["supports"]).every(isTextList)) faults.push(`${at}: "supports" is not a record of text lists.`);
413
520
  checkLimits(at, raw["limits"], faults);
521
+ if (raw["output"] !== undefined) checkOutput(at, raw["output"], schema, faults);
414
522
  if (isText(raw["id"]) && raw["key"] !== catalogKey(raw["id"], raw["step"] as string | undefined)) faults.push(`${at}: the key does not follow from "step" and "id".`);
415
523
  if (!isFields(raw["options"])) {
416
524
  faults.push(`${at}: "options" is not an object.`);
@@ -443,6 +551,7 @@ function readEntry(at: string, raw: unknown, faults: string[]): CatalogEntry | u
443
551
  ...(determinismNote === undefined ? {} : { determinismNote }),
444
552
  optIn: raw["optIn"] as boolean,
445
553
  ...(raw["baseline"] === true ? { baseline: true as const } : {}),
554
+ ...(raw["output"] === undefined ? {} : { output: raw["output"] as readonly OutputRow[] }),
446
555
  options,
447
556
  };
448
557
  }
@@ -512,20 +621,21 @@ function checkReferences(entries: readonly CatalogEntry[], faults: string[]): vo
512
621
  }
513
622
 
514
623
  /**
515
- * This function reads a catalog from parsed JSON. It refuses each unknown field and each other schema.
624
+ * This function reads a catalog from parsed JSON, in each schema of `STRATEGY_CATALOG_SCHEMAS`. It refuses each unknown field and each other schema.
516
625
  * It gives the catalog with its `Infinity` values restored, or the list of all faults.
517
626
  */
518
627
  export function parseStrategyCatalog(value: unknown): StrategyCatalogParse {
519
628
  const faults: string[] = [];
520
629
  if (!isFields(value)) return { ok: false, faults: ["The catalog is not an object."] };
521
630
  refuseUnknown("The catalog", value, TOP_FIELDS, faults);
522
- if (value["schema"] !== STRATEGY_CATALOG_SCHEMA) faults.push(`The schema is not ${STRATEGY_CATALOG_SCHEMA}.`);
631
+ const schema = value["schema"];
632
+ if (!(STRATEGY_CATALOG_SCHEMAS as readonly unknown[]).includes(schema)) faults.push(`The schema is not one of ${STRATEGY_CATALOG_SCHEMAS.join(", ")}.`);
523
633
  if (!isText(value["engine"])) faults.push(`"engine" is not a text.`);
524
634
  if (!isText(value["version"])) faults.push(`"version" is not a text.`);
525
635
  if (!Array.isArray(value["strategies"])) return { ok: false, faults: [...faults, `"strategies" is not a list.`] };
526
636
  const entries: CatalogEntry[] = [];
527
637
  (value["strategies"] as readonly unknown[]).forEach((raw, i) => {
528
- const entry = readEntry(`The strategy ${isFields(raw) && isText(raw["key"]) ? raw["key"] : i}`, raw, faults);
638
+ const entry = readEntry(`The strategy ${isFields(raw) && isText(raw["key"]) ? raw["key"] : i}`, raw, schema, faults);
529
639
  if (entry !== undefined) entries.push(entry);
530
640
  });
531
641
  for (let i = 1; i < entries.length; i++) {
@@ -536,7 +646,7 @@ export function parseStrategyCatalog(value: unknown): StrategyCatalogParse {
536
646
  // A bad entry is not in the list, so each reference to it would give a false fault.
537
647
  if (faults.length === 0) checkReferences(entries, faults);
538
648
  if (faults.length > 0) return { ok: false, faults };
539
- return { ok: true, catalog: { schema: STRATEGY_CATALOG_SCHEMA, engine: value["engine"] as string, version: value["version"] as string, strategies: entries } };
649
+ return { ok: true, catalog: { schema: schema as StrategyCatalogSchema, engine: value["engine"] as string, version: value["version"] as string, strategies: entries } };
540
650
  }
541
651
 
542
652
  /** 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. */
@@ -582,6 +692,23 @@ function writeOption(option: AnyOption | ListItem): Fields {
582
692
  return out;
583
693
  }
584
694
 
695
+ /** This function gives the file form of one output row, with the fields in the order of the file. */
696
+ function writeRow(row: OutputRow): unknown {
697
+ const e = row.evidence;
698
+ return {
699
+ property: row.property,
700
+ class: row.class,
701
+ evidence: {
702
+ inputs: e.inputs,
703
+ ...(e.fractionalInputs === undefined ? {} : { fractionalInputs: e.fractionalInputs }),
704
+ ...(e.nearWholeInputs === undefined ? {} : { nearWholeInputs: e.nearWholeInputs }),
705
+ source: e.source,
706
+ optionSet: e.optionSet,
707
+ catalogVersion: e.catalogVersion,
708
+ },
709
+ };
710
+ }
711
+
585
712
  /** This function gives the file form of an entry, with its fields in the order of the file. */
586
713
  function writeEntry(e: CatalogEntry): Fields {
587
714
  const options = Object.fromEntries(Object.entries(e.options).map(([key, o]) => [key, writeOption(o)]));
@@ -598,6 +725,7 @@ function writeEntry(e: CatalogEntry): Fields {
598
725
  ...(e.determinismNote === undefined ? {} : { determinismNote: e.determinismNote }),
599
726
  optIn: e.optIn,
600
727
  ...(e.baseline === true ? { baseline: true } : {}),
728
+ ...(e.output === undefined ? {} : { output: e.output.map(writeRow) }),
601
729
  options,
602
730
  };
603
731
  }
@@ -613,11 +741,13 @@ function unsafeValues(v: unknown, at: string): string[] {
613
741
 
614
742
  /**
615
743
  * This function gives the text of the catalog file, sorted by key. The same source and version give the same bytes.
744
+ * The file has the oldest schema that holds it, so a catalog with no `output` stays valid for a reader of the schema 1.
616
745
  * The caller gives the version from `package.json`. The function throws an error if the file breaks a rule of the format.
617
746
  */
618
747
  export function writeStrategyCatalog(source: StrategyCatalogSource, version: string): string {
619
748
  const strategies = [...source.strategies].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)).map(writeEntry);
620
- const doc = { schema: STRATEGY_CATALOG_SCHEMA, engine: source.engine, version, strategies };
749
+ const schema = source.strategies.some((e) => e.output !== undefined) ? STRATEGY_CATALOG_SCHEMA : STRATEGY_CATALOG_SCHEMAS[0];
750
+ const doc = { schema, engine: source.engine, version, strategies };
621
751
  const unsafe = unsafeValues(doc, "catalog");
622
752
  if (unsafe.length > 0) throw new Error(`The catalog of ${source.engine} has values that JSON cannot hold: ${unsafe.join(" ")}`);
623
753
  const text = `${JSON.stringify(doc, null, 2)}\n`;