@cervio/plugin-sdk 1.1.0 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026-present Cervio S.r.l.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
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 `create-cervio-plugin` (see
8
- `packages/create-cervio-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 `srcDoc` 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
@@ -47,11 +54,47 @@ console.log(ctx?.routeSlug, ctx?.parentOrigin, ctx?.runtimeSettings)
47
54
  ## HTTP client
48
55
 
49
56
  ```ts
50
- import { createCervioSessionClient } from '@cervio/plugin-sdk'
57
+ import { createCervioSessionClient, getPluginContext } from '@cervio/plugin-sdk'
51
58
 
52
59
  // baseUrl defaults to __CERVIO_PLUGIN_CONTEXT__.parentOrigin
53
60
  const client = createCervioSessionClient()
54
- const { entities } = await client.listEntities()
61
+
62
+ // Records through a view assigned to the user: its filters and permissions apply.
63
+ // Take the view id from the plugin settings, never hard-code it.
64
+ const viewId = String(getPluginContext()?.runtimeSettings?.view_id ?? '')
65
+ const { records, page } = await client.listViewRecords(viewId, { limit: 50 })
66
+ const next = page.next_cursor
67
+ ? await client.listViewRecords(viewId, { limit: 50, cursor: page.next_cursor })
68
+ : null
69
+ const { count } = await client.countViewRecords(viewId) // one call, counted by the server
70
+
71
+ // Entities by technical name: one round trip, no listEntities() first.
72
+ const { capabilities } = await client.getCapabilities('clienti')
73
+ ```
74
+
75
+ `getEntity`, `getCapabilities` and `listRecords` take the entity id **or** its
76
+ technical name. Never hard-code org-specific UUIDs.
77
+
78
+ `listRecords` (records of an entity without a view) works for organization
79
+ administrators only: for other users the API answers `view_required`. A plugin used
80
+ by everyone reads records with `listViewRecords` and counts them with
81
+ `countViewRecords`.
82
+
83
+ ### Fast start-up
84
+
85
+ - `me()` and `listEntities()` are answered from the boot payload when the manifest
86
+ declares `GET /api/v1/me` / `GET /api/v1/entities` in `cervio_apis`: no round trip.
87
+ - Declare the calls your plugin makes at start in the manifest `boot_requests`
88
+ (same path + query as the code, e.g. `/api/v1/views/<view id>/records?limit=50`):
89
+ Cervio starts them while the plugin loads and your call gets the response at once.
90
+ - Call `markReady()` once the first data is on screen:
91
+
92
+ ```ts
93
+ import { markReady } from '@cervio/plugin-sdk'
94
+
95
+ const { records } = await client.listViewRecords(viewId, { limit: 50 })
96
+ setRows(records)
97
+ markReady() // Cervio times the plugin open up to here; no-op outside Cervio
55
98
  ```
56
99
 
57
100
  `createCervioClient({ token })` is the Bearer-token equivalent (PAT / OAuth2
@@ -81,12 +124,58 @@ i18n.t('toolbar.newEntry')
81
124
  ```
82
125
 
83
126
  Resolve order: host locale (if enabled for this plugin) → `runtimeSettings.fallbackLocale`
84
- → plugin default. See [Authoring](https://docs.cervio.app/docs/authoring) → "Plugin i18n / locale" in
85
- the host repo for the full recipe.
127
+ → plugin default. See [Authoring](https://docs.cervio.app/docs/authoring), "Plugin i18n / locale",
128
+ for the full recipe.
129
+
130
+ ## PDF viewer
131
+
132
+ ```tsx
133
+ import { PdfViewer } from '@cervio/plugin-sdk/pdf'
134
+
135
+ <PdfViewer url={documentUrl} activePage={page} onPageChange={setPage} locale="it" />
136
+ ```
137
+
138
+ A separate entry, so plugins that do not show PDFs do not ship it. It needs React and
139
+ bundles the pdf.js worker (it works inside the sandboxed iframe, where a worker file
140
+ cannot be loaded by URL). `renderPageOverlay` draws your own content over the current
141
+ page, at its rendered size.
142
+
143
+ ## Write-gate plugins (`plugin_type: policy`)
144
+
145
+ A write-gate plugin runs in a server-side isolate before a record is created or
146
+ updated and answers allow or deny. It is not a record visibility policy (those are
147
+ configured in Admin, without code). Its helpers live in a separate entry with no
148
+ browser, React or PDF code:
149
+
150
+ ```js
151
+ import { definePolicy, allow, deny } from '@cervio/plugin-sdk/policy'
152
+
153
+ export default definePolicy(async (input, host) => {
154
+ if (input.record.data.blocked) return deny('Blocked by policy', 'BLOCKED')
155
+ return allow()
156
+ })
157
+ ```
158
+
159
+ The isolate loads a single self-contained module: bundle your entry (the scaffolder's
160
+ policy template does it with esbuild) instead of shipping bare imports.
86
161
 
87
162
  ## Versioning
88
163
 
89
- This package version tracks `CERVIO_UI_API_VERSION` (currently `1.0.0`), the
90
- `window.CervioUI.apiVersion` contract - not semver-independent feature
91
- releases. `@cervio/plugin-core` (manifest/ZIP validation) and `@cervio/cli`
92
- version independently.
164
+ This package follows semver on its own. `CERVIO_UI_API_VERSION` (currently `1.0.0`)
165
+ is the version of the `window.CervioUI` contract offered by the host, and changes
166
+ independently of this package's version. `@cervio/plugin-core` (manifest and ZIP
167
+ validation) and `@cervio/cli` also version independently.
168
+
169
+ ## License
170
+
171
+ MIT, see [LICENSE](LICENSE).
172
+
173
+ **Trademark.** "Cervio" and the Cervio logo are trademarks of Cervio S.r.l. This license
174
+ does not grant permission to use them. You may say that a plugin "works with Cervio"; you
175
+ may not imply endorsement or ship a product named Cervio.
176
+
177
+ **Platform.** Using a Cervio organization is governed by your partner or customer
178
+ agreement, not by this license.
179
+
180
+ **Your plugins.** Plugins you write are yours: using this package gives Cervio no rights
181
+ over your plugin, and does not require you to open-source it.
package/dist/index.d.ts CHANGED
@@ -156,6 +156,11 @@ interface CervioUiDateOpenOptions {
156
156
  mode?: 'date' | 'datetime';
157
157
  min?: string;
158
158
  max?: string;
159
+ /**
160
+ * ISO `yyyy-MM-dd` days greyed / unselectable in the calendar even when inside
161
+ * `[min, max]` (weekends, holidays, already taken, …). Max 400 entries.
162
+ */
163
+ disabledDates?: string[];
159
164
  /** Default true. */
160
165
  clearable?: boolean;
161
166
  }
@@ -460,7 +465,7 @@ declare global {
460
465
  * outside the Cervio sandbox host, or in a plain browser tab for local dev).
461
466
  */
462
467
  declare function getCervioUI(): CervioUI;
463
- /** True when the host has injected `window.CervioUI` (srcDoc sandbox). */
468
+ /** True when the host has injected `window.CervioUI` (inside the plugin iframe). */
464
469
  declare function isCervioUIAvailable(): boolean;
465
470
  type CervioUiFrameMetricsEvent = {
466
471
  __cervioUI: 1;
@@ -496,10 +501,10 @@ type CervioUiHostEvent = CervioUiFrameMetricsEvent | CervioUiFrameClosedEvent |
496
501
 
497
502
  /**
498
503
  * Typed access to `window.__CERVIO_PLUGIN_CONTEXT__`, the boot payload the
499
- * Cervio host injects into every route plugin `srcDoc` iframe.
504
+ * Cervio host injects into every route plugin iframe.
500
505
  *
501
506
  * Docs: https://docs.cervio.app/docs/authoring ("Auth inside the iframe", "Plugin i18n /
502
- * locale"). Field shape is set by `components/plugins/plugin-route-sandbox-host.tsx`.
507
+ * locale").
503
508
  */
504
509
  interface CervioPluginRuntimeSettings {
505
510
  /** Locales this plugin install may use (Admin → Plugins → Impostazioni). */
@@ -521,7 +526,7 @@ interface CervioPluginContext {
521
526
  mountedAt?: string;
522
527
  /**
523
528
  * Real app origin - always set by the host. Use this for API base URLs.
524
- * Never use `window.location.origin`: in sandboxed `srcDoc` iframes it
529
+ * Never use `window.location.origin`: in sandboxed iframes it
525
530
  * frequently serializes as the literal string `"null"`.
526
531
  */
527
532
  parentOrigin?: string;
@@ -534,8 +539,6 @@ interface CervioPluginContext {
534
539
  pluginVersion?: string | null;
535
540
  pluginArtifactSha256?: string | null;
536
541
  pluginKey?: string | null;
537
- /** Whether the host is caching this route's `srcDoc` across soft navigations. */
538
- artifactCacheEnabled?: boolean;
539
542
  runtimeSettings?: CervioPluginRuntimeSettings;
540
543
  /** Present only inside `dist/surface.html` (dialog.surface body iframe). */
541
544
  cervioSurface?: boolean;
@@ -546,6 +549,7 @@ declare global {
546
549
  __CERVIO_PLUGIN_CONTEXT__?: CervioPluginContext;
547
550
  /** Host-mediated top-level navigation (OAuth consent, cross-plugin deep links). */
548
551
  __cervioOpenExternalAuth?: (url: string) => boolean;
552
+ __cervioPluginReadySent?: boolean;
549
553
  /** Same-route query/path sync without reloading the iframe (shareable deep links). */
550
554
  __cervioSyncParentUrl?: (url: string, replace?: boolean) => boolean;
551
555
  }
@@ -559,13 +563,18 @@ declare function isInsideCervioSandbox(): boolean;
559
563
  * cross-plugin deep links: the sandboxed iframe cannot navigate `window.top`.
560
564
  */
561
565
  declare function openExternalAuth(url: string): boolean;
566
+ /**
567
+ * Tell the host that the first useful content is on screen (data loaded, not
568
+ * just the skeleton). The host uses it to time the plugin open; calling it is
569
+ * optional, safe outside Cervio, and only the first call counts.
570
+ */
571
+ declare function markReady(): void;
562
572
 
563
573
  /**
564
- * Typed access to the task-plugin boot payload + submit/draft bridge, injected
565
- * by `components/plugins/task-plugin-sandbox-host.tsx` when a human-task node
566
- * uses `taskUiMode: 'plugin'`. Shares the `window.__CERVIO_PLUGIN_CONTEXT__`
567
- * global with route plugins (never both on one page, so no collision), but
568
- * 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()`.
569
578
  */
570
579
  interface CervioTaskOutcome {
571
580
  value: string;
@@ -576,23 +585,20 @@ interface CervioTaskPluginContextData {
576
585
  workflowInstanceId: string;
577
586
  entityDataId: string | null;
578
587
  outcomes: CervioTaskOutcome[];
579
- /** 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. */
580
589
  instanceVariables: Record<string, unknown>;
581
590
  /**
582
- * The task's last `setTaskDraft()` payload (`workflow_tasks.draft_response_payload`),
583
- * or `null` when none was saved yet. Only one `TaskPluginSandboxHost` is ever
584
- * mounted at a time (compact XOR expanded modal) — switching between them
585
- * unmounts/remounts the plugin's iframe, discarding its in-memory state. A
586
- * plugin that seeds its editable fields from extraction data on every mount
587
- * (rather than from this draft first) silently reverts any edit made just
588
- * before that remount, once its own re-seed reaches the host. Read this on
589
- * 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.
590
596
  */
591
597
  draft: Record<string, unknown> | null;
592
598
  }
593
599
  interface CervioTaskPluginBoot {
594
600
  pluginType: 'task' | 'task_form';
595
- /** 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. */
596
602
  canSubmit: boolean;
597
603
  pluginContext: CervioTaskPluginContextData;
598
604
  }
@@ -617,7 +623,7 @@ declare function getTaskPluginContext(): CervioTaskPluginBoot | null;
617
623
  declare function setTaskDraft(data: Record<string, unknown>): Promise<CervioTaskDraftResult>;
618
624
  /**
619
625
  * Completes the task with the given outcome. Only works for `task_form`
620
- * plugins — the host rejects the call server-side for plain `task` plugins.
626
+ * plugins: the host rejects the call for plain `task` plugins.
621
627
  */
622
628
  declare function submitTaskOutcome(outcomeKey: string, data?: Record<string, unknown>): Promise<CervioTaskSubmitResult>;
623
629
 
@@ -658,7 +664,7 @@ declare function getCurrentTheme(): CervioThemeSnapshot | null;
658
664
  *
659
665
  * Both resolve a missing `baseUrl` from `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`
660
666
  * - **never** from `window.location.origin`, which frequently serializes as
661
- * the literal string `"null"` inside a sandboxed `srcDoc` iframe.
667
+ * the literal string `"null"` inside a sandboxed iframe.
662
668
  */
663
669
  interface Identity {
664
670
  user_id: string;
@@ -684,6 +690,32 @@ interface EntityRecord {
684
690
  entity_id: string;
685
691
  data: Record<string, unknown>;
686
692
  }
693
+ /** One page of `GET /api/v1/views/{viewId}/records`. */
694
+ interface ViewRecordsPage {
695
+ records: Array<{
696
+ id: string;
697
+ data: Record<string, unknown>;
698
+ }>;
699
+ page: {
700
+ limit: number;
701
+ has_more: boolean;
702
+ next_cursor?: string;
703
+ };
704
+ /** Content locale used for option labels. */
705
+ locale: string;
706
+ }
707
+ type ListViewRecordsOptions = {
708
+ /** Page size, 1 to 500 (default: the view's own page size). */
709
+ limit?: number;
710
+ /** `page.next_cursor` of the previous page. */
711
+ cursor?: string;
712
+ /** Option fields: `labels`, `slugs` or `both`. */
713
+ options?: 'labels' | 'slugs' | 'both';
714
+ /** Relation fields: `labels`, `uuids` or `both`. */
715
+ relations?: 'labels' | 'uuids' | 'both';
716
+ /** Content locale for option labels; must be enabled on the organization. */
717
+ locale?: string;
718
+ };
687
719
  declare class CervioApiError extends Error {
688
720
  readonly status: number;
689
721
  readonly code: string;
@@ -692,7 +724,7 @@ declare class CervioApiError extends Error {
692
724
  /**
693
725
  * Resolve an API base URL: explicit value wins, otherwise
694
726
  * `__CERVIO_PLUGIN_CONTEXT__.parentOrigin`. Throws rather than silently
695
- * falling back to `location.origin` (which breaks inside `srcDoc` sandboxes).
727
+ * falling back to `location.origin` (which breaks inside sandboxed iframes).
696
728
  */
697
729
  declare function resolveApiBaseUrl(explicitBaseUrl?: string): string;
698
730
  type CervioClientOptions = {
@@ -734,47 +766,83 @@ declare function createCervioClient(opts: CervioClientOptions): {
734
766
  listEntities: () => Promise<{
735
767
  entities: Entity[];
736
768
  }>;
737
- getEntity: (entityId: string) => Promise<{
769
+ /** `entity`: id or technical name (e.g. `'clienti'`). */
770
+ getEntity: (entity: string) => Promise<{
738
771
  entity: Entity;
739
772
  }>;
740
- getCapabilities: (entityId: string) => Promise<{
773
+ /** `entity`: id or technical name. */
774
+ getCapabilities: (entity: string) => Promise<{
741
775
  entity_id: string;
742
776
  capabilities: EntityCapabilities;
743
777
  }>;
744
- listRecords: (entityId: string, opts?: {
778
+ /**
779
+ * Records of an entity, without a view. **Organization administrators only**: for
780
+ * other users the API answers `view_required`, so a plugin used by everyone reads
781
+ * records through {@link listViewRecords}. `entity`: id or technical name.
782
+ */
783
+ listRecords: (entity: string, opts?: {
745
784
  limit?: number;
746
785
  offset?: number;
747
786
  }) => Promise<{
748
787
  records: EntityRecord[];
749
788
  }>;
789
+ /**
790
+ * One page of records through a view assigned to the user: the view's filters,
791
+ * owner scope and field permissions apply. Pass `page.next_cursor` as `cursor`
792
+ * for the next page. Declared in the manifest `boot_requests` with the same path
793
+ * and query, the first page is answered at boot.
794
+ */
795
+ listViewRecords: (viewId: string, opts?: ListViewRecordsOptions) => Promise<ViewRecordsPage>;
796
+ /** Number of records visible through a view, computed by the server in one call. */
797
+ countViewRecords: (viewId: string) => Promise<{
798
+ count: number;
799
+ }>;
750
800
  };
751
801
  type CervioClient = ReturnType<typeof createCervioClient>;
752
802
  /** Same-origin session cookie auth (typical inside the Cervio shell iframe). */
753
803
  declare function createCervioSessionClient(opts?: CervioSessionClientOptions): {
804
+ /** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */
805
+ connectionStatus: (connectionId: string) => Promise<ExternalConnectionStatus>;
806
+ connectionStart: (connectionId: string, returnTo?: string) => Promise<{
807
+ authorizeUrl?: string;
808
+ message?: string;
809
+ }>;
810
+ connectionProxy: <T = unknown>(connectionId: string, input: ExternalProxyInput) => Promise<T>;
754
811
  me: () => Promise<Identity>;
755
812
  listEntities: () => Promise<{
756
813
  entities: Entity[];
757
814
  }>;
758
- getEntity: (entityId: string) => Promise<{
815
+ /** `entity`: id or technical name (e.g. `'clienti'`). */
816
+ getEntity: (entity: string) => Promise<{
759
817
  entity: Entity;
760
818
  }>;
761
- getCapabilities: (entityId: string) => Promise<{
819
+ /** `entity`: id or technical name. */
820
+ getCapabilities: (entity: string) => Promise<{
762
821
  entity_id: string;
763
822
  capabilities: EntityCapabilities;
764
823
  }>;
765
- listRecords: (entityId: string, opts?: {
824
+ /**
825
+ * Records of an entity, without a view. **Organization administrators only**: for
826
+ * other users the API answers `view_required`, so a plugin used by everyone reads
827
+ * records through {@link listViewRecords}. `entity`: id or technical name.
828
+ */
829
+ listRecords: (entity: string, opts?: {
766
830
  limit?: number;
767
831
  offset?: number;
768
832
  }) => Promise<{
769
833
  records: EntityRecord[];
770
834
  }>;
771
- /** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */
772
- connectionStatus: (connectionId: string) => Promise<ExternalConnectionStatus>;
773
- connectionStart: (connectionId: string, returnTo?: string) => Promise<{
774
- authorizeUrl?: string;
775
- message?: string;
835
+ /**
836
+ * One page of records through a view assigned to the user: the view's filters,
837
+ * owner scope and field permissions apply. Pass `page.next_cursor` as `cursor`
838
+ * for the next page. Declared in the manifest `boot_requests` with the same path
839
+ * and query, the first page is answered at boot.
840
+ */
841
+ listViewRecords: (viewId: string, opts?: ListViewRecordsOptions) => Promise<ViewRecordsPage>;
842
+ /** Number of records visible through a view, computed by the server in one call. */
843
+ countViewRecords: (viewId: string) => Promise<{
844
+ count: number;
776
845
  }>;
777
- connectionProxy: <T = unknown>(connectionId: string, input: ExternalProxyInput) => Promise<T>;
778
846
  };
779
847
  type CervioSessionClient = ReturnType<typeof createCervioSessionClient>;
780
848
  /** Ensure user OAuth for an External Connection; opens top-level consent when needed. */
@@ -785,22 +853,15 @@ declare function ensureExternalConnection(api: {
785
853
  message?: string;
786
854
  }>;
787
855
  }, connectionId: string, returnTo?: string): Promise<ExternalConnectionStatus | null>;
788
- type CervioListRecordsClient = {
789
- listRecords: (entityId: string, opts?: {
790
- limit?: number;
791
- offset?: number;
792
- }) => Promise<{
793
- records: EntityRecord[];
794
- }>;
795
- };
796
- /** Total visible records for the caller (paginates until exhausted; cap 200k). */
797
- declare function countVisibleRecords(api: CervioListRecordsClient, entityId: string, pageSize?: number): Promise<number>;
798
- /** Find an entity by technical name (case-insensitive) - prefer names over hard-coded UUIDs. */
856
+ /**
857
+ * Find an entity by technical name (case-insensitive) - prefer names over hard-coded UUIDs.
858
+ * Often not needed: records / capabilities / entity calls accept the name directly.
859
+ */
799
860
  declare function findEntityByName(entities: Entity[], technicalName: string): Entity | undefined;
800
861
 
801
862
  /**
802
- * Minimal i18n helper for route plugins. Route plugins run in a sandboxed
803
- * `srcDoc` iframe: next-intl / `public/locales` are not available, so ship
863
+ * Minimal i18n helper for plugins. Plugins run in a sandboxed iframe where
864
+ * the host's translations are not available, so ship
804
865
  * your own catalogs in the ZIP and resolve the active locale from the host
805
866
  * bootstrap. See https://docs.cervio.app/docs/authoring → "Plugin i18n / locale".
806
867
  *
@@ -838,4 +899,5 @@ interface CervioI18n {
838
899
  /** Build a small `t()` + locale resolver from bundled catalogs. */
839
900
  declare function createI18n(opts: CreateI18nOptions): CervioI18n;
840
901
 
841
- export { CERVIO_UI_API_VERSION, CervioApiError, type CervioClient, type CervioClientOptions, type CervioColorScheme, type CervioHostThemeMessage, type CervioI18n, type CervioI18nCatalog, type CervioI18nMessages, type CervioListRecordsClient, type CervioPluginContext, type CervioPluginRuntimeSettings, type CervioSessionClient, type CervioSessionClientOptions, type CervioTaskDraftResult, type CervioTaskOutcome, type CervioTaskPluginBoot, type CervioTaskPluginContextData, type CervioTaskSubmitResult, type CervioThemeChangeHandler, type CervioThemeSnapshot, type CervioUI, type CervioUiActionSheetAction, type CervioUiActionSheetOpenOptions, type CervioUiAlertOptions, type CervioUiBarcodeScanOptions, type CervioUiBarcodeScanResult, type CervioUiCameraOpenOptions, type CervioUiConfirmOptions, type CervioUiDateOpenOptions, type CervioUiDialogVariant, type CervioUiDomainPickOption, type CervioUiEntityPickOptions, type CervioUiExportDownloadOptions, type CervioUiFileMeta, type CervioUiFilesCaptureOptions, type CervioUiFilesPickOptions, type CervioUiFilesPickResult, type CervioUiFilesUploadOptions, type CervioUiFilesUploadResult, type CervioUiFormatSnapshot, type CervioUiFrameClosedEvent, type CervioUiFrameMetricsEvent, type CervioUiFrameOpenOptions, type CervioUiFrameSize, type CervioUiFrameSlot, type CervioUiGroupPickOptions, type CervioUiHostEvent, type CervioUiLocationPickOptions, type CervioUiLocationResult, type CervioUiNavConfirmLeaveOptions, type CervioUiPrintOpenOptions, type CervioUiProgressShowOptions, type CervioUiProgressUpdateOptions, type CervioUiRecordPickOptions, type CervioUiSelectOpenOptions, type CervioUiSelectOption, type CervioUiShareOpenOptions, type CervioUiShareResult, type CervioUiSheetAction, type CervioUiSheetOpenOptions, type CervioUiSurfaceClosedEvent, type CervioUiSurfaceMessageEvent, type CervioUiSurfaceOpenOptions, type CervioUiSurfaceOpenedEvent, type CervioUiTaskCompleteOptions, type CervioUiTaskCompleteResult, type CervioUiTaskListItem, type CervioUiTaskOpenResult, type CervioUiTaskOutcome, type CervioUiTaskSummary, type CervioUiThemeSnapshot, type CervioUiToastOptions, type CervioUiToastType, type CervioUiUserPickOptions, type CreateI18nOptions, type Entity, type EntityCapabilities, type EntityRecord, type ExternalConnectionStatus, type ExternalProxyInput, type Identity, type ResolvePluginLocaleOptions, countVisibleRecords, createCervioClient, createCervioSessionClient, createI18n, ensureExternalConnection, findEntityByName, getCervioUI, getCurrentTheme, getPluginContext, getTaskPluginContext, isCervioUIAvailable, isInsideCervioSandbox, onThemeChange, openExternalAuth, resolveApiBaseUrl, resolvePluginLocale, setTaskDraft, submitTaskOutcome };
902
+ export { CERVIO_UI_API_VERSION, CervioApiError, createCervioClient, createCervioSessionClient, createI18n, ensureExternalConnection, findEntityByName, getCervioUI, getCurrentTheme, getPluginContext, getTaskPluginContext, isCervioUIAvailable, isInsideCervioSandbox, markReady, onThemeChange, openExternalAuth, resolveApiBaseUrl, resolvePluginLocale, setTaskDraft, submitTaskOutcome };
903
+ 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 };
package/dist/index.js CHANGED
@@ -26,6 +26,15 @@ function openExternalAuth(url) {
26
26
  }
27
27
  return window.__cervioOpenExternalAuth(url);
28
28
  }
29
+ function markReady() {
30
+ if (typeof window === "undefined" || window.parent === window) return;
31
+ if (window.__cervioPluginReadySent) return;
32
+ window.__cervioPluginReadySent = true;
33
+ try {
34
+ window.parent.postMessage({ __cervioPluginReady: 1 }, "*");
35
+ } catch {
36
+ }
37
+ }
29
38
 
30
39
  // src/task-context.ts
31
40
  function getTaskPluginContext() {
@@ -108,6 +117,16 @@ function throwIfNotOk(res, body) {
108
117
  const message = typeof body.message === "string" ? body.message : res.statusText;
109
118
  throw new CervioApiError(res.status, code, message);
110
119
  }
120
+ function buildViewRecordsQuery(opts) {
121
+ const params = new URLSearchParams();
122
+ if (opts?.limit != null) params.set("limit", String(opts.limit));
123
+ if (opts?.cursor) params.set("cursor", opts.cursor);
124
+ if (opts?.options) params.set("options", opts.options);
125
+ if (opts?.relations) params.set("relations", opts.relations);
126
+ if (opts?.locale) params.set("locale", opts.locale);
127
+ const qs = params.toString();
128
+ return qs ? `?${qs}` : "";
129
+ }
111
130
  function buildRecordsQuery(opts) {
112
131
  const params = new URLSearchParams();
113
132
  if (opts?.limit != null) params.set("limit", String(opts.limit));
@@ -115,6 +134,35 @@ function buildRecordsQuery(opts) {
115
134
  const qs = params.toString();
116
135
  return qs ? `?${qs}` : "";
117
136
  }
137
+ function readEndpoints(request) {
138
+ const entityPath = (entity) => `/api/v1/entities/${encodeURIComponent(entity)}`;
139
+ const viewPath = (viewId) => `/api/v1/views/${encodeURIComponent(viewId)}`;
140
+ return {
141
+ me: () => request("/api/v1/me"),
142
+ listEntities: () => request("/api/v1/entities"),
143
+ /** `entity`: id or technical name (e.g. `'clienti'`). */
144
+ getEntity: (entity) => request(entityPath(entity)),
145
+ /** `entity`: id or technical name. */
146
+ getCapabilities: (entity) => request(
147
+ `${entityPath(entity)}/capabilities`
148
+ ),
149
+ /**
150
+ * Records of an entity, without a view. **Organization administrators only**: for
151
+ * other users the API answers `view_required`, so a plugin used by everyone reads
152
+ * records through {@link listViewRecords}. `entity`: id or technical name.
153
+ */
154
+ listRecords: (entity, opts) => request(`${entityPath(entity)}/records${buildRecordsQuery(opts)}`),
155
+ /**
156
+ * One page of records through a view assigned to the user: the view's filters,
157
+ * owner scope and field permissions apply. Pass `page.next_cursor` as `cursor`
158
+ * for the next page. Declared in the manifest `boot_requests` with the same path
159
+ * and query, the first page is answered at boot.
160
+ */
161
+ listViewRecords: (viewId, opts) => request(`${viewPath(viewId)}/records${buildViewRecordsQuery(opts)}`),
162
+ /** Number of records visible through a view, computed by the server in one call. */
163
+ countViewRecords: (viewId) => request(`${viewPath(viewId)}/records/count`)
164
+ };
165
+ }
118
166
  function createCervioClient(opts) {
119
167
  const fetchImpl = opts.fetchImpl ?? fetch;
120
168
  const baseUrl = resolveApiBaseUrl(opts.baseUrl);
@@ -130,15 +178,7 @@ function createCervioClient(opts) {
130
178
  return body;
131
179
  }
132
180
  return {
133
- me: () => request("/api/v1/me"),
134
- listEntities: () => request("/api/v1/entities"),
135
- getEntity: (entityId) => request(`/api/v1/entities/${entityId}`),
136
- getCapabilities: (entityId) => request(
137
- `/api/v1/entities/${entityId}/capabilities`
138
- ),
139
- listRecords: (entityId, opts2) => request(
140
- `/api/v1/entities/${entityId}/records${buildRecordsQuery(opts2)}`
141
- )
181
+ ...readEndpoints(request)
142
182
  };
143
183
  }
144
184
  function createCervioSessionClient(opts = {}) {
@@ -154,15 +194,7 @@ function createCervioSessionClient(opts = {}) {
154
194
  return body;
155
195
  }
156
196
  return {
157
- me: () => request("/api/v1/me"),
158
- listEntities: () => request("/api/v1/entities"),
159
- getEntity: (entityId) => request(`/api/v1/entities/${entityId}`),
160
- getCapabilities: (entityId) => request(
161
- `/api/v1/entities/${entityId}/capabilities`
162
- ),
163
- listRecords: (entityId, opts2) => request(
164
- `/api/v1/entities/${entityId}/records${buildRecordsQuery(opts2)}`
165
- ),
197
+ ...readEndpoints(request),
166
198
  /** External Connections - requires admin bind + `X-Cervio-Plugin-Key` (host injects on relay). */
167
199
  connectionStatus: (connectionId) => request(
168
200
  `/api/v1/plugins/connections/${encodeURIComponent(connectionId)}/status`
@@ -203,20 +235,6 @@ async function ensureExternalConnection(api, connectionId, returnTo) {
203
235
  }
204
236
  return null;
205
237
  }
206
- var DEFAULT_PAGE = 500;
207
- async function countVisibleRecords(api, entityId, pageSize = DEFAULT_PAGE) {
208
- let total = 0;
209
- let offset = 0;
210
- const maxRows = 2e5;
211
- for (; ; ) {
212
- const { records } = await api.listRecords(entityId, { limit: pageSize, offset });
213
- total += records.length;
214
- if (records.length < pageSize) break;
215
- offset += pageSize;
216
- if (offset >= maxRows) break;
217
- }
218
- return total;
219
- }
220
238
  function findEntityByName(entities, technicalName) {
221
239
  const n = technicalName.toLowerCase();
222
240
  return entities.find((e) => e.name.toLowerCase() === n);
@@ -271,6 +289,4 @@ function createI18n(opts) {
271
289
  return { locale, availableLocales, t, localeTag };
272
290
  }
273
291
 
274
- export { CERVIO_UI_API_VERSION, CervioApiError, countVisibleRecords, createCervioClient, createCervioSessionClient, createI18n, ensureExternalConnection, findEntityByName, getCervioUI, getCurrentTheme, getPluginContext, getTaskPluginContext, isCervioUIAvailable, isInsideCervioSandbox, onThemeChange, openExternalAuth, resolveApiBaseUrl, resolvePluginLocale, setTaskDraft, submitTaskOutcome };
275
- //# sourceMappingURL=index.js.map
276
- //# sourceMappingURL=index.js.map
292
+ export { CERVIO_UI_API_VERSION, CervioApiError, createCervioClient, createCervioSessionClient, createI18n, ensureExternalConnection, findEntityByName, getCervioUI, getCurrentTheme, getPluginContext, getTaskPluginContext, isCervioUIAvailable, isInsideCervioSandbox, markReady, onThemeChange, openExternalAuth, resolveApiBaseUrl, resolvePluginLocale, setTaskDraft, submitTaskOutcome };
@@ -1,4 +1,4 @@
1
- import * as react_jsx_runtime from 'react/jsx-runtime';
1
+ import * as react from 'react';
2
2
  import { ReactNode } from 'react';
3
3
 
4
4
  /**
@@ -33,6 +33,7 @@ interface PdfViewerProps {
33
33
  /** `it` (default) or `en` - see `./i18n`. */
34
34
  locale?: PdfViewerLocale;
35
35
  }
36
- declare function PdfViewer({ url, activePage, onPageChange, renderPageOverlay, locale }: PdfViewerProps): react_jsx_runtime.JSX.Element;
36
+ declare function PdfViewer({ url, activePage, onPageChange, renderPageOverlay, locale }: PdfViewerProps): react.JSX.Element;
37
37
 
38
- export { type PdfPageOverlayInfo, PdfViewer, type PdfViewerLocale, type PdfViewerProps };
38
+ export { PdfViewer };
39
+ export type { PdfPageOverlayInfo, PdfViewerLocale, PdfViewerProps };