@voyantjs/plugin-sanity-cms 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +109 -0
- package/README.md +43 -0
- package/dist/src/client.d.ts +54 -0
- package/dist/src/client.d.ts.map +1 -0
- package/dist/src/client.js +91 -0
- package/dist/src/index.d.ts +6 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +2 -0
- package/dist/src/plugin.d.ts +61 -0
- package/dist/src/plugin.d.ts.map +1 -0
- package/dist/src/plugin.js +85 -0
- package/dist/src/types.d.ts +31 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/types.js +1 -0
- package/dist/tests/unit/client.test.d.ts +2 -0
- package/dist/tests/unit/client.test.d.ts.map +1 -0
- package/dist/tests/unit/client.test.js +201 -0
- package/dist/tests/unit/plugin.test.d.ts +2 -0
- package/dist/tests/unit/plugin.test.d.ts.map +1 -0
- package/dist/tests/unit/plugin.test.js +183 -0
- package/package.json +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, Apache 2.0 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-Apache-2.0
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 PixelMakers Studio SRL
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly
|
|
28
|
+
display and redistribute the Software for any Permitted Purpose identified
|
|
29
|
+
below.
|
|
30
|
+
|
|
31
|
+
### Permitted Purpose
|
|
32
|
+
|
|
33
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing
|
|
34
|
+
Use means making the Software available to others in a commercial product or
|
|
35
|
+
service that:
|
|
36
|
+
|
|
37
|
+
1. substitutes for the Software;
|
|
38
|
+
|
|
39
|
+
2. substitutes for any other product or service we offer using the Software
|
|
40
|
+
that exists as of the date we make the Software available; or
|
|
41
|
+
|
|
42
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
43
|
+
|
|
44
|
+
Permitted Purposes specifically include using the Software:
|
|
45
|
+
|
|
46
|
+
1. for your internal use and access;
|
|
47
|
+
|
|
48
|
+
2. for non-commercial education;
|
|
49
|
+
|
|
50
|
+
3. for non-commercial research; and
|
|
51
|
+
|
|
52
|
+
4. in connection with professional services that you provide to a licensee
|
|
53
|
+
using the Software in accordance with these Terms and Conditions.
|
|
54
|
+
|
|
55
|
+
### Patents
|
|
56
|
+
|
|
57
|
+
To the extent your use for a Permitted Purpose would necessarily infringe
|
|
58
|
+
our patents, the license grant above includes a license under our patents.
|
|
59
|
+
If you make a claim against any party that the Software infringes or
|
|
60
|
+
contributes to the infringement of any patent, then your patent license to
|
|
61
|
+
the Software ends immediately.
|
|
62
|
+
|
|
63
|
+
### Redistribution
|
|
64
|
+
|
|
65
|
+
The Terms and Conditions apply to all copies, modifications and derivatives
|
|
66
|
+
of the Software.
|
|
67
|
+
|
|
68
|
+
If you redistribute any copies, modifications or derivatives of the
|
|
69
|
+
Software, you must include a copy of or a link to these Terms and Conditions
|
|
70
|
+
and not remove any copyright notices provided in or with the Software.
|
|
71
|
+
|
|
72
|
+
### Disclaimer
|
|
73
|
+
|
|
74
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS
|
|
75
|
+
OR IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A
|
|
76
|
+
PARTICULAR PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
77
|
+
|
|
78
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO
|
|
79
|
+
THE SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
|
|
80
|
+
DAMAGES, EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
81
|
+
|
|
82
|
+
### Trademarks
|
|
83
|
+
|
|
84
|
+
Except for displaying the License Details and identifying us as the origin
|
|
85
|
+
of the Software, you have no right under these Terms and Conditions to use
|
|
86
|
+
our trademarks, trade names, service marks or product names.
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## Grant of Future License
|
|
91
|
+
|
|
92
|
+
We hereby irrevocably grant you an additional license to use the Software
|
|
93
|
+
under the Apache License, Version 2.0 that is effective on the second
|
|
94
|
+
anniversary of the date we make the Software available. On or after that
|
|
95
|
+
date, you may use the Software under the Apache License, Version 2.0, in
|
|
96
|
+
which case the following will apply:
|
|
97
|
+
|
|
98
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not
|
|
99
|
+
use this file except in compliance with the License.
|
|
100
|
+
|
|
101
|
+
You may obtain a copy of the License at
|
|
102
|
+
|
|
103
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
104
|
+
|
|
105
|
+
Unless required by applicable law or agreed to in writing, software
|
|
106
|
+
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
107
|
+
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
|
108
|
+
License for the specific language governing permissions and limitations
|
|
109
|
+
under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# @voyantjs/plugin-sanity-cms
|
|
2
|
+
|
|
3
|
+
Sanity CMS sync plugin for Voyant. Subscribes to module events and mirrors documents into a Sanity dataset keyed by a `voyantId` field.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @voyantjs/plugin-sanity-cms
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
```typescript
|
|
14
|
+
import { sanityCmsPlugin } from "@voyantjs/plugin-sanity-cms"
|
|
15
|
+
import { createApp } from "@voyantjs/hono"
|
|
16
|
+
|
|
17
|
+
const app = createApp({
|
|
18
|
+
plugins: [
|
|
19
|
+
sanityCmsPlugin({
|
|
20
|
+
projectId: env.SANITY_PROJECT_ID,
|
|
21
|
+
dataset: "production",
|
|
22
|
+
token: env.SANITY_TOKEN,
|
|
23
|
+
documentType: "product",
|
|
24
|
+
// optional: apiVersion, voyantIdField, apiHost, events, mapEvent, logger
|
|
25
|
+
}),
|
|
26
|
+
],
|
|
27
|
+
})
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
Uses GROQ for reads and Sanity Mutations API for writes. Default `apiVersion` is `"2024-01-01"`. By default the plugin wires up 3 subscribers (`product.created`, `product.updated`, `product.deleted`).
|
|
31
|
+
|
|
32
|
+
## Exports
|
|
33
|
+
|
|
34
|
+
| Entry | Description |
|
|
35
|
+
| --- | --- |
|
|
36
|
+
| `.` | Barrel re-exports |
|
|
37
|
+
| `./plugin` | `sanityCmsPlugin(options)` |
|
|
38
|
+
| `./client` | `createSanityClient` — `upsertByVoyantId`, `deleteByVoyantId`, `findByVoyantId` |
|
|
39
|
+
| `./types` | Plugin option types |
|
|
40
|
+
|
|
41
|
+
## License
|
|
42
|
+
|
|
43
|
+
FSL-1.1-Apache-2.0
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { SanityDocBody, SanityFetch } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Options for {@link createSanityClient}.
|
|
4
|
+
*/
|
|
5
|
+
export interface SanityClientOptions {
|
|
6
|
+
/** Sanity project ID (the short slug from sanity.io/manage). */
|
|
7
|
+
projectId: string;
|
|
8
|
+
/** Sanity dataset (e.g. `"production"`). */
|
|
9
|
+
dataset: string;
|
|
10
|
+
/**
|
|
11
|
+
* Sanity API token with write access. Sent as
|
|
12
|
+
* `Authorization: Bearer ${token}`.
|
|
13
|
+
*/
|
|
14
|
+
token: string;
|
|
15
|
+
/**
|
|
16
|
+
* Sanity API version (date-based, e.g. `"2024-01-01"`). Defaults to
|
|
17
|
+
* `"2024-01-01"`.
|
|
18
|
+
*/
|
|
19
|
+
apiVersion?: string;
|
|
20
|
+
/**
|
|
21
|
+
* Field on the Sanity document that stores the Voyant record's ID.
|
|
22
|
+
* Defaults to `"voyantId"`. A matching field (+unique index) must be
|
|
23
|
+
* declared in the Sanity schema.
|
|
24
|
+
*/
|
|
25
|
+
voyantIdField?: string;
|
|
26
|
+
/**
|
|
27
|
+
* Sanity API host. Defaults to `"api.sanity.io"`. Override for regional
|
|
28
|
+
* hosts, proxies, or self-hosted deployments.
|
|
29
|
+
*/
|
|
30
|
+
apiHost?: string;
|
|
31
|
+
/** Override `fetch` (e.g. in tests). Defaults to global `fetch`. */
|
|
32
|
+
fetch?: SanityFetch;
|
|
33
|
+
}
|
|
34
|
+
export interface SanityClient {
|
|
35
|
+
/**
|
|
36
|
+
* Create or replace a document whose {@link SanityClientOptions.voyantIdField}
|
|
37
|
+
* equals `voyantId`.
|
|
38
|
+
*/
|
|
39
|
+
upsertByVoyantId(documentType: string, voyantId: string, body: SanityDocBody): Promise<{
|
|
40
|
+
_id: string;
|
|
41
|
+
created: boolean;
|
|
42
|
+
}>;
|
|
43
|
+
/**
|
|
44
|
+
* Delete a document whose `voyantId` field equals the given value.
|
|
45
|
+
* Returns `false` if no matching document was found.
|
|
46
|
+
*/
|
|
47
|
+
deleteByVoyantId(documentType: string, voyantId: string): Promise<boolean>;
|
|
48
|
+
/** Find at most one document whose `voyantId` field equals the given value. */
|
|
49
|
+
findByVoyantId(documentType: string, voyantId: string): Promise<{
|
|
50
|
+
_id: string;
|
|
51
|
+
} | null>;
|
|
52
|
+
}
|
|
53
|
+
export declare function createSanityClient(options: SanityClientOptions): SanityClient;
|
|
54
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AAE5D;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,gEAAgE;IAChE,SAAS,EAAE,MAAM,CAAA;IACjB,4CAA4C;IAC5C,OAAO,EAAE,MAAM,CAAA;IACf;;;OAGG;IACH,KAAK,EAAE,MAAM,CAAA;IACb;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB;;;;OAIG;IACH,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,oEAAoE;IACpE,KAAK,CAAC,EAAE,WAAW,CAAA;CACpB;AAWD,MAAM,WAAW,YAAY;IAC3B;;;OAGG;IACH,gBAAgB,CACd,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,aAAa,GAClB,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAA;IAC7C;;;OAGG;IACH,gBAAgB,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAA;IAC1E,+EAA+E;IAC/E,cAAc,CAAC,YAAY,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,CAAC,CAAA;CACxF;AAED,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,mBAAmB,GAAG,YAAY,CAiH7E"}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export function createSanityClient(options) {
|
|
2
|
+
const apiVersion = options.apiVersion ?? "2024-01-01";
|
|
3
|
+
const voyantIdField = options.voyantIdField ?? "voyantId";
|
|
4
|
+
const apiHost = options.apiHost ?? "api.sanity.io";
|
|
5
|
+
const baseUrl = `https://${options.projectId}.${apiHost}/v${apiVersion}/data`;
|
|
6
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
7
|
+
function headers() {
|
|
8
|
+
return {
|
|
9
|
+
Authorization: `Bearer ${options.token}`,
|
|
10
|
+
"Content-Type": "application/json",
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
async function request(method, path, body) {
|
|
14
|
+
if (!fetchImpl) {
|
|
15
|
+
throw new Error("Sanity client requires a fetch implementation");
|
|
16
|
+
}
|
|
17
|
+
const init = {
|
|
18
|
+
method,
|
|
19
|
+
headers: headers(),
|
|
20
|
+
};
|
|
21
|
+
if (body !== undefined)
|
|
22
|
+
init.body = JSON.stringify(body);
|
|
23
|
+
const response = await fetchImpl(`${baseUrl}${path}`, init);
|
|
24
|
+
let text = "";
|
|
25
|
+
let json = null;
|
|
26
|
+
try {
|
|
27
|
+
text = await response.text();
|
|
28
|
+
json = text ? JSON.parse(text) : null;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
// leave json as null, surface text
|
|
32
|
+
}
|
|
33
|
+
return { ok: response.ok, status: response.status, json, text };
|
|
34
|
+
}
|
|
35
|
+
async function findByVoyantId(documentType, voyantId) {
|
|
36
|
+
// GROQ parameters are JSON-encoded values attached as $-prefixed query params.
|
|
37
|
+
const groq = `*[_type == $type && ${voyantIdField} == $vid][0]{_id}`;
|
|
38
|
+
const query = [
|
|
39
|
+
`query=${encodeURIComponent(groq)}`,
|
|
40
|
+
`$type=${encodeURIComponent(JSON.stringify(documentType))}`,
|
|
41
|
+
`$vid=${encodeURIComponent(JSON.stringify(voyantId))}`,
|
|
42
|
+
].join("&");
|
|
43
|
+
const res = await request("GET", `/query/${options.dataset}?${query}`);
|
|
44
|
+
if (!res.ok) {
|
|
45
|
+
throw new Error(`Sanity findByVoyantId(${documentType}) failed (${res.status}): ${res.text}`);
|
|
46
|
+
}
|
|
47
|
+
const body = (res.json ?? {});
|
|
48
|
+
const first = body.result;
|
|
49
|
+
if (!first)
|
|
50
|
+
return null;
|
|
51
|
+
return { _id: first._id };
|
|
52
|
+
}
|
|
53
|
+
async function mutate(mutations) {
|
|
54
|
+
return request("POST", `/mutate/${options.dataset}?returnIds=true&visibility=sync`, {
|
|
55
|
+
mutations,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async function upsertByVoyantId(documentType, voyantId, body) {
|
|
59
|
+
const existing = await findByVoyantId(documentType, voyantId);
|
|
60
|
+
const docFields = { ...body, [voyantIdField]: voyantId };
|
|
61
|
+
if (existing) {
|
|
62
|
+
const res = await mutate([{ patch: { id: existing._id, set: docFields } }]);
|
|
63
|
+
if (!res.ok) {
|
|
64
|
+
throw new Error(`Sanity update(${documentType}/${existing._id}) failed (${res.status}): ${res.text}`);
|
|
65
|
+
}
|
|
66
|
+
return { _id: existing._id, created: false };
|
|
67
|
+
}
|
|
68
|
+
const createDoc = { _type: documentType, ...docFields };
|
|
69
|
+
const res = await mutate([{ create: createDoc }]);
|
|
70
|
+
if (!res.ok) {
|
|
71
|
+
throw new Error(`Sanity create(${documentType}) failed (${res.status}): ${res.text}`);
|
|
72
|
+
}
|
|
73
|
+
const json = (res.json ?? {});
|
|
74
|
+
const id = json.results?.[0]?.id;
|
|
75
|
+
if (!id) {
|
|
76
|
+
throw new Error(`Sanity create(${documentType}) response missing id`);
|
|
77
|
+
}
|
|
78
|
+
return { _id: id, created: true };
|
|
79
|
+
}
|
|
80
|
+
async function deleteByVoyantId(documentType, voyantId) {
|
|
81
|
+
const existing = await findByVoyantId(documentType, voyantId);
|
|
82
|
+
if (!existing)
|
|
83
|
+
return false;
|
|
84
|
+
const res = await mutate([{ delete: { id: existing._id } }]);
|
|
85
|
+
if (!res.ok) {
|
|
86
|
+
throw new Error(`Sanity delete(${documentType}/${existing._id}) failed (${res.status}): ${res.text}`);
|
|
87
|
+
}
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
return { upsertByVoyantId, deleteByVoyantId, findByVoyantId };
|
|
91
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { SanityClient, SanityClientOptions } from "./client.js";
|
|
2
|
+
export { createSanityClient } from "./client.js";
|
|
3
|
+
export type { SanityCmsPluginOptions, SanityLogger, SanityMapFn, SanitySyncEventNames, } from "./plugin.js";
|
|
4
|
+
export { sanityCmsPlugin } from "./plugin.js";
|
|
5
|
+
export type { SanityDocBody, SanityFetch, VoyantEntityEvent } from "./types.js";
|
|
6
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAA;AACpE,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAA;AAChD,YAAY,EACV,sBAAsB,EACtB,YAAY,EACZ,WAAW,EACX,oBAAoB,GACrB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAC7C,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA"}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Plugin } from "@voyantjs/core";
|
|
2
|
+
import { type SanityClientOptions } from "./client.js";
|
|
3
|
+
import type { SanityDocBody, VoyantEntityEvent } from "./types.js";
|
|
4
|
+
/**
|
|
5
|
+
* Event names the plugin subscribes to. Defaults match the
|
|
6
|
+
* `<resource>.<pastTenseAction>` naming convention documented by the
|
|
7
|
+
* EventBus contract.
|
|
8
|
+
*/
|
|
9
|
+
export interface SanitySyncEventNames {
|
|
10
|
+
created?: string;
|
|
11
|
+
updated?: string;
|
|
12
|
+
deleted?: string;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Mapper from a Voyant event payload (assumed to carry at least `id: string`)
|
|
16
|
+
* to a Sanity document body. The `voyantId` field + `_type` are injected
|
|
17
|
+
* automatically by the client — do not set either here.
|
|
18
|
+
*/
|
|
19
|
+
export type SanityMapFn = (event: VoyantEntityEvent) => SanityDocBody;
|
|
20
|
+
/**
|
|
21
|
+
* Logger shape used to surface plugin errors without coupling to any specific
|
|
22
|
+
* runtime. Defaults to `console`.
|
|
23
|
+
*/
|
|
24
|
+
export interface SanityLogger {
|
|
25
|
+
error: (message: string, meta?: unknown) => void;
|
|
26
|
+
info?: (message: string, meta?: unknown) => void;
|
|
27
|
+
}
|
|
28
|
+
export interface SanityCmsPluginOptions extends SanityClientOptions {
|
|
29
|
+
/**
|
|
30
|
+
* Sanity document type to sync Voyant records into (e.g. `"product"`).
|
|
31
|
+
* Equivalent to a Payload collection / content model.
|
|
32
|
+
*/
|
|
33
|
+
documentType: string;
|
|
34
|
+
/**
|
|
35
|
+
* Event names this plugin subscribes to. Defaults to
|
|
36
|
+
* `product.created` / `product.updated` / `product.deleted`.
|
|
37
|
+
*/
|
|
38
|
+
events?: SanitySyncEventNames;
|
|
39
|
+
/**
|
|
40
|
+
* Map a Voyant event payload into a Sanity document body. Defaults to
|
|
41
|
+
* passing through every property except `id` (which becomes `voyantId`).
|
|
42
|
+
*/
|
|
43
|
+
mapEvent?: SanityMapFn;
|
|
44
|
+
/** Override logger. Defaults to `console`. */
|
|
45
|
+
logger?: SanityLogger;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Build a Voyant {@link Plugin} that pushes event payloads to a Sanity
|
|
49
|
+
* document type, keyed by `voyantId` for idempotent upserts.
|
|
50
|
+
*
|
|
51
|
+
* The plugin subscribes to three events (configurable via
|
|
52
|
+
* {@link SanityCmsPluginOptions.events}):
|
|
53
|
+
* - `product.created` → upsert document
|
|
54
|
+
* - `product.updated` → upsert document
|
|
55
|
+
* - `product.deleted` → delete document by `voyantId`
|
|
56
|
+
*
|
|
57
|
+
* Errors are caught and logged — subscribers are fire-and-forget per the
|
|
58
|
+
* EventBus contract, so a Sanity outage never blocks the emitter.
|
|
59
|
+
*/
|
|
60
|
+
export declare function sanityCmsPlugin(options: SanityCmsPluginOptions): Plugin;
|
|
61
|
+
//# sourceMappingURL=plugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.d.ts","sourceRoot":"","sources":["../../src/plugin.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAc,MAAM,gBAAgB,CAAA;AAExD,OAAO,EAAsB,KAAK,mBAAmB,EAAE,MAAM,aAAa,CAAA;AAC1E,OAAO,KAAK,EAAE,aAAa,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAA;AAElE;;;;GAIG;AACH,MAAM,WAAW,oBAAoB;IACnC,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB;AAED;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,iBAAiB,KAAK,aAAa,CAAA;AAErE;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,KAAK,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;IAChD,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,OAAO,KAAK,IAAI,CAAA;CACjD;AAED,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IACjE;;;OAGG;IACH,YAAY,EAAE,MAAM,CAAA;IACpB;;;OAGG;IACH,MAAM,CAAC,EAAE,oBAAoB,CAAA;IAC7B;;;OAGG;IACH,QAAQ,CAAC,EAAE,WAAW,CAAA;IACtB,8CAA8C;IAC9C,MAAM,CAAC,EAAE,YAAY,CAAA;CACtB;AAcD;;;;;;;;;;;;GAYG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,sBAAsB,GAAG,MAAM,CAsDvE"}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { createSanityClient } from "./client.js";
|
|
2
|
+
function defaultMapEvent(event) {
|
|
3
|
+
const { id: _id, ...rest } = event;
|
|
4
|
+
return rest;
|
|
5
|
+
}
|
|
6
|
+
function coerceEvent(data) {
|
|
7
|
+
if (data == null || typeof data !== "object")
|
|
8
|
+
return null;
|
|
9
|
+
const maybe = data;
|
|
10
|
+
if (typeof maybe.id !== "string")
|
|
11
|
+
return null;
|
|
12
|
+
return maybe;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Build a Voyant {@link Plugin} that pushes event payloads to a Sanity
|
|
16
|
+
* document type, keyed by `voyantId` for idempotent upserts.
|
|
17
|
+
*
|
|
18
|
+
* The plugin subscribes to three events (configurable via
|
|
19
|
+
* {@link SanityCmsPluginOptions.events}):
|
|
20
|
+
* - `product.created` → upsert document
|
|
21
|
+
* - `product.updated` → upsert document
|
|
22
|
+
* - `product.deleted` → delete document by `voyantId`
|
|
23
|
+
*
|
|
24
|
+
* Errors are caught and logged — subscribers are fire-and-forget per the
|
|
25
|
+
* EventBus contract, so a Sanity outage never blocks the emitter.
|
|
26
|
+
*/
|
|
27
|
+
export function sanityCmsPlugin(options) {
|
|
28
|
+
const client = createSanityClient(options);
|
|
29
|
+
const mapEvent = options.mapEvent ?? defaultMapEvent;
|
|
30
|
+
const logger = options.logger ?? console;
|
|
31
|
+
const eventNames = {
|
|
32
|
+
created: options.events?.created ?? "product.created",
|
|
33
|
+
updated: options.events?.updated ?? "product.updated",
|
|
34
|
+
deleted: options.events?.deleted ?? "product.deleted",
|
|
35
|
+
};
|
|
36
|
+
const subscribers = [
|
|
37
|
+
{
|
|
38
|
+
event: eventNames.created,
|
|
39
|
+
handler: async (data) => {
|
|
40
|
+
const event = coerceEvent(data);
|
|
41
|
+
if (!event)
|
|
42
|
+
return;
|
|
43
|
+
try {
|
|
44
|
+
await client.upsertByVoyantId(options.documentType, event.id, mapEvent(event));
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
logger.error(`[sanity-cms] upsert on "${eventNames.created}" failed for ${event.id}`, err);
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
event: eventNames.updated,
|
|
53
|
+
handler: async (data) => {
|
|
54
|
+
const event = coerceEvent(data);
|
|
55
|
+
if (!event)
|
|
56
|
+
return;
|
|
57
|
+
try {
|
|
58
|
+
await client.upsertByVoyantId(options.documentType, event.id, mapEvent(event));
|
|
59
|
+
}
|
|
60
|
+
catch (err) {
|
|
61
|
+
logger.error(`[sanity-cms] upsert on "${eventNames.updated}" failed for ${event.id}`, err);
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
},
|
|
65
|
+
{
|
|
66
|
+
event: eventNames.deleted,
|
|
67
|
+
handler: async (data) => {
|
|
68
|
+
const event = coerceEvent(data);
|
|
69
|
+
if (!event)
|
|
70
|
+
return;
|
|
71
|
+
try {
|
|
72
|
+
await client.deleteByVoyantId(options.documentType, event.id);
|
|
73
|
+
}
|
|
74
|
+
catch (err) {
|
|
75
|
+
logger.error(`[sanity-cms] delete on "${eventNames.deleted}" failed for ${event.id}`, err);
|
|
76
|
+
}
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
return {
|
|
81
|
+
name: "sanity-cms",
|
|
82
|
+
version: "0.1.0",
|
|
83
|
+
subscribers,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal shape Voyant events expose when carrying a record identifier.
|
|
3
|
+
* The plugin accepts anything with `id: string`; everything else is passed
|
|
4
|
+
* through to `mapEvent` untouched.
|
|
5
|
+
*/
|
|
6
|
+
export interface VoyantEntityEvent {
|
|
7
|
+
id: string;
|
|
8
|
+
[key: string]: unknown;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* A Sanity document body, as a bag of properties. Sanity assigns `_id` +
|
|
12
|
+
* `_type` on creation; the plugin sets a `voyantId` field (configurable)
|
|
13
|
+
* for idempotent lookups.
|
|
14
|
+
*/
|
|
15
|
+
export type SanityDocBody = Record<string, unknown>;
|
|
16
|
+
/**
|
|
17
|
+
* Minimal `fetch` shape the Sanity client depends on. Works with the global
|
|
18
|
+
* `fetch` in Node 18+ / Cloudflare Workers / browsers, and is trivially
|
|
19
|
+
* stubbable in tests.
|
|
20
|
+
*/
|
|
21
|
+
export type SanityFetch = (input: string, init: {
|
|
22
|
+
method: string;
|
|
23
|
+
headers: Record<string, string>;
|
|
24
|
+
body?: string;
|
|
25
|
+
}) => Promise<{
|
|
26
|
+
ok: boolean;
|
|
27
|
+
status: number;
|
|
28
|
+
json: () => Promise<unknown>;
|
|
29
|
+
text: () => Promise<string>;
|
|
30
|
+
}>;
|
|
31
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC,EAAE,EAAE,MAAM,CAAA;IACV,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;CACvB;AAED;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AAEnD;;;;GAIG;AACH,MAAM,MAAM,WAAW,GAAG,CACxB,KAAK,EAAE,MAAM,EACb,IAAI,EAAE;IACJ,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;IAC/B,IAAI,CAAC,EAAE,MAAM,CAAA;CACd,KACE,OAAO,CAAC;IACX,EAAE,EAAE,OAAO,CAAA;IACX,MAAM,EAAE,MAAM,CAAA;IACd,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;IAC5B,IAAI,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAA;CAC5B,CAAC,CAAA"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.test.d.ts","sourceRoot":"","sources":["../../../tests/unit/client.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { createSanityClient } from "../../src/client.js";
|
|
3
|
+
function jsonResponse(status, body) {
|
|
4
|
+
const text = JSON.stringify(body);
|
|
5
|
+
return {
|
|
6
|
+
ok: status >= 200 && status < 300,
|
|
7
|
+
status,
|
|
8
|
+
json: async () => JSON.parse(text),
|
|
9
|
+
text: async () => text,
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
function textResponse(status, text) {
|
|
13
|
+
return {
|
|
14
|
+
ok: status >= 200 && status < 300,
|
|
15
|
+
status,
|
|
16
|
+
json: async () => {
|
|
17
|
+
throw new Error("not json");
|
|
18
|
+
},
|
|
19
|
+
text: async () => text,
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
const baseOptions = {
|
|
23
|
+
projectId: "abc123",
|
|
24
|
+
dataset: "production",
|
|
25
|
+
token: "test-token",
|
|
26
|
+
};
|
|
27
|
+
describe("createSanityClient.findByVoyantId", () => {
|
|
28
|
+
it("returns the first matching doc", async () => {
|
|
29
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { result: { _id: "sn_1", name: "a" } }));
|
|
30
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
31
|
+
const result = await client.findByVoyantId("product", "prod_xyz");
|
|
32
|
+
expect(result).toEqual({ _id: "sn_1" });
|
|
33
|
+
const [url, init] = fetchMock.mock.calls[0];
|
|
34
|
+
expect(url).toContain("https://abc123.api.sanity.io/v2024-01-01/data/query/production?");
|
|
35
|
+
// GROQ query with voyantIdField and params
|
|
36
|
+
expect(url).toContain("query=");
|
|
37
|
+
expect(url).toContain("voyantId%20%3D%3D%20%24vid");
|
|
38
|
+
// JSON-encoded param values (`$` is not percent-encoded in param keys)
|
|
39
|
+
expect(url).toContain("$type=%22product%22");
|
|
40
|
+
expect(url).toContain("$vid=%22prod_xyz%22");
|
|
41
|
+
expect(init.method).toBe("GET");
|
|
42
|
+
expect(init.headers.Authorization).toBe("Bearer test-token");
|
|
43
|
+
});
|
|
44
|
+
it("returns null when no docs match", async () => {
|
|
45
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { result: null }));
|
|
46
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
47
|
+
expect(await client.findByVoyantId("product", "missing")).toBeNull();
|
|
48
|
+
});
|
|
49
|
+
it("respects a custom voyantIdField", async () => {
|
|
50
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { result: null }));
|
|
51
|
+
const client = createSanityClient({
|
|
52
|
+
...baseOptions,
|
|
53
|
+
voyantIdField: "externalId",
|
|
54
|
+
fetch: fetchMock,
|
|
55
|
+
});
|
|
56
|
+
await client.findByVoyantId("product", "prod_1");
|
|
57
|
+
const [url] = fetchMock.mock.calls[0];
|
|
58
|
+
expect(url).toContain("externalId%20%3D%3D%20%24vid");
|
|
59
|
+
});
|
|
60
|
+
it("respects a custom apiVersion", async () => {
|
|
61
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { result: null }));
|
|
62
|
+
const client = createSanityClient({
|
|
63
|
+
...baseOptions,
|
|
64
|
+
apiVersion: "2023-10-01",
|
|
65
|
+
fetch: fetchMock,
|
|
66
|
+
});
|
|
67
|
+
await client.findByVoyantId("product", "prod_1");
|
|
68
|
+
const [url] = fetchMock.mock.calls[0];
|
|
69
|
+
expect(url).toContain("/v2023-10-01/data/query/production?");
|
|
70
|
+
});
|
|
71
|
+
it("respects a custom apiHost", async () => {
|
|
72
|
+
const fetchMock = vi.fn(async () => jsonResponse(200, { result: null }));
|
|
73
|
+
const client = createSanityClient({
|
|
74
|
+
...baseOptions,
|
|
75
|
+
apiHost: "sanity.internal.example.com",
|
|
76
|
+
fetch: fetchMock,
|
|
77
|
+
});
|
|
78
|
+
await client.findByVoyantId("product", "prod_1");
|
|
79
|
+
const [url] = fetchMock.mock.calls[0];
|
|
80
|
+
expect(url).toContain("https://abc123.sanity.internal.example.com/");
|
|
81
|
+
});
|
|
82
|
+
it("throws on non-2xx response", async () => {
|
|
83
|
+
const fetchMock = vi.fn(async () => textResponse(500, "boom"));
|
|
84
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
85
|
+
await expect(client.findByVoyantId("product", "x")).rejects.toThrow(/Sanity findByVoyantId\(product\) failed \(500\)/);
|
|
86
|
+
});
|
|
87
|
+
});
|
|
88
|
+
describe("createSanityClient.upsertByVoyantId", () => {
|
|
89
|
+
it("creates a new doc when none exists", async () => {
|
|
90
|
+
const fetchMock = vi
|
|
91
|
+
.fn()
|
|
92
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
93
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_new", operation: "create" }] }));
|
|
94
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
95
|
+
const result = await client.upsertByVoyantId("product", "prod_1", { name: "X" });
|
|
96
|
+
expect(result).toEqual({ _id: "sn_new", created: true });
|
|
97
|
+
const createCall = fetchMock.mock.calls[1];
|
|
98
|
+
expect(createCall[0]).toContain("https://abc123.api.sanity.io/v2024-01-01/data/mutate/production");
|
|
99
|
+
expect(createCall[0]).toContain("returnIds=true");
|
|
100
|
+
expect(createCall[0]).toContain("visibility=sync");
|
|
101
|
+
expect(createCall[1].method).toBe("POST");
|
|
102
|
+
const body = JSON.parse(createCall[1].body ?? "{}");
|
|
103
|
+
expect(body).toEqual({
|
|
104
|
+
mutations: [
|
|
105
|
+
{
|
|
106
|
+
create: { _type: "product", name: "X", voyantId: "prod_1" },
|
|
107
|
+
},
|
|
108
|
+
],
|
|
109
|
+
});
|
|
110
|
+
});
|
|
111
|
+
it("updates an existing doc when found", async () => {
|
|
112
|
+
const fetchMock = vi
|
|
113
|
+
.fn()
|
|
114
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_existing" } }))
|
|
115
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_existing", operation: "update" }] }));
|
|
116
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
117
|
+
const result = await client.upsertByVoyantId("product", "prod_1", { name: "Y" });
|
|
118
|
+
expect(result).toEqual({ _id: "sn_existing", created: false });
|
|
119
|
+
const patchCall = fetchMock.mock.calls[1];
|
|
120
|
+
expect(patchCall[1].method).toBe("POST");
|
|
121
|
+
const body = JSON.parse(patchCall[1].body ?? "{}");
|
|
122
|
+
expect(body).toEqual({
|
|
123
|
+
mutations: [
|
|
124
|
+
{
|
|
125
|
+
patch: {
|
|
126
|
+
id: "sn_existing",
|
|
127
|
+
set: { name: "Y", voyantId: "prod_1" },
|
|
128
|
+
},
|
|
129
|
+
},
|
|
130
|
+
],
|
|
131
|
+
});
|
|
132
|
+
});
|
|
133
|
+
it("throws if create response has no id", async () => {
|
|
134
|
+
const fetchMock = vi
|
|
135
|
+
.fn()
|
|
136
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
137
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [] }));
|
|
138
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
139
|
+
await expect(client.upsertByVoyantId("product", "p", {})).rejects.toThrow(/response missing id/);
|
|
140
|
+
});
|
|
141
|
+
it("throws on create error", async () => {
|
|
142
|
+
const fetchMock = vi
|
|
143
|
+
.fn()
|
|
144
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
145
|
+
.mockResolvedValueOnce(textResponse(400, "bad request"));
|
|
146
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
147
|
+
await expect(client.upsertByVoyantId("product", "p", {})).rejects.toThrow(/Sanity create\(product\) failed \(400\)/);
|
|
148
|
+
});
|
|
149
|
+
it("throws on update error", async () => {
|
|
150
|
+
const fetchMock = vi
|
|
151
|
+
.fn()
|
|
152
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_1" } }))
|
|
153
|
+
.mockResolvedValueOnce(textResponse(409, "conflict"));
|
|
154
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
155
|
+
await expect(client.upsertByVoyantId("product", "p", {})).rejects.toThrow(/Sanity update\(product\/sn_1\) failed \(409\)/);
|
|
156
|
+
});
|
|
157
|
+
});
|
|
158
|
+
describe("createSanityClient.deleteByVoyantId", () => {
|
|
159
|
+
it("deletes when doc exists", async () => {
|
|
160
|
+
const fetchMock = vi
|
|
161
|
+
.fn()
|
|
162
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_1" } }))
|
|
163
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_1", operation: "delete" }] }));
|
|
164
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
165
|
+
expect(await client.deleteByVoyantId("product", "p")).toBe(true);
|
|
166
|
+
const deleteCall = fetchMock.mock.calls[1];
|
|
167
|
+
expect(deleteCall[1].method).toBe("POST");
|
|
168
|
+
const body = JSON.parse(deleteCall[1].body ?? "{}");
|
|
169
|
+
expect(body).toEqual({ mutations: [{ delete: { id: "sn_1" } }] });
|
|
170
|
+
});
|
|
171
|
+
it("returns false when doc does not exist", async () => {
|
|
172
|
+
const fetchMock = vi
|
|
173
|
+
.fn()
|
|
174
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }));
|
|
175
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
176
|
+
expect(await client.deleteByVoyantId("product", "p")).toBe(false);
|
|
177
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
178
|
+
});
|
|
179
|
+
it("throws on non-2xx delete response", async () => {
|
|
180
|
+
const fetchMock = vi
|
|
181
|
+
.fn()
|
|
182
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_1" } }))
|
|
183
|
+
.mockResolvedValueOnce(textResponse(500, "boom"));
|
|
184
|
+
const client = createSanityClient({ ...baseOptions, fetch: fetchMock });
|
|
185
|
+
await expect(client.deleteByVoyantId("product", "p")).rejects.toThrow(/Sanity delete\(product\/sn_1\) failed \(500\)/);
|
|
186
|
+
});
|
|
187
|
+
});
|
|
188
|
+
describe("createSanityClient — fetch handling", () => {
|
|
189
|
+
it("throws when no fetch implementation is available", async () => {
|
|
190
|
+
const originalFetch = globalThis.fetch;
|
|
191
|
+
globalThis.fetch = undefined;
|
|
192
|
+
try {
|
|
193
|
+
// biome-ignore lint/suspicious/noExplicitAny: simulating missing fetch
|
|
194
|
+
const client = createSanityClient({ ...baseOptions, fetch: undefined });
|
|
195
|
+
await expect(client.findByVoyantId("product", "x")).rejects.toThrow(/requires a fetch implementation/);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
globalThis.fetch = originalFetch;
|
|
199
|
+
}
|
|
200
|
+
});
|
|
201
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"plugin.test.d.ts","sourceRoot":"","sources":["../../../tests/unit/plugin.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { createEventBus, registerPlugins } from "@voyantjs/core";
|
|
2
|
+
import { describe, expect, it, vi } from "vitest";
|
|
3
|
+
import { sanityCmsPlugin } from "../../src/plugin.js";
|
|
4
|
+
function jsonResponse(status, body) {
|
|
5
|
+
const text = JSON.stringify(body);
|
|
6
|
+
return {
|
|
7
|
+
ok: status >= 200 && status < 300,
|
|
8
|
+
status,
|
|
9
|
+
json: async () => JSON.parse(text),
|
|
10
|
+
text: async () => text,
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const baseOptions = {
|
|
14
|
+
projectId: "abc123",
|
|
15
|
+
dataset: "production",
|
|
16
|
+
token: "test-token",
|
|
17
|
+
documentType: "product",
|
|
18
|
+
};
|
|
19
|
+
describe("sanityCmsPlugin", () => {
|
|
20
|
+
it("exposes a stable identity", () => {
|
|
21
|
+
const plugin = sanityCmsPlugin({ ...baseOptions });
|
|
22
|
+
expect(plugin.name).toBe("sanity-cms");
|
|
23
|
+
expect(plugin.version).toBeDefined();
|
|
24
|
+
expect(plugin.subscribers).toHaveLength(3);
|
|
25
|
+
});
|
|
26
|
+
it("subscribes to default product.* events", () => {
|
|
27
|
+
const plugin = sanityCmsPlugin({ ...baseOptions });
|
|
28
|
+
const names = plugin.subscribers?.map((s) => s.event);
|
|
29
|
+
expect(names).toEqual(["product.created", "product.updated", "product.deleted"]);
|
|
30
|
+
});
|
|
31
|
+
it("honors custom event names", () => {
|
|
32
|
+
const plugin = sanityCmsPlugin({
|
|
33
|
+
...baseOptions,
|
|
34
|
+
events: {
|
|
35
|
+
created: "departure.created",
|
|
36
|
+
updated: "departure.updated",
|
|
37
|
+
deleted: "departure.deleted",
|
|
38
|
+
},
|
|
39
|
+
});
|
|
40
|
+
const names = plugin.subscribers?.map((s) => s.event);
|
|
41
|
+
expect(names).toEqual(["departure.created", "departure.updated", "departure.deleted"]);
|
|
42
|
+
});
|
|
43
|
+
it("pushes product.created to Sanity as a create mutation", async () => {
|
|
44
|
+
const fetchMock = vi
|
|
45
|
+
.fn()
|
|
46
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
47
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_1", operation: "create" }] }));
|
|
48
|
+
const bus = createEventBus();
|
|
49
|
+
const plugin = sanityCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
50
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
51
|
+
await bus.emit("product.created", { id: "prod_1", name: "Tour A" });
|
|
52
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
53
|
+
const [, createInit] = fetchMock.mock.calls[1];
|
|
54
|
+
expect(createInit.method).toBe("POST");
|
|
55
|
+
const body = JSON.parse(createInit.body ?? "{}");
|
|
56
|
+
expect(body).toEqual({
|
|
57
|
+
mutations: [{ create: { _type: "product", name: "Tour A", voyantId: "prod_1" } }],
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
it("pushes product.updated to Sanity as a patch mutation", async () => {
|
|
61
|
+
const fetchMock = vi
|
|
62
|
+
.fn()
|
|
63
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_99" } }))
|
|
64
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_99", operation: "update" }] }));
|
|
65
|
+
const bus = createEventBus();
|
|
66
|
+
const plugin = sanityCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
67
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
68
|
+
await bus.emit("product.updated", { id: "prod_1", name: "Tour B" });
|
|
69
|
+
const [, init] = fetchMock.mock.calls[1];
|
|
70
|
+
expect(init.method).toBe("POST");
|
|
71
|
+
const body = JSON.parse(init.body ?? "{}");
|
|
72
|
+
expect(body).toEqual({
|
|
73
|
+
mutations: [{ patch: { id: "sn_99", set: { name: "Tour B", voyantId: "prod_1" } } }],
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
it("deletes from Sanity on product.deleted", async () => {
|
|
77
|
+
const fetchMock = vi
|
|
78
|
+
.fn()
|
|
79
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: { _id: "sn_50" } }))
|
|
80
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_50", operation: "delete" }] }));
|
|
81
|
+
const bus = createEventBus();
|
|
82
|
+
const plugin = sanityCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
83
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
84
|
+
await bus.emit("product.deleted", { id: "prod_1" });
|
|
85
|
+
const [, init] = fetchMock.mock.calls[1];
|
|
86
|
+
expect(init.method).toBe("POST");
|
|
87
|
+
const body = JSON.parse(init.body ?? "{}");
|
|
88
|
+
expect(body).toEqual({ mutations: [{ delete: { id: "sn_50" } }] });
|
|
89
|
+
});
|
|
90
|
+
it("applies a custom mapEvent function", async () => {
|
|
91
|
+
const fetchMock = vi
|
|
92
|
+
.fn()
|
|
93
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
94
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_1", operation: "create" }] }));
|
|
95
|
+
const bus = createEventBus();
|
|
96
|
+
const plugin = sanityCmsPlugin({
|
|
97
|
+
...baseOptions,
|
|
98
|
+
fetch: fetchMock,
|
|
99
|
+
mapEvent: (event) => ({
|
|
100
|
+
title: String(event.name ?? ""),
|
|
101
|
+
_syncedAt: "2024-01-01",
|
|
102
|
+
}),
|
|
103
|
+
});
|
|
104
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
105
|
+
await bus.emit("product.created", { id: "prod_x", name: "Cool Tour" });
|
|
106
|
+
const [, init] = fetchMock.mock.calls[1];
|
|
107
|
+
const body = JSON.parse(init.body ?? "{}");
|
|
108
|
+
expect(body).toEqual({
|
|
109
|
+
mutations: [
|
|
110
|
+
{
|
|
111
|
+
create: {
|
|
112
|
+
_type: "product",
|
|
113
|
+
title: "Cool Tour",
|
|
114
|
+
_syncedAt: "2024-01-01",
|
|
115
|
+
voyantId: "prod_x",
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
],
|
|
119
|
+
});
|
|
120
|
+
});
|
|
121
|
+
it("ignores events with no string id", async () => {
|
|
122
|
+
const fetchMock = vi.fn();
|
|
123
|
+
const bus = createEventBus();
|
|
124
|
+
const plugin = sanityCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
125
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
126
|
+
await bus.emit("product.created", { name: "no id here" });
|
|
127
|
+
await bus.emit("product.created", null);
|
|
128
|
+
await bus.emit("product.created", { id: 42 });
|
|
129
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
130
|
+
});
|
|
131
|
+
it("logs and swallows Sanity errors (fire-and-forget)", async () => {
|
|
132
|
+
const fetchMock = vi.fn().mockResolvedValue({
|
|
133
|
+
ok: false,
|
|
134
|
+
status: 500,
|
|
135
|
+
json: async () => ({}),
|
|
136
|
+
text: async () => "server down",
|
|
137
|
+
});
|
|
138
|
+
const errorFn = vi.fn();
|
|
139
|
+
const bus = createEventBus();
|
|
140
|
+
const plugin = sanityCmsPlugin({
|
|
141
|
+
...baseOptions,
|
|
142
|
+
fetch: fetchMock,
|
|
143
|
+
logger: { error: errorFn },
|
|
144
|
+
});
|
|
145
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
146
|
+
await bus.emit("product.created", { id: "prod_1", name: "X" });
|
|
147
|
+
expect(errorFn).toHaveBeenCalledOnce();
|
|
148
|
+
const [msg] = errorFn.mock.calls[0];
|
|
149
|
+
expect(msg).toContain('[sanity-cms] upsert on "product.created" failed for prod_1');
|
|
150
|
+
});
|
|
151
|
+
it("uses a custom documentType for the Sanity document", async () => {
|
|
152
|
+
const fetchMock = vi
|
|
153
|
+
.fn()
|
|
154
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }))
|
|
155
|
+
.mockResolvedValueOnce(jsonResponse(200, { results: [{ id: "sn_1", operation: "create" }] }));
|
|
156
|
+
const bus = createEventBus();
|
|
157
|
+
const plugin = sanityCmsPlugin({
|
|
158
|
+
...baseOptions,
|
|
159
|
+
documentType: "tour",
|
|
160
|
+
fetch: fetchMock,
|
|
161
|
+
});
|
|
162
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
163
|
+
await bus.emit("product.created", { id: "prod_1", name: "X" });
|
|
164
|
+
// find query uses $type=tour
|
|
165
|
+
const [findUrl] = fetchMock.mock.calls[0];
|
|
166
|
+
expect(findUrl).toContain("$type=%22tour%22");
|
|
167
|
+
// create payload uses _type: "tour"
|
|
168
|
+
const [, createInit] = fetchMock.mock.calls[1];
|
|
169
|
+
const body = JSON.parse(createInit.body ?? "{}");
|
|
170
|
+
expect(body.mutations[0].create._type).toBe("tour");
|
|
171
|
+
});
|
|
172
|
+
it("does not mutate if the doc is missing on product.deleted", async () => {
|
|
173
|
+
const fetchMock = vi
|
|
174
|
+
.fn()
|
|
175
|
+
.mockResolvedValueOnce(jsonResponse(200, { result: null }));
|
|
176
|
+
const bus = createEventBus();
|
|
177
|
+
const plugin = sanityCmsPlugin({ ...baseOptions, fetch: fetchMock });
|
|
178
|
+
registerPlugins([plugin], { eventBus: bus });
|
|
179
|
+
await bus.emit("product.deleted", { id: "prod_missing" });
|
|
180
|
+
// Only the find call should have been made.
|
|
181
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
182
|
+
});
|
|
183
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@voyantjs/plugin-sanity-cms",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "FSL-1.1-Apache-2.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": {
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"import": "./dist/index.js"
|
|
10
|
+
},
|
|
11
|
+
"./client": {
|
|
12
|
+
"types": "./dist/client.d.ts",
|
|
13
|
+
"import": "./dist/client.js"
|
|
14
|
+
},
|
|
15
|
+
"./plugin": {
|
|
16
|
+
"types": "./dist/plugin.d.ts",
|
|
17
|
+
"import": "./dist/plugin.js"
|
|
18
|
+
},
|
|
19
|
+
"./types": {
|
|
20
|
+
"types": "./dist/types.d.ts",
|
|
21
|
+
"import": "./dist/types.js"
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"@voyantjs/core": "0.1.0"
|
|
26
|
+
},
|
|
27
|
+
"devDependencies": {
|
|
28
|
+
"typescript": "^6.0.2",
|
|
29
|
+
"vitest": "^4.1.2",
|
|
30
|
+
"@voyantjs/voyant-typescript-config": "0.1.0"
|
|
31
|
+
},
|
|
32
|
+
"files": [
|
|
33
|
+
"dist"
|
|
34
|
+
],
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"scripts": {
|
|
39
|
+
"typecheck": "tsc --noEmit",
|
|
40
|
+
"lint": "biome check src/",
|
|
41
|
+
"test": "vitest run",
|
|
42
|
+
"build": "tsc -p tsconfig.json",
|
|
43
|
+
"clean": "rm -rf dist"
|
|
44
|
+
},
|
|
45
|
+
"main": "./dist/index.js",
|
|
46
|
+
"types": "./dist/index.d.ts"
|
|
47
|
+
}
|