Skip to content

Commit ee733bb

Browse files
authored
Merge pull request #38 from PureStackStudio/improve-plugin-architecture
Move integration-specific configuration into its owning plugins and add optional image optimization through @purestack/ts-images. Preserve existing default site output while making plugin configuration and asset lifecycle contracts explicit.
2 parents 19b6869 + 8774106 commit ee733bb

117 files changed

Lines changed: 7570 additions & 1200 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎frontend/components/studioBrand.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import {
66
import { defineComponent, html, type RefOrValue } from 'regor'
77

88
export interface StudioBrand {
9-
config: LogoConfig
9+
config?: LogoConfig
1010
size?: RefOrValue<LogoSize>
1111
}
1212

‎frontend/purestack.studio/guides/extending/plugins.mdx‎

Lines changed: 86 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,49 @@ A plugin is a named object that extends how PureStack builds your site. Each of
2929

3030
## Add your first plugin
3131

32+
To use an installed plugin without writing TypeScript, list its package in
33+
`siteConfig.json`. For example, install `@purestack/ts-images`, then enable image
34+
optimization:
35+
36+
```json
37+
{
38+
"plugins": ["@purestack/ts-images#imagesPlugin"],
39+
"extensions": {
40+
"images": { "widths": [480, 960, 1440] }
41+
}
42+
}
43+
```
44+
45+
Use `package#exportName` to select a named export, for example
46+
`"@purestack/ts-images#imagesPlugin"`. Without a suffix, PureStack selects the
47+
default export. Each selected export must be a plugin object or a no-argument
48+
factory. Packages can expose multiple plugins; list each export separately:
49+
50+
```json
51+
{
52+
"plugins": [
53+
"@purestack/ts-page-scripts#consentPlugin",
54+
"@purestack/ts-page-scripts#analyticsPlugin"
55+
]
56+
}
57+
```
58+
59+
The suffix is the JavaScript export name, not the plugin's `name`. Package
60+
subpaths also work: `package/subpath#exportName`. PureStack loads selections for
61+
builds, publishing, and development, and reloads them when this JSON file changes.
62+
Each plugin owns its settings; listing `imagesPlugin` enables
63+
its defaults even without `extensions.images`. Set `extensions.images.enabled`
64+
to `false` to disable optimization. An explicit plugin instance in
65+
`purestack.config.ts` replaces a JSON-selected plugin with the same name.
66+
67+
Both config formats use PureStack's own copy of a package when available so
68+
shared registries stay together; other packages resolve from the site.
69+
Plugin declarations execute installed JavaScript with the build process's
70+
permissions, so treat changes to `plugins` as code changes even when a CMS edits
71+
other site settings.
72+
73+
For local plugins and custom callbacks, use the TypeScript setup below.
74+
3275
Keep plugins in a folder of their own, beside the content folder:
3376

3477
```text
@@ -111,7 +154,23 @@ Metadata defaults compose through `headConfig({ site, pageInfo })` in plugin ord
111154

112155
Auth hints, consent, and analytics are independent plugins in `ts-page-scripts`. The analytics plugin contributes automatic GA4 consent services during configuration resolution, before any factory or lifecycle hook runs. Omitting it removes automatic registration and direct tracking scripts. Explicitly configured consent services remain available. Analytics never bypasses enabled consent when the consent runtime plugin is omitted.
113156

114-
To choose the standard integrations yourself, disable the automatic set and list the plugins you want. The factories are exported from `purestack`, `@purestack/ts-ssg`, and their individual packages:
157+
To choose the standard integrations yourself, disable the automatic set and list the plugins you want in `siteConfig.json`:
158+
159+
```json
160+
{
161+
"defaultPlugins": false,
162+
"plugins": [
163+
"@purestack/ts-theme#themePlugin",
164+
"@purestack/ts-components#componentsPlugin"
165+
]
166+
}
167+
```
168+
169+
Omitting `defaultPlugins` keeps the automatic set enabled. An explicit
170+
TypeScript/programmatic `defaultPlugins` value overrides the JSON flag.
171+
Development reloads changes to either setting.
172+
173+
The same selection is available in `purestack.config.ts`. The factories are exported from `purestack`, `@purestack/ts-ssg`, and their individual packages:
115174

116175
```ts
117176
import { componentsPlugin, defineConfig, themePlugin } from 'purestack'
@@ -132,10 +191,14 @@ The Pagefind plugin supplies a `search` provider. To use another engine, replace
132191

133192
## Configure a plugin
134193

135-
Plugins contribute configuration through `config.resolve({ config, input, file })` and `config.finalize({ config, input, file })`. Both are optional and synchronous. Each returns an object to merge into the config; do not mutate the inputs. All resolvers run first in plugin order, applying configuration overrides. Then all finalizers run in plugin order, deriving dependent settings from the completed overrides. Finalizers should derive settings rather than change resolver inputs. Both phases finish before highlighters, Markdown processors, styles, search providers, components, and templates initialize. The analytics plugin finalizes its automatic GA4 service here, so later site resolvers can enable analytics, change its ID or category, or provide a manual service. The existing `onConfigResolved` hook still runs after factories, so it can customize initialized components and templates. Publishing applies its output-directory and minification overrides after configuration composition.
194+
`resolveSiteConfig(input)` returns `DefaultSiteConfig` for the untouched standard set. Calls supplying a `plugins` array return `SiteConfig`, even when automatic defaults remain enabled, because a supplied plugin can replace a standard owner by name.
195+
196+
Plugins contribute configuration through optional, synchronous `config.resolve`, `config.normalize`, and `config.finalize` functions, each receiving `{ config, input, file }` and returning an object to merge into config. Do not mutate the inputs. All resolvers run first in plugin order to supply defaults and overrides. All normalizers then validate and canonicalize the completed overrides. Finally, all finalizers derive dependent settings from the normalized config. Finalizers should not change the inputs used by other finalizers. Every phase finishes before highlighters, Markdown processors, styles, search providers, components, and templates initialize. Analytics derives its automatic GA4 consent service only after every normalizer finishes, regardless of plugin order. The existing `onConfigResolved` hook still runs after factories. Publishing applies its output-directory and minification overrides after configuration composition.
136197

137198
Custom site settings belong under `extensions` in `siteConfig.json`. File values merge with programmatic input, which takes precedence. The standard JSON schema allows plugin namespaces here while continuing to reject unknown top-level fields. Each plugin owns validation, defaults, and normalization for its namespace. Other namespaces are preserved.
138199

200+
`resolve` and `normalize` receive `SiteConfigDraft`: core fields are ready, while plugin settings can still be partial, including nested extension values. `finalize` receives normalized `SiteConfig` after all selected owners finish normalization. Factories run afterwards. Importing a plugin's setting types does not install its owner; select that plugin before depending on its normalized settings.
201+
139202
```json
140203
{ "extensions": { "brand": { "label": "Acme" } } }
141204
```
@@ -171,10 +234,29 @@ export const brandPlugin = definePlugin({
171234
})
172235
```
173236

174-
Raw `resolveSiteConfig(input)` resolves core settings and extension input. CLI and programmatic builds additionally compose their selected plugins' configuration contributions. Configuration contributions are synchronous and may run whenever a project configuration is resolved; keep file writes and other side effects in lifecycle hooks.
237+
`resolveSiteConfig(input, { plugins, defaultPlugins })` composes the supplied plugin instances with the standard plugins by default. This synchronous helper does not apply JSON plugin selection (`plugins` or `defaultPlugins`) or load `purestack.config.ts`. Plugin-owned sections (`style`, `docLayout`, `pageToc`, `logo`, `auth`, `consent`, `analytics`, `pagefind`, and `preview`) are optional in `SiteConfig`: an omitted plugin does not supply defaults or validate its unused input. A replacement plugin reads its settings from `input` and `file`, then contributes normalized config. Analytics also resolves explicitly configured consent when its browser runtime is omitted, so enabled consent is never bypassed. Configuration contributions are synchronous and may run whenever a project configuration is resolved; keep file writes and other side effects in lifecycle hooks.
175238

176239
Builder style state is isolated across asynchronous operations, including concurrent sites. Its owned theme options remain linked to `context.config.style.theme`, so in-place config-hook changes and `themes.setOptions` update page colors, CSS, and generated favicons consistently. Head, metadata, template, Markdown, provider, and lifecycle errors identify their owning plugin and preserve the original cause. Markdown wrappers preserve unified presets, duplicate-plugin option merging, and callback transforms.
177240

241+
## Optimize images
242+
243+
Image optimization is optional. Install `@purestack/ts-images` alongside PureStack and add it to your existing plugin list:
244+
245+
```ts
246+
import { defineConfig } from 'purestack'
247+
import { imagesPlugin } from '@purestack/ts-images'
248+
249+
export default defineConfig({
250+
plugins: [imagesPlugin({ widths: [480, 960, 1440] })],
251+
})
252+
```
253+
254+
Ordinary Markdown images and rendered HTML images receive responsive AVIF/WebP sources, JPEG/PNG fallbacks, dimensions, and loading defaults. Originals remain available for links and downloads. Remote images, SVGs, animations, existing `picture` markup, and images with `srcset` pass through. Use `data-image-preset="hero"` for eager priority images, `data-image-preset="screenshot"` for lossless output, or `data-image-optimize="false"` to keep an individual image unchanged. Set `sizes` for your actual image layout.
255+
256+
The plugin owns its `extensions.images` settings, persistent cache, and encoder limits. It uses the generic asset contribution: `assets(config)` returns a per-site processor with a unique namespace and `processPage(input)`. This runs after all `onPageDocument` hooks, before URL rewriting. `resolveSource(element, url)` resolves local inputs and registers dependencies; `dependOn(relPath)` registers additional inputs; `emit(fileName, bytes)` atomically writes an owned file and returns its URL. Use content-addressed names and await all writes. Core handles base paths, incremental invalidation, shared references, manifest persistence, and cleanup when pages or processors disappear. The builder contains no image format or encoder selection.
257+
258+
Asset processors run in order within each page, and different page requests can run them concurrently. Keep page-local state inside `processPage`; coordinate shared caches and queues within the processor instance. Await source resolution and emission before returning. Input methods then close, and detached work cannot emit files after page completion. Later processors see earlier DOM edits, while `resolveSource` continues to resolve original content files only. Combine transforms inside one processor when they need intermediate generated bytes. Ownership receipts and processor instances remain private to the builder.
259+
178260
## How the config loads
179261

180262
- **Where it lives.** The CLI looks for `purestack.config.ts` in the folder passed to `--content`. It must default-export `defineConfig({ plugins: [...] })`.
@@ -586,7 +668,7 @@ Every field except `name` is optional.
586668
| `name` | `string`, unique among the site's plugins |
587669
| `defaults` | `boolean`; makes component and template contributions overridable defaults without changing initialization order |
588670
| `skins` | Skins by name, each `{ create(): ThemeSkinPair }` |
589-
| `config` | `{ resolve?: SiteConfigResolver, finalize?: SiteConfigResolver }`; overrides, then derived settings, before factories |
671+
| `config` | `{ resolve?: SiteConfigResolver, normalize?: SiteConfigResolver, finalize?: SiteConfigFinalizer }`; overrides, normalization, then derived settings, before factories |
590672
| `components` | `(config) => ({ [name]: component })` |
591673
| `templates` | Templates by name, each `(input) => TSNode<'html'>` |
592674
| `head` | `(input) => TSNode<'head'>`, or a promise; composes head markup before the page template |

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
{
22
"private": true,
33
"name": "purestack-repo",
4-
"version": "1.1.15",
4+
"version": "1.1.16",
55
"packageManager": "yarn@4.18.1",
66
"type": "module",
77
"sideEffects": false,

‎packages/purestack/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "purestack",
3-
"version": "1.1.15",
3+
"version": "1.1.16",
44
"packageManager": "yarn@4.9.2",
55
"module": "./dist/purestack.mjs",
66
"types": "./dist/purestack.d.mts",

‎packages/purestack/src/index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
export const version: string = '1.1.15'
1+
export const version: string = '1.1.16'
22

33
export * from '@purestack/ts-ssg'

‎packages/ts-common/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@purestack/ts-common",
3-
"version": "1.1.15",
3+
"version": "1.1.16",
44
"packageManager": "yarn@4.9.2",
55
"module": "./dist/ts-common.mjs",
66
"types": "./dist/ts-common.d.mts",

‎packages/ts-common/src/index.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,15 @@ export {
5252
resolvePageContext,
5353
tryResolvePageContext,
5454
} from './resolvePageContext'
55+
export type {
56+
AssetSource,
57+
PageAssetInput,
58+
SiteAssets,
59+
} from './site-assets'
5560
export type {
5661
AnalyticsConfig,
5762
AuthConfig,
63+
CoreSiteConfig,
5864
DocLayoutConfig,
5965
Ga4Config,
6066
I18nConfig,
@@ -65,6 +71,8 @@ export type {
6571
RobotsConfig,
6672
SiteConfig,
6773
SiteConfigContributions,
74+
SiteConfigDraft,
75+
SiteConfigFinalizer,
6876
SiteConfigInput,
6977
SiteConfigResolution,
7078
SiteConfigResolver,
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/** A local source selected through the site's URL and locale resolution rules. */
2+
export interface AssetSource {
3+
relPath: string
4+
absPath: string
5+
/** Root-relative URL, without the site's base path. */
6+
publicPath: string
7+
}
8+
9+
export interface PageAssetInput {
10+
document: Document
11+
sourceRelPath: string
12+
/** Resolves original content assets and records dependencies. Generated outputs are not resolver inputs. */
13+
resolveSource: (
14+
element: Element,
15+
url: string,
16+
) => Promise<AssetSource | undefined>
17+
/** Records another content-root-relative input, including a file not yet created. */
18+
dependOn: (relPath: string) => void
19+
/** Await writes before returning. Use immutable content-addressed names within this namespace. */
20+
emit: (fileName: string, data: Uint8Array) => Promise<string>
21+
}
22+
23+
/** Each build/session owns its processors; core handles generated files and invalidation. */
24+
export interface SiteAssets {
25+
/** A unique path segment under /_assets/. */
26+
namespace: string
27+
/** Ordered within a page; different pages may run concurrently. Input methods expire when this call completes. */
28+
processPage: (input: PageAssetInput) => void | Promise<void>
29+
}

‎packages/ts-common/src/site-config-types.ts‎

Lines changed: 35 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,37 @@ import type { ConsentConfig } from './consent-types'
88
import type { SiteLogoConfig } from './logo-types'
99
import type { NavigationConfig } from './navMenu-types'
1010

11-
export interface SiteConfig {
12-
/** Plugin-owned settings, normalized by their configuration contributions. */
13-
extensions: SiteExtensions
11+
/** Settings normalized by the builder before plugin configuration runs. */
12+
export interface CoreSiteConfig {
1413
rootDir: string
1514
contentDir: string
1615
outDir: string
1716
publishDir: string
1817
basePath: string
1918
siteTitle: string
20-
favicon?: string
21-
logo: SiteLogoConfig
22-
docLayout: DocLayoutConfig
23-
style: SiteStyleConfig
2419
html: SiteHtmlConfig
2520
navigation: NavigationConfig
26-
pageToc: PageTocConfig
27-
auth: AuthConfig
2821
scripts: SiteScriptsConfig
2922
sitemap: SitemapConfig
30-
consent: ConsentConfig
31-
analytics: AnalyticsConfig
32-
pagefind: PagefindConfig
33-
preview: PreviewConfig
3423
i18n: I18nConfig
3524
mdx: SiteMdxConfig
3625
}
3726

27+
export interface SiteConfig extends CoreSiteConfig {
28+
/** Plugin-owned settings, normalized by the installed owners. */
29+
extensions: SiteExtensions
30+
favicon?: string
31+
logo?: SiteLogoConfig
32+
docLayout?: DocLayoutConfig
33+
style?: SiteStyleConfig
34+
pageToc?: PageTocConfig
35+
auth?: AuthConfig
36+
consent?: ConsentConfig
37+
analytics?: AnalyticsConfig
38+
pagefind?: PagefindConfig
39+
preview?: PreviewConfig
40+
}
41+
3842
/** Plugins may augment this interface with optional, typed namespaces. */
3943
export interface SiteExtensions {
4044
[plugin: string]: unknown
@@ -140,7 +144,8 @@ export interface I18nConfig {
140144
}
141145

142146
export interface SiteMdxConfig {
143-
highlighter: 'shiki' | 'highlightjs'
147+
/** An optional provider-owned backend identifier. Core does not select an engine. */
148+
highlighter?: string
144149
disableHighlighter: boolean
145150
compileMdAsMdx: boolean
146151
}
@@ -155,9 +160,15 @@ export type SiteConfigInput = DeepPartial<Omit<SiteConfig, 'style'>> & {
155160
style?: SiteStyleConfigInput
156161
}
157162

163+
/** Core fields are ready; plugin sections may still contain partial input. */
164+
export type SiteConfigDraft = CoreSiteConfig &
165+
Omit<SiteConfigInput, keyof CoreSiteConfig | 'extensions'> & {
166+
extensions: DeepPartial<SiteExtensions>
167+
}
168+
158169
/** Inputs for a pure configuration contribution, before build factories run. */
159-
export interface SiteConfigResolution {
160-
config: SiteConfig
170+
export interface SiteConfigResolution<TConfig = SiteConfigDraft> {
171+
config: TConfig
161172
input: SiteConfigInput
162173
file: SiteConfigInput
163174
}
@@ -166,8 +177,14 @@ export type SiteConfigResolver = (
166177
source: SiteConfigResolution,
167178
) => DeepPartial<SiteConfig>
168179

169-
/** All overrides resolve before any plugin derives dependent settings. */
180+
/** Runs after every installed owner's normalizer has completed. */
181+
export type SiteConfigFinalizer = (
182+
source: SiteConfigResolution<SiteConfig>,
183+
) => DeepPartial<SiteConfig>
184+
185+
/** Overrides, normalization, then dependent settings; all run before factories. */
170186
export interface SiteConfigContributions {
171187
resolve?: SiteConfigResolver
172-
finalize?: SiteConfigResolver
188+
normalize?: SiteConfigResolver
189+
finalize?: SiteConfigFinalizer
173190
}

‎packages/ts-common/src/ts-ssg-context.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ export interface PageContext {
2929
pageInfo: PageInfo
3030
navigation?: TsSsgNavigation
3131
outline?: PageOutlineItem[]
32-
theme: ThemeOptions
32+
theme?: ThemeOptions
3333
basePath: string
3434
locale?: string
3535
locales: string[]

0 commit comments

Comments
 (0)