@eventcatalog/sdk 2.9.9 → 2.9.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/channels.js.map +1 -1
- package/dist/channels.mjs.map +1 -1
- package/dist/commands.js +1 -0
- package/dist/commands.js.map +1 -1
- package/dist/commands.mjs +1 -0
- package/dist/commands.mjs.map +1 -1
- package/dist/containers.js +1 -0
- package/dist/containers.js.map +1 -1
- package/dist/containers.mjs +1 -0
- package/dist/containers.mjs.map +1 -1
- package/dist/custom-docs.js.map +1 -1
- package/dist/custom-docs.mjs.map +1 -1
- package/dist/data-stores.js +1 -0
- package/dist/data-stores.js.map +1 -1
- package/dist/data-stores.mjs +1 -0
- package/dist/data-stores.mjs.map +1 -1
- package/dist/domains.js +1 -0
- package/dist/domains.js.map +1 -1
- package/dist/domains.mjs +1 -0
- package/dist/domains.mjs.map +1 -1
- package/dist/entities.js.map +1 -1
- package/dist/entities.mjs.map +1 -1
- package/dist/eventcatalog.js +1 -0
- package/dist/eventcatalog.js.map +1 -1
- package/dist/eventcatalog.mjs +1 -0
- package/dist/eventcatalog.mjs.map +1 -1
- package/dist/events.js +1 -0
- package/dist/events.js.map +1 -1
- package/dist/events.mjs +1 -0
- package/dist/events.mjs.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -0
- package/dist/index.mjs.map +1 -1
- package/dist/messages.js.map +1 -1
- package/dist/messages.mjs.map +1 -1
- package/dist/queries.js +1 -0
- package/dist/queries.js.map +1 -1
- package/dist/queries.mjs +1 -0
- package/dist/queries.mjs.map +1 -1
- package/dist/services.js +1 -0
- package/dist/services.js.map +1 -1
- package/dist/services.mjs +1 -0
- package/dist/services.mjs.map +1 -1
- package/dist/teams.js.map +1 -1
- package/dist/teams.mjs.map +1 -1
- package/package.json +1 -1
package/dist/teams.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/teams.ts","../src/internal/utils.ts","../src/internal/resources.ts","../src/users.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { Team } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\nimport { getResource } from './internal/resources';\nimport path from 'node:path';\nimport { getUser, getUsers } from './users';\n\n/**\n * Returns a team from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeam } = utils('/path/to/eventcatalog');\n *\n * // Gets the team with the given id\n * const team = await getTeam('eventcatalog-core-team');\n *\n * ```\n */\nexport const getTeam =\n (catalogDir: string) =>\n async (id: string): Promise<Team | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n };\n\n/**\n * Returns all teams from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeams } = utils('/path/to/eventcatalog');\n *\n * // Gets all teams from the catalog\n * const channels = await getTeams();\n *\n * ```\n */\nexport const getTeams =\n (catalogDir: string) =>\n async (options?: {}): Promise<Team[]> => {\n const files = await getFiles(`${catalogDir}/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n });\n };\n\n/**\n * Write a team to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeTeam } = utils('/path/to/eventcatalog');\n *\n * // Write a team to the catalog\n * // team would be written to teams/EventCatalogCoreTeam\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeTeam =\n (catalogDir: string) =>\n async (team: Team, options: { override?: boolean } = {}) => {\n const resource: Team = { ...team };\n\n // Get the path\n const currentTeam = await getTeam(catalogDir)(resource.id);\n const exists = currentTeam !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (team) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a team by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmTeamById } = utils('/path/to/eventcatalog');\n *\n * // deletes the EventCatalogCoreTeam team\n * await rmTeamById('eventcatalog-core-team');\n *\n * ```\n */\nexport const rmTeamById = (catalogDir: string) => async (id: string) => {\n await fs.rm(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n\n/**\n * Returns the owners for a given resource (e.g domain, service, event, command, query, etc.)\n * @param id - The id of the resource to get the owners for\n * @param version - Optional version of the resource\n * @returns { owners: User[] }\n */\nexport const getOwnersForResource = (catalogDir: string) => async (id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n let owners: Team[] = [];\n if (!resource) return [];\n\n if (!resource.owners) return [];\n\n // First check if the owner is a team\n for (const owner of resource.owners) {\n const team = await getTeam(path.join(catalogDir, 'teams'))(owner);\n if (team) {\n owners.push(team);\n } else {\n // If the owner is not a team, check if it's a user\n const user = await getUser(path.join(catalogDir, 'users'))(owner);\n if (user) {\n owners.push(user);\n }\n }\n }\n\n return owners;\n};\n","import { globSync } from 'glob';\nimport fsSync from 'node:fs';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join, dirname, normalize, sep as pathSeparator, resolve, basename, relative } from 'node:path';\nimport matter from 'gray-matter';\nimport { satisfies, validRange, valid } from 'semver';\n\n/**\n * Returns true if a given version of a resource id exists in the catalog\n */\nexport const versionExists = async (catalogDir: string, id: string, version: string) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = (await searchFilesForId(files, id, version)) || [];\n return matchedFiles.length > 0;\n};\n\nexport const findFileById = async (catalogDir: string, id: string, version?: string): Promise<string | undefined> => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n const latestVersion = matchedFiles.find((path) => !path.includes('versioned'));\n\n // If no version is provided, return the latest version\n if (!version) {\n return latestVersion;\n }\n\n // map files into gray matter to get versions\n const parsedFiles = matchedFiles.map((path) => {\n const { data } = matter.read(path);\n return { ...data, path };\n }) as any[];\n\n // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\n};\n\nexport const getFiles = async (pattern: string, ignore: string | string[] = '') => {\n try {\n // 1. Normalize the input pattern to handle mixed separators potentially\n const normalizedInputPattern = normalize(pattern);\n\n // 2. Determine the absolute base directory (cwd for glob)\n // Resolve ensures it's absolute. Handles cases with/without globstar.\n const absoluteBaseDir = resolve(\n normalizedInputPattern.includes('**') ? normalizedInputPattern.split('**')[0] : dirname(normalizedInputPattern)\n );\n\n // 3. Determine the pattern part relative to the absolute base directory\n // We extract the part of the normalized pattern that comes *after* the absoluteBaseDir\n let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);\n\n // On Windows, relative() might return empty string if paths are identical,\n // or might need normalization if the original pattern didn't have `**`\n // Example: pattern = 'dir/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\file.md'\n // relative() -> 'file.md'\n // Example: pattern = 'dir/**/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\**\\file.md'\n // relative() -> '**\\file.md'\n // Convert separators in the relative pattern to forward slashes for glob\n relativePattern = relativePattern.replace(/\\\\/g, '/');\n\n const ignoreList = Array.isArray(ignore) ? ignore : [ignore];\n\n const files = globSync(relativePattern, {\n cwd: absoluteBaseDir,\n ignore: ['node_modules/**', ...ignoreList],\n absolute: true,\n nodir: true,\n });\n\n // 5. Normalize results for consistency before returning\n return files.map(normalize);\n } catch (error: any) {\n // Add more diagnostic info to the error\n const absoluteBaseDirForError = resolve(\n normalize(pattern).includes('**') ? normalize(pattern).split('**')[0] : dirname(normalize(pattern))\n );\n const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\\\/g, '/');\n throw new Error(\n `Error finding files for pattern \"${pattern}\" (using cwd: \"${absoluteBaseDirForError}\", globPattern: \"${relativePatternForError}\"): ${error.message}`\n );\n }\n};\n\nexport const readMdxFile = async (path: string) => {\n const { data } = matter.read(path);\n const { markdown, ...frontmatter } = data;\n return { ...frontmatter, markdown };\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n // Escape the id to avoid regex issues\n const escapedId = id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRegex = new RegExp(`^id:\\\\s*(['\"]|>-)?\\\\s*${escapedId}['\"]?\\\\s*$`, 'm');\n\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = files.map((file) => {\n const content = fsSync.readFileSync(file, 'utf-8');\n const hasIdMatch = content.match(idRegex);\n\n // Check version if provided\n if (version && !content.match(versionRegex)) {\n return undefined;\n }\n\n if (hasIdMatch) {\n return file;\n }\n });\n\n return matches.filter(Boolean).filter((file) => file !== undefined);\n};\n\n/**\n * Function to copy a directory from source to target, uses a tmp directory\n * @param catalogDir\n * @param source\n * @param target\n * @param filter\n */\nexport const copyDir = async (catalogDir: string, source: string, target: string, filter?: CopyFilterAsync | CopyFilterSync) => {\n const tmpDirectory = join(catalogDir, 'tmp');\n fsSync.mkdirSync(tmpDirectory, { recursive: true });\n\n // Copy everything over\n await copy(source, tmpDirectory, {\n overwrite: true,\n filter,\n });\n\n await copy(tmpDirectory, target, {\n overwrite: true,\n filter,\n });\n\n // Remove the tmp directory\n fsSync.rmSync(tmpDirectory, { recursive: true });\n};\n\n// Makes sure values in sends/recieves are unique\nexport const uniqueVersions = (messages: { id: string; version: string }[]): { id: string; version: string }[] => {\n const uniqueSet = new Set();\n\n return messages.filter((message) => {\n const key = `${message.id}-${message.version}`;\n if (!uniqueSet.has(key)) {\n uniqueSet.add(key);\n return true;\n }\n return false;\n });\n};\n","import { dirname, join } from 'path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';\nimport matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { Message, Service, CustomDoc } from '../types';\nimport { satisfies } from 'semver';\nimport { lock, unlock } from 'proper-lockfile';\nimport { basename } from 'node:path';\nimport path from 'node:path';\n\ntype Resource = Service | Message | CustomDoc;\n\nexport const versionResource = async (catalogDir: string, id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No resource found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = getVersionedDirectory(sourceDirectory, version);\n\n fsSync.mkdirSync(targetDirectory, { recursive: true });\n\n const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(sourceDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\n if (file !== 'versioned') {\n fsSync.rmSync(join(sourceDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const writeResource = async (\n catalogDir: string,\n resource: Resource,\n options: { path?: string; type: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n type: '',\n override: false,\n versionExistingContent: false,\n format: 'mdx',\n }\n) => {\n const path = options.path || `/${resource.id}`;\n const fullPath = join(catalogDir, path);\n const format = options.format || 'mdx';\n\n // Create directory if it doesn't exist\n fsSync.mkdirSync(fullPath, { recursive: true });\n\n // Create or get lock file path\n const lockPath = join(fullPath, `index.${format}`);\n\n // Ensure the file exists before attempting to lock it\n if (!fsSync.existsSync(lockPath)) {\n fsSync.writeFileSync(lockPath, '');\n }\n\n try {\n // Acquire lock with retry\n await lock(lockPath, {\n retries: 5,\n stale: 10000, // 10 seconds\n });\n\n const exists = await versionExists(catalogDir, resource.id, resource.version);\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n if (options.versionExistingContent && !exists) {\n const currentResource = await getResource(catalogDir, resource.id);\n\n if (currentResource) {\n if (satisfies(resource.version, `>${currentResource.version}`)) {\n await versionResource(catalogDir, resource.id);\n } else {\n throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);\n }\n }\n }\n\n const document = matter.stringify(markdown.trim(), frontmatter);\n fsSync.writeFileSync(lockPath, document);\n } finally {\n // Always release the lock\n await unlock(lockPath).catch(() => {});\n }\n};\n\nexport const getResource = async (\n catalogDir: string,\n id?: string,\n version?: string,\n options?: { type: string; attachSchema?: boolean },\n filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(file)) return;\n\n const { data, content } = matter.read(file);\n\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResourcePath = async (catalogDir: string, id: string, version?: string) => {\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n return {\n fullPath: file,\n relativePath: file.replace(catalogDir, ''),\n directory: dirname(file.replace(catalogDir, '')),\n };\n};\n\nexport const getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResources = async (\n catalogDir: string,\n {\n type,\n latestOnly = false,\n ignore = [],\n pattern = '',\n attachSchema = false,\n }: { type: string; pattern?: string; latestOnly?: boolean; ignore?: string[]; attachSchema?: boolean }\n): Promise<Resource[] | undefined> => {\n const ignoreList = latestOnly ? `**/versioned/**` : '';\n const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;\n const files = await getFiles(filePattern, [ignoreList, ...ignore]);\n\n if (files.length === 0) return;\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n\n // Attach the schema if the attachSchema option is set to true\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n });\n};\n\nexport const rmResourceById = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; persistFiles?: boolean }\n) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);\n }\n\n if (options?.persistFiles) {\n await Promise.all(\n matchedFiles.map(async (file) => {\n await fs.rm(file, { recursive: true });\n // Verify file is actually removed\n await waitForFileRemoval(file);\n })\n );\n } else {\n await Promise.all(\n matchedFiles.map(async (file) => {\n const directory = dirname(file);\n await fs.rm(directory, { recursive: true, force: true });\n // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\n};\n\nexport const addFileToResource = async (\n catalogDir: string,\n id: string,\n file: { content: string; fileName: string },\n version?: string,\n options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n let fileContent = file.content.trim();\n\n try {\n const json = JSON.parse(fileContent);\n fileContent = JSON.stringify(json, null, 2);\n } catch (error) {\n // Just silently fail if the file is not valid JSON\n // Write it as it is\n }\n\n fsSync.writeFileSync(join(dirname(pathToResource), file.fileName), fileContent);\n};\n\nexport const getFileFromResource = async (catalogDir: string, id: string, file: { fileName: string }, version?: string) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory of resource');\n\n const exists = await fs\n .access(join(dirname(pathToResource), file.fileName))\n .then(() => true)\n .catch(() => false);\n if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);\n\n return fsSync.readFileSync(join(dirname(pathToResource), file.fileName), 'utf-8');\n};\nexport const getVersionedDirectory = (sourceDirectory: string, version: any): string => {\n return join(sourceDirectory, 'versioned', version);\n};\n\nexport const isLatestVersion = async (catalogDir: string, id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n if (!resource) return false;\n\n const pathToResource = await getResourcePath(catalogDir, id, version);\n\n return !pathToResource?.relativePath.replace(/\\\\/g, '/').includes('/versioned/');\n};\n","import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { User } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\n\n/**\n * Returns a user from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUser } = utils('/path/to/eventcatalog');\n *\n * // Gets the user with the given id\n * const user = await getUser('eventcatalog-core-user');\n *\n * ```\n */\nexport const getUser =\n (catalogDir: string) =>\n async (id: string): Promise<User | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n };\n\n/**\n * Returns all users from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUsers } = utils('/path/to/eventcatalog');\n *\n * // Gets all users from the catalog\n * const channels = await getUsers();\n *\n * ```\n */\nexport const getUsers =\n (catalogDir: string) =>\n async (options?: {}): Promise<User[]> => {\n const files = await getFiles(`${catalogDir}/users/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n });\n };\n\n/**\n * Write a user to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeUser } = utils('/path/to/eventcatalog');\n *\n * // Write a user to the catalog\n * // user would be written to users/eventcatalog-tech-lead\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeUser =\n (catalogDir: string) =>\n async (user: User, options: { override?: boolean } = {}) => {\n const resource: User = { ...user };\n\n // Get the path\n const currentUser = await getUser(catalogDir)(resource.id);\n const exists = currentUser !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (user) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a user by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmUserById } = utils('/path/to/eventcatalog');\n *\n * // deletes the user with id eventcatalog-core-user\n * await rmUserById('eventcatalog-core-user');\n *\n * ```\n */\nexport const rmUserById = (catalogDir: string) => async (id: string) => {\n fsSync.rmSync(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,mBAAe;AACf,IAAAC,kBAAmB;AACnB,IAAAC,oBAAqB;AAErB,IAAAC,sBAAmB;;;ACJnB,kBAAyB;AACzB,qBAAmB;AACnB,sBAAsD;AACtD,uBAA4F;AAC5F,yBAAmB;AACnB,oBAA6C;AAWtC,IAAM,eAAe,OAAO,YAAoB,IAAY,YAAkD;AACnH,QAAM,QAAQ,MAAM,SAAS,GAAG,UAAU,oBAAoB;AAE9D,QAAM,eAAgB,MAAM,iBAAiB,OAAO,EAAE,KAAM,CAAC;AAC7D,QAAM,gBAAgB,aAAa,KAAK,CAACC,UAAS,CAACA,MAAK,SAAS,WAAW,CAAC;AAG7E,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAGA,QAAM,cAAc,aAAa,IAAI,CAACA,UAAS;AAC7C,UAAM,EAAE,KAAK,IAAI,mBAAAC,QAAO,KAAKD,KAAI;AACjC,WAAO,EAAE,GAAG,MAAM,MAAAA,MAAK;AAAA,EACzB,CAAC;A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UAAM,OAAO,MAAM,QAAQ,kBAAAC,QAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,QAAI,MAAM;AACR,aAAO,KAAK,IAAI;AAAA,IAClB,OAAO;AAEL,YAAM,OAAO,MAAM,QAAQ,kBAAAA,QAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,UAAI,MAAM;AACR,eAAO,KAAK,IAAI;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_promises","import_node_fs","import_node_path","import_gray_matter","path","matter","fsSync","import_gray_matter","import_node_fs","import_semver","import_node_path","fsSync","matter","import_node_path","import_node_fs","import_node_path","import_gray_matter","matter","matter","fsSync","fs","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/teams.ts","../src/internal/utils.ts","../src/internal/resources.ts","../src/users.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { Team } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\nimport { getResource } from './internal/resources';\nimport path from 'node:path';\nimport { getUser, getUsers } from './users';\n\n/**\n * Returns a team from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeam } = utils('/path/to/eventcatalog');\n *\n * // Gets the team with the given id\n * const team = await getTeam('eventcatalog-core-team');\n *\n * ```\n */\nexport const getTeam =\n (catalogDir: string) =>\n async (id: string): Promise<Team | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n };\n\n/**\n * Returns all teams from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeams } = utils('/path/to/eventcatalog');\n *\n * // Gets all teams from the catalog\n * const channels = await getTeams();\n *\n * ```\n */\nexport const getTeams =\n (catalogDir: string) =>\n async (options?: {}): Promise<Team[]> => {\n const files = await getFiles(`${catalogDir}/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n });\n };\n\n/**\n * Write a team to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeTeam } = utils('/path/to/eventcatalog');\n *\n * // Write a team to the catalog\n * // team would be written to teams/EventCatalogCoreTeam\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeTeam =\n (catalogDir: string) =>\n async (team: Team, options: { override?: boolean } = {}) => {\n const resource: Team = { ...team };\n\n // Get the path\n const currentTeam = await getTeam(catalogDir)(resource.id);\n const exists = currentTeam !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (team) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a team by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmTeamById } = utils('/path/to/eventcatalog');\n *\n * // deletes the EventCatalogCoreTeam team\n * await rmTeamById('eventcatalog-core-team');\n *\n * ```\n */\nexport const rmTeamById = (catalogDir: string) => async (id: string) => {\n await fs.rm(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n\n/**\n * Returns the owners for a given resource (e.g domain, service, event, command, query, etc.)\n * @param id - The id of the resource to get the owners for\n * @param version - Optional version of the resource\n * @returns { owners: User[] }\n */\nexport const getOwnersForResource = (catalogDir: string) => async (id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n let owners: Team[] = [];\n if (!resource) return [];\n\n if (!resource.owners) return [];\n\n // First check if the owner is a team\n for (const owner of resource.owners) {\n const team = await getTeam(path.join(catalogDir, 'teams'))(owner);\n if (team) {\n owners.push(team);\n } else {\n // If the owner is not a team, check if it's a user\n const user = await getUser(path.join(catalogDir, 'users'))(owner);\n if (user) {\n owners.push(user);\n }\n }\n }\n\n return owners;\n};\n","import { globSync } from 'glob';\nimport fsSync from 'node:fs';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join, dirname, normalize, sep as pathSeparator, resolve, basename, relative } from 'node:path';\nimport matter from 'gray-matter';\nimport { satisfies, validRange, valid } from 'semver';\n\n/**\n * Returns true if a given version of a resource id exists in the catalog\n */\nexport const versionExists = async (catalogDir: string, id: string, version: string) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = (await searchFilesForId(files, id, version)) || [];\n return matchedFiles.length > 0;\n};\n\nexport const findFileById = async (catalogDir: string, id: string, version?: string): Promise<string | undefined> => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n const latestVersion = matchedFiles.find((path) => !path.includes('versioned'));\n\n // If no version is provided, return the latest version\n if (!version) {\n return latestVersion;\n }\n\n // map files into gray matter to get versions\n const parsedFiles = matchedFiles.map((path) => {\n const { data } = matter.read(path);\n return { ...data, path };\n }) as any[];\n\n // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\n};\n\nexport const getFiles = async (pattern: string, ignore: string | string[] = '') => {\n try {\n // 1. Normalize the input pattern to handle mixed separators potentially\n const normalizedInputPattern = normalize(pattern);\n\n // 2. Determine the absolute base directory (cwd for glob)\n // Resolve ensures it's absolute. Handles cases with/without globstar.\n const absoluteBaseDir = resolve(\n normalizedInputPattern.includes('**') ? normalizedInputPattern.split('**')[0] : dirname(normalizedInputPattern)\n );\n\n // 3. Determine the pattern part relative to the absolute base directory\n // We extract the part of the normalized pattern that comes *after* the absoluteBaseDir\n let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);\n\n // On Windows, relative() might return empty string if paths are identical,\n // or might need normalization if the original pattern didn't have `**`\n // Example: pattern = 'dir/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\file.md'\n // relative() -> 'file.md'\n // Example: pattern = 'dir/**/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\**\\file.md'\n // relative() -> '**\\file.md'\n // Convert separators in the relative pattern to forward slashes for glob\n relativePattern = relativePattern.replace(/\\\\/g, '/');\n\n const ignoreList = Array.isArray(ignore) ? ignore : [ignore];\n\n const files = globSync(relativePattern, {\n cwd: absoluteBaseDir,\n ignore: ['node_modules/**', ...ignoreList],\n absolute: true,\n nodir: true,\n });\n\n // 5. Normalize results for consistency before returning\n return files.map(normalize);\n } catch (error: any) {\n // Add more diagnostic info to the error\n const absoluteBaseDirForError = resolve(\n normalize(pattern).includes('**') ? normalize(pattern).split('**')[0] : dirname(normalize(pattern))\n );\n const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\\\/g, '/');\n throw new Error(\n `Error finding files for pattern \"${pattern}\" (using cwd: \"${absoluteBaseDirForError}\", globPattern: \"${relativePatternForError}\"): ${error.message}`\n );\n }\n};\n\nexport const readMdxFile = async (path: string) => {\n const { data } = matter.read(path);\n const { markdown, ...frontmatter } = data;\n return { ...frontmatter, markdown };\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n // Escape the id to avoid regex issues\n const escapedId = id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRegex = new RegExp(`^id:\\\\s*(['\"]|>-)?\\\\s*${escapedId}['\"]?\\\\s*$`, 'm');\n\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = files.map((file) => {\n const content = fsSync.readFileSync(file, 'utf-8');\n const hasIdMatch = content.match(idRegex);\n\n // Check version if provided\n if (version && !content.match(versionRegex)) {\n return undefined;\n }\n\n if (hasIdMatch) {\n return file;\n }\n });\n\n return matches.filter(Boolean).filter((file) => file !== undefined);\n};\n\n/**\n * Function to copy a directory from source to target, uses a tmp directory\n * @param catalogDir\n * @param source\n * @param target\n * @param filter\n */\nexport const copyDir = async (catalogDir: string, source: string, target: string, filter?: CopyFilterAsync | CopyFilterSync) => {\n const tmpDirectory = join(catalogDir, 'tmp');\n fsSync.mkdirSync(tmpDirectory, { recursive: true });\n\n // Copy everything over\n await copy(source, tmpDirectory, {\n overwrite: true,\n filter,\n });\n\n await copy(tmpDirectory, target, {\n overwrite: true,\n filter,\n });\n\n // Remove the tmp directory\n fsSync.rmSync(tmpDirectory, { recursive: true });\n};\n\n// Makes sure values in sends/recieves are unique\nexport const uniqueVersions = (messages: { id: string; version: string }[]): { id: string; version: string }[] => {\n const uniqueSet = new Set();\n\n return messages.filter((message) => {\n const key = `${message.id}-${message.version}`;\n if (!uniqueSet.has(key)) {\n uniqueSet.add(key);\n return true;\n }\n return false;\n });\n};\n","import { dirname, join } from 'path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';\nimport matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { Message, Service, CustomDoc } from '../types';\nimport { satisfies } from 'semver';\nimport { lock, unlock } from 'proper-lockfile';\nimport { basename } from 'node:path';\nimport path from 'node:path';\n\ntype Resource = Service | Message | CustomDoc;\n\nexport const versionResource = async (catalogDir: string, id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No resource found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = getVersionedDirectory(sourceDirectory, version);\n\n fsSync.mkdirSync(targetDirectory, { recursive: true });\n\n const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(sourceDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\n if (file !== 'versioned') {\n fsSync.rmSync(join(sourceDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const writeResource = async (\n catalogDir: string,\n resource: Resource,\n options: { path?: string; type: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n type: '',\n override: false,\n versionExistingContent: false,\n format: 'mdx',\n }\n) => {\n const path = options.path || `/${resource.id}`;\n const fullPath = join(catalogDir, path);\n const format = options.format || 'mdx';\n\n // Create directory if it doesn't exist\n fsSync.mkdirSync(fullPath, { recursive: true });\n\n // Create or get lock file path\n const lockPath = join(fullPath, `index.${format}`);\n\n // Ensure the file exists before attempting to lock it\n if (!fsSync.existsSync(lockPath)) {\n fsSync.writeFileSync(lockPath, '');\n }\n\n try {\n // Acquire lock with retry\n await lock(lockPath, {\n retries: 5,\n stale: 10000, // 10 seconds\n });\n\n const exists = await versionExists(catalogDir, resource.id, resource.version);\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n if (options.versionExistingContent && !exists) {\n const currentResource = await getResource(catalogDir, resource.id);\n\n if (currentResource) {\n if (satisfies(resource.version, `>${currentResource.version}`)) {\n await versionResource(catalogDir, resource.id);\n } else {\n throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);\n }\n }\n }\n\n const document = matter.stringify(markdown.trim(), frontmatter);\n fsSync.writeFileSync(lockPath, document);\n } finally {\n // Always release the lock\n await unlock(lockPath).catch(() => {});\n }\n};\n\nexport const getResource = async (\n catalogDir: string,\n id?: string,\n version?: string,\n options?: { type: string; attachSchema?: boolean },\n filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(file)) return;\n\n const { data, content } = matter.read(file);\n\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResourcePath = async (catalogDir: string, id: string, version?: string) => {\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n return {\n fullPath: file,\n relativePath: file.replace(catalogDir, ''),\n directory: dirname(file.replace(catalogDir, '')),\n };\n};\n\nexport const getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResources = async (\n catalogDir: string,\n {\n type,\n latestOnly = false,\n ignore = [],\n pattern = '',\n attachSchema = false,\n }: { type: string; pattern?: string; latestOnly?: boolean; ignore?: string[]; attachSchema?: boolean }\n): Promise<Resource[] | undefined> => {\n const ignoreList = latestOnly ? `**/versioned/**` : '';\n const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;\n const files = await getFiles(filePattern, [ignoreList, ...ignore]);\n\n if (files.length === 0) return;\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n\n // Attach the schema if the attachSchema option is set to true\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n });\n};\n\nexport const rmResourceById = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; persistFiles?: boolean }\n) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);\n }\n\n if (options?.persistFiles) {\n await Promise.all(\n matchedFiles.map(async (file) => {\n await fs.rm(file, { recursive: true });\n // Verify file is actually removed\n await waitForFileRemoval(file);\n })\n );\n } else {\n await Promise.all(\n matchedFiles.map(async (file) => {\n const directory = dirname(file);\n await fs.rm(directory, { recursive: true, force: true });\n // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\n};\n\nexport const addFileToResource = async (\n catalogDir: string,\n id: string,\n file: { content: string; fileName: string },\n version?: string,\n options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n // Create the directory if it doesn't exist\n fsSync.mkdirSync(path.dirname(pathToResource), { recursive: true });\n\n let fileContent = file.content.trim();\n\n try {\n const json = JSON.parse(fileContent);\n fileContent = JSON.stringify(json, null, 2);\n } catch (error) {\n // Just silently fail if the file is not valid JSON\n // Write it as it is\n }\n\n fsSync.writeFileSync(join(dirname(pathToResource), file.fileName), fileContent);\n};\n\nexport const getFileFromResource = async (catalogDir: string, id: string, file: { fileName: string }, version?: string) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory of resource');\n\n const exists = await fs\n .access(join(dirname(pathToResource), file.fileName))\n .then(() => true)\n .catch(() => false);\n if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);\n\n return fsSync.readFileSync(join(dirname(pathToResource), file.fileName), 'utf-8');\n};\nexport const getVersionedDirectory = (sourceDirectory: string, version: any): string => {\n return join(sourceDirectory, 'versioned', version);\n};\n\nexport const isLatestVersion = async (catalogDir: string, id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n if (!resource) return false;\n\n const pathToResource = await getResourcePath(catalogDir, id, version);\n\n return !pathToResource?.relativePath.replace(/\\\\/g, '/').includes('/versioned/');\n};\n","import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { User } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\n\n/**\n * Returns a user from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUser } = utils('/path/to/eventcatalog');\n *\n * // Gets the user with the given id\n * const user = await getUser('eventcatalog-core-user');\n *\n * ```\n */\nexport const getUser =\n (catalogDir: string) =>\n async (id: string): Promise<User | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n };\n\n/**\n * Returns all users from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUsers } = utils('/path/to/eventcatalog');\n *\n * // Gets all users from the catalog\n * const channels = await getUsers();\n *\n * ```\n */\nexport const getUsers =\n (catalogDir: string) =>\n async (options?: {}): Promise<User[]> => {\n const files = await getFiles(`${catalogDir}/users/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n });\n };\n\n/**\n * Write a user to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeUser } = utils('/path/to/eventcatalog');\n *\n * // Write a user to the catalog\n * // user would be written to users/eventcatalog-tech-lead\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeUser =\n (catalogDir: string) =>\n async (user: User, options: { override?: boolean } = {}) => {\n const resource: User = { ...user };\n\n // Get the path\n const currentUser = await getUser(catalogDir)(resource.id);\n const exists = currentUser !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (user) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a user by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmUserById } = utils('/path/to/eventcatalog');\n *\n * // deletes the user with id eventcatalog-core-user\n * await rmUserById('eventcatalog-core-user');\n *\n * ```\n */\nexport const rmUserById = (catalogDir: string) => async (id: string) => {\n fsSync.rmSync(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAAA,mBAAe;AACf,IAAAC,kBAAmB;AACnB,IAAAC,oBAAqB;AAErB,IAAA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,QAAO,cAAU,wBAAK,YAAY,EAAE,GAAG,EAAE,WAAW,KAAK,CAAC;AAC1D,kBAAAA,QAAO,kBAAc,wBAAK,YAAY,IAAI,GAAG,SAAS,EAAE,MAAM,GAAG,QAAQ;AAC3E;AAgBK,IAAM,aAAa,CAAC,eAAuB,OAAO,OAAe;AACtE,QAAM,iBAAAC,QAAG,OAAG,wBAAK,YAAY,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAChE;AAQO,IAAM,uBAAuB,CAAC,eAAuB,OAAO,IAAY,YAAqB;AAClG,QAAM,WAAW,MAAM,YAAY,YAAY,IAAI,OAAO;AAC1D,MAAI,SAAiB,CAAC;AACtB,MAAI,CAAC,SAAU,QAAO,CAAC;AAEvB,MAAI,CAAC,SAAS,OAAQ,QAAO,CAAC;AAG9B,aAAW,SAAS,SAAS,QAAQ;AACnC,UAAM,OAAO,MAAM,QAAQ,kBAAAC,QAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,QAAI,MAAM;AACR,aAAO,KAAK,IAAI;AAAA,IAClB,OAAO;AAEL,YAAM,OAAO,MAAM,QAAQ,kBAAAA,QAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,UAAI,MAAM;AACR,eAAO,KAAK,IAAI;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["import_promises","import_node_fs","import_node_path","import_gray_matter","path","matter","fsSync","import_gray_matter","import_node_fs","import_semver","import_node_path","fsSync","matter","import_node_path","import_node_fs","import_node_path","import_gray_matter","matter","matter","fsSync","fs","path"]}
|
package/dist/teams.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/teams.ts","../src/internal/utils.ts","../src/internal/resources.ts","../src/users.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { Team } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\nimport { getResource } from './internal/resources';\nimport path from 'node:path';\nimport { getUser, getUsers } from './users';\n\n/**\n * Returns a team from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeam } = utils('/path/to/eventcatalog');\n *\n * // Gets the team with the given id\n * const team = await getTeam('eventcatalog-core-team');\n *\n * ```\n */\nexport const getTeam =\n (catalogDir: string) =>\n async (id: string): Promise<Team | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n };\n\n/**\n * Returns all teams from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeams } = utils('/path/to/eventcatalog');\n *\n * // Gets all teams from the catalog\n * const channels = await getTeams();\n *\n * ```\n */\nexport const getTeams =\n (catalogDir: string) =>\n async (options?: {}): Promise<Team[]> => {\n const files = await getFiles(`${catalogDir}/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n });\n };\n\n/**\n * Write a team to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeTeam } = utils('/path/to/eventcatalog');\n *\n * // Write a team to the catalog\n * // team would be written to teams/EventCatalogCoreTeam\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeTeam =\n (catalogDir: string) =>\n async (team: Team, options: { override?: boolean } = {}) => {\n const resource: Team = { ...team };\n\n // Get the path\n const currentTeam = await getTeam(catalogDir)(resource.id);\n const exists = currentTeam !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (team) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a team by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmTeamById } = utils('/path/to/eventcatalog');\n *\n * // deletes the EventCatalogCoreTeam team\n * await rmTeamById('eventcatalog-core-team');\n *\n * ```\n */\nexport const rmTeamById = (catalogDir: string) => async (id: string) => {\n await fs.rm(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n\n/**\n * Returns the owners for a given resource (e.g domain, service, event, command, query, etc.)\n * @param id - The id of the resource to get the owners for\n * @param version - Optional version of the resource\n * @returns { owners: User[] }\n */\nexport const getOwnersForResource = (catalogDir: string) => async (id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n let owners: Team[] = [];\n if (!resource) return [];\n\n if (!resource.owners) return [];\n\n // First check if the owner is a team\n for (const owner of resource.owners) {\n const team = await getTeam(path.join(catalogDir, 'teams'))(owner);\n if (team) {\n owners.push(team);\n } else {\n // If the owner is not a team, check if it's a user\n const user = await getUser(path.join(catalogDir, 'users'))(owner);\n if (user) {\n owners.push(user);\n }\n }\n }\n\n return owners;\n};\n","import { globSync } from 'glob';\nimport fsSync from 'node:fs';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join, dirname, normalize, sep as pathSeparator, resolve, basename, relative } from 'node:path';\nimport matter from 'gray-matter';\nimport { satisfies, validRange, valid } from 'semver';\n\n/**\n * Returns true if a given version of a resource id exists in the catalog\n */\nexport const versionExists = async (catalogDir: string, id: string, version: string) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = (await searchFilesForId(files, id, version)) || [];\n return matchedFiles.length > 0;\n};\n\nexport const findFileById = async (catalogDir: string, id: string, version?: string): Promise<string | undefined> => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n const latestVersion = matchedFiles.find((path) => !path.includes('versioned'));\n\n // If no version is provided, return the latest version\n if (!version) {\n return latestVersion;\n }\n\n // map files into gray matter to get versions\n const parsedFiles = matchedFiles.map((path) => {\n const { data } = matter.read(path);\n return { ...data, path };\n }) as any[];\n\n // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\n};\n\nexport const getFiles = async (pattern: string, ignore: string | string[] = '') => {\n try {\n // 1. Normalize the input pattern to handle mixed separators potentially\n const normalizedInputPattern = normalize(pattern);\n\n // 2. Determine the absolute base directory (cwd for glob)\n // Resolve ensures it's absolute. Handles cases with/without globstar.\n const absoluteBaseDir = resolve(\n normalizedInputPattern.includes('**') ? normalizedInputPattern.split('**')[0] : dirname(normalizedInputPattern)\n );\n\n // 3. Determine the pattern part relative to the absolute base directory\n // We extract the part of the normalized pattern that comes *after* the absoluteBaseDir\n let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);\n\n // On Windows, relative() might return empty string if paths are identical,\n // or might need normalization if the original pattern didn't have `**`\n // Example: pattern = 'dir/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\file.md'\n // relative() -> 'file.md'\n // Example: pattern = 'dir/**/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\**\\file.md'\n // relative() -> '**\\file.md'\n // Convert separators in the relative pattern to forward slashes for glob\n relativePattern = relativePattern.replace(/\\\\/g, '/');\n\n const ignoreList = Array.isArray(ignore) ? ignore : [ignore];\n\n const files = globSync(relativePattern, {\n cwd: absoluteBaseDir,\n ignore: ['node_modules/**', ...ignoreList],\n absolute: true,\n nodir: true,\n });\n\n // 5. Normalize results for consistency before returning\n return files.map(normalize);\n } catch (error: any) {\n // Add more diagnostic info to the error\n const absoluteBaseDirForError = resolve(\n normalize(pattern).includes('**') ? normalize(pattern).split('**')[0] : dirname(normalize(pattern))\n );\n const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\\\/g, '/');\n throw new Error(\n `Error finding files for pattern \"${pattern}\" (using cwd: \"${absoluteBaseDirForError}\", globPattern: \"${relativePatternForError}\"): ${error.message}`\n );\n }\n};\n\nexport const readMdxFile = async (path: string) => {\n const { data } = matter.read(path);\n const { markdown, ...frontmatter } = data;\n return { ...frontmatter, markdown };\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n // Escape the id to avoid regex issues\n const escapedId = id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRegex = new RegExp(`^id:\\\\s*(['\"]|>-)?\\\\s*${escapedId}['\"]?\\\\s*$`, 'm');\n\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = files.map((file) => {\n const content = fsSync.readFileSync(file, 'utf-8');\n const hasIdMatch = content.match(idRegex);\n\n // Check version if provided\n if (version && !content.match(versionRegex)) {\n return undefined;\n }\n\n if (hasIdMatch) {\n return file;\n }\n });\n\n return matches.filter(Boolean).filter((file) => file !== undefined);\n};\n\n/**\n * Function to copy a directory from source to target, uses a tmp directory\n * @param catalogDir\n * @param source\n * @param target\n * @param filter\n */\nexport const copyDir = async (catalogDir: string, source: string, target: string, filter?: CopyFilterAsync | CopyFilterSync) => {\n const tmpDirectory = join(catalogDir, 'tmp');\n fsSync.mkdirSync(tmpDirectory, { recursive: true });\n\n // Copy everything over\n await copy(source, tmpDirectory, {\n overwrite: true,\n filter,\n });\n\n await copy(tmpDirectory, target, {\n overwrite: true,\n filter,\n });\n\n // Remove the tmp directory\n fsSync.rmSync(tmpDirectory, { recursive: true });\n};\n\n// Makes sure values in sends/recieves are unique\nexport const uniqueVersions = (messages: { id: string; version: string }[]): { id: string; version: string }[] => {\n const uniqueSet = new Set();\n\n return messages.filter((message) => {\n const key = `${message.id}-${message.version}`;\n if (!uniqueSet.has(key)) {\n uniqueSet.add(key);\n return true;\n }\n return false;\n });\n};\n","import { dirname, join } from 'path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';\nimport matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { Message, Service, CustomDoc } from '../types';\nimport { satisfies } from 'semver';\nimport { lock, unlock } from 'proper-lockfile';\nimport { basename } from 'node:path';\nimport path from 'node:path';\n\ntype Resource = Service | Message | CustomDoc;\n\nexport const versionResource = async (catalogDir: string, id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No resource found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = getVersionedDirectory(sourceDirectory, version);\n\n fsSync.mkdirSync(targetDirectory, { recursive: true });\n\n const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(sourceDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\n if (file !== 'versioned') {\n fsSync.rmSync(join(sourceDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const writeResource = async (\n catalogDir: string,\n resource: Resource,\n options: { path?: string; type: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n type: '',\n override: false,\n versionExistingContent: false,\n format: 'mdx',\n }\n) => {\n const path = options.path || `/${resource.id}`;\n const fullPath = join(catalogDir, path);\n const format = options.format || 'mdx';\n\n // Create directory if it doesn't exist\n fsSync.mkdirSync(fullPath, { recursive: true });\n\n // Create or get lock file path\n const lockPath = join(fullPath, `index.${format}`);\n\n // Ensure the file exists before attempting to lock it\n if (!fsSync.existsSync(lockPath)) {\n fsSync.writeFileSync(lockPath, '');\n }\n\n try {\n // Acquire lock with retry\n await lock(lockPath, {\n retries: 5,\n stale: 10000, // 10 seconds\n });\n\n const exists = await versionExists(catalogDir, resource.id, resource.version);\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n if (options.versionExistingContent && !exists) {\n const currentResource = await getResource(catalogDir, resource.id);\n\n if (currentResource) {\n if (satisfies(resource.version, `>${currentResource.version}`)) {\n await versionResource(catalogDir, resource.id);\n } else {\n throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);\n }\n }\n }\n\n const document = matter.stringify(markdown.trim(), frontmatter);\n fsSync.writeFileSync(lockPath, document);\n } finally {\n // Always release the lock\n await unlock(lockPath).catch(() => {});\n }\n};\n\nexport const getResource = async (\n catalogDir: string,\n id?: string,\n version?: string,\n options?: { type: string; attachSchema?: boolean },\n filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(file)) return;\n\n const { data, content } = matter.read(file);\n\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResourcePath = async (catalogDir: string, id: string, version?: string) => {\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n return {\n fullPath: file,\n relativePath: file.replace(catalogDir, ''),\n directory: dirname(file.replace(catalogDir, '')),\n };\n};\n\nexport const getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResources = async (\n catalogDir: string,\n {\n type,\n latestOnly = false,\n ignore = [],\n pattern = '',\n attachSchema = false,\n }: { type: string; pattern?: string; latestOnly?: boolean; ignore?: string[]; attachSchema?: boolean }\n): Promise<Resource[] | undefined> => {\n const ignoreList = latestOnly ? `**/versioned/**` : '';\n const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;\n const files = await getFiles(filePattern, [ignoreList, ...ignore]);\n\n if (files.length === 0) return;\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n\n // Attach the schema if the attachSchema option is set to true\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n });\n};\n\nexport const rmResourceById = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; persistFiles?: boolean }\n) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);\n }\n\n if (options?.persistFiles) {\n await Promise.all(\n matchedFiles.map(async (file) => {\n await fs.rm(file, { recursive: true });\n // Verify file is actually removed\n await waitForFileRemoval(file);\n })\n );\n } else {\n await Promise.all(\n matchedFiles.map(async (file) => {\n const directory = dirname(file);\n await fs.rm(directory, { recursive: true, force: true });\n // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\n};\n\nexport const addFileToResource = async (\n catalogDir: string,\n id: string,\n file: { content: string; fileName: string },\n version?: string,\n options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n let fileContent = file.content.trim();\n\n try {\n const json = JSON.parse(fileContent);\n fileContent = JSON.stringify(json, null, 2);\n } catch (error) {\n // Just silently fail if the file is not valid JSON\n // Write it as it is\n }\n\n fsSync.writeFileSync(join(dirname(pathToResource), file.fileName), fileContent);\n};\n\nexport const getFileFromResource = async (catalogDir: string, id: string, file: { fileName: string }, version?: string) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory of resource');\n\n const exists = await fs\n .access(join(dirname(pathToResource), file.fileName))\n .then(() => true)\n .catch(() => false);\n if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);\n\n return fsSync.readFileSync(join(dirname(pathToResource), file.fileName), 'utf-8');\n};\nexport const getVersionedDirectory = (sourceDirectory: string, version: any): string => {\n return join(sourceDirectory, 'versioned', version);\n};\n\nexport const isLatestVersion = async (catalogDir: string, id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n if (!resource) return false;\n\n const pathToResource = await getResourcePath(catalogDir, id, version);\n\n return !pathToResource?.relativePath.replace(/\\\\/g, '/').includes('/versioned/');\n};\n","import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { User } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\n\n/**\n * Returns a user from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUser } = utils('/path/to/eventcatalog');\n *\n * // Gets the user with the given id\n * const user = await getUser('eventcatalog-core-user');\n *\n * ```\n */\nexport const getUser =\n (catalogDir: string) =>\n async (id: string): Promise<User | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n };\n\n/**\n * Returns all users from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUsers } = utils('/path/to/eventcatalog');\n *\n * // Gets all users from the catalog\n * const channels = await getUsers();\n *\n * ```\n */\nexport const getUsers =\n (catalogDir: string) =>\n async (options?: {}): Promise<User[]> => {\n const files = await getFiles(`${catalogDir}/users/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n });\n };\n\n/**\n * Write a user to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeUser } = utils('/path/to/eventcatalog');\n *\n * // Write a user to the catalog\n * // user would be written to users/eventcatalog-tech-lead\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeUser =\n (catalogDir: string) =>\n async (user: User, options: { override?: boolean } = {}) => {\n const resource: User = { ...user };\n\n // Get the path\n const currentUser = await getUser(catalogDir)(resource.id);\n const exists = currentUser !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (user) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a user by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmUserById } = utils('/path/to/eventcatalog');\n *\n * // deletes the user with id eventcatalog-core-user\n * await rmUserById('eventcatalog-core-user');\n *\n * ```\n */\nexport const rmUserById = (catalogDir: string) => async (id: string) => {\n fsSync.rmSync(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAOA,aAAY;AACnB,SAAS,QAAAC,aAAY;AAErB,OAAOC,aAAY;;;ACJnB,SAAS,gBAAgB;AACzB,OAAO,YAAY;AACnB,SAAS,YAA6C;AACtD,SAAS,MAAM,SAAS,WAAiC,SAAmB,gBAAgB;AAC5F,OAAO,YAAY;AACnB,SAAS,WAAW,kBAAyB;AAWtC,IAAM,eAAe,OAAO,YAAoB,IAAY,YAAkD;AACnH,QAAM,QAAQ,MAAM,SAAS,GAAG,UAAU,oBAAoB;AAE9D,QAAM,eAAgB,MAAM,iBAAiB,OAAO,EAAE,KAAM,CAAC;AAC7D,QAAM,gBAAgB,aAAa,KAAK,CAACC,UAAS,CAACA,MAAK,SAAS,WAAW,CAAC;AAG7E,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAGA,QAAM,cAAc,aAAa,IAAI,CAACA,UAAS;AAC7C,UAAM,EAAE,KAAK,IAAI,OAAO,KAAKA,KAAI;AACjC,WAAO,EAAE,GAAG,MAAM,MAAAA,MAAK;AAAA,EACzB,CAAC;AAGD,MAAI,YAAY,UAAU;AACxB,WAAO;AAAA,EACT;AAGA,QAAM,aAAa,YAAY,KAAK,CAAC,MAAM,EAAE,YAAY,OAAO;AAChE,MAAI,YAAY;AACd,WAAO,WAAW;AAAA,EACpB;AAGA,QAAM,cAAc,WAAW,OAAO;AAEtC,MA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CAAC,MAAM;AAC1D,QAAM,WAAiB,EAAE,GAAG,KAAK;AAGjC,QAAM,cAAc,MAAM,QAAQ,UAAU,EAAE,SAAS,EAAE;AACzD,QAAM,SAAS,gBAAgB;AAE/B,MAAI,UAAU,CAAC,QAAQ,UAAU;AAC/B,UAAM,IAAI,MAAM,mBAAmB,SAAS,EAAE,8BAA8B;AAAA,EAC9E;AAEA,QAAM,EAAE,UAAU,GAAG,YAAY,IAAI;AAErC,QAAM,WAAWA,QAAO,UAAU,UAAU,WAAW;AACvD,EAAAC,QAAO,UAAUC,MAAK,YAAY,EAAE,GAAG,EAAE,WAAW,KAAK,CAAC;AAC1D,EAAAD,QAAO,cAAcC,MAAK,YAAY,IAAI,GAAG,SAAS,EAAE,MAAM,GAAG,QAAQ;AAC3E;AAgBK,IAAM,aAAa,CAAC,eAAuB,OAAO,OAAe;AACtE,QAAM,GAAG,GAAGA,MAAK,YAAY,GAAG,EAAE,MAAM,GAAG,EAAE,WAAW,KAAK,CAAC;AAChE;AAQO,IAAM,uBAAuB,CAAC,eAAuB,OAAO,IAAY,YAAqB;AAClG,QAAM,WAAW,MAAM,YAAY,YAAY,IAAI,OAAO;AAC1D,MAAI,SAAiB,CAAC;AACtB,MAAI,CAAC,SAAU,QAAO,CAAC;AAEvB,MAAI,CAAC,SAAS,OAAQ,QAAO,CAAC;AAG9B,aAAW,SAAS,SAAS,QAAQ;AACnC,UAAM,OAAO,MAAM,QAAQ,KAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,QAAI,MAAM;AACR,aAAO,KAAK,IAAI;AAAA,IAClB,OAAO;AAEL,YAAM,OAAO,MAAM,QAAQ,KAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,UAAI,MAAM;AACR,eAAO,KAAK,IAAI;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["fsSync","join","matter","path","dirname","join","matter","fsSync","satisfies","fsSync","matter","dirname","join","matter","matter","matter","fsSync","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/teams.ts","../src/internal/utils.ts","../src/internal/resources.ts","../src/users.ts"],"sourcesContent":["import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { Team } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\nimport { getResource } from './internal/resources';\nimport path from 'node:path';\nimport { getUser, getUsers } from './users';\n\n/**\n * Returns a team from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeam } = utils('/path/to/eventcatalog');\n *\n * // Gets the team with the given id\n * const team = await getTeam('eventcatalog-core-team');\n *\n * ```\n */\nexport const getTeam =\n (catalogDir: string) =>\n async (id: string): Promise<Team | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n };\n\n/**\n * Returns all teams from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getTeams } = utils('/path/to/eventcatalog');\n *\n * // Gets all teams from the catalog\n * const channels = await getTeams();\n *\n * ```\n */\nexport const getTeams =\n (catalogDir: string) =>\n async (options?: {}): Promise<Team[]> => {\n const files = await getFiles(`${catalogDir}/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n markdown: content.trim(),\n } as Team;\n });\n };\n\n/**\n * Write a team to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeTeam } = utils('/path/to/eventcatalog');\n *\n * // Write a team to the catalog\n * // team would be written to teams/EventCatalogCoreTeam\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeTeam({\n * id: 'eventcatalog-core-team',\n * name: 'EventCatalogCoreTeam',\n * members: ['dboyne', 'asmith', 'msmith'],\n * email: 'test@test.com',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeTeam =\n (catalogDir: string) =>\n async (team: Team, options: { override?: boolean } = {}) => {\n const resource: Team = { ...team };\n\n // Get the path\n const currentTeam = await getTeam(catalogDir)(resource.id);\n const exists = currentTeam !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (team) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a team by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmTeamById } = utils('/path/to/eventcatalog');\n *\n * // deletes the EventCatalogCoreTeam team\n * await rmTeamById('eventcatalog-core-team');\n *\n * ```\n */\nexport const rmTeamById = (catalogDir: string) => async (id: string) => {\n await fs.rm(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n\n/**\n * Returns the owners for a given resource (e.g domain, service, event, command, query, etc.)\n * @param id - The id of the resource to get the owners for\n * @param version - Optional version of the resource\n * @returns { owners: User[] }\n */\nexport const getOwnersForResource = (catalogDir: string) => async (id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n let owners: Team[] = [];\n if (!resource) return [];\n\n if (!resource.owners) return [];\n\n // First check if the owner is a team\n for (const owner of resource.owners) {\n const team = await getTeam(path.join(catalogDir, 'teams'))(owner);\n if (team) {\n owners.push(team);\n } else {\n // If the owner is not a team, check if it's a user\n const user = await getUser(path.join(catalogDir, 'users'))(owner);\n if (user) {\n owners.push(user);\n }\n }\n }\n\n return owners;\n};\n","import { globSync } from 'glob';\nimport fsSync from 'node:fs';\nimport { copy, CopyFilterAsync, CopyFilterSync } from 'fs-extra';\nimport { join, dirname, normalize, sep as pathSeparator, resolve, basename, relative } from 'node:path';\nimport matter from 'gray-matter';\nimport { satisfies, validRange, valid } from 'semver';\n\n/**\n * Returns true if a given version of a resource id exists in the catalog\n */\nexport const versionExists = async (catalogDir: string, id: string, version: string) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = (await searchFilesForId(files, id, version)) || [];\n return matchedFiles.length > 0;\n};\n\nexport const findFileById = async (catalogDir: string, id: string, version?: string): Promise<string | undefined> => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = (await searchFilesForId(files, id)) || [];\n const latestVersion = matchedFiles.find((path) => !path.includes('versioned'));\n\n // If no version is provided, return the latest version\n if (!version) {\n return latestVersion;\n }\n\n // map files into gray matter to get versions\n const parsedFiles = matchedFiles.map((path) => {\n const { data } = matter.read(path);\n return { ...data, path };\n }) as any[];\n\n // Handle 'latest' version - return the latest (non-versioned) file\n if (version === 'latest') {\n return latestVersion;\n }\n\n // First, check for exact version match (handles non-semver versions like '1', '2', etc.)\n const exactMatch = parsedFiles.find((c) => c.version === version);\n if (exactMatch) {\n return exactMatch.path;\n }\n\n // Try semver range matching\n const semverRange = validRange(version);\n\n if (semverRange) {\n const match = parsedFiles.filter((c) => {\n try {\n return satisfies(c.version, semverRange);\n } catch (error) {\n // If satisfies fails (e.g., comparing semver range with non-semver version), skip this file\n return false;\n }\n });\n return match.length > 0 ? match[0].path : undefined;\n }\n\n // If no exact match and no valid semver range, return undefined\n return undefined;\n};\n\nexport const getFiles = async (pattern: string, ignore: string | string[] = '') => {\n try {\n // 1. Normalize the input pattern to handle mixed separators potentially\n const normalizedInputPattern = normalize(pattern);\n\n // 2. Determine the absolute base directory (cwd for glob)\n // Resolve ensures it's absolute. Handles cases with/without globstar.\n const absoluteBaseDir = resolve(\n normalizedInputPattern.includes('**') ? normalizedInputPattern.split('**')[0] : dirname(normalizedInputPattern)\n );\n\n // 3. Determine the pattern part relative to the absolute base directory\n // We extract the part of the normalized pattern that comes *after* the absoluteBaseDir\n let relativePattern = relative(absoluteBaseDir, normalizedInputPattern);\n\n // On Windows, relative() might return empty string if paths are identical,\n // or might need normalization if the original pattern didn't have `**`\n // Example: pattern = 'dir/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\file.md'\n // relative() -> 'file.md'\n // Example: pattern = 'dir/**/file.md', absoluteBaseDir='.../dir', normalized='...\\dir\\**\\file.md'\n // relative() -> '**\\file.md'\n // Convert separators in the relative pattern to forward slashes for glob\n relativePattern = relativePattern.replace(/\\\\/g, '/');\n\n const ignoreList = Array.isArray(ignore) ? ignore : [ignore];\n\n const files = globSync(relativePattern, {\n cwd: absoluteBaseDir,\n ignore: ['node_modules/**', ...ignoreList],\n absolute: true,\n nodir: true,\n });\n\n // 5. Normalize results for consistency before returning\n return files.map(normalize);\n } catch (error: any) {\n // Add more diagnostic info to the error\n const absoluteBaseDirForError = resolve(\n normalize(pattern).includes('**') ? normalize(pattern).split('**')[0] : dirname(normalize(pattern))\n );\n const relativePatternForError = relative(absoluteBaseDirForError, normalize(pattern)).replace(/\\\\/g, '/');\n throw new Error(\n `Error finding files for pattern \"${pattern}\" (using cwd: \"${absoluteBaseDirForError}\", globPattern: \"${relativePatternForError}\"): ${error.message}`\n );\n }\n};\n\nexport const readMdxFile = async (path: string) => {\n const { data } = matter.read(path);\n const { markdown, ...frontmatter } = data;\n return { ...frontmatter, markdown };\n};\n\nexport const searchFilesForId = async (files: string[], id: string, version?: string) => {\n // Escape the id to avoid regex issues\n const escapedId = id.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n const idRegex = new RegExp(`^id:\\\\s*(['\"]|>-)?\\\\s*${escapedId}['\"]?\\\\s*$`, 'm');\n\n const versionRegex = new RegExp(`^version:\\\\s*['\"]?${version}['\"]?\\\\s*$`, 'm');\n\n const matches = files.map((file) => {\n const content = fsSync.readFileSync(file, 'utf-8');\n const hasIdMatch = content.match(idRegex);\n\n // Check version if provided\n if (version && !content.match(versionRegex)) {\n return undefined;\n }\n\n if (hasIdMatch) {\n return file;\n }\n });\n\n return matches.filter(Boolean).filter((file) => file !== undefined);\n};\n\n/**\n * Function to copy a directory from source to target, uses a tmp directory\n * @param catalogDir\n * @param source\n * @param target\n * @param filter\n */\nexport const copyDir = async (catalogDir: string, source: string, target: string, filter?: CopyFilterAsync | CopyFilterSync) => {\n const tmpDirectory = join(catalogDir, 'tmp');\n fsSync.mkdirSync(tmpDirectory, { recursive: true });\n\n // Copy everything over\n await copy(source, tmpDirectory, {\n overwrite: true,\n filter,\n });\n\n await copy(tmpDirectory, target, {\n overwrite: true,\n filter,\n });\n\n // Remove the tmp directory\n fsSync.rmSync(tmpDirectory, { recursive: true });\n};\n\n// Makes sure values in sends/recieves are unique\nexport const uniqueVersions = (messages: { id: string; version: string }[]): { id: string; version: string }[] => {\n const uniqueSet = new Set();\n\n return messages.filter((message) => {\n const key = `${message.id}-${message.version}`;\n if (!uniqueSet.has(key)) {\n uniqueSet.add(key);\n return true;\n }\n return false;\n });\n};\n","import { dirname, join } from 'path';\nimport { copyDir, findFileById, getFiles, searchFilesForId, versionExists } from './utils';\nimport matter from 'gray-matter';\nimport fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { Message, Service, CustomDoc } from '../types';\nimport { satisfies } from 'semver';\nimport { lock, unlock } from 'proper-lockfile';\nimport { basename } from 'node:path';\nimport path from 'node:path';\n\ntype Resource = Service | Message | CustomDoc;\n\nexport const versionResource = async (catalogDir: string, id: string) => {\n // Find all the events in the directory\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n const matchedFiles = await searchFilesForId(files, id);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No resource found with id: ${id}`);\n }\n\n // Event that is in the route of the project\n const file = matchedFiles[0];\n // Handle both forward and back slashes for cross-platform compatibility (Windows uses \\, Unix uses /)\n const sourceDirectory = dirname(file).replace(/[/\\\\]versioned[/\\\\][^/\\\\]+[/\\\\]/, path.sep);\n const { data: { version = '0.0.1' } = {} } = matter.read(file);\n const targetDirectory = getVersionedDirectory(sourceDirectory, version);\n\n fsSync.mkdirSync(targetDirectory, { recursive: true });\n\n const ignoreListToCopy = ['events', 'commands', 'queries', 'versioned'];\n\n // Copy the event to the versioned directory\n await copyDir(catalogDir, sourceDirectory, targetDirectory, (src) => {\n // get the folder name\n const folderName = basename(src);\n\n if (ignoreListToCopy.includes(folderName)) {\n return false;\n }\n return true;\n });\n\n // Remove all the files in the root of the resource as they have now been versioned\n await fs.readdir(sourceDirectory).then(async (resourceFiles) => {\n await Promise.all(\n resourceFiles.map(async (file) => {\n // Dont remove anything in the ignore list\n if (ignoreListToCopy.includes(file)) {\n return;\n }\n if (file !== 'versioned') {\n fsSync.rmSync(join(sourceDirectory, file), { recursive: true });\n }\n })\n );\n });\n};\n\nexport const writeResource = async (\n catalogDir: string,\n resource: Resource,\n options: { path?: string; type: string; override?: boolean; versionExistingContent?: boolean; format?: 'md' | 'mdx' } = {\n path: '',\n type: '',\n override: false,\n versionExistingContent: false,\n format: 'mdx',\n }\n) => {\n const path = options.path || `/${resource.id}`;\n const fullPath = join(catalogDir, path);\n const format = options.format || 'mdx';\n\n // Create directory if it doesn't exist\n fsSync.mkdirSync(fullPath, { recursive: true });\n\n // Create or get lock file path\n const lockPath = join(fullPath, `index.${format}`);\n\n // Ensure the file exists before attempting to lock it\n if (!fsSync.existsSync(lockPath)) {\n fsSync.writeFileSync(lockPath, '');\n }\n\n try {\n // Acquire lock with retry\n await lock(lockPath, {\n retries: 5,\n stale: 10000, // 10 seconds\n });\n\n const exists = await versionExists(catalogDir, resource.id, resource.version);\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (${options.type}) as the version ${resource.version} already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n if (options.versionExistingContent && !exists) {\n const currentResource = await getResource(catalogDir, resource.id);\n\n if (currentResource) {\n if (satisfies(resource.version, `>${currentResource.version}`)) {\n await versionResource(catalogDir, resource.id);\n } else {\n throw new Error(`New version ${resource.version} is not greater than current version ${currentResource.version}`);\n }\n }\n }\n\n const document = matter.stringify(markdown.trim(), frontmatter);\n fsSync.writeFileSync(lockPath, document);\n } finally {\n // Always release the lock\n await unlock(lockPath).catch(() => {});\n }\n};\n\nexport const getResource = async (\n catalogDir: string,\n id?: string,\n version?: string,\n options?: { type: string; attachSchema?: boolean },\n filePath?: string\n): Promise<Resource | undefined> => {\n const attachSchema = options?.attachSchema || false;\n const file = filePath || (id ? await findFileById(catalogDir, id, version) : undefined);\n if (!file || !fsSync.existsSync(file)) return;\n\n const { data, content } = matter.read(file);\n\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResourcePath = async (catalogDir: string, id: string, version?: string) => {\n const file = await findFileById(catalogDir, id, version);\n if (!file) return;\n\n return {\n fullPath: file,\n relativePath: file.replace(catalogDir, ''),\n directory: dirname(file.replace(catalogDir, '')),\n };\n};\n\nexport const getResourceFolderName = async (catalogDir: string, id: string, version?: string) => {\n const paths = await getResourcePath(catalogDir, id, version);\n if (!paths) return;\n return paths?.directory.split(path.sep).filter(Boolean).pop();\n};\n\nexport const toResource = async (catalogDir: string, rawContents: string) => {\n const { data, content } = matter(rawContents);\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n};\n\nexport const getResources = async (\n catalogDir: string,\n {\n type,\n latestOnly = false,\n ignore = [],\n pattern = '',\n attachSchema = false,\n }: { type: string; pattern?: string; latestOnly?: boolean; ignore?: string[]; attachSchema?: boolean }\n): Promise<Resource[] | undefined> => {\n const ignoreList = latestOnly ? `**/versioned/**` : '';\n const filePattern = pattern || `${catalogDir}/**/${type}/**/index.{md,mdx}`;\n const files = await getFiles(filePattern, [ignoreList, ...ignore]);\n\n if (files.length === 0) return;\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n\n // Attach the schema if the attachSchema option is set to true\n if (attachSchema && data?.schemaPath) {\n const resourceDirectory = dirname(file);\n const pathToSchema = join(resourceDirectory, data.schemaPath);\n if (fsSync.existsSync(pathToSchema)) {\n const schema = fsSync.readFileSync(pathToSchema, 'utf8');\n // Try to parse the schema\n try {\n data.schema = JSON.parse(schema);\n } catch (error) {\n data.schema = schema;\n }\n }\n }\n return {\n ...data,\n markdown: content.trim(),\n } as Resource;\n });\n};\n\nexport const rmResourceById = async (\n catalogDir: string,\n id: string,\n version?: string,\n options?: { type: string; persistFiles?: boolean }\n) => {\n const files = await getFiles(`${catalogDir}/**/index.{md,mdx}`);\n\n const matchedFiles = await searchFilesForId(files, id, version);\n\n if (matchedFiles.length === 0) {\n throw new Error(`No ${options?.type || 'resource'} found with id: ${id}`);\n }\n\n if (options?.persistFiles) {\n await Promise.all(\n matchedFiles.map(async (file) => {\n await fs.rm(file, { recursive: true });\n // Verify file is actually removed\n await waitForFileRemoval(file);\n })\n );\n } else {\n await Promise.all(\n matchedFiles.map(async (file) => {\n const directory = dirname(file);\n await fs.rm(directory, { recursive: true, force: true });\n // Verify directory is actually removed\n await waitForFileRemoval(directory);\n })\n );\n }\n};\n\n// Helper function to ensure file/directory is completely removed\nconst waitForFileRemoval = async (path: string, maxRetries: number = 50, delay: number = 10): Promise<void> => {\n for (let i = 0; i < maxRetries; i++) {\n try {\n await fs.access(path);\n // If access succeeds, file still exists, wait and retry\n await new Promise((resolve) => setTimeout(resolve, delay));\n } catch (error) {\n // If access fails, file is removed\n return;\n }\n }\n // If we reach here, file still exists after all retries\n throw new Error(`File/directory ${path} was not removed after ${maxRetries} attempts`);\n};\n\nexport const addFileToResource = async (\n catalogDir: string,\n id: string,\n file: { content: string; fileName: string },\n version?: string,\n options?: { path?: string }\n) => {\n let pathToResource: string | undefined;\n\n if (options?.path) {\n pathToResource = join(catalogDir, options.path, 'index.mdx');\n } else {\n // Fall back to global lookup (existing behavior)\n pathToResource = await findFileById(catalogDir, id, version);\n }\n\n if (!pathToResource) throw new Error('Cannot find directory to write file to');\n\n // Create the directory if it doesn't exist\n fsSync.mkdirSync(path.dirname(pathToResource), { recursive: true });\n\n let fileContent = file.content.trim();\n\n try {\n const json = JSON.parse(fileContent);\n fileContent = JSON.stringify(json, null, 2);\n } catch (error) {\n // Just silently fail if the file is not valid JSON\n // Write it as it is\n }\n\n fsSync.writeFileSync(join(dirname(pathToResource), file.fileName), fileContent);\n};\n\nexport const getFileFromResource = async (catalogDir: string, id: string, file: { fileName: string }, version?: string) => {\n const pathToResource = await findFileById(catalogDir, id, version);\n\n if (!pathToResource) throw new Error('Cannot find directory of resource');\n\n const exists = await fs\n .access(join(dirname(pathToResource), file.fileName))\n .then(() => true)\n .catch(() => false);\n if (!exists) throw new Error(`File ${file.fileName} does not exist in resource ${id} v(${version})`);\n\n return fsSync.readFileSync(join(dirname(pathToResource), file.fileName), 'utf-8');\n};\nexport const getVersionedDirectory = (sourceDirectory: string, version: any): string => {\n return join(sourceDirectory, 'versioned', version);\n};\n\nexport const isLatestVersion = async (catalogDir: string, id: string, version?: string) => {\n const resource = await getResource(catalogDir, id, version);\n if (!resource) return false;\n\n const pathToResource = await getResourcePath(catalogDir, id, version);\n\n return !pathToResource?.relativePath.replace(/\\\\/g, '/').includes('/versioned/');\n};\n","import fs from 'node:fs/promises';\nimport fsSync from 'node:fs';\nimport { join } from 'node:path';\nimport type { User } from './types';\nimport matter from 'gray-matter';\nimport { getFiles } from './internal/utils';\n\n/**\n * Returns a user from EventCatalog.\n *\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUser } = utils('/path/to/eventcatalog');\n *\n * // Gets the user with the given id\n * const user = await getUser('eventcatalog-core-user');\n *\n * ```\n */\nexport const getUser =\n (catalogDir: string) =>\n async (id: string): Promise<User | undefined> => {\n const files = await getFiles(`${catalogDir}/${id}.{md,mdx}`);\n\n if (files.length == 0) return undefined;\n const file = files[0];\n\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n };\n\n/**\n * Returns all users from EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { getUsers } = utils('/path/to/eventcatalog');\n *\n * // Gets all users from the catalog\n * const channels = await getUsers();\n *\n * ```\n */\nexport const getUsers =\n (catalogDir: string) =>\n async (options?: {}): Promise<User[]> => {\n const files = await getFiles(`${catalogDir}/users/*.{md,mdx}`);\n if (files.length === 0) return [];\n\n return files.map((file) => {\n const { data, content } = matter.read(file);\n return {\n ...data,\n id: data.id,\n name: data.name,\n avatarUrl: data.avatarUrl,\n markdown: content.trim(),\n } as User;\n });\n };\n\n/**\n * Write a user to EventCatalog.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { writeUser } = utils('/path/to/eventcatalog');\n *\n * // Write a user to the catalog\n * // user would be written to users/eventcatalog-tech-lead\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * });\n *\n * // Write a team to the catalog and override the existing content (if there is any)\n * await writeUser({\n * id: 'eventcatalog-tech-lead',\n * name: 'EventCatalog Tech Lead',\n * email: 'test@test.com',\n * avatarUrl: 'https://pbs.twimg.com/profile_images/1262283153563140096/DYRDqKg6_400x400.png',\n * slackDirectMessageUrl: https://yourteam.slack.com/channels/boyney123\n * }, { override: true });\n *\n * ```\n */\nexport const writeUser =\n (catalogDir: string) =>\n async (user: User, options: { override?: boolean } = {}) => {\n const resource: User = { ...user };\n\n // Get the path\n const currentUser = await getUser(catalogDir)(resource.id);\n const exists = currentUser !== undefined;\n\n if (exists && !options.override) {\n throw new Error(`Failed to write ${resource.id} (user) as it already exists`);\n }\n\n const { markdown, ...frontmatter } = resource;\n\n const document = matter.stringify(markdown, frontmatter);\n fsSync.mkdirSync(join(catalogDir, ''), { recursive: true });\n fsSync.writeFileSync(join(catalogDir, '', `${resource.id}.mdx`), document);\n };\n\n/**\n * Delete a user by it's id.\n *\n * @example\n * ```ts\n * import utils from '@eventcatalog/utils';\n *\n * const { rmUserById } = utils('/path/to/eventcatalog');\n *\n * // deletes the user with id eventcatalog-core-user\n * await rmUserById('eventcatalog-core-user');\n *\n * ```\n */\nexport const rmUserById = (catalogDir: string) => async (id: string) => {\n fsSync.rmSync(join(catalogDir, `${id}.mdx`), { recursive: true });\n};\n"],"mappings":";AAAA,OAAO,QAAQ;AACf,OAAOA,aAAY;AACnB,SAAS,QAAAC,aAAY;AAErB,OAAOC,aAAY;;;ACJnB,SAAS,gBAAgB;AACzB,OAAO,YAAY;AACnB,SAAS,YAA6C;AACtD,SAAS,MAAM,SAAS,WAAiC,SAAmB,gBAAgB;AAC5F,OAAO,YAAY;AACnB,SAAS,WAAW,kBAAyB;AAWtC,IAAM,eAAe,OAAO,YAAoB,IAAY,YAAkD;AACnH,QAAM,QAAQ,MAAM,SAAS,GAAG,UAAU,oBAAoB;AAE9D,QAAM,eAAgB,MAAM,iBAAiB,OAAO,EAAE,KAAM,CAAC;AAC7D,QAAM,gBAAgB,aAAa,KAAK,CAACC,UAAS,CAACA,MAAK,SAAS,WAAW,CAAC;AAG7E,MAAI,CAAC,SAAS;AACZ,WAAO;AAAA,EACT;AAGA,QAAM,cAAc,aAAa,IAAI,CAACA,UAAS;AAC7C,UAAM,EAAE,KAAK,IAAI,OAAO,KAAKA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AAK,IAAI;AAAA,IAClB,OAAO;AAEL,YAAM,OAAO,MAAM,QAAQ,KAAK,KAAK,YAAY,OAAO,CAAC,EAAE,KAAK;AAChE,UAAI,MAAM;AACR,eAAO,KAAK,IAAI;AAAA,MAClB;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;","names":["fsSync","join","matter","path","dirname","join","matter","fsSync","satisfies","fsSync","matter","dirname","join","matter","matter","matter","fsSync","join"]}
|