How to use the url.pathToFileURL function in url

To help you get started, we’ve selected a few url examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github graalvm / graaljs / test / parallel / test-policy-integrity.js View on Github external
const parentURL = pathToFileURL(parentFilepath);
const parentBody = 'require(\'./dep.js\')';

const workerSpawningFilepath = path.join(tmpdir.path, 'worker_spawner.js');
const workerSpawningURL = pathToFileURL(workerSpawningFilepath);
const workerSpawningBody = `
const { Worker } = require('worker_threads');
// make sure this is gone to ensure we don't do another fs read of it
// will error out if we do
require('fs').unlinkSync(${JSON.stringify(policyFilepath)});
const w = new Worker(${JSON.stringify(parentFilepath)});
w.on('exit', process.exit);
`;

const depFilepath = path.join(tmpdir.path, 'dep.js');
const depURL = pathToFileURL(depFilepath);
const depBody = '';
const policyToDepRelativeURLString = `./${
  path.relative(path.dirname(policyFilepath), depFilepath)
}`;

fs.writeFileSync(parentFilepath, parentBody);
fs.writeFileSync(depFilepath, depBody);

const tmpdirURL = pathToFileURL(tmpdir.path);
if (!tmpdirURL.pathname.endsWith('/')) {
  tmpdirURL.pathname += '/';
}
function test({
  shouldFail = false,
  preload = [],
  entry,
github graalvm / graaljs / test / parallel / test-url-pathtofileurl.js View on Github external
const fileURL = url.pathToFileURL('test/').href;
  assert.ok(fileURL.startsWith('file:///'));
  assert.ok(fileURL.endsWith('/'));
}

{
  const fileURL = url.pathToFileURL('test\\').href;
  assert.ok(fileURL.startsWith('file:///'));
  if (isWindows)
    assert.ok(fileURL.endsWith('/'));
  else
    assert.ok(fileURL.endsWith('%5C'));
}

{
  const fileURL = url.pathToFileURL('test/%').href;
  assert.ok(fileURL.includes('%25'));
}

{
  let testCases;
  if (isWindows) {
    testCases = [
      // lowercase ascii alpha
      { path: 'C:\\foo', expected: 'file:///C:/foo' },
      // uppercase ascii alpha
      { path: 'C:\\FOO', expected: 'file:///C:/FOO' },
      // dir
      { path: 'C:\\dir\\foo', expected: 'file:///C:/dir/foo' },
      // trailing separator
      { path: 'C:\\dir\\', expected: 'file:///C:/dir/' },
      // dot
github sourcegraph / sourcegraph-typescript / src / server / server.ts View on Github external
const logger = new PrefixedLogger(connectionLogger, 'install ' + relPackageRoot)
            try {
                const absPackageJsonPath = path.join(extractPath, relPackageRoot, 'package.json')
                const npmConfig = configuration['typescript.npmrc'] || {}
                const hasDeps = await filterDependencies(absPackageJsonPath, { npmConfig, logger, tracer, span, token })
                if (!hasDeps) {
                    return
                }
                // It's important that each concurrent yarn process has their own global and cache folders
                const globalFolder = path.join(globalFolderRoot, relPackageRoot)
                const cacheFolder = path.join(cacheFolderRoot, relPackageRoot)
                const cwd = path.join(extractPath, relPackageRoot)
                await Promise.all([mkdirp(path.join(globalFolder)), mkdirp(path.join(cacheFolder))])
                await install({ cwd, globalFolder, cacheFolder, logger, tracer, span, token, withProgress })
                await sanitizeTsConfigs({
                    dir: pathToFileURL(path.join(cwd, 'node_modules')),
                    pickResourceRetriever,
                    logger,
                    tracer,
                    span,
                    token,
                })
                if (configuration['typescript.restartAfterDependencyInstallation'] !== false) {
                    await restartLanguageServer({ span, token })
                }
            } catch (err) {
                throwIfCancelled(token)
                logger.error('Installation failed', err)
            } finally {
                finishedDependencyInstallations.add(packageRootUri)
            }
        })
github ionic-team / capacitor / electron / index.js View on Github external
width: this.splashOptions.windowWidth,
      height: this.splashOptions.windowHeight,
      frame: false,
      show: false,
      transparent: this.splashOptions.transparentWindow,
      webPreferences: {
        // Required to load file:// splash screen
        webSecurity: false
      }
    });

    let imagePath = path.join(rootPath, 'splash_assets', this.splashOptions.imageFileName);
    let imageUrl = '';
    let useFallback = false;
    try {
      imageUrl = url.pathToFileURL(imagePath).href;
    } catch (err) {
      useFallback = true;
      imageUrl = `./${this.splashOptions.imageFileName}`;
    }

    let splashHtml = this.splashOptions.customHtml || `
      
             <div style="font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; color: ${this.splashOptions.textColor}; position: absolute; top: ${this.splashOptions.textPercentageFromTop}%; text-align: center; font-size: 10vw; width: 100vw;">
            ${this.splashOptions.loadingText}
          </div>
        
      
    `;

    this.mainWindowRef.on('closed', () =&gt; {
      if (this.splashWindow &amp;&amp; !this.splashWindow.isDestroyed()) {
github sourcegraph / sourcegraph-typescript / src / server / resources.ts View on Github external
public async *glob(pattern: URL, { ignore = [] }: GlobOptions = {}): AsyncIterable {
        const files = glob.stream(fileURLToPath(pattern), {
            ignore,
            absolute: true,
            markDirectories: true,
            onlyFiles: false,
        })
        // tslint:disable-next-line: await-promise https://github.com/palantir/tslint/issues/3997
        for await (const file of files) {
            yield pathToFileURL(file as string)
        }
    }
github graalvm / graaljs / graal-nodejs / lib / internal / bootstrap / pre_execution.js View on Github external
function initializePolicy() {
  const experimentalPolicy = getOptionValue('--experimental-policy');
  if (experimentalPolicy) {
    process.emitWarning('Policies are experimental.',
                        'ExperimentalWarning');
    const { pathToFileURL, URL } = require('url');
    // URL here as it is slightly different parsing
    // no bare specifiers for now
    let manifestURL;
    if (require('path').isAbsolute(experimentalPolicy)) {
      manifestURL = new URL(`file:///${experimentalPolicy}`);
    } else {
      const cwdURL = pathToFileURL(process.cwd());
      cwdURL.pathname += '/';
      manifestURL = new URL(experimentalPolicy, cwdURL);
    }
    const fs = require('fs');
    const src = fs.readFileSync(manifestURL, 'utf8');
    const experimentalPolicyIntegrity = getOptionValue('--policy-integrity');
    if (experimentalPolicyIntegrity) {
      const SRI = require('internal/policy/sri');
      const { createHash, timingSafeEqual } = require('crypto');
      const realIntegrities = new Map();
      const integrityEntries = SRI.parse(experimentalPolicyIntegrity);
      let foundMatch = false;
      for (var i = 0; i &lt; integrityEntries.length; i++) {
        const {
          algorithm,
          value: expected
github graalvm / graaljs / test / parallel / test-policy-integrity.js View on Github external
require('fs').unlinkSync(${JSON.stringify(policyFilepath)});
const w = new Worker(${JSON.stringify(parentFilepath)});
w.on('exit', process.exit);
`;

const depFilepath = path.join(tmpdir.path, 'dep.js');
const depURL = pathToFileURL(depFilepath);
const depBody = '';
const policyToDepRelativeURLString = `./${
  path.relative(path.dirname(policyFilepath), depFilepath)
}`;

fs.writeFileSync(parentFilepath, parentBody);
fs.writeFileSync(depFilepath, depBody);

const tmpdirURL = pathToFileURL(tmpdir.path);
if (!tmpdirURL.pathname.endsWith('/')) {
  tmpdirURL.pathname += '/';
}
function test({
  shouldFail = false,
  preload = [],
  entry,
  onerror = undefined,
  resources = {}
}) {
  const manifest = {
    onerror,
    resources: {}
  };
  for (const [url, { body, match }] of Object.entries(resources)) {
    manifest.resources[url] = {
github graalvm / graaljs / test / sequential / test-inspector-exception.js View on Github external
{ 'method': 'Runtime.enable' },
    { 'method': 'Debugger.enable' },
    { 'method': 'Debugger.setPauseOnExceptions',
      'params': { 'state': 'none' } },
    { 'method': 'Debugger.setAsyncCallStackDepth',
      'params': { 'maxDepth': 0 } },
    { 'method': 'Profiler.enable' },
    { 'method': 'Profiler.setSamplingInterval',
      'params': { 'interval': 100 } },
    { 'method': 'Debugger.setBlackboxPatterns',
      'params': { 'patterns': [] } },
    { 'method': 'Runtime.runIfWaitingForDebugger' }
  ];

  await session.send(commands);
  await session.waitForBreakOnLine(0, pathToFileURL(script).toString());
}
github taskrabbit / elasticsearch-dump / elasticdump.js View on Github external
return doc => {
            const filePath = transform.slice(1).split('?')
            const parsed = url.pathToFileURL(filePath[0])
            return require(parsed.pathname)(doc, ElasticDump.getParams(filePath[1]))
          }
        } else {
github elastic / kibana / x-pack / legacy / plugins / code / server / lsp / request_expander.ts View on Github external
private async sendInitRequest(workspacePath: string) {
    return await this.proxy.initialize(
      {},
      [
        {
          name: workspacePath,
          uri: pathToFileURL(workspacePath).href,
        },
      ],
      this.initialOptions
    );
  }