@ms-cloudpack/cli 0.72.13 → 0.72.14

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.
Files changed (46) hide show
  1. package/lib/commands/bundle/execute.js +1 -1
  2. package/lib/commands/bundle/execute.js.map +1 -1
  3. package/lib/commands/init/evaluatePath.d.ts +2 -2
  4. package/lib/commands/init/evaluatePath.d.ts.map +1 -1
  5. package/lib/commands/init/evaluatePath.js +2 -2
  6. package/lib/commands/init/evaluatePath.js.map +1 -1
  7. package/lib/commands/init/init.js +148 -146
  8. package/lib/commands/init/init.js.map +1 -1
  9. package/lib/commands/link/getSessionToLink.js +1 -1
  10. package/lib/commands/link/getSessionToLink.js.map +1 -1
  11. package/lib/commands/start/execute.d.ts.map +1 -1
  12. package/lib/commands/start/execute.js +14 -4
  13. package/lib/commands/start/execute.js.map +1 -1
  14. package/lib/commands/start/getStartingAppPath.d.ts +5 -2
  15. package/lib/commands/start/getStartingAppPath.d.ts.map +1 -1
  16. package/lib/commands/start/getStartingAppPath.js +36 -9
  17. package/lib/commands/start/getStartingAppPath.js.map +1 -1
  18. package/lib/commands/sync/execute.d.ts.map +1 -1
  19. package/lib/commands/sync/execute.js +35 -33
  20. package/lib/commands/sync/execute.js.map +1 -1
  21. package/lib/types/CommandAction.d.ts +8 -0
  22. package/lib/types/CommandAction.d.ts.map +1 -1
  23. package/lib/types/CommandAction.js.map +1 -1
  24. package/lib/utilities/CommandExecutor.d.ts +2 -0
  25. package/lib/utilities/CommandExecutor.d.ts.map +1 -1
  26. package/lib/utilities/CommandExecutor.js +19 -22
  27. package/lib/utilities/CommandExecutor.js.map +1 -1
  28. package/lib/utilities/runPrerequisites.js +1 -1
  29. package/lib/utilities/runPrerequisites.js.map +1 -1
  30. package/package.json +7 -7
  31. package/lib/commands/start/createPathToChoiceMap.d.ts +0 -16
  32. package/lib/commands/start/createPathToChoiceMap.d.ts.map +0 -1
  33. package/lib/commands/start/createPathToChoiceMap.js +0 -29
  34. package/lib/commands/start/createPathToChoiceMap.js.map +0 -1
  35. package/lib/commands/start/getAppPathFromUser.d.ts +0 -9
  36. package/lib/commands/start/getAppPathFromUser.d.ts.map +0 -1
  37. package/lib/commands/start/getAppPathFromUser.js +0 -28
  38. package/lib/commands/start/getAppPathFromUser.js.map +0 -1
  39. package/lib/commands/start/getMatchingApps.d.ts +0 -9
  40. package/lib/commands/start/getMatchingApps.d.ts.map +0 -1
  41. package/lib/commands/start/getMatchingApps.js +0 -10
  42. package/lib/commands/start/getMatchingApps.js.map +0 -1
  43. package/lib/performance/registerPerformanceObservers.d.ts +0 -7
  44. package/lib/performance/registerPerformanceObservers.d.ts.map +0 -1
  45. package/lib/performance/registerPerformanceObservers.js +0 -20
  46. package/lib/performance/registerPerformanceObservers.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/commands/start/execute.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GAGrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE9F,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY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EAAE,EAAE,UAAU,CAAC,CAAC;QAC3F,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;IACzC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,OAAe,CAAC;QACpB,IAAK,GAAwB,CAAC,IAAI,KAAK,eAAe,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC;YACzE,MAAM,aAAa,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1F,OAAO;gBACL,eAAe,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,mDAAmD;oBAC3F,QAAQ,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,0DAA0D;oBAC/F,oBAAoB,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,OAAO,GAAG,8BAA+B,GAAa,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC;QACxE,CAAC;QACD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACtC,CAAC;AACH,CAAC;AAED,wBAAwB","sourcesContent":["import {\n createPartialApiContext,\n ensurePackageBundled,\n type CloudpackServer,\n type Context,\n} from '@ms-cloudpack/api-server';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { isExternalPackage, resolve } from '@ms-cloudpack/package-utilities';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport { cyan, yellow, bold } from '@ms-cloudpack/task-reporter';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { PerfMarkerCliEntry, PerfMeasurementOpenBrowser } from '../../performance/markers.js';\nimport type { CommandAction } from '../../types/CommandAction.js';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { getStartingAppPath } from './getStartingAppPath.js';\nimport { openBrowser } from './openBrowser.js';\nimport { trackSession } from './trackSession.js';\nimport type { StartOptions } from './types/StartOptions.js';\nimport { getCertificate } from '@ms-cloudpack/setup-utilities';\n\n/**\n * Defines the \"start\" verb entry point.\n */\nexport const execute: CommandAction<StartOptions> = async (params) => {\n const { options, cwd, initialize, autoDispose } = params;\n\n const appPath = await getStartingAppPath(cwd, options.app);\n const apiContextOptions = await initialize({ appPath, configOptions: { mode: options.mode } });\n const { config } = apiContextOptions;\n\n console.log('App path:', yellow(appPath));\n console.log('Bundle mode:', yellow(options.mode));\n\n runPrerequisites(apiContextOptions);\n\n const currentDir = path.dirname(fileURLToPath(import.meta.url));\n let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);\n\n // If overlay is an internal package, resolve the overlay from the current package's linked node modules\n // to \"externalize\" it, so that we always use the bundled version of the overlay instead of the source.\n if (overlayPath && !isExternalPackage(overlayPath)) {\n const cliPath = await resolve('@ms-cloudpack/cli', currentDir);\n overlayPath = cliPath ? path.join(cliPath, 'node_modules', '@ms-cloudpack/overlay') : undefined;\n }\n\n const [apiContext] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],\n overlayPath,\n }),\n );\n const { packages, session } = apiContext;\n\n // Increment the session version if caching is disabled.\n if (options.cache === false) {\n session.incrementSessionVersion();\n }\n\n // Make sure the package has a valid definition.\n const definition = await packages.get(appPath);\n\n if (options.logResolveMap) {\n // Write the resolve map to disk.\n await writeJson(path.join(appPath, 'resolve-map.json'), session.resolveMap);\n }\n\n // Start api server for tracking status and handling remote requests.\n const apiServerResult = await createApiServer(options, apiContext);\n if (apiServerResult.hasErrors) {\n return apiServerResult;\n }\n const { apiServer } = apiServerResult;\n\n // Kick off bundling app package as soon as api server is ready.\n void ensurePackageBundled({\n input: { name: definition.name, version: definition.version },\n ctx: apiContext,\n });\n\n // Then start bundle and app servers for hosting the app.\n const { startServers } = await import('@ms-cloudpack/app-server');\n const servers = await startServers(\n {\n definition,\n bundleServerOptions: { disableCache: !options.cache, port: options.bundleServerPort },\n port: options.appServerPort,\n },\n apiContext,\n );\n\n // Save the session to active sessions.\n const sessionTracker = await trackSession(session);\n\n const cleanup = async () => {\n // Stop tracking the session.\n await sessionTracker.close();\n\n await Promise.all(\n Object.entries({ apiServer, ...servers }).map(async ([name, server]) => {\n if (!server) return;\n\n const desc = `${name} (${server.url})`;\n console.info(`Closing ${desc}`);\n try {\n await server.close();\n console.info(`Closed ${desc}`);\n } catch (err) {\n console.warn(`Error closing ${desc}:`, err);\n }\n }),\n );\n };\n\n autoDispose({ dispose: cleanup });\n\n const defaultUrl = makeUrl(config.server?.defaultPath || '', session.urls.appServer).href;\n\n performance.measure(PerfMeasurementOpenBrowser, PerfMarkerCliEntry);\n\n // Open the browser.\n if (options.open !== false) {\n openBrowser(defaultUrl).catch((err) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.warn('Error opening browser:', err?.stack || err);\n console.warn('Please open the browser manually to:', defaultUrl);\n });\n } else {\n console.log('Please open the browser manually to:', defaultUrl);\n }\n\n return null; // the command should keep running\n};\n\n/**\n * Create the API server, or return an error message if the server could not be created.\n */\nasync function createApiServer(\n options: StartOptions,\n apiContext: Context,\n): Promise<{ hasErrors: false; apiServer: CloudpackServer } | { hasErrors: true; message: string }> {\n const { session } = apiContext;\n const { config } = session;\n const { server, appPath } = config;\n\n // If a cert is needed, check that it exists.\n if (server?.https === true && !(await getCertificate({ domain: server?.domain, cwd: appPath }))) {\n return {\n hasErrors: true,\n message:\n `The local site is configured to use https in cloudpack.config.json, but is missing a cert.\\n\\n` +\n `Run \"${cyan(bold('cloudpack setup'))}\" to create the required certificate and try start again.\\n`,\n };\n }\n\n const { createCloudpackServer } = await import('@ms-cloudpack/api-server');\n\n try {\n const apiServer = await createCloudpackServer({ port: options.apiServerPort }, apiContext);\n return { hasErrors: false, apiServer };\n } catch (err) {\n let message: string;\n if ((err as { code: string }).code === 'EADDRNOTAVAIL' && server?.domain) {\n const primaryDomain = (Array.isArray(server.domain) ? server.domain : [server.domain])[0];\n message =\n `The domain \"${cyan(bold(primaryDomain))}\" in cloudpack.config.json is not resolvable.\\n\\n` +\n `Run \"${cyan(bold('cloudpack setup'))}\" to add the appropriate entries to your hosts file and ` +\n `try start again.\\n`;\n } else {\n message = `Error creating API server: ${(err as Error).stack || err}`;\n }\n return { hasErrors: true, message };\n }\n}\n\n// cspell:ignore Prereqs\n"]}
1
+ {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/commands/start/execute.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,uBAAuB,EACvB,oBAAoB,GAGrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AACzD,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,iCAAiC,CAAC;AAC7E,OAAO,EAAE,OAAO,EAAE,MAAM,mCAAmC,CAAC;AAC5D,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,6BAA6B,CAAC;AACjE,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AACpC,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAElE,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAC/C,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D;;GAEG;AACH,MAAM,CAAC,MAAM,OAAO,GAAgC,KAAK,EAAE,MAAM,EAAE,EAAE;IACnE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,WAAW,EAA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AC;IACJ,CAAC;IAED,MAAM,EAAE,qBAAqB,EAAE,GAAG,MAAM,MAAM,CAAC,0BAA0B,CAAC,CAAC;IAE3E,IAAI,CAAC;QACH,MAAM,SAAS,GAAG,MAAM,qBAAqB,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,aAAa,EAAE,EAAE,UAAU,CAAC,CAAC;QAC3F,OAAO,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC;IACzC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,IAAI,OAAe,CAAC;QACpB,IAAK,GAAwB,CAAC,IAAI,KAAK,eAAe,IAAI,MAAM,EAAE,MAAM,EAAE,CAAC;YACzE,MAAM,aAAa,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1F,OAAO;gBACL,eAAe,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,mDAAmD;oBAC3F,QAAQ,IAAI,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC,0DAA0D;oBAC/F,oBAAoB,CAAC;QACzB,CAAC;aAAM,CAAC;YACN,OAAO,GAAG,8BAA+B,GAAa,CAAC,KAAK,IAAI,GAAG,EAAE,CAAC;QACxE,CAAC;QACD,OAAO,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IACtC,CAAC;AACH,CAAC;AAED,wBAAwB","sourcesContent":["import {\n createPartialApiContext,\n ensurePackageBundled,\n type CloudpackServer,\n type Context,\n} from '@ms-cloudpack/api-server';\nimport { writeJson } from '@ms-cloudpack/json-utilities';\nimport { isExternalPackage, resolve } from '@ms-cloudpack/package-utilities';\nimport { makeUrl } from '@ms-cloudpack/path-string-parsing';\nimport { cyan, yellow, bold } from '@ms-cloudpack/task-reporter';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { PerfMarkerCliEntry } from '../../performance/markers.js';\nimport type { CommandAction } from '../../types/CommandAction.js';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { getStartingAppPath } from './getStartingAppPath.js';\nimport { openBrowser } from './openBrowser.js';\nimport { trackSession } from './trackSession.js';\nimport type { StartOptions } from './types/StartOptions.js';\nimport { getCertificate } from '@ms-cloudpack/setup-utilities';\n\n/**\n * Defines the \"start\" verb entry point.\n */\nexport const execute: CommandAction<StartOptions> = async (params) => {\n const { options, cwd, initialize, autoDispose } = params;\n\n const appPathResult = await getStartingAppPath(cwd, options.app);\n if (typeof appPathResult !== 'string') {\n return appPathResult;\n }\n const appPath = appPathResult;\n const apiContextOptions = await initialize({ appPath, configOptions: { mode: options.mode } });\n const { config, telemetryClient } = apiContextOptions;\n\n console.log('App path:', yellow(appPath));\n console.log('Bundle mode:', yellow(options.mode));\n\n runPrerequisites(apiContextOptions);\n\n const currentDir = path.dirname(fileURLToPath(import.meta.url));\n let overlayPath = await resolve('@ms-cloudpack/overlay', currentDir);\n\n // If overlay is an internal package, resolve the overlay from the current package's linked node modules\n // to \"externalize\" it, so that we always use the bundled version of the overlay instead of the source.\n if (overlayPath && !isExternalPackage(overlayPath)) {\n const cliPath = await resolve('@ms-cloudpack/cli', currentDir);\n overlayPath = cliPath ? path.join(cliPath, 'node_modules', '@ms-cloudpack/overlay') : undefined;\n }\n\n const [apiContext] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['bus', 'watcher', 'taskRunner', 'packages', 'session', 'packageImportPaths', 'packageHashes'],\n overlayPath,\n }),\n );\n const { packages, session } = apiContext;\n\n // Increment the session version if caching is disabled.\n if (options.cache === false) {\n session.incrementSessionVersion();\n }\n\n // Make sure the package has a valid definition.\n const definition = await packages.get(appPath);\n\n if (options.logResolveMap) {\n // Write the resolve map to disk.\n await writeJson(path.join(appPath, 'resolve-map.json'), session.resolveMap);\n }\n\n // Start api server for tracking status and handling remote requests.\n const apiServerResult = await createApiServer(options, apiContext);\n if (apiServerResult.hasErrors) {\n return apiServerResult;\n }\n const { apiServer } = apiServerResult;\n\n // Kick off bundling app package as soon as api server is ready.\n void ensurePackageBundled({\n input: { name: definition.name, version: definition.version },\n ctx: apiContext,\n });\n\n // Then start bundle and app servers for hosting the app.\n const { startServers } = await import('@ms-cloudpack/app-server');\n const servers = await startServers(\n {\n definition,\n bundleServerOptions: { disableCache: !options.cache, port: options.bundleServerPort },\n port: options.appServerPort,\n },\n apiContext,\n );\n\n // Save the session to active sessions.\n const sessionTracker = await trackSession(session);\n\n const cleanup = async () => {\n // Stop tracking the session.\n await sessionTracker.close();\n\n await Promise.all(\n Object.entries({ apiServer, ...servers }).map(async ([name, server]) => {\n if (!server) return;\n\n const desc = `${name} (${server.url})`;\n console.info(`Closing ${desc}`);\n try {\n await server.close();\n console.info(`Closed ${desc}`);\n } catch (err) {\n console.warn(`Error closing ${desc}:`, err);\n }\n }),\n );\n };\n\n autoDispose({ dispose: cleanup });\n\n const defaultUrl = makeUrl(config.server?.defaultPath || '', session.urls.appServer).href;\n\n const cliEntryMarker = performance.getEntriesByName(PerfMarkerCliEntry, 'mark')[0];\n if (cliEntryMarker) {\n telemetryClient.tracer.startSpan('TIME_TO_OPEN_BROWSER', { startTime: cliEntryMarker.startTime }).end();\n } else {\n throw new Error('TIME_TO_OPEN_BROWSER marker not found');\n }\n\n // Open the browser.\n if (options.open !== false) {\n openBrowser(defaultUrl).catch((err) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n console.warn('Error opening browser:', err?.stack || err);\n console.warn('Please open the browser manually to:', defaultUrl);\n });\n } else {\n console.log('Please open the browser manually to:', defaultUrl);\n }\n\n return null; // the command should keep running\n};\n\n/**\n * Create the API server, or return an error message if the server could not be created.\n */\nasync function createApiServer(\n options: StartOptions,\n apiContext: Context,\n): Promise<{ hasErrors: false; apiServer: CloudpackServer } | { hasErrors: true; message: string }> {\n const { session } = apiContext;\n const { config } = session;\n const { server, appPath } = config;\n\n // If a cert is needed, check that it exists.\n if (server?.https === true && !(await getCertificate({ domain: server?.domain, cwd: appPath }))) {\n return {\n hasErrors: true,\n message:\n `The local site is configured to use https in cloudpack.config.json, but is missing a cert.\\n\\n` +\n `Run \"${cyan(bold('cloudpack setup'))}\" to create the required certificate and try start again.\\n`,\n };\n }\n\n const { createCloudpackServer } = await import('@ms-cloudpack/api-server');\n\n try {\n const apiServer = await createCloudpackServer({ port: options.apiServerPort }, apiContext);\n return { hasErrors: false, apiServer };\n } catch (err) {\n let message: string;\n if ((err as { code: string }).code === 'EADDRNOTAVAIL' && server?.domain) {\n const primaryDomain = (Array.isArray(server.domain) ? server.domain : [server.domain])[0];\n message =\n `The domain \"${cyan(bold(primaryDomain))}\" in cloudpack.config.json is not resolvable.\\n\\n` +\n `Run \"${cyan(bold('cloudpack setup'))}\" to add the appropriate entries to your hosts file and ` +\n `try start again.\\n`;\n } else {\n message = `Error creating API server: ${(err as Error).stack || err}`;\n }\n return { hasErrors: true, message };\n }\n}\n\n// cspell:ignore Prereqs\n"]}
@@ -1,10 +1,13 @@
1
+ import type { CommandExitParams } from '../../types/CommandAction.js';
2
+ export declare const appPromptQuestionName = "app";
3
+ export type AppPromptKeys = typeof appPromptQuestionName;
1
4
  /**
2
5
  * Gets the appPath from which Cloudpack will start. If the CWD is a Cloudpack-enabled app,
3
6
  * we'll start there; otherwise, we'll scan for Cloudpack-enabled app and present the user
4
7
  * with a menu. If no app are found, Cloudpack will just try to start the CWD anyway.
5
8
  * @param cwd - The current working directory to start in when finding the starting app path
6
9
  * @param desiredApp - The app that should be started as specified via --app arg
7
- * @returns The app path of the app that Cloudpack should start
10
+ * @returns The app path of the app that Cloudpack should start, or an exit options object if the user cancels
8
11
  */
9
- export declare function getStartingAppPath(cwd: string, desiredApp?: string): Promise<string>;
12
+ export declare function getStartingAppPath(cwd: string, desiredApp?: string): Promise<string | CommandExitParams>;
10
13
  //# sourceMappingURL=getStartingAppPath.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"getStartingAppPath.d.ts","sourceRoot":"","sources":["../../../src/commands/start/getStartingAppPath.ts"],"names":[],"mappings":"AAMA;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,mBAgBxE"}
1
+ {"version":3,"file":"getStartingAppPath.d.ts","sourceRoot":"","sources":["../../../src/commands/start/getStartingAppPath.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AAEtE,eAAO,MAAM,qBAAqB,QAAQ,CAAC;AAC3C,MAAM,MAAM,aAAa,GAAG,OAAO,qBAAqB,CAAC;AAEzD;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,iBAAiB,CAAC,CAoD9G"}
@@ -1,15 +1,16 @@
1
- import { findCloudpackAppPaths } from '../../utilities/findCloudpackAppPaths.js';
1
+ import { PackageDefinitions } from '@ms-cloudpack/package-utilities';
2
2
  import fs from 'fs';
3
3
  import path from 'path';
4
- import { createPathToChoiceMap } from './createPathToChoiceMap.js';
5
- import { getAppPathFromUser } from './getAppPathFromUser.js';
4
+ import prompts from 'prompts';
5
+ import { findCloudpackAppPaths } from '../../utilities/findCloudpackAppPaths.js';
6
+ export const appPromptQuestionName = 'app';
6
7
  /**
7
8
  * Gets the appPath from which Cloudpack will start. If the CWD is a Cloudpack-enabled app,
8
9
  * we'll start there; otherwise, we'll scan for Cloudpack-enabled app and present the user
9
10
  * with a menu. If no app are found, Cloudpack will just try to start the CWD anyway.
10
11
  * @param cwd - The current working directory to start in when finding the starting app path
11
12
  * @param desiredApp - The app that should be started as specified via --app arg
12
- * @returns The app path of the app that Cloudpack should start
13
+ * @returns The app path of the app that Cloudpack should start, or an exit options object if the user cancels
13
14
  */
14
15
  export async function getStartingAppPath(cwd, desiredApp) {
15
16
  const cwdIsCloudpackApp = fs.existsSync(path.resolve(path.join(cwd, 'cloudpack.config.json')));
@@ -20,13 +21,39 @@ export async function getStartingAppPath(cwd, desiredApp) {
20
21
  if (folderPaths.length === 0) {
21
22
  return cwd;
22
23
  }
23
- else if (folderPaths.length === 1) {
24
+ if (folderPaths.length === 1) {
24
25
  return folderPaths[0];
25
26
  }
26
- else {
27
- const pathToCloudpackConfigMap = await createPathToChoiceMap(folderPaths);
28
- const appPath = await getAppPathFromUser(pathToCloudpackConfigMap, desiredApp);
29
- return appPath ?? cwd;
27
+ const packages = new PackageDefinitions();
28
+ const choices = await Promise.all(folderPaths.map(async (dir) => {
29
+ const pkg = await packages.get(dir);
30
+ return {
31
+ title: pkg.name,
32
+ description: pkg?.description ?? 'An awesome app that would be even more awesome with a proper description',
33
+ value: dir,
34
+ };
35
+ }));
36
+ choices.sort((c1, c2) => c1.title.localeCompare(c2.title));
37
+ if (desiredApp) {
38
+ const matchingApps = choices.filter((choice) => choice.title.includes(desiredApp));
39
+ if (matchingApps.length === 1) {
40
+ return matchingApps[0].value;
41
+ }
42
+ const exactMatch = matchingApps.find((choice) => choice.title === desiredApp);
43
+ if (exactMatch) {
44
+ return exactMatch.value;
45
+ }
46
+ }
47
+ const response = await prompts({
48
+ type: 'select',
49
+ name: appPromptQuestionName,
50
+ message: 'Select the app you want to start',
51
+ choices,
52
+ });
53
+ // This will be undefined if the user cancels the prompt
54
+ if (!response.app) {
55
+ return { isInterrupted: true, message: '' };
30
56
  }
57
+ return response.app;
31
58
  }
32
59
  //# sourceMappingURL=getStartingAppPath.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"getStartingAppPath.js","sourceRoot":"","sources":["../../../src/commands/start/getStartingAppPath.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AACjF,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAE7D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,GAAW,EAAE,UAAmB;IACvE,MAAM,iBAAiB,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,uBAAuB,CAAC,CAAC,CAAC,CAAC;IAC/F,IAAI,iBAAiB,EAAE,CAAC;QACtB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,WAAW,GAAG,qBAAqB,CAAC,GAAG,CAAC,CAAC;IAC/C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO,GAAG,CAAC;IACb,CAAC;SAAM,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QACpC,OAAO,WAAW,CAAC,CAAC,CAAC,CAAC;IACxB,CAAC;SAAM,CAAC;QACN,MAAM,wBAAwB,GAAG,MAAM,qBAAqB,CAAC,WAAW,CAAC,CAAC;QAC1E,MAAM,OAAO,GAAG,MAAM,kBAAkB,CAAC,wBAAwB,EAAE,UAAU,CAAC,CAAC;QAC/E,OAAO,OAAO,IAAI,GAAG,CAAC;IACxB,CAAC;AACH,CAAC","sourcesContent":["import { findCloudpackAppPaths } from '../../utilities/findCloudpackAppPaths.js';\nimport fs from 'fs';\nimport path from 'path';\nimport { createPathToChoiceMap } from './createPathToChoiceMap.js';\nimport { getAppPathFromUser } from './getAppPathFromUser.js';\n\n/**\n * Gets the appPath from which Cloudpack will start. If the CWD is a Cloudpack-enabled app,\n * we'll start there; otherwise, we'll scan for Cloudpack-enabled app and present the user\n * with a menu. If no app are found, Cloudpack will just try to start the CWD anyway.\n * @param cwd - The current working directory to start in when finding the starting app path\n * @param desiredApp - The app that should be started as specified via --app arg\n * @returns The app path of the app that Cloudpack should start\n */\nexport async function getStartingAppPath(cwd: string, desiredApp?: string) {\n const cwdIsCloudpackApp = fs.existsSync(path.resolve(path.join(cwd, 'cloudpack.config.json')));\n if (cwdIsCloudpackApp) {\n return cwd;\n }\n\n const folderPaths = findCloudpackAppPaths(cwd);\n if (folderPaths.length === 0) {\n return cwd;\n } else if (folderPaths.length === 1) {\n return folderPaths[0];\n } else {\n const pathToCloudpackConfigMap = await createPathToChoiceMap(folderPaths);\n const appPath = await getAppPathFromUser(pathToCloudpackConfigMap, desiredApp);\n return appPath ?? cwd;\n }\n}\n"]}
1
+ {"version":3,"file":"getStartingAppPath.js","sourceRoot":"","sources":["../../../src/commands/start/getStartingAppPath.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AACrE,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,OAAwB,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,0CAA0C,CAAC;AAGjF,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAG3C;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,kBAAkB,CAAC,GAAW,EAAE,UAAmB;IACvE,MAAM,iBAAiB,GAAG,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,uBAAuB,CAAC,CAAC,CAAC,CAAC;IAC/F,IAAI,iBAAiB,EAAE,CAAC;QACtB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,MAAM,WAAW,GAAG,qBAAqB,CAAC,GAAG,CAAC,CAAC;IAC/C,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC7B,OAAO,GAAG,CAAC;IACb,CAAC;IACD,IAAI,WAAW,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC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KACR,CAAC,CAAC;IAEH,wDAAwD;IACxD,IAAI,CAAC,QAAQ,CAAC,GAAG,EAAE,CAAC;QAClB,OAAO,EAAE,aAAa,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IAC9C,CAAC;IAED,OAAO,QAAQ,CAAC,GAAa,CAAC;AAChC,CAAC","sourcesContent":["import { PackageDefinitions } from '@ms-cloudpack/package-utilities';\nimport fs from 'fs';\nimport path from 'path';\nimport prompts, { type Choice } from 'prompts';\nimport { findCloudpackAppPaths } from '../../utilities/findCloudpackAppPaths.js';\nimport type { CommandExitParams } from '../../types/CommandAction.js';\n\nexport const appPromptQuestionName = 'app';\nexport type AppPromptKeys = typeof appPromptQuestionName;\n\n/**\n * Gets the appPath from which Cloudpack will start. If the CWD is a Cloudpack-enabled app,\n * we'll start there; otherwise, we'll scan for Cloudpack-enabled app and present the user\n * with a menu. If no app are found, Cloudpack will just try to start the CWD anyway.\n * @param cwd - The current working directory to start in when finding the starting app path\n * @param desiredApp - The app that should be started as specified via --app arg\n * @returns The app path of the app that Cloudpack should start, or an exit options object if the user cancels\n */\nexport async function getStartingAppPath(cwd: string, desiredApp?: string): Promise<string | CommandExitParams> {\n const cwdIsCloudpackApp = fs.existsSync(path.resolve(path.join(cwd, 'cloudpack.config.json')));\n if (cwdIsCloudpackApp) {\n return cwd;\n }\n\n const folderPaths = findCloudpackAppPaths(cwd);\n if (folderPaths.length === 0) {\n return cwd;\n }\n if (folderPaths.length === 1) {\n return folderPaths[0];\n }\n\n const packages = new PackageDefinitions();\n\n const choices = await Promise.all<Choice>(\n folderPaths.map(async (dir) => {\n const pkg = await packages.get(dir);\n return {\n title: pkg.name,\n description: pkg?.description ?? 'An awesome app that would be even more awesome with a proper description',\n value: dir,\n };\n }),\n );\n choices.sort((c1, c2) => c1.title.localeCompare(c2.title));\n\n if (desiredApp) {\n const matchingApps = choices.filter((choice) => choice.title.includes(desiredApp));\n if (matchingApps.length === 1) {\n return matchingApps[0].value as string;\n }\n const exactMatch = matchingApps.find((choice) => choice.title === desiredApp);\n if (exactMatch) {\n return exactMatch.value as string;\n }\n }\n\n const response = await prompts<AppPromptKeys>({\n type: 'select',\n name: appPromptQuestionName,\n message: 'Select the app you want to start',\n choices,\n });\n\n // This will be undefined if the user cancels the prompt\n if (!response.app) {\n return { isInterrupted: true, message: '' };\n }\n\n return response.app as string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/commands/sync/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAAqD,KAAK,aAAa,EAAE,MAAM,8BAA8B,CAAC;AAUrH,eAAO,MAAM,OAAO,EAAE,aAAa,CAAC,WAAW,CAiF9C,CAAC"}
1
+ {"version":3,"file":"execute.d.ts","sourceRoot":"","sources":["../../../src/commands/sync/execute.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAC1D,OAAO,EAGL,KAAK,aAAa,EAEnB,MAAM,8BAA8B,CAAC;AAUtC,eAAO,MAAM,OAAO,EAAE,aAAa,CAAC,WAAW,CAiF9C,CAAC"}
@@ -1,4 +1,4 @@
1
- import { ExitCodeAuthenticationError, ExitCodeGenericError } from '../../types/CommandAction.js';
1
+ import { ExitCodeAuthenticationError, ExitCodeGenericError, } from '../../types/CommandAction.js';
2
2
  import { createPartialApiContext, syncDownload, syncUpload } from '@ms-cloudpack/api-server';
3
3
  import { runPrerequisites } from '../../utilities/runPrerequisites.js';
4
4
  import { isSyncDisabledByUser } from './isSyncDisabledByUser.js';
@@ -11,43 +11,45 @@ export const execute = async (params) => {
11
11
  const { login, upload } = options;
12
12
  const apiContextOptions = await initialize({ appPath: cwd });
13
13
  const { config, telemetryClient } = apiContextOptions;
14
- if (!config.features?.syncBundles) {
15
- return { message: 'Sync is disabled' };
16
- }
17
- if (isSyncDisabledByUser()) {
18
- telemetryClient.rootSpan.setAttribute('syncDisabled', true);
19
- return { message: 'CLOUDPACK_SYNC environment variable is set. Sync is disabled by the user.' };
20
- }
21
14
  try {
22
- const remoteCacheConfig = config.remoteCache;
23
- if (!remoteCacheConfig) {
24
- return {
25
- message: 'Remote cache is not configured. Please add remoteCache to your cloudpack.config.json file to use this feature.',
15
+ // Await here to ensure that try-catch block catches any errors thrown inside the async function
16
+ return await telemetryClient.tracer.startActiveSpan('SYNC_EXECUTE', async (span) => {
17
+ if (!config.features?.syncBundles) {
18
+ return { message: 'Sync is disabled' };
19
+ }
20
+ if (isSyncDisabledByUser()) {
21
+ span.setAttribute('syncDisabled', true);
22
+ return { message: 'CLOUDPACK_SYNC environment variable is set. Sync is disabled by the user.' };
23
+ }
24
+ const remoteCacheConfig = config.remoteCache;
25
+ if (!remoteCacheConfig) {
26
+ return {
27
+ message: 'Remote cache is not configured. Please add remoteCache to your cloudpack.config.json file to use this feature.',
28
+ };
29
+ }
30
+ const input = {
31
+ loginMethod: login,
26
32
  };
27
- }
28
- const input = {
29
- loginMethod: login,
30
- };
31
- if (upload) {
32
- runPrerequisites(apiContextOptions);
33
- const [ctx] = autoDispose(await createPartialApiContext({
34
- ...apiContextOptions,
35
- items: ['bus', 'taskRunner', 'watcher', 'packages', 'session', 'packageImportPaths', 'packageHashes'],
36
- }));
37
- await syncUpload({ input, ctx });
38
- }
39
- else {
40
- const [ctx] = autoDispose(await createPartialApiContext({
41
- ...apiContextOptions,
42
- items: ['packages', 'session', 'packageHashes'],
43
- }));
44
- await syncDownload({ input, ctx });
45
- }
46
- return { message: 'Sync complete' };
33
+ if (upload) {
34
+ runPrerequisites(apiContextOptions);
35
+ const [ctx] = autoDispose(await createPartialApiContext({
36
+ ...apiContextOptions,
37
+ items: ['bus', 'taskRunner', 'watcher', 'packages', 'session', 'packageImportPaths', 'packageHashes'],
38
+ }));
39
+ await syncUpload({ input, ctx });
40
+ }
41
+ else {
42
+ const [ctx] = autoDispose(await createPartialApiContext({
43
+ ...apiContextOptions,
44
+ items: ['packages', 'session', 'packageHashes'],
45
+ }));
46
+ await syncDownload({ input, ctx });
47
+ }
48
+ return { message: 'Sync complete' };
49
+ });
47
50
  }
48
51
  catch (error) {
49
52
  if (error instanceof Error) {
50
- telemetryClient.rootSpan.recordException(error);
51
53
  if (error.name === 'AuthenticationRequiredError' && error.message.includes('CrossPlatformLockError')) {
52
54
  return {
53
55
  message: red(`Cloudpack encountered an issue acquiring authentication lock. It seems Cloudpack Sync may already be active in another process. Please wait for the current process to complete and then try again`),
@@ -1 +1 @@
1
- {"version":3,"file":"execute.js","sourceRoot":"","sources":["../../../src/commands/sync/execute.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,2BAA2B,EAAE,oBAAoB,EAAsB,MAAM,8BAA8B,CAAC;AACrH,OAAO,EAAE,uBAAuB,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAC7F,OAAO,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AACvE,OAAO,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACjE,OAAO,EAAE,GAAG,EAAE,MAAM,6BAA6B,CAAC;AAElD,SAAS,cAAc,CAAC,KAAc,EAAE,IAAY;IAClD,OAAO,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,IAAI,KAAK,CAAC,IAAI,KAAK,IAAI,CAAC;AAC1E,CAAC;AAED,MAAM,CAAC,MAAM,OAAO,GAA+B,KAAK,EAAE,MAAM,EAAE,EAAE;IAClE,MAAM,EAAE,OAAO,EAAE,GAAG,EAAE,UAAU,EAAE,WAAW,EAAE,GAAG,MAAM,CAAC;IACzD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC;IAClC,MAAM,iBAAiB,GAAG,MAAM,UAAU,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,CAAC,CAAC;IAC7D,MAAM,EAAE,MAAM,EAAE,eAAe,EAAE,G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ACtC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;YAC3B,eAAe,CAAC,QAAQ,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;YAEhD,IAAI,KAAK,CAAC,IAAI,KAAK,6BAA6B,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,wBAAwB,CAAC,EAAE,CAAC;gBACrG,OAAO;oBACL,OAAO,EAAE,GAAG,CACV,oMAAoM,CACrM;oBACD,QAAQ,EAAE,oBAAoB;iBAC/B,CAAC;YACJ,CAAC;YACD,IACE,KAAK,CAAC,IAAI,KAAK,6BAA6B;gBAC5C,CAAC,YAAY,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,KAAK,IAAI,KAAK,CAAC,UAAU,KAAK,KAAK,CAAC,CAAC,EACrF,CAAC;gBACD,OAAO;oBACL,OAAO,EAAE,GAAG,CAAC,oEAAoE,CAAC;oBAClF,QAAQ,EAAE,2BAA2B;iBACtC,CAAC;YACJ,CAAC;YAED,IAAI,cAAc,CAAC,KAAK,EAAE,oBAAoB,CAAC,EAAE,CAAC;gBAChD,OAAO;oBACL,OAAO,EAAE,GAAG,CAAC,+DAA+D,CAAC;oBAC7E,QAAQ,EAAE,oBAAoB;iBAC/B,CAAC;YACJ,CAAC;QACH,CAAC;QAED,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAC","sourcesContent":["import type { SyncOptions } from './types/SyncOptions.js';\nimport { ExitCodeAuthenticationError, ExitCodeGenericError, type CommandAction } from '../../types/CommandAction.js';\nimport { createPartialApiContext, syncDownload, syncUpload } from '@ms-cloudpack/api-server';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { isSyncDisabledByUser } from './isSyncDisabledByUser.js';\nimport { red } from '@ms-cloudpack/task-reporter';\n\nfunction checkErrorCode(error: unknown, code: string) {\n return error instanceof Error && 'code' in error && error.code === code;\n}\n\nexport const execute: CommandAction<SyncOptions> = async (params) => {\n const { options, cwd, initialize, autoDispose } = params;\n const { login, upload } = options;\n const apiContextOptions = await initialize({ appPath: cwd });\n const { config, telemetryClient } = apiContextOptions;\n\n if (!config.features?.syncBundles) {\n return { message: 'Sync is disabled' };\n }\n\n if (isSyncDisabledByUser()) {\n telemetryClient.rootSpan.setAttribute('syncDisabled', true);\n return { message: 'CLOUDPACK_SYNC environment variable is set. Sync is disabled by the user.' };\n }\n\n try {\n const remoteCacheConfig = config.remoteCache;\n if (!remoteCacheConfig) {\n return {\n message:\n 'Remote cache is not configured. Please add remoteCache to your cloudpack.config.json file to use this feature.',\n };\n }\n\n const input = {\n loginMethod: login,\n };\n\n if (upload) {\n runPrerequisites(apiContextOptions);\n\n const [ctx] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['bus', 'taskRunner', 'watcher', 'packages', 'session', 'packageImportPaths', 'packageHashes'],\n }),\n );\n await syncUpload({ input, ctx });\n } else {\n const [ctx] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['packages', 'session', 'packageHashes'],\n }),\n );\n await syncDownload({ input, ctx });\n }\n\n return { message: 'Sync complete' };\n } catch (error) {\n if (error instanceof Error) {\n telemetryClient.rootSpan.recordException(error);\n\n if (error.name === 'AuthenticationRequiredError' && error.message.includes('CrossPlatformLockError')) {\n return {\n message: red(\n `Cloudpack encountered an issue acquiring authentication lock. It seems Cloudpack Sync may already be active in another process. Please wait for the current process to complete and then try again`,\n ),\n exitCode: ExitCodeGenericError,\n };\n }\n if (\n error.name === 'AuthenticationRequiredError' ||\n ('statusCode' in error && (error.statusCode === '401' || error.statusCode === '403'))\n ) {\n return {\n message: red('Authentication error. Please check your credentials and try again.'),\n exitCode: ExitCodeAuthenticationError,\n };\n }\n\n if (checkErrorCode(error, 'REQUEST_SEND_ERROR')) {\n return {\n message: red('Connection error. Please check your connection and try again.'),\n exitCode: ExitCodeGenericError,\n };\n }\n }\n\n throw error;\n }\n};\n"]}
1
+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AAG,CACV,oMAAoM,CACrM;oBACD,QAAQ,EAAE,oBAAoB;iBAC/B,CAAC;YACJ,CAAC;YACD,IACE,KAAK,CAAC,IAAI,KAAK,6BAA6B;gBAC5C,CAAC,YAAY,IAAI,KAAK,IAAI,CAAC,KAAK,CAAC,UAAU,KAAK,KAAK,IAAI,KAAK,CAAC,UAAU,KAAK,KAAK,CAAC,CAAC,EACrF,CAAC;gBACD,OAAO;oBACL,OAAO,EAAE,GAAG,CAAC,oEAAoE,CAAC;oBAClF,QAAQ,EAAE,2BAA2B;iBACtC,CAAC;YACJ,CAAC;YAED,IAAI,cAAc,CAAC,KAAK,EAAE,oBAAoB,CAAC,EAAE,CAAC;gBAChD,OAAO;oBACL,OAAO,EAAE,GAAG,CAAC,+DAA+D,CAAC;oBAC7E,QAAQ,EAAE,oBAAoB;iBAC/B,CAAC;YACJ,CAAC;QACH,CAAC;QAED,MAAM,KAAK,CAAC;IACd,CAAC;AACH,CAAC,CAAC","sourcesContent":["import type { SyncOptions } from './types/SyncOptions.js';\nimport {\n ExitCodeAuthenticationError,\n ExitCodeGenericError,\n type CommandAction,\n type CommandExitParams,\n} from '../../types/CommandAction.js';\nimport { createPartialApiContext, syncDownload, syncUpload } from '@ms-cloudpack/api-server';\nimport { runPrerequisites } from '../../utilities/runPrerequisites.js';\nimport { isSyncDisabledByUser } from './isSyncDisabledByUser.js';\nimport { red } from '@ms-cloudpack/task-reporter';\n\nfunction checkErrorCode(error: unknown, code: string) {\n return error instanceof Error && 'code' in error && error.code === code;\n}\n\nexport const execute: CommandAction<SyncOptions> = async (params) => {\n const { options, cwd, initialize, autoDispose } = params;\n const { login, upload } = options;\n const apiContextOptions = await initialize({ appPath: cwd });\n const { config, telemetryClient } = apiContextOptions;\n try {\n // Await here to ensure that try-catch block catches any errors thrown inside the async function\n return await telemetryClient.tracer.startActiveSpan('SYNC_EXECUTE', async (span): Promise<CommandExitParams> => {\n if (!config.features?.syncBundles) {\n return { message: 'Sync is disabled' };\n }\n\n if (isSyncDisabledByUser()) {\n span.setAttribute('syncDisabled', true);\n return { message: 'CLOUDPACK_SYNC environment variable is set. Sync is disabled by the user.' };\n }\n\n const remoteCacheConfig = config.remoteCache;\n if (!remoteCacheConfig) {\n return {\n message:\n 'Remote cache is not configured. Please add remoteCache to your cloudpack.config.json file to use this feature.',\n };\n }\n\n const input = {\n loginMethod: login,\n };\n\n if (upload) {\n runPrerequisites(apiContextOptions);\n\n const [ctx] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['bus', 'taskRunner', 'watcher', 'packages', 'session', 'packageImportPaths', 'packageHashes'],\n }),\n );\n await syncUpload({ input, ctx });\n } else {\n const [ctx] = autoDispose(\n await createPartialApiContext({\n ...apiContextOptions,\n items: ['packages', 'session', 'packageHashes'],\n }),\n );\n await syncDownload({ input, ctx });\n }\n\n return { message: 'Sync complete' };\n });\n } catch (error) {\n if (error instanceof Error) {\n if (error.name === 'AuthenticationRequiredError' && error.message.includes('CrossPlatformLockError')) {\n return {\n message: red(\n `Cloudpack encountered an issue acquiring authentication lock. It seems Cloudpack Sync may already be active in another process. Please wait for the current process to complete and then try again`,\n ),\n exitCode: ExitCodeGenericError,\n };\n }\n if (\n error.name === 'AuthenticationRequiredError' ||\n ('statusCode' in error && (error.statusCode === '401' || error.statusCode === '403'))\n ) {\n return {\n message: red('Authentication error. Please check your credentials and try again.'),\n exitCode: ExitCodeAuthenticationError,\n };\n }\n\n if (checkErrorCode(error, 'REQUEST_SEND_ERROR')) {\n return {\n message: red('Connection error. Please check your connection and try again.'),\n exitCode: ExitCodeGenericError,\n };\n }\n }\n\n throw error;\n }\n};\n"]}
@@ -18,9 +18,17 @@ export declare const ExitCodeGenericError = 1;
18
18
  export declare const ExitCodeAuthenticationError = 2;
19
19
  export type ExitCode = typeof ExitCodeSuccessful | typeof ExitCodeGenericError | typeof ExitCodeAuthenticationError;
20
20
  export interface CommandExitParams {
21
+ /**
22
+ * Message to show on exit.
23
+ * If `isInterrupted` is true, use an empty string (it will show a default interrupt message).
24
+ */
21
25
  message: string;
26
+ /** Whether there are errors. By default, checks the reporter for failed tasks. */
22
27
  hasErrors?: boolean;
28
+ /** Exit code to use. Defaults to 1 if there are errors, 0 if not. */
23
29
  exitCode?: ExitCode;
30
+ /** True if the user interrupted an operation (ctrl+C). Sets the message automatically. */
31
+ isInterrupted?: true;
24
32
  }
25
33
  export interface CommandActionParams<TOptions extends object> {
26
34
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"CommandAction.d.ts","sourceRoot":"","sources":["../../src/types/CommandAction.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,0BAA0B,CAAC;AACtE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,IAAI,CAClC,qBAAqB,EACrB,SAAS,GAAG,WAAW,GAAG,QAAQ,GAAG,UAAU,GAAG,iBAAiB,CACpE,CAAC;AAEF,8CAA8C;AAC9C,MAAM,WAAW,wBAAwB;IACvC,+DAA+D;IAC/D,aAAa,CAAC,EAAE,iBAAiB,CAAC;CACnC;AAED,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC;AACtC,eAAO,MAAM,2BAA2B,IAAI,CAAC;AAC7C,MAAM,MAAM,QAAQ,GAAG,OAAO,kBAAkB,GAAG,OAAO,oBAAoB,GAAG,OAAO,2BAA2B,CAAC;AAEpH,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,QAAQ,CAAC,EAAE,QAAQ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,CAAC;QAChG,CAAC,iBAAiB,EAAE,wBAAwB,GAAG;YAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;SAAE,GAAG,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAAC;KACtG,CAAC;IAEF;;OAEG;IACH,0BAA0B,EAAE,CAAC,UAAU,EAAE,MAAM,MAAM,KAAK,IAAI,CAAC;CAChE;AAED;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,CAAC,QAAQ,IAAI,CACpC,MAAM,EAAE,mBAAmB,CAAC,QAAQ,GAAG,aAAa,CAAC,KAClD,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC,CAAC;AAEvC,MAAM,MAAM,mBAAmB,CAAC,QAAQ,IAAI;IAC1C,OAAO,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;CAClC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"CommandAction.js","sourceRoot":"","sources":["../../src/types/CommandAction.ts"],"names":[],"mappings":"AAqBA,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AACpC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AACtC,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC","sourcesContent":["import type { LazyApiContextOptions } from '@ms-cloudpack/api-server';\nimport type { ReadConfigOptions } from '@ms-cloudpack/config';\nimport type { TaskReporter } from '@ms-cloudpack/task-reporter';\nimport type { AutoDispose } from './AutoDispose.js';\nimport type { SharedOptions } from './SharedOptions.js';\n\n/**\n * Context for running a command in a specific app (after initialization).\n * For convenience, this can be passed/spread directly to `createPartialApiContext`.\n */\nexport type AppCommandContext = Pick<\n LazyApiContextOptions,\n 'appPath' | 'cachePath' | 'config' | 'reporter' | 'telemetryClient'\n>;\n\n/** Initialize options excluding `appPaths` */\nexport interface CommandInitializeOptions {\n /** Additional options to merge in while reading the config. */\n configOptions?: ReadConfigOptions;\n}\n\nexport const ExitCodeSuccessful = 0;\nexport const ExitCodeGenericError = 1;\nexport const ExitCodeAuthenticationError = 2;\nexport type ExitCode = typeof ExitCodeSuccessful | typeof ExitCodeGenericError | typeof ExitCodeAuthenticationError;\n\nexport interface CommandExitParams {\n message: string;\n hasErrors?: boolean;\n exitCode?: ExitCode;\n}\n\nexport interface CommandActionParams<TOptions extends object> {\n /**\n * Initial working directory (usually `process.cwd()` except in tests).\n * Note that this may differ from the `appPath` used by individual commands.\n */\n cwd: string;\n\n /**\n * Command-specific options, parsed from `process.argv`.\n * Types are generally defined in each command's `src/commands/<name>/types/<Name>Types.ts` module.\n * The command line options are defined in each command's `src/commands/<name>/index.ts` module.\n */\n options: TOptions;\n\n /**\n * Command-specific arguments. Arguments in commander are positional arguments that are not options.\n * For example, in `echo somestring`, `somestring` is an argument.\n */\n args: string[];\n\n reporter: TaskReporter;\n\n abortSignal: AbortSignal;\n\n /**\n * Function that can be called with any `Disposable`s that should be cleaned up automatically\n * when the program exits. (See `AutoDisposableList.add` for implementation.)\n */\n autoDispose: AutoDispose;\n\n /**\n * This should be called at or near the beginning of the action to initialize the config,\n * telemetry, and reporting. (See `CommandExecutor._initialize` for implementation.)\n * `initialize` can be called with either a single string, `appPath` or an a string[], `appPaths`.\n *\n * If it is called with a single string, it returns `Promise<AppCommandContext>`\n * If it is called with a string[], it returns `Promise<AppCommandContext[]>`\n */\n initialize: {\n (initializeOptions: CommandInitializeOptions & { appPath: string }): Promise<AppCommandContext>;\n (initializeOptions: CommandInitializeOptions & { appPaths: string[] }): Promise<AppCommandContext[]>;\n };\n\n /**\n * Set a callback to get the message to display if ctrl+C is pressed.\n */\n setInterruptMessageHandler: (getMessage: () => string) => void;\n}\n\n/**\n * Command action function (executor). This is the type of the `execute` function which should\n * be exported from each command's `src/commands/<name>/execute.ts` module.\n *\n * If it returns an object, the command wrapper will call the exit handler with that object.\n * If it returns null, it's assumed that this command is meant to keep running, such as `start`.\n */\nexport type CommandAction<TOptions> = (\n params: CommandActionParams<TOptions & SharedOptions>,\n) => Promise<CommandExitParams | null>;\n\nexport type CommandActionModule<TOptions> = {\n execute: CommandAction<TOptions>;\n};\n"]}
1
+ {"version":3,"file":"CommandAction.js","sourceRoot":"","sources":["../../src/types/CommandAction.ts"],"names":[],"mappings":"AAqBA,MAAM,CAAC,MAAM,kBAAkB,GAAG,CAAC,CAAC;AACpC,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,CAAC;AACtC,MAAM,CAAC,MAAM,2BAA2B,GAAG,CAAC,CAAC","sourcesContent":["import type { LazyApiContextOptions } from '@ms-cloudpack/api-server';\nimport type { ReadConfigOptions } from '@ms-cloudpack/config';\nimport type { TaskReporter } from '@ms-cloudpack/task-reporter';\nimport type { AutoDispose } from './AutoDispose.js';\nimport type { SharedOptions } from './SharedOptions.js';\n\n/**\n * Context for running a command in a specific app (after initialization).\n * For convenience, this can be passed/spread directly to `createPartialApiContext`.\n */\nexport type AppCommandContext = Pick<\n LazyApiContextOptions,\n 'appPath' | 'cachePath' | 'config' | 'reporter' | 'telemetryClient'\n>;\n\n/** Initialize options excluding `appPaths` */\nexport interface CommandInitializeOptions {\n /** Additional options to merge in while reading the config. */\n configOptions?: ReadConfigOptions;\n}\n\nexport const ExitCodeSuccessful = 0;\nexport const ExitCodeGenericError = 1;\nexport const ExitCodeAuthenticationError = 2;\nexport type ExitCode = typeof ExitCodeSuccessful | typeof ExitCodeGenericError | typeof ExitCodeAuthenticationError;\n\nexport interface CommandExitParams {\n /**\n * Message to show on exit.\n * If `isInterrupted` is true, use an empty string (it will show a default interrupt message).\n */\n message: string;\n /** Whether there are errors. By default, checks the reporter for failed tasks. */\n hasErrors?: boolean;\n /** Exit code to use. Defaults to 1 if there are errors, 0 if not. */\n exitCode?: ExitCode;\n /** True if the user interrupted an operation (ctrl+C). Sets the message automatically. */\n isInterrupted?: true;\n}\n\nexport interface CommandActionParams<TOptions extends object> {\n /**\n * Initial working directory (usually `process.cwd()` except in tests).\n * Note that this may differ from the `appPath` used by individual commands.\n */\n cwd: string;\n\n /**\n * Command-specific options, parsed from `process.argv`.\n * Types are generally defined in each command's `src/commands/<name>/types/<Name>Types.ts` module.\n * The command line options are defined in each command's `src/commands/<name>/index.ts` module.\n */\n options: TOptions;\n\n /**\n * Command-specific arguments. Arguments in commander are positional arguments that are not options.\n * For example, in `echo somestring`, `somestring` is an argument.\n */\n args: string[];\n\n reporter: TaskReporter;\n\n abortSignal: AbortSignal;\n\n /**\n * Function that can be called with any `Disposable`s that should be cleaned up automatically\n * when the program exits. (See `AutoDisposableList.add` for implementation.)\n */\n autoDispose: AutoDispose;\n\n /**\n * This should be called at or near the beginning of the action to initialize the config,\n * telemetry, and reporting. (See `CommandExecutor._initialize` for implementation.)\n * `initialize` can be called with either a single string, `appPath` or an a string[], `appPaths`.\n *\n * If it is called with a single string, it returns `Promise<AppCommandContext>`\n * If it is called with a string[], it returns `Promise<AppCommandContext[]>`\n */\n initialize: {\n (initializeOptions: CommandInitializeOptions & { appPath: string }): Promise<AppCommandContext>;\n (initializeOptions: CommandInitializeOptions & { appPaths: string[] }): Promise<AppCommandContext[]>;\n };\n\n /**\n * Set a callback to get the message to display if ctrl+C is pressed.\n */\n setInterruptMessageHandler: (getMessage: () => string) => void;\n}\n\n/**\n * Command action function (executor). This is the type of the `execute` function which should\n * be exported from each command's `src/commands/<name>/execute.ts` module.\n *\n * If it returns an object, the command wrapper will call the exit handler with that object.\n * If it returns null, it's assumed that this command is meant to keep running, such as `start`.\n */\nexport type CommandAction<TOptions> = (\n params: CommandActionParams<TOptions & SharedOptions>,\n) => Promise<CommandExitParams | null>;\n\nexport type CommandActionModule<TOptions> = {\n execute: CommandAction<TOptions>;\n};\n"]}
@@ -14,6 +14,7 @@ export declare class CommandExecutor<TOptions extends SharedOptions> {
14
14
  private _abortController;
15
15
  private _hasCalledExit;
16
16
  private _args;
17
+ private _sigintCount;
17
18
  private _getMessageOnInterrupt;
18
19
  private static _activeInstances;
19
20
  static exitAll(params: CommandExitParams): Promise<void>;
@@ -39,6 +40,7 @@ export declare class CommandExecutor<TOptions extends SharedOptions> {
39
40
  */
40
41
  private _initialize;
41
42
  private _initTelemetry;
43
+ protected _sigintHandler: () => void;
42
44
  /**
43
45
  * Exit function called with the result returned by the command's execute function,
44
46
  * or manually via `CommandExecutor.exitAll()` in tests.
@@ -1 +1 @@
1
- {"version":3,"file":"CommandExecutor.d.ts","sourceRoot":"","sources":["../../src/utilities/CommandExecutor.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EAGlB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AACjE,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAQ/D;;GAEG;AACH,qBAAa,eAAe,CAAC,QAAQ,SAAS,aAAa;IACzD,OAAO,CAAC,QAAQ,CAAW;IAC3B,OAAO,CAAC,QAAQ,CAA0B;IAC1C,OAAO,CAAC,eAAe,CAAiB;IACxC,OAAO,CAAC,KAAK,CAAS;IACtB,OAAO,CAAC,SAAS,CAAe;IAChC,OAAO,CAAC,mBAAmB,CAAqB;IAChD,OAAO,CAAC,gBAAgB,CAAkB;IAC1C,OAAO,CAAC,cAAc,CAAS;IAC/B,OAAO,CAAC,KAAK,CAAW;IACxB,OAAO,CAAC,sBAAsB,CAA+B;IAE7D,OAAO,CAAC,MAAM,CAAC,gBAAgB,CAA8B;WAEzC,OAAO,CAAC,MAAM,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;gBAQzD,MAAM,EAAE;QAClB,iCAAiC;QACjC,IAAI,EAAE,MAAM,EAAE,CAAC;QACf,2CAA2C;QAC3C,OAAO,EAAE,QAAQ,CAAC;QAClB,uCAAuC;QACvC,OAAO,EAAE,aAAa,CAAC,QAAQ,CAAC,CAAC;QACjC,0CAA0C;QAC1C,cAAc,EAAE,cAAc,CAAC;QAC/B,sDAAsD;QACtD,IAAI,EAAE,MAAM,CAAC;KACd;IAWD,uBAAuB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OAKG;YACW,WAAW;YAuGX,cAAc;IA+D5B,SAAS,CAAC,cAAc,aActB;IAEF;;;OAGG;cACa,KAAK,CAAC,MAAM,EAAE,iBAAiB;CA+BhD"}
@@ -3,7 +3,6 @@ import { readJson } from '@ms-cloudpack/json-utilities';
3
3
  import { TaskReporter, bold, debugLoggingConfig, defaultLoggingConfig, noLoggingConfig, red, verboseLoggingConfig, yellow, } from '@ms-cloudpack/task-reporter';
4
4
  import { createTelemetryClient } from '@ms-cloudpack/telemetry';
5
5
  import path from 'path';
6
- import { registerPerformanceObservers } from '../performance/registerPerformanceObservers.js';
7
6
  import { isCIBuild } from '../utilities/isCIBuild.js';
8
7
  import { AutoDisposableList } from './AutoDisposableList.js';
9
8
  import { checkFeatures } from './checkFeatures.js';
@@ -18,12 +17,26 @@ export class CommandExecutor {
18
17
  // There should only be one instance at a time, but we assume multiple instances for safety.
19
18
  for (const instance of CommandExecutor._activeInstances) {
20
19
  await instance._exit(params);
20
+ process.off('SIGINT', instance._sigintHandler);
21
21
  }
22
22
  CommandExecutor._activeInstances = [];
23
23
  }
24
24
  constructor(params) {
25
25
  this._hasCalledExit = false;
26
+ this._sigintCount = 0;
26
27
  this._getMessageOnInterrupt = () => `Interrupted by user`;
28
+ this._sigintHandler = () => {
29
+ this._sigintCount++;
30
+ if (this._sigintCount > 1) {
31
+ console.debug('Forcing exit');
32
+ // We are forcing the process to exit.
33
+ // No clean-up is needed because user pressed Ctrl+C twice.
34
+ // eslint-disable-next-line no-restricted-properties -- top-level cleanup
35
+ process.exit(1);
36
+ }
37
+ // We are trying to exit gracefully.
38
+ void this._exit({ isInterrupted: true, message: '' });
39
+ };
27
40
  this._args = params.args;
28
41
  this._options = params.options;
29
42
  this._execute = params.execute;
@@ -38,20 +51,8 @@ export class CommandExecutor {
38
51
  async execute() {
39
52
  CommandExecutor._activeInstances.push(this);
40
53
  try {
41
- // Setup cleanup and close things on completion.
42
- let sigintCount = 0;
43
54
  // Handle SIGINT (Ctrl+C) gracefully.
44
- process.on('SIGINT', () => {
45
- sigintCount++;
46
- if (sigintCount > 1) {
47
- console.debug('Forcing exit');
48
- // We are forcing the process to exit.
49
- // No clean-up is needed because user pressed Ctrl+C twice.
50
- process.exit(1);
51
- }
52
- // We are trying to exit gracefully.
53
- void this._exit({ message: this._getMessageOnInterrupt() });
54
- });
55
+ process.on('SIGINT', this._sigintHandler);
55
56
  // Call the execute function which is the real command logic
56
57
  // (ie: real init command logic, real start command logic, etc.)
57
58
  const result = await this._execute({
@@ -103,7 +104,7 @@ export class CommandExecutor {
103
104
  message: `Invalid cloudpack config: ${err.message || err}`,
104
105
  hasErrors: true,
105
106
  });
106
- // this will never be reached, but TypeScript doesn't know that
107
+ // eslint-disable-next-line no-restricted-properties -- this will never be reached, but TypeScript doesn't know that
107
108
  process.exit(1);
108
109
  }
109
110
  if (config.helpMessage) {
@@ -173,7 +174,6 @@ export class CommandExecutor {
173
174
  logLevel,
174
175
  serviceNamespace: 'cloudpack',
175
176
  serviceName: 'cli',
176
- rootSpanName: 'CLI',
177
177
  });
178
178
  telemetryClient.tracer.startActiveSpan('INIT_TELEMETRY', { startTime }, (span) => {
179
179
  const enabledFeatureNames = Object.entries(config.features || {})
@@ -201,13 +201,8 @@ export class CommandExecutor {
201
201
  for (const [key, value] of Object.entries(telemetryAttributes)) {
202
202
  if (value) {
203
203
  span.setAttribute(key, value);
204
- // rootSpan will be deleted in the near future
205
- telemetryClient.rootSpan.setAttribute(key, value);
206
204
  }
207
205
  }
208
- // Register performance observers to track performance metrics as events of CLI span.
209
- registerPerformanceObservers(telemetryClient);
210
- span.end();
211
206
  });
212
207
  return telemetryClient;
213
208
  }
@@ -216,7 +211,8 @@ export class CommandExecutor {
216
211
  * or manually via `CommandExecutor.exitAll()` in tests.
217
212
  */
218
213
  async _exit(params) {
219
- const { message, hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;
214
+ const { hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;
215
+ const message = params.isInterrupted ? this._getMessageOnInterrupt() : params.message;
220
216
  if (this._hasCalledExit) {
221
217
  // Skip most of the operations if exit() was called multiple times.
222
218
  // But only use the error message if not in a test, due to the way we're mocking process.exit.
@@ -237,6 +233,7 @@ export class CommandExecutor {
237
233
  // Show the summary message (this will throw if called twice).
238
234
  this._reporter.complete(hasErrors ? red(message) : message, exitWithError);
239
235
  }
236
+ // eslint-disable-next-line no-restricted-properties -- top-level cleanup
240
237
  process.exit(exitCode);
241
238
  }
242
239
  }
@@ -1 +1 @@
1
- {"version":3,"file":"CommandExecutor.js","sourceRoot":"","sources":["../../src/utilities/CommandExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,GAAG,EACH,oBAAoB,EACpB,MAAM,GACP,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,yBAAyB,CAAC;AACtF,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,4BAA4B,EAAE,MAAM,gDAAgD,CAAC;AAS9F,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAEnD;;GAEG;AACH,MAAM,OAAO,eAAe;IAcnB,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,MAAyB;QACnD,4FAA4F;QAC5F,KA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SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,EAAE,GAAG,MAAM,CAAC;QAEjG,IAAI,IAAI,CAAC,cAAc,EAAE,CAAC;YACxB,mEAAmE;YACnE,8FAA8F;YAC9F,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,CAAC;gBAChC,MAAM,YAAY,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,CAAC;qBACxC,GAAG,CAAC,CAAC,CAAC,GAAG,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,KAAK,KAAK,GAAG,CAAC;qBAC1C,IAAI,CAAC,IAAI,CAAC,CAAC;gBACd,OAAO,CAAC,IAAI,CAAC,0DAA0D,YAAY,GAAG,CAAC,CAAC;YAC1F,CAAC;QACH,CAAC;aAAM,CAAC;YACN,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAE3B,qDAAqD;YACrD,IAAI,CAAC,gBAAgB,CAAC,KAAK,EAAE,CAAC;YAE9B,sCAAsC;YACtC,MAAM,IAAI,CAAC,mBAAmB,CAAC,OAAO,EAAE,CAAC;YAEzC,MAAM,aAAa,GAAG,QAAQ,KAAK,CAAC,CAAC;YAErC,8DAA8D;YAC9D,IAAI,CAAC,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;QAC7E,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IACzB,CAAC;;AAvSD,yFAAyF;AAC1E,gCAAgB,GAA2B,EAAE,AAA7B,CAA8B","sourcesContent":["import { readConfig } from '@ms-cloudpack/config';\nimport type { CloudpackConfig, PackageJson } from '@ms-cloudpack/common-types';\nimport { readJson } from '@ms-cloudpack/json-utilities';\nimport {\n TaskReporter,\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n red,\n verboseLoggingConfig,\n yellow,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient, type TelemetryClient } from '@ms-cloudpack/telemetry';\nimport path from 'path';\nimport { registerPerformanceObservers } from '../performance/registerPerformanceObservers.js';\nimport type {\n CommandAction,\n CommandExitParams,\n AppCommandContext,\n CommandInitializeOptions,\n} from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { isCIBuild } from '../utilities/isCIBuild.js';\nimport { AutoDisposableList } from './AutoDisposableList.js';\nimport { checkFeatures } from './checkFeatures.js';\nimport { isCodespaces } from '../utilities/isCodespaces.js';\nimport { getVersion } from '@ms-cloudpack/package-utilities';\nimport { mergeFeatures } from './mergeFeatures.js';\n\n/**\n * This class manages orchestration and shared state while executing a command.\n */\nexport class CommandExecutor<TOptions extends SharedOptions> {\n private _options: TOptions;\n private _execute: CommandAction<TOptions>;\n private _programOptions: ProgramOptions;\n private _verb: string;\n private _reporter: TaskReporter;\n private _autoDisposableList: AutoDisposableList;\n private _abortController: AbortController;\n private _hasCalledExit = false;\n private _args: string[];\n private _getMessageOnInterrupt = () => `Interrupted by user`;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used\n private static _activeInstances: CommandExecutor<any>[] = [];\n\n public static async exitAll(params: CommandExitParams): Promise<void> {\n // There should only be one instance at a time, but we assume multiple instances for safety.\n for (const instance of CommandExecutor._activeInstances) {\n await instance._exit(params);\n }\n CommandExecutor._activeInstances = [];\n }\n\n constructor(params: {\n /** Command-specific arguments */\n args: string[];\n /** Command-specific and shared options. */\n options: TOptions;\n /** Function to execute the command. */\n execute: CommandAction<TOptions>;\n /** Shared program-level configuration. */\n programOptions: ProgramOptions;\n /** Verb being run, e.g. `bundle` or `cache clean`. */\n verb: string;\n }) {\n this._args = params.args;\n this._options = params.options;\n this._execute = params.execute;\n this._programOptions = params.programOptions;\n this._verb = params.verb;\n this._reporter = new TaskReporter();\n this._abortController = new AbortController();\n this._autoDisposableList = new AutoDisposableList();\n }\n\n /** Run the command. */\n // This has to be a separate method because constructors can't be async.\n public async execute() {\n CommandExecutor._activeInstances.push(this);\n try {\n // Setup cleanup and close things on completion.\n let sigintCount = 0;\n\n // Handle SIGINT (Ctrl+C) gracefully.\n process.on('SIGINT', () => {\n sigintCount++;\n if (sigintCount > 1) {\n console.debug('Forcing exit');\n\n // We are forcing the process to exit.\n // No clean-up is needed because user pressed Ctrl+C twice.\n process.exit(1);\n }\n\n // We are trying to exit gracefully.\n void this._exit({ message: this._getMessageOnInterrupt() });\n });\n\n // Call the execute function which is the real command logic\n // (ie: real init command logic, real start command logic, etc.)\n const result = await this._execute({\n args: this._args,\n options: this._options,\n cwd: this._programOptions.cwd,\n reporter: this._reporter,\n initialize: this._initialize.bind(this),\n abortSignal: this._abortController.signal,\n autoDispose: (disposable) => this._autoDisposableList.add(disposable),\n setInterruptMessageHandler: (getMessage) => {\n this._getMessageOnInterrupt = getMessage;\n },\n });\n if (result) {\n await this._exit(result);\n }\n } catch (error) {\n // If an error occurs, exit the process with a non-zero exit code.\n await this._exit({\n hasErrors: true,\n message: error instanceof Error ? error.stack || error.message : String(error),\n });\n }\n }\n\n /**\n * This is the `initialize` function passed to the command's execute function.\n * This function uses `this` to references several class members, which is why\n * the `execute` method must use `.bind(this)`.\n * (An arrow function isn't possible here due to the overloaded method signature).\n */\n private async _initialize(\n initializeParams: CommandInitializeOptions & { appPath: string },\n ): Promise<AppCommandContext>;\n private async _initialize(\n initializeParams: CommandInitializeOptions & { appPaths: string[] },\n ): Promise<AppCommandContext[]>;\n private async _initialize(\n initializeParams: CommandInitializeOptions & {\n appPath?: string;\n appPaths?: string[];\n },\n ): Promise<AppCommandContext | AppCommandContext[]> {\n const { appPath: singleAppPath, configOptions } = initializeParams;\n let { appPaths } = initializeParams;\n\n if (singleAppPath && appPaths) {\n throw Error('appPath and appPaths cannot both be specified at the same time');\n }\n if (!singleAppPath && !appPaths) {\n throw Error('one of appPath or appPaths must be specified');\n }\n\n if (!appPaths || appPaths.length === 0) {\n appPaths = singleAppPath ? [singleAppPath] : [];\n }\n\n const contexts: AppCommandContext[] = [];\n\n const helpMessages = new Set<string>();\n\n const configs: Record<string, CloudpackConfig> = {};\n for (const appPath of appPaths) {\n let config: CloudpackConfig;\n\n try {\n config = await readConfig(appPath, configOptions);\n } catch (err) {\n await this._exit({\n message: `Invalid cloudpack config: ${(err as Error).message || err}`,\n hasErrors: true,\n });\n // this will never be reached, but TypeScript doesn't know that\n process.exit(1);\n }\n if (config.helpMessage) {\n helpMessages.add(config.helpMessage);\n }\n\n configs[appPath] = config;\n }\n\n // Set reporter options and print the product info header\n this._reporter.setOptions({\n productName: 'Cloudpack',\n version: this._programOptions.version,\n description: () => `Running \"${bold(this._programOptions.argv.slice(2).join(' '))}\"`,\n helpMessage: [...helpMessages].join('\\n'),\n plainTextMode: !this._options.color,\n ...(this._options.debug\n ? debugLoggingConfig\n : this._options.verbose\n ? verboseLoggingConfig\n : this._options.quiet\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n for (const appPath of appPaths) {\n const config = configs[appPath];\n const definition = await readJson<PackageJson>(path.join(appPath, 'package.json'));\n const { name = path.basename(appPath) } = definition || {};\n\n const telemetryClient = await this._initTelemetry(name, config);\n // Dispose the telemetry client when the app is closing\n this._autoDisposableList.add({\n dispose: () => telemetryClient.shutdown(),\n });\n\n // Merge in any additional features from the command line and remote feature flags.\n config.features = mergeFeatures({\n configFeatures: config.features,\n commandLineFeatures: this._options.features,\n });\n\n const featureErrors = checkFeatures({ configFeatures: config.features });\n\n // If there are any invalid features, warn the user and continue.\n if (featureErrors.length) {\n featureErrors.forEach((warning) => console.warn(warning));\n }\n\n contexts.push({\n appPath,\n cachePath: this._options.cachePath,\n config,\n reporter: this._reporter,\n telemetryClient,\n });\n }\n\n return singleAppPath ? contexts[0] : contexts;\n }\n\n private async _initTelemetry(appName: string | undefined, config: CloudpackConfig): Promise<TelemetryClient> {\n // Mark the start time for telemetry.\n const startTime = performance.now();\n\n const programOptions = this._programOptions;\n const options = this._options;\n\n const connectionString = programOptions.disableTelemetry\n ? undefined\n : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;\n\n const logLevel = options.verbose ? 'VERBOSE' : options.debug ? 'DEBUG' : undefined;\n if (!options.debug) {\n this._reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel,\n serviceNamespace: 'cloudpack',\n serviceName: 'cli',\n rootSpanName: 'CLI',\n });\n\n telemetryClient.tracer.startActiveSpan('INIT_TELEMETRY', { startTime }, (span) => {\n const enabledFeatureNames = Object.entries(config.features || {})\n .filter(([, value]) => value)\n .map(([key]) => key);\n\n if (enabledFeatureNames.length) {\n console.log(`Enabled features: ${enabledFeatureNames.map((f) => yellow(f)).join(', ')}`);\n }\n\n const isCI = isCIBuild();\n\n const telemetryAttributes = {\n verb: this._verb,\n arguments: programOptions.argv.slice(3).join(' '),\n environment: isCI ? 'ci' : isCodespaces() ? 'codespaces' : 'local',\n appName: appName || '<unknown>',\n mode: config.mode || 'library',\n\n // External correlation Id is used to correlate telemetry across different services.\n externalCorrelationId: process.env.CLOUDPACK_TELEMETRY_EXTERNAL_CORRELATION_ID,\n\n // Azure DevOps build attributes\n buildId: isCI ? process.env.BUILD_BUILDID : undefined,\n definitionId: isCI ? process.env.SYSTEM_DEFINITIONID : undefined,\n buildReason: isCI ? process.env.BUILD_REASON : undefined,\n pullRequestId: isCI ? process.env.SYSTEM_PULLREQUEST_PULLREQUESTID : undefined,\n features: enabledFeatureNames,\n };\n\n for (const [key, value] of Object.entries(telemetryAttributes)) {\n if (value) {\n span.setAttribute(key, value);\n\n // rootSpan will be deleted in the near future\n telemetryClient.rootSpan.setAttribute(key, value);\n }\n }\n\n // Register performance observers to track performance metrics as events of CLI span.\n registerPerformanceObservers(telemetryClient);\n\n span.end();\n });\n\n return telemetryClient;\n }\n\n /**\n * Exit function called with the result returned by the command's execute function,\n * or manually via `CommandExecutor.exitAll()` in tests.\n */\n protected async _exit(params: CommandExitParams) {\n const { message, hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;\n\n if (this._hasCalledExit) {\n // Skip most of the operations if exit() was called multiple times.\n // But only use the error message if not in a test, due to the way we're mocking process.exit.\n if (!process.env.JEST_WORKER_ID) {\n const prettyParams = Object.entries(params)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(', ');\n console.warn(`exit() was called multiple times. This call's options: ${prettyParams}.`);\n }\n } else {\n this._hasCalledExit = true;\n\n // Let the execute function know that we are exiting.\n this._abortController.abort();\n\n // Dispose all registered disposables.\n await this._autoDisposableList.dispose();\n\n const exitWithError = exitCode !== 0;\n\n // Show the summary message (this will throw if called twice).\n this._reporter.complete(hasErrors ? red(message) : message, exitWithError);\n }\n\n process.exit(exitCode);\n }\n}\n"]}
1
+ {"version":3,"file":"CommandExecutor.js","sourceRoot":"","sources":["../../src/utilities/CommandExecutor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAC;AACxD,OAAO,EACL,YAAY,EACZ,IAAI,EACJ,kBAAkB,EAClB,oBAAoB,EACpB,eAAe,EACf,GAAG,EACH,oBAAoB,EACpB,MAAM,GACP,MAAM,6BAA6B,CAAC;AACrC,OAAO,EAAE,qBAAqB,EAAwB,MAAM,yBAAyB,CAAC;AACtF,OAAO,IAAI,MAAM,MAAM,CAAC;AASxB,OAAO,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtD,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAC5D,OAAO,EAAE,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B,CAAC;;AAlSD,yFAAyF;AAC1E,gCAAgB,GAA2B,EAAE,AAA7B,CAA8B","sourcesContent":["import { readConfig } from '@ms-cloudpack/config';\nimport type { CloudpackConfig, PackageJson } from '@ms-cloudpack/common-types';\nimport { readJson } from '@ms-cloudpack/json-utilities';\nimport {\n TaskReporter,\n bold,\n debugLoggingConfig,\n defaultLoggingConfig,\n noLoggingConfig,\n red,\n verboseLoggingConfig,\n yellow,\n} from '@ms-cloudpack/task-reporter';\nimport { createTelemetryClient, type TelemetryClient } from '@ms-cloudpack/telemetry';\nimport path from 'path';\nimport type {\n CommandAction,\n CommandExitParams,\n AppCommandContext,\n CommandInitializeOptions,\n} from '../types/CommandAction.js';\nimport type { ProgramOptions } from '../types/ProgramOptions.js';\nimport type { SharedOptions } from '../types/SharedOptions.js';\nimport { isCIBuild } from '../utilities/isCIBuild.js';\nimport { AutoDisposableList } from './AutoDisposableList.js';\nimport { checkFeatures } from './checkFeatures.js';\nimport { isCodespaces } from '../utilities/isCodespaces.js';\nimport { getVersion } from '@ms-cloudpack/package-utilities';\nimport { mergeFeatures } from './mergeFeatures.js';\n\n/**\n * This class manages orchestration and shared state while executing a command.\n */\nexport class CommandExecutor<TOptions extends SharedOptions> {\n private _options: TOptions;\n private _execute: CommandAction<TOptions>;\n private _programOptions: ProgramOptions;\n private _verb: string;\n private _reporter: TaskReporter;\n private _autoDisposableList: AutoDisposableList;\n private _abortController: AbortController;\n private _hasCalledExit = false;\n private _args: string[];\n private _sigintCount = 0;\n private _getMessageOnInterrupt = () => `Interrupted by user`;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- options type isn't used\n private static _activeInstances: CommandExecutor<any>[] = [];\n\n public static async exitAll(params: CommandExitParams): Promise<void> {\n // There should only be one instance at a time, but we assume multiple instances for safety.\n for (const instance of CommandExecutor._activeInstances) {\n await instance._exit(params);\n process.off('SIGINT', instance._sigintHandler);\n }\n CommandExecutor._activeInstances = [];\n }\n\n constructor(params: {\n /** Command-specific arguments */\n args: string[];\n /** Command-specific and shared options. */\n options: TOptions;\n /** Function to execute the command. */\n execute: CommandAction<TOptions>;\n /** Shared program-level configuration. */\n programOptions: ProgramOptions;\n /** Verb being run, e.g. `bundle` or `cache clean`. */\n verb: string;\n }) {\n this._args = params.args;\n this._options = params.options;\n this._execute = params.execute;\n this._programOptions = params.programOptions;\n this._verb = params.verb;\n this._reporter = new TaskReporter();\n this._abortController = new AbortController();\n this._autoDisposableList = new AutoDisposableList();\n }\n\n /** Run the command. */\n // This has to be a separate method because constructors can't be async.\n public async execute() {\n CommandExecutor._activeInstances.push(this);\n try {\n // Handle SIGINT (Ctrl+C) gracefully.\n process.on('SIGINT', this._sigintHandler);\n\n // Call the execute function which is the real command logic\n // (ie: real init command logic, real start command logic, etc.)\n const result = await this._execute({\n args: this._args,\n options: this._options,\n cwd: this._programOptions.cwd,\n reporter: this._reporter,\n initialize: this._initialize.bind(this),\n abortSignal: this._abortController.signal,\n autoDispose: (disposable) => this._autoDisposableList.add(disposable),\n setInterruptMessageHandler: (getMessage) => {\n this._getMessageOnInterrupt = getMessage;\n },\n });\n if (result) {\n await this._exit(result);\n }\n } catch (error) {\n // If an error occurs, exit the process with a non-zero exit code.\n await this._exit({\n hasErrors: true,\n message: error instanceof Error ? error.stack || error.message : String(error),\n });\n }\n }\n\n /**\n * This is the `initialize` function passed to the command's execute function.\n * This function uses `this` to references several class members, which is why\n * the `execute` method must use `.bind(this)`.\n * (An arrow function isn't possible here due to the overloaded method signature).\n */\n private async _initialize(\n initializeParams: CommandInitializeOptions & { appPath: string },\n ): Promise<AppCommandContext>;\n private async _initialize(\n initializeParams: CommandInitializeOptions & { appPaths: string[] },\n ): Promise<AppCommandContext[]>;\n private async _initialize(\n initializeParams: CommandInitializeOptions & {\n appPath?: string;\n appPaths?: string[];\n },\n ): Promise<AppCommandContext | AppCommandContext[]> {\n const { appPath: singleAppPath, configOptions } = initializeParams;\n let { appPaths } = initializeParams;\n\n if (singleAppPath && appPaths) {\n throw Error('appPath and appPaths cannot both be specified at the same time');\n }\n if (!singleAppPath && !appPaths) {\n throw Error('one of appPath or appPaths must be specified');\n }\n\n if (!appPaths || appPaths.length === 0) {\n appPaths = singleAppPath ? [singleAppPath] : [];\n }\n\n const contexts: AppCommandContext[] = [];\n\n const helpMessages = new Set<string>();\n\n const configs: Record<string, CloudpackConfig> = {};\n for (const appPath of appPaths) {\n let config: CloudpackConfig;\n\n try {\n config = await readConfig(appPath, configOptions);\n } catch (err) {\n await this._exit({\n message: `Invalid cloudpack config: ${(err as Error).message || err}`,\n hasErrors: true,\n });\n // eslint-disable-next-line no-restricted-properties -- this will never be reached, but TypeScript doesn't know that\n process.exit(1);\n }\n if (config.helpMessage) {\n helpMessages.add(config.helpMessage);\n }\n\n configs[appPath] = config;\n }\n\n // Set reporter options and print the product info header\n this._reporter.setOptions({\n productName: 'Cloudpack',\n version: this._programOptions.version,\n description: () => `Running \"${bold(this._programOptions.argv.slice(2).join(' '))}\"`,\n helpMessage: [...helpMessages].join('\\n'),\n plainTextMode: !this._options.color,\n ...(this._options.debug\n ? debugLoggingConfig\n : this._options.verbose\n ? verboseLoggingConfig\n : this._options.quiet\n ? noLoggingConfig\n : defaultLoggingConfig),\n });\n\n for (const appPath of appPaths) {\n const config = configs[appPath];\n const definition = await readJson<PackageJson>(path.join(appPath, 'package.json'));\n const { name = path.basename(appPath) } = definition || {};\n\n const telemetryClient = await this._initTelemetry(name, config);\n // Dispose the telemetry client when the app is closing\n this._autoDisposableList.add({\n dispose: () => telemetryClient.shutdown(),\n });\n\n // Merge in any additional features from the command line and remote feature flags.\n config.features = mergeFeatures({\n configFeatures: config.features,\n commandLineFeatures: this._options.features,\n });\n\n const featureErrors = checkFeatures({ configFeatures: config.features });\n\n // If there are any invalid features, warn the user and continue.\n if (featureErrors.length) {\n featureErrors.forEach((warning) => console.warn(warning));\n }\n\n contexts.push({\n appPath,\n cachePath: this._options.cachePath,\n config,\n reporter: this._reporter,\n telemetryClient,\n });\n }\n\n return singleAppPath ? contexts[0] : contexts;\n }\n\n private async _initTelemetry(appName: string | undefined, config: CloudpackConfig): Promise<TelemetryClient> {\n // Mark the start time for telemetry.\n const startTime = performance.now();\n\n const programOptions = this._programOptions;\n const options = this._options;\n\n const connectionString = programOptions.disableTelemetry\n ? undefined\n : config.telemetry?.connectionString || process.env.CLOUDPACK_TELEMETRY_CONNECTION_STRING;\n\n const logLevel = options.verbose ? 'VERBOSE' : options.debug ? 'DEBUG' : undefined;\n if (!options.debug) {\n this._reporter.ignoreLogMessage('ApplicationInsights:');\n }\n\n const telemetryClient = await createTelemetryClient({\n productVersion: getVersion(import.meta.url),\n connectionString,\n logLevel,\n serviceNamespace: 'cloudpack',\n serviceName: 'cli',\n });\n\n telemetryClient.tracer.startActiveSpan('INIT_TELEMETRY', { startTime }, (span) => {\n const enabledFeatureNames = Object.entries(config.features || {})\n .filter(([, value]) => value)\n .map(([key]) => key);\n\n if (enabledFeatureNames.length) {\n console.log(`Enabled features: ${enabledFeatureNames.map((f) => yellow(f)).join(', ')}`);\n }\n\n const isCI = isCIBuild();\n\n const telemetryAttributes = {\n verb: this._verb,\n arguments: programOptions.argv.slice(3).join(' '),\n environment: isCI ? 'ci' : isCodespaces() ? 'codespaces' : 'local',\n appName: appName || '<unknown>',\n mode: config.mode || 'library',\n\n // External correlation Id is used to correlate telemetry across different services.\n externalCorrelationId: process.env.CLOUDPACK_TELEMETRY_EXTERNAL_CORRELATION_ID,\n\n // Azure DevOps build attributes\n buildId: isCI ? process.env.BUILD_BUILDID : undefined,\n definitionId: isCI ? process.env.SYSTEM_DEFINITIONID : undefined,\n buildReason: isCI ? process.env.BUILD_REASON : undefined,\n pullRequestId: isCI ? process.env.SYSTEM_PULLREQUEST_PULLREQUESTID : undefined,\n features: enabledFeatureNames,\n };\n\n for (const [key, value] of Object.entries(telemetryAttributes)) {\n if (value) {\n span.setAttribute(key, value);\n }\n }\n });\n\n return telemetryClient;\n }\n\n protected _sigintHandler = () => {\n this._sigintCount++;\n\n if (this._sigintCount > 1) {\n console.debug('Forcing exit');\n\n // We are forcing the process to exit.\n // No clean-up is needed because user pressed Ctrl+C twice.\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(1);\n }\n\n // We are trying to exit gracefully.\n void this._exit({ isInterrupted: true, message: '' });\n };\n\n /**\n * Exit function called with the result returned by the command's execute function,\n * or manually via `CommandExecutor.exitAll()` in tests.\n */\n protected async _exit(params: CommandExitParams) {\n const { hasErrors = this._reporter.hasErrors(), exitCode = hasErrors ? 1 : 0 } = params;\n const message = params.isInterrupted ? this._getMessageOnInterrupt() : params.message;\n\n if (this._hasCalledExit) {\n // Skip most of the operations if exit() was called multiple times.\n // But only use the error message if not in a test, due to the way we're mocking process.exit.\n if (!process.env.JEST_WORKER_ID) {\n const prettyParams = Object.entries(params)\n .map(([key, value]) => `${key}=\"${value}\"`)\n .join(', ');\n console.warn(`exit() was called multiple times. This call's options: ${prettyParams}.`);\n }\n } else {\n this._hasCalledExit = true;\n\n // Let the execute function know that we are exiting.\n this._abortController.abort();\n\n // Dispose all registered disposables.\n await this._autoDisposableList.dispose();\n\n const exitWithError = exitCode !== 0;\n\n // Show the summary message (this will throw if called twice).\n this._reporter.complete(hasErrors ? red(message) : message, exitWithError);\n }\n\n // eslint-disable-next-line no-restricted-properties -- top-level cleanup\n process.exit(exitCode);\n }\n}\n"]}
@@ -5,7 +5,7 @@ import spawn from 'cross-spawn';
5
5
  */
6
6
  export function runPrerequisites(options) {
7
7
  const { config, appPath, telemetryClient } = options;
8
- telemetryClient.performance.track('RUN_PREREQUISITES', () => {
8
+ telemetryClient.tracer.startActiveSpan('RUN_PREREQUISITES', () => {
9
9
  const dependsOn = config?.dependsOn;
10
10
  if (dependsOn) {
11
11
  for (const [command, args] of dependsOn) {