@codenotch/codenotch.react 1.0.81 → 2.0.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.
package/src/index.ts CHANGED
@@ -1,387 +1,532 @@
1
- import ReactDOM from "react-dom";
2
- import { SignalR } from "./core/SignalR";
3
- import ProcessUtils from "./core/ProcessUtils";
4
- import { IDisposable } from "./models/Misc";
5
- import { ICodenotchApi, ICodenotchDialog, ICodenotchEnv, IProcessResult } from "./models/Codenotch";
6
- import { v4 } from "uuid";
7
- import CodeEditor from "./components/CodeEditor";
8
-
9
- var signalR: SignalR | undefined = undefined;
10
-
11
- /**
12
- * The Codenotch runtime environment, populated by {@link init}.
13
- * Prefer reading it through `useCodenotch().env`.
14
- */
15
- const env: ICodenotchEnv = {};
16
-
17
- const MISSING_CLUSTER_URL_ERROR = "Codenotch cluster URL is not defined. Please set it in the Codenotch configuration.";
18
- const MISSING_SERVICE_NAME_ERROR = "Codenotch service name is not defined. Please set it in the Codenotch configuration.";
19
- const MISSING_TENANT_NAME_ERROR = "Codenotch tenant name is not defined. Please set it in the Codenotch configuration.";
20
-
21
- /**
22
- * Initialize the Codenotch environment from the given key-value pairs.
23
- *
24
- * This is normally called once, by the page hosting the application, with the
25
- * environment variables injected by the Codenotch runtime (URL parameters or
26
- * any other source). It must be called before `useCodenotch()` is used.
27
- *
28
- * Recognized key formats:
29
- * - `i18n.<key>.<language>` — a translation, stored in `env.i18n[language][key]`.
30
- * The first language found becomes the current language if none is set.
31
- * - `GLOBAL.<name>` — JSON value assigned to `window[name]` (or `globalThis`).
32
- * - `appManifest` / `projectManifest` — parsed as JSON into the environment.
33
- * - anything else — copied as-is onto {@link env}.
34
- *
35
- * The UI theme is resolved from the `_theme` URL parameter, or from
36
- * `prefers-color-scheme` as a fallback.
37
- *
38
- * @param envVariables An object containing the Codenotch environment variables as key-value pairs.
39
- * @example
40
- * import { init } from 'codenotch-react';
41
- * init({
42
- * clusterUrl: 'https://cluster.example.com',
43
- * serviceName: 'myproject',
44
- * tenantName: 'acme',
45
- * 'i18n.welcome.en': 'Welcome',
46
- * 'i18n.welcome.fr': 'Bienvenue'
47
- * });
48
- */
49
- function init(envVariables: any): void {
50
-
51
-
52
- // Ensure envVariables is an object
53
- if (typeof envVariables === 'object' && envVariables !== null) {
54
-
55
- let i18nLanguages = new Set<string>();
56
-
57
- Object.keys(envVariables).forEach((key) => {
58
- try {
59
- if (key.startsWith('GLOBAL.')) {
60
- // Global variable, we set it directly on the window object
61
- let globalKey = key.substring('GLOBAL.'.length);
62
- let globalObject = typeof window !== 'undefined' ? window : globalThis;
63
- (globalObject as any)[globalKey] = JSON.parse(envVariables[key]);
64
- console.log(`Codenotch global variable ${globalKey} set!`);
65
- return;
66
- }
67
- else if (key.startsWith("i18n.")) {
68
- // Special case
69
- let parts = key.split("."); // i18n.someKey.fr
70
- let language = parts[parts.length - 1]; // fr
71
- let keyName = parts.slice(1, parts.length - 1).join("."); // someKey
72
- i18nLanguages.add(language);
73
-
74
- let value = `${envVariables[key]}`.trim();
75
- if (value.startsWith('"') && value.endsWith('"')) {
76
- // Parse like json
77
- value = JSON.parse(value);
78
- }
79
-
80
- env.i18n = env.i18n ?? {};
81
- env.i18n[language] = env.i18n[language] ?? {};
82
- env.i18n[language][keyName] = value;
83
- }
84
- else {
85
- (env as any)[key] = envVariables[key];
86
-
87
- if (['appManifest', 'projectManifest'].includes(key)) {
88
- // Must be Json
89
- try {
90
- (env as any)[key] = JSON.parse(envVariables[key]);
91
- }
92
- catch (error) {
93
- console.warn(`Codenotch environment variable ${key} is not a valid JSON string. Using raw value.`);
94
- }
95
- }
96
-
97
- console.log(`Codenotch environment variable ${key} set to ${(env as any)[key]}`);
98
- }
99
- }
100
- catch (error) {
101
- console.error(`Error processing Codenotch environment variable ${key}:`, error);
102
- }
103
- });
104
-
105
- if (env.language === undefined) {
106
- // If current language is not defined, we set it to the first language found in i18n
107
- if (i18nLanguages.size > 0) {
108
- env.language = Array.from(i18nLanguages)[0];
109
- console.log(`Codenotch current language set to ${env.language}`);
110
- }
111
- }
112
-
113
- }
114
-
115
- // Instantiate SignalR for further use in the API
116
- if (env.clusterUrl && env.serviceName) {
117
- signalR = new SignalR(env.clusterUrl, env.serviceName, false, env.accessToken);
118
- }
119
-
120
- // Get theme like AEC does
121
- try {
122
- let urlParams = Object.fromEntries(new URLSearchParams(window.location.search).entries());
123
- if (urlParams["_theme"]) {
124
- let theme = urlParams["_theme"].toLowerCase();
125
- if (theme === "light" || theme === "dark") {
126
- env.theme = theme;
127
- }
128
- }
129
- else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
130
- env.theme = 'dark';
131
- }
132
- else {
133
- env.theme = 'light';
134
- }
135
- }
136
- catch {
137
- }
138
- }
139
-
140
- /**
141
- * Return the Codenotch client API bound to the current environment.
142
- *
143
- * Despite its name this is NOT a React hook — it is a plain function with no
144
- * hook rules attached: it can be called anywhere (components, handlers, plain
145
- * modules). `init()` must have been called first, which the Codenotch runtime
146
- * does automatically when serving the application.
147
- *
148
- * @returns The Codenotch API: BPMN processes, SioQL queries, i18n, signals, theme…
149
- * @example
150
- * import { useCodenotch } from 'codenotch-react';
151
- *
152
- * const MyApp: React.FC = () => {
153
- * const cn = useCodenotch();
154
- * return <h1>{cn.i18n('welcome')}</h1>;
155
- * };
156
- */
157
- function useCodenotch(): ICodenotchApi {
158
- return {
159
- env: env,
160
- uuid: () => v4(),
161
- getProjectFileUrl: (relativePath: string): string => {
162
- if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
163
- if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
164
- relativePath = relativePath.replace(/\\/g, "/");
165
- if (relativePath.startsWith("/")) relativePath = relativePath.substring(1);
166
- let url = `${env.clusterUrl}/${env.serviceName}/project/file?name=""&path=${encodeURIComponent(relativePath)}`;
167
- return url;
168
- },
169
- getProjectFile: async (relativePath: string): Promise<string | undefined> => {
170
- let url = useCodenotch().getProjectFileUrl(relativePath);
171
- let resp = await fetch(url);
172
- if (resp.status.toString().startsWith('2') === false) {
173
- throw new Error(`Failed to fetch file content: ${resp.status} ${resp.statusText}`);
174
- }
175
- let content = await resp.text();
176
- return content;
177
- },
178
- requestSioql: async (sioql: string, verbose?: boolean): Promise<any> => {
179
- if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
180
- if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
181
-
182
- const request: RequestInit = {
183
- method: 'POST',
184
- mode: 'cors',
185
- credentials: 'same-origin',
186
- headers: { 'Content-Type': 'application/json' },
187
- body: `"${sioql.replace(/\"/g, '\\\"')}"`
188
- };
189
-
190
- if (`${env.accessToken ?? ''}`.trim() !== "") {
191
- if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
192
- request.headers = {
193
- ...request.headers, [`${env.tenantName}AccessToken`]: env.accessToken!
194
- };
195
- }
196
-
197
- const response = await fetch(`${env.clusterUrl}/${env.serviceName}/sioql${verbose ? "?v=true" : ""}`, request);
198
- if (!response.ok) {
199
- const error = await response.text();
200
- throw new Error(error);
201
- }
202
-
203
- return await response.json();
204
- },
205
- i18n: (key: string, ...args: any[]): string => {
206
- try {
207
- if (env.i18n === undefined || Object.keys(env.i18n).length === 0) {
208
- console.warn("Codenotch i18n is not defined. Please set it in the Codenotch configuration.");
209
- return key;
210
- }
211
-
212
- let language = env.language ?? "en";
213
- let isLanguageExists = env.i18n[language] !== undefined;
214
- if (isLanguageExists === false) {
215
- let fallbackLanguage = Object.keys(env.i18n)[0];
216
- console.warn(`Codenotch i18n language ${language} is not defined. Falling back to ${fallbackLanguage}. Please set the correct language in the Codenotch configuration.`);
217
- language = fallbackLanguage;
218
- }
219
-
220
- let dico = env.i18n[language];
221
- let value = dico[key];
222
-
223
- if (typeof value !== "string") {
224
- console.warn(`Codenotch i18n key ${key} is not defined for language ${language}. Please set it in the Codenotch configuration.`);
225
- return key;
226
- }
227
- args = args ?? [];
228
-
229
- let result = value.replace(/{([\d ]*)}/g, (match, p1) => {
230
- let argValue = args[p1.trim()];
231
- // Instead of returning 'undefined', returns an empty string
232
- return argValue !== undefined ? argValue : "";
233
- });
234
-
235
- return result;
236
- }
237
- catch (error) {
238
- console.error("Error in i18n function:", error);
239
- return key;
240
- }
241
- },
242
- startProcess: async (processName: any, startNodeId: any, inputs: any): Promise<IProcessResult> => {
243
- if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
244
- if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
245
- if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
246
- if (signalR === undefined) throw new Error("SignalR not available. Cannot start process.");
247
- return ProcessUtils.startProcess((processInstanceId, callbacks) => signalR!.subscribeToProcessInstance(processInstanceId, callbacks),
248
- env.clusterUrl,
249
- env.tenantName,
250
- env.serviceName,
251
- processName,
252
- inputs,
253
- undefined,
254
- startNodeId ?? 'start',
255
- env.accessToken);
256
- },
257
- getUrlParams: () => {
258
- let result: { [key: string]: string } = {};
259
- if (typeof window !== 'undefined') {
260
- const params = new URL(window.location.href).searchParams;
261
- params.forEach((value: string, key: string) => {
262
- if (result[key] === undefined) {
263
- result[key] = value;
264
- }
265
- });
266
- }
267
- return result;
268
- },
269
- showDialog: (node: JSX.Element): ICodenotchDialog => {
270
- let dialogId = "codenotch-dialog-" + Math.random().toString(36).substring(2, 9);
271
- let result: ICodenotchDialog = {
272
- id: dialogId,
273
- close: () => {
274
- let dialogElement = document.getElementById(dialogId);
275
- if (dialogElement) {
276
- dialogElement.remove();
277
- }
278
- }
279
- };
280
-
281
- // Find "cn-dialog-container" element in the page
282
- let container = document.getElementById("cn-dialog-container");
283
- if (container === null) {
284
- container = document.createElement("div");
285
- container.id = "cn-dialog-container";
286
- container.style.zIndex = "9999";
287
- container.style.position = "fixed";
288
- container.style.top = "0";
289
- container.style.left = "0";
290
- container.style.minWidth = "100vw";
291
- container.style.minHeight = "100vh";
292
- container.style.maxWidth = "100vw";
293
- container.style.maxHeight = "100vh";
294
- container.style.display = "flex";
295
- container.style.alignItems = "center";
296
- container.style.justifyContent = "center";
297
- container.style.pointerEvents = 'none';
298
- document.body.appendChild(container);
299
- }
300
-
301
- let dialogElement = document.createElement('dialog');
302
- dialogElement.id = dialogId;
303
- dialogElement.style.zIndex = "9999";
304
- dialogElement.style.position = "fixed";
305
- dialogElement.style.top = "0";
306
- dialogElement.style.left = "0";
307
- dialogElement.style.minWidth = "100vw";
308
- dialogElement.style.minHeight = "100vh";
309
- dialogElement.style.maxWidth = "100vw";
310
- dialogElement.style.maxHeight = "100vh";
311
- dialogElement.style.display = "flex";
312
- dialogElement.style.alignItems = "center";
313
- dialogElement.style.justifyContent = "center";
314
- dialogElement.style.pointerEvents = 'all';
315
- dialogElement.style.background = '#78787822';
316
- dialogElement.style.backdropFilter = 'blur(2px)';
317
-
318
- container.appendChild(dialogElement);
319
-
320
- ReactDOM.render(node, dialogElement, () => {
321
- dialogElement.showModal();
322
- });
323
-
324
- return result;
325
- },
326
- listenSignal: async (signalId: string, callback: (data: any) => void): Promise<IDisposable> => {
327
-
328
- if (!signalR) {
329
- throw new Error("SignalR not available. Cannot listen to signal.");
330
- }
331
-
332
- let unsubscribeFunc = await signalR.subscribeToSignal(signalId, callback);
333
-
334
- return {
335
- dispose: () => {
336
- unsubscribeFunc();
337
- }
338
- };
339
-
340
- },
341
- setTheme: (theme: 'light' | 'dark') => {
342
- if (env.theme === theme) return;
343
- if (env.theme) document.documentElement.classList.remove(env.theme);
344
-
345
- env.theme = theme;
346
- document.documentElement.classList.add(theme);
347
- },
348
- setLanguage: (lang: string) => {
349
- if (env.language === lang) return;
350
- env.language = lang;
351
- },
352
- getLanguages: () => {
353
- return env.projectManifest?.languages ?? [];
354
- },
355
- getLanguage: () => {
356
- return env.language;
357
- },
358
- getTheme: () => {
359
- return env.theme;
360
- },
361
- getProjectManifest: () => {
362
- if (env.projectManifest === undefined) {
363
- throw new Error("Project manifest is not defined in Codenotch environment. Please set it in the Codenotch configuration.");
364
- }
365
- return env.projectManifest;
366
- },
367
- getAppManifest: () => {
368
- return env.appManifest;
369
- }
370
- };
371
- }
372
-
373
- export {
374
- env,
375
- useCodenotch,
376
- init,
377
- CodeEditor
378
- };
379
-
380
- // Public models. Re-exported from the package root so that the typings
381
- // generated by the Codenotch IDE (typings/i18n.d.ts and typings/process.d.ts,
382
- // which augment the 'codenotch-react' module) merge with the real
383
- // TranslationRegistry / ProcessRegistry declarations.
384
- export * from "./models/Codenotch";
385
- export * from "./models/Misc";
386
- export * from "./models/AppManifestModels";
1
+ import { createElement, useSyncExternalStore, type ComponentType, type ComponentProps, type FunctionComponent, type ReactNode, type RefAttributes } from "react";
2
+ import { flushSync } from "react-dom";
3
+ import { createRoot, Root } from "react-dom/client";
4
+ import { SignalR } from "./core/SignalR";
5
+ import ProcessUtils from "./core/ProcessUtils";
6
+ import { IDisposable } from "./models/Misc";
7
+ import { ICodenotchApi, ICodenotchDialog, ICodenotchEnv, IProcessResult, WithCodenotchProps } from "./models/Codenotch";
8
+ import { v4 } from "uuid";
9
+ import CodeEditor from "./components/CodeEditor";
10
+
11
+ var signalR: SignalR | undefined = undefined;
12
+
13
+ /**
14
+ * The Codenotch runtime environment, populated by {@link init}.
15
+ * Prefer reading it through `useCodenotch().env`.
16
+ */
17
+ const env: ICodenotchEnv = {};
18
+
19
+ const MISSING_CLUSTER_URL_ERROR = "Codenotch cluster URL is not defined. Please set it in the Codenotch configuration.";
20
+ const MISSING_SERVICE_NAME_ERROR = "Codenotch service name is not defined. Please set it in the Codenotch configuration.";
21
+ const MISSING_TENANT_NAME_ERROR = "Codenotch tenant name is not defined. Please set it in the Codenotch configuration.";
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Change tracking. `env` is a plain mutable object; every mutation done through
25
+ // the public API (init, setTheme, setLanguage) goes through notify(), which
26
+ // rotates the API object (so React sees a new reference) and wakes up the
27
+ // subscribers: useCodenotch() via useSyncExternalStore, withCodenotch(),
28
+ // and any listener registered with onCodenotchChange().
29
+ // ---------------------------------------------------------------------------
30
+ const listeners = new Set<() => void>();
31
+ let currentApi: ICodenotchApi;
32
+
33
+ function notify(): void {
34
+ currentApi = createApi();
35
+ listeners.forEach((listener) => {
36
+ try { listener(); }
37
+ catch (error) { console.error("Error in Codenotch change listener:", error); }
38
+ });
39
+ }
40
+
41
+ function subscribe(listener: () => void): () => void {
42
+ listeners.add(listener);
43
+ return () => { listeners.delete(listener); };
44
+ }
45
+
46
+ /**
47
+ * Initialize the Codenotch environment from the given key-value pairs.
48
+ *
49
+ * This is normally called once, by the page hosting the application, with the
50
+ * environment variables injected by the Codenotch runtime (URL parameters or
51
+ * any other source). It must be called before `useCodenotch()` is used.
52
+ *
53
+ * Recognized key formats:
54
+ * - `i18n.<key>.<language>` — a translation, stored in `env.i18n[language][key]`.
55
+ * The first language found becomes the current language if none is set.
56
+ * - `GLOBAL.<name>` — JSON value assigned to `window[name]` (or `globalThis`).
57
+ * - `appManifest` / `projectManifest` — parsed as JSON into the environment.
58
+ * - anything else — copied as-is onto {@link env}.
59
+ *
60
+ * The UI theme is resolved from the `_theme` URL parameter, or from
61
+ * `prefers-color-scheme` as a fallback.
62
+ *
63
+ * @param envVariables An object containing the Codenotch environment variables as key-value pairs.
64
+ * @example
65
+ * import { init } from 'codenotch-react';
66
+ * init({
67
+ * clusterUrl: 'https://cluster.example.com',
68
+ * serviceName: 'myproject',
69
+ * tenantName: 'acme',
70
+ * 'i18n.welcome.en': 'Welcome',
71
+ * 'i18n.welcome.fr': 'Bienvenue'
72
+ * });
73
+ */
74
+ function init(envVariables: any): void {
75
+
76
+
77
+ // Ensure envVariables is an object
78
+ if (typeof envVariables === 'object' && envVariables !== null) {
79
+
80
+ let i18nLanguages = new Set<string>();
81
+
82
+ Object.keys(envVariables).forEach((key) => {
83
+ try {
84
+ if (key.startsWith('GLOBAL.')) {
85
+ // Global variable, we set it directly on the window object
86
+ let globalKey = key.substring('GLOBAL.'.length);
87
+ let globalObject = typeof window !== 'undefined' ? window : globalThis;
88
+ (globalObject as any)[globalKey] = JSON.parse(envVariables[key]);
89
+ console.log(`Codenotch global variable ${globalKey} set!`);
90
+ return;
91
+ }
92
+ else if (key.startsWith("i18n.")) {
93
+ // Special case
94
+ let parts = key.split("."); // i18n.someKey.fr
95
+ let language = parts[parts.length - 1]; // fr
96
+ let keyName = parts.slice(1, parts.length - 1).join("."); // someKey
97
+ i18nLanguages.add(language);
98
+
99
+ let value = `${envVariables[key]}`.trim();
100
+ if (value.startsWith('"') && value.endsWith('"')) {
101
+ // Parse like json
102
+ value = JSON.parse(value);
103
+ }
104
+
105
+ env.i18n = env.i18n ?? {};
106
+ env.i18n[language] = env.i18n[language] ?? {};
107
+ env.i18n[language][keyName] = value;
108
+ }
109
+ else {
110
+ (env as any)[key] = envVariables[key];
111
+
112
+ if (['appManifest', 'projectManifest'].includes(key)) {
113
+ // Must be Json
114
+ try {
115
+ (env as any)[key] = JSON.parse(envVariables[key]);
116
+ }
117
+ catch (error) {
118
+ console.warn(`Codenotch environment variable ${key} is not a valid JSON string. Using raw value.`);
119
+ }
120
+ }
121
+
122
+ console.log(`Codenotch environment variable ${key} set to ${(env as any)[key]}`);
123
+ }
124
+ }
125
+ catch (error) {
126
+ console.error(`Error processing Codenotch environment variable ${key}:`, error);
127
+ }
128
+ });
129
+
130
+ if (env.language === undefined) {
131
+ // If current language is not defined, we set it to the first language found in i18n
132
+ if (i18nLanguages.size > 0) {
133
+ env.language = Array.from(i18nLanguages)[0];
134
+ console.log(`Codenotch current language set to ${env.language}`);
135
+ }
136
+ }
137
+
138
+ }
139
+
140
+ // Instantiate SignalR for further use in the API
141
+ if (env.clusterUrl && env.serviceName) {
142
+ signalR = new SignalR(env.clusterUrl, env.serviceName, false, env.accessToken);
143
+ }
144
+
145
+ // Get theme like AEC does
146
+ try {
147
+ let urlParams = Object.fromEntries(new URLSearchParams(window.location.search).entries());
148
+ if (urlParams["_theme"]) {
149
+ let theme = urlParams["_theme"].toLowerCase();
150
+ if (theme === "light" || theme === "dark") {
151
+ env.theme = theme;
152
+ }
153
+ }
154
+ else if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
155
+ env.theme = 'dark';
156
+ }
157
+ else {
158
+ env.theme = 'light';
159
+ }
160
+ }
161
+ catch {
162
+ }
163
+
164
+ notify();
165
+ }
166
+
167
+ /**
168
+ * Build the API object bound to {@link env}. Every method reads `env` lazily,
169
+ * so an instance never goes stale; a new one is created by {@link notify} only
170
+ * to give React a fresh reference when the environment changes.
171
+ */
172
+ function createApi(): ICodenotchApi {
173
+ const api: ICodenotchApi = {
174
+ env: env,
175
+ uuid: () => v4(),
176
+ getProjectFileUrl: (relativePath: string): string => {
177
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
178
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
179
+ relativePath = relativePath.replace(/\\/g, "/");
180
+ if (relativePath.startsWith("/")) relativePath = relativePath.substring(1);
181
+ let url = `${env.clusterUrl}/${env.serviceName}/project/file?name=""&path=${encodeURIComponent(relativePath)}`;
182
+ return url;
183
+ },
184
+ getProjectFile: async (relativePath: string): Promise<string | undefined> => {
185
+ let url = api.getProjectFileUrl(relativePath);
186
+ let resp = await fetch(url);
187
+ if (resp.status.toString().startsWith('2') === false) {
188
+ throw new Error(`Failed to fetch file content: ${resp.status} ${resp.statusText}`);
189
+ }
190
+ let content = await resp.text();
191
+ return content;
192
+ },
193
+ requestCnql: async (cnql: string, verbose?: boolean): Promise<any> => {
194
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
195
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
196
+
197
+ const request: RequestInit = {
198
+ method: 'POST',
199
+ mode: 'cors',
200
+ credentials: 'same-origin',
201
+ headers: { 'Content-Type': 'application/json' },
202
+ body: `"${cnql.replace(/\"/g, '\\\"')}"`
203
+ };
204
+
205
+ if (`${env.accessToken ?? ''}`.trim() !== "") {
206
+ if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
207
+ request.headers = {
208
+ ...request.headers, [`${env.tenantName}AccessToken`]: env.accessToken!
209
+ };
210
+ }
211
+
212
+ const response = await fetch(`${env.clusterUrl}/${env.serviceName}/cnql${verbose ? "?v=true" : ""}`, request);
213
+ if (!response.ok) {
214
+ const error = await response.text();
215
+ throw new Error(error);
216
+ }
217
+
218
+ return await response.json();
219
+ },
220
+ i18n: (key: string, ...args: any[]): string => {
221
+ try {
222
+ if (env.i18n === undefined || Object.keys(env.i18n).length === 0) {
223
+ console.warn("Codenotch i18n is not defined. Please set it in the Codenotch configuration.");
224
+ return key;
225
+ }
226
+
227
+ let language = env.language ?? "en";
228
+ let isLanguageExists = env.i18n[language] !== undefined;
229
+ if (isLanguageExists === false) {
230
+ let fallbackLanguage = Object.keys(env.i18n)[0];
231
+ console.warn(`Codenotch i18n language ${language} is not defined. Falling back to ${fallbackLanguage}. Please set the correct language in the Codenotch configuration.`);
232
+ language = fallbackLanguage;
233
+ }
234
+
235
+ let dico = env.i18n[language];
236
+ let value = dico[key];
237
+
238
+ if (typeof value !== "string") {
239
+ console.warn(`Codenotch i18n key ${key} is not defined for language ${language}. Please set it in the Codenotch configuration.`);
240
+ return key;
241
+ }
242
+ args = args ?? [];
243
+
244
+ let result = value.replace(/{([\d ]*)}/g, (match, p1) => {
245
+ let argValue = args[p1.trim()];
246
+ // Instead of returning 'undefined', returns an empty string
247
+ return argValue !== undefined ? argValue : "";
248
+ });
249
+
250
+ return result;
251
+ }
252
+ catch (error) {
253
+ console.error("Error in i18n function:", error);
254
+ return key;
255
+ }
256
+ },
257
+ startProcess: async (processName: any, startNodeId: any, inputs: any): Promise<IProcessResult> => {
258
+ if (env.clusterUrl === undefined) throw new Error(MISSING_CLUSTER_URL_ERROR);
259
+ if (env.serviceName === undefined) throw new Error(MISSING_SERVICE_NAME_ERROR);
260
+ if (env.tenantName === undefined) throw new Error(MISSING_TENANT_NAME_ERROR);
261
+ if (signalR === undefined) throw new Error("SignalR not available. Cannot start process.");
262
+ return ProcessUtils.startProcess((processInstanceId, callbacks) => signalR!.subscribeToProcessInstance(processInstanceId, callbacks),
263
+ env.clusterUrl,
264
+ env.tenantName,
265
+ env.serviceName,
266
+ processName,
267
+ inputs,
268
+ undefined,
269
+ startNodeId ?? 'start',
270
+ env.accessToken);
271
+ },
272
+ getUrlParams: () => {
273
+ let result: { [key: string]: string } = {};
274
+ if (typeof window !== 'undefined') {
275
+ const params = new URL(window.location.href).searchParams;
276
+ params.forEach((value: string, key: string) => {
277
+ if (result[key] === undefined) {
278
+ result[key] = value;
279
+ }
280
+ });
281
+ }
282
+ return result;
283
+ },
284
+ showDialog: (node: ReactNode): ICodenotchDialog => {
285
+ let dialogId = "codenotch-dialog-" + Math.random().toString(36).substring(2, 9);
286
+ let root: Root | undefined = undefined;
287
+ let result: ICodenotchDialog = {
288
+ id: dialogId,
289
+ close: () => {
290
+ // Unmount the React tree first so effects are cleaned up and nothing leaks,
291
+ // then drop the <dialog> element itself.
292
+ root?.unmount();
293
+ root = undefined;
294
+ let dialogElement = document.getElementById(dialogId);
295
+ if (dialogElement) {
296
+ dialogElement.remove();
297
+ }
298
+ }
299
+ };
300
+
301
+ // Find "cn-dialog-container" element in the page
302
+ let container = document.getElementById("cn-dialog-container");
303
+ if (container === null) {
304
+ container = document.createElement("div");
305
+ container.id = "cn-dialog-container";
306
+ container.style.zIndex = "9999";
307
+ container.style.position = "fixed";
308
+ container.style.top = "0";
309
+ container.style.left = "0";
310
+ container.style.minWidth = "100vw";
311
+ container.style.minHeight = "100vh";
312
+ container.style.maxWidth = "100vw";
313
+ container.style.maxHeight = "100vh";
314
+ container.style.display = "flex";
315
+ container.style.alignItems = "center";
316
+ container.style.justifyContent = "center";
317
+ container.style.pointerEvents = 'none';
318
+ document.body.appendChild(container);
319
+ }
320
+
321
+ let dialogElement = document.createElement('dialog');
322
+ dialogElement.id = dialogId;
323
+ dialogElement.style.zIndex = "9999";
324
+ dialogElement.style.position = "fixed";
325
+ dialogElement.style.top = "0";
326
+ dialogElement.style.left = "0";
327
+ dialogElement.style.minWidth = "100vw";
328
+ dialogElement.style.minHeight = "100vh";
329
+ dialogElement.style.maxWidth = "100vw";
330
+ dialogElement.style.maxHeight = "100vh";
331
+ dialogElement.style.display = "flex";
332
+ dialogElement.style.alignItems = "center";
333
+ dialogElement.style.justifyContent = "center";
334
+ dialogElement.style.pointerEvents = 'all';
335
+ dialogElement.style.background = '#78787822';
336
+ dialogElement.style.backdropFilter = 'blur(2px)';
337
+
338
+ container.appendChild(dialogElement);
339
+
340
+ // React 19: ReactDOM.render() is gone. Render synchronously through a dedicated root
341
+ // so the content is in the DOM before showModal() moves the focus into the dialog.
342
+ root = createRoot(dialogElement);
343
+ flushSync(() => root!.render(node));
344
+ dialogElement.showModal();
345
+
346
+ return result;
347
+ },
348
+ listenSignal: async (signalId: string, callback: (data: any) => void): Promise<IDisposable> => {
349
+
350
+ if (!signalR) {
351
+ throw new Error("SignalR not available. Cannot listen to signal.");
352
+ }
353
+
354
+ let unsubscribeFunc = await signalR.subscribeToSignal(signalId, callback);
355
+
356
+ return {
357
+ dispose: () => {
358
+ unsubscribeFunc();
359
+ }
360
+ };
361
+
362
+ },
363
+ setTheme: (theme: 'light' | 'dark') => {
364
+ if (env.theme === theme) return;
365
+ if (env.theme) document.documentElement.classList.remove(env.theme);
366
+
367
+ env.theme = theme;
368
+ document.documentElement.classList.add(theme);
369
+ notify();
370
+ },
371
+ setLanguage: (lang: string) => {
372
+ if (env.language === lang) return;
373
+ env.language = lang;
374
+ notify();
375
+ },
376
+ getLanguages: () => {
377
+ return env.projectManifest?.languages ?? [];
378
+ },
379
+ getLanguage: () => {
380
+ return env.language;
381
+ },
382
+ getTheme: () => {
383
+ return env.theme;
384
+ },
385
+ getProjectManifest: () => {
386
+ if (env.projectManifest === undefined) {
387
+ throw new Error("Project manifest is not defined in Codenotch environment. Please set it in the Codenotch configuration.");
388
+ }
389
+ return env.projectManifest;
390
+ },
391
+ getAppManifest: () => {
392
+ return env.appManifest;
393
+ }
394
+ };
395
+ return api;
396
+ }
397
+
398
+ currentApi = createApi();
399
+
400
+ /**
401
+ * Return the Codenotch client API bound to the current environment, from
402
+ * anywhere: event handlers, plain modules, class components, services…
403
+ *
404
+ * This is a plain function (not a hook). The returned object is never stale —
405
+ * its methods always read the live environment — but it does not trigger any
406
+ * re-render when the language or theme changes: inside React components prefer
407
+ * {@link useCodenotch} (function components) or {@link withCodenotch}
408
+ * (class components), which do.
409
+ *
410
+ * `init()` must have been called first, which the Codenotch runtime does
411
+ * automatically when serving the application.
412
+ *
413
+ * @example
414
+ * import { getCodenotch } from 'codenotch-react';
415
+ *
416
+ * export async function loadTodos(userId: string) {
417
+ * const result = await getCodenotch().startProcess('getTodos', 'start', { UserId: userId });
418
+ * return result.output.todos;
419
+ * }
420
+ */
421
+ function getCodenotch(): ICodenotchApi {
422
+ return currentApi;
423
+ }
424
+
425
+ /**
426
+ * React hook returning the Codenotch client API.
427
+ *
428
+ * The reference is stable across renders and only changes when the environment
429
+ * changes (`setLanguage`, `setTheme`, `init`), in which case every component
430
+ * using the hook re-renders — so `cn.i18n(...)` output follows the current
431
+ * language automatically, and the object is safe to use in `useMemo` /
432
+ * `useEffect` dependency arrays.
433
+ *
434
+ * Regular hook rules apply (call it unconditionally at the top of a function
435
+ * component or a custom hook). Outside of components — handlers defined in
436
+ * plain modules, services, class components — use {@link getCodenotch} or
437
+ * {@link withCodenotch} instead.
438
+ *
439
+ * @returns The Codenotch API: BPMN processes, CNQL queries, i18n, signals, theme…
440
+ * @example
441
+ * import { useCodenotch } from 'codenotch-react';
442
+ *
443
+ * const MyApp = () => {
444
+ * const cn = useCodenotch();
445
+ * return <h1>{cn.i18n('welcome')}</h1>;
446
+ * };
447
+ */
448
+ function useCodenotch(): ICodenotchApi {
449
+ return useSyncExternalStore(subscribe, getCodenotch, getCodenotch);
450
+ }
451
+
452
+ /**
453
+ * Register a listener called each time the Codenotch environment changes
454
+ * (`setLanguage`, `setTheme`, `init`). Escape hatch for code that cannot use
455
+ * {@link useCodenotch} or {@link withCodenotch}, e.g. a class component that
456
+ * wants to `forceUpdate()` itself, or a non-React module caching translations.
457
+ *
458
+ * @returns A disposable — call `dispose()` to stop listening.
459
+ * @example
460
+ * componentDidMount() {
461
+ * this.sub = onCodenotchChange(() => this.forceUpdate());
462
+ * }
463
+ * componentWillUnmount() {
464
+ * this.sub.dispose();
465
+ * }
466
+ */
467
+ function onCodenotchChange(listener: () => void): IDisposable {
468
+ const unsubscribe = subscribe(listener);
469
+ return { dispose: unsubscribe };
470
+ }
471
+
472
+ /** Props of a component wrapped by {@link withCodenotch}, without the injected `cn`. */
473
+ type WithoutCodenotchProps<P> = Omit<P, keyof WithCodenotchProps>;
474
+
475
+ /** Instance type of a component (class components only), used to type the forwarded `ref`. */
476
+ type ComponentInstance<C> = C extends new (...args: any[]) => infer I ? I : never;
477
+
478
+ /**
479
+ * Higher-order component injecting the Codenotch API as a `cn` prop.
480
+ *
481
+ * Meant for class components, which cannot call {@link useCodenotch}: the
482
+ * wrapped component receives `this.props.cn` and re-renders whenever the
483
+ * environment changes (language, theme…), exactly like the hook. A `ref`
484
+ * passed to the wrapper is forwarded to the wrapped component instance.
485
+ *
486
+ * @param Component A component whose props extend {@link WithCodenotchProps}.
487
+ * @returns A component with the same props minus `cn`.
488
+ * @example
489
+ * import { withCodenotch, WithCodenotchProps } from 'codenotch-react';
490
+ *
491
+ * interface Props extends WithCodenotchProps {
492
+ * userId: string;
493
+ * }
494
+ *
495
+ * class TodoList extends React.Component<Props> {
496
+ * render() {
497
+ * return <h1>{this.props.cn.i18n('todos.title')}</h1>;
498
+ * }
499
+ * }
500
+ *
501
+ * export default withCodenotch(TodoList);
502
+ * // <TodoList userId="42" /> — `cn` is injected
503
+ */
504
+ function withCodenotch<C extends ComponentType<any>>(
505
+ Component: C
506
+ ): FunctionComponent<WithoutCodenotchProps<ComponentProps<C>> & RefAttributes<ComponentInstance<C>>> {
507
+ const Wrapped = (props: WithoutCodenotchProps<ComponentProps<C>> & RefAttributes<ComponentInstance<C>>) => {
508
+ const cn = useCodenotch();
509
+ // React 19: `ref` is a regular prop, so spreading `props` forwards it.
510
+ return createElement(Component, { ...props, cn });
511
+ };
512
+ Wrapped.displayName = `withCodenotch(${Component.displayName || Component.name || "Component"})`;
513
+ return Wrapped;
514
+ }
515
+
516
+ export {
517
+ env,
518
+ useCodenotch,
519
+ getCodenotch,
520
+ withCodenotch,
521
+ onCodenotchChange,
522
+ init,
523
+ CodeEditor
524
+ };
525
+
526
+ // Public models. Re-exported from the package root so that the typings
527
+ // generated by the Codenotch IDE (typings/i18n.d.ts and typings/process.d.ts,
528
+ // which augment the 'codenotch-react' module) merge with the real
529
+ // TranslationRegistry / ProcessRegistry declarations.
530
+ export * from "./models/Codenotch";
531
+ export * from "./models/Misc";
387
532
  export * from "@codenotch/codenotch.core";