@dxtmisha/scripts 0.7.9 → 0.7.11

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.
@@ -1,4 +1,4 @@
1
- import { forEach } from '@dxtmisha/functional-basic'
1
+ import { forEach, ServerStorage } from '@dxtmisha/functional-basic'
2
2
  import { getPackageJson } from '../../functions/getPackageJson'
3
3
  import { useAi } from '../../composables/useAi'
4
4
 
@@ -6,7 +6,7 @@ import { PropertiesFile } from '../Properties/PropertiesFile'
6
6
 
7
7
  import type { DesignTypesList } from '../../types/designTypes'
8
8
 
9
- import { UI_DIR_CONSTRUCTOR, UI_FILE_AI_TYPES } from '../../config'
9
+ import { UI_DIR_CONSTRUCTOR, UI_FILE_AI_DESCRIPTION, UI_FILE_AI_TYPES } from '../../config'
10
10
 
11
11
  /**
12
12
  * Engine for generating compressed and AI-optimized TypeScript type definitions.
@@ -32,6 +32,7 @@ export class DesignTypes {
32
32
  constructor(
33
33
  protected readonly dir: string = 'dist'
34
34
  ) {
35
+ ServerStorage.setErrorStatus(true)
35
36
  this.dirArray = this.dir.split('/')
36
37
  }
37
38
 
@@ -40,19 +41,19 @@ export class DesignTypes {
40
41
  *
41
42
  * Основной метод для выполнения процесса генерации типов.
42
43
  */
43
- make() {
44
+ async make() {
44
45
  console.log('DesignTypes: making AI types...')
45
46
 
46
47
  const files = this.getListByFilter()
47
48
  const fullContent = this.toOneFile(files)
48
49
 
49
- this.toAiEdit(fullContent).then(
50
- (aiContent) => {
51
- this.save(aiContent)
50
+ const aiContent = await this.toAiEdit(fullContent)
51
+ this.save(aiContent)
52
52
 
53
- console.log('DesignTypes: AI types saved.')
54
- }
55
- )
53
+ const aiDescription = await this.toAiDescription(fullContent)
54
+ this.saveDescription(aiDescription)
55
+
56
+ console.log('DesignTypes: AI types saved.')
56
57
  }
57
58
 
58
59
  /**
@@ -167,6 +168,19 @@ export class DesignTypes {
167
168
  }
168
169
  }
169
170
 
171
+ /**
172
+ * Saves the AI-generated project description to a file.
173
+ *
174
+ * Сохраняет сгенерированное ИИ описание проекта в файл.
175
+ * @param content content to save / контент для сохранения
176
+ */
177
+ protected saveDescription(content: string) {
178
+ PropertiesFile.writeByPath(
179
+ UI_FILE_AI_DESCRIPTION,
180
+ content
181
+ )
182
+ }
183
+
170
184
  /**
171
185
  * Combines a list of files into a single string.
172
186
  *
@@ -182,31 +196,17 @@ export class DesignTypes {
182
196
  }
183
197
 
184
198
  /**
185
- * Sends content to AI for optimization.
199
+ * Sends content and a prompt to the AI for processing.
186
200
  *
187
- * Отправляет контент ИИ для оптимизации.
188
- * @param content content to optimize / контент для оптимизации
201
+ * Отправляет контент и промпт ИИ для обработки.
202
+ * @param content content for processing / контент для обработки
203
+ * @param prompt instructions for the AI / инструкции для ИИ
189
204
  */
190
- protected async toAiEdit(content: string): Promise<string> {
205
+ protected async toAi(content: string, prompt: string): Promise<string | undefined> {
191
206
  const ai = useAi()
192
207
 
193
208
  if (ai) {
194
- ai.addPrompt(
195
- 'Remove all Russian comments from this code. '
196
- + 'Simplify and shorten all English comments for AI readability while maintaining a clear balance between brevity and context. Do not delete them even if the code seems obvious. '
197
- + 'Always keep All JSDoc "@example", "@remarks", "@note", and any other notes or warnings. '
198
- + 'Remove all imports. '
199
- + 'Remove all non-public content: delete all private and protected class methods and properties, and any non-exported elements. The final output must contain only the members and entities that are accessible from outside. '
200
- + 'Remove any code segments or data that do not provide useful information for an AI assistant. '
201
- + 'You may remove abstract classes or other structures that provide no practical value for code generation, but do so with extreme caution. Maintain a strict balance: if there is even a 5% chance the item might be relevant for understanding the API or generating code, keep it. Think carefully before every deletion. '
202
- + 'Remove any large Enums that add excessive length without providing critical context. '
203
- + 'Your goal is to create a compact, context-rich file that enables any AI coding assistant to generate high-quality code for a developer. '
204
- + 'Ensure that no public API surface, essential data types, or required logic is lost. '
205
- + 'Do not delete any "type" definitions; they are strictly required. '
206
- + 'Do not delete file paths (labels starting with "// File:"). '
207
- + 'All instructions are mandatory and must be executed perfectly. '
208
- + 'Return ONLY the resulting code. No markdown code blocks, no tags, no explanations, and no additional comments from the AI. NOTHING but the pure code.'
209
- )
209
+ ai.addPrompt(prompt)
210
210
  ai.addPrompt(`File Content: ${content}`)
211
211
 
212
212
  const generate = await ai.generate('go!')
@@ -216,6 +216,57 @@ export class DesignTypes {
216
216
  }
217
217
  }
218
218
 
219
- return content
219
+ return undefined
220
+ }
221
+
222
+ /**
223
+ * Sends content to AI for optimization.
224
+ *
225
+ * Отправляет контент ИИ для оптимизации.
226
+ * @param content content to optimize / контент для оптимизации
227
+ */
228
+ protected async toAiEdit(content: string): Promise<string> {
229
+ const generate = await this.toAi(
230
+ content,
231
+ 'Remove all Russian comments from this code. '
232
+ + 'Simplify and shorten all English comments for AI readability while maintaining a clear balance between brevity and context. Do not delete them even if the code seems obvious. '
233
+ + 'Always keep All JSDoc "@example", "@remarks", "@note", and any other notes or warnings. '
234
+ + 'Remove all imports. '
235
+ + 'Remove all non-public content: delete all private and protected class methods and properties, and any non-exported elements. The final output must contain only the members and entities that are accessible from outside. '
236
+ + 'Remove any code segments or data that do not provide useful information for an AI assistant. '
237
+ + 'You may remove abstract classes or other structures that provide no practical value for code generation, but do so with extreme caution. Maintain a strict balance: if there is even a 5% chance the item might be relevant for understanding the API or generating code, keep it. Think carefully before every deletion. '
238
+ + 'Remove any large Enums that add excessive length without providing critical context. '
239
+ + 'Your goal is to create a compact, context-rich file that enables any AI coding assistant to generate high-quality code for a developer. '
240
+ + 'Ensure that no public API surface, essential data types, or required logic is lost. '
241
+ + 'Do not delete any "type" definitions; they are strictly required. '
242
+ + 'Do not delete file paths (labels starting with "// File:"). '
243
+ + 'All instructions are mandatory and must be executed perfectly. '
244
+ + 'Return ONLY the resulting code. No markdown code blocks, no tags, no explanations, and no additional comments from the AI. NOTHING but the pure code.'
245
+ )
246
+
247
+ return generate ?? content
248
+ }
249
+
250
+ /**
251
+ * Generates a project description and usage guidelines using AI.
252
+ *
253
+ * Генерирует описание проекта и рекомендации по использованию с помощью ИИ.
254
+ * @param content cleaned type definitions / очищенные определения типов
255
+ */
256
+ protected async toAiDescription(content: string): Promise<string> {
257
+ const generate = await this.toAi(
258
+ content,
259
+ 'Analyze the provided code and generate a highly technical, concise project overview for another AI coding assistant. '
260
+ + 'Your goal is to help the AI decide whether it needs to study this library to fulfill a user request. '
261
+ + 'The description must be objective, factual, and free of marketing fluff. '
262
+ + 'Include: '
263
+ + '1. Core Purpose: What is the primary function of this library? (e.g., UI component library, state management, utility for X). '
264
+ + '2. Usage Scenarios: In what specific cases and scenarios is this library indispensable? When should an AI study its API? '
265
+ + '3. Integration Context: How does it relate to other technologies in the stack (if evident)? '
266
+ + 'Ensure the structure is clean and enables immediate context retrieval. '
267
+ + 'Return ONLY the resulting description text. No markdown, no labels like "Description:", no explanations. NOTHING but the pure content.'
268
+ )
269
+
270
+ return generate ?? ''
220
271
  }
221
272
  }
@@ -0,0 +1,190 @@
1
+ import {
2
+ FIGMA_API_URL,
3
+ FigmaApiEndpoint,
4
+ type FigmaFileImagesParams,
5
+ type FigmaFileImagesResult,
6
+ type FigmaFileNodesParams,
7
+ type FigmaFileNodesResult,
8
+ type FigmaFilesParams,
9
+ type FigmaFilesResult,
10
+ type FigmaFileStylesResult,
11
+ type FigmaStylesResult
12
+ } from '../types/figmaApiTypes'
13
+
14
+ /**
15
+ * Class for interacting with the Figma REST API.
16
+ *
17
+ * Класс для взаимодействия с Figma REST API.
18
+ */
19
+ export class FigmaApi {
20
+ constructor(
21
+ protected token: string,
22
+ protected fileKey: string,
23
+ protected nodeId?: string
24
+ ) {
25
+ }
26
+
27
+ /**
28
+ * Retrieves file content via the files endpoint.
29
+ *
30
+ * Получает содержимое файла через эндпоинт files.
31
+ * @param parameters query parameters / параметры запроса
32
+ * @returns file content or undefined / содержимое файла или undefined
33
+ */
34
+ async files(parameters: FigmaFilesParams = {}): Promise<FigmaFilesResult | undefined> {
35
+ return await this.fetch(FigmaApiEndpoint.files, parameters)
36
+ }
37
+
38
+ /**
39
+ * Retrieves specific nodes from the file via the fileNodes endpoint.
40
+ *
41
+ * Получает конкретные узлы из файла через эндпоинт fileNodes.
42
+ * @param parameters query parameters / параметры запроса
43
+ * @returns node data or undefined / данные узлов или undefined
44
+ */
45
+ async fileNodes(parameters: FigmaFileNodesParams): Promise<FigmaFileNodesResult | undefined> {
46
+ return await this.fetch(FigmaApiEndpoint.fileNodes, parameters)
47
+ }
48
+
49
+ /**
50
+ * Retrieves images for the file.
51
+ *
52
+ * Получает изображения для файла.
53
+ * @param parameters query parameters / параметры запроса
54
+ * @returns image data or undefined / данные изображения или undefined
55
+ */
56
+ async fileImages(parameters: FigmaFileImagesParams): Promise<FigmaFileImagesResult | undefined> {
57
+ return await this.fetch(FigmaApiEndpoint.fileImages, parameters)
58
+ }
59
+
60
+ /**
61
+ * Retrieves specific nodes from the file via the fileStyles endpoint.
62
+ *
63
+ * Получает конкретные узлы из файла через эндпоинт fileStyles.
64
+ * @returns file styles data or undefined / данные стилей файла или undefined
65
+ */
66
+ async fileStyles(): Promise<FigmaFileStylesResult | undefined> {
67
+ return await this.fetch(FigmaApiEndpoint.fileStyles)
68
+ }
69
+
70
+ /**
71
+ * Retrieves specific style by key via the styles endpoint.
72
+ *
73
+ * Получает конкретный стиль по ключу через эндпоинт styles.
74
+ * @param key the style key / ключ стиля
75
+ * @returns style data or undefined / данные стиля или undefined
76
+ */
77
+ async styles(key: string): Promise<FigmaStylesResult | undefined> {
78
+ return await this.fetch(FigmaApiEndpoint.styles, undefined, key)
79
+ }
80
+
81
+ /**
82
+ * Sets the API token.
83
+ *
84
+ * Устанавливает токен API.
85
+ * @param token the API token / токен API
86
+ * @returns this instance for chaining / этот экземпляр для цепочки вызовов
87
+ */
88
+ setToken(token: string): this {
89
+ this.token = token
90
+ return this
91
+ }
92
+
93
+ /**
94
+ * Sets the file key.
95
+ *
96
+ * Устанавливает ключ файла.
97
+ * @param fileKey the file key / ключ файла
98
+ * @returns this instance for chaining / этот экземпляр для цепочки вызовов
99
+ */
100
+ setFileKey(fileKey: string): this {
101
+ this.fileKey = fileKey
102
+ return this
103
+ }
104
+
105
+ /**
106
+ * Sets the node ID.
107
+ *
108
+ * Устанавливает ID узла.
109
+ * @param nodeId the node ID (optional) / ID узла (необязательно)
110
+ * @returns this instance for chaining / этот экземпляр для цепочки вызовов
111
+ */
112
+ setNodeId(nodeId?: string): this {
113
+ this.nodeId = nodeId
114
+ return this
115
+ }
116
+
117
+ /**
118
+ * Constructs the request URL for the Figma API.
119
+ *
120
+ * Конструирует URL-адрес запроса для Figma API.
121
+ * @param method the API endpoint method / метод конечной точки API
122
+ * @param parameters additional parameters for the request / дополнительные параметры для запроса
123
+ * @param key the key for specific endpoints (e.g., styles) / ключ для конкретных эндпоинтов (например, styles)
124
+ * @returns the constructed URL / сконструированный URL
125
+ */
126
+ getUrl(
127
+ method: FigmaApiEndpoint,
128
+ parameters?: Record<string, any>,
129
+ key?: string
130
+ ) {
131
+ const request = {}
132
+ const endpoint = method
133
+ .replace(':file_key', this.fileKey)
134
+ .replace(':key', key ?? '')
135
+
136
+ if (this.nodeId) {
137
+ Object.assign(request, { 'node-id': this.nodeId })
138
+ }
139
+
140
+ if (parameters) {
141
+ Object.assign(request, parameters)
142
+ }
143
+
144
+ console.log('request', request, Object.keys(request).length)
145
+
146
+ const queryParams = Object.keys(request).length > 0
147
+ ? `?${new URLSearchParams(request).toString()}`
148
+ : ''
149
+
150
+ return `${FIGMA_API_URL}${endpoint}${queryParams}`
151
+ }
152
+
153
+ /**
154
+ * Generic fetch method for making API requests.
155
+ *
156
+ * Общий метод fetch для выполнения запросов к API.
157
+ * @param method the API endpoint method / метод конечной точки API
158
+ * @param parameters parameters for the request / параметры запроса
159
+ * @param key the key for specific endpoints (e.g., styles) / ключ для конкретных эндпоинтов (например, styles)
160
+ * @returns the response data or undefined / данные ответа или undefined
161
+ */
162
+ protected async fetch(
163
+ method: FigmaApiEndpoint,
164
+ parameters: Record<string, any> = {},
165
+ key?: string
166
+ ): Promise<any> {
167
+ const url = this.getUrl(method, parameters, key)
168
+ const headers = {
169
+ 'X-Figma-Token': this.token,
170
+ 'Content-Type': 'application/json'
171
+ }
172
+
173
+ console.log('url', url)
174
+
175
+ const response = await fetch(url, {
176
+ method: 'GET',
177
+ headers
178
+ })
179
+
180
+ console.log('response', response.ok)
181
+
182
+ if (response.ok) {
183
+ return response.json()
184
+ }
185
+
186
+ console.error(`Error fetching Figma API: ${response.status} ${response.statusText}`)
187
+
188
+ return undefined
189
+ }
190
+ }
@@ -121,6 +121,15 @@ export class PropertiesConfig {
121
121
  return this.config.aiKey ?? ''
122
122
  }
123
123
 
124
+ /**
125
+ * Returns the Figma access token.
126
+ *
127
+ * Возвращает токен доступа к Figma.
128
+ */
129
+ static getFigmaToken(): string {
130
+ return this.config.figmaToken ?? ''
131
+ }
132
+
124
133
  /**
125
134
  * Returns the AI configuration object.
126
135
  *
package/src/config.ts CHANGED
@@ -91,6 +91,7 @@ export const UI_FILE_NAME_VITE_WORKERS = 'vite-workers.config.ts'
91
91
  export const UI_FILE_INDEX = 'index.ts'
92
92
 
93
93
  export const UI_FILE_AI_TYPES = 'ai-types.txt'
94
+ export const UI_FILE_AI_DESCRIPTION = 'ai-description.txt'
94
95
  export const UI_FILE_STYLE_SCSS = 'style.scss'
95
96
  export const UI_FILE_STYLE_PROPERTIES = 'ui-properties.scss'
96
97
 
package/src/library.ts CHANGED
@@ -1,50 +1,51 @@
1
- // Classes
2
- export * from './classes/Ai/AiAbstract'
3
- export * from './classes/Ai/AiClaude'
4
- export * from './classes/Ai/AiClaudeCli'
5
- export * from './classes/Ai/AiClaudeCliLite'
6
- export * from './classes/Ai/AiClaudeLite'
7
- export * from './classes/Ai/AiDoc'
8
- export * from './classes/Ai/AiDocItem'
9
- export * from './classes/Ai/AiDocItemAbstract'
10
- export * from './classes/Ai/AiDocItemClasses'
11
- export * from './classes/Ai/AiDocItemComposables'
12
- export * from './classes/Ai/AiDocType'
13
- export * from './classes/Ai/AiGoogle'
14
- export * from './classes/Ai/AiGoogleCli'
15
- export * from './classes/Ai/AiGoogleCliLite'
16
- export * from './classes/Ai/AiGoogleLite'
17
- export * from './classes/Build/buildFunctional'
18
- export * from './classes/BuildItem'
19
- export * from './classes/Design/DesignTypes'
20
- export * from './classes/Design/DesignTypescript'
21
- export * from './classes/Design/DesignWikiStorm'
22
- export * from './classes/Design/DesignWikiStormItem'
23
- export * from './classes/Git/GitRead'
24
- export * from './classes/Library/LibraryAiWiki'
25
- export * from './classes/Library/LibraryAiWikiItem'
26
- export * from './classes/Library/LibraryExport'
27
- export * from './classes/Library/LibraryList'
28
- export * from './classes/Library/LibraryPlugin'
29
- export * from './classes/Library/LibraryTypes'
30
- export * from './classes/Properties/PropertiesFile'
31
-
32
- // Composables
33
- export * from './composables/useAi'
34
-
35
- // Functions
36
- export * from './functions/getConfigAi'
37
- export * from './functions/getDirname'
38
- export * from './functions/getPackageJson'
39
- export * from './functions/hasNativeDirname'
40
- export * from './functions/takeScreenshot'
41
-
42
- // Types
43
- export * from './types/aiTypes'
44
- export * from './types/configTypes'
45
- export * from './types/designTypes'
46
- export * from './types/gitTypes'
47
- export * from './types/libraryTypes'
48
- export * from './types/propertyTypes'
49
- export * from './types/screenshotTypes'
50
- export * from './types/webTypes'
1
+ // Classes
2
+ export * from './classes/Ai/AiAbstract'
3
+ export * from './classes/Ai/AiClaude'
4
+ export * from './classes/Ai/AiClaudeCli'
5
+ export * from './classes/Ai/AiClaudeCliLite'
6
+ export * from './classes/Ai/AiClaudeLite'
7
+ export * from './classes/Ai/AiDoc'
8
+ export * from './classes/Ai/AiDocItem'
9
+ export * from './classes/Ai/AiDocItemAbstract'
10
+ export * from './classes/Ai/AiDocItemClasses'
11
+ export * from './classes/Ai/AiDocItemComposables'
12
+ export * from './classes/Ai/AiDocType'
13
+ export * from './classes/Ai/AiGoogle'
14
+ export * from './classes/Ai/AiGoogleCli'
15
+ export * from './classes/Ai/AiGoogleCliLite'
16
+ export * from './classes/Ai/AiGoogleLite'
17
+ export * from './classes/BrowserItem'
18
+ export * from './classes/Build/buildFunctional'
19
+ export * from './classes/BuildItem'
20
+ export * from './classes/Design/DesignScreenshot'
21
+ export * from './classes/Design/DesignTypes'
22
+ export * from './classes/Design/DesignTypescript'
23
+ export * from './classes/Design/DesignWikiStorm'
24
+ export * from './classes/Design/DesignWikiStormItem'
25
+ export * from './classes/Git/GitRead'
26
+ export * from './classes/Library/LibraryAiWiki'
27
+ export * from './classes/Library/LibraryAiWikiItem'
28
+ export * from './classes/Library/LibraryExport'
29
+ export * from './classes/Library/LibraryList'
30
+ export * from './classes/Library/LibraryPlugin'
31
+ export * from './classes/Library/LibraryTypes'
32
+ export * from './classes/Properties/PropertiesFile'
33
+
34
+ // Composables
35
+ export * from './composables/useAi'
36
+
37
+ // Functions
38
+ export * from './functions/getConfigAi'
39
+ export * from './functions/getDirname'
40
+ export * from './functions/getPackageJson'
41
+ export * from './functions/hasNativeDirname'
42
+
43
+ // Types
44
+ export * from './types/aiTypes'
45
+ export * from './types/configTypes'
46
+ export * from './types/designTypes'
47
+ export * from './types/gitTypes'
48
+ export * from './types/libraryTypes'
49
+ export * from './types/propertyTypes'
50
+ export * from './types/screenshotTypes'
51
+ export * from './types/webTypes'
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env vite-node
2
+ /// <reference types="node" />
3
+
4
+ import { spawn } from 'node:child_process'
5
+
6
+ ;(async () => {
7
+ try {
8
+ // Figma file key. Can be found in the URL of your Figma file:
9
+ // figma.com/design/FILE_KEY/...
10
+ const fileKey = ''
11
+
12
+ // Node ID in Figma file. Select an element and find 'node-id=...' in the URL
13
+ // or use "Copy link to selection" to see it in the URL.
14
+ const nodeId = ''
15
+
16
+ const child = spawn(
17
+ 'npx',
18
+ ['dxt-figma-layout', fileKey, nodeId],
19
+ { stdio: 'inherit' }
20
+ )
21
+
22
+ child.on('exit', code => console.log('End:', code))
23
+ } catch (error) {
24
+ console.error('Error:', error)
25
+ }
26
+ })()
@@ -56,4 +56,7 @@ export type DesignUiConfig = {
56
56
 
57
57
  /** AI configuration object / Объект конфигурации ИИ */
58
58
  aiConfig?: Record<string, any>
59
+
60
+ /** Figma access token for API authentication / Токен доступа Figma для аутентификации API */
61
+ figmaToken?: string
59
62
  }