@dxtmisha/scripts 0.9.1 → 0.10.3
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/CHANGELOG.md +48 -0
- package/package.json +2 -1
- package/src/classes/Ai/AiClaudeAgent.ts +16 -0
- package/src/classes/Ai/AiClaudeAgentLite.ts +86 -0
- package/src/classes/Ai/AiClaudeCliLite.ts +29 -65
- package/src/classes/Ai/AiClaudeLite.ts +19 -7
- package/src/classes/Ai/AiGoogleCliLite.ts +27 -64
- package/src/classes/Ai/AiOpenAi.ts +26 -0
- package/src/classes/Ai/AiOpenAiLite.ts +107 -0
- package/src/classes/Ai/AiZAi.ts +17 -0
- package/src/classes/Ai/AiZAiLite.ts +26 -0
- package/src/classes/Ai/ApiTmp.ts +43 -0
- package/src/classes/Build/BuildPackages.ts +33 -7
- package/src/classes/Design/DesignComponent.ts +1 -1
- package/src/classes/Design/DesignTypes.ts +7 -6
- package/src/classes/Design/DesignWikiStorm.ts +7 -7
- package/src/classes/Design/DesignWikiStormItem.ts +64 -34
- package/src/classes/Library/LibraryAiPrompt.ts +2 -2
- package/src/classes/Library/LibraryAiPromptItem.ts +37 -3
- package/src/composables/useAi.ts +15 -0
- package/src/config.ts +9 -7
- package/src/demo/ai.ts +10 -0
- package/src/library-ai.ts +4 -4
- package/src/library.ts +67 -54
- package/src/media/templates/componentDoc/materials/{prompt.txt → prompt.md} +4 -4
- package/src/media/templates/componentDoc/wiki/prompt.md +21 -0
- package/src/media/templates/componentDoc/wiki/run.ts +1 -1
- package/src/media/templates/packages/library/package.json +7 -5
- package/src/media/templates/prompts/aiCodeGlobalPrompt.en.md +77 -0
- package/src/media/templates/prompts/aiCodeGlobalPrompt.ru.md +78 -0
- package/src/types/configTypes.ts +9 -2
- package/src/types/webTypes.ts +33 -4
- package/src/classes/Component/__tests__/ComponentCreator.test.ts +0 -71
- package/src/classes/Component/__tests__/ComponentItem.test.ts +0 -71
- package/src/classes/Git/__tests__/GitRead.test.ts +0 -70
- package/src/composables/__tests__/useAi.test.ts +0 -75
- package/src/functions/__tests__/getComponentPaths.test.ts +0 -19
- package/src/functions/__tests__/getConfigAi.test.ts +0 -26
- package/src/functions/__tests__/getConstructorProperties.test.ts +0 -51
- package/src/functions/__tests__/getDirname.test.ts +0 -31
- package/src/functions/__tests__/getNameDirByPaths.test.ts +0 -40
- package/src/functions/__tests__/getPackageJson.test.ts +0 -34
- package/src/functions/__tests__/hasNativeDirname.test.ts +0 -18
- package/src/functions/__tests__/toPathStandardSep.test.ts +0 -31
- package/src/media/templates/componentDoc/wiki/prompt.txt +0 -16
- package/src/media/templates/prompts/aiCodeGlobalPrompt.en.txt +0 -40
- package/src/media/templates/prompts/aiCodeGlobalPrompt.ru.txt +0 -40
- /package/src/media/templates/prompts/{aiCodeVuePrompt.en.txt → aiCodeVuePrompt.en.md} +0 -0
- /package/src/media/templates/prompts/{aiCodeVuePrompt.ru.txt → aiCodeVuePrompt.ru.md} +0 -0
package/src/library.ts
CHANGED
|
@@ -1,54 +1,67 @@
|
|
|
1
|
-
// Classes
|
|
2
|
-
export * from './classes/Ai/AiAbstract'
|
|
3
|
-
export * from './classes/Ai/AiClaude'
|
|
4
|
-
export * from './classes/Ai/
|
|
5
|
-
export * from './classes/Ai/
|
|
6
|
-
export * from './classes/Ai/
|
|
7
|
-
export * from './classes/Ai/
|
|
8
|
-
export * from './classes/Ai/
|
|
9
|
-
export * from './classes/Ai/
|
|
10
|
-
export * from './classes/Ai/
|
|
11
|
-
export * from './classes/Ai/
|
|
12
|
-
export * from './classes/Ai/
|
|
13
|
-
export * from './classes/Ai/
|
|
14
|
-
export * from './classes/Ai/
|
|
15
|
-
export * from './classes/Ai/
|
|
16
|
-
export * from './classes/Ai/
|
|
17
|
-
export * from './classes/
|
|
18
|
-
export * from './classes/
|
|
19
|
-
export * from './classes/
|
|
20
|
-
export * from './classes/
|
|
21
|
-
export * from './classes/
|
|
22
|
-
export * from './classes/
|
|
23
|
-
export * from './classes/
|
|
24
|
-
export * from './classes/
|
|
25
|
-
export * from './classes/
|
|
26
|
-
export * from './classes/
|
|
27
|
-
export * from './classes/
|
|
28
|
-
export * from './classes/
|
|
29
|
-
export * from './classes/
|
|
30
|
-
export * from './classes/
|
|
31
|
-
export * from './classes/
|
|
32
|
-
export * from './classes/
|
|
33
|
-
export * from './classes/
|
|
34
|
-
export * from './classes/
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
export * from './
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
export * from './
|
|
41
|
-
export * from './
|
|
42
|
-
export * from './
|
|
43
|
-
export * from './
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
export * from './
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
export * from './
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
export * from './
|
|
53
|
-
export * from './
|
|
54
|
-
export * from './
|
|
1
|
+
// Classes
|
|
2
|
+
export * from './classes/Ai/AiAbstract'
|
|
3
|
+
export * from './classes/Ai/AiClaude'
|
|
4
|
+
export * from './classes/Ai/AiClaudeAgent'
|
|
5
|
+
export * from './classes/Ai/AiClaudeAgentLite'
|
|
6
|
+
export * from './classes/Ai/AiClaudeCli'
|
|
7
|
+
export * from './classes/Ai/AiClaudeCliLite'
|
|
8
|
+
export * from './classes/Ai/AiClaudeLite'
|
|
9
|
+
export * from './classes/Ai/AiDoc'
|
|
10
|
+
export * from './classes/Ai/AiDocItem'
|
|
11
|
+
export * from './classes/Ai/AiDocItemAbstract'
|
|
12
|
+
export * from './classes/Ai/AiDocItemClasses'
|
|
13
|
+
export * from './classes/Ai/AiDocItemComposables'
|
|
14
|
+
export * from './classes/Ai/AiDocType'
|
|
15
|
+
export * from './classes/Ai/AiGoogle'
|
|
16
|
+
export * from './classes/Ai/AiGoogleCli'
|
|
17
|
+
export * from './classes/Ai/AiGoogleCliLite'
|
|
18
|
+
export * from './classes/Ai/AiGoogleLite'
|
|
19
|
+
export * from './classes/Ai/AiOpenAi'
|
|
20
|
+
export * from './classes/Ai/AiOpenAiLite'
|
|
21
|
+
export * from './classes/Ai/AiZAi'
|
|
22
|
+
export * from './classes/Ai/AiZAiLite'
|
|
23
|
+
export * from './classes/Ai/ApiTmp'
|
|
24
|
+
export * from './classes/BrowserItem'
|
|
25
|
+
export * from './classes/Build/BuildFunctional'
|
|
26
|
+
export * from './classes/Build/BuildPackages'
|
|
27
|
+
export * from './classes/Build/BuildPublishPackages'
|
|
28
|
+
export * from './classes/BuildItem'
|
|
29
|
+
export * from './classes/Design/DesignFigma'
|
|
30
|
+
export * from './classes/Design/DesignScreenshot'
|
|
31
|
+
export * from './classes/Design/DesignTypes'
|
|
32
|
+
export * from './classes/Design/DesignTypescript'
|
|
33
|
+
export * from './classes/Design/DesignWikiStorm'
|
|
34
|
+
export * from './classes/Design/DesignWikiStormItem'
|
|
35
|
+
export * from './classes/FigmaApi'
|
|
36
|
+
export * from './classes/Git/GitRead'
|
|
37
|
+
export * from './classes/Library/LibraryAiPrompt'
|
|
38
|
+
export * from './classes/Library/LibraryAiPromptItem'
|
|
39
|
+
export * from './classes/Library/LibraryAiWiki'
|
|
40
|
+
export * from './classes/Library/LibraryAiWikiItem'
|
|
41
|
+
export * from './classes/Library/LibraryExport'
|
|
42
|
+
export * from './classes/Library/LibraryList'
|
|
43
|
+
export * from './classes/Library/LibraryPlugin'
|
|
44
|
+
export * from './classes/Library/LibraryTypes'
|
|
45
|
+
export * from './classes/Package/PackageFile'
|
|
46
|
+
export * from './classes/Properties/PropertiesFile'
|
|
47
|
+
|
|
48
|
+
// Composables
|
|
49
|
+
export * from './composables/useAi'
|
|
50
|
+
|
|
51
|
+
// Functions
|
|
52
|
+
export * from './functions/getConfigAi'
|
|
53
|
+
export * from './functions/getDirname'
|
|
54
|
+
export * from './functions/getPackageJson'
|
|
55
|
+
export * from './functions/hasNativeDirname'
|
|
56
|
+
export * from './functions/run'
|
|
57
|
+
|
|
58
|
+
// Types
|
|
59
|
+
export * from './types/aiTypes'
|
|
60
|
+
export * from './types/configTypes'
|
|
61
|
+
export * from './types/designTypes'
|
|
62
|
+
export * from './types/figmaApiTypes'
|
|
63
|
+
export * from './types/gitTypes'
|
|
64
|
+
export * from './types/libraryTypes'
|
|
65
|
+
export * from './types/propertyTypes'
|
|
66
|
+
export * from './types/screenshotTypes'
|
|
67
|
+
export * from './types/webTypes'
|
|
@@ -13,13 +13,13 @@ The target parent directory (one level up from this "materials" directory) repre
|
|
|
13
13
|
- `wiki/`: Storybook playground configuration and documentation files:
|
|
14
14
|
- `[ComponentName].mdx`: MDX documentation tab/documentation configuration for Storybook.
|
|
15
15
|
- `[ComponentName].stories.ts`: Storybook stories/scenarios configuration.
|
|
16
|
-
- `prompt.
|
|
17
|
-
- `run.ts`: A script running `npx dxt-component-wiki` to write the MDX files automatically using `wiki/prompt.
|
|
16
|
+
- `prompt.md`: The system prompt directing how to generate MDX/Storybook documentation.
|
|
17
|
+
- `run.ts`: A script running `npx dxt-component-wiki` to write the MDX files automatically using `wiki/prompt.md`.
|
|
18
18
|
|
|
19
19
|
Strict Implementation & Architectural Constraints:
|
|
20
20
|
1. Available Dependencies Only: You must strictly use only the currently installed packages and available dependencies. Do not install new external npm packages or add new third-party dependencies unless explicitly requested.
|
|
21
|
-
2. Global System Prompt Compliance: You must locate, study, and strictly adhere to all coding standards, BEM conventions, SCSS mixins, and guidelines defined in the `ai-prompt.
|
|
22
|
-
3. Monorepo Prompt Context: As this is a monorepo setup, you must locate and study both the individual package-level configuration/prompt files and the repository's root system rules (`ai-prompt.
|
|
21
|
+
2. Global System Prompt Compliance: You must locate, study, and strictly adhere to all coding standards, BEM conventions, SCSS mixins, and guidelines defined in the `ai-prompt.md` file located up the folder tree in the root of the repository. Ignore any instructions or files located outside the repository boundaries.
|
|
22
|
+
3. Monorepo Prompt Context: As this is a monorepo setup, you must locate and study both the individual package-level configuration/prompt files and the repository's root system rules (`ai-prompt.md`) to ensure perfect compatibility with the local package architecture.
|
|
23
23
|
4. Zero Tolerance for Hallucinations: You must strictly follow all implementation rules and specifications without any deviation. Hallucinating, inventing properties, methods, slots, or external libraries is strictly forbidden.
|
|
24
24
|
|
|
25
25
|
---
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
Task Goal:
|
|
2
|
+
The primary goal is to write comprehensive, high-quality documentation for the Vue 3 component.
|
|
3
|
+
|
|
4
|
+
Component Resolution & Analysis:
|
|
5
|
+
If the component source files are not directly attached, they are located in the parent directory (one folder above this "wiki" folder). Locate and study the main Vue file, types/props, styles, and dependencies until you fully understand how the component works. Once you have a complete understanding of its behavior and interface, further deep-dive study of outer dependencies is not required.
|
|
6
|
+
|
|
7
|
+
Mandatory Instruction:
|
|
8
|
+
You must read and deeply study the detailed descriptions, rules, coding standards, and templates specified in:
|
|
9
|
+
node_modules/@dxtmisha/scripts/src/media/templates/prompts/componentPrompt.en.txt
|
|
10
|
+
|
|
11
|
+
You must strictly follow those instructions. However, make sure you save your outputs in the correct target locations:
|
|
12
|
+
- Documentation & playground changes (including MDX files and `stories.ts` playground configurations) must be saved inside this current directory (the "wiki" folder).
|
|
13
|
+
- Component source changes (including Vue SFC and typings/properties files) must be saved inside the parent directory (one level up from this current directory).
|
|
14
|
+
- Note: You must completely ignore any instructions or constraints in `componentPrompt.en.txt` regarding how the final result/output should be returned or structured (specifically ignore rules 5-8, the requirement to split the response into 5 parts separated by "#########", and the prohibition on writing or modifying files). Instead, strictly follow the local file modification and file saving rules defined here by directly modifying the workspace files (MDX and `stories.ts` in the current folder, and Vue SFC and `types.ts` in the parent folder).
|
|
15
|
+
|
|
16
|
+
All constraints, formatting standards, and styling helper classes described in that file must be adhered to without exception.
|
|
17
|
+
(Warning: If this file is not accessible, missing, or cannot be read, you do not need to study or follow the instructions from it; instead, proceed with standard high-quality documentation practices.)
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
CRITICAL PRIORITY RULE:
|
|
21
|
+
Everything below this line has a higher priority than the text above it.
|
|
@@ -7,7 +7,7 @@ import { readFileSync } from 'node:fs'
|
|
|
7
7
|
;(async () => {
|
|
8
8
|
try {
|
|
9
9
|
// You can add prompt generation logic here
|
|
10
|
-
const prompt = readFileSync(new URL('./prompt.
|
|
10
|
+
const prompt = readFileSync(new URL('./prompt.md', import.meta.url), 'utf-8')
|
|
11
11
|
|
|
12
12
|
const child = spawn(
|
|
13
13
|
'npx',
|
|
@@ -11,14 +11,16 @@
|
|
|
11
11
|
"test": "vitest",
|
|
12
12
|
"component": "dxt-component",
|
|
13
13
|
"library": "dxt-library",
|
|
14
|
-
"
|
|
14
|
+
"types": "npm run prepublishOnly && dxt-types",
|
|
15
|
+
"wiki": "dxt-ai-doc",
|
|
16
|
+
"prepublishOnly": "npm run library && npm run build",
|
|
17
|
+
"publish-to-npm": "npm publish --access public"
|
|
15
18
|
},
|
|
16
19
|
"files": [
|
|
17
20
|
"dist",
|
|
18
|
-
"ai-description.
|
|
19
|
-
"ai-doc.
|
|
20
|
-
"ai-
|
|
21
|
-
"ai-types.txt",
|
|
21
|
+
"ai-description.md",
|
|
22
|
+
"ai-doc.md",
|
|
23
|
+
"ai-types.md",
|
|
22
24
|
"CHANGELOG.md",
|
|
23
25
|
"LICENSE",
|
|
24
26
|
"package.json",
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
### Global Development Principles (AI Code Promise)
|
|
2
|
+
|
|
3
|
+
Your primary goal is to generate flawless, industrial-grade code that adheres to dxt-ui standards. You promise to follow these rules strictly:
|
|
4
|
+
|
|
5
|
+
0. **Mandatory Deep Study**:
|
|
6
|
+
- Before developing anything for any project or package, you MUST study it completely to fully understand its architecture and stylistic guidelines.
|
|
7
|
+
- Before modifying or fixing any file, you MUST fully study its internal structure and logic first.
|
|
8
|
+
- If any instructions, paths, or files are specified as located inside `node_modules/` or any other external/linked directory, you MUST first check if this package exists locally in the workspace (for example, under `packages/`). If it does exist locally, you MUST resolve the paths to the local workspace package directory and study/modify the local source files instead.
|
|
9
|
+
- **CRITICAL FIRST STEP:** If any project, module, or instruction contains links or references to specific files (e.g. types, developer guides, descriptions), you MUST study all these referenced files as your absolute first action. As soon as you start working with a project, or notice that it is imported/used in the code you are working with, you must immediately read and study all these referenced files before doing any planning, proposing code changes, or writing code. This is mandatory and applies even if the files are located in `node_modules/` (always resolve them to the local workspace directory first if they exist locally).
|
|
10
|
+
- **STRICT BLOCKING GUARD (CHRONOLOGICAL ORDER RULES):**
|
|
11
|
+
1. As your ABSOLUTE FIRST ACTION, before taking any other steps, you MUST check if the `ai-memory.md` file exists in the specific package directory or the repository root depending on the files you are working on:
|
|
12
|
+
- If you are analyzing or modifying files that are located inside a package directory (e.g., any subdirectory under `packages/` like `packages/constructor/`, `packages/scripts/`, etc.), you MUST read/write the `ai-memory.md` file ONLY within that specific package directory (e.g. `packages/constructor/ai-memory.md` or `packages/scripts/ai-memory.md`). You are strictly FORBIDDEN from using, reading, or writing the global `ai-memory.md` in the repository root in this case.
|
|
13
|
+
- If and only if the files you are working with are root-level configurations or not part of any package under `packages/`, you may read/write the `ai-memory.md` file in the repository root.
|
|
14
|
+
If the required local package-level `ai-memory.md` (or root `ai-memory.md` for root-level files) exists, you MUST read it using `view_file`. If it does NOT exist, you MUST CREATE IT immediately using `write_to_file` as an empty file with only a single newline (no placeholder text, comments, or intro text).
|
|
15
|
+
2. As your ABSOLUTE SECOND ACTION, you MUST use the `view_file` tool to read the master `ai-prompt.md` file located in the project root. You MUST read the descriptions of ALL libraries mentioned in this file. If there is even a 1% chance that a library mentioned in `ai-prompt.md` contains functionality or utilities relevant to your task, you are OBLIGED to read and study all files associated with that library that are specified in the `ai-prompt.md` under its respective section. You are strictly forbidden from writing custom logic (helpers, styles, configs, classes) without first performing an exhaustive check of the workspace's existing infrastructure (like `functional`, `functional-basic`) via `grep_search` or `list_dir`.
|
|
16
|
+
3. Identify all paths, directories, or packages involved in the user request.
|
|
17
|
+
4. Scan the prompt for sections corresponding to those paths.
|
|
18
|
+
5. Identify all paths to auxiliary documentation, types, or developer guides mentioned in those sections.
|
|
19
|
+
6. You MUST use the `view_file` tool to read and study ALL of these referenced files BEFORE calling `list_dir` on sub-folders, writing any plans/checklists, or proposing/making code changes. Bypassing this order is a critical protocol violation.
|
|
20
|
+
|
|
21
|
+
1. **"Copy-Paste Ready" Principle**:
|
|
22
|
+
- Generate code that can be copied and run without a single manual edit.
|
|
23
|
+
- All imports must be absolute or correct relative paths.
|
|
24
|
+
- No `// ... rest of the code`, no `// imports here`. Only the complete, working file.
|
|
25
|
+
|
|
26
|
+
2. **Zero Tolerance for Hallucinations**:
|
|
27
|
+
- Use only the libraries and versions specified in the project's `package.json`.
|
|
28
|
+
- Do not invent API methods that do not exist in the current versions of dependencies.
|
|
29
|
+
- If information is insufficient, it is better to ask or point out the limitation than to hallucinate.
|
|
30
|
+
|
|
31
|
+
3. **Clean Code Standards**:
|
|
32
|
+
- **DRY & KISS**: Avoid duplication, write as simply and clearly as possible.
|
|
33
|
+
- **SOLID**: Every module, class, or function must have one clear responsibility.
|
|
34
|
+
- **Declarative Approach**: Prefer a declarative programming style (array functional methods, composition).
|
|
35
|
+
- **No Abbreviations**: Do not use shortened or abbreviated names for variables, properties, arguments, methods, classes, etc. (e.g., do not use `el`, `rect1`/`r1`, `dx`/`dy`, `val`, `temp`). All identifiers must be descriptive, complete, and self-explanatory.
|
|
36
|
+
- **Optimization and Clarity**: Write code that is highly optimized, performant, and clean, ensuring it is easy to read and understand.
|
|
37
|
+
- **Single Responsibility (KISS/SOLID)**: Avoid creating large "mega-functions" or monolithic blocks. Each function must be concise and perform exactly one focused task (1 function = 1 functionality).
|
|
38
|
+
|
|
39
|
+
4. **Uncompromising TypeScript**:
|
|
40
|
+
- No `any`. Use `unknown` if the type is truly unknown, or create generic types.
|
|
41
|
+
- Never use `@ts-ignore`. If a type check suppression is absolutely necessary due to external limitations, use `@ts-expect-error` with a descriptive comment explaining why.
|
|
42
|
+
- Always define interfaces for input and output data.
|
|
43
|
+
- Use `as const`, `readonly`, and enums/union types to increase reliability.
|
|
44
|
+
|
|
45
|
+
5. **Professional Documentation (TSDoc)**:
|
|
46
|
+
- Accompany all exported entities with TSDoc comments in the [wikiLanguage] language.
|
|
47
|
+
- Describe the purpose, parameters, return values, and potential exceptions.
|
|
48
|
+
- Usage examples in comments are encouraged for complex functions.
|
|
49
|
+
|
|
50
|
+
6. **Architectural Consistency**:
|
|
51
|
+
- Respect the project structure. If it is standard in the project to move logic into `composables` or `utils`, follow that pattern.
|
|
52
|
+
- Reuse existing infrastructure: Always check if the required functionality (e.g., API requests, state management, utilities) already exists in the project's core packages (like `@dxtmisha/functional` or `@dxtmisha/functional-basic`) before implementing it from scratch.
|
|
53
|
+
- Do not modify global styles or styles of base UI components unless explicitly requested.
|
|
54
|
+
|
|
55
|
+
7. **Security and Performance**:
|
|
56
|
+
- Write error-proof code (guard clauses, optional chaining `?.`, nullish coalescing `??`).
|
|
57
|
+
- Use explicit `try-catch` blocks for asynchronous operations. Never swallow errors silently; handle them appropriately or throw meaningful error messages.
|
|
58
|
+
- Avoid redundant calculations in loops and heavy operations in reactive dependencies.
|
|
59
|
+
|
|
60
|
+
8. **Aesthetics and Conciseness**:
|
|
61
|
+
- The code must be beautiful. Use logical indentation and group code by meaning.
|
|
62
|
+
- Save tokens by avoiding redundant comments where the code speaks for itself.
|
|
63
|
+
|
|
64
|
+
9. **Strict Adherence to Instructions & Optimization**:
|
|
65
|
+
- Perform all operations strictly in accordance with the provided commands and instructions.
|
|
66
|
+
- Avoid guessing or performing unrelated extra actions. However, you are encouraged to analyze the requirements, optimize the code, and propose or implement better technical solutions directly related to achieving the task's goals.
|
|
67
|
+
- Strictly adhere to the plan, checklists, and execution steps, while refining them for better quality and performance when needed.
|
|
68
|
+
|
|
69
|
+
10. **AI Workspace Memory (`ai-memory.md`)**:
|
|
70
|
+
- As enforced by the STRICT BLOCKING GUARD, `ai-memory.md` MUST be created and read locally inside the root of the specific package you are working with (e.g., `packages/constructor/ai-memory.md` for code in `packages/constructor`).
|
|
71
|
+
- Writing or reading `ai-memory.md` in the repository root when working on code inside a package is a critical violation of these rules.
|
|
72
|
+
- Whenever you receive feedback, corrections, or instructions from the developer, you MUST update that specific package's local `ai-memory.md` file.
|
|
73
|
+
- Explicit Memorization Requests: If the developer explicitly instructs you to "remember this", "keep this in mind", or makes a similar request regarding conventions or rules, you MUST immediately record this information in the relevant local `ai-memory.md` file.
|
|
74
|
+
- Active Application: You must actively APPLY the rules and constraints from `ai-memory.md` to all code you generate. Rules in this file override general assumptions and have the highest priority.
|
|
75
|
+
- The PRIMARY PURPOSE of this file is to store critical coding guidelines, specific architectural constraints, and "do's and don'ts" (e.g., "do not use X; use Y instead") to ensure the AI writes compliant, correct code.
|
|
76
|
+
- DO NOT store change logs, lists of modified files, or commit-like messages (e.g., "updated file X, updated package Y"). Keep the file clean, concise, and focused strictly on active rules, design decisions, and coding standards.
|
|
77
|
+
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
### Глобальные принципы разработки (AI Code Promise)
|
|
2
|
+
|
|
3
|
+
Твоя главная цель — генерировать безупречный, промышленный код, который соответствует стандартам dxt-ui. Ты обещаешь следовать этим правилам неукоснительно:
|
|
4
|
+
|
|
5
|
+
0. **Обязательное глубокое изучение**:
|
|
6
|
+
- Прежде чем разрабатывать что-либо для любого проекта или пакета, ты ОБЯЗАН полностью изучить его, чтобы детально понять его архитектуру и стилистику.
|
|
7
|
+
- Прежде чем изменять или исправлять любой файл, ты ОБЯЗАН полностью изучить его внутреннюю структуру и логику.
|
|
8
|
+
- Если в инструкциях, путях или файлах указано расположение внутри `node_modules/` или любой другой внешней/привязанной директории, ты ОБЯЗАН сначала проверить, существует ли этот пакет локально в рабочей области (например, в каталоге `packages/`). Если пакет существует локально, ты ОБЯЗАН переопределить пути на локальный каталог пакета рабочей области и изучать/изменять локальные исходные файлы вместо указанных.
|
|
9
|
+
- **КРИТИЧЕСКИЙ ПЕРВЫЙ ШАГ:** Если какой-либо проект, модуль или инструкция содержит ссылки или пути к конкретным файлам (например, типы, руководства для разработчиков, описания), ты ОБЯЗАН подробно изучить все эти файлы по ссылкам в первую очередь. Как только ты начинаешь работу с проектом или видишь, что он импортируется/используется в коде, над которым ты работаешь, ты должен незамедлительно прочитать и изучить все эти файлы по ссылкам, прежде чем приступать к планированию, предложению изменений или написанию кода. Это требование обязательно и распространяется в том числе на файлы, находящиеся в `node_modules/` (всегда сначала переопределяй пути на локальный каталог рабочей области, если они существуют локально).
|
|
10
|
+
- **БЛОКИРУЮЩИЙ КОНТРОЛЬ ПОСЛЕДОВАТЕЛЬНОСТИ (ПРАВИЛО ХРОНОЛОГИИ):**
|
|
11
|
+
1. В качестве АБСОЛЮТНО ПЕРВОГО ДЕЙСТВИЯ, прежде чем выполнять любые другие шаги, ты ОБЯЗАН проверить, существует ли файл `ai-memory.md` в директории конкретного пакета или корня репозитория, в зависимости от файлов, с которыми ты работаешь:
|
|
12
|
+
- Если ты анализируешь или изменяешь файлы, находящиеся внутри каталога пакета (например, в любом подкаталоге внутри `packages/`, таком как `packages/constructor/`, `packages/scripts/` и т.д.), ты ОБЯЗАН читать/записывать файл `ai-memory.md` ИСКЛЮЧИТЕЛЬНО внутри каталога этого конкретного пакета (например, `packages/constructor/ai-memory.md` или `packages/scripts/ai-memory.md`). Тебе строго ЗАПРЕЩЕНО использовать, читать или записывать глобальный `ai-memory.md` в корне всего репозитория в этом случае.
|
|
13
|
+
- Если и только если файлы, с которыми ты работаешь, являются конфигурациями корневого уровня или не относятся к какому-либо пакету внутри `packages/`, ты можешь читать/записывать `ai-memory.md` в корне репозитория.
|
|
14
|
+
Если требуемый локальный файл `ai-memory.md` пакета (или корневой `ai-memory.md` для файлов корневого уровня) существует, ты ОБЯЗАН прочитать его с помощью `view_file`. Если его НЕТ, ты ОБЯЗАН НЕМЕДЛЕННО СОЗДАТЬ ЕГО с помощью `write_to_file` как пустой файл с одной лишь новой строкой (без плейсхолдеров, комментариев или вводного текста).
|
|
15
|
+
2. В качестве АБСОЛЮТНО ВТОРОГО ДЕЙСТВИЯ, ты ОБЯЗАН использовать инструмент `view_file` для чтения главного файла `ai-prompt.md` в корне проекта. Ты ОБЯЗАН изучить описания ВСЕХ библиотек, упомянутых в этом файле. Если тебе кажется хотя бы на мизерный процент (1%), что в какой-либо библиотеке есть что-то подходящее или полезное для твоей задачи, ты ОБЯЗАН изучить все файлы в этой библиотеке, которые указаны в `ai-prompt.md` в разделе этой библиотеки. Тебе строго запрещено писать кастомные реализации (хелперы, стили, конфигурации, классы) или придумывать свое, не проверив предварительно существующую инфраструктуру рабочей области (например, `functional`, `functional-basic`).
|
|
16
|
+
3. Определи все пути пакетов или директорий, связанных с запросом.
|
|
17
|
+
4. Найди в промпте секции, соответствующие этим путям.
|
|
18
|
+
5. Выпиши все пути к вспомогательным файлам типов и руководств, упомянутые в этих секциях.
|
|
19
|
+
6. Ты ОБЯЗАН использовать инструмент `view_file` для чтения и изучения ВСЕХ этих файлов ДО ТОГО, как вызывать `list_dir` для папок компонентов, писать какие-либо планы/чек-листы или вносить/предлагать изменения в код. Нарушение этой последовательности является критическим нарушением протокола.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
1. **Принцип «Copy-Paste Ready» (Готовность к использованию)**:
|
|
24
|
+
- Генерируй код, который можно скопировать и запустить без единой правки.
|
|
25
|
+
- Все импорты должны быть абсолютными или корректными относительными.
|
|
26
|
+
- Никаких `// ... остальной код`, никаких `// импорты здесь`. Только полный, рабочий файл.
|
|
27
|
+
|
|
28
|
+
2. **Нулевая толерантность к галлюцинациям**:
|
|
29
|
+
- Используй только те библиотеки и версии, которые указаны в `package.json` проекта.
|
|
30
|
+
- Не выдумывай методы API, которых не существует в текущих версиях зависимостей.
|
|
31
|
+
- Если информации недостаточно — лучше спроси или укажи на ограничение, чем галлюцинируй.
|
|
32
|
+
|
|
33
|
+
3. **Стандарты чистого кода (Clean Code)**:
|
|
34
|
+
- **DRY & KISS**: Избегай дублирования, пиши максимально просто и понятно.
|
|
35
|
+
- **SOLID**: Каждый модуль, класс или функция должны иметь одну четкую ответственность.
|
|
36
|
+
- **Декларативность**: Отдавай предпочтение декларативному стилю программирования (функциональные методы массивов, композиция).
|
|
37
|
+
- **Никаких сокращений**: Запрещено использовать сокращенные имена для переменных, свойств, аргументов, методов, классов и т. д. (например, нельзя использовать `el`, `rect1`/`r1`, `dx`/`dy`, `val`, `temp`). Все идентификаторы должны быть информативными, полными и самодокументируемыми.
|
|
38
|
+
- **Оптимизация и понятность**: Код должен быть максимально оптимизированным, производительным и понятным, обеспечивающим легкое чтение и поддержку.
|
|
39
|
+
- **Принцип единой ответственности**: Избегай создания больших «мега-функций» или монолитных блоков. Каждая функция должна быть лаконичной и решать ровно одну задачу (1 функция — 1 функционал).
|
|
40
|
+
|
|
41
|
+
4. **Бескомпромиссный TypeScript**:
|
|
42
|
+
- Никаких `any`. Используй `unknown`, если тип действительно неизвестен, или создавай generic-типы.
|
|
43
|
+
- Никогда не используй `@ts-ignore`. Если подавление проверки типов абсолютно необходимо из-за внешних ограничений, используй `@ts-expect-error` с обязательным поясняющим комментарием.
|
|
44
|
+
- Всегда определяй интерфейсы для входных и выходных данных.
|
|
45
|
+
- Используй `as const`, `readonly` и перечисления (enums/union types) для повышения надежности.
|
|
46
|
+
|
|
47
|
+
5. **Профессиональное документирование (TSDoc)**:
|
|
48
|
+
- Сопровождай все экспортируемые сущности комментариями TSDoc на [wikiLanguage] языке.
|
|
49
|
+
- Описывай назначение, параметры, возвращаемые значения и возможные исключения.
|
|
50
|
+
- Примеры использования в комментариях приветствуются для сложных функций.
|
|
51
|
+
|
|
52
|
+
6. **Архитектурная консистентность**:
|
|
53
|
+
- Соблюдай структуру проекта. Если в проекте принято выносить логику в `composables` или `utils` — следуй этому паттерну.
|
|
54
|
+
- Переиспользование инфраструктуры: Всегда проверяй, существует ли необходимый функционал (например, API-запросы, управление состоянием, утилиты) в базовых пакетах проекта (таких как `@dxtmisha/functional` или `@dxtmisha/functional-basic`), прежде чем писать его с нуля.
|
|
55
|
+
- Не изменяй глобальные стили или стили базовых UI-компонентов, если это не было явно запрошено.
|
|
56
|
+
|
|
57
|
+
7. **Безопасность и Производительность**:
|
|
58
|
+
- Пиши код, защищенный от ошибок (guard clauses, опциональная цепочка `?.`, nullish coalescing `??`).
|
|
59
|
+
- Используй явные блоки `try-catch` для асинхронных операций. Никогда не "проглатывай" ошибки молча; обрабатывай их корректно или выбрасывай информативные сообщения об ошибках.
|
|
60
|
+
- Избегай лишних вычислений в циклах и тяжелых операций в реактивных зависимостях.
|
|
61
|
+
|
|
62
|
+
8. **Эстетика и Лаконичность**:
|
|
63
|
+
- Код должен быть красивым. Используй логические отступы и группировку кода по смыслу.
|
|
64
|
+
- Экономь токены, избегая избыточных комментариев там, где код говорит сам за себя.
|
|
65
|
+
|
|
66
|
+
9. **Строгое следование инструкциям и оптимизация**:
|
|
67
|
+
- Выполняй все действия строго в соответствии с предоставленными командами и инструкциями.
|
|
68
|
+
- Избегай додумывания или выполнения не связанных с задачей лишних действий. Тем не менее, приветствуется глубокий анализ требований, оптимизация кода, а также поиск и реализация лучших технических решений, напрямую направленных на достижение целей поставленной задачи.
|
|
69
|
+
- Строго придерживайся планов, чек-листов и шагов выполнения, улучшая и дорабатывая их для повышения качества и производительности по мере необходимости.
|
|
70
|
+
|
|
71
|
+
10. **Память ИИ Пространства (`ai-memory.md`)**:
|
|
72
|
+
- Как установлено в БЛОКИРУЮЩЕМ КОНТРОЛЕ ПОСЛЕДОВАТЕЛЬНОСТИ, `ai-memory.md` ОБЯЗАТЕЛЬНО должен быть создан и прочитан локально внутри корня того конкретного пакета, с которым ты работаешь (например, `packages/constructor/ai-memory.md` для кода в `packages/constructor`).
|
|
73
|
+
- Запись или чтение `ai-memory.md` в корне репозитория при работе с кодом внутри пакета является критическим нарушением правил.
|
|
74
|
+
- Каждый раз, когда ты получаешь замечания, исправления или инструкции от разработчика, ты ОБЯЗАН обновить локальный файл `ai-memory.md` именно этого конкретного пакета.
|
|
75
|
+
- Явные запросы на запоминание: Если разработчик явно просит «запомнить это», «иметь в виду» или делает аналогичный запрос касательно соглашений или правил, ты ОБЯЗАН немедленно зафиксировать эту информацию в соответствующем локальном файле `ai-memory.md`.
|
|
76
|
+
- Активное применение: Ты ОБЯЗАН активно ПРИМЕНЯТЬ правила и ограничения из `ai-memory.md` ко всему генерируемому коду. Ограничения из этого файла имеют высший приоритет и переопределяют любые базовые предположения.
|
|
77
|
+
- ОСНОВНАЯ ЦЕЛЬ этого файла — хранение правил написания кода, архитектурных ограничений и принципов разработки (например: «не делай X, делай Y»), чтобы ИИ мог максимально правильно адаптировать и писать код.
|
|
78
|
+
- ЗАПРЕЩЕНО записывать туда историю изменений, списки обновленных файлов или сообщения в стиле коммитов (например: «обновлен файл X, обновлен пакет Y»). Файл должен содержать только актуальные стандарты, правила разработки и конструктивные требования к коду.
|
package/src/types/configTypes.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
/** AI type for content generation / Тип ИИ для генерации контента */
|
|
2
|
-
export type AiType
|
|
2
|
+
export type AiType
|
|
3
|
+
= | 'claude'
|
|
4
|
+
| 'claude-cli'
|
|
5
|
+
| 'claude-agent'
|
|
6
|
+
| 'gemini'
|
|
7
|
+
| 'gemini-cli'
|
|
8
|
+
| 'openai'
|
|
9
|
+
| 'zai'
|
|
3
10
|
|
|
4
11
|
/** Configuration structure for the design system UI project / Структура конфигурации для проекта дизайн-системы UI */
|
|
5
12
|
export type DesignUiConfig = {
|
|
@@ -40,7 +47,7 @@ export type DesignUiConfig = {
|
|
|
40
47
|
packagePrefix?: string
|
|
41
48
|
|
|
42
49
|
/** AI type for generating content / Тип ИИ для генерации контента */
|
|
43
|
-
aiType?:
|
|
50
|
+
aiType?: AiType
|
|
44
51
|
|
|
45
52
|
/** AI model for generating content / Модель ИИ для генерации контента */
|
|
46
53
|
aiModel?: string
|
package/src/types/webTypes.ts
CHANGED
|
@@ -17,6 +17,7 @@ export type WebTypesInfo = {
|
|
|
17
17
|
export type WebTypesProperty = {
|
|
18
18
|
name: string
|
|
19
19
|
type?: string
|
|
20
|
+
description?: string
|
|
20
21
|
}
|
|
21
22
|
export type WebTypesProperties = WebTypesProperty[]
|
|
22
23
|
|
|
@@ -51,7 +52,8 @@ export type WebTypesAttributes = WebTypesAttributeItem[]
|
|
|
51
52
|
export type WebTypesEventItem
|
|
52
53
|
= WebTypesInfo
|
|
53
54
|
& {
|
|
54
|
-
arguments
|
|
55
|
+
arguments?: WebTypesProperties
|
|
56
|
+
type?: string
|
|
55
57
|
}
|
|
56
58
|
export type WebTypesEvents = WebTypesEventItem[]
|
|
57
59
|
|
|
@@ -85,21 +87,48 @@ export type WebTypesTagItem
|
|
|
85
87
|
}
|
|
86
88
|
export type WebTypesTags = WebTypesTagItem[]
|
|
87
89
|
|
|
90
|
+
/**
|
|
91
|
+
* Prop definition for a Vue component.
|
|
92
|
+
*
|
|
93
|
+
* Определение свойства для Vue-компонента.
|
|
94
|
+
*/
|
|
95
|
+
export type WebTypesPropItem = WebTypesInfo & {
|
|
96
|
+
default?: string
|
|
97
|
+
type?: string
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Vue component definition for Web-Types.
|
|
102
|
+
*
|
|
103
|
+
* Определение Vue-компонента для Web-Types.
|
|
104
|
+
*/
|
|
105
|
+
export type WebTypesVueComponentItem = WebTypesInfo & {
|
|
106
|
+
source?: {
|
|
107
|
+
module?: string
|
|
108
|
+
symbol?: string
|
|
109
|
+
}
|
|
110
|
+
props?: WebTypesPropItem[]
|
|
111
|
+
slots?: WebTypesSlots
|
|
112
|
+
js?: {
|
|
113
|
+
events?: WebTypesEventItem[]
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
88
117
|
/**
|
|
89
118
|
* Root object for Web Types JSON.
|
|
90
119
|
*
|
|
91
120
|
* Корневой объект для JSON Web Types.
|
|
92
121
|
*/
|
|
93
122
|
export type WebTypesVueJson = {
|
|
94
|
-
$schema:
|
|
123
|
+
$schema: string
|
|
95
124
|
framework: 'vue'
|
|
96
125
|
name: string
|
|
97
126
|
version: string
|
|
127
|
+
'js-types-syntax'?: 'typescript'
|
|
98
128
|
contributions: {
|
|
99
129
|
html: {
|
|
100
|
-
'types-syntax': 'typescript'
|
|
101
130
|
'description-markup': 'markdown'
|
|
102
|
-
'
|
|
131
|
+
'vue-components': WebTypesVueComponentItem[]
|
|
103
132
|
}
|
|
104
133
|
}
|
|
105
134
|
}
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
|
2
|
-
import { ComponentCreator } from '../ComponentCreator'
|
|
3
|
-
import { PropertiesFile } from '../../Properties/PropertiesFile'
|
|
4
|
-
import { ComponentItem } from '../ComponentItem'
|
|
5
|
-
import { getComponentPaths } from '../../../functions/getComponentPaths'
|
|
6
|
-
import { UI_DIRS_COMPONENTS } from '../../../config'
|
|
7
|
-
|
|
8
|
-
vi.mock('../../Properties/PropertiesFile', () => ({
|
|
9
|
-
PropertiesFile: {
|
|
10
|
-
readDirOnlyRecursive: vi.fn(),
|
|
11
|
-
readDir: vi.fn()
|
|
12
|
-
}
|
|
13
|
-
}))
|
|
14
|
-
|
|
15
|
-
vi.mock('../ComponentItem', () => ({
|
|
16
|
-
ComponentItem: vi.fn().mockImplementation(function () {
|
|
17
|
-
return {
|
|
18
|
-
make: vi.fn()
|
|
19
|
-
}
|
|
20
|
-
})
|
|
21
|
-
}))
|
|
22
|
-
|
|
23
|
-
vi.mock('../../../functions/getComponentPaths', () => ({
|
|
24
|
-
getComponentPaths: vi.fn(path => [path, 'full'])
|
|
25
|
-
}))
|
|
26
|
-
|
|
27
|
-
describe('ComponentCreator', () => {
|
|
28
|
-
let creator: ComponentCreator
|
|
29
|
-
|
|
30
|
-
beforeEach(() => {
|
|
31
|
-
vi.clearAllMocks()
|
|
32
|
-
creator = new ComponentCreator()
|
|
33
|
-
})
|
|
34
|
-
|
|
35
|
-
it('make should call ComponentItem.make for each empty directory', () => {
|
|
36
|
-
vi.mocked(PropertiesFile.readDirOnlyRecursive).mockReturnValue(['dir1', 'dir2', 'dir3'])
|
|
37
|
-
vi.mocked(PropertiesFile.readDir).mockImplementation((path) => {
|
|
38
|
-
if (Array.isArray(path) && path[0] === 'dir2') return ['file.ts']
|
|
39
|
-
return []
|
|
40
|
-
})
|
|
41
|
-
|
|
42
|
-
creator.make()
|
|
43
|
-
|
|
44
|
-
expect(ComponentItem).toHaveBeenCalledWith('dir1')
|
|
45
|
-
expect(ComponentItem).not.toHaveBeenCalledWith('dir2')
|
|
46
|
-
expect(ComponentItem).toHaveBeenCalledWith('dir3')
|
|
47
|
-
|
|
48
|
-
const mockInstance1 = vi.mocked(ComponentItem).mock.results[0]?.value
|
|
49
|
-
const mockInstance2 = vi.mocked(ComponentItem).mock.results[1]?.value
|
|
50
|
-
|
|
51
|
-
expect(mockInstance1?.make).toHaveBeenCalled()
|
|
52
|
-
expect(mockInstance2?.make).toHaveBeenCalled()
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
it('getDirs should return only empty directories', () => {
|
|
56
|
-
vi.mocked(PropertiesFile.readDirOnlyRecursive).mockReturnValue(['empty', 'not-empty'])
|
|
57
|
-
vi.mocked(PropertiesFile.readDir).mockImplementation((path) => {
|
|
58
|
-
if (Array.isArray(path) && path[0] === 'not-empty') return ['index.ts']
|
|
59
|
-
return []
|
|
60
|
-
})
|
|
61
|
-
|
|
62
|
-
// Access protected method for testing
|
|
63
|
-
const dirs = (creator as any).getDirs()
|
|
64
|
-
|
|
65
|
-
expect(dirs).toContain('empty')
|
|
66
|
-
expect(dirs).not.toContain('not-empty')
|
|
67
|
-
expect(dirs).toHaveLength(1)
|
|
68
|
-
expect(PropertiesFile.readDirOnlyRecursive).toHaveBeenCalledWith(UI_DIRS_COMPONENTS)
|
|
69
|
-
expect(getComponentPaths).toHaveBeenCalledWith('empty')
|
|
70
|
-
})
|
|
71
|
-
})
|
|
@@ -1,71 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it, vi, beforeEach } from 'vitest'
|
|
2
|
-
import { ComponentItem } from '../ComponentItem'
|
|
3
|
-
import { PropertiesFile } from '../../Properties/PropertiesFile'
|
|
4
|
-
import { toKebabCase } from '@dxtmisha/functional-basic'
|
|
5
|
-
|
|
6
|
-
vi.mock('../../Properties/PropertiesFile', () => ({
|
|
7
|
-
PropertiesFile: {
|
|
8
|
-
splitForDir: vi.fn(path => path.split('/')),
|
|
9
|
-
readFile: vi.fn(),
|
|
10
|
-
writeByPath: vi.fn(),
|
|
11
|
-
chmod: vi.fn(),
|
|
12
|
-
readDirRecursive: vi.fn()
|
|
13
|
-
}
|
|
14
|
-
}))
|
|
15
|
-
|
|
16
|
-
vi.mock('../../../functions/getComponentPaths', () => ({
|
|
17
|
-
getComponentPaths: vi.fn(path => [path, 'full'])
|
|
18
|
-
}))
|
|
19
|
-
|
|
20
|
-
describe('ComponentItem', () => {
|
|
21
|
-
let item: ComponentItem
|
|
22
|
-
const mockPath = 'src/components/TestComponent'
|
|
23
|
-
|
|
24
|
-
beforeEach(() => {
|
|
25
|
-
vi.clearAllMocks()
|
|
26
|
-
item = new ComponentItem(mockPath)
|
|
27
|
-
})
|
|
28
|
-
|
|
29
|
-
it('getName should return the last part of the path', () => {
|
|
30
|
-
const name = (item as any).getName()
|
|
31
|
-
expect(name).toBe('TestComponent')
|
|
32
|
-
expect(PropertiesFile.splitForDir).toHaveBeenCalledWith(mockPath)
|
|
33
|
-
})
|
|
34
|
-
|
|
35
|
-
it('getProjectName should return package name or "Project"', () => {
|
|
36
|
-
vi.mocked(PropertiesFile.readFile).mockReturnValue({ name: 'test-project' })
|
|
37
|
-
const projectName = (item as any).getProjectName()
|
|
38
|
-
expect(projectName).toBe('test-project')
|
|
39
|
-
|
|
40
|
-
vi.mocked(PropertiesFile.readFile).mockReturnValue(undefined)
|
|
41
|
-
expect((item as any).getProjectName()).toBe('Project')
|
|
42
|
-
})
|
|
43
|
-
|
|
44
|
-
it('replacement should replace placeholders correctly', () => {
|
|
45
|
-
vi.mocked(PropertiesFile.readFile).mockReturnValue({ name: 'test-project' })
|
|
46
|
-
const content = 'Name: ComponentDoc, kebab: component-doc, project: [project], path: [path]'
|
|
47
|
-
const result = (item as any).replacement(content)
|
|
48
|
-
|
|
49
|
-
expect(result).toContain('Name: TestComponent')
|
|
50
|
-
expect(result).toContain(`kebab: ${toKebabCase('TestComponent')}`)
|
|
51
|
-
expect(result).toContain('project: test-project')
|
|
52
|
-
expect(result).toContain(`path: ${mockPath}`)
|
|
53
|
-
})
|
|
54
|
-
|
|
55
|
-
it('make should read templates and write files with replacements', () => {
|
|
56
|
-
vi.mocked(PropertiesFile.readDirRecursive).mockReturnValue(['Template.ts'])
|
|
57
|
-
vi.mocked(PropertiesFile.readFile).mockImplementation((path) => {
|
|
58
|
-
if (Array.isArray(path) && path.includes('package.json')) return { name: 'test-project' }
|
|
59
|
-
return 'export class ComponentDoc {}'
|
|
60
|
-
})
|
|
61
|
-
|
|
62
|
-
item.make()
|
|
63
|
-
|
|
64
|
-
expect(PropertiesFile.readDirRecursive).toHaveBeenCalled()
|
|
65
|
-
expect(PropertiesFile.writeByPath).toHaveBeenCalledWith(
|
|
66
|
-
expect.arrayContaining([mockPath, 'Template.ts']),
|
|
67
|
-
'export class TestComponent {}'
|
|
68
|
-
)
|
|
69
|
-
expect(PropertiesFile.chmod).toHaveBeenCalled()
|
|
70
|
-
})
|
|
71
|
-
})
|