@timefoldai/viz-cli 0.0.0 → 0.2.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.
@@ -0,0 +1,222 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ existsSync,
4
+ lstatSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ readlinkSync,
8
+ realpathSync,
9
+ writeFileSync,
10
+ } from "node:fs";
11
+ import {
12
+ basename,
13
+ dirname,
14
+ isAbsolute,
15
+ join,
16
+ relative,
17
+ resolve,
18
+ sep,
19
+ } from "node:path";
20
+ import process from "node:process";
21
+ import { isDeepStrictEqual } from "node:util";
22
+
23
+ import openapiTS, { astToString, COMMENT_HEADER } from "openapi-typescript";
24
+
25
+ import { runBin } from "./run-bin.mjs";
26
+
27
+ const SCHEMA_REF = "#/components/schemas/";
28
+
29
+ function schemaName(ref) {
30
+ return ref.startsWith(SCHEMA_REF)
31
+ ? ref.slice(SCHEMA_REF.length)
32
+ : undefined;
33
+ }
34
+
35
+ function referencedSchema(schemas, ref, referrer) {
36
+ const name = schemaName(ref);
37
+ if (name === undefined) return undefined;
38
+ const schema = schemas[name];
39
+ if (schema === undefined) {
40
+ throw new Error(
41
+ `${referrer} references ${ref}, which the spec does not define`,
42
+ );
43
+ }
44
+
45
+ return { name, schema };
46
+ }
47
+
48
+ function listsAsVariant(parent, childName) {
49
+ return (parent.oneOf ?? []).some(
50
+ (variant) => variant.$ref === SCHEMA_REF + childName,
51
+ );
52
+ }
53
+
54
+ function mergeParentInto(child, parent) {
55
+ child.type ??= parent.type;
56
+ child.properties = { ...parent.properties, ...child.properties };
57
+ child.required = [
58
+ ...new Set([...(parent.required ?? []), ...(child.required ?? [])]),
59
+ ];
60
+ }
61
+
62
+ function parentLoops(schemas) {
63
+ return Object.entries(schemas).flatMap(([childName, child]) =>
64
+ (child.allOf ?? []).flatMap((entry) => {
65
+ const parent =
66
+ entry.$ref && referencedSchema(schemas, entry.$ref, childName);
67
+ return parent && listsAsVariant(parent.schema, childName)
68
+ ? [{ childName, child, entry, ...parent }]
69
+ : [];
70
+ }),
71
+ );
72
+ }
73
+
74
+ const PROSE_KEYWORDS = new Set(["description", "externalDocs"]);
75
+
76
+ function propertyShape(property) {
77
+ return Object.fromEntries(
78
+ Object.entries(property).filter(
79
+ ([keyword]) => !PROSE_KEYWORDS.has(keyword),
80
+ ),
81
+ );
82
+ }
83
+
84
+ function assertMergeable({ childName, child, name, schema }) {
85
+ if (schema.allOf !== undefined) {
86
+ throw new Error(
87
+ `${name} is a discriminated parent with its own allOf, which the flattening does not resolve`,
88
+ );
89
+ }
90
+ const discriminator = schema.discriminator?.propertyName;
91
+ for (const [property, parentShape] of Object.entries(
92
+ schema.properties ?? {},
93
+ )) {
94
+ const childShape = child.properties?.[property];
95
+ if (
96
+ property !== discriminator &&
97
+ childShape !== undefined &&
98
+ !isDeepStrictEqual(
99
+ propertyShape(childShape),
100
+ propertyShape(parentShape),
101
+ )
102
+ ) {
103
+ throw new Error(
104
+ `${childName}.${property} differs from ${name}.${property}, so inlining ${name} would drop one of them`,
105
+ );
106
+ }
107
+ }
108
+ }
109
+
110
+ /**
111
+ * Inlines each discriminated parent into the children its `oneOf` lists, in place, so the
112
+ * generated types carry no parent-child cycle. Returns each flattened `{ child, parent }` pair.
113
+ */
114
+ export function flattenDiscriminatedChildren(spec) {
115
+ const loops = parentLoops(spec.components?.schemas ?? {});
116
+ loops.forEach(assertMergeable);
117
+
118
+ for (const { child, entry, schema } of loops) {
119
+ mergeParentInto(child, schema);
120
+ child.allOf = child.allOf.filter((kept) => kept !== entry);
121
+ if (child.allOf.length === 0) delete child.allOf;
122
+ }
123
+
124
+ return loops.map(({ childName, name }) => ({
125
+ child: childName,
126
+ parent: name,
127
+ }));
128
+ }
129
+
130
+ /** Renders a parsed OpenAPI document to the text the `openapi-typescript` CLI writes. */
131
+ export async function renderTypes(spec) {
132
+ return (
133
+ COMMENT_HEADER + astToString(await openapiTS(spec, { silent: true }))
134
+ );
135
+ }
136
+
137
+ async function readSpec(source) {
138
+ const text = /^https?:\/\//.test(source)
139
+ ? await fetchSpec(source)
140
+ : readFileSync(source, "utf8");
141
+ try {
142
+ return JSON.parse(text);
143
+ } catch (error) {
144
+ throw new Error(
145
+ `${source} is not a JSON OpenAPI document: ${error.message}`,
146
+ );
147
+ }
148
+ }
149
+
150
+ async function fetchSpec(url) {
151
+ const response = await fetch(url, {
152
+ headers: { Accept: "application/json" },
153
+ });
154
+ if (!response.ok) {
155
+ throw new Error(
156
+ `${url} answered ${response.status} ${response.statusText}`,
157
+ );
158
+ }
159
+
160
+ return response.text();
161
+ }
162
+
163
+ const USAGE = "usage: viz-codegen <spec url or file> <output .d.ts>";
164
+
165
+ const MAX_SYMLINK_HOPS = 40;
166
+
167
+ function isSymlink(path) {
168
+ return (
169
+ lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() ?? false
170
+ );
171
+ }
172
+
173
+ function realPath(path, hops = 0) {
174
+ const absolute = resolve(path);
175
+ const parent = dirname(absolute);
176
+ if (parent === absolute) return absolute;
177
+ const realParent = realPath(parent, hops);
178
+ if (realParent === null) return null;
179
+ const joined = join(realParent, basename(absolute));
180
+ if (existsSync(joined)) return realpathSync(joined);
181
+ if (!isSymlink(joined)) return joined;
182
+ if (hops === MAX_SYMLINK_HOPS) return null;
183
+
184
+ return realPath(resolve(realParent, readlinkSync(joined)), hops + 1);
185
+ }
186
+
187
+ function isInside(directory, path) {
188
+ const fromDirectory = relative(directory, path);
189
+ return (
190
+ fromDirectory !== "" &&
191
+ fromDirectory !== ".." &&
192
+ !fromDirectory.startsWith(`..${sep}`) &&
193
+ !isAbsolute(fromDirectory)
194
+ );
195
+ }
196
+
197
+ function refuse(reason) {
198
+ console.error(`viz-codegen: FAIL — ${reason}; ${USAGE}`);
199
+ process.exit(1);
200
+ }
201
+
202
+ async function main([source, output]) {
203
+ if (!source || !output) {
204
+ console.error(`viz-codegen: FAIL — ${USAGE}`);
205
+ process.exit(1);
206
+ }
207
+ const target = realPath(output);
208
+ if (target === null) refuse(`${output} is a symlink loop`);
209
+ if (!isInside(realpathSync(process.cwd()), target)) {
210
+ refuse(`${output} is outside the current directory`);
211
+ }
212
+ const spec = await readSpec(source);
213
+ const flattened = flattenDiscriminatedChildren(spec);
214
+ const parents = new Set(flattened.map(({ parent }) => parent));
215
+ mkdirSync(dirname(output), { recursive: true });
216
+ writeFileSync(output, await renderTypes(spec), "utf8");
217
+ console.info(
218
+ `${source} -> ${output} (${flattened.length} children flattened into ${[...parents].join(", ") || "no parent"})`,
219
+ );
220
+ }
221
+
222
+ await runBin(import.meta, "viz-codegen", main);
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The `@layer` order statement that the theme stylesheet resolved from `appDir` opens with.
3
+ * An app declares it before any of its CSS loads.
4
+ *
5
+ * @param themeStylesheet - the module specifier of the theme stylesheet
6
+ */
7
+ export declare function declaredLayerOrder(appDir: string, themeStylesheet?: string): string;
@@ -0,0 +1,17 @@
1
+ import { createRequire } from "node:module";
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ // src/layer-order.ts
5
+ /**
6
+ * The `@layer` order statement that the theme stylesheet resolved from `appDir` opens with.
7
+ * An app declares it before any of its CSS loads.
8
+ *
9
+ * @param themeStylesheet - the module specifier of the theme stylesheet
10
+ */
11
+ function declaredLayerOrder(appDir, themeStylesheet = "@timefoldai/viz-react/theme.css") {
12
+ const themeCss = createRequire(path.join(appDir, "package.json")).resolve(themeStylesheet);
13
+ const statement = /^@layer [^;{]+;/m.exec(readFileSync(themeCss, "utf8"))?.[0];
14
+ if (!statement) throw new Error(`${themeCss} has no @layer order statement, such as "@layer theme, base, components, utilities;"`);
15
+ return statement;
16
+ }
17
+ export { declaredLayerOrder };
@@ -0,0 +1,19 @@
1
+ import { PluginOption, UserConfig } from "vite";
2
+ /** The options of the shared Vite config for a model visualisation app. */
3
+ export interface AppViteOptions {
4
+ appDir: string;
5
+ port: number;
6
+ plugins?: PluginOption[];
7
+ alias?: Record<string, string>;
8
+ /** @defaultValue `"@timefoldai/viz-react/theme.css"` */
9
+ themeStylesheet?: string;
10
+ }
11
+ /**
12
+ * The shared Vite config every visualisation app builds on.
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * export default appViteConfig({ appDir: import.meta.dirname, port: 5173 });
17
+ * ```
18
+ */
19
+ export declare function appViteConfig({ appDir, port, plugins, alias, themeStylesheet }: AppViteOptions): UserConfig;
package/dist/vite.mjs ADDED
@@ -0,0 +1,89 @@
1
+ import { declaredLayerOrder } from "./layer-order.mjs";
2
+ import path from "node:path";
3
+ import tailwindcss from "@tailwindcss/vite";
4
+ import react from "@vitejs/plugin-react";
5
+ import { createLogger } from "vite";
6
+ // src/vite.ts
7
+ function vendorChunkName(id) {
8
+ if (!id.includes("node_modules")) return;
9
+ if (id.includes("@timefoldai/viz-")) return;
10
+ if (id.includes("@js-joda")) return "js-joda";
11
+ if (id.includes("vis-timeline")) return "vis-timeline";
12
+ if (id.includes("vis-data")) return "vis-data";
13
+ if (id.includes("maplibre-gl")) return "maplibre-gl";
14
+ return "vendor";
15
+ }
16
+ function declareLayerOrderFirst(appDir, themeStylesheet) {
17
+ const statement = declaredLayerOrder(appDir, themeStylesheet);
18
+ return {
19
+ name: "declare-layer-order-first",
20
+ transformIndexHtml: () => [{
21
+ tag: "style",
22
+ children: statement,
23
+ injectTo: "head-prepend"
24
+ }]
25
+ };
26
+ }
27
+ const VITE_QUERY_IMPORT = /\?(?:.*&)?(?:worker|sharedworker|url|raw|inline)(?:&|$)/;
28
+ function keepViteQueryImportsExternal() {
29
+ return {
30
+ name: "keep-vite-query-imports-external",
31
+ resolveId: {
32
+ filter: { id: VITE_QUERY_IMPORT },
33
+ async handler(id, importer) {
34
+ const queryStart = id.indexOf("?");
35
+ const resolved = await this.resolve(id.slice(0, queryStart), importer);
36
+ if (!resolved) return null;
37
+ return {
38
+ id: `${resolved.id}${id.slice(queryStart)}`,
39
+ external: "absolute"
40
+ };
41
+ }
42
+ }
43
+ };
44
+ }
45
+ function stdoutWarningLogger() {
46
+ return createLogger("info", { console: {
47
+ ...console,
48
+ warn: (...message) => console.log(...message)
49
+ } });
50
+ }
51
+ /**
52
+ * The shared Vite config every visualisation app builds on.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * export default appViteConfig({ appDir: import.meta.dirname, port: 5173 });
57
+ * ```
58
+ */
59
+ function appViteConfig({ appDir, port, plugins = [], alias = {}, themeStylesheet }) {
60
+ return {
61
+ base: "./",
62
+ customLogger: stdoutWarningLogger(),
63
+ server: { port },
64
+ preview: { port },
65
+ optimizeDeps: { rolldownOptions: { plugins: [keepViteQueryImportsExternal()] } },
66
+ build: {
67
+ chunkSizeWarningLimit: 1200,
68
+ rolldownOptions: {
69
+ input: "index.html",
70
+ output: { codeSplitting: { groups: [{
71
+ name: vendorChunkName,
72
+ debugName: "vendors"
73
+ }] } }
74
+ }
75
+ },
76
+ plugins: [
77
+ declareLayerOrderFirst(appDir, themeStylesheet),
78
+ react(),
79
+ tailwindcss(),
80
+ ...plugins
81
+ ],
82
+ css: { devSourcemap: true },
83
+ resolve: { alias: {
84
+ "@": path.join(appDir, "src"),
85
+ ...alias
86
+ } }
87
+ };
88
+ }
89
+ export { appViteConfig };
@@ -0,0 +1,20 @@
1
+ import { ViteUserConfig } from "vitest/config";
2
+ import { CoverageOptions } from "vitest/node";
3
+ /** The coverage block every workspace reports against, with the caller's deviations applied. */
4
+ export declare function coverageConfig(overrides?: CoverageOptions): CoverageOptions;
5
+ /** The options of the shared Vitest config for a Node package. */
6
+ export interface NodeVitestOptions {
7
+ workspaceDir: string;
8
+ alias?: Record<string, string>;
9
+ coverage?: CoverageOptions;
10
+ include?: string[];
11
+ }
12
+ /**
13
+ * The shared Vitest config for a workspace's node suite.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * export default defineConfig(nodeVitestConfig({ workspaceDir: import.meta.dirname }));
18
+ * ```
19
+ */
20
+ export declare function nodeVitestConfig({ workspaceDir, alias, coverage, include }: NodeVitestOptions): ViteUserConfig;
@@ -0,0 +1,61 @@
1
+ import path from "node:path";
2
+ import react from "@vitejs/plugin-react";
3
+ import "vitest/config";
4
+ import "vitest/node";
5
+ // src/vitest.ts
6
+ const sharedCoverage = {
7
+ enabled: false,
8
+ provider: "istanbul",
9
+ thresholds: {
10
+ statements: 80,
11
+ branches: 80,
12
+ functions: 80,
13
+ lines: 80
14
+ },
15
+ reporter: [
16
+ "text",
17
+ "json-summary",
18
+ "json",
19
+ "html"
20
+ ],
21
+ reportsDirectory: "coverage",
22
+ include: ["src/**/*.{ts,tsx}"],
23
+ exclude: [
24
+ "src/**/*.test.{ts,tsx}",
25
+ "src/**/*.spec.{ts,tsx}",
26
+ "src/**/*.stories.{ts,tsx}",
27
+ "src/test/**",
28
+ "src/**/__tests__/**"
29
+ ]
30
+ };
31
+ /** The coverage block every workspace reports against, with the caller's deviations applied. */
32
+ function coverageConfig(overrides = {}) {
33
+ return {
34
+ ...sharedCoverage,
35
+ ...overrides
36
+ };
37
+ }
38
+ /**
39
+ * The shared Vitest config for a workspace's node suite.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * export default defineConfig(nodeVitestConfig({ workspaceDir: import.meta.dirname }));
44
+ * ```
45
+ */
46
+ function nodeVitestConfig({ workspaceDir, alias = {}, coverage = {}, include = ["src/**/*.test.{ts,tsx}"] }) {
47
+ return {
48
+ plugins: [react()],
49
+ resolve: { alias: {
50
+ "@": path.join(workspaceDir, "src"),
51
+ ...alias
52
+ } },
53
+ test: {
54
+ environment: "node",
55
+ include,
56
+ server: { deps: { inline: [/@timefoldai\/viz-/] } },
57
+ coverage: coverageConfig(coverage)
58
+ }
59
+ };
60
+ }
61
+ export { coverageConfig, nodeVitestConfig };
@@ -0,0 +1,175 @@
1
+ const MAX_PROSE_LINES = 2;
2
+ const MAX_PROSE_LINES_CLASS = 4;
3
+ const MAX_PROSE_CHARS = 120;
4
+ const MAX_TAG_LINES = 4;
5
+
6
+ const DIRECTIVE =
7
+ /^(@ts-|@vite-ignore|@vitest-environment|eslint-|oxlint-|\/ <reference|v8 ignore|c8 ignore|istanbul ignore|tokens-allow|#__PURE__|@__PURE__)/;
8
+ const WHY_COMMENT = /^why:\s*\S/;
9
+
10
+ function proseKind(text) {
11
+ if (text === "") return "blank";
12
+ if (text.startsWith("@") || DIRECTIVE.test(text)) return "tag";
13
+ return "prose";
14
+ }
15
+
16
+ function blockLines(lines) {
17
+ const prose = [];
18
+ const tagParagraphs = [];
19
+ let longLine = false;
20
+ let inTag = false;
21
+ let inFence = false;
22
+ for (const raw of lines) {
23
+ const text = raw
24
+ .trim()
25
+ .replace(/^\{?\/\*\*?\s?/, "")
26
+ .replace(/\s*\*\/\}?\s*$/, "")
27
+ .replace(/^\*\s?/, "")
28
+ .trim();
29
+ if (text.startsWith("```")) {
30
+ inFence = !inFence;
31
+ continue;
32
+ }
33
+ if (inFence) continue;
34
+ if (text.length > MAX_PROSE_CHARS) longLine = true;
35
+ const kind = proseKind(text);
36
+ if (kind === "blank") inTag = false;
37
+ else if (kind === "tag") {
38
+ inTag = true;
39
+ tagParagraphs.push(1);
40
+ } else if (inTag) tagParagraphs[tagParagraphs.length - 1]++;
41
+ else prose.push(text);
42
+ }
43
+ return { prose, longLine, longestTag: Math.max(0, ...tagParagraphs) };
44
+ }
45
+
46
+ function collectJsxComments(sourceCode, node, into) {
47
+ if (node.expression.type !== "JSXEmptyExpression") return;
48
+ for (const comment of sourceCode.getCommentsInside(node))
49
+ into.set(comment.start, node);
50
+ }
51
+
52
+ function lineCommentOffence(text, length) {
53
+ if (DIRECTIVE.test(text))
54
+ return length > MAX_PROSE_CHARS
55
+ ? `a directive line beyond ${MAX_PROSE_CHARS} characters`
56
+ : null;
57
+ if (WHY_COMMENT.test(text))
58
+ return length > MAX_PROSE_CHARS
59
+ ? `a why-comment beyond ${MAX_PROSE_CHARS} characters`
60
+ : null;
61
+ return "inline comment";
62
+ }
63
+
64
+ const noInlineComment = {
65
+ meta: {
66
+ type: "suggestion",
67
+ docs: {
68
+ description:
69
+ "A script carries no inline comment but a one-line `// why:`.",
70
+ },
71
+ },
72
+ create(context) {
73
+ const { sourceCode } = context;
74
+ const jsxComments = new Map();
75
+ return {
76
+ JSXExpressionContainer(node) {
77
+ collectJsxComments(sourceCode, node, jsxComments);
78
+ },
79
+ "Program:exit": () => {
80
+ const reported = new Set();
81
+ for (const comment of sourceCode.getAllComments()) {
82
+ const container = jsxComments.get(comment.start);
83
+ if (container) {
84
+ if (reported.has(container.start)) continue;
85
+ reported.add(container.start);
86
+ context.report({
87
+ message: "jsx comment",
88
+ loc: sourceCode.getLoc(container),
89
+ });
90
+ continue;
91
+ }
92
+ if (comment.type !== "Line") continue;
93
+ const offence = lineCommentOffence(
94
+ comment.value.replace(/^\s?/, ""),
95
+ comment.end - comment.start,
96
+ );
97
+ if (offence)
98
+ context.report({
99
+ message: offence,
100
+ loc: sourceCode.getLoc(comment),
101
+ });
102
+ }
103
+ },
104
+ };
105
+ },
106
+ };
107
+
108
+ function docblockOffence(source, cap) {
109
+ const { prose, longLine, longestTag } = blockLines(source.split("\n"));
110
+ if (longLine) return `a docblock line beyond ${MAX_PROSE_CHARS} characters`;
111
+ if (longestTag > MAX_TAG_LINES) return `${longestTag} lines under one tag`;
112
+ if (prose.length === 0) return null;
113
+ if (cap === undefined) return "prose on a non-exported declaration";
114
+ return prose.length > cap ? `${prose.length} lines of prose` : null;
115
+ }
116
+
117
+ const docblockProse = {
118
+ meta: {
119
+ type: "suggestion",
120
+ docs: {
121
+ description:
122
+ "Docblock prose (2 lines, 4 on a class) sits on an exported declaration only.",
123
+ },
124
+ },
125
+ create(context) {
126
+ const { sourceCode } = context;
127
+ const jsxComments = new Map();
128
+ const capByComment = new Map();
129
+ const documents = (node, declaration) => {
130
+ const cap =
131
+ declaration?.type === "ClassDeclaration"
132
+ ? MAX_PROSE_LINES_CLASS
133
+ : MAX_PROSE_LINES;
134
+ for (const comment of sourceCode.getCommentsBefore(node))
135
+ capByComment.set(comment.start, cap);
136
+ };
137
+ return {
138
+ JSXExpressionContainer(node) {
139
+ collectJsxComments(sourceCode, node, jsxComments);
140
+ },
141
+ ExportNamedDeclaration(node) {
142
+ documents(node, node.declaration);
143
+ },
144
+ ExportDefaultDeclaration(node) {
145
+ documents(node, node.declaration);
146
+ },
147
+ ExportAllDeclaration(node) {
148
+ documents(node, null);
149
+ },
150
+ "Program:exit": () => {
151
+ for (const comment of sourceCode.getAllComments()) {
152
+ if (comment.type !== "Block") continue;
153
+ if (jsxComments.has(comment.start)) continue;
154
+ const offence = docblockOffence(
155
+ sourceCode.text.slice(comment.start, comment.end),
156
+ capByComment.get(comment.start),
157
+ );
158
+ if (offence)
159
+ context.report({
160
+ message: offence,
161
+ loc: sourceCode.getLoc(comment),
162
+ });
163
+ }
164
+ },
165
+ };
166
+ },
167
+ };
168
+
169
+ export default {
170
+ meta: { name: "comments" },
171
+ rules: {
172
+ "no-inline-comment": noInlineComment,
173
+ "docblock-prose": docblockProse,
174
+ },
175
+ };
@@ -0,0 +1,50 @@
1
+ import { readdirSync } from "node:fs";
2
+ import path from "node:path";
3
+
4
+ const TEST_FILE = /\.test\.[cm]?[jt]sx?$/;
5
+ const NOT_A_SOURCE = /\.(test|stories)\.[cm]?[jt]sx?$/;
6
+
7
+ /** Why a test file breaks the one-test-file-per-source rule, or null when it keeps it. */
8
+ export function testFileOffence(testPath, siblingNames) {
9
+ const name = path.basename(testPath);
10
+ const stem = name.replace(TEST_FILE, "");
11
+ const isSource = (sibling) =>
12
+ sibling.startsWith(`${stem}.`) && !NOT_A_SOURCE.test(sibling);
13
+ if (!siblingNames.some(isSource))
14
+ return `${name} has no source file ${stem}.* beside it: put its tests in that source's one test file`;
15
+ const testsOfStem = siblingNames.filter(
16
+ (sibling) =>
17
+ TEST_FILE.test(sibling) && sibling.replace(TEST_FILE, "") === stem,
18
+ );
19
+ if (testsOfStem.length > 1)
20
+ return `${stem} has ${testsOfStem.length} test files: keep one`;
21
+ return null;
22
+ }
23
+
24
+ const oneTestFilePerSource = {
25
+ meta: {
26
+ type: "suggestion",
27
+ docs: {
28
+ description:
29
+ "A source file has exactly one test file, named after it and beside it.",
30
+ },
31
+ },
32
+ create(context) {
33
+ const file = context.physicalFilename;
34
+ if (!TEST_FILE.test(file)) return {};
35
+ return {
36
+ Program(node) {
37
+ const offence = testFileOffence(
38
+ file,
39
+ readdirSync(path.dirname(file)),
40
+ );
41
+ if (offence) context.report({ node, message: offence });
42
+ },
43
+ };
44
+ },
45
+ };
46
+
47
+ export default {
48
+ meta: { name: "tests" },
49
+ rules: { "one-test-file-per-source": oneTestFilePerSource },
50
+ };