Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 28 additions & 73 deletions website/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,96 +3,51 @@
> [!TIP]
> This demo website is deployed under https://structured-data-validator.jolicode.com/

Static pages, that run the library in the browser: PHP is built as WebAssembly, with
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
repository is embedded in it. GitHub Pages serves `public/`, deployed from `main` by
`.github/workflows/website.yml`.

- The **homepage**, at `/`, has the form of the validator, and its examples.
- The **validator**, at `/validator/`, audits a document, and shows the result.
- 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
the document is the "Format" button of the result: `assets/format.js` runs Prettier in the browser,
as its `bin/format-document.js` does in node.
Page | Path | What it does
---- | ---- | ----
Homepage | `/` | The form of the validator, and its examples
Validator | `/validator/` | Audits a document, and shows the result
JSON-LD playground | `/playground/` | Runs the JSON-LD algorithms on a document

## 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 state of the pages

The validator and the playground share a state: the document, and what the playground adds to it
(its tab, its context, its frame, its options). `assets/pageState.js` writes it:

- in the fragment of the URL of the page, compressed by `assets/permalink.js`: a link to the page
opens it as it is, and its "Copy link" button copies this link;
- in the links of the menu: the validator opens the playground with its document, and the
playground the validator, that validates what was typed there.

A state too long for a link is kept in the session storage of the tab, and the fragment is `#local`:
the pages still open each other, and reload, but "Copy link" is disabled.
- `assets/php.js` loads PHP and runs a script of `bin/`, with the request as JSON on its standard
input and the answer as JSON on its standard output: `bin/audit.php` for the validator,
`bin/playground.php` for the playground.
- `assets/home.js` runs the homepage, and `assets/controllers/` the two other pages. Both run PHP
again as the visitor types.
- `assets/pageState.js` keeps the document in the fragment of the URL: a link opens a page as it
is, and the validator and the playground open each other with the same document. A document too
long for a link is kept in the session storage instead.
- PHP has no network in the browser: `assets/jsonLd.js` fetches the remote contexts the playground
needs, from the websites that allow it with CORS headers.

### The validator
## Loading a page from its URL

- `public/index.html` is the homepage. `assets/home.js` opens the page of the validator with the
document of its form, or one of `assets/examples.js`. Nothing is audited there: PHP is only
fetched ahead.
- `public/validator/index.html` is the page of the validator. It holds the frame of the result, the
editor and the toolbar, that shows as the page opens: PHP has to start before it answers, and the
document is there meanwhile. `assets/controllers/result_controller.js` runs the page: it gives
the document the page is opened with to PHP, and shows what it answers in this frame. Without a
document, it goes back to the homepage. The document is audited again as it is typed, once the
visitor pauses, as in the playground: PHP runs in the thread of the page, so a document that
takes long to audit waits for a longer pause.
- `bin/audit.php` is what PHP runs: it audits the document, and renders what is found with Twig,
the counts of the toolbar, `templates/counts.html.twig`, and the entities,
`templates/result.html.twig`. The settings of the audit are the ones of who opens the page: they
are not in the link.
A browser can not read a website that does not allow it with CORS headers, and most do not. The
"Load" button of the homepage posts the URL to `/load-url` instead (`loadPage()` in
`assets/loadUrl.js`), where a proxy downloads the page.

### The playground
This proxy is not in this repository, and only exists on the deployed website. Elsewhere, a local
build or a fork, the browser loads the page itself, which only works for the websites that allow it.

- `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/playgroundExamples.js` holds the examples.

Canonicalization (RDFC-1.0) is not there: the library does not implement it.

### Every page

- `assets/editor.js` is the CodeMirror editor of the validator and of the playground.
- The header, with its menu, is written in each page: 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 homepage and the
playground load it.
What is pasted never leaves the browser: only the URL of a page to load is sent.

## Build it

Docker, node and [Castor](https://github.com/jolicode/castor) are needed. The tasks are in
`.castor/website.php`:
Docker, node and [Castor](https://github.com/jolicode/castor) are needed.

Command | Description
---- | -----
`castor website:build` | Installs the dependencies, and builds the assets and PHP in `public/build/`
`castor website:check` | Checks, in node, that PHP boots, and runs the tests of `tests/`
`castor website:serve` | Serves the website on http://localhost:9999

`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.
The website is built with the code of the working directory, not with a release: run
`castor website:build` again after a change. A new test file of `tests/` has to be listed in the
`check()` task of `.castor/website.php`.
50 changes: 44 additions & 6 deletions website/assets/home.js
Original file line number Diff line number Diff line change
@@ -1,35 +1,73 @@
// The homepage, public/index.html: its form, or one of its examples, opens the
// page of the validator with a document. Nothing is audited here.
// page of the validator with a document, pasted or loaded from a URL. Nothing
// is audited here.

import { examples } from "./examples.js";
import { loadPage } from "./loadUrl.js";
import { stateUrl } from "./pageState.js";

const form = document.querySelector("form");
const errorElement = form.querySelector("[data-validation-error]");
const errorMessage = errorElement.querySelector("[data-validation-error-message]");
const errorAdvice = errorElement.querySelector("[data-validation-error-advice]");
// "Load", that loads the page of the URL, and "Validate"
const submitButtons = form.querySelectorAll('button[type="submit"]');
const enableSubmitButtons = (enabled) => submitButtons.forEach((button) => (button.disabled = !enabled));

// No message hides the error. "pasteable" is a page that could not be loaded:
// the error advises to paste it, or to validate it elsewhere
function showError(message, pasteable = false) {
errorMessage.textContent = message;
errorAdvice.hidden = !pasteable;
errorElement.hidden = message === "";
}

// The validator reads the document in the fragment of its URL, or in the
// session storage when it is too long for a URL: see pageState.js
async function validate(body) {
if (body.trim() === "") {
errorElement.textContent = "Please enter some code to validate.";
showError("Please enter some code to validate.");

return;
}

const url = await stateUrl("validator/", { document: body });

if (!url.includes("#")) {
errorElement.textContent = "This document is too long for a link, and your browser gives this page no storage to hand it to the validator.";
showError("This document is too long for a link, and your browser gives this page no storage to hand it to the validator.");

return;
}

errorElement.textContent = "";
showError("");
location.assign(url);
}

form.addEventListener("submit", (event) => {
form.addEventListener("submit", async (event) => {
event.preventDefault();

// The "Load" button, the one of the Enter key in the URL too: the page of
// the URL is the document
if (event.submitter?.hasAttribute("data-load-url")) {
showError("");
enableSubmitButtons(false);

try {
const { body, error, pasteable } = await loadPage(form.elements.url.value);

if (error) {
showError(error, pasteable);

return;
}

// Shown in the form too: it is there when the visitor comes back
form.elements.body.value = body;
} finally {
enableSubmitButtons(true);
}
}

validate(form.elements.body.value);
});

Expand All @@ -45,4 +83,4 @@ document.addEventListener("click", (event) => {
});

// Until then, submitting would reload the page
form.querySelector('button[type="submit"]').disabled = false;
enableSubmitButtons(true);
91 changes: 77 additions & 14 deletions website/assets/loadUrl.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
// Loads the document of a URL, without the DOM: home.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.
// Loads the document of a URL, without the DOM: home.js wires it to the
// homepage, 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.
// with CORS headers, and most do not. The homepage loads a page with
// loadPage(), by the proxy of the website: a server, that any website answers
// to. The playground loads its contexts with loadUrl(), by the browser.

// Where the proxy answers, on the host of the website. It is not part of this
// repository: see the README.
const PROXY = "/load-url";

// The one of bin/audit.php, that refuses a larger document
const MAX_DOCUMENT_SIZE = 2 * 1024 * 1024;
Expand All @@ -13,14 +18,66 @@ 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.";
const UNSUPPORTED = "This URL is neither a HTML page nor a JSON document.";
const httpStatus = (status) => `This page answered with the HTTP status ${status}.`;
// 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.";
export const UNREADABLE = "This URL could not be loaded.";
const UNAVAILABLE = "Loading a page is not available for now.";

// The error of a page that is not loaded, though the validator may read it:
// the homepage advises to paste its source code, or to validate it elsewhere.
// A document the validator refuses, too large or not a page, is not one.
const pasteable = (error) => ({ error, pasteable: true });

// What the proxy answers when it does not load the page
const PROXY_ERRORS = {
forbidden_target: pasteable("This URL can not be loaded: only the public websites are, on their standard port."),
rate_limited: pasteable("Too many pages were loaded lately: try again in a minute."),
too_large: { error: TOO_LARGE },
unreachable: pasteable(UNREADABLE),
unsupported_type: { error: UNSUPPORTED },
};

// 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 page, or the { error } that says why it is
* not loaded, "pasteable" when pasting the page would work. The page is loaded
* by the proxy, or by the browser, as loadUrl() does, where there is no proxy:
* the website served by a static host alone.
*/
export async function loadPage(url) {
const target = httpUrl(url);
if (target === null) {
return { error: INVALID_URL };
}

const response = await fetch(PROXY, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ url: target }),
signal: AbortSignal.timeout(TIMEOUT),
}).catch(() => null);

// The proxy signs what it answers: a static host answers a 404 or a 405
// here, and some of them a page
if (response === null || !response.headers.has("X-Load-Url")) {
response?.body?.cancel().catch(() => {});

return loadUrl(target);
}

if (!response.ok) {
const { error, status } = await response.json().catch(() => ({}));

return error === "http_status" && Number.isInteger(status) ? pasteable(httpStatus(status)) : (PROXY_ERRORS[error] ?? pasteable(UNAVAILABLE));
}

return read(response, response.headers.get("X-Load-Url-Content-Type") ?? "", UNAVAILABLE);
}

/**
* 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
Expand All @@ -41,25 +98,31 @@ export async function loadUrl(url, { accept = ACCEPT } = {}) {
}).catch(() => null);

if (response === null) {
return { error: UNREADABLE };
return pasteable(UNREADABLE);
}

const contentType = response.headers.get("Content-Type") ?? "";

if (!response.ok) {
return refuse(response, `This page answered with the HTTP status ${response.status}.`);
return refuse(response, pasteable(httpStatus(response.status)));
}
if (contentType && !/html|json|^text\//i.test(contentType)) {
return refuse(response, "This URL is neither a HTML page nor a JSON document.");
return refuse(response, { error: UNSUPPORTED });
}
if (Number(response.headers.get("Content-Length")) > MAX_DOCUMENT_SIZE) {
return refuse(response, TOO_LARGE);
return refuse(response, { error: TOO_LARGE });
}

return read(response, contentType, UNREADABLE);
}

// The document a response holds, served as "contentType". "failure" is the
// error of a download that stops halfway.
async function read(response, contentType, failure) {
const buffer = await response.arrayBuffer().catch(() => null);

if (buffer === null) {
return { error: UNREADABLE };
return pasteable(failure);
}
if (buffer.byteLength > MAX_DOCUMENT_SIZE) {
return { error: TOO_LARGE };
Expand All @@ -78,11 +141,11 @@ function httpUrl(url) {
}
}

function refuse(response, error) {
function refuse(response, refusal) {
// Not downloaded any further
response.body?.cancel().catch(() => {});

return { error };
return refusal;
}

// response.text() reads everything as UTF-8: the charset is the one of the
Expand Down
Loading