@cervio/plugin-sdk 1.1.0 → 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/LICENSE +21 -0
- package/README.md +64 -9
- package/dist/index.d.ts +92 -26
- package/dist/index.js +51 -35
- package/dist/pdf/index.d.ts +4 -3
- package/dist/pdf/index.js +6 -6
- package/dist/policy/index.d.ts +82 -0
- package/dist/policy/index.js +25 -0
- package/package.json +32 -21
- package/dist/index.cjs +0 -297
- package/dist/index.cjs.map +0 -1
- package/dist/index.d.cts +0 -841
- package/dist/index.js.map +0 -1
- package/dist/pdf/index.cjs +0 -357
- package/dist/pdf/index.cjs.map +0 -1
- package/dist/pdf/index.d.cts +0 -38
- package/dist/pdf/index.js.map +0 -1
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Policy Plugin hook contract (shared by host, SDK, and manifest authors).
|
|
3
|
+
* Wire legacy: `plugin_type: "server"` is an alias for `"policy"`.
|
|
4
|
+
*/
|
|
5
|
+
type PolicyHookEvent = 'before_create' | 'before_update';
|
|
6
|
+
type PolicyHookCaller = {
|
|
7
|
+
userId?: string;
|
|
8
|
+
channel?: string;
|
|
9
|
+
organizationId?: string;
|
|
10
|
+
};
|
|
11
|
+
type PolicyHookInput = {
|
|
12
|
+
event: PolicyHookEvent;
|
|
13
|
+
entity: {
|
|
14
|
+
id?: string;
|
|
15
|
+
name?: string;
|
|
16
|
+
};
|
|
17
|
+
record: {
|
|
18
|
+
id?: string | null;
|
|
19
|
+
data: Record<string, unknown>;
|
|
20
|
+
previousData?: Record<string, unknown> | null;
|
|
21
|
+
};
|
|
22
|
+
caller?: PolicyHookCaller;
|
|
23
|
+
settings?: Record<string, unknown>;
|
|
24
|
+
pluginKey?: string;
|
|
25
|
+
allowedEntityReads?: string[];
|
|
26
|
+
deadlineMs?: number;
|
|
27
|
+
};
|
|
28
|
+
type PolicyHookResult = {
|
|
29
|
+
allow: true;
|
|
30
|
+
} | {
|
|
31
|
+
allow: false;
|
|
32
|
+
message: string;
|
|
33
|
+
code?: string;
|
|
34
|
+
};
|
|
35
|
+
/** Host-mediated reads injected by plugin-sandbox-runner (null if no allowlist/caller). */
|
|
36
|
+
type PolicyHost = {
|
|
37
|
+
getRecord(entityName: string, id: string): Promise<{
|
|
38
|
+
id: string;
|
|
39
|
+
data: Record<string, unknown>;
|
|
40
|
+
} | null>;
|
|
41
|
+
listRecords(entityName: string, opts?: {
|
|
42
|
+
filters?: Record<string, unknown>;
|
|
43
|
+
limit?: number;
|
|
44
|
+
offset?: number;
|
|
45
|
+
}): Promise<Array<{
|
|
46
|
+
id: string;
|
|
47
|
+
data: Record<string, unknown>;
|
|
48
|
+
}>>;
|
|
49
|
+
sumField(entityName: string, fieldName: string, opts?: {
|
|
50
|
+
filters?: Record<string, unknown>;
|
|
51
|
+
}): Promise<number>;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* `@cervio/plugin-sdk/policy`: helpers for write-gate plugins (`plugin_type: policy`).
|
|
56
|
+
*
|
|
57
|
+
* A policy plugin runs in a server-side isolate before a record is created or
|
|
58
|
+
* updated, and answers allow or deny. This entry is separate from the root entry:
|
|
59
|
+
* it must stay free of browser, React and PDF code, and must not import anything
|
|
60
|
+
* at runtime, so the isolate bundle (`server/index.js`) stays self-contained.
|
|
61
|
+
* The contract types come from `@cervio/plugin-core` as type-only imports and are
|
|
62
|
+
* inlined in this entry's declaration file.
|
|
63
|
+
*/
|
|
64
|
+
|
|
65
|
+
declare function allow(): Extract<PolicyHookResult, {
|
|
66
|
+
allow: true;
|
|
67
|
+
}>;
|
|
68
|
+
declare function deny(message: string, code?: string): Extract<PolicyHookResult, {
|
|
69
|
+
allow: false;
|
|
70
|
+
}>;
|
|
71
|
+
type DefinePolicyOptions = {
|
|
72
|
+
/**
|
|
73
|
+
* Default false. When true, throw/reject becomes `{ allow: false, message }`.
|
|
74
|
+
* When false, errors propagate to the host → legacy `server_plugin_unavailable`.
|
|
75
|
+
*/
|
|
76
|
+
catchErrors?: boolean;
|
|
77
|
+
};
|
|
78
|
+
type PolicyHandler = (input: PolicyHookInput, host: PolicyHost | null) => PolicyHookResult | Promise<PolicyHookResult>;
|
|
79
|
+
declare function definePolicy(handler: PolicyHandler, options?: DefinePolicyOptions): (input: PolicyHookInput, host?: PolicyHost | null) => Promise<PolicyHookResult>;
|
|
80
|
+
|
|
81
|
+
export { allow, definePolicy, deny };
|
|
82
|
+
export type { DefinePolicyOptions, PolicyHandler, PolicyHookCaller, PolicyHookEvent, PolicyHookInput, PolicyHookResult, PolicyHost };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// src/policy/index.ts
|
|
2
|
+
function allow() {
|
|
3
|
+
return { allow: true };
|
|
4
|
+
}
|
|
5
|
+
function deny(message, code) {
|
|
6
|
+
const trimmed = String(message ?? "").trim();
|
|
7
|
+
if (!trimmed) {
|
|
8
|
+
throw new Error("deny() requires a non-empty message");
|
|
9
|
+
}
|
|
10
|
+
return code ? { allow: false, message: trimmed, code } : { allow: false, message: trimmed };
|
|
11
|
+
}
|
|
12
|
+
function definePolicy(handler, options) {
|
|
13
|
+
const catchErrors = options?.catchErrors === true;
|
|
14
|
+
return async (input, host = null) => {
|
|
15
|
+
try {
|
|
16
|
+
return await handler(input, host);
|
|
17
|
+
} catch (err) {
|
|
18
|
+
if (!catchErrors) throw err;
|
|
19
|
+
const message = err instanceof Error && err.message.trim() ? err.message.trim() : "Policy Plugin error";
|
|
20
|
+
return deny(message);
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { allow, definePolicy, deny };
|
package/package.json
CHANGED
|
@@ -1,26 +1,42 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cervio/plugin-sdk",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "SDK for Cervio plugins: CervioUI client, plugin context, /api/v1 client, theme sync, i18n, PDF viewer (./pdf) and write-gate helpers (./policy).",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cervio",
|
|
7
|
+
"plugin",
|
|
8
|
+
"sdk"
|
|
9
|
+
],
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"homepage": "https://github.com/cervio-app/cervio-devkit/tree/main/packages/plugin-sdk#readme",
|
|
12
|
+
"bugs": "https://github.com/cervio-app/cervio-devkit/issues",
|
|
13
|
+
"repository": {
|
|
14
|
+
"type": "git",
|
|
15
|
+
"url": "git+https://github.com/cervio-app/cervio-devkit.git",
|
|
16
|
+
"directory": "packages/plugin-sdk"
|
|
17
|
+
},
|
|
5
18
|
"type": "module",
|
|
6
|
-
"
|
|
7
|
-
"
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"main": "./dist/index.js",
|
|
8
21
|
"types": "./dist/index.d.ts",
|
|
9
22
|
"exports": {
|
|
10
23
|
".": {
|
|
11
24
|
"types": "./dist/index.d.ts",
|
|
12
|
-
"import": "./dist/index.js"
|
|
13
|
-
"require": "./dist/index.cjs"
|
|
25
|
+
"import": "./dist/index.js"
|
|
14
26
|
},
|
|
15
27
|
"./pdf": {
|
|
16
28
|
"types": "./dist/pdf/index.d.ts",
|
|
17
|
-
"import": "./dist/pdf/index.js"
|
|
18
|
-
|
|
29
|
+
"import": "./dist/pdf/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./policy": {
|
|
32
|
+
"types": "./dist/policy/index.d.ts",
|
|
33
|
+
"import": "./dist/policy/index.js"
|
|
19
34
|
}
|
|
20
35
|
},
|
|
21
36
|
"files": [
|
|
22
37
|
"dist",
|
|
23
|
-
"README.md"
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE"
|
|
24
40
|
],
|
|
25
41
|
"peerDependencies": {
|
|
26
42
|
"react": ">=18",
|
|
@@ -35,32 +51,27 @@
|
|
|
35
51
|
}
|
|
36
52
|
},
|
|
37
53
|
"dependencies": {
|
|
38
|
-
"pdfjs-dist": "
|
|
54
|
+
"pdfjs-dist": "6.5.438"
|
|
39
55
|
},
|
|
40
56
|
"devDependencies": {
|
|
41
|
-
"@types/node": "^
|
|
57
|
+
"@types/node": "^26.0.0",
|
|
42
58
|
"@types/react": "^19.0.0",
|
|
43
59
|
"@types/react-dom": "^19.0.0",
|
|
44
|
-
"jsdom": "^
|
|
60
|
+
"jsdom": "^31.0.0",
|
|
45
61
|
"react": "^19.0.0",
|
|
46
62
|
"react-dom": "^19.0.0",
|
|
47
|
-
"tsup": "^
|
|
63
|
+
"tsup": "^9.0.0",
|
|
48
64
|
"typescript": "^5.8.3",
|
|
49
|
-
"vitest": "^
|
|
65
|
+
"vitest": "^5.0.5",
|
|
66
|
+
"@cervio/plugin-core": "^1.0.0"
|
|
50
67
|
},
|
|
51
68
|
"publishConfig": {
|
|
52
69
|
"access": "public"
|
|
53
70
|
},
|
|
54
|
-
"license": "UNLICENSED",
|
|
55
|
-
"keywords": [
|
|
56
|
-
"cervio",
|
|
57
|
-
"plugin",
|
|
58
|
-
"sdk"
|
|
59
|
-
],
|
|
60
71
|
"scripts": {
|
|
61
72
|
"prebuild": "node scripts/generate-pdf-worker-src.mjs",
|
|
62
73
|
"build": "tsup --config tsup.config.ts",
|
|
63
|
-
"typecheck": "tsc -p tsconfig.json
|
|
74
|
+
"typecheck": "node scripts/generate-pdf-worker-src.mjs && tsc -p tsconfig.json && tsc -p tsconfig.test.json",
|
|
64
75
|
"test": "vitest run"
|
|
65
76
|
}
|
|
66
77
|
}
|
package/dist/index.cjs
DELETED
|
@@ -1,297 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
// src/cervio-ui.ts
|
|
4
|
-
var CERVIO_UI_API_VERSION = "1.0.0";
|
|
5
|
-
function getCervioUI() {
|
|
6
|
-
if (typeof window === "undefined" || !window.CervioUI) {
|
|
7
|
-
throw new Error(
|
|
8
|
-
"CervioUI is not available. Route plugins must run inside the Cervio sandbox host."
|
|
9
|
-
);
|
|
10
|
-
}
|
|
11
|
-
return window.CervioUI;
|
|
12
|
-
}
|
|
13
|
-
function isCervioUIAvailable() {
|
|
14
|
-
return typeof window !== "undefined" && !!window.CervioUI;
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
// src/context.ts
|
|
18
|
-
function getPluginContext() {
|
|
19
|
-
if (typeof window === "undefined") return null;
|
|
20
|
-
return window.__CERVIO_PLUGIN_CONTEXT__ ?? null;
|
|
21
|
-
}
|
|
22
|
-
function isInsideCervioSandbox() {
|
|
23
|
-
return getPluginContext() != null;
|
|
24
|
-
}
|
|
25
|
-
function openExternalAuth(url) {
|
|
26
|
-
if (typeof window === "undefined" || typeof window.__cervioOpenExternalAuth !== "function") {
|
|
27
|
-
return false;
|
|
28
|
-
}
|
|
29
|
-
return window.__cervioOpenExternalAuth(url);
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
// src/task-context.ts
|
|
33
|
-
function getTaskPluginContext() {
|
|
34
|
-
if (typeof window === "undefined") return null;
|
|
35
|
-
const raw = window.__CERVIO_PLUGIN_CONTEXT__;
|
|
36
|
-
if (!raw || typeof raw !== "object" || typeof raw.pluginType !== "string") return null;
|
|
37
|
-
return raw;
|
|
38
|
-
}
|
|
39
|
-
async function setTaskDraft(data) {
|
|
40
|
-
if (typeof window === "undefined" || typeof window.__cervioTaskSetDraft !== "function") {
|
|
41
|
-
return { ok: false, error: "not_available" };
|
|
42
|
-
}
|
|
43
|
-
return window.__cervioTaskSetDraft(data);
|
|
44
|
-
}
|
|
45
|
-
async function submitTaskOutcome(outcomeKey, data) {
|
|
46
|
-
if (typeof window === "undefined" || typeof window.__cervioTaskSubmit !== "function") {
|
|
47
|
-
return { ok: false, error: "not_available" };
|
|
48
|
-
}
|
|
49
|
-
return window.__cervioTaskSubmit(outcomeKey, data);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// src/theme.ts
|
|
53
|
-
function isHostThemeMessage(data) {
|
|
54
|
-
return !!data && typeof data === "object" && data.__cervioPluginTheme === 1;
|
|
55
|
-
}
|
|
56
|
-
function onThemeChange(handler) {
|
|
57
|
-
if (typeof window === "undefined") return () => {
|
|
58
|
-
};
|
|
59
|
-
const current = getCurrentTheme();
|
|
60
|
-
if (current) handler(current);
|
|
61
|
-
const listener = (event) => {
|
|
62
|
-
if (!isHostThemeMessage(event.data)) return;
|
|
63
|
-
handler({
|
|
64
|
-
tokens: event.data.tokens ?? {},
|
|
65
|
-
colorScheme: event.data.colorScheme === "dark" ? "dark" : "light"
|
|
66
|
-
});
|
|
67
|
-
};
|
|
68
|
-
window.addEventListener("message", listener);
|
|
69
|
-
return () => window.removeEventListener("message", listener);
|
|
70
|
-
}
|
|
71
|
-
function getCurrentTheme() {
|
|
72
|
-
if (typeof window === "undefined" || !window.CervioUI) return null;
|
|
73
|
-
try {
|
|
74
|
-
return getCervioUI().theme.get();
|
|
75
|
-
} catch {
|
|
76
|
-
return null;
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
// src/client.ts
|
|
81
|
-
var CervioApiError = class extends Error {
|
|
82
|
-
constructor(status, code, message) {
|
|
83
|
-
super(message);
|
|
84
|
-
this.status = status;
|
|
85
|
-
this.code = code;
|
|
86
|
-
this.name = "CervioApiError";
|
|
87
|
-
}
|
|
88
|
-
};
|
|
89
|
-
function resolveApiBaseUrl(explicitBaseUrl) {
|
|
90
|
-
const explicit = explicitBaseUrl?.trim();
|
|
91
|
-
if (explicit) return explicit.replace(/\/$/, "");
|
|
92
|
-
const parentOrigin = getPluginContext()?.parentOrigin?.trim();
|
|
93
|
-
if (parentOrigin && parentOrigin !== "null") {
|
|
94
|
-
return parentOrigin.replace(/\/$/, "");
|
|
95
|
-
}
|
|
96
|
-
throw new Error(
|
|
97
|
-
"Unable to resolve the Cervio API base URL. Pass { baseUrl } explicitly, or run inside the Cervio plugin sandbox so window.__CERVIO_PLUGIN_CONTEXT__.parentOrigin is set. Do not fall back to window.location.origin."
|
|
98
|
-
);
|
|
99
|
-
}
|
|
100
|
-
async function parseJsonSafe(res) {
|
|
101
|
-
try {
|
|
102
|
-
return await res.json();
|
|
103
|
-
} catch {
|
|
104
|
-
return {};
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
function throwIfNotOk(res, body) {
|
|
108
|
-
if (res.ok) return;
|
|
109
|
-
const code = typeof body.error === "string" ? body.error : "http_error";
|
|
110
|
-
const message = typeof body.message === "string" ? body.message : res.statusText;
|
|
111
|
-
throw new CervioApiError(res.status, code, message);
|
|
112
|
-
}
|
|
113
|
-
function buildRecordsQuery(opts) {
|
|
114
|
-
const params = new URLSearchParams();
|
|
115
|
-
if (opts?.limit != null) params.set("limit", String(opts.limit));
|
|
116
|
-
if (opts?.offset != null) params.set("offset", String(opts.offset));
|
|
117
|
-
const qs = params.toString();
|
|
118
|
-
return qs ? `?${qs}` : "";
|
|
119
|
-
}
|
|
120
|
-
function createCervioClient(opts) {
|
|
121
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
122
|
-
const baseUrl = resolveApiBaseUrl(opts.baseUrl);
|
|
123
|
-
async function request(path) {
|
|
124
|
-
const res = await fetchImpl(`${baseUrl}${path}`, {
|
|
125
|
-
headers: {
|
|
126
|
-
Authorization: `Bearer ${opts.token}`,
|
|
127
|
-
Accept: "application/json"
|
|
128
|
-
}
|
|
129
|
-
});
|
|
130
|
-
const body = await parseJsonSafe(res);
|
|
131
|
-
throwIfNotOk(res, body);
|
|
132
|
-
return body;
|
|
133
|
-
}
|
|
134
|
-
return {
|
|
135
|
-
me: () => request("/api/v1/me"),
|
|
136
|
-
listEntities: () => request("/api/v1/entities"),
|
|
137
|
-
getEntity: (entityId) => request(`/api/v1/entities/${entityId}`),
|
|
138
|
-
getCapabilities: (entityId) => request(
|
|
139
|
-
`/api/v1/entities/${entityId}/capabilities`
|
|
140
|
-
),
|
|
141
|
-
listRecords: (entityId, opts2) => request(
|
|
142
|
-
`/api/v1/entities/${entityId}/records${buildRecordsQuery(opts2)}`
|
|
143
|
-
)
|
|
144
|
-
};
|
|
145
|
-
}
|
|
146
|
-
function createCervioSessionClient(opts = {}) {
|
|
147
|
-
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
148
|
-
const baseUrl = resolveApiBaseUrl(opts.baseUrl);
|
|
149
|
-
async function request(path) {
|
|
150
|
-
const res = await fetchImpl(`${baseUrl}${path}`, {
|
|
151
|
-
credentials: "include",
|
|
152
|
-
headers: { Accept: "application/json" }
|
|
153
|
-
});
|
|
154
|
-
const body = await parseJsonSafe(res);
|
|
155
|
-
throwIfNotOk(res, body);
|
|
156
|
-
return body;
|
|
157
|
-
}
|
|
158
|
-
return {
|
|
159
|
-
me: () => request("/api/v1/me"),
|
|
160
|
-
listEntities: () => request("/api/v1/entities"),
|
|
161
|
-
getEntity: (entityId) => request(`/api/v1/entities/${entityId}`),
|
|
162
|
-
getCapabilities: (entityId) => request(
|
|
163
|
-
`/api/v1/entities/${entityId}/capabilities`
|
|
164
|
-
),
|
|
165
|
-
listRecords: (entityId, opts2) => request(
|
|
166
|
-
`/api/v1/entities/${entityId}/records${buildRecordsQuery(opts2)}`
|
|
167
|
-
),
|
|
168
|
-
/** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */
|
|
169
|
-
connectionStatus: (connectionId) => request(
|
|
170
|
-
`/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/status`
|
|
171
|
-
),
|
|
172
|
-
connectionStart: (connectionId, returnTo) => {
|
|
173
|
-
const qs = returnTo ? `?return_to=${encodeURIComponent(returnTo)}` : "";
|
|
174
|
-
return request(
|
|
175
|
-
`/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/start${qs}`
|
|
176
|
-
);
|
|
177
|
-
},
|
|
178
|
-
connectionProxy: async (connectionId, input) => {
|
|
179
|
-
const res = await fetchImpl(
|
|
180
|
-
`${baseUrl}/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/proxy`,
|
|
181
|
-
{
|
|
182
|
-
method: "POST",
|
|
183
|
-
credentials: "include",
|
|
184
|
-
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
|
185
|
-
body: JSON.stringify(input)
|
|
186
|
-
}
|
|
187
|
-
);
|
|
188
|
-
const body = await parseJsonSafe(res);
|
|
189
|
-
throwIfNotOk(res, body);
|
|
190
|
-
return body;
|
|
191
|
-
}
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
async function ensureExternalConnection(api, connectionId, returnTo) {
|
|
195
|
-
const st = await api.connectionStatus(connectionId);
|
|
196
|
-
if (st.connected) return st;
|
|
197
|
-
const start = await api.connectionStart(connectionId, returnTo);
|
|
198
|
-
if (!start.authorizeUrl) {
|
|
199
|
-
throw new CervioApiError(501, "start_failed", start.message || "OAuth start failed");
|
|
200
|
-
}
|
|
201
|
-
if (typeof window !== "undefined" && typeof window.__cervioOpenExternalAuth === "function") {
|
|
202
|
-
window.__cervioOpenExternalAuth(start.authorizeUrl);
|
|
203
|
-
} else if (typeof window !== "undefined") {
|
|
204
|
-
window.top.location.href = start.authorizeUrl;
|
|
205
|
-
}
|
|
206
|
-
return null;
|
|
207
|
-
}
|
|
208
|
-
var DEFAULT_PAGE = 500;
|
|
209
|
-
async function countVisibleRecords(api, entityId, pageSize = DEFAULT_PAGE) {
|
|
210
|
-
let total = 0;
|
|
211
|
-
let offset = 0;
|
|
212
|
-
const maxRows = 2e5;
|
|
213
|
-
for (; ; ) {
|
|
214
|
-
const { records } = await api.listRecords(entityId, { limit: pageSize, offset });
|
|
215
|
-
total += records.length;
|
|
216
|
-
if (records.length < pageSize) break;
|
|
217
|
-
offset += pageSize;
|
|
218
|
-
if (offset >= maxRows) break;
|
|
219
|
-
}
|
|
220
|
-
return total;
|
|
221
|
-
}
|
|
222
|
-
function findEntityByName(entities, technicalName) {
|
|
223
|
-
const n = technicalName.toLowerCase();
|
|
224
|
-
return entities.find((e) => e.name.toLowerCase() === n);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
// src/i18n.ts
|
|
228
|
-
var DEFAULT_LOCALE_TAGS = {
|
|
229
|
-
it: "it-IT",
|
|
230
|
-
en: "en-GB",
|
|
231
|
-
es: "es-ES",
|
|
232
|
-
fr: "fr-FR",
|
|
233
|
-
de: "de-DE"
|
|
234
|
-
};
|
|
235
|
-
function resolvePluginLocale(opts) {
|
|
236
|
-
const ctx = getPluginContext();
|
|
237
|
-
const hostLocale = ctx?.locale ?? ctx?.userLocale;
|
|
238
|
-
const runtimeAvailable = ctx?.runtimeSettings?.availableLocales;
|
|
239
|
-
const runtimeAllowed = Array.isArray(runtimeAvailable) && runtimeAvailable.length > 0 ? runtimeAvailable : null;
|
|
240
|
-
if (hostLocale && opts.availableLocales.includes(hostLocale) && (!runtimeAllowed || runtimeAllowed.includes(hostLocale))) {
|
|
241
|
-
return hostLocale;
|
|
242
|
-
}
|
|
243
|
-
const fallback = ctx?.runtimeSettings?.fallbackLocale;
|
|
244
|
-
if (fallback && opts.availableLocales.includes(fallback)) return fallback;
|
|
245
|
-
return opts.defaultLocale;
|
|
246
|
-
}
|
|
247
|
-
function getNestedValue(obj, path) {
|
|
248
|
-
return path.split(".").reduce((acc, key) => {
|
|
249
|
-
if (acc && typeof acc === "object" && key in acc) {
|
|
250
|
-
return acc[key];
|
|
251
|
-
}
|
|
252
|
-
return void 0;
|
|
253
|
-
}, obj);
|
|
254
|
-
}
|
|
255
|
-
function createI18n(opts) {
|
|
256
|
-
const availableLocales = opts.availableLocales ?? Object.keys(opts.messages);
|
|
257
|
-
const locale = resolvePluginLocale({ availableLocales, defaultLocale: opts.defaultLocale });
|
|
258
|
-
const dict = opts.messages[locale] ?? opts.messages[opts.defaultLocale] ?? {};
|
|
259
|
-
const localeTags = { ...DEFAULT_LOCALE_TAGS, ...opts.localeTags };
|
|
260
|
-
function t(key, vars) {
|
|
261
|
-
const raw = getNestedValue(dict, key);
|
|
262
|
-
let out = typeof raw === "string" ? raw : key;
|
|
263
|
-
if (vars) {
|
|
264
|
-
for (const [k, v] of Object.entries(vars)) {
|
|
265
|
-
out = out.replaceAll(`{${k}}`, String(v));
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
return out;
|
|
269
|
-
}
|
|
270
|
-
function localeTag(l = locale) {
|
|
271
|
-
return localeTags[l] ?? l;
|
|
272
|
-
}
|
|
273
|
-
return { locale, availableLocales, t, localeTag };
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
exports.CERVIO_UI_API_VERSION = CERVIO_UI_API_VERSION;
|
|
277
|
-
exports.CervioApiError = CervioApiError;
|
|
278
|
-
exports.countVisibleRecords = countVisibleRecords;
|
|
279
|
-
exports.createCervioClient = createCervioClient;
|
|
280
|
-
exports.createCervioSessionClient = createCervioSessionClient;
|
|
281
|
-
exports.createI18n = createI18n;
|
|
282
|
-
exports.ensureExternalConnection = ensureExternalConnection;
|
|
283
|
-
exports.findEntityByName = findEntityByName;
|
|
284
|
-
exports.getCervioUI = getCervioUI;
|
|
285
|
-
exports.getCurrentTheme = getCurrentTheme;
|
|
286
|
-
exports.getPluginContext = getPluginContext;
|
|
287
|
-
exports.getTaskPluginContext = getTaskPluginContext;
|
|
288
|
-
exports.isCervioUIAvailable = isCervioUIAvailable;
|
|
289
|
-
exports.isInsideCervioSandbox = isInsideCervioSandbox;
|
|
290
|
-
exports.onThemeChange = onThemeChange;
|
|
291
|
-
exports.openExternalAuth = openExternalAuth;
|
|
292
|
-
exports.resolveApiBaseUrl = resolveApiBaseUrl;
|
|
293
|
-
exports.resolvePluginLocale = resolvePluginLocale;
|
|
294
|
-
exports.setTaskDraft = setTaskDraft;
|
|
295
|
-
exports.submitTaskOutcome = submitTaskOutcome;
|
|
296
|
-
//# sourceMappingURL=index.cjs.map
|
|
297
|
-
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cervio-ui.ts","../src/context.ts","../src/task-context.ts","../src/theme.ts","../src/client.ts","../src/i18n.ts"],"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A,EAAA,SAAS,SAAA,CAAU,IAAY,MAAA,EAAgB;AAC7C,IAAA,OAAO,UAAA,CAAW,CAAC,CAAA,IAAK,CAAA;AAAA,EAC1B;AAEA,EAAA,OAAO,EAAE,MAAA,EAAQ,gBAAA,EAAkB,CAAA,EAAG,SAAA,EAAU;AAClD","file":"index.cjs","sourcesContent":["/**\n * Publishable typed client mirroring `window.CervioUI` injected by the Cervio host.\n * Docs: https://docs.cervio.app/docs/plugins/ui (Admin Components = catalog + try-it only).\n *\n * `CERVIO_UI_API_VERSION` tracks the host `window.CervioUI.apiVersion` wire\n * contract (additive namespaces may ship in a package minor without bumping it).\n */\n\nexport const CERVIO_UI_API_VERSION = '1.0.0' as const\n\nexport type CervioUiToastType = 'success' | 'error' | 'warning' | 'info'\nexport type CervioUiDialogVariant = 'default' | 'destructive'\nexport type CervioUiFrameSize = 'sm' | 'md' | 'lg' | 'full'\n\nexport interface CervioUiSelectOption {\n value: string\n label: string\n}\n\nexport interface CervioUiToastOptions {\n type?: CervioUiToastType\n message: string\n}\n\nexport interface CervioUiConfirmOptions {\n title: string\n description: string\n confirmLabel?: string\n cancelLabel?: string\n variant?: CervioUiDialogVariant\n}\n\nexport interface CervioUiAlertOptions {\n title: string\n description: string\n okLabel?: string\n}\n\nexport interface CervioUiFrameOpenOptions {\n title?: string\n size?: CervioUiFrameSize\n showClose?: boolean\n /**\n * Optional body height in px (120–900) for `dialog.surface`.\n * Host sizes the dialog to content; omit to let the surface report via `update`.\n */\n height?: number\n}\n\nexport interface CervioUiSurfaceOpenOptions extends CervioUiFrameOpenOptions {\n /** Plain JSON forwarded to `dist/surface.html` on open (max ~64KB). */\n params?: unknown\n}\n\nexport interface CervioUiSelectOpenOptions {\n options: CervioUiSelectOption[]\n value?: string\n searchable?: boolean\n placeholder?: string\n emptyText?: string\n}\n\nexport interface CervioUiFrameSlot {\n left: number\n top: number\n width: number\n height: number\n headerHeight: number\n}\n\nexport interface CervioUiThemeSnapshot {\n tokens: Record<string, string>\n colorScheme: 'dark' | 'light'\n}\n\n/** Host locale/date/number preferences pushed via `__cervioPluginFormat`; see `CervioUI.format.*`. */\nexport interface CervioUiFormatSnapshot {\n /** BCP47 tag (e.g. `it-IT`). */\n locale: string\n dateFormat: 'dd/MM/yyyy' | 'MM/dd/yyyy' | 'yyyy-MM-dd'\n decimalSeparator: ',' | '.'\n thousandsSeparator: string\n /** IANA timezone (e.g. `Europe/Rome`). */\n timeZone: string\n /** System UI locale (`NEXT_LOCALE`). */\n uiLocale: 'it' | 'en'\n}\n\n/** Opaque file metadata: the `File`/blob never crosses postMessage. */\nexport interface CervioUiFileMeta {\n id: string\n name: string\n mime: string\n size: number\n}\n\n/** `{ id, label }` action used by `actionSheet.open`. */\nexport interface CervioUiActionSheetAction {\n id: string\n label: string\n variant?: CervioUiDialogVariant\n}\n\n/** Wider variant set accepted by `sheet.open` (mirrors button variants). */\nexport interface CervioUiSheetAction {\n id: string\n label: string\n variant?: 'default' | 'destructive' | 'outline' | 'secondary' | 'ghost'\n}\n\n/** `{ value, label, subtitle? }` option resolved by domain pickers. */\nexport interface CervioUiDomainPickOption {\n value: string\n label: string\n subtitle?: string\n}\n\nexport interface CervioUiActionSheetOpenOptions {\n title?: string\n actions: CervioUiActionSheetAction[]\n cancelLabel?: string\n}\n\nexport interface CervioUiFilesPickOptions {\n /** MIME types / extensions, e.g. `['image/*', '.pdf']`. Omit to allow the default document types. */\n accept?: string[]\n multiple?: boolean\n /** Default 20. */\n maxFiles?: number\n /** Default: host document upload limit (50 MB). */\n maxBytes?: number\n title?: string\n dropHint?: string\n pickLabel?: string\n}\n\nexport interface CervioUiFilesCaptureOptions {\n facing?: 'environment' | 'user'\n title?: string\n}\n\nexport interface CervioUiFilesPickResult {\n files: CervioUiFileMeta[]\n}\n\nexport interface CervioUiFilesUploadOptions {\n entityId: string\n recordId: string\n /** Ids returned by `files.pick` / `files.capture` - consumed on upload (removed from the host's in-memory store). */\n fileIds: string[]\n title?: string\n fileName?: string\n}\n\nexport type CervioUiFilesUploadResult =\n | { ok: true; documents: unknown[] }\n | { ok: false; error: string }\n\nexport interface CervioUiProgressShowOptions {\n /** Plugin-chosen id; reuse it with `update` / `hide`. */\n id: string\n label?: string\n /** 0-100; omit for an indeterminate bar. */\n value?: number\n}\n\nexport interface CervioUiProgressUpdateOptions {\n id: string\n label?: string\n value?: number\n}\n\nexport interface CervioUiDateOpenOptions {\n title?: string\n /** ISO date (`yyyy-MM-dd`) or datetime string. */\n value?: string\n mode?: 'date' | 'datetime'\n min?: string\n max?: string\n /** Default true. */\n clearable?: boolean\n}\n\nexport interface CervioUiRecordPickOptions {\n title?: string\n entityId?: string\n /** Resolved by exact match against entity name/label when `entityId` is omitted. */\n entityName?: string\n value?: string\n /** Default true. */\n searchable?: boolean\n}\n\nexport interface CervioUiEntityPickOptions {\n title?: string\n value?: string\n}\n\nexport interface CervioUiUserPickOptions {\n title?: string\n value?: string\n}\n\nexport interface CervioUiGroupPickOptions {\n title?: string\n value?: string\n}\n\nexport interface CervioUiSheetOpenOptions {\n title?: string\n description?: string\n actions: CervioUiSheetAction[]\n}\n\n/** At least one of `title`, `text`, `url` is required. */\nexport interface CervioUiShareOpenOptions {\n title?: string\n text?: string\n /** Same-origin path starting with `/` (resolved to an absolute URL by the host). */\n url?: string\n}\n\nexport type CervioUiShareResult = { ok: boolean; fallback?: 'clipboard' }\n\n/** Exactly one of `fileId` / `url` is required. */\nexport interface CervioUiPrintOpenOptions {\n fileId?: string\n /** Same-origin path starting with `/`. */\n url?: string\n}\n\n/** Exactly one of `fileId` / `url` is required. */\nexport interface CervioUiExportDownloadOptions {\n fileId?: string\n /** Same-origin path starting with `/`. */\n url?: string\n fileName?: string\n}\n\nexport interface CervioUiNavConfirmLeaveOptions {\n enabled: boolean\n message?: string\n}\n\nexport interface CervioUiCameraOpenOptions {\n title?: string\n facing?: 'environment' | 'user'\n}\n\nexport interface CervioUiBarcodeScanOptions {\n title?: string\n}\n\nexport type CervioUiBarcodeScanResult = { value: string; format?: string } | null\n\nexport interface CervioUiLocationPickOptions {\n title?: string\n}\n\nexport interface CervioUiTaskOutcome {\n value: string\n label: string\n}\n\nexport interface CervioUiTaskSummary {\n id: string\n status: string\n title: string\n outcomes: CervioUiTaskOutcome[]\n entityDataId: string | null\n canComplete: boolean\n blockReason: string | null\n requiresFullView: boolean\n}\n\nexport interface CervioUiTaskListItem {\n id: string\n title: string\n outcomes: CervioUiTaskOutcome[]\n status: string\n}\n\nexport interface CervioUiTaskCompleteOptions {\n taskId: string\n outcomeKey: string\n response?: Record<string, unknown>\n}\n\nexport interface CervioUiTaskCompleteResult {\n taskCompleted: boolean\n}\n\nexport interface CervioUiTaskOpenResult {\n completed: boolean\n outcomeKey?: string\n}\n\nexport type CervioUiLocationResult = { lat: number; lng: number; accuracy?: number } | null\n\nexport interface CervioUI {\n apiVersion: typeof CERVIO_UI_API_VERSION\n capabilities(): Promise<string[]>\n toast(opts: CervioUiToastOptions): Promise<{ ok: true }>\n dialog: {\n confirm(opts: CervioUiConfirmOptions): Promise<boolean>\n alert(opts: CervioUiAlertOptions): Promise<true>\n frame: {\n /** Sync cached slot (null if host has not pushed dialog.frame.slots yet). */\n slot?(size?: 'sm' | 'md' | 'lg' | 'full'): CervioUiFrameSlot | null\n open(opts?: CervioUiFrameOpenOptions): Promise<{ open: true; slot: CervioUiFrameSlot }>\n update(opts: { title?: string }): Promise<{ ok: true }>\n close(): Promise<{ ok: true }>\n }\n /** Recommended for custom modals: host Dialog + body from dist/surface.html. */\n surface: {\n open(opts?: CervioUiSurfaceOpenOptions): Promise<{ open: true }>\n update(opts: { title?: string; height?: number }): Promise<{ ok: true }>\n close(): Promise<{ ok: true }>\n /** Relay plain JSON to the other iframe (page ↔ surface). */\n post(data: unknown): Promise<{ ok: true }>\n }\n }\n backdrop: {\n set(open: boolean): Promise<{ open: boolean }>\n }\n select: {\n open(opts: CervioUiSelectOpenOptions): Promise<string | null>\n }\n combobox: {\n open(opts: CervioUiSelectOpenOptions): Promise<string | null>\n }\n /** Last host theme push (null until first `__cervioPluginTheme` message). Applied automatically by inject script. */\n theme: {\n get(): CervioUiThemeSnapshot | null\n }\n /** Host locale/date/number prefs (`__cervioPluginFormat`). `date`/`dateTime`/`number`/`currency` format client-side, no RPC. */\n format: {\n /** Last host format push (seeded from `__CERVIO_PLUGIN_CONTEXT__.format`). */\n get(): CervioUiFormatSnapshot\n date(value: unknown): string\n dateTime(value: unknown): string\n number(value: unknown, opts?: { maxDecimals?: number }): string\n currency(value: unknown, currency?: string): string\n }\n /** Host bottom sheet with a short list of tappable actions. */\n actionSheet: {\n open(opts: CervioUiActionSheetOpenOptions): Promise<string | null>\n }\n /** Host file picker (pick/capture) and upload to an entity record; blobs never cross postMessage. */\n files: {\n pick(opts?: CervioUiFilesPickOptions): Promise<CervioUiFilesPickResult | null>\n capture(opts?: CervioUiFilesCaptureOptions): Promise<CervioUiFilesPickResult | null>\n upload(opts: CervioUiFilesUploadOptions): Promise<CervioUiFilesUploadResult>\n /** Experimental: image/PDF preview dialog for a previously picked/uploaded file. */\n preview(opts: { fileId: string }): Promise<{ ok: true }>\n /** Experimental: v1 pass-through - resolves the same fileId, no pixel manipulation yet. */\n crop(opts: { fileId: string }): Promise<string | null>\n }\n /** Host top overlay stack of determinate/indeterminate progress bars keyed by plugin-chosen id. */\n progress: {\n show(opts: CervioUiProgressShowOptions): Promise<{ ok: true }>\n update(opts: CervioUiProgressUpdateOptions): Promise<{ ok: true }>\n hide(id: string): Promise<{ ok: true }>\n }\n date: {\n /** Host date / datetime picker; ISO in, ISO out. */\n open(opts?: CervioUiDateOpenOptions): Promise<string | null>\n }\n record: {\n /** Host searchable picker over records of a given entity. */\n pick(opts?: CervioUiRecordPickOptions): Promise<string | null>\n }\n entity: {\n /** Host searchable picker over entity types visible to the caller. */\n pick(opts?: CervioUiEntityPickOptions): Promise<string | null>\n }\n user: {\n /** Host searchable picker over organization users. */\n pick(opts?: CervioUiUserPickOptions): Promise<string | null>\n }\n group: {\n /** Host searchable picker over organization groups. */\n pick(opts?: CervioUiGroupPickOptions): Promise<string | null>\n }\n /** Host bottom sheet with title, description and a richer action variant set than `actionSheet`. */\n sheet: {\n open(opts: CervioUiSheetOpenOptions): Promise<string | null>\n }\n /** Host-mediated clipboard write (sandboxed iframes cannot access the Clipboard API directly). */\n clipboard: {\n write(text: string): Promise<{ ok: boolean }>\n }\n /** Host Web Share (falls back to clipboard copy when unsupported). */\n share: {\n open(opts: CervioUiShareOpenOptions): Promise<CervioUiShareResult>\n }\n /** Host-driven print (fileId or same-origin url). */\n print: {\n open(opts: CervioUiPrintOpenOptions): Promise<{ ok: true }>\n }\n /** Host-driven file download (fileId or same-origin url). */\n export: {\n download(opts: CervioUiExportDownloadOptions): Promise<{ ok: true }>\n }\n /** Plugin-controlled \"leave without saving?\" confirmation on shell navigation / tab close. */\n nav: {\n confirmLeave(opts: CervioUiNavConfirmLeaveOptions): Promise<{ ok: true }>\n }\n /** Experimental: host camera capture (getUserMedia), resolves a single photo file. */\n camera: {\n open(opts?: CervioUiCameraOpenOptions): Promise<CervioUiFileMeta | null>\n }\n /** Experimental: host barcode/QR scan; rejects with `code: 'barcode_error'` on scan failure. */\n barcode: {\n scan(opts?: CervioUiBarcodeScanOptions): Promise<CervioUiBarcodeScanResult>\n }\n /** Experimental: host geolocation lookup on explicit user action. */\n location: {\n pick(opts?: CervioUiLocationPickOptions): Promise<CervioUiLocationResult>\n }\n /**\n * Contextual workflow tasks for route plugins (assignee-gated complete).\n * Rejects with `{ code, message }` for Unauthorized | Forbidden | task_not_open |\n * already_responded | reassigned | workflow_not_active | invalid_outcome |\n * variable_required | document_upload_required | record_link_required | in_flight.\n */\n task: {\n get(opts: { taskId: string }): Promise<CervioUiTaskSummary>\n complete(opts: CervioUiTaskCompleteOptions): Promise<CervioUiTaskCompleteResult>\n open(opts: { taskId: string }): Promise<CervioUiTaskOpenResult>\n listForRecord(opts: { entityDataId: string }): Promise<CervioUiTaskListItem[]>\n }\n}\n\ndeclare global {\n interface Window {\n CervioUI?: CervioUI\n }\n}\n\n/**\n * Returns `window.CervioUI`, throwing when it is not present (e.g. running\n * outside the Cervio sandbox host, or in a plain browser tab for local dev).\n */\nexport function getCervioUI(): CervioUI {\n if (typeof window === 'undefined' || !window.CervioUI) {\n throw new Error(\n 'CervioUI is not available. Route plugins must run inside the Cervio sandbox host.',\n )\n }\n return window.CervioUI\n}\n\n/** True when the host has injected `window.CervioUI` (srcDoc sandbox). */\nexport function isCervioUIAvailable(): boolean {\n return typeof window !== 'undefined' && !!window.CervioUI\n}\n\nexport type CervioUiFrameMetricsEvent = {\n __cervioUI: 1\n event: 'dialog.frame.metrics'\n open: boolean\n title?: string\n size?: CervioUiFrameSize\n showClose?: boolean\n slot?: CervioUiFrameSlot\n}\n\nexport type CervioUiFrameClosedEvent = {\n __cervioUI: 1\n event: 'dialog.frame.closed'\n reason: 'host' | 'plugin' | 'escape'\n}\n\nexport type CervioUiSurfaceOpenedEvent = {\n __cervioUI: 1\n event: 'dialog.surface.opened'\n params?: unknown\n}\n\nexport type CervioUiSurfaceMessageEvent = {\n __cervioUI: 1\n event: 'dialog.surface.message'\n data: unknown\n from: 'page' | 'surface'\n}\n\nexport type CervioUiSurfaceClosedEvent = {\n __cervioUI: 1\n event: 'dialog.surface.closed'\n reason: 'host' | 'plugin' | 'escape'\n}\n\nexport type CervioUiHostEvent =\n | CervioUiFrameMetricsEvent\n | CervioUiFrameClosedEvent\n | CervioUiSurfaceOpenedEvent\n | CervioUiSurfaceMessageEvent\n | CervioUiSurfaceClosedEvent\n","/**\n * Typed access to `window.__CERVIO_PLUGIN_CONTEXT__`, the boot payload the\n * Cervio host injects into every route plugin `srcDoc` iframe.\n *\n * Docs: https://docs.cervio.app/docs/authoring (\"Auth inside the iframe\", \"Plugin i18n /\n * locale\"). Field shape is set by `components/plugins/plugin-route-sandbox-host.tsx`.\n */\n\nexport interface CervioPluginRuntimeSettings {\n /** Locales this plugin install may use (Admin → Plugins → Impostazioni). */\n availableLocales?: string[]\n /** Used when the host locale is not in `availableLocales`. */\n fallbackLocale?: string\n [key: string]: unknown\n}\n\nexport interface CervioPluginContext {\n /** Route slug the plugin was mounted under. */\n routeSlug?: string\n /** Per-menu-item config attached via `menu_items.plugin_context`. */\n pluginContext?: Record<string, unknown> | null\n previewMode?: boolean\n /** Logged-in Cervio UI locale (`NEXT_LOCALE`): `'it' | 'en'`. */\n locale?: string\n /** Alias of `locale` kept for backward compatibility with early bootstraps. */\n userLocale?: string\n mountedAt?: string\n /**\n * Real app origin - always set by the host. Use this for API base URLs.\n * Never use `window.location.origin`: in sandboxed `srcDoc` iframes it\n * frequently serializes as the literal string `\"null\"`.\n */\n parentOrigin?: string\n /** Parent page pathname (the iframe's own `location` is opaque). */\n parentPath?: string\n /** Parent page search string, including leading `?` when present. */\n parentSearch?: string\n /** Full parent `href`, for deep-linking. */\n parentHref?: string\n pluginVersion?: string | null\n pluginArtifactSha256?: string | null\n pluginKey?: string | null\n /** Whether the host is caching this route's `srcDoc` across soft navigations. */\n artifactCacheEnabled?: boolean\n runtimeSettings?: CervioPluginRuntimeSettings\n /** Present only inside `dist/surface.html` (dialog.surface body iframe). */\n cervioSurface?: boolean\n [key: string]: unknown\n}\n\ndeclare global {\n interface Window {\n __CERVIO_PLUGIN_CONTEXT__?: CervioPluginContext\n /** Host-mediated top-level navigation (OAuth consent, cross-plugin deep links). */\n __cervioOpenExternalAuth?: (url: string) => boolean\n /** Same-route query/path sync without reloading the iframe (shareable deep links). */\n __cervioSyncParentUrl?: (url: string, replace?: boolean) => boolean\n }\n}\n\n/** Returns the host boot payload, or `null` outside the Cervio sandbox. */\nexport function getPluginContext(): CervioPluginContext | null {\n if (typeof window === 'undefined') return null\n return window.__CERVIO_PLUGIN_CONTEXT__ ?? null\n}\n\n/** True when running inside a Cervio route plugin sandbox iframe. */\nexport function isInsideCervioSandbox(): boolean {\n return getPluginContext() != null\n}\n\n/**\n * Navigate the real app window (top-level). Required for OAuth consent and\n * cross-plugin deep links: the sandboxed iframe cannot navigate `window.top`.\n */\nexport function openExternalAuth(url: string): boolean {\n if (typeof window === 'undefined' || typeof window.__cervioOpenExternalAuth !== 'function') {\n return false\n }\n return window.__cervioOpenExternalAuth(url)\n}\n","/**\n * Typed access to the task-plugin boot payload + submit/draft bridge, injected\n * by `components/plugins/task-plugin-sandbox-host.tsx` when a human-task node\n * uses `taskUiMode: 'plugin'`. Shares the `window.__CERVIO_PLUGIN_CONTEXT__`\n * global with route plugins (never both on one page, so no collision), but\n * with a different shape — use these helpers rather than `getPluginContext()`.\n */\n\nexport interface CervioTaskOutcome {\n value: string\n label: string\n}\n\nexport interface CervioTaskPluginContextData {\n taskId: string\n workflowInstanceId: string\n entityDataId: string | null\n outcomes: CervioTaskOutcome[]\n /** Allowlisted subset of workflow instance variables declared by the node's exposedVariables config — never the full workflow_instances.context. */\n instanceVariables: Record<string, unknown>\n /**\n * The task's last `setTaskDraft()` payload (`workflow_tasks.draft_response_payload`),\n * or `null` when none was saved yet. Only one `TaskPluginSandboxHost` is ever\n * mounted at a time (compact XOR expanded modal) — switching between them\n * unmounts/remounts the plugin's iframe, discarding its in-memory state. A\n * plugin that seeds its editable fields from extraction data on every mount\n * (rather than from this draft first) silently reverts any edit made just\n * before that remount, once its own re-seed reaches the host. Read this on\n * mount and prefer it over re-deriving initial values from scratch.\n */\n draft: Record<string, unknown> | null\n}\n\nexport interface CervioTaskPluginBoot {\n pluginType: 'task' | 'task_form'\n /** UI hint only: true when this is a task_form plugin on an open task the viewer may complete. Server re-checks independently on every submit. */\n canSubmit: boolean\n pluginContext: CervioTaskPluginContextData\n}\n\nexport interface CervioTaskSubmitResult {\n ok: boolean\n taskCompleted?: boolean\n error?: string\n}\n\nexport interface CervioTaskDraftResult {\n ok: boolean\n error?: string\n}\n\ndeclare global {\n interface Window {\n __cervioTaskSetDraft?: (data: unknown) => Promise<CervioTaskDraftResult>\n __cervioTaskSubmit?: (outcomeKey: string, data?: unknown) => Promise<CervioTaskSubmitResult>\n }\n}\n\n/** Returns the task boot payload, or `null` outside a task-plugin sandbox. */\nexport function getTaskPluginContext(): CervioTaskPluginBoot | null {\n if (typeof window === 'undefined') return null\n const raw = window.__CERVIO_PLUGIN_CONTEXT__ as unknown as Partial<CervioTaskPluginBoot> | undefined\n if (!raw || typeof raw !== 'object' || typeof raw.pluginType !== 'string') return null\n return raw as CervioTaskPluginBoot\n}\n\n/** Incremental autosave (no completion). No-op outside a task-plugin sandbox. */\nexport async function setTaskDraft(data: Record<string, unknown>): Promise<CervioTaskDraftResult> {\n if (typeof window === 'undefined' || typeof window.__cervioTaskSetDraft !== 'function') {\n return { ok: false, error: 'not_available' }\n }\n return window.__cervioTaskSetDraft(data)\n}\n\n/**\n * Completes the task with the given outcome. Only works for `task_form`\n * plugins — the host rejects the call server-side for plain `task` plugins.\n */\nexport async function submitTaskOutcome(\n outcomeKey: string,\n data?: Record<string, unknown>,\n): Promise<CervioTaskSubmitResult> {\n if (typeof window === 'undefined' || typeof window.__cervioTaskSubmit !== 'function') {\n return { ok: false, error: 'not_available' }\n }\n return window.__cervioTaskSubmit(outcomeKey, data)\n}\n","/**\n * Typed wrapper around the host's `__cervioPluginTheme` postMessage push.\n * The CervioUI inject script already applies host tokens to `document`\n * automatically (`var(--background)`, etc.) - use this only when your plugin\n * needs to *react* to a theme change in JS (e.g. re-render a canvas/chart).\n */\n\nimport { getCervioUI } from './cervio-ui'\n\nexport type CervioColorScheme = 'dark' | 'light'\n\nexport interface CervioHostThemeMessage {\n __cervioPluginTheme: 1\n tokens: Record<string, string>\n colorScheme: CervioColorScheme\n}\n\nexport interface CervioThemeSnapshot {\n tokens: Record<string, string>\n colorScheme: CervioColorScheme\n}\n\nexport type CervioThemeChangeHandler = (theme: CervioThemeSnapshot) => void\n\nfunction isHostThemeMessage(data: unknown): data is CervioHostThemeMessage {\n return (\n !!data &&\n typeof data === 'object' &&\n (data as { __cervioPluginTheme?: unknown }).__cervioPluginTheme === 1\n )\n}\n\n/**\n * Subscribe to host theme pushes. Returns an unsubscribe function.\n * Fires immediately with the last known theme (from `CervioUI.theme.get()`)\n * when available, then on every subsequent host theme change.\n */\nexport function onThemeChange(handler: CervioThemeChangeHandler): () => void {\n if (typeof window === 'undefined') return () => {}\n\n const current = getCurrentTheme()\n if (current) handler(current)\n\n const listener = (event: MessageEvent) => {\n if (!isHostThemeMessage(event.data)) return\n handler({\n tokens: event.data.tokens ?? {},\n colorScheme: event.data.colorScheme === 'dark' ? 'dark' : 'light',\n })\n }\n window.addEventListener('message', listener)\n return () => window.removeEventListener('message', listener)\n}\n\n/** Last theme snapshot applied by the CervioUI inject script, if any. */\nexport function getCurrentTheme(): CervioThemeSnapshot | null {\n if (typeof window === 'undefined' || !window.CervioUI) return null\n try {\n return getCervioUI().theme.get()\n } catch {\n return null\n }\n}\n","/**\n * Typed fetch wrapper around the Cervio v1 REST API (`/api/v1/*`) for route\n * plugins and external scripts.\n *\n * Two flavors:\n * - `createCervioClient` - Bearer token (PAT / OAuth2 access token).\n * - `createCervioSessionClient` - same-origin session cookies (typical when\n * running inside the Cervio app shell iframe).\n *\n * Both resolve a missing `baseUrl` from `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`\n * - **never** from `window.location.origin`, which frequently serializes as\n * the literal string `\"null\"` inside a sandboxed `srcDoc` iframe.\n */\n\nimport { getPluginContext } from './context'\n\nexport interface Identity {\n user_id: string\n organization_id: string\n auth_method: 'pat' | 'oauth2' | 'supabase_jwt' | 'session'\n}\n\nexport interface Entity {\n id: string\n name: string\n label: string\n description: string | null\n document_management_enabled: boolean\n}\n\nexport interface EntityCapabilities {\n can_read: boolean\n can_create: boolean\n can_update: boolean\n can_delete: boolean\n can_export: boolean\n}\n\nexport interface EntityRecord {\n id: string\n entity_id: string\n data: Record<string, unknown>\n}\n\nexport class CervioApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly code: string,\n message: string,\n ) {\n super(message)\n this.name = 'CervioApiError'\n }\n}\n\n/**\n * Resolve an API base URL: explicit value wins, otherwise\n * `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`. Throws rather than silently\n * falling back to `location.origin` (which breaks inside `srcDoc` sandboxes).\n */\nexport function resolveApiBaseUrl(explicitBaseUrl?: string): string {\n const explicit = explicitBaseUrl?.trim()\n if (explicit) return explicit.replace(/\\/$/, '')\n\n const parentOrigin = getPluginContext()?.parentOrigin?.trim()\n if (parentOrigin && parentOrigin !== 'null') {\n return parentOrigin.replace(/\\/$/, '')\n }\n\n throw new Error(\n 'Unable to resolve the Cervio API base URL. Pass { baseUrl } explicitly, or run ' +\n 'inside the Cervio plugin sandbox so window.__CERVIO_PLUGIN_CONTEXT__.parentOrigin ' +\n 'is set. Do not fall back to window.location.origin.',\n )\n}\n\nasync function parseJsonSafe(res: Response): Promise<Record<string, unknown>> {\n try {\n return (await res.json()) as Record<string, unknown>\n } catch {\n return {}\n }\n}\n\nfunction throwIfNotOk(res: Response, body: Record<string, unknown>): void {\n if (res.ok) return\n const code = typeof body.error === 'string' ? body.error : 'http_error'\n const message = typeof body.message === 'string' ? body.message : res.statusText\n throw new CervioApiError(res.status, code, message)\n}\n\nexport type CervioClientOptions = {\n /** Defaults to `__CERVIO_PLUGIN_CONTEXT__.parentOrigin` when omitted. */\n baseUrl?: string\n /** PAT (`cpat_…`) or OAuth2 access token. Read-only on writes for PAT. */\n token: string\n fetchImpl?: typeof fetch\n}\n\nexport type CervioSessionClientOptions = {\n /** Defaults to `__CERVIO_PLUGIN_CONTEXT__.parentOrigin` when omitted. */\n baseUrl?: string\n fetchImpl?: typeof fetch\n}\n\nexport type ExternalConnectionStatus = {\n connection_id: string\n provider: string\n connector_key: string\n configured: boolean\n connected: boolean\n account_email: string | null\n scopes: string[]\n allowed_apis: unknown\n /** True when user has separate \"product\" (Profilo) connection for same builtin provider, but not this plugin's own. UX hint only, not auto-usable. */\n has_product_connection?: boolean\n}\n\nexport type ExternalProxyInput = {\n /** Required when the manifest requirement allows more than one API host. */\n host?: string\n method: string\n path: string\n query?: Record<string, string>\n headers?: Record<string, string>\n body?: unknown\n}\n\nfunction buildRecordsQuery(opts?: { limit?: number; offset?: number }): string {\n const params = new URLSearchParams()\n if (opts?.limit != null) params.set('limit', String(opts.limit))\n if (opts?.offset != null) params.set('offset', String(opts.offset))\n const qs = params.toString()\n return qs ? `?${qs}` : ''\n}\n\n/** Bearer-authenticated client (PAT / OAuth2 access token). */\nexport function createCervioClient(opts: CervioClientOptions) {\n const fetchImpl = opts.fetchImpl ?? fetch\n const baseUrl = resolveApiBaseUrl(opts.baseUrl)\n\n async function request<T>(path: string): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n headers: {\n Authorization: `Bearer ${opts.token}`,\n Accept: 'application/json',\n },\n })\n const body = await parseJsonSafe(res)\n throwIfNotOk(res, body)\n return body as T\n }\n\n return {\n me: () => request<Identity>('/api/v1/me'),\n listEntities: () => request<{ entities: Entity[] }>('/api/v1/entities'),\n getEntity: (entityId: string) => request<{ entity: Entity }>(`/api/v1/entities/${entityId}`),\n getCapabilities: (entityId: string) =>\n request<{ entity_id: string; capabilities: EntityCapabilities }>(\n `/api/v1/entities/${entityId}/capabilities`,\n ),\n listRecords: (entityId: string, opts?: { limit?: number; offset?: number }) =>\n request<{ records: EntityRecord[] }>(\n `/api/v1/entities/${entityId}/records${buildRecordsQuery(opts)}`,\n ),\n }\n}\n\nexport type CervioClient = ReturnType<typeof createCervioClient>\n\n/** Same-origin session cookie auth (typical inside the Cervio shell iframe). */\nexport function createCervioSessionClient(opts: CervioSessionClientOptions = {}) {\n const fetchImpl = opts.fetchImpl ?? fetch\n const baseUrl = resolveApiBaseUrl(opts.baseUrl)\n\n async function request<T>(path: string): Promise<T> {\n const res = await fetchImpl(`${baseUrl}${path}`, {\n credentials: 'include',\n headers: { Accept: 'application/json' },\n })\n const body = await parseJsonSafe(res)\n throwIfNotOk(res, body)\n return body as T\n }\n\n return {\n me: () => request<Identity>('/api/v1/me'),\n listEntities: () => request<{ entities: Entity[] }>('/api/v1/entities'),\n getEntity: (entityId: string) => request<{ entity: Entity }>(`/api/v1/entities/${entityId}`),\n getCapabilities: (entityId: string) =>\n request<{ entity_id: string; capabilities: EntityCapabilities }>(\n `/api/v1/entities/${entityId}/capabilities`,\n ),\n listRecords: (entityId: string, opts?: { limit?: number; offset?: number }) =>\n request<{ records: EntityRecord[] }>(\n `/api/v1/entities/${entityId}/records${buildRecordsQuery(opts)}`,\n ),\n /** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */\n connectionStatus: (connectionId: string) =>\n request<ExternalConnectionStatus>(\n `/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/status`,\n ),\n connectionStart: (connectionId: string, returnTo?: string) => {\n const qs = returnTo ? `?return_to=${encodeURIComponent(returnTo)}` : ''\n return request<{ authorizeUrl?: string; message?: string }>(\n `/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/start${qs}`,\n )\n },\n connectionProxy: async <T = unknown>(\n connectionId: string,\n input: ExternalProxyInput,\n ): Promise<T> => {\n const res = await fetchImpl(\n `${baseUrl}/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/proxy`,\n {\n method: 'POST',\n credentials: 'include',\n headers: { Accept: 'application/json', 'Content-Type': 'application/json' },\n body: JSON.stringify(input),\n },\n )\n const body = await parseJsonSafe(res)\n throwIfNotOk(res, body)\n return body as T\n },\n }\n}\n\nexport type CervioSessionClient = ReturnType<typeof createCervioSessionClient>\n\n/** Ensure user OAuth for an External Connection; opens top-level consent when needed. */\nexport async function ensureExternalConnection(\n api: {\n connectionStatus: (id: string) => Promise<ExternalConnectionStatus>\n connectionStart: (id: string, returnTo?: string) => Promise<{ authorizeUrl?: string; message?: string }>\n },\n connectionId: string,\n returnTo?: string,\n): Promise<ExternalConnectionStatus | null> {\n const st = await api.connectionStatus(connectionId)\n if (st.connected) return st\n const start = await api.connectionStart(connectionId, returnTo)\n if (!start.authorizeUrl) {\n throw new CervioApiError(501, 'start_failed', start.message || 'OAuth start failed')\n }\n if (typeof window !== 'undefined' && typeof window.__cervioOpenExternalAuth === 'function') {\n window.__cervioOpenExternalAuth(start.authorizeUrl)\n } else if (typeof window !== 'undefined') {\n window.top!.location.href = start.authorizeUrl\n }\n return null\n}\n\nconst DEFAULT_PAGE = 500\n\nexport type CervioListRecordsClient = {\n listRecords: (entityId: string, opts?: { limit?: number; offset?: number }) => Promise<{ records: EntityRecord[] }>\n}\n\n/** Total visible records for the caller (paginates until exhausted; cap 200k). */\nexport async function countVisibleRecords(\n api: CervioListRecordsClient,\n entityId: string,\n pageSize: number = DEFAULT_PAGE,\n): Promise<number> {\n let total = 0\n let offset = 0\n const maxRows = 200_000\n for (;;) {\n const { records } = await api.listRecords(entityId, { limit: pageSize, offset })\n total += records.length\n if (records.length < pageSize) break\n offset += pageSize\n if (offset >= maxRows) break\n }\n return total\n}\n\n/** Find an entity by technical name (case-insensitive) - prefer names over hard-coded UUIDs. */\nexport function findEntityByName(entities: Entity[], technicalName: string): Entity | undefined {\n const n = technicalName.toLowerCase()\n return entities.find((e) => e.name.toLowerCase() === n)\n}\n","/**\n * Minimal i18n helper for route plugins. Route plugins run in a sandboxed\n * `srcDoc` iframe: next-intl / `public/locales` are not available, so ship\n * your own catalogs in the ZIP and resolve the active locale from the host\n * bootstrap. See https://docs.cervio.app/docs/authoring → \"Plugin i18n / locale\".\n *\n * Resolve order (mandatory):\n * 1. host locale (`__CERVIO_PLUGIN_CONTEXT__.locale`), if enabled for this plugin\n * 2. `runtimeSettings.fallbackLocale`\n * 3. plugin default locale\n */\n\nimport { getPluginContext } from './context'\n\nexport type CervioI18nMessages = Record<string, unknown>\nexport type CervioI18nCatalog = Record<string, CervioI18nMessages>\n\nconst DEFAULT_LOCALE_TAGS: Record<string, string> = {\n it: 'it-IT',\n en: 'en-GB',\n es: 'es-ES',\n fr: 'fr-FR',\n de: 'de-DE',\n}\n\nexport interface ResolvePluginLocaleOptions {\n /** Locales this plugin ships (message keys must exist for each). */\n availableLocales: string[]\n defaultLocale: string\n}\n\n/** Resolve order only - does not read message catalogs. */\nexport function resolvePluginLocale(opts: ResolvePluginLocaleOptions): string {\n const ctx = getPluginContext()\n const hostLocale = ctx?.locale ?? ctx?.userLocale\n const runtimeAvailable = ctx?.runtimeSettings?.availableLocales\n const runtimeAllowed =\n Array.isArray(runtimeAvailable) && runtimeAvailable.length > 0 ? runtimeAvailable : null\n\n if (\n hostLocale &&\n opts.availableLocales.includes(hostLocale) &&\n (!runtimeAllowed || runtimeAllowed.includes(hostLocale))\n ) {\n return hostLocale\n }\n\n const fallback = ctx?.runtimeSettings?.fallbackLocale\n if (fallback && opts.availableLocales.includes(fallback)) return fallback\n\n return opts.defaultLocale\n}\n\nfunction getNestedValue(obj: unknown, path: string): unknown {\n return path.split('.').reduce<unknown>((acc, key) => {\n if (acc && typeof acc === 'object' && key in (acc as Record<string, unknown>)) {\n return (acc as Record<string, unknown>)[key]\n }\n return undefined\n }, obj)\n}\n\nexport interface CreateI18nOptions {\n /** `{ it: { toolbar: { newEntry: '...' } }, en: { ... } }` - identical key sets. */\n messages: CervioI18nCatalog\n defaultLocale: string\n /** Defaults to `Object.keys(messages)`. */\n availableLocales?: string[]\n /** Override `Intl` locale tags (e.g. `{ it: 'it-IT' }`). */\n localeTags?: Record<string, string>\n}\n\nexport interface CervioI18n {\n locale: string\n availableLocales: string[]\n /** Dot-path lookup (`'toolbar.newEntry'`) with `{placeholder}` interpolation. */\n t: (key: string, vars?: Record<string, string | number>) => string\n /** `Intl`-ready BCP 47 tag for `Intl.DateTimeFormat` / `Intl.NumberFormat`. */\n localeTag: (locale?: string) => string\n}\n\n/** Build a small `t()` + locale resolver from bundled catalogs. */\nexport function createI18n(opts: CreateI18nOptions): CervioI18n {\n const availableLocales = opts.availableLocales ?? Object.keys(opts.messages)\n const locale = resolvePluginLocale({ availableLocales, defaultLocale: opts.defaultLocale })\n const dict = opts.messages[locale] ?? opts.messages[opts.defaultLocale] ?? {}\n const localeTags = { ...DEFAULT_LOCALE_TAGS, ...opts.localeTags }\n\n function t(key: string, vars?: Record<string, string | number>): string {\n const raw = getNestedValue(dict, key)\n let out = typeof raw === 'string' ? raw : key\n if (vars) {\n for (const [k, v] of Object.entries(vars)) {\n out = out.replaceAll(`{${k}}`, String(v))\n }\n }\n return out\n }\n\n function localeTag(l: string = locale): string {\n return localeTags[l] ?? l\n }\n\n return { locale, availableLocales, t, localeTag }\n}\n"]}
|