@dxtmisha/scripts 0.10.7 → 0.10.9
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
CHANGED
|
@@ -2,6 +2,21 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.10.9] - 2026-08-03
|
|
6
|
+
|
|
7
|
+
### Changed
|
|
8
|
+
- **DesignTypes**: Updated AI prompt instructions in `DesignTypes.toAiEdit` and `DesignTypes.toAiDescription`:
|
|
9
|
+
- Enforced strict prompt boundaries forbidding AI agents from analyzing unprovided external files, links, paths, or environment data.
|
|
10
|
+
- Enhanced JSDoc generation rules to generate English JSDocs for non-obvious entities directly from JS implementation code.
|
|
11
|
+
- Expanded project description structure in `toAiDescription` to detail all exposed capabilities and triggers for `ai-types.md` analysis, and added optional `code` parameter support.
|
|
12
|
+
|
|
13
|
+
## [0.10.8] - 2026-07-28
|
|
14
|
+
|
|
15
|
+
### Added / Updated
|
|
16
|
+
- **AI Prompt Templates**: Overhauled global AI prompt templates (`aiCodeGlobalPrompt.en.md`, `aiCodeGlobalPrompt.ru.md`) with streamlined rules, mandatory deep study workflows (`view_file`), prohibition of superficial code scans, and full-file self-audit requirements.
|
|
17
|
+
- **DesignReplace**: Escaped dollar sign (`$`) characters in replacement value strings in `DesignReplace` to prevent regex capture group interpolation issues during template processing.
|
|
18
|
+
- **DesignTypes**: Added JavaScript File Validator and improved TypeScript schema generation and translation logic.
|
|
19
|
+
|
|
5
20
|
## [0.10.7] - 2026-07-06
|
|
6
21
|
|
|
7
22
|
### Changed
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxtmisha/scripts",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.9",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Development scripts and CLI tools for DXT UI projects - automated component generation, library building and project management tools",
|
|
7
7
|
"keywords": [
|
|
@@ -45,12 +45,15 @@ export class DesignTypes {
|
|
|
45
45
|
console.log('DesignTypes: making AI types...')
|
|
46
46
|
|
|
47
47
|
const files = this.getListByFilter()
|
|
48
|
+
const jsFiles = this.getListByFilterJs()
|
|
49
|
+
|
|
48
50
|
const fullContent = this.toOneFile(files)
|
|
51
|
+
const fullJsContent = this.toOneFile(jsFiles)
|
|
49
52
|
|
|
50
|
-
const aiContent = await this.toAiEdit(fullContent)
|
|
53
|
+
const aiContent = await this.toAiEdit(fullContent, fullJsContent)
|
|
51
54
|
this.save(aiContent)
|
|
52
55
|
|
|
53
|
-
const aiDescription = await this.toAiDescription(fullContent)
|
|
56
|
+
const aiDescription = await this.toAiDescription(fullContent, fullJsContent)
|
|
54
57
|
this.saveDescription(aiDescription)
|
|
55
58
|
|
|
56
59
|
console.log('DesignTypes: AI types saved.')
|
|
@@ -75,6 +78,16 @@ export class DesignTypes {
|
|
|
75
78
|
)
|
|
76
79
|
}
|
|
77
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Checks if the file is a valid JavaScript or TypeScript file.
|
|
83
|
+
*
|
|
84
|
+
* Проверяет, является ли файл валидным JavaScript или TypeScript файлом.
|
|
85
|
+
* @param file file name / имя файла
|
|
86
|
+
*/
|
|
87
|
+
protected isFileJs(file: string): boolean {
|
|
88
|
+
return file.endsWith('.js')
|
|
89
|
+
}
|
|
90
|
+
|
|
78
91
|
/**
|
|
79
92
|
* Checks if the content contains type definitions.
|
|
80
93
|
*
|
|
@@ -108,15 +121,16 @@ export class DesignTypes {
|
|
|
108
121
|
}
|
|
109
122
|
|
|
110
123
|
/**
|
|
111
|
-
* Gets a list of files filtered by
|
|
124
|
+
* Gets a list of files filtered by a provided checker function.
|
|
112
125
|
*
|
|
113
|
-
* Получает список файлов, отфильтрованный
|
|
126
|
+
* Получает список файлов, отфильтрованный переданной функцией проверки.
|
|
127
|
+
* @param checkFile function to check if the file matches criteria / функция проверки соответствия файла критериям
|
|
114
128
|
*/
|
|
115
|
-
protected
|
|
129
|
+
protected getListBy(checkFile: (file: string) => boolean): DesignTypesList {
|
|
116
130
|
return forEach(
|
|
117
131
|
this.getList(),
|
|
118
132
|
(file) => {
|
|
119
|
-
if (
|
|
133
|
+
if (checkFile(file)) {
|
|
120
134
|
const content = this.readFile(file)
|
|
121
135
|
|
|
122
136
|
if (this.isContent(content)) {
|
|
@@ -132,6 +146,24 @@ export class DesignTypes {
|
|
|
132
146
|
) as DesignTypesList
|
|
133
147
|
}
|
|
134
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Gets a list of files filtered by criteria.
|
|
151
|
+
*
|
|
152
|
+
* Получает список файлов, отфильтрованный по критериям.
|
|
153
|
+
*/
|
|
154
|
+
protected getListByFilter(): DesignTypesList {
|
|
155
|
+
return this.getListBy(file => this.isFile(file))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Gets a list of JS files filtered by criteria.
|
|
160
|
+
*
|
|
161
|
+
* Получает список JS файлов, отфильтрованный по критериям.
|
|
162
|
+
*/
|
|
163
|
+
protected getListByFilterJs(): DesignTypesList {
|
|
164
|
+
return this.getListBy(file => this.isFileJs(file))
|
|
165
|
+
}
|
|
166
|
+
|
|
135
167
|
/**
|
|
136
168
|
* Reads the content of a file.
|
|
137
169
|
*
|
|
@@ -201,14 +233,23 @@ export class DesignTypes {
|
|
|
201
233
|
* Отправляет контент и промпт ИИ для обработки.
|
|
202
234
|
* @param content content for processing / контент для обработки
|
|
203
235
|
* @param prompt instructions for the AI / инструкции для ИИ
|
|
236
|
+
* @param code code to optimize / код для оптимизации
|
|
204
237
|
*/
|
|
205
|
-
protected async toAi(
|
|
238
|
+
protected async toAi(
|
|
239
|
+
content: string,
|
|
240
|
+
prompt: string,
|
|
241
|
+
code?: string
|
|
242
|
+
): Promise<string | undefined> {
|
|
206
243
|
const ai = useAi()
|
|
207
244
|
|
|
208
245
|
if (ai) {
|
|
209
246
|
ai.addPrompt(prompt)
|
|
210
247
|
ai.addPrompt(`File Content: ${content}`)
|
|
211
248
|
|
|
249
|
+
if (code) {
|
|
250
|
+
ai.addPrompt(`File JS Code: ${code}`)
|
|
251
|
+
}
|
|
252
|
+
|
|
212
253
|
const generate = await ai.generate('go!')
|
|
213
254
|
|
|
214
255
|
if (generate) {
|
|
@@ -224,24 +265,37 @@ export class DesignTypes {
|
|
|
224
265
|
*
|
|
225
266
|
* Отправляет контент ИИ для оптимизации.
|
|
226
267
|
* @param content content to optimize / контент для оптимизации
|
|
268
|
+
* @param code code to optimize / код для оптимизации
|
|
227
269
|
*/
|
|
228
|
-
protected async toAiEdit(content: string): Promise<string> {
|
|
270
|
+
protected async toAiEdit(content: string, code: string): Promise<string> {
|
|
229
271
|
const generate = await this.toAi(
|
|
230
272
|
content,
|
|
231
|
-
'
|
|
232
|
-
+ '
|
|
233
|
-
+ '
|
|
234
|
-
+ '
|
|
235
|
-
+ '
|
|
236
|
-
+ '
|
|
237
|
-
+ '
|
|
238
|
-
+ '
|
|
239
|
-
+ '
|
|
240
|
-
+ '
|
|
241
|
-
+ '
|
|
242
|
-
+ '
|
|
243
|
-
+ '
|
|
244
|
-
+ '
|
|
273
|
+
'Goal: Optimize and generate clean, highly informative TypeScript type definitions based ONLY on the provided code and types.\n\n'
|
|
274
|
+
+ 'CRITICAL CONTEXT & SCOPE RESTRICTIONS:\n'
|
|
275
|
+
+ '- IMPORTANT: The AI coding agent that will write code for developers using this library will NEVER see or have access to the underlying JS implementation code or external files. It will rely EXCLUSIVELY on the output document generated by you in this session. You MUST ensure that your output provides complete, flawless context, clear JSDoc explanations, and precise type contracts so that the reading AI agent can write accurate code without making assumptions.\n'
|
|
276
|
+
+ '- Analyze ONLY the code, type definitions, and text explicitly provided in this prompt. Do NOT attempt to read, search, infer, or assume any external files, imports, project structure, or unprovided environment data.\n'
|
|
277
|
+
+ '- Do NOT include any references, links, file paths, or pointers to external files or local directories in the final output, as AI agents will have no environment file access.\n'
|
|
278
|
+
+ '- Do NOT return the provided JS code in your response.\n\n'
|
|
279
|
+
+ 'JSDOC & COMMENT RULES:\n'
|
|
280
|
+
+ '- STUDY THE PROVIDED JS CODE: You are explicitly provided with the JS implementation code (`File JS Code`). You MUST study the JS code for every function/method/property to understand its exact logic, behavior, and purpose.\n'
|
|
281
|
+
+ '- GENERATE MISSING JSDOCS FROM JS CODE: If an entity lacks a JSDoc comment in the input declarations, but its provided JS code implementation reveals its behavior or purpose, you MUST generate and add a clear, fluff-free English JSDoc description directly above its declaration.\n'
|
|
282
|
+
+ '- DEFINITION OF OBVIOUS (NO JSDOC): An entity is "obvious" ONLY IF its name uses clear, standard English naming conventions (e.g., `isString`, `capitalize`, `copyObject`) AND its functionality is 100% self-evident from its signature alone. Obvious entities MUST NOT have a JSDoc.\n'
|
|
283
|
+
+ '- MANDATORY JSDOC FOR NON-OBVIOUS ENTITIES: Any entity with an obscure, non-standard, custom, abbreviated, or ambiguous name (e.g., `abutaSudatoho`, `transformation`), or complex logic, MUST have a clear English JSDoc description generated by inspecting its JS implementation code.\n'
|
|
284
|
+
+ '- Write JSDoc comments WITHOUT fluff or filler text, focusing strictly on operational logic and behavior.\n'
|
|
285
|
+
+ '- Place all JSDoc comments STRICTLY directly above the target declaration.\n'
|
|
286
|
+
+ '- Translate all non-English comments and JSDocs to English.\n'
|
|
287
|
+
+ '- Remove regular inline comments (`//` or `/* ... */`).\n'
|
|
288
|
+
+ '- STRICTLY PRESERVE all JSDoc tags like `@example`, `@remarks`, `@note`, and warnings—keep them intact, translating only to English if needed.\n\n'
|
|
289
|
+
+ 'CLEANING & OPTIMIZATION:\n'
|
|
290
|
+
+ '- Remove all `import` statements and local internal re-exports (e.g., `export * from "./..."`). Strictly KEEP exports from external packages.\n'
|
|
291
|
+
+ '- Delete all non-public content (private/protected class members, unexported elements). Keep all public API surfaces.\n'
|
|
292
|
+
+ '- Do NOT delete any `type` definitions; they are strictly required.\n'
|
|
293
|
+
+ '- Remove large Enums or structures that add length without critical context.\n'
|
|
294
|
+
+ '- Exercise extreme caution when removing abstract classes: if there is even a 5% chance it helps understand the API or generate code, keep it.\n'
|
|
295
|
+
+ '- Format output tightly with no blank lines.\n\n'
|
|
296
|
+
+ 'OUTPUT REQUIREMENTS:\n'
|
|
297
|
+
+ 'Return ONLY the resulting optimized TypeScript type definitions code. No markdown formatting, no code blocks (```), no explanations, and no additional AI text. NOTHING but pure code.',
|
|
298
|
+
code
|
|
245
299
|
)
|
|
246
300
|
|
|
247
301
|
return generate ?? content
|
|
@@ -252,20 +306,24 @@ export class DesignTypes {
|
|
|
252
306
|
*
|
|
253
307
|
* Генерирует описание проекта и рекомендации по использованию с помощью ИИ.
|
|
254
308
|
* @param content cleaned type definitions / очищенные определения типов
|
|
309
|
+
* @param code JS code for analysis / JS код для анализа
|
|
255
310
|
*/
|
|
256
|
-
protected async toAiDescription(content: string): Promise<string> {
|
|
311
|
+
protected async toAiDescription(content: string, code?: string): Promise<string> {
|
|
257
312
|
const generate = await this.toAi(
|
|
258
313
|
content,
|
|
259
|
-
'
|
|
260
|
-
+ '
|
|
261
|
-
+ '
|
|
262
|
-
+ '
|
|
263
|
-
+ '
|
|
264
|
-
+ '
|
|
265
|
-
+ '
|
|
266
|
-
+ '
|
|
267
|
-
+ '
|
|
268
|
-
+ '
|
|
314
|
+
'Goal: Generate a comprehensive, highly technical, and fluff-free project overview designed for an AI coding assistant to evaluate this library\'s exact contents and capabilities.\n\n'
|
|
315
|
+
+ 'CRITICAL RESTRICTIONS:\n'
|
|
316
|
+
+ '- Analyze ONLY the code, type definitions, and text explicitly provided in this prompt. Do NOT attempt to read, search, infer, or assume any external files, dependencies, or unprovided data.\n'
|
|
317
|
+
+ '- Do NOT include any file paths, relative links, or external URLs, as reading AI agents will not have environment file access.\n\n'
|
|
318
|
+
+ 'STRUCTURE & CONTENT REQUIREMENTS:\n'
|
|
319
|
+
+ 'Provide an objective, dense, and complete technical summary including:\n'
|
|
320
|
+
+ '1. Core Purpose: What is the primary technical function, responsibility, and role of this library?\n'
|
|
321
|
+
+ '2. Key Expositions & Capabilities: Detail ALL main classes, composables/hooks, utilities, components, services, or data structures exposed by this library. Specify the exact functionality and specific tasks each exposed entity or module performs so reading AI agents clearly understand the full capability set.\n'
|
|
322
|
+
+ '3. Triggers for Studying ai-types.md: Under what specific coding requirements, keywords, tasks, or architectural needs is this library indispensable, making it mandatory for the AI to study "ai-types.md"?\n'
|
|
323
|
+
+ '4. Integration Context: How does this library connect with other technologies, frameworks, or packages in the system stack?\n\n'
|
|
324
|
+
+ 'OUTPUT REQUIREMENTS:\n'
|
|
325
|
+
+ 'Return ONLY the resulting description text. No markdown formatting, no code blocks, no labels (like "Description:"), and no conversational explanations. NOTHING but pure, dense content.',
|
|
326
|
+
code
|
|
269
327
|
)
|
|
270
328
|
|
|
271
329
|
return generate ?? ''
|
|
@@ -1,78 +1,21 @@
|
|
|
1
1
|
### Global Development Principles (AI Code Promise)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
0. **Mandatory Deep Study**:
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
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
|
-
- DO NOT specify absolute file paths (e.g., file:///... or machine-specific directories like /Users/...) in the memory file. All references to files inside the project must use relative paths (e.g., src/types/textTypes.ts) so that the file works seamlessly for other developers on different operating systems and computers.
|
|
78
|
-
|
|
3
|
+
Strictly follow these rules for flawless dxt-ui code:
|
|
4
|
+
|
|
5
|
+
0. **Mandatory Deep Study (CHRONOLOGICAL GUARD)**:
|
|
6
|
+
- **Step 1**: Read/create local `ai-memory.md` strictly in the current package root (e.g., `packages/constructor/`). Using repository root `ai-memory.md` for package files is FORBIDDEN.
|
|
7
|
+
- **Step 2**: Read root `ai-prompt.md` and study descriptions of all mentioned libraries.
|
|
8
|
+
- **Step 3**: Read all linked `ai-types.md` and `ai-developer.md` BEFORE proposing plans, calling `list_dir`, or writing code. If a package is in `node_modules/` but exists locally (e.g., `packages/`), resolve and study the local source instead.
|
|
9
|
+
- Fully read files via `view_file` before modifying. Superficial scans (grep only) are strictly forbidden. Always check existing infrastructure before writing custom logic.
|
|
10
|
+
|
|
11
|
+
1. **"Copy-Paste Ready"**: Generate complete, runnable files with correct imports. No placeholders (e.g., `// rest of code`).
|
|
12
|
+
2. **Zero Hallucinations**: Strictly use `package.json` dependencies. No invented APIs. Ask if unsure.
|
|
13
|
+
3. **Clean Code (DRY/KISS/SOLID)**: Declarative style. Single responsibility (1 task = 1 function). No abbreviations (`el`, `val`, etc. are forbidden). Optimized and legible.
|
|
14
|
+
4. **Uncompromising TS**: No `any` (use `unknown` or generics). Interfaces for all I/O. `as const`, `readonly`, enums. Use `@ts-expect-error` with comments, never `@ts-ignore`.
|
|
15
|
+
5. **Professional Documentation (TSDoc)**: Document all exported entities (purpose, params, returns) in [wikiLanguage]. Include examples for complex logic.
|
|
16
|
+
6. **Architectural Consistency**: Respect project structure. Reuse existing infrastructure (always check `ai-types.md` first). Do not modify global/base UI styles unless explicitly requested.
|
|
17
|
+
7. **Security & Performance**: Error-proof code (`?.`, `??`, guard clauses). Use explicit `try-catch` for async. Never swallow errors. Avoid heavy ops in loops/reactivity.
|
|
18
|
+
8. **Aesthetics & Conciseness**: Group logically. Save tokens by avoiding redundant comments if code is self-explanatory.
|
|
19
|
+
9. **Strict Adherence & Optimization**: Follow instructions precisely without guessing. Propose relevant technical optimizations while strictly adhering to plans.
|
|
20
|
+
10. **AI Workspace Memory (`ai-memory.md`)**: Actively APPLY its rules (highest priority). Update it on developer feedback. Do NOT store change logs or absolute paths (use relative). Keep it focused strictly on architectural constraints.
|
|
21
|
+
11. **Mandatory Full-File Self-Audit**: When creating new entities, you MUST audit the ENTIRE file (not just modified parts) to ensure no logic duplication (DRY) and full compliance with project rules. *Exception: minor bug fixes to existing code do not require a full audit.*
|
|
@@ -1,79 +1,21 @@
|
|
|
1
1
|
### Глобальные принципы разработки (AI Code Promise)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
0. **Обязательное глубокое
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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»). Файл должен содержать только актуальные стандарты, правила разработки и конструктивные требования к коду.
|
|
79
|
-
- ЗАПРЕЩЕНО указывать абсолютные пути к файлам (например, file:///... или локальные пути вроде /Users/...) в файле памяти. Все ссылки на файлы внутри проекта должны использовать относительные пути (например, src/types/textTypes.ts), чтобы этот файл корректно работал у других разработчиков на разных компьютерах и операционных системах.
|
|
3
|
+
Строго следуй этим правилам для создания безупречного кода dxt-ui:
|
|
4
|
+
|
|
5
|
+
0. **Обязательное глубокое изучение (БЛОКИРУЮЩИЙ КОНТРОЛЬ)**:
|
|
6
|
+
- **Шаг 1**: Читай/создавай локальный `ai-memory.md` СТРОГО в корне текущего пакета (напр., `packages/constructor/`). Использовать корневой `ai-memory.md` репозитория для файлов пакета ЗАПРЕЩЕНО.
|
|
7
|
+
- **Шаг 2**: Прочитай корневой `ai-prompt.md` и изучи описания всех упомянутых библиотек.
|
|
8
|
+
- **Шаг 3**: Прочитай все связанные `ai-types.md` и `ai-developer.md` ДО вызова `list_dir`, планирования или написания кода. Если пакет в `node_modules/` существует локально (в `packages/`), изучай/изменяй локальные исходники.
|
|
9
|
+
- Полностью читай файлы через `view_file` перед изменением. Поверхностное изучение (только grep) запрещено. Всегда проверяй существующую инфраструктуру перед написанием кастомной логики.
|
|
10
|
+
|
|
11
|
+
1. **Готовность к использованию (Copy-Paste Ready)**: Генерируй полные, рабочие файлы с правильными импортами. Никаких заглушек (напр., `// остальной код`).
|
|
12
|
+
2. **Нулевая толерантность к галлюцинациям**: Используй только зависимости из `package.json`. Не выдумывай API. Не знаешь — спроси.
|
|
13
|
+
3. **Чистый код (DRY/KISS/SOLID)**: Декларативный стиль. Единая ответственность (1 задача = 1 функция). Запрет на сокращения (никаких `el`, `val`, `temp` и т.д.). Оптимизация и читаемость.
|
|
14
|
+
4. **Бескомпромиссный TS**: Никаких `any` (используй `unknown` или generics). Интерфейсы для всех I/O. `as const`, `readonly`, enums. Только `@ts-expect-error` с комментариями, никогда `@ts-ignore`.
|
|
15
|
+
5. **TSDoc документирование**: Документируй все экспорты (назначение, параметры, возвраты) на языке [wikiLanguage]. Примеры для сложной логики.
|
|
16
|
+
6. **Архитектурная консистентность**: Соблюдай структуру. Переиспользуй инфраструктуру (сначала всегда читай `ai-types.md`). Не меняй глобальные/базовые UI стили без явного запроса.
|
|
17
|
+
7. **Безопасность и Производительность**: Защищенный код (`?.`, `??`, guard clauses). Явный `try-catch` для асинхронности. Не скрывай ошибки. Избегай тяжелых операций в циклах/реактивности.
|
|
18
|
+
8. **Эстетика и Лаконичность**: Логическая группировка. Экономь токены, избегая избыточных комментариев, если код очевиден.
|
|
19
|
+
9. **Строгое следование инструкциям**: Выполняй команды без додумывания, но предлагай уместные технические оптимизации, придерживаясь плана.
|
|
20
|
+
10. **Память ИИ (`ai-memory.md`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй при правках от разработчика. ЗАПРЕЩЕНО хранить историю изменений (changelogs) и абсолютные пути (только относительные). Только актуальные стандарты.
|
|
21
|
+
11. **Обязательный полный самоаудит**: При создании новых сущностей ОБЯЗАТЕЛЬНО проверяй ВЕСЬ файл целиком. Строго контролируй отсутствие дублирования (DRY) и соблюдение всех правил проекта. *Исключение: мелкие правки существующего кода не требуют полного аудита.*
|