@nera-static/plugin-utils 1.7.0 → 1.8.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/CHANGELOG.md CHANGED
@@ -5,6 +5,72 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.8.0] - 2026-11-27
9
+
10
+ The second half of the helpers Nera plugins, core and the tools copy from
11
+ each other: languages, dates, URLs and `base_path`, escaping, frontmatter,
12
+ glob matching, package names and page selection. Each subpath is written
13
+ once from the best sibling variant and documented in the README under
14
+ "Shared helpers". Nothing in `.` or in the 1.7.0 subpaths changed, and no
15
+ runtime dependency was added (still `js-yaml` only).
16
+
17
+ If you replace a local copy with one of these, check the shapes below: several
18
+ differ from what some siblings return today.
19
+
20
+ ### Added
21
+
22
+ - **`@nera-static/plugin-utils/html`**: `escapeHtml` (`& < > " '`, `'` as
23
+ `&#39;`), `escapeXml` (`'` as `&apos;`, and the characters XML 1.0 forbids
24
+ even escaped are dropped) and `escapeRegExp`. Every escaper takes any
25
+ value: `null` and `undefined` give `''`, so `escapeHtml(null)` is `''`, not
26
+ `'null'`
27
+ - **`@nera-static/plugin-utils/lang`**: `siteLang(app, fallback = 'en')`,
28
+ `pageLang(meta, app, fallback = 'en')`, `siteLanguages(app)`,
29
+ `isLanguageMap(value, languages)` and `localize(value, lang, { fallbacks,
30
+ any })`. Languages are trimmed and a blank one counts as absent, so
31
+ `lang: 'de '` is `de`. `localize` returns `null` (not `undefined`) when no
32
+ entry fits
33
+ - **`@nera-static/plugin-utils/dates`**: `toDate(value)`, `formatW3C(value)`,
34
+ `pageDate(meta, 'published' | 'updated', { warn })`, `byDate(get, {
35
+ descending })` and the frozen key lists `PUBLISHED_KEYS` (`date`,
36
+ `datePublished`, `published`) and `UPDATED_KEYS` (`updated`, `updatedAt`,
37
+ `lastmod`, `dateModified`). **`createdAt` is never read**: core fills it
38
+ from the file's birth time, which CI stamps alike for every file. A time
39
+ without an offset is read as UTC, an impossible day such as `2026-02-30` is
40
+ no date, and only `Z` and `±hh:mm` offsets are accepted (`+0200` is not).
41
+ `pageDate` takes the first valid key and warns once per invalid value;
42
+ `byDate` puts items without a date last in both directions
43
+ - **`@nera-static/plugin-utils/sort`**: `byString` and `byHref`, comparing
44
+ code units instead of `localeCompare`, so the order is the same on every
45
+ machine
46
+ - **`@nera-static/plugin-utils/urls`**: `resolveOrigin({ cwd, app })`
47
+ (`app.origin`, else canonical-links' `app_origin`, trimmed),
48
+ `encodePath`, `joinUrl` and `siteUrl` (percent-encoded, so a canonical
49
+ link and a sitemap URL of a page are the same string),
50
+ `normalizeBasePath`, `withBasePath` and `stripBasePath` (core's exact
51
+ `base_path` rules), `hasScheme`, `isInside(root, target, { self })` (a
52
+ child folder named `..foo` is inside), and `srcsetUrls`/`mapSrcset`. The
53
+ `srcset` helpers follow the HTML candidate rule, where a URL ends at
54
+ whitespace: `/a.jpg?w=1,2` and data URIs stay whole, unlike splitting on
55
+ commas
56
+ - **`@nera-static/plugin-utils/frontmatter`**: `FRONTMATTER_OPTIONS`, core's
57
+ frozen `yaml` options (`timestamp`, `<<` merge, last duplicate key wins),
58
+ and `splitFrontmatter(raw)` → `{ yamlText, body }` by core's fence rule
59
+ (`----` and `--- ` are no fences, an unclosed block is YAML to the end).
60
+ It returns `null` when the file has no frontmatter
61
+ - **`@nera-static/plugin-utils/glob`**: `matchesPattern` and `matchesAny`
62
+ (the `*` glob of the sitemap and feed `exclude` lists), and, mirroring
63
+ core's `.neraignore` handling, `IGNORE_FILE`, `readIgnoreList(cwd)` and
64
+ `isIgnoredAsset(list, file, root)` (`true` means skipped)
65
+ - **`@nera-static/plugin-utils/packages`** gains the package-name rules:
66
+ `isPluginPackage(name)` (core's plugin discovery), `pluginShortName(name)`,
67
+ `pluginPackage(spec)`, which returns `{ name, pkg }` and throws a
68
+ `TypeError` for an invalid spec, and `themePackage(spec)` (core's rule,
69
+ `null` for a local or blank spec)
70
+ - **`@nera-static/plugin-utils/pages`**: `isRenderedPage(meta)` (non-blank
71
+ `layout` and `href`) and `isNoindex(meta, app)` (`noindex` in the page's
72
+ `robots`, else the site's)
73
+
8
74
  ## [1.7.0] - 2026-11-27
9
75
 
10
76
  The helpers that Nera plugins, core and the tools copy from each other now
package/README.md CHANGED
@@ -175,15 +175,23 @@ process.exit(result ? 0 : 1)
175
175
 
176
176
  ## 🧩 Shared helpers (subpath exports)
177
177
 
178
- Since 1.7.0 the helpers that Nera plugins, core and the tools used to copy from each other live here, one subpath per family. Import them from the subpath, never write a local copy. The `.` export above is unchanged. None of them prints unless that is its job (the logger), reads globals beyond a `cwd` default of `process.cwd()`, or calls `process.exit`.
178
+ Since 1.7.0 the helpers that Nera plugins, core and the tools used to copy from each other live here, one subpath per family (1.8.0 added `/html` to `/pages`). Import them from the subpath, never write a local copy. The `.` export above is unchanged. None of them prints unless that is its job (the logger, `pageDate`'s warning), reads globals beyond a `cwd` default of `process.cwd()`, or calls `process.exit`.
179
179
 
180
180
  | Subpath | Exports |
181
181
  |---|---|
182
182
  | `@nera-static/plugin-utils/values` | `isPlainObject`, `isText`, `textOr` |
183
183
  | `@nera-static/plugin-utils/log` | `createLogger` |
184
184
  | `@nera-static/plugin-utils/config` | `getConfig`, `loadPluginConfig`, `createConfigReader` |
185
- | `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion` |
185
+ | `@nera-static/plugin-utils/packages` | `requireFromSite`, `ownVersion`, `isPluginPackage`, `pluginShortName`, `pluginPackage`, `themePackage` |
186
186
  | `@nera-static/plugin-utils/guard` | `satisfiesFloor`, `coreVersion`, `assertCoreVersion`, `GET_ASSETS_CORE` |
187
+ | `@nera-static/plugin-utils/html` | `escapeHtml`, `escapeXml`, `escapeRegExp` |
188
+ | `@nera-static/plugin-utils/lang` | `siteLang`, `pageLang`, `siteLanguages`, `isLanguageMap`, `localize` |
189
+ | `@nera-static/plugin-utils/dates` | `toDate`, `formatW3C`, `PUBLISHED_KEYS`, `UPDATED_KEYS`, `pageDate`, `byDate` |
190
+ | `@nera-static/plugin-utils/sort` | `byString`, `byHref` |
191
+ | `@nera-static/plugin-utils/urls` | `resolveOrigin`, `encodePath`, `joinUrl`, `siteUrl`, `normalizeBasePath`, `withBasePath`, `stripBasePath`, `hasScheme`, `isInside`, `srcsetUrls`, `mapSrcset` |
192
+ | `@nera-static/plugin-utils/frontmatter` | `FRONTMATTER_OPTIONS`, `splitFrontmatter` |
193
+ | `@nera-static/plugin-utils/glob` | `matchesPattern`, `matchesAny`, `IGNORE_FILE`, `readIgnoreList`, `isIgnoredAsset` |
194
+ | `@nera-static/plugin-utils/pages` | `isRenderedPage`, `isNoindex` |
187
195
 
188
196
  ### `/values` — checks for parsed YAML and frontmatter
189
197
 
@@ -322,6 +330,40 @@ const themeDir = siteRequire.resolve('@nera-static/theme-blog/package.json')
322
330
  const version = ownVersion(import.meta.url) // your package's version, e.g. '1.2.0'
323
331
  ```
324
332
 
333
+ #### `isPluginPackage(name: unknown): boolean`
334
+
335
+ Whether core loads the dependency `name` as a plugin: an `@nera-static/plugin-*` package other than the library `@nera-static/plugin-utils`, core's own rule. The scope's other members (`core`, `nera`, `validate`, `theme-*`, `starter-*`) are no plugins; a non-string is `false`.
336
+
337
+ #### `pluginShortName(name: string): string`
338
+
339
+ The name core shows a plugin package under, in its log and in `config/plugin-order.yaml`: the package name without `@nera-static/`. Any other name is returned unchanged.
340
+
341
+ #### `pluginPackage(spec: unknown): { name: string, pkg: string }`
342
+
343
+ The official plugin a spec names, in the forms `nera plugin add` takes: `<name>`, `plugin-<name>` or `@nera-static/plugin-<name>`. `name` is the bare name (`'sitemap'`), `pkg` the package. Throws a `TypeError` for anything else (another scope, a version or tag such as `sitemap@1`, a path, an uppercase name, `utils`), with a message that names the accepted forms and the catalog at https://nera.js.org/plugins/.
344
+
345
+ #### `themePackage(spec: unknown): string | null`
346
+
347
+ The npm package a `theme:` spec (`app.theme`) names, by core's rule: a scoped name or one with a `/` is used verbatim (a third-party theme), a bare name becomes `@nera-static/theme-<name>`. `null` for a local theme (a spec starting with `.`) and for a missing or blank spec: no package.
348
+
349
+ ```js
350
+ import { isPluginPackage, pluginPackage, pluginShortName, themePackage } from '@nera-static/plugin-utils/packages'
351
+
352
+ isPluginPackage('@nera-static/plugin-tags') // true
353
+ isPluginPackage('@nera-static/plugin-utils') // false
354
+ isPluginPackage('@nera-static/theme-blog') // false
355
+
356
+ pluginShortName('@nera-static/plugin-tags') // 'plugin-tags'
357
+
358
+ pluginPackage('sitemap') // { name: 'sitemap', pkg: '@nera-static/plugin-sitemap' }
359
+ pluginPackage('plugin-sitemap') // the same
360
+ pluginPackage('utils') // throws TypeError: "utils" is not a Nera plugin. …
361
+
362
+ themePackage('blog') // '@nera-static/theme-blog'
363
+ themePackage('@acme/theme-x') // '@acme/theme-x'
364
+ themePackage('./theme') // null
365
+ ```
366
+
325
367
  ### `/guard` — failing loudly on a too-old core
326
368
 
327
369
  A plugin that relies on a hook of a newer `@nera-static/core` (`getAssets` since 4.13.0) is silently never called on an older one, and the build still exits 0. Check core's version from `getAppData` and fail loudly instead; `peerDependencies` reports the same at install time, the guard catches an install that ignored it.
@@ -362,6 +404,303 @@ satisfiesFloor('4.13.0-beta.1', '4.13.0') // false
362
404
  satisfiesFloor('latest', '4.13.0') // false
363
405
  ```
364
406
 
407
+ ### `/html` — escaping
408
+
409
+ Each escaper takes any value: `null` and `undefined` give `''`, everything else is converted with `String()` first. Each escapes once (`&amp;` becomes `&amp;amp;`).
410
+
411
+ #### `escapeHtml(value: unknown): string`
412
+
413
+ `& < > " '` as entities (`'` as `&#39;`), safe in a text node and in a double- or single-quoted attribute.
414
+
415
+ #### `escapeXml(value: unknown): string`
416
+
417
+ `& < > " '` as entities (`'` as `&apos;`), and the characters XML 1.0 forbids even escaped (C0 controls other than tab, LF and CR; lone surrogates; U+FFFE and U+FFFF) **dropped**, so any page text gives a well-formed feed or sitemap.
418
+
419
+ #### `escapeRegExp(value: unknown): string`
420
+
421
+ Every regular-expression special character (`. * + ? ^ $ { } ( ) | [ ] \`) escaped, for a `RegExp` that matches the text literally.
422
+
423
+ ```js
424
+ import { escapeHtml, escapeRegExp, escapeXml } from '@nera-static/plugin-utils/html'
425
+
426
+ escapeHtml('<a href="x">Tom & Jerry\'s</a>')
427
+ // '&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&#39;s&lt;/a&gt;'
428
+ escapeHtml(null) // ''
429
+ escapeHtml(42) // '42'
430
+ escapeXml('Tom & Jerry\'s\u0007') // 'Tom &amp; Jerry&apos;s' (the BEL is dropped)
431
+ escapeRegExp('a.b*(c)') // 'a\\.b\\*\\(c\\)'
432
+ ```
433
+
434
+ ### `/lang` — languages and translated values
435
+
436
+ A language is text, **trimmed**: `lang: 'de '` is `de`, and a blank `lang` counts as absent.
437
+
438
+ #### `siteLang(app, fallback = 'en'): string`
439
+
440
+ `app.lang` trimmed, else `fallback`.
441
+
442
+ #### `pageLang(meta, app, fallback = 'en'): string`
443
+
444
+ `meta.lang` trimmed, else `siteLang(app, fallback)`.
445
+
446
+ #### `siteLanguages(app): Set<string>`
447
+
448
+ `app.lang` plus the keys of `app.translations`, each trimmed, blank ones left out. Empty when the site sets neither.
449
+
450
+ #### `isLanguageMap(value: unknown, languages?: Iterable<string>): boolean`
451
+
452
+ Whether `value` is a non-empty plain object and, when `languages` is given, every key is one of them. A map lacking a language still counts (`localize` falls back).
453
+
454
+ #### `localize(value: unknown, lang: string, { fallbacks = [], any = false } = {}): string | null`
455
+
456
+ One value in one language. A string is returned as it is. A language map gives its entry for `lang`, else for the first of `fallbacks` it has, else, with `any`, its first entry; only text entries count, so `de: ''` falls back. Anything else, and a map without a usable entry, gives **`null`** (not `undefined`).
457
+
458
+ ```js
459
+ import { isLanguageMap, localize, pageLang, siteLang, siteLanguages } from '@nera-static/plugin-utils/lang'
460
+
461
+ siteLang({ lang: ' de ' }) // 'de'
462
+ siteLang({}) // 'en'
463
+ pageLang({ lang: 'de ' }, { lang: 'en' }) // 'de'
464
+ pageLang({ lang: ' ' }, { lang: 'fr' }) // 'fr'
465
+ siteLanguages({ lang: 'en', translations: { de: {}, ' es ': {} } }) // Set { 'en', 'de', 'es' }
466
+ isLanguageMap({ en: 'a', xx: 'b' }, ['en', 'de']) // false
467
+
468
+ localize({ en: 'Hi', de: 'Hallo' }, 'de') // 'Hallo'
469
+ localize({ en: 'Hi' }, 'de') // null
470
+ localize({ en: 'Hi' }, 'de', { fallbacks: ['en'] }) // 'Hi'
471
+ localize({ fr: 'Salut' }, 'de', { any: true }) // 'Salut'
472
+ localize('Hi', 'de') // 'Hi'
473
+ ```
474
+
475
+ ### `/dates` — frontmatter dates
476
+
477
+ Nothing here reads the build machine's time zone: a time without an offset is read as **UTC**, as YAML reads an unquoted timestamp, so a site gives the same dates and the same order on every machine.
478
+
479
+ #### `toDate(value: unknown): Date | null`
480
+
481
+ A valid `Date` (core parses an unquoted frontmatter date into one), or a string `YYYY-MM-DD`, optionally followed by `T` or a space and `hh:mm[:ss[.fraction]]` with an optional `Z` or `±hh:mm` offset (surrounding whitespace ignored). A day or time that does not exist (`2026-02-30`, `24:00`) is `null`, as is every other form (`1.10.2026`, a number, an offset like `+0200`).
482
+
483
+ #### `formatW3C(value: unknown): string | null`
484
+
485
+ The date in W3C Datetime form, in UTC: `YYYY-MM-DD` for UTC midnight, else `YYYY-MM-DDThh:mm:ssZ` without milliseconds. Takes whatever `toDate` takes; `null` when that is no date.
486
+
487
+ #### `PUBLISHED_KEYS`
488
+
489
+ `['date', 'datePublished', 'published']`, frozen: the keys `pageDate(meta, 'published')` tries, in order.
490
+
491
+ #### `UPDATED_KEYS`
492
+
493
+ `['updated', 'updatedAt', 'lastmod', 'dateModified']`, frozen: the keys `pageDate(meta, 'updated')` tries, in order.
494
+
495
+ **`createdAt` is in neither list**: core fills it from the file's birth time when the frontmatter has no date, and CI stamps every file alike. A caller that wants it as a fallback for sorting passes it to `byDate` itself.
496
+
497
+ #### `pageDate(meta, kind: 'published' | 'updated', { warn = console.warn } = {}): Date | null`
498
+
499
+ The first key of the list for `kind` whose value is a usable date; `null` when none is. A present value that is no date warns once (`<href>: ignoring <key> <value>, expected a date like …`) and the next key is tried; an absent, `null` or blank value is skipped silently. Pass your logger's `warn`. Any other `kind` throws a `TypeError`.
500
+
501
+ #### `byDate(get, { descending = false } = {}): (a, b) => number`
502
+
503
+ A comparator for `Array.prototype.sort`: `get(item)` returns the item's date in any form `toDate` takes. Oldest first, newest first with `descending`; items without a usable date go **last in both directions**. Equal dates give `0`, so chain a tie-break (`byDate(get)(a, b) || byHref(a, b)`). Throws a `TypeError` when `get` is not a function.
504
+
505
+ ```js
506
+ import { byDate, formatW3C, pageDate, toDate } from '@nera-static/plugin-utils/dates'
507
+ import { createLogger } from '@nera-static/plugin-utils/log'
508
+
509
+ toDate('2026-10-01') // 2026-10-01T00:00:00.000Z
510
+ toDate('2026-10-01 09:30') // 2026-10-01T09:30:00.000Z (UTC)
511
+ toDate('2026-10-01T09:30:00+02:00') // 2026-10-01T07:30:00.000Z
512
+ toDate('2026-02-30') // null
513
+
514
+ formatW3C('2026-10-01') // '2026-10-01'
515
+ formatW3C('2026-10-01T09:30:15.250+02:00') // '2026-10-01T07:30:15Z'
516
+
517
+ const log = createLogger('plugin-feed')
518
+ pageDate({ href: '/a.html', date: '2026-02-30', published: '2026-10-01' }, 'published', { warn: log.warn })
519
+ // 2026-10-01T00:00:00.000Z, after
520
+ // ⚠️ plugin-feed: /a.html: ignoring date "2026-02-30", expected a date like 2026-10-01 or 2026-10-01T09:30:00Z
521
+
522
+ pagesData.sort(byDate((page) => page.meta.date, { descending: true }))
523
+ // newest first, pages without a date at the end
524
+ ```
525
+
526
+ ### `/sort` — locale-free comparators
527
+
528
+ They compare UTF-16 code units, like `<` on strings, never with `localeCompare`: the order is the same on every machine (uppercase before lowercase, ASCII before other letters).
529
+
530
+ #### `byString(a: unknown, b: unknown): -1 | 0 | 1`
531
+
532
+ Two strings by code unit; a non-string compares as `''` and sorts first.
533
+
534
+ #### `byHref(a, b): -1 | 0 | 1`
535
+
536
+ Two pages (`{ meta }`) or two metas by `href` (`x.meta?.href ?? x.href`), as `byString`.
537
+
538
+ ```js
539
+ import { byHref, byString } from '@nera-static/plugin-utils/sort'
540
+
541
+ ['b', 'B', 'a', 'ä'].sort(byString) // ['B', 'a', 'b', 'ä']
542
+ pagesData.sort(byHref) // by meta.href
543
+ ```
544
+
545
+ ### `/urls` — origin, absolute URLs, `base_path`, containment, `srcset`
546
+
547
+ Absolute URLs are percent-encoded, so a canonical link, a sitemap `<loc>` and a feed `<link>` of the same page are the same string. The `base_path` helpers give exactly core's output.
548
+
549
+ #### `resolveOrigin({ cwd = process.cwd(), app } = {}): string`
550
+
551
+ `app.origin`, else `app_origin` from the site's `config/canonical-links.yaml` (`app.folders.config` honoured), without surrounding whitespace and trailing slashes; `''` when neither is set. The file is only read when `app.origin` is blank or missing.
552
+
553
+ #### `encodePath(value: unknown): string`
554
+
555
+ `value` with everything a URL may not contain percent-encoded (space, non-ASCII, a `%` that starts no valid escape), while valid `%XX` escapes and URL delimiters stay, so an encoded path is not encoded twice. A lone surrogate becomes `%EF%BF%BD`; `null`/`undefined` give `''`.
556
+
557
+ #### `joinUrl(origin: string, basePath: string, href: string): string`
558
+
559
+ The absolute URL of a page: `origin` + `basePath` + `href` (`meta.href`), the path encoded by `encodePath`, otherwise verbatim (`/index.html` stays).
560
+
561
+ #### `siteUrl(origin: string, basePath?: string): string`
562
+
563
+ The site's own URL, `origin` + `basePath` without trailing slashes, encoded like `joinUrl`. A non-string `basePath` gives `origin`.
564
+
565
+ #### `normalizeBasePath(raw: unknown): string`
566
+
567
+ `base_path` from `config/app.yaml` as core normalises it into `app.basePath`: a non-string, blank text or `/` gives `''`; otherwise trimmed, trailing slashes dropped, one leading slash guaranteed.
568
+
569
+ #### `withBasePath(url: unknown, basePath: string): unknown`
570
+
571
+ `url` under `basePath`, as core prefixes every root-absolute URL of a built page. Only a string starting with a single `/` is prefixed; `//cdn/…`, a URL with a scheme, a relative URL, a non-string and a value already under `basePath` come back unchanged, so applying it twice is harmless.
572
+
573
+ #### `stripBasePath(url: unknown, basePath: string): unknown`
574
+
575
+ The inverse: `basePath` itself gives `'/'`, `basePath/…` loses the prefix, anything else (`/subway` for `/sub`) comes back unchanged.
576
+
577
+ #### `hasScheme(url: unknown): boolean`
578
+
579
+ Whether `url` starts with a scheme (`https:`, `mailto:`, `data:`, any case). `//host/…` has none.
580
+
581
+ #### `isInside(root: string, target: string, { self = true } = {}): boolean`
582
+
583
+ Whether the path `target` is `root` or lies below it, compared after `path.resolve` (symlinks not followed). A child folder named `..foo` is inside; `/site/publication` is not inside `/site/public`. With `self: false`, `root` itself does not count.
584
+
585
+ #### `srcsetUrls(value: unknown): string[]`
586
+
587
+ The URLs of a `srcset`, by the HTML standard's candidate rule: a URL ends at whitespace, so a comma inside it (`?w=1,2`, a data URI) does not split it. A non-string gives `[]`.
588
+
589
+ #### `mapSrcset(value: unknown, fn: (url, index) => unknown): unknown`
590
+
591
+ `value` with each candidate URL replaced by `fn(url, index)`; descriptors, commas and whitespace are kept byte for byte. A non-string comes back unchanged.
592
+
593
+ ```js
594
+ import {
595
+ encodePath, hasScheme, isInside, joinUrl, mapSrcset, normalizeBasePath,
596
+ resolveOrigin, siteUrl, srcsetUrls, stripBasePath, withBasePath,
597
+ } from '@nera-static/plugin-utils/urls'
598
+
599
+ resolveOrigin({ app: { origin: ' https://ex.com/ ' } }) // 'https://ex.com'
600
+
601
+ encodePath('/über uns.html') // '/%C3%BCber%20uns.html'
602
+ encodePath('/%C3%BCber.html') // '/%C3%BCber.html'
603
+ joinUrl('https://ex.com', '/sub', '/über uns.html') // 'https://ex.com/sub/%C3%BCber%20uns.html'
604
+ siteUrl('https://ex.com', '/sub/') // 'https://ex.com/sub'
605
+
606
+ normalizeBasePath('nera-website/') // '/nera-website'
607
+ normalizeBasePath('/') // ''
608
+ withBasePath('/css/main.css', '/sub') // '/sub/css/main.css'
609
+ withBasePath('/sub/a.html', '/sub') // '/sub/a.html'
610
+ withBasePath('//cdn.example.com/x.js', '/sub') // '//cdn.example.com/x.js'
611
+ stripBasePath('/sub/a.html', '/sub') // '/a.html'
612
+ stripBasePath('/subway', '/sub') // '/subway'
613
+ hasScheme('mailto:x@y.z') // true
614
+
615
+ isInside('/site/public', '/site/public/a.html') // true
616
+ isInside('/site/public', '/site/public', { self: false }) // false
617
+ isInside('/site/public', '/site/publication') // false
618
+
619
+ srcsetUrls('/a.jpg?w=1,2 1x, /b.jpg 2x') // ['/a.jpg?w=1,2', '/b.jpg']
620
+ mapSrcset('/a.jpg 1x, /b.jpg 2x', (url) => withBasePath(url, '/sub'))
621
+ // '/sub/a.jpg 1x, /sub/b.jpg 2x'
622
+ ```
623
+
624
+ ### `/frontmatter` — how core reads a page's frontmatter
625
+
626
+ Both mirror `@nera-static/core`, so a page the validator or an editor accepts parses the same way in the build.
627
+
628
+ #### `FRONTMATTER_OPTIONS`
629
+
630
+ The frozen `yaml` parse options core uses: `{ schema: 'core', customTags: ['timestamp'], merge: true, uniqueKeys: false }` — unquoted dates become `Date` objects, `<<` merge keys work, a repeated key takes the last value. Pass them to `yaml.parse` from your own `yaml` dependency; this package does not depend on `yaml`.
631
+
632
+ #### `splitFrontmatter(raw: string): { yamlText: string, body: string } | null`
633
+
634
+ A page file split by core's rule: CRLF and a lone CR read as LF, the first line must be exactly `---`, the next line that is exactly `---` closes the block (`----` or `--- ` do not). Without a closing line the rest is YAML and the body is empty; an empty block gives `yamlText: ''`. **`null`** when the file has no frontmatter (first line not `---`, a leading BOM or indentation, or `raw` not a string).
635
+
636
+ ```js
637
+ import { parse } from 'yaml'
638
+ import { FRONTMATTER_OPTIONS, splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
639
+
640
+ splitFrontmatter('---\r\ntitle: Hi\r\n---\r\n# Body\r\n') // { yamlText: 'title: Hi', body: '# Body\n' }
641
+ splitFrontmatter('# no frontmatter') // null
642
+ splitFrontmatter('---\n---\nx') // { yamlText: '', body: 'x' }
643
+
644
+ const parts = splitFrontmatter(raw)
645
+ const meta = parts ? parse(parts.yamlText, FRONTMATTER_OPTIONS) ?? {} : {}
646
+ ```
647
+
648
+ ### `/glob` — exclude patterns and `.neraignore`
649
+
650
+ Two rule sets, kept apart on purpose: the `*` glob of the sitemap and feed `exclude` lists, and core's `.neraignore` rule, which knows no wildcards.
651
+
652
+ #### `matchesPattern(href: unknown, pattern: unknown): boolean`
653
+
654
+ `*` matches any run of characters (`/` included, none at all), everything else is literal, anchored at both ends. A non-string never matches.
655
+
656
+ #### `matchesAny(href: unknown, patterns: unknown[] = []): boolean`
657
+
658
+ Whether `href` matches any of `patterns`; a non-array matches nothing.
659
+
660
+ #### `IGNORE_FILE`
661
+
662
+ `'.neraignore'`, the file name `readIgnoreList` reads from the site root.
663
+
664
+ #### `readIgnoreList(cwd = process.cwd()): string[]`
665
+
666
+ The patterns in the site's `.neraignore`, one per line, trimmed, blank lines dropped; `[]` when the file does not exist. Read from the site root, as core reads it.
667
+
668
+ #### `isIgnoredAsset(ignoreList: string[], file: string, root: string): boolean`
669
+
670
+ Whether core's asset copy skips `file`: its path relative to `root` (the assets folder), with `/` separators, equals a pattern or starts with a pattern plus `/`. So `images` skips `images/a.png`, `images/` skips nothing, and `robots` does not skip `robots.txt`.
671
+
672
+ ```js
673
+ import { isIgnoredAsset, matchesAny, matchesPattern, readIgnoreList } from '@nera-static/plugin-utils/glob'
674
+
675
+ matchesPattern('/drafts/a.html', '/drafts/*') // true
676
+ matchesPattern('/drafts/a.html', '/drafts') // false
677
+ matchesAny('/404.html', ['/404.html', '/drafts/*']) // true
678
+
679
+ const ignored = readIgnoreList() // e.g. ['images', 'robots']
680
+ isIgnoredAsset(['images'], '/site/assets/images/a.png', '/site/assets') // true
681
+ isIgnoredAsset(['robots'], '/site/assets/robots.txt', '/site/assets') // false
682
+ ```
683
+
684
+ ### `/pages` — which pages a plugin acts on
685
+
686
+ #### `isRenderedPage(meta): boolean`
687
+
688
+ Whether core renders the page: a non-blank `layout` and `href`. Core skips a page without `layout` silently, so a sitemap, feed or search index listing it points at nothing.
689
+
690
+ #### `isNoindex(meta, app): boolean`
691
+
692
+ Whether the page asks search engines not to index it: `meta.robots`, or `app.robots` when the page sets none, contains `noindex` in any case.
693
+
694
+ ```js
695
+ import { isNoindex, isRenderedPage } from '@nera-static/plugin-utils/pages'
696
+
697
+ isRenderedPage({ layout: 'pages/default.pug', href: '/a.html' }) // true
698
+ isRenderedPage({ href: '/a.html' }) // false
699
+ isNoindex({ robots: 'NoIndex, follow' }, {}) // true
700
+ isNoindex({}, { robots: 'noindex' }) // true
701
+ isNoindex({ robots: 'index' }, { robots: 'noindex' }) // false
702
+ ```
703
+
365
704
  ---
366
705
 
367
706
  ## 🧱 Use Cases
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nera-static/plugin-utils",
3
- "version": "1.7.0",
4
- "description": "Shared utility functions for Nera plugins (config loading, template publishing)",
3
+ "version": "1.8.0",
4
+ "description": "Shared helpers for Nera plugins and tools: config loading, template publishing, and subpath exports for values, logging, languages, dates, URLs and base_path, escaping, frontmatter, globs, package names and pages",
5
5
  "main": "index.js",
6
6
  "type": "module",
7
7
  "repository": {
@@ -31,7 +31,8 @@
31
31
  "devDependencies": {
32
32
  "eslint": "^10.8.0",
33
33
  "husky": "^9.1.7",
34
- "vitest": "^5.0.0"
34
+ "vitest": "^5.0.0",
35
+ "yaml": "^2.4.1"
35
36
  },
36
37
  "scripts": {
37
38
  "test": "vitest",
@@ -45,7 +46,15 @@
45
46
  "./log": "./src/log.js",
46
47
  "./config": "./src/config.js",
47
48
  "./packages": "./src/packages.js",
48
- "./guard": "./src/guard.js"
49
+ "./guard": "./src/guard.js",
50
+ "./html": "./src/html.js",
51
+ "./lang": "./src/lang.js",
52
+ "./dates": "./src/dates.js",
53
+ "./sort": "./src/sort.js",
54
+ "./urls": "./src/urls.js",
55
+ "./frontmatter": "./src/frontmatter.js",
56
+ "./glob": "./src/glob.js",
57
+ "./pages": "./src/pages.js"
49
58
  },
50
59
  "files": [
51
60
  "index.js",
package/src/dates.js ADDED
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Frontmatter dates, shared by every Nera plugin and tool
3
+ * (`@nera-static/plugin-utils/dates`): parsing, the W3C format, the decided
4
+ * key lists and a date comparator.
5
+ *
6
+ * Nothing here reads the build machine's time zone: a time without an
7
+ * offset is read as UTC, as YAML reads an unquoted timestamp, so the same
8
+ * site gives the same dates and the same order on every machine.
9
+ */
10
+
11
+ // `YYYY-MM-DD`, optionally `T` or a space, `hh:mm`, optional `:ss` and
12
+ // fraction, and an optional `Z` or `±hh:mm` offset.
13
+ const DATE_STRING = new RegExp(
14
+ '^(\\d{4})-(\\d{2})-(\\d{2})' +
15
+ '(?:[T ](\\d{2}):(\\d{2})(?::(\\d{2})(?:\\.(\\d+))?)?\\s*(Z|[+-]\\d{2}:\\d{2})?)?$'
16
+ )
17
+
18
+ const MINUTE = 60 * 1000
19
+
20
+ /**
21
+ * Frontmatter keys tried for a page's published date, in order. `createdAt`
22
+ * is left out on purpose: core fills it from the file's birth time when the
23
+ * frontmatter has no date, and CI stamps every file the same.
24
+ */
25
+ export const PUBLISHED_KEYS = Object.freeze(['date', 'datePublished', 'published'])
26
+
27
+ /** Frontmatter keys tried for a page's updated date, in order. */
28
+ export const UPDATED_KEYS = Object.freeze(['updated', 'updatedAt', 'lastmod', 'dateModified'])
29
+
30
+ const KEYS = { published: PUBLISHED_KEYS, updated: UPDATED_KEYS }
31
+
32
+ const validDate = (date) => (Number.isNaN(date.getTime()) ? null : date)
33
+
34
+ // The offset `±hh:mm` in milliseconds, or null when it is out of range.
35
+ function offsetOf(zone) {
36
+ if (zone === undefined || zone === 'Z') return 0
37
+ const hours = Number(zone.slice(1, 3))
38
+ const minutes = Number(zone.slice(4, 6))
39
+ if (hours > 23 || minutes > 59) return null
40
+ return (zone[0] === '-' ? -1 : 1) * (hours * 60 + minutes) * MINUTE
41
+ }
42
+
43
+ /**
44
+ * A frontmatter value as a `Date`, or `null` when it is not a usable date.
45
+ *
46
+ * Accepts a valid `Date` (core parses an unquoted frontmatter date into one)
47
+ * or a string `YYYY-MM-DD`, optionally followed by `T` or a space and
48
+ * `hh:mm[:ss[.fraction]]` with an optional `Z` or `±hh:mm` offset
49
+ * (surrounding whitespace is ignored). A string without an offset is read as
50
+ * UTC. A day or time that does not exist (`2026-02-30`, `24:00`, `09:60`) is
51
+ * not usable; neither is any other type or form (`1.10.2026`, a number).
52
+ *
53
+ * @param {unknown} value
54
+ * @returns {Date | null}
55
+ */
56
+ export function toDate(value) {
57
+ if (value instanceof Date) return validDate(value)
58
+ if (typeof value !== 'string') return null
59
+ const match = DATE_STRING.exec(value.trim())
60
+ if (!match) return null
61
+ const [, year, month, day, hour = '0', minute = '0', second = '0', fraction = '', zone] = match
62
+ const parts = [year, month, day, hour, minute, second].map(Number)
63
+ const wall = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]))
64
+ // `Date.UTC` rolls an impossible day or time over (Feb 30 into March,
65
+ // 24:00 into the next day); a value that does not read back is refused.
66
+ const exists = wall.getUTCFullYear() === parts[0]
67
+ && wall.getUTCMonth() === parts[1] - 1
68
+ && wall.getUTCDate() === parts[2]
69
+ && wall.getUTCHours() === parts[3]
70
+ && wall.getUTCMinutes() === parts[4]
71
+ && wall.getUTCSeconds() === parts[5]
72
+ const offset = offsetOf(zone)
73
+ if (!exists || offset === null) return null
74
+ const milliseconds = Number(fraction.padEnd(3, '0').slice(0, 3))
75
+ return validDate(new Date(wall.getTime() + milliseconds - offset))
76
+ }
77
+
78
+ /**
79
+ * A date in W3C Datetime form, in UTC: `YYYY-MM-DD` for UTC midnight (an
80
+ * unquoted `2026-10-01`), else `YYYY-MM-DDThh:mm:ssZ` without milliseconds.
81
+ * Accepts whatever `toDate` accepts; `null` when that is not a usable date.
82
+ *
83
+ * @param {unknown} value
84
+ * @returns {string | null}
85
+ */
86
+ export function formatW3C(value) {
87
+ const date = toDate(value)
88
+ if (!date) return null
89
+ const iso = date.toISOString()
90
+ if (iso.endsWith('T00:00:00.000Z')) return iso.slice(0, 10)
91
+ return iso.replace(/\.\d{3}Z$/, 'Z')
92
+ }
93
+
94
+ // A rejected value as a warning shows it.
95
+ function show(value) {
96
+ if (value instanceof Date) return 'an invalid date'
97
+ return JSON.stringify(value) ?? String(value)
98
+ }
99
+
100
+ const isAbsent = (value) => value === undefined || value === null
101
+ || (typeof value === 'string' && value.trim() === '')
102
+
103
+ /**
104
+ * A page's published or updated date: the first key of `PUBLISHED_KEYS`
105
+ * resp. `UPDATED_KEYS` whose value is a usable date (see `toDate`), or
106
+ * `null` when none is. A present value that is not a date is skipped with
107
+ * one warning (`<href>: ignoring <key> <value>, …`) and the next key is
108
+ * tried; an absent, `null` or blank value is skipped silently. Keys after
109
+ * the first usable one are not read.
110
+ *
111
+ * @param {object | undefined | null} meta the page's `meta`
112
+ * @param {'published' | 'updated'} kind
113
+ * @param {{ warn?: (message: string) => void }} [options]
114
+ * @returns {Date | null}
115
+ * @throws {TypeError} when `kind` is neither `'published'` nor `'updated'`
116
+ */
117
+ export function pageDate(meta, kind, { warn = console.warn } = {}) {
118
+ if (!Object.hasOwn(KEYS, kind)) {
119
+ throw new TypeError(`pageDate: kind must be 'published' or 'updated', got ${show(kind)}`)
120
+ }
121
+ for (const key of KEYS[kind]) {
122
+ const value = meta?.[key]
123
+ if (isAbsent(value)) continue
124
+ const date = toDate(value)
125
+ if (date) return date
126
+ const where = typeof meta.href === 'string' && meta.href !== '' ? meta.href : 'a page without href'
127
+ warn(`${where}: ignoring ${key} ${show(value)}, expected a date like 2026-10-01 or 2026-10-01T09:30:00Z`)
128
+ }
129
+ return null
130
+ }
131
+
132
+ /**
133
+ * A comparator by date, for `Array.prototype.sort`: `get(item)` returns the
134
+ * item's date in any form `toDate` accepts. Oldest first, or newest first
135
+ * with `descending`; items without a usable date go last in both
136
+ * directions. Equal dates compare as `0`, so chain a tie-break
137
+ * (`byDate(get)(a, b) || byHref(a, b)`) for an order that does not depend
138
+ * on the input.
139
+ *
140
+ * @param {(item: any) => unknown} get
141
+ * @param {{ descending?: boolean }} [options]
142
+ * @returns {(a: any, b: any) => number}
143
+ */
144
+ export function byDate(get, { descending = false } = {}) {
145
+ if (typeof get !== 'function') {
146
+ throw new TypeError('byDate: get must be a function that returns an item\'s date')
147
+ }
148
+ const direction = descending ? -1 : 1
149
+ return (a, b) => {
150
+ const left = toDate(get(a))
151
+ const right = toDate(get(b))
152
+ if (!left || !right) return (left ? 0 : 1) - (right ? 0 : 1)
153
+ return direction * (left.getTime() - right.getTime())
154
+ }
155
+ }