astro-helmet 1.3.0 → 1.4.0-beta.2

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/README.md CHANGED
@@ -9,8 +9,12 @@
9
9
  - Control the order of head items.
10
10
  - Include default charset and viewport meta tags.
11
11
  - Order head items with default or specified priority.
12
- - Meta tag deduplication.
12
+ - Meta and resource-hint link deduplication.
13
13
  - JSON-LD structured data helper with automatic `@context`, serialization, and escaping.
14
+ - Optional SEO helper for canonical, robots, Open Graph, Twitter, alternates, and JSON-LD.
15
+ - Resource hint helpers for preconnect, preload, modulepreload, fonts, images, stylesheets, and external scripts.
16
+ - Dev-time validation for common head, SEO, preload, CSP, SRI, and unsafe-content mistakes.
17
+ - Optional Astro CSP hash/resource registration.
14
18
  - Flexible API for adding head items and tag attributes.
15
19
 
16
20
  ## Installation
@@ -39,9 +43,9 @@ const headItems = {
39
43
  { property: 'og:type', content: 'website' }
40
44
  ],
41
45
  link: [{ rel: 'stylesheet', href: 'styles.css' }],
42
- style: [{ innerHTML: 'body { color: red; }' }],
43
- script: [{ innerHTML: 'console.log("Hello, world!")' }],
44
- noscript: [{ innerHTML: 'Please enable JavaScript' }]
46
+ style: [{ textContent: 'body { color: red; }' }],
47
+ script: [{ textContent: 'console.log("Hello, world!")' }],
48
+ noscript: [{ textContent: 'Please enable JavaScript' }]
45
49
  }
46
50
  ---
47
51
 
@@ -54,9 +58,11 @@ const headItems = {
54
58
 
55
59
  Any attribute can be added to a head item. Simply provide the attribute as a key-value pair in the object.
56
60
 
57
- `'innerHTML', 'priority', 'tagName'` are reserved keys and cannot be used as attributes.
61
+ `'innerHTML', 'textContent', 'priority', 'tagName', 'key'` are reserved keys and cannot be used as attributes.
58
62
 
59
- To add content to a tag, use the `innerHTML` key. This will render the content inside the tag. Only pass trusted content to `innerHTML`; it is intended for code and markup that your application controls, such as inline scripts, inline styles, and `noscript` fallbacks.
63
+ To add content to a tag, prefer `textContent`. For `<script>` and `<style>`, `textContent` preserves the code text while escaping closing-tag sequences such as `</script>`. For tags like `<noscript>`, `textContent` is HTML-escaped.
64
+
65
+ Use `innerHTML` only when you intentionally need raw, trusted markup. Do not pass CMS or user-provided strings into `innerHTML` or inline event-handler attributes.
60
66
 
61
67
  To control the order of head items, use the `priority` key.
62
68
 
@@ -69,6 +75,91 @@ const headItems: HeadItems = {
69
75
 
70
76
  See `applyPriority()` in the [Options](#options) section for more information on controlling the order of head items.
71
77
 
78
+ ### Resource Helpers
79
+
80
+ Resource helpers return ordinary `link` or `script` items. They are optional, but they make common performance-sensitive tags harder to mistype.
81
+
82
+ ```ts
83
+ import {
84
+ externalScript,
85
+ modulepreload,
86
+ preconnect,
87
+ preloadFont,
88
+ preloadImage,
89
+ stylesheet,
90
+ type HeadItems
91
+ } from 'astro-helmet'
92
+
93
+ const headItems: HeadItems = {
94
+ title: 'My Site Title',
95
+ link: [
96
+ preconnect('https://cdn.example.com'),
97
+ preloadFont('/fonts/Inter.woff2', { type: 'font/woff2' }),
98
+ preloadImage('/images/hero.jpg', { fetchpriority: 'high' }),
99
+ preloadImage({
100
+ imagesrcset: '/images/hero-640.jpg 640w, /images/hero-1280.jpg 1280w',
101
+ imagesizes: '100vw',
102
+ fetchpriority: 'high'
103
+ }),
104
+ modulepreload('/scripts/entry.js'),
105
+ stylesheet('/styles/site.css')
106
+ ],
107
+ script: [externalScript('/scripts/app.js', { defer: true })]
108
+ }
109
+ ```
110
+
111
+ `preloadImage()` also supports responsive image preloads without a fallback `href`:
112
+
113
+ ```ts
114
+ preloadImage({
115
+ imagesrcset: '/images/hero-640.jpg 640w, /images/hero-1280.jpg 1280w',
116
+ imagesizes: '100vw',
117
+ fetchpriority: 'high'
118
+ })
119
+ ```
120
+
121
+ Use this when you want browsers that support responsive preloads to choose from `imagesrcset` without causing an additional fallback preload in browsers that do not. Width-descriptor `imagesrcset` values such as `640w` should include `imagesizes`; density descriptors such as `1x, 2x` do not need it.
122
+
123
+ ### SEO Helper
124
+
125
+ Use `createSeoHead()` when you want a small typed layer for common SEO tags while still keeping the raw `HeadItems` escape hatch.
126
+
127
+ ```ts
128
+ import { createSeoHead } from 'astro-helmet'
129
+
130
+ const headItems = createSeoHead({
131
+ title: 'My Article',
132
+ titleTemplate: '%s | My Site',
133
+ description: 'A short page description.',
134
+ site: Astro.site,
135
+ path: Astro.url.pathname,
136
+ openGraph: {
137
+ type: 'article',
138
+ siteName: 'My Site',
139
+ image: {
140
+ url: '/images/article.jpg',
141
+ alt: 'Article image',
142
+ width: 1200,
143
+ height: 630
144
+ }
145
+ },
146
+ twitter: {
147
+ site: '@mysite',
148
+ image: '/images/article-twitter.jpg'
149
+ },
150
+ jsonLd: {
151
+ '@type': 'Article',
152
+ headline: 'My Article'
153
+ }
154
+ })
155
+ ```
156
+
157
+ `createSeoHead()` returns normal `HeadItems`, so layout and page data can still be merged:
158
+
159
+ ```astro
160
+ <Helmet headItems={[layoutHeadItems, pageHeadItems]} />
161
+ ```
162
+
72
163
  You can also pass an array of `headItems` to the `Helmet` component:
73
164
 
74
165
  ```astro
@@ -142,7 +233,12 @@ const headItems: HeadItems = {
142
233
  {
143
234
  '@type': 'BreadcrumbList',
144
235
  itemListElement: [
145
- { '@type': 'ListItem', position: 1, name: 'Home', item: 'https://example.com/' },
236
+ {
237
+ '@type': 'ListItem',
238
+ position: 1,
239
+ name: 'Home',
240
+ item: 'https://example.com/'
241
+ },
146
242
  { '@type': 'ListItem', position: 2, name: 'My Article' }
147
243
  ]
148
244
  }
@@ -174,7 +270,28 @@ JSON-LD script tags are rendered with priority `105`, placing them after regular
174
270
  When provided with an array of `headItems`, `astro-helmet` will merge the items together.
175
271
 
176
272
  `headItems.meta` are deduplicated by `name`, `property`, `http-equiv` and `charset`.
177
- Meta items later in the array replace earlier items. Meta tags without any of these keys (e.g. `itemprop`-only tags) are never deduplicated.
273
+ Meta items later in the array replace earlier items. `name` and `http-equiv` matching is case-insensitive. `media` is part of the deduplication key, so media-specific tags such as multiple `theme-color` metas are preserved. Meta tags without any of these keys (e.g. `itemprop`-only tags) are never deduplicated.
274
+
275
+ `headItems.link` deduplicates:
276
+
277
+ - `rel="canonical"` links, keeping the last one.
278
+ - `rel="preconnect"` and `rel="dns-prefetch"` links with the same `href`, keeping the last one.
279
+ - `rel="preload"` and `rel="modulepreload"` links with the same `href`, `as`, `type`, `crossorigin`, `media`, `imagesrcset`, and `imagesizes`, keeping the last one. Responsive image preloads without `href` are deduplicated by `as`, `type`, `crossorigin`, `media`, `imagesrcset`, and `imagesizes`.
280
+
281
+ Any `meta`, `link`, `style`, `script`, or `noscript` item may provide `key` to opt into explicit last-write-wins deduplication:
282
+
283
+ ```ts
284
+ const headItems = [
285
+ {
286
+ title: 'Layout',
287
+ script: [{ key: 'analytics', src: '/analytics-v1.js', defer: true }]
288
+ },
289
+ {
290
+ title: 'Page',
291
+ script: [{ key: 'analytics', src: '/analytics-v2.js', defer: true }]
292
+ }
293
+ ]
294
+ ```
178
295
 
179
296
  `title` and `base` items are also deduplicated, with the last item in the array taking precedence.
180
297
 
@@ -187,16 +304,50 @@ The `Helmet` component takes two props:
187
304
  ```ts
188
305
  interface Props {
189
306
  headItems: HeadItems | HeadItems[]
190
- options?: {
191
- omitHeadTags?: boolean
192
- applyPriority?: (tag: Tag) => Required<Tag>
193
- csp?: boolean
194
- }
307
+ options?: HelmetOptions
195
308
  }
196
309
  ```
197
310
 
198
311
  ### Options
199
312
 
313
+ #### `validate`
314
+
315
+ By default, `<Helmet />` runs `validateHeadItems()` and logs warnings in Astro dev mode. Production builds stay quiet unless you explicitly pass `options.validate`.
316
+
317
+ ```astro
318
+ <Helmet
319
+ {headItems}
320
+ options={{
321
+ validate: {
322
+ requireSri: true,
323
+ baseUrl: Astro.site
324
+ }
325
+ }}
326
+ />
327
+ ```
328
+
329
+ Set `validate: false` to disable component warnings:
330
+
331
+ ```astro
332
+ <Helmet {headItems} options={{ validate: false }} />
333
+ ```
334
+
335
+ You can also call the validator yourself:
336
+
337
+ ```ts
338
+ import { validateHeadItems } from 'astro-helmet'
339
+
340
+ const issues = validateHeadItems(headItems, {
341
+ baseUrl: 'https://example.com',
342
+ requireOpenGraphImage: true,
343
+ requireSri: true
344
+ })
345
+ ```
346
+
347
+ Validation returns structured issues with `code`, `severity`, `message`, `tagName`, and `path`. It checks for common mistakes such as missing titles/descriptions, duplicate or relative canonicals, invalid preloads, preloads without a usable source, responsive image preloads that use width descriptors without `imagesizes`, font preloads without `crossorigin`, incomplete Open Graph basics, relative Open Graph/Twitter image URLs, raw `innerHTML`, inline event attributes, JSON-LD serialization errors, and optional missing SRI on external scripts/styles.
348
+
349
+ Set `requireOpenGraphImage: true` if every shareable page in your project should provide `og:image`. By default, image-less website pages are allowed so dev validation does not warn on simple pages that still have useful `og:title`, `og:type`, and `og:url` tags.
350
+
200
351
  #### `omitHeadTags`
201
352
 
202
353
  By default, `astro-helmet` will render the <head> opening and closing tags around the head items. If you want it to render only the head items, set `omitHeadTags` to `true`.
@@ -218,10 +369,14 @@ const options = { omitHeadTags: true }
218
369
  </html>
219
370
  ```
220
371
 
372
+ When using `omitHeadTags`, keep `<Helmet />` near the top of your manual `<head>`. The generated charset should remain inside the first 1024 bytes of the document and `<base>` should appear before URL-bearing tags.
373
+
221
374
  #### `applyPriority()`
222
375
 
223
376
  The `applyPriority` option allows you to customize the priority of head items. It takes a function that accepts a `Tag` object and returns a `Tag` object with the priority applied.
224
377
 
378
+ The default ordering follows Harry Roberts' [Get Your Head Straight](https://speakerdeck.com/csswizardry/get-your-head-straight) head-order model: document metadata first, early connection hints, async work, blocking work, future-navigation hints, then SEO/social metadata. It is a safe default ordering, not an auto-optimizer. Use explicit priorities when you have measured that a page needs a different critical path.
379
+
225
380
  By default, items are ordered as follows:
226
381
 
227
382
  | priority | item |
@@ -232,65 +387,28 @@ By default, items are ordered as follows:
232
387
  | \-1 | `<meta http-equiv="">` |
233
388
  | 0 | `<title>` |
234
389
  | 10 | `<link rel="preconnect" />` |
390
+ | 11 | `<link rel="dns-prefetch" />` |
235
391
  | 20 | `<script src="" async></script>` |
236
- | 30 | `<style>` where innerHTML.includes('@import') |
392
+ | 30 | `<style>` where innerHTML.includes('@import') |
237
393
  | 40 | `<script>` |
238
394
  | 50 | `<link rel="stylesheet" />` |
239
395
  | 60 | `<link rel="preload" />` |
396
+ | 60 | `<link rel="modulepreload" />` |
240
397
  | 70 | `<script src="" defer></script>` |
241
398
  | 80 | `<link rel="prefetch" />` |
399
+ | 80 | `<link rel="prerender" />` |
242
400
  | 90 | remaining `<link>` |
243
401
  | 100 | remaining `<meta>` |
244
402
  | 105 | `<script type="application/ld+json">` |
245
403
  | 110 | anything else |
246
404
 
247
- This is the default implementation of `applyPriority()`:
405
+ Resource hints are powerful but easy to overuse:
248
406
 
249
- ```ts
250
- function applyPriority(tag: Tag): Required<Tag> {
251
- if (typeof tag.priority === 'number') return tag as Required<Tag>
252
- let priority: number
253
- switch (tag.tagName) {
254
- case 'title':
255
- priority = 0
256
- break
257
-
258
- case 'base':
259
- priority = -2
260
- break
261
-
262
- case 'meta':
263
- if (tag.charset) priority = -4
264
- else if (tag.name === 'viewport') priority = -3
265
- else if (tag['http-equiv']) priority = -1
266
- else priority = 100
267
- break
268
-
269
- case 'link':
270
- if (tag.rel === 'preconnect') priority = 10
271
- else if (tag.rel === 'preload') priority = 60
272
- else if (tag.rel === 'prefetch') priority = 80
273
- else if (tag.rel === 'stylesheet') priority = 50
274
- else priority = 90
275
- break
276
-
277
- case 'style':
278
- priority = tag.innerHTML?.includes('@import') ? 30 : 51
279
- break
280
-
281
- case 'script':
282
- if (tag.type === 'application/ld+json') priority = 105
283
- else if (tag.async) priority = 20
284
- else if (tag.defer) priority = 70
285
- else priority = 40
286
- break
287
-
288
- default:
289
- priority = 110
290
- }
291
- return { ...tag, priority }
292
- }
293
- ```
407
+ - Use `preconnect` sparingly for important third-party origins needed early. Add `crossorigin` only when the eventual request needs a CORS connection.
408
+ - Use `preload` only for critical resources needed by the current navigation. Provide a correct `as`, and include matching `type` and `crossorigin` when needed.
409
+ - Use `modulepreload` for module graphs, not classic scripts.
410
+ - Prefer `<script src async>` over inline async-loader snippets when possible, so the browser's preload scanner can see the URL.
411
+ - Avoid CSS `@import`; direct stylesheet links are easier for browsers to discover in parallel.
294
412
 
295
413
  #### `csp`
296
414
 
@@ -302,7 +420,41 @@ Set `options.csp` to `true` to register inline script/style hashes and external
302
420
 
303
421
  Leave this disabled unless your Astro project has `security.csp` configured. Astro warns when `Astro.csp` is accessed without CSP enabled, so `astro-helmet` keeps CSP registration opt-in.
304
422
 
305
- Provide a custom `applyPriority()` function to reorder head items as needed.
423
+ Astro CSP is available in Astro 6 and newer. In Astro 4 and 5 this option is a no-op. Astro CSP is also a build/preview feature rather than a dev-server feature, and Astro documents limitations with client-side routing.
424
+
425
+ `astro-helmet` registers:
426
+
427
+ - Inline `<style>`, inline `<script>`, and JSON-LD hashes.
428
+ - External `<script src>`.
429
+ - Stylesheet links.
430
+ - `rel="preload"` links with `as="script"` or `as="style"`.
431
+ - `rel="modulepreload"` links as script resources.
432
+
433
+ It does not infer broader CSP directives from icons, images, fonts, analytics endpoints, or connection hints.
434
+
435
+ For CDN scripts and styles, combine browser-level SRI attributes with validation:
436
+
437
+ ```ts
438
+ const headItems = {
439
+ title: 'Secure assets',
440
+ link: [
441
+ {
442
+ rel: 'stylesheet',
443
+ href: 'https://cdn.example.com/site.css',
444
+ integrity: 'sha384-...',
445
+ crossorigin: 'anonymous'
446
+ }
447
+ ],
448
+ script: [
449
+ {
450
+ src: 'https://cdn.example.com/app.js',
451
+ integrity: 'sha384-...',
452
+ crossorigin: 'anonymous',
453
+ defer: true
454
+ }
455
+ ]
456
+ }
457
+ ```
306
458
 
307
459
  ## Defaults
308
460
 
package/index.d.ts CHANGED
@@ -1,53 +1,53 @@
1
+ import type { HeadItems, HelmetOptions } from './src/main.js'
2
+
1
3
  declare const Helmet: (props: {
2
4
  headItems: HeadItems | HeadItems[]
3
- options?: {
4
- omitHeadTags?: boolean
5
- applyPriority?: (tag: Tag) => Required<Tag>
6
- csp?: boolean
7
- }
5
+ options?: HelmetOptions
8
6
  }) => unknown
9
7
 
10
8
  export default Helmet
11
9
 
12
- type TagName =
13
- | 'title'
14
- | 'base'
15
- | 'meta'
16
- | 'link'
17
- | 'style'
18
- | 'script'
19
- | 'noscript'
20
-
21
- type BaseItem = {
22
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
23
- [key: string]: any
24
- priority?: number
25
- }
26
-
27
- type ContentItem = BaseItem & {
28
- innerHTML?: string
29
- }
30
-
31
- export type Tag = (BaseItem | ContentItem) & {
32
- tagName: TagName
33
- priority?: number
34
- }
35
-
36
- export type JsonLdItem = {
37
- '@type': string
38
- /** Automatically injected - do not provide. */
39
- '@context'?: never
40
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
41
- [key: string]: any
42
- }
10
+ export {
11
+ createSeoHead,
12
+ dnsPrefetch,
13
+ externalScript,
14
+ modulepreload,
15
+ preconnect,
16
+ preload,
17
+ preloadFont,
18
+ preloadImage,
19
+ stylesheet,
20
+ validateHeadItems
21
+ } from './src/main.js'
43
22
 
44
- export type HeadItems = {
45
- title?: string
46
- base?: BaseItem[]
47
- meta?: BaseItem[]
48
- link?: BaseItem[]
49
- style?: ContentItem[]
50
- script?: ContentItem[]
51
- noscript?: ContentItem[]
52
- jsonLd?: JsonLdItem | JsonLdItem[]
53
- }
23
+ export type {
24
+ AlternateLink,
25
+ CrossOrigin,
26
+ ExternalScriptOptions,
27
+ FetchPriority,
28
+ HeadItems,
29
+ HeadValidationCode,
30
+ HeadValidationIssue,
31
+ HeadValidationOptions,
32
+ HeadValidationSeverity,
33
+ HelmetOptions,
34
+ JsonLdItem,
35
+ LinkItem,
36
+ MetaItem,
37
+ NoscriptItem,
38
+ OpenGraphOptions,
39
+ PreloadFontOptions,
40
+ PreloadImageOptions,
41
+ PreloadOptions,
42
+ ReferrerPolicy,
43
+ ResponsivePreloadImageOptions,
44
+ ResourceHintOptions,
45
+ RobotsOptions,
46
+ ScriptItem,
47
+ SeoHeadOptions,
48
+ SeoImage,
49
+ StyleItem,
50
+ StylesheetOptions,
51
+ Tag,
52
+ TwitterOptions
53
+ } from './src/main.js'
package/index.ts CHANGED
@@ -2,4 +2,47 @@ import Helmet from './src/Helmet.astro'
2
2
 
3
3
  export default Helmet
4
4
 
5
- export type { HeadItems, JsonLdItem, Tag } from './src/main'
5
+ export {
6
+ createSeoHead,
7
+ dnsPrefetch,
8
+ externalScript,
9
+ modulepreload,
10
+ preconnect,
11
+ preload,
12
+ preloadFont,
13
+ preloadImage,
14
+ stylesheet,
15
+ validateHeadItems
16
+ } from './src/main'
17
+
18
+ export type {
19
+ AlternateLink,
20
+ CrossOrigin,
21
+ ExternalScriptOptions,
22
+ FetchPriority,
23
+ HeadItems,
24
+ HeadValidationCode,
25
+ HeadValidationIssue,
26
+ HeadValidationOptions,
27
+ HeadValidationSeverity,
28
+ HelmetOptions,
29
+ JsonLdItem,
30
+ LinkItem,
31
+ MetaItem,
32
+ NoscriptItem,
33
+ OpenGraphOptions,
34
+ PreloadFontOptions,
35
+ PreloadImageOptions,
36
+ PreloadOptions,
37
+ ReferrerPolicy,
38
+ ResponsivePreloadImageOptions,
39
+ ResourceHintOptions,
40
+ RobotsOptions,
41
+ ScriptItem,
42
+ SeoHeadOptions,
43
+ SeoImage,
44
+ StyleItem,
45
+ StylesheetOptions,
46
+ Tag,
47
+ TwitterOptions
48
+ } from './src/main'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "astro-helmet",
3
- "version": "1.3.0",
3
+ "version": "1.4.0-beta.2",
4
4
  "type": "module",
5
5
  "description": "A document head manager for astro.",
6
6
  "author": "Ryan Voitiskis <ryanvoitiskis@pm.me> (https://ryanvoitiskis.com/)",
package/src/Helmet.astro CHANGED
@@ -1,17 +1,35 @@
1
1
  ---
2
- import { type HeadItems, type Tag, renderHead, getInlineContent, getExternalResources } from './main'
2
+ import {
3
+ type HeadItems,
4
+ type HelmetOptions,
5
+ renderHead,
6
+ getInlineContent,
7
+ getExternalResources,
8
+ validateHeadItems
9
+ } from './main'
3
10
 
4
11
  interface Props {
5
12
  headItems: HeadItems | HeadItems[]
6
- options?: {
7
- omitHeadTags?: boolean
8
- applyPriority?: (tag: Tag) => Required<Tag>
9
- csp?: boolean
10
- }
13
+ options?: HelmetOptions
11
14
  }
12
15
 
13
16
  const { headItems, options = {} } = Astro.props as Props
14
- const { applyPriority, omitHeadTags = false, csp: cspEnabled = false } = options
17
+ const {
18
+ applyPriority,
19
+ omitHeadTags = false,
20
+ csp: cspEnabled = false,
21
+ validate = import.meta.env.DEV
22
+ } = options
23
+ if (validate) {
24
+ const validationOptions = typeof validate === 'object' ? validate : undefined
25
+ for (const issue of validateHeadItems(headItems, validationOptions)) {
26
+ console.warn(
27
+ `[astro-helmet] ${issue.code}: ${issue.message}${
28
+ issue.path ? ` (${issue.path})` : ''
29
+ }`
30
+ )
31
+ }
32
+ }
15
33
  const head = renderHead(headItems, applyPriority)
16
34
 
17
35
  // Register CSP hashes and resources when the consumer opts in via `options.csp`
@@ -20,14 +38,16 @@ const head = renderHead(headItems, applyPriority)
20
38
  // silent for users who don't need CSP integration. Cast avoids typecheck
21
39
  // failures for downstream consumers on Astro 4/5.
22
40
  const csp = cspEnabled
23
- ? (Astro as unknown as {
24
- csp?: {
25
- insertScriptHash(hash: string): void
26
- insertStyleHash(hash: string): void
27
- insertScriptResource(resource: string): void
28
- insertStyleResource(resource: string): void
41
+ ? (
42
+ Astro as unknown as {
43
+ csp?: {
44
+ insertScriptHash(hash: string): void
45
+ insertStyleHash(hash: string): void
46
+ insertScriptResource(resource: string): void
47
+ insertStyleResource(resource: string): void
48
+ }
29
49
  }
30
- }).csp
50
+ ).csp
31
51
  : undefined
32
52
  if (csp) {
33
53
  for (const { type, content } of getInlineContent(headItems)) {