mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-12-02 21:25:26 +09:00
SDK 1.2.0 -> 1.3.0 (additive). Auditing the extension surface for plan 79 found the localization gap I expected and two pre-existing bugs I did not. The gap: extensions had no way to translate anything. The SDK now re-exports the HOST's translation surface -- useTranslation, Trans, t, useLocale, useLabel, useFormat and the intl door -- and i18next/react-i18next join the shared vendor singletons. That sharing is the load-bearing part: an extension bundling its own i18next would get a separate, uninitialised instance, so every t() in it would render its English default forever and nothing would report it. Exactly the "two React copies" hazard vendorShare already documents, and exactly the failure mode this plan hit twice in core. They also join dedupe/optimizeDeps for the same reason React is there. The bugs, both caused by the same duplication: - The import map listed `react` and `react-router-dom`, but no shim existed for either. A runtime extension importing bare `react` 404'd at load. - The serverkit-sdk shim re-exported 26 of the SDK's 71 exports. An extension importing Button, Modal, EmptyState, formatBytes or timeAgo from the SDK got `undefined`. The shim's own comment claimed parity was "asserted by the frontend build + backend test_sdk_contract"; nothing asserted it. Three files independently restated the same module list -- the import map, the namespace capture, and one hand-written shim per module -- so they drifted. Now vendorManifest.js is the list, generate-vendor-shims.mjs derives every shim's exports (from the real package's namespace, or from the SDK entry's own export statements -- never typed by hand), the import map is built from the same manifest, and `--check` fails the build on drift. 26 -> 85 exports on the SDK shim, 6 -> 8 shims, all present. Manifest contributions gain an optional `labelKey` beside `label` for nav, tabs and command-palette entries, resolved at render by the same translateLabel core uses -- data cannot call t(), and a label resolved at import would translate once and never follow a switch. Omitting it renders `label` verbatim, which is what every existing extension does, so nothing breaks. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
143 lines
5.7 KiB
JavaScript
143 lines
5.7 KiB
JavaScript
#!/usr/bin/env node
|
|
// Generate the runtime-extension vendor shims from one source of truth.
|
|
//
|
|
// A shim hands a runtime-loaded extension the HOST's instance of a module
|
|
// (captured in globalThis.__SK_VENDOR__ by vendorShare.js) instead of letting
|
|
// the extension bundle its own — two copies of React means "Invalid hook
|
|
// call", and two copies of i18next means an extension whose translations
|
|
// silently never load.
|
|
//
|
|
// Every shim is the same six lines around a list of export names, so the lists
|
|
// are DERIVED, never typed: from the real package's namespace for vendored
|
|
// modules, and from the SDK entry's own export statements for the SDK. Three
|
|
// hand-maintained copies of those lists is what produced the two bugs this
|
|
// replaces (see src/plugins/runtime/vendorManifest.js).
|
|
//
|
|
// Usage (from frontend/):
|
|
// node scripts/generate-vendor-shims.mjs # write the shims
|
|
// node scripts/generate-vendor-shims.mjs --check # fail if they drift
|
|
|
|
import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
|
import { dirname, join, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { parse } from 'espree';
|
|
import { VENDOR_MODULES } from '../src/plugins/runtime/vendorManifest.js';
|
|
|
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
const root = resolve(here, '..');
|
|
const outDir = resolve(root, 'public', 'serverkit-vendor');
|
|
const sdkEntry = resolve(root, 'src', 'plugins', 'sdk', 'index.js');
|
|
const vendorShare = resolve(root, 'src', 'plugins', 'runtime', 'vendorShare.js');
|
|
|
|
/** Export names of the SDK entry, read from its own export statements. */
|
|
function sdkExportNames() {
|
|
const ast = parse(readFileSync(sdkEntry, 'utf8'), {
|
|
ecmaVersion: 'latest',
|
|
sourceType: 'module',
|
|
});
|
|
const names = [];
|
|
for (const node of ast.body) {
|
|
if (node.type === 'ExportNamedDeclaration') {
|
|
for (const specifier of node.specifiers || []) {
|
|
names.push(specifier.exported.name);
|
|
}
|
|
const declaration = node.declaration;
|
|
if (declaration?.type === 'VariableDeclaration') {
|
|
for (const d of declaration.declarations) names.push(d.id.name);
|
|
} else if (declaration?.id) {
|
|
names.push(declaration.id.name);
|
|
}
|
|
}
|
|
}
|
|
// `default` cannot be re-exported as a const; the SDK has no default anyway.
|
|
return [...new Set(names)].filter((name) => name !== 'default');
|
|
}
|
|
|
|
/** Export names of a real package, read from its namespace object. */
|
|
async function moduleExportNames(specifier) {
|
|
const namespace = await import(specifier);
|
|
return Object.keys(namespace)
|
|
.filter((name) => name !== 'default')
|
|
// Valid identifiers only — a namespace can carry exotic keys that
|
|
// cannot appear on the left of `export const`.
|
|
.filter((name) => /^[A-Za-z_$][\w$]*$/.test(name))
|
|
.sort();
|
|
}
|
|
|
|
function render(specifier, names, hasDefault) {
|
|
const lines = [
|
|
'// GENERATED by scripts/generate-vendor-shims.mjs — do not edit.',
|
|
`// Runtime-extension shim for \`${specifier}\`: re-exports the HOST instance so`,
|
|
'// the extension and the panel share one copy (see vendorManifest.js).',
|
|
`const m = (globalThis.__SK_VENDOR__ || {})['${specifier}'];`,
|
|
'if (!m) {',
|
|
` throw new Error('[serverkit] host ${specifier} unavailable — vendorShare did not run');`,
|
|
'}',
|
|
];
|
|
if (hasDefault) lines.push('export default m.default ?? m;');
|
|
for (const name of names) lines.push(`export const ${name} = m.${name};`);
|
|
return `${lines.join('\n')}\n`;
|
|
}
|
|
|
|
const generated = new Map();
|
|
for (const entry of VENDOR_MODULES) {
|
|
let names;
|
|
let hasDefault = false;
|
|
if (entry.exportsFrom === 'sdk') {
|
|
names = sdkExportNames();
|
|
} else {
|
|
const namespace = await import(entry.specifier);
|
|
hasDefault = 'default' in namespace;
|
|
names = await moduleExportNames(entry.specifier);
|
|
}
|
|
generated.set(entry.file, render(entry.specifier, names, hasDefault));
|
|
}
|
|
|
|
// vendorShare.js must capture exactly these specifiers, or a shim resolves to
|
|
// undefined at runtime with a misleading "did not run" message.
|
|
const shareSource = readFileSync(vendorShare, 'utf8');
|
|
const missingShare = VENDOR_MODULES
|
|
.map((entry) => entry.specifier)
|
|
.filter((specifier) => !shareSource.includes(`'${specifier}':`));
|
|
|
|
const problems = [];
|
|
if (missingShare.length) {
|
|
problems.push(`vendorShare.js does not capture: ${missingShare.join(', ')}`);
|
|
}
|
|
|
|
if (process.argv.includes('--check')) {
|
|
const onDisk = new Set(readdirSync(outDir).filter((name) => name.endsWith('.mjs')));
|
|
for (const [file, contents] of generated) {
|
|
if (!onDisk.has(file)) {
|
|
problems.push(`missing shim: ${file}`);
|
|
continue;
|
|
}
|
|
onDisk.delete(file);
|
|
if (readFileSync(join(outDir, file), 'utf8') !== contents) {
|
|
problems.push(`stale shim: ${file}`);
|
|
}
|
|
}
|
|
for (const orphan of onDisk) problems.push(`orphan shim (not in the manifest): ${orphan}`);
|
|
|
|
if (problems.length) {
|
|
console.error('\nvendor shim check failed:\n');
|
|
for (const problem of problems) console.error(` ${problem}`);
|
|
console.error('\n node scripts/generate-vendor-shims.mjs\n');
|
|
process.exit(1);
|
|
}
|
|
console.log(`✓ vendor shims: ${generated.size} shims match the manifest.`);
|
|
process.exit(0);
|
|
}
|
|
|
|
if (problems.length) {
|
|
console.error('\nvendor shim generation failed:\n');
|
|
for (const problem of problems) console.error(` ${problem}`);
|
|
console.error('');
|
|
process.exit(1);
|
|
}
|
|
|
|
for (const [file, contents] of generated) {
|
|
writeFileSync(join(outDir, file), contents);
|
|
}
|
|
console.log(`✓ wrote ${generated.size} vendor shims to public/serverkit-vendor/.`);
|