@dxtmisha/scripts 0.6.3 → 0.7.6

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.
Files changed (121) hide show
  1. package/bin/ai-doc.ts +1 -3
  2. package/bin/build-functional.ts +5 -0
  3. package/bin/design-flags.ts +5 -0
  4. package/bin/design-wiki-storm.ts +9 -0
  5. package/package.json +14 -8
  6. package/src/classes/Ai/AiAbstract.ts +14 -1
  7. package/src/classes/Ai/AiGoogleLite.ts +2 -1
  8. package/src/classes/Build/__tests__/buildFunctional.test.ts +43 -0
  9. package/src/classes/Build/buildFunctional.ts +54 -0
  10. package/src/classes/Component/ComponentCreator.ts +1 -0
  11. package/src/classes/Component/ComponentItem.ts +15 -0
  12. package/src/classes/Component/ComponentWiki.ts +8 -0
  13. package/src/classes/Component/ComponentWikiFile.ts +2 -0
  14. package/src/classes/Component/__tests__/ComponentCreator.test.ts +71 -0
  15. package/src/classes/Component/__tests__/ComponentItem.test.ts +71 -0
  16. package/src/classes/Design/DesignCommand.ts +65 -10
  17. package/src/classes/Design/DesignComponent.ts +303 -39
  18. package/src/classes/Design/DesignConstructor.ts +49 -20
  19. package/src/classes/Design/DesignConstructors.ts +61 -2
  20. package/src/classes/Design/DesignFlags.ts +215 -0
  21. package/src/classes/Design/DesignReplace.ts +11 -7
  22. package/src/classes/Design/DesignStructure.ts +8 -6
  23. package/src/classes/Design/DesignStructureClasses.ts +8 -4
  24. package/src/classes/Design/DesignStructureItemAbstract.ts +11 -2
  25. package/src/classes/Design/DesignStructureRead.ts +8 -4
  26. package/src/classes/Design/DesignStructureStyles.ts +8 -4
  27. package/src/classes/Design/DesignTypes.ts +53 -28
  28. package/src/classes/Design/DesignTypescript.ts +11 -2
  29. package/src/classes/Design/DesignUi.ts +74 -4
  30. package/src/classes/Design/DesignWiki.ts +4 -6
  31. package/src/classes/Design/DesignWikiStorm.ts +94 -0
  32. package/src/classes/Design/DesignWikiStormItem.ts +246 -0
  33. package/src/classes/Git/GitRead.ts +1 -0
  34. package/src/classes/Git/__tests__/GitRead.test.ts +70 -0
  35. package/src/classes/Library/LibraryAiWiki.ts +127 -0
  36. package/src/classes/Library/LibraryAiWikiItem.ts +79 -0
  37. package/src/classes/Library/LibraryExport.ts +0 -2
  38. package/src/classes/Library/LibraryFlags.ts +9 -7
  39. package/src/classes/Library/LibraryItems.ts +22 -13
  40. package/src/classes/Library/LibraryList.ts +189 -0
  41. package/src/classes/Library/LibraryMedia.ts +22 -8
  42. package/src/classes/Library/LibraryPlugin.ts +73 -0
  43. package/src/classes/Library/LibraryTypes.ts +130 -0
  44. package/src/classes/Package/PackageInit.ts +12 -4
  45. package/src/classes/Package/PackageItem.ts +16 -5
  46. package/src/classes/Properties/Properties.ts +14 -3
  47. package/src/classes/Properties/PropertiesCache.ts +19 -20
  48. package/src/classes/Properties/PropertiesConfig.ts +46 -26
  49. package/src/classes/Properties/PropertiesConvector.ts +10 -6
  50. package/src/classes/Properties/PropertiesFile.ts +27 -31
  51. package/src/classes/Properties/PropertiesImport.ts +10 -7
  52. package/src/classes/Properties/PropertiesItems.ts +19 -12
  53. package/src/classes/Properties/PropertiesKeys.ts +15 -9
  54. package/src/classes/Properties/PropertiesMain.ts +13 -7
  55. package/src/classes/Properties/PropertiesPalette.ts +12 -6
  56. package/src/classes/Properties/PropertiesPath.ts +17 -11
  57. package/src/classes/Properties/PropertiesScss.ts +10 -8
  58. package/src/classes/Properties/PropertiesSeparator.ts +9 -11
  59. package/src/classes/Properties/PropertiesSettings.ts +8 -6
  60. package/src/classes/Properties/PropertiesStandard.ts +5 -6
  61. package/src/classes/Properties/PropertiesTool.ts +16 -9
  62. package/src/classes/Properties/PropertiesTypes.ts +12 -12
  63. package/src/classes/Properties/PropertiesValues.ts +14 -14
  64. package/src/classes/Properties/PropertiesWrap.ts +5 -6
  65. package/src/classes/Properties/convector/convectorColor.ts +5 -3
  66. package/src/classes/Properties/to/PropertiesToAbstract.ts +18 -4
  67. package/src/classes/Styles/Styles.ts +1 -0
  68. package/src/composables/__tests__/useAi.test.ts +75 -0
  69. package/src/config.ts +9 -0
  70. package/src/functions/__tests__/getComponentPaths.test.ts +19 -0
  71. package/src/functions/__tests__/getConfigAi.test.ts +26 -0
  72. package/src/functions/__tests__/getConstructorProperties.test.ts +51 -0
  73. package/src/functions/__tests__/getDirname.test.ts +31 -0
  74. package/src/functions/__tests__/getNameDirByPaths.test.ts +40 -0
  75. package/src/functions/__tests__/getPackageJson.test.ts +34 -0
  76. package/src/functions/__tests__/hasNativeDirname.test.ts +18 -0
  77. package/src/functions/__tests__/toPathStandardSep.test.ts +31 -0
  78. package/src/functions/getConfigAi.ts +3 -2
  79. package/src/functions/toPathStandardSep.ts +1 -1
  80. package/src/library-ai.ts +0 -1
  81. package/src/library.ts +10 -0
  82. package/src/media/properties/css.ts +3 -1
  83. package/src/media/templates/component/{DesignComponentWikiAi.vue → DesignComponentAiWiki.vue} +2 -2
  84. package/src/media/templates/component/props.ts +2 -3
  85. package/src/media/templates/component/styleToken.scss +1 -1
  86. package/src/media/templates/component/wiki.ts +6 -12
  87. package/src/media/templates/component/wikiData.ts +28 -0
  88. package/src/media/templates/constructors/props.ts +3 -4
  89. package/src/media/templates/packages/figma/README.md +1 -0
  90. package/src/media/templates/packages/figma/ai.sample.config.ts +2 -0
  91. package/src/media/templates/packages/figma/design.config.json +3 -0
  92. package/src/media/templates/packages/figma/index.html +12 -0
  93. package/src/media/templates/packages/figma/manifest.json +25 -0
  94. package/src/media/templates/packages/figma/package.json +37 -0
  95. package/src/media/templates/packages/figma/src/App.vue +9 -0
  96. package/src/media/templates/packages/figma/src/classes/_.gitignore.txt +1 -0
  97. package/src/media/templates/packages/figma/src/code.ts +16 -0
  98. package/src/media/templates/packages/figma/src/components/_.gitignore.txt +1 -0
  99. package/src/media/templates/packages/figma/src/composables/_.gitignore.txt +1 -0
  100. package/src/media/templates/packages/figma/src/functions/_.gitignore.txt +1 -0
  101. package/src/media/templates/packages/figma/src/library.ts +0 -0
  102. package/src/media/templates/packages/figma/src/main.ts +4 -0
  103. package/src/media/templates/packages/figma/src/media/_.gitignore.txt +1 -0
  104. package/src/media/templates/packages/figma/src/storybook/_.gitignore.txt +1 -0
  105. package/src/media/templates/packages/figma/src/types/_.gitignore.txt +1 -0
  106. package/src/media/templates/packages/figma/src/vite-env.d.ts +1 -0
  107. package/src/media/templates/packages/figma/tsconfig.app.json +12 -0
  108. package/src/media/templates/packages/figma/tsconfig.json +7 -0
  109. package/src/media/templates/packages/figma/tsconfig.node.json +8 -0
  110. package/src/media/templates/packages/figma/vite.config.ts +7 -0
  111. package/src/media/templates/packages/library/src/main.ts +1 -1
  112. package/src/media/templates/packages/project/design.config.json +3 -0
  113. package/src/media/templates/packages/project/index.html +1 -2
  114. package/src/media/templates/packages/project/public/_.gitignore.txt +0 -0
  115. package/src/media/templates/packages/project/src/main.ts +2 -1
  116. package/src/media/templates/packages/project/src/vite-env.d.ts +1 -0
  117. package/src/types/configTypes.ts +6 -0
  118. package/src/types/designTypes.ts +12 -0
  119. package/src/types/libraryTypes.ts +1 -1
  120. package/src/types/webTypes.ts +105 -0
  121. /package/src/media/templates/packages/{library/public/_.gitignore.txt → figma/src/config.ts} +0 -0
@@ -0,0 +1,215 @@
1
+ // export:none
2
+
3
+ import { Canvas, createCanvas, loadImage, type SKRSContext2D } from '@napi-rs/canvas'
4
+ import { PropertiesFile } from '../Properties/PropertiesFile'
5
+
6
+ import type { DesignFlagsItem, DesignFlagsList } from '../../types/designTypes'
7
+
8
+ import { UI_DIR_IN } from '../../config'
9
+
10
+ const DESIGN_FLAGS_FACTOR = 2
11
+ const DESIGN_FLAGS_MIME = 'image/webp'
12
+ const DESIGN_FLAGS_FILE_NAME_ITEM = 'flags.webp'
13
+ const DESIGN_FLAGS_FILE_NAME = [UI_DIR_IN, 'assets', DESIGN_FLAGS_FILE_NAME_ITEM]
14
+ const DESIGN_FLAGS_FILE_PATH = ['.', '..', 'assets', DESIGN_FLAGS_FILE_NAME_ITEM]
15
+ const DESIGN_FLAGS_FILE_STYLE_NAME = [UI_DIR_IN, 'styles', 'flags.css']
16
+ const DESIGN_FLAGS_CLASS_NAME = '.ui-sys-flags'
17
+
18
+ /**
19
+ * Class for generating a sprite image and CSS mapping from a directory of flag icons.
20
+ * It automates the creation of a combined webp image and a CSS file with specific background-position utility classes.
21
+ *
22
+ * Класс для генерации спрайта и CSS-маппинга из директории иконок флагов.
23
+ * Автоматизирует создание комбинированного изображения webp и CSS-файла с утилитарными классами для позиционирования фона.
24
+ */
25
+ export class DesignFlags {
26
+ protected list: string[]
27
+ protected data: DesignFlagsList = []
28
+
29
+ protected x: number = 0
30
+ protected y: number = 0
31
+
32
+ protected square: number
33
+ protected top: number
34
+ protected left: number
35
+
36
+ protected readonly canvas: Canvas
37
+ protected readonly context: SKRSContext2D
38
+
39
+ /**
40
+ * Constructor for DesignFlags.
41
+ *
42
+ * Конструктор для DesignFlags.
43
+ * @param dir path to the directory containing SVG icons / путь к директории с SVG-иконками
44
+ * @param width width of a single flag in the sprite / ширина одного флага в спрайте
45
+ * @param height height of a single flag in the sprite / высота одного флага в спрайте
46
+ * @param columns number of columns in the sprite grid / количество колонок в сетке спрайта
47
+ */
48
+ constructor(
49
+ protected readonly dir: string = 'src/assets/flags',
50
+ protected readonly width: number = 96,
51
+ protected readonly height: number = 72,
52
+ protected readonly columns: number = 12
53
+ ) {
54
+ this.list = this.initList()
55
+ this.square = this.initSquare()
56
+ this.top = this.initTop()
57
+ this.left = this.initLeft()
58
+
59
+ this.canvas = this.initCanvas()
60
+ this.context = this.initContext()
61
+ }
62
+
63
+ async make() {
64
+ for (const file of this.list) {
65
+ await this.addImage(file)
66
+
67
+ this.data.push(this.addData(file))
68
+ this.next()
69
+ }
70
+
71
+ this.save()
72
+ this.saveStyle()
73
+ }
74
+
75
+ getLines(): number {
76
+ return Math.ceil(this.list.length / this.columns)
77
+ }
78
+
79
+ /**
80
+ * Returns the maximum width of the canvas.
81
+ *
82
+ * Возвращает максимальную ширину холста.
83
+ */
84
+ protected getCanvasWidth(): number {
85
+ return this.columns * this.square
86
+ }
87
+
88
+ /**
89
+ * Returns the maximum height of the canvas.
90
+ *
91
+ * Возвращает максимальную высоту холста.
92
+ */
93
+ protected getCanvasHeight(): number {
94
+ return this.getLines() * this.square
95
+ }
96
+
97
+ protected getDx() {
98
+ return (this.x * this.square) + this.left
99
+ }
100
+
101
+ protected getDy() {
102
+ return (this.y * this.square) + this.top
103
+ }
104
+
105
+ protected getStyle(): string {
106
+ const backgroundSizeColumns = this.columns * (this.square / this.width)
107
+ const backgroundSizeLines = this.getLines() * (this.square / this.height)
108
+
109
+ let style: string = `
110
+ ${DESIGN_FLAGS_CLASS_NAME} {
111
+ --sys-flags-width: ${this.width}px;
112
+ --sys-flags-height: ${this.height}px;
113
+ --sys-flags-top: ${this.top}px;
114
+ --sys-flags-left: ${this.left}px;
115
+ --sys-flags-lines: ${this.getLines()};
116
+
117
+ background-image: url("${DESIGN_FLAGS_FILE_PATH.join('/')}");
118
+ background-size: calc(100% * ${backgroundSizeColumns}) calc(100% * ${backgroundSizeLines});
119
+ }
120
+ `.trim()
121
+
122
+ const x = 100 / (this.getCanvasWidth() - this.width)
123
+ const y = 100 / (this.getCanvasHeight() - this.height)
124
+
125
+ this.data.forEach((item) => {
126
+ style += `
127
+ ${DESIGN_FLAGS_CLASS_NAME}--${item.name} {
128
+ background-position: ${item.x * x}% ${item.y * y}%;
129
+ }`
130
+ })
131
+
132
+ return style
133
+ }
134
+
135
+ protected async addImage(file: string): Promise<void> {
136
+ const path = PropertiesFile.joinPath([this.dir, file])
137
+ const image = await loadImage(path)
138
+
139
+ this.context.drawImage(
140
+ image,
141
+ this.getDx(),
142
+ this.getDy(),
143
+ this.width,
144
+ this.height
145
+ )
146
+ }
147
+
148
+ protected addData(file: string): DesignFlagsItem {
149
+ return {
150
+ name: file.replace(/\.[^.]+$/, ''),
151
+ x: this.getDx(),
152
+ y: this.getDy()
153
+ }
154
+ }
155
+
156
+ protected next(): void {
157
+ this.x++
158
+
159
+ if (this.x >= this.columns) {
160
+ this.x = 0
161
+ this.y++
162
+ }
163
+ }
164
+
165
+ protected save(): void {
166
+ const buffer = this.canvas.toBuffer(DESIGN_FLAGS_MIME, 64)
167
+
168
+ if (buffer) {
169
+ PropertiesFile.writeByPath(
170
+ DESIGN_FLAGS_FILE_NAME,
171
+ buffer,
172
+ false
173
+ )
174
+ }
175
+ }
176
+
177
+ protected saveStyle(): void {
178
+ PropertiesFile.writeByPath(
179
+ DESIGN_FLAGS_FILE_STYLE_NAME,
180
+ this.getStyle()
181
+ )
182
+ }
183
+
184
+ protected initCanvas(): Canvas {
185
+ return createCanvas(
186
+ this.getCanvasWidth(),
187
+ this.getCanvasHeight()
188
+ )
189
+ }
190
+
191
+ protected initContext(): SKRSContext2D {
192
+ return this.canvas.getContext('2d', { alpha: true })
193
+ }
194
+
195
+ protected initLeft(): number {
196
+ return (this.square / 2) - (this.width / 2)
197
+ }
198
+
199
+ protected initList(): string[] {
200
+ return PropertiesFile.readDir(this.dir)
201
+ .filter(dir => dir.endsWith('.svg'))
202
+ }
203
+
204
+ protected initSquare(): number {
205
+ if (this.width >= this.height) {
206
+ return this.width * DESIGN_FLAGS_FACTOR
207
+ }
208
+
209
+ return this.height * DESIGN_FLAGS_FACTOR
210
+ }
211
+
212
+ protected initTop(): number {
213
+ return (this.square / 2) - (this.height / 2)
214
+ }
215
+ }
@@ -15,19 +15,23 @@ import { UI_KEY_CUSTOM } from '../../config'
15
15
  import { PropertiesConfig } from '../Properties/PropertiesConfig'
16
16
 
17
17
  /**
18
- * Class with basic replacement for templates.
18
+ * Engine for systematic text replacement within file templates based on component structure.
19
+ * It manages the transformation of labels (marks) into actual code segments, including property types, default values, and CSS class mappings.
19
20
  *
20
- * Класс с базовой заменой для шаблонов.
21
+ * Движок для систематической замены текста в шаблонах файлов на основе структуры компонента.
22
+ * Управляет преобразованием меток (marks) в реальные сегменты кода, включая типы свойств, значения по умолчанию и маппинг CSS-классов.
21
23
  */
22
24
  export class DesignReplace {
23
25
  protected readonly component: string
24
26
  protected readonly mark: string
25
27
 
26
28
  /**
27
- * Constructor
28
- * @param structure object for working with components/ объект для работы с компонентами
29
- * @param mark метка для замена на имя
30
- * @param sample property template/ шаблон свойства
29
+ * Constructor for DesignReplace.
30
+ *
31
+ * Конструктор для DesignReplace.
32
+ * @param structure object containing component metadata and design logic / объект, содержащий метаданные компонента и логику дизайна
33
+ * @param mark the identifier used in templates for replacement (e.g., 'button') / идентификатор, используемый в шаблонах для замены
34
+ * @param sample the raw template content to be processed / необработанное содержимое шаблона для обработки
31
35
  */
32
36
  constructor(
33
37
  protected structure: DesignStructure,
@@ -116,7 +120,7 @@ export class DesignReplace {
116
120
  let space = this.sample.match(new RegExp(`^( *)(${regName})`, 'm'))?.[1]
117
121
 
118
122
  if (
119
- !space
123
+ typeof space !== 'string'
120
124
  && this.sample.match(name)
121
125
  ) {
122
126
  regName = `<!-- :${name} `
@@ -19,9 +19,11 @@ import {
19
19
  } from '../../config'
20
20
 
21
21
  /**
22
- * Class for processing structured components.
22
+ * Class for managing and resolving the data structure of a design system component.
23
+ * It serves as a central hub for reading component metadata, generating class mappings, and resolving style tokens.
23
24
  *
24
- * Класс для обработки структурированных компонентов.
25
+ * Класс для управления и разрешения структуры данных компонента дизайн-системы.
26
+ * Служит центральным узлом для чтения метаданных компонента, генерации маппингов классов и разрешения стилевых токенов.
25
27
  */
26
28
  export class DesignStructure {
27
29
  protected readonly component: string
@@ -30,11 +32,11 @@ export class DesignStructure {
30
32
  protected itemsClasses?: DesignStructureClassesList
31
33
  protected itemsStyles?: string[]
32
34
 
33
- constructor(path: string)
34
- constructor(design: string, component: string)
35
35
  /**
36
- * Constructor
37
- * @param component component name/ название компонента
36
+ * Constructor for DesignStructure.
37
+ *
38
+ * Конструктор для DesignStructure.
39
+ * @param component component name or identifier / название или идентификатор компонента
38
40
  */
39
41
  constructor(
40
42
  component?: string
@@ -14,16 +14,20 @@ import {
14
14
  } from '../../types/designTypes'
15
15
 
16
16
  /**
17
- * A class for getting a list of classes of components.
17
+ * Class for resolving and generating a hierarchical list of CSS classes for a component.
18
+ * It recursively parses component properties to identify subclasses and build BEM-compliant class names.
18
19
  *
19
- * Класс для получения списка классов компонентов.
20
+ * Класс для разрешения и генерации иерархического списка CSS-классов для компонента.
21
+ * Рекурсивно анализирует свойства компонента для идентификации подклассов и построения имен классов, соответствующих BEM.
20
22
  */
21
23
  export class DesignStructureClasses extends DesignStructureItemAbstract<DesignStructureClassesList> {
22
24
  protected data: DesignStructureClassesList = []
23
25
 
24
26
  /**
25
- * Constructor
26
- * @param component component name/ название компонента
27
+ * Constructor for DesignStructureClasses.
28
+ *
29
+ * Конструктор для DesignStructureClasses.
30
+ * @param component component name used as the base for class generation / имя компонента, используемое в качестве базы для генерации классов
27
31
  */
28
32
  constructor(
29
33
  component: string
@@ -5,6 +5,13 @@ import { PropertiesConfig } from '../Properties/PropertiesConfig'
5
5
 
6
6
  import type { PropertyItemsItem } from '../../types/propertyTypes'
7
7
 
8
+ /**
9
+ * Base abstract class for structural component items.
10
+ * It provides the foundation for resolving component properties and metadata from the design system's central storage.
11
+ *
12
+ * Базовый абстрактный класс для структурных элементов компонента.
13
+ * Предоставляет основу для разрешения свойств и метаданных компонента из центрального хранилища дизайн-системы.
14
+ */
8
15
  export abstract class DesignStructureItemAbstract<D> {
9
16
  protected properties: Properties
10
17
  protected items?: PropertyItemsItem
@@ -12,8 +19,10 @@ export abstract class DesignStructureItemAbstract<D> {
12
19
  protected abstract data: D
13
20
 
14
21
  /**
15
- * Constructor
16
- * @param component component name/ название компонента
22
+ * Constructor for DesignStructureItemAbstract.
23
+ *
24
+ * Конструктор для DesignStructureItemAbstract.
25
+ * @param component component name for which the structure is being resolved / имя компонента, для которого разрешается структура
17
26
  */
18
27
  protected constructor(
19
28
  protected readonly component: string
@@ -19,9 +19,11 @@ import type {
19
19
  import { UI_PROPERTY_FOR_PROPS } from '../../config'
20
20
 
21
21
  /**
22
- * Class for processing dependency properties of the component.
22
+ * Engine for parsing and resolving component property dependencies and states.
23
+ * It processes the raw property metadata to identify interactive states, link classes, and compile all possible values for code generation.
23
24
  *
24
- * Класс для обработки зависимости свойств у компонента.
25
+ * Движок для парсинга и разрешения зависимостей свойств и состояний компонента.
26
+ * Обрабатывает сырые метаданные свойств для идентификации интерактивных состояний, связанных классов и компиляции всех возможных значений для генерации кода.
25
27
  */
26
28
  export class DesignStructureRead extends DesignStructureItemAbstract<DesignStructureList> {
27
29
  protected states: DesignStructureStateList
@@ -29,8 +31,10 @@ export class DesignStructureRead extends DesignStructureItemAbstract<DesignStruc
29
31
  protected data: DesignStructureList = {}
30
32
 
31
33
  /**
32
- * Constructor
33
- * @param component component name/ название компонента
34
+ * Constructor for DesignStructureRead.
35
+ *
36
+ * Конструктор для DesignStructureRead.
37
+ * @param component component name whose properties are being resolved / имя компонента, свойства которого разрешаются
34
38
  */
35
39
  constructor(
36
40
  component: string
@@ -4,16 +4,20 @@ import { StylesProperties } from '../Styles/StylesProperties'
4
4
  import { DesignStructureItemAbstract } from './DesignStructureItemAbstract'
5
5
 
6
6
  /**
7
- * Class for processing styles from tokens for the component.
7
+ * Engine for compiling component-specific styles from design system tokens.
8
+ * It coordinates the transformation of structural metadata into CSS-in-JS style rules using the global theme environment.
8
9
  *
9
- * Класс для обработки стилей из токенов для компонента.
10
+ * Движок для компиляции специфичных для компонента стилей из токенов дизайн-системы.
11
+ * Координирует преобразование структурных метаданных в правила стилей CSS-in-JS с использованием глобального тематического окружения.
10
12
  */
11
13
  export class DesignStructureStyles extends DesignStructureItemAbstract<string[]> {
12
14
  protected data: string[]
13
15
 
14
16
  /**
15
- * Constructor
16
- * @param component component name/ название компонента
17
+ * Constructor for DesignStructureStyles.
18
+ *
19
+ * Конструктор для DesignStructureStyles.
20
+ * @param component component name for which styles are being compiled / имя компонента, для которого компилируются стили
17
21
  */
18
22
  constructor(
19
23
  component: string
@@ -1,16 +1,19 @@
1
1
  import { forEach } from '@dxtmisha/functional-basic'
2
+ import { getPackageJson } from '../../functions/getPackageJson'
2
3
  import { useAi } from '../../composables/useAi'
3
4
 
4
5
  import { PropertiesFile } from '../Properties/PropertiesFile'
5
6
 
6
7
  import type { DesignTypesList } from '../../types/designTypes'
7
8
 
8
- import { UI_FILE_AI_TYPES } from '../../config'
9
+ import { UI_DIR_CONSTRUCTOR, UI_FILE_AI_TYPES } from '../../config'
9
10
 
10
11
  /**
11
- * Class for generating AI-optimized type definitions.
12
+ * Engine for generating compressed and AI-optimized TypeScript type definitions.
13
+ * It scans the build output for declaration files, sanitizes them, and uses AI to produce a minimal, context-rich type library for use in automated coding assistants.
12
14
  *
13
- * Класс для генерации оптимизированных ИИ определений типов.
15
+ * Движок для генерации сжатых и оптимизированных для ИИ определений типов TypeScript.
16
+ * Сканирует выходные данные сборки на наличие файлов деклараций, очищает их и использует ИИ для создания минимальной, насыщенной контекстом библиотеки типов для использования в автоматизированных помощниках по кодированию.
14
17
  */
15
18
  export class DesignTypes {
16
19
  /**
@@ -21,8 +24,10 @@ export class DesignTypes {
21
24
  protected readonly dirArray: string[]
22
25
 
23
26
  /**
24
- * Constructor
25
- * @param dir directory path / путь к директории
27
+ * Constructor for DesignTypes.
28
+ *
29
+ * Конструктор для DesignTypes.
30
+ * @param dir input directory path containing declaration files / входной путь к директории, содержащей файлы деклараций
26
31
  */
27
32
  constructor(
28
33
  protected readonly dir: string = 'dist'
@@ -58,12 +63,14 @@ export class DesignTypes {
58
63
  */
59
64
  protected isFile(file: string): boolean {
60
65
  return file.endsWith('.d.ts')
66
+ && !file.endsWith('.vue.d.ts')
67
+ && !file.endsWith('wiki.d.ts')
68
+ && !file.endsWith('wikiData.d.ts')
61
69
  && (
62
- !file.includes('constructors/')
63
- || (
64
- !file.endsWith('/props.d.ts')
65
- && !file.endsWith('/types.d.ts')
66
- )
70
+ !file.includes(`${UI_DIR_CONSTRUCTOR}/`)
71
+ || file.endsWith('/basicTypes.d.ts')
72
+ || file.endsWith('/types.d.ts')
73
+ || file.endsWith('/props.d.ts')
67
74
  )
68
75
  }
69
76
 
@@ -75,11 +82,9 @@ export class DesignTypes {
75
82
  */
76
83
  protected isContent(content?: string): content is string {
77
84
  return Boolean(
78
- content && (
79
- content.includes('export interface')
80
- || content.includes('export type')
81
- || content.includes('export enum')
82
- ))
85
+ content
86
+ && content.includes('export')
87
+ )
83
88
  }
84
89
 
85
90
  /**
@@ -143,10 +148,23 @@ export class DesignTypes {
143
148
  * @param content content to save / контент для сохранения
144
149
  */
145
150
  protected save(content: string) {
146
- PropertiesFile.writeByPath(
147
- UI_FILE_AI_TYPES,
148
- content
149
- )
151
+ const packageJson = getPackageJson()
152
+
153
+ if (packageJson) {
154
+ PropertiesFile.writeByPath(
155
+ UI_FILE_AI_TYPES,
156
+ [
157
+ `1) All these methods are in the ${packageJson.name} library.`,
158
+ '2) Everything that is exported can be used.',
159
+ '3) Use what is in this library if it exists; do not use other libraries if there is an analogue here. Do not create new ones if an analogue already exists here.',
160
+ '',
161
+ 'The following is the content of "exports" from package.json:',
162
+ JSON.stringify(packageJson.exports, null, 2),
163
+ '',
164
+ content
165
+ ].join('\n')
166
+ )
167
+ }
150
168
  }
151
169
 
152
170
  /**
@@ -173,18 +191,25 @@ export class DesignTypes {
173
191
  const ai = useAi()
174
192
 
175
193
  if (ai) {
176
- ai.addPrompt(`File Content: ${content}`)
177
-
178
- const generate = await ai.generate(
194
+ ai.addPrompt(
179
195
  'Remove all Russian comments from this code. '
180
- + 'Remove comments if the property name makes its purpose obvious. '
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. '
181
198
  + 'Remove all imports. '
182
- + 'Remove empty lines. '
183
- + 'Remove the "export" keyword if possible. '
184
- + 'Keep only "type", "interface" and "enum" definitions, remove everything else. '
185
- + 'Minimize the content as much as possible without losing any data or logic. '
186
- + 'Return only the corrected code without any additional text or explanations.'
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.'
187
209
  )
210
+ ai.addPrompt(`File Content: ${content}`)
211
+
212
+ const generate = await ai.generate('go!')
188
213
 
189
214
  if (generate) {
190
215
  return generate
@@ -9,9 +9,11 @@ import type {
9
9
  } from '../../types/designTypes'
10
10
 
11
11
  /**
12
- * Class for working with TypeScript types
12
+ * Utility for interacting with the TypeScript Compiler API to analyze and extract type metadata from source files.
13
+ * It parses interfaces and type aliases to retrieve property details, including types, literal unions, and documentation comments.
13
14
  *
14
- * Класс для работы с типами TypeScript
15
+ * Утилита для взаимодействия с TypeScript Compiler API для анализа и извлечения метаданных типов из исходных файлов.
16
+ * Анализирует интерфейсы и псевдонимы типов для получения сведений о свойствах, включая типы, литеральные объединения и комментарии к документации.
15
17
  */
16
18
  export class DesignTypescript {
17
19
  protected readonly program: ts.Program
@@ -19,6 +21,13 @@ export class DesignTypescript {
19
21
  protected readonly sourceFile?: ts.SourceFile
20
22
  protected types?: DesignTypescriptList
21
23
 
24
+ /**
25
+ * Constructor for DesignTypescript.
26
+ *
27
+ * Конструктор для DesignTypescript.
28
+ * @param path path to the TypeScript source file to analyze / путь к исходному файлу TypeScript для анализа
29
+ * @param options compiler options for the TypeScript program / опции компилятора для программы TypeScript
30
+ */
22
31
  constructor(
23
32
  path: string = '',
24
33
  options: ts.CompilerOptions = {}
@@ -1,22 +1,40 @@
1
1
  // export:none
2
2
 
3
- import { toKebabCase } from '@dxtmisha/functional-basic'
3
+ import { toCamelCaseFirst, toKebabCase } from '@dxtmisha/functional-basic'
4
+ import { getPackageJson } from '../../functions/getPackageJson'
4
5
 
6
+ import { PropertiesConfig } from '../Properties/PropertiesConfig'
7
+ import { PropertiesFile } from '../Properties/PropertiesFile'
8
+ import { PropertiesCache } from '../Properties/PropertiesCache'
5
9
  import { DesignComponent } from './DesignComponent'
6
10
  import { LibraryItems } from '../Library/LibraryItems'
7
- import { PropertiesCache } from '../Properties/PropertiesCache'
8
11
  import { Styles } from '../Styles/Styles'
9
12
 
10
13
  import { DesignWiki } from './DesignWiki'
11
14
 
15
+ import { LibraryAiWiki } from '../Library/LibraryAiWiki'
12
16
  import { LibraryMedia } from '../Library/LibraryMedia'
17
+ import { LibraryList } from '../Library/LibraryList'
18
+ import { LibraryPlugin } from '../Library/LibraryPlugin'
19
+ import { LibraryTypes } from '../Library/LibraryTypes'
20
+
21
+ import { UI_FILE_PACKAGE, UI_FILE_STYLE_PROPERTIES } from '../../config'
13
22
 
23
+ /**
24
+ * Orchestrator class for managing and initializing the Design System UI.
25
+ * It coordinates the generation of styles, documentation, component structures, and library-level exports (media, plugins, types).
26
+ *
27
+ * Класс-оркестратор для управления и инициализации пользовательского интерфейса дизайн-системы.
28
+ * Координирует генерацию стилей, документации, структур компонентов и экспортов на уровне библиотеки (медиа, плагины, типы).
29
+ */
14
30
  export class DesignUi {
15
31
  protected readonly components: LibraryItems
16
32
 
17
33
  /**
18
- * Constructor
19
- * @param name component name/ названия компонента
34
+ * Constructor for DesignUi.
35
+ *
36
+ * Конструктор для DesignUi.
37
+ * @param name specific component name to initialize, or empty for all / название конкретного компонента для инициализации или пусто для всех
20
38
  */
21
39
  constructor(
22
40
  protected readonly name: string = ''
@@ -45,8 +63,14 @@ export class DesignUi {
45
63
  new DesignWiki().make()
46
64
 
47
65
  this.makeConstructorComponent()
66
+ .makePackage()
67
+ .makeUiProperties()
48
68
 
49
69
  new LibraryMedia(this.components).make()
70
+ new LibraryList(this.components).make()
71
+ new LibraryPlugin(this.components).make()
72
+ new LibraryAiWiki(this.components).make()
73
+ new LibraryTypes(this.components).make()
50
74
  }
51
75
 
52
76
  /**
@@ -70,4 +94,50 @@ export class DesignUi {
70
94
 
71
95
  return this
72
96
  }
97
+
98
+ /**
99
+ * Updates the package.json file by adding export paths for UI styles and saves the changes.
100
+ *
101
+ * Обновляет файл package.json, добавляя пути экспорта для стилей UI, и сохраняет изменения.
102
+ */
103
+ protected makePackage(): this {
104
+ const packageJson = getPackageJson()
105
+ const projectName = toCamelCaseFirst(PropertiesConfig.getProjectName())
106
+
107
+ if (packageJson?.exports) {
108
+ packageJson.exports['.'] = {
109
+ types: './dist/library/types.d.ts',
110
+ default: './dist/types.js'
111
+ }
112
+ packageJson.exports['./plugin'] = {
113
+ types: './dist/library/plugin.d.ts',
114
+ default: './dist/plugin.js'
115
+ }
116
+ packageJson.exports['./media'] = {
117
+ types: './dist/library/media.d.ts',
118
+ default: './dist/media.js'
119
+ }
120
+ packageJson.exports['./style.css'] = './dist/style.css'
121
+ packageJson.exports['./style/ui.scss'] = `./src/styles/${projectName}/main.scss`
122
+ packageJson.exports['./ui-properties'] = {
123
+ sass: './ui-properties.scss',
124
+ default: './ui-properties.scss'
125
+ }
126
+ packageJson.exports['./types.d.ts'] = './dist/library/types.d.ts'
127
+ packageJson['web-types'] = './dist/web-types.json'
128
+
129
+ PropertiesFile.writeByPath(UI_FILE_PACKAGE, packageJson)
130
+ }
131
+
132
+ return this
133
+ }
134
+
135
+ protected makeUiProperties(): this {
136
+ PropertiesFile.writeByPath(
137
+ UI_FILE_STYLE_PROPERTIES,
138
+ '@forward "./src/styles/Ui/style.scss";'
139
+ )
140
+
141
+ return this
142
+ }
73
143
  }