@slicemachine/manager 0.25.2-alpha.xru-fix-sm-invalid-env.5 → 0.25.2-alpha.xru-fix-sm-invalid-env.6

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.
@@ -264,7 +264,7 @@ Error Message: ${error2.message}`);
264
264
  const { environment: activeEnvironmentDomain } = await this.readEnvironment();
265
265
  const cachedActiveEnvironment = findEnvironment.findEnvironment(activeEnvironmentDomain, this._cachedEnvironments || []);
266
266
  if (cachedActiveEnvironment) {
267
- return { type: "ok", environment: cachedActiveEnvironment };
267
+ return { type: "ok", activeEnvironment: cachedActiveEnvironment };
268
268
  }
269
269
  const { environments } = await this.prismicRepository.fetchEnvironments();
270
270
  if (environments) {
@@ -277,7 +277,7 @@ Error Message: ${error2.message}`);
277
277
  error: new errors.InvalidActiveEnvironmentError()
278
278
  };
279
279
  }
280
- return { type: "ok", environment: activeEnvironment };
280
+ return { type: "ok", activeEnvironment };
281
281
  }
282
282
  async detectVersionControlSystem() {
283
283
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"ProjectManager.cjs","sources":["../../../../src/managers/project/ProjectManager.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { detect as niDetect } from \"@antfu/ni\";\nimport { ExecaChildProcess } from \"execa\";\nimport {\n\tHookError,\n\tCallHookReturnType,\n\tProjectEnvironmentUpdateHook,\n} from \"@slicemachine/plugin-kit\";\nimport * as t from \"io-ts\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport { decodeSliceMachineConfig } from \"../../lib/decodeSliceMachineConfig\";\nimport { findEnvironment } from \"../../lib/findEnvironment\";\nimport { format } from \"../../lib/format\";\nimport { installDependencies } from \"../../lib/installDependencies\";\nimport { locateFileUpward } from \"../../lib/locateFileUpward\";\nimport { requireResolve } from \"../../lib/requireResolve\";\n\nimport {\n\tPackageManager,\n\tSliceMachineConfig,\n\tOnlyHookErrors,\n} from \"../../types\";\n\nimport {\n\tSliceMachineError,\n\tInternalError,\n\tPluginError,\n\tInvalidActiveEnvironmentError,\n} from \"../../errors\";\n\nimport { SLICE_MACHINE_CONFIG_FILENAME } from \"../../constants/SLICE_MACHINE_CONFIG_FILENAME\";\nimport { TS_CONFIG_FILENAME } from \"../../constants/TS_CONFIG_FILENAME\";\nimport { SLICE_MACHINE_NPM_PACKAGE_NAME } from \"../../constants/SLICE_MACHINE_NPM_PACKAGE_NAME\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype ProjectManagerGetSliceMachineConfigPathArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerGetRootArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerCheckIsTypeScriptArgs = {\n\trootOverride?: string;\n};\n\ntype ProjectManagerWriteSliceMachineConfigArgs = {\n\tconfig: SliceMachineConfig;\n\tpath?: string;\n};\n\ntype ProjectManagerInitProjectArgs = {\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerDetectPackageManager = {\n\troot?: string;\n};\n\ntype ProjectManagerInstallDependenciesArgs = {\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\tpackageManager?: PackageManager;\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerInstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\ntype ProjectManagerReadEnvironmentReturnType = {\n\tenvironment: string | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype ProjectManagerUpdateEnvironmentArgs = {\n\tenvironment: string | undefined;\n};\n\ntype ProjectManagerFetchActiveEnvironmentReturnType =\n\t| { type: \"ok\"; environment: Environment }\n\t| { type: \"error\"; error: InvalidActiveEnvironmentError };\n\nexport class ProjectManager extends BaseManager {\n\tprivate _cachedRoot: string | undefined;\n\tprivate _cachedSliceMachineConfigPath: string | undefined;\n\tprivate _cachedSliceMachineConfig: SliceMachineConfig | undefined;\n\tprivate _cachedEnvironments: Environment[] | undefined;\n\n\tasync getSliceMachineConfigPath(\n\t\targs?: ProjectManagerGetSliceMachineConfigPathArgs,\n\t): Promise<string> {\n\t\tif (this._cachedSliceMachineConfigPath && !args?.ignoreCache) {\n\t\t\treturn this._cachedSliceMachineConfigPath;\n\t\t}\n\n\t\ttry {\n\t\t\tthis._cachedSliceMachineConfigPath = await locateFileUpward(\n\t\t\t\tSLICE_MACHINE_CONFIG_FILENAME,\n\t\t\t\t{ startDir: this.cwd },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not find a ${SLICE_MACHINE_CONFIG_FILENAME} file. Please create a config file at the root of your project.`,\n\t\t\t);\n\t\t}\n\n\t\treturn this._cachedSliceMachineConfigPath;\n\t}\n\n\tasync getRoot(args?: ProjectManagerGetRootArgs): Promise<string> {\n\t\tif (this._cachedRoot && !args?.ignoreCache) {\n\t\t\treturn this._cachedRoot;\n\t\t}\n\n\t\tconst sliceMachineConfigFilePath = await this.getSliceMachineConfigPath({\n\t\t\tignoreCache: args?.ignoreCache,\n\t\t});\n\n\t\tthis._cachedRoot = path.dirname(sliceMachineConfigFilePath);\n\n\t\treturn this._cachedRoot;\n\t}\n\n\tasync suggestRoot(): Promise<string> {\n\t\tconst suggestedRootPackageJSON = await locateFileUpward(\"package.json\", {\n\t\t\tstartDir: this.cwd,\n\t\t});\n\n\t\treturn path.dirname(suggestedRootPackageJSON);\n\t}\n\n\tasync suggestSliceMachineConfigPath(): Promise<string> {\n\t\tconst suggestedRoot = await this.suggestRoot();\n\n\t\treturn path.resolve(suggestedRoot, SLICE_MACHINE_CONFIG_FILENAME);\n\t}\n\n\tasync checkIsTypeScript(\n\t\targs?: ProjectManagerCheckIsTypeScriptArgs,\n\t): Promise<boolean> {\n\t\tconst root = args?.rootOverride || (await this.getRoot());\n\t\tconst rootTSConfigPath = path.resolve(root, TS_CONFIG_FILENAME);\n\n\t\t// We just care if the file exists, we don't need access to it\n\t\treturn existsSync(rootTSConfigPath);\n\t}\n\n\tasync getSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\tif (this._cachedSliceMachineConfig) {\n\t\t\treturn this._cachedSliceMachineConfig;\n\t\t} else {\n\t\t\treturn await this.loadSliceMachineConfig();\n\t\t}\n\t}\n\n\tasync writeSliceMachineConfig(\n\t\targs: ProjectManagerWriteSliceMachineConfigArgs,\n\t): Promise<void> {\n\t\tconst configFilePath =\n\t\t\targs.path || (await this.getSliceMachineConfigPath());\n\n\t\tconst config = await format(\n\t\t\tJSON.stringify(args.config, null, 2),\n\t\t\tconfigFilePath,\n\t\t);\n\n\t\tawait fs.writeFile(configFilePath, config, \"utf-8\");\n\t\tdelete this._cachedSliceMachineConfig; // Clear config cache\n\t}\n\n\tasync loadSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\t// TODO: Reload plugins with a fresh plugin runner. Plugins may\n\t\t// have been added or removed.\n\t\tconst configFilePath = await this.getSliceMachineConfigPath();\n\n\t\tlet rawConfig: unknown | undefined;\n\t\ttry {\n\t\t\tconst contents = await fs.readFile(configFilePath, \"utf8\");\n\t\t\trawConfig = JSON.parse(contents);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\tthrow new SliceMachineError(\n\t\t\t\t\t`Could not parse config file at ${configFilePath}.\\n\\nError Message: ${error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Noop, more specific error is thrown after\n\t\t}\n\n\t\tif (!rawConfig) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(\"No config found.\");\n\t\t}\n\n\t\tconst { value: sliceMachineConfig, error } =\n\t\t\tdecodeSliceMachineConfig(rawConfig);\n\n\t\tif (error) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(`Invalid config. ${error.errors.join(\", \")}`, {\n\t\t\t\tcause: { rawConfig },\n\t\t\t});\n\t\t}\n\n\t\t// Allow cached config reading using `SliceMachineManager.prototype.getProjectConfig()`.\n\t\tthis._cachedSliceMachineConfig = sliceMachineConfig;\n\n\t\treturn sliceMachineConfig;\n\t}\n\n\tasync locateSliceMachineUIDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\n\t\tconst sliceMachinePackageJSONPath = requireResolve(\n\t\t\t`${SLICE_MACHINE_NPM_PACKAGE_NAME}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(sliceMachinePackageJSONPath);\n\t}\n\n\t/**\n\t * Returns the project's repository name (i.e. the production environment). It\n\t * ignores the currently selected environment.\n\t *\n\t * Use this method to retrieve the production environment domain.\n\t *\n\t * @returns The project's repository name.\n\t */\n\tasync getRepositoryName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\n\t\treturn sliceMachineConfig.repositoryName;\n\t}\n\n\t/**\n\t * Returns the currently selected environment domain if set. If an environment\n\t * is not set, it returns the project's repository name (the production\n\t * environment).\n\t *\n\t * Use this method to retrieve the repository name to be sent with Prismic API\n\t * requests.\n\t *\n\t * @returns The resolved repository name.\n\t */\n\tasync getResolvedRepositoryName(): Promise<string> {\n\t\tconst repositoryName = await this.getRepositoryName();\n\n\t\tconst supportsEnvironments = this.project.checkSupportsEnvironments();\n\t\tif (!supportsEnvironments) {\n\t\t\treturn repositoryName;\n\t\t}\n\n\t\tconst { environment } = await this.project.readEnvironment();\n\n\t\treturn environment ?? repositoryName;\n\t}\n\n\tasync getAdapterName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\t\tconst adapterName =\n\t\t\ttypeof sliceMachineConfig.adapter === \"string\"\n\t\t\t\t? sliceMachineConfig.adapter\n\t\t\t\t: sliceMachineConfig.adapter.resolve;\n\n\t\treturn adapterName;\n\t}\n\n\tasync locateAdapterDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\t\tconst adapterName = await this.getAdapterName();\n\t\tconst adapterPackageJSONPath = requireResolve(\n\t\t\t`${adapterName}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(adapterPackageJSONPath);\n\t}\n\n\tasync initProject(args?: ProjectManagerInitProjectArgs): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args?.log || console.log.bind(this);\n\n\t\tconst { errors } = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:init\",\n\t\t\t{\n\t\t\t\tlog,\n\t\t\t\tinstallDependencies: async (args) => {\n\t\t\t\t\tconst { execaProcess } = await this.installDependencies({\n\t\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t\t\tdev: args.dev,\n\t\t\t\t\t\tlog,\n\t\t\t\t\t});\n\n\t\t\t\t\tawait execaProcess;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (errors.length > 0) {\n\t\t\t// TODO: Provide better error message.\n\t\t\tthrow new SliceMachineError(\n\t\t\t\t`Failed to initialize project: ${errors.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync detectPackageManager(\n\t\targs?: ProjectManagerDetectPackageManager,\n\t): Promise<PackageManager> {\n\t\tconst projectRoot = args?.root || (await this.getRoot());\n\n\t\tconst packageManager = await niDetect({\n\t\t\tautoInstall: true,\n\t\t\tcwd: projectRoot,\n\t\t});\n\n\t\treturn packageManager || \"npm\";\n\t}\n\n\tasync installDependencies(\n\t\targs: ProjectManagerInstallDependenciesArgs,\n\t): Promise<ProjectManagerInstallDependenciesReturnType> {\n\t\tconst packageManager =\n\t\t\targs.packageManager || (await this.detectPackageManager());\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args.log || console.log.bind(this);\n\n\t\tconst wrappedLogger = (data: Buffer | string | null) => {\n\t\t\tif (data instanceof Buffer) {\n\t\t\t\tlog(data.toString());\n\t\t\t} else if (typeof data === \"string\") {\n\t\t\t\tlog(data);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tconst { execaProcess } = await installDependencies({\n\t\t\t\tpackageManager,\n\t\t\t\tdependencies: args.dependencies,\n\t\t\t\tdev: args.dev,\n\t\t\t});\n\n\t\t\t// Don't clutter console with logs when process is non TTY (CI, etc.)\n\t\t\tif (process.stdout.isTTY || process.env.NODE_ENV === \"test\") {\n\t\t\t\texecaProcess.stdout?.on(\"data\", wrappedLogger);\n\t\t\t}\n\t\t\texecaProcess.stderr?.on(\"data\", wrappedLogger);\n\n\t\t\treturn {\n\t\t\t\texecaProcess,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\t\"shortMessage\" in error &&\n\t\t\t\t\"stderr\" in error\n\t\t\t) {\n\t\t\t\tthrow new InternalError(\"Package installation failed\", {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tcheckSupportsEnvironments(): boolean {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\treturn (\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:read\")\n\t\t\t\t.length > 0 &&\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:update\")\n\t\t\t\t.length > 0\n\t\t);\n\t}\n\n\tasync readEnvironment(): Promise<ProjectManagerReadEnvironmentReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tenvironment: t.union([t.undefined, t.string]),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\t// An undefined value is equivalent to the production environment.\n\t\t// We cast to undefined.\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environmentDomain =\n\t\t\tdata[0]?.environment === repositoryName\n\t\t\t\t? undefined\n\t\t\t\t: data[0]?.environment;\n\n\t\treturn {\n\t\t\tenvironment: environmentDomain,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateEnvironment(\n\t\targs: ProjectManagerUpdateEnvironmentArgs,\n\t): Promise<OnlyHookErrors<CallHookReturnType<ProjectEnvironmentUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environment =\n\t\t\targs.environment === repositoryName ? undefined : args.environment;\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:update\",\n\t\t\t{ environment },\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchActiveEnvironment(): Promise<ProjectManagerFetchActiveEnvironmentReturnType> {\n\t\tconst { environment: activeEnvironmentDomain } =\n\t\t\tawait this.readEnvironment();\n\n\t\t// We can assume an environment cannot change its kind. If the\n\t\t// environment exists in the cached list, we are confident it\n\t\t// will not change.\n\t\tconst cachedActiveEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\t\tif (cachedActiveEnvironment) {\n\t\t\treturn { type: \"ok\", environment: cachedActiveEnvironment };\n\t\t}\n\n\t\t// If the environment is not in the cached environments list, we\n\t\t// must fetch a fresh list and set the cache.\n\t\tconst { environments } = await this.prismicRepository.fetchEnvironments();\n\t\t// TODO: Remove the wrapping if statement when\n\t\t// `this.prismicRepository.fetchEnvironments()` is able to throw\n\t\t// normally. The method returns an object with an `error`\n\t\t// property at the time of this writing, which means we need to\n\t\t// check if the `environments` property exists.\n\t\tif (environments) {\n\t\t\tthis._cachedEnvironments = environments;\n\t\t}\n\n\t\tconst activeEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\n\t\tif (!activeEnvironment) {\n\t\t\treturn {\n\t\t\t\ttype: \"error\",\n\t\t\t\terror: new InvalidActiveEnvironmentError(),\n\t\t\t};\n\t\t}\n\n\t\treturn { type: \"ok\", environment: activeEnvironment };\n\t}\n\n\tasync detectVersionControlSystem(): Promise<string | \"_unknown\"> {\n\t\ttry {\n\t\t\tconst projectRoot = await this.getRoot();\n\n\t\t\tif (existsSync(path.join(projectRoot, \".git\"))) {\n\t\t\t\treturn \"Git\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".svn\"))) {\n\t\t\t\treturn \"SVN\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".hg\"))) {\n\t\t\t\treturn \"Mercurial\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \"CVS\"))) {\n\t\t\t\treturn \"CVS\";\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Failed to detect Version Control System:\", error);\n\t\t\t}\n\t\t}\n\n\t\treturn \"_unknown\";\n\t}\n\n\tprivate async _assertAdapterSupportsEnvironments(): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst supportsEnvironments = this.checkSupportsEnvironments();\n\n\t\tif (!supportsEnvironments) {\n\t\t\tconst adapterName = await this.project.getAdapterName();\n\n\t\t\tthrow new PluginError(\n\t\t\t\t`${adapterName} does not support environments. Use an adapter that implements the \\`project:environment:read\\` and \\`project:environment:update\\` hooks to use environments.`,\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["BaseManager","locateFileUpward","SLICE_MACHINE_CONFIG_FILENAME","path","TS_CONFIG_FILENAME","existsSync","format","fs","error","SliceMachineError","decodeSliceMachineConfig","requireResolve","SLICE_MACHINE_NPM_PACKAGE_NAME","assertPluginsInitialized","errors","args","niDetect","installDependencies","InternalError","decodeHookResult","t","findEnvironment","InvalidActiveEnvironmentError","PluginError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FM,MAAO,uBAAuBA,YAAAA,YAAW;AAAA,EAAzC;AAAA;AACG;AACA;AACA;AACA;AAAA;AAAA,EAER,MAAM,0BACL,MAAkD;AAElD,QAAI,KAAK,iCAAiC,EAAC,6BAAM,cAAa;AAC7D,aAAO,KAAK;AAAA,IACb;AAEI,QAAA;AACE,WAAA,gCAAgC,MAAMC,kCAC1CC,8BAAAA,+BACA,EAAE,UAAU,KAAK,KAAK;AAAA,aAEf,OAAO;AACf,YAAM,IAAI,MACT,oBAAoBA,8BAAAA,6BAA6B,iEAAiE;AAAA,IAEpH;AAEA,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,QAAQ,MAAgC;AAC7C,QAAI,KAAK,eAAe,EAAC,6BAAM,cAAa;AAC3C,aAAO,KAAK;AAAA,IACb;AAEM,UAAA,6BAA6B,MAAM,KAAK,0BAA0B;AAAA,MACvE,aAAa,6BAAM;AAAA,IAAA,CACnB;AAEI,SAAA,cAAcC,gBAAK,QAAQ,0BAA0B;AAE1D,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,cAAW;AACV,UAAA,2BAA2B,MAAMF,iBAAA,iBAAiB,gBAAgB;AAAA,MACvE,UAAU,KAAK;AAAA,IAAA,CACf;AAEM,WAAAE,gBAAK,QAAQ,wBAAwB;AAAA,EAC7C;AAAA,EAEA,MAAM,gCAA6B;AAC5B,UAAA,gBAAgB,MAAM,KAAK;AAE1B,WAAAA,gBAAK,QAAQ,eAAeD,8BAA6B,6BAAA;AAAA,EACjE;AAAA,EAEA,MAAM,kBACL,MAA0C;AAE1C,UAAM,QAAO,6BAAM,iBAAiB,MAAM,KAAK,QAAO;AACtD,UAAM,mBAAmBC,gBAAK,QAAQ,MAAMC,mBA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,WAAK,sBAAsB;AAAA,IAC5B;AAEA,UAAM,oBAAoBA,gBAAAA,gBACzB,yBACA,KAAK,uBAAuB,CAAA,CAAE;AAG/B,QAAI,CAAC,mBAAmB;AAChB,aAAA;AAAA,QACN,MAAM;AAAA,QACN,OAAO,IAAIC,OAAAA,8BAA+B;AAAA,MAAA;AAAA,IAE5C;AAEA,WAAO,EAAE,MAAM,MAAM,aAAa,kBAAiB;AAAA,EACpD;AAAA,EAEA,MAAM,6BAA0B;AAC3B,QAAA;AACG,YAAA,cAAc,MAAM,KAAK;AAE/B,UAAIjB,QAAAA,WAAWF,gBAAK,KAAK,aAAa,MAAM,CAAC,GAAG;AACxC,eAAA;AAAA,MACR;AAEA,UAAIE,QAAAA,WAAWF,gBAAK,KAAK,aAAa,MAAM,CAAC,GAAG;AACxC,eAAA;AAAA,MACR;AAEA,UAAIE,QAAAA,WAAWF,gBAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAEA,UAAIE,QAAAA,WAAWF,gBAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAAA,aACQ,OAAO;AAAA,IAIhB;AAEO,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,qCAAkC;AAC/CU,sDAAyB,KAAK,wBAAwB;AAEhD,UAAA,uBAAuB,KAAK;AAElC,QAAI,CAAC,sBAAsB;AAC1B,YAAM,cAAc,MAAM,KAAK,QAAQ,eAAc;AAErD,YAAM,IAAIU,OAAAA,YACT,GAAG,WAAW,+JAA+J;AAAA,IAE/K;AAAA,EACD;AACA;;"}
1
+ {"version":3,"file":"ProjectManager.cjs","sources":["../../../../src/managers/project/ProjectManager.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { detect as niDetect } from \"@antfu/ni\";\nimport { ExecaChildProcess } from \"execa\";\nimport {\n\tHookError,\n\tCallHookReturnType,\n\tProjectEnvironmentUpdateHook,\n} from \"@slicemachine/plugin-kit\";\nimport * as t from \"io-ts\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport { decodeSliceMachineConfig } from \"../../lib/decodeSliceMachineConfig\";\nimport { findEnvironment } from \"../../lib/findEnvironment\";\nimport { format } from \"../../lib/format\";\nimport { installDependencies } from \"../../lib/installDependencies\";\nimport { locateFileUpward } from \"../../lib/locateFileUpward\";\nimport { requireResolve } from \"../../lib/requireResolve\";\n\nimport {\n\tPackageManager,\n\tSliceMachineConfig,\n\tOnlyHookErrors,\n} from \"../../types\";\n\nimport {\n\tSliceMachineError,\n\tInternalError,\n\tPluginError,\n\tInvalidActiveEnvironmentError,\n} from \"../../errors\";\n\nimport { SLICE_MACHINE_CONFIG_FILENAME } from \"../../constants/SLICE_MACHINE_CONFIG_FILENAME\";\nimport { TS_CONFIG_FILENAME } from \"../../constants/TS_CONFIG_FILENAME\";\nimport { SLICE_MACHINE_NPM_PACKAGE_NAME } from \"../../constants/SLICE_MACHINE_NPM_PACKAGE_NAME\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype ProjectManagerGetSliceMachineConfigPathArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerGetRootArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerCheckIsTypeScriptArgs = {\n\trootOverride?: string;\n};\n\ntype ProjectManagerWriteSliceMachineConfigArgs = {\n\tconfig: SliceMachineConfig;\n\tpath?: string;\n};\n\ntype ProjectManagerInitProjectArgs = {\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerDetectPackageManager = {\n\troot?: string;\n};\n\ntype ProjectManagerInstallDependenciesArgs = {\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\tpackageManager?: PackageManager;\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerInstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\ntype ProjectManagerReadEnvironmentReturnType = {\n\tenvironment: string | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype ProjectManagerUpdateEnvironmentArgs = {\n\tenvironment: string | undefined;\n};\n\ntype ProjectManagerFetchActiveEnvironmentReturnType =\n\t| { type: \"ok\"; activeEnvironment: Environment }\n\t| { type: \"error\"; error: InvalidActiveEnvironmentError };\n\nexport class ProjectManager extends BaseManager {\n\tprivate _cachedRoot: string | undefined;\n\tprivate _cachedSliceMachineConfigPath: string | undefined;\n\tprivate _cachedSliceMachineConfig: SliceMachineConfig | undefined;\n\tprivate _cachedEnvironments: Environment[] | undefined;\n\n\tasync getSliceMachineConfigPath(\n\t\targs?: ProjectManagerGetSliceMachineConfigPathArgs,\n\t): Promise<string> {\n\t\tif (this._cachedSliceMachineConfigPath && !args?.ignoreCache) {\n\t\t\treturn this._cachedSliceMachineConfigPath;\n\t\t}\n\n\t\ttry {\n\t\t\tthis._cachedSliceMachineConfigPath = await locateFileUpward(\n\t\t\t\tSLICE_MACHINE_CONFIG_FILENAME,\n\t\t\t\t{ startDir: this.cwd },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not find a ${SLICE_MACHINE_CONFIG_FILENAME} file. Please create a config file at the root of your project.`,\n\t\t\t);\n\t\t}\n\n\t\treturn this._cachedSliceMachineConfigPath;\n\t}\n\n\tasync getRoot(args?: ProjectManagerGetRootArgs): Promise<string> {\n\t\tif (this._cachedRoot && !args?.ignoreCache) {\n\t\t\treturn this._cachedRoot;\n\t\t}\n\n\t\tconst sliceMachineConfigFilePath = await this.getSliceMachineConfigPath({\n\t\t\tignoreCache: args?.ignoreCache,\n\t\t});\n\n\t\tthis._cachedRoot = path.dirname(sliceMachineConfigFilePath);\n\n\t\treturn this._cachedRoot;\n\t}\n\n\tasync suggestRoot(): Promise<string> {\n\t\tconst suggestedRootPackageJSON = await locateFileUpward(\"package.json\", {\n\t\t\tstartDir: this.cwd,\n\t\t});\n\n\t\treturn path.dirname(suggestedRootPackageJSON);\n\t}\n\n\tasync suggestSliceMachineConfigPath(): Promise<string> {\n\t\tconst suggestedRoot = await this.suggestRoot();\n\n\t\treturn path.resolve(suggestedRoot, SLICE_MACHINE_CONFIG_FILENAME);\n\t}\n\n\tasync checkIsTypeScript(\n\t\targs?: ProjectManagerCheckIsTypeScriptArgs,\n\t): Promise<boolean> {\n\t\tconst root = args?.rootOverride || (await this.getRoot());\n\t\tconst rootTSConfigPath = path.resolve(root, TS_CONFIG_FILENAME);\n\n\t\t// We just care if the file exists, we don't need access to it\n\t\treturn existsSync(rootTSConfigPath);\n\t}\n\n\tasync getSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\tif (this._cachedSliceMachineConfig) {\n\t\t\treturn this._cachedSliceMachineConfig;\n\t\t} else {\n\t\t\treturn await this.loadSliceMachineConfig();\n\t\t}\n\t}\n\n\tasync writeSliceMachineConfig(\n\t\targs: ProjectManagerWriteSliceMachineConfigArgs,\n\t): Promise<void> {\n\t\tconst configFilePath =\n\t\t\targs.path || (await this.getSliceMachineConfigPath());\n\n\t\tconst config = await format(\n\t\t\tJSON.stringify(args.config, null, 2),\n\t\t\tconfigFilePath,\n\t\t);\n\n\t\tawait fs.writeFile(configFilePath, config, \"utf-8\");\n\t\tdelete this._cachedSliceMachineConfig; // Clear config cache\n\t}\n\n\tasync loadSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\t// TODO: Reload plugins with a fresh plugin runner. Plugins may\n\t\t// have been added or removed.\n\t\tconst configFilePath = await this.getSliceMachineConfigPath();\n\n\t\tlet rawConfig: unknown | undefined;\n\t\ttry {\n\t\t\tconst contents = await fs.readFile(configFilePath, \"utf8\");\n\t\t\trawConfig = JSON.parse(contents);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\tthrow new SliceMachineError(\n\t\t\t\t\t`Could not parse config file at ${configFilePath}.\\n\\nError Message: ${error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Noop, more specific error is thrown after\n\t\t}\n\n\t\tif (!rawConfig) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(\"No config found.\");\n\t\t}\n\n\t\tconst { value: sliceMachineConfig, error } =\n\t\t\tdecodeSliceMachineConfig(rawConfig);\n\n\t\tif (error) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(`Invalid config. ${error.errors.join(\", \")}`, {\n\t\t\t\tcause: { rawConfig },\n\t\t\t});\n\t\t}\n\n\t\t// Allow cached config reading using `SliceMachineManager.prototype.getProjectConfig()`.\n\t\tthis._cachedSliceMachineConfig = sliceMachineConfig;\n\n\t\treturn sliceMachineConfig;\n\t}\n\n\tasync locateSliceMachineUIDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\n\t\tconst sliceMachinePackageJSONPath = requireResolve(\n\t\t\t`${SLICE_MACHINE_NPM_PACKAGE_NAME}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(sliceMachinePackageJSONPath);\n\t}\n\n\t/**\n\t * Returns the project's repository name (i.e. the production environment). It\n\t * ignores the currently selected environment.\n\t *\n\t * Use this method to retrieve the production environment domain.\n\t *\n\t * @returns The project's repository name.\n\t */\n\tasync getRepositoryName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\n\t\treturn sliceMachineConfig.repositoryName;\n\t}\n\n\t/**\n\t * Returns the currently selected environment domain if set. If an environment\n\t * is not set, it returns the project's repository name (the production\n\t * environment).\n\t *\n\t * Use this method to retrieve the repository name to be sent with Prismic API\n\t * requests.\n\t *\n\t * @returns The resolved repository name.\n\t */\n\tasync getResolvedRepositoryName(): Promise<string> {\n\t\tconst repositoryName = await this.getRepositoryName();\n\n\t\tconst supportsEnvironments = this.project.checkSupportsEnvironments();\n\t\tif (!supportsEnvironments) {\n\t\t\treturn repositoryName;\n\t\t}\n\n\t\tconst { environment } = await this.project.readEnvironment();\n\n\t\treturn environment ?? repositoryName;\n\t}\n\n\tasync getAdapterName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\t\tconst adapterName =\n\t\t\ttypeof sliceMachineConfig.adapter === \"string\"\n\t\t\t\t? sliceMachineConfig.adapter\n\t\t\t\t: sliceMachineConfig.adapter.resolve;\n\n\t\treturn adapterName;\n\t}\n\n\tasync locateAdapterDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\t\tconst adapterName = await this.getAdapterName();\n\t\tconst adapterPackageJSONPath = requireResolve(\n\t\t\t`${adapterName}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(adapterPackageJSONPath);\n\t}\n\n\tasync initProject(args?: ProjectManagerInitProjectArgs): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args?.log || console.log.bind(this);\n\n\t\tconst { errors } = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:init\",\n\t\t\t{\n\t\t\t\tlog,\n\t\t\t\tinstallDependencies: async (args) => {\n\t\t\t\t\tconst { execaProcess } = await this.installDependencies({\n\t\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t\t\tdev: args.dev,\n\t\t\t\t\t\tlog,\n\t\t\t\t\t});\n\n\t\t\t\t\tawait execaProcess;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (errors.length > 0) {\n\t\t\t// TODO: Provide better error message.\n\t\t\tthrow new SliceMachineError(\n\t\t\t\t`Failed to initialize project: ${errors.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync detectPackageManager(\n\t\targs?: ProjectManagerDetectPackageManager,\n\t): Promise<PackageManager> {\n\t\tconst projectRoot = args?.root || (await this.getRoot());\n\n\t\tconst packageManager = await niDetect({\n\t\t\tautoInstall: true,\n\t\t\tcwd: projectRoot,\n\t\t});\n\n\t\treturn packageManager || \"npm\";\n\t}\n\n\tasync installDependencies(\n\t\targs: ProjectManagerInstallDependenciesArgs,\n\t): Promise<ProjectManagerInstallDependenciesReturnType> {\n\t\tconst packageManager =\n\t\t\targs.packageManager || (await this.detectPackageManager());\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args.log || console.log.bind(this);\n\n\t\tconst wrappedLogger = (data: Buffer | string | null) => {\n\t\t\tif (data instanceof Buffer) {\n\t\t\t\tlog(data.toString());\n\t\t\t} else if (typeof data === \"string\") {\n\t\t\t\tlog(data);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tconst { execaProcess } = await installDependencies({\n\t\t\t\tpackageManager,\n\t\t\t\tdependencies: args.dependencies,\n\t\t\t\tdev: args.dev,\n\t\t\t});\n\n\t\t\t// Don't clutter console with logs when process is non TTY (CI, etc.)\n\t\t\tif (process.stdout.isTTY || process.env.NODE_ENV === \"test\") {\n\t\t\t\texecaProcess.stdout?.on(\"data\", wrappedLogger);\n\t\t\t}\n\t\t\texecaProcess.stderr?.on(\"data\", wrappedLogger);\n\n\t\t\treturn {\n\t\t\t\texecaProcess,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\t\"shortMessage\" in error &&\n\t\t\t\t\"stderr\" in error\n\t\t\t) {\n\t\t\t\tthrow new InternalError(\"Package installation failed\", {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tcheckSupportsEnvironments(): boolean {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\treturn (\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:read\")\n\t\t\t\t.length > 0 &&\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:update\")\n\t\t\t\t.length > 0\n\t\t);\n\t}\n\n\tasync readEnvironment(): Promise<ProjectManagerReadEnvironmentReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tenvironment: t.union([t.undefined, t.string]),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\t// An undefined value is equivalent to the production environment.\n\t\t// We cast to undefined.\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environmentDomain =\n\t\t\tdata[0]?.environment === repositoryName\n\t\t\t\t? undefined\n\t\t\t\t: data[0]?.environment;\n\n\t\treturn {\n\t\t\tenvironment: environmentDomain,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateEnvironment(\n\t\targs: ProjectManagerUpdateEnvironmentArgs,\n\t): Promise<OnlyHookErrors<CallHookReturnType<ProjectEnvironmentUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environment =\n\t\t\targs.environment === repositoryName ? undefined : args.environment;\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:update\",\n\t\t\t{ environment },\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchActiveEnvironment(): Promise<ProjectManagerFetchActiveEnvironmentReturnType> {\n\t\tconst { environment: activeEnvironmentDomain } =\n\t\t\tawait this.readEnvironment();\n\n\t\t// We can assume an environment cannot change its kind. If the\n\t\t// environment exists in the cached list, we are confident it\n\t\t// will not change.\n\t\tconst cachedActiveEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\t\tif (cachedActiveEnvironment) {\n\t\t\treturn { type: \"ok\", activeEnvironment: cachedActiveEnvironment };\n\t\t}\n\n\t\t// If the environment is not in the cached environments list, we\n\t\t// must fetch a fresh list and set the cache.\n\t\tconst { environments } = await this.prismicRepository.fetchEnvironments();\n\t\t// TODO: Remove the wrapping if statement when\n\t\t// `this.prismicRepository.fetchEnvironments()` is able to throw\n\t\t// normally. The method returns an object with an `error`\n\t\t// property at the time of this writing, which means we need to\n\t\t// check if the `environments` property exists.\n\t\tif (environments) {\n\t\t\tthis._cachedEnvironments = environments;\n\t\t}\n\n\t\tconst activeEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\n\t\tif (!activeEnvironment) {\n\t\t\treturn {\n\t\t\t\ttype: \"error\",\n\t\t\t\terror: new InvalidActiveEnvironmentError(),\n\t\t\t};\n\t\t}\n\n\t\treturn { type: \"ok\", activeEnvironment: activeEnvironment };\n\t}\n\n\tasync detectVersionControlSystem(): Promise<string | \"_unknown\"> {\n\t\ttry {\n\t\t\tconst projectRoot = await this.getRoot();\n\n\t\t\tif (existsSync(path.join(projectRoot, \".git\"))) {\n\t\t\t\treturn \"Git\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".svn\"))) {\n\t\t\t\treturn \"SVN\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".hg\"))) {\n\t\t\t\treturn \"Mercurial\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \"CVS\"))) {\n\t\t\t\treturn \"CVS\";\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Failed to detect Version Control System:\", error);\n\t\t\t}\n\t\t}\n\n\t\treturn \"_unknown\";\n\t}\n\n\tprivate async _assertAdapterSupportsEnvironments(): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst supportsEnvironments = this.checkSupportsEnvironments();\n\n\t\tif (!supportsEnvironments) {\n\t\t\tconst adapterName = await this.project.getAdapterName();\n\n\t\t\tthrow new PluginError(\n\t\t\t\t`${adapterName} does not support environments. Use an adapter that implements the \\`project:environment:read\\` and \\`project:environment:update\\` hooks to use environments.`,\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["BaseManager","locateFileUpward","SLICE_MACHINE_CONFIG_FILENAME","path","TS_CONFIG_FILENAME","existsSync","format","fs","error","SliceMachineError","decodeSliceMachineConfig","requireResolve","SLICE_MACHINE_NPM_PACKAGE_NAME","assertPluginsInitialized","errors","args","niDetect","installDependencies","InternalError","decodeHookResult","t","findEnvironment","InvalidActiveEnvironmentError","PluginError"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2FM,MAAO,uBAAuBA,YAAAA,YAAW;AAAA,EAAzC;AAAA;AACG;AACA;AACA;AACA;AAAA;AAAA,EAER,MAAM,0BACL,MAAkD;AAElD,QAAI,KAAK,iCAAiC,EAAC,6BAAM,cAAa;AAC7D,aAAO,KAAK;AAAA,IACb;AAEI,QAAA;AACE,WAAA,gCAAgC,MAAMC,kCAC1CC,8BAAAA,+BACA,EAAE,UAAU,KAAK,KAAK;AAAA,aAEf,OAAO;AACf,YAAM,IAAI,MACT,oBAAoBA,8BAAAA,6BAA6B,iEAAiE;AAAA,IAEpH;AAEA,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,QAAQ,MAAgC;AAC7C,QAAI,KAAK,eAAe,EAAC,6BAAM,cAAa;AAC3C,aAAO,KAAK;AAAA,IACb;AAEM,UAAA,6BAA6B,MAAM,KAAK,0BAA0B;AAAA,MACvE,aAAa,6BAAM;AAAA,IAAA,CACnB;AAEI,SAAA,cAAcC,gBAAK,QAAQ,0BAA0B;AAE1D,WAAO,KAAK;AAAA,EACb;AAAA,EAEA,MAAM,cAAW;AACV,UAAA,2BAA2B,MAAMF,iBAAA,iBAAiB,g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AAQ,eAAc;AAErD,YAAM,IAAIU,OAAAA,YACT,GAAG,WAAW,+JAA+J;AAAA,IAE/K;AAAA,EACD;AACA;;"}
@@ -42,7 +42,7 @@ type ProjectManagerUpdateEnvironmentArgs = {
42
42
  };
43
43
  type ProjectManagerFetchActiveEnvironmentReturnType = {
44
44
  type: "ok";
45
- environment: Environment;
45
+ activeEnvironment: Environment;
46
46
  } | {
47
47
  type: "error";
48
48
  error: InvalidActiveEnvironmentError;
@@ -243,7 +243,7 @@ Error Message: ${error2.message}`);
243
243
  const { environment: activeEnvironmentDomain } = await this.readEnvironment();
244
244
  const cachedActiveEnvironment = findEnvironment(activeEnvironmentDomain, this._cachedEnvironments || []);
245
245
  if (cachedActiveEnvironment) {
246
- return { type: "ok", environment: cachedActiveEnvironment };
246
+ return { type: "ok", activeEnvironment: cachedActiveEnvironment };
247
247
  }
248
248
  const { environments } = await this.prismicRepository.fetchEnvironments();
249
249
  if (environments) {
@@ -256,7 +256,7 @@ Error Message: ${error2.message}`);
256
256
  error: new InvalidActiveEnvironmentError()
257
257
  };
258
258
  }
259
- return { type: "ok", environment: activeEnvironment };
259
+ return { type: "ok", activeEnvironment };
260
260
  }
261
261
  async detectVersionControlSystem() {
262
262
  try {
@@ -1 +1 @@
1
- {"version":3,"file":"ProjectManager.js","sources":["../../../../src/managers/project/ProjectManager.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { detect as niDetect } from \"@antfu/ni\";\nimport { ExecaChildProcess } from \"execa\";\nimport {\n\tHookError,\n\tCallHookReturnType,\n\tProjectEnvironmentUpdateHook,\n} from \"@slicemachine/plugin-kit\";\nimport * as t from \"io-ts\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport { decodeSliceMachineConfig } from \"../../lib/decodeSliceMachineConfig\";\nimport { findEnvironment } from \"../../lib/findEnvironment\";\nimport { format } from \"../../lib/format\";\nimport { installDependencies } from \"../../lib/installDependencies\";\nimport { locateFileUpward } from \"../../lib/locateFileUpward\";\nimport { requireResolve } from \"../../lib/requireResolve\";\n\nimport {\n\tPackageManager,\n\tSliceMachineConfig,\n\tOnlyHookErrors,\n} from \"../../types\";\n\nimport {\n\tSliceMachineError,\n\tInternalError,\n\tPluginError,\n\tInvalidActiveEnvironmentError,\n} from \"../../errors\";\n\nimport { SLICE_MACHINE_CONFIG_FILENAME } from \"../../constants/SLICE_MACHINE_CONFIG_FILENAME\";\nimport { TS_CONFIG_FILENAME } from \"../../constants/TS_CONFIG_FILENAME\";\nimport { SLICE_MACHINE_NPM_PACKAGE_NAME } from \"../../constants/SLICE_MACHINE_NPM_PACKAGE_NAME\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype ProjectManagerGetSliceMachineConfigPathArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerGetRootArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerCheckIsTypeScriptArgs = {\n\trootOverride?: string;\n};\n\ntype ProjectManagerWriteSliceMachineConfigArgs = {\n\tconfig: SliceMachineConfig;\n\tpath?: string;\n};\n\ntype ProjectManagerInitProjectArgs = {\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerDetectPackageManager = {\n\troot?: string;\n};\n\ntype ProjectManagerInstallDependenciesArgs = {\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\tpackageManager?: PackageManager;\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerInstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\ntype ProjectManagerReadEnvironmentReturnType = {\n\tenvironment: string | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype ProjectManagerUpdateEnvironmentArgs = {\n\tenvironment: string | undefined;\n};\n\ntype ProjectManagerFetchActiveEnvironmentReturnType =\n\t| { type: \"ok\"; environment: Environment }\n\t| { type: \"error\"; error: InvalidActiveEnvironmentError };\n\nexport class ProjectManager extends BaseManager {\n\tprivate _cachedRoot: string | undefined;\n\tprivate _cachedSliceMachineConfigPath: string | undefined;\n\tprivate _cachedSliceMachineConfig: SliceMachineConfig | undefined;\n\tprivate _cachedEnvironments: Environment[] | undefined;\n\n\tasync getSliceMachineConfigPath(\n\t\targs?: ProjectManagerGetSliceMachineConfigPathArgs,\n\t): Promise<string> {\n\t\tif (this._cachedSliceMachineConfigPath && !args?.ignoreCache) {\n\t\t\treturn this._cachedSliceMachineConfigPath;\n\t\t}\n\n\t\ttry {\n\t\t\tthis._cachedSliceMachineConfigPath = await locateFileUpward(\n\t\t\t\tSLICE_MACHINE_CONFIG_FILENAME,\n\t\t\t\t{ startDir: this.cwd },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not find a ${SLICE_MACHINE_CONFIG_FILENAME} file. Please create a config file at the root of your project.`,\n\t\t\t);\n\t\t}\n\n\t\treturn this._cachedSliceMachineConfigPath;\n\t}\n\n\tasync getRoot(args?: ProjectManagerGetRootArgs): Promise<string> {\n\t\tif (this._cachedRoot && !args?.ignoreCache) {\n\t\t\treturn this._cachedRoot;\n\t\t}\n\n\t\tconst sliceMachineConfigFilePath = await this.getSliceMachineConfigPath({\n\t\t\tignoreCache: args?.ignoreCache,\n\t\t});\n\n\t\tthis._cachedRoot = path.dirname(sliceMachineConfigFilePath);\n\n\t\treturn this._cachedRoot;\n\t}\n\n\tasync suggestRoot(): Promise<string> {\n\t\tconst suggestedRootPackageJSON = await locateFileUpward(\"package.json\", {\n\t\t\tstartDir: this.cwd,\n\t\t});\n\n\t\treturn path.dirname(suggestedRootPackageJSON);\n\t}\n\n\tasync suggestSliceMachineConfigPath(): Promise<string> {\n\t\tconst suggestedRoot = await this.suggestRoot();\n\n\t\treturn path.resolve(suggestedRoot, SLICE_MACHINE_CONFIG_FILENAME);\n\t}\n\n\tasync checkIsTypeScript(\n\t\targs?: ProjectManagerCheckIsTypeScriptArgs,\n\t): Promise<boolean> {\n\t\tconst root = args?.rootOverride || (await this.getRoot());\n\t\tconst rootTSConfigPath = path.resolve(root, TS_CONFIG_FILENAME);\n\n\t\t// We just care if the file exists, we don't need access to it\n\t\treturn existsSync(rootTSConfigPath);\n\t}\n\n\tasync getSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\tif (this._cachedSliceMachineConfig) {\n\t\t\treturn this._cachedSliceMachineConfig;\n\t\t} else {\n\t\t\treturn await this.loadSliceMachineConfig();\n\t\t}\n\t}\n\n\tasync writeSliceMachineConfig(\n\t\targs: ProjectManagerWriteSliceMachineConfigArgs,\n\t): Promise<void> {\n\t\tconst configFilePath =\n\t\t\targs.path || (await this.getSliceMachineConfigPath());\n\n\t\tconst config = await format(\n\t\t\tJSON.stringify(args.config, null, 2),\n\t\t\tconfigFilePath,\n\t\t);\n\n\t\tawait fs.writeFile(configFilePath, config, \"utf-8\");\n\t\tdelete this._cachedSliceMachineConfig; // Clear config cache\n\t}\n\n\tasync loadSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\t// TODO: Reload plugins with a fresh plugin runner. Plugins may\n\t\t// have been added or removed.\n\t\tconst configFilePath = await this.getSliceMachineConfigPath();\n\n\t\tlet rawConfig: unknown | undefined;\n\t\ttry {\n\t\t\tconst contents = await fs.readFile(configFilePath, \"utf8\");\n\t\t\trawConfig = JSON.parse(contents);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\tthrow new SliceMachineError(\n\t\t\t\t\t`Could not parse config file at ${configFilePath}.\\n\\nError Message: ${error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Noop, more specific error is thrown after\n\t\t}\n\n\t\tif (!rawConfig) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(\"No config found.\");\n\t\t}\n\n\t\tconst { value: sliceMachineConfig, error } =\n\t\t\tdecodeSliceMachineConfig(rawConfig);\n\n\t\tif (error) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(`Invalid config. ${error.errors.join(\", \")}`, {\n\t\t\t\tcause: { rawConfig },\n\t\t\t});\n\t\t}\n\n\t\t// Allow cached config reading using `SliceMachineManager.prototype.getProjectConfig()`.\n\t\tthis._cachedSliceMachineConfig = sliceMachineConfig;\n\n\t\treturn sliceMachineConfig;\n\t}\n\n\tasync locateSliceMachineUIDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\n\t\tconst sliceMachinePackageJSONPath = requireResolve(\n\t\t\t`${SLICE_MACHINE_NPM_PACKAGE_NAME}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(sliceMachinePackageJSONPath);\n\t}\n\n\t/**\n\t * Returns the project's repository name (i.e. the production environment). It\n\t * ignores the currently selected environment.\n\t *\n\t * Use this method to retrieve the production environment domain.\n\t *\n\t * @returns The project's repository name.\n\t */\n\tasync getRepositoryName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\n\t\treturn sliceMachineConfig.repositoryName;\n\t}\n\n\t/**\n\t * Returns the currently selected environment domain if set. If an environment\n\t * is not set, it returns the project's repository name (the production\n\t * environment).\n\t *\n\t * Use this method to retrieve the repository name to be sent with Prismic API\n\t * requests.\n\t *\n\t * @returns The resolved repository name.\n\t */\n\tasync getResolvedRepositoryName(): Promise<string> {\n\t\tconst repositoryName = await this.getRepositoryName();\n\n\t\tconst supportsEnvironments = this.project.checkSupportsEnvironments();\n\t\tif (!supportsEnvironments) {\n\t\t\treturn repositoryName;\n\t\t}\n\n\t\tconst { environment } = await this.project.readEnvironment();\n\n\t\treturn environment ?? repositoryName;\n\t}\n\n\tasync getAdapterName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\t\tconst adapterName =\n\t\t\ttypeof sliceMachineConfig.adapter === \"string\"\n\t\t\t\t? sliceMachineConfig.adapter\n\t\t\t\t: sliceMachineConfig.adapter.resolve;\n\n\t\treturn adapterName;\n\t}\n\n\tasync locateAdapterDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\t\tconst adapterName = await this.getAdapterName();\n\t\tconst adapterPackageJSONPath = requireResolve(\n\t\t\t`${adapterName}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(adapterPackageJSONPath);\n\t}\n\n\tasync initProject(args?: ProjectManagerInitProjectArgs): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args?.log || console.log.bind(this);\n\n\t\tconst { errors } = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:init\",\n\t\t\t{\n\t\t\t\tlog,\n\t\t\t\tinstallDependencies: async (args) => {\n\t\t\t\t\tconst { execaProcess } = await this.installDependencies({\n\t\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t\t\tdev: args.dev,\n\t\t\t\t\t\tlog,\n\t\t\t\t\t});\n\n\t\t\t\t\tawait execaProcess;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (errors.length > 0) {\n\t\t\t// TODO: Provide better error message.\n\t\t\tthrow new SliceMachineError(\n\t\t\t\t`Failed to initialize project: ${errors.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync detectPackageManager(\n\t\targs?: ProjectManagerDetectPackageManager,\n\t): Promise<PackageManager> {\n\t\tconst projectRoot = args?.root || (await this.getRoot());\n\n\t\tconst packageManager = await niDetect({\n\t\t\tautoInstall: true,\n\t\t\tcwd: projectRoot,\n\t\t});\n\n\t\treturn packageManager || \"npm\";\n\t}\n\n\tasync installDependencies(\n\t\targs: ProjectManagerInstallDependenciesArgs,\n\t): Promise<ProjectManagerInstallDependenciesReturnType> {\n\t\tconst packageManager =\n\t\t\targs.packageManager || (await this.detectPackageManager());\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args.log || console.log.bind(this);\n\n\t\tconst wrappedLogger = (data: Buffer | string | null) => {\n\t\t\tif (data instanceof Buffer) {\n\t\t\t\tlog(data.toString());\n\t\t\t} else if (typeof data === \"string\") {\n\t\t\t\tlog(data);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tconst { execaProcess } = await installDependencies({\n\t\t\t\tpackageManager,\n\t\t\t\tdependencies: args.dependencies,\n\t\t\t\tdev: args.dev,\n\t\t\t});\n\n\t\t\t// Don't clutter console with logs when process is non TTY (CI, etc.)\n\t\t\tif (process.stdout.isTTY || process.env.NODE_ENV === \"test\") {\n\t\t\t\texecaProcess.stdout?.on(\"data\", wrappedLogger);\n\t\t\t}\n\t\t\texecaProcess.stderr?.on(\"data\", wrappedLogger);\n\n\t\t\treturn {\n\t\t\t\texecaProcess,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\t\"shortMessage\" in error &&\n\t\t\t\t\"stderr\" in error\n\t\t\t) {\n\t\t\t\tthrow new InternalError(\"Package installation failed\", {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tcheckSupportsEnvironments(): boolean {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\treturn (\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:read\")\n\t\t\t\t.length > 0 &&\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:update\")\n\t\t\t\t.length > 0\n\t\t);\n\t}\n\n\tasync readEnvironment(): Promise<ProjectManagerReadEnvironmentReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tenvironment: t.union([t.undefined, t.string]),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\t// An undefined value is equivalent to the production environment.\n\t\t// We cast to undefined.\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environmentDomain =\n\t\t\tdata[0]?.environment === repositoryName\n\t\t\t\t? undefined\n\t\t\t\t: data[0]?.environment;\n\n\t\treturn {\n\t\t\tenvironment: environmentDomain,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateEnvironment(\n\t\targs: ProjectManagerUpdateEnvironmentArgs,\n\t): Promise<OnlyHookErrors<CallHookReturnType<ProjectEnvironmentUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environment =\n\t\t\targs.environment === repositoryName ? undefined : args.environment;\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:update\",\n\t\t\t{ environment },\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchActiveEnvironment(): Promise<ProjectManagerFetchActiveEnvironmentReturnType> {\n\t\tconst { environment: activeEnvironmentDomain } =\n\t\t\tawait this.readEnvironment();\n\n\t\t// We can assume an environment cannot change its kind. If the\n\t\t// environment exists in the cached list, we are confident it\n\t\t// will not change.\n\t\tconst cachedActiveEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\t\tif (cachedActiveEnvironment) {\n\t\t\treturn { type: \"ok\", environment: cachedActiveEnvironment };\n\t\t}\n\n\t\t// If the environment is not in the cached environments list, we\n\t\t// must fetch a fresh list and set the cache.\n\t\tconst { environments } = await this.prismicRepository.fetchEnvironments();\n\t\t// TODO: Remove the wrapping if statement when\n\t\t// `this.prismicRepository.fetchEnvironments()` is able to throw\n\t\t// normally. The method returns an object with an `error`\n\t\t// property at the time of this writing, which means we need to\n\t\t// check if the `environments` property exists.\n\t\tif (environments) {\n\t\t\tthis._cachedEnvironments = environments;\n\t\t}\n\n\t\tconst activeEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\n\t\tif (!activeEnvironment) {\n\t\t\treturn {\n\t\t\t\ttype: \"error\",\n\t\t\t\terror: new InvalidActiveEnvironmentError(),\n\t\t\t};\n\t\t}\n\n\t\treturn { type: \"ok\", environment: activeEnvironment };\n\t}\n\n\tasync detectVersionControlSystem(): Promise<string | \"_unknown\"> {\n\t\ttry {\n\t\t\tconst projectRoot = await this.getRoot();\n\n\t\t\tif (existsSync(path.join(projectRoot, \".git\"))) {\n\t\t\t\treturn \"Git\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".svn\"))) {\n\t\t\t\treturn \"SVN\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".hg\"))) {\n\t\t\t\treturn \"Mercurial\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \"CVS\"))) {\n\t\t\t\treturn \"CVS\";\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Failed to detect Version Control System:\", error);\n\t\t\t}\n\t\t}\n\n\t\treturn \"_unknown\";\n\t}\n\n\tprivate async _assertAdapterSupportsEnvironments(): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst supportsEnvironments = this.checkSupportsEnvironments();\n\n\t\tif (!supportsEnvironments) {\n\t\t\tconst adapterName = await this.project.getAdapterName();\n\n\t\t\tthrow new PluginError(\n\t\t\t\t`${adapterName} does not support environments. Use an adapter that implements the \\`project:environment:read\\` and \\`project:environment:update\\` hooks to use environments.`,\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["error","args","niDetect"],"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AAc,MAAM,KAAK;AAE/B,UAAI,WAAW,KAAK,KAAK,aAAa,MAAM,CAAC,GAAG;AACxC,eAAA;AAAA,MACR;AAEA,UAAI,WAAW,KAAK,KAAK,aAAa,MAAM,CAAC,GAAG;AACxC,eAAA;AAAA,MACR;AAEA,UAAI,WAAW,KAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAEA,UAAI,WAAW,KAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAAA,aACQ,OAAO;AAAA,IAIhB;AAEO,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,qCAAkC;AAC/C,6BAAyB,KAAK,wBAAwB;AAEhD,UAAA,uBAAuB,KAAK;AAElC,QAAI,CAAC,sBAAsB;AAC1B,YAAM,cAAc,MAAM,KAAK,QAAQ,eAAc;AAErD,YAAM,IAAI,YACT,GAAG,WAAW,+JAA+J;AAAA,IAE/K;AAAA,EACD;AACA;"}
1
+ {"version":3,"file":"ProjectManager.js","sources":["../../../../src/managers/project/ProjectManager.ts"],"sourcesContent":["import * as fs from \"node:fs/promises\";\nimport { existsSync } from \"node:fs\";\nimport * as path from \"node:path\";\nimport { detect as niDetect } from \"@antfu/ni\";\nimport { ExecaChildProcess } from \"execa\";\nimport {\n\tHookError,\n\tCallHookReturnType,\n\tProjectEnvironmentUpdateHook,\n} from \"@slicemachine/plugin-kit\";\nimport * as t from \"io-ts\";\n\nimport { DecodeError } from \"../../lib/DecodeError\";\nimport { assertPluginsInitialized } from \"../../lib/assertPluginsInitialized\";\nimport { decodeHookResult } from \"../../lib/decodeHookResult\";\nimport { decodeSliceMachineConfig } from \"../../lib/decodeSliceMachineConfig\";\nimport { findEnvironment } from \"../../lib/findEnvironment\";\nimport { format } from \"../../lib/format\";\nimport { installDependencies } from \"../../lib/installDependencies\";\nimport { locateFileUpward } from \"../../lib/locateFileUpward\";\nimport { requireResolve } from \"../../lib/requireResolve\";\n\nimport {\n\tPackageManager,\n\tSliceMachineConfig,\n\tOnlyHookErrors,\n} from \"../../types\";\n\nimport {\n\tSliceMachineError,\n\tInternalError,\n\tPluginError,\n\tInvalidActiveEnvironmentError,\n} from \"../../errors\";\n\nimport { SLICE_MACHINE_CONFIG_FILENAME } from \"../../constants/SLICE_MACHINE_CONFIG_FILENAME\";\nimport { TS_CONFIG_FILENAME } from \"../../constants/TS_CONFIG_FILENAME\";\nimport { SLICE_MACHINE_NPM_PACKAGE_NAME } from \"../../constants/SLICE_MACHINE_NPM_PACKAGE_NAME\";\n\nimport { BaseManager } from \"../BaseManager\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype ProjectManagerGetSliceMachineConfigPathArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerGetRootArgs = {\n\tignoreCache?: boolean;\n};\n\ntype ProjectManagerCheckIsTypeScriptArgs = {\n\trootOverride?: string;\n};\n\ntype ProjectManagerWriteSliceMachineConfigArgs = {\n\tconfig: SliceMachineConfig;\n\tpath?: string;\n};\n\ntype ProjectManagerInitProjectArgs = {\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerDetectPackageManager = {\n\troot?: string;\n};\n\ntype ProjectManagerInstallDependenciesArgs = {\n\tdependencies: Record<string, string>;\n\tdev?: boolean;\n\tpackageManager?: PackageManager;\n\tlog?: (message: string) => void;\n};\n\ntype ProjectManagerInstallDependenciesReturnType = {\n\texecaProcess: ExecaChildProcess;\n};\n\ntype ProjectManagerReadEnvironmentReturnType = {\n\tenvironment: string | undefined;\n\terrors: (DecodeError | HookError)[];\n};\n\ntype ProjectManagerUpdateEnvironmentArgs = {\n\tenvironment: string | undefined;\n};\n\ntype ProjectManagerFetchActiveEnvironmentReturnType =\n\t| { type: \"ok\"; activeEnvironment: Environment }\n\t| { type: \"error\"; error: InvalidActiveEnvironmentError };\n\nexport class ProjectManager extends BaseManager {\n\tprivate _cachedRoot: string | undefined;\n\tprivate _cachedSliceMachineConfigPath: string | undefined;\n\tprivate _cachedSliceMachineConfig: SliceMachineConfig | undefined;\n\tprivate _cachedEnvironments: Environment[] | undefined;\n\n\tasync getSliceMachineConfigPath(\n\t\targs?: ProjectManagerGetSliceMachineConfigPathArgs,\n\t): Promise<string> {\n\t\tif (this._cachedSliceMachineConfigPath && !args?.ignoreCache) {\n\t\t\treturn this._cachedSliceMachineConfigPath;\n\t\t}\n\n\t\ttry {\n\t\t\tthis._cachedSliceMachineConfigPath = await locateFileUpward(\n\t\t\t\tSLICE_MACHINE_CONFIG_FILENAME,\n\t\t\t\t{ startDir: this.cwd },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow new Error(\n\t\t\t\t`Could not find a ${SLICE_MACHINE_CONFIG_FILENAME} file. Please create a config file at the root of your project.`,\n\t\t\t);\n\t\t}\n\n\t\treturn this._cachedSliceMachineConfigPath;\n\t}\n\n\tasync getRoot(args?: ProjectManagerGetRootArgs): Promise<string> {\n\t\tif (this._cachedRoot && !args?.ignoreCache) {\n\t\t\treturn this._cachedRoot;\n\t\t}\n\n\t\tconst sliceMachineConfigFilePath = await this.getSliceMachineConfigPath({\n\t\t\tignoreCache: args?.ignoreCache,\n\t\t});\n\n\t\tthis._cachedRoot = path.dirname(sliceMachineConfigFilePath);\n\n\t\treturn this._cachedRoot;\n\t}\n\n\tasync suggestRoot(): Promise<string> {\n\t\tconst suggestedRootPackageJSON = await locateFileUpward(\"package.json\", {\n\t\t\tstartDir: this.cwd,\n\t\t});\n\n\t\treturn path.dirname(suggestedRootPackageJSON);\n\t}\n\n\tasync suggestSliceMachineConfigPath(): Promise<string> {\n\t\tconst suggestedRoot = await this.suggestRoot();\n\n\t\treturn path.resolve(suggestedRoot, SLICE_MACHINE_CONFIG_FILENAME);\n\t}\n\n\tasync checkIsTypeScript(\n\t\targs?: ProjectManagerCheckIsTypeScriptArgs,\n\t): Promise<boolean> {\n\t\tconst root = args?.rootOverride || (await this.getRoot());\n\t\tconst rootTSConfigPath = path.resolve(root, TS_CONFIG_FILENAME);\n\n\t\t// We just care if the file exists, we don't need access to it\n\t\treturn existsSync(rootTSConfigPath);\n\t}\n\n\tasync getSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\tif (this._cachedSliceMachineConfig) {\n\t\t\treturn this._cachedSliceMachineConfig;\n\t\t} else {\n\t\t\treturn await this.loadSliceMachineConfig();\n\t\t}\n\t}\n\n\tasync writeSliceMachineConfig(\n\t\targs: ProjectManagerWriteSliceMachineConfigArgs,\n\t): Promise<void> {\n\t\tconst configFilePath =\n\t\t\targs.path || (await this.getSliceMachineConfigPath());\n\n\t\tconst config = await format(\n\t\t\tJSON.stringify(args.config, null, 2),\n\t\t\tconfigFilePath,\n\t\t);\n\n\t\tawait fs.writeFile(configFilePath, config, \"utf-8\");\n\t\tdelete this._cachedSliceMachineConfig; // Clear config cache\n\t}\n\n\tasync loadSliceMachineConfig(): Promise<SliceMachineConfig> {\n\t\t// TODO: Reload plugins with a fresh plugin runner. Plugins may\n\t\t// have been added or removed.\n\t\tconst configFilePath = await this.getSliceMachineConfigPath();\n\n\t\tlet rawConfig: unknown | undefined;\n\t\ttry {\n\t\t\tconst contents = await fs.readFile(configFilePath, \"utf8\");\n\t\t\trawConfig = JSON.parse(contents);\n\t\t} catch (error) {\n\t\t\tif (error instanceof SyntaxError) {\n\t\t\t\tthrow new SliceMachineError(\n\t\t\t\t\t`Could not parse config file at ${configFilePath}.\\n\\nError Message: ${error.message}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\t// Noop, more specific error is thrown after\n\t\t}\n\n\t\tif (!rawConfig) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(\"No config found.\");\n\t\t}\n\n\t\tconst { value: sliceMachineConfig, error } =\n\t\t\tdecodeSliceMachineConfig(rawConfig);\n\n\t\tif (error) {\n\t\t\t// TODO: Write a more friendly and useful message.\n\t\t\tthrow new Error(`Invalid config. ${error.errors.join(\", \")}`, {\n\t\t\t\tcause: { rawConfig },\n\t\t\t});\n\t\t}\n\n\t\t// Allow cached config reading using `SliceMachineManager.prototype.getProjectConfig()`.\n\t\tthis._cachedSliceMachineConfig = sliceMachineConfig;\n\n\t\treturn sliceMachineConfig;\n\t}\n\n\tasync locateSliceMachineUIDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\n\t\tconst sliceMachinePackageJSONPath = requireResolve(\n\t\t\t`${SLICE_MACHINE_NPM_PACKAGE_NAME}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(sliceMachinePackageJSONPath);\n\t}\n\n\t/**\n\t * Returns the project's repository name (i.e. the production environment). It\n\t * ignores the currently selected environment.\n\t *\n\t * Use this method to retrieve the production environment domain.\n\t *\n\t * @returns The project's repository name.\n\t */\n\tasync getRepositoryName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\n\t\treturn sliceMachineConfig.repositoryName;\n\t}\n\n\t/**\n\t * Returns the currently selected environment domain if set. If an environment\n\t * is not set, it returns the project's repository name (the production\n\t * environment).\n\t *\n\t * Use this method to retrieve the repository name to be sent with Prismic API\n\t * requests.\n\t *\n\t * @returns The resolved repository name.\n\t */\n\tasync getResolvedRepositoryName(): Promise<string> {\n\t\tconst repositoryName = await this.getRepositoryName();\n\n\t\tconst supportsEnvironments = this.project.checkSupportsEnvironments();\n\t\tif (!supportsEnvironments) {\n\t\t\treturn repositoryName;\n\t\t}\n\n\t\tconst { environment } = await this.project.readEnvironment();\n\n\t\treturn environment ?? repositoryName;\n\t}\n\n\tasync getAdapterName(): Promise<string> {\n\t\tconst sliceMachineConfig = await this.getSliceMachineConfig();\n\t\tconst adapterName =\n\t\t\ttypeof sliceMachineConfig.adapter === \"string\"\n\t\t\t\t? sliceMachineConfig.adapter\n\t\t\t\t: sliceMachineConfig.adapter.resolve;\n\n\t\treturn adapterName;\n\t}\n\n\tasync locateAdapterDir(): Promise<string> {\n\t\tconst projectRoot = await this.getRoot();\n\t\tconst adapterName = await this.getAdapterName();\n\t\tconst adapterPackageJSONPath = requireResolve(\n\t\t\t`${adapterName}/package.json`,\n\t\t\tpath.join(projectRoot, \"index.js\"),\n\t\t);\n\n\t\treturn path.dirname(adapterPackageJSONPath);\n\t}\n\n\tasync initProject(args?: ProjectManagerInitProjectArgs): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args?.log || console.log.bind(this);\n\n\t\tconst { errors } = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:init\",\n\t\t\t{\n\t\t\t\tlog,\n\t\t\t\tinstallDependencies: async (args) => {\n\t\t\t\t\tconst { execaProcess } = await this.installDependencies({\n\t\t\t\t\t\tdependencies: args.dependencies,\n\t\t\t\t\t\tdev: args.dev,\n\t\t\t\t\t\tlog,\n\t\t\t\t\t});\n\n\t\t\t\t\tawait execaProcess;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\n\t\tif (errors.length > 0) {\n\t\t\t// TODO: Provide better error message.\n\t\t\tthrow new SliceMachineError(\n\t\t\t\t`Failed to initialize project: ${errors.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tasync detectPackageManager(\n\t\targs?: ProjectManagerDetectPackageManager,\n\t): Promise<PackageManager> {\n\t\tconst projectRoot = args?.root || (await this.getRoot());\n\n\t\tconst packageManager = await niDetect({\n\t\t\tautoInstall: true,\n\t\t\tcwd: projectRoot,\n\t\t});\n\n\t\treturn packageManager || \"npm\";\n\t}\n\n\tasync installDependencies(\n\t\targs: ProjectManagerInstallDependenciesArgs,\n\t): Promise<ProjectManagerInstallDependenciesReturnType> {\n\t\tconst packageManager =\n\t\t\targs.packageManager || (await this.detectPackageManager());\n\n\t\t// eslint-disable-next-line no-console\n\t\tconst log = args.log || console.log.bind(this);\n\n\t\tconst wrappedLogger = (data: Buffer | string | null) => {\n\t\t\tif (data instanceof Buffer) {\n\t\t\t\tlog(data.toString());\n\t\t\t} else if (typeof data === \"string\") {\n\t\t\t\tlog(data);\n\t\t\t}\n\t\t};\n\n\t\ttry {\n\t\t\tconst { execaProcess } = await installDependencies({\n\t\t\t\tpackageManager,\n\t\t\t\tdependencies: args.dependencies,\n\t\t\t\tdev: args.dev,\n\t\t\t});\n\n\t\t\t// Don't clutter console with logs when process is non TTY (CI, etc.)\n\t\t\tif (process.stdout.isTTY || process.env.NODE_ENV === \"test\") {\n\t\t\t\texecaProcess.stdout?.on(\"data\", wrappedLogger);\n\t\t\t}\n\t\t\texecaProcess.stderr?.on(\"data\", wrappedLogger);\n\n\t\t\treturn {\n\t\t\t\texecaProcess,\n\t\t\t};\n\t\t} catch (error) {\n\t\t\tif (\n\t\t\t\terror instanceof Error &&\n\t\t\t\t\"shortMessage\" in error &&\n\t\t\t\t\"stderr\" in error\n\t\t\t) {\n\t\t\t\tthrow new InternalError(\"Package installation failed\", {\n\t\t\t\t\tcause: error,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tcheckSupportsEnvironments(): boolean {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\treturn (\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:read\")\n\t\t\t\t.length > 0 &&\n\t\t\tthis.sliceMachinePluginRunner.hooksForType(\"project:environment:update\")\n\t\t\t\t.length > 0\n\t\t);\n\t}\n\n\tasync readEnvironment(): Promise<ProjectManagerReadEnvironmentReturnType> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:read\",\n\t\t\tundefined,\n\t\t);\n\t\tconst { data, errors } = decodeHookResult(\n\t\t\tt.type({\n\t\t\t\tenvironment: t.union([t.undefined, t.string]),\n\t\t\t}),\n\t\t\thookResult,\n\t\t);\n\n\t\t// An undefined value is equivalent to the production environment.\n\t\t// We cast to undefined.\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environmentDomain =\n\t\t\tdata[0]?.environment === repositoryName\n\t\t\t\t? undefined\n\t\t\t\t: data[0]?.environment;\n\n\t\treturn {\n\t\t\tenvironment: environmentDomain,\n\t\t\terrors,\n\t\t};\n\t}\n\n\tasync updateEnvironment(\n\t\targs: ProjectManagerUpdateEnvironmentArgs,\n\t): Promise<OnlyHookErrors<CallHookReturnType<ProjectEnvironmentUpdateHook>>> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tawait this._assertAdapterSupportsEnvironments();\n\n\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\tconst environment =\n\t\t\targs.environment === repositoryName ? undefined : args.environment;\n\n\t\tconst hookResult = await this.sliceMachinePluginRunner.callHook(\n\t\t\t\"project:environment:update\",\n\t\t\t{ environment },\n\t\t);\n\n\t\treturn {\n\t\t\terrors: hookResult.errors,\n\t\t};\n\t}\n\n\tasync fetchActiveEnvironment(): Promise<ProjectManagerFetchActiveEnvironmentReturnType> {\n\t\tconst { environment: activeEnvironmentDomain } =\n\t\t\tawait this.readEnvironment();\n\n\t\t// We can assume an environment cannot change its kind. If the\n\t\t// environment exists in the cached list, we are confident it\n\t\t// will not change.\n\t\tconst cachedActiveEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\t\tif (cachedActiveEnvironment) {\n\t\t\treturn { type: \"ok\", activeEnvironment: cachedActiveEnvironment };\n\t\t}\n\n\t\t// If the environment is not in the cached environments list, we\n\t\t// must fetch a fresh list and set the cache.\n\t\tconst { environments } = await this.prismicRepository.fetchEnvironments();\n\t\t// TODO: Remove the wrapping if statement when\n\t\t// `this.prismicRepository.fetchEnvironments()` is able to throw\n\t\t// normally. The method returns an object with an `error`\n\t\t// property at the time of this writing, which means we need to\n\t\t// check if the `environments` property exists.\n\t\tif (environments) {\n\t\t\tthis._cachedEnvironments = environments;\n\t\t}\n\n\t\tconst activeEnvironment = findEnvironment(\n\t\t\tactiveEnvironmentDomain,\n\t\t\tthis._cachedEnvironments || [],\n\t\t);\n\n\t\tif (!activeEnvironment) {\n\t\t\treturn {\n\t\t\t\ttype: \"error\",\n\t\t\t\terror: new InvalidActiveEnvironmentError(),\n\t\t\t};\n\t\t}\n\n\t\treturn { type: \"ok\", activeEnvironment: activeEnvironment };\n\t}\n\n\tasync detectVersionControlSystem(): Promise<string | \"_unknown\"> {\n\t\ttry {\n\t\t\tconst projectRoot = await this.getRoot();\n\n\t\t\tif (existsSync(path.join(projectRoot, \".git\"))) {\n\t\t\t\treturn \"Git\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".svn\"))) {\n\t\t\t\treturn \"SVN\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \".hg\"))) {\n\t\t\t\treturn \"Mercurial\";\n\t\t\t}\n\n\t\t\tif (existsSync(path.join(projectRoot, \"CVS\"))) {\n\t\t\t\treturn \"CVS\";\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Failed to detect Version Control System:\", error);\n\t\t\t}\n\t\t}\n\n\t\treturn \"_unknown\";\n\t}\n\n\tprivate async _assertAdapterSupportsEnvironments(): Promise<void> {\n\t\tassertPluginsInitialized(this.sliceMachinePluginRunner);\n\n\t\tconst supportsEnvironments = this.checkSupportsEnvironments();\n\n\t\tif (!supportsEnvironments) {\n\t\t\tconst adapterName = await this.project.getAdapterName();\n\n\t\t\tthrow new PluginError(\n\t\t\t\t`${adapterName} does not support environments. Use an adapter that implements the \\`project:environment:read\\` and \\`project:environment:update\\` hooks to use environments.`,\n\t\t\t);\n\t\t}\n\t}\n}\n"],"names":["error","args","niDetect"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA2FM,MAAO,uBAAuB,YAAW;AAAA,EAAzC;AAAA;AACG;AACA;AACA;AACA;AAAA;AAAA,EAER,MAAM,0BACL,MAAkD;AAElD,QAAI,K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ACR;AAEA,UAAI,WAAW,KAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAEA,UAAI,WAAW,KAAK,KAAK,aAAa,KAAK,CAAC,GAAG;AACvC,eAAA;AAAA,MACR;AAAA,aACQ,OAAO;AAAA,IAIhB;AAEO,WAAA;AAAA,EACR;AAAA,EAEQ,MAAM,qCAAkC;AAC/C,6BAAyB,KAAK,wBAAwB;AAEhD,UAAA,uBAAuB,KAAK;AAElC,QAAI,CAAC,sBAAsB;AAC1B,YAAM,cAAc,MAAM,KAAK,QAAQ,eAAc;AAErD,YAAM,IAAI,YACT,GAAG,WAAW,+JAA+J;AAAA,IAE/K;AAAA,EACD;AACA;"}
@@ -66,7 +66,7 @@ class TelemetryManager extends BaseManager.BaseManager {
66
66
  try {
67
67
  const activeEnvironmentResult = await this.project.fetchActiveEnvironment();
68
68
  if (activeEnvironmentResult.type === "ok") {
69
- environmentKind = activeEnvironmentResult.environment.kind;
69
+ environmentKind = activeEnvironmentResult.activeEnvironment.kind;
70
70
  } else {
71
71
  throw activeEnvironmentResult.error;
72
72
  }
@@ -1 +1 @@
1
- {"version":3,"file":"TelemetryManager.cjs","sources":["../../../../src/managers/telemetry/TelemetryManager.ts"],"sourcesContent":["import {\n\tExperiment,\n\tRemoteEvaluationClient,\n\tVariant,\n} from \"@amplitude/experiment-node-server\";\nimport { randomUUID } from \"node:crypto\";\nimport { Analytics, GroupParams, TrackParams } from \"@segment/analytics-node\";\n\nimport { readPrismicrc } from \"../../lib/prismicrc\";\n\nimport { API_TOKENS } from \"../../constants/API_TOKENS\";\n\nimport { BaseManager } from \"../BaseManager\";\n\nimport {\n\tHumanSegmentEventType,\n\tHumanSegmentEventTypes,\n\tSegmentEvents,\n} from \"./types\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype TelemetryManagerInitTelemetryArgs = {\n\tappName: string;\n\tappVersion: string;\n};\n\ntype TelemetryManagerTrackArgs = SegmentEvents & {\n\t_includeEnvironmentKind?: boolean;\n};\n\ntype TelemetryManagerIdentifyArgs = {\n\tuserID: string;\n\tintercomHash: string;\n};\n\ntype TelemetryManagerGroupArgs = {\n\tmanualLibsCount: number;\n\tdownloadedLibsCount: number;\n\tnpmLibsCount: number;\n\tdownloadedLibs: string[];\n};\n\ntype TelemetryManagerContext = {\n\tapp: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n};\n\nfunction assertTelemetryInitialized(\n\tsegmentClient: (() => Analytics) | undefined,\n): asserts segmentClient is NonNullable<typeof segmentClient> {\n\tif (segmentClient === undefined) {\n\t\tthrow new Error(\n\t\t\t\"Telemetry has not been initialized. Run `SliceMachineManager.telemetry.prototype.initTelemetry()` before re-calling this method.\",\n\t\t);\n\t}\n}\n\nexport class TelemetryManager extends BaseManager {\n\tprivate _segmentClient: (() => Analytics) | undefined = undefined;\n\tprivate _anonymousID: string | undefined = undefined;\n\tprivate _userID: string | undefined = undefined;\n\tprivate _context: TelemetryManagerContext | undefined = undefined;\n\tprivate _experiment: RemoteEvaluationClient | undefined = undefined;\n\n\tasync initTelemetry(args: TelemetryManagerInitTelemetryArgs): Promise<void> {\n\t\tconst isTelemetryEnabled = await this.checkIsTelemetryEnabled();\n\n\t\tthis._segmentClient = () => {\n\t\t\tconst analytics = new Analytics({\n\t\t\t\twriteKey: API_TOKENS.SegmentKey,\n\t\t\t\t// Since it's a local app, we do not benefit from event batching the way a server would normally do, all tracking event will be awaited.\n\t\t\t\tmaxEventsInBatch: 1,\n\t\t\t\t// TODO: Verify that this actually does not send data to Segment when false.\n\t\t\t\tdisable: !isTelemetryEnabled,\n\t\t\t});\n\n\t\t\tanalytics.on(\"error\", (error) => {\n\t\t\t\t// noop - We don't care if the tracking event\n\t\t\t\t// failed. Some users or networks intentionally\n\t\t\t\t// block Segment, so we can't block the app if\n\t\t\t\t// a tracking event is unsuccessful.\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(`An error occurred with Segment`, error);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn analytics;\n\t\t};\n\n\t\tif (isTelemetryEnabled) {\n\t\t\tthis.initExperiment();\n\t\t}\n\n\t\tthis._anonymousID = randomUUID();\n\t\tthis._context = { app: { name: args.appName, version: args.appVersion } };\n\t}\n\n\t// TODO: Should `userId` be automatically populated by the logged in\n\t// user? We already have their info via UserRepository.\n\tasync track(args: TelemetryManagerTrackArgs): Promise<void> {\n\t\tconst { event, repository, _includeEnvironmentKind, ...properties } = args;\n\t\tlet repositoryName = repository;\n\n\t\tif (repositoryName === undefined) {\n\t\t\ttry {\n\t\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t\t} catch (error) {\n\t\t\t\t// noop, happen only when the user is not in a project\n\t\t\t}\n\t\t}\n\n\t\tlet environmentKind: Environment[\"kind\"] | \"_unknown\" | undefined =\n\t\t\tundefined;\n\t\tif (_includeEnvironmentKind) {\n\t\t\tif (this.project.checkSupportsEnvironments()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst activeEnvironmentResult =\n\t\t\t\t\t\tawait this.project.fetchActiveEnvironment();\n\n\t\t\t\t\tif (activeEnvironmentResult.type === \"ok\") {\n\t\t\t\t\t\tenvironmentKind = activeEnvironmentResult.environment.kind;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow activeEnvironmentResult.error;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tenvironmentKind = \"_unknown\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Assume only the production environment can be\n\t\t\t\t// used if the project's adapter does not\n\t\t\t\t// support environments.\n\t\t\t\tenvironmentKind = \"prod\";\n\t\t\t}\n\t\t}\n\n\t\tconst payload: {\n\t\t\tevent: HumanSegmentEventTypes;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\tproperties?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\tevent: HumanSegmentEventType[event],\n\t\t\tproperties: {\n\t\t\t\tnodeVersion: process.versions.node,\n\t\t\t\tenvironmentKind,\n\t\t\t\t...properties,\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().track(\n\t\t\t\tpayload as TrackParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`An error occurred during Segment tracking`,\n\t\t\t\t\t\t\tmaybeError,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// TODO: Should `userID` and `intercomHash` be automatically populated\n\t// by the logged in user? We already have their info via\n\t// UserRepository.\n\tidentify(args: TelemetryManagerIdentifyArgs): Promise<void> {\n\t\tconst payload = {\n\t\t\tuserId: args.userID,\n\t\t\tanonymousId: this._anonymousID,\n\t\t\tintegrations: {\n\t\t\t\tIntercom: {\n\t\t\t\t\tuser_hash: args.intercomHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tthis._userID = args.userID;\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().identify(payload, (maybeError?: unknown) => {\n\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\tconsole.warn(`An error occurred during Segment identify`, maybeError);\n\t\t\t\t}\n\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\tasync group(args: TelemetryManagerGroupArgs): Promise<void> {\n\t\tlet repositoryName;\n\n\t\ttry {\n\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t} catch (error) {\n\t\t\t// noop, happen only when the user is not in a project\n\t\t}\n\n\t\tconst payload: {\n\t\t\tgroupId?: string;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\ttraits?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\ttraits: args,\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.groupId = repositoryName;\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\tthis._segmentClient().group(\n\t\t\t\tpayload as GroupParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(`An error occurred during Segment group`, maybeError);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tasync checkIsTelemetryEnabled(): Promise<boolean> {\n\t\tlet root: string;\n\t\ttry {\n\t\t\troot = await this.project\n\t\t\t\t.getRoot()\n\t\t\t\t.catch(() => this.project.suggestRoot());\n\n\t\t\treturn readPrismicrc(root).telemetry !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate initExperiment(): void {\n\t\ttry {\n\t\t\tthis._experiment = Experiment.initializeRemote(API_TOKENS.AmplitudeKey);\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Error initializing experiment\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getExperimentVariant(variantKey: string): Promise<Variant | undefined> {\n\t\tif (this._experiment) {\n\t\t\ttry {\n\t\t\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\t\t\tconst variants = await this._experiment.fetchV2({\n\t\t\t\t\tuser_id: this._userID,\n\t\t\t\t\tuser_properties: {\n\t\t\t\t\t\tRepository: repositoryName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tconst variantValue = variants[variantKey].value;\n\t\t\t\tif (variantValue) {\n\t\t\t\t\tawait this.track({\n\t\t\t\t\t\tevent: \"experiment:exposure\",\n\t\t\t\t\t\tflag_key: variantKey,\n\t\t\t\t\t\tvariant: variantValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn variants[variantKey];\n\t\t\t} catch (error) {\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(\"Error fetching experiment variant\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n"],"names":["BaseManager","Analytics","API_TOKENS","randomUUID","HumanSegmentEventType","readPrismicrc","Experiment"],"mappings":";;;;;;;;;;;;;;;;AAiDA,SAAS,2BACR,eAA4C;AAE5C,MAAI,kBAAkB,QAAW;AAC1B,UAAA,IAAI,MACT,kIAAkI;AAAA,EAEpI;AACD;AAEM,MAAO,yBAAyBA,YAAAA,YAAW;AAAA,EAA3C;AAAA;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B,OAAO;AAAA,MAIhB;AAAA,IACD;AAEO,WAAA;AAAA,EACR;AACA;;"}
1
+ {"version":3,"file":"TelemetryManager.cjs","sources":["../../../../src/managers/telemetry/TelemetryManager.ts"],"sourcesContent":["import {\n\tExperiment,\n\tRemoteEvaluationClient,\n\tVariant,\n} from \"@amplitude/experiment-node-server\";\nimport { randomUUID } from \"node:crypto\";\nimport { Analytics, GroupParams, TrackParams } from \"@segment/analytics-node\";\n\nimport { readPrismicrc } from \"../../lib/prismicrc\";\n\nimport { API_TOKENS } from \"../../constants/API_TOKENS\";\n\nimport { BaseManager } from \"../BaseManager\";\n\nimport {\n\tHumanSegmentEventType,\n\tHumanSegmentEventTypes,\n\tSegmentEvents,\n} from \"./types\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype TelemetryManagerInitTelemetryArgs = {\n\tappName: string;\n\tappVersion: string;\n};\n\ntype TelemetryManagerTrackArgs = SegmentEvents & {\n\t_includeEnvironmentKind?: boolean;\n};\n\ntype TelemetryManagerIdentifyArgs = {\n\tuserID: string;\n\tintercomHash: string;\n};\n\ntype TelemetryManagerGroupArgs = {\n\tmanualLibsCount: number;\n\tdownloadedLibsCount: number;\n\tnpmLibsCount: number;\n\tdownloadedLibs: string[];\n};\n\ntype TelemetryManagerContext = {\n\tapp: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n};\n\nfunction assertTelemetryInitialized(\n\tsegmentClient: (() => Analytics) | undefined,\n): asserts segmentClient is NonNullable<typeof segmentClient> {\n\tif (segmentClient === undefined) {\n\t\tthrow new Error(\n\t\t\t\"Telemetry has not been initialized. Run `SliceMachineManager.telemetry.prototype.initTelemetry()` before re-calling this method.\",\n\t\t);\n\t}\n}\n\nexport class TelemetryManager extends BaseManager {\n\tprivate _segmentClient: (() => Analytics) | undefined = undefined;\n\tprivate _anonymousID: string | undefined = undefined;\n\tprivate _userID: string | undefined = undefined;\n\tprivate _context: TelemetryManagerContext | undefined = undefined;\n\tprivate _experiment: RemoteEvaluationClient | undefined = undefined;\n\n\tasync initTelemetry(args: TelemetryManagerInitTelemetryArgs): Promise<void> {\n\t\tconst isTelemetryEnabled = await this.checkIsTelemetryEnabled();\n\n\t\tthis._segmentClient = () => {\n\t\t\tconst analytics = new Analytics({\n\t\t\t\twriteKey: API_TOKENS.SegmentKey,\n\t\t\t\t// Since it's a local app, we do not benefit from event batching the way a server would normally do, all tracking event will be awaited.\n\t\t\t\tmaxEventsInBatch: 1,\n\t\t\t\t// TODO: Verify that this actually does not send data to Segment when false.\n\t\t\t\tdisable: !isTelemetryEnabled,\n\t\t\t});\n\n\t\t\tanalytics.on(\"error\", (error) => {\n\t\t\t\t// noop - We don't care if the tracking event\n\t\t\t\t// failed. Some users or networks intentionally\n\t\t\t\t// block Segment, so we can't block the app if\n\t\t\t\t// a tracking event is unsuccessful.\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(`An error occurred with Segment`, error);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn analytics;\n\t\t};\n\n\t\tif (isTelemetryEnabled) {\n\t\t\tthis.initExperiment();\n\t\t}\n\n\t\tthis._anonymousID = randomUUID();\n\t\tthis._context = { app: { name: args.appName, version: args.appVersion } };\n\t}\n\n\t// TODO: Should `userId` be automatically populated by the logged in\n\t// user? We already have their info via UserRepository.\n\tasync track(args: TelemetryManagerTrackArgs): Promise<void> {\n\t\tconst { event, repository, _includeEnvironmentKind, ...properties } = args;\n\t\tlet repositoryName = repository;\n\n\t\tif (repositoryName === undefined) {\n\t\t\ttry {\n\t\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t\t} catch (error) {\n\t\t\t\t// noop, happen only when the user is not in a project\n\t\t\t}\n\t\t}\n\n\t\tlet environmentKind: Environment[\"kind\"] | \"_unknown\" | undefined =\n\t\t\tundefined;\n\t\tif (_includeEnvironmentKind) {\n\t\t\tif (this.project.checkSupportsEnvironments()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst activeEnvironmentResult =\n\t\t\t\t\t\tawait this.project.fetchActiveEnvironment();\n\n\t\t\t\t\tif (activeEnvironmentResult.type === \"ok\") {\n\t\t\t\t\t\tenvironmentKind = activeEnvironmentResult.activeEnvironment.kind;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow activeEnvironmentResult.error;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tenvironmentKind = \"_unknown\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Assume only the production environment can be\n\t\t\t\t// used if the project's adapter does not\n\t\t\t\t// support environments.\n\t\t\t\tenvironmentKind = \"prod\";\n\t\t\t}\n\t\t}\n\n\t\tconst payload: {\n\t\t\tevent: HumanSegmentEventTypes;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\tproperties?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\tevent: HumanSegmentEventType[event],\n\t\t\tproperties: {\n\t\t\t\tnodeVersion: process.versions.node,\n\t\t\t\tenvironmentKind,\n\t\t\t\t...properties,\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().track(\n\t\t\t\tpayload as TrackParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`An error occurred during Segment tracking`,\n\t\t\t\t\t\t\tmaybeError,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// TODO: Should `userID` and `intercomHash` be automatically populated\n\t// by the logged in user? We already have their info via\n\t// UserRepository.\n\tidentify(args: TelemetryManagerIdentifyArgs): Promise<void> {\n\t\tconst payload = {\n\t\t\tuserId: args.userID,\n\t\t\tanonymousId: this._anonymousID,\n\t\t\tintegrations: {\n\t\t\t\tIntercom: {\n\t\t\t\t\tuser_hash: args.intercomHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tthis._userID = args.userID;\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().identify(payload, (maybeError?: unknown) => {\n\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\tconsole.warn(`An error occurred during Segment identify`, maybeError);\n\t\t\t\t}\n\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\tasync group(args: TelemetryManagerGroupArgs): Promise<void> {\n\t\tlet repositoryName;\n\n\t\ttry {\n\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t} catch (error) {\n\t\t\t// noop, happen only when the user is not in a project\n\t\t}\n\n\t\tconst payload: {\n\t\t\tgroupId?: string;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\ttraits?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\ttraits: args,\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.groupId = repositoryName;\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\tthis._segmentClient().group(\n\t\t\t\tpayload as GroupParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(`An error occurred during Segment group`, maybeError);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tasync checkIsTelemetryEnabled(): Promise<boolean> {\n\t\tlet root: string;\n\t\ttry {\n\t\t\troot = await this.project\n\t\t\t\t.getRoot()\n\t\t\t\t.catch(() => this.project.suggestRoot());\n\n\t\t\treturn readPrismicrc(root).telemetry !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate initExperiment(): void {\n\t\ttry {\n\t\t\tthis._experiment = Experiment.initializeRemote(API_TOKENS.AmplitudeKey);\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Error initializing experiment\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getExperimentVariant(variantKey: string): Promise<Variant | undefined> {\n\t\tif (this._experiment) {\n\t\t\ttry {\n\t\t\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\t\t\tconst variants = await this._experiment.fetchV2({\n\t\t\t\t\tuser_id: this._userID,\n\t\t\t\t\tuser_properties: {\n\t\t\t\t\t\tRepository: repositoryName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tconst variantValue = variants[variantKey].value;\n\t\t\t\tif (variantValue) {\n\t\t\t\t\tawait this.track({\n\t\t\t\t\t\tevent: \"experiment:exposure\",\n\t\t\t\t\t\tflag_key: variantKey,\n\t\t\t\t\t\tvariant: variantValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn variants[variantKey];\n\t\t\t} catch (error) {\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(\"Error fetching experiment variant\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n"],"names":["BaseManager","Analytics","API_TOKENS","randomUUID","HumanSegmentEventType","readPrismicrc","Experiment"],"mappings":";;;;;;;;;;;;;;;;AAiDA,SAAS,2BACR,eAA4C;AAE5C,MAAI,kBAAkB,QAAW;AAC1B,UAAA,IAAI,MACT,kIAAkI;AAAA,EAEpI;AACD;AAEM,MAAO,yBAAyBA,YAAAA,YAAW;AAAA,EAA3C;AAAA;AACG;AACA;AACA;AACA;AACA;AAAA;AAAA,EAER,MAAM,cAAc,MAAuC;AACpD,UAAA,qBAAqB,MAAM,KAAK;AAEtC,SAAK,iBAAiB,MAAK;AACpB,YAAA,YAAY,IAAIC,wBAAU;AAAA,QAC/B,UAAUC,WAAW,WAAA;AAAA;AAAA,QAErB,kBAAkB;AAAA;AAAA,QAElB,SAAS,CAAC;AAAA,MAAA,CACV;AAES,gBAAA,GAAG,SAAS,CAAC,UAAS;AAAA,MAO/B,CACA;AAEM,aAAA;AAAA,IAAA;AAGR,QAAI,oBAAoB;AACvB,WAAK,eAAc;AAAA,IACpB;AAEA,SAAK,eAAeC,OAAAA;AACf,SAAA,WAAW,EAAE,KAAK,EAAE,MAAM,KAAK,SAAS,SAAS,KAAK;EAC5D;AAAA;AAAA;AAAA,EAIA,MAAM,MAAM,MAA+B;;AAC1C,UAAM,EAAE,OAAO,YAAY,yBAAyB,GAAG,WAAe,IAAA;AACtE,QAAI,iBAAiB;AAErB,QAAI,mBAAmB,QAA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R;AAAA,EACD;AAAA,EAEQ,iBAAc;AACjB,QAAA;AACH,WAAK,cAAcC,MAAA,UAAA,WAAW,iBAAiBJ,WAAA,WAAW,YAAY;AAAA,aAC9D,OAAO;AAAA,IAIhB;AAAA,EACD;AAAA,EAEA,MAAM,qBAAqB,YAAkB;AAC5C,QAAI,KAAK,aAAa;AACjB,UAAA;AACH,cAAM,iBAAiB,MAAM,KAAK,QAAQ,kBAAiB;AAC3D,cAAM,WAAW,MAAM,KAAK,YAAY,QAAQ;AAAA,UAC/C,SAAS,KAAK;AAAA,UACd,iBAAiB;AAAA,YAChB,YAAY;AAAA,UACZ;AAAA,QAAA,CACD;AAEK,cAAA,eAAe,SAAS,UAAU,EAAE;AAC1C,YAAI,cAAc;AACjB,gBAAM,KAAK,MAAM;AAAA,YAChB,OAAO;AAAA,YACP,UAAU;AAAA,YACV,SAAS;AAAA,UAAA,CACT;AAAA,QACF;AAEA,eAAO,SAAS,UAAU;AAAA,eAClB,OAAO;AAAA,MAIhB;AAAA,IACD;AAEO,WAAA;AAAA,EACR;AACA;;"}
@@ -64,7 +64,7 @@ class TelemetryManager extends BaseManager {
64
64
  try {
65
65
  const activeEnvironmentResult = await this.project.fetchActiveEnvironment();
66
66
  if (activeEnvironmentResult.type === "ok") {
67
- environmentKind = activeEnvironmentResult.environment.kind;
67
+ environmentKind = activeEnvironmentResult.activeEnvironment.kind;
68
68
  } else {
69
69
  throw activeEnvironmentResult.error;
70
70
  }
@@ -1 +1 @@
1
- {"version":3,"file":"TelemetryManager.js","sources":["../../../../src/managers/telemetry/TelemetryManager.ts"],"sourcesContent":["import {\n\tExperiment,\n\tRemoteEvaluationClient,\n\tVariant,\n} from \"@amplitude/experiment-node-server\";\nimport { randomUUID } from \"node:crypto\";\nimport { Analytics, GroupParams, TrackParams } from \"@segment/analytics-node\";\n\nimport { readPrismicrc } from \"../../lib/prismicrc\";\n\nimport { API_TOKENS } from \"../../constants/API_TOKENS\";\n\nimport { BaseManager } from \"../BaseManager\";\n\nimport {\n\tHumanSegmentEventType,\n\tHumanSegmentEventTypes,\n\tSegmentEvents,\n} from \"./types\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype TelemetryManagerInitTelemetryArgs = {\n\tappName: string;\n\tappVersion: string;\n};\n\ntype TelemetryManagerTrackArgs = SegmentEvents & {\n\t_includeEnvironmentKind?: boolean;\n};\n\ntype TelemetryManagerIdentifyArgs = {\n\tuserID: string;\n\tintercomHash: string;\n};\n\ntype TelemetryManagerGroupArgs = {\n\tmanualLibsCount: number;\n\tdownloadedLibsCount: number;\n\tnpmLibsCount: number;\n\tdownloadedLibs: string[];\n};\n\ntype TelemetryManagerContext = {\n\tapp: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n};\n\nfunction assertTelemetryInitialized(\n\tsegmentClient: (() => Analytics) | undefined,\n): asserts segmentClient is NonNullable<typeof segmentClient> {\n\tif (segmentClient === undefined) {\n\t\tthrow new Error(\n\t\t\t\"Telemetry has not been initialized. Run `SliceMachineManager.telemetry.prototype.initTelemetry()` before re-calling this method.\",\n\t\t);\n\t}\n}\n\nexport class TelemetryManager extends BaseManager {\n\tprivate _segmentClient: (() => Analytics) | undefined = undefined;\n\tprivate _anonymousID: string | undefined = undefined;\n\tprivate _userID: string | undefined = undefined;\n\tprivate _context: TelemetryManagerContext | undefined = undefined;\n\tprivate _experiment: RemoteEvaluationClient | undefined = undefined;\n\n\tasync initTelemetry(args: TelemetryManagerInitTelemetryArgs): Promise<void> {\n\t\tconst isTelemetryEnabled = await this.checkIsTelemetryEnabled();\n\n\t\tthis._segmentClient = () => {\n\t\t\tconst analytics = new Analytics({\n\t\t\t\twriteKey: API_TOKENS.SegmentKey,\n\t\t\t\t// Since it's a local app, we do not benefit from event batching the way a server would normally do, all tracking event will be awaited.\n\t\t\t\tmaxEventsInBatch: 1,\n\t\t\t\t// TODO: Verify that this actually does not send data to Segment when false.\n\t\t\t\tdisable: !isTelemetryEnabled,\n\t\t\t});\n\n\t\t\tanalytics.on(\"error\", (error) => {\n\t\t\t\t// noop - We don't care if the tracking event\n\t\t\t\t// failed. Some users or networks intentionally\n\t\t\t\t// block Segment, so we can't block the app if\n\t\t\t\t// a tracking event is unsuccessful.\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(`An error occurred with Segment`, error);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn analytics;\n\t\t};\n\n\t\tif (isTelemetryEnabled) {\n\t\t\tthis.initExperiment();\n\t\t}\n\n\t\tthis._anonymousID = randomUUID();\n\t\tthis._context = { app: { name: args.appName, version: args.appVersion } };\n\t}\n\n\t// TODO: Should `userId` be automatically populated by the logged in\n\t// user? We already have their info via UserRepository.\n\tasync track(args: TelemetryManagerTrackArgs): Promise<void> {\n\t\tconst { event, repository, _includeEnvironmentKind, ...properties } = args;\n\t\tlet repositoryName = repository;\n\n\t\tif (repositoryName === undefined) {\n\t\t\ttry {\n\t\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t\t} catch (error) {\n\t\t\t\t// noop, happen only when the user is not in a project\n\t\t\t}\n\t\t}\n\n\t\tlet environmentKind: Environment[\"kind\"] | \"_unknown\" | undefined =\n\t\t\tundefined;\n\t\tif (_includeEnvironmentKind) {\n\t\t\tif (this.project.checkSupportsEnvironments()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst activeEnvironmentResult =\n\t\t\t\t\t\tawait this.project.fetchActiveEnvironment();\n\n\t\t\t\t\tif (activeEnvironmentResult.type === \"ok\") {\n\t\t\t\t\t\tenvironmentKind = activeEnvironmentResult.environment.kind;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow activeEnvironmentResult.error;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tenvironmentKind = \"_unknown\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Assume only the production environment can be\n\t\t\t\t// used if the project's adapter does not\n\t\t\t\t// support environments.\n\t\t\t\tenvironmentKind = \"prod\";\n\t\t\t}\n\t\t}\n\n\t\tconst payload: {\n\t\t\tevent: HumanSegmentEventTypes;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\tproperties?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\tevent: HumanSegmentEventType[event],\n\t\t\tproperties: {\n\t\t\t\tnodeVersion: process.versions.node,\n\t\t\t\tenvironmentKind,\n\t\t\t\t...properties,\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().track(\n\t\t\t\tpayload as TrackParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`An error occurred during Segment tracking`,\n\t\t\t\t\t\t\tmaybeError,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// TODO: Should `userID` and `intercomHash` be automatically populated\n\t// by the logged in user? We already have their info via\n\t// UserRepository.\n\tidentify(args: TelemetryManagerIdentifyArgs): Promise<void> {\n\t\tconst payload = {\n\t\t\tuserId: args.userID,\n\t\t\tanonymousId: this._anonymousID,\n\t\t\tintegrations: {\n\t\t\t\tIntercom: {\n\t\t\t\t\tuser_hash: args.intercomHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tthis._userID = args.userID;\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().identify(payload, (maybeError?: unknown) => {\n\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\tconsole.warn(`An error occurred during Segment identify`, maybeError);\n\t\t\t\t}\n\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\tasync group(args: TelemetryManagerGroupArgs): Promise<void> {\n\t\tlet repositoryName;\n\n\t\ttry {\n\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t} catch (error) {\n\t\t\t// noop, happen only when the user is not in a project\n\t\t}\n\n\t\tconst payload: {\n\t\t\tgroupId?: string;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\ttraits?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\ttraits: args,\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.groupId = repositoryName;\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\tthis._segmentClient().group(\n\t\t\t\tpayload as GroupParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(`An error occurred during Segment group`, maybeError);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tasync checkIsTelemetryEnabled(): Promise<boolean> {\n\t\tlet root: string;\n\t\ttry {\n\t\t\troot = await this.project\n\t\t\t\t.getRoot()\n\t\t\t\t.catch(() => this.project.suggestRoot());\n\n\t\t\treturn readPrismicrc(root).telemetry !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate initExperiment(): void {\n\t\ttry {\n\t\t\tthis._experiment = Experiment.initializeRemote(API_TOKENS.AmplitudeKey);\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Error initializing experiment\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getExperimentVariant(variantKey: string): Promise<Variant | undefined> {\n\t\tif (this._experiment) {\n\t\t\ttry {\n\t\t\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\t\t\tconst variants = await this._experiment.fetchV2({\n\t\t\t\t\tuser_id: this._userID,\n\t\t\t\t\tuser_properties: {\n\t\t\t\t\t\tRepository: repositoryName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tconst variantValue = variants[variantKey].value;\n\t\t\t\tif (variantValue) {\n\t\t\t\t\tawait this.track({\n\t\t\t\t\t\tevent: \"experiment:exposure\",\n\t\t\t\t\t\tflag_key: variantKey,\n\t\t\t\t\t\tvariant: variantValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn variants[variantKey];\n\t\t\t} catch (error) {\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(\"Error fetching experiment variant\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n"],"names":["Experiment"],"mappings":";;;;;;;;;;;;;;A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AAAA,YAChB,OAAO;AAAA,YACP,UAAU;AAAA,YACV,SAAS;AAAA,UAAA,CACT;AAAA,QACF;AAEA,eAAO,SAAS,UAAU;AAAA,eAClB,OAAO;AAAA,MAIhB;AAAA,IACD;AAEO,WAAA;AAAA,EACR;AACA;"}
1
+ {"version":3,"file":"TelemetryManager.js","sources":["../../../../src/managers/telemetry/TelemetryManager.ts"],"sourcesContent":["import {\n\tExperiment,\n\tRemoteEvaluationClient,\n\tVariant,\n} from \"@amplitude/experiment-node-server\";\nimport { randomUUID } from \"node:crypto\";\nimport { Analytics, GroupParams, TrackParams } from \"@segment/analytics-node\";\n\nimport { readPrismicrc } from \"../../lib/prismicrc\";\n\nimport { API_TOKENS } from \"../../constants/API_TOKENS\";\n\nimport { BaseManager } from \"../BaseManager\";\n\nimport {\n\tHumanSegmentEventType,\n\tHumanSegmentEventTypes,\n\tSegmentEvents,\n} from \"./types\";\nimport { Environment } from \"../prismicRepository/types\";\n\ntype TelemetryManagerInitTelemetryArgs = {\n\tappName: string;\n\tappVersion: string;\n};\n\ntype TelemetryManagerTrackArgs = SegmentEvents & {\n\t_includeEnvironmentKind?: boolean;\n};\n\ntype TelemetryManagerIdentifyArgs = {\n\tuserID: string;\n\tintercomHash: string;\n};\n\ntype TelemetryManagerGroupArgs = {\n\tmanualLibsCount: number;\n\tdownloadedLibsCount: number;\n\tnpmLibsCount: number;\n\tdownloadedLibs: string[];\n};\n\ntype TelemetryManagerContext = {\n\tapp: {\n\t\tname: string;\n\t\tversion: string;\n\t};\n};\n\nfunction assertTelemetryInitialized(\n\tsegmentClient: (() => Analytics) | undefined,\n): asserts segmentClient is NonNullable<typeof segmentClient> {\n\tif (segmentClient === undefined) {\n\t\tthrow new Error(\n\t\t\t\"Telemetry has not been initialized. Run `SliceMachineManager.telemetry.prototype.initTelemetry()` before re-calling this method.\",\n\t\t);\n\t}\n}\n\nexport class TelemetryManager extends BaseManager {\n\tprivate _segmentClient: (() => Analytics) | undefined = undefined;\n\tprivate _anonymousID: string | undefined = undefined;\n\tprivate _userID: string | undefined = undefined;\n\tprivate _context: TelemetryManagerContext | undefined = undefined;\n\tprivate _experiment: RemoteEvaluationClient | undefined = undefined;\n\n\tasync initTelemetry(args: TelemetryManagerInitTelemetryArgs): Promise<void> {\n\t\tconst isTelemetryEnabled = await this.checkIsTelemetryEnabled();\n\n\t\tthis._segmentClient = () => {\n\t\t\tconst analytics = new Analytics({\n\t\t\t\twriteKey: API_TOKENS.SegmentKey,\n\t\t\t\t// Since it's a local app, we do not benefit from event batching the way a server would normally do, all tracking event will be awaited.\n\t\t\t\tmaxEventsInBatch: 1,\n\t\t\t\t// TODO: Verify that this actually does not send data to Segment when false.\n\t\t\t\tdisable: !isTelemetryEnabled,\n\t\t\t});\n\n\t\t\tanalytics.on(\"error\", (error) => {\n\t\t\t\t// noop - We don't care if the tracking event\n\t\t\t\t// failed. Some users or networks intentionally\n\t\t\t\t// block Segment, so we can't block the app if\n\t\t\t\t// a tracking event is unsuccessful.\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(`An error occurred with Segment`, error);\n\t\t\t\t}\n\t\t\t});\n\n\t\t\treturn analytics;\n\t\t};\n\n\t\tif (isTelemetryEnabled) {\n\t\t\tthis.initExperiment();\n\t\t}\n\n\t\tthis._anonymousID = randomUUID();\n\t\tthis._context = { app: { name: args.appName, version: args.appVersion } };\n\t}\n\n\t// TODO: Should `userId` be automatically populated by the logged in\n\t// user? We already have their info via UserRepository.\n\tasync track(args: TelemetryManagerTrackArgs): Promise<void> {\n\t\tconst { event, repository, _includeEnvironmentKind, ...properties } = args;\n\t\tlet repositoryName = repository;\n\n\t\tif (repositoryName === undefined) {\n\t\t\ttry {\n\t\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t\t} catch (error) {\n\t\t\t\t// noop, happen only when the user is not in a project\n\t\t\t}\n\t\t}\n\n\t\tlet environmentKind: Environment[\"kind\"] | \"_unknown\" | undefined =\n\t\t\tundefined;\n\t\tif (_includeEnvironmentKind) {\n\t\t\tif (this.project.checkSupportsEnvironments()) {\n\t\t\t\ttry {\n\t\t\t\t\tconst activeEnvironmentResult =\n\t\t\t\t\t\tawait this.project.fetchActiveEnvironment();\n\n\t\t\t\t\tif (activeEnvironmentResult.type === \"ok\") {\n\t\t\t\t\t\tenvironmentKind = activeEnvironmentResult.activeEnvironment.kind;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tthrow activeEnvironmentResult.error;\n\t\t\t\t\t}\n\t\t\t\t} catch {\n\t\t\t\t\tenvironmentKind = \"_unknown\";\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Assume only the production environment can be\n\t\t\t\t// used if the project's adapter does not\n\t\t\t\t// support environments.\n\t\t\t\tenvironmentKind = \"prod\";\n\t\t\t}\n\t\t}\n\n\t\tconst payload: {\n\t\t\tevent: HumanSegmentEventTypes;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\tproperties?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\tevent: HumanSegmentEventType[event],\n\t\t\tproperties: {\n\t\t\t\tnodeVersion: process.versions.node,\n\t\t\t\tenvironmentKind,\n\t\t\t\t...properties,\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().track(\n\t\t\t\tpayload as TrackParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t\t`An error occurred during Segment tracking`,\n\t\t\t\t\t\t\tmaybeError,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\t// TODO: Should `userID` and `intercomHash` be automatically populated\n\t// by the logged in user? We already have their info via\n\t// UserRepository.\n\tidentify(args: TelemetryManagerIdentifyArgs): Promise<void> {\n\t\tconst payload = {\n\t\t\tuserId: args.userID,\n\t\t\tanonymousId: this._anonymousID,\n\t\t\tintegrations: {\n\t\t\t\tIntercom: {\n\t\t\t\t\tuser_hash: args.intercomHash,\n\t\t\t\t},\n\t\t\t},\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tthis._userID = args.userID;\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\t// TODO: Make sure client fails gracefully when no internet connection\n\t\t\tthis._segmentClient().identify(payload, (maybeError?: unknown) => {\n\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\tconsole.warn(`An error occurred during Segment identify`, maybeError);\n\t\t\t\t}\n\n\t\t\t\tresolve();\n\t\t\t});\n\t\t});\n\t}\n\n\tasync group(args: TelemetryManagerGroupArgs): Promise<void> {\n\t\tlet repositoryName;\n\n\t\ttry {\n\t\t\trepositoryName = await this.project.getRepositoryName();\n\t\t} catch (error) {\n\t\t\t// noop, happen only when the user is not in a project\n\t\t}\n\n\t\tconst payload: {\n\t\t\tgroupId?: string;\n\t\t\tuserId?: string;\n\t\t\tanonymousId?: string;\n\t\t\ttraits?: Record<string, unknown>;\n\t\t\tcontext?: Partial<TelemetryManagerContext> & {\n\t\t\t\tgroupId?: {\n\t\t\t\t\tRepository?: string;\n\t\t\t\t};\n\t\t\t};\n\t\t} = {\n\t\t\ttraits: args,\n\t\t\tcontext: { ...this._context },\n\t\t};\n\n\t\tif (this._userID) {\n\t\t\tpayload.userId = this._userID;\n\t\t} else {\n\t\t\tpayload.anonymousId = this._anonymousID;\n\t\t}\n\n\t\tif (repositoryName) {\n\t\t\tpayload.groupId = repositoryName;\n\t\t\tpayload.context ||= {};\n\t\t\tpayload.context.groupId ||= {};\n\t\t\tpayload.context.groupId.Repository = repositoryName;\n\t\t}\n\n\t\treturn new Promise((resolve) => {\n\t\t\tassertTelemetryInitialized(this._segmentClient);\n\n\t\t\tthis._segmentClient().group(\n\t\t\t\tpayload as GroupParams,\n\t\t\t\t(maybeError?: unknown) => {\n\t\t\t\t\tif (maybeError && import.meta.env.DEV) {\n\t\t\t\t\t\t// TODO: Not sure how we want to deal with that\n\t\t\t\t\t\tconsole.warn(`An error occurred during Segment group`, maybeError);\n\t\t\t\t\t}\n\n\t\t\t\t\tresolve();\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t}\n\n\tasync checkIsTelemetryEnabled(): Promise<boolean> {\n\t\tlet root: string;\n\t\ttry {\n\t\t\troot = await this.project\n\t\t\t\t.getRoot()\n\t\t\t\t.catch(() => this.project.suggestRoot());\n\n\t\t\treturn readPrismicrc(root).telemetry !== false;\n\t\t} catch {\n\t\t\treturn true;\n\t\t}\n\t}\n\n\tprivate initExperiment(): void {\n\t\ttry {\n\t\t\tthis._experiment = Experiment.initializeRemote(API_TOKENS.AmplitudeKey);\n\t\t} catch (error) {\n\t\t\tif (import.meta.env.DEV) {\n\t\t\t\tconsole.error(\"Error initializing experiment\", error);\n\t\t\t}\n\t\t}\n\t}\n\n\tasync getExperimentVariant(variantKey: string): Promise<Variant | undefined> {\n\t\tif (this._experiment) {\n\t\t\ttry {\n\t\t\t\tconst repositoryName = await this.project.getRepositoryName();\n\t\t\t\tconst variants = await this._experiment.fetchV2({\n\t\t\t\t\tuser_id: this._userID,\n\t\t\t\t\tuser_properties: {\n\t\t\t\t\t\tRepository: repositoryName,\n\t\t\t\t\t},\n\t\t\t\t});\n\n\t\t\t\tconst variantValue = variants[variantKey].value;\n\t\t\t\tif (variantValue) {\n\t\t\t\t\tawait this.track({\n\t\t\t\t\t\tevent: \"experiment:exposure\",\n\t\t\t\t\t\tflag_key: variantKey,\n\t\t\t\t\t\tvariant: variantValue,\n\t\t\t\t\t});\n\t\t\t\t}\n\n\t\t\t\treturn variants[variantKey];\n\t\t\t} catch (error) {\n\t\t\t\tif (import.meta.env.DEV) {\n\t\t\t\t\tconsole.error(\"Error fetching experiment variant\", error);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n"],"names":["Experiment"],"mappings":";;;;;;;;;;;;;;AAiDA,SAAS,2BACR,eAA4C;AAE5C,MAAI,kBAAkB,QAAW;AAC1B,UAAA,IAAI,MACT,kIAAkI;AAAA,EAEpI;AACD;AAEM,MAAO,yBAAyB,YAAW;AAAA,EAA3C;AAAA;AACG;AACA;AACA;AACA;AACA;AAAA;AAAA,EAER,MAAM,cAAc,MAAuC;AACpD,UAAA,qBAAqB,MAAM,KAAK;AAEtC,SAAK,iBAAiB,MAAK;AACpB,YAAA,YAAY,IAAI,UAAU;AAAA,QAC/B,UAAU,WAAW;AAAA;AAAA,QAErB,kBAAkB;AAAA;AAAA,QAElB,SAAS,CAAC;AAAA,MAAA,CACV;AAES,gBAAA,GAAG,SAAS,CAAC,UAAS;AAAA,MAO/B,CACA;AAEM,aAAA;AAAA,IAAA;AAGR,QAAI,oBAAoB;AACvB,WAAK,eAAc;AAAA,IACpB;AAEA,SAAK,eAAe;AACf,SAAA,WAAW,EAAE,KAAK,EAAE,MAAM,KAAK,SAAS,SAAS,KAAK;EAC5D;AAAA;AAAA;AAAA,EAIA,MAAM,MAAM,MAA+B;;AAC1C,UAAM,EAAE,OAAO,YAAY,yBAAyB,GAAG,WAAe,IAAA;AACtE,QAAI,iBAA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AClC;AACA,aAAA;AAAA,IACR;AAAA,EACD;AAAA,EAEQ,iBAAc;AACjB,QAAA;AACH,WAAK,cAAcA,IAAA,WAAW,iBAAiB,WAAW,YAAY;AAAA,aAC9D,OAAO;AAAA,IAIhB;AAAA,EACD;AAAA,EAEA,MAAM,qBAAqB,YAAkB;AAC5C,QAAI,KAAK,aAAa;AACjB,UAAA;AACH,cAAM,iBAAiB,MAAM,KAAK,QAAQ,kBAAiB;AAC3D,cAAM,WAAW,MAAM,KAAK,YAAY,QAAQ;AAAA,UAC/C,SAAS,KAAK;AAAA,UACd,iBAAiB;AAAA,YAChB,YAAY;AAAA,UACZ;AAAA,QAAA,CACD;AAEK,cAAA,eAAe,SAAS,UAAU,EAAE;AAC1C,YAAI,cAAc;AACjB,gBAAM,KAAK,MAAM;AAAA,YAChB,OAAO;AAAA,YACP,UAAU;AAAA,YACV,SAAS;AAAA,UAAA,CACT;AAAA,QACF;AAEA,eAAO,SAAS,UAAU;AAAA,eAClB,OAAO;AAAA,MAIhB;AAAA,IACD;AAEO,WAAA;AAAA,EACR;AACA;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slicemachine/manager",
3
- "version": "0.25.2-alpha.xru-fix-sm-invalid-env.5",
3
+ "version": "0.25.2-alpha.xru-fix-sm-invalid-env.6",
4
4
  "description": "Manage all aspects of a Slice Machine project.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -70,7 +70,7 @@
70
70
  "@prismicio/mocks": "2.14.0",
71
71
  "@prismicio/types-internal": "3.11.2",
72
72
  "@segment/analytics-node": "^2.1.2",
73
- "@slicemachine/plugin-kit": "0.4.80-alpha.xru-fix-sm-invalid-env.5",
73
+ "@slicemachine/plugin-kit": "0.4.80-alpha.xru-fix-sm-invalid-env.6",
74
74
  "cookie": "^1.0.1",
75
75
  "cors": "^2.8.5",
76
76
  "execa": "^7.1.1",
@@ -86,7 +86,7 @@ type ProjectManagerUpdateEnvironmentArgs = {
86
86
  };
87
87
 
88
88
  type ProjectManagerFetchActiveEnvironmentReturnType =
89
- | { type: "ok"; environment: Environment }
89
+ | { type: "ok"; activeEnvironment: Environment }
90
90
  | { type: "error"; error: InvalidActiveEnvironmentError };
91
91
 
92
92
  export class ProjectManager extends BaseManager {
@@ -451,7 +451,7 @@ export class ProjectManager extends BaseManager {
451
451
  this._cachedEnvironments || [],
452
452
  );
453
453
  if (cachedActiveEnvironment) {
454
- return { type: "ok", environment: cachedActiveEnvironment };
454
+ return { type: "ok", activeEnvironment: cachedActiveEnvironment };
455
455
  }
456
456
 
457
457
  // If the environment is not in the cached environments list, we
@@ -478,7 +478,7 @@ export class ProjectManager extends BaseManager {
478
478
  };
479
479
  }
480
480
 
481
- return { type: "ok", environment: activeEnvironment };
481
+ return { type: "ok", activeEnvironment: activeEnvironment };
482
482
  }
483
483
 
484
484
  async detectVersionControlSystem(): Promise<string | "_unknown"> {
@@ -120,7 +120,7 @@ export class TelemetryManager extends BaseManager {
120
120
  await this.project.fetchActiveEnvironment();
121
121
 
122
122
  if (activeEnvironmentResult.type === "ok") {
123
- environmentKind = activeEnvironmentResult.environment.kind;
123
+ environmentKind = activeEnvironmentResult.activeEnvironment.kind;
124
124
  } else {
125
125
  throw activeEnvironmentResult.error;
126
126
  }