@coopenomics/app-kit 0.0.0-stage → 2026.12.1

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,25 @@
1
+ import 'reflect-metadata';
2
+ import { NestFactory } from '@nestjs/core';
3
+ import { loadExtensionConfig, runAppMigrations } from '@coopenomics/extension-sdk';
4
+ import { AppModule } from './app.module';
5
+
6
+ async function bootstrap() {
7
+ const cfg = loadExtensionConfig();
8
+ // Своя база приложения: адрес задаёт оркестратор, если package.json
9
+ // запрашивает её (coopenomics.backend.database). Схему создают файлы
10
+ // migrations/*.sql — до подъёма приложения, иначе запросы упадут на
11
+ // отсутствующих таблицах.
12
+ if (cfg.databaseUrl) await runAppMigrations({ databaseUrl: cfg.databaseUrl });
13
+ const app = await NestFactory.create(AppModule);
14
+ await app.listen(cfg.subgraphPort);
15
+ // eslint-disable-next-line no-console
16
+ console.log(
17
+ `[exampleapp] subgraph up at :${cfg.subgraphPort} (coopname=${cfg.coopname})`,
18
+ );
19
+ }
20
+
21
+ bootstrap().catch((err) => {
22
+ // eslint-disable-next-line no-console
23
+ console.error('[exampleapp] bootstrap failed:', err);
24
+ process.exit(1);
25
+ });
@@ -0,0 +1,27 @@
1
+ import { Directive, Field, ID, ObjectType } from '@nestjs/graphql';
2
+
3
+ /**
4
+ * Локальная сущность расширения — заметка пайщика.
5
+ *
6
+ * `@key(fields: "id")` отмечает Note как entity в Federation v2 —
7
+ * на неё можно ссылаться из других subgraph'ов по id.
8
+ *
9
+ * `authorUsername` — внешний ключ на core-entity `Cooperator` (EOSIO
10
+ * account name). В рабочем пакете на этом месте стоит отношение `@requires`
11
+ * либо ResolveReference на SharedCooperator.
12
+ */
13
+ @ObjectType('Note')
14
+ @Directive('@key(fields: "id")')
15
+ export class Note {
16
+ @Field(() => ID)
17
+ id!: string;
18
+
19
+ @Field(() => String, { description: 'EOSIO username пайщика-автора' })
20
+ authorUsername!: string;
21
+
22
+ @Field(() => String)
23
+ body!: string;
24
+
25
+ @Field(() => String, { description: 'ISO-8601 момент создания' })
26
+ createdAt!: string;
27
+ }
@@ -0,0 +1,11 @@
1
+ import { Module } from '@nestjs/common';
2
+ import { NotesService } from './notes.service';
3
+ import { NotesResolver } from './notes.resolver';
4
+
5
+ @Module({
6
+ // Поле на пайщике ядра (Cooperator.exampleAppNotesCount) снято 25.11.2026:
7
+ // ядро не объявляет своих сущностей с @key, шлюз такую схему не соберёт.
8
+ // Вернуть, когда ядро отдаст Account как расширяемую сущность.
9
+ providers: [NotesService, NotesResolver],
10
+ })
11
+ export class NotesModule {}
@@ -0,0 +1,57 @@
1
+ import { UseGuards } from '@nestjs/common';
2
+ import {
3
+ Args,
4
+ Int,
5
+ Mutation,
6
+ Query,
7
+ ResolveReference,
8
+ Resolver,
9
+ } from '@nestjs/graphql';
10
+ import {
11
+ ExtensionAccessGuard,
12
+ type ExtensionIdentity,
13
+ } from '@coopenomics/extension-sdk';
14
+ import { CurrentIdentity } from '../core/current-identity.decorator';
15
+ import { Note } from './note.entity';
16
+ import { NotesService } from './notes.service';
17
+
18
+ /**
19
+ * Локальные Query / Mutation расширения.
20
+ *
21
+ * - `exampleAppNotes` — публичная выдача последних заметок;
22
+ * в реальном пакете её можно тоже закрыть guard'ом — здесь оставлено
23
+ * открытой, чтобы показать оба варианта (open и protected).
24
+ * - `exampleAppAddNote` — защищена `ExtensionJwtAuthGuard`. Username
25
+ * автора берётся из JWT в реальном пакете; в этом примере он передаётся
26
+ * аргументом — чтобы пример был запускаемым без сценария на gateway.
27
+ *
28
+ * - `__resolveReference` — обязателен для @key entity: gateway вызывает
29
+ * его, когда другой subgraph упоминает Note по id.
30
+ */
31
+ @Resolver(() => Note)
32
+ export class NotesResolver {
33
+ constructor(private readonly notes: NotesService) {}
34
+
35
+ @Query(() => [Note], { name: 'exampleAppNotes' })
36
+ list(
37
+ @Args('limit', { type: () => Int, nullable: true }) limit?: number,
38
+ ): Note[] {
39
+ return this.notes.list(limit);
40
+ }
41
+
42
+ @Mutation(() => Note, { name: 'exampleAppAddNote' })
43
+ @UseGuards(ExtensionAccessGuard)
44
+ add(
45
+ // Автор — пайщик, которого опознало ядро, а не аргумент запроса: иначе
46
+ // заметку можно записать от чужого имени.
47
+ @CurrentIdentity() identity: ExtensionIdentity,
48
+ @Args('body') body: string,
49
+ ): Note {
50
+ return this.notes.add(identity.username, body);
51
+ }
52
+
53
+ @ResolveReference()
54
+ resolveReference(ref: { __typename: string; id: string }): Note | undefined {
55
+ return this.notes.findById(ref.id);
56
+ }
57
+ }
@@ -0,0 +1,49 @@
1
+ import { Injectable } from '@nestjs/common';
2
+ import { Note } from './note.entity';
3
+
4
+ /**
5
+ * In-memory storage заметок. В рабочем приложении на этом месте стоит TypeORM /
6
+ * Postgres / любой источник; на уровне SDK ничего про БД не навязывается.
7
+ *
8
+ * State per-process — на старте subgraph'а пустая Map. Перезапуск контейнера
9
+ * orchestrator'ом обнулит её. Это умышленно: пример без зависимостей на БД,
10
+ * чтобы запускаться одной командой `node dist/main.js`.
11
+ */
12
+ @Injectable()
13
+ export class NotesService {
14
+ private readonly notes = new Map<string, Note>();
15
+ private seq = 0;
16
+
17
+ add(authorUsername: string, body: string): Note {
18
+ const id = String(++this.seq);
19
+ const note: Note = {
20
+ id,
21
+ authorUsername,
22
+ body,
23
+ createdAt: new Date().toISOString(),
24
+ };
25
+ this.notes.set(id, note);
26
+ return note;
27
+ }
28
+
29
+ list(limit?: number): Note[] {
30
+ const all = Array.from(this.notes.values()).sort((a, b) =>
31
+ b.createdAt.localeCompare(a.createdAt),
32
+ );
33
+ return typeof limit === 'number' && limit > 0 ? all.slice(0, limit) : all;
34
+ }
35
+
36
+ listByAuthor(authorUsername: string): Note[] {
37
+ return Array.from(this.notes.values()).filter(
38
+ (n) => n.authorUsername === authorUsername,
39
+ );
40
+ }
41
+
42
+ countByAuthor(authorUsername: string): number {
43
+ return this.listByAuthor(authorUsername).length;
44
+ }
45
+
46
+ findById(id: string): Note | undefined {
47
+ return this.notes.get(id);
48
+ }
49
+ }
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "commonjs",
5
+ "moduleResolution": "node",
6
+ "lib": ["ES2022"],
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "experimentalDecorators": true,
11
+ "emitDecoratorMetadata": true,
12
+ "declaration": false,
13
+ "outDir": "dist",
14
+ "rootDir": "src"
15
+ },
16
+ "include": ["src/**/*"]
17
+ }
@@ -0,0 +1,3 @@
1
+ Пакеты SDK приложений, собранные из чекаута mono. Набор кладёт их в эту папку,
2
+ когда команда `create` запущена из чекаута mono: в npm такая версия SDK ещё не
3
+ вышла. Каркас из npm-пакета набора берёт SDK из npm, архивов в папке нет.
@@ -0,0 +1,258 @@
1
+ <!doctype html>
2
+ <!--
3
+ Фронт @voskhod/exampleapp для изолированной рамки стола (487-18).
4
+
5
+ Страница работает в рамке с отдельным происхождением: у неё нет доступа к
6
+ окну стола, хранилищу ключей, IndexedDB и токену пайщика. Со столом она
7
+ общается командами моста:
8
+ init — кто пайщик, кооператив и тема оформления;
9
+ graphql — запрос к бэкенду приложения (токен приложения подставляет стол);
10
+ sign — подпись документа по хэшу (окно подписи рисует стол).
11
+ Зависимостей и сборки нет: образец показывает сам приём.
12
+ -->
13
+ <html lang="ru">
14
+ <head>
15
+ <meta charset="utf-8">
16
+ <meta name="viewport" content="width=device-width, initial-scale=1">
17
+ <title>Example App</title>
18
+ <style>
19
+ :root {
20
+ --p-canvas: #f6f7f8; --p-surface: #ffffff; --p-surface-2: #f1f3f4;
21
+ --p-ink: #14181c; --p-ink-2: #4a5560; --p-ink-3: #7b8794;
22
+ --p-line: #dfe3e7; --p-primary: #0f766e; --p-primary-soft: #d9f0ed;
23
+ --p-pos: #15803d; --p-neg: #b91c1c; --p-warn: #b45309;
24
+ }
25
+ * { box-sizing: border-box; }
26
+ body { margin: 0; padding: 24px; font: 14px/1.5 Inter, system-ui, sans-serif; color: var(--p-ink); background: var(--p-canvas); }
27
+ h1 { margin: 0 0 4px; font-size: 20px; }
28
+ .lead { margin: 0 0 20px; color: var(--p-ink-2); }
29
+ .grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); }
30
+ .card { background: var(--p-surface); border: 1px solid var(--p-line); border-radius: 12px; padding: 20px; }
31
+ .card h2 { margin: 0 0 12px; font-size: 15px; }
32
+ .row { display: flex; justify-content: space-between; gap: 12px; padding: 6px 0; border-bottom: 1px solid var(--p-line); }
33
+ .row:last-child { border-bottom: 0; }
34
+ .row span:first-child { color: var(--p-ink-2); }
35
+ .mono { font-family: "JetBrains Mono", ui-monospace, monospace; font-size: 12px; word-break: break-all; }
36
+ .muted { color: var(--p-ink-3); }
37
+ button { font: inherit; padding: 8px 14px; border-radius: 8px; border: 1px solid var(--p-primary); background: var(--p-primary); color: #fff; cursor: pointer; }
38
+ button.secondary { background: transparent; color: var(--p-primary); }
39
+ button:disabled { opacity: .5; cursor: default; }
40
+ input { font: inherit; width: 100%; padding: 8px 10px; border: 1px solid var(--p-line); border-radius: 8px; background: var(--p-surface); color: var(--p-ink); }
41
+ .line { display: flex; gap: 8px; margin-top: 12px; }
42
+ .badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 12px; }
43
+ .badge.pos { background: var(--p-primary-soft); color: var(--p-pos); }
44
+ .badge.neg { background: #fde8e8; color: var(--p-neg); }
45
+ .error { margin-top: 10px; color: var(--p-neg); }
46
+ ul { margin: 0; padding: 0; list-style: none; }
47
+ @media (max-width: 600px) { body { padding: 12px; } .line { flex-direction: column; } }
48
+ </style>
49
+ </head>
50
+ <body>
51
+ <h1>Example App</h1>
52
+ <p class="lead">Образец приложения каталога в изолированной рамке стола.</p>
53
+
54
+ <div class="grid">
55
+ <section class="card">
56
+ <h2>Пайщик и кооператив</h2>
57
+ <div class="row"><span>Пайщик</span><span class="mono" id="who">…</span></div>
58
+ <div class="row"><span>Кооператив</span><span id="coop">…</span></div>
59
+ <div class="row"><span>Название от ядра</span><span id="coop-name">…</span></div>
60
+ <p class="muted">Название читает бэкенд приложения портом ядра.</p>
61
+ </section>
62
+
63
+ <section class="card">
64
+ <h2>Заметки</h2>
65
+ <ul id="notes"><li class="muted">Загрузка…</li></ul>
66
+ <div class="line">
67
+ <input id="note-body" maxlength="200" placeholder="Текст заметки">
68
+ <button id="note-add">Добавить</button>
69
+ </div>
70
+ <div class="error" id="note-error"></div>
71
+ </section>
72
+
73
+ <section class="card">
74
+ <h2>Документ на подпись</h2>
75
+ <p class="muted">Документ формирует ядро. Окно подписи показывает стол, ключ приложению не передаётся.</p>
76
+ <button id="sign">Сформировать и подписать</button>
77
+ <div id="sign-result"></div>
78
+ <div class="error" id="sign-error"></div>
79
+ </section>
80
+
81
+ <section class="card">
82
+ <h2>Проверка изоляции</h2>
83
+ <p class="muted">Страница пробует достать данные стола. Каждая попытка обязана получить отказ браузера.</p>
84
+ <ul id="probes"></ul>
85
+ </section>
86
+ </div>
87
+
88
+ <script>
89
+ 'use strict';
90
+
91
+ // ── Мост к столу ──────────────────────────────────────────────────────────
92
+ var pending = {};
93
+ var nextId = 1;
94
+
95
+ function call(method, params) {
96
+ return new Promise(function (resolve, reject) {
97
+ var id = nextId++;
98
+ pending[id] = { resolve: resolve, reject: reject };
99
+ window.parent.postMessage({ coopBridge: 1, id: id, method: method, params: params || {} }, '*');
100
+ });
101
+ }
102
+
103
+ window.addEventListener('message', function (event) {
104
+ if (event.source !== window.parent) return;
105
+ var data = event.data;
106
+ if (!data || data.coopBridge !== 1 || !pending[data.id]) return;
107
+ var waiter = pending[data.id];
108
+ delete pending[data.id];
109
+ if (data.error) waiter.reject(new Error(data.error.message));
110
+ else waiter.resolve(data.result);
111
+ });
112
+
113
+ function gql(query, variables) {
114
+ return call('graphql', { query: query, variables: variables || {} }).then(function (res) {
115
+ if (res && res.errors && res.errors.length) throw new Error(res.errors[0].message);
116
+ return res.data;
117
+ });
118
+ }
119
+
120
+ function el(id) { return document.getElementById(id); }
121
+ function text(node, value) { node.textContent = value; }
122
+
123
+ // ── Пайщик и кооператив ───────────────────────────────────────────────────
124
+ function applyTheme(theme) {
125
+ if (!theme || !theme.tokens) return;
126
+ Object.keys(theme.tokens).forEach(function (name) {
127
+ if (theme.tokens[name]) document.documentElement.style.setProperty(name, theme.tokens[name]);
128
+ });
129
+ }
130
+
131
+ call('init').then(function (ctx) {
132
+ applyTheme(ctx.theme);
133
+ text(el('who'), ctx.username);
134
+ text(el('coop'), ctx.coopname);
135
+ return gql('{ exampleAppCooperative { coopname name shortAbbr } }');
136
+ }).then(function (data) {
137
+ var c = data.exampleAppCooperative;
138
+ text(el('coop-name'), c ? c.shortAbbr + ' «' + c.name + '»' : '—');
139
+ }).catch(function (e) { text(el('coop-name'), e.message); });
140
+
141
+ // ── Заметки ───────────────────────────────────────────────────────────────
142
+ function renderNotes(notes) {
143
+ var list = el('notes');
144
+ list.innerHTML = '';
145
+ if (!notes.length) {
146
+ var empty = document.createElement('li');
147
+ empty.className = 'muted';
148
+ text(empty, 'Заметок пока нет');
149
+ list.appendChild(empty);
150
+ return;
151
+ }
152
+ notes.forEach(function (n) {
153
+ var li = document.createElement('li');
154
+ li.className = 'row';
155
+ var body = document.createElement('span');
156
+ var author = document.createElement('span');
157
+ author.className = 'mono';
158
+ text(body, n.body);
159
+ text(author, n.authorUsername);
160
+ li.appendChild(body);
161
+ li.appendChild(author);
162
+ list.appendChild(li);
163
+ });
164
+ }
165
+
166
+ function loadNotes() {
167
+ return gql('{ exampleAppNotes(limit: 10) { id authorUsername body } }').then(function (d) { renderNotes(d.exampleAppNotes); });
168
+ }
169
+ loadNotes().catch(function (e) { text(el('note-error'), e.message); });
170
+
171
+ el('note-add').addEventListener('click', function () {
172
+ var body = el('note-body').value.trim();
173
+ text(el('note-error'), '');
174
+ if (!body) return;
175
+ el('note-add').disabled = true;
176
+ gql('mutation($b: String!) { exampleAppAddNote(body: $b) { id } }', { b: body })
177
+ .then(function () { el('note-body').value = ''; return loadNotes(); })
178
+ .catch(function (e) { text(el('note-error'), e.message); })
179
+ .then(function () { el('note-add').disabled = false; });
180
+ });
181
+
182
+ // ── Документ на подпись ───────────────────────────────────────────────────
183
+ el('sign').addEventListener('click', function () {
184
+ text(el('sign-error'), '');
185
+ el('sign-result').innerHTML = '';
186
+ el('sign').disabled = true;
187
+ gql('mutation { exampleAppDraftDocument { fullTitle hash } }')
188
+ .then(function (d) { return call('sign', { hash: d.exampleAppDraftDocument.hash }); })
189
+ .then(function (signed) {
190
+ var first = signed && signed.signatures && signed.signatures[0];
191
+ var box = el('sign-result');
192
+ [['Документ', signed.hash], ['Подписал', first ? first.signer : '—'], ['Ключ', first ? first.public_key : '—']].forEach(function (pair) {
193
+ var row = document.createElement('div');
194
+ row.className = 'row';
195
+ var k = document.createElement('span');
196
+ var v = document.createElement('span');
197
+ v.className = 'mono';
198
+ text(k, pair[0]);
199
+ text(v, String(pair[1]));
200
+ row.appendChild(k);
201
+ row.appendChild(v);
202
+ box.appendChild(row);
203
+ });
204
+ })
205
+ .catch(function (e) { text(el('sign-error'), e.message); })
206
+ .then(function () { el('sign').disabled = false; });
207
+ });
208
+
209
+ // ── Проверка изоляции ─────────────────────────────────────────────────────
210
+ // Каждая проба — попытка достать то, что принадлежит столу. Исход «закрыто»
211
+ // значит, что браузер отказал; «ОТКРЫТО» — граница не держит.
212
+ function probe(title, attempt) {
213
+ var li = document.createElement('li');
214
+ li.className = 'row';
215
+ var name = document.createElement('span');
216
+ var verdict = document.createElement('span');
217
+ text(name, title);
218
+ function show(open, detail) {
219
+ verdict.className = 'badge ' + (open ? 'neg' : 'pos');
220
+ text(verdict, open ? 'ОТКРЫТО' : 'закрыто');
221
+ verdict.title = detail || '';
222
+ }
223
+ li.appendChild(name);
224
+ li.appendChild(verdict);
225
+ el('probes').appendChild(li);
226
+ try {
227
+ var result = attempt();
228
+ if (result && typeof result.then === 'function') {
229
+ result.then(function (v) { show(true, String(v)); }, function (e) { show(false, e && e.message); });
230
+ } else {
231
+ show(true, String(result));
232
+ }
233
+ } catch (e) {
234
+ show(false, e && e.message);
235
+ }
236
+ }
237
+
238
+ probe('Страница стола (document окна стола)', function () { return window.parent.document.title; });
239
+ probe('Хранилище стола (localStorage окна стола)', function () { return window.parent.localStorage.length; });
240
+ probe('Своё локальное хранилище', function () { return window.localStorage.length; });
241
+ probe('Куки узла', function () { return document.cookie; });
242
+ probe('IndexedDB узла (копия ключа пайщика)', function () {
243
+ return new Promise(function (resolve, reject) {
244
+ var req = window.indexedDB.open('probe');
245
+ req.onsuccess = function () { resolve('открыта'); };
246
+ req.onerror = function () { reject(new Error('отказ')); };
247
+ });
248
+ });
249
+ probe('Прямой запрос к ядру мимо моста', function () {
250
+ return fetch('/backend/v1/graphql', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"query":"{ __typename }"}' })
251
+ .then(function (r) { return r.status; });
252
+ });
253
+ probe('Команда вне перечня моста', function () {
254
+ return call('getMemberToken').then(function (v) { return JSON.stringify(v); });
255
+ });
256
+ </script>
257
+ </body>
258
+ </html>
@@ -0,0 +1,59 @@
1
+ {
2
+ "name": "@voskhod/exampleapp",
3
+ "version": "0.1.0",
4
+ "description": "Эталонное приложение каталога: бэкенд и фронт в рамке стола.",
5
+ "main": "install.js",
6
+ "files": [
7
+ "install.js",
8
+ "assets/",
9
+ "README.md",
10
+ "CATALOG.md",
11
+ "INSTALL.md"
12
+ ],
13
+ "coopenomics": {
14
+ "title": "Эталонное приложение",
15
+ "backend": {
16
+ "image": "voskhod/exampleapp:0.1.0",
17
+ "subgraphPort": 3011,
18
+ "healthcheck": "/_health",
19
+ "env": [
20
+ "COOPNAME"
21
+ ]
22
+ },
23
+ "frontend": {
24
+ "frame": "frontend/frame.html",
25
+ "workspace": {
26
+ "name": "exampleapp",
27
+ "title": "Example",
28
+ "icon": "extension"
29
+ }
30
+ },
31
+ "ports": [
32
+ "accessToken",
33
+ "cooperativeVars",
34
+ "document",
35
+ "chain"
36
+ ],
37
+ "chainActions": [
38
+ "eosio::refund"
39
+ ]
40
+ },
41
+ "catalog": {
42
+ "kind": "remote",
43
+ "workspaces": [
44
+ "exampleapp"
45
+ ],
46
+ "pricing": {
47
+ "rubPerMonth": 0,
48
+ "trialMinutes": 60
49
+ },
50
+ "publisher": {
51
+ "coopname": "voskhod",
52
+ "signer": "chairman"
53
+ }
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ },
58
+ "license": "MIT"
59
+ }