@dxtmisha/scripts 0.10.15 → 0.11.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.
@@ -0,0 +1,289 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { forEach, isFilled } from '@dxtmisha/functional-basic'
3
+ import { PropertiesFile } from '../Properties/PropertiesFile'
4
+ import { DesignTypesAi } from './DesignTypesAi'
5
+
6
+ import type {
7
+ DesignTypesItem,
8
+ DesignTypesList,
9
+ DesignTypesPromptCacheItem,
10
+ DesignTypesPromptCacheList,
11
+ DesignTypesPromptData,
12
+ DesignTypesPromptResult
13
+ } from '../../types/designTypes'
14
+
15
+ import { UI_MODULES } from '../../config'
16
+
17
+ /**
18
+ * Class for reading prompt files and generating AI project rules and prompt triggers description.
19
+ *
20
+ * Класс для чтения файлов промптов и генерации описания правил проекта ИИ и триггеров промптов.
21
+ */
22
+ export class DesignTypesPrompts {
23
+ /** Cached list of prompt files / Кэшированный список файлов с промптами */
24
+ protected listPrompts?: DesignTypesList
25
+
26
+ /** Cached prompt AI metadata list / Кэшированный список метаданных промптов ИИ */
27
+ protected cacheList?: DesignTypesPromptCacheList
28
+
29
+ /**
30
+ * Constructor for DesignTypesPrompts.
31
+ *
32
+ * Конструктор для DesignTypesPrompts.
33
+ * @param promptsDir input directory path containing prompt files / входной путь к директории, содержащей файлы промптов
34
+ * @param ai instance of DesignTypesAi for AI interactions / экземпляр DesignTypesAi для ИИ взаимодействия
35
+ */
36
+ constructor(
37
+ protected readonly promptsDir: string = 'ai-resources',
38
+ protected readonly ai: DesignTypesAi
39
+ ) { }
40
+
41
+ /**
42
+ * Reads and returns the prompt cache list from the JSON cache file.
43
+ *
44
+ * Читает и возвращает список кэша промптов из JSON файла кэша.
45
+ * @returns prompt cache list / список кэша промптов
46
+ */
47
+ getCacheList(): DesignTypesPromptCacheList {
48
+ if (this.cacheList === undefined) {
49
+ const cachePath = this.getCachePath()
50
+ const data = PropertiesFile.readFile<DesignTypesPromptCacheList>(cachePath)
51
+
52
+ this.cacheList = Array.isArray(data) ? data : []
53
+ }
54
+
55
+ return this.cacheList
56
+ }
57
+
58
+ /**
59
+ * Gets a list of prompt files.
60
+ *
61
+ * Получает список файлов с промптами.
62
+ * @returns list of prompt files / список файлов с промптами
63
+ */
64
+ getListPrompts(): DesignTypesList {
65
+ if (this.listPrompts === undefined) {
66
+ const files = PropertiesFile.readDirRecursive(this.promptsDir)
67
+
68
+ this.listPrompts = forEach(
69
+ files,
70
+ (file) => {
71
+ if (file.endsWith('.json')) {
72
+ return undefined
73
+ }
74
+
75
+ const path = `${this.promptsDir}/${file}`
76
+ const content = PropertiesFile.readFileOnly(path)
77
+
78
+ if (content) {
79
+ return {
80
+ path,
81
+ content,
82
+ md5: this.getMd5(content)
83
+ }
84
+ }
85
+ }
86
+ ) as DesignTypesList
87
+ }
88
+
89
+ return this.listPrompts
90
+ }
91
+
92
+ /**
93
+ * Initializes prompt rules by executing cache processing and returning formatted prompt rule strings.
94
+ *
95
+ * Инициализирует правила промптов, выполняя обработку кэша и возвращая список отформатированных строк правил промптов.
96
+ * @returns array of formatted prompt rule strings / массив отформатированных строк правил промптов
97
+ */
98
+ async init(): Promise<string[]> {
99
+ await this.make()
100
+
101
+ const list = this.getListPrompts()
102
+ const cache = this.getCacheList()
103
+ const prompts: string[] = []
104
+
105
+ for (const item of list) {
106
+ const cachedItem = cache.find(itemCache => itemCache.path === item.path)
107
+
108
+ if (cachedItem && isFilled(cachedItem.description)) {
109
+ prompts.push(this.getPromptLine(item.path, cachedItem.description))
110
+ }
111
+ }
112
+
113
+ return prompts
114
+ }
115
+
116
+ /**
117
+ * Processes prompt files using AI and updates the JSON cache file if changes are detected.
118
+ *
119
+ * Обрабатывает файлы промптов с помощью ИИ и обновляет JSON файл кэша при обнаружении изменений.
120
+ * @returns current instance / текущий экземпляр
121
+ */
122
+ async make(): Promise<this> {
123
+ const list = this.getListPrompts()
124
+ let isCacheChanged = false
125
+
126
+ for (const item of list) {
127
+ const result = await this.toAiPromptItem(item)
128
+
129
+ if (result.isChanged) {
130
+ isCacheChanged = true
131
+ }
132
+ }
133
+
134
+ if (isCacheChanged) {
135
+ this.saveCacheList(this.getCacheList())
136
+ }
137
+
138
+ return this
139
+ }
140
+
141
+ /**
142
+ * Generates project rules and prompt triggers description using AI.
143
+ *
144
+ * Генерирует описание правил проекта и триггеров промптов с помощью ИИ.
145
+ * @returns prompt rules description / описание правил промптов
146
+ */
147
+ async toAiPrompts(): Promise<string> {
148
+ const prompts = await this.init()
149
+
150
+ if (prompts.length > 0) {
151
+ return '## Mandatory Rules\n'
152
+ + 'You MUST evaluate whether your task relates to any of the following topics (even if not working directly with this package). If related material is present, you are strictly obligated to read and study the corresponding file before proceeding:\n'
153
+ + `${prompts.join('\n')}`
154
+ }
155
+
156
+ return ''
157
+ }
158
+
159
+ /**
160
+ * Gets the cache JSON file path for prompts.
161
+ *
162
+ * Получает путь к JSON файлу кэша для промптов.
163
+ * @returns cache JSON file path / путь к JSON файлу кэша
164
+ */
165
+ protected getCachePath(): string {
166
+ return `${this.promptsDir}/prompts.json`
167
+ }
168
+
169
+ /**
170
+ * Generates MD5 hash for the given content.
171
+ *
172
+ * Генерирует MD5 хэш для переданного содержимого.
173
+ * @param content file or text content / содержимое файла или текста
174
+ * @returns MD5 hash string / MD5 хэш строка
175
+ */
176
+ protected getMd5(content: string): string {
177
+ return createHash('md5').update(content.trim()).digest('hex')
178
+ }
179
+
180
+ /**
181
+ * Formats a prompt rule entry line for a file and description.
182
+ *
183
+ * Форматирует строку элемента правила промпта для файла и описания.
184
+ * @param path relative file path / относительный путь к файлу
185
+ * @param description rule description / описание правила
186
+ * @returns formatted prompt rule line / отформатированная строка правила промпта
187
+ */
188
+ protected getPromptLine(
189
+ path: string,
190
+ description: string
191
+ ): string {
192
+ return `- '${UI_MODULES}/${this.ai.getProjectName()}/${path}': ${description}`
193
+ }
194
+
195
+ /**
196
+ * Saves the prompt cache list to the JSON cache file.
197
+ *
198
+ * Сохраняет список кэша промптов в JSON файл кэша.
199
+ * @param cache cache list to save / список кэша для сохранения
200
+ */
201
+ protected saveCacheList(cache: DesignTypesPromptCacheList): void {
202
+ this.cacheList = cache
203
+ PropertiesFile.writeByPath(this.getCachePath(), cache)
204
+ }
205
+
206
+ /**
207
+ * Generates document metadata (title and description) for studying a prompt file using AI.
208
+ *
209
+ * Генерирует метаданные документа (название и описание) для изучения файла промпта с помощью ИИ.
210
+ * @param content prompt file content / содержимое файла промпта
211
+ * @returns object with document title and description or undefined / объект с названием и описанием документа или undefined
212
+ */
213
+ protected async toAiPromptData(content: string): Promise<DesignTypesPromptData | undefined> {
214
+ return this.ai.toAiJson<DesignTypesPromptData>(
215
+ content,
216
+ 'Goal: Generate a document metadata object in valid JSON format for an AI coding assistant.\n\n'
217
+ + 'CRITICAL RESTRICTIONS:\n'
218
+ + '- The output MUST be a valid JSON object with keys: "name" and "description".\n'
219
+ + '- Field "name": Short and concise document title (maximum 4-5 words).\n'
220
+ + '- Field "description": Clear description for an AI agent explaining what exact standards, rules, or tools this file contains and what commercial or technical task it solves (maximum 3 sentences).\n'
221
+ + '- Do NOT include markdown code block wrappers (```json). Return ONLY the raw JSON string.\n\n'
222
+ + 'EXAMPLES OF GOOD OUTPUT:\n'
223
+ + '{\n'
224
+ + ' "name": "Coding Standards",\n'
225
+ + ' "description": "Строгие архитектурные конвенции и стандарты написания кода для продукта"\n'
226
+ + '}\n\n'
227
+ + 'OUTPUT REQUIREMENTS:\n'
228
+ + 'Return ONLY the JSON object. No explanations, no markdown formatting, no conversational text.'
229
+ )
230
+ }
231
+
232
+ /**
233
+ * Processes a single prompt file item using cache or AI into a formatted rule entry string and updates cache list if changed.
234
+ *
235
+ * Обрабатывает один элемент файла промпта с использованием кэша или ИИ в отформатированную строку правила и обновляет список кэша при изменениях.
236
+ * @param item prompt file item / элемент файла промпта
237
+ * @returns object with formatted rule string and changed flag / объект с отформатированной строкой правила и флагом изменений
238
+ */
239
+ protected async toAiPromptItem(
240
+ item: DesignTypesItem
241
+ ): Promise<DesignTypesPromptResult> {
242
+ const md5 = item.md5 ?? this.getMd5(item.content)
243
+ const cache = this.getCacheList()
244
+ const cacheIndex = cache.findIndex(itemCache => itemCache.path === item.path)
245
+ const cachedItem = cacheIndex >= 0 ? cache[cacheIndex] : undefined
246
+
247
+ if (
248
+ cachedItem
249
+ && cachedItem.md5 === md5
250
+ && isFilled(cachedItem.name)
251
+ && isFilled(cachedItem.description)
252
+ ) {
253
+ return {
254
+ prompt: this.getPromptLine(item.path, cachedItem.description),
255
+ isChanged: false
256
+ }
257
+ }
258
+
259
+ console.log(`-- processing prompt metadata for ${item.path}...`)
260
+
261
+ const data = await this.toAiPromptData(item.content)
262
+
263
+ if (
264
+ data
265
+ && isFilled(data.name)
266
+ && isFilled(data.description)
267
+ ) {
268
+ const newItem: DesignTypesPromptCacheItem = {
269
+ path: item.path,
270
+ md5,
271
+ name: data.name,
272
+ description: data.description
273
+ }
274
+
275
+ if (cacheIndex >= 0) {
276
+ cache[cacheIndex] = newItem
277
+ } else {
278
+ cache.push(newItem)
279
+ }
280
+
281
+ return {
282
+ prompt: this.getPromptLine(item.path, data.description),
283
+ isChanged: true
284
+ }
285
+ }
286
+
287
+ return { isChanged: false }
288
+ }
289
+ }
package/src/config.ts CHANGED
@@ -25,6 +25,8 @@ export const UI_DIR_IN = 'src'
25
25
  export const UI_DIR_AI = 'ai'
26
26
  /** Screenshot folder name for AI / Название папки со снимками экрана для AI */
27
27
  export const UI_DIR_AI_PROMPT_SCREENSHOT = 'ai-screenshot'
28
+ /** AI types list directory name / Название директории со списком типов AI */
29
+ export const UI_DIR_AI_TYPES_LIST = 'ai-types-list'
28
30
  /** Components directory name/ Название директории компонентов */
29
31
  export const UI_DIR_COMPONENTS = 'components'
30
32
  /** Constructors directory name/ Название директории конструкторов */
package/src/library.ts CHANGED
@@ -1,68 +1,73 @@
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/LibraryAiMcpItem'
38
- export * from './classes/Library/LibraryAiPrompt'
39
- export * from './classes/Library/LibraryAiPromptItem'
40
- export * from './classes/Library/LibraryAiWiki'
41
- export * from './classes/Library/LibraryAiWikiItem'
42
- export * from './classes/Library/LibraryExport'
43
- export * from './classes/Library/LibraryList'
44
- export * from './classes/Library/LibraryPlugin'
45
- export * from './classes/Library/LibraryTypes'
46
- export * from './classes/Package/PackageFile'
47
- export * from './classes/Properties/PropertiesFile'
48
-
49
- // Composables
50
- export * from './composables/useAi'
51
-
52
- // Functions
53
- export * from './functions/getConfigAi'
54
- export * from './functions/getDirname'
55
- export * from './functions/getPackageJson'
56
- export * from './functions/hasNativeDirname'
57
- export * from './functions/run'
58
-
59
- // Types
60
- export * from './types/aiTypes'
61
- export * from './types/configTypes'
62
- export * from './types/designTypes'
63
- export * from './types/figmaApiTypes'
64
- export * from './types/gitTypes'
65
- export * from './types/libraryTypes'
66
- export * from './types/propertyTypes'
67
- export * from './types/screenshotTypes'
68
- export * from './types/webTypes'
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/DesignTypesAi'
33
+ export * from './classes/Design/DesignTypesDescription'
34
+ export * from './classes/Design/DesignTypesMake'
35
+ export * from './classes/Design/DesignTypesMcp'
36
+ export * from './classes/Design/DesignTypesPrompts'
37
+ export * from './classes/Design/DesignTypescript'
38
+ export * from './classes/Design/DesignWikiStorm'
39
+ export * from './classes/Design/DesignWikiStormItem'
40
+ export * from './classes/FigmaApi'
41
+ export * from './classes/Git/GitRead'
42
+ export * from './classes/Library/LibraryAiMcpItem'
43
+ export * from './classes/Library/LibraryAiPrompt'
44
+ export * from './classes/Library/LibraryAiPromptItem'
45
+ export * from './classes/Library/LibraryAiWiki'
46
+ export * from './classes/Library/LibraryAiWikiItem'
47
+ export * from './classes/Library/LibraryExport'
48
+ export * from './classes/Library/LibraryList'
49
+ export * from './classes/Library/LibraryPlugin'
50
+ export * from './classes/Library/LibraryTypes'
51
+ export * from './classes/Package/PackageFile'
52
+ export * from './classes/Properties/PropertiesFile'
53
+
54
+ // Composables
55
+ export * from './composables/useAi'
56
+
57
+ // Functions
58
+ export * from './functions/getConfigAi'
59
+ export * from './functions/getDirname'
60
+ export * from './functions/getPackageJson'
61
+ export * from './functions/hasNativeDirname'
62
+ export * from './functions/run'
63
+
64
+ // Types
65
+ export * from './types/aiTypes'
66
+ export * from './types/configTypes'
67
+ export * from './types/designTypes'
68
+ export * from './types/figmaApiTypes'
69
+ export * from './types/gitTypes'
70
+ export * from './types/libraryTypes'
71
+ export * from './types/propertyTypes'
72
+ export * from './types/screenshotTypes'
73
+ export * from './types/webTypes'
@@ -11,6 +11,8 @@ node_modules
11
11
  dist-ssr
12
12
  *.local
13
13
 
14
+ ai-types.md
15
+
14
16
  # Editor directories and files
15
17
  .vscode/*
16
18
  !.vscode/extensions.json
@@ -7,7 +7,7 @@
7
7
  - **Lists (v-for)**: Always use a unique `:key`. Avoid using the array index as a key.
8
8
  - **Directives**: Never use `v-if` on the same element as `v-for`.
9
9
  - **Reactivity**: Use `ref` for data. Calculate complex logic via `computed`.
10
- - **Logic**: ALL logic must be moved to Composables. The component should only contain the composable call and the template.
10
+ - **Logic**: Extract only complex logic into Composables. Simple logic or calling existing hooks (even multiple) does not need to be extracted into a separate composable.
11
11
  - **Templates**: Cleanest possible HTML. No function calls, calculations, or inline styles. If complex logic is needed, split into sub-components.
12
12
  - **Props**: One-way data flow. Never mutate incoming props.
13
13
  - **Events**: Event names must be strictly in kebab-case.
@@ -7,7 +7,7 @@
7
7
  - **Списки (v-for)**: Всегда используй уникальный `:key`. Избегай использования индекса массива в качестве ключа.
8
8
  - **Директивы**: Никогда не используй `v-if` на том же элементе, что и `v-for`.
9
9
  - **Реактивность**: Используй `ref` для данных. Сложную логику вычисляй через `computed`.
10
- - **Логика**: ВСЯ логика должна быть вынесена в Composables. Компонент должен содержать только вызов composable и шаблон.
10
+ - **Логика**: Выноси в Composables только сложную объёмную логику. Простую логику или прямое использование готовых хуков (даже нескольких) выносить в отдельный composable не требуется.
11
11
  - **Шаблоны**: Максимально чистый HTML. Никаких вызовов функций, вычислений или инлайн-стилей. Если нужна сложная логика — разделяй на подкомпоненты.
12
12
  - **Props**: Односторонний поток данных. Никогда не мутируй входящие пропсы.
13
13
  - **События**: Названия событий — строго в kebab-case.
@@ -107,13 +107,50 @@ export type DesignTypescriptItem = {
107
107
  /** List of TypeScript items / Список TypeScript элементов */
108
108
  export type DesignTypescriptList = DesignTypescriptItem[]
109
109
 
110
+ /** Design types item / Элемент типов дизайна */
110
111
  export type DesignTypesItem = {
112
+ /** Relative file path / Относительный путь к файлу */
111
113
  path: string
114
+ /** File content / Содержимое файла */
112
115
  content: string
116
+ /** MD5 hash string / Строка MD5 хэша */
117
+ md5?: string
113
118
  }
114
119
 
120
+ /** List of design types items / Список элементов типов дизайна */
115
121
  export type DesignTypesList = DesignTypesItem[]
116
122
 
123
+ /** Design types prompt cache item / Элемент кэша промпта типов дизайна */
124
+ export type DesignTypesPromptCacheItem = {
125
+ /** Relative file path / Относительный путь к файлу */
126
+ path: string
127
+ /** MD5 hash string / Строка MD5 хэша */
128
+ md5: string
129
+ /** Document title / Название документа */
130
+ name: string
131
+ /** Document description / Описание документа */
132
+ description: string
133
+ }
134
+
135
+ /** List of design types prompt cache items / Список элементов кэша промптов типов дизайна */
136
+ export type DesignTypesPromptCacheList = DesignTypesPromptCacheItem[]
137
+
138
+ /** Design types prompt data item / Элемент данных промпта типов дизайна */
139
+ export type DesignTypesPromptData = {
140
+ /** Document title / Название документа */
141
+ name?: string
142
+ /** Document description / Описание документа */
143
+ description?: string
144
+ }
145
+
146
+ /** Design types prompt item result / Результат обработки элемента промпта типов дизайна */
147
+ export type DesignTypesPromptResult = {
148
+ /** Formatted prompt rule string / Отформатированная строка правила промпта */
149
+ prompt?: string
150
+ /** Flag indicating whether the cache was changed / Флаг указывающий был ли изменен кэш */
151
+ isChanged: boolean
152
+ }
153
+
117
154
  /** Design MCP resource item / Элемент ресурса MCP дизайна */
118
155
  export type DesignMcpResourceItem = {
119
156
  /** Resource URI / URI ресурса */