astro-helmet 1.3.0 → 1.4.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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,74 @@ 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
+ modulepreload('/scripts/entry.js'),
100
+ stylesheet('/styles/site.css')
101
+ ],
102
+ script: [externalScript('/scripts/app.js', { defer: true })]
103
+ }
104
+ ```
105
+
106
+ ### SEO Helper
107
+
108
+ Use `createSeoHead()` when you want a small typed layer for common SEO tags while still keeping the raw `HeadItems` escape hatch.
109
+
110
+ ```ts
111
+ import { createSeoHead } from 'astro-helmet'
112
+
113
+ const headItems = createSeoHead({
114
+ title: 'My Article',
115
+ titleTemplate: '%s | My Site',
116
+ description: 'A short page description.',
117
+ site: Astro.site,
118
+ path: Astro.url.pathname,
119
+ openGraph: {
120
+ type: 'article',
121
+ siteName: 'My Site',
122
+ image: {
123
+ url: '/images/article.jpg',
124
+ alt: 'Article image',
125
+ width: 1200,
126
+ height: 630
127
+ }
128
+ },
129
+ twitter: {
130
+ site: '@mysite',
131
+ image: '/images/article-twitter.jpg'
132
+ },
133
+ jsonLd: {
134
+ '@type': 'Article',
135
+ headline: 'My Article'
136
+ }
137
+ })
138
+ ```
139
+
140
+ `createSeoHead()` returns normal `HeadItems`, so layout and page data can still be merged:
141
+
142
+ ```astro
143
+ <Helmet headItems={[layoutHeadItems, pageHeadItems]} />
144
+ ```
145
+
72
146
  You can also pass an array of `headItems` to the `Helmet` component:
73
147
 
74
148
  ```astro
@@ -142,7 +216,12 @@ const headItems: HeadItems = {
142
216
  {
143
217
  '@type': 'BreadcrumbList',
144
218
  itemListElement: [
145
- { '@type': 'ListItem', position: 1, name: 'Home', item: 'https://example.com/' },
219
+ {
220
+ '@type': 'ListItem',
221
+ position: 1,
222
+ name: 'Home',
223
+ item: 'https://example.com/'
224
+ },
146
225
  { '@type': 'ListItem', position: 2, name: 'My Article' }
147
226
  ]
148
227
  }
@@ -174,7 +253,28 @@ JSON-LD script tags are rendered with priority `105`, placing them after regular
174
253
  When provided with an array of `headItems`, `astro-helmet` will merge the items together.
175
254
 
176
255
  `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.
256
+ 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.
257
+
258
+ `headItems.link` deduplicates:
259
+
260
+ - `rel="canonical"` links, keeping the last one.
261
+ - `rel="preconnect"` and `rel="dns-prefetch"` links with the same `href`, keeping the last one.
262
+ - `rel="preload"` and `rel="modulepreload"` links with the same `href`, `as`, `type`, `crossorigin`, `media`, `imagesrcset`, and `imagesizes`, keeping the last one.
263
+
264
+ Any `meta`, `link`, `style`, `script`, or `noscript` item may provide `key` to opt into explicit last-write-wins deduplication:
265
+
266
+ ```ts
267
+ const headItems = [
268
+ {
269
+ title: 'Layout',
270
+ script: [{ key: 'analytics', src: '/analytics-v1.js', defer: true }]
271
+ },
272
+ {
273
+ title: 'Page',
274
+ script: [{ key: 'analytics', src: '/analytics-v2.js', defer: true }]
275
+ }
276
+ ]
277
+ ```
178
278
 
179
279
  `title` and `base` items are also deduplicated, with the last item in the array taking precedence.
180
280
 
@@ -187,16 +287,50 @@ The `Helmet` component takes two props:
187
287
  ```ts
188
288
  interface Props {
189
289
  headItems: HeadItems | HeadItems[]
190
- options?: {
191
- omitHeadTags?: boolean
192
- applyPriority?: (tag: Tag) => Required<Tag>
193
- csp?: boolean
194
- }
290
+ options?: HelmetOptions
195
291
  }
196
292
  ```
197
293
 
198
294
  ### Options
199
295
 
296
+ #### `validate`
297
+
298
+ By default, `<Helmet />` runs `validateHeadItems()` and logs warnings in Astro dev mode. Production builds stay quiet unless you explicitly pass `options.validate`.
299
+
300
+ ```astro
301
+ <Helmet
302
+ {headItems}
303
+ options={{
304
+ validate: {
305
+ requireSri: true,
306
+ baseUrl: Astro.site
307
+ }
308
+ }}
309
+ />
310
+ ```
311
+
312
+ Set `validate: false` to disable component warnings:
313
+
314
+ ```astro
315
+ <Helmet {headItems} options={{ validate: false }} />
316
+ ```
317
+
318
+ You can also call the validator yourself:
319
+
320
+ ```ts
321
+ import { validateHeadItems } from 'astro-helmet'
322
+
323
+ const issues = validateHeadItems(headItems, {
324
+ baseUrl: 'https://example.com',
325
+ requireOpenGraphImage: true,
326
+ requireSri: true
327
+ })
328
+ ```
329
+
330
+ 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, 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.
331
+
332
+ 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.
333
+
200
334
  #### `omitHeadTags`
201
335
 
202
336
  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 +352,14 @@ const options = { omitHeadTags: true }
218
352
  </html>
219
353
  ```
220
354
 
355
+ 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.
356
+
221
357
  #### `applyPriority()`
222
358
 
223
359
  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
360
 
361
+ 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.
362
+
225
363
  By default, items are ordered as follows:
226
364
 
227
365
  | priority | item |
@@ -232,65 +370,28 @@ By default, items are ordered as follows:
232
370
  | \-1 | `<meta http-equiv="">` |
233
371
  | 0 | `<title>` |
234
372
  | 10 | `<link rel="preconnect" />` |
373
+ | 11 | `<link rel="dns-prefetch" />` |
235
374
  | 20 | `<script src="" async></script>` |
236
- | 30 | `<style>` where innerHTML.includes('@import') |
375
+ | 30 | `<style>` where innerHTML.includes('@import') |
237
376
  | 40 | `<script>` |
238
377
  | 50 | `<link rel="stylesheet" />` |
239
378
  | 60 | `<link rel="preload" />` |
379
+ | 60 | `<link rel="modulepreload" />` |
240
380
  | 70 | `<script src="" defer></script>` |
241
381
  | 80 | `<link rel="prefetch" />` |
382
+ | 80 | `<link rel="prerender" />` |
242
383
  | 90 | remaining `<link>` |
243
384
  | 100 | remaining `<meta>` |
244
385
  | 105 | `<script type="application/ld+json">` |
245
386
  | 110 | anything else |
246
387
 
247
- This is the default implementation of `applyPriority()`:
388
+ Resource hints are powerful but easy to overuse:
248
389
 
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
- ```
390
+ - Use `preconnect` sparingly for important third-party origins needed early. Add `crossorigin` only when the eventual request needs a CORS connection.
391
+ - Use `preload` only for critical resources needed by the current navigation. Provide a correct `as`, and include matching `type` and `crossorigin` when needed.
392
+ - Use `modulepreload` for module graphs, not classic scripts.
393
+ - Prefer `<script src async>` over inline async-loader snippets when possible, so the browser's preload scanner can see the URL.
394
+ - Avoid CSS `@import`; direct stylesheet links are easier for browsers to discover in parallel.
294
395
 
295
396
  #### `csp`
296
397
 
@@ -302,7 +403,41 @@ Set `options.csp` to `true` to register inline script/style hashes and external
302
403
 
303
404
  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
405
 
305
- Provide a custom `applyPriority()` function to reorder head items as needed.
406
+ 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.
407
+
408
+ `astro-helmet` registers:
409
+
410
+ - Inline `<style>`, inline `<script>`, and JSON-LD hashes.
411
+ - External `<script src>`.
412
+ - Stylesheet links.
413
+ - `rel="preload"` links with `as="script"` or `as="style"`.
414
+ - `rel="modulepreload"` links as script resources.
415
+
416
+ It does not infer broader CSP directives from icons, images, fonts, analytics endpoints, or connection hints.
417
+
418
+ For CDN scripts and styles, combine browser-level SRI attributes with validation:
419
+
420
+ ```ts
421
+ const headItems = {
422
+ title: 'Secure assets',
423
+ link: [
424
+ {
425
+ rel: 'stylesheet',
426
+ href: 'https://cdn.example.com/site.css',
427
+ integrity: 'sha384-...',
428
+ crossorigin: 'anonymous'
429
+ }
430
+ ],
431
+ script: [
432
+ {
433
+ src: 'https://cdn.example.com/app.js',
434
+ integrity: 'sha384-...',
435
+ crossorigin: 'anonymous',
436
+ defer: true
437
+ }
438
+ ]
439
+ }
440
+ ```
306
441
 
307
442
  ## Defaults
308
443
 
package/index.d.ts CHANGED
@@ -1,53 +1,52 @@
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
+ ResourceHintOptions,
44
+ RobotsOptions,
45
+ ScriptItem,
46
+ SeoHeadOptions,
47
+ SeoImage,
48
+ StyleItem,
49
+ StylesheetOptions,
50
+ Tag,
51
+ TwitterOptions
52
+ } from './src/main.js'
package/index.ts CHANGED
@@ -2,4 +2,46 @@ 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
+ ResourceHintOptions,
39
+ RobotsOptions,
40
+ ScriptItem,
41
+ SeoHeadOptions,
42
+ SeoImage,
43
+ StyleItem,
44
+ StylesheetOptions,
45
+ Tag,
46
+ TwitterOptions
47
+ } 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.1",
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)) {