Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented browser and browserPrivate #294

Merged
merged 24 commits into from Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
8b11819
Added browser and browserPrivate under open.apps
leslieyip02 Jan 27, 2023
7253ffc
Switched default browser library
leslieyip02 Jan 30, 2023
5376f3d
Updated docs
leslieyip02 Jan 30, 2023
cc68d5a
Fixed issue with __dirname
leslieyip02 Jan 30, 2023
5828be0
Fix: removed ava test from test script
leslieyip02 Jan 30, 2023
4cf1a6d
Fix the `app` argument with WSL (#295)
kazarmy Jan 30, 2023
5c6582a
Removed unnecessary url import
leslieyip02 Feb 1, 2023
53bb565
Changed exports and specified supported browsers
leslieyip02 Feb 1, 2023
051edca
Fix `allowNonzeroExitCode` option (#296)
xirzec Feb 8, 2023
13a800c
Meta tweaks
sindresorhus Feb 8, 2023
27e4e3a
8.4.1
sindresorhus Feb 8, 2023
51fae87
Fix support for Podman
sindresorhus Feb 20, 2023
cbc008b
8.4.2
sindresorhus Feb 20, 2023
b3212fb
Mapped browser IDs to supported browsers
leslieyip02 Mar 13, 2023
aa21cad
Added browser and browserPrivate under open.apps
leslieyip02 Jan 27, 2023
f7b4c6d
Switched default browser library
leslieyip02 Jan 30, 2023
238770d
Updated docs
leslieyip02 Jan 30, 2023
009b28e
Fixed issue with __dirname
leslieyip02 Jan 30, 2023
69b4bb5
Fix: removed ava test from test script
leslieyip02 Jan 30, 2023
e368f9b
Removed unnecessary url import
leslieyip02 Feb 1, 2023
1af76c2
Changed exports and specified supported browsers
leslieyip02 Feb 1, 2023
a4867a4
Mapped browser IDs to supported browsers
leslieyip02 Mar 13, 2023
b185554
Merge branch 'main' of https://github.com/leslieyip02/open
leslieyip02 Mar 19, 2023
6d9d524
Added documentation for apps export
leslieyip02 Mar 19, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
62 changes: 40 additions & 22 deletions index.d.ts
Expand Up @@ -66,14 +66,32 @@ declare namespace open {
type AppName =
| 'chrome'
| 'firefox'
| 'edge';
| 'edge'
| 'browser'
| 'browserPrivate';

type App = {
name: string | readonly string[];
arguments?: readonly string[];
};
}

/**
An object containing auto-detected binary names for common apps. Useful to work around cross-platform differences.

@example
```
import open from 'open';

await open('https://google.com', {
app: {
name: open.apps.chrome
}
});
```
*/
declare const apps: Record<open.AppName, string | readonly string[]>;

// eslint-disable-next-line no-redeclare
declare const open: {
/**
Expand All @@ -88,20 +106,23 @@ declare const open: {

@example
```
import open = require('open');
import open from 'open';

// Opens the image in the default image viewer
// Opens the image in the default image viewer.
await open('unicorn.png', {wait: true});
console.log('The image viewer app closed');
console.log('The image viewer app quit');

// Opens the url in the default browser
// Opens the URL in the default browser.
await open('https://sindresorhus.com');

// Opens the URL in a specified browser.
await open('https://sindresorhus.com', {app: {name: 'firefox'}});

// Specify app arguments.
await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}});

// Opens the URL in the default browser in incognito mode.
await open('https://sindresorhus.com', {app: {name: open.apps.browserPrivate}});
```
*/
(
Expand All @@ -111,19 +132,8 @@ declare const open: {

/**
An object containing auto-detected binary names for common apps. Useful to work around cross-platform differences.

@example
```
import open = require('open');

await open('https://google.com', {
app: {
name: open.apps.chrome
}
});
```
*/
apps: Record<open.AppName, string | readonly string[]>;
apps: typeof apps;

/**
Open an app. Cross-platform.
Expand All @@ -135,19 +145,27 @@ declare const open: {

@example
```
const {apps, openApp} = require('open');
import open from 'open';
const {apps, openApp} = open;

// Open Firefox
// Open Firefox.
await openApp(apps.firefox);

// Open Chrome incognito mode
// Open Chrome in incognito mode.
await openApp(apps.chrome, {arguments: ['--incognito']});

// Open Xcode
// Open default browser.
await openApp(apps.browser);

// Open default browser in incognito mode.
await openApp(apps.browserPrivate);

// Open Xcode.
await openApp('xcode');
```
*/
openApp: (name: open.App['name'], options?: open.OpenAppOptions) => Promise<ChildProcess>;
};

export = open;
export {apps};
export default open;
92 changes: 79 additions & 13 deletions index.js
@@ -1,15 +1,37 @@
const path = require('path');
const childProcess = require('child_process');
const {promises: fs, constants: fsConstants} = require('fs');
const isWsl = require('is-wsl');
const isDocker = require('is-docker');
const defineLazyProperty = require('define-lazy-prop');
import path from 'path';
import {fileURLToPath} from 'url';
import childProcess from 'child_process';
import {promises as fs, constants as fsConstants} from 'fs';
import isWsl from 'is-wsl';
import isDocker from 'is-docker';
import defineLazyProperty from 'define-lazy-prop';
import defaultBrowser from 'default-browser';

// Path to included `xdg-open`.
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const localXdgOpenPath = path.join(__dirname, 'xdg-open');

const {platform, arch} = process;

// Podman detection
const hasContainerEnv = () => {
try {
fs.statSync('/run/.containerenv');
return true;
} catch {
return false;
}
};

let cachedResult;
function isInsideContainer() {
if (cachedResult === undefined) {
cachedResult = hasContainerEnv() || isDocker();
}

return cachedResult;
}

/**
Get the mount point for fixed drives in WSL.

Expand Down Expand Up @@ -98,6 +120,45 @@ const baseOpen = async options => {
}));
}

if (app === 'browser' || app === 'browserPrivate') {
// IDs from default-browser for macOS and windows are the same
const ids = {
'com.google.chrome': 'chrome',
'google-chrome.desktop': 'chrome',
'org.mozilla.firefox': 'firefox',
'firefox.desktop': 'firefox',
'com.microsoft.msedge': 'edge',
'com.microsoft.edge': 'edge',
'microsoft-edge.desktop': 'edge'
};

// Incognito flags for each browser in open.apps
const flags = {
chrome: '--incognito',
firefox: '--private-window',
edge: '--inPrivate'
};

const browser = await defaultBrowser();
if (browser.id in ids) {
const browserName = ids[browser.id];

if (app === 'browserPrivate') {
appArguments.push(flags[browserName]);
}

return baseOpen({
...options,
app: {
name: open.apps[browserName],
arguments: appArguments
}
});
}

throw new Error(`${browser.name} is not supported as a default browser`);
}

let command;
const cliArguments = [];
const childProcessOptions = {};
Expand All @@ -120,7 +181,7 @@ const baseOpen = async options => {
if (app) {
cliArguments.push('-a', app);
}
} else if (platform === 'win32' || (isWsl && !isDocker())) {
} else if (platform === 'win32' || (isWsl && !isInsideContainer() && !app)) {
const mountPoint = await getWslDrivesMountPoint();

command = isWsl ?
Expand All @@ -130,7 +191,7 @@ const baseOpen = async options => {
cliArguments.push(
'-NoProfile',
'-NonInteractive',
'ExecutionPolicy',
'-ExecutionPolicy',
'Bypass',
'-EncodedCommand'
);
Expand All @@ -148,17 +209,17 @@ const baseOpen = async options => {
if (app) {
// Double quote with double quotes to ensure the inner quotes are passed through.
// Inner quotes are delimited for PowerShell interpretation with backticks.
encodedArguments.push(`"\`"${app}\`""`, '-ArgumentList');
encodedArguments.push(`"\`"${app}\`""`);
if (options.target) {
appArguments.unshift(options.target);
appArguments.push(options.target);
}
} else if (options.target) {
encodedArguments.push(`"${options.target}"`);
}

if (appArguments.length > 0) {
appArguments = appArguments.map(arg => `"\`"${arg}\`""`);
encodedArguments.push(appArguments.join(','));
encodedArguments.push('-ArgumentList', appArguments.join(','));
}

// Using Base64-encoded command, accepted by PowerShell, to allow special characters.
Expand Down Expand Up @@ -209,7 +270,7 @@ const baseOpen = async options => {
subprocess.once('error', reject);

subprocess.once('close', exitCode => {
if (options.allowNonzeroExitCode && exitCode > 0) {
if (!options.allowNonzeroExitCode && exitCode > 0) {
reject(new Error(`Exited with code ${exitCode}`));
return;
}
Expand Down Expand Up @@ -309,7 +370,12 @@ defineLazyProperty(apps, 'edge', () => detectPlatformBinary({
wsl: '/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'
}));

defineLazyProperty(apps, 'browser', () => 'browser');

defineLazyProperty(apps, 'browserPrivate', () => 'browserPrivate');

open.apps = apps;
open.openApp = openApp;

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These should be named exports.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean something like this?

export {apps};
export default open;

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes

module.exports = open;
export {apps};
export default open;
2 changes: 1 addition & 1 deletion index.test-d.ts
@@ -1,6 +1,6 @@
import {expectType} from 'tsd';
import {ChildProcess} from 'child_process';
import open = require('.');
import open from '.';

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const options: open.Options = {};
Expand Down
4 changes: 3 additions & 1 deletion package.json
@@ -1,6 +1,7 @@
{
"name": "open",
"version": "8.4.0",
"type": "module",
"description": "Open stuff like URLs, files, executables. Cross-platform.",
"license": "MIT",
"repository": "sindresorhus/open",
Expand Down Expand Up @@ -50,7 +51,8 @@
"dependencies": {
"define-lazy-prop": "^2.0.0",
"is-docker": "^2.1.1",
"is-wsl": "^2.2.0"
"is-wsl": "^2.2.0",
"default-browser": "^3.1.0"
},
"devDependencies": {
"@types/node": "^15.0.0",
Expand Down
40 changes: 23 additions & 17 deletions readme.md
Expand Up @@ -26,7 +26,7 @@ npm install open
## Usage

```js
const open = require('open');
import open from 'open';

// Opens the image in the default image viewer and waits for the opened app to quit.
await open('unicorn.png', {wait: true});
Expand All @@ -41,10 +41,13 @@ await open('https://sindresorhus.com', {app: {name: 'firefox'}});
// Specify app arguments.
await open('https://sindresorhus.com', {app: {name: 'google chrome', arguments: ['--incognito']}});

// Open an app
// Opens the URL in the default browser in incognito mode.
await open('https://sindresorhus.com', {app: {name: open.apps.browserPrivate}});

// Open an app.
await open.openApp('xcode');

// Open an app with arguments
// Open an app with arguments.
await open.openApp(open.apps.chrome, {arguments: ['--incognito']});
```

Expand Down Expand Up @@ -116,25 +119,40 @@ Allow the opened app to exit with nonzero exit code when the `wait` option is `t

We do not recommend setting this option. The convention for success is exit code zero.

### open.apps
### open.apps / apps

An object containing auto-detected binary names for common apps. Useful to work around [cross-platform differences](#app).

```js
const open = require('open');
// Using default export.
import open from 'open';

await open('https://google.com', {
app: {
name: open.apps.chrome
}
});

// Using named export.
import open, {apps} from 'open';

await open('https://firefox.com', {
app: {
name: apps.browserPrivate
}
});
```
`browser` and `browserPrivate` can also be used to access the user's default browser through [`default-browser`](https://github.com/sindresorhus/default-browser).

#### Supported apps

- [`chrome`](https://www.google.com/chrome) - Web browser
- [`firefox`](https://www.mozilla.org/firefox) - Web browser
- [`edge`](https://www.microsoft.com/edge) - Web browser
- `browser` - Default web browser
- `browserPrivate` - Default web browser in incognito mode
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This needs to document which browsers it supports.


`browser` and `browserPrivate` only supports `chrome`, `firefox` and `edge`.

### open.openApp(name, options?)

Expand Down Expand Up @@ -169,15 +187,3 @@ These arguments are app dependent. Check the app's documentation for what argume

- [open-cli](https://github.com/sindresorhus/open-cli) - CLI for this module
- [open-editor](https://github.com/sindresorhus/open-editor) - Open files in your editor at a specific line and column

---

<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-opn?utm_source=npm-opn&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>