All files inputFiles.ts

86.07% Statements 241/280
73.1% Branches 174/238
97.72% Functions 43/44
90.61% Lines 222/245

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                      43x 47x   43x 28x     28x     43x 1x   1x 1x         43x         24x 24x   26x 24x 2x         43x   43x 1x 1x 1x 1x 1x 1x     43x 15x 15x 15x 15x             43x 22x   43x 20x 20x 20x 20x     43x   43x 11x           43x 5x 5x           5x 4x     1x 1x       1x 1x       2x 2x       2x     43x   43x 43x 43x 43x 96x 24x 24x 24x 19x 19x 18x 18x 18x 18x 18x 17x   19x 6x 6x 5x 5x 5x 1x   4x 4x 4x   13x             43x 12x 12x 12x     43x     22x   22x     22x     22x 5x     17x   17x           20x 3x     14x       17x                                                   14x     1x       2x                                                                                           2x                           2x         1x             2x           1x       1x     2x 2x 2x             1x             14x           43x 3x     43x 4x   4x 4x 3x 3x   1x       43x                         19x   19x 19x 13x 3x 3x     3x     19x 21x 21x     21x   13x     13x   21x               21x     13x 11x             13x     11x 21x 2x 2x 2x     2x 2x     9x 1x 1x     8x 4x 4x   4x       4x 1x     2x     43x                             23x   23x 23x 23x 23x   23x       23x 1x                 23x 23x 23x 23x 23x 23x 23x   23x 23x 24x 21x 21x 21x   24x     23x 23x 28x 28x 1x 1x   27x 7x 1x 1x 1x     6x 6x     6x 5x 5x 5x 5x 5x   1x   6x   20x 20x 20x   20x   20x 1x 1x 1x 1x 1x     19x 19x       20x 19x 19x             5x       15x 15x     8x 1x 1x 1x 1x               1x           8x              
import type { LookupAddress, LookupOptions } from 'node:dns'
import type { LookupFunction } from 'node:net'
import type { Readable } from 'node:stream'
 
import type { EntryObject, IPFamily } from 'cacheable-lookup'
import type { Input as IntoStreamInput } from 'into-stream'
 
import type { CreateAssemblyParams } from './apiTypes.ts'
 
import * as dnsPromises from 'node:dns/promises'
import { createWriteStream } from 'node:fs'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { isIP } from 'node:net'
import { tmpdir } from 'node:os'
import { basename, join, parse } from 'node:path'
import { Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
 
import got from 'got'
 
import { ensureUniqueCounterValue } from './ensureUniqueCounter.ts'
 
export type InputFile =
  | {
      kind: 'path'
      field: string
      path: string
    }
  | {
      kind: 'base64'
      field: string
      base64: string
      filename: string
      contentType?: string
    }
  | {
      kind: 'url'
      field: string
      url: string
      filename?: string
      contentType?: string
    }
 
export type UploadInput = Readable | IntoStreamInput
 
export type Base64Strategy = 'buffer' | 'tempfile'
export type UrlStrategy = 'import' | 'download' | 'import-if-present'
 
export type PrepareInputFilesOptions = {
  inputFiles?: InputFile[]
  params?: CreateAssemblyParams
  fields?: Record<string, unknown>
  base64Strategy?: Base64Strategy
  urlStrategy?: UrlStrategy
  maxBase64Bytes?: number
  allowPrivateUrls?: boolean
  /** Abort once all URL downloads of this call exceed this many bytes together. */
  maxUrlDownloadBytes?: number
  /** Abort a URL download (DNS checks and redirects included) after this many milliseconds. */
  urlDownloadTimeoutMs?: number
  /**
   * Awaited before each URL input is downloaded locally (not for `/http/import`), so a caller can
   * vouch for the requester first; rejecting aborts preparation.
   */
  beforeUrlDownload?: () => Promise<void>
  tempDir?: string
}
 
export type PrepareInputFilesResult = {
  params: CreateAssemblyParams
  files: Record<string, string>
  uploads: Record<string, UploadInput>
  cleanup: Array<() => Promise<void>>
}
 
const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null
 
const ensureUnique = (field: string, used: Set<string>): void => {
  Iif (used.has(field)) {
    throw new Error(`Duplicate file field: ${field}`)
  }
  used.add(field)
}
 
const ensureUniqueStepName = async (baseName: string, used: Set<string>): Promise<string> =>
  await ensureUniqueCounterValue({
    initialValue: baseName,
    isTaken: (candidate) => used.has(candidate),
    reserve: (candidate) => used.add(candidate),
    nextValue: (counter) => `${baseName}_${counter}`,
    scope: used,
  })
 
const ensureUniqueTempFilePath = async (
  root: string,
  filename: string,
  used: Set<string>,
): Promise<string> => {
  const parsedFilename = parse(basename(filename))
  return await ensureUniqueCounterValue({
    initialValue: join(root, parsedFilename.base),
    isTaken: (candidate) => used.has(candidate),
    reserve: (candidate) => used.add(candidate),
    nextValue: (counter) => join(root, `${parsedFilename.name}-${counter}${parsedFilename.ext}`),
    scope: used,
  })
}
 
const decodeBase64 = (value: string): Buffer => Buffer.from(value, 'base64')
 
const estimateBase64DecodedBytes = (value: string): number => {
  const trimmed = value.trim()
  Iif (!trimmed) return 0
  let padding = 0
  Iif (trimmed.endsWith('==')) padding = 2
  else Iif (trimmed.endsWith('=')) padding = 1
  return Math.floor((trimmed.length * 3) / 4) - padding
}
 
const getFilenameFromUrl = (value: string): string | null => {
  try {
    const pathname = new URL(value).pathname
    const base = basename(pathname)
    Eif (base && base !== '/' && base !== '.') return base
  } catch {
    return null
  }
  return null
}
 
const isHttpImportStep = (value: unknown): value is Record<string, unknown> =>
  isRecord(value) && value.robot === '/http/import'
 
const findImportStepName = (field: string, steps: Record<string, unknown>): string | null => {
  Iif (isHttpImportStep(steps[field])) return field
  const matches = Object.entries(steps).filter(([, step]) => isHttpImportStep(step))
  Iif (matches.length === 1) return matches[0]?.[0] ?? null
  return null
}
 
const MAX_URL_REDIRECTS = 10
 
const isRedirectStatusCode = (statusCode: number): boolean =>
  statusCode === 301 ||
  statusCode === 302 ||
  statusCode === 303 ||
  statusCode === 307 ||
  statusCode === 308
 
const ipv4FromMappedIpv6 = (address: string): string | null => {
  const lowerAddress = address.toLowerCase()
  const mappedPrefix = lowerAddress.startsWith('::ffff:')
    ? '::ffff:'
    : lowerAddress.startsWith('0:0:0:0:0:ffff:')
      ? '0:0:0:0:0:ffff:'
      : null
 
  if (mappedPrefix == null) {
    return null
  }
 
  const mappedValue = lowerAddress.slice(mappedPrefix.length)
  Iif (mappedValue.includes('.')) {
    return mappedValue
  }
 
  const segments = mappedValue.split(':')
  Iif (segments.length !== 2) {
    return null
  }
 
  const values = segments.map((segment) => Number.parseInt(segment, 16))
  Iif (values.some((value) => Number.isNaN(value) || value < 0 || value > 0xffff)) {
    return null
  }
 
  return values.flatMap((value) => [(value >> 8) & 0xff, value & 0xff]).join('.')
}
 
const isPrivateIp = (address: string): boolean => {
  const normalizedAddress =
    address.startsWith('[') && address.endsWith(']') ? address.slice(1, -1) : address
  Iif (normalizedAddress === 'localhost') return true
  const family = isIP(normalizedAddress)
  if (family === 4) {
    const parts = normalizedAddress.split('.').map((chunk) => Number(chunk))
    const [a, b] = parts
    Iif (a === 10) return true
    if (a === 127) return true
    Iif (a === 0) return true
    if (a === 100 && b >= 64 && b <= 127) return true
    Iif (a === 169 && b === 254) return true
    Iif (a === 172 && b >= 16 && b <= 31) return true
    Iif (a === 192 && b === 0 && parts[2] === 0) return true
    Iif (a === 192 && b === 168) return true
    if (a === 198 && (b === 18 || b === 19)) return true
    return false
  }
  if (family === 6) {
    const normalized = normalizedAddress.toLowerCase().split('%')[0]
    if (normalized === '::1' || normalized === '0:0:0:0:0:0:0:1') return true
    Iif (normalized === '::' || normalized === '0:0:0:0:0:0:0:0') return true
    const mappedAddress = ipv4FromMappedIpv6(normalized)
    if (mappedAddress != null && isPrivateIp(mappedAddress)) {
      return true
    }
    Iif (normalized.startsWith('fe80:')) return true
    Iif (normalized.startsWith('fc') || normalized.startsWith('fd')) return true
    return false
  }
  return false
}
 
/**
 * Names a URL in error messages without its query or fragment: input URLs are often presigned
 * (ChatGPT attachments, S3), and these messages reach logs and model-visible tool results.
 */
const describeUrl = (value: string): string => {
  Iif (!URL.canParse(value)) return '[unparseable URL]'
  const url = new URL(value)
  return `${url.origin}${url.pathname}`
}
 
export const resolvePublicDownloadAddresses = async (
  value: string,
): Promise<Array<{ address: string; family: 4 | 6 }>> => {
  const parsed = new URL(value)
  const hostname =
    parsed.hostname.startsWith('[') && parsed.hostname.endsWith(']')
      ? parsed.hostname.slice(1, -1)
      : parsed.hostname
  Iif (!['http:', 'https:'].includes(parsed.protocol)) {
    throw new Error(`URL downloads are limited to http/https: ${describeUrl(value)}`)
  }
  if (isPrivateIp(hostname)) {
    throw new Error(`URL downloads are limited to public hosts: ${describeUrl(value)}`)
  }
 
  const literalFamily = isIP(hostname)
  const resolvedAddresses =
    literalFamily !== 0
      ? [{ address: hostname, family: literalFamily as 4 | 6 }]
      : await dnsPromises.lookup(hostname, {
          all: true,
          verbatim: true,
        })
  if (resolvedAddresses.some((address) => isPrivateIp(address.address))) {
    throw new Error(`URL downloads are limited to public hosts: ${describeUrl(value)}`)
  }
 
  Iif (resolvedAddresses.length === 0) {
    throw new Error(`Unable to resolve URL hostname: ${describeUrl(value)}`)
  }
 
  return resolvedAddresses.map((address) => ({
    address: address.address,
    family: address.family as 4 | 6,
  }))
}
 
type PinnedDnsLookup = LookupFunction & {
  (
    hostname: string,
    options: LookupOptions & { all: true },
    callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray<EntryObject>) => void,
  ): void
  (
    hostname: string,
    family: IPFamily,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  (
    hostname: string,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
}
 
export function createPinnedDnsLookup(
  validatedAddresses: Array<{ address: string; family: 4 | 6 }>,
): PinnedDnsLookup {
  const pinnedAddresses = [...validatedAddresses]
 
  function pickAddress(family?: IPFamily): { address: string; family: 4 | 6 } | null {
    Iif (family == null) {
      return pinnedAddresses[0] ?? null
    }
 
    return pinnedAddresses.find((address) => address.family === family) ?? null
  }
 
  function pinnedDnsLookup(
    _hostname: string,
    family: IPFamily,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    options: { all: true },
    callback: (error: NodeJS.ErrnoException | null, result: ReadonlyArray<EntryObject>) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    options: LookupOptions,
    callback: (
      error: NodeJS.ErrnoException | null,
      address: string | LookupAddress[],
      family?: number,
    ) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    options: object,
    callback: (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void,
  ): void
  function pinnedDnsLookup(
    _hostname: string,
    familyOrCallback:
      | IPFamily
      | LookupOptions
      | ((error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void),
    callback?:
      | ((error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void)
      | ((error: NodeJS.ErrnoException | null, result: ReadonlyArray<EntryObject>) => void)
      | ((
          error: NodeJS.ErrnoException | null,
          address: string | LookupAddress[],
          family?: number,
        ) => void),
  ): void {
    Iif (typeof familyOrCallback === 'function') {
      const address = pickAddress()
      if (address == null) {
        familyOrCallback(
          new Error('No validated addresses available') as NodeJS.ErrnoException,
          '',
          4,
        )
        return
      }
      familyOrCallback(null, address.address, address.family)
      return
    }
 
    if (
      typeof familyOrCallback === 'object' &&
      familyOrCallback != null &&
      'all' in familyOrCallback
    ) {
      ;(
        callback as (
          error: NodeJS.ErrnoException | null,
          result: ReadonlyArray<EntryObject>,
        ) => void
      )(
        null,
        pinnedAddresses.map((address) => ({
          address: address.address,
          family: address.family,
          expires: 0,
        })),
      )
      return
    }
 
    const requestedFamily =
      typeof familyOrCallback === 'object' && familyOrCallback != null
        ? familyOrCallback.family
        : familyOrCallback
    const family = requestedFamily === 4 || requestedFamily === 6 ? requestedFamily : undefined
    const address = pickAddress(family)
    Iif (address == null) {
      ;(
        callback as (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void
      )(new Error('No validated addresses available') as NodeJS.ErrnoException, '', family ?? 4)
      return
    }
 
    ;(callback as (error: NodeJS.ErrnoException | null, address: string, family: IPFamily) => void)(
      null,
      address.address,
      address.family,
    )
  }
 
  return pinnedDnsLookup as PinnedDnsLookup
}
 
/** A budget shared by every URL download of one `prepareInputFiles` call. */
type DownloadBudget = { totalBytes: number; remainingBytes: number }
 
const budgetExceeded = (budget: DownloadBudget, url: string): Error =>
  new Error(`URL downloads exceed ${budget.totalBytes} bytes: ${describeUrl(url)}`)
 
/** Errors once the budget is used up, so temp files stay bounded while they stream in. */
const limitDownloadBytes = (budget: DownloadBudget, url: string): Transform =>
  new Transform({
    transform(chunk: Buffer, _encoding, callback) {
      budget.remainingBytes -= chunk.length
      if (budget.remainingBytes < 0) {
        callback(budgetExceeded(budget, url))
        return
      }
      callback(null, chunk)
    },
  })
 
const downloadUrlToFile = async ({
  allowPrivateUrls,
  filePath,
  url,
  budget,
  timeoutMs,
}: {
  allowPrivateUrls: boolean
  filePath: string
  url: string
  budget?: DownloadBudget
  timeoutMs?: number
}): Promise<void> => {
  let currentUrl = url
  // One deadline for the whole download, so DNS checks and redirects cannot each restart it.
  const deadline = timeoutMs === undefined ? undefined : Date.now() + timeoutMs
  const remainingMs = (): number | undefined => {
    if (deadline === undefined) return undefined
    const remaining = deadline - Date.now()
    Iif (remaining <= 0) {
      throw new Error(`URL download timed out after ${timeoutMs} ms: ${describeUrl(url)}`)
    }
    return remaining
  }
 
  for (let redirectCount = 0; redirectCount <= MAX_URL_REDIRECTS; redirectCount += 1) {
    let validatedAddresses: Array<{ address: string; family: 4 | 6 }> | null = null
    Eif (!allowPrivateUrls) {
      // Not raced against the deadline: the system resolver bounds each lookup with its own
      // short timeout and no bytes are transferred, so checking the clock right after suffices.
      validatedAddresses = await resolvePublicDownloadAddresses(currentUrl)
    }
    const requestTimeoutMs = remainingMs()
 
    const dnsLookup: LookupFunction | undefined =
      validatedAddresses == null ? undefined : createPinnedDnsLookup(validatedAddresses)
 
    const responseStream = got.stream(currentUrl, {
      dnsLookup,
      followRedirect: false,
      retry: { limit: 0 },
      throwHttpErrors: false,
      ...(requestTimeoutMs === undefined ? {} : { timeout: { request: requestTimeoutMs } }),
    })
 
    const response = await new Promise<
      Readable & { headers: Record<string, string>; statusCode?: number }
    >((resolvePromise, reject) => {
      responseStream.once('response', (incomingResponse) => {
        resolvePromise(
          incomingResponse as Readable & {
            headers: Record<string, string>
            statusCode?: number
          },
        )
      })
      responseStream.once('error', reject)
    })
 
    const statusCode = response.statusCode ?? 0
    if (isRedirectStatusCode(statusCode)) {
      responseStream.destroy()
      const location = response.headers.location
      Iif (location == null) {
        throw new Error(`Redirect response missing Location header: ${describeUrl(currentUrl)}`)
      }
      currentUrl = new URL(location, currentUrl).toString()
      continue
    }
 
    if (statusCode >= 400) {
      responseStream.destroy()
      throw new Error(`Failed to download URL: ${describeUrl(currentUrl)} (${statusCode})`)
    }
 
    if (budget === undefined) {
      await pipeline(responseStream, createWriteStream(filePath))
      return
    }
    Iif (Number(response.headers['content-length']) > budget.remainingBytes) {
      responseStream.destroy()
      throw budgetExceeded(budget, url)
    }
    await pipeline(responseStream, limitDownloadBytes(budget, url), createWriteStream(filePath))
    return
  }
 
  throw new Error(`Too many redirects while downloading URL input: ${describeUrl(url)}`)
}
 
export const prepareInputFiles = async (
  options: PrepareInputFilesOptions = {},
): Promise<PrepareInputFilesResult> => {
  const {
    inputFiles = [],
    params = {},
    fields,
    base64Strategy = 'buffer',
    urlStrategy = 'import',
    maxBase64Bytes,
    allowPrivateUrls = true,
    maxUrlDownloadBytes,
    urlDownloadTimeoutMs,
    beforeUrlDownload,
    tempDir,
  } = options
 
  let nextParams: CreateAssemblyParams = { ...params }
  const files: Record<string, string> = {}
  const uploads: Record<string, UploadInput> = {}
  const cleanup: Array<() => Promise<void>> = []
  const downloadBudget: DownloadBudget | undefined =
    maxUrlDownloadBytes === undefined
      ? undefined
      : { totalBytes: maxUrlDownloadBytes, remainingBytes: maxUrlDownloadBytes }
 
  if (fields && Object.keys(fields).length > 0) {
    nextParams = {
      ...nextParams,
      fields: {
        ...(isRecord(nextParams.fields) ? nextParams.fields : {}),
        ...fields,
      },
    }
  }
 
  const steps = isRecord(nextParams.steps) ? { ...nextParams.steps } : {}
  const usedSteps = new Set(Object.keys(steps))
  const usedFields = new Set<string>()
  const usedTempPaths = new Set<string>()
  const importUrlsByStep = new Map<string, string[]>()
  const importStepNames = Object.keys(steps).filter((name) => isHttpImportStep(steps[name]))
  const sharedImportStep = importStepNames.length === 1 ? importStepNames[0] : null
 
  let tempRoot: string | null = null
  const ensureTempRoot = async (): Promise<string> => {
    if (!tempRoot) {
      const root = await mkdtemp(join(tempDir ?? tmpdir(), 'transloadit-input-'))
      tempRoot = root
      cleanup.push(() => rm(root, { recursive: true, force: true }))
    }
    return tempRoot
  }
 
  try {
    for (const file of inputFiles) {
      ensureUnique(file.field, usedFields)
      if (file.kind === 'path') {
        files[file.field] = file.path
        continue
      }
      if (file.kind === 'base64') {
        if (maxBase64Bytes) {
          const estimated = estimateBase64DecodedBytes(file.base64)
          Eif (estimated > maxBase64Bytes) {
            throw new Error(`Base64 payload exceeds ${maxBase64Bytes} bytes.`)
          }
        }
        const buffer = decodeBase64(file.base64)
        Iif (maxBase64Bytes && buffer.length > maxBase64Bytes) {
          throw new Error(`Base64 payload exceeds ${maxBase64Bytes} bytes.`)
        }
        if (base64Strategy === 'tempfile') {
          const root = await ensureTempRoot()
          const filename = file.filename ? basename(file.filename) : `${file.field}.bin`
          const filePath = await ensureUniqueTempFilePath(root, filename, usedTempPaths)
          await writeFile(filePath, buffer)
          files[file.field] = filePath
        } else {
          uploads[file.field] = buffer
        }
        continue
      }
      Eif (file.kind === 'url') {
        const matchedStep = findImportStepName(file.field, steps)
        const targetStep = matchedStep ?? sharedImportStep
        const shouldImport =
          urlStrategy === 'import' || (urlStrategy === 'import-if-present' && targetStep)
 
        if (shouldImport) {
          const stepName = targetStep ?? (await ensureUniqueStepName(file.field, usedSteps))
          const urls = importUrlsByStep.get(stepName) ?? []
          urls.push(file.url)
          importUrlsByStep.set(stepName, urls)
          continue
        }
 
        const root = await ensureTempRoot()
        const filename =
          (file.filename ? basename(file.filename) : null) ??
          getFilenameFromUrl(file.url) ??
          `${file.field}.bin`
        const filePath = await ensureUniqueTempFilePath(root, filename, usedTempPaths)
        await beforeUrlDownload?.()
        await downloadUrlToFile({
          allowPrivateUrls,
          filePath,
          url: file.url,
          budget: downloadBudget,
          timeoutMs: urlDownloadTimeoutMs,
        })
        files[file.field] = filePath
      }
    }
  } catch (error) {
    await Promise.all(cleanup.map((fn) => fn()))
    throw error
  }
 
  if (Object.keys(steps).length > 0 || importUrlsByStep.size > 0) {
    Eif (importUrlsByStep.size > 0) {
      for (const [stepName, urls] of importUrlsByStep.entries()) {
        const existing = isRecord(steps[stepName]) ? steps[stepName] : {}
        steps[stepName] = {
          ...existing,
          robot: '/http/import',
          url: urls.length === 1 ? urls[0] : urls,
        }
      }
    }
 
    nextParams = {
      ...nextParams,
      steps,
    }
  }
 
  return {
    params: nextParams,
    files,
    uploads,
    cleanup,
  }
}