@brimsites/brimjs 0.0.0-stage → 1.0.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.
- package/LICENSE +110 -0
- package/README.md +22 -2
- package/bin/brim.js +5 -0
- package/dist/cli.js +3802 -0
- package/editor-dist/editor.css +1 -0
- package/editor-dist/editor.js +91 -0
- package/package.json +71 -3
- package/skills/brim-convert/SKILL.md +256 -0
- package/skills/brim-hosting/SKILL.md +221 -0
- package/src/astro-shim.d.ts +5 -0
- package/src/auth/accounts.ts +341 -0
- package/src/auth/password.ts +34 -0
- package/src/auth/permissions.ts +44 -0
- package/src/blocks/accordion/Accordion.astro +48 -0
- package/src/blocks/accordion/accordion.css +63 -0
- package/src/blocks/analytics/Analytics.astro +45 -0
- package/src/blocks/analytics/ConsentBanner.astro +41 -0
- package/src/blocks/analytics/analytics.client.ts +125 -0
- package/src/blocks/analytics/analytics.css +51 -0
- package/src/blocks/analytics/consent.ts +51 -0
- package/src/blocks/button/Button.astro +64 -0
- package/src/blocks/button/button.css +100 -0
- package/src/blocks/carousel/Carousel.astro +140 -0
- package/src/blocks/carousel/carousel.client.ts +153 -0
- package/src/blocks/carousel/carousel.css +181 -0
- package/src/blocks/data/icons.ts +285 -0
- package/src/blocks/data/image-shapes.ts +91 -0
- package/src/blocks/data/social-icons.ts +41 -0
- package/src/blocks/data/social-networks.ts +256 -0
- package/src/blocks/divider/Divider.astro +27 -0
- package/src/blocks/divider/divider.css +17 -0
- package/src/blocks/form/Captcha.astro +27 -0
- package/src/blocks/form/Form.astro +250 -0
- package/src/blocks/form/FormField.astro +138 -0
- package/src/blocks/form/Newsletter.astro +80 -0
- package/src/blocks/form/form.client.ts +339 -0
- package/src/blocks/form/form.css +271 -0
- package/src/blocks/gallery/ImageGallery.astro +126 -0
- package/src/blocks/gallery/gallery.css +43 -0
- package/src/blocks/gallery/lightbox.client.ts +178 -0
- package/src/blocks/gallery/lightbox.css +134 -0
- package/src/blocks/icon/Icon.astro +41 -0
- package/src/blocks/icon/icon.css +16 -0
- package/src/blocks/image/Image.astro +158 -0
- package/src/blocks/image/image.css +42 -0
- package/src/blocks/images.ts +64 -0
- package/src/blocks/in-editor.client.ts +8 -0
- package/src/blocks/listing/Listing.astro +288 -0
- package/src/blocks/listing/ListingCards.astro +48 -0
- package/src/blocks/listing/listing.css +136 -0
- package/src/blocks/listing/query.ts +363 -0
- package/src/blocks/map/Map.astro +75 -0
- package/src/blocks/map/map.css +32 -0
- package/src/blocks/schemas/accordion.ts +118 -0
- package/src/blocks/schemas/button.ts +78 -0
- package/src/blocks/schemas/carousel.ts +133 -0
- package/src/blocks/schemas/divider.ts +29 -0
- package/src/blocks/schemas/form-field-types.ts +29 -0
- package/src/blocks/schemas/form.ts +350 -0
- package/src/blocks/schemas/icon.ts +24 -0
- package/src/blocks/schemas/image-gallery.ts +54 -0
- package/src/blocks/schemas/image.ts +87 -0
- package/src/blocks/schemas/index.ts +33 -0
- package/src/blocks/schemas/listing.ts +14 -0
- package/src/blocks/schemas/map.ts +81 -0
- package/src/blocks/schemas/newsletter.ts +324 -0
- package/src/blocks/schemas/social-media.ts +348 -0
- package/src/blocks/schemas/text.ts +151 -0
- package/src/blocks/schemas/video.ts +57 -0
- package/src/blocks/search/Search.astro +147 -0
- package/src/blocks/search/search.css +69 -0
- package/src/blocks/search/state.ts +28 -0
- package/src/blocks/settings.ts +94 -0
- package/src/blocks/social/SocialMedia.astro +102 -0
- package/src/blocks/social/social-links.ts +16 -0
- package/src/blocks/social/social.css +31 -0
- package/src/blocks/theme.ts +35 -0
- package/src/blocks/types.ts +52 -0
- package/src/blocks/video/Video.astro +90 -0
- package/src/blocks/video/video-source.ts +77 -0
- package/src/blocks/video/video.client.ts +43 -0
- package/src/blocks/video/video.css +29 -0
- package/src/check.ts +1119 -0
- package/src/cli.ts +493 -0
- package/src/components/Blocks.astro +68 -0
- package/src/components/Field.astro +61 -0
- package/src/components/Footer.astro +36 -0
- package/src/components/Link.astro +18 -0
- package/src/components/MobileMenu.astro +77 -0
- package/src/components/Navbar.astro +42 -0
- package/src/components/RichText.astro +32 -0
- package/src/components/Seo.astro +202 -0
- package/src/components/Setting.astro +46 -0
- package/src/components/Shared.astro +17 -0
- package/src/components/Text.astro +91 -0
- package/src/components/blocks.css +86 -0
- package/src/components/index.ts +27 -0
- package/src/components/mobile-menu.client.ts +21 -0
- package/src/components/mobile-menu.css +52 -0
- package/src/components/text.css +48 -0
- package/src/config.ts +413 -0
- package/src/content/block-layout.ts +63 -0
- package/src/content/block-values.ts +48 -0
- package/src/content/content-check.ts +174 -0
- package/src/content/content-types.ts +408 -0
- package/src/content/drafts.ts +115 -0
- package/src/content/feed.ts +237 -0
- package/src/content/field-types.ts +107 -0
- package/src/content/history.ts +140 -0
- package/src/content/ids.ts +50 -0
- package/src/content/image-size.ts +212 -0
- package/src/content/image-sizes.ts +126 -0
- package/src/content/item-fields.ts +110 -0
- package/src/content/item-head.ts +126 -0
- package/src/content/item-image.ts +26 -0
- package/src/content/item-path.ts +122 -0
- package/src/content/items.ts +580 -0
- package/src/content/language-scopes.ts +40 -0
- package/src/content/media.ts +271 -0
- package/src/content/menus.ts +51 -0
- package/src/content/page-templates.ts +52 -0
- package/src/content/redirects.ts +112 -0
- package/src/content/references.ts +165 -0
- package/src/content/rich-text.ts +63 -0
- package/src/content/search.ts +167 -0
- package/src/content/seed.ts +229 -0
- package/src/content/site-settings.ts +111 -0
- package/src/content/sitemap.ts +143 -0
- package/src/content/store.ts +225 -0
- package/src/content/tags.ts +67 -0
- package/src/content/text-default.ts +139 -0
- package/src/content/types.ts +137 -0
- package/src/content/validate.ts +253 -0
- package/src/content/validation-error.ts +2 -0
- package/src/db/cached.ts +140 -0
- package/src/db/database.ts +15 -0
- package/src/db/libsql.ts +29 -0
- package/src/db/schema.ts +189 -0
- package/src/db/url.ts +44 -0
- package/src/editor/client/BlockSettings.tsx +1063 -0
- package/src/editor/client/Chrome.tsx +284 -0
- package/src/editor/client/ContentBrowser.tsx +1299 -0
- package/src/editor/client/Editor.tsx +1756 -0
- package/src/editor/client/HistoryPanel.tsx +114 -0
- package/src/editor/client/ImagesWidget.tsx +113 -0
- package/src/editor/client/Inspector.tsx +127 -0
- package/src/editor/client/ItemForm.tsx +535 -0
- package/src/editor/client/LinkWidget.tsx +440 -0
- package/src/editor/client/ListingPanel.tsx +99 -0
- package/src/editor/client/Login.tsx +338 -0
- package/src/editor/client/Menu.tsx +64 -0
- package/src/editor/client/PageSettings.tsx +270 -0
- package/src/editor/client/RedirectsSettings.tsx +130 -0
- package/src/editor/client/Resize.tsx +204 -0
- package/src/editor/client/Sidebar.tsx +51 -0
- package/src/editor/client/SiteMap.tsx +568 -0
- package/src/editor/client/SiteSettings.tsx +409 -0
- package/src/editor/client/TextTools.tsx +391 -0
- package/src/editor/client/Toolbar.tsx +449 -0
- package/src/editor/client/VideoUpload.tsx +251 -0
- package/src/editor/client/api.ts +417 -0
- package/src/editor/client/brand.ts +20 -0
- package/src/editor/client/connection.ts +98 -0
- package/src/editor/client/context.ts +19 -0
- package/src/editor/client/css.d.ts +2 -0
- package/src/editor/client/editor.css +4656 -0
- package/src/editor/client/fields.tsx +812 -0
- package/src/editor/client/icons.tsx +174 -0
- package/src/editor/client/keys.ts +15 -0
- package/src/editor/client/kinds.ts +289 -0
- package/src/editor/client/languages.ts +32 -0
- package/src/editor/client/main.tsx +100 -0
- package/src/editor/client/responses.ts +26 -0
- package/src/editor/client/rich-text.ts +326 -0
- package/src/editor/client/site-tree.ts +239 -0
- package/src/editor/client/theme.ts +55 -0
- package/src/editor/client/tsconfig.json +18 -0
- package/src/editor/client/tus.ts +137 -0
- package/src/editor/client/use-rect.ts +50 -0
- package/src/editor/client/widgets.tsx +1218 -0
- package/src/forms/captcha.ts +83 -0
- package/src/forms/define.ts +166 -0
- package/src/forms/fields.ts +197 -0
- package/src/forms/file-types.ts +108 -0
- package/src/forms/files.ts +216 -0
- package/src/forms/form-page.ts +9 -0
- package/src/forms/handler.ts +622 -0
- package/src/forms/spec.ts +89 -0
- package/src/forms/store.ts +96 -0
- package/src/forms/work.ts +50 -0
- package/src/icons/library.ts +144 -0
- package/src/icons/load.ts +63 -0
- package/src/index.ts +99 -0
- package/src/init.ts +257 -0
- package/src/integration.ts +469 -0
- package/src/mail/mailer.ts +197 -0
- package/src/mail/notify.ts +272 -0
- package/src/mail/settings.ts +173 -0
- package/src/mail/templates.ts +191 -0
- package/src/mcp/page-nodes.ts +209 -0
- package/src/mcp/server.ts +111 -0
- package/src/mcp/tools.ts +637 -0
- package/src/runtime/TemplatePage.astro +39 -0
- package/src/runtime/TemplatePageStatic.astro +13 -0
- package/src/runtime/admin-route.ts +80 -0
- package/src/runtime/connect.ts +53 -0
- package/src/runtime/content.ts +188 -0
- package/src/runtime/context.ts +131 -0
- package/src/runtime/form-files.ts +18 -0
- package/src/runtime/forms-route.ts +33 -0
- package/src/runtime/forms.ts +28 -0
- package/src/runtime/icons.ts +5 -0
- package/src/runtime/media.ts +175 -0
- package/src/runtime/middleware.ts +186 -0
- package/src/runtime/nav.ts +13 -0
- package/src/runtime/query-reads.ts +49 -0
- package/src/runtime/query-store.ts +16 -0
- package/src/runtime/request-state.ts +69 -0
- package/src/runtime/robots.ts +29 -0
- package/src/runtime/rss-static.ts +16 -0
- package/src/runtime/rss.ts +29 -0
- package/src/runtime/server.ts +29 -0
- package/src/runtime/sitemap.ts +34 -0
- package/src/runtime/template-paths.ts +34 -0
- package/src/runtime/uploads-route.ts +13 -0
- package/src/seed-cli.ts +253 -0
- package/src/server/auth.ts +31 -0
- package/src/server/fetch-image.ts +219 -0
- package/src/server/handler.ts +2106 -0
- package/src/server/http.ts +162 -0
- package/src/server/locales.ts +73 -0
- package/src/server/node.ts +57 -0
- package/src/server/query-params.ts +249 -0
- package/src/server/rate-limit.ts +72 -0
- package/src/server/video-host.ts +162 -0
- package/src/starter.ts +70 -0
- package/src/version.ts +4 -0
- package/src/virtual.d.ts +65 -0
package/src/check.ts
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { dirname, extname, join, relative, resolve, sep } from "node:path";
|
|
3
|
+
import { isUnchanged, type StarterFile, starterManifest } from "./starter.ts";
|
|
4
|
+
import { queryPathsInConfig, undeclaredQueryReads } from "./server/query-params.ts";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* `brim check`: reads a site's source and reports what would make the owner's edits go wrong, without
|
|
8
|
+
* building or running it. Owner edits are stored under (scope, nodeId), so two elements with one id on a page
|
|
9
|
+
* share one edit, and an id that names a position stops fitting once the markup moves. It reads the source with
|
|
10
|
+
* a small tokenizer instead of Astro's compiler: it only needs elements, their attributes and imports.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type Severity = "error" | "warning";
|
|
14
|
+
|
|
15
|
+
export interface Finding {
|
|
16
|
+
/** Relative to the site's folder, with forward slashes. */
|
|
17
|
+
file: string;
|
|
18
|
+
line?: number;
|
|
19
|
+
severity: Severity;
|
|
20
|
+
rule:
|
|
21
|
+
| "duplicate"
|
|
22
|
+
| "site-duplicate"
|
|
23
|
+
| "positional"
|
|
24
|
+
| "format"
|
|
25
|
+
| "starter"
|
|
26
|
+
| "uploads-in-code"
|
|
27
|
+
| "contact-in-code"
|
|
28
|
+
| "saved-password"
|
|
29
|
+
| "no-git"
|
|
30
|
+
| "vocabulary-page"
|
|
31
|
+
| "hand-drawn-image"
|
|
32
|
+
| "fixed-image-size"
|
|
33
|
+
| "large-public-image"
|
|
34
|
+
| "image-sizes"
|
|
35
|
+
| "no-sharp"
|
|
36
|
+
| "order-field"
|
|
37
|
+
| "text-only-body"
|
|
38
|
+
| "undeclared-query";
|
|
39
|
+
nodeId?: string;
|
|
40
|
+
message: string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface CheckReport {
|
|
44
|
+
files: number;
|
|
45
|
+
/** Elements with a nodeId written as a literal. */
|
|
46
|
+
literalIds: number;
|
|
47
|
+
/** Elements whose nodeId is built at run time (``nodeId={`${id}-title`}``). */
|
|
48
|
+
dynamicIds: number;
|
|
49
|
+
/** Of those, how many were checked anyway because every use passes the prefix as a literal (`id="home-hero"`). */
|
|
50
|
+
resolvedDynamicIds: number;
|
|
51
|
+
findings: Finding[];
|
|
52
|
+
/**
|
|
53
|
+
* Starter files still unchanged that hold the site's structure rather than its content (the layout, styles,
|
|
54
|
+
* content types): expected to stay, so they are listed here instead of as warnings.
|
|
55
|
+
*/
|
|
56
|
+
starterStructure: string[];
|
|
57
|
+
errors: number;
|
|
58
|
+
warnings: number;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface CheckOptions {
|
|
62
|
+
/** Defaults to what create-brim's template contains. */
|
|
63
|
+
starter?: StarterFile[];
|
|
64
|
+
/** Whether to warn when the site is not in git; on unless a caller checks a folder that is never a site. */
|
|
65
|
+
git?: boolean;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Files in which Astro and MDX let primitives appear as elements. Plain .ts/.js files cannot draw them. */
|
|
69
|
+
const SOURCE_EXTENSIONS = [".astro", ".tsx", ".jsx", ".mdx"];
|
|
70
|
+
// The order Vite tries when an import leaves the extension out.
|
|
71
|
+
const RESOLVE_EXTENSIONS = [".astro", ".tsx", ".ts", ".jsx", ".js", ".mdx"];
|
|
72
|
+
const SKIPPED_FOLDERS = new Set(["node_modules", ".git", ".astro", "dist"]);
|
|
73
|
+
/** Every file of the code that can hold an address: data modules and JSON too, not only markup. */
|
|
74
|
+
const CODE_EXTENSIONS = [...RESOLVE_EXTENSIONS, ".mjs", ".cjs", ".json"];
|
|
75
|
+
/**
|
|
76
|
+
* Contact details written into the code: an email or phone link, WhatsApp, or a social profile. They are the owner's
|
|
77
|
+
* to change, so they belong in the site's own settings (src/site-settings.ts), which that file itself may declare.
|
|
78
|
+
*/
|
|
79
|
+
const CONTACT_ADDRESS =
|
|
80
|
+
/(?:mailto:|tel:|wa\.me\/|api\.whatsapp\.com|(?:instagram|facebook|tiktok|linkedin|youtube|pinterest|x|twitter)\.com\/)[^"'`\s]*/g;
|
|
81
|
+
const SETTINGS_MODULE = /(?:^|\/)src\/site-settings\.[cm]?[jt]s$/;
|
|
82
|
+
|
|
83
|
+
/** A media library address written as a string: `"/uploads/…"`, `'/uploads/…'` or in a template literal. */
|
|
84
|
+
const UPLOAD_ADDRESS = /["'`](?:https?:\/\/[^"'`\s/]+)?\/uploads\/[^"'`\s]+/g;
|
|
85
|
+
|
|
86
|
+
/** Components whose content is always saved for the whole site, whatever their `scope`. */
|
|
87
|
+
const ALWAYS_SITE = new Set(["Navbar", "Footer"]);
|
|
88
|
+
/** Components saved for the whole site unless `scope` says otherwise. */
|
|
89
|
+
const SITE_BY_DEFAULT = new Set(["Newsletter", "SocialMedia"]);
|
|
90
|
+
|
|
91
|
+
const TAGS = (
|
|
92
|
+
"div span p a img h1 h2 h3 h4 h5 h6 li ul ol section article header footer nav main aside button " +
|
|
93
|
+
"figure figcaption picture svg strong em b i small label input form table tr td th blockquote"
|
|
94
|
+
).split(" ");
|
|
95
|
+
// prettier-ignore
|
|
96
|
+
const GENERIC_WORDS = (
|
|
97
|
+
"text item block element el elem node component child entry " +
|
|
98
|
+
"row col column cell box wrapper wrap container group"
|
|
99
|
+
).split(" ");
|
|
100
|
+
// `text-3`, `hero-p-2`, `div4`, `item-2-title`: a tag or a generic word followed by a number names a position.
|
|
101
|
+
const POSITIONAL = new RegExp(`(?:^|-)(?:${[...TAGS, ...GENERIC_WORDS].join("|")})-?\\d+(?:-|$)`);
|
|
102
|
+
const UUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
103
|
+
const LONG_HEX = /(?:^|-)(?=[0-9a-f]*\d)[0-9a-f]{12,}(?:-|$)/;
|
|
104
|
+
/** The rule in the brim-convert skill: lowercase letters, digits and dashes, starting with a letter, at most 64. */
|
|
105
|
+
const VALID_ID = /^[a-z][a-z0-9-]{0,63}$/;
|
|
106
|
+
|
|
107
|
+
export function checkSite(siteFolder: string, options: CheckOptions = {}): CheckReport {
|
|
108
|
+
const root = resolve(siteFolder);
|
|
109
|
+
const sourceFolder = join(root, "src");
|
|
110
|
+
if (!existsSync(sourceFolder)) {
|
|
111
|
+
throw new Error(`There is no src folder in ${siteFolder}. Run brim check from the site's folder.`);
|
|
112
|
+
}
|
|
113
|
+
const files = listSources(sourceFolder).map((path) => relative(root, path).split(sep).join("/"));
|
|
114
|
+
const sources = new Map(files.map((file) => [file, parseSource(file, readFileSync(join(root, file), "utf8"))]));
|
|
115
|
+
const findings: Finding[] = [];
|
|
116
|
+
const add = (finding: Finding) => findings.push(finding);
|
|
117
|
+
|
|
118
|
+
let literalIds = 0;
|
|
119
|
+
let dynamicIds = 0;
|
|
120
|
+
for (const [file, source] of sources) {
|
|
121
|
+
for (const element of source.elements) {
|
|
122
|
+
const id = element.nodeId;
|
|
123
|
+
if (!id) continue;
|
|
124
|
+
if (id.kind !== "literal") {
|
|
125
|
+
dynamicIds++;
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
literalIds++;
|
|
129
|
+
checkName(file, element.line, id.value, add);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const resolved = new Set<string>();
|
|
134
|
+
const closures = files.map((file) => ({ file, occurrences: collect(file, sources, resolved) }));
|
|
135
|
+
findDuplicates(closures, add);
|
|
136
|
+
findSiteDuplicates(closures, add);
|
|
137
|
+
const starterStructure = findStarterLeftovers(root, options.starter ?? starterManifest(), add);
|
|
138
|
+
findUploadsInCode(root, sourceFolder, add);
|
|
139
|
+
findContactsInCode(root, sourceFolder, add);
|
|
140
|
+
findSavedPasswords(root, add);
|
|
141
|
+
findVocabularyPages(root, sourceFolder, add);
|
|
142
|
+
findHandDrawnImages(root, sourceFolder, add);
|
|
143
|
+
findFixedImageSizes(root, sourceFolder, add);
|
|
144
|
+
findLargePublicImages(root, add);
|
|
145
|
+
findImagesWithoutSizes(root, sourceFolder, add);
|
|
146
|
+
findMissingSharp(root, add);
|
|
147
|
+
findOrderFields(root, sourceFolder, add);
|
|
148
|
+
findTextOnlyBodies(root, sourceFolder, add);
|
|
149
|
+
findUndeclaredQueryReads(root, sourceFolder, add);
|
|
150
|
+
if (options.git !== false && !insideGit(root)) {
|
|
151
|
+
add({
|
|
152
|
+
file: ".",
|
|
153
|
+
severity: "warning",
|
|
154
|
+
rule: "no-git",
|
|
155
|
+
message:
|
|
156
|
+
"the site is not in git: run `git init` and commit, so every change can be seen, reviewed and taken back " +
|
|
157
|
+
"(the local database and uploads stay out, as .gitignore says)",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) || (a.line ?? 0) - (b.line ?? 0));
|
|
162
|
+
const errors = findings.filter((finding) => finding.severity === "error").length;
|
|
163
|
+
return {
|
|
164
|
+
files: files.length,
|
|
165
|
+
literalIds,
|
|
166
|
+
dynamicIds,
|
|
167
|
+
resolvedDynamicIds: resolved.size,
|
|
168
|
+
findings,
|
|
169
|
+
starterStructure,
|
|
170
|
+
errors,
|
|
171
|
+
warnings: findings.length - errors,
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** One line per finding, grouped by file, then a summary. */
|
|
176
|
+
export function formatReport(report: CheckReport): string {
|
|
177
|
+
const lines: string[] = [];
|
|
178
|
+
let file: string | undefined;
|
|
179
|
+
for (const finding of report.findings) {
|
|
180
|
+
if (finding.file !== file) {
|
|
181
|
+
if (file !== undefined) lines.push("");
|
|
182
|
+
file = finding.file;
|
|
183
|
+
lines.push(file);
|
|
184
|
+
}
|
|
185
|
+
const line = finding.line === undefined ? "" : String(finding.line);
|
|
186
|
+
lines.push(` ${line.padStart(4)} ${finding.severity.padEnd(7)} ${finding.message}`);
|
|
187
|
+
}
|
|
188
|
+
if (lines.length > 0) lines.push("");
|
|
189
|
+
|
|
190
|
+
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
191
|
+
lines.push(
|
|
192
|
+
`${plural(report.errors, "error")}, ${plural(report.warnings, "warning")} in ${plural(report.files, "file")} ` +
|
|
193
|
+
`(${plural(report.literalIds, "literal nodeId")}).`,
|
|
194
|
+
);
|
|
195
|
+
if (report.dynamicIds > 0) {
|
|
196
|
+
const unchecked = report.dynamicIds - report.resolvedDynamicIds;
|
|
197
|
+
lines.push(
|
|
198
|
+
`${plural(report.dynamicIds, "nodeId")} built at run time (\`\${id}-title\`): ` +
|
|
199
|
+
`${report.resolvedDynamicIds} checked through the literal props passed to them, ${unchecked} not checked.`,
|
|
200
|
+
);
|
|
201
|
+
}
|
|
202
|
+
if (report.starterStructure.length > 0) {
|
|
203
|
+
lines.push(
|
|
204
|
+
`${plural(report.starterStructure.length, "structural starter file")} (layout, styles, content types) ` +
|
|
205
|
+
"unchanged; that is expected.",
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
return lines.join("\n");
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function checkName(file: string, line: number, id: string, add: (finding: Finding) => void): void {
|
|
212
|
+
if (!VALID_ID.test(id)) {
|
|
213
|
+
add({
|
|
214
|
+
file,
|
|
215
|
+
line,
|
|
216
|
+
severity: "warning",
|
|
217
|
+
rule: "format",
|
|
218
|
+
nodeId: id,
|
|
219
|
+
message: `nodeId "${id}" should be lowercase letters, digits and dashes, start with a letter, at most 64 characters`,
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
if (UUID.test(id) || LONG_HEX.test(id)) {
|
|
223
|
+
add({
|
|
224
|
+
file,
|
|
225
|
+
line,
|
|
226
|
+
severity: "warning",
|
|
227
|
+
rule: "positional",
|
|
228
|
+
nodeId: id,
|
|
229
|
+
message: `nodeId "${id}" contains a generated id; name it for what the element is (hero-title)`,
|
|
230
|
+
});
|
|
231
|
+
} else if (POSITIONAL.test(id.toLowerCase())) {
|
|
232
|
+
add({
|
|
233
|
+
file,
|
|
234
|
+
line,
|
|
235
|
+
severity: "warning",
|
|
236
|
+
rule: "positional",
|
|
237
|
+
nodeId: id,
|
|
238
|
+
message: `nodeId "${id}" names a position, not what the element is (hero-title rather than text-3)`,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** Text files a password could have been written into; `.env` files hold secrets by design and are not read. */
|
|
244
|
+
const NOTE_FILE = /\.(txt|md|json|ya?ml|csv|ini|cfg|conf)$|^[^.]+$/i;
|
|
245
|
+
const SKIPPED_NOTES = new Set(["pnpm-lock.yaml", "package-lock.json", "yarn.lock", "package.json", "tsconfig.json"]);
|
|
246
|
+
// A word for a password (`password`, `parola`, `pwd`…), a colon or equals sign, and a value on the same line. // betterleaks:allow
|
|
247
|
+
const PASSWORD_LINE =
|
|
248
|
+
/(?<!\p{L})(?:pass(?:word)?|parol[aă]|pwd|passwd|mot de passe|contraseña)(?!\p{L})["']?\s*[:=]\s*["']?[^\s"',{}]{4,}/iu;
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Warns about passwords written into files of the project (a note left after creating a user, a login file): the
|
|
252
|
+
* folder travels (a zip, a deploy, a repository) and the password with it. Sign-in links replace them.
|
|
253
|
+
*/
|
|
254
|
+
function findSavedPasswords(root: string, add: (finding: Finding) => void): void {
|
|
255
|
+
const walk = (folder: string): void => {
|
|
256
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
257
|
+
const path = join(folder, entry.name);
|
|
258
|
+
if (entry.isDirectory()) {
|
|
259
|
+
if (!SKIPPED_FOLDERS.has(entry.name) && entry.name !== "uploads" && entry.name !== "src") walk(path);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
if (!NOTE_FILE.test(entry.name) || SKIPPED_NOTES.has(entry.name) || entry.name.startsWith(".env")) continue;
|
|
263
|
+
if (statSync(path).size > 200_000) continue;
|
|
264
|
+
const lines = readFileSync(path, "utf8").split("\n");
|
|
265
|
+
const line = lines.findIndex((text) => PASSWORD_LINE.test(text));
|
|
266
|
+
if (line === -1) continue;
|
|
267
|
+
add({
|
|
268
|
+
file: relative(root, path).split(sep).join("/"),
|
|
269
|
+
line: line + 1,
|
|
270
|
+
severity: "error",
|
|
271
|
+
rule: "saved-password",
|
|
272
|
+
message:
|
|
273
|
+
"a password written in a file: whoever gets the folder (a zip, a deploy, a repository) gets it too. Delete " +
|
|
274
|
+
"it, change that password, and sign in with a one-time link instead: npx brim user link <email>",
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
};
|
|
278
|
+
walk(root);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Whether the folder is in a git repository: its own `.git`, or one of a folder above it. */
|
|
282
|
+
/** Whether a folder is inside a git repository (its own or a parent's). */
|
|
283
|
+
export function insideGit(root: string): boolean {
|
|
284
|
+
let folder = root;
|
|
285
|
+
for (;;) {
|
|
286
|
+
if (existsSync(join(folder, ".git"))) return true;
|
|
287
|
+
const parent = dirname(folder);
|
|
288
|
+
if (parent === folder) return false;
|
|
289
|
+
folder = parent;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** Warns about contact details written in the code (one finding per file): they belong in the site settings. */
|
|
294
|
+
function findContactsInCode(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
295
|
+
for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
|
|
296
|
+
const file = relative(root, path).split(sep).join("/");
|
|
297
|
+
if (SETTINGS_MODULE.test(file)) continue;
|
|
298
|
+
const found: number[] = [];
|
|
299
|
+
readFileSync(path, "utf8")
|
|
300
|
+
.split("\n")
|
|
301
|
+
.forEach((line, index) => {
|
|
302
|
+
const code = line.trimStart();
|
|
303
|
+
if (code.startsWith("//") || code.startsWith("*")) return;
|
|
304
|
+
// A template literal building the link from a setting (`tel:${phone}`) names no contact itself, and neither
|
|
305
|
+
// does an example shown to visitors: a form field's placeholder, or an address that ends in "…".
|
|
306
|
+
for (const match of line.matchAll(CONTACT_ADDRESS)) {
|
|
307
|
+
const before = line.slice(0, match.index);
|
|
308
|
+
const example = /placeholder\s*[:=]\s*\{?\s*["'`][^"'`]*$/.test(before) || /(\.\.\.|…)$/.test(match[0]);
|
|
309
|
+
if (!/\$\{/.test(match[0]) && match[0].length > 7 && !example) found.push(index + 1);
|
|
310
|
+
}
|
|
311
|
+
});
|
|
312
|
+
if (found.length === 0) continue;
|
|
313
|
+
add({
|
|
314
|
+
file,
|
|
315
|
+
line: found[0] ?? 1,
|
|
316
|
+
severity: "warning",
|
|
317
|
+
rule: "contact-in-code",
|
|
318
|
+
message:
|
|
319
|
+
`${found.length === 1 ? "a contact detail" : `${found.length} contact details`} (email, phone, WhatsApp, social profile) ` +
|
|
320
|
+
"written in the code: the owner cannot change them. Declare them in src/site-settings.ts and read them with " +
|
|
321
|
+
'getSiteSettings(), or show them with <Setting name="…" />',
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Warns about media library addresses (`/uploads/…`) written in the code. Uploads live in `public/uploads` and the
|
|
328
|
+
* database, neither of which is in git, so code that names them breaks on a fresh clone and on a deploy that has not
|
|
329
|
+
* brought the content along, and keeps pointing at files the owner has replaced or deleted. One finding per file.
|
|
330
|
+
*/
|
|
331
|
+
function findUploadsInCode(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
332
|
+
for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
|
|
333
|
+
const lines = readFileSync(path, "utf8").split("\n");
|
|
334
|
+
const found: number[] = [];
|
|
335
|
+
lines.forEach((line, index) => {
|
|
336
|
+
const code = line.trimStart();
|
|
337
|
+
if (code.startsWith("//") || code.startsWith("*")) return;
|
|
338
|
+
for (const _match of line.matchAll(UPLOAD_ADDRESS)) found.push(index + 1);
|
|
339
|
+
});
|
|
340
|
+
if (found.length === 0) continue;
|
|
341
|
+
add({
|
|
342
|
+
file: relative(root, path).split(sep).join("/"),
|
|
343
|
+
line: found[0] ?? 1,
|
|
344
|
+
severity: "warning",
|
|
345
|
+
rule: "uploads-in-code",
|
|
346
|
+
message:
|
|
347
|
+
`${found.length === 1 ? "an address" : `${found.length} addresses`} of the media library (/uploads/…) in the code: ` +
|
|
348
|
+
"uploads are not in git, so a fresh clone or a deploy without the content has none of them. Keep them in the " +
|
|
349
|
+
"content (an item's field, an element's saved value) and give the code a starting picture of its own " +
|
|
350
|
+
"(public/ or src/assets/)",
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** An `<img>` whose address the code reads through `mediaUrl(…)`: an image of the content, drawn by hand. */
|
|
356
|
+
const HAND_DRAWN_IMAGE = /<img\b[^>]*?\ssrc=\{\s*mediaUrl\(/g;
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Warns about `<img src={mediaUrl(…)}>`: an image of the content (an item's picture, an upload) drawn as a plain
|
|
360
|
+
* `<img>`. It has no `srcset`, so every visitor downloads the full upload even where the CDN would serve a copy the
|
|
361
|
+
* size of the layout, and the owner cannot replace it from the page. `<Image bare item={item} field="…" />` draws
|
|
362
|
+
* the same `<img>` with both. One finding per file.
|
|
363
|
+
*/
|
|
364
|
+
function findHandDrawnImages(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
365
|
+
for (const path of listSources(sourceFolder)) {
|
|
366
|
+
const text = readFileSync(path, "utf8");
|
|
367
|
+
const lines = [...text.matchAll(HAND_DRAWN_IMAGE)].map((match) => text.slice(0, match.index).split("\n").length);
|
|
368
|
+
if (lines.length === 0) continue;
|
|
369
|
+
add({
|
|
370
|
+
file: relative(root, path).split(sep).join("/"),
|
|
371
|
+
line: lines[0] ?? 1,
|
|
372
|
+
severity: "warning",
|
|
373
|
+
rule: "hand-drawn-image",
|
|
374
|
+
message:
|
|
375
|
+
`${lines.length === 1 ? "an image" : `${lines.length} images`} of the content drawn as <img src={mediaUrl(…)}>: ` +
|
|
376
|
+
"without a srcset every visitor downloads the full upload, and the owner cannot replace it from the page. " +
|
|
377
|
+
'Use <Image bare nodeId="…" item={item} field="…" src="" alt="" /> (it takes class, loading and sizes as an ' +
|
|
378
|
+
"<img> does), or {...imageSources(src, sizes)} from brimjs/content where it cannot be a component",
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
/** An `<img>` tag, to its closing `>` (an arrow function's `=>` inside it does not end it). */
|
|
384
|
+
const IMG_TAG = /<img\b(?:[^>]|(?<==)>)*>/g;
|
|
385
|
+
/** Its attributes come from Brim: `imageSources(…)`, or a Gallery's or Carousel's `image.img`. */
|
|
386
|
+
const BRIM_SOURCES = /imageSources\(|\.img\s*\}/;
|
|
387
|
+
const FIXED_SIZE = /\s(?:width|height)=(?:["']\d+["']|\{\s*\d+\s*\})/;
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Warns about an `<img>` that takes its address from Brim (`imageSources`, a gallery's `image.img`) and writes its
|
|
391
|
+
* `width` or `height` as a number. Brim gives an upload its own measured size; a number written once is the same for
|
|
392
|
+
* every picture, so portrait photos get a landscape place, the page jumps as each one arrives and a masonry gallery
|
|
393
|
+
* reshuffles its columns. One finding per file.
|
|
394
|
+
*/
|
|
395
|
+
function findFixedImageSizes(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
396
|
+
for (const path of listSources(sourceFolder)) {
|
|
397
|
+
const text = readFileSync(path, "utf8");
|
|
398
|
+
const lines = [...text.matchAll(IMG_TAG)]
|
|
399
|
+
.filter((match) => BRIM_SOURCES.test(match[0]) && FIXED_SIZE.test(match[0]))
|
|
400
|
+
.map((match) => text.slice(0, match.index).split("\n").length);
|
|
401
|
+
if (lines.length === 0) continue;
|
|
402
|
+
add({
|
|
403
|
+
file: relative(root, path).split(sep).join("/"),
|
|
404
|
+
line: lines[0] ?? 1,
|
|
405
|
+
severity: "warning",
|
|
406
|
+
rule: "fixed-image-size",
|
|
407
|
+
message:
|
|
408
|
+
`${lines.length === 1 ? "an image" : `${lines.length} images`} of the content with a width or height written ` +
|
|
409
|
+
"as a number: every picture gets that shape, so portrait photos jump as they load. Leave width and height " +
|
|
410
|
+
"out: imageSources and image.img give each upload its own size (and set height: auto in the CSS)",
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Brim's `Image`, imported under its own name: a site's or Astro's own `Image` component is not it. */
|
|
416
|
+
const BRIM_IMAGE_IMPORT = /import\s*\{[^}]*\bImage\b(?!\s+as\b)[^}]*\}\s*from\s*["']@brimsites\/brimjs\/components["']/;
|
|
417
|
+
/** An `<Image>` tag, to its closing `>` (an arrow function's `=>` inside it does not end it). */
|
|
418
|
+
const IMAGE_TAG = /<Image\b(?:[^>]|(?<==)>)*>/g;
|
|
419
|
+
|
|
420
|
+
/**
|
|
421
|
+
* Warns about `<Image>` without `sizes`: the browser then takes the picture to be as wide as the page (`100vw`) and
|
|
422
|
+
* downloads a copy that wide, twice the bytes for a picture drawn in half of it and nine times for a card in a row
|
|
423
|
+
* of three. A picture that does span the page needs none. Tags that spread their attributes (`{...props}`) may
|
|
424
|
+
* carry it, and are left alone. One finding per file.
|
|
425
|
+
*/
|
|
426
|
+
function findImagesWithoutSizes(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
427
|
+
for (const path of listSources(sourceFolder)) {
|
|
428
|
+
const text = readFileSync(path, "utf8");
|
|
429
|
+
if (!BRIM_IMAGE_IMPORT.test(text)) continue;
|
|
430
|
+
const lines = [...text.matchAll(IMAGE_TAG)]
|
|
431
|
+
.filter(([tag]) => !/\ssizes[=\s/>]/.test(tag) && !tag.includes("{..."))
|
|
432
|
+
.map((match) => text.slice(0, match.index).split("\n").length);
|
|
433
|
+
if (lines.length === 0) continue;
|
|
434
|
+
add({
|
|
435
|
+
file: relative(root, path).split(sep).join("/"),
|
|
436
|
+
line: lines[0] ?? 1,
|
|
437
|
+
severity: "warning",
|
|
438
|
+
rule: "image-sizes",
|
|
439
|
+
message:
|
|
440
|
+
`${lines.length === 1 ? "an <Image>" : `${lines.length} <Image> elements`} without sizes: the browser takes ` +
|
|
441
|
+
"the picture to be as wide as the page and downloads a copy that wide. Where it is drawn narrower, say how " +
|
|
442
|
+
'wide, e.g. sizes="(max-width: 768px) 100vw, 50vw"; a picture that spans the page needs none',
|
|
443
|
+
});
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** `sharp: true` in the site's Astro config: `brim({ media: { sharp: true } })`. */
|
|
448
|
+
const ASKS_FOR_SHARP = /\bsharp\s*:\s*true\b/;
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Warns when the site asks its own server for the smaller copies of the pictures in public/ (`media.sharp`) and
|
|
452
|
+
* `sharp` is not among its installed packages: the built server looks for it from the site's own folder, and without
|
|
453
|
+
* it sends every picture as it was saved. With pnpm a package is found only when the site itself depends on it.
|
|
454
|
+
* A site that does not ask (one behind a CDN that resizes) needs no sharp, and is left alone.
|
|
455
|
+
*/
|
|
456
|
+
function findMissingSharp(root: string, add: (finding: Finding) => void): void {
|
|
457
|
+
const config = ["mjs", "ts", "js", "mts", "cjs"].map((extension) => join(root, `astro.config.${extension}`));
|
|
458
|
+
const asked = config.some((path) => existsSync(path) && ASKS_FOR_SHARP.test(readFileSync(path, "utf8")));
|
|
459
|
+
// The folder itself, not a lookup: run through a package manager, a lookup also finds what other packages brought.
|
|
460
|
+
if (!asked || !existsSync(join(root, "node_modules")) || existsSync(join(root, "node_modules", "sharp"))) return;
|
|
461
|
+
add({
|
|
462
|
+
file: "package.json",
|
|
463
|
+
severity: "warning",
|
|
464
|
+
rule: "no-sharp",
|
|
465
|
+
message:
|
|
466
|
+
"media.sharp is on but sharp is not installed: the pictures in public/ are sent as they were saved, with no " +
|
|
467
|
+
"smaller copies for a phone. Add it to the site's dependencies (npm install sharp)",
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** Images in public/ larger than this are sent whole to every visitor, phones included. */
|
|
472
|
+
const LARGE_PUBLIC_IMAGE = 500 * 1024;
|
|
473
|
+
const IMAGE_EXTENSIONS = new Set([".jpg", ".jpeg", ".png", ".webp", ".avif", ".gif"]);
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Warns about large images in public/: they are served as they are, with no smaller copy for a phone and no
|
|
477
|
+
* `srcset`. The uploads folder is the media library's, left out. One finding for all of them, largest first.
|
|
478
|
+
*/
|
|
479
|
+
function findLargePublicImages(root: string, add: (finding: Finding) => void): void {
|
|
480
|
+
const folder = join(root, "public");
|
|
481
|
+
if (!existsSync(folder)) return;
|
|
482
|
+
const large: { file: string; size: number }[] = [];
|
|
483
|
+
const walk = (directory: string): void => {
|
|
484
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
485
|
+
const path = join(directory, entry.name);
|
|
486
|
+
if (entry.isDirectory()) {
|
|
487
|
+
if (path !== join(folder, "uploads") && !SKIPPED_FOLDERS.has(entry.name)) walk(path);
|
|
488
|
+
} else if (IMAGE_EXTENSIONS.has(extname(entry.name).toLowerCase())) {
|
|
489
|
+
const size = statSync(path).size;
|
|
490
|
+
if (size > LARGE_PUBLIC_IMAGE) large.push({ file: relative(root, path).split(sep).join("/"), size });
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
};
|
|
494
|
+
walk(folder);
|
|
495
|
+
if (large.length === 0) return;
|
|
496
|
+
large.sort((a, b) => b.size - a.size);
|
|
497
|
+
const listed = large
|
|
498
|
+
.slice(0, 5)
|
|
499
|
+
.map(({ file, size }) => `${file} (${(size / 1024 / 1024).toFixed(1)} MB)`)
|
|
500
|
+
.join(", ");
|
|
501
|
+
add({
|
|
502
|
+
file: large[0]?.file ?? "public",
|
|
503
|
+
severity: "warning",
|
|
504
|
+
rule: "large-public-image",
|
|
505
|
+
message:
|
|
506
|
+
`${large.length === 1 ? "an image" : `${large.length} images`} in public/ larger than 500 KB: ${listed}` +
|
|
507
|
+
`${large.length > 5 ? ", …" : ""}. A server sends visitors smaller copies, but each copy is made from this file, ` +
|
|
508
|
+
"every clone and deploy carries it, and a static build sends it whole: save it once at most 2560 px wide " +
|
|
509
|
+
"(about 2000 px is enough for a full-width photo). Pictures of items belong in the media library instead",
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/** A `richtext` field declared in a content type, unless its line says `// text only`. */
|
|
514
|
+
const RICHTEXT_FIELD = /\{[^{}\n]*?\btype\s*:\s*["'`]richtext["'`][^\n]*/g;
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* A content type with pages (`component`) whose fields are rich text but no `blocks`: on those pages the owner can
|
|
518
|
+
* only write text, never put an image, a gallery, a button or a video between its paragraphs. A suggestion, not a
|
|
519
|
+
* rule: a field that should hold text and nothing else says so with `// text only` on its line. Read from the code of
|
|
520
|
+
* src/content-types.
|
|
521
|
+
*/
|
|
522
|
+
function findTextOnlyBodies(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
523
|
+
const folder = join(sourceFolder, "content-types");
|
|
524
|
+
if (!existsSync(folder)) return;
|
|
525
|
+
for (const path of listSources(folder, CODE_EXTENSIONS)) {
|
|
526
|
+
const text = readFileSync(path, "utf8");
|
|
527
|
+
if (!/\bcomponent\s*[:,}]/.test(text) || /\btype\s*:\s*["'`]blocks["'`]/.test(text)) continue;
|
|
528
|
+
const match = [...text.matchAll(RICHTEXT_FIELD)].find((found) => !/\/\/\s*text only/i.test(found[0]));
|
|
529
|
+
if (!match) continue;
|
|
530
|
+
const name = /\bname\s*:\s*["'`]([^"'`]+)["'`]/.exec(match[0])?.[1] ?? "a field";
|
|
531
|
+
add({
|
|
532
|
+
file: relative(root, path).split(sep).join("/"),
|
|
533
|
+
line: text.slice(0, match.index).split("\n").length,
|
|
534
|
+
severity: "warning",
|
|
535
|
+
rule: "text-only-body",
|
|
536
|
+
message:
|
|
537
|
+
`"${name}" is rich text and the type has no blocks field: on its pages the owner can only write text, never ` +
|
|
538
|
+
'add an image, gallery, button or video between paragraphs. For a body, make it type: "blocks" (texts already ' +
|
|
539
|
+
"saved become its first block when the site starts, and <Blocks> draws it); if text is all it should hold, " +
|
|
540
|
+
"add // text only on its line",
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** A number field whose name says it orders items: `order`, `ordine`, `position`, `sort`, `rank`… */
|
|
546
|
+
const ORDER_FIELD =
|
|
547
|
+
/\{[^{}]*?\bname\s*:\s*["'`](order|ordine|ordinea|position|pozitie|poziție|sort|sort_order|rank|weight)["'`][^{}]*?\btype\s*:\s*["'`]number["'`][^{}]*\}|\{[^{}]*?\btype\s*:\s*["'`]number["'`][^{}]*?\bname\s*:\s*["'`](order|ordine|ordinea|position|pozitie|poziție|sort|sort_order|rank|weight)["'`][^{}]*\}/g;
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* A content type that keeps its items' order in a number field. The owner then types numbers into each item to
|
|
551
|
+
* move one, and two items with the same number swap at random; `ordered: true` lets them drag the items into order
|
|
552
|
+
* in the editor, and listings and `getItems` follow it. Read from the code of src/content-types.
|
|
553
|
+
*/
|
|
554
|
+
function findOrderFields(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
555
|
+
const folder = join(sourceFolder, "content-types");
|
|
556
|
+
if (!existsSync(folder)) return;
|
|
557
|
+
for (const path of listSources(folder, CODE_EXTENSIONS)) {
|
|
558
|
+
const text = readFileSync(path, "utf8");
|
|
559
|
+
for (const match of text.matchAll(ORDER_FIELD)) {
|
|
560
|
+
add({
|
|
561
|
+
file: relative(root, path).split(sep).join("/"),
|
|
562
|
+
line: text.slice(0, match.index).split("\n").length,
|
|
563
|
+
severity: "warning",
|
|
564
|
+
rule: "order-field",
|
|
565
|
+
message:
|
|
566
|
+
`the number field "${match[1] ?? match[2]}" keeps the order of the items: the owner has to type a number ` +
|
|
567
|
+
"into each one to move it. Declare the type ordered: true and delete the field; the owner then drags the " +
|
|
568
|
+
'items into order in the editor, and Listing and getItems list them that way (sort="position")',
|
|
569
|
+
});
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Pages written by hand for a vocabulary's terms: `src/pages/produse/[category].astro` next to a `category`
|
|
576
|
+
* vocabulary. Without `path` and `component` on the vocabulary such a page works, but the editor does not know it is
|
|
577
|
+
* the term's (its fields, the site map), the sitemap leaves it out and its `getStaticPaths` is the site's to keep.
|
|
578
|
+
* With them, a page left in src/pages takes the terms' addresses, since the site's own pages come first. Read from
|
|
579
|
+
* the code's text, so a vocabulary declared in an unusual way is not seen.
|
|
580
|
+
*/
|
|
581
|
+
function findVocabularyPages(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
582
|
+
const vocabularies = new Map<string, { component: boolean; path?: string }>();
|
|
583
|
+
for (const path of listSources(sourceFolder, CODE_EXTENSIONS)) {
|
|
584
|
+
const text = readFileSync(path, "utf8");
|
|
585
|
+
for (const match of text.matchAll(/defineVocabulary\s*\(/g)) {
|
|
586
|
+
const call = balanced(text, (match.index ?? 0) + match[0].length - 1);
|
|
587
|
+
const key = /\bkey\s*:\s*["'`]([a-z][a-z0-9_]*)["'`]/.exec(call)?.[1];
|
|
588
|
+
if (!key) continue;
|
|
589
|
+
const route = /\bpath\s*:\s*["'`]([^"'`]+)["'`]/.exec(call)?.[1];
|
|
590
|
+
vocabularies.set(key, { component: /\bcomponent\s*[:,}]/.test(call), ...(route && { path: route }) });
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
if (vocabularies.size === 0) return;
|
|
594
|
+
const pagesFolder = join(sourceFolder, "pages");
|
|
595
|
+
if (!existsSync(pagesFolder)) return;
|
|
596
|
+
for (const path of listSources(pagesFolder, [".astro", ".ts", ".js", ".mdx"])) {
|
|
597
|
+
const file = relative(root, path).split(sep).join("/");
|
|
598
|
+
const name = /\[([a-z][a-z0-9_]*)\]\.[a-z]+$/.exec(file)?.[1];
|
|
599
|
+
if (!name) continue;
|
|
600
|
+
const vocabulary = vocabularies.get(name);
|
|
601
|
+
if (!vocabulary) continue;
|
|
602
|
+
const route = `/${relative(pagesFolder, path).split(sep).join("/")}`.replace(/\.[a-z]+$/, "");
|
|
603
|
+
const address = route.replace(`[${name}]`, "[slug]");
|
|
604
|
+
if (!vocabulary.component) {
|
|
605
|
+
add({
|
|
606
|
+
file,
|
|
607
|
+
line: 1,
|
|
608
|
+
severity: "warning",
|
|
609
|
+
rule: "vocabulary-page",
|
|
610
|
+
message:
|
|
611
|
+
`this page draws the terms of the "${name}" vocabulary by hand. Give the vocabulary path: "${address}" and ` +
|
|
612
|
+
"this page as its component (it gets the term as `item`, like an item's page), then delete this file: " +
|
|
613
|
+
"the terms then have pages the editor knows (their fields, the site map), in the sitemap, without " +
|
|
614
|
+
"getStaticPaths",
|
|
615
|
+
});
|
|
616
|
+
} else if (vocabulary.path === address) {
|
|
617
|
+
add({
|
|
618
|
+
file,
|
|
619
|
+
line: 1,
|
|
620
|
+
severity: "error",
|
|
621
|
+
rule: "vocabulary-page",
|
|
622
|
+
message:
|
|
623
|
+
`this page takes the addresses of the "${name}" vocabulary's pages (${address}): the site's own pages come ` +
|
|
624
|
+
"first, so its component is never used. Delete this file",
|
|
625
|
+
});
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/** The text of a call's arguments, from its opening parenthesis to the one that closes it. */
|
|
631
|
+
function balanced(text: string, open: number): string {
|
|
632
|
+
let depth = 0;
|
|
633
|
+
for (let index = open; index < text.length; index++) {
|
|
634
|
+
const char = text[index];
|
|
635
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
636
|
+
index = skipString(text, index, char) - 1;
|
|
637
|
+
continue;
|
|
638
|
+
}
|
|
639
|
+
if (char === "(") depth++;
|
|
640
|
+
else if (char === ")" && --depth === 0) return text.slice(open, index + 1);
|
|
641
|
+
}
|
|
642
|
+
return text.slice(open);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
646
|
+
// Duplicates
|
|
647
|
+
|
|
648
|
+
interface Occurrence {
|
|
649
|
+
id: string;
|
|
650
|
+
scope: "page" | "site";
|
|
651
|
+
/** Where the element is written. */
|
|
652
|
+
file: string;
|
|
653
|
+
line: number;
|
|
654
|
+
/** The line in the file being checked that draws it: the element itself, or the component that contains it. */
|
|
655
|
+
entryLine: number;
|
|
656
|
+
/** The component, used in the file being checked, that contains the element. */
|
|
657
|
+
through?: string;
|
|
658
|
+
/** `item|field` for an element that shows an item's field (see `Element.binding`). */
|
|
659
|
+
binding?: string;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/**
|
|
663
|
+
* Every element with a known id that a file draws: its own, and those of the local components it uses,
|
|
664
|
+
* followed through their imports. A component used twice contributes its ids twice. An id built from a prop
|
|
665
|
+
* (``nodeId={`${id}-title`}``) becomes known when the use passes that prop as a literal (`<Hero id="home-hero">`).
|
|
666
|
+
*/
|
|
667
|
+
function collect(file: string, sources: Map<string, Source>, resolved: Set<string>): Occurrence[] {
|
|
668
|
+
const occurrences: Occurrence[] = [];
|
|
669
|
+
const visit = (
|
|
670
|
+
current: string,
|
|
671
|
+
props: Map<string, string> | undefined,
|
|
672
|
+
stack: string[],
|
|
673
|
+
entry: { line: number; through: string } | undefined,
|
|
674
|
+
) => {
|
|
675
|
+
const source = sources.get(current);
|
|
676
|
+
if (!source) return;
|
|
677
|
+
for (const element of source.elements) {
|
|
678
|
+
const component = source.imports.get(element.name);
|
|
679
|
+
const target = component && resolveImport(current, component, sources);
|
|
680
|
+
if (target) {
|
|
681
|
+
// A nodeId given to a local component is a prop it passes on; the element it lands on is counted there.
|
|
682
|
+
// A component that (through others) includes itself would never end; the build would not either.
|
|
683
|
+
if (!stack.includes(target) && stack.length < 20) {
|
|
684
|
+
visit(target, element.props, [...stack, target], entry ?? { line: element.line, through: element.name });
|
|
685
|
+
}
|
|
686
|
+
continue;
|
|
687
|
+
}
|
|
688
|
+
const id = element.nodeId && idValue(element.nodeId, props);
|
|
689
|
+
if (!id || element.scope === "unknown") continue;
|
|
690
|
+
if (element.nodeId?.kind === "prefixed") resolved.add(`${current}:${element.line}`);
|
|
691
|
+
occurrences.push({
|
|
692
|
+
id,
|
|
693
|
+
scope: element.scope,
|
|
694
|
+
file: current,
|
|
695
|
+
line: element.line,
|
|
696
|
+
entryLine: entry?.line ?? element.line,
|
|
697
|
+
...(entry && { through: entry.through }),
|
|
698
|
+
...(element.binding && { binding: `${current}|${element.binding}` }),
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
};
|
|
702
|
+
visit(file, undefined, [file], undefined);
|
|
703
|
+
return occurrences;
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
function idValue(id: NodeIdValue, props: Map<string, string> | undefined): string | undefined {
|
|
707
|
+
if (id.kind === "literal") return id.value;
|
|
708
|
+
if (id.kind === "prefixed") {
|
|
709
|
+
const prefix = props?.get(id.prop);
|
|
710
|
+
return prefix === undefined ? undefined : `${prefix}${id.suffix}`;
|
|
711
|
+
}
|
|
712
|
+
return undefined;
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
/**
|
|
716
|
+
* Page-scoped ids repeated within what one file draws. A duplicate shows up in the file where it starts and
|
|
717
|
+
* in every page that includes that file; it is reported once, in the smallest file that contains it.
|
|
718
|
+
*/
|
|
719
|
+
function findDuplicates(closures: { file: string; occurrences: Occurrence[] }[], add: (finding: Finding) => void) {
|
|
720
|
+
const reported = new Set<string>();
|
|
721
|
+
const bySize = [...closures].sort((a, b) => a.occurrences.length - b.occurrences.length);
|
|
722
|
+
for (const { file, occurrences } of bySize) {
|
|
723
|
+
const byId = new Map<string, Occurrence[]>();
|
|
724
|
+
for (const occurrence of occurrences) {
|
|
725
|
+
if (occurrence.scope !== "page") continue;
|
|
726
|
+
byId.set(occurrence.id, [...(byId.get(occurrence.id) ?? []), occurrence]);
|
|
727
|
+
}
|
|
728
|
+
for (const [id, same] of byId) {
|
|
729
|
+
if (same.length < 2) continue;
|
|
730
|
+
const binding = same[0]?.binding;
|
|
731
|
+
if (binding !== undefined && same.every((occurrence) => occurrence.binding === binding)) continue;
|
|
732
|
+
const key = `${id}|${same
|
|
733
|
+
.map((occurrence) => `${occurrence.file}:${occurrence.line}`)
|
|
734
|
+
.sort()
|
|
735
|
+
.join(",")}`;
|
|
736
|
+
if (reported.has(key)) continue;
|
|
737
|
+
reported.add(key);
|
|
738
|
+
const places = same.map((occurrence) =>
|
|
739
|
+
occurrence.file === file && !occurrence.through
|
|
740
|
+
? `line ${occurrence.line}`
|
|
741
|
+
: `${occurrence.file}:${occurrence.line} (through <${occurrence.through}> at line ${occurrence.entryLine})`,
|
|
742
|
+
);
|
|
743
|
+
const where = file.startsWith("src/pages/") ? "on this page" : "in what this file draws";
|
|
744
|
+
add({
|
|
745
|
+
file,
|
|
746
|
+
line: Math.max(...same.map((occurrence) => occurrence.entryLine)),
|
|
747
|
+
severity: "error",
|
|
748
|
+
rule: "duplicate",
|
|
749
|
+
nodeId: id,
|
|
750
|
+
message: `nodeId "${id}" is used ${same.length} times ${where}: ${places.join(", ")}`,
|
|
751
|
+
});
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
/** Site-scoped ids share one namespace: two different elements anywhere in the site must not share one. */
|
|
757
|
+
function findSiteDuplicates(closures: { occurrences: Occurrence[] }[], add: (finding: Finding) => void) {
|
|
758
|
+
const places = new Map<string, Map<string, Occurrence>>();
|
|
759
|
+
for (const { occurrences } of closures) {
|
|
760
|
+
for (const occurrence of occurrences) {
|
|
761
|
+
if (occurrence.scope !== "site") continue;
|
|
762
|
+
const byPlace = places.get(occurrence.id) ?? new Map<string, Occurrence>();
|
|
763
|
+
byPlace.set(`${occurrence.file}:${occurrence.line}`, occurrence);
|
|
764
|
+
places.set(occurrence.id, byPlace);
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
for (const [id, byPlace] of places) {
|
|
768
|
+
if (byPlace.size < 2) continue;
|
|
769
|
+
const sorted = [...byPlace.values()].sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line);
|
|
770
|
+
const [first, ...others] = sorted as [Occurrence, ...Occurrence[]];
|
|
771
|
+
add({
|
|
772
|
+
file: first.file,
|
|
773
|
+
line: first.line,
|
|
774
|
+
severity: "error",
|
|
775
|
+
rule: "site-duplicate",
|
|
776
|
+
nodeId: id,
|
|
777
|
+
message: `site-wide nodeId "${id}" is also used by ${others
|
|
778
|
+
.map((other) => `${other.file}:${other.line}`)
|
|
779
|
+
.join(", ")}; they would share one edit`,
|
|
780
|
+
});
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
785
|
+
// Starter leftovers
|
|
786
|
+
|
|
787
|
+
/** The starter's structure: what a site built from it keeps, unlike its pages, pictures and sections. */
|
|
788
|
+
const STARTER_STRUCTURE =
|
|
789
|
+
/^src\/(layouts|styles|content-types)\/|^src\/page-templates\/index\.ts$|^src\/site-settings\.ts$/;
|
|
790
|
+
|
|
791
|
+
/** Warns about starter content still in the site; returns the unchanged structural files. */
|
|
792
|
+
function findStarterLeftovers(root: string, starter: StarterFile[], add: (finding: Finding) => void): string[] {
|
|
793
|
+
const structure: string[] = [];
|
|
794
|
+
for (const file of starter) {
|
|
795
|
+
const path = join(root, file.path);
|
|
796
|
+
if (!existsSync(path)) continue;
|
|
797
|
+
const unchanged = isUnchanged(file, readFileSync(path, "utf8"));
|
|
798
|
+
if (file.path === "src/pages/components.astro") {
|
|
799
|
+
// A demo of every component, meant to be deleted: reported even when it was changed.
|
|
800
|
+
add({
|
|
801
|
+
file: file.path,
|
|
802
|
+
severity: "warning",
|
|
803
|
+
rule: "starter",
|
|
804
|
+
message: `the starter's component showcase${unchanged ? "" : " (changed)"}: delete it, and its links in the navigation and the home page`,
|
|
805
|
+
});
|
|
806
|
+
} else if (unchanged && STARTER_STRUCTURE.test(file.path)) {
|
|
807
|
+
structure.push(file.path);
|
|
808
|
+
} else if (unchanged) {
|
|
809
|
+
const content = file.path.startsWith("src/pages/") || file.path.startsWith("public/");
|
|
810
|
+
add({
|
|
811
|
+
file: file.path,
|
|
812
|
+
severity: "warning",
|
|
813
|
+
rule: "starter",
|
|
814
|
+
message: content
|
|
815
|
+
? "unchanged from the create-brim starter: replace it with the site's own content or delete it"
|
|
816
|
+
: "unchanged from the create-brim starter: keep it only if the site uses it as it is",
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
return structure;
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
824
|
+
// Reading the source
|
|
825
|
+
|
|
826
|
+
type NodeIdValue =
|
|
827
|
+
| { kind: "literal"; value: string }
|
|
828
|
+
/** ``nodeId={`${id}-title`}`` or `nodeId={nodeId}`: known once the use of the component passes that prop. */
|
|
829
|
+
| { kind: "prefixed"; prop: string; suffix: string }
|
|
830
|
+
| { kind: "dynamic" };
|
|
831
|
+
|
|
832
|
+
export interface Element {
|
|
833
|
+
name: string;
|
|
834
|
+
line: number;
|
|
835
|
+
nodeId?: NodeIdValue;
|
|
836
|
+
scope: "page" | "site" | "unknown";
|
|
837
|
+
/** Attributes written as literal strings, passed down when the element is a local component. */
|
|
838
|
+
props: Map<string, string>;
|
|
839
|
+
/**
|
|
840
|
+
* `item={item} field="title"`: the element shows that field of the item, which is where its value is kept. Two
|
|
841
|
+
* elements with one nodeId bound to the same field (in the two branches of `a ? … : …`) are the same value.
|
|
842
|
+
*/
|
|
843
|
+
binding?: string;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
interface Source {
|
|
847
|
+
elements: Element[];
|
|
848
|
+
/** Local name → import specifier. */
|
|
849
|
+
imports: Map<string, string>;
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
type Attribute = { kind: "string"; value: string } | { kind: "expression"; value: string } | { kind: "bare" };
|
|
853
|
+
|
|
854
|
+
export function parseSource(file: string, text: string): Source {
|
|
855
|
+
const extension = extname(file);
|
|
856
|
+
let start = 0;
|
|
857
|
+
let code = text;
|
|
858
|
+
if (extension === ".astro") {
|
|
859
|
+
// The frontmatter is TypeScript with no elements in it; only its imports matter.
|
|
860
|
+
const frontmatter = /^\s*---\r?\n([\s\S]*?)\r?\n---/.exec(text);
|
|
861
|
+
code = frontmatter?.[1] ?? "";
|
|
862
|
+
start = frontmatter ? frontmatter[0].length : 0;
|
|
863
|
+
}
|
|
864
|
+
return { elements: parseElements(text, start, extension), imports: parseImports(code) };
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function parseImports(code: string): Map<string, string> {
|
|
868
|
+
const imports = new Map<string, string>();
|
|
869
|
+
const statement = /\bimport\s+(?!type\s)([^;'"]*?)\s+from\s+["']([^"']+)["']/g;
|
|
870
|
+
for (const [, clause = "", specifier = ""] of code.matchAll(statement)) {
|
|
871
|
+
if (!specifier.startsWith(".")) continue;
|
|
872
|
+
const defaultName = /^([\w$]+)/.exec(clause.trim())?.[1];
|
|
873
|
+
if (defaultName) imports.set(defaultName, specifier);
|
|
874
|
+
const named = /\{([^}]*)\}/.exec(clause)?.[1] ?? "";
|
|
875
|
+
for (const part of named.split(",")) {
|
|
876
|
+
const name = part.trim().replace(/^type\s+/, "");
|
|
877
|
+
if (!name || part.trim().startsWith("type ")) continue;
|
|
878
|
+
imports.set(name.split(/\s+as\s+/).pop() ?? name, specifier);
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
return imports;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function resolveImport(from: string, specifier: string, sources: Map<string, Source>): string | undefined {
|
|
885
|
+
const base = join(dirname(from), specifier).split(sep).join("/");
|
|
886
|
+
const bare = base.replace(/\.(m?js|jsx)$/, "");
|
|
887
|
+
const candidates = [
|
|
888
|
+
base,
|
|
889
|
+
...RESOLVE_EXTENSIONS.map((extension) => bare + extension),
|
|
890
|
+
...RESOLVE_EXTENSIONS.map((extension) => `${base}/index${extension}`),
|
|
891
|
+
];
|
|
892
|
+
return candidates.find((candidate) => sources.has(candidate));
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* A pragmatic tokenizer for Astro markup, JSX and MDX: finds `<Name attributes>` and reads the attributes,
|
|
897
|
+
* skipping comments, `<script>`/`<style>` contents and the code inside `{…}` attribute values.
|
|
898
|
+
*/
|
|
899
|
+
function parseElements(text: string, start: number, extension: string): Element[] {
|
|
900
|
+
const elements: Element[] = [];
|
|
901
|
+
const lineStarts = [0];
|
|
902
|
+
for (let index = 0; index < text.length; index++) if (text[index] === "\n") lineStarts.push(index + 1);
|
|
903
|
+
const lineOf = (position: number) => {
|
|
904
|
+
let low = 0;
|
|
905
|
+
let high = lineStarts.length - 1;
|
|
906
|
+
while (low < high) {
|
|
907
|
+
const middle = Math.ceil((low + high) / 2);
|
|
908
|
+
if ((lineStarts[middle] ?? 0) <= position) low = middle;
|
|
909
|
+
else high = middle - 1;
|
|
910
|
+
}
|
|
911
|
+
return low + 1;
|
|
912
|
+
};
|
|
913
|
+
const isScript = extension === ".tsx" || extension === ".jsx";
|
|
914
|
+
|
|
915
|
+
let index = start;
|
|
916
|
+
while (index < text.length) {
|
|
917
|
+
if (text.startsWith("<!--", index)) {
|
|
918
|
+
index = after(text, "-->", index + 4);
|
|
919
|
+
} else if (text.startsWith("/*", index)) {
|
|
920
|
+
index = after(text, "*/", index + 2);
|
|
921
|
+
} else if (isScript && text.startsWith("//", index)) {
|
|
922
|
+
index = after(text, "\n", index + 2);
|
|
923
|
+
} else if (text[index] === "<" && /[A-Za-z]/.test(text[index + 1] ?? "")) {
|
|
924
|
+
const tag = parseTag(text, index + 1);
|
|
925
|
+
elements.push(toElement(tag.name, tag.attributes, lineOf(index)));
|
|
926
|
+
index = tag.end;
|
|
927
|
+
// Their contents are CSS or JavaScript, where `<` means something else.
|
|
928
|
+
if (!tag.selfClosing && (tag.name === "script" || tag.name === "style")) {
|
|
929
|
+
index = after(text, `</${tag.name}`, index);
|
|
930
|
+
}
|
|
931
|
+
} else {
|
|
932
|
+
index++;
|
|
933
|
+
}
|
|
934
|
+
}
|
|
935
|
+
return elements;
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
function after(text: string, marker: string, from: number): number {
|
|
939
|
+
const found = text.indexOf(marker, from);
|
|
940
|
+
return found === -1 ? text.length : found + marker.length;
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
function parseTag(text: string, from: number) {
|
|
944
|
+
const name = /^[A-Za-z][\w.:-]*/.exec(text.slice(from, from + 200))?.[0] ?? "";
|
|
945
|
+
const attributes = new Map<string, Attribute>();
|
|
946
|
+
let index = from + name.length;
|
|
947
|
+
while (index < text.length) {
|
|
948
|
+
const char = text[index] ?? "";
|
|
949
|
+
if (char === ">") return { name, attributes, end: index + 1, selfClosing: false };
|
|
950
|
+
if (text.startsWith("/>", index)) return { name, attributes, end: index + 2, selfClosing: true };
|
|
951
|
+
if (char === "{") {
|
|
952
|
+
// A spread (`{...attributes}`) or a shorthand (`{title}`): no name to read.
|
|
953
|
+
index = skipExpression(text, index);
|
|
954
|
+
continue;
|
|
955
|
+
}
|
|
956
|
+
const attributeName = /^[\w:@$.-]+/.exec(text.slice(index, index + 100))?.[0];
|
|
957
|
+
if (!attributeName) {
|
|
958
|
+
index++;
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
index += attributeName.length;
|
|
962
|
+
while (/\s/.test(text[index] ?? "")) index++;
|
|
963
|
+
if (text[index] !== "=") {
|
|
964
|
+
attributes.set(attributeName, { kind: "bare" });
|
|
965
|
+
continue;
|
|
966
|
+
}
|
|
967
|
+
index++;
|
|
968
|
+
while (/\s/.test(text[index] ?? "")) index++;
|
|
969
|
+
const quote = text[index];
|
|
970
|
+
if (quote === '"' || quote === "'") {
|
|
971
|
+
const end = text.indexOf(quote, index + 1);
|
|
972
|
+
const close = end === -1 ? text.length : end;
|
|
973
|
+
attributes.set(attributeName, { kind: "string", value: text.slice(index + 1, close) });
|
|
974
|
+
index = close + 1;
|
|
975
|
+
} else if (quote === "{") {
|
|
976
|
+
const end = skipExpression(text, index);
|
|
977
|
+
attributes.set(attributeName, { kind: "expression", value: text.slice(index + 1, end - 1).trim() });
|
|
978
|
+
index = end;
|
|
979
|
+
} else {
|
|
980
|
+
const value = /^[^\s>]*/.exec(text.slice(index))?.[0] ?? "";
|
|
981
|
+
attributes.set(attributeName, { kind: "string", value: value.replace(/\/$/, "") });
|
|
982
|
+
index += value.length;
|
|
983
|
+
}
|
|
984
|
+
}
|
|
985
|
+
return { name, attributes, end: text.length, selfClosing: false };
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
/** From a `{`, the position after its matching `}`, stepping over strings, template literals and comments. */
|
|
989
|
+
function skipExpression(text: string, from: number): number {
|
|
990
|
+
let depth = 0;
|
|
991
|
+
let index = from;
|
|
992
|
+
while (index < text.length) {
|
|
993
|
+
const char = text[index];
|
|
994
|
+
if (char === '"' || char === "'") {
|
|
995
|
+
index = skipString(text, index, char);
|
|
996
|
+
continue;
|
|
997
|
+
}
|
|
998
|
+
if (char === "`") {
|
|
999
|
+
index = skipTemplate(text, index);
|
|
1000
|
+
continue;
|
|
1001
|
+
}
|
|
1002
|
+
if (text.startsWith("//", index)) {
|
|
1003
|
+
index = after(text, "\n", index + 2);
|
|
1004
|
+
continue;
|
|
1005
|
+
}
|
|
1006
|
+
if (text.startsWith("/*", index)) {
|
|
1007
|
+
index = after(text, "*/", index + 2);
|
|
1008
|
+
continue;
|
|
1009
|
+
}
|
|
1010
|
+
if (char === "{") depth++;
|
|
1011
|
+
if (char === "}") {
|
|
1012
|
+
depth--;
|
|
1013
|
+
if (depth === 0) return index + 1;
|
|
1014
|
+
}
|
|
1015
|
+
index++;
|
|
1016
|
+
}
|
|
1017
|
+
return text.length;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
function skipString(text: string, from: number, quote: string): number {
|
|
1021
|
+
let index = from + 1;
|
|
1022
|
+
while (index < text.length && text[index] !== quote && text[index] !== "\n") {
|
|
1023
|
+
index += text[index] === "\\" ? 2 : 1;
|
|
1024
|
+
}
|
|
1025
|
+
return index + 1;
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
function skipTemplate(text: string, from: number): number {
|
|
1029
|
+
let index = from + 1;
|
|
1030
|
+
while (index < text.length && text[index] !== "`") {
|
|
1031
|
+
if (text[index] === "\\") index += 2;
|
|
1032
|
+
else if (text.startsWith("${", index)) index = skipExpression(text, index + 1);
|
|
1033
|
+
else index++;
|
|
1034
|
+
}
|
|
1035
|
+
return index + 1;
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
function toElement(name: string, attributes: Map<string, Attribute>, line: number): Element {
|
|
1039
|
+
const props = new Map<string, string>();
|
|
1040
|
+
for (const [key, attribute] of attributes) {
|
|
1041
|
+
const value = literalOf(attribute);
|
|
1042
|
+
if (value !== undefined) props.set(key, value);
|
|
1043
|
+
}
|
|
1044
|
+
const element: Element = { name, line, scope: scopeOf(name, attributes.get("scope")), props };
|
|
1045
|
+
const nodeId = attributes.get("nodeId");
|
|
1046
|
+
if (nodeId && nodeId.kind !== "bare") element.nodeId = nodeIdOf(nodeId);
|
|
1047
|
+
const item = attributes.get("item");
|
|
1048
|
+
const field = literalOf(attributes.get("field"));
|
|
1049
|
+
if (item?.kind === "expression" && field !== undefined) element.binding = `${item.value.trim()}|${field}`;
|
|
1050
|
+
return element;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
/** `"x"`, `{"x"}`, `{'x'}` and ``{`x`}`` are all the literal x. */
|
|
1054
|
+
function literalOf(attribute: Attribute | undefined): string | undefined {
|
|
1055
|
+
if (!attribute || attribute.kind === "bare") return undefined;
|
|
1056
|
+
if (attribute.kind === "string") return attribute.value;
|
|
1057
|
+
const quoted = /^"([^"\\]*)"$|^'([^'\\]*)'$|^`([^`$\\]*)`$/.exec(attribute.value);
|
|
1058
|
+
return quoted ? (quoted[1] ?? quoted[2] ?? quoted[3]) : undefined;
|
|
1059
|
+
}
|
|
1060
|
+
|
|
1061
|
+
function nodeIdOf(attribute: Attribute): NodeIdValue {
|
|
1062
|
+
const literal = literalOf(attribute);
|
|
1063
|
+
if (literal !== undefined) return { kind: "literal", value: literal };
|
|
1064
|
+
if (attribute.kind !== "expression") return { kind: "dynamic" };
|
|
1065
|
+
const prefixed = /^`\$\{\s*([\w$]+)\s*\}([^`$\\]*)`$/.exec(attribute.value);
|
|
1066
|
+
if (prefixed) return { kind: "prefixed", prop: prefixed[1] ?? "", suffix: prefixed[2] ?? "" };
|
|
1067
|
+
if (/^[A-Za-z_$][\w$]*$/.test(attribute.value)) return { kind: "prefixed", prop: attribute.value, suffix: "" };
|
|
1068
|
+
return { kind: "dynamic" };
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
function scopeOf(name: string, attribute: Attribute | undefined): Element["scope"] {
|
|
1072
|
+
if (ALWAYS_SITE.has(name)) return "site";
|
|
1073
|
+
if (!attribute) return SITE_BY_DEFAULT.has(name) ? "site" : "page";
|
|
1074
|
+
const value = literalOf(attribute);
|
|
1075
|
+
if (value === "site") return "site";
|
|
1076
|
+
// `item:…` scopes and scopes chosen at run time are not pages; leave them out rather than guess.
|
|
1077
|
+
return value === "page" ? "page" : "unknown";
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
/**
|
|
1081
|
+
* Warns about code that reads the request's query (`Astro.url.searchParams`, `new URL(request.url).searchParams`)
|
|
1082
|
+
* without saying what it reads. A host that caches pages by the parameters they read (Brimsites) cannot tell what
|
|
1083
|
+
* such code needs, so while any is left the pages Brim sees drawn declare nothing and are cached less precisely.
|
|
1084
|
+
* Declared by `readsQuery()` in the file, or for a page of src/pages by `brim({ query })` in astro.config.
|
|
1085
|
+
*/
|
|
1086
|
+
function findUndeclaredQueryReads(root: string, sourceFolder: string, add: (finding: Finding) => void): void {
|
|
1087
|
+
const configFile = ["mjs", "ts", "js", "mts", "cjs"]
|
|
1088
|
+
.map((extension) => join(root, `astro.config.${extension}`))
|
|
1089
|
+
.find((file) => existsSync(file));
|
|
1090
|
+
const declared = configFile ? queryPathsInConfig(readFileSync(configFile, "utf8")) : {};
|
|
1091
|
+
const files = listSources(sourceFolder, CODE_EXTENSIONS.filter((extension) => extension !== ".json"))
|
|
1092
|
+
.filter((path) => !path.endsWith(".d.ts"))
|
|
1093
|
+
.map((path) => ({ file: relative(root, path).split(sep).join("/"), text: readFileSync(path, "utf8") }));
|
|
1094
|
+
for (const { file, line } of undeclaredQueryReads(files, declared)) {
|
|
1095
|
+
add({
|
|
1096
|
+
file,
|
|
1097
|
+
line,
|
|
1098
|
+
severity: "warning",
|
|
1099
|
+
rule: "undeclared-query",
|
|
1100
|
+
message:
|
|
1101
|
+
"reads the request's query without saying which parameters: call readsQuery([\"name\", …]) from " +
|
|
1102
|
+
'"@brimsites/brimjs/server" where it reads them (or declare its route in brim({ query })), so a host caching pages ' +
|
|
1103
|
+
"keeps exactly those. Until then pages are cached less precisely",
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function listSources(folder: string, extensions: string[] = SOURCE_EXTENSIONS): string[] {
|
|
1109
|
+
const found: string[] = [];
|
|
1110
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
1111
|
+
const path = join(folder, entry.name);
|
|
1112
|
+
if (entry.isDirectory()) {
|
|
1113
|
+
if (!SKIPPED_FOLDERS.has(entry.name)) found.push(...listSources(path, extensions));
|
|
1114
|
+
} else if (extensions.includes(extname(entry.name)) && statSync(path).isFile()) {
|
|
1115
|
+
found.push(path);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return found.sort();
|
|
1119
|
+
}
|