@dxtmisha/scripts 0.7.8 → 0.7.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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@dxtmisha/scripts",
3
3
  "private": false,
4
- "version": "0.7.8",
4
+ "version": "0.7.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": [
@@ -63,14 +63,16 @@
63
63
  "engines": {
64
64
  "node": ">=20.0.0"
65
65
  },
66
- "peerDependencies": {
66
+ "dependencies": {
67
+ "@anthropic-ai/sdk": "^0.89.0",
67
68
  "@dxtmisha/configuration": "*",
68
- "@dxtmisha/media": "*",
69
69
  "@dxtmisha/functional": "*",
70
70
  "@dxtmisha/functional-basic": "*",
71
+ "@dxtmisha/media": "*",
71
72
  "@dxtmisha/wiki": "*",
72
- "typescript": "^5.0.0",
73
- "vue": "^3.0.0"
74
- },
75
- "dependencies": {}
73
+ "@google/genai": "^1.50.1",
74
+ "puppeteer": "^24.41.0",
75
+ "typescript": "^6.0.2",
76
+ "vue": "^3.5.32"
77
+ }
76
78
  }
@@ -0,0 +1,26 @@
1
+ import { getConfigAi } from '../../functions/getConfigAi'
2
+ import { AiClaudeLite } from './AiClaudeLite'
3
+
4
+ /**
5
+ * Claude AI implementation of AiAbstract.
6
+ * Initializes Anthropic client and performs text generation requests.
7
+ *
8
+ * Реализация Claude AI поверх AiAbstract.
9
+ * Инициализирует клиент Anthropic и выполняет запросы генерации текста.
10
+ *
11
+ * Responsibilities / Ответственности:
12
+ * - Provide API key / Предоставить API ключ
13
+ * - Initialize low-level client / Инициализировать низкоуровневый клиент
14
+ * - Call messages.create and extract plain text / Вызвать messages.create и извлечь текст
15
+ *
16
+ * Notes / Примечания:
17
+ * - Model must be set via setModel() before generate() / Модель нужно задать через setModel()
18
+ * - Returns empty string if response is missing / Возвращает пустую строку при отсутствии результата
19
+ */
20
+ export class AiClaude extends AiClaudeLite {
21
+ constructor() {
22
+ super(
23
+ ...getConfigAi()
24
+ )
25
+ }
26
+ }
@@ -0,0 +1,24 @@
1
+ import { getConfigAi } from '../../functions/getConfigAi'
2
+ import { AiClaudeCliLite } from './AiClaudeCliLite'
3
+
4
+ /**
5
+ * Claude AI implementation via CLI.
6
+ * Extends AiClaudeCliLite and provides configuration from the project environment.
7
+ *
8
+ * Реализация Claude AI через CLI.
9
+ * Расширяет AiClaudeCliLite и предоставляет конфигурацию из окружения проекта.
10
+ *
11
+ * Responsibilities / Ответственности:
12
+ * - Provide API key and model from config / Предоставить API ключ и модель из конфигурации
13
+ * - Initialize CLI wrapper / Инициализировать обертку CLI
14
+ *
15
+ * Notes / Примечания:
16
+ * - Uses getConfigAi() to retrieve credentials / Использует getConfigAi() для получения учетных данных
17
+ */
18
+ export class AiClaudeCli extends AiClaudeCliLite {
19
+ constructor() {
20
+ super(
21
+ ...getConfigAi()
22
+ )
23
+ }
24
+ }
@@ -0,0 +1,145 @@
1
+ import { forEach } from '@dxtmisha/functional-basic'
2
+ import { exec } from 'node:child_process'
3
+
4
+ import { PropertiesFile } from '../Properties/PropertiesFile'
5
+ import { AiAbstract } from './AiAbstract'
6
+
7
+ const TEMPORARY_DIR = './ai-tmp'
8
+
9
+ /**
10
+ * Claude AI implementation via CLI.
11
+ * Uses system shell to execute Claude CLI commands.
12
+ *
13
+ * Реализация Claude AI через CLI.
14
+ * Использует системную оболочку для выполнения команд Claude CLI.
15
+ *
16
+ * Responsibilities / Ответственности:
17
+ * - Construct CLI command / Сформировать CLI команду
18
+ * - Execute command via shell / Выполнить команду через оболочку
19
+ * - Return stdout as result / Вернуть stdout как результат
20
+ *
21
+ * Notes / Примечания:
22
+ * - Requires 'claude' CLI tool installed (e.g., claude-cli) / Требует установленной утилиты 'claude'
23
+ * - API key is passed via environment variable or config / API ключ передается через переменную окружения или конфиг
24
+ */
25
+ export class AiClaudeCliLite extends AiAbstract<{}> {
26
+ /**
27
+ * Counter for generating unique temporary file names/
28
+ * Счетчик для генерации уникальных имен временных файлов
29
+ */
30
+ protected idFile = 1
31
+
32
+ /**
33
+ * Generates a unique file path for the temporary prompt.
34
+ *
35
+ * Генерирует уникальный путь к файлу для временного промпта.
36
+ */
37
+ protected getFileName(): string {
38
+ return `${TEMPORARY_DIR}/Prompt-${this.idFile++}.txt`
39
+ }
40
+
41
+ /**
42
+ * Initializes the "client".
43
+ * For CLI, we just mark it as initialized.
44
+ *
45
+ * Инициализирует "клиента".
46
+ * Для CLI мы просто помечаем его как инициализированный.
47
+ */
48
+ protected init(): void {
49
+ this.ai = {}
50
+ }
51
+
52
+ /**
53
+ * Implementation hook: convert accumulated images to model-specific format.
54
+ * CLI implementation currently ignores images.
55
+ *
56
+ * Хук реализации: преобразовать накопленные изображения в формат, специфичный для модели.
57
+ * Реализация CLI в настоящее время игнорирует изображения.
58
+ */
59
+ protected toImages(): any {
60
+ return []
61
+ }
62
+
63
+ /**
64
+ * Implementation hook: convert accumulated contents to model-specific format.
65
+ * Returns array of strings.
66
+ *
67
+ * Хук реализации: преобразовать накопленное содержимое в формат, специфичный для модели.
68
+ * Возвращает массив строк.
69
+ */
70
+ protected toContents(): any {
71
+ return forEach(
72
+ this.contents,
73
+ content => this.createFile(content)
74
+ )
75
+ }
76
+
77
+ /**
78
+ * Performs content generation request via CLI and returns textual result.
79
+ *
80
+ * Выполняет запрос генерации контента через CLI и возвращает текстовый результат.
81
+ * @param model Model identifier / Идентификатор модели
82
+ * @param contents Composed contents for generation / Собранный контент для генерации
83
+ */
84
+ protected async response(
85
+ model: string,
86
+ contents: string
87
+ ): Promise<string> {
88
+ return new Promise((resolve) => {
89
+ const fullPrompt = [
90
+ ...this.toContents(),
91
+ this.createFile(contents)
92
+ ].join('\n\n##################\n\n')
93
+
94
+ const escapedPrompt = fullPrompt.replace(/"/g, '\\"')
95
+ const modelFlag = model ? ` --model "${model}"` : ''
96
+ const command = `claude "${escapedPrompt}" Output strictly the code/answer. No preamble, no chatter, no reasoning ${modelFlag}`
97
+
98
+ exec(
99
+ command,
100
+ {
101
+ encoding: 'utf8',
102
+ env: {
103
+ ...process.env,
104
+ ANTHROPIC_API_KEY: this.key
105
+ }
106
+ },
107
+ (error, stdout, stderr) => {
108
+ if (error) {
109
+ console.error('Error executing Claude CLI:', stderr || error.message)
110
+ resolve('')
111
+ } else {
112
+ resolve(stdout.trim())
113
+ }
114
+ }
115
+ )
116
+
117
+ this.removeFile()
118
+ })
119
+ }
120
+
121
+ /**
122
+ * Creates a temporary file with the prompt content and returns the path formatted for the CLI.
123
+ *
124
+ * Создает временный файл с содержимым промпта и возвращает путь, отформатированный для CLI.
125
+ * @param content Prompt content / Содержимое промпта
126
+ * @returns Formatted file path (e.g., @./ai-tmp/Prompt-1.txt) / Отформатированный путь к файлу
127
+ */
128
+ protected createFile(content: string): string {
129
+ const name = this.getFileName()
130
+
131
+ PropertiesFile.writeByPath(name, content)
132
+
133
+ return `Please read the following file as it contains the prompt instructions: @${name}`
134
+ }
135
+
136
+ /**
137
+ * Cleans up temporary files and directories.
138
+ *
139
+ * Очищает временные файлы и директории.
140
+ * @protected
141
+ */
142
+ protected removeFile(): void {
143
+ PropertiesFile.removeDir(TEMPORARY_DIR)
144
+ }
145
+ }
@@ -0,0 +1,100 @@
1
+ import { forEach } from '@dxtmisha/functional-basic'
2
+ import { AiAbstract } from './AiAbstract'
3
+ import { Anthropic } from '@anthropic-ai/sdk'
4
+
5
+ /**
6
+ * Claude AI implementation of AiAbstract.
7
+ * Initializes Anthropic client and performs text generation requests.
8
+ *
9
+ * Реализация Claude AI поверх AiAbstract.
10
+ * Инициализирует клиент Anthropic и выполняет запросы генерации текста.
11
+ *
12
+ * Responsibilities / Ответственности:
13
+ * - Provide API key / Предоставить API ключ
14
+ * - Initialize Anthropic client / Инициализировать клиент Anthropic
15
+ * - Call messages.create and extract text content / Вызвать messages.create и извлечь текст
16
+ *
17
+ * Notes / Примечания:
18
+ * - Model must be set via setModel() before generate() / Модель нужно задать через setModel()
19
+ * - Returns empty string if response is missing / Возвращает пустую строку при отсутствии результата
20
+ */
21
+ export class AiClaudeLite extends AiAbstract<Anthropic> {
22
+ /**
23
+ * Initializes Anthropic client instance.
24
+ *
25
+ * Инициализирует экземпляр клиента Anthropic.
26
+ */
27
+ protected init(): void {
28
+ this.ai = new Anthropic({
29
+ apiKey: this.key
30
+ })
31
+ }
32
+
33
+ /**
34
+ * Implementation hook: convert accumulated images to model-specific format.
35
+ * Claude expects images as content blocks with type 'image'.
36
+ *
37
+ * Хук реализации: преобразовать накопленные изображения в формат, специфичный для модели.
38
+ * Claude ожидает изображения как блоки контента с типом 'image'.
39
+ */
40
+ protected toImages(): any {
41
+ return forEach(this.images, image => ({
42
+ type: 'image',
43
+ source: {
44
+ type: 'base64',
45
+ media_type: image.mime,
46
+ data: image.base64
47
+ }
48
+ }))
49
+ }
50
+
51
+ /**
52
+ * Implementation hook: convert accumulated contents to model-specific format.
53
+ * Claude expects text as content blocks with type 'text'.
54
+ *
55
+ * Хук реализации: преобразовать накопленное содержимое в формат, специфичный для модели.
56
+ * Claude ожидает текст как блоки контента с типом 'text'.
57
+ */
58
+ protected toContents(): any {
59
+ return forEach(this.contents, content => ({
60
+ type: 'text',
61
+ text: content
62
+ }))
63
+ }
64
+
65
+ /**
66
+ * Performs content generation request and returns textual result.
67
+ *
68
+ * Выполняет запрос генерации контента и возвращает текстовый результат.
69
+ * @param model Model identifier (e.g., 'claude-3-5-sonnet-20241022') / Идентификатор модели
70
+ * @param contents Composed contents for generation / Собранный контент для генерации
71
+ */
72
+ protected async response(
73
+ model: string,
74
+ contents: string
75
+ ): Promise<string> {
76
+ const message = await this.ai?.messages.create({
77
+ model,
78
+ max_tokens: this.config.maxTokens ?? 4096,
79
+ messages: [
80
+ {
81
+ role: 'user',
82
+ content: [
83
+ ...this.toImages(),
84
+ ...this.toContents(),
85
+ { type: 'text', text: contents }
86
+ ]
87
+ }
88
+ ],
89
+ ...this.config
90
+ })
91
+
92
+ // Extract text from content blocks
93
+ const textContent = message?.content
94
+ ?.filter(block => block.type === 'text')
95
+ .map(block => 'text' in block ? block.text : '')
96
+ .join('\n')
97
+
98
+ return textContent ?? ''
99
+ }
100
+ }
@@ -1,4 +1,4 @@
1
- import { toCamelCaseFirst } from '@dxtmisha/functional-basic'
1
+ import { ServerStorage, toCamelCaseFirst } from '@dxtmisha/functional-basic'
2
2
  import { getPackageJson } from '../../functions/getPackageJson'
3
3
 
4
4
  import { PropertiesConfig } from '../Properties/PropertiesConfig'
@@ -27,6 +27,7 @@ export class DesignWikiStorm {
27
27
  constructor(
28
28
  protected dir: string = 'dist'
29
29
  ) {
30
+ ServerStorage.setErrorStatus(true)
30
31
  this.components = new LibraryItems()
31
32
  }
32
33
 
@@ -0,0 +1,49 @@
1
+ import puppeteer from 'puppeteer'
2
+ import {
3
+ SCREENSHOT_FORMAT,
4
+ SCREENSHOT_HEIGHTS,
5
+ SCREENSHOT_QUALITY,
6
+ SCREENSHOT_WIDTHS,
7
+ type ScreenshotOptions
8
+ } from '../types/screenshotTypes'
9
+
10
+ /**
11
+ * Takes a screenshot of the given URL.
12
+ *
13
+ * Делает скриншот по указанному URL.
14
+ * @param url URL to capture/URL для захвата
15
+ * @param outputPath Path to save the screenshot/Путь для сохранения скриншота
16
+ * @param options Additional options for screenshot/Дополнительные опции для скриншота
17
+ */
18
+ export async function takeScreenshot(
19
+ url: string,
20
+ outputPath: string,
21
+ options: ScreenshotOptions = {}
22
+ ): Promise<void> {
23
+ const {
24
+ width = SCREENSHOT_WIDTHS,
25
+ height = SCREENSHOT_HEIGHTS,
26
+ format = SCREENSHOT_FORMAT,
27
+ quality = SCREENSHOT_QUALITY,
28
+ fullPage = true
29
+ } = options
30
+
31
+ const browser = await puppeteer.launch()
32
+ const page = await browser.newPage()
33
+
34
+ try {
35
+ await page.setViewport({ width, height })
36
+ await page.goto(url, { waitUntil: 'networkidle2' })
37
+
38
+ await page.screenshot({
39
+ path: outputPath,
40
+ fullPage,
41
+ type: format,
42
+ quality
43
+ })
44
+ } catch (error) {
45
+ console.error('Error taking screenshot:', error)
46
+ } finally {
47
+ await browser.close()
48
+ }
49
+ }
package/src/library-ai.ts CHANGED
@@ -1,3 +1,10 @@
1
1
  // Classes
2
2
  export * from './classes/Ai/AiAbstract'
3
3
  export * from './classes/Ai/AiGoogleLite'
4
+ export * from './classes/Ai/AiGoogle'
5
+ export * from './classes/Ai/AiGoogleCliLite'
6
+ export * from './classes/Ai/AiGoogleCli'
7
+ export * from './classes/Ai/AiClaudeLite'
8
+ export * from './classes/Ai/AiClaude'
9
+ export * from './classes/Ai/AiClaudeCliLite'
10
+ export * from './classes/Ai/AiClaudeCli'
package/src/library.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  // Classes
2
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'
3
7
  export * from './classes/Ai/AiDoc'
4
8
  export * from './classes/Ai/AiDocItem'
5
9
  export * from './classes/Ai/AiDocItemAbstract'
@@ -33,6 +37,7 @@ export * from './functions/getConfigAi'
33
37
  export * from './functions/getDirname'
34
38
  export * from './functions/getPackageJson'
35
39
  export * from './functions/hasNativeDirname'
40
+ export * from './functions/takeScreenshot'
36
41
 
37
42
  // Types
38
43
  export * from './types/aiTypes'
@@ -41,4 +46,5 @@ export * from './types/designTypes'
41
46
  export * from './types/gitTypes'
42
47
  export * from './types/libraryTypes'
43
48
  export * from './types/propertyTypes'
49
+ export * from './types/screenshotTypes'
44
50
  export * from './types/webTypes'
@@ -0,0 +1,25 @@
1
+ /** Options for taking screenshots/ Опции для создания скриншотов */
2
+ export interface ScreenshotOptions {
3
+ /** Width of the screenshot/ Ширина скриншота */
4
+ width?: number
5
+ /** Height of the screenshot/ Высота скриншота */
6
+ height?: number
7
+ /** Format of the screenshot/ Формат скриншота */
8
+ format?: 'png' | 'jpeg' | 'webp'
9
+ /** Quality of the screenshot/ Качество скриншота */
10
+ quality?: number
11
+ /** Whether to take a full page screenshot/ Делать ли скриншот всей страницы */
12
+ fullPage?: boolean
13
+ }
14
+
15
+ /** Default screenshot widths/ Стандартные ширины скриншотов */
16
+ export const SCREENSHOT_WIDTHS = 1920
17
+
18
+ /** Default screenshot heights/ Стандартные высоты скриншотов */
19
+ export const SCREENSHOT_HEIGHTS = 1080
20
+
21
+ /** Default screenshot format/ Стандартный формат скриншотов */
22
+ export const SCREENSHOT_FORMAT = 'webp'
23
+
24
+ /** Default screenshot quality/ Стандартное качество скриншотов */
25
+ export const SCREENSHOT_QUALITY = 80