@scayle/storefront-cms-storyblok 0.2.0-alpha.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/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # @scayle/storefront-cms-storyblok
2
+
3
+ Storyblok CMS provider integration for the SCAYLE Storefront Application V3.
4
+
5
+ > **Requires Storefront Application V3.** This package implements `CMSProviderService` from
6
+ > `@scayle/storefront`. Controllers resolve the constructed provider from the `ServiceRegistry` and call
7
+ > `fetchPageData`/`fetchListingPageData` directly. It has no standalone use outside a Storefront
8
+ > Application V3 project.
9
+
10
+ ## Package entrypoint
11
+
12
+ | Export | Use |
13
+ | --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
14
+ | `StoryblokCMSService` | Concrete `CMSProviderService` implementation. Generic over the tenant's generated Storyblok content-type shape (`TPageData`), defaulting to `MinimalStoryblokPageData` so the package builds standalone. |
15
+ | `StoryblokCMSServiceConfig` | Configuration object for the service (access token and optional folder mapping). |
16
+ | `MinimalStoryblokPageData` | Minimal interface for Storyblok page data shape. |
17
+ | `cspConfig` | `CMSCspConfig` for the Storyblok Visual Editor: iframe embedding, bridge script, and API connect rules. |
18
+
19
+ See [Storyblok's API documentation](https://www.storyblok.com/docs/api/content-delivery/v2) and the
20
+ [`@storyblok/js` package docs](https://www.storyblok.com/docs/packages/storyblok-js) for the underlying client.
21
+
22
+ ## Configuration
23
+
24
+ The `StoryblokCMSServiceConfig` object is constructed from environment variables in the boilerplate's
25
+ `src/server/cms/providers/storyblok/service.ts` via `getRequiredEnv` and `process.env`. These same variables
26
+ are documented in `.env.example`.
27
+
28
+ | Field | Required | Purpose | Env Variable | Found In | Documentation |
29
+ | --------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- | --------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
30
+ | `accessToken` | Yes | Content Delivery API access token used to authenticate requests to Storyblok | `STORYBLOK_CMS_ACCESS_TOKEN` | Storyblok web app: **Space Settings** > **Access Tokens** | [Storyblok API authentication](https://www.storyblok.com/docs/guide/essentials/apis#authentication) |
31
+ | `draftContentEnabled` | Yes | Whether draft/unpublished content may be served during an editor session | `STOREFRONT_CMS_ALLOW_DRAFTS` (read by boilerplate) | N/A | |
32
+ | `folderMapping` | No | Maps storefront locale codes to Storyblok folder names. Defaults to `{ de: 'de', en: 'en' }` when omitted, allowing tenants whose folder names differ from their locale codes to supply custom mappings. | Not from env; configured directly in service.ts | N/A | [Storyblok folder structure docs](https://www.storyblok.com/docs/guide/essentials/folders) |
33
+
34
+ ## Usage
35
+
36
+ The boilerplate's `src/server/cms/providers/storyblok/service.ts` binds the generic and constructs the
37
+ service:
38
+
39
+ ```ts
40
+ import { StoryblokCMSService } from '@scayle/storefront-cms-storyblok'
41
+ import type { StoryblokPageData } from '@shared/types/cms/storyblok'
42
+
43
+ export const createCMSService = (storefront: StorefrontContext) =>
44
+ new StoryblokCMSService<StoryblokPageData>(
45
+ {
46
+ accessToken: getRequiredEnv('STORYBLOK_CMS_ACCESS_TOKEN'),
47
+ draftContentEnabled:
48
+ process.env.STOREFRONT_CMS_ALLOW_DRAFTS?.toLowerCase() === 'true',
49
+ folderMapping: { de: 'de', en: 'en' },
50
+ },
51
+ storefront,
52
+ )
53
+ ```
54
+
55
+ The `storefront` context is used for the service's own application-level caching.
56
+
57
+ The boilerplate registers `createCMSService(storefront)` as the `cms` slot on the `ServiceRegistry`
58
+ (`src/server/registries.ts`), alongside every other domain. A controller resolves it from there, calls
59
+ `resolveCmsRequest()` (`src/server/cms/utils/request.ts`) for editor-mode detection and draft handling,
60
+ then calls `fetchPageData`/`fetchListingPageData` directly with the raw request:
61
+
62
+ ```ts
63
+ const { isCmsEditorSession, cmsEditorData } = resolveCmsRequest(
64
+ this.services.cms,
65
+ this.ctx.req,
66
+ )
67
+ const pageData = await this.services.cms.fetchPageData(
68
+ slug,
69
+ locale,
70
+ this.ctx.req,
71
+ )
72
+ ```
73
+
74
+ See `@scayle/storefront`'s CMS module for the `CMSProviderService` contract this package implements.
75
+
76
+ ## Architecture
77
+
78
+ `StoryblokCMSService` implements `CMSProviderService` directly — there is no shared base class. Each
79
+ provider package owns its own caching, error handling, and constructor validation, so this package can
80
+ diverge from Contentful/Contentstack without a `@scayle/storefront` release touching them:
81
+
82
+ - **`fetchPageData`** wraps the raw fetch with application-level caching (`context.cache.getOrSet(...)`,
83
+ 5-minute TTL, bypassed entirely in draft-content mode) under the cache-key pattern
84
+ `cms:storyblok:page:${slug}:${locale}`. The raw fetch resolves the tenant's locale-to-folder mapping,
85
+ fetches the story from the Storyblok Content Delivery API, and throws `CMSContentNotFoundError` on a
86
+ 404 so the caller can distinguish "not found" from a real API failure.
87
+ - **`fetchListingPageData`** wraps the same raw fetch (against a synthetic `c/c-{categoryId}` slug, since
88
+ Storyblok stores PLP content as regular stories) with caching under
89
+ `cms:storyblok:plp:${categoryId}:${locale}`, and converts a `CMSContentNotFoundError` into `undefined`
90
+ (missing PLP content is expected, not an error), logging any other error before rethrowing it.
91
+ - **`getAlternatePaths`** reads locale alternates directly off the
92
+ fetched story.
93
+ - **`isEditorMode`** detects the Storyblok Visual Editor via the `_storyblok` query parameter.
94
+ - **Draft-content decision**: controlled by the `draftContentEnabled` boolean in the service config,
95
+ read from the `STOREFRONT_CMS_ALLOW_DRAFTS` environment variable in the boilerplate factory.
96
+ When both `isEditorMode()` returns true and `draftContentEnabled` is true, the service fetches
97
+ the draft version; otherwise it fetches published content.
98
+
99
+ The API client is a lazily initialized static singleton shared across requests, since `@storyblok/js`'s
100
+ client carries no per-request state. Construction goes through `@scayle/storefront/cms`'s `wrapClientInit`,
101
+ so a bad access token fails with a message naming the client and the env var to check, not a bare SDK error.
102
+
103
+ **Generic content types stay in the boilerplate.** Storyblok's content-type shape is entirely
104
+ tenant-defined (whatever components exist in the tenant's Storyblok space), so `StoryblokCMSService<TPageData>`
105
+ takes the shape as a generic parameter rather than importing it. The tenant's generated types live in
106
+ `src/shared/types/cms/storyblok/gen/`, regenerated per-tenant by `pnpm cms:sync`. They can never ship
107
+ inside this package.
108
+
109
+ ## Extending and customizing
110
+
111
+ Within a tenant project, all customization happens in the boilerplate's
112
+ `src/server/cms/providers/storyblok/service.ts`, by subclassing `StoryblokCMSService`:
113
+
114
+ - **Query shape**: override `buildStoryQuery(locale, useDraftContent, request)` to change version resolution, resolved
115
+ links, or add other `client.get(...)` query params, without touching slug resolution or error handling.
116
+ - **Response shape**: override `transformStoryResponse(response)` to keep additional response fields
117
+ beyond `story`.
118
+ - **CSP rules**: re-export a modified `cspConfig` (imported from this package as a base) if the tenant's
119
+ Storyblok space is on a different domain or needs additional directives.
120
+ - **Locale-to-folder mapping**: pass a custom `folderMapping` in the service config if the tenant's
121
+ Storyblok space uses folder names that don't match its locale codes.
122
+
123
+ Do not reimplement `fetchPageData` or `fetchListingPageData` from scratch. Override only the method that
124
+ needs to change and call `super` for everything else, so the tenant subclass tracks fixes made to this
125
+ package.
@@ -0,0 +1,123 @@
1
+ import { CMSCspConfig, CMSEditorData, CMSPagePayload, CMSProviderService, CMSRequestLike } from "@scayle/storefront/cms";
2
+ import { StorefrontContext } from "@scayle/storefront/types";
3
+ /**
4
+ * Configuration for the Storyblok CMS service.
5
+ */
6
+ interface StoryblokCMSServiceConfig {
7
+ /** The Storyblok API access token. */
8
+ accessToken: string;
9
+ /** Enable draft content in editor mode. */
10
+ draftContentEnabled: boolean;
11
+ /** Maps storefront locale codes to Storyblok folder names. Defaults to `{ de: 'de', en: 'en' }` when omitted. */
12
+ folderMapping?: Record<string, string>;
13
+ }
14
+ /**
15
+ * Minimal generic default so the package builds and can be used standalone
16
+ * without a tenant's generated types. A tenant subclass binds `TPageData` to
17
+ * its own generated `StoryblokPageData` type.
18
+ */
19
+ interface MinimalStoryblokPageData extends Record<string, unknown> {
20
+ story?: {
21
+ content?: {
22
+ component?: string;
23
+ [key: string]: unknown;
24
+ };
25
+ alternates?: {
26
+ id: number;
27
+ slug: string;
28
+ published: boolean;
29
+ }[];
30
+ full_slug?: string;
31
+ };
32
+ }
33
+ /**
34
+ * Storyblok CMS provider service.
35
+ * Manages a singleton API client that is lazily initialized on first use.
36
+ * Generic over the tenant's generated Storyblok content-type shape
37
+ * (`TPageData`); the tenant subclass binds this to its own generated types
38
+ * from `src/shared/types/cms/storyblok`.
39
+ *
40
+ * This binding cannot move into this package: `TPageData` is generated by
41
+ * `pnpm cms:sync` from the tenant's own Storyblok space, so its shape differs
42
+ * per tenant and is regenerated on demand. A versioned npm package ships one
43
+ * fixed artifact for every tenant, so it can only stay generic here — the
44
+ * concrete type has to be supplied where it's generated, in the boilerplate.
45
+ *
46
+ * @see https://www.storyblok.com/docs/packages/storyblok-js
47
+ */
48
+ declare class StoryblokCMSService<TPageData extends MinimalStoryblokPageData = MinimalStoryblokPageData> implements CMSProviderService {
49
+ /** Shared across all instances so the API client is created once, not per request. */
50
+ private static client;
51
+ readonly cspConfig: CMSCspConfig;
52
+ private readonly accessToken;
53
+ private readonly context;
54
+ private readonly draftContentEnabled;
55
+ private readonly folderMapping;
56
+ constructor(config: StoryblokCMSServiceConfig, context: StorefrontContext);
57
+ private getClient;
58
+ isEditorMode(request: CMSRequestLike): boolean;
59
+ getCMSEditorData(request: CMSRequestLike): CMSEditorData | undefined;
60
+ /**
61
+ * Builds the Storyblok Content Delivery API query for a story lookup.
62
+ * Override to change version resolution, resolved links, or add other
63
+ * `client.get(...)` query params.
64
+ *
65
+ * @param locale Storefront locale code
66
+ * @param useDraftContent Whether to fetch draft content version
67
+ * @param request Incoming request for accessing query parameters
68
+ * @returns Query object passed to `client.get('cdn/stories/...', query)`
69
+ */
70
+ protected buildStoryQuery(locale: string, useDraftContent: boolean, request: CMSRequestLike): Record<string, unknown>;
71
+ /**
72
+ * Transforms a Storyblok Content Delivery API response into the page payload.
73
+ * Override to keep additional response fields beyond `story`.
74
+ *
75
+ * @param response Raw response from `client.get('cdn/stories/...')`
76
+ * @param response.data Response body
77
+ * @param response.data.story Story payload, or undefined when none matched
78
+ * @returns Page payload, or undefined when the response has no story
79
+ */
80
+ protected transformStoryResponse(response: {
81
+ data?: {
82
+ story?: unknown;
83
+ };
84
+ }): TPageData | undefined;
85
+ private fetchRawPageData;
86
+ /**
87
+ * Retrieves CMS page data with application-level caching.
88
+ * Draft content requests bypass the cache entirely.
89
+ *
90
+ * @param slug CMS slug
91
+ * @param locale Storefront locale code
92
+ * @param request Incoming request, used to detect editor mode and read editor-specific query params
93
+ * @returns Storyblok page data or undefined
94
+ */
95
+ fetchPageData(slug: string, locale: string, request: CMSRequestLike): Promise<TPageData | undefined>;
96
+ /**
97
+ * Retrieves CMS content for a product listing page, with caching.
98
+ * Converts a missing entry into `undefined` rather than throwing, since
99
+ * missing PLP content is expected, not an error condition.
100
+ *
101
+ * @param categoryId SCAYLE category ID
102
+ * @param locale Storefront locale code
103
+ * @param request Incoming request, used to detect editor mode and read editor-specific query params
104
+ * @returns Storyblok listing page data or undefined
105
+ */
106
+ fetchListingPageData(categoryId: number, locale: string, request: CMSRequestLike): Promise<TPageData | undefined>;
107
+ /**
108
+ * Extracts per-locale page paths from a Storyblok story using its
109
+ * `alternates` and the configured folder mapping.
110
+ *
111
+ * @param data CMS page payload containing a Storyblok story.
112
+ * @returns Per-locale page path map, or undefined.
113
+ */
114
+ getAlternatePaths(data: CMSPagePayload): Record<string, string> | undefined;
115
+ }
116
+ /**
117
+ * CSP configuration for the Storyblok provider.
118
+ * Allows the Storyblok visual editor to embed the storefront in an iframe
119
+ * and load the bridge script for live editing.
120
+ */
121
+ declare const cspConfig: CMSCspConfig;
122
+ export { type MinimalStoryblokPageData, StoryblokCMSService, type StoryblokCMSServiceConfig, cspConfig };
123
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/StoryblokCMSService.ts","../src/csp.ts"],"mappings":";;;;;UAmCiB;;EAEf;;EAEA;;EAEA,gBAAgB;;;;;;;UAQD,iCAAiC;EAChD;IACE;MAAY;;;IACZ;MAAe;MAAY;MAAc;;IACzC;;;;;;;;;;;;;;;;;;cAmBS,oBACX,kBAAkB,2BAA2B,qCAClC;;iBAEI;WAEN,WAAW;mBAEH;mBACA;mBACA;mBACA;EAEjB,YAAY,QAAQ,2BAA2B,SAAS;UAOhD;EA8BR,aAAa,SAAS;EAItB,iBAAiB,SAAS,iBAAiB;;;;;;;;;;;YAkBjC,gBACR,gBACA,0BACA,SAAS,iBACR;;;;;;;;;;YAmBO,uBAAuB;IAC/B;MAAS;;MACP;UAQU;;;;;;;;;;EAyCd,cACE,cACA,gBACA,SAAS,iBACR,QAAQ;;;;;;;;;;;EAgCX,qBACE,oBACA,gBACA,SAAS,iBACR,QAAQ;;;;;;;;EAqDX,kBAAkB,MAAM,iBAAiB;;;;;;;cChT9B,WAAW"}
package/dist/index.mjs ADDED
@@ -0,0 +1,172 @@
1
+ import { apiPlugin, storyblokInit } from "@storyblok/js";
2
+ import { CMSContentNotFoundError, ensureError, extractErrorStatus, wrapClientInit } from "@scayle/storefront/cms";
3
+ import { createLogger } from "@scayle/storefront/shared";
4
+ const extractLanguageCode = (locale) => locale.split("-")[0];
5
+ const HOMEPAGE_SLUG$1 = "homepage";
6
+ const stripSlashes = (value) => value.trim().replace(/^\/+/, "").replace(/\/+$/, "");
7
+ const resolveStoryblokSlug = (locale, slug, folderMapping = {}) => {
8
+ const localeCode = extractLanguageCode(locale);
9
+ const folder = folderMapping[localeCode] ?? localeCode;
10
+ let normalizedSlug = stripSlashes(slug);
11
+ if (!normalizedSlug) return `${folder}/${HOMEPAGE_SLUG$1}`;
12
+ const localePrefix = `${localeCode}/`;
13
+ if (normalizedSlug === localeCode) normalizedSlug = "";
14
+ else if (normalizedSlug.startsWith(localePrefix)) normalizedSlug = normalizedSlug.slice(localePrefix.length);
15
+ if (!normalizedSlug) return `${folder}/${HOMEPAGE_SLUG$1}`;
16
+ if (normalizedSlug.startsWith(`${folder}/`)) return normalizedSlug;
17
+ return `${folder}/${normalizedSlug}`;
18
+ };
19
+ function getFolderMappingKeysForPath(path, folderMapping) {
20
+ if (!folderMapping || !path) return [];
21
+ return Object.keys(folderMapping).filter((key) => folderMapping[key] === path && key !== path);
22
+ }
23
+ function getAllSourceSlugs(story, folderMapping) {
24
+ return [story.full_slug, ...story.alternates?.map((a) => a.full_slug) ?? []].reduce((acc, sourceSlug) => {
25
+ if (!sourceSlug) return acc;
26
+ const [path, ...rest] = sourceSlug.split("/");
27
+ if (!path) return acc;
28
+ const slug = rest.join("/");
29
+ const aliasKeys = getFolderMappingKeysForPath(path, folderMapping);
30
+ return [
31
+ ...acc,
32
+ ...aliasKeys.map((key) => ({
33
+ path: key,
34
+ slug
35
+ })),
36
+ {
37
+ path,
38
+ slug
39
+ }
40
+ ];
41
+ }, []);
42
+ }
43
+ const cspConfig = {
44
+ isPreviewRequest: (req) => Boolean(req.query("_storyblok")),
45
+ directives: {
46
+ "frame-ancestors": "'self' https://app.storyblok.com",
47
+ "script-src": "'self' 'unsafe-inline' https://app.storyblok.com",
48
+ "connect-src": "'self' https://api.storyblok.com"
49
+ }
50
+ };
51
+ const log = createLogger("cms");
52
+ const CACHE_TTL_SECONDS = 300;
53
+ const HOMEPAGE_SLUG = "homepage";
54
+ var StoryblokCMSService = class StoryblokCMSService {
55
+ static client;
56
+ cspConfig = cspConfig;
57
+ accessToken;
58
+ context;
59
+ draftContentEnabled;
60
+ folderMapping;
61
+ constructor(config, context) {
62
+ this.accessToken = config.accessToken;
63
+ this.draftContentEnabled = config.draftContentEnabled;
64
+ this.context = context;
65
+ this.folderMapping = config.folderMapping ?? {
66
+ de: "de",
67
+ en: "en"
68
+ };
69
+ }
70
+ getClient() {
71
+ if (StoryblokCMSService.client) return StoryblokCMSService.client;
72
+ if (!this.accessToken) throw new Error("Storyblok API client initialization failed: missing or empty access token. Check that STORYBLOK_CMS_ACCESS_TOKEN is set.");
73
+ const { storyblokApi } = wrapClientInit(() => storyblokInit({
74
+ accessToken: this.accessToken,
75
+ use: [apiPlugin]
76
+ }), "Storyblok API client initialization failed");
77
+ if (!storyblokApi) throw new Error("Storyblok API client initialization failed: storyblokInit() did not return an API client instance. Ensure @storyblok/js package and its apiPlugin are correctly installed and compatible.");
78
+ StoryblokCMSService.client = storyblokApi;
79
+ return StoryblokCMSService.client;
80
+ }
81
+ isEditorMode(request) {
82
+ return Boolean(request.query("_storyblok"));
83
+ }
84
+ getCMSEditorData(request) {
85
+ if (!this.isEditorMode(request)) return;
86
+ return {};
87
+ }
88
+ buildStoryQuery(locale, useDraftContent, request) {
89
+ const rawCv = request.query("_storyblok");
90
+ return {
91
+ version: useDraftContent ? "draft" : "published",
92
+ cv: rawCv ? Number(rawCv) : void 0,
93
+ language: extractLanguageCode(locale),
94
+ resolve_links: "url"
95
+ };
96
+ }
97
+ transformStoryResponse(response) {
98
+ if (!response.data?.story) return;
99
+ return { story: response.data.story };
100
+ }
101
+ async fetchRawPageData(slug, locale, useDraftContent, request) {
102
+ const storyblokSlug = resolveStoryblokSlug(locale, slug, this.folderMapping);
103
+ const client = this.getClient();
104
+ const query = this.buildStoryQuery(locale, useDraftContent, request);
105
+ try {
106
+ const response = await client.get(`cdn/stories/${storyblokSlug}`, query);
107
+ return this.transformStoryResponse(response);
108
+ } catch (error) {
109
+ const status = extractErrorStatus(error);
110
+ if (status === 404) throw new CMSContentNotFoundError("Storyblok content not found", {
111
+ cause: error,
112
+ details: {
113
+ slug,
114
+ locale,
115
+ storyblokSlug,
116
+ version: query.version
117
+ }
118
+ });
119
+ const cause = ensureError(error, "Storyblok API request failed");
120
+ throw new Error(`Storyblok API request failed (slug: "${slug}", locale: "${locale}", status: ${status ?? "unknown"}): ${cause.message}`, { cause });
121
+ }
122
+ }
123
+ async fetchPageData(slug, locale, request) {
124
+ const useDraftContent = this.isEditorMode(request) && this.draftContentEnabled;
125
+ if (useDraftContent) {
126
+ log.debug({
127
+ message: "Bypassing CMS cache in preview mode",
128
+ slug,
129
+ locale
130
+ });
131
+ return this.fetchRawPageData(slug, locale, useDraftContent, request);
132
+ }
133
+ return this.context.cache.getOrSet(`cms:storyblok:page:${slug}:${locale}`, () => this.fetchRawPageData(slug, locale, useDraftContent, request), CACHE_TTL_SECONDS);
134
+ }
135
+ async fetchListingPageData(categoryId, locale, request) {
136
+ const slug = `c/c-${categoryId}`;
137
+ const useDraftContent = this.isEditorMode(request) && this.draftContentEnabled;
138
+ const fetchListing = async () => {
139
+ try {
140
+ return await this.fetchRawPageData(slug, locale, useDraftContent, request);
141
+ } catch (error) {
142
+ if (error instanceof CMSContentNotFoundError) return;
143
+ log.error({
144
+ message: "Failed to fetch CMS listing page data",
145
+ err: error instanceof Error ? error : new Error(String(error)),
146
+ categoryId,
147
+ locale
148
+ });
149
+ throw error;
150
+ }
151
+ };
152
+ if (useDraftContent) {
153
+ log.debug({
154
+ message: "Bypassing CMS PLP cache in preview mode",
155
+ categoryId,
156
+ locale
157
+ });
158
+ return fetchListing();
159
+ }
160
+ return this.context.cache.getOrSet(`cms:storyblok:plp:${categoryId}:${locale}`, () => fetchListing(), CACHE_TTL_SECONDS);
161
+ }
162
+ getAlternatePaths(data) {
163
+ const story = data?.story;
164
+ if (!story?.alternates?.length) return;
165
+ const sourceSlugs = getAllSourceSlugs(story, this.folderMapping);
166
+ if (sourceSlugs.length <= 1) return;
167
+ return Object.fromEntries(sourceSlugs.map(({ path, slug }) => [path, !slug || slug === HOMEPAGE_SLUG ? "/" : `/${slug}`]));
168
+ }
169
+ };
170
+ export { StoryblokCMSService, cspConfig };
171
+
172
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["HOMEPAGE_SLUG","pageData"],"sources":["../src/utils/slug.ts","../src/csp.ts","../src/StoryblokCMSService.ts"],"sourcesContent":["/**\n * Storyblok story type. Minimal interface for slug resolution.\n * In the boilerplate context, this is imported from `@shared/types/cms/storyblok`.\n * In the standalone package context, callers provide this shape directly.\n */\nexport interface StoryblokStory {\n full_slug?: string\n alternates?: Array<{ id: number; full_slug?: string; published: boolean }>\n}\n\n/** Extracts the language code portion of a storefront locale (e.g. `de` from `de-DE`). */\nexport const extractLanguageCode = (locale: string): string =>\n locale.split('-')[0]\n\n/** Slug used to identify the homepage story; mapped to `/` in generated hreflangs. */\nconst HOMEPAGE_SLUG = 'homepage'\n\n// A single quantifier on one character class anchored at one end of the string\n// can't backtrack (there's nothing to retry against), so this is linear-time\n// regardless of input length - safe even though `slug` is attacker-controlled.\nconst stripSlashes = (value: string): string =>\n // eslint-disable-next-line sonarjs/super-linear-regex\n value.trim().replace(/^\\/+/, '').replace(/\\/+$/, '')\n\n/**\n * Resolves a Storyblok slug from storefront locale and requested slug.\n * Used by the Storyblok CMS service before requesting a story from the CDN API.\n *\n * @param locale Storefront locale in BCP-47 format\n * @param slug Requested CMS slug\n * @param folderMapping Optional locale folder mapping\n * @returns Storyblok content slug\n *\n * @example\n * ```ts\n * resolveStoryblokSlug('de-DE', '/content/about', { de: 'de' })\n * // \"de/content/about\"\n * ```\n *\n * @see https://www.storyblok.com/docs/concepts/internationalization\n */\nexport const resolveStoryblokSlug = (\n locale: string,\n slug: string,\n folderMapping: Record<string, string> = {},\n): string => {\n const localeCode = extractLanguageCode(locale)\n const folder = folderMapping[localeCode] ?? localeCode\n\n let normalizedSlug = stripSlashes(slug)\n\n if (!normalizedSlug) {\n return `${folder}/${HOMEPAGE_SLUG}`\n }\n\n const localePrefix = `${localeCode}/`\n if (normalizedSlug === localeCode) {\n normalizedSlug = ''\n } else if (normalizedSlug.startsWith(localePrefix)) {\n normalizedSlug = normalizedSlug.slice(localePrefix.length)\n }\n\n if (!normalizedSlug) {\n return `${folder}/${HOMEPAGE_SLUG}`\n }\n\n if (normalizedSlug.startsWith(`${folder}/`)) {\n return normalizedSlug\n }\n\n return `${folder}/${normalizedSlug}`\n}\n\n/**\n * Finds folder mapping keys that point to a given folder name.\n * Used to discover locale aliases when building hreflang links\n * (e.g. folder `\"german\"` maps to key `\"de\"`).\n *\n * @param path Folder name from a Storyblok full slug.\n * @param folderMapping Locale-to-folder mapping from provider config.\n * @returns Array of mapping keys whose value matches `path` but differ from `path` itself.\n */\nexport function getFolderMappingKeysForPath(\n path?: string,\n folderMapping?: Record<string, string>,\n): string[] {\n if (!folderMapping || !path) {\n return []\n }\n\n return Object.keys(folderMapping).filter(\n (key) => folderMapping[key] === path && key !== path,\n )\n}\n\n/**\n * Extracts all locale-folder/slug pairs from a Storyblok story and its alternates.\n * Extends with aliases from `folderMapping` when a folder name maps to multiple locale\n * keys (e.g. folder `\"german\"` aliased as both `\"de\"` and `\"german\"`).\n *\n * Used to build per-locale hreflang links where each locale may have a different CMS slug.\n *\n * @param story Storyblok story data including `full_slug` and `alternates`.\n * @param folderMapping Optional locale-to-folder mapping from provider config.\n * @returns Array of `{ path, slug }` pairs where `path` is the locale/folder key and\n * `slug` is the page-relative path (e.g. `\"content/about\"`).\n *\n * @see https://www.storyblok.com/docs/concepts/internationalization\n */\nexport function getAllSourceSlugs(\n story: StoryblokStory,\n folderMapping?: Record<string, string>,\n): { path: string; slug: string }[] {\n const sourceSlugsFromCMS = [\n story.full_slug,\n ...(story.alternates?.map((a) => a.full_slug) ?? []),\n ]\n\n return sourceSlugsFromCMS.reduce<{ path: string; slug: string }[]>(\n (acc, sourceSlug) => {\n if (!sourceSlug) {\n return acc\n }\n\n const [path, ...rest] = sourceSlug.split('/')\n\n if (!path) {\n return acc\n }\n\n const slug = rest.join('/')\n const aliasKeys = getFolderMappingKeysForPath(path, folderMapping)\n\n return [\n ...acc,\n ...aliasKeys.map((key) => ({ path: key, slug })),\n { path, slug },\n ]\n },\n [],\n )\n}\n","import type { CMSCspConfig } from '@scayle/storefront/cms'\n\n/**\n * CSP configuration for the Storyblok provider.\n * Allows the Storyblok visual editor to embed the storefront in an iframe\n * and load the bridge script for live editing.\n */\nexport const cspConfig: CMSCspConfig = {\n isPreviewRequest: (req) => Boolean(req.query('_storyblok')),\n directives: {\n // Allows Storyblok to embed the storefront in an iframe for the Visual Editor.\n // https://www.storyblok.com/docs/guide/essentials/visual-editor\n 'frame-ancestors': \"'self' https://app.storyblok.com\",\n // Allows the Storyblok bridge script and Inertia inline hydration scripts.\n // 'unsafe-inline' is required because Inertia injects inline scripts for\n // SSR page data, and CSP may not include it when no upstream script-src exists.\n // https://www.storyblok.com/docs/guide/essentials/visual-editor#bridge\n 'script-src': \"'self' 'unsafe-inline' https://app.storyblok.com\",\n // Allows the Storyblok bridge to communicate with the Storyblok API\n // for real-time content updates in the Visual Editor.\n // https://www.storyblok.com/docs/api/content-delivery/v2\n 'connect-src': \"'self' https://api.storyblok.com\",\n },\n}\n","import { storyblokInit, apiPlugin } from '@storyblok/js'\nimport type { StoryblokClient } from '@storyblok/js'\nimport {\n CMSContentNotFoundError,\n extractErrorStatus,\n ensureError,\n wrapClientInit,\n} from '@scayle/storefront/cms'\nimport type {\n CMSCspConfig,\n CMSEditorData,\n CMSPagePayload,\n CMSProviderService,\n CMSRequestLike,\n} from '@scayle/storefront/cms'\nimport { createLogger } from '@scayle/storefront/shared'\nimport type { StorefrontContext } from '@scayle/storefront/types'\nimport {\n resolveStoryblokSlug,\n getAllSourceSlugs,\n extractLanguageCode,\n} from './utils/slug'\nimport { cspConfig } from './csp'\n\nconst log = createLogger('cms')\n\n/** Cache TTL for published CMS content: 5 minutes. */\nconst CACHE_TTL_SECONDS = 5 * 60\n\n/** Slug used to identify the homepage story; mapped to `/` in generated hreflangs. */\nconst HOMEPAGE_SLUG = 'homepage' as const\n\n/**\n * Configuration for the Storyblok CMS service.\n */\nexport interface StoryblokCMSServiceConfig {\n /** The Storyblok API access token. */\n accessToken: string\n /** Enable draft content in editor mode. */\n draftContentEnabled: boolean\n /** Maps storefront locale codes to Storyblok folder names. Defaults to `{ de: 'de', en: 'en' }` when omitted. */\n folderMapping?: Record<string, string>\n}\n\n/**\n * Minimal generic default so the package builds and can be used standalone\n * without a tenant's generated types. A tenant subclass binds `TPageData` to\n * its own generated `StoryblokPageData` type.\n */\nexport interface MinimalStoryblokPageData extends Record<string, unknown> {\n story?: {\n content?: { component?: string; [key: string]: unknown }\n alternates?: { id: number; slug: string; published: boolean }[]\n full_slug?: string\n }\n}\n\n/**\n * Storyblok CMS provider service.\n * Manages a singleton API client that is lazily initialized on first use.\n * Generic over the tenant's generated Storyblok content-type shape\n * (`TPageData`); the tenant subclass binds this to its own generated types\n * from `src/shared/types/cms/storyblok`.\n *\n * This binding cannot move into this package: `TPageData` is generated by\n * `pnpm cms:sync` from the tenant's own Storyblok space, so its shape differs\n * per tenant and is regenerated on demand. A versioned npm package ships one\n * fixed artifact for every tenant, so it can only stay generic here — the\n * concrete type has to be supplied where it's generated, in the boilerplate.\n *\n * @see https://www.storyblok.com/docs/packages/storyblok-js\n */\nexport class StoryblokCMSService<\n TPageData extends MinimalStoryblokPageData = MinimalStoryblokPageData,\n> implements CMSProviderService {\n /** Shared across all instances so the API client is created once, not per request. */\n private static client: StoryblokClient | undefined\n\n readonly cspConfig: CMSCspConfig = cspConfig\n\n private readonly accessToken: string\n private readonly context: StorefrontContext\n private readonly draftContentEnabled: boolean\n private readonly folderMapping: Record<string, string>\n\n constructor(config: StoryblokCMSServiceConfig, context: StorefrontContext) {\n this.accessToken = config.accessToken\n this.draftContentEnabled = config.draftContentEnabled\n this.context = context\n this.folderMapping = config.folderMapping ?? { de: 'de', en: 'en' }\n }\n\n private getClient(): StoryblokClient {\n if (StoryblokCMSService.client) {\n return StoryblokCMSService.client\n }\n\n if (!this.accessToken) {\n throw new Error(\n 'Storyblok API client initialization failed: missing or empty access token. Check that STORYBLOK_CMS_ACCESS_TOKEN is set.',\n )\n }\n\n const { storyblokApi } = wrapClientInit(\n () =>\n storyblokInit({\n accessToken: this.accessToken,\n use: [apiPlugin],\n }),\n 'Storyblok API client initialization failed',\n )\n\n if (!storyblokApi) {\n throw new Error(\n 'Storyblok API client initialization failed: storyblokInit() did not return an API client instance. Ensure @storyblok/js package and its apiPlugin are correctly installed and compatible.',\n )\n }\n\n StoryblokCMSService.client = storyblokApi\n return StoryblokCMSService.client\n }\n\n isEditorMode(request: CMSRequestLike): boolean {\n return Boolean(request.query('_storyblok'))\n }\n\n getCMSEditorData(request: CMSRequestLike): CMSEditorData | undefined {\n if (!this.isEditorMode(request)) {\n return undefined\n }\n\n return {}\n }\n\n /**\n * Builds the Storyblok Content Delivery API query for a story lookup.\n * Override to change version resolution, resolved links, or add other\n * `client.get(...)` query params.\n *\n * @param locale Storefront locale code\n * @param useDraftContent Whether to fetch draft content version\n * @param request Incoming request for accessing query parameters\n * @returns Query object passed to `client.get('cdn/stories/...', query)`\n */\n protected buildStoryQuery(\n locale: string,\n useDraftContent: boolean,\n request: CMSRequestLike,\n ): Record<string, unknown> {\n const rawCv = request.query('_storyblok')\n return {\n version: useDraftContent ? 'draft' : 'published',\n cv: rawCv ? Number(rawCv) : undefined,\n language: extractLanguageCode(locale),\n resolve_links: 'url',\n }\n }\n\n /**\n * Transforms a Storyblok Content Delivery API response into the page payload.\n * Override to keep additional response fields beyond `story`.\n *\n * @param response Raw response from `client.get('cdn/stories/...')`\n * @param response.data Response body\n * @param response.data.story Story payload, or undefined when none matched\n * @returns Page payload, or undefined when the response has no story\n */\n protected transformStoryResponse(response: {\n data?: { story?: unknown }\n }): TPageData | undefined {\n if (!response.data?.story) {\n return undefined\n }\n\n return { story: response.data.story } as TPageData\n }\n\n private async fetchRawPageData(\n slug: string,\n locale: string,\n useDraftContent: boolean,\n request: CMSRequestLike,\n ): Promise<TPageData | undefined> {\n const storyblokSlug = resolveStoryblokSlug(locale, slug, this.folderMapping)\n const client = this.getClient()\n const query = this.buildStoryQuery(locale, useDraftContent, request)\n\n try {\n const response = await client.get(`cdn/stories/${storyblokSlug}`, query)\n\n return this.transformStoryResponse(response)\n } catch (error) {\n const status = extractErrorStatus(error)\n\n if (status === 404) {\n throw new CMSContentNotFoundError('Storyblok content not found', {\n cause: error,\n details: { slug, locale, storyblokSlug, version: query.version },\n })\n }\n\n const cause = ensureError(error, 'Storyblok API request failed')\n throw new Error(\n `Storyblok API request failed (slug: \"${slug}\", locale: \"${locale}\", status: ${status ?? 'unknown'}): ${cause.message}`,\n { cause },\n )\n }\n }\n\n /**\n * Retrieves CMS page data with application-level caching.\n * Draft content requests bypass the cache entirely.\n *\n * @param slug CMS slug\n * @param locale Storefront locale code\n * @param request Incoming request, used to detect editor mode and read editor-specific query params\n * @returns Storyblok page data or undefined\n */\n async fetchPageData(\n slug: string,\n locale: string,\n request: CMSRequestLike,\n ): Promise<TPageData | undefined> {\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS cache in preview mode',\n slug,\n locale,\n })\n return this.fetchRawPageData(slug, locale, useDraftContent, request)\n }\n\n return this.context.cache.getOrSet(\n `cms:storyblok:page:${slug}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () =>\n this.fetchRawPageData(slug, locale, useDraftContent, request) as never,\n CACHE_TTL_SECONDS,\n )\n }\n\n /**\n * Retrieves CMS content for a product listing page, with caching.\n * Converts a missing entry into `undefined` rather than throwing, since\n * missing PLP content is expected, not an error condition.\n *\n * @param categoryId SCAYLE category ID\n * @param locale Storefront locale code\n * @param request Incoming request, used to detect editor mode and read editor-specific query params\n * @returns Storyblok listing page data or undefined\n */\n async fetchListingPageData(\n categoryId: number,\n locale: string,\n request: CMSRequestLike,\n ): Promise<TPageData | undefined> {\n const slug = `c/c-${categoryId}`\n const useDraftContent =\n this.isEditorMode(request) && this.draftContentEnabled\n\n const fetchListing = async () => {\n try {\n return await this.fetchRawPageData(\n slug,\n locale,\n useDraftContent,\n request,\n )\n } catch (error) {\n if (error instanceof CMSContentNotFoundError) {\n return undefined\n }\n\n log.error({\n message: 'Failed to fetch CMS listing page data',\n err: error instanceof Error ? error : new Error(String(error)),\n categoryId,\n locale,\n })\n\n throw error\n }\n }\n\n if (useDraftContent) {\n log.debug({\n message: 'Bypassing CMS PLP cache in preview mode',\n categoryId,\n locale,\n })\n return fetchListing()\n }\n\n return this.context.cache.getOrSet(\n `cms:storyblok:plp:${categoryId}:${locale}`,\n // Cast required: StorageValue excludes undefined, but the fetch can return undefined for missing content\n () => fetchListing() as never,\n CACHE_TTL_SECONDS,\n )\n }\n\n /**\n * Extracts per-locale page paths from a Storyblok story using its\n * `alternates` and the configured folder mapping.\n *\n * @param data CMS page payload containing a Storyblok story.\n * @returns Per-locale page path map, or undefined.\n */\n getAlternatePaths(data: CMSPagePayload): Record<string, string> | undefined {\n const pageData = data as MinimalStoryblokPageData\n const story = pageData?.story\n\n if (!story?.alternates?.length) {\n return undefined\n }\n\n const sourceSlugs = getAllSourceSlugs(story, this.folderMapping)\n\n if (sourceSlugs.length <= 1) {\n return undefined\n }\n\n return Object.fromEntries(\n sourceSlugs.map(({ path, slug }) => [\n path,\n !slug || slug === HOMEPAGE_SLUG ? '/' : `/${slug}`,\n ]),\n )\n }\n}\n"],"mappings":"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"}
package/package.json ADDED
@@ -0,0 +1,53 @@
1
+ {
2
+ "name": "@scayle/storefront-cms-storyblok",
3
+ "version": "0.2.0-alpha.0",
4
+ "description": "Storyblok CMS provider integration for the SCAYLE Storefront Application V3",
5
+ "author": "SCAYLE Commerce Engine",
6
+ "license": "MIT",
7
+ "type": "module",
8
+ "private": false,
9
+ "sideEffects": false,
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ }
15
+ },
16
+ "main": "./dist/index.mjs",
17
+ "files": [
18
+ "CHANGELOG.md",
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">= 24.0.0"
23
+ },
24
+ "peerDependencies": {
25
+ "@storyblok/js": "^6.3.0",
26
+ "@scayle/storefront": "1.0.0-alpha.2"
27
+ },
28
+ "devDependencies": {
29
+ "@arethetypeswrong/cli": "0.18.5",
30
+ "@storyblok/js": "^6.3.0",
31
+ "@types/node": "^24",
32
+ "@vitest/coverage-v8": "4.1.10",
33
+ "eslint": "10.8.1",
34
+ "eslint-formatter-gitlab": "7.2.0",
35
+ "publint": "0.3.23",
36
+ "typescript": "6.0.3",
37
+ "obuild": "0.4.38",
38
+ "vitest": "4.1.10",
39
+ "@scayle/eslint-config-storefront": "4.8.3-alpha.0",
40
+ "@scayle/storefront": "1.0.0-alpha.2",
41
+ "@scayle/vitest-config-storefront": "1.0.0"
42
+ },
43
+ "scripts": {
44
+ "build": "obuild",
45
+ "lint": "eslint .",
46
+ "lint:ci": "eslint . --format gitlab",
47
+ "lint:fix": "eslint . --fix",
48
+ "typecheck": "tsc --noEmit",
49
+ "test": "vitest run",
50
+ "package:lint": "publint",
51
+ "verify-packaging": "attw --pack . --profile esm-only"
52
+ }
53
+ }