Initial commit

This commit is contained in:
2025-03-07 19:22:02 +01:00
commit 4a98255d83
55743 changed files with 5280367 additions and 0 deletions
+78
View File
@@ -0,0 +1,78 @@
# Office-Addin-Manifest-Converter
This package provides the ability to convert an XML manifest to JSON manifest for Office add-ins.
## Command-Line Interface
### convert
Convert the Office add-in manifest from XML format to JSON format.
Syntax:
`office-addin-manifest-converter convert <xml-manifest-file> [options]`
Parameter:
`xml-manifest-file`: path to the XML manifest file.
Options:
`-o <string>` or `--output <string>`
Specify the path to an output directory that will contain the generated JSON manifest and related files. If there is no output directory specified, the default directory will have the same name as the input file's base name and be located at the same place of the input file. For example, if the input XML file is _C:\xmlManifests\myAddin.xml_, the default output directory will be _C:\xmlManifests\myAddin_.
`-i` or `--image-download`
Specify that the conversion should download the root images color and outline into the output directory.
`-v` or `--verbose`
Specify that extra log messages should be written to console.
`--schema-override <url>`
The url that property $schema will be set to. Default is the latest public version schema that the converter supports. $schema and manifestVersion (set with --schema-version-override parameter) properties should be in sync.
`--schema-version-override <version>`
The version string that property manifestVersion will be set to. Default is the latest public version that the converter supports (ie \"1.17\" etc). $schema (set with --schema-override parameter) and manifestVersion properties should be in sync.
Example:
After the package has been installed globally, the following command converts the an XML manifest file, _C:\xmlManifests\myAddin.xml_, to json manifest and puts the converted files into _C:\jsonManifests\myAddin_ directory.
`office-addin-manifest-converter convert C:\xmlManifests\myAddin.xml -o C:\jsonManifests\myAddin -iv`
In the command, both `verbose` and `image-download` flags are turned on.
## API Usage
This package provides an API called `convert`. The API takes two required parameters and two optional ones:
```js
convert(inputXmlManifestFile: string, outputJsonManifestFolder: string, imageDownload: boolean = false, verbose: boolean = false);
```
`inputXmlManifestFile`: path of the input XML manifest file.
`outputJsonManifestFolder`: path of the output folder that will contain all generated files, including one JSON manifest file and a few icon files.
`imageDownload`: whether the conversion should download the images into the output directory.
`verbose`: whether extra log messages should be written to console.
The following example converts an XML manifest file, _C:\xmlManifests\myAddin.xml_, to json manifest and puts the converted files into _C:\jsonManifests\myAddin_ folder.
```js
var converter = require("office-addin-manifest-converter");
converter.convert("C:/xmlManifests/myAddin.xml", "C:/jsonManifests/myAddin", true, false);
```
## Versions
0.4.1 - Fix bug for converting four part version format "0.0.0.0" to the three part format used in json manifest ("0.0.0") as specified by https://semver.org/.
0.4.1 - Add support for devpreview ReportPhishingCommandSurface extension point.
+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");
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env node
export {};
//# sourceMappingURL=cli.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":""}
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env node
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const commander_1 = require("commander");
const main = require("./main");
const utilities_1 = require("./utilities");
const program = new commander_1.Command();
program
.name("office-addin-manifest-converter")
.description("CLI to the Office add-in manifest converter, XML to JSON")
.usage("Usage: convert input-xml-manifest-path [--output <output-json-manifest-directory>] [-i] [-v]");
program
.command("convert")
.argument("<xml-manifest-file>")
.combineFlagAndOptionalValue(false)
.option("-o, --output <directory>", "path to the directory where the JSON manifest files will be written to")
.option("-i, --image-download", "the root images color and outline should be downloaded into the output directory")
.option("-v, --verbose", "extra log messages should be written to console")
.option("-d, --debug", "show asserts and other debugging information")
.option("--schema-override <url>", "the url that property $schema will be set to. Default is the latest public version schema that the converter supports. $schema and manifestVersion properties should be in sync.")
.option("--schema-version-override <version>", "the version string that property manifestVersion will be set to. Default is the latest public version that the converter supports (ie \"1.17\" etc). $schema and manifestVersion properties should be in sync.")
.action((xmlManifestFile, options) => __awaiter(void 0, void 0, void 0, function* () {
yield convert(xmlManifestFile, options);
}));
program.parse();
function convert(xmlManifestFile, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
const output = options.output;
const imageDownload = utilities_1.Utilities.isNullOrUndefined(options.imageDownload) ? false : options.imageDownload;
const schemaOverride = utilities_1.Utilities.isNullOrUndefined(options.schemaOverride) ? null : options.schemaOverride;
const schemaVersionOverride = utilities_1.Utilities.isNullOrUndefined(options.schemaVersionOverride) ? null : options.schemaVersionOverride;
const verbose = utilities_1.Utilities.isNullOrUndefined(options.verbose) ? false : options.verbose;
const dbg = utilities_1.Utilities.isNullOrUndefined(options.debug) ? false : options.debug;
utilities_1.Utilities.setShowDebugInfo(dbg);
utilities_1.Utilities.logDebug("Command line: convert " + xmlManifestFile + " " + JSON.stringify(options));
yield main.convert(xmlManifestFile, output, imageDownload, schemaOverride, schemaVersionOverride, verbose).catch((e) => {
utilities_1.Utilities.logError(e);
});
utilities_1.Utilities.log("Convert is complete");
}
catch (err) {
utilities_1.Utilities.logError(err);
}
});
}
//# sourceMappingURL=cli.js.map
File diff suppressed because one or more lines are too long
+196
View File
@@ -0,0 +1,196 @@
export declare class Constants {
static readonly MosActionId = "actionId";
static readonly MosIcons = "icons";
static readonly MosType = "type";
static readonly MosV100 = "1.0";
static readonly MosV101 = "1.1";
static readonly MosView: string;
static readonly MosManifestGAVersion_1_17 = "1.17";
static readonly $Schema: string;
static readonly MosManifestSchemaVersionDevPreview = "https://developer.microsoft.com/json-schemas/teams/vDevPreview/MicrosoftTeams.schema.json#";
static readonly MosManifestLocalizationSchemaVersionDevPreview = "https://developer.microsoft.com/json-schemas/teams/vDevPreview/MicrosoftTeams.Localization.schema.json#";
static readonly MosManifestSchemaVersionDevPreviewOld = "https://raw.githubusercontent.com/OfficeDev/microsoft-teams-app-schema/preview/DevPreview/MicrosoftTeams.schema.json#";
static readonly MosManifestSchemaVersionGA = "https://developer.microsoft.com/json-schemas/teams/v1.17/MicrosoftTeams.schema.json#";
static readonly MosManifestLocalizationSchemaVersionGA = "https://developer.microsoft.com/json-schemas/teams/v1.17/MicrosoftTeams.Localization.schema.json#";
static readonly DocumentRestrictedUser = "Document.Restricted.User";
static readonly DocumentReadAllUser = "Document.ReadAll.User";
static readonly DocumentReadUser = "Document.Read.User";
static readonly DocumentReadWriteUser = "Document.ReadWrite.User";
static readonly DocumentWriteUser = "Document.Write.User";
static readonly MailboxAccessSharedFoldersUser = "Mailbox.AccessSharedFolders.User";
static readonly MailboxItemAppendOnSendUser = "MailboxItem.AppendOnSend.User";
static readonly MailboxItemRestrictedUser = "MailboxItem.Restricted.User";
static readonly MailboxItemReadUser = "MailboxItem.Read.User";
static readonly MailboxItemReadWriteUser = "MailboxItem.ReadWrite.User";
static readonly MailboxReadWriteUser = "Mailbox.ReadWrite.User";
static readonly InputAction = "action";
static readonly InputActionId = "actionId";
static readonly InputAddinCommandsExtensionPoints = "_addinCommandsExtensionPoints";
static readonly InputAppendOnSend = "AppendOnSend";
static readonly InputAppointmentOrganizerCommandSurface = "AppointmentOrganizerCommandSurface";
static readonly InputAppointmentAttendeeCommandSurface = "AppointmentAttendeeCommandSurface";
static readonly InputAutoRunExtensionPoint = "AutoRunExtensionPoint";
static readonly InputButton = "Button";
static readonly InputChildren = "children";
static readonly InputContextMenuCommandSurface = "ContextMenu";
static readonly InputContextMenuText = "ContextMenuText";
static readonly InputContextMenuCell = "ContextMenuCell";
static readonly InputControl = "control";
static readonly InputControlType = "controlType";
static readonly InputDescription = "description";
static readonly InputDescriptionResId = "descriptionResId";
static readonly InputDesktopFormFactor = "DesktopFormFactor";
static readonly InputDesktopSettings = "DesktopSettings";
static readonly InputDocument = "Document";
static readonly InputEnabled = "enabled";
static readonly InputEvents = "events";
static readonly InputExecuteFunction = "ExecuteFunction";
static readonly InputFixedControl = "fixedControl";
static readonly InputFunctionFileResid = "_functionFileResid";
static readonly InputFunctionName = "functionName";
static readonly InputGetStartedNode = "_getStartedNode";
static readonly InputGroup = "group";
static readonly InputIcon = "icon";
static readonly InputIconResId = "iconResId";
static readonly InputId = "id";
static readonly InputImages = "images";
static readonly InputLabel = "label";
static readonly InputLabelResId = "labelResId";
static readonly InputLaunchEvent = "LaunchEvent";
static readonly InputLearnMoreUrl = "learnMoreUrl";
static readonly InputMailHost = "MailHost";
static readonly InputMeetingDetailsOrganizer = "";
static readonly InputMenu = "Menu";
static readonly InputMenuItem = "MenuItem";
static readonly InputMessageComposeCommandSurface = "MessageComposeCommandSurface";
static readonly InputMessageReadCommandSurface = "MessageReadCommandSurface";
static readonly InputMobileAppointmentAttendeeCommandSurface = "MobileAppointmentAttendeeCommandSurface";
static readonly InputMobileAppointmentOrganizerCommandSurface = "MobileAppointmentOrganizerCommandSurface";
static readonly InputMobileLogEventAppointmentAttendee = "MobileLogEventAppointmentAttendee";
static readonly InputMobileMessageComposeCommandSurface = "MobileMessageComposeCommandSurface";
static readonly InputMobileMessageReadCommandSurface = "MobileMessageReadCommandSurface";
static readonly InputMobileOnlineMeetingCommandSurface = "MobileOnlineMeetingCommandSurface";
static readonly InputMobileFormFactor = "MobileFormFactor";
static readonly InputOptions = "options";
static readonly InputOverridenByRibbonApi = "overridenByRibbonApi";
static readonly InputPosition = "position";
static readonly InputPresentation = "Presentation";
static readonly InputPrimaryCommandSurface = "PrimaryCommandSurface";
static readonly InputRequirements = "_requirements";
static readonly InputReportPhishingCommandSurface = "ReportPhishingCommandSurface";
static readonly InputResid = "resid";
static readonly InputScale = "scale";
static readonly InputSendMode = "sendMode";
static readonly InputSendModeBlock = "block";
static readonly InputSendModePromptUser = "promptuser";
static readonly InputSendModeSoftBlock = "softblock";
static readonly InputSets = "sets";
static readonly InputSize = "size";
static readonly InputShowTaskpane = "ShowTaskpane";
static readonly InputSourceLocation = "sourceLocation";
static readonly InputSourceLocationResid = "sourceLocationResid";
static readonly InputSpamFreeTextSectionLabelResId = "spamFreeTextSectionLabelResId";
static readonly InputSpamMoreInfo = "spamMoreInfo";
static readonly InputSpamPreProcessingDialog = "spamPreProcessingDialog";
static readonly InputSpamReportingOptions = "spamReportingOptions";
static readonly InputSupertip = "superTip";
static readonly InputTabletFormFactor = "TabletFormFactor";
static readonly InputTabs = "tabs";
static readonly InputTaskpaneId = "taskpaneId";
static readonly InputTextResId = "textResId";
static readonly InputPinnable = "pinnable";
static readonly InputTitle = "title";
static readonly InputTitleResId = "titleResId";
static readonly InputType = "type";
static readonly InputUrlResId = "urlResId";
static readonly InputWorkbook = "Workbook";
static readonly InputMailBoxCapability = "Mailbox";
static readonly InputAddinCommandCapability = "AddinCommands";
static readonly LegacyMailAppIconSize: number;
static readonly LegacyWXPAppIconSize: number;
static readonly LegacyMailAppHighResolutionIconSize: number;
static readonly LegacyWXPAppHighResolutionIconSize: number;
static readonly DeveloperPrivacyUrl: string;
static readonly DeveloperTermsOfUseUrl: string;
static readonly DeveloperWebSiteUrl: string;
static readonly ExtensionAudienceClaimUrl: string;
static readonly IconsColor: string;
static readonly IconsOutline: string;
static readonly MosDescriptionFull: string;
static readonly MosDescriptionShort: string;
static readonly MosCode: string;
static readonly MosId: string;
static readonly MosNameFull: string;
static readonly MosNameShort: string;
static readonly MosRequirements: string;
static readonly AlternatesHighResolutionIconUrl: string;
static readonly AlternatesIconUrl: string;
static readonly RibbonsFixedControlsLabel: string;
static readonly RibbonsFixedControlsIconsUrl: string;
static readonly RibbonsFixedControlsSuperTipDescription: string;
static readonly RibbonsFixedControlsSuperTipTitle: string;
static readonly RibbonsSpamProcessingDialogDescription: string;
static readonly RibbonsSpamProcessingDialogSpamFreeTextSectionLabel: string;
static readonly RibbonsSpamProcessingDialogTitle: string;
static readonly RibbonsSpamProcessingDialogSpamMoreInfoText: string;
static readonly RibbonsSpamProcessingDialogSpamMoreInfoUrl: string;
static readonly RibbonsSpamProcessingDialogSpamReportingOptionsTitle: string;
static readonly RibbonsSpamProcessingDialogSpamReportingOptionsOptions: string;
static readonly RibbonsTabsLabel: string;
static readonly RibbonsTabsCustomMobileRibbonGroupsLabel: string;
static readonly RibbonsTabsCustomMobileRibbonGroupsControlsLabel: string;
static readonly RibbonsTabsCustomMobileRibbonGroupsControlsIconsUrl: string;
static readonly RibbonsTabsGroupsIconsFile: string;
static readonly RibbonsTabsGroupsIconsUrl: string;
static readonly RibbonsTabsGroupsLabel: string;
static readonly RibbonsTabsGroupsControlsIconsFile: string;
static readonly RibbonsTabsGroupsControlsIconsUrl: string;
static readonly RibbonsTabsGroupsControlsLabel: string;
static readonly RibbonsTabsGroupsControlsSupertipTitle: string;
static readonly RibbonsTabsGroupsControlsSupertipDescription: string;
static readonly RibbonsTabsGroupsControlsItemsIconsFile: string;
static readonly RibbonsTabsGroupsControlsItemsIconsUrl: string;
static readonly RibbonsTabsGroupsControlsItemsLabel: string;
static readonly RibbonsTabsGroupsControlsItemsSupertipTitle: string;
static readonly RibbonsTabsGroupsControlsItemsSupertipDescription: string;
static readonly ContextMenusMenusControlsIconsFile: string;
static readonly ContextMenusMenusControlsIconsUrl: string;
static readonly ContextMenusMenusControlsLabel: string;
static readonly ContextMenusMenusControlsSupertipTitle: string;
static readonly ContextMenusMenusControlsSupertipDescription: string;
static readonly ContextMenusMenusControlsItemsIconsFile: string;
static readonly ContextMenusMenusControlsItemsIconsUrl: string;
static readonly ContextMenusMenusControlsItemsLabel: string;
static readonly ContextMenusMenusControlsItemsSupertipTitle: string;
static readonly ContextMenusMenusControlsItemsSupertipDescription: string;
static readonly ContentRuntimesPage: string;
static readonly RuntimesPage: string;
static readonly RuntimesScript: string;
static readonly RuntimesActionsDisplayName: string;
static readonly DefaultAccessColor: string;
static readonly DefaultDeveloperUrl: string;
static readonly InvalidCharacterInFileName: RegExp;
static readonly RuntimeLifetimeShort: string;
static readonly RuntimeLifetimeLong: string;
static readonly DefaultOutputFolderName: string;
static readonly EllipsisText: string;
static readonly JSONFileSuffix: string;
static readonly JSONManifestFileName: string;
static readonly LoggingPrefix: string;
static readonly LoggingPrefixWarning: string;
static readonly LoggingPrefixError: string;
static readonly MaxResourceStringLengthAny: number;
static readonly MaxResourceStringLength30: number;
static readonly MaxResourceStringLength32: number;
static readonly MaxResourceStringLength64: number;
static readonly MaxResourceStringLength80: number;
static readonly MaxResourceStringLength100: number;
static readonly MaxResourceStringLength128: number;
static readonly MaxResourceStringLength250: number;
static readonly MaxResourceStringLength256: number;
static readonly MaxResourceStringLength512: number;
static readonly MaxResourceStringLength2048: number;
static readonly MaxResourceStringLength4000: number;
static readonly TruncationText: string;
}
//# sourceMappingURL=constants.d.ts.map
File diff suppressed because one or more lines are too long
+200
View File
@@ -0,0 +1,200 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Constants = void 0;
class Constants {
}
exports.Constants = Constants;
Constants.MosActionId = "actionId";
Constants.MosIcons = "icons";
Constants.MosType = "type";
Constants.MosV100 = "1.0";
Constants.MosV101 = "1.1";
Constants.MosView = "view";
Constants.MosManifestGAVersion_1_17 = "1.17";
Constants.$Schema = "$schema";
Constants.MosManifestSchemaVersionDevPreview = "https://developer.microsoft.com/json-schemas/teams/vDevPreview/MicrosoftTeams.schema.json#";
Constants.MosManifestLocalizationSchemaVersionDevPreview = "https://developer.microsoft.com/json-schemas/teams/vDevPreview/MicrosoftTeams.Localization.schema.json#";
Constants.MosManifestSchemaVersionDevPreviewOld = "https://raw.githubusercontent.com/OfficeDev/microsoft-teams-app-schema/preview/DevPreview/MicrosoftTeams.schema.json#";
Constants.MosManifestSchemaVersionGA = "https://developer.microsoft.com/json-schemas/teams/v1.17/MicrosoftTeams.schema.json#";
Constants.MosManifestLocalizationSchemaVersionGA = "https://developer.microsoft.com/json-schemas/teams/v1.17/MicrosoftTeams.Localization.schema.json#";
Constants.DocumentRestrictedUser = "Document.Restricted.User";
Constants.DocumentReadAllUser = "Document.ReadAll.User";
Constants.DocumentReadUser = "Document.Read.User";
Constants.DocumentReadWriteUser = "Document.ReadWrite.User";
Constants.DocumentWriteUser = "Document.Write.User";
Constants.MailboxAccessSharedFoldersUser = "Mailbox.AccessSharedFolders.User";
Constants.MailboxItemAppendOnSendUser = "MailboxItem.AppendOnSend.User";
Constants.MailboxItemRestrictedUser = "MailboxItem.Restricted.User";
Constants.MailboxItemReadUser = "MailboxItem.Read.User";
Constants.MailboxItemReadWriteUser = "MailboxItem.ReadWrite.User";
Constants.MailboxReadWriteUser = "Mailbox.ReadWrite.User";
Constants.InputAction = "action";
Constants.InputActionId = "actionId";
Constants.InputAddinCommandsExtensionPoints = "_addinCommandsExtensionPoints";
Constants.InputAppendOnSend = "AppendOnSend";
Constants.InputAppointmentOrganizerCommandSurface = "AppointmentOrganizerCommandSurface";
Constants.InputAppointmentAttendeeCommandSurface = "AppointmentAttendeeCommandSurface";
Constants.InputAutoRunExtensionPoint = "AutoRunExtensionPoint";
Constants.InputButton = "Button";
Constants.InputChildren = "children";
Constants.InputContextMenuCommandSurface = "ContextMenu";
Constants.InputContextMenuText = "ContextMenuText";
Constants.InputContextMenuCell = "ContextMenuCell";
Constants.InputControl = "control";
Constants.InputControlType = "controlType";
Constants.InputDescription = "description";
Constants.InputDescriptionResId = "descriptionResId";
Constants.InputDesktopFormFactor = "DesktopFormFactor";
Constants.InputDesktopSettings = "DesktopSettings";
Constants.InputDocument = "Document";
Constants.InputEnabled = "enabled";
Constants.InputEvents = "events";
Constants.InputExecuteFunction = "ExecuteFunction";
Constants.InputFixedControl = "fixedControl";
Constants.InputFunctionFileResid = "_functionFileResid";
Constants.InputFunctionName = "functionName";
Constants.InputGetStartedNode = "_getStartedNode";
Constants.InputGroup = "group";
Constants.InputIcon = "icon";
Constants.InputIconResId = "iconResId";
Constants.InputId = "id";
Constants.InputImages = "images";
Constants.InputLabel = "label";
Constants.InputLabelResId = "labelResId";
Constants.InputLaunchEvent = "LaunchEvent";
Constants.InputLearnMoreUrl = "learnMoreUrl";
Constants.InputMailHost = "MailHost";
Constants.InputMeetingDetailsOrganizer = "";
Constants.InputMenu = "Menu";
Constants.InputMenuItem = "MenuItem";
Constants.InputMessageComposeCommandSurface = "MessageComposeCommandSurface";
Constants.InputMessageReadCommandSurface = "MessageReadCommandSurface";
Constants.InputMobileAppointmentAttendeeCommandSurface = "MobileAppointmentAttendeeCommandSurface";
Constants.InputMobileAppointmentOrganizerCommandSurface = "MobileAppointmentOrganizerCommandSurface";
Constants.InputMobileLogEventAppointmentAttendee = "MobileLogEventAppointmentAttendee";
Constants.InputMobileMessageComposeCommandSurface = "MobileMessageComposeCommandSurface";
Constants.InputMobileMessageReadCommandSurface = "MobileMessageReadCommandSurface";
Constants.InputMobileOnlineMeetingCommandSurface = "MobileOnlineMeetingCommandSurface";
Constants.InputMobileFormFactor = "MobileFormFactor";
Constants.InputOptions = "options";
Constants.InputOverridenByRibbonApi = "overridenByRibbonApi";
Constants.InputPosition = "position";
Constants.InputPresentation = "Presentation";
Constants.InputPrimaryCommandSurface = "PrimaryCommandSurface";
Constants.InputRequirements = "_requirements";
Constants.InputReportPhishingCommandSurface = "ReportPhishingCommandSurface";
Constants.InputResid = "resid";
Constants.InputScale = "scale";
Constants.InputSendMode = "sendMode";
Constants.InputSendModeBlock = "block";
Constants.InputSendModePromptUser = "promptuser";
Constants.InputSendModeSoftBlock = "softblock";
Constants.InputSets = "sets";
Constants.InputSize = "size";
Constants.InputShowTaskpane = "ShowTaskpane";
Constants.InputSourceLocation = "sourceLocation";
Constants.InputSourceLocationResid = "sourceLocationResid";
Constants.InputSpamFreeTextSectionLabelResId = "spamFreeTextSectionLabelResId";
Constants.InputSpamMoreInfo = "spamMoreInfo";
Constants.InputSpamPreProcessingDialog = "spamPreProcessingDialog";
Constants.InputSpamReportingOptions = "spamReportingOptions";
Constants.InputSupertip = "superTip";
Constants.InputTabletFormFactor = "TabletFormFactor";
Constants.InputTabs = "tabs";
Constants.InputTaskpaneId = "taskpaneId";
Constants.InputTextResId = "textResId";
Constants.InputPinnable = "pinnable";
Constants.InputTitle = "title";
Constants.InputTitleResId = "titleResId";
Constants.InputType = "type";
Constants.InputUrlResId = "urlResId";
Constants.InputWorkbook = "Workbook";
Constants.InputMailBoxCapability = "Mailbox";
Constants.InputAddinCommandCapability = "AddinCommands";
Constants.LegacyMailAppIconSize = 64;
Constants.LegacyWXPAppIconSize = 32;
Constants.LegacyMailAppHighResolutionIconSize = 128;
Constants.LegacyWXPAppHighResolutionIconSize = 64;
Constants.DeveloperPrivacyUrl = "developer.privacyUrl";
Constants.DeveloperTermsOfUseUrl = "developer.termsOfUseUrl";
Constants.DeveloperWebSiteUrl = "developer.websiteUrl";
Constants.ExtensionAudienceClaimUrl = "extensions[0].audienceClaimUrl";
Constants.IconsColor = "icons.color";
Constants.IconsOutline = "icons.outline";
Constants.MosDescriptionFull = "description.full";
Constants.MosDescriptionShort = "description.short";
Constants.MosCode = "code";
Constants.MosId = "id";
Constants.MosNameFull = "name.full";
Constants.MosNameShort = "name.short";
Constants.MosRequirements = "requirements";
Constants.AlternatesHighResolutionIconUrl = "extensions[0].alternates[%d].alternateIcons.highResolutionIcon.url";
Constants.AlternatesIconUrl = "extensions[0].alternates[%d].alternateIcons.icon.url";
Constants.RibbonsFixedControlsLabel = "extensions[0].ribbons[%d].fixedControls[%d].label";
Constants.RibbonsFixedControlsIconsUrl = "extensions[0].ribbons[%d].fixedControls[%d].icons[%d].url";
Constants.RibbonsFixedControlsSuperTipDescription = "extensions[0].ribbons[%d].fixedControls[%d].supertip.description";
Constants.RibbonsFixedControlsSuperTipTitle = "extensions[0].ribbons[%d].fixedControls[%d].supertip.title";
Constants.RibbonsSpamProcessingDialogDescription = "extensions[0].ribbons[%d].spamPreProcessingDialog.description";
Constants.RibbonsSpamProcessingDialogSpamFreeTextSectionLabel = "extensions[0].ribbons[%d].spamPreProcessingDialog.spamFreeTextSectionLabel";
Constants.RibbonsSpamProcessingDialogTitle = "extensions[0].ribbons[%d].spamPreProcessingDialog.title";
Constants.RibbonsSpamProcessingDialogSpamMoreInfoText = "extensions[0].ribbons[%d].spamPreProcessingDialog.spamMoreInfo.text";
Constants.RibbonsSpamProcessingDialogSpamMoreInfoUrl = "extensions[0].ribbons[%d].spamPreProcessingDialog.spamMoreInfo.url";
Constants.RibbonsSpamProcessingDialogSpamReportingOptionsTitle = "extensions[0].ribbons[%d].spamPreProcessingDialog.spamReportingOptions.title";
Constants.RibbonsSpamProcessingDialogSpamReportingOptionsOptions = "extensions[0].ribbons[%d].spamPreProcessingDialog.spamReportingOptions.options[%d]";
Constants.RibbonsTabsLabel = "extensions[0].ribbons[%d].tabs[%d].label";
Constants.RibbonsTabsCustomMobileRibbonGroupsLabel = "extensions[0].ribbons[%d].tabs[%d].customMobileRibbonGroups[%d].label";
Constants.RibbonsTabsCustomMobileRibbonGroupsControlsLabel = "extensions[0].ribbons[%d].tabs[%d].customMobileRibbonGroups[%d].controls[%d].label";
Constants.RibbonsTabsCustomMobileRibbonGroupsControlsIconsUrl = "extensions[0].ribbons[%d].tabs[%d].customMobileRibbonGroups[%d].controls[%d].icons[%d].url";
Constants.RibbonsTabsGroupsIconsFile = "extensions[0].ribbons[%d].tabs[%d].groups[%d].icons[%d].file";
Constants.RibbonsTabsGroupsIconsUrl = "extensions[0].ribbons[%d].tabs[%d].groups[%d].icons[%d].url";
Constants.RibbonsTabsGroupsLabel = "extensions[0].ribbons[%d].tabs[%d].groups[%d].label";
Constants.RibbonsTabsGroupsControlsIconsFile = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].icons[%d].file";
Constants.RibbonsTabsGroupsControlsIconsUrl = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].icons[%d].url";
Constants.RibbonsTabsGroupsControlsLabel = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].label";
Constants.RibbonsTabsGroupsControlsSupertipTitle = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].supertip.title";
Constants.RibbonsTabsGroupsControlsSupertipDescription = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].supertip.description";
Constants.RibbonsTabsGroupsControlsItemsIconsFile = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].items[%d].icons[%d].file";
Constants.RibbonsTabsGroupsControlsItemsIconsUrl = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].items[%d].icons[%d].url";
Constants.RibbonsTabsGroupsControlsItemsLabel = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].items[%d].label";
Constants.RibbonsTabsGroupsControlsItemsSupertipTitle = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].items[%d].supertip.title";
Constants.RibbonsTabsGroupsControlsItemsSupertipDescription = "extensions[0].ribbons[%d].tabs[%d].groups[%d].controls[%d].items[%d].supertip.description";
Constants.ContextMenusMenusControlsIconsFile = "extensions[0].contextMenus[%d].menus[%d].controls[%d].icons[%d].file";
Constants.ContextMenusMenusControlsIconsUrl = "extensions[0].contextMenus[%d].menus[%d].controls[%d].icons[%d].url";
Constants.ContextMenusMenusControlsLabel = "extensions[0].contextMenus[%d].menus[%d].controls[%d].label";
Constants.ContextMenusMenusControlsSupertipTitle = "extensions[0].contextMenus[%d].menus[%d].controls[%d].supertip.title";
Constants.ContextMenusMenusControlsSupertipDescription = "extensions[0].contextMenus[%d].menus[%d].controls[%d].supertip.description";
Constants.ContextMenusMenusControlsItemsIconsFile = "extensions[0].contextMenus[%d].menus[%d].controls[%d].items[%d].icons[%d].file";
Constants.ContextMenusMenusControlsItemsIconsUrl = "extensions[0].contextMenus[%d].menus[%d].controls[%d].items[%d].icons[%d].url";
Constants.ContextMenusMenusControlsItemsLabel = "extensions[0].contextMenus[%d].menus[%d].controls[%d].items[%d].label";
Constants.ContextMenusMenusControlsItemsSupertipTitle = "extensions[0].contextMenus[%d].menus[%d].controls[%d].items[%d].supertip.title";
Constants.ContextMenusMenusControlsItemsSupertipDescription = "extensions[0].contextMenus[%d].menus[%d].controls[%d].items[%d].supertip.description";
Constants.ContentRuntimesPage = "extensions[0].contentRuntimes[%d].code.page";
Constants.RuntimesPage = "extensions[0].runtimes[%d].code.page";
Constants.RuntimesScript = "extensions[0].runtimes[%d].code.script";
Constants.RuntimesActionsDisplayName = "extensions[0].runtimes[%d].actions[%d].displayName";
Constants.DefaultAccessColor = "#230201";
Constants.DefaultDeveloperUrl = "http://localhost/";
Constants.InvalidCharacterInFileName = /[/\\?*:|"<>]/g;
Constants.RuntimeLifetimeShort = "short";
Constants.RuntimeLifetimeLong = "long";
Constants.DefaultOutputFolderName = "temp";
Constants.EllipsisText = "...";
Constants.JSONFileSuffix = ".json";
Constants.JSONManifestFileName = "manifest.json";
Constants.LoggingPrefix = "[CONVERTER]: ";
Constants.LoggingPrefixWarning = "[CONVERTER]: WARNING: ";
Constants.LoggingPrefixError = "[CONVERTER]: ERROR: ";
Constants.MaxResourceStringLengthAny = -1;
Constants.MaxResourceStringLength30 = 30;
Constants.MaxResourceStringLength32 = 32;
Constants.MaxResourceStringLength64 = 64;
Constants.MaxResourceStringLength80 = 80;
Constants.MaxResourceStringLength100 = 100;
Constants.MaxResourceStringLength128 = 128;
Constants.MaxResourceStringLength250 = 250;
Constants.MaxResourceStringLength256 = 256;
Constants.MaxResourceStringLength512 = 512;
Constants.MaxResourceStringLength2048 = 2048;
Constants.MaxResourceStringLength4000 = 4000;
Constants.TruncationText = "<TRUNCATED>";
//# sourceMappingURL=constants.js.map
File diff suppressed because one or more lines are too long
@@ -0,0 +1,67 @@
import { OSF } from "../lib/osfmos";
import { CommandSurfaceType } from "./converter";
import * as MOS from "./mosManifest";
export declare class ConversionContext {
private _inputFormFactor;
private _hostType;
private _currentFunctionFileResid;
private _currentVersionOverrideNumber;
private _currentVersionOverrideCapabilities;
private _currentRibbonIndex;
private _currentMenuIndex;
private _currentTabIndex;
private _currentGroupIndex;
private _currentCustomMobileGroupIndex;
private _currentControlIndex;
private _currentFixedControlIndex;
private _currentMenuItemIndex;
private _currentIconIndex;
private _currentContextMenuIndex;
private _currentContextMenuMenuIndex;
private _currentContextMenuMenuControlIndex;
private _currentContextMenuMenuControlMenuItemIndex;
private _currentCommandSurfaceType;
private _isInFixedControl;
static UnsetIndex: number;
constructor();
getFormFactor(): string;
setFormFactor(formFactor: string): void;
getManifestHostType(): OSF.ManifestHostType;
setManifestHostType(hostType: OSF.ManifestHostType): void;
getCurrentFunctionFileResid(): string;
setCurrentFunctionFileResid(currentFunctionFileResid: string): void;
getCurrentVersionOverrideCapabilities(): MOS.Capabilities[];
getCurrentVersionOverrideNumber(): OSF.VersionOverridesNumber;
setCurrentVersionOverrideAndCapabilities(versionOverrideNumber: OSF.VersionOverridesNumber, versionOverrideCapabilities: MOS.Capabilities[]): void;
getCurrentRibbonIndex(): number;
setCurrentRibbonIndex(ribbonIndex: number): void;
getCurrentMenuIndex(): number;
setCurrentMenuIndex(menuIndex: number): void;
getCurrentTabIndex(): number;
setCurrentTabIndex(tabIndex: number): void;
getCurrentGroupIndex(): number;
setCurrentGroupIndex(groupIndex: number): void;
getCurrentCustomMobileGroupIndex(): number;
setCurrentCustomMobileGroupIndex(customMobileGroupIndex: number): void;
getCurrentControlIndex(): number;
setCurrentControlIndex(controlIndex: number): void;
getCurrentMenuItemIndex(): number;
setCurrentMenuItemIndex(menuItemIndex: number): void;
setCurrentCommandSurfaceType(commandSurfaceType: CommandSurfaceType): void;
getCurrentContextMenuIndex(): number;
setCurrentContextMenuIndex(contextMenuIndex: number): void;
getCurrentContextMenuMenuIndex(): number;
setCurrentContextMenuMenuIndex(contextMenuMenuIndex: number): void;
getCurrentContextMenuMenuControlIndex(): number;
setCurrentContextMenuMenuControlIndex(contextMenuMenuControlIndex: number): void;
getCurrentContextMenuMenuControlMenuItemIndex(): number;
setCurrentContextMenuMenuControlMenuItemIndex(contextMenuMenuControlMenuItemIndex: number): void;
getCurrentIconIndex(): number;
setCurrentIconIndex(iconIndex: number): void;
getCurrentFixedControlIndex(): number;
setCurrentFixedControlIndex(fixedControlIndex: number): void;
setInFixedControl(isInFixedControl: boolean): void;
isInFixedControl(): boolean;
isInRibbon(): boolean;
}
//# sourceMappingURL=conversionContext.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"conversionContext.d.ts","sourceRoot":"","sources":["../src/conversionContext.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,eAAe,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AACjD,OAAO,KAAK,GAAG,MAAM,eAAe,CAAC;AAGrC,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,gBAAgB,CAAS;IACjC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,yBAAyB,CAAS;IAC1C,OAAO,CAAC,6BAA6B,CAA6B;IAClE,OAAO,CAAC,mCAAmC,CAAqB;IAChE,OAAO,CAAC,mBAAmB,CAAwC;IACnE,OAAO,CAAC,iBAAiB,CAAwC;IACjE,OAAO,CAAC,gBAAgB,CAAwC;IAChE,OAAO,CAAC,kBAAkB,CAAwC;IAClE,OAAO,CAAC,8BAA8B,CAAwC;IAC9E,OAAO,CAAC,oBAAoB,CAAwC;IACpE,OAAO,CAAC,yBAAyB,CAAwC;IAEzE,OAAO,CAAC,qBAAqB,CAAwC;IAErE,OAAO,CAAC,iBAAiB,CAAwC;IAGjE,OAAO,CAAC,wBAAwB,CAAwC;IACxE,OAAO,CAAC,4BAA4B,CAAwC;IAC5E,OAAO,CAAC,mCAAmC,CAAwC;IACnF,OAAO,CAAC,2CAA2C,CAAwC;IAE3F,OAAO,CAAC,0BAA0B,CAA+C;IAEjF,OAAO,CAAC,iBAAiB,CAAkB;IAE3C,OAAc,UAAU,EAAE,MAAM,CAAM;;IAOtC,aAAa,IAAI,MAAM;IAIvB,aAAa,CAAC,UAAU,EAAE,MAAM,GAAG,IAAI;IAIvC,mBAAmB,IAAI,GAAG,CAAC,gBAAgB;IAI3C,mBAAmB,CAAC,QAAQ,EAAE,GAAG,CAAC,gBAAgB,GAAG,IAAI;IAIzD,2BAA2B,IAAI,MAAM;IAIrC,2BAA2B,CAAC,wBAAwB,EAAE,MAAM,GAAG,IAAI;IAInE,qCAAqC,IAAI,GAAG,CAAC,YAAY,EAAE;IAI3D,+BAA+B,IAAI,GAAG,CAAC,sBAAsB;IAI7D,wCAAwC,CACtC,qBAAqB,EAAE,GAAG,CAAC,sBAAsB,EACjD,2BAA2B,EAAE,GAAG,CAAC,YAAY,EAAE,GAC9C,IAAI;IAKP,qBAAqB,IAAI,MAAM;IAI/B,qBAAqB,CAAC,WAAW,EAAE,MAAM;IAIzC,mBAAmB,IAAI,MAAM;IAI7B,mBAAmB,CAAC,SAAS,EAAE,MAAM;IAIrC,kBAAkB,IAAI,MAAM;IAI5B,kBAAkB,CAAC,QAAQ,EAAE,MAAM;IAInC,oBAAoB,IAAI,MAAM;IAI9B,oBAAoB,CAAC,UAAU,EAAE,MAAM;IAIvC,gCAAgC,IAAI,MAAM;IAI1C,gCAAgC,CAAC,sBAAsB,EAAE,MAAM;IAI/D,sBAAsB,IAAI,MAAM;IAIhC,sBAAsB,CAAC,YAAY,EAAE,MAAM;IAI3C,uBAAuB,IAAI,MAAM;IAIjC,uBAAuB,CAAC,aAAa,EAAE,MAAM;IAI7C,4BAA4B,CAAC,kBAAkB,EAAE,kBAAkB;IAKnE,0BAA0B,IAAI,MAAM;IAIpC,0BAA0B,CAAC,gBAAgB,EAAE,MAAM;IAInD,8BAA8B,IAAI,MAAM;IAIxC,8BAA8B,CAAC,oBAAoB,EAAE,MAAM;IAI3D,qCAAqC,IAAI,MAAM;IAI/C,qCAAqC,CAAC,2BAA2B,EAAE,MAAM;IAIzE,6CAA6C,IAAI,MAAM;IAIvD,6CAA6C,CAAC,mCAAmC,EAAE,MAAM;IAIzF,mBAAmB,IAAI,MAAM;IAI7B,mBAAmB,CAAC,SAAS,EAAE,MAAM;IAIrC,2BAA2B,IAAI,MAAM;IAIrC,2BAA2B,CAAC,iBAAiB,EAAE,MAAM;IAIrD,iBAAiB,CAAC,gBAAgB,EAAE,OAAO;IAI3C,gBAAgB;IAIhB,UAAU;CAGX"}
+146
View File
@@ -0,0 +1,146 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConversionContext = void 0;
const converter_1 = require("./converter");
class ConversionContext {
constructor() {
this._currentRibbonIndex = ConversionContext.UnsetIndex;
this._currentMenuIndex = ConversionContext.UnsetIndex;
this._currentTabIndex = ConversionContext.UnsetIndex;
this._currentGroupIndex = ConversionContext.UnsetIndex;
this._currentCustomMobileGroupIndex = ConversionContext.UnsetIndex;
this._currentControlIndex = ConversionContext.UnsetIndex;
this._currentFixedControlIndex = ConversionContext.UnsetIndex;
this._currentMenuItemIndex = ConversionContext.UnsetIndex;
this._currentIconIndex = ConversionContext.UnsetIndex;
this._currentContextMenuIndex = ConversionContext.UnsetIndex;
this._currentContextMenuMenuIndex = ConversionContext.UnsetIndex;
this._currentContextMenuMenuControlIndex = ConversionContext.UnsetIndex;
this._currentContextMenuMenuControlMenuItemIndex = ConversionContext.UnsetIndex;
this._currentCommandSurfaceType = converter_1.CommandSurfaceType.None;
this._isInFixedControl = false;
this._hostType = null;
this._inputFormFactor = null;
}
getFormFactor() {
return this._inputFormFactor;
}
setFormFactor(formFactor) {
this._inputFormFactor = formFactor;
}
getManifestHostType() {
return this._hostType;
}
setManifestHostType(hostType) {
this._hostType = hostType;
}
getCurrentFunctionFileResid() {
return this._currentFunctionFileResid;
}
setCurrentFunctionFileResid(currentFunctionFileResid) {
this._currentFunctionFileResid = currentFunctionFileResid;
}
getCurrentVersionOverrideCapabilities() {
return this._currentVersionOverrideCapabilities;
}
getCurrentVersionOverrideNumber() {
return this._currentVersionOverrideNumber;
}
setCurrentVersionOverrideAndCapabilities(versionOverrideNumber, versionOverrideCapabilities) {
this._currentVersionOverrideNumber = versionOverrideNumber;
this._currentVersionOverrideCapabilities = versionOverrideCapabilities;
}
getCurrentRibbonIndex() {
return this._currentRibbonIndex;
}
setCurrentRibbonIndex(ribbonIndex) {
this._currentRibbonIndex = ribbonIndex;
}
getCurrentMenuIndex() {
return this._currentMenuIndex;
}
setCurrentMenuIndex(menuIndex) {
this._currentMenuIndex = menuIndex;
}
getCurrentTabIndex() {
return this._currentTabIndex;
}
setCurrentTabIndex(tabIndex) {
this._currentTabIndex = tabIndex;
}
getCurrentGroupIndex() {
return this._currentGroupIndex;
}
setCurrentGroupIndex(groupIndex) {
this._currentGroupIndex = groupIndex;
}
getCurrentCustomMobileGroupIndex() {
return this._currentCustomMobileGroupIndex;
}
setCurrentCustomMobileGroupIndex(customMobileGroupIndex) {
this._currentCustomMobileGroupIndex = customMobileGroupIndex;
}
getCurrentControlIndex() {
return this._currentControlIndex;
}
setCurrentControlIndex(controlIndex) {
this._currentControlIndex = controlIndex;
}
getCurrentMenuItemIndex() {
return this._currentMenuItemIndex;
}
setCurrentMenuItemIndex(menuItemIndex) {
this._currentMenuItemIndex = menuItemIndex;
}
setCurrentCommandSurfaceType(commandSurfaceType) {
this._currentCommandSurfaceType = commandSurfaceType;
}
getCurrentContextMenuIndex() {
return this._currentContextMenuIndex;
}
setCurrentContextMenuIndex(contextMenuIndex) {
this._currentContextMenuIndex = contextMenuIndex;
}
getCurrentContextMenuMenuIndex() {
return this._currentContextMenuMenuIndex;
}
setCurrentContextMenuMenuIndex(contextMenuMenuIndex) {
this._currentContextMenuMenuIndex = contextMenuMenuIndex;
}
getCurrentContextMenuMenuControlIndex() {
return this._currentContextMenuMenuControlIndex;
}
setCurrentContextMenuMenuControlIndex(contextMenuMenuControlIndex) {
this._currentContextMenuMenuControlIndex = contextMenuMenuControlIndex;
}
getCurrentContextMenuMenuControlMenuItemIndex() {
return this._currentContextMenuMenuControlMenuItemIndex;
}
setCurrentContextMenuMenuControlMenuItemIndex(contextMenuMenuControlMenuItemIndex) {
this._currentContextMenuMenuControlMenuItemIndex = contextMenuMenuControlMenuItemIndex;
}
getCurrentIconIndex() {
return this._currentIconIndex;
}
setCurrentIconIndex(iconIndex) {
this._currentIconIndex = iconIndex;
}
getCurrentFixedControlIndex() {
return this._currentFixedControlIndex;
}
setCurrentFixedControlIndex(fixedControlIndex) {
this._currentFixedControlIndex = fixedControlIndex;
}
setInFixedControl(isInFixedControl) {
this._isInFixedControl = isInFixedControl;
}
isInFixedControl() {
return this._isInFixedControl;
}
isInRibbon() {
return this._currentCommandSurfaceType == converter_1.CommandSurfaceType.Ribbon;
}
}
exports.ConversionContext = ConversionContext;
ConversionContext.UnsetIndex = -1;
//# sourceMappingURL=conversionContext.js.map
File diff suppressed because one or more lines are too long
+185
View File
@@ -0,0 +1,185 @@
import { OSF } from "../lib/osfmos";
import { LocaleBuilder } from "./localeBuilder";
import * as MOS from "./mosManifest";
import { MosManifest } from "./mosManifest";
export declare enum RuntimeSource {
DefaultSettingSourceLocations = "DefaultSettingsSourceLocations",
ExecuteFunction = "ExecuteFunction",
LaunchEvent = "LaunchEvent",
SharedRuntimes = "SharedRuntimes",
ShowTaskpane = "ShowTaskpane",
ReportPhishing = "ReportPhishing"
}
export declare enum InputRuntimeLifeTime {
Short = 0,
Long = 1
}
export declare enum ResourceType {
AllLocaleImages = "AllLocaleImages",
AllLocaleUrls = "AllLocaleUrls",
AllLocaleLongStrings = "AllLocaleLongStrings",
AllLocaleShortStrings = "AllLocaleShortStrings"
}
export declare enum CommandSurfaceType {
None = "None",
Ribbon = "Ribbon",
ContextMenu = "ContextMenu"
}
export declare class RuntimeRecord {
_resource: string;
_localeResources: {};
_lifetime: MOS.RuntimesLifetime;
_isResId: boolean;
_isCapabilitiesSorted: boolean;
_requirements: MOS.RequirementsExtensionElement;
_source: RuntimeSource;
_manifestHostType: OSF.ManifestHostType;
_versionOverrideCapabilities: MOS.Capabilities[];
_versionOverridesNumber: OSF.VersionOverridesNumber;
_scriptResId: string;
_inputFormFactor: string;
constructor();
sortCapabilities(): void;
getKey(): string;
}
export declare class Converter {
private _addedExecuteFunctions;
private _mosManifest;
private _xmlManifest;
private _localeBuilder;
private _iconBuilder;
private _runtimeLookup;
private _uniqueSuffix;
private _uniqueRuntimeSuffix;
private _uniqueActionSuffix;
private _uniqueViewSuffix;
constructor(inputXml: string, locale: string);
getMosManifest(): MosManifest;
getLocaleBuilder(): LocaleBuilder;
convert(): void;
downloadAndStoreIcons(folderPath: string): Promise<void>;
private getNextUniqueSuffix;
private getNextRuntimeSuffix;
private getNextActionSuffix;
private getNextViewSuffix;
private _populateRoot;
private _populateRootName;
private _populateRootDescription;
private _populateRootIcons;
private _populateDeveloper;
private _populateLocalizationInfo;
private _populateWebApplicationInfos;
private _populateWebApplicationInfoFromMailbox;
private _populateWebApplicationInfoFromContentAndTaskpane;
private _populateRootPermissions;
private _populateRootDevicePermissions;
private _populateAuthorization;
private _populateExtension;
private _populateAlternates;
private _populateAutoRunEvents;
private _populateAutoRunEventsForFormFactor;
private _populateContextMenus;
private _populateGetStartedMessages;
private _fillGetStartedMessagesFromVersionOverrides;
private _populateKeyboards;
private _populateFormSettings;
private _populateExtensionRequirements;
private static _getCapabilitiesFromLegacyRequirementSets;
private _populateRibbonsAndContextMenus;
private _addRuntimeActionLocalizedDisplayNames;
private _addRibbonOrContextMenuForHostType;
private _addRibbonOrContextMenuForManifestSection;
private _populateRibbonAndContextMenuRequirements;
private _addRequirementSubelementScopesFromHost;
private static _mergeInVersionOverrideRequirements;
private static _getMatchingCapability;
private static _capabilitiesContainCapability;
private _populateTab;
private _populateGroups;
private _populateGroup;
private _populateGroupIcons;
private _createUniqueId;
private _createUniqueActionId;
private _createUniqueViewId;
private _populateGroupControls;
private _populateMenuControl;
private _populateMenuItem;
private _populateControlProperties;
private _populateMobileControlProperties;
private _populateMobileControlIcon;
private _populateControlLocalizedField;
private _populateButtonControl;
private _populateControlAction;
private _controlTypeFromString;
private _populateControlIcons;
private _populateControlSupertip;
private _addScopesFromHosts;
private _populateRuntimes;
private _createMosRuntimesFromRuntimeRecords;
private _collectRuntimes;
private _collectRuntimeRecordsFromExtensionPoints;
private _collectRuntimesFromFunctionFiles;
private _addRuntimeRecordForFunctionFileFormFactor;
private static _legacyFormFactorToMOSFormFactor;
private static _isRibbonCommandSurface;
private static _isContextMenuCommandSurface;
private static _isMobileCommandSurface;
private static _isReportPhishingCommandSurface;
private static _getRibbonContextFromCommandSurface;
private static _getFunctionFileResid;
private static _getAddinCommandsExtensionPoints;
private static _cloneRequirements;
private static _cloneCapabilities;
private _addRuntimeForFormFactor;
private _collectRuntimeRecordsFromRuntimes;
private _collectRuntimeRecordsFromActions;
private _createRuntimeRecord;
private _addRuntimeRecord;
private _populateRootRequirements;
private _populateLocaleSensitiveProperty;
private _populateValidDomains;
private _populateStaticTabs;
private _populateComposeExtensions;
private _populateGraphConnector;
private _populateConfigurableTabs;
private _populateBots;
private _populateConnectors;
private _populateActivities;
private _populateMeetingExtensionDefinition;
private _populateSubscriptionOffer;
private _populateShowLoadingIndicator;
private _populateIsFullScreen;
private _populateConfigurableProperties;
private _populateDefaultBlockUntilAdminAction;
private _populatePublisherDocsUrl;
private _populateDefaultInstallScope;
private _populateDefaultGroupCapability;
getOfficeAppManifest(): OSF.Manifest.OfficeAppManifest;
getJSON(): string;
private _getMailHostOverrides;
private _doesHostHaveContentInManifest;
private _getResourceAndWriteLocalizedValues;
private _addConstantResourceForAllSeenLocales;
private static _incrementCurrentRibbonIndex;
private static _formatResourceStringWithVariableNumberParameters;
private _addRuntimeExecuteAction;
private static _getVersionOverrideHostTypeFromOsfManifestHostType;
private static _getCapabilityVersionFromNumericVersion;
private static _getNumericOverrideVersionFromString;
private static _getRequirementsScopeFromManifestHostType;
private static _mosSendModeFromXmlSendMode;
private static _mosPermissionfromXmlPermission;
private static _setVersionOverrideNumberAndCapabilitiesInContext;
private static _clearVersionOverrideNumberAndCapabilitiesInContext;
private static _legacyLaunchEventToMosEventType;
static _generateExecuteActionKey(runtimeKey: string, actionId: string): string;
static _generateRuntimeLookupKey(url: string, lifetime: MOS.RuntimesLifetime, capabilities: MOS.Capabilities[], formFactor?: string, source?: RuntimeSource): string;
static _sortCapabilitiesAlphabatically(capabilities: MOS.Capabilities[]): void;
static _getImplicitCapabilityBasedOnVersionOverrideForHost(hostType: string, versionOverridesIndex: string): MOS.Capabilities;
static _isWXP(hostType: string): boolean;
static _getMailHostVersionOVerrides(): string[];
static _oSFFormFactorToInputFormFactor(osfFormFactor: string): string;
static _inputFormFactorToMOSFormFactor(inputFormFactor: string): MOS.FormFactors;
static _fixVersionFormat(versionString: string): string;
}
//# sourceMappingURL=converter.d.ts.map
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
export declare class IconBuilder {
private _icons;
constructor();
addIconAndGetReference(url: string, getShortNameAndStore: boolean, forRootIcon?: boolean): string;
private _storeIcon;
private static _getFolderPath;
private _getLeafName;
private _getUniqueIconName;
downloadAndStoreIcons(folderPath: string): Promise<void>;
_downloadAndStoreIcon(iconName: string, folderPath: string): Promise<void>;
_createDefaultIconFile(filePath: string, message: string, resolve: any, reject: any): void;
}
//# sourceMappingURL=iconBuilder.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"iconBuilder.d.ts","sourceRoot":"","sources":["../src/iconBuilder.ts"],"names":[],"mappings":"AAQA,qBAAa,WAAW;IACtB,OAAO,CAAC,MAAM,CAAK;;IAMnB,sBAAsB,CAAC,GAAG,EAAE,MAAM,EAAE,oBAAoB,EAAE,OAAO,EAAE,WAAW,GAAE,OAAe,GAAG,MAAM;IAqBxG,OAAO,CAAC,UAAU;IAIlB,OAAO,CAAC,MAAM,CAAC,cAAc;IAmB7B,OAAO,CAAC,YAAY;IAQpB,OAAO,CAAC,kBAAkB;IAwC1B,qBAAqB,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAexD,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAyC1E,sBAAsB,CAAC,QAAQ,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,KAAA,EAAE,MAAM,KAAA,GAAG,IAAI;CAajF"}
+154
View File
@@ -0,0 +1,154 @@
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.IconBuilder = void 0;
const fs = require("fs");
const http = require("http");
const https = require("https");
const util = require("util");
const constants_1 = require("./constants");
const utilities_1 = require("./utilities");
class IconBuilder {
constructor() {
this._icons = {};
}
addIconAndGetReference(url, getShortNameAndStore, forRootIcon = false) {
utilities_1.Utilities.assert(getShortNameAndStore || !forRootIcon, "Root icon must have getShortNameAndStore to be true");
if (!getShortNameAndStore) {
return url;
}
else {
let imageFile = decodeURIComponent(IconBuilder._getFolderPath(url));
if (!forRootIcon || utilities_1.Utilities._downloadImages) {
imageFile = decodeURIComponent(this._getLeafName(url).trim());
imageFile = imageFile.replace(constants_1.Constants.InvalidCharacterInFileName, "-");
imageFile = this._getUniqueIconName(imageFile);
}
this._storeIcon(imageFile, url);
return imageFile;
}
}
_storeIcon(iconName, url) {
this._icons[iconName] = url;
}
static _getFolderPath(url) {
try {
let realUrl = new URL(url);
let path = realUrl.pathname;
if (!!path && path.charAt(0) == "/") {
path = path.substring(1);
}
if (!path) {
path = realUrl.hostname;
}
return path;
}
catch (err) {
return url;
}
}
_getLeafName(url) {
let segments = url.split("/");
utilities_1.Utilities.assert(segments.length > 2, "valid url with segments");
return segments[segments.length - 1].split("?")[0];
}
_getUniqueIconName(iconName) {
if (utilities_1.Utilities.isNullOrUndefined(this._icons[iconName])) {
return iconName;
}
else {
for (var idx = 2; idx < 100; idx++) {
let suffix = "" + idx;
if (idx < 10) {
suffix = "0" + idx;
}
suffix = "_" + suffix;
if (utilities_1.Utilities.isNullOrUndefined(this._icons[iconName + suffix])) {
let fixedIconName = "";
let nameSegments = iconName.split(".");
if (nameSegments.length > 1) {
fixedIconName =
iconName.substring(0, iconName.length - nameSegments[nameSegments.length - 1].length - 1) +
suffix +
"." +
nameSegments[nameSegments.length - 1];
}
if (utilities_1.Utilities.isNullOrUndefined(this._icons[fixedIconName])) {
return fixedIconName;
}
}
}
utilities_1.Utilities.logError("unable to find a non-conflicting icon name: " + iconName);
utilities_1.Utilities.assert(false, "unable to find a non-conflicting icon name: " + iconName);
return null;
}
}
downloadAndStoreIcons(folderPath) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
let promises = [];
for (var iconName in this._icons) {
if (utilities_1.Utilities._downloadImages) {
promises.push(this._downloadAndStoreIcon(iconName, folderPath));
}
else {
utilities_1.Utilities.log(util.format("File download skipped for file: %s url: %s", iconName, this._icons[iconName]));
}
}
yield utilities_1.Utilities.promiseAll(promises, resolve, reject, "downloadAndStoreIcons: Failed");
}));
}
_downloadAndStoreIcon(iconName, folderPath) {
return new Promise((resolve, reject) => {
let iconUrl = this._icons[iconName];
let filePath = folderPath + "/" + iconName;
try {
const url = new URL(iconUrl);
let protocol = url.protocol == "https:" ? https : http;
protocol
.get(iconUrl, (res) => {
if (!res.headers["content-type"] || res.headers["content-type"].match(/image/)) {
const file = fs.createWriteStream(filePath);
res.pipe(file);
file.on("finish", () => {
file.close();
utilities_1.Utilities.log("File downloaded: ", filePath + ", url: " + iconUrl);
});
resolve();
}
else {
this._createDefaultIconFile(filePath, "Failed to get icon file " + iconUrl + " as image", resolve, reject);
}
})
.on("error", (err) => {
this._createDefaultIconFile(filePath, "Failed to get icon file " + iconUrl + ". " + err, resolve, reject);
});
}
catch (ex) {
this._createDefaultIconFile(filePath, "Failed to get icon file " + iconUrl + ". Exception: " + ex, resolve, reject);
}
});
}
_createDefaultIconFile(filePath, message, resolve, reject) {
utilities_1.Utilities.logError(message + ". Default icon will be used.");
let defaultIconEncoded_32x32 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsIAAA7CARUoSoAAAAQ9SURBVFhHxVdfaFtVHP7uTdLaP2tdK7apBQNLU7SadtC1diyzuFXmgw8qY/qmDwrTPe5JQRF8EcSXISgTN6E+bEPFbaLYdesEpX90dEy7VZydoA2USWM7upE09/j7/e65aZrcJPcGYV/zu/fc73fO+b5z7jknjaEIuIsw9f2uoeoZuHxlGqtnnoKiv6anv0XvowM64w9VzcA6Rer0Xuza14vEvj6kvtpLNqpDVQYujL6Jx3d3Qd2m8a9ZVI7i3OhbOusPvg3cug00Jd8Hau8FLMsmqdyUfE9yfuHbwMRnL2JwdxwqTS/CMIRTGQuDu+KUe0me/cCXgeTiCmLpz2nk99CTLb6BOsTunMLS0qp+9gZfBqZGn0NsRx9UVk+9A9pIKrOO2EAffjz+jCa9wbOBa7/OYeiBWSATtAla9ryBZRPzhV8H5YY6ZjE/N2fX8QDPBq6e2Y+2WA+Uxar0IT0zHILZHrS3IHOUa+vqwdXT+6WNF3gyMHPxLJ58eA1Ib7x3sz0Eo+scjNg4zI5azRIywEj3LVz64awmysOTgdT3r6ChPUIzLWN1B3vjtUDroyEcwT/jL9t8BVQ0MPHFEezZ2UIj0+Ly4gsWIUN4ClkLCnuGtuLil0d0sjTKGqDZRGDhDZiN90vfOZHCLSg83Z1zgcpm430wr78ufZRDWQNjRw8jMdgtB01OXIuUh0UHlUKiP4rxY4c1546SBpZXgPDah0Bwi29xmQ2OUBPaUh9guczZVNLA1LED2P5YL9S6Hn2+OBeZK4IjThXow223D8Qx/ckBO+0CVwMLfy4huuUb6o+2F3/hFI7cTdwgLk88B1WDbfVf4wb16QZXA5dOPIvoI3Tk0vHqKl6kX0Kc1wLtiGhPHLOn3I/oIgNXJmcw/OB12gKUchUvUtfiFAXisLSh9QASHb/hl6kZO5WHIgPJ8RfQGonZR24+HHGvC9ERJ3Bf3Ofi2PM2kYdNBia/O4FEHxUyBSKu4iTiis3iNqgtHQiJeBaTYyc1ZyNnIEux+vMh1LV2khY1cOAmbliwFjNQ809IWMm0TpQQp+Au6lo6sTp9ULQc5AxMnHwXI4NhWTQ5uImzSF4VG1yntLiQ3Iz6HtnRJloOxMAdqtP8xztAfauQgnLitNrNcA2M7vMS/LVcSTyXq29B8+9viyZDDJw/+ir6Ew/ZRy6jgngRijipSFEgThxr9O+MkeZrwpg3V7KIZD+lSg1CVBTXNL93NT8MdW04bw0wSotLSKoRkfTHuLliwbhw/JAa7v6JnNVQkitQVBC3QYcMTztBrnKRivaDqzgROm0E05hYGIIZqE3RPBgwAiaRFKGAfQ/ynXm+U4R0XoJ4MwCTOI7NOapr6jL36fTL/ThlCpgKgdAyjOTfKXX5o23o3PovGdT/cArYsS5uQileQ49wA7pyXhuDftz9tdyM3oM3qv9x+v8A+A89FNxU0V8XUQAAAABJRU5ErkJggg==";
let defaultIconDecoded = Buffer.from(defaultIconEncoded_32x32, "base64");
try {
fs.writeFileSync(filePath, defaultIconDecoded, "binary");
resolve();
}
catch (err) {
utilities_1.Utilities.logError("Failed to create default icon file " + filePath + ". Error is: " + err);
reject();
}
}
}
exports.IconBuilder = IconBuilder;
//# sourceMappingURL=iconBuilder.js.map
File diff suppressed because one or more lines are too long
+10
View File
@@ -0,0 +1,10 @@
export declare class LocaleBuilder {
_locales: any;
constructor();
addLocaleString(locale: string, key: string, value: string): void;
getLocaleFileResources(locale: string): object;
getLocales(): Array<string>;
private getLocaleFile;
static fixLocaleCasing(locale: string): string;
}
//# sourceMappingURL=localeBuilder.d.ts.map
@@ -0,0 +1 @@
{"version":3,"file":"localeBuilder.d.ts","sourceRoot":"","sources":["../src/localeBuilder.ts"],"names":[],"mappings":"AAGA,qBAAa,aAAa;IACxB,QAAQ,EAAE,GAAG,CAAC;;IAMd,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAIjE,sBAAsB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAS9C,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC;IAI3B,OAAO,CAAC,aAAa;IAYrB,MAAM,CAAC,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;CAO/C"}
+37
View File
@@ -0,0 +1,37 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocaleBuilder = void 0;
const localeFile_1 = require("./localeFile");
const utilities_1 = require("./utilities");
class LocaleBuilder {
constructor() {
this._locales = {};
}
addLocaleString(locale, key, value) {
this.getLocaleFile(locale).addResource(key, value);
}
getLocaleFileResources(locale) {
locale = LocaleBuilder.fixLocaleCasing(locale);
utilities_1.Utilities.assert(!utilities_1.Utilities.isNullOrUndefined(this._locales[locale]), "requested locale should exist in the manifest: " + locale);
return this.getLocaleFile(locale).getResources();
}
getLocales() {
return Object.keys(this._locales);
}
getLocaleFile(locale) {
locale = LocaleBuilder.fixLocaleCasing(locale);
let localeFile = this._locales[locale];
if (utilities_1.Utilities.isNullOrUndefined(localeFile)) {
localeFile = this._locales[locale] = new localeFile_1.LocaleFile();
}
return localeFile;
}
static fixLocaleCasing(locale) {
if (!utilities_1.Utilities.isNullOrUndefined(locale)) {
return locale.toLowerCase();
}
return locale;
}
}
exports.LocaleBuilder = LocaleBuilder;
//# sourceMappingURL=localeBuilder.js.map
@@ -0,0 +1 @@
{"version":3,"file":"localeBuilder.js","sourceRoot":"","sources":["../src/localeBuilder.ts"],"names":[],"mappings":";;;AAAA,6CAA0C;AAC1C,2CAAwC;AAExC,MAAa,aAAa;IAGxB;QACE,IAAI,CAAC,QAAQ,GAAG,EAAE,CAAC;IACrB,CAAC;IAED,eAAe,CAAC,MAAc,EAAE,GAAW,EAAE,KAAa;QACxD,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,KAAK,CAAC,CAAC;IACrD,CAAC;IAED,sBAAsB,CAAC,MAAc;QACnC,MAAM,GAAG,aAAa,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QAC/C,qBAAS,CAAC,MAAM,CACd,CAAC,qBAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,EACnD,iDAAiD,GAAG,MAAM,CAC3D,CAAC;QACF,OAAO,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,YAAY,EAAE,CAAC;IACnD,CAAC;IAED,UAAU;QACR,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACpC,CAAC;IAEO,aAAa,CAAC,MAAc;QAElC,MAAM,GAAG,aAAa,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QAC/C,IAAI,UAAU,GAAe,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;QAEnD,IAAI,qBAAS,CAAC,iBAAiB,CAAC,UAAU,CAAC,EAAE,CAAC;YAC5C,UAAU,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,GAAG,IAAI,uBAAU,EAAE,CAAC;QACxD,CAAC;QAED,OAAO,UAAU,CAAC;IACpB,CAAC;IAED,MAAM,CAAC,eAAe,CAAC,MAAc;QACnC,IAAI,CAAC,qBAAS,CAAC,iBAAiB,CAAC,MAAM,CAAC,EAAE,CAAC;YACzC,OAAO,MAAM,CAAC,WAAW,EAAE,CAAC;QAC9B,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA3CD,sCA2CC","sourcesContent":["import { LocaleFile } from \"./localeFile\";\nimport { Utilities } from \"./utilities\";\n\nexport class LocaleBuilder {\n _locales: any;\n\n constructor() {\n this._locales = {};\n }\n\n addLocaleString(locale: string, key: string, value: string): void {\n this.getLocaleFile(locale).addResource(key, value);\n }\n\n getLocaleFileResources(locale: string): object {\n locale = LocaleBuilder.fixLocaleCasing(locale);\n Utilities.assert(\n !Utilities.isNullOrUndefined(this._locales[locale]),\n \"requested locale should exist in the manifest: \" + locale,\n );\n return this.getLocaleFile(locale).getResources();\n }\n\n getLocales(): Array<string> {\n return Object.keys(this._locales);\n }\n\n private getLocaleFile(locale: string): LocaleFile {\n // Locales are case insensisive so we make sure that we store them that way\n locale = LocaleBuilder.fixLocaleCasing(locale);\n let localeFile: LocaleFile = this._locales[locale];\n\n if (Utilities.isNullOrUndefined(localeFile)) {\n localeFile = this._locales[locale] = new LocaleFile();\n }\n\n return localeFile;\n }\n\n static fixLocaleCasing(locale: string): string {\n if (!Utilities.isNullOrUndefined(locale)) {\n return locale.toLowerCase();\n }\n\n return locale;\n }\n}\n"]}
+7
View File
@@ -0,0 +1,7 @@
export declare class LocaleFile {
_resources: Object;
constructor();
addResource(key: string, value: string): void;
getResources(): object;
}
//# sourceMappingURL=localeFile.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"localeFile.d.ts","sourceRoot":"","sources":["../src/localeFile.ts"],"names":[],"mappings":"AAGA,qBAAa,UAAU;IACrB,UAAU,EAAE,MAAM,CAAC;;IAOnB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI;IAK7C,YAAY,IAAI,MAAM;CAGvB"}
+20
View File
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.LocaleFile = void 0;
const constants_1 = require("./constants");
const utilities_1 = require("./utilities");
class LocaleFile {
constructor() {
this._resources = {};
this._resources[constants_1.Constants.$Schema] = constants_1.Constants.MosManifestLocalizationSchemaVersionGA;
}
addResource(key, value) {
utilities_1.Utilities.assert(utilities_1.Utilities.isNullOrUndefined(this._resources[key]), "resource should not already have been added");
this._resources[key] = value;
}
getResources() {
return this._resources;
}
}
exports.LocaleFile = LocaleFile;
//# sourceMappingURL=localeFile.js.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"localeFile.js","sourceRoot":"","sources":["../src/localeFile.ts"],"names":[],"mappings":";;;AAAA,2CAAwC;AACxC,2CAAwC;AAExC,MAAa,UAAU;IAGrB;QACE,IAAI,CAAC,UAAU,GAAG,EAAE,CAAC;QACrB,IAAI,CAAC,UAAU,CAAC,qBAAS,CAAC,OAAO,CAAC,GAAG,qBAAS,CAAC,sCAAsC,CAAC;IACxF,CAAC;IAED,WAAW,CAAC,GAAW,EAAE,KAAa;QACpC,qBAAS,CAAC,MAAM,CAAC,qBAAS,CAAC,iBAAiB,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,6CAA6C,CAAC,CAAC;QACnH,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,GAAG,KAAK,CAAC;IAC/B,CAAC;IAED,YAAY;QACV,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;CACF;AAhBD,gCAgBC","sourcesContent":["import { Constants } from \"./constants\";\nimport { Utilities } from \"./utilities\";\n\nexport class LocaleFile {\n _resources: Object;\n\n constructor() {\n this._resources = {};\n this._resources[Constants.$Schema] = Constants.MosManifestLocalizationSchemaVersionGA;\n }\n\n addResource(key: string, value: string): void {\n Utilities.assert(Utilities.isNullOrUndefined(this._resources[key]), \"resource should not already have been added\");\n this._resources[key] = value;\n }\n\n getResources(): object {\n return this._resources;\n }\n}\n"]}
+2
View File
@@ -0,0 +1,2 @@
export declare function convert(inputXmlFilePath: string, outputJsonFolderPath: string, imageDownload?: boolean, schemaOverride?: string, schemaVersionOverride?: string, verbose?: boolean): Promise<void>;
//# sourceMappingURL=main.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":"AAUA,wBAAsB,OAAO,CAC3B,gBAAgB,EAAE,MAAM,EACxB,oBAAoB,EAAE,MAAM,EAC5B,aAAa,GAAE,OAAe,EAC9B,cAAc,GAAE,MAAa,EAC7B,qBAAqB,GAAE,MAAa,EACpC,OAAO,GAAE,OAAe,GACvB,OAAO,CAAC,IAAI,CAAC,CAyDf"}
+83
View File
@@ -0,0 +1,83 @@
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.convert = convert;
const fs = require("fs");
const path = require("path");
const converter_1 = require("./converter");
const constants_1 = require("./constants");
const utilities_1 = require("./utilities");
function initialize() {
utilities_1.Utilities.setUpOSFAppTelemetry();
}
function convert(inputXmlFilePath_1, outputJsonFolderPath_1) {
return __awaiter(this, arguments, void 0, function* (inputXmlFilePath, outputJsonFolderPath, imageDownload = false, schemaOverride = null, schemaVersionOverride = null, verbose = false) {
initialize();
utilities_1.Utilities.setInputXmlFilePath(inputXmlFilePath);
if (utilities_1.Utilities.isNullOrUndefined(imageDownload)) {
imageDownload = false;
}
utilities_1.Utilities.setDownloadImages(imageDownload);
var imageUrls = true;
if (utilities_1.Utilities.isNullOrUndefined(imageUrls)) {
imageUrls = false;
}
utilities_1.Utilities.setWriteImageUrls(imageUrls);
if (utilities_1.Utilities.isNullOrUndefined(verbose)) {
verbose = false;
}
utilities_1.Utilities.setVerbosity(verbose);
if (!utilities_1.Utilities.isNullOrUndefined(schemaOverride)) {
utilities_1.Utilities.setSchemaOverride(schemaOverride);
}
if (!utilities_1.Utilities.isNullOrUndefined(schemaVersionOverride)) {
utilities_1.Utilities.setSchemaVersionOverride(schemaVersionOverride);
}
const inputXml = fs.readFileSync(inputXmlFilePath, "utf8");
let basename = path.basename(inputXmlFilePath);
if (path.extname(basename).toLowerCase() === ".xml") {
basename = basename.slice(0, -4);
}
let outputFolder = outputJsonFolderPath;
if (utilities_1.Utilities.isNullOrUndefined(outputFolder) || outputFolder.trim().length == 0) {
outputFolder = path.dirname(inputXmlFilePath) + "/" + basename;
}
utilities_1.Utilities.ensureFolder(outputFolder);
const converter = new converter_1.Converter(inputXml, "en-US");
yield converter.convert();
yield converter.downloadAndStoreIcons(outputFolder);
yield writeMainManifestFile(converter, outputFolder);
yield writeLocaleFiles(converter, outputFolder);
});
}
function writeMainManifestFile(converter, outputJSONFolderPath) {
return __awaiter(this, void 0, void 0, function* () {
const manifestFilePath = outputJSONFolderPath + "/" + constants_1.Constants.JSONManifestFileName;
utilities_1.Utilities.log("manifest file path: " + manifestFilePath);
const jsonResult = converter.getJSON();
yield utilities_1.Utilities.writeFile(manifestFilePath, JSON.stringify(jsonResult, null, 4), "Error writing file", "Successfully wrote file: " + manifestFilePath);
});
}
function writeLocaleFiles(converter, outputJSONPath) {
return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
let locales = converter.getLocaleBuilder().getLocales();
let promises = [];
utilities_1.Utilities.log("locales seen by legacy parser: " + locales);
for (let i = 0; i < locales.length; i++) {
let locale = locales[i];
let localeFilePath = outputJSONPath + "/" + utilities_1.Utilities.createLocaleFileName(locale);
utilities_1.Utilities.log("locale file path: " + localeFilePath);
promises.push(utilities_1.Utilities.writeFile(localeFilePath, JSON.stringify(converter.getLocaleBuilder().getLocaleFileResources(locale), null, 4), "Error writing file", "Successfully wrote file: " + localeFilePath));
}
yield utilities_1.Utilities.promiseAll(promises, resolve, reject, "writeLocalFiles:Failed");
}));
}
//# sourceMappingURL=main.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+46
View File
@@ -0,0 +1,46 @@
export declare namespace Utils {
function validateParams(params: any, expectedParams: any, ParameterCount?: any): any;
function validateParameter(param: any, expectedParam: any, paramName: any): any;
function validateParameterCount(params: any, expectedParams: any, validateParameterCount: any): any;
function validateParameterType(param: any, expectedType: any, expectedInteger: any, expectedDomElement: any, mayBeNull: any, paramName: any): any;
function getDomainForUrl(url: any): string;
function OverrideMethods(): void;
}
export declare class DomParserProvider {
_defaultNamespace: any;
_namespaceMapping: any;
_xmldoc: any;
constructor(xml: any, xmlNamespaces: any);
addNamespaceMapping(namespacePrefix: any, namespaceUri: any): boolean;
getNamespaceMapping(): any;
selectSingleNode(name: any, contextNode: any): any;
selectNodes(name: any, contextNode: any): any[];
selectNodesByXPath(xpath: any, contextNode: any): any;
_selectNodes(name: any, contextNode: any): any[];
_removeNodePrefix(nodeName: any): any;
getDocumentElement(): any;
}
export declare class XmlProcessor {
_provider: any;
constructor(xml: any, xmlNamespaces: any);
addNamespaceMapping(namespacePrefix: any, namespaceUri: any): any;
getNamespaceMapping(): any;
selectSingleNode(name: any, contextNode: any): any;
selectNodes(name: any, contextNode: any): any;
selectNodesByXPath(xpath: any, contextNode: any): any;
getDocumentElement(): any;
getNodeValue(node: any): any;
getNodeText(node: any): any;
setNodeText(node: any, text: any): boolean;
getNodeXml(node: any): any;
setNodeXml(node: any, xml: any): any;
getNodeNamespaceURI(node: any): any;
getNodePrefix(node: any): any;
getNodeBaseName(node: any): any;
getNodeType(node: any): any;
appendChild(node: any, childXml: any): any;
_getAttributeLocalName(attribute: any): any;
readAttributes(node: any, attributesToRead: any, objectToFill: any): void;
isValidXml(): boolean;
}
//# sourceMappingURL=osfUtils.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"osfUtils.d.ts","sourceRoot":"","sources":["../src/osfUtils.ts"],"names":[],"mappings":"AAaA,yBAAc,KAAK,CAAC;IAClB,SAAgB,cAAc,CAAC,MAAM,KAAA,EAAE,cAAc,KAAA,EAAE,cAAc,CAAC,KAAA,GAAG,GAAG,CAuB3E;IAED,SAAgB,iBAAiB,CAAC,KAAK,KAAA,EAAE,aAAa,KAAA,EAAE,SAAS,KAAA,GAAG,GAAG,CAsCtE;IAED,SAAgB,sBAAsB,CAAC,MAAM,KAAA,EAAE,cAAc,KAAA,EAAE,sBAAsB,KAAA,GAAG,GAAG,CA8B1F;IAED,SAAgB,qBAAqB,CACnC,KAAK,KAAA,EACL,YAAY,KAAA,EACZ,eAAe,KAAA,EACf,kBAAkB,KAAA,EAClB,SAAS,KAAA,EACT,SAAS,KAAA,OA2BV;IAED,SAAgB,eAAe,CAAC,GAAG,KAAA,UAMlC;IAGD,SAAgB,eAAe,SAG9B;CACF;AAED,qBAAa,iBAAiB;IAC5B,iBAAiB,EAAE,GAAG,CAAC;IACvB,iBAAiB,EAAE,GAAG,CAAC;IACvB,OAAO,EAAE,GAAG,CAAC;gBACD,GAAG,KAAA,EAAE,aAAa,KAAA;IAyB9B,mBAAmB,CAAC,eAAe,KAAA,EAAE,YAAY,KAAA;IASjD,mBAAmB,IAAI,GAAG;IAG1B,gBAAgB,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA;IAMlC,WAAW,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA;IAI7B,kBAAkB,CAAC,KAAK,KAAA,EAAE,WAAW,KAAA;IAIrC,YAAY,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA;IAuB9B,iBAAiB,CAAC,QAAQ,KAAA;IAU1B,kBAAkB;CAGnB;AAQD,qBAAa,YAAY;IACvB,SAAS,EAAE,GAAG,CAAC;gBACH,GAAG,KAAA,EAAE,aAAa,KAAA;IAW9B,mBAAmB,CAAC,eAAe,KAAA,EAAE,YAAY,KAAA;IAYjD,mBAAmB,IAAI,GAAG;IAU1B,gBAAgB,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA;IAelC,WAAW,CAAC,IAAI,KAAA,EAAE,WAAW,KAAA;IAe7B,kBAAkB,CAAC,KAAK,KAAA,EAAE,WAAW,KAAA;IAgBrC,kBAAkB;IAUlB,YAAY,CAAC,IAAI,KAAA;IAoBjB,WAAW,CAAC,IAAI,KAAA;IA2BhB,WAAW,CAAC,IAAI,KAAA,EAAE,IAAI,KAAA;IAgCtB,UAAU,CAAC,IAAI,KAAA;IAyBf,UAAU,CAAC,IAAI,KAAA,EAAE,GAAG,KAAA;IAyBpB,mBAAmB,CAAC,IAAI,KAAA;IAYxB,aAAa,CAAC,IAAI,KAAA;IAYlB,eAAe,CAAC,IAAI,KAAA;IA6BpB,WAAW,CAAC,IAAI,KAAA;IAahB,WAAW,CAAC,IAAI,KAAA,EAAE,QAAQ,KAAA;IAqB1B,sBAAsB,CAAC,SAAS,KAAA;IAmBhC,cAAc,CAAC,IAAI,KAAA,EAAE,gBAAgB,KAAA,EAAE,YAAY,KAAA;IAuBnD,UAAU;CAYX"}
+464
View File
@@ -0,0 +1,464 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.XmlProcessor = exports.DomParserProvider = exports.Utils = void 0;
const osfmos_1 = require("../lib/osfmos");
const xmldom_1 = require("@xmldom/xmldom");
var Utils;
(function (Utils) {
function validateParams(params, expectedParams, ParameterCount) {
var e, expectedLength = expectedParams.length;
ParameterCount = ParameterCount || typeof ParameterCount === "undefined";
e = validateParameterCount(params, expectedParams, ParameterCount);
if (e) {
return e;
}
for (var i = 0, l = params.length; i < l; i++) {
var expectedParam = expectedParams[Math.min(i, expectedLength - 1)], paramName = expectedParam.name;
if (expectedParam.parameterArray) {
paramName += "[" + (i - expectedLength + 1) + "]";
}
else if (!ParameterCount && i >= expectedLength) {
break;
}
e = validateParameter(params[i], expectedParam, paramName);
if (e) {
e.popStackFrame();
return e;
}
}
return null;
}
Utils.validateParams = validateParams;
function validateParameter(param, expectedParam, paramName) {
var e, expectedType = expectedParam.type, expectedInteger = !!expectedParam.integer, expectedDomElement = !!expectedParam.domElement, mayBeNull = !!expectedParam.mayBeNull;
e = validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName);
if (e) {
e.popStackFrame();
return e;
}
var expectedElementType = expectedParam.elementType, elementMayBeNull = !!expectedParam.elementMayBeNull;
if (expectedType === Array &&
typeof param !== "undefined" &&
param !== null &&
(expectedElementType || !elementMayBeNull)) {
var expectedElementInteger = !!expectedParam.elementInteger, expectedElementDomElement = !!expectedParam.elementDomElement;
for (var i = 0; i < param.length; i++) {
var elem = param[i];
e = validateParameterType(elem, expectedElementType, expectedElementInteger, expectedElementDomElement, elementMayBeNull, paramName + "[" + i + "]");
if (e) {
e.popStackFrame();
return e;
}
}
}
return null;
}
Utils.validateParameter = validateParameter;
function validateParameterCount(params, expectedParams, validateParameterCount) {
var i, error, expectedLen = expectedParams.length, actualLen = params.length;
if (actualLen < expectedLen) {
var minParams = expectedLen;
for (i = 0; i < expectedLen; i++) {
var param = expectedParams[i];
if (param.optional || param.parameterArray) {
minParams--;
}
}
if (actualLen < minParams) {
error = true;
}
}
else if (validateParameterCount && actualLen > expectedLen) {
error = true;
for (i = 0; i < expectedLen; i++) {
if (expectedParams[i].parameterArray) {
error = false;
break;
}
}
}
if (error) {
var e = osfmos_1.OfficeExt.MsAjaxError.parameterCount();
return e;
}
return null;
}
Utils.validateParameterCount = validateParameterCount;
function validateParameterType(param, expectedType, expectedInteger, expectedDomElement, mayBeNull, paramName) {
var e, i;
if (typeof param === "undefined") {
if (mayBeNull) {
return null;
}
else {
e = osfmos_1.OfficeExt.MsAjaxError.argumentUndefined(paramName);
e.popStackFrame();
return e;
}
}
if (param === null) {
if (mayBeNull) {
return null;
}
else {
e = osfmos_1.OfficeExt.MsAjaxError.argumentNull(paramName);
e.popStackFrame();
return e;
}
}
if (expectedType && !osfmos_1.OfficeExt.MsAjaxTypeHelper.isInstanceOfType(expectedType, param)) {
e = osfmos_1.OfficeExt.MsAjaxError.argumentType(paramName, typeof param, expectedType);
e.popStackFrame();
return e;
}
return null;
}
Utils.validateParameterType = validateParameterType;
function getDomainForUrl(url) {
if (!url) {
return null;
}
var urlObject = osfmos_1.OSF.OUtil.parseUrl(url, true);
return urlObject.protocol + "//" + urlObject.host;
}
Utils.getDomainForUrl = getDomainForUrl;
function OverrideMethods() {
osfmos_1.OSF.XmlProcessor = XmlProcessor;
osfmos_1.OfficeExt.WACUtils.getDomainForUrl = Utils.getDomainForUrl;
}
Utils.OverrideMethods = OverrideMethods;
})(Utils || (exports.Utils = Utils = {}));
class DomParserProvider {
constructor(xml, xmlNamespaces) {
try {
this._xmldoc = new xmldom_1.DOMParser({}).parseFromString(xml, "text/xml");
}
catch (ex) {
console.trace("xml doc creating error:" + ex);
}
this._namespaceMapping = {};
this._defaultNamespace = null;
var namespaces = xmlNamespaces.split(" ");
var matches;
for (var i = 0; i < namespaces.length; ++i) {
matches = /xmlns="([^"]*)"/g.exec(namespaces[i]);
if (matches) {
this._defaultNamespace = matches[1];
continue;
}
matches = /xmlns:([^=]*)="([^"]*)"/g.exec(namespaces[i]);
if (matches) {
this._namespaceMapping[matches[1]] = matches[2];
continue;
}
}
}
addNamespaceMapping(namespacePrefix, namespaceUri) {
var ns = this._namespaceMapping[namespacePrefix];
if (ns) {
return false;
}
else {
this._namespaceMapping[namespacePrefix] = namespaceUri;
return true;
}
}
getNamespaceMapping() {
return this._namespaceMapping;
}
selectSingleNode(name, contextNode) {
var selectedNode = contextNode || this._xmldoc;
var nodes = this._selectNodes(name, selectedNode);
if (nodes.length === 0)
return null;
return nodes[0];
}
selectNodes(name, contextNode) {
var selectedNode = contextNode || this._xmldoc;
return this._selectNodes(name, selectedNode);
}
selectNodesByXPath(xpath, contextNode) {
return null;
}
_selectNodes(name, contextNode) {
var nodes = [];
if (!name)
return nodes;
var nameInfo = name.split(":");
var ns, nodeName;
if (nameInfo.length === 1) {
ns = null;
nodeName = nameInfo[0];
}
else if (nameInfo.length === 2) {
ns = this._namespaceMapping[nameInfo[0]];
nodeName = nameInfo[1];
}
else {
throw osfmos_1.OfficeExt.MsAjaxError.argument("name");
}
if (!contextNode.hasChildNodes)
return nodes;
var childs = contextNode.childNodes;
for (var i = 0; i < childs.length; i++) {
if (nodeName === this._removeNodePrefix(childs[i].nodeName) && ns === childs[i].namespaceURI) {
nodes.push(childs[i]);
}
}
return nodes;
}
_removeNodePrefix(nodeName) {
if (!nodeName)
return null;
var nodeInfo = nodeName.split(":");
if (nodeInfo.length === 1) {
return nodeName;
}
else {
return nodeInfo[1];
}
}
getDocumentElement() {
return this._xmldoc.documentElement;
}
}
exports.DomParserProvider = DomParserProvider;
class XmlProcessor {
constructor(xml, xmlNamespaces) {
var e = Utils.validateParams(arguments, [
{ name: "xml", type: String, mayBeNull: false },
{ name: "xmlNamespaces", type: String, mayBeNull: false },
]);
if (e)
throw e;
this._provider = new DomParserProvider(xml, xmlNamespaces);
}
addNamespaceMapping(namespacePrefix, namespaceUri) {
var e = Utils.validateParams(arguments, [
{ name: "namespacePrefix", type: String, mayBeNull: false },
{ name: "namespaceUri", type: String, mayBeNull: false },
]);
if (e)
throw e;
return this._provider.addNamespaceMapping(namespacePrefix, namespaceUri);
}
getNamespaceMapping() {
var _a;
return (_a = this._provider) === null || _a === void 0 ? void 0 : _a.getNamespaceMapping();
}
selectSingleNode(name, contextNode) {
var e = Utils.validateParams(arguments, [
{ name: "name", type: String, mayBeNull: false },
{ name: "contextNode", mayBeNull: true, optional: true },
]);
if (e)
throw e;
return this._provider.selectSingleNode(name, contextNode);
}
selectNodes(name, contextNode) {
var e = Utils.validateParams(arguments, [
{ name: "name", type: String, mayBeNull: false },
{ name: "contextNode", mayBeNull: true, optional: true },
]);
if (e)
throw e;
return this._provider.selectNodes(name, contextNode);
}
selectNodesByXPath(xpath, contextNode) {
var e = Utils.validateParams(arguments, [
{ name: "xpath", type: String, mayBeNull: false },
{ name: "contextNode", mayBeNull: true, optional: true },
]);
if (e)
throw e;
contextNode = contextNode || this._provider.getDocumentElement();
return this._provider.selectNodesByXPath(xpath, contextNode);
}
getDocumentElement() {
return this._provider.getDocumentElement();
}
getNodeValue(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
var nodeValue;
if (node.text) {
nodeValue = node.text;
}
else {
nodeValue = node.textContent;
}
return nodeValue;
}
getNodeText(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
if (this.getNodeType(node) == 9) {
return this.getNodeText(this.getDocumentElement());
}
var nodeText;
if (node.text) {
nodeText = node.text;
}
else {
nodeText = node.textContent;
}
return nodeText;
}
setNodeText(node, text) {
var e = Utils.validateParams(arguments, [
{ name: "node", type: Object, mayBeNull: false },
{ name: "text", type: String, mayBeNull: false },
]);
if (e)
throw e;
if (this.getNodeType(node) == 9) {
return false;
}
try {
if (node.text) {
node.text = text;
}
else {
node.textContent = text;
}
}
catch (ex) {
return false;
}
return true;
}
getNodeXml(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
var nodeXml;
if (node.xml) {
nodeXml = node.xml;
}
else {
nodeXml = new XMLSerializer().serializeToString(node);
if (this.getNodeType(node) == 2) {
nodeXml = this.getNodeBaseName(node) + '="' + nodeXml + '"';
}
}
return nodeXml;
}
setNodeXml(node, xml) {
var e = Utils.validateParams(arguments, [
{ name: "node", type: Object, mayBeNull: false },
{ name: "xml", type: String, mayBeNull: false },
]);
if (e)
throw e;
var processor = new osfmos_1.OSF.XmlProcessor(xml, "");
if (!processor.isValidXml()) {
return null;
}
var newNode = processor.getDocumentElement();
try {
node.parentNode.replaceChild(newNode, node);
}
catch (ex) {
return null;
}
return newNode;
}
getNodeNamespaceURI(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
return node.namespaceURI;
}
getNodePrefix(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
return node.prefix;
}
getNodeBaseName(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
var nodeBaseName;
if (node.nodeType && (node.nodeType == 1 || node.nodeType == 2)) {
if (node.baseName) {
nodeBaseName = node.baseName;
}
else {
nodeBaseName = node.localName;
}
}
else {
nodeBaseName = node.nodeName;
}
return nodeBaseName;
}
getNodeType(node) {
var e = Utils.validateParams(arguments, [{ name: "node", type: Object, mayBeNull: false }]);
if (e)
throw e;
return node.nodeType;
}
appendChild(node, childXml) {
var e = Utils.validateParams(arguments, [
{ name: "node", type: Object, mayBeNull: false },
{ name: "childXml", type: String, mayBeNull: false },
]);
if (e)
throw e;
var processor = new osfmos_1.OSF.XmlProcessor(childXml, "");
if (!processor.isValidXml()) {
return null;
}
var childNode = processor.getDocumentElement();
node.appendChild(childNode);
return childNode;
}
_getAttributeLocalName(attribute) {
var localName;
if (attribute.localName) {
localName = attribute.localName;
}
else {
localName = attribute.baseName;
}
return localName;
}
readAttributes(node, attributesToRead, objectToFill) {
var e = Utils.validateParams(arguments, [
{ name: "node", type: Object, mayBeNull: false },
{ name: "attributesToRead", type: Object, mayBeNull: false },
{ name: "objectToFill", type: Object, mayBeNull: false },
]);
if (e)
throw e;
var attribute;
var localName;
for (var i = 0; i < node.attributes.length; i++) {
attribute = node.attributes[i];
localName = this._getAttributeLocalName(attribute);
for (var p in attributesToRead) {
if (localName === p) {
objectToFill[attributesToRead[p]] = attribute.value;
}
}
}
}
isValidXml() {
var documentElement = this.getDocumentElement();
if (documentElement == null) {
return false;
}
else if (this._provider._xmldoc.getElementsByTagName("parsererror").length > 0) {
var parser = new xmldom_1.DOMParser();
var errorParse = parser.parseFromString("<", "text/xml");
var parseErrorNS = errorParse.getElementsByTagName("parsererror")[0].namespaceURI;
return this._provider._xmldoc.getElementsByTagNameNS(parseErrorNS, "parsererror").length <= 0;
}
return true;
}
}
exports.XmlProcessor = XmlProcessor;
//# sourceMappingURL=osfUtils.js.map
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+32
View File
@@ -0,0 +1,32 @@
export declare class Utilities {
static isNullOrUndefined(value: any): boolean;
static writeFile(path: string, contents: string, errorText: string, successText: string): Promise<void>;
static writeFileSync(path: string, contents: string, successText: string): Promise<void>;
static ensureFolder(folderPath: string): void;
static _inputXmlFilePath: string;
static setInputXmlFilePath(inputXmlFilePath: string): void;
static _showDebugInfo: boolean;
static setShowDebugInfo(showDebugInfo: boolean): void;
static _verboseLogging: boolean;
static setVerbosity(verbose: boolean): void;
static getVerbosity(): boolean;
static _downloadImages: boolean;
static setDownloadImages(downloadImages: boolean): void;
static _writeImageUrls: boolean;
static setWriteImageUrls(writeImageUrls: boolean): void;
static _schemaOverride: string;
static setSchemaOverride(schemaOverride: string): void;
static _schemaVersionOverride: string;
static setSchemaVersionOverride(schemaVersionOverride: string): void;
static log(message?: any, ...optionalParams: any[]): void;
static logWarning(message?: any, ...optionalParams: any[]): void;
static logError(message?: any, ...optionalParams: any[]): void;
static logDebug(message?: any, ...optionalParams: any[]): void;
static assert(condition: boolean, message?: any, ...optionalParams: any[]): void;
static createLocaleFileName(locale: string): string;
static truncateString(value: string, maxLength: number): string;
static getLimitedString(value: string, maxLength: number, message: string): string;
static setUpOSFAppTelemetry(): void;
static promiseAll(promises: Promise<void>[], resolve: any, reject: any, message: string): Promise<void>;
}
//# sourceMappingURL=utilities.d.ts.map
+1
View File
@@ -0,0 +1 @@
{"version":3,"file":"utilities.d.ts","sourceRoot":"","sources":["../src/utilities.ts"],"names":[],"mappings":"AAMA,qBAAa,SAAS;IACpB,MAAM,CAAC,iBAAiB,CAAC,KAAK,EAAE,GAAG,GAAG,OAAO;IAI7C,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;WAc1F,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM;IAM9E,MAAM,CAAC,YAAY,CAAC,UAAU,EAAE,MAAM;IAMtC,MAAM,CAAC,iBAAiB,EAAE,MAAM,CAAM;IACtC,MAAM,CAAC,mBAAmB,CAAC,gBAAgB,EAAE,MAAM;IAInD,MAAM,CAAC,cAAc,EAAE,OAAO,CAAS;IACvC,MAAM,CAAC,gBAAgB,CAAC,aAAa,EAAE,OAAO;IAI9C,MAAM,CAAC,eAAe,EAAE,OAAO,CAAS;IACxC,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE,OAAO;IAGpC,MAAM,CAAC,YAAY,IAAI,OAAO;IAI9B,MAAM,CAAC,eAAe,EAAE,OAAO,CAAS;IACxC,MAAM,CAAC,iBAAiB,CAAC,cAAc,EAAE,OAAO;IAIhD,MAAM,CAAC,eAAe,EAAE,OAAO,CAAS;IACxC,MAAM,CAAC,iBAAiB,CAAC,cAAc,EAAE,OAAO;IAIhD,MAAM,CAAC,eAAe,EAAE,MAAM,CAAQ;IACtC,MAAM,CAAC,iBAAiB,CAAC,cAAc,EAAE,MAAM,GAAG,IAAI;IAItD,MAAM,CAAC,sBAAsB,EAAE,MAAM,CAAQ;IAC7C,MAAM,CAAC,wBAAwB,CAAC,qBAAqB,EAAE,MAAM,GAAG,IAAI;IAIpE,MAAM,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,OAAA,GAAG,IAAI;IAMlD,MAAM,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,OAAA,GAAG,IAAI;IAMzD,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,OAAA,GAAG,IAAI;IAMvD,MAAM,CAAC,QAAQ,CAAC,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,OAAA,GAAG,IAAI;IAMvD,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,GAAG,cAAc,OAAA,GAAG,IAAI;IAMzE,MAAM,CAAC,oBAAoB,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM;IAInD,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,GAAG,MAAM;IAoB/D,MAAM,CAAC,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM;IAWzE,MAAM,CAAC,oBAAoB,IAAI,IAAI;WAStB,UAAU,CAAC,QAAQ,EAAE,OAAO,CAAC,IAAI,CAAC,EAAE,EAAE,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,MAAM;CAgB9F"}
+151
View File
@@ -0,0 +1,151 @@
"use strict";
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());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Utilities = void 0;
const osfmos_1 = require("../lib/osfmos");
const constants_1 = require("./constants");
const fs = require("fs");
const console_1 = require("console");
class Utilities {
static isNullOrUndefined(value) {
return value === null || value === undefined;
}
static writeFile(path, contents, errorText, successText) {
return new Promise((resolve, reject) => {
fs.writeFile(path, contents, (err) => {
if (err) {
Utilities.logError(errorText, err);
reject(err);
}
else {
Utilities.log(successText);
resolve();
}
});
});
}
static writeFileSync(path, contents, successText) {
return __awaiter(this, void 0, void 0, function* () {
yield fs.writeFileSync(path, contents);
Utilities.log(successText);
});
}
static ensureFolder(folderPath) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
}
static setInputXmlFilePath(inputXmlFilePath) {
Utilities._inputXmlFilePath = inputXmlFilePath;
}
static setShowDebugInfo(showDebugInfo) {
Utilities._showDebugInfo = showDebugInfo;
}
static setVerbosity(verbose) {
Utilities._verboseLogging = verbose;
}
static getVerbosity() {
return Utilities._verboseLogging;
}
static setDownloadImages(downloadImages) {
Utilities._downloadImages = downloadImages;
}
static setWriteImageUrls(writeImageUrls) {
Utilities._writeImageUrls = writeImageUrls;
}
static setSchemaOverride(schemaOverride) {
Utilities._schemaOverride = schemaOverride;
}
static setSchemaVersionOverride(schemaVersionOverride) {
Utilities._schemaVersionOverride = schemaVersionOverride;
}
static log(message, ...optionalParams) {
if (Utilities._verboseLogging) {
console.log(constants_1.Constants.LoggingPrefix + message, ...optionalParams);
}
}
static logWarning(message, ...optionalParams) {
if (Utilities._verboseLogging) {
console.error(constants_1.Constants.LoggingPrefixWarning + message, ...optionalParams);
}
}
static logError(message, ...optionalParams) {
if (Utilities._verboseLogging) {
console.error(constants_1.Constants.LoggingPrefixError + message, ...optionalParams);
}
}
static logDebug(message, ...optionalParams) {
if (Utilities._showDebugInfo) {
console.log(constants_1.Constants.LoggingPrefix + message, ...optionalParams);
}
}
static assert(condition, message, ...optionalParams) {
if (Utilities._showDebugInfo) {
(0, console_1.assert)(condition, message, ...optionalParams);
}
}
static createLocaleFileName(locale) {
return locale + constants_1.Constants.JSONFileSuffix;
}
static truncateString(value, maxLength) {
if (value.length <= maxLength) {
return value;
}
const insertLengths = constants_1.Constants.TruncationText.length + constants_1.Constants.EllipsisText.length;
if (maxLength <= insertLengths) {
if (maxLength <= constants_1.Constants.EllipsisText.length) {
return value;
}
return value.substring(0, maxLength - constants_1.Constants.EllipsisText.length) + constants_1.Constants.EllipsisText;
}
return constants_1.Constants.TruncationText + value.substring(0, maxLength - insertLengths) + constants_1.Constants.EllipsisText;
}
static getLimitedString(value, maxLength, message) {
if (value.length > maxLength) {
Utilities.logWarning(message, maxLength);
return Utilities.truncateString(value, maxLength);
}
else {
return value;
}
}
static setUpOSFAppTelemetry() {
if (Utilities.isNullOrUndefined(osfmos_1.OSF["AppTelemetry"])) {
osfmos_1.OSF["AppTelemetry"] = {};
osfmos_1.OSF["AppTelemetry"]["logAppCommonMessage"] = function (message) {
Utilities.log(message);
};
}
}
static promiseAll(promises, resolve, reject, message) {
return __awaiter(this, void 0, void 0, function* () {
let failedPromises = [];
yield Promise.all(promises.map((p) => p.catch((e) => {
failedPromises.push(e);
})));
if (failedPromises.length > 0) {
reject(new Error(message));
}
else {
resolve();
}
});
}
}
exports.Utilities = Utilities;
Utilities._inputXmlFilePath = "";
Utilities._showDebugInfo = false;
Utilities._verboseLogging = false;
Utilities._downloadImages = false;
Utilities._writeImageUrls = false;
Utilities._schemaOverride = null;
Utilities._schemaVersionOverride = null;
//# sourceMappingURL=utilities.js.map
File diff suppressed because one or more lines are too long
@@ -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
@@ -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;
@@ -0,0 +1,27 @@
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');
// @ts-check
/**
* Expose the root command.
*/
exports = module.exports = new Command();
exports.program = exports; // More explicit access to global command.
// Implicit export of createArgument, createCommand, and createOption.
/**
* Expose classes
*/
exports.Argument = Argument;
exports.Command = Command;
exports.CommanderError = CommanderError;
exports.Help = Help;
exports.InvalidArgumentError = InvalidArgumentError;
exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated
exports.Option = Option;
@@ -0,0 +1,147 @@
const { InvalidArgumentError } = require('./error.js');
// @ts-check
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;
}
/**
* @api private
*/
_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 {any} 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.
*/
argRequired() {
this.required = true;
return this;
}
/**
* Make argument optional.
*/
argOptional() {
this.required = false;
return this;
}
}
/**
* Takes an argument and returns its human readable equivalent for help usage.
*
* @param {Argument} arg
* @return {string}
* @api 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,45 @@
// @ts-check
/**
* CommanderError class
* @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
*/
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
*/
class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param {string} [message] explanation of why argument is invalid
* @constructor
*/
constructor(message) {
super(1, 'commander.invalidArgument', message);
// properly capture stack trace in Node.js
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
}
}
exports.CommanderError = CommanderError;
exports.InvalidArgumentError = InvalidArgumentError;
@@ -0,0 +1,461 @@
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
*/
// @ts-check
// 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.sortSubcommands = false;
this.sortOptions = false;
this.showGlobalOptions = false;
}
/**
* 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);
if (cmd._hasImplicitHelpCommand()) {
// Create a command matching the implicit help command.
const [, helpName, helpArgs] = cmd._helpCommandnameAndArgs.match(/([^ ]+) *(.*)/);
const helpCommand = cmd.createCommand(helpName)
.helpOption(false);
helpCommand.description(cmd._helpCommandDescription);
if (helpArgs) helpCommand.arguments(helpArgs);
visibleCommands.push(helpCommand);
}
if (this.sortSubcommands) {
visibleCommands.sort((a, b) => {
// @ts-ignore: 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);
// Implicit help
const showShortHelpFlag = cmd._hasHelpOption && cmd._helpShortFlag && !cmd._findOption(cmd._helpShortFlag);
const showLongHelpFlag = cmd._hasHelpOption && !cmd._findOption(cmd._helpLongFlag);
if (showShortHelpFlag || showLongHelpFlag) {
let helpOption;
if (!showShortHelpFlag) {
helpOption = cmd.createOption(cmd._helpLongFlag, cmd._helpDescription);
} else if (!showLongHelpFlag) {
helpOption = cmd.createOption(cmd._helpShortFlag, cmd._helpDescription);
} else {
helpOption = cmd.createOption(cmd._helpFlags, cmd._helpDescription);
}
visibleOptions.push(helpOption);
}
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 parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
const visibleOptions = parentCmd.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._args.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._args.find(argument => argument.description)) {
return cmd._args;
}
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._args.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, helper.subcommandTerm(command).length);
}, 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, helper.optionTerm(option).length);
}, 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, helper.optionTerm(option).length);
}, 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, helper.argumentTerm(argument).length);
}, 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 parentCmdNames = '';
for (let parentCmd = cmd.parent; parentCmd; parentCmd = parentCmd.parent) {
parentCmdNames = parentCmd.name() + ' ' + parentCmdNames;
}
return parentCmdNames + cmdName + ' ' + cmd.usage();
}
/**
* Get the description for the command.
*
* @param {Command} cmd
* @returns {string}
*/
commandDescription(cmd) {
// @ts-ignore: 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: 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 extraDescripton = `(${extraInfo.join(', ')})`;
if (argument.description) {
return `${argument.description} ${extraDescripton}`;
}
return extraDescripton;
}
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;
const itemIndentWidth = 2;
const itemSeparatorWidth = 2; // between term and description
function formatItem(term, description) {
if (description) {
const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`;
return helper.wrap(fullText, helpWidth - itemIndentWidth, termWidth + itemSeparatorWidth);
}
return term;
}
function formatList(textArray) {
return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth));
}
// Usage
let output = [`Usage: ${helper.commandUsage(cmd)}`, ''];
// Description
const commandDescription = helper.commandDescription(cmd);
if (commandDescription.length > 0) {
output = output.concat([commandDescription, '']);
}
// Arguments
const argumentList = helper.visibleArguments(cmd).map((argument) => {
return formatItem(helper.argumentTerm(argument), helper.argumentDescription(argument));
});
if (argumentList.length > 0) {
output = output.concat(['Arguments:', formatList(argumentList), '']);
}
// Options
const optionList = helper.visibleOptions(cmd).map((option) => {
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
});
if (optionList.length > 0) {
output = output.concat(['Options:', formatList(optionList), '']);
}
if (this.showGlobalOptions) {
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
return formatItem(helper.optionTerm(option), helper.optionDescription(option));
});
if (globalOptionList.length > 0) {
output = output.concat(['Global Options:', formatList(globalOptionList), '']);
}
}
// Commands
const commandList = helper.visibleCommands(cmd).map((cmd) => {
return formatItem(helper.subcommandTerm(cmd), helper.subcommandDescription(cmd));
});
if (commandList.length > 0) {
output = output.concat(['Commands:', formatList(commandList), '']);
}
return output.join('\n');
}
/**
* 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)
);
}
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*
* @param {string} str
* @param {number} width
* @param {number} indent
* @param {number} [minColumnWidth=40]
* @return {string}
*
*/
wrap(str, width, indent, minColumnWidth = 40) {
// Detect manually wrapped and indented strings by searching for line breaks
// followed by multiple spaces/tabs.
if (str.match(/[\n]\s+/)) return str;
// Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line).
const columnWidth = width - indent;
if (columnWidth < minColumnWidth) return str;
const leadingStr = str.slice(0, indent);
const columnText = str.slice(indent);
const indentString = ' '.repeat(indent);
const regex = new RegExp('.{1,' + (columnWidth - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g');
const lines = columnText.match(regex) || [];
return leadingStr + lines.map((line, i) => {
if (line.slice(-1) === '\n') {
line = line.slice(0, line.length - 1);
}
return ((i > 0) ? indentString : '') + line.trimRight();
}).join('\n');
}
}
exports.Help = Help;
@@ -0,0 +1,326 @@
const { InvalidArgumentError } = require('./error.js');
// @ts-check
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;
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 {any} 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 {any} 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) {
this.implied = Object.assign(this.implied || {}, impliedOptionValues);
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;
}
/**
* @api private
*/
_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 a object attribute key.
*
* @return {string}
* @api private
*/
attributeName() {
return camelcase(this.name().replace(/^no-/, ''));
}
/**
* Check if `arg` matches the short or long flag.
*
* @param {string} arg
* @return {boolean}
* @api private
*/
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}
* @api private
*/
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 {any} 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}
* @api 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>'
*
* @api private
*/
function splitOptionFlags(flags) {
let shortFlag;
let longFlag;
// Use original very loose parsing to maintain backwards compatibility for now,
// which allowed for example unintended `-sw, --short-word` [sic].
const flagParts = flags.split(/[ |,]+/);
if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
longFlag = flagParts.shift();
// Add support for lone short flag without significantly changing parsing!
if (!shortFlag && /^-[^-]$/.test(longFlag)) {
shortFlag = longFlag;
longFlag = undefined;
}
return { shortFlag, longFlag };
}
exports.Option = Option;
exports.splitOptionFlags = splitOptionFlags;
exports.DualOptions = DualOptions;
@@ -0,0 +1,100 @@
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,80 @@
{
"name": "commander",
"version": "9.5.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": "https://github.com/tj/commander.js.git"
},
"scripts": {
"lint": "npm run lint:javascript && npm run lint:typescript",
"lint:javascript": "eslint index.js esm.mjs \"lib/*.js\" \"tests/**/*.js\"",
"lint:typescript": "eslint typings/*.ts tests/*.ts",
"test": "jest && npm run test-typings",
"test-esm": "node --experimental-modules ./tests/esm-imports-test.mjs",
"test-typings": "tsd",
"typescript-checkJS": "tsc --allowJS --checkJS index.js lib/*.js --noEmit",
"test-all": "npm run test && npm run lint && npm run typescript-checkJS && npm run test-esm"
},
"files": [
"index.js",
"lib/*.js",
"esm.mjs",
"typings/index.d.ts",
"package-support.json"
],
"type": "commonjs",
"main": "./index.js",
"exports": {
".": {
"types": "./typings/index.d.ts",
"require": "./index.js",
"import": "./esm.mjs"
},
"./esm.mjs": "./esm.mjs"
},
"devDependencies": {
"@types/jest": "^28.1.4",
"@types/node": "^16.11.15",
"@typescript-eslint/eslint-plugin": "^5.30.6",
"@typescript-eslint/parser": "^5.30.6",
"eslint": "^8.19.0",
"eslint-config-standard": "^17.0.0",
"eslint-config-standard-with-typescript": "^22.0.0",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-jest": "^26.5.3",
"eslint-plugin-n": "^15.2.4",
"eslint-plugin-promise": "^6.0.0",
"jest": "^28.1.2",
"ts-jest": "^28.0.5",
"tsd": "^0.22.0",
"typescript": "^4.7.4"
},
"types": "typings/index.d.ts",
"jest": {
"testEnvironment": "node",
"collectCoverage": true,
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"testPathIgnorePatterns": [
"/node_modules/"
]
},
"engines": {
"node": "^12.20.0 || >=14"
},
"support": true
}
@@ -0,0 +1,891 @@
// Type definitions for commander
// Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
// Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
/* eslint-disable @typescript-eslint/method-signature-style */
/* eslint-disable @typescript-eslint/no-explicit-any */
export class CommanderError extends Error {
code: string;
exitCode: number;
message: string;
nestedError?: string;
/**
* Constructs the CommanderError class
* @param exitCode - suggested exit code which could be used with process.exit
* @param code - an id string representing the error
* @param message - human-readable description of the error
* @constructor
*/
constructor(exitCode: number, code: string, message: string);
}
export class InvalidArgumentError extends CommanderError {
/**
* Constructs the InvalidArgumentError class
* @param message - explanation of why argument is invalid
* @constructor
*/
constructor(message: string);
}
export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
export interface ErrorOptions { // optional parameter for error()
/** an id string representing the error */
code?: string;
/** suggested exit code which could be used with process.exit */
exitCode?: number;
}
export class Argument {
description: string;
required: boolean;
variadic: boolean;
/**
* 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.
*/
constructor(arg: string, description?: string);
/**
* Return argument name.
*/
name(): string;
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default(value: unknown, description?: string): this;
/**
* Set the custom handler for processing CLI command arguments into argument values.
*/
argParser<T>(fn: (value: string, previous: T) => T): this;
/**
* Only allow argument value to be one of choices.
*/
choices(values: readonly string[]): this;
/**
* Make argument required.
*/
argRequired(): this;
/**
* Make argument optional.
*/
argOptional(): this;
}
export class Option {
flags: string;
description: string;
required: boolean; // A value must be supplied when the option is specified.
optional: boolean; // A value is optional when the option is specified.
variadic: boolean;
mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
optionFlags: string;
short?: string;
long?: string;
negate: boolean;
defaultValue?: any;
defaultValueDescription?: string;
parseArg?: <T>(value: string, previous: T) => T;
hidden: boolean;
argChoices?: string[];
constructor(flags: string, description?: string);
/**
* Set the default value, and optionally supply the description to be displayed in the help.
*/
default(value: unknown, description?: string): this;
/**
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
* The custom processing (parseArg) is called.
*
* @example
* ```ts
* new Option('--color').default('GREYSCALE').preset('RGB');
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
* ```
*/
preset(arg: unknown): this;
/**
* Add option name(s) that conflict with this option.
* An error will be displayed if conflicting options are found during parsing.
*
* @example
* ```ts
* new Option('--rgb').conflicts('cmyk');
* new Option('--js').conflicts(['ts', 'jsx']);
* ```
*/
conflicts(names: string | string[]): 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' }));
*/
implies(optionValues: OptionValues): this;
/**
* Set environment variable to check for option value.
*
* An environment variables 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'.
*/
env(name: string): this;
/**
* Calculate the full description, including defaultValue etc.
*/
fullDescription(): string;
/**
* Set the custom handler for processing CLI option arguments into option values.
*/
argParser<T>(fn: (value: string, previous: T) => T): this;
/**
* Whether the option is mandatory and must have a value after parsing.
*/
makeOptionMandatory(mandatory?: boolean): this;
/**
* Hide option in help.
*/
hideHelp(hide?: boolean): this;
/**
* Only allow option value to be one of choices.
*/
choices(values: readonly string[]): this;
/**
* Return option name.
*/
name(): string;
/**
* Return option name, in a camelcase format that can be used
* as a object attribute key.
*/
attributeName(): string;
/**
* Return whether a boolean option.
*
* Options are one of boolean, negated, required argument, or optional argument.
*/
isBoolean(): boolean;
}
export class Help {
/** output helpWidth, long lines are wrapped to fit */
helpWidth?: number;
sortSubcommands: boolean;
sortOptions: boolean;
showGlobalOptions: boolean;
constructor();
/** Get the command term to show in the list of subcommands. */
subcommandTerm(cmd: Command): string;
/** Get the command summary to show in the list of subcommands. */
subcommandDescription(cmd: Command): string;
/** Get the option term to show in the list of options. */
optionTerm(option: Option): string;
/** Get the option description to show in the list of options. */
optionDescription(option: Option): string;
/** Get the argument term to show in the list of arguments. */
argumentTerm(argument: Argument): string;
/** Get the argument description to show in the list of arguments. */
argumentDescription(argument: Argument): string;
/** Get the command usage to be displayed at the top of the built-in help. */
commandUsage(cmd: Command): string;
/** Get the description for the command. */
commandDescription(cmd: Command): string;
/** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
visibleCommands(cmd: Command): Command[];
/** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
visibleOptions(cmd: Command): Option[];
/** Get an array of the visible global options. (Not including help.) */
visibleGlobalOptions(cmd: Command): Option[];
/** Get an array of the arguments which have descriptions. */
visibleArguments(cmd: Command): Argument[];
/** Get the longest command term length. */
longestSubcommandTermLength(cmd: Command, helper: Help): number;
/** Get the longest option term length. */
longestOptionTermLength(cmd: Command, helper: Help): number;
/** Get the longest global option term length. */
longestGlobalOptionTermLength(cmd: Command, helper: Help): number;
/** Get the longest argument term length. */
longestArgumentTermLength(cmd: Command, helper: Help): number;
/** Calculate the pad width from the maximum term length. */
padWidth(cmd: Command, helper: Help): number;
/**
* Wrap the given string to width characters per line, with lines after the first indented.
* Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
*/
wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
/** Generate the built-in help text. */
formatHelp(cmd: Command, helper: Help): string;
}
export type HelpConfiguration = Partial<Help>;
export interface ParseOptions {
from: 'node' | 'electron' | 'user';
}
export interface HelpContext { // optional parameter for .help() and .outputHelp()
error: boolean;
}
export interface AddHelpTextContext { // passed to text function used with .addHelpText()
error: boolean;
command: Command;
}
export interface OutputConfiguration {
writeOut?(str: string): void;
writeErr?(str: string): void;
getOutHelpWidth?(): number;
getErrHelpWidth?(): number;
outputError?(str: string, write: (str: string) => void): void;
}
export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
export type OptionValueSource = 'default' | 'config' | 'env' | 'cli' | 'implied';
export interface OptionValues {
[key: string]: any;
}
export class Command {
args: string[];
processedArgs: any[];
commands: Command[];
parent: Command | null;
constructor(name?: string);
/**
* Set the program version to `str`.
*
* This method auto-registers the "-V, --version" flag
* which will print the version number when passed.
*
* You can optionally supply the flags and description to override the defaults.
*/
version(str: string, flags?: string, description?: string): this;
/**
* Define a command, implemented using an action handler.
*
* @remarks
* The command description is supplied using `.description`, not as a parameter to `.command`.
*
* @example
* ```ts
* program
* .command('clone <source> [destination]')
* .description('clone a repository into a newly created directory')
* .action((source, destination) => {
* console.log('clone command called');
* });
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param opts - configuration options
* @returns new command
*/
command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
/**
* Define a command, implemented in a separate executable file.
*
* @remarks
* The command description is supplied as the second parameter to `.command`.
*
* @example
* ```ts
* program
* .command('start <service>', 'start named service')
* .command('stop [service]', 'stop named service, or all if no name supplied');
* ```
*
* @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
* @param description - description of executable command
* @param opts - configuration options
* @returns `this` command for chaining
*/
command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;
/**
* Factory routine to create a new unattached command.
*
* See .command() for creating an attached subcommand, which uses this routine to
* create the command. You can override createCommand to customise subcommands.
*/
createCommand(name?: string): Command;
/**
* Add a prepared subcommand.
*
* See .command() for creating an attached subcommand which inherits settings from its parent.
*
* @returns `this` command for chaining
*/
addCommand(cmd: Command, opts?: CommandOptions): this;
/**
* Factory routine to create a new unattached argument.
*
* See .argument() for creating an attached argument, which uses this routine to
* create the argument. You can override createArgument to return a custom argument.
*/
createArgument(name: string, description?: string): Argument;
/**
* Define argument syntax for command.
*
* 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.
*
* @example
* ```
* program.argument('<input-file>');
* program.argument('[output-file]');
* ```
*
* @returns `this` command for chaining
*/
argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
argument(name: string, description?: string, defaultValue?: unknown): this;
/**
* Define argument syntax for command, adding a prepared argument.
*
* @returns `this` command for chaining
*/
addArgument(arg: Argument): this;
/**
* Define argument syntax for command, adding multiple at once (without descriptions).
*
* See also .argument().
*
* @example
* ```
* program.arguments('<cmd> [env]');
* ```
*
* @returns `this` command for chaining
*/
arguments(names: string): this;
/**
* Override default decision whether to add implicit help command.
*
* @example
* ```
* addHelpCommand() // force on
* addHelpCommand(false); // force off
* addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details
* ```
*
* @returns `this` command for chaining
*/
addHelpCommand(enableOrNameAndArgs?: string | boolean, description?: string): this;
/**
* Add hook for life cycle event.
*/
hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;
/**
* Register callback to use as replacement for calling process.exit.
*/
exitOverride(callback?: (err: CommanderError) => never | void): this;
/**
* Display error message and exit (or call exitOverride).
*/
error(message: string, errorOptions?: ErrorOptions): never;
/**
* You can customise the help with a subclass of Help by overriding createHelp,
* or by overriding Help properties using configureHelp().
*/
createHelp(): Help;
/**
* You can customise the help by overriding Help properties using configureHelp(),
* or with a subclass of Help by overriding createHelp().
*/
configureHelp(configuration: HelpConfiguration): this;
/** Get configuration */
configureHelp(): HelpConfiguration;
/**
* The default output goes to stdout and stderr. You can customise this for special
* applications. You can also customise the display of errors by overriding outputError.
*
* The configuration properties are all functions:
* ```
* // functions to change where being written, stdout and stderr
* writeOut(str)
* writeErr(str)
* // matching functions to specify width for wrapping help
* getOutHelpWidth()
* getErrHelpWidth()
* // functions based on what is being written out
* outputError(str, write) // used for displaying errors, and not used for displaying help
* ```
*/
configureOutput(configuration: OutputConfiguration): this;
/** Get configuration */
configureOutput(): OutputConfiguration;
/**
* Copy settings that are useful to have in common across root command and subcommands.
*
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
*/
copyInheritedSettings(sourceCommand: Command): this;
/**
* Display the help or a custom message after an error occurs.
*/
showHelpAfterError(displayHelp?: boolean | string): this;
/**
* Display suggestion of similar commands for unknown commands, or options for unknown options.
*/
showSuggestionAfterError(displaySuggestion?: boolean): this;
/**
* Register callback `fn` for the command.
*
* @example
* ```
* program
* .command('serve')
* .description('start service')
* .action(function() {
* // do work here
* });
* ```
*
* @returns `this` command for chaining
*/
action(fn: (...args: any[]) => void | Promise<void>): this;
/**
* Define option with `flags`, `description` and optional
* coercion `fn`.
*
* The `flags` string contains the short and/or long flags,
* separated by comma, a pipe or space. The following are all valid
* all will output this way when `--help` is used.
*
* "-p, --pepper"
* "-p|--pepper"
* "-p --pepper"
*
* @example
* ```
* // simple boolean defaulting to false
* program.option('-p, --pepper', 'add pepper');
*
* --pepper
* program.pepper
* // => Boolean
*
* // simple boolean defaulting to true
* program.option('-C, --no-cheese', 'remove cheese');
*
* program.cheese
* // => true
*
* --no-cheese
* program.cheese
* // => false
*
* // required argument
* program.option('-C, --chdir <path>', 'change the working directory');
*
* --chdir /tmp
* program.chdir
* // => "/tmp"
*
* // optional argument
* program.option('-c, --cheese [type]', 'add cheese [marble]');
* ```
*
* @returns `this` command for chaining
*/
option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
option<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/** @deprecated since v7, instead use choices or a custom function */
option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
/**
* Define a required option, which must have a value after parsing. This usually means
* the option must be specified on the command line. (Otherwise the same as .option().)
*
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
*/
requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
requiredOption<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
/** @deprecated since v7, instead use choices or a custom function */
requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
/**
* Factory routine to create a new unattached option.
*
* See .option() for creating an attached option, which uses this routine to
* create the option. You can override createOption to return a custom option.
*/
createOption(flags: string, description?: string): Option;
/**
* Add a prepared Option.
*
* See .option() and .requiredOption() for creating and attaching an option in a single call.
*/
addOption(option: Option): this;
/**
* Whether to store option values as properties on command object,
* or store separately (specify false). In both cases the option values can be accessed using .opts().
*
* @returns `this` command for chaining
*/
storeOptionsAsProperties<T extends OptionValues>(): this & T;
storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;
storeOptionsAsProperties(storeAsProperties?: boolean): this;
/**
* Retrieve option value.
*/
getOptionValue(key: string): any;
/**
* Store option value.
*/
setOptionValue(key: string, value: unknown): this;
/**
* Store option value and where the value came from.
*/
setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;
/**
* Get source of option value.
*/
getOptionValueSource(key: string): OptionValueSource | undefined;
/**
* Get source of option value. See also .optsWithGlobals().
*/
getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
/**
* Alter parsing of short flags with optional values.
*
* @example
* ```
* // for `.option('-f,--flag [value]'):
* .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
* .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
* ```
*
* @returns `this` command for chaining
*/
combineFlagAndOptionalValue(combine?: boolean): this;
/**
* Allow unknown options on the command line.
*
* @returns `this` command for chaining
*/
allowUnknownOption(allowUnknown?: boolean): this;
/**
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
*
* @returns `this` command for chaining
*/
allowExcessArguments(allowExcess?: boolean): this;
/**
* Enable positional options. Positional means global options are specified before subcommands which lets
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
*
* The default behaviour is non-positional and global options may appear anywhere on the command line.
*
* @returns `this` command for chaining
*/
enablePositionalOptions(positional?: boolean): this;
/**
* Pass through options that come after command-arguments rather than treat them as command-options,
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
* positional options to have been enabled on the program (parent commands).
*
* The default behaviour is non-positional and options may appear before or after command-arguments.
*
* @returns `this` command for chaining
*/
passThroughOptions(passThrough?: boolean): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* @example
* ```
* program.parse(process.argv);
* program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
* ```
*
* @returns `this` command for chaining
*/
parse(argv?: readonly string[], options?: ParseOptions): this;
/**
* Parse `argv`, setting options and invoking commands when defined.
*
* Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
*
* The default expectation is that the arguments are from node and have the application as argv[0]
* and the script being run in argv[1], with user parameters after that.
*
* @example
* ```
* program.parseAsync(process.argv);
* program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
* program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
* ```
*
* @returns Promise
*/
parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>;
/**
* Parse options from `argv` removing known options,
* and return argv split into operands and unknown arguments.
*
* argv => operands, unknown
* --known kkk op => [op], []
* op --known kkk => [op], []
* sub --unknown uuu op => [sub], [--unknown uuu op]
* sub -- --unknown uuu op => [sub --unknown uuu op], []
*/
parseOptions(argv: string[]): ParseOptionsResult;
/**
* Return an object containing local option values as key-value pairs
*/
opts<T extends OptionValues>(): T;
/**
* Return an object containing merged local and global option values as key-value pairs.
*/
optsWithGlobals<T extends OptionValues>(): T;
/**
* Set the description.
*
* @returns `this` command for chaining
*/
description(str: string): this;
/** @deprecated since v8, instead use .argument to add command argument with description */
description(str: string, argsDescription: {[argName: string]: string}): this;
/**
* Get the description.
*/
description(): string;
/**
* Set the summary. Used when listed as subcommand of parent.
*
* @returns `this` command for chaining
*/
summary(str: string): this;
/**
* Get the summary.
*/
summary(): string;
/**
* Set an alias for the command.
*
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
alias(alias: string): this;
/**
* Get alias for the command.
*/
alias(): string;
/**
* Set aliases for the command.
*
* Only the first alias is shown in the auto-generated help.
*
* @returns `this` command for chaining
*/
aliases(aliases: readonly string[]): this;
/**
* Get aliases for the command.
*/
aliases(): string[];
/**
* Set the command usage.
*
* @returns `this` command for chaining
*/
usage(str: string): this;
/**
* Get the command usage.
*/
usage(): string;
/**
* Set the name of the command.
*
* @returns `this` command for chaining
*/
name(str: string): this;
/**
* Get the name of the command.
*/
name(): string;
/**
* Set the name of the command from script filename, such as process.argv[1],
* or require.main.filename, or __filename.
*
* (Used internally and public although not documented in README.)
*
* @example
* ```ts
* program.nameFromFilename(require.main.filename);
* ```
*
* @returns `this` command for chaining
*/
nameFromFilename(filename: string): this;
/**
* Set the directory for searching for executable subcommands of this command.
*
* @example
* ```ts
* program.executableDir(__dirname);
* // or
* program.executableDir('subcommands');
* ```
*
* @returns `this` command for chaining
*/
executableDir(path: string): this;
/**
* Get the executable search directory.
*/
executableDir(): string;
/**
* Output help information for this command.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*
*/
outputHelp(context?: HelpContext): void;
/** @deprecated since v7 */
outputHelp(cb?: (str: string) => string): void;
/**
* Return command help documentation.
*/
helpInformation(context?: HelpContext): string;
/**
* You can pass in flags and a description to override the help
* flags and help description for your command. Pass in false
* to disable the built-in help option.
*/
helpOption(flags?: string | boolean, description?: string): this;
/**
* Output help information and exit.
*
* Outputs built-in help, and custom text added using `.addHelpText()`.
*/
help(context?: HelpContext): never;
/** @deprecated since v7 */
help(cb?: (str: string) => string): never;
/**
* Add additional text to be displayed with the built-in help.
*
* Position is 'before' or 'after' to affect just this command,
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
*/
addHelpText(position: AddHelpTextPosition, text: string): this;
addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;
/**
* Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
*/
on(event: string | symbol, listener: (...args: any[]) => void): this;
}
export interface CommandOptions {
hidden?: boolean;
isDefault?: boolean;
/** @deprecated since v7, replaced by hidden */
noHelp?: boolean;
}
export interface ExecutableCommandOptions extends CommandOptions {
executableFile?: string;
}
export interface ParseOptionsResult {
operands: string[];
unknown: string[];
}
export function createCommand(name?: string): Command;
export function createOption(flags: string, description?: string): Option;
export function createArgument(name: string, description?: string): Argument;
export const program: Command;
+41
View File
@@ -0,0 +1,41 @@
{
"name": "office-addin-manifest-converter",
"version": "0.4.1",
"description": "A tool to convert Microsoft Office add-in manifests from XML format to JSON format.",
"main": "./lib/main.js",
"license": "MIT",
"author": "Microsoft Corp.",
"bin": {
"office-addin-manifest-converter": "./cli.js"
},
"scripts": {
"clean": "rimraf lib",
"prebuild": "rimraf lib && tsc -p src/osf/tsconfig.json && concat-cli -f lib/osfmos.js src/osf/export.js -o lib/osfmos.js && concat-cli -f lib/osfmos.d.ts src/osf/export.d.ts -o lib/osfmos.d.ts",
"build": "tsc"
},
"dependencies": {
"@xmldom/xmldom": "^0.8.5",
"commander": "^9.0.0",
"terser": "^5.29.1"
},
"devDependencies": {
"shared_src": "^1.0.0",
"concat-cli": "^4.0.0",
"@types/xmldom": "^0.1.31",
"@types/node": "*",
"eslint": "^9.2.0",
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"prettier": "^3.2.5"
},
"types": "./lib/main.d.ts",
"directories": {
"lib": "lib"
},
"files": [
"lib",
"README.md",
"cli.js",
"package.json"
]
}