Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
Meta Vens
6f79f4fed9 test: narrow emit return type in componentResources test
All checks were successful
Engine CI / build-and-test (docker) (push) Successful in 3m23s
2026-12-05 01:48:57 +01:00
Meta Vens
3ee1333880 feat: add SHA-256 query hash cache-busting for css and js assets 2026-12-05 01:48:19 +01:00
Meta Vens
500f938179 teardown: pin graph-spa lockfile and drop dead OG section/icon helpers
All checks were successful
Engine CI / build-and-test (docker) (push) Successful in 3m58s
2026-12-03 21:07:01 +01:00
Meta Vens
178f836760 teardown: remove @gamecult/sai, isolate graph-spa deps, clean mount & OG/tagline 2026-12-03 21:01:12 +01:00
Meta Vens
d37427aa3e teardown: remove Sai/InkEmbedder, isolate graph-spa deps, clean mount & OG/tagline 2026-12-03 21:00:45 +01:00
f6bed01377 Guard Pages workflow on github.server_url (#6)
All checks were successful
Engine CI / build-and-test (docker) (push) Successful in 3m25s
2026-11-12 09:43:38 +00:00
3ec9f4b424 Merge pull request 'Latex: let the site choose KaTeX's output mode' (#5) from void/katex-output-option into main
All checks were successful
Engine CI / build-and-test (docker) (push) Successful in 2m32s
2026-11-10 06:19:51 +00:00
22 changed files with 2295 additions and 1511 deletions

View file

@ -33,7 +33,11 @@ jobs:
repository: GameCult/GameCult-Quartz repository: GameCult/GameCult-Quartz
path: GameCult-Quartz path: GameCult-Quartz
# Pages actions exist only on GitHub: the forge runner resolves actions
# from data.forgejo.org, which has no actions/configure-pages, so the job
# failed there. Build always; touch Pages only on the GitHub mirror.
- name: Configure Pages - name: Configure Pages
if: github.server_url == 'https://github.com'
uses: actions/configure-pages@v5 uses: actions/configure-pages@v5
- name: Setup Node - name: Setup Node
@ -56,11 +60,13 @@ jobs:
--outputDir "${{ inputs.output-dir }}" --outputDir "${{ inputs.output-dir }}"
- name: Upload Pages artifact - name: Upload Pages artifact
if: github.server_url == 'https://github.com'
uses: actions/upload-pages-artifact@v3 uses: actions/upload-pages-artifact@v3
with: with:
path: ${{ inputs.output-dir }} path: ${{ inputs.output-dir }}
deploy: deploy:
if: github.server_url == 'https://github.com'
environment: environment:
name: github-pages name: github-pages
url: ${{ steps.deployment.outputs.page_url }} url: ${{ steps.deployment.outputs.page_url }}

View file

@ -16,7 +16,7 @@ Site-specific content, mastheads, sidebars, render hooks, and custom chrome stay
- **Entry points:** `scripts/build-site.mjs` (stage a site repo against this engine), `scripts/build-graph-spa.mjs` (build the shared graph SPA into a consumer), `quartz/graph-spa` (the SPA source) and `.github/workflows/quartz-pages.yml` (the reusable Pages workflow). - **Entry points:** `scripts/build-site.mjs` (stage a site repo against this engine), `scripts/build-graph-spa.mjs` (build the shared graph SPA into a consumer), `quartz/graph-spa` (the SPA source) and `.github/workflows/quartz-pages.yml` (the reusable Pages workflow).
- **Live:** the engine and workflow serve `gamecult-site` and `AetheriaLore`; the graph SPA serves the deployed Mimir and gamecult.org sites under its default `epiphany-graph` asset route. - **Live:** the engine and workflow serve `gamecult-site` and `AetheriaLore`; the graph SPA serves the deployed Mimir and gamecult.org sites under its default `epiphany-graph` asset route.
- **Migrating:** that default route is a compatibility contract. New or migrated consumers pass the `norn-graph` asset paths and `gamecult-norn-graph-root` explicitly. Future sprite staging extends Sai rather than adding a site-local player. - **Migrating:** that default route is a compatibility contract. New or migrated consumers pass the `norn-graph` asset paths and `gamecult-norn-graph-root` explicitly.
## Consumer Repo Shape ## Consumer Repo Shape
@ -74,41 +74,6 @@ and the fullscreen shell. Norn owns graph interaction and rendering. Consumer
sites provide taxonomy, filtering, placement, and presentation through sites provide taxonomy, filtering, placement, and presentation through
`GameCultGraphSpaShell` configuration and overlay styles. `GameCultGraphSpaShell` configuration and overlay styles.
## Shared Interactive Embeds
### `Plugin.InkEmbedder`
Use `Plugin.InkEmbedder()` in a consumer site's emitter list to enable reusable
Ink embeds. The plugin copies Sai's packaged browser assets from `@gamecult/sai`
into the built site's `/static/interactive/` directory and injects the player
CSS and script.
Authors embed stories with plain HTML:
```html
<div
class="sai-player"
data-ink-format="visual-novel"
data-ink-story="/static/interactive/example/story.ink.json"
data-visual-manifest="/static/interactive/example/visual-manifest.json"
data-scene-label="Scene Name"
></div>
```
Supported formats:
- `data-ink-format="raven"` or omitted: cheap interactive-fiction transcript
layout for Raven Collective-style Ink.
- `data-ink-format="visual-novel"`: fixed scene view with bottom dialogue bar,
speaker avatar, and choices/continue controls inside the dialogue surface.
- `data-ink-format="cinematic"`: slide/deck layout with background plates,
captions, and optional references.
The legacy `data-ink-mode` attribute still works. Future sprite staging should
extend Sai rather than inventing another site-local player. Existing
`.aetheria-ink-player` containers are still initialised by Sai as a migration
bridge, but new embeds should use `.sai-player`.
## Shared Components ## Shared Components
### `AutoIndexFolder` ### `AutoIndexFolder`

1252
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -36,11 +36,9 @@
"dependencies": { "dependencies": {
"@clack/prompts": "^0.11.0", "@clack/prompts": "^0.11.0",
"@floating-ui/dom": "^1.7.4", "@floating-ui/dom": "^1.7.4",
"@gamecult/sai": "github:GameCult/Sai#d070159ba575b2ee643f44222e89dcbb7ded7c49",
"@myriaddreamin/rehype-typst": "^0.6.0", "@myriaddreamin/rehype-typst": "^0.6.0",
"@napi-rs/simple-git": "0.1.22", "@napi-rs/simple-git": "0.1.22",
"@tweenjs/tween.js": "^25.0.0", "@tweenjs/tween.js": "^25.0.0",
"@vitejs/plugin-react": "^5.2.0",
"ansi-truncate": "^1.4.0", "ansi-truncate": "^1.4.0",
"async-mutex": "^0.5.0", "async-mutex": "^0.5.0",
"chokidar": "^5.0.0", "chokidar": "^5.0.0",
@ -66,8 +64,6 @@
"preact-render-to-string": "^6.6.5", "preact-render-to-string": "^6.6.5",
"pretty-bytes": "^7.1.0", "pretty-bytes": "^7.1.0",
"pretty-time": "^1.1.0", "pretty-time": "^1.1.0",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"reading-time": "^1.5.0", "reading-time": "^1.5.0",
"rehype-autolink-headings": "^7.1.0", "rehype-autolink-headings": "^7.1.0",
"rehype-citation": "^2.3.1", "rehype-citation": "^2.3.1",
@ -95,7 +91,6 @@
"unified": "^11.0.5", "unified": "^11.0.5",
"unist-util-visit": "^5.1.0", "unist-util-visit": "^5.1.0",
"vfile": "^6.0.3", "vfile": "^6.0.3",
"vite": "^7.3.3",
"workerpool": "^10.0.1", "workerpool": "^10.0.1",
"ws": "^8.19.0", "ws": "^8.19.0",
"yargs": "^18.0.0" "yargs": "^18.0.0"
@ -106,8 +101,6 @@
"@types/js-yaml": "^4.0.9", "@types/js-yaml": "^4.0.9",
"@types/node": "^25.0.10", "@types/node": "^25.0.10",
"@types/pretty-time": "^1.1.5", "@types/pretty-time": "^1.1.5",
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2",
"@types/source-map-support": "^0.5.10", "@types/source-map-support": "^0.5.10",
"@types/ws": "^8.18.1", "@types/ws": "^8.18.1",
"@types/yargs": "^17.0.35", "@types/yargs": "^17.0.35",

View file

@ -263,7 +263,13 @@ async function rebuild(changes: ChangeEvent[], clientRefresh: () => void, buildD
) )
let emittedFiles = 0 let emittedFiles = 0
for (const emitter of cfg.plugins.emitters) { // Run ComponentResources before page/other emitters so staticResources.assetHashes
// is populated regardless of emitter order in quartz.config.ts.
const orderedEmitters = [
...cfg.plugins.emitters.filter((emitter) => emitter.name === "ComponentResources"),
...cfg.plugins.emitters.filter((emitter) => emitter.name !== "ComponentResources"),
]
for (const emitter of orderedEmitters) {
// Try to use partialEmit if available, otherwise assume the output is static // Try to use partialEmit if available, otherwise assume the output is static
const emitFn = emitter.partialEmit ?? emitter.emit const emitFn = emitter.partialEmit ?? emitter.emit
const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents) const emitted = await emitFn(ctx, processedFiles, staticResources, changeEvents)

View file

@ -24,23 +24,28 @@ interface RenderComponents {
} }
const headerRegex = new RegExp(/h[1-6]/) const headerRegex = new RegExp(/h[1-6]/)
function versionedAsset(assetPath: string, hash?: string): string {
return hash ? `${assetPath}?v=${hash}` : assetPath
}
export function pageResources( export function pageResources(
baseDir: FullSlug | RelativeURL, baseDir: FullSlug | RelativeURL,
staticResources: StaticResources, staticResources: StaticResources,
): StaticResources { ): StaticResources {
const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json") const contentIndexPath = joinSegments(baseDir, "static/contentIndex.json")
const contentIndexScript = `const fetchData = fetch("${contentIndexPath}").then(data => data.json())` const contentIndexScript = `const fetchData = fetch("${contentIndexPath}").then(data => data.json())`
const assetHashes = staticResources.assetHashes
const resources: StaticResources = { const resources: StaticResources = {
css: [ css: [
{ {
content: joinSegments(baseDir, "index.css"), content: versionedAsset(joinSegments(baseDir, "index.css"), assetHashes?.css),
}, },
...staticResources.css, ...staticResources.css,
], ],
js: [ js: [
{ {
src: joinSegments(baseDir, "prescript.js"), src: versionedAsset(joinSegments(baseDir, "prescript.js"), assetHashes?.prescript),
loadTime: "beforeDOMReady", loadTime: "beforeDOMReady",
contentType: "external", contentType: "external",
}, },
@ -56,7 +61,7 @@ export function pageResources(
} }
resources.js.push({ resources.js.push({
src: joinSegments(baseDir, "postscript.js"), src: versionedAsset(joinSegments(baseDir, "postscript.js"), assetHashes?.postscript),
loadTime: "afterDOMReady", loadTime: "afterDOMReady",
moduleType: "module", moduleType: "module",
contentType: "external", contentType: "external",

1764
quartz/graph-spa/package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

View file

@ -7,11 +7,14 @@
"build": "vite build --base ./" "build": "vite build --base ./"
}, },
"dependencies": { "dependencies": {
"@vitejs/plugin-react": "^5.1.1", "@vitejs/plugin-react": "^5.2.0",
"react": "^19.2.0", "react": "^19.2.6",
"react-dom": "^19.2.0", "react-dom": "^19.2.6",
"typescript": "^5.9.3", "typescript": "^5.9.3",
"vite": "^7.2.4" "vite": "^7.3.3"
}, },
"devDependencies": {} "devDependencies": {
"@types/react": "^19.2.2",
"@types/react-dom": "^19.2.2"
}
} }

View file

@ -874,14 +874,9 @@ function mountGameCultGraph() {
}) })
} }
function scheduleGameCultGraphMount() { if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => mountGameCultGraph())
} else {
mountGameCultGraph() mountGameCultGraph()
window.setTimeout(mountGameCultGraph, 50)
window.setTimeout(mountGameCultGraph, 300)
window.setTimeout(mountGameCultGraph, 1000)
window.setTimeout(mountGameCultGraph, 2000)
} }
document.addEventListener("nav", () => mountGameCultGraph())
document.addEventListener("nav", scheduleGameCultGraphMount)
document.addEventListener("DOMContentLoaded", scheduleGameCultGraphMount)
scheduleGameCultGraphMount()

View file

@ -0,0 +1,343 @@
import test, { after, before, describe } from "node:test"
import assert from "node:assert/strict"
import { createHash } from "node:crypto"
import fs from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { pathToFileURL } from "node:url"
import esbuild from "esbuild"
import { sassPlugin } from "esbuild-sass-plugin"
import type { QuartzConfig } from "../../cfg"
import type { QuartzComponent } from "../../components/types"
import type { QuartzEmitterPluginInstance } from "../types"
import type { BuildCtx } from "../../util/ctx"
import type { FilePath } from "../../util/path"
import type { StaticResources } from "../../util/resources"
interface LoadedModules {
ComponentResources: () => QuartzEmitterPluginInstance
emitContent: (ctx: BuildCtx, content: []) => Promise<void>
pageResources: (baseDir: string, staticResources: StaticResources) => StaticResources
}
let loaded: LoadedModules
let bundleFile: string
let tempOutputRoot: string
function sha256Hex8(content: string): string {
return createHash("sha256").update(content).digest("hex").slice(0, 8)
}
async function drainEmitted(
emitted: Promise<FilePath[]> | AsyncGenerator<FilePath> | null,
): Promise<void> {
if (!emitted) return
if (Symbol.asyncIterator in emitted) {
for await (const _ of emitted) {
// exhaust async generator
}
} else {
await emitted
}
}
function makeTestCtx(outputDir: string, emitters: QuartzEmitterPluginInstance[]): BuildCtx {
const cfg: QuartzConfig = {
configuration: {
pageTitle: "Test Site",
enableSPA: false,
enablePopovers: false,
analytics: null,
ignorePatterns: [],
defaultDateType: "modified",
baseUrl: "example.com",
locale: "en-US",
theme: {
fontOrigin: "local",
cdnCaching: true,
typography: {
header: "Schibsted Grotesk",
body: "Source Sans Pro",
code: "IBM Plex Mono",
},
colors: {
lightMode: {
light: "#ffffff",
lightgray: "#eeeeee",
gray: "#888888",
darkgray: "#444444",
dark: "#111111",
secondary: "#224488",
tertiary: "#4488aa",
highlight: "rgba(0,0,0,0.05)",
textHighlight: "#ffff0055",
},
darkMode: {
light: "#111111",
lightgray: "#222222",
gray: "#777777",
darkgray: "#cccccc",
dark: "#eeeeee",
secondary: "#6699ff",
tertiary: "#88bbdd",
highlight: "rgba(255,255,255,0.08)",
textHighlight: "#ffff0055",
},
},
},
},
plugins: {
transformers: [],
filters: [],
emitters,
},
}
return {
buildId: "test-build",
argv: {
directory: "content",
verbose: false,
output: outputDir,
serve: false,
watch: false,
port: 8080,
wsPort: 3001,
},
cfg,
allSlugs: [],
allFiles: [],
incremental: false,
}
}
function makeDummyComponentEmitter(opts: {
css: string
beforeDOMLoaded: string
afterDOMLoaded: string
}): QuartzEmitterPluginInstance {
const Component: QuartzComponent = () => null
Component.css = opts.css
Component.beforeDOMLoaded = opts.beforeDOMLoaded
Component.afterDOMLoaded = opts.afterDOMLoaded
return {
name: "DummyComponentEmitter",
getQuartzComponents: () => [Component],
async emit() {
return []
},
}
}
before(async () => {
const repoRoot = process.cwd()
tempOutputRoot = await fs.mkdtemp(path.join(os.tmpdir(), "quartz-component-resources-"))
bundleFile = path.join(
repoRoot,
"quartz",
"plugins",
"emitters",
`.tmp-component-resources-test-${process.pid}.mjs`,
)
await esbuild.build({
stdin: {
contents: `
export { ComponentResources } from "./quartz/plugins/emitters/componentResources"
export { emitContent } from "./quartz/processors/emit"
export { pageResources } from "./quartz/components/renderPage"
`,
resolveDir: repoRoot,
loader: "ts",
},
outfile: bundleFile,
bundle: true,
platform: "node",
format: "esm",
jsx: "automatic",
jsxImportSource: "preact",
packages: "external",
plugins: [
sassPlugin({
type: "css-text",
cssImports: true,
}),
sassPlugin({
filter: /\.inline\.scss$/,
type: "css",
cssImports: true,
}),
{
name: "inline-script-loader",
setup(build) {
build.onLoad({ filter: /\.inline\.(ts|js)$/ }, async (args) => {
let text = await fs.readFile(args.path, "utf8")
text = text.replace("export default", "").replace("export", "")
const transpiled = await esbuild.build({
stdin: {
contents: text,
loader: "ts",
resolveDir: path.dirname(args.path),
sourcefile: args.path,
},
write: false,
bundle: true,
minify: true,
platform: "browser",
format: "esm",
})
return {
contents: transpiled.outputFiles[0].text,
loader: "text",
}
})
},
},
],
})
loaded = (await import(pathToFileURL(bundleFile).href)) as LoadedModules
})
after(async () => {
await fs.rm(bundleFile, { force: true })
await fs.rm(tempOutputRoot, { recursive: true, force: true })
})
describe("asset cache-busting hashes", () => {
test("pageResources appends ?v=<hash> when assetHashes is set and omits it when absent", () => {
const base: StaticResources = {
css: [],
js: [],
additionalHead: [],
}
const unversioned = loaded.pageResources("..", base)
assert.equal(unversioned.css[0].content, "../index.css")
assert.deepEqual(
unversioned.js.filter((j) => j.contentType === "external").map((j) => j.src),
["../prescript.js", "../postscript.js"],
)
const versioned = loaded.pageResources(".", {
...base,
assetHashes: {
css: "11223344",
prescript: "aabbccdd",
postscript: "deadbeef",
},
})
assert.equal(versioned.css[0].content, "./index.css?v=11223344")
assert.deepEqual(
versioned.js.filter((j) => j.contentType === "external").map((j) => j.src),
["./prescript.js?v=aabbccdd", "./postscript.js?v=deadbeef"],
)
})
test("changing CSS or JS changes only the affected 8-hex hash matching emitted file bytes", async () => {
const runVariant = async (
name: string,
opts: { css: string; beforeDOMLoaded: string; afterDOMLoaded: string },
) => {
const outDir = path.join(tempOutputRoot, name)
const plugin = loaded.ComponentResources()
const ctx = makeTestCtx(outDir, [makeDummyComponentEmitter(opts), plugin])
const resources: StaticResources = { css: [], js: [], additionalHead: [] }
await drainEmitted(plugin.emit(ctx, [], resources))
const [cssFile, preFile, postFile] = await Promise.all([
fs.readFile(path.join(outDir, "index.css"), "utf8"),
fs.readFile(path.join(outDir, "prescript.js"), "utf8"),
fs.readFile(path.join(outDir, "postscript.js"), "utf8"),
])
assert.match(resources.assetHashes?.css ?? "", /^[0-9a-f]{8}$/)
assert.match(resources.assetHashes?.prescript ?? "", /^[0-9a-f]{8}$/)
assert.match(resources.assetHashes?.postscript ?? "", /^[0-9a-f]{8}$/)
assert.equal(resources.assetHashes?.css, sha256Hex8(cssFile))
assert.equal(resources.assetHashes?.prescript, sha256Hex8(preFile))
assert.equal(resources.assetHashes?.postscript, sha256Hex8(postFile))
return resources.assetHashes!
}
const base = await runVariant("base", {
css: ".probe { color: #112233; }",
beforeDOMLoaded: "window.__pre = 1;",
afterDOMLoaded: "window.__post = 1;",
})
const cssChanged = await runVariant("css-changed", {
css: ".probe { color: #445566; }",
beforeDOMLoaded: "window.__pre = 1;",
afterDOMLoaded: "window.__post = 1;",
})
assert.notEqual(cssChanged.css, base.css)
assert.equal(cssChanged.prescript, base.prescript)
assert.equal(cssChanged.postscript, base.postscript)
const preChanged = await runVariant("pre-changed", {
css: ".probe { color: #112233; }",
beforeDOMLoaded: "window.__pre = 2;",
afterDOMLoaded: "window.__post = 1;",
})
assert.equal(preChanged.css, base.css)
assert.notEqual(preChanged.prescript, base.prescript)
assert.equal(preChanged.postscript, base.postscript)
const postChanged = await runVariant("post-changed", {
css: ".probe { color: #112233; }",
beforeDOMLoaded: "window.__pre = 1;",
afterDOMLoaded: "window.__post = 2;",
})
assert.equal(postChanged.css, base.css)
assert.equal(postChanged.prescript, base.prescript)
assert.notEqual(postChanged.postscript, base.postscript)
})
test("emitContent populates assetHashes before page emitters even when ComponentResources is last", async () => {
const outDir = path.join(tempOutputRoot, "ordering")
let observedPageResources: StaticResources | undefined
const pageLikeEmitter: QuartzEmitterPluginInstance = {
name: "PageLikeEmitter",
async emit(_ctx, _content, resources) {
observedPageResources = loaded.pageResources("..", resources)
return [] as FilePath[]
},
}
// Place ComponentResources LAST in cfg.plugins.emitters
const ctx = makeTestCtx(outDir, [pageLikeEmitter, loaded.ComponentResources()])
await loaded.emitContent(ctx, [])
const [cssFile, preFile, postFile] = await Promise.all([
fs.readFile(path.join(outDir, "index.css"), "utf8"),
fs.readFile(path.join(outDir, "prescript.js"), "utf8"),
fs.readFile(path.join(outDir, "postscript.js"), "utf8"),
])
assert.ok(observedPageResources)
assert.equal(observedPageResources.css[0].content, `../index.css?v=${sha256Hex8(cssFile)}`)
assert.deepEqual(
observedPageResources.js.filter((j) => j.contentType === "external").map((j) => j.src),
[`../prescript.js?v=${sha256Hex8(preFile)}`, `../postscript.js?v=${sha256Hex8(postFile)}`],
)
})
test("ComponentResources.partialEmit preserves assetHashes onto fresh staticResources", async () => {
const outDir = path.join(tempOutputRoot, "partial")
const plugin = loaded.ComponentResources()
const ctx = makeTestCtx(outDir, [plugin])
const initialResources: StaticResources = { css: [], js: [], additionalHead: [] }
await drainEmitted(plugin.emit(ctx, [], initialResources))
const freshResources: StaticResources = { css: [], js: [], additionalHead: [] }
const partial = plugin.partialEmit!(ctx, [], freshResources, [])
assert.ok(partial && Symbol.asyncIterator in partial)
await drainEmitted(partial)
assert.deepEqual(freshResources.assetHashes, initialResources.assetHashes)
})
})

View file

@ -1,4 +1,6 @@
import { createHash } from "crypto"
import { FullSlug, joinSegments } from "../../util/path" import { FullSlug, joinSegments } from "../../util/path"
import { AssetHashes } from "../../util/resources"
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
// @ts-ignore // @ts-ignore
@ -265,12 +267,18 @@ function addGlobalPageResources(ctx: BuildCtx, componentResources: ComponentReso
} }
} }
// This emitter should not update the `resources` parameter. If it does, partial function hashAssetContent(content: string): string {
// rebuilds may not work as expected. return createHash("sha256").update(content).digest("hex").slice(0, 8)
}
// Populates `resources.assetHashes` on full emit and caches `lastHashes` so
// incremental `partialEmit` rebuilds preserve the same hashes on fresh `resources`.
export const ComponentResources: QuartzEmitterPlugin = () => { export const ComponentResources: QuartzEmitterPlugin = () => {
let lastHashes: AssetHashes | undefined
return { return {
name: "ComponentResources", name: "ComponentResources",
async *emit(ctx, _content, _resources) { async *emit(ctx, _content, resources) {
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
// component specific scripts and styles // component specific scripts and styles
const componentResources = getComponentResources(ctx) const componentResources = getComponentResources(ctx)
@ -335,23 +343,33 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
joinScripts(componentResources.afterDOMLoaded), joinScripts(componentResources.afterDOMLoaded),
]) ])
const cssContent = transform({
filename: "index.css",
code: Buffer.from(stylesheet),
minify: true,
targets: {
safari: (15 << 16) | (6 << 8), // 15.6
ios_saf: (15 << 16) | (6 << 8), // 15.6
edge: 115 << 16,
firefox: 102 << 16,
chrome: 109 << 16,
},
include: Features.MediaQueries,
}).code.toString()
const hashes: AssetHashes = {
css: hashAssetContent(cssContent),
prescript: hashAssetContent(prescript),
postscript: hashAssetContent(postscript),
}
lastHashes = hashes
resources.assetHashes = hashes
yield write({ yield write({
ctx, ctx,
slug: "index" as FullSlug, slug: "index" as FullSlug,
ext: ".css", ext: ".css",
content: transform({ content: cssContent,
filename: "index.css",
code: Buffer.from(stylesheet),
minify: true,
targets: {
safari: (15 << 16) | (6 << 8), // 15.6
ios_saf: (15 << 16) | (6 << 8), // 15.6
edge: 115 << 16,
firefox: 102 << 16,
chrome: 109 << 16,
},
include: Features.MediaQueries,
}).code.toString(),
}) })
yield write({ yield write({
@ -368,6 +386,10 @@ export const ComponentResources: QuartzEmitterPlugin = () => {
content: postscript, content: postscript,
}) })
}, },
async *partialEmit() {}, async *partialEmit(_ctx, _content, resources) {
if (lastHashes) {
resources.assetHashes = lastHashes
}
},
} }
} }

View file

@ -7,7 +7,6 @@ export { Assets } from "./assets"
export { Static } from "./static" export { Static } from "./static"
export { Favicon } from "./favicon" export { Favicon } from "./favicon"
export { ComponentResources } from "./componentResources" export { ComponentResources } from "./componentResources"
export { InkEmbedder } from "./inkEmbedder"
export { NotFoundPage } from "./404" export { NotFoundPage } from "./404"
export { CNAME } from "./cname" export { CNAME } from "./cname"
export { CustomOgImages } from "./ogImage" export { CustomOgImages } from "./ogImage"

View file

@ -1,73 +0,0 @@
import { QuartzEmitterPlugin } from "../types"
import { FilePath, joinSegments } from "../../util/path"
import { createRequire } from "module"
import fs from "fs"
import path from "path"
export interface InkEmbedderOptions {
scriptSrc?: string
styleSrc?: string
runtimeSrc?: string
}
const defaultOptions: Required<InkEmbedderOptions> = {
scriptSrc: "/static/interactive/sai.js",
styleSrc: "/static/interactive/sai.css",
runtimeSrc: "/static/interactive/ink.js",
}
const require = createRequire(import.meta.url)
function resolveSaiDistPath(filename: string) {
return path.join(path.dirname(require.resolve("@gamecult/sai/sai.js")), filename)
}
function localStaticDest(outputRoot: string, resourcePath: string) {
if (!resourcePath.startsWith("/static/")) return null
return joinSegments(outputRoot, resourcePath.slice(1)) as FilePath
}
async function copySaiAsset(outputRoot: string, resourcePath: string, filename: string) {
const dest = localStaticDest(outputRoot, resourcePath)
if (!dest) return null
await fs.promises.mkdir(path.dirname(dest), { recursive: true })
await fs.promises.copyFile(resolveSaiDistPath(filename), dest)
return dest
}
export const InkEmbedder: QuartzEmitterPlugin<InkEmbedderOptions> = (opts) => {
const options = { ...defaultOptions, ...opts }
return {
name: "InkEmbedder",
async *emit({ argv }) {
const copied = await Promise.all([
copySaiAsset(argv.output, options.scriptSrc, "sai.js"),
copySaiAsset(argv.output, options.styleSrc, "sai.css"),
copySaiAsset(argv.output, options.runtimeSrc, "ink.js"),
])
for (const dest of copied) {
if (dest) yield dest
}
},
async *partialEmit() {},
externalResources: () => ({
css: [
{
content: options.styleSrc,
spaPreserve: true,
},
],
js: [
{
src: options.scriptSrc,
loadTime: "afterDOMReady",
contentType: "external",
spaPreserve: true,
},
],
}),
}
}

View file

@ -1,7 +1,7 @@
import { QuartzEmitterPlugin } from "../types" import { QuartzEmitterPlugin } from "../types"
import { i18n } from "../../i18n" import { i18n } from "../../i18n"
import { unescapeHTML } from "../../util/escape" import { unescapeHTML } from "../../util/escape"
import { FullSlug, getFileExtension, isAbsoluteURL, joinSegments, QUARTZ } from "../../util/path" import { FullSlug, getFileExtension, isAbsoluteURL } from "../../util/path"
import { ImageOptions, SocialImageOptions, defaultImage, getSatoriFonts } from "../../util/og" import { ImageOptions, SocialImageOptions, defaultImage, getSatoriFonts } from "../../util/og"
import sharp from "sharp" import sharp from "sharp"
import satori, { SatoriOptions } from "satori" import satori, { SatoriOptions } from "satori"
@ -12,12 +12,12 @@ import { BuildCtx } from "../../util/ctx"
import { QuartzPluginData } from "../vfile" import { QuartzPluginData } from "../vfile"
import fs from "node:fs/promises" import fs from "node:fs/promises"
import { styleText } from "util" import { styleText } from "util"
import { SiteSocialMetadata } from "../../util/siteOg"
import { import {
resolveSocialDeck, resolveSocialDeck,
resolveSocialDescription, resolveSocialDescription,
resolveSocialImage, resolveSocialImage,
resolveSocialMetadata, resolveSocialMetadata,
resolveSocialSection,
socialImageLocalPath, socialImageLocalPath,
socialImageUrl, socialImageUrl,
} from "../../util/social" } from "../../util/social"
@ -51,21 +51,13 @@ function imageMimeType(filePath: string) {
* @param opts options for generating image * @param opts options for generating image
*/ */
async function generateSocialImage( async function generateSocialImage(
{ cfg, description, deck, section, fonts, title, fileData }: ImageOptions, { cfg, description, deck, fonts, title, fileData }: ImageOptions,
userOpts: SocialImageOptions, userOpts: SocialImageOptions,
socialMetadata: SiteSocialMetadata = resolveSocialMetadata(fileData),
): Promise<Readable> { ): Promise<Readable> {
const { width, height } = userOpts const { width, height } = userOpts
const iconPath = joinSegments(QUARTZ, "static", "icon.png")
let iconBase64: string | undefined = undefined
let imageBase64: string | undefined = undefined let imageBase64: string | undefined = undefined
try {
const iconData = await fs.readFile(iconPath)
iconBase64 = `data:image/png;base64,${iconData.toString("base64")}`
} catch (err) {
console.warn(styleText("yellow", `Warning: Could not find icon at ${iconPath}`))
}
const socialMetadata = resolveSocialMetadata(fileData)
const socialImage = resolveSocialImage(fileData, socialMetadata) const socialImage = resolveSocialImage(fileData, socialMetadata)
const localImagePath = socialImageLocalPath(fileData, socialImage) const localImagePath = socialImageLocalPath(fileData, socialImage)
@ -91,10 +83,8 @@ async function generateSocialImage(
title, title,
description, description,
deck, deck,
section,
fonts, fonts,
fileData, fileData,
iconBase64,
imageBase64, imageBase64,
}) })
@ -129,21 +119,20 @@ async function processOgImage(
fileData, fileData,
unescapeHTML(i18n(cfg.locale).propertyDefaults.description), unescapeHTML(i18n(cfg.locale).propertyDefaults.description),
) )
const siteMetadata = resolveSocialMetadata(fileData) const socialMetadata = resolveSocialMetadata(fileData)
const deck = resolveSocialDeck(fileData, description, siteMetadata) const deck = resolveSocialDeck(fileData, description, socialMetadata)
const section = resolveSocialSection(fileData, siteMetadata)
const stream = await generateSocialImage( const stream = await generateSocialImage(
{ {
title, title,
description, description,
deck, deck,
section,
fonts, fonts,
cfg, cfg,
fileData, fileData,
}, },
fullOptions, fullOptions,
socialMetadata,
) )
return write({ return write({
@ -204,11 +193,15 @@ export const CustomOgImages: QuartzEmitterPlugin<Partial<SocialImageOptions>> =
const generatedOgImagePath = useGeneratedCard const generatedOgImagePath = useGeneratedCard
? `https://${baseUrl}/${pageData.slug!}-og-image.webp` ? `https://${baseUrl}/${pageData.slug!}-og-image.webp`
: undefined : undefined
const pageSiteMetadata = resolveSocialMetadata(pageData)
const pageSocialImage = resolveSocialImage(pageData, pageSiteMetadata)
const imageFromMetadata = socialImageUrl(baseUrl, pageData, pageSocialImage)
const defaultOgImagePath = `https://${baseUrl}/static/og-image.png` const defaultOgImagePath = `https://${baseUrl}/static/og-image.png`
const ogImagePath = generatedOgImagePath ?? imageFromMetadata ?? defaultOgImagePath const ogImagePath =
generatedOgImagePath ??
socialImageUrl(
baseUrl,
pageData,
resolveSocialImage(pageData, resolveSocialMetadata(pageData)),
) ??
defaultOgImagePath
const ogImageMimeType = imageMimeType(ogImagePath) const ogImageMimeType = imageMimeType(ogImagePath)
return ( return (
<> <>

View file

@ -107,3 +107,35 @@ test("extractDescriptionText keeps the first paragraph when it is normal content
"This first paragraph is the actual summary, not decorative throat-clearing.", "This first paragraph is the actual summary, not decorative throat-clearing.",
) )
}) })
test("extractDescriptionText keeps an unquoted emphasized opening paragraph", () => {
const tree: Root = {
type: "root",
children: [
{
type: "element",
tagName: "h1",
properties: {},
children: [{ type: "text", value: "Why Aetheria Went Quiet" }],
},
{
type: "element",
tagName: "p",
properties: {},
children: [
{
type: "element",
tagName: "em",
properties: {},
children: [{ type: "text", value: "This opening note is emphasized, not a tagline." }],
},
],
},
],
}
assert.equal(
extractDescriptionText(tree, "Why Aetheria Went Quiet"),
"This opening note is emphasized, not a tagline.",
)
})

View file

@ -2,6 +2,7 @@ import { Element, Root as HTMLRoot, RootContent } from "hast"
import { toString } from "hast-util-to-string" import { toString } from "hast-util-to-string"
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import { escapeHTML } from "../../util/escape" import { escapeHTML } from "../../util/escape"
import { isStandaloneTagline } from "../../util/social"
export interface Options { export interface Options {
descriptionLength: number descriptionLength: number
@ -36,23 +37,6 @@ function isMeaningfulNode(node: RootContent): boolean {
return normalizeWhitespace(toString(node)).length > 0 return normalizeWhitespace(toString(node)).length > 0
} }
function isStandalonePreviewTagline(node: RootContent): boolean {
if (!isElementNode(node) || node.tagName !== "p") {
return false
}
const meaningfulChildren = node.children.filter(
(child) => !(child.type === "text" && normalizeWhitespace(child.value).length === 0),
)
if (meaningfulChildren.length !== 1) {
return false
}
const onlyChild = meaningfulChildren[0]
return isElementNode(onlyChild) && ["em", "strong"].includes(onlyChild.tagName)
}
function isStructuredMetadataParagraph(node: RootContent): boolean { function isStructuredMetadataParagraph(node: RootContent): boolean {
if (!isElementNode(node) || node.tagName !== "p") { if (!isElementNode(node) || node.tagName !== "p") {
return false return false
@ -80,7 +64,7 @@ export function extractDescriptionText(tree: HTMLRoot, pageTitle?: string): stri
startIdx++ startIdx++
} }
if (startIdx < children.length && pageTitle && isStandalonePreviewTagline(children[startIdx])) { if (startIdx < children.length && pageTitle && isStandaloneTagline(children[startIdx])) {
startIdx++ startIdx++
} }

View file

@ -1,5 +1,6 @@
import { PerfTimer } from "../util/perf" import { PerfTimer } from "../util/perf"
import { getStaticResourcesFromPlugins } from "../plugins" import { getStaticResourcesFromPlugins } from "../plugins"
import { QuartzEmitterPluginInstance } from "../plugins/types"
import { ProcessedContent } from "../plugins/vfile" import { ProcessedContent } from "../plugins/vfile"
import { QuartzLogger } from "../util/log" import { QuartzLogger } from "../util/log"
import { trace } from "../util/trace" import { trace } from "../util/trace"
@ -15,36 +16,49 @@ export async function emitContent(ctx: BuildCtx, content: ProcessedContent[]) {
let emittedFiles = 0 let emittedFiles = 0
const staticResources = getStaticResourcesFromPlugins(ctx) const staticResources = getStaticResourcesFromPlugins(ctx)
await Promise.all(
cfg.plugins.emitters.map(async (emitter) => { const runEmitter = async (emitter: QuartzEmitterPluginInstance) => {
try { try {
const emitted = await emitter.emit(ctx, content, staticResources) const emitted = await emitter.emit(ctx, content, staticResources)
if (Symbol.asyncIterator in emitted) { if (Symbol.asyncIterator in emitted) {
// Async generator case // Async generator case
for await (const file of emitted) { for await (const file of emitted) {
emittedFiles++ emittedFiles++
if (ctx.argv.verbose) { if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`) console.log(`[emit:${emitter.name}] ${file}`)
} else { } else {
log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) log.updateText(`${emitter.name} -> ${styleText("gray", file)}`)
} }
} }
} else { } else {
// Array case // Array case
emittedFiles += emitted.length emittedFiles += emitted.length
for (const file of emitted) { for (const file of emitted) {
if (ctx.argv.verbose) { if (ctx.argv.verbose) {
console.log(`[emit:${emitter.name}] ${file}`) console.log(`[emit:${emitter.name}] ${file}`)
} else { } else {
log.updateText(`${emitter.name} -> ${styleText("gray", file)}`) log.updateText(`${emitter.name} -> ${styleText("gray", file)}`)
}
} }
} }
} catch (err) {
trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error)
} }
}), } catch (err) {
trace(`Failed to emit from plugin \`${emitter.name}\``, err as Error)
}
}
// Run ComponentResources before page/other emitters so staticResources.assetHashes
// is populated regardless of emitter order in quartz.config.ts.
const componentResourceEmitters = cfg.plugins.emitters.filter(
(emitter) => emitter.name === "ComponentResources",
) )
const otherEmitters = cfg.plugins.emitters.filter(
(emitter) => emitter.name !== "ComponentResources",
)
for (const emitter of componentResourceEmitters) {
await runEmitter(emitter)
}
await Promise.all(otherEmitters.map(runEmitter))
log.end(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince()}`) log.end(`Emitted ${emittedFiles} files to \`${argv.output}\` in ${perf.timeSince()}`)
} }

View file

@ -137,7 +137,6 @@ export type SocialImageOptions = {
imageStructure: ( imageStructure: (
options: ImageOptions & { options: ImageOptions & {
userOpts: UserOpts userOpts: UserOpts
iconBase64?: string
imageBase64?: string imageBase64?: string
}, },
) => JSXInternal.Element ) => JSXInternal.Element
@ -158,10 +157,6 @@ export type ImageOptions = {
* short deck/tagline to use inside the image card * short deck/tagline to use inside the image card
*/ */
deck: string deck: string
/**
* section label for the card
*/
section?: string
/** /**
* header + body font to be used when generating satori image (as promise to work around sync in component) * header + body font to be used when generating satori image (as promise to work around sync in component)
*/ */

View file

@ -61,10 +61,17 @@ export function CSSResourceToStyleElement(resource: CSSResource, preserve?: bool
} }
} }
export interface AssetHashes {
css?: string
prescript?: string
postscript?: string
}
export interface StaticResources { export interface StaticResources {
css: CSSResource[] css: CSSResource[]
js: JSResource[] js: JSResource[]
additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[] additionalHead: (JSX.Element | ((pageData: QuartzPluginData) => JSX.Element))[]
assetHashes?: AssetHashes
} }
export type StringResource = string | string[] | undefined export type StringResource = string | string[] | undefined

View file

@ -26,7 +26,7 @@ function stripSurroundingQuotes(value: string) {
.trim() .trim()
} }
function isStandaloneTagline(node: RootContent) { export function isStandaloneTagline(node: RootContent): boolean {
if (!isElementNode(node) || node.tagName !== "p") { if (!isElementNode(node) || node.tagName !== "p") {
return false return false
} }
@ -44,7 +44,7 @@ function isStandaloneTagline(node: RootContent) {
return taglinePattern.test(normalizeWhitespace(toString(child))) return taglinePattern.test(normalizeWhitespace(toString(child)))
} }
function extractTopTagline(root?: HtmlRoot): string | undefined { export function extractTopTagline(root?: HtmlRoot): string | undefined {
if (!root) { if (!root) {
return undefined return undefined
} }
@ -173,24 +173,6 @@ export function resolveSocialDeck(
return description return description
} }
export function resolveSocialSection(
fileData: QuartzPluginData,
siteMetadata = resolveSiteSocialMetadata(fileData),
): string {
if (
typeof fileData.frontmatter?.socialSection === "string" &&
fileData.frontmatter.socialSection
) {
return fileData.frontmatter.socialSection.trim()
}
if (siteMetadata.section && siteMetadata.section.trim().length > 0) {
return siteMetadata.section.trim()
}
return ""
}
export function resolveSocialImage( export function resolveSocialImage(
fileData: QuartzPluginData, fileData: QuartzPluginData,
siteMetadata = resolveSiteSocialMetadata(fileData), siteMetadata = resolveSiteSocialMetadata(fileData),

View file

@ -40,20 +40,6 @@ async function exists(targetPath) {
} }
} }
async function linkNodeModules(graphRoot) {
const source = path.join(engineRoot, "node_modules")
const dest = path.join(graphRoot, "node_modules")
if (!(await exists(source))) {
throw new Error(
"GameCult-Quartz dependencies are missing. Run `npm ci` in the GameCult-Quartz repo first.",
)
}
await fs.rm(dest, { recursive: true, force: true })
await fs.symlink(source, dest, "junction")
}
async function prepareNorn(nornRoot) { async function prepareNorn(nornRoot) {
const viewerRoot = path.join(nornRoot, "web", "norn-viewer") const viewerRoot = path.join(nornRoot, "web", "norn-viewer")
const revisionPath = path.join(engineRoot, "quartz", "graph-spa", "norn-revision.txt") const revisionPath = path.join(engineRoot, "quartz", "graph-spa", "norn-revision.txt")
@ -186,7 +172,10 @@ async function main() {
} }
await buildNorn(norn) await buildNorn(norn)
await linkNodeModules(graphRoot) const vitePath = path.join(graphRoot, "node_modules", "vite", "bin", "vite.js")
if (!(await exists(vitePath))) {
throw new Error(`Graph SPA dependencies are missing. Run 'npm ci' in '${graphRoot}'.`)
}
await runProcess( await runProcess(
process.execPath, process.execPath,
["./node_modules/vite/bin/vite.js", "build", "--base", "./"], ["./node_modules/vite/bin/vite.js", "build", "--base", "./"],

View file

@ -74,7 +74,7 @@ async function copyEngineScaffold(runtimeRoot) {
recursive: true, recursive: true,
filter: (candidate) => { filter: (candidate) => {
const relative = path.relative(engineRoot, candidate).split(path.sep).join("/") const relative = path.relative(engineRoot, candidate).split(path.sep).join("/")
return relative !== "quartz/graph-spa/node_modules" return relative !== "quartz/graph-spa"
}, },
}) })
} else { } else {