@agentcms/react 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 +21 -0
- package/README.md +155 -0
- package/package.json +39 -0
- package/src/client.test.ts +231 -0
- package/src/client.ts +94 -0
- package/src/hooks.ts +53 -0
- package/src/index.ts +29 -0
- package/src/provider.tsx +40 -0
- package/src/types.ts +76 -0
- package/tsconfig.json +19 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MC2 Ventures
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
# @agentcms/react
|
|
2
|
+
|
|
3
|
+
React SDK for the **AgentCMS headless API**. Use it in any React app (Next.js, Vite, Remix, etc.) to fetch posts, site context, and list/filter content from an AgentCMS-backed site.
|
|
4
|
+
|
|
5
|
+
**Requires** a live AgentCMS site (e.g. [@agentcms/core](https://github.com/agentcms/agentcms) on Astro + Cloudflare) that exposes `/api/agent/context` and `/api/agent/posts`.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @agentcms/react
|
|
11
|
+
# or
|
|
12
|
+
pnpm add @agentcms/react
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
**Peer dependency:** React 18 or 19.
|
|
16
|
+
|
|
17
|
+
## Setup
|
|
18
|
+
|
|
19
|
+
Wrap your app (or the subtree that needs AgentCMS data) with `AgentCMSProvider` and pass the base URL of your AgentCMS site.
|
|
20
|
+
|
|
21
|
+
```tsx
|
|
22
|
+
import { AgentCMSProvider } from "@agentcms/react";
|
|
23
|
+
|
|
24
|
+
function App() {
|
|
25
|
+
return (
|
|
26
|
+
<AgentCMSProvider baseUrl="https://your-blog.pages.dev">
|
|
27
|
+
<YourRoutes />
|
|
28
|
+
</AgentCMSProvider>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Optional: `apiKey` for endpoints that require auth (e.g. draft or read-only agent key).
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
<AgentCMSProvider baseUrl="https://..." apiKey="acms_live_...">
|
|
37
|
+
{children}
|
|
38
|
+
</AgentCMSProvider>
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Usage
|
|
42
|
+
|
|
43
|
+
### Hooks (recommended)
|
|
44
|
+
|
|
45
|
+
**Paginated post list** — with optional `limit`, `offset`, `tag`, `category`:
|
|
46
|
+
|
|
47
|
+
```tsx
|
|
48
|
+
import { useAgentCMSPosts } from "@agentcms/react";
|
|
49
|
+
|
|
50
|
+
function PostList() {
|
|
51
|
+
const { posts, total, hasMore, loading, error, refetch } = useAgentCMSPosts({
|
|
52
|
+
limit: 10,
|
|
53
|
+
tag: "ai",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
if (loading) return <div>Loading…</div>;
|
|
57
|
+
if (error) return <div>Error: {error.message}</div>;
|
|
58
|
+
|
|
59
|
+
return (
|
|
60
|
+
<ul>
|
|
61
|
+
{posts.map((p) => (
|
|
62
|
+
<li key={p.slug}>
|
|
63
|
+
<a href={`/blog/${p.slug}`}>{p.title}</a>
|
|
64
|
+
</li>
|
|
65
|
+
))}
|
|
66
|
+
{hasMore && <button onClick={() => refetch()}>Load more</button>}
|
|
67
|
+
</ul>
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
**Single post by slug:**
|
|
73
|
+
|
|
74
|
+
```tsx
|
|
75
|
+
import { useAgentCMSPost } from "@agentcms/react";
|
|
76
|
+
|
|
77
|
+
function Post({ slug }: { slug: string }) {
|
|
78
|
+
const { post, loading, error } = useAgentCMSPost(slug);
|
|
79
|
+
|
|
80
|
+
if (loading) return <div>Loading…</div>;
|
|
81
|
+
if (error || !post) return <div>Not found</div>;
|
|
82
|
+
|
|
83
|
+
return (
|
|
84
|
+
<article>
|
|
85
|
+
<h1>{post.title}</h1>
|
|
86
|
+
<div dangerouslySetInnerHTML={{ __html: post.contentHtml ?? post.content }} />
|
|
87
|
+
</article>
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
**Site context** (voice, guidelines, tags, categories — useful for agent UIs or discovery):
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
import { useAgentCMSContext } from "@agentcms/react";
|
|
96
|
+
|
|
97
|
+
function SiteInfo() {
|
|
98
|
+
const { context, loading } = useAgentCMSContext();
|
|
99
|
+
|
|
100
|
+
if (loading || !context) return null;
|
|
101
|
+
return (
|
|
102
|
+
<p>
|
|
103
|
+
{context.site.name} — {context.site.description}
|
|
104
|
+
</p>
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Client (without hooks)
|
|
110
|
+
|
|
111
|
+
If you need the client outside React or for one-off calls:
|
|
112
|
+
|
|
113
|
+
```tsx
|
|
114
|
+
import { AgentCMSProvider, useAgentCMSClient } from "@agentcms/react";
|
|
115
|
+
|
|
116
|
+
function SomeComponent() {
|
|
117
|
+
const client = useAgentCMSClient();
|
|
118
|
+
const handleClick = async () => {
|
|
119
|
+
const ctx = await client.getContext();
|
|
120
|
+
const { posts } = await client.listPosts({ limit: 5 });
|
|
121
|
+
};
|
|
122
|
+
// ...
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Or instantiate directly (no provider):
|
|
127
|
+
|
|
128
|
+
```tsx
|
|
129
|
+
import { AgentCMSClient } from "@agentcms/react";
|
|
130
|
+
|
|
131
|
+
const client = new AgentCMSClient({
|
|
132
|
+
baseUrl: "https://your-blog.pages.dev",
|
|
133
|
+
apiKey: "optional",
|
|
134
|
+
});
|
|
135
|
+
const context = await client.getContext();
|
|
136
|
+
const { posts } = await client.listPosts({ limit: 10 });
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
## API
|
|
140
|
+
|
|
141
|
+
| Export | Description |
|
|
142
|
+
|--------|-------------|
|
|
143
|
+
| `AgentCMSProvider` | Provider; props: `baseUrl`, `apiKey?`, `children` |
|
|
144
|
+
| `useAgentCMSClient()` | Returns `AgentCMSClient` (must be used inside provider) |
|
|
145
|
+
| `useAgentCMSPosts(params?)` | `{ posts, total, hasMore, loading, error, refetch }`; params: `limit?`, `offset?`, `tag?`, `category?` |
|
|
146
|
+
| `useAgentCMSPost(slug \| null)` | `{ post, loading, error, refetch }` |
|
|
147
|
+
| `useAgentCMSContext()` | `{ context, loading, error, refetch }` |
|
|
148
|
+
| `AgentCMSClient` | `getContext()`, `listPosts(params?)`, `getPost(slug)` |
|
|
149
|
+
| `AgentCMSError` | `Error` subclass with `status` (HTTP status code) |
|
|
150
|
+
|
|
151
|
+
Types: `AgentCMSPost`, `PostListResponse`, `SiteContext`, `ListPostsParams`, `AgentCMSConfig` are exported for TypeScript.
|
|
152
|
+
|
|
153
|
+
## Repo / publish
|
|
154
|
+
|
|
155
|
+
Published as `@agentcms/react`. Source: [github.com/agentcms/react](https://github.com/agentcms/react). It can be used against any deployed AgentCMS site; no direct dependency on Astro or Cloudflare in your React app.
|
package/package.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@agentcms/react",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "React SDK for AgentCMS headless API",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": "MC2 Ventures",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "https://github.com/agentcms/react"
|
|
11
|
+
},
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"default": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc",
|
|
22
|
+
"test": "vitest run"
|
|
23
|
+
},
|
|
24
|
+
"publishConfig": {
|
|
25
|
+
"access": "public"
|
|
26
|
+
},
|
|
27
|
+
"peerDependencies": {
|
|
28
|
+
"react": "^18.0.0 || ^19.0.0",
|
|
29
|
+
"@tanstack/react-query": "^5.0.0"
|
|
30
|
+
},
|
|
31
|
+
"dependencies": {},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"@tanstack/react-query": "^5.64.0",
|
|
34
|
+
"@types/react": "^19.0.0",
|
|
35
|
+
"react": "^19.0.0",
|
|
36
|
+
"typescript": "^5.7.0",
|
|
37
|
+
"vitest": "^3.0.0"
|
|
38
|
+
}
|
|
39
|
+
}
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import { AgentCMSClient, AgentCMSError } from "./client.js";
|
|
3
|
+
import type { PostListResponse, SiteContext, AgentCMSPost } from "./types.js";
|
|
4
|
+
|
|
5
|
+
// --- Mock fetch ---
|
|
6
|
+
|
|
7
|
+
const originalFetch = globalThis.fetch;
|
|
8
|
+
let mockFetch: ReturnType<typeof vi.fn>;
|
|
9
|
+
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
mockFetch = vi.fn();
|
|
12
|
+
globalThis.fetch = mockFetch;
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
globalThis.fetch = originalFetch;
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
function mockJsonResponse(data: unknown, status = 200) {
|
|
20
|
+
return new Response(JSON.stringify(data), {
|
|
21
|
+
status,
|
|
22
|
+
headers: { "Content-Type": "application/json" },
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// ============================================================================
|
|
27
|
+
// Constructor
|
|
28
|
+
// ============================================================================
|
|
29
|
+
|
|
30
|
+
describe("AgentCMSClient", () => {
|
|
31
|
+
it("strips trailing slashes from baseUrl", () => {
|
|
32
|
+
const client = new AgentCMSClient({ baseUrl: "https://example.com///" });
|
|
33
|
+
// Verify by making a request and checking the URL
|
|
34
|
+
mockFetch.mockResolvedValue(mockJsonResponse({ posts: [] }));
|
|
35
|
+
client.listPosts();
|
|
36
|
+
expect(mockFetch).toHaveBeenCalledWith(
|
|
37
|
+
"https://example.com/api/agent/posts",
|
|
38
|
+
expect.any(Object)
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it("includes Authorization header when apiKey is provided", async () => {
|
|
43
|
+
const client = new AgentCMSClient({
|
|
44
|
+
baseUrl: "https://example.com",
|
|
45
|
+
apiKey: "acms_live_test",
|
|
46
|
+
});
|
|
47
|
+
mockFetch.mockResolvedValue(mockJsonResponse({}));
|
|
48
|
+
await client.getContext();
|
|
49
|
+
|
|
50
|
+
const headers = mockFetch.mock.calls[0][1].headers;
|
|
51
|
+
expect(headers.Authorization).toBe("Bearer acms_live_test");
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("omits Authorization header when no apiKey", async () => {
|
|
55
|
+
const client = new AgentCMSClient({ baseUrl: "https://example.com" });
|
|
56
|
+
mockFetch.mockResolvedValue(mockJsonResponse({}));
|
|
57
|
+
await client.getContext();
|
|
58
|
+
|
|
59
|
+
const headers = mockFetch.mock.calls[0][1].headers;
|
|
60
|
+
expect(headers.Authorization).toBeUndefined();
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// ============================================================================
|
|
65
|
+
// getContext
|
|
66
|
+
// ============================================================================
|
|
67
|
+
|
|
68
|
+
describe("getContext", () => {
|
|
69
|
+
it("fetches /api/agent/context", async () => {
|
|
70
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
71
|
+
const ctx: SiteContext = {
|
|
72
|
+
site: {
|
|
73
|
+
name: "Test",
|
|
74
|
+
description: "Test blog",
|
|
75
|
+
url: "https://blog.test",
|
|
76
|
+
language: "en",
|
|
77
|
+
},
|
|
78
|
+
writingGuidelines: {
|
|
79
|
+
tone: "casual",
|
|
80
|
+
targetAudience: "devs",
|
|
81
|
+
preferredLength: "short",
|
|
82
|
+
},
|
|
83
|
+
existingContent: {
|
|
84
|
+
totalPosts: 5,
|
|
85
|
+
recentTitles: ["Hello"],
|
|
86
|
+
existingTags: ["test"],
|
|
87
|
+
existingCategories: ["General"],
|
|
88
|
+
},
|
|
89
|
+
capabilities: {
|
|
90
|
+
maxContentLength: 100000,
|
|
91
|
+
markdownFeatures: ["headings", "code"],
|
|
92
|
+
},
|
|
93
|
+
};
|
|
94
|
+
mockFetch.mockResolvedValue(mockJsonResponse(ctx));
|
|
95
|
+
|
|
96
|
+
const result = await client.getContext();
|
|
97
|
+
expect(result).toEqual(ctx);
|
|
98
|
+
expect(mockFetch).toHaveBeenCalledWith(
|
|
99
|
+
"https://blog.test/api/agent/context",
|
|
100
|
+
expect.objectContaining({ headers: expect.objectContaining({ Accept: "application/json" }) })
|
|
101
|
+
);
|
|
102
|
+
});
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// ============================================================================
|
|
106
|
+
// listPosts
|
|
107
|
+
// ============================================================================
|
|
108
|
+
|
|
109
|
+
describe("listPosts", () => {
|
|
110
|
+
it("fetches /api/agent/posts with no params", async () => {
|
|
111
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
112
|
+
const body: PostListResponse = {
|
|
113
|
+
posts: [],
|
|
114
|
+
total: 0,
|
|
115
|
+
limit: 20,
|
|
116
|
+
offset: 0,
|
|
117
|
+
hasMore: false,
|
|
118
|
+
};
|
|
119
|
+
mockFetch.mockResolvedValue(mockJsonResponse(body));
|
|
120
|
+
|
|
121
|
+
const result = await client.listPosts();
|
|
122
|
+
expect(result).toEqual(body);
|
|
123
|
+
expect(mockFetch).toHaveBeenCalledWith(
|
|
124
|
+
"https://blog.test/api/agent/posts",
|
|
125
|
+
expect.any(Object)
|
|
126
|
+
);
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
it("builds query string from params", async () => {
|
|
130
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
131
|
+
mockFetch.mockResolvedValue(
|
|
132
|
+
mockJsonResponse({ posts: [], total: 0, limit: 5, offset: 10, hasMore: false })
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
await client.listPosts({ limit: 5, offset: 10, tag: "ai", category: "Tech" });
|
|
136
|
+
const url = mockFetch.mock.calls[0][0] as string;
|
|
137
|
+
expect(url).toContain("limit=5");
|
|
138
|
+
expect(url).toContain("offset=10");
|
|
139
|
+
expect(url).toContain("tag=ai");
|
|
140
|
+
expect(url).toContain("category=Tech");
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
it("omits undefined params from query string", async () => {
|
|
144
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
145
|
+
mockFetch.mockResolvedValue(
|
|
146
|
+
mockJsonResponse({ posts: [], total: 0, limit: 20, offset: 0, hasMore: false })
|
|
147
|
+
);
|
|
148
|
+
|
|
149
|
+
await client.listPosts({ tag: "ai" });
|
|
150
|
+
const url = mockFetch.mock.calls[0][0] as string;
|
|
151
|
+
expect(url).toContain("tag=ai");
|
|
152
|
+
expect(url).not.toContain("limit");
|
|
153
|
+
expect(url).not.toContain("offset");
|
|
154
|
+
expect(url).not.toContain("category");
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
// ============================================================================
|
|
159
|
+
// getPost
|
|
160
|
+
// ============================================================================
|
|
161
|
+
|
|
162
|
+
describe("getPost", () => {
|
|
163
|
+
it("fetches /api/agent/posts/:slug", async () => {
|
|
164
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
165
|
+
const post: AgentCMSPost = {
|
|
166
|
+
slug: "hello-world",
|
|
167
|
+
title: "Hello World",
|
|
168
|
+
description: "First post",
|
|
169
|
+
content: "# Hello",
|
|
170
|
+
author: "Agent",
|
|
171
|
+
authorType: "agent",
|
|
172
|
+
tags: ["intro"],
|
|
173
|
+
publishedAt: "2025-01-01T00:00:00.000Z",
|
|
174
|
+
updatedAt: "2025-01-01T00:00:00.000Z",
|
|
175
|
+
status: "published",
|
|
176
|
+
metadata: {},
|
|
177
|
+
};
|
|
178
|
+
mockFetch.mockResolvedValue(mockJsonResponse(post));
|
|
179
|
+
|
|
180
|
+
const result = await client.getPost("hello-world");
|
|
181
|
+
expect(result).toEqual(post);
|
|
182
|
+
expect(mockFetch).toHaveBeenCalledWith(
|
|
183
|
+
"https://blog.test/api/agent/posts/hello-world",
|
|
184
|
+
expect.any(Object)
|
|
185
|
+
);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it("encodes slug in URL", async () => {
|
|
189
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
190
|
+
mockFetch.mockResolvedValue(mockJsonResponse({}));
|
|
191
|
+
await client.getPost("hello world");
|
|
192
|
+
const url = mockFetch.mock.calls[0][0] as string;
|
|
193
|
+
expect(url).toContain("hello%20world");
|
|
194
|
+
});
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// ============================================================================
|
|
198
|
+
// Error handling
|
|
199
|
+
// ============================================================================
|
|
200
|
+
|
|
201
|
+
describe("error handling", () => {
|
|
202
|
+
it("throws AgentCMSError on non-OK response", async () => {
|
|
203
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
204
|
+
mockFetch.mockResolvedValue(
|
|
205
|
+
new Response("Not Found", { status: 404 })
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
try {
|
|
209
|
+
await client.getPost("nope");
|
|
210
|
+
expect.unreachable("should have thrown");
|
|
211
|
+
} catch (e) {
|
|
212
|
+
expect(e).toBeInstanceOf(AgentCMSError);
|
|
213
|
+
expect((e as AgentCMSError).message).toMatch(/404/);
|
|
214
|
+
}
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
it("AgentCMSError has status property", async () => {
|
|
218
|
+
const client = new AgentCMSClient({ baseUrl: "https://blog.test" });
|
|
219
|
+
mockFetch.mockResolvedValue(
|
|
220
|
+
new Response("Forbidden", { status: 403 })
|
|
221
|
+
);
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
await client.getContext();
|
|
225
|
+
expect.unreachable("should have thrown");
|
|
226
|
+
} catch (e) {
|
|
227
|
+
expect(e).toBeInstanceOf(AgentCMSError);
|
|
228
|
+
expect((e as AgentCMSError).status).toBe(403);
|
|
229
|
+
}
|
|
230
|
+
});
|
|
231
|
+
});
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @agentcms/react — API Client
|
|
3
|
+
// ============================================================================
|
|
4
|
+
|
|
5
|
+
import type {
|
|
6
|
+
AgentCMSConfig,
|
|
7
|
+
AgentCMSPost,
|
|
8
|
+
GetPostsParams,
|
|
9
|
+
GetPostsResult,
|
|
10
|
+
GetCategoriesResult,
|
|
11
|
+
GetTagsResult,
|
|
12
|
+
SiteContext,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
|
|
15
|
+
export class AgentCMSClient {
|
|
16
|
+
private baseUrl: string;
|
|
17
|
+
private apiKey?: string;
|
|
18
|
+
|
|
19
|
+
constructor(config: AgentCMSConfig = {}) {
|
|
20
|
+
this.baseUrl = (config.baseUrl ?? "/api").replace(/\/+$/, "");
|
|
21
|
+
this.apiKey = config.apiKey;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
private async fetch<T>(path: string, auth = false): Promise<T> {
|
|
25
|
+
const headers: Record<string, string> = {
|
|
26
|
+
Accept: "application/json",
|
|
27
|
+
};
|
|
28
|
+
if (auth && this.apiKey) {
|
|
29
|
+
headers.Authorization = `Bearer ${this.apiKey}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const res = await fetch(`${this.baseUrl}${path}`, { headers });
|
|
33
|
+
if (!res.ok) {
|
|
34
|
+
throw new AgentCMSError(res.status, await res.text());
|
|
35
|
+
}
|
|
36
|
+
return res.json() as Promise<T>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// --- Public endpoints (no auth) ---
|
|
40
|
+
|
|
41
|
+
async getPosts(params: GetPostsParams = {}): Promise<GetPostsResult> {
|
|
42
|
+
const { page = 1, limit = 20, tag, category } = params;
|
|
43
|
+
const offset = (page - 1) * limit;
|
|
44
|
+
const qs = new URLSearchParams();
|
|
45
|
+
qs.set("limit", String(limit));
|
|
46
|
+
qs.set("offset", String(offset));
|
|
47
|
+
if (tag) qs.set("tag", tag);
|
|
48
|
+
if (category) qs.set("category", category);
|
|
49
|
+
|
|
50
|
+
const raw = await this.fetch<{
|
|
51
|
+
posts: AgentCMSPost[];
|
|
52
|
+
total: number;
|
|
53
|
+
limit: number;
|
|
54
|
+
offset: number;
|
|
55
|
+
hasMore: boolean;
|
|
56
|
+
}>(`/posts?${qs}`);
|
|
57
|
+
|
|
58
|
+
return {
|
|
59
|
+
posts: raw.posts,
|
|
60
|
+
total: raw.total,
|
|
61
|
+
totalPages: Math.ceil(raw.total / limit),
|
|
62
|
+
page,
|
|
63
|
+
hasMore: raw.hasMore,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
async getPost(slug: string): Promise<AgentCMSPost> {
|
|
68
|
+
return this.fetch<AgentCMSPost>(`/posts/${encodeURIComponent(slug)}`);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async getCategories(): Promise<GetCategoriesResult> {
|
|
72
|
+
return this.fetch<GetCategoriesResult>("/categories");
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async getTags(): Promise<GetTagsResult> {
|
|
76
|
+
return this.fetch<GetTagsResult>("/tags");
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// --- Agent endpoints (auth required) ---
|
|
80
|
+
|
|
81
|
+
async getContext(): Promise<SiteContext> {
|
|
82
|
+
return this.fetch<SiteContext>("/agent/context", true);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export class AgentCMSError extends Error {
|
|
87
|
+
status: number;
|
|
88
|
+
|
|
89
|
+
constructor(status: number, body: string) {
|
|
90
|
+
super(`AgentCMS API error ${status}: ${body}`);
|
|
91
|
+
this.name = "AgentCMSError";
|
|
92
|
+
this.status = status;
|
|
93
|
+
}
|
|
94
|
+
}
|
package/src/hooks.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @agentcms/react — TanStack Query Hooks
|
|
3
|
+
// ============================================================================
|
|
4
|
+
|
|
5
|
+
import { useQuery, keepPreviousData } from "@tanstack/react-query";
|
|
6
|
+
import { useAgentCMSClient } from "./provider.js";
|
|
7
|
+
import type {
|
|
8
|
+
GetPostsParams,
|
|
9
|
+
GetPostsResult,
|
|
10
|
+
GetCategoriesResult,
|
|
11
|
+
GetTagsResult,
|
|
12
|
+
AgentCMSPost,
|
|
13
|
+
} from "./types.js";
|
|
14
|
+
|
|
15
|
+
const STALE_TIME = 60_000; // 60s — matches server Cache-Control
|
|
16
|
+
|
|
17
|
+
export function useAgentCMSPosts(params: GetPostsParams = {}) {
|
|
18
|
+
const client = useAgentCMSClient();
|
|
19
|
+
return useQuery<GetPostsResult>({
|
|
20
|
+
queryKey: ["agentcms", "posts", params],
|
|
21
|
+
queryFn: () => client.getPosts(params),
|
|
22
|
+
staleTime: STALE_TIME,
|
|
23
|
+
placeholderData: keepPreviousData,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function useAgentCMSPost(slug: string | undefined | null) {
|
|
28
|
+
const client = useAgentCMSClient();
|
|
29
|
+
return useQuery<AgentCMSPost>({
|
|
30
|
+
queryKey: ["agentcms", "post", slug],
|
|
31
|
+
queryFn: () => client.getPost(slug!),
|
|
32
|
+
enabled: !!slug,
|
|
33
|
+
staleTime: STALE_TIME,
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function useAgentCMSCategories() {
|
|
38
|
+
const client = useAgentCMSClient();
|
|
39
|
+
return useQuery<GetCategoriesResult>({
|
|
40
|
+
queryKey: ["agentcms", "categories"],
|
|
41
|
+
queryFn: () => client.getCategories(),
|
|
42
|
+
staleTime: STALE_TIME,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function useAgentCMSTags() {
|
|
47
|
+
const client = useAgentCMSClient();
|
|
48
|
+
return useQuery<GetTagsResult>({
|
|
49
|
+
queryKey: ["agentcms", "tags"],
|
|
50
|
+
queryFn: () => client.getTags(),
|
|
51
|
+
staleTime: STALE_TIME,
|
|
52
|
+
});
|
|
53
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @agentcms/react — React SDK for AgentCMS
|
|
3
|
+
// ============================================================================
|
|
4
|
+
|
|
5
|
+
// Client
|
|
6
|
+
export { AgentCMSClient, AgentCMSError } from "./client.js";
|
|
7
|
+
|
|
8
|
+
// Provider
|
|
9
|
+
export { AgentCMSProvider, useAgentCMSClient } from "./provider.js";
|
|
10
|
+
export type { AgentCMSProviderProps } from "./provider.js";
|
|
11
|
+
|
|
12
|
+
// Hooks
|
|
13
|
+
export {
|
|
14
|
+
useAgentCMSPosts,
|
|
15
|
+
useAgentCMSPost,
|
|
16
|
+
useAgentCMSCategories,
|
|
17
|
+
useAgentCMSTags,
|
|
18
|
+
} from "./hooks.js";
|
|
19
|
+
|
|
20
|
+
// Types
|
|
21
|
+
export type {
|
|
22
|
+
AgentCMSPost,
|
|
23
|
+
GetPostsParams,
|
|
24
|
+
GetPostsResult,
|
|
25
|
+
GetCategoriesResult,
|
|
26
|
+
GetTagsResult,
|
|
27
|
+
SiteContext,
|
|
28
|
+
AgentCMSConfig,
|
|
29
|
+
} from "./types.js";
|
package/src/provider.tsx
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @agentcms/react — Context Provider
|
|
3
|
+
// ============================================================================
|
|
4
|
+
|
|
5
|
+
import { createContext, useContext, useMemo, type ReactNode } from "react";
|
|
6
|
+
import { AgentCMSClient } from "./client.js";
|
|
7
|
+
import type { AgentCMSConfig } from "./types.js";
|
|
8
|
+
|
|
9
|
+
const AgentCMSContext = createContext<AgentCMSClient | null>(null);
|
|
10
|
+
|
|
11
|
+
export interface AgentCMSProviderProps extends AgentCMSConfig {
|
|
12
|
+
children: ReactNode;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function AgentCMSProvider({
|
|
16
|
+
baseUrl = "/api",
|
|
17
|
+
apiKey,
|
|
18
|
+
children,
|
|
19
|
+
}: AgentCMSProviderProps) {
|
|
20
|
+
const client = useMemo(
|
|
21
|
+
() => new AgentCMSClient({ baseUrl, apiKey }),
|
|
22
|
+
[baseUrl, apiKey]
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
return (
|
|
26
|
+
<AgentCMSContext.Provider value={client}>
|
|
27
|
+
{children}
|
|
28
|
+
</AgentCMSContext.Provider>
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function useAgentCMSClient(): AgentCMSClient {
|
|
33
|
+
const client = useContext(AgentCMSContext);
|
|
34
|
+
if (!client) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
"useAgentCMSClient must be used within an <AgentCMSProvider>"
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
return client;
|
|
40
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// @agentcms/react — Client-side Types
|
|
3
|
+
// ============================================================================
|
|
4
|
+
|
|
5
|
+
export interface AgentCMSPost {
|
|
6
|
+
slug: string;
|
|
7
|
+
title: string;
|
|
8
|
+
description: string;
|
|
9
|
+
content: string;
|
|
10
|
+
contentHtml?: string;
|
|
11
|
+
author: string;
|
|
12
|
+
authorType: "agent" | "human";
|
|
13
|
+
tags: string[];
|
|
14
|
+
category?: string;
|
|
15
|
+
publishedAt: string;
|
|
16
|
+
updatedAt: string;
|
|
17
|
+
status: "published" | "draft" | "scheduled";
|
|
18
|
+
scheduledFor?: string;
|
|
19
|
+
featuredImage?: string;
|
|
20
|
+
ogImage?: string;
|
|
21
|
+
readingTime?: number;
|
|
22
|
+
featured?: boolean;
|
|
23
|
+
metadata: Record<string, unknown>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export interface GetPostsParams {
|
|
27
|
+
page?: number;
|
|
28
|
+
limit?: number;
|
|
29
|
+
tag?: string;
|
|
30
|
+
category?: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface GetPostsResult {
|
|
34
|
+
posts: AgentCMSPost[];
|
|
35
|
+
total: number;
|
|
36
|
+
totalPages: number;
|
|
37
|
+
page: number;
|
|
38
|
+
hasMore: boolean;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface GetCategoriesResult {
|
|
42
|
+
categories: Array<{ category: string; count: number }>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface GetTagsResult {
|
|
46
|
+
tags: Array<{ tag: string; count: number }>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface SiteContext {
|
|
50
|
+
site: {
|
|
51
|
+
name: string;
|
|
52
|
+
description: string;
|
|
53
|
+
url: string;
|
|
54
|
+
language: string;
|
|
55
|
+
};
|
|
56
|
+
writingGuidelines: {
|
|
57
|
+
tone: string;
|
|
58
|
+
targetAudience: string;
|
|
59
|
+
preferredLength: string;
|
|
60
|
+
};
|
|
61
|
+
existingContent: {
|
|
62
|
+
totalPosts: number;
|
|
63
|
+
recentTitles: string[];
|
|
64
|
+
existingTags: string[];
|
|
65
|
+
existingCategories: string[];
|
|
66
|
+
};
|
|
67
|
+
capabilities: {
|
|
68
|
+
maxContentLength: number;
|
|
69
|
+
markdownFeatures: string[];
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export interface AgentCMSConfig {
|
|
74
|
+
baseUrl?: string;
|
|
75
|
+
apiKey?: string;
|
|
76
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ES2022",
|
|
4
|
+
"module": "ES2022",
|
|
5
|
+
"moduleResolution": "bundler",
|
|
6
|
+
"outDir": "./dist",
|
|
7
|
+
"rootDir": "./src",
|
|
8
|
+
"declaration": true,
|
|
9
|
+
"declarationMap": true,
|
|
10
|
+
"sourceMap": true,
|
|
11
|
+
"strict": true,
|
|
12
|
+
"esModuleInterop": true,
|
|
13
|
+
"skipLibCheck": true,
|
|
14
|
+
"jsx": "react-jsx",
|
|
15
|
+
"lib": ["ES2022", "DOM"]
|
|
16
|
+
},
|
|
17
|
+
"include": ["src"],
|
|
18
|
+
"exclude": ["src/**/*.test.*"]
|
|
19
|
+
}
|