Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
# Set the default behavior, in case people don't have core.autocrlf set.
* text=auto
# Declare files that will always have LF line endings on checkout.
cli.js text eol=lf
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
+265
View File
@@ -0,0 +1,265 @@
# Office-Addin-Dev-Settings
Provides the ability to configure developer settings for Office Add-ins.
## Command-Line Interface
* [appcontainer](#appcontainer)
* [clear](#clear)
* [debugging](#debugging)
* [live-reload](#live-reload)
* [register](#register)
* [registered](#registered)
* [runtime-log](#runtime-log)
* [sideload](#sideload)
* [source-bundle-url](#source-bundle-url)
* [unregister](#unregister)
* [webview](#webview)
#
### appcontainer
Display or configure settings related to the appcontainer for an Office Add-in.
Syntax:
`office-addin-dev-settings appcontainer <manifest> [options]`
`manifest`: path to manifest file.
Without options, displays the appcontainer name.
Notes:
* Without options, displays the appcontainer name and whether access to localhost is allowed.
* The appcontainer must be registered in order to allow access to loopback addresses.
Options:
`--loopback`
Allow access to loopback addresses such as `localhost`.
`--prevent-loopback`
Prevent access to loopback addresses such as `localhost`.
#
### clear
Clear developer settings for the Office Add-in.
Syntax:
`office-addin-debugging clear <manifest>`
`manifest`: path to manifest file.
#
### debugging
Display or configure debugging settings for an Office Add-in.
Syntax:
`office-addin-dev-settings debugging <manifest> [options]`
`manifest`: path to manifest file.
Without options, displays whether debugging is enabled.
Notes:
These settings do not apply when the Office Add-in runs in a web browser or WebView control.
Options:
`--disable`
Disable debugging for the Office Add-in.
`--enable`
Enable debugging for the Office Add-in.
`--debug-method <method>`
Specifies which debug method to use:
* `direct`: debug directly using the JavaScript engine.
* `web`: debug using the JavaScript engine in a web browser or Node.
#
### live-reload
Display or configure settings related to live reload for an Office Add-in.
Syntax:
`office-addin-dev-settings live-reload <manifest> [options]`
`manifest`: path to manifest file.
Without options, displays whether live reload is enabled.
Options:
`--disable`
Disable live-reload for the Office Add-in.
`--enable`
Enable live-reload for the Office Add-in.
#
### m365-account
Logs in or out of the m365 account used to sideload json manifests
Syntax:
`office-addin-dev-settings m365-account <operation>`
`operation`: 'login' or 'logout'
### register
Registers an Office Add-in for development.
Syntax:
`office-addin-dev-settings register <manifest> [options]`
`manifest`: path to manifest file.
#
### registered
Displays the Office Add-ins registered for development.
Syntax:
`office-addin-dev-settings registered [options]`
#
### runtime-log
Use the command to enable or disable writing any Office Add-in runtime events to a log file. Without options, it displays whether runtime logging is enabled.
Notes:
The setting is not specific to a particular Office Add-in. It applies to the runtime and will show information for all Office Add-ins.
Syntax:
`office-addin-dev-settings runtime-log [options]`
Without options, displays whether runtime logging is enabled and the log file path (if enabled).
Options:
`--disable`
Disable runtime logging.
`--enable [path]`
Enable runtime logging.
* `path`: Specify the path to the log file. If not specified, uses "OfficeAddins.log.txt" in the TEMP folder.
#
### sideload
Start Office and open a document so the Office Add-in is loaded.
Syntax:
`office-addin-dev-settings sideload <manifest> [app-type] [options]`
`manifest`: path to manifest file.
`app-type`: host application type to sideload ("desktop" or "web").
Note:
If the add-in supports more than one Office app and the app-type is "desktop", the command will prompt to choose the app unless the `--app` parameter is provided.
Options:
`-a`
`--app`
Specify the Office application to load.
`-d`
`--document`
Specify the document to sideload. The document option can either be the local path to a document or a url.
#
### source-bundle-url
Configure the url used to obtain the source bundle from the packager for an Office Add-in.
The url is composed as:
http://`HOST`:`PORT`/`PATH` `EXTENSION`
* `HOST`: host name; default is `localhost`
* `PORT`: port number; default is `8081`
* `PATH`: path
* `EXTENSION`: extension (including period); default is `.bundle`
Syntax:
`office-addin-dev-settings source-bundle-url [options]`
Without options, displays the current source-bundle-url settings.
Options:
`-h <name>`<br>
`--host <name>`
Specify the host name or "" to use the default.
`-p <number>`<br>
`--port <number>`
Specify the port number (0 to 65535) or "" to use the default.
`--path <path>`
Specify the path or "" to use the default.
`-e <string>`<br>
`--extension <string>`
Specify the extension (which should start with a period) or "" to use the default.
#
### unregister
Unregisters an Office Add-in for development.
Syntax:
`office-addin-dev-settings register <manifest> [options]`
`manifest`: path to manifest file.
#
### webview
Switches the webview runtime in Office for testing and development scenarios.
> Office must be running on the Beta channel to switch runtimes
Syntax:
`office-addin-dev-settings webview <manifest> <web-view-type>`
`manifest`: path to manifest file.
`web-view-type`: Office webview to load ('edge' or 'edge-chromium, 'edge-legacy', 'ie', or 'default').
#
+9
View File
@@ -0,0 +1,9 @@
#!/usr/bin/env node
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
//
// If the package.json bin config specifies a file in the lib folder, it will cause an
// error during "npm install" if the lib folder doesn't exist (because the package hasn't been built yet).
// It specifies this file instead which then calls into the file in the lib folder.
require("./lib/cli.js");
+20
View File
@@ -0,0 +1,20 @@
import officeAddins from "eslint-plugin-office-addins";
import tsParser from "@typescript-eslint/parser";
import sdl from "@microsoft/eslint-plugin-sdl";
export default [
...officeAddins.configs.recommended,
...sdl.configs.recommended,
{
plugins: {
"office-addins": officeAddins,
},
languageOptions: {
parser: tsParser,
parserOptions: {
projectService: true,
tsconfigRootDir: "__dirname"
}
},
},
];
+19
View File
@@ -0,0 +1,19 @@
/**
* The type of Office application.
*/
export declare enum AppType {
/**
* Office application for Windows or Mac
*/
Desktop = "desktop",
/**
* Office application for the web browser
*/
Web = "web"
}
/**
* Parse the input text and get the associated AppType
* @param text app-type/platform text
* @returns AppType or undefined.
*/
export declare function parseAppType(text: string | undefined): AppType | undefined;
+41
View File
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseAppType = exports.AppType = void 0;
const office_addin_usage_data_1 = require("office-addin-usage-data");
/**
* The type of Office application.
*/
var AppType;
(function (AppType) {
/**
* Office application for Windows or Mac
*/
AppType["Desktop"] = "desktop";
/**
* Office application for the web browser
*/
AppType["Web"] = "web";
})(AppType = exports.AppType || (exports.AppType = {}));
/**
* Parse the input text and get the associated AppType
* @param text app-type/platform text
* @returns AppType or undefined.
*/
function parseAppType(text) {
switch (text ? text.toLowerCase() : undefined) {
case "desktop":
case "macos":
case "win32":
case "ios":
case "android":
return AppType.Desktop;
case "web":
return AppType.Web;
case undefined:
return undefined;
default:
throw new office_addin_usage_data_1.ExpectedError(`Please select a valid app type instead of '${text}'.`);
}
}
exports.parseAppType = parseAppType;
//# sourceMappingURL=appType.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"appType.js","sourceRoot":"","sources":["../src/appType.ts"],"names":[],"mappings":";;;AAAA,qEAAwD;AAExD;;GAEG;AACH,IAAY,OAUX;AAVD,WAAY,OAAO;IACjB;;OAEG;IACH,8BAAmB,CAAA;IAEnB;;OAEG;IACH,sBAAW,CAAA;AACb,CAAC,EAVW,OAAO,GAAP,eAAO,KAAP,eAAO,QAUlB;AAED;;;;GAIG;AACH,SAAgB,YAAY,CAAC,IAAwB;IACnD,QAAQ,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE;QAC7C,KAAK,SAAS,CAAC;QACf,KAAK,OAAO,CAAC;QACb,KAAK,OAAO,CAAC;QACb,KAAK,KAAK,CAAC;QACX,KAAK,SAAS;YACZ,OAAO,OAAO,CAAC,OAAO,CAAC;QACzB,KAAK,KAAK;YACR,OAAO,OAAO,CAAC,GAAG,CAAC;QACrB,KAAK,SAAS;YACZ,OAAO,SAAS,CAAC;QACnB;YACE,MAAM,IAAI,uCAAa,CAAC,8CAA8C,IAAI,IAAI,CAAC,CAAC;KACnF;AACH,CAAC;AAfD,oCAeC"}
+42
View File
@@ -0,0 +1,42 @@
export declare const EdgeBrowserAppcontainerName: string;
export declare const EdgeWebViewAppcontainerName: string;
export declare const EdgeBrowserName: string;
export declare const EdgeWebViewName: string;
/**
* Adds a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform does not support appcontainers.
*/
export declare function addLoopbackExemptionForAppcontainer(name: string): Promise<void>;
/**
* Returns whether appcontainer is supported on the current platform.
* @returns True if platform supports using appcontainer; false otherwise.
*/
export declare function isAppcontainerSupported(): boolean;
/**
* Adds a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform does not support appcontainers.
*/
export declare function isLoopbackExemptionForAppcontainer(name: string): Promise<boolean>;
/**
* Returns the name of the appcontainer used to run an Office Add-in.
* @param sourceLocation Source location of the Office Add-in.
* @param isFromStore True if installed from the Store; false otherwise.
*/
export declare function getAppcontainerName(sourceLocation: string, isFromStore?: boolean): string;
export declare function getUserConfirmation(name: string): Promise<boolean>;
export declare function getAppcontainerNameFromManifestPath(manifestPath: string): Promise<string>;
export declare function getDisplayNameFromManifestPath(manifestPath: string): string;
export declare function ensureLoopbackIsEnabled(manifestPath: string, askForConfirmation?: boolean): Promise<boolean>;
/**
* Returns the name of the appcontainer used to run an Office Add-in.
* @param manifestPath Path of the manifest file.
*/
export declare function getAppcontainerNameFromManifest(manifestPath: string): Promise<string>;
/**
* Removes a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform doesn't support appcontainers.
*/
export declare function removeLoopbackExemptionForAppcontainer(name: string): Promise<void>;
+179
View File
@@ -0,0 +1,179 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeLoopbackExemptionForAppcontainer = exports.getAppcontainerNameFromManifest = exports.ensureLoopbackIsEnabled = exports.getDisplayNameFromManifestPath = exports.getAppcontainerNameFromManifestPath = exports.getUserConfirmation = exports.getAppcontainerName = exports.isLoopbackExemptionForAppcontainer = exports.isAppcontainerSupported = exports.addLoopbackExemptionForAppcontainer = exports.EdgeWebViewName = exports.EdgeBrowserName = exports.EdgeWebViewAppcontainerName = exports.EdgeBrowserAppcontainerName = void 0;
const tslib_1 = require("tslib");
const child_process_1 = tslib_1.__importDefault(require("child_process"));
const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
const office_addin_manifest_1 = require("office-addin-manifest");
const whatwg_url_1 = require("whatwg-url");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global process */
exports.EdgeBrowserAppcontainerName = "Microsoft.MicrosoftEdge_8wekyb3d8bbwe";
exports.EdgeWebViewAppcontainerName = "Microsoft.win32webviewhost_cw5n1h2txyewy";
exports.EdgeBrowserName = "Microsoft Edge Web Browser";
exports.EdgeWebViewName = "Microsoft Edge WebView";
/**
* Adds a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform does not support appcontainers.
*/
function addLoopbackExemptionForAppcontainer(name) {
if (!isAppcontainerSupported()) {
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
return new Promise((resolve, reject) => {
const command = `CheckNetIsolation.exe LoopbackExempt -a -n=${name}`;
child_process_1.default.exec(command, (error, stdout) => {
if (error) {
reject(stdout);
}
else {
resolve();
}
});
});
}
exports.addLoopbackExemptionForAppcontainer = addLoopbackExemptionForAppcontainer;
/**
* Returns whether appcontainer is supported on the current platform.
* @returns True if platform supports using appcontainer; false otherwise.
*/
function isAppcontainerSupported() {
return process.platform === "win32";
}
exports.isAppcontainerSupported = isAppcontainerSupported;
/**
* Adds a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform does not support appcontainers.
*/
function isLoopbackExemptionForAppcontainer(name) {
if (!isAppcontainerSupported()) {
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
return new Promise((resolve, reject) => {
const command = `CheckNetIsolation.exe LoopbackExempt -s`;
child_process_1.default.exec(command, (error, stdout) => {
if (error) {
reject(stdout);
}
else {
const expr = new RegExp(`Name: ${name}`, "i");
const found = expr.test(stdout);
resolve(found);
}
});
});
}
exports.isLoopbackExemptionForAppcontainer = isLoopbackExemptionForAppcontainer;
/**
* Returns the name of the appcontainer used to run an Office Add-in.
* @param sourceLocation Source location of the Office Add-in.
* @param isFromStore True if installed from the Store; false otherwise.
*/
function getAppcontainerName(sourceLocation, isFromStore = false) {
const url = new whatwg_url_1.URL(sourceLocation);
const origin = url.origin;
const addinType = isFromStore ? 0 : 1; // 0 if from Office Add-in store, 1 otherwise.
const guid = "04ACA5EC-D79A-43EA-AB47-E50E47DD96FC";
// Appcontainer name format is "{addinType}_{origin}{guid}".
// Replace characters ":" and "/" with "_".
const name = `${addinType}_${origin}${guid}`.replace(/[://]/g, "_");
return name;
}
exports.getAppcontainerName = getAppcontainerName;
function getUserConfirmation(name) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const question = {
message: `Allow localhost loopback for ${name}?`,
name: "didUserConfirm",
type: "confirm",
};
const answers = yield inquirer_1.default.prompt([question]);
return answers.didUserConfirm;
});
}
exports.getUserConfirmation = getUserConfirmation;
function getAppcontainerNameFromManifestPath(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (manifestPath.toLowerCase()) {
case "edgewebview":
return exports.EdgeWebViewAppcontainerName;
case "edgewebbrowser":
case "edge":
return exports.EdgeBrowserAppcontainerName;
default:
return yield getAppcontainerNameFromManifest(manifestPath);
}
});
}
exports.getAppcontainerNameFromManifestPath = getAppcontainerNameFromManifestPath;
function getDisplayNameFromManifestPath(manifestPath) {
switch (manifestPath.toLowerCase()) {
case "edgewebview":
return exports.EdgeWebViewName;
case "edgewebbrowser":
case "edge":
return exports.EdgeBrowserName;
default:
return manifestPath;
}
}
exports.getDisplayNameFromManifestPath = getDisplayNameFromManifestPath;
function ensureLoopbackIsEnabled(manifestPath, askForConfirmation = true) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const name = yield getAppcontainerNameFromManifestPath(manifestPath);
let isEnabled = yield isLoopbackExemptionForAppcontainer(name);
if (!isEnabled) {
if (!askForConfirmation ||
(yield getUserConfirmation(getDisplayNameFromManifestPath(manifestPath)))) {
yield addLoopbackExemptionForAppcontainer(name);
isEnabled = true;
}
}
return isEnabled;
});
}
exports.ensureLoopbackIsEnabled = ensureLoopbackIsEnabled;
/**
* Returns the name of the appcontainer used to run an Office Add-in.
* @param manifestPath Path of the manifest file.
*/
function getAppcontainerNameFromManifest(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
const sourceLocation = manifest.defaultSettings
? manifest.defaultSettings.sourceLocation
: undefined;
if (sourceLocation === undefined) {
throw new office_addin_usage_data_1.ExpectedError(`The source location could not be retrieved from the manifest.`);
}
return getAppcontainerName(sourceLocation, false);
});
}
exports.getAppcontainerNameFromManifest = getAppcontainerNameFromManifest;
/**
* Removes a loopback exemption for the appcontainer.
* @param name Appcontainer name
* @throws Error if platform doesn't support appcontainers.
*/
function removeLoopbackExemptionForAppcontainer(name) {
if (!isAppcontainerSupported()) {
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
return new Promise((resolve, reject) => {
const command = `CheckNetIsolation.exe LoopbackExempt -d -n=${name}`;
child_process_1.default.exec(command, (error, stdout) => {
if (error) {
reject(stdout);
}
else {
resolve();
}
});
});
}
exports.removeLoopbackExemptionForAppcontainer = removeLoopbackExemptionForAppcontainer;
//# sourceMappingURL=appcontainer.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"appcontainer.js","sourceRoot":"","sources":["../src/appcontainer.ts"],"names":[],"mappings":"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"}
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env node
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const commander_1 = require("commander");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const commands = tslib_1.__importStar(require("./commands"));
/* global console process */
const commander = new commander_1.Command();
commander.name("office-addin-dev-settings");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command("appcontainer <manifest-path>")
.description("Display or configure the appcontainer used to run the Office Add-in.")
.option("--loopback", `Allow access to loopback addresses such as "localhost".`)
.option("--prevent-loopback", `Prevent access to loopback addresses such as "localhost".`)
.option("-y,--yes", "Provide approval without any prompts.")
.action(commands.appcontainer);
commander
.command("clear [manifest-path]")
.description("Clear all dev settings for the Office Add-in.")
.action(commands.clear);
commander
.command("debugging <manifest-path>")
.option("--enable", `Enable debugging for the add-in.`)
.option("--disable", "Disable debugging for the add-in.")
.option("--debug-method <method>", "Specify the debug method: 'direct' or 'proxy'.")
.option("--open-dev-tools", "Open the web browser dev tools (if supported).")
.description("Configure debugging for the Office Add-in.")
.action(commands.debugging);
commander
.command("live-reload <manifest-path>")
.option("--enable", `Enable live-reload for the add-in.`)
.option("--disable", "Disable live-reload for the add-in")
.description("Configure live-reload for the Office Add-in.")
.action(commands.liveReload);
commander
.command("m365-account <operation>")
.description("Update the M365 account used for registration.")
.action(commands.m365Account);
commander
.command("register <manifest-path>")
.description("Register the Office Add-in for development.")
.action(commands.register);
commander
.command("registered")
.description("Show the Office Add-ins registered for development.")
.action(commands.registered);
commander
.command("runtime-log")
.option("--enable [path]", `Enable the runtime log.`)
.option("--disable", "Disable the runtime log.")
.description("Configure the runtime log for all Office Add-ins.")
.action(commands.runtimeLogging);
commander
.command("sideload <manifest-path> [app-type]")
.description("Launch Office with the Office Add-in loaded.")
.option("-a,--app <app>", `The Office app to launch. ("Excel", "Outlook", "PowerPoint", or "Word")`)
.option("-d,--document <document>", `The file path or url of the Office document to open.`)
.option("--registration <registration>", `Id of the registered add-in`)
.action(commands.sideload)
.on("--help", () => {
console.log("\n[app-type] specifies the type of Office app::\n");
console.log(" 'desktop': Office app for Windows or Mac (default)");
console.log(" 'web': Office running in the web browser");
});
commander
.command("source-bundle-url <manifest-path>")
.description("Specify values for components of the source bundle url.")
.option("-h,--host <host>", `The host name to use, or "" to use the default ('localhost').`)
.option("-p,--port <port>", `The port number to use, or "" to use the default (8081).`)
.option("--path <path>", `The path to use, or "" to use the default.`)
.option("-e,--extension <extension>", `The extension to use, or "" to use the default (".bundle").`)
.action(commands.sourceBundleUrl);
commander
.command("unregister <manifest-path>")
.description("Unregister the Office Add-in for development.")
.action(commands.unregister);
commander
.command("webview <manifest-path> [web-view-type]")
.description("Specify the type of web view to use when debugging. Windows only.")
.action(commands.webView)
.on("--help", () => {
console.log("\nFor [web-view-type], choose one of the following values:\n");
console.log("\t'edge' or 'edge-chromium' for Microsoft Edge (Chromium)");
console.log("\t'edge-legacy' for the legacy Microsoft Edge (EdgeHTML)");
console.log("\t'ie' for Internet Explorer 11");
console.log("\t'default' to remove any preference");
console.log("\nOmit [web-view-type] to see the current setting.");
});
// if the command is not known, display an error
commander.on("command:*", function () {
(0, office_addin_usage_data_1.logErrorMessage)(`The command syntax is not valid.\n`);
process.exitCode = 1;
commander.help();
});
if (process.argv.length > 2) {
commander.parse(process.argv);
}
else {
commander.help();
}
//# sourceMappingURL=cli.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";;AAEA,4DAA4D;AAC5D,kCAAkC;;;AAElC,yCAAoC;AACpC,qEAA0D;AAC1D,6DAAuC;AAEvC,4BAA4B;AAE5B,MAAM,SAAS,GAAG,IAAI,mBAAO,EAAE,CAAC;AAEhC,SAAS,CAAC,IAAI,CAAC,2BAA2B,CAAC,CAAC;AAC5C,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,yBAAyB,CAAC,CAAC;AAEhF,SAAS;KACN,OAAO,CAAC,8BAA8B,CAAC;KACvC,WAAW,CAAC,sEAAsE,CAAC;KACnF,MAAM,CAAC,YAAY,EAAE,yDAAyD,CAAC;KAC/E,MAAM,CAAC,oBAAoB,EAAE,2DAA2D,CAAC;KACzF,MAAM,CAAC,UAAU,EAAE,uCAAuC,CAAC;KAC3D,MAAM,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;AAEjC,SAAS;KACN,OAAO,CAAC,uBAAuB,CAAC;KAChC,WAAW,CAAC,+CAA+C,CAAC;KAC5D,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;AAE1B,SAAS;KACN,OAAO,CAAC,2BAA2B,CAAC;KACpC,MAAM,CAAC,UAAU,EAAE,kCAAkC,CAAC;KACtD,MAAM,CAAC,WAAW,EAAE,mCAAmC,CAAC;KACxD,MAAM,CAAC,yBAAyB,EAAE,gDAAgD,CAAC;KACnF,MAAM,CAAC,kBAAkB,EAAE,gDAAgD,CAAC;KAC5E,WAAW,CAAC,4CAA4C,CAAC;KACzD,MAAM,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AAE9B,SAAS;KACN,OAAO,CAAC,6BAA6B,CAAC;KACtC,MAAM,CAAC,UAAU,EAAE,oCAAoC,CAAC;KACxD,MAAM,CAAC,WAAW,EAAE,oCAAoC,CAAC;KACzD,WAAW,CAAC,8CAA8C,CAAC;KAC3D,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;AAE/B,SAAS;KACN,OAAO,CAAC,0BAA0B,CAAC;KACnC,WAAW,CAAC,gDAAgD,CAAC;KAC7D,MAAM,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AAEhC,SAAS;KACN,OAAO,CAAC,0BAA0B,CAAC;KACnC,WAAW,CAAC,6CAA6C,CAAC;KAC1D,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC;AAE7B,SAAS;KACN,OAAO,CAAC,YAAY,CAAC;KACrB,WAAW,CAAC,qDAAqD,CAAC;KAClE,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;AAE/B,SAAS;KACN,OAAO,CAAC,aAAa,CAAC;KACtB,MAAM,CAAC,iBAAiB,EAAE,yBAAyB,CAAC;KACpD,MAAM,CAAC,WAAW,EAAE,0BAA0B,CAAC;KAC/C,WAAW,CAAC,mDAAmD,CAAC;KAChE,MAAM,CAAC,QAAQ,CAAC,cAAc,CAAC,CAAC;AAEnC,SAAS;KACN,OAAO,CAAC,qCAAqC,CAAC;KAC9C,WAAW,CAAC,8CAA8C,CAAC;KAC3D,MAAM,CACL,gBAAgB,EAChB,yEAAyE,CAC1E;KACA,MAAM,CAAC,0BAA0B,EAAE,sDAAsD,CAAC;KAC1F,MAAM,CAAC,+BAA+B,EAAE,6BAA6B,CAAC;KACtE,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC;KACzB,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;IACjB,OAAO,CAAC,GAAG,CAAC,mDAAmD,CAAC,CAAC;IACjE,OAAO,CAAC,GAAG,CAAC,sDAAsD,CAAC,CAAC;IACpE,OAAO,CAAC,GAAG,CAAC,4CAA4C,CAAC,CAAC;AAC5D,CAAC,CAAC,CAAC;AAEL,SAAS;KACN,OAAO,CAAC,mCAAmC,CAAC;KAC5C,WAAW,CAAC,yDAAyD,CAAC;KACtE,MAAM,CAAC,kBAAkB,EAAE,+DAA+D,CAAC;KAC3F,MAAM,CAAC,kBAAkB,EAAE,0DAA0D,CAAC;KACtF,MAAM,CAAC,eAAe,EAAE,4CAA4C,CAAC;KACrE,MAAM,CACL,4BAA4B,EAC5B,6DAA6D,CAC9D;KACA,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;AAEpC,SAAS;KACN,OAAO,CAAC,4BAA4B,CAAC;KACrC,WAAW,CAAC,+CAA+C,CAAC;KAC5D,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC;AAE/B,SAAS;KACN,OAAO,CAAC,yCAAyC,CAAC;KAClD,WAAW,CAAC,mEAAmE,CAAC;KAChF,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC;KACxB,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;IACjB,OAAO,CAAC,GAAG,CAAC,8DAA8D,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,2DAA2D,CAAC,CAAC;IACzE,OAAO,CAAC,GAAG,CAAC,0DAA0D,CAAC,CAAC;IACxE,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;IAC/C,OAAO,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;IACpD,OAAO,CAAC,GAAG,CAAC,oDAAoD,CAAC,CAAC;AACpE,CAAC,CAAC,CAAC;AAEL,gDAAgD;AAChD,SAAS,CAAC,EAAE,CAAC,WAAW,EAAE;IACxB,IAAA,yCAAe,EAAC,oCAAoC,CAAC,CAAC;IACtD,OAAO,CAAC,QAAQ,GAAG,CAAC,CAAC;IACrB,SAAS,CAAC,IAAI,EAAE,CAAC;AACnB,CAAC,CAAC,CAAC;AAEH,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;IAC3B,SAAS,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;CAC/B;KAAM;IACL,SAAS,CAAC,IAAI,EAAE,CAAC;CAClB"}
+27
View File
@@ -0,0 +1,27 @@
import { OptionValues } from "commander";
import * as devSettings from "./dev-settings";
import { AccountOperation } from "./publish";
export declare function appcontainer(manifestPath: string, options: OptionValues): Promise<void>;
export declare function clear(manifestPath: string): Promise<void>;
export declare function debugging(manifestPath: string, options: OptionValues): Promise<void>;
export declare function disableDebugging(manifestPath: string): Promise<void>;
export declare function disableLiveReload(manifestPath: string): Promise<void>;
export declare function disableRuntimeLogging(): Promise<void>;
export declare function enableDebugging(manifestPath: string, options: OptionValues): Promise<void>;
export declare function enableLiveReload(manifestPath: string): Promise<void>;
export declare function enableRuntimeLogging(path?: string): Promise<void>;
export declare function getSourceBundleUrl(manifestPath: string): Promise<void>;
export declare function isDebuggingEnabled(manifestPath: string): Promise<void>;
export declare function isLiveReloadEnabled(manifestPath: string): Promise<void>;
export declare function isRuntimeLoggingEnabled(): Promise<void>;
export declare function liveReload(manifestPath: string, options: OptionValues): Promise<void>;
export declare function parseWebViewType(webViewString?: string): devSettings.WebViewType | undefined;
export declare function m365Account(operation: AccountOperation, options: OptionValues): Promise<void>;
export declare function register(manifestPath: string, options: OptionValues): Promise<void>;
export declare function registered(options: OptionValues): Promise<void>;
export declare function runtimeLogging(options: OptionValues): Promise<void>;
export declare function sideload(manifestPath: string, type: string | undefined, options: OptionValues): Promise<void>;
export declare function setSourceBundleUrl(manifestPath: string, options: OptionValues): Promise<void>;
export declare function sourceBundleUrl(manifestPath: string, options: OptionValues): Promise<void>;
export declare function unregister(manifestPath: string, options: OptionValues): Promise<void>;
export declare function webView(manifestPath: string, webViewString?: string): Promise<void>;
+519
View File
@@ -0,0 +1,519 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.webView = exports.unregister = exports.sourceBundleUrl = exports.setSourceBundleUrl = exports.sideload = exports.runtimeLogging = exports.registered = exports.register = exports.m365Account = exports.parseWebViewType = exports.liveReload = exports.isRuntimeLoggingEnabled = exports.isLiveReloadEnabled = exports.isDebuggingEnabled = exports.getSourceBundleUrl = exports.enableRuntimeLogging = exports.enableLiveReload = exports.enableDebugging = exports.disableRuntimeLogging = exports.disableLiveReload = exports.disableDebugging = exports.debugging = exports.clear = exports.appcontainer = void 0;
const tslib_1 = require("tslib");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const office_addin_manifest_1 = require("office-addin-manifest");
const appcontainer_1 = require("./appcontainer");
const appType_1 = require("./appType");
const devSettings = tslib_1.__importStar(require("./dev-settings"));
const sideload_1 = require("./sideload");
const defaults_1 = require("./defaults");
const office_addin_usage_data_2 = require("office-addin-usage-data");
const publish_1 = require("./publish");
/* global console process */
function appcontainer(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if ((0, appcontainer_1.isAppcontainerSupported)()) {
try {
if (options.loopback) {
try {
const askForConfirmation = options.yes !== true;
const allowed = yield (0, appcontainer_1.ensureLoopbackIsEnabled)(manifestPath, askForConfirmation);
console.log(allowed ? "Loopback is allowed." : "Loopback is not allowed.");
}
catch (err) {
throw new Error(`Unable to allow loopback for the appcontainer. \n${err}`);
}
}
else if (options.preventLoopback) {
try {
const name = yield (0, appcontainer_1.getAppcontainerNameFromManifestPath)(manifestPath);
yield (0, appcontainer_1.removeLoopbackExemptionForAppcontainer)(name);
console.log(`Loopback is no longer allowed.`);
}
catch (err) {
throw new Error(`Unable to disallow loopback. \n${err}`);
}
}
else {
try {
const name = yield (0, appcontainer_1.getAppcontainerNameFromManifestPath)(manifestPath);
const allowed = yield (0, appcontainer_1.isLoopbackExemptionForAppcontainer)(name);
console.log(allowed ? "Loopback is allowed." : "Loopback is not allowed.");
}
catch (err) {
throw new Error(`Unable to determine if appcontainer allows loopback. \n${err}`);
}
}
defaults_1.usageDataObject.reportSuccess("appcontainer");
}
catch (err) {
defaults_1.usageDataObject.reportException("appcontainer", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
}
else {
console.log("Appcontainer is not supported.");
}
});
}
exports.appcontainer = appcontainer;
function clear(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
yield devSettings.clearDevSettings(manifest.id);
console.log("Developer settings have been cleared.");
defaults_1.usageDataObject.reportSuccess("clear");
}
catch (err) {
defaults_1.usageDataObject.reportException("clear", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.clear = clear;
function debugging(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (options.enable) {
yield enableDebugging(manifestPath, options);
}
else if (options.disable) {
yield disableDebugging(manifestPath);
}
else {
yield isDebuggingEnabled(manifestPath);
}
defaults_1.usageDataObject.reportSuccess("debugging");
}
catch (err) {
defaults_1.usageDataObject.reportException("debugging", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.debugging = debugging;
function displaySourceBundleUrl(components) {
console.log(`host: ${components.host !== undefined ? `"${components.host}"` : '"localhost" (default)'}`);
console.log(`port: ${components.port !== undefined ? `"${components.port}"` : '"8081" (default)'}`);
console.log(`path: ${components.path !== undefined ? `"${components.path}"` : "(default)"}`);
console.log(`extension: ${components.extension !== undefined ? `"${components.extension}"` : '".bundle" (default)'}`);
console.log();
console.log(`Source bundle url: ${components.url}`);
console.log();
}
function disableDebugging(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
yield devSettings.disableDebugging(manifest.id);
console.log("Debugging has been disabled.");
defaults_1.usageDataObject.reportSuccess("disableDebugging()");
}
catch (err) {
defaults_1.usageDataObject.reportException("disableDebugging()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.disableDebugging = disableDebugging;
function disableLiveReload(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
yield devSettings.disableLiveReload(manifest.id);
console.log("Live reload has been disabled.");
defaults_1.usageDataObject.reportSuccess("disableLiveReload()");
}
catch (err) {
defaults_1.usageDataObject.reportException("disableLiveReload()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.disableLiveReload = disableLiveReload;
function disableRuntimeLogging() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
yield devSettings.disableRuntimeLogging();
console.log("Runtime logging has been disabled.");
defaults_1.usageDataObject.reportSuccess("disableRuntimeLogging()");
}
catch (err) {
defaults_1.usageDataObject.reportException("disableRuntimeLogging()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.disableRuntimeLogging = disableRuntimeLogging;
function enableDebugging(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
yield devSettings.enableDebugging(manifest.id, true, toDebuggingMethod(options.debugMethod), options.openDevTools);
console.log("Debugging has been enabled.");
defaults_1.usageDataObject.reportSuccess("enableDebugging()");
}
catch (err) {
defaults_1.usageDataObject.reportException("enableDebugging()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.enableDebugging = enableDebugging;
function enableLiveReload(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
yield devSettings.enableLiveReload(manifest.id);
console.log("Live reload has been enabled.");
defaults_1.usageDataObject.reportSuccess("enableLiveReload()");
}
catch (err) {
defaults_1.usageDataObject.reportException("enableLiveReload()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.enableLiveReload = enableLiveReload;
function enableRuntimeLogging(path) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const logPath = yield devSettings.enableRuntimeLogging(path);
console.log(`Runtime logging has been enabled. File: ${logPath}`);
defaults_1.usageDataObject.reportSuccess("enableRuntimeLogging()");
}
catch (err) {
defaults_1.usageDataObject.reportException("enableRuntimeLogging()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.enableRuntimeLogging = enableRuntimeLogging;
function getSourceBundleUrl(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
const components = yield devSettings.getSourceBundleUrl(manifest.id);
displaySourceBundleUrl(components);
defaults_1.usageDataObject.reportSuccess("getSourceBundleUrl()");
}
catch (err) {
defaults_1.usageDataObject.reportException("getSourceBundleUrl()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.getSourceBundleUrl = getSourceBundleUrl;
function isDebuggingEnabled(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
const enabled = yield devSettings.isDebuggingEnabled(manifest.id);
console.log(enabled ? "Debugging is enabled." : "Debugging is not enabled.");
defaults_1.usageDataObject.reportSuccess("isDebuggingEnabled()");
}
catch (err) {
defaults_1.usageDataObject.reportException("isDebuggingEnabled()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.isDebuggingEnabled = isDebuggingEnabled;
function isLiveReloadEnabled(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
const enabled = yield devSettings.isLiveReloadEnabled(manifest.id);
console.log(enabled ? "Live reload is enabled." : "Live reload is not enabled.");
defaults_1.usageDataObject.reportSuccess("isLiveReloadEnabled()");
}
catch (err) {
defaults_1.usageDataObject.reportException("isLiveReloadEnabled()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.isLiveReloadEnabled = isLiveReloadEnabled;
function isRuntimeLoggingEnabled() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const path = yield devSettings.getRuntimeLoggingPath();
console.log(path ? `Runtime logging is enabled. File: ${path}` : "Runtime logging is not enabled.");
defaults_1.usageDataObject.reportSuccess("isRuntimeLoggingEnabled()");
}
catch (err) {
defaults_1.usageDataObject.reportException("isRuntimeLoggingEnabled()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.isRuntimeLoggingEnabled = isRuntimeLoggingEnabled;
function liveReload(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (options.enable) {
yield enableLiveReload(manifestPath);
}
else if (options.disable) {
yield disableLiveReload(manifestPath);
}
else {
yield isLiveReloadEnabled(manifestPath);
}
defaults_1.usageDataObject.reportSuccess("liveReload");
}
catch (err) {
defaults_1.usageDataObject.reportException("liveReload", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.liveReload = liveReload;
function parseStringCommandOption(optionValue) {
return typeof optionValue === "string" ? optionValue : undefined;
}
function parseWebViewType(webViewString) {
switch (webViewString ? webViewString.toLowerCase() : undefined) {
case "ie":
case "ie11":
case "internet explorer":
case "internetexplorer":
return devSettings.WebViewType.IE;
case "edgelegacy":
case "edge-legacy":
case "spartan":
return devSettings.WebViewType.Edge;
case "edge chromium":
case "edgechromium":
case "edge-chromium":
case "anaheim":
case "edge":
return devSettings.WebViewType.EdgeChromium;
case "default":
case "":
case null:
case undefined:
return undefined;
default:
throw new office_addin_usage_data_2.ExpectedError(`Please select a valid web view type instead of '${webViewString}'.`);
}
}
exports.parseWebViewType = parseWebViewType;
function m365Account(operation, options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
yield (0, publish_1.updateM365Account)(operation);
defaults_1.usageDataObject.reportSuccess("m365Account");
}
catch (err) {
defaults_1.usageDataObject.reportException("m365Account", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.m365Account = m365Account;
function register(manifestPath, options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
yield devSettings.registerAddIn(manifestPath);
defaults_1.usageDataObject.reportSuccess("register");
}
catch (err) {
defaults_1.usageDataObject.reportException("register", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.register = register;
function registered(options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const registeredAddins = yield devSettings.getRegisteredAddIns();
if (registeredAddins.length > 0) {
for (const addin of registeredAddins) {
let id = addin.id;
if (!id && addin.manifestPath) {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(addin.manifestPath);
id = manifest.id || "";
}
catch (_a) {
// ignore errors
}
}
console.log(`${id ? id + " " : ""}${addin.manifestPath}`);
}
}
else {
console.log("No add-ins are registered.");
}
defaults_1.usageDataObject.reportSuccess("registered");
}
catch (err) {
defaults_1.usageDataObject.reportException("registered", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.registered = registered;
function runtimeLogging(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (options.enable) {
const path = typeof options.enable === "string" ? options.enable : undefined;
yield enableRuntimeLogging(path);
}
else if (options.disable) {
yield disableRuntimeLogging();
}
else {
yield isRuntimeLoggingEnabled();
}
defaults_1.usageDataObject.reportSuccess("runtimeLogging");
}
catch (err) {
defaults_1.usageDataObject.reportException("runtimeLogging", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.runtimeLogging = runtimeLogging;
function sideload(manifestPath, type, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const app = options.app ? (0, office_addin_manifest_1.parseOfficeApp)(options.app) : undefined;
const canPrompt = true;
const document = options.document ? options.document : undefined;
const appType = (0, appType_1.parseAppType)(type || process.env.npm_package_config_app_platform_to_debug);
const registration = options.registration;
yield (0, sideload_1.sideloadAddIn)(manifestPath, app, canPrompt, appType, document, registration);
defaults_1.usageDataObject.reportSuccess("sideload");
}
catch (err) {
defaults_1.usageDataObject.reportException("sideload", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.sideload = sideload;
function setSourceBundleUrl(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
const host = parseStringCommandOption(options.host);
const port = parseStringCommandOption(options.port);
const path = parseStringCommandOption(options.path);
const extension = parseStringCommandOption(options.extension);
const components = new devSettings.SourceBundleUrlComponents(host, port, path, extension);
validateManifestId(manifest);
yield devSettings.setSourceBundleUrl(manifest.id, components);
console.log("Configured source bundle url.");
displaySourceBundleUrl(yield devSettings.getSourceBundleUrl(manifest.id));
defaults_1.usageDataObject.reportSuccess("setSourceBundleUrl()");
}
catch (err) {
defaults_1.usageDataObject.reportException("setSourceBundleUrl()", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.setSourceBundleUrl = setSourceBundleUrl;
function sourceBundleUrl(manifestPath, options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (options.host !== undefined ||
options.port !== undefined ||
options.path !== undefined ||
options.extension !== undefined) {
yield setSourceBundleUrl(manifestPath, options);
}
else {
yield getSourceBundleUrl(manifestPath);
}
defaults_1.usageDataObject.reportSuccess("sourceBundleUrl");
}
catch (err) {
defaults_1.usageDataObject.reportException("sourceBundleUrl", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.sourceBundleUrl = sourceBundleUrl;
function toDebuggingMethod(text) {
switch (text) {
case "direct":
return devSettings.DebuggingMethod.Direct;
case "proxy":
return devSettings.DebuggingMethod.Proxy;
case "":
case null:
case undefined:
// preferred debug method
return devSettings.DebuggingMethod.Direct;
default:
throw new office_addin_usage_data_2.ExpectedError(`Please provide a valid debug method instead of '${text}'.`);
}
}
function unregister(manifestPath, options /* eslint-disable-line @typescript-eslint/no-unused-vars */) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (manifestPath === "all") {
yield devSettings.unregisterAllAddIns();
}
else {
yield devSettings.unregisterAddIn(manifestPath);
}
defaults_1.usageDataObject.reportSuccess("unregister");
}
catch (err) {
defaults_1.usageDataObject.reportException("unregister", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.unregister = unregister;
function validateManifestId(manifest) {
if (!manifest.id) {
throw new office_addin_usage_data_2.ExpectedError(`The manifest file doesn't contain the id of the Office Add-in.`);
}
}
function webView(manifestPath, webViewString) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
validateManifestId(manifest);
let webViewType;
if (webViewString === undefined) {
webViewType = yield devSettings.getWebView(manifest.id);
}
else {
webViewType = parseWebViewType(webViewString);
yield devSettings.setWebView(manifest.id, webViewType);
}
const webViewTypeName = devSettings.toWebViewTypeName(webViewType);
console.log(webViewTypeName
? `The web view type is set to ${webViewTypeName}.`
: "The web view type has not been set.");
defaults_1.usageDataObject.reportSuccess("webView");
}
catch (err) {
defaults_1.usageDataObject.reportException("webView", err);
(0, office_addin_usage_data_1.logErrorMessage)(err);
}
});
}
exports.webView = webView;
//# sourceMappingURL=commands.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
import { OfficeAddinUsageData } from "office-addin-usage-data";
export declare const usageDataObject: OfficeAddinUsageData;
+13
View File
@@ -0,0 +1,13 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.usageDataObject = void 0;
const office_addin_usage_data_1 = require("office-addin-usage-data");
// Usage data defaults
exports.usageDataObject = new office_addin_usage_data_1.OfficeAddinUsageData({
projectName: "office-addin-dev-settings",
instrumentationKey: office_addin_usage_data_1.instrumentationKeyForOfficeAddinCLITools,
raisePrompt: false,
});
//# sourceMappingURL=defaults.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"defaults.js","sourceRoot":"","sources":["../src/defaults.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;AAElC,qEAGiC;AAEjC,sBAAsB;AACT,QAAA,eAAe,GAAyB,IAAI,8CAAoB,CAAC;IAC5E,WAAW,EAAE,2BAA2B;IACxC,kBAAkB,EAAE,kEAAwC;IAC5D,WAAW,EAAE,KAAK;CACnB,CAAC,CAAC"}
+6
View File
@@ -0,0 +1,6 @@
import { OfficeApp } from "office-addin-manifest";
import { RegisteredAddin } from "./dev-settings";
export declare function getRegisteredAddIns(): Promise<RegisteredAddin[]>;
export declare function registerAddIn(manifestPath: string, officeApps?: OfficeApp[], registration?: string): Promise<void>;
export declare function unregisterAddIn(addinId: string, manifestPath: string): Promise<void>;
export declare function unregisterAllAddIns(): Promise<void>;
+120
View File
@@ -0,0 +1,120 @@
"use strict";
// copyright (c) Microsoft Corporation. All rights reserved.
// licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterAllAddIns = exports.unregisterAddIn = exports.registerAddIn = exports.getRegisteredAddIns = void 0;
const tslib_1 = require("tslib");
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const junk_1 = tslib_1.__importDefault(require("junk"));
const office_addin_manifest_1 = require("office-addin-manifest");
const os_1 = tslib_1.__importDefault(require("os"));
const path_1 = tslib_1.__importDefault(require("path"));
const dev_settings_1 = require("./dev-settings");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const publish_1 = require("./publish");
const path_2 = tslib_1.__importDefault(require("path"));
function getRegisteredAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const registeredAddins = [];
for (const app of (0, office_addin_manifest_1.getOfficeApps)()) {
const sideloadDirectory = getSideloadDirectory(app);
if (sideloadDirectory && fs_extra_1.default.existsSync(sideloadDirectory)) {
for (const fileName of fs_extra_1.default.readdirSync(sideloadDirectory).filter(junk_1.default.not)) {
const manifestPath = fs_extra_1.default.realpathSync(path_1.default.join(sideloadDirectory, fileName));
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
registeredAddins.push(new dev_settings_1.RegisteredAddin(manifest.id || "", manifestPath));
}
}
}
return registeredAddins;
});
}
exports.getRegisteredAddIns = getRegisteredAddIns;
function getSideloadDirectory(app) {
switch (app) {
case office_addin_manifest_1.OfficeApp.Excel:
return path_1.default.join(os_1.default.homedir(), "Library/Containers/com.microsoft.Excel/Data/Documents/wef");
case office_addin_manifest_1.OfficeApp.PowerPoint:
return path_1.default.join(os_1.default.homedir(), "Library/Containers/com.microsoft.Powerpoint/Data/Documents/wef");
case office_addin_manifest_1.OfficeApp.Word:
return path_1.default.join(os_1.default.homedir(), "Library/Containers/com.microsoft.Word/Data/Documents/wef");
}
}
function registerAddIn(manifestPath, officeApps, registration) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
if (!officeApps) {
officeApps = (0, office_addin_manifest_1.getOfficeAppsForManifestHosts)(manifest.hosts);
if (officeApps.length === 0) {
throw new office_addin_usage_data_1.ExpectedError("The manifest file doesn't specify any hosts for the Office Add-in.");
}
}
if (!manifest.id) {
throw new office_addin_usage_data_1.ExpectedError("The manifest file doesn't contain the id of the Office Add-in.");
}
if (manifestPath.endsWith(".json")) {
if (!registration) {
const targetPath = path_2.default.join(os_1.default.tmpdir(), "manifest.zip");
const zipPath = yield (0, office_addin_manifest_1.exportMetadataPackage)(targetPath, manifestPath);
registration = yield (0, publish_1.registerWithTeams)(zipPath);
}
// TODO: Save registration in "OutlookSideloadManifestPath" as "TitleId"
// and add support for refreshing add-ins in Outlook via registry key
}
else if (manifestPath.endsWith(".xml")) {
// TODO: Look for "Outlook" in manifests.hosts and enable outlook sideloading if there.
// and add support for refreshing add-ins in Outlook via registry key
}
// Save manifest path in "registry"
for (const app of officeApps) {
const sideloadDirectory = getSideloadDirectory(app);
if (sideloadDirectory) {
// include manifest id in sideload filename
const sideloadPath = path_1.default.join(sideloadDirectory, `${manifest.id}.${path_1.default.basename(manifestPath)}`);
fs_extra_1.default.ensureDirSync(sideloadDirectory);
fs_extra_1.default.ensureLinkSync(manifestPath, sideloadPath);
}
}
}
catch (err) {
throw new Error(`Unable to register the Office Add-in.\n${err}`);
}
});
}
exports.registerAddIn = registerAddIn;
function unregisterAddIn(addinId, manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!addinId) {
throw new office_addin_usage_data_1.ExpectedError("The manifest file doesn't contain the id of the Office Add-in.");
}
const registeredAddIns = yield getRegisteredAddIns();
for (const registeredAddIn of registeredAddIns) {
const registeredFileName = path_1.default.basename(registeredAddIn.manifestPath);
const manifestFileName = path_1.default.basename(manifestPath);
if (registeredFileName === manifestFileName || registeredFileName.startsWith(addinId)) {
if (!registeredFileName.endsWith(".xml")) {
(0, publish_1.uninstallWithTeams)(registeredFileName.substring(registeredFileName.indexOf(".") + 1));
// TODO: Add support for refreshing add-ins in Outlook via registry key
}
fs_extra_1.default.unlinkSync(registeredAddIn.manifestPath);
}
}
});
}
exports.unregisterAddIn = unregisterAddIn;
function unregisterAllAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const registeredAddIns = yield getRegisteredAddIns();
for (const registeredAddIn of registeredAddIns) {
const registeredFileName = path_1.default.basename(registeredAddIn.manifestPath);
if (!registeredFileName.endsWith(".xml")) {
(0, publish_1.uninstallWithTeams)(registeredFileName.substring(registeredFileName.indexOf(".") + 1));
// TODO: Add support for refreshing add-ins in Outlook via registry key
}
fs_extra_1.default.unlinkSync(registeredAddIn.manifestPath);
}
});
}
exports.unregisterAllAddIns = unregisterAllAddIns;
//# sourceMappingURL=dev-settings-mac.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"dev-settings-mac.js","sourceRoot":"","sources":["../src/dev-settings-mac.ts"],"names":[],"mappings":"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"}
+26
View File
@@ -0,0 +1,26 @@
#!/usr/bin/env node
import { DebuggingMethod, RegisteredAddin, SourceBundleUrlComponents, WebViewType } from "./dev-settings";
import * as registry from "./registry";
export declare const OutlookSideloadManifestPath: string;
export declare function clearDevSettings(addinId: string): Promise<void>;
export declare function deleteDeveloperSettingsRegistryKey(addinId: string): Promise<void>;
export declare function disableRuntimeLogging(): Promise<void>;
export declare function enableDebugging(addinId: string, enable?: boolean, method?: DebuggingMethod, openDevTools?: boolean): Promise<void>;
export declare function enableLiveReload(addinId: string, enable?: boolean): Promise<void>;
export declare function enableRuntimeLogging(path: string): Promise<void>;
export declare function getDeveloperSettingsRegistryKey(addinId: string): registry.RegistryKey;
export declare function getEnabledDebuggingMethods(addinId: string): Promise<DebuggingMethod[]>;
export declare function getOpenDevTools(addinId: string): Promise<boolean>;
export declare function getRegisteredAddIns(): Promise<RegisteredAddin[]>;
export declare function getRuntimeLoggingPath(): Promise<string | undefined>;
export declare function getSourceBundleUrl(addinId: string): Promise<SourceBundleUrlComponents>;
export declare function getWebView(addinId: string): Promise<WebViewType | undefined>;
export declare function isDebuggingEnabled(addinId: string): Promise<boolean>;
export declare function isLiveReloadEnabled(addinId: string): Promise<boolean>;
export declare function registerAddIn(manifestPath: string, registration?: string): Promise<void>;
export declare function setSourceBundleUrl(addinId: string, components: SourceBundleUrlComponents): Promise<void>;
export declare function setWebView(addinId: string, webViewType: WebViewType | undefined): Promise<void>;
export declare function toWebViewTypeName(webViewType?: WebViewType): string | undefined;
export declare function unregisterAddIn(addinId: string, manifestPath: string): Promise<void>;
export declare function unregisterAllAddIns(): Promise<void>;
export declare function disableRefreshAddins(): Promise<void>;
+342
View File
@@ -0,0 +1,342 @@
#!/usr/bin/env node
"use strict";
// copyright (c) Microsoft Corporation. All rights reserved.
// licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.disableRefreshAddins = exports.unregisterAllAddIns = exports.unregisterAddIn = exports.toWebViewTypeName = exports.setWebView = exports.setSourceBundleUrl = exports.registerAddIn = exports.isLiveReloadEnabled = exports.isDebuggingEnabled = exports.getWebView = exports.getSourceBundleUrl = exports.getRuntimeLoggingPath = exports.getRegisteredAddIns = exports.getOpenDevTools = exports.getEnabledDebuggingMethods = exports.getDeveloperSettingsRegistryKey = exports.enableRuntimeLogging = exports.enableLiveReload = exports.enableDebugging = exports.disableRuntimeLogging = exports.deleteDeveloperSettingsRegistryKey = exports.clearDevSettings = exports.OutlookSideloadManifestPath = void 0;
const tslib_1 = require("tslib");
const office_addin_manifest_1 = require("office-addin-manifest");
const dev_settings_1 = require("./dev-settings");
const office_addin_usage_data_1 = require("office-addin-usage-data");
const registry = tslib_1.__importStar(require("./registry"));
const publish_1 = require("./publish");
const path_1 = tslib_1.__importDefault(require("path"));
/* global process */
const DeveloperSettingsRegistryKey = `HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Office\\16.0\\Wef\\Developer`;
const OpenDevTools = "OpenDevTools";
exports.OutlookSideloadManifestPath = "OutlookSideloadManifestPath";
const RefreshAddins = "RefreshAddins";
const RuntimeLogging = "RuntimeLogging";
const SourceBundleExtension = "SourceBundleExtension";
const SourceBundleHost = "SourceBundleHost";
const SourceBundlePath = "SourceBundlePath";
const SourceBundlePort = "SourceBundlePort";
const TitleId = "TitleId";
const UseDirectDebugger = "UseDirectDebugger";
const UseLiveReload = "UseLiveReload";
const UseProxyDebugger = "UseWebDebugger";
const WebViewSelection = "WebViewSelection";
function clearDevSettings(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return deleteDeveloperSettingsRegistryKey(addinId);
});
}
exports.clearDevSettings = clearDevSettings;
function deleteDeveloperSettingsRegistryKey(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
return registry.deleteKey(key);
});
}
exports.deleteDeveloperSettingsRegistryKey = deleteDeveloperSettingsRegistryKey;
function disableRuntimeLogging() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(RuntimeLogging);
return registry.deleteKey(key);
});
}
exports.disableRuntimeLogging = disableRuntimeLogging;
function enableDebugging(addinId, enable = true, method = dev_settings_1.DebuggingMethod.Proxy, openDevTools = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const useDirectDebugger = enable && method === dev_settings_1.DebuggingMethod.Direct;
const useProxyDebugger = enable && method === dev_settings_1.DebuggingMethod.Proxy;
yield registry.addBooleanValue(key, UseDirectDebugger, useDirectDebugger);
yield registry.addBooleanValue(key, UseProxyDebugger, useProxyDebugger);
if (enable && openDevTools) {
yield registry.addBooleanValue(key, OpenDevTools, true);
}
else {
yield registry.deleteValue(key, OpenDevTools);
}
});
}
exports.enableDebugging = enableDebugging;
function enableLiveReload(addinId, enable = true) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
return registry.addBooleanValue(key, UseLiveReload, enable);
});
}
exports.enableLiveReload = enableLiveReload;
function enableRuntimeLogging(path) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(RuntimeLogging);
return registry.addStringValue(key, "", path); // empty string for the default value
});
}
exports.enableRuntimeLogging = enableRuntimeLogging;
function getDeveloperSettingsRegistryKey(addinId) {
if (!addinId) {
throw new office_addin_usage_data_1.ExpectedError("The addIn parameter is required.");
}
if (typeof addinId !== "string") {
throw new office_addin_usage_data_1.ExpectedError("The addIn parameter should be a string.");
}
return new registry.RegistryKey(`${DeveloperSettingsRegistryKey}\\${addinId}`);
}
exports.getDeveloperSettingsRegistryKey = getDeveloperSettingsRegistryKey;
function getEnabledDebuggingMethods(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const methods = [];
if (isRegistryValueTrue(yield registry.getValue(key, UseDirectDebugger))) {
methods.push(dev_settings_1.DebuggingMethod.Direct);
}
if (isRegistryValueTrue(yield registry.getValue(key, UseProxyDebugger))) {
methods.push(dev_settings_1.DebuggingMethod.Proxy);
}
return methods;
});
}
exports.getEnabledDebuggingMethods = getEnabledDebuggingMethods;
function getOpenDevTools(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
return isRegistryValueTrue(yield registry.getValue(key, OpenDevTools));
});
}
exports.getOpenDevTools = getOpenDevTools;
function getRegisteredAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = new registry.RegistryKey(`${DeveloperSettingsRegistryKey}`);
const values = yield registry.getValues(key);
const filteredValues = values.filter((value) => value.name !== RefreshAddins);
// if the registry value name and data are the same, then the manifest path was used as the name
return filteredValues.map((value) => new dev_settings_1.RegisteredAddin(value.name !== value.data ? value.name : "", value.data));
});
}
exports.getRegisteredAddIns = getRegisteredAddIns;
function getRuntimeLoggingPath() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(RuntimeLogging);
return registry.getStringValue(key, ""); // empty string for the default value
});
}
exports.getRuntimeLoggingPath = getRuntimeLoggingPath;
function getSourceBundleUrl(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const components = new dev_settings_1.SourceBundleUrlComponents(yield registry.getStringValue(key, SourceBundleHost), yield registry.getStringValue(key, SourceBundlePort), yield registry.getStringValue(key, SourceBundlePath), yield registry.getStringValue(key, SourceBundleExtension));
return components;
});
}
exports.getSourceBundleUrl = getSourceBundleUrl;
function getWebView(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const webViewString = yield registry.getStringValue(key, WebViewSelection);
return toWebViewType(webViewString);
});
}
exports.getWebView = getWebView;
function isDebuggingEnabled(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const useDirectDebugger = isRegistryValueTrue(yield registry.getValue(key, UseDirectDebugger));
const useWebDebugger = isRegistryValueTrue(yield registry.getValue(key, UseProxyDebugger));
return useDirectDebugger || useWebDebugger;
});
}
exports.isDebuggingEnabled = isDebuggingEnabled;
function isLiveReloadEnabled(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
const enabled = isRegistryValueTrue(yield registry.getValue(key, UseLiveReload));
return enabled;
});
}
exports.isLiveReloadEnabled = isLiveReloadEnabled;
function isRegistryValueTrue(value) {
if (value) {
switch (value.type) {
case registry.RegistryTypes.REG_DWORD:
case registry.RegistryTypes.REG_QWORD:
case registry.RegistryTypes.REG_SZ:
return parseInt(value.data, undefined) !== 0;
}
}
return false;
}
function registerAddIn(manifestPath, registration) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
const appsInManifest = (0, office_addin_manifest_1.getOfficeAppsForManifestHosts)(manifest.hosts);
// Register using the service
if (manifest.manifestType === office_addin_manifest_1.ManifestType.JSON ||
appsInManifest.indexOf(office_addin_manifest_1.OfficeApp.Outlook) >= 0) {
if (!registration) {
let filePath = "";
if (manifest.manifestType === office_addin_manifest_1.ManifestType.JSON) {
const targetPath = path_1.default.join(process.env.TEMP, "manifest.zip");
filePath = yield (0, office_addin_manifest_1.exportMetadataPackage)(targetPath, manifestPath);
}
else if (manifest.manifestType === office_addin_manifest_1.ManifestType.XML) {
filePath = manifestPath;
}
registration = yield (0, publish_1.registerWithTeams)(filePath);
yield enableRefreshAddins();
}
const key = getDeveloperSettingsRegistryKey(exports.OutlookSideloadManifestPath);
yield registry.addStringValue(key, TitleId, registration);
}
const key = new registry.RegistryKey(`${DeveloperSettingsRegistryKey}`);
yield registry.deleteValue(key, manifestPath); // in case the manifest path was previously used as the key
return registry.addStringValue(key, manifest.id || "", manifestPath);
});
}
exports.registerAddIn = registerAddIn;
function setSourceBundleUrl(addinId, components) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
if (components.host !== undefined) {
if (components.host) {
yield registry.addStringValue(key, SourceBundleHost, components.host);
}
else {
yield registry.deleteValue(key, SourceBundleHost);
}
}
if (components.port !== undefined) {
if (components.port) {
yield registry.addStringValue(key, SourceBundlePort, components.port);
}
else {
yield registry.deleteValue(key, SourceBundlePort);
}
}
if (components.path !== undefined) {
if (components.path) {
yield registry.addStringValue(key, SourceBundlePath, components.path);
}
else {
yield registry.deleteValue(key, SourceBundlePath);
}
}
if (components.extension !== undefined) {
if (components.extension) {
yield registry.addStringValue(key, SourceBundleExtension, components.extension);
}
else {
yield registry.deleteValue(key, SourceBundleExtension);
}
}
});
}
exports.setSourceBundleUrl = setSourceBundleUrl;
function setWebView(addinId, webViewType) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = getDeveloperSettingsRegistryKey(addinId);
switch (webViewType) {
case undefined:
case dev_settings_1.WebViewType.Default:
yield registry.deleteValue(key, WebViewSelection);
break;
case dev_settings_1.WebViewType.IE:
case dev_settings_1.WebViewType.Edge:
case dev_settings_1.WebViewType.EdgeChromium: {
const webViewString = webViewType;
yield registry.addStringValue(key, WebViewSelection, webViewString);
break;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`The webViewType ${webViewType} is not supported.`);
}
});
}
exports.setWebView = setWebView;
function toWebViewType(webViewString) {
switch (webViewString ? webViewString.toLowerCase() : undefined) {
case "ie":
return dev_settings_1.WebViewType.IE;
case "edge":
return dev_settings_1.WebViewType.Edge;
case "edge chromium":
return dev_settings_1.WebViewType.EdgeChromium;
default:
return undefined;
}
}
function toWebViewTypeName(webViewType) {
switch (webViewType) {
case dev_settings_1.WebViewType.Edge:
return "legacy Microsoft Edge (EdgeHTML)";
case dev_settings_1.WebViewType.EdgeChromium:
return "Microsoft Edge (Chromium)";
case dev_settings_1.WebViewType.IE:
return "Microsoft Internet Explorer";
default:
return undefined;
}
}
exports.toWebViewTypeName = toWebViewTypeName;
function unregisterAddIn(addinId, manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = new registry.RegistryKey(`${DeveloperSettingsRegistryKey}`);
if (addinId) {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
const appsInManifest = (0, office_addin_manifest_1.getOfficeAppsForManifestHosts)(manifest.hosts);
// Unregister using the service
// TODO: remove if statement when the service supports all hosts
if (manifest.manifestType === office_addin_manifest_1.ManifestType.JSON ||
appsInManifest.indexOf(office_addin_manifest_1.OfficeApp.Outlook) >= 0) {
yield unacquire(key, addinId);
}
yield registry.deleteValue(key, addinId);
}
// since the key used to be manifest path, delete it too
if (manifestPath) {
yield registry.deleteValue(key, manifestPath);
}
});
}
exports.unregisterAddIn = unregisterAddIn;
function unregisterAllAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const registeredAddins = yield getRegisteredAddIns();
for (const addin of registeredAddins) {
yield unregisterAddIn(addin.id, addin.manifestPath);
}
});
}
exports.unregisterAllAddIns = unregisterAllAddIns;
function unacquire(key, id) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const manifest = yield registry.getStringValue(key, id);
if (manifest != undefined) {
const key = getDeveloperSettingsRegistryKey(exports.OutlookSideloadManifestPath);
const registration = yield registry.getStringValue(key, TitleId);
const uninstallId = registration != undefined ? registration : id;
if (yield (0, publish_1.uninstallWithTeams)(uninstallId)) {
if (registration != undefined) {
registry.deleteValue(key, TitleId);
}
yield enableRefreshAddins();
}
}
});
}
function enableRefreshAddins() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = new registry.RegistryKey(`${DeveloperSettingsRegistryKey}`);
yield registry.addBooleanValue(key, RefreshAddins, true);
});
}
function disableRefreshAddins() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const key = new registry.RegistryKey(`${DeveloperSettingsRegistryKey}`);
yield registry.deleteValue(key, RefreshAddins);
});
}
exports.disableRefreshAddins = disableRefreshAddins;
//# sourceMappingURL=dev-settings-windows.js.map
File diff suppressed because one or more lines are too long
+49
View File
@@ -0,0 +1,49 @@
export { toWebViewTypeName } from "./dev-settings-windows";
export declare enum DebuggingMethod {
Direct = 0,
Proxy = 1,
/** @deprecated use Proxy */
Web = 1
}
export declare enum WebViewType {
Default = "Default",
IE = "IE",
Edge = "Edge",
EdgeChromium = "Edge Chromium"
}
export declare class RegisteredAddin {
id: string;
manifestPath: string;
constructor(id: string, manifestPath: string);
}
export declare class SourceBundleUrlComponents {
host?: string;
port?: string;
path?: string;
extension?: string;
get url(): string;
constructor(host?: string, port?: string, path?: string, extension?: string);
}
export declare function clearDevSettings(addinId: string): Promise<void>;
export declare function disableDebugging(addinId: string): Promise<void>;
export declare function disableLiveReload(addinId: string): Promise<void>;
export declare function disableRuntimeLogging(): Promise<void>;
export declare function enableDebugging(addinId: string, enable?: boolean, method?: DebuggingMethod, openDevTools?: boolean): Promise<void>;
export declare function enableLiveReload(addinId: string, enable?: boolean): Promise<void>;
export declare function enableRuntimeLogging(path?: string): Promise<string>;
/**
* Returns the manifest paths for the add-ins that are registered
*/
export declare function getRegisteredAddIns(): Promise<RegisteredAddin[]>;
export declare function getEnabledDebuggingMethods(addinId: string): Promise<DebuggingMethod[]>;
export declare function getOpenDevTools(addinId: string): Promise<boolean>;
export declare function getRuntimeLoggingPath(): Promise<string | undefined>;
export declare function getSourceBundleUrl(addinId: string): Promise<SourceBundleUrlComponents>;
export declare function getWebView(addinId: string): Promise<WebViewType | undefined>;
export declare function isDebuggingEnabled(addinId: string): Promise<boolean>;
export declare function isLiveReloadEnabled(addinId: string): Promise<boolean>;
export declare function registerAddIn(manifestPath: string, registration?: string): Promise<void>;
export declare function setSourceBundleUrl(addinId: string, components: SourceBundleUrlComponents): Promise<void>;
export declare function setWebView(addinId: string, webViewType: WebViewType | undefined): Promise<void>;
export declare function unregisterAddIn(manifestPath: string): Promise<void>;
export declare function unregisterAllAddIns(): Promise<void>;
+306
View File
@@ -0,0 +1,306 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.unregisterAllAddIns = exports.unregisterAddIn = exports.setWebView = exports.setSourceBundleUrl = exports.registerAddIn = exports.isLiveReloadEnabled = exports.isDebuggingEnabled = exports.getWebView = exports.getSourceBundleUrl = exports.getRuntimeLoggingPath = exports.getOpenDevTools = exports.getEnabledDebuggingMethods = exports.getRegisteredAddIns = exports.enableRuntimeLogging = exports.enableLiveReload = exports.enableDebugging = exports.disableRuntimeLogging = exports.disableLiveReload = exports.disableDebugging = exports.clearDevSettings = exports.SourceBundleUrlComponents = exports.RegisteredAddin = exports.WebViewType = exports.DebuggingMethod = exports.toWebViewTypeName = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const office_addin_manifest_1 = require("office-addin-manifest");
const path_1 = tslib_1.__importDefault(require("path"));
const devSettingsMac = tslib_1.__importStar(require("./dev-settings-mac"));
const devSettingsWindows = tslib_1.__importStar(require("./dev-settings-windows"));
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global process */
const defaultRuntimeLogFileName = "OfficeAddins.log.txt";
var dev_settings_windows_1 = require("./dev-settings-windows");
Object.defineProperty(exports, "toWebViewTypeName", { enumerable: true, get: function () { return dev_settings_windows_1.toWebViewTypeName; } });
var DebuggingMethod;
(function (DebuggingMethod) {
DebuggingMethod[DebuggingMethod["Direct"] = 0] = "Direct";
DebuggingMethod[DebuggingMethod["Proxy"] = 1] = "Proxy";
/** @deprecated use Proxy */
DebuggingMethod[DebuggingMethod["Web"] = 1] = "Web";
})(DebuggingMethod = exports.DebuggingMethod || (exports.DebuggingMethod = {}));
var WebViewType;
(function (WebViewType) {
WebViewType["Default"] = "Default";
WebViewType["IE"] = "IE";
WebViewType["Edge"] = "Edge";
WebViewType["EdgeChromium"] = "Edge Chromium";
})(WebViewType = exports.WebViewType || (exports.WebViewType = {}));
class RegisteredAddin {
constructor(id, manifestPath) {
this.id = id;
this.manifestPath = manifestPath;
}
}
exports.RegisteredAddin = RegisteredAddin;
class SourceBundleUrlComponents {
get url() {
const host = this.host !== undefined ? this.host : "localhost";
const port = this.port !== undefined ? this.port : "8081";
const path = this.path !== undefined ? this.path : "{path}";
const extension = this.extension !== undefined ? this.extension : ".bundle";
// eslint-disable-next-line @microsoft/sdl/no-insecure-url
return `http://${host}${host && port ? ":" : ""}${port}/${path}${extension}`;
}
constructor(host, port, path, extension) {
this.host = host;
this.port = port;
this.path = path;
this.extension = extension;
}
}
exports.SourceBundleUrlComponents = SourceBundleUrlComponents;
function clearDevSettings(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.clearDevSettings(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.clearDevSettings = clearDevSettings;
function disableDebugging(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return enableDebugging(addinId, false);
});
}
exports.disableDebugging = disableDebugging;
function disableLiveReload(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return enableLiveReload(addinId, false);
});
}
exports.disableLiveReload = disableLiveReload;
function disableRuntimeLogging() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.disableRuntimeLogging();
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.disableRuntimeLogging = disableRuntimeLogging;
function enableDebugging(addinId, enable = true, method = DebuggingMethod.Direct, openDevTools = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.enableDebugging(addinId, enable, method, openDevTools);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.enableDebugging = enableDebugging;
function enableLiveReload(addinId, enable = true) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.enableLiveReload(addinId, enable);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.enableLiveReload = enableLiveReload;
function enableRuntimeLogging(path) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32": {
if (!path) {
const tempDir = process.env.TEMP;
if (!tempDir) {
throw new office_addin_usage_data_1.ExpectedError("The TEMP environment variable is not defined.");
}
path = path_1.default.normalize(`${tempDir}/${defaultRuntimeLogFileName}`);
}
const pathExists = fs_1.default.existsSync(path);
if (pathExists) {
const stat = fs_1.default.statSync(path);
if (stat.isDirectory()) {
throw new office_addin_usage_data_1.ExpectedError(`You need to specify the path to a file. This is a directory: "${path}".`);
}
}
try {
const file = fs_1.default.openSync(path, "a+");
fs_1.default.closeSync(file);
}
catch (_a) {
throw new office_addin_usage_data_1.ExpectedError(pathExists
? `You need to specify the path to a writable file. Unable to write to: "${path}".`
: `You need to specify the path where the file can be written. Unable to write to: "${path}".`);
}
yield devSettingsWindows.enableRuntimeLogging(path);
return path;
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.enableRuntimeLogging = enableRuntimeLogging;
/**
* Returns the manifest paths for the add-ins that are registered
*/
function getRegisteredAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "darwin":
return devSettingsMac.getRegisteredAddIns();
case "win32":
return devSettingsWindows.getRegisteredAddIns();
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getRegisteredAddIns = getRegisteredAddIns;
function getEnabledDebuggingMethods(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.getEnabledDebuggingMethods(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getEnabledDebuggingMethods = getEnabledDebuggingMethods;
function getOpenDevTools(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.getOpenDevTools(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getOpenDevTools = getOpenDevTools;
function getRuntimeLoggingPath() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.getRuntimeLoggingPath();
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getRuntimeLoggingPath = getRuntimeLoggingPath;
function getSourceBundleUrl(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.getSourceBundleUrl(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getSourceBundleUrl = getSourceBundleUrl;
function getWebView(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.getWebView(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.getWebView = getWebView;
function isDebuggingEnabled(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.isDebuggingEnabled(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.isDebuggingEnabled = isDebuggingEnabled;
function isLiveReloadEnabled(addinId) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.isLiveReloadEnabled(addinId);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.isLiveReloadEnabled = isLiveReloadEnabled;
function registerAddIn(manifestPath, registration) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32": {
const realManifestPath = fs_1.default.realpathSync(manifestPath);
return devSettingsWindows.registerAddIn(realManifestPath, registration);
}
case "darwin":
return devSettingsMac.registerAddIn(manifestPath);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.registerAddIn = registerAddIn;
function setSourceBundleUrl(addinId, components) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.setSourceBundleUrl(addinId, components);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.setSourceBundleUrl = setSourceBundleUrl;
function setWebView(addinId, webViewType) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "win32":
return devSettingsWindows.setWebView(addinId, webViewType);
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.setWebView = setWebView;
function unregisterAddIn(manifestPath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
switch (process.platform) {
case "darwin":
return devSettingsMac.unregisterAddIn(manifest.id || "", manifestPath);
case "win32": {
const realManifestPath = fs_1.default.realpathSync(manifestPath);
return devSettingsWindows.unregisterAddIn(manifest.id || "", realManifestPath);
}
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.unregisterAddIn = unregisterAddIn;
function unregisterAllAddIns() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
switch (process.platform) {
case "darwin":
return devSettingsMac.unregisterAllAddIns();
case "win32":
return devSettingsWindows.unregisterAllAddIns();
default:
throw new office_addin_usage_data_1.ExpectedError(`Platform not supported: ${process.platform}.`);
}
});
}
exports.unregisterAllAddIns = unregisterAllAddIns;
//# sourceMappingURL=dev-settings.js.map
File diff suppressed because one or more lines are too long
+7
View File
@@ -0,0 +1,7 @@
export * from "./appcontainer";
export * from "./appType";
export * from "./dev-settings";
export * from "./process";
export * from "./sideload";
export { parseWebViewType } from "./commands";
export { updateM365Account } from "./publish";
+16
View File
@@ -0,0 +1,16 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateM365Account = exports.parseWebViewType = void 0;
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./appcontainer"), exports);
tslib_1.__exportStar(require("./appType"), exports);
tslib_1.__exportStar(require("./dev-settings"), exports);
tslib_1.__exportStar(require("./process"), exports);
tslib_1.__exportStar(require("./sideload"), exports);
var commands_1 = require("./commands");
Object.defineProperty(exports, "parseWebViewType", { enumerable: true, get: function () { return commands_1.parseWebViewType; } });
var publish_1 = require("./publish");
Object.defineProperty(exports, "updateM365Account", { enumerable: true, get: function () { return publish_1.updateM365Account; } });
//# sourceMappingURL=main.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"main.js","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;AAElC,yDAA+B;AAC/B,oDAA0B;AAC1B,yDAA+B;AAC/B,oDAA0B;AAC1B,qDAA2B;AAC3B,uCAA8C;AAArC,4GAAA,gBAAgB,OAAA;AACzB,qCAA8C;AAArC,4GAAA,iBAAiB,OAAA"}
+5
View File
@@ -0,0 +1,5 @@
/// <reference types="node" />
import { ChildProcess } from "child_process";
export declare function startProcess(commandLine: string, verbose?: boolean): Promise<void>;
export declare function startDetachedProcess(commandLine: string, verbose?: boolean): ChildProcess;
export declare function stopProcess(processId: number): void;
+60
View File
@@ -0,0 +1,60 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopProcess = exports.startDetachedProcess = exports.startProcess = void 0;
const tslib_1 = require("tslib");
const child_process_1 = tslib_1.__importDefault(require("child_process"));
/* global console process */
function startProcess(commandLine, verbose = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if (verbose) {
console.log(`Starting: ${commandLine}`);
}
child_process_1.default.exec(commandLine, (error, stdout /* eslint-disable-line @typescript-eslint/no-unused-vars */, stderr /* eslint-disable-line @typescript-eslint/no-unused-vars */) => {
if (error) {
reject(error);
}
else {
resolve();
}
});
});
});
}
exports.startProcess = startProcess;
function startDetachedProcess(commandLine, verbose = false) {
if (verbose) {
console.log(`Starting: ${commandLine}`);
}
const subprocess = child_process_1.default.spawn(commandLine, [], {
detached: true,
shell: true,
stdio: "ignore",
windowsHide: false,
});
subprocess.on("error", (err) => {
console.log(`Unable to run command: ${commandLine}.\n${err}`);
});
subprocess.unref();
return subprocess;
}
exports.startDetachedProcess = startDetachedProcess;
function stopProcess(processId) {
if (processId) {
try {
if (process.platform === "win32") {
child_process_1.default.spawn("taskkill", ["/pid", `${processId}`, "/f", "/t"]);
}
else {
process.kill(processId);
}
}
catch (err) {
console.log(`Unable to kill process id ${processId}: ${err}`);
}
}
}
exports.stopProcess = stopProcess;
//# sourceMappingURL=process.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"process.js","sourceRoot":"","sources":["../src/process.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;AAElC,0EAAyC;AAGzC,4BAA4B;AAE5B,SAAsB,YAAY,CAAC,WAAmB,EAAE,UAAmB,KAAK;;QAC9E,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC3C,IAAI,OAAO,EAAE;gBACX,OAAO,CAAC,GAAG,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;aACzC;YAED,uBAAY,CAAC,IAAI,CACf,WAAW,EACX,CACE,KAA2B,EAC3B,MAAc,CAAC,2DAA2D,EAC1E,MAAc,CAAC,2DAA2D,EAC1E,EAAE;gBACF,IAAI,KAAK,EAAE;oBACT,MAAM,CAAC,KAAK,CAAC,CAAC;iBACf;qBAAM;oBACL,OAAO,EAAE,CAAC;iBACX;YACH,CAAC,CACF,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;CAAA;AArBD,oCAqBC;AAED,SAAgB,oBAAoB,CAAC,WAAmB,EAAE,UAAmB,KAAK;IAChF,IAAI,OAAO,EAAE;QACX,OAAO,CAAC,GAAG,CAAC,aAAa,WAAW,EAAE,CAAC,CAAC;KACzC;IAED,MAAM,UAAU,GAAG,uBAAY,CAAC,KAAK,CAAC,WAAW,EAAE,EAAE,EAAE;QACrD,QAAQ,EAAE,IAAI;QACd,KAAK,EAAE,IAAI;QACX,KAAK,EAAE,QAAQ;QACf,WAAW,EAAE,KAAK;KACnB,CAAC,CAAC;IAEH,UAAU,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;QAC7B,OAAO,CAAC,GAAG,CAAC,0BAA0B,WAAW,MAAM,GAAG,EAAE,CAAC,CAAC;IAChE,CAAC,CAAC,CAAC;IAEH,UAAU,CAAC,KAAK,EAAE,CAAC;IACnB,OAAO,UAAU,CAAC;AACpB,CAAC;AAlBD,oDAkBC;AAED,SAAgB,WAAW,CAAC,SAAiB;IAC3C,IAAI,SAAS,EAAE;QACb,IAAI;YACF,IAAI,OAAO,CAAC,QAAQ,KAAK,OAAO,EAAE;gBAChC,uBAAY,CAAC,KAAK,CAAC,UAAU,EAAE,CAAC,MAAM,EAAE,GAAG,SAAS,EAAE,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAC;aACtE;iBAAM;gBACL,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;aACzB;SACF;QAAC,OAAO,GAAG,EAAE;YACZ,OAAO,CAAC,GAAG,CAAC,6BAA6B,SAAS,KAAK,GAAG,EAAE,CAAC,CAAC;SAC/D;KACF;AACH,CAAC;AAZD,kCAYC"}
+2
View File
@@ -0,0 +1,2 @@
import { OfficeApp } from "office-addin-manifest";
export declare function chooseOfficeApp(apps: OfficeApp[]): Promise<OfficeApp>;
+28
View File
@@ -0,0 +1,28 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.chooseOfficeApp = void 0;
const tslib_1 = require("tslib");
const inquirer_1 = tslib_1.__importDefault(require("inquirer"));
const office_addin_manifest_1 = require("office-addin-manifest");
function chooseOfficeApp(apps) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const questionName = "app";
const question = {
choices: apps
.map((app) => {
return { name: (0, office_addin_manifest_1.getOfficeAppName)(app), value: app };
})
.sort((first, second) => first.name.localeCompare(second.name)),
message: "Which Office app?",
name: questionName,
type: "list",
};
const answer = yield inquirer_1.default.prompt([question]);
const choice = answer[questionName];
return choice;
});
}
exports.chooseOfficeApp = chooseOfficeApp;
//# sourceMappingURL=prompt.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"prompt.js","sourceRoot":"","sources":["../src/prompt.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;AAElC,gEAAgC;AAChC,iEAAoE;AAEpE,SAAsB,eAAe,CAAC,IAAiB;;QACrD,MAAM,YAAY,GAAG,KAAK,CAAC;QAC3B,MAAM,QAAQ,GAAmD;YAC/D,OAAO,EAAE,IAAI;iBACV,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE;gBACX,OAAO,EAAE,IAAI,EAAE,IAAA,wCAAgB,EAAC,GAAG,CAAC,EAAE,KAAK,EAAE,GAAG,EAAE,CAAC;YACrD,CAAC,CAAC;iBACD,IAAI,CAAC,CAAC,KAAK,EAAE,MAAM,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;YACjE,OAAO,EAAE,mBAAmB;YAC5B,IAAI,EAAE,YAAY;YAClB,IAAI,EAAE,MAAM;SACb,CAAC;QAEF,MAAM,MAAM,GAAG,MAAM,kBAAQ,CAAC,MAAM,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;QACjD,MAAM,MAAM,GAAc,MAAM,CAAC,YAAY,CAAC,CAAC;QAC/C,OAAO,MAAM,CAAC;IAChB,CAAC;CAAA;AAhBD,0CAgBC"}
+4
View File
@@ -0,0 +1,4 @@
export type AccountOperation = "login" | "logout";
export declare function registerWithTeams(filePath: string): Promise<string>;
export declare function updateM365Account(operation: AccountOperation): Promise<void>;
export declare function uninstallWithTeams(id: string): Promise<boolean>;
+89
View File
@@ -0,0 +1,89 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.uninstallWithTeams = exports.updateM365Account = exports.registerWithTeams = void 0;
const tslib_1 = require("tslib");
const child_process_1 = tslib_1.__importDefault(require("child_process"));
const fs_1 = tslib_1.__importDefault(require("fs"));
function registerWithTeams(filePath) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
if ((filePath.endsWith(".zip") || filePath.endsWith(".xml")) && fs_1.default.existsSync(filePath)) {
const pathSwitch = filePath.endsWith(".zip") ? "--file-path" : "--xml-path";
const sideloadCommand = `npx @microsoft/teamsapp-cli install ${pathSwitch} "${filePath}" --interactive false`;
console.log(`running: ${sideloadCommand}`);
child_process_1.default.exec(sideloadCommand, (error, stdout, stderr) => {
let titleIdMatch = stdout.match(/TitleId:\s*(.*)/);
let titleId = titleIdMatch !== null ? titleIdMatch[1] : "??";
if (error || stderr.match('"error"')) {
console.log(`\n${stdout}\n--Error sideloading!--\nError: ${error}\nSTDERR:\n${stderr}`);
reject(error);
}
else {
console.log(`\n${stdout}\nSuccessfully registered package! (${titleId})\n STDERR: ${stderr}\n`);
resolve(titleId);
}
});
}
else {
reject(new Error(`The file '${filePath}' is not valid`));
}
});
});
}
exports.registerWithTeams = registerWithTeams;
function updateM365Account(operation) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const authCommand = `npx @microsoft/teamsapp-cli auth ${operation} m365`;
console.log(`running: ${authCommand}`);
child_process_1.default.exec(authCommand, (error, stdout, stderr) => {
if (error || (stderr.length > 0 && /Debugger attached\./.test(stderr) == false)) {
console.log(`Error running auth command\n STDOUT: ${stdout}\n ERROR: ${error}\n STDERR: ${stderr}`);
reject(error);
}
else {
console.log(`Successfully ran auth command.\n`);
resolve();
}
});
});
});
}
exports.updateM365Account = updateM365Account;
function uninstallWithTeams(id) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const guidRegex = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}/;
const manifestIdRegex = new RegExp(`^${guidRegex.source}$`);
const titleIdRegex = new RegExp(`^U_${guidRegex.source}$`);
let mode = "";
if (titleIdRegex.test(id)) {
mode = `--mode title-id --title-id ${id}`;
}
else if (manifestIdRegex.test(id)) {
mode = `--mode manifest-id --manifest-id ${id}`;
}
else {
console.error(`Error: Invalid id "${id}". Add-in is still installed.`);
resolve(false);
return;
}
const uninstallCommand = `npx @microsoft/teamsapp-cli uninstall ${mode} --interactive false`;
console.log(`running: ${uninstallCommand}`);
child_process_1.default.exec(uninstallCommand, (error, stdout, stderr) => {
if (error || stderr.match('"error"')) {
console.log(`\n${stdout}\n--Error uninstalling!--\n${error}\n STDERR: ${stderr}`);
reject(error);
}
else {
console.log(`\n${stdout}\nSuccessfully uninstalled!\n STDERR: ${stderr}\n`);
resolve(true);
}
});
});
});
}
exports.uninstallWithTeams = uninstallWithTeams;
//# sourceMappingURL=publish.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"publish.js","sourceRoot":"","sources":["../src/publish.ts"],"names":[],"mappings":"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"}
+37
View File
@@ -0,0 +1,37 @@
import winreg from "winreg";
export declare class RegistryKey {
winreg: winreg.Registry;
get path(): string;
constructor(path: string);
}
export declare class RegistryTypes {
static readonly REG_BINARY: string;
static readonly REG_DWORD: string;
static readonly REG_EXPAND_SZ: string;
static readonly REG_MULTI_SZ: string;
static readonly REG_NONE: string;
static readonly REG_QWORD: string;
static readonly REG_SZ: string;
}
export declare class RegistryValue {
key: string;
name: string;
type: string;
data: string;
get isNumberType(): boolean;
get isStringType(): boolean;
constructor(key: string, name: string, type: string, data: string);
}
export declare function addBooleanValue(key: RegistryKey, value: string, data: boolean): Promise<void>;
export declare function addNumberValue(key: RegistryKey, value: string, data: number): Promise<void>;
export declare function addStringValue(key: RegistryKey, value: string, data: string): Promise<void>;
export declare function deleteKey(key: RegistryKey): Promise<void>;
export declare function deleteValue(key: RegistryKey, value: string): Promise<void>;
export declare function doesKeyExist(key: RegistryKey): Promise<boolean>;
export declare function doesValueExist(key: RegistryKey, value: string): Promise<boolean>;
export declare function getNumberValue(key: RegistryKey, value: string): Promise<number | undefined>;
export declare function getStringValue(key: RegistryKey, value: string): Promise<string | undefined>;
export declare function getValue(key: RegistryKey, value: string): Promise<RegistryValue | undefined>;
export declare function getValues(key: RegistryKey): Promise<RegistryValue[]>;
export declare function isNumberType(registryType: string): boolean;
export declare function isStringType(registryType: string): boolean;
+279
View File
@@ -0,0 +1,279 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.isStringType = exports.isNumberType = exports.getValues = exports.getValue = exports.getStringValue = exports.getNumberValue = exports.doesValueExist = exports.doesKeyExist = exports.deleteValue = exports.deleteKey = exports.addStringValue = exports.addNumberValue = exports.addBooleanValue = exports.RegistryValue = exports.RegistryTypes = exports.RegistryKey = void 0;
const tslib_1 = require("tslib");
const winreg_1 = tslib_1.__importDefault(require("winreg"));
const office_addin_usage_data_1 = require("office-addin-usage-data");
class RegistryKey {
get path() {
return this.winreg.path;
}
constructor(path) {
if (!path) {
throw new office_addin_usage_data_1.ExpectedError("Please provide a registry key path.");
}
const index = path.indexOf("\\");
if (index <= 0) {
throw new office_addin_usage_data_1.ExpectedError(`The registry key path is not valid: "${path}".`);
}
const hive = path.substring(0, index);
const subpath = path.substring(index);
this.winreg = new winreg_1.default({
hive: normalizeRegistryHive(hive),
key: subpath,
});
}
}
exports.RegistryKey = RegistryKey;
class RegistryTypes {
}
exports.RegistryTypes = RegistryTypes;
RegistryTypes.REG_BINARY = winreg_1.default.REG_BINARY;
RegistryTypes.REG_DWORD = winreg_1.default.REG_DWORD;
RegistryTypes.REG_EXPAND_SZ = winreg_1.default.REG_EXPAND_SZ;
RegistryTypes.REG_MULTI_SZ = winreg_1.default.REG_MULTI_SZ;
RegistryTypes.REG_NONE = winreg_1.default.REG_NONE;
RegistryTypes.REG_QWORD = winreg_1.default.REG_QWORD;
RegistryTypes.REG_SZ = winreg_1.default.REG_SZ;
class RegistryValue {
get isNumberType() {
return isNumberType(this.type);
}
get isStringType() {
return isStringType(this.type);
}
constructor(key, name, type, data) {
this.key = key;
this.name = name;
this.type = type;
this.data = data;
}
}
exports.RegistryValue = RegistryValue;
function addValue(key, value, type, data) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const onError = (err) => {
if (err) {
reject(new Error(`Unable to set registry value "${value}" to "${data}" (${type}) for key "${key.path}".\n${err}`));
}
else {
resolve();
}
};
try {
key.winreg.set(value, type, data, onError);
}
catch (err) {
onError(err);
}
});
});
}
function addBooleanValue(key, value, data) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return addValue(key, value, winreg_1.default.REG_DWORD, data ? "1" : "0");
});
}
exports.addBooleanValue = addBooleanValue;
function addNumberValue(key, value, data) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return addValue(key, value, winreg_1.default.REG_DWORD, data.toString());
});
}
exports.addNumberValue = addNumberValue;
function addStringValue(key, value, data) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return addValue(key, value, winreg_1.default.REG_SZ, data);
});
}
exports.addStringValue = addStringValue;
function deleteKey(key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const onError = (err) => {
if (err) {
reject(new Error(`Unable to delete registry key "${key.path}".\n${err}`));
}
else {
resolve();
}
};
try {
key.winreg.keyExists((keyExistsError, exists) => {
if (exists) {
key.winreg.destroy(onError);
}
else {
onError(keyExistsError);
}
});
}
catch (err) {
onError(err);
}
});
});
}
exports.deleteKey = deleteKey;
function deleteValue(key, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const onError = (err) => {
if (err) {
reject(new Error(`Unable to delete registry value "${value}" in key "${key.path}".\n${err}`));
}
else {
resolve();
}
};
try {
key.winreg.valueExists(value, (_, exists) => {
if (exists) {
key.winreg.remove(value, onError);
}
else {
resolve();
}
});
}
catch (err) {
onError(err);
}
});
});
}
exports.deleteValue = deleteValue;
function doesKeyExist(key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const onError = (err, exists = false) => {
if (err) {
reject(new Error(`Unable to determine if registry key exists: "${key.path}".\n${err}`));
}
else {
resolve(exists);
}
};
try {
key.winreg.keyExists(onError);
}
catch (err) {
onError(err);
}
});
});
}
exports.doesKeyExist = doesKeyExist;
function doesValueExist(key, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const onError = (err, exists = false) => {
if (err) {
reject(new Error(`Unable to determine if registry value "${value}" exists for key "${key.path}".\n${err}`));
}
else {
resolve(exists);
}
};
try {
key.winreg.valueExists(value, onError);
}
catch (err) {
onError(err);
}
});
});
}
exports.doesValueExist = doesValueExist;
function getNumberValue(key, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const registryValue = yield getValue(key, value);
return registryValue && registryValue.isNumberType
? parseInt(registryValue.data, undefined)
: undefined;
});
}
exports.getNumberValue = getNumberValue;
function getStringValue(key, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const registryValue = yield getValue(key, value);
return registryValue && registryValue.isStringType ? registryValue.data : undefined;
});
}
exports.getStringValue = getStringValue;
function getValue(key, value) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve) => {
const onError = (err, item) => {
if (err) {
resolve(undefined);
}
else {
resolve(item ? new RegistryValue(key.path, item.name, item.type, item.value) : undefined);
}
};
try {
key.winreg.get(value, onError);
}
catch (err) {
onError(err);
}
});
});
}
exports.getValue = getValue;
function getValues(key) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
const callback = (err, items) => {
if (err) {
reject(err);
}
else {
resolve(items.map((item) => new RegistryValue(key.path, item.name, item.type, item.value)));
}
};
try {
key.winreg.values(callback);
}
catch (err) {
reject(err);
}
});
});
}
exports.getValues = getValues;
function isNumberType(registryType) {
// NOTE: REG_QWORD is not included as a number type since it cannot be returned as a "number".
return registryType === RegistryTypes.REG_DWORD;
}
exports.isNumberType = isNumberType;
function isStringType(registryType) {
switch (registryType) {
case RegistryTypes.REG_SZ:
return true;
default:
return false;
}
}
exports.isStringType = isStringType;
function normalizeRegistryHive(hive) {
switch (hive) {
case "HKEY_CURRENT_USER":
return winreg_1.default.HKCU;
case "HKEY_LOCAL_MACHINE":
return winreg_1.default.HKLM;
case "HKEY_CLASSES_ROOT":
return winreg_1.default.HKCR;
case "HKEY_CURRENT_CONFIG":
return winreg_1.default.HKCC;
case "HKEY_USERS":
return winreg_1.default.HKU;
default:
return hive;
}
}
//# sourceMappingURL=registry.js.map
File diff suppressed because one or more lines are too long
+33
View File
@@ -0,0 +1,33 @@
import { AddInType, ManifestInfo, OfficeApp } from "office-addin-manifest";
import { AppType } from "./appType";
/**
* Create an Office document in the temporary files directory
* which can be opened to launch the Office app and load the add-in.
* @param app Office app
* @param manifest Manifest for the add-in.
* @returns Path to the file.
*/
export declare function generateSideloadFile(app: OfficeApp, manifest: ManifestInfo, document?: string): Promise<string>;
/**
* Create an Office document url with query params which can be opened
* to register an Office add-in in Office Online.
* @param manifestPath Path to the manifest file for the Office Add-in.
* @param documentUrl Office Online document url
* @param isTest Indicates whether to append test query param to suppress Office Online dialogs.
* @returns Document url with query params appended.
*/
export declare function generateSideloadUrl(manifestFileName: string, manifest: ManifestInfo, documentUrl: string, isTest?: boolean): Promise<string>;
/**
* Returns the path to the document used as a template for sideloading,
* or undefined if sideloading is not supported.
* @param app Specifies the Office app.
* @param addInType Specifies the type of add-in.
*/
export declare function getTemplatePath(app: OfficeApp, addInType: AddInType): string | undefined;
/**
* Starts the Office app and loads the Office Add-in.
* @param manifestPath Path to the manifest file for the Office Add-in.
* @param app Office app to launch.
* @param canPrompt
*/
export declare function sideloadAddIn(manifestPath: string, app?: OfficeApp, canPrompt?: boolean, appType?: AppType, document?: string, registration?: string): Promise<void>;
+366
View File
@@ -0,0 +1,366 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.sideloadAddIn = exports.getTemplatePath = exports.generateSideloadUrl = exports.generateSideloadFile = void 0;
const tslib_1 = require("tslib");
const fs_1 = tslib_1.__importDefault(require("fs"));
const adm_zip_1 = tslib_1.__importDefault(require("adm-zip"));
const office_addin_manifest_1 = require("office-addin-manifest");
const open = require("open");
const semver = require("semver");
const os_1 = tslib_1.__importDefault(require("os"));
const path_1 = tslib_1.__importDefault(require("path"));
const appType_1 = require("./appType");
const dev_settings_1 = require("./dev-settings");
const process_1 = require("./process");
const prompt_1 = require("./prompt");
const registry = tslib_1.__importStar(require("./registry"));
const defaults_1 = require("./defaults");
const office_addin_usage_data_1 = require("office-addin-usage-data");
/* global Buffer console process URL __dirname */
/**
* Create an Office document in the temporary files directory
* which can be opened to launch the Office app and load the add-in.
* @param app Office app
* @param manifest Manifest for the add-in.
* @returns Path to the file.
*/
function generateSideloadFile(app, manifest, document) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!manifest.id) {
throw new office_addin_usage_data_1.ExpectedError("The manifest does not contain the id for the add-in.");
}
if (!manifest.officeAppType) {
throw new office_addin_usage_data_1.ExpectedError("The manifest does not contain the OfficeApp xsi:type.");
}
if (!manifest.version) {
throw new office_addin_usage_data_1.ExpectedError("The manifest does not contain the version for the add-in.");
}
const addInType = (0, office_addin_manifest_1.getAddInTypeForManifestOfficeAppType)(manifest.officeAppType);
if (!addInType) {
throw new office_addin_usage_data_1.ExpectedError("The manifest contains an unsupported OfficeApp xsi:type.");
}
const documentWasProvided = document && document !== "";
const templatePath = documentWasProvided
? path_1.default.resolve(document)
: getTemplatePath(app, addInType);
if (!templatePath) {
throw new office_addin_usage_data_1.ExpectedError(`Sideload is not supported for apptype: ${addInType}.`);
}
const appName = (0, office_addin_manifest_1.getOfficeAppName)(app);
const extension = path_1.default.extname(templatePath);
const pathToWrite = makePathUnique(path_1.default.join(os_1.default.tmpdir(), `${appName} add-in ${manifest.id}${extension}`), true);
if (!documentWasProvided) {
const webExtensionPath = getWebExtensionPath(app, addInType);
if (!webExtensionPath) {
throw new office_addin_usage_data_1.ExpectedError("Don't know the webextension path.");
}
// replace the placeholder id and version
const templateZip = new adm_zip_1.default(templatePath);
const outZip = new adm_zip_1.default();
const extEntry = templateZip.getEntry(webExtensionPath);
if (!extEntry) {
throw new office_addin_usage_data_1.ExpectedError("webextension was not found.");
}
const webExtensionXml = templateZip
.readAsText(extEntry)
.replace(/00000000-0000-0000-0000-000000000000/g, manifest.id)
.replace(/1.0.0.0/g, manifest.version);
const webExtensionFolderPath = webExtensionPath.substring(0, webExtensionPath.lastIndexOf("/"));
templateZip.getEntries().forEach(function (entry) {
var data = entry.getData();
if (entry == extEntry && manifest.manifestType == office_addin_manifest_1.ManifestType.XML) {
data = Buffer.from(webExtensionXml);
}
// If manifestType is JSON, remove the web extension folder
if (!entry.entryName.startsWith(webExtensionFolderPath) ||
manifest.manifestType !== office_addin_manifest_1.ManifestType.JSON) {
outZip.addFile(entry.entryName, data, entry.comment, entry.attr);
}
});
// Write the file
yield outZip.writeZipPromise(pathToWrite);
}
else {
yield fs_1.default.promises.copyFile(templatePath, pathToWrite);
}
return pathToWrite;
});
}
exports.generateSideloadFile = generateSideloadFile;
/**
* Create an Office document url with query params which can be opened
* to register an Office add-in in Office Online.
* @param manifestPath Path to the manifest file for the Office Add-in.
* @param documentUrl Office Online document url
* @param isTest Indicates whether to append test query param to suppress Office Online dialogs.
* @returns Document url with query params appended.
*/
function generateSideloadUrl(manifestFileName, manifest, documentUrl, isTest = false) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const testQueryParam = "&wdaddintest=true";
if (!manifest.id) {
throw new office_addin_usage_data_1.ExpectedError("The manifest does not contain the id for the add-in.");
}
if (manifest.defaultSettings === undefined ||
manifest.defaultSettings.sourceLocation === undefined) {
throw new office_addin_usage_data_1.ExpectedError("The manifest does not contain the SourceLocation for the add-in");
}
const sourceLocationUrl = new URL(manifest.defaultSettings.sourceLocation);
if (sourceLocationUrl.protocol.indexOf("https") === -1) {
throw new office_addin_usage_data_1.ExpectedError("The SourceLocation in the manifest does not use the HTTPS protocol.");
}
if (sourceLocationUrl.host.indexOf("localhost") === -1 &&
sourceLocationUrl.host.indexOf("127.0.0.1") === -1) {
throw new office_addin_usage_data_1.ExpectedError("The hostname specified by the SourceLocation in the manifest is not supported for sideload. The hostname should be 'localhost' or 127.0.0.1.");
}
let queryParms = `&wdaddindevserverport=${sourceLocationUrl.port}&wdaddinmanifestfile=${manifestFileName}&wdaddinmanifestguid=${manifest.id}`;
if (isTest) {
queryParms = `${queryParms}${testQueryParam}`;
}
return `${documentUrl}${queryParms}`;
});
}
exports.generateSideloadUrl = generateSideloadUrl;
/**
* Returns the path to the document used as a template for sideloading,
* or undefined if sideloading is not supported.
* @param app Specifies the Office app.
* @param addInType Specifies the type of add-in.
*/
function getTemplatePath(app, addInType) {
switch (app) {
case office_addin_manifest_1.OfficeApp.Excel:
switch (addInType) {
case office_addin_manifest_1.AddInType.Content:
return path_1.default.resolve(__dirname, "../templates/ExcelWorkbookWithContent.xlsx");
case office_addin_manifest_1.AddInType.TaskPane:
return path_1.default.resolve(__dirname, "../templates/ExcelWorkbookWithTaskPane.xlsx");
}
break;
case office_addin_manifest_1.OfficeApp.PowerPoint:
switch (addInType) {
case office_addin_manifest_1.AddInType.Content:
return path_1.default.resolve(__dirname, "../templates/PowerPointPresentationWithContent.pptx");
case office_addin_manifest_1.AddInType.TaskPane:
return path_1.default.resolve(__dirname, "../templates/PowerPointPresentationWithTaskPane.pptx");
}
break;
case office_addin_manifest_1.OfficeApp.Word:
switch (addInType) {
case office_addin_manifest_1.AddInType.TaskPane:
return path_1.default.resolve(__dirname, "../templates/WordDocumentWithTaskPane.docx");
}
break;
}
}
exports.getTemplatePath = getTemplatePath;
/**
* Returns the web extension path in the sideload document.
* @param app Specifies the Office app.
* @param addInType Specifies the type of add-in.
*/
function getWebExtensionPath(app, addInType) {
switch (app) {
case office_addin_manifest_1.OfficeApp.Excel:
return "xl/webextensions/webextension.xml";
case office_addin_manifest_1.OfficeApp.PowerPoint:
switch (addInType) {
case office_addin_manifest_1.AddInType.Content:
return "ppt/slides/udata/data.xml";
case office_addin_manifest_1.AddInType.TaskPane:
return "ppt/webextensions/webextension.xml";
}
break;
case office_addin_manifest_1.OfficeApp.Word:
return "word/webextensions/webextension.xml";
}
}
function isSideloadingSupportedForDesktopHost(app) {
if (app === office_addin_manifest_1.OfficeApp.Excel ||
(app === office_addin_manifest_1.OfficeApp.Outlook && process.platform === "win32") ||
app === office_addin_manifest_1.OfficeApp.PowerPoint ||
app === office_addin_manifest_1.OfficeApp.Word) {
return true;
}
return false;
}
function isSideloadingSupportedForWebHost(app) {
if (app === office_addin_manifest_1.OfficeApp.Excel ||
app === office_addin_manifest_1.OfficeApp.PowerPoint ||
app === office_addin_manifest_1.OfficeApp.Project ||
app === office_addin_manifest_1.OfficeApp.Word) {
return true;
}
return false;
}
function hasOfficeVersion(targetVersion, currentVersion) {
return semver.gte(currentVersion, targetVersion);
}
function getOutlookVersion() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const key = new registry.RegistryKey(`HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Office\\ClickToRun\\Configuration`);
const outlookInstallVersion = yield registry.getStringValue(key, "ClientVersionToReport");
const outlookSmallerVersion = outlookInstallVersion === null || outlookInstallVersion === void 0 ? void 0 : outlookInstallVersion.split(`.`, 3).join(`.`);
return outlookSmallerVersion;
}
catch (_a) {
return undefined;
}
});
}
function getOutlookExePath() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
const OutlookInstallPathRegistryKey = `HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\OUTLOOK.EXE`;
const key = new registry.RegistryKey(`${OutlookInstallPathRegistryKey}`);
const outlookExePath = yield registry.getStringValue(key, "");
if (!outlookExePath) {
throw new Error("Outlook.exe registry empty");
}
return outlookExePath;
}
catch (err) {
const errorMessage = `Unable to find Outlook install location: \n${err}`;
throw new Error(errorMessage);
}
});
}
/**
* Given a file path, returns a unique file path where the file doesn't exist by
* appending a period and a numeric suffix, starting from 2.
* @param tryToDelete If true, first try to delete the file if it exists.
*/
function makePathUnique(originalPath, tryToDelete = false) {
let currentPath = originalPath;
let parsedPath = null;
let suffix = 1;
while (fs_1.default.existsSync(currentPath)) {
let deleted = false;
if (tryToDelete) {
try {
fs_1.default.unlinkSync(currentPath);
deleted = true;
}
catch (_a) {
// no error (file is in use)
}
}
if (!deleted) {
++suffix;
if (parsedPath == null) {
parsedPath = path_1.default.parse(originalPath);
}
currentPath = path_1.default.join(parsedPath.dir, `${parsedPath.name}.${suffix}${parsedPath.ext}`);
}
}
return currentPath;
}
/**
* Starts the Office app and loads the Office Add-in.
* @param manifestPath Path to the manifest file for the Office Add-in.
* @param app Office app to launch.
* @param canPrompt
*/
function sideloadAddIn(manifestPath, app, canPrompt = false, appType, document, registration) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
try {
if (appType === undefined) {
appType = appType_1.AppType.Desktop;
}
const manifest = yield office_addin_manifest_1.OfficeAddinManifest.readManifestFile(manifestPath);
const appsInManifest = (0, office_addin_manifest_1.getOfficeAppsForManifestHosts)(manifest.hosts);
if (app) {
if (appsInManifest.indexOf(app) < 0) {
throw new office_addin_usage_data_1.ExpectedError(`The Office Add-in manifest does not support ${(0, office_addin_manifest_1.getOfficeAppName)(app)}.`);
}
}
else {
switch (appsInManifest.length) {
case 0:
throw new office_addin_usage_data_1.ExpectedError("The manifest does not support any Office apps.");
case 1:
app = appsInManifest[0];
break;
default:
if (canPrompt) {
app = yield (0, prompt_1.chooseOfficeApp)(appsInManifest);
}
break;
}
}
if (!app) {
throw new office_addin_usage_data_1.ExpectedError("Please specify the Office app.");
}
switch (appType) {
case appType_1.AppType.Desktop:
yield (0, dev_settings_1.registerAddIn)(manifestPath, registration);
yield launchDesktopApp(app, manifest, document);
break;
case appType_1.AppType.Web: {
if (!document) {
throw new office_addin_usage_data_1.ExpectedError(`For sideload to web, you need to specify a document url.`);
}
yield launchWebApp(app, manifestPath, manifest, document);
break;
}
default:
throw new office_addin_usage_data_1.ExpectedError("Sideload is not supported for the specified app type.");
}
defaults_1.usageDataObject.reportSuccess("sideloadAddIn()");
}
catch (err) {
defaults_1.usageDataObject.reportException("sideloadAddIn()", err);
throw err;
}
});
}
exports.sideloadAddIn = sideloadAddIn;
function launchDesktopApp(app, manifest, document) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!isSideloadingSupportedForDesktopHost(app)) {
throw new office_addin_usage_data_1.ExpectedError(`Sideload to the ${(0, office_addin_manifest_1.getOfficeAppName)(app)} app is not supported.`);
}
// for Outlook, open Outlook.exe; for other Office apps, open the document
if (app == office_addin_manifest_1.OfficeApp.Outlook) {
const version = yield getOutlookVersion();
if (version && !hasOfficeVersion("16.0.13709", version)) {
throw new office_addin_usage_data_1.ExpectedError(`The current version of Outlook does not support sideload. Please use version 16.0.13709 or greater.`);
}
yield launchApp(app, yield getOutlookExePath());
}
else {
yield launchApp(app, yield generateSideloadFile(app, manifest, document));
}
});
}
function launchWebApp(app, manifestPath, manifest, document) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!isSideloadingSupportedForWebHost(app)) {
throw new office_addin_usage_data_1.ExpectedError(`Sideload to the ${(0, office_addin_manifest_1.getOfficeAppName)(app)} web app is not supported.`);
}
const manifestFileName = path_1.default.basename(manifestPath);
const isTest = process.env.WEB_SIDELOAD_TEST !== undefined;
yield launchApp(app, yield generateSideloadUrl(manifestFileName, manifest, document, isTest));
});
}
function launchApp(app, sideloadFile) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
console.log(`Launching ${app} via ${sideloadFile}`);
if (sideloadFile) {
if (app === office_addin_manifest_1.OfficeApp.Outlook) {
// put the Outlook.exe path in quotes if it contains spaces
if (sideloadFile.indexOf(" ") >= 0) {
sideloadFile = `"${sideloadFile}"`;
}
(0, process_1.startDetachedProcess)(sideloadFile);
}
else {
yield open(sideloadFile, { wait: false });
}
}
});
}
//# sourceMappingURL=sideload.js.map
File diff suppressed because one or more lines are too long
+22
View File
@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
File diff suppressed because it is too large Load Diff
+16
View File
@@ -0,0 +1,16 @@
import commander from './index.js';
// wrapper to provide named exports for ESM.
export const {
program,
createCommand,
createArgument,
createOption,
CommanderError,
InvalidArgumentError,
InvalidOptionArgumentError, // deprecated old name
Command,
Argument,
Option,
Help,
} = commander;
+24
View File
@@ -0,0 +1,24 @@
const { Argument } = require('./lib/argument.js');
const { Command } = require('./lib/command.js');
const { CommanderError, InvalidArgumentError } = require('./lib/error.js');
const { Help } = require('./lib/help.js');
const { Option } = require('./lib/option.js');
exports.program = new Command();
exports.createCommand = (name) => new Command(name);
exports.createOption = (flags, description) => new Option(flags, description);
exports.createArgument = (name, description) => new Argument(name, description);
/**
* Expose classes
*/
exports.Command = Command;
exports.Option = Option;
exports.Argument = Argument;
exports.Help = Help;
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
@@ -0,0 +1,149 @@
const { InvalidArgumentError } = require('./error.js');
class Argument {
/**
* Initialize a new command argument with the given name and description.
* The default is that the argument is required, and you can explicitly
* indicate this with <> around the name. Put [] around the name for an optional argument.
*
* @param {string} name
* @param {string} [description]
*/
constructor(name, description) {
this.description = description || '';
this.variadic = false;
this.parseArg = undefined;
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.argChoices = undefined;
switch (name[0]) {
case '<': // e.g. <required>
this.required = true;
this._name = name.slice(1, -1);
break;
case '[': // e.g. [optional]
this.required = false;
this._name = name.slice(1, -1);
break;
default:
this.required = true;
this._name = name;
break;
}
if (this._name.length > 3 && this._name.slice(-3) === '...') {
this.variadic = true;
this._name = this._name.slice(0, -3);
}
}
/**
* Return argument name.
*
* @return {string}
*/
name() {
return this._name;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Argument}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Set the custom handler for processing CLI command arguments into argument values.
*
* @param {Function} [fn]
* @return {Argument}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Only allow argument value to be one of choices.
*
* @param {string[]} values
* @return {Argument}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Make argument required.
*
* @returns {Argument}
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*
* @returns {Argument}
*/
argOptional() {
this.required = false;
return this;
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Argument} arg
* @return {string}
* @private
*/
function humanReadableArgName(arg) {
const nameOutput = arg.name() + (arg.variadic === true ? '...' : '');
return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']';
}
exports.Argument = Argument;
exports.humanReadableArgName = humanReadableArgName;
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,39 @@
/**
* CommanderError class
*/
class CommanderError extends Error {
/**
* Constructs the CommanderError class
* @param {number} exitCode suggested exit code which could be used with process.exit
* @param {string} code an id string representing the error
* @param {string} message human-readable description of the error
*/
constructor(exitCode, code, message) {
super(message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.code = code;
this.exitCode = exitCode;
this.nestedError = undefined;
}
}
/**
* InvalidArgumentError class
*/
class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
*/
constructor(message) {
super(1, 'commander.invalidArgument', message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
@@ -0,0 +1,709 @@
const { humanReadableArgName } = require('./argument.js');
/**
* TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS`
* https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types
* @typedef { import("./argument.js").Argument } Argument
* @typedef { import("./command.js").Command } Command
* @typedef { import("./option.js").Option } Option
*/
// Although this is a class, methods are static in style to allow override using subclass or just functions.
class Help {
constructor() {
this.helpWidth = undefined;
this.minWidthToWrap = 40;
this.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
* and just before calling `formatHelp()`.
*
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
*
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
*/
prepareContext(contextOptions) {
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
}
/**
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
*
* @param {Command} cmd
* @returns {Command[]}
*/
visibleCommands(cmd) {
const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden);
const helpCommand = cmd._getHelpCommand();
if (helpCommand && !helpCommand._hidden) {
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
// @ts-ignore: because overloaded return type
return a.name().localeCompare(b.name());
});
}
return visibleCommands;
}
/**
* Compare options for sort.
*
* @param {Option} a
* @param {Option} b
* @returns {number}
*/
compareOptions(a, b) {
const getSortKey = (option) => {
// WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated.
return option.short
? option.short.replace(/^-/, '')
: option.long.replace(/^--/, '');
};
return getSortKey(a).localeCompare(getSortKey(b));
}
/**
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleOptions(cmd) {
const visibleOptions = cmd.options.filter((option) => !option.hidden);
// Built-in help option.
const helpOption = cmd._getHelpOption();
if (helpOption && !helpOption.hidden) {
// Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs.
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
if (!removeShort && !removeLong) {
visibleOptions.push(helpOption); // no changes needed
} else if (helpOption.long && !removeLong) {
visibleOptions.push(
cmd.createOption(helpOption.long, helpOption.description),
);
} else if (helpOption.short && !removeShort) {
visibleOptions.push(
cmd.createOption(helpOption.short, helpOption.description),
);
}
}
if (this.sortOptions) {
visibleOptions.sort(this.compareOptions);
}
return visibleOptions;
}
/**
* Get an array of the visible global options. (Not including help.)
*
* @param {Command} cmd
* @returns {Option[]}
*/
visibleGlobalOptions(cmd) {
if (!this.showGlobalOptions) return [];
const globalOptions = [];
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
const visibleOptions = ancestorCmd.options.filter(
(option) => !option.hidden,
);
globalOptions.push(...visibleOptions);
}
if (this.sortOptions) {
globalOptions.sort(this.compareOptions);
}
return globalOptions;
}
/**
* Get an array of the arguments if any have a description.
*
* @param {Command} cmd
* @returns {Argument[]}
*/
visibleArguments(cmd) {
// Side effect! Apply the legacy descriptions before the arguments are displayed.
if (cmd._argsDescription) {
cmd.registeredArguments.forEach((argument) => {
argument.description =
argument.description || cmd._argsDescription[argument.name()] || '';
});
}
// If there are any arguments with a description then return all the arguments.
if (cmd.registeredArguments.find((argument) => argument.description)) {
return cmd.registeredArguments;
}
return [];
}
/**
* Get the command term to show in the list of subcommands.
*
* @param {Command} cmd
* @returns {string}
*/
subcommandTerm(cmd) {
// Legacy. Ignores custom usage string, and nested commands.
const args = cmd.registeredArguments
.map((arg) => humanReadableArgName(arg))
.join(' ');
return (
cmd._name +
(cmd._aliases[0] ? '|' + cmd._aliases[0] : '') +
(cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option
(args ? ' ' + args : '')
);
}
/**
* Get the option term to show in the list of options.
*
* @param {Option} option
* @returns {string}
*/
optionTerm(option) {
return option.flags;
}
/**
* Get the argument term to show in the list of arguments.
*
* @param {Argument} argument
* @returns {string}
*/
argumentTerm(argument) {
return argument.name();
}
/**
* Get the longest command term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestSubcommandTermLength(cmd, helper) {
return helper.visibleCommands(cmd).reduce((max, command) => {
return Math.max(
max,
this.displayWidth(
helper.styleSubcommandTerm(helper.subcommandTerm(command)),
),
);
}, 0);
}
/**
* Get the longest option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestOptionTermLength(cmd, helper) {
return helper.visibleOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest global option term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestGlobalOptionTermLength(cmd, helper) {
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
return Math.max(
max,
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option))),
);
}, 0);
}
/**
* Get the longest argument term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
longestArgumentTermLength(cmd, helper) {
return helper.visibleArguments(cmd).reduce((max, argument) => {
return Math.max(
max,
this.displayWidth(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
),
);
}, 0);
}
/**
* Get the command usage to be displayed at the top of the built-in help.
*
* @param {Command} cmd
* @returns {string}
*/
commandUsage(cmd) {
// Usage
let cmdName = cmd._name;
if (cmd._aliases[0]) {
cmdName = cmdName + '|' + cmd._aliases[0];
}
let ancestorCmdNames = '';
for (
let ancestorCmd = cmd.parent;
ancestorCmd;
ancestorCmd = ancestorCmd.parent
) {
ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames;
}
return ancestorCmdNames + cmdName + ' ' + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.description();
}
/**
* Get the subcommand summary to show in the list of subcommands.
* (Fallback to description for backwards compatibility.)
*
* @param {Command} cmd
* @returns {string}
*/
subcommandDescription(cmd) {
// @ts-ignore: because overloaded return type
return cmd.summary() || cmd.description();
}
/**
* Get the option description to show in the list of options.
*
* @param {Option} option
* @return {string}
*/
optionDescription(option) {
const extraInfo = [];
if (option.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (option.defaultValue !== undefined) {
// default for boolean and negated more for programmer than end user,
// but show true/false for boolean option as may be for hand-rolled env or config processing.
const showDefault =
option.required ||
option.optional ||
(option.isBoolean() && typeof option.defaultValue === 'boolean');
if (showDefault) {
extraInfo.push(
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`,
);
}
}
// preset for boolean and negated are more for programmer than end user
if (option.presetArg !== undefined && option.optional) {
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
}
if (option.envVar !== undefined) {
extraInfo.push(`env: ${option.envVar}`);
}
if (extraInfo.length > 0) {
return `${option.description} (${extraInfo.join(', ')})`;
}
return option.description;
}
/**
* Get the argument description to show in the list of arguments.
*
* @param {Argument} argument
* @return {string}
*/
argumentDescription(argument) {
const extraInfo = [];
if (argument.argChoices) {
extraInfo.push(
// use stringify to match the display of the default value
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`,
);
}
if (argument.defaultValue !== undefined) {
extraInfo.push(
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`,
);
}
if (extraInfo.length > 0) {
const extraDescription = `(${extraInfo.join(', ')})`;
if (argument.description) {
return `${argument.description} ${extraDescription}`;
}
return extraDescription;
}
return argument.description;
}
/**
* Generate the built-in help text.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {string}
*/
formatHelp(cmd, helper) {
const termWidth = helper.padWidth(cmd, helper);
const helpWidth = helper.helpWidth ?? 80; // in case prepareContext() was not called
function callFormatItem(term, description) {
return helper.formatItem(term, termWidth, description, helper);
}
// Usage
let output = [
`${helper.styleTitle('Usage:')} ${helper.styleUsage(helper.commandUsage(cmd))}`,
'',
];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([
helper.boxWrap(
helper.styleCommandDescription(commandDescription),
helpWidth,
),
'',
]);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return callFormatItem(
helper.styleArgumentTerm(helper.argumentTerm(argument)),
helper.styleArgumentDescription(helper.argumentDescription(argument)),
);
});
if (argumentList.length > 0) {
output = output.concat([
helper.styleTitle('Arguments:'),
...argumentList,
'',
]);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (optionList.length > 0) {
output = output.concat([
helper.styleTitle('Options:'),
...optionList,
'',
]);
}
if (helper.showGlobalOptions) {
const globalOptionList = helper
.visibleGlobalOptions(cmd)
.map((option) => {
return callFormatItem(
helper.styleOptionTerm(helper.optionTerm(option)),
helper.styleOptionDescription(helper.optionDescription(option)),
);
});
if (globalOptionList.length > 0) {
output = output.concat([
helper.styleTitle('Global Options:'),
...globalOptionList,
'',
]);
}
}
// Commands
const commandList = helper.visibleCommands(cmd).map((cmd) => {
return callFormatItem(
helper.styleSubcommandTerm(helper.subcommandTerm(cmd)),
helper.styleSubcommandDescription(helper.subcommandDescription(cmd)),
);
});
if (commandList.length > 0) {
output = output.concat([
helper.styleTitle('Commands:'),
...commandList,
'',
]);
}
return output.join('\n');
}
/**
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
*
* @param {string} str
* @returns {number}
*/
displayWidth(str) {
return stripColor(str).length;
}
/**
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
*
* @param {string} str
* @returns {string}
*/
styleTitle(str) {
return str;
}
styleUsage(str) {
// Usage has lots of parts the user might like to color separately! Assume default usage string which is formed like:
// command subcommand [options] [command] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word === '[command]') return this.styleSubcommandText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleCommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleCommandDescription(str) {
return this.styleDescriptionText(str);
}
styleOptionDescription(str) {
return this.styleDescriptionText(str);
}
styleSubcommandDescription(str) {
return this.styleDescriptionText(str);
}
styleArgumentDescription(str) {
return this.styleDescriptionText(str);
}
styleDescriptionText(str) {
return str;
}
styleOptionTerm(str) {
return this.styleOptionText(str);
}
styleSubcommandTerm(str) {
// This is very like usage with lots of parts! Assume default string which is formed like:
// subcommand [options] <foo> [bar]
return str
.split(' ')
.map((word) => {
if (word === '[options]') return this.styleOptionText(word);
if (word[0] === '[' || word[0] === '<')
return this.styleArgumentText(word);
return this.styleSubcommandText(word); // Restrict to initial words?
})
.join(' ');
}
styleArgumentTerm(str) {
return this.styleArgumentText(str);
}
styleOptionText(str) {
return str;
}
styleArgumentText(str) {
return str;
}
styleSubcommandText(str) {
return str;
}
styleCommandText(str) {
return str;
}
/**
* Calculate the pad width from the maximum term length.
*
* @param {Command} cmd
* @param {Help} helper
* @returns {number}
*/
padWidth(cmd, helper) {
return Math.max(
helper.longestOptionTermLength(cmd, helper),
helper.longestGlobalOptionTermLength(cmd, helper),
helper.longestSubcommandTermLength(cmd, helper),
helper.longestArgumentTermLength(cmd, helper),
);
}
/**
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
*
* @param {string} str
* @returns {boolean}
*/
preformatted(str) {
return /\n[^\S\r\n]/.test(str);
}
/**
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
*
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
* TTT DDD DDDD
* DD DDD
*
* @param {string} term
* @param {number} termWidth
* @param {string} description
* @param {Help} helper
* @returns {string}
*/
formatItem(term, termWidth, description, helper) {
const itemIndent = 2;
const itemIndentStr = ' '.repeat(itemIndent);
if (!description) return itemIndentStr + term;
// Pad the term out to a consistent width, so descriptions are aligned.
const paddedTerm = term.padEnd(
termWidth + term.length - helper.displayWidth(term),
);
// Format the description.
const spacerWidth = 2; // between term and description
const helpWidth = this.helpWidth ?? 80; // in case prepareContext() was not called
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
let formattedDescription;
if (
remainingWidth < this.minWidthToWrap ||
helper.preformatted(description)
) {
formattedDescription = description;
} else {
const wrappedDescription = helper.boxWrap(description, remainingWidth);
formattedDescription = wrappedDescription.replace(
/\n/g,
'\n' + ' '.repeat(termWidth + spacerWidth),
);
}
// Construct and overall indent.
return (
itemIndentStr +
paddedTerm +
' '.repeat(spacerWidth) +
formattedDescription.replace(/\n/g, `\n${itemIndentStr}`)
);
}
/**
* Wrap a string at whitespace, preserving existing line breaks.
* Wrapping is skipped if the width is less than `minWidthToWrap`.
*
* @param {string} str
* @param {number} width
* @returns {string}
*/
boxWrap(str, width) {
if (width < this.minWidthToWrap) return str;
const rawLines = str.split(/\r\n|\n/);
// split up text by whitespace
const chunkPattern = /[\s]*[^\s]+/g;
const wrappedLines = [];
rawLines.forEach((line) => {
const chunks = line.match(chunkPattern);
if (chunks === null) {
wrappedLines.push('');
return;
}
let sumChunks = [chunks.shift()];
let sumWidth = this.displayWidth(sumChunks[0]);
chunks.forEach((chunk) => {
const visibleWidth = this.displayWidth(chunk);
// Accumulate chunks while they fit into width.
if (sumWidth + visibleWidth <= width) {
sumChunks.push(chunk);
sumWidth += visibleWidth;
return;
}
wrappedLines.push(sumChunks.join(''));
const nextChunk = chunk.trimStart(); // trim space at line break
sumChunks = [nextChunk];
sumWidth = this.displayWidth(nextChunk);
});
wrappedLines.push(sumChunks.join(''));
});
return wrappedLines.join('\n');
}
}
/**
* Strip style ANSI escape sequences from the string. In particular, SGR (Select Graphic Rendition) codes.
*
* @param {string} str
* @returns {string}
* @package
*/
function stripColor(str) {
// eslint-disable-next-line no-control-regex
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
return str.replace(sgrPattern, '');
}
exports.Help = Help;
exports.stripColor = stripColor;
@@ -0,0 +1,367 @@
const { InvalidArgumentError } = require('./error.js');
class Option {
/**
* Initialize a new `Option` with the given `flags` and `description`.
*
* @param {string} flags
* @param {string} [description]
*/
constructor(flags, description) {
this.flags = flags;
this.description = description || '';
this.required = flags.includes('<'); // A value must be supplied when the option is specified.
this.optional = flags.includes('['); // A value is optional when the option is specified.
// variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
const optionFlags = splitOptionFlags(flags);
this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
this.long = optionFlags.longFlag;
this.negate = false;
if (this.long) {
this.negate = this.long.startsWith('--no-');
}
this.defaultValue = undefined;
this.defaultValueDescription = undefined;
this.presetArg = undefined;
this.envVar = undefined;
this.parseArg = undefined;
this.hidden = false;
this.argChoices = undefined;
this.conflictsWith = [];
this.implied = undefined;
}
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*
* @param {*} value
* @param {string} [description]
* @return {Option}
*/
default(value, description) {
this.defaultValue = value;
this.defaultValueDescription = description;
return this;
}
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
*
* @param {*} arg
* @return {Option}
*/
preset(arg) {
this.presetArg = arg;
return this;
}
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
*
* @param {(string | string[])} names
* @return {Option}
*/
conflicts(names) {
this.conflictsWith = this.conflictsWith.concat(names);
return this;
}
/**
* Specify implied option values for when this option is set and the implied options are not.
*
* The custom processing (parseArg) is not called on the implied values.
*
* @example
* program
* .addOption(new Option('--log', 'write logging information to file'))
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
*
* @param {object} impliedOptionValues
* @return {Option}
*/
implies(impliedOptionValues) {
let newImplied = impliedOptionValues;
if (typeof impliedOptionValues === 'string') {
// string is not documented, but easy mistake and we can do what user probably intended.
newImplied = { [impliedOptionValues]: true };
}
this.implied = Object.assign(this.implied || {}, newImplied);
return this;
}
/**
* Set environment variable to check for option value.
*
* An environment variable is only used if when processed the current option value is
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
*
* @param {string} name
* @return {Option}
*/
env(name) {
this.envVar = name;
return this;
}
/**
* Set the custom handler for processing CLI option arguments into option values.
*
* @param {Function} [fn]
* @return {Option}
*/
argParser(fn) {
this.parseArg = fn;
return this;
}
/**
* Whether the option is mandatory and must have a value after parsing.
*
* @param {boolean} [mandatory=true]
* @return {Option}
*/
makeOptionMandatory(mandatory = true) {
this.mandatory = !!mandatory;
return this;
}
/**
* Hide option in help.
*
* @param {boolean} [hide=true]
* @return {Option}
*/
hideHelp(hide = true) {
this.hidden = !!hide;
return this;
}
/**
* @package
*/
_concatValue(value, previous) {
if (previous === this.defaultValue || !Array.isArray(previous)) {
return [value];
}
return previous.concat(value);
}
/**
* Only allow option value to be one of choices.
*
* @param {string[]} values
* @return {Option}
*/
choices(values) {
this.argChoices = values.slice();
this.parseArg = (arg, previous) => {
if (!this.argChoices.includes(arg)) {
throw new InvalidArgumentError(
`Allowed choices are ${this.argChoices.join(', ')}.`,
);
}
if (this.variadic) {
return this._concatValue(arg, previous);
}
return arg;
};
return this;
}
/**
* Return option name.
*
* @return {string}
*/
name() {
if (this.long) {
return this.long.replace(/^--/, '');
}
return this.short.replace(/^-/, '');
}
/**
* Return option name, in a camelcase format that can be used
* as an object attribute key.
*
* @return {string}
*/
attributeName() {
if (this.negate) {
return camelcase(this.name().replace(/^no-/, ''));
}
return camelcase(this.name());
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @package
*/
is(arg) {
return this.short === arg || this.long === arg;
}
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*
* @return {boolean}
* @package
*/
isBoolean() {
return !this.required && !this.optional && !this.negate;
}
}
/**
* This class is to make it easier to work with dual options, without changing the existing
* implementation. We support separate dual options for separate positive and negative options,
* like `--build` and `--no-build`, which share a single option value. This works nicely for some
* use cases, but is tricky for others where we want separate behaviours despite
* the single shared option value.
*/
class DualOptions {
/**
* @param {Option[]} options
*/
constructor(options) {
this.positiveOptions = new Map();
this.negativeOptions = new Map();
this.dualOptions = new Set();
options.forEach((option) => {
if (option.negate) {
this.negativeOptions.set(option.attributeName(), option);
} else {
this.positiveOptions.set(option.attributeName(), option);
}
});
this.negativeOptions.forEach((value, key) => {
if (this.positiveOptions.has(key)) {
this.dualOptions.add(key);
}
});
}
/**
* Did the value come from the option, and not from possible matching dual option?
*
* @param {*} value
* @param {Option} option
* @returns {boolean}
*/
valueFromOption(value, option) {
const optionKey = option.attributeName();
if (!this.dualOptions.has(optionKey)) return true;
// Use the value to deduce if (probably) came from the option.
const preset = this.negativeOptions.get(optionKey).presetArg;
const negativeValue = preset !== undefined ? preset : false;
return option.negate === (negativeValue === value);
}
}
/**
* Convert string from kebab-case to camelCase.
*
* @param {string} str
* @return {string}
* @private
*/
function camelcase(str) {
return str.split('-').reduce((str, word) => {
return str + word[0].toUpperCase() + word.slice(1);
});
}
/**
* Split the short and long flag out of something like '-m,--mixed <value>'
*
* @private
*/
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
// short flag, single dash and single character
const shortFlagExp = /^-[^-]$/;
// long flag, double dash and at least one character
const longFlagExp = /^--[^-]/;
const flagParts = flags.split(/[ |,]+/).concat('guard');
// Normal is short and/or long.
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
// Long then short. Rarely used but fine.
if (!shortFlag && shortFlagExp.test(flagParts[0]))
shortFlag = flagParts.shift();
// Allow two long flags, like '--ws, --workspace'
// This is the supported way to have a shortish option flag.
if (!shortFlag && longFlagExp.test(flagParts[0])) {
shortFlag = longFlag;
longFlag = flagParts.shift();
}
// Check for unprocessed flag. Fail noisily rather than silently ignore.
if (flagParts[0].startsWith('-')) {
const unsupportedFlag = flagParts[0];
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
if (/^-[^-][^-]/.test(unsupportedFlag))
throw new Error(
`${baseError}
- a short flag is a single dash and a single character
- either use a single dash and a single character (for a short flag)
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
);
if (shortFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many short flags`);
if (longFlagExp.test(unsupportedFlag))
throw new Error(`${baseError}
- too many long flags`);
throw new Error(`${baseError}
- unrecognised flag format`);
}
if (shortFlag === undefined && longFlag === undefined)
throw new Error(
`option creation failed due to no flags found in '${flags}'.`,
);
return { shortFlag, longFlag };
}
exports.Option = Option;
exports.DualOptions = DualOptions;
@@ -0,0 +1,101 @@
const maxDistance = 3;
function editDistance(a, b) {
// https://en.wikipedia.org/wiki/DamerauLevenshtein_distance
// Calculating optimal string alignment distance, no substring is edited more than once.
// (Simple implementation.)
// Quick early exit, return worst case.
if (Math.abs(a.length - b.length) > maxDistance)
return Math.max(a.length, b.length);
// distance between prefix substrings of a and b
const d = [];
// pure deletions turn a into empty string
for (let i = 0; i <= a.length; i++) {
d[i] = [i];
}
// pure insertions turn empty string into b
for (let j = 0; j <= b.length; j++) {
d[0][j] = j;
}
// fill matrix
for (let j = 1; j <= b.length; j++) {
for (let i = 1; i <= a.length; i++) {
let cost = 1;
if (a[i - 1] === b[j - 1]) {
cost = 0;
} else {
cost = 1;
}
d[i][j] = Math.min(
d[i - 1][j] + 1, // deletion
d[i][j - 1] + 1, // insertion
d[i - 1][j - 1] + cost, // substitution
);
// transposition
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
}
}
}
return d[a.length][b.length];
}
/**
* Find close matches, restricted to same number of edits.
*
* @param {string} word
* @param {string[]} candidates
* @returns {string}
*/
function suggestSimilar(word, candidates) {
if (!candidates || candidates.length === 0) return '';
// remove possible duplicates
candidates = Array.from(new Set(candidates));
const searchingOptions = word.startsWith('--');
if (searchingOptions) {
word = word.slice(2);
candidates = candidates.map((candidate) => candidate.slice(2));
}
let similar = [];
let bestDistance = maxDistance;
const minSimilarity = 0.4;
candidates.forEach((candidate) => {
if (candidate.length <= 1) return; // no one character guesses
const distance = editDistance(word, candidate);
const length = Math.max(word.length, candidate.length);
const similarity = (length - distance) / length;
if (similarity > minSimilarity) {
if (distance < bestDistance) {
// better edit distance, throw away previous worse matches
bestDistance = distance;
similar = [candidate];
} else if (distance === bestDistance) {
similar.push(candidate);
}
}
});
similar.sort((a, b) => a.localeCompare(b));
if (searchingOptions) {
similar = similar.map((candidate) => `--${candidate}`);
}
if (similar.length > 1) {
return `\n(Did you mean one of ${similar.join(', ')}?)`;
}
if (similar.length === 1) {
return `\n(Did you mean ${similar[0]}?)`;
}
return '';
}
exports.suggestSimilar = suggestSimilar;
@@ -0,0 +1,16 @@
{
"versions": [
{
"version": "*",
"target": {
"node": "supported"
},
"response": {
"type": "time-permitting"
},
"backing": {
"npm-funding": true
}
}
]
}
@@ -0,0 +1,82 @@
{
"name": "commander",
"version": "13.1.0",
"description": "the complete solution for node.js command-line programs",
"keywords": [
"commander",
"command",
"option",
"parser",
"cli",
"argument",
"args",
"argv"
],
"author": "TJ Holowaychuk <tj@vision-media.ca>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/tj/commander.js.git"
},
"scripts": {
"check": "npm run check:type && npm run check:lint && npm run check:format",
"check:format": "prettier --check .",
"check:lint": "eslint .",
"check:type": "npm run check:type:js && npm run check:type:ts",
"check:type:ts": "tsd && tsc -p tsconfig.ts.json",
"check:type:js": "tsc -p tsconfig.js.json",
"fix": "npm run fix:lint && npm run fix:format",
"fix:format": "prettier --write .",
"fix:lint": "eslint --fix .",
"test": "jest && npm run check:type:ts",
"test-all": "jest && npm run test-esm && npm run check",
"test-esm": "node ./tests/esm-imports-test.mjs"
},
"files": [
"index.js",
"lib/*.js",
"esm.mjs",
"typings/index.d.ts",
"typings/esm.d.mts",
"package-support.json"
],
"type": "commonjs",
"main": "./index.js",
"exports": {
".": {
"require": {
"types": "./typings/index.d.ts",
"default": "./index.js"
},
"import": {
"types": "./typings/esm.d.mts",
"default": "./esm.mjs"
},
"default": "./index.js"
},
"./esm.mjs": {
"types": "./typings/esm.d.mts",
"import": "./esm.mjs"
}
},
"devDependencies": {
"@eslint/js": "^9.4.0",
"@types/jest": "^29.2.4",
"@types/node": "^22.7.4",
"eslint": "^9.17.0",
"eslint-config-prettier": "^9.1.0",
"eslint-plugin-jest": "^28.3.0",
"globals": "^15.7.0",
"jest": "^29.3.1",
"prettier": "^3.2.5",
"ts-jest": "^29.0.3",
"tsd": "^0.31.0",
"typescript": "^5.0.4",
"typescript-eslint": "^8.12.2"
},
"types": "typings/index.d.ts",
"engines": {
"node": ">=18"
},
"support": true
}
@@ -0,0 +1,3 @@
// Just reexport the types from cjs
// This is a bit indirect. There is not an index.js, but TypeScript will look for index.d.ts for types.
export * from './index.js';
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
(The MIT License)
Copyright (c) 2011-2024 JP Richardson
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files
(the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+292
View File
@@ -0,0 +1,292 @@
Node.js: fs-extra
=================
`fs-extra` adds file system methods that aren't included in the native `fs` module and adds promise support to the `fs` methods. It also uses [`graceful-fs`](https://github.com/isaacs/node-graceful-fs) to prevent `EMFILE` errors. It should be a drop in replacement for `fs`.
[![npm Package](https://img.shields.io/npm/v/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![License](https://img.shields.io/npm/l/fs-extra.svg)](https://github.com/jprichardson/node-fs-extra/blob/master/LICENSE)
[![build status](https://img.shields.io/github/actions/workflow/status/jprichardson/node-fs-extra/ci.yml?branch=master)](https://github.com/jprichardson/node-fs-extra/actions/workflows/ci.yml?query=branch%3Amaster)
[![downloads per month](http://img.shields.io/npm/dm/fs-extra.svg)](https://www.npmjs.org/package/fs-extra)
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
Why?
----
I got tired of including `mkdirp`, `rimraf`, and `ncp` in most of my projects.
Installation
------------
npm install fs-extra
Usage
-----
### CommonJS
`fs-extra` is a drop in replacement for native `fs`. All methods in `fs` are attached to `fs-extra`. All `fs` methods return promises if the callback isn't passed.
You don't ever need to include the original `fs` module again:
```js
const fs = require('fs') // this is no longer necessary
```
you can now do this:
```js
const fs = require('fs-extra')
```
or if you prefer to make it clear that you're using `fs-extra` and not `fs`, you may want
to name your `fs` variable `fse` like so:
```js
const fse = require('fs-extra')
```
you can also keep both, but it's redundant:
```js
const fs = require('fs')
const fse = require('fs-extra')
```
### ESM
There is also an `fs-extra/esm` import, that supports both default and named exports. However, note that `fs` methods are not included in `fs-extra/esm`; you still need to import `fs` and/or `fs/promises` seperately:
```js
import { readFileSync } from 'fs'
import { readFile } from 'fs/promises'
import { outputFile, outputFileSync } from 'fs-extra/esm'
```
Default exports are supported:
```js
import fs from 'fs'
import fse from 'fs-extra/esm'
// fse.readFileSync is not a function; must use fs.readFileSync
```
but you probably want to just use regular `fs-extra` instead of `fs-extra/esm` for default exports:
```js
import fs from 'fs-extra'
// both fs and fs-extra methods are defined
```
Sync vs Async vs Async/Await
-------------
Most methods are async by default. All async methods will return a promise if the callback isn't passed.
Sync methods on the other hand will throw if an error occurs.
Also Async/Await will throw an error if one occurs.
Example:
```js
const fs = require('fs-extra')
// Async with promises:
fs.copy('/tmp/myfile', '/tmp/mynewfile')
.then(() => console.log('success!'))
.catch(err => console.error(err))
// Async with callbacks:
fs.copy('/tmp/myfile', '/tmp/mynewfile', err => {
if (err) return console.error(err)
console.log('success!')
})
// Sync:
try {
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
// Async/Await:
async function copyFiles () {
try {
await fs.copy('/tmp/myfile', '/tmp/mynewfile')
console.log('success!')
} catch (err) {
console.error(err)
}
}
copyFiles()
```
Methods
-------
### Async
- [copy](docs/copy.md)
- [emptyDir](docs/emptyDir.md)
- [ensureFile](docs/ensureFile.md)
- [ensureDir](docs/ensureDir.md)
- [ensureLink](docs/ensureLink.md)
- [ensureSymlink](docs/ensureSymlink.md)
- [mkdirp](docs/ensureDir.md)
- [mkdirs](docs/ensureDir.md)
- [move](docs/move.md)
- [outputFile](docs/outputFile.md)
- [outputJson](docs/outputJson.md)
- [pathExists](docs/pathExists.md)
- [readJson](docs/readJson.md)
- [remove](docs/remove.md)
- [writeJson](docs/writeJson.md)
### Sync
- [copySync](docs/copy-sync.md)
- [emptyDirSync](docs/emptyDir-sync.md)
- [ensureFileSync](docs/ensureFile-sync.md)
- [ensureDirSync](docs/ensureDir-sync.md)
- [ensureLinkSync](docs/ensureLink-sync.md)
- [ensureSymlinkSync](docs/ensureSymlink-sync.md)
- [mkdirpSync](docs/ensureDir-sync.md)
- [mkdirsSync](docs/ensureDir-sync.md)
- [moveSync](docs/move-sync.md)
- [outputFileSync](docs/outputFile-sync.md)
- [outputJsonSync](docs/outputJson-sync.md)
- [pathExistsSync](docs/pathExists-sync.md)
- [readJsonSync](docs/readJson-sync.md)
- [removeSync](docs/remove-sync.md)
- [writeJsonSync](docs/writeJson-sync.md)
**NOTE:** You can still use the native Node.js methods. They are promisified and copied over to `fs-extra`. See [notes on `fs.read()`, `fs.write()`, & `fs.writev()`](docs/fs-read-write-writev.md)
### What happened to `walk()` and `walkSync()`?
They were removed from `fs-extra` in v2.0.0. If you need the functionality, `walk` and `walkSync` are available as separate packages, [`klaw`](https://github.com/jprichardson/node-klaw) and [`klaw-sync`](https://github.com/manidlou/node-klaw-sync).
Third Party
-----------
### CLI
[fse-cli](https://www.npmjs.com/package/@atao60/fse-cli) allows you to run `fs-extra` from a console or from [npm](https://www.npmjs.com) scripts.
### TypeScript
If you like TypeScript, you can use `fs-extra` with it: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/fs-extra
### File / Directory Watching
If you want to watch for changes to files or directories, then you should use [chokidar](https://github.com/paulmillr/chokidar).
### Obtain Filesystem (Devices, Partitions) Information
[fs-filesystem](https://github.com/arthurintelligence/node-fs-filesystem) allows you to read the state of the filesystem of the host on which it is run. It returns information about both the devices and the partitions (volumes) of the system.
### Misc.
- [fs-extra-debug](https://github.com/jdxcode/fs-extra-debug) - Send your fs-extra calls to [debug](https://npmjs.org/package/debug).
- [mfs](https://github.com/cadorn/mfs) - Monitor your fs-extra calls.
Hacking on fs-extra
-------------------
Wanna hack on `fs-extra`? Great! Your help is needed! [fs-extra is one of the most depended upon Node.js packages](http://nodei.co/npm/fs-extra.png?downloads=true&downloadRank=true&stars=true). This project
uses [JavaScript Standard Style](https://github.com/feross/standard) - if the name or style choices bother you,
you're gonna have to get over it :) If `standard` is good enough for `npm`, it's good enough for `fs-extra`.
[![js-standard-style](https://cdn.rawgit.com/feross/standard/master/badge.svg)](https://github.com/feross/standard)
What's needed?
- First, take a look at existing issues. Those are probably going to be where the priority lies.
- More tests for edge cases. Specifically on different platforms. There can never be enough tests.
- Improve test coverage.
Note: If you make any big changes, **you should definitely file an issue for discussion first.**
### Running the Test Suite
fs-extra contains hundreds of tests.
- `npm run lint`: runs the linter ([standard](http://standardjs.com/))
- `npm run unit`: runs the unit tests
- `npm run unit-esm`: runs tests for `fs-extra/esm` exports
- `npm test`: runs the linter and all tests
When running unit tests, set the environment variable `CROSS_DEVICE_PATH` to the absolute path of an empty directory on another device (like a thumb drive) to enable cross-device move tests.
### Windows
If you run the tests on the Windows and receive a lot of symbolic link `EPERM` permission errors, it's
because on Windows you need elevated privilege to create symbolic links. You can add this to your Windows's
account by following the instructions here: http://superuser.com/questions/104845/permission-to-make-symbolic-links-in-windows-7
However, I didn't have much luck doing this.
Since I develop on Mac OS X, I use VMWare Fusion for Windows testing. I create a shared folder that I map to a drive on Windows.
I open the `Node.js command prompt` and run as `Administrator`. I then map the network drive running the following command:
net use z: "\\vmware-host\Shared Folders"
I can then navigate to my `fs-extra` directory and run the tests.
Naming
------
I put a lot of thought into the naming of these functions. Inspired by @coolaj86's request. So he deserves much of the credit for raising the issue. See discussion(s) here:
* https://github.com/jprichardson/node-fs-extra/issues/2
* https://github.com/flatiron/utile/issues/11
* https://github.com/ryanmcgrath/wrench-js/issues/29
* https://github.com/substack/node-mkdirp/issues/17
First, I believe that in as many cases as possible, the [Node.js naming schemes](http://nodejs.org/api/fs.html) should be chosen. However, there are problems with the Node.js own naming schemes.
For example, `fs.readFile()` and `fs.readdir()`: the **F** is capitalized in *File* and the **d** is not capitalized in *dir*. Perhaps a bit pedantic, but they should still be consistent. Also, Node.js has chosen a lot of POSIX naming schemes, which I believe is great. See: `fs.mkdir()`, `fs.rmdir()`, `fs.chown()`, etc.
We have a dilemma though. How do you consistently name methods that perform the following POSIX commands: `cp`, `cp -r`, `mkdir -p`, and `rm -rf`?
My perspective: when in doubt, err on the side of simplicity. A directory is just a hierarchical grouping of directories and files. Consider that for a moment. So when you want to copy it or remove it, in most cases you'll want to copy or remove all of its contents. When you want to create a directory, if the directory that it's suppose to be contained in does not exist, then in most cases you'll want to create that too.
So, if you want to remove a file or a directory regardless of whether it has contents, just call `fs.remove(path)`. If you want to copy a file or a directory whether it has contents, just call `fs.copy(source, destination)`. If you want to create a directory regardless of whether its parent directories exist, just call `fs.mkdirs(path)` or `fs.mkdirp(path)`.
Credit
------
`fs-extra` wouldn't be possible without using the modules from the following authors:
- [Isaac Shlueter](https://github.com/isaacs)
- [Charlie McConnel](https://github.com/avianflu)
- [James Halliday](https://github.com/substack)
- [Andrew Kelley](https://github.com/andrewrk)
License
-------
Licensed under MIT
Copyright (c) 2011-2024 [JP Richardson](https://github.com/jprichardson)
[1]: http://nodejs.org/docs/latest/api/fs.html
[jsonfile]: https://github.com/jprichardson/node-jsonfile
@@ -0,0 +1,171 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const mkdirsSync = require('../mkdirs').mkdirsSync
const utimesMillisSync = require('../util/utimes').utimesMillisSync
const stat = require('../util/stat')
function copySync (src, dest, opts) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts = opts || {}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0002'
)
}
const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'copy')
if (opts.filter && !opts.filter(src, dest)) return
const destParent = path.dirname(dest)
if (!fs.existsSync(destParent)) mkdirsSync(destParent)
return getStats(destStat, src, dest, opts)
}
function getStats (destStat, src, dest, opts) {
const statSync = opts.dereference ? fs.statSync : fs.lstatSync
const srcStat = statSync(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
else if (srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts)
else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
throw new Error(`Unknown file: ${src}`)
}
function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
return mayCopyFile(srcStat, src, dest, opts)
}
function mayCopyFile (srcStat, src, dest, opts) {
if (opts.overwrite) {
fs.unlinkSync(dest)
return copyFile(srcStat, src, dest, opts)
} else if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
function copyFile (srcStat, src, dest, opts) {
fs.copyFileSync(src, dest)
if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest)
return setDestMode(dest, srcStat.mode)
}
function handleTimestamps (srcMode, src, dest) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode)
return setDestTimestamps(src, dest)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return setDestMode(dest, srcMode | 0o200)
}
function setDestMode (dest, srcMode) {
return fs.chmodSync(dest, srcMode)
}
function setDestTimestamps (src, dest) {
// The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
const updatedSrcStat = fs.statSync(src)
return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
}
function onDir (srcStat, destStat, src, dest, opts) {
if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts)
return copyDir(src, dest, opts)
}
function mkDirAndCopy (srcMode, src, dest, opts) {
fs.mkdirSync(dest)
copyDir(src, dest, opts)
return setDestMode(dest, srcMode)
}
function copyDir (src, dest, opts) {
const dir = fs.opendirSync(src)
try {
let dirent
while ((dirent = dir.readSync()) !== null) {
copyDirItem(dirent.name, src, dest, opts)
}
} finally {
dir.closeSync()
}
}
function copyDirItem (item, src, dest, opts) {
const srcItem = path.join(src, item)
const destItem = path.join(dest, item)
if (opts.filter && !opts.filter(srcItem, destItem)) return
const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts)
return getStats(destStat, srcItem, destItem, opts)
}
function onLink (destStat, src, dest, opts) {
let resolvedSrc = fs.readlinkSync(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlinkSync(resolvedSrc, dest)
} else {
let resolvedDest
try {
resolvedDest = fs.readlinkSync(dest)
} catch (err) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest)
throw err
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// prevent copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
return copyLink(resolvedSrc, dest)
}
}
function copyLink (resolvedSrc, dest) {
fs.unlinkSync(dest)
return fs.symlinkSync(resolvedSrc, dest)
}
module.exports = copySync
@@ -0,0 +1,182 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const { mkdirs } = require('../mkdirs')
const { pathExists } = require('../path-exists')
const { utimesMillis } = require('../util/utimes')
const stat = require('../util/stat')
async function copy (src, dest, opts = {}) {
if (typeof opts === 'function') {
opts = { filter: opts }
}
opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
// Warn about using preserveTimestamps on 32-bit node
if (opts.preserveTimestamps && process.arch === 'ia32') {
process.emitWarning(
'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
'\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
'Warning', 'fs-extra-WARN0001'
)
}
const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts)
await stat.checkParentPaths(src, srcStat, dest, 'copy')
const include = await runFilter(src, dest, opts)
if (!include) return
// check if the parent of dest exists, and create it if it doesn't exist
const destParent = path.dirname(dest)
const dirExists = await pathExists(destParent)
if (!dirExists) {
await mkdirs(destParent)
}
await getStatsAndPerformCopy(destStat, src, dest, opts)
}
async function runFilter (src, dest, opts) {
if (!opts.filter) return true
return opts.filter(src, dest)
}
async function getStatsAndPerformCopy (destStat, src, dest, opts) {
const statFn = opts.dereference ? fs.stat : fs.lstat
const srcStat = await statFn(src)
if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
if (
srcStat.isFile() ||
srcStat.isCharacterDevice() ||
srcStat.isBlockDevice()
) return onFile(srcStat, destStat, src, dest, opts)
if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
throw new Error(`Unknown file: ${src}`)
}
async function onFile (srcStat, destStat, src, dest, opts) {
if (!destStat) return copyFile(srcStat, src, dest, opts)
if (opts.overwrite) {
await fs.unlink(dest)
return copyFile(srcStat, src, dest, opts)
}
if (opts.errorOnExist) {
throw new Error(`'${dest}' already exists`)
}
}
async function copyFile (srcStat, src, dest, opts) {
await fs.copyFile(src, dest)
if (opts.preserveTimestamps) {
// Make sure the file is writable before setting the timestamp
// otherwise open fails with EPERM when invoked with 'r+'
// (through utimes call)
if (fileIsNotWritable(srcStat.mode)) {
await makeFileWritable(dest, srcStat.mode)
}
// Set timestamps and mode correspondingly
// Note that The initial srcStat.atime cannot be trusted
// because it is modified by the read(2) system call
// (See https://nodejs.org/api/fs.html#fs_stat_time_values)
const updatedSrcStat = await fs.stat(src)
await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
}
return fs.chmod(dest, srcStat.mode)
}
function fileIsNotWritable (srcMode) {
return (srcMode & 0o200) === 0
}
function makeFileWritable (dest, srcMode) {
return fs.chmod(dest, srcMode | 0o200)
}
async function onDir (srcStat, destStat, src, dest, opts) {
// the dest directory might not exist, create it
if (!destStat) {
await fs.mkdir(dest)
}
const promises = []
// loop through the files in the current directory to copy everything
for await (const item of await fs.opendir(src)) {
const srcItem = path.join(src, item.name)
const destItem = path.join(dest, item.name)
promises.push(
runFilter(srcItem, destItem, opts).then(include => {
if (include) {
// only copy the item if it matches the filter function
return stat.checkPaths(srcItem, destItem, 'copy', opts).then(({ destStat }) => {
// If the item is a copyable file, `getStatsAndPerformCopy` will copy it
// If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
return getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
})
}
})
)
}
await Promise.all(promises)
if (!destStat) {
await fs.chmod(dest, srcStat.mode)
}
}
async function onLink (destStat, src, dest, opts) {
let resolvedSrc = await fs.readlink(src)
if (opts.dereference) {
resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
}
if (!destStat) {
return fs.symlink(resolvedSrc, dest)
}
let resolvedDest = null
try {
resolvedDest = await fs.readlink(dest)
} catch (e) {
// dest exists and is a regular file or directory,
// Windows may throw UNKNOWN error. If dest already exists,
// fs throws error anyway, so no need to guard against it here.
if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)
throw e
}
if (opts.dereference) {
resolvedDest = path.resolve(process.cwd(), resolvedDest)
}
if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
}
// do not copy if src is a subdir of dest since unlinking
// dest in this case would result in removing src contents
// and therefore a broken symlink would be created.
if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
}
// copy the link
await fs.unlink(dest)
return fs.symlink(resolvedSrc, dest)
}
module.exports = copy
@@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromPromise
module.exports = {
copy: u(require('./copy')),
copySync: require('./copy-sync')
}
@@ -0,0 +1,39 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const remove = require('../remove')
const emptyDir = u(async function emptyDir (dir) {
let items
try {
items = await fs.readdir(dir)
} catch {
return mkdir.mkdirs(dir)
}
return Promise.all(items.map(item => remove.remove(path.join(dir, item))))
})
function emptyDirSync (dir) {
let items
try {
items = fs.readdirSync(dir)
} catch {
return mkdir.mkdirsSync(dir)
}
items.forEach(item => {
item = path.join(dir, item)
remove.removeSync(item)
})
}
module.exports = {
emptyDirSync,
emptydirSync: emptyDirSync,
emptyDir,
emptydir: emptyDir
}
@@ -0,0 +1,66 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const mkdir = require('../mkdirs')
async function createFile (file) {
let stats
try {
stats = await fs.stat(file)
} catch { }
if (stats && stats.isFile()) return
const dir = path.dirname(file)
let dirStats = null
try {
dirStats = await fs.stat(dir)
} catch (err) {
// if the directory doesn't exist, make it
if (err.code === 'ENOENT') {
await mkdir.mkdirs(dir)
await fs.writeFile(file, '')
return
} else {
throw err
}
}
if (dirStats.isDirectory()) {
await fs.writeFile(file, '')
} else {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
await fs.readdir(dir)
}
}
function createFileSync (file) {
let stats
try {
stats = fs.statSync(file)
} catch { }
if (stats && stats.isFile()) return
const dir = path.dirname(file)
try {
if (!fs.statSync(dir).isDirectory()) {
// parent is not a directory
// This is just to cause an internal ENOTDIR error to be thrown
fs.readdirSync(dir)
}
} catch (err) {
// If the stat call above failed because the directory doesn't exist, create it
if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir)
else throw err
}
fs.writeFileSync(file, '')
}
module.exports = {
createFile: u(createFile),
createFileSync
}
@@ -0,0 +1,23 @@
'use strict'
const { createFile, createFileSync } = require('./file')
const { createLink, createLinkSync } = require('./link')
const { createSymlink, createSymlinkSync } = require('./symlink')
module.exports = {
// file
createFile,
createFileSync,
ensureFile: createFile,
ensureFileSync: createFileSync,
// link
createLink,
createLinkSync,
ensureLink: createLink,
ensureLinkSync: createLinkSync,
// symlink
createSymlink,
createSymlinkSync,
ensureSymlink: createSymlink,
ensureSymlinkSync: createSymlinkSync
}
@@ -0,0 +1,64 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const mkdir = require('../mkdirs')
const { pathExists } = require('../path-exists')
const { areIdentical } = require('../util/stat')
async function createLink (srcpath, dstpath) {
let dstStat
try {
dstStat = await fs.lstat(dstpath)
} catch {
// ignore error
}
let srcStat
try {
srcStat = await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
if (dstStat && areIdentical(srcStat, dstStat)) return
const dir = path.dirname(dstpath)
const dirExists = await pathExists(dir)
if (!dirExists) {
await mkdir.mkdirs(dir)
}
await fs.link(srcpath, dstpath)
}
function createLinkSync (srcpath, dstpath) {
let dstStat
try {
dstStat = fs.lstatSync(dstpath)
} catch {}
try {
const srcStat = fs.lstatSync(srcpath)
if (dstStat && areIdentical(srcStat, dstStat)) return
} catch (err) {
err.message = err.message.replace('lstat', 'ensureLink')
throw err
}
const dir = path.dirname(dstpath)
const dirExists = fs.existsSync(dir)
if (dirExists) return fs.linkSync(srcpath, dstpath)
mkdir.mkdirsSync(dir)
return fs.linkSync(srcpath, dstpath)
}
module.exports = {
createLink: u(createLink),
createLinkSync
}
@@ -0,0 +1,101 @@
'use strict'
const path = require('path')
const fs = require('../fs')
const { pathExists } = require('../path-exists')
const u = require('universalify').fromPromise
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
async function symlinkPaths (srcpath, dstpath) {
if (path.isAbsolute(srcpath)) {
try {
await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
throw err
}
return {
toCwd: srcpath,
toDst: srcpath
}
}
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
const exists = await pathExists(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
}
try {
await fs.lstat(srcpath)
} catch (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
throw err
}
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
function symlinkPathsSync (srcpath, dstpath) {
if (path.isAbsolute(srcpath)) {
const exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
toCwd: srcpath,
toDst: srcpath
}
}
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
const exists = fs.existsSync(relativeToDst)
if (exists) {
return {
toCwd: relativeToDst,
toDst: srcpath
}
}
const srcExists = fs.existsSync(srcpath)
if (!srcExists) throw new Error('relative srcpath does not exist')
return {
toCwd: srcpath,
toDst: path.relative(dstdir, srcpath)
}
}
module.exports = {
symlinkPaths: u(symlinkPaths),
symlinkPathsSync
}
@@ -0,0 +1,34 @@
'use strict'
const fs = require('../fs')
const u = require('universalify').fromPromise
async function symlinkType (srcpath, type) {
if (type) return type
let stats
try {
stats = await fs.lstat(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
function symlinkTypeSync (srcpath, type) {
if (type) return type
let stats
try {
stats = fs.lstatSync(srcpath)
} catch {
return 'file'
}
return (stats && stats.isDirectory()) ? 'dir' : 'file'
}
module.exports = {
symlinkType: u(symlinkType),
symlinkTypeSync
}
@@ -0,0 +1,67 @@
'use strict'
const u = require('universalify').fromPromise
const path = require('path')
const fs = require('../fs')
const { mkdirs, mkdirsSync } = require('../mkdirs')
const { symlinkPaths, symlinkPathsSync } = require('./symlink-paths')
const { symlinkType, symlinkTypeSync } = require('./symlink-type')
const { pathExists } = require('../path-exists')
const { areIdentical } = require('../util/stat')
async function createSymlink (srcpath, dstpath, type) {
let stats
try {
stats = await fs.lstat(dstpath)
} catch { }
if (stats && stats.isSymbolicLink()) {
const [srcStat, dstStat] = await Promise.all([
fs.stat(srcpath),
fs.stat(dstpath)
])
if (areIdentical(srcStat, dstStat)) return
}
const relative = await symlinkPaths(srcpath, dstpath)
srcpath = relative.toDst
const toType = await symlinkType(relative.toCwd, type)
const dir = path.dirname(dstpath)
if (!(await pathExists(dir))) {
await mkdirs(dir)
}
return fs.symlink(srcpath, dstpath, toType)
}
function createSymlinkSync (srcpath, dstpath, type) {
let stats
try {
stats = fs.lstatSync(dstpath)
} catch { }
if (stats && stats.isSymbolicLink()) {
const srcStat = fs.statSync(srcpath)
const dstStat = fs.statSync(dstpath)
if (areIdentical(srcStat, dstStat)) return
}
const relative = symlinkPathsSync(srcpath, dstpath)
srcpath = relative.toDst
type = symlinkTypeSync(relative.toCwd, type)
const dir = path.dirname(dstpath)
const exists = fs.existsSync(dir)
if (exists) return fs.symlinkSync(srcpath, dstpath, type)
mkdirsSync(dir)
return fs.symlinkSync(srcpath, dstpath, type)
}
module.exports = {
createSymlink: u(createSymlink),
createSymlinkSync
}
@@ -0,0 +1,68 @@
import _copy from './copy/index.js'
import _empty from './empty/index.js'
import _ensure from './ensure/index.js'
import _json from './json/index.js'
import _mkdirs from './mkdirs/index.js'
import _move from './move/index.js'
import _outputFile from './output-file/index.js'
import _pathExists from './path-exists/index.js'
import _remove from './remove/index.js'
// NOTE: Only exports fs-extra's functions; fs functions must be imported from "node:fs" or "node:fs/promises"
export const copy = _copy.copy
export const copySync = _copy.copySync
export const emptyDirSync = _empty.emptyDirSync
export const emptydirSync = _empty.emptydirSync
export const emptyDir = _empty.emptyDir
export const emptydir = _empty.emptydir
export const createFile = _ensure.createFile
export const createFileSync = _ensure.createFileSync
export const ensureFile = _ensure.ensureFile
export const ensureFileSync = _ensure.ensureFileSync
export const createLink = _ensure.createLink
export const createLinkSync = _ensure.createLinkSync
export const ensureLink = _ensure.ensureLink
export const ensureLinkSync = _ensure.ensureLinkSync
export const createSymlink = _ensure.createSymlink
export const createSymlinkSync = _ensure.createSymlinkSync
export const ensureSymlink = _ensure.ensureSymlink
export const ensureSymlinkSync = _ensure.ensureSymlinkSync
export const readJson = _json.readJson
export const readJSON = _json.readJSON
export const readJsonSync = _json.readJsonSync
export const readJSONSync = _json.readJSONSync
export const writeJson = _json.writeJson
export const writeJSON = _json.writeJSON
export const writeJsonSync = _json.writeJsonSync
export const writeJSONSync = _json.writeJSONSync
export const outputJson = _json.outputJson
export const outputJSON = _json.outputJSON
export const outputJsonSync = _json.outputJsonSync
export const outputJSONSync = _json.outputJSONSync
export const mkdirs = _mkdirs.mkdirs
export const mkdirsSync = _mkdirs.mkdirsSync
export const mkdirp = _mkdirs.mkdirp
export const mkdirpSync = _mkdirs.mkdirpSync
export const ensureDir = _mkdirs.ensureDir
export const ensureDirSync = _mkdirs.ensureDirSync
export const move = _move.move
export const moveSync = _move.moveSync
export const outputFile = _outputFile.outputFile
export const outputFileSync = _outputFile.outputFileSync
export const pathExists = _pathExists.pathExists
export const pathExistsSync = _pathExists.pathExistsSync
export const remove = _remove.remove
export const removeSync = _remove.removeSync
export default {
..._copy,
..._empty,
..._ensure,
..._json,
..._mkdirs,
..._move,
..._outputFile,
..._pathExists,
..._remove
}
@@ -0,0 +1,146 @@
'use strict'
// This is adapted from https://github.com/normalize/mz
// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors
const u = require('universalify').fromCallback
const fs = require('graceful-fs')
const api = [
'access',
'appendFile',
'chmod',
'chown',
'close',
'copyFile',
'cp',
'fchmod',
'fchown',
'fdatasync',
'fstat',
'fsync',
'ftruncate',
'futimes',
'glob',
'lchmod',
'lchown',
'lutimes',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'opendir',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rm',
'rmdir',
'stat',
'statfs',
'symlink',
'truncate',
'unlink',
'utimes',
'writeFile'
].filter(key => {
// Some commands are not available on some systems. Ex:
// fs.cp was added in Node.js v16.7.0
// fs.statfs was added in Node v19.6.0, v18.15.0
// fs.glob was added in Node.js v22.0.0
// fs.lchown is not available on at least some Linux
return typeof fs[key] === 'function'
})
// Export cloned fs:
Object.assign(exports, fs)
// Universalify async methods:
api.forEach(method => {
exports[method] = u(fs[method])
})
// We differ from mz/fs in that we still ship the old, broken, fs.exists()
// since we are a drop-in replacement for the native module
exports.exists = function (filename, callback) {
if (typeof callback === 'function') {
return fs.exists(filename, callback)
}
return new Promise(resolve => {
return fs.exists(filename, resolve)
})
}
// fs.read(), fs.write(), fs.readv(), & fs.writev() need special treatment due to multiple callback args
exports.read = function (fd, buffer, offset, length, position, callback) {
if (typeof callback === 'function') {
return fs.read(fd, buffer, offset, length, position, callback)
}
return new Promise((resolve, reject) => {
fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => {
if (err) return reject(err)
resolve({ bytesRead, buffer })
})
})
}
// Function signature can be
// fs.write(fd, buffer[, offset[, length[, position]]], callback)
// OR
// fs.write(fd, string[, position[, encoding]], callback)
// We need to handle both cases, so we use ...args
exports.write = function (fd, buffer, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.write(fd, buffer, ...args)
}
return new Promise((resolve, reject) => {
fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => {
if (err) return reject(err)
resolve({ bytesWritten, buffer })
})
})
}
// Function signature is
// s.readv(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.readv = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.readv(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.readv(fd, buffers, ...args, (err, bytesRead, buffers) => {
if (err) return reject(err)
resolve({ bytesRead, buffers })
})
})
}
// Function signature is
// s.writev(fd, buffers[, position], callback)
// We need to handle the optional arg, so we use ...args
exports.writev = function (fd, buffers, ...args) {
if (typeof args[args.length - 1] === 'function') {
return fs.writev(fd, buffers, ...args)
}
return new Promise((resolve, reject) => {
fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => {
if (err) return reject(err)
resolve({ bytesWritten, buffers })
})
})
}
// fs.realpath.native sometimes not available if fs is monkey-patched
if (typeof fs.realpath.native === 'function') {
exports.realpath.native = u(fs.realpath.native)
} else {
process.emitWarning(
'fs.realpath.native is not a function. Is fs being monkey-patched?',
'Warning', 'fs-extra-WARN0003'
)
}
@@ -0,0 +1,16 @@
'use strict'
module.exports = {
// Export promiseified graceful-fs:
...require('./fs'),
// Export extra methods:
...require('./copy'),
...require('./empty'),
...require('./ensure'),
...require('./json'),
...require('./mkdirs'),
...require('./move'),
...require('./output-file'),
...require('./path-exists'),
...require('./remove')
}
@@ -0,0 +1,16 @@
'use strict'
const u = require('universalify').fromPromise
const jsonFile = require('./jsonfile')
jsonFile.outputJson = u(require('./output-json'))
jsonFile.outputJsonSync = require('./output-json-sync')
// aliases
jsonFile.outputJSON = jsonFile.outputJson
jsonFile.outputJSONSync = jsonFile.outputJsonSync
jsonFile.writeJSON = jsonFile.writeJson
jsonFile.writeJSONSync = jsonFile.writeJsonSync
jsonFile.readJSON = jsonFile.readJson
jsonFile.readJSONSync = jsonFile.readJsonSync
module.exports = jsonFile
@@ -0,0 +1,11 @@
'use strict'
const jsonFile = require('jsonfile')
module.exports = {
// jsonfile exports
readJson: jsonFile.readFile,
readJsonSync: jsonFile.readFileSync,
writeJson: jsonFile.writeFile,
writeJsonSync: jsonFile.writeFileSync
}
@@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFileSync } = require('../output-file')
function outputJsonSync (file, data, options) {
const str = stringify(data, options)
outputFileSync(file, str, options)
}
module.exports = outputJsonSync
@@ -0,0 +1,12 @@
'use strict'
const { stringify } = require('jsonfile/utils')
const { outputFile } = require('../output-file')
async function outputJson (file, data, options = {}) {
const str = stringify(data, options)
await outputFile(file, str, options)
}
module.exports = outputJson
@@ -0,0 +1,14 @@
'use strict'
const u = require('universalify').fromPromise
const { makeDir: _makeDir, makeDirSync } = require('./make-dir')
const makeDir = u(_makeDir)
module.exports = {
mkdirs: makeDir,
mkdirsSync: makeDirSync,
// alias
mkdirp: makeDir,
mkdirpSync: makeDirSync,
ensureDir: makeDir,
ensureDirSync: makeDirSync
}
@@ -0,0 +1,27 @@
'use strict'
const fs = require('../fs')
const { checkPath } = require('./utils')
const getMode = options => {
const defaults = { mode: 0o777 }
if (typeof options === 'number') return options
return ({ ...defaults, ...options }).mode
}
module.exports.makeDir = async (dir, options) => {
checkPath(dir)
return fs.mkdir(dir, {
mode: getMode(options),
recursive: true
})
}
module.exports.makeDirSync = (dir, options) => {
checkPath(dir)
return fs.mkdirSync(dir, {
mode: getMode(options),
recursive: true
})
}
@@ -0,0 +1,21 @@
// Adapted from https://github.com/sindresorhus/make-dir
// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'
const path = require('path')
// https://github.com/nodejs/node/issues/8987
// https://github.com/libuv/libuv/pull/1088
module.exports.checkPath = function checkPath (pth) {
if (process.platform === 'win32') {
const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, ''))
if (pathHasInvalidWinCharacters) {
const error = new Error(`Path contains invalid characters: ${pth}`)
error.code = 'EINVAL'
throw error
}
}
}
@@ -0,0 +1,7 @@
'use strict'
const u = require('universalify').fromPromise
module.exports = {
move: u(require('./move')),
moveSync: require('./move-sync')
}
@@ -0,0 +1,55 @@
'use strict'
const fs = require('graceful-fs')
const path = require('path')
const copySync = require('../copy').copySync
const removeSync = require('../remove').removeSync
const mkdirpSync = require('../mkdirs').mkdirpSync
const stat = require('../util/stat')
function moveSync (src, dest, opts) {
opts = opts || {}
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts)
stat.checkParentPathsSync(src, srcStat, dest, 'move')
if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest))
return doRename(src, dest, overwrite, isChangingCase)
}
function isParentRoot (dest) {
const parent = path.dirname(dest)
const parsedPath = path.parse(parent)
return parsedPath.root === parent
}
function doRename (src, dest, overwrite, isChangingCase) {
if (isChangingCase) return rename(src, dest, overwrite)
if (overwrite) {
removeSync(dest)
return rename(src, dest, overwrite)
}
if (fs.existsSync(dest)) throw new Error('dest already exists.')
return rename(src, dest, overwrite)
}
function rename (src, dest, overwrite) {
try {
fs.renameSync(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') throw err
return moveAcrossDevice(src, dest, overwrite)
}
}
function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true,
preserveTimestamps: true
}
copySync(src, dest, opts)
return removeSync(src)
}
module.exports = moveSync
@@ -0,0 +1,59 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const { copy } = require('../copy')
const { remove } = require('../remove')
const { mkdirp } = require('../mkdirs')
const { pathExists } = require('../path-exists')
const stat = require('../util/stat')
async function move (src, dest, opts = {}) {
const overwrite = opts.overwrite || opts.clobber || false
const { srcStat, isChangingCase = false } = await stat.checkPaths(src, dest, 'move', opts)
await stat.checkParentPaths(src, srcStat, dest, 'move')
// If the parent of dest is not root, make sure it exists before proceeding
const destParent = path.dirname(dest)
const parsedParentPath = path.parse(destParent)
if (parsedParentPath.root !== destParent) {
await mkdirp(destParent)
}
return doRename(src, dest, overwrite, isChangingCase)
}
async function doRename (src, dest, overwrite, isChangingCase) {
if (!isChangingCase) {
if (overwrite) {
await remove(dest)
} else if (await pathExists(dest)) {
throw new Error('dest already exists.')
}
}
try {
// Try w/ rename first, and try copy + remove if EXDEV
await fs.rename(src, dest)
} catch (err) {
if (err.code !== 'EXDEV') {
throw err
}
await moveAcrossDevice(src, dest, overwrite)
}
}
async function moveAcrossDevice (src, dest, overwrite) {
const opts = {
overwrite,
errorOnExist: true,
preserveTimestamps: true
}
await copy(src, dest, opts)
return remove(src)
}
module.exports = move
@@ -0,0 +1,31 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
const path = require('path')
const mkdir = require('../mkdirs')
const pathExists = require('../path-exists').pathExists
async function outputFile (file, data, encoding = 'utf-8') {
const dir = path.dirname(file)
if (!(await pathExists(dir))) {
await mkdir.mkdirs(dir)
}
return fs.writeFile(file, data, encoding)
}
function outputFileSync (file, ...args) {
const dir = path.dirname(file)
if (!fs.existsSync(dir)) {
mkdir.mkdirsSync(dir)
}
fs.writeFileSync(file, ...args)
}
module.exports = {
outputFile: u(outputFile),
outputFileSync
}
@@ -0,0 +1,12 @@
'use strict'
const u = require('universalify').fromPromise
const fs = require('../fs')
function pathExists (path) {
return fs.access(path).then(() => true).catch(() => false)
}
module.exports = {
pathExists: u(pathExists),
pathExistsSync: fs.existsSync
}
@@ -0,0 +1,17 @@
'use strict'
const fs = require('graceful-fs')
const u = require('universalify').fromCallback
function remove (path, callback) {
fs.rm(path, { recursive: true, force: true }, callback)
}
function removeSync (path) {
fs.rmSync(path, { recursive: true, force: true })
}
module.exports = {
remove: u(remove),
removeSync
}
@@ -0,0 +1,158 @@
'use strict'
const fs = require('../fs')
const path = require('path')
const u = require('universalify').fromPromise
function getStats (src, dest, opts) {
const statFunc = opts.dereference
? (file) => fs.stat(file, { bigint: true })
: (file) => fs.lstat(file, { bigint: true })
return Promise.all([
statFunc(src),
statFunc(dest).catch(err => {
if (err.code === 'ENOENT') return null
throw err
})
]).then(([srcStat, destStat]) => ({ srcStat, destStat }))
}
function getStatsSync (src, dest, opts) {
let destStat
const statFunc = opts.dereference
? (file) => fs.statSync(file, { bigint: true })
: (file) => fs.lstatSync(file, { bigint: true })
const srcStat = statFunc(src)
try {
destStat = statFunc(dest)
} catch (err) {
if (err.code === 'ENOENT') return { srcStat, destStat: null }
throw err
}
return { srcStat, destStat }
}
async function checkPaths (src, dest, funcName, opts) {
const { srcStat, destStat } = await getStats(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
function checkPathsSync (src, dest, funcName, opts) {
const { srcStat, destStat } = getStatsSync(src, dest, opts)
if (destStat) {
if (areIdentical(srcStat, destStat)) {
const srcBaseName = path.basename(src)
const destBaseName = path.basename(dest)
if (funcName === 'move' &&
srcBaseName !== destBaseName &&
srcBaseName.toLowerCase() === destBaseName.toLowerCase()) {
return { srcStat, destStat, isChangingCase: true }
}
throw new Error('Source and destination must not be the same.')
}
if (srcStat.isDirectory() && !destStat.isDirectory()) {
throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
}
if (!srcStat.isDirectory() && destStat.isDirectory()) {
throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)
}
}
if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
throw new Error(errMsg(src, dest, funcName))
}
return { srcStat, destStat }
}
// recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
async function checkParentPaths (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = await fs.stat(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPaths(src, srcStat, destParent, funcName)
}
function checkParentPathsSync (src, srcStat, dest, funcName) {
const srcParent = path.resolve(path.dirname(src))
const destParent = path.resolve(path.dirname(dest))
if (destParent === srcParent || destParent === path.parse(destParent).root) return
let destStat
try {
destStat = fs.statSync(destParent, { bigint: true })
} catch (err) {
if (err.code === 'ENOENT') return
throw err
}
if (areIdentical(srcStat, destStat)) {
throw new Error(errMsg(src, dest, funcName))
}
return checkParentPathsSync(src, srcStat, destParent, funcName)
}
function areIdentical (srcStat, destStat) {
return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev
}
// return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir (src, dest) {
const srcArr = path.resolve(src).split(path.sep).filter(i => i)
const destArr = path.resolve(dest).split(path.sep).filter(i => i)
return srcArr.every((cur, i) => destArr[i] === cur)
}
function errMsg (src, dest, funcName) {
return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.`
}
module.exports = {
// checkPaths
checkPaths: u(checkPaths),
checkPathsSync,
// checkParent
checkParentPaths: u(checkParentPaths),
checkParentPathsSync,
// Misc
isSrcSubdir,
areIdentical
}
@@ -0,0 +1,36 @@
'use strict'
const fs = require('../fs')
const u = require('universalify').fromPromise
async function utimesMillis (path, atime, mtime) {
// if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback)
const fd = await fs.open(path, 'r+')
let closeErr = null
try {
await fs.futimes(fd, atime, mtime)
} finally {
try {
await fs.close(fd)
} catch (e) {
closeErr = e
}
}
if (closeErr) {
throw closeErr
}
}
function utimesMillisSync (path, atime, mtime) {
const fd = fs.openSync(path, 'r+')
fs.futimesSync(fd, atime, mtime)
return fs.closeSync(fd)
}
module.exports = {
utimesMillis: u(utimesMillis),
utimesMillisSync
}
@@ -0,0 +1,71 @@
{
"name": "fs-extra",
"version": "11.3.0",
"description": "fs-extra contains methods that aren't included in the vanilla Node.js fs package. Such as recursive mkdir, copy, and remove.",
"engines": {
"node": ">=14.14"
},
"homepage": "https://github.com/jprichardson/node-fs-extra",
"repository": {
"type": "git",
"url": "https://github.com/jprichardson/node-fs-extra"
},
"keywords": [
"fs",
"file",
"file system",
"copy",
"directory",
"extra",
"mkdirp",
"mkdir",
"mkdirs",
"recursive",
"json",
"read",
"write",
"extra",
"delete",
"remove",
"touch",
"create",
"text",
"output",
"move",
"promise"
],
"author": "JP Richardson <jprichardson@gmail.com>",
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^6.0.1",
"universalify": "^2.0.0"
},
"devDependencies": {
"klaw": "^2.1.1",
"klaw-sync": "^3.0.2",
"minimist": "^1.1.1",
"mocha": "^10.1.0",
"nyc": "^15.0.0",
"proxyquire": "^2.0.1",
"read-dir-files": "^0.1.1",
"standard": "^17.0.0"
},
"main": "./lib/index.js",
"exports": {
".": "./lib/index.js",
"./esm": "./lib/esm.mjs"
},
"files": [
"lib/",
"!lib/**/__tests__/"
],
"scripts": {
"lint": "standard",
"test-find": "find ./lib/**/__tests__ -name *.test.js | xargs mocha",
"test": "npm run lint && npm run unit && npm run unit-esm",
"unit": "nyc node test.js",
"unit-esm": "node test.mjs"
},
"sideEffects": false
}
+25
View File
@@ -0,0 +1,25 @@
'use strict';
const os = require('os');
const fs = require('fs');
const isWsl = () => {
if (process.platform !== 'linux') {
return false;
}
if (os.release().includes('Microsoft')) {
return true;
}
try {
return fs.readFileSync('/proc/version', 'utf8').includes('Microsoft');
} catch (err) {
return false;
}
};
if (process.env.__IS_WSL_TEST__) {
module.exports = isWsl;
} else {
module.exports = isWsl();
}
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,40 @@
{
"name": "is-wsl",
"version": "1.1.0",
"description": "Check if the process is running inside Windows Subsystem for Linux (Bash on Windows)",
"license": "MIT",
"repository": "sindresorhus/is-wsl",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=4"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js"
],
"keywords": [
"check",
"wsl",
"windows",
"subsystem",
"linux",
"detect",
"bash",
"process",
"console",
"terminal",
"is"
],
"devDependencies": {
"ava": "*",
"clear-require": "^2.0.0",
"proxyquire": "^1.7.11",
"xo": "*"
}
}
+28
View File
@@ -0,0 +1,28 @@
# is-wsl [![Build Status](https://travis-ci.org/sindresorhus/is-wsl.svg?branch=master)](https://travis-ci.org/sindresorhus/is-wsl)
> Check if the process is running inside [Windows Subsystem for Linux](https://msdn.microsoft.com/commandline/wsl/about) (Bash on Windows)
Can be useful if you need to work around unimplemented or buggy features in WSL.
## Install
```
$ npm install --save is-wsl
```
## Usage
```js
const isWsl = require('is-wsl');
// When running inside Windows Subsystem for Linux
console.log(isWsl);
//=> true
```
## License
MIT © [Sindre Sorhus](https://sindresorhus.com)
+70
View File
@@ -0,0 +1,70 @@
/// <reference types="node"/>
import {ChildProcess} from 'child_process';
declare namespace open {
interface Options {
/**
Wait for the opened app to exit before fulfilling the promise. If `false` it's fulfilled immediately when opening the app.
Note that it waits for the app to exit, not just for the window to close.
On Windows, you have to explicitly specify an app for it to be able to wait.
@default false
*/
readonly wait?: boolean;
/**
__macOS only__
Do not bring the app to the foreground.
@default false
*/
readonly background?: boolean;
/**
Specify the app to open the `target` with, or an array with the app and app arguments.
The app name is platform dependent. Don't hard code it in reusable modules. For example, Chrome is `google chrome` on macOS, `google-chrome` on Linux and `chrome` on Windows.
You may also pass in the app's full path. For example on WSL, this can be `/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe` for the Windows installation of Chrome.
*/
readonly app?: string | readonly string[];
}
}
/**
Open stuff like URLs, files, executables. Cross-platform.
Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms.
@param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser.
@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.
@example
```
import open = require('open');
// Opens the image in the default image viewer
(async () => {
await open('unicorn.png', {wait: true});
console.log('The image viewer app closed');
// Opens the url in the default browser
await open('https://sindresorhus.com');
// Specify the app to open in
await open('https://sindresorhus.com', {app: 'firefox'});
// Specify app arguments
await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();
```
*/
declare function open(
target: string,
options?: open.Options
): Promise<ChildProcess>;
export = open;
+134
View File
@@ -0,0 +1,134 @@
'use strict';
const {promisify} = require('util');
const path = require('path');
const childProcess = require('child_process');
const fs = require('fs');
const isWsl = require('is-wsl');
const pAccess = promisify(fs.access);
const pExecFile = promisify(childProcess.execFile);
// Path to included `xdg-open`
const localXdgOpenPath = path.join(__dirname, 'xdg-open');
// Convert a path from WSL format to Windows format:
// `/mnt/c/Program Files/Example/MyApp.exe` → `C:\Program Files\Example\MyApp.exe`
const wslToWindowsPath = async path => {
const {stdout} = await pExecFile('wslpath', ['-w', path]);
return stdout.trim();
};
module.exports = async (target, options) => {
if (typeof target !== 'string') {
throw new TypeError('Expected a `target`');
}
options = {
wait: false,
background: false,
...options
};
let command;
let appArguments = [];
const cliArguments = [];
const childProcessOptions = {};
if (Array.isArray(options.app)) {
appArguments = options.app.slice(1);
options.app = options.app[0];
}
if (process.platform === 'darwin') {
command = 'open';
if (options.wait) {
cliArguments.push('--wait-apps');
}
if (options.background) {
cliArguments.push('--background');
}
if (options.app) {
cliArguments.push('-a', options.app);
}
} else if (process.platform === 'win32' || isWsl) {
command = 'cmd' + (isWsl ? '.exe' : '');
cliArguments.push('/c', 'start', '""', '/b');
target = target.replace(/&/g, '^&');
if (options.wait) {
cliArguments.push('/wait');
}
if (options.app) {
if (isWsl && options.app.startsWith('/mnt/')) {
const windowsPath = await wslToWindowsPath(options.app);
options.app = windowsPath;
}
cliArguments.push(options.app);
}
if (appArguments.length > 0) {
cliArguments.push(...appArguments);
}
} else {
if (options.app) {
command = options.app;
} else {
// When bundled by Webpack, there's no actual package file path and no local `xdg-open`.
const isBundled = !__dirname || __dirname === '/';
// Check if local `xdg-open` exists and is executable.
let exeLocalXdgOpen = false;
try {
await pAccess(localXdgOpenPath, fs.constants.X_OK);
exeLocalXdgOpen = true;
} catch (error) {}
const useSystemXdgOpen = process.versions.electron ||
process.platform === 'android' || isBundled || !exeLocalXdgOpen;
command = useSystemXdgOpen ? 'xdg-open' : localXdgOpenPath;
}
if (appArguments.length > 0) {
cliArguments.push(...appArguments);
}
if (!options.wait) {
// `xdg-open` will block the process unless stdio is ignored
// and it's detached from the parent even if it's unref'd.
childProcessOptions.stdio = 'ignore';
childProcessOptions.detached = true;
}
}
cliArguments.push(target);
if (process.platform === 'darwin' && appArguments.length > 0) {
cliArguments.push('--args', ...appArguments);
}
const subprocess = childProcess.spawn(command, cliArguments, childProcessOptions);
if (options.wait) {
return new Promise((resolve, reject) => {
subprocess.once('error', reject);
subprocess.once('close', exitCode => {
if (exitCode > 0) {
reject(new Error(`Exited with code ${exitCode}`));
return;
}
resolve(subprocess);
});
});
}
subprocess.unref();
return subprocess;
};
+9
View File
@@ -0,0 +1,9 @@
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+58
View File
@@ -0,0 +1,58 @@
{
"name": "open",
"version": "6.4.0",
"description": "Open stuff like URLs, files, executables. Cross-platform.",
"license": "MIT",
"repository": "sindresorhus/open",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"engines": {
"node": ">=8"
},
"scripts": {
"test": "xo && tsd"
},
"files": [
"index.js",
"index.d.ts",
"xdg-open"
],
"keywords": [
"app",
"open",
"opener",
"opens",
"launch",
"start",
"xdg-open",
"xdg",
"default",
"cmd",
"browser",
"editor",
"executable",
"exe",
"url",
"urls",
"arguments",
"args",
"spawn",
"exec",
"child",
"process",
"website",
"file"
],
"dependencies": {
"is-wsl": "^1.1.0"
},
"devDependencies": {
"@types/node": "^11.13.6",
"ava": "^1.4.0",
"tsd": "^0.7.2",
"xo": "^0.24.0"
}
}

Some files were not shown because too many files have changed in this diff Show More