-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompile.ts
More file actions
240 lines (216 loc) · 10 KB
/
compile.ts
File metadata and controls
240 lines (216 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license.
import { Args, Command, Flags } from '@oclif/core';
import path from 'path';
import fs from 'fs';
import chalk from 'chalk';
import { ZodError } from 'zod';
import { ObjectStackDefinitionSchema, normalizeStackInput } from '@objectstack/spec';
import { loadConfig } from '../utils/config.js';
import { lowerCallables } from '../utils/lower-callables.js';
import { buildRuntimeBundle, cleanupOldRuntimeBundles } from '../utils/build-runtime.js';
import {
printHeader,
printKV,
printSuccess,
printError,
printStep,
createTimer,
formatZodErrors,
collectMetadataStats,
printMetadataStats,
} from '../utils/format.js';
export default class Compile extends Command {
static override description = 'Compile ObjectStack configuration to JSON artifact';
static override args = {
config: Args.string({ description: 'Source configuration file', required: false }),
};
static override flags = {
output: Flags.string({ char: 'o', description: 'Output JSON file', default: 'dist/objectstack.json' }),
json: Flags.boolean({ description: 'Output compile result as JSON (for CI)' }),
'strict-body': Flags.boolean({
description: 'Fail the build if any hook/action callable could not be lowered into a metadata-only body (no .mjs fallback)',
default: false,
}),
'runtime-bundle': Flags.boolean({
description: 'Force-emit the legacy objectstack-runtime.{hash}.mjs shim even when every callable has a metadata body. Useful for back-compat with older runtime loaders. By default the bundle is auto-emitted only when at least one callable could not be lowered to a body.',
default: false,
allowNo: true,
}),
// Deprecated alias kept for back-compat. Auto-skip is now the default,
// so this flag is a no-op except that it forces a hard failure when any
// callable still needs the legacy bundle (same semantics as before).
'no-runtime-bundle': Flags.boolean({
description: '[deprecated] Auto-skip is now the default. Pass --no-runtime-bundle to fail loudly if any callable still requires the legacy bundle.',
default: false,
hidden: true,
}),
};
async run(): Promise<void> {
const { args, flags } = await this.parse(Compile);
const timer = createTimer();
if (!flags.json) {
printHeader('Compile');
}
try {
// 1. Load Configuration
if (!flags.json) printStep('Loading configuration...');
const { config, absolutePath, duration } = await loadConfig(args.config);
if (!flags.json) {
printKV('Config', path.relative(process.cwd(), absolutePath));
printKV('Load time', `${duration}ms`);
}
// 2. Normalize map-formatted stack definition.
if (!flags.json) printStep('Normalizing stack definition...');
const normalized = normalizeStackInput(config as Record<string, unknown>);
// 2b. Lower inline `function` handlers (Hook.handler, top-level
// `functions`) to stable string refs BEFORE Zod parse. This
// guarantees we extract the user's real function identity (Zod's
// `z.function()` wraps callables and would otherwise break the
// mapping). The originals are bundled into a sibling ESM module
// by esbuild — without this step `JSON.stringify` would silently
// drop every handler and the production server would boot with
// all hooks disabled.
if (!flags.json) printStep('Lowering inline handlers...');
const lowering = lowerCallables(normalized);
// Strict-body gate: refuse to ship if any callable failed body extraction.
// Body-only is the long-term target — `--strict-body` lets CI enforce it
// before ESM-bundle emission becomes mandatory-off.
const missingBody = lowering.count - lowering.bodyExtracted;
if (flags['strict-body']) {
const issues = [
...lowering.bodyExtractionWarnings,
...(missingBody > 0
? [{ origin: '<aggregate>', reason: `${missingBody} callable(s) lowered to handler ref but produced no body` }]
: []),
];
if (issues.length > 0) {
if (flags.json) {
console.log(JSON.stringify({ success: false, error: 'strict-body: missing body', issues }));
this.exit(1);
}
console.log('');
printError(`--strict-body: ${issues.length} callable(s) lack a metadata body`);
for (const w of issues.slice(0, 20)) {
console.log(` • ${w.origin}: ${w.reason}`);
}
this.exit(1);
}
}
// 3. Validate the lowered (JSON-safe) stack against the Protocol.
if (!flags.json) printStep('Validating protocol compliance...');
const result = ObjectStackDefinitionSchema.safeParse(lowering.lowered);
if (!result.success) {
if (flags.json) {
console.log(JSON.stringify({ success: false, errors: (result.error as unknown as ZodError).issues }));
this.exit(1);
}
console.log('');
printError('Validation failed');
formatZodErrors(result.error as unknown as ZodError);
this.exit(1);
}
// 4. Generate Artifact
if (!flags.json) printStep('Writing artifact...');
const output = flags.output!;
const artifactPath = path.resolve(process.cwd(), output);
const artifactDir = path.dirname(artifactPath);
if (!fs.existsSync(artifactDir)) {
fs.mkdirSync(artifactDir, { recursive: true });
}
const finalBundle: Record<string, unknown> = { ...(result.data as Record<string, unknown>) };
// 4b. Bundle handler functions into `<artifactDir>/objectstack-runtime.{hash}.mjs`
// and stamp the relative path into the JSON so the runtime can
// dynamic-import it at boot. `runtimeModule` is part of the
// declared protocol (see ObjectStackDefinitionSchema) so a
// follow-up safeParse of the artifact preserves it.
let runtimeBundle: { outputFileName: string; hash: string; size: number } | null = null;
if (lowering.count > 0) {
// New default: auto-skip the legacy bundle when every callable is
// body-only (the metadata is fully self-describing). The bundle is
// emitted only when (a) some callable could not be lowered, or
// (b) the user explicitly opted in via --runtime-bundle.
const stillNeeded = lowering.count - lowering.bodyExtracted;
const needsBundle = stillNeeded > 0 || lowering.bodyExtractionWarnings.length > 0;
const forceBundle = flags['runtime-bundle'];
const strictNoBundle = flags['no-runtime-bundle'];
if (strictNoBundle && needsBundle) {
// Legacy strict mode: explicit --no-runtime-bundle fails loudly
// when any callable still requires the bundle. Preserved so CI
// pipelines can guard against accidental regressions.
const msg = `--no-runtime-bundle requires every callable to have a metadata body (${stillNeeded} missing, ${lowering.bodyExtractionWarnings.length} extraction warning(s)). Re-run with --strict-body to see details, or omit --no-runtime-bundle.`;
if (flags.json) {
console.log(JSON.stringify({ success: false, error: msg }));
this.exit(1);
}
console.log('');
printError(msg);
this.exit(1);
}
if (!needsBundle && !forceBundle) {
if (!flags.json) printStep(`Skipping legacy runtime bundle (all ${lowering.count} callables are body-only)`);
// Drop any previously emitted bundle so the artifact dir doesn't carry stale code.
cleanupOldRuntimeBundles(artifactDir, '');
} else {
if (!flags.json) printStep(`Bundling ${lowering.count} handler${lowering.count === 1 ? '' : 's'}...`);
try {
runtimeBundle = await buildRuntimeBundle({
sourceConfigPath: absolutePath,
refs: Object.keys(lowering.functions),
outputDir: artifactDir,
});
finalBundle.runtimeModule = `./${runtimeBundle.outputFileName}`;
cleanupOldRuntimeBundles(artifactDir, runtimeBundle.outputFileName);
} catch (err: any) {
if (flags.json) {
console.log(JSON.stringify({ success: false, error: `runtime bundle failed: ${err.message}` }));
this.exit(1);
}
console.log('');
printError(`Runtime bundle failed: ${err.message}`);
this.error(err.message);
}
}
}
const jsonContent = JSON.stringify(finalBundle, null, 2);
fs.writeFileSync(artifactPath, jsonContent);
const sizeKB = (jsonContent.length / 1024).toFixed(1);
const stats = collectMetadataStats(config);
if (flags.json) {
console.log(JSON.stringify({
success: true,
output: artifactPath,
size: jsonContent.length,
handlersBundled: lowering.count,
runtimeModule: runtimeBundle?.outputFileName ?? null,
runtimeModuleSize: runtimeBundle?.size ?? 0,
stats,
duration: timer.elapsed(),
}));
return;
}
// 5. Summary
console.log('');
printSuccess(`Build complete ${chalk.dim(`(${timer.display()})`)}`);
console.log('');
printMetadataStats(stats);
console.log('');
printKV('Artifact', `${output} ${chalk.dim(`(${sizeKB} KB`)})`);
if (runtimeBundle) {
const runtimeKB = (runtimeBundle.size / 1024).toFixed(1);
printKV(
'Runtime',
`${path.join(path.dirname(output), runtimeBundle.outputFileName)} ${chalk.dim(`(${runtimeKB} KB, ${lowering.count} handler${lowering.count === 1 ? '' : 's'})`)}`,
);
}
console.log('');
} catch (error: any) {
if (flags.json) {
console.log(JSON.stringify({ success: false, error: error.message }));
this.exit(1);
}
console.log('');
printError(error.message || String(error));
this.error(error.message || String(error));
}
}
}