@zachariaz/strapi-plugin-experience-context 0.0.0-stage → 0.1.0-dev.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +86 -2
  3. package/dist/_chunks/en-8ms9Hfxr.mjs +27 -0
  4. package/dist/_chunks/en-yERKDiB0.js +27 -0
  5. package/dist/admin/index.js +464 -0
  6. package/dist/admin/index.mjs +448 -0
  7. package/dist/admin/src/api/client.d.ts +13 -0
  8. package/dist/admin/src/api/types.d.ts +93 -0
  9. package/dist/admin/src/api/useInspect.d.ts +3 -0
  10. package/dist/admin/src/components/BlockMarkers.d.ts +12 -0
  11. package/dist/admin/src/components/ExperienceModal.d.ts +28 -0
  12. package/dist/admin/src/components/HeaderBadge.d.ts +19 -0
  13. package/dist/admin/src/components/Initializer.d.ts +5 -0
  14. package/dist/admin/src/components/ModalTrigger.d.ts +10 -0
  15. package/dist/admin/src/contentManagerHooks/editView.d.ts +7 -0
  16. package/dist/admin/src/index.d.ts +17 -0
  17. package/dist/admin/src/pluginId.d.ts +2 -0
  18. package/dist/admin/src/utils/dzSlots.d.ts +16 -0
  19. package/dist/admin/src/utils/labels.d.ts +30 -0
  20. package/dist/admin/src/utils/markers.d.ts +12 -0
  21. package/dist/admin/src/utils/modal.d.ts +10 -0
  22. package/dist/admin/src/utils/targets.d.ts +12 -0
  23. package/dist/server/index.js +3780 -0
  24. package/dist/server/index.mjs +3781 -0
  25. package/dist/server/src/admin-api/access.d.ts +40 -0
  26. package/dist/server/src/admin-api/inspect.d.ts +132 -0
  27. package/dist/server/src/admin-api/mark.d.ts +9 -0
  28. package/dist/server/src/block-keys/index.d.ts +16 -0
  29. package/dist/server/src/block-keys/middleware.d.ts +17 -0
  30. package/dist/server/src/block-keys/stamp.d.ts +55 -0
  31. package/dist/server/src/block-keys/store.d.ts +33 -0
  32. package/dist/server/src/block-keys/targets.d.ts +43 -0
  33. package/dist/server/src/bootstrap.d.ts +16 -0
  34. package/dist/server/src/changes.d.ts +80 -0
  35. package/dist/server/src/config/index.d.ts +67 -0
  36. package/dist/server/src/constants.d.ts +18 -0
  37. package/dist/server/src/content-types/index.d.ts +309 -0
  38. package/dist/server/src/controllers/admin.d.ts +10 -0
  39. package/dist/server/src/controllers/experience.d.ts +15 -0
  40. package/dist/server/src/controllers/index.d.ts +16 -0
  41. package/dist/server/src/destroy.d.ts +5 -0
  42. package/dist/server/src/index.d.ts +441 -0
  43. package/dist/server/src/integrity/index.d.ts +34 -0
  44. package/dist/server/src/integrity/orphans.d.ts +40 -0
  45. package/dist/server/src/mcp/index.d.ts +2 -0
  46. package/dist/server/src/mcp/operations.d.ts +815 -0
  47. package/dist/server/src/mcp/permissions.d.ts +56 -0
  48. package/dist/server/src/mcp/tools.d.ts +59 -0
  49. package/dist/server/src/model/content.d.ts +32 -0
  50. package/dist/server/src/model/mapping.d.ts +90 -0
  51. package/dist/server/src/model/records.d.ts +132 -0
  52. package/dist/server/src/model/store.d.ts +44 -0
  53. package/dist/server/src/model/target.d.ts +40 -0
  54. package/dist/server/src/policies/index.d.ts +4 -0
  55. package/dist/server/src/rbac/index.d.ts +24 -0
  56. package/dist/server/src/read-path/editor.d.ts +28 -0
  57. package/dist/server/src/read-path/gate.d.ts +26 -0
  58. package/dist/server/src/read-path/index.d.ts +12 -0
  59. package/dist/server/src/read-path/loader.d.ts +31 -0
  60. package/dist/server/src/read-path/middleware.d.ts +32 -0
  61. package/dist/server/src/read-path/payload.d.ts +34 -0
  62. package/dist/server/src/read-path/populate.d.ts +6 -0
  63. package/dist/server/src/register.d.ts +14 -0
  64. package/dist/server/src/registry/index.d.ts +29 -0
  65. package/dist/server/src/registry/unomi.d.ts +53 -0
  66. package/dist/server/src/routes/index.d.ts +25 -0
  67. package/dist/server/src/services/index.d.ts +79 -0
  68. package/package.json +140 -4
  69. package/scripts/experience-smoke.mjs +430 -0
@@ -0,0 +1,56 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ /**
3
+ * Admin RBAC actions that gate the MCP tools and the read-only admin API.
4
+ * Strapi's MCP server authenticates an admin API token and enables a tool for
5
+ * the session when the token's ability satisfies ANY of the tool's policies;
6
+ * the handler then checks every action the call needs (`requires` in
7
+ * ./tools). An admin token's ability never exceeds its owner's roles.
8
+ *
9
+ * - `read`: describe_target, list_registry, list_content_variants,
10
+ * validate_mapping, explain_variant_resolution; the admin inspection routes
11
+ * (Content Manager badge, Experience Builder simulator).
12
+ * - `variations.write`: audience variations and concept annotations.
13
+ * - `experiments.write`: experiment declarations, start/pause, conclude and
14
+ * outcome mappings; also needed by a variation call that touches an
15
+ * experiment outcome.
16
+ * - `maintenance`: backfill_block_keys.
17
+ *
18
+ * Every write action also allows what `read` allows.
19
+ *
20
+ * Admin API tokens keep a frozen permission snapshot: after installing or
21
+ * upgrading the plugin, tick these actions on the token (Settings → API
22
+ * Tokens → token → Plugins → Experience Context) and save.
23
+ */
24
+ export declare const ACTIONS: {
25
+ readonly read: "plugin::experience-context.read";
26
+ readonly variationsWrite: "plugin::experience-context.variations.write";
27
+ readonly experimentsWrite: "plugin::experience-context.experiments.write";
28
+ readonly maintenance: "plugin::experience-context.maintenance";
29
+ };
30
+ export type ExperienceAction = (typeof ACTIONS)[keyof typeof ACTIONS];
31
+ type Policies = [{
32
+ action: string;
33
+ }, ...{
34
+ action: string;
35
+ }[]];
36
+ /** Any of the plugin's actions: each write action implies read. */
37
+ export declare const READ_POLICIES: Policies;
38
+ export declare const VARIATIONS_POLICIES: Policies;
39
+ export declare const EXPERIMENTS_POLICIES: Policies;
40
+ /** remove_mapping: either write action enables it; the handler checks the one the kind needs. */
41
+ export declare const REMOVE_POLICIES: Policies;
42
+ export declare const MAINTENANCE_POLICIES: Policies;
43
+ type AbilityLike = {
44
+ can: (action: string, subject?: string) => boolean;
45
+ } | null | undefined;
46
+ /** The ability holds any of the plugin's actions (the admin routes' policy). */
47
+ export declare const canRead: (ability: AbilityLike) => boolean;
48
+ export declare const PERMISSION_ACTIONS: {
49
+ section: string;
50
+ displayName: string;
51
+ uid: string;
52
+ pluginName: string;
53
+ }[];
54
+ /** Bootstrap: makes the actions grantable to roles and admin API tokens. */
55
+ export declare const registerPermissionActions: (strapi: Core.Strapi) => Promise<void>;
56
+ export {};
@@ -0,0 +1,59 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { z } from '@strapi/utils';
3
+ import { type ExperienceAction } from './permissions';
4
+ /**
5
+ * MCP tools (plan §5.2), registered with `strapi.ai.mcp.registerTool` in the
6
+ * plugin's register phase. Each tool is enabled for an MCP session only when
7
+ * the admin API token holds one of its policies (see ./permissions). These
8
+ * are the only write interface of the plugin.
9
+ *
10
+ * Handlers return `structuredContent` (validated by the MCP SDK against the
11
+ * output schema, so those are loose objects) plus the same JSON as text for
12
+ * clients that only read `content`. Agent mistakes come back as `isError`
13
+ * results whose text names the path and what to fix.
14
+ */
15
+ export interface McpHandlerContext {
16
+ userAbility?: {
17
+ can: (action: string, subject?: string) => boolean;
18
+ };
19
+ user?: {
20
+ id: string | number;
21
+ };
22
+ }
23
+ type Handler = (params: {
24
+ args?: any;
25
+ extra?: unknown;
26
+ }) => Promise<any>;
27
+ export interface ExperienceTool {
28
+ name: string;
29
+ title: string;
30
+ description: string;
31
+ auth: {
32
+ policies: [{
33
+ action: string;
34
+ }, ...{
35
+ action: string;
36
+ }[]];
37
+ };
38
+ telemetry: {
39
+ source: string;
40
+ name: string;
41
+ };
42
+ resolveInputSchema?: () => z.ZodObject<any>;
43
+ resolveOutputSchema: () => z.ZodObject<any>;
44
+ createHandler: (strapi: Core.Strapi, context: McpHandlerContext) => Handler;
45
+ }
46
+ /**
47
+ * Change-log actor: the admin API token that made the call and its owner,
48
+ * `mcp:token:<tokenId>/user:<ownerId>`, so an agent's writes are never
49
+ * mistaken for its owner's. Strapi's MCP context carries only the owner, so
50
+ * the token is looked up from the request's bearer key (the same hash Strapi
51
+ * authenticated it with). Falls back to `mcp:user:<ownerId>`.
52
+ */
53
+ export declare const actorOf: (strapi: Core.Strapi, context: McpHandlerContext) => Promise<string>;
54
+ /** A ToolError when the token lacks `action` (the tool's policies only enable it; a call may need more). */
55
+ export declare const requireAction: (context: McpHandlerContext, action: ExperienceAction, why: string) => void;
56
+ export declare const EXPERIENCE_TOOLS: ExperienceTool[];
57
+ /** Register phase: store the definitions; Strapi's MCP server starts in bootstrap. */
58
+ export declare const registerMcpTools: (strapi: Core.Strapi) => number;
59
+ export {};
@@ -0,0 +1,32 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { type TargetRef } from './target';
3
+ /** Deep populate for one component (relations and media by reference, nested components recursively). */
4
+ export declare function populateFor(strapi: Core.Strapi, componentUid: string, depth?: number): Record<string, unknown> | '*';
5
+ /** Populate for the whole content zone, deep enough to copy any block. */
6
+ export declare function zonePopulate(strapi: Core.Strapi, uid: string): Record<string, unknown>;
7
+ /**
8
+ * Turns a component as read (output format) into create input for a COPY:
9
+ * no ids (new rows), relations as `{ set: [{ documentId, locale? }] }`,
10
+ * media as file ids, nested components recursively.
11
+ */
12
+ export declare function toCopyInput(strapi: Core.Strapi, componentUid: string, value: any, depth?: number): any;
13
+ export interface ZoneBlock {
14
+ __component: string;
15
+ id?: number | string;
16
+ blockKey?: string | null;
17
+ [field: string]: unknown;
18
+ }
19
+ /** The draft of one locale with the content zone deep-populated (for copying). */
20
+ export declare function loadDraftZone(strapi: Core.Strapi, target: TargetRef, locale: string | null): Promise<{
21
+ doc: any;
22
+ blocks: ZoneBlock[];
23
+ }>;
24
+ /** A new block from a copy of `source` (or given input content), with a fresh blockKey. */
25
+ export declare function newBlock(strapi: Core.Strapi, source: ZoneBlock | null, content: Record<string, unknown> | null, blockKey?: string): ZoneBlock;
26
+ /**
27
+ * Writes the zone back: existing blocks by reference (`{ __component, id }`),
28
+ * new blocks in full. `entries` is the final zone in order.
29
+ */
30
+ export declare function writeZone(strapi: Core.Strapi, target: TargetRef, locale: string | null, entries: ZoneBlock[]): Promise<void>;
31
+ /** Can the component be placed in this type's content zone? */
32
+ export declare function zoneAccepts(strapi: Core.Strapi, uid: string, componentUid: string): boolean;
@@ -0,0 +1,90 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { type EffectiveContext, type MappingInput, type Preset, type Registry, type ResolutionExplanation, type ValidationIssue, type ValidationResult } from '@zachariaz/experience-context-core';
3
+ import { type AnnotationRecord, type ExperimentRecord, type VariationRecord } from './records';
4
+ import type { Store } from './store';
5
+ import { type BlockView, type TargetRef } from './target';
6
+ /**
7
+ * The state of one target document in one locale, as every read tool and
8
+ * the admin inspection see it: the draft's blocks, the mappings that apply
9
+ * to the locale, and the experiments they reference.
10
+ */
11
+ export interface Snapshot {
12
+ target: TargetRef;
13
+ locale: string | null;
14
+ status: 'draft' | 'published';
15
+ doc: any;
16
+ blocks: BlockView[];
17
+ /** Every variation row of the document (all locales). */
18
+ allVariations: VariationRecord[];
19
+ allAnnotations: AnnotationRecord[];
20
+ /** Rows that apply to `locale` (locale-specific win over `locale: null`), any status. */
21
+ variations: VariationRecord[];
22
+ annotations: AnnotationRecord[];
23
+ experiments: Map<string, ExperimentRecord>;
24
+ }
25
+ export declare function loadSnapshot(strapi: Core.Strapi, store: Store, target: TargetRef, locale: string | null, status?: 'draft' | 'published'): Promise<Snapshot>;
26
+ /** Outcomes with active content outside this document + locale, per experiment (V6 across targets). */
27
+ export declare function contentOutcomesElsewhere(store: Store, snap: Pick<Snapshot, 'target' | 'variations'>, keys: string[]): Promise<Record<string, string[]>>;
28
+ export interface MappingState {
29
+ variations: VariationRecord[];
30
+ annotations: AnnotationRecord[];
31
+ experiments: ExperimentRecord[];
32
+ blockKeys: string[] | undefined;
33
+ contentOutcomes?: Record<string, string[]>;
34
+ }
35
+ /** The package's `MappingInput` for a state (all statuses; orphaned rows report `status: 'orphaned'`). */
36
+ export declare function mappingInput(state: MappingState, presets?: Preset[]): MappingInput;
37
+ export interface ValidationContext {
38
+ registry: Registry;
39
+ presets: Preset[];
40
+ }
41
+ export declare function validationContext(strapi: Core.Strapi): Promise<ValidationContext>;
42
+ export declare function validateState(state: MappingState, vctx: ValidationContext): ValidationResult;
43
+ /** The state a snapshot validates (the draft's block keys for V4). */
44
+ export declare function snapshotState(store: Store, snap: Snapshot): Promise<MappingState>;
45
+ export interface ChecklistItem {
46
+ status: 'ok' | 'warning' | 'error';
47
+ code?: string;
48
+ path: string;
49
+ text: string;
50
+ }
51
+ export declare const checklistLine: (i: ChecklistItem) => string;
52
+ /**
53
+ * The validation checklist (plan §6): what passed (✓ default exists, ✓ id
54
+ * valid, ✓ outcome mapped), then every error (✗) and warning (⚠). The same
55
+ * list backs `experience_describe_target`, `experience_validate_mapping` and
56
+ * the Content Manager modal.
57
+ */
58
+ export declare function checklist(state: MappingState, result: ValidationResult): ChecklistItem[];
59
+ export interface ValidationReport {
60
+ ok: boolean;
61
+ errors: ValidationIssue[];
62
+ warnings: ValidationIssue[];
63
+ checklist: string[];
64
+ items: ChecklistItem[];
65
+ }
66
+ export declare function report(state: MappingState, result: ValidationResult): ValidationReport;
67
+ /**
68
+ * The effective context `experience_explain_variant_resolution` resolves
69
+ * with (S1.8). The input is synthetic and untrusted: `sanitizeContext` builds
70
+ * the real-context layer (never a real profile). With `preview` (the
71
+ * default), its `experiments` and `now` move into a `PreviewContext`
72
+ * (source `experience-builder`, like the simulator): forced outcomes apply
73
+ * even to experiments that are not running, and nothing is exposable.
74
+ * Without preview, `experiments` count as the storefront's assignment and
75
+ * `now` only pins the evaluation time.
76
+ */
77
+ export declare function explainContext(input: unknown, preview?: boolean): EffectiveContext;
78
+ /**
79
+ * Resolves the snapshot's document for a synthetic context with the shared
80
+ * package, exactly as the storefront and the simulator do: `_experience` is
81
+ * attached like the read path, then `resolvePage` + `explainResolution`
82
+ * over {@link explainContext}.
83
+ */
84
+ export declare function explainSnapshot(snap: Snapshot, context: unknown, preview?: boolean): {
85
+ context: EffectiveContext;
86
+ rendered: (string | null)[];
87
+ sections: Record<string, import("@zachariaz/experience-context-core").SectionResolution>;
88
+ experiments: Record<string, import("@zachariaz/experience-context-core").ExperimentResolution>;
89
+ explanation: ResolutionExplanation;
90
+ };
@@ -0,0 +1,132 @@
1
+ import type { Experiment, ExperimentOutcome, Validity, Variation } from '@zachariaz/experience-context-core';
2
+ /** A stored variation row with its target and audit fields. */
3
+ export interface VariationRecord {
4
+ documentId: string | null;
5
+ targetUid: string;
6
+ targetDocumentId: string;
7
+ locale: string | null;
8
+ blockKey: string;
9
+ sectionKey: string;
10
+ variantKey: string;
11
+ displayName: string | null;
12
+ description: string | null;
13
+ isDefault: boolean;
14
+ status: 'active' | 'inactive';
15
+ orphaned: boolean;
16
+ targetAudiences: string[];
17
+ traits: string[];
18
+ affinities: string[];
19
+ experiment: {
20
+ key: string;
21
+ outcome: string;
22
+ } | null;
23
+ priority: number;
24
+ validity: Validity | null;
25
+ componentUid: string | null;
26
+ source: string | null;
27
+ createdBy: string | null;
28
+ correlationId: string | null;
29
+ createdAt?: string | null;
30
+ updatedAt?: string | null;
31
+ }
32
+ export interface AnnotationRecord {
33
+ documentId: string | null;
34
+ targetUid: string;
35
+ targetDocumentId: string;
36
+ locale: string | null;
37
+ blockKey: string | null;
38
+ concepts: string[];
39
+ orphaned: boolean;
40
+ source: string | null;
41
+ createdBy: string | null;
42
+ correlationId: string | null;
43
+ createdAt?: string | null;
44
+ updatedAt?: string | null;
45
+ }
46
+ export interface ExperimentRecord extends Experiment {
47
+ documentId: string | null;
48
+ source: string | null;
49
+ createdBy: string | null;
50
+ correlationId: string | null;
51
+ createdAt?: string | null;
52
+ updatedAt?: string | null;
53
+ }
54
+ export declare const toVariationRecord: (row: any) => VariationRecord;
55
+ export declare const toAnnotationRecord: (row: any) => AnnotationRecord;
56
+ export declare const toExperimentRecord: (row: any) => ExperimentRecord;
57
+ /** The package's `Variation` (contract v2): orphaned rows report `status: 'orphaned'`. */
58
+ export declare const toVariation: (r: VariationRecord) => Variation;
59
+ /** The package's `Experiment` (contract v2), without audit fields. */
60
+ export declare const toExperiment: (r: ExperimentRecord) => Experiment;
61
+ /** Stored data for a variation record (`locale` → `targetLocale`, `createdBy` → `createdByActor`). */
62
+ export declare const variationData: (r: Omit<VariationRecord, 'documentId'> & {
63
+ documentId?: string | null;
64
+ }) => {
65
+ targetUid: string;
66
+ targetDocumentId: string;
67
+ targetLocale: string | null;
68
+ blockKey: string;
69
+ sectionKey: string;
70
+ variantKey: string;
71
+ displayName: string | null;
72
+ description: string | null;
73
+ isDefault: boolean;
74
+ status: "active" | "inactive";
75
+ orphaned: boolean;
76
+ targetAudiences: string[];
77
+ traits: string[];
78
+ affinities: string[];
79
+ experiment: {
80
+ key: string;
81
+ outcome: string;
82
+ } | null;
83
+ priority: number;
84
+ validity: Validity | null;
85
+ componentUid: string | null;
86
+ source: string | null;
87
+ createdByActor: string | null;
88
+ correlationId: string | null;
89
+ };
90
+ export declare const annotationData: (r: Omit<AnnotationRecord, 'documentId'> & {
91
+ documentId?: string | null;
92
+ }) => {
93
+ targetUid: string;
94
+ targetDocumentId: string;
95
+ targetLocale: string | null;
96
+ blockKey: string | null;
97
+ concepts: string[];
98
+ orphaned: boolean;
99
+ source: string | null;
100
+ createdByActor: string | null;
101
+ correlationId: string | null;
102
+ };
103
+ export declare const experimentData: (r: Omit<ExperimentRecord, 'documentId'> & {
104
+ documentId?: string | null;
105
+ }) => {
106
+ key: string;
107
+ name: string | null;
108
+ description: string | null;
109
+ outcomes: ExperimentOutcome[];
110
+ controlOutcome: string;
111
+ status: import("@zachariaz/experience-context-core").ExperimentStatus;
112
+ validity: Validity | null;
113
+ winner: string | null;
114
+ externalId: string | null;
115
+ source: string | null;
116
+ createdByActor: string | null;
117
+ correlationId: string | null;
118
+ };
119
+ /** Same document, locale and block? (`locale: null` rows apply to every locale.) */
120
+ export declare const sameSlot: (a: {
121
+ locale: string | null;
122
+ blockKey: string | null;
123
+ }, locale: string | null, blockKey: string | null) => boolean;
124
+ /**
125
+ * Rows that apply to a document in `locale`: rows for that locale, plus
126
+ * `locale: null` rows for blocks (or the page) the locale has no row for.
127
+ * A locale-specific row wins over a `null` one.
128
+ */
129
+ export declare function forLocale<T extends {
130
+ locale: string | null;
131
+ blockKey: string | null;
132
+ }>(rows: T[], locale: string | null): T[];
@@ -0,0 +1,44 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { ChangeBatch, type ChangeSource } from '../changes';
3
+ import { type AnnotationRecord, type ExperimentRecord, type VariationRecord } from './records';
4
+ /**
5
+ * Storage for annotations, variations and experiments. Every write records
6
+ * a change-log row (actor, source, correlationId, before/after) and adds its
7
+ * target and experiment to the operation's {@link ChangeBatch}.
8
+ */
9
+ export interface WriteContext {
10
+ actor: string | null;
11
+ source: ChangeSource;
12
+ correlationId?: string | null;
13
+ reason?: string | null;
14
+ batch: ChangeBatch;
15
+ }
16
+ export declare function createStore(strapi: Core.Strapi): {
17
+ listVariations: (filters?: {
18
+ targetUid?: string;
19
+ targetDocumentId?: string | string[];
20
+ locale?: string | null;
21
+ sectionKey?: string;
22
+ blockKey?: string;
23
+ }) => Promise<VariationRecord[]>;
24
+ createVariation: (record: Omit<VariationRecord, 'documentId'>, ctx: WriteContext) => Promise<VariationRecord>;
25
+ updateVariation: (before: VariationRecord, patch: Partial<VariationRecord>, ctx: WriteContext) => Promise<VariationRecord>;
26
+ deleteVariation: (before: VariationRecord, ctx: WriteContext) => Promise<void>;
27
+ listAnnotations: (filters?: {
28
+ targetUid?: string;
29
+ targetDocumentId?: string | string[];
30
+ locale?: string | null;
31
+ blockKey?: string | null;
32
+ }) => Promise<AnnotationRecord[]>;
33
+ setAnnotation: (existing: AnnotationRecord | undefined, record: Omit<AnnotationRecord, 'documentId' | 'source' | 'createdBy' | 'correlationId' | 'orphaned'> & {
34
+ orphaned?: boolean;
35
+ }, ctx: WriteContext) => Promise<AnnotationRecord | null>;
36
+ deleteAnnotation: (before: AnnotationRecord, ctx: WriteContext) => Promise<void>;
37
+ listExperiments: (keys?: string[]) => Promise<ExperimentRecord[]>;
38
+ getExperiment: (key: string) => Promise<ExperimentRecord | undefined>;
39
+ saveExperiment: (existing: ExperimentRecord | undefined, record: Omit<ExperimentRecord, 'documentId' | 'source' | 'createdBy' | 'correlationId'>, ctx: WriteContext) => Promise<ExperimentRecord>;
40
+ deleteExperiment: (before: ExperimentRecord, ctx: WriteContext) => Promise<void>;
41
+ variationsOfExperiment: (key: string) => Promise<VariationRecord[]>;
42
+ logBlock: (action: 'create' | 'delete', block: Record<string, unknown>, ctx: WriteContext) => Promise<void>;
43
+ };
44
+ export type Store = ReturnType<typeof createStore>;
@@ -0,0 +1,40 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ /** A failure the agent (or admin caller) can act on; tools turn it into an `isError` result with this text. */
3
+ export declare class ToolError extends Error {
4
+ }
5
+ export interface TargetRef {
6
+ uid: string;
7
+ documentId: string;
8
+ kind: 'singleType' | 'collectionType';
9
+ localized: boolean;
10
+ }
11
+ export interface BlockView {
12
+ index: number;
13
+ blockKey: string | null;
14
+ componentUid: string;
15
+ /** One line, e.g. `zone.hero (variant: "default", hero_banner: "Spring sale")`. */
16
+ summary: string;
17
+ /** The block's readable title, when it has one (for "Fallback: …"). */
18
+ title: string | null;
19
+ }
20
+ /** Closest candidate by edit distance, as " Did you mean X?" (empty when nothing is close). */
21
+ export declare function didYouMean(input: string, candidates: Iterable<string>): string;
22
+ /** Locale codes configured in i18n (empty when i18n is absent). */
23
+ export declare const localeCodes: (strapi: Core.Strapi) => Promise<string[]>;
24
+ /**
25
+ * Resolves a target content type and document. For single types the
26
+ * documentId may be omitted: the type's only document is used.
27
+ */
28
+ export declare const resolveTarget: (strapi: Core.Strapi, targetUid: string, targetDocumentId?: string | null) => Promise<TargetRef>;
29
+ /** The locale to work in: the given one (checked), else the first locale the document exists in. */
30
+ export declare const pickLocale: (strapi: Core.Strapi, target: TargetRef, locale: string | null | undefined) => Promise<string | null>;
31
+ /** A block's readable title: its own title field, else the title of its first related entry or component. */
32
+ export declare const blockTitle: (block: Record<string, unknown>) => string | null;
33
+ /** One line describing a dynamic-zone block, e.g. `zone.hero (variant: "default", hero_banner: "Spring sale")`. */
34
+ export declare const summarizeBlock: (block: Record<string, unknown>) => string;
35
+ /** Reads one locale/status of the target with its content zone (one level of relations). */
36
+ export declare const loadDocument: (strapi: Core.Strapi, target: TargetRef, locale: string | null | undefined, status: 'draft' | 'published') => Promise<any>;
37
+ export declare const blocksOf: (doc: any) => BlockView[];
38
+ export declare const displayTitle: (doc: any) => string | null;
39
+ /** `zone.hero` → `Hero`, `zone.editorial-banners` → `Editorial banners`. */
40
+ export declare const componentLabel: (uid: string | null | undefined) => string;
@@ -0,0 +1,4 @@
1
+ declare const _default: {
2
+ 'can-read': (policyContext: any) => boolean;
3
+ };
4
+ export default _default;
@@ -0,0 +1,24 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { type ExperienceAction } from '../mcp/permissions';
3
+ /**
4
+ * Add-on admin roles (config `roles: true`). Each holds only this plugin's
5
+ * actions, so it is given to a user next to their base role (Editor,
6
+ * Author, a custom role): Strapi unions a user's roles. An admin API token
7
+ * never exceeds its owner, so the owner of an agent's token needs the role
8
+ * that holds what the token is meant to do.
9
+ *
10
+ * Provisioning is additive: a missing role is created, a missing plugin
11
+ * action is added. Nothing is removed and other permissions an administrator
12
+ * adds to these roles stay.
13
+ */
14
+ export interface RolePreset {
15
+ code: string;
16
+ name: string;
17
+ description: string;
18
+ actions: ExperienceAction[];
19
+ }
20
+ export declare const ROLE_PRESETS: RolePreset[];
21
+ /** Creates missing add-on roles and adds missing plugin actions to them. Returns one line per change. */
22
+ export declare function provisionRoles(strapi: Core.Strapi, presets?: RolePreset[]): Promise<string[]>;
23
+ /** Bootstrap: provisions when configured; logs what changed; never stops startup. */
24
+ export declare function bootstrapRoles(strapi: Core.Strapi, enabled: boolean): Promise<void>;
@@ -0,0 +1,28 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ /**
3
+ * `_experience` for editors that read documents through an admin route
4
+ * (Experience Builder). The content-API read path (`?withExperience=true`)
5
+ * only serves content-API callers holding `experience.read` and refuses
6
+ * admin sessions on purpose. An admin editor that loads a page through its
7
+ * own admin route asks here instead, with the admin user's ability: a user
8
+ * who can read the content type (and, for conditional or locale-limited
9
+ * roles, that document) in the Content Manager gets exactly the content-API
10
+ * shapes (`PageExperience` on the root, `BlockExperience` on blocks), so the
11
+ * editor resolves them with the same package as the storefront. Read-only.
12
+ */
13
+ export interface EditorAttachOptions {
14
+ uid: string;
15
+ /** Documents as returned by the Document Service (each with `documentId`); changed in place. */
16
+ documents: any[];
17
+ /** The locale the documents were read in (each document's own `locale` wins). */
18
+ locale?: string | null;
19
+ /** The admin user's ability (`ctx.state.userAbility` on an admin route). */
20
+ userAbility: any;
21
+ }
22
+ export interface EditorAttachResult {
23
+ /** True when at least one document got `_experience`. */
24
+ attached: boolean;
25
+ /** Why nothing was attached, or which documents were refused. */
26
+ why?: string;
27
+ }
28
+ export declare function attachForEditor(strapi: Core.Strapi, opts: EditorAttachOptions): Promise<EditorAttachResult>;
@@ -0,0 +1,26 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ /**
3
+ * The content-API action that unlocks `_experience`. It comes from the
4
+ * plugin's `GET /api/experience-context/access` route, so it appears in the
5
+ * API token and Users & Permissions editors like any other action. Its name
6
+ * doesn't end in `find`/`findOne`, so read-only tokens never match.
7
+ */
8
+ export declare const READ_ACTION = "plugin::experience-context.experience.read";
9
+ /** The Koa context of the current HTTP request, if any (programmatic calls have none). */
10
+ export declare function currentRequest(strapi: Core.Strapi): any | undefined;
11
+ export declare const isTruthyFlag: (v: unknown) => boolean;
12
+ /** `withExperience` from the Document Service params or, for nested reads, the request query. */
13
+ export declare function flagRequested(params: any, req: any): boolean;
14
+ export interface GateResult {
15
+ ok: boolean;
16
+ why: string;
17
+ }
18
+ /**
19
+ * Who may receive `_experience`: it reveals which audiences content was
20
+ * authored for, so only an authenticated content-API caller holding
21
+ * {@link READ_ACTION} does: a full-access token, a custom token with the
22
+ * action, or a Users & Permissions user whose role has it. Never an
23
+ * anonymous request (even if the Public role was given the action), never a
24
+ * call without a request, never an admin session.
25
+ */
26
+ export declare function checkGate(strapi: Core.Strapi, req: any): Promise<GateResult>;
@@ -0,0 +1,12 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import type { BlockKeyTargets } from '../block-keys/targets';
3
+ export { READ_ACTION, checkGate } from './gate';
4
+ export { PRIVATE_CACHE_CONTROL } from './middleware';
5
+ export { CONTRACT_VERSION } from './payload';
6
+ /**
7
+ * Register phase: declares `?withExperience` as a content-API query param,
8
+ * so `api.rest.strictParams` doesn't reject it.
9
+ */
10
+ export declare function registerReadPathParams(strapi: Core.Strapi): void;
11
+ /** Bootstrap phase: the Document Service middleware and the REST write-back strip. */
12
+ export declare function bootstrapReadPath(strapi: Core.Strapi, targets: BlockKeyTargets): void;
@@ -0,0 +1,31 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import { type ExperimentRecord } from '../model/records';
3
+ import { type DocumentRows } from './payload';
4
+ /**
5
+ * Per-request batch loader for experience mappings.
6
+ *
7
+ * Every enriched read of a request asks for its documents' rows here.
8
+ * Requests made in the same tick (a `findMany` page, or the concurrent
9
+ * `findOne`s the Navigation plugin makes for `related`) are merged into one
10
+ * variation query and one annotation query, and what was loaded is cached
11
+ * for the rest of the request, so a document is never looked up twice.
12
+ */
13
+ export declare class RequestLoader {
14
+ private readonly strapi;
15
+ private readonly loaded;
16
+ private readonly experiments;
17
+ private pending;
18
+ private scheduled;
19
+ constructor(strapi: Core.Strapi);
20
+ /** Rows of one document (after `load`). */
21
+ rowsOf(uid: string, documentId: string): DocumentRows;
22
+ load(uid: string, documentIds: string[]): Promise<void>;
23
+ /** Experiment declarations by key; one query per call for keys not loaded yet. */
24
+ loadExperiments(keys: string[]): Promise<Map<string, ExperimentRecord | undefined>>;
25
+ private flush;
26
+ private where;
27
+ }
28
+ /** The loader of the current request (one per Koa context). */
29
+ export declare function loaderFor(strapi: Core.Strapi, req: object): RequestLoader;
30
+ /** Loads rows and referenced experiments for `docs`, then attaches `_experience` to each. */
31
+ export declare function enrich(loader: RequestLoader, uid: string, docs: any[], zones: readonly string[], locale: string | null): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import type { Core } from '@strapi/strapi';
2
+ import type { BlockKeyTargets } from '../block-keys/targets';
3
+ /** Cache-Control set on every response that carries `_experience`. */
4
+ export declare const PRIVATE_CACHE_CONTROL = "private, no-store";
5
+ export interface ReadPathOptions {
6
+ /** content type uid → its targeted dynamic zones; every configured type is a key. */
7
+ zonesByUid: Map<string, readonly string[]>;
8
+ keyedComponents: ReadonlySet<string>;
9
+ }
10
+ export declare function readPathOptions(configured: readonly string[], targets: BlockKeyTargets): ReadPathOptions;
11
+ /**
12
+ * Document Service middleware of the read path (plan §5.1). Registered in
13
+ * bootstrap after content-variants, so it runs inside its stack: it sees
14
+ * documents already filtered (store-scope, clone hiding) and returns them
15
+ * to the variant overlay, which keeps unknown keys.
16
+ *
17
+ * Reads (`findOne` / `findFirst` / `findMany`) of a configured type with
18
+ * `?withExperience=true` (params or, for nested plugin reads, the request
19
+ * query), when the caller passes the gate and the read is the outermost one:
20
+ * forces `blockKey` into `fields`-restricted populates, loads the mappings of
21
+ * every returned document with one batched query per table, attaches
22
+ * `_experience` (v2) to the root and the mapped blocks, adds the declarations
23
+ * of the experiments they reference, and marks the response
24
+ * `private, no-store`. It never filters or reorders content.
25
+ *
26
+ * Without the flag or the permission the call passes through untouched, so
27
+ * the response is byte-identical to a read without the plugin.
28
+ *
29
+ * Writes (`create` / `update` / `clone`) of a configured type: strips
30
+ * `_experience` from the root and the dynamic-zone entries.
31
+ */
32
+ export declare function registerReadPathMiddleware(strapi: Core.Strapi, options: ReadPathOptions): void;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Pure helpers that turn stored rows into the `_experience` contract v2
3
+ * (`@zachariaz/experience-context-core`: `PageExperience` on the root,
4
+ * `BlockExperience` on blocks) and attach it to documents. No Strapi access
5
+ * here, so everything is unit-testable.
6
+ */
7
+ import { CONTRACT_VERSION } from '@zachariaz/experience-context-core';
8
+ import { type AnnotationRecord, type ExperimentRecord, type VariationRecord } from '../model/records';
9
+ export { CONTRACT_VERSION };
10
+ export interface DocumentRows {
11
+ variations: VariationRecord[];
12
+ annotations: AnnotationRecord[];
13
+ }
14
+ /** Rows that are sent: active, not orphaned, for the document's locale (or every locale). */
15
+ export declare function liveRows(rows: DocumentRows, locale: string | null): DocumentRows;
16
+ /** Experiment keys the live variations of the document's present blocks map to. */
17
+ export declare function experimentKeysOf(doc: any, zones: readonly string[], rows: DocumentRows, locale: string | null): string[];
18
+ /**
19
+ * Adds `_experience` to one document (in place): the root always gets
20
+ * `{ v: 2, concepts, experiments }`, so a client can tell an honoured flag
21
+ * from an ignored one; each block in the targeted zones that belongs to a
22
+ * section or has concepts gets `{ v: 2, concepts?, variation? }`. Inactive
23
+ * and orphaned mappings are not sent; variations outside their validity
24
+ * window are (the resolver applies `now`). Never removes or reorders.
25
+ */
26
+ export declare function attachToDocument(doc: any, zones: readonly string[], rows: DocumentRows, experiments: Map<string, ExperimentRecord | undefined>, fallbackLocale?: string | null): any;
27
+ /** The documents of a Document Service read result (`findOne`, `findMany`, paginated). */
28
+ export declare function documentsOf(result: unknown): any[];
29
+ /**
30
+ * Removes `_experience` from a write payload: the root and every entry of
31
+ * any array of objects (dynamic zones). Returns the paths it removed, e.g.
32
+ * `['root', 'content[1]']`.
33
+ */
34
+ export declare function stripExperience(data: unknown): string[];