@riebeckite/plugin-quality 0.0.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright Rerurate_514
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,69 @@
1
+ # @riebeckite/plugin-quality
2
+
3
+ Static quality and accessibility inspection for generated HTML in Riebeckite.
4
+
5
+ [日本語](./README_ja.md)
6
+
7
+ ## Overview
8
+
9
+ `qualityPlugin()` runs a small set of dependency-free, regex-based rules over
10
+ the HTML produced by the build and reports the findings through the shared
11
+ diagnostics channel. There is no DOM, no axe-core, and no headless browser.
12
+
13
+ At the manifest stage the plugin inspects each public entry's rendered article
14
+ HTML. Integrations that finish HTML generation can additionally call the
15
+ exported `inspectGeneratedHtml` hook for final pages.
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import { defineConfig } from "@riebeckite/core";
21
+ import { qualityPlugin } from "@riebeckite/plugin-quality";
22
+
23
+ export default defineConfig({
24
+ // ...
25
+ plugins: [qualityPlugin({ failOn: "error" })],
26
+ });
27
+ ```
28
+
29
+ ## Options
30
+
31
+ | Option | Type | Description |
32
+ | ------ | ---- | ----------- |
33
+ | `ignoreRules` | `string[]` | Diagnostic codes to suppress (for example `"quality:empty-link-text"`). |
34
+ | `a11y` | `{ enabled?: boolean }` | Accessibility inspection. Defaults to enabled; set `enabled: false` to disable every rule. |
35
+ | `failOn` | `"error" \| "never"` | Throw on the first build with an error-severity diagnostic during the manifest stage. Defaults to `"never"`. |
36
+
37
+ ## Rules
38
+
39
+ | Code | Severity | Description |
40
+ | ---- | -------- | ----------- |
41
+ | `quality:img-alt-missing` | warning | `<img>` without an `alt` attribute. `alt=""` is valid for decorative images. |
42
+ | `quality:duplicate-id` | error | The same `id` value used more than once. |
43
+ | `quality:broken-internal-anchor` | warning | `href="#foo"` with no matching `id="foo"` in the document. |
44
+ | `quality:heading-order` | warning | Skipped heading levels (for example `h1` → `h3`) or headings without any `h1`. |
45
+ | `quality:empty-link-text` | warning | `<a href>` with empty text and no `aria-label`, `title`, or non-empty `img[alt]`. |
46
+ | `quality:html-lang-missing` | warning | `<html>` without a non-empty `lang` attribute (full documents only). |
47
+ | `quality:table-no-header` | warning | `<table>` with data cells but no `<th>`, `scope`, or `headers`. |
48
+
49
+ ## API
50
+
51
+ - `qualityPlugin(options?)` — plugin factory.
52
+ - `inspectHtml(html, options?)` — pure function returning `Diagnostic[]`.
53
+ - `inspectGeneratedHtml(page, options?)` — pure function that inspects a final
54
+ page and sets `filePath` to `page.path`.
55
+ - `RULE_CODES` — the stable code identifiers.
56
+ - Types: `QualityOptions`, `InspectOptions`.
57
+
58
+ ## Limitations
59
+
60
+ The scanner is regex-based, not a real DOM. It does not validate malformed
61
+ markup, does not track nesting depth, and only handles well-formed, non-nested
62
+ elements when pairing an open tag with its close tag. Comments and
63
+ `<script>`/`<style>` contents are masked before scanning. Rules that depend on
64
+ document structure (heading order, table headers) can therefore miss or
65
+ misattribute findings in unusual markup.
66
+
67
+ ## See also
68
+
69
+ - [Plugin guide](../../docs/plugins_en.md)
package/README_ja.md ADDED
@@ -0,0 +1,59 @@
1
+ # @riebeckite/plugin-quality
2
+
3
+ Riebeckite が生成する HTML を静的に検査し、品質とアクセシビリティの問題を報告するプラグインです。
4
+
5
+ [English](./README_en.md)
6
+
7
+ ## 概要
8
+
9
+ `qualityPlugin()` は、ビルドで生成された HTML に対して依存パッケージなしの正規表現ベースのルールを実行し、結果を既存の diagnostics に流します。DOM も axe-core もヘッドレスブラウザも使いません。
10
+
11
+ マニフェスト生成の段階では、公開エントリごとの記事 HTML を検査します。HTML 生成を完了する統合側は、公開ページ向けに公開 API の `inspectGeneratedHtml` を追加で呼び出せます。
12
+
13
+ ## 使い方
14
+
15
+ ```ts
16
+ import { defineConfig } from "@riebeckite/core";
17
+ import { qualityPlugin } from "@riebeckite/plugin-quality";
18
+
19
+ export default defineConfig({
20
+ // ...
21
+ plugins: [qualityPlugin({ failOn: "error" })],
22
+ });
23
+ ```
24
+
25
+ ## オプション
26
+
27
+ | オプション | 型 | 説明 |
28
+ | ---------- | -- | ---- |
29
+ | `ignoreRules` | `string[]` | 抑制する diagnostic の code(例: `"quality:empty-link-text"`)。 |
30
+ | `a11y` | `{ enabled?: boolean }` | アクセシビリティ検査。既定は有効で、`enabled: false` で全ルールを止めます。 |
31
+ | `failOn` | `"error" \| "never"` | マニフェスト段階で error の diagnostic があればビルドを失敗させます。既定は `"never"`。 |
32
+
33
+ ## ルール一覧
34
+
35
+ | Code | 重大度 | 内容 |
36
+ | ---- | ------ | ---- |
37
+ | `quality:img-alt-missing` | warning | `alt` のない `<img>`。装飾画像の `alt=""` は対象外です。 |
38
+ | `quality:duplicate-id` | error | 同じ `id` が同一文書内で複数回使われています。 |
39
+ | `quality:broken-internal-anchor` | warning | `href="#foo"` に対応する `id="foo"` が文書内にありません。 |
40
+ | `quality:heading-order` | warning | 見出しレベルの飛び(`h1` → `h3` など)、または `h1` が1つもない状態。 |
41
+ | `quality:empty-link-text` | warning | テキストが空で、`aria-label`・`title`・alt 付き `img` もない `<a href>`。 |
42
+ | `quality:html-lang-missing` | warning | 空でない `lang` を持たない `<html>`(完全な文書のみ)。 |
43
+ | `quality:table-no-header` | warning | データセルはあるが `<th>`・`scope`・`headers` がない `<table>`。 |
44
+
45
+ ## API
46
+
47
+ - `qualityPlugin(options?)` — プラグインファクトリ。
48
+ - `inspectHtml(html, options?)` — `Diagnostic[]` を返す純粋関数。
49
+ - `inspectGeneratedHtml(page, options?)` — 最終ページを検査し、`filePath` に `page.path` を設定する純粋関数。
50
+ - `RULE_CODES` — 安定した code の一覧。
51
+ - 型: `QualityOptions`、`InspectOptions`。
52
+
53
+ ## 制限事項
54
+
55
+ スキャナは正規表現ベースであり、実際の DOM ではありません。不正なマークアップの検証やネストの深さの追跡は行わず、開始タグと終了タグの対応付けは整形式でネストのない要素だけを扱います。走査の前にコメントと `<script>`・`<style>` の中身はマスクします。そのため、文書構造に依存するルール(見出し順、テーブルヘッダー)は、特殊なマークアップでは検出漏れや誤検出が起こりえます。
56
+
57
+ ## 関連
58
+
59
+ - [プラグインガイド](../../docs/plugins_ja.md)
@@ -0,0 +1,20 @@
1
+ import { type Diagnostic, type PluginGeneratedHtml, type RiebeckitePlugin } from "@riebeckite/core";
2
+ import type { InspectOptions, QualityOptions } from "./src/types.js";
3
+ export { inspectHtml, QUALITY_PLUGIN_NAME, RULE_CODES, type RuleCode, } from "./src/rules.js";
4
+ export type { InspectOptions, QualityOptions, ResolvedInspectOptions, ResolvedQualityOptions, } from "./src/types.js";
5
+ /**
6
+ * Inspects a final, fully rendered SSG page. Each returned diagnostic carries
7
+ * `filePath` set to `page.path` so integrations can attribute it to an emitted
8
+ * file. Purely functional: the page object is not mutated.
9
+ */
10
+ export declare function inspectGeneratedHtml(page: PluginGeneratedHtml, options?: InspectOptions): Diagnostic[];
11
+ /**
12
+ * Static quality and accessibility inspection for generated HTML.
13
+ *
14
+ * At the manifest stage the plugin inspects each public entry's rendered HTML
15
+ * and pushes diagnostics into the shared array. The `inspectGeneratedHtml`
16
+ * field lets an SSG integration inspect final pages after the build, where no
17
+ * manifest is available.
18
+ */
19
+ export declare function qualityPlugin(options?: QualityOptions): RiebeckitePlugin;
20
+ export declare const quality: typeof qualityPlugin;
package/dist/index.js ADDED
@@ -0,0 +1,397 @@
1
+ // index.ts
2
+ import {
3
+ definePlugin
4
+ } from "@riebeckite/core";
5
+
6
+ // src/options.ts
7
+ function resolveInspectOptions(options = {}) {
8
+ return {
9
+ enabled: options.a11y?.enabled !== false,
10
+ ignoreRules: new Set(options.ignoreRules ?? [])
11
+ };
12
+ }
13
+ function resolveQualityOptions(options = {}) {
14
+ return {
15
+ inspect: resolveInspectOptions(options),
16
+ failOn: options.failOn === "error" ? "error" : "never"
17
+ };
18
+ }
19
+
20
+ // src/scanner.ts
21
+ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
22
+ "area",
23
+ "base",
24
+ "br",
25
+ "col",
26
+ "embed",
27
+ "hr",
28
+ "img",
29
+ "input",
30
+ "link",
31
+ "meta",
32
+ "param",
33
+ "source",
34
+ "track",
35
+ "wbr"
36
+ ]);
37
+ var NAMED_ENTITIES = {
38
+ amp: "&",
39
+ apos: "'",
40
+ gt: ">",
41
+ lt: "<",
42
+ nbsp: " ",
43
+ quot: '"'
44
+ };
45
+ var TAG_PATTERN = /<([a-zA-Z][a-zA-Z0-9-]*)((?:[^>"']|"[^"]*"|'[^']*')*?)(\/?)>/g;
46
+ var ATTRIBUTE_PATTERN = /([^\s"'=<>`/]+)(?:\s*=\s*("([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g;
47
+ function maskIgnoredRegions(html) {
48
+ return html.replace(/<!--[\s\S]*?-->/g, (match) => " ".repeat(match.length)).replace(
49
+ /<(script|style)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,
50
+ (match) => " ".repeat(match.length)
51
+ );
52
+ }
53
+ function scanElements(document) {
54
+ const elements = [];
55
+ const pattern = new RegExp(TAG_PATTERN.source, "g");
56
+ for (const match of document.matchAll(pattern)) {
57
+ const tag = (match[1] ?? "").toLowerCase();
58
+ const selfClosing = match[3] === "/" || VOID_ELEMENTS.has(tag);
59
+ const end = match.index + match[0].length;
60
+ elements.push({
61
+ tag,
62
+ attributes: parseAttributes(match[2] ?? ""),
63
+ raw: match[0],
64
+ start: match.index,
65
+ end,
66
+ content: selfClosing ? "" : innerContent(document, tag, end)
67
+ });
68
+ }
69
+ return elements;
70
+ }
71
+ function parseAttributes(text) {
72
+ const attributes = /* @__PURE__ */ new Map();
73
+ const pattern = new RegExp(ATTRIBUTE_PATTERN.source, "g");
74
+ for (const match of text.matchAll(pattern)) {
75
+ const name = (match[1] ?? "").toLowerCase();
76
+ if (attributes.has(name)) continue;
77
+ const value = match[3] ?? match[4] ?? match[5] ?? "";
78
+ attributes.set(name, decodeHtmlEntities(value));
79
+ }
80
+ return attributes;
81
+ }
82
+ function textContent(fragment) {
83
+ return decodeHtmlEntities(fragment.replace(/<[^>]*>/g, " "));
84
+ }
85
+ function attribute(element, name) {
86
+ return element.attributes.get(name);
87
+ }
88
+ function hasNonEmptyAttribute(element, name) {
89
+ const value = element.attributes.get(name);
90
+ return value !== void 0 && value.trim() !== "";
91
+ }
92
+ function decodeHtmlEntities(value) {
93
+ return value.replace(
94
+ /&(#x[0-9a-f]+|#\d+|[a-z]+);/gi,
95
+ (match, entity) => {
96
+ if (entity.startsWith("#")) {
97
+ const hex = entity[1] === "x" || entity[1] === "X";
98
+ const code = Number.parseInt(
99
+ hex ? entity.slice(2) : entity.slice(1),
100
+ hex ? 16 : 10
101
+ );
102
+ if (!Number.isFinite(code) || code < 0 || code > 1114111) return match;
103
+ return String.fromCodePoint(code);
104
+ }
105
+ return NAMED_ENTITIES[entity.toLowerCase()] ?? match;
106
+ }
107
+ );
108
+ }
109
+ function innerContent(document, tag, from) {
110
+ const pattern = new RegExp(`</${tag}\\s*>`, "gi");
111
+ pattern.lastIndex = from;
112
+ const match = pattern.exec(document);
113
+ return match ? document.slice(from, match.index) : "";
114
+ }
115
+
116
+ // src/rules.ts
117
+ var QUALITY_PLUGIN_NAME = "quality";
118
+ var RULE_CODES = {
119
+ imgAltMissing: "quality:img-alt-missing",
120
+ duplicateId: "quality:duplicate-id",
121
+ brokenInternalAnchor: "quality:broken-internal-anchor",
122
+ headingOrder: "quality:heading-order",
123
+ emptyLinkText: "quality:empty-link-text",
124
+ htmlLangMissing: "quality:html-lang-missing",
125
+ tableNoHeader: "quality:table-no-header"
126
+ };
127
+ function runInspection(html, options) {
128
+ if (!options.enabled) return [];
129
+ const masked = maskIgnoredRegions(html);
130
+ const context = {
131
+ html: masked,
132
+ elements: scanElements(masked)
133
+ };
134
+ return RULES.flatMap((rule) => rule(context)).filter(
135
+ (diagnostic) => !options.ignoreRules.has(diagnostic.code)
136
+ );
137
+ }
138
+ function inspectHtml(html, options = {}) {
139
+ return runInspection(html, resolveInspectOptions(options));
140
+ }
141
+ var RULES = [
142
+ imgAltMissing,
143
+ duplicateId,
144
+ brokenInternalAnchor,
145
+ headingOrder,
146
+ emptyLinkText,
147
+ htmlLangMissing,
148
+ tableNoHeader
149
+ ];
150
+ function imgAltMissing({ elements }) {
151
+ const diagnostics = [];
152
+ for (const element of elements) {
153
+ if (element.tag !== "img") continue;
154
+ if (element.attributes.has("alt")) continue;
155
+ diagnostics.push(
156
+ createDiagnostic(
157
+ RULE_CODES.imgAltMissing,
158
+ "warning",
159
+ "<img> is missing an alt attribute.",
160
+ {
161
+ target: "img",
162
+ suggestion: 'Add alt="..." describing the image, or alt="" for decorative images.'
163
+ }
164
+ )
165
+ );
166
+ }
167
+ return diagnostics;
168
+ }
169
+ function duplicateId({ elements }) {
170
+ const diagnostics = [];
171
+ const counts = /* @__PURE__ */ new Map();
172
+ for (const element of elements) {
173
+ const id = attribute(element, "id");
174
+ if (id === void 0 || id.trim() === "") continue;
175
+ const count = (counts.get(id) ?? 0) + 1;
176
+ counts.set(id, count);
177
+ if (count > 1) {
178
+ diagnostics.push(
179
+ createDiagnostic(
180
+ RULE_CODES.duplicateId,
181
+ "error",
182
+ `Duplicate id "${id}" is used ${count} times in the same document.`,
183
+ { target: id, suggestion: "Make each id unique within the page." }
184
+ )
185
+ );
186
+ }
187
+ }
188
+ return diagnostics;
189
+ }
190
+ function brokenInternalAnchor({ elements }) {
191
+ const diagnostics = [];
192
+ const ids = /* @__PURE__ */ new Set();
193
+ for (const element of elements) {
194
+ const id = attribute(element, "id");
195
+ if (id !== void 0 && id.trim() !== "") ids.add(id);
196
+ }
197
+ for (const element of elements) {
198
+ if (element.tag !== "a") continue;
199
+ const href = attribute(element, "href");
200
+ if (href === void 0 || !href.startsWith("#")) continue;
201
+ const target = href.slice(1);
202
+ if (target === "" || ids.has(target)) continue;
203
+ diagnostics.push(
204
+ createDiagnostic(
205
+ RULE_CODES.brokenInternalAnchor,
206
+ "warning",
207
+ `Link target "#${target}" has no matching id in the same document.`,
208
+ {
209
+ target: href,
210
+ suggestion: `Add an element with id="${target}" or fix the link.`
211
+ }
212
+ )
213
+ );
214
+ }
215
+ return diagnostics;
216
+ }
217
+ function headingOrder({ elements }) {
218
+ const levels = [];
219
+ for (const element of elements) {
220
+ const level = headingLevel(element.tag);
221
+ if (level !== null) levels.push(level);
222
+ }
223
+ if (levels.length === 0) return [];
224
+ const diagnostics = [];
225
+ if (!levels.includes(1)) {
226
+ diagnostics.push(
227
+ createDiagnostic(
228
+ RULE_CODES.headingOrder,
229
+ "warning",
230
+ "Document has headings but no <h1>.",
231
+ {
232
+ target: "h1",
233
+ suggestion: "Start the heading outline with a level-1 heading."
234
+ }
235
+ )
236
+ );
237
+ }
238
+ let previous = levels[0] ?? 1;
239
+ for (let index = 1; index < levels.length; index++) {
240
+ const current = levels[index] ?? previous;
241
+ if (current > previous + 1) {
242
+ diagnostics.push(
243
+ createDiagnostic(
244
+ RULE_CODES.headingOrder,
245
+ "warning",
246
+ `Heading level skips from h${previous} to h${current}.`,
247
+ {
248
+ target: `h${current}`,
249
+ suggestion: "Use consecutive heading levels to keep the outline valid."
250
+ }
251
+ )
252
+ );
253
+ }
254
+ previous = current;
255
+ }
256
+ return diagnostics;
257
+ }
258
+ function emptyLinkText({ elements }) {
259
+ const diagnostics = [];
260
+ for (const element of elements) {
261
+ if (element.tag !== "a") continue;
262
+ if (!element.attributes.has("href")) continue;
263
+ if (hasAccessibleName(element)) continue;
264
+ if (textContent(element.content).trim() !== "") continue;
265
+ diagnostics.push(
266
+ createDiagnostic(
267
+ RULE_CODES.emptyLinkText,
268
+ "warning",
269
+ "<a> has empty text and no accessible name.",
270
+ {
271
+ target: attribute(element, "href") ?? "a",
272
+ suggestion: "Add link text, an aria-label/title, or an image with a non-empty alt."
273
+ }
274
+ )
275
+ );
276
+ }
277
+ return diagnostics;
278
+ }
279
+ function htmlLangMissing({ elements }) {
280
+ const html = elements.find((element) => element.tag === "html");
281
+ if (!html) return [];
282
+ const lang = attribute(html, "lang");
283
+ if (lang !== void 0 && lang.trim() !== "") return [];
284
+ return [
285
+ createDiagnostic(
286
+ RULE_CODES.htmlLangMissing,
287
+ "warning",
288
+ "The <html> element is missing a non-empty lang attribute.",
289
+ {
290
+ target: "html",
291
+ suggestion: 'Set lang="..." (for example lang="en") on <html>.'
292
+ }
293
+ )
294
+ ];
295
+ }
296
+ function tableNoHeader({ elements }) {
297
+ const diagnostics = [];
298
+ for (const element of elements) {
299
+ if (element.tag !== "table") continue;
300
+ const cells = scanElements(element.content).filter(
301
+ (candidate) => candidate.tag === "td" || candidate.tag === "th"
302
+ );
303
+ if (cells.length === 0) continue;
304
+ const hasHeaderCell = cells.some((cell) => cell.tag === "th");
305
+ const hasScope = cells.some(
306
+ (cell) => cell.attributes.has("scope") || cell.attributes.has("headers")
307
+ );
308
+ if (hasHeaderCell || hasScope) continue;
309
+ diagnostics.push(
310
+ createDiagnostic(
311
+ RULE_CODES.tableNoHeader,
312
+ "warning",
313
+ "<table> has data cells but no header cell.",
314
+ {
315
+ target: "table",
316
+ suggestion: "Add a <th> header, or annotate cells with scope/headers."
317
+ }
318
+ )
319
+ );
320
+ }
321
+ return diagnostics;
322
+ }
323
+ function hasAccessibleName(element) {
324
+ if (hasNonEmptyAttribute(element, "aria-label")) return true;
325
+ if (hasNonEmptyAttribute(element, "title")) return true;
326
+ return scanElements(element.content).some(
327
+ (candidate) => candidate.tag === "img" && hasNonEmptyAttribute(candidate, "alt")
328
+ );
329
+ }
330
+ function headingLevel(tag) {
331
+ if (tag.length !== 2 || tag[0] !== "h") return null;
332
+ const level = Number.parseInt(tag[1] ?? "", 10);
333
+ return level >= 1 && level <= 6 ? level : null;
334
+ }
335
+ function createDiagnostic(code, severity, message, extra = {}) {
336
+ return {
337
+ code,
338
+ severity,
339
+ message,
340
+ pluginName: QUALITY_PLUGIN_NAME,
341
+ ...extra
342
+ };
343
+ }
344
+
345
+ // index.ts
346
+ function inspectGeneratedHtml(page, options = {}) {
347
+ return inspectHtml(page.html, options).map((diagnostic) => ({
348
+ ...diagnostic,
349
+ filePath: page.path
350
+ }));
351
+ }
352
+ function qualityPlugin(options = {}) {
353
+ const resolved = resolveQualityOptions(options);
354
+ const inspectOptions = {
355
+ ignoreRules: options.ignoreRules,
356
+ a11y: options.a11y
357
+ };
358
+ return definePlugin({
359
+ name: QUALITY_PLUGIN_NAME,
360
+ options,
361
+ onManifestCreated: ({ manifest, diagnostics }) => {
362
+ if (!resolved.inspect.enabled) return;
363
+ for (const entry of manifest.publicEntries) {
364
+ for (const diagnostic of runInspection(entry.html, resolved.inspect)) {
365
+ diagnostics.push({
366
+ ...diagnostic,
367
+ slug: entry.slug,
368
+ filePath: entry.publicLocation?.permalink
369
+ });
370
+ }
371
+ }
372
+ },
373
+ inspectGeneratedHtml: (page) => inspectGeneratedHtml(page, inspectOptions),
374
+ onBuildEnd: ({ manifest }) => {
375
+ if (resolved.failOn !== "error") return;
376
+ const errors = manifest.diagnostics.filter(
377
+ (diagnostic) => diagnostic.pluginName === QUALITY_PLUGIN_NAME && diagnostic.severity === "error"
378
+ );
379
+ if (errors.length > 0) {
380
+ const details = errors.map((diagnostic) => `- ${diagnostic.message}`).join("\n");
381
+ throw new Error(
382
+ `Quality inspection failed with ${errors.length} error diagnostic(s):
383
+ ${details}`
384
+ );
385
+ }
386
+ }
387
+ });
388
+ }
389
+ var quality = qualityPlugin;
390
+ export {
391
+ QUALITY_PLUGIN_NAME,
392
+ RULE_CODES,
393
+ inspectGeneratedHtml,
394
+ inspectHtml,
395
+ quality,
396
+ qualityPlugin
397
+ };
@@ -0,0 +1,11 @@
1
+ import type { InspectOptions, QualityOptions, ResolvedInspectOptions, ResolvedQualityOptions } from "./types.js";
2
+ /**
3
+ * Normalizes inspection options. Accessibility inspection is on by default and
4
+ * must be disabled explicitly with `a11y: { enabled: false }`.
5
+ */
6
+ export declare function resolveInspectOptions(options?: InspectOptions): ResolvedInspectOptions;
7
+ /**
8
+ * Normalizes plugin options. `failOn` defaults to `"never"`, matching the
9
+ * diagnostics plugin's opt-in failure behavior.
10
+ */
11
+ export declare function resolveQualityOptions(options?: QualityOptions): ResolvedQualityOptions;
@@ -0,0 +1,27 @@
1
+ import type { Diagnostic } from "@riebeckite/core";
2
+ import type { InspectOptions, ResolvedInspectOptions } from "./types.js";
3
+ export declare const QUALITY_PLUGIN_NAME = "quality";
4
+ /**
5
+ * Stable diagnostic codes emitted by this package. Codes are part of the
6
+ * public contract and must not change without a major version bump.
7
+ */
8
+ export declare const RULE_CODES: {
9
+ readonly imgAltMissing: "quality:img-alt-missing";
10
+ readonly duplicateId: "quality:duplicate-id";
11
+ readonly brokenInternalAnchor: "quality:broken-internal-anchor";
12
+ readonly headingOrder: "quality:heading-order";
13
+ readonly emptyLinkText: "quality:empty-link-text";
14
+ readonly htmlLangMissing: "quality:html-lang-missing";
15
+ readonly tableNoHeader: "quality:table-no-header";
16
+ };
17
+ export type RuleCode = (typeof RULE_CODES)[keyof typeof RULE_CODES];
18
+ /**
19
+ * Runs every rule against an HTML document. This is the internal entry point;
20
+ * prefer {@link inspectHtml} for the public API.
21
+ */
22
+ export declare function runInspection(html: string, options: ResolvedInspectOptions): Diagnostic[];
23
+ /**
24
+ * Inspects an HTML string and returns the quality diagnostics it violates.
25
+ * Purely functional: the input is never mutated and no filesystem is touched.
26
+ */
27
+ export declare function inspectHtml(html: string, options?: InspectOptions): Diagnostic[];
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Minimal, dependency-free HTML scanning helpers.
3
+ *
4
+ * This is intentionally *not* a spec-compliant HTML parser. It uses regular
5
+ * expressions to find start tags and their attributes, which is enough for the
6
+ * static quality rules in this package but does not model the DOM. Rules that
7
+ * need identical tag pairing (for example `<a>` text content) only work for
8
+ * well-formed, non-nested markup. See the package README for the limitations.
9
+ */
10
+ export type HtmlElement = {
11
+ /** Lowercase tag name. */
12
+ tag: string;
13
+ /** Attributes keyed by lowercase name. The first occurrence wins. */
14
+ attributes: Map<string, string>;
15
+ /** Raw tag text including `<` and `>`. */
16
+ raw: string;
17
+ /** Index of `<` within the scanned document. */
18
+ start: number;
19
+ /** Index just past the closing `>`. */
20
+ end: number;
21
+ /** Inner HTML between the open and close tags. Empty for void elements. */
22
+ content: string;
23
+ };
24
+ /**
25
+ * Replaces comments and the contents of `<script>`/`<style>` elements with
26
+ * spaces of the same length so byte offsets stay aligned with the original
27
+ * document. This keeps code samples from producing phantom attribute matches.
28
+ */
29
+ export declare function maskIgnoredRegions(html: string): string;
30
+ /**
31
+ * Scans start tags in document order. Tags inside masked regions are already
32
+ * removed by {@link maskIgnoredRegions}.
33
+ */
34
+ export declare function scanElements(document: string): HtmlElement[];
35
+ /** Parses an attribute list into a lowercase-keyed map. */
36
+ export declare function parseAttributes(text: string): Map<string, string>;
37
+ /** Extracts text content, dropping tags and decoding common entities. */
38
+ export declare function textContent(fragment: string): string;
39
+ /** Returns the raw attribute value, or `undefined` when it is absent. */
40
+ export declare function attribute(element: HtmlElement, name: string): string | undefined;
41
+ /** True when the attribute is present and its value is not blank. */
42
+ export declare function hasNonEmptyAttribute(element: HtmlElement, name: string): boolean;
43
+ /** Decodes a small set of named and numeric HTML entities. */
44
+ export declare function decodeHtmlEntities(value: string): string;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Options shared by the pure inspection helpers and the plugin factory.
3
+ */
4
+ export type InspectOptions = {
5
+ /**
6
+ * Diagnostic codes to suppress. Matching is exact, so pass values such as
7
+ * `"quality:img-alt-missing"`.
8
+ */
9
+ ignoreRules?: readonly string[];
10
+ /**
11
+ * Accessibility inspection settings. When `enabled` is `false` every rule is
12
+ * skipped and no diagnostics are produced.
13
+ */
14
+ a11y?: {
15
+ enabled?: boolean;
16
+ };
17
+ };
18
+ /**
19
+ * Options for {@link qualityPlugin}. Extends the inspection options with a
20
+ * build-failure policy.
21
+ */
22
+ export type QualityOptions = InspectOptions & {
23
+ /**
24
+ * `"error"` fails the build when the plugin produced an error-severity
25
+ * diagnostic during the manifest stage. Defaults to `"never"`.
26
+ */
27
+ failOn?: "error" | "never";
28
+ };
29
+ /**
30
+ * Normalized inspection options. Internal to the plugin implementation.
31
+ */
32
+ export type ResolvedInspectOptions = {
33
+ enabled: boolean;
34
+ ignoreRules: ReadonlySet<string>;
35
+ };
36
+ /**
37
+ * Normalized plugin options. Internal to the plugin implementation.
38
+ */
39
+ export type ResolvedQualityOptions = {
40
+ inspect: ResolvedInspectOptions;
41
+ failOn: "error" | "never";
42
+ };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@riebeckite/plugin-quality",
3
+ "version": "0.0.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "source": "./index.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "dependencies": {
17
+ "@riebeckite/core": "0.0.1"
18
+ },
19
+ "devDependencies": {
20
+ "tsx": "^4.22.4"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "files": [
26
+ "LICENSE",
27
+ "README.md",
28
+ "README_ja.md",
29
+ "dist"
30
+ ],
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Rerurate514/riebeckite.git",
34
+ "directory": "packages/plugins/quality"
35
+ },
36
+ "homepage": "https://github.com/Rerurate514/riebeckite#readme",
37
+ "bugs": {
38
+ "url": "https://github.com/Rerurate514/riebeckite/issues"
39
+ },
40
+ "description": "Static quality and accessibility inspection for Riebeckite HTML.",
41
+ "keywords": [
42
+ "riebeckite",
43
+ "plugin",
44
+ "accessibility",
45
+ "quality"
46
+ ],
47
+ "engines": {
48
+ "node": "^20.19.0 || >=22.12.0"
49
+ },
50
+ "sideEffects": false,
51
+ "scripts": {
52
+ "build": "node ../../../scripts/build_package.mjs",
53
+ "test": "node --import tsx --test \"test/*.test.ts\""
54
+ }
55
+ }