@shopify/cli-kit 3.68.0 → 3.69.0
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/public_api_versions.d.ts +14 -0
- package/dist/cli/api/graphql/admin/generated/public_api_versions.js +28 -0
- package/dist/cli/api/graphql/admin/generated/public_api_versions.js.map +1 -0
- package/dist/private/node/api/graphql.d.ts +1 -1
- package/dist/private/node/api/graphql.js +1 -0
- package/dist/private/node/api/graphql.js.map +1 -1
- package/dist/private/node/api/headers.js +2 -2
- package/dist/private/node/api/headers.js.map +1 -1
- package/dist/private/node/api/rest.js +3 -1
- package/dist/private/node/api/rest.js.map +1 -1
- package/dist/private/node/api.d.ts +2 -2
- package/dist/private/node/api.js +8 -6
- package/dist/private/node/api.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/demo-recorder.js +1 -0
- package/dist/private/node/demo-recorder.js.map +1 -1
- package/dist/private/node/session/device-authorization.js +15 -7
- package/dist/private/node/session/device-authorization.js.map +1 -1
- package/dist/private/node/session/exchange.d.ts +0 -8
- package/dist/private/node/session/exchange.js +2 -19
- package/dist/private/node/session/exchange.js.map +1 -1
- package/dist/private/node/session/validate.js +1 -0
- package/dist/private/node/session/validate.js.map +1 -1
- package/dist/private/node/session.d.ts +5 -5
- package/dist/private/node/session.js +4 -12
- package/dist/private/node/session.js.map +1 -1
- package/dist/private/node/testing/ui.js +0 -3
- package/dist/private/node/testing/ui.js.map +1 -1
- package/dist/private/node/themes/generate-theme-name.js +1 -0
- package/dist/private/node/themes/generate-theme-name.js.map +1 -1
- package/dist/private/node/ui/components/AutocompletePrompt.test.js +0 -3
- package/dist/private/node/ui/components/AutocompletePrompt.test.js.map +1 -1
- package/dist/private/node/ui/components/Banner.js +1 -0
- package/dist/private/node/ui/components/Banner.js.map +1 -1
- package/dist/private/node/ui/components/ConcurrentOutput.test.js +7 -7
- package/dist/private/node/ui/components/ConcurrentOutput.test.js.map +1 -1
- package/dist/private/node/ui/components/FatalError.js +1 -0
- package/dist/private/node/ui/components/FatalError.js.map +1 -1
- package/dist/private/node/ui/components/List.js +1 -1
- package/dist/private/node/ui/components/List.js.map +1 -1
- package/dist/private/node/ui/components/Prompts/InfoTable.js +1 -0
- package/dist/private/node/ui/components/Prompts/InfoTable.js.map +1 -1
- package/dist/private/node/ui/components/SelectInput.js +1 -1
- package/dist/private/node/ui/components/SelectInput.js.map +1 -1
- package/dist/private/node/ui/components/SelectPrompt.test.js +0 -4
- package/dist/private/node/ui/components/SelectPrompt.test.js.map +1 -1
- package/dist/private/node/ui/components/Table/Row.js.map +1 -1
- package/dist/private/node/ui/components/Tasks.js +2 -1
- package/dist/private/node/ui/components/Tasks.js.map +1 -1
- package/dist/private/node/ui/components/TextPrompt.d.ts +1 -1
- package/dist/private/node/ui/components/TextPrompt.js.map +1 -1
- package/dist/private/node/ui/components/TokenizedText.js +1 -0
- package/dist/private/node/ui/components/TokenizedText.js.map +1 -1
- package/dist/private/node/ui/hooks/use-abort-signal.js +1 -1
- package/dist/private/node/ui/hooks/use-abort-signal.js.map +1 -1
- package/dist/private/node/ui.js +3 -1
- package/dist/private/node/ui.js.map +1 -1
- package/dist/public/common/array.js +1 -0
- package/dist/public/common/array.js.map +1 -1
- package/dist/public/common/string.js +3 -0
- package/dist/public/common/string.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/api/admin.d.ts +14 -1
- package/dist/public/node/api/admin.js +29 -28
- package/dist/public/node/api/admin.js.map +1 -1
- package/dist/public/node/api/app-management.d.ts +5 -3
- package/dist/public/node/api/app-management.js +16 -11
- package/dist/public/node/api/app-management.js.map +1 -1
- package/dist/public/node/api/graphql.js +13 -1
- package/dist/public/node/api/graphql.js.map +1 -1
- package/dist/public/node/api/rest-api-throttler.js +10 -3
- package/dist/public/node/api/rest-api-throttler.js.map +1 -1
- package/dist/public/node/archiver.js +6 -2
- package/dist/public/node/archiver.js.map +1 -1
- package/dist/public/node/base-command.js +1 -1
- package/dist/public/node/base-command.js.map +1 -1
- package/dist/public/node/context/local.d.ts +0 -9
- package/dist/public/node/context/local.js +0 -13
- package/dist/public/node/context/local.js.map +1 -1
- package/dist/public/node/context/spin.js +1 -1
- package/dist/public/node/context/spin.js.map +1 -1
- package/dist/public/node/custom-oclif-loader.js +5 -4
- package/dist/public/node/custom-oclif-loader.js.map +1 -1
- package/dist/public/node/dot-env.js +2 -1
- package/dist/public/node/dot-env.js.map +1 -1
- package/dist/public/node/environments.js +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/framework.js +5 -4
- package/dist/public/node/framework.js.map +1 -1
- package/dist/public/node/fs.d.ts +2 -1
- package/dist/public/node/fs.js +2 -2
- package/dist/public/node/fs.js.map +1 -1
- package/dist/public/node/git.js +2 -0
- package/dist/public/node/git.js.map +1 -1
- package/dist/public/node/github.js +2 -0
- package/dist/public/node/github.js.map +1 -1
- package/dist/public/node/hooks/deprecations.js +1 -1
- package/dist/public/node/hooks/deprecations.js.map +1 -1
- package/dist/public/node/hooks/postrun.js +2 -1
- package/dist/public/node/hooks/postrun.js.map +1 -1
- package/dist/public/node/hooks/prerun.js +1 -1
- package/dist/public/node/hooks/prerun.js.map +1 -1
- package/dist/public/node/http.js +2 -1
- package/dist/public/node/http.js.map +1 -1
- package/dist/public/node/json-schema.d.ts +1 -1
- package/dist/public/node/json-schema.js.map +1 -1
- package/dist/public/node/liquid.js +12 -2
- package/dist/public/node/liquid.js.map +1 -1
- package/dist/public/node/local-storage.d.ts +1 -1
- package/dist/public/node/local-storage.js.map +1 -1
- package/dist/public/node/metadata.js +1 -0
- package/dist/public/node/metadata.js.map +1 -1
- package/dist/public/node/monorail.d.ts +2 -1
- package/dist/public/node/monorail.js +1 -1
- package/dist/public/node/monorail.js.map +1 -1
- package/dist/public/node/output.js +2 -1
- package/dist/public/node/output.js.map +1 -1
- package/dist/public/node/ruby.js +1 -0
- package/dist/public/node/ruby.js.map +1 -1
- package/dist/public/node/session.d.ts +7 -6
- package/dist/public/node/session.js +2 -1
- package/dist/public/node/session.js.map +1 -1
- package/dist/public/node/system.js +1 -1
- package/dist/public/node/system.js.map +1 -1
- package/dist/public/node/themes/api.js +34 -4
- package/dist/public/node/themes/api.js.map +1 -1
- package/dist/public/node/themes/factories.js +1 -0
- package/dist/public/node/themes/factories.js.map +1 -1
- package/dist/public/node/themes/types.d.ts +2 -3
- package/dist/public/node/themes/types.js.map +1 -1
- package/dist/public/node/themes/urls.d.ts +1 -0
- package/dist/public/node/themes/urls.js +3 -0
- package/dist/public/node/themes/urls.js.map +1 -1
- package/dist/public/node/tree-kill.js +8 -4
- package/dist/public/node/tree-kill.js.map +1 -1
- package/dist/public/node/ui.js +5 -2
- package/dist/public/node/ui.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +1 -5
- package/assets/auth-error.html +0 -23
- package/assets/empty-url.html +0 -23
- package/assets/favicon.svg +0 -26
- package/assets/missing-code.html +0 -23
- package/assets/missing-state.html +0 -23
- package/assets/style.css +0 -58
- package/assets/success.html +0 -20
- package/dist/private/node/session/authorize.d.ts +0 -5
- package/dist/private/node/session/authorize.js +0 -69
- package/dist/private/node/session/authorize.js.map +0 -1
- package/dist/private/node/session/post-auth.d.ts +0 -10
- package/dist/private/node/session/post-auth.js +0 -61
- package/dist/private/node/session/post-auth.js.map +0 -1
- package/dist/private/node/session/redirect-listener.d.ts +0 -34
- package/dist/private/node/session/redirect-listener.js +0 -105
- package/dist/private/node/session/redirect-listener.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"liquid.js","sourceRoot":"","sources":["../../../src/public/node/liquid.ts"],"names":[],"mappings":"AAAA,OAA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CAAC,QAAQ,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,EAAE;YAC1D,MAAM,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,CAAA;YAChC,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,gBAAgB,CAAC,CAAA;YAChD,MAAM,aAAa,GAAG,MAAM,oBAAoB,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;YAC/D,MAAM,YAAY,GAAG,MAAM,4BAA4B,CAAC,gBAAgB,CAAC,CAAA;YACzE,MAAM,uBAAuB,GAAG,UAAU,CAAC,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC,CAAA;YACjE,MAAM,QAAQ,CAAC,gBAAgB,EAAE,uBAAuB,CAAC,CAAA;YACzD,MAAM,SAAS,CAAC,uBAAuB,EAAE,aAAa,CAAC,CAAA;YACvD,IAAI,YAAY,EAAE;gBAChB,MAAM,KAAK,CAAC,uBAAuB,EAAE,KAAK,CAAC,CAAA;aAC5C;SACF;aAAM,IAAI,gBAAgB,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;YAC5C,MAAM,oBAAoB,GAAG,UAAU,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAA;YAC3D,MAAM,QAAQ,CAAC,gBAAgB,EAAE,oBAAoB,CAAC,CAAA;SACvD;aAAM;YACL,MAAM,QAAQ,CAAC,gBAAgB,EAAE,UAAU,CAAC,CAAA;SAC7C;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"]}
|
|
@@ -16,7 +16,7 @@ export declare class LocalStorage<T extends {
|
|
|
16
16
|
* @param key - The key to get.
|
|
17
17
|
* @returns The value.
|
|
18
18
|
*/
|
|
19
|
-
get<TKey extends keyof T>(key: TKey): T[TKey];
|
|
19
|
+
get<TKey extends keyof T>(key: TKey): T[TKey] | undefined;
|
|
20
20
|
/**
|
|
21
21
|
* Set a value in the local storage.
|
|
22
22
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/public/node/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,MAAM,CAAA;AAEzB;;;GAGG;AACH,8DAA8D;AAC9D,MAAM,OAAO,YAAY;IAGvB,YAAY,OAA6C;QACvD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAI,OAAO,CAAC,CAAA;IACtC,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS;QACjC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC7B,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS,EAAE,KAAe;QAClD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAuB,GAAS;QACpC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;CACF","sourcesContent":["import Config from 'conf'\n\n/**\n * A wrapper around the `conf` package that provides a strongly-typed interface\n * for accessing the local storage.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class LocalStorage<T extends {[key: string]: any}> {\n private readonly config: Config<T>\n\n constructor(options: {projectName?: string; cwd?: string}) {\n this.config = new Config<T>(options)\n }\n\n /**\n * Get a value from the local storage.\n *\n * @param key - The key to get.\n * @returns The value.\n */\n get<TKey extends keyof T>(key: TKey): T[TKey] {\n return this.config.get(key)\n }\n\n /**\n * Set a value in the local storage.\n *\n * @param key - The key to set.\n * @param value - The value to set.\n */\n set<TKey extends keyof T>(key: TKey, value?: T[TKey]): void {\n this.config.set(key, value)\n }\n\n /**\n * Delete a value from the local storage.\n *\n * @param key - The key to delete.\n */\n delete<TKey extends keyof T>(key: TKey): void {\n this.config.delete(key)\n }\n\n /**\n * Clear the local storage (delete all values).\n */\n clear(): void {\n this.config.clear()\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/public/node/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,MAAM,CAAA;AAEzB;;;GAGG;AACH,8DAA8D;AAC9D,MAAM,OAAO,YAAY;IAGvB,YAAY,OAA6C;QACvD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAI,OAAO,CAAC,CAAA;IACtC,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS;QACjC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC7B,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS,EAAE,KAAe;QAClD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAuB,GAAS;QACpC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;CACF","sourcesContent":["import Config from 'conf'\n\n/**\n * A wrapper around the `conf` package that provides a strongly-typed interface\n * for accessing the local storage.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class LocalStorage<T extends {[key: string]: any}> {\n private readonly config: Config<T>\n\n constructor(options: {projectName?: string; cwd?: string}) {\n this.config = new Config<T>(options)\n }\n\n /**\n * Get a value from the local storage.\n *\n * @param key - The key to get.\n * @returns The value.\n */\n get<TKey extends keyof T>(key: TKey): T[TKey] | undefined {\n return this.config.get(key)\n }\n\n /**\n * Set a value in the local storage.\n *\n * @param key - The key to set.\n * @param value - The value to set.\n */\n set<TKey extends keyof T>(key: TKey, value?: T[TKey]): void {\n this.config.set(key, value)\n }\n\n /**\n * Delete a value from the local storage.\n *\n * @param key - The key to delete.\n */\n delete<TKey extends keyof T>(key: TKey): void {\n this.config.delete(key)\n }\n\n /**\n * Clear the local storage (delete all values).\n */\n clear(): void {\n this.config.clear()\n }\n}\n"]}
|
|
@@ -90,6 +90,7 @@ export function createRuntimeMetadataContainer(defaultPublicMetadata = {}) {
|
|
|
90
90
|
end = Math.max(start, end);
|
|
91
91
|
// The top of the stack is the total time for all nested timers
|
|
92
92
|
const wallClockDuration = Math.max(end - start, 0);
|
|
93
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
93
94
|
const childDurations = durationStack.pop();
|
|
94
95
|
const duration = Math.max(wallClockDuration - childDurations, 0);
|
|
95
96
|
// If this is the topmost timer, the stack will be empty.
|
|
@@ -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;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AI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;wBAC5B,aAAa,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,iBAAiB,CAAA;qBAC7D;oBAED,+KAA+K;oBAC/K,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,aAAa,EAAE;wBACzC,KAAK;wBACL,QAAQ;wBACR,8DAA8D;qBACxD,CAAC,CAAA;oBACT,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,OAAO,EAAE;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;iBACnE;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 const childDurations = durationStack.pop() as number\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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CAAC,CAAC,CAAA;oBAClD,oEAAoE;oBACpE,MAAM,cAAc,GAAG,aAAa,CAAC,GAAG,EAAG,CAAA;oBAC3C,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,CAAC,iBAAiB,GAAG,cAAc,EAAE,CAAC,CAAC,CAAA;oBAEhE,yDAAyD;oBACzD,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE;wBAC5B,aAAa,CAAC,aAAa,CAAC,MAAM,GAAG,CAAC,CAAC,IAAI,iBAAiB,CAAA;qBAC7D;oBAED,+KAA+K;oBAC/K,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,aAAa,EAAE;wBACzC,KAAK;wBACL,QAAQ;wBACR,8DAA8D;qBACxD,CAAC,CAAA;oBACT,WAAW,CAAC,OAAO,CAAC,GAAG,KAAK,OAAO,EAAE;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;iBACnE;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] += 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"]}
|
|
@@ -2,7 +2,7 @@ import { JsonMap } from '../../private/common/json.js';
|
|
|
2
2
|
import { DeepRequired } from '../common/ts/deep-required.js';
|
|
3
3
|
export { DeepRequired };
|
|
4
4
|
type Optional<T> = T | null;
|
|
5
|
-
export declare const MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.
|
|
5
|
+
export declare const MONORAIL_COMMAND_TOPIC = "app_cli3_command/1.15";
|
|
6
6
|
export interface Schemas {
|
|
7
7
|
[MONORAIL_COMMAND_TOPIC]: {
|
|
8
8
|
sensitive: {
|
|
@@ -40,6 +40,7 @@ export interface Schemas {
|
|
|
40
40
|
cmd_all_verbose?: Optional<boolean>;
|
|
41
41
|
cmd_all_exit?: Optional<string>;
|
|
42
42
|
cmd_all_force?: Optional<boolean>;
|
|
43
|
+
cmd_all_last_graphql_request_id?: Optional<string>;
|
|
43
44
|
cmd_all_timing_network_ms?: Optional<number>;
|
|
44
45
|
cmd_all_timing_prompts_ms?: Optional<number>;
|
|
45
46
|
cmd_all_timing_active_ms?: Optional<number>;
|
|
@@ -2,7 +2,7 @@ import { fetch } from './http.js';
|
|
|
2
2
|
import { outputDebug, outputContent, outputToken } from '../../public/node/output.js';
|
|
3
3
|
const url = 'https://monorail-edge.shopifysvc.com/v1/produce';
|
|
4
4
|
// This is the topic name of the main event we log to Monorail, the command tracker
|
|
5
|
-
export const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.
|
|
5
|
+
export const MONORAIL_COMMAND_TOPIC = 'app_cli3_command/1.15';
|
|
6
6
|
const publishedCommandNames = new Set();
|
|
7
7
|
/**
|
|
8
8
|
* Publishes an event to Monorail.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"monorail.js","sourceRoot":"","sources":["../../../src/public/node/monorail.ts"],"names":[],"m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AO,CAAC,CAAC,EAAE,CAAC,CAAA;YAC/F,OAAO,EAAC,IAAI,EAAE,IAAI,EAAC,CAAA;SACpB;aAAM;YACL,WAAW,CAAC,qCAAqC,QAAQ,CAAC,UAAU,EAAE,CAAC,CAAA;YACvE,OAAO,EAAC,IAAI,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,CAAC,UAAU,EAAC,CAAA;SACrD;QACD,qDAAqD;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.14'\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\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;AA+J7D,M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D;QACD,qDAAqD;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.15'\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"]}
|
|
@@ -116,6 +116,7 @@ export function outputContent(strings, ...keys) {
|
|
|
116
116
|
if (i >= keys.length) {
|
|
117
117
|
return;
|
|
118
118
|
}
|
|
119
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
119
120
|
const token = keys[i];
|
|
120
121
|
if (typeof token === 'string') {
|
|
121
122
|
output += token;
|
|
@@ -347,7 +348,7 @@ export function outputWhereAppropriate(logLevel, logger, message, options = { sk
|
|
|
347
348
|
else {
|
|
348
349
|
logger(message, logLevel);
|
|
349
350
|
}
|
|
350
|
-
if (!options
|
|
351
|
+
if (!options.skipUIEvent)
|
|
351
352
|
recordUIEvent({ type: 'output', properties: { content: message } });
|
|
352
353
|
}
|
|
353
354
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output.js","sourceRoot":"","sources":["../../../src/public/node/output.ts"],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AED;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,OAAe;IACzC,IAAI,mBAAmB,EAAE,EAAE;QACzB,OAAO,OAAO,CAAA;KACf;SAAM;QACL,OAAO,QAAQ,CAAC,OAAO,CAAC,CAAA;KACzB;AACH,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,QAAQ,CAAC,OAAe;IACtC,OAAO,SAAS,CAAC,OAAO,CAAC,CAAA;AAC3B,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAQ,GAAG,OAAO;IACpD,MAAM,EAAC,GAAG,EAAE,MAAM,EAAC,GAAG,QAAQ,CAAA;IAC9B,IAAI,MAAM,CAAC,cAAc,CAAC,IAAI,CAAC,GAAG,EAAE,aAAa,CAAC,EAAE;QAClD,OAAO,QAAQ,CAAC,GAAG,CAAC,WAAW,CAAC,CAAA;KACjC;SAAM;QACL,OAAO,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;KAC7B;AACH,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,aAAa,CAAC,KAAa,EAAE,IAAY;IACvD,MAAM,cAAc,GAAG,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,EAAE,CAAA;IAC/E,OAAO,aAAa,CAAA,GAAG,WAAW,CAAC,OAAO,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC,KAAK,CAAA;AAC7E,CAAC;AAED,8BAA8B","sourcesContent":["/* eslint-disable no-console */\nimport {isUnitTest, isVerbose} from './context/local.js'\nimport {PackageManager} from './node-package-manager.js'\nimport {currentProcessIsGlobal} from './is-global.js'\nimport {AbortSignal} from './abort.js'\nimport colors from './colors.js'\nimport {isTruthy} from './context/utilities.js'\nimport {TokenItem} from './ui.js'\nimport {\n ColorContentToken,\n CommandContentToken,\n ContentToken,\n ErrorContentToken,\n HeadingContentToken,\n ItalicContentToken,\n JsonContentToken,\n LinesDiffContentToken,\n LinkContentToken,\n PathContentToken,\n RawContentToken,\n SubHeadingContentToken,\n} from '../../private/node/content-tokens.js'\nimport {recordUIEvent} from '../../private/node/demo-recorder.js'\nimport {tokenItemToString} from '../../private/node/ui/components/TokenizedText.js'\nimport stripAnsi from 'strip-ansi'\nimport {Writable} from 'stream'\nimport type {Change} from 'diff'\n\nexport type Logger = Writable | ((message: string, logLevel?: LogLevel) => void)\n\nexport class TokenizedString {\n value: string\n constructor(value: string) {\n this.value = value\n }\n}\n\nexport type OutputMessage = string | TokenizedString\n\nexport const outputToken = {\n raw(value: string): RawContentToken {\n return new RawContentToken(value)\n },\n genericShellCommand(value: OutputMessage): CommandContentToken {\n return new CommandContentToken(value)\n },\n json(value: unknown): JsonContentToken {\n return new JsonContentToken(value)\n },\n path(value: OutputMessage): PathContentToken {\n return new PathContentToken(value)\n },\n link(value: OutputMessage, link?: string, fallback?: string | undefined): LinkContentToken {\n return new LinkContentToken(value, link, fallback)\n },\n heading(value: OutputMessage): HeadingContentToken {\n return new HeadingContentToken(value)\n },\n subheading(value: OutputMessage): SubHeadingContentToken {\n return new SubHeadingContentToken(value)\n },\n italic(value: OutputMessage): ItalicContentToken {\n return new ItalicContentToken(value)\n },\n errorText(value: OutputMessage): ErrorContentToken {\n return new ErrorContentToken(value)\n },\n cyan(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.cyan)\n },\n yellow(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.yellow)\n },\n magenta(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.magenta)\n },\n green(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.green)\n },\n gray(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.gray)\n },\n packagejsonScript(packageManager: PackageManager, scriptName: string, ...scriptArgs: string[]): CommandContentToken {\n return new CommandContentToken(formatPackageManagerCommand(packageManager, scriptName, ...scriptArgs))\n },\n successIcon(): ColorContentToken {\n return new ColorContentToken('✔', colors.green)\n },\n failIcon(): ErrorContentToken {\n return new ErrorContentToken('✖')\n },\n linesDiff(value: Change[]): LinesDiffContentToken {\n return new LinesDiffContentToken(value)\n },\n}\n\n/**\n * Given a command and its arguments, it formats it depending on the package manager.\n *\n * @param packageManager - The package manager to use (pnpm, npm, yarn).\n * @param scriptName - The name of the script to run.\n * @param scriptArgs - The arguments to pass to the script.\n * @returns The formatted command.\n */\nexport function formatPackageManagerCommand(\n packageManager: PackageManager,\n scriptName: string,\n ...scriptArgs: string[]\n): string {\n if (currentProcessIsGlobal()) {\n return [scriptName, ...scriptArgs].join(' ')\n }\n switch (packageManager) {\n case 'pnpm':\n case 'bun':\n case 'yarn': {\n const pieces = [packageManager, scriptName, ...scriptArgs]\n return pieces.join(' ')\n }\n case 'npm': {\n const pieces = ['npm', 'run', scriptName]\n if (scriptArgs.length > 0) {\n pieces.push('--')\n pieces.push(...scriptArgs)\n }\n return pieces.join(' ')\n }\n case 'unknown': {\n const pieces = [scriptName, ...scriptArgs]\n return pieces.join(' ')\n }\n }\n}\n\n/**\n * Creates a tokenized string from an array of strings and tokens.\n *\n * @param strings - The strings to join.\n * @param keys - Array of tokens or strings to join.\n * @returns The tokenized string.\n */\nexport function outputContent(\n strings: TemplateStringsArray,\n ...keys: (ContentToken<unknown> | string)[]\n): TokenizedString {\n let output = ``\n strings.forEach((string, i) => {\n output += string\n if (i >= keys.length) {\n return\n }\n const token = keys[i]!\n\n if (typeof token === 'string') {\n output += token\n } else if (token) {\n const enumTokenOutput = token.output()\n\n if (Array.isArray(enumTokenOutput)) {\n enumTokenOutput.forEach((line: string) => {\n output += line\n })\n } else {\n output += enumTokenOutput\n }\n }\n })\n return new TokenizedString(output)\n}\n\n/** Log levels. */\nexport type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'\n\n/**\n * It maps a level to a numeric value.\n *\n * @param level - The level for which we'll return its numeric value.\n * @returns The numeric value of the level.\n */\nfunction logLevelValue(level: LogLevel): number {\n switch (level) {\n case 'trace':\n return 10\n case 'debug':\n return 20\n case 'info':\n return 30\n case 'warn':\n return 40\n case 'error':\n return 50\n case 'fatal':\n return 60\n default:\n return 30\n }\n}\n\n/**\n * It returns the current log level (debug or info).\n *\n * @returns The log level set by the user.\n */\nfunction currentLogLevel(): LogLevel {\n if (isVerbose()) {\n return 'debug'\n } else {\n return 'info'\n }\n}\n\n/**\n * It checks if the message should be outputted or not.\n *\n * @param logLevel - The desired log level for the message.\n * @returns True if the message should be outputted, false otherwise.\n */\nfunction shouldOutput(logLevel: LogLevel): boolean {\n if (isUnitTest()) {\n return false\n }\n const currentLogLevelValue = logLevelValue(currentLogLevel())\n const messageLogLevelValue = logLevelValue(logLevel)\n return messageLogLevelValue >= currentLogLevelValue\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let collectedLogs: {[key: string]: string[]} = {}\n\n/**\n * This is only used during UnitTesting.\n * If we are in a testing context, instead of printing the logs to the console,\n * we will store them in a variable that can be accessed from the tests.\n *\n * @param key - The key of the log.\n * @param content - The content of the log.\n */\nexport function collectLog(key: string, content: OutputMessage): void {\n const output = collectedLogs.output ?? []\n const data = collectedLogs[key] ?? []\n data.push(stripAnsi(stringifyMessage(content) ?? ''))\n output.push(stripAnsi(stringifyMessage(content) ?? ''))\n collectedLogs[key] = data\n collectedLogs.output = output\n}\n\nexport const clearCollectedLogs = (): void => {\n // console.log('clearCollectLogs')\n collectedLogs = {}\n // console.log(collectedLogs)\n}\n\n/**\n * Ouputs information to the user.\n * Info messages don't get additional formatting.\n * Note: Info messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputInfo(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = stringifyMessage(content)\n if (isUnitTest()) collectLog('info', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Outputs a success message to the user.\n * Success messages receive a special formatting to make them stand out in the console.\n * Note: Success messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputSuccess(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = colors.bold(`✅ Success! ${stringifyMessage(content)}.`)\n if (isUnitTest()) collectLog('success', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Outputs a completed message to the user.\n * Completed message receive a special formatting to make them stand out in the console.\n * Note: Completed messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputCompleted(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = `${colors.green('✔')} ${stringifyMessage(content)}`\n if (isUnitTest()) collectLog('completed', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Ouputs debug information to the user. By default these output is hidden unless the user calls the CLI with --verbose.\n * Debug messages don't get additional formatting.\n * Note: Debug messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputDebug(content: OutputMessage, logger: Logger = consoleLog): void {\n if (isUnitTest()) collectLog('debug', content)\n const message = colors.gray(stringifyMessage(content))\n outputWhereAppropriate('debug', logger, `${new Date().toISOString()}: ${message}`)\n}\n\n/**\n * Outputs a warning message to the user.\n * Warning messages receive a special formatting to make them stand out in the console.\n * Note: Warning messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputWarn(content: OutputMessage, logger: Logger = consoleWarn): void {\n if (isUnitTest()) collectLog('warn', content)\n const message = colors.yellow(stringifyMessage(content))\n outputWhereAppropriate('warn', logger, message)\n}\n\n/**\n * Prints a new line in the terminal.\n */\nexport function outputNewline(): void {\n console.log()\n}\n\n/**\n * Converts a Message to string.\n *\n * @param message - The message to convert to string.\n * @returns The string representation of the message.\n */\nexport function stringifyMessage(message: OutputMessage): string {\n if (message instanceof TokenizedString) {\n return message.value\n } else {\n return message\n }\n}\n\n/**\n * Convert a TokenItem to string.\n *\n * @param item - The item to convert to string.\n * @returns The string representation of the item.\n */\nexport function itemToString(item: TokenItem): string {\n return tokenItemToString(item)\n}\n\nexport interface OutputProcess {\n /**\n * The prefix to include in the logs\n * [vite] Output coming from Vite.\n */\n prefix: string\n /**\n * A callback to invoke the process. Stdout and stderr should be used\n * to send standard output and error data that gets formatted with the\n * right prefix.\n */\n action: (stdout: Writable, stderr: Writable, signal: AbortSignal) => Promise<void>\n}\n\n/**\n * Prints a log message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleLog(message: string): void {\n console.log(withOrWithoutStyle(message))\n}\n\n/**\n * Prints an error message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleError(message: string): void {\n console.error(withOrWithoutStyle(message))\n}\n\n/**\n * Prints a warning message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleWarn(message: string): void {\n console.warn(withOrWithoutStyle(message))\n}\n\ninterface OutputWhereAppropriateOptions {\n skipUIEvent?: boolean\n}\n\n/**\n * Writes a message to the appropiated logger.\n *\n * @param logLevel - The log level to use to determine if the message should be output.\n * @param logger - The logger to use to output the message.\n * @param message - The message to output.\n * @param options - Additional options.\n */\nexport function outputWhereAppropriate(\n logLevel: LogLevel,\n logger: Logger,\n message: string,\n options: OutputWhereAppropriateOptions = {skipUIEvent: false},\n): void {\n if (shouldOutput(logLevel)) {\n if (logger instanceof Writable) {\n logger.write(message)\n } else {\n logger(message, logLevel)\n }\n if (!options?.skipUIEvent) recordUIEvent({type: 'output', properties: {content: message}})\n }\n}\n\n/**\n * Returns a colored or uncolored version of a message, depending on the environment.\n *\n * @param message - The message to color or not.\n * @returns The message with or without colors.\n */\nfunction withOrWithoutStyle(message: string): string {\n if (shouldDisplayColors()) {\n return message\n } else {\n return unstyled(message)\n }\n}\n\n/**\n * Returns a message without styles (colors or any ANSI escape codes).\n *\n * @param message - The message to remove styles from.\n * @returns The message without styles.\n */\nexport function unstyled(message: string): string {\n return stripAnsi(message)\n}\n\n/**\n * Checks if the console outputs should display colors or not.\n *\n * @param _process - Optional, the process-like object to use to check if the console should display colors. Defaults to the global process.\n * @returns True if the console outputs should display colors, false otherwise.\n */\nexport function shouldDisplayColors(_process = process): boolean {\n const {env, stdout} = _process\n if (Object.hasOwnProperty.call(env, 'FORCE_COLOR')) {\n return isTruthy(env.FORCE_COLOR)\n } else {\n return Boolean(stdout.isTTY)\n }\n}\n\n/**\n * Parse title and body to be a single formatted string.\n *\n * @param title - The title of the message. Will be formatted as a heading.\n * @param body - The body of the message. Will respect the original formatting.\n * @returns The formatted message.\n */\nexport function formatSection(title: string, body: string): string {\n const formattedTitle = `${title.toUpperCase()}${' '.repeat(35 - title.length)}`\n return outputContent`${outputToken.heading(formattedTitle)}\\n${body}`.value\n}\n\n/* eslint-enable no-console */\n"]}
|
|
1
|
+
{"version":3,"file":"output.js","sourceRoot":"","sources":["../../../src/public/node/output.ts"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,OAAO,EAAC,UAAU,EAAE,SAAS,EAAC,MAAM,oBAAoB,CAAA;AAExD,OAAO,EAAC,sBAAsB,EAAC,MAAM,gBAAgB,CAAA;AAErD,OAAO,MAAM,MAAM,aAAa,CAAA;AAChC,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAE/C,OAAO,EACL,iBAAiB,EACjB,mBAAmB,EAEnB,iBAAiB,EACjB,mBAAmB,EACnB,kBAAkB,EAClB,gBAAgB,EAChB,qBAAqB,EACrB,gBAAgB,EAChB,gBAAgB,EAChB,eAAe,EACf,sBAAsB,GACvB,MAAM,sCAAsC,CAAA;AAC7C,OAAO,EAAC,aAAa,EAAC,MAAM,qCAAqC,CAAA;AACjE,OAAO,EAAC,iBAAiB,EAAC,MAAM,mDAAmD,CAAA;AACnF,OAAO,SAAS,MAAM,YAAY,CAAA;AAClC,OAAO,EAAC,QAAQ,EAAC,MAAM,QAAQ,CAAA;AAK/B,MAAM,OAAO,eAAe;IAE1B,YAAY,KAAa;QACvB,IAAI,CAAC,KAAK,GAAG,KAAK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AAY;IACvD,MAAM,cAAc,GAAG,GAAG,KAAK,CAAC,WAAW,EAAE,GAAG,GAAG,CAAC,MAAM,CAAC,EAAE,GAAG,KAAK,CAAC,MAAM,CAAC,EAAE,CAAA;IAC/E,OAAO,aAAa,CAAA,GAAG,WAAW,CAAC,OAAO,CAAC,cAAc,CAAC,KAAK,IAAI,EAAE,CAAC,KAAK,CAAA;AAC7E,CAAC;AAED,8BAA8B","sourcesContent":["/* eslint-disable no-console */\nimport {isUnitTest, isVerbose} from './context/local.js'\nimport {PackageManager} from './node-package-manager.js'\nimport {currentProcessIsGlobal} from './is-global.js'\nimport {AbortSignal} from './abort.js'\nimport colors from './colors.js'\nimport {isTruthy} from './context/utilities.js'\nimport {TokenItem} from './ui.js'\nimport {\n ColorContentToken,\n CommandContentToken,\n ContentToken,\n ErrorContentToken,\n HeadingContentToken,\n ItalicContentToken,\n JsonContentToken,\n LinesDiffContentToken,\n LinkContentToken,\n PathContentToken,\n RawContentToken,\n SubHeadingContentToken,\n} from '../../private/node/content-tokens.js'\nimport {recordUIEvent} from '../../private/node/demo-recorder.js'\nimport {tokenItemToString} from '../../private/node/ui/components/TokenizedText.js'\nimport stripAnsi from 'strip-ansi'\nimport {Writable} from 'stream'\nimport type {Change} from 'diff'\n\nexport type Logger = Writable | ((message: string, logLevel?: LogLevel) => void)\n\nexport class TokenizedString {\n value: string\n constructor(value: string) {\n this.value = value\n }\n}\n\nexport type OutputMessage = string | TokenizedString\n\nexport const outputToken = {\n raw(value: string): RawContentToken {\n return new RawContentToken(value)\n },\n genericShellCommand(value: OutputMessage): CommandContentToken {\n return new CommandContentToken(value)\n },\n json(value: unknown): JsonContentToken {\n return new JsonContentToken(value)\n },\n path(value: OutputMessage): PathContentToken {\n return new PathContentToken(value)\n },\n link(value: OutputMessage, link?: string, fallback?: string | undefined): LinkContentToken {\n return new LinkContentToken(value, link, fallback)\n },\n heading(value: OutputMessage): HeadingContentToken {\n return new HeadingContentToken(value)\n },\n subheading(value: OutputMessage): SubHeadingContentToken {\n return new SubHeadingContentToken(value)\n },\n italic(value: OutputMessage): ItalicContentToken {\n return new ItalicContentToken(value)\n },\n errorText(value: OutputMessage): ErrorContentToken {\n return new ErrorContentToken(value)\n },\n cyan(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.cyan)\n },\n yellow(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.yellow)\n },\n magenta(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.magenta)\n },\n green(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.green)\n },\n gray(value: OutputMessage): ColorContentToken {\n return new ColorContentToken(value, colors.gray)\n },\n packagejsonScript(packageManager: PackageManager, scriptName: string, ...scriptArgs: string[]): CommandContentToken {\n return new CommandContentToken(formatPackageManagerCommand(packageManager, scriptName, ...scriptArgs))\n },\n successIcon(): ColorContentToken {\n return new ColorContentToken('✔', colors.green)\n },\n failIcon(): ErrorContentToken {\n return new ErrorContentToken('✖')\n },\n linesDiff(value: Change[]): LinesDiffContentToken {\n return new LinesDiffContentToken(value)\n },\n}\n\n/**\n * Given a command and its arguments, it formats it depending on the package manager.\n *\n * @param packageManager - The package manager to use (pnpm, npm, yarn).\n * @param scriptName - The name of the script to run.\n * @param scriptArgs - The arguments to pass to the script.\n * @returns The formatted command.\n */\nexport function formatPackageManagerCommand(\n packageManager: PackageManager,\n scriptName: string,\n ...scriptArgs: string[]\n): string {\n if (currentProcessIsGlobal()) {\n return [scriptName, ...scriptArgs].join(' ')\n }\n switch (packageManager) {\n case 'pnpm':\n case 'bun':\n case 'yarn': {\n const pieces = [packageManager, scriptName, ...scriptArgs]\n return pieces.join(' ')\n }\n case 'npm': {\n const pieces = ['npm', 'run', scriptName]\n if (scriptArgs.length > 0) {\n pieces.push('--')\n pieces.push(...scriptArgs)\n }\n return pieces.join(' ')\n }\n case 'unknown': {\n const pieces = [scriptName, ...scriptArgs]\n return pieces.join(' ')\n }\n }\n}\n\n/**\n * Creates a tokenized string from an array of strings and tokens.\n *\n * @param strings - The strings to join.\n * @param keys - Array of tokens or strings to join.\n * @returns The tokenized string.\n */\nexport function outputContent(\n strings: TemplateStringsArray,\n ...keys: (ContentToken<unknown> | string)[]\n): TokenizedString {\n let output = ``\n strings.forEach((string, i) => {\n output += string\n if (i >= keys.length) {\n return\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const token = keys[i]!\n\n if (typeof token === 'string') {\n output += token\n } else if (token) {\n const enumTokenOutput = token.output()\n\n if (Array.isArray(enumTokenOutput)) {\n enumTokenOutput.forEach((line: string) => {\n output += line\n })\n } else {\n output += enumTokenOutput\n }\n }\n })\n return new TokenizedString(output)\n}\n\n/** Log levels. */\nexport type LogLevel = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace' | 'silent'\n\n/**\n * It maps a level to a numeric value.\n *\n * @param level - The level for which we'll return its numeric value.\n * @returns The numeric value of the level.\n */\nfunction logLevelValue(level: LogLevel): number {\n switch (level) {\n case 'trace':\n return 10\n case 'debug':\n return 20\n case 'info':\n return 30\n case 'warn':\n return 40\n case 'error':\n return 50\n case 'fatal':\n return 60\n default:\n return 30\n }\n}\n\n/**\n * It returns the current log level (debug or info).\n *\n * @returns The log level set by the user.\n */\nfunction currentLogLevel(): LogLevel {\n if (isVerbose()) {\n return 'debug'\n } else {\n return 'info'\n }\n}\n\n/**\n * It checks if the message should be outputted or not.\n *\n * @param logLevel - The desired log level for the message.\n * @returns True if the message should be outputted, false otherwise.\n */\nfunction shouldOutput(logLevel: LogLevel): boolean {\n if (isUnitTest()) {\n return false\n }\n const currentLogLevelValue = logLevelValue(currentLogLevel())\n const messageLogLevelValue = logLevelValue(logLevel)\n return messageLogLevelValue >= currentLogLevelValue\n}\n\n// eslint-disable-next-line import/no-mutable-exports\nexport let collectedLogs: {[key: string]: string[]} = {}\n\n/**\n * This is only used during UnitTesting.\n * If we are in a testing context, instead of printing the logs to the console,\n * we will store them in a variable that can be accessed from the tests.\n *\n * @param key - The key of the log.\n * @param content - The content of the log.\n */\nexport function collectLog(key: string, content: OutputMessage): void {\n const output = collectedLogs.output ?? []\n const data = collectedLogs[key] ?? []\n data.push(stripAnsi(stringifyMessage(content) ?? ''))\n output.push(stripAnsi(stringifyMessage(content) ?? ''))\n collectedLogs[key] = data\n collectedLogs.output = output\n}\n\nexport const clearCollectedLogs = (): void => {\n // console.log('clearCollectLogs')\n collectedLogs = {}\n // console.log(collectedLogs)\n}\n\n/**\n * Ouputs information to the user.\n * Info messages don't get additional formatting.\n * Note: Info messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputInfo(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = stringifyMessage(content)\n if (isUnitTest()) collectLog('info', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Outputs a success message to the user.\n * Success messages receive a special formatting to make them stand out in the console.\n * Note: Success messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputSuccess(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = colors.bold(`✅ Success! ${stringifyMessage(content)}.`)\n if (isUnitTest()) collectLog('success', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Outputs a completed message to the user.\n * Completed message receive a special formatting to make them stand out in the console.\n * Note: Completed messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputCompleted(content: OutputMessage, logger: Logger = consoleLog): void {\n const message = `${colors.green('✔')} ${stringifyMessage(content)}`\n if (isUnitTest()) collectLog('completed', content)\n outputWhereAppropriate('info', logger, message)\n}\n\n/**\n * Ouputs debug information to the user. By default these output is hidden unless the user calls the CLI with --verbose.\n * Debug messages don't get additional formatting.\n * Note: Debug messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputDebug(content: OutputMessage, logger: Logger = consoleLog): void {\n if (isUnitTest()) collectLog('debug', content)\n const message = colors.gray(stringifyMessage(content))\n outputWhereAppropriate('debug', logger, `${new Date().toISOString()}: ${message}`)\n}\n\n/**\n * Outputs a warning message to the user.\n * Warning messages receive a special formatting to make them stand out in the console.\n * Note: Warning messages are sent through the standard output.\n *\n * @param content - The content to be output to the user.\n * @param logger - The logging function to use to output to the user.\n */\nexport function outputWarn(content: OutputMessage, logger: Logger = consoleWarn): void {\n if (isUnitTest()) collectLog('warn', content)\n const message = colors.yellow(stringifyMessage(content))\n outputWhereAppropriate('warn', logger, message)\n}\n\n/**\n * Prints a new line in the terminal.\n */\nexport function outputNewline(): void {\n console.log()\n}\n\n/**\n * Converts a Message to string.\n *\n * @param message - The message to convert to string.\n * @returns The string representation of the message.\n */\nexport function stringifyMessage(message: OutputMessage): string {\n if (message instanceof TokenizedString) {\n return message.value\n } else {\n return message\n }\n}\n\n/**\n * Convert a TokenItem to string.\n *\n * @param item - The item to convert to string.\n * @returns The string representation of the item.\n */\nexport function itemToString(item: TokenItem): string {\n return tokenItemToString(item)\n}\n\nexport interface OutputProcess {\n /**\n * The prefix to include in the logs\n * [vite] Output coming from Vite.\n */\n prefix: string\n /**\n * A callback to invoke the process. Stdout and stderr should be used\n * to send standard output and error data that gets formatted with the\n * right prefix.\n */\n action: (stdout: Writable, stderr: Writable, signal: AbortSignal) => Promise<void>\n}\n\n/**\n * Prints a log message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleLog(message: string): void {\n console.log(withOrWithoutStyle(message))\n}\n\n/**\n * Prints an error message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleError(message: string): void {\n console.error(withOrWithoutStyle(message))\n}\n\n/**\n * Prints a warning message in the console.\n *\n * @param message - The message to print.\n */\nexport function consoleWarn(message: string): void {\n console.warn(withOrWithoutStyle(message))\n}\n\ninterface OutputWhereAppropriateOptions {\n skipUIEvent?: boolean\n}\n\n/**\n * Writes a message to the appropiated logger.\n *\n * @param logLevel - The log level to use to determine if the message should be output.\n * @param logger - The logger to use to output the message.\n * @param message - The message to output.\n * @param options - Additional options.\n */\nexport function outputWhereAppropriate(\n logLevel: LogLevel,\n logger: Logger,\n message: string,\n options: OutputWhereAppropriateOptions = {skipUIEvent: false},\n): void {\n if (shouldOutput(logLevel)) {\n if (logger instanceof Writable) {\n logger.write(message)\n } else {\n logger(message, logLevel)\n }\n if (!options.skipUIEvent) recordUIEvent({type: 'output', properties: {content: message}})\n }\n}\n\n/**\n * Returns a colored or uncolored version of a message, depending on the environment.\n *\n * @param message - The message to color or not.\n * @returns The message with or without colors.\n */\nfunction withOrWithoutStyle(message: string): string {\n if (shouldDisplayColors()) {\n return message\n } else {\n return unstyled(message)\n }\n}\n\n/**\n * Returns a message without styles (colors or any ANSI escape codes).\n *\n * @param message - The message to remove styles from.\n * @returns The message without styles.\n */\nexport function unstyled(message: string): string {\n return stripAnsi(message)\n}\n\n/**\n * Checks if the console outputs should display colors or not.\n *\n * @param _process - Optional, the process-like object to use to check if the console should display colors. Defaults to the global process.\n * @returns True if the console outputs should display colors, false otherwise.\n */\nexport function shouldDisplayColors(_process = process): boolean {\n const {env, stdout} = _process\n if (Object.hasOwnProperty.call(env, 'FORCE_COLOR')) {\n return isTruthy(env.FORCE_COLOR)\n } else {\n return Boolean(stdout.isTTY)\n }\n}\n\n/**\n * Parse title and body to be a single formatted string.\n *\n * @param title - The title of the message. Will be formatted as a heading.\n * @param body - The body of the message. Will respect the original formatting.\n * @returns The formatted message.\n */\nexport function formatSection(title: string, body: string): string {\n const formattedTitle = `${title.toUpperCase()}${' '.repeat(35 - title.length)}`\n return outputContent`${outputToken.heading(formattedTitle)}\\n${body}`.value\n}\n\n/* eslint-enable no-console */\n"]}
|
package/dist/public/node/ruby.js
CHANGED
|
@@ -204,6 +204,7 @@ async function bundleInstallShopifyCLI() {
|
|
|
204
204
|
* @returns The absolute path to the directory.
|
|
205
205
|
*/
|
|
206
206
|
async function shopifyCLIDirectory(embedded = false) {
|
|
207
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
207
208
|
const embeddedDirectory = (await file.findPathUp('assets/cli-ruby', {
|
|
208
209
|
type: 'directory',
|
|
209
210
|
cwd: dirname(fileURLToPath(import.meta.url)),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ruby.js","sourceRoot":"","sources":["../../../src/public/node/ruby.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,eAAe,EAAC,MAAM,SAAS,CAAA;AACvC,OAAO,EAAC,aAAa,EAAE,IAAI,EAAc,MAAM,aAAa,CAAA;AAC5D,OAAO,KAAK,IAAI,MAAM,SAAS,CAAA;AAC/B,OAAO,EAAC,QAAQ,EAAE,OAAO,EAAE,GAAG,EAAC,MAAM,WAAW,CAAA;AAChD,OAAO,EAAC,UAAU,EAAE,gBAAgB,EAAC,MAAM,YAAY,CAAA;AACvD,OAAO,EAAC,uBAAuB,EAAC,MAAM,kBAAkB,CAAA;AACxD,OAAO,EAAC,iBAAiB,EAAE,QAAQ,EAAC,MAAM,mBAAmB,CAAA;AAC7D,OAAO,EAAC,aAAa,EAAE,mBAAmB,EAAC,MAAM,oBAAoB,CAAA;AACrE,OAAO,EAAC,aAAa,EAAE,WAAW,EAAC,MAAM,aAAa,CAAA;AACtD,OAAO,EAAC,QAAQ,EAAC,MAAM,wBAAwB,CAAA;AAC/C,OAAO,EAAC,YAAY,EAAC,MAAM,eAAe,CAAA;AAC1C,OAAO,EAAC,aAAa,EAAC,MAAM,iCAAiC,CAAA;AAC7D,OAAO,EAAC,eAAe,EAAC,MAAM,sBAAsB,CAAA;AACpD,OAAO,EAAC,MAAM,EAAS,MAAM,QAAQ,CAAA;AACrC,OAAO,QAAQ,MAAM,WAAW,CAAA;AAEhC,OAAO,EAAC,aAAa,EAAC,MAAM,KAAK,CAAA;AAEjC,MAAM,CAAC,MAAM,cAAc,GAAG,QAAQ,CAAA;AACtC,MAAM,iBAAiB,GAAG,QAAQ,CAAA;AAClC,MAAM,cAAc,GAA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5C;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {AbortSignal} from './abort.js'\nimport {platformAndArch} from './os.js'\nimport {captureOutput, exec, ExecOptions} from './system.js'\nimport * as file from './fs.js'\nimport {joinPath, dirname, cwd} from './path.js'\nimport {AbortError, AbortSilentError} from './error.js'\nimport {getEnvironmentVariables} from './environment.js'\nimport {isSpinEnvironment, spinFqdn} from './context/spin.js'\nimport {firstPartyDev, useEmbeddedThemeCLI} from './context/local.js'\nimport {outputContent, outputToken} from './output.js'\nimport {isTruthy} from './context/utilities.js'\nimport {runWithTimer} from './metadata.js'\nimport {pathConstants} from '../../private/node/constants.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {coerce, SemVer} from 'semver'\nimport envPaths from 'env-paths'\nimport {Writable} from 'stream'\nimport {fileURLToPath} from 'url'\n\nexport const RubyCLIVersion = '2.35.0'\nconst MinBundlerVersion = '2.3.11'\nconst MinRubyVersion = '2.7.5'\nexport const MinWdmWindowsVersion = '0.1.0'\n\ninterface ExecCLI2Options {\n // Contains store to pass to CLI 2.0 as environment variable\n store?: string\n // Contains token for admin access to pass to CLI 2.0 as environment variable\n adminToken?: string\n // Contains token for storefront access to pass to CLI 2.0 as environment variable\n storefrontToken?: string\n // Contains token for partners access to pass to CLI 2.0 as environment variable\n token?: string\n // Directory in which to execute the command. Otherwise the current directory will be used.\n directory?: string\n // A signal to stop the process execution.\n signal?: AbortSignal\n // Stream to pipe the command's stdout to.\n stdout?: Writable\n // Stream to pipe the command's stdout to.\n stderr?: Writable\n}\n/**\n * Execute CLI 2.0 commands.\n * Installs a version of RubyCLI as a vendor dependency in a hidden folder in the system.\n * User must have a valid ruby+bundler environment to run any command.\n *\n * @param args - List of argumets to execute. (ex: ['theme', 'pull']).\n * @param options - Options to customize the execution of cli2.\n */\nexport async function execCLI2(args: string[], options: ExecCLI2Options = {}): Promise<void> {\n const currentEnv = getEnvironmentVariables()\n const embedded = useEmbeddedThemeCLI(currentEnv) && !currentEnv.SHOPIFY_CLI_2_0_DIRECTORY\n\n await installCLIDependencies(options.stdout ?? process.stdout, embedded)\n const env: NodeJS.ProcessEnv = {\n ...currentEnv,\n SHOPIFY_CLI_STOREFRONT_RENDERER_AUTH_TOKEN: options.storefrontToken,\n SHOPIFY_CLI_ADMIN_AUTH_TOKEN: options.adminToken,\n SHOPIFY_SHOP: options.store,\n SHOPIFY_CLI_AUTH_TOKEN: options.token,\n SHOPIFY_CLI_RUN_AS_SUBPROCESS: 'true',\n SHOPIFY_CLI_RUBY_BIN: rubyExecutable(),\n // Bundler uses this Gemfile to understand which gems are available in the\n // environment. We use this to specify our own Gemfile for CLI2, which exists\n // outside the user's project directory.\n BUNDLE_GEMFILE: joinPath(await shopifyCLIDirectory(embedded), 'Gemfile'),\n ...(await getSpinEnvironmentVariables()),\n SHOPIFY_CLI_1P_DEV: firstPartyDev() ? '1' : '0',\n SHOPIFY_CLI_VERSION: CLI_KIT_VERSION,\n }\n\n try {\n const shopifyExecutable = embedded ? [rubyExecutable(), await embeddedCLIExecutable()] : ['shopify']\n await runBundler(['exec', ...shopifyExecutable, ...args], {\n ...(options.stdout === undefined && {stdio: 'inherit'}),\n cwd: options.directory ?? cwd(),\n env,\n ...(options.stdout !== undefined && {stdout: options.stdout, stderr: options.stderr}),\n signal: options.signal,\n })\n } catch (error) {\n // CLI2 will show it's own errors, we don't need to show an additional CLI3 error\n throw new AbortSilentError()\n }\n}\n\n/**\n * Validate Ruby Enviroment\n * Install RubyCLI and its dependencies\n * Shows a loading spinner if it's the first time installing dependencies\n * or if we are installing a new version of RubyCLI.\n *\n * @param stdout - The Writable stream on which to write the standard output.\n * @param embedded - True when embebbed codebase of CLI should be used.\n */\nasync function installCLIDependencies(stdout: Writable, embedded = false) {\n const localCLI = await shopifyCLIDirectory(embedded)\n const exists = await file.fileExists(localCLI)\n\n if (!exists) stdout.write('Installing theme dependencies...')\n const usingLocalCLI2 = embedded || isTruthy(getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY)\n await validateRubyEnv()\n if (usingLocalCLI2) {\n await bundleInstallLocalShopifyCLI(localCLI)\n } else {\n await createShopifyCLIWorkingDirectory()\n await createShopifyCLIGemfile()\n await bundleInstallShopifyCLI()\n }\n\n if (!exists) stdout.write('Installed theme dependencies!')\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Ruby and Bundler.\n */\nasync function validateRubyEnv() {\n await validateRuby()\n await validateBundler()\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Ruby.\n */\nasync function validateRuby() {\n let version: SemVer | null\n try {\n const stdout = await captureOutput(rubyExecutable(), ['-v'])\n version = coerce(stdout)\n } catch {\n throw new AbortError(\n 'Ruby environment not found',\n `Make sure you have Ruby installed on your system. ${\n outputContent`${outputToken.link('Documentation.', 'https://www.ruby-lang.org/en/documentation/installation/')}`\n .value\n }`,\n )\n }\n\n const isValid = version?.compare(MinRubyVersion)\n if (isValid === -1 || isValid === undefined) {\n throw new AbortError(\n `Ruby version ${outputContent`${outputToken.yellow(version?.raw ?? 'unknown')}`.value} is not supported`,\n `Make sure you have at least Ruby ${\n outputContent`${outputToken.yellow(MinRubyVersion)}`.value\n } installed on your system. ${\n outputContent`${outputToken.link('Documentation.', 'https://www.ruby-lang.org/en/documentation/installation/')}`\n .value\n }`,\n )\n }\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Bundler.\n */\nasync function validateBundler() {\n let version: SemVer | null\n try {\n const stdout = await captureOutput(bundleExecutable(), ['-v'], {env: {BUNDLE_USER_HOME: bundleUserHome()}})\n version = coerce(stdout)\n } catch {\n throw new AbortError(\n 'Bundler not found',\n `To install the latest version of Bundler, run ${\n outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value\n }`,\n )\n }\n\n const isValid = version?.compare(MinBundlerVersion)\n if (isValid === -1 || isValid === undefined) {\n throw new AbortError(\n `Bundler version ${outputContent`${outputToken.yellow(version?.raw ?? 'unknown')}`.value} is not supported`,\n `To update to the latest version of Bundler, run ${\n outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value\n }`,\n )\n }\n}\n\n/**\n * It creates the directory where the Ruby CLI will be downloaded along its dependencies.\n */\nasync function createShopifyCLIWorkingDirectory(): Promise<void> {\n return file.mkdir(await shopifyCLIDirectory())\n}\n\n/**\n * It creates the Gemfile to install The Ruby CLI and the dependencies.\n */\nasync function createShopifyCLIGemfile(): Promise<void> {\n const directory = await shopifyCLIDirectory()\n const gemfileContent = getBaseGemfileContent().concat(getWindowsDependencies())\n await addContentToGemfile(directory, gemfileContent)\n}\n\n/**\n * It runs bundle install for the dev-managed copy of the Ruby CLI.\n *\n * @param directory - Directory where CLI2 Gemfile is located.\n */\nasync function bundleInstallLocalShopifyCLI(directory: string): Promise<void> {\n await addContentToGemfile(directory, getWindowsDependencies())\n await shopifyBundleInstall(directory)\n}\n\n/**\n * Build the list of lines with the base content of the Gemfile.\n *\n * @returns List of lines with base content.\n */\nfunction getBaseGemfileContent() {\n return [\"source 'https://rubygems.org'\", `gem 'shopify-cli', '${RubyCLIVersion}'`]\n}\n\n/**\n * Build the list of Windows dependencies.\n *\n * @returns List of Windows dependencies.\n */\nfunction getWindowsDependencies() {\n if (platformAndArch().platform === 'windows') {\n // 'wdm' is required by 'listen', see https://github.com/Shopify/cli/issues/780\n // Because it's a Windows-only dependency, it's not included in the `.gemspec` or `Gemfile`.\n // Otherwise it would be installed in non-Windows environments too, where it is not needed.\n return [`gem 'wdm', '>= ${MinWdmWindowsVersion}'`]\n }\n return []\n}\n\n/**\n * Append contente to a Gemfile located in the given directory.\n *\n * @param gemfileDirectory - Directory where Gemfile is located.\n * @param content - Content to append to the Gemfile.\n */\nasync function addContentToGemfile(gemfileDirectory: string, content: string[]) {\n const gemfilePath = joinPath(gemfileDirectory, 'Gemfile')\n if (!(await file.fileExists(gemfilePath))) await file.touchFile(gemfilePath)\n const gemContent = await file.readFile(gemfilePath, {encoding: 'utf8'})\n const contentNoExisting = content.filter((line) => !gemContent.includes(line)).join('\\n')\n if (contentNoExisting) await file.appendFile(gemfilePath, contentNoExisting.concat('\\n'))\n}\n\n/**\n * It runs bundle install for the CLI-managed copy of the Ruby CLI.\n */\nasync function bundleInstallShopifyCLI() {\n await shopifyBundleInstall(await shopifyCLIDirectory())\n}\n\n/**\n * It returns the directory where the Ruby CLI is located.\n *\n * @param embedded - True when embebbed codebase of CLI should be used.\n * @returns The absolute path to the directory.\n */\nasync function shopifyCLIDirectory(embedded = false): Promise<string> {\n const embeddedDirectory = (await file.findPathUp('assets/cli-ruby', {\n type: 'directory',\n cwd: dirname(fileURLToPath(import.meta.url)),\n })) as string\n const bundledDirectory = joinPath(pathConstants.directories.cache.vendor.path(), 'ruby-cli', RubyCLIVersion)\n\n return embedded ? embeddedDirectory : getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY ?? bundledDirectory\n}\n\n/**\n * It returns the Ruby version present in the envirronment.\n *\n * @returns The Ruby version, or undefined if it is not found.\n */\nexport async function version(): Promise<string | undefined> {\n const parseOutput = (version: string) => version.match(/ruby (\\d+\\.\\d+\\.\\d+)/)?.[1]\n return captureOutput(rubyExecutable(), ['-v'])\n .then(parseOutput)\n .catch(() => undefined)\n}\n\n/**\n * It returns the Ruby binary path set through the environment variable SHOPIFY_RUBY_BINDIR.\n * This is useful when the CLI is managed by an installer like a Homebrew where we need to\n * point the CLI to the Ruby installation managed by Homebrew.\n *\n * @returns The value of the environment variable.\n */\nfunction getRubyBinDir(): string | undefined {\n return getEnvironmentVariables().SHOPIFY_RUBY_BINDIR\n}\n\n/**\n * It returns the path to the \"ruby\" executable.\n *\n * @returns The path to the executable.\n */\nfunction rubyExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'ruby') : 'ruby'\n}\n\n/**\n * It returns the path to the \"bundle\" executable.\n *\n * @returns The path to the executable.\n */\nfunction bundleExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'bundle') : 'bundle'\n}\n\n/**\n * It returns the path to the \"gem\"\" executable.\n *\n * @returns The path to the executable.\n */\nfunction gemExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'gem') : 'gem'\n}\n\n/**\n * It returns the path to the \"bundle\" executable.\n *\n * @returns The path to the executable.\n */\nasync function embeddedCLIExecutable(): Promise<string> {\n const cliDirectory = await shopifyCLIDirectory(true)\n return joinPath(cliDirectory, 'bin', 'shopify')\n}\n\n/**\n * Get environment variables required by the CLI2 in case the CLI3 is running in a Spin environment.\n *\n * @returns The environment variables to set.\n */\nasync function getSpinEnvironmentVariables() {\n if (!isSpinEnvironment()) return {}\n\n return {\n SPIN_FQDN: await spinFqdn(),\n SPIN: '1',\n }\n}\n\n/**\n * It sets bundler's path to a directory dedicated to shopify gems and runs bundle install.\n * This is desirable because these gems will be isolated from the system gems.\n *\n * @param directory - Directory where the Gemfile is located.\n */\nasync function shopifyBundleInstall(directory: string): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n await runBundler(['install'], {cwd: directory})\n })\n}\n\n/**\n * It returns a custom BUNDLE_USER_HOME. This is required in Windows because\n * bundler will instead crash if the username contains UTF-8 characters.\n *\n * @returns The value of the environment variable.\n */\nexport function bundleUserHome(): string | undefined {\n if (platformAndArch().platform === 'windows' && process.env.PUBLIC) {\n return joinPath(process.env.PUBLIC, 'AppData', 'Local', 'shopify-bundler-nodejs', 'Cache')\n } else {\n return undefined\n }\n}\n\n/**\n * It runs bundler commands by setting the correct BUNDLE_USER_HOME env var.\n *\n * @param args - Arguments to pass to the bundle command.\n * @param options - Options to pass to the exec function.\n */\nasync function runBundler(args: string[], options: ExecOptions) {\n return exec(bundleExecutable(), args, {\n ...options,\n env: {\n ...options.env,\n BUNDLE_USER_HOME: bundleUserHome(),\n BUNDLE_WITHOUT: 'development:test',\n BUNDLE_PATH: envPaths('shopify-gems').cache,\n },\n })\n}\n"]}
|
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K,EAAE,SAAS,CAAC,CAAA;AACjD,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,2BAA2B;IACxC,IAAI,CAAC,iBAAiB,EAAE;QAAE,OAAO,EAAE,CAAA;IAEnC,OAAO;QACL,SAAS,EAAE,MAAM,QAAQ,EAAE;QAC3B,IAAI,EAAE,GAAG;KACV,CAAA;AACH,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,oBAAoB,CAAC,SAAiB;IACnD,OAAO,YAAY,CAAC,2BAA2B,CAAC,CAAC,KAAK,IAAI,EAAE;QAC1D,MAAM,UAAU,CAAC,CAAC,SAAS,CAAC,EAAE,EAAC,GAAG,EAAE,SAAS,EAAC,CAAC,CAAA;IACjD,CAAC,CAAC,CAAA;AACJ,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,cAAc;IAC5B,IAAI,eAAe,EAAE,CAAC,QAAQ,KAAK,SAAS,IAAI,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE;QAClE,OAAO,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,wBAAwB,EAAE,OAAO,CAAC,CAAA;KAC3F;SAAM;QACL,OAAO,SAAS,CAAA;KACjB;AACH,CAAC;AAED;;;;;GAKG;AACH,KAAK,UAAU,UAAU,CAAC,IAAc,EAAE,OAAoB;IAC5D,OAAO,IAAI,CAAC,gBAAgB,EAAE,EAAE,IAAI,EAAE;QACpC,GAAG,OAAO;QACV,GAAG,EAAE;YACH,GAAG,OAAO,CAAC,GAAG;YACd,gBAAgB,EAAE,cAAc,EAAE;YAClC,cAAc,EAAE,kBAAkB;YAClC,WAAW,EAAE,QAAQ,CAAC,cAAc,CAAC,CAAC,KAAK;SAC5C;KACF,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import {AbortSignal} from './abort.js'\nimport {platformAndArch} from './os.js'\nimport {captureOutput, exec, ExecOptions} from './system.js'\nimport * as file from './fs.js'\nimport {joinPath, dirname, cwd} from './path.js'\nimport {AbortError, AbortSilentError} from './error.js'\nimport {getEnvironmentVariables} from './environment.js'\nimport {isSpinEnvironment, spinFqdn} from './context/spin.js'\nimport {firstPartyDev, useEmbeddedThemeCLI} from './context/local.js'\nimport {outputContent, outputToken} from './output.js'\nimport {isTruthy} from './context/utilities.js'\nimport {runWithTimer} from './metadata.js'\nimport {pathConstants} from '../../private/node/constants.js'\nimport {CLI_KIT_VERSION} from '../common/version.js'\nimport {coerce, SemVer} from 'semver'\nimport envPaths from 'env-paths'\nimport {Writable} from 'stream'\nimport {fileURLToPath} from 'url'\n\nexport const RubyCLIVersion = '2.35.0'\nconst MinBundlerVersion = '2.3.11'\nconst MinRubyVersion = '2.7.5'\nexport const MinWdmWindowsVersion = '0.1.0'\n\ninterface ExecCLI2Options {\n // Contains store to pass to CLI 2.0 as environment variable\n store?: string\n // Contains token for admin access to pass to CLI 2.0 as environment variable\n adminToken?: string\n // Contains token for storefront access to pass to CLI 2.0 as environment variable\n storefrontToken?: string\n // Contains token for partners access to pass to CLI 2.0 as environment variable\n token?: string\n // Directory in which to execute the command. Otherwise the current directory will be used.\n directory?: string\n // A signal to stop the process execution.\n signal?: AbortSignal\n // Stream to pipe the command's stdout to.\n stdout?: Writable\n // Stream to pipe the command's stdout to.\n stderr?: Writable\n}\n/**\n * Execute CLI 2.0 commands.\n * Installs a version of RubyCLI as a vendor dependency in a hidden folder in the system.\n * User must have a valid ruby+bundler environment to run any command.\n *\n * @param args - List of argumets to execute. (ex: ['theme', 'pull']).\n * @param options - Options to customize the execution of cli2.\n */\nexport async function execCLI2(args: string[], options: ExecCLI2Options = {}): Promise<void> {\n const currentEnv = getEnvironmentVariables()\n const embedded = useEmbeddedThemeCLI(currentEnv) && !currentEnv.SHOPIFY_CLI_2_0_DIRECTORY\n\n await installCLIDependencies(options.stdout ?? process.stdout, embedded)\n const env: NodeJS.ProcessEnv = {\n ...currentEnv,\n SHOPIFY_CLI_STOREFRONT_RENDERER_AUTH_TOKEN: options.storefrontToken,\n SHOPIFY_CLI_ADMIN_AUTH_TOKEN: options.adminToken,\n SHOPIFY_SHOP: options.store,\n SHOPIFY_CLI_AUTH_TOKEN: options.token,\n SHOPIFY_CLI_RUN_AS_SUBPROCESS: 'true',\n SHOPIFY_CLI_RUBY_BIN: rubyExecutable(),\n // Bundler uses this Gemfile to understand which gems are available in the\n // environment. We use this to specify our own Gemfile for CLI2, which exists\n // outside the user's project directory.\n BUNDLE_GEMFILE: joinPath(await shopifyCLIDirectory(embedded), 'Gemfile'),\n ...(await getSpinEnvironmentVariables()),\n SHOPIFY_CLI_1P_DEV: firstPartyDev() ? '1' : '0',\n SHOPIFY_CLI_VERSION: CLI_KIT_VERSION,\n }\n\n try {\n const shopifyExecutable = embedded ? [rubyExecutable(), await embeddedCLIExecutable()] : ['shopify']\n await runBundler(['exec', ...shopifyExecutable, ...args], {\n ...(options.stdout === undefined && {stdio: 'inherit'}),\n cwd: options.directory ?? cwd(),\n env,\n ...(options.stdout !== undefined && {stdout: options.stdout, stderr: options.stderr}),\n signal: options.signal,\n })\n } catch (error) {\n // CLI2 will show it's own errors, we don't need to show an additional CLI3 error\n throw new AbortSilentError()\n }\n}\n\n/**\n * Validate Ruby Enviroment\n * Install RubyCLI and its dependencies\n * Shows a loading spinner if it's the first time installing dependencies\n * or if we are installing a new version of RubyCLI.\n *\n * @param stdout - The Writable stream on which to write the standard output.\n * @param embedded - True when embebbed codebase of CLI should be used.\n */\nasync function installCLIDependencies(stdout: Writable, embedded = false) {\n const localCLI = await shopifyCLIDirectory(embedded)\n const exists = await file.fileExists(localCLI)\n\n if (!exists) stdout.write('Installing theme dependencies...')\n const usingLocalCLI2 = embedded || isTruthy(getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY)\n await validateRubyEnv()\n if (usingLocalCLI2) {\n await bundleInstallLocalShopifyCLI(localCLI)\n } else {\n await createShopifyCLIWorkingDirectory()\n await createShopifyCLIGemfile()\n await bundleInstallShopifyCLI()\n }\n\n if (!exists) stdout.write('Installed theme dependencies!')\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Ruby and Bundler.\n */\nasync function validateRubyEnv() {\n await validateRuby()\n await validateBundler()\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Ruby.\n */\nasync function validateRuby() {\n let version: SemVer | null\n try {\n const stdout = await captureOutput(rubyExecutable(), ['-v'])\n version = coerce(stdout)\n } catch {\n throw new AbortError(\n 'Ruby environment not found',\n `Make sure you have Ruby installed on your system. ${\n outputContent`${outputToken.link('Documentation.', 'https://www.ruby-lang.org/en/documentation/installation/')}`\n .value\n }`,\n )\n }\n\n const isValid = version?.compare(MinRubyVersion)\n if (isValid === -1 || isValid === undefined) {\n throw new AbortError(\n `Ruby version ${outputContent`${outputToken.yellow(version?.raw ?? 'unknown')}`.value} is not supported`,\n `Make sure you have at least Ruby ${\n outputContent`${outputToken.yellow(MinRubyVersion)}`.value\n } installed on your system. ${\n outputContent`${outputToken.link('Documentation.', 'https://www.ruby-lang.org/en/documentation/installation/')}`\n .value\n }`,\n )\n }\n}\n\n/**\n * A function that validates if the environment in which the CLI is running is set up with Bundler.\n */\nasync function validateBundler() {\n let version: SemVer | null\n try {\n const stdout = await captureOutput(bundleExecutable(), ['-v'], {env: {BUNDLE_USER_HOME: bundleUserHome()}})\n version = coerce(stdout)\n } catch {\n throw new AbortError(\n 'Bundler not found',\n `To install the latest version of Bundler, run ${\n outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value\n }`,\n )\n }\n\n const isValid = version?.compare(MinBundlerVersion)\n if (isValid === -1 || isValid === undefined) {\n throw new AbortError(\n `Bundler version ${outputContent`${outputToken.yellow(version?.raw ?? 'unknown')}`.value} is not supported`,\n `To update to the latest version of Bundler, run ${\n outputContent`${outputToken.genericShellCommand(`${gemExecutable()} install bundler`)}`.value\n }`,\n )\n }\n}\n\n/**\n * It creates the directory where the Ruby CLI will be downloaded along its dependencies.\n */\nasync function createShopifyCLIWorkingDirectory(): Promise<void> {\n return file.mkdir(await shopifyCLIDirectory())\n}\n\n/**\n * It creates the Gemfile to install The Ruby CLI and the dependencies.\n */\nasync function createShopifyCLIGemfile(): Promise<void> {\n const directory = await shopifyCLIDirectory()\n const gemfileContent = getBaseGemfileContent().concat(getWindowsDependencies())\n await addContentToGemfile(directory, gemfileContent)\n}\n\n/**\n * It runs bundle install for the dev-managed copy of the Ruby CLI.\n *\n * @param directory - Directory where CLI2 Gemfile is located.\n */\nasync function bundleInstallLocalShopifyCLI(directory: string): Promise<void> {\n await addContentToGemfile(directory, getWindowsDependencies())\n await shopifyBundleInstall(directory)\n}\n\n/**\n * Build the list of lines with the base content of the Gemfile.\n *\n * @returns List of lines with base content.\n */\nfunction getBaseGemfileContent() {\n return [\"source 'https://rubygems.org'\", `gem 'shopify-cli', '${RubyCLIVersion}'`]\n}\n\n/**\n * Build the list of Windows dependencies.\n *\n * @returns List of Windows dependencies.\n */\nfunction getWindowsDependencies() {\n if (platformAndArch().platform === 'windows') {\n // 'wdm' is required by 'listen', see https://github.com/Shopify/cli/issues/780\n // Because it's a Windows-only dependency, it's not included in the `.gemspec` or `Gemfile`.\n // Otherwise it would be installed in non-Windows environments too, where it is not needed.\n return [`gem 'wdm', '>= ${MinWdmWindowsVersion}'`]\n }\n return []\n}\n\n/**\n * Append contente to a Gemfile located in the given directory.\n *\n * @param gemfileDirectory - Directory where Gemfile is located.\n * @param content - Content to append to the Gemfile.\n */\nasync function addContentToGemfile(gemfileDirectory: string, content: string[]) {\n const gemfilePath = joinPath(gemfileDirectory, 'Gemfile')\n if (!(await file.fileExists(gemfilePath))) await file.touchFile(gemfilePath)\n const gemContent = await file.readFile(gemfilePath, {encoding: 'utf8'})\n const contentNoExisting = content.filter((line) => !gemContent.includes(line)).join('\\n')\n if (contentNoExisting) await file.appendFile(gemfilePath, contentNoExisting.concat('\\n'))\n}\n\n/**\n * It runs bundle install for the CLI-managed copy of the Ruby CLI.\n */\nasync function bundleInstallShopifyCLI() {\n await shopifyBundleInstall(await shopifyCLIDirectory())\n}\n\n/**\n * It returns the directory where the Ruby CLI is located.\n *\n * @param embedded - True when embebbed codebase of CLI should be used.\n * @returns The absolute path to the directory.\n */\nasync function shopifyCLIDirectory(embedded = false): Promise<string> {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const embeddedDirectory = (await file.findPathUp('assets/cli-ruby', {\n type: 'directory',\n cwd: dirname(fileURLToPath(import.meta.url)),\n }))!\n const bundledDirectory = joinPath(pathConstants.directories.cache.vendor.path(), 'ruby-cli', RubyCLIVersion)\n\n return embedded ? embeddedDirectory : getEnvironmentVariables().SHOPIFY_CLI_2_0_DIRECTORY ?? bundledDirectory\n}\n\n/**\n * It returns the Ruby version present in the envirronment.\n *\n * @returns The Ruby version, or undefined if it is not found.\n */\nexport async function version(): Promise<string | undefined> {\n const parseOutput = (version: string) => version.match(/ruby (\\d+\\.\\d+\\.\\d+)/)?.[1]\n return captureOutput(rubyExecutable(), ['-v'])\n .then(parseOutput)\n .catch(() => undefined)\n}\n\n/**\n * It returns the Ruby binary path set through the environment variable SHOPIFY_RUBY_BINDIR.\n * This is useful when the CLI is managed by an installer like a Homebrew where we need to\n * point the CLI to the Ruby installation managed by Homebrew.\n *\n * @returns The value of the environment variable.\n */\nfunction getRubyBinDir(): string | undefined {\n return getEnvironmentVariables().SHOPIFY_RUBY_BINDIR\n}\n\n/**\n * It returns the path to the \"ruby\" executable.\n *\n * @returns The path to the executable.\n */\nfunction rubyExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'ruby') : 'ruby'\n}\n\n/**\n * It returns the path to the \"bundle\" executable.\n *\n * @returns The path to the executable.\n */\nfunction bundleExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'bundle') : 'bundle'\n}\n\n/**\n * It returns the path to the \"gem\"\" executable.\n *\n * @returns The path to the executable.\n */\nfunction gemExecutable(): string {\n const rubyBinDir = getRubyBinDir()\n return rubyBinDir ? joinPath(rubyBinDir, 'gem') : 'gem'\n}\n\n/**\n * It returns the path to the \"bundle\" executable.\n *\n * @returns The path to the executable.\n */\nasync function embeddedCLIExecutable(): Promise<string> {\n const cliDirectory = await shopifyCLIDirectory(true)\n return joinPath(cliDirectory, 'bin', 'shopify')\n}\n\n/**\n * Get environment variables required by the CLI2 in case the CLI3 is running in a Spin environment.\n *\n * @returns The environment variables to set.\n */\nasync function getSpinEnvironmentVariables() {\n if (!isSpinEnvironment()) return {}\n\n return {\n SPIN_FQDN: await spinFqdn(),\n SPIN: '1',\n }\n}\n\n/**\n * It sets bundler's path to a directory dedicated to shopify gems and runs bundle install.\n * This is desirable because these gems will be isolated from the system gems.\n *\n * @param directory - Directory where the Gemfile is located.\n */\nasync function shopifyBundleInstall(directory: string): Promise<void> {\n return runWithTimer('cmd_all_timing_network_ms')(async () => {\n await runBundler(['install'], {cwd: directory})\n })\n}\n\n/**\n * It returns a custom BUNDLE_USER_HOME. This is required in Windows because\n * bundler will instead crash if the username contains UTF-8 characters.\n *\n * @returns The value of the environment variable.\n */\nexport function bundleUserHome(): string | undefined {\n if (platformAndArch().platform === 'windows' && process.env.PUBLIC) {\n return joinPath(process.env.PUBLIC, 'AppData', 'Local', 'shopify-bundler-nodejs', 'Cache')\n } else {\n return undefined\n }\n}\n\n/**\n * It runs bundler commands by setting the correct BUNDLE_USER_HOME env var.\n *\n * @param args - Arguments to pass to the bundle command.\n * @param options - Options to pass to the exec function.\n */\nasync function runBundler(args: string[], options: ExecOptions) {\n return exec(bundleExecutable(), args, {\n ...options,\n env: {\n ...options.env,\n BUNDLE_USER_HOME: bundleUserHome(),\n BUNDLE_WITHOUT: 'development:test',\n BUNDLE_PATH: envPaths('shopify-gems').cache,\n },\n })\n}\n"]}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
/// <reference types="node" resolution-mode="require"/>
|
|
2
|
+
import { AdminAPIScope, AppManagementAPIScope, BusinessPlatformScope, PartnersAPIScope, StorefrontRendererScope } from '../../private/node/session.js';
|
|
2
3
|
/**
|
|
3
4
|
* Session Object to access the Admin API, includes the token and the store FQDN.
|
|
4
5
|
*/
|
|
@@ -19,7 +20,7 @@ interface EnsureAuthenticatedAdditionalOptions {
|
|
|
19
20
|
* @param options - Optional extra options to use.
|
|
20
21
|
* @returns The access token for the Partners API.
|
|
21
22
|
*/
|
|
22
|
-
export declare function ensureAuthenticatedPartners(scopes?:
|
|
23
|
+
export declare function ensureAuthenticatedPartners(scopes?: PartnersAPIScope[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<{
|
|
23
24
|
token: string;
|
|
24
25
|
userId: string;
|
|
25
26
|
}>;
|
|
@@ -31,7 +32,7 @@ export declare function ensureAuthenticatedPartners(scopes?: string[], env?: Nod
|
|
|
31
32
|
* @param options - Optional extra options to use.
|
|
32
33
|
* @returns The access token for the App Management API.
|
|
33
34
|
*/
|
|
34
|
-
export declare function ensureAuthenticatedAppManagement(scopes?:
|
|
35
|
+
export declare function ensureAuthenticatedAppManagement(scopes?: AppManagementAPIScope[], env?: NodeJS.ProcessEnv, options?: EnsureAuthenticatedAdditionalOptions): Promise<{
|
|
35
36
|
token: string;
|
|
36
37
|
userId: string;
|
|
37
38
|
}>;
|
|
@@ -43,7 +44,7 @@ export declare function ensureAuthenticatedAppManagement(scopes?: string[], env?
|
|
|
43
44
|
* @param forceRefresh - Optional flag to force a refresh of the token.
|
|
44
45
|
* @returns The access token for the Storefront API.
|
|
45
46
|
*/
|
|
46
|
-
export declare function ensureAuthenticatedStorefront(scopes?:
|
|
47
|
+
export declare function ensureAuthenticatedStorefront(scopes?: StorefrontRendererScope[], password?: string | undefined, forceRefresh?: boolean): Promise<string>;
|
|
47
48
|
/**
|
|
48
49
|
* Ensure that we have a valid Admin session for the given store.
|
|
49
50
|
*
|
|
@@ -53,7 +54,7 @@ export declare function ensureAuthenticatedStorefront(scopes?: string[], passwor
|
|
|
53
54
|
* @param options - Optional extra options to use.
|
|
54
55
|
* @returns The access token for the Admin API.
|
|
55
56
|
*/
|
|
56
|
-
export declare function ensureAuthenticatedAdmin(store: string, scopes?:
|
|
57
|
+
export declare function ensureAuthenticatedAdmin(store: string, scopes?: AdminAPIScope[], forceRefresh?: boolean, options?: EnsureAuthenticatedAdditionalOptions): Promise<AdminSession>;
|
|
57
58
|
/**
|
|
58
59
|
* Ensure that we have a valid session to access the Theme API.
|
|
59
60
|
* If a password is provided, that token will be used against Theme Access API.
|
|
@@ -65,14 +66,14 @@ export declare function ensureAuthenticatedAdmin(store: string, scopes?: string[
|
|
|
65
66
|
* @param forceRefresh - Optional flag to force a refresh of the token.
|
|
66
67
|
* @returns The access token and store.
|
|
67
68
|
*/
|
|
68
|
-
export declare function ensureAuthenticatedThemes(store: string, password: string | undefined, scopes?:
|
|
69
|
+
export declare function ensureAuthenticatedThemes(store: string, password: string | undefined, scopes?: AdminAPIScope[], forceRefresh?: boolean): Promise<AdminSession>;
|
|
69
70
|
/**
|
|
70
71
|
* Ensure that we have a valid session to access the Business Platform API.
|
|
71
72
|
*
|
|
72
73
|
* @param scopes - Optional array of extra scopes to authenticate with.
|
|
73
74
|
* @returns The access token for the Business Platform API.
|
|
74
75
|
*/
|
|
75
|
-
export declare function ensureAuthenticatedBusinessPlatform(scopes?:
|
|
76
|
+
export declare function ensureAuthenticatedBusinessPlatform(scopes?: BusinessPlatformScope[]): Promise<string>;
|
|
76
77
|
/**
|
|
77
78
|
* Logout from Shopify.
|
|
78
79
|
*
|
|
@@ -5,7 +5,7 @@ import { nonRandomUUID } from './crypto.js';
|
|
|
5
5
|
import * as secureStore from '../../private/node/session/store.js';
|
|
6
6
|
import { exchangeCustomPartnerToken } from '../../private/node/session/exchange.js';
|
|
7
7
|
import { outputContent, outputToken, outputDebug } from '../../public/node/output.js';
|
|
8
|
-
import { ensureAuthenticated, setLastSeenAuthMethod, setLastSeenUserIdAfterAuth } from '../../private/node/session.js';
|
|
8
|
+
import { ensureAuthenticated, setLastSeenAuthMethod, setLastSeenUserIdAfterAuth, } from '../../private/node/session.js';
|
|
9
9
|
import { isThemeAccessSession } from '../../private/node/api/rest.js';
|
|
10
10
|
/**
|
|
11
11
|
* Ensure that we have a valid session to access the Partners API.
|
|
@@ -48,6 +48,7 @@ ${outputToken.json(scopes)}
|
|
|
48
48
|
if (!tokens) {
|
|
49
49
|
throw new BugError('No App Management token found after ensuring authenticated');
|
|
50
50
|
}
|
|
51
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
51
52
|
return { token: tokens.appManagement, userId: tokens.userId };
|
|
52
53
|
}
|
|
53
54
|
/**
|