castle-web-cli 0.4.210 → 0.4.211

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 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,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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "castle-web-cli",
3
- "version": "0.4.210",
3
+ "version": "0.4.211",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/castle-xyz/castle-experimental-web.git"