sitecms-next 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oskar Östlind
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 CHANGED
@@ -1,3 +1,108 @@
1
- # Temporary Holding Version
1
+ # sitecms-next
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ ```bash
4
+ npm install sitecms-next
5
+ ```
6
+
7
+ Typad klient för att hämta innehåll från sitecms i en Next.js-sajt (App Router).
8
+ Inga beroenden. All hämtning taggas med `sitecms` så att innehållet kan
9
+ uppdateras direkt när kunden sparar i panelen.
10
+
11
+ > Vill du hellre slippa beroendet? Koden på integrationssidan i panelen
12
+ > (`lib/sitecms.ts`) är identisk och kan klistras in direkt.
13
+
14
+ ## Miljövariabler
15
+
16
+ ```env
17
+ CMS_API_URL=https://sitecms-zeta.vercel.app
18
+ CMS_SITE=din-sajt
19
+ CMS_API_KEY=...
20
+ CMS_REVALIDATE_SECRET=...
21
+ ```
22
+
23
+ Värdena finns under **Integration** för sajten i sitecms.
24
+
25
+ ## Användning
26
+
27
+ ```ts
28
+ // lib/cms.ts
29
+ import { createSitecms } from "sitecms-next";
30
+
31
+ export const cms = createSitecms({
32
+ apiUrl: process.env.CMS_API_URL!,
33
+ site: process.env.CMS_SITE!,
34
+ apiKey: process.env.CMS_API_KEY!,
35
+ });
36
+ ```
37
+
38
+ ```tsx
39
+ // app/page.tsx
40
+ import { cms } from "@/lib/cms";
41
+
42
+ export default async function Home() {
43
+ const content = await cms.getContent();
44
+ const hero = cms.image(content, "home", "hero.image");
45
+
46
+ return (
47
+ <main>
48
+ <h1>{cms.text(content, "home", "hero.title", "Välkommen")}</h1>
49
+ {hero ? <img src={hero.src} alt={hero.alt} /> : null}
50
+ <div dangerouslySetInnerHTML={{ __html: cms.block(content, "home", "intro.body").html }} />
51
+ </main>
52
+ );
53
+ }
54
+ ```
55
+
56
+ | Funktion | Returnerar |
57
+ |---|---|
58
+ | `getContent()` | Sidor med block, tjänster och SEO |
59
+ | `getPosts()` | Publicerade inlägg (utan brödtext), nyast först |
60
+ | `getPost(slug)` | Ett inlägg med `body` (markdown) och `bodyHtml`, eller `null` |
61
+ | `health()` | `{ ok, site, pages, lastSchemaSyncAt }` — verifierar nyckeln |
62
+ | `block(content, page, key)` | `{ value, html, alt }` — alltid strängar |
63
+ | `text(content, page, key, fallback?)` | Blockets text |
64
+ | `image(content, page, key)` | `{ src, alt }` eller `null` |
65
+ | `seo(content, page)` | SEO-uppgifter för sidan eller `null` |
66
+
67
+ Fel från API:et kastas som `SitecmsError` med `status` (401 fel nyckel, 404 okänd sajt).
68
+
69
+ ## Revalidering
70
+
71
+ ```ts
72
+ // app/api/sitecms/revalidate/route.ts
73
+ import { revalidateTag } from "next/cache";
74
+ import { verifyRevalidateSecret } from "sitecms-next";
75
+
76
+ export async function POST(request: Request) {
77
+ const body = (await request.json().catch(() => null)) as { secret?: unknown } | null;
78
+ if (!(await verifyRevalidateSecret(body?.secret, process.env.CMS_REVALIDATE_SECRET))) {
79
+ return Response.json({ revalidated: false }, { status: 401 });
80
+ }
81
+ revalidateTag("sitecms");
82
+ return Response.json({ revalidated: true });
83
+ }
84
+ ```
85
+
86
+ Ange sedan `https://din-domän.se/api/sitecms/revalidate` som revalidate-URL i panelen.
87
+
88
+ ## Schema
89
+
90
+ `sitecms.config.ts` beskriver vilka sidor och fält sajten har:
91
+
92
+ ```ts
93
+ import { defineConfig } from "sitecms-next";
94
+
95
+ export default defineConfig({
96
+ version: 1,
97
+ pages: [
98
+ {
99
+ slug: "home",
100
+ title: "Startsida",
101
+ blocks: [{ key: "hero.title", type: "text", label: "Rubrik", default: "Välkommen" }],
102
+ },
103
+ ],
104
+ });
105
+ ```
106
+
107
+ Synka den med `scripts/sitecms-sync.ts` från integrationssidan (lägg i
108
+ `"prebuild"`). Fullständig dokumentation: `/docs` i sitecms.
@@ -0,0 +1,171 @@
1
+ /**
2
+ * sitecms-next — typad sitecms-klient för Next.js App Router.
3
+ *
4
+ * import { createSitecms } from "sitecms-next";
5
+ * export const cms = createSitecms({
6
+ * apiUrl: process.env.CMS_API_URL!,
7
+ * site: process.env.CMS_SITE!,
8
+ * apiKey: process.env.CMS_API_KEY!,
9
+ * });
10
+ *
11
+ * const content = await cms.getContent();
12
+ * cms.text(content, "home", "hero.title");
13
+ *
14
+ * Inga beroenden. Alla anrop använder `fetch` med `next: { tags: [tag] }` så
15
+ * att en revalidate-route kan tömma cachen med `revalidateTag("sitecms")`.
16
+ * Samma kod som copy-paste-varianten `lib/sitecms.ts` i panelen.
17
+ */
18
+ export type BlockType = "text" | "richtext" | "image";
19
+ export type Block = {
20
+ key: string;
21
+ type: BlockType;
22
+ /** Text, markdown (richtext) eller bild-URL (image). */
23
+ value: string | null;
24
+ /** Bildbeskrivning för image-block, annars null. */
25
+ alt: string | null;
26
+ /** Färdig HTML för richtext-block, annars null. */
27
+ html: string | null;
28
+ label?: string | null;
29
+ };
30
+ export type Page = {
31
+ slug: string;
32
+ title: string;
33
+ description?: string | null;
34
+ blocks: Block[];
35
+ };
36
+ export type Service = {
37
+ title: string;
38
+ description: string | null;
39
+ price: string | null;
40
+ };
41
+ export type Seo = {
42
+ pageSlug: string;
43
+ title: string | null;
44
+ description: string | null;
45
+ ogImage: string | null;
46
+ };
47
+ export type Content = {
48
+ site: {
49
+ name: string;
50
+ domain: string | null;
51
+ };
52
+ pages: Page[];
53
+ services: Service[];
54
+ seo: Seo[];
55
+ };
56
+ export type PostSummary = {
57
+ slug: string;
58
+ title: string;
59
+ excerpt: string | null;
60
+ coverImage: string | null;
61
+ coverImageAlt: string | null;
62
+ publishedAt: string | null;
63
+ };
64
+ export type Post = PostSummary & {
65
+ /** Markdown. */
66
+ body: string | null;
67
+ /** body renderad till HTML. */
68
+ bodyHtml: string;
69
+ };
70
+ export type Health = {
71
+ ok: true;
72
+ site: {
73
+ name: string;
74
+ slug: string;
75
+ };
76
+ pages: number;
77
+ lastSchemaSyncAt: string | null;
78
+ };
79
+ export type ResolvedBlock = {
80
+ value: string;
81
+ html: string;
82
+ alt: string;
83
+ };
84
+ export type SitecmsOptions = {
85
+ /** Bas-URL till sitecms, t.ex. "https://sitecms-zeta.vercel.app". */
86
+ apiUrl: string;
87
+ /** Sajtens slug i sitecms. */
88
+ site: string;
89
+ /** API-nyckel (skickas som x-api-key). Håll den på serversidan. */
90
+ apiKey: string;
91
+ /** Cache-tagg för Next.js fetch-cachen (default "sitecms"). */
92
+ tag?: string;
93
+ /** Egen fetch, t.ex. för tester. Default globalThis.fetch. */
94
+ fetch?: typeof fetch;
95
+ };
96
+ export declare class SitecmsError extends Error {
97
+ readonly status: number;
98
+ constructor(message: string, status: number);
99
+ }
100
+ /**
101
+ * Ett block som alltid går att rendera: tomma strängar i stället för null.
102
+ * `html` är färdig HTML för richtext och HTML-escapad text för övriga typer.
103
+ */
104
+ export declare function block(content: Content, pageSlug: string, key: string): ResolvedBlock;
105
+ /** Textvärdet för ett block, eller `fallback` om det är tomt. */
106
+ export declare function text(content: Content, pageSlug: string, key: string, fallback?: string): string;
107
+ /** Bild-URL + alt-text för ett image-block, eller null om ingen bild är vald. */
108
+ export declare function image(content: Content, pageSlug: string, key: string): {
109
+ src: string;
110
+ alt: string;
111
+ } | null;
112
+ /** SEO-uppgifter för en sida (passar i generateMetadata). */
113
+ export declare function seo(content: Content, pageSlug: string): Seo | null;
114
+ export declare function createSitecms(options: SitecmsOptions): {
115
+ /** Cache-taggen som alla anrop använder. */
116
+ tag: string;
117
+ /** Hela sajtens innehåll: sidor med block, tjänster och SEO. */
118
+ getContent(): Promise<Content>;
119
+ /** Publicerade inlägg, nyast först (utan brödtext). */
120
+ getPosts(): Promise<PostSummary[]>;
121
+ /** Ett publicerat inlägg, eller null om det inte finns. */
122
+ getPost(slug: string): Promise<Post | null>;
123
+ /** Verifierar slug + nyckel. Kastar SitecmsError (401/404) om något är fel. */
124
+ health(): Promise<Health>;
125
+ block: typeof block;
126
+ text: typeof text;
127
+ image: typeof image;
128
+ seo: typeof seo;
129
+ };
130
+ export type Sitecms = ReturnType<typeof createSitecms>;
131
+ /**
132
+ * Hjälpare för `app/api/sitecms/revalidate/route.ts`:
133
+ *
134
+ * import { revalidateTag } from "next/cache";
135
+ * import { verifyRevalidateSecret } from "sitecms-next";
136
+ *
137
+ * export async function POST(request: Request) {
138
+ * const body = await request.json().catch(() => null);
139
+ * if (!(await verifyRevalidateSecret(body?.secret, process.env.CMS_REVALIDATE_SECRET))) {
140
+ * return Response.json({ revalidated: false }, { status: 401 });
141
+ * }
142
+ * revalidateTag("sitecms");
143
+ * return Response.json({ revalidated: true });
144
+ * }
145
+ *
146
+ * Jämför i konstant tid via SHA-256 (Web Crypto), fungerar i både Node och Edge.
147
+ */
148
+ export declare function verifyRevalidateSecret(received: unknown, expected: string | undefined): Promise<boolean>;
149
+ export type SitecmsBlock = {
150
+ /** Unik per sida. a–z, 0–9, punkt, bindestreck, understreck. */
151
+ key: string;
152
+ type: BlockType;
153
+ label?: string;
154
+ help?: string;
155
+ default?: string;
156
+ defaultAlt?: string;
157
+ };
158
+ export type SitecmsPage = {
159
+ slug: string;
160
+ title: string;
161
+ description?: string;
162
+ blocks: SitecmsBlock[];
163
+ };
164
+ export type SitecmsConfig = {
165
+ version: 1;
166
+ pages: SitecmsPage[];
167
+ prune?: boolean;
168
+ };
169
+ /** Identitetsfunktion för typad config: `export default defineConfig({ ... })`. */
170
+ export declare function defineConfig(config: SitecmsConfig): SitecmsConfig;
171
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,MAAM,MAAM,SAAS,GAAG,MAAM,GAAG,UAAU,GAAG,OAAO,CAAC;AAEtD,MAAM,MAAM,KAAK,GAAG;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,SAAS,CAAC;IAChB,wDAAwD;IACxD,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,oDAAoD;IACpD,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,mDAAmD;IACnD,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,MAAM,EAAE,KAAK,EAAE,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG;IACpB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAA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AO,CAAC,WAAW,EAAE,CAAC;IAKxC,2DAA2D;kBACvC,MAAM,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAKjD,+EAA+E;cAC/D,OAAO,CAAC,MAAM,CAAC;;;;;EASlC;AAED,MAAM,MAAM,OAAO,GAAG,UAAU,CAAC,OAAO,aAAa,CAAC,CAAC;AAEvD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,sBAAsB,CAAC,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAAC,OAAO,CAAC,CAY9G;AAMD,MAAM,MAAM,YAAY,GAAG;IACzB,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;IACZ,IAAI,EAAE,SAAS,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,WAAW,GAAG;IACxB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,MAAM,EAAE,YAAY,EAAE,CAAC;CACxB,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG;IAC1B,OAAO,EAAE,CAAC,CAAC;IACX,KAAK,EAAE,WAAW,EAAE,CAAC;IACrB,KAAK,CAAC,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,mFAAmF;AACnF,wBAAgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAEjE"}
package/dist/index.js ADDED
@@ -0,0 +1,147 @@
1
+ /**
2
+ * sitecms-next — typad sitecms-klient för Next.js App Router.
3
+ *
4
+ * import { createSitecms } from "sitecms-next";
5
+ * export const cms = createSitecms({
6
+ * apiUrl: process.env.CMS_API_URL!,
7
+ * site: process.env.CMS_SITE!,
8
+ * apiKey: process.env.CMS_API_KEY!,
9
+ * });
10
+ *
11
+ * const content = await cms.getContent();
12
+ * cms.text(content, "home", "hero.title");
13
+ *
14
+ * Inga beroenden. Alla anrop använder `fetch` med `next: { tags: [tag] }` så
15
+ * att en revalidate-route kan tömma cachen med `revalidateTag("sitecms")`.
16
+ * Samma kod som copy-paste-varianten `lib/sitecms.ts` i panelen.
17
+ */
18
+ export class SitecmsError extends Error {
19
+ status;
20
+ constructor(message, status) {
21
+ super(message);
22
+ this.status = status;
23
+ this.name = "SitecmsError";
24
+ }
25
+ }
26
+ function escapeHtml(value) {
27
+ return value
28
+ .replace(/&/g, "&amp;")
29
+ .replace(/</g, "&lt;")
30
+ .replace(/>/g, "&gt;")
31
+ .replace(/"/g, "&quot;");
32
+ }
33
+ /**
34
+ * Ett block som alltid går att rendera: tomma strängar i stället för null.
35
+ * `html` är färdig HTML för richtext och HTML-escapad text för övriga typer.
36
+ */
37
+ export function block(content, pageSlug, key) {
38
+ const found = content.pages.find((p) => p.slug === pageSlug)?.blocks.find((b) => b.key === key);
39
+ const value = found?.value ?? "";
40
+ return {
41
+ value,
42
+ html: found?.html ?? escapeHtml(value),
43
+ alt: found?.alt ?? "",
44
+ };
45
+ }
46
+ /** Textvärdet för ett block, eller `fallback` om det är tomt. */
47
+ export function text(content, pageSlug, key, fallback = "") {
48
+ return block(content, pageSlug, key).value || fallback;
49
+ }
50
+ /** Bild-URL + alt-text för ett image-block, eller null om ingen bild är vald. */
51
+ export function image(content, pageSlug, key) {
52
+ const { value, alt } = block(content, pageSlug, key);
53
+ return value ? { src: value, alt } : null;
54
+ }
55
+ /** SEO-uppgifter för en sida (passar i generateMetadata). */
56
+ export function seo(content, pageSlug) {
57
+ return content.seo.find((s) => s.pageSlug === pageSlug) ?? null;
58
+ }
59
+ export function createSitecms(options) {
60
+ const apiUrl = options.apiUrl.trim().replace(/\/+$/, "");
61
+ const tag = options.tag ?? "sitecms";
62
+ const doFetch = options.fetch ?? globalThis.fetch;
63
+ if (!apiUrl)
64
+ throw new Error("sitecms-next: apiUrl saknas (CMS_API_URL).");
65
+ if (!options.site)
66
+ throw new Error("sitecms-next: site saknas (CMS_SITE).");
67
+ if (!options.apiKey)
68
+ throw new Error("sitecms-next: apiKey saknas (CMS_API_KEY).");
69
+ const base = `${apiUrl}/api/v1/sites/${encodeURIComponent(options.site)}`;
70
+ async function request(path, { allow404 = false } = {}) {
71
+ const init = {
72
+ headers: { "x-api-key": options.apiKey },
73
+ next: { tags: [tag] },
74
+ };
75
+ const res = await doFetch(`${base}${path}`, init);
76
+ if (allow404 && res.status === 404)
77
+ return null;
78
+ if (!res.ok) {
79
+ const body = (await res.json().catch(() => null));
80
+ throw new SitecmsError(`sitecms: ${body?.error ?? res.statusText} (HTTP ${res.status}, ${path})`, res.status);
81
+ }
82
+ return (await res.json());
83
+ }
84
+ return {
85
+ /** Cache-taggen som alla anrop använder. */
86
+ tag,
87
+ /** Hela sajtens innehåll: sidor med block, tjänster och SEO. */
88
+ async getContent() {
89
+ return (await request("/content"));
90
+ },
91
+ /** Publicerade inlägg, nyast först (utan brödtext). */
92
+ async getPosts() {
93
+ const data = await request("/posts");
94
+ return data?.posts ?? [];
95
+ },
96
+ /** Ett publicerat inlägg, eller null om det inte finns. */
97
+ async getPost(slug) {
98
+ const data = await request(`/posts/${encodeURIComponent(slug)}`, { allow404: true });
99
+ return data?.post ?? null;
100
+ },
101
+ /** Verifierar slug + nyckel. Kastar SitecmsError (401/404) om något är fel. */
102
+ async health() {
103
+ return (await request("/health"));
104
+ },
105
+ block,
106
+ text,
107
+ image,
108
+ seo,
109
+ };
110
+ }
111
+ /**
112
+ * Hjälpare för `app/api/sitecms/revalidate/route.ts`:
113
+ *
114
+ * import { revalidateTag } from "next/cache";
115
+ * import { verifyRevalidateSecret } from "sitecms-next";
116
+ *
117
+ * export async function POST(request: Request) {
118
+ * const body = await request.json().catch(() => null);
119
+ * if (!(await verifyRevalidateSecret(body?.secret, process.env.CMS_REVALIDATE_SECRET))) {
120
+ * return Response.json({ revalidated: false }, { status: 401 });
121
+ * }
122
+ * revalidateTag("sitecms");
123
+ * return Response.json({ revalidated: true });
124
+ * }
125
+ *
126
+ * Jämför i konstant tid via SHA-256 (Web Crypto), fungerar i både Node och Edge.
127
+ */
128
+ export async function verifyRevalidateSecret(received, expected) {
129
+ if (typeof received !== "string" || !received || !expected)
130
+ return false;
131
+ const enc = new TextEncoder();
132
+ const [a, b] = await Promise.all([
133
+ crypto.subtle.digest("SHA-256", enc.encode(received)),
134
+ crypto.subtle.digest("SHA-256", enc.encode(expected)),
135
+ ]);
136
+ const va = new Uint8Array(a);
137
+ const vb = new Uint8Array(b);
138
+ let diff = 0;
139
+ for (let i = 0; i < va.length; i++)
140
+ diff |= va[i] ^ vb[i];
141
+ return diff === 0;
142
+ }
143
+ /** Identitetsfunktion för typad config: `export default defineConfig({ ... })`. */
144
+ export function defineConfig(config) {
145
+ return config;
146
+ }
147
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAiFH,MAAM,OAAO,YAAa,SAAQ,KAAK;IAG1B;IAFX,YACE,OAAe,EACN,MAAc;QAEvB,KAAK,CAAC,OAAO,CAAC,CAAC;QAFN,WAAM,GAAN,MAAM,CAAQ;QAGvB,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;IAC7B,CAAC;CACF;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,KAAK;SACT,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,MAAM,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;AAC7B,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,KAAK,CAAC,OAAgB,EAAE,QAAgB,EAAE,GAAW;IACnE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MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;QACrD,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,SAAS,EAAE,GAAG,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;KACtD,CAAC,CAAC;IACH,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC7B,MAAM,EAAE,GAAG,IAAI,UAAU,CAAC,CAAC,CAAC,CAAC;IAC7B,IAAI,IAAI,GAAG,CAAC,CAAC;IACb,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,EAAE,CAAC,MAAM,EAAE,CAAC,EAAE;QAAE,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IAC1D,OAAO,IAAI,KAAK,CAAC,CAAC;AACpB,CAAC;AA6BD,mFAAmF;AACnF,MAAM,UAAU,YAAY,CAAC,MAAqB;IAChD,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "sitecms-next",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Typad sitecms-klient för Next.js App Router — hämta innehåll, inlägg och block med cache-taggen \"sitecms\". Inga beroenden.",
5
+ "type": "module",
6
+ "main": "./dist/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js",
12
+ "default": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "src",
18
+ "README.md",
19
+ "LICENSE"
20
+ ],
21
+ "sideEffects": false,
22
+ "license": "MIT",
23
+ "peerDependencies": {
24
+ "next": ">=14.2"
25
+ },
26
+ "peerDependenciesMeta": {
27
+ "next": {
28
+ "optional": true
29
+ }
30
+ },
31
+ "engines": {
32
+ "node": ">=18.17"
33
+ },
34
+ "keywords": [
35
+ "sitecms",
36
+ "cms",
37
+ "nextjs",
38
+ "headless"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.json",
42
+ "clean": "rm -rf dist",
43
+ "prepublishOnly": "npm run clean && npm run build",
44
+ "typecheck": "tsc -p tsconfig.json --noEmit"
45
+ },
46
+ "devDependencies": {
47
+ "typescript": "^5.6.0"
48
+ },
49
+ "repository": {
50
+ "type": "git",
51
+ "url": "git+https://github.com/oskarostlind/sitecms.git",
52
+ "directory": "packages/sitecms-next"
53
+ },
54
+ "homepage": "https://sitecms-zeta.vercel.app/docs",
55
+ "bugs": {
56
+ "url": "https://github.com/oskarostlind/sitecms/issues"
57
+ },
58
+ "author": "Oskar Östlind",
59
+ "publishConfig": {
60
+ "access": "public"
61
+ }
62
+ }
package/src/index.ts ADDED
@@ -0,0 +1,272 @@
1
+ /**
2
+ * sitecms-next — typad sitecms-klient för Next.js App Router.
3
+ *
4
+ * import { createSitecms } from "sitecms-next";
5
+ * export const cms = createSitecms({
6
+ * apiUrl: process.env.CMS_API_URL!,
7
+ * site: process.env.CMS_SITE!,
8
+ * apiKey: process.env.CMS_API_KEY!,
9
+ * });
10
+ *
11
+ * const content = await cms.getContent();
12
+ * cms.text(content, "home", "hero.title");
13
+ *
14
+ * Inga beroenden. Alla anrop använder `fetch` med `next: { tags: [tag] }` så
15
+ * att en revalidate-route kan tömma cachen med `revalidateTag("sitecms")`.
16
+ * Samma kod som copy-paste-varianten `lib/sitecms.ts` i panelen.
17
+ */
18
+
19
+ export type BlockType = "text" | "richtext" | "image";
20
+
21
+ export type Block = {
22
+ key: string;
23
+ type: BlockType;
24
+ /** Text, markdown (richtext) eller bild-URL (image). */
25
+ value: string | null;
26
+ /** Bildbeskrivning för image-block, annars null. */
27
+ alt: string | null;
28
+ /** Färdig HTML för richtext-block, annars null. */
29
+ html: string | null;
30
+ label?: string | null;
31
+ };
32
+
33
+ export type Page = {
34
+ slug: string;
35
+ title: string;
36
+ description?: string | null;
37
+ blocks: Block[];
38
+ };
39
+
40
+ export type Service = {
41
+ title: string;
42
+ description: string | null;
43
+ price: string | null;
44
+ };
45
+
46
+ export type Seo = {
47
+ pageSlug: string;
48
+ title: string | null;
49
+ description: string | null;
50
+ ogImage: string | null;
51
+ };
52
+
53
+ export type Content = {
54
+ site: { name: string; domain: string | null };
55
+ pages: Page[];
56
+ services: Service[];
57
+ seo: Seo[];
58
+ };
59
+
60
+ export type PostSummary = {
61
+ slug: string;
62
+ title: string;
63
+ excerpt: string | null;
64
+ coverImage: string | null;
65
+ coverImageAlt: string | null;
66
+ publishedAt: string | null;
67
+ };
68
+
69
+ export type Post = PostSummary & {
70
+ /** Markdown. */
71
+ body: string | null;
72
+ /** body renderad till HTML. */
73
+ bodyHtml: string;
74
+ };
75
+
76
+ export type Health = {
77
+ ok: true;
78
+ site: { name: string; slug: string };
79
+ pages: number;
80
+ lastSchemaSyncAt: string | null;
81
+ };
82
+
83
+ export type ResolvedBlock = { value: string; html: string; alt: string };
84
+
85
+ export type SitecmsOptions = {
86
+ /** Bas-URL till sitecms, t.ex. "https://sitecms-zeta.vercel.app". */
87
+ apiUrl: string;
88
+ /** Sajtens slug i sitecms. */
89
+ site: string;
90
+ /** API-nyckel (skickas som x-api-key). Håll den på serversidan. */
91
+ apiKey: string;
92
+ /** Cache-tagg för Next.js fetch-cachen (default "sitecms"). */
93
+ tag?: string;
94
+ /** Egen fetch, t.ex. för tester. Default globalThis.fetch. */
95
+ fetch?: typeof fetch;
96
+ };
97
+
98
+ export class SitecmsError extends Error {
99
+ constructor(
100
+ message: string,
101
+ readonly status: number,
102
+ ) {
103
+ super(message);
104
+ this.name = "SitecmsError";
105
+ }
106
+ }
107
+
108
+ function escapeHtml(value: string): string {
109
+ return value
110
+ .replace(/&/g, "&amp;")
111
+ .replace(/</g, "&lt;")
112
+ .replace(/>/g, "&gt;")
113
+ .replace(/"/g, "&quot;");
114
+ }
115
+
116
+ /**
117
+ * Ett block som alltid går att rendera: tomma strängar i stället för null.
118
+ * `html` är färdig HTML för richtext och HTML-escapad text för övriga typer.
119
+ */
120
+ export function block(content: Content, pageSlug: string, key: string): ResolvedBlock {
121
+ const found = content.pages.find((p) => p.slug === pageSlug)?.blocks.find((b) => b.key === key);
122
+ const value = found?.value ?? "";
123
+ return {
124
+ value,
125
+ html: found?.html ?? escapeHtml(value),
126
+ alt: found?.alt ?? "",
127
+ };
128
+ }
129
+
130
+ /** Textvärdet för ett block, eller `fallback` om det är tomt. */
131
+ export function text(content: Content, pageSlug: string, key: string, fallback = ""): string {
132
+ return block(content, pageSlug, key).value || fallback;
133
+ }
134
+
135
+ /** Bild-URL + alt-text för ett image-block, eller null om ingen bild är vald. */
136
+ export function image(content: Content, pageSlug: string, key: string): { src: string; alt: string } | null {
137
+ const { value, alt } = block(content, pageSlug, key);
138
+ return value ? { src: value, alt } : null;
139
+ }
140
+
141
+ /** SEO-uppgifter för en sida (passar i generateMetadata). */
142
+ export function seo(content: Content, pageSlug: string): Seo | null {
143
+ return content.seo.find((s) => s.pageSlug === pageSlug) ?? null;
144
+ }
145
+
146
+ type NextFetchInit = RequestInit & { next?: { tags?: string[]; revalidate?: number | false } };
147
+
148
+ export function createSitecms(options: SitecmsOptions) {
149
+ const apiUrl = options.apiUrl.trim().replace(/\/+$/, "");
150
+ const tag = options.tag ?? "sitecms";
151
+ const doFetch = options.fetch ?? globalThis.fetch;
152
+
153
+ if (!apiUrl) throw new Error("sitecms-next: apiUrl saknas (CMS_API_URL).");
154
+ if (!options.site) throw new Error("sitecms-next: site saknas (CMS_SITE).");
155
+ if (!options.apiKey) throw new Error("sitecms-next: apiKey saknas (CMS_API_KEY).");
156
+
157
+ const base = `${apiUrl}/api/v1/sites/${encodeURIComponent(options.site)}`;
158
+
159
+ async function request<T>(path: string, { allow404 = false } = {}): Promise<T | null> {
160
+ const init: NextFetchInit = {
161
+ headers: { "x-api-key": options.apiKey },
162
+ next: { tags: [tag] },
163
+ };
164
+ const res = await doFetch(`${base}${path}`, init);
165
+
166
+ if (allow404 && res.status === 404) return null;
167
+
168
+ if (!res.ok) {
169
+ const body = (await res.json().catch(() => null)) as { error?: string } | null;
170
+ throw new SitecmsError(`sitecms: ${body?.error ?? res.statusText} (HTTP ${res.status}, ${path})`, res.status);
171
+ }
172
+
173
+ return (await res.json()) as T;
174
+ }
175
+
176
+ return {
177
+ /** Cache-taggen som alla anrop använder. */
178
+ tag,
179
+
180
+ /** Hela sajtens innehåll: sidor med block, tjänster och SEO. */
181
+ async getContent(): Promise<Content> {
182
+ return (await request<Content>("/content"))!;
183
+ },
184
+
185
+ /** Publicerade inlägg, nyast först (utan brödtext). */
186
+ async getPosts(): Promise<PostSummary[]> {
187
+ const data = await request<{ posts: PostSummary[] }>("/posts");
188
+ return data?.posts ?? [];
189
+ },
190
+
191
+ /** Ett publicerat inlägg, eller null om det inte finns. */
192
+ async getPost(slug: string): Promise<Post | null> {
193
+ const data = await request<{ post: Post }>(`/posts/${encodeURIComponent(slug)}`, { allow404: true });
194
+ return data?.post ?? null;
195
+ },
196
+
197
+ /** Verifierar slug + nyckel. Kastar SitecmsError (401/404) om något är fel. */
198
+ async health(): Promise<Health> {
199
+ return (await request<Health>("/health"))!;
200
+ },
201
+
202
+ block,
203
+ text,
204
+ image,
205
+ seo,
206
+ };
207
+ }
208
+
209
+ export type Sitecms = ReturnType<typeof createSitecms>;
210
+
211
+ /**
212
+ * Hjälpare för `app/api/sitecms/revalidate/route.ts`:
213
+ *
214
+ * import { revalidateTag } from "next/cache";
215
+ * import { verifyRevalidateSecret } from "sitecms-next";
216
+ *
217
+ * export async function POST(request: Request) {
218
+ * const body = await request.json().catch(() => null);
219
+ * if (!(await verifyRevalidateSecret(body?.secret, process.env.CMS_REVALIDATE_SECRET))) {
220
+ * return Response.json({ revalidated: false }, { status: 401 });
221
+ * }
222
+ * revalidateTag("sitecms");
223
+ * return Response.json({ revalidated: true });
224
+ * }
225
+ *
226
+ * Jämför i konstant tid via SHA-256 (Web Crypto), fungerar i både Node och Edge.
227
+ */
228
+ export async function verifyRevalidateSecret(received: unknown, expected: string | undefined): Promise<boolean> {
229
+ if (typeof received !== "string" || !received || !expected) return false;
230
+ const enc = new TextEncoder();
231
+ const [a, b] = await Promise.all([
232
+ crypto.subtle.digest("SHA-256", enc.encode(received)),
233
+ crypto.subtle.digest("SHA-256", enc.encode(expected)),
234
+ ]);
235
+ const va = new Uint8Array(a);
236
+ const vb = new Uint8Array(b);
237
+ let diff = 0;
238
+ for (let i = 0; i < va.length; i++) diff |= va[i] ^ vb[i];
239
+ return diff === 0;
240
+ }
241
+
242
+ // ---------------------------------------------------------------------------
243
+ // Schema (sitecms.config.ts)
244
+ // ---------------------------------------------------------------------------
245
+
246
+ export type SitecmsBlock = {
247
+ /** Unik per sida. a–z, 0–9, punkt, bindestreck, understreck. */
248
+ key: string;
249
+ type: BlockType;
250
+ label?: string;
251
+ help?: string;
252
+ default?: string;
253
+ defaultAlt?: string;
254
+ };
255
+
256
+ export type SitecmsPage = {
257
+ slug: string;
258
+ title: string;
259
+ description?: string;
260
+ blocks: SitecmsBlock[];
261
+ };
262
+
263
+ export type SitecmsConfig = {
264
+ version: 1;
265
+ pages: SitecmsPage[];
266
+ prune?: boolean;
267
+ };
268
+
269
+ /** Identitetsfunktion för typad config: `export default defineConfig({ ... })`. */
270
+ export function defineConfig(config: SitecmsConfig): SitecmsConfig {
271
+ return config;
272
+ }