@tiptap/cli 3.19.5 → 3.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +70 -0
- package/dist/LICENSE.sass +1692 -0
- package/dist/index.js +78 -45
- package/dist/index.js.map +1 -1
- package/dist/sass.cjs +413 -0
- package/package.json +10 -5
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/add.ts","../src/inquirer/select.ts","../src/preflights/preflight-add.ts","../src/utils/get-config.ts","../src/utils/resolve-import.ts","../src/utils/get-project-info.ts","../src/utils/frameworks.ts","../src/utils/get-package-info.ts","../src/utils/colors.ts","../src/utils/logger.ts","../src/utils/add-components.ts","../src/utils/handle-error.ts","../src/utils/registry/schema.ts","../src/utils/registry/index.ts","../src/utils/token-storage.ts","../src/utils/bootstrap.ts","../src/utils/spinner.ts","../src/utils/get-package-manager.ts","../src/utils/updaters/update-dependencies.ts","../src/utils/updaters/update-files.ts","../src/utils/transformers/index.ts","../src/utils/transformers/transform-import.ts","../src/utils/transformers/transform-jsx.ts","../src/utils/transformers/transform-rsc.ts","../src/utils/transformers/transform-remove-components.ts","../src/utils/transformers/transform-scss-to-css.ts","../src/utils/updaters/update-dev-dependencies.ts","../src/utils/common.ts","../src/utils/auth.ts","../src/utils/package-manager-config.ts","../src/commands/auth.ts","../src/utils/auth-check.ts","../src/utils/cli-ui.ts","../src/utils/prompt-messages.ts","../src/utils/auto-import-styles.ts","../src/commands/info.ts","../src/commands/init.ts","../src/preflights/preflight-init.ts","../src/utils/create-project.ts","../src/index.ts","../package.json"],"sourcesContent":["import path from \"path\"\nimport { Command } from \"commander\"\nimport { z } from \"zod\"\nimport select from \"@/src/inquirer/select\"\nimport { Separator, input, confirm, checkbox } from \"@inquirer/prompts\"\nimport { preFlightAdd } from \"@/src/preflights/preflight-add\"\nimport { addComponents } from \"@/src/utils/add-components\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { getRegistryIndex } from \"@/src/utils/registry\"\nimport { colors } from \"@/src/utils/colors\"\nimport type { RegistryItemIndexSchema } from \"@/src/utils/registry/schema\"\nimport { toReadableName } from \"@/src/utils/common\"\nimport { ensureAuthForPaidComponents } from \"../utils/auth-check\"\nimport { PAID_PLANS, type Plan } from \"../utils/registry/schema\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport {\n showNotionEnvSetupMessage,\n showNotionTemplateSetupMessage,\n showStylesConfigurationMessage,\n showTableNodeSetupMessage,\n} from \"@/src/utils/prompt-messages\"\nimport {\n createWelcomeBanner,\n logLines,\n createExplanationSection,\n clearTerminal,\n createSpacedDivider,\n} from \"@/src/utils/cli-ui\"\nimport {\n autoImportStyles,\n logAutoImportResult,\n} from \"@/src/utils/auto-import-styles\"\n\nexport const addOptionsSchema = z.object({\n components: z.array(z.string()).optional(),\n cwd: z.string(),\n path: z.string().optional(),\n silent: z.boolean(),\n overwrite: z.boolean(),\n})\n\ntype AddOptions = z.infer<typeof addOptionsSchema>\n\ninterface CategoryMap {\n templates: RegistryItemIndexSchema\n newComponents: RegistryItemIndexSchema\n ui: RegistryItemIndexSchema\n primitives: RegistryItemIndexSchema\n uiUtils: RegistryItemIndexSchema\n nodes: RegistryItemIndexSchema\n}\n\nconst PROMPT_PAGE_SIZE = 1_000 // Large size to avoid help tip\nconst TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH = 92\nconst TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH = 48\nconst TEMPLATE_DESCRIPTION_INDENT_WIDTH = 4\n\nconst UI = {\n emptyRegistry: colors.red(\"❌ No components or templates found\"),\n operationCancelled: colors.gray(\"Operation cancelled\"),\n missingDirectory: colors.red(\n \"❌ Directory not found. Use init to initialize a project first.\"\n ),\n}\n\nconst PROMPT_THEME = {\n icon: {\n cursor: colors.cyan(\"▸\"),\n checked: colors.cyan(\"◉\"),\n unchecked: \"○\",\n },\n style: {\n highlight: (text: string) => colors.cyan(text),\n message: (text: string) => text,\n answer: (text: string) => \"\", // Hide inline answer display\n },\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: colors.cyan(\"?\"),\n },\n}\n\nfunction normalizeDescription(description?: string): string {\n const normalized = description?.replace(/\\s+/g, \" \").trim()\n return normalized ?? \"\"\n}\n\nfunction wrapText(text: string, maxLineLength: number): string[] {\n const words = text.split(\" \")\n const lines: string[] = []\n let currentLine = \"\"\n\n for (const word of words) {\n const nextLine = currentLine ? `${currentLine} ${word}` : word\n\n if (nextLine.length > maxLineLength && currentLine) {\n lines.push(currentLine)\n currentLine = word\n } else {\n currentLine = nextLine\n }\n }\n\n if (currentLine) {\n lines.push(currentLine)\n }\n\n return lines\n}\n\nfunction getTemplateDescriptionLineWidth(): number {\n const terminalWidth = process.stdout.columns\n\n if (!terminalWidth) {\n return TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH\n }\n\n return Math.max(\n TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH,\n Math.min(\n TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH,\n terminalWidth - TEMPLATE_DESCRIPTION_INDENT_WIDTH\n )\n )\n}\n\nfunction formatTemplatePlanLabel(plans?: Plan[]): string {\n const planLabel = getPlanLabel(plans)\n\n if (plans?.includes(\"light\") || plans?.includes(\"open-source\")) {\n return \"Open Source - MIT\"\n }\n\n return planLabel\n}\n\nfunction formatTemplateChoiceName(template: RegistryItemIndexSchema[number]) {\n const planLabel = formatTemplatePlanLabel(template.plans)\n const name = `${colors.bold(toReadableName(template.name))} ${colors.dim(\n `(${planLabel})`\n )}:`\n const description = normalizeDescription(template.description)\n\n if (!description) {\n return name\n }\n\n const descriptionLines = wrapText(\n description,\n getTemplateDescriptionLineWidth()\n ).map((line) => ` ${line}`)\n\n return [name, ...descriptionLines].join(\"\\n\")\n}\n\nfunction getPlanLabel(plans?: Plan[]): string {\n if (!plans?.length) {\n return \"Free\"\n }\n\n if (plans.includes(\"light\") || plans.includes(\"open-source\")) {\n return \"Open source (MIT)\"\n }\n\n const requiredPlan = PAID_PLANS.find((plan) => plans.includes(plan))\n if (!requiredPlan) {\n return \"Free\"\n }\n\n const planName = `${requiredPlan[0].toUpperCase()}${requiredPlan.slice(1)}`\n return requiredPlan === \"start\"\n ? `${planName} plan • Trial`\n : `${planName} plan`\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nconst createThemedConfirm = (message: string, defaultValue: boolean = true) => {\n return confirm({\n message,\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Filters templates to only include free ones based on registry data\n */\nfunction filterFreeTemplates(\n templates: RegistryItemIndexSchema,\n freeComponents: string[] | null\n): RegistryItemIndexSchema {\n if (!freeComponents) {\n return templates\n }\n\n return templates.filter((template) => freeComponents.includes(template.name))\n}\n\n/**\n * Clears specified number of lines from console\n */\nfunction clearPromptLines(lines: number) {\n for (let i = 0; i < lines; i++) {\n process.stdout.write(\"\\x1B[1A\") // Move cursor up\n process.stdout.write(\"\\x1B[2K\") // Clear line\n }\n}\n\n/**\n * Categorizes registry items by type\n */\nconst categorizeRegistryItems = (\n registryIndex: RegistryItemIndexSchema\n): CategoryMap => {\n return {\n templates: registryIndex.filter(\n (entry) => entry.type === \"registry:template\"\n ),\n newComponents: registryIndex.filter((entry) => entry.isNew === true),\n ui: registryIndex.filter((entry) => entry.type === \"registry:ui\"),\n primitives: registryIndex.filter(\n (entry) => entry.type === \"registry:ui-primitive\"\n ),\n uiUtils: registryIndex.filter(\n (entry) => entry.type === \"registry:ui-utils\"\n ),\n nodes: registryIndex.filter((entry) => entry.type === \"registry:node\"),\n }\n}\n\n/**\n * Prompts user to select between components and templates\n */\nasync function promptForInitialSelection(\n categories: CategoryMap,\n showDivider = true\n): Promise<\"components\" | \"templates\" | null> {\n const message = \"What would you like to integrate?\"\n\n const choices = []\n const isComponentEmpty =\n categories.ui.length === 0 &&\n categories.nodes.length === 0 &&\n categories.newComponents.length === 0\n const isTemplateEmpty = categories.templates.length === 0\n\n if (!isTemplateEmpty) {\n choices.push({\n name: \"Templates - Full editor applications\",\n value: \"templates\",\n })\n }\n\n if (!isComponentEmpty) {\n choices.push({\n name: \"UI Components - Individual editor building blocks\",\n value: \"components\",\n })\n }\n\n if (choices.length === 0) {\n logger.break()\n console.log(UI.emptyRegistry)\n return null\n }\n\n try {\n if (showDivider) {\n console.log(createSpacedDivider())\n }\n\n const selection = await select({\n message: colors.reset(message),\n pageSize: PROMPT_PAGE_SIZE,\n theme: PROMPT_THEME,\n choices,\n })\n\n if (showDivider) {\n console.log(createSpacedDivider())\n }\n\n return selection as \"templates\" | \"components\"\n } catch (error) {\n clearPromptLines(4)\n console.log(UI.operationCancelled)\n return null\n }\n}\n\n/**\n * Creates choices for component menu with appropriate sections\n */\nasync function createComponentChoices(\n categories: CategoryMap,\n components: string[] | null\n): Promise<Array<{ name: string; value: string } | Separator>> {\n const choices: Array<{ name: string; value: string } | Separator> = []\n\n if (!components) {\n return choices\n }\n\n const addCategorySection = (\n items: RegistryItemIndexSchema,\n title: string\n ) => {\n const filteredItems = items.filter((item) => components.includes(item.name))\n\n if (filteredItems.length > 0) {\n choices.push(new Separator(\"\"))\n choices.push(new Separator(colors.whiteBold(` ${title}`)))\n\n filteredItems.forEach((item) => {\n const planLabel = getPlanLabel(item.plans)\n\n const name = toReadableName(item.name)\n const paddedName = name.padEnd(35)\n\n choices.push({\n name: `${paddedName} ${colors.dim(planLabel)}`,\n value: item.name,\n })\n })\n\n choices.push(new Separator(\" \"))\n }\n }\n\n const addNewComponentsSection = (\n items: RegistryItemIndexSchema,\n title: string\n ) => {\n const filteredItems = items.filter((item) => components.includes(item.name))\n\n if (filteredItems.length > 0) {\n choices.push(new Separator(\"\"))\n choices.push(new Separator(colors.whiteBold(` ${title}`)))\n\n filteredItems.forEach((item) => {\n const planLabel = getPlanLabel(item.plans)\n\n const name = toReadableName(item.name)\n const paddedName = name.padEnd(35)\n const description = item.description\n ? `\\n ${colors.dim(item.description)}`\n : \"\"\n\n choices.push({\n name: `${paddedName} ${colors.dim(planLabel)}${description}`,\n value: item.name,\n })\n })\n\n choices.push(new Separator(\" \"))\n }\n }\n\n addNewComponentsSection(categories.newComponents, \"NEW COMPONENTS\")\n addCategorySection(categories.ui, \"UI COMPONENTS\")\n addCategorySection(categories.nodes, \"NODE COMPONENTS\")\n addCategorySection(categories.primitives, \"PRIMITIVES\")\n\n return choices\n}\n\n/**\n * Shows menu for selecting components\n */\nasync function componentMenu(\n categories: CategoryMap,\n components: string[] | null\n): Promise<string[]> {\n const choices = await createComponentChoices(categories, components)\n\n if (choices.length === 0) {\n return []\n }\n\n try {\n logger.log(\"\")\n logger.log(\n colors.cyan(\n \" Press Space to select • A to toggle all • Enter to confirm\"\n )\n )\n\n const selectedComponents = await checkbox({\n message: \"Choose UI components to install:\",\n pageSize: 20,\n choices,\n theme: PROMPT_THEME,\n validate: (items) => {\n if (items.length === 0) {\n return \"Select at least one component (use Space to select, then Enter to confirm)\"\n }\n return true\n },\n })\n\n // Display selected components\n if (selectedComponents && selectedComponents.length > 0) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Selected components:\"))\n selectedComponents.forEach((component) => {\n logger.log(` ${colors.cyan(\"•\")} ${toReadableName(component)}`)\n })\n }\n\n logger.log(\"\")\n return selectedComponents || []\n } catch (error) {\n clearPromptLines(25)\n console.log(UI.operationCancelled)\n return []\n }\n}\n\n/**\n * Shows menu for selecting templates\n */\nasync function templateMenu(\n templates: RegistryItemIndexSchema\n): Promise<string[]> {\n try {\n const choices = templates.map((template) => {\n return {\n name: formatTemplateChoiceName(template),\n value: template.name,\n }\n })\n\n logger.log(\"\")\n\n const selectedTemplate = await select({\n message: \"Choose an editor template to install:\",\n pageSize: 20,\n choices,\n theme: PROMPT_THEME,\n })\n\n // Display selected template\n if (selectedTemplate) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Selected template:\"))\n logger.log(` ${colors.cyan(\"•\")} ${toReadableName(selectedTemplate)}`)\n }\n\n logger.log(\"\")\n return selectedTemplate ? [selectedTemplate] : []\n } catch (error) {\n clearPromptLines(25)\n console.log(UI.operationCancelled)\n return []\n }\n}\n\n/**\n * Main function to prompt for registry components\n */\nexport async function promptForRegistryComponents(\n options: AddOptions,\n showDivider = true\n): Promise<string[]> {\n if (options.components?.length) {\n return options.components\n }\n\n let registryIndex\n try {\n registryIndex = await getRegistryIndex()\n } catch (error) {\n // Check if this is a 401 authentication error\n if (\n error instanceof Error &&\n error.message.includes(\"You are not authorized\")\n ) {\n // Assume the component is paid and trigger authentication flow\n const isAuthenticated = await ensureAuthForPaidComponents(\n [{ name: \"unknown\", plans: [\"start\" as Plan] }], // Assume paid component\n options.cwd\n )\n\n if (!isAuthenticated) {\n logger.error(\n \"Authentication failed. Cannot proceed with component selection.\"\n )\n return []\n }\n\n // Retry registry fetch after authentication\n try {\n registryIndex = await getRegistryIndex()\n } catch (retryError) {\n logger.break()\n handleError(\n new Error(\n \"[prompts] - Failed to fetch registry index after authentication.\"\n )\n )\n return []\n }\n } else {\n logger.break()\n handleError(error)\n return []\n }\n }\n\n if (!registryIndex) {\n logger.break()\n handleError(new Error(\"[prompts] - Failed to fetch registry index.\"))\n return []\n }\n\n const categories = categorizeRegistryItems(registryIndex)\n const selection = await promptForInitialSelection(categories, showDivider)\n\n if (!selection) {\n return []\n }\n\n const allComponents = registryIndex\n .filter((item) => {\n const hide = item.hide ?? false\n return !hide\n })\n .map((item) => item.name)\n\n switch (selection) {\n case \"components\":\n return (await componentMenu(categories, allComponents)) || []\n case \"templates\": {\n const filteredTemplates = filterFreeTemplates(\n categories.templates,\n allComponents\n )\n const templateResults = await templateMenu(filteredTemplates)\n return templateResults || []\n }\n default:\n return []\n }\n}\n\nexport const add = new Command()\n .name(\"add\")\n .description(\n \"add Tiptap UI components or templates as source code to your project\"\n )\n .argument(\"[components...]\", \"the components to add\")\n .option(\"-o, --overwrite\", \"overwrite existing files.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .option(\"-p, --path <path>\", \"the path to add the component to.\")\n .option(\"-s, --silent\", \"mute output.\", false)\n .action(async (components, opts) => {\n try {\n // Clear terminal for a fresh start\n clearTerminal()\n\n // Show welcome banner\n const welcomeBanner = createWelcomeBanner(\n \"Tiptap UI Components\",\n \"Install UI components or templates as editable source code in your project\"\n )\n logLines(welcomeBanner)\n\n // Explain what Tiptap CLI does\n const explanation = createExplanationSection(\n \"What are Tiptap UI Components?\",\n [\n \"React UI components that help you develop an editor\",\n \"They install as source code (not npm packages) in your src/components/\",\n \"UI components are a foundation for customization rather than a fixed library\",\n ]\n )\n logLines(explanation)\n\n // Wait for user to press Enter\n await input({\n message: colors.reset(\n `Press ${colors.cyan(\"Enter\")} to add components or templates...`\n ),\n theme: {\n prefix: {\n done: \"\",\n idle: \"\",\n },\n },\n })\n\n // Add visual separation\n logger.log(\"\")\n logger.log(\"\")\n logger.log(\"\")\n\n const options = addOptionsSchema.parse({\n components,\n cwd: path.resolve(opts.cwd),\n ...opts,\n })\n\n if (!options.components?.length) {\n options.components = await promptForRegistryComponents(options)\n }\n\n // No components selected\n if (!options.components?.length) {\n return\n }\n\n const registryIndex = await getRegistryIndex()\n if (!registryIndex) {\n throw new Error(\"Failed to fetch registry index.\")\n }\n\n // Get details of selected components\n const selectedComponentDetails = options.components.map(\n (componentName) => {\n const componentInfo = registryIndex.find(\n (item) => item.name === componentName\n )\n return {\n name: componentName,\n plans: componentInfo?.plans || [],\n }\n }\n )\n\n const isAuthenticated = await ensureAuthForPaidComponents(\n selectedComponentDetails,\n options.cwd\n )\n if (!isAuthenticated) {\n logger.error(\n \"Authentication failed. Cannot proceed with paid component download.\"\n )\n logger.log(\n \"You can try again with only free components, or authenticate first.\"\n )\n process.exit(1)\n }\n\n const { errors, config } = await preFlightAdd(options)\n\n if (errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {\n logger.warn(`\\n${UI.missingDirectory}`)\n process.exit(0)\n }\n\n if (!config) {\n throw new Error(`Failed to read config at ${colors.cyan(options.cwd)}.`)\n }\n\n const created = await addComponents(options.components, config, options)\n\n if (!created) {\n throw new Error(\"Component addition failed.\")\n }\n\n // Check if any files were processed (created, updated, or skipped)\n const totalFilesProcessed =\n (created.filesCreated?.length || 0) +\n (created.filesUpdated?.length || 0) +\n (created.filesSkipped?.length || 0)\n\n // Show success message if components were processed\n if (created && totalFilesProcessed > 0) {\n // Check all file arrays for template detection\n const allFiles = [\n ...(created.filesCreated || []),\n ...(created.filesUpdated || []),\n ...(created.filesSkipped || []),\n ]\n\n const containsNotion = allFiles.some((path) => path.includes(\"notion\"))\n const containsSimpleEditor = allFiles.some(\n (path) => path.includes(\"simple\") && path.includes(\"editor\")\n )\n\n if (containsNotion) {\n // Show single-line success message\n logger.log(\"\")\n if (created.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Notion template installed - ${created.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else {\n logger.log(\n `${colors.green(\"✔\")} Notion template already installed - ${created.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Auto-import styles and show env setup for Notion template\n const projectInfo = await getProjectInfo(options.cwd)\n if (projectInfo) {\n const autoImportResult = await autoImportStyles(\n created,\n config,\n projectInfo.framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showNotionTemplateSetupMessage(projectInfo.framework, config)\n } else {\n // Show only env setup since styles were auto-imported\n showNotionEnvSetupMessage(projectInfo.framework)\n }\n }\n } else if (containsSimpleEditor) {\n // Show single-line success message\n logger.log(\"\")\n if (created.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Simple editor template installed - ${created.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else {\n logger.log(\n `${colors.green(\"✔\")} Simple editor template already installed - ${created.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Auto-import styles\n const projectInfo = await getProjectInfo(options.cwd)\n if (projectInfo) {\n const autoImportResult = await autoImportStyles(\n created,\n config,\n projectInfo.framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showStylesConfigurationMessage(projectInfo.framework, config)\n }\n }\n } else {\n // Show single-line success message\n logger.log(\"\")\n if (created.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Components installed - ${created.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else if (created.filesSkipped.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Components already installed - ${created.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Auto-import styles if components were added\n const projectInfo = await getProjectInfo(options.cwd)\n if (projectInfo) {\n const autoImportResult = await autoImportStyles(\n created,\n config,\n projectInfo.framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showStylesConfigurationMessage(projectInfo.framework, config)\n }\n }\n\n // Show Table Node integration guide if table-node was installed\n const containsTableNode = options.components.includes(\"table-node\")\n if (containsTableNode) {\n showTableNodeSetupMessage()\n }\n }\n }\n } catch (error) {\n logger.break()\n handleError(error)\n }\n })\n","import {\n createPrompt,\n useState,\n useKeypress,\n usePrefix,\n usePagination,\n useRef,\n useMemo,\n useEffect,\n isBackspaceKey,\n isEnterKey,\n isUpKey,\n isDownKey,\n isNumberKey,\n Separator,\n ValidationError,\n makeTheme,\n type Theme,\n type Status,\n} from \"@inquirer/core\"\nimport type { PartialDeep } from \"@inquirer/type\"\nimport colors from \"yoctocolors-cjs\"\nimport figures from \"@inquirer/figures\"\nimport ansiEscapes from \"ansi-escapes\"\n\ntype SelectTheme = {\n icon: { cursor: string }\n style: {\n disabled: (text: string) => string\n description: (text: string) => string\n }\n indexMode: \"hidden\" | \"number\"\n}\n\nconst selectTheme: SelectTheme = {\n icon: { cursor: figures.pointer },\n style: {\n disabled: (text: string) => colors.dim(`- ${text}`),\n description: (text: string) => colors.cyan(text),\n },\n indexMode: \"hidden\",\n}\n\ntype Choice<Value> = {\n value: Value\n name?: string\n description?: string\n short?: string\n disabled?: boolean | string\n type?: never\n}\n\ntype NormalizedChoice<Value> = {\n value: Value\n name: string\n description?: string\n short: string\n disabled: boolean | string\n}\n\ntype SelectConfig<\n Value,\n ChoicesObject =\n | ReadonlyArray<string | Separator>\n | ReadonlyArray<Choice<Value> | Separator>,\n> = {\n message: string\n choices: ChoicesObject extends ReadonlyArray<string | Separator>\n ? ChoicesObject\n : ReadonlyArray<Choice<Value> | Separator>\n pageSize?: number\n loop?: boolean\n default?: unknown\n instructions?: string | boolean\n theme?: PartialDeep<Theme<SelectTheme>>\n}\n\nfunction isSelectable<Value>(\n item: NormalizedChoice<Value> | Separator\n): item is NormalizedChoice<Value> {\n return !Separator.isSeparator(item) && !item.disabled\n}\n\nfunction normalizeChoices<Value>(\n choices:\n ReadonlyArray<string | Separator> | ReadonlyArray<Choice<Value> | Separator>\n): Array<NormalizedChoice<Value> | Separator> {\n return choices.map((choice) => {\n if (Separator.isSeparator(choice)) return choice\n\n if (typeof choice === \"string\") {\n return {\n value: choice as Value,\n name: choice,\n short: choice,\n disabled: false,\n }\n }\n\n const name = choice.name ?? String(choice.value)\n const normalizedChoice: NormalizedChoice<Value> = {\n value: choice.value,\n name,\n short: choice.short ?? name,\n disabled: choice.disabled ?? false,\n }\n\n if (choice.description) {\n normalizedChoice.description = choice.description\n }\n\n return normalizedChoice\n })\n}\n\nfunction formatMultilineChoice(text: string, firstLinePrefix: string): string {\n const [firstLine = \"\", ...remainingLines] = text.split(\"\\n\")\n const continuationPrefix = \" \".repeat(stripAnsi(firstLinePrefix).length)\n\n return [\n `${firstLinePrefix}${firstLine}`,\n ...remainingLines.map((line) => `${continuationPrefix}${line}`),\n ].join(\"\\n\")\n}\n\nfunction stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\")\n}\n\nexport default createPrompt(\n <Value>(config: SelectConfig<Value>, done: (value: Value) => void) => {\n const { loop = true, pageSize = 7, instructions } = config\n const firstRender = useRef(true)\n const theme = makeTheme<SelectTheme>(selectTheme, config.theme)\n const [status, setStatus] = useState<Status>(\"idle\")\n const prefix = usePrefix({ status, theme })\n const searchTimeoutRef = useRef<ReturnType<typeof setTimeout>>()\n const [showHelpTip, setShowHelpTip] = useState(true)\n\n const items = useMemo(\n () => normalizeChoices(config.choices),\n [config.choices]\n )\n\n const bounds = useMemo(() => {\n const first = items.findIndex(isSelectable)\n const last = items.findLastIndex(isSelectable)\n\n if (first === -1) {\n throw new ValidationError(\n \"[select prompt] No selectable choices. All choices are disabled.\"\n )\n }\n\n return { first, last }\n }, [items])\n\n const defaultItemIndex = useMemo(() => {\n if (!(\"default\" in config)) return -1\n return items.findIndex(\n (item) => isSelectable(item) && item.value === config.default\n )\n }, [config.default, items])\n\n const [active, setActive] = useState(\n defaultItemIndex === -1 ? bounds.first : defaultItemIndex\n )\n\n // Safe to assume the cursor position always point to a Choice.\n const selectedChoice = items[active] as NormalizedChoice<Value>\n\n useKeypress((key, rl) => {\n clearTimeout(searchTimeoutRef.current)\n setShowHelpTip(false)\n\n if (isEnterKey(key)) {\n setStatus(\"done\")\n done(selectedChoice.value)\n } else if (isUpKey(key) || isDownKey(key)) {\n rl.clearLine(0)\n if (\n loop ||\n (isUpKey(key) && active !== bounds.first) ||\n (isDownKey(key) && active !== bounds.last)\n ) {\n const offset = isUpKey(key) ? -1 : 1\n let next = active\n do {\n next = (next + offset + items.length) % items.length\n } while (!isSelectable(items[next]!))\n setActive(next)\n }\n } else if (isNumberKey(key) && !Number.isNaN(Number(rl.line))) {\n const position = Number(rl.line) - 1\n const item = items[position]\n if (item != null && isSelectable(item)) {\n setActive(position)\n }\n\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0)\n }, 700)\n } else if (isBackspaceKey(key)) {\n rl.clearLine(0)\n } else {\n // Default to search\n const searchTerm = rl.line.toLowerCase()\n const matchIndex = items.findIndex((item) => {\n if (Separator.isSeparator(item) || !isSelectable(item)) return false\n\n return item.name.toLowerCase().startsWith(searchTerm)\n })\n\n if (matchIndex !== -1) {\n setActive(matchIndex)\n }\n\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0)\n }, 700)\n }\n })\n\n useEffect(\n () => () => {\n clearTimeout(searchTimeoutRef.current)\n },\n []\n )\n\n const message = theme.style.message(config.message, status)\n\n let helpTipTop = \"\"\n let helpTipBottom = \"\"\n // Help text is now always hidden\n if (typeof instructions === \"string\") {\n helpTipTop = instructions\n }\n\n const page = usePagination({\n items,\n active,\n renderItem({ item, isActive, index }) {\n if (Separator.isSeparator(item)) {\n return ` ${item.separator}`\n }\n\n const indexLabel = theme.indexMode === \"number\" ? `${index + 1}. ` : \"\"\n if (item.disabled) {\n const disabledLabel =\n typeof item.disabled === \"string\" ? item.disabled : \"(disabled)\"\n return theme.style.disabled(\n `${indexLabel}${item.name} ${disabledLabel}`\n )\n }\n\n const color = isActive ? theme.style.highlight : (x: string) => x\n const cursor = isActive ? theme.icon.cursor : ` `\n return color(\n formatMultilineChoice(item.name, `${cursor} ${indexLabel}`)\n )\n },\n pageSize,\n loop,\n })\n\n if (status === \"done\") {\n return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`\n }\n\n const choiceDescription = selectedChoice.description\n ? `\\n${theme.style.description(selectedChoice.description)}`\n : ``\n\n return `${[prefix, message, helpTipTop].filter(Boolean).join(\" \")}\\n${page}${helpTipBottom}${choiceDescription}${ansiEscapes.cursorHide}`\n }\n)\n\nexport { Separator } from \"@inquirer/core\"\n","import path from \"path\"\nimport { addOptionsSchema } from \"@/src/commands/add\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { getConfig } from \"@/src/utils/get-config\"\nimport { logger } from \"@/src/utils/logger\"\nimport fs from \"fs-extra\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport async function preFlightAdd(options: z.infer<typeof addOptionsSchema>) {\n const errors: Record<string, boolean> = {}\n\n if (\n !fs.existsSync(options.cwd) ||\n !fs.existsSync(path.resolve(options.cwd, \"package.json\"))\n ) {\n errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true\n return {\n errors,\n config: null,\n }\n }\n\n try {\n const config = await getConfig(options.cwd, options.path)\n\n return {\n errors,\n config: config!,\n }\n } catch (error) {\n console.log(\"[preFlightAdd] - \", error)\n\n logger.break()\n logger.error(\n `Make sure you are in a valid project directory. Run ${colors.cyan(\n \"npx @tiptap/cli init\"\n )} to create a new project.`\n )\n logger.break()\n process.exit(1)\n }\n}\n","import path from \"path\"\nimport { resolveImport } from \"@/src/utils/resolve-import\"\nimport { cosmiconfig } from \"cosmiconfig\"\nimport fg from \"fast-glob\"\nimport { loadConfig } from \"tsconfig-paths\"\nimport { z } from \"zod\"\nimport { getProjectInfo } from \"./get-project-info\"\n\nexport const DEFAULT_COMPONENTS = \"@/components\"\nexport const DEFAULT_CONTEXTS = \"@/contexts\"\nexport const DEFAULT_HOOKS = \"@/hooks\"\nexport const DEFAULT_TIPTAP_ICONS = \"@/components/tiptap-icons\"\nexport const DEFAULT_LIB = \"@/lib\"\nexport const DEFAULT_TIPTAP_EXTENSIONS = \"@/components/tiptap-extension\"\nexport const DEFAULT_TIPTAP_NODES = \"@/components/tiptap-node\"\nexport const DEFAULT_TIPTAP_UI = \"@/components/tiptap-ui\"\nexport const DEFAULT_TIPTAP_UI_PRIMITIVES = \"@/components/tiptap-ui-primitive\"\nexport const DEFAULT_TIPTAP_UI_UTILS = \"@/components/tiptap-ui-utils\"\nexport const DEFAULT_STYLES = \"@/styles\"\n\nconst explorer = cosmiconfig(\"components\", {\n searchPlaces: [\"components.json\"],\n})\n\nexport const rawConfigSchema = z.object({\n rsc: z.coerce.boolean().default(false),\n tsx: z.coerce.boolean().default(true),\n aliases: z.object({\n components: z.string(),\n contexts: z.string().optional(),\n hooks: z.string().optional(),\n tiptapIcons: z.string().optional(),\n lib: z.string().optional(),\n tiptapExtensions: z.string().optional(),\n tiptapNodes: z.string().optional(),\n tiptapUi: z.string().optional(),\n tiptapUiPrimitives: z.string().optional(),\n tiptapUiUtils: z.string().optional(),\n styles: z.string().optional(),\n }),\n})\n\nexport const configSchema = rawConfigSchema.extend({\n resolvedPaths: z.object({\n cwd: z.string(),\n components: z.string(),\n contexts: z.string(),\n hooks: z.string(),\n tiptapIcons: z.string(),\n lib: z.string(),\n tiptapExtensions: z.string(),\n tiptapNodes: z.string(),\n tiptapUi: z.string(),\n tiptapUiPrimitives: z.string(),\n tiptapUiUtils: z.string(),\n styles: z.string(),\n }),\n})\n\nexport const workspaceConfigSchema = z.record(z.string(), configSchema)\n\nexport type RawConfig = z.infer<typeof rawConfigSchema>\n\nexport type Config = z.infer<typeof configSchema>\n\nexport async function getConfig(cwd: string, pathOverride?: string) {\n const res = await explorer.search(cwd)\n const projectInfo = await getProjectInfo(cwd)\n\n const defaultAliases = {\n components: DEFAULT_COMPONENTS,\n contexts: DEFAULT_CONTEXTS,\n hooks: DEFAULT_HOOKS,\n tiptapIcons: DEFAULT_TIPTAP_ICONS,\n lib: DEFAULT_LIB,\n tiptapExtensions: DEFAULT_TIPTAP_EXTENSIONS,\n tiptapNodes: DEFAULT_TIPTAP_NODES,\n tiptapUi: DEFAULT_TIPTAP_UI,\n tiptapUiPrimitives: DEFAULT_TIPTAP_UI_PRIMITIVES,\n tiptapUiUtils: DEFAULT_TIPTAP_UI_UTILS,\n styles: DEFAULT_STYLES,\n }\n\n const applyAliasPrefix = (aliases: typeof defaultAliases, prefix: string) => {\n return Object.fromEntries(\n Object.entries(aliases).map(([key, value]) => [\n key,\n value.replace(/^@/, prefix),\n ])\n ) as typeof defaultAliases\n }\n\n let config: RawConfig\n\n if (!res) {\n let aliases = defaultAliases\n\n if (projectInfo?.aliasPrefix) {\n aliases = applyAliasPrefix(aliases, projectInfo.aliasPrefix)\n }\n\n config = rawConfigSchema.parse({\n rsc: projectInfo?.isRSC ?? false,\n tsx: projectInfo?.isTsx ?? true,\n aliases,\n })\n } else {\n const resolvedAliases = {\n ...defaultAliases,\n ...res.config.aliases,\n }\n\n if (projectInfo?.aliasPrefix) {\n config = rawConfigSchema.parse({\n ...res.config,\n aliases: applyAliasPrefix(resolvedAliases, projectInfo.aliasPrefix),\n })\n } else {\n config = rawConfigSchema.parse({\n ...res.config,\n aliases: resolvedAliases,\n })\n }\n }\n\n return await resolveConfigPaths(cwd, config, pathOverride)\n}\n\nexport async function resolveConfigPaths(\n cwd: string,\n config: RawConfig,\n pathOverride?: string\n) {\n // Read tsconfig.json.\n const tsConfig = await loadConfig(cwd)\n\n if (tsConfig.resultType === \"failed\") {\n throw new Error(\n `Failed to load ${config.tsx ? \"tsconfig\" : \"jsconfig\"}.json. ${\n tsConfig.message ?? \"\"\n }`.trim()\n )\n }\n\n if (pathOverride) {\n const resolvedPathOverride = path.isAbsolute(pathOverride)\n ? pathOverride\n : path.resolve(cwd, pathOverride)\n\n const schema = configSchema.parse({\n ...config,\n resolvedPaths: {\n cwd,\n components: resolvedPathOverride,\n contexts: path.resolve(resolvedPathOverride, \"..\", \"contexts\"),\n hooks: path.resolve(resolvedPathOverride, \"..\", \"hooks\"),\n tiptapIcons: path.resolve(resolvedPathOverride, \"tiptap-icons\"),\n lib: path.resolve(resolvedPathOverride, \"..\", \"lib\"),\n tiptapExtensions: path.resolve(\n resolvedPathOverride,\n \"tiptap-extension\"\n ),\n tiptapNodes: path.resolve(resolvedPathOverride, \"tiptap-node\"),\n tiptapUi: path.resolve(resolvedPathOverride, \"tiptap-ui\"),\n tiptapUiPrimitives: path.resolve(\n resolvedPathOverride,\n \"tiptap-ui-primitive\"\n ),\n tiptapUiUtils: path.resolve(resolvedPathOverride, \"tiptap-ui-utils\"),\n styles: path.resolve(resolvedPathOverride, \"..\", \"styles\"),\n },\n })\n\n return schema\n }\n\n const schema = configSchema.parse({\n ...config,\n resolvedPaths: {\n cwd,\n components: await resolveImport(config.aliases.components, tsConfig),\n contexts: config.aliases.contexts\n ? await resolveImport(config.aliases.contexts, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"..\",\n \"contexts\"\n ),\n hooks: config.aliases.hooks\n ? await resolveImport(config.aliases.hooks, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"..\",\n \"hooks\"\n ),\n tiptapIcons: config.aliases.tiptapIcons\n ? await resolveImport(config.aliases.tiptapIcons, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-icons\"\n ),\n lib: config.aliases.lib\n ? await resolveImport(config.aliases.lib, tsConfig)\n : path.resolve(\n (await resolveImport(DEFAULT_LIB, tsConfig)) ?? cwd,\n \"..\"\n ),\n tiptapExtensions: config.aliases.tiptapExtensions\n ? await resolveImport(config.aliases.tiptapExtensions, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-extension\"\n ),\n tiptapNodes: config.aliases.tiptapNodes\n ? await resolveImport(config.aliases.tiptapNodes, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-node\"\n ),\n tiptapUi: config.aliases.tiptapUi\n ? await resolveImport(config.aliases.tiptapUi, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui\"\n ),\n tiptapUiPrimitives: config.aliases.tiptapUiPrimitives\n ? await resolveImport(config.aliases.tiptapUiPrimitives, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui-primitive\"\n ),\n tiptapUiUtils: config.aliases.tiptapUiUtils\n ? await resolveImport(config.aliases.tiptapUiUtils, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui-utils\"\n ),\n styles: config.aliases.styles\n ? await resolveImport(config.aliases.styles, tsConfig)\n : path.resolve(cwd, \"styles\"),\n },\n })\n\n return schema\n}\n\n// Note: we can check for -workspace.yaml or \"workspace\" in package.json.\n// Since cwd is not necessarily the root of the project.\n// We'll instead check if ui aliases resolve to a different root.\nexport async function getWorkspaceConfig(config: Config) {\n const resolvedAliases: Record<string, Config> = {}\n\n for (const key of Object.keys(config.aliases)) {\n if (!isAliasKey(key, config)) {\n continue\n }\n\n const resolvedPath = config.resolvedPaths[key]\n const packageRoot = await findPackageRoot(\n config.resolvedPaths.cwd,\n resolvedPath\n )\n\n if (!packageRoot) {\n resolvedAliases[key] = config\n continue\n }\n\n resolvedAliases[key] = await getConfig(packageRoot)\n }\n\n const result = workspaceConfigSchema.safeParse(resolvedAliases)\n if (!result.success) {\n return null\n }\n\n return result.data\n}\n\nexport async function findPackageRoot(cwd: string, resolvedPath: string) {\n const commonRoot = findCommonRoot(cwd, resolvedPath)\n const relativePath = path.relative(commonRoot, resolvedPath)\n\n const packageRoots = await fg.glob(\"**/package.json\", {\n cwd: commonRoot,\n deep: 3,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/public/**\"],\n })\n\n const matchingPackageRoot = packageRoots\n .map((pkgPath) => path.dirname(pkgPath))\n .find((pkgDir) => relativePath.startsWith(pkgDir))\n\n return matchingPackageRoot ? path.join(commonRoot, matchingPackageRoot) : null\n}\n\nfunction isAliasKey(\n key: string,\n config: Config\n): key is keyof Config[\"aliases\"] {\n return Object.keys(config.resolvedPaths).includes(key)\n}\n\nexport function findCommonRoot(cwd: string, resolvedPath: string) {\n const parts1 = cwd.split(path.sep)\n const parts2 = resolvedPath.split(path.sep)\n const commonParts = []\n\n for (let i = 0; i < Math.min(parts1.length, parts2.length); i++) {\n if (parts1[i] !== parts2[i]) {\n break\n }\n commonParts.push(parts1[i])\n }\n\n return commonParts.join(path.sep)\n}\n","import { createMatchPath, type ConfigLoaderSuccessResult } from \"tsconfig-paths\"\n\nexport async function resolveImport(\n importPath: string,\n config: Pick<ConfigLoaderSuccessResult, \"absoluteBaseUrl\" | \"paths\">\n) {\n return createMatchPath(config.absoluteBaseUrl, config.paths)(\n importPath,\n undefined,\n () => true,\n [\".ts\", \".tsx\"]\n )\n}\n","import path from \"path\"\nimport { FRAMEWORKS, Framework } from \"@/src/utils/frameworks\"\nimport { getPackageInfo } from \"@/src/utils/get-package-info\"\nimport fg from \"fast-glob\"\nimport fs from \"fs-extra\"\nimport { loadConfig } from \"tsconfig-paths\"\nimport {\n Config,\n RawConfig,\n getConfig,\n resolveConfigPaths,\n} from \"@/src/utils/get-config\"\n\nexport type ProjectInfo = {\n framework: Framework\n isSrcDir: boolean\n isRSC: boolean\n isTsx: boolean\n aliasPrefix: string | null\n}\n\nconst PROJECT_SHARED_IGNORE = [\n \"**/node_modules/**\",\n \".next\",\n \"public\",\n \"dist\",\n \"build\",\n]\n\nexport async function getProjectInfo(cwd: string): Promise<ProjectInfo | null> {\n const [configFiles, isSrcDir, isTsx, aliasPrefix, packageJson] =\n await Promise.all([\n fg.glob(\n \"**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*\",\n {\n cwd,\n deep: 3,\n ignore: PROJECT_SHARED_IGNORE,\n }\n ),\n fs.pathExists(path.resolve(cwd, \"src\")),\n isTypeScriptProject(cwd),\n getTsConfigAliasPrefix(cwd),\n getPackageInfo(cwd, false),\n ])\n\n const isUsingAppDir = await fs.pathExists(\n path.resolve(cwd, `${isSrcDir ? \"src/\" : \"\"}app`)\n )\n\n const type: ProjectInfo = {\n framework: FRAMEWORKS[\"manual\"],\n isSrcDir,\n isRSC: false,\n isTsx,\n aliasPrefix,\n }\n\n // Next.js.\n if (configFiles.find((file) => file.startsWith(\"next.config.\"))?.length) {\n type.framework = isUsingAppDir\n ? FRAMEWORKS[\"next-app\"]\n : FRAMEWORKS[\"next-pages\"]\n type.isRSC = isUsingAppDir\n return type\n }\n\n // Astro.\n if (configFiles.find((file) => file.startsWith(\"astro.config.\"))?.length) {\n type.framework = FRAMEWORKS[\"astro\"]\n return type\n }\n\n // Gatsby.\n // if (configFiles.find((file) => file.startsWith(\"gatsby-config.\"))?.length) {\n // type.framework = FRAMEWORKS[\"gatsby\"]\n // return type\n // }\n\n // Laravel.\n if (configFiles.find((file) => file.startsWith(\"composer.json\"))?.length) {\n type.framework = FRAMEWORKS[\"laravel\"]\n return type\n }\n\n // Remix.\n // if (\n // Object.keys(packageJson?.dependencies ?? {}).find((dep) =>\n // dep.startsWith(\"@remix-run/\")\n // )\n // ) {\n // type.framework = FRAMEWORKS[\"remix\"]\n // return type\n // }\n\n // TanStack Start.\n if (\n configFiles.find((file) => file.startsWith(\"app.config.\"))?.length &&\n [\n ...Object.keys(packageJson?.dependencies ?? {}),\n ...Object.keys(packageJson?.devDependencies ?? {}),\n ].find((dep) => dep.startsWith(\"@tanstack/start\"))\n ) {\n type.framework = FRAMEWORKS[\"tanstack-start\"]\n return type\n }\n\n // React Router.\n if (\n configFiles.find((file) => file.startsWith(\"react-router.config.\"))?.length\n ) {\n type.framework = FRAMEWORKS[\"react-router\"]\n return type\n }\n\n // Vite.\n // Some Remix templates also have a vite.config.* file.\n // We'll assume that it got caught by the Remix check above.\n if (configFiles.find((file) => file.startsWith(\"vite.config.\"))?.length) {\n type.framework = FRAMEWORKS[\"vite\"]\n return type\n }\n\n return type\n}\n\nexport async function getTsConfigAliasPrefix(cwd: string) {\n const tsConfig = await loadConfig(cwd)\n\n if (\n tsConfig?.resultType === \"failed\" ||\n !Object.entries(tsConfig?.paths).length\n ) {\n return null\n }\n\n // This assume that the first alias is the prefix.\n for (const [alias, paths] of Object.entries(tsConfig.paths)) {\n if (\n paths.includes(\"./*\") ||\n paths.includes(\"./src/*\") ||\n paths.includes(\"./app/*\") ||\n paths.includes(\"./resources/js/*\") // Laravel.\n ) {\n return alias.replace(/\\/\\*$/, \"\") ?? null\n }\n }\n\n // Use the first alias as the prefix.\n return Object.keys(tsConfig?.paths)?.[0].replace(/\\/\\*$/, \"\") ?? null\n}\n\nexport async function isTypeScriptProject(cwd: string) {\n const files = await fg.glob(\"tsconfig.*\", {\n cwd,\n deep: 1,\n ignore: PROJECT_SHARED_IGNORE,\n })\n\n return files.length > 0\n}\n\nexport async function getProjectConfig(\n cwd: string,\n defaultProjectInfo: ProjectInfo | null = null\n): Promise<Config | null> {\n const [existingConfig, projectInfo] = await Promise.all([\n getConfig(cwd),\n !defaultProjectInfo\n ? getProjectInfo(cwd)\n : Promise.resolve(defaultProjectInfo),\n ])\n\n if (existingConfig) {\n return existingConfig\n }\n\n if (!projectInfo) {\n return null\n }\n\n const config: RawConfig = {\n rsc: projectInfo.isRSC,\n tsx: projectInfo.isTsx,\n aliases: {\n components: `${projectInfo.aliasPrefix}/components`,\n contexts: `${projectInfo.aliasPrefix}/contexts`,\n hooks: `${projectInfo.aliasPrefix}/hooks`,\n tiptapIcons: `${projectInfo.aliasPrefix}/components/tiptap-icons`,\n lib: `${projectInfo.aliasPrefix}/lib`,\n tiptapExtensions: `${projectInfo.aliasPrefix}/components/tiptap-extensions`,\n tiptapNodes: `${projectInfo.aliasPrefix}/components/tiptap-nodes`,\n tiptapUi: `${projectInfo.aliasPrefix}/components/tiptap-ui`,\n tiptapUiPrimitives: `${projectInfo.aliasPrefix}/components/tiptap-ui-primitives`,\n tiptapUiUtils: `${projectInfo.aliasPrefix}/components/tiptap-ui-utils`,\n styles: `${projectInfo.aliasPrefix}/styles`,\n },\n }\n\n return await resolveConfigPaths(cwd, config)\n}\n","export const FRAMEWORKS = {\n \"next-app\": {\n name: \"next-app\",\n label: \"Next.js\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n \"next-pages\": {\n name: \"next-pages\",\n label: \"Next.js\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n // remix: {\n // name: \"remix\",\n // label: \"Remix\",\n // links: {\n // installation: \"https://tiptap.dev/docs/ui-components/install/remix\",\n // },\n // },\n \"react-router\": {\n name: \"react-router\",\n label: \"React Router\",\n links: {\n installation:\n \"https://tiptap.dev/docs/ui-components/install/react-router\",\n },\n },\n vite: {\n name: \"vite\",\n label: \"Vite\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/vite\",\n },\n },\n astro: {\n name: \"astro\",\n label: \"Astro\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/astro\",\n },\n },\n laravel: {\n name: \"laravel\",\n label: \"Laravel\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/laravel\",\n },\n },\n \"tanstack-start\": {\n name: \"tanstack-start\",\n label: \"TanStack Start\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/tanstack\",\n },\n },\n // gatsby: {\n // name: \"gatsby\",\n // label: \"Gatsby\",\n // links: {\n // installation: \"https://tiptap.dev/docs/ui-components/install/gatsby\",\n // },\n // },\n manual: {\n name: \"manual\",\n label: \"Manual\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n} as const\n\nexport type Framework = (typeof FRAMEWORKS)[keyof typeof FRAMEWORKS]\n","import path from \"path\"\nimport fs from \"fs-extra\"\nimport { type PackageJson } from \"type-fest\"\n\nexport function getPackageInfo(\n cwd: string = \"\",\n shouldThrow: boolean = true\n): PackageJson | null {\n const packageJsonPath = path.join(cwd, \"package.json\")\n\n return fs.readJSONSync(packageJsonPath, {\n throws: shouldThrow,\n }) as PackageJson\n}\n","import chalk from \"chalk\"\n\nexport const colors = {\n cyan: chalk.cyan,\n magenta: chalk.magenta,\n gray: chalk.gray,\n white: chalk.white,\n yellow: chalk.yellow,\n green: chalk.green,\n red: chalk.red,\n blue: chalk.blue,\n reset: chalk.reset,\n dim: chalk.dim,\n bold: chalk.bold,\n whiteBold: chalk.white.bold,\n}\n","import { colors } from \"@/src/utils/colors\"\n\nexport type Logger = {\n error: (...args: unknown[]) => void\n warn: (...args: unknown[]) => void\n info: (...args: unknown[]) => void\n success: (...args: unknown[]) => void\n log: (...args: unknown[]) => void\n break: () => void\n}\n\nconst join = (args: unknown[]) => args.map(String).join(\" \")\n\nexport const logger: Logger = {\n error(...args: unknown[]) {\n console.log(colors.red(join(args)))\n },\n warn(...args: unknown[]) {\n console.log(colors.yellow(join(args)))\n },\n info(...args: unknown[]) {\n console.log(colors.cyan(join(args)))\n },\n success(...args: unknown[]) {\n console.log(colors.green(join(args)))\n },\n log(...args: unknown[]) {\n console.log(join(args))\n },\n break() {\n console.log(\"\")\n },\n}\n","import path from \"path\"\nimport {\n configSchema,\n findCommonRoot,\n findPackageRoot,\n getWorkspaceConfig,\n workspaceConfigSchema,\n type Config,\n} from \"@/src/utils/get-config\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport {\n fetchRegistry,\n getRegistryParentMap,\n getRegistryTypeAliasMap,\n registryResolveItemsTree,\n resolveRegistryItems,\n} from \"@/src/utils/registry\"\nimport { registryItemSchema } from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { updateDependencies } from \"@/src/utils/updaters/update-dependencies\"\nimport { updateFiles } from \"@/src/utils/updaters/update-files\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\nimport { updateDevDependencies } from \"@/src/utils/updaters/update-dev-dependencies\"\n\nexport async function addComponents(\n components: string[],\n config: Config,\n options: {\n overwrite?: boolean\n silent?: boolean\n isNewProject?: boolean\n }\n) {\n options = {\n overwrite: false,\n silent: false,\n isNewProject: false,\n ...options,\n }\n\n const workspaceConfig = await getWorkspaceConfig(config)\n\n if (\n workspaceConfig &&\n workspaceConfig.tiptapUi &&\n workspaceConfig.tiptapUi.resolvedPaths.cwd !== config.resolvedPaths.cwd\n ) {\n return await addWorkspaceComponents(components, config, workspaceConfig, {\n ...options,\n })\n }\n\n return await addProjectComponents(components, config, options)\n}\n\nasync function addProjectComponents(\n components: string[],\n config: z.infer<typeof configSchema>,\n options: {\n overwrite?: boolean\n silent?: boolean\n isNewProject?: boolean\n }\n) {\n const registrySpinner = spinner(`Checking registry`, {\n silent: options.silent,\n }).start()\n const tree = await registryResolveItemsTree(components, config)\n if (!tree) {\n registrySpinner?.fail()\n return handleError(new Error(\"Failed to fetch components from registry\"))\n }\n\n registrySpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n\n await updateDependencies(tree.dependencies, config, {\n silent: options.silent,\n })\n\n await updateDevDependencies(tree.devDependencies, config, {\n silent: options.silent,\n })\n\n return await updateFiles(tree.files, config, {\n overwrite: options.overwrite,\n silent: options.silent,\n })\n}\n\nasync function addWorkspaceComponents(\n components: string[],\n config: z.infer<typeof configSchema>,\n workspaceConfig: z.infer<typeof workspaceConfigSchema>,\n options: {\n overwrite?: boolean\n silent?: boolean\n isNewProject?: boolean\n }\n) {\n const registrySpinner = spinner(`Checking registry`, {\n silent: options.silent,\n }).start()\n const registryItems = await resolveRegistryItems(components)\n const result = await fetchRegistry(registryItems)\n\n const payload = z.array(registryItemSchema).parse(result)\n if (!payload.length) {\n registrySpinner?.fail()\n return handleError(new Error(\"Failed to fetch components from registry\"))\n }\n registrySpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n\n const registryParentMap = getRegistryParentMap(payload)\n const registryTypeAliasMap = getRegistryTypeAliasMap()\n\n const filesCreated: string[] = []\n const filesUpdated: string[] = []\n const filesSkipped: string[] = []\n\n const rootSpinner = spinner(`Installing components`)?.start()\n\n for (const component of payload) {\n const alias = registryTypeAliasMap.get(component.type)\n const registryParent = registryParentMap.get(component.name)\n\n // We don't support this type of component.\n if (!alias) {\n continue\n }\n\n // A good start is ui for now.\n const targetConfig =\n component.type === \"registry:ui\" || registryParent?.type === \"registry:ui\"\n ? workspaceConfig.tiptapUi || config\n : config\n\n if (!targetConfig.resolvedPaths.tiptapUi) {\n continue\n }\n\n const workspaceRoot = findCommonRoot(\n config.resolvedPaths.cwd,\n targetConfig.resolvedPaths.tiptapUi\n )\n const packageRoot =\n (await findPackageRoot(workspaceRoot, targetConfig.resolvedPaths.cwd)) ??\n targetConfig.resolvedPaths.cwd\n\n // 3. Update dependencies.\n await updateDependencies(component.dependencies || [], targetConfig, {\n silent: true,\n })\n\n await updateDevDependencies(component.devDependencies || [], targetConfig, {\n silent: true,\n })\n\n // 4. Update files.\n const files = await updateFiles(component.files || [], targetConfig, {\n overwrite: options.overwrite,\n silent: true,\n rootSpinner,\n })\n\n if (files.errors && files.errors.length > 0) {\n spinner(`Encountered ${files.errors.length} errors:`, {\n silent: options.silent,\n })?.fail()\n\n for (const { file, error } of files.errors) {\n logger.error(` - ${file}: ${error}`)\n }\n }\n\n filesCreated.push(\n ...files.filesCreated.map((file) =>\n path.relative(workspaceRoot, path.join(packageRoot, file))\n )\n )\n filesUpdated.push(\n ...files.filesUpdated.map((file) =>\n path.relative(workspaceRoot, path.join(packageRoot, file))\n )\n )\n filesSkipped.push(\n ...files.filesSkipped.map((file) =>\n path.relative(workspaceRoot, path.join(packageRoot, file))\n )\n )\n }\n\n rootSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n\n // Sort files.\n filesCreated.sort()\n filesUpdated.sort()\n filesSkipped.sort()\n\n const hasUpdatedFiles = filesCreated.length || filesUpdated.length\n if (!hasUpdatedFiles && !filesSkipped.length) {\n spinner(`No files updated`, {\n silent: options.silent,\n })?.info()\n }\n\n if (filesCreated.length) {\n spinner(\n `Created ${filesCreated.length} ${\n filesCreated.length === 1 ? \"file\" : \"files\"\n }:`,\n {\n silent: options.silent,\n }\n )?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n for (const file of filesCreated) {\n logger.log(` - ${file}`)\n }\n }\n\n if (filesUpdated.length) {\n spinner(\n `Updated ${filesUpdated.length} ${\n filesUpdated.length === 1 ? \"file\" : \"files\"\n }:`,\n {\n silent: options.silent,\n }\n )?.info()\n for (const file of filesUpdated) {\n logger.log(` - ${file}`)\n }\n }\n\n if (filesSkipped.length) {\n spinner(\n `Skipped ${filesSkipped.length} ${\n filesSkipped.length === 1 ? \"file\" : \"files\"\n }: (use --overwrite to overwrite)`,\n {\n silent: options.silent,\n }\n )?.info()\n for (const file of filesSkipped) {\n logger.log(` - ${file}`)\n }\n }\n\n return {\n filesCreated,\n filesUpdated,\n filesSkipped,\n }\n}\n","import { logger } from \"@/src/utils/logger\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport function handleError(error: unknown) {\n logger.error(\n `Something went wrong. Please check the error below for more details.`\n )\n logger.error(`If the problem persists, please open an issue on GitHub.`)\n logger.error(\"\")\n if (typeof error === \"string\") {\n logger.error(error)\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof z.ZodError) {\n logger.error(\"Validation failed:\")\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${colors.cyan(key)}: ${value}`)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof Error) {\n logger.error(error.message)\n logger.break()\n process.exit(1)\n }\n\n logger.break()\n process.exit(1)\n}\n","import { z } from \"zod\"\n\nexport const registryItemTypeSchema = z.enum([\n \"registry:context\",\n \"registry:extension\",\n \"registry:hook\",\n \"registry:icon\",\n \"registry:lib\",\n \"registry:node\",\n \"registry:template\",\n \"registry:ui-primitive\",\n \"registry:ui\",\n \"registry:ui-utils\",\n \"registry:page\",\n \"registry:component\",\n \"registry:style\",\n \"registry:asset\",\n])\n\nexport type PaidPlan = \"start\" | \"team\" | \"growth\" | \"enterprise\" | \"business\"\nexport type FreePlan = \"open-source\" | \"light\"\nexport type Plan = PaidPlan | FreePlan\n\nexport const PAID_PLANS = [\n \"start\",\n \"team\",\n \"growth\",\n \"enterprise\",\n \"business\",\n] as const satisfies readonly PaidPlan[]\n\nexport const FREE_PLANS = [\n \"open-source\",\n \"light\",\n] as const satisfies readonly FreePlan[]\n\nconst ALL_PLANS = [...PAID_PLANS, ...FREE_PLANS] as const\n\nexport const planSchema = z.array(z.enum(ALL_PLANS)).default([])\n\nexport const registryItemFileSchema = z.object({\n path: z.string(),\n content: z.string().optional(),\n type: registryItemTypeSchema,\n target: z.string().optional(),\n})\n\nexport const registryItemSchema = z.object({\n name: z.string(),\n type: registryItemTypeSchema,\n description: z.string().optional(),\n dependencies: z.array(z.string()).optional(),\n devDependencies: z.array(z.string()).optional(),\n registryDependencies: z.array(z.string()).optional(),\n files: z.array(registryItemFileSchema).optional(),\n meta: z.record(z.string(), z.any()).optional(),\n plans: planSchema.optional(),\n hide: z.boolean().default(false).optional(),\n isNew: z.boolean().default(false).optional(),\n})\n\nexport const registrySchema = z.array(registryItemSchema)\n\nexport type Registry = z.infer<typeof registrySchema>\n\nexport const registryIndexSchema = z.array(\n registryItemSchema.extend({\n files: z.array(z.union([z.string(), registryItemFileSchema])).optional(),\n })\n)\n\nexport const registryResolvedItemsTreeSchema = registryItemSchema.pick({\n dependencies: true,\n devDependencies: true,\n files: true,\n})\n\nexport type RegistryItem = z.infer<typeof registryItemSchema>\nexport type RegistryItemIndexSchema = z.infer<typeof registryIndexSchema>\n","import { configSchema } from \"@/src/utils/get-config\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport {\n registryIndexSchema,\n RegistryItem,\n registryItemSchema,\n registryResolvedItemsTreeSchema,\n} from \"@/src/utils/registry/schema\"\nimport deepmerge from \"deepmerge\"\nimport { HttpsProxyAgent } from \"https-proxy-agent\"\nimport fetch, { Response } from \"node-fetch\"\nimport { z } from \"zod\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { colors } from \"@/src/utils/colors\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\nexport const REGISTRY_URL = \"https://template.tiptap.dev\"\n// export const REGISTRY_URL = \"https://template-preview.tiptap.dev\"\n// export const REGISTRY_URL = \"http://localhost:3000\"\n\nconst agent = process.env.https_proxy\n ? new HttpsProxyAgent(process.env.https_proxy)\n : undefined\n\nexport async function getRegistryIndex() {\n try {\n const [result] = await fetchRegistry([\"index.json\"])\n\n return registryIndexSchema.parse(result)\n } catch (error) {\n logger.error(\"\\n\")\n handleError(error)\n }\n}\n\nfunction createRegistryError(response: Response, url?: string): Error {\n const urlInfo = url ? ` at ${colors.cyan(url)}` : \"\"\n\n switch (response.status) {\n case 400:\n return new Error(\n `The registry rejected the request${urlInfo}.\\n` +\n `Please check the selected components and try again.`\n )\n\n case 401:\n tokenStorage.clearSession()\n return new Error(\n `You are not authorized to access the component${urlInfo}.\\n` +\n `Please run ${colors.cyan(\"@tiptap/cli login\")} to log in to your Tiptap Cloud account.`\n )\n\n case 404:\n return new Error(\n `The component${urlInfo} was not found.\\n` +\n `It may not exist at the registry. Please make sure it is a valid component.`\n )\n\n case 403:\n return new Error(\n `You do not have access to the component${urlInfo}.\\n` +\n `Your account may not have the required subscription plan for this component.\\n` +\n `Please upgrade your subscription or use a component available in your current plan.`\n )\n\n case 429:\n return new Error(\n `Too many registry requests${urlInfo}.\\n` +\n `Please wait a moment and try again.`\n )\n\n default:\n if (response.status >= 500) {\n return new Error(\n `The Tiptap registry is temporarily unavailable${urlInfo}.\\n` +\n `Please try again later.`\n )\n }\n\n return new Error(\n `The registry returned an unexpected response${urlInfo}.\\n` +\n `Please try again.`\n )\n }\n}\n\nasync function fetchComponent(path: string, headers: Record<string, string>) {\n const url = getRegistryUrl(path)\n\n const response = await fetch(url, {\n agent,\n headers,\n })\n\n if (!response.ok) {\n throw createRegistryError(response, url)\n }\n\n return response.json()\n}\n\nasync function fetchRegistryBatch(\n componentNames: string[],\n headers: Record<string, string>\n) {\n const response = await fetch(\n `${REGISTRY_URL}/api/registry/components/batch`,\n {\n method: \"POST\",\n agent,\n headers,\n body: JSON.stringify({ components: componentNames }),\n }\n )\n\n if (!response.ok) {\n throw createRegistryError(response)\n }\n\n const results = (await response.json()) as RegistryItem[]\n\n return results\n}\n\nexport async function fetchRegistry(paths: string[]) {\n try {\n const bearerToken = tokenStorage.getBearerToken()\n const headers: Record<string, string> = {\n \"Content-Type\": \"application/json\",\n }\n\n if (bearerToken) {\n headers[\"Authorization\"] = `Bearer ${bearerToken}`\n }\n\n const componentNames = paths.map((path) => {\n if (path.includes(\"/components/\")) {\n return path.replace(/.*\\/components\\//, \"\").replace(\".json\", \"\")\n }\n return path.replace(\".json\", \"\")\n })\n\n if (componentNames.length > 1) {\n return await fetchRegistryBatch(componentNames, headers)\n }\n\n return Promise.all(paths.map((path) => fetchComponent(path, headers)))\n } catch (error) {\n logger.error(\"\\n\")\n handleError(error)\n return []\n }\n}\n\nexport async function fetchRegistryDependencies(\n components: string[]\n): Promise<string[]> {\n const response = await fetch(`${REGISTRY_URL}/api/registry/dependencies`, {\n method: \"POST\",\n agent,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ components }),\n })\n\n if (!response.ok) {\n throw createRegistryError(\n response,\n `${REGISTRY_URL}/api/registry/dependencies`\n )\n }\n\n return (await response.json()) as Promise<string[]>\n}\n\nexport async function registryResolveItemsTree(\n names: RegistryItem[\"name\"][],\n config: z.infer<typeof configSchema>\n) {\n try {\n const index = await getRegistryIndex()\n if (!index) {\n return null\n }\n\n // If we're resolving the index, we want it to go first.\n if (names.includes(\"index\")) {\n names.unshift(\"index\")\n }\n\n const registryItems = await resolveRegistryItems(names)\n const result = await fetchRegistry(registryItems)\n const payload = z.array(registryItemSchema).parse(result)\n\n if (!payload) {\n return null\n }\n\n const projectInfo = await getProjectInfo(config.resolvedPaths.cwd)\n const framework = projectInfo?.framework.name as Framework[\"name\"]\n\n const allDependencies = deepmerge.all(\n payload.map((item) => item.dependencies ?? [])\n )\n\n const allDevDependencies = deepmerge.all(\n payload.map((item) => item.devDependencies ?? [])\n )\n\n const filteredDevDependencies = filterDevDependenciesByFramework(\n allDevDependencies,\n framework\n )\n\n const dependenciesSet = new Set(\n (Array.isArray(allDependencies) ? allDependencies : []).map((dep) =>\n String(dep)\n )\n )\n const dedupedDevDependencies = filteredDevDependencies.filter(\n (dep) => !dependenciesSet.has(dep)\n )\n\n return registryResolvedItemsTreeSchema.parse({\n dependencies: allDependencies,\n devDependencies: dedupedDevDependencies,\n files: deepmerge.all(payload.map((item) => item.files ?? [])),\n })\n } catch (error) {\n handleError(error)\n return null\n }\n}\n\nexport async function resolveRegistryItems(names: string[]) {\n const results = await fetchRegistryDependencies(names)\n const registryDependencies = results.map((name) =>\n getRegistryUrl(`components/${name}.json`)\n )\n\n return registryDependencies\n}\n\nfunction getRegistryUrl(path: string) {\n if (isUrl(path)) {\n const url = new URL(path)\n return url.toString()\n }\n\n if (!REGISTRY_URL) {\n throw new Error(\"No registry URL found\")\n }\n\n // Keep the index.json path as is (public)\n if (path === \"index.json\") {\n return `${REGISTRY_URL}/r/${path}`\n }\n\n // Only redirect component paths to the API\n if (path.startsWith(\"components/\")) {\n const componentName = path.replace(\"components/\", \"\").replace(\".json\", \"\")\n return `${REGISTRY_URL}/api/registry/components/${componentName}`\n }\n\n return `${REGISTRY_URL}/${path}`\n}\n\nfunction isUrl(path: string) {\n try {\n new URL(path)\n return true\n } catch (error) {\n return false\n }\n}\n\nexport function getRegistryTypeAliasMap() {\n return new Map<string, string>([\n [\"registry:ui\", \"tiptapUi\"],\n [\"registry:ui-primitive\", \"tiptapUiPrimitives\"],\n [\"registry:ui-utils\", \"tiptapUiUtils\"],\n [\"registry:extension\", \"tiptapExtensions\"],\n [\"registry:node\", \"tiptapNodes\"],\n [\"registry:context\", \"contexts\"],\n [\"registry:hook\", \"hooks\"],\n [\"registry:lib\", \"lib\"],\n [\"registry:context\", \"components\"],\n [\"registry:template\", \"tiptapTemplates\"],\n [\"registry:component\", \"components\"],\n [\"registry:icon\", \"tiptapIcons\"],\n [\"registry:style\", \"styles\"],\n ])\n}\n\n// Track a dependency and its parent.\nexport function getRegistryParentMap(registryItems: RegistryItem[]) {\n const map = new Map<string, RegistryItem>()\n\n registryItems.forEach((item) => {\n if (!item.registryDependencies) {\n return\n }\n\n item.registryDependencies.forEach((dependency) => {\n map.set(dependency, item)\n })\n })\n\n return map\n}\n\n/**\n * Filter development dependencies based on framework requirements\n * @param devDependencies Array of development dependencies\n * @param framework Framework name\n * @returns Filtered array of development dependencies\n */\nfunction filterDevDependenciesByFramework(\n devDependencies: unknown,\n framework: Framework[\"name\"]\n): string[] {\n const depsArray = Array.isArray(devDependencies) ? devDependencies : []\n\n if (!depsArray.length) {\n return []\n }\n\n const stringDeps = depsArray.map((dep) => String(dep))\n\n if (framework) {\n const hasSass = stringDeps.includes(\"sass\")\n const hasSassEmbedded = stringDeps.includes(\"sass-embedded\")\n\n if (hasSass || hasSassEmbedded) {\n let filteredDeps = [...stringDeps]\n\n const prefersEmbedded: Framework[\"name\"][] = [\n FRAMEWORKS.astro.name,\n FRAMEWORKS.laravel.name,\n FRAMEWORKS.vite.name,\n // FRAMEWORKS.remix.name,\n FRAMEWORKS[\"tanstack-start\"].name,\n FRAMEWORKS[\"react-router\"].name,\n ]\n\n const prefersRegular: Framework[\"name\"][] = [\n FRAMEWORKS[\"next-app\"].name,\n FRAMEWORKS[\"next-pages\"].name,\n // FRAMEWORKS.gatsby.name,\n ]\n\n if (prefersEmbedded.includes(framework)) {\n filteredDeps = filteredDeps.filter((dep) => dep !== \"sass\")\n } else if (prefersRegular.includes(framework)) {\n filteredDeps = filteredDeps.filter((dep) => dep !== \"sass-embedded\")\n }\n\n return filteredDeps\n }\n }\n\n return stringDeps\n}\n","import Conf from \"conf\"\nimport type { Logger } from \"./logger\"\n\nexport interface TokenConfig {\n bearerToken?: string\n authToken?: string\n email?: string\n loginDate?: string\n plans?: string[]\n licenseAccepted?: boolean\n licenseAcceptedDate?: string\n}\n\nexport class TokenStorage {\n private config: Conf<TokenConfig>\n private logger: Logger\n\n constructor(logger: Logger) {\n this.logger = logger\n this.config = new Conf<TokenConfig>({\n projectName: \"tiptap-cli\",\n clearInvalidConfig: true, // auto-reset if file is corrupted\n schema: {\n bearerToken: { type: \"string\" },\n authToken: { type: \"string\" },\n email: { type: \"string\" },\n loginDate: { type: \"string\" },\n plans: { type: \"array\", items: { type: \"string\" }, default: [] },\n licenseAccepted: { type: \"boolean\" },\n licenseAcceptedDate: { type: \"string\" },\n },\n })\n }\n\n private safeError(prefix: string, error: unknown) {\n const msg =\n error instanceof Error\n ? `${error.name}: ${error.message}`\n : String(error ?? \"Unknown error\")\n try {\n this.logger.error(`${prefix}: ${msg}`)\n } catch {\n // never throw from logging\n }\n }\n\n setBearerToken(\n token: string,\n userInfo?: { email?: string; plans?: string[] }\n ): void {\n try {\n this.config.set(\"bearerToken\", token)\n this.config.set(\"loginDate\", new Date().toISOString())\n if (userInfo?.email) this.config.set(\"email\", userInfo.email)\n if (userInfo?.plans) this.config.set(\"plans\", userInfo.plans)\n } catch (e) {\n this.safeError(\"Failed to store bearer token\", e)\n }\n }\n\n getBearerToken(): string | null {\n try {\n return this.config.get(\"bearerToken\") ?? null\n } catch (e) {\n this.safeError(\"Failed to retrieve bearer token\", e)\n return null\n }\n }\n\n setAuthToken(\n token: string,\n userInfo?: { email?: string; plans?: string[] }\n ): void {\n try {\n this.config.set(\"authToken\", token)\n this.config.set(\"loginDate\", new Date().toISOString())\n if (userInfo?.email) this.config.set(\"email\", userInfo.email)\n if (userInfo?.plans) this.config.set(\"plans\", userInfo.plans)\n } catch (e) {\n this.safeError(\"Failed to store auth token\", e)\n }\n }\n\n getAuthToken(): string | null {\n try {\n return this.config.get(\"authToken\") ?? null\n } catch (e) {\n this.safeError(\"Failed to retrieve auth token\", e)\n return null\n }\n }\n\n getUserInfo(): { email?: string; plans: string[]; loginDate?: string } {\n return {\n email: this.config.get(\"email\"),\n plans: this.config.get(\"plans\") ?? [],\n loginDate: this.config.get(\"loginDate\"),\n }\n }\n\n getTokenExpiration(): string | null {\n const loginDate = this.config.get(\"loginDate\")\n if (!loginDate) return null\n const expiration = new Date(loginDate)\n expiration.setMonth(expiration.getMonth() + 11)\n\n return expiration.toISOString()\n }\n\n isValidToken(): boolean {\n const bearerToken = this.getBearerToken()\n const authToken = this.getAuthToken()\n\n if (!bearerToken && !authToken) return false\n\n const expirationISO = this.getTokenExpiration()\n if (expirationISO) {\n const expiryDate = new Date(expirationISO)\n if (expiryDate <= new Date()) {\n this.clearSession()\n return false\n }\n }\n\n return true\n }\n\n clear(): void {\n try {\n this.config.clear()\n } catch (e) {\n this.safeError(\"Failed to clear token storage\", e)\n }\n }\n\n clearSession(): void {\n try {\n this.config.delete(\"bearerToken\")\n this.config.delete(\"authToken\")\n this.config.delete(\"email\")\n this.config.delete(\"loginDate\")\n this.config.delete(\"plans\")\n } catch (e) {\n this.safeError(\"Failed to clear token storage\", e)\n }\n }\n\n hasPlan(planName: string): boolean {\n const plans = this.config.get(\"plans\") ?? []\n return Array.isArray(plans) && plans.includes(planName)\n }\n\n setLicenseAccepted(): void {\n try {\n this.config.set(\"licenseAccepted\", true)\n this.config.set(\"licenseAcceptedDate\", new Date().toISOString())\n } catch (e) {\n this.safeError(\"Failed to store license acceptance\", e)\n }\n }\n\n hasAcceptedLicense(): boolean {\n try {\n return this.config.get(\"licenseAccepted\") ?? false\n } catch (e) {\n this.safeError(\"Failed to retrieve license acceptance\", e)\n return false\n }\n }\n\n clearLicenseAcceptance(): void {\n try {\n this.config.delete(\"licenseAccepted\")\n this.config.delete(\"licenseAcceptedDate\")\n } catch (e) {\n this.safeError(\"Failed to clear license acceptance\", e)\n }\n }\n}\n","import { logger } from \"./logger\"\nimport { TokenStorage } from \"./token-storage\"\n\nexport const tokenStorage = new TokenStorage(logger)\n","import ora, { type Options } from \"ora\"\nimport { colors } from \"@/src/utils/colors\"\n\n// Custom Tiptap-style spinner frames that resemble a typewriter cursor\nconst tiptapSpinner = {\n frames: [\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n ` `, // Space (cursor hidden)\n ` `, // Space (cursor hidden)\n ` `, // Space (cursor hidden)\n ],\n interval: 200, // Typewriter-like blinking speed\n}\n\nexport function spinner(\n text: Options[\"text\"],\n options?: {\n silent?: boolean\n }\n) {\n return ora({\n text: text,\n spinner: tiptapSpinner,\n color: \"cyan\",\n isSilent: options?.silent,\n })\n}\n","import { detect } from \"@antfu/ni\"\nimport fs from \"fs-extra\"\nimport path from \"path\"\n\nexport async function getPackageManager(\n targetDir: string,\n { withFallback }: { withFallback?: boolean } = {\n withFallback: false,\n }\n): Promise<\"yarn\" | \"pnpm\" | \"bun\" | \"npm\"> {\n const detectedPackageManager = await detect({\n programmatic: true,\n cwd: targetDir,\n })\n\n const packageManager = (() => {\n switch (detectedPackageManager) {\n case \"yarn\":\n case \"yarn@berry\":\n return \"yarn\"\n case \"pnpm\":\n case \"pnpm@6\":\n return \"pnpm\"\n case \"bun\":\n return \"bun\"\n case \"npm\":\n return \"npm\"\n default:\n return undefined\n }\n })()\n\n if (!withFallback) {\n return packageManager ?? \"npm\"\n }\n\n // Fallback to user agent if not detected.\n const userAgent = process.env.npm_config_user_agent || \"\"\n\n if (userAgent.startsWith(\"yarn\")) {\n return \"yarn\"\n }\n\n if (userAgent.startsWith(\"pnpm\")) {\n return \"pnpm\"\n }\n\n if (userAgent.startsWith(\"bun\")) {\n return \"bun\"\n }\n\n return \"npm\"\n}\n\nexport async function getPackageRunner(cwd: string) {\n const packageManager = await getPackageManager(cwd)\n\n if (packageManager === \"pnpm\") return \"pnpm dlx\"\n\n if (packageManager === \"bun\") return \"bunx\"\n\n return \"npx\"\n}\n\nexport function isBunProject(cwd: string) {\n const hasBunLock = fs.existsSync(path.join(cwd, \"bun.lock\"))\n const hasBunfig = fs.existsSync(path.join(cwd, \"bunfig.toml\"))\n\n if (hasBunLock && hasBunfig) {\n return true\n }\n\n return false\n}\n","import { Config } from \"@/src/utils/get-config\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { RegistryItem } from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { execa } from \"execa\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport async function updateDependencies(\n dependencies: RegistryItem[\"dependencies\"],\n config: Config,\n options: {\n silent?: boolean\n }\n) {\n dependencies = Array.from(new Set(dependencies))\n if (!dependencies?.length) {\n return\n }\n\n options = {\n silent: false,\n ...options,\n }\n\n const dependenciesSpinner = spinner(`Installing dependencies.`, {\n silent: options.silent,\n }).start()\n const packageManager = await getPackageManager(config.resolvedPaths.cwd)\n\n await execa(\n packageManager,\n [\n packageManager === \"npm\" ? \"install\" : \"add\",\n ...(packageManager === \"npm\" ? [\"--save\"] : []),\n ...dependencies,\n ],\n {\n cwd: config.resolvedPaths.cwd,\n }\n )\n\n dependenciesSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path, { basename } from \"path\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { getProjectInfo, ProjectInfo } from \"@/src/utils/get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport {\n RegistryItem,\n registryItemFileSchema,\n} from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { transform } from \"@/src/utils/transformers\"\nimport { transformImport } from \"@/src/utils/transformers/transform-import\"\nimport { transformRsc } from \"@/src/utils/transformers/transform-rsc\"\nimport { z } from \"zod\"\nimport { confirm } from \"@inquirer/prompts\"\nimport {\n getPackageManager,\n isBunProject,\n} from \"@/src/utils/get-package-manager\"\nimport { colors } from \"@/src/utils/colors\"\nimport { transformRemoveComponents } from \"@/src/utils/transformers/transform-remove-components\"\n\nconst SCSS_DECLARATION_FILE = \"scss.d.ts\"\nconst SCSS_DECLARATION_CONTENT = `declare module \"*.scss\";\\n`\n\nexport async function updateFiles(\n files: RegistryItem[\"files\"],\n config: Config,\n options: {\n overwrite?: boolean\n force?: boolean\n silent?: boolean\n rootSpinner?: ReturnType<typeof spinner>\n }\n) {\n const result = {\n filesCreated: [] as string[],\n filesUpdated: [] as string[],\n filesSkipped: [] as string[],\n errors: [] as { file: string; error: string }[],\n }\n\n if (!files?.length) {\n return result\n }\n\n options = {\n overwrite: false,\n force: false,\n silent: false,\n ...options,\n }\n\n const filesCreatedSpinner = spinner(`Updating files.`, {\n silent: options.silent,\n })?.start()\n\n try {\n const [projectInfo, packageManager] = await Promise.all([\n getProjectInfo(config.resolvedPaths.cwd),\n getPackageManager(config.resolvedPaths.cwd),\n ])\n\n for (const file of files) {\n try {\n if (!file.content) {\n continue\n }\n\n let filePath: string | undefined\n try {\n filePath = resolveFilePath(file, config, {\n isSrcDir: projectInfo?.isSrcDir,\n framework: projectInfo?.framework.name,\n commonRoot: findCommonRoot(\n files.map((f) => f.path),\n file.path\n ),\n })\n } catch (error) {\n result.errors.push({\n file: file.path,\n error: `Failed to resolve file path: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n }\n\n if (!filePath) {\n continue\n }\n\n const fileName = basename(file.path)\n const targetDir = path.dirname(filePath)\n\n if (!config.tsx) {\n filePath = filePath.replace(/\\.tsx?$/, (match) =>\n match === \".tsx\" ? \".jsx\" : \".js\"\n )\n }\n\n const isBun = isBunProject(config.resolvedPaths.cwd)\n\n // For Bun projects, convert .scss files to .css\n if (isBun && filePath.endsWith(\".scss\")) {\n filePath = filePath.replace(/\\.scss$/, \".css\")\n }\n\n let existingFile = false\n try {\n existingFile = existsSync(filePath)\n } catch (error) {\n result.errors.push({\n file: filePath,\n error: `Failed to check if file exists: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n }\n\n let content: string\n try {\n content = await transform(\n {\n filename: file.path,\n raw: file.content,\n config,\n transformJsx: !config.tsx,\n packageManager,\n },\n [transformImport, transformRsc, transformRemoveComponents]\n )\n } catch (error) {\n result.errors.push({\n file: filePath,\n error: `Failed to transform content: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n }\n\n if (existingFile) {\n try {\n const existingFileContent = await fs.readFile(filePath, \"utf-8\")\n const [normalizedExisting, normalizedNew] = await Promise.all([\n getNormalizedFileContent(existingFileContent),\n getNormalizedFileContent(content),\n ])\n if (normalizedExisting === normalizedNew) {\n result.filesSkipped.push(\n path.relative(config.resolvedPaths.cwd, filePath)\n )\n continue\n }\n } catch (error) {\n result.errors.push({\n file: filePath,\n error: `Failed to read or normalize existing file: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n }\n }\n\n if (existingFile && !options.overwrite) {\n filesCreatedSpinner?.stop()\n if (options.rootSpinner) {\n options.rootSpinner?.stop()\n }\n\n try {\n const overwrite = await confirm({\n message: colors.reset(\n `The file ${colors.cyan(\n fileName\n )} already exists. Would you like to overwrite?`\n ),\n theme: {\n prefix: colors.cyan(\"?\"),\n style: {\n message: (text: string) => colors.reset(text),\n },\n },\n })\n\n if (!overwrite) {\n result.filesSkipped.push(\n path.relative(config.resolvedPaths.cwd, filePath)\n )\n if (options.rootSpinner) {\n options.rootSpinner.start()\n }\n continue\n }\n } catch (error) {\n result.errors.push({\n file: filePath,\n error: `Failed to get user confirmation: ${error instanceof Error ? error.message : String(error)}`,\n })\n continue\n } finally {\n filesCreatedSpinner?.start()\n if (options.rootSpinner) {\n options.rootSpinner.start()\n }\n }\n }\n\n try {\n if (!existsSync(targetDir)) {\n await fs.mkdir(targetDir, { recursive: true })\n }\n\n await fs.writeFile(filePath, content, \"utf-8\")\n\n existingFile\n ? result.filesUpdated.push(\n path.relative(config.resolvedPaths.cwd, filePath)\n )\n : result.filesCreated.push(\n path.relative(config.resolvedPaths.cwd, filePath)\n )\n } catch (error) {\n result.errors.push({\n file: filePath,\n error: `Failed to write file: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n } catch (error) {\n result.errors.push({\n file: file.path || \"unknown\",\n error: `Unexpected error processing file: ${error instanceof Error ? error.message : String(error)}`,\n })\n }\n }\n\n // Create scss.d.ts if any .scss files were added\n const hasScssFiles = [...result.filesCreated, ...result.filesUpdated].some(\n (file) => file.endsWith(\".scss\")\n )\n if (hasScssFiles) {\n const declFile = await ensureScssTypeDeclaration(\n config.resolvedPaths.cwd,\n projectInfo?.isSrcDir ?? false\n )\n if (declFile) {\n result.filesCreated.push(declFile)\n }\n }\n } catch (error) {\n logger.error(\n `An error occurred while updating files: ${error instanceof Error ? error.message : String(error)}`\n )\n } finally {\n const hasUpdatedFiles =\n result.filesCreated.length || result.filesUpdated.length\n if (!hasUpdatedFiles && !result.filesSkipped.length) {\n filesCreatedSpinner?.info(\"No files updated.\")\n }\n\n if (result.filesCreated.length) {\n filesCreatedSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: `Created ${result.filesCreated.length} ${\n result.filesCreated.length === 1 ? \"file\" : \"files\"\n }:`,\n })\n if (!options.silent) {\n for (const file of result.filesCreated) {\n logger.log(` - ${file}`)\n }\n }\n } else {\n filesCreatedSpinner?.stop()\n }\n\n if (result.filesUpdated.length) {\n spinner(\n `Updated ${result.filesUpdated.length} ${\n result.filesUpdated.length === 1 ? \"file\" : \"files\"\n }:`,\n {\n silent: options.silent,\n }\n )?.info()\n if (!options.silent) {\n for (const file of result.filesUpdated) {\n logger.log(` - ${file}`)\n }\n }\n }\n\n if (result.filesSkipped.length) {\n spinner(\n `Skipped ${result.filesSkipped.length} ${\n result.filesUpdated.length === 1 ? \"file\" : \"files\"\n }: (use --overwrite to overwrite)`,\n {\n silent: options.silent,\n }\n )?.info()\n if (!options.silent) {\n for (const file of result.filesSkipped) {\n logger.log(` - ${file}`)\n }\n }\n }\n\n if (result.errors.length) {\n spinner(\n `Failed to process ${result.errors.length} ${\n result.errors.length === 1 ? \"file\" : \"files\"\n }:`,\n {\n silent: options.silent,\n }\n )?.fail()\n if (!options.silent) {\n for (const { file, error } of result.errors) {\n logger.error(` - ${file}: ${error}`)\n }\n }\n }\n\n if (!options.silent) {\n logger.break()\n }\n }\n\n return result\n}\n\nexport function resolveFileTargetDirectory(\n file: z.infer<typeof registryItemFileSchema>,\n config: Config,\n override?: string\n) {\n if (override) {\n return override\n }\n\n if (file.type === \"registry:ui\") {\n return config.resolvedPaths.tiptapUi\n }\n\n if (file.type === \"registry:ui-primitive\") {\n return config.resolvedPaths.tiptapUiPrimitives\n }\n\n if (file.type === \"registry:ui-utils\") {\n return config.resolvedPaths.tiptapUiUtils\n }\n\n if (file.type === \"registry:extension\") {\n return config.resolvedPaths.tiptapExtensions\n }\n\n if (file.type === \"registry:node\") {\n return config.resolvedPaths.tiptapNodes\n }\n\n if (file.type === \"registry:icon\") {\n return config.resolvedPaths.tiptapIcons\n }\n\n if (file.type === \"registry:hook\") {\n return config.resolvedPaths.hooks\n }\n\n if (file.type === \"registry:lib\") {\n return config.resolvedPaths.lib\n }\n\n if (file.type === \"registry:context\") {\n return config.resolvedPaths.contexts\n }\n\n if (file.type === \"registry:template\" || file.type === \"registry:component\") {\n return config.resolvedPaths.components\n }\n\n if (file.type === \"registry:style\") {\n return config.resolvedPaths.styles\n }\n\n return config.resolvedPaths.components\n}\n\nexport function findCommonRoot(paths: string[], needle: string): string {\n // Remove leading slashes for consistent handling\n const normalizedPaths = paths.map((p) => p.replace(/^\\//, \"\"))\n const normalizedNeedle = needle.replace(/^\\//, \"\")\n\n // Get the directory path of the needle by removing the file name\n const needleDir = normalizedNeedle.split(\"/\").slice(0, -1).join(\"/\")\n\n // If needle is at root level, return empty string\n if (!needleDir) {\n return \"\"\n }\n\n // Split the needle directory into segments\n const needleSegments = needleDir.split(\"/\")\n\n // Start from the full path and work backwards\n for (let i = needleSegments.length; i > 0; i--) {\n const testPath = needleSegments.slice(0, i).join(\"/\")\n // Check if this is a common root by verifying if any other paths start with it\n const hasRelatedPaths = normalizedPaths.some(\n (path) => path !== normalizedNeedle && path.startsWith(testPath + \"/\")\n )\n if (hasRelatedPaths) {\n return \"/\" + testPath // Add leading slash back for the result\n }\n }\n\n // If no common root found with other files, return the parent directory of the needle\n return \"/\" + needleDir // Add leading slash back for the result\n}\n\nexport async function getNormalizedFileContent(content: string) {\n return content.replace(/\\r\\n/g, \"\\n\").trim()\n}\n\nexport function resolvePageTarget(\n target: string,\n framework?: ProjectInfo[\"framework\"][\"name\"]\n) {\n if (!framework) {\n return \"\"\n }\n\n if (framework === \"next-app\") {\n return target\n }\n\n if (framework === \"next-pages\") {\n let result = target.replace(/^app\\//, \"pages/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n if (framework === \"react-router\") {\n let result = target.replace(/^app\\//, \"app/routes/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n if (framework === \"laravel\") {\n let result = target.replace(/^app\\//, \"resources/js/pages/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n return \"\"\n}\n\nexport function resolveNestedFilePath(\n filePath: string,\n targetDir: string\n): string {\n // Normalize paths by removing leading/trailing slashes\n const normalizedFilePath = filePath.replace(/^\\/|\\/$/g, \"\")\n const normalizedTargetDir = targetDir.replace(/^\\/|\\/$/g, \"\")\n\n // Split paths into segments\n const fileSegments = normalizedFilePath.split(\"/\")\n const targetSegments = normalizedTargetDir.split(\"/\")\n\n // Find the last matching segment from targetDir in filePath\n const lastTargetSegment = targetSegments[targetSegments.length - 1]\n const commonDirIndex = fileSegments.findIndex(\n (segment) => segment === lastTargetSegment\n )\n\n if (commonDirIndex === -1) {\n // Return just the filename if no common directory is found\n return fileSegments[fileSegments.length - 1]\n }\n\n // Return everything after the common directory\n return fileSegments.slice(commonDirIndex + 1).join(\"/\")\n}\n\nexport function resolveFilePath(\n file: z.infer<typeof registryItemFileSchema>,\n config: Config,\n options: {\n isSrcDir?: boolean\n commonRoot?: string\n framework?: ProjectInfo[\"framework\"][\"name\"]\n }\n) {\n // if (file.type === \"registry:asset\") {\n // if (file.target) {\n // // replace assets/ and public/ with the public directory\n // const targetDir = file.target.replace(/^assets\\//, \"\")\n // const targetDirPublic = targetDir.replace(/^public\\//, \"\")\n // const targetDirPublicPath = path.join(\n // config.resolvedPaths.cwd,\n // \"public\",\n // targetDirPublic\n // )\n\n // return targetDirPublicPath\n // }\n // }\n\n // Special handling for template files without targets\n if (\n !file.target &&\n file.path.includes(\"tiptap-templates/\") &&\n file.type !== \"registry:page\"\n ) {\n const match = file.path.match(/tiptap-templates\\/([^/]+)\\/(.*)/)\n if (match) {\n const [, templateName, relativePath] = match\n\n // If it's a component file in the components directory, adjust the path\n if (relativePath.startsWith(\"components/\")) {\n const finalPath = relativePath.replace(\"components/\", \"\")\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n finalPath\n )\n }\n\n // For data and other files\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n relativePath\n )\n }\n }\n\n // Special handling for data files with targets in templates\n if (\n file.target &&\n file.path.includes(\"tiptap-templates/\") &&\n file.target.includes(\"/data/\")\n ) {\n const templateMatch = file.path.match(/tiptap-templates\\/([^/]+)\\//)\n if (templateMatch) {\n const templateName = templateMatch[1]\n const dataPath = file.target.split(\"/data/\")[1]\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n \"data\",\n dataPath\n )\n }\n }\n\n // Original logic for files with explicit targets\n if (file.target) {\n if (file.target.startsWith(\"~/\")) {\n return path.join(config.resolvedPaths.cwd, file.target.replace(\"~/\", \"\"))\n }\n\n let target = file.target\n\n if (file.type === \"registry:page\") {\n target = resolvePageTarget(target, options.framework)\n if (!target) {\n return \"\"\n }\n }\n\n return options.isSrcDir\n ? path.join(config.resolvedPaths.cwd, \"src\", target.replace(\"src/\", \"\"))\n : path.join(config.resolvedPaths.cwd, target.replace(\"src/\", \"\"))\n }\n\n // Original logic for non-template files\n const targetDir = resolveFileTargetDirectory(file, config)\n const relativePath = resolveNestedFilePath(file.path, targetDir)\n return path.join(targetDir, relativePath)\n}\n\n/**\n * Ensures a scss.d.ts type declaration file exists in the project\n * when SCSS files are being installed. This prevents TypeScript errors\n * like \"Cannot find module '*.scss'\" in the user's project.\n */\nasync function ensureScssTypeDeclaration(\n cwd: string,\n isSrcDir: boolean\n): Promise<string | null> {\n const targetDir = isSrcDir ? path.join(cwd, \"src\") : cwd\n const declarationPath = path.join(targetDir, SCSS_DECLARATION_FILE)\n\n if (existsSync(declarationPath)) {\n return null\n }\n\n if (!existsSync(targetDir)) {\n await fs.mkdir(targetDir, { recursive: true })\n }\n\n await fs.writeFile(declarationPath, SCSS_DECLARATION_CONTENT, \"utf-8\")\n return path.relative(cwd, declarationPath)\n}\n","import { promises as fs } from \"fs\"\nimport { tmpdir } from \"os\"\nimport path from \"path\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { transformImport } from \"@/src/utils/transformers/transform-import\"\nimport { transformJsx } from \"@/src/utils/transformers/transform-jsx\"\nimport { transformRsc } from \"@/src/utils/transformers/transform-rsc\"\nimport { transformRemoveComponents } from \"@/src/utils/transformers/transform-remove-components\"\nimport { transformScssToCSS } from \"@/src/utils/transformers/transform-scss-to-css\"\nimport { Project, ScriptKind, type SourceFile } from \"ts-morph\"\nimport { isBunProject } from \"../get-package-manager\"\n\nexport type TransformOpts = {\n filename: string\n raw: string\n config: Config\n transformJsx?: boolean\n packageManager?: \"yarn\" | \"pnpm\" | \"bun\" | \"npm\"\n}\n\nexport type Transformer<Output = SourceFile> = (\n opts: TransformOpts & {\n sourceFile: SourceFile\n }\n) => Promise<Output>\n\nconst project = new Project({\n compilerOptions: {},\n})\n\nasync function createTempSourceFile(filename: string) {\n const dir = await fs.mkdtemp(path.join(tmpdir(), \"tiptap-\"))\n return path.join(dir, filename)\n}\n\nexport async function transform(\n opts: TransformOpts,\n transformers: Transformer[] = [\n transformImport,\n transformRsc,\n transformRemoveComponents,\n ]\n) {\n const isBun = isBunProject(opts.config.resolvedPaths.cwd)\n // For Bun projects, convert SCSS to CSS\n if (opts.filename.endsWith(\".scss\") && isBun) {\n return await transformScssToCSS(opts.raw)\n }\n\n if (\n opts.filename.endsWith(\".scss\") ||\n opts.filename.endsWith(\".css\") ||\n opts.filename.endsWith(\".json\")\n ) {\n return opts.raw\n }\n\n const tempFile = await createTempSourceFile(opts.filename)\n const sourceFile = project.createSourceFile(tempFile, opts.raw, {\n scriptKind: ScriptKind.TSX,\n })\n\n for (const transformer of transformers) {\n await transformer({ sourceFile, ...opts })\n }\n\n if (opts.transformJsx) {\n return await transformJsx({\n sourceFile,\n ...opts,\n })\n }\n\n return sourceFile.getText()\n}\n","import { Config } from \"@/src/utils/get-config\"\nimport { Transformer } from \"@/src/utils/transformers\"\nimport { isBunProject } from \"../get-package-manager\"\n\nexport const transformImport: Transformer = async ({\n sourceFile,\n config,\n packageManager,\n}) => {\n const importDeclarations = sourceFile.getImportDeclarations()\n\n for (const importDeclaration of importDeclarations) {\n let moduleSpecifier = updateImportAliases(\n importDeclaration.getModuleSpecifierValue(),\n config\n )\n\n const isBun = isBunProject(config.resolvedPaths.cwd)\n\n // For Bun projects, convert .scss imports to .css\n if (isBun && moduleSpecifier.endsWith(\".scss\")) {\n moduleSpecifier = moduleSpecifier.replace(/\\.scss$/, \".css\")\n }\n\n if (moduleSpecifier) {\n importDeclaration.setModuleSpecifier(moduleSpecifier)\n }\n }\n\n return sourceFile\n}\n\nfunction updateImportAliases(moduleSpecifier: string, config: Config): string {\n // Remove \"/registry/\" from the module specifier\n if (!moduleSpecifier.startsWith(\"@/registry/\")) {\n // We fix the alias and return.\n const alias = config.aliases.components.split(\"/\")[0]\n return moduleSpecifier.replace(/^@\\//, `${alias}/`)\n }\n\n // Handle template imports specifically to preserve the template structure\n if (\n moduleSpecifier.match(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/components\\//\n )\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/components\\//,\n `${config.aliases.components}/tiptap-templates/$1/`\n )\n }\n\n // Handle template imports without the components part\n if (\n moduleSpecifier.match(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/(?!components\\/)/\n )\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\//,\n `${config.aliases.components}/tiptap-templates/$1/`\n )\n }\n\n if (\n config.aliases.components &&\n moduleSpecifier.match(/@\\/registry\\/components/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/components/,\n config.aliases.components\n )\n }\n\n if (\n config.aliases.contexts &&\n moduleSpecifier.match(/@\\/registry\\/contexts/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/contexts/,\n config.aliases.contexts\n )\n }\n\n if (\n config.aliases.tiptapExtensions &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-extension/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-extension/,\n config.aliases.tiptapExtensions\n )\n }\n\n if (config.aliases.hooks && moduleSpecifier.match(/@\\/registry\\/hooks/)) {\n return moduleSpecifier.replace(/@\\/registry\\/hooks/, config.aliases.hooks)\n }\n\n if (\n config.aliases.tiptapIcons &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-icons/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-icons/,\n config.aliases.tiptapIcons\n )\n }\n\n if (config.aliases.lib && moduleSpecifier.match(/@\\/registry\\/lib/)) {\n return moduleSpecifier.replace(/@\\/registry\\/lib/, config.aliases.lib)\n }\n\n if (\n config.aliases.tiptapNodes &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-node/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-node/,\n config.aliases.tiptapNodes\n )\n }\n\n if (\n config.aliases.tiptapUiPrimitives &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui-primitive/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui-primitive/,\n config.aliases.tiptapUiPrimitives\n )\n }\n\n if (\n config.aliases.tiptapUiUtils &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui-utils/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui-utils/,\n config.aliases.tiptapUiUtils\n )\n }\n\n if (\n config.aliases.tiptapUi &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui/,\n config.aliases.tiptapUi\n )\n }\n\n if (config.aliases.styles && moduleSpecifier.match(/@\\/registry\\/styles/)) {\n return moduleSpecifier.replace(/@\\/registry\\/styles/, config.aliases.styles)\n }\n\n // Default case - preserve all other imports\n return moduleSpecifier.replace(\n /^@\\/registry\\/[^/]+(?:\\/.*\\/)?/,\n config.aliases.components + \"/\"\n )\n}\n","import { type Transformer } from \"@/src/utils/transformers\"\nimport { transformFromAstSync } from \"@babel/core\"\nimport { ParserOptions, parse } from \"@babel/parser\"\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-expect-error\nimport transformTypescript from \"@babel/plugin-transform-typescript\"\nimport * as recast from \"recast\"\n\n// TODO.\n// I'm using recast for the AST here.\n// Figure out if ts-morph AST is compatible with Babel.\n\n// This is a copy of the babel options from recast/parser.\n// The goal here is to tolerate as much syntax as possible.\n// We want to be able to parse any valid tsx code.\n// See https://github.com/benjamn/recast/blob/master/parsers/_babel_options.ts.\nconst PARSE_OPTIONS: ParserOptions = {\n sourceType: \"module\",\n allowImportExportEverywhere: true,\n allowReturnOutsideFunction: true,\n startLine: 1,\n tokens: true,\n plugins: [\n \"asyncGenerators\",\n \"bigInt\",\n \"classPrivateMethods\",\n \"classPrivateProperties\",\n \"classProperties\",\n \"classStaticBlock\",\n \"decimal\",\n \"decorators-legacy\",\n \"doExpressions\",\n \"dynamicImport\",\n \"exportDefaultFrom\",\n \"exportNamespaceFrom\",\n \"functionBind\",\n \"functionSent\",\n \"importAssertions\",\n \"importMeta\",\n \"nullishCoalescingOperator\",\n \"numericSeparator\",\n \"objectRestSpread\",\n \"optionalCatchBinding\",\n \"optionalChaining\",\n [\n \"pipelineOperator\",\n {\n proposal: \"minimal\",\n },\n ],\n [\n \"recordAndTuple\",\n {\n syntaxType: \"hash\",\n },\n ],\n \"throwExpressions\",\n \"topLevelAwait\",\n \"v8intrinsic\",\n \"typescript\",\n \"jsx\",\n ],\n}\n\nexport const transformJsx: Transformer<string> = async ({\n sourceFile,\n config,\n}) => {\n const output = sourceFile.getFullText()\n\n if (config.tsx) {\n return output\n }\n\n const ast = recast.parse(output, {\n parser: {\n parse: (code: string) => {\n return parse(code, PARSE_OPTIONS)\n },\n },\n })\n\n const result = transformFromAstSync(ast, output, {\n cloneInputAst: false,\n code: false,\n ast: true,\n plugins: [transformTypescript],\n configFile: false,\n })\n\n if (!result || !result.ast) {\n throw new Error(\"Failed to transform JSX\")\n }\n\n return recast.print(result.ast).code\n}\n","import { Transformer } from \"@/src/utils/transformers\"\nimport { SyntaxKind } from \"ts-morph\"\n\nconst directiveRegex = /^[\"']use client[\"']$/g\n\nexport const transformRsc: Transformer = async ({ sourceFile, config }) => {\n if (config.rsc) {\n return sourceFile\n }\n\n // Remove \"use client\" from the top of the file.\n const first = sourceFile.getFirstChildByKind(SyntaxKind.ExpressionStatement)\n if (first && directiveRegex.test(first.getText())) {\n first.remove()\n }\n\n return sourceFile\n}\n","import { Transformer } from \"@/src/utils/transformers\"\nimport {\n BinaryExpression,\n CallExpression,\n Node,\n PropertyAccessExpression,\n PropertyAssignment,\n SourceFile,\n SyntaxKind,\n} from \"ts-morph\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { Config } from \"@/src/utils/get-config\"\n\n/**\n * Defines a rule for excluding components based on name matching patterns\n */\nexport interface ComponentExclusionRule {\n name: string // The name or pattern to match against\n matchType: \"exact\" | \"contains\" | \"startsWith\" | \"endsWith\" | \"regex\" // How to match the name\n caseSensitive?: boolean // Whether matching should be case sensitive\n pattern?: string // Regex pattern (used when matchType is \"regex\")\n onlyInFiles?: string[]\n}\n\ninterface NodeToRemove {\n node: any\n newText?: string\n action: \"remove\" | \"replace\"\n}\n\n/**\n * Default set of exclusion rules for common unwanted component patterns\n * These target development, testing, and internal components that shouldn't\n * be included in production builds or public APIs\n */\n/**\n * Default set of exclusion rules for common unwanted component patterns\n * These target development, testing, and internal components that shouldn't\n * be included in production builds or public APIs\n */\nconst DEFAULT_EXCLUSIONS: ComponentExclusionRule[] = [\n {\n name: \"cta\",\n matchType: \"contains\",\n caseSensitive: false,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"initialContent\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"JSONContent\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"onCreate\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"getDocumentId\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n]\n\n/**\n * Determines whether a component should be excluded based on the provided rules\n * @param componentName - The name of the component to check\n * @param rules - Array of exclusion rules to apply\n * @returns true if the component should be excluded, false otherwise\n */\nfunction shouldExcludeComponent(\n componentName: string,\n rules: ComponentExclusionRule[],\n filePath: string\n): boolean {\n return rules.some((rule) => {\n // Check file path restriction\n if (\n rule.onlyInFiles &&\n !rule.onlyInFiles.some((f) => filePath.endsWith(f))\n ) {\n return false\n }\n\n const name = rule.caseSensitive\n ? componentName\n : componentName.toLowerCase()\n const ruleName = rule.caseSensitive ? rule.name : rule.name.toLowerCase()\n\n switch (rule.matchType) {\n case \"exact\":\n return name === ruleName\n case \"contains\":\n return name.includes(ruleName)\n case \"startsWith\":\n return name.startsWith(ruleName)\n case \"endsWith\":\n return name.endsWith(ruleName)\n case \"regex\":\n if (!rule.pattern) return false\n const regex = new RegExp(rule.pattern, rule.caseSensitive ? \"\" : \"i\")\n return regex.test(name)\n default:\n return false\n }\n })\n}\n\nfunction getFrameworkEnvVarName(\n constantName: string,\n framework: Framework\n): string {\n const frameworkName = framework.name\n\n if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n return `NEXT_PUBLIC_${constantName}`\n } else if (frameworkName === FRAMEWORKS.astro.name) {\n return `PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n return `VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.laravel.name ||\n frameworkName === FRAMEWORKS.manual.name\n ) {\n return constantName\n } else {\n return constantName\n }\n}\n\nfunction stripFrameworkPrefix(varName: string): string {\n return varName.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/, \"\")\n}\n\nasync function transformEnvironmentVariables(\n sourceFile: SourceFile,\n config: Config\n): Promise<void> {\n const projectInfo = await getProjectInfo(config.resolvedPaths.cwd)\n\n if (!projectInfo) {\n return\n }\n\n const nodesToTransform: Array<{\n node: BinaryExpression | PropertyAccessExpression | CallExpression\n newText: string\n }> = []\n\n // 1. Transform environment variable access\n const binaryExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.BinaryExpression\n )\n\n for (const binaryExpr of binaryExpressions) {\n if (binaryExpr.getOperatorToken().getKind() === SyntaxKind.BarBarToken) {\n const left = binaryExpr.getLeft()\n const leftText = left.getText()\n\n if (leftText.match(/^process\\.env\\.[A-Z_]+$/)) {\n const match = leftText.match(/process\\.env\\.([A-Z_]+)/)\n if (match && match[1]) {\n const constantName = stripFrameworkPrefix(match[1])\n const frameworkName = projectInfo.framework.name\n\n let transformedEnvVar: string\n if (frameworkName === FRAMEWORKS.astro.name) {\n transformedEnvVar = `import.meta.env.PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n transformedEnvVar = `import.meta.env.VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n transformedEnvVar = `process.env.NEXT_PUBLIC_${constantName}`\n } else {\n transformedEnvVar = `process.env.${constantName}`\n }\n\n const rightSide = binaryExpr.getRight().getText()\n const newExpression = `${transformedEnvVar} || ${rightSide}`\n\n nodesToTransform.push({\n node: binaryExpr,\n newText: newExpression,\n })\n }\n }\n }\n }\n\n // 2. Transform alert calls that contain environment variable lists\n const callExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.CallExpression\n )\n\n for (const callExpr of callExpressions) {\n const expression = callExpr.getExpression()\n const expressionText = expression.getText()\n\n // Check for alert calls\n if (expressionText.match(/^alert$/)) {\n const args = callExpr.getArguments()\n if (args.length > 0) {\n const firstArg = args[0]\n const argText = firstArg.getText()\n\n // Look for template literals or strings that contain environment variable lists\n if (\n argText.includes(\"TIPTAP_COLLAB_TOKEN\") ||\n argText.includes(\"TIPTAP_COLLAB_DOC_PREFIX\") ||\n argText.includes(\"TIPTAP_AI_TOKEN\")\n ) {\n let newArgText = argText\n\n const envVarsToTransform = [\n \"TIPTAP_COLLAB_DOC_PREFIX\",\n \"TIPTAP_COLLAB_APP_ID\",\n \"TIPTAP_COLLAB_TOKEN\",\n \"TIPTAP_AI_APP_ID\",\n \"TIPTAP_AI_TOKEN\",\n \"USE_JWT_TOKEN_API_ENDPOINT\",\n ]\n\n for (let constantName of envVarsToTransform) {\n const frameworkEnvVarName = getFrameworkEnvVarName(\n constantName,\n projectInfo.framework\n )\n newArgText = newArgText.replace(\n new RegExp(constantName, \"g\"),\n frameworkEnvVarName\n )\n }\n\n if (newArgText !== argText) {\n const newCallExpr = `${expressionText}(${newArgText})`\n nodesToTransform.push({\n node: callExpr,\n newText: newCallExpr,\n })\n }\n }\n }\n }\n }\n\n // 3. Transform standalone process.env\n const propertyAccessExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertyAccessExpression\n )\n\n for (const propAccess of propertyAccessExpressions) {\n const propAccessText = propAccess.getText()\n\n if (propAccessText.match(/^process\\.env\\.[A-Z_]+$/)) {\n const parent = propAccess.getParent()\n if (parent?.getKind() === SyntaxKind.BinaryExpression) {\n continue\n }\n\n const match = propAccessText.match(/process\\.env\\.([A-Z_]+)/)\n if (match && match[1]) {\n const constantName = stripFrameworkPrefix(match[1])\n const frameworkName = projectInfo.framework.name\n\n let transformedEnvVar: string\n if (frameworkName === FRAMEWORKS.astro.name) {\n transformedEnvVar = `import.meta.env.PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n transformedEnvVar = `import.meta.env.VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n transformedEnvVar = `process.env.NEXT_PUBLIC_${constantName}`\n } else {\n transformedEnvVar = `process.env.${constantName}`\n }\n\n nodesToTransform.push({\n node: propAccess,\n newText: transformedEnvVar,\n })\n }\n }\n }\n\n // Apply all transformations\n for (const { node, newText } of nodesToTransform) {\n try {\n node.replaceWithText(newText)\n } catch (error) {\n console.warn(`Skipping transformation of node: ${error}`)\n }\n }\n}\n\n/**\n * Main transformer function that removes excluded components from TypeScript/React source files\n * This transformer processes various AST nodes to remove unwanted components based on exclusion rules\n */\nexport const transformRemoveComponents: Transformer = async ({\n sourceFile,\n config,\n}) => {\n // Use default exclusion rules (could be made configurable in the future)\n const exclusionRules: ComponentExclusionRule[] = DEFAULT_EXCLUSIONS\n const filePath = sourceFile.getFilePath()\n // Collect all nodes to be modified instead of modifying immediately\n const nodesToModify: NodeToRemove[] = []\n\n // STEP 1: Collect excluded component imports\n const importDeclarations = sourceFile.getImportDeclarations()\n\n for (const importDeclaration of importDeclarations) {\n const moduleSpecifier = importDeclaration.getModuleSpecifierValue()\n\n // Check if the entire import module should be removed\n if (\n exclusionRules.some((rule) =>\n shouldExcludeComponent(moduleSpecifier, [rule], filePath)\n )\n ) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n continue\n }\n\n // Handle default imports (import defaultName from \"...\")\n const defaultImport = importDeclaration.getDefaultImport()\n if (\n defaultImport &&\n shouldExcludeComponent(defaultImport.getText(), exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n continue\n }\n\n // Remove specific named imports that match exclusion rules\n const namedImports = importDeclaration.getNamedImports()\n const excludedImports = namedImports.filter((namedImport) =>\n shouldExcludeComponent(namedImport.getName(), exclusionRules, filePath)\n )\n\n if (excludedImports.length > 0) {\n excludedImports.forEach((excludedImport) =>\n nodesToModify.push({ node: excludedImport, action: \"remove\" })\n )\n\n // Check if this would remove all named imports\n const remainingImports = namedImports.filter(\n (namedImport) => !excludedImports.includes(namedImport)\n )\n\n if (remainingImports.length === 0 && !defaultImport) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n }\n }\n }\n\n // STEP 2: Collect excluded component exports\n const exportDeclarations = sourceFile.getExportDeclarations()\n\n for (const exportDeclaration of exportDeclarations) {\n const namedExports = exportDeclaration.getNamedExports()\n const excludedExports = namedExports.filter((namedExport) =>\n shouldExcludeComponent(namedExport.getName(), exclusionRules, filePath)\n )\n\n if (excludedExports.length > 0) {\n excludedExports.forEach((excludedExport) =>\n nodesToModify.push({ node: excludedExport, action: \"remove\" })\n )\n\n // Check if this would remove all named exports\n const remainingExports = namedExports.filter(\n (namedExport) => !excludedExports.includes(namedExport)\n )\n\n if (remainingExports.length === 0) {\n nodesToModify.push({ node: exportDeclaration, action: \"remove\" })\n }\n }\n }\n\n // STEP 3: Collect excluded component variable declarations\n const variableStatements = sourceFile.getVariableStatements()\n\n for (const variableStatement of variableStatements) {\n const declarations = variableStatement.getDeclarations()\n const excludedDeclarations = declarations.filter((declaration) =>\n shouldExcludeComponent(declaration.getName(), exclusionRules, filePath)\n )\n\n if (excludedDeclarations.length > 0) {\n if (declarations.length === excludedDeclarations.length) {\n // Remove entire variable statement if all declarations are excluded\n nodesToModify.push({ node: variableStatement, action: \"remove\" })\n } else {\n // Remove only excluded declarations, keep others\n excludedDeclarations.forEach((declaration) =>\n nodesToModify.push({ node: declaration, action: \"remove\" })\n )\n }\n }\n }\n\n // STEP 4: Collect excluded component function declarations\n const functionDeclarations = sourceFile.getFunctions()\n\n for (const functionDeclaration of functionDeclarations) {\n const functionName = functionDeclaration.getName()\n if (\n functionName &&\n shouldExcludeComponent(functionName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: functionDeclaration, action: \"remove\" })\n }\n }\n\n // STEP 5: Collect excluded component interface declarations\n const interfaceDeclarations = sourceFile.getInterfaces()\n\n for (const interfaceDeclaration of interfaceDeclarations) {\n const interfaceName = interfaceDeclaration.getName()\n if (shouldExcludeComponent(interfaceName, exclusionRules, filePath)) {\n nodesToModify.push({ node: interfaceDeclaration, action: \"remove\" })\n }\n }\n\n // STEP 6: Collect excluded component type aliases\n const typeAliases = sourceFile.getTypeAliases()\n\n for (const typeAlias of typeAliases) {\n const typeName = typeAlias.getName()\n if (shouldExcludeComponent(typeName, exclusionRules, filePath)) {\n nodesToModify.push({ node: typeAlias, action: \"remove\" })\n }\n }\n\n // STEP 6.5: Collect excluded interface property signatures\n const propertySignatures = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertySignature\n )\n\n for (const propertySignature of propertySignatures) {\n const propName = propertySignature.getName()\n if (\n propName &&\n shouldExcludeComponent(propName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: propertySignature, action: \"remove\" })\n }\n }\n\n // STEP 7: Collect excluded JSX elements from React components\n const jsxElements = sourceFile.getDescendantsOfKind(SyntaxKind.JsxElement)\n\n for (const jsxElement of jsxElements) {\n const tagName = jsxElement.getOpeningElement().getTagNameNode().getText()\n if (shouldExcludeComponent(tagName, exclusionRules, filePath)) {\n nodesToModify.push({\n node: jsxElement,\n action: \"replace\",\n newText: \"\",\n })\n }\n }\n\n // STEP 8: Collect excluded self-closing JSX elements\n const jsxSelfClosingElements = sourceFile.getDescendantsOfKind(\n SyntaxKind.JsxSelfClosingElement\n )\n\n for (const jsxSelfClosingElement of jsxSelfClosingElements) {\n const tagName = jsxSelfClosingElement.getTagNameNode().getText()\n if (shouldExcludeComponent(tagName, exclusionRules, filePath)) {\n nodesToModify.push({\n node: jsxSelfClosingElement,\n action: \"replace\",\n newText: \"\",\n })\n }\n }\n\n // STEP 9: Collect excluded component properties from objects\n const propertyAssignments = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertyAssignment\n )\n\n for (const propertyAssignment of propertyAssignments) {\n const propertyName = propertyAssignment.getName()\n if (\n propertyName &&\n shouldExcludeComponent(propertyName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: propertyAssignment, action: \"remove\" })\n }\n }\n\n // STEP 10: Collect excluded JSX attributes\n const jsxAttributes = sourceFile.getDescendantsOfKind(SyntaxKind.JsxAttribute)\n\n for (const jsxAttribute of jsxAttributes) {\n const attributeName = jsxAttribute.getNameNode().getText()\n if (\n attributeName &&\n shouldExcludeComponent(attributeName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: jsxAttribute, action: \"remove\" })\n }\n }\n\n // STEP 11: Collect excluded parameters from function/method signatures\n const parameters = sourceFile.getDescendantsOfKind(SyntaxKind.Parameter)\n\n for (const parameter of parameters) {\n const parameterName = parameter.getName()\n if (\n parameterName &&\n shouldExcludeComponent(parameterName, exclusionRules, filePath)\n ) {\n const paramList = parameter.getParent()\n\n // Only proceed if the parent is a function-like structure\n if (\n paramList &&\n (Node.isFunctionDeclaration(paramList) ||\n Node.isArrowFunction(paramList) ||\n Node.isFunctionExpression(paramList) ||\n Node.isMethodDeclaration(paramList))\n ) {\n const allParams = paramList.getParameters()\n const index = allParams.indexOf(parameter)\n\n // Handle comma removal for cleaner output\n if (index !== -1) {\n if (index === allParams.length - 1 && index > 0) {\n const prev = parameter.getPreviousSibling()\n if (prev?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prev, action: \"remove\" })\n }\n } else {\n const next = parameter.getNextSibling()\n if (next?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: next, action: \"remove\" })\n }\n }\n\n nodesToModify.push({ node: parameter, action: \"remove\" })\n }\n }\n }\n }\n\n // STEP 11.1: Handle function arguments in call expressions\n const callExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.CallExpression\n )\n\n for (const callExpr of callExpressions) {\n const args = callExpr.getArguments()\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n const argText = arg.getText()\n\n if (shouldExcludeComponent(argText, exclusionRules, filePath)) {\n // Handle comma removal for cleaner output\n if (i === args.length - 1) {\n // Last argument - remove preceding comma if exists\n const prevSibling = arg.getPreviousSibling()\n if (prevSibling && prevSibling.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prevSibling, action: \"remove\" })\n }\n } else {\n // Not last argument - remove following comma if exists\n const nextSibling = arg.getNextSibling()\n if (nextSibling && nextSibling.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: nextSibling, action: \"remove\" })\n }\n }\n\n nodesToModify.push({ node: arg, action: \"remove\" })\n }\n }\n }\n\n // STEP 11.5: Collect excluded binding elements (destructured parameters)\n const bindingElements = sourceFile.getDescendantsOfKind(\n SyntaxKind.BindingElement\n )\n\n for (const bindingElement of bindingElements) {\n const bindingName = bindingElement.getName()\n if (\n bindingName &&\n shouldExcludeComponent(bindingName, exclusionRules, filePath)\n ) {\n // Handle comma cleanup (already correct in your code)\n const bindingPattern = bindingElement.getParent()\n if (bindingPattern) {\n const allBindings = bindingPattern.getDescendantsOfKind(\n SyntaxKind.BindingElement\n )\n const bindingIndex = allBindings.indexOf(bindingElement)\n\n if (bindingIndex === allBindings.length - 1) {\n const prevSibling = bindingElement.getPreviousSibling()\n if (prevSibling?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prevSibling, action: \"remove\" })\n }\n } else {\n const nextSibling = bindingElement.getNextSibling()\n if (nextSibling?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: nextSibling, action: \"remove\" })\n }\n }\n }\n\n nodesToModify.push({ node: bindingElement, action: \"remove\" })\n }\n }\n\n // STEP 12: Collect excluded identifiers in function calls and expressions\n const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier)\n\n for (const identifier of identifiers) {\n const identifierName = identifier.getText()\n if (shouldExcludeComponent(identifierName, exclusionRules, filePath)) {\n const parent = identifier.getParent()\n\n // Handle different contexts where the identifier appears\n if (parent) {\n const parentKind = parent.getKind()\n\n // Remove entire call expression if it's calling an excluded function\n if (parentKind === SyntaxKind.CallExpression) {\n const callExpr = parent as CallExpression\n if (callExpr.getExpression() === identifier) {\n // This is a function call like getDocumentId()\n nodesToModify.push({ node: callExpr, action: \"remove\" })\n } else {\n // This is an argument in a function call\n const args = callExpr.getArguments()\n const argIndex = args.findIndex((arg) => arg === identifier)\n if (argIndex !== -1) {\n nodesToModify.push({ node: identifier, action: \"remove\" })\n }\n }\n }\n\n // Remove property access expressions with excluded identifiers\n if (parentKind === SyntaxKind.PropertyAccessExpression) {\n const propAccess = parent as PropertyAccessExpression\n if (propAccess.getName() === identifierName) {\n nodesToModify.push({ node: propAccess, action: \"remove\" })\n }\n }\n\n // Remove variable references and expressions\n if (\n parentKind === SyntaxKind.VariableDeclaration ||\n parentKind === SyntaxKind.BinaryExpression ||\n parentKind === SyntaxKind.IfStatement ||\n parentKind === SyntaxKind.ConditionalExpression\n ) {\n nodesToModify.push({ node: identifier, action: \"remove\" })\n }\n\n // Remove from object literal property values\n if (parentKind === SyntaxKind.PropertyAssignment) {\n const propAssignment = parent as PropertyAssignment\n if (propAssignment.getInitializer() === identifier) {\n nodesToModify.push({ node: propAssignment, action: \"remove\" })\n }\n }\n }\n }\n }\n\n // STEP 13: Collect excluded shorthand property assignments (e.g., { initialContent })\n const shorthandPropertyAssignments = sourceFile.getDescendantsOfKind(\n SyntaxKind.ShorthandPropertyAssignment\n )\n\n for (const shorthandProp of shorthandPropertyAssignments) {\n const propName = shorthandProp.getName()\n if (\n propName &&\n shouldExcludeComponent(propName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: shorthandProp, action: \"remove\" })\n }\n }\n\n // Apply environment variable transformations first (before removing nodes)\n await transformEnvironmentVariables(sourceFile, config)\n\n // STEP 16: Apply all collected modifications\n // Sort by position (deepest nodes first) to avoid accessing removed parents\n nodesToModify.sort((a, b) => {\n const aStart = a.node.getStart?.() ?? 0\n const bStart = b.node.getStart?.() ?? 0\n return bStart - aStart // Reverse order - process deepest/rightmost first\n })\n\n // Apply transformations safely\n for (const { node, action, newText } of nodesToModify) {\n try {\n // Check if node still exists and hasn't been removed\n if (node.wasForgotten?.() === true) {\n continue // Skip nodes that were already removed\n }\n\n if (action === \"remove\") {\n if (typeof node.remove === \"function\") {\n node.remove()\n }\n } else if (action === \"replace\" && newText !== undefined) {\n node.replaceWithText(newText)\n }\n } catch (error) {\n // console.warn(`Skipping transformation of node: ${error}`)\n // Continue with other transformations even if one fails\n }\n }\n\n // Return the modified source file with excluded components removed\n return sourceFile\n}\n","import * as sass from \"sass\"\n\n/**\n * Converts SCSS content to CSS\n * @param scssContent The SCSS content to convert\n * @returns The compiled CSS content\n */\nexport async function transformScssToCSS(scssContent: string): Promise<string> {\n try {\n const result = sass.compileString(scssContent, {\n style: \"expanded\",\n })\n return result.css\n } catch (error) {\n throw new Error(\n `Failed to compile SCSS to CSS: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n}\n","import { Config } from \"@/src/utils/get-config\"\nimport { getPackageInfo } from \"@/src/utils/get-package-info\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { RegistryItem } from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { execa } from \"execa\"\nimport { colors } from \"@/src/utils/colors\"\n\n/**\n * Installs development dependencies for a component\n *\n * @param devDependencies List of development dependencies to install\n * @param config Configuration object with project paths\n * @param options Additional options\n */\nexport async function updateDevDependencies(\n devDependencies: RegistryItem[\"devDependencies\"],\n config: Config,\n options: {\n silent?: boolean\n }\n) {\n devDependencies = Array.from(new Set(devDependencies))\n\n // Yarn Berry refuses `yarn add -D pkg` when pkg is already a regular\n // dependency, so drop anything the project already lists under\n // `dependencies` — it's already installed in a stricter bucket.\n const packageJson = getPackageInfo(config.resolvedPaths.cwd, false)\n const existingRegularDeps = new Set(\n Object.keys(packageJson?.dependencies ?? {})\n )\n devDependencies = devDependencies.filter(\n (dep) => !existingRegularDeps.has(dep)\n )\n\n if (!devDependencies?.length) {\n return\n }\n\n options = {\n silent: false,\n ...options,\n }\n\n const devDependenciesSpinner = spinner(\n `Installing development dependencies.`,\n {\n silent: options.silent,\n }\n )?.start()\n const packageManager = await getPackageManager(config.resolvedPaths.cwd)\n\n devDependenciesSpinner?.start()\n\n // Different package managers have different flags for dev dependencies\n const devFlag = packageManager === \"npm\" ? \"--save-dev\" : \"-D\"\n\n await execa(\n packageManager,\n [packageManager === \"npm\" ? \"install\" : \"add\", devFlag, ...devDependencies],\n {\n cwd: config.resolvedPaths.cwd,\n }\n )\n\n devDependenciesSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n}\n","/**\n * Converts kebab-case or snake_case to Title Case\n */\nexport function toReadableName(input: string): string {\n return input\n .split(/[-_]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \")\n}\n","import fetch from \"node-fetch\"\nimport { HttpsProxyAgent } from \"https-proxy-agent\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { colors } from \"@/src/utils/colors\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\nimport { saveAuthToken, type PackageManager } from \"./package-manager-config\"\nimport { REGISTRY_URL } from \"./registry\"\n\nconst AUTH_API_URL = `${REGISTRY_URL}/api/cli/v1`\n\ntype LoginResponse = {\n token: string\n authToken: string\n}\n\ntype PlanResponse = Array<{\n name: string\n}>\n\ntype AuthTokens = {\n bearerToken: string\n authToken: string\n}\n\nexport type AuthResult = {\n success: boolean\n tokens?: AuthTokens\n error?: string\n}\n\nexport type AuthStatus = {\n authenticated: boolean\n user?: string\n plans?: string[]\n expires?: string | null\n token?: string\n}\n\nconst httpAgent = process.env.https_proxy\n ? new HttpsProxyAgent(process.env.https_proxy)\n : undefined\n\nasync function getApiErrorMessage(response: {\n clone: () => { json: () => Promise<unknown> }\n}): Promise<string | null> {\n try {\n const payload = await response.clone().json()\n\n if (\n payload &&\n typeof payload === \"object\" &&\n \"error\" in payload &&\n typeof payload.error === \"string\"\n ) {\n return payload.error\n }\n\n if (\n payload &&\n typeof payload === \"object\" &&\n \"message\" in payload &&\n typeof payload.message === \"string\"\n ) {\n return payload.message\n }\n } catch {\n return null\n }\n\n return null\n}\n\nfunction getAuthErrorMessage(\n response: { status: number },\n apiErrorMessage?: string | null\n): string {\n switch (response.status) {\n case 400:\n return \"The authentication request was not accepted. Please check your email and password, then try again.\"\n case 401:\n return \"Invalid email or password. Please check your credentials and try again.\"\n case 403:\n return \"Your account is not allowed to use registry authentication. Please check your Tiptap Cloud account access.\"\n case 429:\n return \"Too many login attempts. Please wait a moment and try again.\"\n default:\n if (apiErrorMessage && response.status >= 500) {\n return apiErrorMessage\n }\n\n if (response.status >= 500) {\n return \"Tiptap authentication is temporarily unavailable. Please try again later.\"\n }\n\n return \"Authentication failed. Please try again.\"\n }\n}\n\nfunction getPlansErrorMessage(\n response: { status: number },\n apiErrorMessage?: string | null\n): string {\n switch (response.status) {\n case 401:\n case 403:\n return \"Your login succeeded, but your session could not be verified. Please run tiptap login again.\"\n case 429:\n return \"Your plans could not be loaded because there were too many requests. Please wait a moment and try again.\"\n default:\n if (apiErrorMessage && response.status >= 500) {\n return apiErrorMessage\n }\n\n if (response.status >= 500) {\n return \"Your plans could not be loaded because Tiptap Cloud is temporarily unavailable. Please try again later.\"\n }\n\n return \"Your plans could not be loaded. Please try again.\"\n }\n}\n\n/**\n * Authenticate a user with the Tiptap registry\n */\nexport async function authenticateUser({\n email,\n password,\n packageManager,\n writeConfig = true,\n cwd,\n}: {\n email?: string\n password?: string\n packageManager: PackageManager\n writeConfig?: boolean\n cwd: string\n}): Promise<AuthResult> {\n const loginSpinner = spinner(\n \"Authenticating with Tiptap registry...\"\n )?.start()\n\n try {\n if (!email || !password) {\n loginSpinner?.fail(\"Authentication failed\")\n return { success: false, error: \"Invalid credentials\" }\n }\n\n const tokens = await requestAuthTokens(email, password)\n\n let userPlans: string[] = []\n const plansResponse = await fetch(`${AUTH_API_URL}/plans`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${tokens.bearerToken}`,\n },\n agent: httpAgent,\n })\n\n if (!plansResponse.ok) {\n loginSpinner?.fail(\"Authentication failed (could not load user plans)\")\n const apiErrorMessage = await getApiErrorMessage(plansResponse)\n return {\n success: false,\n error: getPlansErrorMessage(plansResponse, apiErrorMessage),\n }\n }\n\n const plans = (await plansResponse.json()) as PlanResponse\n userPlans = plans.map((plan) => plan.name)\n\n if (!userPlans.length) {\n loginSpinner?.fail(\"Authentication failed (no active plans)\")\n return { success: false, error: \"No active plans found for user\" }\n }\n\n tokenStorage.setBearerToken(tokens.bearerToken, {\n email,\n plans: userPlans,\n })\n tokenStorage.setAuthToken(tokens.authToken)\n\n if (writeConfig) {\n const success = await saveAuthToken(tokens.authToken, packageManager, cwd)\n if (!success) {\n loginSpinner?.fail(\"Failed to save authentication token\")\n return { success: false, error: \"Could not save authentication token\" }\n }\n }\n\n loginSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \"Authentication successful\",\n })\n return { success: true, tokens }\n } catch (error) {\n loginSpinner?.fail(\"Authentication failed\")\n return {\n success: false,\n error:\n error instanceof Error\n ? error.message\n : \"Unknown error during authentication\",\n }\n }\n}\n\n/**\n * Request an authentication token from the API\n */\nasync function requestAuthTokens(\n email: string,\n password: string\n): Promise<AuthTokens> {\n const response = await fetch(`${AUTH_API_URL}/login`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, password }),\n agent: httpAgent,\n })\n\n if (!response.ok) {\n const apiErrorMessage = await getApiErrorMessage(response)\n throw new Error(getAuthErrorMessage(response, apiErrorMessage))\n }\n\n const data = (await response.json()) as LoginResponse\n\n return {\n bearerToken: data.token,\n authToken: data.authToken,\n }\n}\n\n/**\n * Check if user is authenticated with Tiptap registry\n */\nexport async function checkAuthStatus(): Promise<AuthStatus> {\n try {\n const bearerToken = tokenStorage.getBearerToken()\n\n if (!bearerToken) {\n return { authenticated: false }\n }\n\n if (!tokenStorage.isValidToken()) {\n return { authenticated: false }\n }\n\n // Use plans API to verify token is still valid\n let userPlans: string[] = []\n try {\n const plansResponse = await fetch(`${AUTH_API_URL}/plans`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${bearerToken}`,\n },\n agent: httpAgent,\n })\n\n if (!plansResponse.ok) {\n if (plansResponse.status === 401) {\n tokenStorage.clearSession()\n }\n return { authenticated: false }\n }\n\n const plans = (await plansResponse.json()) as PlanResponse\n userPlans = plans.map((plan) => plan.name)\n\n // Update stored plans\n const userInfo = tokenStorage.getUserInfo()\n tokenStorage.setBearerToken(bearerToken, {\n email: userInfo.email,\n plans: userPlans,\n })\n } catch (error) {\n return { authenticated: false }\n }\n\n const userInfo = tokenStorage.getUserInfo()\n const expiration = tokenStorage.getTokenExpiration()\n\n return {\n authenticated: true,\n user: userInfo.email || \"unknown user\",\n plans: userPlans,\n expires: expiration,\n token: bearerToken,\n }\n } catch (error) {\n logger.error(\n `Auth status check error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return { authenticated: false }\n }\n}\n\n/**\n * Logout user from Tiptap registry\n */\nexport async function logoutUser(): Promise<{\n success: boolean\n error?: string\n}> {\n try {\n const bearerToken = tokenStorage.getBearerToken()\n\n if (bearerToken) {\n const response = await fetch(`${AUTH_API_URL}/logout`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${bearerToken}`,\n },\n agent: httpAgent,\n })\n\n if (!response.ok) {\n logger.warn(\"Logout API call failed, but clearing local tokens anyway\")\n }\n }\n\n tokenStorage.clearSession()\n return { success: true }\n } catch (error) {\n tokenStorage.clearSession()\n return {\n success: false,\n error:\n error instanceof Error ? error.message : \"Unknown error during logout\",\n }\n }\n}\n\n/**\n * Check if user has a specific plan\n */\nexport function userHasPlan(planName: string): boolean {\n return tokenStorage.hasPlan(planName)\n}\n\n/**\n * Check if user has any of the specified plans\n */\nexport function userHasAnyPlan(planNames: string[]): boolean {\n return planNames.some((plan) => tokenStorage.hasPlan(plan))\n}\n\n/**\n * Get user's plans\n */\nexport function getUserPlans(): string[] {\n return tokenStorage.getUserInfo().plans || []\n}\n","import fs from \"fs-extra\"\nimport path from \"path\"\nimport os from \"os\"\nimport { execa } from \"execa\"\nimport { logger } from \"@/src/utils/logger\"\nimport yaml from \"yaml\"\n\nconst TIPTAP_REGISTRY = \"https://registry.tiptap.dev/\"\nconst AUTH_TOKEN_KEY = \"//registry.tiptap.dev/:_authToken\"\nconst TIPTAP_PRO_REGISTRY_KEY = \"@tiptap-pro:registry\"\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\"\n\n/**\n * Add .npmrc to .gitignore if it's not already there\n */\nasync function addNpmrcToGitignore(cwd: string): Promise<void> {\n try {\n const gitignorePath = path.join(cwd, \".gitignore\")\n const npmrcEntry = \".npmrc\"\n let gitignoreContent = \"\"\n\n if (await fs.pathExists(gitignorePath)) {\n gitignoreContent = await fs.readFile(gitignorePath, \"utf8\")\n }\n\n const lines = gitignoreContent.split(\"\\n\")\n const hasNpmrcEntry = lines.some(\n (line) =>\n line.trim() === npmrcEntry ||\n line.trim() === \"/.npmrc\" ||\n line.trim() === \"**/.npmrc\"\n )\n\n if (!hasNpmrcEntry) {\n const newContent = gitignoreContent.trim()\n ? `${gitignoreContent}\\n\\n# Authentication tokens\\n${npmrcEntry}\\n`\n : `# Authentication tokens\\n${npmrcEntry}\\n`\n\n await fs.writeFile(gitignorePath, newContent)\n }\n } catch (error) {\n logger.warn(\n `Could not update .gitignore: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n }\n}\n\n/**\n * Save authentication token to package manager config\n */\nexport async function saveAuthToken(\n token: string,\n packageManager: PackageManager,\n cwd: string\n): Promise<boolean> {\n try {\n let createdNpmrc = false\n\n switch (packageManager) {\n case \"npm\":\n await saveNpmToken(token, cwd)\n createdNpmrc = true\n break\n case \"yarn\":\n createdNpmrc = await saveYarnToken(token, cwd)\n break\n case \"pnpm\":\n case \"bun\":\n await saveToNpmrc(path.join(cwd, \".npmrc\"), token)\n createdNpmrc = true\n break\n }\n\n if (createdNpmrc) {\n await addNpmrcToGitignore(cwd)\n }\n\n return true\n } catch (error) {\n logger.error(\n `Error saving auth token: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return false\n }\n}\n\n/**\n * Save token for npm\n */\nasync function saveNpmToken(token: string, cwd: string): Promise<void> {\n await execa(\n \"npm\",\n [\n \"config\",\n \"set\",\n TIPTAP_PRO_REGISTRY_KEY,\n TIPTAP_REGISTRY,\n \"--location=project\",\n ],\n { cwd }\n )\n\n await execa(\n \"npm\",\n [\"config\", \"set\", AUTH_TOKEN_KEY, token, \"--location=project\"],\n { cwd }\n )\n}\n\n/**\n * Save token for yarn (handles v1 and v2+).\n *\n * Returns true when a project `.npmrc` was written (so the caller can decide\n * whether to gitignore it). Yarn Berry writes `.yarnrc.yml` instead, so it\n * returns false in that path.\n */\nasync function saveYarnToken(token: string, cwd: string): Promise<boolean> {\n try {\n const { stdout: yarnVersion } = await execa(\"yarn\", [\"--version\"], { cwd })\n const isYarnV1 = yarnVersion.startsWith(\"1.\")\n\n if (isYarnV1) {\n // Yarn classic silently ignores `--location=project` and writes to the\n // global `~/.yarnrc`, where it doesn't even consult that file for\n // npm-style scoped registry auth. Write the project `.npmrc` directly —\n // that's the file yarn 1 actually reads for `_authToken`.\n await saveToNpmrc(path.join(cwd, \".npmrc\"), token)\n return true\n }\n await saveYarnBerryToken(token, cwd)\n return false\n } catch (error) {\n // Fallback to .npmrc for yarn\n await saveToNpmrc(path.join(cwd, \".npmrc\"), token)\n return true\n }\n}\n\n/**\n * Save token for Yarn Berry (v2+)\n */\nasync function saveYarnBerryToken(token: string, cwd: string): Promise<void> {\n const yarnrcPath = path.join(cwd, \".yarnrc.yml\")\n let yamlObj: Record<string, unknown> = {}\n\n // Read existing config if it exists\n if (fs.existsSync(yarnrcPath)) {\n const yarnrcContent = await fs.readFile(yarnrcPath, \"utf8\")\n try {\n yamlObj = yaml.parse(yarnrcContent) || {}\n } catch (e) {\n // If parsing fails, start with empty object\n }\n }\n\n // Ensure the structure exists\n if (!yamlObj.npmScopes) {\n yamlObj.npmScopes = {}\n }\n\n // Set or update the tiptap-pro scope. `npmAlwaysAuth` ensures Berry sends\n // the token on GET requests too, not just PUTs — the Tiptap Pro registry\n // requires auth on package metadata fetches.\n const npmScopes = yamlObj.npmScopes as Record<string, unknown>\n npmScopes[\"tiptap-pro\"] = {\n npmRegistryServer: TIPTAP_REGISTRY,\n npmAuthToken: token,\n npmAlwaysAuth: true,\n }\n\n // Write back to file\n await fs.writeFile(yarnrcPath, yaml.stringify(yamlObj))\n}\n\n/**\n * Update .npmrc file with token\n */\nasync function saveToNpmrc(npmrcPath: string, token: string): Promise<void> {\n let npmrcContent = \"\"\n\n // Read existing file if it exists\n if (fs.existsSync(npmrcPath)) {\n npmrcContent = await fs.readFile(npmrcPath, \"utf8\")\n }\n\n // Parse .npmrc content\n const { lines, processedKeys } = parseNpmrc(npmrcContent, token)\n\n // Add missing keys\n if (!processedKeys.has(TIPTAP_PRO_REGISTRY_KEY)) {\n lines.push(`${TIPTAP_PRO_REGISTRY_KEY}=${TIPTAP_REGISTRY}`)\n }\n\n if (!processedKeys.has(AUTH_TOKEN_KEY)) {\n lines.push(`${AUTH_TOKEN_KEY}=${token}`)\n }\n\n // Ensure file ends with a newline\n if (lines.length > 0 && lines[lines.length - 1] !== \"\") {\n lines.push(\"\")\n }\n\n // Write the updated content back to the file\n await fs.writeFile(npmrcPath, lines.join(\"\\n\"))\n}\n\n/**\n * Parse .npmrc content\n */\nfunction parseNpmrc(\n npmrcContent: string,\n token: string\n): {\n lines: string[]\n processedKeys: Set<string>\n} {\n const lines: string[] = []\n const processedKeys = new Set<string>()\n\n // Split content into lines\n const contentLines = npmrcContent.split(\"\\n\")\n\n // Process each line\n for (const line of contentLines) {\n const trimmedLine = line.trim()\n\n // Skip empty lines or add them as-is\n if (!trimmedLine) {\n lines.push(line)\n continue\n }\n\n // Preserve comments\n if (trimmedLine.startsWith(\"#\")) {\n lines.push(line)\n continue\n }\n\n // Process key-value pairs\n const index = line.indexOf(\"=\")\n if (index !== -1) {\n const key = line.substring(0, index).trim()\n\n // Update specific keys\n if (key === TIPTAP_PRO_REGISTRY_KEY) {\n lines.push(`${TIPTAP_PRO_REGISTRY_KEY}=${TIPTAP_REGISTRY}`)\n processedKeys.add(key)\n } else if (key === AUTH_TOKEN_KEY) {\n lines.push(`${AUTH_TOKEN_KEY}=${token}`)\n processedKeys.add(key)\n } else {\n // Keep other keys unchanged\n lines.push(line)\n }\n } else {\n // Keep lines that aren't key-value pairs\n lines.push(line)\n }\n }\n\n return { lines, processedKeys }\n}\n\n/**\n * Get auth token from package manager config\n */\nexport async function getAuthToken(\n packageManager: PackageManager,\n cwd: string\n): Promise<string | null> {\n try {\n const projectToken = await checkProjectNpmrc(cwd)\n if (projectToken) {\n return projectToken\n }\n\n if (packageManager === \"npm\") {\n const npmAuthToken = await getNpmAuthToken(cwd)\n return npmAuthToken\n }\n\n const globalAuthToken = await checkGlobalNpmrc()\n if (globalAuthToken) {\n return globalAuthToken\n }\n\n // Older CLI versions wrote yarn 1 tokens into `~/.yarnrc` via\n // `yarn config set --location=project` (which Yarn classic silently\n // misroutes to the global file). Read it as a fallback so `status` and\n // auth checks don't lie when the legacy save path was used.\n if (packageManager === \"yarn\") {\n return await checkGlobalYarnrc()\n }\n\n return null\n } catch (error) {\n return null\n }\n}\n\n/**\n * Check project .npmrc for auth token\n */\nexport async function checkProjectNpmrc(cwd: string): Promise<string | null> {\n const projectNpmrcPath = path.join(cwd, \".npmrc\")\n if (fs.existsSync(projectNpmrcPath)) {\n const content = await fs.readFile(projectNpmrcPath, \"utf8\")\n return extractAuthToken(content)\n }\n return null\n}\n\n/**\n * Get npm auth token using npm config command\n */\nasync function getNpmAuthToken(cwd: string): Promise<string | null> {\n const { stdout } = await execa(\"npm\", [\"config\", \"get\", AUTH_TOKEN_KEY], {\n cwd,\n })\n\n return stdout && stdout !== \"undefined\" ? stdout.trim() : null\n}\n\n/**\n * Check global .npmrc file for auth token\n */\nasync function checkGlobalNpmrc(): Promise<string | null> {\n const globalNpmrcPath = path.join(os.homedir(), \".npmrc\")\n\n if (fs.existsSync(globalNpmrcPath)) {\n const content = await fs.readFile(globalNpmrcPath, \"utf8\")\n return extractAuthToken(content)\n }\n\n return null\n}\n\n/**\n * Check legacy Yarn classic `~/.yarnrc` for auth token. The file uses\n * `\"key\" value` lines (no `=`), so it isn't matched by `extractAuthToken`.\n */\nasync function checkGlobalYarnrc(): Promise<string | null> {\n const yarnrcPath = path.join(os.homedir(), \".yarnrc\")\n if (!fs.existsSync(yarnrcPath)) {\n return null\n }\n const content = await fs.readFile(yarnrcPath, \"utf8\")\n const match = content\n .split(\"\\n\")\n .map((line) =>\n line.match(/^\"\\/\\/registry\\.tiptap\\.dev\\/:_authToken\"\\s+\"?([^\"\\s]+)\"?/)\n )\n .find((m): m is RegExpMatchArray => m !== null)\n return match?.[1] ?? null\n}\n\n/**\n * Extract auth token from config string\n */\nexport function extractAuthToken(configString: string): string | null {\n // Split into lines and filter for registry.tiptap.dev\n const lines = configString\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"//registry.tiptap.dev/:_authToken=\"))\n\n if (lines.length === 0) {\n return null\n }\n\n // Extract the token after the \"=\" sign\n const token = lines[0].split(\"=\")[1]?.trim()\n return token || null\n}\n","import { Command } from \"commander\"\nimport { execa } from \"execa\"\nimport { z } from \"zod\"\nimport { confirm, input, password as passwordPrompt } from \"@inquirer/prompts\"\nimport { authenticateUser, checkAuthStatus } from \"@/src/utils/auth\"\nimport { colors } from \"@/src/utils/colors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { logoutUser } from \"@/src/utils/auth\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { getAuthToken } from \"@/src/utils/package-manager-config\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\nexport const authOptionsSchema = z.object({\n cwd: z.string(),\n email: z.string().optional(),\n password: z.string().optional(),\n writeConfig: z.boolean().optional(),\n showMessage: z.boolean().default(true),\n})\n\ntype AuthOptions = z.infer<typeof authOptionsSchema>\ntype PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\"\n\n/**\n * Creates a themed input prompt with consistent styling\n */\nconst createThemedInput = (\n message: string,\n options: {\n required?: boolean\n validate?: (value: string) => boolean | string\n } = {}\n) => {\n return input({\n message: colors.reset(message),\n required: options.required ?? true,\n validate:\n options.validate ??\n ((value: string) => (value ? true : \"This field is required\")),\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed password prompt with consistent styling\n */\nconst createThemedPassword = (\n message: string,\n options: {\n validate?: (value: string) => boolean | string\n } = {}\n) => {\n return passwordPrompt({\n message: colors.reset(message),\n validate:\n options.validate ??\n ((value: string) => (value ? true : \"This field is required\")),\n mask: \"*\",\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nexport const createThemedConfirm = (\n message: string,\n defaultValue: boolean = true\n) => {\n return confirm({\n message: colors.reset(message),\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Get the appropriate configuration file name based on package manager\n */\nfunction getConfigFileName(packageManager: PackageManager): string {\n switch (packageManager) {\n case \"npm\":\n return \".npmrc (via npm config)\"\n case \"yarn\":\n return \".yarnrc.yml or .npmrc (depending on Yarn version)\"\n case \"pnpm\":\n case \"bun\":\n return \".npmrc\"\n default:\n return \"configuration file\"\n }\n}\n\n/**\n * Display appropriate token configuration instructions for each package manager\n */\nasync function displayTokenInstructions(\n packageManager: PackageManager,\n token: string,\n cwd: string\n) {\n logger.log(\n `To use this token, add it to your project's package manager configuration in ${colors.cyan(cwd)}:`\n )\n\n if (packageManager === \"npm\") {\n logger.log(\"Run these commands in your project directory:\")\n logger.log(\n ` npm config set @tiptap-pro:registry https://registry.tiptap.dev/`\n )\n logger.log(` npm config set //registry.tiptap.dev/:_authToken ${token}`)\n logger.log(`\\nOr add to your project's .npmrc file:`)\n logger.log(` @tiptap-pro:registry=https://registry.tiptap.dev/`)\n logger.log(` //registry.tiptap.dev/:_authToken=${token}`)\n } else if (packageManager === \"yarn\") {\n const isYarnV1 = await checkYarnVersion(cwd)\n\n if (isYarnV1) {\n logger.log(\"Run these commands in your project directory:\")\n logger.log(\n ` yarn config set @tiptap-pro:registry https://registry.tiptap.dev/`\n )\n logger.log(` yarn config set //registry.tiptap.dev/:_authToken ${token}`)\n } else {\n logger.log(`Add to your project's .yarnrc.yml file:`)\n logger.log(\n `npmScopes:\\n tiptap-pro:\\n npmRegistryServer: \"https://registry.tiptap.dev/\"\\n npmAuthToken: \"${token}\"`\n )\n }\n } else if (packageManager === \"pnpm\" || packageManager === \"bun\") {\n logger.log(`Add to your project's .npmrc file:`)\n logger.log(\n colors.cyan(\n `@tiptap-pro:registry=https://registry.tiptap.dev/\\n//registry.tiptap.dev/:_authToken=${token}`\n )\n )\n }\n}\n\n/**\n * Check if the project is using Yarn v1\n */\nasync function checkYarnVersion(cwd: string): Promise<boolean> {\n try {\n const yarnVersionOutput = await execa(\"yarn\", [\"--version\"], { cwd })\n return yarnVersionOutput.stdout.startsWith(\"1.\")\n } catch (error) {\n // If yarn command fails, default to false\n return false\n }\n}\n\n/**\n * Handle the login process with interactive prompts if needed\n */\nexport async function handleLogin(options: AuthOptions) {\n let { email, password, writeConfig, showMessage } = options\n const { cwd } = options\n\n // Interactive prompts if necessary values aren't provided\n if (!email) {\n email = await createThemedInput(\"Email:\", {\n validate: (value: string) => (value ? true : \"Please enter your email\"),\n })\n }\n\n if (!password) {\n password = await createThemedPassword(\"Password:\", {\n validate: (value: string) =>\n value ? true : \"Please enter your password\",\n })\n }\n\n // User cancelled the prompt\n if (!email || !password) {\n logger.error(\"Authentication cancelled\")\n process.exit(0)\n }\n\n const packageManager = await getPackageManager(cwd)\n\n // Prompt for writeConfig if not explicitly set via command line\n if (writeConfig === undefined) {\n const configFileName = getConfigFileName(packageManager)\n\n writeConfig = await createThemedConfirm(\n `Would you like to save the auth token to your ${configFileName}?`\n )\n\n // User cancelled the prompt\n if (writeConfig === undefined) {\n logger.error(\"Authentication cancelled\")\n process.exit(0)\n }\n }\n\n const result = await authenticateUser({\n email,\n password,\n packageManager,\n writeConfig: writeConfig ?? false,\n cwd,\n })\n\n if (result.success && result.tokens) {\n if (writeConfig && showMessage) {\n logger.log(\n `\\nRegistry auth token saved to project directory for ${colors.cyan(packageManager)}`\n )\n logger.log(`.npmrc file saved at: ${colors.cyan(cwd)}`)\n logger.log(`Project path: ${colors.cyan(cwd)}`)\n } else if (result.tokens.authToken && showMessage) {\n logger.log(\n `\\nRegistry Auth Token: ${colors.cyan(result.tokens.authToken)}`\n )\n logger.log(\"This token should be added to your project's configuration:\")\n await displayTokenInstructions(\n packageManager,\n result.tokens.authToken,\n cwd\n )\n }\n\n if (showMessage) {\n logger.log(`Bearer token saved globally for CLI authentication`)\n }\n\n return true\n } else {\n logger.error(\"Authentication failed: \" + result.error)\n\n return false\n }\n}\n\n/**\n * Handle checking authentication status\n */\nasync function handleStatusCheck(cwd: string) {\n const packageManager = await getPackageManager(cwd)\n const status = await checkAuthStatus()\n\n if (status.authenticated) {\n logger.success(\n `Authenticated as ${colors.cyan(status.user ?? \"unknown user\")}`\n )\n\n // Display plans\n if (status.plans && status.plans.length > 0) {\n if (status.plans.length === 1) {\n logger.log(`Plan: ${colors.cyan(status.plans[0])}`)\n } else {\n logger.log(`Plans: ${colors.cyan(status.plans.join(\", \"))}`)\n }\n } else {\n logger.log(`Plans: ${colors.cyan(\"No active plans\")}`)\n }\n\n if (status.expires) {\n const expiryDate = new Date(status.expires)\n const now = new Date()\n const daysUntilExpiry = Math.ceil(\n (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)\n )\n\n if (daysUntilExpiry > 30) {\n logger.log(\n `Token expires: ${colors.cyan(expiryDate.toDateString())} (${daysUntilExpiry} days)`\n )\n } else if (daysUntilExpiry > 0) {\n logger.log(\n `Token expires: ${colors.yellow(expiryDate.toDateString())} (${daysUntilExpiry} days)`\n )\n } else {\n logger.log(`Token expires: ${colors.red(\"Expired\")}`)\n }\n }\n\n if (status.token) {\n const tokenPreview = status.token.substring(0, 10) + \"...\"\n logger.log(`Bearer token: ${colors.cyan(tokenPreview)}`)\n }\n\n const registryToken = await getAuthToken(packageManager, cwd)\n if (registryToken) {\n const registryPreview = registryToken.substring(0, 10) + \"...\"\n logger.log(`Registry token: ${colors.cyan(registryPreview)}`)\n } else {\n logger.log(\n `Registry token: ${colors.yellow(\"Not configured for this project\")}`\n )\n logger.log(\n `Run ${colors.cyan(\"@tiptap/cli login --write-config\")} to configure for this project`\n )\n }\n } else {\n logger.log(\"Not authenticated with Tiptap registry\")\n logger.log(`Run ${colors.cyan(`@tiptap/cli login`)} to authenticate`)\n }\n}\n\nexport const login = new Command()\n .command(\"login\")\n .description(\"log in to your Tiptap Cloud account\")\n .option(\"-e, --email <email>\", \"your account email\")\n .option(\"-p, --password <password>\", \"your account password\")\n .option(\n \"--write-config\",\n \"write the auth token to your package manager config\",\n undefined\n )\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .action(async (options) => {\n try {\n const opts = authOptionsSchema.parse(options)\n await handleLogin(opts)\n } catch (error) {\n handleError(error)\n }\n })\n\nexport const status = new Command()\n .command(\"status\")\n .description(\"review your Tiptap Cloud authentication status\")\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .action(async (options) => {\n const opts = authOptionsSchema.parse(options)\n const { cwd } = opts\n try {\n await handleStatusCheck(cwd)\n } catch (error) {\n handleError(error)\n }\n })\n\nexport const logout = new Command()\n .command(\"logout\")\n .description(\"log out from your Tiptap registry account\")\n\n .action(async () => {\n try {\n const logoutSpinner = spinner(\"Logging out...\")?.start()\n\n const result = await logoutUser()\n\n if (result.success) {\n logoutSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \"Successfully logged out\",\n })\n } else {\n logoutSpinner?.fail(\"Logout failed\")\n logger.error(\"Logout failed: \" + result.error)\n }\n } catch (error) {\n handleError(error)\n }\n })\n\n/**\n * Handle displaying license information\n */\nasync function handleLicenseInfo() {\n logger.log(\"\")\n logger.log(colors.yellow(\"📋 Tiptap Pro License Information\"))\n logger.log(\"\")\n\n // Check license acceptance status\n const hasAccepted = tokenStorage.hasAcceptedLicense()\n const userInfo = tokenStorage.getUserInfo()\n\n if (hasAccepted) {\n logger.log(`${colors.cyan(\"✔\")} Pro License and Terms of Service accepted`)\n if (userInfo.email) {\n logger.log(` Accepted by: ${colors.cyan(userInfo.email)}`)\n }\n logger.log(\"\")\n } else {\n logger.log(\n colors.yellow(\"⚠ Pro License and Terms of Service not yet accepted\")\n )\n logger.log(\" License acceptance is required for using paid components\")\n logger.log(\"\")\n }\n\n logger.log(\"License Details:\")\n logger.log(\n ` • Pro License: ${colors.cyan(\"https://tiptap.dev/pro-license\")}`\n )\n logger.log(\n ` • Terms of Service: ${colors.cyan(\"https://tiptap.dev/terms-of-service\")}`\n )\n logger.log(\"\")\n\n logger.log(\"About Paid Components:\")\n logger.log(\n \" Some paid UI components or templates are limited to specific plans.\"\n )\n logger.log(\n \" The license is valid during your trial period and active subscription.\"\n )\n logger.log(\"\")\n\n // Show hidden command hint only when using license command\n if (hasAccepted) {\n logger.log(colors.gray(\"Available commands:\"))\n logger.log(\n colors.gray(\n ` • ${colors.cyan(\"tiptap license forget me\")} - Reset license acceptance`\n )\n )\n logger.log(\"\")\n }\n}\n\n/**\n * Handle license forget me command\n */\nasync function handleLicenseForgetMe() {\n const hasAccepted = tokenStorage.hasAcceptedLicense()\n\n if (!hasAccepted) {\n logger.log(colors.yellow(\"⚠ License has not been accepted yet\"))\n return\n }\n\n const confirmed = await createThemedConfirm(\n \"Are you sure you want to reset your license acceptance?\",\n false\n )\n\n if (confirmed) {\n tokenStorage.clearLicenseAcceptance()\n logger.log(`${colors.cyan(\"✔\")} License acceptance has been reset`)\n logger.log(\n \" You will need to accept the license again when installing paid components\"\n )\n } else {\n logger.log(\"License acceptance reset cancelled\")\n }\n}\n\nexport const license = new Command()\n .command(\"license\")\n .description(\"display Tiptap Pro license information and acceptance status\")\n .action(async () => {\n try {\n await handleLicenseInfo()\n } catch (error) {\n handleError(error)\n }\n })\n .addCommand(\n new Command()\n .command(\"forget me\")\n .description(\"reset license acceptance status\")\n .action(async () => {\n try {\n await handleLicenseForgetMe()\n } catch (error) {\n handleError(error)\n }\n })\n )\n","import { checkAuthStatus } from \"@/src/utils/auth\"\nimport {\n saveAuthToken,\n type PackageManager,\n} from \"@/src/utils/package-manager-config\"\nimport { logger } from \"@/src/utils/logger\"\nimport { colors } from \"@/src/utils/colors\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { getPackageManager } from \"./get-package-manager\"\nimport { PAID_PLANS, PaidPlan, Plan } from \"./registry/schema\"\nimport { createThemedConfirm, handleLogin } from \"../commands/auth\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\n/**\n * Checks if the selected components contain any paid components\n */\nexport function hasPaidComponents(\n components: Array<{ name: string; plans: Plan[] }>\n): boolean {\n return components.some(\n (component) =>\n component.plans &&\n component.plans.some((plan) => PAID_PLANS.includes(plan as PaidPlan))\n )\n}\n\n/**\n * Prompts user to accept Pro license and Terms of Service for paid components\n */\nasync function promptLicenseAcceptance(\n selectedComponents: Array<{ name: string; plans: Plan[] }>\n): Promise<boolean> {\n const paidComponents = selectedComponents.filter(\n (component) =>\n component.plans &&\n component.plans.some((plan) => PAID_PLANS.includes(plan as PaidPlan))\n )\n\n if (paidComponents.length === 0) {\n return true\n }\n\n // Check if license was already accepted\n if (tokenStorage.hasAcceptedLicense()) {\n logger.log(`${colors.cyan(\"✔\")} Pro license accepted`)\n return true\n }\n\n logger.log(\"\")\n logger.log(colors.yellow(\"📋 License Agreement\"))\n logger.log(\"\")\n logger.log(\"Integrating paid components requires accepting:\")\n logger.log(\n ` • Pro License: ${colors.cyan(\"https://tiptap.dev/pro-license\")}`\n )\n logger.log(\n ` • Terms of Service: ${colors.cyan(\"https://tiptap.dev/terms-of-service\")}`\n )\n logger.log(\"\")\n logger.log(colors.gray(\" Valid during trial and active subscription\"))\n logger.log(\"\")\n\n try {\n const accepted = await createThemedConfirm(\n \"Do you accept the Pro license and terms of service?\",\n false\n )\n\n if (!accepted) {\n logger.log(colors.gray(\"License not accepted\"))\n logger.log(colors.gray(\"Tip: You can still install free components\"))\n return false\n }\n\n // Store license acceptance\n tokenStorage.setLicenseAccepted()\n logger.log(`${colors.cyan(\"✔\")} License accepted`)\n return true\n } catch (error) {\n logger.log(colors.gray(\"License acceptance cancelled\"))\n return false\n }\n}\n\n/**\n * Ensures user is authenticated for paid components and has proper .npmrc configuration.\n */\nexport async function ensureAuthForPaidComponents(\n selectedComponents: Array<{ name: string; plans: Plan[] }>,\n cwd: string\n): Promise<boolean> {\n try {\n if (!hasPaidComponents(selectedComponents)) {\n return true\n }\n\n const authStatus = await checkAuthStatus()\n\n if (!authStatus.authenticated) {\n logger.log(\"\")\n logger.log(colors.yellow(\"🔐 Authentication Required\"))\n logger.log(\"\")\n logger.log(\"Pro components require authentication.\")\n logger.log(\n `Run ${colors.cyan(\"tiptap login\")} or create an account at ${colors.cyan(\"https://cloud.tiptap.dev\")}`\n )\n logger.log(\"\")\n\n const shouldLoginNow = await createThemedConfirm(\n \"Would you like to login now?\",\n true\n )\n\n if (!shouldLoginNow) {\n logger.log(\"\")\n logger.log(colors.gray(\"Authentication cancelled\"))\n logger.log(colors.gray(\"Tip: You can still install free components\"))\n return false\n }\n\n const loginSuccess = await handleLogin({\n cwd,\n writeConfig: true,\n showMessage: false,\n })\n if (!loginSuccess) {\n return false\n }\n } else {\n // Always (re)write the project config from the in-memory token. The\n // registry rotates the npm `authToken` on each login, invalidating older\n // ones, so any token already written to a global `~/.npmrc` or to the\n // project may be stale. Trusting it leads to silent 403s during install.\n const packageManager = await getPackageManager(cwd)\n await createNpmrcConfiguration(packageManager, cwd)\n }\n\n // After authentication is complete, prompt for license acceptance\n const licenseAccepted = await promptLicenseAcceptance(selectedComponents)\n if (!licenseAccepted) {\n return false\n }\n\n return true\n } catch (error) {\n logger.error(\n `Authentication check failed: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return false\n }\n}\n\n/**\n * Creates .npmrc configuration for the project\n */\nasync function createNpmrcConfiguration(\n packageManager: PackageManager,\n cwd: string\n) {\n const configSpinner = spinner(\"Creating registry configuration...\")?.start()\n\n try {\n const authStatus = await checkAuthStatus()\n\n if (!authStatus.authenticated) {\n configSpinner?.fail(\n \"Cannot create configuration - user not authenticated\"\n )\n return false\n }\n\n const authToken = tokenStorage.getAuthToken()\n\n if (!authToken) {\n configSpinner?.fail(\"No authentication token found\")\n return false\n }\n\n const success = await saveAuthToken(authToken, packageManager, cwd)\n if (!success) {\n configSpinner?.fail(\"Failed to save authentication token\")\n return false\n }\n\n configSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \".npmrc created successfully\",\n })\n } catch (error) {\n configSpinner?.fail(\"Failed to create registry configuration\")\n logger.error(\n `Configuration error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n }\n}\n","import { colors } from \"@/src/utils/colors\"\nimport { logger } from \"@/src/utils/logger\"\nimport process from \"process\"\n\n/**\n * CLI UI utilities for consistent visual styling\n */\n\n/**\n * Get the current terminal width with a fallback\n */\nexport function getTerminalWidth(): number {\n return process.stdout.columns || 80\n}\n\n/**\n * Creates a bordered box with content\n */\nexport function createBox(\n title: string,\n content: string[],\n options?: {\n borderColor?: \"cyan\" | \"yellow\" | \"red\" | \"green\" | \"gray\"\n padding?: boolean\n }\n) {\n const borderColor = options?.borderColor || \"gray\"\n const padding = options?.padding !== false\n\n // Box drawing characters\n const topLeft = \"\"\n const topRight = \"\"\n const bottomLeft = \"\"\n const bottomRight = \"\"\n const horizontal = \"-\"\n const vertical = \"\"\n\n // Use terminal width with max constraint for readability\n const terminalWidth = getTerminalWidth()\n const boxWidth = Math.min(terminalWidth - 4, 80) // Max 80 chars for readability\n\n const colorFn = colors[borderColor]\n const topBorder = colorFn(\n topLeft + horizontal.repeat(boxWidth - 2) + topRight\n )\n const bottomBorder = colorFn(\n bottomLeft + horizontal.repeat(boxWidth - 2) + bottomRight\n )\n const sideBorder = colorFn(vertical)\n\n // Create the box\n const lines = []\n\n if (padding) lines.push(\"\")\n\n lines.push(topBorder)\n\n // Empty line before title\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n\n // Title line\n const titlePadding = Math.floor((boxWidth - 4 - stripAnsi(title).length) / 2)\n const titleLine = title\n .padStart(titlePadding + stripAnsi(title).length)\n .padEnd(boxWidth - 4)\n lines.push(`${sideBorder} ${titleLine} ${sideBorder}`)\n\n // Empty line after title\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n\n // Content lines\n content.forEach((line) => {\n const strippedLength = stripAnsi(line).length\n const padding = boxWidth - 4 - strippedLength\n const paddedLine = line + \" \".repeat(Math.max(0, padding))\n lines.push(`${sideBorder} ${paddedLine} ${sideBorder}`)\n })\n\n // Empty line before bottom border\n if (content.length > 0) {\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n }\n\n lines.push(bottomBorder)\n\n if (padding) lines.push(\"\")\n\n return lines\n}\n\n/**\n * Creates a section with title and content\n */\nexport function createSection(\n title: string,\n content: string[],\n subtitle?: string\n) {\n const lines = []\n\n lines.push(\"\")\n lines.push(title)\n\n if (subtitle) {\n lines.push(colors.gray(subtitle))\n }\n\n lines.push(\"\")\n\n content.forEach((line) => {\n lines.push(line)\n })\n\n return lines\n}\n\n/**\n * Creates a welcome banner\n */\nexport function createWelcomeBanner(title: string, subtitle?: string) {\n const content = subtitle ? [subtitle] : []\n return createBox(`${title}`, content, { borderColor: \"gray\" })\n}\n\n/**\n * Creates an info box\n */\nexport function createInfoBox(title: string, content: string[]) {\n return createBox(`ℹ️ ${title}`, content, { borderColor: \"cyan\" })\n}\n\n/**\n * Creates a warning box\n */\nexport function createWarningBox(title: string, content: string[]) {\n return createBox(`⚠️ ${title}`, content, { borderColor: \"yellow\" })\n}\n\n/**\n * Creates a success box\n */\nexport function createSuccessBox(title: string, content: string[]) {\n return createBox(`✅ ${title}`, content, { borderColor: \"green\" })\n}\n\n/**\n * Logs multiple lines with proper spacing\n */\nexport function logLines(lines: string[]) {\n lines.forEach((line) => logger.log(line))\n}\n\n/**\n * Strips ANSI color codes from a string to get actual length\n */\nfunction stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\")\n}\n\n/**\n * Creates a numbered list with proper spacing\n */\nexport function createNumberedList(\n items: Array<{ label: string; description?: string }>\n) {\n const lines: string[] = []\n\n items.forEach((item, index) => {\n const number = colors.gray(`${index + 1}.`)\n lines.push(` ${number} ${item.label}`)\n\n if (item.description) {\n lines.push(` ${colors.gray(item.description)}`)\n }\n\n // Add spacing between items except the last one\n if (index < items.length - 1) {\n lines.push(\"\")\n }\n })\n\n return lines\n}\n\n/**\n * Creates a preview box with code content\n */\nexport function createPreviewBox(title: string, content: string[]) {\n const lines = []\n\n lines.push(\"\")\n lines.push(title)\n lines.push(\"\")\n\n // Create bordered preview area with terminal width constraint\n const terminalWidth = getTerminalWidth()\n const maxLength = Math.max(...content.map((line) => stripAnsi(line).length))\n const boxWidth = Math.min(Math.max(50, maxLength + 4), terminalWidth - 4)\n\n const topBorder = \"┌\" + \"─\".repeat(boxWidth - 2) + \"┐\"\n const bottomBorder = \"└\" + \"─\".repeat(boxWidth - 2) + \"┘\"\n\n lines.push(topBorder)\n\n content.forEach((line, index) => {\n const lineNumber = colors.gray(`${index + 1}`)\n const paddedLine = line.padEnd(boxWidth - 6)\n lines.push(`│ ${lineNumber} ${paddedLine} │`)\n })\n\n lines.push(bottomBorder)\n lines.push(\"\")\n\n return lines\n}\n\n/**\n * Creates an explanation section with bullet points\n */\nexport function createExplanationSection(title: string, points: string[]) {\n const lines = []\n\n lines.push(\"\")\n lines.push(colors.cyan(title))\n lines.push(\"\")\n\n points.forEach((point) => {\n lines.push(` • ${point}`)\n })\n\n lines.push(\"\")\n\n return lines\n}\n\n/**\n * Clears the terminal screen\n */\nexport function clearTerminal() {\n // Clear screen and move cursor to top-left\n process.stdout.write(\"\\x1B[2J\\x1B[0f\")\n\n // Alternative method that works better on some terminals\n // console.clear()\n\n // For Windows compatibility\n if (process.platform === \"win32\") {\n process.stdout.write(\"\\x1B[2J\\x1B[3J\\x1B[H\")\n }\n}\n\n/**\n * Creates a subtle divider line that spans the terminal width\n */\nexport function createDivider() {\n const width = Math.min(getTerminalWidth() - 4, 80)\n return colors.gray(\"─\".repeat(width))\n}\n\n/**\n * Creates a dash divider for prompts\n */\nexport function createSpacedDivider() {\n const width = Math.min(getTerminalWidth() - 4, 80)\n return colors.gray(\"-\".repeat(width))\n}\n","import { colors } from \"@/src/utils/colors\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { createInfoBox, createWarningBox, logLines } from \"@/src/utils/cli-ui\"\nimport { logger } from \"@/src/utils/logger\"\nimport { existsSync } from \"fs\"\nimport path from \"path\"\nimport type { Config } from \"@/src/utils/get-config\"\n\n/**\n * Get the appropriate environment variable prefix for the framework\n */\nfunction getFrameworkEnvPrefix(framework: Framework): string {\n const frameworkName = framework.name\n\n if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n return \"NEXT_PUBLIC_\"\n } else if (frameworkName === FRAMEWORKS.astro.name) {\n return \"PUBLIC_\"\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n return \"VITE_\"\n } else if (\n frameworkName === FRAMEWORKS.laravel.name ||\n frameworkName === FRAMEWORKS.manual.name\n ) {\n return \"\"\n } else {\n return \"\"\n }\n}\n\n/**\n * Detect the actual file extension of style files in the project\n */\nfunction detectStyleFileExtension(config?: Config): string {\n if (!config?.resolvedPaths?.styles) {\n return \"scss\" // Default to scss if no config\n }\n\n const stylesDir = config.resolvedPaths.styles\n const variablesScss = path.join(stylesDir, \"_variables.scss\")\n const variablesCss = path.join(stylesDir, \"_variables.css\")\n\n // Check if CSS version exists (from Bun conversion)\n if (existsSync(variablesCss)) {\n return \"css\"\n }\n\n // Check if SCSS version exists\n if (existsSync(variablesScss)) {\n return \"scss\"\n }\n\n // Default to scss for new installations\n return \"scss\"\n}\n\n/**\n * Calculate the correct import path from main CSS file to styles directory\n */\nfunction calculateStylesImportPath(\n framework?: Framework,\n config?: Config\n): { cssFile: string; importPath: string } {\n const frameworkName = framework?.name || \"unknown\"\n\n // Check if styles are in src directory\n const stylesInSrc = config?.resolvedPaths?.styles?.includes(\"/src/\")\n const hasSrcDir = config?.resolvedPaths?.components?.includes(\"/src/\")\n\n // Determine the main CSS file location based on framework\n let cssFile = \"your main CSS file\"\n let importPath = \"./styles/\"\n\n switch (frameworkName) {\n case FRAMEWORKS[\"next-app\"].name:\n // Next.js App Router\n if (hasSrcDir) {\n // With srcDir: src/app/globals.css -> ../styles/\n cssFile = \"src/app/globals.css\"\n importPath = \"../styles/\"\n } else if (stylesInSrc) {\n // Without srcDir but styles in src: app/globals.css -> ../src/styles/\n cssFile = \"app/globals.css\"\n importPath = \"../src/styles/\"\n } else {\n // Without srcDir and styles at root: app/globals.css -> ../styles/\n cssFile = \"app/globals.css\"\n importPath = \"../styles/\"\n }\n break\n\n case FRAMEWORKS[\"next-pages\"].name:\n // Next.js Pages Router\n if (hasSrcDir) {\n // With srcDir: src/pages/_app.tsx imports from ../styles/globals.css\n cssFile = \"src/styles/globals.css\"\n importPath = \"./\"\n } else if (stylesInSrc) {\n // Without srcDir but styles in src: pages/_app.tsx imports from ../src/styles/\n cssFile = \"src/styles/globals.css\"\n importPath = \"./\"\n } else {\n // Without srcDir: styles/globals.css\n cssFile = \"styles/globals.css\"\n importPath = \"./\"\n }\n break\n\n case FRAMEWORKS.vite.name:\n // Vite - typically src/index.css or src/main.css\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS[\"react-router\"].name:\n // React Router - similar to Vite, uses src structure\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS[\"tanstack-start\"].name:\n // TanStack Start - Vite-based, uses src structure\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS.astro.name:\n // Astro - typically has styles imported in layout files\n if (stylesInSrc) {\n cssFile = \"src/layouts/Layout.astro\" // or src/pages/index.astro\n importPath = \"../styles/\"\n } else {\n cssFile = \"src/layouts/Layout.astro\"\n importPath = \"../../styles/\" // If styles at root\n }\n break\n\n case FRAMEWORKS.laravel.name:\n // Laravel - uses resources/css/app.css\n cssFile = \"resources/css/app.css\"\n // Laravel styles would be in resources/styles/\n importPath = \"../styles/\"\n break\n\n case FRAMEWORKS.manual.name:\n default:\n // Manual/Unknown - make best guess based on config\n if (hasSrcDir || stylesInSrc) {\n cssFile = \"src/index.css\"\n importPath = \"./styles/\"\n } else {\n cssFile = \"your main CSS file\"\n importPath = \"./styles/\"\n }\n break\n }\n\n return { cssFile, importPath }\n}\n\n/**\n * Show styles setup message to remind users to configure styles\n */\nexport function showStylesConfigurationMessage(\n framework?: Framework,\n config?: Config\n) {\n const fileExtension = detectStyleFileExtension(config)\n const { cssFile, importPath } = calculateStylesImportPath(framework, config)\n\n const content = [\n \"The editor requires these style imports:\",\n \"\",\n `Add to ${colors.cyan(cssFile)}:`,\n \"\",\n colors.yellow(` @import '${importPath}_variables.${fileExtension}';`),\n colors.yellow(\n ` @import '${importPath}_keyframe-animations.${fileExtension}';`\n ),\n \"\",\n \"Without these imports, the editor will not display correctly.\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/getting-started/style\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Import Styles\", content)\n logLines(box)\n}\n\n/**\n * Show package manager consistency warning\n */\nexport function showPackageManagerWarning(projectPackageManager: string) {\n const content = [\n `Your project uses ${colors.cyan(projectPackageManager)} as its package manager.`,\n \"\",\n \"For consistency, use the same package manager for all operations:\",\n `• Install dependencies: ${colors.yellow(`${projectPackageManager} install`)}`,\n `• Add packages: ${colors.yellow(`${projectPackageManager} add [package]`)}`,\n `• Run scripts: ${colors.yellow(`${projectPackageManager} run [script]`)}`,\n \"\",\n \"Mixing package managers (npm, pnpm, yarn) can cause conflicts.\",\n ]\n\n const box = createInfoBox(\"Package Manager Detected\", content)\n logLines(box)\n}\n\n/**\n * Show environment variables setup for Notion template (without styles)\n */\nexport function showNotionEnvSetupMessage(framework: Framework) {\n const prefix = getFrameworkEnvPrefix(framework)\n\n const content = [\n \"The Notion-like template requires environment variables for collaborative features:\",\n \"\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_DOC_PREFIX`) +\n \" - Document prefix (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_APP_ID`) +\n \" - Document Server App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_TOKEN`) +\n \" - JWT token for collaboration (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_APP_ID`) + \" - AI App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_TOKEN`) +\n \" - JWT token for AI (required)\",\n \"\",\n \"Get these credentials from your account at cloud.tiptap.dev\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Environment Setup\", content)\n logLines(box)\n}\n\n/**\n * Show combined Notion setup message with environment variables\n */\nexport function showNotionSetupMessage(framework: Framework) {\n const prefix = getFrameworkEnvPrefix(framework)\n\n const content = [\n \"The Notion template requires these environment variables:\",\n \"\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_DOC_PREFIX`) +\n \" - Document prefix (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_APP_ID`) +\n \" - Document Server App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_TOKEN`) +\n \" - JWT token for collaboration (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_APP_ID`) + \" - AI App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_TOKEN`) +\n \" - JWT token for AI (required)\",\n \"\",\n \"Get these credentials from your account at cloud.tiptap.dev\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Environment Setup\", content)\n logLines(box)\n}\n\n/**\n * Show combined Notion template setup message\n */\nexport function showNotionTemplateSetupMessage(\n framework: Framework,\n config?: Config\n) {\n const prefix = getFrameworkEnvPrefix(framework)\n const fileExtension = detectStyleFileExtension(config)\n const { cssFile, importPath } = calculateStylesImportPath(framework, config)\n\n const content = [\n \"The Notion-like template is a complete editor application that requires\",\n \"additional configuration before it can be used:\",\n \"\",\n colors.cyan(\"1. Import Required Styles\"),\n ` Add to ${colors.yellow(cssFile)}:`,\n colors.gray(` @import '${importPath}_variables.${fileExtension}';`),\n colors.gray(\n ` @import '${importPath}_keyframe-animations.${fileExtension}';`\n ),\n \"\",\n colors.cyan(\"2. Add Environment Variables (for collaborative features)\"),\n ` Add to your .env file:`,\n colors.gray(` ${prefix}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),\n colors.gray(` ${prefix}TIPTAP_COLLAB_APP_ID - Document Server App ID`),\n colors.gray(\n ` ${prefix}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`\n ),\n colors.gray(` ${prefix}TIPTAP_AI_APP_ID - AI App ID`),\n colors.gray(` ${prefix}TIPTAP_AI_TOKEN - JWT token for AI`),\n \"\",\n `Get credentials at ${colors.cyan(\"https://cloud.tiptap.dev\")}`,\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Next Steps: Configure your Editor\", content)\n logLines(box)\n}\n\n/**\n * Show Table Node integration guide\n */\nexport function showTableNodeSetupMessage() {\n logger.log(\"\")\n logger.log(colors.cyan(\"→ Table Node integration guide:\"))\n logger.log(\n ` ${colors.dim(\"https://tiptap.dev/docs/ui-components/node-components/table-node#usage\")}`\n )\n logger.log(\"\")\n}\n","import { existsSync, promises as fs } from \"fs\"\nimport path from \"path\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { logger } from \"@/src/utils/logger\"\nimport { colors } from \"@/src/utils/colors\"\n\n/**\n * Detect the actual file extension of style files in the project\n */\nfunction detectStyleFileExtension(config: Config): string {\n if (!config?.resolvedPaths?.styles) {\n return \"scss\"\n }\n\n const stylesDir = config.resolvedPaths.styles\n const variablesScss = path.join(stylesDir, \"_variables.scss\")\n const variablesCss = path.join(stylesDir, \"_variables.css\")\n\n // Check if CSS version exists (from Bun conversion)\n if (existsSync(variablesCss)) {\n return \"css\"\n }\n\n if (existsSync(variablesScss)) {\n return \"scss\"\n }\n\n return \"scss\"\n}\n\n/**\n * Get the main CSS file path based on framework\n */\nfunction getMainCssFilePath(\n framework: Framework,\n config: Config\n): string | null {\n const frameworkName = framework.name\n const cwd = config.resolvedPaths.cwd\n\n const hasSrcDir = config.resolvedPaths.components?.includes(\"/src/\")\n const stylesInSrc = config.resolvedPaths.styles?.includes(\"/src/\")\n\n let possiblePaths: string[] = []\n\n switch (frameworkName) {\n case FRAMEWORKS[\"next-app\"].name:\n if (hasSrcDir) {\n possiblePaths = [\n path.join(cwd, \"src/app/globals.css\"),\n path.join(cwd, \"src/app/globals.scss\"),\n ]\n } else {\n possiblePaths = [\n path.join(cwd, \"app/globals.css\"),\n path.join(cwd, \"app/globals.scss\"),\n ]\n }\n break\n\n case FRAMEWORKS[\"next-pages\"].name:\n if (hasSrcDir) {\n possiblePaths = [\n path.join(cwd, \"src/styles/globals.css\"),\n path.join(cwd, \"src/styles/globals.scss\"),\n ]\n } else {\n possiblePaths = [\n path.join(cwd, \"styles/globals.css\"),\n path.join(cwd, \"styles/globals.scss\"),\n ]\n }\n break\n\n case FRAMEWORKS.vite.name:\n case FRAMEWORKS[\"react-router\"].name:\n case FRAMEWORKS[\"tanstack-start\"].name:\n // Vite-based frameworks\n possiblePaths = [\n path.join(cwd, \"src/index.css\"),\n path.join(cwd, \"src/main.css\"),\n path.join(cwd, \"src/App.css\"),\n ]\n break\n\n case FRAMEWORKS.astro.name:\n possiblePaths = [\n path.join(cwd, \"src/styles/main.css\"),\n path.join(cwd, \"src/styles/global.css\"),\n ]\n break\n\n case FRAMEWORKS.laravel.name:\n possiblePaths = [path.join(cwd, \"resources/css/app.css\")]\n break\n\n case FRAMEWORKS.manual.name:\n default:\n // Try common locations\n if (hasSrcDir || stylesInSrc) {\n possiblePaths = [\n path.join(cwd, \"src/index.css\"),\n path.join(cwd, \"src/main.css\"),\n path.join(cwd, \"src/App.css\"),\n path.join(cwd, \"src/styles/main.css\"),\n ]\n } else {\n possiblePaths = [\n path.join(cwd, \"index.css\"),\n path.join(cwd, \"main.css\"),\n path.join(cwd, \"styles/main.css\"),\n ]\n }\n break\n }\n\n for (const filePath of possiblePaths) {\n if (existsSync(filePath)) {\n return filePath\n }\n }\n\n return possiblePaths[0] || null\n}\n\n/**\n * Calculate the relative import path from main CSS file to styles directory\n */\nfunction calculateImportPath(mainCssPath: string, stylesDir: string): string {\n const mainCssDir = path.dirname(mainCssPath)\n let relativePath = path.relative(mainCssDir, stylesDir)\n\n // Normalize to forward slashes for consistency\n relativePath = relativePath.replace(/\\\\/g, \"/\")\n\n // Ensure it starts with ./ or ../\n if (!relativePath.startsWith(\".\")) {\n relativePath = \"./\" + relativePath\n }\n\n // Add trailing slash\n if (!relativePath.endsWith(\"/\")) {\n relativePath += \"/\"\n }\n\n return relativePath\n}\n\n/**\n * Check if style imports already exist in the file\n */\nfunction hasStyleImports(content: string, fileExtension: string): boolean {\n const variablesImport = new RegExp(\n `@import\\\\s+['\"].*_variables\\\\.${fileExtension}['\"]`,\n \"i\"\n )\n const keyframesImport = new RegExp(\n `@import\\\\s+['\"].*_keyframe-animations\\\\.${fileExtension}['\"]`,\n \"i\"\n )\n\n return variablesImport.test(content) && keyframesImport.test(content)\n}\n\n/**\n * Automatically import style files into the main CSS file\n */\nexport async function autoImportStyles(\n result: {\n filesCreated: string[]\n filesUpdated?: string[]\n filesSkipped?: string[]\n },\n config: Config,\n framework: Framework\n): Promise<{ success: boolean; message: string; filePath?: string }> {\n try {\n // Check all file arrays for style files\n // This is because we don't want explicitly depend on filesCreated only\n // As users may have existing files that were updated or skipped\n const allFiles = [\n ...(result.filesCreated || []),\n ...(result.filesUpdated || []),\n ...(result.filesSkipped || []),\n ]\n\n const hasStyleFiles = allFiles.some(\n (file) =>\n file.includes(\"_variables.\") || file.includes(\"_keyframe-animations.\")\n )\n\n // Skip if no style files found in any of the arrays\n // I don't think there is a scenario where this would happen, but just in case\n if (!hasStyleFiles) {\n return {\n success: true,\n message: \"No style files to import\",\n }\n }\n\n // Detect file extension\n // Since the CLI recently added support for CSS output (from Bun conversion)\n const fileExtension = detectStyleFileExtension(config)\n const mainCssPath = getMainCssFilePath(framework, config)\n\n if (!mainCssPath) {\n return {\n success: false,\n message: \"Could not determine main CSS file location\",\n }\n }\n\n // Check if main CSS file exists\n if (!existsSync(mainCssPath)) {\n return {\n success: false,\n message: `Main CSS file not found at ${mainCssPath}`,\n }\n }\n\n const mainCssContent = await fs.readFile(mainCssPath, \"utf-8\")\n\n if (hasStyleImports(mainCssContent, fileExtension)) {\n return {\n success: true,\n message: \"Style imports already exist\",\n filePath: mainCssPath,\n }\n }\n\n const importPath = calculateImportPath(\n mainCssPath,\n config.resolvedPaths.styles\n )\n\n const imports = [\n `@import '${importPath}_variables.${fileExtension}';`,\n `@import '${importPath}_keyframe-animations.${fileExtension}';`,\n ].join(\"\\n\")\n\n const newContent = `${imports}\\n\\n${mainCssContent}`\n\n await fs.writeFile(mainCssPath, newContent, \"utf-8\")\n\n return {\n success: true,\n message: \"Style imports added\",\n filePath: mainCssPath,\n }\n } catch (error) {\n logger.error(\n `Failed to auto-import styles: ${error instanceof Error ? error.message : String(error)}`\n )\n return {\n success: false,\n message: `Failed to auto-import styles: ${error instanceof Error ? error.message : String(error)}`,\n }\n }\n}\n\n/**\n * Log the result of auto-importing styles\n */\nexport function logAutoImportResult(\n result: Awaited<ReturnType<typeof autoImportStyles>>\n): void {\n if (!result.success) {\n logger.warn(colors.yellow(`⚠ ${result.message}`))\n return\n }\n\n if (result.message === \"No style files to import\") {\n return\n }\n\n if (result.message === \"Style imports already exist\") {\n return\n }\n\n const relativePath = result.filePath\n ? path.relative(process.cwd(), result.filePath)\n : \"main CSS file\"\n\n // remove any ../ from relativePath for cleaner output\n const cleanedRelativePath = relativePath.replace(/\\.\\.\\//g, \"\")\n\n logger.log(\n `${colors.green(\"✔\")} Style imports automatically added to ${colors.cyan(cleanedRelativePath)}`\n )\n logger.log(\"\")\n}\n","import { getConfig } from \"@/src/utils/get-config\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport { Command } from \"commander\"\n\nexport const info = new Command()\n .name(\"info\")\n .description(\"get information about your project\")\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .action(async (opts) => {\n logger.info(\"> project info\")\n console.log(await getProjectInfo(opts.cwd))\n logger.break()\n\n try {\n const config = await getConfig(opts.cwd)\n logger.info(\"> config\")\n console.log(config)\n } catch {\n logger.info(\"\")\n }\n })\n","import path from \"path\"\nimport { Command } from \"commander\"\nimport { confirm, input } from \"@inquirer/prompts\"\nimport { z } from \"zod\"\n\nimport { preFlightInit } from \"@/src/preflights/preflight-init\"\nimport { promptForRegistryComponents } from \"@/src/commands/add\"\nimport { FRAMEWORKS, createProject } from \"@/src/utils/create-project\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { colors } from \"@/src/utils/colors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { addComponents } from \"@/src/utils/add-components\"\nimport {\n getProjectConfig,\n getProjectInfo,\n ProjectInfo,\n} from \"@/src/utils/get-project-info\"\nimport {\n DEFAULT_COMPONENTS,\n DEFAULT_CONTEXTS,\n DEFAULT_HOOKS,\n DEFAULT_TIPTAP_ICONS,\n DEFAULT_LIB,\n DEFAULT_STYLES,\n DEFAULT_TIPTAP_EXTENSIONS,\n DEFAULT_TIPTAP_NODES,\n DEFAULT_TIPTAP_UI,\n DEFAULT_TIPTAP_UI_PRIMITIVES,\n DEFAULT_TIPTAP_UI_UTILS,\n getConfig,\n rawConfigSchema,\n resolveConfigPaths,\n type Config,\n} from \"@/src/utils/get-config\"\nimport { getRegistryIndex } from \"../utils/registry\"\nimport { ensureAuthForPaidComponents } from \"../utils/auth-check\"\nimport { type Plan } from \"../utils/registry/schema\"\nimport {\n showNotionEnvSetupMessage,\n showNotionTemplateSetupMessage,\n showStylesConfigurationMessage,\n showTableNodeSetupMessage,\n} from \"@/src/utils/prompt-messages\"\nimport { Framework } from \"../utils/frameworks\"\nimport {\n createWelcomeBanner,\n logLines,\n createExplanationSection,\n clearTerminal,\n} from \"@/src/utils/cli-ui\"\nimport {\n autoImportStyles,\n logAutoImportResult,\n} from \"@/src/utils/auto-import-styles\"\n\nexport const initOptionsSchema = z.object({\n cwd: z.string(),\n components: z.array(z.string()).optional(),\n silent: z.boolean(),\n isNewProject: z.boolean(),\n srcDir: z.boolean().optional(),\n reactCompiler: z.boolean().optional(),\n framework: z\n .string()\n .optional()\n .refine((val) => !val || FRAMEWORKS[val as keyof typeof FRAMEWORKS], {\n message: \"Invalid framework. Please use 'next' or 'vite'.\",\n }),\n})\n\ntype InitOptions = z.infer<typeof initOptionsSchema> & {\n skipPreflight?: boolean\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nconst createThemedConfirm = (message: string, defaultValue: boolean = true) => {\n return confirm({\n message: colors.reset(message),\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Initialize the CLI command\n */\nexport const init = new Command()\n .name(\"init\")\n .description(\n \"initialize your project and install Tiptap UI components as source code\"\n )\n .argument(\"[components...]\", \"the components to add\")\n .option(\"-f, --framework <framework>\", \"the framework to use. (next, vite)\")\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project (specific to next).\",\n false\n )\n .option(\n \"--react-compiler\",\n \"enable React Compiler when creating a new project (specific to next).\",\n false\n )\n .action(async (components, opts) => {\n try {\n // Clear terminal for a fresh start\n clearTerminal()\n\n // Show welcome banner\n const welcomeBanner = createWelcomeBanner(\n \"Tiptap UI Components\",\n \"Install UI components or templates as editable source code in your project\"\n )\n logLines(welcomeBanner)\n\n // Explain what Tiptap CLI does\n const explanation = createExplanationSection(\n \"What are Tiptap UI Components?\",\n [\n \"React UI components that help you develop an editor\",\n \"They install as source code (not npm packages) in your src/components/\",\n \"UI components are a foundation for customization rather than a fixed library\",\n ]\n )\n logLines(explanation)\n\n // Wait for user to press Enter\n await input({\n message: colors.reset(\n `Press ${colors.cyan(\"Enter\")} to initialize a project...`\n ),\n theme: {\n prefix: {\n done: \"\",\n idle: \"\",\n },\n },\n })\n\n // Add visual separation\n logger.log(\"\")\n\n const options = initOptionsSchema.parse({\n cwd: path.resolve(opts.cwd),\n isNewProject: false,\n components,\n ...opts,\n })\n const result = await runInit(options)\n\n const totalFilesProcessed =\n (result?.filesCreated?.length || 0) +\n (result?.filesUpdated?.length || 0) +\n (result?.filesSkipped?.length || 0)\n\n // Show success message\n if (result && totalFilesProcessed > 0) {\n // Check all file arrays for template detection\n const allFiles = [\n ...(result.filesCreated || []),\n ...(result.filesUpdated || []),\n ...(result.filesSkipped || []),\n ]\n\n const containsNotion = allFiles.some((path) => path.includes(\"notion\"))\n const containsSimpleEditor = allFiles.some(\n (path) => path.includes(\"simple\") && path.includes(\"editor\")\n )\n\n if (containsNotion) {\n // Show single-line success message\n logger.log(\"\")\n if (result.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Notion template installed - ${result.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else {\n logger.log(\n `${colors.green(\"✔\")} Notion template already installed - ${result.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Show combined setup message for Notion template\n const framework = result.framework || result.projectInfo?.framework\n if (framework) {\n const autoImportResult = await autoImportStyles(\n {\n filesCreated: result.filesCreated,\n filesUpdated: result.filesUpdated,\n filesSkipped: result.filesSkipped,\n },\n result.config,\n framework as Framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showNotionTemplateSetupMessage(\n framework as Framework,\n result.config\n )\n } else {\n // Show only env setup since styles were auto-imported\n showNotionEnvSetupMessage(framework as Framework)\n }\n }\n } else if (containsSimpleEditor) {\n // Show single-line success message\n logger.log(\"\")\n if (result.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Simple editor template installed - ${result.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else {\n logger.log(\n `${colors.green(\"✔\")} Simple editor template already installed - ${result.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Show styles configuration as required\n const framework = result.framework || result.projectInfo?.framework\n if (framework) {\n const autoImportResult = await autoImportStyles(\n {\n filesCreated: result.filesCreated,\n filesUpdated: result.filesUpdated,\n filesSkipped: result.filesSkipped,\n },\n result.config,\n framework as Framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showStylesConfigurationMessage(\n framework as Framework,\n result.config\n )\n }\n }\n } else {\n // Show single-line success message\n logger.log(\"\")\n if (result.filesCreated.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Components installed - ${result.filesCreated.length} files added to ${colors.cyan(\"src/components/\")}`\n )\n } else if (result.filesSkipped.length > 0) {\n logger.log(\n `${colors.green(\"✔\")} Components already installed - ${result.filesSkipped.length} files skipped`\n )\n }\n logger.log(\"\")\n\n // Show styles configuration if components were added\n if (result?.projectInfo?.framework) {\n const autoImportResult = await autoImportStyles(\n {\n filesCreated: result.filesCreated,\n filesUpdated: result.filesUpdated,\n filesSkipped: result.filesSkipped,\n },\n result.config,\n result.projectInfo.framework\n )\n logAutoImportResult(autoImportResult)\n\n // Show manual instructions if auto-import failed\n if (!autoImportResult.success) {\n showStylesConfigurationMessage(\n result?.projectInfo?.framework,\n result.config\n )\n }\n }\n\n // Show Table Node integration guide if table-node was installed\n const containsTableNode =\n result.selectedComponents?.includes(\"table-node\")\n if (containsTableNode) {\n showTableNodeSetupMessage()\n }\n }\n }\n\n logger.break()\n } catch (error) {\n logger.break()\n handleError(error)\n }\n })\n\n/**\n * Main initialization function\n */\nexport async function runInit(options: InitOptions) {\n const { cwd, skipPreflight, components, silent } = options\n let updatedOptions = { ...options }\n let newProjectFramework: string | undefined\n\n // Standard return structure creator\n const createResult = (\n config: Config,\n projectInfo: ProjectInfo | null,\n selectedComponents: string[] = [],\n addResult?: {\n filesCreated: string[]\n filesUpdated: string[]\n filesSkipped: string[]\n }\n ) => ({\n config,\n projectInfo,\n framework: newProjectFramework,\n selectedComponents,\n filesCreated: addResult?.filesCreated || [],\n filesUpdated: addResult?.filesUpdated || [],\n filesSkipped: addResult?.filesSkipped || [],\n errors: [],\n })\n\n // Handle preflight checks and project creation\n let projectInfo\n if (!skipPreflight) {\n const preflight = await preFlightInit(options)\n const isMissingDirOrEmptyProject =\n preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]\n\n if (isMissingDirOrEmptyProject) {\n const { projectPath, framework } = await createProject(options)\n if (!projectPath) process.exit(0)\n\n updatedOptions = {\n ...updatedOptions,\n cwd: projectPath,\n isNewProject: true,\n }\n newProjectFramework = framework\n logger.log(\"\")\n }\n projectInfo = preflight.projectInfo\n } else {\n projectInfo = await getProjectInfo(cwd)\n }\n\n // Handle monorepo special case\n if (newProjectFramework === \"next-monorepo\") {\n const monorepoWebPath = path.resolve(updatedOptions.cwd, \"apps/web\")\n const config = await getConfig(monorepoWebPath)\n return createResult(config, projectInfo)\n }\n\n // Get configuration\n const projectConfig = await getProjectConfig(updatedOptions.cwd, projectInfo)\n const config = projectConfig\n ? await promptForMinimalConfig(projectConfig)\n : await promptForConfig(await getConfig(updatedOptions.cwd))\n\n logger.log(\"\")\n\n // Handle component selection\n let selectedComponents = components || []\n if (!selectedComponents.length) {\n const shouldAddComponents = await createThemedConfirm(\n \"Would you like to add a template or UI components to your project?\"\n )\n\n if (!shouldAddComponents) {\n const fullConfig = await resolveConfigPaths(updatedOptions.cwd, config)\n return createResult(fullConfig, projectInfo)\n }\n\n selectedComponents = await promptForRegistryComponents(\n { ...updatedOptions, overwrite: false },\n true // Show divider\n )\n\n if (!selectedComponents.length) {\n const fullConfig = await resolveConfigPaths(updatedOptions.cwd, config)\n return createResult(fullConfig, projectInfo)\n }\n }\n\n // Handle registry fetching and authentication for selected components\n let registryIndex\n try {\n registryIndex = await getRegistryIndex()\n if (!registryIndex) {\n throw new Error(\"Failed to fetch registry index.\")\n }\n } catch (error) {\n // Handle 401 auth error with retry\n if (\n error instanceof Error &&\n error.message.includes(\"You are not authorized\")\n ) {\n // Trigger auth flow with assumed paid components\n const assumedPaidComponents = selectedComponents.map((name) => ({\n name,\n plans: [\"start\" as Plan],\n }))\n\n const isAuthenticated = await ensureAuthForPaidComponents(\n assumedPaidComponents,\n updatedOptions.cwd\n )\n\n if (!isAuthenticated) {\n logger.error(\n \"Authentication failed. Cannot proceed with paid component download.\"\n )\n logger.log(\n \"You can try again with only free components, or authenticate first.\"\n )\n process.exit(1)\n }\n\n // Retry registry fetch after authentication\n registryIndex = await getRegistryIndex()\n if (!registryIndex) {\n throw new Error(\"Failed to fetch registry index after authentication.\")\n }\n } else {\n throw error\n }\n }\n\n // Map components to details and perform final authentication check\n const selectedComponentDetails = selectedComponents.map((componentName) => {\n const componentInfo = registryIndex.find(\n (item) => item.name === componentName\n )\n return {\n name: componentName,\n plans: componentInfo?.plans || [],\n }\n })\n\n const isAuthenticated = await ensureAuthForPaidComponents(\n selectedComponentDetails,\n updatedOptions.cwd\n )\n\n if (!isAuthenticated) {\n logger.error(\n \"Authentication failed. Cannot proceed with paid component download.\"\n )\n logger.log(\n \"You can try again with only free components, or authenticate first.\"\n )\n process.exit(1)\n }\n\n // Add components and return result\n const fullConfig = await resolveConfigPaths(updatedOptions.cwd, config)\n const addComponentsResult = await addComponents(\n selectedComponents,\n fullConfig,\n {\n overwrite: false,\n silent,\n isNewProject:\n updatedOptions.isNewProject ||\n projectInfo?.framework.name === \"next-app\",\n }\n )\n\n return createResult(\n fullConfig,\n projectInfo,\n selectedComponents,\n addComponentsResult || {\n filesCreated: [],\n filesUpdated: [],\n filesSkipped: [],\n }\n )\n}\n/**\n * Prompt for full configuration\n */\nasync function promptForConfig(defaultConfig: Config | null = null) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Project Configuration\"))\n logger.log(\"\")\n\n const tsx = await createThemedConfirm(\n `Would you like to use ${colors.cyan(\"TypeScript\")} (recommended)?`,\n defaultConfig?.tsx ?? true\n )\n\n const rsc = await createThemedConfirm(\n `Are you using ${colors.cyan(\"React Server Components\")}?`,\n defaultConfig?.rsc ?? true\n )\n\n return rawConfigSchema.parse({\n rsc,\n tsx,\n aliases: {\n components: DEFAULT_COMPONENTS,\n contexts: DEFAULT_CONTEXTS,\n hooks: DEFAULT_HOOKS,\n tiptapIcons: DEFAULT_TIPTAP_ICONS,\n lib: DEFAULT_LIB,\n tiptapExtensions: DEFAULT_TIPTAP_EXTENSIONS,\n tiptapNodes: DEFAULT_TIPTAP_NODES,\n tiptapUi: DEFAULT_TIPTAP_UI,\n tiptapUiPrimitives: DEFAULT_TIPTAP_UI_PRIMITIVES,\n tiptapUiUtils: DEFAULT_TIPTAP_UI_UTILS,\n styles: DEFAULT_STYLES,\n },\n })\n}\n\n/**\n * Prompt for minimal configuration from existing config\n */\nasync function promptForMinimalConfig(defaultConfig: Config) {\n return rawConfigSchema.parse({\n rsc: defaultConfig?.rsc,\n tsx: defaultConfig?.tsx,\n aliases: defaultConfig?.aliases,\n })\n}\n","import path from \"path\"\nimport { initOptionsSchema } from \"@/src/commands/init\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport fs from \"fs-extra\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport async function preFlightInit(\n options: z.infer<typeof initOptionsSchema>\n) {\n const errors: Record<string, boolean> = {}\n\n // Ensure target directory exists.\n // Check for empty project. We assume if no package.json exists, the project is empty.\n if (\n !fs.existsSync(options.cwd) ||\n !fs.existsSync(path.resolve(options.cwd, \"package.json\"))\n ) {\n errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true\n return {\n errors,\n projectInfo: null,\n }\n }\n\n const frameworkSpinner = spinner(`Verifying framework.`, {\n silent: options.silent,\n }).start()\n const projectInfo = await getProjectInfo(options.cwd)\n if (!projectInfo || projectInfo?.framework.name === \"manual\") {\n errors[ERRORS.UNSUPPORTED_FRAMEWORK] = true\n frameworkSpinner?.fail()\n logger.break()\n if (projectInfo?.framework.links.installation) {\n logger.error(\n `We could not detect a supported framework at ${colors.cyan(\n options.cwd\n )}.\\n` +\n `Visit ${colors.cyan(\n projectInfo?.framework.links.installation\n )} to manually configure your project.\\nOnce configured, you can use the cli to add components.`\n )\n }\n logger.break()\n process.exit(1)\n }\n frameworkSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: `Verifying framework. Found ${colors.cyan(projectInfo.framework.label)}.`,\n })\n\n const tsConfigSpinner = spinner(`Validating import alias.`, {\n silent: options.silent,\n }).start()\n if (!projectInfo?.aliasPrefix) {\n errors[ERRORS.IMPORT_ALIAS_MISSING] = true\n tsConfigSpinner?.fail()\n } else {\n tsConfigSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n }\n\n if (Object.keys(errors).length > 0) {\n if (errors[ERRORS.IMPORT_ALIAS_MISSING]) {\n logger.break()\n logger.error(`No import alias found in your tsconfig.json file.`)\n if (projectInfo?.framework.links.installation) {\n logger.error(\n `Visit ${colors.cyan(\n projectInfo?.framework.links.installation\n )} to learn how to set an import alias.`\n )\n }\n }\n\n logger.break()\n process.exit(1)\n }\n\n return {\n errors,\n projectInfo,\n }\n}\n","import os from \"os\"\nimport path from \"path\"\nimport fs from \"fs-extra\"\nimport { execa } from \"execa\"\nimport { z } from \"zod\"\nimport { parse as parseJsonc } from \"jsonc-parser\"\nimport { input } from \"@inquirer/prompts\"\n\nimport { initOptionsSchema } from \"@/src/commands/init\"\nimport select from \"@/src/inquirer/select\"\nimport { colors } from \"@/src/utils/colors\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\n\nconst MONOREPO_FRAMEWORK_URL =\n \"https://codeload.github.com/shadcn-ui/ui/tar.gz/main\"\n\nexport const FRAMEWORKS = {\n next: \"next\",\n vite: \"vite\",\n \"next-monorepo\": \"next-monorepo\",\n} as const\n\ntype Framework = keyof typeof FRAMEWORKS\ntype ProjectOptions = Pick<\n z.infer<typeof initOptionsSchema>,\n \"cwd\" | \"srcDir\" | \"components\" | \"framework\" | \"reactCompiler\"\n>\ntype CreateNextOptions = {\n version: string\n cwd: string\n packageManager: string\n srcDir: boolean\n reactCompiler: boolean\n}\ntype CreateViteOptions = {\n cwd: string\n packageManager: string\n projectName: string\n}\ntype CreateMonorepoOptions = {\n packageManager: string\n}\n\n/**\n * Creates a themed input prompt with consistent styling\n */\nconst createThemedInput = (message: string, defaultValue: string = \"\") => {\n return input({\n message: colors.reset(message),\n default: defaultValue,\n required: true,\n validate: (value: string) =>\n value.length > 128 ? `Name should be less than 128 characters.` : true,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed select prompt with consistent styling\n */\nconst createThemedSelect = async (\n message: string,\n choices: Array<{ name: string; value: string }>\n) => {\n const instructions = `\\n${colors.gray(\" Use arrow-keys ▲▼ / [Return] to submit\")}\\n`\n\n return select({\n message: colors.reset(message),\n instructions,\n theme: {\n icon: {\n cursor: colors.cyan(\"❯\"),\n },\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n choices,\n })\n}\n\n/**\n * Creates a new project based on the specified framework\n */\nexport async function createProject(options: ProjectOptions) {\n const normalizedOptions = {\n srcDir: false,\n reactCompiler: false,\n ...options,\n }\n\n let framework: Framework =\n normalizedOptions.framework &&\n FRAMEWORKS[normalizedOptions.framework as Framework]\n ? (normalizedOptions.framework as Framework)\n : \"next\"\n\n let projectName = \"my-app\"\n const nextVersion = \"latest\"\n\n // Only prompt for framework if not already specified\n if (!normalizedOptions.framework) {\n const frameworkPromptMessage = `The path ${colors.cyan(normalizedOptions.cwd)} does not contain a package.json file. Would you like to start a new project?`\n\n const selectedFramework = await createThemedSelect(frameworkPromptMessage, [\n { name: \"Next.js\", value: \"next\" },\n { name: \"Vite + React + TypeScript\", value: \"vite\" },\n // { name: 'Next.js (Monorepo)', value: 'next-monorepo' }\n ])\n\n framework = selectedFramework as Framework\n\n // Add spacing after framework selection\n logger.log(\"\")\n }\n\n // Prompt for project name\n projectName = await createThemedInput(\n \"What is your project named?\",\n projectName\n )\n\n // Get the package manager for the project\n const packageManager = await getPackageManager(normalizedOptions.cwd, {\n withFallback: true,\n })\n\n const projectPath = path.join(normalizedOptions.cwd, projectName)\n\n // Validate path is writable\n await validateProjectPath(normalizedOptions.cwd, projectName)\n\n // Create the project based on framework\n if (framework === FRAMEWORKS.next) {\n await createNextProject(projectPath, {\n version: nextVersion,\n cwd: normalizedOptions.cwd,\n packageManager,\n srcDir: !!normalizedOptions.srcDir,\n reactCompiler: !!normalizedOptions.reactCompiler,\n })\n } else if (framework === FRAMEWORKS.vite) {\n await createViteProject(projectPath, {\n cwd: normalizedOptions.cwd,\n packageManager,\n projectName,\n })\n } else if (framework === FRAMEWORKS[\"next-monorepo\"]) {\n await createMonorepoProject(projectPath, {\n packageManager,\n })\n }\n\n return {\n projectPath,\n projectName,\n framework,\n }\n}\n\n/**\n * Validates that the project path is writable and doesn't already exist\n */\nasync function validateProjectPath(cwd: string, projectName: string) {\n // Check if path is writable\n try {\n await fs.access(cwd, fs.constants.W_OK)\n } catch (error) {\n logger.break()\n logger.error(`The path ${colors.cyan(cwd)} is not writable.`)\n logger.error(\n `It is likely you do not have write permissions for this folder or the path ${colors.cyan(cwd)} does not exist.`\n )\n logger.break()\n process.exit(0)\n }\n\n // Check if project already exists\n if (fs.existsSync(path.resolve(cwd, projectName, \"package.json\"))) {\n logger.break()\n logger.error(\n `A project with the name ${colors.cyan(projectName)} already exists.`\n )\n logger.error(`Please choose a different name and try again.`)\n logger.break()\n process.exit(0)\n }\n}\n\n/**\n * Creates a new Next.js project\n */\nasync function createNextProject(\n projectPath: string,\n options: CreateNextOptions\n) {\n const createSpinner = spinner(\n \"Creating a new Next.js project. This may take a few minutes.\"\n ).start()\n\n // Note: pnpm fails here. Fallback to npx with --use-PACKAGE-MANAGER.\n const args = [\n \"--tailwind\",\n \"--eslint\",\n \"--typescript\",\n \"--app\",\n options.srcDir ? \"--src-dir\" : \"--no-src-dir\",\n \"--no-import-alias\",\n options.reactCompiler ? \"--react-compiler\" : \"--no-react-compiler\",\n `--use-${options.packageManager}`,\n ]\n\n // Add turbopack for Next.js 15+ or canary/latest\n if (\n options.version.startsWith(\"15\") ||\n options.version.startsWith(\"latest\") ||\n options.version.startsWith(\"canary\")\n ) {\n args.push(\"--turbopack\")\n }\n\n try {\n await execa(\n \"npx\",\n [`create-next-app@${options.version}`, projectPath, \"--silent\", ...args],\n { cwd: options.cwd }\n )\n\n await updateReadmeFile(projectPath)\n\n createSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Next.js project.\")\n logger.break()\n logger.error(\n `Something went wrong creating a new Next.js project. Please try again.`\n )\n process.exit(0)\n }\n}\n\n/**\n * Creates a new Vite + React + TypeScript project\n */\nasync function createViteProject(\n projectPath: string,\n options: CreateViteOptions\n) {\n const createSpinner = spinner(\n `Creating a new Vite + React + TypeScript project. This may take a few minutes.`\n ).start()\n\n try {\n await execa(\n \"npm\",\n [\n \"create\",\n \"vite@latest\",\n options.projectName,\n \"--\",\n \"--template\",\n \"react-ts\",\n ],\n { cwd: options.cwd }\n )\n\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n })\n\n await setupViteTsConfig(projectPath, options.packageManager)\n\n await updateReadmeFile(projectPath)\n\n createSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Vite project.\")\n handleError(error)\n }\n}\n\n/**\n * Configures TypeScript and path aliases for a Vite project\n */\nasync function setupViteTsConfig(projectPath: string, packageManager: string) {\n try {\n await setupTsConfigPathAliases(projectPath)\n await setupViteConfigPathAliases(projectPath)\n await installTypesNode(projectPath, packageManager)\n } catch (error) {\n logger.warn(\n \"Failed to set up TypeScript path aliases, but project creation succeeded\"\n )\n }\n}\n\n/**\n * Installs @types/node as a development dependency\n */\nasync function installTypesNode(projectPath: string, packageManager: string) {\n try {\n const devFlag = packageManager === \"npm\" ? \"--save-dev\" : \"-D\"\n\n await execa(\n packageManager,\n [packageManager === \"npm\" ? \"install\" : \"add\", devFlag, \"@types/node\"],\n { cwd: projectPath }\n )\n } catch (error) {\n logger.warn(\"Failed to install @types/node, but project creation succeeded\")\n }\n}\n\n/**\n * Sets up TypeScript configuration files with path aliases\n */\nasync function setupTsConfigPathAliases(projectPath: string) {\n const addAliasToTsConfig = async (tsconfigFile: string) => {\n const tsconfigPath = path.join(projectPath, tsconfigFile)\n if (!(await fs.pathExists(tsconfigPath))) return\n\n const jsonContent = await fs.readFile(tsconfigPath, \"utf-8\")\n const jsonObj = parseJsonc(jsonContent)\n\n jsonObj.compilerOptions = {\n ...jsonObj.compilerOptions,\n baseUrl: \".\",\n paths: {\n ...(jsonObj.compilerOptions?.paths || {}),\n \"@/*\": [\"./src/*\"],\n },\n }\n\n const updatedJson = JSON.stringify(jsonObj, null, 2)\n await fs.writeFile(tsconfigPath, updatedJson)\n }\n\n await addAliasToTsConfig(\"tsconfig.json\")\n await addAliasToTsConfig(\"tsconfig.app.json\")\n}\n\n/**\n * Sets up Vite configuration with path aliases\n */\nasync function setupViteConfigPathAliases(projectPath: string) {\n const viteConfigPath = path.join(projectPath, \"vite.config.ts\")\n const viteConfigContent = await fs.readFile(viteConfigPath, \"utf-8\")\n\n const updatedViteConfig = viteConfigContent\n .replace(\n \"import { defineConfig } from 'vite'\",\n \"import { defineConfig } from 'vite'\\nimport path from 'path'\"\n )\n .replace(\n \"plugins: [react()]\",\n `plugins: [react()],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, './src')\n }\n }`\n )\n\n await fs.writeFile(viteConfigPath, updatedViteConfig)\n}\n\n/**\n * Creates a new Next.js monorepo project\n */\nasync function createMonorepoProject(\n projectPath: string,\n options: CreateMonorepoOptions\n) {\n const createSpinner = spinner(\n `Creating a new Next.js monorepo. This may take a few minutes.`\n ).start()\n\n try {\n await downloadAndExtractFramework(projectPath)\n\n // Run install\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n })\n\n // Initialize git repository\n await initializeGitRepository(projectPath)\n\n createSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: `Created a new Next.js monorepo at ${colors.cyan(projectPath)}`,\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Next.js monorepo.\")\n handleError(error)\n }\n}\n\n/**\n * Downloads and extracts the monorepo framework\n */\nasync function downloadAndExtractFramework(projectPath: string) {\n // Create temporary directory\n const frameworkPath = path.join(os.tmpdir(), `tiptap-framework-${Date.now()}`)\n await fs.ensureDir(frameworkPath)\n\n // Download framework\n const response = await fetch(MONOREPO_FRAMEWORK_URL)\n if (!response.ok) {\n throw new Error(\n \"The starter project could not be downloaded. Please check your connection and try again.\"\n )\n }\n\n // Write the tar file\n const tarPath = path.resolve(frameworkPath, \"framework.tar.gz\")\n await fs.writeFile(tarPath, Buffer.from(await response.arrayBuffer()))\n\n // Extract framework\n await execa(\"tar\", [\n \"-xzf\",\n tarPath,\n \"-C\",\n frameworkPath,\n \"--strip-components=2\",\n \"ui-main/templates/monorepo-next\",\n ])\n\n // Move to project path and cleanup\n const extractedPath = path.resolve(frameworkPath, \"monorepo-next\")\n await fs.move(extractedPath, projectPath)\n await fs.remove(frameworkPath)\n}\n\n/**\n * Initializes a git repository in the project directory\n */\nasync function initializeGitRepository(projectPath: string) {\n const cwd = process.cwd()\n\n try {\n await execa(\"git\", [\"--version\"], { cwd: projectPath })\n await execa(\"git\", [\"init\"], { cwd: projectPath })\n await execa(\"git\", [\"add\", \"-A\"], { cwd: projectPath })\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit\"], {\n cwd: projectPath,\n })\n await execa(\"cd\", [cwd])\n } catch (error) {\n logger.warn(\n \"Failed to initialize git repository, but project creation succeeded\"\n )\n }\n}\n\nconst simpleEditorTemplateDocs = `# Simple template\n\nIntegrate the Tiptap open source editor with UI components and open source extensions.\n\nThe Simple Editor Template is a fully working setup for the Tiptap editor. It includes commonly used open source extensions and UI components, all MIT licensed and ready to customize.\n\n**Quick Links:**\n- [View in Full Screen](http://template.tiptap.dev/preview/templates/simple)\n- [GitHub Repository](https://github.com/ueberdosis/tiptap-ui-components/tree/main/apps/web/src/components/tiptap-templates/simple)\n\n## Installation\n\nAdd the Simple Editor Template to your project using the Tiptap CLI:\n\n\\`\\`\\`bash\nnpx @tiptap/cli add simple-editor\n\\`\\`\\`\n\n## Style\n\n> **Missing styles?** If you haven't added the styles yet, make sure to [follow the style setup guide](/ui-components/getting-started/style) to ensure your editor and components render correctly.\n\n## Usage\n\nAfter installation, use the SimpleEditor component in your React or Next.js project:\n\n\\`\\`\\`jsx\nimport { SimpleEditor } from '@/components/tiptap-templates/simple/simple-editor'\n\nexport default function App() {\n return <SimpleEditor />\n}\n\\`\\`\\`\n\n## Features\n\nA fully responsive rich text editor with built-in support for common formatting and layout tools. All components are open source and easy to extend.\n\n- **Responsive design**: Mobile-friendly by default\n- **Dark and light mode**: Supported out-of-the-box\n- **Formatting**: Bold, Italic, Underline\n- **Lists**: Bullet, Ordered, Checkboxes\n- **Text alignment**: Left, Center, Right, Justified\n- **Headings**: Multiple levels via dropdown\n- **Image upload**\n- **Link editing:** UI for adding and editing links\n- **Undo / Redo:** History management\n\n### Used reference components\n\n#### Hooks\n\n- \\`use-mobile\\`\n- \\`use-window-size\\`\n\n#### Icons\n\n- \\`arrow-left-icon\\`\n- \\`highlighter-icon\\`\n- \\`link-icon\\`\n- \\`moon-star-icon\\`\n- \\`sun-icon\\`\n\n#### Extensions\n\n- \\`selection-extension\\`\n- \\`link-extension\\`\n- \\`trailing-node-extension\\`\n\n#### Lib\n\n- \\`tiptap-utils\\`\n\n#### UI Components\n\n- \\`blockquote-button\\`\n- \\`code-block-button\\`\n- \\`color-highlight-button\\`\n- \\`color-highlight-popover\\`\n- \\`heading-button\\`\n- \\`heading-dropdown-menu\\`\n- \\`image-upload-button\\`\n- \\`link-popover\\`\n- \\`list-button\\`\n- \\`list-dropdown-menu\\`\n- \\`mark-button\\`\n- \\`text-align-button\\`\n- \\`undo-redo-button\\`\n\n#### Node Components\n\n- \\`code-block-node\\`\n- \\`image-node\\`\n- \\`image-upload-node\\`\n- \\`list-node\\`\n- \\`paragraph-node\\`\n\n#### Primitives\n\n- \\`button\\`\n- \\`spacer\\`\n- \\`toolbar\\`\n\n## License\n\nThe Simple Editor Template and all included components are MIT licensed. You're free to use, modify, and extend the code as needed.\n\n## Future compatibility\n\nYou can extend this template with additional features as your needs grow.\n\nPaid Tiptap Cloud features will have matching UI components that integrate just as easily! No rework needed.`\n\nconst notionLikeEditorDocs = `# Notion-like Editor\n\nA Notion-style Tiptap editor with collaboration, AI, and rich UI components. Fully customizable and easy to integrate.\n\nThe **Notion-like Editor Template** is a fully featured block-based editor that replicates the familiar Notion experience. It supports collaboration, AI assistance, emoji, drag & drop, advanced formatting—and it's fully customizable.\n\n## Installation\n\nInstall the Notion-like editor with the Tiptap CLI:\n\n\\`\\`\\`bash\nnpx @tiptap/cli add notion-like-editor\n\\`\\`\\`\n\n## Styling\n\n> **Note:** If the editor doesn't look right, make sure you've followed the [style setup guide](/ui-components/getting-started/style).\n\n## Configuration\n\nBefore running the app, configure the required constants inside \\`tiptap-collab-utils.ts\\`. This is necessary to enable features like AI or collaboration.\n\n### Environment Variables\n\nProvide values for the following environment variables:\n\n- \\`TIPTAP_COLLAB_DOC_PREFIX\\` - Prefix for identifying collaborative documents\n- \\`TIPTAP_COLLAB_APP_ID\\` - Your Document Server App ID\n- \\`TIPTAP_COLLAB_TOKEN\\` - JWT token for accessing Collaboration services\n- \\`TIPTAP_AI_APP_ID\\` - Your AI App ID\n- \\`TIPTAP_AI_TOKEN\\` - JWT token for accessing AI services\n\nThe above environment variables should be available in the client-side. Depending on your framework, use the following prefixes to expose them to the client:\n\n- **[Next.js](/ui-components/install/next)**: \\`NEXT_PUBLIC_\\`. For example, \\`NEXT_PUBLIC_TIPTAP_COLLAB_DOC_PREFIX\\`.\n- **[Vite + React](/ui-components/install/vite)**: \\`VITE_\\`. For example, \\`VITE_TIPTAP_COLLAB_DOC_PREFIX\\`.\n- **Other frameworks**: Follow the specific rules of your framework, and define the variables in the \\`tiptap-collab-utils.ts\\` file.\n\n### JWT Authentication\n\nCollaboration and AI features require a valid server-generated JWT token passed to the editor. See the \\`fetchCollabToken\\` function in \\`tiptap-collab-utils.ts\\` for an example.\n\n> See the full guide on JWT authentication at [https://tiptap.dev/docs/guides/authentication](https://tiptap.dev/docs/guides/authentication).\n\n> **Important:** To get started quickly, you can use the example JWT tokens from your Tiptap Cloud account and store them in the \\`TIPTAP_COLLAB_TOKEN\\` and \\`TIPTAP_AI_TOKEN\\` environment variables. However, example JWT tokens are valid for a short time and should not be used in production. In production, implement an API endpoint that generates JWTs on the server side.\n\n### \\`room\\` prop\n\nUse the \\`room\\` prop to distinguish collaborative documents. Each session should use a unique room ID.\n\n## Usage\n\nImport and render the \\`NotionEditor\\` component in your React app:\n\n\\`\\`\\`tsx\nimport { NotionEditor } from '@/components/tiptap-templates/notion/notion-like-editor'\n\nexport default function App() {\n return <NotionEditor room=\"my-document-room\" placeholder=\"Start writing...\" />\n}\n\\`\\`\\`\n\n## Features\n\nThe template includes all the essentials of a modern Notion-style editor:\n\n- **Real-time collaboration**: Live cursors and user presence\n- **AI assistance**: Inline AI tools for writing and editing\n- **Responsive design**: Mobile-ready UI with adaptive toolbars\n- **Dark/light mode**: Fully themed out of the box\n- **Slash commands**: \\`/\\` menu for quick formatting\n- **Floating toolbar**: Context-aware formatting\n- **Drag and drop**: Block-level reordering\n- **Emoji support**: GitHub-style emoji picker\n- **Mentions**: \\`@user\\` autocomplete\n- **Rich formatting**:\n - Bold, italic, underline, strikethrough\n - Highlight and color\n - Superscript / subscript\n - Syntax-highlighted code blocks\n- **Block types**:\n - Headings, lists, blockquotes, dividers, math\n- **Media support**: Drag & drop image upload\n- **Link management**: With inline previews\n- **Text alignment**: Left, center, right, justified\n- **Undo/Redo**: Full editing history\n- **Context menus**: Right-click enhancements\n\n## Component Breakdown\n\n### Hooks\n\n- \\`use-mobile\\`\n- \\`use-window-size\\`\n- \\`use-ui-editor-state\\`\n\n### Icons\n\n- \\`arrow-left-icon\\`\n- \\`chevron-right-icon\\`\n- \\`highlighter-icon\\`\n- \\`link-icon\\`\n- \\`more-vertical-icon\\`\n\n### Tiptap Extensions\n\n- \\`collaboration\\`, \\`collaboration-cursor\\`\n- \\`selection-extension\\`\n- \\`link-extension\\`\n- \\`trailing-node-extension\\`\n- \\`ai-extension\\`\n- \\`emoji-extension\\`\n- \\`mention-extension\\`\n- \\`mathematics-extension\\`\n- \\`unique-id-extension\\`\n\n### Libs\n\n- \\`tiptap-utils\\`\n- \\`tiptap-collab-utils\\`\n\n### UI Components\n\n- \\`ai-menu\\`\n- \\`blockquote-button\\`\n- \\`code-block-button\\`\n- \\`color-highlight-button\\`, \\`color-highlight-popover\\`\n- \\`drag-context-menu\\`\n- \\`emoji-dropdown-menu\\`\n- \\`heading-button\\`, \\`heading-dropdown-menu\\`\n- \\`image-upload-button\\`\n- \\`link-popover\\`\n- \\`list-button\\`, \\`list-dropdown-menu\\`\n- \\`mark-button\\`\n- \\`mention-dropdown-menu\\`\n- \\`slash-dropdown-menu\\`\n- \\`text-align-button\\`\n- \\`turn-into-dropdown\\`\n- \\`undo-redo-button\\`\n\n### Nodes\n\n- \\`code-block-node\\`\n- \\`image-node\\`, \\`image-upload-node\\`\n- \\`list-node\\`\n- \\`paragraph-node\\`\n\n### Notion-specific\n\n- \\`notion-like-editor-header\\`\n- \\`notion-toolbar-floating\\`\n- \\`mobile-toolbar\\`\n- \\`collaboration-users\\`\n- \\`theme-toggle\\`\n\n### Primitives\n\n- \\`button\\`, \\`button-group\\`\n- \\`dropdown-menu\\`\n- \\`separator\\`, \\`spacer\\`, \\`toolbar\\`\n\n### Contexts\n\n- \\`user-context\\`\n- \\`collab-context\\`\n\n## Collaboration\n\nTo use collaboration:\n\n1. Pass a unique \\`room\\` ID to \\`NotionEditor\\`\n2. Enable JWT auth for each user session\n3. User presence and cursors are handled automatically\n4. Operational transformation handles concurrent edits\n5. Sync and save are managed out-of-the-box\n\n\\`\\`\\`tsx\n<NotionEditor room=\"team-notes\" placeholder=\"Share your ideas...\" />\n\\`\\`\\`\n\n## AI Integration\n\nThe built-in AI tools let you:\n\n- **Generate content** from prompts\n- **Improve** existing text\n- **Get smart completions** based on context\n\n> **AI Configuration:** Make sure to configure your AI provider. Check the [AI Generation extension docs](/content-ai/capabilities/generation/overview) for setup steps.\n\n## Extendability\n\nThis template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system—no rewrites required.`\n\nasync function updateReadmeFile(projectPath: string, templateName?: string) {\n const readmePath = path.join(projectPath, \"README.md\")\n\n const templateContent = {\n \"simple-editor\": simpleEditorTemplateDocs,\n \"notion-like-editor\": notionLikeEditorDocs,\n } as const\n\n type TemplateKey = keyof typeof templateContent\n\n const readmeContent =\n templateName && templateName in templateContent\n ? templateContent[templateName as TemplateKey]\n : \"\"\n\n try {\n if (readmeContent.trim()) {\n await fs.writeFile(readmePath, readmeContent, \"utf-8\")\n }\n } catch {\n /* empty */\n }\n}\n","#!/usr/bin/env node\nimport { add } from \"@/src/commands/add\"\nimport { info } from \"@/src/commands/info\"\nimport { init } from \"@/src/commands/init\"\nimport { login, logout, status, license } from \"@/src/commands/auth\"\nimport { Command } from \"commander\"\n\nimport packageJson from \"../package.json\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = new Command()\n .name(\"tiptap\")\n .description(\"add components and dependencies to your project\")\n .version(\n packageJson.version || \"1.0.0\",\n \"-v, --version\",\n \"display the CLI version number\"\n )\n\n program\n .addCommand(init)\n .addCommand(add)\n .addCommand(info)\n .addCommand(login)\n .addCommand(logout)\n .addCommand(status)\n .addCommand(license)\n\n program.parse()\n}\n\nmain()\n","{\n \"name\": \"@tiptap/cli\",\n \"version\": \"3.19.5\",\n \"description\": \"Tiptap CLI\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"author\": {\n \"name\": \"tiptap\",\n \"url\": \"https://github.com/ueberdosis/tiptap\"\n },\n \"files\": [\n \"dist\"\n ],\n \"keywords\": [\n \"cli\",\n \"components\",\n \"nextjs\",\n \"react\",\n \"templates\",\n \"tiptap\",\n \"@tiptap/cli\",\n \"ui\"\n ],\n \"license\": \"SEE LICENSE IN LICENSE.md\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n }\n },\n \"bin\": \"./dist/index.js\",\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\",\n \"start:dev\": \"cross-env REGISTRY_URL=http://localhost:3000 node dist/index.js\",\n \"start:prod\": \"cross-env REGISTRY_URL=https://template.tiptap.dev node dist/index.js\",\n \"start\": \"node dist/index.js\",\n \"pub:beta\": \"pnpm build && pnpm publish --no-git-checks --access public --tag beta\",\n \"pub:release\": \"pnpm build && pnpm publish --access public\"\n },\n \"dependencies\": {\n \"@antfu/ni\": \"^30.6.0\",\n \"@babel/core\": \"^7.29.7\",\n \"@babel/parser\": \"^7.29.9\",\n \"@babel/plugin-transform-typescript\": \"^7.29.9\",\n \"@inquirer/core\": \"^11.2.1\",\n \"@inquirer/figures\": \"^2.0.9\",\n \"@inquirer/prompts\": \"^8.7.3\",\n \"@inquirer/type\": \"^4.2.0\",\n \"ansi-escapes\": \"^7.3.0\",\n \"chalk\": \"^5.6.2\",\n \"commander\": \"^14.0.3\",\n \"conf\": \"^15.1.0\",\n \"cosmiconfig\": \"^9.0.2\",\n \"deepmerge\": \"^4.3.1\",\n \"execa\": \"^9.6.1\",\n \"fast-glob\": \"^3.3.3\",\n \"fs-extra\": \"^11.4.1\",\n \"https-proxy-agent\": \"^9.1.0\",\n \"jsonc-parser\": \"^3.3.1\",\n \"node-fetch\": \"^3.3.2\",\n \"ora\": \"^9.4.1\",\n \"recast\": \"^0.23.21\",\n \"sass\": \"^1.105.1\",\n \"ts-morph\": \"^28.0.0\",\n \"tsconfig-paths\": \"^4.2.0\",\n \"yaml\": \"^2.9.1\",\n \"yoctocolors-cjs\": \"^2.1.3\",\n \"zod\": \"^4.6.5\"\n },\n \"devDependencies\": {\n \"@babel/plugin-transform-typescript\": \"^7.26.5\",\n \"@types/babel__core\": \"^7.20.5\",\n \"@types/conf\": \"^3.0.3\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/prompts\": \"^2.4.9\",\n \"cross-env\": \"^10.1.0\",\n \"tsup\": \"^8.5.1\",\n \"type-fest\": \"^5.10.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.11\"\n }\n}\n"],"mappings":";AAAA,OAAOA,OAAU,OACjB,OAAS,WAAAC,OAAe,YACxB,OAAS,KAAAC,OAAS,MCFlB,OACE,gBAAAC,GACA,YAAAC,GACA,eAAAC,GACA,aA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G,SAAU,IAAM,QAAQ,KAAK,CAAC,CAAC,EAC1C,QAAQ,GAAG,UAAW,IAAM,QAAQ,KAAK,CAAC,CAAC,EAE3C,eAAeC,IAAO,CACpB,IAAMC,EAAU,IAAIC,GAAQ,EACzB,KAAK,QAAQ,EACb,YAAY,iDAAiD,EAC7D,QACCC,GAAY,SAAW,QACvB,gBACA,gCACF,EAEFF,EACG,WAAWG,EAAI,EACf,WAAWC,EAAG,EACd,WAAWC,EAAI,EACf,WAAWC,EAAK,EAChB,WAAWC,EAAM,EACjB,WAAWC,EAAM,EACjB,WAAWC,EAAO,EAErBT,EAAQ,MAAM,CAChB,CAEAD,GAAK","names":["path","Command","z","createPrompt","useState","useKeypress","usePrefix","usePagination","useRef","useMemo","useEffect","isBackspaceKey","isEnterKey","isUpKey","isDownKey","isNumberKey","Separator","ValidationError","makeTheme","colors","figures","ansiEscapes","selectTheme","text","isSelectable","item","normalizeChoices","choices","choice","name","normalizedChoice","formatMultilineChoice","firstLinePrefix","firstLine","remainingLines","continuationPrefix","stripAnsi","line","str","select_default","config","done","loop","pageSize","instructions","firstRender","theme","status","setStatus","prefix","searchTimeoutRef","showHelpTip","setShowHelpTip","items","bounds","first","last","defaultItemIndex","active","setActive","selectedChoice","key","rl","offset","next","position","searchTerm","matchIndex","message","helpTipTop","helpTipBottom","page","isActive","index","indexLabel","disabledLabel","color","x","cursor","choiceDescription","Separator","input","confirm","checkbox","path","path","createMatchPath","resolveImport","importPath","config","cosmiconfig","fg","loadConfig","z","path","FRAMEWORKS","path","fs","getPackageInfo","cwd","shouldThrow","packageJsonPath","fg","fs","loadConfig","PROJECT_SHARED_IGNORE","getProjectInfo","cwd","configFiles","isSrcDir","isTsx","aliasPrefix","packageJson","fg","fs","path","isTypeScriptProject","getTsConfigAliasPrefix","getPackageInfo","isUsingAppDir","type","FRAMEWORKS","file","dep","tsConfig","loadConfig","alias","paths","getProjectConfig","defaultProjectInfo","existingConfig","projectInfo","getConfig","config","resolveConfigPaths","DEFAULT_COMPONENTS","DEFAULT_CONTEXTS","DEFAULT_HOOKS","DEFAULT_TIPTAP_ICONS","DEFAULT_LIB","DEFAULT_TIPTAP_EXTENSIONS","DEFAULT_TIPTAP_NODES","DEFAULT_TIPTAP_UI","DEFAULT_TIPTAP_UI_PRIMITIVES","DEFAULT_TIPTAP_UI_UTILS","DEFAULT_STYLES","explorer","cosmiconfig","rawConfigSchema","z","configSchema","workspaceConfigSchema","getConfig","cwd","pathOverride","res","projectInfo","getProjectInfo","defaultAliases","applyAliasPrefix","aliases","prefix","key","value","config","resolvedAliases","resolveConfigPaths","tsConfig","loadConfig","resolvedPathOverride","path","resolveImport","getWorkspaceConfig","isAliasKey","resolvedPath","packageRoot","findPackageRoot","result","commonRoot","findCommonRoot","relativePath","matchingPackageRoot","fg","pkgPath","pkgDir","parts1","parts2","commonParts","i","chalk","colors","join","args","logger","colors","fs","preFlightAdd","options","errors","fs","path","config","getConfig","error","logger","colors","path","z","handleError","error","logger","z","key","value","colors","z","registryItemTypeSchema","PAID_PLANS","FREE_PLANS","ALL_PLANS","planSchema","registryItemFileSchema","registryItemSchema","registrySchema","registryIndexSchema","registryResolvedItemsTreeSchema","deepmerge","HttpsProxyAgent","fetch","z","Conf","TokenStorage","logger","prefix","error","msg","token","userInfo","e","loginDate","expiration","bearerToken","authToken","expirationISO","planName","plans","tokenStorage","TokenStorage","logger","REGISTRY_URL","agent","HttpsProxyAgent","getRegistryIndex","result","fetchRegistry","registryIndexSchema","error","logger","handleError","createRegistryError","response","url","urlInfo","colors","tokenStorage","fetchComponent","path","headers","getRegistryUrl","fetch","fetchRegistryBatch","componentNames","paths","bearerToken","fetchRegistryDependencies","components","registryResolveItemsTree","names","config","registryItems","resolveRegistryItems","payload","z","registryItemSchema","framework","getProjectInfo","allDependencies","deepmerge","item","allDevDependencies","filteredDevDependencies","filterDevDependenciesByFramework","dependenciesSet","dep","dedupedDevDependencies","registryResolvedItemsTreeSchema","name","isUrl","componentName","getRegistryTypeAliasMap","getRegistryParentMap","map","dependency","devDependencies","depsArray","stringDeps","hasSass","hasSassEmbedded","filteredDeps","prefersEmbedded","FRAMEWORKS","prefersRegular","ora","tiptapSpinner","colors","spinner","text","options","ora","detect","fs","path","getPackageManager","targetDir","withFallback","detectedPackageManager","packageManager","userAgent","isBunProject","cwd","hasBunLock","fs","path","hasBunfig","execa","updateDependencies","dependencies","config","options","dependenciesSpinner","spinner","packageManager","getPackageManager","execa","colors","existsSync","fs","path","basename","fs","tmpdir","path","transformImport","sourceFile","config","packageManager","importDeclarations","importDeclaration","moduleSpecifier","updateImportAliases","isBunProject","alias","transformFromAstSync","parse","transformTypescript","recast","PARSE_OPTIONS","transformJsx","sourceFile","config","output","ast","code","result","SyntaxKind","directiveRegex","transformRsc","sourceFile","config","first","Node","SyntaxKind","DEFAULT_EXCLUSIONS","shouldExcludeComponent","componentName","rules","filePath","rule","f","name","ruleName","getFrameworkEnvVarName","constantName","framework","frameworkName","FRAMEWORKS","stripFrameworkPrefix","varName","transformEnvironmentVariables","sourceFile","config","projectInfo","getProjectInfo","nodesToTransform","binaryExpressions","SyntaxKind","binaryExpr","leftText","match","transformedEnvVar","rightSide","newExpression","callExpressions","callExpr","expressionText","args","argText","newArgText","envVarsToTransform","frameworkEnvVarName","newCallExpr","propertyAccessExpressions","propAccess","propAccessText","node","newText","error","transformRemoveComponents","exclusionRules","nodesToModify","importDeclarations","importDeclaration","moduleSpecifier","defaultImport","namedImports","excludedImports","namedImport","excludedImport","exportDeclarations","exportDeclaration","namedExports","excludedExports","namedExport","excludedExport","variableStatements","variableStatement","declarations","excludedDeclarations","declaration","functionDeclarations","functionDeclaration","functionName","interfaceDeclarations","interfaceDeclaration","interfaceName","typeAliases","typeAlias","typeName","propertySignatures","propertySignature","propName","jsxElements","jsxElement","tagName","jsxSelfClosingElements","jsxSelfClosingElement","propertyAssignments","propertyAssignment","propertyName","jsxAttributes","jsxAttribute","attributeName","parameters","parameter","parameterName","paramList","Node","allParams","index","prev","next","i","arg","prevSibling","nextSibling","bindingElements","bindingElement","bindingName","bindingPattern","allBindings","identifiers","identifier","identifierName","parent","parentKind","propAssignment","shorthandPropertyAssignments","shorthandProp","a","b","aStart","action","sass","transformScssToCSS","scssContent","error","Project","ScriptKind","project","Project","createTempSourceFile","filename","dir","fs","path","tmpdir","transform","opts","transformers","transformImport","transformRsc","transformRemoveComponents","isBun","isBunProject","transformScssToCSS","tempFile","sourceFile","ScriptKind","transformer","transformJsx","confirm","SCSS_DECLARATION_FILE","SCSS_DECLARATION_CONTENT","updateFiles","files","config","options","result","filesCreatedSpinner","spinner","projectInfo","packageManager","getProjectInfo","getPackageManager","file","filePath","resolveFilePath","findCommonRoot","f","error","fileName","basename","targetDir","path","match","isBunProject","existingFile","existsSync","content","transform","transformImport","transformRsc","transformRemoveComponents","existingFileContent","fs","normalizedExisting","normalizedNew","getNormalizedFileContent","confirm","colors","text","declFile","ensureScssTypeDeclaration","logger","resolveFileTargetDirectory","override","paths","needle","normalizedPaths","p","normalizedNeedle","needleDir","needleSegments","i","testPath","resolvePageTarget","target","framework","resolveNestedFilePath","normalizedFilePath","normalizedTargetDir","fileSegments","targetSegments","lastTargetSegment","commonDirIndex","segment","templateName","relativePath","finalPath","templateMatch","dataPath","cwd","isSrcDir","declarationPath","z","execa","updateDevDependencies","devDependencies","config","options","packageJson","getPackageInfo","existingRegularDeps","dep","devDependenciesSpinner","spinner","packageManager","getPackageManager","execa","colors","addComponents","components","config","options","workspaceConfig","getWorkspaceConfig","addWorkspaceComponents","addProjectComponents","registrySpinner","spinner","tree","registryResolveItemsTree","colors","updateDependencies","updateDevDependencies","updateFiles","handleError","registryItems","resolveRegistryItems","result","fetchRegistry","payload","z","registryItemSchema","registryParentMap","getRegistryParentMap","registryTypeAliasMap","getRegistryTypeAliasMap","filesCreated","filesUpdated","filesSkipped","rootSpinner","component","alias","registryParent","targetConfig","workspaceRoot","findCommonRoot","packageRoot","findPackageRoot","files","file","error","logger","path","toReadableName","input","word","fetch","HttpsProxyAgent","fs","path","os","execa","yaml","TIPTAP_REGISTRY","AUTH_TOKEN_KEY","TIPTAP_PRO_REGISTRY_KEY","addNpmrcToGitignore","cwd","gitignorePath","path","npmrcEntry","gitignoreContent","fs","line","newContent","error","logger","saveAuthToken","token","packageManager","createdNpmrc","saveNpmToken","saveYarnToken","saveToNpmrc","execa","yarnVersion","saveYarnBerryToken","yarnrcPath","yamlObj","yarnrcContent","npmScopes","npmrcPath","npmrcContent","lines","processedKeys","parseNpmrc","contentLines","trimmedLine","index","key","getAuthToken","projectToken","checkProjectNpmrc","getNpmAuthToken","globalAuthToken","checkGlobalNpmrc","checkGlobalYarnrc","projectNpmrcPath","content","extractAuthToken","stdout","globalNpmrcPath","os","m","configString","AUTH_API_URL","REGISTRY_URL","httpAgent","HttpsProxyAgent","getApiErrorMessage","response","payload","getAuthErrorMessage","apiErrorMessage","getPlansErrorMessage","authenticateUser","email","password","packageManager","writeConfig","cwd","loginSpinner","spinner","tokens","requestAuthTokens","userPlans","plansResponse","fetch","plan","tokenStorage","saveAuthToken","colors","error","data","checkAuthStatus","bearerToken","userInfo","expiration","logger","logoutUser","Command","execa","z","confirm","input","passwordPrompt","authOptionsSchema","z","createThemedInput","message","options","input","colors","value","createThemedPassword","passwordPrompt","createThemedConfirm","defaultValue","confirm","getConfigFileName","packageManager","displayTokenInstructions","token","cwd","logger","checkYarnVersion","execa","handleLogin","email","password","writeConfig","showMessage","getPackageManager","configFileName","result","authenticateUser","handleStatusCheck","status","checkAuthStatus","expiryDate","now","daysUntilExpiry","tokenPreview","registryToken","getAuthToken","registryPreview","login","Command","opts","error","handleError","logout","logoutSpinner","spinner","logoutUser","handleLicenseInfo","hasAccepted","tokenStorage","userInfo","handleLicenseForgetMe","license","hasPaidComponents","components","component","plan","PAID_PLANS","promptLicenseAcceptance","selectedComponents","tokenStorage","logger","colors","createThemedConfirm","ensureAuthForPaidComponents","cwd","checkAuthStatus","packageManager","getPackageManager","createNpmrcConfiguration","handleLogin","error","configSpinner","spinner","authToken","saveAuthToken","process","getTerminalWidth","createBox","title","content","options","borderColor","padding","topLeft","topRight","bottomLeft","bottomRight","horizontal","vertical","terminalWidth","boxWidth","colorFn","colors","topBorder","bottomBorder","sideBorder","lines","titlePadding","stripAnsi","titleLine","line","strippedLength","paddedLine","createWelcomeBanner","title","subtitle","content","createBox","createWarningBox","title","content","createBox","logLines","lines","line","logger","stripAnsi","str","createExplanationSection","title","points","lines","colors","point","clearTerminal","process","createSpacedDivider","width","getTerminalWidth","colors","existsSync","path","getFrameworkEnvPrefix","framework","frameworkName","FRAMEWORKS","detectStyleFileExtension","config","stylesDir","variablesScss","variablesCss","calculateStylesImportPath","stylesInSrc","hasSrcDir","cssFile","importPath","showStylesConfigurationMessage","fileExtension","content","colors","box","createWarningBox","logLines","showNotionEnvSetupMessage","framework","prefix","getFrameworkEnvPrefix","content","colors","box","createWarningBox","logLines","showNotionTemplateSetupMessage","framework","config","prefix","getFrameworkEnvPrefix","fileExtension","detectStyleFileExtension","cssFile","importPath","calculateStylesImportPath","content","colors","box","createWarningBox","logLines","showTableNodeSetupMessage","logger","existsSync","fs","path","detectStyleFileExtension","config","stylesDir","variablesScss","path","variablesCss","existsSync","getMainCssFilePath","framework","frameworkName","cwd","hasSrcDir","stylesInSrc","possiblePaths","FRAMEWORKS","filePath","calculateImportPath","mainCssPath","mainCssDir","relativePath","hasStyleImports","content","fileExtension","variablesImport","keyframesImport","autoImportStyles","result","file","mainCssContent","fs","importPath","newContent","error","logger","logAutoImportResult","colors","cleanedRelativePath","addOptionsSchema","z","PROMPT_PAGE_SIZE","TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH","TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH","TEMPLATE_DESCRIPTION_INDENT_WIDTH","UI","colors","PROMPT_THEME","text","normalizeDescription","description","wrapText","maxLineLength","words","lines","currentLine","word","nextLine","getTemplateDescriptionLineWidth","terminalWidth","formatTemplatePlanLabel","plans","planLabel","getPlanLabel","formatTemplateChoiceName","template","name","toReadableName","descriptionLines","line","requiredPlan","PAID_PLANS","plan","planName","filterFreeTemplates","templates","freeComponents","template","clearPromptLines","lines","i","categorizeRegistryItems","registryIndex","entry","promptForInitialSelection","categories","showDivider","message","choices","isComponentEmpty","logger","UI","createSpacedDivider","selection","select_default","colors","PROMPT_PAGE_SIZE","PROMPT_THEME","createComponentChoices","components","addCategorySection","items","title","filteredItems","item","Separator","planLabel","getPlanLabel","paddedName","toReadableName","description","componentMenu","selectedComponents","checkbox","component","templateMenu","formatTemplateChoiceName","selectedTemplate","promptForRegistryComponents","options","getRegistryIndex","error","ensureAuthForPaidComponents","handleError","allComponents","filteredTemplates","add","Command","opts","clearTerminal","welcomeBanner","createWelcomeBanner","logLines","explanation","createExplanationSection","input","addOptionsSchema","path","selectedComponentDetails","componentName","componentInfo","errors","config","preFlightAdd","created","addComponents","totalFilesProcessed","allFiles","containsNotion","containsSimpleEditor","projectInfo","getProjectInfo","autoImportResult","autoImportStyles","logAutoImportResult","showNotionEnvSetupMessage","showNotionTemplateSetupMessage","showStylesConfigurationMessage","showTableNodeSetupMessage","Command","info","opts","logger","getProjectInfo","config","getConfig","path","Command","confirm","input","z","path","fs","preFlightInit","options","errors","fs","path","frameworkSpinner","spinner","projectInfo","getProjectInfo","logger","colors","tsConfigSpinner","os","path","fs","execa","parseJsonc","input","MONOREPO_FRAMEWORK_URL","FRAMEWORKS","createThemedInput","message","defaultValue","input","colors","value","createThemedSelect","choices","instructions","select_default","createProject","options","normalizedOptions","framework","projectName","nextVersion","frameworkPromptMessage","logger","packageManager","getPackageManager","projectPath","path","validateProjectPath","createNextProject","createViteProject","createMonorepoProject","cwd","fs","createSpinner","spinner","args","execa","updateReadmeFile","setupViteTsConfig","error","handleError","setupTsConfigPathAliases","setupViteConfigPathAliases","installTypesNode","addAliasToTsConfig","tsconfigFile","tsconfigPath","jsonContent","jsonObj","parseJsonc","updatedJson","viteConfigPath","updatedViteConfig","downloadAndExtractFramework","initializeGitRepository","frameworkPath","os","response","tarPath","extractedPath","simpleEditorTemplateDocs","notionLikeEditorDocs","templateName","readmePath","templateContent","readmeContent","initOptionsSchema","z","val","FRAMEWORKS","createThemedConfirm","message","defaultValue","confirm","colors","init","Command","components","opts","clearTerminal","welcomeBanner","createWelcomeBanner","logLines","explanation","createExplanationSection","input","logger","options","path","result","runInit","totalFilesProcessed","allFiles","containsNotion","containsSimpleEditor","framework","autoImportResult","autoImportStyles","logAutoImportResult","showNotionEnvSetupMessage","showNotionTemplateSetupMessage","showStylesConfigurationMessage","showTableNodeSetupMessage","error","handleError","cwd","skipPreflight","silent","updatedOptions","newProjectFramework","createResult","config","projectInfo","selectedComponents","addResult","getProjectInfo","preflight","preFlightInit","projectPath","createProject","monorepoWebPath","getConfig","projectConfig","getProjectConfig","promptForMinimalConfig","promptForConfig","fullConfig","resolveConfigPaths","promptForRegistryComponents","registryIndex","getRegistryIndex","assumedPaidComponents","name","ensureAuthForPaidComponents","selectedComponentDetails","componentName","componentInfo","item","addComponentsResult","addComponents","defaultConfig","tsx","rsc","rawConfigSchema","DEFAULT_COMPONENTS","DEFAULT_CONTEXTS","DEFAULT_HOOKS","DEFAULT_TIPTAP_ICONS","DEFAULT_LIB","DEFAULT_TIPTAP_EXTENSIONS","DEFAULT_TIPTAP_NODES","DEFAULT_TIPTAP_UI","DEFAULT_TIPTAP_UI_PRIMITIVES","DEFAULT_TIPTAP_UI_UTILS","DEFAULT_STYLES","Command","package_default","main","program","Command","package_default","init","add","info","login","logout","status","license"]}
|
|
1
|
+
{"version":3,"sources":["../src/commands/add.ts","../src/inquirer/select.ts","../src/preflights/preflight-add.ts","../src/utils/get-config.ts","../src/utils/resolve-import.ts","../src/utils/get-project-info.ts","../src/utils/frameworks.ts","../src/utils/get-package-info.ts","../src/utils/colors.ts","../src/utils/logger.ts","../src/utils/add-components.ts","../src/utils/auth.ts","../src/utils/spinner.ts","../src/utils/token-storage.ts","../src/utils/bootstrap.ts","../src/utils/package-manager-config.ts","../src/utils/registry/schema.ts","../src/utils/registry/index.ts","../src/utils/get-package-manager.ts","../src/commands/auth.ts","../src/utils/handle-error.ts","../src/utils/auth-check.ts","../src/utils/cli-ui.ts","../src/utils/auto-import-styles.ts","../src/utils/updaters/update-files.ts","../src/utils/registry-paths.ts","../src/utils/transformers/index.ts","../src/utils/transformers/transform-import.ts","../src/utils/transformers/transform-jsx.ts","../src/utils/transformers/transform-rsc.ts","../src/utils/transformers/transform-remove-components.ts","../src/utils/transformers/transform-scss-to-css.ts","../src/utils/tiptap-registry-access.ts","../src/utils/plan-collaboration.ts","../src/utils/connect-collaboration.ts","../src/utils/editor-source.ts","../src/utils/plan-editor-extension.ts","../src/utils/updaters/plan-dependencies.ts","../src/utils/install-planned-packages.ts","../src/utils/updaters/update-dependencies.ts","../src/utils/updaters/update-dev-dependencies.ts","../src/utils/print-install-preview.ts","../src/utils/common.ts","../src/utils/prompt-messages.ts","../src/utils/features.ts","../src/utils/feature-project.ts","../src/commands/info.ts","../package.json","../src/commands/search.ts","../src/commands/view.ts","../src/commands/init.ts","../src/preflights/preflight-init.ts","../src/utils/create-project.ts","../src/utils/configure-next-pnpm-builds.ts","../src/index.ts"],"sourcesContent":["import path from \"path\"\nimport { Command } from \"commander\"\nimport { z } from \"zod\"\nimport select from \"@/src/inquirer/select\"\nimport { Separator, input, confirm, checkbox } from \"@inquirer/prompts\"\nimport { preFlightAdd } from \"@/src/preflights/preflight-add\"\nimport { addComponents, planComponents } from \"@/src/utils/add-components\"\nimport { printInstallPreview } from \"@/src/utils/print-install-preview\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { getRegistryIndex } from \"@/src/utils/registry\"\nimport { colors } from \"@/src/utils/colors\"\nimport { toReadableName } from \"@/src/utils/common\"\nimport {\n assertCanPreviewPaidComponents,\n ensureAuthForPaidComponents,\n hasPaidComponents,\n} from \"../utils/auth-check\"\nimport {\n PAID_PLANS,\n type RegistryFeature,\n type Plan,\n type RegistryItemIndexSchema,\n} from \"../utils/registry/schema\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport {\n showNotionEnvSetupMessage,\n showNotionTemplateSetupMessage,\n showStylesConfigurationMessage,\n showTableNodeSetupMessage,\n} from \"@/src/utils/prompt-messages\"\nimport {\n createWelcomeBanner,\n logLines,\n clearTerminal,\n canPrompt,\n createSpacedDivider,\n} from \"@/src/utils/cli-ui\"\nimport {\n featureOption,\n chooseTemplateFeature,\n getOptionalRegistryFeatures,\n resolveSelection,\n resolveEditor,\n showFeatureSetup,\n} from \"@/src/utils/features\"\nimport {\n getFeatureConfig,\n requireReactProject,\n} from \"@/src/utils/feature-project\"\nimport { logAutoImportResult } from \"@/src/utils/auto-import-styles\"\n\nexport const addOptionsSchema = z.object({\n components: z.array(z.string()).optional(),\n with: z.string().min(1).optional(),\n editor: z.string().min(1).optional(),\n cwd: z.string(),\n path: z.string().optional(),\n silent: z.boolean(),\n overwrite: z.boolean(),\n dryRun: z.boolean().optional(),\n diff: z\n .union([\n z.boolean(),\n z.string().min(1, \"Provide a path or use bare --diff.\"),\n ])\n .optional(),\n})\n\ntype AddOptions = z.infer<typeof addOptionsSchema>\n\ninterface CategoryMap {\n templates: RegistryItemIndexSchema\n newComponents: RegistryItemIndexSchema\n ui: RegistryItemIndexSchema\n primitives: RegistryItemIndexSchema\n uiUtils: RegistryItemIndexSchema\n nodes: RegistryItemIndexSchema\n}\n\nconst PROMPT_PAGE_SIZE = 1_000 // Large size to avoid help tip\nconst TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH = 92\nconst TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH = 48\nconst TEMPLATE_DESCRIPTION_INDENT_WIDTH = 4\n\nconst UI = {\n emptyRegistry: colors.red(\"❌ No components or templates found\"),\n operationCancelled: colors.gray(\"Operation cancelled\"),\n}\n\nconst PROMPT_THEME = {\n icon: {\n cursor: colors.cyan(\"▸\"),\n checked: colors.cyan(\"◉\"),\n unchecked: \"○\",\n },\n style: {\n highlight: (text: string) => colors.cyan(text),\n message: (text: string) => text,\n answer: (text: string) => \"\", // Hide inline answer display\n },\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: colors.cyan(\"?\"),\n },\n}\n\nfunction normalizeDescription(description?: string): string {\n const normalized = description?.replace(/\\s+/g, \" \").trim()\n return normalized ?? \"\"\n}\n\nfunction wrapText(text: string, maxLineLength: number): string[] {\n const words = text.split(\" \")\n const lines: string[] = []\n let currentLine = \"\"\n\n for (const word of words) {\n const nextLine = currentLine ? `${currentLine} ${word}` : word\n\n if (nextLine.length > maxLineLength && currentLine) {\n lines.push(currentLine)\n currentLine = word\n } else {\n currentLine = nextLine\n }\n }\n\n if (currentLine) {\n lines.push(currentLine)\n }\n\n return lines\n}\n\nfunction getTemplateDescriptionLineWidth(): number {\n const terminalWidth = process.stdout.columns\n\n if (!terminalWidth) {\n return TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH\n }\n\n return Math.max(\n TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH,\n Math.min(\n TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH,\n terminalWidth - TEMPLATE_DESCRIPTION_INDENT_WIDTH\n )\n )\n}\n\nfunction formatTemplatePlanLabel(plans?: Plan[]): string {\n const planLabel = getPlanLabel(plans)\n\n if (plans?.includes(\"light\") || plans?.includes(\"open-source\")) {\n return \"Open Source - MIT\"\n }\n\n return planLabel\n}\n\nfunction formatTemplateChoiceName(template: RegistryItemIndexSchema[number]) {\n const planLabel = formatTemplatePlanLabel(template.plans)\n const name = `${colors.bold(toReadableName(template.name))} ${colors.dim(\n `(${planLabel})`\n )}:`\n const description = normalizeDescription(template.description)\n\n if (!description) {\n return name\n }\n\n const descriptionLines = wrapText(\n description,\n getTemplateDescriptionLineWidth()\n ).map((line) => ` ${line}`)\n\n return [name, ...descriptionLines].join(\"\\n\")\n}\n\nfunction getPlanLabel(plans?: Plan[]): string {\n if (!plans?.length) {\n return \"Free\"\n }\n\n if (plans.includes(\"light\") || plans.includes(\"open-source\")) {\n return \"Open source (MIT)\"\n }\n\n const requiredPlan = PAID_PLANS.find((plan) => plans.includes(plan))\n if (!requiredPlan) {\n return \"Free\"\n }\n\n const planName = `${requiredPlan[0].toUpperCase()}${requiredPlan.slice(1)}`\n return requiredPlan === \"start\"\n ? `${planName} plan • Trial`\n : `${planName} plan`\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nconst createThemedConfirm = (message: string, defaultValue: boolean = true) => {\n return confirm({\n message,\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Filters templates to only include free ones based on registry data\n */\nfunction filterFreeTemplates(\n templates: RegistryItemIndexSchema,\n freeComponents: string[] | null\n): RegistryItemIndexSchema {\n if (!freeComponents) {\n return templates\n }\n\n return templates.filter((template) => freeComponents.includes(template.name))\n}\n\n/**\n * Clears specified number of lines from console\n */\nfunction clearPromptLines(lines: number) {\n for (let i = 0; i < lines; i++) {\n process.stdout.write(\"\\x1B[1A\") // Move cursor up\n process.stdout.write(\"\\x1B[2K\") // Clear line\n }\n}\n\n/**\n * Categorizes registry items by type\n */\nconst categorizeRegistryItems = (\n registryIndex: RegistryItemIndexSchema\n): CategoryMap => {\n return {\n templates: registryIndex.filter(\n (entry) => entry.type === \"registry:template\"\n ),\n newComponents: registryIndex.filter((entry) => entry.isNew === true),\n ui: registryIndex.filter((entry) => entry.type === \"registry:ui\"),\n primitives: registryIndex.filter(\n (entry) => entry.type === \"registry:ui-primitive\"\n ),\n uiUtils: registryIndex.filter(\n (entry) => entry.type === \"registry:ui-utils\"\n ),\n nodes: registryIndex.filter((entry) => entry.type === \"registry:node\"),\n }\n}\n\n/**\n * Presents the available installation targets\n */\nasync function promptForInitialSelection(\n categories: CategoryMap,\n hasFeatures: boolean,\n showDivider = true\n): Promise<\"components\" | \"templates\" | \"features\" | null> {\n const message = \"What would you like to integrate?\"\n\n const choices = []\n const isComponentEmpty =\n categories.ui.length === 0 &&\n categories.nodes.length === 0 &&\n categories.newComponents.length === 0\n const isTemplateEmpty = categories.templates.length === 0\n\n if (!isTemplateEmpty) {\n choices.push({\n name: \"Templates - Full editor applications\",\n value: \"templates\",\n })\n }\n\n if (!isComponentEmpty) {\n choices.push({\n name: \"UI Components - Individual editor building blocks\",\n value: \"components\",\n })\n }\n\n if (hasFeatures)\n choices.push({ name: \"Features for your editor\", value: \"features\" })\n\n if (choices.length === 0) {\n logger.break()\n console.log(UI.emptyRegistry)\n return null\n }\n\n try {\n if (showDivider) {\n console.log(createSpacedDivider())\n }\n\n const selection = await select({\n message: colors.reset(message),\n pageSize: PROMPT_PAGE_SIZE,\n theme: PROMPT_THEME,\n choices,\n })\n\n if (showDivider) {\n console.log(createSpacedDivider())\n }\n\n return selection as \"templates\" | \"components\" | \"features\"\n } catch (error) {\n clearPromptLines(4)\n console.log(UI.operationCancelled)\n return null\n }\n}\n\n/**\n * Creates choices for component menu with appropriate sections\n */\nasync function createComponentChoices(\n categories: CategoryMap,\n components: string[] | null\n): Promise<Array<{ name: string; value: string } | Separator>> {\n const choices: Array<{ name: string; value: string } | Separator> = []\n\n if (!components) {\n return choices\n }\n\n const addCategorySection = (\n items: RegistryItemIndexSchema,\n title: string\n ) => {\n const filteredItems = items.filter((item) => components.includes(item.name))\n\n if (filteredItems.length > 0) {\n choices.push(new Separator(\"\"))\n choices.push(new Separator(colors.whiteBold(` ${title}`)))\n\n filteredItems.forEach((item) => {\n const planLabel = getPlanLabel(item.plans)\n\n const name = toReadableName(item.name)\n const paddedName = name.padEnd(35)\n\n choices.push({\n name: `${paddedName} ${colors.dim(planLabel)}`,\n value: item.name,\n })\n })\n\n choices.push(new Separator(\" \"))\n }\n }\n\n const addNewComponentsSection = (\n items: RegistryItemIndexSchema,\n title: string\n ) => {\n const filteredItems = items.filter((item) => components.includes(item.name))\n\n if (filteredItems.length > 0) {\n choices.push(new Separator(\"\"))\n choices.push(new Separator(colors.whiteBold(` ${title}`)))\n\n filteredItems.forEach((item) => {\n const planLabel = getPlanLabel(item.plans)\n\n const name = toReadableName(item.name)\n const paddedName = name.padEnd(35)\n const description = item.description\n ? `\\n ${colors.dim(item.description)}`\n : \"\"\n\n choices.push({\n name: `${paddedName} ${colors.dim(planLabel)}${description}`,\n value: item.name,\n })\n })\n\n choices.push(new Separator(\" \"))\n }\n }\n\n addNewComponentsSection(categories.newComponents, \"NEW COMPONENTS\")\n addCategorySection(categories.ui, \"UI COMPONENTS\")\n addCategorySection(categories.nodes, \"NODE COMPONENTS\")\n addCategorySection(categories.primitives, \"PRIMITIVES\")\n\n return choices\n}\n\n/**\n * Shows menu for selecting components\n */\nasync function componentMenu(\n categories: CategoryMap,\n components: string[] | null\n): Promise<string[]> {\n const choices = await createComponentChoices(categories, components)\n\n if (choices.length === 0) {\n return []\n }\n\n try {\n logger.log(\"\")\n logger.log(\n colors.cyan(\n \" Press Space to select • A to toggle all • Enter to confirm\"\n )\n )\n\n const selectedComponents = await checkbox({\n message: \"Choose UI components to install:\",\n pageSize: 20,\n choices,\n theme: PROMPT_THEME,\n validate: (items) => {\n if (items.length === 0) {\n return \"Select at least one component (use Space to select, then Enter to confirm)\"\n }\n return true\n },\n })\n\n // Display selected components\n if (selectedComponents && selectedComponents.length > 0) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Selected components:\"))\n selectedComponents.forEach((component) => {\n logger.log(` ${colors.cyan(\"•\")} ${toReadableName(component)}`)\n })\n }\n\n logger.log(\"\")\n return selectedComponents || []\n } catch (error) {\n clearPromptLines(25)\n console.log(UI.operationCancelled)\n return []\n }\n}\n\n/**\n * Shows menu for selecting templates\n */\nasync function templateMenu(\n templates: RegistryItemIndexSchema\n): Promise<string[]> {\n try {\n const choices = templates.map((template) => {\n return {\n name: formatTemplateChoiceName(template),\n value: template.name,\n }\n })\n\n logger.log(\"\")\n\n const selectedTemplate = await select({\n message: \"Choose an editor template to install:\",\n pageSize: 20,\n choices,\n theme: PROMPT_THEME,\n })\n\n // Display selected template\n if (selectedTemplate) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Selected template:\"))\n logger.log(` ${colors.cyan(\"•\")} ${toReadableName(selectedTemplate)}`)\n }\n\n logger.log(\"\")\n return selectedTemplate ? [selectedTemplate] : []\n } catch (error) {\n clearPromptLines(25)\n console.log(UI.operationCancelled)\n return []\n }\n}\n\n/**\n * Main function to prompt for registry components\n */\nexport async function promptForRegistryComponents(\n options: AddOptions,\n showDivider = true\n): Promise<{ components: string[]; feature?: RegistryFeature }> {\n if (options.components?.length) return { components: options.components }\n const [registryIndex, features] = await Promise.all([\n getRegistryIndex(),\n getOptionalRegistryFeatures(),\n ])\n const categories = categorizeRegistryItems(registryIndex)\n const selection = await promptForInitialSelection(\n categories,\n features.length > 0,\n showDivider\n )\n const visible = registryIndex\n .filter((item) => !item.hide)\n .map((item) => item.name)\n switch (selection) {\n case \"features\": {\n const id = await select({\n message: \"Choose a feature for your editor\",\n choices: features.map((feature) => ({\n name: feature.label,\n value: feature.id,\n description: feature.description,\n })),\n theme: PROMPT_THEME,\n })\n return {\n components: [],\n feature: features.find((feature) => feature.id === id),\n }\n }\n case \"components\":\n return { components: await componentMenu(categories, visible) }\n case \"templates\": {\n const templates = filterFreeTemplates(categories.templates, visible)\n const components = await templateMenu(templates)\n const template = templates.find((item) => item.name === components[0])\n const feature =\n template && !options.dryRun && !options.diff\n ? await chooseTemplateFeature(template, features)\n : undefined\n return { components, feature }\n }\n default:\n return { components: [] }\n }\n}\n\nexport const add = new Command()\n .name(\"add\")\n .description(\"add features, templates, or UI components to your project\")\n .argument(\"[components...]\", \"the components to add\")\n .addOption(featureOption())\n .option(\"--editor <path>\", \"connect the feature to an existing editor file\")\n .option(\"-o, --overwrite\", \"overwrite existing files.\", false)\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .option(\n \"--dry-run\",\n \"preview files and dependencies without installing them.\"\n )\n .option(\"--diff [path]\", \"show changes to all files or one destination path.\")\n .option(\n \"-p, --path <path>\",\n \"parent directory for installed components and feature files.\"\n )\n .option(\"-s, --silent\", \"mute output.\", false)\n .action(async (components, opts) => {\n try {\n const options = addOptionsSchema.parse({\n ...opts,\n components,\n cwd: path.resolve(opts.cwd),\n })\n const preview = options.dryRun || options.diff !== undefined\n const interactive = !options.silent && canPrompt()\n if (options.editor && components.length)\n throw new Error(\n `Choose either ${components.join(\", \")} or --editor ${options.editor}.`\n )\n if (options.editor && !options.with)\n throw new Error(\"Use --editor with --with <id>.\")\n if (!options.with && !components.length && (!interactive || preview)) {\n throw new Error(\n \"Specify the registry items to add or pass --with <id>.\"\n )\n }\n let featureId = options.with\n let selected = options.components ?? []\n if (!selected.length && !featureId) {\n clearTerminal()\n logLines(\n createWelcomeBanner(\n \"Tiptap\",\n \"Add a feature to your editor, install a template, or choose UI components.\"\n )\n )\n\n await input({\n message: colors.reset(\n `Press ${colors.cyan(\"Enter\")} to add a feature, template, or UI component...`\n ),\n theme: {\n prefix: {\n done: \"\",\n idle: \"\",\n },\n },\n })\n\n // Add visual separation\n logger.log(\"\")\n logger.log(\"\")\n logger.log(\"\")\n const choice = await promptForRegistryComponents(options)\n selected = choice.components\n featureId = choice.feature?.id\n if (!selected.length && !featureId) return\n }\n const selection = await resolveSelection(selected, featureId, options.cwd)\n const { sources, feature, builtIn } = selection\n if (builtIn && !options.silent) logger.log(builtIn)\n const standalone = !selected.length && !!feature\n const target = await resolveEditor(\n selection,\n options.cwd,\n options.editor,\n interactive && !preview\n )\n const featureProject = feature\n ? await getProjectInfo(options.cwd, { forFeature: true })\n : undefined\n let config\n if (standalone) {\n config = await getFeatureConfig(\n options.cwd,\n options.path,\n featureProject\n )\n } else {\n if (feature) requireReactProject(options.cwd)\n const preflight = await preFlightAdd(options, featureProject)\n if (preflight.errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT]) {\n throw new Error(\n `No package.json found in ${options.cwd}. Run tiptap init to create a project before adding or previewing components.`\n )\n }\n config = preflight.config\n if (!config) throw new Error(`Failed to read config at ${options.cwd}.`)\n }\n\n const planOptions = {\n features: feature ? [feature] : [],\n editorPath: target.editorPath,\n overwrite: options.overwrite,\n projectInfo: featureProject,\n }\n if (preview) {\n if (hasPaidComponents(sources)) assertCanPreviewPaidComponents(sources)\n const plan = await planComponents(selected, config, planOptions)\n printInstallPreview(plan, options.cwd, options.diff)\n await showFeatureSetup(feature, plan, {\n candidates: standalone ? target.candidates : undefined,\n pathOverride: options.path,\n preview: true,\n cwd: options.cwd,\n diff: options.diff,\n })\n return\n }\n\n if (\n hasPaidComponents(sources) &&\n !(await ensureAuthForPaidComponents(\n sources,\n options.cwd,\n feature ? { interactive } : undefined\n ))\n ) {\n throw new Error(\n \"Authenticate and accept the Pro license before installing paid components.\"\n )\n }\n\n const created = await addComponents(selected, config, {\n ...options,\n ...planOptions,\n interactive: feature ? interactive : undefined,\n })\n\n if (options.silent) return\n\n for (const [action, files] of [\n [\"Created\", created.filesCreated],\n [\"Updated\", created.filesUpdated],\n [\"Skipped\", created.filesSkipped],\n ] as const) {\n if (files.length) {\n logger.log(\n `${action} ${files.length} file${files.length === 1 ? \"\" : \"s\"}`\n )\n for (const file of files) logger.log(` ${file}`)\n }\n }\n if (standalone) {\n await showFeatureSetup(feature, created, {\n cwd: options.cwd,\n candidates: target.candidates,\n pathOverride: options.path,\n })\n return\n }\n logAutoImportResult(created.styles)\n const projectInfo = featureProject ?? (await getProjectInfo(options.cwd))\n if (projectInfo) {\n if (selected.includes(\"notion-like-editor\")) {\n if (created.styles.success)\n showNotionEnvSetupMessage(projectInfo.framework)\n else showNotionTemplateSetupMessage(projectInfo.framework, config)\n } else if (!created.styles.success) {\n showStylesConfigurationMessage(projectInfo.framework, config)\n }\n }\n if (selected.includes(\"table-node\")) showTableNodeSetupMessage()\n await showFeatureSetup(feature, created)\n } catch (error) {\n logger.break()\n handleError(error)\n }\n })\n","import {\n createPrompt,\n useState,\n useKeypress,\n usePrefix,\n usePagination,\n useRef,\n useMemo,\n useEffect,\n isBackspaceKey,\n isEnterKey,\n isUpKey,\n isDownKey,\n isNumberKey,\n Separator,\n ValidationError,\n makeTheme,\n type Theme,\n type Status,\n} from \"@inquirer/core\"\nimport type { PartialDeep } from \"@inquirer/type\"\nimport colors from \"yoctocolors-cjs\"\nimport figures from \"@inquirer/figures\"\nimport ansiEscapes from \"ansi-escapes\"\n\ntype SelectTheme = {\n icon: { cursor: string }\n style: {\n disabled: (text: string) => string\n description: (text: string) => string\n }\n indexMode: \"hidden\" | \"number\"\n}\n\nconst selectTheme: SelectTheme = {\n icon: { cursor: figures.pointer },\n style: {\n disabled: (text: string) => colors.dim(`- ${text}`),\n description: (text: string) => colors.cyan(text),\n },\n indexMode: \"hidden\",\n}\n\ntype Choice<Value> = {\n value: Value\n name?: string\n description?: string\n short?: string\n disabled?: boolean | string\n type?: never\n}\n\ntype NormalizedChoice<Value> = {\n value: Value\n name: string\n description?: string\n short: string\n disabled: boolean | string\n}\n\ntype SelectConfig<\n Value,\n ChoicesObject =\n | ReadonlyArray<string | Separator>\n | ReadonlyArray<Choice<Value> | Separator>,\n> = {\n message: string\n choices: ChoicesObject extends ReadonlyArray<string | Separator>\n ? ChoicesObject\n : ReadonlyArray<Choice<Value> | Separator>\n pageSize?: number\n loop?: boolean\n default?: unknown\n instructions?: string | boolean\n theme?: PartialDeep<Theme<SelectTheme>>\n}\n\nfunction isSelectable<Value>(\n item: NormalizedChoice<Value> | Separator\n): item is NormalizedChoice<Value> {\n return !Separator.isSeparator(item) && !item.disabled\n}\n\nfunction normalizeChoices<Value>(\n choices:\n ReadonlyArray<string | Separator> | ReadonlyArray<Choice<Value> | Separator>\n): Array<NormalizedChoice<Value> | Separator> {\n return choices.map((choice) => {\n if (Separator.isSeparator(choice)) return choice\n\n if (typeof choice === \"string\") {\n return {\n value: choice as Value,\n name: choice,\n short: choice,\n disabled: false,\n }\n }\n\n const name = choice.name ?? String(choice.value)\n const normalizedChoice: NormalizedChoice<Value> = {\n value: choice.value,\n name,\n short: choice.short ?? name,\n disabled: choice.disabled ?? false,\n }\n\n if (choice.description) {\n normalizedChoice.description = choice.description\n }\n\n return normalizedChoice\n })\n}\n\nfunction formatMultilineChoice(text: string, firstLinePrefix: string): string {\n const [firstLine = \"\", ...remainingLines] = text.split(\"\\n\")\n const continuationPrefix = \" \".repeat(stripAnsi(firstLinePrefix).length)\n\n return [\n `${firstLinePrefix}${firstLine}`,\n ...remainingLines.map((line) => `${continuationPrefix}${line}`),\n ].join(\"\\n\")\n}\n\nfunction stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\")\n}\n\nexport default createPrompt(\n <Value>(config: SelectConfig<Value>, done: (value: Value) => void) => {\n const { loop = true, pageSize = 7, instructions } = config\n const firstRender = useRef(true)\n const theme = makeTheme<SelectTheme>(selectTheme, config.theme)\n const [status, setStatus] = useState<Status>(\"idle\")\n const prefix = usePrefix({ status, theme })\n const searchTimeoutRef = useRef<ReturnType<typeof setTimeout>>()\n const [showHelpTip, setShowHelpTip] = useState(true)\n\n const items = useMemo(\n () => normalizeChoices(config.choices),\n [config.choices]\n )\n\n const bounds = useMemo(() => {\n const first = items.findIndex(isSelectable)\n const last = items.findLastIndex(isSelectable)\n\n if (first === -1) {\n throw new ValidationError(\n \"[select prompt] No selectable choices. All choices are disabled.\"\n )\n }\n\n return { first, last }\n }, [items])\n\n const defaultItemIndex = useMemo(() => {\n if (!(\"default\" in config)) return -1\n return items.findIndex(\n (item) => isSelectable(item) && item.value === config.default\n )\n }, [config.default, items])\n\n const [active, setActive] = useState(\n defaultItemIndex === -1 ? bounds.first : defaultItemIndex\n )\n\n // Safe to assume the cursor position always point to a Choice.\n const selectedChoice = items[active] as NormalizedChoice<Value>\n\n useKeypress((key, rl) => {\n clearTimeout(searchTimeoutRef.current)\n setShowHelpTip(false)\n\n if (isEnterKey(key)) {\n setStatus(\"done\")\n done(selectedChoice.value)\n } else if (isUpKey(key) || isDownKey(key)) {\n rl.clearLine(0)\n if (\n loop ||\n (isUpKey(key) && active !== bounds.first) ||\n (isDownKey(key) && active !== bounds.last)\n ) {\n const offset = isUpKey(key) ? -1 : 1\n let next = active\n do {\n next = (next + offset + items.length) % items.length\n } while (!isSelectable(items[next]!))\n setActive(next)\n }\n } else if (isNumberKey(key) && !Number.isNaN(Number(rl.line))) {\n const position = Number(rl.line) - 1\n const item = items[position]\n if (item != null && isSelectable(item)) {\n setActive(position)\n }\n\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0)\n }, 700)\n } else if (isBackspaceKey(key)) {\n rl.clearLine(0)\n } else {\n // Default to search\n const searchTerm = rl.line.toLowerCase()\n const matchIndex = items.findIndex((item) => {\n if (Separator.isSeparator(item) || !isSelectable(item)) return false\n\n return item.name.toLowerCase().startsWith(searchTerm)\n })\n\n if (matchIndex !== -1) {\n setActive(matchIndex)\n }\n\n searchTimeoutRef.current = setTimeout(() => {\n rl.clearLine(0)\n }, 700)\n }\n })\n\n useEffect(\n () => () => {\n clearTimeout(searchTimeoutRef.current)\n },\n []\n )\n\n const message = theme.style.message(config.message, status)\n\n let helpTipTop = \"\"\n let helpTipBottom = \"\"\n // Help text is now always hidden\n if (typeof instructions === \"string\") {\n helpTipTop = instructions\n }\n\n const page = usePagination({\n items,\n active,\n renderItem({ item, isActive, index }) {\n if (Separator.isSeparator(item)) {\n return ` ${item.separator}`\n }\n\n const indexLabel = theme.indexMode === \"number\" ? `${index + 1}. ` : \"\"\n if (item.disabled) {\n const disabledLabel =\n typeof item.disabled === \"string\" ? item.disabled : \"(disabled)\"\n return theme.style.disabled(\n `${indexLabel}${item.name} ${disabledLabel}`\n )\n }\n\n const color = isActive ? theme.style.highlight : (x: string) => x\n const cursor = isActive ? theme.icon.cursor : ` `\n return color(\n formatMultilineChoice(item.name, `${cursor} ${indexLabel}`)\n )\n },\n pageSize,\n loop,\n })\n\n if (status === \"done\") {\n return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`\n }\n\n const choiceDescription = selectedChoice.description\n ? `\\n${theme.style.description(selectedChoice.description)}`\n : ``\n\n return `${[prefix, message, helpTipTop].filter(Boolean).join(\" \")}\\n${page}${helpTipBottom}${choiceDescription}${ansiEscapes.cursorHide}`\n }\n)\n\nexport { Separator } from \"@inquirer/core\"\n","import path from \"path\"\nimport { addOptionsSchema } from \"@/src/commands/add\"\nimport * as ERRORS from \"@/src/utils/errors\"\nimport { getConfig } from \"@/src/utils/get-config\"\nimport { logger } from \"@/src/utils/logger\"\nimport fs from \"fs-extra\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\n\nimport type { ProjectInfo } from \"@/src/utils/get-project-info\"\n\nexport async function preFlightAdd(\n options: z.infer<typeof addOptionsSchema>,\n projectInfo?: ProjectInfo | null\n) {\n const errors: Record<string, boolean> = {}\n\n if (\n !fs.existsSync(options.cwd) ||\n !fs.existsSync(path.resolve(options.cwd, \"package.json\"))\n ) {\n errors[ERRORS.MISSING_DIR_OR_EMPTY_PROJECT] = true\n return {\n errors,\n config: null,\n }\n }\n\n try {\n const config = await getConfig(options.cwd, options.path, {\n featureOnly: projectInfo !== undefined,\n projectInfo,\n })\n\n return {\n errors,\n config: config!,\n }\n } catch (error) {\n console.log(\"[preFlightAdd] - \", error)\n\n logger.break()\n logger.error(\n `Make sure you are in a valid project directory. Run ${colors.cyan(\n \"npx @tiptap/cli init\"\n )} to create a new project.`\n )\n logger.break()\n process.exit(1)\n }\n}\n","import { statSync } from \"node:fs\"\nimport path from \"path\"\nimport { resolveImport } from \"@/src/utils/resolve-import\"\nimport { cosmiconfig } from \"cosmiconfig\"\nimport fg from \"fast-glob\"\nimport { loadConfig } from \"tsconfig-paths\"\nimport { z } from \"zod\"\nimport { getProjectInfo, type ProjectInfo } from \"./get-project-info\"\n\nexport const DEFAULT_COMPONENTS = \"@/components\"\nexport const DEFAULT_CONTEXTS = \"@/contexts\"\nexport const DEFAULT_HOOKS = \"@/hooks\"\nexport const DEFAULT_TIPTAP_ICONS = \"@/components/tiptap-icons\"\nexport const DEFAULT_LIB = \"@/lib\"\nexport const DEFAULT_TIPTAP_EXTENSIONS = \"@/components/tiptap-extension\"\nexport const DEFAULT_TIPTAP_NODES = \"@/components/tiptap-node\"\nexport const DEFAULT_TIPTAP_UI = \"@/components/tiptap-ui\"\nexport const DEFAULT_TIPTAP_UI_PRIMITIVES = \"@/components/tiptap-ui-primitive\"\nexport const DEFAULT_TIPTAP_UI_UTILS = \"@/components/tiptap-ui-utils\"\nexport const DEFAULT_STYLES = \"@/styles\"\n\nconst explorer = cosmiconfig(\"components\", {\n searchPlaces: [\"components.json\"],\n})\n\nexport const rawConfigSchema = z.object({\n rsc: z.coerce.boolean().default(false),\n tsx: z.coerce.boolean().default(true),\n aliases: z.object({\n components: z.string(),\n contexts: z.string().optional(),\n hooks: z.string().optional(),\n tiptapIcons: z.string().optional(),\n lib: z.string().optional(),\n tiptapExtensions: z.string().optional(),\n tiptapNodes: z.string().optional(),\n tiptapUi: z.string().optional(),\n tiptapUiPrimitives: z.string().optional(),\n tiptapUiUtils: z.string().optional(),\n styles: z.string().optional(),\n }),\n})\n\nexport const configSchema = rawConfigSchema.extend({\n overrideImports: z\n .object({\n absoluteBaseUrl: z.string(),\n paths: z.record(z.string(), z.array(z.string())),\n })\n .optional(),\n resolvedPaths: z.object({\n cwd: z.string(),\n components: z.string(),\n contexts: z.string(),\n hooks: z.string(),\n tiptapIcons: z.string(),\n lib: z.string(),\n tiptapExtensions: z.string(),\n tiptapNodes: z.string(),\n tiptapUi: z.string(),\n tiptapUiPrimitives: z.string(),\n tiptapUiUtils: z.string(),\n styles: z.string(),\n }),\n})\n\nexport const workspaceConfigSchema = z.record(z.string(), configSchema)\n\nexport type RawConfig = z.infer<typeof rawConfigSchema>\n\nexport type Config = z.infer<typeof configSchema>\n\nexport function readPathConfig(cwd: string): ReturnType<typeof loadConfig> {\n try {\n return loadConfig(cwd)\n } catch (error) {\n return {\n resultType: \"failed\",\n message: error instanceof Error ? error.message : String(error),\n }\n }\n}\n\nexport async function getConfig(\n cwd: string,\n pathOverride?: string,\n options: { featureOnly?: boolean; projectInfo?: ProjectInfo | null } = {}\n) {\n const res = await explorer.search(cwd)\n const projectInfo =\n options.projectInfo !== undefined\n ? options.projectInfo\n : await getProjectInfo(cwd, {\n forFeature: options.featureOnly,\n })\n\n const defaultAliases = {\n components: DEFAULT_COMPONENTS,\n contexts: DEFAULT_CONTEXTS,\n hooks: DEFAULT_HOOKS,\n tiptapIcons: DEFAULT_TIPTAP_ICONS,\n lib: DEFAULT_LIB,\n tiptapExtensions: DEFAULT_TIPTAP_EXTENSIONS,\n tiptapNodes: DEFAULT_TIPTAP_NODES,\n tiptapUi: DEFAULT_TIPTAP_UI,\n tiptapUiPrimitives: DEFAULT_TIPTAP_UI_PRIMITIVES,\n tiptapUiUtils: DEFAULT_TIPTAP_UI_UTILS,\n styles: DEFAULT_STYLES,\n }\n\n const applyAliasPrefix = (aliases: typeof defaultAliases, prefix: string) => {\n return Object.fromEntries(\n Object.entries(aliases).map(([key, value]) => [\n key,\n value.replace(/^@/, prefix),\n ])\n ) as typeof defaultAliases\n }\n\n if (options.featureOnly) {\n const loaded = readPathConfig(cwd)\n const paths = loaded.resultType === \"success\" ? loaded.paths : {}\n const componentKey = Object.keys(paths).find((key) =>\n /(?:^@?components|\\/components)(?:\\/\\*)?$/.test(key)\n )\n const rootKey = Object.entries(paths).find(\n ([key, targets]) =>\n key.endsWith(\"/*\") &&\n ([\"@/*\", \"~/*\"].includes(key) ||\n targets.some((target) =>\n [\"*\", \"src/*\", \"app/*\", \"resources/js/*\"].includes(\n target.replace(/^\\.\\//, \"\")\n )\n ))\n )?.[0]\n const defaults = rootKey\n ? applyAliasPrefix(defaultAliases, rootKey.slice(0, -2))\n : { ...defaultAliases }\n if (componentKey) defaults.components = componentKey.replace(/\\/\\*$/, \"\")\n const config = rawConfigSchema.parse({\n rsc: projectInfo?.isRSC ?? false,\n tsx: projectInfo?.isTsx ?? true,\n ...res?.config,\n aliases: { ...defaults, ...res?.config.aliases },\n })\n return resolveConfigPaths(\n cwd,\n config,\n pathOverride,\n path.join(cwd, projectInfo?.isSrcDir ? \"src\" : \"\", \"components\"),\n res?.config.aliases ?? {}\n )\n }\n\n let config: RawConfig\n\n if (!res) {\n let aliases = defaultAliases\n\n if (projectInfo?.aliasPrefix) {\n aliases = applyAliasPrefix(aliases, projectInfo.aliasPrefix)\n }\n\n config = rawConfigSchema.parse({\n rsc: projectInfo?.isRSC ?? false,\n tsx: projectInfo?.isTsx ?? true,\n aliases,\n })\n } else {\n const resolvedAliases = {\n ...defaultAliases,\n ...res.config.aliases,\n }\n\n if (projectInfo?.aliasPrefix) {\n config = rawConfigSchema.parse({\n ...res.config,\n aliases: applyAliasPrefix(resolvedAliases, projectInfo.aliasPrefix),\n })\n } else {\n config = rawConfigSchema.parse({\n ...res.config,\n aliases: resolvedAliases,\n })\n }\n }\n\n return await resolveConfigPaths(cwd, config, pathOverride)\n}\n\nexport async function resolveConfigPaths(\n cwd: string,\n config: RawConfig,\n pathOverride?: string,\n componentsFallback?: string,\n explicitAliases: Partial<RawConfig[\"aliases\"]> = {}\n) {\n // Read tsconfig.json.\n const loaded = readPathConfig(cwd)\n\n if (loaded.resultType === \"failed\" && !componentsFallback) {\n throw new Error(\n `Failed to load ${config.tsx ? \"tsconfig\" : \"jsconfig\"}.json. ${\n loaded.message ?? \"\"\n }`.trim()\n )\n }\n\n const tsConfig =\n loaded.resultType === \"success\"\n ? { absoluteBaseUrl: loaded.absoluteBaseUrl, paths: loaded.paths }\n : { absoluteBaseUrl: cwd, paths: {} }\n if (componentsFallback) {\n async function directory(alias: string, explicit: boolean) {\n const hasChildMapping = Object.hasOwn(tsConfig.paths, `${alias}/*`)\n if (!hasChildMapping && Object.hasOwn(tsConfig.paths, alias)) {\n const exact = await resolveImport(alias, tsConfig, false)\n if (exact) {\n const target = statSync(exact, { throwIfNoEntry: false })\n if (target ? target.isDirectory() : !/\\.[cm]?[jt]sx?$/i.test(exact))\n return exact\n }\n }\n if (pathOverride && !explicit && !hasChildMapping) return undefined\n const child = await resolveImport(\n `${alias}/__tiptap_file__`,\n tsConfig,\n explicit\n )\n return child && path.dirname(child)\n }\n const components = pathOverride\n ? path.resolve(cwd, pathOverride)\n : ((await directory(\n config.aliases.components,\n !!explicitAliases.components\n )) ?? componentsFallback)\n const resolvedPaths: Record<string, string> = { cwd, components }\n for (const [key, alias] of Object.entries(config.aliases)) {\n if (key === \"components\" || !alias) continue\n const subdirectory = path.posix.basename(alias)\n const fallback = [\"hooks\", \"lib\", \"styles\", \"contexts\"].includes(key)\n ? path.resolve(components, \"..\", subdirectory)\n : path.join(components, subdirectory)\n resolvedPaths[key] =\n (await directory(\n alias,\n !!explicitAliases[key as keyof typeof explicitAliases]\n )) ?? fallback\n }\n return configSchema.parse({\n ...config,\n overrideImports: tsConfig,\n resolvedPaths,\n })\n }\n\n if (pathOverride) {\n const resolvedPathOverride = path.isAbsolute(pathOverride)\n ? pathOverride\n : path.resolve(cwd, pathOverride)\n\n const schema = configSchema.parse({\n ...config,\n overrideImports: tsConfig,\n resolvedPaths: {\n cwd,\n components: resolvedPathOverride,\n contexts: path.resolve(resolvedPathOverride, \"..\", \"contexts\"),\n hooks: path.resolve(resolvedPathOverride, \"..\", \"hooks\"),\n tiptapIcons: path.resolve(resolvedPathOverride, \"tiptap-icons\"),\n lib: path.resolve(resolvedPathOverride, \"..\", \"lib\"),\n tiptapExtensions: path.resolve(\n resolvedPathOverride,\n \"tiptap-extension\"\n ),\n tiptapNodes: path.resolve(resolvedPathOverride, \"tiptap-node\"),\n tiptapUi: path.resolve(resolvedPathOverride, \"tiptap-ui\"),\n tiptapUiPrimitives: path.resolve(\n resolvedPathOverride,\n \"tiptap-ui-primitive\"\n ),\n tiptapUiUtils: path.resolve(resolvedPathOverride, \"tiptap-ui-utils\"),\n styles: path.resolve(resolvedPathOverride, \"..\", \"styles\"),\n },\n })\n\n return schema\n }\n\n const schema = configSchema.parse({\n ...config,\n resolvedPaths: {\n cwd,\n components: await resolveImport(config.aliases.components, tsConfig),\n contexts: config.aliases.contexts\n ? await resolveImport(config.aliases.contexts, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"..\",\n \"contexts\"\n ),\n hooks: config.aliases.hooks\n ? await resolveImport(config.aliases.hooks, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"..\",\n \"hooks\"\n ),\n tiptapIcons: config.aliases.tiptapIcons\n ? await resolveImport(config.aliases.tiptapIcons, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-icons\"\n ),\n lib: config.aliases.lib\n ? await resolveImport(config.aliases.lib, tsConfig)\n : path.resolve(\n (await resolveImport(DEFAULT_LIB, tsConfig)) ?? cwd,\n \"..\"\n ),\n tiptapExtensions: config.aliases.tiptapExtensions\n ? await resolveImport(config.aliases.tiptapExtensions, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-extension\"\n ),\n tiptapNodes: config.aliases.tiptapNodes\n ? await resolveImport(config.aliases.tiptapNodes, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-node\"\n ),\n tiptapUi: config.aliases.tiptapUi\n ? await resolveImport(config.aliases.tiptapUi, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui\"\n ),\n tiptapUiPrimitives: config.aliases.tiptapUiPrimitives\n ? await resolveImport(config.aliases.tiptapUiPrimitives, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui-primitive\"\n ),\n tiptapUiUtils: config.aliases.tiptapUiUtils\n ? await resolveImport(config.aliases.tiptapUiUtils, tsConfig)\n : path.resolve(\n (await resolveImport(config.aliases.components, tsConfig)) ?? cwd,\n \"tiptap-ui-utils\"\n ),\n styles: config.aliases.styles\n ? await resolveImport(config.aliases.styles, tsConfig)\n : path.resolve(cwd, \"styles\"),\n },\n })\n\n return schema\n}\n\n// Note: we can check for -workspace.yaml or \"workspace\" in package.json.\n// Since cwd is not necessarily the root of the project.\n// We'll instead check if ui aliases resolve to a different root.\nexport async function getWorkspaceConfig(config: Config) {\n const resolvedAliases: Record<string, Config> = {}\n\n for (const key of Object.keys(config.aliases)) {\n if (!isAliasKey(key, config)) {\n continue\n }\n\n const resolvedPath = config.resolvedPaths[key]\n const packageRoot = await findPackageRoot(\n config.resolvedPaths.cwd,\n resolvedPath\n )\n\n if (!packageRoot) {\n resolvedAliases[key] = config\n continue\n }\n\n resolvedAliases[key] = await getConfig(packageRoot)\n }\n\n const result = workspaceConfigSchema.safeParse(resolvedAliases)\n if (!result.success) {\n return null\n }\n\n return result.data\n}\n\nexport async function findPackageRoot(cwd: string, resolvedPath: string) {\n const commonRoot = findCommonRoot(cwd, resolvedPath)\n const relativePath = path.relative(commonRoot, resolvedPath)\n\n const packageRoots = await fg.glob(\"**/package.json\", {\n cwd: commonRoot,\n deep: 3,\n ignore: [\"**/node_modules/**\", \"**/dist/**\", \"**/build/**\", \"**/public/**\"],\n })\n\n const matchingPackageRoot = packageRoots\n .map((pkgPath) => path.dirname(pkgPath))\n .find((pkgDir) => relativePath.startsWith(pkgDir))\n\n return matchingPackageRoot ? path.join(commonRoot, matchingPackageRoot) : null\n}\n\nfunction isAliasKey(\n key: string,\n config: Config\n): key is keyof Config[\"aliases\"] {\n return Object.keys(config.resolvedPaths).includes(key)\n}\n\nexport function findCommonRoot(cwd: string, resolvedPath: string) {\n const parts1 = cwd.split(path.sep)\n const parts2 = resolvedPath.split(path.sep)\n const commonParts = []\n\n for (let i = 0; i < Math.min(parts1.length, parts2.length); i++) {\n if (parts1[i] !== parts2[i]) {\n break\n }\n commonParts.push(parts1[i])\n }\n\n return commonParts.join(path.sep)\n}\n","import { createMatchPath, type ConfigLoaderSuccessResult } from \"tsconfig-paths\"\n\nexport async function resolveImport(\n importPath: string,\n config: Pick<ConfigLoaderSuccessResult, \"absoluteBaseUrl\" | \"paths\">,\n matchBaseUrl = true\n) {\n return createMatchPath(\n config.absoluteBaseUrl,\n config.paths,\n undefined,\n matchBaseUrl\n )(importPath, undefined, () => true, [\".ts\", \".tsx\"])\n}\n","import path from \"path\"\nimport { FRAMEWORKS, Framework } from \"@/src/utils/frameworks\"\nimport { getPackageInfo } from \"@/src/utils/get-package-info\"\nimport fg from \"fast-glob\"\nimport fs from \"fs-extra\"\nimport {\n Config,\n RawConfig,\n getConfig,\n readPathConfig,\n resolveConfigPaths,\n} from \"@/src/utils/get-config\"\n\nexport type ProjectInfo = {\n framework: Framework\n isSrcDir: boolean\n nextAppDir?: \"app\" | \"src/app\"\n isRSC: boolean\n isTsx: boolean\n aliasPrefix: string | null\n}\n\nconst PROJECT_SHARED_IGNORE = [\n \"**/node_modules/**\",\n \".next\",\n \"public\",\n \"dist\",\n \"build\",\n]\n\nexport function getNextAppDir(cwd: string) {\n return ([\"app\", \"src/app\"] as const).find((dir) =>\n fs.existsSync(path.join(cwd, dir))\n )\n}\n\nexport async function getProjectInfo(\n cwd: string,\n options: { forFeature?: boolean } = {}\n): Promise<ProjectInfo | null> {\n const [configFiles, isSrcDir, isTsx, aliasPrefix, packageJson] =\n await Promise.all([\n fg.glob(\n \"**/{next,vite,astro,app}.config.*|gatsby-config.*|composer.json|react-router.config.*\",\n {\n cwd,\n deep: 3,\n ignore: PROJECT_SHARED_IGNORE,\n }\n ),\n fs.pathExists(path.resolve(cwd, \"src\")),\n isTypeScriptProject(cwd),\n getTsConfigAliasPrefix(cwd),\n getPackageInfo(cwd, false),\n ])\n\n const type: ProjectInfo = {\n framework: FRAMEWORKS[\"manual\"],\n isSrcDir,\n isRSC: false,\n isTsx,\n aliasPrefix,\n }\n\n // Next.js.\n if (\n configFiles.some((file) => file.startsWith(\"next.config.\")) ||\n (options.forFeature &&\n (packageJson?.dependencies?.next || packageJson?.devDependencies?.next))\n ) {\n type.nextAppDir = getNextAppDir(cwd)\n type.framework = type.nextAppDir\n ? FRAMEWORKS[\"next-app\"]\n : FRAMEWORKS[\"next-pages\"]\n type.isRSC = Boolean(type.nextAppDir)\n return type\n }\n\n // Astro.\n if (configFiles.find((file) => file.startsWith(\"astro.config.\"))?.length) {\n type.framework = FRAMEWORKS[\"astro\"]\n return type\n }\n\n // Gatsby.\n // if (configFiles.find((file) => file.startsWith(\"gatsby-config.\"))?.length) {\n // type.framework = FRAMEWORKS[\"gatsby\"]\n // return type\n // }\n\n // Laravel.\n if (configFiles.find((file) => file.startsWith(\"composer.json\"))?.length) {\n type.framework = FRAMEWORKS[\"laravel\"]\n return type\n }\n\n // Remix.\n // if (\n // Object.keys(packageJson?.dependencies ?? {}).find((dep) =>\n // dep.startsWith(\"@remix-run/\")\n // )\n // ) {\n // type.framework = FRAMEWORKS[\"remix\"]\n // return type\n // }\n\n // TanStack Start.\n if (\n configFiles.find((file) => file.startsWith(\"app.config.\"))?.length &&\n [\n ...Object.keys(packageJson?.dependencies ?? {}),\n ...Object.keys(packageJson?.devDependencies ?? {}),\n ].find((dep) => dep.startsWith(\"@tanstack/start\"))\n ) {\n type.framework = FRAMEWORKS[\"tanstack-start\"]\n return type\n }\n\n // React Router.\n if (\n configFiles.find((file) => file.startsWith(\"react-router.config.\"))?.length\n ) {\n type.framework = FRAMEWORKS[\"react-router\"]\n return type\n }\n\n // Vite.\n // Some Remix templates also have a vite.config.* file.\n // We'll assume that it got caught by the Remix check above.\n if (configFiles.find((file) => file.startsWith(\"vite.config.\"))?.length) {\n type.framework = FRAMEWORKS[\"vite\"]\n return type\n }\n\n return type\n}\n\nexport async function getTsConfigAliasPrefix(cwd: string) {\n const tsConfig = readPathConfig(cwd)\n\n if (\n tsConfig?.resultType === \"failed\" ||\n !Object.entries(tsConfig?.paths).length\n ) {\n return null\n }\n\n // This assume that the first alias is the prefix.\n for (const [alias, paths] of Object.entries(tsConfig.paths)) {\n if (\n paths.includes(\"./*\") ||\n paths.includes(\"./src/*\") ||\n paths.includes(\"./app/*\") ||\n paths.includes(\"./resources/js/*\") // Laravel.\n ) {\n return alias.replace(/\\/\\*$/, \"\") ?? null\n }\n }\n\n // Use the first alias as the prefix.\n return Object.keys(tsConfig?.paths)?.[0].replace(/\\/\\*$/, \"\") ?? null\n}\n\nexport async function isTypeScriptProject(cwd: string) {\n const files = await fg.glob(\"tsconfig.*\", {\n cwd,\n deep: 1,\n ignore: PROJECT_SHARED_IGNORE,\n })\n\n return files.length > 0\n}\n\nexport async function getProjectConfig(\n cwd: string,\n defaultProjectInfo: ProjectInfo | null = null\n): Promise<Config | null> {\n const [existingConfig, projectInfo] = await Promise.all([\n getConfig(cwd),\n !defaultProjectInfo\n ? getProjectInfo(cwd)\n : Promise.resolve(defaultProjectInfo),\n ])\n\n if (existingConfig) {\n return existingConfig\n }\n\n if (!projectInfo) {\n return null\n }\n\n const config: RawConfig = {\n rsc: projectInfo.isRSC,\n tsx: projectInfo.isTsx,\n aliases: {\n components: `${projectInfo.aliasPrefix}/components`,\n contexts: `${projectInfo.aliasPrefix}/contexts`,\n hooks: `${projectInfo.aliasPrefix}/hooks`,\n tiptapIcons: `${projectInfo.aliasPrefix}/components/tiptap-icons`,\n lib: `${projectInfo.aliasPrefix}/lib`,\n tiptapExtensions: `${projectInfo.aliasPrefix}/components/tiptap-extensions`,\n tiptapNodes: `${projectInfo.aliasPrefix}/components/tiptap-nodes`,\n tiptapUi: `${projectInfo.aliasPrefix}/components/tiptap-ui`,\n tiptapUiPrimitives: `${projectInfo.aliasPrefix}/components/tiptap-ui-primitives`,\n tiptapUiUtils: `${projectInfo.aliasPrefix}/components/tiptap-ui-utils`,\n styles: `${projectInfo.aliasPrefix}/styles`,\n },\n }\n\n return await resolveConfigPaths(cwd, config)\n}\n","export const FRAMEWORKS = {\n \"next-app\": {\n name: \"next-app\",\n label: \"Next.js\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n \"next-pages\": {\n name: \"next-pages\",\n label: \"Next.js\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n // remix: {\n // name: \"remix\",\n // label: \"Remix\",\n // links: {\n // installation: \"https://tiptap.dev/docs/ui-components/install/remix\",\n // },\n // },\n \"react-router\": {\n name: \"react-router\",\n label: \"React Router\",\n links: {\n installation:\n \"https://tiptap.dev/docs/ui-components/install/react-router\",\n },\n },\n vite: {\n name: \"vite\",\n label: \"Vite\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/vite\",\n },\n },\n astro: {\n name: \"astro\",\n label: \"Astro\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/astro\",\n },\n },\n laravel: {\n name: \"laravel\",\n label: \"Laravel\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/laravel\",\n },\n },\n \"tanstack-start\": {\n name: \"tanstack-start\",\n label: \"TanStack Start\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/manual\",\n },\n },\n // gatsby: {\n // name: \"gatsby\",\n // label: \"Gatsby\",\n // links: {\n // installation: \"https://tiptap.dev/docs/ui-components/install/gatsby\",\n // },\n // },\n manual: {\n name: \"manual\",\n label: \"Manual\",\n links: {\n installation: \"https://tiptap.dev/docs/ui-components/install/next\",\n },\n },\n} as const\n\nexport type Framework = (typeof FRAMEWORKS)[keyof typeof FRAMEWORKS]\n","import path from \"path\"\nimport fs from \"fs-extra\"\nimport { type PackageJson } from \"type-fest\"\n\nexport function getPackageInfo(\n cwd: string = \"\",\n shouldThrow: boolean = true\n): PackageJson | null {\n const packageJsonPath = path.join(cwd, \"package.json\")\n\n return fs.readJSONSync(packageJsonPath, {\n throws: shouldThrow,\n }) as PackageJson\n}\n\nexport function getInstalledPackageVersion(\n cwd: string,\n name: string\n): string | null {\n for (let dir = cwd; ; dir = path.dirname(dir)) {\n try {\n const manifest = JSON.parse(\n fs.readFileSync(\n path.join(dir, \"node_modules\", name, \"package.json\"),\n \"utf8\"\n )\n )\n return typeof manifest.version === \"string\" ? manifest.version : null\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n if (dir === path.dirname(dir)) return null\n }\n}\n","import chalk from \"chalk\"\n\nexport const colors = {\n cyan: chalk.cyan,\n magenta: chalk.magenta,\n gray: chalk.gray,\n white: chalk.white,\n yellow: chalk.yellow,\n green: chalk.green,\n red: chalk.red,\n blue: chalk.blue,\n reset: chalk.reset,\n dim: chalk.dim,\n bold: chalk.bold,\n whiteBold: chalk.white.bold,\n}\n","import { colors } from \"@/src/utils/colors\"\n\nexport type Logger = {\n error: (...args: unknown[]) => void\n warn: (...args: unknown[]) => void\n info: (...args: unknown[]) => void\n success: (...args: unknown[]) => void\n log: (...args: unknown[]) => void\n break: () => void\n}\n\nconst join = (args: unknown[]) => args.map(String).join(\" \")\n\nexport const logger: Logger = {\n error(...args: unknown[]) {\n console.log(colors.red(join(args)))\n },\n warn(...args: unknown[]) {\n console.log(colors.yellow(join(args)))\n },\n info(...args: unknown[]) {\n console.log(colors.cyan(join(args)))\n },\n success(...args: unknown[]) {\n console.log(colors.green(join(args)))\n },\n log(...args: unknown[]) {\n console.log(join(args))\n },\n break() {\n console.log(\"\")\n },\n}\n","import path from \"node:path\"\nimport { assertCanPreviewPaidComponents } from \"./auth-check\"\nimport { canPrompt } from \"./cli-ui\"\nimport { getWorkspaceConfig, type Config } from \"./get-config\"\nimport { getProjectInfo } from \"./get-project-info\"\nimport { planStyleImports } from \"./auto-import-styles\"\nimport {\n filterDevDependenciesByFramework,\n getResolvedRegistryItems,\n} from \"./registry\"\nimport {\n registryFeatureSchema,\n registryModulePathSchema,\n type RegistryItem,\n type RegistryFeature,\n} from \"./registry/schema\"\nimport { spinner } from \"./spinner\"\nimport { ensureTiptapRegistryAccess } from \"./tiptap-registry-access\"\nimport {\n getTemplateDemoImport,\n planNewViteEditorEntry,\n planCollaboration,\n} from \"./plan-collaboration\"\nimport { planDependencies } from \"./updaters/plan-dependencies\"\nimport { planEditorExtension } from \"./plan-editor-extension\"\nimport { installPlannedPackages } from \"./install-planned-packages\"\nimport {\n applyFiles,\n getInstallDestination,\n readExistingFile,\n keepExisting,\n planFiles,\n type PlannedFile,\n} from \"./updaters/update-files\"\n\ntype InstallOptions = {\n projectInfo?: Awaited<ReturnType<typeof getProjectInfo>>\n overwrite?: boolean\n interactive?: boolean\n silent?: boolean\n isNewProject?: boolean\n features?: RegistryFeature[]\n editorPath?: string\n}\n\ninterface FileGroup {\n config: Config\n items: RegistryItem[]\n dependencies: string[]\n devDependencies: string[]\n privateNpmPackages: string[]\n}\n\nasync function getFileGroups(\n components: string[],\n config: Config,\n project: Awaited<ReturnType<typeof getProjectInfo>>\n): Promise<FileGroup[]> {\n const items = await getResolvedRegistryItems(components)\n assertCanPreviewPaidComponents(items)\n const workspace = config.overrideImports\n ? null\n : await getWorkspaceConfig(config)\n const sharedUi = workspace?.tiptapUi\n const byName = new Map(items.map((item) => [item.name, item]))\n const owners = new Map<Config, Set<RegistryItem>>()\n\n function collect(name: string, consumer: Config) {\n const item = byName.get(name)\n if (!item) throw new Error(`Registry item ${name} is missing.`)\n const target = item.type === \"registry:ui\" && sharedUi ? sharedUi : consumer\n let owned = owners.get(target)\n if (!owned) {\n owned = new Set()\n owners.set(target, owned)\n }\n if (owned.has(item)) return\n owned.add(item)\n for (const dependency of item.registryDependencies ?? []) {\n collect(dependency, target)\n }\n }\n\n if (sharedUi && sharedUi.resolvedPaths.cwd !== config.resolvedPaths.cwd) {\n for (const component of components) collect(component, config)\n } else {\n owners.set(config, new Set(items))\n }\n\n const groups: FileGroup[] = []\n for (const [target, owned] of owners) {\n const entries = [...owned]\n groups.push({\n config: target,\n items: entries,\n dependencies: entries.flatMap((item) => item.dependencies ?? []),\n devDependencies: entries.flatMap((item) => item.devDependencies ?? []),\n privateNpmPackages: [\n ...new Set(\n entries.flatMap((item) => item.meta?.privateNpmPackages ?? [])\n ),\n ],\n })\n }\n if (project) {\n for (const group of groups) {\n group.devDependencies = filterDevDependenciesByFramework(\n group.devDependencies,\n project.framework.name\n )\n }\n }\n return groups\n}\n\nasync function resolveEditorFile(\n template: RegistryItem | undefined,\n requested: string | undefined,\n files: Map<string, PlannedFile>,\n config: Config\n) {\n if (template) {\n const declared = registryModulePathSchema.safeParse(template.meta?.editor)\n if (!declared.success)\n throw new Error(\n `The registry must declare a valid editor module for ${template.name}.`\n )\n const source = declared.data\n if (!template.files?.some((file) => file.path === source))\n throw new Error(\"The template must ship its declared editor.\")\n const editor = [...files.values()].find(\n (file) => file.registryPath === source\n )\n if (!editor)\n throw new Error(\"The template editor is missing from the install plan.\")\n return editor\n }\n if (!requested) return\n const filePath = path.resolve(config.resolvedPaths.cwd, requested)\n if (!/\\.[jt]sx?$/.test(filePath) || filePath.endsWith(\".d.ts\"))\n throw new Error(\"Choose a JavaScript or TypeScript editor file.\")\n const realPath = await getInstallDestination(filePath, config)\n if (files.has(realPath))\n throw new Error(\"Choose an editor outside the feature setup files.\")\n const before = await readExistingFile(realPath)\n if (before === null)\n throw new Error(`Editor file does not exist: ${requested}`)\n const editor: PlannedFile = {\n path: filePath,\n realPath,\n before,\n after: before,\n status: \"identical\",\n }\n files.set(realPath, editor)\n return editor\n}\n\nasync function planFeatures(\n features: RegistryFeature[],\n components: string[],\n records: RegistryItem[],\n files: Map<string, PlannedFile>,\n config: Config,\n requestedEditor: string | undefined,\n mountViteEntry: boolean,\n overwrite = false\n) {\n let collaboration: ReturnType<typeof planCollaboration> | undefined\n let extensionSetup: ReturnType<typeof planEditorExtension> | undefined\n if (!features.length) return { collaboration, extensionSetup }\n const template = records.find(\n (item) =>\n item.type === \"registry:template\" && components.includes(item.name)\n )\n const editor = features.every(\n (feature) => feature.integration.kind === \"files\"\n )\n ? undefined\n : await resolveEditorFile(template, requestedEditor, files, config)\n const entries = [...files.values()]\n const demoImport = await getTemplateDemoImport(\n template,\n editor,\n entries,\n config\n )\n const conflicts = entries.filter((file) => file.status === \"conflict\")\n const recipeItems = new Set(\n features.flatMap((feature) => [\n ...feature.items,\n ...Object.values(feature.frameworkItems ?? {}).flat(),\n ])\n )\n const featureSources = new Set(\n records\n .filter((item) => recipeItems.has(item.name))\n .flatMap((item) => item.files?.map((file) => file.path) ?? [])\n )\n const protectedSources = new Set(\n features.flatMap(({ integration }) =>\n integration.kind === \"collaboration\"\n ? [integration.config, integration.tokenRoute]\n : []\n )\n )\n for (const file of entries) {\n const source = file.registryPath\n if (\n file.status === \"conflict\" &&\n overwrite &&\n source &&\n featureSources.has(source) &&\n !protectedSources.has(source) &&\n file !== editor\n ) {\n file.status = \"update\"\n } else if (\n components.length === 0 ||\n (components.length === 1 && template) ||\n (source &&\n (featureSources.has(source) ||\n template?.files?.some((item) => item.path === source)))\n ) {\n keepExisting(file)\n }\n }\n for (const feature of features) {\n const { integration } = feature\n const sources = new Set(\n records\n .filter((item) => feature.items.includes(item.name))\n .flatMap((item) => item.files?.map((file) => file.path) ?? [])\n )\n if (integration.kind === \"editor-extension\") {\n if (!sources.has(integration.extension))\n throw new Error(\"The extension module must belong to the feature.\")\n extensionSetup = planEditorExtension(\n integration,\n files,\n editor,\n config.resolvedPaths.cwd\n )\n } else if (integration.kind === \"collaboration\") {\n if (!sources.has(integration.wrapper) || !sources.has(integration.config))\n throw new Error(\n \"The Collaboration wrapper and configuration must belong to the feature.\"\n )\n const customPage = conflicts.find((file) =>\n template?.files?.some(\n (source) =>\n source.path === file.registryPath && source.type === \"registry:page\"\n )\n )\n collaboration = planCollaboration(\n integration,\n files,\n editor,\n config,\n conflicts.some((file) => file.registryPath === integration.tokenRoute),\n customPage && path.relative(config.resolvedPaths.cwd, customPage.path),\n demoImport\n )\n }\n }\n const setup = collaboration ?? extensionSetup\n if (\n mountViteEntry &&\n template &&\n editor &&\n setup &&\n setup.status !== \"pending\"\n ) {\n const entry = await planNewViteEditorEntry(config, editor)\n if (files.has(entry.realPath))\n throw new Error(\n `Registry files and the Vite editor both target ${entry.path}.`\n )\n files.set(entry.realPath, entry)\n setup.entryPath = path.relative(config.resolvedPaths.cwd, entry.path)\n }\n return { collaboration, extensionSetup }\n}\n\nexport async function planComponents(\n components: string[],\n config: Config,\n options: Pick<\n InstallOptions,\n \"features\" | \"editorPath\" | \"isNewProject\" | \"projectInfo\" | \"overwrite\"\n > = {}\n) {\n const features = (options.features ?? []).map((feature) =>\n registryFeatureSchema.parse(feature)\n )\n const project =\n options.projectInfo !== undefined\n ? options.projectInfo\n : await getProjectInfo(config.resolvedPaths.cwd, {\n forFeature: features.length > 0,\n })\n const setupItems = features.flatMap((feature) => [\n ...feature.items,\n ...((project && feature.frameworkItems?.[project.framework.name]) || []),\n ])\n const selected = [...new Set([...components, ...setupItems])]\n const groups = await getFileGroups(selected, config, project)\n const files = new Map<string, PlannedFile>()\n const packages = []\n for (const group of groups) {\n const dependencies = await planDependencies(\n group.dependencies,\n group.devDependencies,\n group.config,\n components.length === 0 ? features[0]?.label : undefined\n )\n // Each package-manager operation can fetch compatible dependencies already in the manifest.\n const privateNpmPackages =\n dependencies.dependencies.length ||\n dependencies.devDependencies.length ||\n dependencies.promotions.length\n ? group.privateNpmPackages\n : []\n packages.push({ config: group.config, ...dependencies, privateNpmPackages })\n for (const file of await planFiles(\n group.items.flatMap((item) => item.files ?? []),\n group.config,\n group.config.resolvedPaths.cwd === config.resolvedPaths.cwd\n ? project\n : undefined\n )) {\n const previous = files.get(file.realPath)\n if (previous && previous.after !== file.after) {\n throw new Error(\n `Registry items provide different contents for ${file.path}.`\n )\n }\n files.set(file.realPath, file)\n }\n }\n\n const { collaboration, extensionSetup } = await planFeatures(\n features,\n components,\n groups.flatMap((group) => group.items),\n files,\n config,\n options.editorPath,\n Boolean(options.isNewProject && project?.framework.name === \"vite\"),\n options.overwrite\n )\n const styles = await planStyleImports(\n [...files.values()].map((file) => file.path),\n config,\n project?.framework\n )\n if (styles.change) {\n if (files.has(styles.change.realPath))\n throw new Error(\n `Registry files and stylesheet imports both target ${styles.change.path}.`\n )\n files.set(styles.change.realPath, styles.change)\n }\n return {\n files: [...files.values()],\n packages,\n styles: styles.result,\n collaboration,\n extensionSetup,\n }\n}\n\nexport type ComponentPlan = Awaited<ReturnType<typeof planComponents>>\n\nexport async function addComponents(\n components: string[],\n config: Config,\n options: InstallOptions\n) {\n const progress = spinner(\"Checking registry\", {\n silent: options.silent,\n }).start()\n const plan = await planComponents(components, config, options).finally(() =>\n progress.stop()\n )\n const interactive = options.interactive ?? (!options.silent && canPrompt())\n for (const group of plan.packages) {\n if (group.privateNpmPackages.length) {\n await ensureTiptapRegistryAccess(\n group.privateNpmPackages,\n group.config.resolvedPaths.cwd,\n { interactive }\n )\n }\n }\n await installPlannedPackages(plan.packages, { ...options, interactive })\n const result = await applyFiles(plan.files, config.resolvedPaths.cwd, options)\n if (result.errors.length) {\n const failures = result.errors\n .map(({ file, error }) => ` ${file}: ${error}`)\n .join(\"\\n\")\n throw new Error(\n `Installation incomplete. ${result.filesCreated.length} files created, ${result.filesUpdated.length} updated.\\n${failures}`\n )\n }\n return {\n ...result,\n styles: plan.styles,\n collaboration: plan.collaboration,\n extensionSetup: plan.extensionSetup,\n }\n}\n","import fetch from \"node-fetch\"\nimport { HttpsProxyAgent } from \"https-proxy-agent\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { colors } from \"@/src/utils/colors\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\nimport { saveAuthToken, type PackageManager } from \"./package-manager-config\"\nimport { TIPTAP_ORIGIN } from \"./registry\"\n\nconst AUTH_API_URL = `${TIPTAP_ORIGIN}/api/cli/v1`\n\ntype LoginResponse = {\n token?: unknown\n authToken?: unknown\n}\n\ntype PlanResponse = Array<{\n name: string\n}>\n\ntype AuthTokens = {\n bearerToken?: string\n authToken: string\n}\n\nexport type AuthResult = {\n success: boolean\n tokens?: AuthTokens\n error?: string\n}\n\nexport type AuthStatus = {\n authenticated: boolean\n user?: string\n plans?: string[]\n expires?: string | null\n token?: string\n}\n\nconst httpAgent = process.env.https_proxy\n ? new HttpsProxyAgent(process.env.https_proxy)\n : undefined\n\nasync function getApiErrorMessage(response: {\n clone: () => { json: () => Promise<unknown> }\n}): Promise<string | null> {\n try {\n const payload = await response.clone().json()\n\n if (\n payload &&\n typeof payload === \"object\" &&\n \"error\" in payload &&\n typeof payload.error === \"string\"\n ) {\n return payload.error\n }\n\n if (\n payload &&\n typeof payload === \"object\" &&\n \"message\" in payload &&\n typeof payload.message === \"string\"\n ) {\n return payload.message\n }\n } catch {\n return null\n }\n\n return null\n}\n\nfunction getAuthErrorMessage(\n response: { status: number },\n apiErrorMessage?: string | null\n): string {\n switch (response.status) {\n case 400:\n return \"The authentication request was not accepted. Please check your email and password, then try again.\"\n case 401:\n return \"Invalid email or password. Please check your credentials and try again.\"\n case 403:\n return \"Your account is not allowed to use registry authentication. Please check your Tiptap Cloud account access.\"\n case 429:\n return \"Too many login attempts. Please wait a moment and try again.\"\n default:\n if (apiErrorMessage && response.status >= 500) {\n return apiErrorMessage\n }\n\n if (response.status >= 500) {\n return \"Tiptap authentication is temporarily unavailable. Please try again later.\"\n }\n\n return \"Authentication failed. Please try again.\"\n }\n}\n\nfunction getPlansErrorMessage(\n response: { status: number },\n apiErrorMessage?: string | null\n): string {\n switch (response.status) {\n case 401:\n case 403:\n return \"Your login succeeded, but your session could not be verified. Please run tiptap login again.\"\n case 429:\n return \"Your plans could not be loaded because there were too many requests. Please wait a moment and try again.\"\n default:\n if (apiErrorMessage && response.status >= 500) {\n return apiErrorMessage\n }\n\n if (response.status >= 500) {\n return \"Your plans could not be loaded because Tiptap Cloud is temporarily unavailable. Please try again later.\"\n }\n\n return \"Your plans could not be loaded. Please try again.\"\n }\n}\n\n/**\n * Authenticate a user with the Tiptap registry\n */\nexport async function authenticateUser({\n email,\n password,\n packageManager,\n writeConfig = true,\n registryOnly = false,\n cwd,\n}: {\n email?: string\n password?: string\n packageManager: PackageManager\n writeConfig?: boolean\n registryOnly?: boolean\n cwd: string\n}): Promise<AuthResult> {\n const loginSpinner = spinner(\n \"Authenticating with Tiptap registry...\"\n )?.start()\n\n try {\n if (!email || !password) {\n loginSpinner?.fail(\"Authentication failed\")\n return { success: false, error: \"Invalid credentials\" }\n }\n\n const tokens = await requestAuthTokens(email, password)\n\n if (!registryOnly) {\n if (!tokens.bearerToken) {\n throw new Error(\"Tiptap did not return a valid source login token.\")\n }\n const plansResponse = await fetch(`${AUTH_API_URL}/plans`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${tokens.bearerToken}`,\n },\n agent: httpAgent,\n redirect: \"error\",\n })\n\n if (!plansResponse.ok) {\n loginSpinner?.fail(\"Authentication failed (could not load user plans)\")\n const apiErrorMessage = await getApiErrorMessage(plansResponse)\n return {\n success: false,\n error: getPlansErrorMessage(plansResponse, apiErrorMessage),\n }\n }\n\n const plans = (await plansResponse.json()) as PlanResponse\n const userPlans = plans.map((plan) => plan.name)\n\n if (!userPlans.length) {\n loginSpinner?.fail(\"Authentication failed (no active plans)\")\n return { success: false, error: \"No active plans found for user\" }\n }\n\n tokenStorage.setBearerToken(tokens.bearerToken, {\n email,\n plans: userPlans,\n })\n } else if (\n tokenStorage.getBearerToken() &&\n tokenStorage.getUserInfo().email !== email\n ) {\n tokenStorage.clearSession()\n if (tokenStorage.getBearerToken()) {\n throw new Error(\n \"Could not clear the previous template login. Check the CLI credential file permissions before switching accounts.\"\n )\n }\n }\n tokenStorage.setAuthToken(tokens.authToken)\n\n if (writeConfig) {\n const success = await saveAuthToken(tokens.authToken, packageManager, cwd)\n if (!success) {\n loginSpinner?.fail(\"Failed to save authentication token\")\n return { success: false, error: \"Could not save authentication token\" }\n }\n }\n\n loginSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \"Authentication successful\",\n })\n return { success: true, tokens }\n } catch (error) {\n loginSpinner?.fail(\"Authentication failed\")\n return {\n success: false,\n error:\n error instanceof Error\n ? error.message\n : \"Unknown error during authentication\",\n }\n }\n}\n\n/**\n * Request an authentication token from the API\n */\nasync function requestAuthTokens(\n email: string,\n password: string\n): Promise<AuthTokens> {\n const response = await fetch(`${AUTH_API_URL}/login`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify({ email, password }),\n agent: httpAgent,\n redirect: \"error\",\n })\n\n if (!response.ok) {\n const apiErrorMessage = await getApiErrorMessage(response)\n throw new Error(getAuthErrorMessage(response, apiErrorMessage))\n }\n\n const data = (await response.json()) as LoginResponse\n if (\n typeof data?.authToken !== \"string\" ||\n !data.authToken ||\n /\\s/.test(data.authToken)\n ) {\n throw new Error(\"Tiptap did not return a package registry token.\")\n }\n\n return {\n bearerToken:\n typeof data.token === \"string\" && !/\\s/.test(data.token)\n ? data.token\n : undefined,\n authToken: data.authToken,\n }\n}\n\n/**\n * Check if user is authenticated with Tiptap registry\n */\nexport async function checkAuthStatus(): Promise<AuthStatus> {\n try {\n const bearerToken = tokenStorage.getBearerToken()\n\n if (!bearerToken) {\n return { authenticated: false }\n }\n\n if (!tokenStorage.isValidToken()) {\n return { authenticated: false }\n }\n\n // Use plans API to verify token is still valid\n let userPlans: string[] = []\n try {\n const plansResponse = await fetch(`${AUTH_API_URL}/plans`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${bearerToken}`,\n },\n agent: httpAgent,\n redirect: \"error\",\n })\n\n if (!plansResponse.ok) {\n if (plansResponse.status === 401) {\n tokenStorage.clearSession()\n }\n return { authenticated: false }\n }\n\n const plans = (await plansResponse.json()) as PlanResponse\n userPlans = plans.map((plan) => plan.name)\n\n // Update stored plans\n const userInfo = tokenStorage.getUserInfo()\n tokenStorage.setBearerToken(bearerToken, {\n email: userInfo.email,\n plans: userPlans,\n })\n } catch (error) {\n return { authenticated: false }\n }\n\n const userInfo = tokenStorage.getUserInfo()\n const expiration = tokenStorage.getTokenExpiration()\n\n return {\n authenticated: true,\n user: userInfo.email || \"unknown user\",\n plans: userPlans,\n expires: expiration,\n token: bearerToken,\n }\n } catch (error) {\n logger.error(\n `Auth status check error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return { authenticated: false }\n }\n}\n\n/**\n * Logout user from Tiptap registry\n */\nexport async function logoutUser(): Promise<{\n success: boolean\n error?: string\n}> {\n try {\n const bearerToken = tokenStorage.getBearerToken()\n\n if (bearerToken) {\n const response = await fetch(`${AUTH_API_URL}/logout`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${bearerToken}`,\n },\n agent: httpAgent,\n redirect: \"error\",\n })\n\n if (!response.ok) {\n logger.warn(\"Logout API call failed, but clearing local tokens anyway\")\n }\n }\n\n tokenStorage.clearSession()\n return { success: true }\n } catch (error) {\n tokenStorage.clearSession()\n return {\n success: false,\n error:\n error instanceof Error ? error.message : \"Unknown error during logout\",\n }\n }\n}\n\n/**\n * Check if user has a specific plan\n */\nexport function userHasPlan(planName: string): boolean {\n return tokenStorage.hasPlan(planName)\n}\n\n/**\n * Check if user has any of the specified plans\n */\nexport function userHasAnyPlan(planNames: string[]): boolean {\n return planNames.some((plan) => tokenStorage.hasPlan(plan))\n}\n\n/**\n * Get user's plans\n */\nexport function getUserPlans(): string[] {\n return tokenStorage.getUserInfo().plans || []\n}\n","import ora, { type Options } from \"ora\"\nimport { colors } from \"@/src/utils/colors\"\n\n// Custom Tiptap-style spinner frames that resemble a typewriter cursor\nconst tiptapSpinner = {\n frames: [\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n `${colors.cyan(\"█\")}`, // Full block (cursor visible)\n ` `, // Space (cursor hidden)\n ` `, // Space (cursor hidden)\n ` `, // Space (cursor hidden)\n ],\n interval: 200, // Typewriter-like blinking speed\n}\n\nexport function spinner(\n text: Options[\"text\"],\n options?: {\n silent?: boolean\n }\n) {\n return ora({\n text: text,\n spinner: tiptapSpinner,\n color: \"cyan\",\n isSilent: options?.silent,\n })\n}\n","import Conf from \"conf\"\nimport fs from \"fs-extra\"\nimport type { Logger } from \"./logger\"\n\nexport interface TokenConfig {\n bearerToken?: string\n authToken?: string\n email?: string\n loginDate?: string\n packageLoginDate?: string\n plans?: string[]\n licenseAccepted?: boolean\n licenseAcceptedDate?: string\n}\n\nfunction expiresAt(loginDate: string | undefined): Date | undefined {\n if (!loginDate) return undefined\n const expiration = new Date(loginDate)\n expiration.setMonth(expiration.getMonth() + 11)\n return expiration\n}\n\nexport class TokenStorage {\n private config: Conf<TokenConfig>\n private logger: Logger\n\n constructor(logger: Logger) {\n this.logger = logger\n this.config = new Conf<TokenConfig>({\n projectName: \"tiptap-cli\",\n configFileMode: 0o600,\n clearInvalidConfig: true, // auto-reset if file is corrupted\n schema: {\n bearerToken: { type: \"string\" },\n authToken: { type: \"string\" },\n email: { type: \"string\" },\n loginDate: { type: \"string\" },\n packageLoginDate: { type: \"string\" },\n plans: { type: \"array\", items: { type: \"string\" }, default: [] },\n licenseAccepted: { type: \"boolean\" },\n licenseAcceptedDate: { type: \"string\" },\n },\n })\n if (process.platform !== \"win32\" && fs.existsSync(this.config.path)) {\n try {\n fs.chmodSync(this.config.path, 0o600)\n } catch {\n throw new Error(\"Could not protect the CLI credential file\")\n }\n }\n }\n\n private safeError(prefix: string, error: unknown) {\n try {\n this.logger.error(prefix)\n } catch {\n // never throw from logging\n }\n }\n\n setBearerToken(\n token: string,\n userInfo?: { email?: string; plans?: string[] }\n ): void {\n try {\n // Older stores used the source login date for both credentials.\n if (\n this.config.has(\"authToken\") &&\n !this.config.has(\"packageLoginDate\") &&\n this.config.has(\"loginDate\")\n ) {\n this.config.set(\"packageLoginDate\", this.config.get(\"loginDate\"))\n }\n this.config.set(\"bearerToken\", token)\n this.config.set(\"loginDate\", new Date().toISOString())\n if (userInfo?.email) this.config.set(\"email\", userInfo.email)\n if (userInfo?.plans) this.config.set(\"plans\", userInfo.plans)\n } catch (e) {\n this.safeError(\"Failed to store bearer token\", e)\n }\n }\n\n getBearerToken(): string | null {\n try {\n return this.config.get(\"bearerToken\") ?? null\n } catch (e) {\n this.safeError(\"Failed to retrieve bearer token\", e)\n return null\n }\n }\n\n setAuthToken(\n token: string,\n userInfo?: { email?: string; plans?: string[] }\n ): void {\n try {\n this.config.set({\n authToken: token,\n packageLoginDate: new Date().toISOString(),\n })\n if (userInfo?.email) this.config.set(\"email\", userInfo.email)\n if (userInfo?.plans) this.config.set(\"plans\", userInfo.plans)\n } catch (e) {\n this.safeError(\"Failed to store auth token\", e)\n }\n }\n\n getAuthToken(): string | null {\n try {\n const token = this.config.get(\"authToken\")\n if (!token) return null\n const expiry = expiresAt(\n this.config.get(\"packageLoginDate\") ?? this.config.get(\"loginDate\")\n )\n if (expiry && expiry.getTime() <= Date.now()) {\n this.config.delete(\"authToken\")\n this.config.delete(\"packageLoginDate\")\n return null\n }\n return token\n } catch (e) {\n this.safeError(\"Failed to retrieve auth token\", e)\n return null\n }\n }\n\n getUserInfo(): { email?: string; plans: string[]; loginDate?: string } {\n return {\n email: this.config.get(\"email\"),\n plans: this.config.get(\"plans\") ?? [],\n loginDate: this.config.get(\"loginDate\"),\n }\n }\n\n getTokenExpiration(): string | null {\n return expiresAt(this.config.get(\"loginDate\"))?.toISOString() ?? null\n }\n\n isValidToken(): boolean {\n if (!this.getBearerToken()) return Boolean(this.getAuthToken())\n const expiry = expiresAt(this.config.get(\"loginDate\"))\n if (!expiry || expiry.getTime() > Date.now()) return true\n // Read legacy package credentials before removing their fallback login date.\n this.getAuthToken()\n this.config.delete(\"bearerToken\")\n this.config.delete(\"email\")\n this.config.delete(\"loginDate\")\n this.config.delete(\"plans\")\n return false\n }\n\n clear(): void {\n try {\n this.config.clear()\n } catch (e) {\n this.safeError(\"Failed to clear token storage\", e)\n }\n }\n\n clearSession(): void {\n try {\n this.config.delete(\"bearerToken\")\n this.config.delete(\"authToken\")\n this.config.delete(\"packageLoginDate\")\n this.config.delete(\"email\")\n this.config.delete(\"loginDate\")\n this.config.delete(\"plans\")\n } catch (e) {\n this.safeError(\"Failed to clear token storage\", e)\n }\n }\n\n hasPlan(planName: string): boolean {\n const plans = this.config.get(\"plans\") ?? []\n return Array.isArray(plans) && plans.includes(planName)\n }\n\n setLicenseAccepted(): void {\n try {\n this.config.set(\"licenseAccepted\", true)\n this.config.set(\"licenseAcceptedDate\", new Date().toISOString())\n } catch (e) {\n this.safeError(\"Failed to store license acceptance\", e)\n }\n }\n\n hasAcceptedLicense(): boolean {\n try {\n return this.config.get(\"licenseAccepted\") ?? false\n } catch (e) {\n this.safeError(\"Failed to retrieve license acceptance\", e)\n return false\n }\n }\n\n clearLicenseAcceptance(): void {\n try {\n this.config.delete(\"licenseAccepted\")\n this.config.delete(\"licenseAcceptedDate\")\n } catch (e) {\n this.safeError(\"Failed to clear license acceptance\", e)\n }\n }\n}\n","import { logger } from \"./logger\"\nimport { TokenStorage } from \"./token-storage\"\n\nexport const tokenStorage = new TokenStorage(logger)\n","import fs from \"fs-extra\"\nimport path from \"path\"\nimport os from \"os\"\nimport { execa } from \"execa\"\nimport { logger } from \"@/src/utils/logger\"\nimport yaml from \"yaml\"\nimport mapWorkspaces from \"@npmcli/map-workspaces\"\n\nconst TIPTAP_REGISTRY = \"https://registry.tiptap.dev/\"\nconst AUTH_TOKEN_KEY = \"//registry.tiptap.dev/:_authToken\"\nconst TIPTAP_PRO_REGISTRY_KEY = \"@tiptap-pro:registry\"\n\nexport type PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\"\n\nclass UnsafeConfigError extends Error {}\n\nexport async function getRegistryConfigDirectory(\n cwd: string,\n manager: PackageManager\n) {\n const start = path.resolve(cwd)\n if (manager === \"bun\") {\n const { stdout, stderr, exitCode } = await execa(\"bun\", [\"pm\", \"bin\"], {\n cwd: start,\n reject: false,\n })\n if (exitCode !== 0 && stderr.includes(\"No package.json was found\"))\n return start\n const bin = stdout.trim()\n const modules = path.dirname(bin)\n if (\n exitCode !== 0 ||\n !path.isAbsolute(bin) ||\n path.basename(bin) !== \".bin\" ||\n path.basename(modules) !== \"node_modules\"\n ) {\n throw new Error(`Could not find Bun's project directory from ${start}.`)\n }\n return path.dirname(modules)\n }\n if (manager !== \"npm\" && manager !== \"pnpm\") return start\n\n let npmProject: string | undefined\n for (let dir = start; ; dir = path.dirname(dir)) {\n if (\n manager === \"pnpm\" &&\n (await fs.pathExists(path.join(dir, \"pnpm-workspace.yaml\")))\n )\n return dir\n if (manager === \"npm\") {\n const manifest = path.join(dir, \"package.json\")\n const hasManifest = await fs.pathExists(manifest)\n if (\n !npmProject &&\n (hasManifest || (await fs.pathExists(path.join(dir, \"node_modules\"))))\n ) {\n npmProject = dir\n } else if (npmProject && hasManifest) {\n const pkg = await fs.readJson(manifest, { throws: false })\n const patterns = pkg?.workspaces?.packages ?? pkg?.workspaces\n if (Array.isArray(patterns)) {\n const members = await mapWorkspaces({ cwd: dir, pkg })\n if (Array.from(members.values()).includes(npmProject)) return dir\n }\n }\n }\n if (dir === path.dirname(dir)) break\n }\n return npmProject ?? start\n}\n\nasync function assertRegularFileOrMissing(file: string): Promise<void> {\n try {\n const stat = await fs.lstat(file)\n if (!stat.isFile()) throw new UnsafeConfigError(`Refusing non-regular configuration file: ${file}`)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n}\n\nasync function protectConfigFile(cwd: string, filename: string): Promise<void> {\n await assertRegularFileOrMissing(path.join(cwd, filename))\n const options = { cwd, reject: false, env: { LC_ALL: \"C\" } } as const\n const repository = await execa(\"git\", [\"rev-parse\", \"--show-toplevel\"], options)\n const inGit = repository.exitCode === 0\n if (!inGit && !(repository.exitCode === 128 && repository.stderr.includes(\"not a git repository\"))) {\n throw new UnsafeConfigError(\"Could not establish Git protection for registry configuration\")\n }\n\n if (inGit) {\n const tracked = await execa(\"git\", [\"ls-files\", \"--error-unmatch\", \"--\", filename], options)\n if (tracked.exitCode === 0) {\n throw new UnsafeConfigError(`Refusing tracked registry configuration: ${path.join(cwd, filename)}. Configure credentials outside tracked files.`)\n }\n if (tracked.exitCode !== 1) throw new UnsafeConfigError(\"Could not check tracked registry configuration\")\n const ignored = await execa(\"git\", [\"check-ignore\", \"--quiet\", \"--\", filename], options)\n if (ignored.exitCode === 0) return\n if (ignored.exitCode !== 1) throw new UnsafeConfigError(\"Could not check ignored registry configuration\")\n }\n\n const ignorePath = path.join(cwd, \".gitignore\")\n await assertRegularFileOrMissing(ignorePath)\n const content = await fs.pathExists(ignorePath) ? await fs.readFile(ignorePath, \"utf8\") : \"\"\n const rule = `/${filename}`\n if (!content.trimEnd().endsWith(`\\n${rule}`) && content.trim() !== rule) {\n await fs.writeFile(ignorePath, `${content}${content.endsWith(\"\\n\") || !content ? \"\" : \"\\n\"}${rule}\\n`)\n }\n if (inGit) {\n const ignored = await execa(\"git\", [\"check-ignore\", \"--quiet\", \"--\", filename], options)\n if (ignored.exitCode !== 0) throw new UnsafeConfigError(\"Registry configuration is not ignored by Git\")\n }\n}\n\n/**\n * Save authentication token to package manager config\n */\nexport async function saveAuthToken(\n token: string,\n packageManager: PackageManager,\n cwd: string\n): Promise<boolean> {\n try {\n if (packageManager === \"yarn\") {\n await saveYarnToken(token, cwd)\n } else {\n await protectConfigFile(cwd, \".npmrc\")\n await saveToNpmrc(path.join(cwd, \".npmrc\"), token)\n }\n return true\n } catch (error) {\n logger.error(error instanceof UnsafeConfigError\n ? error.message\n : `Could not safely save registry configuration in ${cwd}`)\n return false\n }\n}\n\nasync function writePrivateConfig(\n file: string,\n content: string\n): Promise<void> {\n if (process.platform !== \"win32\" && (await fs.pathExists(file))) {\n await fs.chmod(file, 0o600)\n }\n await fs.writeFile(file, content, { mode: 0o600 })\n}\n\n/** Save the token to the configuration read by the detected Yarn version. */\nasync function saveYarnToken(token: string, cwd: string): Promise<void> {\n let isBerry = false\n try {\n const { stdout } = await execa(\"yarn\", [\"--version\"], { cwd })\n isBerry = !stdout.startsWith(\"1.\")\n } catch {\n // Keep the classic fallback only when version detection fails.\n }\n if (isBerry) {\n await protectConfigFile(cwd, \".yarnrc.yml\")\n await saveYarnBerryToken(token, cwd)\n } else {\n await protectConfigFile(cwd, \".npmrc\")\n await saveToNpmrc(path.join(cwd, \".npmrc\"), token)\n }\n}\n\n/**\n * Save token for Yarn Berry (v2+)\n */\nasync function saveYarnBerryToken(token: string, cwd: string): Promise<void> {\n const yarnrcPath = path.join(cwd, \".yarnrc.yml\")\n let yamlObj: Record<string, unknown> = {}\n\n // Read existing config if it exists\n if (fs.existsSync(yarnrcPath)) {\n const yarnrcContent = await fs.readFile(yarnrcPath, \"utf8\")\n yamlObj = yaml.parse(yarnrcContent) ?? {}\n if (typeof yamlObj !== \"object\" || Array.isArray(yamlObj)) {\n throw new UnsafeConfigError(`Invalid Yarn configuration: ${yarnrcPath}`)\n }\n }\n\n // Ensure the structure exists\n if (!yamlObj.npmScopes) {\n yamlObj.npmScopes = {}\n }\n\n if (typeof yamlObj.npmScopes !== \"object\" || Array.isArray(yamlObj.npmScopes)) {\n throw new UnsafeConfigError(`Invalid Yarn scopes: ${yarnrcPath}`)\n }\n\n // Set or update the tiptap-pro scope. `npmAlwaysAuth` ensures Berry sends\n // the token on GET requests too, not just PUTs — the Tiptap Pro registry\n // requires auth on package metadata fetches.\n const npmScopes = yamlObj.npmScopes as Record<string, unknown>\n const previousScope = npmScopes[\"tiptap-pro\"]\n if (previousScope != null && (typeof previousScope !== \"object\" || Array.isArray(previousScope))) {\n throw new UnsafeConfigError(`Invalid Tiptap Yarn scope: ${yarnrcPath}`)\n }\n npmScopes[\"tiptap-pro\"] = {\n ...previousScope as Record<string, unknown> | undefined,\n npmRegistryServer: TIPTAP_REGISTRY,\n npmAuthToken: token,\n npmAlwaysAuth: true,\n }\n\n // Write back to file\n await writePrivateConfig(yarnrcPath, yaml.stringify(yamlObj))\n}\n\n/**\n * Update .npmrc file with token\n */\nasync function saveToNpmrc(npmrcPath: string, token: string): Promise<void> {\n let npmrcContent = \"\"\n\n // Read existing file if it exists\n if (fs.existsSync(npmrcPath)) {\n npmrcContent = await fs.readFile(npmrcPath, \"utf8\")\n }\n\n // Parse .npmrc content\n const { lines, processedKeys } = parseNpmrc(npmrcContent, token)\n\n // Add missing keys\n if (!processedKeys.has(TIPTAP_PRO_REGISTRY_KEY)) {\n lines.push(`${TIPTAP_PRO_REGISTRY_KEY}=${TIPTAP_REGISTRY}`)\n }\n\n if (!processedKeys.has(AUTH_TOKEN_KEY)) {\n lines.push(`${AUTH_TOKEN_KEY}=${token}`)\n }\n\n // Ensure file ends with a newline\n if (lines.length > 0 && lines[lines.length - 1] !== \"\") {\n lines.push(\"\")\n }\n\n // Write the updated content back to the file\n await writePrivateConfig(npmrcPath, lines.join(\"\\n\"))\n}\n\n/**\n * Parse .npmrc content\n */\nfunction parseNpmrc(\n npmrcContent: string,\n token: string\n): {\n lines: string[]\n processedKeys: Set<string>\n} {\n const lines: string[] = []\n const processedKeys = new Set<string>()\n\n // Split content into lines\n const contentLines = npmrcContent.split(\"\\n\")\n\n // Process each line\n for (const line of contentLines) {\n const trimmedLine = line.trim()\n\n // Skip empty lines or add them as-is\n if (!trimmedLine) {\n lines.push(line)\n continue\n }\n\n // Preserve comments\n if (trimmedLine.startsWith(\"#\")) {\n lines.push(line)\n continue\n }\n\n // Process key-value pairs\n const index = line.indexOf(\"=\")\n if (index !== -1) {\n const key = line.substring(0, index).trim()\n\n // Update specific keys\n if (key === TIPTAP_PRO_REGISTRY_KEY) {\n lines.push(`${TIPTAP_PRO_REGISTRY_KEY}=${TIPTAP_REGISTRY}`)\n processedKeys.add(key)\n } else if (key === AUTH_TOKEN_KEY) {\n lines.push(`${AUTH_TOKEN_KEY}=${token}`)\n processedKeys.add(key)\n } else {\n // Keep other keys unchanged\n lines.push(line)\n }\n } else {\n // Keep lines that aren't key-value pairs\n lines.push(line)\n }\n }\n\n return { lines, processedKeys }\n}\n\n/**\n * Get auth token from package manager config\n */\nexport async function getAuthToken(\n packageManager: PackageManager,\n cwd: string\n): Promise<string | null> {\n try {\n const projectToken = await checkProjectNpmrc(cwd)\n if (projectToken) {\n return projectToken\n }\n\n if (packageManager === \"npm\") {\n const npmAuthToken = await getNpmAuthToken(cwd)\n return npmAuthToken\n }\n\n const globalAuthToken = await checkGlobalNpmrc()\n if (globalAuthToken) {\n return globalAuthToken\n }\n\n // Older CLI versions wrote yarn 1 tokens into `~/.yarnrc` via\n // `yarn config set --location=project` (which Yarn classic silently\n // misroutes to the global file). Read it as a fallback so `status` and\n // auth checks don't lie when the legacy save path was used.\n if (packageManager === \"yarn\") {\n return await checkGlobalYarnrc()\n }\n\n return null\n } catch (error) {\n return null\n }\n}\n\n/**\n * Check project .npmrc for auth token\n */\nexport async function checkProjectNpmrc(cwd: string): Promise<string | null> {\n const projectNpmrcPath = path.join(cwd, \".npmrc\")\n if (fs.existsSync(projectNpmrcPath)) {\n const content = await fs.readFile(projectNpmrcPath, \"utf8\")\n return extractAuthToken(content)\n }\n return null\n}\n\n/**\n * Get npm auth token using npm config command\n */\nasync function getNpmAuthToken(cwd: string): Promise<string | null> {\n const { stdout } = await execa(\"npm\", [\"config\", \"get\", AUTH_TOKEN_KEY], {\n cwd,\n })\n\n return stdout && stdout !== \"undefined\" ? stdout.trim() : null\n}\n\n/**\n * Check global .npmrc file for auth token\n */\nasync function checkGlobalNpmrc(): Promise<string | null> {\n const globalNpmrcPath = path.join(os.homedir(), \".npmrc\")\n\n if (fs.existsSync(globalNpmrcPath)) {\n const content = await fs.readFile(globalNpmrcPath, \"utf8\")\n return extractAuthToken(content)\n }\n\n return null\n}\n\n/**\n * Check legacy Yarn classic `~/.yarnrc` for auth token. The file uses\n * `\"key\" value` lines (no `=`), so it isn't matched by `extractAuthToken`.\n */\nasync function checkGlobalYarnrc(): Promise<string | null> {\n const yarnrcPath = path.join(os.homedir(), \".yarnrc\")\n if (!fs.existsSync(yarnrcPath)) {\n return null\n }\n const content = await fs.readFile(yarnrcPath, \"utf8\")\n const match = content\n .split(\"\\n\")\n .map((line) =>\n line.match(/^\"\\/\\/registry\\.tiptap\\.dev\\/:_authToken\"\\s+\"?([^\"\\s]+)\"?/)\n )\n .find((m): m is RegExpMatchArray => m !== null)\n return match?.[1] ?? null\n}\n\n/**\n * Extract auth token from config string\n */\nexport function extractAuthToken(configString: string): string | null {\n // Split into lines and filter for registry.tiptap.dev\n const lines = configString\n .split(\"\\n\")\n .filter((line) => line.startsWith(\"//registry.tiptap.dev/:_authToken=\"))\n\n if (lines.length === 0) {\n return null\n }\n\n // Extract the token after the \"=\" sign\n const token = lines[0].split(\"=\")[1]?.trim()\n return token || null\n}\n","import { z } from \"zod\"\n\nexport const registryItemTypeSchema = z.enum([\n \"registry:context\",\n \"registry:extension\",\n \"registry:hook\",\n \"registry:icon\",\n \"registry:lib\",\n \"registry:node\",\n \"registry:template\",\n \"registry:ui-primitive\",\n \"registry:ui\",\n \"registry:ui-utils\",\n \"registry:page\",\n \"registry:component\",\n \"registry:style\",\n \"registry:asset\",\n])\n\nexport type PaidPlan = \"start\" | \"team\" | \"growth\" | \"enterprise\" | \"business\"\nexport type FreePlan = \"open-source\" | \"light\"\nexport type Plan = PaidPlan | FreePlan\n\nexport const PAID_PLANS = [\n \"start\",\n \"team\",\n \"growth\",\n \"enterprise\",\n \"business\",\n] as const satisfies readonly PaidPlan[]\n\nexport const FREE_PLANS = [\n \"open-source\",\n \"light\",\n] as const satisfies readonly FreePlan[]\n\nconst ALL_PLANS = [...PAID_PLANS, ...FREE_PLANS] as const\n\nexport const planSchema = z.array(z.enum(ALL_PLANS)).default([])\n\nexport const featureIdSchema = z\n .string()\n .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)\n .refine((name) => name !== \"constructor\")\n\nexport const registryModulePathSchema = z\n .string()\n .refine(\n (path) =>\n /\\.[jt]sx?$/.test(path) &&\n !path.endsWith(\".d.ts\") &&\n !/[\\\\:#?]/.test(path) &&\n path.split(\"/\").every((part) => part && part !== \".\" && part !== \"..\") &&\n !/\\p{Cc}/u.test(path),\n \"Use a relative registry source path to a JavaScript or TypeScript module.\"\n )\n\nconst reservedBindings = new Set(\n \"arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield\".split(\n \" \"\n )\n)\nconst exportName = z\n .string()\n .regex(/^[A-Za-z_$][\\w$]*$/)\n .refine((name) => !reservedBindings.has(name), \"Use a named module export.\")\n\nconst featureText = z\n .string()\n .trim()\n .min(1)\n .refine((value) => !/\\p{Cc}/u.test(value), \"Use single-line text.\")\n\nconst featureItems = z.array(featureIdSchema).min(1)\nexport const registryFeatureSchema = z.object({\n id: featureIdSchema,\n label: featureText,\n description: featureText,\n instructions: z.array(featureText),\n docs: z\n .string()\n .url()\n .regex(/^https:\\/\\/[^\\s\\p{Cc}]+$/u),\n items: featureItems,\n frameworkItems: z.record(featureIdSchema, featureItems).optional(),\n integration: z.discriminatedUnion(\"kind\", [\n z.object({ kind: z.literal(\"files\") }),\n z.object({\n kind: z.literal(\"collaboration\"),\n wrapper: registryModulePathSchema,\n config: registryModulePathSchema,\n tokenRoute: registryModulePathSchema,\n }),\n z.object({\n kind: z.literal(\"editor-extension\"),\n extension: registryModulePathSchema,\n exportName,\n }),\n ]),\n})\n\nexport type RegistryFeature = z.infer<typeof registryFeatureSchema>\n\nexport const registryFeatureIdentitySchema = registryFeatureSchema.pick({\n id: true,\n})\nexport type RegistryFeatureEntry =\n RegistryFeature | z.infer<typeof registryFeatureIdentitySchema>\n\nexport const registryFeatureCatalogSchema = z.object({\n version: z.literal(1),\n features: z.array(z.unknown()),\n})\n\nexport const registryItemFileSchema = z.object({\n path: z.string(),\n content: z.string().optional(),\n type: registryItemTypeSchema,\n target: z.string().optional(),\n})\n\nexport const registryItemSchema = z.object({\n name: z.string(),\n type: registryItemTypeSchema,\n description: z.string().optional(),\n dependencies: z.array(z.string()).optional(),\n devDependencies: z.array(z.string()).optional(),\n registryDependencies: z.array(z.string()).optional(),\n files: z.array(registryItemFileSchema).optional(),\n meta: z\n .object({\n editor: z.unknown().optional(),\n featureSupport: z.unknown().optional(),\n privateNpmPackages: z.array(z.string().min(1)).optional(),\n })\n .catchall(z.any())\n .optional(),\n plans: planSchema.optional(),\n hide: z.boolean().default(false).optional(),\n isNew: z.boolean().default(false).optional(),\n})\n\nexport const registrySourceItemSchema = registryItemSchema.extend({\n files: z\n .array(registryItemFileSchema.extend({ content: z.string() }))\n .optional(),\n})\n\nexport const registrySchema = z.array(registryItemSchema)\n\nexport type Registry = z.infer<typeof registrySchema>\n\nexport const registryIndexSchema = z.array(\n registryItemSchema.extend({\n files: z.array(z.union([z.string(), registryItemFileSchema])).optional(),\n })\n)\n\nexport type RegistryItem = z.infer<typeof registryItemSchema>\nexport type RegistryItemIndexSchema = z.infer<typeof registryIndexSchema>\n","import {\n registryIndexSchema,\n registryFeatureSchema,\n registryFeatureIdentitySchema,\n type RegistryFeatureEntry,\n registryFeatureCatalogSchema,\n RegistryItem,\n registrySourceItemSchema,\n} from \"@/src/utils/registry/schema\"\nimport { HttpsProxyAgent } from \"https-proxy-agent\"\nimport fetch, { Response } from \"node-fetch\"\nimport { z } from \"zod\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { colors } from \"@/src/utils/colors\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\nexport const TIPTAP_ORIGIN = \"https://template.tiptap.dev\"\n\nexport function getRegistryBaseUrl() {\n const base = process.env.TIPTAP_REGISTRY_URL || TIPTAP_ORIGIN\n const url = URL.canParse(base) ? new URL(base) : null\n if (\n !url ||\n ![\"http:\", \"https:\"].includes(url.protocol) ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n throw new Error(\n \"Set TIPTAP_REGISTRY_URL to an HTTP or HTTPS URL without credentials, a query, or a fragment.\"\n )\n }\n return url.href.replace(/\\/+$/, \"\")\n}\n\nconst agent = process.env.https_proxy\n ? new HttpsProxyAgent(process.env.https_proxy)\n : undefined\n\nexport async function getRegistryIndex() {\n const result = await fetchComponent(\"index.json\")\n return registryIndexSchema.parse(result)\n}\n\nexport async function getRegistryFeatures(): Promise<RegistryFeatureEntry[]> {\n const url = `${getRegistryBaseUrl()}/r/features.json`\n const signal = AbortSignal.timeout(2000)\n let data: unknown\n try {\n const response = await fetch(url, { agent, signal })\n if (response.status === 404) return []\n if (!response.ok) {\n const reason =\n response.status >= 500 ? \"is temporarily unavailable\" : \"request failed\"\n throw new Error(\n `The registry feature catalog ${reason} with HTTP ${response.status}.`\n )\n }\n data = await response.json()\n } catch (error) {\n if (signal.aborted)\n throw new Error(\"The feature catalog request timed out.\")\n if (error instanceof SyntaxError)\n throw new Error(\"The registry feature catalog contains invalid JSON.\")\n throw error\n }\n const catalog = registryFeatureCatalogSchema.safeParse(data)\n if (!catalog.success) {\n throw new Error(\n \"This CLI cannot read the registry feature catalog. Check its format or update @tiptap/cli.\"\n )\n }\n const entries: RegistryFeatureEntry[] = []\n for (const entry of catalog.data.features) {\n const feature = registryFeatureSchema.safeParse(entry)\n if (feature.success) {\n entries.push(feature.data)\n } else {\n const identity = registryFeatureIdentitySchema.safeParse(entry)\n if (identity.success) entries.push(identity.data)\n }\n }\n return entries\n}\n\nfunction createRegistryError(\n response: Response,\n url: string,\n authenticated = false\n): Error {\n const urlInfo = url ? ` at ${colors.cyan(url)}` : \"\"\n\n switch (response.status) {\n case 400:\n return new Error(\n `The registry rejected the request${urlInfo}.\\n` +\n `Please check the selected components and try again.`\n )\n\n case 401:\n if (authenticated) tokenStorage.clearSession()\n return new Error(\n `You are not authorized to access the component${urlInfo}.\\n` +\n `Please run ${colors.cyan(\"@tiptap/cli login\")} to log in to your Tiptap Cloud account.`\n )\n\n case 404:\n return new Error(\n `The component${urlInfo} was not found.\\n` +\n `It may not exist at the registry. Please make sure it is a valid component.`\n )\n\n case 403:\n return new Error(\n `You do not have access to the component${urlInfo}.\\n` +\n `Your account may not have the required subscription plan for this component.\\n` +\n `Please upgrade your subscription or use a component available in your current plan.`\n )\n\n case 429:\n return new Error(\n `Too many registry requests${urlInfo}.\\n` +\n `Please wait a moment and try again.`\n )\n\n default:\n if (response.status >= 500) {\n return new Error(\n `The Tiptap registry is temporarily unavailable${urlInfo}.\\n` +\n `Please try again later.`\n )\n }\n\n return new Error(\n `The registry returned an unexpected response${urlInfo}.\\n` +\n `Please try again.`\n )\n }\n}\n\nfunction componentHeaders(url: string) {\n const headers: Record<string, string> = { \"Content-Type\": \"application/json\" }\n if (new URL(url).origin === TIPTAP_ORIGIN) {\n const token = tokenStorage.getBearerToken()\n if (token) headers.Authorization = `Bearer ${token}`\n }\n return headers\n}\n\nasync function fetchComponent(path: string) {\n const url = getRegistryUrl(path)\n const headers = path === \"index.json\" ? {} : componentHeaders(url)\n const authenticated = \"Authorization\" in headers\n const response = await fetch(url, {\n agent,\n headers,\n redirect: authenticated ? \"error\" : \"follow\",\n })\n\n if (!response.ok) throw createRegistryError(response, url, authenticated)\n return response.json()\n}\n\nfunction requireNames(requested: string[], received: string[]) {\n const found = new Set(received)\n const missing = [...new Set(requested)].filter((name) => !found.has(name))\n if (missing.length) {\n throw new Error(\n `Registry response is missing required items: ${missing.join(\", \")}`\n )\n }\n}\n\nasync function fetchRegistryBatch(componentNames: string[]) {\n const url = `${getRegistryBaseUrl()}/api/registry/components/batch`\n const headers = componentHeaders(url)\n const response = await fetch(url, {\n method: \"POST\",\n agent,\n headers,\n redirect: headers.Authorization ? \"error\" : \"follow\",\n body: JSON.stringify({ components: componentNames }),\n })\n\n if (!response.ok)\n throw createRegistryError(response, url, Boolean(headers.Authorization))\n const items = z\n .array(z.object({ name: z.string() }).passthrough().nullable())\n .parse(await response.json())\n .filter((item) => item !== null)\n const received = items.map((item) => item.name)\n requireNames(componentNames, received)\n if (items.length !== componentNames.length) {\n throw new Error(\"The registry returned unexpected or duplicate items.\")\n }\n return items\n}\n\nexport async function fetchRegistry(paths: string[]) {\n const componentNames = paths.map((path) =>\n path.replace(/^.*\\//, \"\").replace(/\\.json$/, \"\")\n )\n\n if (componentNames.length > 1) {\n // The registry batch route accepts at most 200 component names.\n const batchSize = 200\n const uniqueNames = [...new Set(componentNames)]\n const results = []\n for (let offset = 0; offset < uniqueNames.length; offset += batchSize) {\n const batch = await fetchRegistryBatch(\n uniqueNames.slice(offset, offset + batchSize)\n )\n results.push(...batch)\n }\n return results\n }\n\n return Promise.all(paths.map(fetchComponent))\n}\n\nexport async function fetchRegistryDependencies(\n components: string[]\n): Promise<string[]> {\n const url = `${getRegistryBaseUrl()}/api/registry/dependencies`\n const response = await fetch(url, {\n method: \"POST\",\n agent,\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ components }),\n })\n\n if (!response.ok) {\n throw createRegistryError(response, url)\n }\n\n const names = z.array(z.string()).parse(await response.json())\n requireNames(components, names)\n return names\n}\n\nexport async function getResolvedRegistryItems(\n names: string[]\n): Promise<RegistryItem[]> {\n const expected = await fetchRegistryDependencies(names)\n const paths = expected.map(\n (name) => `components/${encodeURIComponent(name)}.json`\n )\n const items = z\n .array(registrySourceItemSchema)\n .parse(await fetchRegistry(paths))\n const received = items.map((item) => item.name)\n requireNames(\n [...expected, ...items.flatMap((item) => item.registryDependencies ?? [])],\n received\n )\n return items\n}\n\nfunction getRegistryUrl(path: string) {\n if (isUrl(path)) {\n const url = new URL(path)\n return url.toString()\n }\n\n const base = getRegistryBaseUrl()\n\n // Keep the index.json path as is (public)\n if (path === \"index.json\") {\n return `${base}/r/${path}`\n }\n\n // Only redirect component paths to the API\n if (path.startsWith(\"components/\")) {\n const componentName = path.replace(\"components/\", \"\").replace(\".json\", \"\")\n return `${base}/api/registry/components/${componentName}`\n }\n\n return `${base}/${path}`\n}\n\nfunction isUrl(path: string) {\n try {\n new URL(path)\n return true\n } catch (error) {\n return false\n }\n}\n\n/**\n * Filter development dependencies based on framework requirements\n * @param devDependencies Array of development dependencies\n * @param framework Framework name\n * @returns Filtered array of development dependencies\n */\nexport function filterDevDependenciesByFramework(\n devDependencies: unknown,\n framework: Framework[\"name\"]\n): string[] {\n const depsArray = Array.isArray(devDependencies) ? devDependencies : []\n\n if (!depsArray.length) {\n return []\n }\n\n const stringDeps = depsArray.map((dep) => String(dep))\n\n if (framework) {\n const hasSass = stringDeps.includes(\"sass\")\n const hasSassEmbedded = stringDeps.includes(\"sass-embedded\")\n\n if (hasSass || hasSassEmbedded) {\n let filteredDeps = [...stringDeps]\n\n const prefersEmbedded: Framework[\"name\"][] = [\n FRAMEWORKS.astro.name,\n FRAMEWORKS.laravel.name,\n FRAMEWORKS.vite.name,\n // FRAMEWORKS.remix.name,\n FRAMEWORKS[\"tanstack-start\"].name,\n FRAMEWORKS[\"react-router\"].name,\n ]\n\n const prefersRegular: Framework[\"name\"][] = [\n FRAMEWORKS[\"next-app\"].name,\n FRAMEWORKS[\"next-pages\"].name,\n // FRAMEWORKS.gatsby.name,\n ]\n\n if (prefersEmbedded.includes(framework)) {\n filteredDeps = filteredDeps.filter((dep) => dep !== \"sass\")\n } else if (prefersRegular.includes(framework)) {\n filteredDeps = filteredDeps.filter((dep) => dep !== \"sass-embedded\")\n }\n\n return filteredDeps\n }\n }\n\n return stringDeps\n}\n","import { detect } from \"@antfu/ni\"\nimport fs from \"fs-extra\"\nimport path from \"path\"\n\nexport type PackageManager = \"yarn\" | \"pnpm\" | \"bun\" | \"npm\"\n\nexport async function getPackageManagerInfo(\n targetDir: string,\n { withFallback = true }: { withFallback?: boolean } = {}\n): Promise<{\n name: PackageManager\n source: \"project\" | \"user-agent\" | \"default\"\n}> {\n const detected = await detect({ programmatic: true, cwd: targetDir })\n const name = detected?.split(\"@\")[0]\n if (name === \"yarn\" || name === \"pnpm\" || name === \"bun\" || name === \"npm\") {\n return { name, source: \"project\" }\n }\n\n if (withFallback) {\n const launcher = process.env.npm_config_user_agent?.split(\"/\")[0]\n if (\n launcher === \"yarn\" ||\n launcher === \"pnpm\" ||\n launcher === \"bun\" ||\n launcher === \"npm\"\n ) {\n return { name: launcher, source: \"user-agent\" }\n }\n }\n return { name: \"npm\", source: \"default\" }\n}\n\nexport async function getPackageManager(\n targetDir: string,\n options?: { withFallback?: boolean }\n) {\n return (await getPackageManagerInfo(targetDir, options)).name\n}\n\nexport async function getPackageRunner(cwd: string) {\n const packageManager = await getPackageManager(cwd)\n\n if (packageManager === \"pnpm\") return \"pnpm dlx\"\n\n if (packageManager === \"bun\") return \"bunx\"\n\n return \"npx\"\n}\n\nexport function isBunProject(cwd: string) {\n const hasBunLock = fs.existsSync(path.join(cwd, \"bun.lock\"))\n const hasBunfig = fs.existsSync(path.join(cwd, \"bunfig.toml\"))\n\n if (hasBunLock && hasBunfig) {\n return true\n }\n\n return false\n}\n","import { Command } from \"commander\"\nimport { execa } from \"execa\"\nimport { z } from \"zod\"\nimport { confirm, input, password as passwordPrompt } from \"@inquirer/prompts\"\nimport { authenticateUser, checkAuthStatus } from \"@/src/utils/auth\"\nimport { colors } from \"@/src/utils/colors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { logoutUser } from \"@/src/utils/auth\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport {\n getAuthToken,\n getRegistryConfigDirectory,\n} from \"@/src/utils/package-manager-config\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\nexport const authOptionsSchema = z.object({\n cwd: z.string(),\n email: z.string().optional(),\n password: z.string().optional(),\n writeConfig: z.boolean().optional(),\n registryOnly: z.boolean().optional(),\n showMessage: z.boolean().default(true),\n})\n\ntype AuthOptions = z.infer<typeof authOptionsSchema>\ntype PackageManager = \"npm\" | \"yarn\" | \"pnpm\" | \"bun\"\n\n/**\n * Creates a themed input prompt with consistent styling\n */\nconst createThemedInput = (\n message: string,\n options: {\n required?: boolean\n validate?: (value: string) => boolean | string\n } = {}\n) => {\n return input({\n message: colors.reset(message),\n required: options.required ?? true,\n validate:\n options.validate ??\n ((value: string) => (value ? true : \"This field is required\")),\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed password prompt with consistent styling\n */\nconst createThemedPassword = (\n message: string,\n options: {\n validate?: (value: string) => boolean | string\n } = {}\n) => {\n return passwordPrompt({\n message: colors.reset(message),\n validate:\n options.validate ??\n ((value: string) => (value ? true : \"This field is required\")),\n mask: \"*\",\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nexport const createThemedConfirm = (\n message: string,\n defaultValue: boolean = true\n) => {\n return confirm({\n message: colors.reset(message),\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Get the appropriate configuration file name based on package manager\n */\nfunction getConfigFileName(packageManager: PackageManager): string {\n switch (packageManager) {\n case \"npm\":\n return \".npmrc\"\n case \"yarn\":\n return \".yarnrc.yml or .npmrc (depending on Yarn version)\"\n case \"pnpm\":\n case \"bun\":\n return \".npmrc\"\n default:\n return \"configuration file\"\n }\n}\n\n/**\n * Display appropriate token configuration instructions for each package manager\n */\nasync function displayTokenInstructions(\n packageManager: PackageManager,\n cwd: string\n) {\n const token = \"<registry-auth-token>\"\n logger.log(\n `To use this token, add it to your project's package manager configuration in ${colors.cyan(cwd)}:`\n )\n\n if (packageManager === \"npm\") {\n logger.log(\"Run these commands in your project directory:\")\n logger.log(\n ` npm config set @tiptap-pro:registry https://registry.tiptap.dev/`\n )\n logger.log(` npm config set //registry.tiptap.dev/:_authToken ${token}`)\n logger.log(`\\nOr add to your project's .npmrc file:`)\n logger.log(` @tiptap-pro:registry=https://registry.tiptap.dev/`)\n logger.log(` //registry.tiptap.dev/:_authToken=${token}`)\n } else if (packageManager === \"yarn\") {\n const isYarnV1 = await checkYarnVersion(cwd)\n\n if (isYarnV1) {\n logger.log(\"Run these commands in your project directory:\")\n logger.log(\n ` yarn config set @tiptap-pro:registry https://registry.tiptap.dev/`\n )\n logger.log(` yarn config set //registry.tiptap.dev/:_authToken ${token}`)\n } else {\n logger.log(`Add to your project's .yarnrc.yml file:`)\n logger.log(\n `npmScopes:\\n tiptap-pro:\\n npmRegistryServer: \"https://registry.tiptap.dev/\"\\n npmAuthToken: \"${token}\"`\n )\n }\n } else if (packageManager === \"pnpm\" || packageManager === \"bun\") {\n logger.log(`Add to your project's .npmrc file:`)\n logger.log(\n colors.cyan(\n `@tiptap-pro:registry=https://registry.tiptap.dev/\\n//registry.tiptap.dev/:_authToken=${token}`\n )\n )\n }\n}\n\n/**\n * Check if the project is using Yarn v1\n */\nasync function checkYarnVersion(cwd: string): Promise<boolean> {\n try {\n const yarnVersionOutput = await execa(\"yarn\", [\"--version\"], { cwd })\n return yarnVersionOutput.stdout.startsWith(\"1.\")\n } catch (error) {\n // If yarn command fails, default to false\n return false\n }\n}\n\n/**\n * Handle the login process with interactive prompts if needed\n */\nexport async function handleLogin(options: AuthOptions) {\n let { email, password, writeConfig, showMessage } = options\n const packageManager = await getPackageManager(options.cwd)\n const cwd = options.registryOnly\n ? await getRegistryConfigDirectory(options.cwd, packageManager)\n : options.cwd\n\n if (password) {\n logger.warn(\n \"--password is deprecated. Use TIPTAP_CLI_PASSWORD or the masked prompt.\"\n )\n } else {\n password = process.env.TIPTAP_CLI_PASSWORD\n }\n\n // Interactive prompts if necessary values aren't provided\n if (!email) {\n email = await createThemedInput(\"Email:\", {\n validate: (value: string) => (value ? true : \"Please enter your email\"),\n })\n }\n\n if (!password) {\n password = await createThemedPassword(\"Password:\", {\n validate: (value: string) =>\n value ? true : \"Please enter your password\",\n })\n }\n\n // User cancelled the prompt\n if (!email || !password) {\n if (options.registryOnly) return false\n logger.error(\"Authentication cancelled\")\n process.exit(0)\n }\n\n // Prompt for writeConfig if not explicitly set via command line\n if (writeConfig === undefined) {\n const configFileName = getConfigFileName(packageManager)\n\n writeConfig = await createThemedConfirm(\n `Would you like to save the auth token to your ${configFileName}?`\n )\n\n // User cancelled the prompt\n if (writeConfig === undefined) {\n logger.error(\"Authentication cancelled\")\n process.exit(0)\n }\n }\n\n const result = await authenticateUser({\n email,\n password,\n packageManager,\n writeConfig: writeConfig ?? false,\n registryOnly: options.registryOnly,\n cwd,\n })\n\n if (result.success && result.tokens) {\n if (writeConfig && showMessage) {\n logger.log(\n `\\nRegistry auth token saved to project directory for ${colors.cyan(packageManager)}`\n )\n logger.log(`Project directory: ${colors.cyan(cwd)}`)\n } else if (result.tokens.authToken && showMessage) {\n logger.log(\n \"Registry auth token saved locally. Use login --write-config to configure this project.\"\n )\n await displayTokenInstructions(packageManager, cwd)\n }\n\n if (showMessage && !options.registryOnly) {\n logger.log(`Bearer token saved globally for CLI authentication`)\n }\n\n return true\n } else {\n const errorMessage = result.error?.split(password).join(\"[redacted]\")\n logger.error(\"Authentication failed: \" + errorMessage)\n\n return false\n }\n}\n\n/**\n * Handle checking authentication status\n */\nasync function handleStatusCheck(cwd: string) {\n const packageManager = await getPackageManager(cwd)\n const status = await checkAuthStatus()\n\n if (status.authenticated) {\n logger.success(\n `Authenticated as ${colors.cyan(status.user ?? \"unknown user\")}`\n )\n\n // Display plans\n if (status.plans && status.plans.length > 0) {\n if (status.plans.length === 1) {\n logger.log(`Plan: ${colors.cyan(status.plans[0])}`)\n } else {\n logger.log(`Plans: ${colors.cyan(status.plans.join(\", \"))}`)\n }\n } else {\n logger.log(`Plans: ${colors.cyan(\"No active plans\")}`)\n }\n\n if (status.expires) {\n const expiryDate = new Date(status.expires)\n const now = new Date()\n const daysUntilExpiry = Math.ceil(\n (expiryDate.getTime() - now.getTime()) / (1000 * 60 * 60 * 24)\n )\n\n if (daysUntilExpiry > 30) {\n logger.log(\n `Token expires: ${colors.cyan(expiryDate.toDateString())} (${daysUntilExpiry} days)`\n )\n } else if (daysUntilExpiry > 0) {\n logger.log(\n `Token expires: ${colors.yellow(expiryDate.toDateString())} (${daysUntilExpiry} days)`\n )\n } else {\n logger.log(`Token expires: ${colors.red(\"Expired\")}`)\n }\n }\n\n if (status.token) {\n logger.log(\"Bearer token: configured\")\n }\n\n const registryToken = await getAuthToken(packageManager, cwd)\n if (registryToken) {\n logger.log(\"Registry token: configured\")\n } else {\n logger.log(\n `Registry token: ${colors.yellow(\"Not configured for this project\")}`\n )\n logger.log(\n `Run ${colors.cyan(\"@tiptap/cli login --write-config\")} to configure for this project`\n )\n }\n } else if (tokenStorage.getAuthToken()) {\n logger.log(\"Package registry token available for downloads.\")\n } else {\n logger.log(\"Not authenticated with Tiptap registry\")\n logger.log(`Run ${colors.cyan(`@tiptap/cli login`)} to authenticate`)\n }\n}\n\nexport const login = new Command()\n .command(\"login\")\n .description(\"log in to your Tiptap Cloud account\")\n .option(\"--registry-only\", \"authenticate package downloads\")\n .option(\"-e, --email <email>\", \"your account email\")\n .option(\n \"-p, --password <password>\",\n \"deprecated: use TIPTAP_CLI_PASSWORD or the masked prompt\"\n )\n .option(\n \"--write-config\",\n \"write the auth token to your package manager config\",\n undefined\n )\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .action(async (options) => {\n try {\n const opts = authOptionsSchema.parse(options)\n const success = await handleLogin(opts)\n if (!success) process.exitCode = 1\n } catch (error) {\n handleError(error)\n }\n })\n\nexport const status = new Command()\n .command(\"status\")\n .description(\"review your Tiptap Cloud authentication status\")\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .action(async (options) => {\n const opts = authOptionsSchema.parse(options)\n const { cwd } = opts\n try {\n await handleStatusCheck(cwd)\n } catch (error) {\n handleError(error)\n }\n })\n\nexport const logout = new Command()\n .command(\"logout\")\n .description(\"log out from your Tiptap registry account\")\n\n .action(async () => {\n try {\n const logoutSpinner = spinner(\"Logging out...\")?.start()\n\n const result = await logoutUser()\n\n if (result.success) {\n logoutSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \"Successfully logged out\",\n })\n } else {\n logoutSpinner?.fail(\"Logout failed\")\n logger.error(\"Logout failed: \" + result.error)\n }\n } catch (error) {\n handleError(error)\n }\n })\n\n/**\n * Handle displaying license information\n */\nasync function handleLicenseInfo() {\n logger.log(\"\")\n logger.log(colors.yellow(\"📋 Tiptap Pro License Information\"))\n logger.log(\"\")\n\n // Check license acceptance status\n const hasAccepted = tokenStorage.hasAcceptedLicense()\n const userInfo = tokenStorage.getUserInfo()\n\n if (hasAccepted) {\n logger.log(`${colors.cyan(\"✔\")} Pro License and Terms of Service accepted`)\n if (userInfo.email) {\n logger.log(` Accepted by: ${colors.cyan(userInfo.email)}`)\n }\n logger.log(\"\")\n } else {\n logger.log(\n colors.yellow(\"⚠ Pro License and Terms of Service not yet accepted\")\n )\n logger.log(\" License acceptance is required for using paid components\")\n logger.log(\"\")\n }\n\n logger.log(\"License Details:\")\n logger.log(\n ` • Pro License: ${colors.cyan(\"https://tiptap.dev/pro-license\")}`\n )\n logger.log(\n ` • Terms of Service: ${colors.cyan(\"https://tiptap.dev/terms-of-service\")}`\n )\n logger.log(\"\")\n\n logger.log(\"About Paid Components:\")\n logger.log(\n \" Some paid UI components or templates are limited to specific plans.\"\n )\n logger.log(\n \" The license is valid during your trial period and active subscription.\"\n )\n logger.log(\"\")\n\n // Show hidden command hint only when using license command\n if (hasAccepted) {\n logger.log(colors.gray(\"Available commands:\"))\n logger.log(\n colors.gray(\n ` • ${colors.cyan(\"tiptap license forget me\")} - Reset license acceptance`\n )\n )\n logger.log(\"\")\n }\n}\n\n/**\n * Handle license forget me command\n */\nasync function handleLicenseForgetMe() {\n const hasAccepted = tokenStorage.hasAcceptedLicense()\n\n if (!hasAccepted) {\n logger.log(colors.yellow(\"⚠ License has not been accepted yet\"))\n return\n }\n\n const confirmed = await createThemedConfirm(\n \"Are you sure you want to reset your license acceptance?\",\n false\n )\n\n if (confirmed) {\n tokenStorage.clearLicenseAcceptance()\n logger.log(`${colors.cyan(\"✔\")} License acceptance has been reset`)\n logger.log(\n \" You will need to accept the license again when installing paid components\"\n )\n } else {\n logger.log(\"License acceptance reset cancelled\")\n }\n}\n\nexport const license = new Command()\n .command(\"license\")\n .description(\"display Tiptap Pro license information and acceptance status\")\n .action(async () => {\n try {\n await handleLicenseInfo()\n } catch (error) {\n handleError(error)\n }\n })\n .addCommand(\n new Command()\n .command(\"forget me\")\n .description(\"reset license acceptance status\")\n .action(async () => {\n try {\n await handleLicenseForgetMe()\n } catch (error) {\n handleError(error)\n }\n })\n )\n","import { logger } from \"@/src/utils/logger\"\nimport { z } from \"zod\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport function handleError(error: unknown) {\n logger.error(\n `Something went wrong. Please check the error below for more details.`\n )\n logger.error(`If the problem persists, please open an issue on GitHub.`)\n logger.error(\"\")\n if (typeof error === \"string\") {\n logger.error(error)\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof z.ZodError) {\n logger.error(\"Validation failed:\")\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${colors.cyan(key)}: ${value}`)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof Error) {\n logger.error(error.message)\n logger.break()\n process.exit(1)\n }\n\n logger.break()\n process.exit(1)\n}\n","import { checkAuthStatus } from \"@/src/utils/auth\"\nimport {\n saveAuthToken,\n type PackageManager,\n} from \"@/src/utils/package-manager-config\"\nimport { logger } from \"@/src/utils/logger\"\nimport { colors } from \"@/src/utils/colors\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { getPackageManager } from \"./get-package-manager\"\nimport { PAID_PLANS, PaidPlan, Plan } from \"./registry/schema\"\nimport { createThemedConfirm, handleLogin } from \"../commands/auth\"\nimport { tokenStorage } from \"@/src/utils/bootstrap\"\n\n/**\n * Checks if the selected components contain any paid components\n */\nexport function hasPaidComponents(\n components: Array<{ name: string; plans?: Plan[] }>\n): boolean {\n return components.some(\n (component) =>\n component.plans &&\n component.plans.some((plan) => PAID_PLANS.includes(plan as PaidPlan))\n )\n}\n\nexport function assertCanPreviewPaidComponents(\n items: Array<{ name: string; plans?: Plan[] }>\n) {\n if (!hasPaidComponents(items)) return\n if (!tokenStorage.getBearerToken()) {\n throw new Error(\"Run pnpm dlx @tiptap/cli login to view paid component source.\")\n }\n if (!tokenStorage.hasAcceptedLicense()) {\n throw new Error(\n \"Accept the Pro license during an interactive installation before previewing paid source.\"\n )\n }\n}\n\n/**\n * Prompts user to accept Pro license and Terms of Service for paid components\n */\nasync function promptLicenseAcceptance(\n selectedComponents: Array<{ name: string; plans: Plan[] }>\n): Promise<boolean> {\n const paidComponents = selectedComponents.filter(\n (component) =>\n component.plans &&\n component.plans.some((plan) => PAID_PLANS.includes(plan as PaidPlan))\n )\n\n if (paidComponents.length === 0) {\n return true\n }\n\n // Check if license was already accepted\n if (tokenStorage.hasAcceptedLicense()) {\n logger.log(`${colors.cyan(\"✔\")} Pro license accepted`)\n return true\n }\n\n logger.log(\"\")\n logger.log(colors.yellow(\"📋 License Agreement\"))\n logger.log(\"\")\n logger.log(\"Integrating paid components requires accepting:\")\n logger.log(\n ` • Pro License: ${colors.cyan(\"https://tiptap.dev/pro-license\")}`\n )\n logger.log(\n ` • Terms of Service: ${colors.cyan(\"https://tiptap.dev/terms-of-service\")}`\n )\n logger.log(\"\")\n logger.log(colors.gray(\" Valid during trial and active subscription\"))\n logger.log(\"\")\n\n try {\n const accepted = await createThemedConfirm(\n \"Do you accept the Pro license and terms of service?\",\n false\n )\n\n if (!accepted) {\n logger.log(colors.gray(\"License not accepted\"))\n logger.log(colors.gray(\"Tip: You can still install free components\"))\n return false\n }\n\n // Store license acceptance\n tokenStorage.setLicenseAccepted()\n logger.log(`${colors.cyan(\"✔\")} License accepted`)\n return true\n } catch (error) {\n logger.log(colors.gray(\"License acceptance cancelled\"))\n return false\n }\n}\n\n/**\n * Ensures user is authenticated for paid components and has proper .npmrc configuration.\n */\nexport async function ensureAuthForPaidComponents(\n selectedComponents: Array<{ name: string; plans: Plan[] }>,\n cwd: string,\n { interactive = true }: { interactive?: boolean } = {}\n): Promise<boolean> {\n try {\n if (!hasPaidComponents(selectedComponents)) {\n return true\n }\n\n const authStatus = await checkAuthStatus()\n if (\n !interactive &&\n (!authStatus.authenticated || !tokenStorage.hasAcceptedLicense())\n ) {\n logger.error(\n \"Run tiptap login and accept the Pro license before installing paid components.\"\n )\n return false\n }\n\n if (!authStatus.authenticated) {\n logger.log(\"\")\n logger.log(colors.yellow(\"🔐 Authentication Required\"))\n logger.log(\"\")\n logger.log(\"Pro components require authentication.\")\n logger.log(\n `Run ${colors.cyan(\"tiptap login\")} or create an account at ${colors.cyan(\"https://cloud.tiptap.dev\")}`\n )\n logger.log(\"\")\n\n const shouldLoginNow = await createThemedConfirm(\n \"Would you like to login now?\",\n true\n )\n\n if (!shouldLoginNow) {\n logger.log(\"\")\n logger.log(colors.gray(\"Authentication cancelled\"))\n logger.log(colors.gray(\"Tip: You can still install free components\"))\n return false\n }\n\n const loginSuccess = await handleLogin({\n cwd,\n writeConfig: true,\n showMessage: false,\n })\n if (!loginSuccess) {\n return false\n }\n } else {\n // Always (re)write the project config from the in-memory token. The\n // registry rotates the npm `authToken` on each login, invalidating older\n // ones, so any token already written to a global `~/.npmrc` or to the\n // project may be stale. Trusting it leads to silent 403s during install.\n const packageManager = await getPackageManager(cwd)\n if (!(await createNpmrcConfiguration(packageManager, cwd))) return false\n }\n\n // After authentication is complete, prompt for license acceptance\n const licenseAccepted = await promptLicenseAcceptance(selectedComponents)\n if (!licenseAccepted) {\n return false\n }\n\n return true\n } catch (error) {\n logger.error(\n `Authentication check failed: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return false\n }\n}\n\n/**\n * Creates .npmrc configuration for the project\n */\nasync function createNpmrcConfiguration(\n packageManager: PackageManager,\n cwd: string\n): Promise<boolean> {\n const configSpinner = spinner(\"Creating registry configuration...\")?.start()\n\n try {\n const authStatus = await checkAuthStatus()\n\n if (!authStatus.authenticated) {\n configSpinner?.fail(\n \"Cannot create configuration - user not authenticated\"\n )\n return false\n }\n\n const authToken = tokenStorage.getAuthToken()\n\n if (!authToken) {\n configSpinner?.fail(\"No authentication token found\")\n return false\n }\n\n const success = await saveAuthToken(authToken, packageManager, cwd)\n if (!success) {\n configSpinner?.fail(\"Failed to save authentication token\")\n return false\n }\n\n configSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: \".npmrc created successfully\",\n })\n return true\n } catch (error) {\n configSpinner?.fail(\"Failed to create registry configuration\")\n logger.error(\n `Configuration error: ${error instanceof Error ? error.message : \"Unknown error\"}`\n )\n return false\n }\n}\n","import { colors } from \"@/src/utils/colors\"\nimport { logger } from \"@/src/utils/logger\"\nimport process from \"process\"\n\n/**\n * CLI UI utilities for consistent visual styling\n */\n\n/**\n * Get the current terminal width with a fallback\n */\nexport function getTerminalWidth(): number {\n return process.stdout.columns || 80\n}\n\nexport function canPrompt() {\n return Boolean(process.stdin.isTTY && process.stdout.isTTY && !process.env.CI)\n}\n\n/**\n * Creates a bordered box with content\n */\nexport function createBox(\n title: string,\n content: string[],\n options?: {\n borderColor?: \"cyan\" | \"yellow\" | \"red\" | \"green\" | \"gray\"\n padding?: boolean\n }\n) {\n const borderColor = options?.borderColor || \"gray\"\n const padding = options?.padding !== false\n\n // Box drawing characters\n const topLeft = \"\"\n const topRight = \"\"\n const bottomLeft = \"\"\n const bottomRight = \"\"\n const horizontal = \"-\"\n const vertical = \"\"\n\n // Use terminal width with max constraint for readability\n const terminalWidth = getTerminalWidth()\n const boxWidth = Math.min(terminalWidth - 4, 80) // Max 80 chars for readability\n\n const colorFn = colors[borderColor]\n const topBorder = colorFn(\n topLeft + horizontal.repeat(boxWidth - 2) + topRight\n )\n const bottomBorder = colorFn(\n bottomLeft + horizontal.repeat(boxWidth - 2) + bottomRight\n )\n const sideBorder = colorFn(vertical)\n\n // Create the box\n const lines = []\n\n if (padding) lines.push(\"\")\n\n lines.push(topBorder)\n\n // Empty line before title\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n\n // Title line\n const titlePadding = Math.floor((boxWidth - 4 - stripAnsi(title).length) / 2)\n const titleLine = title\n .padStart(titlePadding + stripAnsi(title).length)\n .padEnd(boxWidth - 4)\n lines.push(`${sideBorder} ${titleLine} ${sideBorder}`)\n\n // Empty line after title\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n\n // Content lines\n content.forEach((line) => {\n const strippedLength = stripAnsi(line).length\n const padding = boxWidth - 4 - strippedLength\n const paddedLine = line + \" \".repeat(Math.max(0, padding))\n lines.push(`${sideBorder} ${paddedLine} ${sideBorder}`)\n })\n\n // Empty line before bottom border\n if (content.length > 0) {\n lines.push(`${sideBorder}${\" \".repeat(boxWidth - 2)}${sideBorder}`)\n }\n\n lines.push(bottomBorder)\n\n if (padding) lines.push(\"\")\n\n return lines\n}\n\n/**\n * Creates a section with title and content\n */\nexport function createSection(\n title: string,\n content: string[],\n subtitle?: string\n) {\n const lines = []\n\n lines.push(\"\")\n lines.push(title)\n\n if (subtitle) {\n lines.push(colors.gray(subtitle))\n }\n\n lines.push(\"\")\n\n content.forEach((line) => {\n lines.push(line)\n })\n\n return lines\n}\n\n/**\n * Creates a welcome banner\n */\nexport function createWelcomeBanner(title: string, subtitle?: string) {\n const content = subtitle ? [subtitle] : []\n return createBox(`${title}`, content, { borderColor: \"gray\" })\n}\n\n/**\n * Creates an info box\n */\nexport function createInfoBox(title: string, content: string[]) {\n return createBox(`ℹ️ ${title}`, content, { borderColor: \"cyan\" })\n}\n\n/**\n * Creates a warning box\n */\nexport function createWarningBox(title: string, content: string[]) {\n return createBox(`⚠️ ${title}`, content, { borderColor: \"yellow\" })\n}\n\n/**\n * Creates a success box\n */\nexport function createSuccessBox(title: string, content: string[]) {\n return createBox(`✅ ${title}`, content, { borderColor: \"green\" })\n}\n\n/**\n * Logs multiple lines with proper spacing\n */\nexport function logLines(lines: string[]) {\n lines.forEach((line) => logger.log(line))\n}\n\n/**\n * Strips ANSI color codes from a string to get actual length\n */\nfunction stripAnsi(str: string): string {\n // eslint-disable-next-line no-control-regex\n return str.replace(/\\x1b\\[[0-9;]*m/g, \"\")\n}\n\n/**\n * Creates a numbered list with proper spacing\n */\nexport function createNumberedList(\n items: Array<{ label: string; description?: string }>\n) {\n const lines: string[] = []\n\n items.forEach((item, index) => {\n const number = colors.gray(`${index + 1}.`)\n lines.push(` ${number} ${item.label}`)\n\n if (item.description) {\n lines.push(` ${colors.gray(item.description)}`)\n }\n\n // Add spacing between items except the last one\n if (index < items.length - 1) {\n lines.push(\"\")\n }\n })\n\n return lines\n}\n\n/**\n * Creates a preview box with code content\n */\nexport function createPreviewBox(title: string, content: string[]) {\n const lines = []\n\n lines.push(\"\")\n lines.push(title)\n lines.push(\"\")\n\n // Create bordered preview area with terminal width constraint\n const terminalWidth = getTerminalWidth()\n const maxLength = Math.max(...content.map((line) => stripAnsi(line).length))\n const boxWidth = Math.min(Math.max(50, maxLength + 4), terminalWidth - 4)\n\n const topBorder = \"┌\" + \"─\".repeat(boxWidth - 2) + \"┐\"\n const bottomBorder = \"└\" + \"─\".repeat(boxWidth - 2) + \"┘\"\n\n lines.push(topBorder)\n\n content.forEach((line, index) => {\n const lineNumber = colors.gray(`${index + 1}`)\n const paddedLine = line.padEnd(boxWidth - 6)\n lines.push(`│ ${lineNumber} ${paddedLine} │`)\n })\n\n lines.push(bottomBorder)\n lines.push(\"\")\n\n return lines\n}\n\n/**\n * Creates an explanation section with bullet points\n */\nexport function createExplanationSection(title: string, points: string[]) {\n const lines = []\n\n lines.push(\"\")\n lines.push(colors.cyan(title))\n lines.push(\"\")\n\n points.forEach((point) => {\n lines.push(` • ${point}`)\n })\n\n lines.push(\"\")\n\n return lines\n}\n\n/**\n * Clears the terminal screen\n */\nexport function clearTerminal() {\n // Clear screen and move cursor to top-left\n process.stdout.write(\"\\x1B[2J\\x1B[0f\")\n\n // Alternative method that works better on some terminals\n // console.clear()\n\n // For Windows compatibility\n if (process.platform === \"win32\") {\n process.stdout.write(\"\\x1B[2J\\x1B[3J\\x1B[H\")\n }\n}\n\n/**\n * Creates a subtle divider line that spans the terminal width\n */\nexport function createDivider() {\n const width = Math.min(getTerminalWidth() - 4, 80)\n return colors.gray(\"─\".repeat(width))\n}\n\n/**\n * Creates a dash divider for prompts\n */\nexport function createSpacedDivider() {\n const width = Math.min(getTerminalWidth() - 4, 80)\n return colors.gray(\"-\".repeat(width))\n}\n","import { existsSync } from \"fs\"\nimport { parse as parseCss, type Root } from \"postcss\"\nimport { parse as parseScss } from \"postcss-scss\"\nimport {\n getInstallDestination,\n readExistingFile,\n type PlannedFile,\n} from \"./updaters/update-files\"\nimport path from \"path\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { resolveImport } from \"./resolve-import\"\nimport { getNextAppDir } from \"./get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport function getMainCssFilePath(\n framework: Framework,\n config: Config\n): string | null {\n const frameworkName = framework.name\n const cwd = config.resolvedPaths.cwd\n\n const hasSrcDir = config.resolvedPaths.components?.includes(\"/src/\")\n const stylesInSrc = config.resolvedPaths.styles?.includes(\"/src/\")\n\n let possiblePaths: string[] = []\n\n switch (frameworkName) {\n case FRAMEWORKS[\"next-app\"].name: {\n const appDir = getNextAppDir(cwd) ?? \"app\"\n possiblePaths = [\"globals.css\", \"globals.scss\"].map((name) =>\n path.join(cwd, appDir, name)\n )\n break\n }\n\n case FRAMEWORKS[\"next-pages\"].name:\n possiblePaths = (\n hasSrcDir ? [\"src/styles\", \"styles\"] : [\"styles\", \"src/styles\"]\n ).flatMap((dir) =>\n [\"globals.css\", \"globals.scss\"].map((name) => path.join(cwd, dir, name))\n )\n break\n\n case FRAMEWORKS.vite.name:\n case FRAMEWORKS[\"react-router\"].name:\n case FRAMEWORKS[\"tanstack-start\"].name:\n // Vite-based frameworks\n possiblePaths = [\n path.join(cwd, \"src/index.css\"),\n path.join(cwd, \"src/main.css\"),\n path.join(cwd, \"src/App.css\"),\n ]\n break\n\n case FRAMEWORKS.astro.name:\n possiblePaths = [\n path.join(cwd, \"src/styles/main.css\"),\n path.join(cwd, \"src/styles/global.css\"),\n ]\n break\n\n case FRAMEWORKS.laravel.name:\n possiblePaths = [path.join(cwd, \"resources/css/app.css\")]\n break\n\n case FRAMEWORKS.manual.name:\n default:\n // Try common locations\n if (hasSrcDir || stylesInSrc) {\n possiblePaths = [\n path.join(cwd, \"src/index.css\"),\n path.join(cwd, \"src/main.css\"),\n path.join(cwd, \"src/App.css\"),\n path.join(cwd, \"src/styles/main.css\"),\n ]\n } else {\n possiblePaths = [\n path.join(cwd, \"index.css\"),\n path.join(cwd, \"main.css\"),\n path.join(cwd, \"styles/main.css\"),\n ]\n }\n break\n }\n\n for (const filePath of possiblePaths) {\n if (existsSync(filePath)) {\n return filePath\n }\n }\n\n return possiblePaths[0] || null\n}\n\nexport interface StyleImportResult {\n success: boolean\n message: string\n filePath?: string\n}\n\nexport async function planStyleImports(\n styleFiles: string[],\n config: Config,\n framework?: Framework\n): Promise<{ result: StyleImportResult; change?: PlannedFile }> {\n const planned = new Set(styleFiles)\n const styles = [...planned].filter((file) => {\n const name = path.basename(file)\n if (!/^_(variables|keyframe-animations)\\.(scss|css)$/.test(name))\n return false\n // The host stylesheet uses its own theme when a shared workspace also installs it.\n const hostStyle = path.join(config.resolvedPaths.styles, name)\n return file === hostStyle || !planned.has(hostStyle)\n })\n if (!styles.length)\n return { result: { success: true, message: \"No style files to import\" } }\n const filePath = framework && getMainCssFilePath(framework, config)\n if (!filePath)\n return {\n result: {\n success: false,\n message: \"Could not determine main CSS file location\",\n },\n }\n const realPath = await getInstallDestination(filePath, config)\n const before = await readExistingFile(realPath)\n if (before === null)\n return {\n result: {\n success: false,\n message: `Main CSS file not found at ${filePath}`,\n },\n }\n\n const scss = filePath.endsWith(\".scss\")\n let stylesheet: Root\n try {\n stylesheet = (scss ? parseScss : parseCss)(before, { from: filePath })\n } catch (error) {\n return {\n result: {\n success: false,\n message: `Could not read style imports in ${filePath}: ${error instanceof Error ? error.message : error}`,\n },\n }\n }\n\n const specifiers = new Set<string>()\n const bom = before.startsWith(\"\\uFEFF\") ? 1 : 0\n let insertion = bom\n for (const node of stylesheet.nodes) {\n if (node.type !== \"atrule\") continue\n const name = node.name.toLowerCase()\n if (\n name === \"charset\" ||\n (scss && (name === \"use\" || name === \"forward\"))\n ) {\n // PostCSS excludes a leading byte order mark from source offsets.\n insertion = bom + node.source!.end!.offset\n }\n if (name === \"import\") {\n const match = node.params.match(\n /^(?:([\"'])(.+?)\\1|url\\(\\s*(?:([\"'])(.+?)\\3|([^\"'()\\s]+))\\s*\\))(?:\\s+layer(?:\\([^()]+\\))?)?(?:\\s+all)?$/i\n )\n if (match) specifiers.add(match[2] ?? match[4] ?? match[5])\n }\n }\n const imports: string[] = []\n for (const style of styles) {\n const relative = path\n .relative(path.dirname(filePath), style)\n .split(path.sep)\n .join(\"/\")\n const specifier = relative.startsWith(\".\") ? relative : \"./\" + relative\n const alias =\n config.aliases.styles &&\n `${config.aliases.styles}/${path.basename(style)}`\n const aliasTarget =\n alias && specifiers.has(alias)\n ? config.overrideImports\n ? await resolveImport(alias, config.overrideImports)\n : path.join(config.resolvedPaths.styles, path.basename(style))\n : undefined\n if (\n !specifiers.has(specifier) &&\n !specifiers.has(relative) &&\n aliasTarget !== style\n ) {\n imports.push(`@import '${specifier}';`)\n }\n }\n if (!imports.length)\n return {\n result: {\n success: true,\n message: \"Style imports already exist\",\n filePath,\n },\n }\n const newline = before.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\"\n const lines = imports.join(newline) + newline + newline\n const prefix = before.slice(0, insertion)\n const suffix = before.slice(insertion)\n const after =\n prefix +\n (insertion > bom ? newline : \"\") +\n lines +\n suffix.replace(/^\\r?\\n/, \"\")\n return {\n result: { success: true, message: \"Style imports added\", filePath },\n change: {\n path: filePath,\n realPath,\n requiredFiles: styles,\n before,\n after,\n status: \"update\",\n },\n }\n}\n\n/**\n * Log the result of auto-importing styles\n */\nexport function logAutoImportResult(result: StyleImportResult): void {\n if (!result.success) {\n logger.warn(colors.yellow(`⚠ ${result.message}`))\n return\n }\n\n if (result.message === \"No style files to import\") {\n return\n }\n\n if (result.message === \"Style imports already exist\") {\n return\n }\n\n const relativePath = result.filePath\n ? path.relative(process.cwd(), result.filePath)\n : \"main CSS file\"\n\n logger.log(\n `${colors.green(\"✔\")} Style imports automatically added to ${colors.cyan(relativePath)}`\n )\n logger.log(\"\")\n}\n","import { promises as fs } from \"fs\"\nimport path from \"path\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { getRegistryPath } from \"@/src/utils/registry-paths\"\nimport { getProjectInfo, ProjectInfo } from \"@/src/utils/get-project-info\"\nimport {\n RegistryItem,\n registryItemFileSchema,\n} from \"@/src/utils/registry/schema\"\nimport { transform } from \"@/src/utils/transformers\"\nimport { registrySassImporter } from \"@/src/utils/transformers/transform-scss-to-css\"\nimport { transformImport } from \"@/src/utils/transformers/transform-import\"\nimport { transformRsc } from \"@/src/utils/transformers/transform-rsc\"\nimport { z } from \"zod\"\nimport { confirm } from \"@inquirer/prompts\"\nimport {\n getPackageManager,\n isBunProject,\n} from \"@/src/utils/get-package-manager\"\nimport { transformRemoveComponents } from \"@/src/utils/transformers/transform-remove-components\"\n\nconst SCSS_DECLARATION_FILE = \"scss.d.ts\"\nconst SCSS_DECLARATION_CONTENT = `declare module \"*.scss\";\\n`\n\nexport interface PlannedFile {\n registryPath?: string\n path: string\n realPath: string\n requiredFiles?: string[]\n before: string | null\n after: string\n status: \"create\" | \"identical\" | \"conflict\" | \"update\" | \"keep\"\n}\n\nexport function keepExisting(file: PlannedFile) {\n if (file.before !== null) {\n file.after = file.before\n if (file.status === \"conflict\") file.status = \"keep\"\n }\n}\n\n// New destinations inherit the physical path of their nearest existing parent.\nasync function resolveInstallPath(filePath: string): Promise<string> {\n try {\n await fs.lstat(filePath)\n } catch (error) {\n const dir = path.dirname(filePath)\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\" || dir === filePath)\n throw error\n const parent = await resolveInstallPath(dir)\n return path.join(parent, path.basename(filePath))\n }\n // A dangling symlink is an existing entry whose destination we cannot verify.\n return fs.realpath(filePath)\n}\n\nfunction isWithin(root: string, filePath: string) {\n const relative = path.relative(root, filePath)\n return (\n relative !== \"\" &&\n relative !== \"..\" &&\n !relative.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relative)\n )\n}\n\nexport async function getInstallDestination(filePath: string, config: Config) {\n const { cwd, ...aliases } = config.resolvedPaths\n // A configured alias can explicitly target a sibling workspace. Paths inside\n // the project still use its root, including when a nested directory is a link.\n const root = isWithin(cwd, filePath)\n ? cwd\n : Object.values(aliases).find(\n (dir) => !isWithin(cwd, dir) && isWithin(dir, filePath)\n )\n if (root) {\n const [realRoot, realPath] = await Promise.all([\n resolveInstallPath(root),\n resolveInstallPath(filePath),\n ])\n if (isWithin(realRoot, realPath)) return realPath\n }\n throw new Error(\n `File destination is outside the configured install directories: ${filePath}`\n )\n}\n\nexport async function readExistingFile(\n filePath: string\n): Promise<string | null> {\n try {\n return await fs.readFile(filePath, \"utf8\")\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") return null\n throw error\n }\n}\n\nexport async function planFiles(\n files: RegistryItem[\"files\"],\n config: Config,\n project?: ProjectInfo | null\n) {\n const cwd = config.resolvedPaths.cwd\n const [projectInfo, packageManager] = await Promise.all([\n project === undefined ? getProjectInfo(cwd) : project,\n getPackageManager(cwd),\n ])\n const isBun = isBunProject(cwd)\n const sassImporter = isBun ? registrySassImporter(files) : undefined\n const changes: PlannedFile[] = []\n\n for (const file of files ?? []) {\n if (file.content === undefined) continue\n let filePath = resolveFilePath(file, config, {\n isSrcDir:\n file.type === \"registry:page\" && projectInfo?.nextAppDir\n ? projectInfo.nextAppDir === \"src/app\"\n : projectInfo?.isSrcDir,\n framework: projectInfo?.framework.name,\n })\n if (!filePath) continue\n if (!config.tsx) filePath = filePath.replace(/\\.ts(x?)$/, \".js$1\")\n if (isBun) filePath = filePath.replace(/\\.scss$/, \".css\")\n\n try {\n const realPath = await getInstallDestination(filePath, config)\n const before = await readExistingFile(realPath)\n const after = await transform(\n {\n filename: file.path,\n outputFilename: filePath,\n raw: file.content,\n sassImporter,\n config,\n projectInfo,\n transformJsx: !config.tsx,\n packageManager,\n },\n // Route handlers use server-only environment variables. The component\n // transform rewrites environment access for the browser.\n file.type === \"registry:page\" &&\n /\\/route\\.[jt]s$/.test(file.target ?? \"\")\n ? [transformImport]\n : [transformImport, transformRsc, transformRemoveComponents]\n )\n const status =\n before === null\n ? \"create\"\n : (await getNormalizedFileContent(before)) ===\n (await getNormalizedFileContent(after))\n ? \"identical\"\n : \"conflict\"\n changes.push({\n registryPath: file.path,\n path: filePath,\n realPath,\n before,\n after,\n status,\n })\n } catch (error) {\n throw new Error(\n `Could not prepare ${filePath}: ${error instanceof Error ? error.message : error}`\n )\n }\n }\n\n if (changes.some((file) => file.path.endsWith(\".scss\"))) {\n const declaration = path.join(\n cwd,\n projectInfo?.isSrcDir ? \"src\" : \"\",\n SCSS_DECLARATION_FILE\n )\n const realPath = await getInstallDestination(declaration, config)\n if ((await readExistingFile(realPath)) === null) {\n changes.push({\n path: declaration,\n realPath,\n before: null,\n after: SCSS_DECLARATION_CONTENT,\n status: \"create\",\n })\n }\n }\n return changes\n}\n\nasync function checkPlannedDestination(file: PlannedFile) {\n if ((await resolveInstallPath(file.path)) !== file.realPath) {\n throw new Error(\n `The destination of ${file.path} changed. Run add again to review it.`\n )\n }\n}\n\nasync function requireExistingFile(filePath: string) {\n try {\n if ((await fs.stat(filePath)).isFile()) return\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n throw new Error(`Missing file ${filePath}. Run add again to restore it.`)\n}\n\nexport async function applyFiles(\n files: PlannedFile[],\n cwd: string,\n options: { overwrite?: boolean; interactive?: boolean }\n) {\n const result = {\n filesCreated: [] as string[],\n filesUpdated: [] as string[],\n filesSkipped: [] as string[],\n errors: [] as { file: string; error: string }[],\n }\n const planned = new Map(files.map((file) => [file.path, file]))\n const installedContents = new Map<string, string | null>()\n for (const file of files) {\n // A stylesheet merge may import a file that this installation failed to write.\n if (file.status === \"update\" && result.errors.length) continue\n const relative = path.relative(cwd, file.path)\n try {\n const keepLocal =\n file.status === \"conflict\" &&\n !options.overwrite &&\n (!(options.interactive ?? process.stdin.isTTY) ||\n !(await confirm({\n message: `Overwrite ${relative}?`,\n default: false,\n })))\n await checkPlannedDestination(file)\n if (keepLocal) {\n await requireExistingFile(file.realPath)\n installedContents.set(file.path, file.before)\n result.filesSkipped.push(relative)\n continue\n }\n if (\n file.before !== null &&\n (await readExistingFile(file.realPath)) !== file.before\n ) {\n throw new Error(\n \"The file changed during installation. Run add again to review it.\"\n )\n }\n if (file.status === \"identical\" || file.status === \"keep\") {\n installedContents.set(file.path, file.before)\n result.filesSkipped.push(relative)\n continue\n }\n for (const source of file.requiredFiles ?? []) {\n const dependency = planned.get(source)\n if (!dependency)\n throw new Error(`Missing required file in install plan: ${source}`)\n const expected = installedContents.get(source)\n if (expected == null)\n throw new Error(`Required file did not pass installation: ${source}`)\n await checkPlannedDestination(dependency)\n if ((await readExistingFile(dependency.realPath)) !== expected)\n throw new Error(\n `Required file changed during installation: ${source}. Run add again to review it.`\n )\n }\n await fs.mkdir(path.dirname(file.realPath), { recursive: true })\n await fs.writeFile(file.realPath, file.after, {\n encoding: \"utf8\",\n flag: file.before === null ? \"wx\" : \"w\",\n })\n installedContents.set(file.path, file.after)\n if (file.before === null) result.filesCreated.push(relative)\n else result.filesUpdated.push(relative)\n } catch (error) {\n result.errors.push({\n file: relative,\n error: error instanceof Error ? error.message : String(error),\n })\n }\n }\n return result\n}\n\nexport async function updateFiles(\n files: RegistryItem[\"files\"],\n config: Config,\n options: { overwrite?: boolean; silent?: boolean }\n) {\n return applyFiles(\n await planFiles(files, config),\n config.resolvedPaths.cwd,\n options\n )\n}\n\nexport function resolveFileTargetDirectory(\n file: z.infer<typeof registryItemFileSchema>,\n config: Config,\n override?: string\n) {\n if (override) {\n return override\n }\n\n if (file.type === \"registry:ui\") {\n return config.resolvedPaths.tiptapUi\n }\n\n if (file.type === \"registry:ui-primitive\") {\n return config.resolvedPaths.tiptapUiPrimitives\n }\n\n if (file.type === \"registry:ui-utils\") {\n return config.resolvedPaths.tiptapUiUtils\n }\n\n if (file.type === \"registry:extension\") {\n return config.resolvedPaths.tiptapExtensions\n }\n\n if (file.type === \"registry:node\") {\n return config.resolvedPaths.tiptapNodes\n }\n\n if (file.type === \"registry:icon\") {\n return config.resolvedPaths.tiptapIcons\n }\n\n if (file.type === \"registry:hook\") {\n return config.resolvedPaths.hooks\n }\n\n if (file.type === \"registry:lib\") {\n return config.resolvedPaths.lib\n }\n\n if (file.type === \"registry:context\") {\n return config.resolvedPaths.contexts\n }\n\n if (file.type === \"registry:template\" || file.type === \"registry:component\") {\n return config.resolvedPaths.components\n }\n\n if (file.type === \"registry:style\") {\n return config.resolvedPaths.styles\n }\n\n return config.resolvedPaths.components\n}\n\nexport async function getNormalizedFileContent(content: string) {\n return content.replace(/\\r\\n/g, \"\\n\").trim()\n}\n\nexport function resolvePageTarget(\n target: string,\n framework?: ProjectInfo[\"framework\"][\"name\"]\n) {\n if (!framework) {\n return \"\"\n }\n\n if (framework === \"next-app\") {\n return target\n }\n\n if (framework === \"next-pages\") {\n let result = target.replace(/^app\\//, \"pages/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n if (framework === \"react-router\") {\n let result = target.replace(/^app\\//, \"app/routes/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n if (framework === \"laravel\") {\n let result = target.replace(/^app\\//, \"resources/js/pages/\")\n result = result.replace(/\\/page(\\.[jt]sx?)$/, \"$1\")\n\n return result\n }\n\n return \"\"\n}\n\nexport function resolveNestedFilePath(\n filePath: string,\n targetDir: string\n): string {\n const registryPath = getRegistryPath(filePath)\n if (registryPath) return registryPath.suffix\n\n // Preserve the fallback for legacy sources outside registry categories.\n // Normalize paths by removing leading/trailing slashes\n const normalizedFilePath = filePath.replace(/^\\/|\\/$/g, \"\")\n const normalizedTargetDir = targetDir.replace(/^\\/|\\/$/g, \"\")\n\n // Split paths into segments\n const fileSegments = normalizedFilePath.split(\"/\")\n const targetSegments = normalizedTargetDir.split(\"/\")\n\n // Find the last matching segment from targetDir in filePath\n const lastTargetSegment = targetSegments[targetSegments.length - 1]\n const commonDirIndex = fileSegments.findIndex(\n (segment) => segment === lastTargetSegment\n )\n\n if (commonDirIndex === -1) {\n // Return just the filename if no common directory is found\n return fileSegments[fileSegments.length - 1]\n }\n\n // Return everything after the common directory\n return fileSegments.slice(commonDirIndex + 1).join(\"/\")\n}\n\nexport function resolveFilePath(\n file: z.infer<typeof registryItemFileSchema>,\n config: Config,\n options: {\n isSrcDir?: boolean\n framework?: ProjectInfo[\"framework\"][\"name\"]\n }\n) {\n // if (file.type === \"registry:asset\") {\n // if (file.target) {\n // // replace assets/ and public/ with the public directory\n // const targetDir = file.target.replace(/^assets\\//, \"\")\n // const targetDirPublic = targetDir.replace(/^public\\//, \"\")\n // const targetDirPublicPath = path.join(\n // config.resolvedPaths.cwd,\n // \"public\",\n // targetDirPublic\n // )\n\n // return targetDirPublicPath\n // }\n // }\n\n // Special handling for template files without targets\n if (\n !file.target &&\n file.path.includes(\"tiptap-templates/\") &&\n file.type !== \"registry:page\"\n ) {\n const match = file.path.match(/tiptap-templates\\/([^/]+)\\/(.*)/)\n if (match) {\n const [, templateName, relativePath] = match\n\n // If it's a component file in the components directory, adjust the path\n if (relativePath.startsWith(\"components/\")) {\n const finalPath = relativePath.replace(\"components/\", \"\")\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n finalPath\n )\n }\n\n // For data and other files\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n relativePath\n )\n }\n }\n\n // Special handling for data files with targets in templates\n if (\n file.target &&\n file.path.includes(\"tiptap-templates/\") &&\n file.target.includes(\"/data/\")\n ) {\n const templateMatch = file.path.match(/tiptap-templates\\/([^/]+)\\//)\n if (templateMatch) {\n const templateName = templateMatch[1]\n const dataPath = file.target.split(\"/data/\")[1]\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n templateName,\n \"data\",\n dataPath\n )\n }\n }\n\n // Original logic for files with explicit targets\n if (file.target) {\n if (file.target.startsWith(\"~/\")) {\n return path.join(config.resolvedPaths.cwd, file.target.replace(\"~/\", \"\"))\n }\n\n let target = file.target\n\n if (file.type === \"registry:page\") {\n target = resolvePageTarget(target, options.framework)\n if (!target) {\n return \"\"\n }\n }\n\n return options.isSrcDir\n ? path.join(config.resolvedPaths.cwd, \"src\", target.replace(\"src/\", \"\"))\n : path.join(config.resolvedPaths.cwd, target.replace(\"src/\", \"\"))\n }\n\n // Original logic for non-template files\n const targetDir = resolveFileTargetDirectory(file, config)\n const relativePath = resolveNestedFilePath(file.path, targetDir)\n return path.join(targetDir, relativePath)\n}\n","import path from \"node:path\"\nimport { resolveImport } from \"./resolve-import\"\nimport type { Config } from \"./get-config\"\n\nconst registryRoots = {\n components: \"components\",\n contexts: \"contexts\",\n hooks: \"hooks\",\n lib: \"lib\",\n styles: \"styles\",\n \"tiptap-icons\": \"tiptapIcons\",\n \"tiptap-extension\": \"tiptapExtensions\",\n \"tiptap-node\": \"tiptapNodes\",\n \"tiptap-ui\": \"tiptapUi\",\n \"tiptap-ui-primitive\": \"tiptapUiPrimitives\",\n \"tiptap-ui-utils\": \"tiptapUiUtils\",\n} as const satisfies Record<string, keyof Config[\"aliases\"]>\n\nexport function getRegistryPath(filePath: string) {\n const normalized = filePath.replace(/\\\\/g, \"/\").replace(/^\\/+|\\/+$/g, \"\").replace(/^registry\\//, \"\")\n const [root, ...segments] = normalized.split(\"/\")\n if (!Object.hasOwn(registryRoots, root)) return undefined\n return {\n key: registryRoots[root as keyof typeof registryRoots],\n suffix: segments.join(\"/\"),\n }\n}\n\nexport function getRegistryImportDestination(source: string, config: Config) {\n const template = source.match(/^tiptap-templates\\/([^/]+)\\/(.*)$/)\n if (template) {\n return path.join(\n config.resolvedPaths.components,\n \"tiptap-templates\",\n template[1],\n template[2].replace(/^components\\//, \"\")\n )\n }\n const registryPath = getRegistryPath(source)\n if (!registryPath) return undefined\n return path.join(config.resolvedPaths[registryPath.key], registryPath.suffix)\n}\n\nexport async function resolveOverrideImport(\n source: string,\n config: Config,\n outputFilename: string\n): Promise<string | undefined> {\n const metadata = config.overrideImports\n if (!metadata) return undefined\n const destination = getRegistryImportDestination(source, config)\n if (!destination) return undefined\n\n const candidates: { specifier: string; specificity: number }[] = []\n for (const [alias, targets] of Object.entries(metadata.paths)) {\n for (const target of targets) {\n const absoluteTarget = path.resolve(metadata.absoluteBaseUrl, target)\n const star = absoluteTarget.indexOf(\"*\")\n if (star < 0) {\n if (absoluteTarget === destination && !alias.includes(\"*\")) {\n candidates.push({\n specifier: alias,\n specificity: absoluteTarget.length,\n })\n }\n continue\n }\n const prefix = absoluteTarget.slice(0, star)\n const suffix = absoluteTarget.slice(star + 1)\n if (\n !alias.includes(\"*\") ||\n !destination.startsWith(prefix) ||\n !destination.endsWith(suffix)\n ) continue\n const match = destination.slice(\n prefix.length,\n destination.length - suffix.length\n )\n const specifier = alias.replace(\"*\", match.split(path.sep).join(\"/\"))\n // TypeScript resolves an exact paths key before any pattern.\n if (Object.hasOwn(metadata.paths, specifier)) continue\n candidates.push({\n specifier,\n specificity: prefix.length + suffix.length,\n })\n }\n }\n\n candidates.sort((a, b) => b.specificity - a.specificity)\n for (const { specifier } of candidates) {\n // Resolve before writing so an earlier alias target cannot shadow the output.\n if ((await resolveImport(specifier, metadata)) === destination) {\n return specifier\n }\n }\n\n const relative = path.relative(path.dirname(outputFilename), destination)\n .split(path.sep).join(\"/\")\n return relative.startsWith(\"../\") ? relative : `./${relative}`\n}\n","import { randomUUID } from \"node:crypto\"\nimport type { Importer } from \"sass\"\nimport type { ProjectInfo } from \"../get-project-info\"\nimport { Config } from \"@/src/utils/get-config\"\nimport { transformImport } from \"@/src/utils/transformers/transform-import\"\nimport { transformJsx } from \"@/src/utils/transformers/transform-jsx\"\nimport { transformRsc } from \"@/src/utils/transformers/transform-rsc\"\nimport { transformRemoveComponents } from \"@/src/utils/transformers/transform-remove-components\"\nimport { transformScssToCSS } from \"@/src/utils/transformers/transform-scss-to-css\"\nimport { Project, ScriptKind, type SourceFile } from \"ts-morph\"\n\nexport type TransformOpts = {\n projectInfo?: ProjectInfo | null\n filename: string\n outputFilename?: string\n raw: string\n sassImporter?: Importer<\"sync\">\n config: Config\n transformJsx?: boolean\n packageManager?: \"yarn\" | \"pnpm\" | \"bun\" | \"npm\"\n}\n\nexport type Transformer<Output = SourceFile> = (\n opts: TransformOpts & {\n sourceFile: SourceFile\n }\n) => Promise<Output>\n\nconst project = new Project({ useInMemoryFileSystem: true })\n\nexport async function transform(\n opts: TransformOpts,\n transformers: Transformer[] = [\n transformImport,\n transformRsc,\n transformRemoveComponents,\n ]\n) {\n if (opts.filename.endsWith(\".scss\") && opts.sassImporter) {\n return await transformScssToCSS(opts.raw, opts.filename, opts.sassImporter)\n }\n\n if (!/\\.(?:[cm]?[jt]s|[jt]sx)$/i.test(opts.filename)) {\n return opts.raw\n }\n\n const sourceFile = project.createSourceFile(\n `/${randomUUID()}/${opts.filename}`,\n opts.raw,\n {\n scriptKind: ScriptKind.TSX,\n }\n )\n try {\n for (const transformer of transformers) {\n await transformer({ sourceFile, ...opts })\n }\n if (opts.transformJsx) return await transformJsx({ sourceFile, ...opts })\n return sourceFile.getText()\n } finally {\n sourceFile.forget()\n }\n}\n","import { Config } from \"@/src/utils/get-config\"\nimport { resolveOverrideImport } from \"@/src/utils/registry-paths\"\nimport { Transformer } from \"@/src/utils/transformers\"\nimport { isBunProject } from \"../get-package-manager\"\n\nexport const transformImport: Transformer = async ({\n sourceFile,\n config,\n packageManager,\n outputFilename,\n}) => {\n const importDeclarations = sourceFile.getImportDeclarations()\n\n for (const importDeclaration of importDeclarations) {\n const originalSpecifier = importDeclaration.getModuleSpecifierValue()\n const overrideSpecifier =\n config.overrideImports && outputFilename && originalSpecifier.startsWith(\"@/registry/\")\n ? await resolveOverrideImport(\n originalSpecifier.slice(\"@/registry/\".length),\n config,\n outputFilename\n )\n : undefined\n let moduleSpecifier =\n overrideSpecifier ?? updateImportAliases(originalSpecifier, config)\n\n const isBun = isBunProject(config.resolvedPaths.cwd)\n\n // For Bun projects, convert .scss imports to .css\n if (isBun && moduleSpecifier.endsWith(\".scss\")) {\n moduleSpecifier = moduleSpecifier.replace(/\\.scss$/, \".css\")\n }\n\n if (moduleSpecifier) {\n importDeclaration.setModuleSpecifier(moduleSpecifier)\n }\n }\n\n return sourceFile\n}\n\nfunction updateImportAliases(moduleSpecifier: string, config: Config): string {\n // Remove \"/registry/\" from the module specifier\n if (!moduleSpecifier.startsWith(\"@/registry/\")) {\n // We fix the alias and return.\n const alias = config.aliases.components.split(\"/\")[0]\n return moduleSpecifier.replace(/^@\\//, `${alias}/`)\n }\n\n // Handle template imports specifically to preserve the template structure\n if (\n moduleSpecifier.match(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/components\\//\n )\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/components\\//,\n `${config.aliases.components}/tiptap-templates/$1/`\n )\n }\n\n // Handle template imports without the components part\n if (\n moduleSpecifier.match(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\/(?!components\\/)/\n )\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-templates\\/([^/]+)\\//,\n `${config.aliases.components}/tiptap-templates/$1/`\n )\n }\n\n if (\n config.aliases.components &&\n moduleSpecifier.match(/@\\/registry\\/components/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/components/,\n config.aliases.components\n )\n }\n\n if (\n config.aliases.contexts &&\n moduleSpecifier.match(/@\\/registry\\/contexts/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/contexts/,\n config.aliases.contexts\n )\n }\n\n if (\n config.aliases.tiptapExtensions &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-extension/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-extension/,\n config.aliases.tiptapExtensions\n )\n }\n\n if (config.aliases.hooks && moduleSpecifier.match(/@\\/registry\\/hooks/)) {\n return moduleSpecifier.replace(/@\\/registry\\/hooks/, config.aliases.hooks)\n }\n\n if (\n config.aliases.tiptapIcons &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-icons/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-icons/,\n config.aliases.tiptapIcons\n )\n }\n\n if (config.aliases.lib && moduleSpecifier.match(/@\\/registry\\/lib/)) {\n return moduleSpecifier.replace(/@\\/registry\\/lib/, config.aliases.lib)\n }\n\n if (\n config.aliases.tiptapNodes &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-node/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-node/,\n config.aliases.tiptapNodes\n )\n }\n\n if (\n config.aliases.tiptapUiPrimitives &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui-primitive/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui-primitive/,\n config.aliases.tiptapUiPrimitives\n )\n }\n\n if (\n config.aliases.tiptapUiUtils &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui-utils/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui-utils/,\n config.aliases.tiptapUiUtils\n )\n }\n\n if (\n config.aliases.tiptapUi &&\n moduleSpecifier.match(/@\\/registry\\/tiptap-ui/)\n ) {\n return moduleSpecifier.replace(\n /@\\/registry\\/tiptap-ui/,\n config.aliases.tiptapUi\n )\n }\n\n if (config.aliases.styles && moduleSpecifier.match(/@\\/registry\\/styles/)) {\n return moduleSpecifier.replace(/@\\/registry\\/styles/, config.aliases.styles)\n }\n\n // Default case - preserve all other imports\n return moduleSpecifier.replace(\n /^@\\/registry\\/[^/]+(?:\\/.*\\/)?/,\n config.aliases.components + \"/\"\n )\n}\n","import { type Transformer } from \"@/src/utils/transformers\"\nimport { transformFromAstSync } from \"@babel/core\"\nimport { ParserOptions, parse } from \"@babel/parser\"\n// eslint-disable-next-line @typescript-eslint/ban-ts-comment\n// @ts-expect-error\nimport transformTypescript from \"@babel/plugin-transform-typescript\"\nimport * as recast from \"recast\"\n\n// TODO.\n// I'm using recast for the AST here.\n// Figure out if ts-morph AST is compatible with Babel.\n\n// This is a copy of the babel options from recast/parser.\n// The goal here is to tolerate as much syntax as possible.\n// We want to be able to parse any valid tsx code.\n// See https://github.com/benjamn/recast/blob/master/parsers/_babel_options.ts.\nconst PARSE_OPTIONS: ParserOptions = {\n sourceType: \"module\",\n allowImportExportEverywhere: true,\n allowReturnOutsideFunction: true,\n startLine: 1,\n tokens: true,\n plugins: [\n \"asyncGenerators\",\n \"bigInt\",\n \"classPrivateMethods\",\n \"classPrivateProperties\",\n \"classProperties\",\n \"classStaticBlock\",\n \"decimal\",\n \"decorators-legacy\",\n \"doExpressions\",\n \"dynamicImport\",\n \"exportDefaultFrom\",\n \"exportNamespaceFrom\",\n \"functionBind\",\n \"functionSent\",\n \"importAssertions\",\n \"importMeta\",\n \"nullishCoalescingOperator\",\n \"numericSeparator\",\n \"objectRestSpread\",\n \"optionalCatchBinding\",\n \"optionalChaining\",\n [\n \"pipelineOperator\",\n {\n proposal: \"minimal\",\n },\n ],\n [\n \"recordAndTuple\",\n {\n syntaxType: \"hash\",\n },\n ],\n \"throwExpressions\",\n \"topLevelAwait\",\n \"v8intrinsic\",\n \"typescript\",\n \"jsx\",\n ],\n}\n\nexport const transformJsx: Transformer<string> = async ({\n sourceFile,\n config,\n}) => {\n const output = sourceFile.getFullText()\n\n if (config.tsx) {\n return output\n }\n\n const ast = recast.parse(output, {\n parser: {\n parse: (code: string) => {\n return parse(code, PARSE_OPTIONS)\n },\n },\n })\n\n const result = transformFromAstSync(ast, output, {\n cloneInputAst: false,\n code: false,\n ast: true,\n plugins: [transformTypescript],\n configFile: false,\n })\n\n if (!result || !result.ast) {\n throw new Error(\"Failed to transform JSX\")\n }\n\n return recast.print(result.ast).code\n}\n","import { Transformer } from \"@/src/utils/transformers\"\nimport { SyntaxKind } from \"ts-morph\"\n\nexport const transformRsc: Transformer = async ({ sourceFile, config }) => {\n if (config.rsc) {\n return sourceFile\n }\n\n // Remove \"use client\" from the top of the file.\n const first = sourceFile\n .getStatements()[0]\n ?.asKind(SyntaxKind.ExpressionStatement)\n if (\n first\n ?.getExpression()\n .asKind(SyntaxKind.StringLiteral)\n ?.getLiteralValue() === \"use client\"\n ) {\n first.remove()\n }\n\n return sourceFile\n}\n","import { Transformer } from \"@/src/utils/transformers\"\nimport {\n BinaryExpression,\n CallExpression,\n Node,\n PropertyAccessExpression,\n PropertyAssignment,\n SourceFile,\n SyntaxKind,\n} from \"ts-morph\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\n\n/**\n * Defines a rule for excluding components based on name matching patterns\n */\nexport interface ComponentExclusionRule {\n name: string // The name or pattern to match against\n matchType: \"exact\" | \"contains\" | \"startsWith\" | \"endsWith\" | \"regex\" // How to match the name\n caseSensitive?: boolean // Whether matching should be case sensitive\n pattern?: string // Regex pattern (used when matchType is \"regex\")\n onlyInFiles?: string[]\n}\n\ninterface NodeToRemove {\n node: any\n newText?: string\n action: \"remove\" | \"replace\"\n}\n\n/**\n * Default set of exclusion rules for common unwanted component patterns\n * These target development, testing, and internal components that shouldn't\n * be included in production builds or public APIs\n */\n/**\n * Default set of exclusion rules for common unwanted component patterns\n * These target development, testing, and internal components that shouldn't\n * be included in production builds or public APIs\n */\nconst DEFAULT_EXCLUSIONS: ComponentExclusionRule[] = [\n {\n name: \"cta\",\n matchType: \"contains\",\n caseSensitive: false,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"initialContent\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"JSONContent\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"onCreate\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n {\n name: \"getDocumentId\",\n matchType: \"exact\",\n caseSensitive: true,\n onlyInFiles: [\"notion-like-editor.tsx\"],\n },\n]\n\n/**\n * Determines whether a component should be excluded based on the provided rules\n * @param componentName - The name of the component to check\n * @param rules - Array of exclusion rules to apply\n * @returns true if the component should be excluded, false otherwise\n */\nfunction shouldExcludeComponent(\n componentName: string,\n rules: ComponentExclusionRule[],\n filePath: string\n): boolean {\n return rules.some((rule) => {\n // Check file path restriction\n if (\n rule.onlyInFiles &&\n !rule.onlyInFiles.some((f) => filePath.endsWith(f))\n ) {\n return false\n }\n\n const name = rule.caseSensitive\n ? componentName\n : componentName.toLowerCase()\n const ruleName = rule.caseSensitive ? rule.name : rule.name.toLowerCase()\n\n switch (rule.matchType) {\n case \"exact\":\n return name === ruleName\n case \"contains\":\n return name.includes(ruleName)\n case \"startsWith\":\n return name.startsWith(ruleName)\n case \"endsWith\":\n return name.endsWith(ruleName)\n case \"regex\":\n if (!rule.pattern) return false\n const regex = new RegExp(rule.pattern, rule.caseSensitive ? \"\" : \"i\")\n return regex.test(name)\n default:\n return false\n }\n })\n}\n\nfunction getFrameworkEnvVarName(\n constantName: string,\n framework: Framework\n): string {\n const frameworkName = framework.name\n\n if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n return `NEXT_PUBLIC_${constantName}`\n } else if (frameworkName === FRAMEWORKS.astro.name) {\n return `PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n return `VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.laravel.name ||\n frameworkName === FRAMEWORKS.manual.name\n ) {\n return constantName\n } else {\n return constantName\n }\n}\n\nfunction stripFrameworkPrefix(varName: string): string {\n return varName.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_)/, \"\")\n}\n\nasync function transformEnvironmentVariables(\n sourceFile: SourceFile,\n projectInfo: Awaited<ReturnType<typeof getProjectInfo>>\n): Promise<void> {\n if (!projectInfo) {\n return\n }\n\n const nodesToTransform: Array<{\n node: BinaryExpression | PropertyAccessExpression | CallExpression\n newText: string\n }> = []\n\n // 1. Transform environment variable access\n const binaryExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.BinaryExpression\n )\n\n for (const binaryExpr of binaryExpressions) {\n if (binaryExpr.getOperatorToken().getKind() === SyntaxKind.BarBarToken) {\n const left = binaryExpr.getLeft()\n const leftText = left.getText()\n\n if (leftText.match(/^process\\.env\\.[A-Z_]+$/)) {\n const match = leftText.match(/process\\.env\\.([A-Z_]+)/)\n if (match && match[1]) {\n const constantName = stripFrameworkPrefix(match[1])\n const frameworkName = projectInfo.framework.name\n\n let transformedEnvVar: string\n if (frameworkName === FRAMEWORKS.astro.name) {\n transformedEnvVar = `import.meta.env.PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n transformedEnvVar = `import.meta.env.VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n transformedEnvVar = `process.env.NEXT_PUBLIC_${constantName}`\n } else {\n transformedEnvVar = `process.env.${constantName}`\n }\n\n const rightSide = binaryExpr.getRight().getText()\n const newExpression = `${transformedEnvVar} || ${rightSide}`\n\n nodesToTransform.push({\n node: binaryExpr,\n newText: newExpression,\n })\n }\n }\n }\n }\n\n // 2. Transform alert calls that contain environment variable lists\n const callExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.CallExpression\n )\n\n for (const callExpr of callExpressions) {\n const expression = callExpr.getExpression()\n const expressionText = expression.getText()\n\n // Check for alert calls\n if (expressionText.match(/^alert$/)) {\n const args = callExpr.getArguments()\n if (args.length > 0) {\n const firstArg = args[0]\n const argText = firstArg.getText()\n\n // Look for template literals or strings that contain environment variable lists\n if (\n argText.includes(\"TIPTAP_COLLAB_TOKEN\") ||\n argText.includes(\"TIPTAP_COLLAB_DOC_PREFIX\") ||\n argText.includes(\"TIPTAP_AI_TOKEN\")\n ) {\n let newArgText = argText\n\n const envVarsToTransform = [\n \"TIPTAP_COLLAB_DOC_PREFIX\",\n \"TIPTAP_COLLAB_APP_ID\",\n \"TIPTAP_COLLAB_TOKEN\",\n \"TIPTAP_AI_APP_ID\",\n \"TIPTAP_AI_TOKEN\",\n \"USE_JWT_TOKEN_API_ENDPOINT\",\n ]\n\n for (let constantName of envVarsToTransform) {\n const frameworkEnvVarName = getFrameworkEnvVarName(\n constantName,\n projectInfo.framework\n )\n newArgText = newArgText.replace(\n new RegExp(constantName, \"g\"),\n frameworkEnvVarName\n )\n }\n\n if (newArgText !== argText) {\n const newCallExpr = `${expressionText}(${newArgText})`\n nodesToTransform.push({\n node: callExpr,\n newText: newCallExpr,\n })\n }\n }\n }\n }\n }\n\n // 3. Transform standalone process.env\n const propertyAccessExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertyAccessExpression\n )\n\n for (const propAccess of propertyAccessExpressions) {\n const propAccessText = propAccess.getText()\n\n if (propAccessText.match(/^process\\.env\\.[A-Z_]+$/)) {\n const parent = propAccess.getParent()\n if (parent?.getKind() === SyntaxKind.BinaryExpression) {\n continue\n }\n\n const match = propAccessText.match(/process\\.env\\.([A-Z_]+)/)\n if (match && match[1]) {\n const constantName = stripFrameworkPrefix(match[1])\n const frameworkName = projectInfo.framework.name\n\n let transformedEnvVar: string\n if (frameworkName === FRAMEWORKS.astro.name) {\n transformedEnvVar = `import.meta.env.PUBLIC_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n transformedEnvVar = `import.meta.env.VITE_${constantName}`\n } else if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n transformedEnvVar = `process.env.NEXT_PUBLIC_${constantName}`\n } else {\n transformedEnvVar = `process.env.${constantName}`\n }\n\n nodesToTransform.push({\n node: propAccess,\n newText: transformedEnvVar,\n })\n }\n }\n }\n\n // Apply all transformations\n for (const { node, newText } of nodesToTransform) {\n try {\n node.replaceWithText(newText)\n } catch (error) {\n console.warn(`Skipping transformation of node: ${error}`)\n }\n }\n}\n\n/**\n * Main transformer function that removes excluded components from TypeScript/React source files\n * This transformer processes various AST nodes to remove unwanted components based on exclusion rules\n */\nexport const transformRemoveComponents: Transformer = async ({\n sourceFile,\n config,\n projectInfo,\n}) => {\n // Use default exclusion rules (could be made configurable in the future)\n const exclusionRules: ComponentExclusionRule[] = DEFAULT_EXCLUSIONS\n const filePath = sourceFile.getFilePath()\n // Collect all nodes to be modified instead of modifying immediately\n const nodesToModify: NodeToRemove[] = []\n\n // STEP 1: Collect excluded component imports\n const importDeclarations = sourceFile.getImportDeclarations()\n\n for (const importDeclaration of importDeclarations) {\n const moduleSpecifier = importDeclaration.getModuleSpecifierValue()\n\n // Check if the entire import module should be removed\n if (\n exclusionRules.some((rule) =>\n shouldExcludeComponent(moduleSpecifier, [rule], filePath)\n )\n ) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n continue\n }\n\n // Handle default imports (import defaultName from \"...\")\n const defaultImport = importDeclaration.getDefaultImport()\n if (\n defaultImport &&\n shouldExcludeComponent(defaultImport.getText(), exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n continue\n }\n\n // Remove specific named imports that match exclusion rules\n const namedImports = importDeclaration.getNamedImports()\n const excludedImports = namedImports.filter((namedImport) =>\n shouldExcludeComponent(namedImport.getName(), exclusionRules, filePath)\n )\n\n if (excludedImports.length > 0) {\n excludedImports.forEach((excludedImport) =>\n nodesToModify.push({ node: excludedImport, action: \"remove\" })\n )\n\n // Check if this would remove all named imports\n const remainingImports = namedImports.filter(\n (namedImport) => !excludedImports.includes(namedImport)\n )\n\n if (remainingImports.length === 0 && !defaultImport) {\n nodesToModify.push({ node: importDeclaration, action: \"remove\" })\n }\n }\n }\n\n // STEP 2: Collect excluded component exports\n const exportDeclarations = sourceFile.getExportDeclarations()\n\n for (const exportDeclaration of exportDeclarations) {\n const namedExports = exportDeclaration.getNamedExports()\n const excludedExports = namedExports.filter((namedExport) =>\n shouldExcludeComponent(namedExport.getName(), exclusionRules, filePath)\n )\n\n if (excludedExports.length > 0) {\n excludedExports.forEach((excludedExport) =>\n nodesToModify.push({ node: excludedExport, action: \"remove\" })\n )\n\n // Check if this would remove all named exports\n const remainingExports = namedExports.filter(\n (namedExport) => !excludedExports.includes(namedExport)\n )\n\n if (remainingExports.length === 0) {\n nodesToModify.push({ node: exportDeclaration, action: \"remove\" })\n }\n }\n }\n\n // STEP 3: Collect excluded component variable declarations\n const variableStatements = sourceFile.getVariableStatements()\n\n for (const variableStatement of variableStatements) {\n const declarations = variableStatement.getDeclarations()\n const excludedDeclarations = declarations.filter((declaration) =>\n shouldExcludeComponent(declaration.getName(), exclusionRules, filePath)\n )\n\n if (excludedDeclarations.length > 0) {\n if (declarations.length === excludedDeclarations.length) {\n // Remove entire variable statement if all declarations are excluded\n nodesToModify.push({ node: variableStatement, action: \"remove\" })\n } else {\n // Remove only excluded declarations, keep others\n excludedDeclarations.forEach((declaration) =>\n nodesToModify.push({ node: declaration, action: \"remove\" })\n )\n }\n }\n }\n\n // STEP 4: Collect excluded component function declarations\n const functionDeclarations = sourceFile.getFunctions()\n\n for (const functionDeclaration of functionDeclarations) {\n const functionName = functionDeclaration.getName()\n if (\n functionName &&\n shouldExcludeComponent(functionName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: functionDeclaration, action: \"remove\" })\n }\n }\n\n // STEP 5: Collect excluded component interface declarations\n const interfaceDeclarations = sourceFile.getInterfaces()\n\n for (const interfaceDeclaration of interfaceDeclarations) {\n const interfaceName = interfaceDeclaration.getName()\n if (shouldExcludeComponent(interfaceName, exclusionRules, filePath)) {\n nodesToModify.push({ node: interfaceDeclaration, action: \"remove\" })\n }\n }\n\n // STEP 6: Collect excluded component type aliases\n const typeAliases = sourceFile.getTypeAliases()\n\n for (const typeAlias of typeAliases) {\n const typeName = typeAlias.getName()\n if (shouldExcludeComponent(typeName, exclusionRules, filePath)) {\n nodesToModify.push({ node: typeAlias, action: \"remove\" })\n }\n }\n\n // STEP 6.5: Collect excluded interface property signatures\n const propertySignatures = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertySignature\n )\n\n for (const propertySignature of propertySignatures) {\n const propName = propertySignature.getName()\n if (\n propName &&\n shouldExcludeComponent(propName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: propertySignature, action: \"remove\" })\n }\n }\n\n // STEP 7: Collect excluded JSX elements from React components\n const jsxElements = sourceFile.getDescendantsOfKind(SyntaxKind.JsxElement)\n\n for (const jsxElement of jsxElements) {\n const tagName = jsxElement.getOpeningElement().getTagNameNode().getText()\n if (shouldExcludeComponent(tagName, exclusionRules, filePath)) {\n nodesToModify.push({\n node: jsxElement,\n action: \"replace\",\n newText: \"\",\n })\n }\n }\n\n // STEP 8: Collect excluded self-closing JSX elements\n const jsxSelfClosingElements = sourceFile.getDescendantsOfKind(\n SyntaxKind.JsxSelfClosingElement\n )\n\n for (const jsxSelfClosingElement of jsxSelfClosingElements) {\n const tagName = jsxSelfClosingElement.getTagNameNode().getText()\n if (shouldExcludeComponent(tagName, exclusionRules, filePath)) {\n nodesToModify.push({\n node: jsxSelfClosingElement,\n action: \"replace\",\n newText: \"\",\n })\n }\n }\n\n // STEP 9: Collect excluded component properties from objects\n const propertyAssignments = sourceFile.getDescendantsOfKind(\n SyntaxKind.PropertyAssignment\n )\n\n for (const propertyAssignment of propertyAssignments) {\n const propertyName = propertyAssignment.getName()\n if (\n propertyName &&\n shouldExcludeComponent(propertyName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: propertyAssignment, action: \"remove\" })\n }\n }\n\n // STEP 10: Collect excluded JSX attributes\n const jsxAttributes = sourceFile.getDescendantsOfKind(SyntaxKind.JsxAttribute)\n\n for (const jsxAttribute of jsxAttributes) {\n const attributeName = jsxAttribute.getNameNode().getText()\n if (\n attributeName &&\n shouldExcludeComponent(attributeName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: jsxAttribute, action: \"remove\" })\n }\n }\n\n // STEP 11: Collect excluded parameters from function/method signatures\n const parameters = sourceFile.getDescendantsOfKind(SyntaxKind.Parameter)\n\n for (const parameter of parameters) {\n const parameterName = parameter.getName()\n if (\n parameterName &&\n shouldExcludeComponent(parameterName, exclusionRules, filePath)\n ) {\n const paramList = parameter.getParent()\n\n // Only proceed if the parent is a function-like structure\n if (\n paramList &&\n (Node.isFunctionDeclaration(paramList) ||\n Node.isArrowFunction(paramList) ||\n Node.isFunctionExpression(paramList) ||\n Node.isMethodDeclaration(paramList))\n ) {\n const allParams = paramList.getParameters()\n const index = allParams.indexOf(parameter)\n\n // Handle comma removal for cleaner output\n if (index !== -1) {\n if (index === allParams.length - 1 && index > 0) {\n const prev = parameter.getPreviousSibling()\n if (prev?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prev, action: \"remove\" })\n }\n } else {\n const next = parameter.getNextSibling()\n if (next?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: next, action: \"remove\" })\n }\n }\n\n nodesToModify.push({ node: parameter, action: \"remove\" })\n }\n }\n }\n }\n\n // STEP 11.1: Handle function arguments in call expressions\n const callExpressions = sourceFile.getDescendantsOfKind(\n SyntaxKind.CallExpression\n )\n\n for (const callExpr of callExpressions) {\n const args = callExpr.getArguments()\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]\n const argText = arg.getText()\n\n if (shouldExcludeComponent(argText, exclusionRules, filePath)) {\n // Handle comma removal for cleaner output\n if (i === args.length - 1) {\n // Last argument - remove preceding comma if exists\n const prevSibling = arg.getPreviousSibling()\n if (prevSibling && prevSibling.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prevSibling, action: \"remove\" })\n }\n } else {\n // Not last argument - remove following comma if exists\n const nextSibling = arg.getNextSibling()\n if (nextSibling && nextSibling.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: nextSibling, action: \"remove\" })\n }\n }\n\n nodesToModify.push({ node: arg, action: \"remove\" })\n }\n }\n }\n\n // STEP 11.5: Collect excluded binding elements (destructured parameters)\n const bindingElements = sourceFile.getDescendantsOfKind(\n SyntaxKind.BindingElement\n )\n\n for (const bindingElement of bindingElements) {\n const bindingName = bindingElement.getName()\n if (\n bindingName &&\n shouldExcludeComponent(bindingName, exclusionRules, filePath)\n ) {\n // Handle comma cleanup (already correct in your code)\n const bindingPattern = bindingElement.getParent()\n if (bindingPattern) {\n const allBindings = bindingPattern.getDescendantsOfKind(\n SyntaxKind.BindingElement\n )\n const bindingIndex = allBindings.indexOf(bindingElement)\n\n if (bindingIndex === allBindings.length - 1) {\n const prevSibling = bindingElement.getPreviousSibling()\n if (prevSibling?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: prevSibling, action: \"remove\" })\n }\n } else {\n const nextSibling = bindingElement.getNextSibling()\n if (nextSibling?.getKind() === SyntaxKind.CommaToken) {\n nodesToModify.push({ node: nextSibling, action: \"remove\" })\n }\n }\n }\n\n nodesToModify.push({ node: bindingElement, action: \"remove\" })\n }\n }\n\n // STEP 12: Collect excluded identifiers in function calls and expressions\n const identifiers = sourceFile.getDescendantsOfKind(SyntaxKind.Identifier)\n\n for (const identifier of identifiers) {\n const identifierName = identifier.getText()\n if (shouldExcludeComponent(identifierName, exclusionRules, filePath)) {\n const parent = identifier.getParent()\n\n // Handle different contexts where the identifier appears\n if (parent) {\n const parentKind = parent.getKind()\n\n // Remove entire call expression if it's calling an excluded function\n if (parentKind === SyntaxKind.CallExpression) {\n const callExpr = parent as CallExpression\n if (callExpr.getExpression() === identifier) {\n // This is a function call like getDocumentId()\n nodesToModify.push({ node: callExpr, action: \"remove\" })\n } else {\n // This is an argument in a function call\n const args = callExpr.getArguments()\n const argIndex = args.findIndex((arg) => arg === identifier)\n if (argIndex !== -1) {\n nodesToModify.push({ node: identifier, action: \"remove\" })\n }\n }\n }\n\n // Remove property access expressions with excluded identifiers\n if (parentKind === SyntaxKind.PropertyAccessExpression) {\n const propAccess = parent as PropertyAccessExpression\n if (propAccess.getName() === identifierName) {\n nodesToModify.push({ node: propAccess, action: \"remove\" })\n }\n }\n\n // Remove variable references and expressions\n if (\n parentKind === SyntaxKind.VariableDeclaration ||\n parentKind === SyntaxKind.BinaryExpression ||\n parentKind === SyntaxKind.IfStatement ||\n parentKind === SyntaxKind.ConditionalExpression\n ) {\n nodesToModify.push({ node: identifier, action: \"remove\" })\n }\n\n // Remove from object literal property values\n if (parentKind === SyntaxKind.PropertyAssignment) {\n const propAssignment = parent as PropertyAssignment\n if (propAssignment.getInitializer() === identifier) {\n nodesToModify.push({ node: propAssignment, action: \"remove\" })\n }\n }\n }\n }\n }\n\n // STEP 13: Collect excluded shorthand property assignments (e.g., { initialContent })\n const shorthandPropertyAssignments = sourceFile.getDescendantsOfKind(\n SyntaxKind.ShorthandPropertyAssignment\n )\n\n for (const shorthandProp of shorthandPropertyAssignments) {\n const propName = shorthandProp.getName()\n if (\n propName &&\n shouldExcludeComponent(propName, exclusionRules, filePath)\n ) {\n nodesToModify.push({ node: shorthandProp, action: \"remove\" })\n }\n }\n\n // Apply environment variable transformations first (before removing nodes)\n await transformEnvironmentVariables(\n sourceFile,\n projectInfo === undefined\n ? await getProjectInfo(config.resolvedPaths.cwd)\n : projectInfo\n )\n\n // STEP 16: Apply all collected modifications\n // Sort by position (deepest nodes first) to avoid accessing removed parents\n nodesToModify.sort((a, b) => {\n const aStart = a.node.getStart?.() ?? 0\n const bStart = b.node.getStart?.() ?? 0\n return bStart - aStart // Reverse order - process deepest/rightmost first\n })\n\n // Apply transformations safely\n for (const { node, action, newText } of nodesToModify) {\n try {\n // Check if node still exists and hasn't been removed\n if (node.wasForgotten?.() === true) {\n continue // Skip nodes that were already removed\n }\n\n if (action === \"remove\") {\n if (typeof node.remove === \"function\") {\n node.remove()\n }\n } else if (action === \"replace\" && newText !== undefined) {\n node.replaceWithText(newText)\n }\n } catch (error) {\n // console.warn(`Skipping transformation of node: ${error}`)\n // Continue with other transformations even if one fails\n }\n }\n\n // Return the modified source file with excluded components removed\n return sourceFile\n}\n","import { posix } from \"node:path\"\nimport type { Importer } from \"sass\"\nimport type { RegistryItem } from \"../registry/schema\"\n\n// Sass resolves these files before the installer writes them to the project.\nexport function registrySassImporter(\n files: RegistryItem[\"files\"]\n): Importer<\"sync\"> {\n const styles = new Map<string, string>()\n for (const file of files ?? []) {\n if (file.path.endsWith(\".scss\") && file.content !== undefined) {\n styles.set(new URL(file.path, \"registry:/\").href, file.content)\n }\n }\n\n return {\n canonicalize(specifier, { containingUrl }) {\n const url = new URL(specifier, containingUrl ?? \"registry:/\")\n if (url.protocol !== \"registry:\") return null\n\n const candidates = url.pathname.endsWith(\".scss\")\n ? [url.pathname]\n : [url.pathname + \".scss\", posix.join(url.pathname, \"index.scss\")]\n for (const filename of candidates) {\n const partial = posix.join(\n posix.dirname(filename),\n \"_\" + posix.basename(filename)\n )\n const matches = [filename, partial]\n .map((name) => new URL(name, url))\n .filter((candidate) => styles.has(candidate.href))\n if (matches.length > 1)\n throw new Error(`Ambiguous Sass import: ${specifier}`)\n if (matches.length === 1) return matches[0]\n }\n return null\n },\n load(url) {\n const contents = styles.get(url.href)\n return contents === undefined ? null : { contents, syntax: \"scss\" }\n },\n }\n}\n\nexport async function transformScssToCSS(\n content: string,\n filename: string,\n importer: Importer<\"sync\">\n): Promise<string> {\n try {\n const { compileString } = await import(\"sass\")\n return compileString(content, {\n url: new URL(filename, \"registry:/\"),\n importers: [importer],\n style: \"expanded\",\n }).css\n } catch (error) {\n throw new Error(\n `Failed to compile SCSS to CSS: ${error instanceof Error ? error.message : String(error)}`\n )\n }\n}\n","import os from \"node:os\"\nimport path from \"node:path\"\nimport fs from \"fs-extra\"\nimport { execa } from \"execa\"\nimport semver from \"semver\"\nimport { createThemedConfirm, handleLogin } from \"../commands/auth\"\nimport { tokenStorage } from \"./bootstrap\"\nimport { getPackageManager, getPackageRunner } from \"./get-package-manager\"\nimport {\n getRegistryConfigDirectory,\n saveAuthToken,\n type PackageManager,\n} from \"./package-manager-config\"\n\nconst docs = \"https://tiptap.dev/docs/guides/pro-extensions\"\nexport async function registryLoginCommand(cwd: string) {\n const runner = await getPackageRunner(cwd)\n const command = `${runner} @tiptap/cli login --registry-only --write-config`\n return `Run in ${path.resolve(cwd)}\\n${command}`\n}\n\nconst privatePackage = /^@tiptap-pro\\/[\\w.-]+(?:@[^/]+)?$/\n\ntype RegistryRoute = \"tiptap\" | \"mirror\" | \"public\"\n\nfunction classifyRoute(value: string | undefined): RegistryRoute {\n if (!value || !URL.canParse(value)) return \"public\"\n const url = new URL(value)\n if (url.origin === \"https://registry.tiptap.dev\") return \"tiptap\"\n if (![\"https:\", \"http:\"].includes(url.protocol)) return \"public\"\n return [\"registry.npmjs.org\", \"registry.yarnpkg.com\"].includes(url.hostname)\n ? \"public\"\n : \"mirror\"\n}\n\nasync function bunUserNpmrc(startDir: string, home: string, xdg?: string) {\n const selected =\n process.env.NPM_CONFIG_USERCONFIG || process.env.npm_config_userconfig\n const homeFile = path.join(home, \".npmrc\")\n if (!selected && !xdg) return homeFile\n\n const { stdout } = await execa(\"bun\", [\"--version\"], { cwd: startDir })\n const version = stdout.trim()\n if (selected && semver.gte(version, \"1.4.4\")) {\n return selected.startsWith(\"~/\")\n ? path.join(home, selected.slice(2))\n : path.resolve(startDir, selected)\n }\n if (xdg) {\n const file = path.join(xdg, \".npmrc\")\n if (semver.lt(version, \"1.4.0\") || (await fs.pathExists(file))) return file\n }\n return homeFile\n}\n\nasync function bunRoute(cwd: string, startDir: string) {\n // Bun supports registry overrides in bunfig.toml in addition to .npmrc.\n const home = os.homedir()\n const xdg = process.env.XDG_CONFIG_HOME\n const configHome = xdg && path.isAbsolute(xdg) ? xdg : undefined\n const files = [\n path.join(configHome || home, \".bunfig.toml\"),\n path.join(cwd, \"bunfig.toml\"),\n ]\n const configs = []\n for (const file of files) {\n if (await fs.pathExists(file)) configs.push(file)\n }\n let bunScope: string | undefined\n let bunDefault: string | undefined\n if (configs.length) {\n const query = `\n let scope, registry\n for (const file of process.argv.slice(1)) {\n const { install } = (await import(file)).default\n scope = install?.scopes?.[\"tiptap-pro\"] ?? install?.scopes?.[\"@tiptap-pro\"] ?? scope\n registry = install?.registry ?? registry\n }\n const url = value => typeof value === \"string\" ? value : value?.url\n console.log(JSON.stringify([url(scope), url(registry)]))\n `\n const { stdout } = await execa(\"bun\", [\"-e\", query, ...configs], { cwd })\n const [scope, defaultRegistry] = JSON.parse(stdout)\n bunScope = scope\n bunDefault = defaultRegistry\n }\n const npm = await npmrcRoutes([\n await bunUserNpmrc(startDir, home, configHome),\n path.join(cwd, \".npmrc\"),\n ])\n return expandRegistry(\n bunScope ||\n npm.scope ||\n process.env.BUN_CONFIG_REGISTRY ||\n process.env.npm_config_registry ||\n process.env.NPM_CONFIG_REGISTRY ||\n bunDefault ||\n npm.registry\n )\n}\n\nfunction expandRegistry(value: string | undefined) {\n return value\n ?.replace(/^(['\"])(.*)\\1$/, \"$2\")\n .replace(\n /\\$\\{([^}]+)\\}|\\$([A-Z_][A-Z_0-9]*)/g,\n (_, wrapped: string, plain: string) => process.env[wrapped || plain] ?? \"\"\n )\n}\n\nasync function npmrcRoutes(files: string[]) {\n let npmScope: string | undefined\n let npmDefault: string | undefined\n for (const file of files) {\n if (!(await fs.pathExists(file))) continue\n const contents = await fs.readFile(file, \"utf8\")\n for (const line of contents.split(\"\\n\")) {\n const match =\n /^\\s*(@tiptap-pro:registry|registry)\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^;#]*)/.exec(\n line\n )\n if (match?.[1] === \"registry\") npmDefault = match[2].trim()\n else if (match) npmScope = match[2].trim()\n }\n }\n return {\n scope: expandRegistry(npmScope),\n registry: expandRegistry(npmDefault),\n }\n}\n\nfunction yarnClassicGlobalNpmrc() {\n const nodeDir = path.dirname(process.execPath)\n const prefix =\n process.env.PREFIX ||\n (process.platform === \"win32\"\n ? nodeDir\n : path.join(process.env.DESTDIR || \"\", path.dirname(nodeDir)))\n return path.join(prefix, \"etc\", \"npmrc\")\n}\n\nasync function readRegistryRoute(\n manager: PackageManager,\n cwd: string,\n startDir: string\n) {\n const get = async (args: string[]) =>\n (await execa(manager, args, { cwd })).stdout.trim()\n try {\n if (manager === \"bun\") return classifyRoute(await bunRoute(cwd, startDir))\n if (manager === \"yarn\" && !(await get([\"--version\"])).startsWith(\"1.\")) {\n // Yarn reads the effective scope from .yarnrc.yml, home settings and the environment.\n const scope = await execa(\n manager,\n [\n \"config\",\n \"get\",\n 'npmScopes[\"tiptap-pro\"].npmRegistryServer',\n \"--json\",\n ],\n { cwd, reject: false }\n )\n const value = scope.stdout.trim()\n const route =\n scope.exitCode === 0 && value && value !== \"undefined\"\n ? JSON.parse(value)\n : undefined\n return classifyRoute(\n route ||\n JSON.parse(\n await get([\"config\", \"get\", \"npmRegistryServer\", \"--json\"])\n )\n )\n }\n const scope = await get([\"config\", \"get\", \"@tiptap-pro:registry\"])\n const scopedRegistry =\n scope && scope !== \"undefined\" && scope !== \"null\" ? scope : undefined\n if (manager === \"yarn\") {\n const ancestors = []\n for (\n let dir = path.dirname(cwd);\n dir !== path.dirname(dir);\n dir = path.dirname(dir)\n ) {\n ancestors.unshift(path.join(dir, \".npmrc\"))\n }\n // Yarn Classic checks its npm registry settings before its default Yarn registry.\n const userconfig =\n process.env.npm_config_userconfig ||\n process.env.NPM_CONFIG_USERCONFIG ||\n path.join(os.homedir(), \".npmrc\")\n const npm = await npmrcRoutes([\n ...ancestors,\n yarnClassicGlobalNpmrc(),\n userconfig,\n path.join(cwd, \".npmrc\"),\n ])\n const route =\n npm.scope ||\n scopedRegistry ||\n process.env.npm_config_registry ||\n process.env.NPM_CONFIG_REGISTRY ||\n npm.registry\n if (route) return classifyRoute(route)\n }\n if (scopedRegistry) return classifyRoute(scopedRegistry)\n if (manager === \"pnpm\") {\n const settings = await get([\"config\", \"get\", \"registries\", \"--json\"])\n if (settings && settings !== \"undefined\" && settings !== \"null\") {\n const registries = JSON.parse(settings)\n if (registries[\"@tiptap-pro\"])\n return classifyRoute(registries[\"@tiptap-pro\"])\n if (registries.default) return classifyRoute(registries.default)\n }\n }\n return classifyRoute(await get([\"config\", \"get\", \"registry\"]))\n } catch {\n throw new Error(\n `Could not read the registry route from ${manager} in ${cwd}. Check the package manager configuration. ${docs}`\n )\n }\n}\n\nexport async function getTiptapRegistryRoute(\n cwd: string\n): Promise<RegistryRoute> {\n const manager = await getPackageManager(cwd)\n return readRegistryRoute(\n manager,\n await getRegistryConfigDirectory(cwd, manager),\n path.resolve(cwd)\n )\n}\n\nexport async function ensureTiptapRegistryAccess(\n packages: string[],\n cwd: string,\n { interactive }: { interactive: boolean }\n): Promise<void> {\n const requested = packages.filter((pkg) => privatePackage.test(pkg))\n if (!requested.length) return\n\n const manager = await getPackageManager(cwd)\n const directory = await getRegistryConfigDirectory(cwd, manager)\n if (\n (await readRegistryRoute(manager, directory, path.resolve(cwd))) !==\n \"public\"\n )\n return\n\n const token = tokenStorage.getAuthToken()\n if (token) {\n if (await saveAuthToken(token, manager, directory)) return\n throw new Error(\n `Configure package registry access in ${directory}. ${docs}\\n${await registryLoginCommand(directory)}`\n )\n }\n await renewTiptapRegistryAccess(requested, cwd, { interactive })\n}\n\nexport async function renewTiptapRegistryAccess(\n packages: string[],\n cwd: string,\n { interactive }: { interactive: boolean }\n): Promise<void> {\n const requested = packages.filter((pkg) => privatePackage.test(pkg))\n if (!requested.length) return\n const recovery = `Configure package registry access for ${requested.join(\", \")}. ${docs}\\n${await registryLoginCommand(cwd)}`\n if (\n !interactive ||\n !(await createThemedConfirm(\n `Sign in and configure this project to download ${requested.join(\", \")} from the Tiptap registry?`\n ))\n ) {\n throw new Error(recovery)\n }\n if (\n !(await handleLogin({\n cwd,\n registryOnly: true,\n writeConfig: true,\n showMessage: false,\n }))\n ) {\n throw new Error(recovery)\n }\n}\n","import path from \"node:path\"\nimport { createTwoFilesPatch } from \"diff\"\nimport {\n connectCollaboration,\n editorComponentName,\n} from \"./connect-collaboration\"\nimport type { Config } from \"./get-config\"\nimport { resolveOverrideImport } from \"./registry-paths\"\nimport { parseEditorSource } from \"./editor-source\"\nimport type { RegistryFeature, RegistryItem } from \"./registry/schema\"\nimport {\n getInstallDestination,\n readExistingFile,\n type PlannedFile,\n} from \"./updaters/update-files\"\nimport {\n editorImportPath,\n hasValueExport,\n moduleSpecifier,\n updateEditor,\n} from \"./plan-editor-extension\"\n\nexport interface CollaborationSetup {\n status: \"connected\" | \"unchanged\" | \"pending\"\n editorPath?: string\n componentName?: string\n wrapperPath: string\n importPath?: string\n configPath: string\n entryPath?: string\n customPagePath?: string\n tokenPath?: string\n existingTokenRoute?: boolean\n suggestedTemplate?: string\n reason?: string\n patch?: string\n}\n\ntype CollaborationIntegration = Extract<\n RegistryFeature[\"integration\"],\n { kind: \"collaboration\" }\n>\n\nexport async function getTemplateDemoImport(\n template: RegistryItem | undefined,\n editor: PlannedFile | undefined,\n entries: PlannedFile[],\n config: Config\n) {\n if (\n template?.name !== \"simple-editor\" ||\n editor?.registryPath !==\n \"tiptap-templates/simple/components/simple-editor.tsx\"\n )\n return\n const demoPath = \"tiptap-templates/simple/data/content.json\"\n const demo = entries.find((file) => file.registryPath === demoPath)\n if (\n !demo ||\n (demo.before !== null && demo.before !== demo.after) ||\n demo.path !== path.join(path.dirname(editor.path), \"data\", \"content.json\")\n )\n return\n const raw = template.files?.find(\n (file) => file.path === editor.registryPath\n )?.content\n const rawEditor = raw && parseEditorSource(raw)\n if (!rawEditor) return\n const imports = rawEditor.getImportDeclarations().filter((declaration) => {\n const specifier = declaration.getModuleSpecifierValue()\n return (\n specifier === `@/registry/${demoPath}` ||\n (specifier.startsWith(\".\") &&\n path.posix.join(path.posix.dirname(editor.registryPath!), specifier) ===\n demoPath)\n )\n })\n const binding = imports[0]?.getDefaultImport()?.getText()\n if (imports.length !== 1 || !binding) return\n const installed = parseEditorSource(editor.before ?? editor.after)\n ?.getImportDeclarations()\n .filter((item) => item.getDefaultImport()?.getText() === binding)\n const specifier = installed?.[0]?.getModuleSpecifierValue()\n if (installed?.length !== 1 || !specifier) return\n if (specifier.startsWith(\"./\") || specifier.startsWith(\"../\")) {\n if (\n path.resolve(path.dirname(editor.path), specifier) === demo.path &&\n path.resolve(path.dirname(editor.realPath), specifier) === demo.realPath\n )\n return { specifier, path: demo.path }\n return\n }\n const registryImport = config.overrideImports\n ? await resolveOverrideImport(demoPath, config, editor.path)\n : `${config.aliases.components}/${demoPath}`\n if (specifier === registryImport) return { specifier, path: demo.path }\n}\n\nexport function planCollaboration(\n integration: CollaborationIntegration,\n files: Map<string, PlannedFile>,\n editor: PlannedFile | undefined,\n config: Config,\n existingTokenRoute: boolean,\n customPagePath?: string,\n demoImport?: { specifier: string; path: string }\n): CollaborationSetup {\n const cwd = config.resolvedPaths.cwd\n const entries = [...files.values()]\n const settings = entries.find(\n (file) => file.registryPath === integration.config\n )\n const wrapper = entries.find(\n (file) => file.registryPath === integration.wrapper\n )\n const token = entries.find(\n (file) => file.registryPath === integration.tokenRoute\n )\n if (!settings || !wrapper)\n throw new Error(\n \"The registry must provide the Collaboration wrapper and configuration.\"\n )\n const setup: CollaborationSetup = {\n status: \"pending\",\n wrapperPath: path.relative(cwd, wrapper.path),\n configPath: path.relative(cwd, settings.path),\n tokenPath: token && path.relative(cwd, token.path),\n existingTokenRoute,\n customPagePath,\n }\n setup.editorPath = editor && path.relative(cwd, editor.path)\n if (!hasValueExport(wrapper, \"withCollaboration\")) {\n setup.reason = `Export withCollaboration as a value from ${setup.wrapperPath} before connecting the editor.`\n return setup\n }\n if (!editor) return setup\n if ([settings, wrapper, token].includes(editor))\n throw new Error(\"Choose an editor outside the Collaboration setup files.\")\n const source = editor.after\n const name = editorComponentName(source)\n const specifier = editorImportPath(editor, wrapper)\n setup.componentName = name\n setup.importPath = specifier\n if (!specifier) {\n setup.reason =\n \"A symlink changes the relative import. Select the editor at its real path.\"\n return setup\n }\n const connected = name\n ? connectCollaboration(source, name, specifier, demoImport?.specifier)\n : {\n reason:\n \"The connector needs one useEditor call inside a named component.\",\n }\n if (\"reason\" in connected) {\n setup.reason = connected.reason\n if (\n !editor.registryPath &&\n /(?:^|\\/)tiptap-templates\\/simple\\/simple-editor\\.[jt]sx$/.test(\n editor.path.split(path.sep).join(\"/\")\n )\n )\n setup.suggestedTemplate = \"simple-editor\"\n setup.reason += \" Adapt the example patch to your editor.\"\n const component = name && /^[A-Z][\\w$]*$/.test(name) ? name : \"Editor\"\n const example = [\n 'import { EditorContent, useEditor } from \"@tiptap/react\"',\n 'import { StarterKit } from \"@tiptap/starter-kit\"',\n `export function ${component}() {`,\n \" const editor = useEditor({\",\n \" extensions: [StarterKit],\",\n \" })\",\n \" return <EditorContent editor={editor} />\",\n \"}\",\n \"\",\n ].join(\"\\n\")\n const wired = connectCollaboration(example, component, specifier)\n if (\"source\" in wired)\n setup.patch = createTwoFilesPatch(\n \"example-editor.tsx\",\n \"example-editor.tsx\",\n example,\n wired.source\n )\n return setup\n }\n if (demoImport && connected.removedDemoContent)\n editor.requiredFiles = [...(editor.requiredFiles ?? []), demoImport.path]\n setup.status = updateEditor(files, editor, connected.source, wrapper)\n return setup\n}\n\nexport async function planNewViteEditorEntry(\n config: Config,\n editor: PlannedFile\n): Promise<PlannedFile> {\n const cwd = config.resolvedPaths.cwd\n const filePath = path.join(cwd, \"src\", config.tsx ? \"App.tsx\" : \"App.jsx\")\n const realPath = await getInstallDestination(filePath, config)\n const before = await readExistingFile(realPath)\n const source = parseEditorSource(editor.after)\n const name = editorComponentName(editor.after)\n const binding = source?.getDefaultExportSymbol()\n ? \"default\"\n : name &&\n source?.getExportSymbols().some((symbol) => symbol.getName() === name)\n ? `${name} as default`\n : undefined\n if (!binding)\n throw new Error(\n \"The template editor needs a component export to open in the Vite starter.\"\n )\n const after = `export { ${binding} } from ${JSON.stringify(moduleSpecifier(filePath, editor.path))}\\n`\n return {\n path: filePath,\n realPath,\n requiredFiles: [editor.path],\n before,\n after,\n status:\n before === null ? \"create\" : after === before ? \"identical\" : \"update\",\n }\n}\n","import {\n Node,\n SyntaxKind as Kind,\n type FunctionExpression,\n type Identifier,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\"\n\nimport {\n namedImport,\n hasStaticOptions,\n findRenderedEditor,\n parseEditorSource,\n} from \"./editor-source\"\n\nconst wrapperName = \"withCollaboration\"\n\nfunction usedBeforeInitialization(\n name: Identifier,\n boundary: number,\n visited = new Set<Node>()\n): boolean {\n if (visited.has(name)) return false\n visited.add(name)\n return name.findReferencesAsNodes().some((reference) => {\n if (reference === name) return false\n const statement = reference.getFirstAncestor((node) =>\n Node.isSourceFile(node.getParent())\n )\n if (!statement) return false\n if (Node.isFunctionDeclaration(statement)) {\n const owner = statement.getNameNode()\n return !!owner && usedBeforeInitialization(owner, boundary, visited)\n }\n if (statement.getStart() >= boundary) return false\n const variable = reference.getFirstAncestorByKind(Kind.VariableDeclaration)\n const initializer = variable?.getInitializer()\n const binding = variable?.getNameNode()\n if (\n Node.isVariableStatement(statement) &&\n Node.isIdentifier(binding) &&\n (initializer === reference ||\n Node.isArrowFunction(initializer) ||\n Node.isFunctionExpression(initializer))\n )\n return usedBeforeInitialization(binding, boundary, visited)\n return true\n })\n}\n\nfunction editorComponent(file: SourceFile, name: string, wrapperPath: string) {\n const plain = file.getFunction(name)\n const declaration = file.getVariableDeclaration(name)\n const innerName = `Collaborative${name}`\n const inner = file.getVariableDeclaration(innerName)\n if (plain) {\n if (\n !/^[A-Z][\\w$]*$/.test(name) ||\n file.getFunctions().filter((fn) => fn.getName() === name).length !== 1 ||\n declaration ||\n !plain.hasExportKeyword() ||\n plain.getParameters().length ||\n plain\n .getNameNode()\n ?.findReferencesAsNodes()\n .some((reference) =>\n reference.getFirstAncestor((node) => node === plain.getBody())\n )\n )\n return\n if (!inner) return { fn: plain, wrapped: false as const }\n const rendered = plain.getBody()?.asKind(Kind.Block)?.getStatements()\n if (\n rendered?.length !== 1 ||\n !Node.isReturnStatement(rendered[0]) ||\n rendered[0]\n .getExpression()\n ?.asKind(Kind.JsxSelfClosingElement)\n ?.getTagNameNode()\n .getSymbol() !== inner.getNameNode().getSymbol()\n )\n return\n }\n const wrappedDeclaration = plain ? inner : declaration\n const statement = wrappedDeclaration?.getVariableStatement()\n const call = wrappedDeclaration?.getInitializerIfKind(Kind.CallExpression)\n const fn = call?.getArguments()[0]\n if (\n statement?.getDeclarationKind() !== \"const\" ||\n (!plain &&\n !statement.hasExportKeyword() &&\n !file.getExportAssignment(\n (item) => item.getExpression().getText() === name\n ))\n )\n return\n const wrapper = namedImport(file, wrapperPath, wrapperName)\n if (!wrapper || call?.getExpression().getSymbol() !== wrapper.getSymbol())\n return\n if (\n call?.getExpression().getText() !== wrapperName ||\n call.getArguments().length !== 1\n )\n return\n if (!Node.isFunctionExpression(fn) || fn.getName() !== name) return\n const props = fn\n .getParameters()\n .map((parameter) => parameter.getText().replace(/\\s/g, \"\"))\n if (props.length !== 1 || props[0] !== \"{collaboration,editable}\") return\n return { fn, wrapped: true as const }\n}\n\nfunction hasReassignedWrapperProp(fn: FunctionExpression) {\n const bindings = fn\n .getParameters()[0]!\n .getNameNode()\n .asKindOrThrow(Kind.ObjectBindingPattern)\n return bindings.getElements().some((binding) => {\n const name = binding.getNameNode().asKindOrThrow(Kind.Identifier)\n return name.findReferences().some((symbol) =>\n symbol.getReferences().some((reference) => {\n const node = reference.getNode()\n if (node === name || !reference.isWriteAccess()) return false\n // TypeScript marks shorthand property reads as writes, too.\n if (!node.getParentIfKind(Kind.ShorthandPropertyAssignment)) return true\n return node.getAncestors().some((ancestor) => {\n if (\n Node.isForOfStatement(ancestor) ||\n Node.isForInStatement(ancestor)\n )\n return ancestor\n .getInitializer()\n .containsRange(node.getStart(), node.getEnd())\n return (\n Node.isBinaryExpression(ancestor) &&\n ancestor.getOperatorToken().getKind() === Kind.EqualsToken &&\n ancestor.getLeft().containsRange(node.getStart(), node.getEnd())\n )\n })\n })\n )\n })\n}\n\nfunction hasConflictingExtension(file: SourceFile) {\n return file.getImportDeclarations().some((declaration) => {\n const path = declaration.getModuleSpecifierValue()\n if (\n /^(?:@tiptap\\/(?:extension-collaboration(?:-caret)?|extension-history|extension-undo-redo|y-tiptap)|@tiptap-pro\\/provider|y-prosemirror|yjs)(?:\\/|$)/.test(\n path\n )\n )\n return true\n return declaration\n .getNamedImports()\n .some((item) =>\n [\"Collaboration\", \"UndoRedo\", \"History\"].includes(item.getName())\n )\n })\n}\n\nfunction findEditorOptions(file: SourceFile, body: Node) {\n const editor = findRenderedEditor(file, body)\n if (!editor) return\n const { options, extensions } = editor\n const kitModule = file.getImportDeclaration(\"@tiptap/starter-kit\")\n const kit =\n namedImport(file, \"@tiptap/starter-kit\", \"StarterKit\") ??\n (!kitModule?.isTypeOnly() &&\n kitModule?.getDefaultImport()?.getText() === \"StarterKit\"\n ? kitModule.getDefaultImport()\n : undefined)\n const kitReferences = extensions\n .getDescendantsOfKind(Kind.Identifier)\n .filter((id) => id.getText() === \"StarterKit\")\n const reference = kitReferences[0]\n if (\n !kit ||\n kitReferences.length !== 1 ||\n reference.getSymbol() !== kit.getSymbol()\n )\n return\n if (reference.getParent() === extensions)\n return { options, extensions, kitReference: reference }\n const kitCall = reference\n .getParentIfKind(Kind.PropertyAccessExpression)\n ?.getParentIfKind(Kind.CallExpression)\n if (\n kitCall?.getParent() !== extensions ||\n kitCall.getExpression().getText() !== \"StarterKit.configure\" ||\n kitCall.getArguments().length !== 1\n )\n return\n const kitOptions = kitCall\n .getArguments()[0]\n ?.asKind(Kind.ObjectLiteralExpression)\n if (\n !kitOptions ||\n !hasStaticOptions(kitOptions) ||\n kitOptions.getProperty(\"history\")\n )\n return\n return { options, extensions, kitOptions }\n}\n\nfunction hasCompleteWiring(\n wiring: NonNullable<ReturnType<typeof findEditorOptions>>\n) {\n const { options, extensions, kitOptions } = wiring\n return (\n Node.isShorthandPropertyAssignment(options.getProperty(\"editable\")) &&\n !options.getProperty(\"content\") &&\n extensions\n .getElements()\n .filter((element) => element.getText() === \"collaboration\").length ===\n 1 &&\n kitOptions\n ?.getProperty(\"undoRedo\")\n ?.asKind(Kind.PropertyAssignment)\n ?.getInitializer()\n ?.getKind() === Kind.FalseKeyword\n )\n}\n\ntype Edit = { start: number; end: number; text: string }\n\nfunction removeNode(source: string, node: Node): Edit {\n const start = node.getStart()\n const end =\n node.getNextSiblingIfKind(Kind.CommaToken)?.getEnd() ?? node.getEnd()\n const lineStart = source.lastIndexOf(\"\\n\", start - 1) + 1\n const newline = source.slice(end).match(/^[ \\t]*\\r?\\n/)\n if (newline && source.slice(lineStart, start).trim() === \"\") {\n return { start: lineStart, end: end + newline[0].length, text: \"\" }\n }\n return { start, end, text: \"\" }\n}\n\nfunction removeDemoContent(\n file: SourceFile,\n options: ObjectLiteralExpression,\n demoImport?: string\n): Edit[] | null {\n const content = options.getProperty(\"content\")\n if (!content) return []\n const value = Node.isShorthandPropertyAssignment(content)\n ? content.getNameNode()\n : content.asKind(Kind.PropertyAssignment)?.getInitializer()\n if (!Node.isIdentifier(value)) return null\n const demo = file\n .getImportDeclarations()\n .find(\n (item) =>\n item.getModuleSpecifierValue() === demoImport &&\n item.getDefaultImport()?.getText() === value.getText()\n )\n const imported = demo?.getDefaultImport()\n if (!demo || !imported) return null\n const uses = imported\n .findReferencesAsNodes()\n .filter((id) => id.getStart() !== imported.getStart())\n if (!uses.some((id) => id.getStart() === value.getStart())) return null\n const source = file.getFullText()\n const edits = [removeNode(source, content)]\n if (\n uses.length === 1 &&\n !demo.getNamedImports().length &&\n !demo.getNamespaceImport()\n ) {\n edits.push(removeNode(source, demo))\n }\n return edits\n}\n\nexport function editorComponentName(source: string) {\n const file = parseEditorSource(source)\n const calls = file\n ?.getDescendantsOfKind(Kind.CallExpression)\n .filter((call) => call.getExpression().getText() === \"useEditor\")\n if (calls?.length !== 1) return\n const fn = calls[0]!.getFirstAncestor(\n (node) =>\n Node.isFunctionDeclaration(node) ||\n Node.isFunctionExpression(node) ||\n Node.isArrowFunction(node)\n )\n if (Node.isFunctionDeclaration(fn) || Node.isFunctionExpression(fn))\n return fn.getName()\n return fn?.getParentIfKind(Kind.VariableDeclaration)?.getName()\n}\n\nexport function connectCollaboration(\n original: string,\n name: string,\n wrapperPath: string,\n demoImport?: string\n): { source: string; removedDemoContent?: boolean } | { reason: string } {\n const bom = original.startsWith(\"\\uFEFF\") ? \"\\uFEFF\" : \"\"\n const source = original.slice(bom.length)\n const file = parseEditorSource(source)\n if (!file) return { reason: \"The editor source contains a syntax error.\" }\n const target = editorComponent(file, name, wrapperPath)\n const body = target?.fn.getBody()\n if (\n !target ||\n !body ||\n target.fn.isAsync() ||\n target.fn.isGenerator() ||\n target.fn.getTypeParameters().length\n )\n return {\n reason:\n \"The connector needs an exported, named function component without props or type parameters.\",\n }\n const declared = file.getFunction(name)\n const binding = declared?.getNameNode()\n const innerName = `Collaborative${name}`\n if (\n declared &&\n binding &&\n usedBeforeInitialization(\n binding,\n file.getVariableDeclaration(innerName)?.getStart() ?? declared.getStart()\n )\n )\n return {\n reason:\n \"The module may render the editor before its Collaboration wrapper initializes. Move the first render after the editor declaration.\",\n }\n if (hasConflictingExtension(file))\n return {\n reason:\n \"The editor already imports a collaboration, history or provider module. Check how it manages document history before adding Collaboration.\",\n }\n const wiring = findEditorOptions(file, body)\n if (!wiring)\n return {\n reason:\n \"The connector needs one useEditor call with a static extensions array containing StarterKit and an EditorContent that renders the same editor.\",\n }\n const { options, extensions, kitOptions, kitReference } = wiring\n const undo = kitOptions?.getProperty(\"undoRedo\")\n if (\n undo &&\n undo.asKind(Kind.PropertyAssignment)?.getInitializer()?.getKind() !==\n Kind.FalseKeyword\n )\n return {\n reason:\n \"The editor configures StarterKit undoRedo. Disable it when using Collaboration.\",\n }\n const editable = options.getProperty(\"editable\")\n const shared = extensions\n .getElements()\n .filter((item) => item.getText() === \"collaboration\")\n if (target.wrapped) {\n if (hasReassignedWrapperProp(target.fn))\n return {\n reason:\n \"Pass the wrapper's collaboration and editable values unchanged to useEditor.\",\n }\n return hasCompleteWiring(wiring)\n ? { source: original }\n : {\n reason:\n \"The existing wrapper needs editable, one collaboration extension, disabled StarterKit undoRedo and no initial content.\",\n }\n }\n\n if (\n editable ||\n shared.length ||\n file\n .getDescendantsOfKind(Kind.Identifier)\n .some((id) => [innerName, wrapperName].includes(id.getText())) ||\n body\n .getDescendantsOfKind(Kind.Identifier)\n .some((id) =>\n [\"collaboration\", \"editable\", \"arguments\"].includes(id.getText())\n )\n )\n return {\n reason:\n \"The editor already uses an option or name needed by the Collaboration wrapper.\",\n }\n const edits = removeDemoContent(file, options, demoImport)\n if (!edits)\n return {\n reason:\n \"The editor supplies initial content. To keep it, seed the shared document once before opening the editor.\",\n }\n const removedDemoContent = edits.length > 0\n const newline = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\"\n const insert = (start: number, text: string) =>\n edits.push({ start, end: start, text })\n const prepend = (node: Node, value: string) => {\n const start = node.getStart() + 1\n const whitespace = source.slice(start).match(/^\\s*/)?.[0] ?? \"\"\n const next = source[start]\n if (next === \"}\") insert(start, ` ${value} `)\n else insert(start, whitespace + value + (whitespace ? \",\" : \", \"))\n }\n\n insert(\n file.getImportDeclarations()[0]!.getStart(),\n `import { ${wrapperName} } from ${JSON.stringify(wrapperPath)}${newline}`\n )\n insert(\n body.getStart(),\n [\n \"{\",\n ` return <${innerName} />`,\n \"}\",\n \"\",\n `const ${innerName} = ${wrapperName}(function ${name}({ collaboration, editable }) `,\n ].join(newline)\n )\n insert(target.fn.getEnd(), \");\")\n prepend(options, \"editable\")\n prepend(extensions, \"collaboration\")\n if (kitReference)\n insert(kitReference.getEnd(), \".configure({ undoRedo: false })\")\n else if (kitOptions && !undo) prepend(kitOptions, \"undoRedo: false\")\n let result = source\n for (const edit of edits.sort((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.text + result.slice(edit.end)\n }\n const checked = parseEditorSource(result)\n const component = checked && editorComponent(checked, name, wrapperPath)\n const checkedBody = component?.fn.getBody()\n const wired =\n checked && checkedBody && findEditorOptions(checked, checkedBody)\n if (!component?.wrapped || !wired || !hasCompleteWiring(wired))\n return { reason: \"The connector could not verify the edited source.\" }\n return { source: bom + result, removedDemoContent }\n}\n","import {\n Node,\n Project,\n SyntaxKind as Kind,\n type ObjectLiteralExpression,\n type SourceFile,\n} from \"ts-morph\"\n\nexport function namedImport(file: SourceFile, module: string, name: string) {\n const imports = file\n .getImportDeclarations()\n .filter(\n (declaration) =>\n declaration.getModuleSpecifierValue() === module &&\n !declaration.isTypeOnly()\n )\n .flatMap((declaration) => declaration.getNamedImports())\n .filter((item) => item.getText() === name)\n return imports.length === 1 ? imports[0]!.getNameNode() : undefined\n}\n\n// A spread, dynamic key or duplicate can override an option after we insert it.\nexport function hasStaticOptions(object: ObjectLiteralExpression) {\n const keys = object\n .getProperties()\n .map((property) =>\n Node.isPropertyAssignment(property) ||\n Node.isShorthandPropertyAssignment(property)\n ? property.getNameNode().asKind(Kind.Identifier)?.getText()\n : undefined\n )\n return !keys.includes(undefined) && new Set(keys).size === keys.length\n}\n\nexport function findRenderedEditor(file: SourceFile, componentBody?: Node) {\n const calls = file.getDescendantsOfKind(Kind.CallExpression)\n const hooks = calls.filter(\n (call) => call.getExpression().getText() === \"useEditor\"\n )\n const hook = hooks[0]\n const reactImports = file\n .getImportDeclarations()\n .filter((item) => item.getModuleSpecifierValue() === \"@tiptap/react\")\n if (\n reactImports.some((item) => item.getNamespaceImport()) ||\n reactImports\n .flatMap((item) => item.getNamedImports())\n .filter((item) => item.getName() === \"useEditor\").length !== 1\n )\n return\n const importedHook = namedImport(file, \"@tiptap/react\", \"useEditor\")\n const variable = hook?.getParentIfKind(Kind.VariableDeclaration)\n if (\n !importedHook ||\n hooks.length !== 1 ||\n hook.getExpression().getSymbol() !== importedHook.getSymbol()\n )\n return\n const body = variable?.getVariableStatement()?.getParentIfKind(Kind.Block)\n if (\n !variable ||\n !body ||\n (componentBody && body !== componentBody) ||\n hook.getArguments().length !== 1\n )\n return\n const editorContents = body\n .getDescendantsOfKind(Kind.JsxSelfClosingElement)\n .filter((element) => element.getTagNameNode().getText() === \"EditorContent\")\n const element = editorContents[0]\n const returned = body.getStatements().find(Node.isReturnStatement)\n const container = element?.getFirstAncestor(\n (node) =>\n !Node.isJsxElement(node) &&\n !Node.isJsxFragment(node) &&\n !Node.isJsxExpression(node) &&\n !Node.isParenthesizedExpression(node)\n )\n const importedContent = namedImport(file, \"@tiptap/react\", \"EditorContent\")\n if (\n !returned ||\n container !== returned ||\n !importedContent ||\n element?.getTagNameNode().getSymbol() !== importedContent.getSymbol()\n )\n return\n const rendered = element\n ?.getAttributes()\n .filter(\n (attribute) =>\n Node.isJsxSpreadAttribute(attribute) ||\n attribute.getNameNode().getText() === \"editor\"\n )\n .at(-1)\n ?.asKind(Kind.JsxAttribute)\n ?.getInitializer()\n ?.asKind(Kind.JsxExpression)\n ?.getExpression()\n if (\n editorContents.length !== 1 ||\n !rendered ||\n rendered.getSymbol() !== variable.getNameNode().getSymbol()\n )\n return\n const options = hook.getArguments()[0]?.asKind(Kind.ObjectLiteralExpression)\n if (!options || !hasStaticOptions(options)) return\n const extensions = options\n .getProperty(\"extensions\")\n ?.asKind(Kind.PropertyAssignment)\n ?.getInitializerIfKind(Kind.ArrayLiteralExpression)\n if (!extensions) return\n\n if (extensions.getElements().some(Node.isSpreadElement)) return\n return { options, extensions }\n}\n\nexport function parseEditorSource(source: string, filename = \"editor.tsx\") {\n const project = new Project({\n useInMemoryFileSystem: true,\n compilerOptions: { noLib: true, allowJs: true },\n })\n const file = project.createSourceFile(filename, source)\n if (\n project\n .getProgram()\n .compilerObject.getSyntacticDiagnostics(file.compilerNode).length\n )\n return null\n return file\n}\n","import path from \"node:path\"\nimport { Node, SymbolFlags, SyntaxKind as Kind, ts } from \"ts-morph\"\nimport { findRenderedEditor, parseEditorSource } from \"./editor-source\"\nimport type { RegistryFeature } from \"./registry/schema\"\nimport type { PlannedFile } from \"./updaters/update-files\"\n\ntype EditorIntegration = Extract<\n RegistryFeature[\"integration\"],\n { kind: \"editor-extension\" }\n>\n\nexport interface EditorExtensionSetup {\n status: \"connected\" | \"unchanged\" | \"pending\"\n editorPath?: string\n extensionPath: string\n exportName: string\n importPath?: string\n entryPath?: string\n reason?: string\n}\n\nexport function hasValueExport(file: PlannedFile, name: string) {\n const symbol = parseEditorSource(file.after, path.basename(file.path))\n ?.getExportSymbols()\n .find((item) => item.getName() === name)\n if (!symbol) return false\n const value = symbol.isAlias() ? symbol.getAliasedSymbol() : symbol\n if (!value || !(value.getFlags() & SymbolFlags.Value)) return false\n if (\n symbol.isAlias() &&\n !symbol\n .getDeclarations()\n .some(\n (decl) =>\n Node.isExportSpecifier(decl) &&\n !decl.isTypeOnly() &&\n !decl.getExportDeclaration().isTypeOnly()\n )\n )\n return false\n return value\n .getDeclarations()\n .some(\n (decl) =>\n !(decl.getCombinedModifierFlags() & ts.ModifierFlags.Ambient) &&\n (!Node.isFunctionDeclaration(decl) || decl.getBody() !== undefined)\n )\n}\n\nfunction connectExtension(\n source: string,\n importPath: string,\n exportName: string\n) {\n const bom = source.startsWith(\"\\uFEFF\") ? \"\\uFEFF\" : \"\"\n source = source.slice(bom.length)\n const file = parseEditorSource(source)\n const editor = file && findRenderedEditor(file)\n if (!file || !editor) return null\n const { extensions } = editor\n const imports = file.getImportDeclarations()\n const matching = imports.filter(\n (decl) => decl.getModuleSpecifierValue() === importPath\n )\n let localName = exportName\n if (matching.length) {\n const [decl] = matching\n if (!decl || matching.length !== 1 || decl.isTypeOnly()) return null\n const specifiers = decl\n .getNamedImports()\n .filter((item) => item.getName() === exportName)\n if (specifiers.length !== 1 || specifiers[0]!.isTypeOnly()) return null\n const local = specifiers[0]!.getAliasNode() ?? specifiers[0]!.getNameNode()\n if (!Node.isIdentifier(local)) return null\n localName = local.getText()\n const symbol = local.getSymbol()\n if (\n !symbol ||\n !extensions\n .getSymbolsInScope(SymbolFlags.Value | SymbolFlags.Alias)\n .includes(symbol)\n )\n return null\n const registered = extensions\n .getElements()\n .filter((el) => Node.isIdentifier(el) && el.getSymbol() === symbol)\n if (registered.length === 1) return bom + source\n if (registered.length || local.findReferencesAsNodes().length) return null\n } else if (\n file\n .getDescendantsOfKind(Kind.Identifier)\n .some((id) => id.getText() === exportName)\n ) {\n return null\n }\n\n const start = extensions.getStart() + 1\n const whitespace = source.slice(start).match(/^\\s*/)?.[0] ?? \"\"\n const separator = extensions.getElements().length\n ? whitespace\n ? \",\"\n : \", \"\n : \"\"\n const wired =\n source.slice(0, start) +\n whitespace +\n localName +\n separator +\n source.slice(start)\n const originalPosition = imports[0]!.getStart()\n const before =\n originalPosition > start\n ? originalPosition + wired.length - source.length\n : originalPosition\n const eol = source.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\"\n const declaration = `import { ${exportName} } from ${JSON.stringify(importPath)}${eol}`\n const result = matching.length\n ? wired\n : wired.slice(0, before) + declaration + wired.slice(before)\n const checked = parseEditorSource(result)\n const imported = checked\n ?.getImportDeclaration(importPath)\n ?.getNamedImports()\n .find((item) => item.getName() === exportName)\n const symbol = (\n imported?.getAliasNode() ?? imported?.getNameNode()\n )?.getSymbol()\n return checked &&\n symbol &&\n findRenderedEditor(checked)\n ?.extensions.getElements()\n .some((item) => item.getSymbol() === symbol)\n ? bom + result\n : null\n}\n\nexport function moduleSpecifier(from: string, to: string) {\n const relative = path\n .relative(path.dirname(from), to)\n .split(path.sep)\n .join(\"/\")\n .replace(/\\.[jt]sx?$/, \"\")\n return relative.startsWith(\"../\") ? relative : `./${relative}`\n}\n\nexport function editorImportPath(editor: PlannedFile, dependency: PlannedFile) {\n const physical = moduleSpecifier(editor.realPath, dependency.realPath)\n return physical === moduleSpecifier(editor.path, dependency.path)\n ? physical\n : undefined\n}\n\nexport function updateEditor(\n files: Map<string, PlannedFile>,\n editor: PlannedFile,\n connected: string,\n dependency: PlannedFile\n) {\n editor.after = connected\n editor.status =\n editor.before === null\n ? \"create\"\n : connected === editor.before\n ? \"identical\"\n : \"update\"\n editor.requiredFiles = [...(editor.requiredFiles ?? []), dependency.path]\n files.delete(editor.realPath)\n files.set(editor.realPath, editor)\n return editor.status === \"identical\" ? \"unchanged\" : \"connected\"\n}\n\nexport function planEditorExtension(\n integration: EditorIntegration,\n files: Map<string, PlannedFile>,\n editor: PlannedFile | undefined,\n cwd: string\n): EditorExtensionSetup {\n const { exportName } = integration\n const matches = [...files.values()].filter(\n (file) => file.registryPath === integration.extension\n )\n if (matches.length !== 1)\n throw new Error(\n `Expected one installed registry file for ${integration.extension}.`\n )\n const extension = matches[0]!\n if (editor === extension)\n throw new Error(\"The editor and its extension must be separate files.\")\n const setup: EditorExtensionSetup = {\n status: \"pending\",\n editorPath: editor && path.relative(cwd, editor.path),\n extensionPath: path.relative(cwd, extension.path),\n exportName,\n importPath: editor && editorImportPath(editor, extension),\n }\n if (!hasValueExport(extension, exportName)) {\n if (extension.before === null)\n throw new Error(\n `The registry file ${integration.extension} must export ${exportName}.`\n )\n setup.reason = `Export ${exportName} from ${setup.extensionPath} before connecting it to the editor.`\n return setup\n }\n if (!editor) return setup\n if (!setup.importPath) {\n setup.reason =\n \"A symlink changes the relative import. Select the editor at its real path.\"\n return setup\n }\n const connected = connectExtension(editor.after, setup.importPath, exportName)\n if (connected === null) {\n setup.reason =\n \"Register the extension in the extensions array of the editor that EditorContent renders.\"\n return setup\n }\n setup.status = updateEditor(files, editor, connected, extension)\n return setup\n}\n","import semver from \"semver\"\nimport type { Config } from \"../get-config\"\nimport { getInstalledPackageVersion, getPackageInfo } from \"../get-package-info\"\n\nconst editorPackages =\n /^@tiptap\\/(?:core|extensions|extension-[^/]+|pm|react|starter-kit|suggestion)$/\nconst editorRange = \"^3.0.0\"\n\nfunction equivalentVersions(left: string, right: string) {\n return (\n left === right ||\n Boolean(\n semver.validRange(left) &&\n semver.validRange(right) &&\n semver.subset(left, right) &&\n semver.subset(right, left)\n )\n )\n}\n\nexport type DependencyPromotion = { name: string; version: string }\n\nexport function planDependencies(\n dependencies: string[],\n devDependencies: string[],\n config: Config,\n subject = \"This template\"\n) {\n const cwd = config.resolvedPaths.cwd\n const manifest = getPackageInfo(cwd)\n const declared = {\n ...manifest?.peerDependencies,\n ...manifest?.devDependencies,\n ...manifest?.optionalDependencies,\n ...manifest?.dependencies,\n }\n const requests = new Map<string, { version?: string; dev: boolean }>()\n function collect(specs: string[], dev: boolean) {\n for (const spec of specs) {\n const match = /^((?:@[\\w.-]+\\/)?[\\w.-]+)(?:@(.+))?$/.exec(spec)\n if (!match) throw new Error(`Invalid registry dependency \"${spec}\".`)\n const [, name, version] = match\n const previous = requests.get(name)\n if (\n previous?.version &&\n version &&\n !equivalentVersions(previous.version, version)\n ) {\n throw new Error(\n `Registry items request both ${name}@${previous.version} and ${name}@${version}.`\n )\n }\n requests.set(name, {\n version: previous?.version ?? version,\n dev: dev && (previous?.dev ?? true),\n })\n }\n }\n collect(dependencies, false)\n collect(devDependencies, true)\n\n const result = {\n dependencies: [] as string[],\n devDependencies: [] as string[],\n promotions: [] as DependencyPromotion[],\n }\n const needsEditor = [...requests.keys()].some((name) =>\n editorPackages.test(name)\n )\n // Tiptap publishes every editor package at the same version, so any declared\n // one gives the version that new editor packages must match.\n const coreName = declared[\"@tiptap/core\"]\n ? \"@tiptap/core\"\n : Object.keys(declared).find((name) => editorPackages.test(name))\n const core = coreName && declared[coreName]\n const installedCore =\n needsEditor && coreName\n ? getInstalledPackageVersion(cwd, coreName)\n : undefined\n const incompatibleCore =\n installedCore && !semver.satisfies(installedCore, editorRange)\n ? installedCore\n : core && semver.validRange(core) && !semver.intersects(core, editorRange)\n ? core\n : undefined\n if (needsEditor && incompatibleCore) {\n throw new Error(\n `${subject} requires Tiptap 3. The project uses ${coreName}@${incompatibleCore}.`\n )\n }\n\n const coreRange =\n core && semver.validRange(core) && semver.subset(core, editorRange)\n ? core\n : editorRange\n\n for (const [name, { version, dev }] of requests) {\n const existing = declared[name]\n const isEditor = editorPackages.test(name)\n const required = version ?? (isEditor ? editorRange : undefined)\n\n if (existing) {\n if (required && existing !== required) {\n const installed = getInstalledPackageVersion(cwd, name)\n const compatible =\n semver.validRange(required) &&\n (installed\n ? semver.satisfies(installed, required)\n : semver.validRange(existing) && semver.subset(existing, required))\n if (!compatible) {\n throw new Error(\n `The registry requires ${name}@${required}. Check the project's ${name}@${existing} before installing.`\n )\n }\n }\n if (\n !dev &&\n manifest?.devDependencies?.[name] &&\n !manifest.dependencies?.[name] &&\n !manifest.optionalDependencies?.[name] &&\n !manifest.peerDependencies?.[name]\n ) {\n result.promotions.push({ name, version: existing })\n }\n continue\n }\n\n const target = dev ? result.devDependencies : result.dependencies\n const wanted =\n version ?? (isEditor ? (installedCore ?? coreRange) : undefined)\n target.push(wanted ? `${name}@${wanted}` : name)\n }\n return result\n}\n","import { stripVTControlCharacters } from \"node:util\"\nimport type { ComponentPlan } from \"./add-components\"\nimport {\n getTiptapRegistryRoute,\n registryLoginCommand,\n renewTiptapRegistryAccess,\n} from \"./tiptap-registry-access\"\nimport { updateDependencies } from \"./updaters/update-dependencies\"\nimport { updateDevDependencies } from \"./updaters/update-dev-dependencies\"\n\ntype RegistryRejection = {\n name: string\n code?: string\n route?: \"tiptap\" | \"mirror\"\n}\n\nfunction rejectedUrl(\n address: string,\n code: string | undefined,\n packages: string[],\n expectedName?: string\n): RegistryRejection | undefined {\n if (!URL.canParse(address)) return\n const url = new URL(address)\n if ([\"registry.npmjs.org\", \"registry.yarnpkg.com\"].includes(url.hostname))\n return\n const path = url.pathname.replace(/%2f/gi, \"/\").replace(/%40/gi, \"@\")\n const name = /\\/(@tiptap-pro\\/[\\w.-]+)(?=\\/-\\/|:|\\/?$)/.exec(path)?.[1]\n if (!name || (expectedName && name !== expectedName)) return\n const official = url.origin === \"https://registry.tiptap.dev\"\n if (official || packages.includes(name))\n return { name, code, route: official ? \"tiptap\" : \"mirror\" }\n}\n\nfunction privatePackageRejection(\n error: unknown,\n packages: string[]\n): RegistryRejection | undefined {\n if (!(error instanceof Error)) return\n const streams = [\n \"stderr\" in error && error.stderr,\n \"stdout\" in error && error.stdout,\n ].filter((value) => typeof value === \"string\" || Buffer.isBuffer(value))\n const output = stripVTControlCharacters(\n streams.map(String).join(\"\\n\").trim() || error.message\n )\n if (\n /\\bELIFECYCLE\\b|\\bLifecycle script\\b|\\bnpm (?:ERR!|error) command sh -c\\b/i.test(\n output\n )\n )\n return\n\n const lines = output.split(/\\r?\\n/)\n for (const [index, line] of lines.entries()) {\n const berryPackage = /\\bYN0035: [│ ]*(@tiptap-pro\\/[\\w.-]+)@npm:/.exec(\n line\n )?.[1]\n if (berryPackage) {\n const code = /\\bYN0035: [│ ]*Response Code: (401|403)\\b/.exec(\n lines[index + 1] ?? \"\"\n )?.[1]\n const get = /\\bYN0035: [│ ]*Request Method: GET$/.test(\n lines[index + 2] ?? \"\"\n )\n const address = /\\bYN0035: [│ ]*Request URL: (https?:\\/\\/\\S+)/.exec(\n lines[index + 3] ?? \"\"\n )?.[1]\n if (code && get && address) {\n const rejection = rejectedUrl(address, code, packages, berryPackage)\n if (rejection) return rejection\n }\n }\n if (/Command (?:failed|was killed)\\b/i.test(line)) continue\n const status =\n /\\b(?:E|ERR_PNPM_FETCH_)(401|403)\\b|\\b(401|403)\\s+(?:Unauthorized|Forbidden)\\b|\\s-\\s+(401|403)\\b/i.exec(\n line\n )\n const yarnAuth = /\\bYN00(?:33|41)\\b/i.test(line)\n const classic =\n /^error (?:Error: )?https?:\\/\\/\\S+: (Unauthorized|Forbidden)\\s*$/i.exec(\n line\n )\n if (!status && !yarnAuth && !classic) continue\n\n const code = classic\n ? classic[1].toLowerCase() === \"forbidden\"\n ? \"403\"\n : \"401\"\n : status?.slice(1).find(Boolean)\n const address = /https?:\\/\\/[^\\s\"'<>]+/i.exec(line)?.[0]\n if (address) {\n const rejection = rejectedUrl(address, code, packages)\n if (rejection) return rejection\n } else if (yarnAuth) {\n const name =\n /\\bYN00(?:33|41):\\s*(?:│\\s*)?(@tiptap-pro\\/[\\w.-]+)@npm:/.exec(\n line\n )?.[1]\n if (name && packages.includes(name)) return { name, code }\n }\n }\n}\n\nexport async function installPlannedPackages(\n groups: ComponentPlan[\"packages\"],\n options: { silent?: boolean; interactive: boolean }\n) {\n const { interactive } = options\n let attemptedLogin = false\n for (const group of groups) {\n async function install(operation: () => Promise<void>) {\n for (;;) {\n try {\n await operation()\n return\n } catch (error) {\n const rejection = privatePackageRejection(\n error,\n group.privateNpmPackages\n )\n if (!rejection) throw error\n const cwd = group.config.resolvedPaths.cwd\n const summary = `The package registry rejected access to ${rejection.name}${rejection.code ? ` with HTTP ${rejection.code}` : \"\"}.`\n const route =\n rejection.route === \"mirror\"\n ? \"mirror\"\n : await getTiptapRegistryRoute(cwd)\n if (!rejection.route && route === \"public\") throw error\n if (route === \"mirror\") {\n throw new Error(\n `${summary} Authenticate with the registry configured for @tiptap-pro in ${cwd}, check access to this package, then repeat the install.`\n )\n }\n const help = `${summary} Check that your account can download the package. Sign in again, then repeat the install. https://tiptap.dev/docs/guides/pro-extensions\\n${await registryLoginCommand(cwd)}`\n if (!interactive || attemptedLogin) throw new Error(help)\n attemptedLogin = true\n try {\n await renewTiptapRegistryAccess([rejection.name], cwd, {\n interactive,\n })\n } catch {\n throw new Error(help)\n }\n }\n }\n }\n await install(() =>\n updateDependencies(group.dependencies, group.config, options)\n )\n if (group.promotions.length) {\n await install(() =>\n updateDependencies([], group.config, options, group.promotions)\n )\n }\n await install(() =>\n updateDevDependencies(group.devDependencies, group.config, options)\n )\n }\n}\n","import fs from \"node:fs\"\nimport path from \"node:path\"\nimport { execa } from \"execa\"\nimport { applyEdits, modify } from \"jsonc-parser\"\nimport type { PackageJson } from \"type-fest\"\n\nimport { Config } from \"@/src/utils/get-config\"\nimport {\n getPackageManager,\n type PackageManager,\n} from \"@/src/utils/get-package-manager\"\nimport { RegistryItem } from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { colors } from \"@/src/utils/colors\"\nimport type { DependencyPromotion } from \"./plan-dependencies\"\n\nfunction moveDeclarations(\n content: string,\n moves: DependencyPromotion[],\n undo = false\n) {\n const from = undo ? \"dependencies\" : \"devDependencies\"\n const to = undo ? \"devDependencies\" : \"dependencies\"\n const manifest = JSON.parse(content) as PackageJson\n const indent = /^[ \\t]+(?=\")/m.exec(content)?.[0]\n const formattingOptions = {\n insertSpaces: !indent?.includes(\"\\t\"),\n tabSize: indent?.length ?? 2,\n eol: content.includes(\"\\r\\n\") ? \"\\r\\n\" : \"\\n\",\n }\n for (const { name, version } of moves) {\n if (\n manifest[from]?.[name] !== version ||\n manifest[to]?.[name] !== undefined ||\n (!undo &&\n (manifest.peerDependencies?.[name] ||\n manifest.optionalDependencies?.[name]))\n ) {\n if (undo) continue\n throw new Error(\n `The declaration for ${name} changed. Run add again to review it.`\n )\n }\n content = applyEdits(\n content,\n modify(content, [to, name], version, { formattingOptions })\n )\n content = applyEdits(\n content,\n modify(content, [from, name], undefined, { formattingOptions })\n )\n }\n return content\n}\n\nasync function promoteDependencies(\n cwd: string,\n manager: PackageManager,\n moves: DependencyPromotion[]\n) {\n const manifest = path.join(cwd, \"package.json\")\n const original = fs.readFileSync(manifest, \"utf8\")\n const promoted = moveDeclarations(original, moves)\n fs.writeFileSync(manifest, promoted)\n try {\n // The project package manager updates its lockfile using the original version specs.\n await execa(\n manager,\n manager === \"pnpm\" ? [\"install\", \"--no-frozen-lockfile\"] : [\"install\"],\n {\n cwd,\n env:\n manager === \"yarn\"\n ? { YARN_ENABLE_IMMUTABLE_INSTALLS: \"false\" }\n : undefined,\n }\n )\n } catch (error) {\n const current = fs.readFileSync(manifest, \"utf8\")\n const restored =\n current === promoted ? original : moveDeclarations(current, moves, true)\n if (current !== restored) {\n fs.writeFileSync(manifest, restored)\n // Yarn stores both scopes in the same lockfile dependency map.\n if (manager !== \"yarn\") {\n const flag =\n manager === \"npm\" ? \"--package-lock-only\" : \"--lockfile-only\"\n try {\n await execa(\n manager,\n [\n \"install\",\n flag,\n \"--ignore-scripts\",\n ...(manager === \"pnpm\" ? [\"--no-frozen-lockfile\"] : []),\n ],\n { cwd }\n )\n } catch (repairError) {\n throw new Error(\n `Dependency promotion failed: ${error instanceof Error ? error.message : error}. Run ${manager} install in ${cwd} to sync the restored declarations. Lockfile update failed: ${repairError instanceof Error ? repairError.message : repairError}.`\n )\n }\n }\n }\n throw error\n }\n}\n\nexport async function updateDependencies(\n dependencies: RegistryItem[\"dependencies\"],\n config: Config,\n options: {\n silent?: boolean\n },\n promotions: DependencyPromotion[] = []\n) {\n dependencies = Array.from(new Set(dependencies))\n if (!dependencies.length && !promotions.length) return\n\n const dependenciesSpinner = spinner(`Installing dependencies.`, {\n silent: options.silent,\n }).start()\n const cwd = config.resolvedPaths.cwd\n try {\n const packageManager = await getPackageManager(cwd)\n\n if (dependencies.length) {\n await execa(\n packageManager,\n [\n packageManager === \"npm\" ? \"install\" : \"add\",\n ...(packageManager === \"npm\" ? [\"--save\"] : []),\n ...dependencies,\n ],\n { cwd }\n )\n }\n if (promotions.length)\n await promoteDependencies(cwd, packageManager, promotions)\n } catch (error) {\n dependenciesSpinner.stop()\n throw error\n }\n\n dependenciesSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n}\n","import { Config } from \"@/src/utils/get-config\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { RegistryItem } from \"@/src/utils/registry/schema\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { execa } from \"execa\"\nimport { colors } from \"@/src/utils/colors\"\n\n/**\n * Installs development dependencies for a component\n *\n * @param devDependencies List of development dependencies to install\n * @param config Configuration object with project paths\n * @param options Additional options\n */\nexport async function updateDevDependencies(\n devDependencies: RegistryItem[\"devDependencies\"],\n config: Config,\n options: {\n silent?: boolean\n }\n) {\n devDependencies = Array.from(new Set(devDependencies))\n\n if (!devDependencies?.length) {\n return\n }\n\n options = {\n silent: false,\n ...options,\n }\n\n const devDependenciesSpinner = spinner(\n `Installing development dependencies.`,\n {\n silent: options.silent,\n }\n )?.start()\n try {\n const packageManager = await getPackageManager(config.resolvedPaths.cwd)\n\n // Different package managers have different flags for dev dependencies\n const devFlag = packageManager === \"npm\" ? \"--save-dev\" : \"-D\"\n\n await execa(\n packageManager,\n [\n packageManager === \"npm\" ? \"install\" : \"add\",\n devFlag,\n ...devDependencies,\n ],\n {\n cwd: config.resolvedPaths.cwd,\n }\n )\n } catch (error) {\n devDependenciesSpinner?.stop()\n throw error\n }\n\n devDependenciesSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n}\n","import path from \"node:path\"\nimport { createTwoFilesPatch } from \"diff\"\nimport type { ComponentPlan } from \"./add-components\"\nimport { logger } from \"./logger\"\n\nexport function printInstallPreview(\n plan: ComponentPlan,\n cwd: string,\n diff?: boolean | string\n) {\n const files =\n typeof diff === \"string\"\n ? plan.files.filter((file) => file.path === path.resolve(cwd, diff))\n : plan.files\n if (typeof diff === \"string\" && !files.length) {\n throw new Error(\n `The installation does not include ${diff}. Run add --dry-run to list the target paths.`\n )\n }\n for (const file of files) {\n const relative = path.relative(cwd, file.path)\n if (diff && file.status !== \"identical\" && file.status !== \"keep\") {\n logger.log(\n createTwoFilesPatch(\n file.before === null ? \"/dev/null\" : `a/${relative}`,\n `b/${relative}`,\n file.before ?? \"\",\n file.after\n )\n )\n } else {\n logger.log(`${file.status.padEnd(10)} ${relative}`)\n }\n }\n if (typeof diff !== \"string\") {\n for (const group of plan.packages) {\n const prefix = path.relative(cwd, group.config.resolvedPaths.cwd) || \".\"\n if (group.dependencies.length)\n logger.log(\n `Dependencies in ${prefix}: ${group.dependencies.join(\", \")}`\n )\n if (group.promotions.length) {\n const specs = group.promotions.map(\n ({ name, version }) => `${name}@${version}`\n )\n logger.log(`Move to dependencies in ${prefix}: ${specs.join(\", \")}`)\n }\n if (group.devDependencies.length)\n logger.log(\n `Dev dependencies in ${prefix}: ${group.devDependencies.join(\", \")}`\n )\n if (group.privateNpmPackages.length)\n logger.log(\n `Your package manager needs registry access to install ${group.privateNpmPackages.join(\", \")}.`\n )\n }\n if (!plan.styles.success) logger.warn(plan.styles.message)\n }\n}\n","/**\n * Converts kebab-case or snake_case to Title Case\n */\nexport function toReadableName(input: string): string {\n return input\n .split(/[-_]/)\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(\" \")\n}\n","import { colors } from \"@/src/utils/colors\"\nimport { Framework, FRAMEWORKS } from \"@/src/utils/frameworks\"\nimport { createInfoBox, createWarningBox, logLines } from \"@/src/utils/cli-ui\"\nimport { logger } from \"@/src/utils/logger\"\nimport { existsSync } from \"fs\"\nimport path from \"path\"\nimport type { Config } from \"@/src/utils/get-config\"\n\n/**\n * Get the appropriate environment variable prefix for the framework\n */\nfunction getFrameworkEnvPrefix(framework: Framework): string {\n const frameworkName = framework.name\n\n if (\n frameworkName === FRAMEWORKS[\"next-app\"].name ||\n frameworkName === FRAMEWORKS[\"next-pages\"].name\n ) {\n return \"NEXT_PUBLIC_\"\n } else if (frameworkName === FRAMEWORKS.astro.name) {\n return \"PUBLIC_\"\n } else if (\n frameworkName === FRAMEWORKS.vite.name ||\n frameworkName === FRAMEWORKS[\"tanstack-start\"].name ||\n frameworkName === FRAMEWORKS[\"react-router\"].name\n ) {\n return \"VITE_\"\n } else if (\n frameworkName === FRAMEWORKS.laravel.name ||\n frameworkName === FRAMEWORKS.manual.name\n ) {\n return \"\"\n } else {\n return \"\"\n }\n}\n\n/**\n * Detect the actual file extension of style files in the project\n */\nfunction detectStyleFileExtension(config?: Config): string {\n if (!config?.resolvedPaths?.styles) {\n return \"scss\" // Default to scss if no config\n }\n\n const stylesDir = config.resolvedPaths.styles\n const variablesScss = path.join(stylesDir, \"_variables.scss\")\n const variablesCss = path.join(stylesDir, \"_variables.css\")\n\n // Check if CSS version exists (from Bun conversion)\n if (existsSync(variablesCss)) {\n return \"css\"\n }\n\n // Check if SCSS version exists\n if (existsSync(variablesScss)) {\n return \"scss\"\n }\n\n // Default to scss for new installations\n return \"scss\"\n}\n\n/**\n * Calculate the correct import path from main CSS file to styles directory\n */\nfunction calculateStylesImportPath(\n framework?: Framework,\n config?: Config\n): { cssFile: string; importPath: string } {\n const frameworkName = framework?.name || \"unknown\"\n\n // Check if styles are in src directory\n const stylesInSrc = config?.resolvedPaths?.styles?.includes(\"/src/\")\n const hasSrcDir = config?.resolvedPaths?.components?.includes(\"/src/\")\n\n // Determine the main CSS file location based on framework\n let cssFile = \"your main CSS file\"\n let importPath = \"./styles/\"\n\n switch (frameworkName) {\n case FRAMEWORKS[\"next-app\"].name:\n // Next.js App Router\n if (hasSrcDir) {\n // With srcDir: src/app/globals.css -> ../styles/\n cssFile = \"src/app/globals.css\"\n importPath = \"../styles/\"\n } else if (stylesInSrc) {\n // Without srcDir but styles in src: app/globals.css -> ../src/styles/\n cssFile = \"app/globals.css\"\n importPath = \"../src/styles/\"\n } else {\n // Without srcDir and styles at root: app/globals.css -> ../styles/\n cssFile = \"app/globals.css\"\n importPath = \"../styles/\"\n }\n break\n\n case FRAMEWORKS[\"next-pages\"].name:\n // Next.js Pages Router\n if (hasSrcDir) {\n // With srcDir: src/pages/_app.tsx imports from ../styles/globals.css\n cssFile = \"src/styles/globals.css\"\n importPath = \"./\"\n } else if (stylesInSrc) {\n // Without srcDir but styles in src: pages/_app.tsx imports from ../src/styles/\n cssFile = \"src/styles/globals.css\"\n importPath = \"./\"\n } else {\n // Without srcDir: styles/globals.css\n cssFile = \"styles/globals.css\"\n importPath = \"./\"\n }\n break\n\n case FRAMEWORKS.vite.name:\n // Vite - typically src/index.css or src/main.css\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS[\"react-router\"].name:\n // React Router - similar to Vite, uses src structure\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS[\"tanstack-start\"].name:\n // TanStack Start - Vite-based, uses src structure\n cssFile = \"src/index.css\" // or src/main.css\n importPath = \"./styles/\"\n break\n\n case FRAMEWORKS.astro.name:\n // Astro - typically has styles imported in layout files\n if (stylesInSrc) {\n cssFile = \"src/layouts/Layout.astro\" // or src/pages/index.astro\n importPath = \"../styles/\"\n } else {\n cssFile = \"src/layouts/Layout.astro\"\n importPath = \"../../styles/\" // If styles at root\n }\n break\n\n case FRAMEWORKS.laravel.name:\n // Laravel - uses resources/css/app.css\n cssFile = \"resources/css/app.css\"\n // Laravel styles would be in resources/styles/\n importPath = \"../styles/\"\n break\n\n case FRAMEWORKS.manual.name:\n default:\n // Manual/Unknown - make best guess based on config\n if (hasSrcDir || stylesInSrc) {\n cssFile = \"src/index.css\"\n importPath = \"./styles/\"\n } else {\n cssFile = \"your main CSS file\"\n importPath = \"./styles/\"\n }\n break\n }\n\n return { cssFile, importPath }\n}\n\n/**\n * Show styles setup message to remind users to configure styles\n */\nexport function showStylesConfigurationMessage(\n framework?: Framework,\n config?: Config\n) {\n const fileExtension = detectStyleFileExtension(config)\n const { cssFile, importPath } = calculateStylesImportPath(framework, config)\n\n const content = [\n \"The editor requires these style imports:\",\n \"\",\n `Add to ${colors.cyan(cssFile)}:`,\n \"\",\n colors.yellow(` @import '${importPath}_variables.${fileExtension}';`),\n colors.yellow(\n ` @import '${importPath}_keyframe-animations.${fileExtension}';`\n ),\n \"\",\n \"Without these imports, the editor will not display correctly.\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/getting-started/style\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Import Styles\", content)\n logLines(box)\n}\n\n/**\n * Show package manager consistency warning\n */\nexport function showPackageManagerWarning(projectPackageManager: string) {\n const content = [\n `Your project uses ${colors.cyan(projectPackageManager)} as its package manager.`,\n \"\",\n \"For consistency, use the same package manager for all operations:\",\n `• Install dependencies: ${colors.yellow(`${projectPackageManager} install`)}`,\n `• Add packages: ${colors.yellow(`${projectPackageManager} add [package]`)}`,\n `• Run scripts: ${colors.yellow(`${projectPackageManager} run [script]`)}`,\n \"\",\n \"Mixing package managers (npm, pnpm, yarn) can cause conflicts.\",\n ]\n\n const box = createInfoBox(\"Package Manager Detected\", content)\n logLines(box)\n}\n\n/**\n * Show environment variables setup for Notion template (without styles)\n */\nexport function showNotionEnvSetupMessage(framework: Framework) {\n const prefix = getFrameworkEnvPrefix(framework)\n\n const content = [\n \"The Notion-like template requires environment variables for collaborative features:\",\n \"\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_DOC_PREFIX`) +\n \" - Document prefix (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_APP_ID`) +\n \" - Document Server App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_TOKEN`) +\n \" - JWT token for collaboration (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_APP_ID`) + \" - AI App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_TOKEN`) +\n \" - JWT token for AI (required)\",\n \"\",\n \"Get these credentials from your account at cloud.tiptap.dev\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Environment Setup\", content)\n logLines(box)\n}\n\n/**\n * Show combined Notion setup message with environment variables\n */\nexport function showNotionSetupMessage(framework: Framework) {\n const prefix = getFrameworkEnvPrefix(framework)\n\n const content = [\n \"The Notion template requires these environment variables:\",\n \"\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_DOC_PREFIX`) +\n \" - Document prefix (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_APP_ID`) +\n \" - Document Server App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_COLLAB_TOKEN`) +\n \" - JWT token for collaboration (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_APP_ID`) + \" - AI App ID (required)\",\n colors.yellow(`${prefix}TIPTAP_AI_TOKEN`) +\n \" - JWT token for AI (required)\",\n \"\",\n \"Get these credentials from your account at cloud.tiptap.dev\",\n \"\",\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Action Required: Environment Setup\", content)\n logLines(box)\n}\n\n/**\n * Show combined Notion template setup message\n */\nexport function showNotionTemplateSetupMessage(\n framework: Framework,\n config?: Config\n) {\n const prefix = getFrameworkEnvPrefix(framework)\n const fileExtension = detectStyleFileExtension(config)\n const { cssFile, importPath } = calculateStylesImportPath(framework, config)\n\n const content = [\n \"The Notion-like template is a complete editor application that requires\",\n \"additional configuration before it can be used:\",\n \"\",\n colors.cyan(\"1. Import Required Styles\"),\n ` Add to ${colors.yellow(cssFile)}:`,\n colors.gray(` @import '${importPath}_variables.${fileExtension}';`),\n colors.gray(\n ` @import '${importPath}_keyframe-animations.${fileExtension}';`\n ),\n \"\",\n colors.cyan(\"2. Add Environment Variables (for collaborative features)\"),\n ` Add to your .env file:`,\n colors.gray(` ${prefix}TIPTAP_COLLAB_DOC_PREFIX - Document prefix`),\n colors.gray(` ${prefix}TIPTAP_COLLAB_APP_ID - Document Server App ID`),\n colors.gray(\n ` ${prefix}TIPTAP_COLLAB_TOKEN - JWT token for collaboration`\n ),\n colors.gray(` ${prefix}TIPTAP_AI_APP_ID - AI App ID`),\n colors.gray(` ${prefix}TIPTAP_AI_TOKEN - JWT token for AI`),\n \"\",\n `Get credentials at ${colors.cyan(\"https://cloud.tiptap.dev\")}`,\n `Setup guide: ${colors.cyan(\"https://tiptap.dev/docs/ui-components/templates/notion-like-editor\")}`,\n ]\n\n const box = createWarningBox(\"Next Steps: Configure your Editor\", content)\n logLines(box)\n}\n\n/**\n * Show Table Node integration guide\n */\nexport function showTableNodeSetupMessage() {\n logger.log(\"\")\n logger.log(colors.cyan(\"→ Table Node integration guide:\"))\n logger.log(\n ` ${colors.dim(\"https://tiptap.dev/docs/ui-components/node-components/table-node#usage\")}`\n )\n logger.log(\"\")\n}\n","import path from \"node:path\"\nimport { getPackageRunner } from \"./get-package-manager\"\nimport { confirm, select } from \"@inquirer/prompts\"\nimport { InvalidArgumentError, Option } from \"commander\"\nimport { canPrompt } from \"./cli-ui\"\nimport { toReadableName } from \"./common\"\nimport { logger } from \"./logger\"\nimport type { ComponentPlan } from \"./add-components\"\nimport type { CollaborationSetup } from \"./plan-collaboration\"\nimport { getRegistryFeatures, getRegistryIndex } from \"./registry\"\nimport { resolveFeatureEditor } from \"./feature-project\"\nimport {\n featureIdSchema,\n registryModulePathSchema,\n type RegistryFeatureEntry,\n type RegistryItemIndexSchema,\n type RegistryFeature,\n} from \"./registry/schema\"\n\ntype Template = RegistryItemIndexSchema[number]\n\nexport function featureOption() {\n return new Option(\n \"--with <id>\",\n \"install a feature from the registry\"\n ).argParser((value: string, previous?: string) => {\n if (previous !== undefined) {\n throw new InvalidArgumentError(\n \"Pass --with once per command. To install another feature, run add again.\"\n )\n }\n return value\n })\n}\n\nexport function templateFeatureNames(\n template: Template,\n status: \"supported\" | \"built-in\" = \"supported\"\n) {\n const relations = template.meta?.featureSupport\n if (!relations || typeof relations !== \"object\" || Array.isArray(relations))\n return []\n return Object.entries(relations)\n .filter(\n ([id, relation]) =>\n relation === status && featureIdSchema.safeParse(id).success\n )\n .map(([id]) => id)\n}\n\nexport function isInstallableFeature(\n entry: RegistryFeatureEntry\n): entry is RegistryFeature {\n return \"integration\" in entry\n}\n\nexport async function getOptionalRegistryFeatures() {\n try {\n return (await getRegistryFeatures()).filter(isInstallableFeature)\n } catch (error) {\n const reason =\n error instanceof Error ? error.message : \"The catalog is unavailable.\"\n console.warn(`Could not load editor features. ${reason}`)\n return []\n }\n}\n\nexport async function findRegistryFeature(\n entries: RegistryFeatureEntry[],\n id: string,\n cwd = process.cwd()\n) {\n const entry = entries.find((item) => item.id === id)\n if (!entry || isInstallableFeature(entry)) return entry\n const runner = await getPackageRunner(cwd)\n throw new Error(\n `This CLI version cannot install feature \"${id}\". Run ${runner} @tiptap/cli@latest view ${id}.`\n )\n}\n\nexport async function chooseTemplateFeature(\n template: Template,\n features?: RegistryFeature[]\n) {\n if (!canPrompt()) return\n const ids = templateFeatureNames(template)\n if (!ids.length) return\n const choices = (features ?? (await getOptionalRegistryFeatures())).filter(\n (feature) => ids.includes(feature.id)\n )\n if (!choices.length) return\n if (choices.length === 1) {\n const recipe = choices[0]!\n const accepted = await confirm({\n message: `Add ${recipe.label} to ${toReadableName(template.name)}?`,\n default: false,\n })\n return accepted ? recipe : undefined\n }\n const id = await select({\n message: `Add an optional feature to ${toReadableName(template.name)}?`,\n choices: [\n { name: \"Skip optional features\", value: \"\" },\n ...choices.map((feature) => ({ name: feature.label, value: feature.id })),\n ],\n default: \"\",\n })\n return choices.find((feature) => feature.id === id)\n}\n\nexport async function resolveSelection(\n components: string[],\n requested?: string,\n cwd = process.cwd()\n) {\n const registry = components.length ? await getRegistryIndex() : []\n const sources = components.map((name) => ({\n name,\n plans: registry.find((item) => item.name === name)?.plans ?? [],\n }))\n const templates = registry.filter(\n (item) =>\n item.type === \"registry:template\" && components.includes(item.name)\n )\n const template = templates.length === 1 ? templates[0] : undefined\n let feature: RegistryFeature | undefined\n let builtIn: string | undefined\n if (requested) {\n const catalog = await getRegistryFeatures()\n if (!catalog.length)\n throw new Error(\"This registry offers no features for this CLI.\")\n feature = await findRegistryFeature(catalog, requested, cwd)\n if (!feature)\n throw new Error(\n `Unknown feature \"${requested}\". Available features: ${catalog.map((item) => item.id).join(\", \")}.`\n )\n if (components.length && !template)\n throw new Error(\n \"Choose one template with --with, or omit the positional arguments to install the feature on its own.\"\n )\n if (template) {\n if (templateFeatureNames(template, \"built-in\").includes(requested)) {\n builtIn = `${toReadableName(template.name)} already includes ${feature.label}.`\n feature = undefined\n } else if (!templateFeatureNames(template).includes(requested)) {\n const runner = await getPackageRunner(cwd)\n throw new Error(\n `${toReadableName(template.name)} does not declare support for ${feature.label}. Run ${runner} @tiptap/cli add --with ${requested} to install it in your own editor.`\n )\n } else if (\n feature.integration.kind !== \"files\" &&\n !registryModulePathSchema.safeParse(template.meta?.editor).success\n ) {\n throw new Error(\n `The registry must declare a valid editor module for ${template.name} to install ${feature.label}.`\n )\n }\n }\n }\n return { sources, template, feature, builtIn }\n}\n\nexport async function resolveEditor(\n selection: Awaited<ReturnType<typeof resolveSelection>>,\n cwd: string,\n editor: string | undefined,\n interactive: boolean\n) {\n if (\n !selection.feature ||\n selection.template ||\n (selection.feature.integration.kind === \"files\" && !editor)\n )\n return { editorPath: undefined, candidates: [] }\n return resolveFeatureEditor(cwd, editor, interactive)\n}\n\nfunction quoteArgument(value: string) {\n return /^[a-zA-Z0-9_./-]+$/.test(value)\n ? value\n : \"'\" + value.replaceAll(\"'\", \"'\\\\''\") + \"'\"\n}\n\ntype FeaturePlan = Pick<ComponentPlan, \"collaboration\" | \"extensionSetup\">\n\nexport async function showFeatureSetup(\n recipe: RegistryFeature | undefined,\n plan: FeaturePlan,\n options?: {\n preview?: boolean\n cwd: string\n diff?: boolean | string\n pathOverride?: string\n candidates?: string[]\n }\n) {\n if (!recipe) return\n const preview = options?.preview ?? false\n const setup = plan.extensionSetup\n const collaboration = plan.collaboration\n const filtered = typeof options?.diff === \"string\"\n if (options && typeof options.diff === \"string\") {\n const target = setup ?? collaboration\n if (\n target?.status !== \"pending\" ||\n !target.editorPath ||\n path.resolve(options.cwd, target.editorPath) !==\n path.resolve(options.cwd, options.diff)\n )\n return\n }\n if (\n !filtered &&\n options?.candidates &&\n !(setup ?? collaboration)?.editorPath &&\n recipe.integration.kind !== \"files\"\n ) {\n const candidates = options.candidates\n logger.log(\n candidates.length\n ? \"Choose an editor to connect:\"\n : \"The CLI found no editor. After you create one, connect it with --editor.\"\n )\n for (const candidate of candidates) logger.log(` ${candidate}`)\n const editor = candidates.length ? quoteArgument(candidates[0]!) : \"<path>\"\n const destination = options.pathOverride\n ? ` --path ${quoteArgument(options.pathOverride)}`\n : \"\"\n logger.log(\n `${await getPackageRunner(options.cwd)} @tiptap/cli add --with ${recipe.id} --editor ${editor}${destination}`\n )\n }\n if (collaboration) {\n if (filtered) showPendingCollaborationEdit(collaboration)\n else showCollaborationSetup(collaboration, preview)\n if (collaboration.suggestedTemplate) {\n const runner = await getPackageRunner(options?.cwd ?? process.cwd())\n const destination = options?.pathOverride\n ? ` --path ${quoteArgument(options.pathOverride)}`\n : \"\"\n logger.log(\n `To connect the template with its original demo content, run ${runner} @tiptap/cli add ${collaboration.suggestedTemplate} --with ${recipe.id}${destination}`\n )\n }\n }\n if (setup) {\n if (!setup.editorPath) {\n logger.log(\n `Import { ${setup.exportName} } from ${setup.extensionPath} and add it to your editor's extensions array.`\n )\n } else if (setup.status === \"pending\") {\n logger.warn(`${recipe.label} needs a manual edit in ${setup.editorPath}.`)\n if (setup.reason) logger.log(setup.reason)\n if (setup.importPath)\n logger.log(\n `Import { ${setup.exportName} } from \"${setup.importPath}\" and add it to the editor's extensions array.`\n )\n } else if (setup.status === \"unchanged\") {\n logger.log(`${setup.editorPath} already uses ${recipe.label}.`)\n } else {\n logger.log(\n preview\n ? `The CLI will connect ${recipe.label} to ${setup.editorPath}.`\n : `The CLI connected ${recipe.label} to ${setup.editorPath}.`\n )\n }\n if (!filtered) logger.log(`Extension file ${setup.extensionPath}`)\n }\n if (!filtered) {\n for (const instruction of recipe.instructions ?? []) logger.log(instruction)\n if (recipe.docs) logger.log(`Documentation ${recipe.docs}`)\n }\n}\n\nfunction showPendingCollaborationEdit(setup: CollaborationSetup) {\n logger.warn(`Collaboration needs a manual edit in ${setup.editorPath}.`)\n if (setup.reason) logger.log(setup.reason)\n if (setup.patch) logger.log(setup.patch)\n}\n\nfunction showCollaborationSetup(setup: CollaborationSetup, preview = false) {\n if (!setup.editorPath) {\n if (setup.reason) logger.warn(setup.reason)\n logger.log(\n `Import { withCollaboration } from ${setup.wrapperPath} and wrap your editor component. Pass collaboration to its extensions, pass editable to useEditor, and disable StarterKit undoRedo.`\n )\n } else if (setup.status === \"pending\") {\n showPendingCollaborationEdit(setup)\n } else if (setup.status === \"unchanged\") {\n logger.log(`${setup.editorPath} already uses Collaboration.`)\n } else {\n logger.log(\n preview\n ? `The CLI will connect Collaboration to ${setup.editorPath}.`\n : `The CLI connected Collaboration to ${setup.editorPath}.`\n )\n }\n\n logger.log(\n `For live sync, set appId to the Document Server ID from your Tiptap Cloud trial or subscription in ${setup.configPath}. Set defaultDocumentName to a stable document ID.`\n )\n if (setup.customPagePath) {\n logger.log(\n `Check that your custom route in ${setup.customPagePath} renders the connected editor.`\n )\n }\n if (setup.tokenPath && setup.existingTokenRoute) {\n logger.log(\n `Check that your existing handler in ${setup.tokenPath} authorizes the documentName in the POST body and returns { \"token\": \"...\" }.`\n )\n } else if (setup.tokenPath) {\n logger.log(\n `Connect authorizeDocument to your session and document permissions in ${setup.tokenPath}.`\n )\n logger.log(\n \"Set TIPTAP_AUTH_ENVIRONMENT_ID and TIPTAP_AUTH_PRIVATE_KEY on your server.\"\n )\n } else {\n logger.log(\n setup.entryPath\n ? `Your app opens the editor from ${setup.entryPath}.`\n : \"Render the wrapped editor where your app opens the document.\"\n )\n logger.log(\n 'Point tokenEndpoint at your backend. It must authorize POST { \"documentName\": \"...\" } and return { \"token\": \"...\" }.'\n )\n }\n logger.log(\n \"After configuring access, open the same document in two sessions and type in one.\"\n )\n logger.log(\n \"Document authentication https://tiptap.dev/docs/collaboration/getting-started/authenticate\"\n )\n}\n","import { promises as fs } from \"node:fs\"\nimport path from \"node:path\"\nimport { confirm } from \"@inquirer/prompts\"\nimport fg from \"fast-glob\"\nimport { ts } from \"ts-morph\"\nimport { canPrompt } from \"./cli-ui\"\nimport type { ProjectInfo } from \"./get-project-info\"\nimport { getConfig } from \"./get-config\"\nimport { getPackageInfo } from \"./get-package-info\"\n\nconst reactGuide =\n \"https://tiptap.dev/docs/editor/getting-started/install/react\"\n\nexport function requireReactProject(cwd: string) {\n const manifest = getPackageInfo(cwd, false)\n if (!manifest)\n throw new Error(\n `Run this command in a project with a package.json. Check ${cwd}.`\n )\n if (\n !manifest.dependencies?.react &&\n !manifest.devDependencies?.react &&\n !manifest.peerDependencies?.react &&\n !manifest.optionalDependencies?.react\n ) {\n throw new Error(\n `Install React in this project before adding an editor feature. ${reactGuide}`\n )\n }\n}\n\nexport async function getFeatureConfig(\n cwd: string,\n pathOverride?: string,\n projectInfo?: ProjectInfo | null\n) {\n requireReactProject(cwd)\n return getConfig(cwd, pathOverride, { featureOnly: true, projectInfo })\n}\n\nasync function importsEditorHook(cwd: string, file: string) {\n const text = await fs.readFile(path.resolve(cwd, file), \"utf8\")\n if (!text.includes(\"@tiptap/react\") || !text.includes(\"useEditor\"))\n return false\n const source = ts.createSourceFile(file, text, ts.ScriptTarget.Latest)\n return source.statements.some((statement) => {\n if (\n !ts.isImportDeclaration(statement) ||\n !ts.isStringLiteral(statement.moduleSpecifier) ||\n statement.moduleSpecifier.text !== \"@tiptap/react\" ||\n statement.importClause?.isTypeOnly\n )\n return false\n const named = statement.importClause?.namedBindings\n return (\n named &&\n ts.isNamedImports(named) &&\n named.elements.some(\n (item) =>\n !item.isTypeOnly &&\n (item.propertyName ?? item.name).text === \"useEditor\"\n )\n )\n })\n}\n\nfunction withinProject(root: string, file: string) {\n const rel = path.relative(root, file)\n return (\n rel !== \"\" &&\n rel !== \"..\" &&\n !rel.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(rel)\n )\n}\n\nasync function findNestedPackage(cwd: string, editor: string) {\n const root = await fs.realpath(cwd)\n let directory = path.dirname(await fs.realpath(editor))\n while (withinProject(root, directory)) {\n if (\n await fs.stat(path.join(directory, \"package.json\")).then(\n (stat) => stat.isFile(),\n () => false\n )\n ) {\n return directory\n }\n directory = path.dirname(directory)\n }\n}\n\nexport async function resolveFeatureEditor(\n cwd: string,\n explicitEditor: string | undefined,\n interactive: boolean\n): Promise<{ editorPath?: string; candidates: string[] }> {\n if (explicitEditor !== undefined) {\n const editorPath = path.resolve(cwd, explicitEditor)\n const real = await fs\n .realpath(editorPath)\n .catch((error: NodeJS.ErrnoException) => {\n if (error.code !== \"ENOENT\") throw error\n throw new Error(`Cannot find the editor file ${explicitEditor}.`)\n })\n if (\n !withinProject(cwd, editorPath) ||\n !withinProject(await fs.realpath(cwd), real) ||\n !/\\.[jt]sx?$/i.test(editorPath) ||\n /\\.d\\.ts$/i.test(editorPath) ||\n !(await fs.stat(real)).isFile()\n ) {\n throw new Error(\n \"--editor needs a JavaScript or TypeScript source file inside this project.\"\n )\n }\n const nestedPackage = await findNestedPackage(cwd, editorPath)\n if (nestedPackage)\n throw new Error(\n `The editor belongs to a workspace package. Run this command in ${nestedPackage}.`\n )\n if (!(await importsEditorHook(cwd, editorPath))) {\n throw new Error(\n `${explicitEditor} must import useEditor from @tiptap/react.`\n )\n }\n return { editorPath, candidates: [] }\n }\n\n const files = await fg(\"**/*.{js,jsx,ts,tsx}\", {\n cwd,\n followSymbolicLinks: false,\n onlyFiles: true,\n ignore: [\n \"**/{node_modules,dist,build,coverage,public,out,vendor}/**\",\n \"**/*.d.ts\",\n \"**/*.{test,spec,stories}.*\",\n \"**/{__tests__,__mocks__,e2e,.storybook}/**\",\n ],\n })\n const candidates: string[] = []\n for (const file of files.sort()) {\n try {\n if (\n (await importsEditorHook(cwd, file)) &&\n !(await findNestedPackage(cwd, path.resolve(cwd, file)))\n ) {\n candidates.push(file)\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error\n }\n }\n if (candidates.length === 1 && interactive && canPrompt()) {\n const candidate = candidates[0]!\n if (\n await confirm({\n message: `Connect the feature to ${candidate}?`,\n default: false,\n })\n ) {\n return { editorPath: path.resolve(cwd, candidate), candidates }\n }\n }\n return { candidates }\n}\n","import { existsSync } from \"node:fs\"\nimport { getInstalledPackageVersion } from \"@/src/utils/get-package-info\"\nimport path from \"node:path\"\nimport { Command } from \"commander\"\nimport cli from \"../../package.json\"\nimport { getMainCssFilePath } from \"@/src/utils/auto-import-styles\"\nimport { getConfig } from \"@/src/utils/get-config\"\nimport { getPackageManagerInfo } from \"@/src/utils/get-package-manager\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport { getRegistryBaseUrl } from \"@/src/utils/registry\"\n\nexport const info = new Command()\n .name(\"info\")\n .description(\"get information about your project\")\n .option(\"-c, --cwd <cwd>\", \"the working directory\", process.cwd())\n .option(\"--json\", \"print project diagnostics as JSON\")\n .action(async (opts) => {\n const cwd = path.resolve(opts.cwd)\n const project = await getProjectInfo(cwd)\n const config = await getConfig(cwd).catch(() => null)\n if (opts.json) {\n const stylesheet =\n config && project && getMainCssFilePath(project.framework, config)\n console.log(\n JSON.stringify(\n {\n cliVersion: cli.version,\n cwd,\n project,\n packageManager: await getPackageManagerInfo(cwd, {\n withFallback: true,\n }),\n installedVersions: Object.fromEntries(\n [\"next\", \"react\", \"@tiptap/core\"].map((name) => [\n name,\n getInstalledPackageVersion(cwd, name),\n ])\n ),\n stylesheet:\n stylesheet && existsSync(stylesheet) ? stylesheet : null,\n aliases: config?.aliases ?? null,\n registryOrigin: new URL(getRegistryBaseUrl()).origin,\n },\n null,\n 2\n )\n )\n return\n }\n logger.info(\"> project info\")\n console.log(project)\n logger.break()\n if (config) {\n logger.info(\"> config\")\n console.log(config)\n }\n })\n","{\n \"name\": \"@tiptap/cli\",\n \"version\": \"3.21.0\",\n \"description\": \"Tiptap CLI\",\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"author\": {\n \"name\": \"tiptap\",\n \"url\": \"https://github.com/ueberdosis/tiptap\"\n },\n \"files\": [\n \"dist\"\n ],\n \"keywords\": [\n \"cli\",\n \"components\",\n \"nextjs\",\n \"react\",\n \"templates\",\n \"tiptap\",\n \"@tiptap/cli\",\n \"ui\"\n ],\n \"license\": \"SEE LICENSE IN LICENSE.md\",\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"types\": \"./dist/index.d.ts\",\n \"default\": \"./dist/index.js\"\n }\n },\n \"bin\": \"./dist/index.js\",\n \"scripts\": {\n \"dev\": \"tsup --watch\",\n \"build\": \"tsup\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\",\n \"clean\": \"rm -rf dist\",\n \"start:dev\": \"cross-env TIPTAP_REGISTRY_URL=http://localhost:3000 node dist/index.js\",\n \"start:prod\": \"cross-env TIPTAP_REGISTRY_URL=https://template.tiptap.dev node dist/index.js\",\n \"start\": \"node dist/index.js\",\n \"pub:beta\": \"pnpm build && pnpm publish --no-git-checks --access public --tag beta\",\n \"pub:release\": \"pnpm build && pnpm publish --access public\"\n },\n \"dependencies\": {\n \"@antfu/ni\": \"^30.6.0\",\n \"@babel/core\": \"^7.29.7\",\n \"@babel/parser\": \"^7.29.9\",\n \"@babel/plugin-transform-typescript\": \"^7.29.9\",\n \"@inquirer/core\": \"^11.2.1\",\n \"@inquirer/figures\": \"^2.0.9\",\n \"@inquirer/prompts\": \"^8.7.3\",\n \"@inquirer/type\": \"^4.2.0\",\n \"@npmcli/map-workspaces\": \"^5.0.3\",\n \"ansi-escapes\": \"^7.3.0\",\n \"chalk\": \"^5.6.2\",\n \"commander\": \"^14.0.3\",\n \"conf\": \"^15.1.0\",\n \"cosmiconfig\": \"^9.0.2\",\n \"diff\": \"^9.0.0\",\n \"execa\": \"^9.6.1\",\n \"fast-glob\": \"^3.3.3\",\n \"fs-extra\": \"^11.4.1\",\n \"https-proxy-agent\": \"^9.1.0\",\n \"jsonc-parser\": \"^3.3.1\",\n \"node-fetch\": \"^3.3.2\",\n \"ora\": \"^9.4.1\",\n \"postcss\": \"^8.5.32\",\n \"postcss-scss\": \"^4.0.9\",\n \"recast\": \"^0.23.21\",\n \"semver\": \"^7.8.6\",\n \"ts-morph\": \"^28.0.0\",\n \"tsconfig-paths\": \"^4.2.0\",\n \"yaml\": \"^2.9.1\",\n \"yoctocolors-cjs\": \"^2.1.3\",\n \"zod\": \"^4.6.5\"\n },\n \"devDependencies\": {\n \"@babel/plugin-transform-typescript\": \"^7.26.5\",\n \"@types/babel__core\": \"^7.20.5\",\n \"@types/conf\": \"^3.0.3\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/prompts\": \"^2.4.9\",\n \"@types/semver\": \"^7.8.0\",\n \"cross-env\": \"^10.1.0\",\n \"sass\": \"^1.105.1\",\n \"tsup\": \"^8.5.1\",\n \"type-fest\": \"^5.10.0\",\n \"typescript\": \"^5.9.3\",\n \"vitest\": \"^4.1.11\"\n }\n}\n","import { Command, InvalidArgumentError } from \"commander\"\nimport { getRegistryIndex } from \"@/src/utils/registry\"\nimport {\n registryItemTypeSchema,\n type RegistryItemIndexSchema,\n} from \"@/src/utils/registry/schema\"\n\nfunction parseType(value: string) {\n const type = value.startsWith(\"registry:\") ? value : `registry:${value}`\n const parsed = registryItemTypeSchema.safeParse(type)\n if (!parsed.success)\n throw new InvalidArgumentError(`Unknown registry type \"${value}\".`)\n return parsed.data\n}\n\nfunction parseCount(value: string) {\n const count = Number(value)\n if (!/^\\d+$/.test(value) || !Number.isSafeInteger(count)) {\n throw new InvalidArgumentError(\"Use a nonnegative integer.\")\n }\n return count\n}\n\nexport function searchRegistryIndex(\n index: RegistryItemIndexSchema,\n query: string,\n options: { type?: string; limit?: number; offset: number }\n) {\n const terms = query.trim().toLowerCase().split(/\\s+/)\n const matches = index.filter((item) => {\n if (item.hide || (options.type && item.type !== options.type)) return false\n const text = `${item.name} ${item.description ?? \"\"}`.toLowerCase()\n return terms.every((term) => text.includes(term))\n })\n const end =\n options.limit === undefined ? undefined : options.offset + options.limit\n return {\n total: matches.length,\n items: matches.slice(options.offset, end).map((item) => ({\n name: item.name,\n type: item.type,\n description: item.description ?? null,\n plans: item.plans ?? [],\n addCommand: `pnpm dlx @tiptap/cli add ${item.name}`,\n })),\n }\n}\n\nexport const search = new Command(\"search\")\n .description(\"search public registry entries\")\n .argument(\"[query...]\", \"words to match in the name or description\")\n .option(\n \"--type <type>\",\n \"filter by registry type, such as node or template\",\n parseType\n )\n .option(\"--limit <count>\", \"maximum number of results\", parseCount)\n .option(\n \"--offset <count>\",\n \"number of matching entries to skip\",\n parseCount,\n 0\n )\n .option(\"--json\", \"print results as JSON\")\n .action(async (query: string[], options) => {\n const result = searchRegistryIndex(\n await getRegistryIndex(),\n query.join(\" \"),\n {\n type: options.type,\n limit: options.limit,\n offset: options.offset,\n }\n )\n if (options.json) {\n console.log(JSON.stringify(result, null, 2))\n return\n }\n console.log(`${result.items.length} of ${result.total} matching entries`)\n for (const item of result.items) {\n console.log(`\\n${item.name} ${item.type} ${item.plans.join(\", \")}`)\n if (item.description) console.log(item.description)\n console.log(item.addCommand)\n }\n })\n","import { Command } from \"commander\"\nimport { getPackageRunner } from \"@/src/utils/get-package-manager\"\nimport {\n findRegistryFeature,\n getOptionalRegistryFeatures,\n isInstallableFeature,\n templateFeatureNames,\n} from \"@/src/utils/features\"\nimport { assertCanPreviewPaidComponents } from \"@/src/utils/auth-check\"\nimport {\n fetchRegistry,\n getRegistryIndex,\n getRegistryFeatures,\n} from \"@/src/utils/registry\"\nimport {\n registrySourceItemSchema,\n type RegistryItemIndexSchema,\n} from \"@/src/utils/registry/schema\"\n\nasync function describeItem(item: RegistryItemIndexSchema[number]) {\n const supported = templateFeatureNames(item)\n const features = supported.length\n ? (await getOptionalRegistryFeatures())\n .filter((feature) => supported.includes(feature.id))\n .map((feature) => feature.id)\n : []\n const files = (item.files ?? []).map((file) => {\n if (typeof file === \"string\")\n return { path: file, type: item.type, target: null }\n return { path: file.path, type: file.type, target: file.target || null }\n })\n const routes = files.flatMap(({ type, target }) => {\n if (\n type !== \"registry:page\" ||\n !target ||\n !/^(?:src\\/)?app\\/(?:.*\\/)?page\\.[jt]sx?$/.test(target)\n )\n return []\n const route = target\n .replace(/^(?:src\\/)?app/, \"\")\n .replace(/\\/page\\.[jt]sx?$/, \"\")\n return [route || \"/\"]\n })\n return {\n name: item.name,\n type: item.type,\n description: item.description ?? null,\n plans: item.plans ?? [],\n routes,\n links: item.meta?.links ?? {},\n dependencies: item.dependencies ?? [],\n devDependencies: item.devDependencies ?? [],\n registryDependencies: item.registryDependencies ?? [],\n features,\n builtInFeatures: templateFeatureNames(item, \"built-in\"),\n files,\n addCommand: `pnpm dlx @tiptap/cli add ${item.name}`,\n }\n}\n\nexport const view = new Command(\"view\")\n .description(\"inspect a registry item and its direct dependencies\")\n .argument(\"[name]\", \"registry item name or feature id\")\n .option(\"--features\", \"list all feature ids from the registry\")\n .option(\"--source\", \"retrieve file contents from the component endpoint\")\n .option(\"--json\", \"print item metadata as JSON\")\n .action(async (name: string | undefined, options) => {\n if (options.features) {\n if (name || options.source)\n throw new Error(\"Use view --features on its own or with --json.\")\n const features = await getRegistryFeatures()\n if (options.json)\n console.log(\n JSON.stringify(\n features.map((feature) => feature.id),\n null,\n 2\n )\n )\n else\n console.log(\n features.length\n ? features\n .map((feature) =>\n isInstallableFeature(feature)\n ? feature.id\n : `${feature.id} (requires a newer CLI)`\n )\n .join(\"\\n\")\n : \"This registry offers no features for this CLI.\"\n )\n return\n }\n if (!name)\n throw new Error(\n \"Name a registry item or feature, or run view --features.\"\n )\n const item = (await getRegistryIndex()).find(\n (entry) => entry.name === name && !entry.hide\n )\n if (!item) {\n const features = await getRegistryFeatures()\n const feature = await findRegistryFeature(features, name)\n if (!feature)\n throw new Error(\n `No public registry entry named \"${name}\".${features.length ? \" Available features: \" + features.map((entry) => entry.id).join(\", \") + \".\" : \"\"}`\n )\n const addCommand = `${await getPackageRunner(process.cwd())} @tiptap/cli add --with ${feature.id}`\n if (options.source)\n throw new Error(\n `To preview the feature files, run ${addCommand} --diff in your React project.`\n )\n if (options.json)\n console.log(JSON.stringify({ ...feature, addCommand }, null, 2))\n else {\n console.log(`${feature.label} ${feature.id}\\n${feature.description}`)\n console.log(`Registry items ${feature.items.join(\", \")}`)\n for (const [framework, items] of Object.entries(\n feature.frameworkItems ?? {}\n ))\n console.log(`${framework} ${items.join(\", \")}`)\n for (const instruction of feature.instructions) console.log(instruction)\n console.log(`Documentation ${feature.docs}\\n\\n${addCommand}`)\n }\n return\n }\n\n if (options.source) {\n assertCanPreviewPaidComponents([item])\n const [source] = await fetchRegistry([\n `components/${encodeURIComponent(name)}.json`,\n ])\n const payload = registrySourceItemSchema.parse(source)\n if (payload.name !== name)\n throw new Error(`The registry returned a different item for \"${name}\".`)\n assertCanPreviewPaidComponents([payload])\n console.log(JSON.stringify(payload, null, 2))\n return\n }\n\n const details = await describeItem(item)\n if (options.json) {\n console.log(JSON.stringify(details, null, 2))\n return\n }\n\n console.log(`${details.name} ${details.type} ${details.plans.join(\", \")}`)\n if (details.description) console.log(details.description)\n for (const [label, entries] of [\n [\"Routes\", details.routes],\n [\"Dependencies\", details.dependencies],\n [\"Development dependencies\", details.devDependencies],\n [\"Registry dependencies\", details.registryDependencies],\n [\n \"Optional features\",\n details.features.map((feature) => `--with ${feature}`),\n ],\n [\"Built-in features\", details.builtInFeatures],\n [\n \"Files\",\n details.files.map((file) =>\n file.target ? `${file.path} -> ${file.target}` : file.path\n ),\n ],\n ] as const) {\n if (entries.length) console.log(`\\n${label}\\n${entries.join(\"\\n\")}`)\n }\n for (const [label, link] of Object.entries(details.links)) {\n if (typeof link === \"string\") console.log(`${label} ${link}`)\n }\n console.log(`\\n${details.addCommand}`)\n })\n","import { existsSync } from \"node:fs\"\nimport path from \"path\"\nimport { Command } from \"commander\"\nimport { confirm, input } from \"@inquirer/prompts\"\nimport { z } from \"zod\"\n\nimport { preFlightInit } from \"@/src/preflights/preflight-init\"\nimport { promptForRegistryComponents } from \"@/src/commands/add\"\nimport { FRAMEWORKS, createProject } from \"@/src/utils/create-project\"\nimport { colors } from \"@/src/utils/colors\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { addComponents } from \"@/src/utils/add-components\"\nimport {\n getProjectConfig,\n getProjectInfo,\n ProjectInfo,\n} from \"@/src/utils/get-project-info\"\nimport {\n DEFAULT_COMPONENTS,\n DEFAULT_CONTEXTS,\n DEFAULT_HOOKS,\n DEFAULT_TIPTAP_ICONS,\n DEFAULT_LIB,\n DEFAULT_STYLES,\n DEFAULT_TIPTAP_EXTENSIONS,\n DEFAULT_TIPTAP_NODES,\n DEFAULT_TIPTAP_UI,\n DEFAULT_TIPTAP_UI_PRIMITIVES,\n DEFAULT_TIPTAP_UI_UTILS,\n getConfig,\n rawConfigSchema,\n resolveConfigPaths,\n type Config,\n} from \"@/src/utils/get-config\"\nimport {\n ensureAuthForPaidComponents,\n hasPaidComponents,\n} from \"../utils/auth-check\"\nimport {\n showNotionEnvSetupMessage,\n showNotionTemplateSetupMessage,\n showStylesConfigurationMessage,\n showTableNodeSetupMessage,\n} from \"@/src/utils/prompt-messages\"\nimport {\n createWelcomeBanner,\n logLines,\n clearTerminal,\n canPrompt,\n} from \"@/src/utils/cli-ui\"\nimport {\n featureOption,\n resolveSelection,\n resolveEditor,\n showFeatureSetup,\n} from \"@/src/utils/features\"\nimport type { RegistryFeature } from \"@/src/utils/registry/schema\"\nimport { getFeatureConfig } from \"@/src/utils/feature-project\"\nimport { logAutoImportResult } from \"@/src/utils/auto-import-styles\"\n\nexport const initOptionsSchema = z.object({\n cwd: z.string(),\n components: z.array(z.string()).optional(),\n with: z.string().min(1).optional(),\n editor: z.string().min(1).optional(),\n silent: z.boolean(),\n isNewProject: z.boolean(),\n name: z\n .string()\n .min(1)\n .max(128)\n .regex(\n /^[a-z0-9][a-z0-9._-]*$/,\n \"Use a project name with lowercase letters, digits, dots, underscores, or hyphens.\"\n )\n .optional(),\n defaults: z.boolean().optional(),\n srcDir: z.boolean().optional(),\n reactCompiler: z.boolean().optional(),\n framework: z\n .string()\n .optional()\n .refine((val) => !val || FRAMEWORKS[val as keyof typeof FRAMEWORKS], {\n message: \"Invalid framework. Please use 'next' or 'vite'.\",\n }),\n})\n\nexport type InitOptions = z.infer<typeof initOptionsSchema> & {\n skipPreflight?: boolean\n}\n\n/**\n * Creates a themed confirmation prompt with consistent styling\n */\nconst createThemedConfirm = (message: string, defaultValue: boolean = true) => {\n return confirm({\n message: colors.reset(message),\n default: defaultValue,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Initialize the CLI command\n */\nexport const init = new Command()\n .name(\"init\")\n .description(\n \"initialize a project and install editor features, templates, or UI components\"\n )\n .argument(\"[components...]\", \"the components to add\")\n .addOption(featureOption())\n .option(\"--editor <path>\", \"connect the feature to an existing editor file\")\n .option(\"-f, --framework <framework>\", \"the framework to use. (next, vite)\")\n .option(\n \"-c, --cwd <cwd>\",\n \"the working directory. defaults to the current directory.\",\n process.cwd()\n )\n .option(\"--name <name>\", \"name the new project\")\n .option(\n \"--defaults\",\n \"use scaffold defaults and install the requested items\",\n false\n )\n .option(\"-s, --silent\", \"mute output.\", false)\n .option(\n \"--src-dir\",\n \"use the src directory when creating a new project (specific to next).\",\n false\n )\n .option(\n \"--react-compiler\",\n \"enable React Compiler when creating a new project (specific to next).\",\n false\n )\n .action(async (components, opts) => {\n try {\n const options = initOptionsSchema.parse({\n ...opts,\n defaults:\n opts.defaults || Boolean(opts.with && (opts.silent || !canPrompt())),\n cwd: path.resolve(opts.cwd),\n isNewProject: false,\n components,\n })\n if (options.editor && !options.with)\n throw new Error(\"Use --editor with --with <id>.\")\n if (!options.with && !options.defaults && !options.silent) {\n clearTerminal()\n\n logLines(\n createWelcomeBanner(\n \"Tiptap\",\n \"Create a project or add a feature, template, or UI component to an existing app.\"\n )\n )\n\n await input({\n message: colors.reset(\n `Press ${colors.cyan(\"Enter\")} to initialize a project...`\n ),\n theme: {\n prefix: {\n done: \"\",\n idle: \"\",\n },\n },\n })\n\n logger.log(\"\")\n }\n\n const result = await runInit(options)\n\n if (!result || options.silent) return\n if (result.framework)\n logger.log(`Project directory ${result.config.resolvedPaths.cwd}`)\n const files = [\n ...result.filesCreated,\n ...result.filesUpdated,\n ...result.filesSkipped,\n ]\n if (!files.length && !result.feature) return\n\n const hasNotion = files.some((file) => file.includes(\"notion\"))\n const hasSimple = result.selectedComponents.includes(\"simple-editor\")\n const label = hasNotion\n ? \"Notion template\"\n : hasSimple\n ? \"Simple editor template\"\n : (result.feature?.label ?? \"Components\")\n logger.log(\n `${colors.green(\"✔\")} ${label}: ${result.filesCreated.length} created, ${result.filesUpdated.length} updated, ${result.filesSkipped.length} skipped`\n )\n\n const framework = result.projectInfo?.framework\n if (framework && result.styles && result.selectedComponents.length) {\n logAutoImportResult(result.styles)\n if (!result.styles.success) {\n if (hasNotion)\n showNotionTemplateSetupMessage(framework, result.config)\n else showStylesConfigurationMessage(framework, result.config)\n } else if (hasNotion) {\n showNotionEnvSetupMessage(framework)\n }\n }\n if (result.selectedComponents.includes(\"table-node\"))\n showTableNodeSetupMessage()\n\n await showFeatureSetup(result.feature, result, {\n cwd: result.config.resolvedPaths.cwd,\n candidates: result.candidates,\n })\n\n logger.break()\n } catch (error) {\n logger.break()\n handleError(error)\n }\n })\n\n/**\n * Main initialization function\n */\nexport async function runInit(options: InitOptions) {\n const { skipPreflight, components, silent } = options\n if (options.editor && components?.length)\n throw new Error(\n `Choose either ${components.join(\", \")} or --editor ${options.editor}.`\n )\n const requested = options.with\n ? await resolveSelection(components ?? [], options.with, options.cwd)\n : undefined\n if (requested?.builtIn && !silent) logger.log(requested.builtIn)\n let updatedOptions = { ...options }\n let newProjectFramework: string | undefined\n\n // Standard return structure creator\n const createResult = (\n config: Config,\n projectInfo: ProjectInfo | null,\n selectedComponents: string[] = [],\n addResult?: Awaited<ReturnType<typeof addComponents>>,\n feature?: RegistryFeature,\n candidates?: string[]\n ) => ({\n config,\n projectInfo,\n framework: newProjectFramework,\n selectedComponents,\n filesCreated: addResult?.filesCreated || [],\n filesUpdated: addResult?.filesUpdated || [],\n filesSkipped: addResult?.filesSkipped || [],\n styles: addResult?.styles,\n collaboration: addResult?.collaboration,\n extensionSetup: addResult?.extensionSetup,\n feature,\n candidates,\n })\n\n if (!skipPreflight && !existsSync(path.join(options.cwd, \"package.json\"))) {\n if (options.editor)\n throw new Error(\n `Cannot connect --editor ${options.editor} before the project exists in ${options.cwd}.`\n )\n const { projectPath, framework } = await createProject(options)\n\n updatedOptions = {\n ...updatedOptions,\n cwd: projectPath,\n isNewProject: true,\n }\n newProjectFramework = framework\n logger.log(\"\")\n }\n\n // Handle monorepo special case\n if (newProjectFramework === \"next-monorepo\") {\n const monorepoWebPath = path.resolve(updatedOptions.cwd, \"apps/web\")\n if (!requested && !components?.length) {\n const config = await getConfig(monorepoWebPath)\n return createResult(config, null)\n }\n updatedOptions.cwd = monorepoWebPath\n }\n\n let selectedComponents = components ?? []\n let featureId = options.with\n const interactive = !options.defaults && !silent && canPrompt()\n\n if (\n !selectedComponents.length &&\n !featureId &&\n interactive &&\n (await createThemedConfirm(\n \"Would you like to add a template, feature, or UI components to your project?\"\n ))\n ) {\n const choice = await promptForRegistryComponents({\n ...updatedOptions,\n overwrite: false,\n })\n selectedComponents = choice.components\n featureId = choice.feature?.id\n }\n\n const selection =\n requested ??\n (await resolveSelection(selectedComponents, featureId, updatedOptions.cwd))\n const { sources, feature } = selection\n const standalone = !!feature && !selectedComponents.length\n const projectInfo =\n !feature && !skipPreflight && !newProjectFramework\n ? await preFlightInit(updatedOptions)\n : await getProjectInfo(updatedOptions.cwd, { forFeature: !!feature })\n async function templateConfig() {\n const projectConfig = await getProjectConfig(\n updatedOptions.cwd,\n projectInfo\n )\n const config = projectConfig\n ? await promptForMinimalConfig(projectConfig)\n : await promptForConfig(\n await getConfig(updatedOptions.cwd),\n options.defaults\n )\n return resolveConfigPaths(updatedOptions.cwd, config)\n }\n const target = await resolveEditor(\n selection,\n updatedOptions.cwd,\n options.editor,\n interactive\n )\n const fullConfig = feature\n ? await getFeatureConfig(updatedOptions.cwd, undefined, projectInfo)\n : await templateConfig()\n if (!selectedComponents.length && !feature)\n return createResult(fullConfig, projectInfo)\n\n if (\n hasPaidComponents(sources) &&\n !(await ensureAuthForPaidComponents(sources, updatedOptions.cwd, {\n interactive,\n }))\n ) {\n throw new Error(\n \"Authenticate and accept the Pro license before installing paid components.\"\n )\n }\n\n // Add components and return result\n const addComponentsResult = await addComponents(\n selectedComponents,\n fullConfig,\n {\n overwrite: false,\n features: feature ? [feature] : [],\n projectInfo: feature ? projectInfo : undefined,\n editorPath: target.editorPath,\n interactive,\n silent,\n isNewProject:\n updatedOptions.isNewProject ||\n projectInfo?.framework.name === \"next-app\",\n }\n )\n\n return createResult(\n fullConfig,\n projectInfo,\n selectedComponents,\n addComponentsResult,\n feature,\n standalone ? target.candidates : undefined\n )\n}\n/**\n * Prompt for full configuration\n */\nasync function promptForConfig(defaultConfig: Config | null, defaults = false) {\n logger.log(\"\")\n logger.log(colors.cyan(\"Project Configuration\"))\n logger.log(\"\")\n\n const tsx = defaults\n ? (defaultConfig?.tsx ?? true)\n : await createThemedConfirm(\n `Would you like to use ${colors.cyan(\"TypeScript\")} (recommended)?`,\n defaultConfig?.tsx ?? true\n )\n\n const rsc = defaults\n ? (defaultConfig?.rsc ?? true)\n : await createThemedConfirm(\n `Are you using ${colors.cyan(\"React Server Components\")}?`,\n defaultConfig?.rsc ?? true\n )\n\n return rawConfigSchema.parse({\n rsc,\n tsx,\n aliases: {\n components: DEFAULT_COMPONENTS,\n contexts: DEFAULT_CONTEXTS,\n hooks: DEFAULT_HOOKS,\n tiptapIcons: DEFAULT_TIPTAP_ICONS,\n lib: DEFAULT_LIB,\n tiptapExtensions: DEFAULT_TIPTAP_EXTENSIONS,\n tiptapNodes: DEFAULT_TIPTAP_NODES,\n tiptapUi: DEFAULT_TIPTAP_UI,\n tiptapUiPrimitives: DEFAULT_TIPTAP_UI_PRIMITIVES,\n tiptapUiUtils: DEFAULT_TIPTAP_UI_UTILS,\n styles: DEFAULT_STYLES,\n },\n })\n}\n\n/**\n * Prompt for minimal configuration from existing config\n */\nasync function promptForMinimalConfig(defaultConfig: Config) {\n return rawConfigSchema.parse({\n rsc: defaultConfig?.rsc,\n tsx: defaultConfig?.tsx,\n aliases: defaultConfig?.aliases,\n })\n}\n","import type { InitOptions } from \"@/src/commands/init\"\nimport { getProjectInfo } from \"@/src/utils/get-project-info\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport { colors } from \"@/src/utils/colors\"\n\nexport async function preFlightInit(options: InitOptions) {\n const frameworkSpinner = spinner(`Verifying framework.`, {\n silent: options.silent,\n }).start()\n const projectInfo = await getProjectInfo(options.cwd)\n if (!projectInfo || projectInfo?.framework.name === \"manual\") {\n frameworkSpinner?.fail()\n logger.break()\n if (projectInfo?.framework.links.installation) {\n logger.error(\n `We could not detect a supported framework at ${colors.cyan(\n options.cwd\n )}.\\n` +\n `Visit ${colors.cyan(\n projectInfo?.framework.links.installation\n )} to manually configure your project.\\nOnce configured, you can use the cli to add components.`\n )\n }\n logger.break()\n process.exit(1)\n }\n frameworkSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: `Verifying framework. Found ${colors.cyan(projectInfo.framework.label)}.`,\n })\n\n const tsConfigSpinner = spinner(`Validating import alias.`, {\n silent: options.silent,\n }).start()\n if (!projectInfo.aliasPrefix) {\n tsConfigSpinner?.fail()\n logger.break()\n logger.error(`No import alias found in your tsconfig.json file.`)\n if (projectInfo.framework.links.installation) {\n logger.error(\n `Visit ${colors.cyan(\n projectInfo.framework.links.installation\n )} to learn how to set an import alias.`\n )\n }\n logger.break()\n process.exit(1)\n }\n tsConfigSpinner?.stopAndPersist({ symbol: colors.cyan(\"✔\") })\n return projectInfo\n}\n","import os from \"os\"\nimport path from \"path\"\nimport fs from \"fs-extra\"\nimport { execa } from \"execa\"\nimport { z } from \"zod\"\nimport { parse as parseJsonc } from \"jsonc-parser\"\nimport { input } from \"@inquirer/prompts\"\n\nimport { initOptionsSchema } from \"@/src/commands/init\"\nimport select from \"@/src/inquirer/select\"\nimport { colors } from \"@/src/utils/colors\"\nimport { getPackageManager } from \"@/src/utils/get-package-manager\"\nimport { handleError } from \"@/src/utils/handle-error\"\nimport { logger } from \"@/src/utils/logger\"\nimport { spinner } from \"@/src/utils/spinner\"\nimport {\n configureNextPnpmBuilds,\n configureVitePnpmBuilds,\n} from \"@/src/utils/configure-next-pnpm-builds\"\n\nconst MONOREPO_FRAMEWORK_URL =\n \"https://codeload.github.com/shadcn-ui/ui/tar.gz/main\"\n\nexport const FRAMEWORKS = {\n next: \"next\",\n vite: \"vite\",\n \"next-monorepo\": \"next-monorepo\",\n} as const\n\ntype Framework = keyof typeof FRAMEWORKS\ntype ProjectOptions = Pick<\n z.infer<typeof initOptionsSchema>,\n | \"cwd\"\n | \"srcDir\"\n | \"components\"\n | \"framework\"\n | \"reactCompiler\"\n | \"name\"\n | \"defaults\"\n>\ntype CreateNextOptions = {\n version: string\n cwd: string\n packageManager: string\n srcDir: boolean\n reactCompiler: boolean\n}\ntype CreateViteOptions = {\n cwd: string\n packageManager: string\n projectName: string\n}\ntype CreateMonorepoOptions = {\n packageManager: string\n}\n\n/**\n * Creates a themed input prompt with consistent styling\n */\nconst createThemedInput = (message: string, defaultValue: string = \"\") => {\n return input({\n message: colors.reset(message),\n default: defaultValue,\n required: true,\n validate: (value: string) =>\n value.length > 128 ? `Name should be less than 128 characters.` : true,\n theme: {\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n })\n}\n\n/**\n * Creates a themed select prompt with consistent styling\n */\nconst createThemedSelect = async (\n message: string,\n choices: Array<{ name: string; value: string }>\n) => {\n const instructions = `\\n${colors.gray(\" Use arrow-keys ▲▼ / [Return] to submit\")}\\n`\n\n return select({\n message: colors.reset(message),\n instructions,\n theme: {\n icon: {\n cursor: colors.cyan(\"❯\"),\n },\n prefix: {\n done: colors.cyan(\"✔\"),\n idle: \"?\",\n },\n },\n choices,\n })\n}\n\n/**\n * Creates a new project based on the specified framework\n */\nexport async function createProject(options: ProjectOptions) {\n const normalizedOptions = {\n srcDir: false,\n reactCompiler: false,\n ...options,\n }\n\n let framework: Framework =\n normalizedOptions.framework &&\n FRAMEWORKS[normalizedOptions.framework as Framework]\n ? (normalizedOptions.framework as Framework)\n : \"next\"\n\n const nextVersion = \"latest\"\n\n // Only prompt for framework if not already specified\n if (!normalizedOptions.framework && !normalizedOptions.defaults) {\n const frameworkPromptMessage = `The path ${colors.cyan(normalizedOptions.cwd)} does not contain a package.json file. Would you like to start a new project?`\n\n const selectedFramework = await createThemedSelect(frameworkPromptMessage, [\n { name: \"Next.js\", value: \"next\" },\n { name: \"Vite + React + TypeScript\", value: \"vite\" },\n // { name: 'Next.js (Monorepo)', value: 'next-monorepo' }\n ])\n\n framework = selectedFramework as Framework\n\n // Add spacing after framework selection\n logger.log(\"\")\n }\n\n const projectName =\n normalizedOptions.name ??\n (normalizedOptions.defaults\n ? \"my-app\"\n : await createThemedInput(\"What is your project named?\", \"my-app\"))\n\n // Get the package manager for the project\n const packageManager = await getPackageManager(normalizedOptions.cwd, {\n withFallback: true,\n })\n\n const projectPath = path.join(normalizedOptions.cwd, projectName)\n\n // Validate path is writable\n await validateProjectPath(normalizedOptions.cwd, projectName)\n\n // Create the project based on framework\n if (framework === FRAMEWORKS.next) {\n await createNextProject(projectPath, {\n version: nextVersion,\n cwd: normalizedOptions.cwd,\n packageManager,\n srcDir: !!normalizedOptions.srcDir,\n reactCompiler: !!normalizedOptions.reactCompiler,\n })\n } else if (framework === FRAMEWORKS.vite) {\n await createViteProject(projectPath, {\n cwd: normalizedOptions.cwd,\n packageManager,\n projectName,\n })\n } else if (framework === FRAMEWORKS[\"next-monorepo\"]) {\n await createMonorepoProject(projectPath, {\n packageManager,\n })\n }\n\n return {\n projectPath,\n projectName,\n framework,\n }\n}\n\n/**\n * Validates that the project path is writable and doesn't already exist\n */\nasync function validateProjectPath(cwd: string, projectName: string) {\n try {\n await fs.access(cwd, fs.constants.W_OK)\n } catch {\n throw new Error(\n `Cannot create a project in ${cwd}. Check that the directory exists and is writable.`\n )\n }\n\n if (fs.existsSync(path.resolve(cwd, projectName, \"package.json\"))) {\n throw new Error(\n `A project named ${projectName} already exists in ${cwd}. Choose another name.`\n )\n }\n}\n\n/**\n * Creates a new Next.js project\n */\nasync function createNextProject(\n projectPath: string,\n options: CreateNextOptions\n) {\n const createSpinner = spinner(\n \"Creating a new Next.js project. This may take a few minutes.\"\n ).start()\n\n const args = [\n // The empty starter builds without fetching Google Fonts for its home page.\n \"--empty\",\n \"--tailwind\",\n \"--eslint\",\n \"--typescript\",\n \"--app\",\n options.srcDir ? \"--src-dir\" : \"--no-src-dir\",\n \"--no-import-alias\",\n options.reactCompiler ? \"--react-compiler\" : \"--no-react-compiler\",\n `--use-${options.packageManager}`,\n ]\n\n // Add turbopack for Next.js 15+ or canary/latest\n if (\n options.version.startsWith(\"15\") ||\n options.version.startsWith(\"latest\") ||\n options.version.startsWith(\"canary\")\n ) {\n args.push(\"--turbopack\")\n }\n\n try {\n await execa(\n \"npx\",\n [\n \"--yes\",\n `--package=create-next-app@${options.version}`,\n \"--\",\n \"create-next-app\",\n projectPath,\n \"--silent\",\n ...args,\n ],\n { cwd: options.cwd }\n )\n\n if (options.packageManager === \"pnpm\") {\n await configureNextPnpmBuilds(projectPath)\n }\n await updateReadmeFile(projectPath)\n\n createSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Next.js project.\")\n throw error\n }\n}\n\n/**\n * Creates a new Vite + React + TypeScript project\n */\nasync function createViteProject(\n projectPath: string,\n options: CreateViteOptions\n) {\n const createSpinner = spinner(\n `Creating a new Vite + React + TypeScript project. This may take a few minutes.`\n ).start()\n\n try {\n await execa(\n \"npm\",\n [\n \"create\",\n \"vite@latest\",\n options.projectName,\n \"--\",\n \"--template\",\n \"react-ts\",\n ],\n { cwd: options.cwd }\n )\n\n if (options.packageManager === \"pnpm\")\n await configureVitePnpmBuilds(projectPath)\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n })\n\n await setupViteTsConfig(projectPath, options.packageManager)\n\n await updateReadmeFile(projectPath)\n\n createSpinner.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Vite project.\")\n handleError(error)\n }\n}\n\n/**\n * Configures TypeScript and path aliases for a Vite project\n */\nasync function setupViteTsConfig(projectPath: string, packageManager: string) {\n try {\n await setupTsConfigPathAliases(projectPath)\n await setupViteConfigPathAliases(projectPath)\n await installTypesNode(projectPath, packageManager)\n } catch (error) {\n logger.warn(\n \"Failed to set up TypeScript path aliases, but project creation succeeded\"\n )\n }\n}\n\n/**\n * Installs @types/node as a development dependency\n */\nasync function installTypesNode(projectPath: string, packageManager: string) {\n try {\n const devFlag = packageManager === \"npm\" ? \"--save-dev\" : \"-D\"\n\n await execa(\n packageManager,\n [packageManager === \"npm\" ? \"install\" : \"add\", devFlag, \"@types/node\"],\n { cwd: projectPath }\n )\n } catch (error) {\n logger.warn(\"Failed to install @types/node, but project creation succeeded\")\n }\n}\n\n/**\n * Sets up TypeScript configuration files with path aliases\n */\nasync function setupTsConfigPathAliases(projectPath: string) {\n const addAliasToTsConfig = async (tsconfigFile: string) => {\n const tsconfigPath = path.join(projectPath, tsconfigFile)\n if (!(await fs.pathExists(tsconfigPath))) return\n\n const jsonContent = await fs.readFile(tsconfigPath, \"utf-8\")\n const jsonObj = parseJsonc(jsonContent)\n\n jsonObj.compilerOptions = {\n ...jsonObj.compilerOptions,\n paths: {\n ...(jsonObj.compilerOptions?.paths || {}),\n \"@/*\": [\"./src/*\"],\n },\n }\n\n const updatedJson = JSON.stringify(jsonObj, null, 2)\n await fs.writeFile(tsconfigPath, updatedJson)\n }\n\n await addAliasToTsConfig(\"tsconfig.json\")\n await addAliasToTsConfig(\"tsconfig.app.json\")\n}\n\n/**\n * Sets up Vite configuration with path aliases\n */\nasync function setupViteConfigPathAliases(projectPath: string) {\n const viteConfigPath = path.join(projectPath, \"vite.config.ts\")\n const viteConfigContent = await fs.readFile(viteConfigPath, \"utf-8\")\n\n const updatedViteConfig = viteConfigContent\n .replace(\n \"import { defineConfig } from 'vite'\",\n \"import { defineConfig } from 'vite'\\nimport path from 'path'\"\n )\n .replace(\n \"plugins: [react()]\",\n `plugins: [react()],\n resolve: {\n alias: {\n '@': path.resolve(__dirname, './src')\n }\n }`\n )\n\n await fs.writeFile(viteConfigPath, updatedViteConfig)\n}\n\n/**\n * Creates a new Next.js monorepo project\n */\nasync function createMonorepoProject(\n projectPath: string,\n options: CreateMonorepoOptions\n) {\n const createSpinner = spinner(\n `Creating a new Next.js monorepo. This may take a few minutes.`\n ).start()\n\n try {\n await downloadAndExtractFramework(projectPath)\n\n // Run install\n await execa(options.packageManager, [\"install\"], {\n cwd: projectPath,\n })\n\n // Initialize git repository\n await initializeGitRepository(projectPath)\n\n createSpinner?.stopAndPersist({\n symbol: colors.cyan(\"✔\"),\n text: `Created a new Next.js monorepo at ${colors.cyan(projectPath)}`,\n })\n } catch (error) {\n createSpinner?.fail(\"Something went wrong creating a new Next.js monorepo.\")\n handleError(error)\n }\n}\n\n/**\n * Downloads and extracts the monorepo framework\n */\nasync function downloadAndExtractFramework(projectPath: string) {\n // Create temporary directory\n const frameworkPath = path.join(os.tmpdir(), `tiptap-framework-${Date.now()}`)\n await fs.ensureDir(frameworkPath)\n\n // Download framework\n const response = await fetch(MONOREPO_FRAMEWORK_URL)\n if (!response.ok) {\n throw new Error(\n \"The starter project could not be downloaded. Please check your connection and try again.\"\n )\n }\n\n // Write the tar file\n const tarPath = path.resolve(frameworkPath, \"framework.tar.gz\")\n await fs.writeFile(tarPath, Buffer.from(await response.arrayBuffer()))\n\n // Extract framework\n await execa(\"tar\", [\n \"-xzf\",\n tarPath,\n \"-C\",\n frameworkPath,\n \"--strip-components=2\",\n \"ui-main/templates/monorepo-next\",\n ])\n\n // Move to project path and cleanup\n const extractedPath = path.resolve(frameworkPath, \"monorepo-next\")\n await fs.move(extractedPath, projectPath)\n await fs.remove(frameworkPath)\n}\n\n/**\n * Initializes a git repository in the project directory\n */\nasync function initializeGitRepository(projectPath: string) {\n const cwd = process.cwd()\n\n try {\n await execa(\"git\", [\"--version\"], { cwd: projectPath })\n await execa(\"git\", [\"init\"], { cwd: projectPath })\n await execa(\"git\", [\"add\", \"-A\"], { cwd: projectPath })\n await execa(\"git\", [\"commit\", \"-m\", \"Initial commit\"], {\n cwd: projectPath,\n })\n await execa(\"cd\", [cwd])\n } catch (error) {\n logger.warn(\n \"Failed to initialize git repository, but project creation succeeded\"\n )\n }\n}\n\nconst simpleEditorTemplateDocs = `# Simple template\n\nIntegrate the Tiptap open source editor with UI components and open source extensions.\n\nThe Simple Editor Template is a fully working setup for the Tiptap editor. It includes commonly used open source extensions and UI components, all MIT licensed and ready to customize.\n\n**Quick Links:**\n- [View in Full Screen](http://template.tiptap.dev/preview/templates/simple)\n- [GitHub Repository](https://github.com/ueberdosis/tiptap-ui-components/tree/main/apps/web/src/components/tiptap-templates/simple)\n\n## Installation\n\nAdd the Simple Editor Template to your project using the Tiptap CLI:\n\n\\`\\`\\`bash\nnpx @tiptap/cli add simple-editor\n\\`\\`\\`\n\n## Style\n\n> **Missing styles?** If you haven't added the styles yet, make sure to [follow the style setup guide](/ui-components/getting-started/style) to ensure your editor and components render correctly.\n\n## Usage\n\nAfter installation, use the SimpleEditor component in your React or Next.js project:\n\n\\`\\`\\`jsx\nimport { SimpleEditor } from '@/components/tiptap-templates/simple/simple-editor'\n\nexport default function App() {\n return <SimpleEditor />\n}\n\\`\\`\\`\n\n## Features\n\nA fully responsive rich text editor with built-in support for common formatting and layout tools. All components are open source and easy to extend.\n\n- **Responsive design**: Mobile-friendly by default\n- **Dark and light mode**: Supported out-of-the-box\n- **Formatting**: Bold, Italic, Underline\n- **Lists**: Bullet, Ordered, Checkboxes\n- **Text alignment**: Left, Center, Right, Justified\n- **Headings**: Multiple levels via dropdown\n- **Image upload**\n- **Link editing:** UI for adding and editing links\n- **Undo / Redo:** History management\n\n### Used reference components\n\n#### Hooks\n\n- \\`use-mobile\\`\n- \\`use-window-size\\`\n\n#### Icons\n\n- \\`arrow-left-icon\\`\n- \\`highlighter-icon\\`\n- \\`link-icon\\`\n- \\`moon-star-icon\\`\n- \\`sun-icon\\`\n\n#### Extensions\n\n- \\`selection-extension\\`\n- \\`link-extension\\`\n- \\`trailing-node-extension\\`\n\n#### Lib\n\n- \\`tiptap-utils\\`\n\n#### UI Components\n\n- \\`blockquote-button\\`\n- \\`code-block-button\\`\n- \\`color-highlight-button\\`\n- \\`color-highlight-popover\\`\n- \\`heading-button\\`\n- \\`heading-dropdown-menu\\`\n- \\`image-upload-button\\`\n- \\`link-popover\\`\n- \\`list-button\\`\n- \\`list-dropdown-menu\\`\n- \\`mark-button\\`\n- \\`text-align-button\\`\n- \\`undo-redo-button\\`\n\n#### Node Components\n\n- \\`code-block-node\\`\n- \\`image-node\\`\n- \\`image-upload-node\\`\n- \\`list-node\\`\n- \\`paragraph-node\\`\n\n#### Primitives\n\n- \\`button\\`\n- \\`spacer\\`\n- \\`toolbar\\`\n\n## License\n\nThe Simple Editor Template and all included components are MIT licensed. You're free to use, modify, and extend the code as needed.\n\n## Future compatibility\n\nYou can extend this template with additional features as your needs grow.\n\nPaid Tiptap Cloud features will have matching UI components that integrate just as easily! No rework needed.`\n\nconst notionLikeEditorDocs = `# Notion-like Editor\n\nA Notion-style Tiptap editor with collaboration, AI, and rich UI components. Fully customizable and easy to integrate.\n\nThe **Notion-like Editor Template** is a fully featured block-based editor that replicates the familiar Notion experience. It supports collaboration, AI assistance, emoji, drag & drop, advanced formatting—and it's fully customizable.\n\n## Installation\n\nInstall the Notion-like editor with the Tiptap CLI:\n\n\\`\\`\\`bash\nnpx @tiptap/cli add notion-like-editor\n\\`\\`\\`\n\n## Styling\n\n> **Note:** If the editor doesn't look right, make sure you've followed the [style setup guide](/ui-components/getting-started/style).\n\n## Configuration\n\nBefore running the app, configure the required constants inside \\`tiptap-collab-utils.ts\\`. This is necessary to enable features like AI or collaboration.\n\n### Environment Variables\n\nProvide values for the following environment variables:\n\n- \\`TIPTAP_COLLAB_DOC_PREFIX\\` - Prefix for identifying collaborative documents\n- \\`TIPTAP_COLLAB_APP_ID\\` - Your Document Server App ID\n- \\`TIPTAP_COLLAB_TOKEN\\` - JWT token for accessing Collaboration services\n- \\`TIPTAP_AI_APP_ID\\` - Your AI App ID\n- \\`TIPTAP_AI_TOKEN\\` - JWT token for accessing AI services\n\nThe above environment variables should be available in the client-side. Depending on your framework, use the following prefixes to expose them to the client:\n\n- **[Next.js](/ui-components/install/next)**: \\`NEXT_PUBLIC_\\`. For example, \\`NEXT_PUBLIC_TIPTAP_COLLAB_DOC_PREFIX\\`.\n- **[Vite + React](/ui-components/install/vite)**: \\`VITE_\\`. For example, \\`VITE_TIPTAP_COLLAB_DOC_PREFIX\\`.\n- **Other frameworks**: Follow the specific rules of your framework, and define the variables in the \\`tiptap-collab-utils.ts\\` file.\n\n### JWT Authentication\n\nCollaboration and AI features require a valid server-generated JWT token passed to the editor. See the \\`fetchCollabToken\\` function in \\`tiptap-collab-utils.ts\\` for an example.\n\n> See the full guide on JWT authentication at [https://tiptap.dev/docs/guides/authentication](https://tiptap.dev/docs/guides/authentication).\n\n> **Important:** To get started quickly, you can use the example JWT tokens from your Tiptap Cloud account and store them in the \\`TIPTAP_COLLAB_TOKEN\\` and \\`TIPTAP_AI_TOKEN\\` environment variables. However, example JWT tokens are valid for a short time and should not be used in production. In production, implement an API endpoint that generates JWTs on the server side.\n\n### \\`room\\` prop\n\nUse the \\`room\\` prop to distinguish collaborative documents. Each session should use a unique room ID.\n\n## Usage\n\nImport and render the \\`NotionEditor\\` component in your React app:\n\n\\`\\`\\`tsx\nimport { NotionEditor } from '@/components/tiptap-templates/notion/notion-like-editor'\n\nexport default function App() {\n return <NotionEditor room=\"my-document-room\" placeholder=\"Start writing...\" />\n}\n\\`\\`\\`\n\n## Features\n\nThe template includes all the essentials of a modern Notion-style editor:\n\n- **Real-time collaboration**: Live cursors and user presence\n- **AI assistance**: Inline AI tools for writing and editing\n- **Responsive design**: Mobile-ready UI with adaptive toolbars\n- **Dark/light mode**: Fully themed out of the box\n- **Slash commands**: \\`/\\` menu for quick formatting\n- **Floating toolbar**: Context-aware formatting\n- **Drag and drop**: Block-level reordering\n- **Emoji support**: GitHub-style emoji picker\n- **Mentions**: \\`@user\\` autocomplete\n- **Rich formatting**:\n - Bold, italic, underline, strikethrough\n - Highlight and color\n - Superscript / subscript\n - Syntax-highlighted code blocks\n- **Block types**:\n - Headings, lists, blockquotes, dividers, math\n- **Media support**: Drag & drop image upload\n- **Link management**: With inline previews\n- **Text alignment**: Left, center, right, justified\n- **Undo/Redo**: Full editing history\n- **Context menus**: Right-click enhancements\n\n## Component Breakdown\n\n### Hooks\n\n- \\`use-mobile\\`\n- \\`use-window-size\\`\n- \\`use-ui-editor-state\\`\n\n### Icons\n\n- \\`arrow-left-icon\\`\n- \\`chevron-right-icon\\`\n- \\`highlighter-icon\\`\n- \\`link-icon\\`\n- \\`more-vertical-icon\\`\n\n### Tiptap Extensions\n\n- \\`collaboration\\`, \\`collaboration-cursor\\`\n- \\`selection-extension\\`\n- \\`link-extension\\`\n- \\`trailing-node-extension\\`\n- \\`ai-extension\\`\n- \\`emoji-extension\\`\n- \\`mention-extension\\`\n- \\`mathematics-extension\\`\n- \\`unique-id-extension\\`\n\n### Libs\n\n- \\`tiptap-utils\\`\n- \\`tiptap-collab-utils\\`\n\n### UI Components\n\n- \\`ai-menu\\`\n- \\`blockquote-button\\`\n- \\`code-block-button\\`\n- \\`color-highlight-button\\`, \\`color-highlight-popover\\`\n- \\`drag-context-menu\\`\n- \\`emoji-dropdown-menu\\`\n- \\`heading-button\\`, \\`heading-dropdown-menu\\`\n- \\`image-upload-button\\`\n- \\`link-popover\\`\n- \\`list-button\\`, \\`list-dropdown-menu\\`\n- \\`mark-button\\`\n- \\`mention-dropdown-menu\\`\n- \\`slash-dropdown-menu\\`\n- \\`text-align-button\\`\n- \\`turn-into-dropdown\\`\n- \\`undo-redo-button\\`\n\n### Nodes\n\n- \\`code-block-node\\`\n- \\`image-node\\`, \\`image-upload-node\\`\n- \\`list-node\\`\n- \\`paragraph-node\\`\n\n### Notion-specific\n\n- \\`notion-like-editor-header\\`\n- \\`notion-toolbar-floating\\`\n- \\`mobile-toolbar\\`\n- \\`collaboration-users\\`\n- \\`theme-toggle\\`\n\n### Primitives\n\n- \\`button\\`, \\`button-group\\`\n- \\`dropdown-menu\\`\n- \\`separator\\`, \\`spacer\\`, \\`toolbar\\`\n\n### Contexts\n\n- \\`user-context\\`\n- \\`collab-context\\`\n\n## Collaboration\n\nTo use collaboration:\n\n1. Pass a unique \\`room\\` ID to \\`NotionEditor\\`\n2. Enable JWT auth for each user session\n3. User presence and cursors are handled automatically\n4. Operational transformation handles concurrent edits\n5. Sync and save are managed out-of-the-box\n\n\\`\\`\\`tsx\n<NotionEditor room=\"team-notes\" placeholder=\"Share your ideas...\" />\n\\`\\`\\`\n\n## AI Integration\n\nThe built-in AI tools let you:\n\n- **Generate content** from prompts\n- **Improve** existing text\n- **Get smart completions** based on context\n\n> **AI Configuration:** Make sure to configure your AI provider. Check the [AI Generation extension docs](/content-ai/capabilities/generation/overview) for setup steps.\n\n## Extendability\n\nThis template is designed to grow with your needs. New Tiptap Cloud features will be seamlessly compatible with the same UI system—no rewrites required.`\n\nasync function updateReadmeFile(projectPath: string, templateName?: string) {\n const readmePath = path.join(projectPath, \"README.md\")\n\n const templateContent = {\n \"simple-editor\": simpleEditorTemplateDocs,\n \"notion-like-editor\": notionLikeEditorDocs,\n } as const\n\n type TemplateKey = keyof typeof templateContent\n\n const readmeContent =\n templateName && templateName in templateContent\n ? templateContent[templateName as TemplateKey]\n : \"\"\n\n try {\n if (readmeContent.trim()) {\n await fs.writeFile(readmePath, readmeContent, \"utf-8\")\n }\n } catch {\n /* empty */\n }\n}\n","import path from \"node:path\"\nimport fs from \"fs-extra\"\nimport { execa } from \"execa\"\nimport { isMap, isSeq, parseDocument } from \"yaml\"\n\nconst watcher = \"@parcel/watcher\"\n\nfunction coversWatcher(rule: string) {\n return (\n rule === watcher || rule.startsWith(`${watcher}@`) || rule.includes(\"*\")\n )\n}\n\nexport async function configureNextPnpmBuilds(projectPath: string) {\n // create-next-app writes the build policy for pnpm 10 and later.\n const file = path.join(projectPath, \"pnpm-workspace.yaml\")\n if (!(await fs.pathExists(file))) return\n\n const policy = parseDocument(await fs.readFile(file, \"utf8\"))\n if (\n policy.errors.length ||\n [\n \"dangerouslyAllowAllBuilds\",\n \"neverBuiltDependencies\",\n \"onlyBuiltDependencies\",\n \"onlyBuiltDependenciesFile\",\n \"permissions\",\n ].some((key) => policy.has(key))\n ) {\n return\n }\n\n // Next compiles Sass without running the optional watcher's install script.\n const builds = policy.get(\"allowBuilds\")\n const ignored = policy.get(\"ignoredBuiltDependencies\")\n if (isMap(builds) && !ignored) {\n if (builds.items.some(({ key }) => coversWatcher(String(key)))) return\n builds.set(watcher, false)\n } else if (!builds && isSeq(ignored)) {\n if (ignored.items.some((item) => coversWatcher(String(item)))) return\n ignored.add(watcher)\n } else {\n return\n }\n\n await fs.writeFile(file, policy.toString())\n}\n\nexport async function configureVitePnpmBuilds(projectPath: string) {\n const filename = \"pnpm-workspace.yaml\"\n const file = path.join(projectPath, filename)\n if (await fs.pathExists(file)) return configureNextPnpmBuilds(projectPath)\n\n for (let dir = path.dirname(projectPath); ; dir = path.dirname(dir)) {\n if (await fs.pathExists(path.join(dir, filename))) return\n if (dir === path.dirname(dir)) break\n }\n\n const { stdout } = await execa(\"pnpm\", [\"--version\"], { cwd: projectPath })\n if (Number.parseInt(stdout, 10) >= 11) {\n // pnpm 11 requires a decision about the optional Sass watcher at install time.\n await fs.writeFile(file, `allowBuilds:\\n '${watcher}': false\\n`, {\n flag: \"wx\",\n })\n }\n}\n","#!/usr/bin/env node\nimport { add } from \"@/src/commands/add\"\nimport { info } from \"@/src/commands/info\"\nimport { search } from \"@/src/commands/search\"\nimport { view } from \"@/src/commands/view\"\nimport { init } from \"@/src/commands/init\"\nimport { login, logout, status, license } from \"@/src/commands/auth\"\nimport { Command } from \"commander\"\n\nimport packageJson from \"../package.json\"\n\nprocess.on(\"SIGINT\", () => process.exit(0))\nprocess.on(\"SIGTERM\", () => process.exit(0))\n\nasync function main() {\n const program = new Command()\n .name(\"tiptap\")\n .description(\"add components and dependencies to your project\")\n .version(\n packageJson.version || \"1.0.0\",\n \"-v, --version\",\n \"display the CLI version number\"\n )\n\n program\n .addCommand(init)\n .addCommand(add)\n .addCommand(info)\n .addCommand(search)\n .addCommand(view)\n .addCommand(login)\n .addCommand(logout)\n .addCommand(status)\n .addCommand(license)\n\n await program.parseAsync()\n}\n\nmain().catch((error) => {\n console.error(error instanceof Error ? error.message : String(error))\n process.exitCode = 1\n})\n"],"mappings":";AAAA,OAAOA,OAAU,OACjB,OAAS,WAAAC,OAAe,YACxB,OAAS,KAAAC,MAAS,MCFlB,OACE,gBAAAC,GACA,YAAAC,GACA,eAAAC,GACA,aAAAC,GACA,iBAAAC,GACA,UAAAC,GACA,WAAAC,GACA,aAAAC,GACA,kBAAAC,GACA,cAAAC,GACA,WAAAC,GACA,aAAAC,GACA,eAAAC,GACA,aAAAC,GACA,mBAAAC,GACA,aAAAC,OAGK,iBAEP,OAAOC,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AIC,GAAQ,EACzB,KAAK,QAAQ,EACb,YAAY,iDAAiD,EAC7D,QACCC,GAAY,SAAW,QACvB,gBACA,gCACF,EAEFF,EACG,WAAWG,EAAI,EACf,WAAWC,EAAG,EACd,WAAWC,EAAI,EACf,WAAWC,EAAM,EACjB,WAAWC,EAAI,EACf,WAAWC,EAAK,EAChB,WAAWC,EAAM,EACjB,WAAWC,EAAM,EACjB,WAAWC,EAAO,EAErB,MAAMX,EAAQ,WAAW,CAC3B,CAEAD,GAAK,EAAE,MAAOa,GAAU,CACtB,QAAQ,MAAMA,aAAiB,MAAQA,EAAM,QAAU,OAAOA,CAAK,CAAC,EACpE,QAAQ,SAAW,CACrB,CAAC","names":["path","Command","z","createPrompt","useState","useKeypress","usePrefix","usePagination","useRef","useMemo","useEffect","isBackspaceKey","isEnterKey","isUpKey","isDownKey","isNumberKey","Separator","ValidationError","makeTheme","colors","figures","ansiEscapes","selectTheme","text","isSelectable","item","normalizeChoices","choices","choice","name","normalizedChoice","formatMultilineChoice","firstLinePrefix","firstLine","remainingLines","continuationPrefix","stripAnsi","line","str","select_default","config","done","loop","pageSize","instructions","firstRender","theme","status","setStatus","prefix","searchTimeoutRef","showHelpTip","setShowHelpTip","items","bounds","first","last","defaultItemIndex","active","setActive","selectedChoice","key","rl","offset","next","position","searchTerm","matchIndex","message","helpTipTop","helpTipBottom","page","isActive","index","indexLabel","disabledLabel","color","x","cursor","choiceDescription","Separator","input","confirm","checkbox","path","statSync","path","createMatchPath","resolveImport","importPath","config","matchBaseUrl","cosmiconfig","fg","loadConfig","z","path","FRAMEWORKS","path","fs","getPackageInfo","cwd","shouldThrow","packageJsonPath","getInstalledPackageVersion","name","dir","manifest","error","fg","fs","PROJECT_SHARED_IGNORE","getNextAppDir","cwd","dir","fs","path","getProjectInfo","options","configFiles","isSrcDir","isTsx","aliasPrefix","packageJson","fg","isTypeScriptProject","getTsConfigAliasPrefix","getPackageInfo","type","FRAMEWORKS","file","dep","tsConfig","readPathConfig","alias","paths","getProjectConfig","defaultProjectInfo","existingConfig","projectInfo","getConfig","config","resolveConfigPaths","DEFAULT_COMPONENTS","DEFAULT_CONTEXTS","DEFAULT_HOOKS","DEFAULT_TIPTAP_ICONS","DEFAULT_LIB","DEFAULT_TIPTAP_EXTENSIONS","DEFAULT_TIPTAP_NODES","DEFAULT_TIPTAP_UI","DEFAULT_TIPTAP_UI_PRIMITIVES","DEFAULT_TIPTAP_UI_UTILS","DEFAULT_STYLES","explorer","cosmiconfig","rawConfigSchema","z","configSchema","workspaceConfigSchema","readPathConfig","cwd","loadConfig","error","getConfig","pathOverride","options","res","projectInfo","getProjectInfo","defaultAliases","applyAliasPrefix","aliases","prefix","key","value","loaded","paths","componentKey","rootKey","targets","target","defaults","config","resolveConfigPaths","path","resolvedAliases","componentsFallback","explicitAliases","tsConfig","directory","alias","explicit","hasChildMapping","exact","resolveImport","statSync","child","components","resolvedPaths","subdirectory","fallback","resolvedPathOverride","getWorkspaceConfig","isAliasKey","resolvedPath","packageRoot","findPackageRoot","result","commonRoot","findCommonRoot","relativePath","matchingPackageRoot","fg","pkgPath","pkgDir","parts1","parts2","commonParts","chalk","colors","join","args","logger","colors","fs","preFlightAdd","options","projectInfo","errors","fs","path","config","getConfig","error","logger","colors","path","fetch","HttpsProxyAgent","ora","tiptapSpinner","colors","spinner","text","options","ora","Conf","fs","expiresAt","loginDate","expiration","TokenStorage","logger","prefix","error","token","userInfo","e","expiry","planName","plans","tokenStorage","TokenStorage","logger","fs","path","os","execa","yaml","mapWorkspaces","TIPTAP_REGISTRY","AUTH_TOKEN_KEY","TIPTAP_PRO_REGISTRY_KEY","UnsafeConfigError","getRegistryConfigDirectory","cwd","manager","start","path","stdout","stderr","exitCode","execa","bin","modules","npmProject","dir","fs","manifest","hasManifest","pkg","patterns","members","assertRegularFileOrMissing","file","error","protectConfigFile","filename","options","repository","inGit","tracked","ignored","ignorePath","content","rule","saveAuthToken","token","packageManager","saveYarnToken","saveToNpmrc","logger","writePrivateConfig","isBerry","saveYarnBerryToken","yarnrcPath","yamlObj","yarnrcContent","npmScopes","previousScope","npmrcPath","npmrcContent","lines","processedKeys","parseNpmrc","contentLines","line","trimmedLine","index","key","getAuthToken","projectToken","checkProjectNpmrc","getNpmAuthToken","globalAuthToken","checkGlobalNpmrc","checkGlobalYarnrc","projectNpmrcPath","extractAuthToken","globalNpmrcPath","os","m","configString","z","registryItemTypeSchema","PAID_PLANS","FREE_PLANS","ALL_PLANS","planSchema","featureIdSchema","name","registryModulePathSchema","path","part","reservedBindings","exportName","featureText","value","featureItems","registryFeatureSchema","registryFeatureIdentitySchema","registryFeatureCatalogSchema","registryItemFileSchema","registryItemSchema","registrySourceItemSchema","registrySchema","registryIndexSchema","HttpsProxyAgent","fetch","z","TIPTAP_ORIGIN","getRegistryBaseUrl","base","url","agent","HttpsProxyAgent","getRegistryIndex","result","fetchComponent","registryIndexSchema","getRegistryFeatures","signal","data","response","fetch","reason","error","catalog","registryFeatureCatalogSchema","entries","entry","feature","registryFeatureSchema","identity","registryFeatureIdentitySchema","createRegistryError","authenticated","urlInfo","colors","tokenStorage","componentHeaders","headers","token","path","getRegistryUrl","requireNames","requested","received","found","missing","name","fetchRegistryBatch","componentNames","items","z","item","fetchRegistry","paths","uniqueNames","results","offset","batch","fetchRegistryDependencies","components","names","getResolvedRegistryItems","expected","registrySourceItemSchema","isUrl","componentName","filterDevDependenciesByFramework","devDependencies","framework","depsArray","stringDeps","dep","hasSass","hasSassEmbedded","filteredDeps","prefersEmbedded","FRAMEWORKS","prefersRegular","AUTH_API_URL","TIPTAP_ORIGIN","httpAgent","HttpsProxyAgent","getApiErrorMessage","response","payload","getAuthErrorMessage","apiErrorMessage","getPlansErrorMessage","authenticateUser","email","password","packageManager","writeConfig","registryOnly","cwd","loginSpinner","spinner","tokens","requestAuthTokens","tokenStorage","plansResponse","fetch","userPlans","plan","saveAuthToken","colors","error","data","checkAuthStatus","bearerToken","userInfo","expiration","logger","logoutUser","detect","fs","path","getPackageManagerInfo","targetDir","withFallback","name","launcher","getPackageManager","options","getPackageRunner","cwd","packageManager","isBunProject","hasBunLock","hasBunfig","Command","execa","z","confirm","input","passwordPrompt","z","handleError","error","logger","z","key","value","colors","authOptionsSchema","z","createThemedInput","message","options","input","colors","value","createThemedPassword","passwordPrompt","createThemedConfirm","defaultValue","confirm","getConfigFileName","packageManager","displayTokenInstructions","cwd","token","logger","checkYarnVersion","execa","handleLogin","email","password","writeConfig","showMessage","getPackageManager","getRegistryConfigDirectory","configFileName","result","authenticateUser","errorMessage","handleStatusCheck","status","checkAuthStatus","expiryDate","now","daysUntilExpiry","getAuthToken","tokenStorage","login","Command","opts","error","handleError","logout","logoutSpinner","spinner","logoutUser","handleLicenseInfo","hasAccepted","userInfo","handleLicenseForgetMe","license","hasPaidComponents","components","component","plan","PAID_PLANS","assertCanPreviewPaidComponents","items","tokenStorage","promptLicenseAcceptance","selectedComponents","logger","colors","createThemedConfirm","ensureAuthForPaidComponents","cwd","interactive","authStatus","checkAuthStatus","packageManager","getPackageManager","createNpmrcConfiguration","handleLogin","error","configSpinner","spinner","authToken","saveAuthToken","process","getTerminalWidth","canPrompt","createBox","title","content","options","borderColor","padding","topLeft","topRight","bottomLeft","bottomRight","horizontal","vertical","terminalWidth","boxWidth","colorFn","colors","topBorder","bottomBorder","sideBorder","lines","titlePadding","stripAnsi","titleLine","line","strippedLength","paddedLine","createWelcomeBanner","title","subtitle","content","createBox","createWarningBox","title","content","createBox","logLines","lines","line","logger","stripAnsi","str","clearTerminal","process","createSpacedDivider","width","getTerminalWidth","colors","existsSync","parseCss","parseScss","fs","path","path","registryRoots","getRegistryPath","filePath","normalized","root","segments","getRegistryImportDestination","source","config","template","path","registryPath","resolveOverrideImport","outputFilename","metadata","destination","candidates","alias","targets","target","absoluteTarget","star","prefix","suffix","match","specifier","b","resolveImport","relative","randomUUID","transformImport","sourceFile","config","packageManager","outputFilename","importDeclarations","importDeclaration","originalSpecifier","moduleSpecifier","resolveOverrideImport","updateImportAliases","isBunProject","alias","transformFromAstSync","parse","transformTypescript","recast","PARSE_OPTIONS","transformJsx","sourceFile","config","output","ast","code","result","SyntaxKind","transformRsc","sourceFile","config","first","Node","SyntaxKind","DEFAULT_EXCLUSIONS","shouldExcludeComponent","componentName","rules","filePath","rule","f","name","ruleName","getFrameworkEnvVarName","constantName","framework","frameworkName","FRAMEWORKS","stripFrameworkPrefix","varName","transformEnvironmentVariables","sourceFile","projectInfo","nodesToTransform","binaryExpressions","SyntaxKind","binaryExpr","leftText","match","transformedEnvVar","rightSide","newExpression","callExpressions","callExpr","expressionText","args","argText","newArgText","envVarsToTransform","frameworkEnvVarName","newCallExpr","propertyAccessExpressions","propAccess","propAccessText","node","newText","error","transformRemoveComponents","config","exclusionRules","nodesToModify","importDeclarations","importDeclaration","moduleSpecifier","defaultImport","namedImports","excludedImports","namedImport","excludedImport","exportDeclarations","exportDeclaration","namedExports","excludedExports","namedExport","excludedExport","variableStatements","variableStatement","declarations","excludedDeclarations","declaration","functionDeclarations","functionDeclaration","functionName","interfaceDeclarations","interfaceDeclaration","interfaceName","typeAliases","typeAlias","typeName","propertySignatures","propertySignature","propName","jsxElements","jsxElement","tagName","jsxSelfClosingElements","jsxSelfClosingElement","propertyAssignments","propertyAssignment","propertyName","jsxAttributes","jsxAttribute","attributeName","parameters","parameter","parameterName","paramList","Node","allParams","index","prev","next","i","arg","prevSibling","nextSibling","bindingElements","bindingElement","bindingName","bindingPattern","allBindings","identifiers","identifier","identifierName","parent","parentKind","propAssignment","shorthandPropertyAssignments","shorthandProp","getProjectInfo","a","b","aStart","action","posix","registrySassImporter","files","styles","file","specifier","containingUrl","url","candidates","filename","partial","matches","name","candidate","contents","transformScssToCSS","content","importer","compileString","error","Project","ScriptKind","project","transform","opts","transformers","transformImport","transformRsc","transformRemoveComponents","transformScssToCSS","sourceFile","randomUUID","transformer","transformJsx","confirm","SCSS_DECLARATION_FILE","SCSS_DECLARATION_CONTENT","keepExisting","file","resolveInstallPath","filePath","fs","error","dir","path","parent","isWithin","root","relative","getInstallDestination","config","cwd","aliases","realRoot","realPath","readExistingFile","planFiles","files","project","projectInfo","packageManager","getProjectInfo","getPackageManager","isBun","isBunProject","sassImporter","registrySassImporter","changes","resolveFilePath","before","after","transform","transformImport","transformRsc","transformRemoveComponents","status","getNormalizedFileContent","declaration","checkPlannedDestination","requireExistingFile","applyFiles","options","result","planned","installedContents","keepLocal","confirm","source","dependency","expected","resolveFileTargetDirectory","file","config","override","getNormalizedFileContent","content","resolvePageTarget","target","framework","result","resolveNestedFilePath","filePath","targetDir","registryPath","getRegistryPath","normalizedFilePath","normalizedTargetDir","fileSegments","targetSegments","lastTargetSegment","commonDirIndex","segment","resolveFilePath","options","match","templateName","relativePath","finalPath","path","templateMatch","dataPath","path","getMainCssFilePath","framework","config","frameworkName","cwd","hasSrcDir","stylesInSrc","possiblePaths","FRAMEWORKS","appDir","getNextAppDir","name","path","dir","filePath","existsSync","planStyleImports","styleFiles","planned","styles","file","hostStyle","realPath","getInstallDestination","before","readExistingFile","scss","stylesheet","parseScss","parseCss","error","specifiers","bom","insertion","node","match","imports","style","relative","specifier","alias","aliasTarget","resolveImport","newline","lines","prefix","suffix","after","logAutoImportResult","result","logger","colors","relativePath","os","path","fs","execa","semver","docs","registryLoginCommand","cwd","command","getPackageRunner","path","privatePackage","classifyRoute","value","url","bunUserNpmrc","startDir","home","xdg","selected","homeFile","stdout","execa","version","semver","file","fs","bunRoute","os","configHome","files","configs","bunScope","bunDefault","query","scope","defaultRegistry","npm","npmrcRoutes","expandRegistry","_","wrapped","plain","npmScope","npmDefault","contents","line","match","yarnClassicGlobalNpmrc","nodeDir","prefix","readRegistryRoute","manager","get","args","route","scopedRegistry","ancestors","dir","userconfig","settings","registries","getTiptapRegistryRoute","getPackageManager","getRegistryConfigDirectory","ensureTiptapRegistryAccess","packages","interactive","requested","pkg","directory","token","tokenStorage","saveAuthToken","renewTiptapRegistryAccess","recovery","createThemedConfirm","handleLogin","path","createTwoFilesPatch","Node","Kind","Node","Project","Kind","namedImport","file","module","name","imports","declaration","item","hasStaticOptions","object","keys","property","findRenderedEditor","componentBody","hooks","call","hook","reactImports","importedHook","variable","body","editorContents","element","returned","container","node","importedContent","rendered","attribute","options","extensions","parseEditorSource","source","filename","project","wrapperName","usedBeforeInitialization","name","boundary","visited","reference","statement","node","Node","owner","variable","Kind","initializer","binding","editorComponent","file","wrapperPath","plain","declaration","innerName","inner","fn","rendered","wrappedDeclaration","call","item","wrapper","namedImport","props","parameter","hasReassignedWrapperProp","symbol","ancestor","hasConflictingExtension","path","findEditorOptions","body","editor","findRenderedEditor","options","extensions","kitModule","kit","kitReferences","id","kitCall","kitOptions","hasStaticOptions","hasCompleteWiring","wiring","element","removeNode","source","start","end","lineStart","newline","removeDemoContent","demoImport","content","value","demo","imported","uses","edits","editorComponentName","calls","parseEditorSource","connectCollaboration","original","bom","target","declared","kitReference","undo","editable","shared","removedDemoContent","insert","text","prepend","whitespace","result","edit","a","b","checked","component","checkedBody","wired","path","Node","SymbolFlags","Kind","ts","hasValueExport","file","name","symbol","parseEditorSource","path","item","value","SymbolFlags","decl","Node","ts","connectExtension","source","importPath","exportName","bom","editor","findRenderedEditor","extensions","imports","matching","localName","specifiers","local","registered","el","Kind","id","start","whitespace","separator","wired","originalPosition","before","eol","declaration","result","checked","imported","moduleSpecifier","from","to","relative","editorImportPath","dependency","physical","updateEditor","files","connected","planEditorExtension","integration","cwd","matches","extension","setup","getTemplateDemoImport","template","editor","entries","config","demoPath","demo","file","path","raw","rawEditor","parseEditorSource","imports","declaration","specifier","binding","installed","item","registryImport","resolveOverrideImport","planCollaboration","integration","files","existingTokenRoute","customPagePath","demoImport","cwd","settings","wrapper","token","setup","hasValueExport","source","name","editorComponentName","editorImportPath","connected","connectCollaboration","component","example","wired","createTwoFilesPatch","updateEditor","planNewViteEditorEntry","filePath","realPath","getInstallDestination","before","readExistingFile","symbol","after","moduleSpecifier","semver","editorPackages","editorRange","equivalentVersions","left","right","semver","planDependencies","dependencies","devDependencies","config","subject","cwd","manifest","getPackageInfo","declared","requests","collect","specs","dev","spec","match","name","version","previous","result","needsEditor","coreName","core","installedCore","getInstalledPackageVersion","incompatibleCore","coreRange","existing","isEditor","required","installed","target","wanted","stripVTControlCharacters","fs","path","execa","applyEdits","modify","moveDeclarations","content","moves","undo","from","to","manifest","indent","formattingOptions","name","version","applyEdits","modify","promoteDependencies","cwd","manager","path","original","fs","promoted","execa","error","current","restored","flag","repairError","updateDependencies","dependencies","config","options","promotions","dependenciesSpinner","spinner","packageManager","getPackageManager","colors","execa","updateDevDependencies","devDependencies","config","options","devDependenciesSpinner","spinner","packageManager","getPackageManager","execa","error","colors","rejectedUrl","address","code","packages","expectedName","url","path","name","official","privatePackageRejection","error","streams","value","output","stripVTControlCharacters","lines","index","line","berryPackage","get","rejection","status","yarnAuth","classic","installPlannedPackages","groups","options","interactive","attemptedLogin","group","install","operation","cwd","summary","route","getTiptapRegistryRoute","help","registryLoginCommand","renewTiptapRegistryAccess","updateDependencies","updateDevDependencies","getFileGroups","components","config","project","items","getResolvedRegistryItems","assertCanPreviewPaidComponents","sharedUi","getWorkspaceConfig","byName","item","owners","collect","name","consumer","target","owned","dependency","component","groups","entries","group","filterDevDependenciesByFramework","resolveEditorFile","template","requested","files","declared","registryModulePathSchema","source","file","editor","filePath","path","realPath","getInstallDestination","before","readExistingFile","planFeatures","features","records","requestedEditor","mountViteEntry","overwrite","collaboration","extensionSetup","feature","demoImport","getTemplateDemoImport","conflicts","recipeItems","featureSources","protectedSources","integration","keepExisting","sources","planEditorExtension","customPage","planCollaboration","setup","entry","planNewViteEditorEntry","planComponents","options","registryFeatureSchema","getProjectInfo","setupItems","selected","packages","dependencies","planDependencies","privateNpmPackages","planFiles","previous","styles","planStyleImports","addComponents","progress","spinner","plan","interactive","canPrompt","ensureTiptapRegistryAccess","installPlannedPackages","result","applyFiles","failures","error","path","createTwoFilesPatch","printInstallPreview","plan","cwd","diff","files","file","path","relative","logger","createTwoFilesPatch","group","prefix","specs","name","version","toReadableName","input","word","existsSync","path","getFrameworkEnvPrefix","framework","frameworkName","FRAMEWORKS","detectStyleFileExtension","config","stylesDir","variablesScss","variablesCss","calculateStylesImportPath","stylesInSrc","hasSrcDir","cssFile","importPath","showStylesConfigurationMessage","fileExtension","content","colors","box","createWarningBox","logLines","showNotionEnvSetupMessage","framework","prefix","getFrameworkEnvPrefix","content","colors","box","createWarningBox","logLines","showNotionTemplateSetupMessage","framework","config","prefix","getFrameworkEnvPrefix","fileExtension","detectStyleFileExtension","cssFile","importPath","calculateStylesImportPath","content","colors","box","createWarningBox","logLines","showTableNodeSetupMessage","logger","path","confirm","select","InvalidArgumentError","Option","fs","path","confirm","fg","ts","reactGuide","requireReactProject","cwd","manifest","getPackageInfo","getFeatureConfig","pathOverride","projectInfo","getConfig","importsEditorHook","file","text","fs","path","ts","statement","named","item","withinProject","root","rel","findNestedPackage","editor","directory","stat","resolveFeatureEditor","explicitEditor","interactive","editorPath","real","error","nestedPackage","files","fg","candidates","canPrompt","candidate","confirm","featureOption","Option","value","previous","InvalidArgumentError","templateFeatureNames","template","status","relations","id","relation","featureIdSchema","isInstallableFeature","entry","getOptionalRegistryFeatures","getRegistryFeatures","error","reason","findRegistryFeature","entries","cwd","item","runner","getPackageRunner","chooseTemplateFeature","features","canPrompt","ids","choices","feature","recipe","confirm","toReadableName","select","resolveSelection","components","requested","registry","getRegistryIndex","sources","name","templates","builtIn","catalog","registryModulePathSchema","resolveEditor","selection","editor","interactive","resolveFeatureEditor","quoteArgument","showFeatureSetup","plan","options","preview","setup","collaboration","filtered","target","path","candidates","logger","candidate","destination","showPendingCollaborationEdit","showCollaborationSetup","instruction","addOptionsSchema","z","PROMPT_PAGE_SIZE","TEMPLATE_DESCRIPTION_MAX_LINE_WIDTH","TEMPLATE_DESCRIPTION_MIN_LINE_WIDTH","TEMPLATE_DESCRIPTION_INDENT_WIDTH","UI","colors","PROMPT_THEME","text","normalizeDescription","description","wrapText","maxLineLength","words","lines","currentLine","word","nextLine","getTemplateDescriptionLineWidth","terminalWidth","formatTemplatePlanLabel","plans","planLabel","getPlanLabel","formatTemplateChoiceName","template","name","toReadableName","descriptionLines","line","requiredPlan","PAID_PLANS","plan","planName","filterFreeTemplates","templates","freeComponents","template","clearPromptLines","lines","i","categorizeRegistryItems","registryIndex","entry","promptForInitialSelection","categories","hasFeatures","showDivider","message","choices","isComponentEmpty","logger","UI","createSpacedDivider","selection","select_default","colors","PROMPT_PAGE_SIZE","PROMPT_THEME","createComponentChoices","components","addCategorySection","items","title","filteredItems","item","Separator","planLabel","getPlanLabel","paddedName","toReadableName","description","componentMenu","selectedComponents","checkbox","component","templateMenu","formatTemplateChoiceName","selectedTemplate","promptForRegistryComponents","options","features","getRegistryIndex","getOptionalRegistryFeatures","visible","id","feature","chooseTemplateFeature","add","Command","featureOption","opts","addOptionsSchema","path","preview","interactive","canPrompt","featureId","selected","clearTerminal","logLines","createWelcomeBanner","input","choice","resolveSelection","sources","builtIn","standalone","target","resolveEditor","featureProject","getProjectInfo","config","getFeatureConfig","requireReactProject","preflight","preFlightAdd","planOptions","hasPaidComponents","assertCanPreviewPaidComponents","plan","planComponents","printInstallPreview","showFeatureSetup","ensureAuthForPaidComponents","created","addComponents","action","files","file","logAutoImportResult","projectInfo","showNotionEnvSetupMessage","showNotionTemplateSetupMessage","showStylesConfigurationMessage","showTableNodeSetupMessage","error","handleError","existsSync","path","Command","package_default","info","Command","opts","cwd","path","project","getProjectInfo","config","getConfig","stylesheet","getMainCssFilePath","package_default","getPackageManagerInfo","name","getInstalledPackageVersion","existsSync","getRegistryBaseUrl","logger","Command","InvalidArgumentError","parseType","value","type","parsed","registryItemTypeSchema","InvalidArgumentError","parseCount","count","searchRegistryIndex","index","query","options","terms","matches","item","text","term","end","search","Command","result","getRegistryIndex","Command","describeItem","item","supported","templateFeatureNames","features","getOptionalRegistryFeatures","feature","files","file","routes","type","target","view","Command","name","options","getRegistryFeatures","isInstallableFeature","getRegistryIndex","entry","findRegistryFeature","addCommand","getPackageRunner","framework","items","instruction","assertCanPreviewPaidComponents","source","fetchRegistry","payload","registrySourceItemSchema","details","label","entries","link","existsSync","path","Command","confirm","input","z","preFlightInit","options","frameworkSpinner","spinner","projectInfo","getProjectInfo","logger","colors","tsConfigSpinner","os","path","fs","execa","parseJsonc","input","path","fs","execa","isMap","isSeq","parseDocument","watcher","coversWatcher","rule","configureNextPnpmBuilds","projectPath","file","policy","key","builds","ignored","item","configureVitePnpmBuilds","filename","dir","stdout","MONOREPO_FRAMEWORK_URL","FRAMEWORKS","createThemedInput","message","defaultValue","input","colors","value","createThemedSelect","choices","instructions","select_default","createProject","options","normalizedOptions","framework","nextVersion","frameworkPromptMessage","logger","projectName","packageManager","getPackageManager","projectPath","path","validateProjectPath","createNextProject","createViteProject","createMonorepoProject","cwd","fs","createSpinner","spinner","args","execa","configureNextPnpmBuilds","updateReadmeFile","error","configureVitePnpmBuilds","setupViteTsConfig","handleError","setupTsConfigPathAliases","setupViteConfigPathAliases","installTypesNode","addAliasToTsConfig","tsconfigFile","tsconfigPath","jsonContent","jsonObj","parseJsonc","updatedJson","viteConfigPath","updatedViteConfig","downloadAndExtractFramework","initializeGitRepository","frameworkPath","os","response","tarPath","extractedPath","simpleEditorTemplateDocs","notionLikeEditorDocs","templateName","readmePath","templateContent","readmeContent","initOptionsSchema","z","val","FRAMEWORKS","createThemedConfirm","message","defaultValue","confirm","colors","init","Command","featureOption","components","opts","options","canPrompt","path","clearTerminal","logLines","createWelcomeBanner","input","logger","result","runInit","files","hasNotion","file","hasSimple","label","framework","logAutoImportResult","showNotionEnvSetupMessage","showNotionTemplateSetupMessage","showStylesConfigurationMessage","showTableNodeSetupMessage","showFeatureSetup","error","handleError","skipPreflight","silent","requested","resolveSelection","updatedOptions","newProjectFramework","createResult","config","projectInfo","selectedComponents","addResult","feature","candidates","existsSync","projectPath","createProject","monorepoWebPath","getConfig","featureId","interactive","choice","promptForRegistryComponents","selection","sources","standalone","preFlightInit","getProjectInfo","templateConfig","projectConfig","getProjectConfig","promptForMinimalConfig","promptForConfig","resolveConfigPaths","target","resolveEditor","fullConfig","getFeatureConfig","hasPaidComponents","ensureAuthForPaidComponents","addComponentsResult","addComponents","defaultConfig","defaults","tsx","rsc","rawConfigSchema","DEFAULT_COMPONENTS","DEFAULT_CONTEXTS","DEFAULT_HOOKS","DEFAULT_TIPTAP_ICONS","DEFAULT_LIB","DEFAULT_TIPTAP_EXTENSIONS","DEFAULT_TIPTAP_NODES","DEFAULT_TIPTAP_UI","DEFAULT_TIPTAP_UI_PRIMITIVES","DEFAULT_TIPTAP_UI_UTILS","DEFAULT_STYLES","Command","main","program","Command","package_default","init","add","info","search","view","login","logout","status","license","error"]}
|