Skip to content

Commit

Permalink
Add navigator global with userAgent property
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Oct 2, 2023
1 parent f4e136d commit 2331b1e
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/five-goats-hang.md
@@ -0,0 +1,5 @@
---
'nxjs-runtime': patch
---

Add `navigator` global with `userAgent` property
3 changes: 2 additions & 1 deletion packages/runtime/src/fetch/fetch.ts
Expand Up @@ -5,6 +5,7 @@ import { decoder } from '../polyfills/text-decoder';
import { Request, type RequestInit } from './request';
import { Response } from './response';
import { Headers } from './headers';
import { navigator } from '../navigator';
import type { SwitchClass } from '../switch';

declare const Switch: SwitchClass;
Expand Down Expand Up @@ -143,7 +144,7 @@ async function fetchHttp(req: Request, url: URL) {
req.headers.set('host', url.host);
}
if (!req.headers.has('user-agent')) {
req.headers.set('user-agent', `nx.js/${Switch.version.nxjs}`);
req.headers.set('user-agent', navigator.userAgent);
}
if (!req.headers.has('accept')) {
req.headers.set('accept', '*/*');
Expand Down
3 changes: 3 additions & 0 deletions packages/runtime/src/index.ts
Expand Up @@ -22,6 +22,7 @@ export type {
export type { InspectOptions } from './inspect';
export type * from './types';
export type * from './console';
export type * from './navigator';
export type {
CanvasImageSource,
Canvas,
Expand Down Expand Up @@ -73,6 +74,8 @@ def('setInterval', setInterval);
def('clearTimeout', clearTimeout);
def('clearInterval', clearInterval);

import './navigator';

import * as WebAssembly from './wasm';
def('WebAssembly', WebAssembly);

Expand Down
33 changes: 33 additions & 0 deletions packages/runtime/src/navigator.ts
@@ -0,0 +1,33 @@
import { def } from './utils';
import type { SwitchClass } from './switch';

declare const Switch: SwitchClass;

/**
* The `Navigator` interface represents the state and the identity of the user agent.
* It allows scripts to query it and to register themselves to carry on some activities.
*
* A `Navigator` instance can be retrieved by accessing the global {@link navigator | `navigator`} property.
*
* @see https://developer.mozilla.org/docs/Web/API/Navigator
*/
export class Navigator {
constructor() {
throw new TypeError('Illegal constructor.');
}

/**
* Returns the value used for the `User-Agent` HTTP request header for
* HTTP requests initiated with {@link fetch | `fetch()`}.
*
* @example "my-app/0.0.1 (Switch; en-us; rv:14.1.2|AMS 1.5.4|E) nx.js/0.0.18"
* @see https://developer.mozilla.org/docs/Web/API/Navigator/userAgent
*/
get userAgent(): string {
return `nx.js/${Switch.version.nxjs}`;
}
}
def('Navigator', Navigator);

export const navigator: Navigator = Object.create(Navigator.prototype);
def('navigator', navigator);

0 comments on commit 2331b1e

Please sign in to comment.