{"version":3,"sources":["../src/lib/intermediate2/intermediate2.ts"],"names":["path","tmpdir","nanoid","gulplog","streamx","vfs","Composer","fs","promisify","asyncDone","PluginError","streams"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,IAAM,WAAA,GAAc,oBAAA;AAyKb,SAAS,aAAA,CAAc,SAAkB,aAAA,EAA8D;AAE5G,EAAA,MAAM,eAAA,GAAkD;AAAA,IACtD,aAAa,EAAC;AAAA,IACd,QAAA,EAAU,MAAA;AAAA,IACV,YAAY,EAAC;AAAA,IACb,MAAA,EAAQ,MAAA;AAAA,IACR,SAAA,EAAW;AAAA,GACb;AACA,EAAA,MAAM,QAAA,GAA2C,EAAE,GAAG,eAAA,EAAiB,GAAG,aAAA,EAAc;AACxF,EAAA,MAAM,QAAA,GAAoB,OAAA;AAE1B,EAAA,MAAM,iBAAA,GAAiCA,eAAA,CAAA,IAAA,CAAKC,SAAA,EAAO,EAAGC,eAAQ,CAAA;AAC9D,EAAA,MAAM,yBAAkC,QAAA,CAAS,SAAA,GAC1CF,qBAAK,iBAAA,EAAmB,QAAA,CAAS,SAAS,CAAA,GAC/C,iBAAA;AACF,EAAA,MAAM,sBAA+B,QAAA,CAAS,MAAA,GACvCA,qBAAK,iBAAA,EAAmB,QAAA,CAAS,MAAM,CAAA,GAC5C,iBAAA;AACF,EAAA,IAAI,CAAC,QAAA,CAAS,UAAA,CAAW,GAAA,EAAK,MAAA,EAAQ;AACpC,IAAA,QAAA,CAAS,WAAW,GAAA,GAAM,mBAAA;AAAA,EAC5B;AAEA,EAAAG,wBAAA,CAAQ,KAAA,CAAM,CAAA,OAAA,EAAU,WAAW,CAAA,qBAAA,EAAwB,iBAAiB,CAAA,CAAE,CAAA;AAE9E,EAAA,MAAM,0BAA2C,EAAC;AAClD,EAAA,MAAM,QAAA,GAAW,IAAYC,kBAAA,CAAA,WAAA,EAAY;AACzC,EAAA,MAAM,QAAA,GACJC,oBAAA,CAA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C,UAAA;AAAA,QACH,CAAC,CAAA,CACA,IAAA,CAAK,QAA4C,CAAA;AACpD,QAAA,MAAcM,kBAAA,CAAA,QAAA,CAAS,SAAS,qBAAqB,CAAA;AACrD,QAAA,MAAM,OAAA,CAAQ,IAAI,uBAAuB,CAAA;AAAA,MAC3C,SAAS,KAAA,EAAgB;AAMvB,QAAA,YAAA,CAAa,IAAA;AAAA,UAAK,OAAA;AAAA,UAChB,KAAA,YAAiBD,4BAAA,GAAc,KAAA,GAC7B,KAAA,YAAiB,KAAA,GAAQ,IAAIA,4BAAA,CAAY,WAAA,EAAa,KAAK,CAAA,GACzD,IAAIA,4BAAA,CAAY,aAAa,KAAe;AAAA,SAClD;AAAA,MACF,CAAA,SAAE;AACA,QAAAP,wBAAA,CAAQ,KAAA,CAAM,CAAA,OAAA,EAAU,WAAW,CAAA,SAAA,EAAY,iBAAiB,CAAA,CAAE,CAAA;AAClE,QAAA,MAASI,iBAAG,iBAAA,EAAmB,EAAE,OAAO,IAAA,EAAM,SAAA,EAAW,MAAM,CAAA;AAAA,MACjE;AAAC,IACH,CAAA,GAAG;AAAA,EACL,CAAC,CAAA;AAEH,EAAA,OAAO,YAAA;AACT","file":"index.cjs","sourcesContent":["/**\n * A gulp helper for tools that need files on disk\n *\n * Some tools require access to files on disk instead of working with `stdin` and `stdout`\n * (e.g., [Jekyll](http://jekyllrb.com/), [Ruby Sass](http://sass-lang.com/)).\n * `gulp-intermediate2` is a convenience plugin\n * that writes the current vinyl stream to a temporary directory,\n * lets you run commands on the file system, and pushes the results back into the pipe.\n *\n * @packageDocumentation\n */\n\nimport { promisify } from 'node:util';\nimport * as streams from 'node:stream';\nimport type { EventEmitter } from 'node:stream';\nimport * as streamx from 'streamx';\nimport Composer from 'stream-composer/index.js';\nimport * as path from 'node:path';\nimport * as fs from 'node:fs/promises';\nimport { tmpdir } from 'node:os';\nimport { ChildProcess } from 'node:child_process';\nimport { nanoid } from 'nanoid';\nimport PluginError from 'plugin-error';\nimport vfs from 'vinyl-fs';\nimport GulpFile from 'vinyl';\nimport asyncDone from 'async-done';\nimport gulplog from 'gulplog';\n\nconst PLUGIN_NAME = 'gulp-intermediate2';\n\n/**\n * gulp-intermediate2 plugin options\n *\n * @remarks\n *\n * @see {@link intermediate2} for more details.\n *\n * @public\n */\nexport interface Intermediate2Options {\n\n  /**\n   * Process output dir relative path.\n   * The directory read back into the stream when processing is finished.\n   * Relative to tempDir.\n   *\n   * @defaultValue `'.'`\n   *\n   * @remarks\n   *\n   * @see {@link intermediate2} for more details.\n   *\n   * @public\n   */\n  output?: string;\n\n  /**\n   * Process input temp directory relative path.\n   * The directory that files are written to,\n   * relative to the operating system's temporary directory.\n   * The container is emptied before every run.\n   *\n   * @defaultValue `'.'`\n   *\n   * @remarks\n   *\n   * @see {@link intermediate2} for more details.\n   *\n   * @public\n   */\n  container?: string;\n\n  /**\n   * Options for `gulp.dest`\n   * for writing files to {@link Intermediate2Options.container| container}\n   * temp directory before processing.\n   *\n   * @remarks\n   *\n   * @see `gulp.dest()` for more details.\n   *\n   * @public\n   */\n  destOptions?: vfs.DestOptions;\n\n  /**\n   * Process output files glob.\n   * Glob for `gulp.src`\n   * for reading files from {@link Intermediate2Options.output| output} temp directory after processing.\n   *\n   * @defaultValue `'**\\*'`\n   *\n   * @remarks\n   *\n   * @see `gulp.src()` for more details.\n   *\n   * @public\n   */\n  srcGlobs?: string | string[];\n\n  /**\n   * `gulp.src` options for process output files.\n   * Options for `gulp.src`\n   * for reading files from {@link Intermediate2Options.output| output} temp directory after processing.\n   *\n   * @remarks\n   *\n   * @see `gulp.src()` for more details.\n   *\n   * @public\n   */\n  srcOptions?: vfs.SrcOptions;\n};\n\n/**\n * {@link intermediate2} {@link Process} function callback\n *\n * @param Error - error (if failure) or null (if success)\n *\n * @remarks\n *\n * @see {@link intermediate2} for more details.\n *\n * @public\n */\nexport type ProcessCallback = (Error?: Error | null) => void;\n\n/**\n * {@link intermediate2} Process function.\n *\n * Process started after input files written to\n * `srcDirPath` directory\n * ({@link Intermediate2Options.container| pluginOptions.container} temp directory).\n *\n * Process must write output files to `destDirPath`\n * ({@link Intermediate2Options.output| pluginOptions.output} temp directory).\n *\n * After the process is completed, it need to call a callback.\n * Or process function can return `ChildProcess`, `EventEmitter`,\n * `Observable<R>`, `PromiseLike<R>`, `Stream` object.\n * `intermediate2` await processes, represented by returned object.\n *\n * After process finished, result files pushed to output stream.\n *\n * @param srcDirPath - {@link Intermediate2Options.container| pluginOptions.container} temp directory path\n * @param destDirPath - {@link Intermediate2Options.output| pluginOptions.output} temp directory path\n * @param callback - process first-error {@link ProcessCallback| callback}\n *\n * @remarks\n *\n * @see {@link intermediate2}\n *\n * @public\n */\nexport type Process<R = any> =\n  ((srcDirPath: string, destDirPath: string, callback: ProcessCallback) => void) |\n  ((srcDirPath: string, destDirPath: string) =>\n    ChildProcess |\n    EventEmitter |\n    asyncDone.Observable<R> |\n    PromiseLike<R> |\n    streams.Stream\n  );\n\n/**\n * Plugin fabric function.\n *\n * A gulp helper for tools that need files on disk.\n *\n * Some tools require access to files on disk instead of working with `stdin` and `stdout`\n * (e.g., {@link http://jekyllrb.com/| Jekyll}, {@link http://sass-lang.com/| Ruby Sass}).\n * `gulp-intermediate2` is a convenience plugin\n * that writes the current `Vinyl` stream to a temporary directory,\n * lets You run commands on the file system, and pushes the results back into the pipe.\n *\n * Returns Gulp stream.\n *\n * `intermediate2` writes (with `gulp.dest()`) input `Vinyl` file objects to\n * {@link Intermediate2Options.container| container} subdirectory in temporary directory\n * under system `Temp`.\n *\n * After all files are written, `intermediate2` run {@link Process| process}\n * and wait for it finish.\n *\n * {@link Process} must be read files from `srcDirPath` directory\n * ({@link Intermediate2Options.container| pluginOptions.container} temp directory),\n * and write output files to `destDirPath`\n * ({@link Intermediate2Options.output| pluginOptions.output} temp directory).\n *\n * After that `intermediate2` will read files (with `gulp.src()`) from\n * {@link Intermediate2Options.output| pluginOptions.output} directory\n * and will push they to gulp stream.\n *\n * @param process - contains the {@link Process| process} for files processing\n * @param pluginOptions - contains the {@link Intermediate2Options| options} for gulp plugin.\n * @public\n */\nexport function intermediate2(process: Process, pluginOptions?: Intermediate2Options): NodeJS.ReadWriteStream {\n\n  const optionsDefaults: Required<Intermediate2Options> = {\n    destOptions: {},\n    srcGlobs: '**/*',\n    srcOptions: {},\n    output: 'dest',\n    container: 'src'\n  };\n  const _options: Required<Intermediate2Options> = { ...optionsDefaults, ...pluginOptions };\n  const _process: Process = process;\n\n  const tempDirectoryPath: string = path.join(tmpdir(), nanoid());\n  const containerDirectoryPath: string = (_options.container) ?\n    path.join(tempDirectoryPath, _options.container) :\n    tempDirectoryPath;\n  const outputDirectoryPath: string = (_options.output) ?\n    path.join(tempDirectoryPath, _options.output) :\n    tempDirectoryPath;\n  if (!_options.srcOptions.cwd?.length) {\n    _options.srcOptions.cwd = outputDirectoryPath;\n  };\n\n  gulplog.debug(`plugin ${PLUGIN_NAME} used temp directory ${tempDirectoryPath}`);\n\n  const srcFilesStreamsFinishes: Promise<void>[] = [];\n  const readable = new streamx.PassThrough();\n  const writable: streamx.Writable =\n    vfs.dest(containerDirectoryPath, _options.destOptions) as unknown as streamx.Writable;\n\n  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access\n  const pluginStream: streamx.Duplex = Composer.duplexer(\n    writable,\n    readable as unknown as streamx.Readable\n  );\n\n  writable\n    .on('close', () => {\n      void (async () => {\n        try {\n          await fs.mkdir(outputDirectoryPath, { recursive: true });\n\n          await promisify(asyncDone)((done: ProcessCallback) => {\n            return _process(containerDirectoryPath, outputDirectoryPath, done);\n          })\n            .catch((error: unknown) => {\n              throw (error instanceof PluginError ? (error) :\n                new PluginError(PLUGIN_NAME, `exception in temp files processing handler: ${error as string}`));\n            });\n\n          const outputTempFilesStream = vfs.src(_options.srcGlobs, _options.srcOptions)\n            .on('error', (err) => {\n              return;\n            })\n            .on('data', (file: GulpFile) => {\n              if (file.isStream()) {\n                // streamx doesn't emit 'close' event. Use 'end' event.\n                // srcFilesStreamsFinishes.push(streams.promises.finished(file.contents));\n                srcFilesStreamsFinishes.push(new Promise<void>((resolve, reject) => {\n                  file.contents\n                    .on('close', resolve)\n                    .on('end', resolve)\n                    .on('error', reject);\n                }));\n              };\n            })\n            .pipe(readable as unknown as NodeJS.WritableStream);\n          await streams.promises.finished(outputTempFilesStream);\n          await Promise.all(srcFilesStreamsFinishes);\n        } catch (error: unknown) {\n          // pluginStream.destroy(\n          //   error instanceof PluginError ? error as PluginError :\n          //     error instanceof Error ? new PluginError(PLUGIN_NAME, error) :\n          //       new PluginError(PLUGIN_NAME, error as string)\n          // );\n          pluginStream.emit('error',\n            error instanceof PluginError ? error as PluginError :\n              error instanceof Error ? new PluginError(PLUGIN_NAME, error) :\n                new PluginError(PLUGIN_NAME, error as string)\n          );\n        } finally {\n          gulplog.debug(`plugin ${PLUGIN_NAME} deleted ${tempDirectoryPath}`);\n          await fs.rm(tempDirectoryPath, { force: true, recursive: true });\n        };\n      })();\n    });\n\n  return pluginStream as unknown as NodeJS.ReadWriteStream;\n};\n"]}