{"version":3,"file":"index.mjs","names":["optionsDefaults: Required<ChunkingOptions>","results: (R | undefined)[]","results"],"sources":["../src/utils/invariant.ts","../src/utils/is-empty.ts","../src/utils/chunk.ts","../src/utils/get-error-message.ts","../src/utils/verbose.ts","../src/utils/wait-seconds.ts","../src/process-in-chunks.ts"],"sourcesContent":["export function invariant(condition: unknown, msg: string): asserts condition {\n  if (!condition) {\n    throw new Error(msg);\n  }\n}\n","/**\n * Arrays only. Typically isEmpty does more than that, but we don't need it\n * here.\n */\nexport function isEmpty<T>(array: T[]): array is [] {\n  return array.length === 0;\n}\n","import { invariant } from \"./invariant\";\nimport { isEmpty } from \"./is-empty\";\n\nexport function chunk<T>(array: T[], size: number): T[][] {\n  invariant(size > 0, \"Size must be greater than 0\");\n\n  if (isEmpty(array)) {\n    return [];\n  }\n\n  const length = array.length;\n\n  let index = 0;\n  let resIndex = 0;\n  const result = new Array(Math.ceil(length / size));\n\n  while (index < length) {\n    result[resIndex++] = array.slice(index, (index += size));\n  }\n\n  return result;\n}\n","/**\n * Copied from:\n * https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript\n */\n\nexport function getErrorMessage(error: unknown) {\n  return toErrorWithMessage(error).message;\n}\n\ntype ErrorWithMessage = {\n  message: string;\n};\n\nfunction isErrorWithMessage(error: unknown): error is ErrorWithMessage {\n  return (\n    typeof error === \"object\" &&\n    error !== null &&\n    \"message\" in error &&\n    typeof (error as Record<string, unknown>).message === \"string\"\n  );\n}\n\nfunction toErrorWithMessage(maybeError: unknown): ErrorWithMessage {\n  if (isErrorWithMessage(maybeError)) return maybeError;\n\n  try {\n    return new Error(JSON.stringify(maybeError));\n  } catch {\n    // fallback in case there's an error stringifying the maybeError\n    // like with circular references for example.\n    return new Error(String(maybeError));\n  }\n}\n","export function logIfVerbose(...args: unknown[]) {\n  if (process.env.VERBOSE) {\n    console.log(...args);\n  }\n}\n\nexport function countIfVerbose(label: string) {\n  if (process.env.VERBOSE) {\n    console.count(label);\n  }\n}\n","export async function waitSeconds(numSeconds: number): Promise<void> {\n  return new Promise((resolve) => {\n    setTimeout(resolve, numSeconds * 1000);\n  });\n}\n","import { chunk, getErrorMessage, logIfVerbose, waitSeconds } from \"./utils\";\n\nexport type ChunkingOptions = {\n  chunkSize?: number;\n  throttleSeconds?: number;\n  noThrow?: boolean;\n};\n\nexport type ProcessResult<R> =\n  | {\n      hasErrors: false;\n      results: R[];\n      errorMessages?: undefined;\n    }\n  | {\n      hasErrors: true;\n      results: (R | undefined)[];\n      errorMessages: string[];\n    };\n\nconst optionsDefaults: Required<ChunkingOptions> = {\n  chunkSize: 500,\n  throttleSeconds: 0,\n  noThrow: false,\n};\n\n/**\n * Iterate over a potentially large set of items and process them in chunks with\n * some optional CLI feedback on progress. If the process function returns a\n * value those values are aggregated in the final result.\n */\nexport async function processInChunks<T, R>(\n  allItems: T[],\n  processFn: (value: T, index: number) => R | Promise<R>,\n  options: ChunkingOptions & { noThrow: true },\n): Promise<ProcessResult<R>>;\nexport async function processInChunks<T, R>(\n  allItems: T[],\n  processFn: (value: T, index: number) => R | Promise<R>,\n  options?: ChunkingOptions,\n): Promise<R[]>;\nexport async function processInChunks<T, R>(\n  allItems: T[],\n  processFn: (value: T, index: number) => R | Promise<R>,\n  options: ChunkingOptions = {},\n): Promise<ProcessResult<R> | R[]> {\n  const { chunkSize, throttleSeconds, noThrow } = Object.assign(\n    {},\n    optionsDefaults,\n    options,\n  );\n\n  const chunks = chunk(allItems, chunkSize);\n  let overallIndex = 0;\n\n  const errorMessagesSet = new Set<string>();\n  const results: (R | undefined)[] = [];\n\n  for (const [index, items] of chunks.entries()) {\n    logIfVerbose(`Processing chunk ${index + 1}/${chunks.length}`);\n\n    // Process each item individually with error handling\n    const itemPromises = items.map(async (v, idx) => {\n      try {\n        const result = await processFn(v, overallIndex + idx);\n        return { success: true, result };\n      } catch (err) {\n        if (!noThrow) {\n          throw err; // Rethrow original error immediately\n        }\n        errorMessagesSet.add(getErrorMessage(err));\n        return { success: false, result: undefined };\n      }\n    });\n\n    /** Run throttle wait in parallel with processing if throttling is enabled */\n    const itemResults = await (throttleSeconds > 0\n      ? Promise.all([\n          Promise.all(itemPromises),\n          waitSeconds(throttleSeconds),\n        ]).then(([results]) => results)\n      : Promise.all(itemPromises));\n\n    for (const itemResult of itemResults) {\n      results.push(itemResult.result);\n    }\n\n    overallIndex += items.length;\n  }\n\n  const errorMessages = Array.from(errorMessagesSet);\n\n  if (!noThrow) {\n    // If noThrow is false (default) and we reach here, there were no errors\n    return results as R[];\n  }\n\n  if (errorMessages.length === 0) {\n    return {\n      hasErrors: false,\n      results: results as R[],\n    };\n  } else {\n    return {\n      hasErrors: true,\n      results,\n      errorMessages,\n    };\n  }\n}\n\n/**\n * Same as processInChunks, but passing the whole chunk to the callback\n * function.\n */\nexport async function processInChunksByChunk<T, R>(\n  allItems: T[],\n  processFn: (chunk: T[], index: number) => R | Promise<R>,\n  options: ChunkingOptions & { noThrow: true },\n): Promise<ProcessResult<R>>;\nexport async function processInChunksByChunk<T, R>(\n  allItems: T[],\n  processFn: (chunk: T[], index: number) => R | Promise<R>,\n  options?: ChunkingOptions,\n): Promise<R[]>;\nexport async function processInChunksByChunk<T, R>(\n  allItems: T[],\n  processFn: (chunk: T[], index: number) => R | Promise<R>,\n  options: ChunkingOptions = {},\n): Promise<ProcessResult<R> | R[]> {\n  const { chunkSize, throttleSeconds, noThrow } = Object.assign(\n    {},\n    optionsDefaults,\n    options,\n  );\n\n  const chunks = chunk(allItems, chunkSize);\n  const errorMessagesSet = new Set<string>();\n  const results: (R | undefined)[] = [];\n\n  for (const [index, items] of chunks.entries()) {\n    logIfVerbose(`Processing chunk ${index + 1}/${chunks.length}`);\n\n    try {\n      const processPromise = processFn(items, index);\n\n      /** Run throttle wait in parallel with processing if throttling is enabled */\n      const result = await (throttleSeconds > 0\n        ? Promise.all([processPromise, waitSeconds(throttleSeconds)]).then(\n            ([res]) => res,\n          )\n        : processPromise);\n\n      results.push(result);\n    } catch (err) {\n      if (!noThrow) {\n        throw err; // Rethrow original error immediately\n      }\n      errorMessagesSet.add(getErrorMessage(err));\n      results.push(undefined);\n    }\n  }\n\n  const errorMessages = Array.from(errorMessagesSet);\n\n  if (!noThrow) {\n    // If noThrow is false (default) and we reach here, there were no errors\n    return results as R[];\n  }\n\n  if (errorMessages.length === 0) {\n    return {\n      hasErrors: false,\n      results: results as R[],\n    };\n  } else {\n    return {\n      hasErrors: true,\n      results,\n      errorMessages,\n    };\n  }\n}\n"],"mappings":";AAAA,SAAgB,UAAU,WAAoB,KAAgC;AAC5E,KAAI,CAAC,UACH,OAAM,IAAI,MAAM,IAAI;;;;;;;;;ACExB,SAAgB,QAAW,OAAyB;AAClD,QAAO,MAAM,WAAW;;;;;ACF1B,SAAgB,MAAS,OAAY,MAAqB;AACxD,WAAU,OAAO,GAAG,8BAA8B;AAElD,KAAI,QAAQ,MAAM,CAChB,QAAO,EAAE;CAGX,MAAM,SAAS,MAAM;CAErB,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,MAAM,SAAS,IAAI,MAAM,KAAK,KAAK,SAAS,KAAK,CAAC;AAElD,QAAO,QAAQ,OACb,QAAO,cAAc,MAAM,MAAM,OAAQ,SAAS,KAAM;AAG1D,QAAO;;;;;;;;;ACfT,SAAgB,gBAAgB,OAAgB;AAC9C,QAAO,mBAAmB,MAAM,CAAC;;AAOnC,SAAS,mBAAmB,OAA2C;AACrE,QACE,OAAO,UAAU,YACjB,UAAU,QACV,aAAa,SACb,OAAQ,MAAkC,YAAY;;AAI1D,SAAS,mBAAmB,YAAuC;AACjE,KAAI,mBAAmB,WAAW,CAAE,QAAO;AAE3C,KAAI;AACF,SAAO,IAAI,MAAM,KAAK,UAAU,WAAW,CAAC;SACtC;AAGN,SAAO,IAAI,MAAM,OAAO,WAAW,CAAC;;;;;;AC9BxC,SAAgB,aAAa,GAAG,MAAiB;AAC/C,KAAI,QAAQ,IAAI,QACd,SAAQ,IAAI,GAAG,KAAK;;;;;ACFxB,eAAsB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