@uxfront/site-checks 0.1.0 → 0.1.1

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/lib/validate.js CHANGED
@@ -4,21 +4,21 @@
4
4
 
5
5
  /** @param {unknown} value */
6
6
  const show = (value) => {
7
- try {
8
- return JSON.stringify(value) ?? String(value);
9
- } catch {
10
- return String(value);
11
- }
7
+ try {
8
+ return JSON.stringify(value) ?? String(value);
9
+ } catch {
10
+ return String(value);
11
+ }
12
12
  };
13
13
 
14
14
  /** @param {string} path @param {string} expected @param {unknown} value */
15
15
  const fail = (path, expected, value) => {
16
- throw new TypeError(`${path} must be ${expected}, not ${show(value)}`);
16
+ throw new TypeError(`${path} must be ${expected}, not ${show(value)}`);
17
17
  };
18
18
 
19
19
  /** @param {unknown} value @returns {value is Record<string, unknown>} */
20
20
  export const isPlainObject = (value) =>
21
- Boolean(value) && typeof value === "object" && !Array.isArray(value);
21
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
22
22
 
23
23
  /**
24
24
  * One of these values.
@@ -26,28 +26,32 @@ export const isPlainObject = (value) =>
26
26
  * @returns {Validator}
27
27
  */
28
28
  export const oneOf =
29
- (...values) =>
30
- (value, path) => {
31
- if (!values.includes(/** @type {string | boolean} */ (value))) {
32
- fail(path, `one of ${values.map(show).join(", ")}`, value);
33
- }
34
- };
29
+ (...values) =>
30
+ (value, path) => {
31
+ if (!values.some((allowed) => allowed === value)) {
32
+ fail(path, `one of ${values.map(show).join(", ")}`, value);
33
+ }
34
+ };
35
35
 
36
36
  /** @type {Validator} */
37
37
  export const bool = (value, path) => {
38
- if (typeof value !== "boolean") fail(path, "true or false", value);
38
+ if (typeof value !== "boolean") {
39
+ fail(path, "true or false", value);
40
+ }
39
41
  };
40
42
 
41
43
  /** @type {Validator} */
42
44
  export const count = (value, path) => {
43
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
44
- fail(path, "a number of 0 or more", value);
45
- }
45
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
46
+ fail(path, "a number of 0 or more", value);
47
+ }
46
48
  };
47
49
 
48
50
  /** @type {Validator} */
49
51
  export const text = (value, path) => {
50
- if (typeof value !== "string" || !value) fail(path, "a string that isn't empty", value);
52
+ if (typeof value !== "string" || !value) {
53
+ fail(path, "a string that isn't empty", value);
54
+ }
51
55
  };
52
56
 
53
57
  /**
@@ -57,28 +61,34 @@ export const text = (value, path) => {
57
61
  * @returns {Validator}
58
62
  */
59
63
  export const list =
60
- (item, { nonEmpty = false } = {}) =>
61
- (value, path) => {
62
- if (!Array.isArray(value)) return fail(path, "a list", value);
63
- if (nonEmpty && !value.length) fail(path, "a list that isn't empty", value);
64
- value.forEach((entry, index) => item(entry, `${path}[${index}]`));
65
- };
64
+ (item, { nonEmpty = false } = {}) =>
65
+ (value, path) => {
66
+ if (!Array.isArray(value)) {
67
+ return fail(path, "a list", value);
68
+ }
69
+ if (nonEmpty && !value.length) {
70
+ fail(path, "a list that isn't empty", value);
71
+ }
72
+ value.forEach((entry, index) => item(entry, `${path}[${index}]`));
73
+ };
66
74
 
67
75
  /** A site path, like `/docs/`, or a pattern, like `/docs/*` or `*`. @type {Validator} */
68
76
  export const pattern = (value, path) => {
69
- if (typeof value !== "string" || !(value.startsWith("/") || value === "*")) {
70
- fail(path, 'a path that starts with "/", or "*"', value);
71
- }
77
+ if (typeof value !== "string" || !(value.startsWith("/") || value === "*")) {
78
+ fail(path, 'a path that starts with "/", or "*"', value);
79
+ }
72
80
  };
73
81
 
74
82
  /** @type {Validator} */
75
83
  export const url = (value, path) => {
76
- try {
77
- if (typeof value !== "string") throw new TypeError();
78
- new URL(value);
79
- } catch {
80
- fail(path, "a URL", value);
81
- }
84
+ try {
85
+ if (typeof value !== "string") {
86
+ throw new TypeError();
87
+ }
88
+ new URL(value);
89
+ } catch {
90
+ fail(path, "a URL", value);
91
+ }
82
92
  };
83
93
 
84
94
  /**
@@ -88,101 +98,114 @@ export const url = (value, path) => {
88
98
  * @returns {Validator}
89
99
  */
90
100
  export const shape =
91
- (required, optional = {}) =>
92
- (value, path) => {
93
- if (!isPlainObject(value)) return fail(path, "an object", value);
94
- for (const [key, check] of Object.entries(required)) {
95
- if (!(key in value)) throw new TypeError(`${path} needs ${key}`);
96
- check(value[key], `${path}.${key}`);
97
- }
98
- for (const [key, entry] of Object.entries(value)) {
99
- if (key in required) continue;
100
- const check = optional[key];
101
- if (!check) {
102
- const known = [...Object.keys(required), ...Object.keys(optional)];
103
- throw new TypeError(`${path} has no option "${key}". Its options are: ${known.join(", ")}`);
104
- }
105
- check(entry, `${path}.${key}`);
106
- }
107
- };
101
+ (required, optional = {}) =>
102
+ (value, path) => {
103
+ if (!isPlainObject(value)) {
104
+ return fail(path, "an object", value);
105
+ }
106
+ for (const [key, check] of Object.entries(required)) {
107
+ if (!(key in value)) {
108
+ throw new TypeError(`${path} needs ${key}`);
109
+ }
110
+ check(value[key], `${path}.${key}`);
111
+ }
112
+ for (const [key, entry] of Object.entries(value)) {
113
+ if (key in required) {
114
+ continue;
115
+ }
116
+ const check = optional[key];
117
+ if (!check) {
118
+ const known = [...Object.keys(required), ...Object.keys(optional)];
119
+ throw new TypeError(`${path} has no option "${key}". Its options are: ${known.join(", ")}`);
120
+ }
121
+ check(entry, `${path}.${key}`);
122
+ }
123
+ };
108
124
 
109
125
  const SCOPES = ["head", "head-element", "document", "markup"];
110
126
 
111
127
  /** A source of `sitemap-indexable` or `sitemap-coverage`. @type {Validator} */
112
128
  export const source = (value, path) => {
113
- if (!isPlainObject(value)) return fail(path, "an object with a type", value);
114
- const types = {
115
- meta: shape(
116
- { type: text, names: list(text, { nonEmpty: true }) },
117
- {
118
- values: list(text, { nonEmpty: true }),
119
- word: bool,
120
- caseSensitive: bool,
121
- property: bool,
122
- anyCaseNames: bool,
123
- scope: oneOf(...SCOPES),
124
- },
125
- ),
126
- refresh: shape({ type: text }),
127
- files: shape({ type: text, files: list(text) }),
128
- under: shape({ type: text, paths: list(text) }),
129
- redirects: shape({ type: text }),
130
- headers: shape(
131
- { type: text, hosts: oneOf("ignore", "match", "drop") },
132
- { values: list(text, { nonEmpty: true }), word: bool },
133
- ),
134
- };
135
- const check = types[/** @type {keyof typeof types} */ (String(value.type))];
136
- if (!check)
137
- return fail(`${path}.type`, `one of ${Object.keys(types).map(show).join(", ")}`, value.type);
138
- check(value, path);
129
+ if (!isPlainObject(value)) {
130
+ return fail(path, "an object with a type", value);
131
+ }
132
+ const types = new Map(
133
+ Object.entries({
134
+ meta: shape(
135
+ { type: text, names: list(text, { nonEmpty: true }) },
136
+ {
137
+ values: list(text, { nonEmpty: true }),
138
+ word: bool,
139
+ caseSensitive: bool,
140
+ property: bool,
141
+ anyCaseNames: bool,
142
+ scope: oneOf(...SCOPES),
143
+ },
144
+ ),
145
+ refresh: shape({ type: text }),
146
+ files: shape({ type: text, files: list(text) }),
147
+ under: shape({ type: text, paths: list(text) }),
148
+ redirects: shape({ type: text }),
149
+ headers: shape(
150
+ { type: text, hosts: oneOf("ignore", "match", "drop") },
151
+ { values: list(text, { nonEmpty: true }), word: bool },
152
+ ),
153
+ }),
154
+ );
155
+ // A Map, so a type like "constructor" or "toString" finds no check on Object.prototype.
156
+ const check = types.get(String(value.type));
157
+ if (!check) {
158
+ return fail(`${path}.type`, `one of ${[...types.keys()].map(show).join(", ")}`, value.type);
159
+ }
160
+ check(value, path);
139
161
  };
140
162
 
141
163
  /** `json-ld-types`'s map of path patterns to `@type`s. @type {Validator} */
142
164
  export const typesByPath = (value, path) => {
143
- if (!isPlainObject(value))
144
- return fail(path, 'an object of path patterns, like { "/docs/*": ["TechArticle"] }', value);
145
- for (const [key, types] of Object.entries(value)) {
146
- pattern(key, `${path} key`);
147
- list(text)(types, `${path}["${key}"]`);
148
- }
165
+ if (!isPlainObject(value)) {
166
+ return fail(path, 'an object of path patterns, like { "/docs/*": ["TechArticle"] }', value);
167
+ }
168
+ for (const [key, types] of Object.entries(value)) {
169
+ pattern(key, `${path} key`);
170
+ list(text)(types, `${path}["${key}"]`);
171
+ }
149
172
  };
150
173
 
151
174
  /** The parsing profile's settings. @type {Record<string, Validator>} */
152
175
  export const PARSE = {
153
- scope: oneOf(...SCOPES),
154
- titleScope: oneOf(...SCOPES),
155
- titleTag: oneOf("any", "plain-text", "bare"),
156
- trimTitle: oneOf("after-decode", "before-decode", "none"),
157
- quotes: oneOf("any", "double"),
158
- caseSensitiveTags: bool,
159
- tagEnd: oneOf("word", "space"),
160
- metaKey: oneOf("name-or-property", "property-first"),
161
- trimValues: bool,
162
- decode: list((value, path) => {
163
- if (
164
- typeof value !== "string" ||
165
- !(
166
- ["numeric", "amp", "lt", "gt", "quot", "apos"].includes(value) ||
167
- /^#(x[\da-f]+|\d+)$/i.test(value)
168
- )
169
- ) {
170
- fail(
171
- path,
172
- 'an entity: "numeric", "amp", "lt", "gt", "quot", "apos" or a reference like "#x27"',
173
- value,
174
- );
175
- }
176
- }),
177
- decodeOrder: oneOf("one-pass", "numeric-first"),
178
- decodeIgnoreCase: bool,
179
- count: oneOf("utf-16", "code-points"),
180
- h1: oneOf("anywhere", "markup", "rendered"),
181
- nodes: oneOf("graph-or-block", "block-and-graph", "all", "graph-deep"),
182
- typeArrays: bool,
183
- jsonLdType: oneOf("exact", "prefix-any-case"),
184
- blankLines: oneOf("whitespace", "empty"),
185
- trimSitemap: bool,
186
- mergeDuplicateLocs: bool,
187
- headersParser: oneOf("lines", "blocks"),
176
+ scope: oneOf(...SCOPES),
177
+ titleScope: oneOf(...SCOPES),
178
+ titleTag: oneOf("any", "plain-text", "bare"),
179
+ trimTitle: oneOf("after-decode", "before-decode", "none"),
180
+ quotes: oneOf("any", "double"),
181
+ caseSensitiveTags: bool,
182
+ tagEnd: oneOf("word", "space"),
183
+ metaKey: oneOf("name-or-property", "property-first"),
184
+ trimValues: bool,
185
+ decode: list((value, path) => {
186
+ if (
187
+ typeof value !== "string" ||
188
+ !(
189
+ ["numeric", "amp", "lt", "gt", "quot", "apos"].includes(value) ||
190
+ /^#(x[\da-f]+|\d+)$/i.test(value)
191
+ )
192
+ ) {
193
+ fail(
194
+ path,
195
+ 'an entity: "numeric", "amp", "lt", "gt", "quot", "apos" or a reference like "#x27"',
196
+ value,
197
+ );
198
+ }
199
+ }),
200
+ decodeOrder: oneOf("one-pass", "numeric-first"),
201
+ decodeIgnoreCase: bool,
202
+ count: oneOf("utf-16", "code-points"),
203
+ h1: oneOf("anywhere", "markup", "rendered"),
204
+ nodes: oneOf("graph-or-block", "block-and-graph", "all", "graph-deep"),
205
+ typeArrays: bool,
206
+ jsonLdType: oneOf("exact", "prefix-any-case"),
207
+ blankLines: oneOf("whitespace", "empty"),
208
+ trimSitemap: bool,
209
+ mergeDuplicateLocs: bool,
210
+ headersParser: oneOf("lines", "blocks"),
188
211
  };
package/lighthouse.d.ts CHANGED
@@ -3,41 +3,43 @@ export type Category = "performance" | "accessibility" | "best-practices" | "seo
3
3
 
4
4
  /** How a category's score is asserted: `error` and a `minScore` of 0.95, or 1 for `seo`, unless set. */
5
5
  export interface CategoryAssertion {
6
- level?: "error" | "warn" | "off";
7
- minScore?: number;
6
+ level?: "error" | "warn" | "off";
7
+ minScore?: number;
8
8
  }
9
9
 
10
10
  export interface LighthouseOptions {
11
- /** Lighthouse CI's `collect` settings, like `staticDistDir` and `url`. `numberOfRuns` defaults to 3. */
12
- collect: Record<string, unknown>;
13
- /** Changes to a category's assertion, like `{ seo: { minScore: 0.95 } }`. */
14
- categories?: Partial<Record<Category, CategoryAssertion>>;
15
- /**
16
- * Asserts each category only on the URLs that match a pattern, as Lighthouse CI's
17
- * `assertMatrix`, like `{ matchingUrlPattern: "^http://localhost:8799/$", categories: ["performance"] }`.
18
- */
19
- matrix?: readonly { matchingUrlPattern: string; categories: readonly Category[] }[];
11
+ /** Lighthouse CI's `collect` settings, like `staticDistDir` and `url`. `numberOfRuns` defaults to 3. */
12
+ // oxlint-disable-next-line quality/no-unsafe-dictionary-type -- Lighthouse CI owns these settings
13
+ collect: Record<string, unknown>;
14
+ /** Changes to a category's assertion, like `{ seo: { minScore: 0.95 } }`. */
15
+ categories?: Partial<Record<Category, CategoryAssertion>>;
16
+ /**
17
+ * Asserts each category only on the URLs that match a pattern, as Lighthouse CI's
18
+ * `assertMatrix`, like `{ matchingUrlPattern: "^http://localhost:8799/$", categories: ["performance"] }`.
19
+ */
20
+ matrix?: ReadonlyArray<{ matchingUrlPattern: string; categories: ReadonlyArray<Category> }>;
20
21
  }
21
22
 
22
23
  type Assertion = [level: "error" | "warn" | "off", options: { minScore: number }];
23
24
 
24
25
  export interface LighthouseConfig {
25
- ci: {
26
- collect: Record<string, unknown>;
27
- assert:
28
- | { assertions: Partial<Record<`categories:${Category}`, Assertion>> }
29
- | {
30
- assertMatrix: {
31
- matchingUrlPattern: string;
32
- assertions: Partial<Record<`categories:${Category}`, Assertion>>;
33
- }[];
34
- };
35
- upload: { target: "filesystem"; outputDir: ".lighthouseci" };
36
- };
26
+ ci: {
27
+ // oxlint-disable-next-line quality/no-unsafe-dictionary-type -- Lighthouse CI owns these settings
28
+ collect: Record<string, unknown>;
29
+ assert:
30
+ | { assertions: Partial<Record<`categories:${Category}`, Assertion>> }
31
+ | {
32
+ assertMatrix: Array<{
33
+ matchingUrlPattern: string;
34
+ assertions: Partial<Record<`categories:${Category}`, Assertion>>;
35
+ }>;
36
+ };
37
+ upload: { target: "filesystem"; outputDir: ".lighthouseci" };
38
+ };
37
39
  }
38
40
 
39
41
  /** The four categories, in the order the preset asserts them. */
40
- export declare const CATEGORIES: readonly Category[];
42
+ export declare const CATEGORIES: ReadonlyArray<Category>;
41
43
 
42
44
  /** A full Lighthouse CI config: the shared thresholds, with the site's `collect` merged in. */
43
45
  export declare function lighthouseConfig(options: LighthouseOptions): LighthouseConfig;
package/lighthouse.js CHANGED
@@ -6,46 +6,50 @@ import { isPlainObject, list, oneOf, shape } from "./lib/validate.js";
6
6
  /** @type {readonly Category[]} */
7
7
  export const CATEGORIES = Object.freeze(["performance", "accessibility", "best-practices", "seo"]);
8
8
 
9
- /** @type {Validator} */
9
+ /** @type {(value: unknown, path: string) => asserts value is object} */
10
10
  const isObject = (value, path) => {
11
- if (!isPlainObject(value)) throw new TypeError(`${path} must be an object of settings`);
11
+ if (!isPlainObject(value)) {
12
+ throw new TypeError(`${path} must be an object of settings`);
13
+ }
12
14
  };
13
15
 
14
16
  /** @type {Validator} */
15
17
  const minScore = (value, path) => {
16
- if (typeof value !== "number" || !(value >= 0 && value <= 1)) {
17
- throw new TypeError(`${path} must be a score from 0 to 1, not ${JSON.stringify(value)}`);
18
- }
18
+ if (typeof value !== "number" || !(value >= 0 && value <= 1)) {
19
+ throw new TypeError(`${path} must be a score from 0 to 1, not ${JSON.stringify(value)}`);
20
+ }
19
21
  };
20
22
 
21
23
  const category = oneOf(...CATEGORIES);
22
24
 
23
25
  /** @type {Validator} */
24
26
  const categoryChanges = (value, path) => {
25
- isObject(value, path);
26
- for (const [key, change] of Object.entries(/** @type {object} */ (value))) {
27
- category(key, `${path} key`);
28
- shape({}, { level: oneOf("error", "warn", "off"), minScore })(change, `${path}.${key}`);
29
- }
27
+ isObject(value, path);
28
+ for (const [key, change] of Object.entries(value)) {
29
+ category(key, `${path} key`);
30
+ shape({}, { level: oneOf("error", "warn", "off"), minScore })(change, `${path}.${key}`);
31
+ }
30
32
  };
31
33
 
32
34
  const matrixEntries = list(
33
- shape({
34
- matchingUrlPattern: (value, path) => {
35
- if (typeof value !== "string" || !value) throw new TypeError(`${path} must be a pattern`);
36
- },
37
- categories: list(category, { nonEmpty: true }),
38
- }),
39
- { nonEmpty: true },
35
+ shape({
36
+ matchingUrlPattern: (value, path) => {
37
+ if (typeof value !== "string" || !value) {
38
+ throw new TypeError(`${path} must be a pattern`);
39
+ }
40
+ },
41
+ categories: list(category, { nonEmpty: true }),
42
+ }),
43
+ { nonEmpty: true },
40
44
  );
41
45
 
42
46
  // Every site errors below 0.95, and below 1 in SEO, unless it says otherwise.
43
47
  /** @type {Readonly<Record<Category, Required<CategoryAssertion>>>} */
44
48
  const BASE = {
45
- performance: { level: "error", minScore: 0.95 },
46
- accessibility: { level: "error", minScore: 0.95 },
47
- "best-practices": { level: "error", minScore: 0.95 },
48
- seo: { level: "error", minScore: 1 },
49
+ performance: { level: "error", minScore: 0.95 },
50
+ accessibility: { level: "error", minScore: 0.95 },
51
+ "best-practices": { level: "error", minScore: 0.95 },
52
+ seo: { level: "error", minScore: 1 },
49
53
  };
50
54
 
51
55
  /**
@@ -54,31 +58,31 @@ const BASE = {
54
58
  * @returns {LighthouseConfig}
55
59
  */
56
60
  export function lighthouseConfig(options) {
57
- shape({ collect: isObject }, { categories: categoryChanges, matrix: matrixEntries })(
58
- options,
59
- "lighthouseConfig's options",
60
- );
61
- const { collect, categories = {}, matrix } = options;
62
- /** @param {readonly Category[]} list */
63
- const assertions = (list) =>
64
- Object.fromEntries(
65
- CATEGORIES.filter((category) => list.includes(category)).map((category) => {
66
- const { level, minScore } = { ...BASE[category], ...categories[category] };
67
- return [`categories:${category}`, [level, { minScore }]];
68
- }),
69
- );
70
- return {
71
- ci: {
72
- collect: { numberOfRuns: 3, ...collect },
73
- assert: matrix
74
- ? {
75
- assertMatrix: matrix.map(({ matchingUrlPattern, categories: list }) => ({
76
- matchingUrlPattern,
77
- assertions: assertions(list),
78
- })),
79
- }
80
- : { assertions: assertions(CATEGORIES) },
81
- upload: { target: "filesystem", outputDir: ".lighthouseci" },
82
- },
83
- };
61
+ shape({ collect: isObject }, { categories: categoryChanges, matrix: matrixEntries })(
62
+ options,
63
+ "lighthouseConfig's options",
64
+ );
65
+ const { collect, categories = {}, matrix } = options;
66
+ /** @param {readonly Category[]} list */
67
+ const assertions = (list) =>
68
+ Object.fromEntries(
69
+ CATEGORIES.filter((category) => list.includes(category)).map((category) => {
70
+ const { level, minScore } = { ...BASE[category], ...categories[category] };
71
+ return [`categories:${category}`, [level, { minScore }]];
72
+ }),
73
+ );
74
+ return {
75
+ ci: {
76
+ collect: { numberOfRuns: 3, ...collect },
77
+ assert: matrix
78
+ ? {
79
+ assertMatrix: matrix.map(({ matchingUrlPattern, categories: list }) => ({
80
+ matchingUrlPattern,
81
+ assertions: assertions(list),
82
+ })),
83
+ }
84
+ : { assertions: assertions(CATEGORIES) },
85
+ upload: { target: "filesystem", outputDir: ".lighthouseci" },
86
+ },
87
+ };
84
88
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxfront/site-checks",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The search and AI search checks and the Lighthouse CI preset shared by the uxfront.com family of sites.",
5
5
  "keywords": [
6
6
  "lighthouse",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "devDependencies": {
45
45
  "@types/node": "^26.4.1",
46
- "@uxfront/typescript-config": "0.2.0",
46
+ "@uxfront/typescript-config": "0.2.1",
47
47
  "vitest": "^5.0.1"
48
48
  },
49
49
  "engines": {