anhedral 0.17.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 (105) hide show
  1. package/README.md +33 -68
  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/dist/bin.js +55 -36
  25. package/dist/capabilities.d.ts +1 -1
  26. package/dist/capability-catalog.d.ts +44 -11
  27. package/dist/capability-catalog.js +96 -11
  28. package/dist/capability-command.d.ts +2 -2
  29. package/dist/capability-command.js +178 -27
  30. package/dist/capability-editor.js +6 -5
  31. package/dist/capability-recipes.js +54 -6
  32. package/dist/cli-arguments.d.ts +2 -0
  33. package/dist/cli-arguments.js +101 -50
  34. package/dist/cli-commands.d.ts +1 -1
  35. package/dist/cli-commands.js +30 -6
  36. package/dist/cli-errors.d.ts +18 -0
  37. package/dist/cli-errors.js +63 -0
  38. package/dist/cli-output.d.ts +22 -0
  39. package/dist/cli-output.js +42 -7
  40. package/dist/command-runner.d.ts +1 -0
  41. package/dist/command-runner.js +88 -0
  42. package/dist/command-schema.d.ts +16 -0
  43. package/dist/command-schema.js +390 -21
  44. package/dist/completion.d.ts +2 -0
  45. package/dist/completion.js +201 -0
  46. package/dist/composition.d.ts +35 -0
  47. package/dist/composition.js +28 -0
  48. package/dist/contracts/cli-transport.d.ts +217 -0
  49. package/dist/contracts/cli-transport.js +167 -0
  50. package/dist/contracts/deployment.d.ts +282 -0
  51. package/dist/contracts/deployment.js +234 -0
  52. package/dist/contracts/environment-file.d.ts +7 -0
  53. package/dist/contracts/environment-file.js +112 -0
  54. package/dist/contracts/environment-transport.d.ts +79 -0
  55. package/dist/contracts/environment-transport.js +110 -0
  56. package/dist/contracts/runtime-logs-transport.d.ts +127 -0
  57. package/dist/contracts/runtime-logs-transport.js +50 -0
  58. package/dist/contracts/source-bundle.d.ts +11 -0
  59. package/dist/contracts/source-bundle.js +197 -0
  60. package/dist/contracts/source-profile.d.ts +4 -0
  61. package/dist/contracts/source-profile.js +5 -0
  62. package/dist/contracts/staging-transport.d.ts +79 -0
  63. package/dist/contracts/staging-transport.js +43 -0
  64. package/dist/dependencies.d.ts +10 -1
  65. package/dist/dependencies.js +18 -1
  66. package/dist/index.d.ts +6 -0
  67. package/dist/index.js +4 -0
  68. package/dist/launch.d.ts +21 -0
  69. package/dist/launch.js +250 -0
  70. package/dist/platform-command.d.ts +9 -0
  71. package/dist/platform-command.js +584 -0
  72. package/dist/platform-environment.d.ts +18 -0
  73. package/dist/platform-environment.js +257 -0
  74. package/dist/platform-operations.d.ts +26 -0
  75. package/dist/platform-operations.js +155 -0
  76. package/dist/platform-source.d.ts +8 -0
  77. package/dist/platform-source.js +111 -0
  78. package/dist/platform-state.d.ts +13 -0
  79. package/dist/platform-state.js +207 -0
  80. package/dist/platforms/tanstack.d.ts +8 -0
  81. package/dist/platforms/tanstack.js +155 -0
  82. package/dist/registry/options.js +34 -31
  83. package/dist/registry/usage.d.ts +4 -1
  84. package/dist/registry/usage.js +58 -4
  85. package/dist/scaffold/styling.d.ts +1 -1
  86. package/dist/scaffold/workspace.js +11 -1
  87. package/dist/stack-registry.d.ts +2 -2
  88. package/dist/standard.js +21 -6
  89. package/dist/transaction.js +28 -3
  90. package/dist/ui-command.d.ts +4 -2
  91. package/dist/ui-command.js +79 -38
  92. package/dist/ui-project.d.ts +2 -0
  93. package/dist/ui-project.js +38 -8
  94. package/dist/util.js +40 -61
  95. package/dist/version.d.ts +1 -1
  96. package/dist/version.js +1 -1
  97. package/docs/capabilities.md +22 -88
  98. package/docs/software-factory.md +169 -9
  99. package/docs/stack-standard.md +7 -17
  100. package/docs/ui.md +9 -22
  101. package/package.json +27 -20
  102. package/docs/anhedral-stack.md +0 -12
  103. package/docs/assets/anhedral-stack-light.png +0 -0
  104. package/docs/assets/anhedral-stack.png +0 -0
  105. package/docs/native-ui.md +0 -47
@@ -0,0 +1,257 @@
1
+ import { constants, fstatSync, lstatSync, openSync, readSync, closeSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { z } from 'zod';
5
+ import { commandArguments, commandArgumentError } from './cli-arguments.js';
6
+ import { createReporter } from './cli-output.js';
7
+ import { environmentImportSchema, environmentImportReceiptSchema, environmentMetadataSchema, environmentNameSchema, projectEnvironmentSchema, } from './contracts/environment-transport.js';
8
+ import { inferredEnvironmentKind, parseEnvironmentFile } from './contracts/environment-file.js';
9
+ import { platformFailure, readPrivate, writePrivate } from './platform-state.js';
10
+ const planSchema = z
11
+ .object({
12
+ origin: z.string(),
13
+ principalId: z.uuid(),
14
+ projectId: z.uuid(),
15
+ teamId: z.uuid(),
16
+ environment: projectEnvironmentSchema,
17
+ requestId: z.uuid(),
18
+ variables: z
19
+ .array(z
20
+ .object({
21
+ name: environmentNameSchema,
22
+ kind: z.enum(['secret', 'config']),
23
+ note: z.string(),
24
+ expectedVersion: z.number().int().nonnegative(),
25
+ })
26
+ .strict())
27
+ .max(128),
28
+ receipt: environmentImportReceiptSchema.optional(),
29
+ })
30
+ .strict();
31
+ export function readEnvironmentSecret(file) {
32
+ const path = resolve(file);
33
+ for (let parent = dirname(path);; parent = dirname(parent)) {
34
+ const info = lstatSync(parent);
35
+ if (!info.isDirectory() || info.isSymbolicLink())
36
+ throw platformFailure('Environment input has a symlinked or invalid directory.');
37
+ if (dirname(parent) === parent)
38
+ break;
39
+ }
40
+ const descriptor = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
41
+ try {
42
+ const info = fstatSync(descriptor);
43
+ if (!info.isFile() ||
44
+ info.size > 65536 ||
45
+ (process.platform !== 'win32' &&
46
+ (info.uid !== process.getuid?.() || (info.mode & 0o077) !== 0)))
47
+ throw platformFailure('Environment input must be your regular owner-only file (mode 0600), at most 64 KiB.');
48
+ const data = Buffer.alloc(65537);
49
+ let length = 0;
50
+ while (length < data.length) {
51
+ const read = readSync(descriptor, data, length, data.length - length, null);
52
+ if (!read)
53
+ break;
54
+ length += read;
55
+ }
56
+ if (length > 65536)
57
+ throw platformFailure('Environment input exceeds 64 KiB.');
58
+ return data.subarray(0, length);
59
+ }
60
+ finally {
61
+ closeSync(descriptor);
62
+ }
63
+ }
64
+ async function stdinBytes() {
65
+ if (process.stdin.isTTY)
66
+ throw platformFailure('Pipe a value or dotenv contents to --stdin; interactive secret entry is not supported.');
67
+ const chunks = [];
68
+ let length = 0;
69
+ const timeout = setTimeout(() => process.stdin.destroy(new Error('Environment input timed out.')), 30000);
70
+ try {
71
+ for await (const item of process.stdin) {
72
+ const bytes = Buffer.from(item);
73
+ length += bytes.length;
74
+ if (length > 65536)
75
+ throw platformFailure('Environment input exceeds 64 KiB.');
76
+ chunks.push(bytes);
77
+ }
78
+ return Buffer.concat(chunks);
79
+ }
80
+ finally {
81
+ clearTimeout(timeout);
82
+ }
83
+ }
84
+ export function validateEnvironmentArguments(args) {
85
+ const options = commandArguments('env', args);
86
+ const [operation, name] = options.positional;
87
+ if (operation === 'list') {
88
+ if (['--file', '--stdin', '--type', '--replace', '--new', '--dry-run'].some((flag) => options.has(flag)))
89
+ throw commandArgumentError('env', 'env list accepts only context and environment options.');
90
+ }
91
+ else {
92
+ if (!options.value('--environment'))
93
+ throw commandArgumentError('env', 'An explicit --environment staging|production is required.');
94
+ if (options.has('--file') === options.has('--stdin'))
95
+ throw commandArgumentError('env', 'Choose exactly one --file <file> or --stdin. Values cannot be supplied in arguments.');
96
+ if (operation === 'set' && !environmentNameSchema.safeParse(name).success)
97
+ throw commandArgumentError('env', 'Use an uppercase variable name.');
98
+ }
99
+ return options;
100
+ }
101
+ export async function runEnvironmentCommand(args, output, context, request, readInput = stdinBytes) {
102
+ const options = validateEnvironmentArguments(args);
103
+ const [operation, name] = options.positional;
104
+ const reporter = createReporter(output, (value) => {
105
+ const data = value;
106
+ return (`${data.status} ${data.environment ?? ''}\n` +
107
+ (data.variables ?? data.imported ?? [])
108
+ .map((entry) => `${entry.name}${entry.version ? ` v${entry.version}` : ''}`)
109
+ .join('\n'));
110
+ }, true);
111
+ const environment = options.value('--environment');
112
+ if (environment && !projectEnvironmentSchema.safeParse(environment).success)
113
+ throw commandArgumentError('env', 'Choose staging or production.');
114
+ if (operation === 'list') {
115
+ if (!context || !request)
116
+ throw platformFailure('Link and sign in to the intended project first.');
117
+ const metadata = environmentMetadataSchema.parse(await request(`/projects/${context.projectId}/environment`, 'GET'));
118
+ reporter.result({
119
+ status: 'listed',
120
+ projectId: context.projectId,
121
+ environment: environment ?? 'all',
122
+ variables: metadata.variables.filter((entry) => !environment || entry.environment === environment),
123
+ });
124
+ return;
125
+ }
126
+ const explicitKind = options.value('--type');
127
+ let entries;
128
+ try {
129
+ const bytes = options.has('--file')
130
+ ? readEnvironmentSecret(options.value('--file'))
131
+ : await readInput();
132
+ if (bytes.length > 65536)
133
+ throw new Error('Environment input exceeds 64 KiB.');
134
+ const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
135
+ entries = operation === 'set' ? [{ name: name, value: text }] : parseEnvironmentFile(text);
136
+ }
137
+ catch (error) {
138
+ if (error instanceof Error && error.name === 'CliArgumentError')
139
+ throw error;
140
+ throw platformFailure(error instanceof Error && /^(Line \d+:|Environment (files|file|input))/.test(error.message)
141
+ ? error.message
142
+ : 'Could not read private UTF-8 environment input. No variables were uploaded.');
143
+ }
144
+ const variables = entries
145
+ .map((entry) => ({
146
+ ...entry,
147
+ kind: (explicitKind ?? inferredEnvironmentKind(entry.name)),
148
+ note: '',
149
+ expectedVersion: 0,
150
+ }))
151
+ .sort((a, b) => a.name.localeCompare(b.name));
152
+ if (!environmentImportSchema.safeParse({ requestId: randomUUID(), environment, variables }).success)
153
+ throw platformFailure('Check variable names, type and size. Empty values, reserved names and public-prefixed secrets are rejected. No variables were uploaded.');
154
+ if (options.has('--dry-run')) {
155
+ reporter.result({
156
+ status: 'dry_run',
157
+ environment,
158
+ projectId: context?.projectId ?? null,
159
+ projectVerified: false,
160
+ variables: variables.map(({ name, kind }) => ({ name, kind })),
161
+ applied: false,
162
+ });
163
+ return;
164
+ }
165
+ if (!context || !request)
166
+ throw platformFailure('Link and sign in to the intended project first.');
167
+ const statePath = join(process.cwd(), '.anhedral', 'platform', `environment-${environment}.json`);
168
+ const raw = await readPrivate(statePath);
169
+ const parsed = raw === null ? null : planSchema.safeParse(raw);
170
+ if (parsed && !parsed.success)
171
+ throw platformFailure('Saved environment import state is invalid. Preserve it and reconcile the selected context.');
172
+ const previous = parsed?.success ? parsed.data : null;
173
+ if (previous &&
174
+ (previous.origin !== context.origin ||
175
+ previous.principalId !== context.principalId ||
176
+ previous.projectId !== context.projectId ||
177
+ previous.teamId !== context.teamId ||
178
+ previous.environment !== environment))
179
+ throw platformFailure('Saved environment import belongs to a different identity or project. Preserve it and select the original context.');
180
+ if (previous &&
181
+ !options.has('--new') &&
182
+ JSON.stringify(previous.variables.map(({ name, kind }) => ({ name, kind }))) !==
183
+ JSON.stringify(variables.map(({ name, kind }) => ({ name, kind }))))
184
+ throw platformFailure('Saved import names or types changed. Use --new for another import.');
185
+ if (previous?.receipt &&
186
+ (previous.receipt.requestId !== previous.requestId ||
187
+ previous.receipt.imported.length !== previous.variables.length ||
188
+ previous.receipt.imported.some((entry, index) => entry.name !== previous.variables[index]?.name ||
189
+ entry.kind !== previous.variables[index]?.kind ||
190
+ entry.environment !== previous.environment ||
191
+ (previous.variables[index].expectedVersion > 0 &&
192
+ entry.version !== previous.variables[index].expectedVersion + 1))))
193
+ throw platformFailure('Saved environment receipt differs from its import. Preserve state and reconcile before retrying.');
194
+ if (previous?.receipt && !options.has('--new')) {
195
+ reporter.result({
196
+ status: 'already_imported',
197
+ projectId: context.projectId,
198
+ environment,
199
+ ...previous.receipt,
200
+ nextAction: 'Use --new to start another import. Existing values additionally require --replace.',
201
+ });
202
+ return;
203
+ }
204
+ let state;
205
+ if (previous && !options.has('--new')) {
206
+ if (JSON.stringify(previous.variables.map(({ name, kind }) => ({ name, kind }))) !==
207
+ JSON.stringify(variables.map(({ name, kind }) => ({ name, kind }))))
208
+ throw platformFailure('Pending import names or types changed. Restore its original input or use --new.');
209
+ state = previous;
210
+ }
211
+ else {
212
+ const metadata = environmentMetadataSchema.parse(await request(`/projects/${context.projectId}/environment`, 'GET'));
213
+ const existing = new Map(metadata.variables
214
+ .filter((entry) => entry.environment === environment)
215
+ .map((entry) => [entry.name, entry]));
216
+ if (!options.has('--replace') && variables.some((entry) => existing.has(entry.name)))
217
+ throw platformFailure('Some variables already exist. Review their names with env list, then explicitly use --replace.');
218
+ state = {
219
+ ...context,
220
+ environment: projectEnvironmentSchema.parse(environment),
221
+ requestId: randomUUID(),
222
+ variables: variables.map(({ name, kind, note }) => ({
223
+ name,
224
+ kind,
225
+ note,
226
+ expectedVersion: existing.get(name)?.version ?? 0,
227
+ })),
228
+ };
229
+ // Persist only retry identity and versions. No value or value digest is saved.
230
+ await writePrivate(statePath, state);
231
+ }
232
+ const input = environmentImportSchema.parse({
233
+ requestId: state.requestId,
234
+ environment,
235
+ variables: variables.map((entry, index) => ({
236
+ ...entry,
237
+ expectedVersion: state.variables[index].expectedVersion,
238
+ })),
239
+ });
240
+ const receipt = environmentImportReceiptSchema.parse(await request(`/projects/${context.projectId}/environment/import`, 'POST', input));
241
+ if (receipt.requestId !== state.requestId ||
242
+ receipt.imported.length !== variables.length ||
243
+ receipt.imported.some((entry, index) => entry.name !== variables[index]?.name ||
244
+ entry.kind !== variables[index]?.kind ||
245
+ entry.environment !== environment ||
246
+ (state.variables[index].expectedVersion > 0 &&
247
+ entry.version !== state.variables[index].expectedVersion + 1)))
248
+ throw platformFailure('Environment receipt differs from this import. Preserve saved state before retrying.');
249
+ await writePrivate(statePath, { ...state, receipt });
250
+ reporter.result({
251
+ status: 'imported',
252
+ projectId: context.projectId,
253
+ environment,
254
+ ...receipt,
255
+ appliedToRunningDeployments: false,
256
+ });
257
+ }
@@ -0,0 +1,26 @@
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 validateStagingArguments(args: string[]): {
10
+ positional: string[];
11
+ has: (flag: string) => boolean;
12
+ value: (flag: string) => string | undefined;
13
+ values: (flag: string) => string[];
14
+ };
15
+ export declare function validateLogsArguments(args: string[]): {
16
+ environment: "staging" | "production";
17
+ range: "1h" | "24h" | "7d";
18
+ search: string;
19
+ deploymentId?: string | undefined;
20
+ level?: "debug" | "info" | "warn" | "error" | undefined;
21
+ source?: "request" | "console" | "exception" | undefined;
22
+ cursor?: string | undefined;
23
+ };
24
+ export declare function runStagingCommand(args: string[], output: OutputOptions, context: Context, request: Request): Promise<void>;
25
+ export declare function runLogsCommand(args: string[], output: OutputOptions, context: Context, request: Request): Promise<void>;
26
+ export {};
@@ -0,0 +1,155 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import { stripVTControlCharacters } from 'node:util';
4
+ import { z } from 'zod';
5
+ import { commandArguments, commandArgumentError } from './cli-arguments.js';
6
+ import { createReporter } from './cli-output.js';
7
+ import { stagingCreateSchema, stagingStateSchema, stagingCreateReceiptSchema, } from './contracts/staging-transport.js';
8
+ import { runtimeLogQuerySchema, runtimeLogPageSchema } from './contracts/runtime-logs-transport.js';
9
+ import { platformFailure, readPrivate, writePrivate } from './platform-state.js';
10
+ const contextSchema = z.object({
11
+ origin: z.string(),
12
+ principalId: z.uuid(),
13
+ projectId: z.uuid(),
14
+ teamId: z.uuid(),
15
+ });
16
+ const receiptSchema = stagingCreateReceiptSchema;
17
+ const stateSchema = contextSchema
18
+ .extend({ input: stagingCreateSchema, receipt: receiptSchema.optional() })
19
+ .strict();
20
+ const visible = (value) => stripVTControlCharacters(String(value ?? '')).replace(/[\x00-\x1f\x7f]/g, ' ');
21
+ export function validateStagingArguments(args) {
22
+ const options = commandArguments('staging', args);
23
+ const [operation] = options.positional;
24
+ if (operation === 'status' && (options.has('--candidate') || options.has('--new')))
25
+ throw commandArgumentError('staging', 'Candidate and --new apply to staging deploy only.');
26
+ if (operation === 'deploy' && !z.uuid().safeParse(options.value('--candidate')).success)
27
+ throw commandArgumentError('staging', 'Select a ready candidate UUID with --candidate.');
28
+ return options;
29
+ }
30
+ export function validateLogsArguments(args) {
31
+ const options = commandArguments('logs', args);
32
+ const parsed = runtimeLogQuerySchema.safeParse({
33
+ environment: options.value('--environment') ?? 'staging',
34
+ deploymentId: options.value('--deployment'),
35
+ level: options.value('--level'),
36
+ source: options.value('--source'),
37
+ range: options.value('--range'),
38
+ search: options.value('--search'),
39
+ cursor: options.value('--cursor'),
40
+ });
41
+ if (!parsed.success)
42
+ throw commandArgumentError('logs', 'Check the environment, deployment, level, source, range and cursor filters.');
43
+ return parsed.data;
44
+ }
45
+ export async function runStagingCommand(args, output, context, request) {
46
+ const options = validateStagingArguments(args);
47
+ const [operation] = options.positional;
48
+ const reporter = createReporter(output, (value) => {
49
+ const data = value;
50
+ if (data.status === 'requested' || data.status === 'already_requested')
51
+ return `Staging deployment requested (${visible(data.deployment.id)}).\nRun anhedral staging status to follow preparation.`;
52
+ const state = data.staging;
53
+ return [
54
+ `Staging generation ${state.generation}.`,
55
+ state.enabled === false
56
+ ? 'Persistent staging is not configured.'
57
+ : `Active deployment: ${visible(state.activeDeploymentId ?? 'none')}.`,
58
+ ...state.deployments.map((entry) => `${entry.id} ${entry.status} ${entry.sourceRevision.slice(0, 12)}`),
59
+ ].join('\n');
60
+ }, true);
61
+ const path = `/projects/${context.projectId}/staging`;
62
+ const checkedState = (value) => {
63
+ const state = stagingStateSchema.parse(value);
64
+ if (state.deployments.some((entry) => entry.developmentId !== context.projectId))
65
+ throw platformFailure('Staging history belongs to another project.');
66
+ return state;
67
+ };
68
+ if (operation === 'status') {
69
+ reporter.result({
70
+ status: 'read',
71
+ environment: 'staging',
72
+ projectId: context.projectId,
73
+ staging: checkedState(await request(path, 'GET')),
74
+ });
75
+ return;
76
+ }
77
+ const candidateId = options.value('--candidate');
78
+ const file = join(process.cwd(), '.anhedral', 'platform', 'staging.json');
79
+ const raw = await readPrivate(file);
80
+ const parsed = raw === null ? null : stateSchema.safeParse(raw);
81
+ if (parsed && !parsed.success)
82
+ throw platformFailure('Saved staging deployment state is invalid. Preserve it before retrying.');
83
+ const previous = parsed?.success ? parsed.data : null;
84
+ if (previous &&
85
+ Object.entries(context).some(([key, value]) => previous[key] !== value))
86
+ throw platformFailure('Saved staging deployment belongs to a different identity, team or project. Restore its original context.');
87
+ if (previous && !options.has('--new') && previous.input.candidateId !== candidateId)
88
+ throw platformFailure('The candidate differs from the pending staging deployment. Use --new for another deployment.');
89
+ if (previous?.receipt &&
90
+ (previous.receipt.developmentId !== context.projectId ||
91
+ previous.receipt.requestId !== previous.input.requestId ||
92
+ previous.receipt.candidateId !== previous.input.candidateId ||
93
+ previous.receipt.generation !== previous.input.expectedGeneration + 1))
94
+ throw platformFailure('Saved staging receipt differs from its request. Preserve state and reconcile before retrying.');
95
+ if (previous?.receipt && !options.has('--new')) {
96
+ reporter.result({
97
+ status: 'already_requested',
98
+ environment: 'staging',
99
+ projectId: context.projectId,
100
+ requestId: previous.input.requestId,
101
+ deployment: previous.receipt,
102
+ });
103
+ return;
104
+ }
105
+ let state;
106
+ if (previous && !options.has('--new'))
107
+ state = previous;
108
+ else {
109
+ const current = checkedState(await request(path, 'GET'));
110
+ if (current.enabled !== true || !current.canDeploy)
111
+ throw platformFailure('Staging deployment is not configured or current build permission is unavailable.');
112
+ state = {
113
+ ...context,
114
+ input: stagingCreateSchema.parse({
115
+ requestId: randomUUID(),
116
+ candidateId,
117
+ expectedGeneration: current.generation,
118
+ }),
119
+ };
120
+ await writePrivate(file, state);
121
+ }
122
+ const receipt = receiptSchema.parse(await request(`${path}/deployments`, 'POST', state.input));
123
+ if (receipt.developmentId !== context.projectId ||
124
+ receipt.requestId !== state.input.requestId ||
125
+ receipt.candidateId !== state.input.candidateId ||
126
+ receipt.generation !== state.input.expectedGeneration + 1)
127
+ throw platformFailure('Staging receipt differs from this request. Preserve saved state before retrying.');
128
+ await writePrivate(file, { ...state, receipt });
129
+ reporter.result({
130
+ status: 'requested',
131
+ environment: 'staging',
132
+ projectId: context.projectId,
133
+ requestId: state.input.requestId,
134
+ deployment: receipt,
135
+ });
136
+ }
137
+ export async function runLogsCommand(args, output, context, request) {
138
+ const query = validateLogsArguments(args);
139
+ const params = new URLSearchParams(Object.entries(query).filter((entry) => typeof entry[1] === 'string'));
140
+ const page = runtimeLogPageSchema.parse(await request(`/projects/${context.projectId}/runtime-logs?${params}`, 'GET'));
141
+ if (page.environment !== query.environment ||
142
+ page.entries.some((entry) => entry.environment !== query.environment ||
143
+ (query.deploymentId && entry.deploymentId !== query.deploymentId)))
144
+ throw platformFailure('Runtime log response differs from the selected environment or deployment.');
145
+ const reporter = createReporter(output, (value) => {
146
+ const logs = value.logs;
147
+ return [
148
+ logs.state === 'ready' ? `Runtime logs: ${logs.environment}.` : visible(logs.reason),
149
+ ...logs.entries.map((entry) => `${entry.occurredAt} ${entry.level} ${entry.component}/${entry.kind} ${visible(entry.message)}`),
150
+ ...(logs.nextCursor ? [`More entries: use --cursor ${logs.nextCursor}.`] : []),
151
+ ...(logs.dropped ? [`${logs.dropped} entries were dropped by collection limits.`] : []),
152
+ ].join('\n');
153
+ }, true);
154
+ reporter.result({ projectId: context.projectId, logs: page });
155
+ }
@@ -0,0 +1,8 @@
1
+ export declare function packageSource(root: string): Promise<{
2
+ archive: Uint8Array<ArrayBuffer>;
3
+ inventoryDigest: string;
4
+ cliVersion: string;
5
+ files: number;
6
+ paths: string[];
7
+ bytes: number;
8
+ }>;
@@ -0,0 +1,111 @@
1
+ import { sourceContainsCredential as localCredentialMaterial } from '../assets/security/credential-patterns.mjs';
2
+ import { constants } from 'node:fs';
3
+ import { lstat, readFile, readdir, open } from 'node:fs/promises';
4
+ import { join } from 'node:path';
5
+ import ignore from 'ignore';
6
+ import { SOURCE_LIMITS, sourceContainsCredential, uploadExcluded, uploadSecret, } from './contracts/cli-transport.js';
7
+ import { excludedSource, generatedSource, secretSource } from './contracts/source-profile.js';
8
+ import { packSource, setSourceExecutable, sourceInventory, validateSourcePath, } from './contracts/source-bundle.js';
9
+ import { platformFailure } from './platform-state.js';
10
+ export async function packageSource(root) {
11
+ const files = new Map();
12
+ let bytes = 0;
13
+ async function walk(relative, rules) {
14
+ const directory = join(root, relative);
15
+ const gitignore = await lstat(join(directory, '.gitignore')).catch(() => null);
16
+ if (gitignore && (!gitignore.isFile() || gitignore.isSymbolicLink()))
17
+ throw platformFailure('Source ignore file is unsafe.');
18
+ if (gitignore) {
19
+ if (gitignore.size > 65536)
20
+ throw platformFailure('Source ignore file exceeds its limit.');
21
+ rules = [
22
+ ...rules,
23
+ {
24
+ base: relative,
25
+ matcher: ignore().add(await readFile(join(directory, '.gitignore'), 'utf8')),
26
+ },
27
+ ];
28
+ }
29
+ for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
30
+ const path = relative ? `${relative}/${entry.name}` : entry.name;
31
+ if (excludedSource.test(path) ||
32
+ generatedSource.test(path) ||
33
+ secretSource.test(path) ||
34
+ uploadExcluded.test(path) ||
35
+ uploadSecret.test(path))
36
+ continue;
37
+ let ignored = false;
38
+ for (const { base, matcher } of rules) {
39
+ const match = matcher.test(path.slice(base ? base.length + 1 : 0) + (entry.isDirectory() ? '/' : ''));
40
+ if (match.ignored)
41
+ ignored = true;
42
+ else if (match.unignored)
43
+ ignored = false;
44
+ }
45
+ if (ignored)
46
+ continue;
47
+ const info = await lstat(join(root, path));
48
+ if (info.isSymbolicLink() || (!info.isFile() && !info.isDirectory()))
49
+ throw platformFailure('Source contains a symbolic link or special file. Exclude it before uploading.');
50
+ validateSourcePath(path);
51
+ if (info.isDirectory()) {
52
+ await walk(path, rules);
53
+ continue;
54
+ }
55
+ if (files.size >= SOURCE_LIMITS.files || (bytes += info.size) > SOURCE_LIMITS.bytes)
56
+ throw platformFailure('Source exceeds its file or byte limit.');
57
+ const handle = await open(join(root, path), constants.O_RDONLY | constants.O_NOFOLLOW);
58
+ let content;
59
+ try {
60
+ const before = await handle.stat();
61
+ if (!before.isFile() ||
62
+ before.dev !== info.dev ||
63
+ before.ino !== info.ino ||
64
+ before.size !== info.size)
65
+ throw platformFailure('Source changed during packaging.');
66
+ content = Buffer.alloc(info.size);
67
+ let offset = 0;
68
+ while (offset < content.length) {
69
+ const read = await handle.read(content, offset, content.length - offset, offset);
70
+ if (!read.bytesRead)
71
+ break;
72
+ offset += read.bytesRead;
73
+ }
74
+ const after = await handle.stat();
75
+ if (offset !== info.size || after.size !== info.size || after.mtimeMs !== before.mtimeMs)
76
+ throw platformFailure('Source changed during packaging.');
77
+ }
78
+ finally {
79
+ await handle.close();
80
+ }
81
+ if (content.length !== info.size)
82
+ throw platformFailure('Source changed during packaging. Retry after saving your files.');
83
+ if (sourceContainsCredential(content) || localCredentialMaterial(content))
84
+ throw platformFailure('Source contains credential material. Remove it before uploading.');
85
+ files.set(path, content);
86
+ setSourceExecutable(files, path, Boolean(info.mode & 0o111));
87
+ }
88
+ }
89
+ await walk('', []);
90
+ const config = files.get('anhedral.json');
91
+ if (!config || !files.has('pnpm-lock.yaml'))
92
+ throw platformFailure('Upload requires anhedral.json and pnpm-lock.yaml.');
93
+ let cliVersion;
94
+ try {
95
+ cliVersion = JSON.parse(new TextDecoder().decode(config)).setup?.cliVersion;
96
+ }
97
+ catch {
98
+ throw platformFailure('Workspace configuration is invalid.');
99
+ }
100
+ if (typeof cliVersion !== 'string')
101
+ throw platformFailure('The workspace must declare setup.cliVersion.');
102
+ const inventory = await sourceInventory(files), archive = await packSource(files);
103
+ return {
104
+ archive,
105
+ inventoryDigest: inventory.digest,
106
+ cliVersion,
107
+ files: files.size,
108
+ paths: [...files.keys()].sort(),
109
+ bytes,
110
+ };
111
+ }
@@ -0,0 +1,13 @@
1
+ import { CliFailure } from './cli-errors.js';
2
+ export type PlatformFailureCategory = ConstructorParameters<typeof CliFailure>[3];
3
+ export declare const platformFailure: (message: string, nextAction?: string, category?: PlatformFailureCategory, retryable?: boolean) => CliFailure;
4
+ export declare function platformOrigin(value?: string): string;
5
+ export declare function readPrivate(path: string): Promise<unknown | null>;
6
+ export declare function writePrivate(path: string, data: unknown): Promise<void>;
7
+ export interface SecretStore {
8
+ read(): Promise<unknown | null>;
9
+ write(data: unknown): Promise<void>;
10
+ clear(): Promise<void>;
11
+ }
12
+ export declare function runCredentialProcess(binary: string, args: string[], input?: string, timeoutMs?: number): Promise<string>;
13
+ export declare function secretStore(origin: string, file?: string, runProcess?: typeof runCredentialProcess, platform?: NodeJS.Platform): SecretStore;