@shopify/cli-kit 3.73.2 → 3.74.1
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/dist/cli/api/graphql/admin/generated/get_theme.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/get_theme_file_bodies.d.ts +1 -5
- package/dist/cli/api/graphql/admin/generated/get_theme_file_checksums.d.ts +1 -4
- package/dist/cli/api/graphql/admin/generated/get_themes.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/metafield_definitions_by_owner_type.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/online_store_password_protection.d.ts +13 -0
- package/dist/cli/api/graphql/admin/generated/online_store_password_protection.js +37 -0
- package/dist/cli/api/graphql/admin/generated/online_store_password_protection.js.map +1 -0
- package/dist/cli/api/graphql/admin/generated/public_api_versions.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/theme_delete.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/theme_files_upsert.d.ts +1 -4
- package/dist/cli/api/graphql/admin/generated/theme_publish.d.ts +1 -3
- package/dist/cli/api/graphql/admin/generated/theme_update.d.ts +1 -4
- package/dist/private/node/analytics.js.map +1 -1
- package/dist/private/node/api/graphql.js.map +1 -1
- package/dist/private/node/api/headers.d.ts +2 -2
- package/dist/private/node/api/headers.js +1 -1
- package/dist/private/node/api/headers.js.map +1 -1
- package/dist/private/node/api/rest.js.map +1 -1
- package/dist/private/node/api/urls.js.map +1 -1
- package/dist/private/node/api.js.map +1 -1
- package/dist/private/node/conf-store.js.map +1 -1
- package/dist/private/node/constants.d.ts +0 -1
- package/dist/private/node/constants.js +0 -1
- package/dist/private/node/constants.js.map +1 -1
- package/dist/private/node/content-tokens.js.map +1 -1
- package/dist/private/node/context/deprecations-store.js.map +1 -1
- package/dist/private/node/context/service.d.ts +0 -1
- package/dist/private/node/context/service.js.map +1 -1
- package/dist/private/node/context/utilities.d.ts +0 -1
- package/dist/private/node/context/utilities.js.map +1 -1
- package/dist/private/node/otel-metrics.js.map +1 -1
- package/dist/private/node/request-ids.js.map +1 -1
- package/dist/private/node/session/device-authorization.js.map +1 -1
- package/dist/private/node/session/exchange.js +2 -3
- package/dist/private/node/session/exchange.js.map +1 -1
- package/dist/private/node/session/identity-token-validation.js.map +1 -1
- package/dist/private/node/session/identity.js.map +1 -1
- package/dist/private/node/session/scopes.d.ts +2 -3
- package/dist/private/node/session/scopes.js +7 -8
- package/dist/private/node/session/scopes.js.map +1 -1
- package/dist/private/node/session/store.js.map +1 -1
- package/dist/private/node/session/validate.js.map +1 -1
- package/dist/private/node/session.d.ts +0 -1
- package/dist/private/node/session.js +3 -74
- package/dist/private/node/session.js.map +1 -1
- package/dist/private/node/testing/ui.d.ts +0 -1
- package/dist/private/node/testing/ui.js.map +1 -1
- package/dist/private/node/themes/replace-invalid-characters.js +3 -3
- package/dist/private/node/themes/replace-invalid-characters.js.map +1 -1
- package/dist/private/node/ui/components/Alert.d.ts +2 -1
- package/dist/private/node/ui/components/Alert.js +2 -1
- package/dist/private/node/ui/components/Alert.js.map +1 -1
- package/dist/private/node/ui/components/AutocompletePrompt.js.map +1 -1
- package/dist/private/node/ui/components/Banner.js.map +1 -1
- package/dist/private/node/ui/components/ConcurrentOutput.js.map +1 -1
- package/dist/private/node/ui/components/DangerousConfirmationPrompt.js.map +1 -1
- package/dist/private/node/ui/components/FatalError.js +2 -1
- package/dist/private/node/ui/components/FatalError.js.map +1 -1
- package/dist/private/node/ui/components/Link.js.map +1 -1
- package/dist/private/node/ui/components/Prompts/PromptLayout.js.map +1 -1
- package/dist/private/node/ui/components/Scrollbar.js.map +1 -1
- package/dist/private/node/ui/components/SelectInput.js.map +1 -1
- package/dist/private/node/ui/components/SelectPrompt.js.map +1 -1
- package/dist/private/node/ui/components/Table/Row.d.ts +0 -1
- package/dist/private/node/ui/components/Table/Row.js.map +1 -1
- package/dist/private/node/ui/components/Table/Table.d.ts +0 -1
- package/dist/private/node/ui/components/Table/Table.js.map +1 -1
- package/dist/private/node/ui/components/TabularData.d.ts +8 -0
- package/dist/private/node/ui/components/TabularData.js +16 -0
- package/dist/private/node/ui/components/TabularData.js.map +1 -0
- package/dist/private/node/ui/components/Tasks.d.ts +1 -1
- package/dist/private/node/ui/components/Tasks.js.map +1 -1
- package/dist/private/node/ui/components/Tasks.test.js.map +1 -1
- package/dist/private/node/ui/components/TextInput.js.map +1 -1
- package/dist/private/node/ui/components/TextPrompt.js.map +1 -1
- package/dist/private/node/ui/components/TokenizedText.d.ts +12 -19
- package/dist/private/node/ui/components/TokenizedText.js.map +1 -1
- package/dist/private/node/ui/hooks/use-layout.d.ts +0 -1
- package/dist/private/node/ui/hooks/use-layout.js.map +1 -1
- package/dist/private/node/ui/hooks/use-prompt.d.ts +0 -1
- package/dist/private/node/ui/hooks/use-select-state.js.map +1 -1
- package/dist/private/node/ui/utilities.d.ts +15 -1
- package/dist/private/node/ui.d.ts +0 -2
- package/dist/private/node/ui.js.map +1 -1
- package/dist/public/common/retry.js.map +1 -1
- package/dist/public/common/string.js.map +1 -1
- package/dist/public/common/ts/json-narrowing.js.map +1 -1
- package/dist/public/common/url.js.map +1 -1
- package/dist/public/common/version.d.ts +1 -1
- package/dist/public/common/version.js +1 -1
- package/dist/public/common/version.js.map +1 -1
- package/dist/public/node/analytics.js.map +1 -1
- package/dist/public/node/api/admin.js.map +1 -1
- package/dist/public/node/api/app-management.js.map +1 -1
- package/dist/public/node/api/graphql.js.map +1 -1
- package/dist/public/node/api/partners.js.map +1 -1
- package/dist/public/node/api/rest-api-throttler.js.map +1 -1
- package/dist/public/node/archiver.js.map +1 -1
- package/dist/public/node/base-command.js.map +1 -1
- package/dist/public/node/cli-launcher.js.map +1 -1
- package/dist/public/node/cli.d.ts +0 -1
- package/dist/public/node/cli.js.map +1 -1
- package/dist/public/node/context/fqdn.js.map +1 -1
- package/dist/public/node/context/local.d.ts +4 -5
- package/dist/public/node/context/local.js +6 -5
- package/dist/public/node/context/local.js.map +1 -1
- package/dist/public/node/context/spin.d.ts +0 -1
- package/dist/public/node/context/spin.js.map +1 -1
- package/dist/public/node/context/utilities.js.map +1 -1
- package/dist/public/node/crypto.d.ts +0 -1
- package/dist/public/node/custom-oclif-loader.js.map +1 -1
- package/dist/public/node/dot-env.js.map +1 -1
- package/dist/public/node/environment.d.ts +0 -1
- package/dist/public/node/environment.js.map +1 -1
- package/dist/public/node/environments.js.map +1 -1
- package/dist/public/node/error-handler.js +1 -1
- package/dist/public/node/error-handler.js.map +1 -1
- package/dist/public/node/error.js.map +1 -1
- package/dist/public/node/framework.js.map +1 -1
- package/dist/public/node/fs.d.ts +20 -2
- package/dist/public/node/fs.js +24 -0
- package/dist/public/node/fs.js.map +1 -1
- package/dist/public/node/git.js.map +1 -1
- package/dist/public/node/github.js.map +1 -1
- package/dist/public/node/global-context.js.map +1 -1
- package/dist/public/node/hooks/deprecations.js.map +1 -1
- package/dist/public/node/hooks/postrun.js.map +1 -1
- package/dist/public/node/hooks/prerun.js.map +1 -1
- package/dist/public/node/http.js.map +1 -1
- package/dist/public/node/is-global.js.map +1 -1
- package/dist/public/node/json-schema.js.map +1 -1
- package/dist/public/node/liquid.js.map +1 -1
- package/dist/public/node/metadata.js +1 -1
- package/dist/public/node/metadata.js.map +1 -1
- package/dist/public/node/monorail.d.ts +1 -0
- package/dist/public/node/monorail.js.map +1 -1
- package/dist/public/node/node-package-manager.d.ts +0 -2
- package/dist/public/node/node-package-manager.js.map +1 -1
- package/dist/public/node/notifications-system.d.ts +6 -7
- package/dist/public/node/notifications-system.js.map +1 -1
- package/dist/public/node/os.js.map +1 -1
- package/dist/public/node/output.d.ts +0 -2
- package/dist/public/node/output.js +3 -3
- package/dist/public/node/output.js.map +1 -1
- package/dist/public/node/path.d.ts +0 -1
- package/dist/public/node/path.js.map +1 -1
- package/dist/public/node/plugins.d.ts +1 -1
- package/dist/public/node/plugins.js.map +1 -1
- package/dist/public/node/result.js.map +1 -1
- package/dist/public/node/schema.js.map +1 -1
- package/dist/public/node/session.d.ts +0 -1
- package/dist/public/node/session.js.map +1 -1
- package/dist/public/node/system.d.ts +0 -1
- package/dist/public/node/system.js.map +1 -1
- package/dist/public/node/tcp.js.map +1 -1
- package/dist/public/node/themes/api.d.ts +1 -0
- package/dist/public/node/themes/api.js +10 -0
- package/dist/public/node/themes/api.js.map +1 -1
- package/dist/public/node/themes/conf.js.map +1 -1
- package/dist/public/node/themes/theme-manager.js.map +1 -1
- package/dist/public/node/themes/types.d.ts +4 -1
- package/dist/public/node/themes/types.js.map +1 -1
- package/dist/public/node/themes/urls.js.map +1 -1
- package/dist/public/node/themes/utils.js.map +1 -1
- package/dist/public/node/tree-kill.js.map +1 -1
- package/dist/public/node/ui.d.ts +0 -1
- package/dist/public/node/ui.js.map +1 -1
- package/dist/public/node/upgrade.js.map +1 -1
- package/dist/public/node/vendor/dev_server/DevServer.js.map +1 -1
- package/dist/public/node/vendor/otel-js/export/InstantaneousMetricReader.js.map +1 -1
- package/dist/public/node/vendor/otel-js/service/BaseOtelService/BaseOtelService.js.map +1 -1
- package/dist/public/node/vendor/otel-js/service/DefaultOtelService/DefaultMeterProvider.js.map +1 -1
- package/dist/public/node/vendor/otel-js/utils/throttle.js.map +1 -1
- package/dist/public/node/vendor/otel-js/utils/validators.js.map +1 -1
- package/dist/public/node/version.js.map +1 -1
- package/dist/public/node/vscode.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +27 -29
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"postrun.js","sourceRoot":"","sources":["../../../../src/public/node/hooks/postrun.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,OAAO,IAAI,gBAAgB,EAAC,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAC,oBAAoB,EAAC,MAAM,iBAAiB,CAAA;AACpD,OAAO,EAAC,WAAW,EAAC,MAAM,gCAAgC,CAAA;AAE1D,OAAO,KAAK,QAAQ,MAAM,kCAAkC,CAAA;AAG5D,gGAAgG;A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,MAAM,OAAO,GAAG,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IAC7C,WAAW,CAAC,qBAAqB,OAAO,EAAE,CAAC,CAAA;AAC7C,CAAC,CAAA;AAED;;;;GAIG;AACH,KAAK,UAAU,iBAAiB,CAAC,YAAgD;IAC/E,MAAM,WAAW,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAA;IACxC,IAAI,YAAY,IAAI,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,YAAY,EAAE,sBAAsB,CAAC,EAAE,CAAC;QAC/F,MAAM,WAAW,GAAI,YAAmC,CAAC,oBAAoB,EAAE,CAAA;QAC/E,IAAI,WAAW,EAAE,CAAC;YAChB,MAAM,EAAC,mBAAmB,EAAC,GAAG,QAAQ,CAAC,uBAAuB,EAAE,CAAA;YAChE,MAAM,QAAQ,CAAC,oBAAoB,CAAC,GAAG,EAAE,CAAC,CAAC;gBACzC,mBAAmB,EAAE;oBACnB,oEAAoE;oBACpE,GAAG,mBAAoB;oBACvB,SAAS,EAAE,WAAW;oBACtB,YAAY,EAAE,WAAW;iBAC1B;aACF,CAAC,CAAC,CAAA;QACL,CAAC;IACH,CAAC;AACH,CAAC","sourcesContent":["import {postrun as deprecationsHook} from './deprecations.js'\nimport {reportAnalyticsEvent} from '../analytics.js'\nimport {outputDebug} from '../../../public/node/output.js'\nimport BaseCommand from '../base-command.js'\nimport * as metadata from '../../../public/node/metadata.js'\nimport {Command, Hook} from '@oclif/core'\n\n// This hook is called after each successful command run. More info: https://oclif.io/docs/hooks\nexport const hook: Hook.Postrun = async ({config, Command}) => {\n await detectStopCommand(Command as unknown as typeof Command)\n await reportAnalyticsEvent({config, exitMode: 'ok'})\n deprecationsHook(Command)\n\n const command = Command.id.replace(/:/g, ' ')\n outputDebug(`Completed command ${command}`)\n}\n\n/**\n * Override the command name with the stop one for analytics purposes.\n *\n * @param commandClass - Oclif command class.\n */\nasync function detectStopCommand(commandClass: Command.Class | typeof BaseCommand): Promise<void> {\n const currentTime = new Date().getTime()\n if (commandClass && Object.prototype.hasOwnProperty.call(commandClass, 'analyticsStopCommand')) {\n const stopCommand = (commandClass as typeof BaseCommand).analyticsStopCommand()\n if (stopCommand) {\n const {commandStartOptions} = metadata.getAllSensitiveMetadata()\n await metadata.addSensitiveMetadata(() => ({\n commandStartOptions: {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n ...commandStartOptions!,\n startTime: currentTime,\n startCommand: stopCommand,\n },\n }))\n }\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prerun.js","sourceRoot":"","sources":["../../../../src/public/node/hooks/prerun.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,eAAe,EAAC,MAAM,yBAAyB,CAAA;AACvD,OAAO,EAAC,kBAAkB,EAAE,wBAAwB,EAAC,MAAM,4BAA4B,CAAA;AACvF,OAAO,EAAC,cAAc,EAAC,MAAM,oCAAoC,CAAA;AACjE,OAAO,EAAC,WAAW,EAAE,UAAU,EAAC,MAAM,gCAAgC,CAAA;AACtE,OAAO,EAAC,0BAA0B,EAAC,MAAM,iCAAiC,CAAA;AAE1E,OAAO,EAAC,oBAAoB,EAAC,MAAM,qCAAqC,CAAA;AAQxE,sFAAsF;AACtF,MAAM,CAAC,MAAM,IAAI,GAAgB,KAAK,EAAE,OAAO,EAAE,EAAE;IACjD,MAAM,cAAc,GAAG,mBAAmB,CAAC;QACzC,EAAE,EAAE,OAAO,CAAC,OAAO,CAAC,EAAE;QACtB,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,OAAO;QAChC,WAAW,EAAE,OAAO,CAAC,OAAO,CAAC,MAAM,EAAE,KAAK;KAC3C,CAAC,CAAA;IACF,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAA;IACzB,MAAM,sBAAsB,EAAE,CAAA;IAC9B,WAAW,CAAC,mBAAmB,cAAc,CAAC,OAAO,EA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,EAAE,EAAE,CAC3C,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,CAC1E,CAAA;IACD,IAAI,aAAa,EAAE,CAAC;QAClB,OAAO,aAAa,CAAC,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;IACzC,CAAC;AACH,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB;IAC1C,MAAM,aAAa,GAAG,cAAc,CAAA;IACpC,MAAM,cAAc,GAAG,eAAe,CAAA;IACtC,IAAI,cAAc,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC;QACvC,yFAAyF;QACzF,OAAM;IACR,CAAC;IAED,sCAAsC;IACtC,mCAAmC;IACnC,KAAK,kBAAkB,CAAC,aAAa,EAAE,cAAc,EAAE,EAAC,kBAAkB,EAAE,EAAE,EAAC,CAAC,CAAA;IAEhF,4CAA4C;IAC5C,MAAM,oBAAoB,CAAC,2BAA2B,EAAE,EAAC,IAAI,EAAE,CAAC,EAAC,EAAE,KAAK,IAAI,EAAE;QAC5E,MAAM,YAAY,GAAG,wBAAwB,CAAC,aAAa,EAAE,cAAc,CAAC,CAAA;QAC5E,IAAI,YAAY,EAAE,CAAC;YACjB,UAAU,CAAC,0BAA0B,CAAC,YAAY,CAAC,CAAC,CAAA;QACtD,CAAC;IACH,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {CLI_KIT_VERSION} from '../../common/version.js'\nimport {checkForNewVersion, checkForCachedNewVersion} from '../node-package-manager.js'\nimport {startAnalytics} from '../../../private/node/analytics.js'\nimport {outputDebug, outputWarn} from '../../../public/node/output.js'\nimport {getOutputUpdateCLIReminder} from '../../../public/node/upgrade.js'\nimport Command from '../../../public/node/base-command.js'\nimport {runAtMinimumInterval} from '../../../private/node/conf-store.js'\nimport {Hook} from '@oclif/core'\n\nexport declare interface CommandContent {\n command: string\n topic?: string\n alias?: string\n}\n// This hook is called before each command run. More info: https://oclif.io/docs/hooks\nexport const hook: Hook.Prerun = async (options) => {\n const commandContent = parseCommandContent({\n id: options.Command.id,\n aliases: options.Command.aliases,\n pluginAlias: options.Command.plugin?.alias,\n })\n const args = options.argv\n await warnOnAvailableUpgrade()\n outputDebug(`Running command ${commandContent.command}`)\n await startAnalytics({commandContent, args, commandClass: options.Command as unknown as typeof Command})\n}\n\nexport function parseCommandContent(cmdInfo: {id: string; aliases: string[]; pluginAlias?: string}): CommandContent {\n let commandContent = parseCreateCommand(cmdInfo.pluginAlias)\n if (!commandContent) {\n commandContent = parseNormalCommand(cmdInfo.id, cmdInfo.aliases)\n }\n return commandContent\n}\n\nfunction parseNormalCommand(id: string, aliases: string[]): CommandContent {\n return {\n command: id.replace(/:/g, ' '),\n topic: parseTopic(id),\n alias: findAlias(aliases),\n }\n}\n\n/**\n * Create commands implement Init by default, so the name of the command must be extracted from\n * the plugin/module name. Neither alias or topic are supported\n *\n * @param commandClass - Oclif command configuration\n * @returns Command content with the name of the command or undefined otherwise\n */\nfunction parseCreateCommand(pluginAlias?: string): CommandContent | undefined {\n if (!pluginAlias?.startsWith('@shopify/create-')) {\n return undefined\n }\n\n return {command: pluginAlias.substring(pluginAlias.indexOf('/') + 1)}\n}\n\n/**\n * Commands use this pattern topic:subtopic1:...:subtopicN:command. This method extract the topic and subtopic\n * information replacing the ':' separator with one space\n *\n * @param cmd - Complete command string to extract the topic information\n * @returns The topic name or undefined otherwise\n */\nfunction parseTopic(cmd: string) {\n if (cmd.lastIndexOf(':') === -1) {\n return\n }\n return cmd.slice(0, cmd.lastIndexOf(':')).replace(/:/g, ' ')\n}\n\n/**\n * Identifies if the command was launched using an alias instead of the oficial command name\n *\n * @param aliases - List of possible alias a command has\n * @returns The alias used or undefined otherwise\n */\nfunction findAlias(aliases: string[]) {\n const existingAlias = aliases.find((alias) =>\n alias.split(':').every((aliasToken) => process.argv.includes(aliasToken)),\n )\n if (existingAlias) {\n return existingAlias.replace(/:/g, ' ')\n }\n}\n\n/**\n * Warns the user if there is a new version of the CLI available\n */\nexport async function warnOnAvailableUpgrade(): Promise<void> {\n const cliDependency = '@shopify/cli'\n const currentVersion = CLI_KIT_VERSION\n if (currentVersion.startsWith('0.0.0')) {\n // This is a nightly/snapshot/experimental version, so we don't want to check for updates\n return\n }\n\n // Check in the background, once daily\n // eslint-disable-next-line no-void\n void checkForNewVersion(cliDependency, currentVersion, {cacheExpiryInHours: 24})\n\n // Warn if we previously found a new version\n await runAtMinimumInterval('warn-on-available-upgrade', {days: 1}, async () => {\n const newerVersion = checkForCachedNewVersion(cliDependency, currentVersion)\n if (newerVersion) {\n outputWarn(getOutputUpdateCLIReminder(newerVersion))\n }\n })\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.js","sourceRoot":"","sources":["../../../src/public/node/http.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAA;AACjC,OAAO,EAAC,qBAAqB,EAAE,cAAc,EAAE,SAAS,EAAE,cAAc,EAAC,MAAM,SAAS,CAAA;AACxF,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,YAAY,EAAE,UAAU,EAAE,sBAAsB,EAAC,MAAM,mCAAmC,CAAA;AAClG,OAAO,EAAC,WAAW,EAAC,MAAM,gCAAgC,CAAA;AAC1D,OAAO,EAAC,aAAa,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACtE,OAAO,EAAC,yBAAyB,EAAC,MAAM,2BAA2B,CAAA;AACnE,OAAO,QAAQ,MAAM,WAAW,CAAA;AAChC,OAAO,SAA+C,MAAM,YAAY,CAAA;AAExE,OAAO,EAAC,UAAU,EAAE,OAAO,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAA;AAExD;;;;GAIG;AACH,MAAM,UAAU,QAAQ;I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B,CAAC,CAAC,GAAG,EAAE;QACpD,OAAO,IAAI,OAAO,CAAS,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAC7C,IAAI,CAAC,cAAc,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;gBACjC,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,CAAA;YACxB,CAAC;YAED,MAAM,IAAI,GAAG,qBAAqB,CAAC,EAAE,CAAC,CAAA;YAEtC,IAAI,CAAC,EAAE,CAAC,QAAQ,EAAE,GAAG,EAAE;gBACrB,IAAI,CAAC,KAAK,EAAE,CAAA;gBACZ,OAAO,CAAC,EAAE,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;YAEF,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;gBACvB,cAAc,CAAC,EAAE,CAAC,CAAA;gBAClB,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;YAEF,SAAS,CAAC,GAAG,EAAE,EAAC,QAAQ,EAAE,QAAQ,EAAC,CAAC;iBACjC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;gBACZ,GAAG,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAA;YACtB,CAAC,CAAC;iBACD,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE;gBACb,cAAc,CAAC,EAAE,CAAC,CAAA;gBAClB,MAAM,CAAC,GAAG,CAAC,CAAA;YACb,CAAC,CAAC,CAAA;QACN,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-base-to-string */\nimport {dirname} from './path.js'\nimport {createFileWriteStream, fileExistsSync, mkdirSync, unlinkFileSync} from './fs.js'\nimport {runWithTimer} from './metadata.js'\nimport {buildHeaders, httpsAgent, sanitizedHeadersOutput} from '../../private/node/api/headers.js'\nimport {sanitizeURL} from '../../private/node/api/urls.js'\nimport {outputContent, outputDebug} from '../../public/node/output.js'\nimport {simpleRequestWithDebugLog} from '../../private/node/api.js'\nimport FormData from 'form-data'\nimport nodeFetch, {RequestInfo, RequestInit, Response} from 'node-fetch'\n\nexport {FetchError, Request, Response} from 'node-fetch'\n\n/**\n * Create a new FormData object.\n *\n * @returns A FormData object.\n */\nexport function formData(): FormData {\n return new FormData()\n}\n\n/**\n * An interface that abstracts way node-fetch. When Node has built-in\n * support for \"fetch\" in the standard library, we can drop the node-fetch\n * dependency from here.\n * Note that we are exposing types from \"node-fetch\". The reason being is that\n * they are consistent with the Web API so if we drop node-fetch in the future\n * it won't require changes from the callers.\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n return runWithTimer('cmd_all_timing_network_ms')(() =>\n simpleRequestWithDebugLog({url: url.toString(), request: () => nodeFetch(url, init)}),\n )\n}\n\n/**\n * A fetch function to use with Shopify services. The function ensures the right\n * TLS configuragion is used based on the environment in which the service is running\n * (e.g. Spin).\n *\n * @param url - This defines the resource that you wish to fetch.\n * @param init - An object containing any custom settings that you want to apply to the request.\n * @returns A promise that resolves with the response.\n */\nexport async function shopifyFetch(url: RequestInfo, init?: RequestInit): Promise<Response> {\n const sanitizedUrl = sanitizeURL(url.toString())\n const options: RequestInit = {\n ...(init ?? {}),\n headers: {\n ...(await buildHeaders()),\n ...(init?.headers ?? {}),\n },\n }\n\n outputDebug(outputContent`Sending ${options.method ?? 'GET'} request to URL ${sanitizedUrl}\nWith request headers:\n${sanitizedHeadersOutput((options.headers ?? {}) as {[header: string]: string})}\n`)\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return simpleRequestWithDebugLog({\n url: url.toString(),\n request: async () => nodeFetch(url, {...init, agent: await httpsAgent()}),\n })\n })\n}\n\n/**\n * Download a file from a URL to a local path.\n *\n * @param url - The URL to download from.\n * @param to - The local path to download to.\n * @returns - A promise that resolves with the local path.\n */\nexport function downloadFile(url: string, to: string): Promise<string> {\n const sanitizedUrl = sanitizeURL(url)\n outputDebug(`Downloading ${sanitizedUrl} to ${to}`)\n\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return new Promise<string>((resolve, reject) => {\n if (!fileExistsSync(dirname(to))) {\n mkdirSync(dirname(to))\n }\n\n const file = createFileWriteStream(to)\n\n file.on('finish', () => {\n file.close()\n resolve(to)\n })\n\n file.on('error', (err) => {\n unlinkFileSync(to)\n reject(err)\n })\n\n nodeFetch(url, {redirect: 'follow'})\n .then((res) => {\n res.body?.pipe(file)\n })\n .catch((err) => {\n unlinkFileSync(to)\n reject(err)\n })\n })\n })\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"is-global.js","sourceRoot":"","sources":["../../../src/public/node/is-global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAE7C,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,GAAG,EAAE,YAAY,EAAC,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAC,aAAa,EAAE,IAAI,EAAE,yBAAyB,EAAC,MAAM,aAAa,CAAA;AAC1E,OAAO,EAAC,kBAAkB,EAAC,MAAM,SAAS,CAAA;AAC1C,OAAO,EAAC,SAAS,EAAC,MAAM,OAAO,CAAA;AAE/B,IAAI,SAA8B,CAAA;AAElC;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACxD,wDAAwD;IACxD,IAAI;
|
|
1
|
+
{"version":3,"file":"is-global.js","sourceRoot":"","sources":["../../../src/public/node/is-global.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAE7C,OAAO,EAAC,UAAU,EAAC,MAAM,aAAa,CAAA;AACtC,OAAO,EAAC,GAAG,EAAE,YAAY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B,EAAE,KAAK,EAAC,CAAA;AAC7D,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI;IACjE,IAAI,CAAC,sBAAsB,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IAEnD,mDAAmD;IACnD,MAAM,WAAW,GAAG,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;IACjC,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,MAAM,CAAC;QAAE,OAAO,MAAM,CAAA;IAC/C,IAAI,WAAW,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAA;IAC7C,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {PackageManager} from './node-package-manager.js'\nimport {outputInfo} from './output.js'\nimport {cwd, sniffForPath} from './path.js'\nimport {captureOutput, exec, terminalSupportsPrompting} from './system.js'\nimport {renderSelectPrompt} from './ui.js'\nimport {execaSync} from 'execa'\n\nlet _isGlobal: boolean | undefined\n\n/**\n * Returns true if the current process is running in a global context.\n *\n * @param argv - The arguments passed to the process.\n * @returns `true` if the current process is running in a global context.\n */\nexport function currentProcessIsGlobal(argv = process.argv): boolean {\n // If we are running tests, we need to disable the cache\n try {\n if (_isGlobal !== undefined && !isUnitTest()) return _isGlobal\n\n // Path where the current project is (app/hydrogen)\n const path = sniffForPath() ?? cwd()\n\n // Closest parent directory to contain a package.json file or node_modules directory\n // https://docs.npmjs.com/cli/v8/commands/npm-prefix#description\n const npmPrefix = execaSync('npm', ['prefix'], {cwd: path}).stdout.trim()\n\n // From node docs: \"The second element [of the array] will be the path to the JavaScript file being executed\"\n const binDir = argv[1] ?? ''\n\n // If binDir starts with npmPrefix, then we are running a local CLI\n const isLocal = binDir.startsWith(npmPrefix.trim())\n\n _isGlobal = !isLocal\n return _isGlobal\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return false\n }\n}\n\n/**\n * Returns true if the global CLI is installed.\n *\n * @returns `true` if the global CLI is installed.\n */\nexport async function isGlobalCLIInstalled(): Promise<boolean> {\n try {\n const env = {...process.env, SHOPIFY_CLI_NO_ANALYTICS: '1'}\n const output = await captureOutput('shopify', ['app'], {env})\n // Installed if `app dev` is available globally\n return output.includes('app dev')\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Installs the global Shopify CLI, using the provided package manager.\n *\n * @param packageManager - The package manager to use.\n */\nexport async function installGlobalShopifyCLI(packageManager: PackageManager): Promise<void> {\n const args =\n packageManager === 'yarn' ? ['global', 'add', '@shopify/cli@latest'] : ['install', '-g', '@shopify/cli@latest']\n outputInfo(`Running ${packageManager} ${args.join(' ')}...`)\n await exec(packageManager, args, {stdio: 'inherit'})\n}\n\nexport interface InstallGlobalCLIPromptResult {\n install: boolean\n alreadyInstalled: boolean\n}\n/**\n * Prompts the user to install the global CLI.\n *\n * @returns `true` if the user has installed the global CLI.\n */\nexport async function installGlobalCLIPrompt(): Promise<InstallGlobalCLIPromptResult> {\n if (!terminalSupportsPrompting()) return {install: false, alreadyInstalled: false}\n if (await isGlobalCLIInstalled()) {\n return {install: false, alreadyInstalled: true}\n }\n const result = await renderSelectPrompt({\n message: 'We recommend installing Shopify CLI globally in your system. Would you like to install it now?',\n choices: [\n {value: 'yes', label: 'Yes'},\n {value: 'no', label: 'No, just for this project'},\n ],\n })\n\n return {install: result === 'yes', alreadyInstalled: false}\n}\n\n/**\n * Infers the package manager used by the global CLI.\n *\n * @param argv - The arguments passed to the process.\n * @returns The package manager used by the global CLI.\n */\nexport function inferPackageManagerForGlobalCLI(argv = process.argv): PackageManager {\n if (!currentProcessIsGlobal(argv)) return 'unknown'\n\n // argv[1] contains the path of the executed binary\n const processArgv = argv[1] ?? ''\n if (processArgv.includes('yarn')) return 'yarn'\n if (processArgv.includes('pnpm')) return 'pnpm'\n if (processArgv.includes('bun')) return 'bun'\n return 'npm'\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../../src/public/node/json-schema.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,YAAY,EAAC,MAAM,qBAAqB,CAAA;AAChD,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAC,GAAG,EAA8C,MAAM,KAAK,CAAA;AACpE,OAAO,UAAU,MAAM,qCAAqC,CAAA;AAI5D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,MAAc;IACtD,0FAA0F;IAC1F,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACvC,MAAM,UAAU,CAAC,WAAW,CAAC,YAAY,EAAE,EAAC,OAAO,EAAE,EAAC,QAAQ,EAAE,KAAK,EAAC,EAAC,CAAC,CAAA;IACxE,OAAO,YAAY,CAAA;AACrB,CAAC;AAED,MAAM,eAAe,GAAG,IAAI,GAAG,EAA4B,CAAA;AAE3D;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAe,EACf,MAAoB,EACpB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,EAAC,eAAe,EAAE,IAAI,EAAC,CAAC,CAAA;IAE5C,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,CAAA;IAEzB,MAAM,SAAS,GAAG,eAAe,CAAC,GAAG,CAAC,UAAU,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,MAAM,CAAC,CAAA;IACxE,eAAe,CAAC,GAAG,CAAC,UAAU,EAAE,SAAS,CAAC,CAAA;IAE1C,SAAS,CAAC,OAAO,CAAC,CAAA;IAElB,iGAAiG;IACjG,IAAI,gBAAgB,CAAA;IACpB,IAAI,SAAS,CAAC,MAAM,IAAI,SAAS,CAA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BAED,OAAO,CAAC,KAAK,EAAE,wBAAwB,CAAC,MAAO,CAAU,CAAA;YAC3D,CAAC,CAAC;iBACD,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,MAAM,GAAG,MAAM,CAAC,CAAA;YAEhD,IAAI,sBAAsB,CAAC,MAAM,IAAI,CAAC,EAAE;gBACtC,MAAM,CAAC,SAAS,EAAE,UAAU,CAAC,GAAG,sBAAsB,CAAC,sBAAsB,CAAC,MAAM,GAAG,CAAC,CAAE,CAAA;gBAC1F,MAAM,CAAC,gBAAgB,CAAC,GAAG,sBAAsB,CAAC,sBAAsB,CAAC,MAAM,GAAG,CAAC,CAAE,CAAA;gBAErF,IAAI,SAAS,KAAK,gBAAgB,EAAE;oBAClC,4FAA4F;oBAC5F,+EAA+E;oBAC/E,4BAA4B,GAAG;wBAC7B,UAAU;wBACV,GAAG,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;4BAChC,GAAG,SAAS;4BACZ,YAAY,EAAE,UAAU,CAAC,YAAY,GAAG,SAAS,CAAC,YAAY;yBAC/D,CAAC,CAAC;qBACJ,CAAA;iBACF;aACF;SACF;QACD,MAAM,GAAG,CAAC,GAAG,eAAe,EAAE,GAAG,4BAA4B,CAAC,CAAA;QAE9D,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,YAAY,CAAC,CAAA;KACjD;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport {ParseConfigurationResult} from './schema.js'\nimport {getPathValue} from '../common/object.js'\nimport {capitalize} from '../common/string.js'\nimport {Ajv, ErrorObject, SchemaObject, ValidateFunction} from 'ajv'\nimport $RefParser from '@apidevtools/json-schema-ref-parser'\n\ntype AjvError = ErrorObject<string, {[key: string]: unknown}>\n\n/**\n * Normalises a JSON Schema by standardising it's internal implementation.\n *\n * We prefer to not use $ref elements in our schemas, so we inline them; it's easier then to process errors.\n *\n * @param schema - The JSON schema (as a string) to normalise.\n * @returns The normalised JSON schema.\n */\nexport async function normaliseJsonSchema(schema: string): Promise<SchemaObject> {\n // we want to modify the schema, removing any $ref elements and inlining with their source\n const parsedSchema = JSON.parse(schema)\n await $RefParser.dereference(parsedSchema, {resolve: {external: false}})\n return parsedSchema\n}\n\nconst validatorsCache = new Map<string, ValidateFunction>()\n\n/**\n * Given a subject object and a JSON schema contract, validate the subject against the contract.\n *\n * Errors are returned in a zod-like format, and processed to better handle unions.\n *\n * @param subject - The object to validate.\n * @param schema - The JSON schema to validate against.\n * @param identifier - The identifier of the schema being validated, used to cache the validator.\n * @returns The result of the validation. If the state is 'error', the errors will be in a zod-like format.\n */\nexport function jsonSchemaValidate(\n subject: object,\n schema: SchemaObject,\n identifier: string,\n): ParseConfigurationResult<unknown> & {rawErrors?: AjvError[]} {\n const ajv = new Ajv({allowUnionTypes: true})\n\n ajv.addKeyword('x-taplo')\n\n const validator = validatorsCache.get(identifier) ?? ajv.compile(schema)\n validatorsCache.set(identifier, validator)\n\n validator(subject)\n\n // Errors from the contract are post-processed to be more zod-like and to deal with unions better\n let jsonSchemaErrors\n if (validator.errors && validator.errors.length > 0) {\n jsonSchemaErrors = convertJsonSchemaErrors(validator.errors, subject, schema)\n return {\n state: 'error',\n data: undefined,\n errors: jsonSchemaErrors,\n rawErrors: validator.errors,\n }\n }\n return {\n state: 'ok',\n data: subject,\n errors: undefined,\n rawErrors: undefined,\n }\n}\n\n/**\n * Converts errors from Ajv into a zod-like format.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns The errors in a zod-like format.\n */\nfunction convertJsonSchemaErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject) {\n // This reduces the number of errors by simplifying errors coming from different branches of a union\n const errors = simplifyUnionErrors(rawErrors, subject, schema)\n\n // Now we can remap errors to be more zod-like\n return errors.map((error) => {\n const path: string[] = error.instancePath.split('/').slice(1)\n if (error.params.missingProperty) {\n const missingProperty = error.params.missingProperty as string\n return {path: [...path, missingProperty], message: 'Required'}\n }\n\n if (error.params.type) {\n const expectedType = error.params.type as string\n const actualType = getPathValue(subject, path.join('.'))\n return {path, message: `Expected ${expectedType}, received ${typeof actualType}`}\n }\n\n if (error.keyword === 'anyOf' || error.keyword === 'oneOf') {\n return {path, message: 'Invalid input'}\n }\n\n if (error.params.allowedValues) {\n const allowedValues = error.params.allowedValues as string[]\n const actualValue = getPathValue(subject, path.join('.'))\n return {\n path,\n message: `Invalid enum value. Expected ${allowedValues\n .map((value) => JSON.stringify(value))\n .join(' | ')}, received ${JSON.stringify(actualValue)}`.replace(/\"/g, \"'\"),\n }\n }\n\n if (error.params.comparison) {\n const comparison = error.params.comparison as string\n const limit = error.params.limit\n const actualValue = getPathValue(subject, path.join('.'))\n\n let comparisonText = comparison\n switch (comparison) {\n case '<=':\n comparisonText = 'less than or equal to'\n break\n case '<':\n comparisonText = 'less than'\n break\n case '>=':\n comparisonText = 'greater than or equal to'\n break\n case '>':\n comparisonText = 'greater than'\n break\n }\n\n return {\n path,\n message: capitalize(`${typeof actualValue} must be ${comparisonText} ${limit}`),\n }\n }\n\n return {\n path,\n message: error.message,\n }\n })\n}\n\n/**\n * If a JSON schema specifies a union (anyOf, oneOf), and the subject doesn't meet any of the 'candidates' for the\n * union, then the error list received ends up being quite long: you get an error for the union property itself, and\n * then additional errors for each of the candidate branches.\n *\n * This function simplifies the error collection. By default it strips anything other than the union error itself.\n *\n * In some cases, it can be possible to identify what the intended branch of the union was -- for instance, maybe there\n * is a discriminating field like `type` that is unique between the branches. We inspect each candidate branch and if\n * one branch is less wrong than the others -- e.g. It had a valid `type`, but problems elsewhere -- then we keep the\n * errors for that branch.\n *\n * This is complex but in practise gives much more actionable errors.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns A simplified list of errors.\n */\nfunction simplifyUnionErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject): AjvError[] {\n const ajv = new Ajv({allowUnionTypes: true})\n ajv.addKeyword('x-taplo')\n let errors = rawErrors\n\n const resolvedUnionErrors = new Set()\n while (true) {\n const unionError = errors.filter(\n (error) =>\n (error.keyword === 'oneOf' || error.keyword === 'anyOf') && !resolvedUnionErrors.has(error.instancePath),\n )[0]\n if (unionError === undefined) {\n break\n }\n // split errors into those sharing an instance path and those not\n const unrelatedErrors = errors.filter((error) => !error.instancePath.startsWith(unionError.instancePath))\n\n // we start by assuming only the union error itself is useful, and not the errors from the candidate schemas\n let simplifiedUnionRelatedErrors: AjvError[] = [unionError]\n\n // get the schema list from where the union issue occured\n const dottedSchemaPath = unionError.schemaPath.replace('#/', '').replace(/\\//g, '.')\n const unionSchemas = getPathValue<SchemaObject[]>(schema, dottedSchemaPath)\n // and the slice of the subject that caused the issue\n const subjectValue = getPathValue(subject, unionError.instancePath.split('/').slice(1).join('.'))\n\n if (unionSchemas !== undefined && subjectValue !== undefined) {\n // we know that none of the union schemas are correct, but for each of them we can measure how wrong they are\n const correctValuesAndErrors = unionSchemas\n .map((candidateSchemaFromUnion: SchemaObject) => {\n const candidateSchemaValidator = ajv.compile(candidateSchemaFromUnion)\n candidateSchemaValidator(subjectValue)\n\n let score = 0\n if (candidateSchemaFromUnion.type === 'object') {\n // provided the schema is an object, we can measure how many properties are good\n const candidatesObjectProperties = Object.keys(candidateSchemaFromUnion.properties)\n score = candidatesObjectProperties.reduce((acc, propertyName) => {\n const subSchema = candidateSchemaFromUnion.properties[propertyName] as SchemaObject\n const subjectValueSlice = getPathValue(subjectValue, propertyName)\n\n const subValidator = ajv.compile(subSchema)\n if (subValidator(subjectValueSlice)) {\n return acc + 1\n }\n return acc\n }, score)\n }\n\n return [score, candidateSchemaValidator.errors!] as const\n })\n .sort(([scoreA], [scoreB]) => scoreA - scoreB)\n\n if (correctValuesAndErrors.length >= 2) {\n const [bestScore, bestErrors] = correctValuesAndErrors[correctValuesAndErrors.length - 1]!\n const [penultimateScore] = correctValuesAndErrors[correctValuesAndErrors.length - 2]!\n\n if (bestScore !== penultimateScore) {\n // If there's a winner, show the errors for the best schema as they'll likely be actionable.\n // We got these through a nested schema, so we need to adjust the instance path\n simplifiedUnionRelatedErrors = [\n unionError,\n ...bestErrors.map((bestError) => ({\n ...bestError,\n instancePath: unionError.instancePath + bestError.instancePath,\n })),\n ]\n }\n }\n }\n errors = [...unrelatedErrors, ...simplifiedUnionRelatedErrors]\n\n resolvedUnionErrors.add(unionError.instancePath)\n }\n return errors\n}\n"]}
|
|
1
|
+
{"version":3,"file":"json-schema.js","sourceRoot":"","sources":["../../../src/public/node/json-schema.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,YAAY,EAAC,MAAM,qBAAqB,CAAA;AAChD,OAAO,EAAC,UAAU,EAAC,MAAM,qBAAqB,CAAA;AAC9C,OAAO,EAAC,GAAG,EAA8C,MAAM,KAAK,CAAA;AACpE,OAAO,UAAU,MAAM,qCAAqC,CAAA;AAI5D;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,MAAc;IACtD,0FAA0F;IAC1F,MAAM,YAAY,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACvC,MAAM,UAAU,CAAC,WAAW,CAAC,YAAY,EAAE,EAAC,OAAO,EAAE,EAAC,QAAQ,EAAE,KAAK,EAAC,EAAC,CAAC,CAAA;IACxE,OAAO,YAAY,CAAA;AACrB,CAAC;AAED,MAAM,eAAe,GAAG,IAAI,GAAG,EAA4B,CAAA;AAE3D;;;;;;;;;GASG;AACH,MAAM,UAAU,kBAAkB,CAChC,OAAe,EACf,MAAoB,EACpB,UAAkB;IAElB,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,EAAC,eAAe,EAAE,IAAI,EAAC,CAAC,CAAA;IAE5C,GAAG,CAAC,UAAU,CAAC,SAAS,CAAC,CAAA;I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,GAAG,CAAC,GAAG,eAAe,EAAE,GAAG,4BAA4B,CAAC,CAAA;QAE9D,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,YAAY,CAAC,CAAA;IAClD,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["/* eslint-disable @typescript-eslint/no-non-null-assertion */\nimport {ParseConfigurationResult} from './schema.js'\nimport {getPathValue} from '../common/object.js'\nimport {capitalize} from '../common/string.js'\nimport {Ajv, ErrorObject, SchemaObject, ValidateFunction} from 'ajv'\nimport $RefParser from '@apidevtools/json-schema-ref-parser'\n\ntype AjvError = ErrorObject<string, {[key: string]: unknown}>\n\n/**\n * Normalises a JSON Schema by standardising it's internal implementation.\n *\n * We prefer to not use $ref elements in our schemas, so we inline them; it's easier then to process errors.\n *\n * @param schema - The JSON schema (as a string) to normalise.\n * @returns The normalised JSON schema.\n */\nexport async function normaliseJsonSchema(schema: string): Promise<SchemaObject> {\n // we want to modify the schema, removing any $ref elements and inlining with their source\n const parsedSchema = JSON.parse(schema)\n await $RefParser.dereference(parsedSchema, {resolve: {external: false}})\n return parsedSchema\n}\n\nconst validatorsCache = new Map<string, ValidateFunction>()\n\n/**\n * Given a subject object and a JSON schema contract, validate the subject against the contract.\n *\n * Errors are returned in a zod-like format, and processed to better handle unions.\n *\n * @param subject - The object to validate.\n * @param schema - The JSON schema to validate against.\n * @param identifier - The identifier of the schema being validated, used to cache the validator.\n * @returns The result of the validation. If the state is 'error', the errors will be in a zod-like format.\n */\nexport function jsonSchemaValidate(\n subject: object,\n schema: SchemaObject,\n identifier: string,\n): ParseConfigurationResult<unknown> & {rawErrors?: AjvError[]} {\n const ajv = new Ajv({allowUnionTypes: true})\n\n ajv.addKeyword('x-taplo')\n\n const validator = validatorsCache.get(identifier) ?? ajv.compile(schema)\n validatorsCache.set(identifier, validator)\n\n validator(subject)\n\n // Errors from the contract are post-processed to be more zod-like and to deal with unions better\n let jsonSchemaErrors\n if (validator.errors && validator.errors.length > 0) {\n jsonSchemaErrors = convertJsonSchemaErrors(validator.errors, subject, schema)\n return {\n state: 'error',\n data: undefined,\n errors: jsonSchemaErrors,\n rawErrors: validator.errors,\n }\n }\n return {\n state: 'ok',\n data: subject,\n errors: undefined,\n rawErrors: undefined,\n }\n}\n\n/**\n * Converts errors from Ajv into a zod-like format.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns The errors in a zod-like format.\n */\nfunction convertJsonSchemaErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject) {\n // This reduces the number of errors by simplifying errors coming from different branches of a union\n const errors = simplifyUnionErrors(rawErrors, subject, schema)\n\n // Now we can remap errors to be more zod-like\n return errors.map((error) => {\n const path: string[] = error.instancePath.split('/').slice(1)\n if (error.params.missingProperty) {\n const missingProperty = error.params.missingProperty as string\n return {path: [...path, missingProperty], message: 'Required'}\n }\n\n if (error.params.type) {\n const expectedType = error.params.type as string\n const actualType = getPathValue(subject, path.join('.'))\n return {path, message: `Expected ${expectedType}, received ${typeof actualType}`}\n }\n\n if (error.keyword === 'anyOf' || error.keyword === 'oneOf') {\n return {path, message: 'Invalid input'}\n }\n\n if (error.params.allowedValues) {\n const allowedValues = error.params.allowedValues as string[]\n const actualValue = getPathValue(subject, path.join('.'))\n return {\n path,\n message: `Invalid enum value. Expected ${allowedValues\n .map((value) => JSON.stringify(value))\n .join(' | ')}, received ${JSON.stringify(actualValue)}`.replace(/\"/g, \"'\"),\n }\n }\n\n if (error.params.comparison) {\n const comparison = error.params.comparison as string\n const limit = error.params.limit\n const actualValue = getPathValue(subject, path.join('.'))\n\n let comparisonText = comparison\n switch (comparison) {\n case '<=':\n comparisonText = 'less than or equal to'\n break\n case '<':\n comparisonText = 'less than'\n break\n case '>=':\n comparisonText = 'greater than or equal to'\n break\n case '>':\n comparisonText = 'greater than'\n break\n }\n\n return {\n path,\n message: capitalize(`${typeof actualValue} must be ${comparisonText} ${limit}`),\n }\n }\n\n return {\n path,\n message: error.message,\n }\n })\n}\n\n/**\n * If a JSON schema specifies a union (anyOf, oneOf), and the subject doesn't meet any of the 'candidates' for the\n * union, then the error list received ends up being quite long: you get an error for the union property itself, and\n * then additional errors for each of the candidate branches.\n *\n * This function simplifies the error collection. By default it strips anything other than the union error itself.\n *\n * In some cases, it can be possible to identify what the intended branch of the union was -- for instance, maybe there\n * is a discriminating field like `type` that is unique between the branches. We inspect each candidate branch and if\n * one branch is less wrong than the others -- e.g. It had a valid `type`, but problems elsewhere -- then we keep the\n * errors for that branch.\n *\n * This is complex but in practise gives much more actionable errors.\n *\n * @param rawErrors - JSON Schema errors taken directly from Ajv.\n * @param subject - The object being validated.\n * @param schema - The JSON schema to validated against.\n * @returns A simplified list of errors.\n */\nfunction simplifyUnionErrors(rawErrors: AjvError[], subject: object, schema: SchemaObject): AjvError[] {\n const ajv = new Ajv({allowUnionTypes: true})\n ajv.addKeyword('x-taplo')\n let errors = rawErrors\n\n const resolvedUnionErrors = new Set()\n while (true) {\n const unionError = errors.filter(\n (error) =>\n (error.keyword === 'oneOf' || error.keyword === 'anyOf') && !resolvedUnionErrors.has(error.instancePath),\n )[0]\n if (unionError === undefined) {\n break\n }\n // split errors into those sharing an instance path and those not\n const unrelatedErrors = errors.filter((error) => !error.instancePath.startsWith(unionError.instancePath))\n\n // we start by assuming only the union error itself is useful, and not the errors from the candidate schemas\n let simplifiedUnionRelatedErrors: AjvError[] = [unionError]\n\n // get the schema list from where the union issue occured\n const dottedSchemaPath = unionError.schemaPath.replace('#/', '').replace(/\\//g, '.')\n const unionSchemas = getPathValue<SchemaObject[]>(schema, dottedSchemaPath)\n // and the slice of the subject that caused the issue\n const subjectValue = getPathValue(subject, unionError.instancePath.split('/').slice(1).join('.'))\n\n if (unionSchemas !== undefined && subjectValue !== undefined) {\n // we know that none of the union schemas are correct, but for each of them we can measure how wrong they are\n const correctValuesAndErrors = unionSchemas\n .map((candidateSchemaFromUnion: SchemaObject) => {\n const candidateSchemaValidator = ajv.compile(candidateSchemaFromUnion)\n candidateSchemaValidator(subjectValue)\n\n let score = 0\n if (candidateSchemaFromUnion.type === 'object') {\n // provided the schema is an object, we can measure how many properties are good\n const candidatesObjectProperties = Object.keys(candidateSchemaFromUnion.properties)\n score = candidatesObjectProperties.reduce((acc, propertyName) => {\n const subSchema = candidateSchemaFromUnion.properties[propertyName] as SchemaObject\n const subjectValueSlice = getPathValue(subjectValue, propertyName)\n\n const subValidator = ajv.compile(subSchema)\n if (subValidator(subjectValueSlice)) {\n return acc + 1\n }\n return acc\n }, score)\n }\n\n return [score, candidateSchemaValidator.errors!] as const\n })\n .sort(([scoreA], [scoreB]) => scoreA - scoreB)\n\n if (correctValuesAndErrors.length >= 2) {\n const [bestScore, bestErrors] = correctValuesAndErrors[correctValuesAndErrors.length - 1]!\n const [penultimateScore] = correctValuesAndErrors[correctValuesAndErrors.length - 2]!\n\n if (bestScore !== penultimateScore) {\n // If there's a winner, show the errors for the best schema as they'll likely be actionable.\n // We got these through a nested schema, so we need to adjust the instance path\n simplifiedUnionRelatedErrors = [\n unionError,\n ...bestErrors.map((bestError) => ({\n ...bestError,\n instancePath: unionError.instancePath + bestError.instancePath,\n })),\n ]\n }\n }\n }\n errors = [...unrelatedErrors, ...simplifiedUnionRelatedErrors]\n\n resolvedUnionErrors.add(unionError.instancePath)\n }\n return errors\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"liquid.js","sourceRoot":"","sources":["../../../src/public/node/liquid.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,KAAK,EACL,WAAW,EACX,SAAS,EACT,4BAA4B,EAC5B,IAAI,EACJ,UAAU,EACV,SAAS,GACV,MAAM,SAAS,CAAA;AAChB,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAC,MAAM,WAAW,CAAA;AACzD,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,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AAA;YACjE,MAAM,QAAQ,CAAC,gBAAgB,EAAE,uBAAuB,CAAC,CAAA;YACzD,MAAM,SAAS,CAAC,uBAAuB,EAAE,aAAa,CAAC,CAAA;YACvD,IAAI,YAAY,EAAE,CAAC;gBACjB,MAAM,KAAK,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAA;YAC7C,CAAC;QACH,CAAC;aAAM,IAAI,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE,CAAC;YAC7C,MAAM,oBAAoB,GAAG,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;YAC3D,MAAM,QAAQ,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CAAA;QACxD,CAAC;aAAM,CAAC;YACN,MAAM,QAAQ,CAAC,gBAAgB,EAAE,UAAU,CAAC,CAAA;QAC9C,CAAC;IACH,CAAC,CAAC,CACH,CAAA;AACH,CAAC","sourcesContent":["import {\n mkdir,\n readFile,\n copyFile,\n chmod,\n isDirectory,\n writeFile,\n fileHasExecutablePermissions,\n glob,\n fileExists,\n matchGlob,\n} from './fs.js'\nimport {joinPath, dirname, relativePath} from './path.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {Liquid} from 'liquidjs'\n\n/**\n * Renders a template using the Liquid template engine.\n *\n * @param templateContent - Template content.\n * @param data - Data to feed the template engine.\n * @returns Rendered template.\n */\nexport function renderLiquidTemplate(templateContent: string, data: object): Promise<string> {\n const engine = new Liquid()\n return engine.render(engine.parse(templateContent), data)\n}\n\n/**\n * Given a directory, it traverses the files and directories recursively\n * and replaces variables in directory and file names, and files' content\n * using the Liquid template engine.\n * Files indicate that they are liquid template by using the .liquid extension.\n *\n * @param from - Directory that contains the template.\n * @param to - Output directory.\n * @param data - Data to feed the template engine.\n */\nexport async function recursiveLiquidTemplateCopy(from: string, to: string, data: object): Promise<void> {\n outputDebug(outputContent`Copying template from directory ${outputToken.path(from)} to ${outputToken.path(to)}`)\n const templateFiles: string[] = await glob(joinPath(from, '**/*'), {dot: true})\n\n const bypassPaths = joinPath(from, '.cli-liquid-bypass')\n let bypassPatterns: string[] = []\n if (await fileExists(bypassPaths)) {\n bypassPatterns = (await readFile(bypassPaths)).split('\\n').filter((line) => line.trim().length > 0)\n }\n\n const sortedTemplateFiles = templateFiles\n .map((path) => path.split('/'))\n .sort((lhs, rhs) => (lhs.length < rhs.length ? 1 : -1))\n .map((components) => components.join('/'))\n await Promise.all(\n sortedTemplateFiles.map(async (templateItemPath) => {\n const outputPath = await renderLiquidTemplate(joinPath(to, relativePath(from, templateItemPath)), data)\n const bypass = bypassPatterns.some((pattern) => {\n const path = relativePath(from, templateItemPath)\n const cleanPattern = pattern.replace(/^\\.\\//, '')\n\n return matchGlob(path, cleanPattern) || path.startsWith(cleanPattern)\n })\n\n if (await isDirectory(templateItemPath)) {\n await mkdir(outputPath)\n } else if (templateItemPath.endsWith('.liquid') && !bypass) {\n await mkdir(dirname(outputPath))\n const content = await readFile(templateItemPath)\n const contentOutput = await renderLiquidTemplate(content, data)\n const isExecutable = await fileHasExecutablePermissions(templateItemPath)\n const outputPathWithoutLiquid = outputPath.replace('.liquid', '')\n await copyFile(templateItemPath, outputPathWithoutLiquid)\n await writeFile(outputPathWithoutLiquid, contentOutput)\n if (isExecutable) {\n await chmod(outputPathWithoutLiquid, 0o755)\n }\n } else if (templateItemPath.endsWith('.raw')) {\n const outputPathWithoutRaw = outputPath.replace('.raw', '')\n await copyFile(templateItemPath, outputPathWithoutRaw)\n } else {\n await copyFile(templateItemPath, outputPath)\n }\n }),\n )\n}\n"]}
|
|
@@ -95,7 +95,7 @@ export function createRuntimeMetadataContainer(defaultPublicMetadata = {}) {
|
|
|
95
95
|
const duration = Math.max(wallClockDuration - childDurations, 0);
|
|
96
96
|
// If this is the topmost timer, the stack will be empty.
|
|
97
97
|
if (durationStack.length > 0) {
|
|
98
|
-
durationStack[durationStack.length - 1]
|
|
98
|
+
durationStack[durationStack.length - 1] = (durationStack[durationStack.length - 1] ?? 0) + wallClockDuration;
|
|
99
99
|
}
|
|
100
100
|
// Log it -- we include it in the metadata, but also log via the standard performance API. The TS types for this library are not quite right, so we have to cast to `any` here.
|
|
101
101
|
performance.measure(`${field}#measurable`, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../src/public/node/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAC,WAAW,EAAC,MAAM,iBAAiB,CAAA;AAe3C;;;;GAIG;AACH,SAAS,gCAAgC;IACvC,IAAI,UAAU,EAAE,EAAE;QAChB,OAAO,QAAQ,CAAA;KAChB;IACD,OAAO,iBAAiB,CAAA;AAC1B,CAAC;AA4BD;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAG5C,wBAA0C,EAAE;IAC5C,MAAM,GAAG,GAA+D;QACtE,SAAS,EAAE,EAAE;QACb,MAAM,EAAE;YACN,GAAG,qBAAqB;SACzB;KACF,CAAA;IACD,MAAM,SAAS,GAAG,CAAC,IAAsB,EAAE,EAAE;QAC3C,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IACjC,CAAC,CAAA;IACD,MAAM,YAAY,GAAG,CAAC,IAAyB,EAAE,EAAE;QACjD,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACpC,CAAC,CAAA;IAED,MAAM,WAAW,GAAG,KAAK,EACvB,KAAiC,EACjC,KAAyB,EACzB,OAA8B,EAC9B,EAAE;QACF,MAAM,aAAa,GAAG,OAAO,KAAK,MAAM,CAAC,CAAC,CAAC,gCAAgC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAA;QACvF,MAAM,SAAS,GAAG,KAAK,IAAI,EAAE;YAC3B,MAAM,IAAI,GAAG,MAAM,KAAK,EAAE,CAAA;YAC1B,KAAK,C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B,EAAE,CAAC,EAAC,CAAC,CAAA;AAE/D,MAAM,CAAC,MAAM,EAAC,oBAAoB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,YAAY,EAAC,GACjH,QAAQ,CAAA","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {performance} from 'node:perf_hooks'\nimport type {PickByPrefix} from '../common/ts/pick-by-prefix.js'\nimport type {AnyJson} from '../../private/common/json.js'\nimport type {MonorailEventPublic} from './monorail.js'\n\ntype ProvideMetadata<T> = () => Partial<T> | Promise<Partial<T>>\n\ntype MetadataErrorHandling =\n // Mute & report errors in production, throw them whilst testing\n | 'auto'\n // Errors are not reported to the user and do not stop execution, but they are reported to Bugsnag\n | 'mute-and-report'\n // Errors are not caught and will bubble out as normal\n | 'bubble'\n\n/**\n * Get the error handling strategy for metadata.\n *\n * @returns 'mute-and-report' in production, 'bubble' in tests.\n */\nfunction getMetadataErrorHandlingStrategy(): 'mute-and-report' | 'bubble' {\n if (isUnitTest()) {\n return 'bubble'\n }\n return 'mute-and-report'\n}\n\n/**\n * Any key in T that has a numeric value.\n */\ntype NumericKeyOf<T> = {\n [K in keyof T]: T[K] extends number ? (K extends string ? K : never) : never\n}[keyof T]\n\nexport interface RuntimeMetadataManager<TPublic extends AnyJson, TSensitive extends AnyJson> {\n /** Add some public metadata -- this should not contain any PII. */\n addPublicMetadata: (getData: ProvideMetadata<TPublic>, onError?: MetadataErrorHandling) => Promise<void>\n /**\n * Add some potentially sensitive metadata -- this may include PII, but unnecessary data should never be tracked\n * (this is a good fit for command args for instance).\n */\n addSensitiveMetadata: (getData: ProvideMetadata<TSensitive>, onError?: MetadataErrorHandling) => Promise<void>\n /** Get a snapshot of the tracked public data. */\n getAllPublicMetadata: () => Partial<TPublic>\n /** Get a snapshot of the tracked sensitive data. */\n getAllSensitiveMetadata: () => Partial<TSensitive>\n /** Run a function, monitoring how long it takes, and adding the elapsed time to a running total. */\n runWithTimer: (field: NumericKeyOf<TPublic>) => <T>(fn: () => Promise<T>) => Promise<T>\n}\n\nexport type PublicSchema<T> = T extends RuntimeMetadataManager<infer TPublic, infer _TSensitive> ? TPublic : never\nexport type SensitiveSchema<T> = T extends RuntimeMetadataManager<infer _TPublic, infer TSensitive> ? TSensitive : never\n\n/**\n * Creates a container for metadata collected at runtime.\n * The container provides async-safe functions for extracting the gathered metadata, and for setting it.\n *\n * @param defaultPublicMetadata - Optional, default data for the container.\n * @returns A container for the metadata.\n */\nexport function createRuntimeMetadataContainer<\n TPublic extends AnyJson,\n TSensitive extends AnyJson = {[key: string]: never},\n>(defaultPublicMetadata: Partial<TPublic> = {}): RuntimeMetadataManager<TPublic, TSensitive> {\n const raw: {sensitive: Partial<TSensitive>; public: Partial<TPublic>} = {\n sensitive: {},\n public: {\n ...defaultPublicMetadata,\n },\n }\n const addPublic = (data: Partial<TPublic>) => {\n Object.assign(raw.public, data)\n }\n const addSensitive = (data: Partial<TSensitive>) => {\n Object.assign(raw.sensitive, data)\n }\n\n const addMetadata = async <T>(\n addFn: (data: Partial<T>) => void,\n getFn: ProvideMetadata<T>,\n onError: MetadataErrorHandling,\n ) => {\n const errorHandling = onError === 'auto' ? getMetadataErrorHandlingStrategy() : onError\n const getAndSet = async () => {\n const data = await getFn()\n addFn(data)\n }\n\n if (errorHandling === 'bubble') {\n await getAndSet()\n } else {\n try {\n await getAndSet()\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (error: any) {\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(error, 'unexpected_error')\n }\n }\n }\n\n // See `runWithTimer` below.\n const durationStack: number[] = []\n\n return {\n getAllPublicMetadata: () => {\n return {...raw.public}\n },\n getAllSensitiveMetadata: () => {\n return {...raw.sensitive}\n },\n addPublicMetadata: async (getData: ProvideMetadata<TPublic>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addPublic, getData, onError)\n },\n addSensitiveMetadata: async (getData: ProvideMetadata<TSensitive>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addSensitive, getData, onError)\n },\n runWithTimer: (field: NumericKeyOf<TPublic>): (<T>(fn: () => Promise<T>) => Promise<T>) => {\n return async (fn) => {\n /**\n * For nested timers, we subtract the inner timer's duration from the outer timer's. We use a stack to track the\n * cumulative durations of nested timers. On starting a timer, we push a zero onto the stack to initialize the total\n * duration for subsequent nested timers. Before logging, we pop the stack to get the total nested timers' duration.\n * We subtract this from the current timer's actual duration to get its measurable duration. We then add the current\n * timer's actual duration to the stack's top, allowing any parent timer to deduct it from its own duration.\n */\n\n // Initialise the running total duration for all nested timers\n durationStack.push(0)\n\n // Do the work, and time it\n const start = performance.now()\n try {\n const result = await fn()\n return result\n } finally {\n let end = performance.now()\n // For very short durations, the end time can be before the start time(!) - we flatten this out to zero.\n end = Math.max(start, end)\n\n // The top of the stack is the total time for all nested timers\n const wallClockDuration = Math.max(end - start, 0)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const childDurations = durationStack.pop()!\n const duration = Math.max(wallClockDuration - childDurations, 0)\n\n // If this is the topmost timer, the stack will be empty.\n if (durationStack.length > 0) {\n durationStack[durationStack.length - 1] += wallClockDuration\n }\n\n // Log it -- we include it in the metadata, but also log via the standard performance API. The TS types for this library are not quite right, so we have to cast to `any` here.\n performance.measure(`${field}#measurable`, {\n start,\n duration,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n performance.measure(`${field}#wall`, {\n start,\n end,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n\n // There might not be a value set, yet\n let currentValue = (raw.public[field] || 0) as number\n currentValue += duration\n\n // TS is not quite smart enough to realise that raw.public[field] must be a numeric type\n raw.public[field] = currentValue as TPublic[NumericKeyOf<TPublic>]\n }\n }\n },\n }\n}\n\n// We want to track anything that ends up getting sent to monorail as `cmd_all_*` and\n// `cmd_app_*`\ntype CmdFieldsFromMonorail = PickByPrefix<MonorailEventPublic, 'cmd_all_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_create_app_'>\n\nconst coreData = createRuntimeMetadataContainer<\n CmdFieldsFromMonorail,\n {\n commandStartOptions: {\n startTime: number\n startCommand: string\n startTopic?: string\n startArgs: string[]\n }\n } & {environmentFlags: string}\n>({cmd_all_timing_network_ms: 0, cmd_all_timing_prompts_ms: 0})\n\nexport const {getAllPublicMetadata, getAllSensitiveMetadata, addPublicMetadata, addSensitiveMetadata, runWithTimer} =\n coreData\n\nexport type Public = PublicSchema<typeof coreData>\nexport type Sensitive = SensitiveSchema<typeof coreData>\n"]}
|
|
1
|
+
{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../../src/public/node/metadata.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAC,MAAM,oBAAoB,CAAA;AAC7C,OAAO,EAAC,WAAW,EAAC,MAAM,iBAAiB,CAAA;AAe3C;;;;GAIG;AACH,SAAS,gCAAgC;IACvC,IAAI,UAAU,EAAE,EAAE,CAAC;QACjB,OAAO,QAAQ,CAAA;IACjB,CAAC;IACD,OAAO,iBAAiB,CAAA;AAC1B,CAAC;AA4BD;;;;;;GAMG;AACH,MAAM,UAAU,8BAA8B,CAG5C,wBAA0C,EAAE;IAC5C,MAAM,GAAG,GAA+D;QACtE,SAAS,EAAE,EAAE;QACb,MAAM,EAAE;YACN,GAAG,qBAAqB;SACzB;KACF,CAAA;IACD,MAAM,SAAS,GAAG,CAAC,IAAsB,EAAE,EAAE;QAC3C,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,MAAM,EAAE,IAAI,CAAC,CAAA;IACjC,CAAC,CAAA;IACD,MAAM,YAAY,GAAG,CAAC,IAAyB,EAAE,EAAE;QACjD,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,SAAS,EAAE,IAAI,CAAC,CAAA;IACpC,CAAC,CAAA;IAED,MAAM,WAAW,GAAG,KAAK,EAC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AAE;wBACnC,KAAK;wBACL,GAAG;wBACH,8DAA8D;qBACxD,CAAC,CAAA;oBAET,sCAAsC;oBACtC,IAAI,YAAY,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,CAAW,CAAA;oBACrD,YAAY,IAAI,QAAQ,CAAA;oBAExB,wFAAwF;oBACxF,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,YAA8C,CAAA;gBACpE,CAAC;YACH,CAAC,CAAA;QACH,CAAC;KACF,CAAA;AACH,CAAC;AAQD,MAAM,QAAQ,GAAG,8BAA8B,CAU7C,EAAC,yBAAyB,EAAE,CAAC,EAAE,yBAAyB,EAAE,CAAC,EAAC,CAAC,CAAA;AAE/D,MAAM,CAAC,MAAM,EAAC,oBAAoB,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,oBAAoB,EAAE,YAAY,EAAC,GACjH,QAAQ,CAAA","sourcesContent":["import {isUnitTest} from './context/local.js'\nimport {performance} from 'node:perf_hooks'\nimport type {PickByPrefix} from '../common/ts/pick-by-prefix.js'\nimport type {AnyJson} from '../../private/common/json.js'\nimport type {MonorailEventPublic} from './monorail.js'\n\ntype ProvideMetadata<T> = () => Partial<T> | Promise<Partial<T>>\n\ntype MetadataErrorHandling =\n // Mute & report errors in production, throw them whilst testing\n | 'auto'\n // Errors are not reported to the user and do not stop execution, but they are reported to Bugsnag\n | 'mute-and-report'\n // Errors are not caught and will bubble out as normal\n | 'bubble'\n\n/**\n * Get the error handling strategy for metadata.\n *\n * @returns 'mute-and-report' in production, 'bubble' in tests.\n */\nfunction getMetadataErrorHandlingStrategy(): 'mute-and-report' | 'bubble' {\n if (isUnitTest()) {\n return 'bubble'\n }\n return 'mute-and-report'\n}\n\n/**\n * Any key in T that has a numeric value.\n */\ntype NumericKeyOf<T> = {\n [K in keyof T]: T[K] extends number ? (K extends string ? K : never) : never\n}[keyof T]\n\nexport interface RuntimeMetadataManager<TPublic extends AnyJson, TSensitive extends AnyJson> {\n /** Add some public metadata -- this should not contain any PII. */\n addPublicMetadata: (getData: ProvideMetadata<TPublic>, onError?: MetadataErrorHandling) => Promise<void>\n /**\n * Add some potentially sensitive metadata -- this may include PII, but unnecessary data should never be tracked\n * (this is a good fit for command args for instance).\n */\n addSensitiveMetadata: (getData: ProvideMetadata<TSensitive>, onError?: MetadataErrorHandling) => Promise<void>\n /** Get a snapshot of the tracked public data. */\n getAllPublicMetadata: () => Partial<TPublic>\n /** Get a snapshot of the tracked sensitive data. */\n getAllSensitiveMetadata: () => Partial<TSensitive>\n /** Run a function, monitoring how long it takes, and adding the elapsed time to a running total. */\n runWithTimer: (field: NumericKeyOf<TPublic>) => <T>(fn: () => Promise<T>) => Promise<T>\n}\n\nexport type PublicSchema<T> = T extends RuntimeMetadataManager<infer TPublic, infer _TSensitive> ? TPublic : never\nexport type SensitiveSchema<T> = T extends RuntimeMetadataManager<infer _TPublic, infer TSensitive> ? TSensitive : never\n\n/**\n * Creates a container for metadata collected at runtime.\n * The container provides async-safe functions for extracting the gathered metadata, and for setting it.\n *\n * @param defaultPublicMetadata - Optional, default data for the container.\n * @returns A container for the metadata.\n */\nexport function createRuntimeMetadataContainer<\n TPublic extends AnyJson,\n TSensitive extends AnyJson = {[key: string]: never},\n>(defaultPublicMetadata: Partial<TPublic> = {}): RuntimeMetadataManager<TPublic, TSensitive> {\n const raw: {sensitive: Partial<TSensitive>; public: Partial<TPublic>} = {\n sensitive: {},\n public: {\n ...defaultPublicMetadata,\n },\n }\n const addPublic = (data: Partial<TPublic>) => {\n Object.assign(raw.public, data)\n }\n const addSensitive = (data: Partial<TSensitive>) => {\n Object.assign(raw.sensitive, data)\n }\n\n const addMetadata = async <T>(\n addFn: (data: Partial<T>) => void,\n getFn: ProvideMetadata<T>,\n onError: MetadataErrorHandling,\n ) => {\n const errorHandling = onError === 'auto' ? getMetadataErrorHandlingStrategy() : onError\n const getAndSet = async () => {\n const data = await getFn()\n addFn(data)\n }\n\n if (errorHandling === 'bubble') {\n await getAndSet()\n } else {\n try {\n await getAndSet()\n // eslint-disable-next-line no-catch-all/no-catch-all, @typescript-eslint/no-explicit-any\n } catch (error: any) {\n // This is very prone to becoming a circular dependency, so we import it dynamically\n const {sendErrorToBugsnag} = await import('./error-handler.js')\n await sendErrorToBugsnag(error, 'unexpected_error')\n }\n }\n }\n\n // See `runWithTimer` below.\n const durationStack: number[] = []\n\n return {\n getAllPublicMetadata: () => {\n return {...raw.public}\n },\n getAllSensitiveMetadata: () => {\n return {...raw.sensitive}\n },\n addPublicMetadata: async (getData: ProvideMetadata<TPublic>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addPublic, getData, onError)\n },\n addSensitiveMetadata: async (getData: ProvideMetadata<TSensitive>, onError: MetadataErrorHandling = 'auto') => {\n return addMetadata(addSensitive, getData, onError)\n },\n runWithTimer: (field: NumericKeyOf<TPublic>): (<T>(fn: () => Promise<T>) => Promise<T>) => {\n return async (fn) => {\n /**\n * For nested timers, we subtract the inner timer's duration from the outer timer's. We use a stack to track the\n * cumulative durations of nested timers. On starting a timer, we push a zero onto the stack to initialize the total\n * duration for subsequent nested timers. Before logging, we pop the stack to get the total nested timers' duration.\n * We subtract this from the current timer's actual duration to get its measurable duration. We then add the current\n * timer's actual duration to the stack's top, allowing any parent timer to deduct it from its own duration.\n */\n\n // Initialise the running total duration for all nested timers\n durationStack.push(0)\n\n // Do the work, and time it\n const start = performance.now()\n try {\n const result = await fn()\n return result\n } finally {\n let end = performance.now()\n // For very short durations, the end time can be before the start time(!) - we flatten this out to zero.\n end = Math.max(start, end)\n\n // The top of the stack is the total time for all nested timers\n const wallClockDuration = Math.max(end - start, 0)\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const childDurations = durationStack.pop()!\n const duration = Math.max(wallClockDuration - childDurations, 0)\n\n // If this is the topmost timer, the stack will be empty.\n if (durationStack.length > 0) {\n durationStack[durationStack.length - 1] = (durationStack[durationStack.length - 1] ?? 0) + wallClockDuration\n }\n\n // Log it -- we include it in the metadata, but also log via the standard performance API. The TS types for this library are not quite right, so we have to cast to `any` here.\n performance.measure(`${field}#measurable`, {\n start,\n duration,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n performance.measure(`${field}#wall`, {\n start,\n end,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n\n // There might not be a value set, yet\n let currentValue = (raw.public[field] || 0) as number\n currentValue += duration\n\n // TS is not quite smart enough to realise that raw.public[field] must be a numeric type\n raw.public[field] = currentValue as TPublic[NumericKeyOf<TPublic>]\n }\n }\n },\n }\n}\n\n// We want to track anything that ends up getting sent to monorail as `cmd_all_*` and\n// `cmd_app_*`\ntype CmdFieldsFromMonorail = PickByPrefix<MonorailEventPublic, 'cmd_all_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_app_'> &\n PickByPrefix<MonorailEventPublic, 'cmd_create_app_'>\n\nconst coreData = createRuntimeMetadataContainer<\n CmdFieldsFromMonorail,\n {\n commandStartOptions: {\n startTime: number\n startCommand: string\n startTopic?: string\n startArgs: string[]\n }\n } & {environmentFlags: string}\n>({cmd_all_timing_network_ms: 0, cmd_all_timing_prompts_ms: 0})\n\nexport const {getAllPublicMetadata, getAllSensitiveMetadata, addPublicMetadata, addSensitiveMetadata, runWithTimer} =\n coreData\n\nexport type Public = PublicSchema<typeof coreData>\nexport type Sensitive = SensitiveSchema<typeof coreData>\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monorail.js","sourceRoot":"","sources":["../../../src/public/node/monorail.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,WAAW,CAAA;AAE/B,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AAKnF,MAAM,GAAG,GAAG,iDAAiD,CAAA;AAI7D,mFAAmF;AACnF,MAAM,CAAC,MAAM,sBAAsB,GAAG,uBAAuB,CAAA;AA+J7D,MAAM,qBAAqB,GA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KACtD;IAAC,OAAO,KAAK,EAAE;QACd,IAAI,OAAO,GAAG,kCAAkC,CAAA;QAChD,IAAI,KAAK,YAAY,KAAK,EAAE;YAC1B,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;SAC/C;QACD,WAAW,CAAC,OAAO,CAAC,CAAA;QACpB,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAC,CAAA;KAChC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CAAmB,OAAU;IACnD,MAAM,MAAM,GAAG,EAAC,GAAG,OAAO,EAAC,CAAA;IAC3B,IAAI,SAAS,IAAI,MAAM,EAAE;QACvB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA;KACxB;IAED,OAAO,MAAM,CAAA;AACf,CAAC;AAED,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,iCAAiC;QACjD,qCAAqC,EAAE,WAAW,CAAC,QAAQ,EAAE;QAC7D,kCAAkC,EAAE,WAAW,CAAC,QAAQ,EAAE;KAC3D,CAAA;AACH,CAAC,CAAA","sourcesContent":["import {fetch} from './http.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {outputDebug, outputContent, outputToken} from '../../public/node/output.js'\nimport {DeepRequired} from '../common/ts/deep-required.js'\n\nexport {DeepRequired}\n\nconst url = 'https://monorail-edge.shopifysvc.com/v1/produce'\n\ntype Optional<T> = T | null\n\n// This is the topic name of the main event we log to Monorail, the command tracker\nexport const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.16'\n\nexport interface Schemas {\n [MONORAIL_COMMAND_TOPIC]: {\n sensitive: {\n args: string\n error_message?: Optional<string>\n app_name?: Optional<string>\n metadata?: Optional<string>\n store_fqdn?: Optional<string>\n cmd_all_environment_flags?: Optional<string>\n\n // Dev related commands\n cmd_dev_tunnel_custom?: Optional<string>\n\n // Environment\n env_plugin_installed_all?: Optional<string>\n }\n public: {\n partner_id?: Optional<number>\n command: string\n project_type?: Optional<string>\n time_start: number\n time_end: number\n total_time: number\n success: boolean\n api_key?: Optional<string>\n cli_version: string\n uname: string\n ruby_version: string\n node_version: string\n is_employee: boolean\n store_fqdn_hash?: Optional<string>\n user_id: string\n\n // Any and all commands\n cmd_all_alias_used?: Optional<string>\n cmd_all_launcher?: Optional<string>\n cmd_all_path_override?: Optional<boolean>\n cmd_all_path_override_hash?: Optional<string>\n cmd_all_plugin?: Optional<string>\n cmd_all_topic?: Optional<string>\n cmd_all_verbose?: Optional<boolean>\n cmd_all_exit?: Optional<string>\n cmd_all_force?: Optional<boolean>\n cmd_all_last_graphql_request_id?: Optional<string>\n\n cmd_all_timing_network_ms?: Optional<number>\n cmd_all_timing_prompts_ms?: Optional<number>\n cmd_all_timing_active_ms?: Optional<number>\n\n // Any extension related command\n cmd_extensions_binary_from_source?: Optional<boolean>\n\n // Scaffolding related commands\n cmd_scaffold_required_auth?: Optional<boolean>\n cmd_scaffold_template_custom?: Optional<boolean>\n cmd_scaffold_template_flavor?: Optional<string>\n cmd_scaffold_type?: Optional<string>\n cmd_scaffold_type_category?: Optional<string>\n cmd_scaffold_type_gated?: Optional<boolean>\n cmd_scaffold_type_owner?: Optional<string>\n cmd_scaffold_used_prompts_for_type?: Optional<boolean>\n\n // Used in several but not all commands\n cmd_app_dependency_installation_skipped?: Optional<boolean>\n cmd_app_reset_used?: Optional<boolean>\n cmd_app_linked_config_used?: Optional<boolean>\n cmd_app_linked_config_name?: Optional<string>\n cmd_app_linked_config_git_tracked?: Optional<boolean>\n cmd_app_all_configs_any?: Optional<boolean>\n cmd_app_all_configs_clients?: Optional<string>\n cmd_app_linked_config_source?: Optional<string>\n cmd_app_linked_config_uses_cli_managed_urls?: Optional<boolean>\n cmd_app_warning_api_key_deprecation_displayed?: Optional<boolean>\n cmd_app_deployment_mode?: Optional<string>\n\n // Dev related commands\n cmd_dev_tunnel_type?: Optional<string>\n cmd_dev_tunnel_custom_hash?: Optional<string>\n cmd_dev_urls_updated?: Optional<boolean>\n cmd_dev_preview_url_opened?: Optional<boolean>\n cmd_dev_graphiql_opened?: Optional<boolean>\n cmd_dev_dev_preview_toggle_used?: Optional<boolean>\n\n // Create-app related commands\n cmd_create_app_template?: Optional<string>\n cmd_create_app_template_url?: Optional<string>\n\n // Deploy related commands\n cmd_deploy_flag_message_used?: Optional<boolean>\n cmd_deploy_flag_version_used?: Optional<boolean>\n cmd_deploy_flag_source_url_used?: Optional<boolean>\n cmd_deploy_confirm_new_registrations?: Optional<number>\n cmd_deploy_confirm_updated_registrations?: Optional<number>\n cmd_deploy_confirm_removed_registrations?: Optional<number>\n cmd_deploy_confirm_cancelled?: Optional<boolean>\n cmd_deploy_confirm_time_to_complete_ms?: Optional<number>\n cmd_deploy_prompt_upgrade_to_unified_displayed?: Optional<boolean>\n cmd_deploy_prompt_upgrade_to_unified_response?: Optional<string>\n cmd_deploy_confirm_include_config_used?: Optional<boolean>\n cmd_deploy_include_config_used?: Optional<boolean>\n cmd_deploy_config_modules_breakdown?: Optional<string>\n cmd_deploy_config_modules_updated?: Optional<string>\n cmd_deploy_config_modules_added?: Optional<string>\n cmd_deploy_config_modules_deleted?: Optional<string>\n\n // Release related commands\n cmd_release_confirm_cancelled?: Optional<boolean>\n\n // App setup\n app_extensions_any?: Optional<boolean>\n app_extensions_breakdown?: Optional<string>\n app_extensions_count?: Optional<number>\n app_extensions_custom_layout?: Optional<boolean>\n app_extensions_function_any?: Optional<boolean>\n app_extensions_function_count?: Optional<number>\n app_extensions_function_custom_layout?: Optional<boolean>\n app_extensions_theme_any?: Optional<boolean>\n app_extensions_theme_count?: Optional<number>\n app_extensions_theme_custom_layout?: Optional<boolean>\n app_extensions_ui_any?: Optional<boolean>\n app_extensions_ui_count?: Optional<number>\n app_extensions_ui_custom_layout?: Optional<boolean>\n app_name_hash?: Optional<string>\n app_path_hash?: Optional<string>\n app_scopes?: Optional<string>\n app_web_backend_any?: Optional<boolean>\n app_web_backend_count?: Optional<number>\n app_web_custom_layout?: Optional<boolean>\n app_web_framework?: Optional<string>\n app_web_frontend_any?: Optional<boolean>\n app_web_frontend_count?: Optional<number>\n\n // Environment\n env_ci?: Optional<boolean>\n env_ci_platform?: Optional<string>\n env_device_id?: Optional<string>\n env_package_manager?: Optional<string>\n env_package_manager_workspaces?: Optional<boolean>\n env_plugin_installed_any_custom?: Optional<boolean>\n env_plugin_installed_shopify?: Optional<string>\n env_shell?: Optional<string>\n env_web_ide?: Optional<string>\n env_cloud?: Optional<string>\n env_is_global?: Optional<boolean>\n env_auth_method?: Optional<string>\n }\n }\n [schemaId: string]: {sensitive: JsonMap; public: JsonMap}\n}\n\n// In reality, we're normally most interested in just this from Schemas, so export it for ease of use.\n// The monorail schema itself has lots of optional values as it must be backwards-compatible. For our schema we want mandatory values instead.\nexport type MonorailEventPublic = DeepRequired<Schemas[typeof MONORAIL_COMMAND_TOPIC]['public']>\nexport type MonorailEventSensitive = Schemas[typeof MONORAIL_COMMAND_TOPIC]['sensitive']\n\ntype MonorailResult = {type: 'ok'} | {type: 'error'; message: string}\n\nconst publishedCommandNames = new Set<string>()\n\n/**\n * Publishes an event to Monorail.\n *\n * @param schemaId - The schema ID of the event to publish.\n * @param publicData - The public data to publish.\n * @param sensitiveData - The sensitive data to publish.\n * @returns A result indicating whether the event was successfully published.\n */\nexport async function publishMonorailEvent<TSchemaId extends keyof Schemas, TPayload extends Schemas[TSchemaId]>(\n schemaId: TSchemaId,\n publicData: TPayload['public'],\n sensitiveData: TPayload['sensitive'],\n): Promise<MonorailResult> {\n // If a command has already been logged, never re-log it. This is to prevent duplication caused by unexpected errors.\n const commandName = publicData.command\n if (commandName && typeof commandName === 'string') {\n if (publishedCommandNames.has(commandName)) {\n return {type: 'ok'}\n }\n publishedCommandNames.add(commandName)\n }\n\n try {\n const currentTime = new Date().getTime()\n const payload = {...publicData, ...sensitiveData}\n const body = JSON.stringify({schema_id: schemaId, payload})\n const headers = buildHeaders(currentTime)\n\n const response = await fetch(url, {method: 'POST', body, headers})\n\n if (response.status === 200) {\n outputDebug(outputContent`Analytics event sent: ${outputToken.json(sanitizePayload(payload))}`)\n return {type: 'ok'}\n } else {\n outputDebug(`Failed to report usage analytics: ${response.statusText}`)\n return {type: 'error', message: response.statusText}\n }\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n return {type: 'error', message}\n }\n}\n\n/**\n * Sanitizies the api_key from the payload and returns a new hash.\n *\n * @param payload - The public and sensitive data.\n * @returns A copy of the payload with the api_key sanitized.\n */\nfunction sanitizePayload<T extends object>(payload: T): T {\n const result = {...payload}\n if ('api_key' in result) {\n result.api_key = '****'\n }\n\n return result\n}\n\nconst buildHeaders = (currentTime: number) => {\n return {\n 'Content-Type': 'application/json; charset=utf-8',\n 'X-Monorail-Edge-Event-Created-At-Ms': currentTime.toString(),\n 'X-Monorail-Edge-Event-Sent-At-Ms': currentTime.toString(),\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"monorail.js","sourceRoot":"","sources":["../../../src/public/node/monorail.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,KAAK,EAAC,MAAM,WAAW,CAAA;AAE/B,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AAKnF,MAAM,GAAG,GAAG,iDAAiD,CAAA;AAI7D,mFAAmF;AACnF,MAAM,CAAC,MAAM,sBAAsB,GAAG,uBAAuB,CAAA;AAgK7D,MAAM,qBAAqB,GAAG,IAAI,GAAG,EAAU,CAAA;AAE/C;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,oBAAoB,CACxC,QAAmB,EACnB,UAA8B,EAC9B,aAAoC;IAEpC,qHAAqH;IACrH,MAAM,WAAW,GAAG,UAAU,CAAC,OAAO,CAAA;IACtC,IAAI,WAAW,IAAI,OA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C,KAAK,KAAK,CAAC,OAAO,EAAE,CAAC,CAAA;QAChD,CAAC;QACD,WAAW,CAAC,OAAO,CAAC,CAAA;QACpB,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAC,CAAA;IACjC,CAAC;AACH,CAAC;AAED;;;;;GAKG;AACH,SAAS,eAAe,CAAmB,OAAU;IACnD,MAAM,MAAM,GAAG,EAAC,GAAG,OAAO,EAAC,CAAA;IAC3B,IAAI,SAAS,IAAI,MAAM,EAAE,CAAC;QACxB,MAAM,CAAC,OAAO,GAAG,MAAM,CAAA;IACzB,CAAC;IAED,OAAO,MAAM,CAAA;AACf,CAAC;AAED,MAAM,YAAY,GAAG,CAAC,WAAmB,EAAE,EAAE;IAC3C,OAAO;QACL,cAAc,EAAE,iCAAiC;QACjD,qCAAqC,EAAE,WAAW,CAAC,QAAQ,EAAE;QAC7D,kCAAkC,EAAE,WAAW,CAAC,QAAQ,EAAE;KAC3D,CAAA;AACH,CAAC,CAAA","sourcesContent":["import {fetch} from './http.js'\nimport {JsonMap} from '../../private/common/json.js'\nimport {outputDebug, outputContent, outputToken} from '../../public/node/output.js'\nimport {DeepRequired} from '../common/ts/deep-required.js'\n\nexport {DeepRequired}\n\nconst url = 'https://monorail-edge.shopifysvc.com/v1/produce'\n\ntype Optional<T> = T | null\n\n// This is the topic name of the main event we log to Monorail, the command tracker\nexport const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.16'\n\nexport interface Schemas {\n [MONORAIL_COMMAND_TOPIC]: {\n sensitive: {\n args: string\n error_message?: Optional<string>\n app_name?: Optional<string>\n metadata?: Optional<string>\n store_fqdn?: Optional<string>\n cmd_all_environment_flags?: Optional<string>\n\n // Dev related commands\n cmd_dev_tunnel_custom?: Optional<string>\n\n // Environment\n env_plugin_installed_all?: Optional<string>\n }\n public: {\n business_platform_id?: Optional<number>\n partner_id?: Optional<number>\n command: string\n project_type?: Optional<string>\n time_start: number\n time_end: number\n total_time: number\n success: boolean\n api_key?: Optional<string>\n cli_version: string\n uname: string\n ruby_version: string\n node_version: string\n is_employee: boolean\n store_fqdn_hash?: Optional<string>\n user_id: string\n\n // Any and all commands\n cmd_all_alias_used?: Optional<string>\n cmd_all_launcher?: Optional<string>\n cmd_all_path_override?: Optional<boolean>\n cmd_all_path_override_hash?: Optional<string>\n cmd_all_plugin?: Optional<string>\n cmd_all_topic?: Optional<string>\n cmd_all_verbose?: Optional<boolean>\n cmd_all_exit?: Optional<string>\n cmd_all_force?: Optional<boolean>\n cmd_all_last_graphql_request_id?: Optional<string>\n\n cmd_all_timing_network_ms?: Optional<number>\n cmd_all_timing_prompts_ms?: Optional<number>\n cmd_all_timing_active_ms?: Optional<number>\n\n // Any extension related command\n cmd_extensions_binary_from_source?: Optional<boolean>\n\n // Scaffolding related commands\n cmd_scaffold_required_auth?: Optional<boolean>\n cmd_scaffold_template_custom?: Optional<boolean>\n cmd_scaffold_template_flavor?: Optional<string>\n cmd_scaffold_type?: Optional<string>\n cmd_scaffold_type_category?: Optional<string>\n cmd_scaffold_type_gated?: Optional<boolean>\n cmd_scaffold_type_owner?: Optional<string>\n cmd_scaffold_used_prompts_for_type?: Optional<boolean>\n\n // Used in several but not all commands\n cmd_app_dependency_installation_skipped?: Optional<boolean>\n cmd_app_reset_used?: Optional<boolean>\n cmd_app_linked_config_used?: Optional<boolean>\n cmd_app_linked_config_name?: Optional<string>\n cmd_app_linked_config_git_tracked?: Optional<boolean>\n cmd_app_all_configs_any?: Optional<boolean>\n cmd_app_all_configs_clients?: Optional<string>\n cmd_app_linked_config_source?: Optional<string>\n cmd_app_linked_config_uses_cli_managed_urls?: Optional<boolean>\n cmd_app_warning_api_key_deprecation_displayed?: Optional<boolean>\n cmd_app_deployment_mode?: Optional<string>\n\n // Dev related commands\n cmd_dev_tunnel_type?: Optional<string>\n cmd_dev_tunnel_custom_hash?: Optional<string>\n cmd_dev_urls_updated?: Optional<boolean>\n cmd_dev_preview_url_opened?: Optional<boolean>\n cmd_dev_graphiql_opened?: Optional<boolean>\n cmd_dev_dev_preview_toggle_used?: Optional<boolean>\n\n // Create-app related commands\n cmd_create_app_template?: Optional<string>\n cmd_create_app_template_url?: Optional<string>\n\n // Deploy related commands\n cmd_deploy_flag_message_used?: Optional<boolean>\n cmd_deploy_flag_version_used?: Optional<boolean>\n cmd_deploy_flag_source_url_used?: Optional<boolean>\n cmd_deploy_confirm_new_registrations?: Optional<number>\n cmd_deploy_confirm_updated_registrations?: Optional<number>\n cmd_deploy_confirm_removed_registrations?: Optional<number>\n cmd_deploy_confirm_cancelled?: Optional<boolean>\n cmd_deploy_confirm_time_to_complete_ms?: Optional<number>\n cmd_deploy_prompt_upgrade_to_unified_displayed?: Optional<boolean>\n cmd_deploy_prompt_upgrade_to_unified_response?: Optional<string>\n cmd_deploy_confirm_include_config_used?: Optional<boolean>\n cmd_deploy_include_config_used?: Optional<boolean>\n cmd_deploy_config_modules_breakdown?: Optional<string>\n cmd_deploy_config_modules_updated?: Optional<string>\n cmd_deploy_config_modules_added?: Optional<string>\n cmd_deploy_config_modules_deleted?: Optional<string>\n\n // Release related commands\n cmd_release_confirm_cancelled?: Optional<boolean>\n\n // App setup\n app_extensions_any?: Optional<boolean>\n app_extensions_breakdown?: Optional<string>\n app_extensions_count?: Optional<number>\n app_extensions_custom_layout?: Optional<boolean>\n app_extensions_function_any?: Optional<boolean>\n app_extensions_function_count?: Optional<number>\n app_extensions_function_custom_layout?: Optional<boolean>\n app_extensions_theme_any?: Optional<boolean>\n app_extensions_theme_count?: Optional<number>\n app_extensions_theme_custom_layout?: Optional<boolean>\n app_extensions_ui_any?: Optional<boolean>\n app_extensions_ui_count?: Optional<number>\n app_extensions_ui_custom_layout?: Optional<boolean>\n app_name_hash?: Optional<string>\n app_path_hash?: Optional<string>\n app_scopes?: Optional<string>\n app_web_backend_any?: Optional<boolean>\n app_web_backend_count?: Optional<number>\n app_web_custom_layout?: Optional<boolean>\n app_web_framework?: Optional<string>\n app_web_frontend_any?: Optional<boolean>\n app_web_frontend_count?: Optional<number>\n\n // Environment\n env_ci?: Optional<boolean>\n env_ci_platform?: Optional<string>\n env_device_id?: Optional<string>\n env_package_manager?: Optional<string>\n env_package_manager_workspaces?: Optional<boolean>\n env_plugin_installed_any_custom?: Optional<boolean>\n env_plugin_installed_shopify?: Optional<string>\n env_shell?: Optional<string>\n env_web_ide?: Optional<string>\n env_cloud?: Optional<string>\n env_is_global?: Optional<boolean>\n env_auth_method?: Optional<string>\n }\n }\n [schemaId: string]: {sensitive: JsonMap; public: JsonMap}\n}\n\n// In reality, we're normally most interested in just this from Schemas, so export it for ease of use.\n// The monorail schema itself has lots of optional values as it must be backwards-compatible. For our schema we want mandatory values instead.\nexport type MonorailEventPublic = DeepRequired<Schemas[typeof MONORAIL_COMMAND_TOPIC]['public']>\nexport type MonorailEventSensitive = Schemas[typeof MONORAIL_COMMAND_TOPIC]['sensitive']\n\ntype MonorailResult = {type: 'ok'} | {type: 'error'; message: string}\n\nconst publishedCommandNames = new Set<string>()\n\n/**\n * Publishes an event to Monorail.\n *\n * @param schemaId - The schema ID of the event to publish.\n * @param publicData - The public data to publish.\n * @param sensitiveData - The sensitive data to publish.\n * @returns A result indicating whether the event was successfully published.\n */\nexport async function publishMonorailEvent<TSchemaId extends keyof Schemas, TPayload extends Schemas[TSchemaId]>(\n schemaId: TSchemaId,\n publicData: TPayload['public'],\n sensitiveData: TPayload['sensitive'],\n): Promise<MonorailResult> {\n // If a command has already been logged, never re-log it. This is to prevent duplication caused by unexpected errors.\n const commandName = publicData.command\n if (commandName && typeof commandName === 'string') {\n if (publishedCommandNames.has(commandName)) {\n return {type: 'ok'}\n }\n publishedCommandNames.add(commandName)\n }\n\n try {\n const currentTime = new Date().getTime()\n const payload = {...publicData, ...sensitiveData}\n const body = JSON.stringify({schema_id: schemaId, payload})\n const headers = buildHeaders(currentTime)\n\n const response = await fetch(url, {method: 'POST', body, headers})\n\n if (response.status === 200) {\n outputDebug(outputContent`Analytics event sent: ${outputToken.json(sanitizePayload(payload))}`)\n return {type: 'ok'}\n } else {\n outputDebug(`Failed to report usage analytics: ${response.statusText}`)\n return {type: 'error', message: response.statusText}\n }\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n let message = 'Failed to report usage analytics'\n if (error instanceof Error) {\n message = message.concat(`: ${error.message}`)\n }\n outputDebug(message)\n return {type: 'error', message}\n }\n}\n\n/**\n * Sanitizies the api_key from the payload and returns a new hash.\n *\n * @param payload - The public and sensitive data.\n * @returns A copy of the payload with the api_key sanitized.\n */\nfunction sanitizePayload<T extends object>(payload: T): T {\n const result = {...payload}\n if ('api_key' in result) {\n result.api_key = '****'\n }\n\n return result\n}\n\nconst buildHeaders = (currentTime: number) => {\n return {\n 'Content-Type': 'application/json; charset=utf-8',\n 'X-Monorail-Edge-Event-Created-At-Ms': currentTime.toString(),\n 'X-Monorail-Edge-Event-Sent-At-Ms': currentTime.toString(),\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-package-manager.js","sourceRoot":"","sources":["../../../src/public/node/node-package-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAA;AAC/C,OAAO,EAAC,eAAe,EAAc,MAAM,YAAY,CAAA;AACvD,OAAO,EAAC,aAAa,EAAE,IAAI,EAAC,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,EAAC,MAAM,SAAS,CAAA;AACzE,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,+BAA+B,EAAC,MAAM,gBAAgB,CAAA;AAC9D,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAoB,aAAa,EAAE,yBAAy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AwB;IAChF,WAAW,CAAC,aAAa,CAAA,wDAAwD,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IAClH,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;IACvD,MAAM,SAAS,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAA;AACpE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,qBAAyC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG;IAC9F,IAAI,qBAAqB,IAAI,cAAc,CAAC,QAAQ,CAAC,qBAAuC,CAAC,EAAE;QAC7F,OAAO,qBAAuC,CAAA;KAC/C;IACD,MAAM,kBAAkB,GAAG,2BAA2B,CAAC,GAAG,CAAC,CAAA;IAC3D,IAAI,kBAAkB,KAAK,SAAS;QAAE,OAAO,kBAAkB,CAAA;IAE/D,MAAM,oBAAoB,GAAG,+BAA+B,EAAE,CAAA;IAC9D,IAAI,oBAAoB,KAAK,SAAS;QAAE,OAAO,oBAAoB,CAAA;IAEnE,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import {AbortError, BugError} from './error.js'\nimport {AbortController, AbortSignal} from './abort.js'\nimport {captureOutput, exec} from './system.js'\nimport {fileExists, readFile, writeFile, findPathUp, glob} from './fs.js'\nimport {dirname, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {inferPackageManagerForGlobalCLI} from './is-global.js'\nimport {outputToken, outputContent, outputDebug} from '../../public/node/output.js'\nimport {PackageVersionKey, cacheRetrieve, cacheRetrieveOrRepopulate} from '../../private/node/conf-store.js'\nimport latestVersion from 'latest-version'\nimport {SemVer, satisfies as semverSatisfies} from 'semver'\nimport type {Writable} from 'stream'\nimport type {ExecOptions} from './system.js'\n\n/** The name of the Yarn lock file */\nexport const yarnLockfile = 'yarn.lock'\n\n/** The name of the npm lock file */\nexport const npmLockfile = 'package-lock.json'\n\n/** The name of the pnpm lock file */\nexport const pnpmLockfile = 'pnpm-lock.yaml'\n\n/** The name of the bun lock file */\nexport const bunLockfile = 'bun.lockb'\n\n/** The name of the pnpm workspace file */\nexport const pnpmWorkspaceFile = 'pnpm-workspace.yaml'\n\n/** An array containing the lockfiles from all the package managers */\nexport const lockfiles: Lockfile[] = [yarnLockfile, pnpmLockfile, npmLockfile, bunLockfile]\nexport const lockfilesByManager: {[key in PackageManager]: Lockfile | undefined} = {\n yarn: yarnLockfile,\n npm: npmLockfile,\n pnpm: pnpmLockfile,\n bun: bunLockfile,\n unknown: undefined,\n}\nexport type Lockfile = 'yarn.lock' | 'package-lock.json' | 'pnpm-lock.yaml' | 'bun.lockb'\n\n/**\n * A union type that represents the type of dependencies in the package.json\n * - dev: devDependencies\n * - prod: dependencies\n * - peer: peerDependencies\n */\nexport type DependencyType = 'dev' | 'prod' | 'peer'\n\n/**\n * A union that represents the package managers available.\n */\nexport const packageManager = ['yarn', 'npm', 'pnpm', 'bun', 'unknown'] as const\nexport type PackageManager = (typeof packageManager)[number]\n\n/**\n * Returns an abort error that's thrown when the package manager can't be determined.\n * @returns An abort error.\n */\nexport class UnknownPackageManagerError extends AbortError {\n constructor() {\n super('Unknown package manager')\n }\n}\n\n/**\n * Returns an abort error that's thrown when a directory that's expected to have\n * a package.json doesn't have it.\n * @param directory - The path to the directory that should contain a package.json\n * @returns An abort error.\n */\nexport class PackageJsonNotFoundError extends AbortError {\n constructor(directory: string) {\n super(outputContent`The directory ${outputToken.path(directory)} doesn't have a package.json.`)\n }\n}\n\n/**\n * Returns a bug error that's thrown when the lookup of the package.json traversing the directory\n * hierarchy up can't find a package.json\n * @param directory - The directory from which the traverse has been done\n * @returns An abort error.\n */\nexport class FindUpAndReadPackageJsonNotFoundError extends BugError {\n constructor(directory: string) {\n super(outputContent`Couldn't find a a package.json traversing directories from ${outputToken.path(directory)}`)\n }\n}\n\n/**\n * Returns the dependency manager used to run the create workflow.\n * @param env - The environment variables of the process in which the CLI runs.\n * @returns The dependency manager\n */\nexport function packageManagerFromUserAgent(env = process.env): PackageManager {\n if (env.npm_config_user_agent?.includes('yarn')) {\n return 'yarn'\n } else if (env.npm_config_user_agent?.includes('pnpm')) {\n return 'pnpm'\n } else if (env.npm_config_user_agent?.includes('bun')) {\n return 'bun'\n } else if (env.npm_config_user_agent?.includes('npm')) {\n return 'npm'\n }\n return 'unknown'\n}\n\n/**\n * Returns the dependency manager used in a directory.\n * @param fromDirectory - The starting directory\n * @returns The dependency manager\n */\nexport async function getPackageManager(fromDirectory: string): Promise<PackageManager> {\n const directory = await captureOutput('npm', ['prefix'], {cwd: fromDirectory})\n outputDebug(outputContent`Obtaining the dependency manager in directory ${outputToken.path(directory)}...`)\n const packageJson = joinPath(directory, 'package.json')\n if (!(await fileExists(packageJson))) {\n return packageManagerFromUserAgent()\n }\n const yarnLockPath = joinPath(directory, yarnLockfile)\n const pnpmLockPath = joinPath(directory, pnpmLockfile)\n const bunLockPath = joinPath(directory, bunLockfile)\n if (await fileExists(yarnLockPath)) {\n return 'yarn'\n } else if (await fileExists(pnpmLockPath)) {\n return 'pnpm'\n } else if (await fileExists(bunLockPath)) {\n return 'bun'\n } else {\n return 'npm'\n }\n}\n\ninterface InstallNPMDependenciesRecursivelyOptions {\n /**\n * The dependency manager to use to install the dependencies.\n */\n packageManager: PackageManager\n /**\n * The directory from where we'll find package.json's recursively\n */\n directory: string\n\n /**\n * Specifies the maximum depth of the glob search.\n */\n deep?: number\n}\n\n/**\n * This function traverses down a directory tree to find directories containing a package.json\n * and installs the dependencies if needed. To know if it's needed, it uses the \"check\" command\n * provided by dependency managers.\n * @param options - Options to install dependencies recursively.\n */\nexport async function installNPMDependenciesRecursively(\n options: InstallNPMDependenciesRecursivelyOptions,\n): Promise<void> {\n const packageJsons = await glob(joinPath(options.directory, '**/package.json'), {\n ignore: [joinPath(options.directory, 'node_modules/**/package.json')],\n cwd: options.directory,\n onlyFiles: true,\n deep: options.deep,\n })\n const abortController = new AbortController()\n try {\n await Promise.all(\n packageJsons.map(async (packageJsonPath) => {\n const directory = dirname(packageJsonPath)\n await installNodeModules({\n directory,\n packageManager: options.packageManager,\n stdout: undefined,\n stderr: undefined,\n signal: abortController.signal,\n args: [],\n })\n }),\n )\n } catch (error) {\n abortController.abort()\n throw error\n }\n}\n\ninterface InstallNodeModulesOptions {\n directory: string\n args?: string[]\n packageManager: PackageManager\n stdout?: Writable\n stderr?: Writable\n signal?: AbortSignal\n}\n\nexport async function installNodeModules(options: InstallNodeModulesOptions): Promise<void> {\n const execOptions: ExecOptions = {\n cwd: options.directory,\n stdin: undefined,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n }\n let args = ['install']\n if (options.args) {\n args = args.concat(options.args)\n }\n await runWithTimer('cmd_all_timing_network_ms')(async () => {\n await exec(options.packageManager, args, execOptions)\n })\n}\n\n/**\n * Returns the name of the package configured in its package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the name.\n */\nexport async function getPackageName(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.name\n}\n/**\n * Returns the version of the package configured in its package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the version.\n */\nexport async function getPackageVersion(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.version\n}\n\n/**\n * Returns the list of production and dev dependencies of a package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the list of dependencies.\n */\nexport async function getDependencies(packageJsonPath: string): Promise<{[key: string]: string}> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const dependencies: {[key: string]: string} = packageJsonContent.dependencies ?? {}\n const devDependencies: {[key: string]: string} = packageJsonContent.devDependencies ?? {}\n\n return {...dependencies, ...devDependencies}\n}\n\n/**\n * Returns true if the app uses workspaces, false otherwise.\n * @param packageJsonPath - Path to the package.json file\n * @param pnpmWorkspacePath - Path to the pnpm-workspace.yaml file\n * @returns A promise that resolves with true if the app uses workspaces, false otherwise.\n */\nexport async function usesWorkspaces(appDirectory: string): Promise<boolean> {\n const packageJsonPath = joinPath(appDirectory, 'package.json')\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const pnpmWorkspacePath = joinPath(appDirectory, pnpmWorkspaceFile)\n return Boolean(packageJsonContent.workspaces) || fileExists(pnpmWorkspacePath)\n}\n\n/**\n * Given an NPM dependency, it checks if there's a more recent version, and if there is, it returns its value.\n * @param dependency - The dependency name (e.g. react)\n * @param currentVersion - The current version.\n * @param cacheExpiryInHours - If the last check was done more than this amount of hours ago, it will\n * refresh the cache. Defaults to always refreshing.\n * @returns A promise that resolves with a more recent version or undefined if there's no more recent version.\n */\nexport async function checkForNewVersion(\n dependency: string,\n currentVersion: string,\n {cacheExpiryInHours = 0} = {},\n): Promise<string | undefined> {\n const getLatestVersion = async () => {\n outputDebug(outputContent`Checking if there's a version of ${dependency} newer than ${currentVersion}`)\n return getLatestNPMPackageVersion(dependency)\n }\n\n const cacheKey: PackageVersionKey = `npm-package-${dependency}`\n let lastVersion\n try {\n lastVersion = await cacheRetrieveOrRepopulate(cacheKey, getLatestVersion, cacheExpiryInHours * 3600 * 1000)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return undefined\n }\n\n if (lastVersion && new SemVer(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n}\n\n/**\n * Given an NPM dependency, it checks if there's a cached more recent version, and if there is, it returns its value.\n * @param dependency - The dependency name (e.g. react)\n * @param currentVersion - The current version.\n * @returns A more recent version or undefined if there's no more recent version.\n */\nexport function checkForCachedNewVersion(dependency: string, currentVersion: string): string | undefined {\n const cacheKey: PackageVersionKey = `npm-package-${dependency}`\n const lastVersion = cacheRetrieve(cacheKey)?.value\n\n if (lastVersion && new SemVer(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n}\n\n/**\n * Utility function used to check whether a package version satisfies some requirements\n * @param version - The version to check\n * @param requirements - The requirements to check against, e.g. \"\\>=1.0.0\" - see https://www.npmjs.com/package/semver#ranges\n * @returns A boolean indicating whether the version satisfies the requirements\n */\nexport function versionSatisfies(version: string, requirements: string): boolean {\n return semverSatisfies(version, requirements)\n}\n\n/**\n * An interface that represents a package.json\n */\nexport interface PackageJson {\n /**\n * The name attribute of the package.json\n */\n name?: string\n\n /**\n * The author attribute of the package.json\n */\n author?: string\n\n /**\n * The version attribute of the package.json\n */\n version?: string\n\n /**\n * The scripts attribute of the package.json\n */\n scripts?: {[key: string]: string}\n\n /**\n * The dependencies attribute of the package.json\n */\n dependencies?: {[key: string]: string}\n\n /**\n * The devDependencies attribute of the package.json\n */\n devDependencies?: {[key: string]: string}\n\n /**\n * The peerDependencies attribute of the package.json\n */\n peerDependencies?: {[key: string]: string}\n\n /**\n * The optional oclif settings attribute of the package.json\n */\n oclif?: {\n plugins?: string[]\n }\n\n /**\n * The workspaces attribute of the package.json\n */\n workspaces?: string[]\n\n /**\n * The resolutions attribute of the package.json. Only useful when using yarn as package manager\n */\n resolutions?: {[key: string]: string}\n\n /**\n * The overrides attribute of the package.json. Only useful when using npm o npmn as package managers\n */\n overrides?: {[key: string]: string}\n\n /**\n * The prettier attribute of the package.json\n */\n prettier?: string\n\n /**\n * The private attribute of the package.json.\n * https://docs.npmjs.com/cli/v9/configuring-npm/package-json#private\n */\n private?: boolean\n}\n\n/**\n * Reads and parses a package.json\n * @param packageJsonPath - Path to the package.json\n * @returns An promise that resolves with an in-memory representation\n * of the package.json or rejects with an error if the file is not found or the content is\n * not decodable.\n */\nexport async function readAndParsePackageJson(packageJsonPath: string): Promise<PackageJson> {\n if (!(await fileExists(packageJsonPath))) {\n throw new PackageJsonNotFoundError(dirname(packageJsonPath))\n }\n return JSON.parse(await readFile(packageJsonPath))\n}\n\ninterface AddNPMDependenciesIfNeededOptions {\n /** How dependencies should be added */\n type: DependencyType\n\n /** The dependency manager to use to add dependencies */\n packageManager: PackageManager\n\n /** The directory that contains the package.json where dependencies will be added */\n directory: string\n\n /** Standard output coming from the underlying installation process */\n stdout?: Writable\n\n /** Standard error coming from the underlying installation process */\n stderr?: Writable\n\n /** Abort signal to stop the process */\n signal?: AbortSignal\n\n /** Whether to add the dependencies to the root package.json or to the package.json of the directory */\n addToRootDirectory?: boolean\n}\n\n/**\n * An interface that represents a dependency name with its version\n */\nexport interface DependencyVersion {\n /**\n * The name of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below name would be \"react\"\n * ```\n * {\n * \"react\": \"1.2.3\"\n * }\n * ```\n */\n name: string\n\n /**\n * The version of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below version would be \"1.2.3\"\n * ```\n * {\n * \"react\": \"1.2.3\"\n * }\n * ```\n */\n version: string | undefined\n}\n\n/**\n * Adds dependencies to a Node project (i.e. a project that has a package.json)\n * @param dependencies - List of dependencies to be added.\n * @param options - Options for adding dependencies.\n */\nexport async function addNPMDependenciesIfNeeded(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n outputDebug(outputContent`Adding the following dependencies if needed:\n${outputToken.json(dependencies)}\nWith options:\n${outputToken.json(options)}\n `)\n const packageJsonPath = joinPath(options.directory, 'package.json')\n if (!(await fileExists(packageJsonPath))) {\n throw new PackageJsonNotFoundError(options.directory)\n }\n const existingDependencies = Object.keys(await getDependencies(packageJsonPath))\n const dependenciesToAdd = dependencies.filter((dep) => {\n return !existingDependencies.includes(dep.name)\n })\n if (dependenciesToAdd.length === 0) {\n return\n }\n await addNPMDependencies(dependenciesToAdd, options)\n}\n\nexport async function addNPMDependencies(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n const dependenciesWithVersion = dependencies.map((dep) => {\n return dep.version ? `${dep.name}@${dep.version}` : dep.name\n })\n options.stdout?.write(`Installing ${[dependenciesWithVersion].join(' ')} with ${options.packageManager}`)\n switch (options.packageManager) {\n case 'npm':\n // npm isn't too smart when resolving the dependency tree. For example, admin ui extensions include react as\n // a peer dependency, but npm can't figure out the relationship and fails. Installing dependencies one by one\n // makes the task easier and npm can then proceed.\n for (const dep of dependenciesWithVersion) {\n // eslint-disable-next-line no-await-in-loop\n await installDependencies(options, argumentsToAddDependenciesWithNPM(dep, options.type))\n }\n break\n case 'yarn':\n await installDependencies(\n options,\n argumentsToAddDependenciesWithYarn(dependenciesWithVersion, options.type, Boolean(options.addToRootDirectory)),\n )\n break\n case 'pnpm':\n await installDependencies(\n options,\n argumentsToAddDependenciesWithPNPM(dependenciesWithVersion, options.type, Boolean(options.addToRootDirectory)),\n )\n break\n case 'bun':\n await installDependencies(options, argumentsToAddDependenciesWithBun(dependenciesWithVersion, options.type))\n await installDependencies(options, ['install'])\n break\n case 'unknown':\n throw new UnknownPackageManagerError()\n }\n}\n\nasync function installDependencies(options: AddNPMDependenciesIfNeededOptions, args: string[]) {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return exec(options.packageManager, args, {\n cwd: options.directory,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n })\n })\n}\n\nexport async function addNPMDependenciesWithoutVersionIfNeeded(\n dependencies: string[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n await addNPMDependenciesIfNeeded(\n dependencies.map((dependency) => {\n return {name: dependency, version: undefined}\n }),\n options,\n )\n}\n\n/**\n * Returns the arguments to add dependencies using NPM.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithNPM(dependency: string, type: DependencyType): string[] {\n let command = ['install']\n command = command.concat(dependency)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n // NPM adds ^ to the installed version by default. We want to install exact versions unless specified otherwise.\n if (dependency.match(/@\\d/g)) {\n command.push('--save-exact')\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Yarn.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @param addAtRoot - Force to install the dependencies in the workspace root (optional, default = false)\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithYarn(dependencies: string[], type: DependencyType, addAtRoot = false): string[] {\n let command = ['add']\n\n if (addAtRoot) {\n command.push('-W')\n }\n\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--dev')\n break\n case 'peer':\n command.push('--peer')\n break\n case 'prod':\n command.push('--prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using PNPM.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @param addAtRoot - Force to install the dependencies in the workspace root (optional, default = false)\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithPNPM(dependencies: string[], type: DependencyType, addAtRoot = false): string[] {\n let command = ['add']\n\n if (addAtRoot) {\n command.push('-w')\n }\n\n command = command.concat(dependencies)\n\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Bun.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithBun(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n\n command = command.concat(dependencies)\n\n switch (type) {\n case 'dev':\n command.push('--development')\n break\n case 'peer':\n command.push('--optional')\n break\n case 'prod':\n break\n }\n return command\n}\n\n/**\n * Given a directory it traverses the directory up looking for a package.json and if found, it reads it\n * decodes the JSON, and returns its content as a Javascript object.\n * @param options - The directory from which traverse up.\n * @returns If found, the promise resolves with the path to the\n * package.json and its content. If not found, it throws a FindUpAndReadPackageJsonNotFoundError error.\n */\nexport async function findUpAndReadPackageJson(fromDirectory: string): Promise<{path: string; content: PackageJson}> {\n const packageJsonPath = await findPathUp('package.json', {cwd: fromDirectory, type: 'file'})\n if (packageJsonPath) {\n const packageJson = JSON.parse(await readFile(packageJsonPath))\n return {path: packageJsonPath, content: packageJson}\n } else {\n throw new FindUpAndReadPackageJsonNotFoundError(fromDirectory)\n }\n}\n\nexport async function addResolutionOrOverride(directory: string, dependencies: {[key: string]: string}): Promise<void> {\n const packageManager = await getPackageManager(directory)\n const packageJsonPath = joinPath(directory, 'package.json')\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n\n if (packageManager === 'yarn') {\n packageJsonContent.resolutions = packageJsonContent.resolutions\n ? {...packageJsonContent.resolutions, ...dependencies}\n : dependencies\n }\n if (packageManager === 'npm' || packageManager === 'pnpm' || packageManager === 'bun') {\n packageJsonContent.overrides = packageJsonContent.overrides\n ? {...packageJsonContent.overrides, ...dependencies}\n : dependencies\n }\n\n await writeFile(packageJsonPath, JSON.stringify(packageJsonContent, null, 2))\n}\n\n/**\n * Returns the latest available version of an NPM package.\n * @param name - The name of the NPM package.\n * @returns A promise to get the latest available version of a package.\n */\nasync function getLatestNPMPackageVersion(name: string) {\n outputDebug(outputContent`Getting the latest version of NPM package: ${outputToken.raw(name)}`)\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return latestVersion(name)\n })\n}\n\n/**\n * Writes the package.json file to the given directory.\n *\n * @param directory - Directory where the package.json file will be written.\n * @param packageJSON - Package.json file to write.\n */\nexport async function writePackageJSON(directory: string, packageJSON: PackageJson): Promise<void> {\n outputDebug(outputContent`JSON-encoding and writing content to package.json at ${outputToken.path(directory)}...`)\n const packagePath = joinPath(directory, 'package.json')\n await writeFile(packagePath, JSON.stringify(packageJSON, null, 2))\n}\n\n/**\n * Infers the package manager to be used based on the provided options and environment.\n *\n * This function determines the package manager in the following order of precedence:\n * 1. Uses the package manager specified in the options, if valid.\n * 2. Infers the package manager from the user agent string.\n * 3. Infers the package manager used for the global CLI installation.\n * 4. Defaults to 'npm' if no other method succeeds.\n *\n * @param optionsPackageManager - The package manager specified in the options (if any).\n * @returns The inferred package manager as a PackageManager type.\n */\nexport function inferPackageManager(optionsPackageManager: string | undefined, env = process.env): PackageManager {\n if (optionsPackageManager && packageManager.includes(optionsPackageManager as PackageManager)) {\n return optionsPackageManager as PackageManager\n }\n const usedPackageManager = packageManagerFromUserAgent(env)\n if (usedPackageManager !== 'unknown') return usedPackageManager\n\n const globalPackageManager = inferPackageManagerForGlobalCLI()\n if (globalPackageManager !== 'unknown') return globalPackageManager\n\n return 'npm'\n}\n"]}
|
|
1
|
+
{"version":3,"file":"node-package-manager.js","sourceRoot":"","sources":["../../../src/public/node/node-package-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAA;AAC/C,OAAO,EAAC,eAAe,EAAc,MAAM,YAAY,CAAA;AACvD,OAAO,EAAC,aAAa,EAAE,IAAI,EAAC,MAAM,aAAa,CAAA;AAC/C,OAAO,EAAC,UAAU,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,IAAI,EAAC,MAAM,SAAS,CAAA;AACzE,OAAO,EAAC,OAAO,EAAE,QAAQ,EAAC,MAAM,WAAW,CAAA;AAC3C,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,+BAA+B,EAAC,MAAM,gBAAgB,CAAA;AAC9D,OAAO,EAAC,WAAW,EAAE,aAAa,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAoB,aAAa,EAAE,yBAAyB,EAAC,MAAM,kCAAkC,CAAA;AAC5G,OAAO,aAAa,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAC,MAAM,EAAE,SAAS,IAAI,eAAe,EAAC,MAAM,QAAQ,CAAA;AAI3D,qCAAqC;AACrC,MAAM,CAAC,MAAM,YAAY,GAAG,WAAW,CAAA;AAEvC,oCAAoC;AACpC,MAAM,CAAC,MAA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,EAAE;QACpD,OAAO,aAAa,CAAC,IAAI,CAAC,CAAA;IAC5B,CAAC,CAAC,CAAA;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CAAC,SAAiB,EAAE,WAAwB;IAChF,WAAW,CAAC,aAAa,CAAA,wDAAwD,WAAW,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAA;IAClH,MAAM,WAAW,GAAG,QAAQ,CAAC,SAAS,EAAE,cAAc,CAAC,CAAA;IACvD,MAAM,SAAS,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,WAAW,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,CAAA;AACpE,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,qBAAyC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG;IAC9F,IAAI,qBAAqB,IAAI,cAAc,CAAC,QAAQ,CAAC,qBAAuC,CAAC,EAAE,CAAC;QAC9F,OAAO,qBAAuC,CAAA;IAChD,CAAC;IACD,MAAM,kBAAkB,GAAG,2BAA2B,CAAC,GAAG,CAAC,CAAA;IAC3D,IAAI,kBAAkB,KAAK,SAAS;QAAE,OAAO,kBAAkB,CAAA;IAE/D,MAAM,oBAAoB,GAAG,+BAA+B,EAAE,CAAA;IAC9D,IAAI,oBAAoB,KAAK,SAAS;QAAE,OAAO,oBAAoB,CAAA;IAEnE,OAAO,KAAK,CAAA;AACd,CAAC","sourcesContent":["import {AbortError, BugError} from './error.js'\nimport {AbortController, AbortSignal} from './abort.js'\nimport {captureOutput, exec} from './system.js'\nimport {fileExists, readFile, writeFile, findPathUp, glob} from './fs.js'\nimport {dirname, joinPath} from './path.js'\nimport {runWithTimer} from './metadata.js'\nimport {inferPackageManagerForGlobalCLI} from './is-global.js'\nimport {outputToken, outputContent, outputDebug} from '../../public/node/output.js'\nimport {PackageVersionKey, cacheRetrieve, cacheRetrieveOrRepopulate} from '../../private/node/conf-store.js'\nimport latestVersion from 'latest-version'\nimport {SemVer, satisfies as semverSatisfies} from 'semver'\nimport type {Writable} from 'stream'\nimport type {ExecOptions} from './system.js'\n\n/** The name of the Yarn lock file */\nexport const yarnLockfile = 'yarn.lock'\n\n/** The name of the npm lock file */\nexport const npmLockfile = 'package-lock.json'\n\n/** The name of the pnpm lock file */\nexport const pnpmLockfile = 'pnpm-lock.yaml'\n\n/** The name of the bun lock file */\nexport const bunLockfile = 'bun.lockb'\n\n/** The name of the pnpm workspace file */\nexport const pnpmWorkspaceFile = 'pnpm-workspace.yaml'\n\n/** An array containing the lockfiles from all the package managers */\nexport const lockfiles: Lockfile[] = [yarnLockfile, pnpmLockfile, npmLockfile, bunLockfile]\nexport const lockfilesByManager: {[key in PackageManager]: Lockfile | undefined} = {\n yarn: yarnLockfile,\n npm: npmLockfile,\n pnpm: pnpmLockfile,\n bun: bunLockfile,\n unknown: undefined,\n}\nexport type Lockfile = 'yarn.lock' | 'package-lock.json' | 'pnpm-lock.yaml' | 'bun.lockb'\n\n/**\n * A union type that represents the type of dependencies in the package.json\n * - dev: devDependencies\n * - prod: dependencies\n * - peer: peerDependencies\n */\nexport type DependencyType = 'dev' | 'prod' | 'peer'\n\n/**\n * A union that represents the package managers available.\n */\nexport const packageManager = ['yarn', 'npm', 'pnpm', 'bun', 'unknown'] as const\nexport type PackageManager = (typeof packageManager)[number]\n\n/**\n * Returns an abort error that's thrown when the package manager can't be determined.\n * @returns An abort error.\n */\nexport class UnknownPackageManagerError extends AbortError {\n constructor() {\n super('Unknown package manager')\n }\n}\n\n/**\n * Returns an abort error that's thrown when a directory that's expected to have\n * a package.json doesn't have it.\n * @param directory - The path to the directory that should contain a package.json\n * @returns An abort error.\n */\nexport class PackageJsonNotFoundError extends AbortError {\n constructor(directory: string) {\n super(outputContent`The directory ${outputToken.path(directory)} doesn't have a package.json.`)\n }\n}\n\n/**\n * Returns a bug error that's thrown when the lookup of the package.json traversing the directory\n * hierarchy up can't find a package.json\n * @param directory - The directory from which the traverse has been done\n * @returns An abort error.\n */\nexport class FindUpAndReadPackageJsonNotFoundError extends BugError {\n constructor(directory: string) {\n super(outputContent`Couldn't find a a package.json traversing directories from ${outputToken.path(directory)}`)\n }\n}\n\n/**\n * Returns the dependency manager used to run the create workflow.\n * @param env - The environment variables of the process in which the CLI runs.\n * @returns The dependency manager\n */\nexport function packageManagerFromUserAgent(env = process.env): PackageManager {\n if (env.npm_config_user_agent?.includes('yarn')) {\n return 'yarn'\n } else if (env.npm_config_user_agent?.includes('pnpm')) {\n return 'pnpm'\n } else if (env.npm_config_user_agent?.includes('bun')) {\n return 'bun'\n } else if (env.npm_config_user_agent?.includes('npm')) {\n return 'npm'\n }\n return 'unknown'\n}\n\n/**\n * Returns the dependency manager used in a directory.\n * @param fromDirectory - The starting directory\n * @returns The dependency manager\n */\nexport async function getPackageManager(fromDirectory: string): Promise<PackageManager> {\n const directory = await captureOutput('npm', ['prefix'], {cwd: fromDirectory})\n outputDebug(outputContent`Obtaining the dependency manager in directory ${outputToken.path(directory)}...`)\n const packageJson = joinPath(directory, 'package.json')\n if (!(await fileExists(packageJson))) {\n return packageManagerFromUserAgent()\n }\n const yarnLockPath = joinPath(directory, yarnLockfile)\n const pnpmLockPath = joinPath(directory, pnpmLockfile)\n const bunLockPath = joinPath(directory, bunLockfile)\n if (await fileExists(yarnLockPath)) {\n return 'yarn'\n } else if (await fileExists(pnpmLockPath)) {\n return 'pnpm'\n } else if (await fileExists(bunLockPath)) {\n return 'bun'\n } else {\n return 'npm'\n }\n}\n\ninterface InstallNPMDependenciesRecursivelyOptions {\n /**\n * The dependency manager to use to install the dependencies.\n */\n packageManager: PackageManager\n /**\n * The directory from where we'll find package.json's recursively\n */\n directory: string\n\n /**\n * Specifies the maximum depth of the glob search.\n */\n deep?: number\n}\n\n/**\n * This function traverses down a directory tree to find directories containing a package.json\n * and installs the dependencies if needed. To know if it's needed, it uses the \"check\" command\n * provided by dependency managers.\n * @param options - Options to install dependencies recursively.\n */\nexport async function installNPMDependenciesRecursively(\n options: InstallNPMDependenciesRecursivelyOptions,\n): Promise<void> {\n const packageJsons = await glob(joinPath(options.directory, '**/package.json'), {\n ignore: [joinPath(options.directory, 'node_modules/**/package.json')],\n cwd: options.directory,\n onlyFiles: true,\n deep: options.deep,\n })\n const abortController = new AbortController()\n try {\n await Promise.all(\n packageJsons.map(async (packageJsonPath) => {\n const directory = dirname(packageJsonPath)\n await installNodeModules({\n directory,\n packageManager: options.packageManager,\n stdout: undefined,\n stderr: undefined,\n signal: abortController.signal,\n args: [],\n })\n }),\n )\n } catch (error) {\n abortController.abort()\n throw error\n }\n}\n\ninterface InstallNodeModulesOptions {\n directory: string\n args?: string[]\n packageManager: PackageManager\n stdout?: Writable\n stderr?: Writable\n signal?: AbortSignal\n}\n\nexport async function installNodeModules(options: InstallNodeModulesOptions): Promise<void> {\n const execOptions: ExecOptions = {\n cwd: options.directory,\n stdin: undefined,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n }\n let args = ['install']\n if (options.args) {\n args = args.concat(options.args)\n }\n await runWithTimer('cmd_all_timing_network_ms')(async () => {\n await exec(options.packageManager, args, execOptions)\n })\n}\n\n/**\n * Returns the name of the package configured in its package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the name.\n */\nexport async function getPackageName(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.name\n}\n/**\n * Returns the version of the package configured in its package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the version.\n */\nexport async function getPackageVersion(packageJsonPath: string): Promise<string | undefined> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n return packageJsonContent.version\n}\n\n/**\n * Returns the list of production and dev dependencies of a package.json\n * @param packageJsonPath - Path to the package.json file\n * @returns A promise that resolves with the list of dependencies.\n */\nexport async function getDependencies(packageJsonPath: string): Promise<{[key: string]: string}> {\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const dependencies: {[key: string]: string} = packageJsonContent.dependencies ?? {}\n const devDependencies: {[key: string]: string} = packageJsonContent.devDependencies ?? {}\n\n return {...dependencies, ...devDependencies}\n}\n\n/**\n * Returns true if the app uses workspaces, false otherwise.\n * @param packageJsonPath - Path to the package.json file\n * @param pnpmWorkspacePath - Path to the pnpm-workspace.yaml file\n * @returns A promise that resolves with true if the app uses workspaces, false otherwise.\n */\nexport async function usesWorkspaces(appDirectory: string): Promise<boolean> {\n const packageJsonPath = joinPath(appDirectory, 'package.json')\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n const pnpmWorkspacePath = joinPath(appDirectory, pnpmWorkspaceFile)\n return Boolean(packageJsonContent.workspaces) || fileExists(pnpmWorkspacePath)\n}\n\n/**\n * Given an NPM dependency, it checks if there's a more recent version, and if there is, it returns its value.\n * @param dependency - The dependency name (e.g. react)\n * @param currentVersion - The current version.\n * @param cacheExpiryInHours - If the last check was done more than this amount of hours ago, it will\n * refresh the cache. Defaults to always refreshing.\n * @returns A promise that resolves with a more recent version or undefined if there's no more recent version.\n */\nexport async function checkForNewVersion(\n dependency: string,\n currentVersion: string,\n {cacheExpiryInHours = 0} = {},\n): Promise<string | undefined> {\n const getLatestVersion = async () => {\n outputDebug(outputContent`Checking if there's a version of ${dependency} newer than ${currentVersion}`)\n return getLatestNPMPackageVersion(dependency)\n }\n\n const cacheKey: PackageVersionKey = `npm-package-${dependency}`\n let lastVersion\n try {\n lastVersion = await cacheRetrieveOrRepopulate(cacheKey, getLatestVersion, cacheExpiryInHours * 3600 * 1000)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n return undefined\n }\n\n if (lastVersion && new SemVer(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n}\n\n/**\n * Given an NPM dependency, it checks if there's a cached more recent version, and if there is, it returns its value.\n * @param dependency - The dependency name (e.g. react)\n * @param currentVersion - The current version.\n * @returns A more recent version or undefined if there's no more recent version.\n */\nexport function checkForCachedNewVersion(dependency: string, currentVersion: string): string | undefined {\n const cacheKey: PackageVersionKey = `npm-package-${dependency}`\n const lastVersion = cacheRetrieve(cacheKey)?.value\n\n if (lastVersion && new SemVer(currentVersion).compare(lastVersion) < 0) {\n return lastVersion\n } else {\n return undefined\n }\n}\n\n/**\n * Utility function used to check whether a package version satisfies some requirements\n * @param version - The version to check\n * @param requirements - The requirements to check against, e.g. \"\\>=1.0.0\" - see https://www.npmjs.com/package/semver#ranges\n * @returns A boolean indicating whether the version satisfies the requirements\n */\nexport function versionSatisfies(version: string, requirements: string): boolean {\n return semverSatisfies(version, requirements)\n}\n\n/**\n * An interface that represents a package.json\n */\nexport interface PackageJson {\n /**\n * The name attribute of the package.json\n */\n name?: string\n\n /**\n * The author attribute of the package.json\n */\n author?: string\n\n /**\n * The version attribute of the package.json\n */\n version?: string\n\n /**\n * The scripts attribute of the package.json\n */\n scripts?: {[key: string]: string}\n\n /**\n * The dependencies attribute of the package.json\n */\n dependencies?: {[key: string]: string}\n\n /**\n * The devDependencies attribute of the package.json\n */\n devDependencies?: {[key: string]: string}\n\n /**\n * The peerDependencies attribute of the package.json\n */\n peerDependencies?: {[key: string]: string}\n\n /**\n * The optional oclif settings attribute of the package.json\n */\n oclif?: {\n plugins?: string[]\n }\n\n /**\n * The workspaces attribute of the package.json\n */\n workspaces?: string[]\n\n /**\n * The resolutions attribute of the package.json. Only useful when using yarn as package manager\n */\n resolutions?: {[key: string]: string}\n\n /**\n * The overrides attribute of the package.json. Only useful when using npm o npmn as package managers\n */\n overrides?: {[key: string]: string}\n\n /**\n * The prettier attribute of the package.json\n */\n prettier?: string\n\n /**\n * The private attribute of the package.json.\n * https://docs.npmjs.com/cli/v9/configuring-npm/package-json#private\n */\n private?: boolean\n}\n\n/**\n * Reads and parses a package.json\n * @param packageJsonPath - Path to the package.json\n * @returns An promise that resolves with an in-memory representation\n * of the package.json or rejects with an error if the file is not found or the content is\n * not decodable.\n */\nexport async function readAndParsePackageJson(packageJsonPath: string): Promise<PackageJson> {\n if (!(await fileExists(packageJsonPath))) {\n throw new PackageJsonNotFoundError(dirname(packageJsonPath))\n }\n return JSON.parse(await readFile(packageJsonPath))\n}\n\ninterface AddNPMDependenciesIfNeededOptions {\n /** How dependencies should be added */\n type: DependencyType\n\n /** The dependency manager to use to add dependencies */\n packageManager: PackageManager\n\n /** The directory that contains the package.json where dependencies will be added */\n directory: string\n\n /** Standard output coming from the underlying installation process */\n stdout?: Writable\n\n /** Standard error coming from the underlying installation process */\n stderr?: Writable\n\n /** Abort signal to stop the process */\n signal?: AbortSignal\n\n /** Whether to add the dependencies to the root package.json or to the package.json of the directory */\n addToRootDirectory?: boolean\n}\n\n/**\n * An interface that represents a dependency name with its version\n */\nexport interface DependencyVersion {\n /**\n * The name of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below name would be \"react\"\n * ```\n * {\n * \"react\": \"1.2.3\"\n * }\n * ```\n */\n name: string\n\n /**\n * The version of the NPM dependency as it's reflected in the package.json:\n *\n * @example\n * In the example below version would be \"1.2.3\"\n * ```\n * {\n * \"react\": \"1.2.3\"\n * }\n * ```\n */\n version: string | undefined\n}\n\n/**\n * Adds dependencies to a Node project (i.e. a project that has a package.json)\n * @param dependencies - List of dependencies to be added.\n * @param options - Options for adding dependencies.\n */\nexport async function addNPMDependenciesIfNeeded(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n outputDebug(outputContent`Adding the following dependencies if needed:\n${outputToken.json(dependencies)}\nWith options:\n${outputToken.json(options)}\n `)\n const packageJsonPath = joinPath(options.directory, 'package.json')\n if (!(await fileExists(packageJsonPath))) {\n throw new PackageJsonNotFoundError(options.directory)\n }\n const existingDependencies = Object.keys(await getDependencies(packageJsonPath))\n const dependenciesToAdd = dependencies.filter((dep) => {\n return !existingDependencies.includes(dep.name)\n })\n if (dependenciesToAdd.length === 0) {\n return\n }\n await addNPMDependencies(dependenciesToAdd, options)\n}\n\nexport async function addNPMDependencies(\n dependencies: DependencyVersion[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n const dependenciesWithVersion = dependencies.map((dep) => {\n return dep.version ? `${dep.name}@${dep.version}` : dep.name\n })\n options.stdout?.write(`Installing ${[dependenciesWithVersion].join(' ')} with ${options.packageManager}`)\n switch (options.packageManager) {\n case 'npm':\n // npm isn't too smart when resolving the dependency tree. For example, admin ui extensions include react as\n // a peer dependency, but npm can't figure out the relationship and fails. Installing dependencies one by one\n // makes the task easier and npm can then proceed.\n for (const dep of dependenciesWithVersion) {\n // eslint-disable-next-line no-await-in-loop\n await installDependencies(options, argumentsToAddDependenciesWithNPM(dep, options.type))\n }\n break\n case 'yarn':\n await installDependencies(\n options,\n argumentsToAddDependenciesWithYarn(dependenciesWithVersion, options.type, Boolean(options.addToRootDirectory)),\n )\n break\n case 'pnpm':\n await installDependencies(\n options,\n argumentsToAddDependenciesWithPNPM(dependenciesWithVersion, options.type, Boolean(options.addToRootDirectory)),\n )\n break\n case 'bun':\n await installDependencies(options, argumentsToAddDependenciesWithBun(dependenciesWithVersion, options.type))\n await installDependencies(options, ['install'])\n break\n case 'unknown':\n throw new UnknownPackageManagerError()\n }\n}\n\nasync function installDependencies(options: AddNPMDependenciesIfNeededOptions, args: string[]) {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n return exec(options.packageManager, args, {\n cwd: options.directory,\n stdout: options.stdout,\n stderr: options.stderr,\n signal: options.signal,\n })\n })\n}\n\nexport async function addNPMDependenciesWithoutVersionIfNeeded(\n dependencies: string[],\n options: AddNPMDependenciesIfNeededOptions,\n): Promise<void> {\n await addNPMDependenciesIfNeeded(\n dependencies.map((dependency) => {\n return {name: dependency, version: undefined}\n }),\n options,\n )\n}\n\n/**\n * Returns the arguments to add dependencies using NPM.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithNPM(dependency: string, type: DependencyType): string[] {\n let command = ['install']\n command = command.concat(dependency)\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n // NPM adds ^ to the installed version by default. We want to install exact versions unless specified otherwise.\n if (dependency.match(/@\\d/g)) {\n command.push('--save-exact')\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Yarn.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @param addAtRoot - Force to install the dependencies in the workspace root (optional, default = false)\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithYarn(dependencies: string[], type: DependencyType, addAtRoot = false): string[] {\n let command = ['add']\n\n if (addAtRoot) {\n command.push('-W')\n }\n\n command = command.concat(dependencies)\n switch (type) {\n case 'dev':\n command.push('--dev')\n break\n case 'peer':\n command.push('--peer')\n break\n case 'prod':\n command.push('--prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using PNPM.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @param addAtRoot - Force to install the dependencies in the workspace root (optional, default = false)\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithPNPM(dependencies: string[], type: DependencyType, addAtRoot = false): string[] {\n let command = ['add']\n\n if (addAtRoot) {\n command.push('-w')\n }\n\n command = command.concat(dependencies)\n\n switch (type) {\n case 'dev':\n command.push('--save-dev')\n break\n case 'peer':\n command.push('--save-peer')\n break\n case 'prod':\n command.push('--save-prod')\n break\n }\n return command\n}\n\n/**\n * Returns the arguments to add dependencies using Bun.\n * @param dependencies - The list of dependencies to add\n * @param type - The dependency type.\n * @returns An array with the arguments.\n */\nfunction argumentsToAddDependenciesWithBun(dependencies: string[], type: DependencyType): string[] {\n let command = ['add']\n\n command = command.concat(dependencies)\n\n switch (type) {\n case 'dev':\n command.push('--development')\n break\n case 'peer':\n command.push('--optional')\n break\n case 'prod':\n break\n }\n return command\n}\n\n/**\n * Given a directory it traverses the directory up looking for a package.json and if found, it reads it\n * decodes the JSON, and returns its content as a Javascript object.\n * @param options - The directory from which traverse up.\n * @returns If found, the promise resolves with the path to the\n * package.json and its content. If not found, it throws a FindUpAndReadPackageJsonNotFoundError error.\n */\nexport async function findUpAndReadPackageJson(fromDirectory: string): Promise<{path: string; content: PackageJson}> {\n const packageJsonPath = await findPathUp('package.json', {cwd: fromDirectory, type: 'file'})\n if (packageJsonPath) {\n const packageJson = JSON.parse(await readFile(packageJsonPath))\n return {path: packageJsonPath, content: packageJson}\n } else {\n throw new FindUpAndReadPackageJsonNotFoundError(fromDirectory)\n }\n}\n\nexport async function addResolutionOrOverride(directory: string, dependencies: {[key: string]: string}): Promise<void> {\n const packageManager = await getPackageManager(directory)\n const packageJsonPath = joinPath(directory, 'package.json')\n const packageJsonContent = await readAndParsePackageJson(packageJsonPath)\n\n if (packageManager === 'yarn') {\n packageJsonContent.resolutions = packageJsonContent.resolutions\n ? {...packageJsonContent.resolutions, ...dependencies}\n : dependencies\n }\n if (packageManager === 'npm' || packageManager === 'pnpm' || packageManager === 'bun') {\n packageJsonContent.overrides = packageJsonContent.overrides\n ? {...packageJsonContent.overrides, ...dependencies}\n : dependencies\n }\n\n await writeFile(packageJsonPath, JSON.stringify(packageJsonContent, null, 2))\n}\n\n/**\n * Returns the latest available version of an NPM package.\n * @param name - The name of the NPM package.\n * @returns A promise to get the latest available version of a package.\n */\nasync function getLatestNPMPackageVersion(name: string) {\n outputDebug(outputContent`Getting the latest version of NPM package: ${outputToken.raw(name)}`)\n return runWithTimer('cmd_all_timing_network_ms')(() => {\n return latestVersion(name)\n })\n}\n\n/**\n * Writes the package.json file to the given directory.\n *\n * @param directory - Directory where the package.json file will be written.\n * @param packageJSON - Package.json file to write.\n */\nexport async function writePackageJSON(directory: string, packageJSON: PackageJson): Promise<void> {\n outputDebug(outputContent`JSON-encoding and writing content to package.json at ${outputToken.path(directory)}...`)\n const packagePath = joinPath(directory, 'package.json')\n await writeFile(packagePath, JSON.stringify(packageJSON, null, 2))\n}\n\n/**\n * Infers the package manager to be used based on the provided options and environment.\n *\n * This function determines the package manager in the following order of precedence:\n * 1. Uses the package manager specified in the options, if valid.\n * 2. Infers the package manager from the user agent string.\n * 3. Infers the package manager used for the global CLI installation.\n * 4. Defaults to 'npm' if no other method succeeds.\n *\n * @param optionsPackageManager - The package manager specified in the options (if any).\n * @returns The inferred package manager as a PackageManager type.\n */\nexport function inferPackageManager(optionsPackageManager: string | undefined, env = process.env): PackageManager {\n if (optionsPackageManager && packageManager.includes(optionsPackageManager as PackageManager)) {\n return optionsPackageManager as PackageManager\n }\n const usedPackageManager = packageManagerFromUserAgent(env)\n if (usedPackageManager !== 'unknown') return usedPackageManager\n\n const globalPackageManager = inferPackageManagerForGlobalCLI()\n if (globalPackageManager !== 'unknown') return globalPackageManager\n\n return 'npm'\n}\n"]}
|