url#Url TypeScript Examples

The following examples show how to use url#Url. 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: utils.ts    From next-page-tester with MIT License 7 votes vote down vote up
export function parseRoute({
  route,
}: {
  route: string;
}): {
  urlObject: URL;
  detectedLocale: string | undefined;
} {
  const { i18n } = getNextConfig();
  const locales = i18n?.locales;
  const urlObject = new URL(`http://test.com${route}`);
  const { pathname: localePath } = urlObject;
  const { pathname, detectedLocale } = normalizeLocalePath(localePath, locales);
  urlObject.pathname = pathname;

  /*
   * Next.js redirects by default routes with trailing slash to the counterpart without trailing slash
   * @NOTE: Here we might handle Next.js trailingSlash option
   * https://nextjs.org/docs/api-reference/next.config.js/trailing-slash
   */
  if (pathname.endsWith('/') && pathname !== '/') {
    urlObject.pathname = pathname.slice(0, -1);
  }

  return { urlObject, detectedLocale };
}
Example #2
Source File: utils.ts    From views with MIT License 7 votes vote down vote up
getViewsKeys = (req: VercelRequest): RequestViewer => {
  let { hostname } = new URL(req.headers.referer)
  if (!hostname) throw new Error('not found origin')

  const isAllow = domains.includes(hostname)
  if (!isAllow) throw new Error('not allow')

  const viewId = md5(hostname)
  const key = md5(req.query.key as string)
  return {
    viewId,
    key,
    host: `${hostname}`,
    page: `${req.query.key}`,
  }
}
Example #3
Source File: connection.ts    From Assistive-Webdriver with MIT License 6 votes vote down vote up
async connect(url: string): Promise<void> {
    const parsedURL = new URL(url);
    const urlWithoutAuth = format(parsedURL, {
      auth: false
    });
    this.websessionManager = await connect(urlWithoutAuth);
    this.virtualbox = await this.websessionManager.logon(
      parsedURL.username,
      parsedURL.password
    );
    this.keepAlive();
  }
Example #4
Source File: impl.ts    From kassette with MIT License 6 votes vote down vote up
export async function requestHTTPS({
  url,
  method,
  headers,
  body,
}: RequestPayload): Promise<IncomingMessage> {
  const { hostname, port, pathname, search, hash } = new URL(url);
  return new Promise<IncomingMessage>((resolve, reject) =>
    httpsRequest(
      // url,
      // {rejectUnauthorized: false, method, headers},

      // XXX 2018-12-17T11:57:56+01:00
      // This is to make it compatible with older versions of Node.js
      // as well as some 3rd-party dependencies used in e2e testing
      // see https://github.com/TooTallNate/node-agent-base/issues/24
      // agent-base is indirectly used by puppeteer
      // and patches this Node.js core API
      {
        rejectUnauthorized: false,
        method,
        headers,

        hostname,
        port,
        path: [pathname, search, hash].join(''),
      },
      (message) => resolve(message),
    )
      .on('error', reject)
      .end(body),
  );
}
Example #5
Source File: url-explode.parser.ts    From nr-apm-stack with Apache License 2.0 6 votes vote down vote up
/**
   * Add exploded url to document
   * @param document The document to modify
   */
  apply(document: OsDocument): void {
    const urlOriginal: string = lodash.get(document.data, 'url.original');

    // Do nothing if not set
    if (!urlOriginal) {
      return;
    }

    try {
      if (urlOriginal.startsWith('/')) {
        // eslint-disable-next-line max-len
        if (!lodash.isNil(lodash.get(document.data, 'url.scheme')) && !lodash.isNil(lodash.get(document.data, 'url.domain')) && !lodash.isNil(lodash.get(document.data, 'url.port'))) {
          // eslint-disable-next-line max-len
          const url = new URL(`${lodash.get(document.data, 'url.scheme')}://${lodash.get(document.data, 'url.domain')}:${lodash.get(document.data, 'url.port')}${urlOriginal}`);
          lodash.merge(document.data.url, this.explodeURL(url));
        } else {
          const url = new URL(`http://localhost:80${urlOriginal}`);
          lodash.merge(document.data.url, this.explodeURL(url));
          lodash.unset(document.data.url, 'scheme');
          lodash.unset(document.data.url, 'port');
          lodash.unset(document.data.url, 'domain');
          lodash.unset(document.data.url, 'full');
        }
      } else if (urlOriginal === '*') {
        // Do nothing
      } else if (regexUrlWithProtocol.exec(urlOriginal)) {
        lodash.merge(document.data.url, this.explodeURL(new URL(urlOriginal)));
      } else {
        lodash.merge(document.data.url, this.explodeURL(new URL(`http://${urlOriginal}`)));
      }
    } catch (e: unknown) {
      throw new ParserError(`Could not parse [${urlOriginal}]`, this.constructor.name);
    }
  }
Example #6
Source File: EmbedBuilder.ts    From evolvejs with GNU Affero General Public License v3.0 6 votes vote down vote up
public setThumbnail(
		url: URL,
		proxyURL?: URL,
		height?: number,
		width?: number
	): EmbedBuilder {
		const thumbnail = new EmbedThumbnailBuilder();
		if (url) thumbnail.setURL(url);
		if (proxyURL) thumbnail.setProxyURL(proxyURL);
		if (height) thumbnail.setHeight(height);
		if (width) thumbnail.setWidth(width);

		this.thumbnail = thumbnail.build();
		return this;
	}
Example #7
Source File: datadog.ts    From dd-opentelemetry-exporter-js with Apache License 2.0 6 votes vote down vote up
constructor(config: DatadogExporterConfig = {}) {
    this._url =
      config.agentUrl ||
      process.env.DD_TRACE_AGENT_URL ||
      DatadogExportDefaults.AGENT_URL;
    this._logger = config.logger || new api.NoopLogger();
    this._serviceName =
      config.serviceName ||
      process.env.DD_SERVICE ||
      DatadogExportDefaults.SERVICE_NAME;
    this._env = config.env || process.env.DD_ENV;

    this._version = config.version || process.env.DD_VERSION;
    this._tags = config.tags || process.env.DD_TAGS;
    this._flushInterval =
      config.flushInterval || DatadogExportDefaults.FLUSH_INTERVAL;
    this._exporter = new AgentExporter(
      { url: new URL(this._url), flushInterval: this._flushInterval },
      new PrioritySampler()
    );
    this._isShutdown = false;
  }
Example #8
Source File: ImageData.ts    From context-mod with MIT License 6 votes vote down vote up
static fromSubmission(sub: Submission, aggressive = false): ImageData {
        const url = new URL(sub.url);
        const data: any = {
            url,
        };
        let variants = [];
        if (sub.preview !== undefined && sub.preview.enabled && sub.preview.images.length > 0) {
            const firstImg = sub.preview.images[0];
            const ref = sub.preview.images[0].source;
            data.width = ref.width;
            data.height = ref.height;

            variants = firstImg.resolutions.map(x => new ImageData(x));
            data.variants = variants;
        }
        return new ImageData(data, aggressive);
    }
Example #9
Source File: dynamicLinks.ts    From companion-kit with MIT License 6 votes vote down vote up
export function getClientInviteLink(params?: { [x: string]: string }) {
    const url = new URL(LinksSettings.ClientInvitationLink);
    if (params) {
        Object.keys(params).forEach(k => {
            url.searchParams.append(k, params[k]);
        });
    }

    return url.href;
}
Example #10
Source File: index.ts    From javascript-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Sends an HTTP GET request to Kava
 * @param {String} path the request's url extension
 * @param {String} base the request's base url
 * @return {Promise}
 */
async function getTx(path: string, base: string, timeout = 5000, args = {}) {
  const requestUrl = new URL(path, base).toString();

  try {
    return await retry(
      axios.get,
      axios,
      [applyRequestArgs(requestUrl, args)],
      Math.floor(timeout / 1000),
      1000,
      false
    );
  } catch (err) {
    throw err;
  }
}
Example #11
Source File: UserInfo.ts    From ADR-Gateway with MIT License 6 votes vote down vote up
ForwardRequest = async (dh: DataholderOidcResponse, consent: ConsentRequestLog, req: express.Request, res:express.Response) =>{

        let url = new URL(await dh.userinfo_endpoint)

        let headers = <any>{
            "content-type":"application/json",
            "accept":"application/json",
            Authorization: `Bearer ${consent.accessToken}`
        }

        let options:AxiosRequestConfig = {
            method: "GET",
            url: url.toString(),
            headers: headers,
            responseType:"json"
        }

        this.clientCertInjector.inject(options,consent.softwareProductId);

        try {
            let dhRes = await axios.request(options);
            if (dhRes.status == 200) {
                return res.json(dhRes.data)
            } else {
                throw 'Unexpected userInfo access error'
            }
        } catch (e) {
            throw new UserInfoAccessError(e);
        }

    }
Example #12
Source File: BinanceService.ts    From sakeperp-arbitrageur with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private async makeRequest(
        uri: string,
        method: Method,
        requiredAuthentication: AuthenticationMethod,
        ...parameters: [string, any][]
    ): Promise<any> {
        const apiUrl: URL = new URL(uri)

        for (const parameter of parameters) {
            if (this.isNullOrUndefined(parameter[1])) {
                continue
            }
            apiUrl.searchParams.append(parameter[0], parameter[1].toString())
        }

        const headers: any = this.setupAuthentication(
            apiUrl,
            requiredAuthentication
        )

        try {
            return await axios.request({
                method: method,
                url: apiUrl.href,
                headers: headers,
            })
        } catch (error) {
            this.log.jinfo({
                event: "requestError",
                params: error,
            })
        }
    }
Example #13
Source File: renderer.ts    From Adachi-BOT with MIT License 6 votes vote down vote up
private getURL( route: string, params?: Record<string, any> ): string {
		const paramStr: string = new URLSearchParams( params ).toString();
		
		try {
			new URL( route );
			return `${ route }?${ paramStr }`;
		} catch ( e ) {
			const url: string = this.httpBase + route;
			return `${ url }?${ paramStr }`;
		}
	}
Example #14
Source File: app-file-protocol.ts    From awakened-poe-trade with MIT License 6 votes vote down vote up
export function createFileProtocol () {
  protocol.registerFileProtocol('app', (req, resp) => {
    const url = new URL(req.url)
    const pathName = path.join(url.host, url.pathname)
    resp({ path: path.join(__dirname, pathName) })
  })

  protocol.registerFileProtocol('app-file', (req, resp) => {
    resp({ path: path.join(app.getPath('userData'), 'apt-data/files', req.url.slice('app-file://'.length)) })
  })

  overlayOnEvent('OVERLAY->MAIN::import-file', (e, filePath) => {
    const file = fs.readFileSync(filePath)
    const hash = crypto.createHash('md5').update(file).digest('hex')
    const filename = `${hash}${path.extname(filePath)}`

    fs.mkdirSync(path.join(app.getPath('userData'), 'apt-data/files'), { recursive: true })
    fs.writeFileSync(path.join(app.getPath('userData'), 'apt-data/files', filename), file)

    e.returnValue = `app-file://${filename}`
  })
}
Example #15
Source File: AWSLambdaGatewayAPIHTTP.ts    From skywalking-nodejs with Apache License 2.0 6 votes vote down vote up
start(event: any, context: any): Span {
    const headers = event.headers;
    const reqCtx = event.requestContext;
    const http = reqCtx?.http;
    const method = http?.method;
    const proto = http?.protocol ? http.protocol.split('/')[0].toLowerCase() : headers?.['x-forwarded-proto'];
    const port = headers?.['x-forwarded-port'] || '';
    const host = headers?.host ?? (reqCtx?.domainName || '');
    const hostport = host ? (port ? `${host}:${port}` : host) : port;
    const operation = http?.path ?? event.rawPath ?? (context.functionName ? `/${context.functionName}` : '/');

    const query = event.rawQueryString
      ? `?${event.rawQueryString}`
      : event.queryStringParameters
      ? '?' +
        Object.entries(event.queryStringParameters)
          .map(([k, v]) => `${k}=${v}`)
          .join('&')
      : '';

    const carrier = headers && ContextCarrier.from(headers);

    const span =
      method && ignoreHttpMethodCheck(method)
        ? DummySpan.create()
        : ContextManager.current.newEntrySpan(operation, carrier);

    span.layer = SpanLayer.HTTP;
    span.component = Component.AWSLAMBDA_GATEWAYAPIHTTP;
    span.peer = http?.sourceIp ?? headers?.['x-forwarded-for'] ?? 'Unknown';

    if (method) span.tag(Tag.httpMethod(method));

    if (hostport && proto) span.tag(Tag.httpURL(new URL(`${proto}://${hostport}${operation}${query}`).toString()));

    span.start();

    return span;
  }
Example #16
Source File: OAuthAdapter.ts    From backstage with Apache License 2.0 6 votes vote down vote up
static fromConfig(
    config: AuthProviderConfig,
    handlers: OAuthHandlers,
    options: Pick<
      Options,
      'providerId' | 'persistScopes' | 'tokenIssuer' | 'callbackUrl'
    >,
  ): OAuthAdapter {
    const { origin: appOrigin } = new URL(config.appUrl);

    const cookieConfigurer = config.cookieConfigurer ?? defaultCookieConfigurer;
    const cookieConfig = cookieConfigurer({
      providerId: options.providerId,
      baseUrl: config.baseUrl,
      callbackUrl: options.callbackUrl,
    });

    return new OAuthAdapter(handlers, {
      ...options,
      appOrigin,
      cookieDomain: cookieConfig.domain,
      cookiePath: cookieConfig.path,
      secure: cookieConfig.secure,
      isOriginAllowed: config.isOriginAllowed,
    });
  }
Example #17
Source File: authorizationError.ts    From cli with Apache License 2.0 6 votes vote down vote up
public constructor(public url: URL) {
    super();

    this.message = [
      url.searchParams.get('error'),
      url.searchParams.get('error_description'),
      url.searchParams.get('error_uri'),
    ]
      .filter((value) => value !== null)
      .join('\n');
  }
Example #18
Source File: Auth.ts    From fnbr.js with MIT License 6 votes vote down vote up
/**
   * Authentication via an authorization code
   * @param authorizationCodeResolvable A resolvable authorization code
   */
  private async authorizationCodeAuthenticate(authorizationCodeResolvable: AuthStringResolveable, authClient: AuthClient) {
    let authorizationCode: string | undefined;

    switch (typeof authorizationCodeResolvable) {
      case 'function':
        authorizationCode = await authorizationCodeResolvable();
        break;
      case 'string':
        if (authorizationCodeResolvable.length === 32) {
          authorizationCode = authorizationCodeResolvable;
        } else if (authorizationCodeResolvable.includes('?code=')) {
          try {
            const url = new URL(authorizationCodeResolvable);
            authorizationCode = url.searchParams.get('code') || undefined;
          } catch (err) {
            return { error: err as Error };
          }
        } else {
          try {
            authorizationCode = (await fs.readFile(authorizationCodeResolvable)).toString();
          } catch (err) {
            return { error: err as Error };
          }
        }
        break;
      default:
        return { error: new TypeError(`${typeof authorizationCodeResolvable} is not a valid authorization code type`) };
    }

    return this.getOAuthToken('authorization_code', { code: authorizationCode }, authClient);
  }
Example #19
Source File: stringify-request.ts    From playwright-fluent with MIT License 6 votes vote down vote up
export function toQueryString(url: string): QueryString {
  try {
    const nodeUrl = new URL(url);
    const rawSearch = nodeUrl.search;
    let rawQueryString = rawSearch;
    if (rawSearch && rawSearch.startsWith('?')) {
      rawQueryString = rawSearch.replace('?', '');
    }
    const query = querystring.parse(rawQueryString) as QueryString;
    return query;
  } catch (error) {
    return {};
  }
}
Example #20
Source File: NsisUpdater.ts    From electron-differential-updater with MIT License 6 votes vote down vote up
private async differentialDownloadWebPackage(
    packageInfo: PackageFileInfo,
    packagePath: string,
    provider: Provider<any>
  ): Promise<boolean> {
    if (packageInfo.blockMapSize == null) {
      return true;
    }

    try {
      await new FileWithEmbeddedBlockMapDifferentialDownloader(
        packageInfo,
        this.httpExecutor,
        {
          newUrl: new URL(packageInfo.path),
          oldFile: path.join(
            this.downloadedUpdateHelper!!.cacheDir,
            CURRENT_APP_PACKAGE_FILE_NAME
          ),
          logger: this._logger,
          newFile: packagePath,
          requestHeaders: this.requestHeaders,
          isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest
        }
      ).download();
    } catch (e) {
      this._logger.error(
        `Cannot download differentially, fallback to full download: ${e.stack ||
          e}`
      );
      // during test (developer machine mac or linux) we must throw error
      return process.platform === "win32";
    }
    return false;
  }
Example #21
Source File: shortener.lambda.ts    From cloudstructs with Apache License 2.0 6 votes vote down vote up
function isUrlValid(url?: string): boolean {
  if (!url) {
    return false;
  }
  try {
    new URL(url);
    return true;
  } catch (err) {
    return false;
  }
}
Example #22
Source File: proxy-middleware.ts    From kfp-tekton-backend with Apache License 2.0 6 votes vote down vote up
export function _routePathWithReferer(proxyPrefix: string, path: string, referer = ''): string {
  // If a referer header is included, extract the referer URL, otherwise
  // just trim out the /_proxy/ prefix. Use the origin of the resulting URL.
  const proxiedUrlInReferer = _extractUrlFromReferer(proxyPrefix, referer);
  let decodedPath = decodeURIComponent(proxiedUrlInReferer || _trimProxyPrefix(proxyPrefix, path));
  if (!decodedPath.startsWith('http://') && !decodedPath.startsWith('https://')) {
    decodedPath = 'http://' + decodedPath;
  }
  return new URL(decodedPath).origin;
}
Example #23
Source File: exec.ts    From harness-cli with Apache License 2.0 6 votes vote down vote up
async loadTemplate(path: string) {
        try {
            // try to parse as url
            // eslint-disable-next-line no-new
            new URL(path)
            const response = await axios.get(path)
            return response.data
        } catch {}

        try {
            const templateText = await fs.promises.readFile(path, { encoding: 'utf-8' })
            return templateText        
        } catch {}

        throw new Error(`Error loading template from ${path}`)
    }
Example #24
Source File: docview.ts    From vscode-lean4 with Apache License 2.0 6 votes vote down vote up
private mkRelativeUrl(relative: string, base: string): string {
        const uri = new URL(relative, base);
        if (uri.protocol === 'file:') {
            if (new URL(base).protocol !== 'file:') {
                return '';
            }
            const path = Uri.parse(uri.toString()).fsPath;
            if (this.webview) {
                return this.webview.webview.asWebviewUri(Uri.parse(uri.toString())).toString();
            }
            return '';
        } else {
            return uri.toString();
        }
    }
Example #25
Source File: webhook.ts    From livepeer-com with MIT License 6 votes vote down vote up
function validateWebhookPayload(id, userId, createdAt, payload) {
  try {
    new URL(payload.url);
  } catch (e) {
    console.error(`couldn't parse the provided url: ${payload.url}`);
    throw new UnprocessableEntityError(`bad url: ${payload.url}`);
  }

  if (!payload.events && !payload.event) {
    throw new UnprocessableEntityError(
      `must provide "events" field with subscriptions`
    );
  }

  return {
    id,
    userId,
    createdAt,
    kind: "webhook",
    name: payload.name,
    events: payload.events ?? [payload.event],
    url: payload.url,
    sharedSecret: payload.sharedSecret,
    streamId: payload.streamId,
  };
}
Example #26
Source File: parser.ts    From vscode-rss with MIT License 6 votes vote down vote up
function resolveAttr($: CheerioAPI, base: string, selector: string, attr: string) {
    $(selector).each((_, ele) => {
        const $ele = $(ele);
        const url = $ele.attr(attr);
        if (url) {
            try {
                $ele.attr(attr, new URL(url, base).href);
            } catch {}
        }
    });
}
Example #27
Source File: spanUtils.ts    From opentelemetry-azure-monitor-js with MIT License 6 votes vote down vote up
function createRequestData(span: ReadableSpan): RequestData {
  const data = new RequestData();
  data.name = span.name;
  data.id = `|${span.spanContext.traceId}.${span.spanContext.spanId}.`;
  data.success = span.status.code === CanonicalCode.OK;
  data.responseCode = String(span.status.code);
  data.duration = msToTimeSpan(hrTimeToMilliseconds(span.duration));
  data.ver = 1;
  data.source = undefined;

  if (span.attributes[HTTP_METHOD]) {
    data.name = span.attributes[HTTP_METHOD] as string;

    if (span.attributes[HTTP_STATUS_CODE]) {
      data.responseCode = String(span.attributes[HTTP_STATUS_CODE]);
    }

    if (span.attributes[HTTP_URL]) {
      data.url = span.attributes[HTTP_URL] as string;
    }

    if (span.attributes[HTTP_ROUTE]) {
      data.name = `${span.attributes[HTTP_METHOD]} ${span.attributes[HTTP_ROUTE]}`;
    } else if (span.attributes[HTTP_URL]) {
      const url = new URL(span.attributes[HTTP_URL] as string);
      data.name = `${span.attributes[HTTP_METHOD]} ${url.pathname}`;
    }
  }

  if (span.attributes[GRPC_STATUS_CODE]) {
    data.responseCode = String(span.attributes[GRPC_STATUS_CODE]);
  }
  if (span.attributes[GRPC_METHOD]) {
    data.url = String(span.attributes[GRPC_METHOD]);
  }

  return data;
}
Example #28
Source File: saml.ts    From node-saml with MIT License 6 votes vote down vote up
private getCallbackUrl(host?: string | undefined) {
    // Post-auth destination
    if (this.options.callbackUrl) {
      return this.options.callbackUrl;
    } else {
      const url = new URL("http://localhost");
      if (host) {
        url.host = host;
      } else {
        url.host = this.options.host;
      }
      if (this.options.protocol) {
        url.protocol = this.options.protocol;
      }
      url.pathname = this.options.path;
      return url.toString();
    }
  }
Example #29
Source File: TuyaAPIHelper.ts    From homebridge-tuya-ir with Apache License 2.0 6 votes vote down vote up
_loginApiCall(endpoint: string, body: object, cb) {
        // eslint-disable-next-line @typescript-eslint/no-this-alias
        const _this = this;

        const parsedUrl = new URL(endpoint);
        this._calculateSign(false, parsedUrl.search, parsedUrl.pathname, 'GET');
        const options = {
            url: endpoint,
            headers: {
                'client_id': this.clientId,
                'sign': this.signKey,
                't': this.timestamp,
                'sign_method': 'HMAC-SHA256',
                'nonce': ''
            }
        };

        request.get(options, function (error, response, body) {
            _this.log.debug("API call successful.");
            cb(body);
        })
            .on('error', (err) => {
                _this.log.error("API call failed.");
                _this.log.error(err);
            })
    }