Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ To start a local HyperFormula docs server:
```
5. In your browser, go to: http://localhost:4321/docs/hyperformula/. Search works only in a full build (`npm run docs:build`), which indexes the pages with [Pagefind](https://pagefind.app/).

The live examples load HyperFormula from the CDN, and HyperFormula checks the license key everywhere except on handsontable.com. On `localhost`, an example shows `#LIC!` once the CDN serves a version that needs a key. `npm run docs:dev` can't give the examples a key. To run them locally with the internal test key, build with the opt-in and serve the build:
The live examples on the production site load HyperFormula from the CDN, pinned to the version in `hyperformula/package.json`. Every other build, the dev server included, serves the engine from `hyperformula/dist`, so a preview of the release branch runs the new engine before it is on npm; run `npm run bundle-all` from the repository root first. `src/engine-scripts.mjs` decides which. HyperFormula checks the license key everywhere except on handsontable.com. On `localhost`, an example shows `#LIC!` when the version it loads needs a key. `npm run docs:dev` can't give the examples a key. To run them locally with the internal test key, build with the opt-in and serve the build:

```bash
DOCS_TEST_LICENSE_KEY=true npm run docs:build
Expand Down
11 changes: 7 additions & 4 deletions docs/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { DOCS_DATA } from './src/docs-data.mjs';
import { docsMarkdownPlugin, legacyAnchorsPlugin, tableWrapperPlugin } from './src/markdown-plugins.mjs';
import { mdCompanions } from './src/md-companions/index.mjs';
import { previewLicenseKey } from './src/preview-license-key.mjs';
import { engineAssets, engineScripts, resolveUsesCdn } from './src/engine-scripts.mjs';
import { apiPageGroup } from './src/api-sidebar.mjs';

// CommonJS, because the Worker and `script/prepare-cf-assets.js` read it too.
Expand All @@ -21,6 +22,9 @@ const normalizeBase = (base) => `/${base.replace(/^\/+|\/+$/g, '')}/`.replace(/^
const base = normalizeBase(process.env.DOCS_BASE || buildConfig.base);
const hostname = process.env.DOCS_HOSTNAME || buildConfig.hostname;

// Where the live examples load the engine from: `src/engine-scripts.mjs`.
const engineFromCdn = await resolveUsesCdn(process.env, DOCS_DATA.version);

/**
* The image that link previews show for every docs page. Starlight emits `og:title`, `og:description`, and
* `twitter:card=summary_large_image` by itself, but no image. This is the handsontable.com default card, which carries
Expand Down Expand Up @@ -109,10 +113,8 @@ export default defineConfig({
},
plugins: [starlightThemeRapide()],
head: [
// The live examples use the published engine and these globals.
{ tag: 'script', attrs: { src: 'https://cdn.jsdelivr.net/npm/hyperformula/dist/hyperformula.full.min.js' } },
{ tag: 'script', attrs: { src: 'https://cdn.jsdelivr.net/npm/hyperformula/dist/languages/enUS.js' } },
{ tag: 'script', attrs: { src: 'https://cdn.jsdelivr.net/npm/hyperformula/dist/languages/frFR.js' } },
// The live examples use the engine and these globals.
...engineScripts(engineFromCdn, base, DOCS_DATA.version),
{ tag: 'script', attrs: { src: 'https://cdn.jsdelivr.net/npm/moment/moment.min.js' } },
// Builds the "Source code" tabs of the live examples and toggles them (a copy of the Handsontable docs' script).
{ tag: 'script', attrs: { src: `${base}example-tabs.js`, defer: true } },
Expand Down Expand Up @@ -297,6 +299,7 @@ j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
}),
mdCompanions({ base, hostname }),
// Last, so it reads everything the build wrote.
engineAssets(engineFromCdn, base),
previewLicenseKey(process.env),
],
});
148 changes: 148 additions & 0 deletions docs/src/engine-scripts.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/**
* Where the live examples load the engine from.
*
* A build of the production branch loads the published engine from jsDelivr, pinned to the version the docs are built
* from, once that version is on npm. An unpinned URL serves whatever jsDelivr last cached as `latest`, for up to 12 hours on the CDN and 7 days in a
* browser, so after a release the pages would run on the previous engine. The version comes from
* `hyperformula/package.json`, which `npm run release -- code-freeze` bumps, so the pin moves with every release.
*
* Every other build (a preview, staging, a local build, the dev server) serves the engine it was built with, from
* `hyperformula/dist`. During a code freeze the release branch carries a version that is not on npm yet, so jsDelivr
* has nothing to serve for it, and these builds are where the new examples are tested against the new engine.
*
* A production build whose version is not on npm serves its own engine too. `npm run release -- publish` pushes
* `master` before it publishes to npm, so the build that push starts would otherwise point every example at a version
* jsDelivr cannot serve, for as long as the publish takes, or for good if it never happens.
*/
import { copyFileSync, createReadStream, existsSync, mkdirSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { PRODUCTION_BRANCH } from './preview-license-key.mjs';

const ENGINE_DIST = resolve(fileURLToPath(new URL('.', import.meta.url)), '../../hyperformula/dist');

/**
* The files the live examples load, relative to `hyperformula/dist` and to the package root on jsDelivr's `dist/`.
*/
const ENGINE_FILES = ['hyperformula.full.min.js', 'languages/enUS.js', 'languages/frFR.js'];

/**
* The directory, under the docs base, that a non-production build serves the engine from.
*/
const ENGINE_DIR = 'engine/';

/**
* Whether `hyperformula@<version>` is on npm. Anything but a clear yes, a network error included, is a no: serving the
* engine from the build always works, and pointing at a version jsDelivr lacks never does.
*
* @param {string} version The engine version.
* @returns {Promise<boolean>}
*/
async function isPublished(version) {
try {
const response = await fetch(`https://registry.npmjs.org/hyperformula/${encodeURIComponent(version)}`, {
signal: AbortSignal.timeout(10_000),
});

return response.ok;
} catch {
return false;
}
}

/**
* Whether this build loads the published engine from jsDelivr: a build of the production branch, of a version on npm.
*
* @param {NodeJS.ProcessEnv} env The environment. Workers Builds sets `WORKERS_CI_BRANCH`.
* @param {string} version The engine version the docs are built from.
* @returns {Promise<boolean>}
*/
export async function resolveUsesCdn(env, version) {
if (env.WORKERS_CI_BRANCH !== PRODUCTION_BRANCH) {
return false;
}

const published = await isPublished(version);

if (!published) {
console.warn(`hyperformula@${version} is not on npm, so the live examples serve the engine from hyperformula/dist instead of jsDelivr.`);
}

return published;
}

/**
* The `<script>` tags that load the engine and its languages, in the order the examples need them.
*
* @param {boolean} usesCdn What {@link resolveUsesCdn} returned.
* @param {string} base The docs base path, with a leading and a trailing slash.
* @param {string} version The engine version the docs are built from.
* @returns {{ tag: 'script', attrs: { src: string } }[]}
*/
export function engineScripts(usesCdn, base, version) {
const root = usesCdn
? `https://cdn.jsdelivr.net/npm/hyperformula@${version}/dist/`
: `${base}${ENGINE_DIR}`;

return ENGINE_FILES.map((file) => ({ tag: 'script', attrs: { src: `${root}${file}` } }));
}

/**
* Astro integration that serves the engine from `hyperformula/dist` in every build that does not load it from
* jsDelivr: the dev server serves the files, and a build copies them into its output.
*
* @param {boolean} usesCdn What {@link resolveUsesCdn} returned.
* @param {string} base The docs base path, with a leading and a trailing slash.
* @returns {import('astro').AstroIntegration}
*/
export function engineAssets(usesCdn, base) {
const missing = () => ENGINE_FILES.filter((file) => !existsSync(join(ENGINE_DIST, file)));

return {
name: 'engine-assets',
hooks: {
'astro:server:setup': ({ server, logger }) => {
if (usesCdn) {
return;
}

if (missing().length) {
logger.warn(`The live examples need ${missing().join(', ')} in ${ENGINE_DIST}. Run \`npm run bundle-all\` from the repository root.`);
}

const prefix = `${base}${ENGINE_DIR}`;

server.middlewares.use((req, res, next) => {
const path = (req.url ?? '').split('?')[0];
const file = path.startsWith(prefix) ? path.slice(prefix.length) : null;

if (file === null || !ENGINE_FILES.includes(file) || !existsSync(join(ENGINE_DIST, file))) {
next();

return;
}

res.setHeader('Content-Type', 'text/javascript; charset=utf-8');
createReadStream(join(ENGINE_DIST, file)).pipe(res);
});
},
'astro:build:done': ({ dir, logger }) => {
if (usesCdn) {
return;
}

if (missing().length) {
throw new Error(`The live examples need ${missing().join(', ')} in ${ENGINE_DIST}. Run \`npm run bundle-all\` from the repository root before the docs build.`);
}

const target = join(fileURLToPath(dir), ENGINE_DIR);

ENGINE_FILES.forEach((file) => {
mkdirSync(dirname(join(target, file)), { recursive: true });
copyFileSync(join(ENGINE_DIST, file), join(target, file));
});
logger.info(`Copied the engine from ${ENGINE_DIST} into ${target}.`);
},
},
};
}
2 changes: 1 addition & 1 deletion docs/src/preview-license-key.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ export const TEST_KEY_MARKER = 'HYPERFORMULA INTERNAL TEST KEY';
/**
* The branch Workers Builds deploys to production. A build of it never gets the key.
*/
const PRODUCTION_BRANCH = 'master';
export const PRODUCTION_BRANCH = 'master';

/**
* One placeholder line, with its trailing comment: `// licenseKey: 'your-license-key', // get a key at ...`, with
Expand Down
6 changes: 5 additions & 1 deletion script/release/release-README.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,11 @@ describe decisions made from stale refs. The script marks these fetches
the freeze.
3. **Sets the version and the release date** — `version` in `hyperformula/package.json` and
`HT_RELEASE_DATE` in `hyperformula/ht.config.js`. Each is skipped when it already matches,
so a re-run does not rewrite files it already wrote.
so a re-run does not rewrite files it already wrote. The `version` is also the
version the production docs' live examples load from jsDelivr
(`docs/src/engine-scripts.mjs`), so this step moves that pin too. Every other
docs build, staging included, serves the engine it was built with, so the
examples run on the new engine during the freeze.
4. **Reinstalls dependencies** and regenerates the lock file — skipped when
the root `package-lock.json` already records the new version for the
`hyperformula` workspace *and* `node_modules` exists.
Expand Down
Loading