anhedral 0.16.0 → 0.18.0

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.
Files changed (195) hide show
  1. package/README.md +42 -20
  2. package/assets/contracts/LICENSE +201 -0
  3. package/assets/contracts/LICENSE.environment +201 -0
  4. package/assets/contracts/LICENSE.operations +201 -0
  5. package/assets/contracts/deployment-provenance.json +15 -0
  6. package/assets/contracts/environment-provenance.json +11 -0
  7. package/assets/contracts/operations-provenance.json +11 -0
  8. package/assets/launch/application.server.ts.txt +13 -0
  9. package/assets/launch/auth-client.ts.txt +4 -0
  10. package/assets/launch/home.tsx.txt +20 -0
  11. package/assets/launch/minimal-application.server.ts.txt +5 -0
  12. package/assets/launch/minimal-server.ts.txt +7 -0
  13. package/assets/launch/request-context.ts.txt +3 -0
  14. package/assets/launch/root.tsx.txt +27 -0
  15. package/assets/launch/router.tsx.txt +21 -0
  16. package/assets/launch/server.ts.txt +13 -0
  17. package/assets/launch/sign-in.tsx.txt +53 -0
  18. package/assets/launch/styles.css.txt +19 -0
  19. package/assets/security/credential-patterns.d.mts +3 -0
  20. package/assets/security/credential-patterns.mjs +59 -0
  21. package/assets/stack/api-index.ts.txt +6 -1
  22. package/assets/stack/event-retention.sql.txt +10 -0
  23. package/assets/stack/stripe.ts.txt +30 -13
  24. package/assets/ui/UPSTREAM.json +1 -18
  25. package/dist/bin.js +55 -36
  26. package/dist/capabilities.d.ts +1 -1
  27. package/dist/capability-catalog.d.ts +44 -11
  28. package/dist/capability-catalog.js +96 -11
  29. package/dist/capability-command.d.ts +2 -2
  30. package/dist/capability-command.js +178 -27
  31. package/dist/capability-editor.js +6 -5
  32. package/dist/capability-recipes.js +54 -6
  33. package/dist/cli-arguments.d.ts +2 -0
  34. package/dist/cli-arguments.js +101 -50
  35. package/dist/cli-commands.d.ts +1 -1
  36. package/dist/cli-commands.js +30 -6
  37. package/dist/cli-errors.d.ts +18 -0
  38. package/dist/cli-errors.js +63 -0
  39. package/dist/cli-output.d.ts +22 -0
  40. package/dist/cli-output.js +42 -7
  41. package/dist/command-runner.d.ts +1 -0
  42. package/dist/command-runner.js +88 -0
  43. package/dist/command-schema.d.ts +16 -0
  44. package/dist/command-schema.js +390 -21
  45. package/dist/completion.d.ts +2 -0
  46. package/dist/completion.js +201 -0
  47. package/dist/composition.d.ts +35 -0
  48. package/dist/composition.js +28 -0
  49. package/dist/contracts/cli-transport.d.ts +217 -0
  50. package/dist/contracts/cli-transport.js +167 -0
  51. package/dist/contracts/deployment.d.ts +282 -0
  52. package/dist/contracts/deployment.js +234 -0
  53. package/dist/contracts/environment-file.d.ts +7 -0
  54. package/dist/contracts/environment-file.js +112 -0
  55. package/dist/contracts/environment-transport.d.ts +79 -0
  56. package/dist/contracts/environment-transport.js +110 -0
  57. package/dist/contracts/runtime-logs-transport.d.ts +127 -0
  58. package/dist/contracts/runtime-logs-transport.js +50 -0
  59. package/dist/contracts/source-bundle.d.ts +11 -0
  60. package/dist/contracts/source-bundle.js +197 -0
  61. package/dist/contracts/source-profile.d.ts +4 -0
  62. package/dist/contracts/source-profile.js +5 -0
  63. package/dist/contracts/staging-transport.d.ts +79 -0
  64. package/dist/contracts/staging-transport.js +43 -0
  65. package/dist/dependencies.d.ts +10 -4
  66. package/dist/dependencies.js +17 -54
  67. package/dist/index.d.ts +6 -0
  68. package/dist/index.js +4 -0
  69. package/dist/launch.d.ts +21 -0
  70. package/dist/launch.js +250 -0
  71. package/dist/platform-command.d.ts +9 -0
  72. package/dist/platform-command.js +584 -0
  73. package/dist/platform-environment.d.ts +18 -0
  74. package/dist/platform-environment.js +257 -0
  75. package/dist/platform-operations.d.ts +26 -0
  76. package/dist/platform-operations.js +155 -0
  77. package/dist/platform-source.d.ts +8 -0
  78. package/dist/platform-source.js +111 -0
  79. package/dist/platform-state.d.ts +13 -0
  80. package/dist/platform-state.js +207 -0
  81. package/dist/platforms/tanstack.d.ts +8 -0
  82. package/dist/platforms/tanstack.js +155 -0
  83. package/dist/registry/options.js +34 -31
  84. package/dist/registry/resolve.js +2 -0
  85. package/dist/registry/usage.d.ts +4 -1
  86. package/dist/registry/usage.js +58 -4
  87. package/dist/scaffold/documentation.js +17 -48
  88. package/dist/scaffold/styling.d.ts +1 -1
  89. package/dist/scaffold/workspace.js +11 -7
  90. package/dist/stack-registry.d.ts +2 -4
  91. package/dist/stack-registry.js +1 -11
  92. package/dist/standard.js +21 -6
  93. package/dist/transaction.js +28 -3
  94. package/dist/ui-command.d.ts +4 -2
  95. package/dist/ui-command.js +79 -38
  96. package/dist/ui-project.d.ts +2 -0
  97. package/dist/ui-project.js +38 -8
  98. package/dist/util.js +40 -61
  99. package/dist/version.d.ts +1 -1
  100. package/dist/version.js +1 -1
  101. package/docs/capabilities.md +22 -88
  102. package/docs/software-factory.md +189 -16
  103. package/docs/stack-standard.md +6 -18
  104. package/docs/ui.md +9 -22
  105. package/docs/verification.md +6 -1067
  106. package/package.json +33 -22
  107. package/assets/ui/native/_controls.tsx +0 -521
  108. package/assets/ui/native/_core.tsx +0 -118
  109. package/assets/ui/native/_data.tsx +0 -200
  110. package/assets/ui/native/_display.tsx +0 -453
  111. package/assets/ui/native/_feedback.tsx +0 -242
  112. package/assets/ui/native/_legacy-dialog.tsx +0 -38
  113. package/assets/ui/native/_motion.tsx +0 -520
  114. package/assets/ui/native/_overlay.tsx +0 -402
  115. package/assets/ui/native/_selection.tsx +0 -366
  116. package/assets/ui/native/accordion.tsx +0 -1
  117. package/assets/ui/native/alert-dialog.tsx +0 -11
  118. package/assets/ui/native/alert.tsx +0 -1
  119. package/assets/ui/native/aspect-ratio.tsx +0 -1
  120. package/assets/ui/native/attachment.tsx +0 -8
  121. package/assets/ui/native/avatar.tsx +0 -8
  122. package/assets/ui/native/badge.tsx +0 -1
  123. package/assets/ui/native/breadcrumb.tsx +0 -9
  124. package/assets/ui/native/bubble.tsx +0 -1
  125. package/assets/ui/native/button-group.tsx +0 -1
  126. package/assets/ui/native/button.tsx +0 -86
  127. package/assets/ui/native/calendar.tsx +0 -170
  128. package/assets/ui/native/card.tsx +0 -44
  129. package/assets/ui/native/carousel.tsx +0 -1
  130. package/assets/ui/native/chart.tsx +0 -193
  131. package/assets/ui/native/checkbox.tsx +0 -1
  132. package/assets/ui/native/code-block.tsx +0 -137
  133. package/assets/ui/native/collapsible.tsx +0 -1
  134. package/assets/ui/native/combobox.tsx +0 -1
  135. package/assets/ui/native/command.tsx +0 -11
  136. package/assets/ui/native/context-menu.tsx +0 -16
  137. package/assets/ui/native/data-table.tsx +0 -1
  138. package/assets/ui/native/date-picker.tsx +0 -43
  139. package/assets/ui/native/dialog.tsx +0 -15
  140. package/assets/ui/native/direction.tsx +0 -1
  141. package/assets/ui/native/drawer.tsx +0 -10
  142. package/assets/ui/native/dropdown-menu.tsx +0 -16
  143. package/assets/ui/native/empty.tsx +0 -8
  144. package/assets/ui/native/field.tsx +0 -13
  145. package/assets/ui/native/hover-card.tsx +0 -1
  146. package/assets/ui/native/input-group.tsx +0 -8
  147. package/assets/ui/native/input-otp.tsx +0 -1
  148. package/assets/ui/native/input.tsx +0 -28
  149. package/assets/ui/native/item.tsx +0 -12
  150. package/assets/ui/native/kbd.tsx +0 -1
  151. package/assets/ui/native/label.tsx +0 -4
  152. package/assets/ui/native/layout.tsx +0 -26
  153. package/assets/ui/native/marker.tsx +0 -1
  154. package/assets/ui/native/menubar.tsx +0 -17
  155. package/assets/ui/native/message-scroller.tsx +0 -6
  156. package/assets/ui/native/message.tsx +0 -10
  157. package/assets/ui/native/native-select.tsx +0 -1
  158. package/assets/ui/native/navigation-menu.tsx +0 -10
  159. package/assets/ui/native/pagination.tsx +0 -9
  160. package/assets/ui/native/popover.tsx +0 -1
  161. package/assets/ui/native/progress.tsx +0 -1
  162. package/assets/ui/native/questionnaire.tsx +0 -130
  163. package/assets/ui/native/radio-group.tsx +0 -1
  164. package/assets/ui/native/registry.json +0 -1103
  165. package/assets/ui/native/resizable.tsx +0 -1
  166. package/assets/ui/native/scroll-area.tsx +0 -1
  167. package/assets/ui/native/select.tsx +0 -11
  168. package/assets/ui/native/separator.tsx +0 -1
  169. package/assets/ui/native/sheet.tsx +0 -10
  170. package/assets/ui/native/sidebar.tsx +0 -22
  171. package/assets/ui/native/skeleton.tsx +0 -1
  172. package/assets/ui/native/slider.tsx +0 -1
  173. package/assets/ui/native/spinner.tsx +0 -1
  174. package/assets/ui/native/switch.tsx +0 -1
  175. package/assets/ui/native/table.tsx +0 -10
  176. package/assets/ui/native/tabs.tsx +0 -1
  177. package/assets/ui/native/text.tsx +0 -20
  178. package/assets/ui/native/textarea.tsx +0 -1
  179. package/assets/ui/native/theme-switcher.tsx +0 -22
  180. package/assets/ui/native/toast.tsx +0 -11
  181. package/assets/ui/native/toggle-group.tsx +0 -1
  182. package/assets/ui/native/toggle.tsx +0 -1
  183. package/assets/ui/native/tooltip.tsx +0 -1
  184. package/assets/ui/native/trace.tsx +0 -20
  185. package/assets/ui/native/typography.tsx +0 -15
  186. package/assets/ui/theme-storage.ts +0 -25
  187. package/assets/ui/theme.tsx +0 -66
  188. package/dist/platforms/mobile.d.ts +0 -2
  189. package/dist/platforms/mobile.js +0 -137
  190. package/dist/scaffold/expo-runtime.d.ts +0 -3
  191. package/dist/scaffold/expo-runtime.js +0 -42
  192. package/dist/scaffold/native-ui.d.ts +0 -2
  193. package/dist/scaffold/native-ui.js +0 -74
  194. package/docs/anhedral-stack.md +0 -7
  195. package/docs/native-ui.md +0 -102
@@ -0,0 +1,584 @@
1
+ import { runEnvironmentCommand, validateEnvironmentArguments } from './platform-environment.js';
2
+ import { runStagingCommand, runLogsCommand, validateStagingArguments, validateLogsArguments, } from './platform-operations.js';
3
+ import { constants } from 'node:fs';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { join, resolve } from 'node:path';
6
+ import { unlink } from 'node:fs/promises';
7
+ import { z } from 'zod';
8
+ import { CliArgumentError, commandArguments, commandArgumentError } from './cli-arguments.js';
9
+ import { CliFailure } from './cli-errors.js';
10
+ import { stripVTControlCharacters } from 'node:util';
11
+ import { createReporter } from './cli-output.js';
12
+ import { canonicalCliJson, cliPlanInputSchema, cliPlanSchema, cliPreparationSchema, cliDeviceSchema, cliLinkSchema, cliLoginSchema, SOURCE_LIMITS, sourceUploadInputSchema, sourceUploadReceiptSchema, } from './contracts/cli-transport.js';
13
+ import { readSourceBounded } from './contracts/source-bundle.js';
14
+ import { deploymentManifestSchema } from './contracts/deployment.js';
15
+ import { packageSource } from './platform-source.js';
16
+ import { platformFailure as createPlatformFailure, platformOrigin, readPrivate, secretStore, writePrivate, } from './platform-state.js';
17
+ const credential = cliLoginSchema.extend({ origin: z.string() });
18
+ const pending = z
19
+ .object({ origin: z.string(), device: cliDeviceSchema, expiresAt: z.number() })
20
+ .strict();
21
+ const linkSchema = cliLinkSchema.extend({ origin: z.string() }).strict();
22
+ const uploadState = z
23
+ .object({
24
+ origin: z.string(),
25
+ principalId: z.uuid(),
26
+ input: sourceUploadInputSchema,
27
+ uploadId: z.uuid().optional(),
28
+ })
29
+ .strict();
30
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
31
+ function visible(value) {
32
+ return stripVTControlCharacters(String(value ?? '')).replace(/[\x00-\x1f\x7f]/g, ' ');
33
+ }
34
+ function formatPlatformResult(command, result) {
35
+ const data = result;
36
+ if (data.status === 'authorization_required')
37
+ return `Approve CLI access at ${visible(data.verificationUrl)}\nConfirm code ${visible(data.userCode)}.\nNext: ${visible(data.nextAction)}`;
38
+ if (data.status === 'authenticated')
39
+ return `Signed in to ${visible(data.origin)}.\nExpires: ${visible(data.expiresAt)}.`;
40
+ if (data.status === 'logged_out')
41
+ return `Logged out of ${visible(data.origin)}.`;
42
+ if (data.status === 'unlinked')
43
+ return 'Removed the local project link.';
44
+ if (command === 'whoami') {
45
+ const context = data.context;
46
+ return [
47
+ `Signed in as ${visible(data.name)} (${visible(data.principalId)}).`,
48
+ `API origin: ${visible(data.origin)}.`,
49
+ `Expires: ${visible(data.expiresAt)}.`,
50
+ ...(context
51
+ ? [
52
+ `Credential store: ${visible(context.credential?.kind)}.`,
53
+ context.project
54
+ ? `Saved local project: ${visible(context.project.name)} (${visible(context.project.projectId)}), team ${visible(context.project.teamId)}. Project access has not been verified.`
55
+ : 'No local project link is saved.',
56
+ ]
57
+ : []),
58
+ ].join('\n');
59
+ }
60
+ if (command === 'link')
61
+ return `Linked to ${visible(data.name)} (${visible(data.projectId)}).\nTeam: ${visible(data.teamId)}.`;
62
+ if (data.status === 'dry_run')
63
+ return `Source archive preview: ${visible(data.files)} files, ${visible(data.bytes)} source bytes, ${visible(data.archiveBytes)} archive bytes.\nNo source was uploaded. Review the included paths with --json.`;
64
+ if (command === 'source')
65
+ return `Source ${visible(data.state)} (${visible(data.id)}).\nSource revision: ${visible(data.sourceRevision ?? 'not sealed')}.\nUpload does not activate a runtime or deployment.`;
66
+ if (command === 'deploy')
67
+ return [
68
+ data.state
69
+ ? `Candidate ${visible(data.state)} (${visible(data.candidateId)}).`
70
+ : `Deployment plan prepared (${visible(data.id)}).`,
71
+ `Source revision: ${visible(data.sourceRevision)}.`,
72
+ 'Server policy controls runtime admission. No preview or deployment was activated.',
73
+ ].join('\n');
74
+ return 'Platform command completed.';
75
+ }
76
+ export async function runPlatformCommand(command, args, output, dependencies = {}) {
77
+ try {
78
+ await runPlatformOperation(command, args, output, dependencies);
79
+ }
80
+ catch (error) {
81
+ if (error instanceof CliArgumentError || error instanceof CliFailure)
82
+ throw error;
83
+ if (error instanceof z.ZodError)
84
+ throw createPlatformFailure('Platform data or saved context does not match the supported protocol. Preserve saved state and verify the selected context before retrying.', `Run anhedral ${command} --help.`, 'context');
85
+ if (error instanceof SyntaxError)
86
+ throw createPlatformFailure('Selected local Platform input is not valid JSON. Preserve saved state and review the selected input before retrying.', `Run anhedral ${command} --help.`, 'context');
87
+ if (['ENOENT', 'ENOTDIR', 'EISDIR', 'EACCES', 'EPERM'].includes(error?.code ?? ''))
88
+ throw createPlatformFailure('A required local Platform file is missing or inaccessible. Review the selected working directory, manifest and credential store.', `Run anhedral ${command} --help.`, 'context');
89
+ throw error;
90
+ }
91
+ }
92
+ async function runPlatformOperation(command, args, output, dependencies) {
93
+ const reporter = createReporter(output, (result) => formatPlatformResult(command, result), true);
94
+ const platformFailure = (message, category = 'context', retryable = false, nextAction = `Run anhedral ${command} --help.`) => createPlatformFailure(message, nextAction, category, retryable);
95
+ const options = commandArguments(command, args), origin = platformOrigin(options.value('--api-url'));
96
+ if (command === 'env')
97
+ validateEnvironmentArguments(args);
98
+ if (command === 'staging')
99
+ validateStagingArguments(args);
100
+ if (command === 'logs')
101
+ validateLogsArguments(args);
102
+ const emit = (result) => reporter.result(result);
103
+ if (['login', 'logout', 'whoami', 'link', 'unlink'].includes(command) &&
104
+ options.positional.length)
105
+ throw commandArgumentError(command, 'Unexpected positional arguments.');
106
+ if (command === 'login' && options.has('--start') && options.has('--resume'))
107
+ throw commandArgumentError(command, 'Choose --start or --resume.');
108
+ if (command === 'source' &&
109
+ (options.positional.length !== 1 || !['upload', 'status'].includes(options.positional[0])))
110
+ throw commandArgumentError(command, 'Use source upload or source status.');
111
+ if (command === 'deploy' &&
112
+ (options.positional.length !== 1 ||
113
+ !['plan', 'prepare', 'status'].includes(options.positional[0])))
114
+ throw commandArgumentError(command, 'Use deploy plan, deploy prepare or deploy status.');
115
+ if (command === 'deploy' &&
116
+ options.positional[0] !== 'plan' &&
117
+ (options.has('--manifest') || options.has('--new')))
118
+ throw commandArgumentError(command, 'Manifest and --new options apply to deploy plan only.');
119
+ if (command === 'link' &&
120
+ (!z.uuid().safeParse(options.value('--project')).success ||
121
+ !z.uuid().safeParse(options.value('--team')).success))
122
+ throw commandArgumentError(command, 'Supply existing project and team UUIDs with --project and --team.');
123
+ const root = process.cwd(), stateDir = join(root, '.anhedral', 'platform'), linkPath = join(stateDir, 'project.json'), uploadPath = join(stateDir, 'upload.json');
124
+ if (command === 'unlink') {
125
+ await readPrivate(linkPath);
126
+ await unlink(linkPath).catch((e) => {
127
+ if (e.code !== 'ENOENT')
128
+ throw e;
129
+ });
130
+ emit({ status: 'unlinked' });
131
+ return;
132
+ }
133
+ if (command === 'env' && options.has('--dry-run'))
134
+ return runEnvironmentCommand(args, output);
135
+ if (command === 'source' && options.has('--dry-run')) {
136
+ if (options.positional[0] !== 'upload')
137
+ throw commandArgumentError(command, 'Use source upload --dry-run.');
138
+ const source = await packageSource(root), archiveDigest = hash(source.archive);
139
+ emit({
140
+ status: 'dry_run',
141
+ archiveDigest,
142
+ inventoryDigest: source.inventoryDigest,
143
+ files: source.files,
144
+ includedPaths: source.paths,
145
+ bytes: source.bytes,
146
+ archiveBytes: source.archive.length,
147
+ });
148
+ return;
149
+ }
150
+ const store = dependencies.store ??
151
+ secretStore(origin, options.value('--credential-file') ? resolve(options.value('--credential-file')) : undefined);
152
+ const readCredential = async () => {
153
+ try {
154
+ return await store.read();
155
+ }
156
+ catch (error) {
157
+ if (error instanceof SyntaxError)
158
+ throw platformFailure('Saved credential data is not valid JSON. Preserve it and reconcile the selected credential store.', 'auth', false, 'Run anhedral login --help.');
159
+ throw error;
160
+ }
161
+ };
162
+ const request = async (path, method, body, token, team) => {
163
+ let response;
164
+ try {
165
+ response = await (dependencies.fetch ?? fetch)(`${origin}/api/cli/v1${path}`, {
166
+ method,
167
+ redirect: 'error',
168
+ signal: AbortSignal.timeout(30000),
169
+ headers: {
170
+ 'x-anhedral-cli-protocol': '1',
171
+ ...(body instanceof Uint8Array
172
+ ? { 'content-type': 'application/octet-stream' }
173
+ : { 'content-type': 'application/json' }),
174
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
175
+ ...(team ? { 'x-anhedral-team': team } : {}),
176
+ },
177
+ body: body === undefined
178
+ ? undefined
179
+ : body instanceof Uint8Array
180
+ ? Uint8Array.from(body)
181
+ : JSON.stringify(body),
182
+ });
183
+ }
184
+ catch {
185
+ throw platformFailure('Platform request was interrupted. Retry the same command to resume.', 'network', true, `Retry anhedral ${command} with the same API origin, working directory and options to resume.`);
186
+ }
187
+ const data = await readSourceBounded(response.body, /\/projects\/[^/]+\/(environment|staging|runtime-logs)(\?|$)/.test(path)
188
+ ? 1024 * 1024
189
+ : 65536)
190
+ .then((b) => JSON.parse(new TextDecoder().decode(b)))
191
+ .catch(() => {
192
+ throw platformFailure('Platform returned an invalid response.', 'network');
193
+ });
194
+ if (!response.ok) {
195
+ if (path === '/auth/token') {
196
+ const error = z
197
+ .object({
198
+ error: z.enum([
199
+ 'authorization_pending',
200
+ 'slow_down',
201
+ 'access_denied',
202
+ 'expired_token',
203
+ 'invalid_grant',
204
+ ]),
205
+ })
206
+ .safeParse(data);
207
+ if (error.success)
208
+ return error.data;
209
+ }
210
+ throw platformFailure(response.status === 401
211
+ ? 'CLI login expired or was revoked. Run anhedral login.'
212
+ : response.status === 409
213
+ ? command === 'deploy'
214
+ ? 'Deployment plan is stale or inputs conflict. Review deploy plan --new.'
215
+ : command === 'staging'
216
+ ? 'Candidate, configuration or staging generation changed. Review staging status before starting a new deployment.'
217
+ : command === 'env'
218
+ ? 'Environment versions or import contents conflict. Review env list and preserve saved retry state before starting a new import.'
219
+ : 'Upload conflicts with saved source. Restore the original files or use source upload --new.'
220
+ : response.status === 403
221
+ ? command === 'env'
222
+ ? 'Current project environment access or administrator permission is unavailable.'
223
+ : command === 'logs'
224
+ ? 'Current project log access is unavailable.'
225
+ : 'Current project build access is unavailable.'
226
+ : `Platform request failed (${response.status}).`, response.status === 401
227
+ ? 'auth'
228
+ : response.status === 403
229
+ ? 'permission'
230
+ : response.status === 409
231
+ ? 'conflict'
232
+ : 'network', response.status === 429 || response.status >= 500, response.status === 401
233
+ ? 'Run anhedral login with the same API origin and credential store.'
234
+ : `Run anhedral ${command} --help.`);
235
+ }
236
+ return data;
237
+ };
238
+ if (command === 'login') {
239
+ if (options.positional.length)
240
+ throw commandArgumentError(command, 'Login does not accept positional arguments.');
241
+ let state = pending.safeParse(await readCredential());
242
+ if (!options.has('--resume') ||
243
+ !state.success ||
244
+ state.data.origin !== origin ||
245
+ state.data.expiresAt <= Date.now()) {
246
+ const device = cliDeviceSchema.parse(await request('/auth/code', 'POST', {}));
247
+ if (new URL(device.verification_uri_complete).origin !== origin ||
248
+ new URL(device.verification_uri_complete).protocol !== new URL(origin).protocol)
249
+ throw platformFailure('Platform returned an unexpected verification origin.');
250
+ const saved = { origin, device, expiresAt: Date.now() + device.expires_in * 1000 };
251
+ await store.write(saved);
252
+ state = pending.safeParse(saved);
253
+ }
254
+ if (!state.success)
255
+ throw platformFailure('Login state is unavailable. Start login again.');
256
+ const saved = state.data;
257
+ if (options.has('--start') || (!reporter.canPrompt && !options.has('--resume'))) {
258
+ emit({
259
+ status: 'authorization_required',
260
+ verificationUrl: saved.device.verification_uri_complete,
261
+ userCode: saved.device.user_code,
262
+ expiresAt: new Date(saved.expiresAt).toISOString(),
263
+ nextAction: 'Approve in your browser, then run anhedral login --resume with the same API origin and credential store.',
264
+ });
265
+ return;
266
+ }
267
+ reporter.diagnostic(`Approve CLI access at ${saved.device.verification_uri_complete}\nConfirm code ${saved.device.user_code}.`);
268
+ let interval = saved.device.interval * 1000;
269
+ while (Date.now() < saved.expiresAt) {
270
+ await (dependencies.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(interval);
271
+ const result = await request('/auth/token', 'POST', {
272
+ device_code: saved.device.device_code,
273
+ });
274
+ const grant = cliLoginSchema.safeParse(result);
275
+ if (grant.success) {
276
+ await store.write({ ...grant.data, origin });
277
+ emit({ status: 'authenticated', origin, expiresAt: grant.data.expiresAt });
278
+ return;
279
+ }
280
+ const error = result.error;
281
+ if (error === 'slow_down')
282
+ interval += 5000;
283
+ else if (error !== 'authorization_pending') {
284
+ await store.clear();
285
+ throw platformFailure('Device approval was denied or expired. Start login again.');
286
+ }
287
+ }
288
+ await store.clear();
289
+ throw platformFailure('Device approval expired. Start login again.');
290
+ }
291
+ const saved = credential.safeParse(await readCredential());
292
+ if (!saved.success || saved.data.origin !== origin)
293
+ throw platformFailure('Log in to the selected API origin first.', 'auth', false, 'Run anhedral login with the same API origin and credential store.');
294
+ const token = saved.data.token;
295
+ if (command === 'logout') {
296
+ await request('/auth/logout', 'POST', {}, token);
297
+ try {
298
+ await store.clear();
299
+ }
300
+ catch {
301
+ throw platformFailure('Platform access was revoked, but the saved local credential could not be removed.', 'context', false, 'Remove the saved credential from the selected credential store before signing in again.');
302
+ }
303
+ emit({ status: 'logged_out', origin });
304
+ return;
305
+ }
306
+ const actor = z
307
+ .object({
308
+ protocol: z.literal(1),
309
+ principalId: z.uuid(),
310
+ name: z.string(),
311
+ teamId: z.uuid().nullable(),
312
+ })
313
+ .parse(await request('/actor', 'GET', undefined, token));
314
+ if (command === 'whoami') {
315
+ const identity = { ...actor, origin, expiresAt: saved.data.expiresAt };
316
+ if (!options.has('--context')) {
317
+ emit(identity);
318
+ return;
319
+ }
320
+ const savedLink = await readPrivate(linkPath);
321
+ const localLink = savedLink === null ? null : linkSchema.safeParse(savedLink);
322
+ if (localLink &&
323
+ (!localLink.success ||
324
+ localLink.data.origin !== origin ||
325
+ localLink.data.principalId !== actor.principalId))
326
+ throw platformFailure('The saved project link does not match the selected API origin and signed-in identity. Preserve it and explicitly link the intended project.', 'context', false, 'Run anhedral link --help.');
327
+ const file = options.value('--credential-file');
328
+ emit({
329
+ ...identity,
330
+ context: {
331
+ apiOrigin: { value: origin, source: options.has('--api-url') ? 'flag' : 'default' },
332
+ identityVerification: 'live-platform',
333
+ credential: {
334
+ source: file ? 'flag' : dependencies.store ? 'injected' : 'os-secret-store',
335
+ kind: file
336
+ ? 'owner-only-file'
337
+ : dependencies.store
338
+ ? 'injected'
339
+ : process.platform === 'darwin'
340
+ ? 'macos-keychain'
341
+ : process.platform === 'linux'
342
+ ? 'linux-secret-service'
343
+ : 'unsupported',
344
+ },
345
+ project: localLink && localLink.success
346
+ ? {
347
+ projectId: localLink.data.projectId,
348
+ teamId: localLink.data.teamId,
349
+ name: localLink.data.name,
350
+ source: '.anhedral/platform/project.json',
351
+ verification: 'saved-local-link',
352
+ access: 'not-verified',
353
+ }
354
+ : null,
355
+ },
356
+ });
357
+ return;
358
+ }
359
+ if (command === 'link') {
360
+ const input = z
361
+ .object({ projectId: z.uuid(), teamId: z.uuid() })
362
+ .parse({ projectId: options.value('--project'), teamId: options.value('--team') });
363
+ if (options.positional.length)
364
+ throw commandArgumentError(command, 'Use --project and --team.');
365
+ const link = cliLinkSchema.parse(await request('/link', 'POST', input, token, input.teamId));
366
+ if (link.principalId !== actor.principalId ||
367
+ link.projectId !== input.projectId ||
368
+ link.teamId !== input.teamId)
369
+ throw platformFailure('Project link identity differs.');
370
+ await writePrivate(linkPath, { ...link, origin });
371
+ emit({ ...link, origin });
372
+ return;
373
+ }
374
+ if (['env', 'staging', 'logs'].includes(command)) {
375
+ const link = linkSchema.parse(await readPrivate(linkPath));
376
+ if (link.origin !== origin || link.principalId !== actor.principalId)
377
+ throw platformFailure('Link this project to the selected API origin and signed-in identity.');
378
+ const operation = command === 'env'
379
+ ? runEnvironmentCommand
380
+ : command === 'staging'
381
+ ? runStagingCommand
382
+ : runLogsCommand;
383
+ return operation(args, output, { origin, principalId: actor.principalId, projectId: link.projectId, teamId: link.teamId }, (path, method, body) => request(path, method, body, token, link.teamId));
384
+ }
385
+ if (!['source', 'deploy'].includes(command) ||
386
+ options.positional.length !== 1 ||
387
+ !(command === 'deploy' ? ['plan', 'prepare', 'status'] : ['upload', 'status']).includes(options.positional[0]))
388
+ throw commandArgumentError(command, 'Use source upload/status or deploy plan/prepare/status.');
389
+ const link = linkSchema.parse(await readPrivate(linkPath));
390
+ if (link.origin !== origin || link.principalId !== actor.principalId)
391
+ throw platformFailure('Link this project to the selected API origin and signed-in identity.');
392
+ if (command === 'deploy') {
393
+ const localPath = join(stateDir, 'deployment.json');
394
+ const stateSchema = z
395
+ .object({
396
+ origin: z.string(),
397
+ principalId: z.uuid(),
398
+ projectId: z.uuid(),
399
+ planInput: cliPlanInputSchema,
400
+ plan: cliPlanSchema.optional(),
401
+ prepareRequestId: z.uuid().optional(),
402
+ candidateId: z.uuid().optional(),
403
+ })
404
+ .strict();
405
+ const stored = stateSchema.safeParse(await readPrivate(localPath));
406
+ const state = stored.success &&
407
+ stored.data.origin === origin &&
408
+ stored.data.principalId === actor.principalId &&
409
+ stored.data.projectId === link.projectId
410
+ ? stored.data
411
+ : null;
412
+ const persist = (v) => writePrivate(localPath, v);
413
+ const checkedPlan = (plan, input) => {
414
+ const { digest, ...unsigned } = plan;
415
+ if (hash(new TextEncoder().encode(canonicalCliJson(unsigned))) !== digest ||
416
+ plan.projectId !== link.projectId ||
417
+ plan.uploadId !== input.uploadId ||
418
+ plan.requestId !== input.requestId ||
419
+ canonicalCliJson(plan.manifest) !== canonicalCliJson(input.manifest))
420
+ throw platformFailure('Deployment plan identity or integrity differs.');
421
+ return plan;
422
+ };
423
+ if (state?.plan)
424
+ checkedPlan(state.plan, state.planInput);
425
+ if (options.positional[0] === 'plan') {
426
+ const upload = uploadState.parse(await readPrivate(uploadPath));
427
+ if (upload.origin !== origin ||
428
+ upload.principalId !== actor.principalId ||
429
+ upload.input.projectId !== link.projectId ||
430
+ !upload.uploadId)
431
+ throw platformFailure('Choose a sealed upload for this linked identity.');
432
+ const receipt = sourceUploadReceiptSchema.parse(await request(`/uploads/${upload.uploadId}`, 'GET', undefined, token, link.teamId));
433
+ if (receipt.state !== 'sealed' ||
434
+ receipt.sourceRevision !== upload.input.archiveDigest ||
435
+ receipt.projectId !== link.projectId)
436
+ throw platformFailure('The saved source upload is not sealed.');
437
+ const file = options.value('--manifest');
438
+ if (!file)
439
+ throw commandArgumentError(command, 'Use deploy plan --manifest <file>.');
440
+ const handle = await import('node:fs/promises').then((fs) => fs.open(resolve(file), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
441
+ let manifest;
442
+ try {
443
+ const info = await handle.stat();
444
+ if (!info.isFile() || info.size > 32768)
445
+ throw platformFailure('Deployment manifest exceeds its limit.');
446
+ try {
447
+ manifest = JSON.parse(await handle.readFile('utf8'));
448
+ }
449
+ catch {
450
+ throw commandArgumentError(command, 'The deployment manifest is not valid JSON. Review it before retrying.');
451
+ }
452
+ }
453
+ finally {
454
+ await handle.close();
455
+ }
456
+ const checkedManifest = deploymentManifestSchema.safeParse(manifest);
457
+ if (!checkedManifest.success)
458
+ throw commandArgumentError(command, 'The deployment manifest must match its foundation, capabilities, identity and runtime profile. TanStack Start uses the anhedral-stack runtime profile.');
459
+ const compared = cliPlanInputSchema.parse({
460
+ protocol: 1,
461
+ requestId: state && !options.has('--new') ? state.planInput.requestId : randomUUID(),
462
+ uploadId: upload.uploadId,
463
+ manifest: checkedManifest.data,
464
+ });
465
+ if (state &&
466
+ !options.has('--new') &&
467
+ canonicalCliJson(state.planInput) !== canonicalCliJson(compared))
468
+ throw platformFailure('Plan inputs changed. Use deploy plan --new to create a new request.');
469
+ const local = {
470
+ origin,
471
+ principalId: actor.principalId,
472
+ projectId: link.projectId,
473
+ planInput: compared,
474
+ };
475
+ // Persist before POST so lost plan responses can be recovered by the same request identity.
476
+ await persist({
477
+ ...local,
478
+ ...(state?.prepareRequestId && !options.has('--new')
479
+ ? { prepareRequestId: state.prepareRequestId, candidateId: state.candidateId }
480
+ : {}),
481
+ });
482
+ const plan = cliPlanSchema.parse(await request('/plans', 'POST', compared, token, link.teamId));
483
+ const { digest, ...unsigned } = plan;
484
+ if (hash(new TextEncoder().encode(canonicalCliJson(unsigned))) !== digest ||
485
+ plan.projectId !== link.projectId ||
486
+ plan.uploadId !== compared.uploadId ||
487
+ plan.requestId !== compared.requestId ||
488
+ canonicalCliJson(plan.manifest) !== canonicalCliJson(compared.manifest) ||
489
+ plan.sourceRevision !== receipt.sourceRevision)
490
+ throw platformFailure('Deployment plan identity or integrity differs.');
491
+ await persist({
492
+ ...local,
493
+ plan,
494
+ ...(state?.prepareRequestId && !options.has('--new')
495
+ ? { prepareRequestId: state.prepareRequestId, candidateId: state.candidateId }
496
+ : {}),
497
+ });
498
+ emit(plan);
499
+ return;
500
+ }
501
+ if (!state?.plan)
502
+ throw platformFailure('Create a deployment plan for this linked identity first.');
503
+ if (options.positional[0] === 'status') {
504
+ if (state.candidateId) {
505
+ const result = cliPreparationSchema.parse(await request(`/candidates/${state.candidateId}`, 'GET', undefined, token, link.teamId));
506
+ if (result.planId !== state.plan.id ||
507
+ result.planDigest !== state.plan.digest ||
508
+ result.candidateId !== state.candidateId ||
509
+ result.sourceRevision !== state.plan.sourceRevision)
510
+ throw platformFailure('Candidate receipt identity differs.');
511
+ emit(result);
512
+ }
513
+ else {
514
+ const plan = checkedPlan(cliPlanSchema.parse(await request(`/plans/${state.plan.id}`, 'GET', undefined, token, link.teamId)), state.planInput);
515
+ if (plan.digest !== state.plan.digest || plan.id !== state.plan.id)
516
+ throw platformFailure('Plan receipt identity differs.');
517
+ emit(plan);
518
+ }
519
+ return;
520
+ }
521
+ const requestId = state.prepareRequestId ?? randomUUID();
522
+ await persist({ ...state, prepareRequestId: requestId });
523
+ const prepared = cliPreparationSchema.parse(await request('/candidates', 'POST', { protocol: 1, requestId, planId: state.plan.id, planDigest: state.plan.digest }, token, link.teamId));
524
+ if (prepared.planId !== state.plan.id ||
525
+ prepared.planDigest !== state.plan.digest ||
526
+ prepared.sourceRevision !== state.plan.sourceRevision)
527
+ throw platformFailure('Candidate receipt identity differs.');
528
+ await persist({ ...state, prepareRequestId: requestId, candidateId: prepared.candidateId });
529
+ emit(prepared);
530
+ return;
531
+ }
532
+ const state = uploadState.safeParse(await readPrivate(uploadPath));
533
+ const checkedState = state.success &&
534
+ state.data.origin === origin &&
535
+ state.data.principalId === actor.principalId &&
536
+ state.data.input.projectId === link.projectId &&
537
+ state.data.input.teamId === link.teamId
538
+ ? state.data
539
+ : null;
540
+ if (options.positional[0] === 'status') {
541
+ if (!checkedState?.uploadId)
542
+ throw platformFailure('No resumable upload is saved for this project.');
543
+ emit(sourceUploadReceiptSchema.parse(await request(`/uploads/${checkedState.uploadId}`, 'GET', undefined, token, link.teamId)));
544
+ return;
545
+ }
546
+ const source = await packageSource(root), archiveDigest = hash(source.archive);
547
+ if (checkedState && checkedState.input.archiveDigest !== archiveDigest && !options.has('--new'))
548
+ throw platformFailure('Source changed since the saved upload. Restore those files or explicitly use source upload --new.');
549
+ const chunks = Array.from({ length: Math.ceil(source.archive.length / SOURCE_LIMITS.chunkBytes) }, (_, i) => source.archive.subarray(i * SOURCE_LIMITS.chunkBytes, (i + 1) * SOURCE_LIMITS.chunkBytes));
550
+ const input = sourceUploadInputSchema.parse({
551
+ protocol: 1,
552
+ requestId: checkedState && !options.has('--new') ? checkedState.input.requestId : randomUUID(),
553
+ projectId: link.projectId,
554
+ teamId: link.teamId,
555
+ archiveDigest,
556
+ archiveBytes: source.archive.length,
557
+ inventoryDigest: source.inventoryDigest,
558
+ cliVersion: source.cliVersion,
559
+ chunks: chunks.map(hash),
560
+ });
561
+ // Persist the request identity before the first network mutation, including lost responses.
562
+ const local = { origin, principalId: actor.principalId, input };
563
+ await writePrivate(uploadPath, local);
564
+ const receipt = sourceUploadReceiptSchema.parse(await request('/uploads', 'POST', input, token, link.teamId));
565
+ if (receipt.projectId !== link.projectId ||
566
+ receipt.requestId !== input.requestId ||
567
+ receipt.archiveDigest !== input.archiveDigest ||
568
+ receipt.inventoryDigest !== input.inventoryDigest)
569
+ throw platformFailure('Upload receipt identity differs.');
570
+ await writePrivate(uploadPath, { ...local, uploadId: receipt.id });
571
+ if (receipt.state === 'cancelled')
572
+ throw platformFailure('Upload was cancelled. Start source upload --new.');
573
+ if (receipt.state !== 'sealed') {
574
+ for (let i = 0; i < chunks.length; i++)
575
+ if (!receipt.received.includes(i))
576
+ await request(`/uploads/${receipt.id}/chunks/${i}`, 'PUT', chunks[i], token, link.teamId);
577
+ }
578
+ const complete = sourceUploadReceiptSchema.parse(await request(`/uploads/${receipt.id}/complete`, 'POST', {}, token, link.teamId));
579
+ if (complete.id !== receipt.id ||
580
+ complete.sourceRevision !== archiveDigest ||
581
+ complete.state !== 'sealed')
582
+ throw platformFailure('Source completion was not sealed. Resume this upload.');
583
+ emit({ ...complete, hostedAdmission: false });
584
+ }
@@ -0,0 +1,18 @@
1
+ import { type OutputOptions } from './cli-output.js';
2
+ type Context = {
3
+ origin: string;
4
+ principalId: string;
5
+ projectId: string;
6
+ teamId: string;
7
+ };
8
+ type Request = (path: string, method: string, body?: unknown) => Promise<unknown>;
9
+ export declare function readEnvironmentSecret(file: string): Uint8Array;
10
+ declare function stdinBytes(): Promise<Uint8Array>;
11
+ export declare function validateEnvironmentArguments(args: string[]): {
12
+ positional: string[];
13
+ has: (flag: string) => boolean;
14
+ value: (flag: string) => string | undefined;
15
+ values: (flag: string) => string[];
16
+ };
17
+ export declare function runEnvironmentCommand(args: string[], output: OutputOptions, context?: Context, request?: Request, readInput?: typeof stdinBytes): Promise<void>;
18
+ export {};