From 810dcaa97179aedce425a31f06d4fb08233805bb Mon Sep 17 00:00:00 2001 From: Xavier Lacot Date: Mon, 23 Nov 2026 11:11:46 +0100 Subject: [PATCH 1/3] Add a JSON-LD playground to the demo website, with a menu between it and the validator --- .castor/website.php | 18 +- CONTRIBUTING.md | 7 +- docs/json-ld.md | 3 + website/README.md | 51 ++- .../controllers/playground_controller.js | 305 ++++++++++++++++++ .../assets/controllers/result_controller.js | 56 ++-- website/assets/editor.js | 98 ++++++ website/assets/jsonLd.js | 99 ++++++ website/assets/loadUrl.js | 101 ++++++ website/assets/permalink.js | 105 ++++++ website/assets/php.js | 38 ++- website/assets/playground.js | 8 + website/assets/playgroundExamples.js | 190 +++++++++++ website/assets/styles/app.css | 19 ++ website/bin/playground.php | 133 ++++++++ website/package.json | 2 +- website/public/index.html | 7 +- website/public/playground/index.html | 162 ++++++++++ .../src/JsonLd/PreloadedDocumentLoader.php | 98 ++++++ website/templates/result.html.twig | 21 +- website/tests/loadUrl.test.mjs | 122 +++++++ website/tests/permalink.test.mjs | 73 +++++ website/tests/playground.test.mjs | 242 ++++++++++++++ 23 files changed, 1889 insertions(+), 69 deletions(-) create mode 100644 website/assets/controllers/playground_controller.js create mode 100644 website/assets/editor.js create mode 100644 website/assets/jsonLd.js create mode 100644 website/assets/loadUrl.js create mode 100644 website/assets/permalink.js create mode 100644 website/assets/playground.js create mode 100644 website/assets/playgroundExamples.js create mode 100644 website/bin/playground.php create mode 100644 website/public/playground/index.html create mode 100644 website/src/JsonLd/PreloadedDocumentLoader.php create mode 100644 website/tests/loadUrl.test.mjs create mode 100644 website/tests/permalink.test.mjs create mode 100644 website/tests/playground.test.mjs diff --git a/.castor/website.php b/.castor/website.php index 7d92ed32d..e36352639 100644 --- a/.castor/website.php +++ b/.castor/website.php @@ -30,8 +30,9 @@ use Symfony\Component\Console\Input\InputOption; -// The demo website: a static page, in website/public, that audits a document -// with the validator, run by PHP built as WebAssembly. See website/README.md. +// The demo website: two static pages, in website/public, that audit a document +// with the validator, and run the JSON-LD algorithms on one, with PHP built as +// WebAssembly. See website/README.md. #[AsTask(description: 'Installs the dependencies of the demo website')] function install(): void @@ -75,7 +76,7 @@ function build( ])); // What is embedded takes some of the memory of the WebAssembly module: - // only what bin/audit.php reads + // only what bin/audit.php and bin/playground.php read fs()->mirror($website, $app, finder() ->in(["{$website}/assets/images", "{$website}/bin", "{$website}/src", "{$website}/templates", "{$website}/vendor"]) // Composer copies the directories of the repository that Git ignores too @@ -94,7 +95,13 @@ function check(): void io()->title('Checking the website'); check_stack(wasmStack()); - test_page('website/tests/page.test.mjs', 'website/tests/format.test.mjs'); + test_page( + 'website/tests/page.test.mjs', + 'website/tests/format.test.mjs', + 'website/tests/loadUrl.test.mjs', + 'website/tests/permalink.test.mjs', + 'website/tests/playground.test.mjs', + ); } #[AsTask(description: 'Serves the demo website')] @@ -131,7 +138,8 @@ function wasmStack(): Stack ->php('8.5.12') // What the library, Twig and league/commonmark require ->extensions('ctype', 'dom', 'filter', 'libxml', 'mbstring') - // Filled by build(), assets/php.js runs /app/bin/audit.php + // Filled by build(), assets/php.js runs /app/bin/audit.php and + // /app/bin/playground.php ->embed('website/build/app', at: '/app') ->targets(Target::Web) ->outputDir('website/public/build') diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9ff857bc6..27e5d42dc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -154,12 +154,13 @@ The latest figures, and what each of them measures, are in [BENCHMARKS.md](BENCH ### Demo website -These commands build the [demo website](website/README.md), that runs the validator in the browser: +These commands build the [demo website](website/README.md), that runs the validator and the JSON-LD +algorithms in the browser: Command | Description ---- | ----- -`castor website:build` | Builds the demo website: its assets, and PHP as WebAssembly with the validator -`castor website:check` | Checks, in node, that what is built boots, and audits a document +`castor website:build` | Builds the demo website: its assets, and PHP as WebAssembly with the library +`castor website:check` | Checks, in node, that what is built boots, audits a document, and runs the JSON-LD algorithms `castor website:serve` | Serves the demo website ### Vocabulary generation diff --git a/docs/json-ld.md b/docs/json-ld.md index 4fe44865f..9b91e2889 100644 --- a/docs/json-ld.md +++ b/docs/json-ld.md @@ -11,6 +11,9 @@ The library implements the W3C - [Deserialization to RDF](https://www.w3.org/TR/json-ld11-api/#deserialize-json-ld-to-rdf-algorithm) (`toRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter` - [Serialization from RDF](https://www.w3.org/TR/json-ld11-api/#serialize-rdf-as-json-ld-algorithm) (`fromRdf`): `JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter` +> [!TIP] +> Try them in your browser, in the [JSON-LD playground](https://structured-data-validator.jolicode.com/playground/). + ## Usage Create an instance of the algorithm and pass it the JSON-LD document you want to convert. diff --git a/website/README.md b/website/README.md index 96af4a32c..f2249d1da 100644 --- a/website/README.md +++ b/website/README.md @@ -3,12 +3,16 @@ > [!TIP] > This demo website is deployed under https://structured-data-validator.jolicode.com/ -A static page that audits a document with the validator, in the browser: PHP is built as -WebAssembly, with [lyrixx/php-wasm-builder](https://github.com/lyrixx/php-wasm-builder), and the -library of this repository embedded in it. GitHub Pages serves `public/`, deployed from `main` by +Two static pages, that run the library in the browser: PHP is built as WebAssembly, with +[lyrixx/php-wasm-builder](https://github.com/lyrixx/php-wasm-builder), and the library of this +repository embedded in it. GitHub Pages serves `public/`, deployed from `main` by `.github/workflows/website.yml`. -It comes from +- The **validator**, at `/`, audits a document. +- The **JSON-LD playground**, at `/playground/`, runs the JSON-LD algorithms on a document: expand, + compact, flatten, frame, to RDF and from RDF. + +The validator comes from [jolicode/structured-data-validator-demo](https://github.com/jolicode/structured-data-validator-demo), without its server: the editor and the tree of the properties are its ones, with another look. Fetching a URL needs a server, and is not here: a page can not read another website. Pretty-printing @@ -17,14 +21,43 @@ as its `bin/format-document.js` does in node. ## How it works +`assets/php.js` loads PHP, and runs a script of `bin/`: the request is on its standard input, and its +answer on its standard output, as JSON. + +### The validator + - `public/index.html` is the homepage. `assets/app.js` gives the document of its form, or one of `assets/examples.js`, to PHP, and shows what it answers in place of the form. - `bin/audit.php` is what PHP runs: it audits the document, and renders `templates/result.html.twig`, the editor and the result, with Twig. -- `assets/php.js` loads PHP, and runs `bin/audit.php`. -- The footer of the homepage is the JoliCode open-source one, - [jolicode/oss-theme](https://github.com/jolicode/oss-theme): `castor website:build` downloads it - to `public/build/joli-footer.html`, and the homepage loads it. +- The "Open in playground" button of the result, shown for a JSON-LD document, opens the playground + with it. + +### The playground + +- `public/playground/index.html` is the page, and `assets/controllers/playground_controller.js` what + runs it: the algorithm of the selected tab runs again as the visitor types, on the document, with + the context or the frame it needs, and the options it reads. +- `bin/playground.php` is what PHP runs: an algorithm, on what it is given. It answers with the + output, or the error code of the specification. +- `assets/jsonLd.js` loads the remote contexts. PHP has no network in the browser: when a document + needs a context that is not there, `bin/playground.php` answers that it is missing, + `assets/loadUrl.js` fetches it, and PHP is asked again with it. The website of the context has to + allow it, with CORS headers. The schema.org context is the one the library ships, and is never + fetched. +- `assets/permalink.js` writes the state of the page (the tab, the documents, the options) in the + fragment of its URL: the "Copy link" button copies a link that opens the page as it is. +- `assets/playgroundExamples.js` holds the examples. + +Canonicalization (RDFC-1.0) is not there: the library does not implement it. + +### Both + +- `assets/editor.js` is the CodeMirror editor of both pages. +- The menu is written in each page, and in `templates/result.html.twig`: there is no layout to + share it. The links are relative: the website works under any path. +- The footer is the JoliCode open-source one, [jolicode/oss-theme](https://github.com/jolicode/oss-theme): + `castor website:build` downloads it to `public/build/joli-footer.html`, and the pages load it. ## Build it @@ -40,3 +73,5 @@ Command | Description `composer.json` declares the parent directory as a path repository: the website is built with the code of the working directory, not with a release. Run `castor website:build` again after a change: only the last step of the build of PHP runs again. + +A test file of `tests/` runs once it is listed in the `check()` task. diff --git a/website/assets/controllers/playground_controller.js b/website/assets/controllers/playground_controller.js new file mode 100644 index 000000000..2bcb1d830 --- /dev/null +++ b/website/assets/controllers/playground_controller.js @@ -0,0 +1,305 @@ +import { Controller } from "@hotwired/stimulus"; +import { createEditor } from "../editor.js"; +import { OPTIONS, createJsonLdProcessor } from "../jsonLd.js"; +import { UNREADABLE, loadUrl } from "../loadUrl.js"; +import { decodeState, encodeState, normalizeState } from "../permalink.js"; +import { runPlayground } from "../php.js"; +import { DEFAULT_EXAMPLE, examples } from "../playgroundExamples.js"; + +// Typing runs the algorithm again, once the visitor pauses +const RUN_DELAY = 300; + +// A longer state is not written in the URL: a browser, or what the link is +// pasted in, cuts it +const MAX_FRAGMENT_LENGTH = 32_000; + +const OUTPUT_LABELS = { + expand: "Expanded document", + compact: "Compacted document", + flatten: "Flattened document", + frame: "Framed document", + toRdf: "RDF dataset, as N-Quads", + fromRdf: "JSON-LD document, from RDF", +}; + +// A context is served as JSON-LD by content negotiation +const load = async (url) => { + const answer = await loadUrl(url, { accept: "application/ld+json, application/json;q=0.9" }); + + return answer.error === UNREADABLE + ? { error: "Your browser could not read it: its website has to allow it with CORS headers, and to be reachable." } + : answer; +}; + +export default class extends Controller { + static targets = [ + "contextEditor", + "contextLabel", + "contextPanel", + "copyLink", + "copyOutput", + "documentEditor", + "documentLabel", + "error", + "frameEditor", + "framePanel", + "option", + "options", + "outputEditor", + "outputLabel", + "outputPanel", + "status", + "tab", + ]; + + async connect() { + this.process = createJsonLdProcessor({ run: runPlayground, load }); + this.state = normalizeState(examples[DEFAULT_EXAMPLE]); + + this.editors = { + // The document of every algorithm but one, that reads N-Quads + document: createEditor({ + parent: this.documentEditorTarget, + label: "Document", + onChange: (value) => this.edit(this.state.algorithm === "fromRdf" ? "nquads" : "document", value), + }), + context: createEditor({ + parent: this.contextEditorTarget, + label: "Context", + onChange: (value) => this.edit("context", value), + }), + frame: createEditor({ + parent: this.frameEditorTarget, + label: "Frame", + onChange: (value) => this.edit("frame", value), + }), + output: createEditor({ parent: this.outputEditorTarget, label: "Output", readOnly: true }), + }; + + // A permalink, or what the result of the validator opens the playground with + const shared = await decodeState(location.hash); + + if (shared) { + // The N-Quads of the examples, when the link has none: its tab shows something + this.state = { ...shared, nquads: shared.nquads || examples.nquads.nquads }; + } else { + this.state.nquads = examples.nquads.nquads; + } + + this.render(); + this.run(); + } + + disconnect() { + clearTimeout(this.runTimeout); + } + + // The actions of the page + + selectTab({ currentTarget }) { + this.state.algorithm = currentTarget.dataset.algorithm; + this.render(); + this.changed({ now: true }); + } + + // The arrows move across the tabs, as in any tab list + moveTab(event) { + const tabs = this.tabTargets; + const index = tabs.indexOf(event.currentTarget); + const next = { ArrowLeft: index - 1, ArrowRight: index + 1, Home: 0, End: tabs.length - 1 }[event.key]; + + if (next === undefined) { + return; + } + + event.preventDefault(); + + const tab = tabs[(next + tabs.length) % tabs.length]; + tab.focus(); + tab.click(); + } + + loadExample({ currentTarget }) { + const { label, ...example } = examples[currentTarget.dataset.example]; + + // An example is a document with its context and its frame, or some N-Quads: + // what it does not hold stays + Object.assign(this.state, example); + this.render(); + this.changed({ now: true }); + } + + changeOption({ currentTarget }) { + const name = currentTarget.name; + + if (currentTarget.type === "checkbox") { + this.state.options[name] = currentTarget.checked; + } else if (name === "omitGraph") { + this.state.options[name] = { yes: true, no: false }[currentTarget.value] ?? null; + } else { + this.state.options[name] = currentTarget.value; + } + + this.changed({ now: currentTarget.type !== "text" }); + } + + copyLink() { + this.copy(location.href, this.copyLinkTarget); + } + + copyOutput() { + this.copy(this.editors.output.getValue(), this.copyOutputTarget); + } + + // What they do + + edit(field, value) { + this.state[field] = value; + this.changed(); + } + + changed({ now = false } = {}) { + clearTimeout(this.runTimeout); + this.runTimeout = setTimeout(() => this.run(), now ? 0 : RUN_DELAY); + } + + /** + * Runs the algorithm, one run at a time: PHP runs in the thread of the page. + * What changes meanwhile is run next, and only the last answer is shown. + */ + async run() { + this.writePermalink(); + + if (this.running) { + this.outdated = true; + + return; + } + + this.running = true; + this.statusTarget.textContent = this.ran ? "Running…" : "Loading PHP…"; + + try { + let answer; + + do { + this.outdated = false; + + const { algorithm, document, nquads, context, frame, options } = this.state; + + try { + answer = await this.process({ + algorithm, + document: algorithm === "fromRdf" ? nquads : document, + context, + frame, + options, + }); + } catch (error) { + console.error(error); + answer = { error: "The playground crashed on this document, see the console for details." }; + } + } while (this.outdated); + + this.ran = true; + this.show(answer); + } finally { + this.running = false; + this.statusTarget.textContent = ""; + } + } + + show({ output, language, error }) { + this.errorTarget.textContent = error ?? ""; + this.errorTarget.hidden = !error; + // The output of the last run that worked stays, dimmed: it does not blink + // while the document is being typed + this.outputEditorTarget.classList.toggle("opacity-40", Boolean(error)); + + if (error) { + return; + } + + this.editors.output.setLanguage(language === "json" ? "json" : "text"); + this.editors.output.setValue(output); + } + + /** + * Shows the state: the tab, its editors and its options. + */ + render() { + const { algorithm, options } = this.state; + const fromRdf = algorithm === "fromRdf"; + + for (const tab of this.tabTargets) { + const selected = tab.dataset.algorithm === algorithm; + + tab.setAttribute("aria-selected", String(selected)); + tab.tabIndex = selected ? 0 : -1; + + if (selected) { + this.outputPanelTarget.setAttribute("aria-labelledby", tab.id); + } + } + + this.documentLabelTarget.textContent = fromRdf ? "RDF dataset, as N-Quads" : "JSON-LD document"; + this.editors.document.setLanguage(fromRdf ? "text" : "json"); + this.editors.document.setValue(fromRdf ? this.state.nquads : this.state.document); + + this.contextPanelTarget.hidden = !["compact", "flatten"].includes(algorithm); + this.contextLabelTarget.textContent = algorithm === "flatten" ? "Context (optional)" : "Context"; + this.editors.context.setValue(this.state.context); + + this.framePanelTarget.hidden = algorithm !== "frame"; + this.editors.frame.setValue(this.state.frame); + + this.outputLabelTarget.textContent = OUTPUT_LABELS[algorithm]; + + for (const wrapper of this.optionTargets) { + const field = wrapper.querySelector("[name]"); + const value = options[field.name]; + + wrapper.hidden = !OPTIONS[field.name].algorithms.includes(algorithm); + + if (field.type === "checkbox") { + field.checked = value; + } else if (field.name === "omitGraph") { + field.value = value === null ? "" : value ? "yes" : "no"; + } else { + field.value = value; + } + } + + this.optionsTarget.hidden = this.optionTargets.every((wrapper) => wrapper.hidden); + } + + async writePermalink() { + // The one of this change, when another one comes before it is encoded + const change = (this.permalinkChange = Symbol()); + const fragment = await encodeState(this.state); + + if (change !== this.permalinkChange) { + return; + } + + history.replaceState(null, "", fragment.length > MAX_FRAGMENT_LENGTH ? location.pathname + location.search : `#${fragment}`); + } + + async copy(text, button) { + // Kept on the button: a second click comes while it still says "Copied" + button.dataset.label ??= button.textContent; + + try { + await navigator.clipboard.writeText(text); + button.textContent = "Copied"; + } catch { + button.textContent = "Not copied"; + } + + clearTimeout(this.copyTimeouts?.get(button)); + (this.copyTimeouts ??= new Map()).set( + button, + setTimeout(() => (button.textContent = button.dataset.label), 1500), + ); + } +} diff --git a/website/assets/controllers/result_controller.js b/website/assets/controllers/result_controller.js index 442c0c6aa..7143a27fd 100644 --- a/website/assets/controllers/result_controller.js +++ b/website/assets/controllers/result_controller.js @@ -1,7 +1,7 @@ import { Controller } from "@hotwired/stimulus"; +import { editorExtensions } from "../editor.js"; +import { encodeState } from "../permalink.js"; import { loadSettings, persistSettings } from "../validatorSettings.js"; -import * as autocomplete from "@codemirror/autocomplete"; -import * as commands from "@codemirror/commands"; import { htmlLanguage } from "@codemirror/lang-html"; import { json, jsonLanguage } from "@codemirror/lang-json"; import * as language from "@codemirror/language"; @@ -104,11 +104,20 @@ export default class extends Controller { }); } this.refreshExpandButton(); + + // the header wraps on a narrow window: the editor sticks under it, however + // tall it is, see the --result-header of the template + const header = this.element.querySelector("header"); + this.headerObserver = new ResizeObserver(() => { + this.element.style.setProperty("--result-header", `${header.offsetHeight}px`); + }); + this.headerObserver.observe(header); } disconnect() { this.nodesTarget.removeEventListener("toggle", this.onBranchToggle, true); cancelAnimationFrame(this.refreshFrame); + this.headerObserver.disconnect(); } // the branches of the property tree: the warnings list of an entity is not one @@ -212,6 +221,13 @@ export default class extends Controller { } } + async openInPlayground() { + // The playground reads its state in the fragment of its URL + const fragment = await encodeState({ document: this.editorView.state.doc.toString() }); + + location.assign(`playground/#${fragment}`); + } + setupCodemirror() { let compartmentInitialized = false; const compartmentEffects = []; @@ -307,40 +323,8 @@ export default class extends Controller { } ); - const customSelectionStyle = view.EditorView.baseTheme({ - ".cm-selectionBackground": { - backgroundColor: "rgb(255 255 100)", - }, - }); - - const extensions = (() => [ - view.highlightActiveLineGutter(), - view.highlightSpecialChars(), - commands.history(), - view.drawSelection(), - view.dropCursor(), - state.EditorState.allowMultipleSelections.of(true), - language.indentOnInput(), - language.syntaxHighlighting(language.defaultHighlightStyle, { - fallback: true, - }), - language.bracketMatching(), - compartment.of([]), - compartmentExtension, - autocomplete.closeBrackets(), - autocomplete.autocompletion(), - view.rectangularSelection(), - view.crosshairCursor(), - view.highlightActiveLine(), - view.keymap.of([ - ...autocomplete.closeBracketsKeymap, - ...commands.defaultKeymap, - ...commands.historyKeymap, - commands.indentWithTab, - ...autocomplete.completionKeymap, - ]), - customSelectionStyle, - ])(); + // the editor of every page, with the language and the gutters of this one + const extensions = editorExtensions([compartment.of([]), compartmentExtension]); // create the editor const editorView = new view.EditorView({ diff --git a/website/assets/editor.js b/website/assets/editor.js new file mode 100644 index 000000000..8c4b10713 --- /dev/null +++ b/website/assets/editor.js @@ -0,0 +1,98 @@ +// The CodeMirror editor of the pages: the result of the validator adds its +// gutter markers to these extensions, the playground makes its editors with +// createEditor(). + +import * as autocomplete from "@codemirror/autocomplete"; +import * as commands from "@codemirror/commands"; +import { json } from "@codemirror/lang-json"; +import * as language from "@codemirror/language"; +import * as state from "@codemirror/state"; +import * as view from "@codemirror/view"; + +const selectionStyle = view.EditorView.baseTheme({ + ".cm-selectionBackground": { + backgroundColor: "rgb(255 255 100)", + }, +}); + +/** + * What every editor is made of. "own" is what an editor adds: its language, + * its gutters. + */ +export function editorExtensions(own = []) { + return [ + view.highlightActiveLineGutter(), + view.highlightSpecialChars(), + commands.history(), + view.drawSelection(), + view.dropCursor(), + state.EditorState.allowMultipleSelections.of(true), + language.indentOnInput(), + language.syntaxHighlighting(language.defaultHighlightStyle, { + fallback: true, + }), + language.bracketMatching(), + ...own, + autocomplete.closeBrackets(), + autocomplete.autocompletion(), + view.rectangularSelection(), + view.crosshairCursor(), + view.highlightActiveLine(), + view.keymap.of([ + ...autocomplete.closeBracketsKeymap, + ...commands.defaultKeymap, + ...commands.historyKeymap, + commands.indentWithTab, + ...autocomplete.completionKeymap, + ]), + selectionStyle, + ]; +} + +// "json", or "text" for what has no grammar here, as N-Quads +const languageExtension = (name) => (name === "json" ? json() : []); + +// Marks what setValue() writes, that is not typed: onChange is not told +const written = state.Annotation.define(); + +/** + * Makes an editor in "parent". "onChange" is given what is typed, "label" names + * the editor for a screen reader. A read-only editor still takes the focus, to + * select and copy what it shows. + */ +export function createEditor({ parent, label, doc = "", language: name = "json", readOnly = false, onChange = null }) { + const languageCompartment = new state.Compartment(); + + const editorView = new view.EditorView({ + doc, + parent, + extensions: editorExtensions([ + view.lineNumbers(), + languageCompartment.of(languageExtension(name)), + state.EditorState.readOnly.of(readOnly), + view.EditorView.contentAttributes.of({ "aria-label": label }), + view.EditorView.updateListener.of((update) => { + if (onChange && update.docChanged && !update.transactions.some((transaction) => transaction.annotation(written))) { + onChange(update.state.doc.toString()); + } + }), + ]), + }); + + return { + getValue: () => editorView.state.doc.toString(), + setLanguage(name) { + editorView.dispatch({ effects: languageCompartment.reconfigure(languageExtension(name)) }); + }, + setValue(value) { + if (value === editorView.state.doc.toString()) { + return; + } + + editorView.dispatch({ + annotations: written.of(true), + changes: { from: 0, to: editorView.state.doc.length, insert: value }, + }); + }, + }; +} diff --git a/website/assets/jsonLd.js b/website/assets/jsonLd.js new file mode 100644 index 000000000..5fabb1d97 --- /dev/null +++ b/website/assets/jsonLd.js @@ -0,0 +1,99 @@ +// Runs a JSON-LD algorithm, with the remote contexts of the document, without +// the DOM: playground.js wires it to the page, tests/playground.test.mjs tests +// it in node. +// +// PHP WebAssembly has no network. bin/playground.php answers with the documents +// it misses, a remote context most of the time: they are fetched here, by the +// browser, and PHP is asked again with them, until it misses nothing. A context +// that loads another one is found this way too. + +// What a single document may load: each one is a run of PHP more +export const MAX_DOCUMENTS = 20; + +export const ALGORITHMS = ["expand", "compact", "flatten", "frame", "toRdf", "fromRdf"]; + +// The options of bin/playground.php, and the algorithms that read them +export const OPTIONS = { + base: { default: "", algorithms: ["expand", "compact", "flatten", "frame", "toRdf"] }, + ordered: { default: false, algorithms: ["expand", "compact", "frame", "toRdf", "fromRdf"] }, + compactArrays: { default: true, algorithms: ["compact", "flatten", "frame"] }, + compactToRelative: { default: true, algorithms: ["compact", "flatten"] }, + // null lets the algorithm decide: omitted, in JSON-LD 1.1 + omitGraph: { default: null, values: [null, true, false], algorithms: ["frame"] }, + produceGeneralizedRdf: { default: false, algorithms: ["toRdf"] }, + rdfDirection: { default: "", values: ["", "i18n-datatype", "compound-literal"], algorithms: ["toRdf", "fromRdf"] }, + useNativeTypes: { default: false, algorithms: ["fromRdf"] }, + useRdfType: { default: false, algorithms: ["fromRdf"] }, +}; + +export const defaultOptions = () => + Object.fromEntries(Object.entries(OPTIONS).map(([name, option]) => [name, option.default])); + +/** + * The options as bin/playground.php expects them, whatever is given: the ones + * of a permalink are written by anyone. + */ +export function normalizeOptions(given) { + const options = defaultOptions(); + + for (const [name, { default: byDefault, values }] of Object.entries(OPTIONS)) { + const value = given?.[name]; + + if (values ? values.includes(value) : typeof value === typeof byDefault) { + options[name] = value; + } + } + + return options; +} + +/** + * Gives the function that runs an algorithm. "run" is the runPlayground() of + * php.js, "load" resolves with the { body } of a URL, or the { error } that + * says why it is not loaded, as loadUrl() does. + * + * The function resolves with the { output } of the algorithm and its + * { language }, or the { error } that says why there is none. + */ +export function createJsonLdProcessor({ run, load }) { + // What was fetched, for as long as the page lives: typing in the document + // runs the algorithm again, not the requests + const fetched = new Map(); + // What the last run read, given again without waiting for PHP to miss it + let needed = []; + + return async function process({ algorithm, document, context = "", frame = "", options = {} }) { + const documents = Object.fromEntries(needed.map((url) => [url, fetched.get(url)])); + + // Each run gives PHP one document more, at least: it ends + for (;;) { + const answer = await run({ algorithm, document, context, frame, options: normalizeOptions(options), documents }); + + if (!answer.missing?.length) { + if (answer.loaded) { + needed = answer.loaded; + } + + return answer; + } + + for (const url of answer.missing) { + if (Object.keys(documents).length >= MAX_DOCUMENTS) { + return { error: `This document loads more than ${MAX_DOCUMENTS} remote documents.` }; + } + + if (!fetched.has(url)) { + const { body, error } = await load(url); + + if (error) { + return { error: `${url} could not be loaded. ${error}` }; + } + + fetched.set(url, body); + } + + documents[url] = fetched.get(url); + } + } + }; +} diff --git a/website/assets/loadUrl.js b/website/assets/loadUrl.js new file mode 100644 index 000000000..2affae5eb --- /dev/null +++ b/website/assets/loadUrl.js @@ -0,0 +1,101 @@ +// Loads the document of a URL, without the DOM: app.js wires it to the page, +// the playground loads the remote contexts of a document with it, see +// jsonLd.js, and tests/loadUrl.test.mjs tests it in node. +// +// A browser only lets a page read another website when that website allows it, +// with CORS headers, and most do not. Loading any page needs a server, a CORS +// proxy: it would be a second try here, when the website refuses. + +// The one of bin/audit.php, that refuses a larger document +const MAX_DOCUMENT_SIZE = 2 * 1024 * 1024; + +const TIMEOUT = 15_000; + +const INVALID_URL = "Please enter the URL of a page, starting with http:// or https://."; +const TOO_LARGE = "This document is too large to be validated."; +// fetch does not say whether the website refused, or the network failed. +// Exported for the playground, that says it of a context, not of a page. +export const UNREADABLE = + "This page could not be read from your browser: most websites do not let another website read their pages. Paste its source code instead."; + +// A page, or a JSON-LD document +const ACCEPT = "text/html,application/ld+json,application/json;q=0.9,*/*;q=0.8"; + +/** + * Resolves with the { body } of the document, or the { error } that says why + * it is not loaded. "accept" is what is asked for: the playground asks for + * JSON-LD, as a context is often served by content negotiation. + */ +export async function loadUrl(url, { accept = ACCEPT } = {}) { + const target = httpUrl(url); + if (target === null) { + return { error: INVALID_URL }; + } + + const response = await fetch(target, { + // A website that allows every origin is refused when cookies are sent + credentials: "omit", + // A safelisted header: the browser does not ask the website first + headers: { Accept: accept }, + signal: AbortSignal.timeout(TIMEOUT), + }).catch(() => null); + + if (response === null) { + return { error: UNREADABLE }; + } + + const contentType = response.headers.get("Content-Type") ?? ""; + + if (!response.ok) { + return refuse(response, `This page answered with the HTTP status ${response.status}.`); + } + if (contentType && !/html|json|^text\//i.test(contentType)) { + return refuse(response, "This URL is neither a HTML page nor a JSON document."); + } + if (Number(response.headers.get("Content-Length")) > MAX_DOCUMENT_SIZE) { + return refuse(response, TOO_LARGE); + } + + const buffer = await response.arrayBuffer().catch(() => null); + + if (buffer === null) { + return { error: UNREADABLE }; + } + if (buffer.byteLength > MAX_DOCUMENT_SIZE) { + return { error: TOO_LARGE }; + } + + return { body: decode(new Uint8Array(buffer), contentType) }; +} + +function httpUrl(url) { + try { + const { protocol, href } = new URL(url.trim()); + + return protocol === "http:" || protocol === "https:" ? href : null; + } catch { + return null; + } +} + +function refuse(response, error) { + // Not downloaded any further + response.body?.cancel().catch(() => {}); + + return { error }; +} + +// response.text() reads everything as UTF-8: the charset is the one of the +// Content-Type header, or the one a HTML page declares in its first bytes +function decode(bytes, contentType) { + const charset = + /charset\s*=\s*"?([^\s;"]+)/i.exec(contentType)?.[1] ?? + /]+charset\s*=\s*["']?([\w-]+)/i.exec(new TextDecoder("latin1").decode(bytes.subarray(0, 1024)))?.[1]; + + try { + return new TextDecoder(charset).decode(bytes); + } catch { + // A charset that the browser does not know + return new TextDecoder().decode(bytes); + } +} diff --git a/website/assets/permalink.js b/website/assets/permalink.js new file mode 100644 index 000000000..a33781cf7 --- /dev/null +++ b/website/assets/permalink.js @@ -0,0 +1,105 @@ +// The state of the playground, in the fragment of its URL, without the DOM: +// controllers/playground_controller.js wires it to the page, and the result of +// the validator opens the playground with it, tests/permalink.test.mjs tests it +// in node. +// +// The fragment is a version, then the state as JSON, compressed and written in +// base64url: "1" when the browser compresses (deflate), "0" when it can not. + +import { ALGORITHMS, normalizeOptions } from "./jsonLd.js"; + +// What a fragment may decompress to: a few bytes can inflate to gigabytes +const MAX_STATE_SIZE = 4 * 1024 * 1024; + +/** + * The state as the playground expects it, whatever is given: a fragment is + * written by anyone. + */ +export function normalizeState(given) { + const text = (value) => (typeof value === "string" ? value : ""); + + return { + algorithm: ALGORITHMS.includes(given?.algorithm) ? given.algorithm : "expand", + document: text(given?.document), + nquads: text(given?.nquads), + context: text(given?.context), + frame: text(given?.frame), + options: normalizeOptions(given?.options), + }; +} + +/** + * Resolves with the fragment of a state, without its "#". + */ +export async function encodeState(state) { + const bytes = new TextEncoder().encode(JSON.stringify(state)); + + if (typeof CompressionStream === "undefined") { + return "0" + toBase64Url(bytes); + } + + return "1" + toBase64Url(await through(bytes, new CompressionStream("deflate-raw"))); +} + +/** + * Resolves with the state of a fragment, or null when it holds none. + */ +export async function decodeState(fragment) { + const encoded = fragment.replace(/^#/, ""); + + try { + let bytes = fromBase64Url(encoded.slice(1)); + + if (encoded[0] === "1") { + bytes = await through(bytes, new DecompressionStream("deflate-raw")); + } else if (encoded[0] !== "0") { + return null; + } + + const state = JSON.parse(new TextDecoder().decode(bytes)); + + return state !== null && typeof state === "object" && !Array.isArray(state) ? normalizeState(state) : null; + } catch { + // Not a state: a fragment of another kind, or one cut by a mail client + return null; + } +} + +async function through(bytes, stream) { + const reader = new Blob([bytes]).stream().pipeThrough(stream).getReader(); + const chunks = []; + let size = 0; + + for (;;) { + const { done, value } = await reader.read(); + + if (done) { + return new Uint8Array(await new Blob(chunks).arrayBuffer()); + } + + size += value.length; + + if (size > MAX_STATE_SIZE) { + await reader.cancel(); + + throw new RangeError("The state is too large."); + } + + chunks.push(value); + } +} + +function toBase64Url(bytes) { + let binary = ""; + + // Not all at once: the arguments of a call are limited + for (let offset = 0; offset < bytes.length; offset += 0x8000) { + binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000)); + } + + return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} + +function fromBase64Url(encoded) { + return Uint8Array.from(atob(encoded.replaceAll("-", "+").replaceAll("_", "/")), (character) => character.charCodeAt(0)); +} diff --git a/website/assets/php.js b/website/assets/php.js index 11bc4ecb4..54dd9c2d0 100644 --- a/website/assets/php.js +++ b/website/assets/php.js @@ -1,24 +1,21 @@ -// The validator in PHP WebAssembly, without the DOM: app.js wires it to the -// page, tests/page.test.mjs tests it in node. +// The library in PHP WebAssembly, without the DOM: app.js and playground.js +// wire it to their page, tests/page.test.mjs and tests/playground.test.mjs +// test it in node. // Built next to this module, in public/build: see .castor/website.php import createPhp from "./php-web.mjs"; -// Where .castor/website.php embeds it +// Where .castor/website.php embeds them const AUDIT_SCRIPT = "/app/bin/audit.php"; +const PLAYGROUND_SCRIPT = "/app/bin/playground.php"; -// Loading starts with the page, the first audit waits for it +// Loading starts with the page, the first run waits for it const loadingPhp = createPhp(); -/** - * Resolves with what bin/audit.php answers: the { html } of the result, or the - * { error } that says why the document is not audited. - */ -export async function audit({ body, mergeSharedIdentifiers, allowPendingVocabulary }) { +// Both scripts read their request on stdin, and answer on stdout, as JSON +async function run(script, request) { const php = await loadingPhp; - const { exitCode, stdout, stderr } = await php.runFile(AUDIT_SCRIPT, { - stdin: JSON.stringify({ allowPendingVocabulary, body, mergeSharedIdentifiers }), - }); + const { exitCode, stdout, stderr } = await php.runFile(script, { stdin: JSON.stringify(request) }); if (stderr) { console.error(stderr); @@ -29,3 +26,20 @@ export async function audit({ body, mergeSharedIdentifiers, allowPendingVocabula return JSON.parse(stdout); } + +/** + * Resolves with what bin/audit.php answers: the { html } of the result, or the + * { error } that says why the document is not audited. + */ +export function audit({ body, mergeSharedIdentifiers, allowPendingVocabulary }) { + return run(AUDIT_SCRIPT, { allowPendingVocabulary, body, mergeSharedIdentifiers }); +} + +/** + * Resolves with what bin/playground.php answers: the { output } of a JSON-LD + * algorithm, the { error } that says why there is none, or the { missing } + * documents to fetch first. assets/jsonLd.js fetches them, and asks again. + */ +export function runPlayground({ algorithm, document, context, frame, options, documents }) { + return run(PLAYGROUND_SCRIPT, { algorithm, context, document, documents, frame, options }); +} diff --git a/website/assets/playground.js b/website/assets/playground.js new file mode 100644 index 000000000..bbfde62bf --- /dev/null +++ b/website/assets/playground.js @@ -0,0 +1,8 @@ +// The page of the playground, public/playground/index.html: the JSON-LD +// algorithms of the library, run on what the visitor types. + +import { Application } from "@hotwired/stimulus"; +import PlaygroundController from "./controllers/playground_controller.js"; + +const app = Application.start(); +app.register("playground", PlaygroundController); diff --git a/website/assets/playgroundExamples.js b/website/assets/playgroundExamples.js new file mode 100644 index 000000000..eb8c9bbee --- /dev/null +++ b/website/assets/playgroundExamples.js @@ -0,0 +1,190 @@ +// The examples of the playground. Each one opens the tab of its "algorithm". +// The ones made of a JSON-LD "document" come with the "context" and the "frame" +// of the tabs that need one: every tab shows something for every example, see +// tests/playground.test.mjs. + +const person = { + label: "Person", + algorithm: "expand", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/people/ada", + "@type": "Person", + "name": "Ada Lovelace", + "jobTitle": "Mathematician", + "birthDate": "1815-12-10", + "knows": { + "@id": "https://example.com/people/charles", + "@type": "Person", + "name": "Charles Babbage" + } +}`, + context: `{ + "@context": { + "schema": "http://schema.org/", + "Person": "schema:Person", + "name": "schema:name", + "knows": "schema:knows" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Person", + "knows": { + "@embed": "@never" + } +}`, +}; + +const event = { + label: "Event", + algorithm: "compact", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/events/php-meetup", + "@type": "Event", + "name": "PHP meetup", + "startDate": "2026-12-03T19:00:00+01:00", + "eventAttendanceMode": "https://schema.org/OfflineEventAttendanceMode", + "location": { + "@type": "Place", + "name": "JoliCode", + "address": { + "@type": "PostalAddress", + "addressLocality": "Paris", + "addressCountry": "FR" + } + } +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/", + "title": "name", + "starts": { + "@id": "startDate", + "@type": "DateTime" + }, + "where": "location" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Place" +}`, +}; + +const product = { + label: "Product", + algorithm: "toRdf", + document: `{ + "@context": "https://schema.org", + "@id": "https://example.com/products/mug", + "@type": "Product", + "name": "Yellow mug", + "sku": "MUG-001", + "brand": { + "@type": "Brand", + "name": "JoliCode" + }, + "offers": { + "@type": "Offer", + "price": 12.5, + "priceCurrency": "EUR", + "availability": "https://schema.org/InStock" + } +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Offer" +}`, +}; + +// What a SEO plugin writes: flat nodes that refer to each other, which a frame +// turns into the tree of the article +const articleGraph = { + label: "Article graph, framed", + algorithm: "frame", + document: `{ + "@context": "https://schema.org", + "@graph": [ + { + "@id": "https://example.com/#organization", + "@type": "Organization", + "name": "Example", + "url": "https://example.com/" + }, + { + "@id": "https://example.com/#/people/ada", + "@type": "Person", + "name": "Ada Lovelace" + }, + { + "@id": "https://example.com/blog/hello/#article", + "@type": "Article", + "headline": "Hello world", + "datePublished": "2026-11-02", + "author": { + "@id": "https://example.com/#/people/ada" + }, + "publisher": { + "@id": "https://example.com/#organization" + } + } + ] +}`, + context: `{ + "@context": { + "@vocab": "http://schema.org/" + } +}`, + frame: `{ + "@context": "https://schema.org", + "@type": "Article" +}`, +}; + +// Its context is not schema.org, that the library ships: the browser fetches it +const activity = { + label: "Activity, with a remote context", + algorithm: "expand", + document: `{ + "@context": "https://www.w3.org/ns/activitystreams", + "id": "https://example.com/notes/1", + "type": "Note", + "attributedTo": "https://example.com/people/ada", + "content": "A remote context, fetched by your browser.", + "published": "2026-11-23T10:00:00Z" +}`, + context: `{ + "@context": { + "as": "https://www.w3.org/ns/activitystreams#", + "content": "as:content" + } +}`, + frame: `{ + "@context": "https://www.w3.org/ns/activitystreams", + "type": "Note" +}`, +}; + +const nquads = { + label: "N-Quads", + algorithm: "fromRdf", + nquads: ` . + "Ada Lovelace" . + "1815-12-10"^^ . + . + . + "Charles Babbage" . +`, +}; + +export const examples = { person, event, product, articleGraph, activity, nquads }; + +// What the playground opens with +export const DEFAULT_EXAMPLE = "person"; diff --git a/website/assets/styles/app.css b/website/assets/styles/app.css index 3eb3a051d..d7fb30476 100644 --- a/website/assets/styles/app.css +++ b/website/assets/styles/app.css @@ -56,6 +56,25 @@ @apply inline-flex min-h-10 cursor-pointer items-center gap-2 rounded-full border border-gray-300 bg-white px-4 text-[13px] font-medium shadow-sm transition hover:-translate-y-px hover:border-gray-900 hover:shadow-md focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; } +/* The menu of the pages: the highlighter underlines the current one */ +.site-nav-link { + @apply inline-flex min-h-9 items-center font-medium text-gray-700 hover:text-gray-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; + + &[aria-current="page"] { + @apply text-gray-950; + box-shadow: inset 0 -3px 0 var(--color-joli); + } +} + +/* The algorithms of the playground */ +.playground-tab { + @apply min-h-9 cursor-pointer rounded-lg px-3 text-[13px] font-medium text-gray-700 hover:bg-gray-100 hover:text-gray-950 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-gray-900; + + &[aria-selected="true"] { + @apply bg-gray-900 text-white; + } +} + .cm-editor { @apply h-full text-[13px]; diff --git a/website/bin/playground.php b/website/bin/playground.php new file mode 100644 index 000000000..3d91a6a42 --- /dev/null +++ b/website/bin/playground.php @@ -0,0 +1,133 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +// Run in the browser by PHP WebAssembly, see assets/php.js: the request is on +// stdin, and the answer on stdout, as JSON. It is the "output" of the +// algorithm, with its "language", or the "error" that says why there is none, +// or the "missing" documents: PHP has no network here, so the page fetches +// them, and asks again with them, see assets/jsonLd.js. + +use JoliCode\StructuredData\JsonLd\Algorithms\Compact\Compactor; +use JoliCode\StructuredData\JsonLd\Algorithms\Exception\JsonLdException; +use JoliCode\StructuredData\JsonLd\Algorithms\Expand\Expander; +use JoliCode\StructuredData\JsonLd\Algorithms\Flatten\Flattener; +use JoliCode\StructuredData\JsonLd\Algorithms\Frame\Framer; +use JoliCode\StructuredData\JsonLd\Algorithms\JsonLd\ProcessorOptions; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\FromRdfConverter; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\NQuadsSerializer; +use JoliCode\StructuredData\JsonLd\Algorithms\Rdf\ToRdfConverter; +use JoliCode\StructuredData\Website\JsonLd\PreloadedDocumentLoader; + +ini_set('display_errors', '0'); +ini_set('log_errors', '1'); + +require __DIR__ . '/../vendor/autoload.php'; + +// As bin/audit.php: the memory of the WebAssembly module does not grow. It is +// the size of everything the algorithm reads, the fetched documents too. +const MAX_REQUEST_SIZE = 2 * 1024 * 1024; + +const JSON_OUTPUT = \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION | \JSON_THROW_ON_ERROR; + +const ALGORITHMS = ['expand', 'compact', 'flatten', 'frame', 'toRdf', 'fromRdf']; + +/** + * @var array{ + * algorithm: string, + * document: string, + * context?: string, + * frame?: string, + * options?: array, + * documents?: array, + * } $request + */ +$request = json_decode((string) file_get_contents('php://stdin'), true, flags: \JSON_THROW_ON_ERROR); + +$algorithm = $request['algorithm']; +$document = $request['document']; +$context = $request['context'] ?? ''; +$frame = $request['frame'] ?? ''; +$given = $request['options'] ?? []; +$documents = $request['documents'] ?? []; + +$answer = static function (array $answer): void { + echo json_encode($answer, \JSON_THROW_ON_ERROR); +}; + +// A context, or a frame: what is not JSON is said so, rather than taken for a URL +$isJson = static function (string $json): bool { + json_decode($json); + + return \JSON_ERROR_NONE === json_last_error(); +}; + +$size = strlen($document) + strlen($context) + strlen($frame) + array_sum(array_map(strlen(...), $documents)); + +$error = match (true) { + !in_array($algorithm, ALGORITHMS, true) => 'This algorithm is not known.', + '' === trim($document) => 'fromRdf' === $algorithm ? 'Please enter some N-Quads.' : 'Please enter a JSON-LD document.', + $size > MAX_REQUEST_SIZE => 'This document is too large to be processed.', + 'compact' === $algorithm && '' === trim($context) => 'Please enter the context to compact the document with.', + in_array($algorithm, ['compact', 'flatten'], true) && '' !== trim($context) && !$isJson($context) => 'The context is not valid JSON.', + 'frame' === $algorithm && '' === trim($frame) => 'Please enter the frame to frame the document with.', + 'frame' === $algorithm && !$isJson($frame) => 'The frame is not valid JSON.', + default => null, +}; + +if (null !== $error) { + $answer(['error' => $error]); + + return; +} + +$options = new ProcessorOptions( + base: '' === ($given['base'] ?? '') ? null : (string) $given['base'], + compactArrays: (bool) ($given['compactArrays'] ?? true), + compactToRelative: (bool) ($given['compactToRelative'] ?? true), + omitGraph: isset($given['omitGraph']) ? (bool) $given['omitGraph'] : null, + ordered: (bool) ($given['ordered'] ?? false), + produceGeneralizedRdf: (bool) ($given['produceGeneralizedRdf'] ?? false), + rdfDirection: '' === ($given['rdfDirection'] ?? '') ? null : (string) $given['rdfDirection'], + useNativeTypes: (bool) ($given['useNativeTypes'] ?? false), + useRdfType: (bool) ($given['useRdfType'] ?? false), +); + +$loader = new PreloadedDocumentLoader($documents); + +try { + $output = match ($algorithm) { + 'expand' => json_encode(new Expander(documentLoader: $loader)->expand($document, $options, encodeResult: false), JSON_OUTPUT), + 'compact' => json_encode(new Compactor(documentLoader: $loader)->compact($document, json_decode($context), $options, encodeResult: false), JSON_OUTPUT), + // It answers a string, that is not always indented + 'flatten' => json_encode(json_decode((string) new Flattener(documentLoader: $loader)->flatten($document, '' === trim($context) ? null : json_decode($context), $options)), JSON_OUTPUT), + 'frame' => json_encode(new Framer(documentLoader: $loader)->frame($document, $frame, $options, encodeResult: false), JSON_OUTPUT), + 'toRdf' => NQuadsSerializer::serialize(new ToRdfConverter(documentLoader: $loader)->toRdf($document, $options)), + 'fromRdf' => json_encode(new FromRdfConverter()->fromRdf($document, $options, encodeResult: false), JSON_OUTPUT), + }; +} catch (JsonLdException $exception) { + // The message of the library is the error code of the specification, and + // never says which URL failed. Here the URL comes from the document of the + // visitor, and is fetched by their browser: naming it tells nothing more. + $answer(match (true) { + [] !== $loader->getMissing() => ['missing' => $loader->getMissing()], + [] !== $loader->getUnreadable() => ['error' => sprintf('%s: %s is not a JSON document.', $exception->getMessage(), implode(', ', $loader->getUnreadable()))], + default => ['error' => $exception->getMessage()], + }); + + return; +} + +$answer([ + 'language' => 'toRdf' === $algorithm ? 'nquads' : 'json', + // What the page has to give again, the next time it asks + 'loaded' => $loader->getLoaded(), + 'output' => $output, +]); diff --git a/website/package.json b/website/package.json index 024f0578c..dcfa5d051 100644 --- a/website/package.json +++ b/website/package.json @@ -7,7 +7,7 @@ "build": "npm run build:fonts && npm run build:css && npm run build:js", "build:css": "tailwindcss --input assets/styles/app.css --output public/build/app.css --minify", "build:fonts": "mkdir -p public/build/files && cp node_modules/@fontsource-variable/inter/files/*-wght-normal.woff2 node_modules/@fontsource-variable/jetbrains-mono/files/*-wght-normal.woff2 node_modules/@fontsource-variable/space-grotesk/files/*-wght-normal.woff2 public/build/files/", - "build:js": "esbuild assets/app.js assets/php.js --bundle --splitting --format=esm --minify --outdir=public/build --external:./php-web.mjs" + "build:js": "esbuild assets/app.js assets/playground.js assets/php.js --bundle --splitting --format=esm --minify --outdir=public/build --external:./php-web.mjs" }, "devDependencies": { "@codemirror/autocomplete": "6.20.4", diff --git a/website/public/index.html b/website/public/index.html index 5b5b4caf5..32ca188e4 100644 --- a/website/public/index.html +++ b/website/public/index.html @@ -23,7 +23,10 @@ Structured Data Validator -