@obelism/content 0.0.0-stage → 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/dist/site.mjs ADDED
@@ -0,0 +1,302 @@
1
+ import { n as normalizeUrl, a as DEFAULT_TIMEOUT, D as DEFAULT_URL } from './config-c6qktlz6.mjs';
2
+
3
+ // Editing on your own site, outside the visual editor (the CMS's
4
+ // docs/site-editing.md). One handler serves everything under `/cms` (the
5
+ // `basePath`) on your site:
6
+ //
7
+ // - `/cms/login?return_to=/pricing` — sends the browser to Obelism Content
8
+ // to sign in, with a PKCE challenge, and…
9
+ // - `/cms/callback` — …takes it back: trades the one-time code for a site
10
+ // token, keeps it in an httpOnly cookie, calls `onSignIn` (turn on your
11
+ // framework's draft mode there) and returns to `return_to`.
12
+ // - `/cms/logout` — ends the session in the CMS, clears the cookies, calls
13
+ // `onSignOut`.
14
+ // - `/cms/api/…` — what the bridge's prompt bar calls in the browser,
15
+ // forwarded to the CMS with the token. The token never reaches page
16
+ // scripts.
17
+ //
18
+ // While signed in, render drafts by reading the delivery API with the token
19
+ // (`readSiteToken`), and the bridge shows the prompt bar with Save and
20
+ // Publish.
21
+ const SITE_TOKEN_COOKIE = 'obelism_content_token';
22
+ // Readable by the page: tells the bridge the site is being edited, and where
23
+ // this handler lives. Holds no secret.
24
+ const SITE_EDITING_COOKIE = 'obelism_content_editing';
25
+ const FLOW_COOKIE = 'obelism_content_flow';
26
+ // The bridge sends it with every write, which a cross-site form can't.
27
+ const SITE_REQUEST_HEADER = 'x-obelism-content';
28
+ const SITE_PATH = '/api/site/v1';
29
+ const FLOW_MAX_AGE = 10 * 60;
30
+ // The site token from a Cookie header (or a framework's cookie store), or
31
+ // null when not signed in to edit:
32
+ //
33
+ // const token = readSiteToken(request.headers.get('cookie'))
34
+ // const content = token ? new ContentClient({ token, init: { cache: 'no-store' } }) : delivery
35
+ const readSiteToken = (cookies)=>{
36
+ if (!cookies) return null;
37
+ if (typeof cookies !== 'string') return cookies.get(SITE_TOKEN_COOKIE)?.value || null;
38
+ return parseCookies(cookies).get(SITE_TOKEN_COOKIE) || null;
39
+ };
40
+ const parseCookies = (header)=>{
41
+ const cookies = new Map();
42
+ for (const part of header.split(';')){
43
+ const index = part.indexOf('=');
44
+ if (index < 0) continue;
45
+ const name = part.slice(0, index).trim();
46
+ if (!name || cookies.has(name)) continue;
47
+ try {
48
+ cookies.set(name, decodeURIComponent(part.slice(index + 1).trim()));
49
+ } catch {
50
+ cookies.set(name, part.slice(index + 1).trim());
51
+ }
52
+ }
53
+ return cookies;
54
+ };
55
+ const serializeCookie = (name, value, { maxAge, path, httpOnly, secure })=>[
56
+ `${name}=${encodeURIComponent(value)}`,
57
+ `Path=${path}`,
58
+ `Max-Age=${Math.max(0, Math.floor(maxAge))}`,
59
+ // Also Expires: Next.js re-serializes response cookies when draft mode
60
+ // changes, and drops a Max-Age of 0.
61
+ `Expires=${new Date(maxAge > 0 ? Date.now() + maxAge * 1000 : 0).toUTCString()}`,
62
+ 'SameSite=Lax',
63
+ httpOnly && 'HttpOnly',
64
+ secure && 'Secure'
65
+ ].filter(Boolean).join('; ');
66
+ const base64Url = (bytes)=>{
67
+ let binary = '';
68
+ for (const byte of bytes)binary += String.fromCharCode(byte);
69
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
70
+ };
71
+ const randomString = (bytes = 32)=>base64Url(crypto.getRandomValues(new Uint8Array(bytes)));
72
+ const pkceChallenge = async (verifier)=>base64Url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
73
+ // Only a path on this site: never an open redirect.
74
+ const safeReturnTo = (value)=>value && value.startsWith('/') && !value.startsWith('//') && !value.includes('\\') ? value : '/';
75
+ const normalizeBasePath = (basePath)=>`/${basePath.replace(/^\/+|\/+$/g, '')}`;
76
+ // What the browser may reach through `/cms/api/…`: reads, and the writes
77
+ // the prompt bar makes. Nothing else of the site API is exposed.
78
+ const PROXY_ROUTES = [
79
+ {
80
+ method: 'GET',
81
+ pattern: /^session$/
82
+ },
83
+ {
84
+ method: 'GET',
85
+ pattern: /^entries\/[\w-]+$/
86
+ },
87
+ {
88
+ method: 'POST',
89
+ pattern: /^entries\/[\w-]+\/(preview|prompt|save|publish)$/
90
+ }
91
+ ];
92
+ // The handler for everything under `basePath`. In Next.js:
93
+ //
94
+ // // app/cms/[...path]/route.ts
95
+ // const handler = createSiteEditing({
96
+ // spaceId: process.env.CONTENT_SPACE_ID!,
97
+ // environment: 'production',
98
+ // onSignIn: async () => (await draftMode()).enable(),
99
+ // onSignOut: async () => (await draftMode()).disable(),
100
+ // })
101
+ // export { handler as GET, handler as POST }
102
+ const createSiteEditing = ({ spaceId, environment, url, basePath = '/cms', siteUrl, onSignIn, onSignOut, timeout = DEFAULT_TIMEOUT, fetch: fetchImpl })=>{
103
+ const cms = normalizeUrl(url || DEFAULT_URL);
104
+ const base = normalizeBasePath(basePath);
105
+ const doFetch = fetchImpl ?? ((...args)=>fetch(...args));
106
+ const callCms = (path, init = {})=>doFetch(`${cms}${SITE_PATH}/${path}`, {
107
+ ...init,
108
+ redirect: 'manual',
109
+ signal: AbortSignal.timeout(timeout)
110
+ });
111
+ return async (request)=>{
112
+ const requestUrl = new URL(request.url);
113
+ const origin = siteUrl ? normalizeUrl(siteUrl) : requestUrl.origin;
114
+ const secure = origin.startsWith('https:');
115
+ const redirectUri = `${origin}${base}/callback`;
116
+ const cookies = parseCookies(request.headers.get('cookie') ?? '');
117
+ const path = requestUrl.pathname.startsWith(`${base}/`) ? requestUrl.pathname.slice(base.length + 1) : null;
118
+ const sessionCookies = (session)=>[
119
+ serializeCookie(SITE_TOKEN_COOKIE, session.token, {
120
+ maxAge: session.maxAge,
121
+ path: '/',
122
+ httpOnly: true,
123
+ secure
124
+ }),
125
+ serializeCookie(SITE_EDITING_COOKIE, session.token ? base : '', {
126
+ maxAge: session.maxAge,
127
+ path: '/',
128
+ httpOnly: false,
129
+ secure
130
+ })
131
+ ];
132
+ const clearedCookies = ()=>sessionCookies({
133
+ token: '',
134
+ maxAge: 0
135
+ });
136
+ const redirect = (location, setCookies = [])=>{
137
+ const headers = new Headers({
138
+ Location: location,
139
+ 'Cache-Control': 'no-store'
140
+ });
141
+ for (const cookie of setCookies)headers.append('Set-Cookie', cookie);
142
+ return new Response(null, {
143
+ status: 302,
144
+ headers
145
+ });
146
+ };
147
+ if (path === 'login' && request.method === 'GET') {
148
+ const state = randomString(16);
149
+ const verifier = randomString(48);
150
+ const flow = JSON.stringify({
151
+ state,
152
+ verifier,
153
+ returnTo: safeReturnTo(requestUrl.searchParams.get('return_to'))
154
+ });
155
+ const connect = new URL(`${cms}/site/connect`);
156
+ connect.search = new URLSearchParams({
157
+ space: spaceId,
158
+ environment,
159
+ redirect_uri: redirectUri,
160
+ state,
161
+ code_challenge: await pkceChallenge(verifier),
162
+ code_challenge_method: 'S256'
163
+ }).toString();
164
+ return redirect(connect.toString(), [
165
+ serializeCookie(FLOW_COOKIE, flow, {
166
+ maxAge: FLOW_MAX_AGE,
167
+ path: base,
168
+ httpOnly: true,
169
+ secure
170
+ })
171
+ ]);
172
+ }
173
+ if (path === 'callback' && request.method === 'GET') {
174
+ const clearFlow = serializeCookie(FLOW_COOKIE, '', {
175
+ maxAge: 0,
176
+ path: base,
177
+ httpOnly: true,
178
+ secure
179
+ });
180
+ let flow;
181
+ try {
182
+ flow = JSON.parse(cookies.get(FLOW_COOKIE) ?? '');
183
+ } catch {
184
+ flow = {};
185
+ }
186
+ const code = requestUrl.searchParams.get('code');
187
+ if (!code || typeof flow.state !== 'string' || typeof flow.verifier !== 'string' || flow.state !== requestUrl.searchParams.get('state')) {
188
+ return textResponse(400, 'This sign-in link is invalid or expired. Start again from the login link.', [
189
+ clearFlow
190
+ ]);
191
+ }
192
+ const response = await callCms('token', {
193
+ method: 'POST',
194
+ headers: {
195
+ 'Content-Type': 'application/json'
196
+ },
197
+ body: JSON.stringify({
198
+ code,
199
+ code_verifier: flow.verifier,
200
+ redirect_uri: redirectUri
201
+ })
202
+ });
203
+ if (!response.ok) {
204
+ return textResponse(400, 'Obelism Content did not accept the sign-in. Start again from the login link.', [
205
+ clearFlow
206
+ ]);
207
+ }
208
+ const session = await response.json();
209
+ await onSignIn?.(session);
210
+ const maxAge = (Date.parse(session.expiresAt) - Date.now()) / 1000;
211
+ return redirect(safeReturnTo(flow.returnTo), [
212
+ clearFlow,
213
+ ...sessionCookies({
214
+ token: session.token,
215
+ maxAge
216
+ })
217
+ ]);
218
+ }
219
+ if (path === 'logout') {
220
+ const token = cookies.get(SITE_TOKEN_COOKIE);
221
+ if (token) {
222
+ await callCms('session', {
223
+ method: 'DELETE',
224
+ headers: {
225
+ Authorization: `Bearer ${token}`
226
+ }
227
+ }).catch(()=>null);
228
+ }
229
+ await onSignOut?.();
230
+ return redirect(safeReturnTo(requestUrl.searchParams.get('return_to')), clearedCookies());
231
+ }
232
+ if (path?.startsWith('api/')) {
233
+ const route = path.slice('api/'.length);
234
+ if (!PROXY_ROUTES.some(({ method, pattern })=>method === request.method && pattern.test(route))) {
235
+ return Response.json({
236
+ error: 'Not found'
237
+ }, {
238
+ status: 404
239
+ });
240
+ }
241
+ if (request.method !== 'GET' && request.headers.get(SITE_REQUEST_HEADER) !== '1') {
242
+ return Response.json({
243
+ error: 'Forbidden'
244
+ }, {
245
+ status: 403
246
+ });
247
+ }
248
+ const token = cookies.get(SITE_TOKEN_COOKIE);
249
+ if (!token) {
250
+ return Response.json({
251
+ error: 'Not signed in'
252
+ }, {
253
+ status: 401
254
+ });
255
+ }
256
+ const response = await callCms(route, {
257
+ method: request.method,
258
+ headers: {
259
+ Authorization: `Bearer ${token}`,
260
+ ...request.method !== 'GET' && {
261
+ 'Content-Type': 'application/json'
262
+ }
263
+ },
264
+ ...request.method !== 'GET' && {
265
+ body: await request.text()
266
+ }
267
+ });
268
+ const headers = new Headers({
269
+ 'Content-Type': 'application/json',
270
+ 'Cache-Control': 'no-store'
271
+ });
272
+ // The session ended in the CMS: stop showing the editing UI.
273
+ if (response.status === 401) {
274
+ for (const cookie of clearedCookies()){
275
+ headers.append('Set-Cookie', cookie);
276
+ }
277
+ }
278
+ return new Response(await response.text(), {
279
+ status: response.status,
280
+ headers
281
+ });
282
+ }
283
+ return Response.json({
284
+ error: 'Not found'
285
+ }, {
286
+ status: 404
287
+ });
288
+ };
289
+ };
290
+ const textResponse = (status, text, setCookies)=>{
291
+ const headers = new Headers({
292
+ 'Content-Type': 'text/plain; charset=utf-8',
293
+ 'Cache-Control': 'no-store'
294
+ });
295
+ for (const cookie of setCookies)headers.append('Set-Cookie', cookie);
296
+ return new Response(text, {
297
+ status,
298
+ headers
299
+ });
300
+ };
301
+
302
+ export { SITE_EDITING_COOKIE, SITE_REQUEST_HEADER, SITE_TOKEN_COOKIE, createSiteEditing, pkceChallenge, readSiteToken, safeReturnTo };
@@ -0,0 +1,120 @@
1
+ type Environment = 'develop' | 'staging' | 'production';
2
+ type RichTextFormat = 'json' | 'html';
3
+ type Asset = {
4
+ id: string;
5
+ url: string;
6
+ filename: string;
7
+ mimeType: string;
8
+ size: number;
9
+ width: number | null;
10
+ height: number | null;
11
+ title: string | Record<string, string> | null;
12
+ alt: string | Record<string, string> | null;
13
+ };
14
+ type Entry<TFields extends Record<string, unknown> = Record<string, unknown>, TContentType extends string = string> = {
15
+ id: string;
16
+ contentType: TContentType;
17
+ name: string;
18
+ slug: string | null;
19
+ path: string | null;
20
+ publishedAt: string | null;
21
+ firstPublishedAt: string | null;
22
+ updatedAt: string;
23
+ fields: TFields;
24
+ };
25
+ type EntryStub<TContentType extends string = string> = {
26
+ id: string;
27
+ contentType: TContentType;
28
+ };
29
+ type Block<TFields extends Record<string, unknown> = Record<string, unknown>, TType extends string = string> = {
30
+ _uid: string;
31
+ _type: TType;
32
+ } & TFields;
33
+ type RichTextMark = {
34
+ type: 'bold' | 'italic' | 'underline' | 'strike' | 'code' | 'link' | string;
35
+ attrs?: Record<string, unknown>;
36
+ };
37
+ type RichTextNode = {
38
+ type: string;
39
+ attrs?: Record<string, unknown>;
40
+ content?: RichTextNode[];
41
+ text?: string;
42
+ marks?: RichTextMark[];
43
+ };
44
+ type RichTextDocument = RichTextNode & {
45
+ type: 'doc';
46
+ };
47
+ type EntryList<TEntry extends Entry = Entry> = {
48
+ items: TEntry[];
49
+ total: number;
50
+ limit: number;
51
+ skip: number;
52
+ };
53
+ type ContentTypeKind = 'page' | 'data' | 'block';
54
+ type BaseField = {
55
+ apiId: string;
56
+ name: string;
57
+ description?: string;
58
+ required?: boolean;
59
+ localized?: boolean;
60
+ };
61
+ type FieldDefinition = BaseField & ({
62
+ type: 'text';
63
+ minLength?: number;
64
+ maxLength?: number;
65
+ pattern?: string;
66
+ } | {
67
+ type: 'textarea';
68
+ minLength?: number;
69
+ maxLength?: number;
70
+ } | {
71
+ type: 'richtext';
72
+ } | {
73
+ type: 'number';
74
+ integer?: boolean;
75
+ min?: number;
76
+ max?: number;
77
+ } | {
78
+ type: 'boolean';
79
+ } | {
80
+ type: 'datetime';
81
+ withTime?: boolean;
82
+ } | {
83
+ type: 'select';
84
+ multiple?: boolean;
85
+ options: {
86
+ value: string;
87
+ label: string;
88
+ }[];
89
+ } | {
90
+ type: 'asset';
91
+ multiple?: boolean;
92
+ mimeTypes?: string[];
93
+ } | {
94
+ type: 'reference';
95
+ multiple?: boolean;
96
+ contentTypes?: string[];
97
+ } | {
98
+ type: 'blocks';
99
+ allowedBlocks?: string[];
100
+ min?: number;
101
+ max?: number;
102
+ } | {
103
+ type: 'json';
104
+ });
105
+ type FieldType = FieldDefinition['type'];
106
+ type ContentTypeDefinition = {
107
+ apiId: string;
108
+ name: string;
109
+ kind: ContentTypeKind;
110
+ description?: string | null;
111
+ fields: FieldDefinition[];
112
+ };
113
+ type ModelFile = {
114
+ $schema?: string;
115
+ version: 1;
116
+ contentTypes: ContentTypeDefinition[];
117
+ };
118
+
119
+ export type { Asset as A, Block as B, ContentTypeDefinition as C, Entry as E, FieldDefinition as F, ModelFile as M, RichTextFormat as R, EntryList as a, EntryStub as b, RichTextNode as c, ContentTypeKind as d, Environment as e, FieldType as f, RichTextDocument as g, RichTextMark as h };
120
+ //# sourceMappingURL=types-pa96z6po.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-pa96z6po.d.ts","sources":["../src/types.ts"],"mappings":"AAAA,KAAK,WAAW;AAChB,KAAK,cAAc;AACnB,KAAK,KAAK;AACV;AACA;AACA;AACA;AACA;AACA;AACA;AACA,oBAAoB,MAAM;AAC1B,kBAAkB,MAAM;AACxB;AACA,KAAK,KAAK,iBAAiB,MAAM,oBAAoB,MAAM;AAC3D;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,SAAS;AACd;AACA;AACA;AACA,KAAK,KAAK,iBAAiB,MAAM,oBAAoB,MAAM;AAC3D;AACA;AACA;AACA,KAAK,YAAY;AACjB;AACA,YAAY,MAAM;AAClB;AACA,KAAK,YAAY;AACjB;AACA,YAAY,MAAM;AAClB,cAAc,YAAY;AAC1B;AACA,YAAY,YAAY;AACxB;AACA,KAAK,gBAAgB,GAAG,YAAY;AACpC;AACA;AACA,KAAK,SAAS,gBAAgB,KAAK,GAAG,KAAK;AAC3C;AACA;AACA;AACA;AACA;AACA,KAAK,eAAe;AACpB,KAAK,SAAS;AACd;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,eAAe,GAAG,SAAS;AAChC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,KAAK,SAAS,GAAG,eAAe;AAChC,KAAK,qBAAqB;AAC1B;AACA;AACA,UAAU,eAAe;AACzB;AACA,YAAY,eAAe;AAC3B;AACA,KAAK,SAAS;AACd;AACA;AACA,kBAAkB,qBAAqB;AACvC;;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,92 @@
1
1
  {
2
- "name": "@obelism/content",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@obelism/content",
3
+ "description": "Obelism Content SDK: the delivery API client, the visual editor bridge with prompt editing, editing on your own site, and the content model CLI",
4
+ "version": "0.1.0",
5
+ "keywords": [
6
+ "cms",
7
+ "headless-cms",
8
+ "visual-editor",
9
+ "typescript",
10
+ "obelism"
11
+ ],
12
+ "license": "MIT",
13
+ "author": "Obelism <hello@obelism.studio> (https://www.obelism.studio)",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "https://github.com/Obelism/content-sdk"
17
+ },
18
+ "sideEffects": false,
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "bin": {
23
+ "content": "./dist/bin/content.js"
24
+ },
25
+ "exports": {
26
+ ".": {
27
+ "import": {
28
+ "types": "./dist/index.d.mts",
29
+ "default": "./dist/index.mjs"
30
+ },
31
+ "require": {
32
+ "types": "./dist/index.d.ts",
33
+ "default": "./dist/index.js"
34
+ }
35
+ },
36
+ "./bridge": {
37
+ "import": {
38
+ "types": "./dist/bridge.d.mts",
39
+ "default": "./dist/bridge.mjs"
40
+ },
41
+ "require": {
42
+ "types": "./dist/bridge.d.ts",
43
+ "default": "./dist/bridge.js"
44
+ }
45
+ },
46
+ "./site": {
47
+ "import": {
48
+ "types": "./dist/site.d.mts",
49
+ "default": "./dist/site.mjs"
50
+ },
51
+ "require": {
52
+ "types": "./dist/site.d.ts",
53
+ "default": "./dist/site.js"
54
+ }
55
+ },
56
+ "./prompt": {
57
+ "import": {
58
+ "types": "./dist/prompt.d.mts",
59
+ "default": "./dist/prompt.mjs"
60
+ },
61
+ "require": {
62
+ "types": "./dist/prompt.d.ts",
63
+ "default": "./dist/prompt.js"
64
+ }
65
+ }
66
+ },
67
+ "scripts": {
68
+ "build": "bunchee",
69
+ "dev": "bunchee --watch --no-clean",
70
+ "test": "vitest",
71
+ "test:coverage": "vitest run --coverage",
72
+ "test:ci": "vitest run",
73
+ "lint": "npm-run-all --parallel lint:*",
74
+ "lint:oxlint": "oxlint",
75
+ "lint:types": "tsc --noEmit",
76
+ "clean": "rm -rf ./node_modules && rm -rf ./dist && rm -rf ./.turbo"
77
+ },
78
+ "devDependencies": {
79
+ "@obelism/content-typescript-config": "^0.0.0",
80
+ "@types/node": "^24.0.0",
81
+ "@typescript/typescript6": "^6.0.2",
82
+ "bunchee": "^7.0.2",
83
+ "jsdom": "^30.1.2",
84
+ "npm-run-all2": "^9.0.2",
85
+ "oxlint": "^1.88.0",
86
+ "typescript": "^7.0.2",
87
+ "vitest": "^5.0.4"
88
+ },
89
+ "engines": {
90
+ "node": ">=20"
91
+ }
92
+ }