@veriforms/webapp-vite 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,501 @@
1
+ // @veriforms/webapp-vite — the Vite plugin for VeriForms web apps built in code
2
+ // (docs/webapp-builder/CWA-CODE-APPS-CONCEPT.md §4.5 and §7.6).
3
+ //
4
+ // What it makes `vite build` produce, so `vf app push` can upload it as one build:
5
+ // - one entry per page: src/pages/{name}.tsx → page {name}; "main" is the main page.
6
+ // Names follow the gateway's page rules (VeriForms.Ai.CwaPages; pinned by a test);
7
+ // - one small HTML shell per page (pages/{name}.html) that loads the page's entry and CSS
8
+ // through {{vf_bundle}}/… — the gateway replaces it with the build's address (CwaBundles);
9
+ // - React and the curated packages (zod, date-fns, clsx) are NOT bundled: their specifiers stay
10
+ // bare imports and the gateway's import map gives every page the platform's reviewed copy; every
11
+ // name a page imports from one is checked against what that copy exports;
12
+ // - readable output: whitespace is removed, identifiers and syntax are kept, so the platform's
13
+ // checks and the release review read the real names (owner decision: whitespace-only);
14
+ // - what the server would refuse anyway fails the build here, with the file and line.
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ // The platform's vendor manifest (Veriforms.AppsGateway/Vendor), copied by tools/webapp-vendor; a test pins the two.
18
+ import platform from './platform-modules.json' with { type: 'json' };
19
+ import { buildServerFunctions, findServerFunctionFiles, serverTypes, SERVER_TYPES_FILE } from './server.js';
20
+ export * from './server.js';
21
+ /** What a shell writes for the build's base path (VeriForms.Ai.CwaBundles.Placeholder). */
22
+ export const BUNDLE_PLACEHOLDER = '{{vf_bundle}}';
23
+ /** The bare specifiers the platform provides (the gateway's import map, AppVendor). */
24
+ export const PLATFORM_MODULES = platform.imports;
25
+ /** The served packages and the versions the platform pins ("zod" → "4.6.7"); install exactly these. */
26
+ export const PLATFORM_PACKAGES = platform.packages;
27
+ /** What each provided specifier exports ("default" for a default export). */
28
+ export const PLATFORM_EXPORTS = platform.exports;
29
+ /**
30
+ * The npm packages a build may use (VeriForms.Ai.CwaBundles.AllowedPackages; owner decision 2): React and
31
+ * the curated packages (provided by the platform, never bundled) and the platform's SDK packages. Importing
32
+ * any other fails the build — the upload would be refused.
33
+ */
34
+ export const ALLOWED_PACKAGES = ['react', 'react-dom', 'scheduler', 'loose-envify', 'js-tokens',
35
+ 'zod', 'date-fns', 'clsx',
36
+ '@veriforms/webapp-sdk', '@veriforms/webapp-react'];
37
+ /** The package a bare specifier names ("@scope/name/sub" → "@scope/name", "name/sub" → "name"). */
38
+ export function packageOf(specifier) {
39
+ const parts = specifier.split('/');
40
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
41
+ }
42
+ /** The main page's name. */
43
+ export const MAIN_PAGE = 'main';
44
+ /** A page name (VeriForms.Ai.CwaPages.NamePattern). */
45
+ export const PAGE_NAME = /^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])?$/;
46
+ /** Names the gateway uses itself (VeriForms.Ai.CwaPages.ReservedNames, minus "main"). */
47
+ export const RESERVED_PAGE_NAMES = ['index', 'app', 'files', 'draft', 'dev', 'api', 'auth', 'agent', 'ux', 'upload', 'collab',
48
+ 'values', 'link', 'correct', 'test-payment', 'vf-errors', 'vf-strip', 'fn'];
49
+ /** At most this many pages, the main page included (VeriForms.Ai.CwaPages.MaxPages). */
50
+ export const MAX_PAGES = 20;
51
+ /** Vite's preload helper module (vite:build-import-analysis), replaced by the plugin. */
52
+ const VITE_PRELOAD_HELPER = '\0vite/preload-helper.js';
53
+ const PAGE_FILE = /\.(tsx|ts|jsx|js)$/;
54
+ /** The pages of a project: name → entry file. Throws, naming every problem, when they cannot be a web app's pages. */
55
+ export function findPages(root, pagesDir = 'src/pages') {
56
+ const dir = path.resolve(root, pagesDir);
57
+ if (!fs.existsSync(dir))
58
+ throw plainError(`[veriforms] ${pagesDir} does not exist. Each page is a file there: ${pagesDir}/main.tsx is the main page.`);
59
+ const pages = {};
60
+ const problems = [];
61
+ for (const file of fs.readdirSync(dir).sort()) {
62
+ if (!PAGE_FILE.test(file) || file.endsWith('.d.ts') || /\.(test|spec)\./.test(file))
63
+ continue;
64
+ const name = file.replace(PAGE_FILE, '');
65
+ if (!PAGE_NAME.test(name))
66
+ problems.push(`${pagesDir}/${file}: "${name}" is not a page name (1–30 lowercase letters, digits and hyphens, not at the start or end).`);
67
+ else if (RESERVED_PAGE_NAMES.includes(name))
68
+ problems.push(`${pagesDir}/${file}: "${name}" is an address the gateway uses itself; choose another name.`);
69
+ else if (pages[name])
70
+ problems.push(`${pagesDir}/${file}: a second file for page "${name}".`);
71
+ else
72
+ pages[name] = path.join(dir, file);
73
+ }
74
+ if (!pages[MAIN_PAGE])
75
+ problems.push(`${pagesDir}/main.tsx is missing: every web app has a main page.`);
76
+ if (Object.keys(pages).length > MAX_PAGES)
77
+ problems.push(`${Object.keys(pages).length} pages; a web app may have at most ${MAX_PAGES}.`);
78
+ if (problems.length)
79
+ throw plainError('[veriforms] The pages cannot be built:\n ' + problems.join('\n '));
80
+ return pages;
81
+ }
82
+ /**
83
+ * The folder of a project's server functions (CWA-CODE-BACKEND-CONCEPT §5.1; R7 batch 3b). Server functions are a
84
+ * PILOT FOR PLATFORM ADMINISTRATORS: a project builds src/server/ only when it opts in with
85
+ * `veriformsWebApp({ serverFunctions: true })`; without it a project that has the folder does not build (the
86
+ * gateway would refuse its server/ folder anyway, bundle_server_code_not_enabled). Whatever the option, no page
87
+ * may import from src/server/ — server code in a page would be published to every visitor.
88
+ */
89
+ export const SERVER_DIR = 'src/server';
90
+ const SERVER_NOT_ENABLED = 'server functions are not enabled for this build';
91
+ /** The refusal for a project that has src/server/ while server functions are not enabled, or undefined. */
92
+ export function serverDirProblem(root, enabled = false) {
93
+ const dir = path.resolve(root, SERVER_DIR);
94
+ return fs.existsSync(dir) && !enabled
95
+ ? `[veriforms] ${SERVER_DIR}/ is reserved for server functions, and ${SERVER_NOT_ENABLED}. `
96
+ + 'Server functions are a pilot for platform administrators: only a platform administrator may push and release them '
97
+ + '(for a web app in any account), with veriformsWebApp({ serverFunctions: true }) in vite.config.ts — for everyone else the upload is refused. '
98
+ + `Otherwise move code the pages use to another folder under src/ and remove ${SERVER_DIR}/.`
99
+ : undefined;
100
+ }
101
+ /** True when an import from `importer` names a module inside the project's src/server/. */
102
+ export function importsServerCode(root, id, importer) {
103
+ if (!importer || id.startsWith('\0'))
104
+ return false;
105
+ const clean = id.split('?')[0];
106
+ const isPath = clean.startsWith('.') || clean.startsWith('/') || /^[a-zA-Z]:[\\/]/.test(clean);
107
+ if (!isPath)
108
+ return false;
109
+ const server = path.resolve(root, SERVER_DIR);
110
+ const inside = (target) => {
111
+ const rel = path.relative(server, target);
112
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
113
+ };
114
+ if (clean.startsWith('.'))
115
+ return inside(path.resolve(path.dirname(importer), clean));
116
+ // An absolute file path, or one from the project root ("/src/server/x", as Vite writes it).
117
+ return inside(path.resolve(clean)) || inside(path.resolve(root, clean.replace(/^[\\/]+/, '')));
118
+ }
119
+ /**
120
+ * A refusal thrown outside Rollup (the `config` hook): Vite's CLI prints an error's `stack`, so the
121
+ * stack IS the sentence — the refusal, and no frames of the bundler after it (R4-13).
122
+ */
123
+ export function plainError(message) {
124
+ const error = new Error(message);
125
+ error.stack = message;
126
+ return error;
127
+ }
128
+ /**
129
+ * A refusal raised through Rollup (`this.error`): the sentence, the file and the line. Rollup copies
130
+ * these properties onto the error it throws; the empty `stack` is what keeps Vite from appending the
131
+ * bundler's own frames ("at getRollupError …") to the message it prints — ten lines that hid the one
132
+ * that says what to fix (R4-13). The file, the line and the code frame are still printed.
133
+ */
134
+ export function refusal(message, id, line) {
135
+ return { message, stack: '', ...(id ? { id } : {}), ...(line ? { loc: { line, column: 0 } } : {}) };
136
+ }
137
+ /**
138
+ * The calls that open a connection to an address: fetch, navigator.sendBeacon, XMLHttpRequest's
139
+ * open(method, url), new WebSocket / EventSource — the data-call sinks of the server's own list
140
+ * (VeriForms.Ai.CwaPageSafety.LoadSinks; a test pins the two).
141
+ */
142
+ export const NETWORK_CALL_SINKS = ['fetch', 'sendBeacon', 'open', 'WebSocket', 'EventSource'];
143
+ const FORBIDDEN = [
144
+ { rule: 'eval', pattern: /\beval\s*\(/, message: 'eval() runs a string as code; the platform refuses it. Write the code itself.' },
145
+ { rule: 'new-function', pattern: /\bnew\s+Function\s*\(/, message: 'new Function() runs a string as code; the platform refuses it.' },
146
+ { rule: 'html-from-string', pattern: /\bdangerouslySetInnerHTML\b/, message: 'dangerouslySetInnerHTML writes HTML from a string; the platform refuses writing HTML from strings. Render elements instead.' },
147
+ { rule: 'inner-html', pattern: /\.(?:innerHTML|outerHTML)\s*=(?!=)|\binsertAdjacentHTML\s*\(|\bdocument\.write\s*\(/, message: 'Writing HTML from a string is refused by the platform. Create elements (or render React) instead.' },
148
+ { rule: 'external-import', pattern: /(?:\bfrom\s*|\bimport\s*\(\s*|\bimport\s+)["'](?:https?:)?\/\//, message: 'A web app loads nothing from other hosts. Install the package and let the build include it.' },
149
+ // R4-04: a call to a literal absolute address built, uploaded and was first noticed in a browser
150
+ // console — the page's policy (connect-src 'self') blocks it there. The upload check refuses a
151
+ // foreign host too (CwaPageSafety external_url); this names the call at build time, whatever the host.
152
+ {
153
+ rule: 'foreign-call',
154
+ pattern: /(?:\bfetch\s*\(\s*|\bsendBeacon\s*\(\s*|\bnew\s+(?:WebSocket|EventSource)\s*\(\s*|\.open\s*\(\s*["'`][A-Za-z]+["'`]\s*,\s*)["'`](?:https?:|wss?:)?\/\//,
155
+ message: 'A page calls only its own sources: a request to another address is blocked in the browser (connect-src \'self\') and refused at upload. '
156
+ + 'Declare an "http" source in config.json and read it with fetchSource / useSource — the server makes the call.',
157
+ },
158
+ ];
159
+ /** What in this source the server would refuse (comments are not skipped: the server reads them as code too). */
160
+ export function scanSource(code) {
161
+ const findings = [];
162
+ const lines = code.split(/\r?\n/);
163
+ lines.forEach((text, i) => {
164
+ for (const f of FORBIDDEN)
165
+ if (f.pattern.test(text))
166
+ findings.push({ rule: f.rule, line: i + 1, message: f.message });
167
+ });
168
+ return findings;
169
+ }
170
+ /** The refusal of a name the platform's copy of a provided module does not export — one sentence for both checks. */
171
+ export function notExportedMessage(where, name, spec) {
172
+ const pkg = packageOf(spec);
173
+ return `[veriforms] ${where} imports "${name}" from "${spec}", which the platform's copy`
174
+ + ` (${PLATFORM_PACKAGES[pkg] ? `${pkg}@${PLATFORM_PACKAGES[pkg]}` : spec}) does not export.`;
175
+ }
176
+ const nameOf = (n) => {
177
+ const node = n;
178
+ return node?.type === 'Identifier' ? String(node.name) : node?.type === 'Literal' ? String(node.value) : undefined;
179
+ };
180
+ /**
181
+ * Every name a module's import and `export … from` declarations take from a provided module, read from
182
+ * the module's parsed AST (after TypeScript is stripped, before tree-shaking). `import * as` takes no
183
+ * single name and is left out; a default import is "default".
184
+ */
185
+ export function providedImports(ast) {
186
+ const found = [];
187
+ for (const raw of ast?.body ?? []) {
188
+ const node = raw;
189
+ if (node.type !== 'ImportDeclaration' && node.type !== 'ExportNamedDeclaration')
190
+ continue;
191
+ const spec = node.source?.value;
192
+ if (typeof spec !== 'string' || !PLATFORM_EXPORTS[spec])
193
+ continue;
194
+ for (const s of node.specifiers ?? []) {
195
+ const name = s.type === 'ImportDefaultSpecifier' ? 'default'
196
+ : s.type === 'ImportSpecifier' ? nameOf(s.imported)
197
+ : s.type === 'ExportSpecifier' ? nameOf(s.local)
198
+ : undefined;
199
+ if (name)
200
+ found.push({ spec, name });
201
+ }
202
+ }
203
+ return found;
204
+ }
205
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
206
+ /**
207
+ * The line of the original source where `name` is imported from `spec`: in the declaration naming both,
208
+ * else the first declaration naming spec; undefined when the source has none (the message then names the file).
209
+ */
210
+ export function importLine(source, spec, name) {
211
+ // One declaration: from its keyword to its `from "spec"`, never across the next import/export (no semicolons).
212
+ const declaration = new RegExp(`\\b(?:import|export)\\b(?:(?!\\b(?:import|export)\\b)[^;])*?\\bfrom\\s*(["'])${escapeRegExp(spec)}\\1`, 'g');
213
+ const lineAt = (offset) => source.slice(0, offset).split('\n').length;
214
+ let first;
215
+ for (const m of source.matchAll(declaration)) {
216
+ const at = m.index ?? 0;
217
+ first ?? (first = lineAt(at));
218
+ if (name === 'default') {
219
+ // `import x from` / `import x, { … } from`: a default import is the identifier right after `import`.
220
+ if (/^import\s+[\w$]+\s*(?:,|from\b)/.test(m[0]))
221
+ return lineAt(at);
222
+ continue;
223
+ }
224
+ const word = m[0].search(new RegExp(`(?<![\\w$])${escapeRegExp(name)}(?![\\w$])`));
225
+ if (word >= 0)
226
+ return lineAt(at + word);
227
+ }
228
+ return first;
229
+ }
230
+ const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
231
+ /** A page's HTML shell: its CSS and its entry, through the placeholder. */
232
+ export function shell(opts) {
233
+ return '<!doctype html>\n'
234
+ + `<html lang="${escapeHtml(opts.lang)}">\n<head>\n<meta charset="utf-8">\n`
235
+ + '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
236
+ + `<title>${escapeHtml(opts.title)}</title>\n`
237
+ + opts.styles.map((css) => `<link rel="stylesheet" href="${BUNDLE_PLACEHOLDER}/${css}">\n`).join('')
238
+ + `<script type="module" src="${BUNDLE_PLACEHOLDER}/${opts.script}"></script>\n`
239
+ + '</head>\n<body>\n<div id="root"></div>\n</body>\n</html>\n';
240
+ }
241
+ /** Where `vf app dev` keeps the draft preview's address (refreshed while it runs; the token lives 15 minutes). */
242
+ export const DEV_PREVIEW_FILE = '.vf-dev-preview';
243
+ /** The draft preview's address, as `vf app dev` last wrote it; undefined when it is not running. */
244
+ export function readDevPreview(root) {
245
+ const file = path.join(root, DEV_PREVIEW_FILE);
246
+ if (!fs.existsSync(file))
247
+ return undefined;
248
+ const text = fs.readFileSync(file, 'utf8').trim();
249
+ try {
250
+ return new URL(text);
251
+ }
252
+ catch {
253
+ throw new Error(`[veriforms] ${DEV_PREVIEW_FILE} does not hold an address. Run \`vf app dev\` again.`);
254
+ }
255
+ }
256
+ /** The preview address of one page: /a/draft-{app} for main, /a/draft-{app}/{page} otherwise, with the token. */
257
+ export function pagePreviewUrl(preview, page) {
258
+ const url = new URL(preview.href);
259
+ const base = url.pathname.replace(/\/+$/, '').replace(/^(\/a\/draft-[^/]+).*$/, '$1');
260
+ url.pathname = page === MAIN_PAGE ? base : `${base}/${page}`;
261
+ return url;
262
+ }
263
+ /**
264
+ * The gateway's draft preview of a page, made a dev page: the platform's runtime and bridge stay
265
+ * (window.__VF__, /vf-ui.js — data calls go to the draft plane's preview data, through the proxy),
266
+ * the uploaded build's tags and the platform's import map go (Vite serves React and the page's
267
+ * code itself), and the page's own entry is loaded from the sources.
268
+ */
269
+ export function devPage(previewHtml, entry) {
270
+ const withoutBuild = previewHtml
271
+ .replace(/<script\b[^>]*\btype=["']?importmap["']?[^>]*>[\s\S]*?<\/script>/gi, '')
272
+ .replace(/<script\b[^>]*\bsrc=["'][^"']*\/_app\/[^"']*["'][^>]*>\s*<\/script>/gi, '')
273
+ .replace(/<link\b[^>]*\bhref=["'][^"']*\/_app\/[^"']*["'][^>]*>/gi, '');
274
+ const tags = `<script type="module" src="/@vite/client"></script><script type="module" src="${entry}"></script>`;
275
+ const close = withoutBuild.search(/<\/body>/i);
276
+ return close >= 0 ? withoutBuild.slice(0, close) + tags + withoutBuild.slice(close) : withoutBuild + tags;
277
+ }
278
+ /** The plugin. Use it as the only plugin a web app's vite.config.ts needs: plugins: [veriformsWebApp()]. */
279
+ export function veriformsWebApp(options = {}) {
280
+ let pages = {};
281
+ // The app's own sources as written, by module id: the line a refusal names is the author's line.
282
+ const sources = new Map();
283
+ const outDir = options.outDir ?? 'vf-build';
284
+ let projectRoot = process.cwd();
285
+ let command = 'build';
286
+ let mode = 'production';
287
+ let serverFiles = {};
288
+ return {
289
+ name: 'veriforms-webapp',
290
+ enforce: 'pre',
291
+ config(user, env) {
292
+ const root = path.resolve(user.root ?? process.cwd());
293
+ projectRoot = root;
294
+ const serverDir = serverDirProblem(root, options.serverFunctions === true);
295
+ if (serverDir)
296
+ throw plainError(serverDir);
297
+ pages = findPages(root, options.pagesDir);
298
+ command = env.command;
299
+ mode = env.mode;
300
+ // Server functions (opted in): the pages' types for the client stub, written before anything type-checks.
301
+ serverFiles = options.serverFunctions === true ? findServerFunctionFiles(path.resolve(root, SERVER_DIR)) : {};
302
+ if (Object.keys(serverFiles).length > 0)
303
+ writeIfChanged(path.join(root, SERVER_TYPES_FILE), serverTypes(root, serverFiles));
304
+ // `vite` (dev, run by `vf app dev`): the gateway's draft plane behind a proxy, so the page's data
305
+ // calls reach the real server with the draft's config and its preview data rules.
306
+ const preview = env.command === 'serve' ? readDevPreview(root) : undefined;
307
+ const origin = preview ? `${preview.protocol}//${preview.host}` : undefined;
308
+ const toGateway = origin ? {
309
+ target: origin, changeOrigin: true, secure: true,
310
+ // The gateway answers its own origin only: the dev page speaks for it.
311
+ configure: (proxy) => proxy.on('proxyReq', (req) => { req.setHeader('origin', origin); req.removeHeader('referer'); }),
312
+ } : undefined;
313
+ return {
314
+ ...(toGateway ? { server: { proxy: { '/a/': toGateway, '/vf-ui.js': toGateway, '/vf/': toGateway } } } : {}),
315
+ base: './',
316
+ esbuild: {
317
+ jsx: 'automatic',
318
+ // Always the production runtime (react/jsx-runtime): the platform provides no dev runtime.
319
+ jsxDev: false,
320
+ // Whitespace only (owner decision 2026-11-27): the platform's checks and the review read real names.
321
+ minifyIdentifiers: false,
322
+ minifySyntax: false,
323
+ minifyWhitespace: true,
324
+ legalComments: 'none',
325
+ },
326
+ build: {
327
+ outDir,
328
+ emptyOutDir: true,
329
+ assetsDir: 'assets',
330
+ target: 'es2020',
331
+ minify: 'esbuild',
332
+ // Batch 200 (owner 2026-11-28): the maps are written and pushed for the error pages' server-side
333
+ // symbolication, but no chunk names them: the gateway never serves a .map, and a public reference would only 404.
334
+ sourcemap: 'hidden',
335
+ // No preload helper or polyfill: nothing inline, nothing the shell does not name.
336
+ modulePreload: false,
337
+ cssCodeSplit: true,
338
+ manifest: false,
339
+ rollupOptions: {
340
+ input: pages,
341
+ external: [...PLATFORM_MODULES],
342
+ output: {
343
+ format: 'es',
344
+ entryFileNames: 'assets/[name]-[hash].js',
345
+ chunkFileNames: 'assets/[name]-[hash].js',
346
+ assetFileNames: 'assets/[name]-[hash][extname]',
347
+ },
348
+ },
349
+ },
350
+ };
351
+ },
352
+ // Vite wraps every dynamic import in its preload helper, which reads the page's CSP nonce and sets
353
+ // <link href> from a value — both refused by the platform's checks. Ours only runs the import:
354
+ // nothing is preloaded, and a lazily loaded page part's CSS is linked in the shell up front.
355
+ resolveId(id, importer) {
356
+ if (id === VITE_PRELOAD_HELPER)
357
+ return id;
358
+ // A page never imports server code (prep P2): it would be published to every visitor.
359
+ if (importer && !importer.includes('/node_modules/') && importsServerCode(projectRoot, id, importer)) {
360
+ this.error(refusal(`[veriforms] ${path.relative(process.cwd(), importer)} imports "${id}" from ${SERVER_DIR}/: `
361
+ + 'a page cannot import server code — it would be published to every visitor. A page calls a server function through the SDK: '
362
+ + "server.placeOrder(input) or callServerFunction('placeOrder', input) from '@veriforms/webapp-sdk'."));
363
+ }
364
+ // A bare import from the app's own code: the platform's packages only (owner decision 2).
365
+ const bare = !id.startsWith('.') && !id.startsWith('/') && !id.startsWith('\0') && !/^[a-zA-Z]:[\\/]/.test(id) && !id.includes(':');
366
+ if (bare && importer && !importer.includes('/node_modules/')) {
367
+ const from = path.relative(process.cwd(), importer);
368
+ const pkg = packageOf(id);
369
+ if (!ALLOWED_PACKAGES.includes(pkg)) {
370
+ this.error(refusal(`[veriforms] ${from} imports "${id}": a web app built in code uses only the packages the platform provides `
371
+ + `(${Object.keys(PLATFORM_PACKAGES).join(', ')}) and its own SDK. Write the code in the app, or ask for the package to be added to the curated list.`));
372
+ }
373
+ // A served package is served only under the names in the import map: a deep import would bundle
374
+ // a second, unreviewed copy of part of it (and the upload refuses that).
375
+ if (pkg in PLATFORM_PACKAGES && !PLATFORM_MODULES.includes(id)) {
376
+ this.error(refusal(`[veriforms] ${from} imports "${id}", which the platform does not provide. `
377
+ + `From ${pkg} it provides: ${PLATFORM_MODULES.filter((m) => packageOf(m) === pkg).join(', ')}.`));
378
+ }
379
+ }
380
+ return null;
381
+ },
382
+ load(id) {
383
+ return id === VITE_PRELOAD_HELPER ? 'export const __vitePreload = (load) => load();\n' : null;
384
+ },
385
+ configureServer(server) {
386
+ const root = server.config.root;
387
+ server.middlewares.use(async (req, res, next) => {
388
+ const url = new URL(req.url ?? '/', 'http://dev.local');
389
+ const name = url.pathname === '/' || url.pathname === '/index.html' ? MAIN_PAGE : url.pathname.slice(1);
390
+ if (req.method !== 'GET' || !pages[name])
391
+ return next();
392
+ try {
393
+ const preview = readDevPreview(root);
394
+ if (!preview)
395
+ throw new Error(`No draft preview to load the page from. Start the dev server with \`vf app dev\`, which signs in and keeps ${DEV_PREVIEW_FILE} fresh.`);
396
+ const answer = await fetch(pagePreviewUrl(preview, name));
397
+ if (!answer.ok)
398
+ throw new Error(`The draft preview answered ${answer.status} for page "${name}". Upload a build first (\`vf app push\`), or restart \`vf app dev\` for a fresh preview.`);
399
+ const entry = '/' + path.relative(root, pages[name]).split(path.sep).join('/');
400
+ const html = await server.transformIndexHtml(url.pathname, devPage(await answer.text(), entry));
401
+ res.setHeader('content-type', 'text/html; charset=utf-8');
402
+ res.end(html);
403
+ }
404
+ catch (e) {
405
+ res.statusCode = 502;
406
+ res.setHeader('content-type', 'text/plain; charset=utf-8');
407
+ res.end(`[veriforms] ${e.message}`);
408
+ }
409
+ });
410
+ },
411
+ transform(code, id) {
412
+ if (id.includes('/node_modules/') || id.startsWith('\0') || !/\.(tsx?|jsx?|mjs)$/.test(id.split('?')[0]))
413
+ return null;
414
+ sources.set(id, code);
415
+ const findings = scanSource(code);
416
+ if (findings.length) {
417
+ const first = findings[0];
418
+ this.error(refusal(`[veriforms] ${path.relative(process.cwd(), id)}:${first.line} — ${first.message}`
419
+ + (findings.length > 1 ? ` (and ${findings.length - 1} more)` : ''), id, first.line));
420
+ }
421
+ return null;
422
+ },
423
+ // Every name the app's own code imports from a provided module must be one the platform's copy exports,
424
+ // whether or not it survives tree-shaking (batch 199a: `import { fr } from "date-fns/locale/de"; void fr;`
425
+ // passed, because the unused import was gone before the output was checked). Read from each module's
426
+ // declarations as parsed — TypeScript already stripped, so a type-only import is not a name here.
427
+ moduleParsed(info) {
428
+ const source = sources.get(info.id);
429
+ if (source === undefined)
430
+ return;
431
+ for (const { spec, name } of providedImports(info.ast)) {
432
+ if (PLATFORM_EXPORTS[spec].includes(name))
433
+ continue;
434
+ const line = importLine(source, spec, name);
435
+ const where = path.relative(process.cwd(), info.id) + (line ? `:${line}` : '');
436
+ this.error(refusal(notExportedMessage(where, name, spec), info.id, line));
437
+ }
438
+ },
439
+ // The server functions: built after the pages, into <outDir>/server/, with the manifest beside it.
440
+ async closeBundle() {
441
+ if (command !== 'build' || options.serverFunctions !== true || Object.keys(serverFiles).length === 0)
442
+ return;
443
+ await buildServerFunctions(projectRoot, outDir, serverFiles, mode, options.pagesDir ?? 'src/pages');
444
+ },
445
+ generateBundle(_output, bundle) {
446
+ // And on the output, which is what the browser links: it also sees names the source check does not
447
+ // read (a dependency's own imports, a name a later transform adds). The browser refuses to link a
448
+ // page with a missing name and shows nothing (the upload checks the same).
449
+ for (const item of Object.values(bundle)) {
450
+ if (item.type !== 'chunk')
451
+ continue;
452
+ for (const [spec, names] of Object.entries(item.importedBindings)) {
453
+ const exported = PLATFORM_EXPORTS[spec];
454
+ if (!exported)
455
+ continue;
456
+ for (const name of names) {
457
+ if (name !== '*' && !exported.includes(name)) {
458
+ this.error(refusal(notExportedMessage(item.fileName, name, spec)));
459
+ }
460
+ }
461
+ }
462
+ }
463
+ for (const item of Object.values(bundle)) {
464
+ if (item.type !== 'chunk' || !item.isEntry || !pages[item.name])
465
+ continue;
466
+ // The page's CSS: its own and that of every chunk it imports statically (a shared component's
467
+ // stylesheet sits on the shared chunk), in import order, each once.
468
+ const styles = [];
469
+ const seen = new Set();
470
+ const visit = (fileName) => {
471
+ if (seen.has(fileName))
472
+ return;
473
+ seen.add(fileName);
474
+ const chunk = bundle[fileName];
475
+ if (!chunk || chunk.type !== 'chunk')
476
+ return;
477
+ for (const imported of [...chunk.imports, ...chunk.dynamicImports])
478
+ visit(imported);
479
+ const css = chunk.viteMetadata?.importedCss;
480
+ for (const file of css ?? [])
481
+ if (!styles.includes(file))
482
+ styles.push(file);
483
+ };
484
+ visit(item.fileName);
485
+ const title = typeof options.title === 'string' ? options.title : options.title?.[item.name] ?? item.name;
486
+ this.emitFile({
487
+ type: 'asset',
488
+ fileName: `pages/${item.name}.html`,
489
+ source: shell({ title, lang: options.lang ?? 'de', script: item.fileName, styles }),
490
+ });
491
+ }
492
+ },
493
+ };
494
+ }
495
+ /** Writes `text` to `file` unless it already holds exactly that (a generated file is not touched for nothing). */
496
+ function writeIfChanged(file, text) {
497
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === text)
498
+ return;
499
+ fs.writeFileSync(file, text);
500
+ }
501
+ export default veriformsWebApp;