@milaboratories/pl-model-middle-layer 1.32.2 → 1.33.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.
Files changed (87) hide show
  1. package/dist/folders/commit.cjs +79 -0
  2. package/dist/folders/commit.cjs.map +1 -0
  3. package/dist/folders/commit.d.ts +82 -0
  4. package/dist/folders/commit.d.ts.map +1 -0
  5. package/dist/folders/commit.js +78 -0
  6. package/dist/folders/commit.js.map +1 -0
  7. package/dist/folders/decode.cjs +79 -0
  8. package/dist/folders/decode.cjs.map +1 -0
  9. package/dist/folders/decode.d.ts +57 -0
  10. package/dist/folders/decode.d.ts.map +1 -0
  11. package/dist/folders/decode.js +77 -0
  12. package/dist/folders/decode.js.map +1 -0
  13. package/dist/folders/document.cjs +49 -0
  14. package/dist/folders/document.cjs.map +1 -0
  15. package/dist/folders/document.d.ts +56 -0
  16. package/dist/folders/document.d.ts.map +1 -0
  17. package/dist/folders/document.js +45 -0
  18. package/dist/folders/document.js.map +1 -0
  19. package/dist/folders/index.cjs +37 -0
  20. package/dist/folders/index.d.ts +10 -0
  21. package/dist/folders/index.js +10 -0
  22. package/dist/folders/inheritance.cjs +23 -0
  23. package/dist/folders/inheritance.cjs.map +1 -0
  24. package/dist/folders/inheritance.d.ts +19 -0
  25. package/dist/folders/inheritance.d.ts.map +1 -0
  26. package/dist/folders/inheritance.js +23 -0
  27. package/dist/folders/inheritance.js.map +1 -0
  28. package/dist/folders/invariants.cjs +115 -0
  29. package/dist/folders/invariants.cjs.map +1 -0
  30. package/dist/folders/invariants.d.ts +48 -0
  31. package/dist/folders/invariants.d.ts.map +1 -0
  32. package/dist/folders/invariants.js +114 -0
  33. package/dist/folders/invariants.js.map +1 -0
  34. package/dist/folders/naming.cjs +53 -0
  35. package/dist/folders/naming.cjs.map +1 -0
  36. package/dist/folders/naming.d.ts +31 -0
  37. package/dist/folders/naming.d.ts.map +1 -0
  38. package/dist/folders/naming.js +51 -0
  39. package/dist/folders/naming.js.map +1 -0
  40. package/dist/folders/planner.cjs +187 -0
  41. package/dist/folders/planner.cjs.map +1 -0
  42. package/dist/folders/planner.d.ts +100 -0
  43. package/dist/folders/planner.d.ts.map +1 -0
  44. package/dist/folders/planner.js +185 -0
  45. package/dist/folders/planner.js.map +1 -0
  46. package/dist/folders/removal.cjs +47 -0
  47. package/dist/folders/removal.cjs.map +1 -0
  48. package/dist/folders/removal.d.ts +42 -0
  49. package/dist/folders/removal.d.ts.map +1 -0
  50. package/dist/folders/removal.js +45 -0
  51. package/dist/folders/removal.js.map +1 -0
  52. package/dist/folders/view.cjs +210 -0
  53. package/dist/folders/view.cjs.map +1 -0
  54. package/dist/folders/view.d.ts +93 -0
  55. package/dist/folders/view.d.ts.map +1 -0
  56. package/dist/folders/view.js +205 -0
  57. package/dist/folders/view.js.map +1 -0
  58. package/dist/index.cjs +43 -2
  59. package/dist/index.d.ts +12 -2
  60. package/dist/index.js +12 -1
  61. package/dist/project.cjs +23 -0
  62. package/dist/project.cjs.map +1 -0
  63. package/dist/project.d.ts +13 -0
  64. package/dist/project.d.ts.map +1 -1
  65. package/dist/project.js +22 -0
  66. package/dist/project.js.map +1 -0
  67. package/package.json +7 -4
  68. package/src/folders/commit.ts +133 -0
  69. package/src/folders/decode.test.ts +128 -0
  70. package/src/folders/decode.ts +142 -0
  71. package/src/folders/document.ts +96 -0
  72. package/src/folders/index.ts +9 -0
  73. package/src/folders/inheritance.test.ts +86 -0
  74. package/src/folders/inheritance.ts +32 -0
  75. package/src/folders/invariants.test.ts +157 -0
  76. package/src/folders/invariants.ts +155 -0
  77. package/src/folders/naming.test.ts +62 -0
  78. package/src/folders/naming.ts +58 -0
  79. package/src/folders/planner.test.ts +436 -0
  80. package/src/folders/planner.ts +276 -0
  81. package/src/folders/removal.test.ts +142 -0
  82. package/src/folders/removal.ts +77 -0
  83. package/src/folders/test_utils.ts +86 -0
  84. package/src/folders/view.test.ts +422 -0
  85. package/src/folders/view.ts +324 -0
  86. package/src/index.ts +1 -0
  87. package/src/project.ts +21 -0
@@ -0,0 +1,142 @@
1
+ import { FOLDERS_SCHEMA_VERSION, FoldersDocument, emptyFoldersDocument } from "./document";
2
+
3
+ /** Why a stored document could not be read as it stands. */
4
+ export type FoldersDocumentProblem =
5
+ | {
6
+ readonly kind: "newer-schema";
7
+ /** Version found in the document, which is higher than this build understands. */
8
+ readonly documentSchemaVersion: number;
9
+ readonly message: string;
10
+ }
11
+ | {
12
+ readonly kind: "unreadable";
13
+ readonly message: string;
14
+ };
15
+
16
+ /**
17
+ * A stored document as this build sees it.
18
+ *
19
+ * A document written by a newer build, or one that cannot be parsed at all, reads as no folders
20
+ * so that the project list still renders, and turns `writable` off: an old build that both
21
+ * degraded the read and kept writing would silently replace a newer build's tree with its own
22
+ * truncated view of it. Every refusal says why.
23
+ */
24
+ export type FoldersDecoded =
25
+ | {
26
+ readonly document: FoldersDocument;
27
+ readonly writable: true;
28
+ readonly problem?: undefined;
29
+ }
30
+ | {
31
+ readonly document: FoldersDocument;
32
+ /** Every folder write must be refused. */
33
+ readonly writable: false;
34
+ readonly problem: FoldersDocumentProblem;
35
+ };
36
+
37
+ /**
38
+ * What the store holds for the folder document: nothing at all, or a stored value and its bytes
39
+ * when they could be obtained.
40
+ */
41
+ export type FoldersStoredDocument =
42
+ | { readonly present: false }
43
+ | {
44
+ readonly present: true;
45
+ /** The stored JSON; undefined when the value carries no bytes this build can fetch. */
46
+ readonly raw: string | undefined;
47
+ };
48
+
49
+ /**
50
+ * Decode whatever the store holds for the folder document.
51
+ *
52
+ * An absent document is a user with no folders, and is writable. A document that is present but
53
+ * carries no bytes, or empty ones, is not the same thing: it exists and cannot be read here — a
54
+ * newer build keeping the tree in another shape, or a value this build cannot fetch — so it reads
55
+ * as no folders and is **not** writable, because writing an empty tree over one that is merely
56
+ * unreadable from this build destroys it.
57
+ */
58
+ export function decodeStoredFoldersDocument(stored: FoldersStoredDocument): FoldersDecoded {
59
+ if (!stored.present) return readable(emptyFoldersDocument());
60
+ if (stored.raw === undefined || stored.raw === "")
61
+ return unreadable("the folder document is stored in a shape this build cannot read");
62
+ return decodeFoldersDocument(stored.raw);
63
+ }
64
+
65
+ /** Decode the stored JSON of a document that is present. */
66
+ export function decodeFoldersDocument(raw: string): FoldersDecoded {
67
+ let parsed: unknown;
68
+ try {
69
+ parsed = JSON.parse(raw);
70
+ } catch (error: unknown) {
71
+ return unreadable(`the folder document is not valid JSON: ${errorText(error)}`);
72
+ }
73
+
74
+ return decodeFoldersValue(parsed);
75
+ }
76
+
77
+ /** Serialise a document for storage. */
78
+ export function encodeFoldersDocument(document: FoldersDocument): string {
79
+ return JSON.stringify(document);
80
+ }
81
+
82
+ //
83
+ // Internals
84
+ //
85
+
86
+ function decodeFoldersValue(value: unknown): FoldersDecoded {
87
+ if (!isMapping(value)) return unreadable("the folder document is not an object");
88
+
89
+ const version = value.schemaVersion;
90
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1)
91
+ return unreadable("the folder document carries no usable schema version");
92
+
93
+ if (version > FOLDERS_SCHEMA_VERSION)
94
+ return {
95
+ document: emptyFoldersDocument(),
96
+ writable: false,
97
+ problem: {
98
+ kind: "newer-schema",
99
+ documentSchemaVersion: version,
100
+ message:
101
+ `the folder document was written by a newer version of the application ` +
102
+ `(schema ${version}, this build understands ${FOLDERS_SCHEMA_VERSION})`,
103
+ },
104
+ };
105
+
106
+ const result = FoldersDocument.safeParse(value);
107
+ if (!result.success)
108
+ return unreadable(
109
+ `the folder document does not match schema ${FOLDERS_SCHEMA_VERSION}: ` +
110
+ result.error.issues.map(formatIssue).join("; "),
111
+ );
112
+
113
+ return readable(result.data);
114
+ }
115
+
116
+ function readable(document: FoldersDocument): FoldersDecoded {
117
+ return { document, writable: true };
118
+ }
119
+
120
+ function unreadable(message: string): FoldersDecoded {
121
+ return {
122
+ document: emptyFoldersDocument(),
123
+ writable: false,
124
+ problem: { kind: "unreadable", message },
125
+ };
126
+ }
127
+
128
+ function isMapping(value: unknown): value is Record<string, unknown> {
129
+ return typeof value === "object" && value !== null && !Array.isArray(value);
130
+ }
131
+
132
+ function formatIssue(issue: {
133
+ readonly path: readonly PropertyKey[];
134
+ readonly message: string;
135
+ }): string {
136
+ const path = issue.path.map((segment) => String(segment)).join(".");
137
+ return path === "" ? issue.message : `${path}: ${issue.message}`;
138
+ }
139
+
140
+ function errorText(error: unknown): string {
141
+ return error instanceof Error ? error.message : String(error);
142
+ }
@@ -0,0 +1,96 @@
1
+ import type { Branded } from "@milaboratories/pl-model-common";
2
+ import { z } from "zod";
3
+
4
+ /**
5
+ * Schema version this build writes and fully understands.
6
+ *
7
+ * A document carrying a higher version is not readable here, and folder writes are refused rather
8
+ * than allowed to truncate whatever the newer build stored.
9
+ */
10
+ export const FOLDERS_SCHEMA_VERSION = 1;
11
+
12
+ /** Identifier of a folder, unique within one user's folder document. */
13
+ export type FolderId = Branded<string, "FolderId">;
14
+
15
+ /** Brands a string already known to be a folder id, such as one handed back by a caller. */
16
+ export function asFolderId(id: string): FolderId {
17
+ return id as FolderId;
18
+ }
19
+
20
+ /**
21
+ * A folder as it is persisted: a name, a reference to the folder that contains it, and what the
22
+ * user wrote about it.
23
+ *
24
+ * A folder nobody described carries no description at all rather than an empty one, so clearing
25
+ * a description leaves the same document a folder that never had one has.
26
+ */
27
+ export interface FolderEntry {
28
+ readonly id: FolderId;
29
+ readonly name: string;
30
+ /** Absent for a top-level folder. */
31
+ readonly parent?: FolderId;
32
+ /** Free text the user wrote about the folder. Absent when there is none. */
33
+ readonly description?: string;
34
+ }
35
+
36
+ export const FolderEntry: z.ZodType<FolderEntry, z.ZodTypeDef, unknown> = z
37
+ .object({
38
+ id: folderId(),
39
+ name: z.string().min(1),
40
+ parent: folderId().optional(),
41
+ description: z.string().optional(),
42
+ })
43
+ .strict();
44
+
45
+ /**
46
+ * The whole folder tree of one user, as one persisted document.
47
+ *
48
+ * Projects and templates live in the same tree, so one folder holds both, and each has its own
49
+ * assignment map. They are separate maps rather than one because the two ids are looked up in
50
+ * two different lists: merged, an id present in neither list could not be told apart from a
51
+ * project that was deleted, and the dead-entry pruning a read performs would have nothing to go
52
+ * on.
53
+ *
54
+ * Each map points from the item to the folder holding it, not the other way round: an item lives
55
+ * in at most one folder, so one entry per item can never contradict itself, and an item the map
56
+ * does not mention needs no entry at all — it is at the top level.
57
+ */
58
+ export interface FoldersDocument {
59
+ readonly schemaVersion: typeof FOLDERS_SCHEMA_VERSION;
60
+ readonly folders: readonly FolderEntry[];
61
+ /** Project id to the folder holding it. Projects at the top level are absent. */
62
+ readonly assignments: Readonly<Record<string, FolderId>>;
63
+ /** Template id to the folder holding it. Templates at the top level are absent. */
64
+ readonly templateAssignments: Readonly<Record<string, FolderId>>;
65
+ }
66
+
67
+ export const FoldersDocument: z.ZodType<FoldersDocument, z.ZodTypeDef, unknown> = z
68
+ .object({
69
+ schemaVersion: z.literal(FOLDERS_SCHEMA_VERSION),
70
+ folders: z.array(FolderEntry),
71
+ assignments: z.record(z.string().min(1), folderId()),
72
+ templateAssignments: z.record(z.string().min(1), folderId()),
73
+ })
74
+ .strict();
75
+
76
+ /** The document of a user who has never made a folder. */
77
+ export function emptyFoldersDocument(): FoldersDocument {
78
+ return {
79
+ schemaVersion: FOLDERS_SCHEMA_VERSION,
80
+ folders: [],
81
+ assignments: {},
82
+ templateAssignments: {},
83
+ };
84
+ }
85
+
86
+ //
87
+ // Internals
88
+ //
89
+
90
+ /**
91
+ * Folder ids are plain strings on the wire; the brand exists so that a project id and a folder id
92
+ * cannot be swapped by accident in the code consuming them.
93
+ */
94
+ function folderId() {
95
+ return z.string().min(1).transform(asFolderId);
96
+ }
@@ -0,0 +1,9 @@
1
+ export * from "./document";
2
+ export * from "./decode";
3
+ export * from "./view";
4
+ export * from "./invariants";
5
+ export * from "./naming";
6
+ export * from "./planner";
7
+ export * from "./commit";
8
+ export * from "./removal";
9
+ export * from "./inheritance";
@@ -0,0 +1,86 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import { inheritedFolder } from "./inheritance";
3
+ import { fid, pid, project, template, view } from "./test_utils";
4
+
5
+ describe("what a new item inherits from the project it was made from", () => {
6
+ test("a copy lands in the folder holding its source", () => {
7
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run", folder: "a" }]);
8
+
9
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBe(fid("a"));
10
+ });
11
+
12
+ test("a template taken from a project lands in that project's folder", () => {
13
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run", folder: "a" }]);
14
+
15
+ expect(inheritedFolder(tree, pid("p1"), template("t1"), "Run (Copy)")).toBe(fid("a"));
16
+ });
17
+
18
+ test("a template is held to the same names as everything else in that folder", () => {
19
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run", folder: "a" }]);
20
+
21
+ // "Run" is taken in that folder by the source project itself.
22
+ expect(inheritedFolder(tree, pid("p1"), template("t1"), "Run")).toBeUndefined();
23
+ });
24
+
25
+ test("a source at the top level leaves the new item at the top level", () => {
26
+ const tree = view([{ id: "a", name: "Samples" }], [{ id: "p1", name: "Run" }]);
27
+
28
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBeUndefined();
29
+ });
30
+
31
+ test("a source that is no longer in the tree places nothing", () => {
32
+ const tree = view([{ id: "a", name: "Samples" }], []);
33
+
34
+ expect(inheritedFolder(tree, pid("ghost"), project("p2"), "Run (Copy)")).toBeUndefined();
35
+ });
36
+
37
+ test("a name already taken in that folder leaves the copy at the top level", () => {
38
+ const tree = view(
39
+ [{ id: "a", name: "Samples" }],
40
+ [
41
+ { id: "p1", name: "Run", folder: "a" },
42
+ { id: "p2", name: "Run (Copy)", folder: "a" },
43
+ ],
44
+ );
45
+
46
+ expect(inheritedFolder(tree, pid("p1"), project("p3"), "Run (Copy)")).toBeUndefined();
47
+ });
48
+
49
+ test("a child folder's name is taken too: folders, projects and templates share the namespace", () => {
50
+ const tree = view(
51
+ [
52
+ { id: "a", name: "Samples" },
53
+ { id: "b", name: "Run (Copy)", parent: "a" },
54
+ ],
55
+ [{ id: "p1", name: "Run", folder: "a" }],
56
+ );
57
+
58
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBeUndefined();
59
+ });
60
+
61
+ test("a name taken elsewhere in the tree does not block the placement", () => {
62
+ // Uniqueness is per parent, never global: the copy is placed although another project at the
63
+ // top level already carries the name it is being given.
64
+ const tree = view(
65
+ [{ id: "a", name: "Samples" }],
66
+ [
67
+ { id: "p1", name: "Run", folder: "a" },
68
+ { id: "p2", name: "Run (Copy)" },
69
+ ],
70
+ );
71
+
72
+ expect(inheritedFolder(tree, pid("p1"), project("p2"), "Run (Copy)")).toBe(fid("a"));
73
+ });
74
+
75
+ test("the comparison ignores case, exactly as the naming rule does", () => {
76
+ const tree = view(
77
+ [{ id: "a", name: "Samples" }],
78
+ [
79
+ { id: "p1", name: "Run", folder: "a" },
80
+ { id: "p2", name: "RUN (COPY)", folder: "a" },
81
+ ],
82
+ );
83
+
84
+ expect(inheritedFolder(tree, pid("p1"), project("p3"), "Run (Copy)")).toBeUndefined();
85
+ });
86
+ });
@@ -0,0 +1,32 @@
1
+ import type { ProjectId } from "@milaboratories/pl-model-common";
2
+ import type { FolderId } from "./document";
3
+ import { foldersNameTaken } from "./naming";
4
+ import type { FoldersLeafItem } from "./planner";
5
+ import type { FoldersView } from "./view";
6
+ import { foldersSiblingNames } from "./view";
7
+
8
+ /**
9
+ * The folder a newly created item should land in, given the project it was made from.
10
+ *
11
+ * A copy of a project, and a template taken from one, belong beside their source; landing at the
12
+ * top level reads as the app having lost them. `undefined` means leave it at the top level:
13
+ *
14
+ * - the source is itself at the top level, or is no longer in the tree at all;
15
+ * - the name is already taken where the source sits. The creating caller chose that name, so
16
+ * suffixing it here would disagree with what it reported, and refusing the whole creation over
17
+ * a placement would be the worse trade.
18
+ */
19
+ export function inheritedFolder(
20
+ view: FoldersView,
21
+ source: ProjectId,
22
+ created: FoldersLeafItem,
23
+ name: string,
24
+ ): FolderId | undefined {
25
+ const folder = view.projects.find((candidate) => candidate.id === source)?.folder;
26
+ if (folder === undefined) return undefined;
27
+
28
+ // Scoped to the destination, because the rule is: names are unique within a parent, never
29
+ // globally. The item being created is left out in case the view already lists it.
30
+ const siblings = foldersSiblingNames(view, folder, [created.id]);
31
+ return foldersNameTaken(name, siblings) ? undefined : folder;
32
+ }
@@ -0,0 +1,157 @@
1
+ import { describe, expect, test } from "vitest";
2
+ import type { FoldersDocument } from "./document";
3
+ import { formatFoldersViolation, validateFoldersDocument } from "./invariants";
4
+ import { document, pid, tid } from "./test_utils";
5
+ import type { FoldersProjectInput } from "./view";
6
+
7
+ const kinds = (value: FoldersDocument, projects?: FoldersProjectInput[]) =>
8
+ validateFoldersDocument(value, projects).map((violation) => violation.kind);
9
+
10
+ describe("validateFoldersDocument", () => {
11
+ test("a project assigned to a nested folder is valid", () => {
12
+ expect(
13
+ validateFoldersDocument(
14
+ document(
15
+ [
16
+ { id: "a", name: "A" },
17
+ { id: "b", name: "B", parent: "a" },
18
+ { id: "c", name: "C", parent: "b" },
19
+ ],
20
+ { p1: "c" },
21
+ ),
22
+ [{ id: pid("p1"), name: "Run" }],
23
+ ),
24
+ ).toEqual([]);
25
+ });
26
+
27
+ test("nesting has no limit: a long chain is a valid document", () => {
28
+ const chain = Array.from({ length: 12 }, (_, index) => ({
29
+ id: `f${index}`,
30
+ name: `F${index}`,
31
+ ...(index === 0 ? {} : { parent: `f${index - 1}` }),
32
+ }));
33
+
34
+ expect(kinds(document(chain))).toEqual([]);
35
+ });
36
+
37
+ test("a cycle is reported for every folder in it", () => {
38
+ expect(
39
+ kinds(
40
+ document([
41
+ { id: "a", name: "A", parent: "b" },
42
+ { id: "b", name: "B", parent: "a" },
43
+ ]),
44
+ ),
45
+ ).toEqual(["cycle", "cycle"]);
46
+ });
47
+
48
+ test("a folder hanging below a cycle is not reported as sitting in it", () => {
49
+ const violations = validateFoldersDocument(
50
+ document([
51
+ { id: "a", name: "A", parent: "b" },
52
+ { id: "b", name: "B", parent: "a" },
53
+ { id: "c", name: "C", parent: "a" },
54
+ ]),
55
+ );
56
+ expect(violations).toEqual([
57
+ { kind: "cycle", folder: "a" },
58
+ { kind: "cycle", folder: "b" },
59
+ ]);
60
+ });
61
+
62
+ test("a folder named with whitespace only is reported", () => {
63
+ expect(kinds(document([{ id: "a", name: " " }]))).toEqual(["empty-folder-name"]);
64
+ });
65
+
66
+ test("a parent that is not there is reported", () => {
67
+ expect(kinds(document([{ id: "a", name: "A", parent: "gone" }]))).toEqual(["missing-parent"]);
68
+ });
69
+
70
+ test("a folder id used twice is reported", () => {
71
+ expect(
72
+ kinds(
73
+ document([
74
+ { id: "a", name: "A" },
75
+ { id: "a", name: "B" },
76
+ ]),
77
+ ),
78
+ ).toEqual(["duplicate-folder-id"]);
79
+ });
80
+
81
+ test("names must be unique within one parent, ignoring case", () => {
82
+ expect(
83
+ kinds(
84
+ document([
85
+ { id: "a", name: "Samples" },
86
+ { id: "b", name: "samples" },
87
+ ]),
88
+ ),
89
+ ).toEqual(["duplicate-name"]);
90
+ });
91
+
92
+ test("the same name under different parents is fine", () => {
93
+ expect(
94
+ kinds(
95
+ document([
96
+ { id: "a", name: "A" },
97
+ { id: "b", name: "B" },
98
+ { id: "a1", name: "Runs", parent: "a" },
99
+ { id: "b1", name: "Runs", parent: "b" },
100
+ ]),
101
+ ),
102
+ ).toEqual([]);
103
+ });
104
+
105
+ test("a folder and a project inside the same parent share one namespace", () => {
106
+ expect(kinds(document([{ id: "a", name: "Runs" }], { p1: "gone-nowhere" }), [])).toEqual([]);
107
+
108
+ expect(kinds(document([{ id: "a", name: "Runs" }]), [{ id: pid("p1"), name: "runs" }])).toEqual(
109
+ ["duplicate-name"],
110
+ );
111
+ });
112
+
113
+ test("a template shares that namespace with folders, projects and other templates", () => {
114
+ const withTemplates = (templates: { id: string; name: string }[]) =>
115
+ validateFoldersDocument(
116
+ document([{ id: "a", name: "Runs" }], { p1: "a" }, { t1: "a", t2: "a" }),
117
+ [{ id: pid("p1"), name: "Pilot" }],
118
+ templates.map((template) => ({ id: tid(template.id), name: template.name })),
119
+ ).map((violation) => violation.kind);
120
+
121
+ expect(withTemplates([{ id: "t1", name: "Snapshot" }])).toEqual([]);
122
+ expect(withTemplates([{ id: "t1", name: "pilot" }])).toEqual(["duplicate-name"]);
123
+ expect(
124
+ withTemplates([
125
+ { id: "t1", name: "Snapshot" },
126
+ { id: "t2", name: "Snapshot" },
127
+ ]),
128
+ ).toEqual(["duplicate-name"]);
129
+ });
130
+
131
+ test("an assignment naming a folder that is not there is reported", () => {
132
+ expect(kinds(document([], { p1: "gone" }), [{ id: pid("p1"), name: "Run" }])).toEqual([
133
+ "unknown-assignment-folder",
134
+ ]);
135
+ });
136
+
137
+ test("an assignment naming a project that is gone is not the document's problem", () => {
138
+ expect(kinds(document([{ id: "a", name: "A" }], { ghost: "gone" }), [])).toEqual([]);
139
+ });
140
+
141
+ test("every violation formats to a line naming what is wrong", () => {
142
+ const violations = validateFoldersDocument(
143
+ document(
144
+ [
145
+ { id: "a", name: "A", parent: "gone" },
146
+ { id: "b", name: "B" },
147
+ { id: "b", name: "B" },
148
+ ],
149
+ { p1: "missing" },
150
+ ),
151
+ [{ id: pid("p1"), name: "Run" }],
152
+ );
153
+
154
+ expect(violations.length).toBeGreaterThan(0);
155
+ for (const violation of violations) expect(formatFoldersViolation(violation)).not.toBe("");
156
+ });
157
+ });
@@ -0,0 +1,155 @@
1
+ import type { ProjectId, TemplateId } from "@milaboratories/pl-model-common";
2
+ import { asProjectId, asTemplateId } from "@milaboratories/pl-model-common";
3
+ import type { FoldersDocument, FolderId } from "./document";
4
+ import { foldersNameBlank, foldersNameTaken } from "./naming";
5
+ import type { FoldersProjectInput, FoldersTemplateInput } from "./view";
6
+
7
+ /** One way a document breaks the rules the write path enforces. */
8
+ export type FoldersViolation =
9
+ | { readonly kind: "duplicate-folder-id"; readonly folder: FolderId }
10
+ | { readonly kind: "empty-folder-name"; readonly folder: FolderId }
11
+ | {
12
+ readonly kind: "missing-parent";
13
+ readonly folder: FolderId;
14
+ readonly parent: FolderId;
15
+ }
16
+ | { readonly kind: "cycle"; readonly folder: FolderId }
17
+ | {
18
+ readonly kind: "duplicate-name";
19
+ readonly parent?: FolderId;
20
+ readonly name: string;
21
+ }
22
+ | {
23
+ readonly kind: "unknown-assignment-folder";
24
+ readonly project: ProjectId;
25
+ readonly folder: FolderId;
26
+ }
27
+ | {
28
+ readonly kind: "unknown-template-assignment-folder";
29
+ readonly template: TemplateId;
30
+ readonly folder: FolderId;
31
+ };
32
+
33
+ /**
34
+ * Everything wrong with a document, in one pass.
35
+ *
36
+ * This is the write path's check: a read heals the same problems instead of reporting them, but a
37
+ * write that would persist any of them is refused, because a document no reader can render as
38
+ * stored is a document someone has to repair by hand.
39
+ *
40
+ * Project and template names are optional. Without them the namespace folders, projects and
41
+ * templates share can only be checked between folders, so a write path that can supply them
42
+ * should. The template list also tells an assignment for a template that is gone — which a read
43
+ * prunes — from one naming a folder that does not exist, which is a broken document.
44
+ */
45
+ export function validateFoldersDocument(
46
+ document: FoldersDocument,
47
+ projects?: readonly FoldersProjectInput[],
48
+ templates?: readonly FoldersTemplateInput[],
49
+ ): readonly FoldersViolation[] {
50
+ const violations: FoldersViolation[] = [];
51
+
52
+ const byId = new Map<FolderId, { name: string; parent?: FolderId }>();
53
+ for (const folder of document.folders) {
54
+ if (byId.has(folder.id)) {
55
+ violations.push({ kind: "duplicate-folder-id", folder: folder.id });
56
+ continue;
57
+ }
58
+ if (foldersNameBlank(folder.name))
59
+ violations.push({ kind: "empty-folder-name", folder: folder.id });
60
+ byId.set(folder.id, { name: folder.name, parent: folder.parent });
61
+ }
62
+
63
+ for (const [id, folder] of byId) {
64
+ if (folder.parent !== undefined && !byId.has(folder.parent)) {
65
+ violations.push({ kind: "missing-parent", folder: id, parent: folder.parent });
66
+ continue;
67
+ }
68
+
69
+ if (onCycle(id, byId)) violations.push({ kind: "cycle", folder: id });
70
+ }
71
+
72
+ // The comparison is the naming rule's, not a second one written here: a document is invalid in
73
+ // exactly the cases the rule would have refused, or the write path and the checker would drift.
74
+ const namesByParent = new Map<string, string[]>();
75
+ const claim = (parent: FolderId | undefined, name: string) => {
76
+ const key = parent ?? "";
77
+ const names = namesByParent.get(key) ?? [];
78
+ namesByParent.set(key, names);
79
+ if (foldersNameTaken(name, names)) violations.push({ kind: "duplicate-name", parent, name });
80
+ names.push(name);
81
+ };
82
+
83
+ for (const folder of byId.values()) claim(folder.parent, folder.name);
84
+
85
+ const knownProjects = new Set<string>((projects ?? []).map((project) => project.id));
86
+ for (const project of projects ?? []) {
87
+ const parent = document.assignments[project.id];
88
+ if (parent === undefined || byId.has(parent)) claim(parent, project.name);
89
+ }
90
+
91
+ for (const [project, folder] of Object.entries(document.assignments))
92
+ if (!byId.has(folder) && (projects === undefined || knownProjects.has(project)))
93
+ violations.push({
94
+ kind: "unknown-assignment-folder",
95
+ project: asProjectId(project),
96
+ folder,
97
+ });
98
+
99
+ for (const template of templates ?? []) {
100
+ const parent = document.templateAssignments[template.id];
101
+ if (parent === undefined || byId.has(parent)) claim(parent, template.name);
102
+ }
103
+
104
+ const knownTemplates = new Set<string>((templates ?? []).map((template) => template.id));
105
+ for (const [template, folder] of Object.entries(document.templateAssignments))
106
+ if (!byId.has(folder) && (templates === undefined || knownTemplates.has(template)))
107
+ violations.push({
108
+ kind: "unknown-template-assignment-folder",
109
+ template: asTemplateId(template),
110
+ folder,
111
+ });
112
+
113
+ return violations;
114
+ }
115
+
116
+ /** A one-line description of a violation, for an error a user or a log will read. */
117
+ export function formatFoldersViolation(violation: FoldersViolation): string {
118
+ switch (violation.kind) {
119
+ case "duplicate-folder-id":
120
+ return `folder id ${violation.folder} appears more than once`;
121
+ case "empty-folder-name":
122
+ return `folder ${violation.folder} has an empty name`;
123
+ case "missing-parent":
124
+ return `folder ${violation.folder} names a parent that does not exist (${violation.parent})`;
125
+ case "cycle":
126
+ return `folder ${violation.folder} sits in a cycle of parents`;
127
+ case "duplicate-name":
128
+ return violation.parent === undefined
129
+ ? `the name "${violation.name}" is used more than once at the top level`
130
+ : `the name "${violation.name}" is used more than once inside folder ${violation.parent}`;
131
+ case "unknown-assignment-folder":
132
+ return `project ${violation.project} is assigned to a folder that does not exist (${violation.folder})`;
133
+ case "unknown-template-assignment-folder":
134
+ return `template ${violation.template} is assigned to a folder that does not exist (${violation.folder})`;
135
+ }
136
+ }
137
+
138
+ //
139
+ // Internals
140
+ //
141
+
142
+ /**
143
+ * True when following parents from this folder leads back to it. A folder that merely hangs below
144
+ * a cycle is not on it.
145
+ */
146
+ function onCycle(id: FolderId, byId: ReadonlyMap<FolderId, { parent?: FolderId }>): boolean {
147
+ const seen = new Set<FolderId>();
148
+ let current = byId.get(id)?.parent;
149
+ while (current !== undefined && !seen.has(current)) {
150
+ if (current === id) return true;
151
+ seen.add(current);
152
+ current = byId.get(current)?.parent;
153
+ }
154
+ return false;
155
+ }