castle-web-cli 0.4.211 → 0.4.212

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.
@@ -0,0 +1,29 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { Plugin } from 'vite';
3
+ export declare const SOURCEMAP_ROUTE = "/@castle-sourcemap";
4
+ export declare function moduleUrlForMap(requestUrl: string): string;
5
+ export declare function externalizeInlineSourcemap(code: string, mapUrl: string | null): string | null;
6
+ type ModuleMap = {
7
+ map: {
8
+ sources?: unknown;
9
+ sourceRoot?: unknown;
10
+ };
11
+ etag: string | null;
12
+ };
13
+ type MapLookup = (moduleUrl: string) => ModuleMap | null;
14
+ type GraphLike = {
15
+ urlToModuleMap?: Map<string, {
16
+ transformResult?: {
17
+ map?: unknown;
18
+ etag?: string;
19
+ } | null;
20
+ }>;
21
+ } | undefined;
22
+ export declare function moduleMap(graph: GraphLike, moduleUrl: string): ModuleMap | null;
23
+ export declare function mapForModuleUrl(map: ModuleMap['map'], moduleUrl: string): object;
24
+ export declare function sourcemapUrl(moduleUrl: string, etag: string | null): string;
25
+ export declare function wrapJavaScriptEnd(req: IncomingMessage, res: ServerResponse, lookup: MapLookup): void;
26
+ export declare function externalSourcemapsPlugin(options: {
27
+ enabled: boolean;
28
+ }): Plugin;
29
+ export {};
@@ -0,0 +1,162 @@
1
+ // Vite appends a source map to every script module it serves, as a base64
2
+ // comment. Since Vite 8.1 an optimized dep carries its whole bundle map that way,
3
+ // and a module with no map of its own (every kit and deck file here) gets a
4
+ // generated one that only repeats the served code. That is most of a deck page's
5
+ // bytes: a physics-3d play page is 7.3 MB with them and 2.3 MB without, and a
6
+ // phone pays for all of it on every open although only an open DevTools reads a
7
+ // map. A real map is swapped for a URL that serves it on demand, so DevTools
8
+ // still shows the original source; the generated kind is dropped.
9
+ //
10
+ // Off unless CASTLE_EXTERNAL_SOURCEMAPS=1, so the sandbox image decides.
11
+ export const SOURCEMAP_ROUTE = '/@castle-sourcemap';
12
+ const INLINE_PREFIX = '\n//# sourceMappingURL=data:application/json;';
13
+ // The module graph keys a module by its URL without the `t=` timestamp or the
14
+ // `import` marker Vite adds for non-script imports.
15
+ export function moduleUrlForMap(requestUrl) {
16
+ const [path, query = ''] = requestUrl.split('?', 2);
17
+ const kept = query
18
+ .split('&')
19
+ .filter((part) => part && part !== 'import' && !/^t=\d+$/.test(part));
20
+ return kept.length ? `${path}?${kept.join('&')}` : path;
21
+ }
22
+ // `code` with a trailing inline source map replaced by a comment pointing at
23
+ // `mapUrl` (or removed when `mapUrl` is null), or null when it has none. Only a
24
+ // comment that ends the file counts: an inline map anywhere else is someone's
25
+ // string, not Vite's.
26
+ export function externalizeInlineSourcemap(code, mapUrl) {
27
+ const at = code.lastIndexOf(INLINE_PREFIX);
28
+ if (at < 0)
29
+ return null;
30
+ const tail = code.slice(at + 1);
31
+ if (!/^\/\/# sourceMappingURL=data:application\/json;[^\s]*base64,[A-Za-z0-9+/=]*\s*$/.test(tail)) {
32
+ return null;
33
+ }
34
+ return mapUrl === null
35
+ ? code.slice(0, at)
36
+ : `${code.slice(0, at)}\n//# sourceMappingURL=${mapUrl}`;
37
+ }
38
+ // The module's own map as Vite holds it, if it has a real one, with the etag of
39
+ // the code it maps. A lookup in the graph's URL index only: resolving an
40
+ // arbitrary URL here could run plugins.
41
+ export function moduleMap(graph, moduleUrl) {
42
+ const result = graph?.urlToModuleMap?.get(moduleUrl)?.transformResult;
43
+ const map = result?.map;
44
+ if (!map || typeof map !== 'object' || !('mappings' in map) || !map.mappings)
45
+ return null;
46
+ return { map: map, etag: result?.etag ?? null };
47
+ }
48
+ // Vite writes a map's `sources` relative to the module's own directory, which is
49
+ // where an inline map resolves them from. Served from SOURCEMAP_ROUTE they would
50
+ // resolve against the site root instead, so they are made absolute here.
51
+ export function mapForModuleUrl(map, moduleUrl) {
52
+ const dir = `http://module${moduleUrl.split('?')[0].replace(/[^/]*$/, '')}`;
53
+ const root = typeof map.sourceRoot === 'string' && map.sourceRoot
54
+ ? new URL(map.sourceRoot.replace(/\/?$/, '/'), dir).href
55
+ : dir;
56
+ const sources = Array.isArray(map.sources)
57
+ ? map.sources.map((source) => {
58
+ if (typeof source !== 'string' || /^[a-z][a-z0-9+.-]*:/i.test(source))
59
+ return source;
60
+ const resolved = new URL(source, root);
61
+ return resolved.origin === 'http://module' ? resolved.pathname : resolved.href;
62
+ })
63
+ : map.sources;
64
+ const out = { ...map, sources };
65
+ delete out.sourceRoot;
66
+ return out;
67
+ }
68
+ export function sourcemapUrl(moduleUrl, etag) {
69
+ const version = etag ? `&e=${encodeURIComponent(etag)}` : '';
70
+ return `${SOURCEMAP_ROUTE}?u=${encodeURIComponent(moduleUrl)}${version}`;
71
+ }
72
+ function isJavaScript(contentType) {
73
+ return /^(text|application)\/javascript\b/.test(String(contentType ?? ''));
74
+ }
75
+ // Rewrites the body Vite hands to `res.end` in one piece (its `send` does exactly
76
+ // that). Anything written in parts, or already sent, passes through untouched.
77
+ export function wrapJavaScriptEnd(req, res, lookup) {
78
+ const end = res.end.bind(res);
79
+ let wrote = false;
80
+ const write = res.write.bind(res);
81
+ res.write = ((...args) => {
82
+ wrote = true;
83
+ return write(...args);
84
+ });
85
+ res.end = ((...args) => {
86
+ const [chunk] = args;
87
+ if (!wrote &&
88
+ !res.headersSent &&
89
+ res.statusCode === 200 &&
90
+ (typeof chunk === 'string' || Buffer.isBuffer(chunk)) &&
91
+ isJavaScript(res.getHeader('content-type'))) {
92
+ const text = typeof chunk === 'string' ? chunk : chunk.toString('utf8');
93
+ const moduleUrl = moduleUrlForMap(req.url || '/');
94
+ const found = lookup(moduleUrl);
95
+ // The etag only versions the URL, so DevTools never pairs new code with
96
+ // an old map it cached; the route itself ignores it.
97
+ const mapUrl = found ? sourcemapUrl(moduleUrl, found.etag) : null;
98
+ const replaced = externalizeInlineSourcemap(text, mapUrl);
99
+ if (replaced !== null) {
100
+ if (res.hasHeader('content-length')) {
101
+ res.setHeader('content-length', Buffer.byteLength(replaced));
102
+ }
103
+ args[0] = replaced;
104
+ if (Buffer.isBuffer(chunk) && typeof args[1] !== 'string')
105
+ args.splice(1, 0, 'utf8');
106
+ }
107
+ }
108
+ return end(...args);
109
+ });
110
+ }
111
+ export function externalSourcemapsPlugin(options) {
112
+ return {
113
+ name: 'castle-external-sourcemaps',
114
+ apply: 'serve',
115
+ configureServer(server) {
116
+ if (!options.enabled)
117
+ return;
118
+ // Registered after Castle's own middleware, so the content-role checks and
119
+ // the compressor have already run: this wraps `end` inside the compressor,
120
+ // which then compresses the shorter body.
121
+ const client = server.environments?.client;
122
+ const lookup = (moduleUrl) => moduleMap(client?.moduleGraph, moduleUrl);
123
+ server.middlewares.use((req, res, next) => {
124
+ if (req.method !== 'GET' && req.method !== 'HEAD')
125
+ return next();
126
+ const url = new URL(req.url || '/', 'http://localhost');
127
+ if (url.pathname !== SOURCEMAP_ROUTE) {
128
+ wrapJavaScriptEnd(req, res, lookup);
129
+ return next();
130
+ }
131
+ const moduleUrl = url.searchParams.get('u') || '';
132
+ if (!moduleUrl.startsWith('/') || moduleUrl.startsWith('//')) {
133
+ res.writeHead(400).end();
134
+ return;
135
+ }
136
+ // A module this server has served has its map in the graph: the map it
137
+ // would have carried inline to this same client. An optimized dep is
138
+ // cached by the browser for a year, so after a restart its map is rebuilt
139
+ // on demand; every other module is served (and so mapped) afresh.
140
+ void (async () => {
141
+ let found = lookup(moduleUrl);
142
+ if (!found && client && moduleUrl.startsWith('/node_modules/.vite/deps/')) {
143
+ await client.transformRequest(moduleUrl).catch(() => null);
144
+ found = lookup(moduleUrl);
145
+ }
146
+ if (!found) {
147
+ res.writeHead(404).end();
148
+ return;
149
+ }
150
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-cache' });
151
+ res.end(req.method === 'HEAD'
152
+ ? undefined
153
+ : JSON.stringify(mapForModuleUrl(found.map, moduleUrl)));
154
+ })().catch(() => {
155
+ if (!res.headersSent)
156
+ res.writeHead(404);
157
+ res.end();
158
+ });
159
+ });
160
+ },
161
+ };
162
+ }
@@ -0,0 +1,7 @@
1
+ import { type Plugin } from 'vite';
2
+ export declare function installedFaces(projectDir: string): string[] | null;
3
+ export declare function rewriteFontFaceImports(code: string, faces: Set<string>): string | null;
4
+ export declare function fontFaceImportsPlugin(options: {
5
+ enabled: boolean;
6
+ projectDir: string;
7
+ }): Plugin;
@@ -0,0 +1,129 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { parseAst } from 'vite';
4
+ // A deck names its font as `import { installDMSans } from 'castle-web-fonts'`, and
5
+ // the kit reads the catalog the same way. A published bundle keeps only what is
6
+ // named, but the dev server pre-bundles the package's root entry whole, so every
7
+ // deck page downloads all nine faces (375 KB, barely compressible) to use one
8
+ // (DMSans is 27 KB). The package exports each face and the catalog on their own
9
+ // entries; this points dev imports at those. Only the dev serve does it: the
10
+ // source keeps the root import the bundler already handles.
11
+ //
12
+ // Off unless CASTLE_FONT_FACE_IMPORTS=1, so the sandbox image decides.
13
+ const PACKAGE = 'castle-web-fonts';
14
+ const CATALOG_NAMES = new Set(['FACES', 'FACE_NAMES', 'faceInfo']);
15
+ // The faces this deck's own copy of the package provides, or null when it has
16
+ // none or its exports do not offer per-face entries.
17
+ export function installedFaces(projectDir) {
18
+ const root = path.join(projectDir, 'node_modules', PACKAGE);
19
+ try {
20
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
21
+ if (!pkg.exports?.['./faces/*'] || !pkg.exports?.['./catalog'])
22
+ return null;
23
+ return fs
24
+ .readdirSync(path.join(root, 'dist', 'faces'))
25
+ .filter((f) => /^[A-Za-z0-9]+\.js$/.test(f))
26
+ .map((f) => f.slice(0, -3))
27
+ .sort();
28
+ }
29
+ catch {
30
+ return null;
31
+ }
32
+ }
33
+ const nameOf = (n) => n?.name ?? n?.value ?? '';
34
+ function entryFor(imported, faces) {
35
+ if (CATALOG_NAMES.has(imported))
36
+ return `${PACKAGE}/catalog`;
37
+ const face = /^install([A-Za-z0-9]+)$/.exec(imported)?.[1];
38
+ return face && faces.has(face) ? `${PACKAGE}/faces/${face}` : null;
39
+ }
40
+ // `code` with each value import or re-export of named bindings from the package
41
+ // root split into per-entry statements, or null when there is nothing it can
42
+ // rewrite. A statement is left whole unless every name in it has an entry, and
43
+ // the replacement keeps the statement's line count so later lines stay put.
44
+ export function rewriteFontFaceImports(code, faces) {
45
+ if (!code.includes(PACKAGE))
46
+ return null;
47
+ let ast;
48
+ try {
49
+ ast = parseAst(code);
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ const edits = [];
55
+ for (const node of ast.body) {
56
+ const isImport = node.type === 'ImportDeclaration';
57
+ const isReexport = node.type === 'ExportNamedDeclaration' && !!node.source;
58
+ if (!isImport && !isReexport)
59
+ continue;
60
+ if (node.source?.value !== PACKAGE)
61
+ continue;
62
+ if ((node.importKind ?? node.exportKind ?? 'value') !== 'value')
63
+ continue;
64
+ const specs = node.specifiers ?? [];
65
+ if (!specs.length)
66
+ continue;
67
+ const groups = new Map();
68
+ let ok = true;
69
+ for (const s of specs) {
70
+ if (s.type !== (isImport ? 'ImportSpecifier' : 'ExportSpecifier')) {
71
+ ok = false;
72
+ break;
73
+ }
74
+ const imported = nameOf(isImport ? s.imported : s.local);
75
+ const alias = nameOf(isImport ? s.local : s.exported);
76
+ const entry = entryFor(imported, faces);
77
+ if (!entry || !/^[A-Za-z_$][\w$]*$/.test(alias)) {
78
+ ok = false;
79
+ break;
80
+ }
81
+ const list = groups.get(entry) ?? [];
82
+ list.push(alias === imported ? imported : `${imported} as ${alias}`);
83
+ groups.set(entry, list);
84
+ }
85
+ if (!ok)
86
+ continue;
87
+ const keyword = isImport ? 'import' : 'export';
88
+ const text = [...groups]
89
+ .map(([entry, names]) => `${keyword} { ${names.join(', ')} } from '${entry}';`)
90
+ .join(' ');
91
+ const lines = code.slice(node.start, node.end).split('\n').length - 1;
92
+ edits.push({ start: node.start, end: node.end, text: text + '\n'.repeat(lines) });
93
+ }
94
+ if (!edits.length)
95
+ return null;
96
+ let out = code;
97
+ for (const e of edits.sort((a, b) => b.start - a.start)) {
98
+ out = out.slice(0, e.start) + e.text + out.slice(e.end);
99
+ }
100
+ return out;
101
+ }
102
+ export function fontFaceImportsPlugin(options) {
103
+ const faceList = options.enabled ? installedFaces(options.projectDir) : null;
104
+ const faces = new Set(faceList ?? []);
105
+ return {
106
+ name: 'castle-font-face-imports',
107
+ apply: 'serve',
108
+ config() {
109
+ // Pre-bundle the entries up front: found only once a page asks for them,
110
+ // they would make Vite re-optimize and reload that page.
111
+ if (!faceList)
112
+ return;
113
+ return {
114
+ optimizeDeps: {
115
+ include: [`${PACKAGE}/catalog`, ...faceList.map((f) => `${PACKAGE}/faces/${f}`)],
116
+ },
117
+ };
118
+ },
119
+ transform(code, id) {
120
+ if (!faceList)
121
+ return null;
122
+ const file = id.split('?')[0];
123
+ if (file.includes('/node_modules/') || !/\.(m?[jt]sx?)$/.test(file))
124
+ return null;
125
+ const out = rewriteFontFaceImports(code, faces);
126
+ return out === null ? null : { code: out, map: null };
127
+ },
128
+ };
129
+ }
package/dist/serve.js CHANGED
@@ -12,6 +12,8 @@ import { sceneFilesPlugin, importsAliasPlugin, forksOverlayPlugin, sdkAliasPlugi
12
12
  import { viteClientStubPlugin } from './viteClientStub.js';
13
13
  import { paramsRegisterPlugin } from './paramsRegisterPlugin.js';
14
14
  import { modulePreloadPlugin } from './modulePreload.js';
15
+ import { externalSourcemapsPlugin } from './externalSourcemaps.js';
16
+ import { fontFaceImportsPlugin } from './fontFaceImports.js';
15
17
  import { createScriptErrors, scriptErrorsPlugin } from './scriptErrors.js';
16
18
  import { installFilesChangedWatcher } from './filesChanged.js';
17
19
  import { applyDeckWrite, createTuneLedger } from './paramsTunes.js';
@@ -1228,6 +1230,11 @@ export async function serve(dir, options = {}) {
1228
1230
  sceneFilesPlugin(),
1229
1231
  scriptErrorsPlugin(scriptErrors),
1230
1232
  modulePreloadPlugin({ enabled: process.env.CASTLE_MODULE_PRELOAD === '1' }),
1233
+ externalSourcemapsPlugin({ enabled: process.env.CASTLE_EXTERNAL_SOURCEMAPS === '1' }),
1234
+ fontFaceImportsPlugin({
1235
+ enabled: process.env.CASTLE_FONT_FACE_IMPORTS === '1',
1236
+ projectDir,
1237
+ }),
1231
1238
  ],
1232
1239
  server: {
1233
1240
  port,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.211",
3
+ "version": "0.4.212",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"