-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathrenderer.ts
More file actions
279 lines (251 loc) · 10.2 KB
/
Copy pathrenderer.ts
File metadata and controls
279 lines (251 loc) · 10.2 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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
import path from 'node:path';
import { createDeck, type DeckClient } from '@deckops/sdk';
import { credentialsRejected, DeckRenderError } from '../errors/index.js';
import { CloudEngine } from '../engines/cloud.js';
import { validateEngineOutput } from '../engines/validate.js';
import type { EngineOutput, RenderEngine } from '../engines/engine.js';
import { inputBaseName, resolveInput } from '../input/resolve.js';
import { DEFAULT_EXTENSION } from '../output/naming.js';
import { writeArtifacts } from '../output/writer.js';
import {
describeCredentialOrigin,
hasCredentials,
resolveCredentials,
type CredentialOverrides,
} from '../config/credentials.js';
import type { RenderArtifact, RenderOptions, RenderResult } from '../types.js';
import { parsePageSelection } from './pages.js';
import { buildPlan } from './plan.js';
import { validateRenderOptions } from './validation.js';
export interface RendererOptions extends CredentialOverrides {
/** Pre-built DeckOps client. Supplying one skips credential resolution. */
client?: DeckClient;
/** Custom engine. Overrides the built-in cloud engine. */
engine?: RenderEngine;
/** Called with non-fatal notices, e.g. a snapped resolution. */
onWarning?: (message: string) => void;
/** Interactive login hook, invoked by the SDK on a 401. */
onUnauthorized?: () => Promise<{ token: string; spaceId?: string } | string>;
/** Checkout hook, invoked by the SDK on a 402. */
onPaymentRequired?: () => Promise<void>;
}
export interface Renderer {
render(options: RenderOptions): Promise<RenderResult>;
}
export function createRenderer(rendererOptions: RendererOptions = {}): Renderer {
return {
render: (options) => runRender(options, rendererOptions),
};
}
/** One-shot render. Equivalent to `createRenderer(opts).render(opts)`. */
export function render(options: RenderOptions & RendererOptions): Promise<RenderResult> {
return runRender(options, options);
}
async function runRender(options: RenderOptions, rendererOptions: RendererOptions): Promise<RenderResult> {
validateRenderOptions(options);
const startedAt = Date.now();
const warn = rendererOptions.onWarning ?? (() => undefined);
options.onProgress?.({ phase: 'resolve', message: `Resolving ${options.input}` });
const input = await resolveInput(options.input, options.from ? { from: options.from } : {});
const pages = options.pages ? parsePageSelection(options.pages) : undefined;
options.onProgress?.({ phase: 'plan', message: 'Building render plan' });
const { plan, warnings } = buildPlan({
source: input.format,
target: options.format ?? 'image',
...(options.imageFormat ? { imageFormat: options.imageFormat } : {}),
...(options.width !== undefined ? { width: options.width } : {}),
...(options.scale !== undefined ? { scale: options.scale } : {}),
...(options.quality ? { quality: options.quality } : {}),
...(pages ? { pages } : {}),
...(options.embedFonts !== undefined ? { embedFonts: options.embedFonts } : {}),
...(options.soft ? { soft: options.soft } : {}),
});
for (const warning of warnings) {
warn(warning.message);
}
if (plan.caveat) {
warn(plan.caveat);
}
if (plan.kind === 'derived') {
const route = plan.steps.map((step) => step.task).join(' → ');
warn(`via ${route} (${plan.steps.length} steps)`);
}
const executed = await executePlan(plan, input, options, rendererOptions, warn);
options.onProgress?.({ phase: 'write', message: 'Writing artifacts' });
const written = await writeArtifacts(executed.artifacts, {
...(options.out ? { out: options.out } : {}),
baseName: inputBaseName(input),
baseDir: input.kind === 'file' && input.path ? path.dirname(input.path) : process.cwd(),
...(options.onProgress ? { onProgress: options.onProgress } : {}),
});
return {
ok: true,
input: input.display,
format: plan.target,
engine: executed.engine,
route: plan.steps.map((step) => step.task),
pages: executed.totalPages,
outputs: written.entries,
durationMs: Date.now() - startedAt,
...(plan.caveat ? { caveat: plan.caveat } : {}),
};
}
async function executePlan(
plan: ReturnType<typeof buildPlan>['plan'],
input: Awaited<ReturnType<typeof resolveInput>>,
options: RenderOptions,
rendererOptions: RendererOptions,
warn: (message: string) => void
): Promise<EngineOutput & { engine: string }> {
// Passthrough: the input is already in the target format, so no backend work
// and no upload — just hand the local file to the writer.
if (plan.kind === 'passthrough') {
if (!input.path) {
throw DeckRenderError.usage('Passthrough requires a local file input.');
}
const artifact: RenderArtifact = {
page: 1,
source: input.path,
ext: DEFAULT_EXTENSION[plan.target],
};
return { artifacts: [artifact], totalPages: 1, engine: 'passthrough' };
}
// Everything else renders in the cloud. DeckRender ships no local renderer:
// a format the backend cannot convert is reported as unsupported rather than
// approximated here.
const selection: EngineSelection = rendererOptions.engine
? { engine: rendererOptions.engine }
: await createCloudEngine(options, rendererOptions);
const { engine } = selection;
if (!engine.supports(plan)) {
throw DeckRenderError.render(`The ${engine.name} engine cannot execute this route.`);
}
const context = {
input,
...(options.onProgress ? { onProgress: options.onProgress } : {}),
};
try {
return await run(engine, plan, context);
} catch (error) {
const guest = credentialsRejected(error) ? selection.guestFallback?.() : undefined;
if (!guest) {
throw error;
}
warn(
`The backend rejected the ${guest.origin}, so it is being ignored and the render retried ` +
'in guest mode, which is rate-limited. Run `deckrender auth login` for full access, or ' +
'`deckrender config list` to see where that credential came from.'
);
return run(guest.engine, plan, context);
}
}
async function run(
engine: RenderEngine,
plan: ReturnType<typeof buildPlan>['plan'],
context: { input: Awaited<ReturnType<typeof resolveInput>>; onProgress?: RenderOptions['onProgress'] }
): Promise<EngineOutput & { engine: string }> {
const rawOutput: unknown = await engine.execute(plan, context);
const output = validateEngineOutput(engine.name, rawOutput);
return { ...output, engine: engine.name };
}
interface EngineSelection {
engine: RenderEngine;
/**
* Rebuild the engine with no credentials at all.
*
* Present only when credentials were sent in the first place, and fires at
* most once. Returns the origin of the credential being dropped so the
* warning can name the file or variable to clean up.
*/
guestFallback?: () => { engine: RenderEngine; origin: string } | undefined;
}
/**
* Build the cloud engine, and the guest engine to fall back to.
*
* A credential the backend rejects is not a credential: the render continues as
* a guest rather than failing, because leftover state on a machine — an expired
* `deckrender auth login`, a token another DeckFlow tool wrote — must not break
* the promise that rendering works with no setup at all. The warning names what
* was dropped, so this is never silent.
*
* The interactive login therefore hangs off the *guest* client, not the
* credentialed one: a bad credential is answered with guest mode, and only a
* backend that refuses guests too is worth interrupting the user for.
*/
async function createCloudEngine(
options: RenderOptions,
rendererOptions: RendererOptions
): Promise<EngineSelection> {
const timeout = options.timeout !== undefined ? { timeout: options.timeout } : {};
if (rendererOptions.client) {
// A caller-supplied client owns its own credentials, so there is nothing
// here to second-guess and nothing to fall back to.
return {
engine: new CloudEngine({ client: rendererOptions.client, authenticated: true, ...timeout }),
};
}
const credentials = await resolveCredentials(rendererOptions);
/**
* An engine carrying nothing but the API base.
*
* The backend treats a credential-free request as a rate-limited guest and
* parks its tasks until they are started explicitly, which is what
* `authenticated: false` tells the engine to do. A login part-way through
* flips that, so the flag is read live rather than captured — starting a task
* the backend already started fails.
*/
const guestEngine = (): RenderEngine => {
let authenticated = false;
const onUnauthorized = rendererOptions.onUnauthorized
? async () => {
const authorization = await rendererOptions.onUnauthorized!();
authenticated = true;
return authorization;
}
: undefined;
return new CloudEngine({
client: createDeck({
root: credentials.apiBase,
...(onUnauthorized ? { onUnauthorized } : {}),
...(rendererOptions.onPaymentRequired
? { onPaymentRequired: rendererOptions.onPaymentRequired }
: {}),
}),
authenticated: false,
isAuthenticated: () => authenticated,
...timeout,
});
};
// Nothing to send: this is guest mode from the start, with nothing to drop.
if (!hasCredentials(credentials)) {
return { engine: guestEngine() };
}
const client = createDeck({
root: credentials.apiBase,
...(credentials.token ? { token: credentials.token } : {}),
...(credentials.apiKey ? { apiKey: credentials.apiKey } : {}),
...(credentials.spaceId ? { spaceId: credentials.spaceId } : {}),
...(rendererOptions.onPaymentRequired ? { onPaymentRequired: rendererOptions.onPaymentRequired } : {}),
});
let dropped = false;
return {
engine: new CloudEngine({
client,
authenticated: true,
credentialOrigin: () => describeCredentialOrigin(credentials),
...timeout,
}),
guestFallback: () => {
if (dropped) {
return undefined;
}
dropped = true;
// The spaceId belongs to the rejected credential's workspace, so it is
// left behind with it — sending it as a guest earns a 403.
return {
engine: guestEngine(),
origin: describeCredentialOrigin(credentials) ?? 'stored credential',
};
},
};
}