castle-web-cli 0.4.210 → 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.
- package/dist/api.d.ts +10 -0
- package/dist/api.js +31 -0
- package/dist/externalSourcemaps.d.ts +29 -0
- package/dist/externalSourcemaps.js +162 -0
- package/dist/fontFaceImports.d.ts +7 -0
- package/dist/fontFaceImports.js +129 -0
- package/dist/gitRemote.d.ts +49 -0
- package/dist/gitRemote.js +376 -0
- package/dist/index.js +83 -0
- package/dist/serve.js +7 -0
- package/package.json +1 -1
package/dist/api.d.ts
CHANGED
|
@@ -170,4 +170,14 @@ export interface DeckMeta {
|
|
|
170
170
|
export declare function deckMeta(deckId: string): Promise<DeckMeta | null>;
|
|
171
171
|
export declare function webDeckSource(deckId: string): Promise<WebDeckSource | null>;
|
|
172
172
|
export declare function saveWebDeckSource(deckId: string, uploadId: string): Promise<WebDeckSource>;
|
|
173
|
+
export type CloudDeckKit = 'PHYSICS_2D' | 'PHYSICS_3D' | 'MULTIPLAYER_2D' | 'MULTIPLAYER_3D' | 'TURN_BASED' | 'NONE';
|
|
174
|
+
export interface RegisteredCloudDeck {
|
|
175
|
+
deckId: string;
|
|
176
|
+
initialCardId: string;
|
|
177
|
+
}
|
|
178
|
+
export declare function registerCloudDeck(operationId: string, title: string, kit: CloudDeckKit): Promise<RegisteredCloudDeck>;
|
|
179
|
+
export type GitEnvironment = 'staging' | 'production';
|
|
180
|
+
export declare function ensureGitRepo(deckId: string, environment: GitEnvironment): Promise<{
|
|
181
|
+
remoteUrl: string;
|
|
182
|
+
}>;
|
|
173
183
|
export {};
|
package/dist/api.js
CHANGED
|
@@ -301,3 +301,34 @@ export async function saveWebDeckSource(deckId, uploadId) {
|
|
|
301
301
|
handleAPIError(data);
|
|
302
302
|
return pickData(data, 'saveWebDeckSource');
|
|
303
303
|
}
|
|
304
|
+
// Mints a deck id server-side before anything is published, the way the cloud
|
|
305
|
+
// editor creates a deck. Idempotent by `operationId`. Ghost refuses it without the
|
|
306
|
+
// `cloud_editor` gate or from a sandbox session.
|
|
307
|
+
export async function registerCloudDeck(operationId, title, kit) {
|
|
308
|
+
const data = await graphql(`mutation($operationId: String!, $title: String!, $bootstrap: CloudDeckBootstrapInput!) {
|
|
309
|
+
registerCloudDeck(operationId: $operationId, title: $title, bootstrap: $bootstrap) {
|
|
310
|
+
deckId
|
|
311
|
+
initialCardId
|
|
312
|
+
}
|
|
313
|
+
}`, { operationId, title, bootstrap: { kind: 'KIT', kit } });
|
|
314
|
+
handleAPIError(data);
|
|
315
|
+
const result = pickData(data, 'registerCloudDeck');
|
|
316
|
+
if (!result?.deckId || !result.initialCardId) {
|
|
317
|
+
throw new Error('registerCloudDeck returned no deck.');
|
|
318
|
+
}
|
|
319
|
+
return result;
|
|
320
|
+
}
|
|
321
|
+
// Creates the deck's Castle git repo for one environment if it has none. Idempotent.
|
|
322
|
+
export async function ensureGitRepo(deckId, environment) {
|
|
323
|
+
const data = await graphql(`mutation($deckId: ID!, $environment: String!) {
|
|
324
|
+
ensureGitRepo(deckId: $deckId, environment: $environment) {
|
|
325
|
+
remoteUrl
|
|
326
|
+
}
|
|
327
|
+
}`, { deckId, environment });
|
|
328
|
+
handleAPIError(data);
|
|
329
|
+
const result = pickData(data, 'ensureGitRepo');
|
|
330
|
+
if (typeof result?.remoteUrl !== 'string') {
|
|
331
|
+
throw new Error('ensureGitRepo returned no remote URL.');
|
|
332
|
+
}
|
|
333
|
+
return { remoteUrl: result.remoteUrl };
|
|
334
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { CloudDeckKit, GitEnvironment, RegisteredCloudDeck } from './api.js';
|
|
2
|
+
export declare const GIT_HOSTS: Record<GitEnvironment, string>;
|
|
3
|
+
export declare const GIT_REMOTE_NAME = "castle";
|
|
4
|
+
export declare const CREDENTIAL_HELPER = "!castle-web git credential";
|
|
5
|
+
export declare const DEFAULT_GITIGNORE: string;
|
|
6
|
+
export declare function isSandboxToken(token: string | undefined | null): boolean;
|
|
7
|
+
export declare function credentialConfigKey(environment: GitEnvironment): string;
|
|
8
|
+
export interface CredentialAnswer {
|
|
9
|
+
stdout: string;
|
|
10
|
+
stderr: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function answerCredentialRequest(action: string, input: string, opts: {
|
|
13
|
+
token: string | null;
|
|
14
|
+
envToken: string | undefined;
|
|
15
|
+
}): CredentialAnswer;
|
|
16
|
+
export interface GitResult {
|
|
17
|
+
status: number | null;
|
|
18
|
+
stdout: string;
|
|
19
|
+
stderr: string;
|
|
20
|
+
error?: Error;
|
|
21
|
+
}
|
|
22
|
+
export interface GitInitDeps {
|
|
23
|
+
token: string | null;
|
|
24
|
+
envToken: string | undefined;
|
|
25
|
+
registerCloudDeck(operationId: string, title: string, kit: CloudDeckKit): Promise<RegisteredCloudDeck>;
|
|
26
|
+
ensureGitRepo(deckId: string, environment: GitEnvironment): Promise<{
|
|
27
|
+
remoteUrl: string;
|
|
28
|
+
}>;
|
|
29
|
+
git(args: string[], cwd: string): GitResult;
|
|
30
|
+
newOperationId(): string;
|
|
31
|
+
castleWebOnPath(): boolean;
|
|
32
|
+
log(message: string): void;
|
|
33
|
+
warn(message: string): void;
|
|
34
|
+
}
|
|
35
|
+
export declare function isOnPath(name: string, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): boolean;
|
|
36
|
+
export declare function runGit(args: string[], cwd: string): GitResult;
|
|
37
|
+
export declare function cloudKitFor(castleJson: Record<string, unknown> | null): CloudDeckKit;
|
|
38
|
+
export declare const PENDING_INIT_FILE: string;
|
|
39
|
+
export interface GitInitResult {
|
|
40
|
+
deckId: string;
|
|
41
|
+
remoteUrl: string;
|
|
42
|
+
registered: boolean;
|
|
43
|
+
initialized: boolean;
|
|
44
|
+
wroteGitignore: boolean;
|
|
45
|
+
remote: 'added' | 'updated' | 'unchanged';
|
|
46
|
+
}
|
|
47
|
+
export declare function gitInit(dirArg: string, opts: {
|
|
48
|
+
environment: GitEnvironment;
|
|
49
|
+
}, deps: GitInitDeps): Promise<GitInitResult>;
|
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
import { spawnSync } from 'child_process';
|
|
2
|
+
import * as fs from 'fs';
|
|
3
|
+
import * as path from 'path';
|
|
4
|
+
import { readCastleJsonOrThrow } from './castleJson.js';
|
|
5
|
+
// Castle-hosted git remotes (castle-sandboxes docs/git-remotes-phase1.md): each deck
|
|
6
|
+
// gets `https://git.castle.xyz/<deckId>.git`, served by the sandbox proxy, which
|
|
7
|
+
// takes the user's Castle session token as the Basic auth password. `git init` wires
|
|
8
|
+
// a local repo to it; `git credential` is the helper git calls to get that token.
|
|
9
|
+
export const GIT_HOSTS = {
|
|
10
|
+
production: 'git.castle.xyz',
|
|
11
|
+
staging: 'git-staging.castle.xyz',
|
|
12
|
+
};
|
|
13
|
+
export const GIT_REMOTE_NAME = 'castle';
|
|
14
|
+
// Runs through the shell as `castle-web git credential <action>`, so the helper
|
|
15
|
+
// needs no binary of its own.
|
|
16
|
+
export const CREDENTIAL_HELPER = '!castle-web git credential';
|
|
17
|
+
// The kits' own .gitignore: build output, dependencies, and imports/ (other decks'
|
|
18
|
+
// files, restored from castle.json's pins).
|
|
19
|
+
export const DEFAULT_GITIGNORE = ['node_modules/', 'dist/', '.castle/', '.vite/', '/imports/', ''].join('\n');
|
|
20
|
+
// Inside a cloud sandbox CASTLE_TOKEN is the llm-proxy's per-boot HMAC token,
|
|
21
|
+
// `v1.<base64url payload>.<base64url hmac>`, not a Castle session. The git proxy
|
|
22
|
+
// would reject it anyway; refusing here keeps it from being sent off-host at all.
|
|
23
|
+
const SANDBOX_TOKEN_RE = /^v1\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
|
|
24
|
+
export function isSandboxToken(token) {
|
|
25
|
+
return typeof token === 'string' && SANDBOX_TOKEN_RE.test(token);
|
|
26
|
+
}
|
|
27
|
+
export function credentialConfigKey(environment) {
|
|
28
|
+
return `credential.https://${GIT_HOSTS[environment]}.helper`;
|
|
29
|
+
}
|
|
30
|
+
function parseCredentialInput(input) {
|
|
31
|
+
const fields = new Map();
|
|
32
|
+
for (const line of input.split('\n')) {
|
|
33
|
+
const trimmed = line.replace(/\r$/, '');
|
|
34
|
+
if (trimmed === '')
|
|
35
|
+
break;
|
|
36
|
+
const eq = trimmed.indexOf('=');
|
|
37
|
+
if (eq <= 0)
|
|
38
|
+
continue;
|
|
39
|
+
fields.set(trimmed.slice(0, eq), trimmed.slice(eq + 1));
|
|
40
|
+
}
|
|
41
|
+
return fields;
|
|
42
|
+
}
|
|
43
|
+
const CASTLE_GIT_HOSTS = new Set(Object.values(GIT_HOSTS));
|
|
44
|
+
// git's credential-helper protocol (gitcredentials(7)). Only `get` answers, and only
|
|
45
|
+
// for the Castle git hosts over https; `store` and `erase` do nothing, since the
|
|
46
|
+
// token belongs to `castle-web login`. A refusal says `quit=1` so git stops rather
|
|
47
|
+
// than prompting for a password the user doesn't have.
|
|
48
|
+
export function answerCredentialRequest(action, input, opts) {
|
|
49
|
+
if (action !== 'get')
|
|
50
|
+
return { stdout: '', stderr: '' };
|
|
51
|
+
const fields = parseCredentialInput(input);
|
|
52
|
+
const host = fields.get('host');
|
|
53
|
+
if (fields.get('protocol') !== 'https' || !host || !CASTLE_GIT_HOSTS.has(host)) {
|
|
54
|
+
return { stdout: '', stderr: '' };
|
|
55
|
+
}
|
|
56
|
+
if (isSandboxToken(opts.envToken)) {
|
|
57
|
+
return {
|
|
58
|
+
stdout: 'quit=1\n',
|
|
59
|
+
stderr: 'castle-web: CASTLE_TOKEN is a cloud sandbox token, which Castle git remotes do not accept.\n',
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const token = opts.token;
|
|
63
|
+
if (!token) {
|
|
64
|
+
return {
|
|
65
|
+
stdout: 'quit=1\n',
|
|
66
|
+
stderr: 'castle-web: not logged in. Run `castle-web login`, then retry.\n',
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (/[\n\r\0]/.test(token)) {
|
|
70
|
+
return { stdout: 'quit=1\n', stderr: 'castle-web: the stored Castle token is malformed.\n' };
|
|
71
|
+
}
|
|
72
|
+
return { stdout: `username=castle\npassword=${token}\n`, stderr: '' };
|
|
73
|
+
}
|
|
74
|
+
// A PATH lookup with no spawn: is there an executable `name` in one of its dirs?
|
|
75
|
+
export function isOnPath(name, env = process.env, platform = process.platform) {
|
|
76
|
+
const dirs = (env.PATH ?? env.Path ?? '').split(path.delimiter).filter(Boolean);
|
|
77
|
+
const exts = platform === 'win32' ? ['', ...(env.PATHEXT ?? '.EXE;.CMD;.BAT;.COM').split(';').filter(Boolean)] : [''];
|
|
78
|
+
for (const dir of dirs) {
|
|
79
|
+
for (const ext of exts) {
|
|
80
|
+
const candidate = path.join(dir, name + ext);
|
|
81
|
+
try {
|
|
82
|
+
if (!fs.statSync(candidate).isFile())
|
|
83
|
+
continue;
|
|
84
|
+
if (platform !== 'win32')
|
|
85
|
+
fs.accessSync(candidate, fs.constants.X_OK);
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// not here
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
export function runGit(args, cwd) {
|
|
96
|
+
// Force git's untranslated messages: callers match stderr text (e.g. "not a git repository"),
|
|
97
|
+
// which a localized git would print in another language.
|
|
98
|
+
const result = spawnSync('git', args, {
|
|
99
|
+
cwd,
|
|
100
|
+
encoding: 'utf-8',
|
|
101
|
+
env: { ...process.env, LC_ALL: 'C', LANGUAGE: 'C' },
|
|
102
|
+
});
|
|
103
|
+
return {
|
|
104
|
+
status: result.status,
|
|
105
|
+
stdout: result.stdout ?? '',
|
|
106
|
+
stderr: result.stderr ?? '',
|
|
107
|
+
error: result.error,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
const STORAGE_KIT_TO_CLOUD = {
|
|
111
|
+
'physics-2d': 'PHYSICS_2D',
|
|
112
|
+
'physics-3d': 'PHYSICS_3D',
|
|
113
|
+
'multiplayer-2d': 'MULTIPLAYER_2D',
|
|
114
|
+
'multiplayer-3d': 'MULTIPLAYER_3D',
|
|
115
|
+
'turn-based': 'TURN_BASED',
|
|
116
|
+
};
|
|
117
|
+
// The kit a deck was scaffolded from, as registerCloudDeck names it: the builtin
|
|
118
|
+
// import it pinned directly (not one another import brought in). A deck on no kit,
|
|
119
|
+
// or on a kit the cloud doesn't list, registers as NONE.
|
|
120
|
+
export function cloudKitFor(castleJson) {
|
|
121
|
+
const imports = castleJson?.imports;
|
|
122
|
+
if (!imports || typeof imports !== 'object')
|
|
123
|
+
return 'NONE';
|
|
124
|
+
for (const pin of Object.values(imports)) {
|
|
125
|
+
if (!pin || typeof pin !== 'object')
|
|
126
|
+
continue;
|
|
127
|
+
const { source, kit, via } = pin;
|
|
128
|
+
if (source !== 'builtin' || via !== undefined || typeof kit !== 'string')
|
|
129
|
+
continue;
|
|
130
|
+
const cloud = STORAGE_KIT_TO_CLOUD[kit];
|
|
131
|
+
if (cloud)
|
|
132
|
+
return cloud;
|
|
133
|
+
}
|
|
134
|
+
return 'NONE';
|
|
135
|
+
}
|
|
136
|
+
function errorCode(e) {
|
|
137
|
+
const code = e?.extensions?.code;
|
|
138
|
+
return typeof code === 'string' ? code : undefined;
|
|
139
|
+
}
|
|
140
|
+
function explainRegisterFailure(e) {
|
|
141
|
+
const code = errorCode(e);
|
|
142
|
+
const detail = e instanceof Error ? e.message : String(e);
|
|
143
|
+
if (code === 'FEATURE_NOT_ENABLED') {
|
|
144
|
+
return new Error(`Castle refused to create a deck for this directory: the cloud editor isn't enabled for your account. (${detail})`);
|
|
145
|
+
}
|
|
146
|
+
if (code === 'CLOUD_DECK_AUTH_REQUIRED' || code === 'LOGIN_REQUIRED' || code === 'SIGN_UP_REQUIRED') {
|
|
147
|
+
return new Error(`Castle refused to create a deck: it needs a signed-in Castle account. Run \`castle-web login\`. (${detail})`);
|
|
148
|
+
}
|
|
149
|
+
return new Error(`Could not create a Castle deck for this directory: ${detail}`);
|
|
150
|
+
}
|
|
151
|
+
function git(deps, args, cwd) {
|
|
152
|
+
const result = deps.git(args, cwd);
|
|
153
|
+
if (result.error && result.error.code === 'ENOENT') {
|
|
154
|
+
throw new Error('git is not installed (or not on PATH).');
|
|
155
|
+
}
|
|
156
|
+
return result;
|
|
157
|
+
}
|
|
158
|
+
function gitOrThrow(deps, args, cwd) {
|
|
159
|
+
const result = git(deps, args, cwd);
|
|
160
|
+
if (result.status !== 0) {
|
|
161
|
+
const why = (result.stderr || result.stdout || result.error?.message || '').trim();
|
|
162
|
+
throw new Error(`\`git ${args.join(' ')}\` failed${why ? `: ${why}` : ''}`);
|
|
163
|
+
}
|
|
164
|
+
return result.stdout;
|
|
165
|
+
}
|
|
166
|
+
function sameDir(a, b) {
|
|
167
|
+
try {
|
|
168
|
+
return fs.realpathSync(a) === fs.realpathSync(b);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
return path.resolve(a) === path.resolve(b);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
// A deck dir that is its own repo is used as is; one with no repo gets `git init`.
|
|
175
|
+
// One inside ANOTHER repo (a decks monorepo) is refused, before any server call:
|
|
176
|
+
// the castle remote would then push that whole repo's history, and a nested repo
|
|
177
|
+
// is a surprise either way.
|
|
178
|
+
// Only git's own "not a git repository" means there is none; any other failure
|
|
179
|
+
// (dubious ownership, a broken .git) is surfaced, since reading it as "no repo"
|
|
180
|
+
// would `git init` a nested repo inside one git refused to open.
|
|
181
|
+
function hasOwnRepo(deps, dir) {
|
|
182
|
+
const top = git(deps, ['rev-parse', '--show-toplevel'], dir);
|
|
183
|
+
if (top.status !== 0) {
|
|
184
|
+
if (/not a git repository/i.test(top.stderr))
|
|
185
|
+
return false;
|
|
186
|
+
const why = (top.stderr || top.stdout || top.error?.message || '').trim();
|
|
187
|
+
throw new Error(`git could not read the repo at ${dir}${why ? `: ${why}` : ''}`);
|
|
188
|
+
}
|
|
189
|
+
const toplevel = top.stdout.trim();
|
|
190
|
+
if (sameDir(toplevel, dir))
|
|
191
|
+
return true;
|
|
192
|
+
throw new Error(`${dir} is inside the git repo at ${toplevel}. Run \`castle-web git init\` on a deck that is its own repo, or at that repo's root.`);
|
|
193
|
+
}
|
|
194
|
+
function initRepo(deps, dir) {
|
|
195
|
+
const withMain = git(deps, ['init', '--initial-branch=main'], dir);
|
|
196
|
+
if (withMain.status !== 0)
|
|
197
|
+
gitOrThrow(deps, ['init'], dir);
|
|
198
|
+
}
|
|
199
|
+
function isCastleGitUrl(url) {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = new URL(url);
|
|
202
|
+
return parsed.protocol === 'https:' && CASTLE_GIT_HOSTS.has(parsed.host);
|
|
203
|
+
}
|
|
204
|
+
catch {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
// A pushurl would send pushes somewhere other than the url this sets, so it goes.
|
|
209
|
+
function clearPushUrl(deps, dir) {
|
|
210
|
+
const key = `remote.${GIT_REMOTE_NAME}.pushurl`;
|
|
211
|
+
const current = git(deps, ['config', '--local', '--get-all', key], dir);
|
|
212
|
+
if (current.status !== 0 || !current.stdout.trim())
|
|
213
|
+
return;
|
|
214
|
+
gitOrThrow(deps, ['config', '--local', '--unset-all', key], dir);
|
|
215
|
+
deps.warn(`Removed ${key} (${current.stdout.trim().split('\n').join(', ')}), so pushes go to the Castle remote.`);
|
|
216
|
+
}
|
|
217
|
+
function setRemote(deps, dir, remoteUrl) {
|
|
218
|
+
const current = git(deps, ['remote', 'get-url', GIT_REMOTE_NAME], dir);
|
|
219
|
+
if (current.status === 0) {
|
|
220
|
+
clearPushUrl(deps, dir);
|
|
221
|
+
const previous = current.stdout.trim();
|
|
222
|
+
if (previous === remoteUrl)
|
|
223
|
+
return 'unchanged';
|
|
224
|
+
gitOrThrow(deps, ['remote', 'set-url', GIT_REMOTE_NAME, remoteUrl], dir);
|
|
225
|
+
if (!isCastleGitUrl(previous)) {
|
|
226
|
+
deps.warn(`Warning: the "${GIT_REMOTE_NAME}" remote pointed at ${previous}; it now points at ${remoteUrl}.`);
|
|
227
|
+
}
|
|
228
|
+
return 'updated';
|
|
229
|
+
}
|
|
230
|
+
gitOrThrow(deps, ['remote', 'add', GIT_REMOTE_NAME, remoteUrl], dir);
|
|
231
|
+
return 'added';
|
|
232
|
+
}
|
|
233
|
+
// What to tell the user to run next: push the current branch, or commit first.
|
|
234
|
+
function pushHint(deps, dir) {
|
|
235
|
+
const branchResult = git(deps, ['symbolic-ref', '--quiet', '--short', 'HEAD'], dir);
|
|
236
|
+
const branch = branchResult.status === 0 ? branchResult.stdout.trim() : '';
|
|
237
|
+
const hasCommit = git(deps, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}'], dir).status === 0;
|
|
238
|
+
const push = branch ? `git push -u ${GIT_REMOTE_NAME} ${branch}` : `git push ${GIT_REMOTE_NAME} HEAD:main`;
|
|
239
|
+
if (!hasCommit) {
|
|
240
|
+
return `The repo has no commits yet. Commit first (git add -A && git commit -m "First version"), then push with: ${push}`;
|
|
241
|
+
}
|
|
242
|
+
return `Push with: ${push}`;
|
|
243
|
+
}
|
|
244
|
+
// registerCloudDeck is idempotent by operationId, so the id is written down before
|
|
245
|
+
// the call and reused until castle.json has the deckId: a lost response, or a
|
|
246
|
+
// castle.json write that failed, then retries into the same deck, not a second one.
|
|
247
|
+
// .castle/ is the deck's local, gitignored state.
|
|
248
|
+
export const PENDING_INIT_FILE = path.join('.castle', 'git-init.json');
|
|
249
|
+
function readPendingOperationId(dir) {
|
|
250
|
+
try {
|
|
251
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(dir, PENDING_INIT_FILE), 'utf-8'));
|
|
252
|
+
const id = parsed?.operationId;
|
|
253
|
+
return typeof id === 'string' && /^[A-Za-z0-9._:-]{1,128}$/.test(id) ? id : null;
|
|
254
|
+
}
|
|
255
|
+
catch {
|
|
256
|
+
return null;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
function writePendingOperationId(dir, operationId) {
|
|
260
|
+
const file = path.join(dir, PENDING_INIT_FILE);
|
|
261
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
262
|
+
fs.writeFileSync(file, JSON.stringify({ operationId }, null, 2) + '\n', 'utf-8');
|
|
263
|
+
}
|
|
264
|
+
function clearPendingOperationId(dir) {
|
|
265
|
+
fs.rmSync(path.join(dir, PENDING_INIT_FILE), { force: true });
|
|
266
|
+
}
|
|
267
|
+
// The helper is set in the repo's own config, keyed to the Castle git host. An empty
|
|
268
|
+
// entry first resets the helper list for that URL, so a global helper (osxkeychain,
|
|
269
|
+
// manager) neither answers ahead of this one with a stale token nor stores the
|
|
270
|
+
// Castle token after a successful push.
|
|
271
|
+
function setCredentialHelper(deps, dir, environment) {
|
|
272
|
+
const key = credentialConfigKey(environment);
|
|
273
|
+
const unset = git(deps, ['config', '--local', '--unset-all', key], dir);
|
|
274
|
+
// 5: the key wasn't set, which is the first-run case.
|
|
275
|
+
if (unset.status !== 0 && unset.status !== 5) {
|
|
276
|
+
gitOrThrow(deps, ['config', '--local', '--unset-all', key], dir);
|
|
277
|
+
}
|
|
278
|
+
gitOrThrow(deps, ['config', '--local', '--add', key, ''], dir);
|
|
279
|
+
gitOrThrow(deps, ['config', '--local', '--add', key, CREDENTIAL_HELPER], dir);
|
|
280
|
+
}
|
|
281
|
+
function expectedRemoteUrl(environment, deckId) {
|
|
282
|
+
return `https://${GIT_HOSTS[environment]}/${deckId}.git`;
|
|
283
|
+
}
|
|
284
|
+
export async function gitInit(dirArg, opts, deps) {
|
|
285
|
+
const { environment } = opts;
|
|
286
|
+
if (isSandboxToken(deps.envToken)) {
|
|
287
|
+
throw new Error('Castle git remotes are not available from a cloud sandbox yet: CASTLE_TOKEN here is a sandbox token.');
|
|
288
|
+
}
|
|
289
|
+
if (!deps.token)
|
|
290
|
+
throw new Error('Not logged in. Run `castle-web login`.');
|
|
291
|
+
const dir = path.resolve(dirArg);
|
|
292
|
+
// Only a deck: never a folder made up on the spot, or one that isn't a deck.
|
|
293
|
+
let isDir = false;
|
|
294
|
+
try {
|
|
295
|
+
isDir = fs.statSync(dir).isDirectory();
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
isDir = false;
|
|
299
|
+
}
|
|
300
|
+
if (!isDir) {
|
|
301
|
+
throw new Error(`${dir} does not exist. Create a deck with \`castle-web init <dir>\` first.`);
|
|
302
|
+
}
|
|
303
|
+
const castleJsonPath = path.join(dir, 'castle.json');
|
|
304
|
+
if (!fs.existsSync(castleJsonPath)) {
|
|
305
|
+
throw new Error(`${dir} has no castle.json, so it isn't a Castle deck. Create one with \`castle-web init <dir>\`, or run this in a deck's directory.`);
|
|
306
|
+
}
|
|
307
|
+
// Before touching the server, so a machine without git doesn't get a deck for nothing.
|
|
308
|
+
gitOrThrow(deps, ['--version'], dir);
|
|
309
|
+
const repoExists = hasOwnRepo(deps, dir);
|
|
310
|
+
// 1. The deck: castle.json's, or a new one minted server-side.
|
|
311
|
+
const castleJson = readCastleJsonOrThrow(dir);
|
|
312
|
+
let deckId = typeof castleJson?.deckId === 'string' && castleJson.deckId ? castleJson.deckId : '';
|
|
313
|
+
let registered = false;
|
|
314
|
+
if (!deckId) {
|
|
315
|
+
const rawTitle = typeof castleJson?.title === 'string' && castleJson.title.trim()
|
|
316
|
+
? castleJson.title.trim()
|
|
317
|
+
: path.basename(dir);
|
|
318
|
+
const title = rawTitle.slice(0, 255);
|
|
319
|
+
let operationId = readPendingOperationId(dir);
|
|
320
|
+
if (!operationId) {
|
|
321
|
+
operationId = deps.newOperationId();
|
|
322
|
+
writePendingOperationId(dir, operationId);
|
|
323
|
+
}
|
|
324
|
+
let deck;
|
|
325
|
+
try {
|
|
326
|
+
deck = await deps.registerCloudDeck(operationId, title, cloudKitFor(castleJson));
|
|
327
|
+
}
|
|
328
|
+
catch (e) {
|
|
329
|
+
throw explainRegisterFailure(e);
|
|
330
|
+
}
|
|
331
|
+
deckId = deck.deckId;
|
|
332
|
+
// The card id is the placeholder card the server made, so a later save-deck
|
|
333
|
+
// publishes onto it rather than minting a second card.
|
|
334
|
+
const next = { ...(castleJson ?? {}), deckId, cardId: deck.initialCardId };
|
|
335
|
+
fs.writeFileSync(castleJsonPath, JSON.stringify(next, null, 2) + '\n', 'utf-8');
|
|
336
|
+
clearPendingOperationId(dir);
|
|
337
|
+
registered = true;
|
|
338
|
+
deps.log(`Created deck "${title}" (${deckId}). Saved castle.json.`);
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
// A leftover from a run that registered but died before clearing it.
|
|
342
|
+
clearPendingOperationId(dir);
|
|
343
|
+
}
|
|
344
|
+
// 2. The repo on Castle's side.
|
|
345
|
+
const { remoteUrl } = await deps.ensureGitRepo(deckId, environment);
|
|
346
|
+
const expected = expectedRemoteUrl(environment, deckId);
|
|
347
|
+
if (remoteUrl !== expected) {
|
|
348
|
+
// The credential helper is keyed to GIT_HOSTS; a remote anywhere else would
|
|
349
|
+
// either get no token or, worse, be the wrong deck.
|
|
350
|
+
throw new Error(`Castle returned an unexpected remote URL ${remoteUrl} (expected ${expected}).`);
|
|
351
|
+
}
|
|
352
|
+
// 3. The local repo.
|
|
353
|
+
const initialized = !repoExists;
|
|
354
|
+
if (initialized)
|
|
355
|
+
initRepo(deps, dir);
|
|
356
|
+
const gitignorePath = path.join(dir, '.gitignore');
|
|
357
|
+
let wroteGitignore = false;
|
|
358
|
+
if (!fs.existsSync(gitignorePath)) {
|
|
359
|
+
fs.writeFileSync(gitignorePath, DEFAULT_GITIGNORE, 'utf-8');
|
|
360
|
+
wroteGitignore = true;
|
|
361
|
+
}
|
|
362
|
+
const remote = setRemote(deps, dir, remoteUrl);
|
|
363
|
+
setCredentialHelper(deps, dir, environment);
|
|
364
|
+
if (initialized)
|
|
365
|
+
deps.log(`Initialized a git repo in ${dir}.`);
|
|
366
|
+
if (wroteGitignore)
|
|
367
|
+
deps.log('Wrote .gitignore.');
|
|
368
|
+
deps.log(remote === 'unchanged'
|
|
369
|
+
? `Remote "${GIT_REMOTE_NAME}" already points at ${remoteUrl}.`
|
|
370
|
+
: `Remote "${GIT_REMOTE_NAME}" ${remote}: ${remoteUrl}`);
|
|
371
|
+
if (!deps.castleWebOnPath()) {
|
|
372
|
+
deps.warn('Warning: `castle-web` is not on PATH. git runs `castle-web git credential` to get your Castle token, so pushes will fail to authenticate until it is (npm install -g castle-web-cli).');
|
|
373
|
+
}
|
|
374
|
+
deps.log(pushHint(deps, dir));
|
|
375
|
+
return { deckId, remoteUrl, registered, initialized, wroteGitignore, remote };
|
|
376
|
+
}
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import { randomUUID } from 'crypto';
|
|
2
3
|
import * as fs from 'fs';
|
|
3
4
|
import * as path from 'path';
|
|
4
5
|
import { login } from './login.js';
|
|
@@ -76,6 +77,17 @@ function getFlagValue(flag) {
|
|
|
76
77
|
function hasFlag(flag) {
|
|
77
78
|
return args.includes(flag);
|
|
78
79
|
}
|
|
80
|
+
function readStdin() {
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
let input = '';
|
|
83
|
+
process.stdin.setEncoding('utf-8');
|
|
84
|
+
process.stdin.on('data', (chunk) => {
|
|
85
|
+
input += chunk;
|
|
86
|
+
});
|
|
87
|
+
process.stdin.on('end', () => resolve(input));
|
|
88
|
+
process.stdin.on('error', reject);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
79
91
|
function readServeSocketPort(dir) {
|
|
80
92
|
try {
|
|
81
93
|
const serveJson = JSON.parse(fs.readFileSync(path.join(path.resolve(dir), '.castle', 'serve.json'), 'utf-8'));
|
|
@@ -153,6 +165,8 @@ function usage() {
|
|
|
153
165
|
castle-web list-versions [version] [--dir DIR] (defaults to the latest version)
|
|
154
166
|
castle-web show-version <version> [--dir DIR] (diffs of the files that version changed)
|
|
155
167
|
castle-web restore-version <version> [--force] [--dir DIR]
|
|
168
|
+
castle-web git init [dir] [--dir DIR] [--staging] (connects the deck to its Castle git remote: git push castle <branch>)
|
|
169
|
+
castle-web git credential get|store|erase (git's credential helper for git.castle.xyz; git init sets it up)
|
|
156
170
|
castle-web login
|
|
157
171
|
castle-web whoami
|
|
158
172
|
castle-web --version
|
|
@@ -163,6 +177,72 @@ ${kitLines}
|
|
|
163
177
|
After init, read the scaffolded deck's CLAUDE.md (also AGENTS.md) for the kit's full author guide.`);
|
|
164
178
|
process.exit(1);
|
|
165
179
|
}
|
|
180
|
+
// `git init`'s own arguments, strictly: an unknown flag is an error rather than
|
|
181
|
+
// ignored, since a typo'd `--staging` would otherwise target production.
|
|
182
|
+
function parseGitInitArgs() {
|
|
183
|
+
let dir;
|
|
184
|
+
let staging = false;
|
|
185
|
+
const setDir = (value) => {
|
|
186
|
+
if (dir !== undefined && path.resolve(dir) !== path.resolve(value)) {
|
|
187
|
+
throw new Error(`git init takes one deck directory; got ${dir} and ${value}.`);
|
|
188
|
+
}
|
|
189
|
+
dir = value;
|
|
190
|
+
};
|
|
191
|
+
let sawSubcommand = false;
|
|
192
|
+
for (let i = 1; i < args.length; i++) {
|
|
193
|
+
const arg = args[i];
|
|
194
|
+
if (!sawSubcommand && arg === 'init') {
|
|
195
|
+
sawSubcommand = true;
|
|
196
|
+
}
|
|
197
|
+
else if (arg === '--staging') {
|
|
198
|
+
staging = true;
|
|
199
|
+
}
|
|
200
|
+
else if (arg === '--dir') {
|
|
201
|
+
const value = args[++i];
|
|
202
|
+
if (value === undefined || value.startsWith('-'))
|
|
203
|
+
throw new Error('--dir needs a directory.');
|
|
204
|
+
setDir(value);
|
|
205
|
+
}
|
|
206
|
+
else if (arg.startsWith('-')) {
|
|
207
|
+
throw new Error(`Unknown option for git init: ${arg} (it takes [dir] [--dir DIR] [--staging]).`);
|
|
208
|
+
}
|
|
209
|
+
else {
|
|
210
|
+
setDir(arg);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
return { dir: dir ?? '.', staging };
|
|
214
|
+
}
|
|
215
|
+
// `castle-web git init [dir] [--dir DIR] [--staging]` and `castle-web git credential <action>`.
|
|
216
|
+
async function gitCommand() {
|
|
217
|
+
const [sub, arg] = readPositionals();
|
|
218
|
+
const gitRemote = await import('./gitRemote.js');
|
|
219
|
+
if (sub === 'credential') {
|
|
220
|
+
// git's credential-helper protocol: key=value lines on stdin, the answer on
|
|
221
|
+
// stdout. Nothing else may print to stdout here.
|
|
222
|
+
const input = await readStdin();
|
|
223
|
+
const answer = gitRemote.answerCredentialRequest(arg ?? '', input, {
|
|
224
|
+
token: config.getToken(),
|
|
225
|
+
envToken: process.env.CASTLE_TOKEN,
|
|
226
|
+
});
|
|
227
|
+
process.stderr.write(answer.stderr);
|
|
228
|
+
process.stdout.write(answer.stdout);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
if (sub !== 'init')
|
|
232
|
+
usage();
|
|
233
|
+
const initArgs = parseGitInitArgs();
|
|
234
|
+
await gitRemote.gitInit(initArgs.dir, { environment: initArgs.staging ? 'staging' : 'production' }, {
|
|
235
|
+
token: config.getToken(),
|
|
236
|
+
envToken: process.env.CASTLE_TOKEN,
|
|
237
|
+
registerCloudDeck: api.registerCloudDeck,
|
|
238
|
+
ensureGitRepo: api.ensureGitRepo,
|
|
239
|
+
git: gitRemote.runGit,
|
|
240
|
+
newOperationId: () => `castle-web-git-init:${randomUUID()}`,
|
|
241
|
+
castleWebOnPath: () => gitRemote.isOnPath('castle-web'),
|
|
242
|
+
log: (message) => console.log(message),
|
|
243
|
+
warn: (message) => console.error(message),
|
|
244
|
+
});
|
|
245
|
+
}
|
|
166
246
|
async function main() {
|
|
167
247
|
// Before the switch: `--version` is a flag, not a command, and it has to work
|
|
168
248
|
// when there is no command at all. Which version is installed is the first
|
|
@@ -341,6 +421,9 @@ async function main() {
|
|
|
341
421
|
await runMcpPlaytestServer(path.resolve(dir), getFlagValue('--task-id'));
|
|
342
422
|
return;
|
|
343
423
|
}
|
|
424
|
+
case 'git':
|
|
425
|
+
await gitCommand();
|
|
426
|
+
break;
|
|
344
427
|
case 'login':
|
|
345
428
|
await login();
|
|
346
429
|
break;
|
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,
|