@kirigami/php-prepros 1.9.3 → 3.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/README.md CHANGED
@@ -1,1817 +1,1988 @@
1
- <div align="center">
2
-
3
- <img src="https://zmotrin.github.io/assets/kirigami/kirigami-logo-universal.svg" alt="Kirigami" width="400" />
4
-
5
- ---
6
-
7
- # @kirigami/php-prepros
8
-
9
-
10
- PHP preprocessor for the **Kirigami** static site generator.
11
-
12
- [![npm version](https://img.shields.io/npm/v/@kirigami/php-prepros)](https://www.npmjs.com/package/@kirigami/php-prepros)
13
- [![License: MIT](https://img.shields.io/badge/license-MIT-blue)](./LICENSE)
14
- [![Node.js >=24.0.0](https://img.shields.io/badge/node-%3E%3D24.0.0-brightgreen)](https://nodejs.org)
15
- [![Website](https://img.shields.io/badge/website-php--kirigami.github.io-1f6b4a)](https://php-kirigami.github.io)
16
-
17
- </div>
18
-
19
- ---
20
-
21
- ## Overview
22
-
23
- Build full static websites in PHP — with zero server, zero runtime dependency, zero compromise on expressiveness. Write your pages as regular PHP files, annotate them with a PHPDOC header, and let `php-prepros` compile everything to clean, deployable HTML.
24
-
25
- It is the perfect solution for **GitHub Pages**. Since it runs entirely in Node.js, it is fully compatible with **GitHub Actions**, allowing you to automate your deployment pipeline effortlessly.
26
-
27
- Part of the **Kirigami** project ecosystem.
28
-
29
-
30
- ---
31
-
32
-
33
- ## Table of contents
34
-
35
- - [@kirigami/php-prepros](#kirigamiphp-prepros)
36
- - [Overview](#overview)
37
- - [Table of contents](#table-of-contents)
38
- - [What's new in 1.7.2](#whats-new-in-172)
39
- - [What's new in 1.7.1](#whats-new-in-171)
40
- - [What's new in 1.7.0](#whats-new-in-170)
41
- - [What's new in 1.6.0](#whats-new-in-160)
42
- - [What's new in 1.4.0](#whats-new-in-140)
43
- - [What's new in 1.3.0](#whats-new-in-130)
44
- - [What's new in 1.2.1](#whats-new-in-121)
45
- - [What's new in 1.2.0](#whats-new-in-120)
46
- - [How it works](#how-it-works)
47
- - [Installation](#installation)
48
- - [Configuration — `kirigami.yaml`](#configuration--kirigamiyaml)
49
- - [`kirigami` block](#kirigami-block)
50
- - [`jsonld` block](#jsonld-block)
51
- - [`meta` block](#meta-block)
52
- - [`prepros` block](#prepros-block)
53
- - [`image` block](#image-block)
54
- - [`plugins` block](#plugins-block)
55
- - [`esbuild` / `sass` blocks](#esbuild--sass-blocks)
56
- - [`export` block](#export-block)
57
- - [`scripts` block](#scripts-block)
58
- - [`tasks` block](#tasks-block)
59
- - [Writing pages](#writing-pages)
60
- - [PHPDOC header](#phpdoc-header)
61
- - [Auto-loading data files](#auto-loading-data-files)
62
- - [`@content` and `@indent`](#content-and-indent)
63
- - [Built-in tags](#built-in-tags)
64
- - [JavaScript API](#javascript-api)
65
- - [`render(file?)`](#renderfile)
66
- - [`sitemap()`](#sitemap)
67
- - [`runenv(script, paths?, ...args)`](#runenvscript-paths-args)
68
- - [`mountPath(localPath, virtualDir?, php?)`](#mountpathlocalpath-virtualdir-php)
69
- - [`processImages(jobs)`](#processimagesjobs)
70
- - [PHP classes reference](#php-classes-reference)
71
- - [PREPROS](#prepros)
72
- - [`PREPROS::render(string $file)`](#preprosrenderstring-file)
73
- - [`PREPROS::sitemap()`](#preprossitemap)
74
- - [`PREPROS::mount(string|array $patterns)`](#preprosmountstringarray-patterns)
75
- - [`PREPROS::exportFile(string $file)`](#preprosexportfilestring-file)
76
- - [MD](#md)
77
- - [Plugin API](#plugin-api)
78
- - [HTML](#html)
79
- - [YAML](#yaml)
80
- - [SCHEMA](#schema)
81
- - [LD](#ld)
82
- - [Automatic mode](#automatic-mode)
83
- - [Explicit builders](#explicit-builders)
84
- - [`jsonld` config](#jsonld-config)
85
- - [META](#meta)
86
- - [`meta` config](#meta-config)
87
- - [CACHE](#cache)
88
- - [IMG](#img)
89
- - [FS](#fs)
90
- - [STR](#str)
91
- - [ARR](#arr)
92
- - [CURL](#curl)
93
- - [SCRAPER](#scraper)
94
- - [OBF](#obf)
95
- - [STD](#std)
96
- - [Bundled polyfills](#bundled-polyfills)
97
- - [Procedural shortcuts (aliases)](#procedural-shortcuts-aliases)
98
- - [Plugin system](#plugin-system)
99
- - [PREPROS tags](#prepros-tags)
100
- - [PREPROS hooks](#prepros-hooks)
101
- - [MD plugins](#md-plugins)
102
- - [Built-in plugins](#built-in-plugins)
103
- - [`{% callout type ["Title"] content %}`](#-callout-type-title-content-)
104
- - [`{% youtube id [width height] %}`](#-youtube-id-width-height-)
105
- - [`{% codepen id [user height] %}`](#-codepen-id-user-height-)
106
- - [`{% checklist ["Title"] items %}`](#-checklist-title-items-)
107
- - [Extending the `<markdown>` tag](#extending-the-markdown-tag)
108
- - [Requirements](#requirements)
109
- - [License](#license)
110
-
111
- ---
112
-
113
- ## What's new in 1.9.1
114
-
115
- - **`{% img-asset %}` no longer crashes the build on an unresolvable path.**
116
- `IMG::asset()`'s exception is now caught and turned into an HTML comment,
117
- matching `codepen`/`checklist`'s own missing-argument behavior instead of
118
- aborting the whole render. This also makes it safe to *document* the tag —
119
- a literal `` `{% img-asset path … %}` `` written as prose inside a code
120
- span still runs the plugin (code-span protection only swaps the *displayed*
121
- output back to the literal text; the callback itself always executes), so
122
- a placeholder path used to throw "Invalid image file." and fail the build.
123
-
124
- ---
125
-
126
- ## What's new in 1.9.0
127
-
128
- - **`{% youtube %}` removed** — moved to
129
- [`@kirigami/plugin-embed`](https://www.npmjs.com/package/@kirigami/plugin-embed),
130
- which replaces the old plain-iframe output with a real oEmbed-backed card
131
- (cover thumbnail, title, play button — no network call until the visitor
132
- actually clicks play). If a project used the built-in `{% youtube %}`,
133
- install the plugin; without it, the tag now falls through unresolved
134
- (`{% youtube ID %}` printed as-is) rather than rendering an iframe.
135
- `codepen`/`checklist`/`callout` are unaffected.
136
-
137
- ---
138
-
139
- ## What's new in 1.8.0
140
-
141
- - **`{% img-asset %}` — a new built-in Markdown plugin.** Same pipeline as the
142
- `<img asset>` HTML tag (`IMG::asset()`: resize, cache, publish under
143
- `image.dest`), usable straight from Markdown text:
144
-
145
- ```
146
- {% img-asset photo.jpg %}
147
- {% img-asset photo.jpg 800 %}
148
- {% img-asset photo.jpg 800 600 %}
149
- {% img-asset photo.jpg 800 600 cover %}
150
- ```
151
-
152
- Positional args: source path (relative to `image.source`), width, height,
153
- and the literal `cover` keyword. Registered in `md.plugins.php` alongside
154
- `codepen`/`youtube`/`checklist`/`callout` — available out of the box, drop
155
- it with `MD::unregisterPlugin('img-asset')` if you don't want it.
156
-
157
- ---
158
-
159
- ## What's new in 1.7.2
160
-
161
- - **Cleaner formatted output around highlighted code.** The de-indent script
162
- `PREPROS::injectHead()` adds when `prepros.format` is on now flattens the
163
- `<pre><code>` indentation `HTML::format()` writes for *every* block, including
164
- ones a build-time highlighter has wrapped in `<span>`s. It works on
165
- `innerHTML` line by line and removes only the shared leading run (relative
166
- indentation is kept). This lets [`@kirigami/plugin-highlight`](https://www.npmjs.com/package/@kirigami/plugin-highlight)
167
- 1.7.2+ re-indent its markup to line up with the rest of the document instead
168
- of leaving it flush-left — the served HTML stays consistently indented, the
169
- rendered code is still de-indented before the first paint.
170
-
171
- - **`<markdown prose>` wraps in `.prose`.** With the `prose` attribute the
172
- built-in tag emits `<div class="prose"> … </div>` so long-form Markdown picks
173
- up `@kirigami/canva`'s `styles/prose` typography with no extra markup. Opt-in
174
- (a bare `<markdown>` is unchanged); `class` / `id` on the tag land on the
175
- wrapper.
176
-
177
- ---
178
-
179
- ## What's new in 1.7.1
180
-
181
- - **No side effects on import.** `kirigami.yaml` is now loaded on first use
182
- (`render()` / `sitemap()` / `runenv()` / `processImages()`), not while the
183
- module is being imported. `import '@kirigami/php-prepros'` from a directory
184
- with no project no longer throws — which is what made `kiri build --help` /
185
- `kiri export --help` / `kiri run --help` crash instead of printing their help.
186
-
187
- ---
188
-
189
- ## What's new in 1.7.0
190
-
191
- - **`META`** class — a `<head>` SEO / social metadata generator, the companion
192
- to [`LD`](#ld). Builds the standard tags — `<title>`, `description`,
193
- `keywords`, `robots`, `language`, `generator`, `author`, Open Graph, Twitter
194
- Card, `<link rel="canonical">`, favicon / apple-touch-icon / humans — from
195
- each page's PHPDOC, the top-level `meta:` block, and the loose `kirigami:` /
196
- `jsonld:` keys `LD` already reads. It emits only what it can resolve, and
197
- leaves any tag the layout already hand-writes untouched.
198
-
199
- - **Opt-in**: a top-level `meta:` block (empty `meta: {}` is enough) switches
200
- on automatic injection into every page's `<head>`. `meta: false` (or
201
- `{ auto: false }`) keeps the config but stops the injection.
202
- - Per-page PHPDOC: `@meta false` (skip), `@meta_title`, `@meta_description`
203
- (falls back to `@description` / `@abstract` / `@excerpt`), `@meta_keywords`,
204
- `@meta_image`, `@meta_robots`, `@meta_type`, `@canonical`.
205
- - Manual builders — always emitted, still de-duplicated: `META::tag()`,
206
- `META::link()`, `META::raw()`, `META::tags()`. Procedural aliases:
207
- `meta_tag()`, `meta_link()`, `meta_raw()`, `meta_tags()`.
208
-
209
- Full key reference: [`META` → `meta` config](#meta-config).
210
-
211
- ---
212
-
213
- ## What's new in 1.6.0
214
-
215
- - **Managed `<head>` (`prepros.head`).** Every rendered page's `<head>` is now
216
- auto-wired: a tiny theme/FOUC guard as the first child (adds the `js` class,
217
- applies the stored `data-theme` before first paint), a
218
- `<link rel="stylesheet">` for every `sass` task output, and a `<script>` (no
219
- `defer`, just before `</body>`) for every `esbuild` task output — each with a
220
- per-page relative path and a `?<timestamp>` cache-bust. A file already
221
- referenced in the page is left alone, so you can still hand-place one. Turn it
222
- off with `prepros: { head: false }`, or `head: false` on a single sass/esbuild
223
- task. A template's `header.php` no longer wires assets at all.
224
-
225
- - **`HTML::format()` indents `<pre><code>`.** A fenced code block's lines are
226
- shifted to the block's nesting depth so the HTML source stays readable
227
- (relative indentation preserved). The exact leading run is stripped again
228
- before it's shown, by a small de-indent script `prepros.head` injects before
229
- `</body>` (only when `format` is on). Since 1.7.2 the script works on
230
- `innerHTML` line by line, so it also flattens blocks a build-time highlighter
231
- has wrapped in `<span>`s. A bare `<pre>` and `<textarea>` are still emitted
232
- byte-for-byte.
233
-
234
- ---
235
-
236
- ## What's new in 1.4.0
237
-
238
- A round of fixes to the rough edges that showed up building a full site from
239
- scratch — mostly developer-experience, all backward compatible.
240
-
241
- - **`HTML::format()` keeps `<pre>` / `<textarea>` verbatim.** Their line breaks,
242
- indentation and blank lines are no longer collapsed, so a fenced code block
243
- survives the formatter intact — `format: true` and Markdown code blocks now
244
- coexist. (1.6.0 refines this: a `<pre><code>` block is re-indented to its
245
- nesting depth and de-indented again before display.)
246
- - **The default Markdown plugins load out of the box.** `{% callout %}`,
247
- `{% youtube %}`, `{% codepen %}` and `{% checklist %}` are registered
248
- automatically (`md.plugins.php` is auto-included from `MD`), as the docs always
249
- said. Drop one with `MD::unregisterPlugin('name')` or shadow it with your own
250
- `MD::registerPlugin()`.
251
- - **Build errors you can actually read.** A fatal in a template (a bad call, a
252
- `null` argument, a `TypeError`…) comes back as a structured failure with the
253
- message, the offending page and the `file:line` — never a bare
254
- `Error: undefined`. The `try/catch` now covers `Throwable`, not just
255
- `Exception`. PHP warnings and notices no longer sink an otherwise-clean build:
256
- they surface as `warnings` on the result. `kiri` prints the message, the page,
257
- and the tail of the PHP stderr/debug output on failure.
258
- - **PHPDOC parsing.** A tag value may now wrap onto the following *indented*
259
- continuation lines instead of being silently truncated at the first line. And
260
- an `@word` written in the block's prose is ignored rather than overwriting a
261
- real tag — only lines that *start* with `@` open a tag.
262
- - **`FS::getBreadcrumb()` / `FS::getChildren()`** are anchored on the page being
263
- rendered (`PREPROS::$file`), so they return the right trail / child list when
264
- called from a layout include, a partial, or a helper function — not only
265
- straight from the template. Pass an explicit path to override.
266
- - **`{% tag %}` inside a code span or code block stays literal** (`` `{% badge %}` ``
267
- renders as text) instead of being expanded — or leaking an unrestored
268
- placeholder.
269
- - **`IMG` never upscales.** A requested size larger than the source is clamped
270
- down to the source instead of throwing an opaque encoder error (the AVIF
271
- encoder in particular).
272
- - **Build-time tokens expand at render time.** `###YEAR###`, `###TIMESTAMP###`
273
- and `###TODAY###` are substituted when each page is generated, so
274
- `kiri build` / `kiri watch` previews show real values, not the literal token
275
- (previously only `kiri export` replaced them).
276
- - **`page_info` hook robustness.** The first built-in callback accepts either the
277
- `[$file, $info]` pair the hook fires with or the bare `$info` object a later
278
- callback receives, so a custom `page_info` hook can't fatal on the argument
279
- shape. See [PREPROS hooks](#prepros-hooks).
280
-
281
- ---
282
-
283
- ## What's new in 1.3.0
284
-
285
- - **`LD`** class — a schema.org JSON-LD generator. Collects structured-data
286
- nodes during a render and emits them as a single
287
- `<script type="application/ld+json">` `@graph` in every page's `<head>`.
288
- - Automatic injection is **opt-in**: add a top-level `jsonld:` block to
289
- `kirigami.yaml` (even empty, `jsonld: {}`) and an `Organization` (+ `Person`, `WebSite`,
290
- `WebPage`, `BreadcrumbList`) graph is derived from that block plus the loose
291
- keys projects already carry (`person`, `jobtitle`, `email`, `area`,
292
- `knowsabout`, `keywords`, `facebook`, …). No `jsonld:` block → nothing is
293
- injected.
294
- - Turn it back off with `jsonld: false` / `jsonld: { auto: false }`, or per
295
- page with `@ld false`; per-page `@ld_type` / `@ld_title` / `@ld_image` / …
296
- tags feed the page node, and a `BreadcrumbList` is built from the
297
- `_index.php` ancestor trail with no opt-in.
298
- - Explicit builders for everything else: `LD::add()`, `LD::article()`,
299
- `LD::faqPage()`, `LD::breadcrumb()`, `LD::ref()`, and every schema.org type
300
- via `LD::typeName([...])`. Procedural aliases: `ld_add()`, `ld_organization()`,
301
- `ld_script()`, …
302
- - A page that already hand-writes an `application/ld+json` script is left
303
- untouched.
304
-
305
- ---
306
-
307
- ## What's new in 1.2.1
308
-
309
- - **`processImages()`** JS export — batch resize / palette-extraction through the
310
- `IMG` class (`src/imagebatch.php`). `@kirigami/kirigami`'s `sass` task now uses
311
- it for `img-asset()` / `colors()`, so the whole toolchain is free of a native
312
- image dependency (`sharp` is gone).
313
- - **`IMG::save()`** takes an optional `$quality` (0-100) for jpg / webp / avif;
314
- `null` keeps the per-format default (82).
315
-
316
- ---
317
-
318
- ## What's new in 1.2.0
319
-
320
- - **`SCHEMA`** class — a pure-PHP, dependency-free JSON Schema validator
321
- (Draft-7 style, Ajv-like API: `isValid()` / `validate()` / `getErrors()`).
322
- - **`IMG::asset()` / `IMG::palette()`** — static helpers powering kirigami-core's
323
- `img-asset()` and `colors()` Sass functions: on-demand resize/convert of a
324
- source image, and cached representative-colour extraction.
325
- - **`<img asset="…">` tag** — the HTML-side entry point of the image
326
- autogenerator, same parameters as `IMG::asset()` (see [Built-in tags](#built-in-tags)).
327
- - **`IMG` now handles vector and exotic formats** — SVG, EPS, AI, PDF (rasterized
328
- via Imagick), plus HEIC / TIFF / BMP, on top of GD's JPEG / PNG / GIF / WebP /
329
- AVIF.
330
- - **`MD` emoji shortcodes** — `:rocket:` → 🚀 from a large built-in map, extend­able
331
- with `MD::registerEmoji()`.
332
- - **`MD` footnotes and definition lists** — `[^1]` / `[^1]: …`, and `Term` / `: …`.
333
- - **`MD` inline HTML is now sanitized** against a tag/attribute allowlist rather
334
- than passed through verbatim.
335
- - **`STR::normalize()`** — Unicode NFD + combining-mark stripping;
336
- **`STR::slug($str, $sep = '')`** now takes a separator (pass `'-'` for a
337
- hyphenated slug).
338
- - **Bundled `Normalizer` polyfill** — `ext-intl` isn't in the WASM build, so a
339
- polyfill keeps `Normalizer::normalize()` (and `STR::normalize()` / `slug()`)
340
- working.
341
-
342
- Earlier, in 1.1.x: `PREPROS::mount()` + the `mountPath()` / `runenv()` JS
343
- exports, the `SCRAPER` and `CURL` and `ARR` classes, `YAML::loadFile()`, the
344
- `STR::is_url()` / `html_entities_decode()` / `shorthash()` / `slug()` helpers,
345
- the `{% youtube %}` / `{% codepen %}` / `{% checklist %}` MD plugins, and the
346
- `@content` / `@indent` PHPDOC annotations.
347
-
348
- ---
349
-
350
- ## How it works
351
-
352
- `@kirigami/php-prepros` runs your PHP source files inside a **WebAssembly PHP 8.x runtime** ([`@kirigami/php-wasm`](https://www.npmjs.com/package/@kirigami/php-wasm)), entirely in Node.js — no PHP installation required on the host machine.
353
-
354
- The lifecycle of a page build looks like this:
355
-
356
- ```
357
- _index.php ──▶ PHP (wasm) ──▶ processTags() ──▶ HTML::format() ──▶ index.html
358
- │
359
- ├── before.php (optional layout header)
360
- ├── after.php (optional layout footer)
361
- └── PHPDOC annotations resolved (yaml / json / md / url)
362
- ```
363
-
364
- Files are mounted into the WebAssembly virtual filesystem on demand. Only `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt` and any extra extensions listed in `prepros.mountext` are mounted automatically, keeping memory usage low. Anything else can be mounted on demand with [`PREPROS::mount()`](#preprosmountstringarray-patterns).
365
-
366
- ---
367
-
368
- ## Installation
369
-
370
- ```bash
371
- npm install @kirigami/php-prepros
372
- ```
373
-
374
- ---
375
-
376
- ## Configuration — `kirigami.yaml`
377
-
378
- Every project **must** have a `kirigami.yaml` at its root. The preprocessor reads it at startup and throws if it is absent or invalid.
379
-
380
- `@kirigami/php-prepros` itself only acts on four blocks — **`kirigami:`**, **`jsonld:`**, **`prepros:`**, and **`image:`**. The remaining blocks (**`plugins:`**, **`esbuild:`**, **`sass:`**, **`export:`**, **`scripts:`**, **`tasks:`**) are consumed by the [`kiri`](https://www.npmjs.com/package/@kirigami/kirigami) CLI that drives the build; they are documented here for completeness because everything lives in the one file. The full file is validated against [`kirigami.schema.json`](https://github.com/php-kirigami/kirigami/blob/main/packages/kirigami/kirigami.schema.json), also served for editor autocompletion:
381
-
382
- ```yaml
383
- # yaml-language-server: $schema=https://cdn.jsdelivr.net/gh/php-kirigami/kirigami@main/packages/kirigami/kirigami.schema.json
384
- ```
385
-
386
- ```yaml
387
- kirigami:
388
- # ── Required ──────────────────────────────────────────────────────────
389
- project: My Website # Site name. Printed in the CLI banner, exposed as $project.
390
- baseurl: https://example.com # Deployed root URL, no trailing slash. Used for sitemap.xml.
391
- root: src # Source directory containing your _*.php pages.
392
-
393
- # ── Optional ────────────────────────────────────────────────────────
394
- banner: assets/banner.txt # Text file stamped as a license banner on exported files.
395
-
396
- # ── Arbitrary project data ──────────────────────────────────────────
397
- # Everything else under `kirigami:` is free-form. The whole block is
398
- # extracted as PHP variables and made available in every page, in
399
- # before.php/after.php, and anywhere PREPROS::$config->data is read.
400
- author: Jane Doe
401
- email: hello@example.com
402
- gtag: G-XXXXXXXXXX
403
- description: A short description of the site, useful for <meta name="description">.
404
- keywords:
405
- - keyword one
406
- - keyword two
407
-
408
- jsonld: # Presence turns on the LD schema.org JSON-LD generator.
409
- type: Organization # `jsonld: {}` alone is enough; see the jsonld block below.
410
- logo: assets/logo.png
411
-
412
- prepros:
413
- before: _layouts/header.php # Included before every page body.
414
- after: _layouts/footer.php # Included after every page body.
415
- format: true # Pretty-print the HTML output (default: false).
416
- network: true # Allow HTTP fetches in PHPDOC @tag annotations / CURL / SCRAPER.
417
- mountext: # Extra file extensions to auto-mount into the wasm fs,
418
- - .svg # in addition to the defaults (.php .json .yaml .yml .md .db .txt).
419
- - .webp
420
- includes: # PHP files auto-included once, before any page renders.
421
- - _lib/functions.php
422
-
423
- image: # Image autogenerator — powers IMG::asset() / IMG::palette().
424
- format: webp # webp | avif (default: webp)
425
- source: assets/images # Source folder, relative to cwd() (default: assets/images)
426
- dest: images # Output folder, relative to kirigami.root (default: images)
427
-
428
- plugins:
429
- - name: "@kirigami/plugin-highlight"
430
- active: true
431
- options:
432
- style: canva
433
- color: black
434
-
435
- esbuild:
436
- # minify: false
437
-
438
- sass:
439
- style: expanded
440
-
441
- export:
442
- path: dist
443
- ignore: ["*.psd", "notes/"]
444
-
445
- scripts:
446
- - name: convert-images
447
- mount: ["assets/images/**/*.jpg"]
448
- trigger: before-build # before-build | before-export | after-export
449
-
450
- tasks:
451
- - name: js-core
452
- type: esbuild
453
- entry: scripts/kirigami.core.js
454
-
455
- - name: scss-core
456
- type: sass
457
- entry: styles/kirigami.core.scss
458
- ```
459
-
460
- ### `kirigami` block
461
-
462
- Core project settings. **Read by `php-prepros`.** The entire block is extracted into PHP variables and made available in every page template, `before.php`, `after.php`, and `prepros.includes` files — `$project`, `$author`, `$gtag`, etc. are available with no further setup, and also as `PREPROS::$config->data`.
463
-
464
- | Key | Required | Description |
465
- |-----|----------|--------------|
466
- | `project` | ✅ | Human-readable site name. Exposed as `$project`. |
467
- | `baseurl` | ✅ | Root URL of the deployed site, no trailing slash. Used to build absolute `<loc>` entries in `sitemap.xml`; exposed as `$baseurl`. |
468
- | `root` | ✅ | Path (relative to the project root) to the directory containing your `_*.php` source pages. Build fails immediately if missing or if the path doesn't exist. |
469
- | `banner` | — | Path (relative to the project root) to a text file stamped as a license/copyright banner on exported `.js`/`.css`/`.html` files during `kiri export`. May contain the `###DATE###` token, replaced with today's date. Falls back to an auto-generated banner. |
470
- | *anything else* | — | Free-form key/value pairs (strings, numbers, booleans, lists, nested maps — anything valid YAML). Every key is extracted as a PHP variable (`$author`, `$gtag`, …). Use this for contact info, social links, analytics IDs, SEO keywords, or any project data you want available everywhere. When the top-level `jsonld` block is present, [`LD`](#ld) also reads some of these by convention: `person`, `jobtitle`, `email`, `area`, `knowsabout`, `keywords`, and social-network URL keys (`facebook`, `instagram`, …). |
471
-
472
- ### `jsonld` block
473
-
474
- Top-level, optional. Its **presence** switches on the [`LD`](#ld) schema.org
475
- JSON-LD generator — an `application/ld+json` graph is then injected into every
476
- page's `<head>`. An empty `jsonld: {}` is enough; its keys refine what `LD`
477
- otherwise infers from the `kirigami` block and each page's PHPDOC. `jsonld: false`
478
- (or `jsonld: { auto: false }`) keeps the config values but stops the injection;
479
- no block at all means nothing is injected. Full key reference and per-page
480
- `@ld_*` tags: [`LD` → `jsonld` config](#jsonld-config).
481
-
482
- ### `meta` block
483
-
484
- Top-level, optional. Its **presence** switches on the [`META`](#meta) generator —
485
- the standard SEO / social `<meta>` and `<link>` tags are then built for every
486
- page and injected into its `<head>`. An empty `meta: {}` is enough; everything is
487
- derived from the `kirigami` block, the `jsonld` block, and each page's PHPDOC
488
- (`@title`, `@description` / `@abstract`, `@keywords`, `@image`, `@robots`,
489
- `@og_type`, `@canonical`). Keys refine those inferences. A tag the layout already
490
- hand-writes is left untouched. `meta: false` (or `meta: { auto: false }`) keeps
491
- the config values but stops the injection; no block at all means nothing is
492
- injected (explicit `META::tag()` / `meta_tag()` calls still emit). Full key
493
- reference and per-page `@meta_*` tags: [`META` → `meta` config](#meta-config).
494
-
495
- ### `prepros` block
496
-
497
- Options for the PHP → HTML compiler. **Read by `php-prepros`.** Declaring this block (even empty) also makes `kiri` prepend a forced `prepros` task on every build/export/watch.
498
-
499
- | Key | Type | Default | Description |
500
- |-----|------|---------|--------------|
501
- | `before` | `string` | — | Path (relative to `kirigami.root`) to a PHP file included **before** every page's body. Typically your `<head>`/layout opening. |
502
- | `after` | `string` | — | Path (relative to `kirigami.root`) to a PHP file included **after** every page's body. Typically your layout closing. |
503
- | `format` | `bool` | `false` | Pretty-print the compiled HTML via [`HTML::format()`](#html) before writing it to disk. |
504
- | `head` | `bool` | `true` | Auto-wire each page's `<head>`: a theme/FOUC guard as the first child, a `<link rel="stylesheet">` per `sass` task output, and a `<script>` (no `defer`, before `</body>`) per `esbuild` task output — each with a per-page relative path and a `?<timestamp>` cache-bust. A file already referenced in the page is skipped. Set `false` to disable, or `head: false` on a single `sass`/`esbuild` task to skip just its tag. |
505
- | `network` | `bool` | `false` | Enables outbound HTTP(S) inside the WASM PHP runtime. Required for PHPDOC `@tag https://…` annotations that fetch remote `.yaml`/`.json`/`.md` data (see [Auto-loading data files](#auto-loading-data-files)), and for the `CURL` / `SCRAPER` classes. |
506
- | `mountext` | `string[]` | `[]` | Extra file extensions to mount automatically into the virtual filesystem alongside the built-in `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`. Use this for assets your PHP code reads directly (e.g. `.svg`, `.webp`). Files with extensions not in this set are skipped during mounting — mount them on demand with [`PREPROS::mount()`](#preprosmountstringarray-patterns) instead. |
507
- | `includes` | `string[]` | `[]` | PHP files (relative to `kirigami.root`) `include_once`'d once, right after config is loaded — before any page renders. The natural place to `PREPROS::registerTag()`, `PREPROS::registerHook()`, or `MD::registerPlugin()`. |
508
-
509
- ### `image` block
510
-
511
- Options for the image autogenerator. **Read by `php-prepros`** — these are what [`IMG::asset()` / `IMG::palette()`](#img), the [`<img asset>` tag](#img-asset), and kirigami-core's `img-asset()` / `colors()` Sass functions all resolve against. Optional; the defaults below apply even when the block is absent.
512
-
513
- | Key | Type | Default | Description |
514
- |-----|------|---------|--------------|
515
- | `format` | `string` | `webp` | Output format for generated images: `webp` or `avif`. |
516
- | `source` | `string` | `assets/images` | Folder holding the source images, relative to `cwd()`. |
517
- | `dest` | `string` | `images` | Destination folder for generated images, relative to `kirigami.root`. |
518
-
519
- ### `plugins` block
520
-
521
- List of Kirigami plugins. **Consumed by the `kiri` CLI** (see [`@kirigami/sdk`](https://www.npmjs.com/package/@kirigami/sdk)), not by `php-prepros` directly.
522
-
523
- | Key | Required | Description |
524
- |-----|----------|--------------|
525
- | `name` | ✅ | Plugin package name. Must match `@kirigami/plugin-*`, `<scope>/kirigami-plugin-*`, or `kirigami-plugin-*`. |
526
- | `active` | ✅ | Whether the plugin is loaded. |
527
- | `options` | — | Free-form object passed to the plugin; its shape depends on the plugin. |
528
-
529
- ### `esbuild` / `sass` blocks
530
-
531
- Free-form objects. **Consumed by the `kiri` CLI.** There is no fixed key set: whatever you put here is spread straight into the underlying library call for every matching task, *after* Kirigami's own defaults — so it can also override them (`minify`, `target`, `style: "compressed"`, source maps, …). Refer to esbuild's [`BuildOptions`](https://esbuild.github.io/api/#build-api) and Dart Sass's [`Options`](https://sass-lang.com/documentation/js-api/interfaces/options/) for what's accepted. Writing the key with nothing under it parses to `null` in YAML, equivalent to omitting the block.
532
-
533
- `sass:` additionally recognizes two keys that are **not** passed to Dart Sass:
534
-
535
- | Key | Type | Description |
536
- |-----|------|--------------|
537
- | `before` | `string` / `string[]` | Extra `.scss` files compiled **before** the task entry (paths relative to `cwd()`). |
538
- | `after` | `string` / `string[]` | Extra `.scss` files compiled **after** the task entry. |
539
-
540
- ### `export` block
541
-
542
- Options for `kiri export`. **Consumed by the `kiri` CLI.** Optional.
543
-
544
- | Key | Type | Default | Description |
545
- |-----|------|---------|--------------|
546
- | `path` | `string` | `dist` | Output directory for `kiri export`, relative to the project root. |
547
- | `ignore` | `string[]` | `[]` | Extra gitignore-style patterns excluded from the export copy, on top of Kirigami's built-in exclusions. |
548
-
549
- ### `scripts` block
550
-
551
- Named PHP scripts. **Consumed by the `kiri` CLI**, which runs each `scripts/<name>.php` through [`runenv()`](#runenvscript-paths-args) — so the full `php-prepros` class library is available and `kirigami.yaml`'s `kirigami` block is exposed as `PREPROS::$config->data`.
552
-
553
- | Key | Required | Description |
554
- |-----|----------|--------------|
555
- | `name` | ✅ | Must match an existing `scripts/<name>.php` file. Run with `kiri run <name> [args...]`; extra CLI arguments are forwarded as `$argv` entries. |
556
- | `mount` | — | Glob patterns (relative to the project root) of extra local files to mount into the sandbox before the script runs. |
557
- | `trigger` | — | Fire the script automatically: `before-build` (start of `build` and `export`), `before-export` (very start of `export`), or `after-export` (once `export` has finished). |
558
-
559
- ### `tasks` block
560
-
561
- Ordered list of build tasks, run in array order. **Consumed by the `kiri` CLI**, on top of the implicit `prepros` task (added when the `prepros` block is present) and the implicit `dist` task (added during `kiri export`).
562
-
563
- | `type` | Purpose | Required fields | Optional |
564
- |--------|---------|-----------------|----------|
565
- | `esbuild` | Bundle/minify a JS/TS entry. Build + watch. Output: `<entry>.min.js`. | `name`, `type`, `entry` | `force` |
566
- | `sass` | Compile a `.scss`/`.sass` entry, minified with csso on export. Build + watch. Output: `<entry>.min.css`. | `name`, `type`, `entry` | `force` |
567
- | `prepros` | Render pages + `sitemap.xml`. Watch only (runs on build/export only when forced/implicit). | `name`, `type` | `target`, `force` |
568
- | `dist` | Copy `kirigami.root` into an output dir, stamping the banner. Forced/implicit only. | `name`, `type`, `path` | `ignore`, `force` |
569
-
570
- ---
571
-
572
- ## Writing pages
573
-
574
- Source pages live in the directory pointed to by `kirigami.root`. The naming convention is straightforward: any file whose name starts with `_` and ends in `.php` is treated as a page source. The leading underscore is stripped in the output filename.
575
-
576
- ```
577
- src/
578
- ├── _layouts/
579
- ├── _lib/
580
- ├── _index.php → src/index.html
581
- ├── about/
582
- │ └── _index.php → src/about/index.html
583
- └── blog/
584
- ├── _index.php → src/blog/index.html
585
- └── _articles.yaml (data file, not compiled)
586
- ```
587
-
588
- Directories whose name starts with `_` (e.g. `_layouts/`, `_lib/`) are skipped entirely during directory-wide builds.
589
-
590
- ### PHPDOC header
591
-
592
- Every page starts with a PHP docblock that drives metadata and data loading:
593
-
594
- ```php
595
- <?php
596
- /**
597
- * @name about
598
- * @title About us
599
- * @abstract A short description of this page.
600
- */
601
- ?>
602
- <section>
603
- <h1><?php echo $title; ?></h1>
604
- <p><?php echo $abstract; ?></p>
605
- </section>
606
- ```
607
-
608
- All annotations are injected as PHP variables (`$name`, `$title`, `$abstract`, …). You can define any custom annotation you need.
609
-
610
- Annotations are also available as variables in `before` and `after` PHP included files, so you can write proper metas in the HTML header.
611
-
612
- Only lines whose first non-whitespace character (past the `*` gutter) is `@`
613
- open an annotation — an `@word` written in the prose of the block is left alone.
614
- A value can wrap onto the following **indented** continuation lines:
615
-
616
- ```php
617
- /**
618
- * @title About us
619
- * @description A longer blurb that does not fit comfortably
620
- * on a single line and continues here.
621
- */
622
- ```
623
-
624
- ### Auto-loading data files
625
-
626
- When an annotation value looks like a filename (with a `.yaml`, `.yml`, `.json`, or `.md` extension), it is automatically parsed and injected as a structured variable instead of a plain string.
627
-
628
- ```php
629
- <?php
630
- /**
631
- * @name medias
632
- * @articles _articles.yaml
633
- */
634
- ?>
635
- <?php foreach ($articles as $article): ?>
636
- <a href="<?php echo $article->lien; ?>">
637
- <?php echo $article->titre; ?>
638
- </a>
639
- <?php endforeach; ?>
640
- ```
641
-
642
- | Extension | Parsed as |
643
- |-----------|-----------|
644
- | `.yaml` / `.yml` | `stdClass` object (or array of objects for sequences) |
645
- | `.json` | Result of `json_decode()` |
646
- | `.md` | HTML string via `MD::toHtml()` |
647
-
648
- When `network: true` is set in `kirigami.yaml`, annotation values that start with `http://` or `https://` are fetched from the network and parsed the same way:
649
-
650
- ```php
651
- /**
652
- * @posts https://api.example.com/posts.json
653
- */
654
- ```
655
-
656
- ### `@content` and `@indent`
657
-
658
- Two special annotation names change how a page's body is assembled:
659
-
660
- - **`@content`** — if a `content` variable already resolves to a non-empty value (typically because it's a `.md`/`.yaml`/`.json` annotation that auto-loaded into HTML/data, see above), it is used **as-is** as the page body, and the PHP file itself is **not executed** for its output. This is handy for pages that are pure data/markdown wrapped by a shared layout.
661
- - **`@indent`** — when set to a number, every line of the rendered body is prefixed with that many spaces before being wrapped by `before.php`/`after.php`. Useful for keeping generated HTML readable when a page is nested inside indented layout markup.
662
-
663
- ```php
664
- <?php
665
- /**
666
- * @name changelog
667
- * @title Changelog
668
- * @content _changelog.md
669
- * @indent 4
670
- */
671
- ```
672
-
673
- ### Built-in tags
674
-
675
- Two tags are registered out of the box (`prepros.plugins.php`) and processed
676
- **after** the PHP runs, on the assembled HTML — no include or plugin needed.
677
-
678
- #### `<markdown> … </markdown>`
679
-
680
- Converts its inner content from Markdown to HTML, stripping the common leading
681
- indentation first (via `STR::trimIndent()`) so you can indent it naturally inside
682
- your template. All registered [MD plugins](#md-plugins) work inside it. See
683
- [Extending the `<markdown>` tag](#extending-the-markdown-tag) to override it.
684
-
685
- ```html
686
- <section>
687
- <markdown>
688
- ## Who we are
689
-
690
- We are a **student organization** from Québec.
691
- </markdown>
692
- </section>
693
- ```
694
-
695
- Add the `prose` attribute — `<markdown prose>` — to wrap the output in
696
- `<div class="prose">`, so it picks up the long-form typography of
697
- [`@kirigami/canva`'s `styles/prose`](https://www.npmjs.com/package/@kirigami/canva)
698
- with no extra markup. Any `class` / `id` on the tag lands on that wrapper
699
- (`<markdown prose class="lede" id="intro">` → `<div class="prose lede" id="intro">`).
700
- A bare `<markdown>` emits just the converted HTML, as before.
701
-
702
- #### `<img asset="…">`
703
-
704
- The HTML-side entry point of the image autogenerator — the exact same feature as
705
- the [`img-asset()` Sass function](https://www.npmjs.com/package/@kirigami/kirigami#sass-functions)
706
- and [`IMG::asset()`](#img), with the same parameters. The tag calls `IMG::asset()`
707
- under the hood, then swaps the `asset` attribute for the generated `src`.
708
-
709
- ```html
710
- <!-- in: resolves assets/images/hero.jpg through IMG::asset('hero.jpg', 800, 0, false) -->
711
- <img asset="hero.jpg" width="800" alt="Our office" loading="lazy">
712
- <!-- out: <img src="../images/hero-800w.webp" alt="Our office" loading="lazy"> -->
713
- ```
714
-
715
- | Attribute | Maps to `IMG::asset()` arg | Notes |
716
- |-----------|---------------------------|-------|
717
- | `asset` | `$path` | **Required.** Path relative to `image.source`. Missing/empty ⇒ the tag is left untouched. |
718
- | `width` | `$width` | Optional, integer. Omitted ⇒ `0` (keep). |
719
- | `height` | `$height` | Optional, integer. Omitted ⇒ `0` (keep). |
720
- | `cover` | `$cover` | Boolean — **presence means `true`** (crop + fill). |
721
- | *(any other)* | — | `alt`, `class`, `id`, `loading`, … are passed straight through onto the output `<img>`. |
722
-
723
- `asset` / `width` / `height` / `cover` are consumed and removed; everything else
724
- survives. The generated file lands in `image.dest` and is only (re)generated when
725
- missing or older than the source — see [`IMG`](#img) for the naming convention.
726
-
727
- > The Sass `img-asset()` / `colors()` functions, the `<img asset>` tag and
728
- > `IMG::asset()` all run on the **same engine** — the `IMG` class (GD, with the
729
- > Imagick fallback) in this package. `@kirigami/kirigami`'s `sass` task routes its
730
- > image work here through [`processImages()`](#processimagesjobs), so there is no
731
- > native image dependency in the toolchain.
732
-
733
- ---
734
-
735
- ## JavaScript API
736
-
737
- ```js
738
- import { render, sitemap, runenv, mountPath, processImages } from '@kirigami/php-prepros';
739
- ```
740
-
741
- ### `render(file?)`
742
-
743
- Compile a single PHP page or a whole directory.
744
-
745
- ```js
746
- // Compile one page
747
- const result = await render('about/_index.php');
748
-
749
- // Compile everything under src/
750
- const result = await render('.');
751
-
752
- // Compile everything (uses kirigami.root from config)
753
- const result = await render();
754
- ```
755
- > Paths used by `render()` are all relative to the `kirigami.root` configuration.
756
-
757
-
758
- **Returns** `Promise<PreprosResult>`:
759
-
760
- ```ts
761
- interface PreprosResult {
762
- success: boolean;
763
- files: string[]; // relative paths of every file written
764
- error?: string; // present only on failure
765
- }
766
- ```
767
-
768
- ### `sitemap()`
769
-
770
- Generate `sitemap.xml` at the source root.
771
-
772
- ```js
773
- const result = await sitemap();
774
- // result.files === ['src/sitemap.xml']
775
- ```
776
-
777
- ### `runenv(script, paths?, ...args)`
778
-
779
- Run an arbitrary PHP script — not a page template — inside the very same sandboxed WASM environment used for `render()`, with the full `php-prepros` class library autoloaded and `kirigami.yaml`'s `kirigami` block available as `PREPROS::$config->data`. Useful for one-off maintenance scripts, data migrations, or CLI-style tooling that needs `CACHE`, `SCRAPER`, `IMG`, etc. without going through the page-rendering pipeline.
780
-
781
- ```js
782
- // Run a standalone PHP script
783
- const result = await runenv('scripts/purge-cache.php');
784
-
785
- // Also mount extra local paths/files into the sandbox before running
786
- const result = await runenv('scripts/build-og-images.php', ['assets/photos']);
787
-
788
- // Extra arguments are appended and available as $argv[2], $argv[3], … in the script
789
- const result = await runenv('scripts/import.php', [], '--force');
790
- ```
791
-
792
- - `script` — path to a PHP file **inside the project**, executed with `require_once`.
793
- - `paths` — optional array of extra local paths (files or directories) to mount into the sandbox before the script runs.
794
- - `...args` — extra string arguments appended to the script's `$argv`.
795
-
796
- **Returns** `Promise<PreprosResult>`, following the same shape as `render()`. Inside the script, call `PREPROS::exportFile()` for any file you want listed in `result.files`.
797
-
798
- ### `mountPath(localPath, virtualDir?, php?)`
799
-
800
- The JavaScript-side counterpart to [`PREPROS::mount()`](#preprosmountstringarray-patterns). Mounts a local file or directory — recursively, preserving structure — into the WASM sandbox's virtual filesystem, ahead of (or between) calls to `render()`, `sitemap()`, or `runenv()`. Useful when a Node-side build step needs to make extra local files visible to PHP before rendering starts.
801
-
802
- ```js
803
- import { mountPath, render } from '@kirigami/php-prepros';
804
-
805
- // Mount a single file at its natural virtual path (/project/<relative path>)
806
- await mountPath('assets/data/team.yaml');
807
-
808
- // Mount a whole directory, at a custom virtual path
809
- await mountPath('vendor/fonts', '/project/fonts');
810
-
811
- await render();
812
- ```
813
-
814
- - `localPath` — path to a local file or directory. Relative paths are resolved against the project root.
815
- - `virtualDir` — optional destination path inside the WASM filesystem. Defaults to `/project/<localPath relative to the project root>` when omitted.
816
- - `php` — optional WASM PHP instance to mount into. Defaults to the shared singleton instance (the same one used internally by `render()`/`sitemap()`/`runenv()`), creating it if needed.
817
-
818
- Mounting a **directory** only copies files whose extension is one of the defaults (`.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`) or listed in `prepros.mountext`, same as automatic root mounting. Mounting a **single file directly** copies it regardless of extension — this is the simplest way to make an arbitrary asset (an image, a font, a CSV, …) available to PHP without adding its extension to `prepros.mountext` project-wide.
819
-
820
- **Returns** `Promise<void>`.
821
-
822
- ### `processImages(jobs)`
823
-
824
- Run a batch of image jobs — resize/encode, or palette extraction — through the
825
- [`IMG`](#img) class (GD, with the Imagick fallback). This is the engine
826
- `@kirigami/kirigami`'s `sass` task uses for its `img-asset()` and `colors()`
827
- functions, so Sass, `IMG::asset()` and the [`<img asset>` tag](#built-in-tags)
828
- all share one implementation, one `image:` config and one set of output
829
- filenames — with no native image dependency.
830
-
831
- ```js
832
- import { processImages } from '@kirigami/php-prepros';
833
-
834
- const { files, colors } = await processImages([
835
- // resize/encode `hero.jpg` (resolved against image.source) to each dest —
836
- // absolute virtual paths, already carrying the target extension
837
- { op: 'resize', src: 'hero.jpg', width: 1200, height: 0, cover: false, quality: 82,
838
- dests: ['/project/src/images/hero-1200w.webp'] },
839
-
840
- // extract a 5-colour palette (cached in .cache.db); returned, not written
841
- { op: 'palette', src: 'hero.jpg', count: 5 },
842
- ]);
843
-
844
- // files → ['src/images/hero-1200w.webp'] (also copied back to the host)
845
- // colors → { 'hero.jpg:5': ['#1e3a5f', '#c8a24b', …] }
846
- ```
847
-
848
- - `jobs` — array of `resize` / `palette` jobs (see the shape above). An **empty
849
- array is a no-op** and does **not** start the WASM runtime.
850
- - Staleness is the caller's responsibility: every `resize` job listed is executed.
851
-
852
- **Returns** `Promise<PreprosResult & { colors: Record<string, string[]> }>`.
853
-
854
- ---
855
-
856
- ## PHP classes reference
857
-
858
- All classes are autoloaded — no manual `require` needed inside your page files.
859
-
860
- ---
861
-
862
- ### PREPROS
863
-
864
- The core engine. Manages the rendering pipeline, tag processing, hooks, mounting, and file export.
865
-
866
- ```php
867
- // Available inside page templates and included files.
868
- PREPROS::$config // stdClass — full resolved config; ->data is the kirigami: block,
869
- // ->image the image: block, plus before/after/format/… from prepros:
870
- PREPROS::registerTag(string $tag, callable $callback)
871
- PREPROS::registerHook(string $hook, callable $callback)
872
- PREPROS::runHook(string $hook, mixed $data = null) // fire a hook (built-in or your own), returns the piped $data
873
- PREPROS::mount(string|array $patterns)
874
- PREPROS::exportFile(string|array $absolutePath)
875
- PREPROS::getExportedFiles(): string[]
876
- PREPROS::fstat(string $path) // stat a file in the WASM FS (or false)
877
- PREPROS::backtraceFile() // path of the page currently rendering
878
- ```
879
-
880
- #### `PREPROS::render(string $file)`
881
-
882
- Internal method called once per source file. Orchestrates the full pipeline:
883
-
884
- 1. Resolves PHPDOC metadata and auto-loads data files.
885
- 2. Fires the `pre_render` hook with the raw source contents.
886
- 3. Includes `before.php` (wrapped in the `pre_before` / `post_before` hooks), the page body (or `@content`, see [above](#content-and-indent)), and `after.php` (wrapped in `pre_after` / `post_after`) into a single string.
887
- 4. Processes all registered custom HTML tags.
888
- 5. Fires the `post_render` hook on the assembled HTML.
889
- 6. Optionally pretty-prints via `HTML::format()` (when `format: true`).
890
- 7. Writes the output `.html` file.
891
-
892
- #### `PREPROS::sitemap()`
893
-
894
- Scans the source tree for `_index.php` files and generates a standards-compliant `sitemap.xml` (Sitemaps 0.9), using `kirigami.baseurl` as the root URL.
895
-
896
- #### `PREPROS::mount(string|array $patterns)`
897
-
898
- Mounts additional local project files into the WASM virtual filesystem, on demand, from one or more glob patterns evaluated against the project root (via `picomatch`). Unlike the automatic mounting done for `kirigami.root` (limited to `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`, and `prepros.mountext`), `mount()` copies **any** matching file, regardless of extension.
899
-
900
- ```php
901
- // Mount every .webp under assets/, wherever the page needs them
902
- PREPROS::mount('assets/**/*.webp');
903
-
904
- // Multiple patterns at once
905
- PREPROS::mount(['data/**/*.csv', 'vendor/fonts/*.woff2']);
906
- ```
907
-
908
- Returns an array of the virtual paths (under `/project/...`) that were mounted, or `false` on failure.
909
-
910
- #### `PREPROS::exportFile(string $file)`
911
-
912
- Marks a file as a build output so it gets surfaced in `PreprosResult.files`. Called automatically by `render()`, `sitemap()`, `CACHE::set()`, and `CURL`. Call it manually if your custom code writes additional files.
913
-
914
- ---
915
-
916
- ### MD
917
-
918
- Markdown-to-HTML converter with a plugin system for custom shortcodes.
919
-
920
- ```php
921
- $html = MD::toHtml(string $markdown): string;
922
- ```
923
-
924
- Supports the full GitHub Flavored Markdown subset, plus a few extensions:
925
-
926
- - ATX (`#` … `######`) and Setext headings, with auto-generated `id` attributes
927
- - Ordered and unordered lists, including nested
928
- - GFM task lists (`- [ ]` / `- [x]`)
929
- - GFM tables with column alignment
930
- - GFM alerts (`> [!NOTE]`, `> [!WARNING]`, etc.)
931
- - Blockquotes (recursive)
932
- - Fenced code blocks with language class
933
- - Inline code
934
- - Bold, italic, bold+italic, strikethrough
935
- - Links with automatic `target="_blank" rel="noopener noreferrer"` for external URLs
936
- - Images with `loading="lazy"`
937
- - Auto-linked bare URLs
938
- - Horizontal rules
939
- - Hard line breaks (trailing double space → `<br>`)
940
- - **Footnotes** — `[^1]` references and `[^1]: …` definitions (multi-paragraph)
941
- - **Definition lists** — `Term` / `: Definition`
942
- - **Emoji shortcodes** — `:rocket:` → 🚀, from a built-in map (see `MD::registerEmoji()`)
943
- - **Sanitized inline HTML** — raw tags are filtered against an allowlist of tags and attributes, not passed through verbatim
944
-
945
- #### Plugin API
946
-
947
- Extend Markdown with custom shortcode tags:
948
-
949
- ```php
950
- // Inline tag {% tagname arg1 "arg with spaces" %}
951
- // Block tag {% tagname arg1
952
- // body content
953
- // %}
954
-
955
- MD::registerPlugin(string $name, callable $callback): void
956
- MD::unregisterPlugin(string $name): void
957
- MD::getRegisteredPlugins(): string[]
958
- MD::registerEmoji(string $shortcode, string $char): void // `:name:` → char
959
- ```
960
-
961
- The callback always receives `(array $args, string $body)`:
962
-
963
- ```php
964
- MD::registerPlugin('video', function (array $args, string $body): string {
965
- $src = htmlspecialchars($args[0] ?? '', ENT_QUOTES, 'UTF-8');
966
- return "<video src=\"{$src}\" controls></video>";
967
- });
968
- ```
969
-
970
- Then in any Markdown content (including inside `<markdown>` tags):
971
-
972
- ```
973
- {% video /videos/intro.mp4 %}
974
- ```
975
-
976
- ---
977
-
978
- ### HTML
979
-
980
- Pretty-printer for the final HTML output. Used automatically when `format: true` is set in the config.
981
-
982
- ```php
983
- $formatted = HTML::format(string $html): string;
984
- ```
985
-
986
- Uses PHP 8.4's `Dom\HTMLDocument` (Lexbor engine) to parse the input and re-serialize it with consistent 4-space indentation. Inline elements, `<script>`, and `<style>` blocks are handled correctly — their content is indented but not reformatted. A `<pre><code>` block is shifted to its nesting depth too (relative indentation kept), and the leading run is stripped again before display; a bare `<pre>` and `<textarea>` stay byte-for-byte. Boolean HTML5 attributes (`muted`, `autoplay`, `noopener`, etc.) are written without a value.
987
-
988
- ---
989
-
990
- ### YAML
991
-
992
- A lightweight, zero-dependency YAML parser. Covers the full subset used in static site projects.
993
-
994
- ```php
995
- $data = YAML::parse(string $yaml, bool $assoc = false): mixed;
996
- $data = YAML::parseFile(string $path, bool $assoc = false): mixed;
997
- $data = YAML::loadFile(string $path, bool $assoc = false): mixed;
998
- ```
999
-
1000
- Supported features:
1001
-
1002
- - Scalars: strings (quoted and unquoted), integers, floats, booleans, null
1003
- - Single and double quoted strings with escape sequences
1004
- - Literal block scalars (`|`, `|-`, `|+`)
1005
- - Folded block scalars (`>`, `>-`, `>+`)
1006
- - Plain scalars spanning multiple lines
1007
- - Nested mappings and sequences
1008
- - Inline collections (`[a, b]` and `{k: v}`)
1009
- - Comments (`#`)
1010
- - Multiple documents separated by `---`
1011
-
1012
- By default, YAML mappings are returned as `stdClass` objects. Pass `true` as the second argument to get associative arrays instead.
1013
-
1014
- `YAML::loadFile()` behaves like `YAML::parseFile()`, then walks the result recursively: any string value ending in `.yaml`, `.yml`, or `.json` that resolves to an existing file (relative to *its own* file's directory) is replaced by that file's parsed content, and so on, recursively. Values that don't match an existing file are left untouched. Circular references (`A → B → A`) throw a `RuntimeException`.
1015
-
1016
- ```yaml
1017
- # team.yaml
1018
- lead: people/jane.yaml # resolved and inlined automatically
1019
- members:
1020
- - people/jane.yaml
1021
- - people/john.yaml
1022
- ```
1023
-
1024
- ```php
1025
- $team = YAML::loadFile('/project/data/team.yaml');
1026
- // $team->lead is now the fully parsed content of people/jane.yaml, not a string
1027
- ```
1028
-
1029
- ---
1030
-
1031
- ### SCHEMA
1032
-
1033
- A pure-PHP, dependency-free JSON Schema validator — Draft-7 style, with an
1034
- Ajv-like API. Used internally to validate structured data, but available to your
1035
- own code and plugins.
1036
-
1037
- ```php
1038
- $validator = new SCHEMA(array $schema);
1039
-
1040
- $validator->isValid(mixed $data): bool // true / false
1041
- $validator->validate(mixed $data): bool // alias of isValid()
1042
- $validator->getErrors(): string[] // "path: message" strings from the last run
1043
- ```
1044
-
1045
- Supported keywords: `type`, `required`, `properties`, `patternProperties`,
1046
- `additionalProperties`, `items`, `minItems`, `maxItems`, `uniqueItems`,
1047
- `minLength`, `maxLength`, `pattern`, `minimum`, `maximum`, `exclusiveMinimum`,
1048
- `exclusiveMaximum`, `minProperties`, `maxProperties`, `enum`, `const`,
1049
- `anyOf`, `allOf`, `oneOf`, `not`, `format`, and local `$ref` pointers.
1050
-
1051
- ```php
1052
- $validator = new SCHEMA([
1053
- 'type' => 'object',
1054
- 'required' => ['name', 'age'],
1055
- 'properties' => [
1056
- 'name' => ['type' => 'string', 'minLength' => 1],
1057
- 'age' => ['type' => 'integer', 'minimum' => 0],
1058
- ],
1059
- 'additionalProperties' => false,
1060
- ]);
1061
-
1062
- if (!$validator->isValid($data)) {
1063
- foreach ($validator->getErrors() as $err) echo $err, PHP_EOL;
1064
- }
1065
- ```
1066
-
1067
- ---
1068
-
1069
- ### LD
1070
-
1071
- A **schema.org JSON-LD generator**. `LD` accumulates structured-data nodes for
1072
- the page under render and emits them as one
1073
- `<script type="application/ld+json">` block — with an `@graph` when there is more
1074
- than one node — in the `<head>`.
1075
-
1076
- #### Automatic mode
1077
-
1078
- Opt in by adding a top-level `jsonld:` block to `kirigami.yaml` (a sibling of
1079
- `kirigami:`, not nested under it) — an empty `jsonld: {}` is enough. A
1080
- `post_render` hook then injects a graph built from that block, the loose keys of
1081
- the `kirigami` block, and the current page's PHPDOC:
1082
-
1083
- - an `Organization` node (`@id` `#organization`) — `name`/`url`/`description`
1084
- from `project`/`baseurl`/`description`, `sameAs` gathered from every
1085
- recognised social-network URL key (`facebook`, `instagram`, `linkedin`,
1086
- `github`, `youtube`, `mastodon`, …), plus `email`, `telephone`, `areaServed`
1087
- (← `area`), `knowsAbout` (← `knowsabout`), `address`, `logo`, and `founder` →
1088
- the Person node when there is one. `@type` comes from `jsonld.type`;
1089
- - a `Person` node (`#person`) when `person` is set — `name` + `jobTitle`
1090
- (← `jobtitle`) + `email` + `url`, linked to the Organization via `worksFor`;
1091
- - a `WebSite` node (`#website`) — `publisher` → Organization, `inLanguage`,
1092
- `keywords` (← `keywords`), and a `SearchAction` when `jsonld.search` is set;
1093
- - a `WebPage` node for the page — see the per-page tags below;
1094
- - a `BreadcrumbList` for every non-home page, derived from the `_index.php`
1095
- ancestor trail (home → each parent section → this page). No `@breadcrumb`
1096
- opt-in needed — it is always attempted while the `jsonld:` block is on.
1097
- Disable it for one page with `@ld_breadcrumb false`.
1098
-
1099
- Remove the `jsonld:` block (or set `jsonld: false` / `jsonld: { auto: false }`)
1100
- to stop the automatic pass. A page whose rendered `<head>` already contains an
1101
- `application/ld+json` script is never touched, so hand-rolled markup keeps
1102
- working.
1103
-
1104
- **Per-page PHPDOC tags** — these feed the page node (and override the generic
1105
- `@title` / `@description` / `@datePublished` fallbacks):
1106
-
1107
- | Tag | Effect |
1108
- |-----|--------|
1109
- | `@ld false` | Skip JSON-LD for this page entirely (`@ld_ignore true` also works). |
1110
- | `@ld_type <Type>` | `@type` of the page node — `AboutPage`, `ContactPage`, `CollectionPage`, `ProfilePage`, or a content type like `Article`, `Service`, `Recipe`, … (default `WebPage`). Types containing “Page” also get `primaryImageOfPage` + a `breadcrumb` link; others get a plain `image`. |
1111
- | `@ld_title <text>` | Page node `name` (default: `@title`). |
1112
- | `@ld_description <text>` | Page node `description` (default: `@description`). |
1113
- | `@ld_image <path>` | Page image, absolute or relative to `baseurl` (default: `@image` / `@ogimage`). |
1114
- | `@ld_published <date>` | `datePublished` (default: `@datePublished` / `@published` / `@date`). |
1115
- | `@ld_modified <date>` | `dateModified` (default: `@dateModified` / `@modified` / `@updated`). |
1116
- | `@ld_breadcrumb false` | No `BreadcrumbList` for this page. |
1117
-
1118
- ```php
1119
- /**
1120
- * @title À propos
1121
- * @ld_type AboutPage
1122
- * @ld_title À propos de Humain Humain
1123
- * @ld_description Notre approche ethnographique de la consultation.
1124
- */
1125
- ```
1126
-
1127
- #### Explicit builders
1128
-
1129
- Call these from a page template or from a `prepros.includes` file. Nodes added
1130
- this way are always emitted — with or without a `jsonld:` block — and share the
1131
- graph the automatic pass uses, so the two combine; a node with a stable `@id` is
1132
- merged on repeat calls.
1133
-
1134
- ```php
1135
- LD::add(string|array $type, array $props = [], ?string $id = null): array // build + register a node
1136
- LD::node(string|array $type, array $props = []): array // build only, no register
1137
- LD::push(array $node): array // register a ready-made node
1138
- LD::ref(string $id): array // ['@id' => …] ('#person' → the Person node)
1139
- LD::remove(string $id): void
1140
- LD::graph(): array
1141
- LD::reset(): void
1142
-
1143
- LD::organization(array $overrides = []): array // config-aware, @id #organization
1144
- LD::person(array $overrides = []): array // config-aware, @id #person
1145
- LD::website(array $overrides = []): array // config-aware, @id #website
1146
- LD::webPage(array $overrides = []): array // current-page-aware, @id …#webpage
1147
- LD::breadcrumb(?array $items = null, array $overrides = []): array // items: [['name'=>…,'url'=>…], …]
1148
- LD::faqPage(array $qa, array $overrides = []): array // qa: ['Question ?' => 'Answer.', …]
1149
-
1150
- LD::address(array|string $a): array
1151
- LD::image(string $url, ?string $id = null, ?int $w = null, ?int $h = null): array
1152
- LD::geo(float $lat, float $lng): array
1153
- LD::rating(int|float $value, ?int $count = null, $best = 5, $worst = 1): array
1154
- LD::offer(array $o): array
1155
- LD::contactPoint(array $c): array
1156
- LD::searchAction(string $urlTemplate): array
1157
-
1158
- LD::script(bool $pretty = true): string // <script>…</script>, and disables auto-injection
1159
- LD::json(bool $pretty = true): string // the document, no wrapper
1160
- ```
1161
-
1162
- Every other schema.org type is reachable through `__callStatic` — the method
1163
- name is upper-cased to form the `@type`:
1164
-
1165
- ```php
1166
- LD::recipe([ 'name' => 'Tarte aux pommes', 'recipeYield' => '6', 'prepTime' => 'PT30M' ]);
1167
- LD::event([ 'name' => 'Vernissage', 'startDate' => '2026-10-01T18:00' ]);
1168
- LD::softwareApplication([ 'name' => 'Kirigami', 'applicationCategory' => 'DeveloperApplication' ]);
1169
-
1170
- LD::article([
1171
- 'headline' => $title,
1172
- 'datePublished' => '2026-09-01',
1173
- 'author' => LD::ref('#person'),
1174
- 'image' => LD::image('images/cover.webp'),
1175
- 'publisher' => LD::ref('#organization'),
1176
- ]);
1177
- ```
1178
-
1179
- Same API from procedural code: `ld_add()`, `ld_node()`, `ld_ref()`,
1180
- `ld_organization()`, `ld_person()`, `ld_website()`, `ld_web_page()`,
1181
- `ld_breadcrumb()`, `ld_faq_page()`, `ld_script()`, `ld_json()`.
1182
-
1183
- #### `jsonld` config
1184
-
1185
- `jsonld:` is a **top-level** block of `kirigami.yaml` (a sibling of `kirigami:`,
1186
- `prepros:`, …), and its presence is what **switches automatic injection on**. An
1187
- empty `jsonld: {}` is enough — everything is then derived from the `kirigami`
1188
- block's loose keys. Adding keys overrides those inferences; all are optional.
1189
-
1190
- ```yaml
1191
- kirigami:
1192
- project: Humain Humain
1193
- baseurl: https://humainhumain.com
1194
- person: Méralie Murray-Hall
1195
- jobtitle: Anthropologue
1196
- facebook: https://www.facebook.com/humainhumainconsultation.ethnographie/
1197
-
1198
- jsonld: # top-level; the block being present is
1199
- type: ProfessionalService # the switch — `jsonld: {}` also works
1200
- lang: fr-CA # inLanguage on WebSite / WebPage (default: en)
1201
- logo: assets/logo.png # absolute, or relative to baseurl
1202
- knowsAbout: [Ethnographie, Recherche qualitative]
1203
- address:
1204
- addressLocality: Québec
1205
- addressCountry: CA
1206
- search: https://humainhumain.com/?q={search_term_string}
1207
- ```
1208
-
1209
- | Key | Type | Description |
1210
- |-----|------|-------------|
1211
- | `auto` | `bool` | Inject the `<script>` automatically. Default `true` **once the `jsonld:` block exists**. Set `auto: false` (or `jsonld: false`) to keep the block for its config values but stop the automatic injection — `LD::script()` / `ld_script()` can still place it by hand. |
1212
- | `type` | `string` | `@type` for the main entity — `Organization`, `ProfessionalService`, `LocalBusiness`, … |
1213
- | `name` / `url` / `description` | `string` | Main-entity / WebSite fields. Default to `project` / `baseurl` / `description`. |
1214
- | `logo` / `image` | `string` | Absolute URL or path relative to `baseurl`. `image` defaults to `logo`. |
1215
- | `sameAs` | `string[]` | Profile URLs, merged with the social-network URL keys found loose in the block. |
1216
- | `email` / `telephone` | `string` | Default to the loose `email` / `telephone` keys. |
1217
- | `address` | `map` | `PostalAddress` properties. |
1218
- | `areaServed` | `string` | Defaults to the loose `area` key. |
1219
- | `knowsAbout` / `keywords` | `string[]` | Default to the loose `knowsabout` / `keywords` keys. |
1220
- | `person` | `string` \| `map` | The `#person` node. A string is the name; a map takes any `Person` property. Defaults to `person` + `jobtitle` + `email`. |
1221
- | `lang` | `string` | BCP-47 tag for `inLanguage`. Default `en`. |
1222
- | `search` | `string` | URL template for a sitelinks `SearchAction`; must contain `{search_term_string}`. |
1223
-
1224
- ---
1225
-
1226
- ### META
1227
-
1228
- A **`<head>` SEO / social metadata generator** — the companion to [`LD`](#ld).
1229
- Where `LD` emits a schema.org `application/ld+json` graph, `META` emits the plain
1230
- tags a browser and a link-preview crawler read: `<title>`, `<meta name="…">`,
1231
- `<meta property="og:…">`, `<meta name="twitter:…">`, and a handful of `<link>`s.
1232
-
1233
- It draws on the same sources, in this order of precedence: the page's PHPDOC, the
1234
- top-level `meta:` block, then the loose `kirigami:` keys and the `jsonld:` block.
1235
- Every tag is emitted **only when it can be resolved** — no value, no tag — and a
1236
- tag the page's layout already writes by hand is detected and skipped, so it drops
1237
- in beside an existing `header.php` without duplicating anything.
1238
-
1239
- **Automatic mode** is opt-in: the top-level `meta:` block (empty `meta: {}` is
1240
- enough) turns on injection into every page's `<head>`, right before `</head>`.
1241
-
1242
- ```yaml
1243
- kirigami:
1244
- project: Humain Humain
1245
- baseurl: https://humainhumain.com
1246
- tagline: Ethnographie au service des organisations
1247
- description: A social-science consultancy using ethnography for organisational change.
1248
- keywords: [ethnographie, consultation publique, sciences sociales]
1249
- author: Maxime Larrivée-Roy
1250
-
1251
- jsonld: {} # META reads its logo / image / lang / person too
1252
- meta: # top-level; the block being present is the switch
1253
- twitter: "@humainhumain"
1254
- themeColor: "#0b7285"
1255
- ```
1256
-
1257
- Per-page, from the PHPDOC block — each falls back to the generic page tag:
1258
-
1259
- | Tag | Feeds | Default |
1260
- |-----|-------|---------|
1261
- | `@meta false` | skip metadata for this page entirely | — (`@meta_ignore true` also works) |
1262
- | `@meta_title` | `<title>`, `og:title`, `twitter:title` | `@title` |
1263
- | `@meta_description` | `description`, `og:description`, `twitter:description` | `@description` / `@abstract` / `@excerpt` / `@summary`, then the site `description` |
1264
- | `@meta_keywords` | `<meta name="keywords">` | `@keywords`, then `meta.keywords` |
1265
- | `@meta_image` | `og:image`, `twitter:image` | `@image` / `@ogimage`, then `meta.image` |
1266
- | `@meta_robots` | `<meta name="robots">` | `@robots`, then `meta.robots` |
1267
- | `@meta_type` | `og:type` | `@og_type`, then `meta.ogType` |
1268
- | `@canonical` | `<link rel="canonical">` | derived from the file path + `baseurl` |
1269
-
1270
- **Manual builders** — always emitted (with or without a `meta:` block), still
1271
- de-duplicated against the page:
1272
-
1273
- ```php
1274
- META::tag(string $name, ?string $content): void // name= , or property= for an og:* key
1275
- META::link(string $rel, string $href, array $attrs = []): void
1276
- META::raw(string $html): void // a verbatim, already-valid tag line
1277
- META::tags(string $html = ''): string // the whole block, \n-joined
1278
- META::reset(): void
1279
- ```
1280
-
1281
- ```php
1282
- META::tag('twitter:image', 'https://humainhumain.com/card.png');
1283
- META::tag('og:image:alt', 'The Humain Humain team at work');
1284
- META::link('icon', './favicon.svg', ['type' => 'image/svg+xml']);
1285
- ```
1286
-
1287
- Same API from procedural code: `meta_tag()`, `meta_link()`, `meta_raw()`,
1288
- `meta_tags()`.
1289
-
1290
- #### `meta` config
1291
-
1292
- `meta:` is a **top-level** block of `kirigami.yaml` (a sibling of `kirigami:`,
1293
- `jsonld:`, `prepros:`, …). All keys are optional.
1294
-
1295
- | Key | Type | Description |
1296
- |-----|------|-------------|
1297
- | `auto` | `bool` | Inject the tags automatically. Default `true` **once the `meta:` block exists**. `auto: false` (or `meta: false`) keeps the block for its values but stops the injection — `META::tags()` / `meta_tags()` can place them by hand. |
1298
- | `titleFormat` | `string` | `<title>` template for a normal page. Tokens `{title}`, `{project}`, `{tagline}`. Dangling separators from an empty token are trimmed. Default `{title} — {project}`. |
1299
- | `titleFormatHome` | `string` | Title template when the page has no `@title` (home / section landings). Default `{project} — {tagline}`. |
1300
- | `description` | `string` | Default description for pages with no `@description` / `@abstract`. Defaults to the `jsonld` / loose `description`. |
1301
- | `keywords` | `string[]` \| `string` | Default `keywords` content (list or comma string). Defaults to the `jsonld` / loose `keywords`. |
1302
- | `robots` | `string` | Default robots directive. Default `index, follow`. `robots: false` omits the tag. |
1303
- | `language` | `string` | BCP-47 tag → `<meta name="language">` and, dash→underscore, `og:locale`. Defaults to `jsonld.lang` / loose `lang` / `language`, then `en`. |
1304
- | `generator` | `string` \| `false` | `<meta name="generator">`. Default `Kirigami`; `false` omits it. |
1305
- | `author` / `designer` | `string` | Default to the loose `author` / `designer` keys (author also falls back to the `jsonld` person's name). `designer` is not emitted unless set. |
1306
- | `themeColor` | `string` | `<meta name="theme-color">`. Not emitted unless set. |
1307
- | `image` | `string` | Default `og:image` / `twitter:image` — absolute URL or path relative to `baseurl`. Defaults to `jsonld.image` → `jsonld.logo` → loose `image` / `ogimage`. |
1308
- | `ogType` | `string` | Default `og:type`. Default `website`. |
1309
- | `twitterCard` | `string` | `twitter:card` type. Default `summary_large_image`. |
1310
- | `twitter` | `string` \| `map` | Handle for `twitter:site` / `twitter:creator`. A bare string (with/without `@`, or a profile URL) fills both; a map takes `site` / `creator` separately. |
1311
- | `canonical` | `bool` | Emit `<link rel="canonical">`. Default `true`. |
1312
- | `favicon` / `appleTouchIcon` / `humans` | `string` \| `bool` | `<link rel="icon">` / `rel="apple-touch-icon"` / `rel="author"`. A path sets it (page-relative when a bare filename); `true` forces the default file (`favicon.ico` / `apple-touch-icon.png` / `humans.txt`); omitted, the default file is auto-detected on disk at the source root; `false` disables it. |
1313
-
1314
- ---
1315
-
1316
- ### CACHE
1317
-
1318
- Persistent SQLite-backed key-value cache. Survives across incremental builds via `.cache.db` at the project root.
1319
-
1320
- ```php
1321
- CACHE::get(string $key): mixed
1322
- CACHE::set(string $key, mixed $val, int $ttl = 0): bool
1323
- CACHE::delete(string $key): bool
1324
- CACHE::purge(): bool // removes expired entries
1325
- ```
1326
-
1327
- The `$ttl` is in seconds. `0` means the entry never expires. Typical use case: caching the result of network fetches in custom hooks or plugins — it is what powers [`SCRAPER`](#scraper) and `CURL`'s cookie persistence internally.
1328
-
1329
- ```php
1330
- $data = CACHE::get('my-remote-data');
1331
- if ($data === null) {
1332
- $data = json_decode(file_get_contents('https://api.example.com/data.json'));
1333
- CACHE::set('my-remote-data', $data, 3600); // cache for 1 hour
1334
- }
1335
- ```
1336
-
1337
- ---
1338
-
1339
- ### IMG
1340
-
1341
- Image manipulation helper. GD handles JPEG, PNG, GIF, WebP and AVIF directly;
1342
- anything GD can't decode (HEIC, TIFF, BMP, and the vector formats SVG, EPS, AI,
1343
- PDF) falls back to Imagick, which rasterizes it to a GD image in memory. Vector
1344
- files with no intrinsic pixel size are rasterized at 2000&nbsp;px on the longest
1345
- side, preserving the aspect ratio.
1346
-
1347
- ```php
1348
- $img = new IMG(string $file);
1349
-
1350
- // Properties
1351
- $img->width // int
1352
- $img->height // int
1353
-
1354
- // Instance methods (resize/save are chainable)
1355
- $img->resize(int $width, int $height = 0, bool $cover = false): self
1356
- $img->save(string $dest, ?int $quality = null): self // quality 0-100 for jpg/webp/avif; null = per-format default (82)
1357
- $img->getRepresentativeColors(int $count = 5): string[] // ['#rrggbb', …]
1358
-
1359
- // Static helpers
1360
- IMG::asset(string $path, int $width = 0, int $height = 0, bool $cover = false): string // same feature as the <img asset> tag and the img-asset() Sass function
1361
- IMG::palette(string $path, int $colors = 5): string[]
1362
- ```
1363
-
1364
- `resize()` operates in *contain* mode by default (scales to fit within the target box while preserving aspect ratio). Pass `$cover = true` to crop and fill the exact target dimensions.
1365
-
1366
- `save()` infers the output format from the file extension (`.jpg`, `.jpeg`, `.png`, `.gif`, `.webp`, `.avif`) and marks the file as a build output.
1367
-
1368
- ```php
1369
- // Build a 1200×630 cropped Open Graph image next to the original
1370
- (new IMG('/project/src/images/hero.jpg'))
1371
- ->resize(1200, 630, true)
1372
- ->save('/project/src/images/hero-og.jpg');
1373
- ```
1374
-
1375
- `IMG::asset()` and `IMG::palette()` are what back kirigami-core's `img-asset()`
1376
- and `colors()` Sass functions: they resolve `$path` against `image.source` from
1377
- `kirigami.yaml`, generate a resized/re-encoded file under `image.dest` (only
1378
- when missing or stale), or return a `CACHE`-backed list of representative
1379
- colours. Both are equally usable from your own PHP.
1380
-
1381
- `IMG::asset()` is the single implementation behind the [`<img asset>` tag](#built-in-tags)
1382
- too — the tag is just a thin wrapper. Generated files are named after the source
1383
- plus a dimension suffix: `-<W>w`, `-<H>h`, `-<W>x<H>`, or `-<W>x<H>-cover`, with
1384
- the `image.format` extension (e.g. `hero.jpg` + `width="800"` → `hero-800w.webp`).
1385
- `@kirigami/kirigami`'s Sass `img-asset()` / `colors()` functions produce the same
1386
- files from the same config through this same class, via
1387
- [`processImages()`](#processimagesjobs) — one engine, no native dependency.
1388
-
1389
- ---
1390
-
1391
- ### FS
1392
-
1393
- Filesystem utilities.
1394
-
1395
- ```php
1396
- FS::dig(string $glob): iterable // recursive glob, yields file paths
1397
- FS::getRelativePath(string $from, string $to): string
1398
- FS::phpFileInfo(string $file): object|false // parse PHPDOC annotations
1399
- FS::getChildren(string $backtrace = ''): object[] // child _index.php pages, ordered by @position
1400
- FS::getBreadcrumb(string $backtrace = ''): object[] // ancestor _index.php pages, top-most first (opt-in via @breadcrumb)
1401
- FS::rmdir(string $dir, bool $removeSelf = true): bool
1402
- FS::pathJoin(string ...$parts): string // URL-aware path join with .. resolution
1403
- ```
1404
-
1405
- `FS::dig()` is the workhorse of directory-wide builds — it recursively walks a glob pattern and yields every matching file path.
1406
-
1407
- `FS::phpFileInfo()` parses the first PHPDOC block of a PHP file and returns its `@tag value` pairs as a `stdClass`. This is used internally to resolve page metadata and data-file annotations.
1408
-
1409
- `FS::getChildren()` (procedural: `fs_get_children()`) — usable only during a render — scans the folders directly below the calling template, keeps the ones that contain an `_index.php`, and returns one `stdClass` per child: the parsed PHPDOC of that `_index.php` plus a `->file` key with its absolute path. Entries are ordered by `@position` ascending (a page with no `@position` sorts as `999999`), then by folder name (natural, case-insensitive). Handy for building a section index or a navigation menu:
1410
-
1411
- ```php
1412
- <?php foreach (fs_get_children() as $page): ?>
1413
- <li><a href="<?= FS::getRelativePath(__DIR__, dirname($page->file)) ?>/"><?= $page->title ?></a></li>
1414
- <?php endforeach ?>
1415
- ```
1416
-
1417
- `FS::getBreadcrumb()` (procedural: `fs_get_breadcrumb()`) — also render-only — is the upward counterpart: it returns the calling page's breadcrumb trail. It only produces output when the calling file opts in with `@breadcrumb true` (or `@breadcrumb 1`) in its first PHPDOC block, otherwise it returns `[]`. From the folder **above** the caller's own folder (a page is never part of its own trail), it walks the parent directories upward and collects the `_index.php` of each, stopping at the source root or at the first ancestor `_index.php` that carries no active `@breadcrumb` tag — that page acts as a separator and is left out. Directories without an `_index.php` are skipped without breaking the chain. Entries come back ordered from the top-most ancestor down to the nearest parent, each a `stdClass` (parsed PHPDOC of its `_index.php` plus a `->file` key with its absolute path):
1418
-
1419
- ```php
1420
- <nav aria-label="Breadcrumb">
1421
- <?php foreach (fs_get_breadcrumb() as $crumb): ?>
1422
- <a href="<?= FS::getRelativePath(__DIR__, dirname($crumb->file)) ?>/"><?= $crumb->title ?></a>
1423
- <?php endforeach ?>
1424
- </nav>
1425
- ```
1426
-
1427
- ---
1428
-
1429
- ### STR
1430
-
1431
- String utilities used internally by the tag-processing pipeline, and available for your own templates and plugins.
1432
-
1433
- ```php
1434
- STR::htmlesc(string $str): string
1435
- STR::replaceTags(string $tag, string $html, callable $callback): string
1436
- STR::parseHtmlAttributes(string $attrString): array
1437
- STR::trimIndent(string $str): string
1438
- STR::is_url(string $str): bool
1439
- STR::html_entities_decode(string $str): string
1440
- STR::shorthash(string $str): string
1441
- STR::normalize(string $str): string
1442
- STR::slug(string $str, string $sep = ''): string
1443
- ```
1444
-
1445
- `STR::replaceTags()` is the engine behind `PREPROS::registerTag()`. It finds all occurrences of `<tagname ...>...</tagname>` in an HTML string and replaces each with the return value of `$callback($fullMatch, $attrs, $body)`.
1446
-
1447
- `STR::trimIndent()` strips the common leading whitespace from a multi-line string — handy when pulling content out of indented `<markdown>` blocks.
1448
-
1449
- `STR::is_url()` checks whether a string parses as a URL with a recognized scheme (`http`, `https`, `ftp`, `ftps`, `ssh`, `ssl`, `sftp`, `itunes`).
1450
-
1451
- `STR::html_entities_decode()` trims a string and decodes its HTML entities — handy when normalizing text scraped from a third-party page.
1452
-
1453
- `STR::shorthash()` returns the first 12 characters of a string's SHA-256 hash — used internally as a stable, filename-safe cache key (see `SCRAPER`).
1454
-
1455
- `STR::normalize()` applies Unicode NFD decomposition and strips combining marks (`é` → `e`) — the accent-folding step used by `slug()`.
1456
-
1457
- `STR::slug()` normalizes, transliterates to ASCII, lowercases, and replaces every run of non-`[a-z0-9]` characters with `$sep` (empty by default → a compact identifier; pass `'-'` for a conventional hyphenated slug).
1458
-
1459
- ---
1460
-
1461
- ### ARR
1462
-
1463
- Recursive lookup helper for nested arrays and objects.
1464
-
1465
- ```php
1466
- ARR::find_key(mixed $data, string $key): mixed
1467
- ```
1468
-
1469
- Walks an array or object (including mixed nested `stdClass`/array structures, as produced by `YAML::parse()` or `json_decode()`) depth-first and returns the value of the **first** matching key found, at any depth, or `null` if none matches.
1470
-
1471
- ```php
1472
- $config = YAML::parseFile('team.yaml');
1473
- $email = ARR::find_key($config, 'email'); // finds `email` however deep it's nested
1474
- ```
1475
-
1476
- ---
1477
-
1478
- ### CURL
1479
-
1480
- Low-level HTTP client built on PHP's cURL extension, used internally by `SCRAPER`. Ships with a realistic browser `User-Agent`/header set and a cookie jar persisted at `.cookie.txt` (auto-registered via `PREPROS::exportFile()`).
1481
-
1482
- ```php
1483
- CURL::urlExists(string $url, ?string $mimereg = null): bool
1484
- CURL::getInfo(string $url): array|false // HEAD request, returns curl_getinfo()
1485
- CURL::getContents(string $file, ?string $dest = null, ?callable $clb = null): string|bool
1486
- ```
1487
-
1488
- `CURL::urlExists()` issues a `HEAD` request and returns `true` for any `2xx`/`3xx` response.
1489
-
1490
- `CURL::getContents()` downloads a URL. Without `$dest`, it returns the body as a string; with `$dest`, it streams the download to that file path and returns a boolean. Pass `$clb` to receive download progress as a float between `0` and `1`.
1491
-
1492
- ```php
1493
- CURL::getContents('https://example.com/report.pdf', '/project/src/downloads/report.pdf', function (float $progress) {
1494
- error_log(sprintf('%.0f%%', $progress * 100));
1495
- });
1496
- ```
1497
-
1498
- ---
1499
-
1500
- ### SCRAPER
1501
-
1502
- Fetches a URL and extracts page metadata (`title`, `description`, `image`, `label`) from its JSON-LD (`schema.org`), Open Graph, and standard `<meta>` tags — the kind of data you'd want for a rich link preview. Results are cached indefinitely via `CACHE`, keyed on the URL.
1503
-
1504
- ```php
1505
- $metas = SCRAPER::get(string $url): object|false;
1506
- ```
1507
-
1508
- ```php
1509
- $metas = SCRAPER::get('https://example.com/blog/some-article');
1510
- if ($metas) {
1511
- echo $metas->title; // string
1512
- echo $metas->description; // string
1513
- echo $metas->image; // string (absolute URL, may be empty)
1514
- echo $metas->label; // string — site/publisher name, may be empty
1515
- echo $metas->url; // string — the URL that was scraped
1516
- }
1517
- ```
1518
-
1519
- Returns `false` if the page can't be reached, can't be parsed, or has no discoverable title. Throws an `Exception` on invalid URLs. Uses `CURL::getContents()` under the hood, so it benefits from the same shared cookie jar and browser-like headers.
1520
-
1521
- ---
1522
-
1523
- ### OBF
1524
-
1525
- Simple reversible obfuscation for values you want to embed in HTML without making them trivially readable (e.g., contact data, API tokens in templates).
1526
-
1527
- ```php
1528
- $encoded = OBF::encode(mixed $obj): string;
1529
- $decoded = OBF::decode(string $str): mixed;
1530
- ```
1531
-
1532
- Applies JSON encoding → base64 → ROT-13 → gzip. Not cryptographically secure; intended for light obfuscation only.
1533
-
1534
- ---
1535
-
1536
- ### STD
1537
-
1538
- Output helpers used by the PHP runtime to communicate back to Node.js over stdout/stderr.
1539
-
1540
- ```php
1541
- STD::succeed(array|string $props = []): void // exits 0, writes JSON to stdout
1542
- STD::error(array|string $props = []): void // exits 1, writes JSON to stderr
1543
- ```
1544
-
1545
- These are internal to the build runner (`render()`, `sitemap()`, and `runenv()` all rely on them). You generally do not need to call them in page templates, but they are available if a script run via `runenv()` needs to terminate early with a custom result.
1546
-
1547
- ---
1548
-
1549
- ### Bundled polyfills
1550
-
1551
- The WASM PHP build ships without `ext-intl`, so `@kirigami/php-prepros` bundles a
1552
- `Normalizer` polyfill (autoloaded like every other class). It provides the
1553
- standard `Normalizer::normalize()` / `Normalizer::isNormalized()` API and the
1554
- `Normalizer::NFC` / `NFD` / `NFKC` / `NFKD` (and `FORM_*`) constants — enough for
1555
- `STR::normalize()` and `STR::slug()` to fold accents. Prefer the `STR` helpers in
1556
- your own code; the polyfill is there so third-party snippets that call
1557
- `Normalizer` directly keep working.
1558
-
1559
- ---
1560
-
1561
- ### Procedural shortcuts (aliases)
1562
-
1563
- Every static method of every class above is also exposed as a plain function by
1564
- `src/libraries/aliases.inc.php` (autoloaded — no `require` needed). Each alias is
1565
- named `<lowercase class>_<snake_case method>()` and does nothing but forward its
1566
- arguments, so the classes remain the canonical API. They exist to make page
1567
- templates and `kiri run` scripts read better:
1568
-
1569
- ```php
1570
- <?= md_to_html(file_get_contents('CHANGELOG.md')) ?>
1571
- <img src="<?= img_asset('hero.jpg', 1200, 630, true) ?>" alt="">
1572
- ```
1573
-
1574
- Every function has a complete PHPDoc block, so editor hover and autocomplete
1575
- surface the signature, parameters, and description.
1576
-
1577
- | Class | Aliases |
1578
- |---|---|
1579
- | `PREPROS` | `prepros_render` · `prepros_sitemap` · `prepros_mount` · `prepros_fstat` · `prepros_export_file` · `prepros_get_exported_files` · `prepros_backtrace_file` · `prepros_register_tag` · `prepros_register_hook` · `prepros_run_hook` |
1580
- | `MD` | `md_to_html` · `md_register_plugin` · `md_unregister_plugin` · `md_get_registered_plugins` · `md_register_emoji` |
1581
- | `HTML` | `html_format` |
1582
- | `YAML` | `yaml_parse` · `yaml_parse_file` · `yaml_load_file` |
1583
- | `SCHEMA` | `schema` (factory) · `schema_validate` |
1584
- | `LD` | `ld_add` · `ld_node` · `ld_ref` · `ld_organization` · `ld_person` · `ld_website` · `ld_web_page` · `ld_breadcrumb` · `ld_faq_page` · `ld_script` · `ld_json` |
1585
- | `META` | `meta_tag` · `meta_link` · `meta_raw` · `meta_tags` |
1586
- | `CACHE` | `cache_get` · `cache_set` · `cache_delete` · `cache_purge` |
1587
- | `IMG` | `img_asset` · `img_palette` |
1588
- | `FS` | `fs_dig` · `fs_get_relative_path` · `fs_php_file_info` · `fs_rmdir` · `fs_path_join` |
1589
- | `STR` | `str_htmlesc` · `str_replace_tags` · `str_parse_html_attributes` · `str_trim_indent` · `str_is_url` · `str_html_entities_decode` · `str_shorthash` · `str_normalize` · `str_slug` |
1590
- | `ARR` | `arr_find_key` |
1591
- | `CURL` | `curl_url_exists` · `curl_get_info` · `curl_get_contents` |
1592
- | `SCRAPER` | `scraper_get` |
1593
- | `OBF` | `obf_encode` · `obf_decode` |
1594
- | `STD` | `std_succeed` · `std_error` |
1595
-
1596
- Notes:
1597
-
1598
- - `register_tag()` / `register_hook()` are kept as unprefixed aliases of
1599
- `prepros_register_tag()` / `prepros_register_hook()`.
1600
- - `img_asset()` resolves the generated URL relative to the file that calls it,
1601
- exactly like `IMG::asset()`.
1602
- - `schema_validate(array $schema, mixed $data, ?array &$errors = null): bool`
1603
- fills `$errors` with the validation messages.
1604
- - `yaml_parse()` / `yaml_parse_file()` are only defined when the PECL `yaml`
1605
- extension isn't already providing them.
1606
-
1607
- ---
1608
-
1609
- ## Plugin system
1610
-
1611
- `@kirigami/php-prepros` has two complementary plugin layers: **PREPROS** (HTML-tag level, operates on the assembled page) and **MD** (shortcode level, operates inside Markdown content).
1612
-
1613
- ---
1614
-
1615
- ### PREPROS tags
1616
-
1617
- Register a custom HTML tag that is processed **after** PHP execution, on the fully assembled HTML string:
1618
-
1619
- ```php
1620
- // In a file listed under prepros.includes in kirigami.yaml, or in before.php:
1621
-
1622
- PREPROS::registerTag('gallery', function (string $fullTag, array $attrs, string $body): string {
1623
- $id = $attrs['id'] ?? '';
1624
- $imgs = glob("/project/src/images/gallery/{$id}/*.webp");
1625
- $html = '<div class="gallery">';
1626
- foreach ($imgs as $img) {
1627
- $src = str_replace('/project/src', '', $img);
1628
- $html .= "<img src=\"{$src}\" loading=\"lazy\">";
1629
- }
1630
- return $html . '</div>';
1631
- });
1632
- ```
1633
-
1634
- Then in any page template:
1635
-
1636
- ```html
1637
- <gallery id="summer-2025"></gallery>
1638
- ```
1639
-
1640
- The callback receives:
1641
-
1642
- | Parameter | Type | Description |
1643
- |-----------|------|-------------|
1644
- | `$fullTag` | `string` | The complete matched tag string |
1645
- | `$attrs` | `array` | Parsed HTML attributes as an associative array |
1646
- | `$body` | `string` | Inner content between opening and closing tags |
1647
-
1648
- The built-in [`<markdown>` and `<img asset>` tags](#built-in-tags) are registered
1649
- this way.
1650
-
1651
- ---
1652
-
1653
- ### PREPROS hooks
1654
-
1655
- Hooks let you intercept and transform data at key points in the rendering pipeline:
1656
-
1657
- ```php
1658
- PREPROS::registerHook(string $hookName, callable $callback): void
1659
- ```
1660
-
1661
- | Hook | When it fires | `$data` type | Expected return |
1662
- |------|---------------|--------------|-----------------|
1663
- | `boot` | Once per process, right after bootstrap (config loaded, `includes` pulled in), before any page renders. Fires for every entrypoint. | `stdClass $config` | ignored |
1664
- | `page_info` | After PHPDOC parsing, before rendering (auto-loads `.yaml`/`.json`/`.md` annotations) | `[$filePath, $pageObject]` — see note | `$pageObject` (modified) |
1665
- | `pre_render` | Before PHP execution | Raw file contents as `string` | `string` |
1666
- | `pre_before` | Just before the `before` include (inside its output buffer — `echo` to prepend to the header) | `before` config path as `string\|null` | ignored |
1667
- | `post_before` | Right after the `before` include, on the captured header | Header `string` | `string` |
1668
- | `pre_after` | Just before the `after` include (inside its output buffer — `echo` to prepend to the footer) | `after` config path as `string\|null` | ignored |
1669
- | `post_after` | Right after the `after` include, on the captured footer | Footer `string` | `string` |
1670
- | `post_render` | After tag processing, before `HTML::format()` | Assembled HTML `string` | `string` |
1671
-
1672
- Multiple callbacks can be registered for the same hook — they are executed in registration order, each receiving the return value of the previous one.
1673
-
1674
- > Built-in `page_info` + `post_render` callbacks power [`LD`](#ld) and
1675
- > [`META`](#meta): `page_info` captures the page under render, `post_render`
1676
- > injects the JSON-LD `<script>` and the `<meta>`/`<link>` block into its
1677
- > `<head>`. Your own callbacks run after them.
1678
-
1679
- > **`page_info` payload shape.** The hook *fires* with `[$filePath, $pageObject]`,
1680
- > but each callback is expected to return the `$pageObject` alone — so a callback
1681
- > registered after the built-ins receives the bare object, not the pair. Handle
1682
- > both: `$page = is_array($p) ? $p[1] : $p;` (the current page path is always
1683
- > available as `PREPROS::$file`).
1684
-
1685
- ```php
1686
- // Example: inject a last-modified date into every page
1687
- PREPROS::registerHook('post_render', function (string $html): string {
1688
- $date = date('Y-m-d');
1689
- return str_replace('{{build_date}}', $date, $html);
1690
- });
1691
- ```
1692
-
1693
- ---
1694
-
1695
- ### MD plugins
1696
-
1697
- MD plugins add custom shortcode tags inside Markdown content. They work inside `<markdown>` blocks, in `.md` data files, and anywhere `MD::toHtml()` is called.
1698
-
1699
- **Inline syntax** (all on one line):
1700
-
1701
- ```
1702
- {% tagname arg1 "argument with spaces" %}
1703
- ```
1704
-
1705
- **Block syntax** (body on subsequent lines):
1706
-
1707
- ```
1708
- {% tagname optional-arg
1709
- Line one of the body.
1710
- Line two of the body.
1711
- %}
1712
- ```
1713
-
1714
- ```php
1715
- MD::registerPlugin(string $name, callable $callback): void
1716
- ```
1717
-
1718
- The callback signature is always `(array $args, string $body): string`. `$args` contains arguments parsed from the opening line; `$body` is the trimmed multi-line body (empty string for inline tags).
1719
-
1720
- ---
1721
-
1722
- ### Built-in plugins
1723
-
1724
- The following MD plugins are registered out of the box in `md.plugins.php`:
1725
-
1726
- #### `{% callout type ["Title"] content %}`
1727
-
1728
- Renders a styled callout block. `type` is one of `info`, `success`, `warning`, `danger`.
1729
-
1730
- ```
1731
- {% callout warning "Heads up" This section is outdated. %}
1732
-
1733
- {% callout danger "Critical"
1734
- Line one of a longer warning.
1735
-
1736
- Line two after a blank line.
1737
- %}
1738
- ```
1739
-
1740
- #### `{% youtube id [width height] %}`
1741
-
1742
- Embeds a responsive YouTube player via `<iframe>`. `width`/`height` default to `560`/`315`.
1743
-
1744
- ```
1745
- {% youtube dQw4w9WgXcQ %}
1746
- {% youtube dQw4w9WgXcQ 800 450 %}
1747
- ```
1748
-
1749
- #### `{% codepen id [user height] %}`
1750
-
1751
- Embeds a CodePen result via `<iframe>`. `user` defaults to `anonymous`, `height` defaults to `400`.
1752
-
1753
- ```
1754
- {% codepen abcXYZ %}
1755
- {% codepen abcXYZ jsmith 500 %}
1756
- ```
1757
-
1758
- #### `{% checklist ["Title"] items %}`
1759
-
1760
- Renders a block-syntax list of checkbox items, one per line, with an optional title.
1761
-
1762
- ```
1763
- {% checklist "Today"
1764
- Do the dishes
1765
- Walk the dog
1766
- Read a book
1767
- %}
1768
- ```
1769
-
1770
- ---
1771
-
1772
- ## Extending the `<markdown>` tag
1773
-
1774
- The `<markdown>` tag is one of the [built-in tags](#built-in-tags) (alongside
1775
- `<img asset>`), registered as a PREPROS tag out of the box. It converts its inner
1776
- content from Markdown to HTML and strips common leading indentation so you can
1777
- write cleanly inside your PHP templates:
1778
-
1779
- ```html
1780
- <section class="about">
1781
- <div>
1782
- <markdown>
1783
- ## Who we are
1784
-
1785
- We are a **student organization** from Québec.
1786
-
1787
- {% youtube dQw4w9WgXcQ %}
1788
- </markdown>
1789
- </div>
1790
- </section>
1791
- ```
1792
-
1793
- All registered MD plugins are available inside `<markdown>` blocks. You can extend the tag's behaviour by registering additional MD plugins (see above) or by overriding the tag itself:
1794
-
1795
- ```php
1796
- PREPROS::registerTag('markdown', function (string $tag, array $attrs, string $body): string {
1797
- $body = STR::trimIndent($body);
1798
- $html = MD::toHtml($body);
1799
- // wrap in a container, add a class, etc.
1800
- $class = $attrs['class'] ?? 'prose';
1801
- return "<div class=\"{$class}\">{$html}</div>";
1802
- });
1803
- ```
1804
-
1805
- ---
1806
-
1807
- ## Requirements
1808
-
1809
- - Node.js `>= 24.0.0`
1810
- - npm `>= 10.2.3`
1811
- - ESM only (`"type": "module"`)
1812
-
1813
- ---
1814
-
1815
- ## License
1816
-
1817
- MIT © Maxime Larrivée-Roy, 2026
1
+ <div align="center">
2
+
3
+ <img src="https://zmotrin.github.io/assets/kirigami/kirigami-logo-universal.svg" alt="Kirigami" width="400" />
4
+
5
+ ---
6
+
7
+ # @kirigami/php-prepros
8
+
9
+
10
+ PHP preprocessor for the **Kirigami** static site generator.
11
+
12
+ [![npm version](https://img.shields.io/npm/v/@kirigami/php-prepros)](https://www.npmjs.com/package/@kirigami/php-prepros)
13
+ [![License: GPL-3.0-or-later](https://img.shields.io/badge/license-GPL--3.0--or--later-blue)](./LICENSE)
14
+ [![Node.js >=24.0.0](https://img.shields.io/badge/node-%3E%3D24.0.0-brightgreen)](https://nodejs.org)
15
+ [![Website](https://img.shields.io/badge/website-php--kirigami.github.io-1f6b4a)](https://php-kirigami.github.io)
16
+
17
+ </div>
18
+
19
+ ---
20
+
21
+ ## Overview
22
+
23
+ Build full static websites in PHP — with zero server, zero runtime dependency, zero compromise on expressiveness. Write your pages as regular PHP files, annotate them with a PHPDOC header, and let `php-prepros` compile everything to clean, deployable HTML.
24
+
25
+ It is the perfect solution for **GitHub Pages**. Since it runs entirely in Node.js, it is fully compatible with **GitHub Actions**, allowing you to automate your deployment pipeline effortlessly.
26
+
27
+ Part of the **Kirigami** project ecosystem.
28
+
29
+
30
+ ---
31
+
32
+
33
+ ## Table of contents
34
+
35
+ - [@kirigami/php-prepros](#kirigamiphp-prepros)
36
+ - [Overview](#overview)
37
+ - [What's new in 3.0.0](#whats-new-in-300)
38
+ - [What's new in 2.0.0](#whats-new-in-200)
39
+ - [What's new in 1.9.3](#whats-new-in-193)
40
+ - [What's new in 1.9.2](#whats-new-in-192)
41
+ - [What's new in 1.9.1](#whats-new-in-191)
42
+ - [What's new in 1.9.0](#whats-new-in-190)
43
+ - [What's new in 1.8.0](#whats-new-in-180)
44
+ - [What's new in 1.7.2](#whats-new-in-172)
45
+ - [What's new in 1.7.1](#whats-new-in-171)
46
+ - [What's new in 1.7.0](#whats-new-in-170)
47
+ - [What's new in 1.6.0](#whats-new-in-160)
48
+ - [What's new in 1.4.0](#whats-new-in-140)
49
+ - [What's new in 1.3.0](#whats-new-in-130)
50
+ - [What's new in 1.2.1](#whats-new-in-121)
51
+ - [What's new in 1.2.0](#whats-new-in-120)
52
+ - [How it works](#how-it-works)
53
+ - [Installation](#installation)
54
+ - [Configuration — `kirigami.yaml`](#configuration--kirigamiyaml)
55
+ - [`kirigami` block](#kirigami-block)
56
+ - [`seo` block](#seo-block)
57
+ - [`prepros` block](#prepros-block)
58
+ - [`image` block](#image-block)
59
+ - [`plugins` block](#plugins-block)
60
+ - [`esbuild` / `sass` blocks](#esbuild--sass-blocks)
61
+ - [`export` block](#export-block)
62
+ - [`scripts` block](#scripts-block)
63
+ - [`tasks` block](#tasks-block)
64
+ - [Writing pages](#writing-pages)
65
+ - [PHPDOC header](#phpdoc-header)
66
+ - [Auto-loading data files](#auto-loading-data-files)
67
+ - [`@content`, `@indent`, and `@type`](#content-indent-and-type)
68
+ - [Built-in tags](#built-in-tags)
69
+ - [JavaScript API](#javascript-api)
70
+ - [`render(file?, phpIncludes?)`](#renderfile-phpincludes)
71
+ - [`sitemap()`](#sitemap)
72
+ - [`runenv(script, paths?, ...args)`](#runenvscript-paths-args)
73
+ - [`runPluginScript(script, pluginRoot, paths?, ...args)`](#runpluginscriptscript-pluginroot-paths-args)
74
+ - [`mountPath(localPath, virtualDir?, php?)`](#mountpathlocalpath-virtualdir-php)
75
+ - [`processImages(jobs)`](#processimagesjobs)
76
+ - [`resetRuntime()`](#resetruntime)
77
+ - [TypeScript declarations](#typescript-declarations)
78
+ - [PHP classes reference](#php-classes-reference)
79
+ - [PREPROS](#prepros)
80
+ - [MD](#md)
81
+ - [HTML](#html)
82
+ - [YAML](#yaml)
83
+ - [SCHEMA](#schema)
84
+ - [LD](#ld)
85
+ - [META](#meta)
86
+ - [CACHE](#cache)
87
+ - [IMG](#img)
88
+ - [FS](#fs)
89
+ - [STR](#str)
90
+ - [ARR](#arr)
91
+ - [CURL](#curl)
92
+ - [SCRAPER](#scraper)
93
+ - [OBF](#obf)
94
+ - [STD](#std)
95
+ - [Unicode normalization](#unicode-normalization)
96
+ - [Procedural shortcuts (aliases)](#procedural-shortcuts-aliases)
97
+ - [Plugin system](#plugin-system)
98
+ - [PREPROS tags](#prepros-tags)
99
+ - [PREPROS hooks](#prepros-hooks)
100
+ - [MD plugins](#md-plugins)
101
+ - [Built-in plugins](#built-in-plugins)
102
+ - [Extending the `<markdown>` tag](#extending-the-markdown-tag)
103
+ - [Requirements](#requirements)
104
+ - [License](#license)
105
+
106
+ ---
107
+
108
+ ## What's new in 3.0.0
109
+
110
+ This release switches `YAML::` to the native YAML extension, `MD::` to native mdhtml, `SCHEMA` to native jsonk, and `Normalizer` to native norm. It also includes page types and request lifecycle hooks.
111
+
112
+ PHP data files use the native `yaml` extension backed by LibYAML. Its YAML 1.1 implicit booleans include unquoted `y`, `n`, `yes`, `no`, `on`, `off`, `true`, and `false`, including mapping keys. Quote these words when you mean strings (for example, `"NO": Norway`). `YAML::parse()` / `parseFile()` / `loadFile()` preserve the wrapper’s array/object choice; native `yaml_parse()` / `yaml_parse_file()` have their own extension signatures. `yaml_load_file()` remains a wrapper alias. The project’s `kirigami.yaml` is parsed separately in Node through `struct-walker` and `js-yaml`.
113
+
114
+ `MD::` delegates to the native `mdhtml` extension (cmark-gfm). Footnotes now use `<section class="footnotes" data-footnotes>` instead of the old `<div class="footnotes">`; target `.footnotes` rather than a specific container tag in custom CSS.
115
+
116
+ `SCHEMA` validates through the native `jsonk` extension (draft 2020-12), keeping its API and the `"path: message"` error format. It now also supports `if`/`then`/`else`, `contains`, `propertyNames`, `dependentRequired`/`dependentSchemas`, `prefixItems`, and `$ref` to absolute or `$id`-relative URLs (fetched over the network). Error messages use jsonk's wording, and an `additionalProperties: false` violation is reported on the parent object instead of the extra property. The previous pure-PHP validator stays available as `SCHEMA_LEGACY`.
117
+
118
+ `Normalizer` now comes from the native `norm` extension (utf8proc) instead of the bundled pure-PHP polyfill, which stays available as `NORMALIZER_LEGACY`.
119
+
120
+ **Breaking: the `seo.jsonld` sub-block is merged into `seo:`.** META and LD now read one set of keys, so the site description, keywords, image, language and person are declared once. JSON-LD is injected whenever the `seo:` block exists; `seo.jsonld` is only an on/off switch (default `true`). To migrate, move the keys of `seo.jsonld: {…}` up into `seo:` (`jsonld.auto: false` becomes `jsonld: false`) and rename `seo.language` to `seo.lang`. `kiri` rejects the old shapes with a message saying so. Sites with `seo: {}` and no `jsonld` now get JSON-LD too; add `jsonld: false` to keep them without it.
121
+
122
+ ```yaml
123
+ # before # after
124
+ seo: seo:
125
+ language: fr-CA lang: fr-CA
126
+ jsonld: type: ProfessionalService
127
+ type: ProfessionalService logo: images/logo.png
128
+ logo: images/logo.png
129
+ ```
130
+
131
+ ---
132
+
133
+ ## What's new in 2.0.0
134
+
135
+ - **Breaking: `meta:` and `jsonld:` merged into one top-level `seo:` block.**
136
+ The two used to be independent siblings of `kirigami:` that happened to
137
+ share fallback data; they're now one block, one mental model for a
138
+ project's whole SEO/social surface — `META`'s own keys live directly under
139
+ `seo:`, and `jsonld` is nested inside it as its own sub-block:
140
+
141
+ ```yaml
142
+ # before (1.x)
143
+ meta:
144
+ favicon: favicon.png
145
+ jsonld: {}
146
+
147
+ # after (2.0.0)
148
+ seo:
149
+ favicon: favicon.png
150
+ jsonld: {}
151
+ ```
152
+
153
+ The two stay **independently toggled** exactly as before — a project can
154
+ have META's tags without JSON-LD, or vice versa; `seo: { jsonld: false }`
155
+ (or `{ auto: false }`) stops just the JSON-LD injection, `seo: false` (or
156
+ `{ auto: false }` at the top level) stops just META's. Every fallback chain
157
+ (a page's PHPDOC → the block → the loose `kirigami:` keys) is unchanged,
158
+ including `jsonld`'s own keys still feeding META's defaults (`jsonld.image`,
159
+ `jsonld.lang`, `jsonld.person`, …) — only *where the two blocks live* in
160
+ `kirigami.yaml` changed, not how resolution works. **Migration**: rename
161
+ `meta:` to `seo:` and move the `jsonld:` block's content under it as
162
+ `seo.jsonld:`. See [`seo` block](#seo-block) / [`meta` config](#meta-config)
163
+ / [`jsonld` config](#jsonld-config).
164
+
165
+ ---
166
+
167
+ ## What's new in 1.9.3
168
+
169
+ - Dependency bump to `@kirigami/struct-walker` 1.0.5; `homepage` + README
170
+ pointed at the site (metadata only).
171
+
172
+ ---
173
+
174
+ ## What's new in 1.9.2
175
+
176
+ - **Fixed a real Markdown bug**: a list item's source line count was 1:1
177
+ with `<li>` count, so an indented continuation line with no marker of its
178
+ own (a soft-wrapped `- **foo** text\n more text`) fell outside the
179
+ block-matching regex entirely — the list closed after the first line, the
180
+ continuation resurfaced as a stray flat `<p>`, and a new list reopened for
181
+ the next marker line. Fixed by widening the block regex to also accept a
182
+ marker-less indented line and, in the per-line loop, appending it to the
183
+ previous item instead of dropping it.
184
+
185
+ ---
186
+
187
+ ## What's new in 1.9.1
188
+
189
+ - **`{% img-asset %}` no longer crashes the build on an unresolvable path.**
190
+ `IMG::asset()`'s exception is now caught and turned into an HTML comment,
191
+ matching `codepen`/`checklist`'s own missing-argument behavior instead of
192
+ aborting the whole render. This also makes it safe to *document* the tag —
193
+ a literal `` `{% img-asset path … %}` `` written as prose inside a code
194
+ span still runs the plugin (code-span protection only swaps the *displayed*
195
+ output back to the literal text; the callback itself always executes), so
196
+ a placeholder path used to throw "Invalid image file." and fail the build.
197
+
198
+ ---
199
+
200
+ ## What's new in 1.9.0
201
+
202
+ - **`{% youtube %}` removed** — moved to
203
+ [`@kirigami/plugin-embed`](https://www.npmjs.com/package/@kirigami/plugin-embed),
204
+ which replaces the old plain-iframe output with a real oEmbed-backed card
205
+ (cover thumbnail, title, play button — no network call until the visitor
206
+ actually clicks play). If a project used the built-in `{% youtube %}`,
207
+ install the plugin; without it, the tag now falls through unresolved
208
+ (`{% youtube ID %}` printed as-is) rather than rendering an iframe.
209
+ `codepen`/`checklist`/`callout` are unaffected.
210
+
211
+ ---
212
+
213
+ ## What's new in 1.8.0
214
+
215
+ - **`{% img-asset %}` — a new built-in Markdown plugin.** Same pipeline as the
216
+ `<img asset>` HTML tag (`IMG::asset()`: resize, cache, publish under
217
+ `image.dest`), usable straight from Markdown text:
218
+
219
+ ```
220
+ {% img-asset photo.jpg %}
221
+ {% img-asset photo.jpg 800 %}
222
+ {% img-asset photo.jpg 800 600 %}
223
+ {% img-asset photo.jpg 800 600 cover %}
224
+ ```
225
+
226
+ Positional args: source path (relative to `image.source`), width, height,
227
+ and the literal `cover` keyword. Registered in `md.plugins.php` alongside
228
+ `codepen`/`youtube`/`checklist`/`callout` — available out of the box, drop
229
+ it with `MD::unregisterPlugin('img-asset')` if you don't want it.
230
+
231
+ ---
232
+
233
+ ## What's new in 1.7.2
234
+
235
+ - **Cleaner formatted output around highlighted code.** The de-indent script
236
+ `PREPROS::injectHead()` adds when `prepros.format` is on now flattens the
237
+ `<pre><code>` indentation `HTML::format()` writes for *every* block, including
238
+ ones a build-time highlighter has wrapped in `<span>`s. It works on
239
+ `innerHTML` line by line and removes only the shared leading run (relative
240
+ indentation is kept). This lets [`@kirigami/plugin-highlight`](https://www.npmjs.com/package/@kirigami/plugin-highlight)
241
+ 1.7.2+ re-indent its markup to line up with the rest of the document instead
242
+ of leaving it flush-left — the served HTML stays consistently indented, the
243
+ rendered code is still de-indented before the first paint.
244
+
245
+ - **`<markdown prose>` wraps in `.prose`.** With the `prose` attribute the
246
+ built-in tag emits `<div class="prose"> … </div>` so long-form Markdown picks
247
+ up `@kirigami/canva`'s `styles/prose` typography with no extra markup. Opt-in
248
+ (a bare `<markdown>` is unchanged); `class` / `id` on the tag land on the
249
+ wrapper.
250
+
251
+ ---
252
+
253
+ ## What's new in 1.7.1
254
+
255
+ - **No side effects on import.** `kirigami.yaml` is now loaded on first use
256
+ (`render()` / `sitemap()` / `runenv()` / `processImages()`), not while the
257
+ module is being imported. `import '@kirigami/php-prepros'` from a directory
258
+ with no project no longer throws — which is what made `kiri build --help` /
259
+ `kiri export --help` / `kiri run --help` crash instead of printing their help.
260
+
261
+ ---
262
+
263
+ ## What's new in 1.7.0
264
+
265
+ - **`META`** class — a `<head>` SEO / social metadata generator, the companion
266
+ to [`LD`](#ld). Builds the standard tags — `<title>`, `description`,
267
+ `keywords`, `robots`, `language`, `generator`, `author`, Open Graph, Twitter
268
+ Card, `<link rel="canonical">`, favicon / apple-touch-icon / humans — from
269
+ each page's PHPDOC, the top-level `meta:` block, and the loose `kirigami:` /
270
+ `jsonld:` keys `LD` already reads. It emits only what it can resolve, and
271
+ leaves any tag the layout already hand-writes untouched.
272
+
273
+ - **Opt-in**: a top-level `meta:` block (empty `meta: {}` is enough) switches
274
+ on automatic injection into every page's `<head>`. `meta: false` (or
275
+ `{ auto: false }`) keeps the config but stops the injection.
276
+ - Per-page PHPDOC: `@meta false` (skip), `@meta_title`, `@meta_description`
277
+ (falls back to `@description` / `@abstract` / `@excerpt`), `@meta_keywords`,
278
+ `@meta_image`, `@meta_robots`, `@meta_type`, `@canonical`.
279
+ - Manual builders — always emitted, still de-duplicated: `META::tag()`,
280
+ `META::link()`, `META::raw()`, `META::tags()`. Procedural aliases:
281
+ `meta_tag()`, `meta_link()`, `meta_raw()`, `meta_tags()`.
282
+
283
+ Full key reference: [`META` → `meta` config](#meta-config).
284
+
285
+ ---
286
+
287
+ ## What's new in 1.6.0
288
+
289
+ - **Managed `<head>` (`prepros.head`).** Every rendered page's `<head>` is now
290
+ auto-wired: a tiny theme/FOUC guard as the first child (adds the `js` class,
291
+ applies the stored `data-theme` before first paint), a
292
+ `<link rel="stylesheet">` for every `sass` task output, and a `<script>` (no
293
+ `defer`, just before `</body>`) for every `esbuild` task output — each with a
294
+ per-page relative path and a `?<timestamp>` cache-bust. A file already
295
+ referenced in the page is left alone, so you can still hand-place one. Turn it
296
+ off with `prepros: { head: false }`, or `head: false` on a single sass/esbuild
297
+ task. A template's `header.php` no longer wires assets at all.
298
+
299
+ - **`HTML::format()` indents `<pre><code>`.** A fenced code block's lines are
300
+ shifted to the block's nesting depth so the HTML source stays readable
301
+ (relative indentation preserved). The exact leading run is stripped again
302
+ before it's shown, by a small de-indent script `prepros.head` injects before
303
+ `</body>` (only when `format` is on). Since 1.7.2 the script works on
304
+ `innerHTML` line by line, so it also flattens blocks a build-time highlighter
305
+ has wrapped in `<span>`s. A bare `<pre>` and `<textarea>` are still emitted
306
+ byte-for-byte.
307
+
308
+ ---
309
+
310
+ ## What's new in 1.4.0
311
+
312
+ A round of fixes to the rough edges that showed up building a full site from
313
+ scratch — mostly developer-experience, all backward compatible.
314
+
315
+ - **`HTML::format()` keeps `<pre>` / `<textarea>` verbatim.** Their line breaks,
316
+ indentation and blank lines are no longer collapsed, so a fenced code block
317
+ survives the formatter intact — `format: true` and Markdown code blocks now
318
+ coexist. (1.6.0 refines this: a `<pre><code>` block is re-indented to its
319
+ nesting depth and de-indented again before display.)
320
+ - **The default Markdown plugins load out of the box.** `{% callout %}`,
321
+ `{% youtube %}`, `{% codepen %}` and `{% checklist %}` are registered
322
+ automatically (`md.plugins.php` is auto-included from `MD`), as the docs always
323
+ said. Drop one with `MD::unregisterPlugin('name')` or shadow it with your own
324
+ `MD::registerPlugin()`.
325
+ - **Build errors you can actually read.** A fatal in a template (a bad call, a
326
+ `null` argument, a `TypeError`…) comes back as a structured failure with the
327
+ message, the offending page and the `file:line` — never a bare
328
+ `Error: undefined`. The `try/catch` now covers `Throwable`, not just
329
+ `Exception`. PHP warnings and notices no longer sink an otherwise-clean build:
330
+ they surface as `warnings` on the result. `kiri` prints the message, the page,
331
+ and the tail of the PHP stderr/debug output on failure.
332
+ - **PHPDOC parsing.** A tag value may now wrap onto the following *indented*
333
+ continuation lines instead of being silently truncated at the first line. And
334
+ an `@word` written in the block's prose is ignored rather than overwriting a
335
+ real tag — only lines that *start* with `@` open a tag.
336
+ - **`FS::getBreadcrumb()` / `FS::getChildren()`** are anchored on the page being
337
+ rendered (`PREPROS::$file`), so they return the right trail / child list when
338
+ called from a layout include, a partial, or a helper function — not only
339
+ straight from the template. Pass an explicit path to override.
340
+ - **`{% tag %}` inside a code span or code block stays literal** (`` `{% badge %}` ``
341
+ renders as text) instead of being expanded — or leaking an unrestored
342
+ placeholder.
343
+ - **`IMG` never upscales.** A requested size larger than the source is clamped
344
+ down to the source instead of throwing an opaque encoder error (the AVIF
345
+ encoder in particular).
346
+ - **Build-time tokens expand at render time.** `###YEAR###`, `###TIMESTAMP###`
347
+ and `###TODAY###` are substituted when each page is generated, so
348
+ `kiri build` / `kiri watch` previews show real values, not the literal token
349
+ (previously only `kiri export` replaced them).
350
+ - **`page_info` hook robustness.** The first built-in callback accepts either the
351
+ `[$file, $info]` pair the hook fires with or the bare `$info` object a later
352
+ callback receives, so a custom `page_info` hook can't fatal on the argument
353
+ shape. See [PREPROS hooks](#prepros-hooks).
354
+
355
+ ---
356
+
357
+ ## What's new in 1.3.0
358
+
359
+ - **`LD`** class — a schema.org JSON-LD generator. Collects structured-data
360
+ nodes during a render and emits them as a single
361
+ `<script type="application/ld+json">` `@graph` in every page's `<head>`.
362
+ - Automatic injection is **opt-in**: add a top-level `jsonld:` block to
363
+ `kirigami.yaml` (even empty, `jsonld: {}`) and an `Organization` (+ `Person`, `WebSite`,
364
+ `WebPage`, `BreadcrumbList`) graph is derived from that block plus the loose
365
+ keys projects already carry (`person`, `jobtitle`, `email`, `area`,
366
+ `knowsabout`, `keywords`, `facebook`, …). No `jsonld:` block → nothing is
367
+ injected.
368
+ - Turn it back off with `jsonld: false` / `jsonld: { auto: false }`, or per
369
+ page with `@ld false`; per-page `@ld_type` / `@ld_title` / `@ld_image` / …
370
+ tags feed the page node, and a `BreadcrumbList` is built from the
371
+ `_index.php` ancestor trail with no opt-in.
372
+ - Explicit builders for everything else: `LD::add()`, `LD::article()`,
373
+ `LD::faqPage()`, `LD::breadcrumb()`, `LD::ref()`, and every schema.org type
374
+ via `LD::typeName([...])`. Procedural aliases: `ld_add()`, `ld_organization()`,
375
+ `ld_script()`, …
376
+ - A page that already hand-writes an `application/ld+json` script is left
377
+ untouched.
378
+
379
+ ---
380
+
381
+ ## What's new in 1.2.1
382
+
383
+ - **`processImages()`** JS export — batch resize / palette-extraction through the
384
+ `IMG` class (`src/imagebatch.php`). `@kirigami/kirigami`'s `sass` task now uses
385
+ it for `img-asset()` / `colors()`, so the whole toolchain is free of a native
386
+ image dependency (`sharp` is gone).
387
+ - **`IMG::save()`** takes an optional `$quality` (0-100) for jpg / webp / avif;
388
+ `null` keeps the per-format default (82).
389
+
390
+ ---
391
+
392
+ ## What's new in 1.2.0
393
+
394
+ - **`SCHEMA`** class — a pure-PHP, dependency-free JSON Schema validator
395
+ (Draft-7 style, Ajv-like API: `isValid()` / `validate()` / `getErrors()`).
396
+ - **`IMG::asset()` / `IMG::palette()`** — static helpers powering kirigami-core's
397
+ `img-asset()` and `colors()` Sass functions: on-demand resize/convert of a
398
+ source image, and cached representative-colour extraction.
399
+ - **`<img asset="…">` tag** — the HTML-side entry point of the image
400
+ autogenerator, same parameters as `IMG::asset()` (see [Built-in tags](#built-in-tags)).
401
+ - **`IMG` now handles vector and exotic formats** — SVG, EPS, AI, PDF (rasterized
402
+ via Imagick), plus HEIC / TIFF / BMP, on top of GD's JPEG / PNG / GIF / WebP /
403
+ AVIF.
404
+ - **`MD` emoji shortcodes** — `:rocket:` → 🚀 from a large built-in map, extend­able
405
+ with `MD::registerEmoji()`.
406
+ - **`MD` footnotes and definition lists** — `[^1]` / `[^1]: …`, and `Term` / `: …`.
407
+ - **`MD` inline HTML is now sanitized** against a tag/attribute allowlist rather
408
+ than passed through verbatim.
409
+ - **`STR::normalize()`** — Unicode NFD + combining-mark stripping;
410
+ **`STR::slug($str, $sep = '')`** now takes a separator (pass `'-'` for a
411
+ hyphenated slug).
412
+ - **Bundled `Normalizer` polyfill** — `ext-intl` isn't in the WASM build, so a
413
+ polyfill keeps `Normalizer::normalize()` (and `STR::normalize()` / `slug()`)
414
+ working.
415
+
416
+ Earlier, in 1.1.x: `PREPROS::mount()` + the `mountPath()` / `runenv()` JS
417
+ exports, the `SCRAPER` and `CURL` and `ARR` classes, `YAML::loadFile()`, the
418
+ `STR::is_url()` / `html_entities_decode()` / `shorthash()` / `slug()` helpers,
419
+ the `{% youtube %}` / `{% codepen %}` / `{% checklist %}` MD plugins, and the
420
+ `@content` / `@indent` PHPDOC annotations.
421
+
422
+ ---
423
+
424
+ ## How it works
425
+
426
+ `@kirigami/php-prepros` runs your PHP source files inside a **WebAssembly PHP 8.x runtime** ([`@kirigami/php-wasm`](https://www.npmjs.com/package/@kirigami/php-wasm)), entirely in Node.js — no PHP installation required on the host machine.
427
+
428
+ The lifecycle of a page build looks like this:
429
+
430
+ ```
431
+ _index.php ──▶ PHP (wasm) ──▶ processTags() ──▶ HTML::format() ──▶ index.html
432
+ │
433
+ ├── before.php (optional layout header)
434
+ ├── after.php (optional layout footer)
435
+ └── PHPDOC annotations resolved (yaml / json / md / url)
436
+ ```
437
+
438
+ Files are mounted into the WebAssembly virtual filesystem on demand. Only `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt` and any extra extensions listed in `prepros.mountext` are mounted automatically, keeping memory usage low. Anything else can be mounted on demand with [`PREPROS::mount()`](#preprosmountstringarray-patterns).
439
+
440
+ ---
441
+
442
+ ## Installation
443
+
444
+ ```bash
445
+ npm install @kirigami/php-prepros
446
+ ```
447
+
448
+ ---
449
+
450
+ ## Configuration — `kirigami.yaml`
451
+
452
+ Every project **must** have a `kirigami.yaml` at its root. The preprocessor reads it at startup and throws if it is absent or invalid.
453
+
454
+ `@kirigami/php-prepros` consumes project data, SEO, preprocessing, image settings, and task metadata for managed head injection. The core engine owns plugin loading, task orchestration, export, and full schema validation. Direct use of this package is not a substitute for core configuration validation. All settings share `kirigami.yaml`; its schema is [`kirigami.schema.json`](../kirigami/kirigami.schema.json).
455
+
456
+ ```yaml
457
+ # yaml-language-server: $schema=https://cdn.jsdelivr.net/gh/php-kirigami/kirigami@main/packages/kirigami/kirigami.schema.json
458
+ ```
459
+
460
+ ```yaml
461
+ kirigami:
462
+ # ── Required ──────────────────────────────────────────────────────────
463
+ project: My Website # Site name. Printed in the CLI banner, exposed as $project.
464
+ baseurl: https://example.com # Deployed root URL, no trailing slash. Used for sitemap.xml.
465
+ root: src # Source directory containing your _*.php pages.
466
+
467
+ # ── Optional ────────────────────────────────────────────────────────
468
+ banner: assets/banner.txt # Text file stamped as a license banner on exported files.
469
+
470
+ # ── Arbitrary project data ──────────────────────────────────────────
471
+ # Everything else under `kirigami:` is free-form. The whole block is
472
+ # extracted as PHP variables and made available in every page, in
473
+ # before.php/after.php, and anywhere PREPROS::$config->data is read.
474
+ author: Jane Doe
475
+ email: hello@example.com
476
+ gtag: G-XXXXXXXXXX
477
+ description: A short description of the site, useful for <meta name="description">.
478
+ keywords:
479
+ - keyword one
480
+ - keyword two
481
+
482
+ seo: # Presence turns on the META tags and LD JSON-LD (`seo: {}` is enough).
483
+ type: Organization # JSON-LD main entity; `jsonld: false` turns the JSON-LD off.
484
+ logo: assets/logo.png
485
+
486
+ prepros:
487
+ before: _layouts/header.php # Included before every page body.
488
+ after: _layouts/footer.php # Included after every page body.
489
+ format: true # Pretty-print the HTML output (default: false).
490
+ network: true # Allow HTTP fetches in PHPDOC @tag annotations / CURL / SCRAPER.
491
+ mountext: # Extra file extensions to auto-mount into the wasm fs,
492
+ - .svg # in addition to the defaults (.php .json .yaml .yml .md .db .txt).
493
+ - .webp
494
+ includes: # PHP files auto-included once, before any page renders.
495
+ - _lib/functions.php
496
+ types: # Named page types — opt in per page with @type <name>.
497
+ article:
498
+ before: _layouts/types/article.header.php
499
+ after: _layouts/types/article.footer.php
500
+
501
+ image: # Image autogenerator — powers IMG::asset() / IMG::palette().
502
+ format: webp # webp | avif (default: webp)
503
+ source: assets/images # Source folder, relative to cwd() (default: assets/images)
504
+ dest: images # Output folder, relative to kirigami.root (default: images)
505
+
506
+ plugins:
507
+ - name: "@kirigami/plugin-highlight"
508
+ active: true
509
+ options:
510
+ theme: auto
511
+
512
+ esbuild:
513
+ # minify: false
514
+
515
+ sass:
516
+ style: expanded
517
+
518
+ export:
519
+ path: dist
520
+ ignore: ["*.psd", "notes/"]
521
+
522
+ scripts:
523
+ - name: convert-images
524
+ mount: ["assets/images/**/*.jpg"]
525
+ trigger: before-build # before-build | before-export | after-export
526
+
527
+ tasks:
528
+ - name: js-core
529
+ type: esbuild
530
+ entry: scripts/kirigami.core.js
531
+
532
+ - name: scss-core
533
+ type: sass
534
+ entry: styles/kirigami.core.scss
535
+ ```
536
+
537
+ ### `kirigami` block
538
+
539
+ Core project settings. **Read by `php-prepros`.** The entire block is extracted into PHP variables and made available in every page template, `before.php`, `after.php`, and `prepros.includes` files — `$project`, `$author`, `$gtag`, etc. are available with no further setup, and also as `PREPROS::$config->data`.
540
+
541
+ | Key | Required | Description |
542
+ |-----|----------|--------------|
543
+ | `project` | ✅ | Human-readable site name. Exposed as `$project`. |
544
+ | `baseurl` | ✅ | Root URL of the deployed site, no trailing slash. Used to build absolute `<loc>` entries in `sitemap.xml`; exposed as `$baseurl`. |
545
+ | `root` | ✅ | Path (relative to the project root) to the directory containing your `_*.php` source pages. Build fails immediately if missing or if the path doesn't exist. |
546
+ | `banner` | — | Path (relative to the project root) to a text file stamped as a license/copyright banner on exported `.js`/`.css`/`.html` files during `kiri export`. May contain the `###DATE###` token, replaced with today's date. Falls back to an auto-generated banner. |
547
+ | *anything else* | — | Free-form key/value pairs (strings, numbers, booleans, lists, nested maps — anything valid YAML). Every key is extracted as a PHP variable (`$author`, `$gtag`, …). Use this for contact info, social links, analytics IDs, SEO keywords, or any project data you want available everywhere. When the top-level `seo` block is present, [`LD`](#ld) also reads some of these by convention: `person`, `jobtitle`, `email`, `area`, `knowsabout`, `keywords`, and social-network URL keys (`facebook`, `instagram`, …). |
548
+
549
+ ### `seo` block
550
+
551
+ Top-level, optional. The SEO surface: one set of keys feeds both the
552
+ [`META`](#meta) tags (the standard SEO / social `<meta>` and `<link>` tags) and
553
+ the [`LD`](#ld) schema.org JSON-LD graph, and its **presence** switches both on
554
+ for every page's `<head>`. An empty `seo: {}` is enough; everything is derived
555
+ from the `kirigami` block and each page's PHPDOC (`@title`, `@description` /
556
+ `@abstract`, `@keywords`, `@image`, `@robots`, `@og_type`, `@canonical`). A
557
+ tag or script the layout already hand-writes is left untouched.
558
+
559
+ - `auto: false` stops META's tags, `jsonld: false` stops the JSON-LD; the
560
+ config values stay available to `META::tags()` / `LD::script()`.
561
+ - `seo: false` keeps nothing on; no block at all means nothing is injected
562
+ (explicit `META::tag()` / `LD::add()` calls still emit).
563
+
564
+ Full key reference: [`seo` config](#seo-config). Per-page tags:
565
+ [`@meta_*`](#meta) and [`@ld_*`](#ld).
566
+
567
+ ### `prepros` block
568
+
569
+ Global `before` and `after` files are optional and default to `null`; an empty `prepros: {}` renders without a layout. When provided, these paths must refer to existing files. PHP warnings are logged to stderr and returned as diagnostics, without being inserted into generated HTML.
570
+
571
+ Options for the PHP → HTML compiler. **Read by `php-prepros`.** Declaring this block (even empty) also makes `kiri` prepend a forced `prepros` task on every build/export/watch.
572
+
573
+ | Key | Type | Default | Description |
574
+ |-----|------|---------|--------------|
575
+ | `before` | `string` | — | Path (relative to `kirigami.root`) to a PHP file included **before** every page's body. Typically your `<head>`/layout opening. |
576
+ | `after` | `string` | — | Path (relative to `kirigami.root`) to a PHP file included **after** every page's body. Typically your layout closing. |
577
+ | `format` | `bool` | `false` | Pretty-print the compiled HTML via [`HTML::format()`](#html) before writing it to disk. |
578
+ | `head` | `bool` | `true` | Auto-wire each page's `<head>`: a theme/FOUC guard as the first child, a `<link rel="stylesheet">` per `sass` task output, and a `<script>` (no `defer`, before `</body>`) per `esbuild` task output — each with a per-page relative path and a `?<timestamp>` cache-bust. A file already referenced in the page is skipped. Set `false` to disable, or `head: false` on a single `sass`/`esbuild` task to skip just its tag. |
579
+ | `network` | `bool` | `false` | Enables outbound HTTP(S) inside the WASM PHP runtime. Required for PHPDOC `@tag https://…` annotations that fetch remote `.yaml`/`.json`/`.md` data (see [Auto-loading data files](#auto-loading-data-files)), and for the `CURL` / `SCRAPER` classes. |
580
+ | `mountext` | `string[]` | `[]` | Extra file extensions to mount automatically into the virtual filesystem alongside the built-in `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`. Use this for assets your PHP code reads directly (e.g. `.svg`, `.webp`). Files with extensions not in this set are skipped during mounting — mount them on demand with [`PREPROS::mount()`](#preprosmountstringarray-patterns) instead. |
581
+ | `includes` | `string[]` | `[]` | PHP files (relative to `kirigami.root`) `include_once`'d once, right after config is loaded — before any page renders. The natural place to `PREPROS::registerTag()`, `PREPROS::registerHook()`, or `MD::registerPlugin()`. |
582
+ | `types` | `object` | `{}` | Named page types. A page opts in with `@type <name>` in its PHPDOC header; the matching entry's `before`/`after` (each `string`, relative to `kirigami.root`, both optional) wrap the page body **one level inside** the global `before`/`after` — render order is global before → type before → body → type after → global after. A page with no `@type`, or naming a type absent here, renders with just the global wrap. See [`@type`](#content-indent-and-type). |
583
+
584
+ ### `image` block
585
+
586
+ Options for the image autogenerator. **Read by `php-prepros`** — these are what [`IMG::asset()` / `IMG::palette()`](#img), the [`<img asset>` tag](#img-asset), and kirigami-core's `img-asset()` / `colors()` Sass functions all resolve against. Optional; the defaults below apply even when the block is absent.
587
+
588
+ | Key | Type | Default | Description |
589
+ |-----|------|---------|--------------|
590
+ | `format` | `string` | `webp` | Output format for generated images: `webp` or `avif`. |
591
+ | `source` | `string` | `assets/images` | Folder holding the source images, relative to `cwd()`. |
592
+ | `dest` | `string` | `images` | Destination folder for generated images, relative to `kirigami.root`. |
593
+
594
+ ### `plugins` block
595
+
596
+ List of Kirigami plugins. **Consumed by the `kiri` CLI** (see [`@kirigami/sdk`](https://www.npmjs.com/package/@kirigami/sdk)), not by `php-prepros` directly.
597
+
598
+ | Key | Required | Description |
599
+ |-----|----------|--------------|
600
+ | `name` | ✅ | Plugin package name. Must match `@kirigami/plugin-*`, `<scope>/kirigami-plugin-*`, or `kirigami-plugin-*`. |
601
+ | `active` | ✅ | Whether the plugin is loaded. |
602
+ | `options` | — | Free-form object passed to the plugin; its shape depends on the plugin. |
603
+
604
+ ### `esbuild` / `sass` blocks
605
+
606
+ Free-form objects. **Consumed by the `kiri` CLI.** There is no fixed key set: whatever you put here is spread straight into the underlying library call for every matching task, *after* Kirigami's own defaults — so it can also override them (`minify`, `target`, `style: "compressed"`, source maps, …). Refer to esbuild's [`BuildOptions`](https://esbuild.github.io/api/#build-api) and Dart Sass's [`Options`](https://sass-lang.com/documentation/js-api/interfaces/options/) for what's accepted. Writing the key with nothing under it parses to `null` in YAML, equivalent to omitting the block.
607
+
608
+ `sass:` additionally recognizes two keys that are **not** passed to Dart Sass:
609
+
610
+ | Key | Type | Description |
611
+ |-----|------|--------------|
612
+ | `before` | `string` / `string[]` | Extra `.scss` files compiled **before** the task entry (paths relative to `cwd()`). |
613
+ | `after` | `string` / `string[]` | Extra `.scss` files compiled **after** the task entry. |
614
+
615
+ ### `export` block
616
+
617
+ Options for `kiri export`. **Consumed by the `kiri` CLI.** Optional.
618
+
619
+ | Key | Type | Default | Description |
620
+ |-----|------|---------|--------------|
621
+ | `path` | `string` | `dist` | Output directory for `kiri export`, relative to the project root. |
622
+ | `ignore` | `string[]` | `[]` | Extra gitignore-style patterns excluded from the export copy, on top of Kirigami's built-in exclusions. |
623
+
624
+ ### `scripts` block
625
+
626
+ Named PHP scripts. **Consumed by the `kiri` CLI**, which runs each `scripts/<name>.php` through [`runenv()`](#runenvscript-paths-args) — so the full `php-prepros` class library is available and `kirigami.yaml`'s `kirigami` block is exposed as `PREPROS::$config->data`.
627
+
628
+ | Key | Required | Description |
629
+ |-----|----------|--------------|
630
+ | `name` | ✅ | Must match an existing `scripts/<name>.php` file. Run with `kiri run <name> [args...]`; extra CLI arguments are forwarded as `$argv` entries. |
631
+ | `mount` | — | Glob patterns (relative to the project root) of extra local files to mount into the sandbox before the script runs. |
632
+ | `trigger` | — | Fire the script automatically: `before-build` (start of `build` and `export`), `before-export` (very start of `export`), or `after-export` (once `export` has finished). |
633
+
634
+ ### `tasks` block
635
+
636
+ Ordered list of build tasks, run in array order. **Consumed by the `kiri` CLI**, on top of the implicit `prepros` task (added when the `prepros` block is present) and the implicit `dist` task (added during `kiri export`).
637
+
638
+ | `type` | Purpose | Required fields | Optional |
639
+ |--------|---------|-----------------|----------|
640
+ | `esbuild` | Bundle/minify a JS/TS entry. Build + watch. Output: `<entry>.min.js`. | `name`, `type`, `entry` | `force` |
641
+ | `sass` | Compile a `.scss`/`.sass` entry, minified with csso on export. Build + watch. Output: `<entry>.min.css`. | `name`, `type`, `entry` | `force` |
642
+ | `prepros` | Render pages + `sitemap.xml`. Watch only (runs on build/export only when forced/implicit). | `name`, `type` | `target`, `force` |
643
+ | `dist` | Copy `kirigami.root` into an output dir, stamping the banner. Forced/implicit only. | `name`, `type`, `path` | `ignore`, `force` |
644
+
645
+ ---
646
+
647
+ ## Writing pages
648
+
649
+ Source pages live in the directory pointed to by `kirigami.root`. The naming convention is straightforward: any file whose name starts with `_` and ends in `.php` is treated as a page source. The leading underscore is stripped in the output filename.
650
+
651
+ ```
652
+ src/
653
+ ├── _layouts/
654
+ ├── _lib/
655
+ ├── _index.php → src/index.html
656
+ ├── about/
657
+ │ └── _index.php → src/about/index.html
658
+ └── blog/
659
+ ├── _index.php → src/blog/index.html
660
+ └── _articles.yaml (data file, not compiled)
661
+ ```
662
+
663
+ Directories whose name starts with `_` (e.g. `_layouts/`, `_lib/`) are skipped entirely during directory-wide builds.
664
+
665
+ ### PHPDOC header
666
+
667
+ Every page starts with a PHP docblock that drives metadata and data loading:
668
+
669
+ ```php
670
+ <?php
671
+ /**
672
+ * @name about
673
+ * @title About us
674
+ * @abstract A short description of this page.
675
+ */
676
+ ?>
677
+ <section>
678
+ <h1><?php echo $title; ?></h1>
679
+ <p><?php echo $abstract; ?></p>
680
+ </section>
681
+ ```
682
+
683
+ All annotations are injected as PHP variables (`$name`, `$title`, `$abstract`, …). You can define any custom annotation you need.
684
+
685
+ Annotations are also available as variables in `before` and `after` PHP included files, so you can write proper metas in the HTML header.
686
+
687
+ Only lines whose first non-whitespace character (past the `*` gutter) is `@`
688
+ open an annotation — an `@word` written in the prose of the block is left alone.
689
+ A value can wrap onto the following **indented** continuation lines:
690
+
691
+ ```php
692
+ /**
693
+ * @title About us
694
+ * @description A longer blurb that does not fit comfortably
695
+ * on a single line and continues here.
696
+ */
697
+ ```
698
+
699
+ ### Auto-loading data files
700
+
701
+ When an annotation value looks like a filename (with a `.yaml`, `.yml`, `.json`, or `.md` extension), it is automatically parsed and injected as a structured variable instead of a plain string.
702
+
703
+ ```php
704
+ <?php
705
+ /**
706
+ * @name medias
707
+ * @articles _articles.yaml
708
+ */
709
+ ?>
710
+ <?php foreach ($articles as $article): ?>
711
+ <a href="<?php echo $article->lien; ?>">
712
+ <?php echo $article->titre; ?>
713
+ </a>
714
+ <?php endforeach; ?>
715
+ ```
716
+
717
+ | Extension | Parsed as |
718
+ |-----------|-----------|
719
+ | `.yaml` / `.yml` | `stdClass` object (or array of objects for sequences) |
720
+ | `.json` | Result of `json_decode()` |
721
+ | `.md` | HTML string via `MD::toHtml()` |
722
+
723
+ When `network: true` is set in `kirigami.yaml`, annotation values that start with `http://` or `https://` are fetched from the network and parsed the same way:
724
+
725
+ ```php
726
+ /**
727
+ * @posts https://api.example.com/posts.json
728
+ */
729
+ ```
730
+
731
+ ### `@content`, `@indent`, and `@type`
732
+
733
+ Three special annotation names change how a page's body is assembled:
734
+
735
+ - **`@content`** — if a `content` variable already resolves to a non-empty value (typically because it's a `.md`/`.yaml`/`.json` annotation that auto-loaded into HTML/data, see above), it is used **as-is** as the page body, and the PHP file itself is **not executed** for its output. This is handy for pages that are pure data/markdown wrapped by a shared layout.
736
+ - **`@indent`** — when set to a number, every line of the rendered body is prefixed with that many spaces before being wrapped by `before.php`/`after.php`. Useful for keeping generated HTML readable when a page is nested inside indented layout markup.
737
+ - **`@type`** — names an entry under [`prepros.types`](#prepros-block). If it matches, that entry's `before`/`after` wrap the (already-indented) body **one level inside** `before.php`/`after.php`: global before → type before → body → type after → global after. No match (missing annotation, or a name absent from `prepros.types`) leaves the page with just the global wrap — a page type is an extra layer, never a replacement for the site's real header/footer.
738
+
739
+ ```php
740
+ <?php
741
+ /**
742
+ * @name changelog
743
+ * @title Changelog
744
+ * @content _changelog.md
745
+ * @indent 4
746
+ * @type article
747
+ */
748
+ ```
749
+
750
+ ### Built-in tags
751
+
752
+ Two tags are registered out of the box (`prepros.plugins.php`) and processed
753
+ **after** the PHP runs, on the assembled HTML — no include or plugin needed.
754
+
755
+ #### `<markdown> … </markdown>`
756
+
757
+ Converts its inner content from Markdown to HTML, stripping the common leading
758
+ indentation first (via `STR::trimIndent()`) so you can indent it naturally inside
759
+ your template. All registered [MD plugins](#md-plugins) work inside it. See
760
+ [Extending the `<markdown>` tag](#extending-the-markdown-tag) to override it.
761
+
762
+ ```html
763
+ <section>
764
+ <markdown>
765
+ ## Who we are
766
+
767
+ We are a **student organization** from Québec.
768
+ </markdown>
769
+ </section>
770
+ ```
771
+
772
+ Add the `prose` attribute — `<markdown prose>` — to wrap the output in
773
+ `<div class="prose">`, so it picks up the long-form typography of
774
+ [`@kirigami/canva`'s `styles/prose`](https://www.npmjs.com/package/@kirigami/canva)
775
+ with no extra markup. Any `class` / `id` on the tag lands on that wrapper
776
+ (`<markdown prose class="lede" id="intro">` → `<div class="prose lede" id="intro">`).
777
+ A bare `<markdown>` emits just the converted HTML, as before.
778
+
779
+ #### `<img asset="…">`
780
+
781
+ The HTML-side entry point of the image autogenerator — the exact same feature as
782
+ the [`img-asset()` Sass function](https://www.npmjs.com/package/@kirigami/kirigami#sass-functions)
783
+ and [`IMG::asset()`](#img), with the same parameters. The tag calls `IMG::asset()`
784
+ under the hood, then swaps the `asset` attribute for the generated `src`.
785
+
786
+ ```html
787
+ <!-- in: resolves assets/images/hero.jpg through IMG::asset('hero.jpg', 800, 0, false) -->
788
+ <img asset="hero.jpg" width="800" alt="Our office" loading="lazy">
789
+ <!-- out: <img src="../images/hero-800w.webp" alt="Our office" loading="lazy"> -->
790
+ ```
791
+
792
+ | Attribute | Maps to `IMG::asset()` arg | Notes |
793
+ |-----------|---------------------------|-------|
794
+ | `asset` | `$path` | **Required.** Path relative to `image.source`. Missing/empty ⇒ the tag is left untouched. |
795
+ | `width` | `$width` | Optional, integer. Omitted ⇒ `0` (keep). |
796
+ | `height` | `$height` | Optional, integer. Omitted ⇒ `0` (keep). |
797
+ | `cover` | `$cover` | Boolean — **presence means `true`** (crop + fill). |
798
+ | *(any other)* | — | `alt`, `class`, `id`, `loading`, … are passed straight through onto the output `<img>`. |
799
+
800
+ `asset` / `width` / `height` / `cover` are consumed and removed; everything else
801
+ survives. The generated file lands in `image.dest` and is only (re)generated when
802
+ missing or older than the source — see [`IMG`](#img) for the naming convention.
803
+
804
+ > The Sass `img-asset()` / `colors()` functions, the `<img asset>` tag and
805
+ > `IMG::asset()` all run on the **same engine** — the `IMG` class (GD, with the
806
+ > Imagick fallback) in this package. `@kirigami/kirigami`'s `sass` task routes its
807
+ > image work here through [`processImages()`](#processimagesjobs), so there is no
808
+ > native image dependency in the toolchain.
809
+
810
+ ---
811
+
812
+ ## JavaScript API
813
+
814
+ ```js
815
+ import { render, sitemap, runenv, mountPath, processImages, resetRuntime } from '@kirigami/php-prepros';
816
+ ```
817
+
818
+ PHP operations are queued in call order, including mounts and result extraction.
819
+ `await resetRuntime()` waits for preceding PHP work, disposes the owned runtime
820
+ and its network proxy, and clears cached configuration and mounts. The next
821
+ operation initializes a fresh runtime from `kirigami.yaml`. Core
822
+ `Project.reload()` calls this and also clears the plugin PHP include list.
823
+ It does not clear persistent cache/cookie files on disk. This remains a
824
+ single-project API whose working directory must be set before import.
825
+
826
+ ### `render(file?, phpIncludes?)`
827
+
828
+ `phpIncludes` defaults to `[]`. The core collects it through `prepros:php`;
829
+ direct callers supply local PHP file paths (absolute or relative to the
830
+ working directory). Existing paths are mounted under `/plugins/` and included
831
+ before rendering; missing paths are silently skipped. Each render replaces
832
+ the runtime include list, which remains on its configuration until another
833
+ render or reset. Direct calls do not load the core plugin registry for you.
834
+
835
+ Compile a single PHP page or a whole directory.
836
+
837
+ ```js
838
+ // Compile one page
839
+ const pageResult = await render('about/_index.php');
840
+
841
+ // Compile everything under src/
842
+ const treeResult = await render('.');
843
+
844
+ // Compile everything (uses kirigami.root from config)
845
+ const defaultResult = await render();
846
+ ```
847
+ > Paths used by `render()` are all relative to the `kirigami.root` configuration.
848
+
849
+
850
+ **Returns** `Promise<PreprosResult>`:
851
+
852
+ ```ts
853
+ interface PreprosResult {
854
+ success: boolean;
855
+ files?: string[]; // project-relative paths; may be absent on parsing failure
856
+ error?: string;
857
+ debug?: string; // captured PHP stdout
858
+ stderr?: string; // diagnostics attached to failures
859
+ warnings?: string; // nonfatal stderr on success
860
+ page?: string | null; // PHP-render failure context, when available
861
+ where?: string; // PHP source location, when available
862
+ }
863
+ ```
864
+
865
+ Setup and filesystem failures can reject before a result exists; PHP failures
866
+ usually return `success: false`. Check both channels. Files may already have
867
+ been copied to the host before a later error; operations are not transactional.
868
+ The runtime returns `debug`/`stderr`, not the older declared `response` field.
869
+
870
+ Directory rendering selects `_*.php` files only when every directory between
871
+ `kirigami.root` and the page has a name without a leading underscore. Sitemap
872
+ selection uses the same rule. Direct requests for private pages fail; rendering
873
+ a private directory produces no pages. The configured source root itself may
874
+ start with `_` (for example `_src`). Previously generated private HTML is not
875
+ deleted by this selection rule; remove stale outputs when migrating a site.
876
+
877
+ ### `sitemap()`
878
+
879
+ Generate `sitemap.xml` and `robots.txt` at the source root, plus `humans.txt`
880
+ when author configuration provides content. It accepts no directory argument.
881
+
882
+ ```js
883
+ const result = await sitemap();
884
+ // With kirigami.root: src, files includes src/sitemap.xml and src/robots.txt.
885
+ ```
886
+
887
+ ### `runenv(script, paths?, ...args)`
888
+
889
+ Run an arbitrary PHP script — not a page template — inside the very same sandboxed WASM environment used for `render()`, with the full `php-prepros` class library autoloaded and `kirigami.yaml`'s `kirigami` block available as `PREPROS::$config->data`. Useful for one-off maintenance scripts, data migrations, or CLI-style tooling that needs `CACHE`, `SCRAPER`, `IMG`, etc. without going through the page-rendering pipeline.
890
+
891
+ ```js
892
+ // Run a standalone PHP script
893
+ const purgeResult = await runenv('scripts/purge-cache.php');
894
+
895
+ // Also mount explicit extra files into the sandbox before running
896
+ const imageResult = await runenv('scripts/build-og-images.php', ['assets/photos/hero.jpg']);
897
+
898
+ // Extra arguments are appended and available as $argv[2], $argv[3], … in the script
899
+ const importResult = await runenv('scripts/import.php', [], '--force');
900
+ ```
901
+
902
+ - `script` — path to a PHP file **inside the project**, executed with `require_once`.
903
+ - `paths` — optional array of explicit local file paths, not directories. Missing
904
+ files are skipped; a directory can cause a filesystem rejection. Use
905
+ `mountPath()` first for recursive directory mounting.
906
+ - `...args` — extra string arguments appended to the script's `$argv`.
907
+
908
+ Script and extra-file paths resolve against the project captured at import.
909
+ Before initializing PHP or copying files, `runenv()` rejects paths outside
910
+ that project, including symbolic links whose real targets are outside it.
911
+ Directories are rejected; missing optional files are skipped. This check does
912
+ not make PHP scripts untrusted-code sandboxes or restrict explicit `mountPath()`
913
+ calls.
914
+
915
+ **Returns** `Promise<PreprosResult>`, following the same shape as `render()`. Inside the script, call `PREPROS::exportFile()` for any file you want listed in `result.files`.
916
+
917
+ ### `runPluginScript(script, pluginRoot, paths?, ...args)`
918
+
919
+ Same as `runenv()`, for a script shipped inside a plugin package. A plugin
920
+ installed with `npm link` or from a workspace lives outside the project, so
921
+ `runenv()` would reject it. Here the script's authored and real paths must stay
922
+ inside `pluginRoot` instead, and it is mounted under
923
+ `/plugin-scripts/<package dir>/`. Extra `paths` are still project files.
924
+ The caller vouches for `pluginRoot`: `@kirigami/kirigami` only passes the
925
+ resolved package directory of an active plugin.
926
+
927
+ ### `mountPath(localPath, virtualDir?, php?)`
928
+
929
+ The JavaScript-side counterpart to [`PREPROS::mount()`](#preprosmountstringarray-patterns). Mounts a local file or directory — recursively, preserving structure — into the WASM sandbox's virtual filesystem, ahead of (or between) calls to `render()`, `sitemap()`, or `runenv()`. Useful when a Node-side build step needs to make extra local files visible to PHP before rendering starts.
930
+
931
+ ```js
932
+ import { mountPath, render } from '@kirigami/php-prepros';
933
+
934
+ // Mount a single file at its natural virtual path (/project/<relative path>)
935
+ await mountPath('assets/data/team.yaml');
936
+
937
+ // Mount a whole directory, at a custom virtual path
938
+ await mountPath('vendor/fonts', '/project/fonts');
939
+
940
+ await render();
941
+ ```
942
+
943
+ - `localPath` — path to a local file or directory. Relative paths are resolved against the project root.
944
+ - `virtualDir` — optional destination path inside the WASM filesystem. Defaults to `/project/<localPath relative to the project root>` when omitted.
945
+ - `php` — optional WASM PHP instance to mount into. Defaults to PHP-prepros's owned instance (the same one used internally by `render()`/`sitemap()`/`runenv()`), creating it if needed. This is separate from PHP-WASM's shared getter instances and is replaced after `resetRuntime()`.
946
+
947
+ Mounting a **directory** only copies files whose extension is one of the defaults (`.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`) or listed in `prepros.mountext`, same as automatic root mounting. Mounting a **single file directly** copies it regardless of extension — this is the simplest way to make an arbitrary asset (an image, a font, a CSV, …) available to PHP without adding its extension to `prepros.mountext` project-wide.
948
+
949
+ **Returns** `Promise<void>`.
950
+
951
+ ### `processImages(jobs)`
952
+
953
+ Run a batch of image jobs — resize/encode, or palette extraction — through the
954
+ [`IMG`](#img) class (GD, with the Imagick fallback). This is the engine
955
+ `@kirigami/kirigami`'s `sass` task uses for its `img-asset()` and `colors()`
956
+ functions, so Sass, `IMG::asset()` and the [`<img asset>` tag](#built-in-tags)
957
+ all share one implementation, one `image:` config and one set of output
958
+ filenames — with no native image dependency.
959
+
960
+ ```js
961
+ import { processImages } from '@kirigami/php-prepros';
962
+
963
+ const { files, colors } = await processImages([
964
+ // resize/encode `hero.jpg` (resolved against image.source) to each dest —
965
+ // absolute virtual paths, already carrying the target extension
966
+ { op: 'resize', src: 'hero.jpg', width: 1200, height: 0, cover: false, quality: 82,
967
+ dests: ['/project/src/images/hero-1200w.webp'] },
968
+
969
+ // extract a 5-colour palette (cached in .cache.db); returned, not written
970
+ { op: 'palette', src: 'hero.jpg', count: 5 },
971
+ ]);
972
+
973
+ // files includes 'src/images/hero-1200w.webp' and may include '.cache.db'.
974
+ // colors → { 'hero.jpg:5': ['#1e3a5f', '#c8a24b', …] }
975
+ ```
976
+
977
+ - `jobs` — array of `resize` / `palette` jobs (see the shape above). An **empty
978
+ array is a no-op** and does **not** start the WASM runtime.
979
+ - Omitted `jobs` also returns `{ success: true, files: [], colors: {} }`
980
+ without starting PHP. Non-array input currently does the same; this is not
981
+ strict input validation.
982
+ - Staleness is the caller's responsibility: every `resize` job listed is executed.
983
+ - `resize`: `width`/`height` default to `0` (preserve size when both are zero),
984
+ `cover` to `false`, and lossy encoder quality to `82`. `dests` contains
985
+ absolute `/project/...` output paths. `palette` defaults `count` to `5`.
986
+ - The PHP worker handles `palette` explicitly and treats any other `op` as a
987
+ resize; pass only the two documented operations. Processing stops at the
988
+ first exception. Always check `success` before using files or colors.
989
+
990
+ **Returns** `Promise<PreprosResult & { colors: Record<string, string[]> }>`.
991
+
992
+ ### `resetRuntime()`
993
+
994
+ Returns `Promise<void>`. Queued after preceding operations, it disposes the
995
+ owned runtime, mounts, and cached configuration. It does not change the project
996
+ path captured at import, clear disk caches, or reset the SDK hook registry.
997
+
998
+ ### TypeScript declarations
999
+
1000
+ The shipped `index.d.ts` includes `render(file?, phpIncludes?)`, argument-free
1001
+ `sitemap()`, explicit-file `runenv()` mounts, and the current diagnostic fields.
1002
+ `PreprosResult.files` is optional because response parsing can fail before a
1003
+ file list exists. `ImageBatchResult.files` is always normalized to an array.
1004
+ The obsolete `response` field is replaced by `debug` and `stderr`.
1005
+
1006
+ ---
1007
+
1008
+ ## PHP classes reference
1009
+
1010
+ All classes are autoloaded — no manual `require` needed inside your page files.
1011
+ The autoloader itself, `$argv`/`$config`, procedural aliases, and the `boot`
1012
+ hook are installed via php.ini's `auto_prepend_file` (pointed at
1013
+ `utils.inc.php`), set once per WASM runtime instance — every entrypoint
1014
+ (`prepros.php`, `runenv.php`, `imagebatch.php`) gets it automatically,
1015
+ with no `include` of its own.
1016
+
1017
+ ---
1018
+
1019
+ ### PREPROS
1020
+
1021
+ The core engine. Manages the rendering pipeline, tag processing, hooks, mounting, and file export.
1022
+
1023
+ ```php
1024
+ // Available inside page templates and included files.
1025
+ PREPROS::$config // stdClass — full resolved config; ->data is the kirigami: block,
1026
+ // ->image the image: block, plus before/after/format/… from prepros:
1027
+ PREPROS::registerTag(string $tag, callable $callback)
1028
+ PREPROS::registerHook(string $hook, callable $callback)
1029
+ PREPROS::runHook(string $hook, mixed $data = null) // fire a hook (built-in or your own), returns the piped $data
1030
+ PREPROS::mount(string|array $patterns)
1031
+ PREPROS::exportFile(string|array $absolutePath)
1032
+ PREPROS::getExportedFiles(): string[]
1033
+ PREPROS::fstat(string $path) // stat a file in the WASM FS (or false)
1034
+ PREPROS::backtraceFile() // path of the page currently rendering
1035
+ ```
1036
+
1037
+ #### `PREPROS::render(string $file)`
1038
+
1039
+ Internal method called once per source file. Orchestrates the full pipeline:
1040
+
1041
+ 1. Resolves PHPDOC metadata and auto-loads data files.
1042
+ 2. Fires the `pre_render` hook with the raw source contents.
1043
+ 3. Includes `before.php` (wrapped in the `pre_before` / `post_before` hooks) and the page body (or `@content`, see [above](#content-indent-and-type)).
1044
+ 4. If the page declares `@type <name>` and `prepros.types.<name>` exists, wraps the body with that type's `before`/`after` (wrapped in `pre_type_before` / `post_type_before` and `pre_type_after` / `post_type_after`) — nested inside the global wrap.
1045
+ 5. Includes `after.php` (wrapped in `pre_after` / `post_after`), assembling everything into a single string.
1046
+ 6. Processes all registered custom HTML tags.
1047
+ 7. Fires the `post_render` hook on the assembled HTML.
1048
+ 8. Optionally pretty-prints via `HTML::format()` (when `format: true`).
1049
+ 9. Writes the output `.html` file.
1050
+
1051
+ #### `PREPROS::sitemap()`
1052
+
1053
+ Scans the source tree for `_index.php` files and generates a standards-compliant `sitemap.xml` (Sitemaps 0.9), using `kirigami.baseurl` as the root URL.
1054
+
1055
+ #### `PREPROS::mount(string|array $patterns)`
1056
+
1057
+ Mounts additional local project files into the WASM virtual filesystem, on demand, from one or more glob patterns evaluated against the project root (via `picomatch`). Unlike the automatic mounting done for `kirigami.root` (limited to `.php`, `.json`, `.yaml`, `.yml`, `.md`, `.db`, `.txt`, and `prepros.mountext`), `mount()` copies **any** matching file, regardless of extension.
1058
+
1059
+ ```php
1060
+ // Mount every .webp under assets/, wherever the page needs them
1061
+ PREPROS::mount('assets/**/*.webp');
1062
+
1063
+ // Multiple patterns at once
1064
+ PREPROS::mount(['data/**/*.csv', 'vendor/fonts/*.woff2']);
1065
+ ```
1066
+
1067
+ Returns an array of the virtual paths (under `/project/...`) that were mounted, or `false` on failure.
1068
+
1069
+ #### `PREPROS::exportFile(string $file)`
1070
+
1071
+ Marks a file as a build output so it gets surfaced in `PreprosResult.files`. Called automatically by `render()`, `sitemap()`, `CACHE::set()`, and `CURL`. Call it manually if your custom code writes additional files.
1072
+
1073
+ ---
1074
+
1075
+ ### MD
1076
+
1077
+ Markdown-to-HTML converter with a plugin system for custom shortcodes,
1078
+ backed by PHP's native `mdhtml` extension (real `cmark-gfm`), statically
1079
+ built into `@kirigami/php-wasm` — no userland parsing.
1080
+
1081
+ ```php
1082
+ $html = MD::toHtml(string $markdown): string;
1083
+ ```
1084
+
1085
+ Supports the full GitHub Flavored Markdown subset, plus a few extensions:
1086
+
1087
+ - ATX (`#` … `######`) and Setext headings, with auto-generated `id` attributes
1088
+ - Ordered and unordered lists, including nested
1089
+ - GFM task lists (`- [ ]` / `- [x]`)
1090
+ - GFM tables with column alignment
1091
+ - GFM alerts (`> [!NOTE]`, `> [!WARNING]`, etc.)
1092
+ - Blockquotes (recursive)
1093
+ - Fenced code blocks with language class
1094
+ - Inline code
1095
+ - Bold, italic, bold+italic, strikethrough
1096
+ - Links with automatic `target="_blank" rel="noopener noreferrer"` for external URLs
1097
+ - Images with `loading="lazy"`
1098
+ - Auto-linked bare URLs
1099
+ - Horizontal rules
1100
+ - Hard line breaks (trailing double space → `<br>`)
1101
+ - **Footnotes** — `[^1]` references and `[^1]: …` definitions (multi-paragraph)
1102
+ - **Definition lists** — `Term` / `: Definition`
1103
+ - **Emoji shortcodes** — `:rocket:` → 🚀, from a built-in map (see `MD::registerEmoji()`)
1104
+ - **Sanitized inline HTML** — raw tags are filtered against an allowlist of tags and attributes, not passed through verbatim
1105
+
1106
+ #### Plugin API
1107
+
1108
+ Extend Markdown with custom shortcode tags:
1109
+
1110
+ ```php
1111
+ // Inline tag {% tagname arg1 "arg with spaces" %}
1112
+ // Block tag {% tagname arg1
1113
+ // body content
1114
+ // %}
1115
+
1116
+ MD::registerPlugin(string $name, callable $callback): void
1117
+ MD::unregisterPlugin(string $name): void
1118
+ MD::getRegisteredPlugins(): string[]
1119
+ MD::registerEmoji(string $shortcode, string $char): void // `:name:` → char
1120
+ ```
1121
+
1122
+ The callback always receives `(array $args, string $body)`:
1123
+
1124
+ ```php
1125
+ MD::registerPlugin('video', function (array $args, string $body): string {
1126
+ $src = htmlspecialchars($args[0] ?? '', ENT_QUOTES, 'UTF-8');
1127
+ return "<video src=\"{$src}\" controls></video>";
1128
+ });
1129
+ ```
1130
+
1131
+ Then in any Markdown content (including inside `<markdown>` tags):
1132
+
1133
+ ```
1134
+ {% video /videos/intro.mp4 %}
1135
+ ```
1136
+
1137
+ ---
1138
+
1139
+ ### HTML
1140
+
1141
+ Pretty-printer for the final HTML output. Used automatically when `format: true` is set in the config.
1142
+
1143
+ ```php
1144
+ $formatted = HTML::format(string $html): string;
1145
+ ```
1146
+
1147
+ Uses PHP 8.4's `Dom\HTMLDocument` (Lexbor engine) to parse the input and re-serialize it with consistent 4-space indentation. Inline elements, `<script>`, and `<style>` blocks are handled correctly — their content is indented but not reformatted. A `<pre><code>` block is shifted to its nesting depth too (relative indentation kept), and the leading run is stripped again before display; a bare `<pre>` and `<textarea>` stay byte-for-byte. Boolean HTML5 attributes (`muted`, `autoplay`, `noopener`, etc.) are written without a value.
1148
+
1149
+ ---
1150
+
1151
+ ### YAML
1152
+
1153
+ PHP data files use the native `yaml` extension backed by LibYAML. Its YAML 1.1 implicit booleans include unquoted `y`, `n`, `yes`, `no`, `on`, `off`, `true`, and `false`, including mapping keys. Quote these words when you mean strings (for example, `"NO": Norway`). `YAML::parse()` / `parseFile()` / `loadFile()` preserve the wrapper’s array/object choice; native `yaml_parse()` / `yaml_parse_file()` have their own extension signatures. `yaml_load_file()` remains a wrapper alias. The project’s `kirigami.yaml` is parsed separately in Node through `struct-walker` and `js-yaml`.
1154
+
1155
+ A YAML parser backed by PHP's native `yaml` extension (libyaml), statically built into `@kirigami/php-wasm` — full YAML 1.1 support, no userland parsing.
1156
+
1157
+ ```php
1158
+ $data = YAML::parse(string $yaml, bool $assoc = false): mixed;
1159
+ $data = YAML::parseFile(string $path, bool $assoc = false): mixed;
1160
+ $data = YAML::loadFile(string $path, bool $assoc = false): mixed;
1161
+ ```
1162
+
1163
+ By default, YAML mappings are returned as `stdClass` objects. Pass `true` as the second argument to get associative arrays instead.
1164
+
1165
+ Following YAML 1.1 means the usual implicit-boolean gotcha applies to both values *and* mapping keys: `y`/`Y`/`n`/`N`, `yes`/`no`, `true`/`false`, `on`/`off` (any case) all resolve to a boolean when unquoted — so an unquoted `no:` key or a `NO` value becomes `false`. Quote a scalar (`"y": 2`) to keep it a string.
1166
+
1167
+ `YAML::loadFile()` behaves like `YAML::parseFile()`, then walks the result recursively: any string value ending in `.yaml`, `.yml`, or `.json` that resolves to an existing file (relative to *its own* file's directory) is replaced by that file's parsed content, and so on, recursively. Values that don't match an existing file are left untouched. Circular references (`A → B → A`) throw a `RuntimeException`.
1168
+
1169
+ ```yaml
1170
+ # team.yaml
1171
+ lead: people/jane.yaml # resolved and inlined automatically
1172
+ members:
1173
+ - people/jane.yaml
1174
+ - people/john.yaml
1175
+ ```
1176
+
1177
+ ```php
1178
+ $team = YAML::loadFile('/project/data/team.yaml');
1179
+ // $team->lead is now the fully parsed content of people/jane.yaml, not a string
1180
+ ```
1181
+
1182
+ ---
1183
+
1184
+ ### SCHEMA
1185
+
1186
+ A JSON Schema validator with an Ajv-like API, backed by the native `jsonk`
1187
+ extension built into `@kirigami/php-wasm`. Available to your own code and
1188
+ plugins.
1189
+
1190
+ ```php
1191
+ $validator = new SCHEMA(array $schema);
1192
+
1193
+ $validator->isValid(mixed $data): bool // true / false
1194
+ $validator->validate(mixed $data): bool // alias of isValid()
1195
+ $validator->getErrors(): string[] // "path: message" strings from the last run
1196
+ ```
1197
+
1198
+ jsonk implements draft 2020-12 for a self-contained schema: every validation
1199
+ keyword (`type`, `enum`, `const`, `required`, `properties`,
1200
+ `patternProperties`, `additionalProperties`, `propertyNames`,
1201
+ `dependentRequired`, `dependentSchemas`, `items`, `prefixItems`, `contains`,
1202
+ `uniqueItems`, the `min*`/`max*` and `exclusive*` bounds, `multipleOf`,
1203
+ `pattern`, `format`, `if`/`then`/`else`, `allOf`/`anyOf`/`oneOf`/`not`) and
1204
+ `$ref` to `#/$defs/…` / `#/definitions/…`, absolute URLs, or URLs relative to
1205
+ the schema's `$id`. See [php-jsonk](https://github.com/php-kirigami/php-jsonk)
1206
+ for the details and limits.
1207
+
1208
+ Schemas are PHP arrays, so `SCHEMA` adapts them before handing them to jsonk:
1209
+ an empty array in a schema position (`'properties' => []`) is treated as `{}`,
1210
+ draft-07 tuple `items` (a list of schemas) becomes `prefixItems` (and
1211
+ `additionalItems` becomes `items`), and `format: url` is read as `uri`. Error
1212
+ paths look like `(root)`, `name` or `tags[1]`.
1213
+
1214
+ The previous pure-PHP (Draft-7 style) validator is still available as
1215
+ `SCHEMA_LEGACY`, with the same API.
1216
+
1217
+ ```php
1218
+ $validator = new SCHEMA([
1219
+ 'type' => 'object',
1220
+ 'required' => ['name', 'age'],
1221
+ 'properties' => [
1222
+ 'name' => ['type' => 'string', 'minLength' => 1],
1223
+ 'age' => ['type' => 'integer', 'minimum' => 0],
1224
+ ],
1225
+ 'additionalProperties' => false,
1226
+ ]);
1227
+
1228
+ if (!$validator->isValid($data)) {
1229
+ foreach ($validator->getErrors() as $err) echo $err, PHP_EOL;
1230
+ }
1231
+ ```
1232
+
1233
+ ---
1234
+
1235
+ ### LD
1236
+
1237
+ A **schema.org JSON-LD generator**. `LD` accumulates structured-data nodes for
1238
+ the page under render and emits them as one
1239
+ `<script type="application/ld+json">` block — with an `@graph` when there is more
1240
+ than one node — in the `<head>`.
1241
+
1242
+ #### Automatic mode
1243
+
1244
+ On as soon as `kirigami.yaml` has a [`seo:` block](#seo-block) (`seo: {}` is
1245
+ enough), alongside [`META`](#meta)'s tags and from the same keys. A
1246
+ `post_render` hook injects a graph built from `seo:`, the loose keys of the
1247
+ `kirigami` block, and the current page's PHPDOC:
1248
+
1249
+ - an `Organization` node (`@id` `#organization`) — `name`/`url`/`description`
1250
+ from `project`/`baseurl`/`description`, `sameAs` gathered from every
1251
+ recognised social-network URL key (`facebook`, `instagram`, `linkedin`,
1252
+ `github`, `youtube`, `mastodon`, …), plus `email`, `telephone`, `areaServed`
1253
+ (← `area`), `knowsAbout` (← `knowsabout`), `address`, `logo`, and `founder` →
1254
+ the Person node when there is one. `@type` comes from `seo.type`;
1255
+ - a `Person` node (`#person`) when `person` is set — `name` + `jobTitle`
1256
+ (← `jobtitle`) + `email` + `url`, linked to the Organization via `worksFor`;
1257
+ - a `WebSite` node (`#website`) — `publisher` → Organization, `inLanguage`,
1258
+ `keywords` (← `keywords`), and a `SearchAction` when `seo.search` is set;
1259
+ - a `WebPage` node for the page — see the per-page tags below;
1260
+ - a `BreadcrumbList` for every non-home page, derived from the `_index.php`
1261
+ ancestor trail (home → each parent section → this page). No `@breadcrumb`
1262
+ opt-in needed. Disable it for one page with `@ld_breadcrumb false`.
1263
+
1264
+ `seo: { jsonld: false }` stops the automatic pass; META's tags keep working.
1265
+ A page whose rendered `<head>` already contains an `application/ld+json`
1266
+ script is never touched, so hand-rolled markup keeps working.
1267
+
1268
+ **Per-page PHPDOC tags** — these feed the page node (and override the generic
1269
+ `@title` / `@description` / `@datePublished` fallbacks):
1270
+
1271
+ | Tag | Effect |
1272
+ |-----|--------|
1273
+ | `@ld false` | Skip JSON-LD for this page entirely (`@ld_ignore true` also works). |
1274
+ | `@ld_type <Type>` | `@type` of the page node — `AboutPage`, `ContactPage`, `CollectionPage`, `ProfilePage`, or a content type like `Article`, `Service`, `Recipe`, … (default `WebPage`). Types containing “Page” also get `primaryImageOfPage` + a `breadcrumb` link; others get a plain `image`. |
1275
+ | `@ld_title <text>` | Page node `name` (default: `@title`). |
1276
+ | `@ld_description <text>` | Page node `description` (default: `@description`). |
1277
+ | `@ld_image <path>` | Page image, absolute or relative to `baseurl` (default: `@image` / `@ogimage`). |
1278
+ | `@ld_published <date>` | `datePublished` (default: `@datePublished` / `@published` / `@date`). |
1279
+ | `@ld_modified <date>` | `dateModified` (default: `@dateModified` / `@modified` / `@updated`). |
1280
+ | `@ld_breadcrumb false` | No `BreadcrumbList` for this page. |
1281
+
1282
+ ```php
1283
+ /**
1284
+ * @title À propos
1285
+ * @ld_type AboutPage
1286
+ * @ld_title À propos de Humain Humain
1287
+ * @ld_description Notre approche ethnographique de la consultation.
1288
+ */
1289
+ ```
1290
+
1291
+ #### Explicit builders
1292
+
1293
+ Call these from a page template or from a `prepros.includes` file. Nodes added
1294
+ this way are always emitted — automatic pass on or not — and share
1295
+ the graph the automatic pass uses, so the two combine; a node with a stable
1296
+ `@id` is merged on repeat calls.
1297
+
1298
+ ```php
1299
+ LD::add(string|array $type, array $props = [], ?string $id = null): array // build + register a node
1300
+ LD::node(string|array $type, array $props = []): array // build only, no register
1301
+ LD::push(array $node): array // register a ready-made node
1302
+ LD::ref(string $id): array // ['@id' => …] ('#person' → the Person node)
1303
+ LD::remove(string $id): void
1304
+ LD::graph(): array
1305
+ LD::reset(): void
1306
+
1307
+ LD::organization(array $overrides = []): array // config-aware, @id #organization
1308
+ LD::person(array $overrides = []): array // config-aware, @id #person
1309
+ LD::website(array $overrides = []): array // config-aware, @id #website
1310
+ LD::webPage(array $overrides = []): array // current-page-aware, @id …#webpage
1311
+ LD::breadcrumb(?array $items = null, array $overrides = []): array // items: [['name'=>…,'url'=>…], …]
1312
+ LD::faqPage(array $qa, array $overrides = []): array // qa: ['Question ?' => 'Answer.', …]
1313
+
1314
+ LD::address(array|string $a): array
1315
+ LD::image(string $url, ?string $id = null, ?int $w = null, ?int $h = null): array
1316
+ LD::geo(float $lat, float $lng): array
1317
+ LD::rating(int|float $value, ?int $count = null, $best = 5, $worst = 1): array
1318
+ LD::offer(array $o): array
1319
+ LD::contactPoint(array $c): array
1320
+ LD::searchAction(string $urlTemplate): array
1321
+
1322
+ LD::script(bool $pretty = true): string // <script>…</script>, and disables auto-injection
1323
+ LD::json(bool $pretty = true): string // the document, no wrapper
1324
+ ```
1325
+
1326
+ Every other schema.org type is reachable through `__callStatic` — the method
1327
+ name is upper-cased to form the `@type`:
1328
+
1329
+ ```php
1330
+ LD::recipe([ 'name' => 'Tarte aux pommes', 'recipeYield' => '6', 'prepTime' => 'PT30M' ]);
1331
+ LD::event([ 'name' => 'Vernissage', 'startDate' => '2026-10-01T18:00' ]);
1332
+ LD::softwareApplication([ 'name' => 'Kirigami', 'applicationCategory' => 'DeveloperApplication' ]);
1333
+
1334
+ LD::article([
1335
+ 'headline' => $title,
1336
+ 'datePublished' => '2026-09-01',
1337
+ 'author' => LD::ref('#person'),
1338
+ 'image' => LD::image('images/cover.webp'),
1339
+ 'publisher' => LD::ref('#organization'),
1340
+ ]);
1341
+ ```
1342
+
1343
+ Same API from procedural code: `ld_add()`, `ld_node()`, `ld_ref()`,
1344
+ `ld_organization()`, `ld_person()`, `ld_website()`, `ld_web_page()`,
1345
+ `ld_breadcrumb()`, `ld_faq_page()`, `ld_script()`, `ld_json()`.
1346
+
1347
+ LD's keys (`type`, `logo`, `person`, `address`, `search`, …) live in the
1348
+ [`seo` config](#seo-config) with META's.
1349
+
1350
+ ---
1351
+
1352
+ ### META
1353
+
1354
+ A **`<head>` SEO / social metadata generator** — the companion to [`LD`](#ld).
1355
+ Where `LD` emits a schema.org `application/ld+json` graph, `META` emits the plain
1356
+ tags a browser and a link-preview crawler read: `<title>`, `<meta name="…">`,
1357
+ `<meta property="og:…">`, `<meta name="twitter:…">`, and a handful of `<link>`s.
1358
+
1359
+ It draws on the same sources, in this order of precedence: the page's PHPDOC, the
1360
+ top-level `seo:` block, then the loose `kirigami:` keys. Every tag is emitted **only when it can be resolved** — no value, no
1361
+ tag — and a tag the page's layout already writes by hand is detected and
1362
+ skipped, so it drops in beside an existing `header.php` without duplicating
1363
+ anything.
1364
+
1365
+ **Automatic mode** is opt-in: the top-level `seo:` block (empty `seo: {}` is
1366
+ enough) turns on injection into every page's `<head>`, right before `</head>`.
1367
+
1368
+ ```yaml
1369
+ kirigami:
1370
+ project: Humain Humain
1371
+ baseurl: https://humainhumain.com
1372
+ tagline: Ethnographie au service des organisations
1373
+ description: A social-science consultancy using ethnography for organisational change.
1374
+ keywords: [ethnographie, consultation publique, sciences sociales]
1375
+ author: Maxime Larrivée-Roy
1376
+
1377
+ seo: # top-level; the block being present is the switch
1378
+ twitter: "@humainhumain"
1379
+ themeColor: "#0b7285"
1380
+ lang: fr-CA # <meta name="language">, og:locale, JSON-LD inLanguage
1381
+ logo: assets/logo.png # JSON-LD logo, and og:image when there is no `image`
1382
+ ```
1383
+
1384
+ Per-page, from the PHPDOC block — each falls back to the generic page tag:
1385
+
1386
+ | Tag | Feeds | Default |
1387
+ |-----|-------|---------|
1388
+ | `@meta false` | skip metadata for this page entirely | — (`@meta_ignore true` also works) |
1389
+ | `@meta_title` | `<title>`, `og:title`, `twitter:title` | `@title` |
1390
+ | `@meta_description` | `description`, `og:description`, `twitter:description` | `@description` / `@abstract` / `@excerpt` / `@summary`, then the site `description` |
1391
+ | `@meta_keywords` | `<meta name="keywords">` | `@keywords`, then `seo.keywords` |
1392
+ | `@meta_image` | `og:image`, `twitter:image` | `@image` / `@ogimage`, then `seo.image` |
1393
+ | `@meta_robots` | `<meta name="robots">` | `@robots`, then `seo.robots` |
1394
+ | `@meta_type` | `og:type` | `@og_type`, then `seo.ogType` |
1395
+ | `@canonical` | `<link rel="canonical">` | derived from the file path + `baseurl` |
1396
+
1397
+ **Manual builders** — always emitted (with or without a `seo:` block), still
1398
+ de-duplicated against the page:
1399
+
1400
+ ```php
1401
+ META::tag(string $name, ?string $content): void // name= , or property= for an og:* key
1402
+ META::link(string $rel, string $href, array $attrs = []): void
1403
+ META::raw(string $html): void // a verbatim, already-valid tag line
1404
+ META::tags(string $html = ''): string // the whole block, \n-joined
1405
+ META::reset(): void
1406
+ ```
1407
+
1408
+ ```php
1409
+ META::tag('twitter:image', 'https://humainhumain.com/card.png');
1410
+ META::tag('og:image:alt', 'The Humain Humain team at work');
1411
+ META::link('icon', './favicon.svg', ['type' => 'image/svg+xml']);
1412
+ ```
1413
+
1414
+ Same API from procedural code: `meta_tag()`, `meta_link()`, `meta_raw()`,
1415
+ `meta_tags()`.
1416
+
1417
+ <a id="meta-config"></a><a id="jsonld-config"></a>
1418
+
1419
+ #### `seo` config
1420
+
1421
+ These keys live directly under the **top-level** `seo:` block of
1422
+ `kirigami.yaml` (a sibling of `kirigami:`, `prepros:`, …) and feed both META's
1423
+ tags and LD's JSON-LD. All are optional.
1424
+
1425
+ | Key | Type | Description |
1426
+ |-----|------|-------------|
1427
+ | `auto` | `bool` | Inject META's tags automatically. Default `true` **once the `seo:` block exists**. `auto: false` keeps the block for its values but stops the tags — `META::tags()` / `meta_tags()` can place them by hand. |
1428
+ | `jsonld` | `bool` | Inject LD's JSON-LD automatically. Default `true` **once the `seo:` block exists**. `jsonld: false` stops it — `LD::script()` / `ld_script()` can place it by hand. |
1429
+ | `titleFormat` | `string` | `<title>` template for a normal page. Tokens `{title}`, `{project}`, `{tagline}`. Dangling separators from an empty token are trimmed. Default `{title} — {project}`. |
1430
+ | `titleFormatHome` | `string` | Title template when the page has no `@title` (home / section landings). Default `{project} — {tagline}`. |
1431
+ | `description` | `string` | Default description for pages with no `@description` / `@abstract`, and the JSON-LD main entity / WebSite description. Defaults to the loose `description`. |
1432
+ | `keywords` | `string[]` \| `string` | Default `keywords` content (list or comma string) and the WebSite `keywords`. Defaults to the loose `keywords`. |
1433
+ | `robots` | `string` | Default robots directive. Default `index, follow`. `robots: false` omits the tag. |
1434
+ | `lang` | `string` | BCP-47 tag → `<meta name="language">`, `og:locale` (dash→underscore) and JSON-LD `inLanguage`. Defaults to the loose `lang` / `language`, then `en`. |
1435
+ | `generator` | `string` \| `false` | `<meta name="generator">`. Default `Kirigami`; `false` omits it. |
1436
+ | `author` / `designer` | `string` | Default to the loose `author` / `designer` keys (author also falls back to `person`'s name). `designer` is not emitted unless set. |
1437
+ | `themeColor` | `string` | `<meta name="theme-color">`. Not emitted unless set. |
1438
+ | `image` | `string` | Default `og:image` / `twitter:image` and JSON-LD image — absolute URL or path relative to `baseurl`. Defaults to `logo`, then the loose `image` / `ogimage`. |
1439
+ | `logo` | `string` | Organization logo (JSON-LD `ImageObject`), absolute URL or path relative to `baseurl`. |
1440
+ | `ogType` | `string` | Default `og:type`. Default `website`. |
1441
+ | `twitterCard` | `string` | `twitter:card` type. Default `summary_large_image`. |
1442
+ | `twitter` | `string` \| `map` | Handle for `twitter:site` / `twitter:creator`. A bare string (with/without `@`, or a profile URL) fills both; a map takes `site` / `creator` separately. |
1443
+ | `canonical` | `bool` | Emit `<link rel="canonical">`. Default `true`. |
1444
+ | `favicon` / `appleTouchIcon` / `humans` | `string` \| `bool` | `<link rel="icon">` / `rel="apple-touch-icon"` / `rel="author"`. A path sets it (page-relative when a bare filename); `true` forces the default file (`favicon.ico` / `apple-touch-icon.png` / `humans.txt`); omitted, the default file is auto-detected on disk at the source root; `false` disables it. |
1445
+ | `type` | `string` | JSON-LD `@type` of the main entity — `Organization` (default), `ProfessionalService`, `LocalBusiness`, … |
1446
+ | `name` / `url` | `string` | JSON-LD main entity / WebSite name and URL. Default to `project` / `baseurl`. |
1447
+ | `sameAs` | `string[]` | Profile URLs, merged with the social-network URL keys found loose in the `kirigami` block. |
1448
+ | `email` / `telephone` | `string` | Default to the loose `email` / `telephone` keys. |
1449
+ | `address` | `map` | `PostalAddress` properties. |
1450
+ | `areaServed` | `string` | Defaults to the loose `area` key. |
1451
+ | `knowsAbout` | `string[]` | Defaults to the loose `knowsabout` key. |
1452
+ | `person` | `string` \| `map` | The `#person` node (and the default `author`). A string is the name; a map takes any `Person` property. Defaults to `person` + `jobtitle` + `email`. |
1453
+ | `search` | `string` | URL template for a sitelinks `SearchAction`; must contain `{search_term_string}`. |
1454
+
1455
+ ```yaml
1456
+ kirigami:
1457
+ project: Humain Humain
1458
+ baseurl: https://humainhumain.com
1459
+ person: Méralie Murray-Hall
1460
+ jobtitle: Anthropologue
1461
+ facebook: https://www.facebook.com/humainhumainconsultation.ethnographie/
1462
+
1463
+ seo:
1464
+ type: ProfessionalService
1465
+ lang: fr-CA
1466
+ logo: assets/logo.png
1467
+ knowsAbout: [Ethnographie, Recherche qualitative]
1468
+ address:
1469
+ addressLocality: Québec
1470
+ addressCountry: CA
1471
+ search: https://humainhumain.com/?q={search_term_string}
1472
+ ```
1473
+
1474
+ ---
1475
+
1476
+ ### CACHE
1477
+
1478
+ Persistent SQLite-backed key-value cache. Survives across incremental builds via `.cache.db` at the project root.
1479
+
1480
+ ```php
1481
+ CACHE::get(string $key): mixed
1482
+ CACHE::set(string $key, mixed $val, int $ttl = 0): bool
1483
+ CACHE::delete(string $key): bool
1484
+ CACHE::purge(): bool // removes expired entries
1485
+ ```
1486
+
1487
+ The `$ttl` is in seconds. `0` means the entry never expires. Typical use case: caching the result of network fetches in custom hooks or plugins — it is what powers [`SCRAPER`](#scraper) internally. `CURL` persists its cookie jar separately in `.cookie.txt`.
1488
+
1489
+ ```php
1490
+ $data = CACHE::get('my-remote-data');
1491
+ if ($data === null) {
1492
+ $data = json_decode(file_get_contents('https://api.example.com/data.json'));
1493
+ CACHE::set('my-remote-data', $data, 3600); // cache for 1 hour
1494
+ }
1495
+ ```
1496
+
1497
+ ---
1498
+
1499
+ ### IMG
1500
+
1501
+ Image manipulation helper. GD handles JPEG, PNG, GIF, WebP and AVIF directly;
1502
+ anything GD can't decode (HEIC, TIFF, BMP, and the vector formats SVG, EPS, AI,
1503
+ PDF) falls back to Imagick, which rasterizes it to a GD image in memory. Vector
1504
+ files with no intrinsic pixel size are rasterized at 2000&nbsp;px on the longest
1505
+ side, preserving the aspect ratio.
1506
+
1507
+ ```php
1508
+ $img = new IMG(string $file);
1509
+
1510
+ // Properties
1511
+ $img->width // int
1512
+ $img->height // int
1513
+
1514
+ // Instance methods (resize/save are chainable)
1515
+ $img->resize(int $width, int $height = 0, bool $cover = false): self
1516
+ $img->save(string $dest, ?int $quality = null): self // quality 0-100 for jpg/webp/avif; null = per-format default (82)
1517
+ $img->getRepresentativeColors(int $count = 5): string[] // ['#rrggbb', …]
1518
+
1519
+ // Static helpers
1520
+ IMG::asset(string $path, int $width = 0, int $height = 0, bool $cover = false): string // same feature as the <img asset> tag and the img-asset() Sass function
1521
+ IMG::palette(string $path, int $colors = 5): string[]
1522
+ ```
1523
+
1524
+ `resize()` operates in *contain* mode by default (scales to fit within the target box while preserving aspect ratio). Pass `$cover = true` to crop and fill the exact target dimensions.
1525
+
1526
+ `save()` infers the output format from the file extension (`.jpg`, `.jpeg`, `.png`, `.gif`, `.webp`, `.avif`) and marks the file as a build output.
1527
+
1528
+ ```php
1529
+ // Build a 1200×630 cropped Open Graph image next to the original
1530
+ (new IMG('/project/src/images/hero.jpg'))
1531
+ ->resize(1200, 630, true)
1532
+ ->save('/project/src/images/hero-og.jpg');
1533
+ ```
1534
+
1535
+ `IMG::asset()` and `IMG::palette()` are what back kirigami-core's `img-asset()`
1536
+ and `colors()` Sass functions: they resolve `$path` against `image.source` from
1537
+ `kirigami.yaml`, generate a resized/re-encoded file under `image.dest` (only
1538
+ when missing or stale), or return a `CACHE`-backed list of representative
1539
+ colours. Both are equally usable from your own PHP.
1540
+
1541
+ `IMG::asset()` is the single implementation behind the [`<img asset>` tag](#built-in-tags)
1542
+ too — the tag is just a thin wrapper. Generated files are named after the source
1543
+ plus a dimension suffix: `-<W>w`, `-<H>h`, `-<W>x<H>`, or `-<W>x<H>-cover`, with
1544
+ the `image.format` extension (e.g. `hero.jpg` + `width="800"` → `hero-800w.webp`).
1545
+ `@kirigami/kirigami`'s Sass `img-asset()` / `colors()` functions produce the same
1546
+ files from the same config through this same class, via
1547
+ [`processImages()`](#processimagesjobs) — one engine, no native dependency.
1548
+
1549
+ ---
1550
+
1551
+ ### FS
1552
+
1553
+ Filesystem utilities.
1554
+
1555
+ ```php
1556
+ FS::dig(string $glob): iterable // recursive glob, yields file paths
1557
+ FS::getRelativePath(string $from, string $to): string
1558
+ FS::phpFileInfo(string $file): object|false // parse PHPDOC annotations
1559
+ FS::getChildren(string $backtrace = ''): object[] // child _index.php pages, ordered by @position
1560
+ FS::getBreadcrumb(string $backtrace = ''): object[] // ancestor _index.php pages, top-most first (opt-in via @breadcrumb)
1561
+ FS::rmdir(string $dir, bool $removeSelf = true): bool
1562
+ FS::pathJoin(string ...$parts): string // URL-aware path join with .. resolution
1563
+ ```
1564
+
1565
+ `FS::dig()` is the workhorse of directory-wide builds — it recursively walks a glob pattern and yields every matching file path.
1566
+
1567
+ `FS::phpFileInfo()` parses the first PHPDOC block of a PHP file and returns its `@tag value` pairs as a `stdClass`. This is used internally to resolve page metadata and data-file annotations.
1568
+
1569
+ `FS::getChildren()` (procedural: `fs_get_children()`) — usable only during a render — scans the folders directly below the calling template, keeps the ones that contain an `_index.php`, and returns one `stdClass` per child: the parsed PHPDOC of that `_index.php` plus a `->file` key with its absolute path. Entries are ordered by `@position` ascending (a page with no `@position` sorts as `999999`), then by folder name (natural, case-insensitive). Handy for building a section index or a navigation menu:
1570
+
1571
+ ```php
1572
+ <?php foreach (fs_get_children() as $page): ?>
1573
+ <li><a href="<?= FS::getRelativePath(__DIR__, dirname($page->file)) ?>/"><?= $page->title ?></a></li>
1574
+ <?php endforeach ?>
1575
+ ```
1576
+
1577
+ `FS::getBreadcrumb()` (procedural: `fs_get_breadcrumb()`) — also render-only — is the upward counterpart: it returns the calling page's breadcrumb trail. It only produces output when the calling file opts in with `@breadcrumb true` (or `@breadcrumb 1`) in its first PHPDOC block, otherwise it returns `[]`. From the folder **above** the caller's own folder (a page is never part of its own trail), it walks the parent directories upward and collects the `_index.php` of each, stopping at the source root or at the first ancestor `_index.php` that carries no active `@breadcrumb` tag — that page acts as a separator and is left out. Directories without an `_index.php` are skipped without breaking the chain. Entries come back ordered from the top-most ancestor down to the nearest parent, each a `stdClass` (parsed PHPDOC of its `_index.php` plus a `->file` key with its absolute path):
1578
+
1579
+ ```php
1580
+ <nav aria-label="Breadcrumb">
1581
+ <?php foreach (fs_get_breadcrumb() as $crumb): ?>
1582
+ <a href="<?= FS::getRelativePath(__DIR__, dirname($crumb->file)) ?>/"><?= $crumb->title ?></a>
1583
+ <?php endforeach ?>
1584
+ </nav>
1585
+ ```
1586
+
1587
+ ---
1588
+
1589
+ ### STR
1590
+
1591
+ String utilities used internally by the tag-processing pipeline, and available for your own templates and plugins.
1592
+
1593
+ ```php
1594
+ STR::htmlesc(string $str): string
1595
+ STR::replaceTags(string $tag, string $html, callable $callback): string
1596
+ STR::parseHtmlAttributes(string $attrString): array
1597
+ STR::trimIndent(string $str): string
1598
+ STR::is_url(string $str): bool
1599
+ STR::html_entities_decode(string $str): string
1600
+ STR::shorthash(string $str): string
1601
+ STR::normalize(string $str): string
1602
+ STR::slug(string $str, string $sep = ''): string
1603
+ ```
1604
+
1605
+ `STR::replaceTags()` is the engine behind `PREPROS::registerTag()`. It finds all occurrences of `<tagname ...>...</tagname>` in an HTML string and replaces each with the return value of `$callback($fullMatch, $attrs, $body)`.
1606
+
1607
+ `STR::trimIndent()` strips the common leading whitespace from a multi-line string — handy when pulling content out of indented `<markdown>` blocks.
1608
+
1609
+ `STR::is_url()` checks whether a string parses as a URL with a recognized scheme (`http`, `https`, `ftp`, `ftps`, `ssh`, `ssl`, `sftp`, `itunes`).
1610
+
1611
+ `STR::html_entities_decode()` trims a string and decodes its HTML entities — handy when normalizing text scraped from a third-party page.
1612
+
1613
+ `STR::shorthash()` returns the first 12 characters of a string's SHA-256 hash — used internally as a stable, filename-safe cache key (see `SCRAPER`).
1614
+
1615
+ `STR::normalize()` applies Unicode NFD decomposition and strips combining marks (`é` → `e`) — the accent-folding step used by `slug()`.
1616
+
1617
+ `STR::slug()` normalizes, transliterates to ASCII, lowercases, and replaces every run of non-`[a-z0-9]` characters with `$sep` (empty by default → a compact identifier; pass `'-'` for a conventional hyphenated slug).
1618
+
1619
+ ---
1620
+
1621
+ ### ARR
1622
+
1623
+ Recursive lookup helper for nested arrays and objects.
1624
+
1625
+ ```php
1626
+ ARR::find_key(mixed $data, string $key): mixed
1627
+ ```
1628
+
1629
+ Walks an array or object (including mixed nested `stdClass`/array structures, as produced by `YAML::parse()` or `json_decode()`) depth-first and returns the value of the **first** matching key found, at any depth, or `null` if none matches.
1630
+
1631
+ ```php
1632
+ $config = YAML::parseFile('team.yaml');
1633
+ $email = ARR::find_key($config, 'email'); // finds `email` however deep it's nested
1634
+ ```
1635
+
1636
+ ---
1637
+
1638
+ ### CURL
1639
+
1640
+ CURL verifies HTTPS certificate chains and hostnames, including redirects. The network-enabled WASM runtime supplies Node’s root certificates through `curl.cainfo` and `openssl.cafile`. Untrusted certificates and hostname mismatches are rejected; there is no insecure fallback. `getInfo()` returns `false` when cURL fails, and `getContents()` preserves its existing failure return values.
1641
+
1642
+ Low-level HTTP client built on PHP's cURL extension, used internally by `SCRAPER`. Ships with a realistic browser `User-Agent`/header set and a cookie jar persisted at `.cookie.txt` (auto-registered via `PREPROS::exportFile()`).
1643
+
1644
+ ```php
1645
+ CURL::urlExists(string $url, ?string $mimereg = null): bool
1646
+ CURL::getInfo(string $url): array|false // HEAD request, returns curl_getinfo()
1647
+ CURL::getContents(string $file, ?string $dest = null, ?callable $clb = null): string|bool
1648
+ ```
1649
+
1650
+ `CURL::urlExists()` issues a `HEAD` request and returns `true` for any `2xx`/`3xx` response.
1651
+
1652
+ `CURL::getContents()` downloads a URL. Without `$dest`, it returns the body as a string; with `$dest`, it streams the download to that file path and returns a boolean. Pass `$clb` to receive download progress as a float between `0` and `1`.
1653
+
1654
+ ```php
1655
+ CURL::getContents('https://example.com/report.pdf', '/project/src/downloads/report.pdf', function (float $progress) {
1656
+ error_log(sprintf('%.0f%%', $progress * 100));
1657
+ });
1658
+ ```
1659
+
1660
+ ---
1661
+
1662
+ ### SCRAPER
1663
+
1664
+ Fetches a URL and extracts page metadata (`title`, `description`, `image`, `label`) from its JSON-LD (`schema.org`), Open Graph, and standard `<meta>` tags — the kind of data you'd want for a rich link preview. Results are cached indefinitely via `CACHE`, keyed on the URL.
1665
+
1666
+ ```php
1667
+ $metas = SCRAPER::get(string $url): object|false;
1668
+ ```
1669
+
1670
+ ```php
1671
+ $metas = SCRAPER::get('https://example.com/blog/some-article');
1672
+ if ($metas) {
1673
+ echo $metas->title; // string
1674
+ echo $metas->description; // string
1675
+ echo $metas->image; // string (absolute URL, may be empty)
1676
+ echo $metas->label; // string — site/publisher name, may be empty
1677
+ echo $metas->url; // string — the URL that was scraped
1678
+ }
1679
+ ```
1680
+
1681
+ Returns `false` if the page can't be reached, can't be parsed, or has no discoverable title. Throws an `Exception` on invalid URLs. Uses `CURL::getContents()` under the hood, so it benefits from the same shared cookie jar and browser-like headers.
1682
+
1683
+ ---
1684
+
1685
+ ### OBF
1686
+
1687
+ Simple reversible obfuscation for non-secret values embedded in HTML, such as display labels or contact data. It does not protect API tokens or other credentials.
1688
+
1689
+ ```php
1690
+ $encoded = OBF::encode(mixed $obj): string;
1691
+ $decoded = OBF::decode(string $str): mixed;
1692
+ ```
1693
+
1694
+ Applies JSON encoding → base64 → ROT-13 → gzip. Not cryptographically secure; intended for light obfuscation only.
1695
+
1696
+ ---
1697
+
1698
+ ### STD
1699
+
1700
+ Result helpers that write JSON to `/internal/prepros_result.json` in the virtual filesystem. Node reads that result file; ordinary PHP stdout/stderr are separate diagnostic channels.
1701
+
1702
+ ```php
1703
+ STD::succeed(array|string $props = []): void // exits 0, writes JSON to /internal/prepros_result.json
1704
+ STD::error(array|string $props = []): void // exits 1, writes JSON to /internal/prepros_result.json
1705
+ ```
1706
+
1707
+ These are internal to the build runner (`render()`, `sitemap()`, and `runenv()` all rely on them). You generally do not need to call them in page templates, but they are available if a script run via `runenv()` needs to terminate early with a custom result.
1708
+
1709
+ ---
1710
+
1711
+ ### Unicode normalization
1712
+
1713
+ The WASM PHP build ships without `ext-intl`; the native `norm` extension
1714
+ ([php-norm](https://github.com/php-kirigami/php-norm), utf8proc) provides the
1715
+ standard `Normalizer` class instead: `Normalizer::normalize()` /
1716
+ `Normalizer::isNormalized()`, the `NFC` / `NFD` / `NFKC` / `NFKD` (and
1717
+ `FORM_*`) constants, and the `normalizer_normalize()` /
1718
+ `normalizer_is_normalized()` functions. `STR::normalize()` and `STR::slug()`
1719
+ use it to fold accents. Prefer the `STR` helpers in your own code.
1720
+
1721
+ The pure-PHP polyfill that used to fill this gap is still autoloadable as
1722
+ `NORMALIZER_LEGACY`, with the same API.
1723
+
1724
+ ---
1725
+
1726
+ ### Procedural shortcuts (aliases)
1727
+
1728
+ Every static method of every class above is also exposed as a plain function by
1729
+ `src/libraries/aliases.inc.php` (autoloaded — no `require` needed). Each alias is
1730
+ named `<lowercase class>_<snake_case method>()` and does nothing but forward its
1731
+ arguments, so the classes remain the canonical API. They exist to make page
1732
+ templates and `kiri run` scripts read better:
1733
+
1734
+ ```php
1735
+ <?= md_to_html(file_get_contents('CHANGELOG.md')) ?>
1736
+ <img src="<?= img_asset('hero.jpg', 1200, 630, true) ?>" alt="">
1737
+ ```
1738
+
1739
+ Every function has a complete PHPDoc block, so editor hover and autocomplete
1740
+ surface the signature, parameters, and description.
1741
+
1742
+ | Class | Aliases |
1743
+ |---|---|
1744
+ | `PREPROS` | `prepros_render` · `prepros_sitemap` · `prepros_mount` · `prepros_fstat` · `prepros_export_file` · `prepros_get_exported_files` · `prepros_backtrace_file` · `prepros_register_tag` · `prepros_register_hook` · `prepros_run_hook` |
1745
+ | `MD` | `md_to_html` · `md_register_plugin` · `md_unregister_plugin` · `md_get_registered_plugins` · `md_register_emoji` |
1746
+ | `HTML` | `html_format` |
1747
+ | `YAML` | `yaml_parse` · `yaml_parse_file` · `yaml_load_file` |
1748
+ | `SCHEMA` | `schema` (factory) · `schema_validate` |
1749
+ | `LD` | `ld_add` · `ld_node` · `ld_ref` · `ld_organization` · `ld_person` · `ld_website` · `ld_web_page` · `ld_breadcrumb` · `ld_faq_page` · `ld_script` · `ld_json` |
1750
+ | `META` | `meta_tag` · `meta_link` · `meta_raw` · `meta_tags` |
1751
+ | `CACHE` | `cache_get` · `cache_set` · `cache_delete` · `cache_purge` |
1752
+ | `IMG` | `img_asset` · `img_palette` |
1753
+ | `FS` | `fs_dig` · `fs_get_relative_path` · `fs_php_file_info` · `fs_rmdir` · `fs_path_join` |
1754
+ | `STR` | `str_htmlesc` · `str_replace_tags` · `str_parse_html_attributes` · `str_trim_indent` · `str_is_url` · `str_html_entities_decode` · `str_shorthash` · `str_normalize` · `str_slug` |
1755
+ | `ARR` | `arr_find_key` |
1756
+ | `CURL` | `curl_url_exists` · `curl_get_info` · `curl_get_contents` |
1757
+ | `SCRAPER` | `scraper_get` |
1758
+ | `OBF` | `obf_encode` · `obf_decode` |
1759
+ | `STD` | `std_succeed` · `std_error` |
1760
+
1761
+ Notes:
1762
+
1763
+ - `register_tag()` / `register_hook()` are kept as unprefixed aliases of
1764
+ `prepros_register_tag()` / `prepros_register_hook()`.
1765
+ - `img_asset()` resolves the generated URL relative to the file that calls it,
1766
+ exactly like `IMG::asset()`.
1767
+ - `schema_validate(array $schema, mixed $data, ?array &$errors = null): bool`
1768
+ fills `$errors` with the validation messages.
1769
+ - `yaml_parse()` / `yaml_parse_file()` are only defined when the PECL `yaml`
1770
+ extension isn't already providing them.
1771
+
1772
+ ---
1773
+
1774
+ ## Plugin system
1775
+
1776
+ `@kirigami/php-prepros` has two complementary plugin layers: **PREPROS** (HTML-tag level, operates on the assembled page) and **MD** (shortcode level, operates inside Markdown content).
1777
+
1778
+ ---
1779
+
1780
+ ### PREPROS tags
1781
+
1782
+ Register a custom HTML tag that is processed **after** PHP execution, on the fully assembled HTML string:
1783
+
1784
+ ```php
1785
+ // In a file listed under prepros.includes in kirigami.yaml, or in before.php:
1786
+
1787
+ PREPROS::registerTag('gallery', function (string $fullTag, array $attrs, string $body): string {
1788
+ $id = $attrs['id'] ?? '';
1789
+ $imgs = glob("/project/src/images/gallery/{$id}/*.webp");
1790
+ $html = '<div class="gallery">';
1791
+ foreach ($imgs as $img) {
1792
+ $src = str_replace('/project/src', '', $img);
1793
+ $html .= "<img src=\"{$src}\" loading=\"lazy\">";
1794
+ }
1795
+ return $html . '</div>';
1796
+ });
1797
+ ```
1798
+
1799
+ Then in any page template:
1800
+
1801
+ ```html
1802
+ <gallery id="summer-2025"></gallery>
1803
+ ```
1804
+
1805
+ The callback receives:
1806
+
1807
+ | Parameter | Type | Description |
1808
+ |-----------|------|-------------|
1809
+ | `$fullTag` | `string` | The complete matched tag string |
1810
+ | `$attrs` | `array` | Parsed HTML attributes as an associative array |
1811
+ | `$body` | `string` | Inner content between opening and closing tags |
1812
+
1813
+ The built-in [`<markdown>` and `<img asset>` tags](#built-in-tags) are registered
1814
+ this way.
1815
+
1816
+ ---
1817
+
1818
+ ### PREPROS hooks
1819
+
1820
+ Hooks let you intercept and transform data at key points in the rendering pipeline:
1821
+
1822
+ ```php
1823
+ PREPROS::registerHook(string $hookName, callable $callback): void
1824
+ ```
1825
+
1826
+ | Hook | When it fires | `$data` type | Expected return |
1827
+ |------|---------------|--------------|-----------------|
1828
+ | `boot` | Once per process, right after bootstrap (config loaded, `includes` pulled in), before any page renders. Fires for every entrypoint. | `stdClass $config` | ignored |
1829
+ | `shutdown` | Via `register_shutdown_function()`, at the very end of the request — fires even after `STD::succeed()`/`STD::error()`'s `exit()`, unlike `auto_append_file` (which PHP skips whenever the script exits). The place for cleanup that must always run. | `null` | ignored |
1830
+ | `page_info` | After PHPDOC parsing, before rendering (auto-loads `.yaml`/`.json`/`.md` annotations) | `[$filePath, $pageObject]` — see note | `$pageObject` (modified) |
1831
+ | `pre_render` | Before PHP execution | Raw file contents as `string` | Ignored by the current render call |
1832
+ | `pre_before` | Just before the `before` include (inside its output buffer — `echo` to prepend to the header) | `before` config path as `string\|null` | ignored |
1833
+ | `post_before` | Right after the `before` include, on the captured header | Header `string` | `string` |
1834
+ | `pre_type_before` | Just before the page's `@type` `before` include, if any (inside its output buffer) | Type's `before` config path as `string\|null` | ignored |
1835
+ | `post_type_before` | Right after the `@type` `before` include, on the captured type header | Type header `string` | `string` |
1836
+ | `pre_type_after` | Just before the page's `@type` `after` include, if any (inside its output buffer) | Type's `after` config path as `string\|null` | ignored |
1837
+ | `post_type_after` | Right after the `@type` `after` include, on the captured type footer | Type footer `string` | `string` |
1838
+ | `pre_after` | Just before the `after` include (inside its output buffer — `echo` to prepend to the footer) | `after` config path as `string\|null` | ignored |
1839
+ | `post_after` | Right after the `after` include, on the captured footer | Footer `string` | `string` |
1840
+ | `post_render` | After tag processing, before `HTML::format()` | Assembled HTML `string` | `string` |
1841
+
1842
+ Multiple callbacks can be registered for the same hook — they are executed in registration order, each receiving the return value of the previous one.
1843
+
1844
+ > Built-in `page_info` + `post_render` callbacks power [`LD`](#ld) and
1845
+ > [`META`](#meta): `page_info` captures the page under render, `post_render`
1846
+ > injects the JSON-LD `<script>` and the `<meta>`/`<link>` block into its
1847
+ > `<head>`. Your own callbacks run after them.
1848
+
1849
+ > **`page_info` payload shape.** The hook *fires* with `[$filePath, $pageObject]`,
1850
+ > but each callback is expected to return the `$pageObject` alone — so a callback
1851
+ > registered after the built-ins receives the bare object, not the pair. Handle
1852
+ > both: `$page = is_array($p) ? $p[1] : $p;` (the current page path is always
1853
+ > available as `PREPROS::$file`).
1854
+
1855
+ ```php
1856
+ // Example: inject a last-modified date into every page
1857
+ PREPROS::registerHook('post_render', function (string $html): string {
1858
+ $date = date('Y-m-d');
1859
+ return str_replace('{{build_date}}', $date, $html);
1860
+ });
1861
+ ```
1862
+
1863
+ ---
1864
+
1865
+ ### MD plugins
1866
+
1867
+ MD plugins add custom shortcode tags inside Markdown content. They work inside `<markdown>` blocks, in `.md` data files, and anywhere `MD::toHtml()` is called.
1868
+
1869
+ **Inline syntax** (all on one line):
1870
+
1871
+ ```
1872
+ {% tagname arg1 "argument with spaces" %}
1873
+ ```
1874
+
1875
+ **Block syntax** (body on subsequent lines):
1876
+
1877
+ ```
1878
+ {% tagname optional-arg
1879
+ Line one of the body.
1880
+ Line two of the body.
1881
+ %}
1882
+ ```
1883
+
1884
+ ```php
1885
+ MD::registerPlugin(string $name, callable $callback): void
1886
+ ```
1887
+
1888
+ The callback signature is always `(array $args, string $body): string`. `$args` contains arguments parsed from the opening line; `$body` is the trimmed multi-line body (empty string for inline tags).
1889
+
1890
+ ---
1891
+
1892
+ ### Built-in plugins
1893
+
1894
+ The following MD plugins are registered out of the box in `md.plugins.php`:
1895
+
1896
+ #### `{% callout type ["Title"] content %}`
1897
+
1898
+ Renders a styled callout block. `type` is one of `info`, `success`, `warning`, `danger`.
1899
+
1900
+ ```
1901
+ {% callout warning "Heads up" This section is outdated. %}
1902
+
1903
+ {% callout danger "Critical"
1904
+ Line one of a longer warning.
1905
+
1906
+ Line two after a blank line.
1907
+ %}
1908
+ ```
1909
+
1910
+ #### `{% img-asset path [width height [cover]] %}`
1911
+
1912
+ Generate an image with `IMG::asset()` and emit an `<img>` tag. Width and height default to zero; the optional final `cover` selects cropping.
1913
+
1914
+ ```markdown
1915
+ {% img-asset photo.jpg 800 600 cover %}
1916
+ ```
1917
+
1918
+ YouTube and Vimeo shortcuts require `@kirigami/plugin-embed`; YouTube is no longer a built-in plugin.
1919
+
1920
+ #### `{% codepen id [user height] %}`
1921
+
1922
+ Embeds a CodePen result via `<iframe>`. `user` defaults to `anonymous`, `height` defaults to `400`.
1923
+
1924
+ ```
1925
+ {% codepen abcXYZ %}
1926
+ {% codepen abcXYZ jsmith 500 %}
1927
+ ```
1928
+
1929
+ #### `{% checklist ["Title"] items %}`
1930
+
1931
+ Renders a block-syntax list of checkbox items, one per line, with an optional title.
1932
+
1933
+ ```
1934
+ {% checklist "Today"
1935
+ Do the dishes
1936
+ Walk the dog
1937
+ Read a book
1938
+ %}
1939
+ ```
1940
+
1941
+ ---
1942
+
1943
+ ## Extending the `<markdown>` tag
1944
+
1945
+ The `<markdown>` tag is one of the [built-in tags](#built-in-tags) (alongside
1946
+ `<img asset>`), registered as a PREPROS tag out of the box. It converts its inner
1947
+ content from Markdown to HTML and strips common leading indentation so you can
1948
+ write cleanly inside your PHP templates:
1949
+
1950
+ ```html
1951
+ <section class="about">
1952
+ <div>
1953
+ <markdown>
1954
+ ## Who we are
1955
+
1956
+ We are a **student organization** from Québec.
1957
+
1958
+ {% codepen abc123 author 400 %}
1959
+ </markdown>
1960
+ </div>
1961
+ </section>
1962
+ ```
1963
+
1964
+ All registered MD plugins are available inside `<markdown>` blocks. You can extend the tag's behaviour by registering additional MD plugins (see above) or by overriding the tag itself:
1965
+
1966
+ ```php
1967
+ PREPROS::registerTag('markdown', function (string $tag, array $attrs, string $body): string {
1968
+ $body = STR::trimIndent($body);
1969
+ $html = MD::toHtml($body);
1970
+ // wrap in a container, add a class, etc.
1971
+ $class = $attrs['class'] ?? 'prose';
1972
+ return "<div class=\"{$class}\">{$html}</div>";
1973
+ });
1974
+ ```
1975
+
1976
+ ---
1977
+
1978
+ ## Requirements
1979
+
1980
+ - Node.js `>= 24.0.0`
1981
+ - npm `>= 10.2.3`
1982
+ - ESM only (`"type": "module"`)
1983
+
1984
+ ---
1985
+
1986
+ ## License
1987
+
1988
+ GPL-3.0-or-later © Maxime Larrivée-Roy, 2026