@digitalocean/functions-deployer 5.0.19 → 5.0.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/deploy-struct.ts", "../src/util.ts", "../src/credentials.ts", "../src/runtimes.ts", "../src/triggers.ts", "../src/deploy.ts", "../src/project-reader.ts", "../src/finder-builder.ts", "../src/slice-reader.ts", "../src/file-reader.ts", "../src/includer.ts", "../src/api.ts", "../src/watch.ts", "../src/main.ts", "../src/version.ts"],
4
- "sourcesContent": ["/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Gather together the major deployer exports for convenient import in other packages\n\nexport {\n initializeAPI,\n deployProject,\n readPrepareAndBuild,\n readAndPrepare,\n deploy,\n readProject,\n buildProject,\n prepareToDeploy,\n wipeNamespace,\n getUserAgent\n} from './api';\nexport {\n DeployStructure,\n DeployResponse,\n DeploySuccess,\n OWOptions,\n Credentials,\n CredentialRow,\n Flags,\n PackageSpec,\n ActionSpec,\n CredentialHostMap,\n CredentialNSMap,\n DeployerAnnotation,\n VersionMap,\n Feedback,\n DefaultFeedback,\n FullCredentials,\n IdProvider\n} from './deploy-struct';\nexport {\n addCredentialAndSave,\n getCredentials,\n getCredentialList,\n getCredentialDict,\n getCredentialsForNamespace,\n forgetNamespace,\n switchNamespace,\n getCurrentNamespace,\n getApiHosts,\n Persister,\n authPersister,\n getCredentialsFromEnvironment,\n nimbellaDir\n} from './credentials';\nexport {\n wskRequest,\n delay,\n writeSliceResult,\n getBestProjectName,\n renamePackage,\n getExclusionList,\n isExcluded,\n SYSTEM_EXCLUDE_PATTERNS,\n getRuntimeForAction,\n emptyStructure,\n invokeWebSecure,\n renameActionsToFunctions,\n deleteAction\n} from './util';\nexport * from './runtimes';\nexport { deleteSlice } from './slice-reader';\nexport { makeIncluder } from './includer';\nexport {\n DefaultLogger,\n CaptureLogger,\n runCommand,\n main,\n flush,\n handleError\n} from './main';\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { Dict, Client, Limits, KeyVal as OWKeyVal } from 'openwhisk';\n\n// Contains the primary type definition for the deployer structure.\n// The structure consists of the contents of a 'project' (its file and folder structure) along\n// with the contents of a distinguished config file in the root of the project, if present.\n\n// Describes one package containing zero or more actions\nexport interface PackageSpec {\n name: string; // The 'default' package is used to hold actions with no package. Only the 'actions' member is processed then.\n actions?: ActionSpec[];\n shared?: boolean; // Indicates that the package is intended to be shared (public)\n annotations?: Dict; // package annotations\n parameters?: Dict; // Bound parameters for all actions in the package, passed in the usual way\n environment?: Dict; // Bound parameters for all actions in the package, destined to go in the environment of each action\n web?: any; // like 'web' on an action but affects all actions of the package that don't redeclare the flag\n deployedDuringBuild?: boolean; // set when the package was deployed early because some builds were remote\n binding?: BindingSpec; // may be present in lieu of an actions array if the package is bound to another\n}\n\n// Describes the binding information for a bound package (with no actions of its own)\nexport interface BindingSpec {\n name: string; // the name of the package to which the present package is bound\n namespace: string; // the namespace of the package to which the present package is bound\n}\n\n// Describes one action\nexport interface ActionSpec {\n name: string; // The name of the action\n package?: string; // The name of the package where action appears ('default' if no package)\n // The following are used to assemble 'exec'. Currently, you can't specify exec directly\n file?: string; // The path to the file comprising the action (possibly a zip file)\n displayFile?: string; // The file path to display in messages\n code?: string; // The code of the action (bypasses file reading; used internally; not specifiable in the config)\n runtime?: string; // The runtime to use for the action\n main?: string; // The 'main' directive if needed\n binary?: boolean; // Indicates the need for base64 encoding\n docker?: string; // Docker image to use with blackbox runtime\n zipped?: boolean; // (Ignored unless binary) indicates that the binary object is a zip archive\n // End of 'exec' properties\n sequence?: string[]; // Indicates that this action is a sequence and provides its components. Mutually exclusive with the 'exec' options\n web?: any; // like --web on the CLI; expands to multiple annotations. Project reader assigns true unless overridden.\n webSecure?: any; // like --web-secure on the CLI. False unless overridden\n annotations?: Dict; // 'web' and 'webSecure' are merged with what's here iff present\n parameters?: Dict; // Bound parameters for the action passed in the usual way\n environment?: Dict; // Bound parameters for the action destined to go in the environment\n limits?: Limits; // Action limits (time, memory, logs)\n remoteBuild?: boolean; // States that the build (if any) must be done remotely\n localBuild?: boolean; // States that the build (if any) must be done locally\n triggers?: TriggerSpec[]; // Triggers for the function if any\n // Build information (not specifiable in the config)\n build?: string;\n buildResult?: string; // The activation id of the remote build\n buildError?: Error; // Error reported from the build step\n}\n\nexport enum TriggerType {\n SCHEDULED = 'SCHEDULED'\n}\n// Information about one trigger. An action can have many triggers. However, different actions may not\n// share the same trigger.\nexport interface TriggerSpec {\n name: string; // The name of the trigger. Must be unique within the namespace.\n type: TriggerType; // Currently, the one supported value \"scheduled\" is required.\n scheduledDetails?: ScheduledSourceDetails;\n enabled?: boolean; // Assumed true if omitted\n}\n\n// The type used for the sourceDetails of a trigger whose sourceType is \"scheduled\"\nexport interface ScheduledSourceDetails {\n cron?: string; // must be a cron expression\n interval?: number; // in minutes (not yet implemented)\n once?: string; // an ISO-format date (not yet implemented)\n // (cron, interval and once are mutually exclusive)\n body?: object; // optional body to use when posting the function\n}\n\n// Information of various kinds typically specified on the command line\nexport interface Flags {\n verboseBuild: boolean;\n verboseZip: boolean;\n incremental: boolean;\n yarn: boolean;\n env: string | undefined;\n buildEnv: string | undefined;\n include: string | undefined;\n exclude: string | undefined;\n remoteBuild: boolean;\n json: boolean;\n // low-level flags, documented in help but not how-tos, infrequently used\n auth: string;\n apiHost: string;\n insecure: boolean;\n // special flag to reject triggers when found in project.yml (for use in contexts where triggers can't be supported)\n noTriggers: boolean;\n}\n\n// Object to provide feedback (warnings and progress reports) in real time during execution.\n// NOT for debugging.\n// NOT for normal communication: summary messages should be fed back through DeployResponse\n// NOT for hard errors: those should be thrown or Promise-rejected.\nexport interface Feedback {\n warn(message?: any, ...optionalParams: any[]): void;\n progress(message?: any, ...optionalParams: any[]): void;\n}\n\nexport class DefaultFeedback implements Feedback {\n warn(message?: any, ...optionalParams: any[]): void {\n console.warn(message, ...optionalParams);\n }\n\n progress(message?: any, ...optionalParams: any[]): void {\n console.log(message, ...optionalParams);\n }\n}\n\n// The top-level deploy structure. Nothing is required. If the structure is vacuous, nothing is deployed. This interface\n// describes the syntax of project.yml and also the structure of a project on disk where 'packages' is a subdirectory\n// of the project). The two sources of information are merged.\nexport interface DeployStructure {\n packages?: PackageSpec[]; // The packages found in the package directory\n targetNamespace?: string; // The namespace to which we are deploying\n parameters?: Dict; // Parameters to apply to all packages in the project\n environment?: Dict; // Environment to apply to all packages in the project\n // The following fields are not documented for inclusion project.yml but may be present in a project slice config (remote build)\n // They are typically added internally.\n slice?: boolean; // Labels this DeployStructure as belonging to a a project slice\n credentials?: Credentials; // The full credentials for the deployment (consistent with targetNamespace if one was specified)\n flags?: Flags; // options typically specified on the command line\n deployerAnnotation?: DeployerAnnotation; // The deployer annotation to use (with the digest undefined, as it varies)\n buildEnv?: Record<string, string>; // Build time environment\n // The following fields are never permitted in project.yml but are always added internally\n libBuild?: string; // Type of build (build.sh or package.json) to apply to the lib directory\n strays?: string[]; // files or directories found in the project that don't fit the model, not necessarily an error\n filePath?: string; // The location of the project on disk\n owClient?: Client; // The openwhisk client for deploying actions and packages\n includer?: Includer; // The 'includer' for deciding which packages and actions are included in the deploy\n reader?: ProjectReader; // The project reader to use\n versions?: VersionEntry; // The VersionEntry for credentials.namespace on the selected API host if available\n feedback?: Feedback; // The object to use for immediate communication to the user (e.g. for warnings and progress reports)\n error?: Error; // Records an error in reading or preparing, or a terminal error in building; the structure should not be used\n unresolvedVariables?: string[]; // Variables that couldn't be resolved in project reading (error may be set also)\n sequences?: ActionSpec[]; // detected during action deployment and deferred until ordinary actions are deployed\n}\n\n// Types used in the DeployResponse\nexport interface VersionInfo {\n version: string;\n digest: string;\n}\nexport interface VersionMap {\n [key: string]: VersionInfo;\n}\n\nexport type DeployKind = 'action' | 'trigger' | 'binding';\n\nexport interface DeploySuccess {\n name: string;\n kind: DeployKind;\n skipped: boolean;\n}\n\n// Contains the responses from an actual deployment\nexport interface DeployResponse {\n successes: DeploySuccess[];\n failures: Error[];\n ignored: string[];\n namespace: string;\n packageVersions: VersionMap;\n actionVersions: VersionMap;\n apihost?: string;\n}\n\n// The version file entry for a given deployment\nexport interface VersionEntry {\n apihost: string;\n namespace: string;\n packageVersions: VersionMap;\n actionVersions: VersionMap;\n}\n\n// The annotation placed in every action and package deployed by the deployer\nexport interface DeployerAnnotation {\n repository?: string;\n commit?: string;\n digest: string;\n projectPath: string;\n user: string;\n zipped?: boolean;\n newSliceHandling?: boolean;\n}\n\n// Grouping for OW Options that can be specified on the command line or by caller; also part of credential lookup response\nexport interface OWOptions {\n apihost?: string;\n api_key?: string;\n ignore_certs?: boolean;\n}\n\n// Supporting types for oauth\n\n// These types duplicate declarations in main/deployable/login, except that Credentials is renamed to FullCredentials\n// to avoid confusing it with the Credentials type used through nim.\nexport type IdProvider = {\n provider: string;\n name: string;\n key: string;\n};\n\nexport type FullCredentials = {\n status: string;\n apihost: string;\n namespace: string;\n uuid: string;\n key: string;\n redis: boolean;\n storage?: string;\n externalId?: IdProvider;\n};\n\n// Format of the JSON file containing credential information, persisted in ~/.nimbella/credentials.json\nexport interface CredentialStore {\n currentHost: string;\n currentNamespace: string;\n credentials: CredentialHostMap;\n}\n\nexport interface CredentialHostMap {\n [key: string]: CredentialNSMap; // Keyed by API host\n}\n\n// Part of CredentialStore for a single API host\nexport interface CredentialNSMap {\n [key: string]: CredentialEntry; // keyed by namespace relative to API host\n}\n\n// Part of CredentialStore for a single namespace relative to an API host.\n// It describes the credentials owned by the user who owns ~/.\n// While different subjects in couchdb can have different credentials to a shared namespace,\n// we assume that a user keeps only one credential set for that namespace.\nexport interface CredentialEntry {\n api_key: string;\n project?: string;\n production?: boolean;\n}\n\n// The Result of a credential lookup\nexport interface Credentials {\n namespace: string | undefined;\n ow: OWOptions;\n do_token: string;\n}\n\n// Compact and less complete information about a Credential suitable for listing and tabular display\nexport interface CredentialRow {\n namespace: string;\n current: boolean;\n apihost: string;\n}\n\n// The Includer object is used during project reading and deployment to screen packages, and actions to be included\nexport interface Includer {\n isPackageIncluded: (pkg: string, all: boolean) => boolean;\n isActionIncluded: (pkg: string, action: string) => boolean;\n isIncludingEverything: () => boolean;\n}\n\n// Defines the general ProjectReader interface\n\n// A simplified fs.Dirent that just distinguishes files, directories, and symlinks.\n// The symlink case is only for \"dangling\" symlinks: intact symlinks are followed.\nexport type PathKind = {\n name: string;\n isDirectory: boolean;\n isFile: boolean;\n symlink?: string;\n mode: number;\n};\n\n// The method repertoire for reading projects.\n// Path names passed to these methods may, in the most general case, be either absolute or relative to the\n// project root. After canonicalizing `..` directives in such paths, they may point inside or outside the project.\n// For the file system, we accept absolute paths and allow a relative path to land anywhere in the file system.\n// Historically, there was also a github reader which has been discontinued; therefore, currently, the file\n// system reader is the only exemplar of this interface. I think the interface is worth retaining, however,\n// for future experimentation.\nexport interface ProjectReader {\n // Read the contents of a directory (non-recursively)\n readdir: (path: string) => Promise<PathKind[]>;\n // Read the contents of a file (e.g. config, code, .include ...)\n readFileContents: (path: string) => Promise<Buffer>;\n // Test whether a file exists\n isExistingFile: (path: string) => Promise<boolean>;\n // Get the PathKind of a path\n getPathKind: (path: string) => Promise<PathKind>;\n // Get the location of the project in a real file system (returns null for \"non-real\" file systems, if any)\n getFSLocation: () => string | null;\n}\n\n// Define KeyVal for our purposes, supporting the `init` option for parameters\nexport interface KeyVal extends OWKeyVal {\n init?: boolean;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n DeployStructure,\n DeployResponse,\n DeploySuccess,\n DeployKind,\n ActionSpec,\n PackageSpec,\n Feedback,\n DeployerAnnotation,\n VersionMap,\n VersionEntry,\n PathKind,\n ProjectReader,\n KeyVal,\n TriggerSpec,\n TriggerType,\n Credentials\n} from './deploy-struct';\nimport { getUserAgent } from './api';\nimport { XMLHttpRequest } from 'xmlhttprequest';\nimport { Client, Dict, Activation, Action } from 'openwhisk';\nimport { isValidCron } from 'cron-validator';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport simplegit from 'simple-git';\nimport * as randomstring from 'randomstring';\nimport * as crypto from 'crypto';\nimport * as yaml from 'js-yaml';\nimport makeDebug from 'debug';\nimport anymatch from 'anymatch';\nimport { nimbellaDir } from './credentials';\nimport {\n isBinaryFileExtension,\n runtimeForZipMid,\n runtimeForFileExtension,\n isValidRuntime\n} from './runtimes';\nimport { undeployTriggers, listTriggersForNamespace } from './triggers';\nconst debug = makeDebug('nim:deployer:util');\n\n// List of files/paths to be ignored, add https://github.com/micromatch/anymatch compatible definitions\nexport const SYSTEM_EXCLUDE_PATTERNS = [\n '.gitignore',\n '.DS_Store',\n '**/.git/**',\n (s: string): boolean => s.includes('.nimbella'),\n (s: string): boolean => s.includes('.deployed'),\n (s: string): boolean => s.includes('_tmp_'),\n (s: string): boolean => s.includes('.#'),\n (s: string): boolean => s.endsWith('~'),\n '**/*.swp',\n '**/*.swx'\n];\n\n//\n// General utilities\n//\n\n// Read the project config file, with validation\nexport async function loadProjectConfig(\n configFile: string,\n envPath: string,\n buildEnvPath: string,\n filePath: string,\n reader: ProjectReader,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<DeployStructure> {\n const learnMore =\n ' Learn more about the project configuration file https://docs.digitalocean.com/products/functions/reference/project-configuration/';\n\n return reader.readFileContents(configFile).then(async (data) => {\n let configData = String(data);\n\n const encryptionKey = process.env.ENCRYPTION_KEY;\n if (encryptionKey) {\n configData = decryptProjectConfig(configData, encryptionKey);\n }\n\n try {\n // Read the config, substituting from env\n const { content, badVars } = substituteFromEnvAndFiles(\n String(configData),\n envPath,\n filePath,\n feedback\n );\n let config: Record<string, any>;\n if (configFile.endsWith('.json')) {\n config = JSON.parse(content);\n } else {\n if (content.includes('\\t')) {\n throw new Error('YAML configuration may not contain tabs');\n } else {\n config = yaml.safeLoad(content) as Record<string, any>;\n }\n }\n if (!config) {\n throw new Error('configuration is empty or unparseable');\n }\n // Adjust from the external convention (packages contain functions) to the internal one\n // (packages contain actions).\n renameFunctionsToActions(config);\n // Check config\n const configError = await validateDeployConfig(config, noTriggers);\n if (configError) {\n throw new Error(configError);\n } else {\n removeEmptyStringMembers(config);\n }\n // Add build environment if specified\n if (buildEnvPath) {\n config.buildEnv = getPropsFromFile(buildEnvPath);\n }\n config.unresolvedVariables = badVars;\n if (badVars && badVars.length > 0) {\n const formatted = \"'\" + badVars.join(\"', '\") + \"'\";\n config.error = new Error(\n 'The following substitutions could not be resolved: ' + formatted\n );\n }\n return config;\n } catch (err) {\n const errMsgPrefix = `Invalid project configuration file (${configFile})`;\n if (err.message) {\n err.message = `${errMsgPrefix}: ${err.message}`;\n } else {\n err.message = `${errMsgPrefix}`;\n }\n\n err.message = `${err.message} \\n ${learnMore}`;\n return errorStructure(err);\n }\n });\n}\n\nexport function encryptProjectConfig(config: string): {\n config: string;\n key: string;\n} {\n const key = crypto.randomBytes(32);\n const iv = Buffer.alloc(16).fill(0);\n const cipher = crypto.createCipheriv('aes256', key, iv);\n const encrypted = cipher.update(config, 'utf8', 'hex') + cipher.final('hex');\n return {\n config: encrypted,\n key: key.toString('hex')\n };\n}\n\nexport function decryptProjectConfig(config: string, key: string): string {\n const iv = Buffer.alloc(16).fill(0);\n const decipher = crypto.createDecipheriv(\n 'aes256',\n Buffer.from(key, 'hex'),\n iv\n );\n const decryptedMessage = Buffer.concat([\n decipher.update(config, 'hex'),\n decipher.final()\n ]);\n return decryptedMessage.toString('utf8');\n}\n\n// Rename any 'functions' members of the contained PackageSpecs of a config to 'actions'.\n// This adjust from an external convention to an internal one. It is done before validation.\nfunction renameFunctionsToActions(config: Record<string, any>): void {\n if (config.packages) {\n for (const pkg of config.packages) {\n if (pkg.functions) {\n pkg.actions = pkg.functions;\n delete pkg.functions;\n }\n }\n }\n}\n\n// Rename any 'actions' members of the contained PackageSpecs of a config to 'functions'.\n// This adjust from an external convention to an internal one. It is done before writing out\n// a config to be visible to users.\nexport function renameActionsToFunctions(config: Record<string, any>): void {\n if (config.packages) {\n for (const pkg of config.packages) {\n if (pkg.actions) {\n pkg.functions = pkg.actions;\n delete pkg.actions;\n }\n }\n }\n}\n\n// Check whether a build field actually implies a build must be run\nexport function isRealBuild(buildField: string): boolean {\n switch (buildField) {\n case 'build.sh':\n case 'build.cmd':\n case 'package.json':\n return true;\n default:\n return false;\n }\n}\n\n// Replace a build field with 'remote' or 'remote-default' if it is supposed to be remote according to flags,\n// directives, environment, or the type of runtime.\nfunction locateBuild(\n buildField: string,\n remoteRequested: boolean,\n defaultRemote: boolean,\n remoteRequired: boolean,\n localRequired: boolean\n) {\n if (!isRealBuild(buildField)) {\n // Not a real build. Check remote-default conditions.\n if (defaultRemote && !localRequired) {\n return 'remote-default';\n } // else does not meet remote-default conditions\n return buildField;\n } // else it's a real build. Check conditions for remote.\n if (remoteRequired || (remoteRequested && !localRequired)) {\n return 'remote';\n } // else does not meet conditions for remote\n return buildField;\n}\n\n// Set up the build fields for a project and detect conflicts.\n// Returns true if any build is required to be local.\nexport async function checkBuildingRequirements(\n todeploy: DeployStructure,\n requestRemote: boolean\n): Promise<boolean> {\n const checkConflicts = (remote: boolean, local: boolean, tag: string) => {\n if (remote && local) {\n throw new Error(\n `Local and remote building cannot both be required (${tag})`\n );\n }\n };\n if (todeploy.packages) {\n for (const pkg of todeploy.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n checkConflicts(\n action.remoteBuild,\n action.localBuild,\n `function ${action.name}`\n );\n }\n }\n }\n }\n let needsLocal = false;\n if (todeploy.packages) {\n for (const pkg of todeploy.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n const defaultRemote = await hasDefaultRemote(action, todeploy.reader);\n action.build = locateBuild(\n action.build,\n requestRemote,\n defaultRemote,\n action.remoteBuild,\n action.localBuild\n );\n if (action.build === 'build.sh' && process.platform === 'win32') {\n // If there was a build.cmd it would have been recorded in preference to build.sh\n throw new Error(\n `In function ${action.name}: 'build.sh' won't run on this platform and no 'build.cmd' is provided`\n );\n }\n needsLocal =\n needsLocal ||\n (!action.build?.startsWith('remote') && isRealBuild(action.build));\n }\n }\n }\n }\n return needsLocal;\n}\n\n// Determine if an action has a default remote build. This depends on the action's 'kind': currently, swift and go have a\n// default remote build while other languages do not. This function is designed to be called before the runtime is otherwise\n// known so it is prepared to peek into the project to figure out the operative runtime.\nasync function hasDefaultRemote(\n action: ActionSpec,\n reader: ProjectReader\n): Promise<boolean> {\n const runtime = await getRuntimeForAction(action, reader);\n if (!runtime) {\n return false;\n }\n const kind = runtime.split(':')[0];\n switch (kind) {\n // TODO should this be an external table?\n case 'go':\n case 'swift':\n return true;\n default:\n return false;\n }\n}\n\nexport async function getRuntimeForAction(\n action: ActionSpec,\n reader: ProjectReader\n): Promise<string> {\n if (action.runtime) {\n return action.runtime;\n }\n if (action.sequence && action.sequence.length > 0) {\n return '';\n }\n const pathKind = await reader.getPathKind(action.file);\n if (pathKind.isFile) {\n const { runtime } = await actionFileToParts(pathKind.name);\n return runtime;\n } else if (pathKind.isDirectory) {\n const files = await promiseFilesAndFilterFiles(action.file, reader);\n return agreeOnRuntime(files);\n } else {\n return '';\n }\n}\n\n// Check whether a list of names that are candidates for zipping can agree on a runtime. This is called only when the\n// config doesn't already provide a runtime, or on the raw material in the case of remote builds.\nexport async function agreeOnRuntime(items: string[]): Promise<string> {\n let agreedRuntime: string;\n const partsArray = await Promise.all(\n items.map((item) => actionFileToParts(item))\n );\n partsArray.forEach((answer) => {\n if (answer.runtime) {\n if (agreedRuntime && answer.runtime !== agreedRuntime) {\n return undefined;\n }\n agreedRuntime = answer.runtime;\n }\n });\n return agreedRuntime;\n}\n\n// In project config we permit many optional string-valued members to be set to '' to remind users that they are available\n// without actually setting a value. Here we delete those members to simplify subsequent handling.\nfunction removeEmptyStringMembers(config: DeployStructure) {\n if (config.targetNamespace && config.targetNamespace === '') {\n delete config.targetNamespace;\n }\n removeEmptyStringMembersFromPackages(config.packages);\n}\n\n// Remove empty optional string-valued members from an array of PackageSpecs\nfunction removeEmptyStringMembersFromPackages(packages: PackageSpec[]) {\n if (!packages) return;\n for (const pkg of packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n if (action.main && action.main === '') {\n delete action.main;\n }\n if (action.runtime && action.runtime === '') {\n delete action.runtime;\n }\n }\n }\n }\n}\n\n// Validation for DeployStructure read from disk.\nexport async function validateDeployConfig(\n arg: any,\n noTriggers: boolean\n): Promise<string> {\n const isNimbellaDeploy = arg.targetNamespace === 'nimbella';\n const slice = !!arg.slice;\n for (const item in arg) {\n if (!arg[item]) continue;\n switch (item) {\n case 'slice':\n continue;\n break;\n case 'targetNamespace': {\n if (!(typeof arg[item] === 'string') && !isValidOwnership(arg[item])) {\n return `${item} must be a string or a dictionary containing 'test' and/or 'production' members`;\n }\n break;\n }\n case 'packages': {\n if (!Array.isArray(arg[item])) {\n return 'packages member must be an array';\n }\n for (const subitem of arg[item]) {\n const pkgError = await validatePackageSpec(\n subitem,\n slice,\n isNimbellaDeploy,\n noTriggers\n );\n if (pkgError) {\n return pkgError;\n }\n }\n break;\n }\n case 'parameters':\n case 'environment': {\n if (!isDictionary(arg[item])) {\n return `${item} member must be a dictionary`;\n }\n break;\n }\n case 'credentials':\n case 'flags':\n case 'deployerAnnotation':\n case 'buildEnv':\n if (slice) continue;\n // In a slice we accept these without further validation; otherwise, they are illegal\n // Otherwise, fall through\n default:\n return `Invalid key '${item}' found in project.yml`;\n }\n }\n return undefined;\n}\n\n// Test whether an item is a dictionary. In practice this means its basic type is object and it isn't an array or null.\nfunction isDictionary(item: any) {\n return typeof item === 'object' && !Array.isArray(item) && item != null;\n}\n\n// Test whether an item is an Ownership. This means it's a dictionary and has 'production' and/or 'test' string members\nfunction isValidOwnership(item: any): boolean {\n return (\n isDictionary(item) &&\n (typeof item.production === 'string' || typeof item.test === 'string')\n );\n}\n\n// Validator for a PackageSpec\nasync function validatePackageSpec(\n arg: Record<string, any>,\n slice: boolean,\n isNimbella: boolean,\n noTriggers: boolean\n): Promise<string> {\n const isDefault = arg.name === 'default';\n for (const item in arg) {\n if (!arg[item]) continue;\n if (item === 'name') {\n if (!(typeof arg[item] === 'string')) {\n return `'${item}' member of a 'package' must be a string`;\n }\n } else if (item === 'actions') {\n if (!Array.isArray(arg[item])) {\n return \"functions member of a 'package' must be an array\";\n }\n for (const subitem of arg[item]) {\n const actionError = await validateActionSpec(\n subitem,\n isNimbella,\n noTriggers\n );\n if (actionError) {\n return actionError;\n }\n }\n } else if (item === 'shared') {\n if (!(typeof arg[item] === 'boolean')) {\n return `'${item}' member of a 'package' must be a boolean`;\n } else if (isDefault && arg[item]) {\n return `'${item}' must be absent or false for the default package`;\n }\n } else if (item === 'web') {\n if (!(typeof arg[item] === 'boolean' || arg[item] === 'raw')) {\n return `${item} member of an 'package' must be a boolean or the string 'raw'`;\n }\n } else if (item === 'environment') {\n const envErr = validateEnvironment(arg[item]);\n if (envErr) {\n return envErr;\n }\n } else if (item === 'parameters' || item === 'annotations') {\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n if (isDefault && Object.keys(arg[item]).length > 0) {\n return `'${item}' must be absent or empty for the default package`;\n }\n } else if (item === 'binding') {\n // We don't check here for a package with both actions and a binding because we don't have\n // complete information (just parsing the spec, but the package may have actions in the file system\n // that aren't in the spec). This conflict is detected later at deploy time.\n if (\n typeof arg[item]?.namespace !== 'string' ||\n typeof arg[item]?.name != 'string'\n ) {\n return 'binding information is incomplete: namespace and package name are both required';\n }\n } else if (item === 'deployedDuringBuild' && slice) {\n continue;\n } else {\n return `Invalid key '${item}' found in 'package' in project.yml`;\n }\n }\n return undefined;\n}\n\n// Validator for ActionSpec\nasync function validateActionSpec(\n arg: Record<string, any>,\n isNimbella: boolean,\n noTriggers: boolean\n): Promise<string> {\n for (const item in arg) {\n if (!arg[item]) continue;\n switch (item) {\n case 'name':\n case 'file':\n case 'runtime':\n case 'main':\n case 'docker':\n if (!(typeof arg[item] === 'string')) {\n return `'${item}' member of a function must be a string`;\n }\n if (item === 'runtime' && !(await isValidRuntime(arg[item]))) {\n return `'${arg[item]}' is not a valid runtime value`;\n }\n break;\n case 'binary':\n case 'remoteBuild':\n case 'localBuild':\n if (!(typeof arg[item] === 'boolean')) {\n return `'${item}' member of a function must be a boolean`;\n }\n break;\n case 'sequence':\n if (\n !Array.isArray(arg[item]) ||\n arg[item].length === 0 ||\n typeof arg[item][0] !== 'string'\n ) {\n return `'${item}' member of a function must be an array of one or more strings naming other functions`;\n }\n break;\n case 'web':\n if (!(typeof arg[item] === 'boolean' || arg[item] === 'raw')) {\n return `${item} member of a function must be a boolean or the string 'raw'`;\n }\n break;\n case 'webSecure':\n if (isNimbella && arg[item] === true) {\n // allowed\n continue;\n }\n if (!(arg[item] === false || typeof arg[item] === 'string')) {\n return `'${item}' member of a function must be a boolean false or a string`;\n }\n break;\n case 'environment': {\n const envError = validateEnvironment(arg[item]);\n if (envError) {\n return envError;\n }\n }\n // falls through\n case 'annotations': {\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n const annotErr = screenForbiddenAnnotations(arg[item]);\n if (annotErr) {\n return annotErr;\n }\n break;\n }\n case 'parameters':\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n break;\n case 'limits': {\n const limitsError = validateLimits(arg[item]);\n if (limitsError) {\n return limitsError;\n }\n break;\n }\n case 'triggers': {\n if (noTriggers) {\n return `the project requests triggers but triggers are not available`;\n }\n const triggerArs = transformLegacyTriggers(arg[item]);\n const trigErr = validateTriggers(triggerArs);\n if (trigErr) {\n return trigErr;\n }\n break;\n }\n default:\n return `Invalid key '${item}' found in 'functions' clause in project.yml`;\n }\n }\n return undefined;\n}\n\n// Don't permit manual setting of annotations that are supposed to be set specially\nfunction screenForbiddenAnnotations(annots: object): string {\n const forbidden = {\n 'require-whisk-auth': 'webSecure',\n 'web-export': 'web=true|false|\"raw\"',\n 'raw-http': 'web=raw'\n };\n for (const annot of Object.keys(annots)) {\n const subst = forbidden[annot];\n if (subst) {\n return `the '${annot}' annotation may not be set explicitly; use '${subst}'`;\n }\n }\n return '';\n}\n\n// Transforms legacy triggers format to new format for backwards compatibility.\n// Should be removed after the triggers beta is over and throw error to users.\n//\n// sourceType -> type (\"scheduler\" -> \"scheduled\")\n// sourceDetails -> scheduledDetails\n// sourceDetails.withBody -> scheduledDetails.body\nfunction transformLegacyTriggers(args: any) {\n const transformedArgs = args;\n if (!Array.isArray(transformedArgs)) {\n return args;\n }\n\n transformedArgs.forEach((trigger, index) => {\n if (!trigger.sourceType && !trigger.sourceDetails) {\n return;\n }\n transformedArgs[index].scheduledDetails = {\n cron: trigger.sourceDetails?.cron,\n body: trigger.sourceDetails?.withBody\n };\n transformedArgs[index].type =\n trigger.sourceType === 'scheduler' ? 'SCHEDULED' : trigger.sourceType;\n\n delete transformedArgs[index].sourceType;\n delete transformedArgs[index].sourceDetails;\n });\n\n return transformedArgs;\n}\n\n// Validator for the 'triggers' clause of an action\nexport function validateTriggers(arg: any): string {\n if (!Array.isArray(arg)) {\n return `a 'triggers' clause must be an array`;\n }\n\n for (const trigger of arg as TriggerSpec[]) {\n if (!isDictionary(trigger)) {\n return 'an individual trigger must be a dictionary';\n }\n\n for (const item of Object.keys(trigger)) {\n if (!['name', 'enabled', 'type', 'scheduledDetails'].includes(item)) {\n return `Invalid key '${item}' found in 'triggers' clause in project.yml`;\n }\n }\n\n const name = trigger.name;\n const type =\n typeof trigger.type === 'string'\n ? trigger.type.toUpperCase()\n : trigger.type;\n const scheduledDetails = trigger.scheduledDetails;\n\n if (typeof name !== 'string') {\n return `the 'name' field of a trigger is required`;\n }\n\n if (![TriggerType.SCHEDULED].includes(type as TriggerType)) {\n return `the trigger 'type' field must be '${Object.values(\n TriggerType\n ).join(' | ')}'`;\n }\n\n if (type === TriggerType.SCHEDULED) {\n if (!isDictionary(scheduledDetails)) {\n return `the 'scheduledDetails' property of a trigger is required for type=\"${TriggerType.SCHEDULED}\"`;\n }\n\n const err = validateScheduledTriggerDetails(scheduledDetails);\n if (err) {\n return err;\n }\n }\n\n if (trigger.enabled && typeof trigger.enabled !== 'boolean') {\n return `the 'enabled' property of a trigger must be boolean'`;\n }\n }\n return undefined;\n}\n\n// Validator for the sourceDetails of a trigger when the sourceType is 'scheduled'\nfunction validateScheduledTriggerDetails(details: any): string | undefined {\n if (!isDictionary(details)) {\n return 'the scheduledDetails field of a trigger specification must be a dictionary';\n }\n\n for (const item of Object.keys(details)) {\n if (!['cron', 'body'].includes(item)) {\n return `Invalid key '${item}' found in scheduledDetails in project.yml`;\n }\n }\n\n const cron = details.cron;\n const body = details.body;\n\n if (typeof cron !== 'string') {\n return `the 'cron' member of 'scheduledDetails' must be a string`;\n }\n\n if (!isValidCron(cron)) {\n // Note we are now validating with no \"special options\" enabled, so this is\n // least-common-denominator crontab (no seconds, no aliases, etc.). We should make sure\n // we are at least considering valid anything that the scheduler will actually accept.\n return `the cron expression '${cron}' is not valid crontab syntax`;\n }\n\n if (body && !isDictionary(body)) {\n return `the 'body' member of scheduledDetails must be a dictionary`;\n }\n}\n\n// Validator for the 'environment' clause of package or action. Checks that all values are strings\nfunction validateEnvironment(item: any): string {\n if (!isDictionary(item)) {\n return 'the environment clause must be a dictionary';\n }\n for (const entry in item) {\n const value = item[entry];\n if (typeof value !== 'string') {\n return `All environment values must be strings but '${entry}' has type '${typeof value}'`;\n }\n }\n return undefined;\n}\n\n// Validator for the limits clause\nfunction validateLimits(arg: any): string {\n for (const item in arg) {\n const value = arg[item];\n switch (item) {\n case 'timeout':\n case 'memory':\n case 'logs':\n if (typeof value !== 'number') {\n return `'${item}' member of a 'limits' clause must be a number`;\n }\n break;\n default:\n return `Invalid key '${item}' found in 'limits' clause in project.yml`;\n }\n }\n return undefined;\n}\n\n// Convert convenient \"Dict\" to the less convenient \"KeyVal[]\" required in an action object\nexport function keyVal(from: Dict): KeyVal[] {\n if (!from) {\n return undefined;\n }\n return Object.keys(from).map((key) => ({ key, value: from[key] }));\n}\n\n// Make an openwhisk KeyVal into an openwhisk Dict (the former appears in Action and Package, the latter in ActionSpec and PackageSpec)\nexport function makeDict(keyVal: KeyVal[]): Dict {\n const ans: Dict = {};\n keyVal.forEach((pair) => {\n ans[pair.key] = pair.value;\n });\n return ans;\n}\n\n// Provide an empty DeployStructure with all array and object members defined but empty\nexport function emptyStructure(): DeployStructure {\n return { packages: [], strays: [] };\n}\n\n// Provide an empty DeployStructure that records an error\nexport function errorStructure(err: Error): DeployStructure {\n const ans = emptyStructure();\n ans.error = err;\n return ans;\n}\n\n// Provide an empty DeployResponse with all required members defined but empty\nexport function emptyResponse(): DeployResponse {\n return {\n successes: [],\n failures: [],\n ignored: [],\n namespace: undefined,\n packageVersions: {},\n actionVersions: {}\n };\n}\n\n// Combine multiple DeployResponses into a single DeployResponse\nexport function combineResponses(responses: DeployResponse[]): DeployResponse {\n if (responses.length === 0) {\n return emptyResponse();\n }\n const combinedSuccesses: DeploySuccess[][] = responses.map(\n (response) => response.successes\n );\n const successes = combinedSuccesses.reduce(\n (prev, curr) => prev.concat(curr),\n []\n );\n const combinedFailures: Error[][] = responses.map(\n (response) => response.failures\n );\n const failures = combinedFailures.reduce(\n (prev, curr) => prev.concat(curr),\n []\n );\n const combinedIgnored: string[][] = responses.map(\n (response) => response.ignored\n );\n const ignored = combinedIgnored.reduce((prev, curr) => prev.concat(curr));\n const packageVersions = responses.reduce(\n (prev, curr) => Object.assign(prev, curr.packageVersions),\n {}\n );\n const actionVersions = responses.reduce(\n (prev, curr) => Object.assign(prev, curr.actionVersions),\n {}\n );\n const namespace = responses\n .map((r) => r.namespace)\n .reduce((prev, curr) => prev || curr);\n return {\n successes,\n failures,\n ignored,\n packageVersions,\n actionVersions,\n namespace\n };\n}\n\n// Turn the strays from a DeployStructure into a response indicating that they were skipped\nexport function straysToResponse(strays: string[]): DeployResponse {\n return {\n successes: [],\n ignored: strays,\n failures: [],\n packageVersions: {},\n actionVersions: {},\n namespace: undefined\n };\n}\n\n// Wrap a single success as a DeployResponse\nexport function wrapSuccess(\n name: string,\n kind: DeployKind,\n skipped: boolean,\n actionVersions: VersionMap,\n namespace: string\n): DeployResponse {\n const success: DeploySuccess = { name, kind, skipped };\n return {\n successes: [success],\n failures: [],\n ignored: [],\n namespace,\n packageVersions: {},\n actionVersions\n };\n}\n\n// Wrap a single error as a DeployResponse\nexport function wrapError(err: any, context: string): DeployResponse {\n debug('wrapping an error: %O', err);\n if (typeof err === 'object') {\n err.context = context;\n }\n const result = {\n successes: [],\n failures: [err],\n ignored: [],\n packageVersions: {},\n actionVersions: {},\n namespace: undefined\n };\n debug('wrapped error: %O', result);\n return result;\n}\n\n// Compute an appropriately qualified action name based on package inclusion\nexport function getActionName(action: ActionSpec): string {\n if (action.package && action.package !== 'default') {\n return action.package + '/' + action.name;\n }\n return action.name;\n}\n\n// Check whether the namespace for an OW client's current auth matches a desired target\nexport function isTargetNamespaceValid(\n client: Client,\n namespace: string\n): Promise<boolean> {\n return getTargetNamespace(client).then((ns) => {\n if (ns === namespace) {\n return Promise.resolve(true);\n } else {\n throw new Error(\n `Supplied credentials do not match target namespace '${namespace}'; deployment aborted`\n );\n }\n });\n}\n\n// Get the target namespace\nexport function getTargetNamespace(client: Client): Promise<string> {\n return client.namespaces.list().then((ns) => ns[0]);\n}\n\n// Process an action file name, producing 'name', 'binary', 'zipped' and 'runtime' parts\nexport async function actionFileToParts(fileName: string): Promise<{\n name: string;\n binary: boolean;\n zipped: boolean;\n runtime: string;\n}> {\n let runtime: string;\n let binary: boolean;\n let zipped: boolean;\n let name = path.basename(fileName);\n const split = name.indexOf('.');\n if (split > 0) {\n const parts = name.split('.');\n const ext = parts[parts.length - 1];\n let mid: string;\n if (parts.length === 2) {\n name = parts[0];\n } else if (ext === 'zip') {\n [name, mid] = getNameAndMid(parts.slice(0, -1));\n } else {\n name = parts.slice(0, -1).join('.');\n }\n runtime = mid ? await runtimeForZipMid(mid) : runtimeForFileExtension(ext);\n binary = isBinaryFileExtension(ext);\n zipped = ext === 'zip';\n } else {\n // No extension. Assume binary, with unknown runtime\n binary = true;\n zipped = false;\n }\n const z = zipped ? '' : 'not ';\n debug(`action ${name} is ${z}zipped`);\n return { name, binary, zipped, runtime };\n}\n\n// Correctly parse a \"mid\" segment from a zip file name. The input is the name split\n// on periods with the extension dropped. There are always at least two parts.\n// We should return the name and mid-segment as a two-element array.\nfunction getNameAndMid(parts: string[]): string[] {\n if (parts.length === 2) {\n return parts;\n }\n // There are at least three parts. Either the runtime is the last one or the last two\n const last = parts[parts.length - 1];\n const nextToLast = parts[parts.length - 2];\n if (/^\\d+$/.test(last) && nextToLast.includes('-')) {\n // Looks like a runtime version was split on a dot so we need to reassemble\n const name = parts.slice(0, -2).join('.');\n const mid = parts.slice(-2).join('.');\n return [name, mid];\n } else {\n const name = parts.slice(0, -1).join('.');\n return [name, last];\n }\n}\n\n// Filters temp files from an array of Dirent structures\nexport function filterFiles(entries: PathKind[]): PathKind[] {\n return entries.filter((entry) => {\n if (!entry.isDirectory) {\n return !anymatch(getExclusionList(), entry.name);\n } else {\n return entry;\n }\n });\n}\n\n// Emulates promiseFiles (from node-dir) using a ProjectReader and adds filtering like filterFiles\nexport async function promiseFilesAndFilterFiles(\n root: string,\n reader: ProjectReader\n): Promise<string[]> {\n let items = await promiseFiles(root, reader);\n debug('items before filtering: %O', items);\n const exclusions = getExclusionList();\n debug('exclusion list: %O', exclusions);\n items = items.filter((item: string) => !anymatch(exclusions, item));\n debug('items after filtering: %O', items);\n return items;\n}\n\n// Emulate promiseFiles using a ProjectReader\nasync function promiseFiles(\n dir: string,\n reader: ProjectReader\n): Promise<string[]> {\n debug('promiseFiles called on directory %s', dir);\n const files: string[] = [];\n let subdirs = await promiseFilesRound(dir, files, [], reader);\n while (subdirs.length > 0) {\n const next = subdirs.pop();\n debug(\n \"promiseFiles recursing on subdirectory '%s', with '%d' files accumulated and '%d' subdirectories still pending\",\n next,\n files.length,\n subdirs.length\n );\n subdirs = await promiseFilesRound(next, files, subdirs, reader);\n }\n debug('promiseFiles returning with %d files', files.length);\n return files;\n}\n\n// Working subroutine of promiseFiles\nasync function promiseFilesRound(\n dir: string,\n files: string[],\n subdirs: string[],\n reader: ProjectReader\n): Promise<string[]> {\n const items = await reader.readdir(dir);\n items.forEach(async (item) => {\n const itemPath = path.join(dir, item.name);\n if (item.isDirectory) {\n subdirs.push(itemPath);\n } else {\n files.push(itemPath);\n }\n });\n return subdirs;\n}\n\n// Substitute from the environment and from files. Variable references look like template variables: ${FOO} reads the\n// contents of variable FOO. Variables may be found in the process environment (higher precedence) or in the property file\n// located at 'envPath' (lower precedence, and only if 'envPath is defined).\n// ${<path} reads the contents of a file at the given path relative to the project root.\n// The semantics of variable substitution are purely textual (whatever is in the variable is substituted).\n// The semantics of file substitution are richer (see getSubstituteFromFile)\n// The form ${ token1 token2 token3 } where tokens are non-whitespace separated by whitespace is a special shorthand\n// that expands to { token1: value, token2: value, token3: value } where the values are obtained by looking up the\n// tokens in the process environment (higher precedence) or property file located at 'envPath'.\nexport function substituteFromEnvAndFiles(\n input: string,\n envPath: string,\n projectPath: string,\n feedback: Feedback\n): { content: string; badVars: string[] } {\n let result = ''; // Will accumulate the result\n const badVars: string[] = []; // Will accumulate failures to resolve\n const props = envPath ? getPropsFromFile(envPath) : {};\n debug('envPath: %s', envPath);\n debug('props %O', props);\n let nextSym = findNextSymbol(input);\n let warn = false;\n while (nextSym.index >= 0) {\n const before = input.substr(0, nextSym.index);\n const after = input.substr(nextSym.index + 2);\n const endVar = after.indexOf(nextSym.terminator);\n if (endVar < 0) {\n throw new Error('Runaway variable name or path directive in project.yml');\n }\n let subst: string;\n let doStringEscapes = true;\n let envar = after.substr(0, endVar).trim();\n debug('substituting for envar: %s', envar);\n if (nextSym.terminator === ')' || /\\s/.test(envar)) {\n warn = warn || nextSym.terminator !== ')';\n subst = getDictionarySubstitution(envar, props, badVars);\n } else if (envar.startsWith('<')) {\n if (nextSym.terminator === ')') {\n throw new Error('Invalid substitution: $(' + envar + ')');\n }\n const fileSubst = path.join(projectPath, envar.slice(1).trim());\n subst = getSubstituteFromFile(fileSubst);\n } else {\n if (envar.startsWith('|')) {\n envar = envar.slice(1).trim();\n doStringEscapes = false;\n }\n subst = process.env[envar] || props[envar];\n }\n if (!subst) {\n badVars.push(envar);\n subst = `<${envar}>`;\n } else if (doStringEscapes) {\n subst = escapeNewlines(subst);\n }\n debug('substitution is: %s', subst);\n result = result + before + subst;\n input = after.substr(endVar + 1);\n nextSym = findNextSymbol(input);\n }\n result = result + input;\n if (warn) {\n feedback.warn(\n \"Using '${}' for dictionary substitution is now deprecated; use '$()'\"\n );\n }\n if (badVars.length > 0) {\n return { content: result, badVars };\n }\n return { content: result, badVars: undefined };\n}\n\n// Perform escaping of newlines.\nfunction escapeNewlines(original: string): string {\n const parts = original.split('\\n');\n return parts.join('\\\\n');\n}\n\n// Scan forward for the next symbol introducer\nfunction findNextSymbol(input: string): { index: number; terminator: string } {\n const nextBrace = input.indexOf('${');\n const nextParen = input.indexOf('$(');\n const haveBrace = nextBrace >= 0;\n const haveParen = nextParen >= 0;\n if (haveBrace) {\n if (haveParen) {\n return nextBrace < nextParen\n ? { index: nextBrace, terminator: '}' }\n : { index: nextParen, terminator: ')' };\n } else {\n return { index: nextBrace, terminator: '}' };\n }\n } else if (haveParen) {\n return { index: nextParen, terminator: ')' };\n } else {\n return { index: -1, terminator: '' };\n }\n}\n\n// Get one or more substitutions in the form of a dictionary, given one or more tokens separated by whitespace.\n// Each token is a symbol to be looked up in the process environment or env file\nfunction getDictionarySubstitution(\n tokens: string,\n props: Record<string, unknown>,\n badVars: string[]\n): string {\n debug('dictionary substitution with %s', tokens);\n const ans = {};\n for (const tok of tokens.split(/\\s+/)) {\n debug('token: %s', tok);\n const value = process.env[tok] || props[tok];\n if (value) {\n ans[tok] = value;\n } else {\n badVars.push(tok);\n ans[tok] = `<${tok}>`;\n }\n }\n return JSON.stringify(ans);\n}\n\n// Get a substitution JSON string from a file. The file is read and, if it is valid JSON, it is simply used as is.\n// Otherwise, it is reparsed as a properties file and the result is converted to JSON. If the file is neither a valid JSON\n// file nor a valid properties file, that is an error.\nfunction getSubstituteFromFile(path: string): string {\n if (!fs.existsSync(path)) {\n return undefined;\n }\n const props = getPropsFromFile(path);\n const answer = JSON.stringify(props);\n return answer === '{}' ? undefined : answer;\n}\n\n// Get properties from a file, which may be a properties file or JSON\n// This function does not use the project reader because the environment file is specified separately\nfunction getPropsFromFile(filePath: string): Record<string, string> {\n if (!fs.existsSync(filePath)) {\n return {};\n }\n const contents = fs.readFileSync(filePath);\n try {\n return JSON.parse(String(contents));\n } catch {\n // Do nothing\n }\n // It's not JSON, so see if it's a properties file\n const propParser = require('dotenv'); // eslint-disable-line @typescript-eslint/no-var-requires\n // The dotenv parser doesn't throw but returns the empty object if malformed\n return propParser.parse(contents);\n}\n\n// Types for the map versions of the PackageSpec and ActionSpec types\nexport interface PackageMap {\n [key: string]: PackageSpec;\n}\nexport interface ActionMap {\n [key: string]: ActionSpec;\n}\n\n// Turn a PackageSpec array into a PackageMap\nexport function mapPackages(packages: PackageSpec[]): PackageMap {\n const ans: PackageMap = {};\n for (const pkg of packages) {\n ans[pkg.name] = pkg;\n }\n return ans;\n}\n\n// Turn an ActionSpec array into an ActionMap\nexport function mapActions(actions: ActionSpec[]): ActionMap {\n const ans: ActionMap = {};\n for (const action of actions || []) {\n ans[action.name] = action;\n }\n return ans;\n}\n\n// Get the best available name for a project for recording. If project is in a cloned repo\n// the name should reflect the github coordinates and not include incidental aspects of the github URL.\n// If the project is just in the file system we use its absolute path (best we have)\nexport function getBestProjectName(project: DeployStructure): string {\n const annot = project.deployerAnnotation;\n if (!annot) {\n return project.filePath;\n }\n if (annot.repository) {\n let repo = annot.repository;\n if (repo.includes(':')) {\n repo = repo.split(':')[1];\n }\n if (repo.endsWith('.git')) {\n repo = repo.slice(0, -4);\n }\n while (repo.startsWith('/')) {\n repo = repo.slice(1);\n }\n return repo + '/' + annot.projectPath;\n }\n return annot.projectPath;\n}\n\n// Calculate the 'deployer' annotation for inclusion in package and action annotations. This won't change\n// in the course of a deploy run so can be calculated once for inclusion in everything that is deployed.\nexport async function getDeployerAnnotation(\n project: string\n): Promise<DeployerAnnotation> {\n const digest = undefined;\n try {\n const git = simplegit(project);\n const root = await git.revparse(['--show-toplevel']);\n const repo = await git.raw(['config', '--get', 'remote.origin.url']);\n const user = (await git.raw(['config', '--get', 'user.email'])).trim();\n const projectPath = path.relative(root, path.resolve(project));\n let commit = await git.revparse(['head']);\n commit = commit.substring(0, 8);\n const status = await git.status();\n if (!status.isClean()) {\n commit += '++';\n }\n return { user, repository: repo.trim(), projectPath, commit, digest };\n } catch {\n const user = os.userInfo().username.trim();\n const projectPath = path.resolve(project);\n return { user, projectPath, digest };\n }\n}\n\n// Wipe all the entities from the namespace referred to by an OW client handle.\n// This is not guaranteed to succeed but it will attempt to wipe as much as possible,\n// returning all errors that occurred. If an error occurs when removing a trigger that\n// is associated with a function, the function is not deleted.\nexport async function wipe(\n client: Client,\n credentials: Credentials\n): Promise<void> {\n const errors: any[] = [];\n // Delete the actions, which will delete associated triggers if possible. If a trigger\n // cannot be deleted, the action is left also.\n await wipeActions(client, credentials, errors);\n debug('Actions wiped');\n // Delete the packages. Note that if an action deletion failed, the containing\n // package will likely fail also.\n await wipeAll(client.packages, 'Package', errors);\n debug('Packages wiped');\n // There _could_ have been orphaned triggers that were not deleted when we\n // deleted actions (since they were not connected to an existing action).\n // On the other hand, if one or more triggers failed deletion before, they\n // may fail again here, with duplicate errors. We are tolerating that for the moment.\n const namespace = await getTargetNamespace(client);\n const triggers = await listTriggersForNamespace(namespace, credentials, '');\n const errs = await undeployTriggers(triggers, credentials);\n if (errs.length > 0) {\n errors.push(...errs);\n }\n // Delete rules and OpenWhisk triggers for good measure (there really shouldn't be any)\n await wipeAll(client.rules, 'Rule', errors);\n debug('Rules wiped');\n await wipeAll(client.triggers, 'Trigger', errors);\n debug('OpenWhisk triggers wiped');\n // Determine if any errors occurred. If so, throw them. We have tried using AggregateError\n // here but ran into perplexing problems. So, using an ad hoc approach when combining errors.\n if (errors.length > 1) {\n const combined = Error(\n 'multiple errors occurred while cleaning the namespace'\n ) as any;\n combined.errors = errors;\n throw combined;\n }\n if (errors.length == 1) {\n throw errors[0];\n }\n}\n\n// Repeatedly wipe an entity (rule, trigger, or package) from the namespace denoted by the OW client until none are left\n// Note that the list function can only return 200 entities at a time).\n// Actions are handled differently since they may have triggers associated with them.\nasync function wipeAll(handle: any, kind: string, errors: any[]) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const entities = await handle.list({ limit: 200 });\n if (entities.length === 0) {\n return;\n }\n for (const entity of entities) {\n let name = entity.name;\n const nsparts = entity.namespace.split('/');\n if (nsparts.length > 1) {\n name = nsparts[1] + '/' + name;\n }\n try {\n await handle.delete(name);\n debug('%s %s deleted', kind, name);\n } catch (err) {\n debug('error deleting %s %s: %O', err);\n errors.push(err);\n }\n }\n }\n}\n\n// Repeatedly wipe actions from the namespace denoted by the OW client until none are left.\n// Note that the list function can only return 200 actions at a time. This is done\n// differently from the other entity types because actions can have associated triggers\n// which should be deleted first (with the action remaining if the trigger deletion fails).\nasync function wipeActions(\n client: Client,\n credentials: Credentials,\n errors: any[]\n) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const actions = await client.actions.list({ limit: 200 });\n if (actions.length === 0) {\n return;\n }\n for (const action of actions) {\n let name = action.name;\n const nsparts = action.namespace.split('/');\n if (nsparts.length > 1) {\n name = nsparts[1] + '/' + name;\n }\n const result = await deleteAction(name, client, credentials);\n if (Array.isArray(result)) {\n errors.push(...result);\n debug('error deleting the triggers');\n }\n debug('action %s deleted', name);\n }\n }\n}\n\n// Delete an action after first deleting any DigitalOcean triggers that are targeting it.\n// If we can't delete the triggers, we don't delete the action (maintains the invariant that\n// a trigger should only exist if its invoked function also exists). This function is not\n// intended to throw but to return errors in an array (either errors deleting triggers or an\n// error deleting the action).\nexport async function deleteAction(\n actionName: string,\n owClient: Client,\n credentials: Credentials\n): Promise<Action | Error[]> {\n // Delete triggers.\n const namespace = await getTargetNamespace(owClient);\n const triggers = await listTriggersForNamespace(\n namespace,\n credentials,\n actionName\n );\n const errs = await undeployTriggers(triggers, credentials);\n if (errs.length > 0) {\n return errs;\n }\n try {\n return await owClient.actions.delete({ name: actionName });\n } catch (err) {\n const msg = err.message ? err.message : err;\n return [new Error(`unable to undeploy action '${actionName}': ${msg}`)];\n }\n}\n\n// Generate a secret in the form of a random alphameric string (TODO what form(s) do we actually support)\nexport function generateSecret(): string {\n return randomstring.generate();\n}\n\n// Guard against accidental deployment to a sensitive namespace on a production host\n// Not called if the --production flag was set.\n// 'nim install actions' will set this flag.\n// The workbench 'project deploy' command will never set this flag\n// Developers using the deployProject CLI may set this flag but presumably will only do so by intention.\nexport function saveUsFromOurselves(\n namespace: string,\n apihost: string\n): boolean {\n let sensitiveNamespaces: string[];\n let productionProjects: string[];\n try {\n sensitiveNamespaces = require('../sensitiveNamespaces.json');\n productionProjects = require('../productionProjects.json');\n } catch (_) {\n // Customers don't need a --production flag ... their auth token defines what they can and can't do\n return false;\n }\n return (\n sensitiveNamespaces.includes(namespace) &&\n isProductionProject(apihost, productionProjects)\n );\n}\n\n// Determine whether an apihost (given as a string URL) denotes any of a list of projects\nfunction isProductionProject(\n apihost: string,\n productionProjects: string[]\n): boolean {\n const url = new URL(apihost);\n const domain = url.hostname.split('.')[0];\n if (domain === 'api') {\n return true;\n }\n const project = domain.replace('api', 'nim');\n return productionProjects.includes(project);\n}\n\n// Compute the digest of a PackageSpec\nexport function digestPackage(pkg: PackageSpec): string {\n const hash = crypto.createHash('sha256');\n digestBoolean(hash, pkg.shared);\n digestBoolean(hash, pkg.web);\n digestDictionary(hash, pkg.annotations);\n digestDictionary(hash, pkg.parameters);\n digestDictionary(hash, pkg.environment);\n digestDictionary(hash, pkg.binding);\n for (const action of pkg.actions || []) {\n hash.update(action.name);\n }\n return String(hash.digest('hex'));\n}\n\nfunction digestBoolean(hash: crypto.Hash, toDigest: boolean) {\n hash.update(String(!!toDigest));\n}\n\nfunction digestStringArray(hash: crypto.Hash, toDigest: string[]) {\n if (toDigest) {\n for (const value of toDigest) {\n hash.update(value);\n }\n }\n}\n\nfunction digestDictionary(hash: crypto.Hash, toDigest: Record<string, any>) {\n if (toDigest) {\n const keys = Object.keys(toDigest).sort();\n for (const key of keys) {\n hash.update(key);\n const value = toDigest[key];\n switch (typeof value) {\n case 'string':\n hash.update(value);\n break;\n case 'boolean':\n digestBoolean(hash, value);\n break;\n case 'object':\n digestDictionary(hash, value);\n break;\n default: // number, bigint ... and some exotic cases TODO: need we do better?\n hash.update(String(value));\n break;\n }\n }\n }\n}\n\n// Compute the digest of an ActionSpec. Code is provided as a separate argument (code member of the ActionSpec will either be identical or undefined)\nexport function digestAction(action: ActionSpec, code: string): string {\n const hash = crypto.createHash('sha256');\n digestBoolean(hash, action.binary);\n digestBoolean(hash, action.zipped);\n hash.update(String(action.web));\n hash.update(String(action.webSecure));\n digestDictionary(hash, action.annotations);\n digestDictionary(hash, action.parameters);\n digestDictionary(hash, action.environment);\n digestDictionary(hash, action.limits);\n digestStringArray(hash, action.sequence);\n hash.update(code);\n if (action.main) {\n hash.update(action.main);\n }\n hash.update(action.runtime);\n return String(hash.digest('hex'));\n}\n\n// Get the status reporting directory, making it if it doesn't exist\nfunction getStatusDir(project: string): {\n statusDir: string;\n created: boolean;\n} {\n const statusDir = path.join(project, '.deployed');\n let created = false;\n if (!fs.existsSync(statusDir)) {\n fs.mkdirSync(statusDir);\n created = true;\n }\n return { statusDir, created };\n}\n\n// Write the \"slice result\" to the status area\n// Note: this is not being used yet. It is not clear how the remote build action is supposed to find the status area.\n// Other possibilities are to write it in a more easily found place or to write it to a file descriptor and pipe it\n// somewhere.\nexport function writeSliceResult(project: string, result: string): void {\n const file = path.join(getStatusDir(project).statusDir, 'sliceResult');\n fs.writeFileSync(file, result);\n}\n\n// Called after a deploy step to record important information from the DeployResponse into the project.\n// Essentially a dual of loadVersions but not quite symmetrical since its argument is a DeployResponse\n// The 'replace' argument causes the new VersionEntry calculated from the DeployResponse to replace\n// an existing one. This was the behavior prior to the advent of include/exclude, and it is what is\n// requested when that feature is not used. If 'replace' is false, then the new VersionEntry is merged\n// into an existing one if any, preserving information for things not deployed in the current round.\n// Returns the path name of the status directory if newly created, empty string otherwise\nexport function writeProjectStatus(\n project: string,\n results: DeployResponse,\n replace: boolean\n): string {\n debug('writing project status with %O', results);\n const { apihost, namespace, packageVersions, actionVersions } = results;\n if (\n Object.keys(actionVersions).length === 0 &&\n Object.keys(packageVersions).length === 0\n ) {\n debug('there is no meaningful project status to write');\n return '';\n }\n const { statusDir, created } = getStatusDir(project);\n let versionList: VersionEntry[] = [];\n const versionFile = path.join(statusDir, 'versions.json');\n if (fs.existsSync(versionFile)) {\n debug('version file already exists');\n const old = JSON.parse(String(fs.readFileSync(versionFile)));\n if (Array.isArray(old)) {\n versionList = old;\n debug('version list using legacy format, not preserved');\n } // Otherwise (not array) it is the legacy format and cannot be added to so we just overwrite\n }\n const versionInfo: VersionEntry = {\n apihost,\n namespace,\n packageVersions,\n actionVersions\n };\n const oldEntry: VersionEntry = versionList.find(\n (entry) => entry.apihost === apihost && entry.namespace === namespace\n );\n if (!oldEntry) {\n debug('new entry pushed to version list');\n versionList.push(versionInfo);\n } else {\n debug('merging new entry into old');\n mergeVersions(oldEntry, versionInfo, replace);\n }\n fs.writeFileSync(versionFile, JSON.stringify(versionList, null, 2));\n debug('wrote version info to %s', versionFile);\n return created ? statusDir : '';\n}\n\n// Merge new information into old information within the version store.\n// If replace is specified, each major element of the old entry (packageVersions, actionVersions) is replaced\n// with the new. Otherwise, the dictionaries are merged.\nfunction mergeVersions(\n oldEntry: VersionEntry,\n newEntry: VersionEntry,\n replace: boolean\n) {\n if (replace) {\n Object.assign(oldEntry, newEntry);\n } else {\n Object.assign(oldEntry.actionVersions, newEntry.actionVersions);\n Object.assign(oldEntry.packageVersions, newEntry.packageVersions);\n }\n}\n\n// Load the version information of a project for a namespace and apihost. Return an appropriately empty structure if not found.\nexport function loadVersions(\n projectPath: string,\n namespace: string,\n apihost: string\n): VersionEntry {\n const versionFile = path.join(projectPath, '.deployed', 'versions.json');\n if (fs.existsSync(versionFile)) {\n const allEntries = JSON.parse(String(fs.readFileSync(versionFile)));\n for (const entry of allEntries) {\n if (namespace === entry.namespace && apihost === entry.apihost) {\n return entry;\n }\n }\n }\n return {\n namespace,\n apihost,\n packageVersions: {},\n actionVersions: {}\n };\n}\n\n// Introduce small delay\nexport function delay(millis: number): Promise<void> {\n return new Promise(function (resolve) {\n setTimeout(() => resolve(), millis);\n });\n}\n\n// Await the completion of an action invoke. The poll interval is fixed at 1 second.\n// The 'waiting' argument is called every 10 polls (intended for providing progress feedback).\n// The total wait time should be expressed in #polls. Because of imprecision in the time\n// management this will generally be longer than #seconds but not by a huge factor.\n// If the wait \"times out\", undefined is returned.\nexport async function waitForActivation(\n id: string,\n wsk: Client,\n waiting: () => void,\n total: number\n): Promise<Activation<Dict>> {\n debug(`waiting for activation with id ${id}`);\n let errors = 0;\n const maxErrors = 3;\n for (let i = 1; i <= total; i++) {\n try {\n const activation = await wsk.activations.get(id);\n if (activation.end || activation.response.status) {\n debug('activation %s found after %d iterations', id, i);\n return activation;\n }\n } catch (err) {\n if (err.statusCode !== 404) {\n errors++;\n }\n if (errors > maxErrors) {\n throw err;\n }\n }\n if (i % 10 === 0) {\n waiting();\n }\n await delay(1000);\n }\n return undefined;\n}\n\n// Higher level wrapper around wskRequest for web-secure actions. Forms the URL\nexport function invokeWebSecure(\n actionAndQuery: string,\n auth: string,\n apihost: string\n): Promise<any> {\n const url = apihost + '/api/v1/web' + actionAndQuery;\n return wskRequest(url, auth);\n}\n\n// Subroutine to invoke OW with a GET and return the response. Bypasses the OW client. Used\n// to invoke web actions, with or without auth needed.\nexport function wskRequest(\n url: string,\n auth: string = undefined\n): Promise<any> {\n debug('Request to: %s', url);\n return new Promise(function (resolve, reject) {\n const xhr = new XMLHttpRequest();\n xhr.open('GET', url);\n const userAgent = getUserAgent();\n xhr.setRequestHeader('User-Agent', userAgent);\n xhr.onload = function () {\n if (this.status >= 200 && this.status < 300) {\n debug('useful response');\n resolve(JSON.parse(xhr.responseText));\n } else {\n debug('Error from OW %s %s', xhr.status, xhr.responseText);\n reject(new Error(xhr.responseText));\n }\n };\n xhr.onerror = function () {\n debug('network error');\n reject(new Error('Network error'));\n };\n if (auth) {\n if (auth.includes(':')) {\n debug('Setting basic authorization header');\n xhr.setRequestHeader(\n 'Authorization',\n 'Basic ' + Buffer.from(auth).toString('base64')\n );\n } else {\n debug('Setting X-Require-Whisk-Auth header to %s', auth);\n xhr.setRequestHeader('X-Require-Whisk-Auth', auth);\n }\n }\n xhr.send();\n });\n}\n\n// Utility to rename a package in a DeployStructure in a safe and consistent way.\n// Will throw if the oldName does not match a package in the spec.\nexport function renamePackage(\n spec: DeployStructure,\n oldName: string,\n newName: string\n): DeployStructure {\n const pkg = spec.packages?.find((pkg) => pkg.name === oldName);\n if (!pkg) {\n throw new Error(\n `Package '${oldName}' was not found in the DeployStructure`\n );\n }\n pkg.name = newName;\n if (pkg.actions) {\n for (const action of pkg.actions) {\n action.package = newName;\n }\n }\n return spec;\n}\n\n// Checks if a given pattern matches exclusion list, defined by system or user via global .exclude file.\nexport function isExcluded(match: string): boolean {\n return anymatch(getExclusionList(), match);\n}\n\n// Returns full list of exclusion patterns, predefined or listed in the global .exclude file.\nexport function getExclusionList(): string[] {\n let userDefinedPatterns = [];\n try {\n const globalExcludeFile = path.join(nimbellaDir(), '.exclude');\n userDefinedPatterns = fs\n .readFileSync(globalExcludeFile)\n .toString()\n .split('\\n')\n .filter((e) => e.toString().trim() !== '');\n } catch (e) {\n debug(e.message);\n }\n const allPatterns = [...userDefinedPatterns, ...SYSTEM_EXCLUDE_PATTERNS];\n return allPatterns;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Functions to manage the credential store.\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n CredentialStore,\n CredentialEntry,\n Credentials,\n CredentialRow,\n Feedback\n} from './deploy-struct';\nimport createDebug from 'debug';\nimport { wskRequest } from './util';\nconst debug = createDebug('nimbella.cli');\n\n// Non-exported constants\nconst HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];\nconst NAMESPACE_URL_PATH = '/api/v1/namespaces';\nconst NIMBELLA_DIR = '.nimbella';\nconst WSK_PROPS = 'wskprops';\nconst CREDENTIAL_STORE = 'credentials.json';\n// Function indirection needed for webpack\nexport function nimbellaDir(): string {\n const fromEnv = process.env.NIMBELLA_DIR;\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return path.join(HOME, NIMBELLA_DIR);\n}\nfunction wskProps() {\n return path.join(nimbellaDir(), WSK_PROPS);\n}\nfunction credentialStore() {\n return path.join(nimbellaDir(), CREDENTIAL_STORE);\n}\n\n// Exports\n\n// The type of a persistance manager, which will differ between cloud and local\nexport interface Persister {\n loadCredentialStoreIfPresent: () => CredentialStore;\n loadCredentialStore: () => Promise<CredentialStore>;\n saveCredentialStore: (store: CredentialStore) => void;\n saveLegacyInfo: (apihost: string, auth: string) => void;\n}\n\n// The persister to use when local storage is accessible.\n// This can be replaced to bypass file system access.\nconst fileSystemPersister: Persister = {\n loadCredentialStoreIfPresent,\n loadCredentialStore,\n saveCredentialStore,\n saveLegacyInfo\n};\n\n// The persister to use for all auth code.\n// Not a constant so that it can be explicitly set to bypass file system access.\nexport const authPersister = fileSystemPersister;\n\n// Add credential to credential store and make it the default. Does not persist the result\nexport function addCredential(\n store: CredentialStore,\n apihost: string,\n namespace: string,\n api_key: string\n): Credentials {\n debug('Adding credential to credential store');\n let nsMap = store.credentials[apihost];\n if (!nsMap) {\n nsMap = {};\n store.credentials[apihost] = nsMap;\n }\n nsMap[namespace] = { api_key };\n store.currentHost = apihost;\n store.currentNamespace = namespace;\n return {\n namespace,\n ow: { apihost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n\n// Remove a namespace from the credential store\nexport async function forgetNamespace(\n namespace: string,\n apihost: string | undefined,\n feedback: Feedback\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n const creds = getUniqueCredentials(namespace, apihost, store);\n const host = apihost || creds.ow.apihost;\n const hostMap = store.credentials[host];\n let undefinedWarning = false;\n if (hostMap && hostMap[namespace]) {\n delete hostMap[namespace];\n if (host === store.currentHost && store.currentNamespace === namespace) {\n store.currentNamespace = undefined;\n undefinedWarning = true;\n try {\n fs.unlinkSync(wskProps());\n } catch {\n // Do nothing\n }\n }\n authPersister.saveCredentialStore(store);\n if (undefinedWarning) {\n feedback.warn(`'${namespace}' was the current namespace`);\n feedback.warn(\n 'A new namespace target must be specified on or before the next project deployment'\n );\n }\n } else {\n feedback.warn(\n `There is no credential entry for namespace '${namespace}' on API host '${host}'`\n );\n }\n return creds;\n}\n\n// Switch the active namespace in the credential store. The namespace argument is required.\n// All occurrences of the namespace across all API hosts are collected.\n// If there is an explicit 'apihost' argument this collection must include an entry with that API host\n// Otherwise,\n// - if there is just one occurrence, the switch is to that namespace on that API host\n// - otherwise, no switch occurs and the thrown Error either states that no credentials exist for that namespace\n// or that the --apihost flag is required to indicate which one is intended\nexport async function switchNamespace(\n namespace: string,\n apihost: string | undefined\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n const answer = getUniqueCredentials(namespace, apihost, store);\n const newHost = answer.ow.apihost;\n if (store.currentHost === newHost && store.currentNamespace === namespace) {\n debug('not an actual change');\n return answer;\n }\n store.currentHost = newHost;\n store.currentNamespace = namespace;\n authPersister.saveCredentialStore(store);\n authPersister.saveLegacyInfo(newHost, answer.ow.api_key);\n debug(`Switched target namespace to '${namespace}' on API host '${newHost}'`);\n return answer;\n}\n\n// Get a valid Credentials object by finding the information in the environment. This will generally not work in the\n// CLI context but is designed to work via the deployer API when running in actions. It may be especially\n// useful in shared packages, where the credentials in the environment will vary by invoking user.\n// For the information to be fully usable the environment must include __OW_API_KEY, which is only present when\n// the action is annotated with provide-api-key=true.\n// If the environment is inadequate to support this API, an error is generally not indicated. Instead,\n// an incomplete Credentials object is returned.\nexport function getCredentialsFromEnvironment(): Credentials {\n const apihost = process.env.__OW_API_HOST;\n const namespace = process.env.__OW_NAMESPACE;\n const api_key = process.env.__OW_API_KEY;\n const do_token = process.env.DO_API_KEY;\n return { namespace, ow: { api_key, apihost }, do_token };\n}\n\n// Get the credentials for a namespace. Similar logic to switchNamespace but does not change which\n// namespace is considered current.\nexport async function getCredentialsForNamespace(\n namespace: string,\n apihost: string | undefined\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n return getUniqueCredentials(namespace, apihost, store);\n}\n\n// Get the current credentials. This will succeed iff the user has a credential store and a current namespace.\n// Otherwise, we throw an error.\nexport async function getCredentials(): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n if (!store.currentHost || !store.currentNamespace) {\n throw new Error(\n \"You do not have a current namespace. Use 'nim auth login' to create a new one or 'nim auth switch' to use an existing one\"\n );\n }\n const entry = store.credentials[store.currentHost][store.currentNamespace];\n const { api_key } = entry;\n return {\n namespace: store.currentNamespace,\n ow: { apihost: store.currentHost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n\n// Convenience function to load, add, save a new credential.\nexport async function addCredentialAndSave(\n apihost: string,\n auth: string,\n namespace: string\n): Promise<Credentials> {\n const credStore = await authPersister.loadCredentialStore();\n const nsPromise = namespace\n ? Promise.resolve(namespace)\n : getNamespace(apihost, auth);\n return nsPromise.then((namespace) => {\n const credentials = addCredential(credStore, apihost, namespace, auth);\n authPersister.saveCredentialStore(credStore);\n return credentials;\n });\n}\n\n// Provide contents of the CredentialStore in a dictionary style suitable for listing and tabular presentation\nexport async function getCredentialDict(): Promise<{\n [host: string]: CredentialRow[];\n}> {\n const store = await authPersister.loadCredentialStore();\n const result: { [host: string]: CredentialRow[] } = {};\n for (const apihost in store.credentials) {\n let rows: CredentialRow[] = [];\n for (const namespace in store.credentials[apihost]) {\n const current =\n apihost === store.currentHost && namespace === store.currentNamespace;\n rows.push({ namespace, current, apihost });\n rows = rows.sort((a, b) => a.namespace.localeCompare(b.namespace));\n }\n result[apihost] = rows;\n }\n return result;\n}\n\n// Get the list of apihosts from the credential store\nexport async function getApiHosts(persister: Persister): Promise<string[]> {\n const store = await persister.loadCredentialStore();\n return Object.keys(store.credentials);\n}\n\n// Flat (single array) version of getCredentialDict\nexport async function getCredentialList(): Promise<CredentialRow[]> {\n const dict = await getCredentialDict();\n return Object.values(dict).reduce((acc, val) => acc.concat(val), []);\n}\n\n// Get the namespace associated with an auth on a specific host\nexport function getNamespace(host: string, auth: string): Promise<string> {\n debug('getting current namespace');\n const url = host + NAMESPACE_URL_PATH;\n return wskRequest(url, auth).then((list) => list[0]);\n}\n\n// Get current namespace\nexport async function getCurrentNamespace(): Promise<string | undefined> {\n debug('getting current namespace');\n const store = await authPersister.loadCredentialStore();\n return store.currentNamespace;\n}\n\n// fileSystemPersister functions (indirectly exported)\nfunction saveCredentialStore(store: CredentialStore): void {\n const toWrite = JSON.stringify(store, null, 2);\n debug('writing credential store');\n fs.writeFileSync(credentialStore(), toWrite, { mode: 0o600 });\n}\n\nfunction saveLegacyInfo(apihost: string, auth: string): void {\n saveWskProps(apihost, auth);\n debug('stored .wskprops with API host %s', apihost);\n}\n\nfunction loadCredentialStore(): Promise<CredentialStore> {\n // Returns a promise for historical reasons. Could be tweaked since\n // the promise is no longer needed.\n if (!fs.existsSync(credentialStore())) {\n return Promise.resolve(initialCredentialStore());\n }\n const contents = fs.readFileSync(credentialStore());\n return Promise.resolve(JSON.parse(String(contents)));\n}\n\nfunction loadCredentialStoreIfPresent(): CredentialStore {\n if (!fs.existsSync(credentialStore())) {\n return undefined;\n }\n const contents = fs.readFileSync(credentialStore());\n return JSON.parse(String(contents));\n}\n\n// Utility functions (not exported)\n\n// Make the initial credential store when none exists. It always starts out empty. This also makes\n// the parent directory preparatory to the first write. It does not actually write the credential store.\nfunction initialCredentialStore(): CredentialStore {\n if (!fs.existsSync(nimbellaDir())) {\n fs.mkdirSync(nimbellaDir(), { mode: 0o700 });\n }\n return {\n currentHost: undefined,\n currentNamespace: undefined,\n credentials: {}\n };\n}\n\n// Write ~/.nimbella/wskprops. Used when the default api host or api key change (TODO: this never saves the 'insecure' flag; that should\n// probably be correlated with the api host)\nfunction saveWskProps(apihost: string, auth: string) {\n const wskPropsContents = `APIHOST=${apihost}\\nAUTH=${auth}\\n`;\n fs.writeFileSync(wskProps(), wskPropsContents, { mode: 0o600 });\n}\n\n// Given a namespace and _optionally_ an apihost, return the credentials, throwing errors based on the\n// number of matches. Used in cases where the credentials are expected to exist but the client may or\n// may not have provided an API host\nfunction getUniqueCredentials(\n namespace: string,\n apihost: string | undefined,\n store: CredentialStore\n): Credentials {\n const possibles: { [key: string]: CredentialEntry } = {};\n let credentialEntry: CredentialEntry;\n let newHost: string;\n for (const host in store.credentials) {\n const entry = store.credentials[host][namespace];\n if (entry) {\n possibles[host] = entry;\n }\n }\n if (apihost) {\n if (possibles[apihost]) {\n credentialEntry = possibles[apihost];\n newHost = apihost;\n } else {\n throw new Error(\n `No credentials found for namespace '${namespace}' on API host '${apihost}'`\n );\n }\n } else {\n const pairs = Object.entries(possibles);\n if (pairs.length === 1) {\n [newHost, credentialEntry] = pairs[0];\n } else if (pairs.length === 0) {\n throw new Error(\n `No credentials found for namespace '${namespace}' on any API host`\n );\n } else {\n throw new Error(\n `The namespace '${namespace}' exists on more than one API host. An '--apihost' argument is required`\n );\n }\n }\n const { api_key } = credentialEntry;\n debug('have authkey: %s', api_key);\n return {\n namespace,\n ow: { apihost: newHost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n", "import axios, { AxiosInstance } from 'axios';\nimport { getCredentials } from './credentials';\nimport { Credentials } from './deploy-struct';\n\nimport debug from 'debug';\nconst debug_log = debug('nim:deployer:runtimes');\n\nexport const API_ENDPOINT = '/api/v1';\n\nlet cachedRuntimes: RuntimesConfig;\n\n// Static table to use if the host cannot be contacted\nconst staticRuntimes: RuntimesConfig = {\n go: [\n {\n default: false,\n kind: 'go:1.15'\n },\n {\n default: true,\n kind: 'go:1.17'\n }\n ],\n nodejs: [\n {\n default: true,\n kind: 'nodejs:14'\n },\n {\n default: false,\n kind: 'nodejs-lambda:14'\n },\n {\n default: false,\n kind: 'nodejs:18'\n },\n {\n default: false,\n kind: 'nodejs-lambda:18'\n }\n ],\n php: [\n {\n default: true,\n kind: 'php:8.0'\n }\n ],\n python: [\n {\n default: true,\n kind: 'python:3.9'\n }\n ]\n};\n\n// Custom types for runtimes.json configuration parameters\ntype RuntimeLabel = string;\ntype RuntimeKind = string;\ntype RuntimeFileExtension = string;\n\nexport interface Runtime {\n kind: RuntimeKind;\n default?: boolean;\n}\n\nexport type RuntimesConfig = Record<RuntimeLabel, Runtime[]>;\n\n// List of file extensions for runtimes. This hardcoded list used to be present\n// in the extensions field of the runtimes.json document.\n// The commented-out lines are not currently supported by DigitalOcean;\n// some may be supported in the future.\nconst FileExtensionRuntimes: Record<RuntimeKind, RuntimeFileExtension[]> = {\n go: ['go'],\n // 'java': ['java', 'jar'],\n nodejs: ['js', 'ts'], // nodejs works for both javascript and typescript\n // 'typescript': ['ts'],\n php: ['php'],\n python: ['py']\n // 'ruby': ['rb'],\n // 'rust': ['rs'],\n // 'swift': ['swift'],\n // 'deno': ['ts', 'js'],\n // 'dotnet': ['cs', 'vb']\n};\n\n// File extensions which imply binary data\nconst BinaryFileExtensions: Set<RuntimeFileExtension> =\n new Set<RuntimeFileExtension>(['zip', 'jar']);\n\n// Send HTTP request to platform endpoint for runtimes configuration\nexport async function fromPlatform(\n httpClient: AxiosInstance,\n platformUrl: string\n): Promise<Record<string, unknown>> {\n const url = `${platformUrl}${API_ENDPOINT}`;\n debug_log(`loading runtimes from platform @ ${url}`);\n try {\n const { data } = await httpClient.get(url);\n debug_log(`loaded runtimes json: ${JSON.stringify(data)}`);\n return data?.runtimes;\n } catch (err) {\n // Error due to HTTP Code > 2XX\n if (err.response) {\n throw new Error(\n `http request failed (${url}) with status (${err.response.status}): ${err.response.statusText} `\n );\n // or response never received\n } else if (err.request) {\n throw new Error(`http request failed: GET ${url}`);\n // or something else...\n } else {\n throw err;\n }\n }\n}\n\n// Compute the runtime from the file extension.\nexport function runtimeForFileExtension(\n fileExtension: RuntimeFileExtension\n): RuntimeKind | undefined {\n const runtime = Object.entries(FileExtensionRuntimes).find((item) =>\n item[1].includes(fileExtension)\n );\n return runtime && runtime.length > 0 ? `${runtime[0]}:default` : undefined;\n}\n\n// Does file extension imply binary data?\nexport function isBinaryFileExtension(\n fileExtension: RuntimeFileExtension\n): boolean {\n return BinaryFileExtensions.has(fileExtension);\n}\n\n// Compute the expected file extension from a runtime name.\n// Runtime returned should match the option for whether file extension refers to binary data\nexport function fileExtensionForRuntime(\n runtime: RuntimeKind,\n isBinaryExtension: boolean\n): RuntimeFileExtension {\n debug_log(\n `fileExtensionForRuntime: runtime (${runtime}) binary (${isBinaryExtension})`\n );\n const isSameRuntime = (r: string): boolean => r.includes(runtime);\n const isValidRuntime = Object.keys(FileExtensionRuntimes).some(isSameRuntime);\n if (!isValidRuntime)\n throw new Error(`Invalid runtime ${runtime} encountered`);\n\n return isBinaryExtension\n ? FileExtensionRuntimes[runtime].filter((item) =>\n BinaryFileExtensions.has(item)\n )[0]\n : FileExtensionRuntimes[runtime][0];\n}\n\n// Does the runtime kind exist in the platform config?\nexport async function isValidRuntime(kind: RuntimeKind): Promise<boolean> {\n debug_log(`isValidRuntime: kind (${kind})`);\n let exactMatch = true;\n if (kind.endsWith(':default')) {\n kind = kind.split(':')[0] + ':';\n exactMatch = false;\n }\n debug_log('searching');\n const runtimes = await getRuntimes();\n for (const runtimeArray of Object.values(runtimes)) {\n for (const runtime of runtimeArray) {\n if (exactMatch && kind === runtime.kind) {\n debug_log(`${kind}===${runtime.kind}`);\n return true;\n } else if (\n !exactMatch &&\n runtime.kind.startsWith(kind) &&\n runtime.default\n ) {\n debug_log(`${runtime.kind} starts with ${kind} and is the default`);\n return true;\n }\n debug_log(`no match on ${runtime.kind}`);\n }\n }\n return false;\n}\n\n// Find the default runtime for a language\nexport function defaultRuntime(\n runtimes: RuntimesConfig,\n label: RuntimeLabel\n): RuntimeKind {\n debug_log(`defaultRuntime: runtimes (${runtimes}) label (${label})`);\n const kinds = runtimes[label] ?? [];\n const defaultRuntime = kinds.find((k) => k.default) ?? { kind: undefined };\n return defaultRuntime.kind;\n}\n\n// Compute a runtime kind from the 'mid string' of a file name of the form name.runtime.zip\nexport async function runtimeForZipMid(mid: string): Promise<RuntimeKind> {\n const runtime = mid.includes('-') ? mid.replace('-', ':') : `${mid}:default`;\n return (await isValidRuntime(runtime)) ? runtime : undefined;\n}\n\n// Return default kind for runtime label - if explicit version isn't used.\nexport async function canonicalRuntime(\n runtime: RuntimeKind\n): Promise<RuntimeKind> {\n if (runtime.endsWith(':default')) {\n const [label] = runtime.split(':');\n const runtimes = await getRuntimes();\n return defaultRuntime(runtimes, label);\n }\n return runtime;\n}\n\n// Custom type guard to ensure JSON response is in the correct format\nfunction isValidRuntimesJson(\n src: Record<string, unknown>\n): src is RuntimesConfig {\n return Object.values(src).every(\n (v) => Array.isArray(v) && v.every((k) => k.hasOwnProperty('kind')) // eslint-disable-line no-prototype-builtins\n );\n}\n\n// Load runtimes JSON configuration file from platform endpoint\nexport async function load(apihost: string): Promise<RuntimesConfig> {\n const runtimes = await fromPlatform(axios, apihost);\n if (!isValidRuntimesJson(runtimes)) {\n throw new Error(\n `Invalid runtime JSON received from platform API: ${apihost}`\n );\n }\n return runtimes;\n}\n\n// Get the runtimes configuration. This code assumes that _either_ all API hosts are equivalent\n// _or_ only one API host is used in the module lifetime.\n// The parsed runtime configuration will be stored in a local cache and returned after the first call.\n// If no API host can be determined or there is an error contacting the host, then a built-in table\n// is returned (this information changes slowly and so the built-in value can't be terribly stale).\nexport async function getRuntimes(): Promise<RuntimesConfig> {\n if (cachedRuntimes) {\n return cachedRuntimes;\n }\n // Determine the API host either by reading the credential store or looking in the environment.\n // The latter is needed when running in a container performing remote build, since there may not be\n // any credential store.\n let creds: Credentials;\n try {\n creds = await getCredentials();\n } catch {\n // DO NOTHING\n }\n const apihost =\n creds?.ow?.apihost ||\n process.env.__OW_API_HOST ||\n process.env.savedOW_API_HOST;\n if (apihost) {\n cachedRuntimes = await load(apihost);\n } else {\n cachedRuntimes = staticRuntimes;\n }\n return cachedRuntimes;\n}\n", "/*\n * Copyright (c) 2022 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Includes support for listing, installing, and removing triggers, when such triggers are attached to\n// an action.\n\n// Note well: this code is prepared to succeed silently (no-op) in contexts where the authorization to\n// manage triggers is absent. To make the code do something, the DO_API_KEY environment variable must be\n// set to the DO API key that should be used to contact the DO API endpoint. In doctl, this key will be\n// placed in the process environment of the subprocess that runs the deployer. If the deployer is invoked\n// via nim rather than doctl, the invoking context must set this key (e.g. in the app platform build container\n// or for testing).\n\nimport { TriggerSpec, DeploySuccess, Credentials } from './deploy-struct';\nimport { default as axios, AxiosRequestConfig } from 'axios';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:triggers');\nconst doAPIEndpoint = 'https://api.digitalocean.com';\n\n// Returns an array. Elements are a either DeploySuccess structure for use in reporting when the trigger\n// is deployed successfully, or an Error if the trigger failed to deploy. These are 1-1 with the input\n// triggers argument.\nexport async function deployTriggers(\n triggers: TriggerSpec[],\n functionName: string,\n credentials: Credentials\n): Promise<(DeploySuccess | Error)[]> {\n const result: (DeploySuccess | Error)[] = [];\n for (const trigger of triggers) {\n result.push(await deployTrigger(trigger, functionName, credentials));\n }\n debug('finished deploying triggers, returning result');\n return result;\n}\n\n// Undeploy one or more triggers. Returns the empty array on success. Otherwise, the return\n// contains all the errors from attempted deletions.\nexport async function undeployTriggers(\n triggers: string[],\n credentials: Credentials\n): Promise<Error[]> {\n const errors: any[] = [];\n for (const trigger of triggers) {\n try {\n await undeployTrigger(trigger, credentials);\n } catch (err) {\n const msg = err.message ? err.message : err;\n errors.push(new Error(`unable to undeploy trigger '${trigger}': ${msg}`));\n }\n }\n return errors;\n}\n\n// Code to deploy a trigger.\n// Note that basic structural validation of each trigger has been done previously\n// so paranoid checking is omitted.\nasync function deployTrigger(\n trigger: TriggerSpec,\n functionName: string,\n credentials: Credentials\n): Promise<DeploySuccess | Error> {\n const details = trigger.scheduledDetails;\n const { cron, body } = details;\n const { enabled } = trigger;\n const { do_token } = credentials;\n try {\n if (do_token) {\n debug('calling the trigger API to create %s', trigger.name);\n return await doTriggerCreate(\n trigger.name,\n functionName,\n credentials,\n cron,\n enabled,\n body\n );\n } // otherwise do nothing\n } catch (err) {\n debug('caught an error while deploying trigger; will return it');\n // Assume 'err' is either string or Error in the following. Actually it can be anything but use of\n // other types is rare.\n if (typeof err === 'string') {\n return new Error(err);\n }\n return err as Error; // TODO this could lead to a type error eventually if err isn't an Error\n }\n // Neither envvar is set. No-op\n return { name: trigger.name, kind: 'trigger', skipped: true };\n}\n\n// Create a trigger using the real API. Note: the prototype API has the capability to do an UPSERT (by\n// setting the overwrite flag) and we use this. Here, we need to simulate the effect by doing a speculative\n// delete, ignoring 404 errors (actually, we are ignoring all errors, which is probably adequate).\nasync function doTriggerCreate(\n trigger: string,\n fcn: string,\n credentials: Credentials,\n cron: string,\n enabled: boolean,\n withBody: object\n): Promise<DeploySuccess> {\n try {\n await doTriggerDelete(trigger, credentials);\n } catch {\n // DO NOTHING, this assumes the trigger never existed.\n }\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${credentials.namespace}/triggers`,\n method: 'post',\n data: {\n name: trigger,\n function: fcn,\n is_enabled: enabled !== false, // ie, defaults to true\n type: 'SCHEDULED',\n scheduled_details: {\n cron,\n body: withBody\n }\n }\n };\n debug('trigger create request config is: %O', config);\n await doAxios(config, credentials.do_token);\n return { name: trigger, kind: 'trigger', skipped: false };\n}\n\n// Perform a network operation with axios, given a config object.\n// The config object should be complete except for headers. The auth header\n// is added here. The function assumes that doApiKey is set.\nasync function doAxios(\n config: AxiosRequestConfig,\n token: string\n): Promise<object> {\n config.headers = {\n Authorization: `Bearer ${token}`\n };\n const response = await axios(config);\n return response.data;\n}\n\n// Code to delete a trigger.\nasync function undeployTrigger(trigger: string, credentials: Credentials) {\n debug('undeploying trigger %s', trigger);\n const { do_token } = credentials;\n\n if (do_token) {\n return doTriggerDelete(trigger, credentials);\n }\n // Else no-up. A Promise<void> (non-error) is returned implicitly\n}\n\n// Delete a trigger using the real API\nasync function doTriggerDelete(\n trigger: string,\n credentials: Credentials\n): Promise<object> {\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${credentials.namespace}/triggers/${trigger}`,\n method: 'delete'\n };\n return doAxios(config, credentials.do_token);\n}\n\n// Code to get all the triggers for a namespace, or all the triggers for a function in the namespace.\nexport async function listTriggersForNamespace(\n namespace: string,\n credentials: Credentials,\n fcn?: string\n): Promise<string[]> {\n debug('listing triggers');\n const { do_token } = credentials;\n if (do_token) {\n return doTriggerList(namespace, credentials, fcn);\n }\n // No-op if no envvars are set\n return [];\n}\n\n// The trigger list API returns this structure (abridged here to just what we care about)\ninterface TriggerList {\n triggers: TriggerInfo[];\n}\ninterface TriggerInfo {\n name: string;\n function: string;\n}\n\n// List triggers using the real API. Currently, filtering by function is not\n// provided by the API so it is done here.\nasync function doTriggerList(\n namespace: string,\n credentials: Credentials,\n fcn: string\n): Promise<string[]> {\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${namespace}/triggers`,\n method: 'get'\n };\n let triggers: TriggerList;\n try {\n triggers = (await doAxios(config, credentials.do_token)) as TriggerList;\n } catch (err) {\n debug('error listing triggers: %s', err.message);\n return [];\n }\n debug('got trigger list result from the API: %O', triggers);\n if (!triggers.triggers) {\n debug('result did not have triggers member');\n return [];\n }\n const filtered = fcn\n ? triggers.triggers.filter((trig) => trig.function === fcn)\n : triggers.triggers;\n const names = filtered.map((trig) => trig.name);\n debug('reduced the list to %O', names);\n return names;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n DeployStructure,\n DeployResponse,\n ActionSpec,\n PackageSpec,\n KeyVal,\n Feedback,\n DeploySuccess\n} from './deploy-struct';\nimport {\n combineResponses,\n wrapError,\n wrapSuccess,\n keyVal,\n emptyResponse,\n getActionName,\n straysToResponse,\n makeDict,\n digestPackage,\n digestAction,\n loadVersions,\n waitForActivation\n} from './util';\nimport openwhisk from 'openwhisk';\nimport { deployTriggers } from './triggers';\nimport makeDebug from 'debug';\n\nconst debug = makeDebug('nim:deployer:deploy');\nconst seqDebug = makeDebug('nim:deployer:sequences');\nconst chunkDebug = makeDebug('nim:deployer:chunk');\n\n// Temp fix until https://github.com/apache/openwhisk-client-js/pull/225 is merged.\ntype Exec = openwhisk.Exec & { image?: string };\n\n//\n// Main deploy logic, excluding that assigned to more specialized files\n//\n\n// The max number of operations to have outstanding at a time (for actions).\n// It isn't obvious how to tune this, but 25 seems to work reliably and 50 sometimes has\n// failures. I have had success with 40, actually, but don't want to push our luck.\nconst DEPLOYMENT_CHUNK_SIZE = parseInt(process.env.DEPLOYMENT_CHUNK_SIZE) || 25;\n\n// Load the versions if incremental. If not incremental, the former versions are irrelevant.\nexport async function maybeLoadVersions(\n todeploy: DeployStructure\n): Promise<DeployStructure> {\n if (todeploy.flags.incremental) {\n // Incremental deployment requires the versions up front to have access to the form hashes\n todeploy.versions = loadVersions(\n todeploy.filePath,\n todeploy.credentials.namespace,\n todeploy.credentials.ow.apihost\n );\n }\n return Promise.resolve(todeploy);\n}\n\n// Do the actual deployment\nexport async function doDeploy(\n todeploy: DeployStructure\n): Promise<DeployResponse> {\n const skipPkgDeploy =\n todeploy.slice && todeploy.deployerAnnotation.newSliceHandling;\n delete todeploy.deployerAnnotation.newSliceHandling;\n const actionPromises = (todeploy.packages || []).map((pkg) =>\n deployPackage(pkg, todeploy, skipPkgDeploy)\n );\n const responses: DeployResponse[] = await Promise.all(actionPromises);\n responses.push(straysToResponse(todeploy.strays));\n const sequenceResponses = await deploySequences(todeploy);\n responses.push(...sequenceResponses);\n const response = combineResponses(responses);\n response.apihost = todeploy.credentials.ow.apihost;\n if (!response.namespace) {\n response.namespace = todeploy.credentials.namespace;\n }\n return response;\n}\n\n// Process the remote result when something has been built remotely\nasync function processRemoteResponse(\n activationId: string,\n owClient: openwhisk.Client,\n context: string,\n feedback: Feedback\n): Promise<DeployResponse> {\n let activation: openwhisk.Activation<openwhisk.Dict>;\n const tick = () =>\n feedback.progress(`Processing of ${context} is still running remotely ...`);\n try {\n activation = await waitForActivation(activationId, owClient, tick, 15 * 60); // approx 15 minutes limit\n } catch (err) {\n return wrapError(err, context + ' (waiting for remote build response)');\n }\n if (!activation) {\n return wrapError(\n new Error('Build timed out'),\n ' (waiting for remote build response)'\n );\n }\n if (!activation.response || !activation.response.success) {\n let err = 'Remote build failed to provide a result';\n const resultError = activation?.response?.result?.error;\n if (resultError) {\n const errMsg =\n typeof resultError === 'string' ? resultError : resultError.message;\n if (typeof errMsg === 'string') {\n const parts = errMsg.split('Error:');\n err = parts[parts.length - 1];\n }\n }\n const thrown = new Error(err) as any;\n thrown.activation = JSON.stringify(activation, null, 2); // ensure deep enough nesting\n return wrapError(thrown, context + ' (running remote build)');\n }\n const result = activation.response.result as Record<string, any>;\n debug('Remote result was %O', result);\n const { transcript, outcome } = result;\n if (transcript && transcript.length > 0) {\n feedback.progress(`Transcript of remote build session for ${context}:`);\n for (const line of transcript) {\n feedback.progress(line);\n }\n }\n return outcome;\n}\n\n// Deploy an array of actions of arbitrary size, ensuring that most CHUNK_SIZE operations\n// are pending at the same time.\nasync function deployActionArray(\n actions: ActionSpec[],\n spec: DeployStructure\n): Promise<DeployResponse> {\n let pending = actions;\n const responses: DeployResponse[] = [];\n while (pending.length > 0) {\n const chunk =\n pending.length > DEPLOYMENT_CHUNK_SIZE\n ? pending.slice(0, DEPLOYMENT_CHUNK_SIZE)\n : pending;\n pending = pending.slice(chunk.length);\n const chunkResults = await Promise.all(\n chunk.map((action) => deployAction(action, spec))\n ).then(combineResponses);\n responses.push(chunkResults);\n chunkDebug('Deployed chunk of %d actions', chunk.length);\n }\n return combineResponses(responses);\n}\n\n// Subroutine to deploy just a package and not its actions. Should only be called for\n// \"deployable\" packages (not the default package) and only when deployment of the package\n// is appropriate (not if the package has already been deployed or the context is a slice deploy).\nexport async function onlyDeployPackage(\n pkg: PackageSpec,\n spec: DeployStructure\n): Promise<DeployResponse> {\n const {\n parameters: projectParams,\n environment: projectEnv,\n versions,\n owClient: wsk,\n deployerAnnotation: deployer,\n flags\n } = spec;\n // Check whether the package metadata needs to be deployed; if so, deploy it. If not, make a vacuous response with the existing package\n // VersionInfo. That is needed so that the new versions.json will have the information in it.\n const digest = digestPackage(pkg);\n if (\n flags.incremental &&\n versions.packageVersions &&\n versions.packageVersions[pkg.name] &&\n digest === versions.packageVersions[pkg.name].digest\n ) {\n const packageVersions = {};\n packageVersions[pkg.name] = versions.packageVersions[pkg.name];\n return {\n successes: [],\n failures: [],\n ignored: [],\n packageVersions,\n actionVersions: {},\n namespace: undefined\n };\n } else {\n const former = await wsk.packages\n .get({ name: pkg.name })\n .catch(() => undefined);\n const oldAnnots =\n former && former.annotations ? makeDict(former.annotations) : {};\n delete oldAnnots.deployerAnnot; // remove unwanted legacy from undetected earlier error\n deployer.digest = digest.substring(0, 8);\n const annotDict = Object.assign({}, oldAnnots, pkg.annotations, {\n deployer\n });\n const annotations = keyVal(annotDict);\n const mergedParams = Object.assign({}, projectParams, pkg.parameters);\n const mergedEnv = Object.assign({}, projectEnv, pkg.environment);\n const params = encodeParameters(mergedParams, mergedEnv);\n const owPkg: openwhisk.Package = {\n parameters: params,\n annotations,\n publish: pkg.shared\n };\n let successes: DeploySuccess[] = [];\n if (pkg.binding) {\n if (pkg.actions && pkg.actions.length > 0) {\n throw new Error('a bound package may not contain functions of its own');\n }\n owPkg.binding = pkg.binding;\n successes = [{ name: pkg.name, kind: 'binding', skipped: false }];\n }\n debug('successes: %O', successes);\n return await wsk.packages\n .update({ name: pkg.name, package: owPkg })\n .then((result) => {\n const packageVersions = {};\n packageVersions[pkg.name] = { version: result.version, digest };\n return {\n successes,\n failures: [],\n ignored: [],\n packageVersions,\n actionVersions: {},\n namespace: result.namespace\n };\n })\n .catch((err) => {\n return wrapError(err, `package '${pkg.name}'`);\n });\n }\n}\n\n// Deploy a package, then deploy everything in it (currently just actions and triggers associated with those actions).\nexport async function deployPackage(\n pkg: PackageSpec,\n spec: DeployStructure,\n skipPkgDeploy: boolean\n): Promise<DeployResponse> {\n const { parameters: projectParams, environment: projectEnv } = spec;\n if (\n pkg.name === 'default' &&\n (pkg.binding ||\n isAtLeastOneNonEmpty([\n projectParams,\n projectEnv,\n pkg.parameters,\n pkg.environment,\n pkg.annotations\n ]))\n ) {\n return wrapError(\n new Error(\n 'The default package does not support attaching environment, parameters, or binding'\n ),\n `package 'default'`\n );\n }\n if (pkg.name === 'default' || skipPkgDeploy || pkg.deployedDuringBuild) {\n return deployActionArray(pkg.actions, spec);\n }\n const pkgResponse = await onlyDeployPackage(pkg, spec);\n // Now deploy (or skip) the actions of the package\n const actionPromise = await deployActionArray(pkg.actions || [], spec);\n return combineResponses([actionPromise, pkgResponse]);\n}\n\n// Test whether any object in an array of objects is non-empty. Used here to check for illegal attachment of\n// parameters or environment to the 'default' package, which doesn't really exist.\nfunction isAtLeastOneNonEmpty(toCheck: object[]): boolean {\n for (const source of toCheck) {\n if (source && Object.keys(source).length > 0) {\n return true;\n }\n }\n return false;\n}\n\n// Deploy an action\nfunction deployAction(\n action: ActionSpec,\n spec: DeployStructure\n): Promise<DeployResponse> {\n const { owClient: wsk, feedback, reader } = spec;\n const context = `action '${getActionName(action)}'`;\n debug('deploying %s', context);\n if (action.buildError) {\n return Promise.resolve(wrapError(action.buildError, context));\n }\n if (action.buildResult) {\n return processRemoteResponse(action.buildResult, wsk, context, feedback);\n }\n if (action.code) {\n debug('action already has code');\n return deployActionFromCodeOrSequence(action, spec, action.code, undefined);\n }\n if (action.sequence) {\n const error = checkForLegalSequence(action);\n if (error) {\n return Promise.resolve(wrapError(error, context));\n }\n if (!spec.sequences) {\n spec.sequences = [];\n }\n spec.sequences.push(action);\n return Promise.resolve(emptyResponse());\n }\n const codeFile = action.file;\n if (codeFile) {\n debug('reading action code from %s', codeFile);\n return reader\n .readFileContents(codeFile)\n .then((data) => {\n const code = action.binary ? data.toString('base64') : String(data);\n return code;\n })\n .then((code: string) =>\n deployActionFromCodeOrSequence(action, spec, code, undefined)\n )\n .catch((err) => Promise.resolve(wrapError(err, context)));\n } else {\n return Promise.resolve(\n wrapError(\n new Error(\n 'Action is named in the config but does not exist in the project'\n ),\n context\n )\n );\n }\n}\n\n// The ActionSpec is known to include the sequence member but may still not be consistent\nfunction checkForLegalSequence(action: ActionSpec): any {\n if (action.file) {\n return new Error(\n 'An action cannot be a sequence and also exist in the project directory structure'\n );\n }\n if (action.runtime || action.binary || action.main) {\n return new Error(\n 'An action cannot be a sequence and also have the runtime, binary, or main attributes'\n );\n }\n return false;\n}\n\n// Order the sequences of this deployment so that ones that depend on others come later in the order.\n// Throw on cycle.\nfunction sortSequences(\n sequences: ActionSpec[],\n spec: DeployStructure\n): ActionSpec[] {\n const {\n credentials: { namespace }\n } = spec;\n const actionNames = getAllActionFqns(spec, namespace);\n const inProgress = new Set<string>();\n const completed = new Set<string>();\n const result: ActionSpec[] = [];\n for (const seq of sequences) {\n if (\n !addSequenceToList(\n seq,\n namespace,\n result,\n inProgress,\n completed,\n sequences,\n actionNames,\n spec.feedback\n )\n ) {\n // Cycle detected\n throw new Error('A cycle was detected in mutually dependent sequences');\n }\n }\n return result;\n}\n\n// Recursive subroutine of sortSequences to check and position an individual sequence so as to follow its dependencies.\n// To accomplish the goal, the dependencies are added first in the order found, and a \"completed\" set is used to prevent\n// duplicates.\nfunction addSequenceToList(\n seq: ActionSpec,\n namespace: string,\n result: ActionSpec[],\n inProgress: Set<string>,\n completed: Set<string>,\n sequences: ActionSpec[],\n actionNames: Set<string>,\n feedback: Feedback\n): boolean {\n const seqName = fqnFromActionSpec(seq, namespace);\n seqDebug('addSequenceToList %s', seqName);\n if (inProgress.has(seqName)) {\n seqDebug('found in inProgress');\n return false;\n }\n if (completed.has(seqName)) {\n seqDebug('found in completed');\n return true;\n }\n inProgress.add(seqName);\n const thisNsPrefix = '/' + namespace + '/';\n for (const member of seq.sequence) {\n const memberName = fqn(member, namespace);\n const preReq = sequences.find(\n (cand) => memberName === fqnFromActionSpec(cand, namespace)\n );\n if (preReq) {\n seqDebug('Found pre-requisite sequence %s', preReq.name);\n if (\n !addSequenceToList(\n preReq,\n namespace,\n result,\n inProgress,\n completed,\n sequences,\n actionNames,\n feedback\n )\n ) {\n return false;\n }\n }\n if (memberName.startsWith(thisNsPrefix) && !actionNames.has(memberName)) {\n feedback.warn(\n \"Sequence '%s' contains action '%s' which is in the same namespace but not part of the deployment\",\n seq.name,\n memberName\n );\n }\n }\n inProgress.delete(seqName);\n completed.add(seqName);\n seqDebug('adding %s to result', seqName);\n result.push(seq);\n return true;\n}\n\n// Deploy the sequences of the project, if any. These were identified while deploying the\n// actions. Sequence actions were lightly checked, then deferred. Here, we sort the sequences\n// so that dependent sequences are deployed before they are needed by other sequences.\n// If that works (no cycles) then we deploy the result.\nasync function deploySequences(\n todeploy: DeployStructure\n): Promise<DeployResponse[]> {\n try {\n todeploy.sequences = sortSequences(todeploy.sequences || [], todeploy);\n } catch (err) {\n return [wrapError(err, 'sequences')];\n }\n const result: DeployResponse[] = [];\n for (const seq of todeploy.sequences ?? []) {\n const components = seq.sequence.map((action) =>\n fqn(action, todeploy.credentials.namespace)\n );\n const exec: openwhisk.Sequence = { kind: 'sequence', components };\n result.push(\n await deployActionFromCodeOrSequence(seq, todeploy, undefined, exec)\n );\n }\n return result;\n}\n\n// Compute a fully qualified OW name from an ActionSpec plus a default namespace\nfunction fqnFromActionSpec(spec: ActionSpec, namespace: string): string {\n let name = spec.name;\n if (spec.package && spec.package !== 'default') {\n name = `${spec.package}/${name}`;\n }\n return `/${namespace}/${name}`;\n}\n\n// Get the fqns of all actions in the spec\nfunction getAllActionFqns(\n spec: DeployStructure,\n namespace: string\n): Set<string> {\n const ans = new Set<string>();\n for (const pkg of spec.packages ?? []) {\n if (pkg.actions) {\n pkg.actions.forEach((action) =>\n ans.add(fqnFromActionSpec(action, namespace))\n );\n }\n }\n return ans;\n}\n\n// Convert an OW resource name to fqn form (it may already be in that form)\nfunction fqn(name: string, namespace: string): string {\n if (name.startsWith('/')) {\n return name;\n }\n return `/${namespace}/${name}`;\n}\n\nfunction encodeParameters(\n normalParms: openwhisk.Dict,\n envParms: openwhisk.Dict\n): KeyVal[] {\n let ans: KeyVal[] = [];\n if (normalParms) {\n ans = keyVal(normalParms);\n }\n if (envParms) {\n const envs = keyVal(envParms);\n envs.forEach((env) => {\n env.init = true;\n });\n ans = ans.concat(envs);\n }\n return ans;\n}\n\n// Construct the Action.Exec struct from the deployment configuration values.\nexport function calculateActionExec(action: ActionSpec, code: string): Exec {\n const main = action.main ? action.main : undefined; // '' is falsey but won't be recognized as such by OW\n if (action.docker) {\n return {\n code,\n binary: action.binary,\n kind: 'blackbox',\n image: action.docker,\n main\n };\n }\n\n return { code, binary: action.binary, kind: action.runtime, main };\n}\n\n// Deploy an action when the code has already been read from a() file or constructed programmatically or when the\n// action is a sequence (Sequence passed in lieu of code).\nasync function deployActionFromCodeOrSequence(\n action: ActionSpec,\n spec: DeployStructure,\n code: string,\n sequence: openwhisk.Sequence\n): Promise<DeployResponse> {\n const name = getActionName(action);\n const { versions, flags, deployerAnnotation, owClient: wsk } = spec;\n const deployerAnnot = Object.assign({}, deployerAnnotation);\n\n debug('deploying %s using %s', name, !sequence ? 'code' : 'sequence info');\n if (code && !action.runtime) {\n return Promise.resolve(\n wrapError(\n new Error(\n `Action '${name}' not deployed: runtime type could not be determined`\n ),\n `action ${name}`\n )\n );\n }\n // Check whether the action needs to be deployed; if so, deploy it. If not, make a vacuous response with the existing package\n // VersionInfo. That is needed so that the new versions.json will have the information in it. We don't digest\n // or skip deployment for sequences.\n let digest: string;\n if (!sequence) {\n // test for absence of sequence, not presence of code; code may be the empty string\n digest = digestAction(action, code);\n debug('computed digest for %s', name);\n if (\n flags.incremental &&\n versions.actionVersions &&\n versions.actionVersions[name] &&\n digest === versions.actionVersions[name].digest\n ) {\n // Skipping deployment\n debug('matched digest for %s', name);\n const actionVersions = {};\n actionVersions[name] = versions.actionVersions[name];\n return Promise.resolve(\n wrapSuccess(name, 'action', true, actionVersions, undefined)\n );\n }\n // Record\n debug('recording digest for %s', name);\n deployerAnnot.digest = digest.substring(0, 8);\n }\n // Will be deployed\n // Compute the annotations that we will definitely be adding\n deployerAnnot.zipped = action.zipped;\n const annotations = Object.assign({}, action.annotations) || {};\n annotations.deployer = deployerAnnot;\n annotations.final = true;\n\n if (action.web === true) {\n annotations['web-export'] = true;\n annotations['raw-http'] = false;\n } else if (action.web === 'raw') {\n annotations['web-export'] = true;\n annotations['raw-http'] = true;\n } else if (!action.web) {\n annotations['web-export'] = false;\n annotations['raw-http'] = false;\n }\n if (typeof action.webSecure === 'string') {\n annotations['require-whisk-auth'] = action.webSecure;\n } else {\n // A value of true should already have been flagged at validation time.\n annotations['require-whisk-auth'] = false;\n }\n // Get the former annotations of the action if any\n const options = { name, code: false };\n const former = await wsk.actions.get(options).catch(() => undefined);\n const oldAnnots =\n former && former.annotations ? makeDict(former.annotations) : {};\n // Merge the annotations\n const annotDict = Object.assign({}, oldAnnots, annotations);\n // Compute the complete Action value for the call\n const params = encodeParameters(action.parameters, action.environment);\n const exec = sequence || calculateActionExec(action, code);\n const actionBody: openwhisk.Action = {\n annotations: keyVal(annotDict),\n parameters: params,\n exec: exec as Exec\n };\n if (action.limits) {\n actionBody.limits = action.limits;\n }\n const deployParams = { name, action: actionBody };\n try {\n const response = await wsk.actions.update(deployParams);\n\n let triggerResults: (DeploySuccess | Error)[] = [];\n if (action.triggers) {\n triggerResults = await deployTriggers(\n action.triggers,\n name,\n spec.credentials\n );\n }\n const map = {};\n if (digest) {\n map[name] = { version: response.version, digest };\n }\n const namespace = response.namespace.split('/')[0];\n const success = wrapSuccess(name, 'action', false, map, namespace);\n for (let i = 0; i < triggerResults.length; i++) {\n if (triggerResults[i] instanceof Error) {\n const err = triggerResults[i] as any;\n err.context = `while deploying trigger '${action.triggers[i].name}'`;\n success.failures.push(triggerResults[i] as Error);\n } else {\n success.successes.push(triggerResults[i] as DeploySuccess);\n }\n }\n return Promise.resolve(success);\n } catch (err) {\n // Note this is not the usual catch block for trigger deployment errors. Those are caught in\n // deployTriggers and fed back in the results. The function itself will not be backed out if triggers\n // fail to deploy. Rather, both statuses are reported (success for the function and possibly some\n // triggers, failure for those triggers that failed). We reach here if the function fails to deploy\n // or if system-level errors occurred in the logic somewhere.\n return Promise.resolve(wrapError(err, `action '${name}'`));\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport {\n DeployStructure,\n PackageSpec,\n ActionSpec,\n Includer,\n ProjectReader,\n PathKind,\n Feedback\n} from './deploy-struct';\nimport {\n emptyStructure,\n actionFileToParts,\n filterFiles,\n loadProjectConfig,\n errorStructure,\n getDeployerAnnotation,\n getBestProjectName\n} from './util';\nimport { getBuildForAction, getBuildForLib } from './finder-builder';\nimport makeDebug from 'debug';\nimport { makeFileReader } from './file-reader';\nimport { fetchSlice } from './slice-reader';\nconst debug = makeDebug('nim:deployer:project-reader');\n\nconst CONFIG_FILE = 'project.yml';\nconst LEGACY_CONFIG_FILE = 'projectConfig.yml';\nconst ENV_FILE = '.env';\n\n// Read the top level files and dirs of the project. Only one file and two dirs are legal at this level; everything else is a 'stray'\ninterface TopLevel {\n lib: string;\n packages: string;\n config?: string;\n env?: string;\n buildEnv?: string;\n strays: string[];\n filePath: string;\n includer: Includer;\n reader: ProjectReader;\n feedback: Feedback;\n noTriggers: boolean;\n}\nexport async function readTopLevel(\n filePath: string,\n env: string,\n buildEnv: string,\n includer: Includer,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<TopLevel> {\n debug(\"readTopLevel with filePath:'%s'\", filePath);\n debug('feedback is %O', feedback);\n // Before doing the more expensive operations, check existence of env, which is cheap. If does not exist we will fail later anyway.\n if (env && !fs.existsSync(env)) {\n throw new Error(`The specified environment file '${env}' does not exist`);\n }\n if (buildEnv && !fs.existsSync(buildEnv)) {\n throw new Error(\n `The specified environment file '${buildEnv}' does not exist`\n );\n }\n if (filePath.startsWith('slice:')) {\n debug('fetching slice');\n filePath = await fetchSlice(filePath.replace('slice:', ''));\n if (!filePath) {\n throw new Error('Could not fetch slice');\n }\n }\n const reader = makeFileReader(filePath);\n const pkgDir = 'packages';\n const libDir = 'lib';\n return reader.readdir('').then((items) => {\n items = filterFiles(items);\n let config: string;\n let notconfig: string;\n let legacyConfig: string;\n let packages: string;\n const strays: string[] = [];\n let lib: string;\n for (const item of items) {\n if (item.isDirectory) {\n switch (item.name) {\n case pkgDir:\n packages = pkgDir;\n break;\n case libDir:\n lib = libDir;\n break;\n case '.nimbella':\n case '.deployed':\n break;\n default:\n strays.push(item.name);\n }\n } else if (!item.isDirectory && item.name === CONFIG_FILE) {\n config = item.name;\n } else if (!item.isDirectory && item.name === LEGACY_CONFIG_FILE) {\n legacyConfig = item.name;\n } else if (\n !item.isDirectory &&\n (item.name.endsWith('.yml') || item.name.endsWith('.yaml'))\n ) {\n notconfig = item.name;\n } else if (!env && !item.isDirectory && item.name === ENV_FILE) {\n // Env file reading will not go through the reader so use a path that includes a path to the project\n env = path.join(filePath, item.name);\n } else {\n strays.push(item.name);\n }\n }\n if (legacyConfig && !config) {\n config = legacyConfig;\n feedback.warn(\n `Warning: the name '${LEGACY_CONFIG_FILE}' is deprecated; please rename to '${CONFIG_FILE}' soon`\n );\n }\n if (notconfig && !config) {\n feedback.warn('Warning: found %s but no %s', notconfig, CONFIG_FILE);\n }\n const ans = {\n lib,\n packages,\n config,\n strays,\n filePath,\n env,\n buildEnv,\n includer,\n reader,\n feedback,\n noTriggers\n };\n debug('readTopLevel returning %O', ans);\n return ans;\n });\n}\n\n// Probe the top level structure to obtain the major parts of the final config. Spawn builders for those parts and\n// assemble a \"Promise.all\" for the combined work\nexport async function buildStructureParts(\n topLevel: TopLevel\n): Promise<DeployStructure[]> {\n const {\n lib,\n packages,\n config,\n strays,\n filePath,\n env,\n buildEnv,\n includer,\n reader,\n feedback,\n noTriggers\n } = topLevel;\n let configPart = await readConfig(\n config,\n env,\n buildEnv,\n filePath,\n includer,\n reader,\n feedback,\n noTriggers\n );\n const deployerAnnotation =\n configPart.deployerAnnotation || (await getDeployerAnnotation(filePath));\n configPart = Object.assign(configPart, {\n strays,\n filePath,\n includer,\n reader,\n feedback,\n deployerAnnotation\n });\n const displayName = getBestProjectName(configPart);\n debug('display path for actions is %O', displayName);\n const actionsPart = await buildActionsPart(\n packages,\n displayName,\n includer,\n reader\n );\n configPart.libBuild = await getBuildForLib(lib, reader);\n return [actionsPart, configPart];\n}\n\n// Assemble a complete initial structure containing all file system information and config. May be deployed as is or adjusted\n// before deployment. Input is the resolved output of buildStructureParts.\nexport function assembleInitialStructure(\n parts: DeployStructure[]\n): DeployStructure {\n debug('Assembling structure from parts');\n const [actionsPart, configPart] = parts;\n const errPart = parts.find((part) => part.error);\n if (errPart) {\n return errPart;\n }\n const strays = (actionsPart.strays || []).concat(configPart.strays || []);\n configPart.strays = strays;\n configPart.packages =\n actionsPart.packages && configPart.packages\n ? mergePackages(actionsPart.packages, configPart.packages)\n : actionsPart.packages\n ? actionsPart.packages\n : configPart.packages\n ? configPart.packages\n : [];\n adjustWebExportFlags(configPart.packages);\n debug('Result of assembly: %O', configPart);\n return configPart;\n}\n\n// Merge 'packages' portion of config, if any, into the 'packages' array read from the file system.\n// The merge key is the package name.\nfunction mergePackages(\n fs: PackageSpec[],\n config: PackageSpec[]\n): PackageSpec[] {\n const merge = {};\n fs.forEach((pkg) => {\n merge[pkg.name] = pkg;\n });\n config.forEach((pkg) => {\n const already = merge[pkg.name];\n if (already) {\n merge[pkg.name] = mergePackage(already, pkg);\n } else {\n (pkg.actions || []).forEach((action) => {\n action.package = pkg.name;\n });\n merge[pkg.name] = pkg;\n }\n });\n const ans: PackageSpec[] = [];\n for (const name in merge) {\n ans.push(merge[name]);\n }\n return ans;\n}\n\n// Merge a single PackageSpec: the file system and config contributions have the same name. The actions are merged.\n// Other attributes are preferentially taken from the config.\nfunction mergePackage(fs: PackageSpec, config: PackageSpec): PackageSpec {\n const fsActions = fs.actions;\n const cfgActions = config.actions;\n const ans = Object.assign({}, fs, config);\n if (fsActions && fsActions.length > 0) {\n if (cfgActions && cfgActions.length > 0) {\n ans.actions = mergeActions(fsActions, cfgActions, config.name);\n } else {\n ans.actions = fsActions;\n }\n } else {\n ans.actions = cfgActions;\n }\n return ans;\n}\n\n// Adjust the web export value for the actions of the project. For each action that already has this property set, leave it alone.\n// Otherwise, if its package specifies a web export value use it. Otherwise, apply the default of 'true'. Must test explicitly\n// for 'undefined' type since false is a real value but is falsey.\nfunction adjustWebExportFlags(pkgs: PackageSpec[]) {\n pkgs.forEach((pkg) => {\n if (pkg.actions) {\n pkg.actions.forEach((action) => {\n if (typeof action.web === 'undefined') {\n action.web = typeof pkg.web === 'undefined' ? true : pkg.web;\n }\n });\n }\n });\n}\n\n// Merge the actions portion of a PackageSpec in config, if any, into the corresponding PackageSpec actions read from the file system.\n// The merge key is the action name.\nfunction mergeActions(\n fs: ActionSpec[],\n config: ActionSpec[],\n pkgName: string\n): ActionSpec[] {\n const merge = {};\n fs.forEach((action) => {\n merge[action.name] = action;\n });\n config.forEach((action) => {\n const already = merge[action.name];\n if (already) {\n merge[action.name] = mergeAction(already, action);\n } else {\n action.package = pkgName;\n merge[action.name] = action;\n }\n });\n const ans: ActionSpec[] = [];\n for (const name in merge) {\n ans.push(merge[name]);\n }\n return ans;\n}\n\n// Merge a single ActionSpec: the file system and config contributions have the same name. The config contributions\n// take precedence\nfunction mergeAction(fs: ActionSpec, config: ActionSpec): ActionSpec {\n debug('Action from filesystem: %O', fs);\n debug('Action from config: %O', config);\n const result = Object.assign({}, fs, config);\n debug('Result of merge: %O', result);\n return result;\n}\n\n// Probe the packages directory\nfunction buildActionsPart(\n pkgsdir: string,\n displayPath: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<DeployStructure> {\n if (!pkgsdir) {\n return Promise.resolve(emptyStructure());\n } else {\n return buildPkgArray(\n pkgsdir,\n displayPath + '/packages',\n includer,\n reader\n ).then((values) => {\n const [strays, pkgs] = values;\n return { packages: pkgs, strays: strays };\n });\n }\n}\n\n// Accumulate the arrays of PackageSpecs and Strays in the 'packages' directory\nfunction buildPkgArray(\n pkgsDir: string,\n displayPath: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<any> {\n debug('Building package array');\n return reader.readdir(pkgsDir).then((items: PathKind[]) => {\n items = filterFiles(items);\n const strays = items\n .filter((dirent) => !dirent.isDirectory)\n .map((dirent) => dirent.name);\n const pkgNames = items\n .filter((dirent) => dirent.isDirectory)\n .map((dirent) => dirent.name);\n const rdrs: Promise<PackageSpec>[] = [];\n for (const name of pkgNames) {\n if (includer.isPackageIncluded(name, false)) {\n const pkgPath = path.join(pkgsDir, name);\n rdrs.push(\n readPackage(\n pkgPath,\n path.join(displayPath, name),\n name,\n includer,\n reader\n )\n );\n }\n }\n return Promise.all([Promise.resolve(strays), Promise.all(rdrs)]);\n });\n}\n\n// Read the contents of a directory defining a package. By convention, actions not requiring a build step are stored directly in the\n// package directory. Those requiring a build are stored in a subdirectory. The name of each action is the single file name (sans suffix)\n// or the name of the subdirectory.\nasync function readPackage(\n pkgPath: string,\n displayPath: string,\n pkgName: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<PackageSpec> {\n debug(\n \"reading information for package '%s' with display path '%s'\",\n pkgPath,\n displayPath\n );\n return reader\n .readdir(pkgPath)\n .then(async (items: PathKind[]) => {\n items = filterFiles(items);\n const promises: Promise<ActionSpec>[] = [];\n const seen = new Map<string, string>();\n for (const item of items) {\n const file = path.join(pkgPath, item.name);\n const displayFile = path.join(displayPath, item.name);\n debug('item %s has display path %s', item.name, displayFile);\n if (!item.isDirectory) {\n // Directly deployable action not requiring a build.\n const { name, runtime, binary, zipped } = await actionFileToParts(\n item.name\n );\n if (!includer.isActionIncluded(pkgName, name)) continue;\n const before = seen.get(name);\n if (before) {\n throw duplicateName(name, before, runtime);\n }\n seen.set(name, runtime);\n promises.push(\n Promise.resolve({\n name,\n file,\n displayFile,\n runtime,\n binary,\n zipped,\n package: pkgName\n })\n );\n } else if (item.isDirectory) {\n // Build-dependent action or renamed action\n if (!includer.isActionIncluded(pkgName, item.name)) continue;\n const before = seen.get(item.name);\n if (before) {\n throw duplicateName(item.name, before, '*');\n }\n seen.set(item.name, '*');\n promises.push(\n getBuildForAction(file, reader).then((build) => {\n return {\n name: item.name,\n file,\n displayFile,\n build,\n package: pkgName\n };\n })\n );\n }\n }\n return Promise.all(promises);\n })\n .then((actions: ActionSpec[]) => {\n return { name: pkgName, actions: actions, shared: false };\n });\n}\n\n// Build an error indicating o duplicate action name. This can happen if, e.g. you have both eval.js and eval.swift\n// or if you have eval.js and an action directory called eval.\nfunction duplicateName(actionName: string, formerUse: string, newUse: string) {\n const former =\n formerUse === '*' ? 'as a directory' : `with runtime '${formerUse}'`;\n const present =\n newUse === '*' ? 'as a directory' : `with runtime '${newUse}'`;\n return new Error(\n `The action name '${actionName}' appears twice, once ${former} and once ${present}`\n );\n}\n\n// Read the config file if present. For convenience, the extra information not merged from elsewhere is tacked on here\nasync function readConfig(\n configFile: string,\n envPath: string,\n buildEnvPath: string,\n filePath: string,\n includer: Includer,\n reader: ProjectReader,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<DeployStructure> {\n if (!configFile) {\n debug('No config file found');\n const ans = Object.assign({}, emptyStructure());\n return Promise.resolve(ans);\n }\n debug('Reading config file');\n const config = loadProjectConfig(\n configFile,\n envPath,\n buildEnvPath,\n filePath,\n reader,\n feedback,\n noTriggers\n )\n .then((config) => trimConfigWithIncluder(config, includer))\n .catch((err) => errorStructure(err));\n debug('Config contents: %O', config);\n return config;\n}\n\n// Given a DeployStructure with a package section, trim that section according to the rules of an Includer\nfunction trimConfigWithIncluder(\n config: DeployStructure,\n includer: Includer\n): DeployStructure {\n if (config.packages) {\n const newPkgs: PackageSpec[] = [];\n for (const pkg of config.packages) {\n if (includer.isPackageIncluded(pkg.name, false)) {\n if (pkg.actions) {\n pkg.actions = pkg.actions.filter((action) =>\n includer.isActionIncluded(pkg.name, action.name)\n );\n }\n newPkgs.push(pkg);\n }\n }\n config.packages = newPkgs;\n }\n return config;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { spawn } from 'child_process';\nimport {\n DeployStructure,\n ActionSpec,\n PackageSpec,\n Flags,\n ProjectReader,\n PathKind,\n Feedback\n} from './deploy-struct';\nimport {\n actionFileToParts,\n filterFiles,\n mapPackages,\n mapActions,\n promiseFilesAndFilterFiles,\n agreeOnRuntime,\n getBestProjectName,\n getExclusionList,\n waitForActivation,\n getActionName,\n encryptProjectConfig\n} from './util';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as yaml from 'js-yaml';\nimport ignore from 'ignore';\nimport axios from 'axios';\nimport archiver from 'archiver';\nimport touch from 'touch';\nimport makeDebug from 'debug';\nimport { Writable } from 'stream';\nimport * as memoryStreams from 'memory-streams';\nimport openwhisk = require('openwhisk');\nimport { canonicalRuntime } from './runtimes';\nimport { onlyDeployPackage } from './deploy';\nimport { MAX_SLICE_UPLOAD_SIZE } from './slice-reader';\n\nconst debug = makeDebug('nim:deployer:finder-builder');\nconst zipDebug = makeDebug('nim:deployer:zip');\n\n// Type to use with the ignore package.\ninterface Ignore {\n filter: (arg: string[]) => string[];\n}\n\nconst ZIP_TARGET = '__deployer__.zip';\nexport const BUILDER_NAMESPACE =\n process.env['TEST_BUILDER_NAMESPACE'] || 'nimbella';\nconst BUILDER_ACTION_STEM = `/${BUILDER_NAMESPACE}/builder/build_`;\nconst GET_UPLOAD_URL = `/${BUILDER_NAMESPACE}/builder/getUploadUrl`;\nconst CANNED_REMOTE_BUILD = `#!/bin/bash\nset -e\n/bin/defaultBuild %MAIN%\n`;\n\n// Determine the build type for an action that is defined as a directory\nexport function getBuildForAction(\n filepath: string,\n reader: ProjectReader\n): Promise<string> {\n return readDirectory(filepath, reader).then((items) =>\n findSpecialFile(items, filepath, true)\n );\n}\n\n// Build all the actions in an array of PackageSpecs, returning a new array of PackageSpecs. We try to return\n// undefined for the case where no building occurred at all, since we are obligated to return a full array if\n// any building occurred, even if most things weren't subject to building.\nexport async function buildAllActions(\n spec: DeployStructure\n): Promise<PackageSpec[]> {\n const packages = spec.packages;\n if (!packages || packages.length === 0) {\n return undefined;\n }\n // If there are any packages, we are going to have to search through them but if none of them build anything we can punt\n const pkgMap = mapPackages(packages);\n const promises: Promise<PackageSpec>[] = [];\n for (const pkg of packages) {\n if ((pkg.actions && pkg.actions.length > 0) || pkg.binding) {\n const builtPackage = buildActionsOfPackage(pkg, spec);\n promises.push(builtPackage);\n }\n }\n if (promises.length === 0) {\n return undefined;\n }\n return Promise.all(promises).then((newpkgs: PackageSpec[]) => {\n for (const pkg of newpkgs) {\n if (pkg) {\n pkgMap[pkg.name] = pkg;\n }\n }\n return Object.values(pkgMap);\n });\n}\n\n// Build the actions of a package, returning an updated PackageSpec or undefined if nothing got built\nasync function buildActionsOfPackage(\n pkg: PackageSpec,\n spec: DeployStructure\n): Promise<PackageSpec> {\n // Determine if any remote builds exist in this package. If so, we have to deploy the package before doing the builds.\n const mustDeployPackage =\n pkg.name !== 'default' &&\n pkg.actions?.some(\n (action) => action.build === 'remote' || action.build === 'remote-default'\n );\n if (mustDeployPackage) {\n const pkgResult = await onlyDeployPackage(pkg, spec);\n if (pkgResult.failures.length > 0) {\n throw pkgResult.failures[0];\n }\n pkg.deployedDuringBuild = true;\n spec.deployerAnnotation.newSliceHandling = true;\n }\n // Now run all the builds in this package\n const actionMap = mapActions(pkg.actions);\n let nobuilds = true;\n for (const action of pkg.actions || []) {\n if (action.build) {\n nobuilds = false;\n const builtAction = await buildAction(action, spec).catch((err) => {\n action.buildError = err;\n return action;\n });\n actionMap[action.name] = builtAction;\n }\n }\n if (nobuilds) {\n return undefined;\n }\n pkg.actions = Object.values(actionMap);\n return pkg;\n}\n\n// Perform the build defined for an action or just return the action if there is no build step\nfunction buildAction(\n action: ActionSpec,\n spec: DeployStructure\n): Promise<ActionSpec> {\n if (!action.build) {\n return Promise.resolve(action);\n }\n debug('building action %O', action);\n let actionDir: string;\n const { reader, flags, feedback, slice, buildEnv } = spec;\n switch (action.build) {\n case 'build.sh':\n actionDir = makeLocal(reader, action.file);\n return scriptBuilder(\n './build.sh',\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case 'build.cmd':\n actionDir = makeLocal(reader, action.file);\n return scriptBuilder(\n 'build.cmd',\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case 'package.json':\n actionDir = makeLocal(reader, action.file);\n return npmBuilder(\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case '.include':\n case 'identify':\n return identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n );\n case 'remote':\n case 'remote-default':\n checkBuiltLocally(reader, action.file);\n return doRemoteActionBuild(action, spec);\n default:\n throw new Error('Unknown build type in ActionSpec: ' + action.build);\n }\n}\n\n// Process .include file by reading it, recognize any .. or absolute path references, expanding directories, and filtering the result.\n// Absolute path references are illegal. References to ../../../lib/* are allowed, otherwise, references outside the build directory\n// are illegal.\n// Returns a list of pairs. In each pair, the first member is the path of a file to be included. The second member is its name the file\n// should assume once included. Except for ../../../lib/* cases, these will be the same. In the latter case, the dirname portion of the\n// path is elided inside the zip file.\nasync function processInclude(\n includesPath: string,\n dirPath: string,\n reader: ProjectReader\n): Promise<string[][]> {\n debug(\"processing includes from '%s'\", includesPath);\n const items = await readFileAsList(includesPath, reader);\n const errMsg = checkIncludeItems(items);\n if (errMsg) {\n return Promise.reject(new Error(errMsg));\n }\n return processIncludeFileItems(items, dirPath, reader);\n}\n\n// Used instead of path.resolve to deal with possible '..' directives. We don't want absolute path names\n// as a result, nor do we want the current directory to be consulted, just path concatenation and normalization.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction joinAndNormalize(...paths: string[]): string {\n return path.normalize(path.join(...paths));\n}\n\n// Convert a path that is relative to the project root into a path usable with 'fs'. This should be done only for things\n// that require real building since it will abort the deploy when the project root cannot be found in the file system.\nfunction makeLocal(reader: ProjectReader, ...paths: string[]): string {\n const project = reader.getFSLocation();\n if (!project) {\n throw new Error('invalid call to makeLocal');\n }\n return path.resolve(project, ...paths);\n}\n\n// Subroutine of processInclude to run after items are read\nasync function processIncludeFileItems(\n items: string[],\n dirPath: string,\n reader: ProjectReader\n): Promise<string[][]> {\n const complex: Promise<string[][]>[] = [];\n const simple: string[][] = [];\n for (let item of items) {\n debug('processing include item %s', item);\n if (item.startsWith('./') || item.startsWith('.\\\\')) {\n item = item.slice(2);\n }\n let oldPath = path.join(dirPath, item);\n if (oldPath.endsWith('/') || oldPath.endsWith('\\\\')) {\n oldPath = oldPath.slice(0, -1);\n }\n debug(\"Calculated oldPath '%s'\", oldPath);\n const lstat: PathKind = await reader.getPathKind(oldPath);\n if (!lstat) {\n return Promise.reject(\n new Error(`${oldPath} is included for '${dirPath}' but does not exist`)\n );\n }\n let newPath: string;\n if (item.includes('..')) {\n // Already screened for legality\n newPath = path.basename(item);\n } else {\n newPath = item;\n }\n const toElide = oldPath.length - newPath.length;\n debug(\"Calculated newPath '%s' with elision %d\", newPath, toElide);\n if (lstat.isFile) {\n simple.push([oldPath, newPath]);\n } else if (lstat.isDirectory) {\n const expanded = promiseFilesAndFilterFiles(oldPath, reader).then(\n (items) => items.map((item) => [item, item.slice(toElide)])\n );\n debug(\"Expanded directory '%s'\", oldPath);\n complex.push(expanded);\n } else {\n return Promise.reject(\n new Error(`'${item}' is neither a file nor a directory`)\n );\n }\n }\n return Promise.all(complex.concat(Promise.resolve(simple))).then((arrays) =>\n arrays.reduce((prev, curr) => prev.concat(curr), [])\n );\n}\n\n// Identify the files that make up an action directory, based on the files in the directory and .include. .source, or .ignore if present.\n// If there is more than one file, perform autozipping.\nasync function identifyActionFiles(\n action: ActionSpec,\n incremental: boolean,\n verboseZip: boolean,\n reader: ProjectReader,\n feedback: Feedback\n): Promise<ActionSpec> {\n let includesPath = path.join(action.file, '.include');\n if (!(await reader.isExistingFile(includesPath))) {\n // Backward compatibility: try .source also\n includesPath = path.join(action.file, '.source');\n }\n if (await reader.isExistingFile(includesPath)) {\n // If there is .include or .source, it is canonical and all else is ignored\n return processInclude(includesPath, action.file, reader).then((pairs) => {\n if (pairs.length === 0) {\n return Promise.reject(new Error(includesPath + ' is empty'));\n } else if (pairs.length > 1) {\n return autozipBuilder(\n pairs,\n action,\n incremental,\n verboseZip,\n reader,\n feedback\n );\n } else {\n return singleFileBuilder(action, pairs[0][0]);\n }\n });\n }\n return getIgnores(action.file, reader).then((ignore) => {\n return promiseFilesAndFilterFiles(action.file, reader).then(\n (items: string[]) => {\n items = applyIgnores(action.file, items, ignore);\n if (items.length === 0) {\n return Promise.reject(\n new Error(`Action '${getActionName(action)}' has no included files`)\n );\n } else if (items.length === 1) {\n return singleFileBuilder(action, items[0]);\n } else {\n const pairs = items.map((item) => {\n const shortName = item.substring(action.file.length + 1);\n return [item, shortName];\n });\n return autozipBuilder(\n pairs,\n action,\n incremental,\n verboseZip,\n reader,\n feedback\n );\n }\n }\n );\n });\n}\n\n// Utility for applying the ignore filter. Sensitive to the limitations of the 'ignore' npm package.\nfunction applyIgnores(basePath: string, items: string[], ignore: Ignore) {\n // If the basepath is already absolute, relativize in hopes that that all paths will be internal.\n // TODO this is not a panacea: we need to pin down our assumptions about how ignore is supposed to work.\n const absolute = path.isAbsolute(basePath);\n if (absolute) {\n items = items.map((item) => path.relative(basePath, item));\n }\n // Do the filtering\n items = ignore.filter(items);\n // Restore absolute paths\n if (absolute) {\n items = items.map((item) => path.join(basePath, item));\n }\n return items;\n}\n\n// Utility for reading .include, .source, or .build\nfunction readFileAsList(\n file: string,\n reader: ProjectReader\n): Promise<string[]> {\n return reader.readFileContents(file).then((data) =>\n String(data)\n .split('\\n')\n .filter((line) => line && line.trim().length > 0)\n .map((line) => line.trim())\n );\n}\n\n// Determine the build step for the lib directory or return undefined if there isn't one\nexport function getBuildForLib(\n filepath: string,\n reader: ProjectReader\n): Promise<string> {\n if (!filepath) {\n return Promise.resolve(undefined);\n }\n return readDirectory(filepath, reader).then((items) =>\n findSpecialFile(items, filepath, false)\n );\n}\n\n// Build the lib directory only if appropriate. It is appropriate to build it\n// if (1) we are deploying a slice (\"already running remotely\") or (2) there is\n// some action that will be deployed locally. In other words,\n// we do _not_ build lib in the case where this deployment is running locally but\n// everything will in fact be deployed remotely.\nexport async function maybeBuildLib(spec: DeployStructure): Promise<void> {\n function isRemote(build: string): boolean {\n return build === 'remote' || build === 'remote-default';\n }\n let shouldBuild = spec.slice;\n if (!shouldBuild && spec.packages) {\n pkgLoop: for (const pkg of spec.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n shouldBuild = action.build && !isRemote(action.build);\n if (shouldBuild) {\n break pkgLoop;\n }\n }\n }\n }\n }\n if (shouldBuild) {\n let scriptPath: string;\n const displayPath = path.join(getBestProjectName(spec), 'lib');\n const { reader, flags, feedback, slice, buildEnv } = spec;\n switch (spec.libBuild) {\n case 'build.sh':\n scriptPath = makeLocal(reader, 'lib');\n return scriptBuilder(\n './build.sh',\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n case 'build.cmd':\n scriptPath = makeLocal(reader, 'lib');\n return scriptBuilder(\n 'build.cmd',\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n case 'package.json':\n scriptPath = makeLocal(reader, 'lib');\n return npmBuilder(\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n default:\n throw new Error(\n 'Unknown or inappropriate build type for lib directory: ' +\n spec.libBuild\n );\n }\n }\n}\n\n// Check whether path seems to denote a directory that is already built (heuristic). Throws if case detected\nfunction checkBuiltLocally(reader: ProjectReader, localPath: string) {\n const loc = reader.getFSLocation();\n if (!loc) {\n debug(\n 'checkBuiltLocally skipped because project reader does not use local file system'\n );\n return;\n }\n const filepath = path.join(loc, localPath);\n debug(\n 'checking for local build artifacts in %s when remote build requested',\n filepath\n );\n if (fs.existsSync(filepath) && fs.lstatSync(filepath).isDirectory()) {\n debug('%s exists and is a directory', filepath);\n const zipped = path.join(filepath, ZIP_TARGET);\n const dotBuilt = path.join(filepath, '.built');\n if (fs.existsSync(zipped) || fs.existsSync(dotBuilt)) {\n throw new Error(\n `Remote build is requested for '${filepath}' but it appears to have been built locally. Remove derived artifacts first.`\n );\n }\n debug('did not find %s or %s', zipped, dotBuilt);\n }\n debug('checkBuiltLocally passed');\n}\n\n// Check that all include file items resolve to \"legal\" places (inside the directory being built or a 'lib' directory at project root)\n// Returns an error message if an illegal item is found, else the empty string.\nexport function checkIncludeItems(items: string[]): string {\n const legalDots = '../../../lib';\n for (const item of items) {\n if (!item || item.length === 0) {\n continue;\n }\n if (path.isAbsolute(item)) {\n return `Absolute paths are prohibited in an '.include' file`;\n }\n if (item.includes('..') && !item.startsWith(legalDots)) {\n return `Illegal use of '..' in an '.include' file`;\n }\n }\n return '';\n}\n\n// Check the .include file, if any, for illegal inclusions. This permits\n// a \"fail-fast\" for remote builds that are going to fail anyway.\nasync function checkRemoteBuildPreReqs(\n filepath: string,\n project: DeployStructure\n) {\n debug(`checking remote build pre-reqs for '${filepath}'`);\n const reader = project.reader;\n if ((await reader.getPathKind(filepath)).isDirectory) {\n const include = path.join(filepath, '.include');\n if (await reader.isExistingFile(include)) {\n debug(`found an .include file for '${filepath}'`);\n const items = await readFileAsList(include, reader);\n debug(`read ${items.length} .include items for '${filepath}'`);\n const msg = checkIncludeItems(items);\n if (msg) {\n throw new Error(msg);\n }\n }\n }\n}\n\n// Initiate request to builder for building an action\nasync function doRemoteActionBuild(\n action: ActionSpec,\n project: DeployStructure\n): Promise<ActionSpec> {\n // Check that a remote build is supportable\n await checkRemoteBuildPreReqs(action.file, project);\n // Get the zipper\n const { zip, output, outputPromise } = makeProjectSliceZip(action.file);\n // Get the project slice in convenient form\n const pkgName = path.basename(path.dirname(action.file));\n const actionName =\n pkgName === 'default' ? action.name : path.join(pkgName, action.name);\n // Zip the actionPath, also determining runtime if the action spec doesn't already have one\n debug('zipping action path %s for project slice', action.file);\n const generateRemote = defaultRemote(action);\n const runtime = await appendToZip(\n zip,\n action.file,\n project.reader,\n generateRemote\n );\n if (!action.runtime) {\n if (!runtime) {\n throw new Error(\n `Could not determine runtime for remote build of '${actionName}'. You may need to specify it in 'project.yml'`\n );\n }\n debug('Setting runtime to %s for remote build', runtime);\n action.runtime = runtime;\n }\n // Add 'lib' if it is present\n if (project.libBuild) {\n await appendLibToZip(zip, 'lib', project.reader);\n }\n // Add the project.yml\n const spec = makeConfigFromActionSpec(action, project, pkgName);\n debug('converting slice spec to YAML: %O', spec);\n\n // Encrypts the configuration file yaml file before uploading it.\n const { config, key } = encryptProjectConfig(yaml.safeDump(spec));\n\n zip.append(config, { name: 'project.yml' });\n debug('finalizing zip for project slice');\n zip.finalize();\n debug('zip finalized for project slice of action %s', getActionName(action));\n await outputPromise;\n debug(\n 'outputPromise settled for project slice of action %s',\n getActionName(action)\n );\n const toSend = (output as memoryStreams.WritableStream).toBuffer();\n debug(\n 'sending the remote build request for project %s and action %s',\n project.filePath,\n actionName\n );\n action.buildResult = await invokeRemoteBuilder(\n toSend,\n project.owClient,\n project.feedback,\n action,\n key\n );\n return action;\n}\n\n// Information about a default remote build\ninterface DefaultRemoteBuildInfo {\n contents: string; // The contents of the generated build.sh\n actionName: string; // the name of the action, used to generate intra-slice paths\n}\n\n// Generate DefaultRemoteBuildInfo from ActionSpec iff appropriate, else undefined\nfunction defaultRemote(action: ActionSpec): DefaultRemoteBuildInfo {\n if (action.build && action.build === 'remote-default') {\n const main = action.main || 'Main';\n const contents = CANNED_REMOTE_BUILD.replace('%MAIN%', main);\n const actionName = action.name;\n return { contents, actionName };\n }\n return undefined;\n}\n\n// Zip a file or directory for a remote build slice. Also attempts to determine a runtime.\n// If the generateBuild argument\n// is defined, it provides the action directory name and indicates that we should add a two-line `build.sh`.\n// This may require changing the single-file case to a multi-file case.\nasync function appendToZip(\n zip: archiver.Archiver,\n actionPath: string,\n reader: ProjectReader,\n generateBuild: DefaultRemoteBuildInfo | undefined\n): Promise<string> {\n const kind = await reader.getPathKind(actionPath);\n let analyzeForRuntime: string[];\n if (kind.isFile) {\n if (generateBuild) {\n // Change to multi-file case, although there is still only one source file\n const parent = path.dirname(actionPath);\n const simpleFile = path.basename(actionPath);\n const name = path.join(parent, generateBuild.actionName, simpleFile);\n const contents = await reader.readFileContents(actionPath);\n zip.append(contents, { name, mode: 0o666 });\n const buildFile = path.join(parent, generateBuild.actionName, 'build.sh');\n zip.append(generateBuild.contents, { name: buildFile, mode: 0o777 });\n } else {\n await appendAndCheck(zip, actionPath, actionPath, reader);\n }\n analyzeForRuntime = [actionPath];\n } else if (kind.isDirectory) {\n zipDebug('getting contents of directory %s for remote build slice', path);\n const files = await promiseFilesAndFilterFiles(actionPath, reader);\n analyzeForRuntime = files;\n for (const file of files) {\n await appendAndCheck(zip, file, actionPath, reader);\n }\n if (generateBuild) {\n const buildFile = path.join(actionPath, 'build.sh');\n zip.append(generateBuild.contents, { name: buildFile, mode: 0o777 });\n }\n }\n return agreeOnRuntime(analyzeForRuntime);\n}\n\n// A simplified version of appendToZip for adding secondary directories (currently 'lib') to the slice\nasync function appendLibToZip(\n zip: archiver.Archiver,\n path: string,\n reader: ProjectReader\n) {\n zipDebug('getting contents of directory %s for remote build slice', path);\n const files = await promiseFilesAndFilterFiles(path, reader);\n for (const file of files) {\n await appendAndCheck(zip, file, path, reader);\n }\n}\n\n// Append a path known to be a file to the in-memory zip, checking for excessive size and issuing debug if requested.\nasync function appendAndCheck(\n zip: archiver.Archiver,\n file: string,\n actionPath: string,\n reader: ProjectReader\n) {\n const contents = await reader.readFileContents(file);\n let mode: number;\n if (file.endsWith('.sh') && process.platform === 'win32') {\n // This is a weak heuristic to be around the fact that there is no executable bit on windows,\n // which can cause remote builds with shell scripts to fail. It might still be necessary for\n // a windows user to understand the issue and fix up permissions on things that don't end in .sh but\n // that really are scripts (this can be done in the primary script build.sh).\n mode = 0o777;\n } else {\n mode = (await reader.getPathKind(file)).mode;\n }\n debug(`mode for ${file} is ${mode}`);\n zip.append(contents, { name: file, mode });\n zipDebug(\"zipped '%s' for remote build slice\", file);\n}\n\n// Slice the project to contain only one ActionSpec; return a DeployStructure that can be written\n// out as a project.yml and also the path to the action file or directory, for zipping.\nfunction makeConfigFromActionSpec(\n action: ActionSpec,\n spec: DeployStructure,\n pkgName: string\n): DeployStructure {\n debug('converting action spec to sliced project.yml: %O', action);\n const {\n targetNamespace,\n parameters,\n environment: globalEnv,\n credentials,\n flags,\n deployerAnnotation,\n buildEnv\n } = spec;\n flags.remoteBuild = false;\n flags.buildEnv = undefined;\n const {\n name,\n runtime,\n main,\n binary,\n zipped,\n web,\n webSecure,\n annotations,\n environment,\n limits\n } = action;\n const newSpec = {\n targetNamespace,\n parameters,\n environment: globalEnv,\n credentials,\n flags,\n deployerAnnotation,\n buildEnv,\n slice: true\n } as DeployStructure;\n const newAction = {\n name,\n runtime,\n main,\n binary,\n zipped,\n web,\n webSecure,\n annotations,\n parameters: action.parameters,\n environment,\n limits\n } as ActionSpec;\n removeUndefined(newSpec);\n removeUndefined(newAction);\n const pkg = Object.assign(\n {},\n spec.packages.find((pkg) => pkg.name === pkgName)\n );\n pkg.actions = [newAction];\n pkg.deployedDuringBuild = false;\n newSpec.packages = [pkg];\n return newSpec;\n}\n\n// Remove undefined fields from object (mutates object but returns it as well)\nfunction removeUndefined(obj: Record<string, any>): Record<string, any> {\n for (const item in obj) {\n if (typeof obj[item] === 'undefined') {\n delete obj[item];\n } else if (typeof obj[item] === 'object') {\n obj[item] = removeUndefined(obj[item]);\n }\n }\n return obj;\n}\n\n// Create an in-memory zip for storing a project slice. Note: code here duplicates code in autozipBuilder. Refactoring\n// to avoid duplication might be delicate and is deferred for now.\ninterface ProjectSliceZip {\n output: Writable;\n zip: archiver.Archiver;\n outputPromise: Promise<any>;\n}\nfunction makeProjectSliceZip(context: string): ProjectSliceZip {\n const output: Writable = new memoryStreams.WritableStream({\n highWaterMark: MAX_SLICE_UPLOAD_SIZE\n });\n const zip = archiver('zip');\n const outputPromise = new Promise(function (resolve, reject) {\n zip.on('error', (err) => {\n debug('zip error occurred: %O', err);\n reject(err);\n });\n output.on('close', () => {\n debug('zipfile successfully closed');\n resolve(undefined);\n });\n output.on('finish', () => {\n debug('zipfile successfully finished');\n resolve(undefined);\n });\n output.on('end', () => {\n debug('zipfile data has been drained');\n });\n output.on('drain', () => {\n debug('memory stream posted a drain event');\n reject(\n new Error(\n `Remote build upload for '${context}' is too large. Make sure the directory is free of derived artifacts`\n )\n );\n });\n zip.on('warning', (err) => {\n debug('warning issued from archiver %O', err);\n if (err.code !== 'ENOENT') {\n reject(err);\n }\n });\n });\n zip.pipe(output);\n return { output, zip, outputPromise };\n}\n\n// Generate a remote build name for the \"legacy\" path\nconst BUCKET_BUILDER_PREFIX = '.nimbella/builds';\nexport function getRemoteBuildName(): string {\n const buildName = new Date().toISOString().replace(/:/g, '-');\n return `${BUCKET_BUILDER_PREFIX}/${buildName}`;\n}\n\n// Computes the tag to be added to a remote build slice name. Should be a function of the\n// qualified action name (pkg/action) but with / replaced by _.\nfunction computeTag(action: ActionSpec): string {\n if (action.package) {\n return `${action.package}_${action.name}`;\n }\n return action.name;\n}\n\n// Expected return value from getUploadUrl\ninterface UploadInfo {\n url: string;\n sliceName: string;\n}\n\n// This function simulates a blocking invoke of the builder/getUploadUrl action without actually\n// blocking at the controller. It does a non-blocking invoke, then polls the returned activation Id.\n// Note: errors thrown by the original invoke or during polling will not be caught here. They are intended\n// to be caught in buildProject, which will handle them appropriately.\nasync function getUploadUrl(\n owClient: openwhisk.Client,\n params: { action: string },\n feedback: Feedback\n): Promise<UploadInfo> {\n const invoked = await owClient.actions.invoke({\n name: GET_UPLOAD_URL,\n params\n });\n const tick = () =>\n feedback.progress(\n `Waiting for permission to upload remote build for '${params.action}'`\n );\n const activation = await waitForActivation(\n invoked.activationId,\n owClient,\n tick,\n 2 * 60\n );\n if (!activation) {\n throw new Error(\n `Timed out awaiting permission to upload remote build for '${params.action}'`\n );\n }\n if (!activation.response || !activation.response.success) {\n let err = 'Failed to get remote build upload permission';\n const resultError = activation?.response?.result?.error;\n if (resultError) {\n const errMsg =\n typeof resultError === 'string' ? resultError : resultError.message;\n if (typeof errMsg === 'string') {\n const parts = errMsg.split('Error:');\n err = parts[parts.length - 1];\n }\n }\n const thrown = new Error(err) as any;\n thrown.activation = JSON.stringify(activation, null, 2); // ensure deep enough nesting\n throw thrown;\n }\n const result = activation.response.result as Record<string, any>;\n return { url: result.url, sliceName: result.sliceName };\n}\n\n// Invoke the remote builder, return the response.\nasync function invokeRemoteBuilder(\n zipped: Buffer,\n owClient: openwhisk.Client,\n feedback: Feedback,\n action: ActionSpec,\n encryptionKey?: string\n): Promise<string> {\n // Upload project slice\n const params = { action: computeTag(action) };\n debug(`Invoking 'getUploadUrl'`);\n const { url, sliceName } = await getUploadUrl(owClient, params, feedback);\n if (!url || !sliceName) {\n const msg = `Unexpected response from getUploadUrl`;\n throw new Error(msg);\n }\n debug('remote build url is %s', url);\n const axiosConfig = {\n // Override capacity limiting defaults\n maxBodyLength: MAX_SLICE_UPLOAD_SIZE,\n maxContentLength: MAX_SLICE_UPLOAD_SIZE\n };\n const result = await axios.put(url, zipped, axiosConfig);\n if (result.status !== 200) {\n throw new Error(\n `Bad response [$result.status}] when uploading '${sliceName}' for remote build`\n );\n }\n debug('axios put of url was successful');\n // Invoke the remote builder action. The action name incorporates the runtime 'kind'.\n // That action will re-invoke the deployer in the target runtime.\n const kind = action.runtime;\n const activityName = `function '${getActionName(action)}'`;\n const runtime = (await canonicalRuntime(kind)).replace(':', '_');\n const buildActionName = `${BUILDER_ACTION_STEM}${runtime}`;\n debug(\n `Invoking remote build action '${buildActionName}' for build '${path.basename(\n sliceName\n )} of ${activityName}`\n );\n try {\n const invoked = await owClient.actions.invoke({\n name: buildActionName,\n params: { toBuild: sliceName, encryptionKey }\n });\n feedback.progress(\n `Submitted ${activityName} for remote building and deployment in runtime ${kind} (id: ${invoked.activationId})`\n );\n return invoked.activationId;\n } catch (err) {\n if (err.statusCode === 404) {\n throw new Error(\n `Remote build service is not available for runtime '${kind}' on this platform instance.`\n );\n } else if (err.statusCode >= 500 && err.statusCode <= 599) {\n throw new Error('Remote build service returned error status.');\n } else {\n throw err;\n }\n }\n}\n\n// Read a directory and filter the result\nfunction readDirectory(\n filepath: string,\n reader: ProjectReader\n): Promise<PathKind[]> {\n return reader.readdir(filepath).then(filterFiles);\n}\n\n// Find the \"dominant\" special file in a collection of files within an action or lib directory, while checking for some errors\n// The dominance order is build.[sh|cmd] > package.json > .include > none-of-these (returns 'identify' since 'building' will\n// then start by identifying files)\n// Errors detected are:\n// .ignore when there is also .include\n// .include and/or .ignore present in the lib directory\n// no files in directory (or only an .ignore file); actions only\n// -- note that this does not find all vacuous builds ... there could be more than one file, e.g., one of\n// which is .ignore and ignores the other, or there could be a vacuous .include. These more complex\n// cases are found later in identifyActionFiles, where a more generic error will result\n// build.cmd but no build.sh on a non-windows system. This is wrong even if the build is later rescheduled to\n// be remote, because the remote build will run in a runtime container which is definitely not windows\n// There is another possible error, which is build.sh but no build.cmd on a windows system. We can't detect that\n// here because we do not yet know whether the build will be remote or local and it is only an error if local.\n// The error will be found in checkBuildingRequirements.\nfunction findSpecialFile(\n items: PathKind[],\n filepath: string,\n isAction: boolean\n): string {\n const files = items.filter((item) => !item.isDirectory);\n let buildDotSh = false;\n let buildDotCmd = false;\n let npm = false;\n let include = false;\n let ignore = false;\n for (const file of files) {\n if (file.name === 'build.sh') {\n buildDotSh = true;\n } else if (file.name === 'build.cmd') {\n buildDotCmd = true;\n } else if (file.name === 'package.json') {\n npm = true;\n } else if (file.name === '.include' || file.name === '.source') {\n include = true;\n } else if (file.name === '.ignore') {\n ignore = true;\n }\n }\n // Error checks\n if (include && ignore) {\n throw new Error(\n `In ${filepath}: '.include' (or '.source') and '.ignore' may not both be present`\n );\n } else if (\n isAction &&\n (files.length === 0 || (ignore && files.length === 1))\n ) {\n throw new Error(`Action directory ${filepath} has no files`);\n } else if (!isAction && (include || ignore)) {\n throw new Error(\n `'.include' and '.ignore' are not supported in the 'lib' directory`\n );\n }\n if (buildDotCmd && process.platform === 'win32') {\n return 'build.cmd';\n }\n if (buildDotCmd && !buildDotSh) {\n throw new Error(\n `In ${filepath}: 'build.cmd' won't run on this platform and no 'build.sh' is provided`\n );\n }\n if (buildDotSh) {\n // We don't do the \"won't run on this platform\" check here because we don't know if the build is remote\n return 'build.sh';\n }\n return npm ? 'package.json' : include ? '.include' : 'identify';\n}\n\n// The 'builder' for use when the action is a single file after all other processing\nasync function singleFileBuilder(\n action: ActionSpec,\n file: string\n): Promise<ActionSpec> {\n debug(\"singleFileBuilder deploying '%s'\", file);\n const newMeta = (await actionFileToParts(file)) as ActionSpec;\n delete newMeta.name;\n newMeta.web = true;\n // After a build, only the file, zipped, and binary flags take precedence over what's in the action already.\n // Metadata calculated from the file name is filled in, as is the default for web, but these apply only if not\n // already specified in the action (except for binary and zipped, which always change to match the build result).\n const { binary, zipped } = newMeta;\n const newAction = Object.assign(newMeta, action, { file, binary, zipped });\n return Promise.resolve(newAction);\n}\n\n// The 'builder' for when multiple files (and/or directories) have been identified as constituting the action.\n// 1. If there is an existing ZIP_TARGET\n// a. If incremental is specified, see whether the autozip can be skipped\n// b. Otherwise, remove the old zip.\n// 2. If there is a runtime provided in the ActionSpec we leave it there. Otherwise, we scan the files to see if we\n// can decide on an unambiguous runtime value. If we can't, it's an error.\n// 3. Use archiver to zip the items individually, according to the rules that\n// - an item is renamed to the basename of the item if it contains ..\n// - an item is zipped as is otherwise\n// - directories are zipped recursively\n// 4. Return an ActionSpec promise describing the result.\nasync function autozipBuilder(\n pairs: string[][],\n action: ActionSpec,\n incremental: boolean,\n verboseZip: boolean,\n reader: ProjectReader,\n feedback: Feedback\n): Promise<ActionSpec> {\n if (verboseZip) {\n feedback.progress('Zipping action contents in', action.file);\n } else {\n debug('Zipping action contents in %s', action.file);\n }\n if (!action.runtime) {\n action.runtime = await agreeOnRuntime(pairs.map((pair) => pair[0]));\n }\n // If there's real file system, observe and store the zip results there for incremental support\n const targetZip = path.join(action.file, ZIP_TARGET);\n const inMemory = reader.getFSLocation() === null;\n let output: Writable;\n if (!inMemory) {\n zipDebug('zipping to %s for action %s', targetZip, getActionName(action));\n const localTargetZip = makeLocal(reader, targetZip);\n pairs = pairs.map((pair) => [makeLocal(reader, pair[0]), pair[1]]);\n if (fs.existsSync(localTargetZip)) {\n zipDebug('the file exists and will be either reused or deleted');\n if (incremental) {\n const metaFiles: string[] = [\n makeLocal(reader, action.file, '.include'),\n makeLocal(reader, action.file, '.ignore')\n ].filter(fs.existsSync);\n debug(\n 'checking whether to build a new zip for %s with metaFiles %o',\n getActionName(action),\n metaFiles\n );\n if (\n zipFileAppearsCurrent(\n localTargetZip,\n pairs.map((pair) => pair[0]).concat(metaFiles)\n )\n ) {\n return singleFileBuilder(action, targetZip);\n }\n }\n zipDebug('deleting old target zip');\n fs.unlinkSync(localTargetZip);\n }\n output = fs.createWriteStream(localTargetZip);\n } else {\n zipDebug('zipping to memory buffer for action %s', getActionName(action));\n output = new memoryStreams.WritableStream({ highWaterMark: 1024 * 1024 });\n }\n const zip = archiver('zip');\n const outputPromise = new Promise(function (resolve, reject) {\n zip.on('error', (err) => {\n zipDebug('zip error occurred: %O', err);\n reject(err);\n });\n output.on('close', () => {\n zipDebug('zipfile successfully closed');\n resolve(undefined);\n });\n output.on('finish', () => {\n zipDebug('zipfile successfully finished');\n resolve(undefined);\n });\n output.on('end', () => {\n zipDebug('zipfile data has been drained');\n });\n zip.on('warning', (err) => {\n zipDebug('warning issued from archiver %O', err);\n if (err.code !== 'ENOENT') {\n reject(err);\n }\n });\n });\n zip.pipe(output);\n zipDebug('zipping %d files', pairs.length);\n for (const pair of pairs) {\n const [oldPath, newPath] = pair;\n const pathKind = await reader.getPathKind(oldPath);\n if (pathKind.symlink) {\n zip.symlink(newPath, pathKind.symlink);\n } else {\n const mode = pathKind.mode;\n const data = await reader.readFileContents(oldPath);\n zipDebug(\n \"Zipping file with old path '%s', buffer length '%d', new path '%s', and mode %d\",\n oldPath,\n data.length,\n newPath,\n mode\n );\n zip.append(data, { name: newPath, mode: mode });\n zipDebug(\n \"Zipped '%s' for action '%s', emitted %d\",\n newPath,\n action.name,\n zip.pointer()\n );\n }\n }\n zipDebug('finalizing zip for action %s', action.name);\n zip.finalize();\n zipDebug('zip finalized for action %s', action.name);\n return outputPromise.then(() => {\n if (verboseZip) {\n feedback.progress('Zipping complete in', action.file);\n } else {\n debug('zipping complete for %s', action.name);\n }\n if (inMemory) {\n const code = (output as memoryStreams.WritableStream)\n .toBuffer()\n .toString('base64');\n if (!code) {\n return Promise.reject(\n new Error('An error occurred in in-memory zipping')\n );\n }\n zipDebug(\n 'in memory zipping complete with code of length %d',\n code.length\n );\n action.code = code as string;\n return singleFileBuilder(action, action.file);\n } else {\n return singleFileBuilder(action, targetZip);\n }\n });\n}\n\n// Subroutine for performing a \"real\" build requiring a spawn.\nfunction build(\n cmd: string,\n args: string[],\n realPath: string,\n displayPath: string,\n infoMsg: string,\n errorTag: string,\n verbose: boolean,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n debug('building with realPath=%s and displayPath=%s', realPath, displayPath);\n let result = '';\n let time = Date.now();\n function statusUpdate(data: { toString: () => string }) {\n result += data.toString();\n const newTime = Date.now();\n if (newTime - time > 5000) {\n time = newTime;\n feedback.progress('Still running', infoMsg, 'in', displayPath);\n }\n }\n const env = buildEnv ? Object.assign({}, process.env, buildEnv) : process.env;\n return new Promise(function (resolve, reject) {\n feedback.progress('Started running', infoMsg, 'in', displayPath);\n const shell =\n process.platform === 'win32' ? true : process.env.shell || '/bin/bash';\n const child = spawn(cmd, args, { cwd: realPath, shell, env });\n if (verbose && !slice) {\n // Verbose build behavior when build is local\n child.stdout.on('data', (data) => feedback.progress(String(data)));\n child.stderr.on('data', (data) => feedback.warn(String(data)));\n } else {\n // Non-verbose build behavior and verbose build behavior when build is remote\n child.stdout.on('data', statusUpdate);\n child.stderr.on('data', statusUpdate);\n }\n child.on('close', (code) => {\n if (code !== 0) {\n // Failure case: locally, we dump the result iff verbose was not requested.\n // Remotely, we always dump the result because it always has to be shown on error.\n if (!verbose || slice) {\n feedback.warn('Output of failed build in %s', realPath);\n feedback.warn(result);\n }\n reject(new Error(`'${errorTag}' exited with code ${code}`));\n } else {\n // Success case.\n feedback.progress('Finished running', infoMsg, 'in', displayPath);\n // For a local build, verbosity, if requested, has already occurred.\n // For a remote build, verbosity requires dumping the accumulated output.\n if (verbose && slice) {\n // Only warn is active for a remote build, so use that channel to report\n feedback.warn(result);\n }\n resolve(undefined);\n }\n });\n child.on('error', (err) => {\n reject(err);\n });\n });\n}\n\n// The builder for a shell script\nfunction scriptBuilder(\n script: string,\n realPath: string,\n displayPath: string,\n flags: Flags,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n if (flags.incremental && scriptAppearsBuilt(realPath)) {\n if (flags.verboseBuild) {\n feedback.progress(\n `Skipping build in ${displayPath} because the action was previously built`\n );\n }\n return Promise.resolve(true);\n }\n return build(\n script,\n [],\n realPath,\n displayPath,\n script,\n script,\n flags.verboseBuild,\n buildEnv,\n slice,\n feedback\n );\n}\n\n// Determine if a shell-script style build appears to have been run. For this we just check for the presence of a `.built` file since\n// we don't have any dependency information. If the author of the build wants to do better, he should do dependency checking _in_ the build\n// and never write a `.built` marker; in that case, the build will always run but will usually do very little.\nfunction scriptAppearsBuilt(filepath: string): boolean {\n const toTest = path.join(filepath, '.built');\n return fs.existsSync(toTest);\n}\n\n// Determine if a new zip should be generated. The existing zip is considered current if it is newer than its dependencies.\n// This won't happen when zipping is in memory because that only happens when there is no local file system and\n// hence no possibility of incremental building.\nfunction zipFileAppearsCurrent(\n zipfile: string,\n dependencies: string[]\n): boolean {\n const ziptime = fs.statSync(zipfile).mtimeMs;\n for (const dep of dependencies) {\n if (fs.existsSync(dep)) {\n if (fs.statSync(dep).mtimeMs > ziptime) {\n debug('%s not considered current because %s is newer', zipfile, dep);\n return false;\n }\n } else {\n debug(\"dependency %s doesn't exist\", dep);\n return false; // play it safe\n }\n }\n debug('%s seems up to date so no re-zip', zipfile);\n return true;\n}\n\n// Determine if an npm|yarn style build appears to have been run \"recently enough\". This is heuristic and does not do a full dependency check.\n// It returns true iff both `node_modules` and either of `package-lock.json` or `yarn.lock` are present and newer than `package.json`.\nfunction npmPackageAppearsBuilt(filepath: string): boolean {\n const packageJson = path.join(filepath, 'package.json');\n const packageLockJson = path.join(filepath, 'package-lock.json');\n const yarnLock = path.join(filepath, 'yarn.lock');\n const nodeModules = path.join(filepath, 'node_modules');\n const packageJsonTime = fs.statSync(packageJson).mtimeMs;\n const packageLockJsonTime = fs.existsSync(packageLockJson)\n ? fs.statSync(packageLockJson).mtimeMs\n : 0;\n const nodeModulesTime = fs.existsSync(nodeModules)\n ? fs.statSync(nodeModules).mtimeMs\n : 0;\n const yarnLockTime = fs.existsSync(yarnLock)\n ? fs.statSync(yarnLock).mtimeMs\n : 0;\n const lockTime =\n yarnLockTime > packageLockJsonTime ? yarnLockTime : packageLockJsonTime;\n return lockTime >= packageJsonTime && nodeModulesTime >= packageJsonTime;\n}\n\n// To avoid getting 'stuck' when package.json changes in a way that does not cause an update to the lock file or node_modules,\n// we touch these resources after every npm build\nfunction makeNpmPackageAppearBuilt(filepath: string) {\n const packageLockJson = path.join(filepath, 'package-lock.json');\n if (fs.existsSync(packageLockJson)) touch(packageLockJson);\n const yarnLock = path.join(filepath, 'yarn.lock');\n if (fs.existsSync(yarnLock)) touch(yarnLock);\n const nodeModules = path.join(filepath, 'node_modules');\n if (fs.existsSync(nodeModules)) touch(nodeModules);\n}\n\n// The builder for npm|yarn install --production or npm|yarn install && npm|yarn run build\n// A package.json must be present since this builder wouldn't have been invoked otherwise.\n// This doesn't mean that npm|yarn install will succeed, just that, if it fails it is for some other reason\nfunction npmBuilder(\n filepath: string,\n displayPath: string,\n flags: Flags,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n debug('Performing npm build for %s', filepath);\n const cmd = flags.yarn ? 'yarn' : 'npm';\n const npmRunBuild = buildScriptExists(filepath);\n const args = npmRunBuild\n ? ['install', '&&', cmd, 'run', 'build']\n : ['install', '--production'];\n const infoMsg = [cmd, ...args].join(' ');\n if (flags.incremental) {\n debug('Detected incremental build');\n const pkgBuilt = npmPackageAppearsBuilt(filepath);\n const scriptBuilt = scriptAppearsBuilt(filepath);\n const shouldSkip = npmRunBuild ? pkgBuilt && scriptBuilt : pkgBuilt;\n debug(\n `npmRunBuild=${!!npmRunBuild}, npmPackageAppearsBuilt=${pkgBuilt}, scriptAppearsBuilt=${scriptBuilt}, shouldSkip=${shouldSkip}`\n );\n if (shouldSkip) {\n if (flags.verboseBuild) {\n feedback.progress(\n `Skipping '${infoMsg}' in ${filepath} because the previous build is still valid`\n );\n }\n return Promise.resolve(true);\n }\n } else {\n debug('Build was not incremental');\n }\n return build(\n cmd,\n args,\n filepath,\n displayPath,\n infoMsg,\n `${cmd} install`,\n flags.verboseBuild,\n buildEnv,\n slice,\n feedback\n ).then(() => makeNpmPackageAppearBuilt(filepath));\n}\n\n// Test whether the `package.json` of a filepath (known to exist) contains a 'build' script.\n// We can assume that the local file system is usable.\nfunction buildScriptExists(filepath: string): boolean {\n const contents = fs.readFileSync(path.join(filepath, 'package.json'));\n try {\n const pj = JSON.parse(String(contents));\n return pj.scripts && pj.scripts.build;\n } catch {\n // For any parse failure, we simply avoid leaking the exception, which will be uninformative\n // since the user doesn't realize we are doing our own parse of package.json. The ensuing\n // 'npm install'' or 'yarn install' will then fail with a diagnostic much more familiar to\n // the developer who provided the unparsable package.json.\n return false;\n }\n}\n\n// Get the Ignore object for screening files. This always has the fixed entries for .ignore itself, .build, build.sh, and .build.cmd\n// but adds anything found in an .ignore file. Note that package.json is not ignored, even though it is a build trigger. We\n// also don't add an entry for .include (or .source) since that case is driven by a fixed set of files and not by scanning a directory.\nfunction getIgnores(dir: string, reader: ProjectReader): Promise<Ignore> {\n const filePath = path.join(dir, '.ignore');\n const fixedItems = [\n '.ignore',\n 'build.sh',\n 'build.cmd',\n ZIP_TARGET,\n ...getExclusionList()\n ];\n return readFileAsList(filePath, reader)\n .then((items) => {\n return ignore().add(items.concat(fixedItems));\n })\n .catch(() => {\n return ignore().add(fixedItems);\n });\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport makeDebug from 'debug';\nimport Zip from 'adm-zip';\nimport * as rimraf from 'rimraf';\nimport { DeployStructure } from './deploy-struct';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand\n} from '@aws-sdk/client-s3';\nimport { Readable, Writable } from 'stream';\nimport { WritableStream } from 'memory-streams';\n\nconst debug = makeDebug('nim:deployer:slice-reader');\nconst TEMP = process.platform === 'win32' ? process.env.TEMP : '/tmp';\nconst bucket = process.env.BUILDER_BUCKET_NAME;\nconst endpoint = process.env.S3_ENDPOINT;\n// Environment must also contain AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY\n\n// MAX_SLICE_UPLOAD_SIZE governs the maximum supported zipped size for a project slice\nexport const MAX_SLICE_UPLOAD_SIZE =\n parseInt(process.env.MAX_SLICE_UPLOAD_SIZE) || 64 * 1024 * 1024;\n\nlet s3Client: S3Client;\n\n// Supports the fetching and deletion of project slices from build bucket.\n// Uses the aws s3 client directly (does not go through the Nimbella storage\n// abstraction). Assumes the necessary s3 properties are in the environment.\n// This will not work on older clusters (e.g `nimgcp`) where the use of a data\n// bucket associated with the namespace is assumed. A nim CLI < 2.0.0 must be\n// used for those clusters.\n\n// Get the cache area\nfunction cacheArea() {\n return path.join(TEMP, 'slices');\n}\n\n// Get the s3 client\nfunction getS3Client(): S3Client {\n if (!s3Client) {\n s3Client = new S3Client({ endpoint, region: 'us-east-1' });\n }\n return s3Client;\n}\n\n// Pipe data from one stream to another\nfunction pipe(input: Readable, output: Writable): Promise<unknown> {\n const toWait = new Promise(function (resolve) {\n output.on('close', () => {\n resolve(true);\n });\n output.on('finish', () => {\n resolve(true);\n });\n });\n input.pipe(output);\n return toWait;\n}\n\n// Fetch the slice to cache storage.\nexport async function fetchSlice(sliceName: string): Promise<string> {\n const cache = path.join(cacheArea(), sliceName);\n if (fs.existsSync(cache)) {\n rimraf.sync(cache);\n }\n debug('Making cache directory: %s', cache);\n fs.mkdirSync(cache, { recursive: true });\n const s3 = getS3Client();\n const cmd = new GetObjectCommand({ Bucket: bucket, Key: sliceName });\n const result = await s3.send(cmd);\n const content = result.Body as Readable; // Body has type ReadableStream<any>|Readable|Blob. Readable seems to work in practice\n const destination = new WritableStream({\n highWaterMark: MAX_SLICE_UPLOAD_SIZE\n });\n await pipe(content, destination);\n const data = (destination as WritableStream).toBuffer();\n const zip = new Zip(data);\n debug('zip file has %d entries', zip.getEntries().length);\n for (const entry of zip.getEntries().filter((entry) => !entry.isDirectory)) {\n const target = path.join(cache, entry.entryName);\n const parent = path.dirname(target);\n if (!fs.existsSync(parent)) {\n fs.mkdirSync(parent, { recursive: true });\n }\n const mode = entry.attr >>> 16;\n debug('storing %s', entry.entryName);\n fs.writeFileSync(target, entry.getData(), { mode });\n }\n return cache;\n}\n\n// Delete\nexport async function deleteSlice(project: DeployStructure): Promise<void> {\n const sliceName = path.relative(cacheArea(), project.filePath);\n const s3 = getS3Client();\n const cmd = new DeleteObjectCommand({ Bucket: bucket, Key: sliceName });\n await s3.send(cmd);\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as fs from 'fs';\nimport * as Path from 'path';\nimport { promisify } from 'util';\nimport { ProjectReader, PathKind } from './deploy-struct';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:file-reader');\n\n// Don't run promisify at module scope: will fail in browser. This module will never actually be used in a browser.\nlet fs_readdir: (\n dir: fs.PathLike,\n options: { withFileTypes: boolean }\n) => Promise<fs.Dirent[]>;\nlet fs_readfile: (file: fs.PathLike) => Promise<any>;\nlet fs_lstat: (path: fs.PathLike) => Promise<any>;\nlet fs_realpath: (path: fs.PathLike) => Promise<any>;\nlet fs_readlink: (path: fs.PathLike) => Promise<any>;\n\n// The file system implementation of ProjectReader\n// The file system implementation accepts absolute paths and relative paths landing anywhere in the filesystem.\n// At 'make' time, the path of the project (within the file system is provided)\n\n// Make\nexport function makeFileReader(basepath: string): ProjectReader {\n debug(\"making file reader on basepath '%s'\", basepath);\n fs_readdir = promisify(fs.readdir);\n fs_readfile = promisify(fs.readFile);\n fs_lstat = promisify(fs.lstat);\n fs_realpath = promisify(fs.realpath);\n fs_readlink = promisify(fs.readlink);\n return new FileProjectReader(basepath);\n}\n\n// Implementing class\nclass FileProjectReader implements ProjectReader {\n // Project location in the file system\n basepath: string;\n\n constructor(basepath: string) {\n this.basepath = basepath;\n }\n\n // Retrieve the basepath\n getFSLocation(): string {\n return this.basepath;\n }\n\n // File system implementation of readdir.\n async readdir(path: string): Promise<PathKind[]> {\n debug(\"request to read directory '%s'\", path);\n path = Path.resolve(this.basepath, path);\n path = await fs_realpath(path);\n debug(\"resolved to directory '%s\", path);\n const entries = await fs_readdir(path, { withFileTypes: true });\n const results = entries.map(async (entry) => {\n let isFile: boolean, isDirectory: boolean, symlink: string;\n if (entry.isSymbolicLink()) {\n try {\n const fullName = await fs_realpath(Path.resolve(path, entry.name));\n const stat = await fs_lstat(fullName);\n isFile = stat.isFile();\n isDirectory = stat.isDirectory();\n } catch (_) {\n symlink = await fs_readlink(Path.resolve(path, entry.name));\n }\n } else {\n isFile = entry.isFile();\n isDirectory = entry.isDirectory();\n }\n return { name: entry.name, isDirectory, isFile, symlink, mode: 0o666 };\n });\n return Promise.all(results);\n }\n\n // File system implementation of readFileContents\n async readFileContents(path: string): Promise<Buffer> {\n debug('request to read %s', path);\n path = Path.resolve(this.basepath, path);\n path = await fs_realpath(path);\n return fs_readfile(path);\n }\n\n // File system implementation of isExistingFile\n isExistingFile(path: string): Promise<boolean> {\n debug(\"testing existence for file '%s'\", path);\n path = Path.resolve(this.basepath, path);\n debug(\"resolved to file '%s\", path);\n return fs_lstat(path)\n .then((stats: fs.Stats) => {\n if (stats.isFile()) {\n debug('file exists');\n return true;\n }\n debug('path exists but is not a file');\n return false;\n })\n .catch(() => {\n debug('lstat failed for path %s', path);\n return false;\n });\n }\n\n // File system implementation of getPathKind\n async getPathKind(path: string): Promise<PathKind> {\n path = Path.resolve(this.basepath, path);\n const stats = await fs_lstat(path).catch(() => undefined);\n if (!stats) {\n return undefined;\n }\n let symlink: string;\n if (stats.isSymbolicLink()) {\n symlink = await fs_readlink(path);\n }\n return {\n name: Path.basename(path),\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n symlink,\n mode: stats.mode\n };\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { Includer } from './deploy-struct';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:includer');\n\n// Make an includer\nexport function makeIncluder(include: string, exclude: string): Includer {\n const includes = include ? include.split(',') : undefined;\n const excludes = exclude ? exclude.split(',') : undefined;\n const ans = new IncluderImpl(includes, excludes);\n debug('constructed includer: %O', ans);\n return ans;\n}\n\n// The implementation behind the Includer interface\nclass IncluderImpl implements Includer {\n isExcludingOnly = false;\n includedPackages: Set<string> = new Set();\n excludedPackages: Set<string> = new Set();\n includedActions: Map<string, Set<string>> = new Map();\n excludedActions: Map<string, Set<string>> = new Map();\n\n // Construct\n constructor(includes: string[], excludes: string[]) {\n if (!includes) {\n this.isExcludingOnly = true;\n } else {\n for (let token of includes) {\n if (token.endsWith('/')) {\n token = token.slice(0, -1);\n }\n const [pkg, action] = token.split('/');\n if (action) {\n this.addToMap(pkg, action, this.includedActions);\n } else {\n this.includedPackages.add(pkg);\n }\n }\n }\n if (excludes) {\n for (let token of excludes) {\n if (token.endsWith('/')) {\n token = token.slice(0, -1);\n }\n const [pkg, action] = token.split('/');\n if (action) {\n this.addToMap(pkg, action, this.excludedActions);\n } else {\n this.excludedPackages.add(pkg);\n }\n }\n }\n }\n\n // Implement isPackageIncluded\n isPackageIncluded = (pkg: string, all: boolean) => {\n const nominallyIncluded =\n this.includedPackages.has(pkg) ||\n (this.isExcludingOnly && !this.excludedPackages.has(pkg));\n if (all) {\n return nominallyIncluded && !this.excludedActions.has(pkg);\n } else {\n return nominallyIncluded || this.includedActions.has(pkg);\n }\n };\n\n // Implement isActionIncluded\n isActionIncluded = (pkg: string, action: string) => {\n if (this.isActionInMap(pkg, action, this.includedActions)) {\n return true; // explicitly included\n }\n if (\n this.excludedPackages.has(pkg) ||\n this.isActionInMap(pkg, action, this.excludedActions)\n ) {\n return false; // excluded, either explicitly or at package level\n }\n // So far, the action is not excluded but was not explicitly included either so the result depends on package inclusion\n return this.isExcludingOnly || this.includedPackages.has(pkg);\n };\n\n // Implement isIncludingEverything\n isIncludingEverything = () => {\n return (\n this.isExcludingOnly &&\n this.includedActions.size === 0 &&\n this.includedPackages.size === 0\n );\n };\n\n // Utility to add an action to an action map\n addToMap(pkg: string, action: string, map: Map<string, Set<string>>) {\n let set = map.get(pkg);\n if (!set) {\n set = new Set();\n map.set(pkg, set);\n }\n set.add(action);\n }\n\n // Utility to interrogate whether an action is in an action map\n isActionInMap(\n pkg: string,\n action: string,\n map: Map<string, Set<string>>\n ): boolean {\n const set = map.get(pkg);\n if (!set) {\n return false;\n }\n return set.has(action);\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Contains the main public (library) API of the deployer (some exports in 'util' may also be used externally but are incidental)\n\nimport { doDeploy, maybeLoadVersions } from './deploy';\nimport {\n DeployStructure,\n DeployResponse,\n PackageSpec,\n OWOptions,\n Credentials,\n Flags,\n Includer,\n Feedback,\n DefaultFeedback\n} from './deploy-struct';\nimport {\n readTopLevel,\n buildStructureParts,\n assembleInitialStructure\n} from './project-reader';\nimport {\n isTargetNamespaceValid,\n wrapError,\n wipe,\n writeProjectStatus,\n getTargetNamespace,\n checkBuildingRequirements,\n errorStructure,\n isRealBuild\n} from './util';\nimport { buildAllActions, maybeBuildLib } from './finder-builder';\nimport openwhisk = require('openwhisk');\nimport { getCredentialsForNamespace, getCredentials } from './credentials';\nimport { makeIncluder } from './includer';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:api');\n\n// Initialize the API by 1. purging existing __OW_ entries from the environment, 2. setting __OW_USER_AGENT, 3. returning a map of\n// entries that were purged. Also saves the __OW_NAMESPACE and __OW_API_HOST values in the environment, renamed, for the special\n// cases where there is no credential store but certain code paths still must work. An example is the slice reader.\nexport function initializeAPI(userAgent: string): { [key: string]: string } {\n const result: Record<string, string> = {};\n for (const item in process.env) {\n if (item.startsWith('__OW_')) {\n result[item] = process.env[item];\n delete process.env[item];\n }\n }\n process.env.__OW_USER_AGENT = userAgent;\n // Careful with these transfers. Assigning a value to the env always casts to string (even undefined -> \"undefined\")\n if (result.__OW_NAMESPACE) {\n process.env.savedOW_NAMESPACE = result.__OW_NAMESPACE;\n }\n if (result.__OW_API_HOST) {\n process.env.savedOW_API_HOST = result.__OW_API_HOST;\n }\n if (result.__OW_API_KEY) {\n process.env.savedOW_API_KEY = result.__OW_API_KEY;\n }\n return result;\n}\n\n// Get a vaguely valid user agent string. Hopefully, this was set in the environment during initialize. But, we use some fallbacks if not.\n// It is not necessary to call this function when using the OW client because it will respect __OW_USER_AGENT directly. It is used\n// when using other web APIs in order to set a valid and possibly useful value in the user-agent header.\nexport function getUserAgent(): string {\n const ans = process.env.__OW_USER_AGENT;\n return ans || 'nimbella-cli';\n}\n\n// Deploy a disk-resident project given its path and options to pass to openwhisk. The options are merged\n// with those in the config; the result must include api or apihost, and must include api_key.\nexport async function deployProject(\n path: string,\n credentials: Credentials | undefined,\n flags: Flags\n): Promise<DeployResponse> {\n debug('deployProject invoked with incremental %s', flags.incremental);\n return readPrepareAndBuild(path, credentials, flags).then((spec) => {\n if (spec.error) {\n debug('An error was caught prior to %O:', spec.error);\n return Promise.resolve(wrapError(spec.error, undefined));\n }\n return deploy(spec);\n });\n}\n\n// Combines the read, prepare, and build phases but does not deploy\nexport function readPrepareAndBuild(\n path: string,\n credentials: Credentials,\n flags: Flags,\n feedback?: Feedback\n): Promise<DeployStructure> {\n return readAndPrepare(path, credentials, flags, feedback).then((spec) =>\n spec.error ? spec : buildProject(spec)\n );\n}\n\n// Combines the read and prepare phases but does not build or deploy\nexport function readAndPrepare(\n path: string,\n credentials: Credentials,\n flags: Flags,\n feedback?: Feedback\n): Promise<DeployStructure> {\n const includer = makeIncluder(flags.include, flags.exclude);\n return readProject(\n path,\n flags.env,\n flags.buildEnv,\n includer,\n flags.remoteBuild,\n feedback,\n flags.noTriggers\n ).then((spec) =>\n spec.error ? spec : prepareToDeploy(spec, credentials, flags)\n );\n}\n\n// Perform deployment from a deploy structure. The 'cleanOrLoadVersions' step is currently folded into this step\nexport function deploy(todeploy: DeployStructure): Promise<DeployResponse> {\n debug('Starting deploy');\n return maybeLoadVersions(todeploy)\n .then(doDeploy)\n .then((results) => {\n const statusDir = writeProjectStatus(\n todeploy.filePath,\n results,\n todeploy.includer.isIncludingEverything()\n );\n if (statusDir && !todeploy.slice) {\n todeploy.feedback.progress(\n `Deployment status recorded in '${statusDir}'`\n );\n }\n if (!results.namespace && todeploy.credentials) {\n results.namespace = todeploy.credentials.namespace;\n }\n debug('deploy results are: %O', results);\n return results;\n });\n}\n\n// Read the information contained in the project, initializing the DeployStructure\nexport async function readProject(\n projectPath: string,\n envPath: string,\n buildEnvPath: string,\n includer: Includer,\n requestRemote: boolean,\n feedback: Feedback = new DefaultFeedback(),\n noTriggers = false\n): Promise<DeployStructure> {\n debug(\n 'Starting readProject, projectPath=%s, envPath=%s',\n projectPath,\n envPath\n );\n let ans: DeployStructure;\n try {\n const topLevel = await readTopLevel(\n projectPath,\n envPath,\n buildEnvPath,\n includer,\n feedback,\n noTriggers\n );\n const parts = await buildStructureParts(topLevel);\n ans = assembleInitialStructure(parts);\n } catch (err) {\n return errorStructure(err);\n }\n if (ans.error) {\n // Remaining steps are treacherous if there was an error detected in the config. We don't use the\n // errorStructure return for that case, because we need to support get-metadata, which wants a config\n // even if erroneous. However, any other uses are going to fail.\n return ans;\n }\n debug('evaluating the just-read project: %O', ans);\n try {\n await checkBuildingRequirements(ans, requestRemote);\n } catch (err) {\n return errorStructure(err);\n }\n return ans;\n}\n\n// 'Build' the project by running the \"finder builder\" steps in\n// 1. the 'lib' directory if found and if building it is appropriate\n// 2. each action-as-directory\n// These steps cannot be overlapped.\nexport async function buildProject(\n project: DeployStructure\n): Promise<DeployStructure> {\n debug('Starting buildProject with spec %O', project);\n if (project.libBuild && isRealBuild(project.libBuild)) {\n try {\n await maybeBuildLib(project);\n } catch (err) {\n return errorStructure(err);\n }\n }\n const actionPromise: Promise<PackageSpec[]> = buildAllActions(project);\n if (actionPromise) {\n return actionPromise\n .then((packages) => {\n project.packages = packages;\n return project;\n })\n .catch((err) => errorStructure(err));\n } else {\n return Promise.resolve(project);\n }\n}\n\n// Prepare a DeployStruct for deployment.\n// 1. Ensure that we are using the right credentials\n// 2. Merge credentials and user-specified auth/apihost flags that were not necessarily part of the credentials.\n// 3. Open the OW client handle to ensure it is valid before the (possibly extensive) build step is performed.\n// Validation includes the optional check on the target namespace; even if it came from the credentials it might no longer be valid.\nexport async function prepareToDeploy(\n inputSpec: DeployStructure,\n credentials: Credentials,\n flags: Flags\n): Promise<DeployStructure> {\n debug('Starting prepare with spec: %O', inputSpec);\n // 0. Handle slice. In that case, credentials and flags come from the DeployStructure\n if (inputSpec.slice) {\n debug('Retrieving credentials and flags from spec for slice');\n credentials = inputSpec.credentials;\n // The API host in the slice spec may represent a proxy and hence not be the real intended host.\n // If __OW_API_HOST is set, it is more trustworthy.\n if (process.env.__OW_API_HOST) {\n credentials.ow.apihost = process.env.__OW_API_HOST;\n } else if (process.env.savedOW_API_HOST) {\n credentials.ow.apihost = process.env.savedOW_API_HOST;\n }\n flags = inputSpec.flags;\n }\n // 1. Acquire credentials if not already present\n const owOptions: OWOptions = {\n api_key: flags.auth,\n apihost: flags.apiHost,\n ignore_certs: flags.insecure\n };\n if (!credentials) {\n debug('Finding credentials locally');\n let namespace: string;\n if (inputSpec.targetNamespace) {\n namespace = inputSpec.targetNamespace;\n }\n if (namespace) {\n // The config specified a target namespace so attempt to use it.\n debug('Retrieving specific credentials for namespace %s', namespace);\n credentials = await getCredentialsForNamespace(\n namespace,\n owOptions.apihost\n );\n } else {\n // There is no target namespace so get credentials for the current one\n let badCredentials: Error;\n debug('Attempting to get credentials for current namespace');\n credentials = await getCredentials().catch((err) => {\n badCredentials = err;\n return undefined;\n });\n if (badCredentials) {\n debug(\n 'Could not get credentials, returning error structure with %O',\n badCredentials\n );\n return errorStructure(badCredentials);\n }\n }\n }\n debug('owOptions: %O', owOptions);\n debug('credentials.ow: %O', credentials.ow);\n // Merge and save credentials information\n const wskoptions: OWOptions = {\n api_key: owOptions.api_key || credentials.ow.api_key,\n apihost: owOptions.apihost || credentials.ow.apihost,\n ignore_certs: owOptions.ignore_certs || credentials.ow.ignore_certs\n };\n debug('wskoptions\" %O', wskoptions);\n inputSpec.credentials = credentials;\n debug('prepareToDeploy merging flags: %O', flags);\n inputSpec.flags = flags;\n debug('Options merged');\n // 3. Open handles\n debug('Auth sufficiency established');\n inputSpec.owClient = openwhisk(wskoptions);\n if (!credentials.namespace) {\n credentials.namespace = await getTargetNamespace(inputSpec.owClient);\n } else {\n await isTargetNamespaceValid(inputSpec.owClient, credentials.namespace);\n }\n debug('Target namespace validated');\n debug('Sensitive project/namespace guard passed');\n debug('returning spec %O', inputSpec);\n return Promise.resolve(inputSpec);\n}\n\n// Utility to convert errors into useful messages. Usually, this just means getting the message field from the error but there\n// is logic to recognize the particular error pattern used by OW\nexport function getMessageFromError(err: any): string {\n // Although we attempt to say that all errors have type Error, in the loosy-goosy untyped world of Javascript this is easily violated.\n // Sometimes 'err' is just a string\n if (typeof err === 'string') {\n return err;\n }\n // Pattern match against the OW error pattern\n if (err.error && err.error.error && err.error.code) {\n return '[OpenWhisk] ' + err.error.error;\n }\n // Default case\n return err.message;\n}\n\n// Wipe a namespace of everything except its activations (the activations cannot be wiped via the public API)\nexport async function wipeNamespace(credentials: Credentials): Promise<void> {\n debug(\n 'Requested wipe-namespace function with host %s and auth %s',\n credentials.ow.apihost,\n credentials.ow.api_key\n );\n const init: OWOptions = {\n apihost: credentials.ow.apihost,\n api_key: credentials.ow.api_key\n };\n const client = openwhisk(init);\n debug('Client opened');\n return wipe(client, credentials);\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// This is the essence of the old watch command from Nimbella CLI.\n// It should probably be replaced by go code or at least revised to use the best available\n// file-watching techniques for the target OSs.\n\nimport * as fs from 'fs';\nimport * as chokidar from 'chokidar';\nimport { Flags, Credentials } from './deploy-struct';\nimport { Logger, deployProject } from './main';\nimport { isExcluded, delay } from './util';\n\n// Validate a project and start watching it if it actually looks like a project\nexport function watch(\n project: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n logger: Logger\n) {\n logger.log(`Watching '${project}' [use Control-C to terminate]`);\n let watcher: chokidar.FSWatcher;\n const reset = async () => {\n if (watcher) {\n //logger.log(\"Closing watcher\")\n await watcher.close();\n }\n };\n const watch = () => {\n //logger.log(\"Opening new watcher\")\n watcher = chokidar.watch(project, {\n ignoreInitial: true,\n followSymlinks: false,\n usePolling: false,\n useFsEvents: false\n });\n watcher.on('all', async (event, filename) => {\n if (!isExcluded(filename)) {\n await fireDeploy(\n project,\n filename,\n cmdFlags,\n creds,\n logger,\n reset,\n watch,\n event\n );\n }\n });\n };\n watch();\n}\n\n// Fire a deploy cycle. Suspends the watcher so that mods made to the project by the deployer won't cause a spurious re-trigger.\n// TODO this logic was crafted for fs.watch(). There might be a better way to suspend chokidar.\n// Displays an informative message before deploying.\nasync function fireDeploy(\n project: string,\n filename: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n logger: Logger,\n reset: () => Promise<void>,\n watch: () => void,\n event: string\n) {\n if (event === 'addDir') {\n // Don't fire on directory add ... it never represents a complete change.\n return;\n }\n if (event === 'add' && isSymlink(filename)) {\n // There may be a bug in chokidar ... we seem to get spurious add events for symlinks.\n // We strongly discourage symlinks within projects, so a new symlink is likely to be inside\n // a node_modules where we can ignore it.\n return;\n }\n await reset();\n logger.log(`\\nDeploying '${project}' due to change in '${filename}'`);\n let error = false;\n const result = await deployProject(\n project,\n cmdFlags,\n creds,\n true,\n logger\n ).catch((err) => {\n logger.displayError('', err);\n error = true;\n });\n if (error || !result) {\n return;\n }\n logger.log('Deployment complete. Resuming watch.\\n');\n await delay(200).then(() => watch());\n}\n\n// Test whether a file is a symlink\nfunction isSymlink(filename: string): boolean {\n try {\n const stat = fs.lstatSync(filename);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { readAndPrepare, readProject, buildProject, deploy } from './api';\nimport {\n Flags,\n OWOptions,\n DeployResponse,\n Credentials,\n Feedback\n} from './deploy-struct';\nimport { deleteSlice } from './slice-reader';\nimport { makeIncluder } from './includer';\nimport { getRuntimeForAction, renameActionsToFunctions } from './util';\nimport { watch } from './watch';\nimport * as path from 'path';\nimport { default as parser } from 'yargs-parser';\nimport { STATUS_CODES } from 'http';\nimport createDebug from 'debug';\nimport { version } from './version';\nconst verboseError = createDebug('nim:error');\n\n// Provides a limited purpose main function for the deployer\n//main().then(flush).catch(handleError)\n\n// Also provides a library entry point (runCommand) which abstracts the output\n// of the main function so it can be captured.\n\n// The Logger type is adopted from the nim CLI\nexport interface Logger {\n log: (msg: string, ...args: any[]) => void;\n handleError: (msg: string, err?: Error) => never;\n exit: (code: number) => void; // don't use 'never' here because 'exit' doesn't always exit\n displayError: (msg: string, err?: Error) => void;\n logJSON: (entity: any) => void;\n logTable: (\n data: Record<string, unknown>[],\n columns: Record<string, unknown>,\n options: Record<string, unknown>\n ) => void;\n logOutput: (json: any, msgs: string[]) => void;\n}\n\n// The default logger implementation\nexport class DefaultLogger implements Logger {\n log(msg = '', ...args: any[]): void {\n console.log(msg, ...args);\n }\n\n handleError(msg: string, err?: Error): never {\n if (err) throw err;\n msg = improveErrorMsg(msg, err);\n throw new Error(msg);\n }\n\n displayError(msg: string, err?: Error): void {\n msg = improveErrorMsg(msg, err);\n verboseError('%O', err);\n const bang = process.platform === 'win32' ? '\u00BB' : '\u203A';\n console.error(bang + ' Error: ' + msg);\n }\n\n exit(code: number): void {\n process.exit(code);\n }\n\n logJSON(entity: Record<string, unknown>): void {\n console.log(JSON.stringify(entity, null, 2));\n }\n\n logTable(\n data: Record<string, unknown>[],\n _columns: Record<string, unknown>,\n _options: Record<string, unknown> = {}\n ): void {\n console.log(JSON.stringify(data, null, 2));\n }\n\n logOutput(json: Record<string, unknown>, msgs: string[]): void {\n for (const msg of msgs) {\n console.log(msg);\n }\n console.log(JSON.stringify(json, null, 2));\n }\n}\n\n// An alternative Logger for capturing output\nexport class CaptureLogger implements Logger {\n table: Record<string, unknown>[]; // The output table (array of entity) if that kind of output was produced\n captured: string[] = []; // Captured line by line output (flowing via Logger.log)\n errors: string[] = []; // Captured calls to displayError (these are Errors that are not supposed to be thrown)\n entity: Record<string, unknown>; // An output entity if that kind of output was produced\n\n log(msg = '', ...args: any[]): void {\n const msgs = String(msg).split('\\n');\n for (const msg of msgs) {\n this.captured.push(msg, ...args);\n }\n }\n\n handleError(msg: string, err?: Error): never {\n if (err) throw err;\n msg = improveErrorMsg(msg, err);\n throw new Error(msg);\n }\n\n displayError(msg: string, err?: Error): void {\n msg = improveErrorMsg(msg, err);\n this.errors.push(msg);\n }\n\n exit(_code: number): void {\n // a no-op here\n }\n\n logJSON(entity: Record<string, unknown>): void {\n this.entity = entity;\n }\n\n logTable(\n data: Record<string, unknown>[],\n _columns: Record<string, unknown>,\n _options: Record<string, unknown> = {}\n ): void {\n this.table = data;\n }\n\n logOutput(json: Record<string, unknown>, msgs: string[]): void {\n this.entity = json;\n this.captured = msgs;\n }\n}\n\n// Wrap a Logger in a Feedback for using the deployer API.\nclass LoggerFeedback implements Feedback {\n logger: Logger;\n warnOnly: boolean;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n warn(msg?: any, ...args: any[]): void {\n this.logger.log(String(msg), ...args);\n }\n\n progress(msg?: any, ...args: any[]): void {\n if (this.warnOnly) return;\n this.logger.log(String(msg), ...args);\n }\n}\n\n// Ensure that console output is flushed when the command is really finished\nexport async function flush() {\n process.stdout.once('drain', () => process.exit(0));\n}\n\n// Deal with errors thrown from within the deployer\nexport function handleError(err: any) {\n console.error(err);\n process.exit(1);\n}\n\n// Parsing template: declares the flags\nconst parsing = {\n string: ['env', 'build-env', 'apihost', 'auth', 'include', 'exclude'],\n boolean: [\n 'insecure',\n 'verbose-build',\n 'verbose-zip',\n 'yarn',\n 'remote-build',\n 'incremental',\n 'json',\n 'no-triggers'\n ],\n configuration: {\n 'parse-positional-numbers': false,\n 'unknown-options-as-args': true,\n 'boolean-negation': false\n }\n};\n\n// Main function. The thinnest possible shell around 'runCommand' which is a library-level entry\n// point suitable for use by a reduced doctl plugin. The only thing added here is the default logger,\n// which simply causes output to go directly to the console.\nexport function main(): Promise<void> {\n return runCommand(process.argv.slice(2), new DefaultLogger());\n}\n\n// Primary library entry point for running the commands with an arbitrary Logger\nexport async function runCommand(inputArgs: string[], logger: Logger) {\n const parsed = parser(inputArgs, parsing);\n const args = parsed._ as string[];\n const badFlags = args.filter((arg) => arg.startsWith('-'));\n if (badFlags.length > 0) {\n logger.handleError(`unknown flag(s): [${badFlags}]`);\n }\n if (args.length != 2 && args[0] !== 'version') {\n logger.handleError(\n 'exactly two non-flag tokens are required: the command, and the project'\n );\n }\n const [cmd, project] = args;\n const {\n env,\n buildEnv,\n apihost,\n auth,\n include,\n exclude,\n insecure,\n verboseBuild,\n verboseZip,\n yarn,\n remoteBuild,\n incremental,\n json,\n noTriggers\n } = parsed;\n const flags: Flags = {\n env,\n buildEnv,\n apiHost: apihost,\n auth,\n include,\n exclude,\n insecure,\n verboseBuild,\n verboseZip,\n yarn,\n remoteBuild,\n incremental,\n json,\n noTriggers\n };\n switch (cmd) {\n case 'deploy':\n await doDeploy(project, flags, logger);\n break;\n case 'get-metadata':\n await doGetMetadata(project, flags, logger);\n break;\n case 'watch':\n // Note: it is up to the caller to use a non-capturing Logger with watch\n await doWatch(project, flags, logger);\n break;\n case 'version':\n logger.log(version);\n break;\n default:\n logger.handleError(`unknown command: ${cmd}`);\n }\n}\n\n// Command to do deployment\nasync function doDeploy(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n const { insecure, apiHost: apihost, auth } = flags;\n const creds = await processCredentials(insecure, apihost, auth);\n await deployProject(project, flags, creds, false, logger);\n}\n\n// Command to retrieve project description metadata\nasync function doGetMetadata(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n // Convert include/exclude flags into an Includer object\n const includer = makeIncluder(flags.include, flags.exclude);\n\n // Read the project\n const result = await readProject(\n project,\n flags.env,\n undefined,\n includer,\n false,\n undefined,\n flags.noTriggers\n );\n if (result.error && !result.unresolvedVariables) {\n logger.displayError('', result.error);\n logger.exit(1);\n }\n\n // Fill in any missing runtimes\n if (result.packages && !result.unresolvedVariables) {\n // Too dangerous to attempt this if the parse wasn't perfect\n for (const pkg of result.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n action.runtime = await getRuntimeForAction(action, result.reader);\n }\n }\n }\n }\n\n // Display result\n renameActionsToFunctions(result);\n logger.logJSON(result);\n}\n\n// Command to do a project watch.\nasync function doWatch(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n const { insecure, apiHost: apihost, auth } = flags;\n const creds = await processCredentials(insecure, apihost, auth);\n watch(project, flags, creds, logger);\n}\n\n// Set up credentials based on flags if supplied. Otherwise, credentials will be undefined until later, either based on\n// targetNamespace in the project.yml or else just the current connected namespace.\nasync function processCredentials(\n ignore_certs: boolean,\n apihost: string | undefined,\n auth: string | undefined\n): Promise<Credentials> {\n const owOptions: OWOptions = { ignore_certs }; // No explicit undefined\n if (apihost) {\n owOptions.apihost = parseAPIHost(apihost);\n }\n if (auth) {\n owOptions.api_key = auth;\n }\n let creds: Credentials | undefined;\n if (apihost && auth) {\n creds = {\n namespace: undefined,\n ow: owOptions,\n do_token: process.env.DO_API_TOKEN\n };\n }\n return creds;\n}\n\n// Utility to parse the value of an --apihost flag, permitting certain abbreviations\nfunction parseAPIHost(host: string | undefined): string | undefined {\n if (!host) {\n return undefined;\n }\n if (host.includes(':')) {\n return host;\n }\n if (host.includes('.')) {\n return 'https://' + host;\n }\n return 'https://' + host + '.doserverless.co';\n}\n\n// Deploy one project\nexport async function deployProject(\n project: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n watching: boolean,\n logger: Logger\n): Promise<boolean> {\n let feedback: LoggerFeedback;\n if (project.startsWith('slice:') || cmdFlags.json) {\n feedback = new LoggerFeedback(new CaptureLogger());\n feedback.warnOnly = true;\n } else {\n feedback = new LoggerFeedback(logger);\n }\n\n let todeploy = await readAndPrepare(project, creds, cmdFlags, feedback);\n if (!todeploy) {\n return false;\n } else if (todeploy.error && !cmdFlags.json) {\n logger.displayError('', todeploy.error);\n return false;\n }\n if (!watching && !todeploy.slice && !cmdFlags.json) {\n displayHeader(project, todeploy.credentials, logger);\n }\n todeploy = await buildProject(todeploy);\n if (todeploy.error && !cmdFlags.json) {\n logger.displayError('', todeploy.error);\n return false;\n }\n const result: DeployResponse = await deploy(todeploy);\n if (cmdFlags.json || todeploy.slice) {\n const success = displayJSONResult(result, logger, feedback, todeploy.slice);\n if (success && todeploy.slice) {\n await deleteSlice(todeploy);\n }\n return success;\n }\n return displayResult(result, watching, logger);\n}\n\n// Display the deployment \"header\" (what we are about to deploy)\nfunction displayHeader(project: string, creds: Credentials, logger: Logger) {\n let namespaceClause = '';\n if (creds && creds.namespace) {\n namespaceClause = `\\n to namespace '${creds.namespace}'`;\n }\n let hostClause = '';\n if (creds && creds.ow.apihost) {\n hostClause = `\\n on host '${creds.ow.apihost}'`;\n }\n const projectPath = path.resolve(project);\n logger.log(`Deploying '${projectPath}'${namespaceClause}${hostClause}`);\n}\n\n// Display the result of a successful run when deploying a slice or when JSON is requested.\n// The output should be the DeployResponse as JSON on a single line, combined with the Feedback transcript if any\nfunction displayJSONResult(\n outcome: DeployResponse,\n logger: Logger,\n feedback: any,\n slice: boolean\n): boolean {\n const transcript = feedback.logger.captured;\n const result = { transcript, outcome };\n if (slice) {\n // Not using logJSON here because we need single-line output.\n // This is executing in a builder action anyway ... doesn't matter how output is produced.\n // eslint-disable-next-line no-inner-declarations\n function replaceErrors(_key: string, value: any): any {\n if (value instanceof Error) {\n const error = {};\n Object.getOwnPropertyNames(value).forEach(function (key) {\n error[key] = value[key];\n });\n return error;\n }\n return value;\n }\n const toDisplay = JSON.stringify(result, replaceErrors);\n logger.log(toDisplay);\n } else {\n // Normal JSON, print normally with indentation\n logger.logJSON(result);\n }\n return outcome.failures.length === 0;\n}\n\n// Display the result of a successful run\nfunction displayResult(\n result: DeployResponse,\n _watching: boolean,\n logger: Logger\n): boolean {\n let success = true;\n if (result.successes.length === 0 && result.failures.length === 0) {\n logger.log('\\nNothing deployed');\n } else {\n logger.log('');\n const actions: string[] = [];\n const triggers: string[] = [];\n const packages: string[] = [];\n let skippedActions = 0;\n let skippedTriggers = 0;\n let skippedPackages = 0;\n for (const success of result.successes) {\n if (success.kind === 'action') {\n if (success.skipped) {\n skippedActions++;\n } else {\n const name = success.name;\n actions.push(name);\n }\n } else if (success.kind === 'trigger') {\n if (success.skipped) {\n skippedTriggers++;\n } else {\n triggers.push(success.name);\n }\n } else if (success.kind === 'binding') {\n if (success.skipped) {\n skippedPackages++;\n } else {\n packages.push(success.name);\n }\n }\n }\n if (actions.length > 0) {\n logger.log(\n \"Deployed functions ('doctl sls fn get <funcName> --url' for URL):\"\n );\n for (const action of actions) {\n logger.log(` - ${action}`);\n }\n }\n if (skippedActions > 0) {\n logger.log(`Skipped ${skippedActions} unchanged functions`);\n }\n if (triggers.length > 0) {\n logger.log('Deployed triggers:');\n for (const trigger of triggers) {\n logger.log(` - ${trigger}`);\n }\n }\n if (skippedTriggers > 0) {\n logger.log(`Skipped ${skippedTriggers} triggers`);\n }\n if (packages.length > 0) {\n logger.log('Deployed bound packages:');\n for (const pkg of packages) {\n logger.log(` - ${pkg}`);\n }\n }\n if (skippedPackages > 0) {\n logger.log(`Skipped ${skippedPackages} bound packages`);\n }\n if (result.failures.length > 0) {\n success = false;\n logger.log('Failures:');\n for (const err of result.failures) {\n success = false;\n const context = (err as any).context;\n if (context) {\n logger.displayError(`While deploying ${context}`, err);\n } else {\n logger.displayError('', err);\n }\n }\n }\n }\n return success;\n}\n\n// Improves an error message based on analyzing the accompanying Error object (adopted from the nim CLI)\nfunction improveErrorMsg(msg: string, err?: any): string {\n const getStatusCode = (code: number) =>\n `${code} ${STATUS_CODES[code] || ''}`.trim();\n\n let pretty = '';\n if (err) {\n pretty = err.message || '';\n if (err.name === 'OpenWhiskError') {\n if (err.error && err.error.error) {\n pretty = err.error.error.toLowerCase();\n if (err.statusCode)\n pretty = `${pretty} (${getStatusCode(err.statusCode)})`;\n else if (err.error.code) pretty = `${pretty} (${err.error.code})`;\n } else if (err.statusCode) {\n pretty = getStatusCode(err.statusCode);\n }\n }\n }\n if ((pretty || '').toString().trim()) {\n msg = msg ? `${msg}: ${pretty}` : pretty;\n }\n if (!msg) {\n if (err.status) {\n msg = getStatusCode(err.status);\n } else {\n msg = 'unknown error';\n }\n }\n return msg;\n}\n", "////////////////////////////////////////////////////////////////\n// THIS FILE WAS AUTO-GENERATED BY scripts/generateVersion.sh\n// DO NOT EDIT MANUALLY\n////////////////////////////////////////////////////////////////\n\nexport const version = '5.0.19';\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoEO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,eAAY;AADF,SAAAA;AAAA,GAAA;AAkDL,IAAM,kBAAN,MAA0C;AAAA,EAC/C,KAAK,YAAkB,gBAA6B;AAClD,YAAQ,KAAK,SAAS,GAAG,cAAc;AAAA,EACzC;AAAA,EAEA,SAAS,YAAkB,gBAA6B;AACtD,YAAQ,IAAI,SAAS,GAAG,cAAc;AAAA,EACxC;AACF;;;AC9FA,4BAA+B;AAE/B,4BAA4B;AAC5B,IAAAC,MAAoB;AACpB,SAAoB;AACpB,IAAAC,QAAsB;AACtB,wBAAsB;AACtB,mBAA8B;AAC9B,aAAwB;AACxB,WAAsB;AACtB,IAAAC,gBAAsB;AACtB,sBAAqB;;;AC5BrB,SAAoB;AACpB,WAAsB;AAQtB,mBAAwB;AAExB,IAAM,YAAQ,aAAAC,SAAY,cAAc;AA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MAAM,YAAY;AACrC,YAAI,IAAI;AACN,mBAAS,GAAG,WAAW,cAAc,IAAI,UAAU;AAAA,iBAC5C,IAAI,MAAM;AAAM,mBAAS,GAAG,WAAW,IAAI,MAAM;AAAA,MAC5D,WAAW,IAAI,YAAY;AACzB,iBAAS,cAAc,IAAI,UAAU;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACA,OAAK,UAAU,IAAI,SAAS,EAAE,KAAK,GAAG;AACpC,UAAM,MAAM,GAAG,QAAQ,WAAW;AAAA,EACpC;AACA,MAAI,CAAC,KAAK;AACR,QAAI,IAAI,QAAQ;AACd,YAAM,cAAc,IAAI,MAAM;AAAA,IAChC,OAAO;AACL,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;",
6
- "names": ["TriggerType", "fs", "path", "import_debug", "createDebug", "namespace", "import_debug", "debug", "isValidRuntime", "defaultRuntime", "axios", "import_axios", "import_debug", "debug", "makeDebug", "axios", "debug", "makeDebug", "defaultRemote", "keyVal", "anymatch", "path", "simplegit", "debug", "resolve", "pkg", "anymatch", "import_debug", "debug", "makeDebug", "main", "path", "fs", "path", "fs", "yaml", "import_axios", "import_debug", "path", "fs", "import_debug", "debug", "makeDebug", "resolve", "Zip", "entry", "debug", "makeDebug", "debug", "lstat", "items", "item", "ignore", "build", "main", "path", "pkg", "archiver", "resolve", "debug", "axios", "ignore", "archiver", "resolve", "touch", "import_debug", "fs", "import_util", "import_debug", "debug", "makeDebug", "path", "debug", "makeDebug", "fs", "build", "config", "import_debug", "debug", "makeDebug", "import_debug", "openwhisk", "debug", "makeDebug", "path", "debug", "openwhisk", "fs", "watch", "deployProject", "path", "import_debug", "createDebug", "msg", "parser", "doDeploy", "deployProject", "watch", "success"]
4
+ "sourcesContent": ["/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Gather together the major deployer exports for convenient import in other packages\n\nexport {\n initializeAPI,\n deployProject,\n readPrepareAndBuild,\n readAndPrepare,\n deploy,\n readProject,\n buildProject,\n prepareToDeploy,\n wipeNamespace,\n getUserAgent\n} from './api';\nexport {\n DeployStructure,\n DeployResponse,\n DeploySuccess,\n OWOptions,\n Credentials,\n CredentialRow,\n Flags,\n PackageSpec,\n ActionSpec,\n CredentialHostMap,\n CredentialNSMap,\n DeployerAnnotation,\n VersionMap,\n Feedback,\n DefaultFeedback,\n FullCredentials,\n IdProvider\n} from './deploy-struct';\nexport {\n addCredentialAndSave,\n getCredentials,\n getCredentialList,\n getCredentialDict,\n getCredentialsForNamespace,\n forgetNamespace,\n switchNamespace,\n getCurrentNamespace,\n getApiHosts,\n Persister,\n authPersister,\n getCredentialsFromEnvironment,\n nimbellaDir\n} from './credentials';\nexport {\n wskRequest,\n delay,\n writeSliceResult,\n getBestProjectName,\n renamePackage,\n getExclusionList,\n isExcluded,\n SYSTEM_EXCLUDE_PATTERNS,\n getRuntimeForAction,\n emptyStructure,\n invokeWebSecure,\n renameActionsToFunctions,\n deleteAction\n} from './util';\nexport * from './runtimes';\nexport { deleteSlice } from './slice-reader';\nexport { makeIncluder } from './includer';\nexport {\n DefaultLogger,\n CaptureLogger,\n runCommand,\n main,\n flush,\n handleError\n} from './main';\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { Dict, Client, Limits, KeyVal as OWKeyVal } from 'openwhisk';\n\n// Contains the primary type definition for the deployer structure.\n// The structure consists of the contents of a 'project' (its file and folder structure) along\n// with the contents of a distinguished config file in the root of the project, if present.\n\n// Describes one package containing zero or more actions\nexport interface PackageSpec {\n name: string; // The 'default' package is used to hold actions with no package. Only the 'actions' member is processed then.\n actions?: ActionSpec[];\n shared?: boolean; // Indicates that the package is intended to be shared (public)\n annotations?: Dict; // package annotations\n parameters?: Dict; // Bound parameters for all actions in the package, passed in the usual way\n environment?: Dict; // Bound parameters for all actions in the package, destined to go in the environment of each action\n web?: any; // like 'web' on an action but affects all actions of the package that don't redeclare the flag\n deployedDuringBuild?: boolean; // set when the package was deployed early because some builds were remote\n binding?: BindingSpec; // may be present in lieu of an actions array if the package is bound to another\n}\n\n// Describes the binding information for a bound package (with no actions of its own)\nexport interface BindingSpec {\n name: string; // the name of the package to which the present package is bound\n namespace: string; // the namespace of the package to which the present package is bound\n}\n\n// Describes one action\nexport interface ActionSpec {\n name: string; // The name of the action\n package?: string; // The name of the package where action appears ('default' if no package)\n // The following are used to assemble 'exec'. Currently, you can't specify exec directly\n file?: string; // The path to the file comprising the action (possibly a zip file)\n displayFile?: string; // The file path to display in messages\n code?: string; // The code of the action (bypasses file reading; used internally; not specifiable in the config)\n runtime?: string; // The runtime to use for the action\n main?: string; // The 'main' directive if needed\n binary?: boolean; // Indicates the need for base64 encoding\n docker?: string; // Docker image to use with blackbox runtime\n zipped?: boolean; // (Ignored unless binary) indicates that the binary object is a zip archive\n // End of 'exec' properties\n sequence?: string[]; // Indicates that this action is a sequence and provides its components. Mutually exclusive with the 'exec' options\n web?: any; // like --web on the CLI; expands to multiple annotations. Project reader assigns true unless overridden.\n webSecure?: any; // like --web-secure on the CLI. False unless overridden\n annotations?: Dict; // 'web' and 'webSecure' are merged with what's here iff present\n parameters?: Dict; // Bound parameters for the action passed in the usual way\n environment?: Dict; // Bound parameters for the action destined to go in the environment\n limits?: Limits; // Action limits (time, memory, logs)\n remoteBuild?: boolean; // States that the build (if any) must be done remotely\n localBuild?: boolean; // States that the build (if any) must be done locally\n triggers?: TriggerSpec[]; // Triggers for the function if any\n // Build information (not specifiable in the config)\n build?: string;\n buildResult?: string; // The activation id of the remote build\n buildError?: Error; // Error reported from the build step\n}\n\nexport enum TriggerType {\n SCHEDULED = 'SCHEDULED'\n}\n// Information about one trigger. An action can have many triggers. However, different actions may not\n// share the same trigger.\nexport interface TriggerSpec {\n name: string; // The name of the trigger. Must be unique within the namespace.\n type: TriggerType; // Currently, the one supported value \"scheduled\" is required.\n scheduledDetails?: ScheduledSourceDetails;\n enabled?: boolean; // Assumed true if omitted\n}\n\n// The type used for the sourceDetails of a trigger whose sourceType is \"scheduled\"\nexport interface ScheduledSourceDetails {\n cron?: string; // must be a cron expression\n interval?: number; // in minutes (not yet implemented)\n once?: string; // an ISO-format date (not yet implemented)\n // (cron, interval and once are mutually exclusive)\n body?: object; // optional body to use when posting the function\n}\n\n// Information of various kinds typically specified on the command line\nexport interface Flags {\n verboseBuild: boolean;\n verboseZip: boolean;\n incremental: boolean;\n yarn: boolean;\n env: string | undefined;\n buildEnv: string | undefined;\n include: string | undefined;\n exclude: string | undefined;\n remoteBuild: boolean;\n json: boolean;\n // low-level flags, documented in help but not how-tos, infrequently used\n auth: string;\n apiHost: string;\n insecure: boolean;\n // special flag to reject triggers when found in project.yml (for use in contexts where triggers can't be supported)\n noTriggers: boolean;\n}\n\n// Object to provide feedback (warnings and progress reports) in real time during execution.\n// NOT for debugging.\n// NOT for normal communication: summary messages should be fed back through DeployResponse\n// NOT for hard errors: those should be thrown or Promise-rejected.\nexport interface Feedback {\n warn(message?: any, ...optionalParams: any[]): void;\n progress(message?: any, ...optionalParams: any[]): void;\n}\n\nexport class DefaultFeedback implements Feedback {\n warn(message?: any, ...optionalParams: any[]): void {\n console.warn(message, ...optionalParams);\n }\n\n progress(message?: any, ...optionalParams: any[]): void {\n console.log(message, ...optionalParams);\n }\n}\n\n// The top-level deploy structure. Nothing is required. If the structure is vacuous, nothing is deployed. This interface\n// describes the syntax of project.yml and also the structure of a project on disk where 'packages' is a subdirectory\n// of the project). The two sources of information are merged.\nexport interface DeployStructure {\n packages?: PackageSpec[]; // The packages found in the package directory\n targetNamespace?: string; // The namespace to which we are deploying\n parameters?: Dict; // Parameters to apply to all packages in the project\n environment?: Dict; // Environment to apply to all packages in the project\n // The following fields are not documented for inclusion project.yml but may be present in a project slice config (remote build)\n // They are typically added internally.\n slice?: boolean; // Labels this DeployStructure as belonging to a a project slice\n credentials?: Credentials; // The full credentials for the deployment (consistent with targetNamespace if one was specified)\n flags?: Flags; // options typically specified on the command line\n deployerAnnotation?: DeployerAnnotation; // The deployer annotation to use (with the digest undefined, as it varies)\n buildEnv?: Record<string, string>; // Build time environment\n // The following fields are never permitted in project.yml but are always added internally\n libBuild?: string; // Type of build (build.sh or package.json) to apply to the lib directory\n strays?: string[]; // files or directories found in the project that don't fit the model, not necessarily an error\n filePath?: string; // The location of the project on disk\n owClient?: Client; // The openwhisk client for deploying actions and packages\n includer?: Includer; // The 'includer' for deciding which packages and actions are included in the deploy\n reader?: ProjectReader; // The project reader to use\n versions?: VersionEntry; // The VersionEntry for credentials.namespace on the selected API host if available\n feedback?: Feedback; // The object to use for immediate communication to the user (e.g. for warnings and progress reports)\n error?: Error; // Records an error in reading or preparing, or a terminal error in building; the structure should not be used\n unresolvedVariables?: string[]; // Variables that couldn't be resolved in project reading (error may be set also)\n sequences?: ActionSpec[]; // detected during action deployment and deferred until ordinary actions are deployed\n}\n\n// Types used in the DeployResponse\nexport interface VersionInfo {\n version: string;\n digest: string;\n}\nexport interface VersionMap {\n [key: string]: VersionInfo;\n}\n\nexport type DeployKind = 'action' | 'trigger' | 'binding';\n\nexport interface DeploySuccess {\n name: string;\n kind: DeployKind;\n skipped: boolean;\n}\n\n// Contains the responses from an actual deployment\nexport interface DeployResponse {\n successes: DeploySuccess[];\n failures: Error[];\n ignored: string[];\n namespace: string;\n packageVersions: VersionMap;\n actionVersions: VersionMap;\n apihost?: string;\n}\n\n// The version file entry for a given deployment\nexport interface VersionEntry {\n apihost: string;\n namespace: string;\n packageVersions: VersionMap;\n actionVersions: VersionMap;\n}\n\n// The annotation placed in every action and package deployed by the deployer\nexport interface DeployerAnnotation {\n repository?: string;\n commit?: string;\n digest: string;\n projectPath: string;\n user: string;\n zipped?: boolean;\n newSliceHandling?: boolean;\n}\n\n// Grouping for OW Options that can be specified on the command line or by caller; also part of credential lookup response\nexport interface OWOptions {\n apihost?: string;\n api_key?: string;\n ignore_certs?: boolean;\n}\n\n// Supporting types for oauth\n\n// These types duplicate declarations in main/deployable/login, except that Credentials is renamed to FullCredentials\n// to avoid confusing it with the Credentials type used through nim.\nexport type IdProvider = {\n provider: string;\n name: string;\n key: string;\n};\n\nexport type FullCredentials = {\n status: string;\n apihost: string;\n namespace: string;\n uuid: string;\n key: string;\n redis: boolean;\n storage?: string;\n externalId?: IdProvider;\n};\n\n// Format of the JSON file containing credential information, persisted in ~/.nimbella/credentials.json\nexport interface CredentialStore {\n currentHost: string;\n currentNamespace: string;\n credentials: CredentialHostMap;\n}\n\nexport interface CredentialHostMap {\n [key: string]: CredentialNSMap; // Keyed by API host\n}\n\n// Part of CredentialStore for a single API host\nexport interface CredentialNSMap {\n [key: string]: CredentialEntry; // keyed by namespace relative to API host\n}\n\n// Part of CredentialStore for a single namespace relative to an API host.\n// It describes the credentials owned by the user who owns ~/.\n// While different subjects in couchdb can have different credentials to a shared namespace,\n// we assume that a user keeps only one credential set for that namespace.\nexport interface CredentialEntry {\n api_key: string;\n project?: string;\n production?: boolean;\n}\n\n// The Result of a credential lookup\nexport interface Credentials {\n namespace: string | undefined;\n ow: OWOptions;\n do_token: string;\n}\n\n// Compact and less complete information about a Credential suitable for listing and tabular display\nexport interface CredentialRow {\n namespace: string;\n current: boolean;\n apihost: string;\n}\n\n// The Includer object is used during project reading and deployment to screen packages, and actions to be included\nexport interface Includer {\n isPackageIncluded: (pkg: string, all: boolean) => boolean;\n isActionIncluded: (pkg: string, action: string) => boolean;\n isIncludingEverything: () => boolean;\n}\n\n// Defines the general ProjectReader interface\n\n// A simplified fs.Dirent that just distinguishes files, directories, and symlinks.\n// The symlink case is only for \"dangling\" symlinks: intact symlinks are followed.\nexport type PathKind = {\n name: string;\n isDirectory: boolean;\n isFile: boolean;\n symlink?: string;\n mode: number;\n};\n\n// The method repertoire for reading projects.\n// Path names passed to these methods may, in the most general case, be either absolute or relative to the\n// project root. After canonicalizing `..` directives in such paths, they may point inside or outside the project.\n// For the file system, we accept absolute paths and allow a relative path to land anywhere in the file system.\n// Historically, there was also a github reader which has been discontinued; therefore, currently, the file\n// system reader is the only exemplar of this interface. I think the interface is worth retaining, however,\n// for future experimentation.\nexport interface ProjectReader {\n // Read the contents of a directory (non-recursively)\n readdir: (path: string) => Promise<PathKind[]>;\n // Read the contents of a file (e.g. config, code, .include ...)\n readFileContents: (path: string) => Promise<Buffer>;\n // Test whether a file exists\n isExistingFile: (path: string) => Promise<boolean>;\n // Get the PathKind of a path\n getPathKind: (path: string) => Promise<PathKind>;\n // Get the location of the project in a real file system (returns null for \"non-real\" file systems, if any)\n getFSLocation: () => string | null;\n}\n\n// Define KeyVal for our purposes, supporting the `init` option for parameters\nexport interface KeyVal extends OWKeyVal {\n init?: boolean;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n DeployStructure,\n DeployResponse,\n DeploySuccess,\n DeployKind,\n ActionSpec,\n PackageSpec,\n Feedback,\n DeployerAnnotation,\n VersionMap,\n VersionEntry,\n PathKind,\n ProjectReader,\n KeyVal,\n TriggerSpec,\n TriggerType,\n Credentials\n} from './deploy-struct';\nimport { getUserAgent } from './api';\nimport { XMLHttpRequest } from 'xmlhttprequest';\nimport { Client, Dict, Activation, Action } from 'openwhisk';\nimport { isValidCron } from 'cron-validator';\nimport * as fs from 'fs';\nimport * as os from 'os';\nimport * as path from 'path';\nimport simplegit from 'simple-git';\nimport * as randomstring from 'randomstring';\nimport * as crypto from 'crypto';\nimport * as yaml from 'js-yaml';\nimport makeDebug from 'debug';\nimport anymatch from 'anymatch';\nimport { nimbellaDir } from './credentials';\nimport {\n isBinaryFileExtension,\n runtimeForZipMid,\n runtimeForFileExtension,\n isValidRuntime\n} from './runtimes';\nimport { undeployTriggers, listTriggersForNamespace } from './triggers';\nconst debug = makeDebug('nim:deployer:util');\n\n// List of files/paths to be ignored, add https://github.com/micromatch/anymatch compatible definitions\nexport const SYSTEM_EXCLUDE_PATTERNS = [\n '.gitignore',\n '.DS_Store',\n '**/.git/**',\n (s: string): boolean => s.includes('.nimbella'),\n (s: string): boolean => s.includes('.deployed'),\n (s: string): boolean => s.includes('_tmp_'),\n (s: string): boolean => s.includes('.#'),\n (s: string): boolean => s.endsWith('~'),\n '**/*.swp',\n '**/*.swx'\n];\n\n//\n// General utilities\n//\n\n// Read the project config file, with validation\nexport async function loadProjectConfig(\n configFile: string,\n envPath: string,\n buildEnvPath: string,\n filePath: string,\n reader: ProjectReader,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<DeployStructure> {\n const learnMore =\n ' Learn more about the project configuration file https://docs.digitalocean.com/products/functions/reference/project-configuration/';\n\n return reader.readFileContents(configFile).then(async (data) => {\n let configData = String(data);\n\n const encryptionKey = process.env.ENCRYPTION_KEY;\n if (encryptionKey) {\n configData = decryptProjectConfig(configData, encryptionKey);\n }\n\n try {\n // Read the config, substituting from env\n const { content, badVars } = substituteFromEnvAndFiles(\n String(configData),\n envPath,\n filePath,\n feedback\n );\n let config: Record<string, any>;\n if (configFile.endsWith('.json')) {\n config = JSON.parse(content);\n } else {\n if (content.includes('\\t')) {\n throw new Error('YAML configuration may not contain tabs');\n } else {\n config = yaml.safeLoad(content) as Record<string, any>;\n }\n }\n if (!config) {\n throw new Error('configuration is empty or unparseable');\n }\n // Adjust from the external convention (packages contain functions) to the internal one\n // (packages contain actions).\n renameFunctionsToActions(config);\n // Check config\n const configError = await validateDeployConfig(config, noTriggers);\n if (configError) {\n throw new Error(configError);\n } else {\n removeEmptyStringMembers(config);\n }\n // Add build environment if specified\n if (buildEnvPath) {\n config.buildEnv = getPropsFromFile(buildEnvPath);\n }\n config.unresolvedVariables = badVars;\n if (badVars && badVars.length > 0) {\n const formatted = \"'\" + badVars.join(\"', '\") + \"'\";\n config.error = new Error(\n 'The following substitutions could not be resolved: ' + formatted\n );\n }\n return config;\n } catch (err) {\n const errMsgPrefix = `Invalid project configuration file (${configFile})`;\n if (err.message) {\n err.message = `${errMsgPrefix}: ${err.message}`;\n } else {\n err.message = `${errMsgPrefix}`;\n }\n\n err.message = `${err.message} \\n ${learnMore}`;\n return errorStructure(err);\n }\n });\n}\n\nexport function encryptProjectConfig(config: string): {\n config: string;\n key: string;\n} {\n const key = crypto.randomBytes(32);\n const iv = Buffer.alloc(16).fill(0);\n const cipher = crypto.createCipheriv('aes256', key, iv);\n const encrypted = cipher.update(config, 'utf8', 'hex') + cipher.final('hex');\n return {\n config: encrypted,\n key: key.toString('hex')\n };\n}\n\nexport function decryptProjectConfig(config: string, key: string): string {\n const iv = Buffer.alloc(16).fill(0);\n const decipher = crypto.createDecipheriv(\n 'aes256',\n Buffer.from(key, 'hex'),\n iv\n );\n const decryptedMessage = Buffer.concat([\n decipher.update(config, 'hex'),\n decipher.final()\n ]);\n return decryptedMessage.toString('utf8');\n}\n\n// Rename any 'functions' members of the contained PackageSpecs of a config to 'actions'.\n// This adjust from an external convention to an internal one. It is done before validation.\nfunction renameFunctionsToActions(config: Record<string, any>): void {\n if (config.packages) {\n for (const pkg of config.packages) {\n if (pkg.functions) {\n pkg.actions = pkg.functions;\n delete pkg.functions;\n }\n }\n }\n}\n\n// Rename any 'actions' members of the contained PackageSpecs of a config to 'functions'.\n// This adjust from an external convention to an internal one. It is done before writing out\n// a config to be visible to users.\nexport function renameActionsToFunctions(config: Record<string, any>): void {\n if (config.packages) {\n for (const pkg of config.packages) {\n if (pkg.actions) {\n pkg.functions = pkg.actions;\n delete pkg.actions;\n }\n }\n }\n}\n\n// Check whether a build field actually implies a build must be run\nexport function isRealBuild(buildField: string): boolean {\n switch (buildField) {\n case 'build.sh':\n case 'build.cmd':\n case 'package.json':\n return true;\n default:\n return false;\n }\n}\n\n// Replace a build field with 'remote' or 'remote-default' if it is supposed to be remote according to flags,\n// directives, environment, or the type of runtime.\nfunction locateBuild(\n buildField: string,\n remoteRequested: boolean,\n defaultRemote: boolean,\n remoteRequired: boolean,\n localRequired: boolean\n) {\n if (!isRealBuild(buildField)) {\n // Not a real build. Check remote-default conditions.\n if (defaultRemote && !localRequired) {\n return 'remote-default';\n } // else does not meet remote-default conditions\n return buildField;\n } // else it's a real build. Check conditions for remote.\n if (remoteRequired || (remoteRequested && !localRequired)) {\n return 'remote';\n } // else does not meet conditions for remote\n return buildField;\n}\n\n// Set up the build fields for a project and detect conflicts.\n// Returns true if any build is required to be local.\nexport async function checkBuildingRequirements(\n todeploy: DeployStructure,\n requestRemote: boolean\n): Promise<boolean> {\n const checkConflicts = (remote: boolean, local: boolean, tag: string) => {\n if (remote && local) {\n throw new Error(\n `Local and remote building cannot both be required (${tag})`\n );\n }\n };\n if (todeploy.packages) {\n for (const pkg of todeploy.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n checkConflicts(\n action.remoteBuild,\n action.localBuild,\n `function ${action.name}`\n );\n }\n }\n }\n }\n let needsLocal = false;\n if (todeploy.packages) {\n for (const pkg of todeploy.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n const defaultRemote = await hasDefaultRemote(action, todeploy.reader);\n action.build = locateBuild(\n action.build,\n requestRemote,\n defaultRemote,\n action.remoteBuild,\n action.localBuild\n );\n if (action.build === 'build.sh' && process.platform === 'win32') {\n // If there was a build.cmd it would have been recorded in preference to build.sh\n throw new Error(\n `In function ${action.name}: 'build.sh' won't run on this platform and no 'build.cmd' is provided`\n );\n }\n needsLocal =\n needsLocal ||\n (!action.build?.startsWith('remote') && isRealBuild(action.build));\n }\n }\n }\n }\n return needsLocal;\n}\n\n// Determine if an action has a default remote build. This depends on the action's 'kind': currently, swift and go have a\n// default remote build while other languages do not. This function is designed to be called before the runtime is otherwise\n// known so it is prepared to peek into the project to figure out the operative runtime.\nasync function hasDefaultRemote(\n action: ActionSpec,\n reader: ProjectReader\n): Promise<boolean> {\n const runtime = await getRuntimeForAction(action, reader);\n if (!runtime) {\n return false;\n }\n const kind = runtime.split(':')[0];\n switch (kind) {\n // TODO should this be an external table?\n case 'go':\n case 'swift':\n return true;\n default:\n return false;\n }\n}\n\nexport async function getRuntimeForAction(\n action: ActionSpec,\n reader: ProjectReader\n): Promise<string> {\n if (action.runtime) {\n return action.runtime;\n }\n if (action.sequence && action.sequence.length > 0) {\n return '';\n }\n const pathKind = await reader.getPathKind(action.file);\n if (pathKind.isFile) {\n const { runtime } = await actionFileToParts(pathKind.name);\n return runtime;\n } else if (pathKind.isDirectory) {\n const files = await promiseFilesAndFilterFiles(action.file, reader);\n return agreeOnRuntime(files);\n } else {\n return '';\n }\n}\n\n// Check whether a list of names that are candidates for zipping can agree on a runtime. This is called only when the\n// config doesn't already provide a runtime, or on the raw material in the case of remote builds.\nexport async function agreeOnRuntime(items: string[]): Promise<string> {\n let agreedRuntime: string;\n const partsArray = await Promise.all(\n items.map((item) => actionFileToParts(item))\n );\n partsArray.forEach((answer) => {\n if (answer.runtime) {\n if (agreedRuntime && answer.runtime !== agreedRuntime) {\n return undefined;\n }\n agreedRuntime = answer.runtime;\n }\n });\n return agreedRuntime;\n}\n\n// In project config we permit many optional string-valued members to be set to '' to remind users that they are available\n// without actually setting a value. Here we delete those members to simplify subsequent handling.\nfunction removeEmptyStringMembers(config: DeployStructure) {\n if (config.targetNamespace && config.targetNamespace === '') {\n delete config.targetNamespace;\n }\n removeEmptyStringMembersFromPackages(config.packages);\n}\n\n// Remove empty optional string-valued members from an array of PackageSpecs\nfunction removeEmptyStringMembersFromPackages(packages: PackageSpec[]) {\n if (!packages) return;\n for (const pkg of packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n if (action.main && action.main === '') {\n delete action.main;\n }\n if (action.runtime && action.runtime === '') {\n delete action.runtime;\n }\n }\n }\n }\n}\n\n// Validation for DeployStructure read from disk.\nexport async function validateDeployConfig(\n arg: any,\n noTriggers: boolean\n): Promise<string> {\n const isNimbellaDeploy = arg.targetNamespace === 'nimbella';\n const slice = !!arg.slice;\n for (const item in arg) {\n if (!arg[item]) continue;\n switch (item) {\n case 'slice':\n continue;\n break;\n case 'targetNamespace': {\n if (!(typeof arg[item] === 'string') && !isValidOwnership(arg[item])) {\n return `${item} must be a string or a dictionary containing 'test' and/or 'production' members`;\n }\n break;\n }\n case 'packages': {\n if (!Array.isArray(arg[item])) {\n return 'packages member must be an array';\n }\n for (const subitem of arg[item]) {\n const pkgError = await validatePackageSpec(\n subitem,\n slice,\n isNimbellaDeploy,\n noTriggers\n );\n if (pkgError) {\n return pkgError;\n }\n }\n break;\n }\n case 'parameters':\n case 'environment': {\n if (!isDictionary(arg[item])) {\n return `${item} member must be a dictionary`;\n }\n break;\n }\n case 'credentials':\n case 'flags':\n case 'deployerAnnotation':\n case 'buildEnv':\n if (slice) continue;\n // In a slice we accept these without further validation; otherwise, they are illegal\n // Otherwise, fall through\n default:\n return `Invalid key '${item}' found in project.yml`;\n }\n }\n return undefined;\n}\n\n// Test whether an item is a dictionary. In practice this means its basic type is object and it isn't an array or null.\nfunction isDictionary(item: any) {\n return typeof item === 'object' && !Array.isArray(item) && item != null;\n}\n\n// Test whether an item is an Ownership. This means it's a dictionary and has 'production' and/or 'test' string members\nfunction isValidOwnership(item: any): boolean {\n return (\n isDictionary(item) &&\n (typeof item.production === 'string' || typeof item.test === 'string')\n );\n}\n\n// Validator for a PackageSpec\nasync function validatePackageSpec(\n arg: Record<string, any>,\n slice: boolean,\n isNimbella: boolean,\n noTriggers: boolean\n): Promise<string> {\n const isDefault = arg.name === 'default';\n for (const item in arg) {\n if (!arg[item]) continue;\n if (item === 'name') {\n if (!(typeof arg[item] === 'string')) {\n return `'${item}' member of a 'package' must be a string`;\n }\n } else if (item === 'actions') {\n if (!Array.isArray(arg[item])) {\n return \"functions member of a 'package' must be an array\";\n }\n for (const subitem of arg[item]) {\n const actionError = await validateActionSpec(\n subitem,\n isNimbella,\n noTriggers\n );\n if (actionError) {\n return actionError;\n }\n }\n } else if (item === 'shared') {\n if (!(typeof arg[item] === 'boolean')) {\n return `'${item}' member of a 'package' must be a boolean`;\n } else if (isDefault && arg[item]) {\n return `'${item}' must be absent or false for the default package`;\n }\n } else if (item === 'web') {\n if (!(typeof arg[item] === 'boolean' || arg[item] === 'raw')) {\n return `${item} member of an 'package' must be a boolean or the string 'raw'`;\n }\n } else if (item === 'environment') {\n const envErr = validateEnvironment(arg[item]);\n if (envErr) {\n return envErr;\n }\n } else if (item === 'parameters' || item === 'annotations') {\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n if (isDefault && Object.keys(arg[item]).length > 0) {\n return `'${item}' must be absent or empty for the default package`;\n }\n } else if (item === 'binding') {\n // We don't check here for a package with both actions and a binding because we don't have\n // complete information (just parsing the spec, but the package may have actions in the file system\n // that aren't in the spec). This conflict is detected later at deploy time.\n if (\n typeof arg[item]?.namespace !== 'string' ||\n typeof arg[item]?.name != 'string'\n ) {\n return 'binding information is incomplete: namespace and package name are both required';\n }\n } else if (item === 'deployedDuringBuild' && slice) {\n continue;\n } else {\n return `Invalid key '${item}' found in 'package' in project.yml`;\n }\n }\n return undefined;\n}\n\n// Validator for ActionSpec\nasync function validateActionSpec(\n arg: Record<string, any>,\n isNimbella: boolean,\n noTriggers: boolean\n): Promise<string> {\n for (const item in arg) {\n if (!arg[item]) continue;\n switch (item) {\n case 'name':\n case 'file':\n case 'runtime':\n case 'main':\n case 'docker':\n if (!(typeof arg[item] === 'string')) {\n return `'${item}' member of a function must be a string`;\n }\n if (item === 'runtime' && !(await isValidRuntime(arg[item]))) {\n return `'${arg[item]}' is not a valid runtime value`;\n }\n break;\n case 'binary':\n case 'remoteBuild':\n case 'localBuild':\n if (!(typeof arg[item] === 'boolean')) {\n return `'${item}' member of a function must be a boolean`;\n }\n break;\n case 'sequence':\n if (\n !Array.isArray(arg[item]) ||\n arg[item].length === 0 ||\n typeof arg[item][0] !== 'string'\n ) {\n return `'${item}' member of a function must be an array of one or more strings naming other functions`;\n }\n break;\n case 'web':\n if (!(typeof arg[item] === 'boolean' || arg[item] === 'raw')) {\n return `${item} member of a function must be a boolean or the string 'raw'`;\n }\n break;\n case 'webSecure':\n if (isNimbella && arg[item] === true) {\n // allowed\n continue;\n }\n if (!(arg[item] === false || typeof arg[item] === 'string')) {\n return `'${item}' member of a function must be a boolean false or a string`;\n }\n break;\n case 'environment': {\n const envError = validateEnvironment(arg[item]);\n if (envError) {\n return envError;\n }\n }\n // falls through\n case 'annotations': {\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n const annotErr = screenForbiddenAnnotations(arg[item]);\n if (annotErr) {\n return annotErr;\n }\n break;\n }\n case 'parameters':\n if (!isDictionary(arg[item])) {\n return `${item} must be a dictionary`;\n }\n break;\n case 'limits': {\n const limitsError = validateLimits(arg[item]);\n if (limitsError) {\n return limitsError;\n }\n break;\n }\n case 'triggers': {\n if (noTriggers) {\n return `the project requests triggers but triggers are not available`;\n }\n const triggerArs = transformLegacyTriggers(arg[item]);\n const trigErr = validateTriggers(triggerArs);\n if (trigErr) {\n return trigErr;\n }\n break;\n }\n default:\n return `Invalid key '${item}' found in 'functions' clause in project.yml`;\n }\n }\n return undefined;\n}\n\n// Don't permit manual setting of annotations that are supposed to be set specially\nfunction screenForbiddenAnnotations(annots: object): string {\n const forbidden = {\n 'require-whisk-auth': 'webSecure',\n 'web-export': 'web=true|false|\"raw\"',\n 'raw-http': 'web=raw'\n };\n for (const annot of Object.keys(annots)) {\n const subst = forbidden[annot];\n if (subst) {\n return `the '${annot}' annotation may not be set explicitly; use '${subst}'`;\n }\n }\n return '';\n}\n\n// Transforms legacy triggers format to new format for backwards compatibility.\n// Should be removed after the triggers beta is over and throw error to users.\n//\n// sourceType -> type (\"scheduler\" -> \"scheduled\")\n// sourceDetails -> scheduledDetails\n// sourceDetails.withBody -> scheduledDetails.body\nfunction transformLegacyTriggers(args: any) {\n const transformedArgs = args;\n if (!Array.isArray(transformedArgs)) {\n return args;\n }\n\n transformedArgs.forEach((trigger, index) => {\n if (!trigger.sourceType && !trigger.sourceDetails) {\n return;\n }\n transformedArgs[index].scheduledDetails = {\n cron: trigger.sourceDetails?.cron,\n body: trigger.sourceDetails?.withBody\n };\n transformedArgs[index].type =\n trigger.sourceType === 'scheduler' ? 'SCHEDULED' : trigger.sourceType;\n\n delete transformedArgs[index].sourceType;\n delete transformedArgs[index].sourceDetails;\n });\n\n return transformedArgs;\n}\n\n// Validator for the 'triggers' clause of an action\nexport function validateTriggers(arg: any): string {\n if (!Array.isArray(arg)) {\n return `a 'triggers' clause must be an array`;\n }\n\n for (const trigger of arg as TriggerSpec[]) {\n if (!isDictionary(trigger)) {\n return 'an individual trigger must be a dictionary';\n }\n\n for (const item of Object.keys(trigger)) {\n if (!['name', 'enabled', 'type', 'scheduledDetails'].includes(item)) {\n return `Invalid key '${item}' found in 'triggers' clause in project.yml`;\n }\n }\n\n const name = trigger.name;\n const type =\n typeof trigger.type === 'string'\n ? trigger.type.toUpperCase()\n : trigger.type;\n const scheduledDetails = trigger.scheduledDetails;\n\n if (typeof name !== 'string') {\n return `the 'name' field of a trigger is required`;\n }\n\n if (![TriggerType.SCHEDULED].includes(type as TriggerType)) {\n return `the trigger 'type' field must be '${Object.values(\n TriggerType\n ).join(' | ')}'`;\n }\n\n if (type === TriggerType.SCHEDULED) {\n if (!isDictionary(scheduledDetails)) {\n return `the 'scheduledDetails' property of a trigger is required for type=\"${TriggerType.SCHEDULED}\"`;\n }\n\n const err = validateScheduledTriggerDetails(scheduledDetails);\n if (err) {\n return err;\n }\n }\n\n if (trigger.enabled && typeof trigger.enabled !== 'boolean') {\n return `the 'enabled' property of a trigger must be boolean'`;\n }\n }\n return undefined;\n}\n\n// Validator for the sourceDetails of a trigger when the sourceType is 'scheduled'\nfunction validateScheduledTriggerDetails(details: any): string | undefined {\n if (!isDictionary(details)) {\n return 'the scheduledDetails field of a trigger specification must be a dictionary';\n }\n\n for (const item of Object.keys(details)) {\n if (!['cron', 'body'].includes(item)) {\n return `Invalid key '${item}' found in scheduledDetails in project.yml`;\n }\n }\n\n const cron = details.cron;\n const body = details.body;\n\n if (typeof cron !== 'string') {\n return `the 'cron' member of 'scheduledDetails' must be a string`;\n }\n\n if (!isValidCron(cron)) {\n // Note we are now validating with no \"special options\" enabled, so this is\n // least-common-denominator crontab (no seconds, no aliases, etc.). We should make sure\n // we are at least considering valid anything that the scheduler will actually accept.\n return `the cron expression '${cron}' is not valid crontab syntax`;\n }\n\n if (body && !isDictionary(body)) {\n return `the 'body' member of scheduledDetails must be a dictionary`;\n }\n}\n\n// Validator for the 'environment' clause of package or action. Checks that all values are strings\nfunction validateEnvironment(item: any): string {\n if (!isDictionary(item)) {\n return 'the environment clause must be a dictionary';\n }\n for (const entry in item) {\n const value = item[entry];\n if (typeof value !== 'string') {\n return `All environment values must be strings but '${entry}' has type '${typeof value}'`;\n }\n }\n return undefined;\n}\n\n// Validator for the limits clause\nfunction validateLimits(arg: any): string {\n for (const item in arg) {\n const value = arg[item];\n switch (item) {\n case 'timeout':\n case 'memory':\n case 'logs':\n if (typeof value !== 'number') {\n return `'${item}' member of a 'limits' clause must be a number`;\n }\n break;\n default:\n return `Invalid key '${item}' found in 'limits' clause in project.yml`;\n }\n }\n return undefined;\n}\n\n// Convert convenient \"Dict\" to the less convenient \"KeyVal[]\" required in an action object\nexport function keyVal(from: Dict): KeyVal[] {\n if (!from) {\n return undefined;\n }\n return Object.keys(from).map((key) => ({ key, value: from[key] }));\n}\n\n// Make an openwhisk KeyVal into an openwhisk Dict (the former appears in Action and Package, the latter in ActionSpec and PackageSpec)\nexport function makeDict(keyVal: KeyVal[]): Dict {\n const ans: Dict = {};\n keyVal.forEach((pair) => {\n ans[pair.key] = pair.value;\n });\n return ans;\n}\n\n// Provide an empty DeployStructure with all array and object members defined but empty\nexport function emptyStructure(): DeployStructure {\n return { packages: [], strays: [] };\n}\n\n// Provide an empty DeployStructure that records an error\nexport function errorStructure(err: Error): DeployStructure {\n const ans = emptyStructure();\n ans.error = err;\n return ans;\n}\n\n// Provide an empty DeployResponse with all required members defined but empty\nexport function emptyResponse(): DeployResponse {\n return {\n successes: [],\n failures: [],\n ignored: [],\n namespace: undefined,\n packageVersions: {},\n actionVersions: {}\n };\n}\n\n// Combine multiple DeployResponses into a single DeployResponse\nexport function combineResponses(responses: DeployResponse[]): DeployResponse {\n if (responses.length === 0) {\n return emptyResponse();\n }\n const combinedSuccesses: DeploySuccess[][] = responses.map(\n (response) => response.successes\n );\n const successes = combinedSuccesses.reduce(\n (prev, curr) => prev.concat(curr),\n []\n );\n const combinedFailures: Error[][] = responses.map(\n (response) => response.failures\n );\n const failures = combinedFailures.reduce(\n (prev, curr) => prev.concat(curr),\n []\n );\n const combinedIgnored: string[][] = responses.map(\n (response) => response.ignored\n );\n const ignored = combinedIgnored.reduce((prev, curr) => prev.concat(curr));\n const packageVersions = responses.reduce(\n (prev, curr) => Object.assign(prev, curr.packageVersions),\n {}\n );\n const actionVersions = responses.reduce(\n (prev, curr) => Object.assign(prev, curr.actionVersions),\n {}\n );\n const namespace = responses\n .map((r) => r.namespace)\n .reduce((prev, curr) => prev || curr);\n return {\n successes,\n failures,\n ignored,\n packageVersions,\n actionVersions,\n namespace\n };\n}\n\n// Turn the strays from a DeployStructure into a response indicating that they were skipped\nexport function straysToResponse(strays: string[]): DeployResponse {\n return {\n successes: [],\n ignored: strays,\n failures: [],\n packageVersions: {},\n actionVersions: {},\n namespace: undefined\n };\n}\n\n// Wrap a single success as a DeployResponse\nexport function wrapSuccess(\n name: string,\n kind: DeployKind,\n skipped: boolean,\n actionVersions: VersionMap,\n namespace: string\n): DeployResponse {\n const success: DeploySuccess = { name, kind, skipped };\n return {\n successes: [success],\n failures: [],\n ignored: [],\n namespace,\n packageVersions: {},\n actionVersions\n };\n}\n\n// Wrap a single error as a DeployResponse\nexport function wrapError(err: any, context: string): DeployResponse {\n debug('wrapping an error: %O', err);\n if (typeof err === 'object') {\n err.context = context;\n }\n const result = {\n successes: [],\n failures: [err],\n ignored: [],\n packageVersions: {},\n actionVersions: {},\n namespace: undefined\n };\n debug('wrapped error: %O', result);\n return result;\n}\n\n// Compute an appropriately qualified action name based on package inclusion\nexport function getActionName(action: ActionSpec): string {\n if (action.package && action.package !== 'default') {\n return action.package + '/' + action.name;\n }\n return action.name;\n}\n\n// Check whether the namespace for an OW client's current auth matches a desired target\nexport function isTargetNamespaceValid(\n client: Client,\n namespace: string\n): Promise<boolean> {\n return getTargetNamespace(client).then((ns) => {\n if (ns === namespace) {\n return Promise.resolve(true);\n } else {\n throw new Error(\n `Supplied credentials do not match target namespace '${namespace}'; deployment aborted`\n );\n }\n });\n}\n\n// Get the target namespace\nexport function getTargetNamespace(client: Client): Promise<string> {\n return client.namespaces.list().then((ns) => ns[0]);\n}\n\n// Process an action file name, producing 'name', 'binary', 'zipped' and 'runtime' parts\nexport async function actionFileToParts(fileName: string): Promise<{\n name: string;\n binary: boolean;\n zipped: boolean;\n runtime: string;\n}> {\n let runtime: string;\n let binary: boolean;\n let zipped: boolean;\n let name = path.basename(fileName);\n const split = name.indexOf('.');\n if (split > 0) {\n const parts = name.split('.');\n const ext = parts[parts.length - 1];\n let mid: string;\n if (parts.length === 2) {\n name = parts[0];\n } else if (ext === 'zip') {\n [name, mid] = getNameAndMid(parts.slice(0, -1));\n } else {\n name = parts.slice(0, -1).join('.');\n }\n runtime = mid ? await runtimeForZipMid(mid) : runtimeForFileExtension(ext);\n binary = isBinaryFileExtension(ext);\n zipped = ext === 'zip';\n } else {\n // No extension. Assume binary, with unknown runtime\n binary = true;\n zipped = false;\n }\n const z = zipped ? '' : 'not ';\n debug(`action ${name} is ${z}zipped`);\n return { name, binary, zipped, runtime };\n}\n\n// Correctly parse a \"mid\" segment from a zip file name. The input is the name split\n// on periods with the extension dropped. There are always at least two parts.\n// We should return the name and mid-segment as a two-element array.\nfunction getNameAndMid(parts: string[]): string[] {\n if (parts.length === 2) {\n return parts;\n }\n // There are at least three parts. Either the runtime is the last one or the last two\n const last = parts[parts.length - 1];\n const nextToLast = parts[parts.length - 2];\n if (/^\\d+$/.test(last) && nextToLast.includes('-')) {\n // Looks like a runtime version was split on a dot so we need to reassemble\n const name = parts.slice(0, -2).join('.');\n const mid = parts.slice(-2).join('.');\n return [name, mid];\n } else {\n const name = parts.slice(0, -1).join('.');\n return [name, last];\n }\n}\n\n// Filters temp files from an array of Dirent structures\nexport function filterFiles(entries: PathKind[]): PathKind[] {\n return entries.filter((entry) => {\n if (!entry.isDirectory) {\n return !anymatch(getExclusionList(), entry.name);\n } else {\n return entry;\n }\n });\n}\n\n// Emulates promiseFiles (from node-dir) using a ProjectReader and adds filtering like filterFiles\nexport async function promiseFilesAndFilterFiles(\n root: string,\n reader: ProjectReader\n): Promise<string[]> {\n let items = await promiseFiles(root, reader);\n debug('items before filtering: %O', items);\n const exclusions = getExclusionList();\n debug('exclusion list: %O', exclusions);\n items = items.filter((item: string) => !anymatch(exclusions, item));\n debug('items after filtering: %O', items);\n return items;\n}\n\n// Emulate promiseFiles using a ProjectReader\nasync function promiseFiles(\n dir: string,\n reader: ProjectReader\n): Promise<string[]> {\n debug('promiseFiles called on directory %s', dir);\n const files: string[] = [];\n let subdirs = await promiseFilesRound(dir, files, [], reader);\n while (subdirs.length > 0) {\n const next = subdirs.pop();\n debug(\n \"promiseFiles recursing on subdirectory '%s', with '%d' files accumulated and '%d' subdirectories still pending\",\n next,\n files.length,\n subdirs.length\n );\n subdirs = await promiseFilesRound(next, files, subdirs, reader);\n }\n debug('promiseFiles returning with %d files', files.length);\n return files;\n}\n\n// Working subroutine of promiseFiles\nasync function promiseFilesRound(\n dir: string,\n files: string[],\n subdirs: string[],\n reader: ProjectReader\n): Promise<string[]> {\n const items = await reader.readdir(dir);\n items.forEach(async (item) => {\n const itemPath = path.join(dir, item.name);\n if (item.isDirectory) {\n subdirs.push(itemPath);\n } else {\n files.push(itemPath);\n }\n });\n return subdirs;\n}\n\n// Substitute from the environment and from files. Variable references look like template variables: ${FOO} reads the\n// contents of variable FOO. Variables may be found in the process environment (higher precedence) or in the property file\n// located at 'envPath' (lower precedence, and only if 'envPath is defined).\n// ${<path} reads the contents of a file at the given path relative to the project root.\n// The semantics of variable substitution are purely textual (whatever is in the variable is substituted).\n// The semantics of file substitution are richer (see getSubstituteFromFile)\n// The form ${ token1 token2 token3 } where tokens are non-whitespace separated by whitespace is a special shorthand\n// that expands to { token1: value, token2: value, token3: value } where the values are obtained by looking up the\n// tokens in the process environment (higher precedence) or property file located at 'envPath'.\nexport function substituteFromEnvAndFiles(\n input: string,\n envPath: string,\n projectPath: string,\n feedback: Feedback\n): { content: string; badVars: string[] } {\n let result = ''; // Will accumulate the result\n const badVars: string[] = []; // Will accumulate failures to resolve\n const props = envPath ? getPropsFromFile(envPath) : {};\n debug('envPath: %s', envPath);\n debug('props %O', props);\n let nextSym = findNextSymbol(input);\n let warn = false;\n while (nextSym.index >= 0) {\n const before = input.substr(0, nextSym.index);\n const after = input.substr(nextSym.index + 2);\n const endVar = after.indexOf(nextSym.terminator);\n if (endVar < 0) {\n throw new Error('Runaway variable name or path directive in project.yml');\n }\n let subst: string;\n let doStringEscapes = true;\n let envar = after.substr(0, endVar).trim();\n debug('substituting for envar: %s', envar);\n if (nextSym.terminator === ')' || /\\s/.test(envar)) {\n warn = warn || nextSym.terminator !== ')';\n subst = getDictionarySubstitution(envar, props, badVars);\n } else if (envar.startsWith('<')) {\n if (nextSym.terminator === ')') {\n throw new Error('Invalid substitution: $(' + envar + ')');\n }\n const fileSubst = path.join(projectPath, envar.slice(1).trim());\n subst = getSubstituteFromFile(fileSubst);\n } else {\n if (envar.startsWith('|')) {\n envar = envar.slice(1).trim();\n doStringEscapes = false;\n }\n subst = process.env[envar] || props[envar];\n }\n if (!subst) {\n badVars.push(envar);\n subst = `<${envar}>`;\n } else if (doStringEscapes) {\n subst = escapeNewlines(subst);\n }\n debug('substitution is: %s', subst);\n result = result + before + subst;\n input = after.substr(endVar + 1);\n nextSym = findNextSymbol(input);\n }\n result = result + input;\n if (warn) {\n feedback.warn(\n \"Using '${}' for dictionary substitution is now deprecated; use '$()'\"\n );\n }\n if (badVars.length > 0) {\n return { content: result, badVars };\n }\n return { content: result, badVars: undefined };\n}\n\n// Perform escaping of newlines.\nfunction escapeNewlines(original: string): string {\n const parts = original.split('\\n');\n return parts.join('\\\\n');\n}\n\n// Scan forward for the next symbol introducer\nfunction findNextSymbol(input: string): { index: number; terminator: string } {\n const nextBrace = input.indexOf('${');\n const nextParen = input.indexOf('$(');\n const haveBrace = nextBrace >= 0;\n const haveParen = nextParen >= 0;\n if (haveBrace) {\n if (haveParen) {\n return nextBrace < nextParen\n ? { index: nextBrace, terminator: '}' }\n : { index: nextParen, terminator: ')' };\n } else {\n return { index: nextBrace, terminator: '}' };\n }\n } else if (haveParen) {\n return { index: nextParen, terminator: ')' };\n } else {\n return { index: -1, terminator: '' };\n }\n}\n\n// Get one or more substitutions in the form of a dictionary, given one or more tokens separated by whitespace.\n// Each token is a symbol to be looked up in the process environment or env file\nfunction getDictionarySubstitution(\n tokens: string,\n props: Record<string, unknown>,\n badVars: string[]\n): string {\n debug('dictionary substitution with %s', tokens);\n const ans = {};\n for (const tok of tokens.split(/\\s+/)) {\n debug('token: %s', tok);\n const value = process.env[tok] || props[tok];\n if (value) {\n ans[tok] = value;\n } else {\n badVars.push(tok);\n ans[tok] = `<${tok}>`;\n }\n }\n return JSON.stringify(ans);\n}\n\n// Get a substitution JSON string from a file. The file is read and, if it is valid JSON, it is simply used as is.\n// Otherwise, it is reparsed as a properties file and the result is converted to JSON. If the file is neither a valid JSON\n// file nor a valid properties file, that is an error.\nfunction getSubstituteFromFile(path: string): string {\n if (!fs.existsSync(path)) {\n return undefined;\n }\n const props = getPropsFromFile(path);\n const answer = JSON.stringify(props);\n return answer === '{}' ? undefined : answer;\n}\n\n// Get properties from a file, which may be a properties file or JSON\n// This function does not use the project reader because the environment file is specified separately\nfunction getPropsFromFile(filePath: string): Record<string, string> {\n if (!fs.existsSync(filePath)) {\n return {};\n }\n const contents = fs.readFileSync(filePath);\n try {\n return JSON.parse(String(contents));\n } catch {\n // Do nothing\n }\n // It's not JSON, so see if it's a properties file\n const propParser = require('dotenv'); // eslint-disable-line @typescript-eslint/no-var-requires\n // The dotenv parser doesn't throw but returns the empty object if malformed\n return propParser.parse(contents);\n}\n\n// Types for the map versions of the PackageSpec and ActionSpec types\nexport interface PackageMap {\n [key: string]: PackageSpec;\n}\nexport interface ActionMap {\n [key: string]: ActionSpec;\n}\n\n// Turn a PackageSpec array into a PackageMap\nexport function mapPackages(packages: PackageSpec[]): PackageMap {\n const ans: PackageMap = {};\n for (const pkg of packages) {\n ans[pkg.name] = pkg;\n }\n return ans;\n}\n\n// Turn an ActionSpec array into an ActionMap\nexport function mapActions(actions: ActionSpec[]): ActionMap {\n const ans: ActionMap = {};\n for (const action of actions || []) {\n ans[action.name] = action;\n }\n return ans;\n}\n\n// Get the best available name for a project for recording. If project is in a cloned repo\n// the name should reflect the github coordinates and not include incidental aspects of the github URL.\n// If the project is just in the file system we use its absolute path (best we have)\nexport function getBestProjectName(project: DeployStructure): string {\n const annot = project.deployerAnnotation;\n if (!annot) {\n return project.filePath;\n }\n if (annot.repository) {\n let repo = annot.repository;\n if (repo.includes(':')) {\n repo = repo.split(':')[1];\n }\n if (repo.endsWith('.git')) {\n repo = repo.slice(0, -4);\n }\n while (repo.startsWith('/')) {\n repo = repo.slice(1);\n }\n return repo + '/' + annot.projectPath;\n }\n return annot.projectPath;\n}\n\n// Calculate the 'deployer' annotation for inclusion in package and action annotations. This won't change\n// in the course of a deploy run so can be calculated once for inclusion in everything that is deployed.\nexport async function getDeployerAnnotation(\n project: string\n): Promise<DeployerAnnotation> {\n const digest = undefined;\n try {\n const git = simplegit(project);\n const root = await git.revparse(['--show-toplevel']);\n const repo = await git.raw(['config', '--get', 'remote.origin.url']);\n const user = (await git.raw(['config', '--get', 'user.email'])).trim();\n const projectPath = path.relative(root, path.resolve(project));\n let commit = await git.revparse(['head']);\n commit = commit.substring(0, 8);\n const status = await git.status();\n if (!status.isClean()) {\n commit += '++';\n }\n return { user, repository: repo.trim(), projectPath, commit, digest };\n } catch {\n const user = os.userInfo().username.trim();\n const projectPath = path.resolve(project);\n return { user, projectPath, digest };\n }\n}\n\n// Wipe all the entities from the namespace referred to by an OW client handle.\n// This is not guaranteed to succeed but it will attempt to wipe as much as possible,\n// returning all errors that occurred. If an error occurs when removing a trigger that\n// is associated with a function, the function is not deleted.\nexport async function wipe(\n client: Client,\n credentials: Credentials\n): Promise<void> {\n const errors: any[] = [];\n // Delete the actions, which will delete associated triggers if possible. If a trigger\n // cannot be deleted, the action is left also.\n await wipeActions(client, credentials, errors);\n debug('Actions wiped');\n // Delete the packages. Note that if an action deletion failed, the containing\n // package will likely fail also.\n await wipeAll(client.packages, 'Package', errors);\n debug('Packages wiped');\n // There _could_ have been orphaned triggers that were not deleted when we\n // deleted actions (since they were not connected to an existing action).\n // On the other hand, if one or more triggers failed deletion before, they\n // may fail again here, with duplicate errors. We are tolerating that for the moment.\n const namespace = await getTargetNamespace(client);\n const triggers = await listTriggersForNamespace(namespace, credentials, '');\n const errs = await undeployTriggers(triggers, credentials);\n if (errs.length > 0) {\n errors.push(...errs);\n }\n // Delete rules and OpenWhisk triggers for good measure (there really shouldn't be any)\n await wipeAll(client.rules, 'Rule', errors);\n debug('Rules wiped');\n await wipeAll(client.triggers, 'Trigger', errors);\n debug('OpenWhisk triggers wiped');\n // Determine if any errors occurred. If so, throw them. We have tried using AggregateError\n // here but ran into perplexing problems. So, using an ad hoc approach when combining errors.\n if (errors.length > 1) {\n const combined = Error(\n 'multiple errors occurred while cleaning the namespace'\n ) as any;\n combined.errors = errors;\n throw combined;\n }\n if (errors.length == 1) {\n throw errors[0];\n }\n}\n\n// Repeatedly wipe an entity (rule, trigger, or package) from the namespace denoted by the OW client until none are left\n// Note that the list function can only return 200 entities at a time).\n// Actions are handled differently since they may have triggers associated with them.\nasync function wipeAll(handle: any, kind: string, errors: any[]) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const entities = await handle.list({ limit: 200 });\n if (entities.length === 0) {\n return;\n }\n for (const entity of entities) {\n let name = entity.name;\n const nsparts = entity.namespace.split('/');\n if (nsparts.length > 1) {\n name = nsparts[1] + '/' + name;\n }\n try {\n await handle.delete(name);\n debug('%s %s deleted', kind, name);\n } catch (err) {\n debug('error deleting %s %s: %O', err);\n errors.push(err);\n }\n }\n }\n}\n\n// Repeatedly wipe actions from the namespace denoted by the OW client until none are left.\n// Note that the list function can only return 200 actions at a time. This is done\n// differently from the other entity types because actions can have associated triggers\n// which should be deleted first (with the action remaining if the trigger deletion fails).\nasync function wipeActions(\n client: Client,\n credentials: Credentials,\n errors: any[]\n) {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const actions = await client.actions.list({ limit: 200 });\n if (actions.length === 0) {\n return;\n }\n for (const action of actions) {\n let name = action.name;\n const nsparts = action.namespace.split('/');\n if (nsparts.length > 1) {\n name = nsparts[1] + '/' + name;\n }\n const result = await deleteAction(name, client, credentials);\n if (Array.isArray(result)) {\n errors.push(...result);\n debug('error deleting the triggers');\n }\n debug('action %s deleted', name);\n }\n }\n}\n\n// Delete an action after first deleting any DigitalOcean triggers that are targeting it.\n// If we can't delete the triggers, we don't delete the action (maintains the invariant that\n// a trigger should only exist if its invoked function also exists). This function is not\n// intended to throw but to return errors in an array (either errors deleting triggers or an\n// error deleting the action).\nexport async function deleteAction(\n actionName: string,\n owClient: Client,\n credentials: Credentials\n): Promise<Action | Error[]> {\n // Delete triggers.\n const namespace = await getTargetNamespace(owClient);\n const triggers = await listTriggersForNamespace(\n namespace,\n credentials,\n actionName\n );\n const errs = await undeployTriggers(triggers, credentials);\n if (errs.length > 0) {\n return errs;\n }\n try {\n return await owClient.actions.delete({ name: actionName });\n } catch (err) {\n const msg = err.message ? err.message : err;\n return [new Error(`unable to undeploy action '${actionName}': ${msg}`)];\n }\n}\n\n// Generate a secret in the form of a random alphameric string (TODO what form(s) do we actually support)\nexport function generateSecret(): string {\n return randomstring.generate();\n}\n\n// Guard against accidental deployment to a sensitive namespace on a production host\n// Not called if the --production flag was set.\n// 'nim install actions' will set this flag.\n// The workbench 'project deploy' command will never set this flag\n// Developers using the deployProject CLI may set this flag but presumably will only do so by intention.\nexport function saveUsFromOurselves(\n namespace: string,\n apihost: string\n): boolean {\n let sensitiveNamespaces: string[];\n let productionProjects: string[];\n try {\n sensitiveNamespaces = require('../sensitiveNamespaces.json');\n productionProjects = require('../productionProjects.json');\n } catch (_) {\n // Customers don't need a --production flag ... their auth token defines what they can and can't do\n return false;\n }\n return (\n sensitiveNamespaces.includes(namespace) &&\n isProductionProject(apihost, productionProjects)\n );\n}\n\n// Determine whether an apihost (given as a string URL) denotes any of a list of projects\nfunction isProductionProject(\n apihost: string,\n productionProjects: string[]\n): boolean {\n const url = new URL(apihost);\n const domain = url.hostname.split('.')[0];\n if (domain === 'api') {\n return true;\n }\n const project = domain.replace('api', 'nim');\n return productionProjects.includes(project);\n}\n\n// Compute the digest of a PackageSpec\nexport function digestPackage(pkg: PackageSpec): string {\n const hash = crypto.createHash('sha256');\n digestBoolean(hash, pkg.shared);\n digestBoolean(hash, pkg.web);\n digestDictionary(hash, pkg.annotations);\n digestDictionary(hash, pkg.parameters);\n digestDictionary(hash, pkg.environment);\n digestDictionary(hash, pkg.binding);\n for (const action of pkg.actions || []) {\n hash.update(action.name);\n }\n return String(hash.digest('hex'));\n}\n\nfunction digestBoolean(hash: crypto.Hash, toDigest: boolean) {\n hash.update(String(!!toDigest));\n}\n\nfunction digestStringArray(hash: crypto.Hash, toDigest: string[]) {\n if (toDigest) {\n for (const value of toDigest) {\n hash.update(value);\n }\n }\n}\n\nfunction digestDictionary(hash: crypto.Hash, toDigest: Record<string, any>) {\n if (toDigest) {\n const keys = Object.keys(toDigest).sort();\n for (const key of keys) {\n hash.update(key);\n const value = toDigest[key];\n switch (typeof value) {\n case 'string':\n hash.update(value);\n break;\n case 'boolean':\n digestBoolean(hash, value);\n break;\n case 'object':\n digestDictionary(hash, value);\n break;\n default: // number, bigint ... and some exotic cases TODO: need we do better?\n hash.update(String(value));\n break;\n }\n }\n }\n}\n\n// Compute the digest of an ActionSpec. Code is provided as a separate argument (code member of the ActionSpec will either be identical or undefined)\nexport function digestAction(action: ActionSpec, code: string): string {\n const hash = crypto.createHash('sha256');\n digestBoolean(hash, action.binary);\n digestBoolean(hash, action.zipped);\n hash.update(String(action.web));\n hash.update(String(action.webSecure));\n digestDictionary(hash, action.annotations);\n digestDictionary(hash, action.parameters);\n digestDictionary(hash, action.environment);\n digestDictionary(hash, action.limits);\n digestStringArray(hash, action.sequence);\n hash.update(code);\n if (action.main) {\n hash.update(action.main);\n }\n hash.update(action.runtime);\n return String(hash.digest('hex'));\n}\n\n// Get the status reporting directory, making it if it doesn't exist\nfunction getStatusDir(project: string): {\n statusDir: string;\n created: boolean;\n} {\n const statusDir = path.join(project, '.deployed');\n let created = false;\n if (!fs.existsSync(statusDir)) {\n fs.mkdirSync(statusDir);\n created = true;\n }\n return { statusDir, created };\n}\n\n// Write the \"slice result\" to the status area\n// Note: this is not being used yet. It is not clear how the remote build action is supposed to find the status area.\n// Other possibilities are to write it in a more easily found place or to write it to a file descriptor and pipe it\n// somewhere.\nexport function writeSliceResult(project: string, result: string): void {\n const file = path.join(getStatusDir(project).statusDir, 'sliceResult');\n fs.writeFileSync(file, result);\n}\n\n// Called after a deploy step to record important information from the DeployResponse into the project.\n// Essentially a dual of loadVersions but not quite symmetrical since its argument is a DeployResponse\n// The 'replace' argument causes the new VersionEntry calculated from the DeployResponse to replace\n// an existing one. This was the behavior prior to the advent of include/exclude, and it is what is\n// requested when that feature is not used. If 'replace' is false, then the new VersionEntry is merged\n// into an existing one if any, preserving information for things not deployed in the current round.\n// Returns the path name of the status directory if newly created, empty string otherwise\nexport function writeProjectStatus(\n project: string,\n results: DeployResponse,\n replace: boolean\n): string {\n debug('writing project status with %O', results);\n const { apihost, namespace, packageVersions, actionVersions } = results;\n if (\n Object.keys(actionVersions).length === 0 &&\n Object.keys(packageVersions).length === 0\n ) {\n debug('there is no meaningful project status to write');\n return '';\n }\n const { statusDir, created } = getStatusDir(project);\n let versionList: VersionEntry[] = [];\n const versionFile = path.join(statusDir, 'versions.json');\n if (fs.existsSync(versionFile)) {\n debug('version file already exists');\n const old = JSON.parse(String(fs.readFileSync(versionFile)));\n if (Array.isArray(old)) {\n versionList = old;\n debug('version list using legacy format, not preserved');\n } // Otherwise (not array) it is the legacy format and cannot be added to so we just overwrite\n }\n const versionInfo: VersionEntry = {\n apihost,\n namespace,\n packageVersions,\n actionVersions\n };\n const oldEntry: VersionEntry = versionList.find(\n (entry) => entry.apihost === apihost && entry.namespace === namespace\n );\n if (!oldEntry) {\n debug('new entry pushed to version list');\n versionList.push(versionInfo);\n } else {\n debug('merging new entry into old');\n mergeVersions(oldEntry, versionInfo, replace);\n }\n fs.writeFileSync(versionFile, JSON.stringify(versionList, null, 2));\n debug('wrote version info to %s', versionFile);\n return created ? statusDir : '';\n}\n\n// Merge new information into old information within the version store.\n// If replace is specified, each major element of the old entry (packageVersions, actionVersions) is replaced\n// with the new. Otherwise, the dictionaries are merged.\nfunction mergeVersions(\n oldEntry: VersionEntry,\n newEntry: VersionEntry,\n replace: boolean\n) {\n if (replace) {\n Object.assign(oldEntry, newEntry);\n } else {\n Object.assign(oldEntry.actionVersions, newEntry.actionVersions);\n Object.assign(oldEntry.packageVersions, newEntry.packageVersions);\n }\n}\n\n// Load the version information of a project for a namespace and apihost. Return an appropriately empty structure if not found.\nexport function loadVersions(\n projectPath: string,\n namespace: string,\n apihost: string\n): VersionEntry {\n const versionFile = path.join(projectPath, '.deployed', 'versions.json');\n if (fs.existsSync(versionFile)) {\n const allEntries = JSON.parse(String(fs.readFileSync(versionFile)));\n for (const entry of allEntries) {\n if (namespace === entry.namespace && apihost === entry.apihost) {\n return entry;\n }\n }\n }\n return {\n namespace,\n apihost,\n packageVersions: {},\n actionVersions: {}\n };\n}\n\n// Introduce small delay\nexport function delay(millis: number): Promise<void> {\n return new Promise(function (resolve) {\n setTimeout(() => resolve(), millis);\n });\n}\n\n// Await the completion of an action invoke. The poll interval is fixed at 1 second.\n// The 'waiting' argument is called every 10 polls (intended for providing progress feedback).\n// The total wait time should be expressed in #polls. Because of imprecision in the time\n// management this will generally be longer than #seconds but not by a huge factor.\n// If the wait \"times out\", undefined is returned.\nexport async function waitForActivation(\n id: string,\n wsk: Client,\n waiting: () => void,\n total: number\n): Promise<Activation<Dict>> {\n debug(`waiting for activation with id ${id}`);\n let errors = 0;\n const maxErrors = 3;\n for (let i = 1; i <= total; i++) {\n try {\n const activation = await wsk.activations.get(id);\n if (activation.end || activation.response.status) {\n debug('activation %s found after %d iterations', id, i);\n return activation;\n }\n } catch (err) {\n if (err.statusCode !== 404) {\n errors++;\n }\n if (errors > maxErrors) {\n throw err;\n }\n }\n if (i % 10 === 0) {\n waiting();\n }\n await delay(1000);\n }\n return undefined;\n}\n\n// Higher level wrapper around wskRequest for web-secure actions. Forms the URL\nexport function invokeWebSecure(\n actionAndQuery: string,\n auth: string,\n apihost: string\n): Promise<any> {\n const url = apihost + '/api/v1/web' + actionAndQuery;\n return wskRequest(url, auth);\n}\n\n// Subroutine to invoke OW with a GET and return the response. Bypasses the OW client. Used\n// to invoke web actions, with or without auth needed.\nexport function wskRequest(\n url: string,\n auth: string = undefined\n): Promise<any> {\n debug('Request to: %s', url);\n return new Promise(function (resolve, reject) {\n const xhr = new XMLHttpRequest();\n xhr.open('GET', url);\n const userAgent = getUserAgent();\n xhr.setRequestHeader('User-Agent', userAgent);\n xhr.onload = function () {\n if (this.status >= 200 && this.status < 300) {\n debug('useful response');\n resolve(JSON.parse(xhr.responseText));\n } else {\n debug('Error from OW %s %s', xhr.status, xhr.responseText);\n reject(new Error(xhr.responseText));\n }\n };\n xhr.onerror = function () {\n debug('network error');\n reject(new Error('Network error'));\n };\n if (auth) {\n if (auth.includes(':')) {\n debug('Setting basic authorization header');\n xhr.setRequestHeader(\n 'Authorization',\n 'Basic ' + Buffer.from(auth).toString('base64')\n );\n } else {\n debug('Setting X-Require-Whisk-Auth header to %s', auth);\n xhr.setRequestHeader('X-Require-Whisk-Auth', auth);\n }\n }\n xhr.send();\n });\n}\n\n// Utility to rename a package in a DeployStructure in a safe and consistent way.\n// Will throw if the oldName does not match a package in the spec.\nexport function renamePackage(\n spec: DeployStructure,\n oldName: string,\n newName: string\n): DeployStructure {\n const pkg = spec.packages?.find((pkg) => pkg.name === oldName);\n if (!pkg) {\n throw new Error(\n `Package '${oldName}' was not found in the DeployStructure`\n );\n }\n pkg.name = newName;\n if (pkg.actions) {\n for (const action of pkg.actions) {\n action.package = newName;\n }\n }\n return spec;\n}\n\n// Checks if a given pattern matches exclusion list, defined by system or user via global .exclude file.\nexport function isExcluded(match: string): boolean {\n return anymatch(getExclusionList(), match);\n}\n\n// Returns full list of exclusion patterns, predefined or listed in the global .exclude file.\nexport function getExclusionList(): string[] {\n let userDefinedPatterns = [];\n try {\n const globalExcludeFile = path.join(nimbellaDir(), '.exclude');\n userDefinedPatterns = fs\n .readFileSync(globalExcludeFile)\n .toString()\n .split('\\n')\n .filter((e) => e.toString().trim() !== '');\n } catch (e) {\n debug(e.message);\n }\n const allPatterns = [...userDefinedPatterns, ...SYSTEM_EXCLUDE_PATTERNS];\n return allPatterns;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Functions to manage the credential store.\n\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport {\n CredentialStore,\n CredentialEntry,\n Credentials,\n CredentialRow,\n Feedback\n} from './deploy-struct';\nimport createDebug from 'debug';\nimport { wskRequest } from './util';\nconst debug = createDebug('nimbella.cli');\n\n// Non-exported constants\nconst HOME = process.env[process.platform === 'win32' ? 'USERPROFILE' : 'HOME'];\nconst NAMESPACE_URL_PATH = '/api/v1/namespaces';\nconst NIMBELLA_DIR = '.nimbella';\nconst WSK_PROPS = 'wskprops';\nconst CREDENTIAL_STORE = 'credentials.json';\n// Function indirection needed for webpack\nexport function nimbellaDir(): string {\n const fromEnv = process.env.NIMBELLA_DIR;\n if (fromEnv && fromEnv.length > 0) {\n return fromEnv;\n }\n return path.join(HOME, NIMBELLA_DIR);\n}\nfunction wskProps() {\n return path.join(nimbellaDir(), WSK_PROPS);\n}\nfunction credentialStore() {\n return path.join(nimbellaDir(), CREDENTIAL_STORE);\n}\n\n// Exports\n\n// The type of a persistance manager, which will differ between cloud and local\nexport interface Persister {\n loadCredentialStoreIfPresent: () => CredentialStore;\n loadCredentialStore: () => Promise<CredentialStore>;\n saveCredentialStore: (store: CredentialStore) => void;\n saveLegacyInfo: (apihost: string, auth: string) => void;\n}\n\n// The persister to use when local storage is accessible.\n// This can be replaced to bypass file system access.\nconst fileSystemPersister: Persister = {\n loadCredentialStoreIfPresent,\n loadCredentialStore,\n saveCredentialStore,\n saveLegacyInfo\n};\n\n// The persister to use for all auth code.\n// Not a constant so that it can be explicitly set to bypass file system access.\nexport const authPersister = fileSystemPersister;\n\n// Add credential to credential store and make it the default. Does not persist the result\nexport function addCredential(\n store: CredentialStore,\n apihost: string,\n namespace: string,\n api_key: string\n): Credentials {\n debug('Adding credential to credential store');\n let nsMap = store.credentials[apihost];\n if (!nsMap) {\n nsMap = {};\n store.credentials[apihost] = nsMap;\n }\n nsMap[namespace] = { api_key };\n store.currentHost = apihost;\n store.currentNamespace = namespace;\n return {\n namespace,\n ow: { apihost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n\n// Remove a namespace from the credential store\nexport async function forgetNamespace(\n namespace: string,\n apihost: string | undefined,\n feedback: Feedback\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n const creds = getUniqueCredentials(namespace, apihost, store);\n const host = apihost || creds.ow.apihost;\n const hostMap = store.credentials[host];\n let undefinedWarning = false;\n if (hostMap && hostMap[namespace]) {\n delete hostMap[namespace];\n if (host === store.currentHost && store.currentNamespace === namespace) {\n store.currentNamespace = undefined;\n undefinedWarning = true;\n try {\n fs.unlinkSync(wskProps());\n } catch {\n // Do nothing\n }\n }\n authPersister.saveCredentialStore(store);\n if (undefinedWarning) {\n feedback.warn(`'${namespace}' was the current namespace`);\n feedback.warn(\n 'A new namespace target must be specified on or before the next project deployment'\n );\n }\n } else {\n feedback.warn(\n `There is no credential entry for namespace '${namespace}' on API host '${host}'`\n );\n }\n return creds;\n}\n\n// Switch the active namespace in the credential store. The namespace argument is required.\n// All occurrences of the namespace across all API hosts are collected.\n// If there is an explicit 'apihost' argument this collection must include an entry with that API host\n// Otherwise,\n// - if there is just one occurrence, the switch is to that namespace on that API host\n// - otherwise, no switch occurs and the thrown Error either states that no credentials exist for that namespace\n// or that the --apihost flag is required to indicate which one is intended\nexport async function switchNamespace(\n namespace: string,\n apihost: string | undefined\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n const answer = getUniqueCredentials(namespace, apihost, store);\n const newHost = answer.ow.apihost;\n if (store.currentHost === newHost && store.currentNamespace === namespace) {\n debug('not an actual change');\n return answer;\n }\n store.currentHost = newHost;\n store.currentNamespace = namespace;\n authPersister.saveCredentialStore(store);\n authPersister.saveLegacyInfo(newHost, answer.ow.api_key);\n debug(`Switched target namespace to '${namespace}' on API host '${newHost}'`);\n return answer;\n}\n\n// Get a valid Credentials object by finding the information in the environment. This will generally not work in the\n// CLI context but is designed to work via the deployer API when running in actions. It may be especially\n// useful in shared packages, where the credentials in the environment will vary by invoking user.\n// For the information to be fully usable the environment must include __OW_API_KEY, which is only present when\n// the action is annotated with provide-api-key=true.\n// If the environment is inadequate to support this API, an error is generally not indicated. Instead,\n// an incomplete Credentials object is returned.\nexport function getCredentialsFromEnvironment(): Credentials {\n const apihost = process.env.__OW_API_HOST;\n const namespace = process.env.__OW_NAMESPACE;\n const api_key = process.env.__OW_API_KEY;\n const do_token = process.env.DO_API_KEY;\n return { namespace, ow: { api_key, apihost }, do_token };\n}\n\n// Get the credentials for a namespace. Similar logic to switchNamespace but does not change which\n// namespace is considered current.\nexport async function getCredentialsForNamespace(\n namespace: string,\n apihost: string | undefined\n): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n return getUniqueCredentials(namespace, apihost, store);\n}\n\n// Get the current credentials. This will succeed iff the user has a credential store and a current namespace.\n// Otherwise, we throw an error.\nexport async function getCredentials(): Promise<Credentials> {\n const store = await authPersister.loadCredentialStore();\n if (!store.currentHost || !store.currentNamespace) {\n throw new Error(\n \"You do not have a current namespace. Use 'nim auth login' to create a new one or 'nim auth switch' to use an existing one\"\n );\n }\n const entry = store.credentials[store.currentHost][store.currentNamespace];\n const { api_key } = entry;\n return {\n namespace: store.currentNamespace,\n ow: { apihost: store.currentHost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n\n// Convenience function to load, add, save a new credential.\nexport async function addCredentialAndSave(\n apihost: string,\n auth: string,\n namespace: string\n): Promise<Credentials> {\n const credStore = await authPersister.loadCredentialStore();\n const nsPromise = namespace\n ? Promise.resolve(namespace)\n : getNamespace(apihost, auth);\n return nsPromise.then((namespace) => {\n const credentials = addCredential(credStore, apihost, namespace, auth);\n authPersister.saveCredentialStore(credStore);\n return credentials;\n });\n}\n\n// Provide contents of the CredentialStore in a dictionary style suitable for listing and tabular presentation\nexport async function getCredentialDict(): Promise<{\n [host: string]: CredentialRow[];\n}> {\n const store = await authPersister.loadCredentialStore();\n const result: { [host: string]: CredentialRow[] } = {};\n for (const apihost in store.credentials) {\n let rows: CredentialRow[] = [];\n for (const namespace in store.credentials[apihost]) {\n const current =\n apihost === store.currentHost && namespace === store.currentNamespace;\n rows.push({ namespace, current, apihost });\n rows = rows.sort((a, b) => a.namespace.localeCompare(b.namespace));\n }\n result[apihost] = rows;\n }\n return result;\n}\n\n// Get the list of apihosts from the credential store\nexport async function getApiHosts(persister: Persister): Promise<string[]> {\n const store = await persister.loadCredentialStore();\n return Object.keys(store.credentials);\n}\n\n// Flat (single array) version of getCredentialDict\nexport async function getCredentialList(): Promise<CredentialRow[]> {\n const dict = await getCredentialDict();\n return Object.values(dict).reduce((acc, val) => acc.concat(val), []);\n}\n\n// Get the namespace associated with an auth on a specific host\nexport function getNamespace(host: string, auth: string): Promise<string> {\n debug('getting current namespace');\n const url = host + NAMESPACE_URL_PATH;\n return wskRequest(url, auth).then((list) => list[0]);\n}\n\n// Get current namespace\nexport async function getCurrentNamespace(): Promise<string | undefined> {\n debug('getting current namespace');\n const store = await authPersister.loadCredentialStore();\n return store.currentNamespace;\n}\n\n// fileSystemPersister functions (indirectly exported)\nfunction saveCredentialStore(store: CredentialStore): void {\n const toWrite = JSON.stringify(store, null, 2);\n debug('writing credential store');\n fs.writeFileSync(credentialStore(), toWrite, { mode: 0o600 });\n}\n\nfunction saveLegacyInfo(apihost: string, auth: string): void {\n saveWskProps(apihost, auth);\n debug('stored .wskprops with API host %s', apihost);\n}\n\nfunction loadCredentialStore(): Promise<CredentialStore> {\n // Returns a promise for historical reasons. Could be tweaked since\n // the promise is no longer needed.\n if (!fs.existsSync(credentialStore())) {\n return Promise.resolve(initialCredentialStore());\n }\n const contents = fs.readFileSync(credentialStore());\n return Promise.resolve(JSON.parse(String(contents)));\n}\n\nfunction loadCredentialStoreIfPresent(): CredentialStore {\n if (!fs.existsSync(credentialStore())) {\n return undefined;\n }\n const contents = fs.readFileSync(credentialStore());\n return JSON.parse(String(contents));\n}\n\n// Utility functions (not exported)\n\n// Make the initial credential store when none exists. It always starts out empty. This also makes\n// the parent directory preparatory to the first write. It does not actually write the credential store.\nfunction initialCredentialStore(): CredentialStore {\n if (!fs.existsSync(nimbellaDir())) {\n fs.mkdirSync(nimbellaDir(), { mode: 0o700 });\n }\n return {\n currentHost: undefined,\n currentNamespace: undefined,\n credentials: {}\n };\n}\n\n// Write ~/.nimbella/wskprops. Used when the default api host or api key change (TODO: this never saves the 'insecure' flag; that should\n// probably be correlated with the api host)\nfunction saveWskProps(apihost: string, auth: string) {\n const wskPropsContents = `APIHOST=${apihost}\\nAUTH=${auth}\\n`;\n fs.writeFileSync(wskProps(), wskPropsContents, { mode: 0o600 });\n}\n\n// Given a namespace and _optionally_ an apihost, return the credentials, throwing errors based on the\n// number of matches. Used in cases where the credentials are expected to exist but the client may or\n// may not have provided an API host\nfunction getUniqueCredentials(\n namespace: string,\n apihost: string | undefined,\n store: CredentialStore\n): Credentials {\n const possibles: { [key: string]: CredentialEntry } = {};\n let credentialEntry: CredentialEntry;\n let newHost: string;\n for (const host in store.credentials) {\n const entry = store.credentials[host][namespace];\n if (entry) {\n possibles[host] = entry;\n }\n }\n if (apihost) {\n if (possibles[apihost]) {\n credentialEntry = possibles[apihost];\n newHost = apihost;\n } else {\n throw new Error(\n `No credentials found for namespace '${namespace}' on API host '${apihost}'`\n );\n }\n } else {\n const pairs = Object.entries(possibles);\n if (pairs.length === 1) {\n [newHost, credentialEntry] = pairs[0];\n } else if (pairs.length === 0) {\n throw new Error(\n `No credentials found for namespace '${namespace}' on any API host`\n );\n } else {\n throw new Error(\n `The namespace '${namespace}' exists on more than one API host. An '--apihost' argument is required`\n );\n }\n }\n const { api_key } = credentialEntry;\n debug('have authkey: %s', api_key);\n return {\n namespace,\n ow: { apihost: newHost, api_key },\n do_token: process.env.DO_API_KEY\n };\n}\n", "import axios, { AxiosInstance } from 'axios';\nimport { getCredentials } from './credentials';\nimport { Credentials } from './deploy-struct';\n\nimport debug from 'debug';\nconst debug_log = debug('nim:deployer:runtimes');\n\nexport const API_ENDPOINT = '/api/v1';\n\nlet cachedRuntimes: RuntimesConfig;\n\n// Static table to use if the host cannot be contacted\nconst staticRuntimes: RuntimesConfig = {\n go: [\n {\n default: false,\n kind: 'go:1.15'\n },\n {\n default: true,\n kind: 'go:1.17'\n }\n ],\n nodejs: [\n {\n default: true,\n kind: 'nodejs:14'\n },\n {\n default: false,\n kind: 'nodejs-lambda:14'\n },\n {\n default: false,\n kind: 'nodejs:18'\n },\n {\n default: false,\n kind: 'nodejs-lambda:18'\n }\n ],\n php: [\n {\n default: true,\n kind: 'php:8.0'\n }\n ],\n python: [\n {\n default: true,\n kind: 'python:3.9'\n }\n ]\n};\n\n// Custom types for runtimes.json configuration parameters\ntype RuntimeLabel = string;\ntype RuntimeKind = string;\ntype RuntimeFileExtension = string;\n\nexport interface Runtime {\n kind: RuntimeKind;\n default?: boolean;\n}\n\nexport type RuntimesConfig = Record<RuntimeLabel, Runtime[]>;\n\n// List of file extensions for runtimes. This hardcoded list used to be present\n// in the extensions field of the runtimes.json document.\n// The commented-out lines are not currently supported by DigitalOcean;\n// some may be supported in the future.\nconst FileExtensionRuntimes: Record<RuntimeKind, RuntimeFileExtension[]> = {\n go: ['go'],\n // 'java': ['java', 'jar'],\n nodejs: ['js', 'ts'], // nodejs works for both javascript and typescript\n // 'typescript': ['ts'],\n php: ['php'],\n python: ['py']\n // 'ruby': ['rb'],\n // 'rust': ['rs'],\n // 'swift': ['swift'],\n // 'deno': ['ts', 'js'],\n // 'dotnet': ['cs', 'vb']\n};\n\n// File extensions which imply binary data\nconst BinaryFileExtensions: Set<RuntimeFileExtension> =\n new Set<RuntimeFileExtension>(['zip', 'jar']);\n\n// Send HTTP request to platform endpoint for runtimes configuration\nexport async function fromPlatform(\n httpClient: AxiosInstance,\n platformUrl: string\n): Promise<Record<string, unknown>> {\n const url = `${platformUrl}${API_ENDPOINT}`;\n debug_log(`loading runtimes from platform @ ${url}`);\n try {\n const { data } = await httpClient.get(url);\n debug_log(`loaded runtimes json: ${JSON.stringify(data)}`);\n return data?.runtimes;\n } catch (err) {\n // Error due to HTTP Code > 2XX\n if (err.response) {\n throw new Error(\n `http request failed (${url}) with status (${err.response.status}): ${err.response.statusText} `\n );\n // or response never received\n } else if (err.request) {\n throw new Error(`http request failed: GET ${url}`);\n // or something else...\n } else {\n throw err;\n }\n }\n}\n\n// Compute the runtime from the file extension.\nexport function runtimeForFileExtension(\n fileExtension: RuntimeFileExtension\n): RuntimeKind | undefined {\n const runtime = Object.entries(FileExtensionRuntimes).find((item) =>\n item[1].includes(fileExtension)\n );\n return runtime && runtime.length > 0 ? `${runtime[0]}:default` : undefined;\n}\n\n// Does file extension imply binary data?\nexport function isBinaryFileExtension(\n fileExtension: RuntimeFileExtension\n): boolean {\n return BinaryFileExtensions.has(fileExtension);\n}\n\n// Compute the expected file extension from a runtime name.\n// Runtime returned should match the option for whether file extension refers to binary data\nexport function fileExtensionForRuntime(\n runtime: RuntimeKind,\n isBinaryExtension: boolean\n): RuntimeFileExtension {\n debug_log(\n `fileExtensionForRuntime: runtime (${runtime}) binary (${isBinaryExtension})`\n );\n const isSameRuntime = (r: string): boolean => r.includes(runtime);\n const isValidRuntime = Object.keys(FileExtensionRuntimes).some(isSameRuntime);\n if (!isValidRuntime)\n throw new Error(`Invalid runtime ${runtime} encountered`);\n\n return isBinaryExtension\n ? FileExtensionRuntimes[runtime].filter((item) =>\n BinaryFileExtensions.has(item)\n )[0]\n : FileExtensionRuntimes[runtime][0];\n}\n\n// Does the runtime kind exist in the platform config?\nexport async function isValidRuntime(kind: RuntimeKind): Promise<boolean> {\n debug_log(`isValidRuntime: kind (${kind})`);\n let exactMatch = true;\n if (kind.endsWith(':default')) {\n kind = kind.split(':')[0] + ':';\n exactMatch = false;\n }\n debug_log('searching');\n const runtimes = await getRuntimes();\n for (const runtimeArray of Object.values(runtimes)) {\n for (const runtime of runtimeArray) {\n if (exactMatch && kind === runtime.kind) {\n debug_log(`${kind}===${runtime.kind}`);\n return true;\n } else if (\n !exactMatch &&\n runtime.kind.startsWith(kind) &&\n runtime.default\n ) {\n debug_log(`${runtime.kind} starts with ${kind} and is the default`);\n return true;\n }\n debug_log(`no match on ${runtime.kind}`);\n }\n }\n return false;\n}\n\n// Find the default runtime for a language\nexport function defaultRuntime(\n runtimes: RuntimesConfig,\n label: RuntimeLabel\n): RuntimeKind {\n debug_log(`defaultRuntime: runtimes (${runtimes}) label (${label})`);\n const kinds = runtimes[label] ?? [];\n const defaultRuntime = kinds.find((k) => k.default) ?? { kind: undefined };\n return defaultRuntime.kind;\n}\n\n// Compute a runtime kind from the 'mid string' of a file name of the form name.runtime.zip\nexport async function runtimeForZipMid(mid: string): Promise<RuntimeKind> {\n const runtime = mid.includes('-') ? mid.replace('-', ':') : `${mid}:default`;\n return (await isValidRuntime(runtime)) ? runtime : undefined;\n}\n\n// Return default kind for runtime label - if explicit version isn't used.\nexport async function canonicalRuntime(\n runtime: RuntimeKind\n): Promise<RuntimeKind> {\n if (runtime.endsWith(':default')) {\n const [label] = runtime.split(':');\n const runtimes = await getRuntimes();\n return defaultRuntime(runtimes, label);\n }\n return runtime;\n}\n\n// Custom type guard to ensure JSON response is in the correct format\nfunction isValidRuntimesJson(\n src: Record<string, unknown>\n): src is RuntimesConfig {\n return Object.values(src).every(\n (v) => Array.isArray(v) && v.every((k) => k.hasOwnProperty('kind')) // eslint-disable-line no-prototype-builtins\n );\n}\n\n// Load runtimes JSON configuration file from platform endpoint\nexport async function load(apihost: string): Promise<RuntimesConfig> {\n const runtimes = await fromPlatform(axios, apihost);\n if (!isValidRuntimesJson(runtimes)) {\n throw new Error(\n `Invalid runtime JSON received from platform API: ${apihost}`\n );\n }\n return runtimes;\n}\n\n// Get the runtimes configuration. This code assumes that _either_ all API hosts are equivalent\n// _or_ only one API host is used in the module lifetime.\n// The parsed runtime configuration will be stored in a local cache and returned after the first call.\n// If no API host can be determined or there is an error contacting the host, then a built-in table\n// is returned (this information changes slowly and so the built-in value can't be terribly stale).\nexport async function getRuntimes(): Promise<RuntimesConfig> {\n if (cachedRuntimes) {\n return cachedRuntimes;\n }\n // Determine the API host either by reading the credential store or looking in the environment.\n // The latter is needed when running in a container performing remote build, since there may not be\n // any credential store.\n let creds: Credentials;\n try {\n creds = await getCredentials();\n } catch {\n // DO NOTHING\n }\n const apihost =\n creds?.ow?.apihost ||\n process.env.__OW_API_HOST ||\n process.env.savedOW_API_HOST;\n if (apihost) {\n cachedRuntimes = await load(apihost);\n } else {\n cachedRuntimes = staticRuntimes;\n }\n return cachedRuntimes;\n}\n", "/*\n * Copyright (c) 2022 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Includes support for listing, installing, and removing triggers, when such triggers are attached to\n// an action.\n\n// Note well: this code is prepared to succeed silently (no-op) in contexts where the authorization to\n// manage triggers is absent. To make the code do something, the DO_API_KEY environment variable must be\n// set to the DO API key that should be used to contact the DO API endpoint. In doctl, this key will be\n// placed in the process environment of the subprocess that runs the deployer. If the deployer is invoked\n// via nim rather than doctl, the invoking context must set this key (e.g. in the app platform build container\n// or for testing).\n\nimport { TriggerSpec, DeploySuccess, Credentials } from './deploy-struct';\nimport { default as axios, AxiosRequestConfig } from 'axios';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:triggers');\nconst doAPIEndpoint = 'https://api.digitalocean.com';\n\n// Returns an array. Elements are a either DeploySuccess structure for use in reporting when the trigger\n// is deployed successfully, or an Error if the trigger failed to deploy. These are 1-1 with the input\n// triggers argument.\nexport async function deployTriggers(\n triggers: TriggerSpec[],\n functionName: string,\n credentials: Credentials\n): Promise<(DeploySuccess | Error)[]> {\n const result: (DeploySuccess | Error)[] = [];\n for (const trigger of triggers) {\n result.push(await deployTrigger(trigger, functionName, credentials));\n }\n debug('finished deploying triggers, returning result');\n return result;\n}\n\n// Undeploy one or more triggers. Returns the empty array on success. Otherwise, the return\n// contains all the errors from attempted deletions.\nexport async function undeployTriggers(\n triggers: string[],\n credentials: Credentials\n): Promise<Error[]> {\n const errors: any[] = [];\n for (const trigger of triggers) {\n try {\n await undeployTrigger(trigger, credentials);\n } catch (err) {\n const msg = err.message ? err.message : err;\n errors.push(new Error(`unable to undeploy trigger '${trigger}': ${msg}`));\n }\n }\n return errors;\n}\n\n// Code to deploy a trigger.\n// Note that basic structural validation of each trigger has been done previously\n// so paranoid checking is omitted.\nasync function deployTrigger(\n trigger: TriggerSpec,\n functionName: string,\n credentials: Credentials\n): Promise<DeploySuccess | Error> {\n const details = trigger.scheduledDetails;\n const { cron, body } = details;\n const { enabled } = trigger;\n const { do_token } = credentials;\n try {\n if (do_token) {\n debug('calling the trigger API to create %s', trigger.name);\n return await doTriggerCreate(\n trigger.name,\n functionName,\n credentials,\n cron,\n enabled,\n body\n );\n } // otherwise do nothing\n } catch (err) {\n debug('caught an error while deploying trigger; will return it');\n // Assume 'err' is either string or Error in the following. Actually it can be anything but use of\n // other types is rare.\n if (typeof err === 'string') {\n return new Error(err);\n }\n return err as Error; // TODO this could lead to a type error eventually if err isn't an Error\n }\n // Neither envvar is set. No-op\n return { name: trigger.name, kind: 'trigger', skipped: true };\n}\n\n// Create a trigger using the real API. Note: the prototype API has the capability to do an UPSERT (by\n// setting the overwrite flag) and we use this. Here, we need to simulate the effect by doing a speculative\n// delete, ignoring 404 errors (actually, we are ignoring all errors, which is probably adequate).\nasync function doTriggerCreate(\n trigger: string,\n fcn: string,\n credentials: Credentials,\n cron: string,\n enabled: boolean,\n withBody: object\n): Promise<DeploySuccess> {\n try {\n await doTriggerDelete(trigger, credentials);\n } catch {\n // DO NOTHING, this assumes the trigger never existed.\n }\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${credentials.namespace}/triggers`,\n method: 'post',\n data: {\n name: trigger,\n function: fcn,\n is_enabled: enabled !== false, // ie, defaults to true\n type: 'SCHEDULED',\n scheduled_details: {\n cron,\n body: withBody\n }\n }\n };\n debug('trigger create request config is: %O', config);\n await doAxios(config, credentials.do_token);\n return { name: trigger, kind: 'trigger', skipped: false };\n}\n\n// Perform a network operation with axios, given a config object.\n// The config object should be complete except for headers. The auth header\n// is added here. The function assumes that doApiKey is set.\nasync function doAxios(\n config: AxiosRequestConfig,\n token: string\n): Promise<object> {\n config.headers = {\n Authorization: `Bearer ${token}`\n };\n const response = await axios(config);\n return response.data;\n}\n\n// Code to delete a trigger.\nasync function undeployTrigger(trigger: string, credentials: Credentials) {\n debug('undeploying trigger %s', trigger);\n const { do_token } = credentials;\n\n if (do_token) {\n return doTriggerDelete(trigger, credentials);\n }\n // Else no-up. A Promise<void> (non-error) is returned implicitly\n}\n\n// Delete a trigger using the real API\nasync function doTriggerDelete(\n trigger: string,\n credentials: Credentials\n): Promise<object> {\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${credentials.namespace}/triggers/${trigger}`,\n method: 'delete'\n };\n return doAxios(config, credentials.do_token);\n}\n\n// Code to get all the triggers for a namespace, or all the triggers for a function in the namespace.\nexport async function listTriggersForNamespace(\n namespace: string,\n credentials: Credentials,\n fcn?: string\n): Promise<string[]> {\n debug('listing triggers');\n const { do_token } = credentials;\n if (do_token) {\n return doTriggerList(namespace, credentials, fcn);\n }\n // No-op if no envvars are set\n return [];\n}\n\n// The trigger list API returns this structure (abridged here to just what we care about)\ninterface TriggerList {\n triggers: TriggerInfo[];\n}\ninterface TriggerInfo {\n name: string;\n function: string;\n}\n\n// List triggers using the real API. Currently, filtering by function is not\n// provided by the API so it is done here.\nasync function doTriggerList(\n namespace: string,\n credentials: Credentials,\n fcn: string\n): Promise<string[]> {\n const config: AxiosRequestConfig = {\n url: `${doAPIEndpoint}/v2/functions/namespaces/${namespace}/triggers`,\n method: 'get'\n };\n let triggers: TriggerList;\n try {\n triggers = (await doAxios(config, credentials.do_token)) as TriggerList;\n } catch (err) {\n debug('error listing triggers: %s', err.message);\n return [];\n }\n debug('got trigger list result from the API: %O', triggers);\n if (!triggers.triggers) {\n debug('result did not have triggers member');\n return [];\n }\n const filtered = fcn\n ? triggers.triggers.filter((trig) => trig.function === fcn)\n : triggers.triggers;\n const names = filtered.map((trig) => trig.name);\n debug('reduced the list to %O', names);\n return names;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport {\n DeployStructure,\n DeployResponse,\n ActionSpec,\n PackageSpec,\n KeyVal,\n Feedback,\n DeploySuccess\n} from './deploy-struct';\nimport {\n combineResponses,\n wrapError,\n wrapSuccess,\n keyVal,\n emptyResponse,\n getActionName,\n straysToResponse,\n makeDict,\n digestPackage,\n digestAction,\n loadVersions,\n waitForActivation\n} from './util';\nimport openwhisk from 'openwhisk';\nimport { deployTriggers } from './triggers';\nimport makeDebug from 'debug';\n\nconst debug = makeDebug('nim:deployer:deploy');\nconst seqDebug = makeDebug('nim:deployer:sequences');\nconst chunkDebug = makeDebug('nim:deployer:chunk');\n\n// Temp fix until https://github.com/apache/openwhisk-client-js/pull/225 is merged.\ntype Exec = openwhisk.Exec & { image?: string };\n\n//\n// Main deploy logic, excluding that assigned to more specialized files\n//\n\n// The max number of operations to have outstanding at a time (for actions).\n// It isn't obvious how to tune this, but 25 seems to work reliably and 50 sometimes has\n// failures. I have had success with 40, actually, but don't want to push our luck.\nconst DEPLOYMENT_CHUNK_SIZE = parseInt(process.env.DEPLOYMENT_CHUNK_SIZE) || 25;\n\n// Load the versions if incremental. If not incremental, the former versions are irrelevant.\nexport async function maybeLoadVersions(\n todeploy: DeployStructure\n): Promise<DeployStructure> {\n if (todeploy.flags.incremental) {\n // Incremental deployment requires the versions up front to have access to the form hashes\n todeploy.versions = loadVersions(\n todeploy.filePath,\n todeploy.credentials.namespace,\n todeploy.credentials.ow.apihost\n );\n }\n return Promise.resolve(todeploy);\n}\n\n// Do the actual deployment\nexport async function doDeploy(\n todeploy: DeployStructure\n): Promise<DeployResponse> {\n const skipPkgDeploy =\n todeploy.slice && todeploy.deployerAnnotation.newSliceHandling;\n delete todeploy.deployerAnnotation.newSliceHandling;\n const actionPromises = (todeploy.packages || []).map((pkg) =>\n deployPackage(pkg, todeploy, skipPkgDeploy)\n );\n const responses: DeployResponse[] = await Promise.all(actionPromises);\n responses.push(straysToResponse(todeploy.strays));\n const sequenceResponses = await deploySequences(todeploy);\n responses.push(...sequenceResponses);\n const response = combineResponses(responses);\n response.apihost = todeploy.credentials.ow.apihost;\n if (!response.namespace) {\n response.namespace = todeploy.credentials.namespace;\n }\n return response;\n}\n\n// Process the remote result when something has been built remotely\nasync function processRemoteResponse(\n activationId: string,\n owClient: openwhisk.Client,\n context: string,\n feedback: Feedback\n): Promise<DeployResponse> {\n let activation: openwhisk.Activation<openwhisk.Dict>;\n const tick = () =>\n feedback.progress(`Processing of ${context} is still running remotely ...`);\n try {\n activation = await waitForActivation(activationId, owClient, tick, 15 * 60); // approx 15 minutes limit\n } catch (err) {\n return wrapError(err, context + ' (waiting for remote build response)');\n }\n if (!activation) {\n return wrapError(\n new Error('Build timed out'),\n ' (waiting for remote build response)'\n );\n }\n if (!activation.response || !activation.response.success) {\n let err = 'Remote build failed to provide a result';\n const resultError = activation?.response?.result?.error;\n if (resultError) {\n const errMsg =\n typeof resultError === 'string' ? resultError : resultError.message;\n if (typeof errMsg === 'string') {\n const parts = errMsg.split('Error:');\n err = parts[parts.length - 1];\n }\n }\n const thrown = new Error(err) as any;\n thrown.activation = JSON.stringify(activation, null, 2); // ensure deep enough nesting\n return wrapError(thrown, context + ' (running remote build)');\n }\n const result = activation.response.result as Record<string, any>;\n debug('Remote result was %O', result);\n const { transcript, outcome } = result;\n if (transcript && transcript.length > 0) {\n feedback.progress(`Transcript of remote build session for ${context}:`);\n for (const line of transcript) {\n feedback.progress(line);\n }\n }\n return outcome;\n}\n\n// Deploy an array of actions of arbitrary size, ensuring that most CHUNK_SIZE operations\n// are pending at the same time.\nasync function deployActionArray(\n actions: ActionSpec[],\n spec: DeployStructure\n): Promise<DeployResponse> {\n let pending = actions;\n const responses: DeployResponse[] = [];\n while (pending.length > 0) {\n const chunk =\n pending.length > DEPLOYMENT_CHUNK_SIZE\n ? pending.slice(0, DEPLOYMENT_CHUNK_SIZE)\n : pending;\n pending = pending.slice(chunk.length);\n const chunkResults = await Promise.all(\n chunk.map((action) => deployAction(action, spec))\n ).then(combineResponses);\n responses.push(chunkResults);\n chunkDebug('Deployed chunk of %d actions', chunk.length);\n }\n return combineResponses(responses);\n}\n\n// Subroutine to deploy just a package and not its actions. Should only be called for\n// \"deployable\" packages (not the default package) and only when deployment of the package\n// is appropriate (not if the package has already been deployed or the context is a slice deploy).\nexport async function onlyDeployPackage(\n pkg: PackageSpec,\n spec: DeployStructure\n): Promise<DeployResponse> {\n const {\n parameters: projectParams,\n environment: projectEnv,\n versions,\n owClient: wsk,\n deployerAnnotation: deployer,\n flags\n } = spec;\n // Check whether the package metadata needs to be deployed; if so, deploy it. If not, make a vacuous response with the existing package\n // VersionInfo. That is needed so that the new versions.json will have the information in it.\n const digest = digestPackage(pkg);\n if (\n flags.incremental &&\n versions.packageVersions &&\n versions.packageVersions[pkg.name] &&\n digest === versions.packageVersions[pkg.name].digest\n ) {\n const packageVersions = {};\n packageVersions[pkg.name] = versions.packageVersions[pkg.name];\n return {\n successes: [],\n failures: [],\n ignored: [],\n packageVersions,\n actionVersions: {},\n namespace: undefined\n };\n } else {\n const former = await wsk.packages\n .get({ name: pkg.name })\n .catch(() => undefined);\n const oldAnnots =\n former && former.annotations ? makeDict(former.annotations) : {};\n delete oldAnnots.deployerAnnot; // remove unwanted legacy from undetected earlier error\n deployer.digest = digest.substring(0, 8);\n const annotDict = Object.assign({}, oldAnnots, pkg.annotations, {\n deployer\n });\n const annotations = keyVal(annotDict);\n const mergedParams = Object.assign({}, projectParams, pkg.parameters);\n const mergedEnv = Object.assign({}, projectEnv, pkg.environment);\n const params = encodeParameters(mergedParams, mergedEnv);\n const owPkg: openwhisk.Package = {\n parameters: params,\n annotations,\n publish: pkg.shared\n };\n let successes: DeploySuccess[] = [];\n if (pkg.binding) {\n if (pkg.actions && pkg.actions.length > 0) {\n throw new Error('a bound package may not contain functions of its own');\n }\n owPkg.binding = pkg.binding;\n successes = [{ name: pkg.name, kind: 'binding', skipped: false }];\n }\n debug('successes: %O', successes);\n return await wsk.packages\n .update({ name: pkg.name, package: owPkg })\n .then((result) => {\n const packageVersions = {};\n packageVersions[pkg.name] = { version: result.version, digest };\n return {\n successes,\n failures: [],\n ignored: [],\n packageVersions,\n actionVersions: {},\n namespace: result.namespace\n };\n })\n .catch((err) => {\n return wrapError(err, `package '${pkg.name}'`);\n });\n }\n}\n\n// Deploy a package, then deploy everything in it (currently just actions and triggers associated with those actions).\nexport async function deployPackage(\n pkg: PackageSpec,\n spec: DeployStructure,\n skipPkgDeploy: boolean\n): Promise<DeployResponse> {\n const { parameters: projectParams, environment: projectEnv } = spec;\n if (\n pkg.name === 'default' &&\n (pkg.binding ||\n isAtLeastOneNonEmpty([\n projectParams,\n projectEnv,\n pkg.parameters,\n pkg.environment,\n pkg.annotations\n ]))\n ) {\n return wrapError(\n new Error(\n 'The default package does not support attaching environment, parameters, or binding'\n ),\n `package 'default'`\n );\n }\n if (pkg.name === 'default' || skipPkgDeploy || pkg.deployedDuringBuild) {\n return deployActionArray(pkg.actions, spec);\n }\n const pkgResponse = await onlyDeployPackage(pkg, spec);\n // Now deploy (or skip) the actions of the package\n const actionPromise = await deployActionArray(pkg.actions || [], spec);\n return combineResponses([actionPromise, pkgResponse]);\n}\n\n// Test whether any object in an array of objects is non-empty. Used here to check for illegal attachment of\n// parameters or environment to the 'default' package, which doesn't really exist.\nfunction isAtLeastOneNonEmpty(toCheck: object[]): boolean {\n for (const source of toCheck) {\n if (source && Object.keys(source).length > 0) {\n return true;\n }\n }\n return false;\n}\n\n// Deploy an action\nfunction deployAction(\n action: ActionSpec,\n spec: DeployStructure\n): Promise<DeployResponse> {\n const { owClient: wsk, feedback, reader } = spec;\n const context = `action '${getActionName(action)}'`;\n debug('deploying %s', context);\n if (action.buildError) {\n return Promise.resolve(wrapError(action.buildError, context));\n }\n if (action.buildResult) {\n return processRemoteResponse(action.buildResult, wsk, context, feedback);\n }\n if (action.code) {\n debug('action already has code');\n return deployActionFromCodeOrSequence(action, spec, action.code, undefined);\n }\n if (action.sequence) {\n const error = checkForLegalSequence(action);\n if (error) {\n return Promise.resolve(wrapError(error, context));\n }\n if (!spec.sequences) {\n spec.sequences = [];\n }\n spec.sequences.push(action);\n return Promise.resolve(emptyResponse());\n }\n const codeFile = action.file;\n if (codeFile) {\n debug('reading action code from %s', codeFile);\n return reader\n .readFileContents(codeFile)\n .then((data) => {\n const code = action.binary ? data.toString('base64') : String(data);\n return code;\n })\n .then((code: string) =>\n deployActionFromCodeOrSequence(action, spec, code, undefined)\n )\n .catch((err) => Promise.resolve(wrapError(err, context)));\n } else {\n return Promise.resolve(\n wrapError(\n new Error(\n 'Action is named in the config but does not exist in the project'\n ),\n context\n )\n );\n }\n}\n\n// The ActionSpec is known to include the sequence member but may still not be consistent\nfunction checkForLegalSequence(action: ActionSpec): any {\n if (action.file) {\n return new Error(\n 'An action cannot be a sequence and also exist in the project directory structure'\n );\n }\n if (action.runtime || action.binary || action.main) {\n return new Error(\n 'An action cannot be a sequence and also have the runtime, binary, or main attributes'\n );\n }\n return false;\n}\n\n// Order the sequences of this deployment so that ones that depend on others come later in the order.\n// Throw on cycle.\nfunction sortSequences(\n sequences: ActionSpec[],\n spec: DeployStructure\n): ActionSpec[] {\n const {\n credentials: { namespace }\n } = spec;\n const actionNames = getAllActionFqns(spec, namespace);\n const inProgress = new Set<string>();\n const completed = new Set<string>();\n const result: ActionSpec[] = [];\n for (const seq of sequences) {\n if (\n !addSequenceToList(\n seq,\n namespace,\n result,\n inProgress,\n completed,\n sequences,\n actionNames,\n spec.feedback\n )\n ) {\n // Cycle detected\n throw new Error('A cycle was detected in mutually dependent sequences');\n }\n }\n return result;\n}\n\n// Recursive subroutine of sortSequences to check and position an individual sequence so as to follow its dependencies.\n// To accomplish the goal, the dependencies are added first in the order found, and a \"completed\" set is used to prevent\n// duplicates.\nfunction addSequenceToList(\n seq: ActionSpec,\n namespace: string,\n result: ActionSpec[],\n inProgress: Set<string>,\n completed: Set<string>,\n sequences: ActionSpec[],\n actionNames: Set<string>,\n feedback: Feedback\n): boolean {\n const seqName = fqnFromActionSpec(seq, namespace);\n seqDebug('addSequenceToList %s', seqName);\n if (inProgress.has(seqName)) {\n seqDebug('found in inProgress');\n return false;\n }\n if (completed.has(seqName)) {\n seqDebug('found in completed');\n return true;\n }\n inProgress.add(seqName);\n const thisNsPrefix = '/' + namespace + '/';\n for (const member of seq.sequence) {\n const memberName = fqn(member, namespace);\n const preReq = sequences.find(\n (cand) => memberName === fqnFromActionSpec(cand, namespace)\n );\n if (preReq) {\n seqDebug('Found pre-requisite sequence %s', preReq.name);\n if (\n !addSequenceToList(\n preReq,\n namespace,\n result,\n inProgress,\n completed,\n sequences,\n actionNames,\n feedback\n )\n ) {\n return false;\n }\n }\n if (memberName.startsWith(thisNsPrefix) && !actionNames.has(memberName)) {\n feedback.warn(\n \"Sequence '%s' contains action '%s' which is in the same namespace but not part of the deployment\",\n seq.name,\n memberName\n );\n }\n }\n inProgress.delete(seqName);\n completed.add(seqName);\n seqDebug('adding %s to result', seqName);\n result.push(seq);\n return true;\n}\n\n// Deploy the sequences of the project, if any. These were identified while deploying the\n// actions. Sequence actions were lightly checked, then deferred. Here, we sort the sequences\n// so that dependent sequences are deployed before they are needed by other sequences.\n// If that works (no cycles) then we deploy the result.\nasync function deploySequences(\n todeploy: DeployStructure\n): Promise<DeployResponse[]> {\n try {\n todeploy.sequences = sortSequences(todeploy.sequences || [], todeploy);\n } catch (err) {\n return [wrapError(err, 'sequences')];\n }\n const result: DeployResponse[] = [];\n for (const seq of todeploy.sequences ?? []) {\n const components = seq.sequence.map((action) =>\n fqn(action, todeploy.credentials.namespace)\n );\n const exec: openwhisk.Sequence = { kind: 'sequence', components };\n result.push(\n await deployActionFromCodeOrSequence(seq, todeploy, undefined, exec)\n );\n }\n return result;\n}\n\n// Compute a fully qualified OW name from an ActionSpec plus a default namespace\nfunction fqnFromActionSpec(spec: ActionSpec, namespace: string): string {\n let name = spec.name;\n if (spec.package && spec.package !== 'default') {\n name = `${spec.package}/${name}`;\n }\n return `/${namespace}/${name}`;\n}\n\n// Get the fqns of all actions in the spec\nfunction getAllActionFqns(\n spec: DeployStructure,\n namespace: string\n): Set<string> {\n const ans = new Set<string>();\n for (const pkg of spec.packages ?? []) {\n if (pkg.actions) {\n pkg.actions.forEach((action) =>\n ans.add(fqnFromActionSpec(action, namespace))\n );\n }\n }\n return ans;\n}\n\n// Convert an OW resource name to fqn form (it may already be in that form)\nfunction fqn(name: string, namespace: string): string {\n if (name.startsWith('/')) {\n return name;\n }\n return `/${namespace}/${name}`;\n}\n\nfunction encodeParameters(\n normalParms: openwhisk.Dict,\n envParms: openwhisk.Dict\n): KeyVal[] {\n let ans: KeyVal[] = [];\n if (normalParms) {\n ans = keyVal(normalParms);\n }\n if (envParms) {\n const envs = keyVal(envParms);\n envs.forEach((env) => {\n env.init = true;\n });\n ans = ans.concat(envs);\n }\n return ans;\n}\n\n// Construct the Action.Exec struct from the deployment configuration values.\nexport function calculateActionExec(action: ActionSpec, code: string): Exec {\n const main = action.main ? action.main : undefined; // '' is falsey but won't be recognized as such by OW\n if (action.docker) {\n return {\n code,\n binary: action.binary,\n kind: 'blackbox',\n image: action.docker,\n main\n };\n }\n\n return { code, binary: action.binary, kind: action.runtime, main };\n}\n\n// Deploy an action when the code has already been read from a() file or constructed programmatically or when the\n// action is a sequence (Sequence passed in lieu of code).\nasync function deployActionFromCodeOrSequence(\n action: ActionSpec,\n spec: DeployStructure,\n code: string,\n sequence: openwhisk.Sequence\n): Promise<DeployResponse> {\n const name = getActionName(action);\n const { versions, flags, deployerAnnotation, owClient: wsk } = spec;\n const deployerAnnot = Object.assign({}, deployerAnnotation);\n\n debug('deploying %s using %s', name, !sequence ? 'code' : 'sequence info');\n if (code && !action.runtime) {\n return Promise.resolve(\n wrapError(\n new Error(\n `Action '${name}' not deployed: runtime type could not be determined`\n ),\n `action ${name}`\n )\n );\n }\n // Check whether the action needs to be deployed; if so, deploy it. If not, make a vacuous response with the existing package\n // VersionInfo. That is needed so that the new versions.json will have the information in it. We don't digest\n // or skip deployment for sequences.\n let digest: string;\n if (!sequence) {\n // test for absence of sequence, not presence of code; code may be the empty string\n digest = digestAction(action, code);\n debug('computed digest for %s', name);\n if (\n flags.incremental &&\n versions.actionVersions &&\n versions.actionVersions[name] &&\n digest === versions.actionVersions[name].digest\n ) {\n // Skipping deployment\n debug('matched digest for %s', name);\n const actionVersions = {};\n actionVersions[name] = versions.actionVersions[name];\n return Promise.resolve(\n wrapSuccess(name, 'action', true, actionVersions, undefined)\n );\n }\n // Record\n debug('recording digest for %s', name);\n deployerAnnot.digest = digest.substring(0, 8);\n }\n // Will be deployed\n // Compute the annotations that we will definitely be adding\n deployerAnnot.zipped = action.zipped;\n const annotations = Object.assign({}, action.annotations) || {};\n annotations.deployer = deployerAnnot;\n annotations.final = true;\n\n if (action.web === true) {\n annotations['web-export'] = true;\n annotations['raw-http'] = false;\n } else if (action.web === 'raw') {\n annotations['web-export'] = true;\n annotations['raw-http'] = true;\n } else if (!action.web) {\n annotations['web-export'] = false;\n annotations['raw-http'] = false;\n }\n if (typeof action.webSecure === 'string') {\n annotations['require-whisk-auth'] = action.webSecure;\n } else {\n // A value of true should already have been flagged at validation time.\n annotations['require-whisk-auth'] = false;\n }\n // Get the former annotations of the action if any\n const options = { name, code: false };\n const former = await wsk.actions.get(options).catch(() => undefined);\n const oldAnnots =\n former && former.annotations ? makeDict(former.annotations) : {};\n // Merge the annotations\n const annotDict = Object.assign({}, oldAnnots, annotations);\n // Compute the complete Action value for the call\n const params = encodeParameters(action.parameters, action.environment);\n const exec = sequence || calculateActionExec(action, code);\n const actionBody: openwhisk.Action = {\n annotations: keyVal(annotDict),\n parameters: params,\n exec: exec as Exec\n };\n if (action.limits) {\n actionBody.limits = action.limits;\n }\n const deployParams = { name, action: actionBody };\n try {\n const response = await wsk.actions.update(deployParams);\n\n let triggerResults: (DeploySuccess | Error)[] = [];\n if (action.triggers) {\n triggerResults = await deployTriggers(\n action.triggers,\n name,\n spec.credentials\n );\n }\n const map = {};\n if (digest) {\n map[name] = { version: response.version, digest };\n }\n const namespace = response.namespace.split('/')[0];\n const success = wrapSuccess(name, 'action', false, map, namespace);\n for (let i = 0; i < triggerResults.length; i++) {\n if (triggerResults[i] instanceof Error) {\n const err = triggerResults[i] as any;\n err.context = `while deploying trigger '${action.triggers[i].name}'`;\n success.failures.push(triggerResults[i] as Error);\n } else {\n success.successes.push(triggerResults[i] as DeploySuccess);\n }\n }\n return Promise.resolve(success);\n } catch (err) {\n // Note this is not the usual catch block for trigger deployment errors. Those are caught in\n // deployTriggers and fed back in the results. The function itself will not be backed out if triggers\n // fail to deploy. Rather, both statuses are reported (success for the function and possibly some\n // triggers, failure for those triggers that failed). We reach here if the function fails to deploy\n // or if system-level errors occurred in the logic somewhere.\n return Promise.resolve(wrapError(err, `action '${name}'`));\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport {\n DeployStructure,\n PackageSpec,\n ActionSpec,\n Includer,\n ProjectReader,\n PathKind,\n Feedback\n} from './deploy-struct';\nimport {\n emptyStructure,\n actionFileToParts,\n filterFiles,\n loadProjectConfig,\n errorStructure,\n getDeployerAnnotation,\n getBestProjectName\n} from './util';\nimport { getBuildForAction, getBuildForLib } from './finder-builder';\nimport makeDebug from 'debug';\nimport { makeFileReader } from './file-reader';\nimport { fetchSlice } from './slice-reader';\nconst debug = makeDebug('nim:deployer:project-reader');\n\nconst CONFIG_FILE = 'project.yml';\nconst LEGACY_CONFIG_FILE = 'projectConfig.yml';\nconst ENV_FILE = '.env';\n\n// Read the top level files and dirs of the project. Only one file and two dirs are legal at this level; everything else is a 'stray'\ninterface TopLevel {\n lib: string;\n packages: string;\n config?: string;\n env?: string;\n buildEnv?: string;\n strays: string[];\n filePath: string;\n includer: Includer;\n reader: ProjectReader;\n feedback: Feedback;\n noTriggers: boolean;\n}\nexport async function readTopLevel(\n filePath: string,\n env: string,\n buildEnv: string,\n includer: Includer,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<TopLevel> {\n debug(\"readTopLevel with filePath:'%s'\", filePath);\n debug('feedback is %O', feedback);\n // Before doing the more expensive operations, check existence of env, which is cheap. If does not exist we will fail later anyway.\n if (env && !fs.existsSync(env)) {\n throw new Error(`The specified environment file '${env}' does not exist`);\n }\n if (buildEnv && !fs.existsSync(buildEnv)) {\n throw new Error(\n `The specified environment file '${buildEnv}' does not exist`\n );\n }\n if (filePath.startsWith('slice:')) {\n debug('fetching slice');\n filePath = await fetchSlice(filePath.replace('slice:', ''));\n if (!filePath) {\n throw new Error('Could not fetch slice');\n }\n }\n const reader = makeFileReader(filePath);\n const pkgDir = 'packages';\n const libDir = 'lib';\n return reader.readdir('').then((items) => {\n items = filterFiles(items);\n let config: string;\n let notconfig: string;\n let legacyConfig: string;\n let packages: string;\n const strays: string[] = [];\n let lib: string;\n for (const item of items) {\n if (item.isDirectory) {\n switch (item.name) {\n case pkgDir:\n packages = pkgDir;\n break;\n case libDir:\n lib = libDir;\n break;\n case '.nimbella':\n case '.deployed':\n break;\n default:\n strays.push(item.name);\n }\n } else if (!item.isDirectory && item.name === CONFIG_FILE) {\n config = item.name;\n } else if (!item.isDirectory && item.name === LEGACY_CONFIG_FILE) {\n legacyConfig = item.name;\n } else if (\n !item.isDirectory &&\n (item.name.endsWith('.yml') || item.name.endsWith('.yaml'))\n ) {\n notconfig = item.name;\n } else if (!env && !item.isDirectory && item.name === ENV_FILE) {\n // Env file reading will not go through the reader so use a path that includes a path to the project\n env = path.join(filePath, item.name);\n } else {\n strays.push(item.name);\n }\n }\n if (legacyConfig && !config) {\n config = legacyConfig;\n feedback.warn(\n `Warning: the name '${LEGACY_CONFIG_FILE}' is deprecated; please rename to '${CONFIG_FILE}' soon`\n );\n }\n if (notconfig && !config) {\n feedback.warn('Warning: found %s but no %s', notconfig, CONFIG_FILE);\n }\n const ans = {\n lib,\n packages,\n config,\n strays,\n filePath,\n env,\n buildEnv,\n includer,\n reader,\n feedback,\n noTriggers\n };\n debug('readTopLevel returning %O', ans);\n return ans;\n });\n}\n\n// Probe the top level structure to obtain the major parts of the final config. Spawn builders for those parts and\n// assemble a \"Promise.all\" for the combined work\nexport async function buildStructureParts(\n topLevel: TopLevel\n): Promise<DeployStructure[]> {\n const {\n lib,\n packages,\n config,\n strays,\n filePath,\n env,\n buildEnv,\n includer,\n reader,\n feedback,\n noTriggers\n } = topLevel;\n let configPart = await readConfig(\n config,\n env,\n buildEnv,\n filePath,\n includer,\n reader,\n feedback,\n noTriggers\n );\n const deployerAnnotation =\n configPart.deployerAnnotation || (await getDeployerAnnotation(filePath));\n configPart = Object.assign(configPart, {\n strays,\n filePath,\n includer,\n reader,\n feedback,\n deployerAnnotation\n });\n const displayName = getBestProjectName(configPart);\n debug('display path for actions is %O', displayName);\n const actionsPart = await buildActionsPart(\n packages,\n displayName,\n includer,\n reader\n );\n configPart.libBuild = await getBuildForLib(lib, reader);\n return [actionsPart, configPart];\n}\n\n// Assemble a complete initial structure containing all file system information and config. May be deployed as is or adjusted\n// before deployment. Input is the resolved output of buildStructureParts.\nexport function assembleInitialStructure(\n parts: DeployStructure[]\n): DeployStructure {\n debug('Assembling structure from parts');\n const [actionsPart, configPart] = parts;\n const errPart = parts.find((part) => part.error);\n if (errPart) {\n return errPart;\n }\n const strays = (actionsPart.strays || []).concat(configPart.strays || []);\n configPart.strays = strays;\n configPart.packages =\n actionsPart.packages && configPart.packages\n ? mergePackages(actionsPart.packages, configPart.packages)\n : actionsPart.packages\n ? actionsPart.packages\n : configPart.packages\n ? configPart.packages\n : [];\n adjustWebExportFlags(configPart.packages);\n debug('Result of assembly: %O', configPart);\n return configPart;\n}\n\n// Merge 'packages' portion of config, if any, into the 'packages' array read from the file system.\n// The merge key is the package name.\nfunction mergePackages(\n fs: PackageSpec[],\n config: PackageSpec[]\n): PackageSpec[] {\n const merge = {};\n fs.forEach((pkg) => {\n merge[pkg.name] = pkg;\n });\n config.forEach((pkg) => {\n const already = merge[pkg.name];\n if (already) {\n merge[pkg.name] = mergePackage(already, pkg);\n } else {\n (pkg.actions || []).forEach((action) => {\n action.package = pkg.name;\n });\n merge[pkg.name] = pkg;\n }\n });\n const ans: PackageSpec[] = [];\n for (const name in merge) {\n ans.push(merge[name]);\n }\n return ans;\n}\n\n// Merge a single PackageSpec: the file system and config contributions have the same name. The actions are merged.\n// Other attributes are preferentially taken from the config.\nfunction mergePackage(fs: PackageSpec, config: PackageSpec): PackageSpec {\n const fsActions = fs.actions;\n const cfgActions = config.actions;\n const ans = Object.assign({}, fs, config);\n if (fsActions && fsActions.length > 0) {\n if (cfgActions && cfgActions.length > 0) {\n ans.actions = mergeActions(fsActions, cfgActions, config.name);\n } else {\n ans.actions = fsActions;\n }\n } else {\n ans.actions = cfgActions;\n }\n return ans;\n}\n\n// Adjust the web export value for the actions of the project. For each action that already has this property set, leave it alone.\n// Otherwise, if its package specifies a web export value use it. Otherwise, apply the default of 'true'. Must test explicitly\n// for 'undefined' type since false is a real value but is falsey.\nfunction adjustWebExportFlags(pkgs: PackageSpec[]) {\n pkgs.forEach((pkg) => {\n if (pkg.actions) {\n pkg.actions.forEach((action) => {\n if (typeof action.web === 'undefined') {\n action.web = typeof pkg.web === 'undefined' ? true : pkg.web;\n }\n });\n }\n });\n}\n\n// Merge the actions portion of a PackageSpec in config, if any, into the corresponding PackageSpec actions read from the file system.\n// The merge key is the action name.\nfunction mergeActions(\n fs: ActionSpec[],\n config: ActionSpec[],\n pkgName: string\n): ActionSpec[] {\n const merge = {};\n fs.forEach((action) => {\n merge[action.name] = action;\n });\n config.forEach((action) => {\n const already = merge[action.name];\n if (already) {\n merge[action.name] = mergeAction(already, action);\n } else {\n action.package = pkgName;\n merge[action.name] = action;\n }\n });\n const ans: ActionSpec[] = [];\n for (const name in merge) {\n ans.push(merge[name]);\n }\n return ans;\n}\n\n// Merge a single ActionSpec: the file system and config contributions have the same name. The config contributions\n// take precedence\nfunction mergeAction(fs: ActionSpec, config: ActionSpec): ActionSpec {\n debug('Action from filesystem: %O', fs);\n debug('Action from config: %O', config);\n const result = Object.assign({}, fs, config);\n debug('Result of merge: %O', result);\n return result;\n}\n\n// Probe the packages directory\nfunction buildActionsPart(\n pkgsdir: string,\n displayPath: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<DeployStructure> {\n if (!pkgsdir) {\n return Promise.resolve(emptyStructure());\n } else {\n return buildPkgArray(\n pkgsdir,\n displayPath + '/packages',\n includer,\n reader\n ).then((values) => {\n const [strays, pkgs] = values;\n return { packages: pkgs, strays: strays };\n });\n }\n}\n\n// Accumulate the arrays of PackageSpecs and Strays in the 'packages' directory\nfunction buildPkgArray(\n pkgsDir: string,\n displayPath: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<any> {\n debug('Building package array');\n return reader.readdir(pkgsDir).then((items: PathKind[]) => {\n items = filterFiles(items);\n const strays = items\n .filter((dirent) => !dirent.isDirectory)\n .map((dirent) => dirent.name);\n const pkgNames = items\n .filter((dirent) => dirent.isDirectory)\n .map((dirent) => dirent.name);\n const rdrs: Promise<PackageSpec>[] = [];\n for (const name of pkgNames) {\n if (includer.isPackageIncluded(name, false)) {\n const pkgPath = path.join(pkgsDir, name);\n rdrs.push(\n readPackage(\n pkgPath,\n path.join(displayPath, name),\n name,\n includer,\n reader\n )\n );\n }\n }\n return Promise.all([Promise.resolve(strays), Promise.all(rdrs)]);\n });\n}\n\n// Read the contents of a directory defining a package. By convention, actions not requiring a build step are stored directly in the\n// package directory. Those requiring a build are stored in a subdirectory. The name of each action is the single file name (sans suffix)\n// or the name of the subdirectory.\nasync function readPackage(\n pkgPath: string,\n displayPath: string,\n pkgName: string,\n includer: Includer,\n reader: ProjectReader\n): Promise<PackageSpec> {\n debug(\n \"reading information for package '%s' with display path '%s'\",\n pkgPath,\n displayPath\n );\n return reader\n .readdir(pkgPath)\n .then(async (items: PathKind[]) => {\n items = filterFiles(items);\n const promises: Promise<ActionSpec>[] = [];\n const seen = new Map<string, string>();\n for (const item of items) {\n const file = path.join(pkgPath, item.name);\n const displayFile = path.join(displayPath, item.name);\n debug('item %s has display path %s', item.name, displayFile);\n if (!item.isDirectory) {\n // Directly deployable action not requiring a build.\n const { name, runtime, binary, zipped } = await actionFileToParts(\n item.name\n );\n if (!includer.isActionIncluded(pkgName, name)) continue;\n const before = seen.get(name);\n if (before) {\n throw duplicateName(name, before, runtime);\n }\n seen.set(name, runtime);\n promises.push(\n Promise.resolve({\n name,\n file,\n displayFile,\n runtime,\n binary,\n zipped,\n package: pkgName\n })\n );\n } else if (item.isDirectory) {\n // Build-dependent action or renamed action\n if (!includer.isActionIncluded(pkgName, item.name)) continue;\n const before = seen.get(item.name);\n if (before) {\n throw duplicateName(item.name, before, '*');\n }\n seen.set(item.name, '*');\n promises.push(\n getBuildForAction(file, reader).then((build) => {\n return {\n name: item.name,\n file,\n displayFile,\n build,\n package: pkgName\n };\n })\n );\n }\n }\n return Promise.all(promises);\n })\n .then((actions: ActionSpec[]) => {\n return { name: pkgName, actions: actions, shared: false };\n });\n}\n\n// Build an error indicating o duplicate action name. This can happen if, e.g. you have both eval.js and eval.swift\n// or if you have eval.js and an action directory called eval.\nfunction duplicateName(actionName: string, formerUse: string, newUse: string) {\n const former =\n formerUse === '*' ? 'as a directory' : `with runtime '${formerUse}'`;\n const present =\n newUse === '*' ? 'as a directory' : `with runtime '${newUse}'`;\n return new Error(\n `The action name '${actionName}' appears twice, once ${former} and once ${present}`\n );\n}\n\n// Read the config file if present. For convenience, the extra information not merged from elsewhere is tacked on here\nasync function readConfig(\n configFile: string,\n envPath: string,\n buildEnvPath: string,\n filePath: string,\n includer: Includer,\n reader: ProjectReader,\n feedback: Feedback,\n noTriggers: boolean\n): Promise<DeployStructure> {\n if (!configFile) {\n debug('No config file found');\n const ans = Object.assign({}, emptyStructure());\n return Promise.resolve(ans);\n }\n debug('Reading config file');\n const config = loadProjectConfig(\n configFile,\n envPath,\n buildEnvPath,\n filePath,\n reader,\n feedback,\n noTriggers\n )\n .then((config) => trimConfigWithIncluder(config, includer))\n .catch((err) => errorStructure(err));\n debug('Config contents: %O', config);\n return config;\n}\n\n// Given a DeployStructure with a package section, trim that section according to the rules of an Includer\nfunction trimConfigWithIncluder(\n config: DeployStructure,\n includer: Includer\n): DeployStructure {\n if (config.packages) {\n const newPkgs: PackageSpec[] = [];\n for (const pkg of config.packages) {\n if (includer.isPackageIncluded(pkg.name, false)) {\n if (pkg.actions) {\n pkg.actions = pkg.actions.filter((action) =>\n includer.isActionIncluded(pkg.name, action.name)\n );\n }\n newPkgs.push(pkg);\n }\n }\n config.packages = newPkgs;\n }\n return config;\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { spawn } from 'child_process';\nimport {\n DeployStructure,\n ActionSpec,\n PackageSpec,\n Flags,\n ProjectReader,\n PathKind,\n Feedback\n} from './deploy-struct';\nimport {\n actionFileToParts,\n filterFiles,\n mapPackages,\n mapActions,\n promiseFilesAndFilterFiles,\n agreeOnRuntime,\n getBestProjectName,\n getExclusionList,\n waitForActivation,\n getActionName,\n encryptProjectConfig\n} from './util';\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport * as yaml from 'js-yaml';\nimport ignore from 'ignore';\nimport axios from 'axios';\nimport archiver from 'archiver';\nimport touch from 'touch';\nimport makeDebug from 'debug';\nimport { Writable } from 'stream';\nimport * as memoryStreams from 'memory-streams';\nimport openwhisk = require('openwhisk');\nimport { canonicalRuntime } from './runtimes';\nimport { onlyDeployPackage } from './deploy';\nimport { MAX_SLICE_UPLOAD_SIZE } from './slice-reader';\n\nconst debug = makeDebug('nim:deployer:finder-builder');\nconst zipDebug = makeDebug('nim:deployer:zip');\n\n// Type to use with the ignore package.\ninterface Ignore {\n filter: (arg: string[]) => string[];\n}\n\nconst ZIP_TARGET = '__deployer__.zip';\nexport const BUILDER_NAMESPACE =\n process.env['TEST_BUILDER_NAMESPACE'] || 'nimbella';\nconst BUILDER_ACTION_STEM = `/${BUILDER_NAMESPACE}/builder/build_`;\nconst GET_UPLOAD_URL = `/${BUILDER_NAMESPACE}/builder/getUploadUrl`;\nconst CANNED_REMOTE_BUILD = `#!/bin/bash\nset -e\n/bin/defaultBuild %MAIN%\n`;\n\n// Determine the build type for an action that is defined as a directory\nexport function getBuildForAction(\n filepath: string,\n reader: ProjectReader\n): Promise<string> {\n return readDirectory(filepath, reader).then((items) =>\n findSpecialFile(items, filepath, true)\n );\n}\n\n// Build all the actions in an array of PackageSpecs, returning a new array of PackageSpecs. We try to return\n// undefined for the case where no building occurred at all, since we are obligated to return a full array if\n// any building occurred, even if most things weren't subject to building.\nexport async function buildAllActions(\n spec: DeployStructure\n): Promise<PackageSpec[]> {\n const packages = spec.packages;\n if (!packages || packages.length === 0) {\n return undefined;\n }\n // If there are any packages, we are going to have to search through them but if none of them build anything we can punt\n const pkgMap = mapPackages(packages);\n const promises: Promise<PackageSpec>[] = [];\n for (const pkg of packages) {\n if ((pkg.actions && pkg.actions.length > 0) || pkg.binding) {\n const builtPackage = buildActionsOfPackage(pkg, spec);\n promises.push(builtPackage);\n }\n }\n if (promises.length === 0) {\n return undefined;\n }\n return Promise.all(promises).then((newpkgs: PackageSpec[]) => {\n for (const pkg of newpkgs) {\n if (pkg) {\n pkgMap[pkg.name] = pkg;\n }\n }\n return Object.values(pkgMap);\n });\n}\n\n// Build the actions of a package, returning an updated PackageSpec or undefined if nothing got built\nasync function buildActionsOfPackage(\n pkg: PackageSpec,\n spec: DeployStructure\n): Promise<PackageSpec> {\n // Determine if any remote builds exist in this package. If so, we have to deploy the package before doing the builds.\n const mustDeployPackage =\n pkg.name !== 'default' &&\n pkg.actions?.some(\n (action) => action.build === 'remote' || action.build === 'remote-default'\n );\n if (mustDeployPackage) {\n const pkgResult = await onlyDeployPackage(pkg, spec);\n if (pkgResult.failures.length > 0) {\n throw pkgResult.failures[0];\n }\n pkg.deployedDuringBuild = true;\n spec.deployerAnnotation.newSliceHandling = true;\n }\n // Now run all the builds in this package\n const actionMap = mapActions(pkg.actions);\n let nobuilds = true;\n for (const action of pkg.actions || []) {\n if (action.build) {\n nobuilds = false;\n const builtAction = await buildAction(action, spec).catch((err) => {\n action.buildError = err;\n return action;\n });\n actionMap[action.name] = builtAction;\n }\n }\n if (nobuilds) {\n return undefined;\n }\n pkg.actions = Object.values(actionMap);\n return pkg;\n}\n\n// Perform the build defined for an action or just return the action if there is no build step\nfunction buildAction(\n action: ActionSpec,\n spec: DeployStructure\n): Promise<ActionSpec> {\n if (!action.build) {\n return Promise.resolve(action);\n }\n debug('building action %O', action);\n let actionDir: string;\n const { reader, flags, feedback, slice, buildEnv } = spec;\n switch (action.build) {\n case 'build.sh':\n actionDir = makeLocal(reader, action.file);\n return scriptBuilder(\n './build.sh',\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case 'build.cmd':\n actionDir = makeLocal(reader, action.file);\n return scriptBuilder(\n 'build.cmd',\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case 'package.json':\n actionDir = makeLocal(reader, action.file);\n return npmBuilder(\n actionDir,\n action.displayFile,\n flags,\n buildEnv,\n slice,\n feedback\n ).then(() =>\n identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n )\n );\n case '.include':\n case 'identify':\n return identifyActionFiles(\n action,\n flags.incremental,\n flags.verboseZip,\n reader,\n feedback\n );\n case 'remote':\n case 'remote-default':\n checkBuiltLocally(reader, action.file);\n return doRemoteActionBuild(action, spec);\n default:\n throw new Error('Unknown build type in ActionSpec: ' + action.build);\n }\n}\n\n// Process .include file by reading it, recognize any .. or absolute path references, expanding directories, and filtering the result.\n// Absolute path references are illegal. References to ../../../lib/* are allowed, otherwise, references outside the build directory\n// are illegal.\n// Returns a list of pairs. In each pair, the first member is the path of a file to be included. The second member is its name the file\n// should assume once included. Except for ../../../lib/* cases, these will be the same. In the latter case, the dirname portion of the\n// path is elided inside the zip file.\nasync function processInclude(\n includesPath: string,\n dirPath: string,\n reader: ProjectReader\n): Promise<string[][]> {\n debug(\"processing includes from '%s'\", includesPath);\n const items = await readFileAsList(includesPath, reader);\n const errMsg = checkIncludeItems(items);\n if (errMsg) {\n return Promise.reject(new Error(errMsg));\n }\n return processIncludeFileItems(items, dirPath, reader);\n}\n\n// Used instead of path.resolve to deal with possible '..' directives. We don't want absolute path names\n// as a result, nor do we want the current directory to be consulted, just path concatenation and normalization.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction joinAndNormalize(...paths: string[]): string {\n return path.normalize(path.join(...paths));\n}\n\n// Convert a path that is relative to the project root into a path usable with 'fs'. This should be done only for things\n// that require real building since it will abort the deploy when the project root cannot be found in the file system.\nfunction makeLocal(reader: ProjectReader, ...paths: string[]): string {\n const project = reader.getFSLocation();\n if (!project) {\n throw new Error('invalid call to makeLocal');\n }\n return path.resolve(project, ...paths);\n}\n\n// Subroutine of processInclude to run after items are read\nasync function processIncludeFileItems(\n items: string[],\n dirPath: string,\n reader: ProjectReader\n): Promise<string[][]> {\n const complex: Promise<string[][]>[] = [];\n const simple: string[][] = [];\n for (let item of items) {\n debug('processing include item %s', item);\n if (item.startsWith('./') || item.startsWith('.\\\\')) {\n item = item.slice(2);\n }\n let oldPath = path.join(dirPath, item);\n if (oldPath.endsWith('/') || oldPath.endsWith('\\\\')) {\n oldPath = oldPath.slice(0, -1);\n }\n debug(\"Calculated oldPath '%s'\", oldPath);\n const lstat: PathKind = await reader.getPathKind(oldPath);\n if (!lstat) {\n return Promise.reject(\n new Error(`${oldPath} is included for '${dirPath}' but does not exist`)\n );\n }\n let newPath: string;\n if (item.includes('..')) {\n // Already screened for legality\n newPath = path.basename(item);\n } else {\n newPath = item;\n }\n const toElide = oldPath.length - newPath.length;\n debug(\"Calculated newPath '%s' with elision %d\", newPath, toElide);\n if (lstat.isFile) {\n simple.push([oldPath, newPath]);\n } else if (lstat.isDirectory) {\n const expanded = promiseFilesAndFilterFiles(oldPath, reader).then(\n (items) => items.map((item) => [item, item.slice(toElide)])\n );\n debug(\"Expanded directory '%s'\", oldPath);\n complex.push(expanded);\n } else {\n return Promise.reject(\n new Error(`'${item}' is neither a file nor a directory`)\n );\n }\n }\n return Promise.all(complex.concat(Promise.resolve(simple))).then((arrays) =>\n arrays.reduce((prev, curr) => prev.concat(curr), [])\n );\n}\n\n// Identify the files that make up an action directory, based on the files in the directory and .include. .source, or .ignore if present.\n// If there is more than one file, perform autozipping.\nasync function identifyActionFiles(\n action: ActionSpec,\n incremental: boolean,\n verboseZip: boolean,\n reader: ProjectReader,\n feedback: Feedback\n): Promise<ActionSpec> {\n let includesPath = path.join(action.file, '.include');\n if (!(await reader.isExistingFile(includesPath))) {\n // Backward compatibility: try .source also\n includesPath = path.join(action.file, '.source');\n }\n if (await reader.isExistingFile(includesPath)) {\n // If there is .include or .source, it is canonical and all else is ignored\n return processInclude(includesPath, action.file, reader).then((pairs) => {\n if (pairs.length === 0) {\n return Promise.reject(new Error(includesPath + ' is empty'));\n } else if (pairs.length > 1) {\n return autozipBuilder(\n pairs,\n action,\n incremental,\n verboseZip,\n reader,\n feedback\n );\n } else {\n return singleFileBuilder(action, pairs[0][0]);\n }\n });\n }\n return getIgnores(action.file, reader).then((ignore) => {\n return promiseFilesAndFilterFiles(action.file, reader).then(\n (items: string[]) => {\n items = applyIgnores(action.file, items, ignore);\n if (items.length === 0) {\n return Promise.reject(\n new Error(`Action '${getActionName(action)}' has no included files`)\n );\n } else if (items.length === 1) {\n return singleFileBuilder(action, items[0]);\n } else {\n const pairs = items.map((item) => {\n const shortName = item.substring(action.file.length + 1);\n return [item, shortName];\n });\n return autozipBuilder(\n pairs,\n action,\n incremental,\n verboseZip,\n reader,\n feedback\n );\n }\n }\n );\n });\n}\n\n// Utility for applying the ignore filter. Sensitive to the limitations of the 'ignore' npm package.\nfunction applyIgnores(basePath: string, items: string[], ignore: Ignore) {\n // If the basepath is already absolute, relativize in hopes that that all paths will be internal.\n // TODO this is not a panacea: we need to pin down our assumptions about how ignore is supposed to work.\n const absolute = path.isAbsolute(basePath);\n if (absolute) {\n items = items.map((item) => path.relative(basePath, item));\n }\n // Do the filtering\n items = ignore.filter(items);\n // Restore absolute paths\n if (absolute) {\n items = items.map((item) => path.join(basePath, item));\n }\n return items;\n}\n\n// Utility for reading .include, .source, or .build\nfunction readFileAsList(\n file: string,\n reader: ProjectReader\n): Promise<string[]> {\n return reader.readFileContents(file).then((data) =>\n String(data)\n .split('\\n')\n .filter((line) => line && line.trim().length > 0)\n .map((line) => line.trim())\n );\n}\n\n// Determine the build step for the lib directory or return undefined if there isn't one\nexport function getBuildForLib(\n filepath: string,\n reader: ProjectReader\n): Promise<string> {\n if (!filepath) {\n return Promise.resolve(undefined);\n }\n return readDirectory(filepath, reader).then((items) =>\n findSpecialFile(items, filepath, false)\n );\n}\n\n// Build the lib directory only if appropriate. It is appropriate to build it\n// if (1) we are deploying a slice (\"already running remotely\") or (2) there is\n// some action that will be deployed locally. In other words,\n// we do _not_ build lib in the case where this deployment is running locally but\n// everything will in fact be deployed remotely.\nexport async function maybeBuildLib(spec: DeployStructure): Promise<void> {\n function isRemote(build: string): boolean {\n return build === 'remote' || build === 'remote-default';\n }\n let shouldBuild = spec.slice;\n if (!shouldBuild && spec.packages) {\n pkgLoop: for (const pkg of spec.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n shouldBuild = action.build && !isRemote(action.build);\n if (shouldBuild) {\n break pkgLoop;\n }\n }\n }\n }\n }\n if (shouldBuild) {\n let scriptPath: string;\n const displayPath = path.join(getBestProjectName(spec), 'lib');\n const { reader, flags, feedback, slice, buildEnv } = spec;\n switch (spec.libBuild) {\n case 'build.sh':\n scriptPath = makeLocal(reader, 'lib');\n return scriptBuilder(\n './build.sh',\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n case 'build.cmd':\n scriptPath = makeLocal(reader, 'lib');\n return scriptBuilder(\n 'build.cmd',\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n case 'package.json':\n scriptPath = makeLocal(reader, 'lib');\n return npmBuilder(\n scriptPath,\n displayPath,\n flags,\n buildEnv,\n slice,\n feedback\n );\n default:\n throw new Error(\n 'Unknown or inappropriate build type for lib directory: ' +\n spec.libBuild\n );\n }\n }\n}\n\n// Check whether path seems to denote a directory that is already built (heuristic). Throws if case detected\nfunction checkBuiltLocally(reader: ProjectReader, localPath: string) {\n const loc = reader.getFSLocation();\n if (!loc) {\n debug(\n 'checkBuiltLocally skipped because project reader does not use local file system'\n );\n return;\n }\n const filepath = path.join(loc, localPath);\n debug(\n 'checking for local build artifacts in %s when remote build requested',\n filepath\n );\n if (fs.existsSync(filepath) && fs.lstatSync(filepath).isDirectory()) {\n debug('%s exists and is a directory', filepath);\n const zipped = path.join(filepath, ZIP_TARGET);\n const dotBuilt = path.join(filepath, '.built');\n if (fs.existsSync(zipped) || fs.existsSync(dotBuilt)) {\n throw new Error(\n `Remote build is requested for '${filepath}' but it appears to have been built locally. Remove derived artifacts first.`\n );\n }\n debug('did not find %s or %s', zipped, dotBuilt);\n }\n debug('checkBuiltLocally passed');\n}\n\n// Check that all include file items resolve to \"legal\" places (inside the directory being built or a 'lib' directory at project root)\n// Returns an error message if an illegal item is found, else the empty string.\nexport function checkIncludeItems(items: string[]): string {\n const legalDots = '../../../lib';\n for (const item of items) {\n if (!item || item.length === 0) {\n continue;\n }\n if (path.isAbsolute(item)) {\n return `Absolute paths are prohibited in an '.include' file`;\n }\n if (item.includes('..') && !item.startsWith(legalDots)) {\n return `Illegal use of '..' in an '.include' file`;\n }\n }\n return '';\n}\n\n// Check the .include file, if any, for illegal inclusions. This permits\n// a \"fail-fast\" for remote builds that are going to fail anyway.\nasync function checkRemoteBuildPreReqs(\n filepath: string,\n project: DeployStructure\n) {\n debug(`checking remote build pre-reqs for '${filepath}'`);\n const reader = project.reader;\n if ((await reader.getPathKind(filepath)).isDirectory) {\n const include = path.join(filepath, '.include');\n if (await reader.isExistingFile(include)) {\n debug(`found an .include file for '${filepath}'`);\n const items = await readFileAsList(include, reader);\n debug(`read ${items.length} .include items for '${filepath}'`);\n const msg = checkIncludeItems(items);\n if (msg) {\n throw new Error(msg);\n }\n }\n }\n}\n\n// Initiate request to builder for building an action\nasync function doRemoteActionBuild(\n action: ActionSpec,\n project: DeployStructure\n): Promise<ActionSpec> {\n // Check that a remote build is supportable\n await checkRemoteBuildPreReqs(action.file, project);\n // Get the zipper\n const { zip, output, outputPromise } = makeProjectSliceZip(action.file);\n // Get the project slice in convenient form\n const pkgName = path.basename(path.dirname(action.file));\n const actionName =\n pkgName === 'default' ? action.name : path.join(pkgName, action.name);\n // Zip the actionPath, also determining runtime if the action spec doesn't already have one\n debug('zipping action path %s for project slice', action.file);\n const generateRemote = defaultRemote(action);\n const runtime = await appendToZip(\n zip,\n action.file,\n project.reader,\n generateRemote\n );\n if (!action.runtime) {\n if (!runtime) {\n throw new Error(\n `Could not determine runtime for remote build of '${actionName}'. You may need to specify it in 'project.yml'`\n );\n }\n debug('Setting runtime to %s for remote build', runtime);\n action.runtime = runtime;\n }\n // Add 'lib' if it is present\n if (project.libBuild) {\n await appendLibToZip(zip, 'lib', project.reader);\n }\n // Add the project.yml\n const spec = makeConfigFromActionSpec(action, project, pkgName);\n debug('converting slice spec to YAML: %O', spec);\n\n // Encrypts the configuration file yaml file before uploading it.\n const { config, key } = encryptProjectConfig(yaml.safeDump(spec));\n\n zip.append(config, { name: 'project.yml' });\n debug('finalizing zip for project slice');\n zip.finalize();\n debug('zip finalized for project slice of action %s', getActionName(action));\n await outputPromise;\n debug(\n 'outputPromise settled for project slice of action %s',\n getActionName(action)\n );\n const toSend = (output as memoryStreams.WritableStream).toBuffer();\n debug(\n 'sending the remote build request for project %s and action %s',\n project.filePath,\n actionName\n );\n action.buildResult = await invokeRemoteBuilder(\n toSend,\n project.owClient,\n project.feedback,\n action,\n key\n );\n return action;\n}\n\n// Information about a default remote build\ninterface DefaultRemoteBuildInfo {\n contents: string; // The contents of the generated build.sh\n actionName: string; // the name of the action, used to generate intra-slice paths\n}\n\n// Generate DefaultRemoteBuildInfo from ActionSpec iff appropriate, else undefined\nfunction defaultRemote(action: ActionSpec): DefaultRemoteBuildInfo {\n if (action.build && action.build === 'remote-default') {\n const main = action.main || 'Main';\n const contents = CANNED_REMOTE_BUILD.replace('%MAIN%', main);\n const actionName = action.name;\n return { contents, actionName };\n }\n return undefined;\n}\n\n// Zip a file or directory for a remote build slice. Also attempts to determine a runtime.\n// If the generateBuild argument\n// is defined, it provides the action directory name and indicates that we should add a two-line `build.sh`.\n// This may require changing the single-file case to a multi-file case.\nasync function appendToZip(\n zip: archiver.Archiver,\n actionPath: string,\n reader: ProjectReader,\n generateBuild: DefaultRemoteBuildInfo | undefined\n): Promise<string> {\n const kind = await reader.getPathKind(actionPath);\n let analyzeForRuntime: string[];\n if (kind.isFile) {\n if (generateBuild) {\n // Change to multi-file case, although there is still only one source file\n const parent = path.dirname(actionPath);\n const simpleFile = path.basename(actionPath);\n const name = path.join(parent, generateBuild.actionName, simpleFile);\n const contents = await reader.readFileContents(actionPath);\n zip.append(contents, { name, mode: 0o666 });\n const buildFile = path.join(parent, generateBuild.actionName, 'build.sh');\n zip.append(generateBuild.contents, { name: buildFile, mode: 0o777 });\n } else {\n await appendAndCheck(zip, actionPath, actionPath, reader);\n }\n analyzeForRuntime = [actionPath];\n } else if (kind.isDirectory) {\n zipDebug('getting contents of directory %s for remote build slice', path);\n const files = await promiseFilesAndFilterFiles(actionPath, reader);\n analyzeForRuntime = files;\n for (const file of files) {\n await appendAndCheck(zip, file, actionPath, reader);\n }\n if (generateBuild) {\n const buildFile = path.join(actionPath, 'build.sh');\n zip.append(generateBuild.contents, { name: buildFile, mode: 0o777 });\n }\n }\n return agreeOnRuntime(analyzeForRuntime);\n}\n\n// A simplified version of appendToZip for adding secondary directories (currently 'lib') to the slice\nasync function appendLibToZip(\n zip: archiver.Archiver,\n path: string,\n reader: ProjectReader\n) {\n zipDebug('getting contents of directory %s for remote build slice', path);\n const files = await promiseFilesAndFilterFiles(path, reader);\n for (const file of files) {\n await appendAndCheck(zip, file, path, reader);\n }\n}\n\n// Append a path known to be a file to the in-memory zip, checking for excessive size and issuing debug if requested.\nasync function appendAndCheck(\n zip: archiver.Archiver,\n file: string,\n actionPath: string,\n reader: ProjectReader\n) {\n const contents = await reader.readFileContents(file);\n let mode: number;\n if (file.endsWith('.sh') && process.platform === 'win32') {\n // This is a weak heuristic to be around the fact that there is no executable bit on windows,\n // which can cause remote builds with shell scripts to fail. It might still be necessary for\n // a windows user to understand the issue and fix up permissions on things that don't end in .sh but\n // that really are scripts (this can be done in the primary script build.sh).\n mode = 0o777;\n } else {\n mode = (await reader.getPathKind(file)).mode;\n }\n debug(`mode for ${file} is ${mode}`);\n zip.append(contents, { name: file, mode });\n zipDebug(\"zipped '%s' for remote build slice\", file);\n}\n\n// Slice the project to contain only one ActionSpec; return a DeployStructure that can be written\n// out as a project.yml and also the path to the action file or directory, for zipping.\nfunction makeConfigFromActionSpec(\n action: ActionSpec,\n spec: DeployStructure,\n pkgName: string\n): DeployStructure {\n debug('converting action spec to sliced project.yml: %O', action);\n const {\n targetNamespace,\n parameters,\n environment: globalEnv,\n credentials,\n flags,\n deployerAnnotation,\n buildEnv\n } = spec;\n flags.remoteBuild = false;\n flags.buildEnv = undefined;\n const {\n name,\n runtime,\n main,\n binary,\n zipped,\n web,\n webSecure,\n annotations,\n environment,\n limits\n } = action;\n const newSpec = {\n targetNamespace,\n parameters,\n environment: globalEnv,\n credentials,\n flags,\n deployerAnnotation,\n buildEnv,\n slice: true\n } as DeployStructure;\n const newAction = {\n name,\n runtime,\n main,\n binary,\n zipped,\n web,\n webSecure,\n annotations,\n parameters: action.parameters,\n environment,\n limits\n } as ActionSpec;\n removeUndefined(newSpec);\n removeUndefined(newAction);\n const pkg = Object.assign(\n {},\n spec.packages.find((pkg) => pkg.name === pkgName)\n );\n pkg.actions = [newAction];\n pkg.deployedDuringBuild = false;\n newSpec.packages = [pkg];\n return newSpec;\n}\n\n// Remove undefined fields from object (mutates object but returns it as well)\nfunction removeUndefined(obj: Record<string, any>): Record<string, any> {\n for (const item in obj) {\n if (typeof obj[item] === 'undefined') {\n delete obj[item];\n } else if (typeof obj[item] === 'object') {\n obj[item] = removeUndefined(obj[item]);\n }\n }\n return obj;\n}\n\n// Create an in-memory zip for storing a project slice. Note: code here duplicates code in autozipBuilder. Refactoring\n// to avoid duplication might be delicate and is deferred for now.\ninterface ProjectSliceZip {\n output: Writable;\n zip: archiver.Archiver;\n outputPromise: Promise<any>;\n}\nfunction makeProjectSliceZip(context: string): ProjectSliceZip {\n const output: Writable = new memoryStreams.WritableStream({\n highWaterMark: MAX_SLICE_UPLOAD_SIZE\n });\n const zip = archiver('zip');\n const outputPromise = new Promise(function (resolve, reject) {\n zip.on('error', (err) => {\n debug('zip error occurred: %O', err);\n reject(err);\n });\n output.on('close', () => {\n debug('zipfile successfully closed');\n resolve(undefined);\n });\n output.on('finish', () => {\n debug('zipfile successfully finished');\n resolve(undefined);\n });\n output.on('end', () => {\n debug('zipfile data has been drained');\n });\n output.on('drain', () => {\n debug('memory stream posted a drain event');\n reject(\n new Error(\n `Remote build upload for '${context}' is too large. Make sure the directory is free of derived artifacts`\n )\n );\n });\n zip.on('warning', (err) => {\n debug('warning issued from archiver %O', err);\n if (err.code !== 'ENOENT') {\n reject(err);\n }\n });\n });\n zip.pipe(output);\n return { output, zip, outputPromise };\n}\n\n// Generate a remote build name for the \"legacy\" path\nconst BUCKET_BUILDER_PREFIX = '.nimbella/builds';\nexport function getRemoteBuildName(): string {\n const buildName = new Date().toISOString().replace(/:/g, '-');\n return `${BUCKET_BUILDER_PREFIX}/${buildName}`;\n}\n\n// Computes the tag to be added to a remote build slice name. Should be a function of the\n// qualified action name (pkg/action) but with / replaced by _.\nfunction computeTag(action: ActionSpec): string {\n if (action.package) {\n return `${action.package}_${action.name}`;\n }\n return action.name;\n}\n\n// Expected return value from getUploadUrl\ninterface UploadInfo {\n url: string;\n sliceName: string;\n}\n\n// This function simulates a blocking invoke of the builder/getUploadUrl action without actually\n// blocking at the controller. It does a non-blocking invoke, then polls the returned activation Id.\n// Note: errors thrown by the original invoke or during polling will not be caught here. They are intended\n// to be caught in buildProject, which will handle them appropriately.\nasync function getUploadUrl(\n owClient: openwhisk.Client,\n params: { action: string },\n feedback: Feedback\n): Promise<UploadInfo> {\n const invoked = await owClient.actions.invoke({\n name: GET_UPLOAD_URL,\n params\n });\n const tick = () =>\n feedback.progress(\n `Waiting for permission to upload remote build for '${params.action}'`\n );\n const activation = await waitForActivation(\n invoked.activationId,\n owClient,\n tick,\n 2 * 60\n );\n if (!activation) {\n throw new Error(\n `Timed out awaiting permission to upload remote build for '${params.action}'`\n );\n }\n if (!activation.response || !activation.response.success) {\n let err = 'Failed to get remote build upload permission';\n const resultError = activation?.response?.result?.error;\n if (resultError) {\n const errMsg =\n typeof resultError === 'string' ? resultError : resultError.message;\n if (typeof errMsg === 'string') {\n const parts = errMsg.split('Error:');\n err = parts[parts.length - 1];\n }\n }\n const thrown = new Error(err) as any;\n thrown.activation = JSON.stringify(activation, null, 2); // ensure deep enough nesting\n throw thrown;\n }\n const result = activation.response.result as Record<string, any>;\n return { url: result.url, sliceName: result.sliceName };\n}\n\n// Invoke the remote builder, return the response.\nasync function invokeRemoteBuilder(\n zipped: Buffer,\n owClient: openwhisk.Client,\n feedback: Feedback,\n action: ActionSpec,\n encryptionKey?: string\n): Promise<string> {\n // Upload project slice\n const params = { action: computeTag(action) };\n debug(`Invoking 'getUploadUrl'`);\n const { url, sliceName } = await getUploadUrl(owClient, params, feedback);\n if (!url || !sliceName) {\n const msg = `Unexpected response from getUploadUrl`;\n throw new Error(msg);\n }\n debug('remote build url is %s', url);\n const axiosConfig = {\n // Override capacity limiting defaults\n maxBodyLength: MAX_SLICE_UPLOAD_SIZE,\n maxContentLength: MAX_SLICE_UPLOAD_SIZE\n };\n const result = await axios.put(url, zipped, axiosConfig);\n if (result.status !== 200) {\n throw new Error(\n `Bad response [$result.status}] when uploading '${sliceName}' for remote build`\n );\n }\n debug('axios put of url was successful');\n // Invoke the remote builder action. The action name incorporates the runtime 'kind'.\n // That action will re-invoke the deployer in the target runtime.\n const kind = action.runtime;\n const activityName = `function '${getActionName(action)}'`;\n const runtime = (await canonicalRuntime(kind)).replace(':', '_');\n const buildActionName = `${BUILDER_ACTION_STEM}${runtime}`;\n debug(\n `Invoking remote build action '${buildActionName}' for build '${path.basename(\n sliceName\n )} of ${activityName}`\n );\n try {\n const invoked = await owClient.actions.invoke({\n name: buildActionName,\n params: { toBuild: sliceName, encryptionKey }\n });\n feedback.progress(\n `Submitted ${activityName} for remote building and deployment in runtime ${kind} (id: ${invoked.activationId})`\n );\n return invoked.activationId;\n } catch (err) {\n if (err.statusCode === 404) {\n throw new Error(\n `Remote build service is not available for runtime '${kind}' on this platform instance.`\n );\n } else if (err.statusCode >= 500 && err.statusCode <= 599) {\n throw new Error('Remote build service returned error status.');\n } else {\n throw err;\n }\n }\n}\n\n// Read a directory and filter the result\nfunction readDirectory(\n filepath: string,\n reader: ProjectReader\n): Promise<PathKind[]> {\n return reader.readdir(filepath).then(filterFiles);\n}\n\n// Find the \"dominant\" special file in a collection of files within an action or lib directory, while checking for some errors\n// The dominance order is build.[sh|cmd] > package.json > .include > none-of-these (returns 'identify' since 'building' will\n// then start by identifying files)\n// Errors detected are:\n// .ignore when there is also .include\n// .include and/or .ignore present in the lib directory\n// no files in directory (or only an .ignore file); actions only\n// -- note that this does not find all vacuous builds ... there could be more than one file, e.g., one of\n// which is .ignore and ignores the other, or there could be a vacuous .include. These more complex\n// cases are found later in identifyActionFiles, where a more generic error will result\n// build.cmd but no build.sh on a non-windows system. This is wrong even if the build is later rescheduled to\n// be remote, because the remote build will run in a runtime container which is definitely not windows\n// There is another possible error, which is build.sh but no build.cmd on a windows system. We can't detect that\n// here because we do not yet know whether the build will be remote or local and it is only an error if local.\n// The error will be found in checkBuildingRequirements.\nfunction findSpecialFile(\n items: PathKind[],\n filepath: string,\n isAction: boolean\n): string {\n const files = items.filter((item) => !item.isDirectory);\n let buildDotSh = false;\n let buildDotCmd = false;\n let npm = false;\n let include = false;\n let ignore = false;\n for (const file of files) {\n if (file.name === 'build.sh') {\n buildDotSh = true;\n } else if (file.name === 'build.cmd') {\n buildDotCmd = true;\n } else if (file.name === 'package.json') {\n npm = true;\n } else if (file.name === '.include' || file.name === '.source') {\n include = true;\n } else if (file.name === '.ignore') {\n ignore = true;\n }\n }\n // Error checks\n if (include && ignore) {\n throw new Error(\n `In ${filepath}: '.include' (or '.source') and '.ignore' may not both be present`\n );\n } else if (\n isAction &&\n (files.length === 0 || (ignore && files.length === 1))\n ) {\n throw new Error(`Action directory ${filepath} has no files`);\n } else if (!isAction && (include || ignore)) {\n throw new Error(\n `'.include' and '.ignore' are not supported in the 'lib' directory`\n );\n }\n if (buildDotCmd && process.platform === 'win32') {\n return 'build.cmd';\n }\n if (buildDotCmd && !buildDotSh) {\n throw new Error(\n `In ${filepath}: 'build.cmd' won't run on this platform and no 'build.sh' is provided`\n );\n }\n if (buildDotSh) {\n // We don't do the \"won't run on this platform\" check here because we don't know if the build is remote\n return 'build.sh';\n }\n return npm ? 'package.json' : include ? '.include' : 'identify';\n}\n\n// The 'builder' for use when the action is a single file after all other processing\nasync function singleFileBuilder(\n action: ActionSpec,\n file: string\n): Promise<ActionSpec> {\n debug(\"singleFileBuilder deploying '%s'\", file);\n const newMeta = (await actionFileToParts(file)) as ActionSpec;\n delete newMeta.name;\n newMeta.web = true;\n // After a build, only the file, zipped, and binary flags take precedence over what's in the action already.\n // Metadata calculated from the file name is filled in, as is the default for web, but these apply only if not\n // already specified in the action (except for binary and zipped, which always change to match the build result).\n const { binary, zipped } = newMeta;\n const newAction = Object.assign(newMeta, action, { file, binary, zipped });\n return Promise.resolve(newAction);\n}\n\n// The 'builder' for when multiple files (and/or directories) have been identified as constituting the action.\n// 1. If there is an existing ZIP_TARGET\n// a. If incremental is specified, see whether the autozip can be skipped\n// b. Otherwise, remove the old zip.\n// 2. If there is a runtime provided in the ActionSpec we leave it there. Otherwise, we scan the files to see if we\n// can decide on an unambiguous runtime value. If we can't, it's an error.\n// 3. Use archiver to zip the items individually, according to the rules that\n// - an item is renamed to the basename of the item if it contains ..\n// - an item is zipped as is otherwise\n// - directories are zipped recursively\n// 4. Return an ActionSpec promise describing the result.\nasync function autozipBuilder(\n pairs: string[][],\n action: ActionSpec,\n incremental: boolean,\n verboseZip: boolean,\n reader: ProjectReader,\n feedback: Feedback\n): Promise<ActionSpec> {\n if (verboseZip) {\n feedback.progress('Zipping action contents in', action.file);\n } else {\n debug('Zipping action contents in %s', action.file);\n }\n if (!action.runtime) {\n action.runtime = await agreeOnRuntime(pairs.map((pair) => pair[0]));\n }\n // If there's real file system, observe and store the zip results there for incremental support\n const targetZip = path.join(action.file, ZIP_TARGET);\n const inMemory = reader.getFSLocation() === null;\n let output: Writable;\n if (!inMemory) {\n zipDebug('zipping to %s for action %s', targetZip, getActionName(action));\n const localTargetZip = makeLocal(reader, targetZip);\n pairs = pairs.map((pair) => [makeLocal(reader, pair[0]), pair[1]]);\n if (fs.existsSync(localTargetZip)) {\n zipDebug('the file exists and will be either reused or deleted');\n if (incremental) {\n const metaFiles: string[] = [\n makeLocal(reader, action.file, '.include'),\n makeLocal(reader, action.file, '.ignore')\n ].filter(fs.existsSync);\n debug(\n 'checking whether to build a new zip for %s with metaFiles %o',\n getActionName(action),\n metaFiles\n );\n if (\n zipFileAppearsCurrent(\n localTargetZip,\n pairs.map((pair) => pair[0]).concat(metaFiles)\n )\n ) {\n return singleFileBuilder(action, targetZip);\n }\n }\n zipDebug('deleting old target zip');\n fs.unlinkSync(localTargetZip);\n }\n output = fs.createWriteStream(localTargetZip);\n } else {\n zipDebug('zipping to memory buffer for action %s', getActionName(action));\n output = new memoryStreams.WritableStream({ highWaterMark: 1024 * 1024 });\n }\n const zip = archiver('zip');\n const outputPromise = new Promise(function (resolve, reject) {\n zip.on('error', (err) => {\n zipDebug('zip error occurred: %O', err);\n reject(err);\n });\n output.on('close', () => {\n zipDebug('zipfile successfully closed');\n resolve(undefined);\n });\n output.on('finish', () => {\n zipDebug('zipfile successfully finished');\n resolve(undefined);\n });\n output.on('end', () => {\n zipDebug('zipfile data has been drained');\n });\n zip.on('warning', (err) => {\n zipDebug('warning issued from archiver %O', err);\n if (err.code !== 'ENOENT') {\n reject(err);\n }\n });\n });\n zip.pipe(output);\n zipDebug('zipping %d files', pairs.length);\n for (const pair of pairs) {\n const [oldPath, newPath] = pair;\n const pathKind = await reader.getPathKind(oldPath);\n if (pathKind.symlink) {\n zip.symlink(newPath, pathKind.symlink);\n } else {\n const mode = pathKind.mode;\n const data = await reader.readFileContents(oldPath);\n zipDebug(\n \"Zipping file with old path '%s', buffer length '%d', new path '%s', and mode %d\",\n oldPath,\n data.length,\n newPath,\n mode\n );\n zip.append(data, { name: newPath, mode: mode });\n zipDebug(\n \"Zipped '%s' for action '%s', emitted %d\",\n newPath,\n action.name,\n zip.pointer()\n );\n }\n }\n zipDebug('finalizing zip for action %s', action.name);\n zip.finalize();\n zipDebug('zip finalized for action %s', action.name);\n return outputPromise.then(() => {\n if (verboseZip) {\n feedback.progress('Zipping complete in', action.file);\n } else {\n debug('zipping complete for %s', action.name);\n }\n if (inMemory) {\n const code = (output as memoryStreams.WritableStream)\n .toBuffer()\n .toString('base64');\n if (!code) {\n return Promise.reject(\n new Error('An error occurred in in-memory zipping')\n );\n }\n zipDebug(\n 'in memory zipping complete with code of length %d',\n code.length\n );\n action.code = code as string;\n return singleFileBuilder(action, action.file);\n } else {\n return singleFileBuilder(action, targetZip);\n }\n });\n}\n\n// Subroutine for performing a \"real\" build requiring a spawn.\nfunction build(\n cmd: string,\n args: string[],\n realPath: string,\n displayPath: string,\n infoMsg: string,\n errorTag: string,\n verbose: boolean,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n debug('building with realPath=%s and displayPath=%s', realPath, displayPath);\n let result = '';\n let time = Date.now();\n function statusUpdate(data: { toString: () => string }) {\n result += data.toString();\n const newTime = Date.now();\n if (newTime - time > 5000) {\n time = newTime;\n feedback.progress('Still running', infoMsg, 'in', displayPath);\n }\n }\n const env = buildEnv ? Object.assign({}, process.env, buildEnv) : process.env;\n return new Promise(function (resolve, reject) {\n feedback.progress('Started running', infoMsg, 'in', displayPath);\n const shell =\n process.platform === 'win32' ? true : process.env.shell || '/bin/bash';\n const child = spawn(cmd, args, { cwd: realPath, shell, env });\n if (verbose && !slice) {\n // Verbose build behavior when build is local\n child.stdout.on('data', (data) => feedback.progress(String(data)));\n child.stderr.on('data', (data) => feedback.warn(String(data)));\n } else {\n // Non-verbose build behavior and verbose build behavior when build is remote\n child.stdout.on('data', statusUpdate);\n child.stderr.on('data', statusUpdate);\n }\n child.on('close', (code) => {\n if (code !== 0) {\n // Failure case: locally, we dump the result iff verbose was not requested.\n // Remotely, we always dump the result because it always has to be shown on error.\n if (!verbose || slice) {\n feedback.warn('Output of failed build in %s', realPath);\n feedback.warn(result);\n }\n reject(new Error(`'${errorTag}' exited with code ${code}`));\n } else {\n // Success case.\n feedback.progress('Finished running', infoMsg, 'in', displayPath);\n // For a local build, verbosity, if requested, has already occurred.\n // For a remote build, verbosity requires dumping the accumulated output.\n if (verbose && slice) {\n // Only warn is active for a remote build, so use that channel to report\n feedback.warn(result);\n }\n resolve(undefined);\n }\n });\n child.on('error', (err) => {\n reject(err);\n });\n });\n}\n\n// The builder for a shell script\nfunction scriptBuilder(\n script: string,\n realPath: string,\n displayPath: string,\n flags: Flags,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n if (flags.incremental && scriptAppearsBuilt(realPath)) {\n if (flags.verboseBuild) {\n feedback.progress(\n `Skipping build in ${displayPath} because the action was previously built`\n );\n }\n return Promise.resolve(true);\n }\n return build(\n script,\n [],\n realPath,\n displayPath,\n script,\n script,\n flags.verboseBuild,\n buildEnv,\n slice,\n feedback\n );\n}\n\n// Determine if a shell-script style build appears to have been run. For this we just check for the presence of a `.built` file since\n// we don't have any dependency information. If the author of the build wants to do better, he should do dependency checking _in_ the build\n// and never write a `.built` marker; in that case, the build will always run but will usually do very little.\nfunction scriptAppearsBuilt(filepath: string): boolean {\n const toTest = path.join(filepath, '.built');\n return fs.existsSync(toTest);\n}\n\n// Determine if a new zip should be generated. The existing zip is considered current if it is newer than its dependencies.\n// This won't happen when zipping is in memory because that only happens when there is no local file system and\n// hence no possibility of incremental building.\nfunction zipFileAppearsCurrent(\n zipfile: string,\n dependencies: string[]\n): boolean {\n const ziptime = fs.statSync(zipfile).mtimeMs;\n for (const dep of dependencies) {\n if (fs.existsSync(dep)) {\n if (fs.statSync(dep).mtimeMs > ziptime) {\n debug('%s not considered current because %s is newer', zipfile, dep);\n return false;\n }\n } else {\n debug(\"dependency %s doesn't exist\", dep);\n return false; // play it safe\n }\n }\n debug('%s seems up to date so no re-zip', zipfile);\n return true;\n}\n\n// Determine if an npm|yarn style build appears to have been run \"recently enough\". This is heuristic and does not do a full dependency check.\n// It returns true iff both `node_modules` and either of `package-lock.json` or `yarn.lock` are present and newer than `package.json`.\nfunction npmPackageAppearsBuilt(filepath: string): boolean {\n const packageJson = path.join(filepath, 'package.json');\n const packageLockJson = path.join(filepath, 'package-lock.json');\n const yarnLock = path.join(filepath, 'yarn.lock');\n const nodeModules = path.join(filepath, 'node_modules');\n const packageJsonTime = fs.statSync(packageJson).mtimeMs;\n const packageLockJsonTime = fs.existsSync(packageLockJson)\n ? fs.statSync(packageLockJson).mtimeMs\n : 0;\n const nodeModulesTime = fs.existsSync(nodeModules)\n ? fs.statSync(nodeModules).mtimeMs\n : 0;\n const yarnLockTime = fs.existsSync(yarnLock)\n ? fs.statSync(yarnLock).mtimeMs\n : 0;\n const lockTime =\n yarnLockTime > packageLockJsonTime ? yarnLockTime : packageLockJsonTime;\n return lockTime >= packageJsonTime && nodeModulesTime >= packageJsonTime;\n}\n\n// To avoid getting 'stuck' when package.json changes in a way that does not cause an update to the lock file or node_modules,\n// we touch these resources after every npm build\nfunction makeNpmPackageAppearBuilt(filepath: string) {\n const packageLockJson = path.join(filepath, 'package-lock.json');\n if (fs.existsSync(packageLockJson)) touch(packageLockJson);\n const yarnLock = path.join(filepath, 'yarn.lock');\n if (fs.existsSync(yarnLock)) touch(yarnLock);\n const nodeModules = path.join(filepath, 'node_modules');\n if (fs.existsSync(nodeModules)) touch(nodeModules);\n}\n\n// The builder for npm|yarn install --production or npm|yarn install && npm|yarn run build\n// A package.json must be present since this builder wouldn't have been invoked otherwise.\n// This doesn't mean that npm|yarn install will succeed, just that, if it fails it is for some other reason\nfunction npmBuilder(\n filepath: string,\n displayPath: string,\n flags: Flags,\n buildEnv: Record<string, string>,\n slice: boolean,\n feedback: Feedback\n): Promise<any> {\n debug('Performing npm build for %s', filepath);\n const cmd = flags.yarn ? 'yarn' : 'npm';\n const npmRunBuild = buildScriptExists(filepath);\n const args = npmRunBuild\n ? ['install', '&&', cmd, 'run', 'build']\n : ['install', '--production'];\n const infoMsg = [cmd, ...args].join(' ');\n if (flags.incremental) {\n debug('Detected incremental build');\n const pkgBuilt = npmPackageAppearsBuilt(filepath);\n const scriptBuilt = scriptAppearsBuilt(filepath);\n const shouldSkip = npmRunBuild ? pkgBuilt && scriptBuilt : pkgBuilt;\n debug(\n `npmRunBuild=${!!npmRunBuild}, npmPackageAppearsBuilt=${pkgBuilt}, scriptAppearsBuilt=${scriptBuilt}, shouldSkip=${shouldSkip}`\n );\n if (shouldSkip) {\n if (flags.verboseBuild) {\n feedback.progress(\n `Skipping '${infoMsg}' in ${filepath} because the previous build is still valid`\n );\n }\n return Promise.resolve(true);\n }\n } else {\n debug('Build was not incremental');\n }\n return build(\n cmd,\n args,\n filepath,\n displayPath,\n infoMsg,\n `${cmd} install`,\n flags.verboseBuild,\n buildEnv,\n slice,\n feedback\n ).then(() => makeNpmPackageAppearBuilt(filepath));\n}\n\n// Test whether the `package.json` of a filepath (known to exist) contains a 'build' script.\n// We can assume that the local file system is usable.\nfunction buildScriptExists(filepath: string): boolean {\n const contents = fs.readFileSync(path.join(filepath, 'package.json'));\n try {\n const pj = JSON.parse(String(contents));\n return pj.scripts && pj.scripts.build;\n } catch {\n // For any parse failure, we simply avoid leaking the exception, which will be uninformative\n // since the user doesn't realize we are doing our own parse of package.json. The ensuing\n // 'npm install'' or 'yarn install' will then fail with a diagnostic much more familiar to\n // the developer who provided the unparsable package.json.\n return false;\n }\n}\n\n// Get the Ignore object for screening files. This always has the fixed entries for .ignore itself, .build, build.sh, and .build.cmd\n// but adds anything found in an .ignore file. Note that package.json is not ignored, even though it is a build trigger. We\n// also don't add an entry for .include (or .source) since that case is driven by a fixed set of files and not by scanning a directory.\nfunction getIgnores(dir: string, reader: ProjectReader): Promise<Ignore> {\n const filePath = path.join(dir, '.ignore');\n const fixedItems = [\n '.ignore',\n 'build.sh',\n 'build.cmd',\n ZIP_TARGET,\n ...getExclusionList()\n ];\n return readFileAsList(filePath, reader)\n .then((items) => {\n return ignore().add(items.concat(fixedItems));\n })\n .catch(() => {\n return ignore().add(fixedItems);\n });\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as path from 'path';\nimport * as fs from 'fs';\nimport makeDebug from 'debug';\nimport Zip from 'adm-zip';\nimport * as rimraf from 'rimraf';\nimport { DeployStructure } from './deploy-struct';\nimport { Readable, Writable } from 'stream';\nimport { WritableStream } from 'memory-streams';\nimport { BUILDER_NAMESPACE } from './finder-builder';\nimport axios from 'axios';\nimport { getCredentialsFromEnvironment } from './credentials';\nimport openwhisk from 'openwhisk';\nimport { waitForActivation } from './util';\n\nconst debug = makeDebug('nim:deployer:slice-reader');\nconst TEMP = process.platform === 'win32' ? process.env.TEMP : '/tmp';\n// Environment must also contain AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY\n\n// MAX_SLICE_UPLOAD_SIZE governs the maximum supported zipped size for a project slice\nexport const MAX_SLICE_UPLOAD_SIZE =\n parseInt(process.env.MAX_SLICE_UPLOAD_SIZE) || 64 * 1024 * 1024;\n\n// Supports the fetching and deletion of project slices from build bucket.\n// Uses the aws s3 client directly (does not go through the Nimbella storage\n// abstraction). Assumes the necessary s3 properties are in the environment.\n// This will not work on older clusters (e.g `nimgcp`) where the use of a data\n// bucket associated with the namespace is assumed. A nim CLI < 2.0.0 must be\n// used for those clusters.\n\n// Get the cache area\nfunction cacheArea() {\n return path.join(TEMP, 'slices');\n}\n\n// Pipe data from one stream to another\nfunction pipe(input: Readable, output: Writable): Promise<unknown> {\n const toWait = new Promise(function (resolve) {\n output.on('close', () => {\n resolve(true);\n });\n output.on('finish', () => {\n resolve(true);\n });\n });\n input.pipe(output);\n return toWait;\n}\n\n// Fetch the slice to cache storage.\nexport async function fetchSlice(sliceName: string): Promise<string> {\n const GET_DOWNLOAD_URL = `/${BUILDER_NAMESPACE}/builder/getDownloadUrl`;\n const credentials = getCredentialsFromEnvironment();\n const owClient = openwhisk({\n apihost: credentials.ow.apihost,\n api_key: credentials.ow.api_key,\n namespace: credentials.namespace\n });\n\n const invoked = await owClient.actions.invoke({\n name: GET_DOWNLOAD_URL,\n params: {\n name: sliceName\n }\n });\n\n const activation = await waitForActivation(\n invoked.activationId,\n owClient,\n () => {\n debug('fetching build assets ...');\n },\n 60\n );\n\n if (!activation) {\n throw new Error(`Timed out fetching assets url for '${sliceName}'`);\n }\n\n const activationResponse = activation.response;\n const downloadUrl = activation.response?.result?.url;\n if (!activationResponse || !activationResponse?.success || !downloadUrl) {\n throw new Error(`Failed to fetch assets url for '${sliceName}'`);\n }\n\n const response = await axios.get(downloadUrl, {\n responseType: 'stream'\n });\n\n const cache = path.join(cacheArea(), sliceName);\n if (fs.existsSync(cache)) {\n rimraf.sync(cache);\n }\n debug('Making cache directory: %s', cache);\n fs.mkdirSync(cache, { recursive: true });\n const destination = new WritableStream({\n highWaterMark: MAX_SLICE_UPLOAD_SIZE\n });\n\n await pipe(response.data, destination);\n const data = (destination as WritableStream).toBuffer();\n const zip = new Zip(data);\n debug('zip file has %d entries', zip.getEntries().length);\n for (const entry of zip.getEntries().filter((entry) => !entry.isDirectory)) {\n const target = path.join(cache, entry.entryName);\n const parent = path.dirname(target);\n if (!fs.existsSync(parent)) {\n fs.mkdirSync(parent, { recursive: true });\n }\n const mode = entry.attr >>> 16;\n debug('storing %s', entry.entryName);\n fs.writeFileSync(target, entry.getData(), { mode });\n }\n return cache;\n}\n\n// Delete\nexport async function deleteSlice(project: DeployStructure): Promise<void> {\n const DELETE_ASSETS_URL = `/${BUILDER_NAMESPACE}/builder/deleteBuildAssets`;\n const sliceName = path.relative(cacheArea(), project.filePath);\n const credentials = getCredentialsFromEnvironment();\n\n const owClient = openwhisk({\n apihost: credentials.ow.apihost,\n api_key: credentials.ow.api_key,\n namespace: credentials.namespace\n });\n\n const invoked = await owClient.actions.invoke({\n name: DELETE_ASSETS_URL,\n params: {\n name: sliceName\n }\n });\n\n await waitForActivation(\n invoked.activationId,\n owClient,\n () => debug('removing build assets ...'),\n 60\n );\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport * as fs from 'fs';\nimport * as Path from 'path';\nimport { promisify } from 'util';\nimport { ProjectReader, PathKind } from './deploy-struct';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:file-reader');\n\n// Don't run promisify at module scope: will fail in browser. This module will never actually be used in a browser.\nlet fs_readdir: (\n dir: fs.PathLike,\n options: { withFileTypes: boolean }\n) => Promise<fs.Dirent[]>;\nlet fs_readfile: (file: fs.PathLike) => Promise<any>;\nlet fs_lstat: (path: fs.PathLike) => Promise<any>;\nlet fs_realpath: (path: fs.PathLike) => Promise<any>;\nlet fs_readlink: (path: fs.PathLike) => Promise<any>;\n\n// The file system implementation of ProjectReader\n// The file system implementation accepts absolute paths and relative paths landing anywhere in the filesystem.\n// At 'make' time, the path of the project (within the file system is provided)\n\n// Make\nexport function makeFileReader(basepath: string): ProjectReader {\n debug(\"making file reader on basepath '%s'\", basepath);\n fs_readdir = promisify(fs.readdir);\n fs_readfile = promisify(fs.readFile);\n fs_lstat = promisify(fs.lstat);\n fs_realpath = promisify(fs.realpath);\n fs_readlink = promisify(fs.readlink);\n return new FileProjectReader(basepath);\n}\n\n// Implementing class\nclass FileProjectReader implements ProjectReader {\n // Project location in the file system\n basepath: string;\n\n constructor(basepath: string) {\n this.basepath = basepath;\n }\n\n // Retrieve the basepath\n getFSLocation(): string {\n return this.basepath;\n }\n\n // File system implementation of readdir.\n async readdir(path: string): Promise<PathKind[]> {\n debug(\"request to read directory '%s'\", path);\n path = Path.resolve(this.basepath, path);\n path = await fs_realpath(path);\n debug(\"resolved to directory '%s\", path);\n const entries = await fs_readdir(path, { withFileTypes: true });\n const results = entries.map(async (entry) => {\n let isFile: boolean, isDirectory: boolean, symlink: string;\n if (entry.isSymbolicLink()) {\n try {\n const fullName = await fs_realpath(Path.resolve(path, entry.name));\n const stat = await fs_lstat(fullName);\n isFile = stat.isFile();\n isDirectory = stat.isDirectory();\n } catch (_) {\n symlink = await fs_readlink(Path.resolve(path, entry.name));\n }\n } else {\n isFile = entry.isFile();\n isDirectory = entry.isDirectory();\n }\n return { name: entry.name, isDirectory, isFile, symlink, mode: 0o666 };\n });\n return Promise.all(results);\n }\n\n // File system implementation of readFileContents\n async readFileContents(path: string): Promise<Buffer> {\n debug('request to read %s', path);\n path = Path.resolve(this.basepath, path);\n path = await fs_realpath(path);\n return fs_readfile(path);\n }\n\n // File system implementation of isExistingFile\n isExistingFile(path: string): Promise<boolean> {\n debug(\"testing existence for file '%s'\", path);\n path = Path.resolve(this.basepath, path);\n debug(\"resolved to file '%s\", path);\n return fs_lstat(path)\n .then((stats: fs.Stats) => {\n if (stats.isFile()) {\n debug('file exists');\n return true;\n }\n debug('path exists but is not a file');\n return false;\n })\n .catch(() => {\n debug('lstat failed for path %s', path);\n return false;\n });\n }\n\n // File system implementation of getPathKind\n async getPathKind(path: string): Promise<PathKind> {\n path = Path.resolve(this.basepath, path);\n const stats = await fs_lstat(path).catch(() => undefined);\n if (!stats) {\n return undefined;\n }\n let symlink: string;\n if (stats.isSymbolicLink()) {\n symlink = await fs_readlink(path);\n }\n return {\n name: Path.basename(path),\n isFile: stats.isFile(),\n isDirectory: stats.isDirectory(),\n symlink,\n mode: stats.mode\n };\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { Includer } from './deploy-struct';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:includer');\n\n// Make an includer\nexport function makeIncluder(include: string, exclude: string): Includer {\n const includes = include ? include.split(',') : undefined;\n const excludes = exclude ? exclude.split(',') : undefined;\n const ans = new IncluderImpl(includes, excludes);\n debug('constructed includer: %O', ans);\n return ans;\n}\n\n// The implementation behind the Includer interface\nclass IncluderImpl implements Includer {\n isExcludingOnly = false;\n includedPackages: Set<string> = new Set();\n excludedPackages: Set<string> = new Set();\n includedActions: Map<string, Set<string>> = new Map();\n excludedActions: Map<string, Set<string>> = new Map();\n\n // Construct\n constructor(includes: string[], excludes: string[]) {\n if (!includes) {\n this.isExcludingOnly = true;\n } else {\n for (let token of includes) {\n if (token.endsWith('/')) {\n token = token.slice(0, -1);\n }\n const [pkg, action] = token.split('/');\n if (action) {\n this.addToMap(pkg, action, this.includedActions);\n } else {\n this.includedPackages.add(pkg);\n }\n }\n }\n if (excludes) {\n for (let token of excludes) {\n if (token.endsWith('/')) {\n token = token.slice(0, -1);\n }\n const [pkg, action] = token.split('/');\n if (action) {\n this.addToMap(pkg, action, this.excludedActions);\n } else {\n this.excludedPackages.add(pkg);\n }\n }\n }\n }\n\n // Implement isPackageIncluded\n isPackageIncluded = (pkg: string, all: boolean) => {\n const nominallyIncluded =\n this.includedPackages.has(pkg) ||\n (this.isExcludingOnly && !this.excludedPackages.has(pkg));\n if (all) {\n return nominallyIncluded && !this.excludedActions.has(pkg);\n } else {\n return nominallyIncluded || this.includedActions.has(pkg);\n }\n };\n\n // Implement isActionIncluded\n isActionIncluded = (pkg: string, action: string) => {\n if (this.isActionInMap(pkg, action, this.includedActions)) {\n return true; // explicitly included\n }\n if (\n this.excludedPackages.has(pkg) ||\n this.isActionInMap(pkg, action, this.excludedActions)\n ) {\n return false; // excluded, either explicitly or at package level\n }\n // So far, the action is not excluded but was not explicitly included either so the result depends on package inclusion\n return this.isExcludingOnly || this.includedPackages.has(pkg);\n };\n\n // Implement isIncludingEverything\n isIncludingEverything = () => {\n return (\n this.isExcludingOnly &&\n this.includedActions.size === 0 &&\n this.includedPackages.size === 0\n );\n };\n\n // Utility to add an action to an action map\n addToMap(pkg: string, action: string, map: Map<string, Set<string>>) {\n let set = map.get(pkg);\n if (!set) {\n set = new Set();\n map.set(pkg, set);\n }\n set.add(action);\n }\n\n // Utility to interrogate whether an action is in an action map\n isActionInMap(\n pkg: string,\n action: string,\n map: Map<string, Set<string>>\n ): boolean {\n const set = map.get(pkg);\n if (!set) {\n return false;\n }\n return set.has(action);\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// Contains the main public (library) API of the deployer (some exports in 'util' may also be used externally but are incidental)\n\nimport { doDeploy, maybeLoadVersions } from './deploy';\nimport {\n DeployStructure,\n DeployResponse,\n PackageSpec,\n OWOptions,\n Credentials,\n Flags,\n Includer,\n Feedback,\n DefaultFeedback\n} from './deploy-struct';\nimport {\n readTopLevel,\n buildStructureParts,\n assembleInitialStructure\n} from './project-reader';\nimport {\n isTargetNamespaceValid,\n wrapError,\n wipe,\n writeProjectStatus,\n getTargetNamespace,\n checkBuildingRequirements,\n errorStructure,\n isRealBuild\n} from './util';\nimport { buildAllActions, maybeBuildLib } from './finder-builder';\nimport openwhisk = require('openwhisk');\nimport { getCredentialsForNamespace, getCredentials } from './credentials';\nimport { makeIncluder } from './includer';\nimport makeDebug from 'debug';\nconst debug = makeDebug('nim:deployer:api');\n\n// Initialize the API by 1. purging existing __OW_ entries from the environment, 2. setting __OW_USER_AGENT, 3. returning a map of\n// entries that were purged. Also saves the __OW_NAMESPACE and __OW_API_HOST values in the environment, renamed, for the special\n// cases where there is no credential store but certain code paths still must work. An example is the slice reader.\nexport function initializeAPI(userAgent: string): { [key: string]: string } {\n const result: Record<string, string> = {};\n for (const item in process.env) {\n if (item.startsWith('__OW_')) {\n result[item] = process.env[item];\n delete process.env[item];\n }\n }\n process.env.__OW_USER_AGENT = userAgent;\n // Careful with these transfers. Assigning a value to the env always casts to string (even undefined -> \"undefined\")\n if (result.__OW_NAMESPACE) {\n process.env.savedOW_NAMESPACE = result.__OW_NAMESPACE;\n }\n if (result.__OW_API_HOST) {\n process.env.savedOW_API_HOST = result.__OW_API_HOST;\n }\n if (result.__OW_API_KEY) {\n process.env.savedOW_API_KEY = result.__OW_API_KEY;\n }\n return result;\n}\n\n// Get a vaguely valid user agent string. Hopefully, this was set in the environment during initialize. But, we use some fallbacks if not.\n// It is not necessary to call this function when using the OW client because it will respect __OW_USER_AGENT directly. It is used\n// when using other web APIs in order to set a valid and possibly useful value in the user-agent header.\nexport function getUserAgent(): string {\n const ans = process.env.__OW_USER_AGENT;\n return ans || 'nimbella-cli';\n}\n\n// Deploy a disk-resident project given its path and options to pass to openwhisk. The options are merged\n// with those in the config; the result must include api or apihost, and must include api_key.\nexport async function deployProject(\n path: string,\n credentials: Credentials | undefined,\n flags: Flags\n): Promise<DeployResponse> {\n debug('deployProject invoked with incremental %s', flags.incremental);\n return readPrepareAndBuild(path, credentials, flags).then((spec) => {\n if (spec.error) {\n debug('An error was caught prior to %O:', spec.error);\n return Promise.resolve(wrapError(spec.error, undefined));\n }\n return deploy(spec);\n });\n}\n\n// Combines the read, prepare, and build phases but does not deploy\nexport function readPrepareAndBuild(\n path: string,\n credentials: Credentials,\n flags: Flags,\n feedback?: Feedback\n): Promise<DeployStructure> {\n return readAndPrepare(path, credentials, flags, feedback).then((spec) =>\n spec.error ? spec : buildProject(spec)\n );\n}\n\n// Combines the read and prepare phases but does not build or deploy\nexport function readAndPrepare(\n path: string,\n credentials: Credentials,\n flags: Flags,\n feedback?: Feedback\n): Promise<DeployStructure> {\n const includer = makeIncluder(flags.include, flags.exclude);\n return readProject(\n path,\n flags.env,\n flags.buildEnv,\n includer,\n flags.remoteBuild,\n feedback,\n flags.noTriggers\n ).then((spec) =>\n spec.error ? spec : prepareToDeploy(spec, credentials, flags)\n );\n}\n\n// Perform deployment from a deploy structure. The 'cleanOrLoadVersions' step is currently folded into this step\nexport function deploy(todeploy: DeployStructure): Promise<DeployResponse> {\n debug('Starting deploy');\n return maybeLoadVersions(todeploy)\n .then(doDeploy)\n .then((results) => {\n const statusDir = writeProjectStatus(\n todeploy.filePath,\n results,\n todeploy.includer.isIncludingEverything()\n );\n if (statusDir && !todeploy.slice) {\n todeploy.feedback.progress(\n `Deployment status recorded in '${statusDir}'`\n );\n }\n if (!results.namespace && todeploy.credentials) {\n results.namespace = todeploy.credentials.namespace;\n }\n debug('deploy results are: %O', results);\n return results;\n });\n}\n\n// Read the information contained in the project, initializing the DeployStructure\nexport async function readProject(\n projectPath: string,\n envPath: string,\n buildEnvPath: string,\n includer: Includer,\n requestRemote: boolean,\n feedback: Feedback = new DefaultFeedback(),\n noTriggers = false\n): Promise<DeployStructure> {\n debug(\n 'Starting readProject, projectPath=%s, envPath=%s',\n projectPath,\n envPath\n );\n let ans: DeployStructure;\n try {\n const topLevel = await readTopLevel(\n projectPath,\n envPath,\n buildEnvPath,\n includer,\n feedback,\n noTriggers\n );\n const parts = await buildStructureParts(topLevel);\n ans = assembleInitialStructure(parts);\n } catch (err) {\n return errorStructure(err);\n }\n if (ans.error) {\n // Remaining steps are treacherous if there was an error detected in the config. We don't use the\n // errorStructure return for that case, because we need to support get-metadata, which wants a config\n // even if erroneous. However, any other uses are going to fail.\n return ans;\n }\n debug('evaluating the just-read project: %O', ans);\n try {\n await checkBuildingRequirements(ans, requestRemote);\n } catch (err) {\n return errorStructure(err);\n }\n return ans;\n}\n\n// 'Build' the project by running the \"finder builder\" steps in\n// 1. the 'lib' directory if found and if building it is appropriate\n// 2. each action-as-directory\n// These steps cannot be overlapped.\nexport async function buildProject(\n project: DeployStructure\n): Promise<DeployStructure> {\n debug('Starting buildProject with spec %O', project);\n if (project.libBuild && isRealBuild(project.libBuild)) {\n try {\n await maybeBuildLib(project);\n } catch (err) {\n return errorStructure(err);\n }\n }\n const actionPromise: Promise<PackageSpec[]> = buildAllActions(project);\n if (actionPromise) {\n return actionPromise\n .then((packages) => {\n project.packages = packages;\n return project;\n })\n .catch((err) => errorStructure(err));\n } else {\n return Promise.resolve(project);\n }\n}\n\n// Prepare a DeployStruct for deployment.\n// 1. Ensure that we are using the right credentials\n// 2. Merge credentials and user-specified auth/apihost flags that were not necessarily part of the credentials.\n// 3. Open the OW client handle to ensure it is valid before the (possibly extensive) build step is performed.\n// Validation includes the optional check on the target namespace; even if it came from the credentials it might no longer be valid.\nexport async function prepareToDeploy(\n inputSpec: DeployStructure,\n credentials: Credentials,\n flags: Flags\n): Promise<DeployStructure> {\n debug('Starting prepare with spec: %O', inputSpec);\n // 0. Handle slice. In that case, credentials and flags come from the DeployStructure\n if (inputSpec.slice) {\n debug('Retrieving credentials and flags from spec for slice');\n credentials = inputSpec.credentials;\n // The API host in the slice spec may represent a proxy and hence not be the real intended host.\n // If __OW_API_HOST is set, it is more trustworthy.\n if (process.env.__OW_API_HOST) {\n credentials.ow.apihost = process.env.__OW_API_HOST;\n } else if (process.env.savedOW_API_HOST) {\n credentials.ow.apihost = process.env.savedOW_API_HOST;\n }\n flags = inputSpec.flags;\n }\n // 1. Acquire credentials if not already present\n const owOptions: OWOptions = {\n api_key: flags.auth,\n apihost: flags.apiHost,\n ignore_certs: flags.insecure\n };\n if (!credentials) {\n debug('Finding credentials locally');\n let namespace: string;\n if (inputSpec.targetNamespace) {\n namespace = inputSpec.targetNamespace;\n }\n if (namespace) {\n // The config specified a target namespace so attempt to use it.\n debug('Retrieving specific credentials for namespace %s', namespace);\n credentials = await getCredentialsForNamespace(\n namespace,\n owOptions.apihost\n );\n } else {\n // There is no target namespace so get credentials for the current one\n let badCredentials: Error;\n debug('Attempting to get credentials for current namespace');\n credentials = await getCredentials().catch((err) => {\n badCredentials = err;\n return undefined;\n });\n if (badCredentials) {\n debug(\n 'Could not get credentials, returning error structure with %O',\n badCredentials\n );\n return errorStructure(badCredentials);\n }\n }\n }\n debug('owOptions: %O', owOptions);\n debug('credentials.ow: %O', credentials.ow);\n // Merge and save credentials information\n const wskoptions: OWOptions = {\n api_key: owOptions.api_key || credentials.ow.api_key,\n apihost: owOptions.apihost || credentials.ow.apihost,\n ignore_certs: owOptions.ignore_certs || credentials.ow.ignore_certs\n };\n debug('wskoptions\" %O', wskoptions);\n inputSpec.credentials = credentials;\n debug('prepareToDeploy merging flags: %O', flags);\n inputSpec.flags = flags;\n debug('Options merged');\n // 3. Open handles\n debug('Auth sufficiency established');\n inputSpec.owClient = openwhisk(wskoptions);\n if (!credentials.namespace) {\n credentials.namespace = await getTargetNamespace(inputSpec.owClient);\n } else {\n await isTargetNamespaceValid(inputSpec.owClient, credentials.namespace);\n }\n debug('Target namespace validated');\n debug('Sensitive project/namespace guard passed');\n debug('returning spec %O', inputSpec);\n return Promise.resolve(inputSpec);\n}\n\n// Utility to convert errors into useful messages. Usually, this just means getting the message field from the error but there\n// is logic to recognize the particular error pattern used by OW\nexport function getMessageFromError(err: any): string {\n // Although we attempt to say that all errors have type Error, in the loosy-goosy untyped world of Javascript this is easily violated.\n // Sometimes 'err' is just a string\n if (typeof err === 'string') {\n return err;\n }\n // Pattern match against the OW error pattern\n if (err.error && err.error.error && err.error.code) {\n return '[OpenWhisk] ' + err.error.error;\n }\n // Default case\n return err.message;\n}\n\n// Wipe a namespace of everything except its activations (the activations cannot be wiped via the public API)\nexport async function wipeNamespace(credentials: Credentials): Promise<void> {\n debug(\n 'Requested wipe-namespace function with host %s and auth %s',\n credentials.ow.apihost,\n credentials.ow.api_key\n );\n const init: OWOptions = {\n apihost: credentials.ow.apihost,\n api_key: credentials.ow.api_key\n };\n const client = openwhisk(init);\n debug('Client opened');\n return wipe(client, credentials);\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\n// This is the essence of the old watch command from Nimbella CLI.\n// It should probably be replaced by go code or at least revised to use the best available\n// file-watching techniques for the target OSs.\n\nimport * as fs from 'fs';\nimport * as chokidar from 'chokidar';\nimport { Flags, Credentials } from './deploy-struct';\nimport { Logger, deployProject } from './main';\nimport { isExcluded, delay } from './util';\n\n// Validate a project and start watching it if it actually looks like a project\nexport function watch(\n project: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n logger: Logger\n) {\n logger.log(`Watching '${project}' [use Control-C to terminate]`);\n let watcher: chokidar.FSWatcher;\n const reset = async () => {\n if (watcher) {\n //logger.log(\"Closing watcher\")\n await watcher.close();\n }\n };\n const watch = () => {\n //logger.log(\"Opening new watcher\")\n watcher = chokidar.watch(project, {\n ignoreInitial: true,\n followSymlinks: false,\n usePolling: false,\n useFsEvents: false\n });\n watcher.on('all', async (event, filename) => {\n if (!isExcluded(filename)) {\n await fireDeploy(\n project,\n filename,\n cmdFlags,\n creds,\n logger,\n reset,\n watch,\n event\n );\n }\n });\n };\n watch();\n}\n\n// Fire a deploy cycle. Suspends the watcher so that mods made to the project by the deployer won't cause a spurious re-trigger.\n// TODO this logic was crafted for fs.watch(). There might be a better way to suspend chokidar.\n// Displays an informative message before deploying.\nasync function fireDeploy(\n project: string,\n filename: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n logger: Logger,\n reset: () => Promise<void>,\n watch: () => void,\n event: string\n) {\n if (event === 'addDir') {\n // Don't fire on directory add ... it never represents a complete change.\n return;\n }\n if (event === 'add' && isSymlink(filename)) {\n // There may be a bug in chokidar ... we seem to get spurious add events for symlinks.\n // We strongly discourage symlinks within projects, so a new symlink is likely to be inside\n // a node_modules where we can ignore it.\n return;\n }\n await reset();\n logger.log(`\\nDeploying '${project}' due to change in '${filename}'`);\n let error = false;\n const result = await deployProject(\n project,\n cmdFlags,\n creds,\n true,\n logger\n ).catch((err) => {\n logger.displayError('', err);\n error = true;\n });\n if (error || !result) {\n return;\n }\n logger.log('Deployment complete. Resuming watch.\\n');\n await delay(200).then(() => watch());\n}\n\n// Test whether a file is a symlink\nfunction isSymlink(filename: string): boolean {\n try {\n const stat = fs.lstatSync(filename);\n return stat.isSymbolicLink();\n } catch {\n return false;\n }\n}\n", "/*\n * Copyright (c) 2019 - present DigitalOcean, LLC\n *\n * This file is licensed to you under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License. You may obtain a copy\n * of the License at http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under\n * the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS\n * OF ANY KIND, either express or implied. See the License for the specific language\n * governing permissions and limitations under the License.\n */\n\nimport { readAndPrepare, readProject, buildProject, deploy } from './api';\nimport {\n Flags,\n OWOptions,\n DeployResponse,\n Credentials,\n Feedback\n} from './deploy-struct';\nimport { deleteSlice } from './slice-reader';\nimport { makeIncluder } from './includer';\nimport { getRuntimeForAction, renameActionsToFunctions } from './util';\nimport { watch } from './watch';\nimport * as path from 'path';\nimport { default as parser } from 'yargs-parser';\nimport { STATUS_CODES } from 'http';\nimport createDebug from 'debug';\nimport { version } from './version';\nconst verboseError = createDebug('nim:error');\n\n// Provides a limited purpose main function for the deployer\n//main().then(flush).catch(handleError)\n\n// Also provides a library entry point (runCommand) which abstracts the output\n// of the main function so it can be captured.\n\n// The Logger type is adopted from the nim CLI\nexport interface Logger {\n log: (msg: string, ...args: any[]) => void;\n handleError: (msg: string, err?: Error) => never;\n exit: (code: number) => void; // don't use 'never' here because 'exit' doesn't always exit\n displayError: (msg: string, err?: Error) => void;\n logJSON: (entity: any) => void;\n logTable: (\n data: Record<string, unknown>[],\n columns: Record<string, unknown>,\n options: Record<string, unknown>\n ) => void;\n logOutput: (json: any, msgs: string[]) => void;\n}\n\n// The default logger implementation\nexport class DefaultLogger implements Logger {\n log(msg = '', ...args: any[]): void {\n console.log(msg, ...args);\n }\n\n handleError(msg: string, err?: Error): never {\n if (err) throw err;\n msg = improveErrorMsg(msg, err);\n throw new Error(msg);\n }\n\n displayError(msg: string, err?: Error): void {\n msg = improveErrorMsg(msg, err);\n verboseError('%O', err);\n const bang = process.platform === 'win32' ? '\u00BB' : '\u203A';\n console.error(bang + ' Error: ' + msg);\n }\n\n exit(code: number): void {\n process.exit(code);\n }\n\n logJSON(entity: Record<string, unknown>): void {\n console.log(JSON.stringify(entity, null, 2));\n }\n\n logTable(\n data: Record<string, unknown>[],\n _columns: Record<string, unknown>,\n _options: Record<string, unknown> = {}\n ): void {\n console.log(JSON.stringify(data, null, 2));\n }\n\n logOutput(json: Record<string, unknown>, msgs: string[]): void {\n for (const msg of msgs) {\n console.log(msg);\n }\n console.log(JSON.stringify(json, null, 2));\n }\n}\n\n// An alternative Logger for capturing output\nexport class CaptureLogger implements Logger {\n table: Record<string, unknown>[]; // The output table (array of entity) if that kind of output was produced\n captured: string[] = []; // Captured line by line output (flowing via Logger.log)\n errors: string[] = []; // Captured calls to displayError (these are Errors that are not supposed to be thrown)\n entity: Record<string, unknown>; // An output entity if that kind of output was produced\n\n log(msg = '', ...args: any[]): void {\n const msgs = String(msg).split('\\n');\n for (const msg of msgs) {\n this.captured.push(msg, ...args);\n }\n }\n\n handleError(msg: string, err?: Error): never {\n if (err) throw err;\n msg = improveErrorMsg(msg, err);\n throw new Error(msg);\n }\n\n displayError(msg: string, err?: Error): void {\n msg = improveErrorMsg(msg, err);\n this.errors.push(msg);\n }\n\n exit(_code: number): void {\n // a no-op here\n }\n\n logJSON(entity: Record<string, unknown>): void {\n this.entity = entity;\n }\n\n logTable(\n data: Record<string, unknown>[],\n _columns: Record<string, unknown>,\n _options: Record<string, unknown> = {}\n ): void {\n this.table = data;\n }\n\n logOutput(json: Record<string, unknown>, msgs: string[]): void {\n this.entity = json;\n this.captured = msgs;\n }\n}\n\n// Wrap a Logger in a Feedback for using the deployer API.\nclass LoggerFeedback implements Feedback {\n logger: Logger;\n warnOnly: boolean;\n constructor(logger: Logger) {\n this.logger = logger;\n }\n\n warn(msg?: any, ...args: any[]): void {\n this.logger.log(String(msg), ...args);\n }\n\n progress(msg?: any, ...args: any[]): void {\n if (this.warnOnly) return;\n this.logger.log(String(msg), ...args);\n }\n}\n\n// Ensure that console output is flushed when the command is really finished\nexport async function flush() {\n process.stdout.once('drain', () => process.exit(0));\n}\n\n// Deal with errors thrown from within the deployer\nexport function handleError(err: any) {\n console.error(err);\n process.exit(1);\n}\n\n// Parsing template: declares the flags\nconst parsing = {\n string: ['env', 'build-env', 'apihost', 'auth', 'include', 'exclude'],\n boolean: [\n 'insecure',\n 'verbose-build',\n 'verbose-zip',\n 'yarn',\n 'remote-build',\n 'incremental',\n 'json',\n 'no-triggers'\n ],\n configuration: {\n 'parse-positional-numbers': false,\n 'unknown-options-as-args': true,\n 'boolean-negation': false\n }\n};\n\n// Main function. The thinnest possible shell around 'runCommand' which is a library-level entry\n// point suitable for use by a reduced doctl plugin. The only thing added here is the default logger,\n// which simply causes output to go directly to the console.\nexport function main(): Promise<void> {\n return runCommand(process.argv.slice(2), new DefaultLogger());\n}\n\n// Primary library entry point for running the commands with an arbitrary Logger\nexport async function runCommand(inputArgs: string[], logger: Logger) {\n const parsed = parser(inputArgs, parsing);\n const args = parsed._ as string[];\n const badFlags = args.filter((arg) => arg.startsWith('-'));\n if (badFlags.length > 0) {\n logger.handleError(`unknown flag(s): [${badFlags}]`);\n }\n if (args.length != 2 && args[0] !== 'version') {\n logger.handleError(\n 'exactly two non-flag tokens are required: the command, and the project'\n );\n }\n const [cmd, project] = args;\n const {\n env,\n buildEnv,\n apihost,\n auth,\n include,\n exclude,\n insecure,\n verboseBuild,\n verboseZip,\n yarn,\n remoteBuild,\n incremental,\n json,\n noTriggers\n } = parsed;\n const flags: Flags = {\n env,\n buildEnv,\n apiHost: apihost,\n auth,\n include,\n exclude,\n insecure,\n verboseBuild,\n verboseZip,\n yarn,\n remoteBuild,\n incremental,\n json,\n noTriggers\n };\n switch (cmd) {\n case 'deploy':\n await doDeploy(project, flags, logger);\n break;\n case 'get-metadata':\n await doGetMetadata(project, flags, logger);\n break;\n case 'watch':\n // Note: it is up to the caller to use a non-capturing Logger with watch\n await doWatch(project, flags, logger);\n break;\n case 'version':\n logger.log(version);\n break;\n default:\n logger.handleError(`unknown command: ${cmd}`);\n }\n}\n\n// Command to do deployment\nasync function doDeploy(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n const { insecure, apiHost: apihost, auth } = flags;\n const creds = await processCredentials(insecure, apihost, auth);\n await deployProject(project, flags, creds, false, logger);\n}\n\n// Command to retrieve project description metadata\nasync function doGetMetadata(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n // Convert include/exclude flags into an Includer object\n const includer = makeIncluder(flags.include, flags.exclude);\n\n // Read the project\n const result = await readProject(\n project,\n flags.env,\n undefined,\n includer,\n false,\n undefined,\n flags.noTriggers\n );\n if (result.error && !result.unresolvedVariables) {\n logger.displayError('', result.error);\n logger.exit(1);\n }\n\n // Fill in any missing runtimes\n if (result.packages && !result.unresolvedVariables) {\n // Too dangerous to attempt this if the parse wasn't perfect\n for (const pkg of result.packages) {\n if (pkg.actions) {\n for (const action of pkg.actions) {\n action.runtime = await getRuntimeForAction(action, result.reader);\n }\n }\n }\n }\n\n // Display result\n renameActionsToFunctions(result);\n logger.logJSON(result);\n}\n\n// Command to do a project watch.\nasync function doWatch(\n project: string,\n flags: Flags,\n logger: Logger\n): Promise<void> {\n const { insecure, apiHost: apihost, auth } = flags;\n const creds = await processCredentials(insecure, apihost, auth);\n watch(project, flags, creds, logger);\n}\n\n// Set up credentials based on flags if supplied. Otherwise, credentials will be undefined until later, either based on\n// targetNamespace in the project.yml or else just the current connected namespace.\nasync function processCredentials(\n ignore_certs: boolean,\n apihost: string | undefined,\n auth: string | undefined\n): Promise<Credentials> {\n const owOptions: OWOptions = { ignore_certs }; // No explicit undefined\n if (apihost) {\n owOptions.apihost = parseAPIHost(apihost);\n }\n if (auth) {\n owOptions.api_key = auth;\n }\n let creds: Credentials | undefined;\n if (apihost && auth) {\n creds = {\n namespace: undefined,\n ow: owOptions,\n do_token: process.env.DO_API_TOKEN\n };\n }\n return creds;\n}\n\n// Utility to parse the value of an --apihost flag, permitting certain abbreviations\nfunction parseAPIHost(host: string | undefined): string | undefined {\n if (!host) {\n return undefined;\n }\n if (host.includes(':')) {\n return host;\n }\n if (host.includes('.')) {\n return 'https://' + host;\n }\n return 'https://' + host + '.doserverless.co';\n}\n\n// Deploy one project\nexport async function deployProject(\n project: string,\n cmdFlags: Flags,\n creds: Credentials | undefined,\n watching: boolean,\n logger: Logger\n): Promise<boolean> {\n let feedback: LoggerFeedback;\n if (project.startsWith('slice:') || cmdFlags.json) {\n feedback = new LoggerFeedback(new CaptureLogger());\n feedback.warnOnly = true;\n } else {\n feedback = new LoggerFeedback(logger);\n }\n\n let todeploy = await readAndPrepare(project, creds, cmdFlags, feedback);\n if (!todeploy) {\n return false;\n } else if (todeploy.error && !cmdFlags.json) {\n logger.displayError('', todeploy.error);\n return false;\n }\n if (!watching && !todeploy.slice && !cmdFlags.json) {\n displayHeader(project, todeploy.credentials, logger);\n }\n todeploy = await buildProject(todeploy);\n if (todeploy.error && !cmdFlags.json) {\n logger.displayError('', todeploy.error);\n return false;\n }\n const result: DeployResponse = await deploy(todeploy);\n if (cmdFlags.json || todeploy.slice) {\n const success = displayJSONResult(result, logger, feedback, todeploy.slice);\n if (success && todeploy.slice) {\n await deleteSlice(todeploy);\n }\n return success;\n }\n return displayResult(result, watching, logger);\n}\n\n// Display the deployment \"header\" (what we are about to deploy)\nfunction displayHeader(project: string, creds: Credentials, logger: Logger) {\n let namespaceClause = '';\n if (creds && creds.namespace) {\n namespaceClause = `\\n to namespace '${creds.namespace}'`;\n }\n let hostClause = '';\n if (creds && creds.ow.apihost) {\n hostClause = `\\n on host '${creds.ow.apihost}'`;\n }\n const projectPath = path.resolve(project);\n logger.log(`Deploying '${projectPath}'${namespaceClause}${hostClause}`);\n}\n\n// Display the result of a successful run when deploying a slice or when JSON is requested.\n// The output should be the DeployResponse as JSON on a single line, combined with the Feedback transcript if any\nfunction displayJSONResult(\n outcome: DeployResponse,\n logger: Logger,\n feedback: any,\n slice: boolean\n): boolean {\n const transcript = feedback.logger.captured;\n const result = { transcript, outcome };\n if (slice) {\n // Not using logJSON here because we need single-line output.\n // This is executing in a builder action anyway ... doesn't matter how output is produced.\n // eslint-disable-next-line no-inner-declarations\n function replaceErrors(_key: string, value: any): any {\n if (value instanceof Error) {\n const error = {};\n Object.getOwnPropertyNames(value).forEach(function (key) {\n error[key] = value[key];\n });\n return error;\n }\n return value;\n }\n const toDisplay = JSON.stringify(result, replaceErrors);\n logger.log(toDisplay);\n } else {\n // Normal JSON, print normally with indentation\n logger.logJSON(result);\n }\n return outcome.failures.length === 0;\n}\n\n// Display the result of a successful run\nfunction displayResult(\n result: DeployResponse,\n _watching: boolean,\n logger: Logger\n): boolean {\n let success = true;\n if (result.successes.length === 0 && result.failures.length === 0) {\n logger.log('\\nNothing deployed');\n } else {\n logger.log('');\n const actions: string[] = [];\n const triggers: string[] = [];\n const packages: string[] = [];\n let skippedActions = 0;\n let skippedTriggers = 0;\n let skippedPackages = 0;\n for (const success of result.successes) {\n if (success.kind === 'action') {\n if (success.skipped) {\n skippedActions++;\n } else {\n const name = success.name;\n actions.push(name);\n }\n } else if (success.kind === 'trigger') {\n if (success.skipped) {\n skippedTriggers++;\n } else {\n triggers.push(success.name);\n }\n } else if (success.kind === 'binding') {\n if (success.skipped) {\n skippedPackages++;\n } else {\n packages.push(success.name);\n }\n }\n }\n if (actions.length > 0) {\n logger.log(\n \"Deployed functions ('doctl sls fn get <funcName> --url' for URL):\"\n );\n for (const action of actions) {\n logger.log(` - ${action}`);\n }\n }\n if (skippedActions > 0) {\n logger.log(`Skipped ${skippedActions} unchanged functions`);\n }\n if (triggers.length > 0) {\n logger.log('Deployed triggers:');\n for (const trigger of triggers) {\n logger.log(` - ${trigger}`);\n }\n }\n if (skippedTriggers > 0) {\n logger.log(`Skipped ${skippedTriggers} triggers`);\n }\n if (packages.length > 0) {\n logger.log('Deployed bound packages:');\n for (const pkg of packages) {\n logger.log(` - ${pkg}`);\n }\n }\n if (skippedPackages > 0) {\n logger.log(`Skipped ${skippedPackages} bound packages`);\n }\n if (result.failures.length > 0) {\n success = false;\n logger.log('Failures:');\n for (const err of result.failures) {\n success = false;\n const context = (err as any).context;\n if (context) {\n logger.displayError(`While deploying ${context}`, err);\n } else {\n logger.displayError('', err);\n }\n }\n }\n }\n return success;\n}\n\n// Improves an error message based on analyzing the accompanying Error object (adopted from the nim CLI)\nfunction improveErrorMsg(msg: string, err?: any): string {\n const getStatusCode = (code: number) =>\n `${code} ${STATUS_CODES[code] || ''}`.trim();\n\n let pretty = '';\n if (err) {\n pretty = err.message || '';\n if (err.name === 'OpenWhiskError') {\n if (err.error && err.error.error) {\n pretty = err.error.error.toLowerCase();\n if (err.statusCode)\n pretty = `${pretty} (${getStatusCode(err.statusCode)})`;\n else if (err.error.code) pretty = `${pretty} (${err.error.code})`;\n } else if (err.statusCode) {\n pretty = getStatusCode(err.statusCode);\n }\n }\n }\n if ((pretty || '').toString().trim()) {\n msg = msg ? `${msg}: ${pretty}` : pretty;\n }\n if (!msg) {\n if (err.status) {\n msg = getStatusCode(err.status);\n } else {\n msg = 'unknown error';\n }\n }\n return msg;\n}\n", "////////////////////////////////////////////////////////////////\n// THIS FILE WAS AUTO-GENERATED BY scripts/generateVersion.sh\n// DO NOT EDIT MANUALLY\n////////////////////////////////////////////////////////////////\n\nexport const version = '5.0.20';\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoEO,IAAK,cAAL,kBAAKA,iBAAL;AACL,EAAAA,aAAA,eAAY;AADF,SAAAA;AAAA,GAAA;AAkDL,IAAM,kBAAN,MAA0C;AAAA,EAC/C,KAAK,YAAkB,gBAA6B;AAClD,YAAQ,KAAK,SAAS,GAAG,cAAc;AAAA,EACzC;AAAA,EAEA,SAAS,YAAkB,gBAA6B;AACtD,YAAQ,IAAI,SAAS,GAAG,cAAc;AAAA,EACxC;AACF;;;AC9FA,4BAA+B;AAE/B,4BAA4B;AAC5B,IAAAC,MAAoB;AACpB,SAAoB;AACpB,IAAAC,QAAsB;AACtB,wBAAsB;AACtB,mBAA8B;AAC9B,aAAwB;AACxB,WAAsB;AACtB,IAAAC,gBAAsB;AACtB,sBAAqB;;;AC5BrB,SAAoB;AACpB,WAAsB;AAQtB,mBAAwB;AAExB,IAAM,YAAQ,aAAAC,SAAY,cAAc;AAGxC,IAAM,OAAO,QAAQ,IAAI,QAAQ,aAAa,UAAU,gBAAgB;AACxE,IAAM,qBAA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OAAO,KAAK;AAAA,MACzB;AAAA,IACF;AACA,QAAI,kBAAkB,GAAG;AACvB,aAAO,IAAI,WAAW,gCAAgC;AAAA,IACxD;AACA,QAAI,OAAO,SAAS,SAAS,GAAG;AAC9B,gBAAU;AACV,aAAO,IAAI,WAAW;AACtB,iBAAW,OAAO,OAAO,UAAU;AACjC,kBAAU;AACV,cAAM,UAAW,IAAY;AAC7B,YAAI,SAAS;AACX,iBAAO,aAAa,mBAAmB,WAAW,GAAG;AAAA,QACvD,OAAO;AACL,iBAAO,aAAa,IAAI,GAAG;AAAA,QAC7B;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAGA,SAAS,gBAAgB,KAAa,KAAmB;AACvD,QAAM,gBAAgB,CAAC,SACrB,GAAG,QAAQ,yBAAa,SAAS,KAAK,KAAK;AAE7C,MAAI,SAAS;AACb,MAAI,KAAK;AACP,aAAS,IAAI,WAAW;AACxB,QAAI,IAAI,SAAS,kBAAkB;AACjC,UAAI,IAAI,SAAS,IAAI,MAAM,OAAO;AAChC,iBAAS,IAAI,MAAM,MAAM,YAAY;AACrC,YAAI,IAAI;AACN,mBAAS,GAAG,WAAW,cAAc,IAAI,UAAU;AAAA,iBAC5C,IAAI,MAAM;AAAM,mBAAS,GAAG,WAAW,IAAI,MAAM;AAAA,MAC5D,WAAW,IAAI,YAAY;AACzB,iBAAS,cAAc,IAAI,UAAU;AAAA,MACvC;AAAA,IACF;AAAA,EACF;AACA,OAAK,UAAU,IAAI,SAAS,EAAE,KAAK,GAAG;AACpC,UAAM,MAAM,GAAG,QAAQ,WAAW;AAAA,EACpC;AACA,MAAI,CAAC,KAAK;AACR,QAAI,IAAI,QAAQ;AACd,YAAM,cAAc,IAAI,MAAM;AAAA,IAChC,OAAO;AACL,YAAM;AAAA,IACR;AAAA,EACF;AACA,SAAO;AACT;",
6
+ "names": ["TriggerType", "fs", "path", "import_debug", "createDebug", "namespace", "import_debug", "debug", "isValidRuntime", "defaultRuntime", "axios", "import_axios", "import_debug", "debug", "makeDebug", "axios", "debug", "makeDebug", "defaultRemote", "keyVal", "anymatch", "path", "simplegit", "debug", "resolve", "pkg", "anymatch", "import_debug", "debug", "makeDebug", "main", "path", "fs", "path", "fs", "yaml", "import_axios", "import_debug", "path", "fs", "import_debug", "import_axios", "debug", "makeDebug", "resolve", "openwhisk", "axios", "Zip", "entry", "openwhisk", "debug", "makeDebug", "debug", "lstat", "items", "item", "ignore", "build", "main", "path", "pkg", "archiver", "resolve", "debug", "axios", "ignore", "archiver", "resolve", "touch", "import_debug", "fs", "import_util", "import_debug", "debug", "makeDebug", "path", "debug", "makeDebug", "fs", "build", "config", "import_debug", "debug", "makeDebug", "import_debug", "openwhisk", "debug", "makeDebug", "path", "debug", "openwhisk", "fs", "watch", "deployProject", "path", "import_debug", "createDebug", "msg", "parser", "doDeploy", "deployProject", "watch", "success"]
7
7
  }