path#sep JavaScript Examples

The following examples show how to use path#sep. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: index.js    From cs-wiki with GNU General Public License v3.0 6 votes vote down vote up
function getMatcherString(id, resolutionBase) {
    if (resolutionBase === false) {
        return id;
    }
    // resolve('') is valid and will default to process.cwd()
    const basePath = resolve(resolutionBase || '')
        .split(sep)
        .join('/')
        // escape all possible (posix + win) path characters that might interfere with regex
        .replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
    // Note that we use posix.join because:
    // 1. the basePath has been normalized to use /
    // 2. the incoming glob (id) matcher, also uses /
    // otherwise Node will force backslash (\) on windows
    return posix.join(basePath, id);
}
Example #2
Source File: index.js    From cs-wiki with GNU General Public License v3.0 6 votes vote down vote up
createFilter = function createFilter(include, exclude, options) {
    const resolutionBase = options && options.resolve;
    const getMatcher = (id) => id instanceof RegExp
        ? id
        : {
            test: (what) => {
                // this refactor is a tad overly verbose but makes for easy debugging
                const pattern = getMatcherString(id, resolutionBase);
                const fn = pm(pattern, { dot: true });
                const result = fn(what);
                return result;
            }
        };
    const includeMatchers = ensureArray(include).map(getMatcher);
    const excludeMatchers = ensureArray(exclude).map(getMatcher);
    return function result(id) {
        if (typeof id !== 'string')
            return false;
        if (/\0/.test(id))
            return false;
        const pathId = id.split(sep).join('/');
        for (let i = 0; i < excludeMatchers.length; ++i) {
            const matcher = excludeMatchers[i];
            if (matcher.test(pathId))
                return false;
        }
        for (let i = 0; i < includeMatchers.length; ++i) {
            const matcher = includeMatchers[i];
            if (matcher.test(pathId))
                return true;
        }
        return !includeMatchers.length;
    };
}
Example #3
Source File: telemeter.js    From medusa with MIT License 6 votes vote down vote up
getCliVersion() {
    try {
      const jsonfile = join(
        require
          .resolve(`@medusajs/medusa-cli`) // Resolve where current gatsby-cli would be loaded from.
          .split(sep)
          .slice(0, -2) // drop lib/index.js
          .join(sep),
        `package.json`
      )

      const { version } = require(jsonfile)
      return version
    } catch (e) {
      if (isTruthy(MEDUSA_TELEMETRY_VERBOSE)) {
        console.error("failed to get medusa version", e)
      }
    }

    return `-0.0.0`
  }
Example #4
Source File: error.js    From the-eye-knows-the-garbage with MIT License 6 votes vote down vote up
export function parseStack (stack) {
  const cwd = process.cwd() + sep

  const lines = stack
    .split('\n')
    .splice(1)
    .map(l => l
      .trim()
      .replace('file://', '')
      .replace(cwd, '')
    )

  return lines
}
Example #5
Source File: index.js    From cs-wiki with GNU General Public License v3.0 4 votes vote down vote up
function nodeResolve(opts = {}) {
  const { warnings } = handleDeprecatedOptions(opts);

  const options = { ...defaults, ...opts };
  const { extensions, jail, moduleDirectories, ignoreSideEffectsForRoot } = options;
  const conditionsEsm = [...baseConditionsEsm, ...(options.exportConditions || [])];
  const conditionsCjs = [...baseConditionsCjs, ...(options.exportConditions || [])];
  const packageInfoCache = new Map();
  const idToPackageInfo = new Map();
  const mainFields = getMainFields(options);
  const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
  const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
  const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
  const rootDir = resolve(options.rootDir || process.cwd());
  let { dedupe } = options;
  let rollupOptions;

  if (typeof dedupe !== 'function') {
    dedupe = (importee) =>
      options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
  }

  const resolveOnly = options.resolveOnly.map((pattern) => {
    if (pattern instanceof RegExp) {
      return pattern;
    }
    const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
    return new RegExp(`^${normalized}$`);
  });

  const browserMapCache = new Map();
  let preserveSymlinks;

  return {
    name: 'node-resolve',

    buildStart(options) {
      rollupOptions = options;

      for (const warning of warnings) {
        this.warn(warning);
      }

      ({ preserveSymlinks } = options);
    },

    generateBundle() {
      readCachedFile.clear();
      isFileCached.clear();
      isDirCached.clear();
    },

    async resolveId(importee, importer, opts) {
      if (importee === ES6_BROWSER_EMPTY) {
        return importee;
      }
      // ignore IDs with null character, these belong to other plugins
      if (/\0/.test(importee)) return null;

      if (/\0/.test(importer)) {
        importer = undefined;
      }

      // strip query params from import
      const [importPath, params] = importee.split('?');
      const importSuffix = `${params ? `?${params}` : ''}`;
      importee = importPath;

      const baseDir = !importer || dedupe(importee) ? rootDir : dirname(importer);

      // https://github.com/defunctzombie/package-browser-field-spec
      const browser = browserMapCache.get(importer);
      if (useBrowserOverrides && browser) {
        const resolvedImportee = resolve(baseDir, importee);
        if (browser[importee] === false || browser[resolvedImportee] === false) {
          return ES6_BROWSER_EMPTY;
        }
        const browserImportee =
          browser[importee] ||
          browser[resolvedImportee] ||
          browser[`${resolvedImportee}.js`] ||
          browser[`${resolvedImportee}.json`];
        if (browserImportee) {
          importee = browserImportee;
        }
      }

      const parts = importee.split(/[/\\]/);
      let id = parts.shift();
      let isRelativeImport = false;

      if (id[0] === '@' && parts.length > 0) {
        // scoped packages
        id += `/${parts.shift()}`;
      } else if (id[0] === '.') {
        // an import relative to the parent dir of the importer
        id = resolve(baseDir, importee);
        isRelativeImport = true;
      }

      if (
        !isRelativeImport &&
        resolveOnly.length &&
        !resolveOnly.some((pattern) => pattern.test(id))
      ) {
        if (normalizeInput(rollupOptions.input).includes(importee)) {
          return null;
        }
        return false;
      }

      const importSpecifierList = [];

      if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
        // For module graph roots (i.e. when importer is undefined), we
        // need to handle 'path fragments` like `foo/bar` that are commonly
        // found in rollup config files. If importee doesn't look like a
        // relative or absolute path, we make it relative and attempt to
        // resolve it. If we don't find anything, we try resolving it as we
        // got it.
        importSpecifierList.push(`./${importee}`);
      }

      const importeeIsBuiltin = builtins.has(importee);

      if (importeeIsBuiltin) {
        // The `resolve` library will not resolve packages with the same
        // name as a node built-in module. If we're resolving something
        // that's a builtin, and we don't prefer to find built-ins, we
        // first try to look up a local module with that name. If we don't
        // find anything, we resolve the builtin which just returns back
        // the built-in's name.
        importSpecifierList.push(`${importee}/`);
      }

      // TypeScript files may import '.js' to refer to either '.ts' or '.tsx'
      if (importer && importee.endsWith('.js')) {
        for (const ext of ['.ts', '.tsx']) {
          if (importer.endsWith(ext) && extensions.includes(ext)) {
            importSpecifierList.push(importee.replace(/.js$/, ext));
          }
        }
      }

      importSpecifierList.push(importee);

      const warn = (...args) => this.warn(...args);
      const isRequire =
        opts && opts.custom && opts.custom['node-resolve'] && opts.custom['node-resolve'].isRequire;
      const exportConditions = isRequire ? conditionsCjs : conditionsEsm;

      const resolvedWithoutBuiltins = await resolveImportSpecifiers({
        importer,
        importSpecifierList,
        exportConditions,
        warn,
        packageInfoCache,
        extensions,
        mainFields,
        preserveSymlinks,
        useBrowserOverrides,
        baseDir,
        moduleDirectories,
        rootDir,
        ignoreSideEffectsForRoot
      });

      const resolved =
        importeeIsBuiltin && preferBuiltins
          ? {
              packageInfo: undefined,
              hasModuleSideEffects: () => null,
              hasPackageEntry: true,
              packageBrowserField: false
            }
          : resolvedWithoutBuiltins;
      if (!resolved) {
        return null;
      }

      const { packageInfo, hasModuleSideEffects, hasPackageEntry, packageBrowserField } = resolved;
      let { location } = resolved;
      if (packageBrowserField) {
        if (Object.prototype.hasOwnProperty.call(packageBrowserField, location)) {
          if (!packageBrowserField[location]) {
            browserMapCache.set(location, packageBrowserField);
            return ES6_BROWSER_EMPTY;
          }
          location = packageBrowserField[location];
        }
        browserMapCache.set(location, packageBrowserField);
      }

      if (hasPackageEntry && !preserveSymlinks) {
        const fileExists = await exists(location);
        if (fileExists) {
          location = await realpath(location);
        }
      }

      idToPackageInfo.set(location, packageInfo);

      if (hasPackageEntry) {
        if (importeeIsBuiltin && preferBuiltins) {
          if (!isPreferBuiltinsSet && resolvedWithoutBuiltins && resolved !== importee) {
            this.warn(
              `preferring built-in module '${importee}' over local alternative at '${resolvedWithoutBuiltins.location}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`
            );
          }
          return false;
        } else if (jail && location.indexOf(normalize(jail.trim(sep))) !== 0) {
          return null;
        }
      }

      if (options.modulesOnly && (await exists(location))) {
        const code = await readFile(location, 'utf-8');
        if (isModule(code)) {
          return {
            id: `${location}${importSuffix}`,
            moduleSideEffects: hasModuleSideEffects(location)
          };
        }
        return null;
      }
      const result = {
        id: `${location}${importSuffix}`,
        moduleSideEffects: hasModuleSideEffects(location)
      };
      return result;
    },

    load(importee) {
      if (importee === ES6_BROWSER_EMPTY) {
        return 'export default {};';
      }
      return null;
    },

    getPackageInfoForId(id) {
      return idToPackageInfo.get(id);
    }
  };
}
Example #6
Source File: index.es.js    From smart-contracts with MIT License 4 votes vote down vote up
function nodeResolve(opts = {}) {
  const options = Object.assign({}, defaults, opts);
  const customResolveOptions = options.customResolveOptions,
        extensions = options.extensions,
        jail = options.jail;
  const warnings = [];
  const packageInfoCache = new Map();
  const idToPackageInfo = new Map();
  const mainFields = getMainFields(options);
  const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
  const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
  const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
  const rootDir = options.rootDir || process.cwd();
  let dedupe = options.dedupe;
  let rollupOptions;

  if (options.only) {
    warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
    options.resolveOnly = options.only;
  }

  if (typeof dedupe !== 'function') {
    dedupe = importee => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
  }

  const resolveOnly = options.resolveOnly.map(pattern => {
    if (pattern instanceof RegExp) {
      return pattern;
    }

    const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
    return new RegExp(`^${normalized}$`);
  });
  const browserMapCache = new Map();
  let preserveSymlinks;
  return {
    name: 'node-resolve',

    buildStart(options) {
      rollupOptions = options;
      var _iteratorNormalCompletion = true;
      var _didIteratorError = false;
      var _iteratorError = undefined;

      try {
        for (var _iterator = warnings[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
          const warning = _step.value;
          this.warn(warning);
        }
      } catch (err) {
        _didIteratorError = true;
        _iteratorError = err;
      } finally {
        try {
          if (!_iteratorNormalCompletion && _iterator.return != null) {
            _iterator.return();
          }
        } finally {
          if (_didIteratorError) {
            throw _iteratorError;
          }
        }
      }

      preserveSymlinks = options.preserveSymlinks;
    },

    generateBundle() {
      readCachedFile.clear();
      isFileCached.clear();
      isDirCached.clear();
    },

    resolveId(importee, importer) {
      var _this = this;

      return _asyncToGenerator(function* () {
        if (importee === ES6_BROWSER_EMPTY) {
          return importee;
        } // ignore IDs with null character, these belong to other plugins


        if (/\0/.test(importee)) return null;
        const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer); // https://github.com/defunctzombie/package-browser-field-spec

        const browser = browserMapCache.get(importer);

        if (useBrowserOverrides && browser) {
          const resolvedImportee = resolve(basedir, importee);

          if (browser[importee] === false || browser[resolvedImportee] === false) {
            return ES6_BROWSER_EMPTY;
          }

          const browserImportee = browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`];

          if (browserImportee) {
            importee = browserImportee;
          }
        }

        const parts = importee.split(/[/\\]/);
        let id = parts.shift();

        if (id[0] === '@' && parts.length > 0) {
          // scoped packages
          id += `/${parts.shift()}`;
        } else if (id[0] === '.') {
          // an import relative to the parent dir of the importer
          id = resolve(basedir, importee);
        }

        const input = normalizeInput(rollupOptions.input);

        if (resolveOnly.length && !resolveOnly.some(pattern => pattern.test(id))) {
          if (input.includes(id)) {
            return null;
          }

          return false;
        }

        let hasModuleSideEffects = nullFn;
        let hasPackageEntry = true;
        let packageBrowserField = false;
        let packageInfo;

        const filter = (pkg, pkgPath) => {
          const info = getPackageInfo({
            cache: packageInfoCache,
            extensions,
            pkg,
            pkgPath,
            mainFields,
            preserveSymlinks,
            useBrowserOverrides
          });
          packageInfo = info.packageInfo;
          hasModuleSideEffects = info.hasModuleSideEffects;
          hasPackageEntry = info.hasPackageEntry;
          packageBrowserField = info.packageBrowserField;
          return info.cachedPkg;
        };

        let resolveOptions = {
          basedir,
          packageFilter: filter,
          readFile: readCachedFile,
          isFile: isFileCached,
          isDirectory: isDirCached,
          extensions
        };

        if (preserveSymlinks !== undefined) {
          resolveOptions.preserveSymlinks = preserveSymlinks;
        }

        const importSpecifierList = [];

        if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
          // For module graph roots (i.e. when importer is undefined), we
          // need to handle 'path fragments` like `foo/bar` that are commonly
          // found in rollup config files. If importee doesn't look like a
          // relative or absolute path, we make it relative and attempt to
          // resolve it. If we don't find anything, we try resolving it as we
          // got it.
          importSpecifierList.push(`./${importee}`);
        }

        const importeeIsBuiltin = builtins.has(importee);

        if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
          // The `resolve` library will not resolve packages with the same
          // name as a node built-in module. If we're resolving something
          // that's a builtin, and we don't prefer to find built-ins, we
          // first try to look up a local module with that name. If we don't
          // find anything, we resolve the builtin which just returns back
          // the built-in's name.
          importSpecifierList.push(`${importee}/`);
        }

        importSpecifierList.push(importee);
        resolveOptions = Object.assign(resolveOptions, customResolveOptions);

        try {
          let resolved = yield resolveImportSpecifiers(importSpecifierList, resolveOptions);

          if (resolved && packageBrowserField) {
            if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
              if (!packageBrowserField[resolved]) {
                browserMapCache.set(resolved, packageBrowserField);
                return ES6_BROWSER_EMPTY;
              }

              resolved = packageBrowserField[resolved];
            }

            browserMapCache.set(resolved, packageBrowserField);
          }

          if (hasPackageEntry && !preserveSymlinks && resolved) {
            const fileExists = yield exists(resolved);

            if (fileExists) {
              resolved = yield realpath(resolved);
            }
          }

          idToPackageInfo.set(resolved, packageInfo);

          if (hasPackageEntry) {
            if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
              return null;
            } else if (importeeIsBuiltin && preferBuiltins) {
              if (!isPreferBuiltinsSet) {
                _this.warn(`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`);
              }

              return null;
            } else if (jail && resolved.indexOf(normalize(jail.trim(sep))) !== 0) {
              return null;
            }
          }

          if (resolved && options.modulesOnly) {
            const code = yield readFile(resolved, 'utf-8');

            if (isModule(code)) {
              return {
                id: resolved,
                moduleSideEffects: hasModuleSideEffects(resolved)
              };
            }

            return null;
          }

          const result = {
            id: resolved,
            moduleSideEffects: hasModuleSideEffects(resolved)
          };
          return result;
        } catch (error) {
          return null;
        }
      })();
    },

    load(importee) {
      if (importee === ES6_BROWSER_EMPTY) {
        return 'export default {};';
      }

      return null;
    },

    getPackageInfoForId(id) {
      return idToPackageInfo.get(id);
    }

  };
}
Example #7
Source File: export.js    From medusa with MIT License 4 votes vote down vote up
describe("Batchjob with type order-export", () => {
  let medusaProcess
  let dbConnection
  let exportFilePath = ""
  let topDir = ""

  beforeAll(async () => {
    const cwd = path.resolve(path.join(__dirname, "..", "..", ".."))
    dbConnection = await initDb({ cwd })
    medusaProcess = await setupServer({
      cwd,
      redisUrl: "redis://127.0.0.1:6379",
      uploadDir: __dirname,
      verbose: false,
    })
  })

  afterAll(async () => {
    if (topDir !== "") {
      await fs.rm(resolve(__dirname, topDir), { recursive: true })
    }

    const db = useDb()
    await db.shutdown()

    medusaProcess.kill()
  })

  beforeEach(async () => {
    try {
      await adminSeeder(dbConnection)
      await userSeeder(dbConnection)
      await orderSeeder(dbConnection)
    } catch (e) {
      console.log(e)
      throw e
    }
  })

  afterEach(async () => {
    const db = useDb()
    await db.teardown()

    const isFileExists = (await fs.stat(exportFilePath))?.isFile()

    if (isFileExists) {
      const [, relativeRoot] = exportFilePath.replace(__dirname, "").split(sep)

      if ((await fs.stat(resolve(__dirname, relativeRoot)))?.isDirectory()) {
        topDir = relativeRoot
      }

      await fs.unlink(exportFilePath)
    }
  })

  it("Should export a file containing all orders", async () => {
    jest.setTimeout(1000000)
    const api = useApi()

    const batchPayload = {
      type: "order-export",
      context: {},
    }

    const batchJobRes = await api.post(
      "/admin/batch-jobs",
      batchPayload,
      adminReqConfig
    )
    const batchJobId = batchJobRes.data.batch_job.id

    expect(batchJobId).toBeTruthy()

    // Pull to check the status until it is completed
    let batchJob
    let shouldContinuePulling = true

    while (shouldContinuePulling) {
      const res = await api.get(
        `/admin/batch-jobs/${batchJobId}`,
        adminReqConfig
      )

      batchJob = res.data.batch_job
      shouldContinuePulling = !(
        batchJob.status === "completed" || batchJob.status === "failed"
      )

      if (shouldContinuePulling) {
        await new Promise((resolve, _) => {
          setTimeout(resolve, 1000)
        })
      }
    }

    expect(batchJob.status).toBe("completed")

    expect(batchJob.status).toBe("completed")

    exportFilePath = path.resolve(__dirname, batchJob.result.file_key)
    const isFileExists = (await fs.stat(exportFilePath)).isFile()

    expect(isFileExists).toBeTruthy()

    const fileSize = (await fs.stat(exportFilePath)).size
    expect(batchJob.result?.file_size).toBe(fileSize)

    const data = (await fs.readFile(exportFilePath)).toString()
    const [, ...lines] = data.split("\r\n").filter((l) => l)

    expect(lines.length).toBe(6)

    const csvLine = lines[0].split(";")

    expect(csvLine[0]).toBe("discount-order")
    expect(csvLine[1]).toBe("6")
    expect(csvLine[14]).toBe("fulfilled")
    expect(csvLine[15]).toBe("captured")
    expect(csvLine[16]).toBe("8000")
  })

  it("Should export a file containing a limited number of orders", async () => {
    jest.setTimeout(1000000)
    const api = useApi()

    const batchPayload = {
      type: "order-export",
      context: { batch_size: 3 },
    }

    const batchJobRes = await api.post(
      "/admin/batch-jobs",
      batchPayload,
      adminReqConfig
    )
    const batchJobId = batchJobRes.data.batch_job.id

    expect(batchJobId).toBeTruthy()

    // Pull to check the status until it is completed
    let batchJob
    let shouldContinuePulling = true

    while (shouldContinuePulling) {
      const res = await api.get(
        `/admin/batch-jobs/${batchJobId}`,
        adminReqConfig
      )

      batchJob = res.data.batch_job
      shouldContinuePulling = !(
        batchJob.status === "completed" || batchJob.status === "failed"
      )

      if (shouldContinuePulling) {
        await new Promise((resolve, _) => {
          setTimeout(resolve, 1000)
        })
      }
    }

    exportFilePath = path.resolve(__dirname, batchJob.result.file_key)
    const isFileExists = (await fs.stat(exportFilePath)).isFile()

    expect(isFileExists).toBeTruthy()

    const data = (await fs.readFile(exportFilePath)).toString()
    const [, ...lines] = data.split("\r\n").filter((l) => l)

    expect(lines.length).toBe(3)
  })

  it("Should export a file with orders from a single customer", async () => {
    jest.setTimeout(1000000)
    const api = useApi()

    const batchPayload = {
      type: "order-export",
      context: { filterable_fields: { email: "[email protected]" } },
    }

    const batchJobRes = await api.post(
      "/admin/batch-jobs",
      batchPayload,
      adminReqConfig
    )
    const batchJobId = batchJobRes.data.batch_job.id

    expect(batchJobId).toBeTruthy()

    // Pull to check the status until it is completed
    let batchJob
    let shouldContinuePulling = true

    while (shouldContinuePulling) {
      const res = await api.get(
        `/admin/batch-jobs/${batchJobId}`,
        adminReqConfig
      )

      batchJob = res.data.batch_job
      shouldContinuePulling = !(
        batchJob.status === "completed" || batchJob.status === "failed"
      )

      if (shouldContinuePulling) {
        await new Promise((resolve, _) => {
          setTimeout(resolve, 1000)
        })
      }
    }

    expect(batchJob.status).toBe("completed")

    exportFilePath = path.resolve(__dirname, batchJob.result.file_key)
    const isFileExists = (await fs.stat(exportFilePath)).isFile()

    expect(isFileExists).toBeTruthy()

    const data = (await fs.readFile(exportFilePath)).toString()
    const [, ...lines] = data.split("\r\n").filter((l) => l)

    expect(lines.length).toBe(1)

    const csvLine = lines[0].split(";")

    expect(csvLine[0]).toBe("test-order")
    expect(csvLine[6]).toBe("[email protected]")
  })
})
Example #8
Source File: export.js    From medusa with MIT License 4 votes vote down vote up
describe("Batch job of product-export type", () => {
  let medusaProcess
  let dbConnection
  let exportFilePath = ""
  let topDir = ""

  beforeAll(async () => {
    const cwd = path.resolve(path.join(__dirname, "..", "..", ".."))
    dbConnection = await initDb({ cwd })
    medusaProcess = await setupServer({
      cwd,
      redisUrl: "redis://127.0.0.1:6379",
      uploadDir: __dirname,
      verbose: false,
    })
  })

  afterAll(async () => {
    if (topDir !== "") {
      await fs.rm(resolve(__dirname, topDir), { recursive: true })
    }

    const db = useDb()
    await db.shutdown()

    medusaProcess.kill()
  })

  beforeEach(async () => {
    try {
      await productSeeder(dbConnection)
      await adminSeeder(dbConnection)
      await userSeeder(dbConnection)
    } catch (e) {
      console.log(e)
      throw e
    }
  })

  afterEach(async () => {
    const db = useDb()
    await db.teardown()

    const isFileExists = (await fs.stat(exportFilePath))?.isFile()

    if (isFileExists) {
      const [, relativeRoot] = exportFilePath.replace(__dirname, "").split(sep)

      if ((await fs.stat(resolve(__dirname, relativeRoot)))?.isDirectory()) {
        topDir = relativeRoot
      }

      await fs.unlink(exportFilePath)
    }
  })

  it("should export a csv file containing the expected products", async () => {
    jest.setTimeout(1000000)
    const api = useApi()

    const productPayload = {
      title: "Test export product",
      description: "test-product-description",
      type: { value: "test-type" },
      images: ["test-image.png", "test-image-2.png"],
      collection_id: "test-collection",
      tags: [{ value: "123" }, { value: "456" }],
      options: [{ title: "size" }, { title: "color" }],
      variants: [
        {
          title: "Test variant",
          inventory_quantity: 10,
          sku: "test-variant-sku-product-export",
          prices: [
            {
              currency_code: "usd",
              amount: 100,
            },
            {
              currency_code: "eur",
              amount: 45,
            },
            {
              currency_code: "dkk",
              amount: 30,
            },
          ],
          options: [{ value: "large" }, { value: "green" }],
        },
      ],
    }
    const createProductRes = await api.post(
      "/admin/products",
      productPayload,
      adminReqConfig
    )
    const productId = createProductRes.data.product.id
    const variantId = createProductRes.data.product.variants[0].id

    const batchPayload = {
      type: "product-export",
      context: {
        filterable_fields: {
          title: "Test export product",
        },
      },
    }
    const batchJobRes = await api.post(
      "/admin/batch-jobs",
      batchPayload,
      adminReqConfig
    )
    const batchJobId = batchJobRes.data.batch_job.id

    expect(batchJobId).toBeTruthy()

    // Pull to check the status until it is completed
    let batchJob
    let shouldContinuePulling = true
    while (shouldContinuePulling) {
      const res = await api.get(
        `/admin/batch-jobs/${batchJobId}`,
        adminReqConfig
      )

      await new Promise((resolve, _) => {
        setTimeout(resolve, 1000)
      })

      batchJob = res.data.batch_job
      shouldContinuePulling = !(
        batchJob.status === "completed" || batchJob.status === "failed"
      )
    }

    expect(batchJob.status).toBe("completed")

    exportFilePath = path.resolve(__dirname, batchJob.result.file_key)
    const isFileExists = (await fs.stat(exportFilePath)).isFile()

    expect(isFileExists).toBeTruthy()

    const fileSize = (await fs.stat(exportFilePath)).size
    expect(batchJob.result?.file_size).toBe(fileSize)

    const data = (await fs.readFile(exportFilePath)).toString()
    const [, ...lines] = data.split("\r\n").filter((l) => l)

    expect(lines.length).toBe(1)

    const lineColumn = lines[0].split(";")

    expect(lineColumn[0]).toBe(productId)
    expect(lineColumn[2]).toBe(productPayload.title)
    expect(lineColumn[4]).toBe(productPayload.description)
    expect(lineColumn[23]).toBe(variantId)
    expect(lineColumn[24]).toBe(productPayload.variants[0].title)
    expect(lineColumn[25]).toBe(productPayload.variants[0].sku)
  })

  it("should export a csv file containing a limited number of products", async () => {
    jest.setTimeout(1000000)
    const api = useApi()

    const batchPayload = {
      type: "product-export",
      context: {
        batch_size: 1,
        filterable_fields: { collection_id: "test-collection" },
        order: "created_at",
      },
    }

    const batchJobRes = await api.post(
      "/admin/batch-jobs",
      batchPayload,
      adminReqConfig
    )
    const batchJobId = batchJobRes.data.batch_job.id

    expect(batchJobId).toBeTruthy()

    // Pull to check the status until it is completed
    let batchJob
    let shouldContinuePulling = true
    while (shouldContinuePulling) {
      const res = await api.get(
        `/admin/batch-jobs/${batchJobId}`,
        adminReqConfig
      )

      await new Promise((resolve, _) => {
        setTimeout(resolve, 1000)
      })

      batchJob = res.data.batch_job
      shouldContinuePulling = !(
        batchJob.status === "completed" || batchJob.status === "failed"
      )
    }

    expect(batchJob.status).toBe("completed")

    exportFilePath = path.resolve(__dirname, batchJob.result.file_key)
    const isFileExists = (await fs.stat(exportFilePath)).isFile()

    expect(isFileExists).toBeTruthy()

    const data = (await fs.readFile(exportFilePath)).toString()
    const [, ...lines] = data.split("\r\n").filter((l) => l)

    expect(lines.length).toBe(4)

    const csvLine = lines[0].split(";")
    expect(csvLine[0]).toBe("test-product")
  })
})