first commit

This commit is contained in:
Stefan Hacker
2026-04-03 09:38:48 +02:00
commit 37ad745546
47450 changed files with 3120798 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
+26
View File
@@ -0,0 +1,26 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Tests",
"program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
"args": [
"-u",
"bdd",
"--timeout",
"999999",
"--colors",
"${workspaceFolder}/test",
"-r",
"ts-node/register",
"${workspaceFolder}/test/**/*.ts"
],
"internalConsoleOptions": "openOnSessionStart"
}
]
}
+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
+43
View File
@@ -0,0 +1,43 @@
# Office-Addin-Usage-Data
This package allows for reporting usage data events and exception data to the selected telemetry infrastructure (e.g. ApplicationInsights).
# Privacy
The Office-Addin-Usage-Data package collects anonymized usage data and sends it to Microsoft. For more details on how we use this data and under what circumstances it may be shared,
please see the [Microsoft privacy statement](https://privacy.microsoft.com/en-us/privacystatement).
The package collects:
* Usage data about operations performed.
* Exception call stacks to help diagnose issues.
## Command-Line Interface
* [List](#List)
* [Off](#Off)
* [On](#On)
### List
Display the current usage data settings.
Syntax:
`list`
#
### Off
Sets the usage data level to Off(sending no usage data data).
Syntax:
`off`
#
### On
Sets the usage data level to On(sending usage and exception data).
Syntax:
`on`
#
Generated Vendored Executable
+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");
+14
View File
@@ -0,0 +1,14 @@
import officeAddins from "eslint-plugin-office-addins";
import tsParser from "@typescript-eslint/parser";
export default [
...officeAddins.configs.recommended,
{
plugins: {
"office-addins": officeAddins,
},
languageOptions: {
parser: tsParser,
},
},
];
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env node
export {};
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env node
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const log_1 = require("./log");
const commands = __importStar(require("./command"));
/* global process */
const commander = new commander_1.Command();
commander.name("office-addin-usage-data");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command(`list`)
.description(`Display the current usage data settings.`)
.action(commands.listUsageDataSettings);
commander
.command(`off`)
.description(`Turn off reporting of anonymous usage data.`)
.action(commands.turnUsageDataOff);
commander
.command(`on`)
.description(`Turn on reporting of anonymous usage data.`)
.action(commands.turnUsageDataOn);
// if the command is not known, display an error
commander.on("command:*", function () {
(0, log_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,+BAAwC;AACxC,oDAAsC;AAEtC,oBAAoB;AAEpB,MAAM,SAAS,GAAG,IAAI,mBAAO,EAAE,CAAC;AAEhC,SAAS,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAC;AAC1C,SAAS,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,mBAAmB,IAAI,yBAAyB,CAAC,CAAC;AAEhF,SAAS;KACN,OAAO,CAAC,MAAM,CAAC;KACf,WAAW,CAAC,0CAA0C,CAAC;KACvD,MAAM,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC;AAE1C,SAAS;KACN,OAAO,CAAC,KAAK,CAAC;KACd,WAAW,CAAC,6CAA6C,CAAC;KAC1D,MAAM,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AAErC,SAAS;KACN,OAAO,CAAC,IAAI,CAAC;KACb,WAAW,CAAC,4CAA4C,CAAC;KACzD,MAAM,CAAC,QAAQ,CAAC,eAAe,CAAC,CAAC;AAEpC,gDAAgD;AAChD,SAAS,CAAC,EAAE,CAAC,WAAW,EAAE;IACxB,IAAA,qBAAe,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"}
+3
View File
@@ -0,0 +1,3 @@
export declare function listUsageDataSettings(): void;
export declare function turnUsageDataOff(): void;
export declare function turnUsageDataOn(): void;
+69
View File
@@ -0,0 +1,69 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.turnUsageDataOn = exports.turnUsageDataOff = exports.listUsageDataSettings = void 0;
const defaults = __importStar(require("./defaults"));
const usageData_1 = require("./usageData");
const jsonData = __importStar(require("./usageDataSettings"));
/* global console */
function listUsageDataSettings() {
const usageDataSettings = jsonData.readUsageDataSettings(defaults.groupName);
if (usageDataSettings) {
for (const value of Object.keys(usageDataSettings)) {
console.log(`${value}: ${usageDataSettings[value]}\n`);
}
}
else {
console.log(`No usage data settings.`);
}
}
exports.listUsageDataSettings = listUsageDataSettings;
function turnUsageDataOff() {
setUsageDataLevel(usageData_1.UsageDataLevel.off);
}
exports.turnUsageDataOff = turnUsageDataOff;
function turnUsageDataOn() {
setUsageDataLevel(usageData_1.UsageDataLevel.on);
}
exports.turnUsageDataOn = turnUsageDataOn;
function setUsageDataLevel(level) {
try {
jsonData.modifyUsageDataJsonData(defaults.groupName, "usageDataLevel", level);
switch (level) {
case usageData_1.UsageDataLevel.off:
console.log("Usage data has been turned off.");
break;
case usageData_1.UsageDataLevel.on:
console.log("Usage data has been turned on.");
break;
}
}
catch (err) {
throw new Error(`Unable to set the usage data level.\n${err}`);
}
}
//# sourceMappingURL=command.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,qDAAuC;AACvC,2CAA6C;AAC7C,8DAAgD;AAEhD,oBAAoB;AAEpB,SAAgB,qBAAqB;IACnC,MAAM,iBAAiB,GAAG,QAAQ,CAAC,qBAAqB,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;IAE7E,IAAI,iBAAiB,EAAE;QACrB,KAAK,MAAM,KAAK,IAAI,MAAM,CAAC,IAAI,CAAC,iBAAiB,CAAC,EAAE;YAClD,OAAO,CAAC,GAAG,CAAC,GAAG,KAAK,KAAK,iBAAiB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;SACxD;KACF;SAAM;QACL,OAAO,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC;KACxC;AACH,CAAC;AAVD,sDAUC;AAED,SAAgB,gBAAgB;IAC9B,iBAAiB,CAAC,0BAAc,CAAC,GAAG,CAAC,CAAC;AACxC,CAAC;AAFD,4CAEC;AAED,SAAgB,eAAe;IAC7B,iBAAiB,CAAC,0BAAc,CAAC,EAAE,CAAC,CAAC;AACvC,CAAC;AAFD,0CAEC;AAED,SAAS,iBAAiB,CAAC,KAAqB;IAC9C,IAAI;QACF,QAAQ,CAAC,uBAAuB,CAAC,QAAQ,CAAC,SAAS,EAAE,gBAAgB,EAAE,KAAK,CAAC,CAAC;QAE9E,QAAQ,KAAK,EAAE;YACb,KAAK,0BAAc,CAAC,GAAG;gBACrB,OAAO,CAAC,GAAG,CAAC,iCAAiC,CAAC,CAAC;gBAC/C,MAAM;YACR,KAAK,0BAAc,CAAC,EAAE;gBACpB,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC,CAAC;gBAC9C,MAAM;SACT;KACF;IAAC,OAAO,GAAG,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,wCAAwC,GAAG,EAAE,CAAC,CAAC;KAChE;AACH,CAAC"}
+4
View File
@@ -0,0 +1,4 @@
export declare const usageDataJsonFilePath: string;
export declare const groupName: string;
export declare const instrumentationKeyForOfficeAddinCLITools: string;
export declare const generatorOffice: string;
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.generatorOffice = exports.instrumentationKeyForOfficeAddinCLITools = exports.groupName = exports.usageDataJsonFilePath = void 0;
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
exports.usageDataJsonFilePath = path_1.default.join(os_1.default.homedir(), "/office-addin-usage-data.json");
exports.groupName = "office-addin-usage-data";
exports.instrumentationKeyForOfficeAddinCLITools = "de0d9e7c-1f46-4552-bc21-4e43e489a015";
exports.generatorOffice = "generator-office";
//# 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,4CAAoB;AACpB,gDAAwB;AAEX,QAAA,qBAAqB,GAAW,cAAI,CAAC,IAAI,CACpD,YAAE,CAAC,OAAO,EAAE,EACZ,+BAA+B,CAChC,CAAC;AACW,QAAA,SAAS,GAAW,yBAAyB,CAAC;AAC9C,QAAA,wCAAwC,GACnD,sCAAsC,CAAC;AAC5B,QAAA,eAAe,GAAW,kBAAkB,CAAC"}
+5
View File
@@ -0,0 +1,5 @@
/**
* Logs an error message
* @param err The error to be logged
*/
export declare function logErrorMessage(err: any): void;
+15
View File
@@ -0,0 +1,15 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
Object.defineProperty(exports, "__esModule", { value: true });
exports.logErrorMessage = void 0;
/* global console */
/**
* Logs an error message
* @param err The error to be logged
*/
function logErrorMessage(err) {
console.error(`Error: ${err instanceof Error ? err.message : err}`);
}
exports.logErrorMessage = logErrorMessage;
//# sourceMappingURL=log.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"log.js","sourceRoot":"","sources":["../src/log.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;AAElC,oBAAoB;AAEpB;;;GAGG;AACH,SAAgB,eAAe,CAAC,GAAQ;IACtC,OAAO,CAAC,KAAK,CAAC,UAAU,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC;AACtE,CAAC;AAFD,0CAEC"}
+4
View File
@@ -0,0 +1,4 @@
export * from "./defaults";
export * from "./log";
export * from "./usageData";
export * from "./usageDataSettings";
+23
View File
@@ -0,0 +1,23 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./defaults"), exports);
__exportStar(require("./log"), exports);
__exportStar(require("./usageData"), exports);
__exportStar(require("./usageDataSettings"), exports);
//# 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,6CAA2B;AAC3B,wCAAsB;AACtB,8CAA4B;AAC5B,sDAAoC"}
+181
View File
@@ -0,0 +1,181 @@
/**
* Specifies the usage data infrastructure the user wishes to use
* @enum Application Insights: Microsoft Azure service used to collect and query through data
*/
export declare enum UsageDataReportingMethod {
applicationInsights = "applicationInsights"
}
/**
* Level controlling what type of usage data is being sent
* @enum off: off level of usage data, sends no usage data
* @enum on: on level of usage data, sends errors and events
*/
export declare enum UsageDataLevel {
off = "off",
on = "on"
}
/**
* Defines an error that is expected to happen given some situation
* @member message Message to be logged in the error
*/
export declare class ExpectedError extends Error {
constructor(message: string | undefined);
}
/**
* UpdateData options
* @member groupName Group name for usage data settings (Optional)
* @member projectName The name of the project that is using the usage data package.
* @member instrumentationKey Instrumentation key for usage data resource
* @member promptQuestion Question displayed to user over opt-in for usage data (Optional)
* @member raisePrompt Specifies whether to raise usage data prompt (this allows for using a custom prompt) (Optional)
* @member usageDataLevel User's response to the prompt for usage data (Optional)
* @member method The desired method to use for reporting usage data. (Optional)
* @member isForTesting True if the data is just for testing, false for actual data that should be reported. (Optional)
*/
export interface IUsageDataOptions {
groupName?: string;
projectName: string;
instrumentationKey: string;
promptQuestion?: string;
raisePrompt?: boolean;
usageDataLevel?: UsageDataLevel;
method?: UsageDataReportingMethod;
isForTesting?: boolean;
deviceID?: string;
}
/**
* Creates and initializes member variables while prompting user for usage data collection when necessary
* @param usageDataObject
*/
export declare class OfficeAddinUsageData {
private usageDataClient;
private eventsSent;
private exceptionsSent;
private options;
private defaultData;
constructor(usageDataOptions: IUsageDataOptions);
/**
* Reports custom event object to usage data structure
* @param eventName Event name sent to usage data structure
* @param data Data object sent to usage data structure
*/
reportEvent(eventName: string, data: object): Promise<void>;
/**
* Reports custom event object to Application Insights
* @param eventName Event name sent to Application Insights
* @param data Data object sent to Application Insights
*/
reportEventApplicationInsights(eventName: string, data: object): Promise<void>;
/**
* Reports error to usage data structure
* @param errorName Error name sent to usage data structure
* @param err Error sent to usage data structure
*/
reportError(errorName: string, err: Error): Promise<void>;
/**
* Reports error to Application Insights
* @param errorName Error name sent to Application Insights
* @param err Error sent to Application Insights
*/
reportErrorApplicationInsights(errorName: string, err: Error): Promise<void>;
/**
* Prompts user for usage data participation once and records response
* @param testData Specifies whether test code is calling this method
* @param testReponse Specifies test response
*/
usageDataOptIn(testData?: boolean, testResponse?: string): void;
/**
* Stops usage data from being sent, by default usage data will be on
*/
setUsageDataOff(): void;
/**
* Starts sending usage data, by default usage data will be on
*/
setUsageDataOn(): void;
/**
* Returns whether the usage data is currently on or off
* @returns Whether usage data is turned on or off
*/
isUsageDataOn(): boolean;
/**
* Returns the instrumentation key associated with the resource
* @returns The usage data instrumentation key
*/
getUsageDataKey(): string;
/**
* Transform the project name by adddin '-test' suffix to it if necessary
*/
private getEventName;
/**
* Returns the amount of events that have been sent
* @returns The count of events sent
*/
getEventsSent(): any;
/**
* Returns the amount of exceptions that have been sent
* @returns The count of exceptions sent
*/
getExceptionsSent(): any;
/**
* Get the usage data level
* @returns the usage data level
*/
getUsageDataLevel(): string;
/**
* Returns parsed file path, scrubbing file names and sensitive information
* @returns Error after removing PII
*/
maskFilePaths(err: Error): Error;
/**
* Removes sensitive information fields from ApplicationInsights data
*/
private removeApplicationInsightsSensitiveInformation;
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportException(method: string, err: Error | string, data?: object): void;
/**
* Reports custom expected exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportExpectedException(method: string, err: Error | string, data?: object): void;
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportSuccess(method: string, data?: object): void;
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportUnexpectedError` instead.
*/
sendUsageDataException(method: string, err: Error | string, data?: object): void;
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportSuccess` instead.
*/
sendUsageDataSuccessEvent(method: string, data?: object): void;
/**
* Reports custom successful fail event object to Application Insights
* "Successful fail" means that there was an error as a result of user error, but our code worked properly
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportExpectedError` instead.
*/
sendUsageDataSuccessfulFailEvent(method: string, data?: object): void;
/**
* Reports custom event object to Application Insights
* @param data Data object(s) sent to Application Insights
*/
sendUsageDataEvent(data?: object): void;
}
+423
View File
@@ -0,0 +1,423 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.OfficeAddinUsageData = exports.ExpectedError = exports.UsageDataLevel = exports.UsageDataReportingMethod = void 0;
const appInsights = __importStar(require("applicationinsights"));
const readline_sync_1 = __importDefault(require("readline-sync"));
const jsonData = __importStar(require("./usageDataSettings"));
const defaults = __importStar(require("./defaults"));
/* global process */
/**
* Specifies the usage data infrastructure the user wishes to use
* @enum Application Insights: Microsoft Azure service used to collect and query through data
*/
var UsageDataReportingMethod;
(function (UsageDataReportingMethod) {
UsageDataReportingMethod["applicationInsights"] = "applicationInsights";
})(UsageDataReportingMethod = exports.UsageDataReportingMethod || (exports.UsageDataReportingMethod = {}));
/**
* Level controlling what type of usage data is being sent
* @enum off: off level of usage data, sends no usage data
* @enum on: on level of usage data, sends errors and events
*/
var UsageDataLevel;
(function (UsageDataLevel) {
UsageDataLevel["off"] = "off";
UsageDataLevel["on"] = "on";
})(UsageDataLevel = exports.UsageDataLevel || (exports.UsageDataLevel = {}));
/**
* Defines an error that is expected to happen given some situation
* @member message Message to be logged in the error
*/
class ExpectedError extends Error {
constructor(message) {
super(message);
// need to adjust the prototype after super()
// See https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, ExpectedError.prototype);
}
}
exports.ExpectedError = ExpectedError;
/**
* Creates and initializes member variables while prompting user for usage data collection when necessary
* @param usageDataObject
*/
class OfficeAddinUsageData {
constructor(usageDataOptions) {
this.usageDataClient = appInsights.defaultClient;
this.eventsSent = 0;
this.exceptionsSent = 0;
this.defaultData = {
Platform: process.platform,
NodeVersion: process.version,
};
try {
this.options = Object.assign({ groupName: defaults.groupName, promptQuestion: "", raisePrompt: true, usageDataLevel: UsageDataLevel.off, method: UsageDataReportingMethod.applicationInsights, isForTesting: false }, usageDataOptions);
if (this.options.instrumentationKey === undefined) {
throw new Error("Instrumentation Key not defined - cannot create usage data object");
}
if (this.options.groupName === undefined) {
throw new Error("Group Name not defined - cannot create usage data object");
}
if (jsonData.groupNameExists(this.options.groupName)) {
this.options.usageDataLevel = jsonData.readUsageDataLevel(this.options.groupName);
}
// Generator-office will not raise a prompt because the yeoman generator creates the prompt. If the projectName
// is defaults.generatorOffice and a office-addin-usage-data file hasn't been written yet, write one out.
if (this.options.projectName === defaults.generatorOffice &&
this.options.instrumentationKey === defaults.instrumentationKeyForOfficeAddinCLITools &&
jsonData.needToPromptForUsageData(this.options.groupName)) {
jsonData.writeUsageDataJsonData(this.options.groupName, this.options.usageDataLevel);
}
if (!this.options.isForTesting &&
this.options.raisePrompt &&
jsonData.needToPromptForUsageData(this.options.groupName)) {
this.usageDataOptIn();
}
this.options.deviceID = jsonData.readDeviceID();
if (this.options.usageDataLevel === UsageDataLevel.on) {
appInsights.setup(this.options.instrumentationKey).setAutoCollectExceptions(false).start();
this.usageDataClient = appInsights.defaultClient;
this.removeApplicationInsightsSensitiveInformation();
}
}
catch (err) {
throw new Error(err);
}
}
/**
* Reports custom event object to usage data structure
* @param eventName Event name sent to usage data structure
* @param data Data object sent to usage data structure
*/
reportEvent(eventName, data) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
this.reportEventApplicationInsights(eventName, data);
}
});
}
/**
* Reports custom event object to Application Insights
* @param eventName Event name sent to Application Insights
* @param data Data object sent to Application Insights
*/
reportEventApplicationInsights(eventName, data) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
const usageDataEvent = new appInsights.Contracts.EventData();
usageDataEvent.name = this.options.isForTesting ? `${eventName}-test` : eventName;
try {
for (const [key, [value, elapsedTime]] of Object.entries(data)) {
usageDataEvent.properties[key] = value;
usageDataEvent.measurements[key + " durationElapsed"] = elapsedTime;
}
usageDataEvent.properties["deviceID"] = this.options.deviceID;
this.usageDataClient.trackEvent(usageDataEvent);
this.eventsSent++;
}
catch (err) {
this.reportError("sendUsageDataEvents", err);
throw new Error(err);
}
}
});
}
/**
* Reports error to usage data structure
* @param errorName Error name sent to usage data structure
* @param err Error sent to usage data structure
*/
reportError(errorName, err) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
this.reportErrorApplicationInsights(errorName, err);
}
});
}
/**
* Reports error to Application Insights
* @param errorName Error name sent to Application Insights
* @param err Error sent to Application Insights
*/
reportErrorApplicationInsights(errorName, err) {
return __awaiter(this, void 0, void 0, function* () {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
let error = Object.create(err);
error.name = this.options.isForTesting ? `${errorName}-test` : errorName;
this.usageDataClient.trackException({
exception: this.maskFilePaths(error),
});
this.exceptionsSent++;
}
});
}
/**
* Prompts user for usage data participation once and records response
* @param testData Specifies whether test code is calling this method
* @param testReponse Specifies test response
*/
usageDataOptIn(testData = this.options.isForTesting, testResponse = "") {
try {
let response = "";
if (testData) {
response = testResponse;
}
else {
response = readline_sync_1.default.question(`${this.options.promptQuestion}\n`);
}
if (response.toLowerCase() === "y") {
this.options.usageDataLevel = UsageDataLevel.on;
}
else {
this.options.usageDataLevel = UsageDataLevel.off;
}
jsonData.writeUsageDataJsonData(this.options.groupName, this.options.usageDataLevel);
}
catch (err) {
this.reportError("UsageDataOptIn", err);
throw new Error(err);
}
}
/**
* Stops usage data from being sent, by default usage data will be on
*/
setUsageDataOff() {
appInsights.defaultClient.config.samplingPercentage = 0;
}
/**
* Starts sending usage data, by default usage data will be on
*/
setUsageDataOn() {
appInsights.defaultClient.config.samplingPercentage = 100;
}
/**
* Returns whether the usage data is currently on or off
* @returns Whether usage data is turned on or off
*/
isUsageDataOn() {
return appInsights.defaultClient.config.samplingPercentage === 100;
}
/**
* Returns the instrumentation key associated with the resource
* @returns The usage data instrumentation key
*/
getUsageDataKey() {
return this.options.instrumentationKey;
}
/**
* Transform the project name by adddin '-test' suffix to it if necessary
*/
getEventName() {
return this.options.isForTesting
? `${this.options.projectName}-test`
: this.options.projectName;
}
/**
* Returns the amount of events that have been sent
* @returns The count of events sent
*/
getEventsSent() {
return this.eventsSent;
}
/**
* Returns the amount of exceptions that have been sent
* @returns The count of exceptions sent
*/
getExceptionsSent() {
return this.exceptionsSent;
}
/**
* Get the usage data level
* @returns the usage data level
*/
getUsageDataLevel() {
return this.options.usageDataLevel;
}
/**
* Returns parsed file path, scrubbing file names and sensitive information
* @returns Error after removing PII
*/
maskFilePaths(err) {
try {
const regexRemoveUserFilePaths = /(\w:)*[/\\](.*[/\\]+)*(.+\.)+[a-zA-Z]+/gim;
const maskToken = "<filepath>";
err.message = err.message.replace(regexRemoveUserFilePaths, maskToken);
err.stack = err.stack.replace(regexRemoveUserFilePaths, maskToken);
return err;
}
catch (err) {
this.reportError("maskFilePaths", err);
throw new Error(err);
}
}
/**
* Removes sensitive information fields from ApplicationInsights data
*/
removeApplicationInsightsSensitiveInformation() {
delete this.usageDataClient.context.tags["ai.cloud.roleInstance"]; // cloud name
delete this.usageDataClient.context.tags["ai.device.id"]; // machine name
delete this.usageDataClient.context.tags["ai.user.accountId"]; // subscription
}
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportException(method, err, data = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
if (err instanceof ExpectedError) {
this.reportExpectedException(method, err, data);
return;
}
let error = err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
let exceptionTelemetryObj = {
exception: this.maskFilePaths(error),
properties: {},
};
Object.entries(Object.assign(Object.assign(Object.assign({ Succeeded: false, Method: method, ExpectedError: false }, this.defaultData), data), { deviceID: this.options.deviceID })).forEach((entry) => {
exceptionTelemetryObj.properties[entry[0]] = JSON.stringify(entry[1]);
});
this.usageDataClient.trackException(exceptionTelemetryObj);
this.exceptionsSent++;
}
catch (e) {
this.reportError("reportException", e);
throw e;
}
}
}
/**
* Reports custom expected exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportExpectedException(method, err, data = {}) {
let error = err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
this.maskFilePaths(error);
const errorMessage = error instanceof Error ? error.message : error;
this.sendUsageDataEvent(Object.assign({ Succeeded: true, Method: method, ExpectedError: true, Error: errorMessage }, data));
}
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
reportSuccess(method, data = {}) {
this.sendUsageDataEvent(Object.assign({ Succeeded: true, Method: method, ExpectedError: false }, data));
}
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportUnexpectedError` instead.
*/
sendUsageDataException(method, err, data = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
let error = err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
let exceptionTelemetryObj = {
exception: this.maskFilePaths(error),
properties: {},
};
Object.entries(Object.assign(Object.assign({ Succeeded: false, Method: method }, this.defaultData), data)).forEach((entry) => {
exceptionTelemetryObj.properties[entry[0]] = JSON.stringify(entry[1]);
});
this.usageDataClient.trackException(exceptionTelemetryObj);
this.exceptionsSent++;
}
catch (e) {
this.reportError("sendUsageDataException", e);
throw e;
}
}
}
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportSuccess` instead.
*/
sendUsageDataSuccessEvent(method, data = {}) {
this.sendUsageDataEvent(Object.assign({ Succeeded: true, Method: method, Pass: true }, data));
}
/**
* Reports custom successful fail event object to Application Insights
* "Successful fail" means that there was an error as a result of user error, but our code worked properly
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportExpectedError` instead.
*/
sendUsageDataSuccessfulFailEvent(method, data = {}) {
this.sendUsageDataEvent(Object.assign({ Succeeded: true, Method: method, Pass: false }, data));
}
/**
* Reports custom event object to Application Insights
* @param data Data object(s) sent to Application Insights
*/
sendUsageDataEvent(data = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
let eventTelemetryObj = new appInsights.Contracts.EventData();
eventTelemetryObj.name = this.getEventName();
eventTelemetryObj.properties = Object.assign(Object.assign(Object.assign({}, this.defaultData), data), { deviceID: this.options.deviceID });
this.usageDataClient.trackEvent(eventTelemetryObj);
this.eventsSent++;
}
catch (e) {
this.reportError("sendUsageDataEvent", e);
}
}
}
}
exports.OfficeAddinUsageData = OfficeAddinUsageData;
//# sourceMappingURL=usageData.js.map
File diff suppressed because one or more lines are too long
+54
View File
@@ -0,0 +1,54 @@
import { UsageDataLevel } from "./usageData";
/**
* Allows developer to check if the program has already prompted before
* @param groupName Group name of the usage data object
* @returns Boolean of whether the program should prompt
*/
export declare function needToPromptForUsageData(groupName: string): boolean;
/**
* Allows developer to add or modify a specific property to the group
* @param groupName Group name of property
* @param property Property that will be created or modified
* @param value Property's value that will be assigned
*/
export declare function modifyUsageDataJsonData(groupName: string, property: any, value: any): void;
/**
* Returns the session identifier
* @returns The uuid of the session identifier
*/
export declare function readDeviceID(): string;
/**
* Reads data from the usage data json config file
* @returns Parsed object from json file if it exists
*/
export declare function readUsageDataJsonData(): any;
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @returns Whether usage data is enabled specific to the group name
*/
export declare function readUsageDataLevel(groupName: string): UsageDataLevel;
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @param propertyName Property name that will be used to access and return the associated value
* @returns Property of the specific group name
*/
export declare function readUsageDataObjectProperty(groupName: string, propertyName: string): any;
/**
* Writes to usage data config file either appending to already existing file or creating new file
* @param groupName Group name of usage data object
* @param level usageDataLevel Whether user is sending none or full usage data
*/
export declare function writeUsageDataJsonData(groupName: string, level: UsageDataLevel): void;
/**
* Checks to see if the given group name exists in the specified json data
* @param groupName Group name to search for in the specified json data
* @returns Boolean of whether group name exists
*/
export declare function groupNameExists(groupName: string): boolean;
/**
* Reads usage data settings from the usage data json config file for a specific group
* @returns Settings for the specified group
*/
export declare function readUsageDataSettings(groupName?: string): object | undefined;
+185
View File
@@ -0,0 +1,185 @@
"use strict";
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readUsageDataSettings = exports.groupNameExists = exports.writeUsageDataJsonData = exports.readUsageDataObjectProperty = exports.readUsageDataLevel = exports.readUsageDataJsonData = exports.readDeviceID = exports.modifyUsageDataJsonData = exports.needToPromptForUsageData = void 0;
const fs_1 = __importDefault(require("fs"));
const defaults = __importStar(require("./defaults"));
const uuid_1 = require("uuid");
/**
* Allows developer to check if the program has already prompted before
* @param groupName Group name of the usage data object
* @returns Boolean of whether the program should prompt
*/
function needToPromptForUsageData(groupName) {
return !groupNameExists(groupName);
}
exports.needToPromptForUsageData = needToPromptForUsageData;
/**
* Allows developer to add or modify a specific property to the group
* @param groupName Group name of property
* @param property Property that will be created or modified
* @param value Property's value that will be assigned
*/
function modifyUsageDataJsonData(groupName, property, value) {
try {
if (readUsageDataJsonData()) {
const usageDataJsonData = readUsageDataJsonData();
if (!groupNameExists(groupName)) {
usageDataJsonData.usageDataInstances[groupName] = {
usageDataLevel: String,
};
}
usageDataJsonData.usageDataInstances[groupName][property] = value;
if (!usageDataJsonData.usageDataInstances["deviceID"]) {
usageDataJsonData.usageDataInstances["deviceID"] = (0, uuid_1.v4)();
}
fs_1.default.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
else {
let usageDataJsonData = {};
usageDataJsonData[groupName] = value;
usageDataJsonData = { usageDataInstances: usageDataJsonData };
usageDataJsonData = {
usageDataInstances: { [groupName]: { [property]: value }, deviceID: (0, uuid_1.v4)() },
};
fs_1.default.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
}
catch (err) {
throw new Error(err);
}
}
exports.modifyUsageDataJsonData = modifyUsageDataJsonData;
/**
* Returns the session identifier
* @returns The uuid of the session identifier
*/
function readDeviceID() {
var _a;
const jsonData = readUsageDataJsonData();
return (_a = jsonData === null || jsonData === void 0 ? void 0 : jsonData.usageDataInstances.deviceID) !== null && _a !== void 0 ? _a : "";
}
exports.readDeviceID = readDeviceID;
/**
* Reads data from the usage data json config file
* @returns Parsed object from json file if it exists
*/
function readUsageDataJsonData() {
if (fs_1.default.existsSync(defaults.usageDataJsonFilePath)) {
const jsonData = fs_1.default.readFileSync(defaults.usageDataJsonFilePath, "utf8");
return JSON.parse(jsonData.toString());
}
}
exports.readUsageDataJsonData = readUsageDataJsonData;
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @returns Whether usage data is enabled specific to the group name
*/
function readUsageDataLevel(groupName) {
const jsonData = readUsageDataJsonData();
return jsonData.usageDataInstances[groupName].usageDataLevel;
}
exports.readUsageDataLevel = readUsageDataLevel;
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @param propertyName Property name that will be used to access and return the associated value
* @returns Property of the specific group name
*/
function readUsageDataObjectProperty(groupName, propertyName) {
const jsonData = readUsageDataJsonData();
return jsonData.usageDataInstances[groupName][propertyName];
}
exports.readUsageDataObjectProperty = readUsageDataObjectProperty;
/**
* Writes to usage data config file either appending to already existing file or creating new file
* @param groupName Group name of usage data object
* @param level usageDataLevel Whether user is sending none or full usage data
*/
function writeUsageDataJsonData(groupName, level) {
if (fs_1.default.existsSync(defaults.usageDataJsonFilePath) &&
fs_1.default.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "" &&
fs_1.default.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "undefined") {
if (groupNameExists(groupName)) {
modifyUsageDataJsonData(groupName, "usageDataLevel", level);
}
else {
const usageDataJsonData = readUsageDataJsonData();
usageDataJsonData.usageDataInstances[groupName] = {
usageDataLevel: String,
};
usageDataJsonData.usageDataInstances[groupName].usageDataLevel = level;
if (!usageDataJsonData.usageDataInstances["deviceID"]) {
usageDataJsonData.usageDataInstances["deviceID"] = (0, uuid_1.v4)();
}
fs_1.default.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
}
else {
let usageDataJsonData = {};
usageDataJsonData[groupName] = level;
usageDataJsonData = { usageDataInstances: usageDataJsonData };
usageDataJsonData = {
usageDataInstances: { [groupName]: { ["usageDataLevel"]: level }, deviceID: (0, uuid_1.v4)() },
};
fs_1.default.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
}
exports.writeUsageDataJsonData = writeUsageDataJsonData;
/**
* Checks to see if the given group name exists in the specified json data
* @param groupName Group name to search for in the specified json data
* @returns Boolean of whether group name exists
*/
function groupNameExists(groupName) {
if (fs_1.default.existsSync(defaults.usageDataJsonFilePath) &&
fs_1.default.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "" &&
fs_1.default.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "undefined") {
const jsonData = readUsageDataJsonData();
return Object.getOwnPropertyNames(jsonData.usageDataInstances).includes(groupName);
}
return false;
}
exports.groupNameExists = groupNameExists;
/**
* Reads usage data settings from the usage data json config file for a specific group
* @returns Settings for the specified group
*/
function readUsageDataSettings(groupName = defaults.groupName) {
if (fs_1.default.existsSync(defaults.usageDataJsonFilePath)) {
return readUsageDataJsonData().usageDataInstances[groupName];
}
else {
return undefined;
}
}
exports.readUsageDataSettings = readUsageDataSettings;
//# sourceMappingURL=usageDataSettings.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"usageDataSettings.js","sourceRoot":"","sources":["../src/usageDataSettings.ts"],"names":[],"mappings":";AAAA,4DAA4D;AAC5D,kCAAkC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAElC,4CAAoB;AACpB,qDAAuC;AAEvC,+BAAoC;AAEpC;;;;GAIG;AACH,SAAgB,wBAAwB,CAAC,SAAiB;IACxD,OAAO,CAAC,eAAe,CAAC,SAAS,CAAC,CAAC;AACrC,CAAC;AAFD,4DAEC;AAED;;;;;GAKG;AACH,SAAgB,uBAAuB,CAAC,SAAiB,EAAE,QAAa,EAAE,KAAU;IAClF,IAAI;QACF,IAAI,qBAAqB,EAAE,EAAE;YAC3B,MAAM,iBAAiB,GAAG,qBAAqB,EAAE,CAAC;YAClD,IAAI,CAAC,eAAe,CAAC,SAAS,CAAC,EAAE;gBAC/B,iBAAiB,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG;oBAChD,cAAc,EAAE,MAAM;iBACvB,CAAC;aACH;YACD,iBAAiB,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;YAClE,IAAI,CAAC,iBAAiB,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE;gBACrD,iBAAiB,CAAC,kBAAkB,CAAC,UAAU,CAAC,GAAG,IAAA,SAAM,GAAE,CAAC;aAC7D;YACD,YAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,qBAAqB,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;SAC9F;aAAM;YACL,IAAI,iBAAiB,GAAG,EAAE,CAAC;YAC3B,iBAAiB,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;YACrC,iBAAiB,GAAG,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,CAAC;YAC9D,iBAAiB,GAAG;gBAClB,kBAAkB,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,CAAC,QAAQ,CAAC,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAA,SAAM,GAAE,EAAE;aAC/E,CAAC;YACF,YAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,qBAAqB,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;SAC9F;KACF;IAAC,OAAO,GAAG,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,GAAG,CAAC,CAAC;KACtB;AACH,CAAC;AA1BD,0DA0BC;AACD;;;GAGG;AACH,SAAgB,YAAY;;IAC1B,MAAM,QAAQ,GAAG,qBAAqB,EAAE,CAAC;IACzC,OAAO,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,kBAAkB,CAAC,QAAQ,mCAAI,EAAE,CAAC;AACrD,CAAC;AAHD,oCAGC;AACD;;;GAGG;AACH,SAAgB,qBAAqB;IACnC,IAAI,YAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE;QACjD,MAAM,QAAQ,GAAG,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,CAAC;QACzE,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,EAAE,CAAC,CAAC;KACxC;AACH,CAAC;AALD,sDAKC;AACD;;;;GAIG;AACH,SAAgB,kBAAkB,CAAC,SAAiB;IAClD,MAAM,QAAQ,GAAG,qBAAqB,EAAE,CAAC;IACzC,OAAO,QAAQ,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,cAAc,CAAC;AAC/D,CAAC;AAHD,gDAGC;AACD;;;;;GAKG;AACH,SAAgB,2BAA2B,CAAC,SAAiB,EAAE,YAAoB;IACjF,MAAM,QAAQ,GAAG,qBAAqB,EAAE,CAAC;IACzC,OAAO,QAAQ,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,YAAY,CAAC,CAAC;AAC9D,CAAC;AAHD,kEAGC;AACD;;;;GAIG;AAEH,SAAgB,sBAAsB,CAAC,SAAiB,EAAE,KAAqB;IAC7E,IACE,YAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC;QAC7C,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,KAAK,EAAE;QAC9D,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,KAAK,WAAW,EACvE;QACA,IAAI,eAAe,CAAC,SAAS,CAAC,EAAE;YAC9B,uBAAuB,CAAC,SAAS,EAAE,gBAAgB,EAAE,KAAK,CAAC,CAAC;SAC7D;aAAM;YACL,MAAM,iBAAiB,GAAG,qBAAqB,EAAE,CAAC;YAClD,iBAAiB,CAAC,kBAAkB,CAAC,SAAS,CAAC,GAAG;gBAChD,cAAc,EAAE,MAAM;aACvB,CAAC;YACF,iBAAiB,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC,cAAc,GAAG,KAAK,CAAC;YACvE,IAAI,CAAC,iBAAiB,CAAC,kBAAkB,CAAC,UAAU,CAAC,EAAE;gBACrD,iBAAiB,CAAC,kBAAkB,CAAC,UAAU,CAAC,GAAG,IAAA,SAAM,GAAE,CAAC;aAC7D;YACD,YAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,qBAAqB,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;SAC9F;KACF;SAAM;QACL,IAAI,iBAAiB,GAAG,EAAE,CAAC;QAC3B,iBAAiB,CAAC,SAAS,CAAC,GAAG,KAAK,CAAC;QACrC,iBAAiB,GAAG,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,CAAC;QAC9D,iBAAiB,GAAG;YAClB,kBAAkB,EAAE,EAAE,CAAC,SAAS,CAAC,EAAE,EAAE,CAAC,gBAAgB,CAAC,EAAE,KAAK,EAAE,EAAE,QAAQ,EAAE,IAAA,SAAM,GAAE,EAAE;SACvF,CAAC;QAEF,YAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,qBAAqB,EAAE,IAAI,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;KAC9F;AACH,CAAC;AA7BD,wDA6BC;AACD;;;;GAIG;AACH,SAAgB,eAAe,CAAC,SAAiB;IAC/C,IACE,YAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC;QAC7C,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,KAAK,EAAE;QAC9D,YAAE,CAAC,YAAY,CAAC,QAAQ,CAAC,qBAAqB,EAAE,MAAM,CAAC,KAAK,WAAW,EACvE;QACA,MAAM,QAAQ,GAAG,qBAAqB,EAAE,CAAC;QACzC,OAAO,MAAM,CAAC,mBAAmB,CAAC,QAAQ,CAAC,kBAAkB,CAAC,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;KACpF;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAVD,0CAUC;AACD;;;GAGG;AACH,SAAgB,qBAAqB,CAAC,SAAS,GAAG,QAAQ,CAAC,SAAS;IAClE,IAAI,YAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,qBAAqB,CAAC,EAAE;QACjD,OAAO,qBAAqB,EAAE,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;KAC9D;SAAM;QACL,OAAO,SAAS,CAAC;KAClB;AACH,CAAC;AAND,sDAMC"}
+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;
+709
View File
@@ -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
+53
View File
@@ -0,0 +1,53 @@
{
"name": "office-addin-usage-data",
"version": "2.0.6",
"description": "Provides infrastructure to send usage data events and exceptions.",
"main": "./lib/main.js",
"scripts": {
"build": "rimraf lib && concurrently \"tsc -p tsconfig.json\"",
"cli": "node lib/cli.js",
"lint": "eslint src/**/*.{ts,tsx,js,jsx}",
"lint:fix": "eslint src/**/*.{ts,tsx,js,jsx} --fix",
"test": "mocha -r ts-node/register test/**/*.ts",
"watch": "rimraf lib && concurrently \"tsc -p tsconfig.json -w\""
},
"author": "Office Dev",
"license": "MIT",
"bin": {
"office-addin-usage-data": "./cli.js"
},
"keywords": [
"Office",
"Office Add-in"
],
"dependencies": {
"applicationinsights": "^1.7.3",
"commander": "^13.0.0",
"readline-sync": "^1.4.9",
"uuid": "8.3.2"
},
"devDependencies": {
"@types/mocha": "^10.0.6",
"@types/node": "^14.17.2",
"concurrently": "^9.0.0",
"eslint": "^9.0.0",
"eslint-plugin-office-addins": "^4.0.6",
"eslint-plugin-prettier": "^5.2.1",
"mocha": "^11.0.1",
"office-addin-prettier-config": "^2.0.1",
"rimraf": "^6.0.1",
"sinon": "^19.0.2",
"ts-node": "^10.9.1",
"typescript": "^4.7.4",
"typescript-eslint": "^8.4.0"
},
"repository": {
"type": "git",
"url": "https://github.com/OfficeDev/Office-Addin-Scripts"
},
"bugs": {
"url": "https://github.com/OfficeDev/Office-Addin-Scripts/issues"
},
"prettier": "office-addin-prettier-config",
"gitHead": "3023b9e22db5320008316d9eaf99993caa2e7a86"
}
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env node
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import { Command } from "commander";
import { logErrorMessage } from "./log";
import * as commands from "./command";
/* global process */
const commander = new Command();
commander.name("office-addin-usage-data");
commander.version(process.env.npm_package_version || "(version not available)");
commander
.command(`list`)
.description(`Display the current usage data settings.`)
.action(commands.listUsageDataSettings);
commander
.command(`off`)
.description(`Turn off reporting of anonymous usage data.`)
.action(commands.turnUsageDataOff);
commander
.command(`on`)
.description(`Turn on reporting of anonymous usage data.`)
.action(commands.turnUsageDataOn);
// if the command is not known, display an error
commander.on("command:*", function () {
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();
}
+45
View File
@@ -0,0 +1,45 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as defaults from "./defaults";
import { UsageDataLevel } from "./usageData";
import * as jsonData from "./usageDataSettings";
/* global console */
export function listUsageDataSettings(): void {
const usageDataSettings = jsonData.readUsageDataSettings(defaults.groupName);
if (usageDataSettings) {
for (const value of Object.keys(usageDataSettings)) {
console.log(`${value}: ${usageDataSettings[value]}\n`);
}
} else {
console.log(`No usage data settings.`);
}
}
export function turnUsageDataOff(): void {
setUsageDataLevel(UsageDataLevel.off);
}
export function turnUsageDataOn(): void {
setUsageDataLevel(UsageDataLevel.on);
}
function setUsageDataLevel(level: UsageDataLevel) {
try {
jsonData.modifyUsageDataJsonData(defaults.groupName, "usageDataLevel", level);
switch (level) {
case UsageDataLevel.off:
console.log("Usage data has been turned off.");
break;
case UsageDataLevel.on:
console.log("Usage data has been turned on.");
break;
}
} catch (err) {
throw new Error(`Unable to set the usage data level.\n${err}`);
}
}
+14
View File
@@ -0,0 +1,14 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import os from "os";
import path from "path";
export const usageDataJsonFilePath: string = path.join(
os.homedir(),
"/office-addin-usage-data.json"
);
export const groupName: string = "office-addin-usage-data";
export const instrumentationKeyForOfficeAddinCLITools: string =
"de0d9e7c-1f46-4552-bc21-4e43e489a015";
export const generatorOffice: string = "generator-office";
+12
View File
@@ -0,0 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
/* global console */
/**
* Logs an error message
* @param err The error to be logged
*/
export function logErrorMessage(err: any) {
console.error(`Error: ${err instanceof Error ? err.message : err}`);
}
+7
View File
@@ -0,0 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
export * from "./defaults";
export * from "./log";
export * from "./usageData";
export * from "./usageDataSettings";
+480
View File
@@ -0,0 +1,480 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as appInsights from "applicationinsights";
import readLine from "readline-sync";
import * as jsonData from "./usageDataSettings";
import * as defaults from "./defaults";
/* global process */
/**
* Specifies the usage data infrastructure the user wishes to use
* @enum Application Insights: Microsoft Azure service used to collect and query through data
*/
export enum UsageDataReportingMethod {
applicationInsights = "applicationInsights",
}
/**
* Level controlling what type of usage data is being sent
* @enum off: off level of usage data, sends no usage data
* @enum on: on level of usage data, sends errors and events
*/
export enum UsageDataLevel {
off = "off",
on = "on",
}
/**
* Defines an error that is expected to happen given some situation
* @member message Message to be logged in the error
*/
export class ExpectedError extends Error {
constructor(message: string | undefined) {
super(message);
// need to adjust the prototype after super()
// See https://github.com/Microsoft/TypeScript-wiki/blob/master/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work
Object.setPrototypeOf(this, ExpectedError.prototype);
}
}
/**
* UpdateData options
* @member groupName Group name for usage data settings (Optional)
* @member projectName The name of the project that is using the usage data package.
* @member instrumentationKey Instrumentation key for usage data resource
* @member promptQuestion Question displayed to user over opt-in for usage data (Optional)
* @member raisePrompt Specifies whether to raise usage data prompt (this allows for using a custom prompt) (Optional)
* @member usageDataLevel User's response to the prompt for usage data (Optional)
* @member method The desired method to use for reporting usage data. (Optional)
* @member isForTesting True if the data is just for testing, false for actual data that should be reported. (Optional)
*/
export interface IUsageDataOptions {
groupName?: string;
projectName: string;
instrumentationKey: string;
promptQuestion?: string;
raisePrompt?: boolean;
usageDataLevel?: UsageDataLevel;
method?: UsageDataReportingMethod;
isForTesting?: boolean;
deviceID?: string;
}
/**
* Creates and initializes member variables while prompting user for usage data collection when necessary
* @param usageDataObject
*/
export class OfficeAddinUsageData {
private usageDataClient = appInsights.defaultClient;
private eventsSent: number = 0;
private exceptionsSent: number = 0;
private options: IUsageDataOptions;
private defaultData = {
Platform: process.platform,
NodeVersion: process.version,
};
constructor(usageDataOptions: IUsageDataOptions) {
try {
this.options = {
groupName: defaults.groupName,
promptQuestion: "",
raisePrompt: true,
usageDataLevel: UsageDataLevel.off,
method: UsageDataReportingMethod.applicationInsights,
isForTesting: false,
...usageDataOptions,
};
if (this.options.instrumentationKey === undefined) {
throw new Error("Instrumentation Key not defined - cannot create usage data object");
}
if (this.options.groupName === undefined) {
throw new Error("Group Name not defined - cannot create usage data object");
}
if (jsonData.groupNameExists(this.options.groupName)) {
this.options.usageDataLevel = jsonData.readUsageDataLevel(this.options.groupName);
}
// Generator-office will not raise a prompt because the yeoman generator creates the prompt. If the projectName
// is defaults.generatorOffice and a office-addin-usage-data file hasn't been written yet, write one out.
if (
this.options.projectName === defaults.generatorOffice &&
this.options.instrumentationKey === defaults.instrumentationKeyForOfficeAddinCLITools &&
jsonData.needToPromptForUsageData(this.options.groupName)
) {
jsonData.writeUsageDataJsonData(this.options.groupName, this.options.usageDataLevel);
}
if (
!this.options.isForTesting &&
this.options.raisePrompt &&
jsonData.needToPromptForUsageData(this.options.groupName)
) {
this.usageDataOptIn();
}
this.options.deviceID = jsonData.readDeviceID();
if (this.options.usageDataLevel === UsageDataLevel.on) {
appInsights.setup(this.options.instrumentationKey).setAutoCollectExceptions(false).start();
this.usageDataClient = appInsights.defaultClient;
this.removeApplicationInsightsSensitiveInformation();
}
} catch (err) {
throw new Error(err);
}
}
/**
* Reports custom event object to usage data structure
* @param eventName Event name sent to usage data structure
* @param data Data object sent to usage data structure
*/
public async reportEvent(eventName: string, data: object): Promise<void> {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
this.reportEventApplicationInsights(eventName, data);
}
}
/**
* Reports custom event object to Application Insights
* @param eventName Event name sent to Application Insights
* @param data Data object sent to Application Insights
*/
public async reportEventApplicationInsights(eventName: string, data: object): Promise<void> {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
const usageDataEvent = new appInsights.Contracts.EventData();
usageDataEvent.name = this.options.isForTesting ? `${eventName}-test` : eventName;
try {
for (const [key, [value, elapsedTime]] of Object.entries(data)) {
usageDataEvent.properties[key] = value;
usageDataEvent.measurements[key + " durationElapsed"] = elapsedTime;
}
usageDataEvent.properties["deviceID"] = this.options.deviceID;
this.usageDataClient.trackEvent(usageDataEvent);
this.eventsSent++;
} catch (err) {
this.reportError("sendUsageDataEvents", err);
throw new Error(err);
}
}
}
/**
* Reports error to usage data structure
* @param errorName Error name sent to usage data structure
* @param err Error sent to usage data structure
*/
public async reportError(errorName: string, err: Error): Promise<void> {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
this.reportErrorApplicationInsights(errorName, err);
}
}
/**
* Reports error to Application Insights
* @param errorName Error name sent to Application Insights
* @param err Error sent to Application Insights
*/
public async reportErrorApplicationInsights(errorName: string, err: Error): Promise<void> {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
let error = Object.create(err);
error.name = this.options.isForTesting ? `${errorName}-test` : errorName;
this.usageDataClient.trackException({
exception: this.maskFilePaths(error),
});
this.exceptionsSent++;
}
}
/**
* Prompts user for usage data participation once and records response
* @param testData Specifies whether test code is calling this method
* @param testReponse Specifies test response
*/
public usageDataOptIn(
testData: boolean = this.options.isForTesting,
testResponse: string = ""
): void {
try {
let response: string = "";
if (testData) {
response = testResponse;
} else {
response = readLine.question(`${this.options.promptQuestion}\n`);
}
if (response.toLowerCase() === "y") {
this.options.usageDataLevel = UsageDataLevel.on;
} else {
this.options.usageDataLevel = UsageDataLevel.off;
}
jsonData.writeUsageDataJsonData(this.options.groupName, this.options.usageDataLevel);
} catch (err) {
this.reportError("UsageDataOptIn", err);
throw new Error(err);
}
}
/**
* Stops usage data from being sent, by default usage data will be on
*/
public setUsageDataOff() {
appInsights.defaultClient.config.samplingPercentage = 0;
}
/**
* Starts sending usage data, by default usage data will be on
*/
public setUsageDataOn() {
appInsights.defaultClient.config.samplingPercentage = 100;
}
/**
* Returns whether the usage data is currently on or off
* @returns Whether usage data is turned on or off
*/
public isUsageDataOn(): boolean {
return appInsights.defaultClient.config.samplingPercentage === 100;
}
/**
* Returns the instrumentation key associated with the resource
* @returns The usage data instrumentation key
*/
public getUsageDataKey(): string {
return this.options.instrumentationKey;
}
/**
* Transform the project name by adddin '-test' suffix to it if necessary
*/
private getEventName() {
return this.options.isForTesting
? `${this.options.projectName}-test`
: this.options.projectName;
}
/**
* Returns the amount of events that have been sent
* @returns The count of events sent
*/
public getEventsSent(): any {
return this.eventsSent;
}
/**
* Returns the amount of exceptions that have been sent
* @returns The count of exceptions sent
*/
public getExceptionsSent(): any {
return this.exceptionsSent;
}
/**
* Get the usage data level
* @returns the usage data level
*/
public getUsageDataLevel(): string {
return this.options.usageDataLevel;
}
/**
* Returns parsed file path, scrubbing file names and sensitive information
* @returns Error after removing PII
*/
public maskFilePaths(err: Error): Error {
try {
const regexRemoveUserFilePaths = /(\w:)*[/\\](.*[/\\]+)*(.+\.)+[a-zA-Z]+/gim;
const maskToken: string = "<filepath>";
err.message = err.message.replace(regexRemoveUserFilePaths, maskToken);
err.stack = err.stack.replace(regexRemoveUserFilePaths, maskToken);
return err;
} catch (err) {
this.reportError("maskFilePaths", err);
throw new Error(err);
}
}
/**
* Removes sensitive information fields from ApplicationInsights data
*/
private removeApplicationInsightsSensitiveInformation() {
delete this.usageDataClient.context.tags["ai.cloud.roleInstance"]; // cloud name
delete this.usageDataClient.context.tags["ai.device.id"]; // machine name
delete this.usageDataClient.context.tags["ai.user.accountId"]; // subscription
}
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
public reportException(method: string, err: Error | string, data: object = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
if (err instanceof ExpectedError) {
this.reportExpectedException(method, err, data);
return;
}
let error =
err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
let exceptionTelemetryObj: appInsights.Contracts.ExceptionTelemetry = {
exception: this.maskFilePaths(error),
properties: {},
};
Object.entries({
Succeeded: false,
Method: method,
ExpectedError: false,
...this.defaultData,
...data,
deviceID: this.options.deviceID,
}).forEach((entry) => {
exceptionTelemetryObj.properties[entry[0]] = JSON.stringify(entry[1]);
});
this.usageDataClient.trackException(exceptionTelemetryObj);
this.exceptionsSent++;
} catch (e) {
this.reportError("reportException", e);
throw e;
}
}
}
/**
* Reports custom expected exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
public reportExpectedException(method: string, err: Error | string, data: object = {}) {
let error =
err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
this.maskFilePaths(error);
const errorMessage = error instanceof Error ? error.message : error;
this.sendUsageDataEvent({
Succeeded: true,
Method: method,
ExpectedError: true,
Error: errorMessage,
...data,
});
}
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
*/
public reportSuccess(method: string, data: object = {}) {
this.sendUsageDataEvent({
Succeeded: true,
Method: method,
ExpectedError: false,
...data,
});
}
/**
* Reports custom exception event object to Application Insights
* @param method Method name sent to Application Insights
* @param err Error or message about error sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportUnexpectedError` instead.
*/
public sendUsageDataException(method: string, err: Error | string, data: object = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
let error =
err instanceof Error
? Object.create(err)
: new Error(`${this.options.projectName} error: ${err}`);
error.name = this.getEventName();
let exceptionTelemetryObj: appInsights.Contracts.ExceptionTelemetry = {
exception: this.maskFilePaths(error),
properties: {},
};
Object.entries({
Succeeded: false,
Method: method,
...this.defaultData,
...data,
}).forEach((entry) => {
exceptionTelemetryObj.properties[entry[0]] = JSON.stringify(entry[1]);
});
this.usageDataClient.trackException(exceptionTelemetryObj);
this.exceptionsSent++;
} catch (e) {
this.reportError("sendUsageDataException", e);
throw e;
}
}
}
/**
* Reports custom success event object to Application Insights
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportSuccess` instead.
*/
public sendUsageDataSuccessEvent(method: string, data: object = {}) {
this.sendUsageDataEvent({
Succeeded: true,
Method: method,
Pass: true,
...data,
});
}
/**
* Reports custom successful fail event object to Application Insights
* "Successful fail" means that there was an error as a result of user error, but our code worked properly
* @param method Method name sent to Application Insights
* @param data Data object(s) sent to Application Insights
* @deprecated Use `reportExpectedError` instead.
*/
public sendUsageDataSuccessfulFailEvent(method: string, data: object = {}) {
this.sendUsageDataEvent({
Succeeded: true,
Method: method,
Pass: false,
...data,
});
}
/**
* Reports custom event object to Application Insights
* @param data Data object(s) sent to Application Insights
*/
public sendUsageDataEvent(data: object = {}) {
if (this.getUsageDataLevel() === UsageDataLevel.on) {
try {
let eventTelemetryObj = new appInsights.Contracts.EventData();
eventTelemetryObj.name = this.getEventName();
eventTelemetryObj.properties = {
...this.defaultData,
...data,
deviceID: this.options.deviceID,
};
this.usageDataClient.trackEvent(eventTelemetryObj);
this.eventsSent++;
} catch (e) {
this.reportError("sendUsageDataEvent", e);
}
}
}
}
+150
View File
@@ -0,0 +1,150 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import fs from "fs";
import * as defaults from "./defaults";
import { UsageDataLevel } from "./usageData";
import { v4 as uuidv4 } from "uuid";
/**
* Allows developer to check if the program has already prompted before
* @param groupName Group name of the usage data object
* @returns Boolean of whether the program should prompt
*/
export function needToPromptForUsageData(groupName: string): boolean {
return !groupNameExists(groupName);
}
/**
* Allows developer to add or modify a specific property to the group
* @param groupName Group name of property
* @param property Property that will be created or modified
* @param value Property's value that will be assigned
*/
export function modifyUsageDataJsonData(groupName: string, property: any, value: any): void {
try {
if (readUsageDataJsonData()) {
const usageDataJsonData = readUsageDataJsonData();
if (!groupNameExists(groupName)) {
usageDataJsonData.usageDataInstances[groupName] = {
usageDataLevel: String,
};
}
usageDataJsonData.usageDataInstances[groupName][property] = value;
if (!usageDataJsonData.usageDataInstances["deviceID"]) {
usageDataJsonData.usageDataInstances["deviceID"] = uuidv4();
}
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
} else {
let usageDataJsonData = {};
usageDataJsonData[groupName] = value;
usageDataJsonData = { usageDataInstances: usageDataJsonData };
usageDataJsonData = {
usageDataInstances: { [groupName]: { [property]: value }, deviceID: uuidv4() },
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
} catch (err) {
throw new Error(err);
}
}
/**
* Returns the session identifier
* @returns The uuid of the session identifier
*/
export function readDeviceID(): string {
const jsonData = readUsageDataJsonData();
return jsonData?.usageDataInstances.deviceID ?? "";
}
/**
* Reads data from the usage data json config file
* @returns Parsed object from json file if it exists
*/
export function readUsageDataJsonData(): any {
if (fs.existsSync(defaults.usageDataJsonFilePath)) {
const jsonData = fs.readFileSync(defaults.usageDataJsonFilePath, "utf8");
return JSON.parse(jsonData.toString());
}
}
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @returns Whether usage data is enabled specific to the group name
*/
export function readUsageDataLevel(groupName: string): UsageDataLevel {
const jsonData = readUsageDataJsonData();
return jsonData.usageDataInstances[groupName].usageDataLevel;
}
/**
* Returns whether usage data is enabled on the usage data object
* @param groupName Group name to search for in the specified json data
* @param propertyName Property name that will be used to access and return the associated value
* @returns Property of the specific group name
*/
export function readUsageDataObjectProperty(groupName: string, propertyName: string): any {
const jsonData = readUsageDataJsonData();
return jsonData.usageDataInstances[groupName][propertyName];
}
/**
* Writes to usage data config file either appending to already existing file or creating new file
* @param groupName Group name of usage data object
* @param level usageDataLevel Whether user is sending none or full usage data
*/
export function writeUsageDataJsonData(groupName: string, level: UsageDataLevel): void {
if (
fs.existsSync(defaults.usageDataJsonFilePath) &&
fs.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "" &&
fs.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "undefined"
) {
if (groupNameExists(groupName)) {
modifyUsageDataJsonData(groupName, "usageDataLevel", level);
} else {
const usageDataJsonData = readUsageDataJsonData();
usageDataJsonData.usageDataInstances[groupName] = {
usageDataLevel: String,
};
usageDataJsonData.usageDataInstances[groupName].usageDataLevel = level;
if (!usageDataJsonData.usageDataInstances["deviceID"]) {
usageDataJsonData.usageDataInstances["deviceID"] = uuidv4();
}
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
} else {
let usageDataJsonData = {};
usageDataJsonData[groupName] = level;
usageDataJsonData = { usageDataInstances: usageDataJsonData };
usageDataJsonData = {
usageDataInstances: { [groupName]: { ["usageDataLevel"]: level }, deviceID: uuidv4() },
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageDataJsonData, null, 2));
}
}
/**
* Checks to see if the given group name exists in the specified json data
* @param groupName Group name to search for in the specified json data
* @returns Boolean of whether group name exists
*/
export function groupNameExists(groupName: string): boolean {
if (
fs.existsSync(defaults.usageDataJsonFilePath) &&
fs.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "" &&
fs.readFileSync(defaults.usageDataJsonFilePath, "utf8") !== "undefined"
) {
const jsonData = readUsageDataJsonData();
return Object.getOwnPropertyNames(jsonData.usageDataInstances).includes(groupName);
}
return false;
}
/**
* Reads usage data settings from the usage data json config file for a specific group
* @returns Settings for the specified group
*/
export function readUsageDataSettings(groupName = defaults.groupName): object | undefined {
if (fs.existsSync(defaults.usageDataJsonFilePath)) {
return readUsageDataJsonData().usageDataInstances[groupName];
} else {
return undefined;
}
}
+464
View File
@@ -0,0 +1,464 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
import * as appInsights from "applicationinsights";
import assert from "assert";
import fs from "fs";
import { beforeEach, describe, it } from "mocha";
import sinon from "sinon";
import os from "os";
import * as defaults from "../src/defaults";
import * as officeAddinUsageData from "../src/usageData";
import * as jsonData from "../src/usageDataSettings";
import * as log from "../src/log";
import { v4 as uuidv4 } from "uuid";
/* global console */
let addInUsageData: officeAddinUsageData.OfficeAddinUsageData;
const err = new Error(
`this error contains a file path:C:/${os.homedir()}/AppData/Roaming/npm/node_modules/alanced-match/index.js`
);
let usageData: string = "";
const mockDeviceID = uuidv4();
const usageDataObject: officeAddinUsageData.IUsageDataOptions = {
groupName: "office-addin-usage-data",
projectName: "office-addin-usage-data",
instrumentationKey: defaults.instrumentationKeyForOfficeAddinCLITools,
promptQuestion:
"-----------------------------------------\nDo you want to opt-in for usage data?[y/n]\n-----------------------------------------",
raisePrompt: false,
usageDataLevel: officeAddinUsageData.UsageDataLevel.on,
method: officeAddinUsageData.UsageDataReportingMethod.applicationInsights,
isForTesting: true,
deviceID: mockDeviceID,
};
describe("Test office-addin-usage data-package", function () {
this.beforeAll(function () {
try {
if (fs.existsSync(defaults.usageDataJsonFilePath)) {
const fileContent = fs.readFileSync(defaults.usageDataJsonFilePath, "utf8");
if (fileContent) {
usageData = JSON.parse(fileContent) || "";
}
}
} catch {
// do nothing
}
});
this.afterAll(function () {
if (fs.existsSync(defaults.usageDataJsonFilePath) && usageData !== undefined) {
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(usageData, null, 2));
} else if (fs.existsSync(defaults.usageDataJsonFilePath)) {
fs.unlinkSync(defaults.usageDataJsonFilePath);
}
});
beforeEach(function () {
if (fs.existsSync(defaults.usageDataJsonFilePath)) {
fs.unlinkSync(defaults.usageDataJsonFilePath);
}
addInUsageData = new officeAddinUsageData.OfficeAddinUsageData(usageDataObject);
addInUsageData.setUsageDataOn();
});
describe("Test constructor with minimal options", () => {
it("Should successfully construct an OfficeAddInUsageData instance", () => {
assert.doesNotThrow(() => {
new officeAddinUsageData.OfficeAddinUsageData({
isForTesting: true,
usageDataLevel: officeAddinUsageData.UsageDataLevel.off,
projectName: "office-addin-usage-data",
groupName: "TestGroupName",
instrumentationKey: defaults.instrumentationKeyForOfficeAddinCLITools,
});
});
});
});
describe("Test reportEvent method", () => {
it("should track event of object passed in with a project name", () => {
const testEvent = {
Test1: [true, 100],
ScriptType: ["JavaScript", 1],
};
addInUsageData.reportEvent("office-addin-usage-data", testEvent);
assert.equal(addInUsageData.getEventsSent(), 1);
});
});
describe("Test reportError method", () => {
it("should send usage data exception", () => {
addInUsageData.reportError("ReportErrorCheck", err);
assert.equal(addInUsageData.getExceptionsSent(), 1);
});
});
describe("Test promptForUsageData method", () => {
it("Should return 'true' because usageDataJsonFilePath doesn't exist", () => {
// delete officeAddinUsageData.json
if (fs.existsSync(defaults.usageDataJsonFilePath)) {
fs.unlinkSync(defaults.usageDataJsonFilePath);
}
assert.equal(jsonData.needToPromptForUsageData(usageDataObject.groupName as string), true);
});
});
describe("Test promptForUsageData method", () => {
it("Should return 'false' because usageDataJsonFilePath exists and groupName exists in file", () => {
jsonData.writeUsageDataJsonData(
usageDataObject.groupName as string,
usageDataObject.usageDataLevel as officeAddinUsageData.UsageDataLevel
);
assert.equal(jsonData.needToPromptForUsageData(usageDataObject.groupName as string), false);
});
});
describe("Test promptForUsageData method", () => {
it("Should return 'true' because usageDataJsonFilePath exists but groupName doesn't exist on file", () => {
jsonData.writeUsageDataJsonData(
usageDataObject.groupName as string,
usageDataObject.usageDataLevel as officeAddinUsageData.UsageDataLevel
);
assert.equal(jsonData.needToPromptForUsageData("test group name"), true);
});
});
describe("Test usageDataOptIn method", () => {
it("Should write out file with groupName set to true to usageDataJsonFilePath", () => {
addInUsageData.usageDataOptIn(usageDataObject.isForTesting, "y");
const jsonTelemtryData = jsonData.readUsageDataJsonData();
assert.equal(
jsonTelemtryData.usageDataInstances[usageDataObject.groupName as string].usageDataLevel,
usageDataObject.usageDataLevel
);
});
});
describe("Test setUsageDataOff method", () => {
it("should change samplingPercentage to 100, turns usage data on", () => {
addInUsageData.setUsageDataOn();
addInUsageData.setUsageDataOff();
assert.equal(addInUsageData.isUsageDataOn(), false);
});
});
describe("Test setUsageDataOn method", () => {
it("should change samplingPercentage to 100, turns usage data on", () => {
addInUsageData.setUsageDataOff();
addInUsageData.setUsageDataOn();
assert.equal(appInsights.defaultClient.config.samplingPercentage, 100);
});
});
describe("Test isUsageDataOn method", () => {
it("should return true if samplingPercentage is on(100)", () => {
appInsights.defaultClient.config.samplingPercentage = 100;
assert.equal(addInUsageData.isUsageDataOn(), true);
});
it("should return false if samplingPercentage is off(0)", () => {
appInsights.defaultClient.config.samplingPercentage = 0;
assert.equal(addInUsageData.isUsageDataOn(), false);
});
});
describe("Test getUsageDataKey method", () => {
it("should return usage data key", () => {
assert.equal(addInUsageData.getUsageDataKey(), "de0d9e7c-1f46-4552-bc21-4e43e489a015");
});
});
describe("Test getEventsSent method", () => {
it("should return amount of events successfully sent", () => {
addInUsageData.setUsageDataOff();
const testEvent = {
Test1: [true, 100],
ScriptType: ["Java", 1],
};
addInUsageData.reportEvent("office-addin-usage-data", testEvent);
assert.equal(addInUsageData.getEventsSent(), 1);
});
});
describe("Test getExceptionsSent method", () => {
it("should return amount of exceptions successfully sent ", () => {
addInUsageData.setUsageDataOff();
addInUsageData.reportError("TestData", err);
assert.equal(addInUsageData.getExceptionsSent(), 1);
});
});
describe("Test UsageDataLevel method", () => {
it("should return the usage data level of the object", () => {
assert.equal("on", addInUsageData.getUsageDataLevel());
});
});
describe("Test maskFilePaths method", () => {
it("should parse error file paths with slashs", () => {
addInUsageData.setUsageDataOff();
const error = new Error(
`this error contains a file path: C:/${os.homedir()}/AppData/Roaming/npm/node_modules/alanced-match/index.js`
);
const compareError = new Error();
compareError.name = "Error";
compareError.message = "this error contains a file path: <filepath>";
// may throw error if change any part of the top of the test file
compareError.stack = "this error contains a file path: <filepath>";
addInUsageData.maskFilePaths(error);
assert.strictEqual(compareError.name, error.name);
assert.strictEqual(compareError.message, error.message);
assert.strictEqual((error.stack ?? "").includes(compareError.stack), true);
});
it("should parse error file paths with backslashs", () => {
addInUsageData.setUsageDataOff();
const errWithBackslash = new Error(
`this error contains a file path: C:\\Users\\admin\\AppData\\Local\\Temp\\excel file .xlsx`
);
const compareErrorWithBackslash = new Error();
compareErrorWithBackslash.message = "this error contains a file path: <filepath>";
compareErrorWithBackslash.stack = "this error contains a file path: <filepath>";
addInUsageData.maskFilePaths(errWithBackslash);
assert.strictEqual(compareErrorWithBackslash.message, errWithBackslash.message);
assert.strictEqual((errWithBackslash.stack ?? "").includes(compareErrorWithBackslash.stack), true);
});
it("should parse error file paths with slashs and backslashs", () => {
addInUsageData.setUsageDataOff();
const error = new Error(
`this error contains a file path: C:\\Users/\\admin\\AppData\\Local//Temp\\excel_file .xlsx`
);
const compareError = new Error();
compareError.message = "this error contains a file path: <filepath>";
compareError.stack = "this error contains a file path: <filepath>";
addInUsageData.maskFilePaths(error);
assert.strictEqual(compareError.message, error.message);
assert.strictEqual((error.stack ?? "").includes(compareError.stack), true);
});
it("should handle relative paths", () => {
addInUsageData.setUsageDataOff();
const error = new Error(`file path: /this is a file path/path/manifestName.xml`);
const compareError = new Error();
compareError.message = "file path: <filepath>";
compareError.stack = "file path: <filepath>";
addInUsageData.maskFilePaths(error);
assert.strictEqual(compareError.message, error.message);
assert.strictEqual((error.stack ?? "").includes(compareError.stack), true);
});
});
describe("Test modifySetting method", () => {
it("should modify or create specific property to new value", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel }, deviceID: mockDeviceID },
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
const usageDataJsonData = jsonData.readUsageDataJsonData();
const testPropertyName = "testProperty";
usageDataJsonData.usageDataInstances[usageDataObject.groupName as string][testPropertyName] = 0;
jsonData.modifyUsageDataJsonData(usageDataObject.groupName as string, testPropertyName, 0);
assert.equal(JSON.stringify(usageDataJsonData), JSON.stringify(jsonData.readUsageDataJsonData()));
});
});
describe("Test readUsageDataJsonData method", () => {
it("should read and return parsed object object from usage data", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel } },
deviceID: mockDeviceID,
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
assert.equal(JSON.stringify(jsonObject), JSON.stringify(jsonData.readUsageDataJsonData()));
});
});
describe("Test readUsageDataLevel method", () => {
it("should read and return object's usage data level from file", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel } },
deviceID: mockDeviceID,
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
assert.equal(
officeAddinUsageData.UsageDataLevel.on,
jsonData.readUsageDataLevel(usageDataObject.groupName as string)
);
});
});
describe("Test readUsageDataObjectProperty method", () => {
it("should read and return parsed object object from usage data", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel } },
deviceID: mockDeviceID,
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
assert.equal(
officeAddinUsageData.UsageDataLevel.on,
jsonData.readUsageDataObjectProperty(usageDataObject.groupName as string, "usageDataLevel")
);
});
});
describe("Test writeUsageDataJsonData method", () => {
it("should write to already existing file", () => {
fs.writeFileSync(defaults.usageDataJsonFilePath, "");
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel }, deviceID: mockDeviceID },
};
jsonData.writeUsageDataJsonData(
usageDataObject.groupName as string,
usageDataObject.usageDataLevel as officeAddinUsageData.UsageDataLevel
);
assert.equal(
JSON.stringify(jsonObject["usageDataInstances"][usageDataObject.groupName as string], null, 2),
JSON.stringify(
JSON.parse(fs.readFileSync(defaults.usageDataJsonFilePath, "utf8"))["usageDataInstances"][
usageDataObject.groupName as string
],
null,
2
)
);
});
});
describe("Test writeUsageDataJsonData method", () => {
it("should create new existing file with correct format", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel }, deviceID: mockDeviceID },
};
jsonData.writeUsageDataJsonData(
usageDataObject.groupName as string,
usageDataObject.usageDataLevel as officeAddinUsageData.UsageDataLevel
);
assert.equal(
JSON.stringify(jsonObject["usageDataInstances"][usageDataObject.groupName as string], null, 2),
JSON.stringify(
JSON.parse(fs.readFileSync(defaults.usageDataJsonFilePath, "utf8"))["usageDataInstances"][
usageDataObject.groupName as string
],
null,
2
)
);
});
});
describe("Test groupNameExists method", () => {
it("should check if groupName exists", () => {
fs.writeFileSync(defaults.usageDataJsonFilePath, "test");
const usageDataLevel = usageDataObject.usageDataLevel;
let jsonObject = {};
jsonObject[usageDataObject.groupName as string] = usageDataObject.usageDataLevel;
jsonObject = { usageDataInstances: jsonData };
jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel }, deviceID: mockDeviceID },
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
assert.equal(true, jsonData.groupNameExists("office-addin-usage-data"));
});
});
describe("Test readUsageDataSettings method", () => {
it("should read and return parsed usage data object group settings", () => {
const usageDataLevel = usageDataObject.usageDataLevel;
const jsonObject = {
usageDataInstances: { [usageDataObject.groupName as string]: { usageDataLevel } },
deviceID: mockDeviceID,
};
fs.writeFileSync(defaults.usageDataJsonFilePath, JSON.stringify(jsonObject));
assert.equal(
JSON.stringify(jsonObject.usageDataInstances[usageDataObject.groupName as string]),
JSON.stringify(jsonData.readUsageDataSettings(usageDataObject.groupName))
);
});
});
describe("Test reportSuccess", () => {
it("should send success events successfully", () => {
addInUsageData.reportSuccess("testMethod-reportSuccess", { TestVal: 42, OtherTestVal: "testing" });
assert.equal(addInUsageData.getEventsSent(), 1);
});
it("should send success events successfully, even when there's no additional data", () => {
addInUsageData.reportSuccess("testMethod-reportSuccess");
assert.equal(addInUsageData.getEventsSent(), 1);
});
});
describe("Test reportExpectedException", () => {
it("should send successful fail events successfully", () => {
addInUsageData.reportExpectedException("testMethod-reportExpectedException", new Error("Test"), {
TestVal: 42,
OtherTestVal: "testing",
});
assert.equal(addInUsageData.getEventsSent(), 1);
});
it("should send successful fail events successfully, even when there's no additional data", () => {
addInUsageData.reportExpectedException("testMethod-reportExpectedException", new Error("Test"));
assert.equal(addInUsageData.getEventsSent(), 1);
});
});
describe("Test sendUsageDataEvent", () => {
it("should send events successfully", () => {
addInUsageData.sendUsageDataEvent({ TestVal: 42, OtherTestVal: "testing" });
assert.equal(addInUsageData.getEventsSent(), 1);
});
it("should send events successfully, even when there's no data", () => {
addInUsageData.sendUsageDataEvent();
assert.equal(addInUsageData.getEventsSent(), 1);
});
});
describe("Test reportException", () => {
it("should send exceptions successfully", () => {
addInUsageData.reportException("testMethod-reportException", new Error("Test"), {
TestVal: 42,
OtherTestVal: "testing",
});
assert.equal(addInUsageData.getExceptionsSent(), 1);
});
it("should send exceptions successfully, even when there's no data", () => {
addInUsageData.reportException("testMethod-reportException", new Error("Test"));
assert.equal(addInUsageData.getExceptionsSent(), 1);
});
});
describe("log.ts", function () {
describe("logErrorMessage()", function () {
it("called with Error", function () {
const spyConsoleError = sinon.spy(console, "error");
const spyConsoleLog = sinon.spy(console, "log");
const message = "This is an error.";
const error = new Error(message);
log.logErrorMessage(error);
assert.ok(spyConsoleError.calledOnceWith(`Error: ${message}`));
assert.ok(spyConsoleLog.notCalled);
spyConsoleError.restore();
spyConsoleLog.restore();
});
it("called with string", function () {
const spyConsoleError = sinon.spy(console, "error");
const spyConsoleLog = sinon.spy(console, "log");
const message = "This is the error message.";
log.logErrorMessage(message);
assert.ok(spyConsoleError.calledOnceWith(`Error: ${message}`));
assert.ok(spyConsoleLog.notCalled);
spyConsoleError.restore();
spyConsoleLog.restore();
});
});
});
});
+10
View File
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "lib",
"skipLibCheck": true,
"strict": false,
},
"include": ["src/**/*"],
"exclude": ["lib", "node_modules"],
}