@cervio/plugin-sdk 2.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,19 +1,26 @@
1
1
  # @cervio/plugin-sdk
2
2
 
3
- Typed client + runtime helpers for **Cervio route plugins**: `window.CervioUI`,
4
- the plugin boot context (`__CERVIO_PLUGIN_CONTEXT__`), the `/api/v1` HTTP
5
- client, host theme sync, and a tiny i18n resolver.
3
+ The SDK for Cervio plugins: the `CervioUI` client, the plugin context, the `/api/v1`
4
+ HTTP client, host theme sync, i18n, a PDF viewer and the helpers for write-gate plugins.
6
5
 
7
- Scaffold a new plugin with `npm create @cervio/plugin` (package
8
- [`@cervio/create-plugin`](../create-plugin)): it ships with this package pre-wired.
6
+ Start a new plugin with `npm create @cervio/plugin`: the templates come with this
7
+ package wired in.
9
8
 
10
9
  ```bash
11
- pnpm add @cervio/plugin-sdk
10
+ npm install @cervio/plugin-sdk
12
11
  ```
13
12
 
13
+ ESM only, no dependencies at runtime for the root entry.
14
+
15
+ | Entry | For | Contents |
16
+ |---|---|---|
17
+ | `@cervio/plugin-sdk` | route and task plugins (iframe) | CervioUI, context, HTTP clients, `markReady`, theme, i18n |
18
+ | `@cervio/plugin-sdk/pdf` | route and task plugins with React | `PdfViewer` |
19
+ | `@cervio/plugin-sdk/policy` | write-gate plugins (server isolate) | `definePolicy`, `allow`, `deny`, contract types |
20
+
14
21
  ## Why not `location.origin`?
15
22
 
16
- Route plugins run in a sandboxed iframe (`sandbox="allow-scripts"`,
23
+ Route and task plugins run in a sandboxed iframe (`sandbox="allow-scripts"`,
17
24
  no `allow-same-origin`). `window.location.origin` frequently serializes as the
18
25
  literal string `"null"` there. Always resolve the API base URL from
19
26
  `__CERVIO_PLUGIN_CONTEXT__.parentOrigin` - every helper in this package does
@@ -68,6 +75,19 @@ const { capabilities } = await client.getCapabilities('clienti')
68
75
  `getEntity`, `getCapabilities` and `listRecords` take the entity id **or** its
69
76
  technical name. Never hard-code org-specific UUIDs.
70
77
 
78
+ Writes run with the user's permissions and the rules of the entity's form:
79
+
80
+ ```ts
81
+ const { id } = await client.createRecord('ordini', { titolo: 'Sedie', importo: 1200 })
82
+ await client.updateRecord('ordini', id, { stato: 'ordinato' }) // only the fields you pass
83
+ await client.deleteRecord('ordini', id) // to the bin
84
+ ```
85
+
86
+ A technical name is resolved to the entity id once per client. Pass
87
+ `expectedUpdatedAt` to `updateRecord` to fail with `etag_conflict` (409) instead of
88
+ overwriting a record someone saved since you read it. Declare the methods in
89
+ `cervio_apis` (`POST`, `PATCH`, `DELETE` on `/api/v1/entities/`).
90
+
71
91
  `listRecords` (records of an entity without a view) works for organization
72
92
  administrators only: for other users the API answers `view_required`. A plugin used
73
93
  by everyone reads records with `listViewRecords` and counts them with
@@ -117,8 +137,21 @@ i18n.t('toolbar.newEntry')
117
137
  ```
118
138
 
119
139
  Resolve order: host locale (if enabled for this plugin) → `runtimeSettings.fallbackLocale`
120
- → plugin default. See [Authoring](https://docs.cervio.app/docs/authoring) → "Plugin i18n / locale" in
121
- the host repo for the full recipe.
140
+ → plugin default. See [Authoring](https://docs.cervio.app/docs/authoring), "Plugin i18n / locale",
141
+ for the full recipe.
142
+
143
+ ## PDF viewer
144
+
145
+ ```tsx
146
+ import { PdfViewer } from '@cervio/plugin-sdk/pdf'
147
+
148
+ <PdfViewer url={documentUrl} activePage={page} onPageChange={setPage} locale="it" />
149
+ ```
150
+
151
+ A separate entry, so plugins that do not show PDFs do not ship it. It needs React and
152
+ bundles the pdf.js worker (it works inside the sandboxed iframe, where a worker file
153
+ cannot be loaded by URL). `renderPageOverlay` draws your own content over the current
154
+ page, at its rendered size.
122
155
 
123
156
  ## Write-gate plugins (`plugin_type: policy`)
124
157
 
@@ -145,3 +178,17 @@ This package follows semver on its own. `CERVIO_UI_API_VERSION` (currently `1.0.
145
178
  is the version of the `window.CervioUI` contract offered by the host, and changes
146
179
  independently of this package's version. `@cervio/plugin-core` (manifest and ZIP
147
180
  validation) and `@cervio/cli` also version independently.
181
+
182
+ ## License
183
+
184
+ MIT, see [LICENSE](LICENSE).
185
+
186
+ **Trademark.** "Cervio" and the Cervio logo are trademarks of Cervio S.r.l. This license
187
+ does not grant permission to use them. You may say that a plugin "works with Cervio"; you
188
+ may not imply endorsement or ship a product named Cervio.
189
+
190
+ **Platform.** Using a Cervio organization is governed by your partner or customer
191
+ agreement, not by this license.
192
+
193
+ **Your plugins.** Plugins you write are yours: using this package gives Cervio no rights
194
+ over your plugin, and does not require you to open-source it.
package/dist/index.d.ts CHANGED
@@ -465,7 +465,7 @@ declare global {
465
465
  * outside the Cervio sandbox host, or in a plain browser tab for local dev).
466
466
  */
467
467
  declare function getCervioUI(): CervioUI;
468
- /** True when the host has injected `window.CervioUI` (srcDoc sandbox). */
468
+ /** True when the host has injected `window.CervioUI` (inside the plugin iframe). */
469
469
  declare function isCervioUIAvailable(): boolean;
470
470
  type CervioUiFrameMetricsEvent = {
471
471
  __cervioUI: 1;
@@ -501,10 +501,10 @@ type CervioUiHostEvent = CervioUiFrameMetricsEvent | CervioUiFrameClosedEvent |
501
501
 
502
502
  /**
503
503
  * Typed access to `window.__CERVIO_PLUGIN_CONTEXT__`, the boot payload the
504
- * Cervio host injects into every route plugin `srcDoc` iframe.
504
+ * Cervio host injects into every route plugin iframe.
505
505
  *
506
506
  * Docs: https://docs.cervio.app/docs/authoring ("Auth inside the iframe", "Plugin i18n /
507
- * locale"). Field shape is set by `components/plugins/plugin-route-sandbox-host.tsx`.
507
+ * locale").
508
508
  */
509
509
  interface CervioPluginRuntimeSettings {
510
510
  /** Locales this plugin install may use (Admin → Plugins → Impostazioni). */
@@ -526,7 +526,7 @@ interface CervioPluginContext {
526
526
  mountedAt?: string;
527
527
  /**
528
528
  * Real app origin - always set by the host. Use this for API base URLs.
529
- * Never use `window.location.origin`: in sandboxed `srcDoc` iframes it
529
+ * Never use `window.location.origin`: in sandboxed iframes it
530
530
  * frequently serializes as the literal string `"null"`.
531
531
  */
532
532
  parentOrigin?: string;
@@ -571,11 +571,10 @@ declare function openExternalAuth(url: string): boolean;
571
571
  declare function markReady(): void;
572
572
 
573
573
  /**
574
- * Typed access to the task-plugin boot payload + submit/draft bridge, injected
575
- * by `components/plugins/task-plugin-sandbox-host.tsx` when a human-task node
576
- * uses `taskUiMode: 'plugin'`. Shares the `window.__CERVIO_PLUGIN_CONTEXT__`
577
- * global with route plugins (never both on one page, so no collision), but
578
- * with a different shape — use these helpers rather than `getPluginContext()`.
574
+ * Typed access to the task-plugin boot payload and the submit/draft bridge, which
575
+ * the Cervio host injects when a task layout shows a plugin widget. It shares the
576
+ * `window.__CERVIO_PLUGIN_CONTEXT__` global with route plugins (never both on one
577
+ * page) but has a different shape: use these helpers, not `getPluginContext()`.
579
578
  */
580
579
  interface CervioTaskOutcome {
581
580
  value: string;
@@ -586,23 +585,20 @@ interface CervioTaskPluginContextData {
586
585
  workflowInstanceId: string;
587
586
  entityDataId: string | null;
588
587
  outcomes: CervioTaskOutcome[];
589
- /** Allowlisted subset of workflow instance variables declared by the node's exposedVariables config — never the full workflow_instances.context. */
588
+ /** The workflow variables the task layout exposes to this widget, never the whole workflow context. */
590
589
  instanceVariables: Record<string, unknown>;
591
590
  /**
592
- * The task's last `setTaskDraft()` payload (`workflow_tasks.draft_response_payload`),
593
- * or `null` when none was saved yet. Only one `TaskPluginSandboxHost` is ever
594
- * mounted at a time (compact XOR expanded modal) — switching between them
595
- * unmounts/remounts the plugin's iframe, discarding its in-memory state. A
596
- * plugin that seeds its editable fields from extraction data on every mount
597
- * (rather than from this draft first) silently reverts any edit made just
598
- * before that remount, once its own re-seed reaches the host. Read this on
599
- * mount and prefer it over re-deriving initial values from scratch.
591
+ * The task's last `setTaskDraft()` payload, or `null` when none was saved yet.
592
+ * The widget is remounted when the user switches between the compact and the
593
+ * expanded view, which discards its in-memory state: read this on mount and
594
+ * prefer it over deriving initial values from scratch, or the last edits made
595
+ * before the remount are lost.
600
596
  */
601
597
  draft: Record<string, unknown> | null;
602
598
  }
603
599
  interface CervioTaskPluginBoot {
604
600
  pluginType: 'task' | 'task_form';
605
- /** 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. */
601
+ /** UI hint only: true for a task_form plugin on an open task the viewer may complete. The server checks again on every submit. */
606
602
  canSubmit: boolean;
607
603
  pluginContext: CervioTaskPluginContextData;
608
604
  }
@@ -627,7 +623,7 @@ declare function getTaskPluginContext(): CervioTaskPluginBoot | null;
627
623
  declare function setTaskDraft(data: Record<string, unknown>): Promise<CervioTaskDraftResult>;
628
624
  /**
629
625
  * Completes the task with the given outcome. Only works for `task_form`
630
- * plugins — the host rejects the call server-side for plain `task` plugins.
626
+ * plugins: the host rejects the call for plain `task` plugins.
631
627
  */
632
628
  declare function submitTaskOutcome(outcomeKey: string, data?: Record<string, unknown>): Promise<CervioTaskSubmitResult>;
633
629
 
@@ -668,7 +664,7 @@ declare function getCurrentTheme(): CervioThemeSnapshot | null;
668
664
  *
669
665
  * Both resolve a missing `baseUrl` from `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`
670
666
  * - **never** from `window.location.origin`, which frequently serializes as
671
- * the literal string `"null"` inside a sandboxed `srcDoc` iframe.
667
+ * the literal string `"null"` inside a sandboxed iframe.
672
668
  */
673
669
  interface Identity {
674
670
  user_id: string;
@@ -728,7 +724,7 @@ declare class CervioApiError extends Error {
728
724
  /**
729
725
  * Resolve an API base URL: explicit value wins, otherwise
730
726
  * `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`. Throws rather than silently
731
- * falling back to `location.origin` (which breaks inside `srcDoc` sandboxes).
727
+ * falling back to `location.origin` (which breaks inside sandboxed iframes).
732
728
  */
733
729
  declare function resolveApiBaseUrl(explicitBaseUrl?: string): string;
734
730
  type CervioClientOptions = {
@@ -764,8 +760,27 @@ type ExternalProxyInput = {
764
760
  headers?: Record<string, string>;
765
761
  body?: unknown;
766
762
  };
763
+ type RecordWriteOptions = {
764
+ /** Form whose rules (required fields, validations) apply; default: the entity's default form. */
765
+ formName?: string;
766
+ };
767
+ type UpdateRecordOptions = RecordWriteOptions & {
768
+ /**
769
+ * `updated_at` of the record as you read it. If someone saved it since, the update
770
+ * fails with `CervioApiError` code `etag_conflict` (409) instead of overwriting.
771
+ */
772
+ expectedUpdatedAt?: string;
773
+ };
767
774
  /** Bearer-authenticated client (PAT / OAuth2 access token). */
768
775
  declare function createCervioClient(opts: CervioClientOptions): {
776
+ /** Creates a record with the user's permissions. `entity`: id or technical name. */
777
+ createRecord: (entity: string, data: Record<string, unknown>, opts?: RecordWriteOptions) => Promise<{
778
+ id: string;
779
+ }>;
780
+ /** Updates the given fields of a record (the others stay as they are). */
781
+ updateRecord: (entity: string, recordId: string, data: Record<string, unknown>, opts?: UpdateRecordOptions) => Promise<void>;
782
+ /** Moves a record to the bin (soft delete), with the user's permissions. */
783
+ deleteRecord: (entity: string, recordId: string) => Promise<void>;
769
784
  me: () => Promise<Identity>;
770
785
  listEntities: () => Promise<{
771
786
  entities: Entity[];
@@ -812,6 +827,14 @@ declare function createCervioSessionClient(opts?: CervioSessionClientOptions): {
812
827
  message?: string;
813
828
  }>;
814
829
  connectionProxy: <T = unknown>(connectionId: string, input: ExternalProxyInput) => Promise<T>;
830
+ /** Creates a record with the user's permissions. `entity`: id or technical name. */
831
+ createRecord: (entity: string, data: Record<string, unknown>, opts?: RecordWriteOptions) => Promise<{
832
+ id: string;
833
+ }>;
834
+ /** Updates the given fields of a record (the others stay as they are). */
835
+ updateRecord: (entity: string, recordId: string, data: Record<string, unknown>, opts?: UpdateRecordOptions) => Promise<void>;
836
+ /** Moves a record to the bin (soft delete), with the user's permissions. */
837
+ deleteRecord: (entity: string, recordId: string) => Promise<void>;
815
838
  me: () => Promise<Identity>;
816
839
  listEntities: () => Promise<{
817
840
  entities: Entity[];
@@ -864,8 +887,8 @@ declare function ensureExternalConnection(api: {
864
887
  declare function findEntityByName(entities: Entity[], technicalName: string): Entity | undefined;
865
888
 
866
889
  /**
867
- * Minimal i18n helper for route plugins. Route plugins run in a sandboxed
868
- * `srcDoc` iframe: next-intl / `public/locales` are not available, so ship
890
+ * Minimal i18n helper for plugins. Plugins run in a sandboxed iframe where
891
+ * the host's translations are not available, so ship
869
892
  * your own catalogs in the ZIP and resolve the active locale from the host
870
893
  * bootstrap. See https://docs.cervio.app/docs/authoring → "Plugin i18n / locale".
871
894
  *
@@ -904,4 +927,4 @@ interface CervioI18n {
904
927
  declare function createI18n(opts: CreateI18nOptions): CervioI18n;
905
928
 
906
929
  export { CERVIO_UI_API_VERSION, CervioApiError, createCervioClient, createCervioSessionClient, createI18n, ensureExternalConnection, findEntityByName, getCervioUI, getCurrentTheme, getPluginContext, getTaskPluginContext, isCervioUIAvailable, isInsideCervioSandbox, markReady, onThemeChange, openExternalAuth, resolveApiBaseUrl, resolvePluginLocale, setTaskDraft, submitTaskOutcome };
907
- export type { CervioClient, CervioClientOptions, CervioColorScheme, CervioHostThemeMessage, CervioI18n, CervioI18nCatalog, CervioI18nMessages, CervioPluginContext, CervioPluginRuntimeSettings, CervioSessionClient, CervioSessionClientOptions, CervioTaskDraftResult, CervioTaskOutcome, CervioTaskPluginBoot, CervioTaskPluginContextData, CervioTaskSubmitResult, CervioThemeChangeHandler, CervioThemeSnapshot, CervioUI, CervioUiActionSheetAction, CervioUiActionSheetOpenOptions, CervioUiAlertOptions, CervioUiBarcodeScanOptions, CervioUiBarcodeScanResult, CervioUiCameraOpenOptions, CervioUiConfirmOptions, CervioUiDateOpenOptions, CervioUiDialogVariant, CervioUiDomainPickOption, CervioUiEntityPickOptions, CervioUiExportDownloadOptions, CervioUiFileMeta, CervioUiFilesCaptureOptions, CervioUiFilesPickOptions, CervioUiFilesPickResult, CervioUiFilesUploadOptions, CervioUiFilesUploadResult, CervioUiFormatSnapshot, CervioUiFrameClosedEvent, CervioUiFrameMetricsEvent, CervioUiFrameOpenOptions, CervioUiFrameSize, CervioUiFrameSlot, CervioUiGroupPickOptions, CervioUiHostEvent, CervioUiLocationPickOptions, CervioUiLocationResult, CervioUiNavConfirmLeaveOptions, CervioUiPrintOpenOptions, CervioUiProgressShowOptions, CervioUiProgressUpdateOptions, CervioUiRecordPickOptions, CervioUiSelectOpenOptions, CervioUiSelectOption, CervioUiShareOpenOptions, CervioUiShareResult, CervioUiSheetAction, CervioUiSheetOpenOptions, CervioUiSurfaceClosedEvent, CervioUiSurfaceMessageEvent, CervioUiSurfaceOpenOptions, CervioUiSurfaceOpenedEvent, CervioUiTaskCompleteOptions, CervioUiTaskCompleteResult, CervioUiTaskListItem, CervioUiTaskOpenResult, CervioUiTaskOutcome, CervioUiTaskSummary, CervioUiThemeSnapshot, CervioUiToastOptions, CervioUiToastType, CervioUiUserPickOptions, CreateI18nOptions, Entity, EntityCapabilities, EntityRecord, ExternalConnectionStatus, ExternalProxyInput, Identity, ListViewRecordsOptions, ResolvePluginLocaleOptions, ViewRecordsPage };
930
+ export type { CervioClient, CervioClientOptions, CervioColorScheme, CervioHostThemeMessage, CervioI18n, CervioI18nCatalog, CervioI18nMessages, CervioPluginContext, CervioPluginRuntimeSettings, CervioSessionClient, CervioSessionClientOptions, CervioTaskDraftResult, CervioTaskOutcome, CervioTaskPluginBoot, CervioTaskPluginContextData, CervioTaskSubmitResult, CervioThemeChangeHandler, CervioThemeSnapshot, CervioUI, CervioUiActionSheetAction, CervioUiActionSheetOpenOptions, CervioUiAlertOptions, CervioUiBarcodeScanOptions, CervioUiBarcodeScanResult, CervioUiCameraOpenOptions, CervioUiConfirmOptions, CervioUiDateOpenOptions, CervioUiDialogVariant, CervioUiDomainPickOption, CervioUiEntityPickOptions, CervioUiExportDownloadOptions, CervioUiFileMeta, CervioUiFilesCaptureOptions, CervioUiFilesPickOptions, CervioUiFilesPickResult, CervioUiFilesUploadOptions, CervioUiFilesUploadResult, CervioUiFormatSnapshot, CervioUiFrameClosedEvent, CervioUiFrameMetricsEvent, CervioUiFrameOpenOptions, CervioUiFrameSize, CervioUiFrameSlot, CervioUiGroupPickOptions, CervioUiHostEvent, CervioUiLocationPickOptions, CervioUiLocationResult, CervioUiNavConfirmLeaveOptions, CervioUiPrintOpenOptions, CervioUiProgressShowOptions, CervioUiProgressUpdateOptions, CervioUiRecordPickOptions, CervioUiSelectOpenOptions, CervioUiSelectOption, CervioUiShareOpenOptions, CervioUiShareResult, CervioUiSheetAction, CervioUiSheetOpenOptions, CervioUiSurfaceClosedEvent, CervioUiSurfaceMessageEvent, CervioUiSurfaceOpenOptions, CervioUiSurfaceOpenedEvent, CervioUiTaskCompleteOptions, CervioUiTaskCompleteResult, CervioUiTaskListItem, CervioUiTaskOpenResult, CervioUiTaskOutcome, CervioUiTaskSummary, CervioUiThemeSnapshot, CervioUiToastOptions, CervioUiToastType, CervioUiUserPickOptions, CreateI18nOptions, Entity, EntityCapabilities, EntityRecord, ExternalConnectionStatus, ExternalProxyInput, Identity, ListViewRecordsOptions, RecordWriteOptions, ResolvePluginLocaleOptions, UpdateRecordOptions, ViewRecordsPage };
package/dist/index.js CHANGED
@@ -134,6 +134,7 @@ function buildRecordsQuery(opts) {
134
134
  const qs = params.toString();
135
135
  return qs ? `?${qs}` : "";
136
136
  }
137
+ var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
137
138
  function readEndpoints(request) {
138
139
  const entityPath = (entity) => `/api/v1/entities/${encodeURIComponent(entity)}`;
139
140
  const viewPath = (viewId) => `/api/v1/views/${encodeURIComponent(viewId)}`;
@@ -163,38 +164,84 @@ function readEndpoints(request) {
163
164
  countViewRecords: (viewId) => request(`${viewPath(viewId)}/records/count`)
164
165
  };
165
166
  }
167
+ function writeEndpoints(request, getEntity) {
168
+ const ids = /* @__PURE__ */ new Map();
169
+ const entityId = (entity) => {
170
+ if (UUID_RE.test(entity)) return Promise.resolve(entity);
171
+ let id = ids.get(entity);
172
+ if (!id) {
173
+ id = getEntity(entity).then((r) => r.entity.id);
174
+ id.catch(() => ids.delete(entity));
175
+ ids.set(entity, id);
176
+ }
177
+ return id;
178
+ };
179
+ const recordsPath = async (entity) => `/api/v1/entities/${encodeURIComponent(await entityId(entity))}/records`;
180
+ return {
181
+ /** Creates a record with the user's permissions. `entity`: id or technical name. */
182
+ createRecord: async (entity, data, opts) => request(await recordsPath(entity), {
183
+ method: "POST",
184
+ body: { data, ...opts?.formName ? { form_name: opts.formName } : {} }
185
+ }),
186
+ /** Updates the given fields of a record (the others stay as they are). */
187
+ updateRecord: async (entity, recordId, data, opts) => {
188
+ await request(`${await recordsPath(entity)}/${encodeURIComponent(recordId)}`, {
189
+ method: "PATCH",
190
+ body: {
191
+ data,
192
+ ...opts?.formName ? { form_name: opts.formName } : {},
193
+ ...opts?.expectedUpdatedAt ? { expected_updated_at: opts.expectedUpdatedAt } : {}
194
+ }
195
+ });
196
+ },
197
+ /** Moves a record to the bin (soft delete), with the user's permissions. */
198
+ deleteRecord: async (entity, recordId) => {
199
+ await request(`${await recordsPath(entity)}/${encodeURIComponent(recordId)}`, { method: "DELETE" });
200
+ }
201
+ };
202
+ }
203
+ function jsonInit(init, headers) {
204
+ if (init?.body === void 0) return { method: init?.method ?? "GET", headers };
205
+ return {
206
+ method: init.method ?? "POST",
207
+ headers: { ...headers, "Content-Type": "application/json" },
208
+ body: JSON.stringify(init.body)
209
+ };
210
+ }
166
211
  function createCervioClient(opts) {
167
212
  const fetchImpl = opts.fetchImpl ?? fetch;
168
213
  const baseUrl = resolveApiBaseUrl(opts.baseUrl);
169
- async function request(path) {
170
- const res = await fetchImpl(`${baseUrl}${path}`, {
171
- headers: {
172
- Authorization: `Bearer ${opts.token}`,
173
- Accept: "application/json"
174
- }
175
- });
214
+ async function request(path, init) {
215
+ const res = await fetchImpl(
216
+ `${baseUrl}${path}`,
217
+ jsonInit(init, { Authorization: `Bearer ${opts.token}`, Accept: "application/json" })
218
+ );
176
219
  const body = await parseJsonSafe(res);
177
220
  throwIfNotOk(res, body);
178
221
  return body;
179
222
  }
223
+ const read = readEndpoints(request);
180
224
  return {
181
- ...readEndpoints(request)
225
+ ...read,
226
+ ...writeEndpoints(request, read.getEntity)
182
227
  };
183
228
  }
184
229
  function createCervioSessionClient(opts = {}) {
185
230
  const fetchImpl = opts.fetchImpl ?? fetch;
186
231
  const baseUrl = resolveApiBaseUrl(opts.baseUrl);
187
- async function request(path) {
232
+ async function request(path, init) {
188
233
  const res = await fetchImpl(`${baseUrl}${path}`, {
189
- credentials: "include",
190
- headers: { Accept: "application/json" }
234
+ ...jsonInit(init, { Accept: "application/json" }),
235
+ credentials: "include"
191
236
  });
192
237
  const body = await parseJsonSafe(res);
193
238
  throwIfNotOk(res, body);
194
239
  return body;
195
240
  }
241
+ const read = readEndpoints(request);
196
242
  return {
197
- ...readEndpoints(request),
243
+ ...read,
244
+ ...writeEndpoints(request, read.getEntity),
198
245
  /** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */
199
246
  connectionStatus: (connectionId) => request(
200
247
  `/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/status`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cervio/plugin-sdk",
3
- "version": "2.0.0",
3
+ "version": "2.1.0",
4
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
5
  "keywords": [
6
6
  "cervio",
@@ -63,7 +63,7 @@
63
63
  "tsup": "^9.0.0",
64
64
  "typescript": "^5.8.3",
65
65
  "vitest": "^5.0.5",
66
- "@cervio/plugin-core": "^1.0.0"
66
+ "@cervio/plugin-core": "^1.0.1"
67
67
  },
68
68
  "publishConfig": {
69
69
  "access": "public"