@rimori/react-client 0.1.0

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 (139) hide show
  1. package/.prettierignore +35 -0
  2. package/LICENSE +201 -0
  3. package/README copy.md +1216 -0
  4. package/README.md +1 -0
  5. package/dist/components/MarkdownEditor.d.ts +8 -0
  6. package/dist/components/MarkdownEditor.js +48 -0
  7. package/dist/components/Spinner.d.ts +8 -0
  8. package/dist/components/Spinner.js +4 -0
  9. package/dist/components/ai/Assistant.d.ts +9 -0
  10. package/dist/components/ai/Assistant.js +58 -0
  11. package/dist/components/ai/Avatar.d.ts +14 -0
  12. package/dist/components/ai/Avatar.js +59 -0
  13. package/dist/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  14. package/dist/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  15. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  16. package/dist/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  17. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  18. package/dist/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  19. package/dist/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  20. package/dist/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  21. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  22. package/dist/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  23. package/dist/components/ai/utils.d.ts +6 -0
  24. package/dist/components/ai/utils.js +13 -0
  25. package/dist/components/audio/Playbutton.d.ts +15 -0
  26. package/dist/components/audio/Playbutton.js +80 -0
  27. package/dist/components/components/ContextMenu.d.ts +10 -0
  28. package/dist/components/components/ContextMenu.js +135 -0
  29. package/dist/hooks/I18nHooks.d.ts +11 -0
  30. package/dist/hooks/I18nHooks.js +25 -0
  31. package/dist/hooks/UseChatHook.d.ts +10 -0
  32. package/dist/hooks/UseChatHook.js +29 -0
  33. package/dist/providers/PluginProvider.d.ts +11 -0
  34. package/dist/providers/PluginProvider.js +142 -0
  35. package/dist/react-client/plugin/ThemeSetter.d.ts +2 -0
  36. package/dist/react-client/plugin/ThemeSetter.js +19 -0
  37. package/dist/react-client/src/components/ContextMenu.d.ts +10 -0
  38. package/dist/react-client/src/components/ContextMenu.js +135 -0
  39. package/dist/react-client/src/components/MarkdownEditor.d.ts +8 -0
  40. package/dist/react-client/src/components/MarkdownEditor.js +48 -0
  41. package/dist/react-client/src/components/Spinner.d.ts +8 -0
  42. package/dist/react-client/src/components/Spinner.js +4 -0
  43. package/dist/react-client/src/components/ai/Assistant.d.ts +9 -0
  44. package/dist/react-client/src/components/ai/Assistant.js +58 -0
  45. package/dist/react-client/src/components/ai/Avatar.d.ts +14 -0
  46. package/dist/react-client/src/components/ai/Avatar.js +59 -0
  47. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.d.ts +7 -0
  48. package/dist/react-client/src/components/ai/EmbeddedAssistent/AudioInputField.js +37 -0
  49. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.d.ts +8 -0
  50. package/dist/react-client/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.js +79 -0
  51. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.d.ts +19 -0
  52. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/MessageSender.js +91 -0
  53. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.d.ts +27 -0
  54. package/dist/react-client/src/components/ai/EmbeddedAssistent/TTS/Player.js +185 -0
  55. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.d.ts +11 -0
  56. package/dist/react-client/src/components/ai/EmbeddedAssistent/VoiceRecoder.js +95 -0
  57. package/dist/react-client/src/components/ai/utils.d.ts +6 -0
  58. package/dist/react-client/src/components/ai/utils.js +13 -0
  59. package/dist/react-client/src/components/audio/Playbutton.d.ts +15 -0
  60. package/dist/react-client/src/components/audio/Playbutton.js +82 -0
  61. package/dist/react-client/src/components/components/ContextMenu.d.ts +10 -0
  62. package/dist/react-client/src/components/components/ContextMenu.js +135 -0
  63. package/dist/react-client/src/hooks/I18nHooks.d.ts +11 -0
  64. package/dist/react-client/src/hooks/I18nHooks.js +25 -0
  65. package/dist/react-client/src/hooks/UseChatHook.d.ts +10 -0
  66. package/dist/react-client/src/hooks/UseChatHook.js +29 -0
  67. package/dist/react-client/src/plugin/ThemeSetter.d.ts +2 -0
  68. package/dist/react-client/src/plugin/ThemeSetter.js +19 -0
  69. package/dist/react-client/src/providers/PluginProvider.d.ts +12 -0
  70. package/dist/react-client/src/providers/PluginProvider.js +142 -0
  71. package/dist/react-client/src/utils/FullscreenUtils.d.ts +2 -0
  72. package/dist/react-client/src/utils/FullscreenUtils.js +23 -0
  73. package/dist/react-client/src/utils/PluginUtils.d.ts +2 -0
  74. package/dist/react-client/src/utils/PluginUtils.js +23 -0
  75. package/dist/rimori-client/src/cli/types/DatabaseTypes.d.ts +103 -0
  76. package/dist/rimori-client/src/cli/types/DatabaseTypes.js +2 -0
  77. package/dist/rimori-client/src/controller/AIController.d.ts +15 -0
  78. package/dist/rimori-client/src/controller/AIController.js +255 -0
  79. package/dist/rimori-client/src/controller/AccomplishmentController.d.ts +38 -0
  80. package/dist/rimori-client/src/controller/AccomplishmentController.js +112 -0
  81. package/dist/rimori-client/src/controller/AudioController.d.ts +37 -0
  82. package/dist/rimori-client/src/controller/AudioController.js +68 -0
  83. package/dist/rimori-client/src/controller/ExerciseController.d.ts +54 -0
  84. package/dist/rimori-client/src/controller/ExerciseController.js +74 -0
  85. package/dist/rimori-client/src/controller/ObjectController.d.ts +42 -0
  86. package/dist/rimori-client/src/controller/ObjectController.js +76 -0
  87. package/dist/rimori-client/src/controller/SettingsController.d.ts +79 -0
  88. package/dist/rimori-client/src/controller/SettingsController.js +118 -0
  89. package/dist/rimori-client/src/controller/SharedContentController.d.ts +106 -0
  90. package/dist/rimori-client/src/controller/SharedContentController.js +285 -0
  91. package/dist/rimori-client/src/controller/TranslationController.d.ts +38 -0
  92. package/dist/rimori-client/src/controller/TranslationController.js +106 -0
  93. package/dist/rimori-client/src/controller/VoiceController.d.ts +9 -0
  94. package/dist/rimori-client/src/controller/VoiceController.js +37 -0
  95. package/dist/rimori-client/src/fromRimori/EventBus.d.ts +101 -0
  96. package/dist/rimori-client/src/fromRimori/EventBus.js +263 -0
  97. package/dist/rimori-client/src/fromRimori/PluginTypes.d.ts +174 -0
  98. package/dist/rimori-client/src/fromRimori/PluginTypes.js +1 -0
  99. package/dist/rimori-client/src/index.d.ts +11 -0
  100. package/dist/rimori-client/src/index.js +10 -0
  101. package/dist/rimori-client/src/plugin/CommunicationHandler.d.ts +48 -0
  102. package/dist/rimori-client/src/plugin/CommunicationHandler.js +234 -0
  103. package/dist/rimori-client/src/plugin/Logger.d.ts +73 -0
  104. package/dist/rimori-client/src/plugin/Logger.js +308 -0
  105. package/dist/rimori-client/src/plugin/RimoriClient.d.ts +258 -0
  106. package/dist/rimori-client/src/plugin/RimoriClient.js +375 -0
  107. package/dist/rimori-client/src/plugin/StandaloneClient.d.ts +17 -0
  108. package/dist/rimori-client/src/plugin/StandaloneClient.js +115 -0
  109. package/dist/rimori-client/src/utils/difficultyConverter.d.ts +4 -0
  110. package/dist/rimori-client/src/utils/difficultyConverter.js +10 -0
  111. package/dist/rimori-client/src/utils/endpoint.d.ts +2 -0
  112. package/dist/rimori-client/src/utils/endpoint.js +2 -0
  113. package/dist/style.css +110 -0
  114. package/dist/style.css.map +1 -0
  115. package/dist/utils/PluginUtils.d.ts +2 -0
  116. package/dist/utils/PluginUtils.js +23 -0
  117. package/eslint.config.js +53 -0
  118. package/index.ts +6 -0
  119. package/package.json +47 -0
  120. package/prettier.config.js +8 -0
  121. package/src/components/ContextMenu.tsx +177 -0
  122. package/src/components/MarkdownEditor.tsx +144 -0
  123. package/src/components/Spinner.tsx +29 -0
  124. package/src/components/ai/Assistant.tsx +96 -0
  125. package/src/components/ai/Avatar.tsx +99 -0
  126. package/src/components/ai/EmbeddedAssistent/AudioInputField.tsx +73 -0
  127. package/src/components/ai/EmbeddedAssistent/CircleAudioAvatar.tsx +107 -0
  128. package/src/components/ai/EmbeddedAssistent/TTS/MessageSender.ts +96 -0
  129. package/src/components/ai/EmbeddedAssistent/TTS/Player.ts +197 -0
  130. package/src/components/ai/EmbeddedAssistent/VoiceRecoder.tsx +129 -0
  131. package/src/components/ai/utils.ts +21 -0
  132. package/src/components/audio/Playbutton.tsx +126 -0
  133. package/src/hooks/I18nHooks.ts +33 -0
  134. package/src/hooks/UseChatHook.ts +38 -0
  135. package/src/plugin/ThemeSetter.ts +23 -0
  136. package/src/providers/PluginProvider.tsx +197 -0
  137. package/src/style.scss +136 -0
  138. package/src/utils/FullscreenUtils.ts +22 -0
  139. package/tsconfig.json +23 -0
@@ -0,0 +1,255 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __rest = (this && this.__rest) || function (s, e) {
11
+ var t = {};
12
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
13
+ t[p] = s[p];
14
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
15
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
16
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
17
+ t[p[i]] = s[p[i]];
18
+ }
19
+ return t;
20
+ };
21
+ export function generateText(backendUrl, messages, tools, token) {
22
+ return __awaiter(this, void 0, void 0, function* () {
23
+ const response = yield fetch(`${backendUrl}/ai/llm`, {
24
+ method: 'POST',
25
+ body: JSON.stringify({ messages, tools }),
26
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
27
+ });
28
+ return yield response.json();
29
+ });
30
+ }
31
+ export function streamChatGPT(backendUrl, messages, tools, onResponse, token) {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ const messageId = Math.random().toString(36).substring(3);
34
+ const currentMessages = [...messages];
35
+ console.log('Starting streamChatGPT with:', {
36
+ messageId,
37
+ messageCount: messages.length,
38
+ toolCount: tools.length,
39
+ backendUrl,
40
+ });
41
+ while (true) {
42
+ const messagesForApi = currentMessages.map((_a) => {
43
+ var { id } = _a, rest = __rest(_a, ["id"]);
44
+ return rest;
45
+ });
46
+ try {
47
+ const response = yield fetch(`${backendUrl}/ai/llm`, {
48
+ method: 'POST',
49
+ body: JSON.stringify({ messages: messagesForApi, tools, stream: true }),
50
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
51
+ });
52
+ if (!response.ok) {
53
+ throw new Error(`HTTP error! status: ${response.status}`);
54
+ }
55
+ if (!response.body) {
56
+ console.error('No response body.');
57
+ return;
58
+ }
59
+ const reader = response.body.getReader();
60
+ const decoder = new TextDecoder('utf-8');
61
+ let content = '';
62
+ let done = false;
63
+ const toolInvocations = [];
64
+ let currentTextId = '';
65
+ let isToolCallMode = false;
66
+ let buffer = ''; // Buffer for incomplete chunks
67
+ while (!done) {
68
+ const { value, done: readerDone } = yield reader.read();
69
+ if (value) {
70
+ const chunk = decoder.decode(value, { stream: true });
71
+ buffer += chunk;
72
+ // Split by lines, but handle incomplete lines
73
+ const lines = buffer.split('\n');
74
+ // Keep the last line in buffer if it's incomplete
75
+ if (lines.length > 1) {
76
+ buffer = lines.pop() || '';
77
+ }
78
+ for (const line of lines) {
79
+ if (line.trim() === '')
80
+ continue;
81
+ // Handle the new streaming format
82
+ if (line.startsWith('data: ')) {
83
+ const dataStr = line.substring(6); // Remove 'data: ' prefix
84
+ // Handle [DONE] marker
85
+ if (dataStr === '[DONE]') {
86
+ done = true;
87
+ break;
88
+ }
89
+ try {
90
+ const data = JSON.parse(dataStr);
91
+ // Log the first message to understand the format
92
+ if (!content && !isToolCallMode) {
93
+ // console.log('First stream message received:', data);
94
+ }
95
+ switch (data.type) {
96
+ case 'start':
97
+ // Stream started, no action needed
98
+ // console.log('Stream started');
99
+ break;
100
+ case 'start-step':
101
+ // Step started, no action needed
102
+ // console.log('Step started');
103
+ break;
104
+ case 'reasoning-start':
105
+ // Reasoning started, no action needed
106
+ console.log('Reasoning started:', data.id);
107
+ break;
108
+ case 'reasoning-end':
109
+ // Reasoning ended, no action needed
110
+ console.log('Reasoning ended:', data.id);
111
+ break;
112
+ case 'text-start':
113
+ // Text generation started, store the ID
114
+ currentTextId = data.id;
115
+ console.log('Text generation started:', data.id);
116
+ break;
117
+ case 'text-delta':
118
+ // Text delta received, append to content
119
+ if (data.delta) {
120
+ content += data.delta;
121
+ onResponse(messageId, content, false);
122
+ }
123
+ break;
124
+ case 'text-end':
125
+ // Text generation ended
126
+ console.log('Text generation ended:', data.id);
127
+ break;
128
+ case 'finish-step':
129
+ // Step finished, no action needed
130
+ // console.log('Step finished');
131
+ break;
132
+ case 'finish':
133
+ // Stream finished
134
+ // console.log('Stream finished');
135
+ done = true;
136
+ break;
137
+ // Additional message types that might be present in the AI library
138
+ case 'tool-call':
139
+ case 'tool-input-available': //for now input calls should be handled the same way as tool calls
140
+ // Tool call initiated
141
+ console.log('Tool call initiated:', data);
142
+ isToolCallMode = true;
143
+ if (data.toolCallId && data.toolName && (data.args || data.input)) {
144
+ toolInvocations.push({
145
+ toolCallId: data.toolCallId,
146
+ toolName: data.toolName,
147
+ args: data.args || data.input,
148
+ });
149
+ }
150
+ break;
151
+ case 'tool-input-delta': //for now input calls should be handled the same way as tool calls
152
+ case 'tool-call-delta':
153
+ // Tool call delta (for streaming tool calls)
154
+ console.log('Tool call delta:', data);
155
+ break;
156
+ case 'tool-call-end':
157
+ // Tool call completed
158
+ console.log('Tool call completed:', data);
159
+ break;
160
+ case 'tool-result':
161
+ // Tool execution result
162
+ console.log('Tool result:', data);
163
+ break;
164
+ case 'error':
165
+ // Error occurred
166
+ console.error('Stream error:', data);
167
+ break;
168
+ case 'usage':
169
+ // Usage information
170
+ console.log('Usage info:', data);
171
+ break;
172
+ case 'model':
173
+ // Model information
174
+ console.log('Model info:', data);
175
+ break;
176
+ case 'stop':
177
+ // Stop signal
178
+ console.log('Stop signal received');
179
+ done = true;
180
+ break;
181
+ default:
182
+ // Unknown type, log for debugging
183
+ console.log('Unknown stream type:', data.type, data);
184
+ break;
185
+ }
186
+ }
187
+ catch (error) {
188
+ console.error('Error parsing stream data:', error, dataStr);
189
+ }
190
+ }
191
+ }
192
+ }
193
+ if (readerDone) {
194
+ done = true;
195
+ }
196
+ }
197
+ // Check if we have content or if this was a tool call response
198
+ if (content || toolInvocations.length > 0) {
199
+ currentMessages.push({
200
+ id: messageId,
201
+ role: 'assistant',
202
+ content: content,
203
+ toolCalls: toolInvocations.length > 0 ? toolInvocations : undefined,
204
+ });
205
+ }
206
+ // Handle tool call scenario if tools were provided
207
+ if (tools.length > 0 && toolInvocations.length > 0) {
208
+ console.log('Tool calls detected, executing tools...');
209
+ const toolResults = [];
210
+ for (const toolInvocation of toolInvocations) {
211
+ const tool = tools.find((t) => t.name === toolInvocation.toolName);
212
+ if (tool && tool.execute) {
213
+ try {
214
+ const result = yield tool.execute(toolInvocation.args);
215
+ toolResults.push({
216
+ id: Math.random().toString(36).substring(3),
217
+ role: 'user',
218
+ content: `Tool '${toolInvocation.toolName}' returned: ${JSON.stringify(result)}`,
219
+ });
220
+ }
221
+ catch (error) {
222
+ console.error(`Error executing tool ${toolInvocation.toolName}:`, error);
223
+ toolResults.push({
224
+ id: Math.random().toString(36).substring(3),
225
+ role: 'user',
226
+ content: `Tool '${toolInvocation.toolName}' failed with error: ${error}`,
227
+ });
228
+ }
229
+ }
230
+ }
231
+ if (toolResults.length > 0) {
232
+ currentMessages.push(...toolResults);
233
+ // Continue the loop to handle the next response
234
+ continue;
235
+ }
236
+ }
237
+ // Since the new format doesn't seem to support tool calls in the same way,
238
+ // we'll assume the stream is complete when we reach the end
239
+ // If tools are provided and no content was generated, this might indicate a tool call
240
+ if (tools.length > 0 && !content && !isToolCallMode) {
241
+ // This might be a tool call scenario, but we need more information
242
+ // For now, we'll just finish the stream
243
+ console.log('No content generated, but tools provided - might be tool call scenario');
244
+ }
245
+ onResponse(messageId, content, true, toolInvocations);
246
+ return;
247
+ }
248
+ catch (error) {
249
+ console.error('Error in streamChatGPT:', error);
250
+ onResponse(messageId, `Error: ${error instanceof Error ? error.message : String(error)}`, true, []);
251
+ return;
252
+ }
253
+ }
254
+ });
255
+ }
@@ -0,0 +1,38 @@
1
+ import { EventBusMessage } from '../fromRimori/EventBus';
2
+ export type AccomplishmentMessage = EventBusMessage<MicroAccomplishmentPayload>;
3
+ export declare const skillCategories: readonly ["reading", "listening", "speaking", "writing", "learning", "community"];
4
+ interface BaseAccomplishmentPayload {
5
+ type: 'micro' | 'macro';
6
+ skillCategory: (typeof skillCategories)[number];
7
+ accomplishmentKeyword: string;
8
+ description: string;
9
+ meta?: {
10
+ key: string;
11
+ value: string | number | boolean;
12
+ description: string;
13
+ }[];
14
+ }
15
+ export interface MicroAccomplishmentPayload extends BaseAccomplishmentPayload {
16
+ type: 'micro';
17
+ }
18
+ export interface MacroAccomplishmentPayload extends BaseAccomplishmentPayload {
19
+ type: 'macro';
20
+ errorRatio: number;
21
+ durationMinutes: number;
22
+ }
23
+ export type AccomplishmentPayload = MicroAccomplishmentPayload | MacroAccomplishmentPayload;
24
+ export declare class AccomplishmentController {
25
+ private pluginId;
26
+ constructor(pluginId: string);
27
+ emitAccomplishment(payload: Omit<AccomplishmentPayload, 'type'>): void;
28
+ private validateAccomplishment;
29
+ private sanitizeAccomplishment;
30
+ private getDecoupledTopic;
31
+ /**
32
+ * Subscribe to accomplishment events
33
+ * @param accomplishmentTopic - The topic of the accomplishment event. The pattern can be any pattern of plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword
34
+ * @param callback - The callback function to be called when the accomplishment event is triggered
35
+ */
36
+ subscribe(accomplishmentTopics: string | string[] | undefined, callback: (payload: EventBusMessage<AccomplishmentPayload>) => void): void;
37
+ }
38
+ export {};
@@ -0,0 +1,112 @@
1
+ import { EventBus } from '../fromRimori/EventBus';
2
+ export const skillCategories = ['reading', 'listening', 'speaking', 'writing', 'learning', 'community'];
3
+ export class AccomplishmentController {
4
+ constructor(pluginId) {
5
+ this.pluginId = pluginId;
6
+ }
7
+ emitAccomplishment(payload) {
8
+ const accomplishmentPayload = Object.assign(Object.assign({}, payload), { type: 'durationMinutes' in payload ? 'macro' : 'micro' });
9
+ this.validateAccomplishment(accomplishmentPayload);
10
+ const sanitizedPayload = this.sanitizeAccomplishment(accomplishmentPayload);
11
+ const topic = 'global.accomplishment.trigger' + (accomplishmentPayload.type === 'macro' ? 'Macro' : 'Micro');
12
+ EventBus.emit(this.pluginId, topic, sanitizedPayload);
13
+ }
14
+ validateAccomplishment(payload) {
15
+ if (!skillCategories.includes(payload.skillCategory)) {
16
+ throw new Error(`Invalid skill category: ${payload.skillCategory}`);
17
+ }
18
+ //regex validate accomplishmentKeyword
19
+ if (!/^[a-z_-]+$/.test(payload.accomplishmentKeyword)) {
20
+ throw new Error(`The accomplishment keyword: ${payload.accomplishmentKeyword} is invalid. Only lowercase letters, minuses and underscores are allowed`);
21
+ }
22
+ //description is required
23
+ if (payload.description.length < 10) {
24
+ throw new Error('Description is too short');
25
+ }
26
+ //check that the type is valid
27
+ if (!['micro', 'macro'].includes(payload.type)) {
28
+ throw new Error('Invalid accomplishment type ' + payload.type);
29
+ }
30
+ //durationMinutes is required
31
+ if (payload.type === 'macro' && payload.durationMinutes < 4) {
32
+ throw new Error('The duration must be at least 4 minutes');
33
+ }
34
+ //errorRatio is required
35
+ if (payload.type === 'macro' && (payload.errorRatio < 0 || payload.errorRatio > 1)) {
36
+ throw new Error('The error ratio must be between 0 and 1');
37
+ }
38
+ //regex check meta data key
39
+ if (payload.meta) {
40
+ payload.meta.forEach((meta) => {
41
+ if (!/^[a-z_]+$/.test(meta.key)) {
42
+ throw new Error('Invalid meta data key ' + meta.key + ', only lowercase letters and underscores are allowed');
43
+ }
44
+ });
45
+ }
46
+ }
47
+ sanitizeAccomplishment(payload) {
48
+ var _a;
49
+ payload.description = payload.description.replace(/[^\x20-\x7E]/g, '');
50
+ (_a = payload.meta) === null || _a === void 0 ? void 0 : _a.forEach((meta) => {
51
+ meta.description = meta.description.replace(/[^\x20-\x7E]/g, '');
52
+ });
53
+ return payload;
54
+ }
55
+ getDecoupledTopic(topic) {
56
+ const [plugin, skillCategory, accomplishmentKeyword] = topic.split('.');
57
+ return {
58
+ plugin: plugin || '*',
59
+ skillCategory: skillCategory || '*',
60
+ accomplishmentKeyword: accomplishmentKeyword || '*',
61
+ };
62
+ }
63
+ /**
64
+ * Subscribe to accomplishment events
65
+ * @param accomplishmentTopic - The topic of the accomplishment event. The pattern can be any pattern of plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword
66
+ * @param callback - The callback function to be called when the accomplishment event is triggered
67
+ */
68
+ subscribe(accomplishmentTopics = '*', callback) {
69
+ if (typeof accomplishmentTopics === 'string') {
70
+ accomplishmentTopics = [accomplishmentTopics];
71
+ }
72
+ accomplishmentTopics.forEach((accomplishmentTopic) => {
73
+ const topicLength = accomplishmentTopic.split('.').length;
74
+ if (topicLength === 1) {
75
+ accomplishmentTopic += '.*.*';
76
+ }
77
+ else if (topicLength === 2) {
78
+ accomplishmentTopic += '.*';
79
+ }
80
+ else if (topicLength !== 3) {
81
+ throw new Error('Invalid accomplishment topic pattern. The pattern must be plugin.skillCategory.accomplishmentKeyword or an * as wildcard for any plugin, skill category or accomplishment keyword');
82
+ }
83
+ EventBus.on(['global.accomplishment.triggerMicro', 'global.accomplishment.triggerMacro'], (event) => {
84
+ const { plugin, skillCategory, accomplishmentKeyword } = this.getDecoupledTopic(accomplishmentTopic);
85
+ if (plugin !== '*' && event.sender !== plugin)
86
+ return;
87
+ if (skillCategory !== '*' && event.data.skillCategory !== skillCategory)
88
+ return;
89
+ if (accomplishmentKeyword !== '*' && event.data.accomplishmentKeyword !== accomplishmentKeyword)
90
+ return;
91
+ callback(event);
92
+ }, [this.pluginId]);
93
+ });
94
+ }
95
+ }
96
+ // const accomplishmentHandler = AccomplishmentHandler.getInstance("my-plugin");
97
+ // accomplishmentHandler.subscribe("*", (payload) => {
98
+ // console.log(payload);
99
+ // });
100
+ // accomplishmentHandler.emitAccomplishment({
101
+ // skillCategory: "reading",
102
+ // accomplishmentKeyword: "chapter",
103
+ // description: "Read chapter 1 of the book",
104
+ // durationMinutes: 10,
105
+ // meta: [
106
+ // {
107
+ // key: "book",
108
+ // value: "The Great Gatsby",
109
+ // description: "The book I read",
110
+ // },
111
+ // ],
112
+ // });
@@ -0,0 +1,37 @@
1
+ /**
2
+ * AudioController is a class that provides methods to record audio. It is a wrapper around the Capacitor Voice Recorder plugin. For more information, see https://github.com/tchvu3/capacitor-voice-recorder.
3
+ *
4
+ * @example
5
+ * const audioController = new AudioController();
6
+ * await audioController.startRecording();
7
+ */
8
+ export declare class AudioController {
9
+ private pluginId;
10
+ constructor(pluginId: string);
11
+ /**
12
+ * Start the recording.
13
+ *
14
+ * @example
15
+ * const audioController = new AudioController();
16
+ * await audioController.startRecording();
17
+ * @returns void
18
+ */
19
+ startRecording(): Promise<void>;
20
+ /**
21
+ * Stop the recording and return the audio data.
22
+ * @returns The audio data.
23
+ *
24
+ * @example
25
+ * const audioRef = new Audio(`data:${mimeType};base64,${base64Sound}`)
26
+ * audioRef.oncanplaythrough = () => audioRef.play()
27
+ * audioRef.load()
28
+ */
29
+ stopRecording(): Promise<{
30
+ recording: Blob;
31
+ msDuration: number;
32
+ mimeType: string;
33
+ }>;
34
+ pauseRecording(): Promise<boolean>;
35
+ resumeRecording(): Promise<boolean>;
36
+ getCurrentStatus(): Promise<'RECORDING' | 'PAUSED' | 'NONE'>;
37
+ }
@@ -0,0 +1,68 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { EventBus } from '../fromRimori/EventBus';
11
+ /**
12
+ * AudioController is a class that provides methods to record audio. It is a wrapper around the Capacitor Voice Recorder plugin. For more information, see https://github.com/tchvu3/capacitor-voice-recorder.
13
+ *
14
+ * @example
15
+ * const audioController = new AudioController();
16
+ * await audioController.startRecording();
17
+ */
18
+ export class AudioController {
19
+ constructor(pluginId) {
20
+ this.pluginId = pluginId;
21
+ }
22
+ /**
23
+ * Start the recording.
24
+ *
25
+ * @example
26
+ * const audioController = new AudioController();
27
+ * await audioController.startRecording();
28
+ * @returns void
29
+ */
30
+ startRecording() {
31
+ return __awaiter(this, void 0, void 0, function* () {
32
+ EventBus.emit(this.pluginId, 'global.microphone.triggerStartRecording');
33
+ });
34
+ }
35
+ /**
36
+ * Stop the recording and return the audio data.
37
+ * @returns The audio data.
38
+ *
39
+ * @example
40
+ * const audioRef = new Audio(`data:${mimeType};base64,${base64Sound}`)
41
+ * audioRef.oncanplaythrough = () => audioRef.play()
42
+ * audioRef.load()
43
+ */
44
+ stopRecording() {
45
+ return __awaiter(this, void 0, void 0, function* () {
46
+ const result = yield EventBus.request(this.pluginId, 'global.microphone.triggerStopRecording');
47
+ return result.data;
48
+ });
49
+ }
50
+ pauseRecording() {
51
+ return __awaiter(this, void 0, void 0, function* () {
52
+ const result = yield EventBus.request(this.pluginId, 'global.microphone.triggerPauseRecording');
53
+ return result.data;
54
+ });
55
+ }
56
+ resumeRecording() {
57
+ return __awaiter(this, void 0, void 0, function* () {
58
+ const result = yield EventBus.request(this.pluginId, 'global.microphone.triggerResumeRecording');
59
+ return result.data;
60
+ });
61
+ }
62
+ getCurrentStatus() {
63
+ return __awaiter(this, void 0, void 0, function* () {
64
+ const result = yield EventBus.request(this.pluginId, 'global.microphone.triggerGetCurrentStatus');
65
+ return result.data;
66
+ });
67
+ }
68
+ }
@@ -0,0 +1,54 @@
1
+ import { SupabaseClient } from '@supabase/supabase-js';
2
+ export type TriggerAction = {
3
+ action_key: string;
4
+ } & Record<string, string | number | boolean>;
5
+ export interface CreateExerciseParams {
6
+ plugin_id: string;
7
+ start_date: string;
8
+ end_date: string;
9
+ trigger_action: TriggerAction;
10
+ name: string;
11
+ description: string;
12
+ estimated_duration: number;
13
+ }
14
+ export interface Exercise {
15
+ id: string;
16
+ plugin_id: string;
17
+ start_date: string;
18
+ end_date: string;
19
+ trigger_action: TriggerAction;
20
+ name: string;
21
+ description: string;
22
+ estimated_duration: number;
23
+ created_at?: string;
24
+ updated_at?: string;
25
+ }
26
+ export declare class ExerciseController {
27
+ private supabase;
28
+ constructor(supabase: SupabaseClient);
29
+ /**
30
+ * Fetches weekly exercises from the weekly_exercises view.
31
+ * Shows exercises for the current week that haven't expired.
32
+ * @returns Array of exercise objects.
33
+ */
34
+ viewWeeklyExercises(): Promise<Exercise[]>;
35
+ /**
36
+ * Creates a new exercise via the backend API.
37
+ * @param token The token to use for authentication.
38
+ * @param backendUrl The URL of the backend API.
39
+ * @param params Exercise creation parameters.
40
+ * @returns Created exercise object.
41
+ */
42
+ addExercise(token: string, backendUrl: string, params: CreateExerciseParams): Promise<Exercise>;
43
+ /**
44
+ * Deletes an exercise via the backend API.
45
+ * @param token The token to use for authentication.
46
+ * @param backendUrl The URL of the backend API.
47
+ * @param exerciseId The exercise ID to delete.
48
+ * @returns Success status.
49
+ */
50
+ deleteExercise(token: string, backendUrl: string, id: string): Promise<{
51
+ success: boolean;
52
+ message: string;
53
+ }>;
54
+ }
@@ -0,0 +1,74 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ export class ExerciseController {
11
+ constructor(supabase) {
12
+ this.supabase = supabase;
13
+ }
14
+ /**
15
+ * Fetches weekly exercises from the weekly_exercises view.
16
+ * Shows exercises for the current week that haven't expired.
17
+ * @returns Array of exercise objects.
18
+ */
19
+ viewWeeklyExercises() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ const { data, error } = yield this.supabase.from('weekly_exercises').select('*');
22
+ if (error) {
23
+ throw new Error(`Failed to fetch weekly exercises: ${error.message}`);
24
+ }
25
+ return data || [];
26
+ });
27
+ }
28
+ /**
29
+ * Creates a new exercise via the backend API.
30
+ * @param token The token to use for authentication.
31
+ * @param backendUrl The URL of the backend API.
32
+ * @param params Exercise creation parameters.
33
+ * @returns Created exercise object.
34
+ */
35
+ addExercise(token, backendUrl, params) {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ const response = yield fetch(`${backendUrl}/exercises`, {
38
+ method: 'POST',
39
+ headers: {
40
+ 'Content-Type': 'application/json',
41
+ Authorization: `Bearer ${token}`,
42
+ },
43
+ body: JSON.stringify(params),
44
+ });
45
+ if (!response.ok) {
46
+ const errorText = yield response.text();
47
+ throw new Error(`Failed to create exercise: ${errorText}`);
48
+ }
49
+ return yield response.json();
50
+ });
51
+ }
52
+ /**
53
+ * Deletes an exercise via the backend API.
54
+ * @param token The token to use for authentication.
55
+ * @param backendUrl The URL of the backend API.
56
+ * @param exerciseId The exercise ID to delete.
57
+ * @returns Success status.
58
+ */
59
+ deleteExercise(token, backendUrl, id) {
60
+ return __awaiter(this, void 0, void 0, function* () {
61
+ const response = yield fetch(`${backendUrl}/exercises/${id}`, {
62
+ method: 'DELETE',
63
+ headers: {
64
+ Authorization: `Bearer ${token}`,
65
+ },
66
+ });
67
+ if (!response.ok) {
68
+ const errorText = yield response.text();
69
+ throw new Error(`Failed to delete exercise: ${errorText}`);
70
+ }
71
+ return yield response.json();
72
+ });
73
+ }
74
+ }