feat: the plugin listing, built from registry data
One YAML file per plugin. There is deliberately no version and no runtimes field in an entry: both are read from npm and JSR when the page is built, so a card cannot go stale or claim support a package never declared. The strictness lives in one flag. Under CI a registry that does not answer fails the build, because a listing that silently drops a plugin is worse than no deploy. Locally an unpublished package falls back to scripts/preview.mjs and says so — a site nobody can look at until its packages ship is a site nobody can design. The three seed plugins are unpublished today, so that fallback is what renders them; it goes away with them. Every card shows all four runtimes, never only the supported ones. Colour means the package declares it runs there, dim grey means it does not — and the tooltip is what separates "declared unsupported" from "nobody said", which look identical but are not the same fact. The brand marks carry no <title>: an SVG's own title wins over its parent's, which is why the first attempt showed a help cursor and no tooltip. They are aria-hidden and pointer-events: none, so the label and the hover both belong to the list item, and the tooltip works from the keyboard too. Type and palette are self-hosted from green-tea-site, so the sites read as one project rather than three that share a colour. Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
24 files changed
+5203
No files matched your search
@@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env node
|
||||
// Sube dist/ al docroot de cPanel por SFTP.
|
||||
//
|
||||
// El shell remoto está deshabilitado en esa cuenta, así que rsync, tar y cualquier
|
||||
// comando remoto están descartados: `sftp -b` es el único canal. Eso trae dos
|
||||
// consecuencias que este script asume en vez de intentar resolver:
|
||||
// - No borra nada. Los assets con hash viejos y las páginas que dejaron de
|
||||
// existir se quedan ahí. Es basura inofensiva; borrar a ciegas en ese docroot
|
||||
// se llevaría .well-known/acme-challenge y con él la renovación del certificado.
|
||||
// - No hay swap atómico, de ahí el orden de subida (ver buildBatch).
|
||||
import { readdirSync, existsSync } from 'node:fs';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { join, relative, dirname } from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
// El destino sale del entorno, no del repositorio. No es un secreto — la llave privada
|
||||
// nunca ha estado aquí y el acceso es sólo por clave — pero un usuario de cPanel escrito
|
||||
// en un repo público es la mitad de un par de credenciales y un objetivo confirmado, a
|
||||
// cambio de nada. Se leen tarde, dentro del deploy, para que `--self-test` siga corriendo
|
||||
// en CI sin necesidad de configurarlas.
|
||||
const REMOTE = process.env.DEPLOY_REMOTE ?? 'public_html';
|
||||
const DIST = fileURLToPath(new URL('../dist/', import.meta.url));
|
||||
|
||||
/**
|
||||
* Rutas relativas a dist/ -> batch de sftp. Puro a propósito: el orden es lo único
|
||||
* delicado que hay aquí, y así se puede probar sin tocar ni el disco ni la red.
|
||||
*/
|
||||
export function buildBatch(paths) {
|
||||
// .htaccess nunca viaja desde dist/. El que está en el servidor lleva además el
|
||||
// bloque de handlers que genera cPanel (ea-php81 en el apex, distinto por dominio),
|
||||
// y ese bloque no está en el repo: subir el de dist/ le cambiaría la versión de PHP
|
||||
// al dominio principal en silencio.
|
||||
const files = paths.filter((p) => p !== '.htaccess');
|
||||
// Cada ruta aporta toda su cadena de ancestros: `mkdir` no crea padres, así que
|
||||
// blog/2026/post.html necesita `blog` antes que `blog/2026`.
|
||||
const ancestors = (p) => dirname(p).split('/').map((_, i, a) => a.slice(0, i + 1).join('/'));
|
||||
const dirs = [...new Set(files.flatMap(ancestors))]
|
||||
.filter((d) => d !== '.')
|
||||
.sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));
|
||||
// HTML al final: sin swap atómico, hay una ventana en la que el HTML nuevo ya está
|
||||
// servido y sus assets no han llegado. Subiendo el HTML de último la ventana existe
|
||||
// al revés — HTML viejo, assets nuevos — que nadie nota.
|
||||
const isHtml = (p) => p.endsWith('.html');
|
||||
return [
|
||||
`cd ${REMOTE}`,
|
||||
`lcd ${DIST}`,
|
||||
...dirs.map((d) => `-mkdir ${d}`), // el '-' deja continuar si ya existe
|
||||
...files.filter((p) => !isHtml(p)).map((p) => `put ${p} ${p}`),
|
||||
...files.filter(isHtml).map((p) => `put ${p} ${p}`),
|
||||
'bye',
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function walk(dir, base = dir) {
|
||||
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
|
||||
const p = join(dir, e.name);
|
||||
return e.isDirectory() ? walk(p, base) : [relative(base, p)];
|
||||
});
|
||||
}
|
||||
|
||||
function selfTest() {
|
||||
const batch = buildBatch(['index.html', '.htaccess', 'og.png', 'blog/x/index.html', '_astro/a.css']);
|
||||
const at = (line) => {
|
||||
const i = batch.split('\n').indexOf(line);
|
||||
assert.notEqual(i, -1, `falta la línea: ${line}`);
|
||||
return i;
|
||||
};
|
||||
assert.ok(!batch.includes('.htaccess'), '.htaccess no debe viajar desde dist/');
|
||||
assert.ok(at('-mkdir blog') < at('-mkdir blog/x'), 'los directorios padre van primero');
|
||||
assert.ok(at('-mkdir blog/x') < at('put blog/x/index.html blog/x/index.html'), 'mkdir antes del put');
|
||||
assert.ok(at('put og.png og.png') < at('put index.html index.html'), 'el HTML se sube al final');
|
||||
console.log('deploy self-test ok');
|
||||
}
|
||||
|
||||
if (process.argv.includes('--self-test')) {
|
||||
selfTest();
|
||||
} else {
|
||||
if (!existsSync(DIST)) {
|
||||
console.error('No hay dist/. Corre `npm run build` primero.');
|
||||
process.exit(1);
|
||||
}
|
||||
const paths = walk(DIST);
|
||||
if (paths.includes('.htaccess')) {
|
||||
console.error('nota: dist/.htaccess no se sube. Si cambiaron las redirecciones, súbelo a mano');
|
||||
console.error(' con el bloque PHP de cPanel ya mezclado (ver README).\n');
|
||||
}
|
||||
const batch = buildBatch(paths);
|
||||
console.log(batch);
|
||||
if (!process.argv.includes('--dry-run')) {
|
||||
const host = process.env.DEPLOY_HOST;
|
||||
const key = process.env.DEPLOY_KEY ?? `${process.env.HOME}/.ssh/expressive-tea-cpanel`;
|
||||
if (!host) {
|
||||
console.error('Falta DEPLOY_HOST (usuario@host del cPanel). Ver README.');
|
||||
console.error(' DEPLOY_HOST=usuario@dominio npm run deploy');
|
||||
process.exit(2);
|
||||
}
|
||||
if (!existsSync(key)) {
|
||||
console.error(`No existe la clave ${key}. Pon la ruta en DEPLOY_KEY si vive en otro sitio.`);
|
||||
process.exit(2);
|
||||
}
|
||||
const r = spawnSync('sftp', ['-i', key, '-b', '-', host], { input: batch, stdio: ['pipe', 'inherit', 'inherit'] });
|
||||
process.exit(r.status ?? 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// What the seed plugins declare, copied from their `package.json` in Green-Tea/plugins.
|
||||
//
|
||||
// This exists so the site can be designed and reviewed before the packages ship. It is used ONLY
|
||||
// when a registry has no answer and `CI` is unset — in GitHub Actions a missing package fails the
|
||||
// build instead, which is where the real check lives.
|
||||
//
|
||||
// **Delete this file, and its import in `src/pages/index.astro`, once the three are published.**
|
||||
// Every entry here is a claim nobody verified; the registry is the source of truth and this is a
|
||||
// stand-in for a registry that does not have the package yet.
|
||||
export const PREVIEW = {
|
||||
'@green-tea/jwt': { version: '26.9.0-beta.0', engines: { node: '>=22', deno: '>=2', bun: '>=1.3' } },
|
||||
'@green-tea/metrics': { version: '26.9.0-beta.0', engines: { node: '>=22', deno: '>=2', bun: '>=1.3' } },
|
||||
'@green-tea/rate-limit': { version: '26.9.0-beta.0', engines: { node: '>=22', deno: '>=2', bun: '>=1.3' } },
|
||||
};
|
||||
@@ -0,0 +1,138 @@
|
||||
// Every registry call lives here, and both the validator and the site build import it. One
|
||||
// implementation on purpose: if the check that gates a merge and the data that renders a card came
|
||||
// from two readers, a plugin could pass validation and then render wrong.
|
||||
|
||||
/** The four runtimes, in the order every card shows them. */
|
||||
export const RUNTIMES = Object.freeze(['node', 'deno', 'bun', 'workerd']);
|
||||
|
||||
/**
|
||||
* Where the strictness lives.
|
||||
*
|
||||
* In GitHub Actions a package that does not answer is a failure — that is the check, and it runs
|
||||
* against the live registries on every pull request and every push to main. Locally it is a
|
||||
* warning and the card renders from `preview.mjs`, because a site you cannot look at until its
|
||||
* packages ship is a site nobody can design.
|
||||
*/
|
||||
export const STRICT = process.env.CI === 'true';
|
||||
|
||||
/** Compare two semver strings. Enough for CalVer + `-beta.N`; no dependency for a dozen lines. */
|
||||
function compare(a, b) {
|
||||
const split = (v) => {
|
||||
const [core, pre] = v.split('-');
|
||||
return [core.split('.').map(Number), pre ? pre.split('.') : null];
|
||||
};
|
||||
const [an, ap] = split(a);
|
||||
const [bn, bp] = split(b);
|
||||
for (let i = 0; i < 3; i += 1) if (an[i] !== bn[i]) return an[i] - bn[i];
|
||||
// A release outranks its own prerelease: 1.0.0 > 1.0.0-beta.1.
|
||||
if (!ap && !bp) return 0;
|
||||
if (!ap) return 1;
|
||||
if (!bp) return -1;
|
||||
for (let i = 0; i < Math.max(ap.length, bp.length); i += 1) {
|
||||
const x = ap[i];
|
||||
const y = bp[i];
|
||||
if (x === y) continue;
|
||||
if (x === undefined) return -1;
|
||||
if (y === undefined) return 1;
|
||||
const numeric = /^\d+$/.test(x) && /^\d+$/.test(y);
|
||||
return numeric ? Number(x) - Number(y) : String(x).localeCompare(String(y));
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest of a version list.
|
||||
*
|
||||
* Never npm's `dist-tags.latest` and never JSR's `latest`: JSR returns `null` there while a
|
||||
* package has only prereleases, which is every green-tea package today — verified against
|
||||
* `@green-tea/core`, which has two published versions and `"latest": null`.
|
||||
*/
|
||||
export function newestVersion(versions) {
|
||||
return [...versions].sort(compare).pop();
|
||||
}
|
||||
|
||||
async function getJson(url, what) {
|
||||
const response = await fetch(url, { headers: { accept: 'application/json' } });
|
||||
if (!response.ok) throw new Error(`${what}: ${url} answered ${response.status}`);
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
/** The npm packument, reduced to what validation and the card need. */
|
||||
export async function readNpm(name) {
|
||||
const packument = await getJson(`https://registry.npmjs.org/${name.replace('/', '%2f')}`, `npm ${name}`);
|
||||
const versions = Object.keys(packument.versions ?? {});
|
||||
const newest = newestVersion(versions);
|
||||
const version = newest ? packument.versions[newest] : {};
|
||||
|
||||
return {
|
||||
versions,
|
||||
newest,
|
||||
description: version.description ?? '',
|
||||
engines: version.engines ?? {},
|
||||
// All three maps: a check treats core in `devDependencies` as correct and core in
|
||||
// `dependencies` or `peerDependencies` as a convention smell worth a warning, so it has to be
|
||||
// able to tell them apart rather than just miss it.
|
||||
devDependencies: version.devDependencies ?? {},
|
||||
dependencies: version.dependencies ?? {},
|
||||
peerDependencies: version.peerDependencies ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
/** JSR, reduced the same way. Three calls, because JSR splits what npm returns in one document. */
|
||||
export async function readJsr(name) {
|
||||
const [scope, pkg] = name.replace(/^@/, '').split('/');
|
||||
const base = `https://api.jsr.io/scopes/${scope}/packages/${pkg}`;
|
||||
const info = await getJson(base, `jsr ${name}`);
|
||||
const listing = await getJson(`${base}/versions`, `jsr ${name} versions`);
|
||||
// `items`, not `latestVersion`. See newestVersion.
|
||||
const versions = (listing.items ?? []).map((item) => item.version);
|
||||
const newest = newestVersion(versions);
|
||||
const dependencies = newest ? await getJson(`${base}/versions/${newest}/dependencies`, `jsr ${name} deps`) : [];
|
||||
|
||||
return { versions, newest, runtimeCompat: info.runtimeCompat ?? {}, dependencies };
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of the four runtimes a package declares.
|
||||
*
|
||||
* npm says it in `engines`, which also carries non-runtime keys like `npm` — hence the filter
|
||||
* against RUNTIMES rather than taking every key. JSR says it in `runtimeCompat`, where `false` is
|
||||
* a declaration that it does *not* run there and must never be read as support.
|
||||
*/
|
||||
export function declaredRuntimes({ engines, runtimeCompat }) {
|
||||
if (runtimeCompat && Object.keys(runtimeCompat).length > 0) {
|
||||
return RUNTIMES.filter((runtime) => runtimeCompat[runtime] === true);
|
||||
}
|
||||
|
||||
return RUNTIMES.filter((runtime) => engines?.[runtime] !== undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything one card needs, live where possible.
|
||||
*
|
||||
* Under `CI` a registry that does not answer throws and fails the build, which is the rule that
|
||||
* stops a stale or half-empty listing reaching production. Off CI it falls back to `preview.mjs`
|
||||
* and says so, loudly, once per package.
|
||||
*/
|
||||
export async function readEntry(entry, preview) {
|
||||
try {
|
||||
const npm = entry.npm ? await readNpm(entry.npm) : undefined;
|
||||
const jsr = entry.jsr ? await readJsr(entry.jsr) : undefined;
|
||||
|
||||
return {
|
||||
version: (npm ?? jsr).newest,
|
||||
// npm's `engines` is the richer of the two — JSR's `runtimeCompat` is empty far more often,
|
||||
// including on `@green-tea/core` itself — so it wins when both exist.
|
||||
runtimes: declaredRuntimes({ engines: npm?.engines, runtimeCompat: jsr?.runtimeCompat }),
|
||||
live: true,
|
||||
};
|
||||
} catch (error) {
|
||||
if (STRICT) throw error;
|
||||
const fallback = preview[entry.npm ?? entry.jsr];
|
||||
if (!fallback) throw error;
|
||||
console.warn(` not published yet, rendering from preview data: ${entry.npm ?? entry.jsr}`);
|
||||
|
||||
return { version: fallback.version, runtimes: declaredRuntimes({ engines: fallback.engines }), live: false };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user