@collective-intelligence/external-apps-server-sdk-strapi 0.0.0-stage → 0.13.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/README.md +97 -2
- package/dist/index/declarations/index.d.ts +4 -0
- package/dist/index/declarations/strapi.d.ts +83 -0
- package/dist/index/declarations/toolkit/codec.d.ts +8 -0
- package/dist/index/declarations/toolkit/contracts.d.ts +77 -0
- package/dist/index/declarations/toolkit/mapping.d.ts +18 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/package.json +60 -4
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@collective-intelligence/external-apps-server-sdk-strapi`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Strapi SDK connects a self-hosted Strapi 5 site to Collective
|
|
4
|
+
Intelligence (CI) through a Gateway. It turns a Strapi Document Service into a
|
|
5
|
+
Gateway resource that CI reads, and it holds the Strapi plugin hooks for soft
|
|
6
|
+
delete, restore and incremental changes. It is a CMS SDK: it uses the server
|
|
7
|
+
SDK `@collective-intelligence/external-apps-server-sdk` through its public
|
|
8
|
+
entries only.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
npm install @collective-intelligence/external-apps-server-sdk-strapi @collective-intelligence/external-apps-server-sdk effect
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
- The server SDK is a dependency with an exact version: install the version
|
|
17
|
+
that this package names. The server SDK needs `effect` (`^4.1.0`) as a peer.
|
|
18
|
+
- `@strapi/strapi` (`>=5 <6`) is an optional peer. The adapter calls the
|
|
19
|
+
Document Service that you give it and imports nothing from Strapi.
|
|
20
|
+
|
|
21
|
+
## Define a source
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
import { defineStrapiSource } from "@collective-intelligence/external-apps-server-sdk-strapi"
|
|
25
|
+
import { defineGateway } from "@collective-intelligence/external-apps-server-sdk/gateway"
|
|
26
|
+
|
|
27
|
+
const customers = defineStrapiSource({
|
|
28
|
+
authorization,
|
|
29
|
+
authorize: ({ action, context }) => checkStrapiPermission(action, context),
|
|
30
|
+
capabilities,
|
|
31
|
+
contentType: "collection",
|
|
32
|
+
definition,
|
|
33
|
+
documents: strapi,
|
|
34
|
+
identity: { fields: ["documentId", "locale"] },
|
|
35
|
+
localeField: "locale",
|
|
36
|
+
projection: { fields: ["documentId", "locale", "name"] },
|
|
37
|
+
revision: (record) => String(record.updatedAt),
|
|
38
|
+
sanitize: ({ value }) => value,
|
|
39
|
+
uid: "api::customer.customer",
|
|
40
|
+
updatedAt: (record) => String(record.updatedAt)
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
const gateway = defineGateway({
|
|
44
|
+
id: "cms",
|
|
45
|
+
version: "1.0.0",
|
|
46
|
+
knowledge: [{ resource: customers, access: "read" }],
|
|
47
|
+
// A Gateway that only serves Knowledge declares no operation domain.
|
|
48
|
+
operationDomains: []
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
- `documents` is the Strapi instance (`strapi.documents(uid)`), or any object
|
|
53
|
+
with a `documents(uid)` function that returns a `StrapiDocumentService`.
|
|
54
|
+
- `identity.fields` starts with `documentId`. The adapter writes each record id
|
|
55
|
+
as a Resource id of the server SDK (`strapi:id.` and the base64url JSON of
|
|
56
|
+
the id field values).
|
|
57
|
+
- `capabilities` must agree with `definition` and with the installed plugin
|
|
58
|
+
hooks: `nativePolicy` is required, `transactions` is not supported, and
|
|
59
|
+
`softDelete`, `restore` and `incrementalChanges` need their hooks.
|
|
60
|
+
- `authorize` runs before each Document Service call, and `sanitize` runs on
|
|
61
|
+
each document before it leaves the adapter.
|
|
62
|
+
|
|
63
|
+
`defineStrapiGatewayPlugin(hooks)` freezes the `changes`, `restore` and
|
|
64
|
+
`softDelete` hooks that you pass as `plugin`.
|
|
65
|
+
|
|
66
|
+
## Answers and formats
|
|
67
|
+
|
|
68
|
+
- A request with a bad Resource id or a bad list or changes cursor answers
|
|
69
|
+
`invalid_request`, with the error message in `details.cause`. A failure of
|
|
70
|
+
the Document Service answers `internal`.
|
|
71
|
+
- A cursor is `strapi:cursor.` (list) or `strapi:changes:cursor.` (changes)
|
|
72
|
+
and the base64url JSON of its value; a revision is `strapi:rev.` and the
|
|
73
|
+
base64url JSON of the revision text. These formats are the ones that the
|
|
74
|
+
server SDK `./knowledge-sources/strapi` entry writes, so cursors and
|
|
75
|
+
revisions that it issued still work.
|
|
76
|
+
- `DataSourceMappingError` is a `TypeError` with one of the codes
|
|
77
|
+
`capability_mismatch`, `duplicate_field`, `invalid_pagination` and
|
|
78
|
+
`unsupported_mapping`. A cursor that the adapter cannot read throws
|
|
79
|
+
`invalid_pagination`. The root entry exports the class:
|
|
80
|
+
`error instanceof DataSourceMappingError` holds for a source configuration
|
|
81
|
+
that `defineStrapiSource` refuses.
|
|
82
|
+
|
|
83
|
+
## Upgrade from the server SDK Strapi entry
|
|
84
|
+
|
|
85
|
+
- Import `defineStrapiSource`, `defineStrapiGatewayPlugin` and their types
|
|
86
|
+
from this package, not from
|
|
87
|
+
`@collective-intelligence/external-apps-server-sdk/knowledge-sources/strapi`.
|
|
88
|
+
- Import the resource types (`ResourceDefinition`, `ResourceRecord`,
|
|
89
|
+
`ResourceResult` and the others) from
|
|
90
|
+
`@collective-intelligence/external-apps-server-sdk/resources`. This package
|
|
91
|
+
does not re-export them.
|
|
92
|
+
- `DataSourceKind` and `dataSource.kind` are removed: `dataSource` holds only
|
|
93
|
+
`capabilities`.
|
|
94
|
+
- `DataSourceMappingError` has no `invalid_identity` code. A bad Resource id
|
|
95
|
+
throws the server SDK `ResourceIdError`; the adapter still answers
|
|
96
|
+
`invalid_request`.
|
|
97
|
+
- `DataSourceMappingError` is a class that you can import, not only a type:
|
|
98
|
+
`new` and `instanceof` work. The server SDK entry exported only its type.
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { defineStrapiGatewayPlugin, defineStrapiSource } from "./strapi.js";
|
|
2
|
+
export type { StrapiDataSource, StrapiDocumentService, StrapiDocumentServiceFactory, StrapiGatewayHooks, StrapiNativeAction, StrapiParameters, StrapiSourceOptions } from "./strapi.js";
|
|
3
|
+
export { DataSourceMappingError } from "./toolkit/contracts.js";
|
|
4
|
+
export type { DataSourceAdapter, DataSourceBaseOptions, DataSourceCapabilities, DataSourceChange, DataSourceChangePage, DataSourceMappingErrorCode, DataSourceProjection, DataSourceRelation, NativeChange, NativeChangePage, NativeRecord } from "./toolkit/contracts.js";
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { ResourceJsonValue } from "@collective-intelligence/external-apps-server-sdk/resources";
|
|
2
|
+
import type { DataSourceAdapter, DataSourceBaseOptions, NativeChangePage, NativeRecord } from "./toolkit/contracts.js";
|
|
3
|
+
export type StrapiParameters = Readonly<Record<string, ResourceJsonValue>>;
|
|
4
|
+
export interface StrapiDocumentService {
|
|
5
|
+
readonly count: (parameters: StrapiParameters) => Promise<number>;
|
|
6
|
+
readonly create: (parameters: StrapiParameters) => Promise<NativeRecord>;
|
|
7
|
+
readonly delete: (parameters: StrapiParameters) => Promise<NativeRecord>;
|
|
8
|
+
readonly findFirst: (parameters: StrapiParameters) => Promise<NativeRecord | null>;
|
|
9
|
+
readonly findMany: (parameters: StrapiParameters) => Promise<readonly NativeRecord[]>;
|
|
10
|
+
readonly findOne: (parameters: StrapiParameters) => Promise<NativeRecord | null>;
|
|
11
|
+
readonly publish?: (parameters: StrapiParameters) => Promise<NativeRecord>;
|
|
12
|
+
readonly unpublish?: (parameters: StrapiParameters) => Promise<NativeRecord>;
|
|
13
|
+
readonly update: (parameters: StrapiParameters) => Promise<NativeRecord>;
|
|
14
|
+
}
|
|
15
|
+
export interface StrapiDocumentServiceFactory {
|
|
16
|
+
readonly documents: (uid: string) => StrapiDocumentService;
|
|
17
|
+
}
|
|
18
|
+
export type StrapiGatewayHooks = Readonly<{
|
|
19
|
+
changes?: (input: {
|
|
20
|
+
after?: Readonly<{
|
|
21
|
+
externalId: string;
|
|
22
|
+
updatedAt: string;
|
|
23
|
+
}>;
|
|
24
|
+
limit: number;
|
|
25
|
+
locale?: string;
|
|
26
|
+
organizationId: string;
|
|
27
|
+
overlapMs: number;
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
uid: string;
|
|
30
|
+
}) => Promise<NativeChangePage>;
|
|
31
|
+
restore?: (input: {
|
|
32
|
+
documentId: string;
|
|
33
|
+
locale?: string;
|
|
34
|
+
organizationId: string;
|
|
35
|
+
signal?: AbortSignal;
|
|
36
|
+
uid: string;
|
|
37
|
+
}) => Promise<NativeRecord>;
|
|
38
|
+
softDelete?: (input: {
|
|
39
|
+
documentId: string;
|
|
40
|
+
locale?: string;
|
|
41
|
+
organizationId: string;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
uid: string;
|
|
44
|
+
}) => Promise<NativeRecord>;
|
|
45
|
+
}>;
|
|
46
|
+
export type StrapiNativeAction = "create" | "delete" | "find" | "publish" | "restore" | "update";
|
|
47
|
+
export type StrapiSourceOptions<Entity = NativeRecord> = DataSourceBaseOptions<Entity> & Readonly<{
|
|
48
|
+
authorize: (input: {
|
|
49
|
+
action: StrapiNativeAction;
|
|
50
|
+
context: Parameters<DataSourceAdapter["execute"]>[1];
|
|
51
|
+
}) => Promise<void> | void;
|
|
52
|
+
contentType: "collection" | "single";
|
|
53
|
+
documents: StrapiDocumentServiceFactory;
|
|
54
|
+
includeDrafts?: boolean;
|
|
55
|
+
incrementalChanges?: Readonly<{
|
|
56
|
+
overlapMs?: number;
|
|
57
|
+
}>;
|
|
58
|
+
locale?: string;
|
|
59
|
+
localeField?: string;
|
|
60
|
+
plugin?: StrapiGatewayHooks;
|
|
61
|
+
sanitize: (input: {
|
|
62
|
+
action: StrapiNativeAction;
|
|
63
|
+
context: Parameters<DataSourceAdapter["execute"]>[1];
|
|
64
|
+
value: NativeRecord;
|
|
65
|
+
}) => Promise<NativeRecord> | NativeRecord;
|
|
66
|
+
uid: string;
|
|
67
|
+
}>;
|
|
68
|
+
export type StrapiDataSource<Entity = NativeRecord> = DataSourceAdapter<Entity> & Readonly<{
|
|
69
|
+
publication: Readonly<{
|
|
70
|
+
publish?: (input: Readonly<{
|
|
71
|
+
context: Parameters<DataSourceAdapter["execute"]>[1];
|
|
72
|
+
documentId: string;
|
|
73
|
+
locale?: string;
|
|
74
|
+
}>) => Promise<Entity>;
|
|
75
|
+
unpublish?: (input: Readonly<{
|
|
76
|
+
context: Parameters<DataSourceAdapter["execute"]>[1];
|
|
77
|
+
documentId: string;
|
|
78
|
+
locale?: string;
|
|
79
|
+
}>) => Promise<Entity>;
|
|
80
|
+
}>;
|
|
81
|
+
}>;
|
|
82
|
+
export declare const defineStrapiSource: <Entity = NativeRecord>(options: StrapiSourceOptions<Entity>) => StrapiDataSource<Entity>;
|
|
83
|
+
export declare const defineStrapiGatewayPlugin: (hooks: StrapiGatewayHooks) => StrapiGatewayHooks;
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { ResourceJsonValue } from "@collective-intelligence/external-apps-server-sdk/resources";
|
|
2
|
+
/** Writes the opaque value of `value` under `prefix`. */
|
|
3
|
+
export declare const encode: (prefix: string, value: ResourceJsonValue) => string;
|
|
4
|
+
/**
|
|
5
|
+
* Reads an opaque value that `encode` wrote under `prefix`. Only cursors are
|
|
6
|
+
* read, so a value that it cannot read is a paging failure.
|
|
7
|
+
*/
|
|
8
|
+
export declare const decode: (prefix: string, value: string) => ResourceJsonValue;
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { GatewayResourceAuthorization, GatewayResourceDefinition, ResourceDefinition, ResourceJsonValue, ResourceRecord } from "@collective-intelligence/external-apps-server-sdk/resources";
|
|
2
|
+
export type NativeRecord = Readonly<Record<string, ResourceJsonValue>>;
|
|
3
|
+
export type DataSourceCapabilities = Readonly<{
|
|
4
|
+
create: boolean;
|
|
5
|
+
hardDelete: boolean;
|
|
6
|
+
incrementalChanges: boolean;
|
|
7
|
+
nativePolicy: boolean;
|
|
8
|
+
pagination: readonly ("cursor" | "page")[];
|
|
9
|
+
read: true;
|
|
10
|
+
relations: boolean;
|
|
11
|
+
restore: boolean;
|
|
12
|
+
softDelete: boolean;
|
|
13
|
+
transactions: boolean;
|
|
14
|
+
update: boolean;
|
|
15
|
+
}>;
|
|
16
|
+
export type DataSourceRelation = Readonly<{
|
|
17
|
+
cardinality: "many" | "one";
|
|
18
|
+
field: string;
|
|
19
|
+
targetIdentityFields: readonly [string, ...string[]];
|
|
20
|
+
targetResourceId: string;
|
|
21
|
+
}>;
|
|
22
|
+
export type DataSourceProjection = Readonly<{
|
|
23
|
+
fields: readonly string[];
|
|
24
|
+
redact?: readonly string[];
|
|
25
|
+
relations?: readonly DataSourceRelation[];
|
|
26
|
+
}>;
|
|
27
|
+
export type DataSourceChange<Entity> = Readonly<{
|
|
28
|
+
kind: "tombstone";
|
|
29
|
+
deletedAt: string;
|
|
30
|
+
id: string;
|
|
31
|
+
revision: string;
|
|
32
|
+
}> | Readonly<{
|
|
33
|
+
kind: "upsert";
|
|
34
|
+
record: ResourceRecord<Entity>;
|
|
35
|
+
}>;
|
|
36
|
+
export type DataSourceChangePage<Entity> = Readonly<{
|
|
37
|
+
changes: readonly DataSourceChange<Entity>[];
|
|
38
|
+
nextCursor?: string;
|
|
39
|
+
}>;
|
|
40
|
+
export type NativeChange = Readonly<{
|
|
41
|
+
deletedAt: string;
|
|
42
|
+
identity: NativeRecord;
|
|
43
|
+
kind: "tombstone";
|
|
44
|
+
revision: string;
|
|
45
|
+
updatedAt: string;
|
|
46
|
+
}> | Readonly<{
|
|
47
|
+
kind: "upsert";
|
|
48
|
+
row: NativeRecord;
|
|
49
|
+
}>;
|
|
50
|
+
export type NativeChangePage = Readonly<{
|
|
51
|
+
changes: readonly NativeChange[];
|
|
52
|
+
}>;
|
|
53
|
+
export type DataSourceAdapter<Entity = NativeRecord> = GatewayResourceDefinition<Entity> & Readonly<{
|
|
54
|
+
dataSource: Readonly<{
|
|
55
|
+
capabilities: DataSourceCapabilities;
|
|
56
|
+
}>;
|
|
57
|
+
}>;
|
|
58
|
+
export type DataSourceBaseOptions<Entity = NativeRecord> = Readonly<{
|
|
59
|
+
authorization: GatewayResourceAuthorization;
|
|
60
|
+
capabilities: DataSourceCapabilities;
|
|
61
|
+
definition: ResourceDefinition<Entity>;
|
|
62
|
+
identity: Readonly<{
|
|
63
|
+
fields: readonly [string, ...string[]];
|
|
64
|
+
}>;
|
|
65
|
+
maxPageSize?: number;
|
|
66
|
+
projection: DataSourceProjection;
|
|
67
|
+
revision: (record: NativeRecord) => string;
|
|
68
|
+
softDelete?: Readonly<{
|
|
69
|
+
deletedAt: (record: NativeRecord) => string | undefined;
|
|
70
|
+
}>;
|
|
71
|
+
updatedAt: (record: NativeRecord) => string;
|
|
72
|
+
}>;
|
|
73
|
+
export type DataSourceMappingErrorCode = "capability_mismatch" | "duplicate_field" | "invalid_pagination" | "unsupported_mapping";
|
|
74
|
+
export declare class DataSourceMappingError extends TypeError {
|
|
75
|
+
readonly code: DataSourceMappingErrorCode;
|
|
76
|
+
constructor(code: DataSourceMappingErrorCode, message: string);
|
|
77
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { ResourceCapabilities, ResourceJsonValue, ResourceRecord, ResourceResult } from "@collective-intelligence/external-apps-server-sdk/resources";
|
|
2
|
+
import { resourceCapabilityByOperation } from "@collective-intelligence/external-apps-server-sdk/resources";
|
|
3
|
+
import type { DataSourceBaseOptions, NativeRecord } from "./contracts.js";
|
|
4
|
+
export declare const parseJsonValue: (value: unknown) => ResourceJsonValue;
|
|
5
|
+
export declare const opaqueRevision: (kind: string, revision: string) => string;
|
|
6
|
+
export declare const optionalNativeString: (value: ResourceJsonValue | undefined) => string | undefined;
|
|
7
|
+
export declare const cursor: (kind: string, value: ResourceJsonValue) => string;
|
|
8
|
+
export declare const decodeCursor: <Value>(kind: string, value: string) => Value;
|
|
9
|
+
export declare const record: <Entity>(kind: string, options: DataSourceBaseOptions<Entity>, row: NativeRecord) => ResourceRecord<Entity>;
|
|
10
|
+
/** Restores the camelCase operator spelling native data sources expect. */
|
|
11
|
+
export declare const nativeFilterOperator: (operator: string) => string;
|
|
12
|
+
export declare const unsupportedOperation: (correlationId: string, capabilities: ResourceCapabilities, operation: keyof typeof resourceCapabilityByOperation) => ResourceResult<never> | undefined;
|
|
13
|
+
export declare const conflict: (correlationId: string) => ResourceResult<never>;
|
|
14
|
+
export declare const invalid: (correlationId: string, cause: unknown) => ResourceResult<never>;
|
|
15
|
+
export declare const nativeFailure: (correlationId: string, cause: unknown) => ResourceResult<never>;
|
|
16
|
+
export declare const assertConfiguration: <Entity>(options: DataSourceBaseOptions<Entity>) => void;
|
|
17
|
+
export declare const boundedLimit: (requested: number, maximum?: number) => number;
|
|
18
|
+
export declare const expectedRevisionMatches: <Entity>(kind: string, options: DataSourceBaseOptions<Entity>, row: NativeRecord, expectedRevision: string) => boolean;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./index/declarations/index.js"
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{decodeResourceId,encodeResourceId as encodeResourceId2,resourceSuccess}from"@collective-intelligence/external-apps-server-sdk/resources";import{encodeResourceId,isResourceJsonValue as isResourceJsonValue2,resourceCapabilityByOperation,resourceFailure}from"@collective-intelligence/external-apps-server-sdk/resources";import{isResourceJsonValue}from"@collective-intelligence/external-apps-server-sdk/resources";class DataSourceMappingError extends TypeError{code;constructor(code,message){super(message);this.name="DataSourceMappingError";this.code=code}}var encode=(prefix,value)=>`${prefix}.${Buffer.from(JSON.stringify(value)).toString("base64url")}`;var decode=(prefix,value)=>{if(!value.startsWith(`${prefix}.`)){throw new DataSourceMappingError("invalid_pagination",`Expected an opaque ${prefix} identifier`)}try{const parsed=JSON.parse(Buffer.from(value.slice(prefix.length+1),"base64url").toString("utf-8"));if(isResourceJsonValue(parsed)){return parsed}}catch{}throw new DataSourceMappingError("invalid_pagination",`Invalid opaque ${prefix} identifier`)};var parseJsonValue=(value)=>{if(!isResourceJsonValue2(value)){throw new DataSourceMappingError("unsupported_mapping","Value must be JSON-compatible")}return value};var opaqueRevision=(kind,revision)=>encode(`${kind}:rev`,revision);var optionalNativeString=(value)=>typeof value==="string"?value:undefined;var cursor=(kind,value)=>encode(`${kind}:cursor`,value);var decodeCursor=(kind,value)=>decode(`${kind}:cursor`,value);var projectedRelation=(kind,relation,value)=>{const normalize=(record)=>{if(typeof record!=="object"||record===null){throw new DataSourceMappingError("unsupported_mapping",`Relation ${relation.field} requires an object identity`)}const nativeRecord=Object.fromEntries(Object.entries(record));return encodeResourceId(`${kind}:${relation.targetResourceId}`,relation.targetIdentityFields,nativeRecord)};if(relation.cardinality==="many"){if(!Array.isArray(value)){throw new DataSourceMappingError("unsupported_mapping",`Relation ${relation.field} requires an array`)}return value.map(normalize)}return value===null||value===undefined?null:normalize(value)};var project=(kind,projection,row)=>{const redacted=new Set(projection.redact);const relations=new Map((projection.relations??[]).map((relation)=>[relation.field,relation]));const entries=[];for(const field of projection.fields){if(redacted.has(field)){continue}const value=row[field];const relation=relations.get(field);if(relation!==undefined){entries.push([field,projectedRelation(kind,relation,value)]);continue}if(value===undefined){continue}if(!isResourceJsonValue2(value)){throw new DataSourceMappingError("unsupported_mapping",`Field ${field} is not JSON-compatible`)}entries.push([field,value])}return Object.fromEntries(entries)};var record=(kind,options,row)=>{const deletedAt=options.softDelete?.deletedAt(row);const result={id:encodeResourceId(kind,options.identity.fields,row),revision:opaqueRevision(kind,options.revision(row)),value:project(kind,options.projection,row)};if(deletedAt!==undefined){result.deletedAt=deletedAt}return result};var nativeFilterOperator=(operator)=>operator.replaceAll(/_(?<letter>[a-z])/gu,(_match,letter)=>letter.toUpperCase());var unsupportedOperation=(correlationId,capabilities,operation)=>{const capability=resourceCapabilityByOperation[operation];if(capabilities[capability]===true){return}return resourceFailure(correlationId,{code:"capability_not_supported",details:{capability},message:`The data source does not support ${capability}`,retryable:false})};var conflict=(correlationId)=>resourceFailure(correlationId,{code:"conflict",message:"The expected revision does not match the current record",retryable:false});var invalid=(correlationId,cause)=>resourceFailure(correlationId,{code:"invalid_request",details:{cause:cause instanceof Error?cause.message:String(cause)},message:"The data-source request is invalid",retryable:false});var nativeFailure=(correlationId,cause)=>resourceFailure(correlationId,{code:"internal",details:{cause:cause instanceof Error?cause.message:String(cause)},message:"The native data source failed",retryable:false});var assertConfiguration=(options)=>{const fields=[...options.projection.fields,...options.projection.redact??[]];if(new Set(fields).size!==fields.length){throw new DataSourceMappingError("duplicate_field","Exposed and redacted fields must be disjoint and unique")}const maxPageSize=options.maxPageSize??100;if(!Number.isSafeInteger(maxPageSize)||maxPageSize<1){throw new DataSourceMappingError("invalid_pagination","maxPageSize must be a positive safe integer")}if(options.capabilities.pagination.length===0){throw new DataSourceMappingError("invalid_pagination","At least one pagination mode must be declared")}const declaredPagination=new Set(options.definition.query.pagination.modes);if(declaredPagination.size!==options.capabilities.pagination.length||options.capabilities.pagination.some((mode)=>!declaredPagination.has(mode))){throw new DataSourceMappingError("capability_mismatch","Data-source pagination must match the resource definition")}if(options.capabilities.relations!==(options.projection.relations?.length??0)>0){throw new DataSourceMappingError("capability_mismatch","Relation capability must match the explicit relation projection")}for(const capability of["create","hardDelete","restore","softDelete","update"]){if(options.capabilities[capability]!==(options.definition.capabilities[capability]===true)){throw new DataSourceMappingError("capability_mismatch",`${capability} capability must match the resource definition`)}}};var boundedLimit=(requested,maximum=100)=>{if(!Number.isSafeInteger(requested)||requested<1){throw new DataSourceMappingError("invalid_pagination","Page size must be a positive safe integer")}return Math.min(requested,maximum)};var expectedRevisionMatches=(kind,options,row,expectedRevision)=>opaqueRevision(kind,options.revision(row))===expectedRevision;var nativeFilter=(filter)=>{if("filters"in filter){return{...filter,filters:filter.filters.map(nativeFilter)}}if("filter"in filter){return{...filter,filter:nativeFilter(filter.filter)}}return{...filter,operator:nativeFilterOperator(filter.operator)}};var kind="strapi";var optionalProperty=(key,value)=>value===undefined?{}:{[key]:value};var documentId=(identity)=>{const value=identity.documentId;const documentIdentifier=optionalNativeString(value);if(documentIdentifier===undefined||documentIdentifier.length===0){throw new TypeError("Strapi identity must contain documentId")}return documentIdentifier};var localeFor=(options,identity)=>{if(options.localeField!==undefined&&identity!==undefined){const value=identity[options.localeField];const localeValue=optionalNativeString(value);if(localeValue!==undefined){return localeValue}}return options.locale};var validateStrapi=(options)=>{if(options.identity.fields[0]!=="documentId"){throw new TypeError("Strapi identity must prefer documentId")}if(!options.capabilities.nativePolicy){throw new TypeError("Strapi must declare nativePolicy support")}if(options.capabilities.transactions||options.capabilities.softDelete!==(options.softDelete!==undefined)){throw new TypeError("Strapi transaction and soft-delete capabilities require explicit policy")}if(options.capabilities.softDelete!==(options.plugin?.softDelete!==undefined)||options.capabilities.restore!==(options.plugin?.restore!==undefined)||options.capabilities.incrementalChanges!==(options.plugin?.changes!==undefined)){throw new TypeError("Strapi capabilities must match installed plugin hooks")}};var paginationStart=(pagination)=>{if(pagination.mode==="cursor"){return pagination.cursor===undefined?0:decodeCursor(kind,pagination.cursor)}return(pagination.page-1)*pagination.pageSize};var defineStrapiSource=(options)=>{assertConfiguration(options);validateStrapi(options);const maximum=options.maxPageSize??100;const documents=options.documents.documents(options.uid);const published=options.includeDrafts===true?"draft":"published";const sanitizedRecord=async(action,context,row)=>record(kind,options,await options.sanitize({action,context,value:row}));const executeList=async(request,context,publishedStatus)=>{await options.authorize({action:"find",context});const{pagination}=request.query;const limit=boundedLimit(pagination.mode==="cursor"?pagination.limit:pagination.pageSize,maximum);const start=paginationStart(pagination);const parameters={...optionalProperty("filters",request.query.filter===undefined?undefined:nativeFilter(request.query.filter)),limit,...optionalProperty("locale",options.locale),start,status:publishedStatus,...optionalProperty("sort",request.query.sort?.map(({direction,field})=>`${field}:${direction}`))};let rows;if(options.contentType==="single"){const single=await documents.findFirst(parameters);rows=single===null?[]:[single]}else{rows=await documents.findMany(parameters)}const items=await Promise.all(rows.map(async(row)=>await sanitizedRecord("find",context,row)));if(pagination.mode==="page"){const totalItems=options.contentType==="single"?items.length:await documents.count(parameters);return resourceSuccess(request.requestId,{items,page:pagination.page,pageSize:pagination.pageSize,pagination:"page",totalItems,totalPages:Math.ceil(totalItems/pagination.pageSize)})}return resourceSuccess(request.requestId,{items,...optionalProperty("nextCursor",items.length<limit?undefined:cursor(kind,start+items.length)),pagination:"cursor"})};const lifecycleMethod=(operation)=>operation==="restore"?options.plugin?.restore:options.plugin?.softDelete;const execute=async(request,context,requestOptions)=>{const unsupported=unsupportedOperation(request.requestId,options.definition.capabilities,request.operation);if(unsupported!==undefined){return unsupported}try{if(request.operation==="list"){return await executeList(request,context,published)}if(request.operation==="create"){await options.authorize({action:"create",context});const row=await documents.create({data:parseJsonValue(request.value),...optionalProperty("locale",options.locale),status:published});return resourceSuccess(request.requestId,await sanitizedRecord("create",context,row))}const identity=decodeResourceId(kind,options.identity.fields,request.id);const id=documentId(identity);const locale=localeFor(options,identity);await options.authorize({action:"find",context});const current=await documents.findOne({documentId:id,...optionalProperty("locale",locale),status:published});if(current===null){return{correlationId:request.requestId,error:{code:"not_found",message:"The Strapi document was not found",retryable:false},ok:false}}if(request.operation==="get"){return resourceSuccess(request.requestId,await sanitizedRecord("find",context,current))}if(!expectedRevisionMatches(kind,options,current,request.expectedRevision)){return conflict(request.requestId)}if(request.operation==="update"){await options.authorize({action:"update",context});const row=await documents.update({data:parseJsonValue(request.value),documentId:id,...optionalProperty("locale",locale),status:published});return resourceSuccess(request.requestId,await sanitizedRecord("update",context,row))}if(request.operation==="hard_delete"){await options.authorize({action:"delete",context});await documents.delete({documentId:id,...optionalProperty("locale",locale)});return resourceSuccess(request.requestId,null)}const action=request.operation==="restore"?"restore":"delete";await options.authorize({action,context});const method=lifecycleMethod(request.operation==="restore"?"restore":"soft_delete");const row=await method?.({documentId:id,...optionalProperty("locale",locale),organizationId:context.organizationId,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(row===undefined){throw new TypeError(`${request.operation} is not supported`)}return resourceSuccess(request.requestId,await sanitizedRecord(action,context,row))}catch(error){return error instanceof TypeError?invalid(request.requestId,error):nativeFailure(request.requestId,error)}};const publication=(action)=>{const method=documents[action];return method===undefined?undefined:async(input)=>{await options.authorize({action:"publish",context:input.context});const row=await method({documentId:input.documentId,...optionalProperty("locale",input.locale)});const sanitized=await sanitizedRecord("publish",input.context,row);return sanitized.value}};const changes=options.plugin?.changes===undefined?undefined:async(request,context,requestOptions)=>{try{await options.authorize({action:"find",context});const after=request.cursor===undefined?undefined:decodeCursor(`${kind}:changes`,request.cursor);const page=await options.plugin?.changes?.({...optionalProperty("after",after),limit:boundedLimit(request.limit,maximum),...optionalProperty("locale",options.locale),organizationId:context.organizationId,overlapMs:options.incrementalChanges?.overlapMs??5000,...optionalProperty("signal",requestOptions?.signal),uid:options.uid});if(page===undefined){throw new TypeError("Changes are unavailable")}const projectedChanges=await Promise.all(page.changes.map(async(change)=>change.kind==="upsert"?{kind:"upsert",record:await sanitizedRecord("find",context,change.row)}:{deletedAt:change.deletedAt,id:encodeResourceId2(kind,options.identity.fields,change.identity),kind:"tombstone",revision:opaqueRevision(kind,change.revision)}));const final=page.changes.at(-1);const nextCursor=final===undefined?undefined:cursor(`${kind}:changes`,{externalId:final.kind==="upsert"?encodeResourceId2(kind,options.identity.fields,final.row):encodeResourceId2(kind,options.identity.fields,final.identity),updatedAt:final.kind==="upsert"?options.updatedAt(final.row):final.updatedAt});return resourceSuccess(request.requestId,{changes:projectedChanges,...optionalProperty("nextCursor",nextCursor)})}catch(error){return invalid(request.requestId,error)}};const publish=publication("publish");const unpublish=publication("unpublish");const source={authorization:options.authorization,...optionalProperty("changes",changes),dataSource:{capabilities:options.capabilities},definition:options.definition,execute,publication:{...optionalProperty("publish",publish),...optionalProperty("unpublish",unpublish)}};return Object.freeze(source)};var defineStrapiGatewayPlugin=(hooks)=>Object.freeze(hooks);export{DataSourceMappingError,defineStrapiGatewayPlugin,defineStrapiSource};
|
package/package.json
CHANGED
|
@@ -1,6 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@collective-intelligence/external-apps-server-sdk-strapi",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.13.1",
|
|
4
|
+
"description": "The Strapi SDK: the CMS SDK that connects a Strapi 5 site to Collective Intelligence through a Gateway.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"sideEffects": false,
|
|
7
|
+
"files": [
|
|
8
|
+
"dist",
|
|
9
|
+
"README.md"
|
|
10
|
+
],
|
|
11
|
+
"main": "./dist/index.js",
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"ci-source": "./src/index.ts",
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js",
|
|
18
|
+
"default": "./dist/index.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"scripts": {
|
|
22
|
+
"build": "bun tools/build.ts",
|
|
23
|
+
"test": "bun run test:unit && bun run test:pack",
|
|
24
|
+
"test:pack": "bun tools/test-pack.ts",
|
|
25
|
+
"test:unit": "bun --conditions=ci-source test src test/imports.test.ts test/manifest.test.ts",
|
|
26
|
+
"format": "oxfmt --write .",
|
|
27
|
+
"format:check": "oxfmt --check .",
|
|
28
|
+
"format:check:staged": "oxfmt --check",
|
|
29
|
+
"lint": "node \"../../../.agents/scripts/managed-lint-runner.mjs\" --scope \"packages/public/external-apps-server-sdk-strapi\"",
|
|
30
|
+
"lint:staged": "oxlint --no-error-on-unmatched-pattern",
|
|
31
|
+
"prepack": "bun run build",
|
|
32
|
+
"type-check": "bun check --no-script -p tsconfig.json"
|
|
33
|
+
},
|
|
34
|
+
"dependencies": {
|
|
35
|
+
"@collective-intelligence/external-apps-server-sdk": "0.13.1"
|
|
36
|
+
},
|
|
37
|
+
"peerDependencies": {
|
|
38
|
+
"@strapi/strapi": ">=5 <6"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"@strapi/strapi": {
|
|
42
|
+
"optional": true
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"publishConfig": {
|
|
46
|
+
"access": "public"
|
|
47
|
+
},
|
|
48
|
+
"devDependencies": {
|
|
49
|
+
"@effect/eslint-plugin": "0.3.2",
|
|
50
|
+
"@oxlint/plugins": "1.94.0",
|
|
51
|
+
"@punks/lints": "0.2.0",
|
|
52
|
+
"@types/bun": "1.4.2",
|
|
53
|
+
"@types/node": "25.9.7",
|
|
54
|
+
"@typescript-eslint/utils": "8.22.0",
|
|
55
|
+
"eslint": "9.39.5",
|
|
56
|
+
"oxfmt": "0.66.0",
|
|
57
|
+
"oxlint": "1.94.0",
|
|
58
|
+
"typescript": "5.9.3",
|
|
59
|
+
"ultracite": "7.10.7"
|
|
60
|
+
},
|
|
61
|
+
"gitHead": "3dc11c5a7be499eb0ac6776ab75a904cb2c8bb74"
|
|
62
|
+
}
|