@joripspace/cli 0.5.0 → 0.5.2

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/bin/joripspace.js CHANGED
@@ -1,1614 +1,1627 @@
1
1
  #!/usr/bin/env node
2
-
3
- const fs = require('node:fs');
4
- const os = require('node:os');
5
- const path = require('node:path');
6
- const { spawn } = require('node:child_process');
7
- const readline = require('node:readline/promises');
8
- const { formatDeploymentFailure } = require('../lib/deployment-error');
9
- const {
10
- printHelp,
11
- printDeployHelp,
12
- printDeployTemplateHelp,
13
- printInstallTemplateHelp,
14
- } = require('../lib/help');
15
- const { createTemplateCommands } = require('../lib/template-commands');
16
- const { createCheckpointCommands } = require('../lib/checkpoint-commands');
17
- const { createRealtimeV2Commands } = require('../lib/realtime-v2-commands');
18
- const {
19
- assertDeployableProjectPath,
20
- assertDeployableSourceFilePath,
21
- buildDeployPayload,
22
- isProtectedProjectPath,
23
- resolveDeploySourceDirectory,
24
- resolveDeploySourceFile,
25
- } = require('../lib/deploy-files');
26
- const { createRemoteCommands } = require('../lib/remote-commands');
27
- const {
28
- resolveProjectDirectoryTarget,
29
- resolveProjectFileTarget,
30
- safeProjectRelativePath,
31
- } = require('../lib/project-paths');
32
- const { ensureProjectEnvIgnored, readProjectEnv, updateDotEnvFile } = require('../lib/project-env');
33
- const { createStartProjectCommand } = require('../lib/start-command');
34
- const { legacyCredentialSessionConnection, readProjectMarker } = require('../lib/start');
35
- const { buildTemplateDeployRequest, listTemplates } = loadTemplatesPackage();
36
- const templateCommands = createTemplateCommands({
37
- listTemplates,
38
- buildTemplateDeployRequest,
39
- output,
40
- requireProjectId,
41
- stringFlag,
42
- templateVars,
43
- apiRequest,
44
- projectAuth,
45
- requireApiToken,
46
- resolveConnection,
47
- booleanFlag,
48
- deployCode,
49
- });
50
- const remoteCommands = createRemoteCommands({
51
- apiRequest,
52
- booleanFlag,
53
- isProtectedProjectPath,
54
- output,
55
- positiveIntegerFlag,
56
- projectAuth,
57
- projectWorkspaceDir,
58
- requireProjectId,
59
- stringFlag,
60
- webOnlyCommand,
61
- writeTextAtomically,
62
- });
63
- const checkpointCommands = createCheckpointCommands({
64
- apiRequest,
65
- arrayFlag,
66
- assertDeployableProjectPath,
67
- assertDeployableSourceFilePath,
68
- booleanFlag,
69
- output,
70
- positiveIntegerFlag,
71
- projectAuth,
72
- projectWorkspaceDir,
73
- requireApiToken,
74
- requireProjectId,
75
- resolveDeploySourceDirectory,
76
- resolveDeploySourceFile,
77
- resolveConnection,
78
- safeProjectRelativePath,
79
- splitFileMapping,
80
- stringFlag,
81
- });
82
- const startProjectCommand = createStartProjectCommand(
83
- apiRequest,
84
- output,
85
- resolveConnection,
86
- stringFlag,
87
- remoteCommands.pullDeploymentSource,
88
- projectWorkspaceDir,
89
- persistStartConnection,
90
- connectForStart
91
- );
92
-
93
- const DEFAULT_API_URL = 'https://api.joripspace.com';
94
- const GENERAL_REQUEST_TIMEOUT_MS = 25_000;
95
- const SESSION_COOKIE_PREFIX = 'joripspace_session=';
2
+
3
+ const fs = require('node:fs');
4
+ const os = require('node:os');
5
+ const path = require('node:path');
6
+ const { spawn } = require('node:child_process');
7
+ const readline = require('node:readline/promises');
8
+ const { formatDeploymentFailure } = require('../lib/deployment-error');
9
+ const {
10
+ printHelp,
11
+ printDeployHelp,
12
+ printDeployTemplateHelp,
13
+ printInstallTemplateHelp,
14
+ } = require('../lib/help');
15
+ const { createTemplateCommands } = require('../lib/template-commands');
16
+ const { createCheckpointCommands } = require('../lib/checkpoint-commands');
17
+ const { createRealtimeV2Commands } = require('../lib/realtime-v2-commands');
18
+ const { createGithubCommands } = require('../lib/github-commands');
19
+ const {
20
+ assertDeployableProjectPath,
21
+ assertDeployableSourceFilePath,
22
+ buildDeployPayload,
23
+ isProtectedProjectPath,
24
+ resolveDeploySourceDirectory,
25
+ resolveDeploySourceFile,
26
+ } = require('../lib/deploy-files');
27
+ const { createRemoteCommands } = require('../lib/remote-commands');
28
+ const {
29
+ resolveProjectDirectoryTarget,
30
+ resolveProjectFileTarget,
31
+ safeProjectRelativePath,
32
+ } = require('../lib/project-paths');
33
+ const { ensureProjectEnvIgnored, readProjectEnv, updateDotEnvFile } = require('../lib/project-env');
34
+ const { createStartProjectCommand } = require('../lib/start-command');
35
+ const { legacyCredentialSessionConnection, readProjectMarker } = require('../lib/start');
36
+ const { buildTemplateDeployRequest, listTemplates } = loadTemplatesPackage();
37
+ const templateCommands = createTemplateCommands({
38
+ listTemplates,
39
+ buildTemplateDeployRequest,
40
+ output,
41
+ requireProjectId,
42
+ stringFlag,
43
+ templateVars,
44
+ apiRequest,
45
+ projectAuth,
46
+ requireApiToken,
47
+ resolveConnection,
48
+ booleanFlag,
49
+ deployCode,
50
+ });
51
+ const remoteCommands = createRemoteCommands({
52
+ apiRequest,
53
+ booleanFlag,
54
+ isProtectedProjectPath,
55
+ output,
56
+ positiveIntegerFlag,
57
+ projectAuth,
58
+ projectWorkspaceDir,
59
+ requireProjectId,
60
+ stringFlag,
61
+ webOnlyCommand,
62
+ writeTextAtomically,
63
+ });
64
+ const checkpointCommands = createCheckpointCommands({
65
+ apiRequest,
66
+ arrayFlag,
67
+ assertDeployableProjectPath,
68
+ assertDeployableSourceFilePath,
69
+ booleanFlag,
70
+ output,
71
+ positiveIntegerFlag,
72
+ projectAuth,
73
+ projectWorkspaceDir,
74
+ requireApiToken,
75
+ requireProjectId,
76
+ resolveDeploySourceDirectory,
77
+ resolveDeploySourceFile,
78
+ resolveConnection,
79
+ safeProjectRelativePath,
80
+ splitFileMapping,
81
+ stringFlag,
82
+ });
83
+ const startProjectCommand = createStartProjectCommand(
84
+ apiRequest,
85
+ output,
86
+ resolveConnection,
87
+ stringFlag,
88
+ remoteCommands.pullDeploymentSource,
89
+ projectWorkspaceDir,
90
+ persistStartConnection,
91
+ connectForStart
92
+ );
93
+ const githubCommand = createGithubCommands({
94
+ apiRequest,
95
+ output,
96
+ projectAuth,
97
+ projectWorkspaceDir,
98
+ requireProjectId,
99
+ stringFlag,
100
+ writeTextAtomically,
101
+ });
102
+
103
+ const DEFAULT_API_URL = 'https://api.joripspace.com';
104
+ const GENERAL_REQUEST_TIMEOUT_MS = 25_000;
105
+ const SESSION_COOKIE_PREFIX = 'joripspace_session=';
96
106
  function loadTemplatesPackage() {
97
107
  return require('../vendor/templates');
98
108
  }
99
-
100
- main().catch((error) => {
101
- const message = error instanceof Error ? error.message : String(error);
102
- if (process.argv.slice(2).some((argument) => argument === '--json' || argument.startsWith('--json='))) {
103
- const serialized = {
104
- code: typeof error?.code === 'string' ? error.code : 'invalid_arguments',
105
- message,
106
- ...(Number.isInteger(error?.status) ? { status: error.status } : {}),
107
- ...(error?.details === undefined ? {} : { details: error.details }),
108
- };
109
- console.error(JSON.stringify({ ok: false, error: serialized }));
110
- } else {
111
- console.error(`joripspace: ${message}`);
112
- }
113
- process.exitCode = Number.isInteger(error?.exitCode) ? error.exitCode : 1;
114
- });
115
-
116
- async function main() {
117
- const { command, rest, flags } = parseArgs(process.argv.slice(2));
118
-
119
- if (flags.version || flags.v) {
120
- console.log(require('../package.json').version);
121
- return;
122
- }
123
-
124
- if (!command || command === 'help') {
125
- printHelp();
126
- return;
127
- }
128
-
129
- if (
130
- (flags.help || flags.h) &&
131
- command !== 'deploy' &&
132
- command !== 'deploy-template' &&
133
- command !== 'install-template'
134
- ) {
135
- printHelp();
136
- return;
137
- }
138
-
139
- switch (command) {
140
- case 'version':
141
- console.log(require('../package.json').version);
142
- return;
143
- case 'login':
144
- await login(flags);
145
- return;
146
- case 'me':
147
- await getMe(flags);
148
- return;
149
- case 'projects':
150
- await listMyProjects(flags);
151
- return;
152
- case 'billing-projects':
153
- webOnlyCommand('결제 프로젝트');
154
- return;
155
- case 'billing-usage':
156
- webOnlyCommand('결제 사용량');
157
- return;
158
- case 'invoices':
159
- webOnlyCommand('청구서');
160
- return;
161
- case 'link':
162
- await linkProject(flags);
163
- return;
164
- case 'start':
165
- await startProjectCommand(rest, flags);
166
- return;
167
- case 'create':
168
- webOnlyCommand('프로젝트 생성');
169
- return;
170
- case 'get':
171
- await getProject(flags);
172
- return;
173
- case 'db':
174
- await dbCommand(rest, flags);
175
- return;
176
- case 'storage':
177
- await storageCommand(rest, flags);
178
- return;
179
- case 'deploy':
180
- if (flags.help || flags.h) {
181
- printDeployHelp();
182
- return;
183
- }
184
- await deployCode(flags);
185
- return;
186
- case 'templates':
187
- await templateCommands.list(flags);
188
- return;
189
- case 'template':
190
- if (rest[0] === 'list') {
191
- await templateCommands.marketplaceList(flags);
192
- return;
193
- }
194
- if (rest[0] === 'pull') {
195
- await templateCommands.pull(flags);
196
- return;
197
- }
198
- throw new Error('template command requires: list or pull');
199
- case 'knowledge':
200
- await remoteCommands.knowledge(rest, flags);
201
- return;
202
- case 'deployment':
203
- await remoteCommands.deployment(rest, flags);
204
- return;
205
- case 'template-pull':
206
- await templateCommands.pull(flags);
207
- return;
208
- case 'deploy-template':
209
- if (flags.help || flags.h) {
210
- printDeployTemplateHelp();
211
- return;
212
- }
213
- await templateCommands.deploy(flags);
214
- return;
215
- case 'install-template':
216
- if (flags.help || flags.h) {
217
- printInstallTemplateHelp();
218
- return;
219
- }
220
- await templateCommands.install(flags);
221
- return;
222
- case 'deployments':
223
- await listDeployments(flags);
224
- return;
225
- case 'checkpoint':
226
- case 'checkpoints':
227
- await checkpointCommands.command(rest, flags);
228
- return;
229
- case 'realtime-v2':
230
- await createRealtimeV2Commands({apiRequest,output,projectAuth,requireProjectId,stringFlag})(rest,flags);
231
- return;
232
- case 'rollback':
233
- await rollbackDeployment(flags);
234
- return;
235
- case 'events':
236
- case 'logs':
237
- await listRuntimeEvents(flags);
238
- return;
239
- case 'usage':
240
- webOnlyCommand('일일 사용량 상세');
241
- return;
242
- case 'usage-summary':
243
- await getUsageSummary(flags);
244
- return;
245
- case 'usage-breakdown':
246
- await getUsageBreakdown(flags);
247
- return;
248
- case 'tokens':
249
- webOnlyCommand('API 토큰 관리');
250
- return;
251
- case 'crons':
252
- await remoteCommands.listCrons(flags);
253
- return;
254
- case 'domains':
255
- await remoteCommands.listDomains(flags);
256
- return;
257
- case 'secrets':
258
- await remoteCommands.listSecrets(flags);
259
- return;
260
- case 'mail':
261
- await remoteCommands.mail(rest, flags);
262
- return;
263
- case 'webhooks':
264
- webOnlyCommand('웹훅 관리');
265
- return;
266
- case 'token':
267
- webOnlyCommand('API 토큰 관리');
268
- return;
269
- case 'secret':
270
- await remoteCommands.secrets(rest, flags);
271
- return;
272
- case 'cron':
273
- await remoteCommands.crons(rest, flags);
274
- return;
275
- case 'domain':
276
- await remoteCommands.domains(rest, flags);
277
- return;
278
- case 'webhook':
279
- webOnlyCommand('웹훅 관리');
280
- return;
281
- case 'delete':
282
- webOnlyCommand('프로젝트 삭제');
283
- return;
284
- default:
285
- throw new Error(`Unknown command: ${command}`);
286
- }
287
- }
288
-
289
- async function login(flags) {
290
- const connectionCode = stringFlag(flags, 'code');
291
- if (connectionCode) {
292
- ensureProjectEnvIgnored(projectWorkspaceDir(flags, { discover: false }));
293
- const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
294
- const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
295
- method: 'POST',
296
- body: { code: normalizeConnectionCode(connectionCode) },
297
- apiBaseUrl: exchangeApiBaseUrl,
298
- });
299
- const exchangedToken = normalizeConnectToken(exchange.connect_token);
300
- await saveBrowserConnectToken(flags, exchangedToken, 'connection-code', exchangeApiBaseUrl);
301
- return;
302
- }
303
- const connectToken =
304
- stringFlag(flags, 'connect-token') || stringFlag(flags, 'api-token') || stringFlag(flags, 'token');
305
- if (connectToken) {
306
- ensureProjectEnvIgnored(projectWorkspaceDir(flags, { discover: false }));
307
- await saveBrowserConnectToken(flags, normalizeConnectToken(connectToken));
308
- return;
309
- }
310
- output(flags, browserConnectInstructions(), printBrowserConnectInstructions);
311
- }
312
-
313
- async function saveBrowserConnectToken(flags, apiToken, source = 'browser-connect', selectedApiBaseUrl = '') {
314
- return saveBrowserConnectTokenWithOptions(flags, apiToken, source, selectedApiBaseUrl);
315
- }
316
-
317
- async function saveBrowserConnectTokenWithOptions(
318
- flags,
319
- apiToken,
320
- source = 'browser-connect',
321
- selectedApiBaseUrl = '',
322
- options = {}
323
- ) {
324
- const connection = selectedApiBaseUrl
325
- ? { apiBaseUrl: trimTrailingSlash(selectedApiBaseUrl), apiToken, source }
326
- : connectionForExplicitToken(flags, apiToken);
327
- const workspaceDir = projectWorkspaceDir(flags, { discover: false });
328
- managedProjectFilePath(workspaceDir, '.env.joripspace');
329
- managedProjectFilePath(workspaceDir, '.gitignore');
330
- ensureProjectEnvIgnored(workspaceDir);
331
- const body = await apiRequest(flags, '/v1/me/projects', {
332
- method: 'GET',
333
- apiToken,
334
- apiBaseUrl: connection.apiBaseUrl,
335
- });
336
- const requestedProject = stringFlag(flags, 'project') || stringFlag(flags, 'project-id');
337
- const projects = Array.isArray(body.projects) ? body.projects : [];
338
- const selected = requestedProject
339
- ? projects.find((project) =>
340
- [project.project_id, project.project_slug, project.slug].filter(Boolean).includes(requestedProject)
341
- )
342
- : projects.length === 1
343
- ? projects[0]
344
- : null;
345
- if (requestedProject && !selected) throw new Error(`project is not accessible: ${requestedProject}`);
346
- updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
347
- JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
348
- JORIPSPACE_API_TOKEN: apiToken,
349
- JORIPSPACE_ACCOUNT_ID: body.account_id,
350
- JORIPSPACE_CONNECTION_SOURCE: source,
351
- });
352
- scrubGlobalSessionToken();
353
- if (options.output !== false) {
354
- output(flags, body, (value) => {
355
- console.log(`연결 완료: ${value.account_id}`);
356
- console.log(`저장 위치: ${path.join(workspaceDir, '.env.joripspace')}`);
357
- console.log('이 폴더에서 joripspace projects 또는 joripspace start 명령을 실행하세요.');
358
- console.log('회원정보와 API 토큰 관리는 웹 프로필에서만 가능합니다.');
359
- });
360
- }
361
- return body;
362
- }
363
-
364
- async function getMe(flags) {
365
- const body = await apiRequest(flags, '/v1/me/projects', {
366
- method: 'GET',
367
- ...projectAuth(flags),
368
- });
369
-
370
- output(flags, body, (value) => {
371
- console.log(`Account: ${value.account_id}`);
372
- console.log(`Projects: ${(value.projects ?? []).length}`);
373
- });
374
- }
375
-
376
- async function listMyProjects(flags) {
377
- const body = await apiRequest(flags, '/v1/me/projects', {
378
- method: 'GET',
379
- ...projectAuth(flags),
380
- });
381
-
382
- output(flags, body, (value) => {
383
- for (const project of value.projects ?? []) {
384
- console.log(
385
- `${project.project_id}\t${project.role}\towner=${project.role === 'owner' ? 'yes' : 'no'}\t${project.default_url}`
386
- );
387
- }
388
- });
389
- }
390
-
391
- function webOnlyCommand(label) {
392
- throw new Error(
393
- `${label} 기능은 웹 화면에서만 사용할 수 있습니다. CLI는 개발, DB/스토리지 작업, 서버 배포, 사용량, 로그 조회용입니다.`
394
- );
395
- }
396
-
397
- async function linkProject(flags, options = {}) {
398
- const project = requireProjectId(flags);
399
- if (options.output === false) {
400
- throw new Error('link no longer supports internal workspace generation; use start');
401
- }
402
- await startProjectCommand([project], flags);
403
- }
404
-
405
- async function getProject(flags) {
406
- const project = requireProjectId(flags);
407
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}`, {
408
- method: 'GET',
409
- ...projectAuth(flags),
410
- });
411
-
412
- output(flags, body, (value) => {
413
- console.log(`Project: ${value.project_id}`);
414
- console.log(`Slug: ${value.project_slug}`);
415
- console.log(`Status: ${value.status}`);
416
- console.log(`URL: ${value.default_url}`);
417
- console.log(`Last deployed: ${value.last_deployed_at ?? 'never'}`);
418
- });
419
- }
420
-
421
- async function dbCommand(rest, flags) {
422
- const subcommand = rest[0] || 'schema';
423
- const project = requireProjectId(flags);
424
-
425
- if (subcommand === 'schema') {
426
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/schema`, {
427
- method: 'GET',
428
- ...projectAuth(flags),
429
- });
430
- output(flags, body, (value) => {
431
- for (const object of value.objects ?? []) {
432
- console.log(`${object.type}\t${object.name}`);
433
- if (object.sql) console.log(` ${object.sql}`);
434
- }
435
- });
436
- return;
437
- }
438
-
439
- if (subcommand === 'query') {
440
- const sql = sqlFromFlags(flags, 'query');
441
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/query`, {
442
- method: 'POST',
443
- ...projectAuth(flags),
444
- body: { sql },
445
- });
446
- output(flags, body, (value) => {
447
- console.log(JSON.stringify(value.rows ?? [], null, 2));
448
- });
449
- return;
450
- }
451
-
452
- if (subcommand === 'migrate') {
453
- const sql = sqlFromFlags(flags, 'migrate');
454
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/migrations`, {
455
- method: 'POST',
456
- ...projectAuth(flags),
457
- body: {
458
- name: stringFlag(flags, 'name') || null,
459
- sql,
460
- },
461
- });
462
- output(flags, body, (value) => {
463
- console.log(`DB migration complete: ${value.project_id}`);
464
- console.log(`Statements: ${value.statements}`);
465
- });
466
- return;
467
- }
468
-
469
- throw new Error(`Unknown db command: ${subcommand}`);
470
- }
471
-
472
- async function storageCommand(rest, flags) {
473
- const subcommand = rest[0] || 'list';
474
- const project = requireProjectId(flags);
475
-
476
- if (subcommand === 'list') {
477
- const search = new URLSearchParams();
478
- const prefix = stringFlag(flags, 'prefix');
479
- const cursor = stringFlag(flags, 'cursor');
480
- const limit = stringFlag(flags, 'limit');
481
- if (prefix) search.set('prefix', prefix);
482
- if (cursor) search.set('cursor', cursor);
483
- if (limit) search.set('limit', limit);
484
- const query = search.toString() ? `?${search.toString()}` : '';
485
- const body = await apiRequest(
486
- flags,
487
- `/v1/projects/${encodeURIComponent(project)}/storage/objects${query}`,
488
- {
489
- method: 'GET',
490
- ...projectAuth(flags),
491
- }
492
- );
493
- output(flags, body, (value) => {
494
- for (const object of value.objects ?? []) {
495
- console.log(`${object.key}\t${object.size ?? 0} B\t${object.uploaded ?? ''}`);
496
- }
497
- if (value.cursor) console.log(`Next cursor: ${value.cursor}`);
498
- });
499
- return;
500
- }
501
-
502
- if (subcommand === 'get') {
503
- const key = requireStorageKey(flags);
504
- const body = await apiRequest(
505
- flags,
506
- `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
507
- {
508
- method: 'GET',
509
- ...projectAuth(flags),
510
- }
511
- );
512
- const outPath = stringFlag(flags, 'out');
513
- if (outPath) {
514
- const bytes = body.base64
515
- ? Buffer.from(body.base64, 'base64')
516
- : Buffer.from(String(body.text ?? ''), 'utf8');
517
- fs.writeFileSync(path.resolve(outPath), bytes);
518
- }
519
- output(flags, body, (value) => {
520
- if (outPath) {
521
- console.log(`Wrote: ${path.resolve(outPath)}`);
522
- return;
523
- }
524
- if (typeof value.text === 'string') {
525
- console.log(value.text);
526
- return;
527
- }
528
- console.log(`Binary object: ${value.key} (${value.size} B). Use --out to save it.`);
529
- });
530
- return;
531
- }
532
-
533
- if (subcommand === 'put') {
534
- const key = requireStorageKey(flags);
535
- const filePath = stringFlag(flags, 'file');
536
- const text = stringFlag(flags, 'text');
537
- const hasText = flags.text !== undefined && flags.text !== true;
538
- if (!filePath && !hasText) {
539
- throw new Error('storage put requires --file or --text');
540
- }
541
- if (filePath && hasText) throw new Error('storage put accepts only one of --file or --text');
542
- const body = filePath
543
- ? {
544
- base64: fs.readFileSync(path.resolve(filePath)).toString('base64'),
545
- content_type: stringFlag(flags, 'content-type') || contentTypeForPath(filePath),
546
- }
547
- : {
548
- text,
549
- content_type: stringFlag(flags, 'content-type') || 'text/plain; charset=utf-8',
550
- };
551
- const result = await apiRequest(
552
- flags,
553
- `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
554
- {
555
- method: 'PUT',
556
- ...projectAuth(flags),
557
- body,
558
- }
559
- );
560
- output(flags, result, (value) => {
561
- console.log(`Stored: ${value.key} (${value.size} B)`);
562
- });
563
- return;
564
- }
565
-
566
- if (subcommand === 'delete') {
567
- const key = requireStorageKey(flags);
568
- if (!flags.yes) {
569
- throw new Error('storage delete requires --yes');
570
- }
571
- const body = await apiRequest(
572
- flags,
573
- `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
574
- {
575
- method: 'DELETE',
576
- ...projectAuth(flags),
577
- }
578
- );
579
- output(flags, body, (value) => {
580
- console.log(`Deleted: ${value.key}`);
581
- });
582
- return;
583
- }
584
-
585
- throw new Error(`Unknown storage command: ${subcommand}`);
586
- }
587
-
588
- async function deployCode(flags, options = {}) {
589
- const project = requireProjectId(flags);
590
- const label = stringFlag(flags, 'label').trim();
591
- if (!label) throw new Error('deploy requires --label');
592
- let deployPayload;
593
- try {
594
- deployPayload = buildDeployPayload(flags);
595
- } catch (error) {
596
- if (error?.code !== 'archive_required') throw error;
597
- return checkpointCommands.deployArchive(flags, project, label, error.message, options);
598
- }
599
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deploy`, {
600
- method: 'POST',
601
- ...projectAuth(flags),
602
- body: { ...deployPayload, label },
603
- });
604
-
605
- if (options.output !== false) {
606
- output(flags, body, (value) => {
607
- console.log(`Deployment: ${value.deployment_id}`);
608
- console.log(`Status: ${value.status}`);
609
- console.log(`URL: ${value.url}`);
610
- printDeploymentWarnings(value.warnings);
611
- });
612
- }
613
- return body;
614
- }
615
-
616
- function printDeploymentWarnings(warnings) {
617
- for (const warning of warnings || []) console.warn(`경고: ${warning.message}`);
618
- }
619
-
620
- async function listDeployments(flags) {
621
- const project = requireProjectId(flags);
622
- const limit = positiveIntegerFlag(flags, 'limit');
623
- const params = new URLSearchParams();
624
- if (limit) params.set('limit', String(limit));
625
- if (booleanFlag(flags, 'include-failure-details')) params.set('include_failure_details', 'true');
626
- const query = params.size ? `?${params}` : '';
627
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deployments${query}`, {
628
- method: 'GET',
629
- ...projectAuth(flags),
630
- });
631
-
632
- output(flags, body, (value) => {
633
- for (const deployment of value.deployments) {
634
- console.log(
635
- `${deployment.version}\t${deployment.deployment_id}\t${deployment.status}\trollback=${deployment.rollback_available}\t${deployment.created_at}`
636
- );
637
- if (deployment.error_message) console.log(`${deployment.error_stage || 'unknown'} / ${deployment.error_code || 'unknown'}: ${deployment.error_message}`);
638
- if (deployment.github) console.log(`GitHub: ${deployment.github.commit_sha} ${deployment.github.run_url} (${deployment.github.diagnostic_status || 'pending'})`);
639
- if (deployment.error_details) console.log(deployment.error_details);
640
- }
641
- });
642
- }
643
-
644
- async function rollbackDeployment(flags) {
645
- const project = requireProjectId(flags);
646
- const deployment = stringFlag(flags, 'deployment') || stringFlag(flags, 'deployment-id');
647
- if (!deployment) {
648
- throw new Error('rollback requires --deployment');
649
- }
650
-
651
- const body = await apiRequest(
652
- flags,
653
- `/v1/projects/${encodeURIComponent(project)}/deployments/${encodeURIComponent(deployment)}/rollback`,
654
- {
655
- method: 'POST',
656
- ...projectAuth(flags),
657
- }
658
- );
659
-
660
- output(flags, body, (value) => {
661
- console.log(`Deployment: ${value.deployment_id}`);
662
- console.log(`Rolled back from: ${value.rolled_back_from}`);
663
- console.log(`URL: ${value.url}`);
664
- });
665
- }
666
-
667
- async function listRuntimeEvents(flags) {
668
- const project = requireProjectId(flags);
669
- const params = new URLSearchParams();
670
- const eventType = stringFlag(flags, 'event-type') || stringFlag(flags, 'event_type');
671
- const limit = positiveIntegerFlag(flags, 'limit');
672
- if (eventType) {
673
- params.set('event_type', eventType);
674
- }
675
- if (limit) {
676
- params.set('limit', String(limit));
677
- }
678
-
679
- const query = params.toString() ? `?${params.toString()}` : '';
680
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/runtime-events${query}`, {
681
- method: 'GET',
682
- ...projectAuth(flags),
683
- });
684
-
685
- output(flags, body, (value) => {
686
- for (const event of value.events) {
687
- console.log(
688
- `${event.created_at}\t${event.event_type}\t${event.status}\t${event.method}\t${event.path}\t${event.duration_ms}ms\t${event.error_message ?? ''}`
689
- );
690
- }
691
- });
692
- }
693
-
694
- async function getUsage(flags) {
695
- const project = requireProjectId(flags);
696
- const date = stringFlag(flags, 'date');
697
- const query = date ? `?date=${encodeURIComponent(date)}` : '';
698
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/usage${query}`, {
699
- method: 'GET',
700
- ...projectAuth(flags),
701
- });
702
-
703
- output(flags, body, (value) => {
704
- console.log(`Date: ${value.date}`);
705
- console.log(`Requests: ${value.requests}`);
706
- console.log(`Errors: ${value.errors}`);
707
- console.log(`Deploys: ${value.deploy_count}`);
708
- });
709
- }
710
-
711
- async function getUsageSummary(flags) {
712
- const project = requireProjectId(flags);
713
- const query = usageRangeQuery(flags);
714
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/usage/summary${query}`, {
715
- method: 'GET',
716
- ...projectAuth(flags),
717
- });
718
-
719
- output(flags, body, printUsageSummary);
720
- }
721
-
722
- async function getUsageBreakdown(flags) {
723
- const project = requireProjectId(flags);
724
- const params = new URLSearchParams(usageRangeParams(flags));
725
- const groupBy = stringFlag(flags, 'group-by') || stringFlag(flags, 'group_by');
726
- if (groupBy) {
727
- params.set('group_by', groupBy);
728
- }
729
- const query = params.toString() ? `?${params.toString()}` : '';
730
- const body = await apiRequest(
731
- flags,
732
- `/v1/projects/${encodeURIComponent(project)}/usage/breakdown${query}`,
733
- {
734
- method: 'GET',
735
- ...projectAuth(flags),
736
- }
737
- );
738
-
739
- output(flags, body, (value) => {
740
- printUsageSummary(value);
741
- for (const item of value.series ?? []) {
742
- console.log(
743
- `${item.bucket}\trequests=${item.requests_total}\terrors=${item.errors_total}\tin=${item.request_bytes ?? 0}\tout=${item.response_bytes ?? 0}\trealtime_out=${item.realtime_messages_out ?? 0}\trealtime_peak=${item.realtime_peak_connections ?? 0}\tdeploys=${item.deploy_count}\tcron=${item.cron_runs}\twebhooks=${item.webhook_deliveries}`
744
- );
745
- }
746
- });
747
- }
748
-
749
- function printUsageSummary(value) {
750
- console.log(`Range: ${value.range.from}..${value.range.to}`);
751
- console.log(`Requests: ${value.totals.requests_total}`);
752
- console.log(`Errors: ${value.totals.errors_total}`);
753
- console.log(
754
- `2xx/3xx/4xx/5xx: ${value.totals.requests_2xx}/${value.totals.requests_3xx}/${value.totals.requests_4xx}/${value.totals.requests_5xx}`
755
- );
756
- console.log(`Deploys: ${value.totals.deploy_count}`);
757
- console.log(`Rollbacks: ${value.totals.rollback_count}`);
758
- console.log(`Realtime messages out: ${value.totals.realtime_messages_out ?? 0}`);
759
- console.log(`Realtime peak connections: ${value.totals.realtime_peak_connections ?? 0}`);
760
- console.log(`Storage total: ${formatBytes(storageTotalUsageBytes(value.totals))}`);
761
- console.log(`Project files: ${formatBytes(value.totals.deployment_source_storage_bytes ?? 0)}`);
762
- console.log(`Cron runs/failures: ${value.totals.cron_runs}/${value.totals.cron_failures}`);
763
- console.log(
764
- `Webhook deliveries/failures: ${value.totals.webhook_deliveries}/${value.totals.webhook_failures}`
765
- );
766
- }
767
-
768
- function storageTotalUsageBytes(totals = {}) {
769
- if (totals.storage_total_bytes !== undefined && totals.storage_total_bytes !== null) {
770
- return Number(totals.storage_total_bytes || 0);
771
- }
772
- return Number(totals.r2_storage_bytes || 0) + Number(totals.deployment_source_storage_bytes || 0);
773
- }
774
-
775
- function formatBytes(value) {
776
- const bytes = Number(value || 0);
777
- if (!Number.isFinite(bytes) || bytes <= 0) {
778
- return '0 B';
779
- }
780
- if (bytes < 1024) {
781
- return `${Math.round(bytes).toLocaleString()} B`;
782
- }
783
- const units = ['KB', 'MB', 'GB', 'TB'];
784
- let size = bytes / 1024;
785
- let unitIndex = 0;
786
- while (size >= 1024 && unitIndex < units.length - 1) {
787
- size /= 1024;
788
- unitIndex += 1;
789
- }
790
- return `${size.toLocaleString(undefined, { maximumFractionDigits: size >= 10 ? 1 : 2 })} ${units[unitIndex]}`;
791
- }
792
-
793
- async function listWebhooks(flags) {
794
- const project = requireProjectId(flags);
795
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/webhooks`, {
796
- method: 'GET',
797
- ...projectAuth(flags),
798
- });
799
-
800
- output(flags, body, (value) => {
801
- for (const webhook of value.webhooks) {
802
- console.log(
803
- `${webhook.webhook_id}\t${webhook.name}\t${webhook.url}\tevents=${webhook.events.join(',')}\tlast=${webhook.last_status ?? 'none'}`
804
- );
805
- }
806
- });
807
- }
808
-
809
- async function createWebhook(flags) {
810
- const project = requireProjectId(flags);
811
- const url = stringFlag(flags, 'url');
812
- if (!url) {
813
- throw new Error('webhook create requires --url');
814
- }
815
-
816
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/webhooks`, {
817
- method: 'POST',
818
- ...projectAuth(flags),
819
- body: {
820
- name: stringFlag(flags, 'name') || undefined,
821
- url,
822
- events: stringFlag(flags, 'events') || undefined,
823
- },
824
- });
825
-
826
- output(flags, body, (value) => {
827
- printWebhook(value.webhook);
828
- console.log(`Signing secret: ${value.signing_secret}`);
829
- });
830
- }
831
-
832
- async function testWebhook(flags) {
833
- const project = requireProjectId(flags);
834
- const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
835
- if (!webhookId) {
836
- throw new Error('webhook test requires --webhook-id');
837
- }
838
-
839
- const body = await apiRequest(
840
- flags,
841
- `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}/test`,
842
- {
843
- method: 'POST',
844
- ...projectAuth(flags),
845
- }
846
- );
847
-
848
- output(flags, body, (value) => {
849
- printWebhookDelivery(value.delivery);
850
- });
851
- }
852
-
853
- async function listWebhookDeliveries(flags) {
854
- const project = requireProjectId(flags);
855
- const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
856
- if (!webhookId) {
857
- throw new Error('webhook deliveries requires --webhook-id');
858
- }
859
-
860
- const limit = positiveIntegerFlag(flags, 'limit');
861
- const query = limit ? `?limit=${encodeURIComponent(String(limit))}` : '';
862
- const body = await apiRequest(
863
- flags,
864
- `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}/deliveries${query}`,
865
- {
866
- method: 'GET',
867
- ...projectAuth(flags),
868
- }
869
- );
870
-
871
- output(flags, body, (value) => {
872
- for (const delivery of value.deliveries) {
873
- printWebhookDelivery(delivery);
874
- }
875
- });
876
- }
877
-
878
- async function deleteWebhook(flags) {
879
- const project = requireProjectId(flags);
880
- const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
881
- if (!webhookId) {
882
- throw new Error('webhook delete requires --webhook-id');
883
- }
884
-
885
- const body = await apiRequest(
886
- flags,
887
- `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}`,
888
- {
889
- method: 'DELETE',
890
- ...projectAuth(flags),
891
- }
892
- );
893
-
894
- output(flags, body, (value) => {
895
- console.log(`${value.webhook_id}: ${value.status}`);
896
- });
897
- }
898
-
899
- function printWebhook(webhook) {
900
- console.log(`Webhook: ${webhook.webhook_id}`);
901
- console.log(`Name: ${webhook.name}`);
902
- console.log(`URL: ${webhook.url}`);
903
- console.log(`Events: ${webhook.events.join(', ')}`);
904
- console.log(`Last status: ${webhook.last_status ?? 'none'}`);
905
- console.log(`Last error: ${webhook.last_error ?? 'none'}`);
906
- }
907
-
908
- function printWebhookDelivery(delivery) {
909
- console.log(
910
- `${delivery.delivery_id}\t${delivery.event_type}\tstatus=${delivery.status ?? 'none'}\tduration=${delivery.duration_ms}ms\terror=${delivery.error_message ?? 'none'}`
911
- );
912
- }
913
-
914
- async function listTokens(flags) {
915
- throw new Error(
916
- 'API 토큰은 웹 프로필에서 발급하거나 사용 중지해주세요. CLI 토큰은 프로젝트 관리 전용입니다.'
917
- );
918
- }
919
-
920
- async function createToken(flags) {
921
- throw new Error('API 토큰은 웹 프로필에서 발급해주세요. CLI 토큰으로 새 토큰을 만들 수 없습니다.');
922
- }
923
-
924
- async function revokeToken(flags) {
925
- throw new Error('API 토큰은 웹 프로필에서 사용 중지해주세요. CLI 토큰으로 토큰을 폐기할 수 없습니다.');
926
- }
927
-
928
- async function deleteProject(flags) {
929
- const project = requireProjectId(flags);
930
- if (!flags.yes) {
931
- throw new Error('delete requires --yes');
932
- }
933
-
934
- const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}`, {
935
- method: 'DELETE',
936
- ...projectAuth(flags),
937
- body: { delete_agreement: true },
938
- });
939
-
940
- output(flags, body, (value) => {
941
- console.log(`${project}: ${value.status}`);
942
- });
943
- }
944
-
945
- async function apiRequest(flags, apiPath, options) {
946
- const apiUrl = trimTrailingSlash(options.apiBaseUrl || apiBaseUrl(flags));
947
- const headers = {
948
- ...(options.apiToken ? { Authorization: `Bearer ${options.apiToken}` } : {}),
949
- ...(options.adminToken ? { 'X-Joripspace-Admin-Token': options.adminToken } : {}),
950
- ...(options.body ? { 'Content-Type': 'application/json' } : {}),
951
- 'X-Joripspace-Session-Context': 'cli',
952
- };
953
-
954
- const timeoutMs = options.timeoutMs ?? (isDeploymentRequest(apiPath) ? null : GENERAL_REQUEST_TIMEOUT_MS);
955
- const controller = new AbortController();
956
- const timer = timeoutMs === null ? undefined : setTimeout(() => controller.abort(), timeoutMs);
957
- let response;
958
- try {
959
- response = await fetch(`${apiUrl}${apiPath}`, {
960
- method: options.method,
961
- headers,
962
- body: options.body ? JSON.stringify(options.body) : undefined,
963
- signal: controller.signal,
964
- });
965
- } catch (error) {
966
- if (error?.name === 'AbortError') {
967
- const state = isDeploymentMutation(apiPath, options.method)
968
- ? ' Deployment state is unknown; list deployments before retrying.'
969
- : '';
970
- const timeoutError = new Error(
971
- `request timed out after ${Math.round(timeoutMs / 1000)} seconds.${state}`
972
- );
973
- timeoutError.code = 'request_timeout';
974
- throw timeoutError;
975
- }
976
- const requestError = new Error(error instanceof Error ? error.message : String(error));
977
- requestError.code = 'request_failed';
978
- throw requestError;
979
- } finally {
980
- clearTimeout(timer);
981
- }
982
- const text = await response.text();
983
- const body = text ? parseJson(text) : {};
984
-
985
- if (!response.ok) {
986
- const message = body?.error?.message || body?.message || text || `HTTP ${response.status}`;
987
- const apiError = new Error(formatDeploymentFailure(message, body?.error?.details));
988
- apiError.code = body?.error?.code || 'http_error';
989
- apiError.status = response.status;
990
- if (body?.error?.details !== undefined) apiError.details = body.error.details;
991
- throw apiError;
992
- }
993
-
994
- if (options.includeHeaders) {
995
- return { body, headers: response.headers };
996
- }
997
-
998
- return body;
999
- }
1000
-
1001
- function isDeploymentRequest(apiPath) {
1002
- return /\/deploy(?:ments)?(?:[/?]|$)|\/checkpoints\/[^/]+\/deploy(?:[/?]|$)/.test(apiPath);
1003
- }
1004
-
1005
- function isDeploymentMutation(apiPath, method) {
1006
- return method === 'POST' && (/\/deploy(?:[/?]|$)/.test(apiPath) || /\/rollback(?:[/?]|$)/.test(apiPath));
1007
- }
1008
-
1009
- function browserConnectInstructions() {
1010
- return {
1011
- status: 'browser_connection_required',
1012
- connect_url: 'https://joripspace.com/connect/',
1013
- message:
1014
- '이메일 주소는 필요 없습니다. 브라우저에서 JoripSpace에 로그인한 뒤 연결을 승인하고 5분 일회용 연결 코드를 복사하세요.',
1015
- save_command: 'joripspace login --code "복사한_연결_코드"',
1016
- };
1017
- }
1018
-
1019
- function printBrowserConnectInstructions(value) {
1020
- console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1021
- console.log('이메일 주소 입력이나 메일 확인은 필요 없습니다.');
1022
- console.log(`연결 페이지: ${value.connect_url}`);
1023
- console.log('승인 후 화면에 표시되는 5분 일회용 연결 코드를 아래 명령으로 교환하세요.');
1024
- console.log(value.save_command);
1025
- }
1026
-
1027
- function normalizeConnectToken(value) {
1028
- const token = String(value || '').trim();
1029
- if (!token) {
1030
- throw new Error('connect token is required');
1031
- }
1032
- if (
1033
- token.startsWith(SESSION_COOKIE_PREFIX) ||
1034
- /^bearer\s+/i.test(token) ||
1035
- ['dummy', 'test', 'token', 'undefined', 'null'].includes(token.toLowerCase())
1036
- ) {
1037
- throw new Error(
1038
- '브라우저 쿠키, Bearer 문자열, 빈 자리표시자, 테스트 값은 CLI 연결 토큰으로 사용할 수 없습니다. /connect/에서 새 연결 토큰을 발급하세요.'
1039
- );
1040
- }
1041
- return token;
1042
- }
1043
-
1044
- function normalizeConnectionCode(value) {
1045
- const normalized = String(value || '')
1046
- .replace(/[\s-]+/g, '')
1047
- .toUpperCase();
1048
- if (!/^[0-9A-HJKMNP-TV-Z]{16}$/.test(normalized)) {
1049
- throw new Error('연결 코드는 화면에 표시된 16자리 영숫자 값이어야 합니다.');
1050
- }
1051
- return normalized.match(/.{1,4}/g).join('-');
1052
- }
1053
-
1054
- function parseArgs(argv) {
1055
- const flags = {};
1056
- const positional = [];
1057
-
1058
- for (let index = 0; index < argv.length; index += 1) {
1059
- const arg = argv[index];
1060
- if (arg === '--') {
1061
- positional.push(...argv.slice(index + 1));
1062
- break;
1063
- }
1064
-
1065
- if (arg.startsWith('--')) {
1066
- const [rawKey, inlineValue] = arg.slice(2).split('=', 2);
1067
- const key = rawKey.trim();
1068
- const next = argv[index + 1];
1069
- const value =
1070
- inlineValue !== undefined ? inlineValue : next && !next.startsWith('-') ? argv[++index] : true;
1071
- addFlag(flags, key, value);
1072
- continue;
1073
- }
1074
-
1075
- if (arg.startsWith('-') && arg.length === 2) {
1076
- addFlag(flags, arg.slice(1), true);
1077
- continue;
1078
- }
1079
-
1080
- positional.push(arg);
1081
- }
1082
-
1083
- return {
1084
- command: positional[0],
1085
- rest: positional.slice(1),
1086
- flags,
1087
- };
1088
- }
1089
-
1090
- function addFlag(flags, key, value) {
1091
- if (flags[key] === undefined) {
1092
- flags[key] = value;
1093
- return;
1094
- }
1095
-
1096
- if (Array.isArray(flags[key])) {
1097
- flags[key].push(value);
1098
- return;
1099
- }
1100
-
1101
- flags[key] = [flags[key], value];
1102
- }
1103
-
1104
- function output(flags, body, humanPrinter) {
1105
- if (flags.json) {
1106
- console.log(JSON.stringify(body, null, 2));
1107
- return;
1108
- }
1109
-
1110
- humanPrinter(body);
1111
- }
1112
-
1113
- function requireProjectId(flags) {
1114
- const explicit = stringFlag(flags, 'project') || stringFlag(flags, 'project-id');
1115
- const linked = readLinkedProjectId(flags);
1116
- if (explicit && linked && explicit !== linked) {
1117
- throw new Error(`project ${explicit} conflicts with linked project ${linked}`);
1118
- }
1119
- const value = explicit || linked;
1120
- if (!value) {
1121
- throw new Error('missing project slug. Pass --project or run joripspace start PROJECT --cwd PATH');
1122
- }
1123
- return value;
1124
- }
1125
-
1126
- function sqlFromFlags(flags, commandName) {
1127
- const inline = stringFlag(flags, 'sql');
1128
- const filePath = stringFlag(flags, 'file');
1129
- if (inline) {
1130
- return inline;
1131
- }
1132
- if (filePath) {
1133
- return fs.readFileSync(path.resolve(filePath), 'utf8');
1134
- }
1135
- throw new Error(`db ${commandName} requires --sql or --file`);
1136
- }
1137
-
1138
- function requireStorageKey(flags) {
1139
- const key = stringFlag(flags, 'key');
1140
- if (!key) {
1141
- throw new Error('storage command requires --key');
1142
- }
1143
- if (key.startsWith('/') || key.includes('../') || key.includes('..\\')) {
1144
- throw new Error('storage key must be a project-relative object key');
1145
- }
1146
- return key;
1147
- }
1148
-
1149
- function contentTypeForPath(filePath) {
1150
- const ext = path.extname(filePath).toLowerCase();
1151
- if (ext === '.html') return 'text/html; charset=utf-8';
1152
- if (ext === '.css') return 'text/css; charset=utf-8';
1153
- if (ext === '.js' || ext === '.mjs') return 'application/javascript; charset=utf-8';
1154
- if (ext === '.json') return 'application/json; charset=utf-8';
1155
- if (ext === '.svg') return 'image/svg+xml';
1156
- if (ext === '.png') return 'image/png';
1157
- if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
1158
- if (ext === '.webp') return 'image/webp';
1159
- if (ext === '.gif') return 'image/gif';
1160
- if (ext === '.pdf') return 'application/pdf';
1161
- return 'application/octet-stream';
1162
- }
1163
-
1164
- function requireAccountId(flags) {
1165
- const projectEnv = readProjectEnv(projectWorkspaceDir(flags));
1166
- const value =
1167
- stringFlag(flags, 'account') ||
1168
- stringFlag(flags, 'account-id') ||
1169
- process.env.JORIPSPACE_ACCOUNT_ID ||
1170
- projectEnv.JORIPSPACE_ACCOUNT_ID ||
1171
- readGlobalSession(flags)?.account?.account_id;
1172
- if (!value) {
1173
- throw new Error('missing account id. Run joripspace login or pass --account');
1174
- }
1175
- return value;
1176
- }
1177
-
1178
- function projectAuth(flags) {
1179
- const connection = resolveConnection(flags);
1180
- return {
1181
- apiToken: requireApiToken(flags, connection),
1182
- apiBaseUrl: connection.apiBaseUrl,
1183
- };
1184
- }
1185
-
1186
- function optionalApiToken(flags) {
1187
- const token = resolveConnection(flags).apiToken;
1188
- return token ? normalizeConnectToken(token) : '';
1189
- }
1190
-
1191
- function apiBaseUrl(flags) {
1192
- return resolveConnection(flags).apiBaseUrl;
1193
- }
1194
-
1195
- function resolveConnection(flags) {
1196
- const explicitToken = stringFlag(flags, 'token') || stringFlag(flags, 'api-token');
1197
- if (explicitToken) return connectionForExplicitToken(flags, explicitToken);
1198
-
1199
- const environmentToken = process.env.JORIPSPACE_API_TOKEN || process.env.JORIPSPACE_CONNECT_TOKEN || '';
1200
- if (environmentToken) {
1201
- return {
1202
- apiToken: environmentToken,
1203
- apiBaseUrl: trimTrailingSlash(
1204
- process.env.JORIPSPACE_API_URL || process.env.JORIPSPACE_API_BASE_URL || DEFAULT_API_URL
1205
- ),
1206
- source: 'process-environment',
1207
- };
1208
- }
1209
-
1210
- const workspaceDir = projectWorkspaceDir(flags);
1211
- const projectEnv = readProjectEnv(workspaceDir);
1212
- if (projectEnv.JORIPSPACE_API_TOKEN) {
1213
- return {
1214
- apiToken: projectEnv.JORIPSPACE_API_TOKEN,
1215
- apiBaseUrl: trimTrailingSlash(projectEnv.JORIPSPACE_API_BASE_URL || DEFAULT_API_URL),
1216
- source: 'project-env',
1217
- workspaceDir,
1218
- };
1219
- }
1220
-
1221
- const legacyProjectConnection = readLegacyProjectSessionConnection(workspaceDir);
1222
- if (legacyProjectConnection) return legacyProjectConnection;
1223
-
1224
- const legacy = readGlobalSession(flags);
1225
- const legacyToken = legacy?.api_token || legacy?.connect_token;
1226
- if (legacyToken) {
1227
- return {
1228
- apiToken: legacyToken,
1229
- apiBaseUrl: trimTrailingSlash(legacy.api_base_url || DEFAULT_API_URL),
1230
- source: 'legacy-global-session',
1231
- workspaceDir,
1232
- };
1233
- }
1234
-
1235
- return {
1236
- apiToken: '',
1237
- apiBaseUrl: trimTrailingSlash(
1238
- stringFlag(flags, 'api-url') ||
1239
- process.env.JORIPSPACE_API_URL ||
1240
- process.env.JORIPSPACE_API_BASE_URL ||
1241
- projectEnv.JORIPSPACE_API_BASE_URL ||
1242
- DEFAULT_API_URL
1243
- ),
1244
- source: 'none',
1245
- workspaceDir,
1246
- };
1247
- }
1248
-
1249
- function connectionForExplicitToken(flags, apiToken) {
1250
- return {
1251
- apiToken,
1252
- apiBaseUrl: trimTrailingSlash(stringFlag(flags, 'api-url') || DEFAULT_API_URL),
1253
- source: 'explicit-flag',
1254
- };
1255
- }
1256
-
1257
- function unauthenticatedApiBaseUrl(flags) {
1258
- return trimTrailingSlash(
1259
- stringFlag(flags, 'api-url') ||
1260
- process.env.JORIPSPACE_API_URL ||
1261
- process.env.JORIPSPACE_API_BASE_URL ||
1262
- DEFAULT_API_URL
1263
- );
1264
- }
1265
-
1266
- function globalSessionPath(flags) {
1267
- return path.join(os.homedir(), '.joripspace', 'session.json');
1268
- }
1269
-
1270
- function readGlobalSession(flags) {
1271
- const filePath = globalSessionPath(flags);
1272
- const value = readJsonFile(filePath);
1273
- return value ? { ...value, path: filePath } : null;
1274
- }
1275
-
1276
- function scrubGlobalSessionToken() {
1277
- const filePath = globalSessionPath({});
1278
- const session = readJsonFile(filePath);
1279
- if (
1280
- !session ||
1281
- (!Object.prototype.hasOwnProperty.call(session, 'api_token') &&
1282
- !Object.prototype.hasOwnProperty.call(session, 'connect_token'))
1283
- ) {
1284
- return false;
1285
- }
1286
- const next = { ...session };
1287
- delete next.api_token;
1288
- delete next.connect_token;
1289
- next.migrated_at = new Date().toISOString();
1290
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
1291
- writeJsonFile(filePath, next, 0o600);
1292
- return true;
1293
- }
1294
-
1295
- function persistStartConnection(flags, connection) {
1296
- if (
1297
- !['legacy-global-session', 'legacy-project-session'].includes(connection?.source) ||
1298
- !connection.apiToken
1299
- ) {
1300
- return false;
1301
- }
1302
- const workspaceDir = path.resolve(stringFlag(flags, 'cwd') || projectWorkspaceDir(flags));
1303
- ensureProjectEnvIgnored(workspaceDir);
1304
- updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
1305
- JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
1306
- JORIPSPACE_API_TOKEN: connection.apiToken,
1307
- JORIPSPACE_ACCOUNT_ID: connection.accountId,
1308
- JORIPSPACE_CONNECTION_SOURCE: `${connection.source}-migration`,
1309
- });
1310
- if (connection.source === 'legacy-global-session') scrubGlobalSessionToken();
1311
- return true;
1312
- }
1313
-
1314
- function readLegacyProjectSessionConnection(workspaceDir) {
1315
- const managedDirectory = canonicalWorkspaceEntry(workspaceDir, '.joripspace');
1316
- if (!managedDirectory) return null;
1317
- const sessionName = canonicalWorkspaceEntry(
1318
- path.join(workspaceDir, managedDirectory),
1319
- 'agent-session.json'
1320
- );
1321
- if (!sessionName) return null;
1322
- const sessionPath = managedProjectFilePath(workspaceDir, '.joripspace/agent-session.json');
1323
- let session;
1324
- try {
1325
- session = JSON.parse(fs.readFileSync(sessionPath, 'utf8'));
1326
- } catch {
1327
- const error = new Error('legacy .joripspace/agent-session.json is not valid JSON');
1328
- error.code = 'legacy_workspace_migration_blocked';
1329
- throw error;
1330
- }
1331
- const connection = legacyCredentialSessionConnection(session);
1332
- if (!connection) return null;
1333
- return {
1334
- apiToken: connection.apiToken,
1335
- apiBaseUrl: connection.apiBaseUrl,
1336
- accountId: connection.accountId,
1337
- source: 'legacy-project-session',
1338
- workspaceDir,
1339
- };
1340
- }
1341
-
1342
- function canonicalWorkspaceEntry(directory, expected) {
1343
- let entries;
1344
- try {
1345
- entries = fs.readdirSync(directory);
1346
- } catch (error) {
1347
- if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return '';
1348
- throw error;
1349
- }
1350
- const matches = entries.filter((entry) => entry.toLowerCase() === expected.toLowerCase());
1351
- if (!matches.length) return '';
1352
- if (matches.length !== 1 || matches[0] !== expected) {
1353
- const error = new Error(`legacy workspace path must use canonical casing: ${expected}`);
1354
- error.code = 'non_canonical_workspace_path';
1355
- throw error;
1356
- }
1357
- return matches[0];
1358
- }
1359
-
1360
- async function connectForStart(flags, context) {
1361
- let connectionCode = stringFlag(flags, 'code');
1362
- const interactive = !flags.json && Boolean(process.stdin.isTTY && process.stdout.isTTY);
1363
- if (!connectionCode && !interactive) return resolveConnection(flags);
1364
-
1365
- if (!connectionCode) {
1366
- const instructions = browserConnectInstructions();
1367
- console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1368
- console.log(`연결 페이지: ${instructions.connect_url}`);
1369
- console.log('승인 후 표시된 5분 일회용 연결 코드를 이 터미널에 붙여 넣으세요.');
1370
- openExternalUrl(instructions.connect_url);
1371
- const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
1372
- try {
1373
- connectionCode = await prompt.question('연결 코드: ');
1374
- } finally {
1375
- prompt.close();
1376
- }
1377
- }
1378
-
1379
- const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
1380
- ensureProjectEnvIgnored(context.cwd);
1381
- const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
1382
- method: 'POST',
1383
- body: { code: normalizeConnectionCode(connectionCode) },
1384
- apiBaseUrl: exchangeApiBaseUrl,
1385
- });
1386
- const exchangedToken = normalizeConnectToken(exchange.connect_token);
1387
- await saveBrowserConnectTokenWithOptions(
1388
- { ...flags, cwd: context.cwd },
1389
- exchangedToken,
1390
- 'connection-code',
1391
- exchangeApiBaseUrl,
1392
- { output: false }
1393
- );
1394
- return resolveConnection({ ...flags, cwd: context.cwd });
1395
- }
1396
-
1397
- function openExternalUrl(url) {
1398
- const command =
1399
- process.platform === 'win32'
1400
- ? { file: 'cmd.exe', args: ['/d', '/c', 'start', '', url] }
1401
- : process.platform === 'darwin'
1402
- ? { file: 'open', args: [url] }
1403
- : { file: 'xdg-open', args: [url] };
1404
- try {
1405
- const child = spawn(command.file, command.args, {
1406
- detached: true,
1407
- stdio: 'ignore',
1408
- windowsHide: true,
1409
- });
1410
- child.once('error', () => {});
1411
- child.unref();
1412
- return true;
1413
- } catch {
1414
- return false;
1415
- }
1416
- }
1417
-
1418
- function projectWorkspaceDir(flags, options = {}) {
1419
- const start = path.resolve(stringFlag(flags, 'cwd') || process.cwd());
1420
- if (options.discover === false) return start;
1421
- let current = start;
1422
- for (;;) {
1423
- if (
1424
- fs.existsSync(path.join(current, '.env.joripspace')) ||
1425
- fs.existsSync(path.join(current, '.joripspace', 'project.json')) ||
1426
- fs.existsSync(path.join(current, '.joripspace', 'project'))
1427
- ) {
1428
- return current;
1429
- }
1430
- const parent = path.dirname(current);
1431
- if (parent === current) return start;
1432
- current = parent;
1433
- }
1434
- }
1435
-
1436
- function readLinkedProjectId(flags) {
1437
- const workspaceDir = projectWorkspaceDir(flags);
1438
- const markerPath = managedProjectFilePath(workspaceDir, '.joripspace/project');
1439
- if (fs.existsSync(markerPath)) return readProjectMarker(workspaceDir);
1440
- return '';
1441
- }
1442
-
1443
- function readJsonFile(filePath) {
1444
- try {
1445
- return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1446
- } catch {
1447
- return null;
1448
- }
1449
- }
1450
-
1451
- function writeJsonFile(filePath, value, mode) {
1452
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
1453
- const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
1454
- fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
1455
- encoding: 'utf8',
1456
- ...(mode ? { mode } : {}),
1457
- });
1458
- replaceFileAtomically(temporaryPath, filePath);
1459
- if (mode && process.platform !== 'win32') fs.chmodSync(filePath, mode);
1460
- }
1461
-
1462
- function writeTextAtomically(filePath, value) {
1463
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
1464
- const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
1465
- fs.writeFileSync(temporaryPath, value, 'utf8');
1466
- replaceFileAtomically(temporaryPath, filePath);
1467
- }
1468
-
1469
- function managedProjectFilePath(workspaceDir, relative) {
1470
- const location = resolveProjectFileTarget(workspaceDir, relative);
1471
- if (location.blockers.length) {
1472
- throw new Error(`managed project file path is blocked: ${location.blockers.join(', ')}`);
1473
- }
1474
- return location.target;
1475
- }
1476
-
1477
- function assertSafeManagedWorkspace(workspaceDir) {
1478
- resolveProjectDirectoryTarget(workspaceDir, '.joripspace');
1479
- for (const relative of [
1480
- '.env.joripspace',
1481
- '.gitignore',
1482
- 'AGENTS.md',
1483
- 'CLAUDE.md',
1484
- 'package.json',
1485
- '.joripspace/project',
1486
- '.joripspace/project.json',
1487
- '.joripspace/agent-session.json',
1488
- '.joripspace/doctor.mjs',
1489
- '.joripspace/deploy.mjs',
1490
- '.joripspace/install-template.mjs',
1491
- '.joripspace/pull.mjs',
1492
- '.joripspace/checkpoint-client.mjs',
1493
- '.joripspace/save.mjs',
1494
- '.joripspace/checkpoints.mjs',
1495
- '.joripspace/restore.mjs',
1496
- '.joripspace/deploy-checkpoint.mjs',
1497
- '.joripspace/github-actions-template.yml',
1498
- ]) {
1499
- managedProjectFilePath(workspaceDir, relative);
1500
- }
1501
- }
1502
-
1503
- function replaceFileAtomically(temporaryPath, filePath) {
1504
- try {
1505
- fs.renameSync(temporaryPath, filePath);
1506
- return;
1507
- } catch (error) {
1508
- const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
1509
- try {
1510
- if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
1511
- fs.renameSync(temporaryPath, filePath);
1512
- fs.rmSync(backupPath, { force: true });
1513
- } catch {
1514
- try {
1515
- if (fs.existsSync(backupPath) && !fs.existsSync(filePath)) fs.renameSync(backupPath, filePath);
1516
- } catch {}
1517
- fs.rmSync(temporaryPath, { force: true });
1518
- throw error;
1519
- }
1520
- }
1521
- }
1522
-
1523
- function requireApiToken(flags, connection) {
1524
- const value = connection?.apiToken ? normalizeConnectToken(connection.apiToken) : optionalApiToken(flags);
1525
- if (!value) {
1526
- throw new Error('missing API token. Run joripspace login, pass --token, or set JORIPSPACE_API_TOKEN');
1527
- }
1528
- return value;
1529
- }
1530
-
1531
- function stringFlag(flags, name) {
1532
- const value = flags[name];
1533
- if (Array.isArray(value)) {
1534
- return String(value[value.length - 1]);
1535
- }
1536
- return typeof value === 'string' ? value : '';
1537
- }
1538
-
1539
- function booleanFlag(flags, name) {
1540
- const value = flags[name];
1541
- if (Array.isArray(value)) {
1542
- return Boolean(value[value.length - 1]);
1543
- }
1544
- return value === true || value === 'true' || value === '1';
1545
- }
1546
-
1547
- function arrayFlag(flags, name) {
1548
- const value = flags[name];
1549
- if (value === undefined) {
1550
- return [];
1551
- }
1552
- return Array.isArray(value) ? value.map(String) : [String(value)];
1553
- }
1554
-
1555
- function positiveIntegerFlag(flags, name) {
1556
- const value = stringFlag(flags, name);
1557
- if (!value) {
1558
- return null;
1559
- }
1560
-
1561
- const parsed = Number(value);
1562
- if (!Number.isInteger(parsed) || parsed < 1) {
1563
- throw new Error(`--${name} must be a positive integer`);
1564
- }
1565
- return parsed;
1566
- }
1567
-
1568
- function usageRangeQuery(flags) {
1569
- const params = new URLSearchParams(usageRangeParams(flags));
1570
- return params.toString() ? `?${params.toString()}` : '';
1571
- }
1572
-
1573
- function usageRangeParams(flags) {
1574
- const params = {};
1575
- const from = stringFlag(flags, 'from');
1576
- const to = stringFlag(flags, 'to');
1577
- if (from) {
1578
- params.from = from;
1579
- }
1580
- if (to) {
1581
- params.to = to;
1582
- }
1583
- return params;
1584
- }
1585
-
1586
- function splitFileMapping(value) {
1587
- const separator = value.indexOf('=');
1588
- if (separator <= 0 || separator === value.length - 1) {
1589
- throw new Error('--file must use name=path');
1590
- }
1591
-
1592
- return [value.slice(0, separator), value.slice(separator + 1)];
1593
- }
1594
-
1595
- function templateVars(flags) {
1596
- const vars = {};
1597
- for (const item of arrayFlag(flags, 'var')) {
1598
- const [name, value] = splitFileMapping(item);
1599
- vars[name] = value;
1600
- }
1601
- return vars;
1602
- }
1603
-
1604
- function parseJson(text) {
1605
- try {
1606
- return JSON.parse(text);
1607
- } catch {
1608
- return { raw: text };
1609
- }
1610
- }
1611
-
1612
- function trimTrailingSlash(value) {
1613
- return value.replace(/\/+$/, '');
1614
- }
109
+
110
+ main().catch((error) => {
111
+ const message = error instanceof Error ? error.message : String(error);
112
+ if (process.argv.slice(2).some((argument) => argument === '--json' || argument.startsWith('--json='))) {
113
+ const serialized = {
114
+ code: typeof error?.code === 'string' ? error.code : 'invalid_arguments',
115
+ message,
116
+ ...(Number.isInteger(error?.status) ? { status: error.status } : {}),
117
+ ...(error?.details === undefined ? {} : { details: error.details }),
118
+ };
119
+ console.error(JSON.stringify({ ok: false, error: serialized }));
120
+ } else {
121
+ console.error(`joripspace: ${message}`);
122
+ }
123
+ process.exitCode = Number.isInteger(error?.exitCode) ? error.exitCode : 1;
124
+ });
125
+
126
+ async function main() {
127
+ const { command, rest, flags } = parseArgs(process.argv.slice(2));
128
+
129
+ if (flags.version || flags.v) {
130
+ console.log(require('../package.json').version);
131
+ return;
132
+ }
133
+
134
+ if (!command || command === 'help') {
135
+ printHelp();
136
+ return;
137
+ }
138
+
139
+ if (
140
+ (flags.help || flags.h) &&
141
+ command !== 'deploy' &&
142
+ command !== 'deploy-template' &&
143
+ command !== 'install-template'
144
+ ) {
145
+ printHelp();
146
+ return;
147
+ }
148
+
149
+ switch (command) {
150
+ case 'version':
151
+ console.log(require('../package.json').version);
152
+ return;
153
+ case 'login':
154
+ await login(flags);
155
+ return;
156
+ case 'me':
157
+ await getMe(flags);
158
+ return;
159
+ case 'projects':
160
+ await listMyProjects(flags);
161
+ return;
162
+ case 'billing-projects':
163
+ webOnlyCommand('결제 프로젝트');
164
+ return;
165
+ case 'billing-usage':
166
+ webOnlyCommand('결제 사용량');
167
+ return;
168
+ case 'invoices':
169
+ webOnlyCommand('청구서');
170
+ return;
171
+ case 'link':
172
+ await linkProject(flags);
173
+ return;
174
+ case 'start':
175
+ await startProjectCommand(rest, flags);
176
+ return;
177
+ case 'create':
178
+ webOnlyCommand('프로젝트 생성');
179
+ return;
180
+ case 'get':
181
+ await getProject(flags);
182
+ return;
183
+ case 'db':
184
+ await dbCommand(rest, flags);
185
+ return;
186
+ case 'storage':
187
+ await storageCommand(rest, flags);
188
+ return;
189
+ case 'deploy':
190
+ if (flags.help || flags.h) {
191
+ printDeployHelp();
192
+ return;
193
+ }
194
+ await deployCode(flags);
195
+ return;
196
+ case 'templates':
197
+ await templateCommands.list(flags);
198
+ return;
199
+ case 'template':
200
+ if (rest[0] === 'list') {
201
+ await templateCommands.marketplaceList(flags);
202
+ return;
203
+ }
204
+ if (rest[0] === 'pull') {
205
+ await templateCommands.pull(flags);
206
+ return;
207
+ }
208
+ throw new Error('template command requires: list or pull');
209
+ case 'knowledge':
210
+ await remoteCommands.knowledge(rest, flags);
211
+ return;
212
+ case 'deployment':
213
+ await remoteCommands.deployment(rest, flags);
214
+ return;
215
+ case 'template-pull':
216
+ await templateCommands.pull(flags);
217
+ return;
218
+ case 'deploy-template':
219
+ if (flags.help || flags.h) {
220
+ printDeployTemplateHelp();
221
+ return;
222
+ }
223
+ await templateCommands.deploy(flags);
224
+ return;
225
+ case 'install-template':
226
+ if (flags.help || flags.h) {
227
+ printInstallTemplateHelp();
228
+ return;
229
+ }
230
+ await templateCommands.install(flags);
231
+ return;
232
+ case 'deployments':
233
+ await listDeployments(flags);
234
+ return;
235
+ case 'checkpoint':
236
+ case 'checkpoints':
237
+ await checkpointCommands.command(rest, flags);
238
+ return;
239
+ case 'realtime-v2':
240
+ await createRealtimeV2Commands({apiRequest,output,projectAuth,requireProjectId,stringFlag})(rest,flags);
241
+ return;
242
+ case 'github':
243
+ await githubCommand(rest, flags);
244
+ return;
245
+ case 'rollback':
246
+ await rollbackDeployment(flags);
247
+ return;
248
+ case 'events':
249
+ case 'logs':
250
+ await listRuntimeEvents(flags);
251
+ return;
252
+ case 'usage':
253
+ webOnlyCommand('일일 사용량 상세');
254
+ return;
255
+ case 'usage-summary':
256
+ await getUsageSummary(flags);
257
+ return;
258
+ case 'usage-breakdown':
259
+ await getUsageBreakdown(flags);
260
+ return;
261
+ case 'tokens':
262
+ webOnlyCommand('API 토큰 관리');
263
+ return;
264
+ case 'crons':
265
+ await remoteCommands.listCrons(flags);
266
+ return;
267
+ case 'domains':
268
+ await remoteCommands.listDomains(flags);
269
+ return;
270
+ case 'secrets':
271
+ await remoteCommands.listSecrets(flags);
272
+ return;
273
+ case 'mail':
274
+ await remoteCommands.mail(rest, flags);
275
+ return;
276
+ case 'webhooks':
277
+ webOnlyCommand('웹훅 관리');
278
+ return;
279
+ case 'token':
280
+ webOnlyCommand('API 토큰 관리');
281
+ return;
282
+ case 'secret':
283
+ await remoteCommands.secrets(rest, flags);
284
+ return;
285
+ case 'cron':
286
+ await remoteCommands.crons(rest, flags);
287
+ return;
288
+ case 'domain':
289
+ await remoteCommands.domains(rest, flags);
290
+ return;
291
+ case 'webhook':
292
+ webOnlyCommand('웹훅 관리');
293
+ return;
294
+ case 'delete':
295
+ webOnlyCommand('프로젝트 삭제');
296
+ return;
297
+ default:
298
+ throw new Error(`Unknown command: ${command}`);
299
+ }
300
+ }
301
+
302
+ async function login(flags) {
303
+ const connectionCode = stringFlag(flags, 'code');
304
+ if (connectionCode) {
305
+ ensureProjectEnvIgnored(projectWorkspaceDir(flags, { discover: false }));
306
+ const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
307
+ const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
308
+ method: 'POST',
309
+ body: { code: normalizeConnectionCode(connectionCode) },
310
+ apiBaseUrl: exchangeApiBaseUrl,
311
+ });
312
+ const exchangedToken = normalizeConnectToken(exchange.connect_token);
313
+ await saveBrowserConnectToken(flags, exchangedToken, 'connection-code', exchangeApiBaseUrl);
314
+ return;
315
+ }
316
+ const connectToken =
317
+ stringFlag(flags, 'connect-token') || stringFlag(flags, 'api-token') || stringFlag(flags, 'token');
318
+ if (connectToken) {
319
+ ensureProjectEnvIgnored(projectWorkspaceDir(flags, { discover: false }));
320
+ await saveBrowserConnectToken(flags, normalizeConnectToken(connectToken));
321
+ return;
322
+ }
323
+ output(flags, browserConnectInstructions(), printBrowserConnectInstructions);
324
+ }
325
+
326
+ async function saveBrowserConnectToken(flags, apiToken, source = 'browser-connect', selectedApiBaseUrl = '') {
327
+ return saveBrowserConnectTokenWithOptions(flags, apiToken, source, selectedApiBaseUrl);
328
+ }
329
+
330
+ async function saveBrowserConnectTokenWithOptions(
331
+ flags,
332
+ apiToken,
333
+ source = 'browser-connect',
334
+ selectedApiBaseUrl = '',
335
+ options = {}
336
+ ) {
337
+ const connection = selectedApiBaseUrl
338
+ ? { apiBaseUrl: trimTrailingSlash(selectedApiBaseUrl), apiToken, source }
339
+ : connectionForExplicitToken(flags, apiToken);
340
+ const workspaceDir = projectWorkspaceDir(flags, { discover: false });
341
+ managedProjectFilePath(workspaceDir, '.env.joripspace');
342
+ managedProjectFilePath(workspaceDir, '.gitignore');
343
+ ensureProjectEnvIgnored(workspaceDir);
344
+ const body = await apiRequest(flags, '/v1/me/projects', {
345
+ method: 'GET',
346
+ apiToken,
347
+ apiBaseUrl: connection.apiBaseUrl,
348
+ });
349
+ const requestedProject = stringFlag(flags, 'project') || stringFlag(flags, 'project-id');
350
+ const projects = Array.isArray(body.projects) ? body.projects : [];
351
+ const selected = requestedProject
352
+ ? projects.find((project) =>
353
+ [project.project_id, project.project_slug, project.slug].filter(Boolean).includes(requestedProject)
354
+ )
355
+ : projects.length === 1
356
+ ? projects[0]
357
+ : null;
358
+ if (requestedProject && !selected) throw new Error(`project is not accessible: ${requestedProject}`);
359
+ updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
360
+ JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
361
+ JORIPSPACE_API_TOKEN: apiToken,
362
+ JORIPSPACE_ACCOUNT_ID: body.account_id,
363
+ JORIPSPACE_CONNECTION_SOURCE: source,
364
+ });
365
+ scrubGlobalSessionToken();
366
+ if (options.output !== false) {
367
+ output(flags, body, (value) => {
368
+ console.log(`연결 완료: ${value.account_id}`);
369
+ console.log(`저장 위치: ${path.join(workspaceDir, '.env.joripspace')}`);
370
+ console.log('이 폴더에서 joripspace projects 또는 joripspace start 명령을 실행하세요.');
371
+ console.log('회원정보와 API 토큰 관리는 웹 프로필에서만 가능합니다.');
372
+ });
373
+ }
374
+ return body;
375
+ }
376
+
377
+ async function getMe(flags) {
378
+ const body = await apiRequest(flags, '/v1/me/projects', {
379
+ method: 'GET',
380
+ ...projectAuth(flags),
381
+ });
382
+
383
+ output(flags, body, (value) => {
384
+ console.log(`Account: ${value.account_id}`);
385
+ console.log(`Projects: ${(value.projects ?? []).length}`);
386
+ });
387
+ }
388
+
389
+ async function listMyProjects(flags) {
390
+ const body = await apiRequest(flags, '/v1/me/projects', {
391
+ method: 'GET',
392
+ ...projectAuth(flags),
393
+ });
394
+
395
+ output(flags, body, (value) => {
396
+ for (const project of value.projects ?? []) {
397
+ console.log(
398
+ `${project.project_id}\t${project.role}\towner=${project.role === 'owner' ? 'yes' : 'no'}\t${project.default_url}`
399
+ );
400
+ }
401
+ });
402
+ }
403
+
404
+ function webOnlyCommand(label) {
405
+ throw new Error(
406
+ `${label} 기능은 웹 화면에서만 사용할 수 있습니다. CLI는 개발, DB/스토리지 작업, 서버 배포, 사용량, 로그 조회용입니다.`
407
+ );
408
+ }
409
+
410
+ async function linkProject(flags, options = {}) {
411
+ const project = requireProjectId(flags);
412
+ if (options.output === false) {
413
+ throw new Error('link no longer supports internal workspace generation; use start');
414
+ }
415
+ await startProjectCommand([project], flags);
416
+ }
417
+
418
+ async function getProject(flags) {
419
+ const project = requireProjectId(flags);
420
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}`, {
421
+ method: 'GET',
422
+ ...projectAuth(flags),
423
+ });
424
+
425
+ output(flags, body, (value) => {
426
+ console.log(`Project: ${value.project_id}`);
427
+ console.log(`Slug: ${value.project_slug}`);
428
+ console.log(`Status: ${value.status}`);
429
+ console.log(`URL: ${value.default_url}`);
430
+ console.log(`Last deployed: ${value.last_deployed_at ?? 'never'}`);
431
+ });
432
+ }
433
+
434
+ async function dbCommand(rest, flags) {
435
+ const subcommand = rest[0] || 'schema';
436
+ const project = requireProjectId(flags);
437
+
438
+ if (subcommand === 'schema') {
439
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/schema`, {
440
+ method: 'GET',
441
+ ...projectAuth(flags),
442
+ });
443
+ output(flags, body, (value) => {
444
+ for (const object of value.objects ?? []) {
445
+ console.log(`${object.type}\t${object.name}`);
446
+ if (object.sql) console.log(` ${object.sql}`);
447
+ }
448
+ });
449
+ return;
450
+ }
451
+
452
+ if (subcommand === 'query') {
453
+ const sql = sqlFromFlags(flags, 'query');
454
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/query`, {
455
+ method: 'POST',
456
+ ...projectAuth(flags),
457
+ body: { sql },
458
+ });
459
+ output(flags, body, (value) => {
460
+ console.log(JSON.stringify(value.rows ?? [], null, 2));
461
+ });
462
+ return;
463
+ }
464
+
465
+ if (subcommand === 'migrate') {
466
+ const sql = sqlFromFlags(flags, 'migrate');
467
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/db/migrations`, {
468
+ method: 'POST',
469
+ ...projectAuth(flags),
470
+ body: {
471
+ name: stringFlag(flags, 'name') || null,
472
+ sql,
473
+ },
474
+ });
475
+ output(flags, body, (value) => {
476
+ console.log(`DB migration complete: ${value.project_id}`);
477
+ console.log(`Statements: ${value.statements}`);
478
+ });
479
+ return;
480
+ }
481
+
482
+ throw new Error(`Unknown db command: ${subcommand}`);
483
+ }
484
+
485
+ async function storageCommand(rest, flags) {
486
+ const subcommand = rest[0] || 'list';
487
+ const project = requireProjectId(flags);
488
+
489
+ if (subcommand === 'list') {
490
+ const search = new URLSearchParams();
491
+ const prefix = stringFlag(flags, 'prefix');
492
+ const cursor = stringFlag(flags, 'cursor');
493
+ const limit = stringFlag(flags, 'limit');
494
+ if (prefix) search.set('prefix', prefix);
495
+ if (cursor) search.set('cursor', cursor);
496
+ if (limit) search.set('limit', limit);
497
+ const query = search.toString() ? `?${search.toString()}` : '';
498
+ const body = await apiRequest(
499
+ flags,
500
+ `/v1/projects/${encodeURIComponent(project)}/storage/objects${query}`,
501
+ {
502
+ method: 'GET',
503
+ ...projectAuth(flags),
504
+ }
505
+ );
506
+ output(flags, body, (value) => {
507
+ for (const object of value.objects ?? []) {
508
+ console.log(`${object.key}\t${object.size ?? 0} B\t${object.uploaded ?? ''}`);
509
+ }
510
+ if (value.cursor) console.log(`Next cursor: ${value.cursor}`);
511
+ });
512
+ return;
513
+ }
514
+
515
+ if (subcommand === 'get') {
516
+ const key = requireStorageKey(flags);
517
+ const body = await apiRequest(
518
+ flags,
519
+ `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
520
+ {
521
+ method: 'GET',
522
+ ...projectAuth(flags),
523
+ }
524
+ );
525
+ const outPath = stringFlag(flags, 'out');
526
+ if (outPath) {
527
+ const bytes = body.base64
528
+ ? Buffer.from(body.base64, 'base64')
529
+ : Buffer.from(String(body.text ?? ''), 'utf8');
530
+ fs.writeFileSync(path.resolve(outPath), bytes);
531
+ }
532
+ output(flags, body, (value) => {
533
+ if (outPath) {
534
+ console.log(`Wrote: ${path.resolve(outPath)}`);
535
+ return;
536
+ }
537
+ if (typeof value.text === 'string') {
538
+ console.log(value.text);
539
+ return;
540
+ }
541
+ console.log(`Binary object: ${value.key} (${value.size} B). Use --out to save it.`);
542
+ });
543
+ return;
544
+ }
545
+
546
+ if (subcommand === 'put') {
547
+ const key = requireStorageKey(flags);
548
+ const filePath = stringFlag(flags, 'file');
549
+ const text = stringFlag(flags, 'text');
550
+ const hasText = flags.text !== undefined && flags.text !== true;
551
+ if (!filePath && !hasText) {
552
+ throw new Error('storage put requires --file or --text');
553
+ }
554
+ if (filePath && hasText) throw new Error('storage put accepts only one of --file or --text');
555
+ const body = filePath
556
+ ? {
557
+ base64: fs.readFileSync(path.resolve(filePath)).toString('base64'),
558
+ content_type: stringFlag(flags, 'content-type') || contentTypeForPath(filePath),
559
+ }
560
+ : {
561
+ text,
562
+ content_type: stringFlag(flags, 'content-type') || 'text/plain; charset=utf-8',
563
+ };
564
+ const result = await apiRequest(
565
+ flags,
566
+ `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
567
+ {
568
+ method: 'PUT',
569
+ ...projectAuth(flags),
570
+ body,
571
+ }
572
+ );
573
+ output(flags, result, (value) => {
574
+ console.log(`Stored: ${value.key} (${value.size} B)`);
575
+ });
576
+ return;
577
+ }
578
+
579
+ if (subcommand === 'delete') {
580
+ const key = requireStorageKey(flags);
581
+ if (!flags.yes) {
582
+ throw new Error('storage delete requires --yes');
583
+ }
584
+ const body = await apiRequest(
585
+ flags,
586
+ `/v1/projects/${encodeURIComponent(project)}/storage/objects/${encodeURIComponent(key)}`,
587
+ {
588
+ method: 'DELETE',
589
+ ...projectAuth(flags),
590
+ }
591
+ );
592
+ output(flags, body, (value) => {
593
+ console.log(`Deleted: ${value.key}`);
594
+ });
595
+ return;
596
+ }
597
+
598
+ throw new Error(`Unknown storage command: ${subcommand}`);
599
+ }
600
+
601
+ async function deployCode(flags, options = {}) {
602
+ const project = requireProjectId(flags);
603
+ const label = stringFlag(flags, 'label').trim();
604
+ if (!label) throw new Error('deploy requires --label');
605
+ let deployPayload;
606
+ try {
607
+ deployPayload = buildDeployPayload(flags);
608
+ } catch (error) {
609
+ if (error?.code !== 'archive_required') throw error;
610
+ return checkpointCommands.deployArchive(flags, project, label, error.message, options);
611
+ }
612
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deploy`, {
613
+ method: 'POST',
614
+ ...projectAuth(flags),
615
+ body: { ...deployPayload, label },
616
+ });
617
+
618
+ if (options.output !== false) {
619
+ output(flags, body, (value) => {
620
+ console.log(`Deployment: ${value.deployment_id}`);
621
+ console.log(`Status: ${value.status}`);
622
+ console.log(`URL: ${value.url}`);
623
+ printDeploymentWarnings(value.warnings);
624
+ });
625
+ }
626
+ return body;
627
+ }
628
+
629
+ function printDeploymentWarnings(warnings) {
630
+ for (const warning of warnings || []) console.warn(`경고: ${warning.message}`);
631
+ }
632
+
633
+ async function listDeployments(flags) {
634
+ const project = requireProjectId(flags);
635
+ const limit = positiveIntegerFlag(flags, 'limit');
636
+ const params = new URLSearchParams();
637
+ if (limit) params.set('limit', String(limit));
638
+ if (booleanFlag(flags, 'include-failure-details')) params.set('include_failure_details', 'true');
639
+ const query = params.size ? `?${params}` : '';
640
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/deployments${query}`, {
641
+ method: 'GET',
642
+ ...projectAuth(flags),
643
+ });
644
+
645
+ output(flags, body, (value) => {
646
+ for (const deployment of value.deployments) {
647
+ console.log(
648
+ `${deployment.version}\t${deployment.deployment_id}\t${deployment.status}\trollback=${deployment.rollback_available}\t${deployment.created_at}`
649
+ );
650
+ if (deployment.error_message) console.log(`${deployment.error_stage || 'unknown'} / ${deployment.error_code || 'unknown'}: ${deployment.error_message}`);
651
+ if (deployment.github) console.log(`GitHub: ${deployment.github.commit_sha} ${deployment.github.run_url} (${deployment.github.diagnostic_status || 'pending'})`);
652
+ if (deployment.error_details) console.log(deployment.error_details);
653
+ }
654
+ });
655
+ }
656
+
657
+ async function rollbackDeployment(flags) {
658
+ const project = requireProjectId(flags);
659
+ const deployment = stringFlag(flags, 'deployment') || stringFlag(flags, 'deployment-id');
660
+ if (!deployment) {
661
+ throw new Error('rollback requires --deployment');
662
+ }
663
+
664
+ const body = await apiRequest(
665
+ flags,
666
+ `/v1/projects/${encodeURIComponent(project)}/deployments/${encodeURIComponent(deployment)}/rollback`,
667
+ {
668
+ method: 'POST',
669
+ ...projectAuth(flags),
670
+ }
671
+ );
672
+
673
+ output(flags, body, (value) => {
674
+ console.log(`Deployment: ${value.deployment_id}`);
675
+ console.log(`Rolled back from: ${value.rolled_back_from}`);
676
+ console.log(`URL: ${value.url}`);
677
+ });
678
+ }
679
+
680
+ async function listRuntimeEvents(flags) {
681
+ const project = requireProjectId(flags);
682
+ const params = new URLSearchParams();
683
+ const eventType = stringFlag(flags, 'event-type') || stringFlag(flags, 'event_type');
684
+ const limit = positiveIntegerFlag(flags, 'limit');
685
+ if (eventType) {
686
+ params.set('event_type', eventType);
687
+ }
688
+ if (limit) {
689
+ params.set('limit', String(limit));
690
+ }
691
+
692
+ const query = params.toString() ? `?${params.toString()}` : '';
693
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/runtime-events${query}`, {
694
+ method: 'GET',
695
+ ...projectAuth(flags),
696
+ });
697
+
698
+ output(flags, body, (value) => {
699
+ for (const event of value.events) {
700
+ console.log(
701
+ `${event.created_at}\t${event.event_type}\t${event.status}\t${event.method}\t${event.path}\t${event.duration_ms}ms\t${event.error_message ?? ''}`
702
+ );
703
+ }
704
+ });
705
+ }
706
+
707
+ async function getUsage(flags) {
708
+ const project = requireProjectId(flags);
709
+ const date = stringFlag(flags, 'date');
710
+ const query = date ? `?date=${encodeURIComponent(date)}` : '';
711
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/usage${query}`, {
712
+ method: 'GET',
713
+ ...projectAuth(flags),
714
+ });
715
+
716
+ output(flags, body, (value) => {
717
+ console.log(`Date: ${value.date}`);
718
+ console.log(`Requests: ${value.requests}`);
719
+ console.log(`Errors: ${value.errors}`);
720
+ console.log(`Deploys: ${value.deploy_count}`);
721
+ });
722
+ }
723
+
724
+ async function getUsageSummary(flags) {
725
+ const project = requireProjectId(flags);
726
+ const query = usageRangeQuery(flags);
727
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/usage/summary${query}`, {
728
+ method: 'GET',
729
+ ...projectAuth(flags),
730
+ });
731
+
732
+ output(flags, body, printUsageSummary);
733
+ }
734
+
735
+ async function getUsageBreakdown(flags) {
736
+ const project = requireProjectId(flags);
737
+ const params = new URLSearchParams(usageRangeParams(flags));
738
+ const groupBy = stringFlag(flags, 'group-by') || stringFlag(flags, 'group_by');
739
+ if (groupBy) {
740
+ params.set('group_by', groupBy);
741
+ }
742
+ const query = params.toString() ? `?${params.toString()}` : '';
743
+ const body = await apiRequest(
744
+ flags,
745
+ `/v1/projects/${encodeURIComponent(project)}/usage/breakdown${query}`,
746
+ {
747
+ method: 'GET',
748
+ ...projectAuth(flags),
749
+ }
750
+ );
751
+
752
+ output(flags, body, (value) => {
753
+ printUsageSummary(value);
754
+ for (const item of value.series ?? []) {
755
+ console.log(
756
+ `${item.bucket}\trequests=${item.requests_total}\terrors=${item.errors_total}\tin=${item.request_bytes ?? 0}\tout=${item.response_bytes ?? 0}\trealtime_out=${item.realtime_messages_out ?? 0}\trealtime_peak=${item.realtime_peak_connections ?? 0}\tdeploys=${item.deploy_count}\tcron=${item.cron_runs}\twebhooks=${item.webhook_deliveries}`
757
+ );
758
+ }
759
+ });
760
+ }
761
+
762
+ function printUsageSummary(value) {
763
+ console.log(`Range: ${value.range.from}..${value.range.to}`);
764
+ console.log(`Requests: ${value.totals.requests_total}`);
765
+ console.log(`Errors: ${value.totals.errors_total}`);
766
+ console.log(
767
+ `2xx/3xx/4xx/5xx: ${value.totals.requests_2xx}/${value.totals.requests_3xx}/${value.totals.requests_4xx}/${value.totals.requests_5xx}`
768
+ );
769
+ console.log(`Deploys: ${value.totals.deploy_count}`);
770
+ console.log(`Rollbacks: ${value.totals.rollback_count}`);
771
+ console.log(`Realtime messages out: ${value.totals.realtime_messages_out ?? 0}`);
772
+ console.log(`Realtime peak connections: ${value.totals.realtime_peak_connections ?? 0}`);
773
+ console.log(`Storage total: ${formatBytes(storageTotalUsageBytes(value.totals))}`);
774
+ console.log(`Project files: ${formatBytes(value.totals.deployment_source_storage_bytes ?? 0)}`);
775
+ console.log(`Cron runs/failures: ${value.totals.cron_runs}/${value.totals.cron_failures}`);
776
+ console.log(
777
+ `Webhook deliveries/failures: ${value.totals.webhook_deliveries}/${value.totals.webhook_failures}`
778
+ );
779
+ }
780
+
781
+ function storageTotalUsageBytes(totals = {}) {
782
+ if (totals.storage_total_bytes !== undefined && totals.storage_total_bytes !== null) {
783
+ return Number(totals.storage_total_bytes || 0);
784
+ }
785
+ return Number(totals.r2_storage_bytes || 0) + Number(totals.deployment_source_storage_bytes || 0);
786
+ }
787
+
788
+ function formatBytes(value) {
789
+ const bytes = Number(value || 0);
790
+ if (!Number.isFinite(bytes) || bytes <= 0) {
791
+ return '0 B';
792
+ }
793
+ if (bytes < 1024) {
794
+ return `${Math.round(bytes).toLocaleString()} B`;
795
+ }
796
+ const units = ['KB', 'MB', 'GB', 'TB'];
797
+ let size = bytes / 1024;
798
+ let unitIndex = 0;
799
+ while (size >= 1024 && unitIndex < units.length - 1) {
800
+ size /= 1024;
801
+ unitIndex += 1;
802
+ }
803
+ return `${size.toLocaleString(undefined, { maximumFractionDigits: size >= 10 ? 1 : 2 })} ${units[unitIndex]}`;
804
+ }
805
+
806
+ async function listWebhooks(flags) {
807
+ const project = requireProjectId(flags);
808
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/webhooks`, {
809
+ method: 'GET',
810
+ ...projectAuth(flags),
811
+ });
812
+
813
+ output(flags, body, (value) => {
814
+ for (const webhook of value.webhooks) {
815
+ console.log(
816
+ `${webhook.webhook_id}\t${webhook.name}\t${webhook.url}\tevents=${webhook.events.join(',')}\tlast=${webhook.last_status ?? 'none'}`
817
+ );
818
+ }
819
+ });
820
+ }
821
+
822
+ async function createWebhook(flags) {
823
+ const project = requireProjectId(flags);
824
+ const url = stringFlag(flags, 'url');
825
+ if (!url) {
826
+ throw new Error('webhook create requires --url');
827
+ }
828
+
829
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}/webhooks`, {
830
+ method: 'POST',
831
+ ...projectAuth(flags),
832
+ body: {
833
+ name: stringFlag(flags, 'name') || undefined,
834
+ url,
835
+ events: stringFlag(flags, 'events') || undefined,
836
+ },
837
+ });
838
+
839
+ output(flags, body, (value) => {
840
+ printWebhook(value.webhook);
841
+ console.log(`Signing secret: ${value.signing_secret}`);
842
+ });
843
+ }
844
+
845
+ async function testWebhook(flags) {
846
+ const project = requireProjectId(flags);
847
+ const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
848
+ if (!webhookId) {
849
+ throw new Error('webhook test requires --webhook-id');
850
+ }
851
+
852
+ const body = await apiRequest(
853
+ flags,
854
+ `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}/test`,
855
+ {
856
+ method: 'POST',
857
+ ...projectAuth(flags),
858
+ }
859
+ );
860
+
861
+ output(flags, body, (value) => {
862
+ printWebhookDelivery(value.delivery);
863
+ });
864
+ }
865
+
866
+ async function listWebhookDeliveries(flags) {
867
+ const project = requireProjectId(flags);
868
+ const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
869
+ if (!webhookId) {
870
+ throw new Error('webhook deliveries requires --webhook-id');
871
+ }
872
+
873
+ const limit = positiveIntegerFlag(flags, 'limit');
874
+ const query = limit ? `?limit=${encodeURIComponent(String(limit))}` : '';
875
+ const body = await apiRequest(
876
+ flags,
877
+ `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}/deliveries${query}`,
878
+ {
879
+ method: 'GET',
880
+ ...projectAuth(flags),
881
+ }
882
+ );
883
+
884
+ output(flags, body, (value) => {
885
+ for (const delivery of value.deliveries) {
886
+ printWebhookDelivery(delivery);
887
+ }
888
+ });
889
+ }
890
+
891
+ async function deleteWebhook(flags) {
892
+ const project = requireProjectId(flags);
893
+ const webhookId = stringFlag(flags, 'webhook-id') || stringFlag(flags, 'webhook_id');
894
+ if (!webhookId) {
895
+ throw new Error('webhook delete requires --webhook-id');
896
+ }
897
+
898
+ const body = await apiRequest(
899
+ flags,
900
+ `/v1/projects/${encodeURIComponent(project)}/webhooks/${encodeURIComponent(webhookId)}`,
901
+ {
902
+ method: 'DELETE',
903
+ ...projectAuth(flags),
904
+ }
905
+ );
906
+
907
+ output(flags, body, (value) => {
908
+ console.log(`${value.webhook_id}: ${value.status}`);
909
+ });
910
+ }
911
+
912
+ function printWebhook(webhook) {
913
+ console.log(`Webhook: ${webhook.webhook_id}`);
914
+ console.log(`Name: ${webhook.name}`);
915
+ console.log(`URL: ${webhook.url}`);
916
+ console.log(`Events: ${webhook.events.join(', ')}`);
917
+ console.log(`Last status: ${webhook.last_status ?? 'none'}`);
918
+ console.log(`Last error: ${webhook.last_error ?? 'none'}`);
919
+ }
920
+
921
+ function printWebhookDelivery(delivery) {
922
+ console.log(
923
+ `${delivery.delivery_id}\t${delivery.event_type}\tstatus=${delivery.status ?? 'none'}\tduration=${delivery.duration_ms}ms\terror=${delivery.error_message ?? 'none'}`
924
+ );
925
+ }
926
+
927
+ async function listTokens(flags) {
928
+ throw new Error(
929
+ 'API 토큰은 웹 프로필에서 발급하거나 사용 중지해주세요. CLI 토큰은 프로젝트 관리 전용입니다.'
930
+ );
931
+ }
932
+
933
+ async function createToken(flags) {
934
+ throw new Error('API 토큰은 웹 프로필에서 발급해주세요. CLI 토큰으로 새 토큰을 만들 수 없습니다.');
935
+ }
936
+
937
+ async function revokeToken(flags) {
938
+ throw new Error('API 토큰은 웹 프로필에서 사용 중지해주세요. CLI 토큰으로 토큰을 폐기할 수 없습니다.');
939
+ }
940
+
941
+ async function deleteProject(flags) {
942
+ const project = requireProjectId(flags);
943
+ if (!flags.yes) {
944
+ throw new Error('delete requires --yes');
945
+ }
946
+
947
+ const body = await apiRequest(flags, `/v1/projects/${encodeURIComponent(project)}`, {
948
+ method: 'DELETE',
949
+ ...projectAuth(flags),
950
+ body: { delete_agreement: true },
951
+ });
952
+
953
+ output(flags, body, (value) => {
954
+ console.log(`${project}: ${value.status}`);
955
+ });
956
+ }
957
+
958
+ async function apiRequest(flags, apiPath, options) {
959
+ const apiUrl = trimTrailingSlash(options.apiBaseUrl || apiBaseUrl(flags));
960
+ const headers = {
961
+ ...(options.apiToken ? { Authorization: `Bearer ${options.apiToken}` } : {}),
962
+ ...(options.adminToken ? { 'X-Joripspace-Admin-Token': options.adminToken } : {}),
963
+ ...(options.body ? { 'Content-Type': 'application/json' } : {}),
964
+ 'X-Joripspace-Session-Context': 'cli',
965
+ };
966
+
967
+ const timeoutMs = options.timeoutMs ?? (isDeploymentRequest(apiPath) ? null : GENERAL_REQUEST_TIMEOUT_MS);
968
+ const controller = new AbortController();
969
+ const timer = timeoutMs === null ? undefined : setTimeout(() => controller.abort(), timeoutMs);
970
+ let response;
971
+ try {
972
+ response = await fetch(`${apiUrl}${apiPath}`, {
973
+ method: options.method,
974
+ headers,
975
+ body: options.body ? JSON.stringify(options.body) : undefined,
976
+ signal: controller.signal,
977
+ });
978
+ } catch (error) {
979
+ if (error?.name === 'AbortError') {
980
+ const state = isDeploymentMutation(apiPath, options.method)
981
+ ? ' Deployment state is unknown; list deployments before retrying.'
982
+ : '';
983
+ const timeoutError = new Error(
984
+ `request timed out after ${Math.round(timeoutMs / 1000)} seconds.${state}`
985
+ );
986
+ timeoutError.code = 'request_timeout';
987
+ throw timeoutError;
988
+ }
989
+ const requestError = new Error(error instanceof Error ? error.message : String(error));
990
+ requestError.code = 'request_failed';
991
+ throw requestError;
992
+ } finally {
993
+ clearTimeout(timer);
994
+ }
995
+ const text = await response.text();
996
+ const body = text ? parseJson(text) : {};
997
+
998
+ if (!response.ok) {
999
+ const message = body?.error?.message || body?.message || text || `HTTP ${response.status}`;
1000
+ const apiError = new Error(formatDeploymentFailure(message, body?.error?.details));
1001
+ apiError.code = body?.error?.code || 'http_error';
1002
+ apiError.status = response.status;
1003
+ if (body?.error?.details !== undefined) apiError.details = body.error.details;
1004
+ throw apiError;
1005
+ }
1006
+
1007
+ if (options.includeHeaders) {
1008
+ return { body, headers: response.headers };
1009
+ }
1010
+
1011
+ return body;
1012
+ }
1013
+
1014
+ function isDeploymentRequest(apiPath) {
1015
+ return /\/deploy(?:ments)?(?:[/?]|$)|\/checkpoints\/[^/]+\/deploy(?:[/?]|$)/.test(apiPath);
1016
+ }
1017
+
1018
+ function isDeploymentMutation(apiPath, method) {
1019
+ return method === 'POST' && (/\/deploy(?:[/?]|$)/.test(apiPath) || /\/rollback(?:[/?]|$)/.test(apiPath));
1020
+ }
1021
+
1022
+ function browserConnectInstructions() {
1023
+ return {
1024
+ status: 'browser_connection_required',
1025
+ connect_url: 'https://joripspace.com/connect/',
1026
+ message:
1027
+ '이메일 주소는 필요 없습니다. 브라우저에서 JoripSpace에 로그인한 뒤 연결을 승인하고 5분 일회용 연결 코드를 복사하세요.',
1028
+ save_command: 'joripspace login --code "복사한_연결_코드"',
1029
+ };
1030
+ }
1031
+
1032
+ function printBrowserConnectInstructions(value) {
1033
+ console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1034
+ console.log('이메일 주소 입력이나 메일 확인은 필요 없습니다.');
1035
+ console.log(`연결 페이지: ${value.connect_url}`);
1036
+ console.log('승인 후 화면에 표시되는 5분 일회용 연결 코드를 아래 명령으로 교환하세요.');
1037
+ console.log(value.save_command);
1038
+ }
1039
+
1040
+ function normalizeConnectToken(value) {
1041
+ const token = String(value || '').trim();
1042
+ if (!token) {
1043
+ throw new Error('connect token is required');
1044
+ }
1045
+ if (
1046
+ token.startsWith(SESSION_COOKIE_PREFIX) ||
1047
+ /^bearer\s+/i.test(token) ||
1048
+ ['dummy', 'test', 'token', 'undefined', 'null'].includes(token.toLowerCase())
1049
+ ) {
1050
+ throw new Error(
1051
+ '브라우저 쿠키, Bearer 문자열, 빈 자리표시자, 테스트 값은 CLI 연결 토큰으로 사용할 수 없습니다. /connect/에서 새 연결 토큰을 발급하세요.'
1052
+ );
1053
+ }
1054
+ return token;
1055
+ }
1056
+
1057
+ function normalizeConnectionCode(value) {
1058
+ const normalized = String(value || '')
1059
+ .replace(/[\s-]+/g, '')
1060
+ .toUpperCase();
1061
+ if (!/^[0-9A-HJKMNP-TV-Z]{16}$/.test(normalized)) {
1062
+ throw new Error('연결 코드는 화면에 표시된 16자리 영숫자 값이어야 합니다.');
1063
+ }
1064
+ return normalized.match(/.{1,4}/g).join('-');
1065
+ }
1066
+
1067
+ function parseArgs(argv) {
1068
+ const flags = {};
1069
+ const positional = [];
1070
+
1071
+ for (let index = 0; index < argv.length; index += 1) {
1072
+ const arg = argv[index];
1073
+ if (arg === '--') {
1074
+ positional.push(...argv.slice(index + 1));
1075
+ break;
1076
+ }
1077
+
1078
+ if (arg.startsWith('--')) {
1079
+ const [rawKey, inlineValue] = arg.slice(2).split('=', 2);
1080
+ const key = rawKey.trim();
1081
+ const next = argv[index + 1];
1082
+ const value =
1083
+ inlineValue !== undefined ? inlineValue : next && !next.startsWith('-') ? argv[++index] : true;
1084
+ addFlag(flags, key, value);
1085
+ continue;
1086
+ }
1087
+
1088
+ if (arg.startsWith('-') && arg.length === 2) {
1089
+ addFlag(flags, arg.slice(1), true);
1090
+ continue;
1091
+ }
1092
+
1093
+ positional.push(arg);
1094
+ }
1095
+
1096
+ return {
1097
+ command: positional[0],
1098
+ rest: positional.slice(1),
1099
+ flags,
1100
+ };
1101
+ }
1102
+
1103
+ function addFlag(flags, key, value) {
1104
+ if (flags[key] === undefined) {
1105
+ flags[key] = value;
1106
+ return;
1107
+ }
1108
+
1109
+ if (Array.isArray(flags[key])) {
1110
+ flags[key].push(value);
1111
+ return;
1112
+ }
1113
+
1114
+ flags[key] = [flags[key], value];
1115
+ }
1116
+
1117
+ function output(flags, body, humanPrinter) {
1118
+ if (flags.json) {
1119
+ console.log(JSON.stringify(body, null, 2));
1120
+ return;
1121
+ }
1122
+
1123
+ humanPrinter(body);
1124
+ }
1125
+
1126
+ function requireProjectId(flags) {
1127
+ const explicit = stringFlag(flags, 'project') || stringFlag(flags, 'project-id');
1128
+ const linked = readLinkedProjectId(flags);
1129
+ if (explicit && linked && explicit !== linked) {
1130
+ throw new Error(`project ${explicit} conflicts with linked project ${linked}`);
1131
+ }
1132
+ const value = explicit || linked;
1133
+ if (!value) {
1134
+ throw new Error('missing project slug. Pass --project or run joripspace start PROJECT --cwd PATH');
1135
+ }
1136
+ return value;
1137
+ }
1138
+
1139
+ function sqlFromFlags(flags, commandName) {
1140
+ const inline = stringFlag(flags, 'sql');
1141
+ const filePath = stringFlag(flags, 'file');
1142
+ if (inline) {
1143
+ return inline;
1144
+ }
1145
+ if (filePath) {
1146
+ return fs.readFileSync(path.resolve(filePath), 'utf8');
1147
+ }
1148
+ throw new Error(`db ${commandName} requires --sql or --file`);
1149
+ }
1150
+
1151
+ function requireStorageKey(flags) {
1152
+ const key = stringFlag(flags, 'key');
1153
+ if (!key) {
1154
+ throw new Error('storage command requires --key');
1155
+ }
1156
+ if (key.startsWith('/') || key.includes('../') || key.includes('..\\')) {
1157
+ throw new Error('storage key must be a project-relative object key');
1158
+ }
1159
+ return key;
1160
+ }
1161
+
1162
+ function contentTypeForPath(filePath) {
1163
+ const ext = path.extname(filePath).toLowerCase();
1164
+ if (ext === '.html') return 'text/html; charset=utf-8';
1165
+ if (ext === '.css') return 'text/css; charset=utf-8';
1166
+ if (ext === '.js' || ext === '.mjs') return 'application/javascript; charset=utf-8';
1167
+ if (ext === '.json') return 'application/json; charset=utf-8';
1168
+ if (ext === '.svg') return 'image/svg+xml';
1169
+ if (ext === '.png') return 'image/png';
1170
+ if (ext === '.jpg' || ext === '.jpeg') return 'image/jpeg';
1171
+ if (ext === '.webp') return 'image/webp';
1172
+ if (ext === '.gif') return 'image/gif';
1173
+ if (ext === '.pdf') return 'application/pdf';
1174
+ return 'application/octet-stream';
1175
+ }
1176
+
1177
+ function requireAccountId(flags) {
1178
+ const projectEnv = readProjectEnv(projectWorkspaceDir(flags));
1179
+ const value =
1180
+ stringFlag(flags, 'account') ||
1181
+ stringFlag(flags, 'account-id') ||
1182
+ process.env.JORIPSPACE_ACCOUNT_ID ||
1183
+ projectEnv.JORIPSPACE_ACCOUNT_ID ||
1184
+ readGlobalSession(flags)?.account?.account_id;
1185
+ if (!value) {
1186
+ throw new Error('missing account id. Run joripspace login or pass --account');
1187
+ }
1188
+ return value;
1189
+ }
1190
+
1191
+ function projectAuth(flags) {
1192
+ const connection = resolveConnection(flags);
1193
+ return {
1194
+ apiToken: requireApiToken(flags, connection),
1195
+ apiBaseUrl: connection.apiBaseUrl,
1196
+ };
1197
+ }
1198
+
1199
+ function optionalApiToken(flags) {
1200
+ const token = resolveConnection(flags).apiToken;
1201
+ return token ? normalizeConnectToken(token) : '';
1202
+ }
1203
+
1204
+ function apiBaseUrl(flags) {
1205
+ return resolveConnection(flags).apiBaseUrl;
1206
+ }
1207
+
1208
+ function resolveConnection(flags) {
1209
+ const explicitToken = stringFlag(flags, 'token') || stringFlag(flags, 'api-token');
1210
+ if (explicitToken) return connectionForExplicitToken(flags, explicitToken);
1211
+
1212
+ const environmentToken = process.env.JORIPSPACE_API_TOKEN || process.env.JORIPSPACE_CONNECT_TOKEN || '';
1213
+ if (environmentToken) {
1214
+ return {
1215
+ apiToken: environmentToken,
1216
+ apiBaseUrl: trimTrailingSlash(
1217
+ process.env.JORIPSPACE_API_URL || process.env.JORIPSPACE_API_BASE_URL || DEFAULT_API_URL
1218
+ ),
1219
+ source: 'process-environment',
1220
+ };
1221
+ }
1222
+
1223
+ const workspaceDir = projectWorkspaceDir(flags);
1224
+ const projectEnv = readProjectEnv(workspaceDir);
1225
+ if (projectEnv.JORIPSPACE_API_TOKEN) {
1226
+ return {
1227
+ apiToken: projectEnv.JORIPSPACE_API_TOKEN,
1228
+ apiBaseUrl: trimTrailingSlash(projectEnv.JORIPSPACE_API_BASE_URL || DEFAULT_API_URL),
1229
+ source: 'project-env',
1230
+ workspaceDir,
1231
+ };
1232
+ }
1233
+
1234
+ const legacyProjectConnection = readLegacyProjectSessionConnection(workspaceDir);
1235
+ if (legacyProjectConnection) return legacyProjectConnection;
1236
+
1237
+ const legacy = readGlobalSession(flags);
1238
+ const legacyToken = legacy?.api_token || legacy?.connect_token;
1239
+ if (legacyToken) {
1240
+ return {
1241
+ apiToken: legacyToken,
1242
+ apiBaseUrl: trimTrailingSlash(legacy.api_base_url || DEFAULT_API_URL),
1243
+ source: 'legacy-global-session',
1244
+ workspaceDir,
1245
+ };
1246
+ }
1247
+
1248
+ return {
1249
+ apiToken: '',
1250
+ apiBaseUrl: trimTrailingSlash(
1251
+ stringFlag(flags, 'api-url') ||
1252
+ process.env.JORIPSPACE_API_URL ||
1253
+ process.env.JORIPSPACE_API_BASE_URL ||
1254
+ projectEnv.JORIPSPACE_API_BASE_URL ||
1255
+ DEFAULT_API_URL
1256
+ ),
1257
+ source: 'none',
1258
+ workspaceDir,
1259
+ };
1260
+ }
1261
+
1262
+ function connectionForExplicitToken(flags, apiToken) {
1263
+ return {
1264
+ apiToken,
1265
+ apiBaseUrl: trimTrailingSlash(stringFlag(flags, 'api-url') || DEFAULT_API_URL),
1266
+ source: 'explicit-flag',
1267
+ };
1268
+ }
1269
+
1270
+ function unauthenticatedApiBaseUrl(flags) {
1271
+ return trimTrailingSlash(
1272
+ stringFlag(flags, 'api-url') ||
1273
+ process.env.JORIPSPACE_API_URL ||
1274
+ process.env.JORIPSPACE_API_BASE_URL ||
1275
+ DEFAULT_API_URL
1276
+ );
1277
+ }
1278
+
1279
+ function globalSessionPath(flags) {
1280
+ return path.join(os.homedir(), '.joripspace', 'session.json');
1281
+ }
1282
+
1283
+ function readGlobalSession(flags) {
1284
+ const filePath = globalSessionPath(flags);
1285
+ const value = readJsonFile(filePath);
1286
+ return value ? { ...value, path: filePath } : null;
1287
+ }
1288
+
1289
+ function scrubGlobalSessionToken() {
1290
+ const filePath = globalSessionPath({});
1291
+ const session = readJsonFile(filePath);
1292
+ if (
1293
+ !session ||
1294
+ (!Object.prototype.hasOwnProperty.call(session, 'api_token') &&
1295
+ !Object.prototype.hasOwnProperty.call(session, 'connect_token'))
1296
+ ) {
1297
+ return false;
1298
+ }
1299
+ const next = { ...session };
1300
+ delete next.api_token;
1301
+ delete next.connect_token;
1302
+ next.migrated_at = new Date().toISOString();
1303
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1304
+ writeJsonFile(filePath, next, 0o600);
1305
+ return true;
1306
+ }
1307
+
1308
+ function persistStartConnection(flags, connection) {
1309
+ if (
1310
+ !['legacy-global-session', 'legacy-project-session'].includes(connection?.source) ||
1311
+ !connection.apiToken
1312
+ ) {
1313
+ return false;
1314
+ }
1315
+ const workspaceDir = path.resolve(stringFlag(flags, 'cwd') || projectWorkspaceDir(flags));
1316
+ ensureProjectEnvIgnored(workspaceDir);
1317
+ updateDotEnvFile(path.join(workspaceDir, '.env.joripspace'), {
1318
+ JORIPSPACE_API_BASE_URL: connection.apiBaseUrl,
1319
+ JORIPSPACE_API_TOKEN: connection.apiToken,
1320
+ JORIPSPACE_ACCOUNT_ID: connection.accountId,
1321
+ JORIPSPACE_CONNECTION_SOURCE: `${connection.source}-migration`,
1322
+ });
1323
+ if (connection.source === 'legacy-global-session') scrubGlobalSessionToken();
1324
+ return true;
1325
+ }
1326
+
1327
+ function readLegacyProjectSessionConnection(workspaceDir) {
1328
+ const managedDirectory = canonicalWorkspaceEntry(workspaceDir, '.joripspace');
1329
+ if (!managedDirectory) return null;
1330
+ const sessionName = canonicalWorkspaceEntry(
1331
+ path.join(workspaceDir, managedDirectory),
1332
+ 'agent-session.json'
1333
+ );
1334
+ if (!sessionName) return null;
1335
+ const sessionPath = managedProjectFilePath(workspaceDir, '.joripspace/agent-session.json');
1336
+ let session;
1337
+ try {
1338
+ session = JSON.parse(fs.readFileSync(sessionPath, 'utf8'));
1339
+ } catch {
1340
+ const error = new Error('legacy .joripspace/agent-session.json is not valid JSON');
1341
+ error.code = 'legacy_workspace_migration_blocked';
1342
+ throw error;
1343
+ }
1344
+ const connection = legacyCredentialSessionConnection(session);
1345
+ if (!connection) return null;
1346
+ return {
1347
+ apiToken: connection.apiToken,
1348
+ apiBaseUrl: connection.apiBaseUrl,
1349
+ accountId: connection.accountId,
1350
+ source: 'legacy-project-session',
1351
+ workspaceDir,
1352
+ };
1353
+ }
1354
+
1355
+ function canonicalWorkspaceEntry(directory, expected) {
1356
+ let entries;
1357
+ try {
1358
+ entries = fs.readdirSync(directory);
1359
+ } catch (error) {
1360
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return '';
1361
+ throw error;
1362
+ }
1363
+ const matches = entries.filter((entry) => entry.toLowerCase() === expected.toLowerCase());
1364
+ if (!matches.length) return '';
1365
+ if (matches.length !== 1 || matches[0] !== expected) {
1366
+ const error = new Error(`legacy workspace path must use canonical casing: ${expected}`);
1367
+ error.code = 'non_canonical_workspace_path';
1368
+ throw error;
1369
+ }
1370
+ return matches[0];
1371
+ }
1372
+
1373
+ async function connectForStart(flags, context) {
1374
+ let connectionCode = stringFlag(flags, 'code');
1375
+ const interactive = !flags.json && Boolean(process.stdin.isTTY && process.stdout.isTTY);
1376
+ if (!connectionCode && !interactive) return resolveConnection(flags);
1377
+
1378
+ if (!connectionCode) {
1379
+ const instructions = browserConnectInstructions();
1380
+ console.log('브라우저에서 JoripSpace 연결을 승인하세요.');
1381
+ console.log(`연결 페이지: ${instructions.connect_url}`);
1382
+ console.log('승인 후 표시된 5분 일회용 연결 코드를 이 터미널에 붙여 넣으세요.');
1383
+ openExternalUrl(instructions.connect_url);
1384
+ const prompt = readline.createInterface({ input: process.stdin, output: process.stdout });
1385
+ try {
1386
+ connectionCode = await prompt.question('연결 코드: ');
1387
+ } finally {
1388
+ prompt.close();
1389
+ }
1390
+ }
1391
+
1392
+ const exchangeApiBaseUrl = unauthenticatedApiBaseUrl(flags);
1393
+ ensureProjectEnvIgnored(context.cwd);
1394
+ const exchange = await apiRequest(flags, '/v1/auth/connection-code/exchange', {
1395
+ method: 'POST',
1396
+ body: { code: normalizeConnectionCode(connectionCode) },
1397
+ apiBaseUrl: exchangeApiBaseUrl,
1398
+ });
1399
+ const exchangedToken = normalizeConnectToken(exchange.connect_token);
1400
+ await saveBrowserConnectTokenWithOptions(
1401
+ { ...flags, cwd: context.cwd },
1402
+ exchangedToken,
1403
+ 'connection-code',
1404
+ exchangeApiBaseUrl,
1405
+ { output: false }
1406
+ );
1407
+ return resolveConnection({ ...flags, cwd: context.cwd });
1408
+ }
1409
+
1410
+ function openExternalUrl(url) {
1411
+ const command =
1412
+ process.platform === 'win32'
1413
+ ? { file: 'cmd.exe', args: ['/d', '/c', 'start', '', url] }
1414
+ : process.platform === 'darwin'
1415
+ ? { file: 'open', args: [url] }
1416
+ : { file: 'xdg-open', args: [url] };
1417
+ try {
1418
+ const child = spawn(command.file, command.args, {
1419
+ detached: true,
1420
+ stdio: 'ignore',
1421
+ windowsHide: true,
1422
+ });
1423
+ child.once('error', () => {});
1424
+ child.unref();
1425
+ return true;
1426
+ } catch {
1427
+ return false;
1428
+ }
1429
+ }
1430
+
1431
+ function projectWorkspaceDir(flags, options = {}) {
1432
+ const start = path.resolve(stringFlag(flags, 'cwd') || process.cwd());
1433
+ if (options.discover === false) return start;
1434
+ let current = start;
1435
+ for (;;) {
1436
+ if (
1437
+ fs.existsSync(path.join(current, '.env.joripspace')) ||
1438
+ fs.existsSync(path.join(current, '.joripspace', 'project.json')) ||
1439
+ fs.existsSync(path.join(current, '.joripspace', 'project'))
1440
+ ) {
1441
+ return current;
1442
+ }
1443
+ const parent = path.dirname(current);
1444
+ if (parent === current) return start;
1445
+ current = parent;
1446
+ }
1447
+ }
1448
+
1449
+ function readLinkedProjectId(flags) {
1450
+ const workspaceDir = projectWorkspaceDir(flags);
1451
+ const markerPath = managedProjectFilePath(workspaceDir, '.joripspace/project');
1452
+ if (fs.existsSync(markerPath)) return readProjectMarker(workspaceDir);
1453
+ return '';
1454
+ }
1455
+
1456
+ function readJsonFile(filePath) {
1457
+ try {
1458
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
1459
+ } catch {
1460
+ return null;
1461
+ }
1462
+ }
1463
+
1464
+ function writeJsonFile(filePath, value, mode) {
1465
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1466
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
1467
+ fs.writeFileSync(temporaryPath, `${JSON.stringify(value, null, 2)}\n`, {
1468
+ encoding: 'utf8',
1469
+ ...(mode ? { mode } : {}),
1470
+ });
1471
+ replaceFileAtomically(temporaryPath, filePath);
1472
+ if (mode && process.platform !== 'win32') fs.chmodSync(filePath, mode);
1473
+ }
1474
+
1475
+ function writeTextAtomically(filePath, value) {
1476
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1477
+ const temporaryPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
1478
+ fs.writeFileSync(temporaryPath, value, 'utf8');
1479
+ replaceFileAtomically(temporaryPath, filePath);
1480
+ }
1481
+
1482
+ function managedProjectFilePath(workspaceDir, relative) {
1483
+ const location = resolveProjectFileTarget(workspaceDir, relative);
1484
+ if (location.blockers.length) {
1485
+ throw new Error(`managed project file path is blocked: ${location.blockers.join(', ')}`);
1486
+ }
1487
+ return location.target;
1488
+ }
1489
+
1490
+ function assertSafeManagedWorkspace(workspaceDir) {
1491
+ resolveProjectDirectoryTarget(workspaceDir, '.joripspace');
1492
+ for (const relative of [
1493
+ '.env.joripspace',
1494
+ '.gitignore',
1495
+ 'AGENTS.md',
1496
+ 'CLAUDE.md',
1497
+ 'package.json',
1498
+ '.joripspace/project',
1499
+ '.joripspace/project.json',
1500
+ '.joripspace/agent-session.json',
1501
+ '.joripspace/doctor.mjs',
1502
+ '.joripspace/deploy.mjs',
1503
+ '.joripspace/install-template.mjs',
1504
+ '.joripspace/pull.mjs',
1505
+ '.joripspace/checkpoint-client.mjs',
1506
+ '.joripspace/save.mjs',
1507
+ '.joripspace/checkpoints.mjs',
1508
+ '.joripspace/restore.mjs',
1509
+ '.joripspace/deploy-checkpoint.mjs',
1510
+ '.joripspace/github-actions-template.yml',
1511
+ ]) {
1512
+ managedProjectFilePath(workspaceDir, relative);
1513
+ }
1514
+ }
1515
+
1516
+ function replaceFileAtomically(temporaryPath, filePath) {
1517
+ try {
1518
+ fs.renameSync(temporaryPath, filePath);
1519
+ return;
1520
+ } catch (error) {
1521
+ const backupPath = `${filePath}.bak-${process.pid}-${Date.now()}`;
1522
+ try {
1523
+ if (fs.existsSync(filePath)) fs.renameSync(filePath, backupPath);
1524
+ fs.renameSync(temporaryPath, filePath);
1525
+ fs.rmSync(backupPath, { force: true });
1526
+ } catch {
1527
+ try {
1528
+ if (fs.existsSync(backupPath) && !fs.existsSync(filePath)) fs.renameSync(backupPath, filePath);
1529
+ } catch {}
1530
+ fs.rmSync(temporaryPath, { force: true });
1531
+ throw error;
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ function requireApiToken(flags, connection) {
1537
+ const value = connection?.apiToken ? normalizeConnectToken(connection.apiToken) : optionalApiToken(flags);
1538
+ if (!value) {
1539
+ throw new Error('missing API token. Run joripspace login, pass --token, or set JORIPSPACE_API_TOKEN');
1540
+ }
1541
+ return value;
1542
+ }
1543
+
1544
+ function stringFlag(flags, name) {
1545
+ const value = flags[name];
1546
+ if (Array.isArray(value)) {
1547
+ return String(value[value.length - 1]);
1548
+ }
1549
+ return typeof value === 'string' ? value : '';
1550
+ }
1551
+
1552
+ function booleanFlag(flags, name) {
1553
+ const value = flags[name];
1554
+ if (Array.isArray(value)) {
1555
+ return Boolean(value[value.length - 1]);
1556
+ }
1557
+ return value === true || value === 'true' || value === '1';
1558
+ }
1559
+
1560
+ function arrayFlag(flags, name) {
1561
+ const value = flags[name];
1562
+ if (value === undefined) {
1563
+ return [];
1564
+ }
1565
+ return Array.isArray(value) ? value.map(String) : [String(value)];
1566
+ }
1567
+
1568
+ function positiveIntegerFlag(flags, name) {
1569
+ const value = stringFlag(flags, name);
1570
+ if (!value) {
1571
+ return null;
1572
+ }
1573
+
1574
+ const parsed = Number(value);
1575
+ if (!Number.isInteger(parsed) || parsed < 1) {
1576
+ throw new Error(`--${name} must be a positive integer`);
1577
+ }
1578
+ return parsed;
1579
+ }
1580
+
1581
+ function usageRangeQuery(flags) {
1582
+ const params = new URLSearchParams(usageRangeParams(flags));
1583
+ return params.toString() ? `?${params.toString()}` : '';
1584
+ }
1585
+
1586
+ function usageRangeParams(flags) {
1587
+ const params = {};
1588
+ const from = stringFlag(flags, 'from');
1589
+ const to = stringFlag(flags, 'to');
1590
+ if (from) {
1591
+ params.from = from;
1592
+ }
1593
+ if (to) {
1594
+ params.to = to;
1595
+ }
1596
+ return params;
1597
+ }
1598
+
1599
+ function splitFileMapping(value) {
1600
+ const separator = value.indexOf('=');
1601
+ if (separator <= 0 || separator === value.length - 1) {
1602
+ throw new Error('--file must use name=path');
1603
+ }
1604
+
1605
+ return [value.slice(0, separator), value.slice(separator + 1)];
1606
+ }
1607
+
1608
+ function templateVars(flags) {
1609
+ const vars = {};
1610
+ for (const item of arrayFlag(flags, 'var')) {
1611
+ const [name, value] = splitFileMapping(item);
1612
+ vars[name] = value;
1613
+ }
1614
+ return vars;
1615
+ }
1616
+
1617
+ function parseJson(text) {
1618
+ try {
1619
+ return JSON.parse(text);
1620
+ } catch {
1621
+ return { raw: text };
1622
+ }
1623
+ }
1624
+
1625
+ function trimTrailingSlash(value) {
1626
+ return value.replace(/\/+$/, '');
1627
+ }