-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathassemblies.ts
More file actions
1373 lines (1192 loc) · 40.6 KB
/
assemblies.ts
File metadata and controls
1373 lines (1192 loc) · 40.6 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import EventEmitter from 'node:events'
import fs from 'node:fs'
import fsp from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import type { Readable, Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { setTimeout as delay } from 'node:timers/promises'
import tty from 'node:tty'
import { promisify } from 'node:util'
import { Command, Option } from 'clipanion'
import got from 'got'
import PQueue from 'p-queue'
import * as t from 'typanion'
import { z } from 'zod'
import { tryCatch } from '../../alphalib/tryCatch.ts'
import type { Steps, StepsInput } from '../../alphalib/types/template.ts'
import { stepsSchema } from '../../alphalib/types/template.ts'
import type { CreateAssemblyParams, ReplayAssemblyParams } from '../../apiTypes.ts'
import type { CreateAssemblyOptions, Transloadit } from '../../Transloadit.ts'
import { createReadStream, formatAPIError, streamToBuffer } from '../helpers.ts'
import type { IOutputCtl } from '../OutputCtl.ts'
import { ensureError, isErrnoException } from '../types.ts'
import { AuthenticatedCommand } from './BaseCommand.ts'
// --- From assemblies.ts: Schemas and interfaces ---
export interface AssemblyListOptions {
before?: string
after?: string
fields?: string[]
keywords?: string[]
pagesize?: number
}
export interface AssemblyGetOptions {
assemblies: string[]
}
interface AssemblyDeleteOptions {
assemblies: string[]
}
export interface AssemblyReplayOptions {
fields?: Record<string, string>
reparse?: boolean
steps?: string
notify_url?: string
assemblies: string[]
}
const AssemblySchema = z.object({
id: z.string(),
})
// --- Business logic functions (from assemblies.ts) ---
export function list(
output: IOutputCtl,
client: Transloadit,
{ before, after, fields, keywords }: AssemblyListOptions,
): Promise<void> {
const assemblies = client.streamAssemblies({
fromdate: after,
todate: before,
keywords,
})
assemblies.on('readable', () => {
const assembly: unknown = assemblies.read()
if (assembly == null) return
const parsed = AssemblySchema.safeParse(assembly)
if (!parsed.success) return
if (fields == null) {
output.print(parsed.data.id, assembly)
} else {
const assemblyRecord = assembly as Record<string, unknown>
output.print(fields.map((field) => assemblyRecord[field]).join(' '), assembly)
}
})
return new Promise<void>((resolve) => {
assemblies.on('end', resolve)
assemblies.on('error', (err: unknown) => {
output.error(formatAPIError(err))
resolve()
})
})
}
export async function get(
output: IOutputCtl,
client: Transloadit,
{ assemblies }: AssemblyGetOptions,
): Promise<void> {
for (const assembly of assemblies) {
await delay(1000)
const [err, result] = await tryCatch(client.getAssembly(assembly))
if (err) {
output.error(formatAPIError(err))
throw ensureError(err)
}
output.print(result, result)
}
}
async function deleteAssemblies(
output: IOutputCtl,
client: Transloadit,
{ assemblies }: AssemblyDeleteOptions,
): Promise<void> {
const promises = assemblies.map(async (assembly) => {
const [err] = await tryCatch(client.cancelAssembly(assembly))
if (err) {
output.error(formatAPIError(err))
}
})
await Promise.all(promises)
}
// Export with `delete` alias for tests (can't use `delete` as function name)
export { deleteAssemblies as delete }
export async function replay(
output: IOutputCtl,
client: Transloadit,
{ fields, reparse, steps, notify_url, assemblies }: AssemblyReplayOptions,
): Promise<void> {
if (steps) {
try {
const buf = await streamToBuffer(createReadStream(steps))
const parsed: unknown = JSON.parse(buf.toString())
const validated = stepsSchema.safeParse(parsed)
if (!validated.success) {
throw new Error(`Invalid steps format: ${validated.error.message}`)
}
await apiCall(validated.data)
} catch (err) {
const error = ensureError(err)
output.error(error.message)
}
} else {
await apiCall()
}
async function apiCall(stepsOverride?: Steps): Promise<void> {
const promises = assemblies.map(async (assembly) => {
const [err] = await tryCatch(
client.replayAssembly(assembly, {
reparse_template: reparse ? 1 : 0,
fields,
notify_url,
// Steps (validated) is assignable to StepsInput at runtime; cast for TS
steps: stepsOverride as ReplayAssemblyParams['steps'],
}),
)
if (err) {
output.error(formatAPIError(err))
}
})
await Promise.all(promises)
}
}
// --- From assemblies-create.ts: Helper classes and functions ---
interface NodeWatcher {
on(event: 'error', listener: (err: Error) => void): void
on(event: 'close', listener: () => void): void
on(event: 'change', listener: (evt: string, filename: string) => void): void
on(event: string, listener: (...args: unknown[]) => void): void
close(): void
}
type NodeWatchFn = (path: string, options?: { recursive?: boolean }) => NodeWatcher
let nodeWatch: NodeWatchFn | undefined
async function getNodeWatch(): Promise<NodeWatchFn> {
if (!nodeWatch) {
const mod = (await import('node-watch')) as unknown as { default: NodeWatchFn }
nodeWatch = mod.default
}
return nodeWatch
}
// workaround for determining mime-type of stdin
const stdinWithPath = process.stdin as unknown as { path: string }
stdinWithPath.path = '/dev/stdin'
interface OutStream extends Writable {
path?: string
mtime?: Date
}
interface Job {
in: Readable | null
out: OutStream | null
}
type OutstreamProvider = (inpath: string | null, indir?: string) => Promise<OutStream | null>
interface StreamRegistry {
[key: string]: OutStream | undefined
}
interface JobEmitterOptions {
recursive?: boolean
outstreamProvider: OutstreamProvider
streamRegistry: StreamRegistry
watch?: boolean
reprocessStale?: boolean
}
interface ReaddirJobEmitterOptions {
dir: string
streamRegistry: StreamRegistry
recursive?: boolean
outstreamProvider: OutstreamProvider
topdir?: string
}
interface SingleJobEmitterOptions {
file: string
streamRegistry: StreamRegistry
outstreamProvider: OutstreamProvider
}
interface WatchJobEmitterOptions {
file: string
streamRegistry: StreamRegistry
recursive?: boolean
outstreamProvider: OutstreamProvider
}
interface StatLike {
isDirectory(): boolean
}
const fstatAsync = promisify(fs.fstat)
async function myStat(
stdioStream: NodeJS.ReadStream | NodeJS.WriteStream,
filepath: string,
): Promise<fs.Stats> {
if (filepath === '-') {
const stream = stdioStream as NodeJS.ReadStream & { fd: number }
return await fstatAsync(stream.fd)
}
return await fsp.stat(filepath)
}
function dirProvider(output: string): OutstreamProvider {
return async (inpath, indir = process.cwd()) => {
if (inpath == null || inpath === '-') {
throw new Error('You must provide an input to output to a directory')
}
let relpath = path.relative(indir, inpath)
relpath = relpath.replace(/^(\.\.\/)+/, '')
const outpath = path.join(output, relpath)
const outdir = path.dirname(outpath)
await fsp.mkdir(outdir, { recursive: true })
const [, stats] = await tryCatch(fsp.stat(outpath))
const mtime = stats?.mtime ?? new Date(0)
const outstream = fs.createWriteStream(outpath) as OutStream
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
outstream.on('error', () => {})
outstream.mtime = mtime
return outstream
}
}
function fileProvider(output: string): OutstreamProvider {
const dirExistsP = fsp.mkdir(path.dirname(output), { recursive: true })
return async (_inpath) => {
await dirExistsP
if (output === '-') return process.stdout as OutStream
const [, stats] = await tryCatch(fsp.stat(output))
const mtime = stats?.mtime ?? new Date(0)
const outstream = fs.createWriteStream(output) as OutStream
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
outstream.on('error', () => {})
outstream.mtime = mtime
return outstream
}
}
function nullProvider(): OutstreamProvider {
return async (_inpath) => null
}
class MyEventEmitter extends EventEmitter {
protected hasEnded: boolean
constructor() {
super()
this.hasEnded = false
}
override emit(event: string | symbol, ...args: unknown[]): boolean {
if (this.hasEnded) return false
if (event === 'end' || event === 'error') {
this.hasEnded = true
return super.emit(event, ...args)
}
return super.emit(event, ...args)
}
}
class ReaddirJobEmitter extends MyEventEmitter {
constructor({
dir,
streamRegistry,
recursive,
outstreamProvider,
topdir = dir,
}: ReaddirJobEmitterOptions) {
super()
process.nextTick(() => {
this.processDirectory({ dir, streamRegistry, recursive, outstreamProvider, topdir }).catch(
(err) => {
this.emit('error', err)
},
)
})
}
private async processDirectory({
dir,
streamRegistry,
recursive,
outstreamProvider,
topdir,
}: ReaddirJobEmitterOptions & { topdir: string }): Promise<void> {
const files = await fsp.readdir(dir)
const pendingOperations: Promise<void>[] = []
for (const filename of files) {
const file = path.normalize(path.join(dir, filename))
pendingOperations.push(
this.processFile({ file, streamRegistry, recursive, outstreamProvider, topdir }),
)
}
await Promise.all(pendingOperations)
this.emit('end')
}
private async processFile({
file,
streamRegistry,
recursive = false,
outstreamProvider,
topdir,
}: {
file: string
streamRegistry: StreamRegistry
recursive?: boolean
outstreamProvider: OutstreamProvider
topdir: string
}): Promise<void> {
const stats = await fsp.stat(file)
if (stats.isDirectory()) {
if (recursive) {
await new Promise<void>((resolve, reject) => {
const subdirEmitter = new ReaddirJobEmitter({
dir: file,
streamRegistry,
recursive,
outstreamProvider,
topdir,
})
subdirEmitter.on('job', (job: Job) => this.emit('job', job))
subdirEmitter.on('error', (error: Error) => reject(error))
subdirEmitter.on('end', () => resolve())
})
}
} else {
const existing = streamRegistry[file]
if (existing) existing.end()
const outstream = await outstreamProvider(file, topdir)
streamRegistry[file] = outstream ?? undefined
const instream = fs.createReadStream(file)
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
instream.on('error', () => {})
this.emit('job', { in: instream, out: outstream })
}
}
}
class SingleJobEmitter extends MyEventEmitter {
constructor({ file, streamRegistry, outstreamProvider }: SingleJobEmitterOptions) {
super()
const normalizedFile = path.normalize(file)
const existing = streamRegistry[normalizedFile]
if (existing) existing.end()
outstreamProvider(normalizedFile).then((outstream) => {
streamRegistry[normalizedFile] = outstream ?? undefined
let instream: Readable | null
if (normalizedFile === '-') {
if (tty.isatty(process.stdin.fd)) {
instream = null
} else {
instream = process.stdin
}
} else {
instream = fs.createReadStream(normalizedFile)
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
instream.on('error', () => {})
}
process.nextTick(() => {
this.emit('job', { in: instream, out: outstream })
this.emit('end')
})
})
}
}
class InputlessJobEmitter extends MyEventEmitter {
constructor({
outstreamProvider,
}: { streamRegistry: StreamRegistry; outstreamProvider: OutstreamProvider }) {
super()
process.nextTick(() => {
outstreamProvider(null).then((outstream) => {
try {
this.emit('job', { in: null, out: outstream })
} catch (err) {
this.emit('error', err)
}
this.emit('end')
})
})
}
}
class NullJobEmitter extends MyEventEmitter {
constructor() {
super()
process.nextTick(() => this.emit('end'))
}
}
class WatchJobEmitter extends MyEventEmitter {
private watcher: NodeWatcher | null = null
constructor({ file, streamRegistry, recursive, outstreamProvider }: WatchJobEmitterOptions) {
super()
this.init({ file, streamRegistry, recursive, outstreamProvider }).catch((err) => {
this.emit('error', err)
})
// Clean up watcher on process exit signals
const cleanup = () => this.close()
process.once('SIGINT', cleanup)
process.once('SIGTERM', cleanup)
}
/** Close the file watcher and release resources */
close(): void {
if (this.watcher) {
this.watcher.close()
this.watcher = null
}
}
private async init({
file,
streamRegistry,
recursive,
outstreamProvider,
}: WatchJobEmitterOptions): Promise<void> {
const stats = await fsp.stat(file)
const topdir = stats.isDirectory() ? file : undefined
const watchFn = await getNodeWatch()
this.watcher = watchFn(file, { recursive })
this.watcher.on('error', (err: Error) => {
this.close()
this.emit('error', err)
})
this.watcher.on('close', () => this.emit('end'))
this.watcher.on('change', (_evt: string, filename: string) => {
const normalizedFile = path.normalize(filename)
this.handleChange(normalizedFile, topdir, streamRegistry, outstreamProvider).catch((err) => {
this.emit('error', err)
})
})
}
private async handleChange(
normalizedFile: string,
topdir: string | undefined,
streamRegistry: StreamRegistry,
outstreamProvider: OutstreamProvider,
): Promise<void> {
const stats = await fsp.stat(normalizedFile)
if (stats.isDirectory()) return
const existing = streamRegistry[normalizedFile]
if (existing) existing.end()
const outstream = await outstreamProvider(normalizedFile, topdir)
streamRegistry[normalizedFile] = outstream ?? undefined
const instream = fs.createReadStream(normalizedFile)
// Attach a no-op error handler to prevent unhandled errors if stream is destroyed
// before being consumed (e.g., due to output collision detection)
instream.on('error', () => {})
this.emit('job', { in: instream, out: outstream })
}
}
class MergedJobEmitter extends MyEventEmitter {
constructor(...jobEmitters: MyEventEmitter[]) {
super()
let ncomplete = 0
for (const jobEmitter of jobEmitters) {
jobEmitter.on('error', (err: Error) => this.emit('error', err))
jobEmitter.on('job', (job: Job) => this.emit('job', job))
jobEmitter.on('end', () => {
if (++ncomplete === jobEmitters.length) this.emit('end')
})
}
if (jobEmitters.length === 0) {
this.emit('end')
}
}
}
class ConcattedJobEmitter extends MyEventEmitter {
constructor(emitterFn: () => MyEventEmitter, ...emitterFns: (() => MyEventEmitter)[]) {
super()
const emitter = emitterFn()
emitter.on('error', (err: Error) => this.emit('error', err))
emitter.on('job', (job: Job) => this.emit('job', job))
if (emitterFns.length === 0) {
emitter.on('end', () => this.emit('end'))
} else {
emitter.on('end', () => {
const firstFn = emitterFns[0]
if (!firstFn) {
this.emit('end')
return
}
const restEmitter = new ConcattedJobEmitter(firstFn, ...emitterFns.slice(1))
restEmitter.on('error', (err: Error) => this.emit('error', err))
restEmitter.on('job', (job: Job) => this.emit('job', job))
restEmitter.on('end', () => this.emit('end'))
})
}
}
}
function detectConflicts(jobEmitter: EventEmitter): MyEventEmitter {
const emitter = new MyEventEmitter()
const outfileAssociations: Record<string, string> = {}
jobEmitter.on('end', () => emitter.emit('end'))
jobEmitter.on('error', (err: Error) => emitter.emit('error', err))
jobEmitter.on('job', (job: Job) => {
if (job.in == null || job.out == null) {
emitter.emit('job', job)
return
}
const inPath = (job.in as fs.ReadStream).path as string
const outPath = job.out.path as string
if (Object.hasOwn(outfileAssociations, outPath) && outfileAssociations[outPath] !== inPath) {
emitter.emit(
'error',
new Error(`Output collision between '${inPath}' and '${outfileAssociations[outPath]}'`),
)
} else {
outfileAssociations[outPath] = inPath
emitter.emit('job', job)
}
})
return emitter
}
function dismissStaleJobs(jobEmitter: EventEmitter): MyEventEmitter {
const emitter = new MyEventEmitter()
const pendingChecks: Promise<void>[] = []
jobEmitter.on('end', () => Promise.all(pendingChecks).then(() => emitter.emit('end')))
jobEmitter.on('error', (err: Error) => emitter.emit('error', err))
jobEmitter.on('job', (job: Job) => {
if (job.in == null || job.out == null) {
emitter.emit('job', job)
return
}
const inPath = (job.in as fs.ReadStream).path as string
const checkPromise = fsp
.stat(inPath)
.then((stats) => {
const inM = stats.mtime
const outM = job.out?.mtime ?? new Date(0)
if (outM <= inM) emitter.emit('job', job)
})
.catch(() => {
emitter.emit('job', job)
})
pendingChecks.push(checkPromise)
})
return emitter
}
function makeJobEmitter(
inputs: string[],
{
recursive,
outstreamProvider,
streamRegistry,
watch: watchOption,
reprocessStale,
}: JobEmitterOptions,
): MyEventEmitter {
const emitter = new EventEmitter()
const emitterFns: (() => MyEventEmitter)[] = []
const watcherFns: (() => MyEventEmitter)[] = []
async function processInputs(): Promise<void> {
for (const input of inputs) {
if (input === '-') {
emitterFns.push(
() => new SingleJobEmitter({ file: input, outstreamProvider, streamRegistry }),
)
watcherFns.push(() => new NullJobEmitter())
} else {
const stats = await fsp.stat(input)
if (stats.isDirectory()) {
emitterFns.push(
() =>
new ReaddirJobEmitter({ dir: input, recursive, outstreamProvider, streamRegistry }),
)
watcherFns.push(
() =>
new WatchJobEmitter({ file: input, recursive, outstreamProvider, streamRegistry }),
)
} else {
emitterFns.push(
() => new SingleJobEmitter({ file: input, outstreamProvider, streamRegistry }),
)
watcherFns.push(
() =>
new WatchJobEmitter({ file: input, recursive, outstreamProvider, streamRegistry }),
)
}
}
}
if (inputs.length === 0) {
emitterFns.push(() => new InputlessJobEmitter({ outstreamProvider, streamRegistry }))
}
startEmitting()
}
function startEmitting(): void {
let source: MyEventEmitter = new MergedJobEmitter(...emitterFns.map((f) => f()))
if (watchOption) {
source = new ConcattedJobEmitter(
() => source,
() => new MergedJobEmitter(...watcherFns.map((f) => f())),
)
}
source.on('job', (job: Job) => emitter.emit('job', job))
source.on('error', (err: Error) => emitter.emit('error', err))
source.on('end', () => emitter.emit('end'))
}
processInputs().catch((err) => {
emitter.emit('error', err)
})
const stalefilter = reprocessStale ? (x: EventEmitter) => x as MyEventEmitter : dismissStaleJobs
return stalefilter(detectConflicts(emitter))
}
export interface AssembliesCreateOptions {
steps?: string
template?: string
fields?: Record<string, string>
watch?: boolean
recursive?: boolean
inputs: string[]
output?: string | null
del?: boolean
reprocessStale?: boolean
singleAssembly?: boolean
concurrency?: number
}
const DEFAULT_CONCURRENCY = 5
// --- Main assembly create function ---
export async function create(
outputctl: IOutputCtl,
client: Transloadit,
{
steps,
template,
fields,
watch: watchOption,
recursive,
inputs,
output,
del,
reprocessStale,
singleAssembly,
concurrency = DEFAULT_CONCURRENCY,
}: AssembliesCreateOptions,
): Promise<{ results: unknown[]; hasFailures: boolean }> {
// Quick fix for https://github.com/transloadit/transloadify/issues/13
// Only default to stdout when output is undefined (not provided), not when explicitly null
let resolvedOutput = output
if (resolvedOutput === undefined && !process.stdout.isTTY) resolvedOutput = '-'
// Read steps file async before entering the Promise constructor
// We use StepsInput (the input type) rather than Steps (the transformed output type)
// to avoid zod adding default values that the API may reject
let stepsData: StepsInput | undefined
if (steps) {
const stepsContent = await fsp.readFile(steps, 'utf8')
const parsed: unknown = JSON.parse(stepsContent)
// Basic structural validation: must be an object with step names as keys
if (parsed == null || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('Invalid steps format: expected an object with step names as keys')
}
// Validate each step has a robot field
for (const [stepName, step] of Object.entries(parsed)) {
if (step == null || typeof step !== 'object' || Array.isArray(step)) {
throw new Error(`Invalid steps format: step '${stepName}' must be an object`)
}
if (!('robot' in step) || typeof (step as Record<string, unknown>).robot !== 'string') {
throw new Error(
`Invalid steps format: step '${stepName}' must have a 'robot' string property`,
)
}
}
stepsData = parsed as StepsInput
}
// Determine output stat async before entering the Promise constructor
let outstat: StatLike | undefined
if (resolvedOutput != null) {
const [err, stat] = await tryCatch(myStat(process.stdout, resolvedOutput))
if (err && (!isErrnoException(err) || err.code !== 'ENOENT')) throw err
outstat = stat ?? { isDirectory: () => false }
if (!outstat.isDirectory() && inputs.length !== 0) {
const firstInput = inputs[0]
if (firstInput) {
const firstInputStat = await myStat(process.stdin, firstInput)
if (inputs.length > 1 || firstInputStat.isDirectory()) {
const msg = 'Output must be a directory when specifying multiple inputs'
outputctl.error(msg)
throw new Error(msg)
}
}
}
}
return new Promise((resolve, reject) => {
const params: CreateAssemblyParams = (
stepsData ? { steps: stepsData as CreateAssemblyParams['steps'] } : { template_id: template }
) as CreateAssemblyParams
if (fields) {
params.fields = fields
}
const outstreamProvider: OutstreamProvider =
resolvedOutput == null
? nullProvider()
: outstat?.isDirectory()
? dirProvider(resolvedOutput)
: fileProvider(resolvedOutput)
const streamRegistry: StreamRegistry = {}
const emitter = makeJobEmitter(inputs, {
recursive,
watch: watchOption,
outstreamProvider,
streamRegistry,
reprocessStale,
})
// Use p-queue for concurrency management
const queue = new PQueue({ concurrency })
const results: unknown[] = []
let hasFailures = false
// AbortController to cancel all in-flight createAssembly calls when an error occurs
const abortController = new AbortController()
// Helper to process a single assembly job
async function processAssemblyJob(
inPath: string | null,
outPath: string | null,
outMtime: Date | undefined,
): Promise<unknown> {
outputctl.debug(`PROCESSING JOB ${inPath ?? 'null'} ${outPath ?? 'null'}`)
// Create fresh streams for this job
const inStream = inPath ? fs.createReadStream(inPath) : null
inStream?.on('error', () => {})
const outStream = outPath ? (fs.createWriteStream(outPath) as OutStream) : null
outStream?.on('error', () => {})
if (outStream) outStream.mtime = outMtime
let superceded = false
if (outStream != null) {
outStream.on('finish', () => {
superceded = true
})
}
const createOptions: CreateAssemblyOptions = {
params,
signal: abortController.signal,
}
if (inStream != null) {
createOptions.uploads = { in: inStream }
}
const result = await client.createAssembly(createOptions)
if (superceded) return undefined
const assemblyId = result.assembly_id
if (!assemblyId) throw new Error('No assembly_id in result')
const assembly = await client.awaitAssemblyCompletion(assemblyId, {
signal: abortController.signal,
onPoll: () => {
if (superceded) return false
return true
},
onAssemblyProgress: (status) => {
outputctl.debug(`Assembly status: ${status.ok}`)
},
})
if (superceded) return undefined
if (assembly.error || (assembly.ok && assembly.ok !== 'ASSEMBLY_COMPLETED')) {
const msg = `Assembly failed: ${assembly.error || assembly.message} (Status: ${assembly.ok})`
outputctl.error(msg)
throw new Error(msg)
}
if (!assembly.results) throw new Error('No results in assembly')
const resultsKeys = Object.keys(assembly.results)
const firstKey = resultsKeys[0]
if (!firstKey) throw new Error('No results in assembly')
const firstResult = assembly.results[firstKey]
if (!firstResult || !firstResult[0]) throw new Error('No results in assembly')
const resulturl = firstResult[0].url
if (outStream != null && resulturl && !superceded) {
outputctl.debug('DOWNLOADING')
const [dlErr] = await tryCatch(
pipeline(got.stream(resulturl, { signal: abortController.signal }), outStream),
)
if (dlErr) {
if (dlErr.name !== 'AbortError') {
outputctl.error(dlErr.message)
throw dlErr
}
}
}
outputctl.debug(`COMPLETED ${inPath ?? 'null'} ${outPath ?? 'null'}`)
if (del && inPath) {
await fsp.unlink(inPath)
}
return assembly
}
if (singleAssembly) {
// Single-assembly mode: collect file paths, then create one assembly with all inputs
// We close streams immediately to avoid exhausting file descriptors with many files
const collectedPaths: string[] = []
emitter.on('job', (job: Job) => {
if (job.in != null) {
const inPath = (job.in as fs.ReadStream).path as string
outputctl.debug(`COLLECTING JOB ${inPath}`)
collectedPaths.push(inPath)
// Close the stream immediately to avoid file descriptor exhaustion
;(job.in as fs.ReadStream).destroy()
outputctl.debug(`STREAM CLOSED ${inPath}`)
}
})
emitter.on('error', (err: Error) => {
abortController.abort()
queue.clear()
outputctl.error(err)
reject(err)
})
emitter.on('end', async () => {
if (collectedPaths.length === 0) {
resolve({ results: [], hasFailures: false })
return
}
// Build uploads object, creating fresh streams for each file
const uploads: Record<string, Readable> = {}
const inputPaths: string[] = []
for (const inPath of collectedPaths) {
const basename = path.basename(inPath)
let key = basename
let counter = 1
while (key in uploads) {
key = `${path.parse(basename).name}_${counter}${path.parse(basename).ext}`
counter++
}
uploads[key] = fs.createReadStream(inPath)
inputPaths.push(inPath)
}
outputctl.debug(`Creating single assembly with ${Object.keys(uploads).length} files`)
try {
const assembly = await queue.add(async () => {
const createOptions: CreateAssemblyOptions = {
params,
signal: abortController.signal,
}
if (Object.keys(uploads).length > 0) {
createOptions.uploads = uploads
}
const result = await client.createAssembly(createOptions)
const assemblyId = result.assembly_id
if (!assemblyId) throw new Error('No assembly_id in result')
const asm = await client.awaitAssemblyCompletion(assemblyId, {
signal: abortController.signal,
onAssemblyProgress: (status) => {
outputctl.debug(`Assembly status: ${status.ok}`)
},
})
if (asm.error || (asm.ok && asm.ok !== 'ASSEMBLY_COMPLETED')) {
const msg = `Assembly failed: ${asm.error || asm.message} (Status: ${asm.ok})`
outputctl.error(msg)
throw new Error(msg)
}
// Download all results
if (asm.results && resolvedOutput != null) {
for (const [stepName, stepResults] of Object.entries(asm.results)) {
for (const stepResult of stepResults) {
const resultUrl = stepResult.url
if (!resultUrl) continue
let outPath: string
if (outstat?.isDirectory()) {
outPath = path.join(resolvedOutput, stepResult.name || `${stepName}_result`)
} else {
outPath = resolvedOutput
}
outputctl.debug(`DOWNLOADING ${stepResult.name} to ${outPath}`)
const [dlErr] = await tryCatch(
pipeline(
got.stream(resultUrl, { signal: abortController.signal }),
fs.createWriteStream(outPath),