url#fileURLToPath JavaScript Examples

The following examples show how to use url#fileURLToPath. 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: _util.js    From ctzn with MIT License 7 votes vote down vote up
export async function createServer () {
  const tmpdir = await tmp.dir({unsafeCleanup: true})
  const domain = `dev${nServer++}.localhost`
  const port = DEBUG_MODE_PORTS_MAP[domain]
  console.log('Storing config in', tmpdir.path)

  const binPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin.js')
  const serverProcess = spawn(
    'node',
    [binPath, 'start-test', '--configDir', tmpdir.path, '--domain', domain],
    {
      stdio: [process.stdin, process.stdout, process.stderr],
      env: INSPECTOR_ENABLED ? Object.assign({}, process.env, {NODE_OPTIONS: `--inspect=localhost:${5555+nServer}`}) : undefined
    }
  )

  const client = new WsClient(`ws://localhost:${port}/`)
  const api = await createRpcApi(client)
  await api.debug.whenServerReady()

  return {
    url: `http://localhost:${port}/`,
    domain,
    serverUserId: `server@${domain}`,
    client,
    api,
    process: serverProcess,
    close: async () => {
      const p = new Promise(r => {
        if (serverProcess.exitCode !== null) r()
        serverProcess.on('exit', r)
      })
      serverProcess.kill()
      await p
      await tmpdir.cleanup()
    }
  }
}
Example #2
Source File: dsv2dsv.js    From cs-wiki with GNU General Public License v3.0 6 votes vote down vote up
options = program
    .version(JSON.parse(readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), "../package.json"))).version)
    .usage("[options] [file]")
    .option("-o, --out <file>", "output file name; defaults to “-” for stdout", "-")
    .option("-r, --input-delimiter <character>", "input delimiter character", defaultInDelimiter)
    .option("-w, --output-delimiter <character>", "output delimiter character", defaultOutDelimiter)
    .option("--input-encoding <encoding>", "input character encoding; defaults to “utf8”", "utf8")
    .option("--output-encoding <encoding>", "output character encoding; defaults to “utf8”", "utf8")
    .parse(process.argv)
    .opts()
Example #3
Source File: logger.js    From aresrpg with MIT License 6 votes vote down vote up
export default function logger({
  url = null,
  name = strip_extension(relative(root, fileURLToPath(url))),
}) {
  return pino({
    base: { name },
    level: 'info',
  })
}
Example #4
Source File: schemas.js    From ctzn with MIT License 6 votes vote down vote up
export async function setup () {
  const schemasPath = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'schemas')
  const schemaFilenames = await fsp.readdir(schemasPath)
  for (let filename of schemaFilenames) {
    try {
      const str = await fsp.readFile(path.join(schemasPath, filename), 'utf8')
      const obj = JSON.parse(str)
      if (!obj.id) throw new Error('No .id')
      schemas.set(obj.id, new Schema(obj))
    } catch (e) {
      console.error('Failed to load schema', filename)
      console.error(e)
      process.exit(1)
    }
  }
}
Example #5
Source File: hyp.js    From cli with MIT License 6 votes vote down vote up
// error output when no/invalid command is given
function none (args) {
  if (args.version) {
    const packageJson = JSON.parse(fs.readFileSync(path.join(fileURLToPath(import.meta.url), '../../package.json'), 'utf8'))
    console.log(packageJson.version)
    process.exit(0)
  }
  if (args._[0]) {
    console.error(`Invalid command: ${args._[0]}`)
  } else {
    usage(commands)
  }
}
Example #6
Source File: cli.js    From ZzFXM with MIT License 6 votes vote down vote up
options = cli({
  name: 'ZzFXM Song Conversion Tool',
  packageJson: resolve(dirname(fileURLToPath(import.meta.url)), 'package.json'),
  inputPaths: 'single',
  outputPath: 'optional',
  options: [
    { name: 'ignore-errors', alias: 'i', type: Boolean, description: 'Ignore incompatability errors with ZzxFM and the source song.' },
    { name: 'no-instruments', alias: 'n', type: Boolean, description: 'Don\'t generate instrument data.'},
    { name: 'sane-instruments', alias: 's', type: Boolean, description: 'Only generate data for known instruments.'},
    { name: 'pretty-print', alias: 'p', type: Boolean, description: 'Generate human-readable output file.'},
    { name: 'format', alias: 'f', values: ['none', 'esm'], type: String, description: `Output format.`, defaultValue: 'none'},
  ]
})
Example #7
Source File: utils.js    From rally-core-addon with Mozilla Public License 2.0 6 votes vote down vote up
__filename = fileURLToPath(import.meta.url)
Example #8
Source File: utils.js    From kit with MIT License 6 votes vote down vote up
/**
 * @typedef {{
 *   cwd: string;
 *   port: number;
 *   server: import('http').Server;
 *   base: string;
 *   browser: import('playwright-chromium').Browser;
 *   page: import('playwright-chromium').Page;
 * }} TestContext
 */

/**
 * @param {string} app
 * @param {(test: import('uvu').Test<TestContext>) => void} callback
 */
export function run(app, callback) {
	/** @type {import('uvu').Test<TestContext>} */
	const suite = uvu.suite(app);

	suite.before(async (context) => {
		try {
			const cwd = fileURLToPath(new URL(`apps/${app}`, import.meta.url));

			rimraf(`${cwd}/build`);

			await spawn('npm run build', {
				cwd,
				stdio: 'inherit',
				shell: true
			});

			context.cwd = cwd;
			context.port = await ports.find(4000);
			const handler = sirv(`${cwd}/build`, {
				single: '200.html'
			});
			context.server = await create_server(context.port, handler);

			context.base = `http://localhost:${context.port}`;
			context.browser = await chromium.launch();
			context.page = await context.browser.newPage();
		} catch (e) {
			// TODO remove unnecessary try-catch https://github.com/lukeed/uvu/pull/61
			console.error(e);
		}
	});

	suite.after(async (context) => {
		context.server.close();
		context.browser.close();
	});

	callback(suite);

	suite.run();
}
Example #9
Source File: path.js    From bot with GNU General Public License v3.0 6 votes vote down vote up
/**
 * pathTo is a oneline solution for resolving path.resolve(__dirname, 'something.js') to an absolute path.
 * I created this as a replacement for desm, because you don't need another
 * npm package just for resolving this one.
 * @param {ImportMeta.url} url import.meta.url
 * @param {String} path
 * @returns {import("fs").PathLike} Absolute path from the given path string
 * @example
 * // Say we call the function from src/app.js
 * const envPath = pathTo('../env') // returns the full .env path outside the src dir
 * const redisPath = pathTo('./utils/redis.js') // returns what you expect.
 */
export function pathTo(url, path) {
  return resolve(dirname(fileURLToPath(url)), path);
}
Example #10
Source File: dirname.js    From javascript with MIT License 6 votes vote down vote up
/**
 * Returns __dirname
 * @param url — import.meta.url
 * @returns
 */
export default function dirname (url) {
  if (!url) throw Error("Please provide 'import.meta.url' to dirname")
  return path.dirname(fileURLToPath(url))
}
Example #11
Source File: constants.js    From BlockYouTubeAdsShortcut with GNU General Public License v3.0 5 votes vote down vote up
__dirname = dirname(fileURLToPath(import.meta.url))
Example #12
Source File: commons.js    From gidget with Apache License 2.0 5 votes vote down vote up
export default function (metaURL = import.meta.url) {
  if (typeof metaURL !== 'string') throw new Error("metaURL must be a string");
  const require = createRequire(metaURL);
  const __filename = fileURLToPath(metaURL);
  const __dirname = dirname(__filename);
  return { require, __filename, __dirname };
}
Example #13
Source File: config.js    From HinataMd with GNU General Public License v3.0 5 votes vote down vote up
file = fileURLToPath(import.meta.url)
Example #14
Source File: genChangelog.js    From GooseMod with MIT License 5 votes vote down vote up
__dirname = dirname(fileURLToPath(import.meta.url))
Example #15
Source File: document.js    From architecture with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #16
Source File: document.js    From architecture-starter with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #17
Source File: document.js    From classes-starter with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #18
Source File: document.js    From javascript-30-starter with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #19
Source File: document.js    From javascript-quiz with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #20
Source File: test.js    From old-javascript-30-starter with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #21
Source File: document.js    From separation-of-concerns with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #22
Source File: webpack.config.js    From tinyimg-webpack-plugin with MIT License 5 votes vote down vote up
__dirname = dirname(fileURLToPath(import.meta.url))
Example #23
Source File: docs.js    From bitECS with Mozilla Public License 2.0 5 votes vote down vote up
__dirname = dirname(fileURLToPath(import.meta.url))
Example #24
Source File: index.js    From playwright-addons with MIT License 5 votes vote down vote up
/**
 * Enable the stealth add-on
 * @param {Browser} br - Playwright Browser or BrowserContext object
 */
export default async function (br) {
    if (typeof br !== 'object' || !(br.contexts || br.pages)) {
        console.error('Need to provide a Playwright Browser or BrowserContext object');
    } else {
        let context = br.contexts ? br.contexts() : [br];

        await context.forEach(async c => {
            // Init evasions script on every page load
            await c.addInitScript({ path: dirname(fileURLToPath(import.meta.url)) + '/evasions.js' });

            // Properly set UA info (vanilla Playwright only sets the UA)
            const userAgent = c._options.userAgent || '';
            const acceptLanguage = c._options.locale;
            const platform = userAgent.indexOf('Macintosh') !== -1 ? 'MacIntel' : (userAgent.indexOf('Windows') !== -1 ? 'Win32' : '');
            const oscpu = userAgent.match('(Intel.*?|Windows.*?)[;)]') ? userAgent.match('(Intel.*?|Windows.*?)[;)]')[1] : '';
            const userAgentMetadata = undefined; // TODO, see https://chromedevtools.github.io/devtools-protocol/tot/Emulation/#type-UserAgentMetadata

            // Firefox - write to prefs
            if (br.constructor.name.indexOf('FFBrowser') === 0) {
                let prefs = `
                user_pref("general.appversion.override", "` + userAgent.replace('Mozilla/', '') + `");
                user_pref("general.oscpu.override", "` + oscpu + `");
                user_pref("general.platform.override", "` + platform + `");
                user_pref("general.useragent.override", "` + userAgent + `");
                `;
                if (acceptLanguage) {
                    prefs += `
                    user_pref("general.useragent.locale", "` + acceptLanguage + `");
                    user_pref("intl.accept_languages", "` + acceptLanguage + `");
                    `;
                }
                let proc = (br._options.ownedServer ? br._options.ownedServer : br._browser._options.ownedServer)._process;
                proc.spawnargs.forEach((a, k) => {
                    if (a.indexOf('-profile') !== -1) {
                        let dir = proc.spawnargs[k + 1];
                        appendFileSync(dir + '/prefs.js', prefs);
                    }
                });
            } else { // Chromium - use CDP to override
                c.pages().forEach(async p => {
                    try {
                        (await p.context().newCDPSession(p)).send('Emulation.setUserAgentOverride', { userAgent, acceptLanguage, platform, userAgentMetadata })
                    } catch (e) { console.log('Warning: could not set UA override:', e); }
                });

                c.on('page', async p => {
                    try {
                        (await p.context().newCDPSession(p)).send('Emulation.setUserAgentOverride', { userAgent, acceptLanguage, platform, userAgentMetadata })
                    } catch (e) { console.log('Warning: could not set UA override:', e); }
                });

            }
        });

        console.log('Stealth enabled');
    }
}
Example #25
Source File: obfuscated.spec.js    From js-x-ray with MIT License 5 votes vote down vote up
__dirname = dirname(fileURLToPath(import.meta.url))
Example #26
Source File: factory.js    From SquadJS with Boost Software License 1.0 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))
Example #27
Source File: index.js    From ip-index with GNU General Public License v3.0 5 votes vote down vote up
__filename = fileURLToPath(import.meta.url)
Example #28
Source File: generate-helpers.js    From cs-wiki with GNU General Public License v3.0 5 votes vote down vote up
export default async function generateHelpers() {
  let output = `/*
 * This file is auto-generated! Do not modify it directly.
 * To re-generate run 'yarn gulp generate-runtime-helpers'
 */

import template from "@babel/template";

function helper(minVersion, source) {
  return Object.freeze({
    minVersion,
    ast: () => template.program.ast(source),
  })
}

export default Object.freeze({
`;

  for (const file of (await fs.promises.readdir(HELPERS_FOLDER)).sort()) {
    if (IGNORED_FILES.has(file)) continue;
    if (file.startsWith(".")) continue; // ignore e.g. vim swap files

    const [helperName] = file.split(".");

    const filePath = join(fileURLToPath(HELPERS_FOLDER), file);
    if (!file.endsWith(".js")) {
      console.error("ignoring", filePath);
      continue;
    }

    const fileContents = await fs.promises.readFile(filePath, "utf8");
    const minVersionMatch = fileContents.match(
      /^\s*\/\*\s*@minVersion\s+(?<minVersion>\S+)\s*\*\/\s*$/m
    );
    if (!minVersionMatch) {
      throw new Error(`@minVersion number missing in ${filePath}`);
    }
    const { minVersion } = minVersionMatch.groups;

    const source = await minify(fileContents, {
      mangle: false,
      // The _typeof helper has a custom directive that we must keep
      compress: { directives: false },
    });

    output += `\
  ${JSON.stringify(helperName)}: helper(
    ${JSON.stringify(minVersion)},
    ${JSON.stringify(source.code)},
  ),
`;
  }

  output += "});";
  return output;
}
Example #29
Source File: index.test.js    From v8-deopt-viewer with MIT License 5 votes vote down vote up
__dirname = path.dirname(fileURLToPath(import.meta.url))