@tomsher/cms-theme-kit 0.1.4 → 0.1.7

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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/lib/dev/data-source.ts","../../cms-core/src/utils/liquid/analysis/template.utils.ts","../../cms-core/src/utils/static/editor/html-editor.utils.ts"],"sourcesContent":["import { readFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { getLiquidThemeCollectionHandles, getLiquidThemeEntityQueries, getLiquidThemeEntitySources, getLiquidThemeReachableBuffers, getLiquidThemeTemplateCategory, requiresCurrentEntry } from '@tomsher/cms-core/utils';\nimport { themeTemplateCategoryKeys } from '@tomsher/cms-core/constants';\nimport { collectThemeLinkTargetReferences } from '@tomsher/cms-core/utils';\nimport type { CmsClient, RemoteRoute, ThemePreviewRequest } from '../cms-client';\nimport { CliError } from '../errors';\nimport { sha256Hex } from '../hash';\n\nexport interface PreviewData {\n entities: Record<string, Record<string, unknown>>;\n contentCollections: Record<string, unknown>;\n linkTargets?: Record<string, unknown>;\n page?: Record<string, unknown>;\n collection?: Record<string, unknown>;\n}\n\nexport interface DataSourceInput {\n templatePath: string;\n buffers: Record<string, string>;\n path?: string;\n}\n\nexport interface DataSource {\n load: (input: DataSourceInput) => Promise<PreviewData>;\n resolveRoute?: (path: string, templatePaths: string[]) => Promise<string | null>;\n listRoutes?: () => Promise<RemoteRoute[]>;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => {\n return Boolean(value) && typeof value === 'object' && !Array.isArray(value);\n};\n\nconst emptyPreviewData = (): PreviewData => {\n return { entities: {}, contentCollections: {} };\n};\n\nconst hasLinkTargetReferences = (content: string): boolean => {\n try {\n return collectThemeLinkTargetReferences(JSON.parse(content)).length > 0;\n } catch {\n return false;\n }\n};\n\n// Mirrors useThemeVisualBuilderEntities in the admin editor.\nexport const buildPreviewRequest = (buffers: Record<string, string>, templatePath: string, path?: string): ThemePreviewRequest => {\n const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);\n const category = getLiquidThemeTemplateCategory(templatePath);\n const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category, ...(path ? { path } : {}) } : undefined;\n const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));\n const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);\n const sources = getLiquidThemeEntitySources(reachable, templatePath);\n\n const templatePaths = Object.keys(buffers).filter((path) => /^templates\\/[^/]+\\.json$/.test(path));\n const linkSources = Object.entries(buffers)\n .filter(([path, content]) => path.endsWith('.json') && hasLinkTargetReferences(content))\n .map(([, content]) => content);\n\n return { entities, contentCollections, sources, linkSources, templatePaths, page };\n};\n\n// The response is either the envelope { requestedData } or a bare payload; the editor reads requestedData.\nexport const normalizePreviewData = (raw: unknown): PreviewData => {\n const body = isRecord(raw) ? raw : {};\n let payload: Record<string, unknown> = body;\n\n if (isRecord(body.requestedData)) {\n payload = body.requestedData;\n } else if (isRecord(body.data)) {\n payload = body.data;\n }\n\n return {\n entities: isRecord(payload.entities) ? (payload.entities as PreviewData['entities']) : {},\n contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},\n linkTargets: isRecord(payload.linkTargets) ? payload.linkTargets : undefined,\n page: isRecord(payload.page) ? payload.page : undefined,\n collection: isRecord(payload.collection) ? payload.collection : undefined,\n };\n};\n\nexport const createFixturesDataSource = (themeDir: string): DataSource => {\n return {\n load: async ({ templatePath }) => {\n const fixturePath = join(themeDir, 'fixtures', templatePath.replace(/\\//g, '-'));\n let raw: string;\n\n try {\n raw = await readFile(fixturePath, 'utf8');\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n return emptyPreviewData();\n }\n\n throw error;\n }\n\n try {\n return normalizePreviewData(JSON.parse(raw));\n } catch {\n throw new CliError(`${fixturePath} is not valid JSON.`);\n }\n },\n };\n};\n\nexport interface LiveDataSourceOptions {\n client: CmsClient;\n themeId: string;\n countryCode?: string;\n}\n\nconst hasPreviewWork = (request: ThemePreviewRequest): boolean => {\n return request.entities.length > 0 || request.contentCollections.length > 0 || request.linkSources.length > 0 || Boolean(request.page);\n};\n\n// The key covers the query inputs only, so markup and CSS edits that keep the same queries reuse the cached data.\nconst cacheKeyOf = (request: ThemePreviewRequest): string => {\n const keyInput = { entities: request.entities, contentCollections: request.contentCollections, linkSources: request.linkSources, templatePaths: request.templatePaths, page: request.page };\n return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));\n};\n\n// Cached until the process restarts; a restart is also the only time theme metadata is read again.\nexport const createLiveDataSource = (options: LiveDataSourceOptions): DataSource => {\n const cache = new Map<string, Promise<PreviewData>>();\n\n return {\n resolveRoute: (path, templatePaths) => options.client.resolveRoute(options.themeId, path, templatePaths, options.countryCode),\n listRoutes: () => options.client.listRoutes(options.themeId, options.countryCode),\n load: async ({ buffers, templatePath, path }) => {\n const request = buildPreviewRequest(buffers, templatePath, path);\n\n if (!hasPreviewWork(request)) {\n return emptyPreviewData();\n }\n\n const key = cacheKeyOf(request);\n const cached = cache.get(key);\n\n if (cached) {\n return cached;\n }\n\n const pending = options.client\n .previewData(options.themeId, request, options.countryCode)\n .then(normalizePreviewData);\n\n cache.set(key, pending);\n pending.catch(() => {\n if (cache.get(key) === pending) {\n cache.delete(key);\n }\n });\n\n return pending;\n },\n };\n};\n","import { themeTemplateCategories, themeTemplateCategoryKeys, type ThemeTemplateCategory } from '../../../constants/theme';\nimport { liquidThemeFolderNames, liquidThemeTemplatePaths } from '../../../constants/theme';\n\nexport const getLiquidThemeTemplateCategory = (path: string): ThemeTemplateCategory | 'system' | null => {\n if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;\n if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;\n if (path === liquidThemeTemplatePaths.entityDetails) return themeTemplateCategoryKeys.details;\n if (path === liquidThemeTemplatePaths.notFound) return themeTemplateCategoryKeys.system;\n\n for (const category of Object.keys(themeTemplateCategories) as (keyof typeof themeTemplateCategories)[]) {\n const prefix = themeTemplateCategories[category].prefix;\n if (!prefix) continue;\n const categoryPrefix = `${liquidThemeFolderNames.templates}/${prefix}`;\n const name = path.startsWith(categoryPrefix) ? path.slice(categoryPrefix.length) : '';\n if (/^[a-z0-9][a-z0-9_-]*\\.json$/.test(name)) return category;\n }\n return null;\n};\n\nexport const getLiquidThemeTemplateTitle = (path: string, category?: ThemeTemplateCategory): string => {\n if (path === liquidThemeTemplatePaths.index) return 'Home page';\n if (path === liquidThemeTemplatePaths.collection) return 'Collection';\n if (path === liquidThemeTemplatePaths.entityDetails) return 'Entity details';\n\n const templateCategory = category || getLiquidThemeTemplateCategory(path);\n const prefix = templateCategory && templateCategory !== themeTemplateCategoryKeys.system ? themeTemplateCategories[templateCategory].prefix : null;\n const templateName = path.replace(`${liquidThemeFolderNames.templates}/`, '').replace(/\\.json$/, '').replace(prefix || '', '');\n return templateName.replace(/[-_]/g, ' ').replace(/\\b\\w/g, (letter) => letter.toUpperCase());\n};\n\nexport const createLiquidThemeTemplatePath = (category: ThemeTemplateCategory, name: string): string =>\n `${liquidThemeFolderNames.templates}/${themeTemplateCategories[category].prefix}${name}.json`;\n","import { staticThemeFolderNames, staticThemeHtmlExtensionPattern } from '../../../constants/theme';\n\nexport const getStaticHtmlPaths = (files: Array<{ path: string }>): string[] =>\n files\n .map((file) => file.path)\n .filter((path) => path.startsWith(`${staticThemeFolderNames.root}/`) && staticThemeHtmlExtensionPattern.test(path))\n .sort();\n\nexport const getStaticHtmlPageOptions = (paths: string[]) => paths.map((path) => ({ value: path, label: path }));\n\nexport const getStaticHtmlPageContent = (\n selectedPath: string,\n fileBuffers: Record<string, string | undefined>,\n files: Array<{ path: string; content?: string | null }>,\n): string => selectedPath ? fileBuffers[selectedPath] ?? files.find((file) => file.path === selectedPath)?.content ?? '' : '';\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,gB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QAAQ,WAAW,EACzD,KAAK,oBAAoB;AAE9B,YAAM,IAAI,KAAK,OAAO;AACtB,cAAQ,MAAM,MAAM;AAChB,YAAI,MAAM,IAAI,GAAG,MAAM,SAAS;AAC5B,gBAAM,OAAO,GAAG;AAAA,QACpB;AAAA,MACJ,CAAC;AAED,aAAO;AAAA,IACX;AAAA,EACJ;AACJ;","names":["path"]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  liquidThemeAllowedDirectories,
4
4
  sha256Hex
5
- } from "./chunk-UOEFVNM4.js";
5
+ } from "./chunk-VY553LTO.js";
6
6
 
7
7
  // src/lib/theme-files.ts
8
8
  import { readdir, readFile } from "fs/promises";
@@ -53,4 +53,4 @@ export {
53
53
  readLocalTheme,
54
54
  toHashMap
55
55
  };
56
- //# sourceMappingURL=chunk-C5SWGZ55.js.map
56
+ //# sourceMappingURL=chunk-PEG6K5NX.js.map