@shopify/cli-kit 3.85.4 → 3.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ import { temporaryDirectory, temporaryDirectoryTask } from 'tempy';
9
9
  import { sep, join } from 'pathe';
10
10
  import { findUp as internalFindUp } from 'find-up';
11
11
  import { minimatch } from 'minimatch';
12
- import { mkdirSync as fsMkdirSync, readFileSync as fsReadFileSync, writeFileSync as fsWriteFileSync, appendFileSync as fsAppendFileSync, statSync as fsStatSync, createReadStream as fsCreateReadStream, createWriteStream as fsCreateWriteStream, constants as fsConstants, existsSync as fsFileExistsSync, unlinkSync as fsUnlinkSync, } from 'fs';
12
+ import { mkdirSync as fsMkdirSync, readFileSync as fsReadFileSync, writeFileSync as fsWriteFileSync, appendFileSync as fsAppendFileSync, statSync as fsStatSync, createReadStream as fsCreateReadStream, createWriteStream as fsCreateWriteStream, constants as fsConstants, existsSync as fsFileExistsSync, unlinkSync as fsUnlinkSync, accessSync, statSync, } from 'fs';
13
13
  import { mkdir as fsMkdir, writeFile as fsWriteFile, readFile as fsReadFile, realpath as fsRealPath, appendFile as fsAppendFile, mkdtemp as fsMkdtemp, stat as fsStat, lstat as fsLstat, chmod as fsChmod, access as fsAccess, rename as fsRename, unlink as fsUnlink, readdir as fsReaddir, } from 'fs/promises';
14
14
  import { pathToFileURL as pathToFile } from 'url';
15
15
  import * as os from 'os';
@@ -337,6 +337,32 @@ export async function fileHasExecutablePermissions(path) {
337
337
  return false;
338
338
  }
339
339
  }
340
+ export function fileHasWritePermissions(path) {
341
+ try {
342
+ accessSync(path, fsConstants.W_OK);
343
+ return true;
344
+ // eslint-disable-next-line no-catch-all/no-catch-all
345
+ }
346
+ catch {
347
+ return false;
348
+ }
349
+ }
350
+ export function unixFileIsOwnedByCurrentUser(path) {
351
+ // process.getuid() is only available on Unix-like systems
352
+ if (process.platform === 'win32' || typeof process.getuid !== 'function')
353
+ return undefined;
354
+ if (!fileExistsSync(path))
355
+ return false;
356
+ try {
357
+ const stats = statSync(path);
358
+ const currentUid = process.getuid();
359
+ return stats.uid === currentUid;
360
+ // eslint-disable-next-line no-catch-all/no-catch-all
361
+ }
362
+ catch {
363
+ return false;
364
+ }
365
+ }
340
366
  /**
341
367
  * Returns true if a file or directory exists.
342
368
  *
@@ -1 +1 @@
1
- {"version":3,"file":"fs.js","sourceRoot":"","sources":["../../../src/public/node/fs.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAE,aAAa,EAAC,MAAM,WAAW,CAAA;AACjD,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAAC,aAAa,EAAmB,MAAM,qBAAqB,CAAA;AAEnE,OAAO,EACL,IAAI,IAAI,MAAM,EACd,UAAU,IAAI,YAAY,EAC1B,cAAc,IAAI,gBAAgB,EAClC,MAAM,IAAI,QAAQ,EAClB,UAAU,IAAI,YAAY,EAC1B,IAAI,IAAI,MAAM;AACd,6DAA6D;AAC7D,aAAa;EACd,MAAM,cAAc,CAAA;AAErB,OAAO,EAAC,kBAAkB,EAAE,sBAAsB,EAAC,MAAM,OAAO,CAAA;AAChE,OAAO,EAAC,GAAG,EAAE,IAAI,EAAC,MAAM,OAAO,CAAA;AAC/B,OAAO,EAAC,MAAM,IAAI,cAAc,EAAC,MAAM,SAAS,CAAA;AAChD,OAAO,EAAC,SAAS,EAAC,MAAM,WAAW,CAAA;AACnC,OAAO,EACL,SAAS,IAAI,WAAW,EACxB,YAAY,IAAI,cAAc,EAC9B,aAAa,IAAI,eAAe,EAChC,cAAc,IAAI,gBAAgB,EAClC,QAAQ,IAAI,UAAU,EACtB,gBAAgB,IAAI,kBAAkB,EACtC,iBAAiB,IAAI,mBAAmB,EACxC,SAAS,IAAI,WAAW,EACxB,UAAU,IAAI,gBAAgB,EAC9B,UAAU,IAAI,YAAY,GAG3B,MAAM,IAAI,CAAA;AACX,O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,IAAI,KAAK,CAAC,oBAAoB,MAAM,iBAAiB,CAAC,CAAA;IAC9D,CAAC;IAED,IAAI,CAAC,CAAC,MAAM,UAAU,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC;QACjC,MAAM,KAAK,CAAC,OAAO,CAAC,CAAA;IACtB,CAAC;IAED,wDAAwD;IACxD,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAA;IAElD,MAAM,WAAW,GAAG,EAAE,CAAA;IAEtB,KAAK,MAAM,IAAI,IAAI,KAAK,EAAE,CAAC;QACzB,MAAM,YAAY,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,EAAE,EAAE,CAAC,CAAA;QACnE,MAAM,QAAQ,GAAG,QAAQ,CAAC,OAAO,EAAE,YAAY,CAAC,CAAA;QAEhD,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAA;IAC5C,CAAC;IAED,MAAM,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAA;AAChC,CAAC","sourcesContent":["import {joinPath, normalizePath} from './path.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {getRandomName, RandomNameFamily} from '../common/string.js'\nimport {OverloadParameters} from '../../private/common/ts/overloaded-parameters.js'\nimport {\n copy as fsCopy,\n ensureFile as fsEnsureFile,\n ensureFileSync as fsEnsureFileSync,\n remove as fsRemove,\n removeSync as fsRemoveSync,\n move as fsMove,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n} from 'fs-extra/esm'\n\nimport {temporaryDirectory, temporaryDirectoryTask} from 'tempy'\nimport {sep, join} from 'pathe'\nimport {findUp as internalFindUp} from 'find-up'\nimport {minimatch} from 'minimatch'\nimport {\n mkdirSync as fsMkdirSync,\n readFileSync as fsReadFileSync,\n writeFileSync as fsWriteFileSync,\n appendFileSync as fsAppendFileSync,\n statSync as fsStatSync,\n createReadStream as fsCreateReadStream,\n createWriteStream as fsCreateWriteStream,\n constants as fsConstants,\n existsSync as fsFileExistsSync,\n unlinkSync as fsUnlinkSync,\n ReadStream,\n WriteStream,\n} from 'fs'\nimport {\n mkdir as fsMkdir,\n writeFile as fsWriteFile,\n readFile as fsReadFile,\n realpath as fsRealPath,\n appendFile as fsAppendFile,\n mkdtemp as fsMkdtemp,\n stat as fsStat,\n lstat as fsLstat,\n chmod as fsChmod,\n access as fsAccess,\n rename as fsRename,\n unlink as fsUnlink,\n readdir as fsReaddir,\n} from 'fs/promises'\nimport {pathToFileURL as pathToFile} from 'url'\nimport * as os from 'os'\nimport type {Pattern, Options as GlobOptions} from 'fast-glob'\n\n/**\n * Strip the first `strip` parts of the path.\n *\n * @param path - Path to strip.\n * @param strip - Number of parts to strip.\n * @returns The stripped path.\n */\nexport function stripUpPath(path: string, strip: number): string {\n const parts = path.split(sep)\n return join(...parts.slice(strip))\n}\n\n/**\n * Creates a temporary directory and ties its lifecycle to the lifecycle of the callback.\n *\n * @param callback - The callback that receives the temporary directory.\n */\nexport async function inTemporaryDirectory<T>(callback: (tmpDir: string) => T | Promise<T>): Promise<T> {\n return temporaryDirectoryTask(callback)\n}\n\n/**\n * Return a temporary directory\n * @returns - The path to the temporary directory.\n */\nexport function tempDirectory(): string {\n return temporaryDirectory()\n}\n\n/**\n * It reads a file and returns its content as a string using the\n * utf-8 encoding.\n *\n * @param path - Path to the file to read.\n * @returns A promise that resolves with the content of the file.\n */\n\nexport type ReadOptions =\n | undefined\n | {flag?: string | undefined}\n | {\n encoding: string\n flag?: string | undefined\n }\nexport async function readFile(path: string, options?: ReadOptions): Promise<string>\nexport async function readFile(path: string, options?: ReadOptions): Promise<Buffer>\n\n/**\n * It reads a file and returns its content as a string.\n * Uses utf-8 encoding by default.\n *\n * @param path - Path to the file to read.\n * @param options - Options to read the file with (defaults to utf-8 encoding).\n * @returns A promise that resolves with the content of the file.\n */\nexport async function readFile(path: string, options: ReadOptions = {encoding: 'utf8'}): Promise<string | Buffer> {\n outputDebug(outputContent`Reading the content of file at ${outputToken.path(path)}...`)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return fsReadFile(path, options)\n}\n\n/**\n * Synchronously reads a file and returns its content as a buffer.\n *\n * @param path - Path to the file to read.\n * @returns The content of the file.\n */\nexport function readFileSync(path: string): Buffer {\n outputDebug(outputContent`Sync-reading the content of file at ${outputToken.path(path)}...`)\n return fsReadFileSync(path)\n}\n\n/**\n * Given a path, it determines the actual path. This is useful when working\n * with paths that represent symlinks.\n *\n * @param path - Path whose real path will be returned.\n */\nexport async function fileRealPath(path: string): Promise<string> {\n return fsRealPath(path)\n}\n\n/**\n * Copies a file.\n *\n * @param from - Path to the directory or file to be copied.\n * @param to - Destination path.\n */\nexport async function copyFile(from: string, to: string): Promise<void> {\n outputDebug(outputContent`Copying file from ${outputToken.path(from)} to ${outputToken.path(to)}...`)\n await fsCopy(from, to)\n}\n\n/**\n * Creates a file at the given path.\n *\n * @param path - Path to the file to be created.\n */\nexport async function touchFile(path: string): Promise<void> {\n outputDebug(outputContent`Creating an empty file at ${outputToken.path(path)}...`)\n await fsEnsureFile(path)\n}\n\n/**\n * Synchronously creates a file at the given path.\n *\n * @param path - Path to the file to be created.\n */\nexport function touchFileSync(path: string): void {\n outputDebug(outputContent`Creating an empty file at ${outputToken.path(path)}...`)\n fsEnsureFileSync(path)\n}\n\n/**\n * Appnds content to file at path.\n *\n * @param path - Path to the file to be appended.\n * @param content - Content to be appended.\n */\nexport async function appendFile(path: string, content: string): Promise<void> {\n outputDebug(outputContent`Appending the following content to ${outputToken.path(path)}:\n ${content\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n')}\n `)\n await fsAppendFile(path, content)\n}\n\n/**\n * Synchronously appends content to file at path.\n *\n * @param path - Path to the file to be appended.\n * @param data - Content to be appended.\n */\nexport function appendFileSync(path: string, data: string): void {\n fsAppendFileSync(path, data)\n}\n\nexport interface WriteOptions {\n encoding: BufferEncoding\n}\n\n/**\n * Writes content to file at path.\n *\n * @param path - Path to the file to be written.\n * @param data - Content to be written.\n * @param options - Options to write the file with (defaults to utf-8 encoding).\n */\nexport async function writeFile(\n path: string,\n data: string | Buffer,\n options: WriteOptions = {encoding: 'utf8'},\n): Promise<void> {\n outputDebug(outputContent`Writing some content to file at ${outputToken.path(path)}...`)\n await fsWriteFile(path, data, options)\n}\n\n/**\n * Synchronously writes content to file at path.\n *\n * @param path - Path to the file to be written.\n * @param data - Content to be written.\n */\nexport function writeFileSync(path: string, data: string): void {\n outputDebug(outputContent`File-writing some content to file at ${outputToken.path(path)}...`)\n fsWriteFileSync(path, data)\n}\n\n/**\n * Creates a directory at the given path.\n *\n * @param path - Path to the directory to be created.\n */\nexport async function mkdir(path: string): Promise<void> {\n outputDebug(outputContent`Creating directory at ${outputToken.path(path)}...`)\n await fsMkdir(path, {recursive: true})\n}\n\n/**\n * Synchronously creates a directory at the given path.\n *\n * @param path - Path to the directory to be created.\n */\nexport function mkdirSync(path: string): void {\n outputDebug(outputContent`Sync-creating directory at ${outputToken.path(path)}...`)\n fsMkdirSync(path, {recursive: true})\n}\n\n/**\n * Removes a file at the given path.\n *\n * @param path - Path to the file to be removed.\n */\nexport async function removeFile(path: string): Promise<void> {\n outputDebug(outputContent`Removing file at ${outputToken.path(path)}...`)\n await fsRemove(path)\n}\n\n/**\n * Renames a file.\n * @param from - Path to the file to be renamed.\n * @param to - New path for the file.\n */\nexport async function renameFile(from: string, to: string): Promise<void> {\n outputDebug(outputContent`Renaming file from ${outputToken.path(from)} to ${outputToken.path(to)}...`)\n await fsRename(from, to)\n}\n\n/**\n * Synchronously removes a file at the given path.\n *\n * @param path - Path to the file to be removed.\n */\nexport function removeFileSync(path: string): void {\n outputDebug(outputContent`Sync-removing file at ${outputToken.path(path)}...`)\n fsRemoveSync(path)\n}\n\ninterface RmDirOptions {\n force?: boolean\n}\n/**\n * Removes a directory at the given path.\n *\n * @param path - Path to the directory to be removed.\n * @param options - Options to remove the directory with.\n */\nexport async function rmdir(path: string, options: RmDirOptions = {}): Promise<void> {\n const {default: del} = await import('del')\n outputDebug(outputContent`Removing directory at ${outputToken.path(path)}...`)\n await del(path, {force: options.force})\n}\n\n/**\n * Create a temporary directory within the OS provided location for temp directories\n *\n * @returns Path to the temporary directory.\n */\nexport async function mkTmpDir(): Promise<string> {\n outputDebug(outputContent`Creating a temporary directory...`)\n const directory = await fsMkdtemp(joinPath(os.tmpdir(), 'tmp-'))\n return directory\n}\n\n/**\n * Check whether a path is a directory.\n *\n * @param path - Path to check.\n * @returns True if the path is a directory, false otherwise.\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n outputDebug(outputContent`Checking if ${outputToken.path(path)} is a directory...`)\n return (await fsLstat(path)).isDirectory()\n}\n\n/**\n * Get the size of a file.\n *\n * @param path - Path to the file.\n * @returns The size of the file in bytes.\n */\nexport async function fileSize(path: string): Promise<number> {\n outputDebug(outputContent`Getting the size of file file at ${outputToken.path(path)}...`)\n return (await fsStat(path)).size\n}\n\n/**\n * Synchronously get the size of a file.\n *\n * @param path - Path to the file.\n * @returns The size of the file in bytes.\n */\nexport function fileSizeSync(path: string): number {\n outputDebug(outputContent`Sync-getting the size of file file at ${outputToken.path(path)}...`)\n return fsStatSync(path).size\n}\n\n/**\n * Synchronously unlink a file at the given path.\n *\n * @param path - Path to the file.\n */\nexport function unlinkFileSync(path: string): void {\n fsUnlinkSync(path)\n}\n\n/**\n * Unlink a file at the given path.\n *\n * @param path - Path to the file.\n * @returns A promise that resolves when the file is unlinked.\n */\nexport function unlinkFile(path: string): Promise<void> {\n return fsUnlink(path)\n}\n\n/**\n * Create a read stream for a file with optional options.\n *\n * @param path - Path to the file.\n * @param options - Options for the read stream.\n * @returns A read stream for the file.\n */\nexport function createFileReadStream(\n path: string,\n options?: {encoding?: BufferEncoding; start?: number; end?: number},\n): ReadStream {\n return fsCreateReadStream(path, options)\n}\n\n/**\n * Create a write stream for a file.\n *\n * @param path - Path to the file.\n * @returns A write stream for the file.\n */\nexport function createFileWriteStream(path: string): WriteStream {\n return fsCreateWriteStream(path)\n}\n\n/**\n * Returns the Date object for the last modification of a file.\n *\n * @param path - Path to the directory or file.\n * @returns A unix timestamp.\n */\nexport async function fileLastUpdated(path: string): Promise<Date> {\n outputDebug(outputContent`Getting last updated timestamp for file at ${outputToken.path(path)}...`)\n return (await fsStat(path)).ctime\n}\n\n/**\n * Returns the unix timestamp of the last modification of a file.\n *\n * @param path - Path to the directory or file.\n * @returns A unix timestamp.\n */\nexport async function fileLastUpdatedTimestamp(path: string): Promise<number | undefined> {\n try {\n const lastUpdatedDateTime = await fileLastUpdated(path)\n return lastUpdatedDateTime.getTime()\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return undefined\n }\n}\n\ninterface MoveFileOptions {\n overwrite?: boolean\n}\n\n/**\n * Moves a file.\n *\n * @param src - File to be moved.\n * @param dest - Path to be moved to.\n * @param options - Moving options.\n */\nexport async function moveFile(src: string, dest: string, options: MoveFileOptions = {}): Promise<void> {\n await fsMove(src, dest, options)\n}\n\n/**\n * Changes the permissions of a directory or file.\n *\n * @param path - Path to the file or directory whose permissions will be modified.\n * @param mode - Permissions to set to the file or directory.\n */\nexport async function chmod(path: string, mode: number | string): Promise<void> {\n await fsChmod(path, mode)\n}\n\n/**\n * Checks if a file has executable permissions.\n *\n * @param path - Path to the file whose permissions will be checked.\n */\nexport async function fileHasExecutablePermissions(path: string): Promise<boolean> {\n try {\n await fsAccess(path, fsConstants.X_OK)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Returns true if a file or directory exists.\n *\n * @param path - Path to the directory or file.\n * @returns True if it exists.\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await fsAccess(path)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\nexport function fileExistsSync(path: string): boolean {\n return fsFileExistsSync(path)\n}\n\ninterface GenerateRandomDirectoryOptions {\n /** Suffix to include in the randomly generated directory name. */\n suffix: string\n\n /** Absolute path to the directory where the random directory will be created. */\n directory: string\n\n /** Type of word to use for random name. */\n family?: RandomNameFamily\n}\n\n/**\n * It generates a random directory directory name for a sub-directory.\n * It ensures that the returned directory name doesn't exist.\n *\n * @param options - Options to generate the random directory name.\n * @returns It returns the name of the directory.\n */\nexport async function generateRandomNameForSubdirectory(options: GenerateRandomDirectoryOptions): Promise<string> {\n const generated = `${getRandomName(options.family ?? 'business')}-${options.suffix}`\n const randomDirectoryPath = joinPath(options.directory, generated)\n const isAppDirectoryTaken = await fileExists(randomDirectoryPath)\n\n if (isAppDirectoryTaken) {\n return generateRandomNameForSubdirectory(options)\n } else {\n return generated\n }\n}\n\n/**\n * Traverse the file system and return pathnames that match the given pattern.\n *\n * @param pattern - A glob pattern or an array of glob patterns.\n * @param options - Options for the glob.\n * @returns A promise that resolves to an array of pathnames that match the given pattern.\n */\nexport async function glob(pattern: Pattern | Pattern[], options?: GlobOptions): Promise<string[]> {\n const {default: fastGlob} = await import('fast-glob')\n let overridenOptions = options\n if (options?.dot == null) {\n overridenOptions = {...options, dot: true}\n }\n return fastGlob(pattern, overridenOptions)\n}\n\n/**\n * Convert a path to a File URL.\n *\n * @param path - Path to convert.\n * @returns The File URL.\n */\nexport function pathToFileURL(path: string): URL {\n return pathToFile(path)\n}\n\n/**\n * The operating system-specific end-of-line marker:\n * - `\\n` on POSIX\n * - `\\r\\n` on Windows\n */\nexport type EOL = '\\r\\n' | '\\n'\n\n/**\n * Detects the end-of-line marker used in a string.\n *\n * @param content - file contents to analyze\n *\n * @returns The detected end-of-line marker\n */\nexport function detectEOL(content: string): EOL {\n const match = content.match(/\\r\\n|\\n/g)\n\n if (!match) {\n return defaultEOL()\n }\n\n const crlf = match.filter((eol) => eol === '\\r\\n').length\n const lf = match.filter((eol) => eol === '\\n').length\n\n return crlf > lf ? '\\r\\n' : '\\n'\n}\n\n/**\n * Returns the operating system's end-of-line marker.\n *\n * @returns The OS-specific end-of-line marker\n */\nexport function defaultEOL(): EOL {\n return os.EOL as EOL\n}\n\n/**\n * Find a file by walking parent directories.\n *\n * @param matcher - A pattern or an array of patterns to match a file name.\n * @param options - Options for the search.\n * @returns The first path found that matches or `undefined` if none could be found.\n */\nexport async function findPathUp(\n matcher: OverloadParameters<typeof internalFindUp>[0],\n options: OverloadParameters<typeof internalFindUp>[1],\n): ReturnType<typeof internalFindUp> {\n // findUp has odd typing\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const got = await internalFindUp(matcher as any, options)\n return got ? normalizePath(got) : undefined\n}\n\nexport interface MatchGlobOptions {\n matchBase: boolean\n noglobstar: boolean\n}\n\n/**\n * Matches a key against a glob pattern.\n * @param key - The key to match.\n * @param pattern - The glob pattern to match against.\n * @param options - The options to refine the matching approach.\n * @returns true if the key matches the pattern, false otherwise.\n */\nexport function matchGlob(key: string, pattern: string, options?: MatchGlobOptions): boolean {\n return minimatch(key, pattern, options)\n}\n\n/**\n * Read a directory.\n * @param path - The path to read.\n * @returns A promise that resolves to an array of file names.\n */\nexport function readdir(path: string): Promise<string[]> {\n return fsReaddir(path)\n}\n\n/**\n * Copies the contents of a directory to another directory.\n *\n * @param srcDir - Source directory path.\n * @param destDir - Destination directory path.\n */\nexport async function copyDirectoryContents(srcDir: string, destDir: string): Promise<void> {\n if (!(await fileExists(srcDir))) {\n throw new Error(`Source directory ${srcDir} does not exist`)\n }\n\n if (!(await fileExists(destDir))) {\n await mkdir(destDir)\n }\n\n // Get all files and directories in the source directory\n const items = await glob(joinPath(srcDir, '**/*'))\n\n const filesToCopy = []\n\n for (const item of items) {\n const relativePath = item.replace(srcDir, '').replace(/^[/\\\\]/, '')\n const destPath = joinPath(destDir, relativePath)\n\n filesToCopy.push(copyFile(item, destPath))\n }\n\n await Promise.all(filesToCopy)\n}\n"]}
1
+ {"version":3,"file":"fs.js","sourceRoot":"","sources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Path, normalizePath} from './path.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {getRandomName, RandomNameFamily} from '../common/string.js'\nimport {OverloadParameters} from '../../private/common/ts/overloaded-parameters.js'\nimport {\n copy as fsCopy,\n ensureFile as fsEnsureFile,\n ensureFileSync as fsEnsureFileSync,\n remove as fsRemove,\n removeSync as fsRemoveSync,\n move as fsMove,\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n} from 'fs-extra/esm'\n\nimport {temporaryDirectory, temporaryDirectoryTask} from 'tempy'\nimport {sep, join} from 'pathe'\nimport {findUp as internalFindUp} from 'find-up'\nimport {minimatch} from 'minimatch'\nimport {\n mkdirSync as fsMkdirSync,\n readFileSync as fsReadFileSync,\n writeFileSync as fsWriteFileSync,\n appendFileSync as fsAppendFileSync,\n statSync as fsStatSync,\n createReadStream as fsCreateReadStream,\n createWriteStream as fsCreateWriteStream,\n constants as fsConstants,\n existsSync as fsFileExistsSync,\n unlinkSync as fsUnlinkSync,\n accessSync,\n ReadStream,\n WriteStream,\n statSync,\n} from 'fs'\nimport {\n mkdir as fsMkdir,\n writeFile as fsWriteFile,\n readFile as fsReadFile,\n realpath as fsRealPath,\n appendFile as fsAppendFile,\n mkdtemp as fsMkdtemp,\n stat as fsStat,\n lstat as fsLstat,\n chmod as fsChmod,\n access as fsAccess,\n rename as fsRename,\n unlink as fsUnlink,\n readdir as fsReaddir,\n} from 'fs/promises'\nimport {pathToFileURL as pathToFile} from 'url'\nimport * as os from 'os'\nimport type {Pattern, Options as GlobOptions} from 'fast-glob'\n\n/**\n * Strip the first `strip` parts of the path.\n *\n * @param path - Path to strip.\n * @param strip - Number of parts to strip.\n * @returns The stripped path.\n */\nexport function stripUpPath(path: string, strip: number): string {\n const parts = path.split(sep)\n return join(...parts.slice(strip))\n}\n\n/**\n * Creates a temporary directory and ties its lifecycle to the lifecycle of the callback.\n *\n * @param callback - The callback that receives the temporary directory.\n */\nexport async function inTemporaryDirectory<T>(callback: (tmpDir: string) => T | Promise<T>): Promise<T> {\n return temporaryDirectoryTask(callback)\n}\n\n/**\n * Return a temporary directory\n * @returns - The path to the temporary directory.\n */\nexport function tempDirectory(): string {\n return temporaryDirectory()\n}\n\n/**\n * It reads a file and returns its content as a string using the\n * utf-8 encoding.\n *\n * @param path - Path to the file to read.\n * @returns A promise that resolves with the content of the file.\n */\n\nexport type ReadOptions =\n | undefined\n | {flag?: string | undefined}\n | {\n encoding: string\n flag?: string | undefined\n }\nexport async function readFile(path: string, options?: ReadOptions): Promise<string>\nexport async function readFile(path: string, options?: ReadOptions): Promise<Buffer>\n\n/**\n * It reads a file and returns its content as a string.\n * Uses utf-8 encoding by default.\n *\n * @param path - Path to the file to read.\n * @param options - Options to read the file with (defaults to utf-8 encoding).\n * @returns A promise that resolves with the content of the file.\n */\nexport async function readFile(path: string, options: ReadOptions = {encoding: 'utf8'}): Promise<string | Buffer> {\n outputDebug(outputContent`Reading the content of file at ${outputToken.path(path)}...`)\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return fsReadFile(path, options)\n}\n\n/**\n * Synchronously reads a file and returns its content as a buffer.\n *\n * @param path - Path to the file to read.\n * @returns The content of the file.\n */\nexport function readFileSync(path: string): Buffer {\n outputDebug(outputContent`Sync-reading the content of file at ${outputToken.path(path)}...`)\n return fsReadFileSync(path)\n}\n\n/**\n * Given a path, it determines the actual path. This is useful when working\n * with paths that represent symlinks.\n *\n * @param path - Path whose real path will be returned.\n */\nexport async function fileRealPath(path: string): Promise<string> {\n return fsRealPath(path)\n}\n\n/**\n * Copies a file.\n *\n * @param from - Path to the directory or file to be copied.\n * @param to - Destination path.\n */\nexport async function copyFile(from: string, to: string): Promise<void> {\n outputDebug(outputContent`Copying file from ${outputToken.path(from)} to ${outputToken.path(to)}...`)\n await fsCopy(from, to)\n}\n\n/**\n * Creates a file at the given path.\n *\n * @param path - Path to the file to be created.\n */\nexport async function touchFile(path: string): Promise<void> {\n outputDebug(outputContent`Creating an empty file at ${outputToken.path(path)}...`)\n await fsEnsureFile(path)\n}\n\n/**\n * Synchronously creates a file at the given path.\n *\n * @param path - Path to the file to be created.\n */\nexport function touchFileSync(path: string): void {\n outputDebug(outputContent`Creating an empty file at ${outputToken.path(path)}...`)\n fsEnsureFileSync(path)\n}\n\n/**\n * Appnds content to file at path.\n *\n * @param path - Path to the file to be appended.\n * @param content - Content to be appended.\n */\nexport async function appendFile(path: string, content: string): Promise<void> {\n outputDebug(outputContent`Appending the following content to ${outputToken.path(path)}:\n ${content\n .split('\\n')\n .map((line) => ` ${line}`)\n .join('\\n')}\n `)\n await fsAppendFile(path, content)\n}\n\n/**\n * Synchronously appends content to file at path.\n *\n * @param path - Path to the file to be appended.\n * @param data - Content to be appended.\n */\nexport function appendFileSync(path: string, data: string): void {\n fsAppendFileSync(path, data)\n}\n\nexport interface WriteOptions {\n encoding: BufferEncoding\n}\n\n/**\n * Writes content to file at path.\n *\n * @param path - Path to the file to be written.\n * @param data - Content to be written.\n * @param options - Options to write the file with (defaults to utf-8 encoding).\n */\nexport async function writeFile(\n path: string,\n data: string | Buffer,\n options: WriteOptions = {encoding: 'utf8'},\n): Promise<void> {\n outputDebug(outputContent`Writing some content to file at ${outputToken.path(path)}...`)\n await fsWriteFile(path, data, options)\n}\n\n/**\n * Synchronously writes content to file at path.\n *\n * @param path - Path to the file to be written.\n * @param data - Content to be written.\n */\nexport function writeFileSync(path: string, data: string): void {\n outputDebug(outputContent`File-writing some content to file at ${outputToken.path(path)}...`)\n fsWriteFileSync(path, data)\n}\n\n/**\n * Creates a directory at the given path.\n *\n * @param path - Path to the directory to be created.\n */\nexport async function mkdir(path: string): Promise<void> {\n outputDebug(outputContent`Creating directory at ${outputToken.path(path)}...`)\n await fsMkdir(path, {recursive: true})\n}\n\n/**\n * Synchronously creates a directory at the given path.\n *\n * @param path - Path to the directory to be created.\n */\nexport function mkdirSync(path: string): void {\n outputDebug(outputContent`Sync-creating directory at ${outputToken.path(path)}...`)\n fsMkdirSync(path, {recursive: true})\n}\n\n/**\n * Removes a file at the given path.\n *\n * @param path - Path to the file to be removed.\n */\nexport async function removeFile(path: string): Promise<void> {\n outputDebug(outputContent`Removing file at ${outputToken.path(path)}...`)\n await fsRemove(path)\n}\n\n/**\n * Renames a file.\n * @param from - Path to the file to be renamed.\n * @param to - New path for the file.\n */\nexport async function renameFile(from: string, to: string): Promise<void> {\n outputDebug(outputContent`Renaming file from ${outputToken.path(from)} to ${outputToken.path(to)}...`)\n await fsRename(from, to)\n}\n\n/**\n * Synchronously removes a file at the given path.\n *\n * @param path - Path to the file to be removed.\n */\nexport function removeFileSync(path: string): void {\n outputDebug(outputContent`Sync-removing file at ${outputToken.path(path)}...`)\n fsRemoveSync(path)\n}\n\ninterface RmDirOptions {\n force?: boolean\n}\n/**\n * Removes a directory at the given path.\n *\n * @param path - Path to the directory to be removed.\n * @param options - Options to remove the directory with.\n */\nexport async function rmdir(path: string, options: RmDirOptions = {}): Promise<void> {\n const {default: del} = await import('del')\n outputDebug(outputContent`Removing directory at ${outputToken.path(path)}...`)\n await del(path, {force: options.force})\n}\n\n/**\n * Create a temporary directory within the OS provided location for temp directories\n *\n * @returns Path to the temporary directory.\n */\nexport async function mkTmpDir(): Promise<string> {\n outputDebug(outputContent`Creating a temporary directory...`)\n const directory = await fsMkdtemp(joinPath(os.tmpdir(), 'tmp-'))\n return directory\n}\n\n/**\n * Check whether a path is a directory.\n *\n * @param path - Path to check.\n * @returns True if the path is a directory, false otherwise.\n */\nexport async function isDirectory(path: string): Promise<boolean> {\n outputDebug(outputContent`Checking if ${outputToken.path(path)} is a directory...`)\n return (await fsLstat(path)).isDirectory()\n}\n\n/**\n * Get the size of a file.\n *\n * @param path - Path to the file.\n * @returns The size of the file in bytes.\n */\nexport async function fileSize(path: string): Promise<number> {\n outputDebug(outputContent`Getting the size of file file at ${outputToken.path(path)}...`)\n return (await fsStat(path)).size\n}\n\n/**\n * Synchronously get the size of a file.\n *\n * @param path - Path to the file.\n * @returns The size of the file in bytes.\n */\nexport function fileSizeSync(path: string): number {\n outputDebug(outputContent`Sync-getting the size of file file at ${outputToken.path(path)}...`)\n return fsStatSync(path).size\n}\n\n/**\n * Synchronously unlink a file at the given path.\n *\n * @param path - Path to the file.\n */\nexport function unlinkFileSync(path: string): void {\n fsUnlinkSync(path)\n}\n\n/**\n * Unlink a file at the given path.\n *\n * @param path - Path to the file.\n * @returns A promise that resolves when the file is unlinked.\n */\nexport function unlinkFile(path: string): Promise<void> {\n return fsUnlink(path)\n}\n\n/**\n * Create a read stream for a file with optional options.\n *\n * @param path - Path to the file.\n * @param options - Options for the read stream.\n * @returns A read stream for the file.\n */\nexport function createFileReadStream(\n path: string,\n options?: {encoding?: BufferEncoding; start?: number; end?: number},\n): ReadStream {\n return fsCreateReadStream(path, options)\n}\n\n/**\n * Create a write stream for a file.\n *\n * @param path - Path to the file.\n * @returns A write stream for the file.\n */\nexport function createFileWriteStream(path: string): WriteStream {\n return fsCreateWriteStream(path)\n}\n\n/**\n * Returns the Date object for the last modification of a file.\n *\n * @param path - Path to the directory or file.\n * @returns A unix timestamp.\n */\nexport async function fileLastUpdated(path: string): Promise<Date> {\n outputDebug(outputContent`Getting last updated timestamp for file at ${outputToken.path(path)}...`)\n return (await fsStat(path)).ctime\n}\n\n/**\n * Returns the unix timestamp of the last modification of a file.\n *\n * @param path - Path to the directory or file.\n * @returns A unix timestamp.\n */\nexport async function fileLastUpdatedTimestamp(path: string): Promise<number | undefined> {\n try {\n const lastUpdatedDateTime = await fileLastUpdated(path)\n return lastUpdatedDateTime.getTime()\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return undefined\n }\n}\n\ninterface MoveFileOptions {\n overwrite?: boolean\n}\n\n/**\n * Moves a file.\n *\n * @param src - File to be moved.\n * @param dest - Path to be moved to.\n * @param options - Moving options.\n */\nexport async function moveFile(src: string, dest: string, options: MoveFileOptions = {}): Promise<void> {\n await fsMove(src, dest, options)\n}\n\n/**\n * Changes the permissions of a directory or file.\n *\n * @param path - Path to the file or directory whose permissions will be modified.\n * @param mode - Permissions to set to the file or directory.\n */\nexport async function chmod(path: string, mode: number | string): Promise<void> {\n await fsChmod(path, mode)\n}\n\n/**\n * Checks if a file has executable permissions.\n *\n * @param path - Path to the file whose permissions will be checked.\n */\nexport async function fileHasExecutablePermissions(path: string): Promise<boolean> {\n try {\n await fsAccess(path, fsConstants.X_OK)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\nexport function fileHasWritePermissions(path: string): boolean {\n try {\n accessSync(path, fsConstants.W_OK)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\nexport function unixFileIsOwnedByCurrentUser(path: string): boolean | undefined {\n // process.getuid() is only available on Unix-like systems\n if (process.platform === 'win32' || typeof process.getuid !== 'function') return undefined\n if (!fileExistsSync(path)) return false\n\n try {\n const stats = statSync(path)\n const currentUid = process.getuid()\n\n return stats.uid === currentUid\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\n/**\n * Returns true if a file or directory exists.\n *\n * @param path - Path to the directory or file.\n * @returns True if it exists.\n */\nexport async function fileExists(path: string): Promise<boolean> {\n try {\n await fsAccess(path)\n return true\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch {\n return false\n }\n}\n\nexport function fileExistsSync(path: string): boolean {\n return fsFileExistsSync(path)\n}\n\ninterface GenerateRandomDirectoryOptions {\n /** Suffix to include in the randomly generated directory name. */\n suffix: string\n\n /** Absolute path to the directory where the random directory will be created. */\n directory: string\n\n /** Type of word to use for random name. */\n family?: RandomNameFamily\n}\n\n/**\n * It generates a random directory directory name for a sub-directory.\n * It ensures that the returned directory name doesn't exist.\n *\n * @param options - Options to generate the random directory name.\n * @returns It returns the name of the directory.\n */\nexport async function generateRandomNameForSubdirectory(options: GenerateRandomDirectoryOptions): Promise<string> {\n const generated = `${getRandomName(options.family ?? 'business')}-${options.suffix}`\n const randomDirectoryPath = joinPath(options.directory, generated)\n const isAppDirectoryTaken = await fileExists(randomDirectoryPath)\n\n if (isAppDirectoryTaken) {\n return generateRandomNameForSubdirectory(options)\n } else {\n return generated\n }\n}\n\n/**\n * Traverse the file system and return pathnames that match the given pattern.\n *\n * @param pattern - A glob pattern or an array of glob patterns.\n * @param options - Options for the glob.\n * @returns A promise that resolves to an array of pathnames that match the given pattern.\n */\nexport async function glob(pattern: Pattern | Pattern[], options?: GlobOptions): Promise<string[]> {\n const {default: fastGlob} = await import('fast-glob')\n let overridenOptions = options\n if (options?.dot == null) {\n overridenOptions = {...options, dot: true}\n }\n return fastGlob(pattern, overridenOptions)\n}\n\n/**\n * Convert a path to a File URL.\n *\n * @param path - Path to convert.\n * @returns The File URL.\n */\nexport function pathToFileURL(path: string): URL {\n return pathToFile(path)\n}\n\n/**\n * The operating system-specific end-of-line marker:\n * - `\\n` on POSIX\n * - `\\r\\n` on Windows\n */\nexport type EOL = '\\r\\n' | '\\n'\n\n/**\n * Detects the end-of-line marker used in a string.\n *\n * @param content - file contents to analyze\n *\n * @returns The detected end-of-line marker\n */\nexport function detectEOL(content: string): EOL {\n const match = content.match(/\\r\\n|\\n/g)\n\n if (!match) {\n return defaultEOL()\n }\n\n const crlf = match.filter((eol) => eol === '\\r\\n').length\n const lf = match.filter((eol) => eol === '\\n').length\n\n return crlf > lf ? '\\r\\n' : '\\n'\n}\n\n/**\n * Returns the operating system's end-of-line marker.\n *\n * @returns The OS-specific end-of-line marker\n */\nexport function defaultEOL(): EOL {\n return os.EOL as EOL\n}\n\n/**\n * Find a file by walking parent directories.\n *\n * @param matcher - A pattern or an array of patterns to match a file name.\n * @param options - Options for the search.\n * @returns The first path found that matches or `undefined` if none could be found.\n */\nexport async function findPathUp(\n matcher: OverloadParameters<typeof internalFindUp>[0],\n options: OverloadParameters<typeof internalFindUp>[1],\n): ReturnType<typeof internalFindUp> {\n // findUp has odd typing\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const got = await internalFindUp(matcher as any, options)\n return got ? normalizePath(got) : undefined\n}\n\nexport interface MatchGlobOptions {\n matchBase: boolean\n noglobstar: boolean\n}\n\n/**\n * Matches a key against a glob pattern.\n * @param key - The key to match.\n * @param pattern - The glob pattern to match against.\n * @param options - The options to refine the matching approach.\n * @returns true if the key matches the pattern, false otherwise.\n */\nexport function matchGlob(key: string, pattern: string, options?: MatchGlobOptions): boolean {\n return minimatch(key, pattern, options)\n}\n\n/**\n * Read a directory.\n * @param path - The path to read.\n * @returns A promise that resolves to an array of file names.\n */\nexport function readdir(path: string): Promise<string[]> {\n return fsReaddir(path)\n}\n\n/**\n * Copies the contents of a directory to another directory.\n *\n * @param srcDir - Source directory path.\n * @param destDir - Destination directory path.\n */\nexport async function copyDirectoryContents(srcDir: string, destDir: string): Promise<void> {\n if (!(await fileExists(srcDir))) {\n throw new Error(`Source directory ${srcDir} does not exist`)\n }\n\n if (!(await fileExists(destDir))) {\n await mkdir(destDir)\n }\n\n // Get all files and directories in the source directory\n const items = await glob(joinPath(srcDir, '**/*'))\n\n const filesToCopy = []\n\n for (const item of items) {\n const relativePath = item.replace(srcDir, '').replace(/^[/\\\\]/, '')\n const destPath = joinPath(destDir, relativePath)\n\n filesToCopy.push(copyFile(item, destPath))\n }\n\n await Promise.all(filesToCopy)\n}\n"]}
@@ -15,6 +15,8 @@ export declare class LocalStorage<T extends {
15
15
  *
16
16
  * @param key - The key to get.
17
17
  * @returns The value.
18
+ * @throws AbortError if a permission error occurs.
19
+ * @throws BugError if an unexpected error occurs.
18
20
  */
19
21
  get<TKey extends keyof T>(key: TKey): T[TKey] | undefined;
20
22
  /**
@@ -22,16 +24,36 @@ export declare class LocalStorage<T extends {
22
24
  *
23
25
  * @param key - The key to set.
24
26
  * @param value - The value to set.
27
+ * @throws AbortError if a permission error occurs.
28
+ * @throws BugError if an unexpected error occurs.
25
29
  */
26
30
  set<TKey extends keyof T>(key: TKey, value?: T[TKey]): void;
27
31
  /**
28
32
  * Delete a value from the local storage.
29
33
  *
30
34
  * @param key - The key to delete.
35
+ * @throws AbortError if a permission error occurs.
36
+ * @throws BugError if an unexpected error occurs.
31
37
  */
32
38
  delete<TKey extends keyof T>(key: TKey): void;
33
39
  /**
34
40
  * Clear the local storage (delete all values).
41
+ *
42
+ * @throws AbortError if a permission error occurs.
43
+ * @throws BugError if an unexpected error occurs.
35
44
  */
36
45
  clear(): void;
46
+ /**
47
+ * Handle errors from config operations.
48
+ * If the error is permission-related, throw an AbortError with helpful hints.
49
+ * Otherwise, throw a BugError.
50
+ *
51
+ * @param error - The error that occurred.
52
+ * @param operation - The operation that failed.
53
+ * @throws AbortError if the error is permission-related.
54
+ * @throws BugError if the error is not permission-related.
55
+ */
56
+ private handleError;
57
+ private isPermissionError;
58
+ private tryMessage;
37
59
  }
@@ -1,3 +1,6 @@
1
+ import { AbortError, BugError } from './error.js';
2
+ import { fileHasWritePermissions, unixFileIsOwnedByCurrentUser } from './fs.js';
3
+ import { dirname } from './path.js';
1
4
  import Config from 'conf';
2
5
  /**
3
6
  * A wrapper around the `conf` package that provides a strongly-typed interface
@@ -13,32 +16,100 @@ export class LocalStorage {
13
16
  *
14
17
  * @param key - The key to get.
15
18
  * @returns The value.
19
+ * @throws AbortError if a permission error occurs.
20
+ * @throws BugError if an unexpected error occurs.
16
21
  */
17
22
  get(key) {
18
- return this.config.get(key);
23
+ try {
24
+ return this.config.get(key);
25
+ // eslint-disable-next-line no-catch-all/no-catch-all
26
+ }
27
+ catch (error) {
28
+ this.handleError(error, 'get');
29
+ }
19
30
  }
20
31
  /**
21
32
  * Set a value in the local storage.
22
33
  *
23
34
  * @param key - The key to set.
24
35
  * @param value - The value to set.
36
+ * @throws AbortError if a permission error occurs.
37
+ * @throws BugError if an unexpected error occurs.
25
38
  */
26
39
  set(key, value) {
27
- this.config.set(key, value);
40
+ try {
41
+ this.config.set(key, value);
42
+ // eslint-disable-next-line no-catch-all/no-catch-all
43
+ }
44
+ catch (error) {
45
+ this.handleError(error, 'set');
46
+ }
28
47
  }
29
48
  /**
30
49
  * Delete a value from the local storage.
31
50
  *
32
51
  * @param key - The key to delete.
52
+ * @throws AbortError if a permission error occurs.
53
+ * @throws BugError if an unexpected error occurs.
33
54
  */
34
55
  delete(key) {
35
- this.config.delete(key);
56
+ try {
57
+ this.config.delete(key);
58
+ // eslint-disable-next-line no-catch-all/no-catch-all
59
+ }
60
+ catch (error) {
61
+ this.handleError(error, 'delete');
62
+ }
36
63
  }
37
64
  /**
38
65
  * Clear the local storage (delete all values).
66
+ *
67
+ * @throws AbortError if a permission error occurs.
68
+ * @throws BugError if an unexpected error occurs.
39
69
  */
40
70
  clear() {
41
- this.config.clear();
71
+ try {
72
+ this.config.clear();
73
+ // eslint-disable-next-line no-catch-all/no-catch-all
74
+ }
75
+ catch (error) {
76
+ this.handleError(error, 'clear');
77
+ }
78
+ }
79
+ /**
80
+ * Handle errors from config operations.
81
+ * If the error is permission-related, throw an AbortError with helpful hints.
82
+ * Otherwise, throw a BugError.
83
+ *
84
+ * @param error - The error that occurred.
85
+ * @param operation - The operation that failed.
86
+ * @throws AbortError if the error is permission-related.
87
+ * @throws BugError if the error is not permission-related.
88
+ */
89
+ handleError(error, operation) {
90
+ if (this.isPermissionError()) {
91
+ throw new AbortError(`Failed to access local storage (${operation}): ${error}`, this.tryMessage());
92
+ }
93
+ else {
94
+ throw new BugError(`Unexpected error while accessing local storage at ${this.config.path} (${operation}): ${error}`);
95
+ }
96
+ }
97
+ isPermissionError() {
98
+ const canAccessFile = fileHasWritePermissions(this.config.path);
99
+ const canAccessFolder = fileHasWritePermissions(dirname(this.config.path));
100
+ const ownsFile = unixFileIsOwnedByCurrentUser(this.config.path);
101
+ return !canAccessFile || !canAccessFolder || ownsFile === false;
102
+ }
103
+ tryMessage() {
104
+ const ownsFile = unixFileIsOwnedByCurrentUser(this.config.path);
105
+ const ownsFolder = unixFileIsOwnedByCurrentUser(dirname(this.config.path));
106
+ const message = [`Check that you have write permissions for`, { filePath: this.config.path }];
107
+ if (ownsFile === false || ownsFolder === false) {
108
+ message.push('- The file is owned by a different user. This typically happens when Shopify CLI was previously run with elevated permissions (e.g., sudo).');
109
+ }
110
+ message.push('\n\nTo resolve this, remove the Shopify CLI preferences folder:');
111
+ message.push({ command: `rm -rf ${dirname(this.config.path)}` });
112
+ return message;
42
113
  }
43
114
  }
44
115
  //# sourceMappingURL=local-storage.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/public/node/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,MAAM,CAAA;AAEzB;;;GAGG;AACH,8DAA8D;AAC9D,MAAM,OAAO,YAAY;IAGvB,YAAY,OAA6C;QACvD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAI,OAAO,CAAC,CAAA;IACtC,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS;QACjC,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;IAC7B,CAAC;IAED;;;;;OAKG;IACH,GAAG,CAAuB,GAAS,EAAE,KAAe;QAClD,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;IAC7B,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAuB,GAAS;QACpC,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;IAED;;OAEG;IACH,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAA;IACrB,CAAC;CACF","sourcesContent":["import Config from 'conf'\n\n/**\n * A wrapper around the `conf` package that provides a strongly-typed interface\n * for accessing the local storage.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class LocalStorage<T extends {[key: string]: any}> {\n private readonly config: Config<T>\n\n constructor(options: {projectName?: string; cwd?: string}) {\n this.config = new Config<T>(options)\n }\n\n /**\n * Get a value from the local storage.\n *\n * @param key - The key to get.\n * @returns The value.\n */\n get<TKey extends keyof T>(key: TKey): T[TKey] | undefined {\n return this.config.get(key)\n }\n\n /**\n * Set a value in the local storage.\n *\n * @param key - The key to set.\n * @param value - The value to set.\n */\n set<TKey extends keyof T>(key: TKey, value?: T[TKey]): void {\n this.config.set(key, value)\n }\n\n /**\n * Delete a value from the local storage.\n *\n * @param key - The key to delete.\n */\n delete<TKey extends keyof T>(key: TKey): void {\n this.config.delete(key)\n }\n\n /**\n * Clear the local storage (delete all values).\n */\n clear(): void {\n this.config.clear()\n }\n}\n"]}
1
+ {"version":3,"file":"local-storage.js","sourceRoot":"","sources":["../../../src/public/node/local-storage.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,UAAU,EAAE,QAAQ,EAAC,MAAM,YAAY,CAAA;AAC/C,OAAO,EAAC,uBAAuB,EAAE,4BAA4B,EAAC,MAAM,SAAS,CAAA;AAC7E,OAAO,EAAC,OAAO,EAAC,MAAM,WAAW,CAAA;AAEjC,OAAO,MAAM,MAAM,MAAM,CAAA;AAEzB;;;GAGG;AACH,8DAA8D;AAC9D,MAAM,OAAO,YAAY;IAGvB,YAAY,OAA6C;QACvD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAI,OAAO,CAAC,CAAA;IACtC,CAAC;IAED;;;;;;;OAOG;IACH,GAAG,CAAuB,GAAS;QACjC,IAAI,CAAC;YACH,OAAO,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,CAAC,CAAA;YAC3B,qDAAqD;QACvD,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;QAChC,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACH,GAAG,CAAuB,GAAS,EAAE,KAAe;QAClD,IAAI,CAAC;YACH,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC,CAAA;YAC3B,qDAAqD;QACvD,CAAC;QAAC,OAAO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;QAE/D,OAAO,CAAC,aAAa,IAAI,CAAC,eAAe,IAAI,QAAQ,KAAK,KAAK,CAAA;IACjE,CAAC;IAEO,UAAU;QAChB,MAAM,QAAQ,GAAG,4BAA4B,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAA;QAC/D,MAAM,UAAU,GAAG,4BAA4B,CAAC,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAA;QAE1E,MAAM,OAAO,GAAc,CAAC,2CAA2C,EAAE,EAAC,QAAQ,EAAE,IAAI,CAAC,MAAM,CAAC,IAAI,EAAC,CAAC,CAAA;QACtG,IAAI,QAAQ,KAAK,KAAK,IAAI,UAAU,KAAK,KAAK,EAAE,CAAC;YAC/C,OAAO,CAAC,IAAI,CACV,6IAA6I,CAC9I,CAAA;QACH,CAAC;QAED,OAAO,CAAC,IAAI,CAAC,iEAAiE,CAAC,CAAA;QAC/E,OAAO,CAAC,IAAI,CAAC,EAAC,OAAO,EAAE,UAAU,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,EAAC,CAAC,CAAA;QAE9D,OAAO,OAAO,CAAA;IAChB,CAAC;CACF","sourcesContent":["import {AbortError, BugError} from './error.js'\nimport {fileHasWritePermissions, unixFileIsOwnedByCurrentUser} from './fs.js'\nimport {dirname} from './path.js'\nimport {TokenItem} from './ui.js'\nimport Config from 'conf'\n\n/**\n * A wrapper around the `conf` package that provides a strongly-typed interface\n * for accessing the local storage.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport class LocalStorage<T extends {[key: string]: any}> {\n private readonly config: Config<T>\n\n constructor(options: {projectName?: string; cwd?: string}) {\n this.config = new Config<T>(options)\n }\n\n /**\n * Get a value from the local storage.\n *\n * @param key - The key to get.\n * @returns The value.\n * @throws AbortError if a permission error occurs.\n * @throws BugError if an unexpected error occurs.\n */\n get<TKey extends keyof T>(key: TKey): T[TKey] | undefined {\n try {\n return this.config.get(key)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n this.handleError(error, 'get')\n }\n }\n\n /**\n * Set a value in the local storage.\n *\n * @param key - The key to set.\n * @param value - The value to set.\n * @throws AbortError if a permission error occurs.\n * @throws BugError if an unexpected error occurs.\n */\n set<TKey extends keyof T>(key: TKey, value?: T[TKey]): void {\n try {\n this.config.set(key, value)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n this.handleError(error, 'set')\n }\n }\n\n /**\n * Delete a value from the local storage.\n *\n * @param key - The key to delete.\n * @throws AbortError if a permission error occurs.\n * @throws BugError if an unexpected error occurs.\n */\n delete<TKey extends keyof T>(key: TKey): void {\n try {\n this.config.delete(key)\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n this.handleError(error, 'delete')\n }\n }\n\n /**\n * Clear the local storage (delete all values).\n *\n * @throws AbortError if a permission error occurs.\n * @throws BugError if an unexpected error occurs.\n */\n clear(): void {\n try {\n this.config.clear()\n // eslint-disable-next-line no-catch-all/no-catch-all\n } catch (error) {\n this.handleError(error, 'clear')\n }\n }\n\n /**\n * Handle errors from config operations.\n * If the error is permission-related, throw an AbortError with helpful hints.\n * Otherwise, throw a BugError.\n *\n * @param error - The error that occurred.\n * @param operation - The operation that failed.\n * @throws AbortError if the error is permission-related.\n * @throws BugError if the error is not permission-related.\n */\n private handleError(error: unknown, operation: string): never {\n if (this.isPermissionError()) {\n throw new AbortError(`Failed to access local storage (${operation}): ${error}`, this.tryMessage())\n } else {\n throw new BugError(\n `Unexpected error while accessing local storage at ${this.config.path} (${operation}): ${error}`,\n )\n }\n }\n\n private isPermissionError(): boolean {\n const canAccessFile = fileHasWritePermissions(this.config.path)\n const canAccessFolder = fileHasWritePermissions(dirname(this.config.path))\n const ownsFile = unixFileIsOwnedByCurrentUser(this.config.path)\n\n return !canAccessFile || !canAccessFolder || ownsFile === false\n }\n\n private tryMessage() {\n const ownsFile = unixFileIsOwnedByCurrentUser(this.config.path)\n const ownsFolder = unixFileIsOwnedByCurrentUser(dirname(this.config.path))\n\n const message: TokenItem = [`Check that you have write permissions for`, {filePath: this.config.path}]\n if (ownsFile === false || ownsFolder === false) {\n message.push(\n '- The file is owned by a different user. This typically happens when Shopify CLI was previously run with elevated permissions (e.g., sudo).',\n )\n }\n\n message.push('\\n\\nTo resolve this, remove the Shopify CLI preferences folder:')\n message.push({command: `rm -rf ${dirname(this.config.path)}`})\n\n return message\n }\n}\n"]}
@@ -6,6 +6,41 @@ export interface AdminSession {
6
6
  token: string;
7
7
  storeFqdn: string;
8
8
  }
9
+ /**
10
+ * Session Object for Partners API and App Management API access.
11
+ */
12
+ export interface Session {
13
+ token: string;
14
+ businessPlatformToken: string;
15
+ accountInfo: AccountInfo;
16
+ userId: string;
17
+ }
18
+ export type AccountInfo = UserAccountInfo | ServiceAccountInfo | UnknownAccountInfo;
19
+ interface UserAccountInfo {
20
+ type: 'UserAccount';
21
+ email: string;
22
+ }
23
+ interface ServiceAccountInfo {
24
+ type: 'ServiceAccount';
25
+ orgName: string;
26
+ }
27
+ interface UnknownAccountInfo {
28
+ type: 'UnknownAccount';
29
+ }
30
+ /**
31
+ * Type guard to check if an account is a UserAccount.
32
+ *
33
+ * @param account - The account to check.
34
+ * @returns True if the account is a UserAccount.
35
+ */
36
+ export declare function isUserAccount(account: AccountInfo): account is UserAccountInfo;
37
+ /**
38
+ * Type guard to check if an account is a ServiceAccount.
39
+ *
40
+ * @param account - The account to check.
41
+ * @returns True if the account is a ServiceAccount.
42
+ */
43
+ export declare function isServiceAccount(account: AccountInfo): account is ServiceAccountInfo;
9
44
  /**
10
45
  * Ensure that we have a valid session with no particular scopes.
11
46
  *
@@ -87,3 +122,4 @@ export declare function ensureAuthenticatedBusinessPlatform(scopes?: BusinessPla
87
122
  * @returns A promise that resolves when the logout is complete.
88
123
  */
89
124
  export declare function logout(): Promise<void>;
125
+ export {};
@@ -6,6 +6,24 @@ import { exchangeCustomPartnerToken, exchangeCliTokenForAppManagementAccessToken
6
6
  import { outputContent, outputToken, outputDebug } from '../../public/node/output.js';
7
7
  import { ensureAuthenticated, setLastSeenAuthMethod, setLastSeenUserIdAfterAuth, } from '../../private/node/session.js';
8
8
  import { isThemeAccessSession } from '../../private/node/api/rest.js';
9
+ /**
10
+ * Type guard to check if an account is a UserAccount.
11
+ *
12
+ * @param account - The account to check.
13
+ * @returns True if the account is a UserAccount.
14
+ */
15
+ export function isUserAccount(account) {
16
+ return account.type === 'UserAccount';
17
+ }
18
+ /**
19
+ * Type guard to check if an account is a ServiceAccount.
20
+ *
21
+ * @param account - The account to check.
22
+ * @returns True if the account is a ServiceAccount.
23
+ */
24
+ export function isServiceAccount(account) {
25
+ return account.type === 'ServiceAccount';
26
+ }
9
27
  /**
10
28
  * Ensure that we have a valid session with no particular scopes.
11
29
  *
@@ -1 +1 @@
1
- {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/public/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAA;AACnC,OAAO,EAAC,gBAAgB,EAAC,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,YAAY,MAAM,qCAAqC,CAAA;AACnE,OAAO,EACL,0BAA0B,EAC1B,2CAA2C,EAC3C,8CAA8C,GAC/C,MAAM,wCAAwC,CAAA;AAC/C,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAOL,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,GAC3B,MAAM,+BAA+B,CAAA;AACtC,OAAO,EAAC,oBAAoB,EAAC,MAAM,gCAAgC,CAAA;AAUnE;;;;;;GAMG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAC3C,GAAG,GAAG,OAAO,CAAC,GAAG,EACjB,UAAgD,EAAE;IAElD,WAAW,CAAC,aAAa,CAAA,mEAAmE,CAAC,C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AM,CAAC;CACzB,CAAC,CAAA;IACA,IAAI,QAAQ,EAAE,CAAC;QACb,MAAM,OAAO,GAAG,EAAC,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,KAAK,EAAC,CAAA;QACnD,MAAM,UAAU,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,kBAAkB,CAAA;QAC5F,qBAAqB,CAAC,UAAU,CAAC,CAAA;QACjC,0BAA0B,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC,CAAA;QACnD,OAAO,OAAO,CAAA;IAChB,CAAC;IACD,OAAO,wBAAwB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,CAAA;AACzD,CAAC;AAED;;;;;GAKG;AACH,MAAM,CAAC,KAAK,UAAU,mCAAmC,CAAC,SAAkC,EAAE;IAC5F,WAAW,CAAC,aAAa,CAAA;EACzB,WAAW,CAAC,IAAI,CAAC,MAAM,CAAC;CACzB,CAAC,CAAA;IACA,MAAM,MAAM,GAAG,MAAM,mBAAmB,CAAC,EAAC,mBAAmB,EAAE,EAAC,MAAM,EAAC,EAAC,EAAE,OAAO,CAAC,GAAG,CAAC,CAAA;IACtF,IAAI,CAAC,MAAM,CAAC,gBAAgB,EAAE,CAAC;QAC7B,MAAM,IAAI,QAAQ,CAAC,+DAA+D,CAAC,CAAA;IACrF,CAAC;IACD,OAAO,MAAM,CAAC,gBAAgB,CAAA;AAChC,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,MAAM;IACpB,OAAO,YAAY,CAAC,MAAM,EAAE,CAAA;AAC9B,CAAC","sourcesContent":["import {BugError} from './error.js'\nimport {getPartnersToken} from './environment.js'\nimport {nonRandomUUID} from './crypto.js'\nimport * as sessionStore from '../../private/node/session/store.js'\nimport {\n exchangeCustomPartnerToken,\n exchangeCliTokenForAppManagementAccessToken,\n exchangeCliTokenForBusinessPlatformAccessToken,\n} from '../../private/node/session/exchange.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {\n AdminAPIScope,\n AppManagementAPIScope,\n BusinessPlatformScope,\n EnsureAuthenticatedAdditionalOptions,\n PartnersAPIScope,\n StorefrontRendererScope,\n ensureAuthenticated,\n setLastSeenAuthMethod,\n setLastSeenUserIdAfterAuth,\n} from '../../private/node/session.js'\nimport {isThemeAccessSession} from '../../private/node/api/rest.js'\n\n/**\n * Session Object to access the Admin API, includes the token and the store FQDN.\n */\nexport interface AdminSession {\n token: string\n storeFqdn: string\n}\n\n/**\n * Ensure that we have a valid session with no particular scopes.\n *\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The user ID.\n */\nexport async function ensureAuthenticatedUser(\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with no particular scopes`)\n const tokens = await ensureAuthenticated({}, env, options)\n return {userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the Partners API.\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, that token will be used to obtain a valid Partners Token\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, scopes will be ignored.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Partners API.\n */\nexport async function ensureAuthenticatedPartners(\n scopes: PartnersAPIScope[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{token: string; userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const envToken = getPartnersToken()\n if (envToken) {\n const result = await exchangeCustomPartnerToken(envToken)\n return {token: result.accessToken, userId: result.userId}\n }\n const tokens = await ensureAuthenticated({partnersApi: {scopes}}, env, options)\n if (!tokens.partners) {\n throw new BugError('No partners token found after ensuring authenticated')\n }\n return {token: tokens.partners, userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the App Management API.\n *\n * @param options - Optional extra options to use.\n * @param appManagementScopes - Optional array of extra scopes to authenticate with.\n * @param businessPlatformScopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @returns The access token for the App Management API.\n */\nexport async function ensureAuthenticatedAppManagementAndBusinessPlatform(\n options: EnsureAuthenticatedAdditionalOptions = {},\n appManagementScopes: AppManagementAPIScope[] = [],\n businessPlatformScopes: BusinessPlatformScope[] = [],\n env = process.env,\n): Promise<{appManagementToken: string; userId: string; businessPlatformToken: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:\n${outputToken.json(appManagementScopes)}\n`)\n\n const envToken = getPartnersToken()\n if (envToken) {\n const appManagmentToken = await exchangeCliTokenForAppManagementAccessToken(envToken)\n const businessPlatformToken = await exchangeCliTokenForBusinessPlatformAccessToken(envToken)\n\n return {\n appManagementToken: appManagmentToken.accessToken,\n userId: appManagmentToken.userId,\n businessPlatformToken: businessPlatformToken.accessToken,\n }\n }\n\n const tokens = await ensureAuthenticated(\n {appManagementApi: {scopes: appManagementScopes}, businessPlatformApi: {scopes: businessPlatformScopes}},\n env,\n options,\n )\n if (!tokens.appManagement || !tokens.businessPlatform) {\n throw new BugError('No App Management or Business Platform token found after ensuring authenticated')\n }\n\n return {\n appManagementToken: tokens.appManagement,\n userId: tokens.userId,\n businessPlatformToken: tokens.businessPlatform,\n }\n}\n\n/**\n * Ensure that we have a valid session to access the Storefront API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param password - Optional password to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Storefront API.\n */\nexport async function ensureAuthenticatedStorefront(\n scopes: StorefrontRendererScope[] = [],\n password: string | undefined = undefined,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<string> {\n if (password) {\n const session = {token: password, storeFqdn: ''}\n const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'\n setLastSeenAuthMethod(authMethod)\n setLastSeenUserIdAfterAuth(nonRandomUUID(password))\n return password\n }\n\n outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({storefrontRendererApi: {scopes}}, process.env, options)\n if (!tokens.storefront) {\n throw new BugError('No storefront token found after ensuring authenticated')\n }\n return tokens.storefront\n}\n\n/**\n * Ensure that we have a valid Admin session for the given store.\n *\n * @param store - Store fqdn to request auth for.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param options - Optional extra options to use.\n * @returns The access token for the Admin API.\n */\nexport async function ensureAuthenticatedAdmin(\n store: string,\n scopes: AdminAPIScope[] = [],\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(\n store,\n )}:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({adminApi: {scopes, storeFqdn: store}}, process.env, {\n ...options,\n })\n if (!tokens.admin) {\n throw new BugError('No admin token found after ensuring authenticated')\n }\n return tokens.admin\n}\n\n/**\n * Ensure that we have a valid session to access the Theme API.\n * If a password is provided, that token will be used against Theme Access API.\n * Otherwise, it will ensure that the user is authenticated with the Admin API.\n *\n * @param store - Store fqdn to request auth for.\n * @param password - Password generated from Theme Access app.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param options - Optional extra options to use.\n * @returns The access token and store.\n */\nexport async function ensureAuthenticatedThemes(\n store: string,\n password: string | undefined,\n scopes: AdminAPIScope[] = [],\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:\n${outputToken.json(scopes)}\n`)\n if (password) {\n const session = {token: password, storeFqdn: store}\n const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'\n setLastSeenAuthMethod(authMethod)\n setLastSeenUserIdAfterAuth(nonRandomUUID(password))\n return session\n }\n return ensureAuthenticatedAdmin(store, scopes, options)\n}\n\n/**\n * Ensure that we have a valid session to access the Business Platform API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @returns The access token for the Business Platform API.\n */\nexport async function ensureAuthenticatedBusinessPlatform(scopes: BusinessPlatformScope[] = []): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({businessPlatformApi: {scopes}}, process.env)\n if (!tokens.businessPlatform) {\n throw new BugError('No business-platform token found after ensuring authenticated')\n }\n return tokens.businessPlatform\n}\n\n/**\n * Logout from Shopify.\n *\n * @returns A promise that resolves when the logout is complete.\n */\nexport function logout(): Promise<void> {\n return sessionStore.remove()\n}\n"]}
1
+ {"version":3,"file":"session.js","sourceRoot":"","sources":["../../../src/public/node/session.ts"],"names":[],"mappings":"AAAA,OAAO,EAAC,QAAQ,EAAC,MAAM,YAAY,CAAA;AACnC,OAAO,EAAC,gBAAgB,EAAC,MAAM,kBAAkB,CAAA;AACjD,OAAO,EAAC,aAAa,EAAC,MAAM,aAAa,CAAA;AACzC,OAAO,KAAK,YAAY,MAAM,qCAAqC,CAAA;AACnE,OAAO,EACL,0BAA0B,EAC1B,2CAA2C,EAC3C,8CAA8C,GAC/C,MAAM,wCAAwC,CAAA;AAC/C,OAAO,EAAC,aAAa,EAAE,WAAW,EAAE,WAAW,EAAC,MAAM,6BAA6B,CAAA;AACnF,OAAO,EAOL,mBAAmB,EACnB,qBAAqB,EACrB,0BAA0B,GAC3B,MAAM,+BAA+B,CAAA;AACtC,OAAO,EAAC,oBAAoB,EAAC,MAAM,gCAAgC,CAAA;AAoCnE;;;;;GAKG;AACH,MAAM,UAAU,aAAa,CAAC,OAAoB;IAChD,OAAO,OAAO,CAAC,IAAI,KAAK,aAAa,CAAA;AACvC,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB,CAAC,OAAoB;IACnD,OAAO,OAA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'./error.js'\nimport {getPartnersToken} from './environment.js'\nimport {nonRandomUUID} from './crypto.js'\nimport * as sessionStore from '../../private/node/session/store.js'\nimport {\n exchangeCustomPartnerToken,\n exchangeCliTokenForAppManagementAccessToken,\n exchangeCliTokenForBusinessPlatformAccessToken,\n} from '../../private/node/session/exchange.js'\nimport {outputContent, outputToken, outputDebug} from '../../public/node/output.js'\nimport {\n AdminAPIScope,\n AppManagementAPIScope,\n BusinessPlatformScope,\n EnsureAuthenticatedAdditionalOptions,\n PartnersAPIScope,\n StorefrontRendererScope,\n ensureAuthenticated,\n setLastSeenAuthMethod,\n setLastSeenUserIdAfterAuth,\n} from '../../private/node/session.js'\nimport {isThemeAccessSession} from '../../private/node/api/rest.js'\n\n/**\n * Session Object to access the Admin API, includes the token and the store FQDN.\n */\nexport interface AdminSession {\n token: string\n storeFqdn: string\n}\n\n/**\n * Session Object for Partners API and App Management API access.\n */\nexport interface Session {\n token: string\n businessPlatformToken: string\n accountInfo: AccountInfo\n userId: string\n}\n\nexport type AccountInfo = UserAccountInfo | ServiceAccountInfo | UnknownAccountInfo\n\ninterface UserAccountInfo {\n type: 'UserAccount'\n email: string\n}\n\ninterface ServiceAccountInfo {\n type: 'ServiceAccount'\n orgName: string\n}\n\ninterface UnknownAccountInfo {\n type: 'UnknownAccount'\n}\n\n/**\n * Type guard to check if an account is a UserAccount.\n *\n * @param account - The account to check.\n * @returns True if the account is a UserAccount.\n */\nexport function isUserAccount(account: AccountInfo): account is UserAccountInfo {\n return account.type === 'UserAccount'\n}\n\n/**\n * Type guard to check if an account is a ServiceAccount.\n *\n * @param account - The account to check.\n * @returns True if the account is a ServiceAccount.\n */\nexport function isServiceAccount(account: AccountInfo): account is ServiceAccountInfo {\n return account.type === 'ServiceAccount'\n}\n\n/**\n * Ensure that we have a valid session with no particular scopes.\n *\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The user ID.\n */\nexport async function ensureAuthenticatedUser(\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with no particular scopes`)\n const tokens = await ensureAuthenticated({}, env, options)\n return {userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the Partners API.\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, that token will be used to obtain a valid Partners Token\n * If SHOPIFY_CLI_PARTNERS_TOKEN exists, scopes will be ignored.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Partners API.\n */\nexport async function ensureAuthenticatedPartners(\n scopes: PartnersAPIScope[] = [],\n env = process.env,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<{token: string; userId: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Partners API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const envToken = getPartnersToken()\n if (envToken) {\n const result = await exchangeCustomPartnerToken(envToken)\n return {token: result.accessToken, userId: result.userId}\n }\n const tokens = await ensureAuthenticated({partnersApi: {scopes}}, env, options)\n if (!tokens.partners) {\n throw new BugError('No partners token found after ensuring authenticated')\n }\n return {token: tokens.partners, userId: tokens.userId}\n}\n\n/**\n * Ensure that we have a valid session to access the App Management API.\n *\n * @param options - Optional extra options to use.\n * @param appManagementScopes - Optional array of extra scopes to authenticate with.\n * @param businessPlatformScopes - Optional array of extra scopes to authenticate with.\n * @param env - Optional environment variables to use.\n * @returns The access token for the App Management API.\n */\nexport async function ensureAuthenticatedAppManagementAndBusinessPlatform(\n options: EnsureAuthenticatedAdditionalOptions = {},\n appManagementScopes: AppManagementAPIScope[] = [],\n businessPlatformScopes: BusinessPlatformScope[] = [],\n env = process.env,\n): Promise<{appManagementToken: string; userId: string; businessPlatformToken: string}> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the App Management API with the following scopes:\n${outputToken.json(appManagementScopes)}\n`)\n\n const envToken = getPartnersToken()\n if (envToken) {\n const appManagmentToken = await exchangeCliTokenForAppManagementAccessToken(envToken)\n const businessPlatformToken = await exchangeCliTokenForBusinessPlatformAccessToken(envToken)\n\n return {\n appManagementToken: appManagmentToken.accessToken,\n userId: appManagmentToken.userId,\n businessPlatformToken: businessPlatformToken.accessToken,\n }\n }\n\n const tokens = await ensureAuthenticated(\n {appManagementApi: {scopes: appManagementScopes}, businessPlatformApi: {scopes: businessPlatformScopes}},\n env,\n options,\n )\n if (!tokens.appManagement || !tokens.businessPlatform) {\n throw new BugError('No App Management or Business Platform token found after ensuring authenticated')\n }\n\n return {\n appManagementToken: tokens.appManagement,\n userId: tokens.userId,\n businessPlatformToken: tokens.businessPlatform,\n }\n}\n\n/**\n * Ensure that we have a valid session to access the Storefront API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param password - Optional password to use.\n * @param options - Optional extra options to use.\n * @returns The access token for the Storefront API.\n */\nexport async function ensureAuthenticatedStorefront(\n scopes: StorefrontRendererScope[] = [],\n password: string | undefined = undefined,\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<string> {\n if (password) {\n const session = {token: password, storeFqdn: ''}\n const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'\n setLastSeenAuthMethod(authMethod)\n setLastSeenUserIdAfterAuth(nonRandomUUID(password))\n return password\n }\n\n outputDebug(outputContent`Ensuring that the user is authenticated with the Storefront API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({storefrontRendererApi: {scopes}}, process.env, options)\n if (!tokens.storefront) {\n throw new BugError('No storefront token found after ensuring authenticated')\n }\n return tokens.storefront\n}\n\n/**\n * Ensure that we have a valid Admin session for the given store.\n *\n * @param store - Store fqdn to request auth for.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param options - Optional extra options to use.\n * @returns The access token for the Admin API.\n */\nexport async function ensureAuthenticatedAdmin(\n store: string,\n scopes: AdminAPIScope[] = [],\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Admin API with the following scopes for the store ${outputToken.raw(\n store,\n )}:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({adminApi: {scopes, storeFqdn: store}}, process.env, {\n ...options,\n })\n if (!tokens.admin) {\n throw new BugError('No admin token found after ensuring authenticated')\n }\n return tokens.admin\n}\n\n/**\n * Ensure that we have a valid session to access the Theme API.\n * If a password is provided, that token will be used against Theme Access API.\n * Otherwise, it will ensure that the user is authenticated with the Admin API.\n *\n * @param store - Store fqdn to request auth for.\n * @param password - Password generated from Theme Access app.\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @param options - Optional extra options to use.\n * @returns The access token and store.\n */\nexport async function ensureAuthenticatedThemes(\n store: string,\n password: string | undefined,\n scopes: AdminAPIScope[] = [],\n options: EnsureAuthenticatedAdditionalOptions = {},\n): Promise<AdminSession> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Theme API with the following scopes:\n${outputToken.json(scopes)}\n`)\n if (password) {\n const session = {token: password, storeFqdn: store}\n const authMethod = isThemeAccessSession(session) ? 'theme_access_token' : 'custom_app_token'\n setLastSeenAuthMethod(authMethod)\n setLastSeenUserIdAfterAuth(nonRandomUUID(password))\n return session\n }\n return ensureAuthenticatedAdmin(store, scopes, options)\n}\n\n/**\n * Ensure that we have a valid session to access the Business Platform API.\n *\n * @param scopes - Optional array of extra scopes to authenticate with.\n * @returns The access token for the Business Platform API.\n */\nexport async function ensureAuthenticatedBusinessPlatform(scopes: BusinessPlatformScope[] = []): Promise<string> {\n outputDebug(outputContent`Ensuring that the user is authenticated with the Business Platform API with the following scopes:\n${outputToken.json(scopes)}\n`)\n const tokens = await ensureAuthenticated({businessPlatformApi: {scopes}}, process.env)\n if (!tokens.businessPlatform) {\n throw new BugError('No business-platform token found after ensuring authenticated')\n }\n return tokens.businessPlatform\n}\n\n/**\n * Logout from Shopify.\n *\n * @returns A promise that resolves when the logout is complete.\n */\nexport function logout(): Promise<void> {\n return sessionStore.remove()\n}\n"]}