postcrm-plugin-cli 0.1.0__tar.gz

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,33 @@
1
+ PostCRM Plugin CLI License
2
+
3
+ Copyright (c) 2026 PostLTD. All rights reserved.
4
+
5
+ This license applies to the PostCRM Plugin CLI published by PostLTD: the
6
+ postcrm-plugin-cli Python package, including its source code, documentation
7
+ and build artifacts (the "CLI").
8
+
9
+ 1. Grant of use. PostLTD grants you a non-exclusive, royalty-free right to
10
+ use, copy, modify and compile the CLI solely to develop, build, test and
11
+ run plugins for the PostCRM platform.
12
+
13
+ 2. Restrictions. You may not:
14
+ a) sell, resell, sublicense or otherwise make the CLI available as a
15
+ standalone product, or as part of a product whose primary value is the
16
+ CLI itself;
17
+ b) publish, distribute or repackage the CLI (including modified copies) to
18
+ any public or private package registry, marketplace or repository as an
19
+ independent product;
20
+ c) remove or alter this license or any copyright notice.
21
+
22
+ 3. Plugins. Plugins that you develop using the CLI are your own work and may be
23
+ distributed under terms of your choice, provided that they do not contain or
24
+ redistribute the CLI itself.
25
+
26
+ 4. No warranty. THE CLI IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
29
+ EVENT SHALL POSTLTD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY
30
+ ARISING FROM THE USE OF THE CLI.
31
+
32
+ 5. Termination. This license terminates automatically if you breach any of its
33
+ terms.
@@ -0,0 +1,109 @@
1
+ Metadata-Version: 2.3
2
+ Name: postcrm-plugin-cli
3
+ Version: 0.1.0
4
+ Summary: PostCRM plugin packaging CLI
5
+ License: PostCRM Plugin CLI License
6
+
7
+ Copyright (c) 2026 PostLTD. All rights reserved.
8
+
9
+ This license applies to the PostCRM Plugin CLI published by PostLTD: the
10
+ postcrm-plugin-cli Python package, including its source code, documentation
11
+ and build artifacts (the "CLI").
12
+
13
+ 1. Grant of use. PostLTD grants you a non-exclusive, royalty-free right to
14
+ use, copy, modify and compile the CLI solely to develop, build, test and
15
+ run plugins for the PostCRM platform.
16
+
17
+ 2. Restrictions. You may not:
18
+ a) sell, resell, sublicense or otherwise make the CLI available as a
19
+ standalone product, or as part of a product whose primary value is the
20
+ CLI itself;
21
+ b) publish, distribute or repackage the CLI (including modified copies) to
22
+ any public or private package registry, marketplace or repository as an
23
+ independent product;
24
+ c) remove or alter this license or any copyright notice.
25
+
26
+ 3. Plugins. Plugins that you develop using the CLI are your own work and may be
27
+ distributed under terms of your choice, provided that they do not contain or
28
+ redistribute the CLI itself.
29
+
30
+ 4. No warranty. THE CLI IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
33
+ EVENT SHALL POSTLTD BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY
34
+ ARISING FROM THE USE OF THE CLI.
35
+
36
+ 5. Termination. This license terminates automatically if you breach any of its
37
+ terms.
38
+ Author: PostCRM
39
+ Requires-Python: >=3.12,<4.0
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Environment :: Console
42
+ Classifier: License :: Other/Proprietary License
43
+ Requires-Dist: postcrm-plugin-sdk (>=0.1.3,<0.2.0)
44
+ Description-Content-Type: text/markdown
45
+
46
+ # postcrm-plugin-cli
47
+
48
+ CLI для создания, сборки и проверки плагинов PostCRM. Пакет публикуется в
49
+ публичный PyPI, репозиторий для создания каркаса плагина не нужен.
50
+
51
+ ## Установка
52
+
53
+ ```bash
54
+ pipx install postcrm-plugin-cli
55
+ ```
56
+
57
+ Или в текущее окружение:
58
+
59
+ ```bash
60
+ pip install postcrm-plugin-cli
61
+ ```
62
+
63
+ Требуется Python 3.12 или новее. Для установки не нужны токены и
64
+ дополнительный index-url.
65
+
66
+ ## Команды
67
+
68
+ - `init` - создать каркас плагина с manifest, frontend и backend.
69
+ - `keygen` - создать пару ключей Ed25519 для подписи пакета.
70
+ - `pack` - собрать и подписать `.postcrm-plugin`.
71
+ - `validate` - проверить структуру, checksums и manifest пакета.
72
+
73
+ ## Создание каркаса
74
+
75
+ ```bash
76
+ postcrm-plugin init ./my-plugin \
77
+ --plugin-id ru.example.myplugin \
78
+ --name "My plugin" \
79
+ --publisher postltd
80
+ ```
81
+
82
+ В каталоге `my-plugin` появятся `manifest.json`, frontend-приложение с
83
+ dev-harness (`frontend/dev/main.ts`, `frontend/vite.dev.config.ts`) и backend
84
+ с `backend/requirements.lock`.
85
+
86
+ ## Сборка и проверка
87
+
88
+ ```bash
89
+ postcrm-plugin keygen --private key.pem --public key.pub
90
+ postcrm-plugin pack ./my-plugin -o my-plugin.postcrm-plugin -k key.pem --key-id dev
91
+ postcrm-plugin validate my-plugin.postcrm-plugin
92
+ ```
93
+
94
+ ## Разработка в монорепозитории
95
+
96
+ В каталоге `plugin-cli` CLI запускается из Poetry:
97
+
98
+ ```bash
99
+ cd plugin-cli
100
+ poetry install
101
+ poetry run postcrm-plugin --help
102
+ ```
103
+
104
+ ## Лицензия
105
+
106
+ Пакет распространяется по PostCRM Plugin CLI License (см. `LICENSE` в
107
+ пакете): CLI разрешено использовать только для разработки, сборки и запуска
108
+ плагинов PostCRM.
109
+
@@ -0,0 +1,63 @@
1
+ # postcrm-plugin-cli
2
+
3
+ CLI для создания, сборки и проверки плагинов PostCRM. Пакет публикуется в
4
+ публичный PyPI, репозиторий для создания каркаса плагина не нужен.
5
+
6
+ ## Установка
7
+
8
+ ```bash
9
+ pipx install postcrm-plugin-cli
10
+ ```
11
+
12
+ Или в текущее окружение:
13
+
14
+ ```bash
15
+ pip install postcrm-plugin-cli
16
+ ```
17
+
18
+ Требуется Python 3.12 или новее. Для установки не нужны токены и
19
+ дополнительный index-url.
20
+
21
+ ## Команды
22
+
23
+ - `init` - создать каркас плагина с manifest, frontend и backend.
24
+ - `keygen` - создать пару ключей Ed25519 для подписи пакета.
25
+ - `pack` - собрать и подписать `.postcrm-plugin`.
26
+ - `validate` - проверить структуру, checksums и manifest пакета.
27
+
28
+ ## Создание каркаса
29
+
30
+ ```bash
31
+ postcrm-plugin init ./my-plugin \
32
+ --plugin-id ru.example.myplugin \
33
+ --name "My plugin" \
34
+ --publisher postltd
35
+ ```
36
+
37
+ В каталоге `my-plugin` появятся `manifest.json`, frontend-приложение с
38
+ dev-harness (`frontend/dev/main.ts`, `frontend/vite.dev.config.ts`) и backend
39
+ с `backend/requirements.lock`.
40
+
41
+ ## Сборка и проверка
42
+
43
+ ```bash
44
+ postcrm-plugin keygen --private key.pem --public key.pub
45
+ postcrm-plugin pack ./my-plugin -o my-plugin.postcrm-plugin -k key.pem --key-id dev
46
+ postcrm-plugin validate my-plugin.postcrm-plugin
47
+ ```
48
+
49
+ ## Разработка в монорепозитории
50
+
51
+ В каталоге `plugin-cli` CLI запускается из Poetry:
52
+
53
+ ```bash
54
+ cd plugin-cli
55
+ poetry install
56
+ poetry run postcrm-plugin --help
57
+ ```
58
+
59
+ ## Лицензия
60
+
61
+ Пакет распространяется по PostCRM Plugin CLI License (см. `LICENSE` в
62
+ пакете): CLI разрешено использовать только для разработки, сборки и запуска
63
+ плагинов PostCRM.
@@ -0,0 +1 @@
1
+ """PostCRM plugin CLI."""
@@ -0,0 +1,511 @@
1
+ """CLI сборки и проверки плагинных пакетов."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import re
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ from postcrm_plugin_sdk.packaging import (
11
+ PackageError,
12
+ build_package,
13
+ generate_keypair,
14
+ inspect_package,
15
+ )
16
+
17
+ REQUIRED_MANIFEST_FIELDS = {"apiVersion", "id", "version", "name", "publisher", "compatibility"}
18
+ REMOTE_NAME_PART_RE = re.compile(r"[^a-zA-Z0-9_]")
19
+
20
+
21
+ def build_remote_name(plugin_id: str, version: str, package_hash: str = "00000000") -> str:
22
+ """Строит remote name в едином формате control plane.
23
+
24
+ :param plugin_id: str - Идентификатор плагина.
25
+ :param version: str - SemVer версии.
26
+ :param package_hash: str - Hash пакета; до сборки используется placeholder.
27
+
28
+ :return: str - Имя `plugin_<hash8>_<version>_<package_hash8>`.
29
+ """
30
+ digest = hashlib.sha256(plugin_id.encode("utf-8")).hexdigest()[:8]
31
+ version_part = REMOTE_NAME_PART_RE.sub("_", version)
32
+ package_part = REMOTE_NAME_PART_RE.sub("_", package_hash)[:8]
33
+ return f"plugin_{digest}_{version_part}_{package_part}"
34
+
35
+
36
+ def cmd_keygen(args: argparse.Namespace) -> int:
37
+ """Создаёт Ed25519 keypair."""
38
+ generate_keypair(args.private, args.public)
39
+ print(f"private: {args.private}\npublic: {args.public}")
40
+ return 0
41
+
42
+
43
+ def cmd_validate(args: argparse.Namespace) -> int:
44
+ """Проверяет структуру, checksums и manifest пакета."""
45
+ try:
46
+ inspection = inspect_package(Path(args.package).read_bytes())
47
+ except PackageError as error:
48
+ print(f"invalid: {error}", file=sys.stderr)
49
+ return 1
50
+ manifest = inspection["manifest"]
51
+ missing = sorted(REQUIRED_MANIFEST_FIELDS - set(manifest))
52
+ if missing:
53
+ print(f"invalid manifest: missing {', '.join(missing)}", file=sys.stderr)
54
+ return 1
55
+ if args.json:
56
+ print(json.dumps({"ok": True, "packageHash": inspection["packageHash"], "manifest": manifest}))
57
+ else:
58
+ print(f"ok: {manifest['id']}@{manifest['version']} {inspection['packageHash']}")
59
+ return 0
60
+
61
+
62
+ def cmd_pack(args: argparse.Namespace) -> int:
63
+ """Собирает и подписывает пакет."""
64
+ try:
65
+ output = build_package(
66
+ source_dir=args.source,
67
+ output=args.output,
68
+ private_key_path=args.key,
69
+ key_id=args.key_id,
70
+ sbom_components=(
71
+ json.loads(Path(args.sbom_components).read_text(encoding="utf-8")) if args.sbom_components else None
72
+ ),
73
+ )
74
+ except (PackageError, OSError, ValueError) as error:
75
+ print(f"pack failed: {error}", file=sys.stderr)
76
+ return 1
77
+ print(str(output))
78
+ return 0
79
+
80
+
81
+ DEV_HARNESS_TEMPLATE = """<template>
82
+ <div class="dev-harness">
83
+ <q-card dark class="dev-harness__card">
84
+ <q-card-section>
85
+ <div class="text-h6">PostCRM dev-harness</div>
86
+ <div class="text-caption">
87
+ {{ context.pluginId }}@{{ context.version }}
88
+ </div>
89
+ <div class="text-caption">
90
+ Доступные компоненты: {{ componentNames.join(', ') }}
91
+ </div>
92
+ </q-card-section>
93
+ </q-card>
94
+
95
+ <q-card v-if="pluginPage" dark class="dev-harness__card">
96
+ <q-card-section>
97
+ <div class="text-subtitle1">PluginPage</div>
98
+ </q-card-section>
99
+ <q-card-section>
100
+ <component :is="pluginPage" :context="context" />
101
+ </q-card-section>
102
+ </q-card>
103
+
104
+ <q-card v-if="dashboardWidget" dark class="dev-harness__card">
105
+ <q-card-section>
106
+ <div class="text-subtitle1">DashboardWidget</div>
107
+ </q-card-section>
108
+ <q-card-section>
109
+ <component
110
+ :is="dashboardWidget"
111
+ :context="context"
112
+ :props="mockProps"
113
+ />
114
+ </q-card-section>
115
+ </q-card>
116
+
117
+ <q-card v-if="inquiryCardBlock" dark class="dev-harness__card">
118
+ <q-card-section>
119
+ <div class="text-subtitle1">InquiryCardBlock</div>
120
+ </q-card-section>
121
+ <q-card-section>
122
+ <component
123
+ :is="inquiryCardBlock"
124
+ :context="context"
125
+ :props="mockProps"
126
+ />
127
+ </q-card-section>
128
+ </q-card>
129
+
130
+ <q-card v-if="actionButton" dark class="dev-harness__card">
131
+ <q-card-section>
132
+ <div class="text-subtitle1">ActionButton</div>
133
+ </q-card-section>
134
+ <q-card-section>
135
+ <component
136
+ :is="actionButton"
137
+ :context="context"
138
+ :props="mockProps"
139
+ />
140
+ </q-card-section>
141
+ </q-card>
142
+ </div>
143
+ </template>
144
+
145
+ <script setup lang="ts">
146
+ import type { Component } from 'vue';
147
+ import { createMockContext } from './mockContext';
148
+
149
+ const modules = import.meta.glob('../src/*.vue', { eager: true }) as Record<
150
+ string,
151
+ { default: Component }
152
+ >;
153
+
154
+ function resolveComponent(name: string): Component | null {
155
+ const match = Object.entries(modules).find(([path]) =>
156
+ path.endsWith(`/${name}`)
157
+ );
158
+ return match ? match[1].default : null;
159
+ }
160
+
161
+ const context = createMockContext('__PLUGIN_ID__', '0.1.0');
162
+ const mockProps = { inquiryId: 1, interactionId: 1, ids: [1] };
163
+ const componentNames = Object.keys(modules).map(
164
+ path => path.split('/').pop() ?? path
165
+ );
166
+ const pluginPage = resolveComponent('PluginPage.vue');
167
+ const dashboardWidget = resolveComponent('DashboardWidget.vue');
168
+ const inquiryCardBlock = resolveComponent('InquiryCardBlock.vue');
169
+ const actionButton = resolveComponent('ActionButton.vue');
170
+ </script>
171
+
172
+ <style scoped>
173
+ .dev-harness {
174
+ display: flex;
175
+ flex-direction: column;
176
+ gap: 16px;
177
+ padding: 24px;
178
+ }
179
+
180
+ .dev-harness__card {
181
+ border-radius: 10px;
182
+ }
183
+ </style>
184
+ """
185
+
186
+ DEV_HARNESS_README = """# Frontend плагина
187
+
188
+ ## Визуальная проверка в dev-harness
189
+
190
+ ```bash
191
+ cd frontend
192
+ pnpm install
193
+ pnpm dev
194
+ ```
195
+
196
+ Harness открывается по адресу http://localhost:5173. Он рендерит `PluginPage`
197
+ и, если они есть в `src/`, компоненты `DashboardWidget`, `InquiryCardBlock`
198
+ и `ActionButton` с mock-props.
199
+
200
+ Mock-context не ходит в CRM: `api`, `external`, `navigate`, `onEvent` и
201
+ `publishEvent` только логируют вызовы в консоль браузера и возвращают
202
+ заглушки. Для проверки реальной интеграции с CRM нужен dev-remote override:
203
+ запустите `pnpm dev` в плагине и откройте CRM в dev-режиме с параметрами
204
+ `?pluginRemote=http://localhost:5173/remoteEntry.js&pluginRemoteName=<remoteName>`.
205
+ Подробности - в `docs/plugin-sdk-v1.md`, раздел "Визуальная проверка плагина".
206
+ """
207
+
208
+
209
+ def cmd_init(args: argparse.Namespace) -> int:
210
+ """Создаёт минимальный каркас плагина."""
211
+ target = Path(args.directory)
212
+ (target / "frontend" / "src").mkdir(parents=True, exist_ok=True)
213
+ (target / "backend" / "plugin").mkdir(parents=True, exist_ok=True)
214
+ plugin_id = args.plugin_id
215
+ plugin_id_slug = plugin_id.replace(".", "_").replace("-", "_")
216
+ sdk_ui_dependency = f"file:{args.local_sdk}" if args.local_sdk else "^0.1.3"
217
+ manifest = {
218
+ "apiVersion": "postcrm.io/v1alpha1",
219
+ "id": plugin_id,
220
+ "version": "0.1.0",
221
+ "name": args.name,
222
+ "publisher": args.publisher,
223
+ "trust": "trusted",
224
+ "compatibility": {
225
+ "core": ">=0.9 <2",
226
+ "pluginSdk": "1",
227
+ "python": "3.12",
228
+ "runnerPlatform": "python3.12-bookworm",
229
+ },
230
+ "navigation": {
231
+ "surface": "admin",
232
+ "title": args.name,
233
+ "icon": "mdi-puzzle",
234
+ "order": 500,
235
+ "suggestedRoles": ["AD"],
236
+ },
237
+ "frontend": {
238
+ "exposedModule": "./PluginPage",
239
+ "entry": "remoteEntry.js",
240
+ "remoteName": build_remote_name(plugin_id, "0.1.0"),
241
+ "shared": ["vue", "quasar", "pinia", "vue-router"],
242
+ },
243
+ "backend": {"entry": "plugin.main:create_app", "healthPath": "/healthz"},
244
+ "requestedPermissions": ["extensions.pages"],
245
+ }
246
+ (target / "manifest.json").write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding="utf-8")
247
+ (target / "frontend" / "src" / "PluginPage.vue").write_text(
248
+ "<template><div>{{ context.pluginId }}</div></template>\n"
249
+ '<script setup lang="ts">defineProps<{ context: any }>();</script>\n',
250
+ encoding="utf-8",
251
+ )
252
+ (target / "backend" / "plugin" / "main.py").write_text(
253
+ "from fastapi import APIRouter\n"
254
+ "from postcrm_plugin_sdk import create_app\n\n"
255
+ "router = APIRouter()\n\n"
256
+ "@router.get('/hello')\n"
257
+ "async def hello() -> dict[str, str]:\n"
258
+ " return {'message': 'hello'}\n\n"
259
+ "app = create_app(router=router)\n",
260
+ encoding="utf-8",
261
+ )
262
+ (target / "frontend" / "index.html").write_text(
263
+ "<!doctype html>\n"
264
+ '<html lang="ru">\n'
265
+ " <head>\n"
266
+ ' <meta charset="UTF-8" />\n'
267
+ " <title>PostCRM plugin</title>\n"
268
+ " </head>\n"
269
+ " <body>\n"
270
+ ' <div id="app"></div>\n'
271
+ " </body>\n"
272
+ "</html>\n",
273
+ encoding="utf-8",
274
+ )
275
+ (target / "frontend" / "package.json").write_text(
276
+ json.dumps(
277
+ {
278
+ "name": f"@{plugin_id_slug}/ui",
279
+ "private": True,
280
+ "type": "module",
281
+ "scripts": {
282
+ "dev": "vite --config vite.dev.config.ts",
283
+ "build": "vite build",
284
+ },
285
+ "dependencies": {
286
+ "@quasar/extras": "^1.16.12",
287
+ "postcrm-plugin-sdk-ui": sdk_ui_dependency,
288
+ "quasar": "^2.17.7",
289
+ "vue": "^3.5.13",
290
+ },
291
+ "devDependencies": {
292
+ "@module-federation/vite": "1.24.0",
293
+ "@vitejs/plugin-vue": "5.2.1",
294
+ "typescript": "^5.4.5",
295
+ "vite": "5.4.14",
296
+ },
297
+ },
298
+ ensure_ascii=False,
299
+ indent=2,
300
+ ),
301
+ encoding="utf-8",
302
+ )
303
+ (target / "frontend" / "vite.config.ts").write_text(
304
+ "import { defineConfig } from 'vite';\n"
305
+ "import vue from '@vitejs/plugin-vue';\n"
306
+ "import { federation } from '@module-federation/vite';\n\n"
307
+ "export default defineConfig({\n"
308
+ " base: './',\n"
309
+ " plugins: [\n"
310
+ " vue(),\n"
311
+ " federation({\n"
312
+ f" name: '{build_remote_name(plugin_id, '0.1.0')}',\n"
313
+ " filename: 'remoteEntry.js',\n"
314
+ " exposes: { './PluginPage': './src/PluginPage.vue' },\n"
315
+ " shared: { vue: { singleton: true } },\n"
316
+ " manifest: false,\n"
317
+ " dts: false,\n"
318
+ " }),\n"
319
+ " ],\n"
320
+ " build: { outDir: 'dist', assetsDir: 'assets' },\n"
321
+ "});\n",
322
+ encoding="utf-8",
323
+ )
324
+ (target / "frontend" / ".gitignore").write_text("node_modules\ndist\n.quasar\n", encoding="utf-8")
325
+ (target / "frontend" / "vite.dev.config.ts").write_text(
326
+ "import { defineConfig } from 'vite';\n"
327
+ "import vue from '@vitejs/plugin-vue';\n\n"
328
+ "// Harness рендерит компоненты напрямую, без Module Federation.\n"
329
+ "export default defineConfig({\n"
330
+ " root: 'dev',\n"
331
+ " plugins: [vue()],\n"
332
+ " resolve: {\n"
333
+ " alias: {\n"
334
+ " '@': '../src',\n"
335
+ " },\n"
336
+ " },\n"
337
+ " server: {\n"
338
+ " port: 5173,\n"
339
+ " strictPort: true,\n"
340
+ " cors: true,\n"
341
+ " },\n"
342
+ "});\n",
343
+ encoding="utf-8",
344
+ )
345
+ (target / "frontend" / "dev").mkdir(exist_ok=True)
346
+ (target / "frontend" / "dev" / "index.html").write_text(
347
+ "<!doctype html>\n"
348
+ '<html lang="ru">\n'
349
+ " <head>\n"
350
+ ' <meta charset="UTF-8" />\n'
351
+ ' <meta name="viewport" content="width=device-width, initial-scale=1.0" />\n'
352
+ " <title>PostCRM plugin dev-harness</title>\n"
353
+ " </head>\n"
354
+ " <body>\n"
355
+ ' <div id="app"></div>\n'
356
+ ' <script type="module" src="/main.ts"></script>\n'
357
+ " </body>\n"
358
+ "</html>\n",
359
+ encoding="utf-8",
360
+ )
361
+ (target / "frontend" / "dev" / "main.ts").write_text(
362
+ "import { createApp } from 'vue';\n"
363
+ "import { Dark, Quasar } from 'quasar';\n"
364
+ "import 'quasar/dist/quasar.prod.css';\n"
365
+ "import '@quasar/extras/material-icons/material-icons.css';\n"
366
+ "import DevHarness from './DevHarness.vue';\n\n"
367
+ "const app = createApp(DevHarness);\n"
368
+ "app.use(Quasar, { config: {} });\n"
369
+ "Dark.set(true);\n"
370
+ "app.mount('#app');\n",
371
+ encoding="utf-8",
372
+ )
373
+ (target / "frontend" / "dev" / "mockContext.ts").write_text(
374
+ "import type { PluginContext } from 'postcrm-plugin-sdk-ui';\n\n"
375
+ "type MockContext = PluginContext & { locale: string };\n\n"
376
+ "function logCall(method: string, ...args: unknown[]): void {\n"
377
+ " console.info(`[dev-harness] ${method}`, ...args);\n"
378
+ "}\n\n"
379
+ "/**\n"
380
+ " * Создаёт mock-context для визуальной проверки без CRM.\n"
381
+ " *\n"
382
+ " * Все вызовы API, external HTTP, navigate и событий только логируются\n"
383
+ " * и возвращают заглушку, поэтому harness не ходит в реальную CRM.\n"
384
+ " *\n"
385
+ " * :param pluginId: Идентификатор плагина.\n"
386
+ " * :param version: Версия плагина.\n"
387
+ " * :return: Контекст, совместимый с PluginContext.\n"
388
+ " */\n"
389
+ "export function createMockContext(\n"
390
+ " pluginId: string,\n"
391
+ " version: string\n"
392
+ "): MockContext {\n"
393
+ " const resolveMock = <T>(method: string, target: string): Promise<T> => {\n"
394
+ " logCall(method, target);\n"
395
+ " return Promise.resolve({ ok: true } as T);\n"
396
+ " };\n\n"
397
+ " return {\n"
398
+ " pluginId,\n"
399
+ " version,\n"
400
+ " surface: 'admin',\n"
401
+ " accountId: 1,\n"
402
+ " userId: 1,\n"
403
+ " role: 'ADMIN',\n"
404
+ " apiBase: '/api/v1',\n"
405
+ " sdkVersion: '1',\n"
406
+ " capabilities: [],\n"
407
+ " locale: 'ru-RU',\n"
408
+ " api: {\n"
409
+ " get: <T>(path: string) => resolveMock<T>('api.get', path),\n"
410
+ " post: <T>(path: string, data?: unknown) => {\n"
411
+ " logCall('api.post', path, data);\n"
412
+ " return Promise.resolve({ ok: true } as T);\n"
413
+ " },\n"
414
+ " put: <T>(path: string, data?: unknown) => {\n"
415
+ " logCall('api.put', path, data);\n"
416
+ " return Promise.resolve({ ok: true } as T);\n"
417
+ " },\n"
418
+ " patch: <T>(path: string, data?: unknown) => {\n"
419
+ " logCall('api.patch', path, data);\n"
420
+ " return Promise.resolve({ ok: true } as T);\n"
421
+ " },\n"
422
+ " delete: <T>(path: string) =>\n"
423
+ " resolveMock<T>('api.delete', path),\n"
424
+ " },\n"
425
+ " external: {\n"
426
+ " allowedOrigins: [],\n"
427
+ " get: <T>(url: string, headers?: Record<string, string>) => {\n"
428
+ " logCall('external.get', url, headers);\n"
429
+ " return Promise.resolve({ ok: true } as T);\n"
430
+ " },\n"
431
+ " post: <T>(\n"
432
+ " url: string,\n"
433
+ " body: unknown,\n"
434
+ " headers?: Record<string, string>\n"
435
+ " ) => {\n"
436
+ " logCall('external.post', url, body, headers);\n"
437
+ " return Promise.resolve({ ok: true } as T);\n"
438
+ " },\n"
439
+ " },\n"
440
+ " navigate: (path: string) => logCall('navigate', path),\n"
441
+ " onEvent: () => {\n"
442
+ " logCall('onEvent');\n"
443
+ " return () => undefined;\n"
444
+ " },\n"
445
+ " publishEvent: async (\n"
446
+ " eventKey: string,\n"
447
+ " payload: Record<string, unknown>\n"
448
+ " ) => {\n"
449
+ " logCall('publishEvent', eventKey, payload);\n"
450
+ " },\n"
451
+ " };\n"
452
+ "}\n",
453
+ encoding="utf-8",
454
+ )
455
+ (target / "frontend" / "dev" / "DevHarness.vue").write_text(
456
+ DEV_HARNESS_TEMPLATE.replace("__PLUGIN_ID__", plugin_id),
457
+ encoding="utf-8",
458
+ )
459
+ (target / "frontend" / "README.md").write_text(
460
+ DEV_HARNESS_README,
461
+ encoding="utf-8",
462
+ )
463
+ (target / "backend" / "requirements.lock").write_text(
464
+ "postcrm-plugin-sdk==0.1.3\nuvicorn>=0.30.1\n", encoding="utf-8"
465
+ )
466
+ (target / "backend" / "wheels").mkdir(exist_ok=True)
467
+ print(f"created {target}")
468
+ return 0
469
+
470
+
471
+ def build_parser() -> argparse.ArgumentParser:
472
+ """Собирает argparse-парсер."""
473
+ parser = argparse.ArgumentParser(prog="postcrm-plugin", description="PostCRM plugin CLI")
474
+ sub = parser.add_subparsers(dest="command", required=True)
475
+ keygen = sub.add_parser("keygen", help="создать Ed25519 keypair")
476
+ keygen.add_argument("--private", required=True)
477
+ keygen.add_argument("--public", required=True)
478
+ keygen.set_defaults(func=cmd_keygen)
479
+
480
+ validate = sub.add_parser("validate", help="проверить пакет")
481
+ validate.add_argument("package")
482
+ validate.add_argument("--json", action="store_true")
483
+ validate.set_defaults(func=cmd_validate)
484
+
485
+ pack = sub.add_parser("pack", help="собрать подписанный пакет")
486
+ pack.add_argument("source")
487
+ pack.add_argument("-o", "--output", required=True)
488
+ pack.add_argument("-k", "--key", required=True)
489
+ pack.add_argument("--key-id", required=True)
490
+ pack.add_argument("--sbom-components")
491
+ pack.set_defaults(func=cmd_pack)
492
+
493
+ init = sub.add_parser("init", help="создать каркас плагина")
494
+ init.add_argument("directory")
495
+ init.add_argument("--plugin-id", required=True)
496
+ init.add_argument("--name", required=True)
497
+ init.add_argument("--publisher", default="postltd")
498
+ init.add_argument("--local-sdk", metavar="PATH", help="использовать локальную сборку UI SDK через file:<PATH>")
499
+ init.set_defaults(func=cmd_init)
500
+ return parser
501
+
502
+
503
+ def main() -> int:
504
+ """Точка входа CLI."""
505
+ parser = build_parser()
506
+ args = parser.parse_args()
507
+ return int(args.func(args))
508
+
509
+
510
+ if __name__ == "__main__":
511
+ raise SystemExit(main())
@@ -0,0 +1,45 @@
1
+ [project]
2
+ name = "postcrm-plugin-cli"
3
+ version = "0.1.0"
4
+ description = "PostCRM plugin packaging CLI"
5
+ authors = [{ name = "PostCRM" }]
6
+ license = { file = "LICENSE" }
7
+ readme = "README.md"
8
+ requires-python = ">=3.12,<4.0"
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3.12",
11
+ "Environment :: Console",
12
+ "License :: Other/Proprietary License",
13
+ ]
14
+ dynamic = ["dependencies"]
15
+
16
+ [project.scripts]
17
+ postcrm-plugin = "postcrm_plugin_cli.main:main"
18
+
19
+ [tool.poetry]
20
+ packages = [{ include = "postcrm_plugin_cli" }]
21
+ include = ["LICENSE", "README.md"]
22
+
23
+ [tool.poetry.dependencies]
24
+ python = "^3.12"
25
+ postcrm-plugin-sdk = "^0.1.3"
26
+
27
+ [tool.poetry.group.dev.dependencies]
28
+ pytest = "^8.2.2"
29
+ ruff = "0.12.8"
30
+ black = "^26.3.1"
31
+
32
+ [tool.ruff]
33
+ line-length = 120
34
+ target-version = "py312"
35
+
36
+ [tool.black]
37
+ line-length = 120
38
+ target-version = ["py312"]
39
+
40
+ [tool.pytest.ini_options]
41
+ pythonpath = ["."]
42
+
43
+ [build-system]
44
+ requires = ["poetry-core"]
45
+ build-backend = "poetry.core.masonry.api"