@tomsher/cms-theme-kit 0.1.0 → 0.1.2
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/bin.js +5 -5
- package/dist/bin.js.map +1 -1
- package/dist/{chunk-TN3DQWJE.js → chunk-JNTSZZHB.js} +10 -2
- package/dist/chunk-JNTSZZHB.js.map +1 -0
- package/dist/{chunk-ND62XRUU.js → chunk-NRS5OZJC.js} +222 -133
- package/dist/chunk-NRS5OZJC.js.map +1 -0
- package/dist/{chunk-YAYCHT4W.js → chunk-O6HJD7DS.js} +2 -2
- package/dist/{server-SWGQTMET.js → chunk-S4NCVJKH.js} +223 -172
- package/dist/chunk-S4NCVJKH.js.map +1 -0
- package/dist/chunk-VCSHHQGG.js +128 -0
- package/dist/chunk-VCSHHQGG.js.map +1 -0
- package/dist/{data-source-CKDBOWKF.js → data-source-DPKANGMF.js} +4 -4
- package/dist/server-4TLWATN6.js +177 -0
- package/dist/server-4TLWATN6.js.map +1 -0
- package/dist/static-server-SKZUHFNU.js +132 -0
- package/dist/static-server-SKZUHFNU.js.map +1 -0
- package/package.json +3 -4
- package/dist/chunk-6NVYKM2E.js +0 -219
- package/dist/chunk-6NVYKM2E.js.map +0 -1
- package/dist/chunk-ND62XRUU.js.map +0 -1
- package/dist/chunk-TN3DQWJE.js.map +0 -1
- package/dist/chunk-UDJL2R66.js +0 -158
- package/dist/chunk-UDJL2R66.js.map +0 -1
- package/dist/server-SWGQTMET.js.map +0 -1
- package/dist/static-server-BTUWXORJ.js +0 -196
- package/dist/static-server-BTUWXORJ.js.map +0 -1
- /package/dist/{chunk-YAYCHT4W.js.map → chunk-O6HJD7DS.js.map} +0 -0
- /package/dist/{data-source-CKDBOWKF.js.map → data-source-DPKANGMF.js.map} +0 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
getLiquidThemeCollectionHandles,
|
|
4
|
+
getLiquidThemeEntityQueries,
|
|
5
|
+
getLiquidThemeEntitySources,
|
|
6
|
+
getLiquidThemeReachableBuffers,
|
|
7
|
+
requiresCurrentEntry
|
|
8
|
+
} from "./chunk-NRS5OZJC.js";
|
|
9
|
+
import {
|
|
10
|
+
CliError,
|
|
11
|
+
liquidThemeFolderNames,
|
|
12
|
+
liquidThemeTemplatePaths,
|
|
13
|
+
sha256Hex,
|
|
14
|
+
themeTemplateCategories,
|
|
15
|
+
themeTemplateCategoryKeys
|
|
16
|
+
} from "./chunk-JNTSZZHB.js";
|
|
17
|
+
|
|
18
|
+
// src/lib/dev/data-source.ts
|
|
19
|
+
import { readFile } from "fs/promises";
|
|
20
|
+
import { join } from "path";
|
|
21
|
+
|
|
22
|
+
// ../cms-theme-engines/dist/utils/index.js
|
|
23
|
+
var getLiquidThemeTemplateCategory = (path) => {
|
|
24
|
+
if (path === liquidThemeTemplatePaths.index) return themeTemplateCategoryKeys.pages;
|
|
25
|
+
if (path === liquidThemeTemplatePaths.collection) return themeTemplateCategoryKeys.collections;
|
|
26
|
+
if (path === liquidThemeTemplatePaths.entityDetails) return themeTemplateCategoryKeys.details;
|
|
27
|
+
if (path === liquidThemeTemplatePaths.notFound) return themeTemplateCategoryKeys.system;
|
|
28
|
+
for (const category of Object.keys(themeTemplateCategories)) {
|
|
29
|
+
const prefix = themeTemplateCategories[category].prefix;
|
|
30
|
+
if (!prefix) continue;
|
|
31
|
+
const categoryPrefix = `${liquidThemeFolderNames.templates}/${prefix}`;
|
|
32
|
+
const name = path.startsWith(categoryPrefix) ? path.slice(categoryPrefix.length) : "";
|
|
33
|
+
if (/^[a-z0-9][a-z0-9_-]*\.json$/.test(name)) return category;
|
|
34
|
+
}
|
|
35
|
+
return null;
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
// src/lib/dev/data-source.ts
|
|
39
|
+
var isRecord = (value) => {
|
|
40
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
41
|
+
};
|
|
42
|
+
var emptyPreviewData = () => {
|
|
43
|
+
return { entities: {}, contentCollections: {} };
|
|
44
|
+
};
|
|
45
|
+
var buildPreviewRequest = (buffers, templatePath) => {
|
|
46
|
+
const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);
|
|
47
|
+
const category = getLiquidThemeTemplateCategory(templatePath);
|
|
48
|
+
const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : void 0;
|
|
49
|
+
const entities = getLiquidThemeEntityQueries(reachable, templatePath).filter((query) => page || !requiresCurrentEntry(query));
|
|
50
|
+
const contentCollections = getLiquidThemeCollectionHandles(buffers, templatePath);
|
|
51
|
+
const sources = getLiquidThemeEntitySources(reachable, templatePath);
|
|
52
|
+
return { entities, contentCollections, sources, page };
|
|
53
|
+
};
|
|
54
|
+
var normalizePreviewData = (raw) => {
|
|
55
|
+
const body = isRecord(raw) ? raw : {};
|
|
56
|
+
let payload = body;
|
|
57
|
+
if (isRecord(body.requestedData)) {
|
|
58
|
+
payload = body.requestedData;
|
|
59
|
+
} else if (isRecord(body.data)) {
|
|
60
|
+
payload = body.data;
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
entities: isRecord(payload.entities) ? payload.entities : {},
|
|
64
|
+
contentCollections: isRecord(payload.contentCollections) ? payload.contentCollections : {},
|
|
65
|
+
page: isRecord(payload.page) ? payload.page : void 0,
|
|
66
|
+
collection: isRecord(payload.collection) ? payload.collection : void 0
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
var createFixturesDataSource = (themeDir) => {
|
|
70
|
+
return {
|
|
71
|
+
load: async ({ templatePath }) => {
|
|
72
|
+
const fixturePath = join(themeDir, "fixtures", templatePath.replace(/\//g, "-"));
|
|
73
|
+
let raw;
|
|
74
|
+
try {
|
|
75
|
+
raw = await readFile(fixturePath, "utf8");
|
|
76
|
+
} catch (error) {
|
|
77
|
+
if (error.code === "ENOENT") {
|
|
78
|
+
return emptyPreviewData();
|
|
79
|
+
}
|
|
80
|
+
throw error;
|
|
81
|
+
}
|
|
82
|
+
try {
|
|
83
|
+
return normalizePreviewData(JSON.parse(raw));
|
|
84
|
+
} catch {
|
|
85
|
+
throw new CliError(`${fixturePath} is not valid JSON.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
var hasPreviewWork = (request) => {
|
|
91
|
+
return request.entities.length > 0 || request.contentCollections.length > 0 || Boolean(request.page);
|
|
92
|
+
};
|
|
93
|
+
var cacheKeyOf = (request) => {
|
|
94
|
+
const keyInput = { entities: request.entities, contentCollections: request.contentCollections, page: request.page };
|
|
95
|
+
return sha256Hex(new TextEncoder().encode(JSON.stringify(keyInput)));
|
|
96
|
+
};
|
|
97
|
+
var createLiveDataSource = (options) => {
|
|
98
|
+
const cache = /* @__PURE__ */ new Map();
|
|
99
|
+
return {
|
|
100
|
+
load: async ({ buffers, templatePath }) => {
|
|
101
|
+
const request = buildPreviewRequest(buffers, templatePath);
|
|
102
|
+
if (!hasPreviewWork(request)) {
|
|
103
|
+
return emptyPreviewData();
|
|
104
|
+
}
|
|
105
|
+
const key = cacheKeyOf(request);
|
|
106
|
+
const cached = cache.get(key);
|
|
107
|
+
if (cached) {
|
|
108
|
+
return cached;
|
|
109
|
+
}
|
|
110
|
+
const pending = options.client.previewData(options.themeId, request, options.countryCode).then(normalizePreviewData);
|
|
111
|
+
cache.set(key, pending);
|
|
112
|
+
pending.catch(() => {
|
|
113
|
+
if (cache.get(key) === pending) {
|
|
114
|
+
cache.delete(key);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
return pending;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
};
|
|
121
|
+
|
|
122
|
+
export {
|
|
123
|
+
buildPreviewRequest,
|
|
124
|
+
normalizePreviewData,
|
|
125
|
+
createFixturesDataSource,
|
|
126
|
+
createLiveDataSource
|
|
127
|
+
};
|
|
128
|
+
//# sourceMappingURL=chunk-VCSHHQGG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/dev/data-source.ts","../../cms-theme-engines/src/utils/analysis/liquid-theme-template.utils.ts","../../cms-theme-engines/src/utils/static-editor/static-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-theme-engines/utils';\nimport { themeTemplateCategoryKeys } from '@tomsher/cms-core/constants';\nimport type { CmsClient, 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 page?: Record<string, unknown>;\n collection?: Record<string, unknown>;\n}\n\nexport interface DataSourceInput {\n templatePath: string;\n buffers: Record<string, string>;\n}\n\nexport interface DataSource {\n load: (input: DataSourceInput) => Promise<PreviewData>;\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\n// Mirrors useThemeVisualBuilderEntities in the admin editor.\nexport const buildPreviewRequest = (buffers: Record<string, string>, templatePath: string): ThemePreviewRequest => {\n const reachable = getLiquidThemeReachableBuffers(buffers, templatePath);\n const category = getLiquidThemeTemplateCategory(templatePath);\n const page = category === themeTemplateCategoryKeys.collections || category === themeTemplateCategoryKeys.details ? { templatePath, category } : 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 return { entities, contentCollections, sources, 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 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 || 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, 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 load: async ({ buffers, templatePath }) => {\n const request = buildPreviewRequest(buffers, templatePath);\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 '@tomsher/cms-core/constants';\nimport { liquidThemeFolderNames, liquidThemeTemplatePaths } from '@tomsher/cms-core/constants';\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 '@tomsher/cms-core/constants';\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,gBAAgB;AACzB,SAAS,YAAY;;;ACEd,IAAM,iCAAiC,CAAC,SAA0D;AACrG,MAAI,SAAS,yBAAyB,MAAO,QAAO,0BAA0B;AAC9E,MAAI,SAAS,yBAAyB,WAAY,QAAO,0BAA0B;AACnF,MAAI,SAAS,yBAAyB,cAAe,QAAO,0BAA0B;AACtF,MAAI,SAAS,yBAAyB,SAAU,QAAO,0BAA0B;AAEjF,aAAW,YAAY,OAAO,KAAK,uBAAuB,GAA+C;AACrG,UAAM,SAAS,wBAAwB,QAAQ,EAAE;AACjD,QAAI,CAAC,OAAQ;AACb,UAAM,iBAAiB,GAAG,uBAAuB,SAAS,IAAI,MAAM;AACpE,UAAM,OAAO,KAAK,WAAW,cAAc,IAAI,KAAK,MAAM,eAAe,MAAM,IAAI;AACnF,QAAI,8BAA8B,KAAK,IAAI,EAAG,QAAO;EACzD;AACA,SAAO;AACX;;;ADOA,IAAM,WAAW,CAAC,UAAqD;AACnE,SAAO,QAAQ,KAAK,KAAK,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC9E;AAEA,IAAM,mBAAmB,MAAmB;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
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
createFixturesDataSource,
|
|
5
5
|
createLiveDataSource,
|
|
6
6
|
normalizePreviewData
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import "./chunk-
|
|
9
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-VCSHHQGG.js";
|
|
8
|
+
import "./chunk-NRS5OZJC.js";
|
|
9
|
+
import "./chunk-JNTSZZHB.js";
|
|
10
10
|
export {
|
|
11
11
|
buildPreviewRequest,
|
|
12
12
|
createFixturesDataSource,
|
|
13
13
|
createLiveDataSource,
|
|
14
14
|
normalizePreviewData
|
|
15
15
|
};
|
|
16
|
-
//# sourceMappingURL=data-source-
|
|
16
|
+
//# sourceMappingURL=data-source-DPKANGMF.js.map
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
closeServer,
|
|
4
|
+
createLiquidFilters,
|
|
5
|
+
createReloadHub,
|
|
6
|
+
createRouteServer,
|
|
7
|
+
linkListHtml,
|
|
8
|
+
listenOnLocalhost,
|
|
9
|
+
notFoundHtml,
|
|
10
|
+
renderErrorPage,
|
|
11
|
+
renderLiquidThemeBundle,
|
|
12
|
+
safeDecode,
|
|
13
|
+
sendHtml,
|
|
14
|
+
sendResponse,
|
|
15
|
+
serveFile
|
|
16
|
+
} from "./chunk-S4NCVJKH.js";
|
|
17
|
+
import {
|
|
18
|
+
isTextPath,
|
|
19
|
+
readLocalTheme
|
|
20
|
+
} from "./chunk-O6HJD7DS.js";
|
|
21
|
+
import {
|
|
22
|
+
buildPreviewRequest
|
|
23
|
+
} from "./chunk-VCSHHQGG.js";
|
|
24
|
+
import {
|
|
25
|
+
applyThemeCustomizerLocaleOverrides,
|
|
26
|
+
ensureThemeStylesheetsBeforeContent,
|
|
27
|
+
getThemeAssetUrls,
|
|
28
|
+
resolveThemeMediaUrl,
|
|
29
|
+
rewriteLiquidThemeAssetBuffers
|
|
30
|
+
} from "./chunk-NRS5OZJC.js";
|
|
31
|
+
import {
|
|
32
|
+
defaultLanguageCode,
|
|
33
|
+
liquidThemeFolderNames
|
|
34
|
+
} from "./chunk-JNTSZZHB.js";
|
|
35
|
+
|
|
36
|
+
// src/lib/dev/server.ts
|
|
37
|
+
import { join, resolve } from "path";
|
|
38
|
+
|
|
39
|
+
// src/lib/dev/render-page.ts
|
|
40
|
+
var buildLocalization = (languageCode, countryCode) => {
|
|
41
|
+
return {
|
|
42
|
+
country: countryCode ? { name: countryCode, countryCode } : void 0,
|
|
43
|
+
language: { languageCode, languageName: languageCode },
|
|
44
|
+
availableCountries: [],
|
|
45
|
+
availableLanguages: []
|
|
46
|
+
};
|
|
47
|
+
};
|
|
48
|
+
var buildPageContext = (data) => {
|
|
49
|
+
if (!data.page) {
|
|
50
|
+
return {};
|
|
51
|
+
}
|
|
52
|
+
const entry = data.page.entry ?? {};
|
|
53
|
+
return {
|
|
54
|
+
page: { ...entry, entity: data.page.entity, type: data.page.type },
|
|
55
|
+
collection: data.collection
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
var renderThemePage = async (options) => {
|
|
59
|
+
const { buffers, assetPaths, templatePath, data, languageCode, countryCode, assetOrigin } = options;
|
|
60
|
+
const localizedBuffers = applyThemeCustomizerLocaleOverrides(buffers, languageCode, defaultLanguageCode);
|
|
61
|
+
const assetFiles = assetPaths.map((path) => ({ path, fileUrl: `${assetOrigin}/${path}` }));
|
|
62
|
+
const themeAssetUrls = getThemeAssetUrls(assetFiles, liquidThemeFolderNames.assets, resolveThemeMediaUrl);
|
|
63
|
+
const previewBuffers = rewriteLiquidThemeAssetBuffers(localizedBuffers, themeAssetUrls);
|
|
64
|
+
const localization = buildLocalization(languageCode, countryCode);
|
|
65
|
+
const customFilters = createLiquidFilters({ fileBuffers: localizedBuffers, activeLocale: languageCode, localization });
|
|
66
|
+
const { entities: entityQueries } = buildPreviewRequest(buffers, templatePath);
|
|
67
|
+
const renderedHtml = await renderLiquidThemeBundle(previewBuffers, {
|
|
68
|
+
customFilters,
|
|
69
|
+
themeAssetUrls,
|
|
70
|
+
templatePath,
|
|
71
|
+
context: {
|
|
72
|
+
entities: data.entities,
|
|
73
|
+
contentCollections: data.contentCollections,
|
|
74
|
+
entityQueries,
|
|
75
|
+
linkTargets: {},
|
|
76
|
+
contentLoading: false,
|
|
77
|
+
localization,
|
|
78
|
+
...buildPageContext(data)
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
return ensureThemeStylesheetsBeforeContent(renderedHtml);
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
// src/lib/dev/server.ts
|
|
85
|
+
var readThemeSnapshot = async (themeDir) => {
|
|
86
|
+
const files = await readLocalTheme(themeDir);
|
|
87
|
+
const buffers = {};
|
|
88
|
+
const assetPaths = [];
|
|
89
|
+
for (const file of files) {
|
|
90
|
+
if (file.path.startsWith("assets/")) {
|
|
91
|
+
assetPaths.push(file.path);
|
|
92
|
+
}
|
|
93
|
+
if (isTextPath(file.path)) {
|
|
94
|
+
buffers[file.path] = new TextDecoder().decode(file.bytes);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return { buffers, assetPaths };
|
|
98
|
+
};
|
|
99
|
+
var startDevServer = async (options) => {
|
|
100
|
+
const themeDir = resolve(options.themeDir);
|
|
101
|
+
const assetsDir = join(themeDir, "assets");
|
|
102
|
+
const reload = createReloadHub();
|
|
103
|
+
let snapshot = await readThemeSnapshot(themeDir);
|
|
104
|
+
const renderTemplate = async (response, templatePath, assetOrigin) => {
|
|
105
|
+
if (snapshot.buffers[templatePath] === void 0) {
|
|
106
|
+
sendHtml(response, 404, notFoundHtml(`${templatePath} does not exist. See /__templates.`));
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
const data = await options.dataSource.load({ templatePath, buffers: snapshot.buffers });
|
|
111
|
+
const html = await renderThemePage({
|
|
112
|
+
buffers: snapshot.buffers,
|
|
113
|
+
assetPaths: snapshot.assetPaths,
|
|
114
|
+
templatePath,
|
|
115
|
+
data,
|
|
116
|
+
languageCode: options.languageCode,
|
|
117
|
+
countryCode: options.countryCode,
|
|
118
|
+
assetOrigin
|
|
119
|
+
});
|
|
120
|
+
sendHtml(response, 200, html);
|
|
121
|
+
} catch (error) {
|
|
122
|
+
sendHtml(response, 500, renderErrorPage(error));
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
const route = async (request, response) => {
|
|
126
|
+
if (request.method !== "GET") {
|
|
127
|
+
sendResponse(response, 405, { "Content-Type": "text/plain; charset=utf-8", Allow: "GET" }, "Method not allowed");
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
131
|
+
const address2 = server.address();
|
|
132
|
+
const assetOrigin = `http://localhost:${address2.port}`;
|
|
133
|
+
if (pathname === "/__events") {
|
|
134
|
+
reload.open(request, response);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
if (pathname === "/__templates") {
|
|
138
|
+
const templatePaths = Object.keys(snapshot.buffers).filter((path) => /^templates\/[^/]+\.json$/.test(path)).sort();
|
|
139
|
+
const links = templatePaths.map((path) => ({ href: `/t/${encodeURI(path)}`, label: path }));
|
|
140
|
+
sendHtml(response, 200, linkListHtml("Templates", links));
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (pathname.startsWith("/assets/")) {
|
|
144
|
+
await serveFile(response, assetsDir, pathname.slice("/assets/".length));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (pathname === "/") {
|
|
148
|
+
await renderTemplate(response, options.templatePath, assetOrigin);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (pathname.startsWith("/t/")) {
|
|
152
|
+
const templatePath = safeDecode(pathname.slice("/t/".length));
|
|
153
|
+
if (templatePath === null) {
|
|
154
|
+
sendHtml(response, 400, notFoundHtml("Malformed template path."));
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
await renderTemplate(response, templatePath, assetOrigin);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
sendHtml(response, 404, notFoundHtml(`No route for ${pathname}.`));
|
|
161
|
+
};
|
|
162
|
+
const server = createRouteServer(route);
|
|
163
|
+
await listenOnLocalhost(server, options.port);
|
|
164
|
+
const address = server.address();
|
|
165
|
+
return {
|
|
166
|
+
url: `http://localhost:${address.port}`,
|
|
167
|
+
notifyChanged: async () => {
|
|
168
|
+
snapshot = await readThemeSnapshot(themeDir);
|
|
169
|
+
reload.broadcast();
|
|
170
|
+
},
|
|
171
|
+
close: () => closeServer(server, reload)
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
export {
|
|
175
|
+
startDevServer
|
|
176
|
+
};
|
|
177
|
+
//# sourceMappingURL=server-4TLWATN6.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/dev/server.ts","../src/lib/dev/render-page.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { join, resolve } from 'node:path';\nimport { isTextPath, readLocalTheme } from '../theme-files';\nimport type { DataSource } from './data-source';\nimport { renderThemePage } from './render-page';\nimport { closeServer, createReloadHub, createRouteServer, linkListHtml, listenOnLocalhost, notFoundHtml, renderErrorPage, safeDecode, sendHtml, sendResponse, serveFile } from './server-shared';\n\nexport interface DevServerOptions {\n themeDir: string;\n port: number;\n templatePath: string;\n languageCode: string;\n countryCode?: string;\n dataSource: DataSource;\n}\n\nexport interface DevServer {\n url: string;\n notifyChanged: () => Promise<void>;\n close: () => Promise<void>;\n}\n\ninterface ThemeSnapshot {\n buffers: Record<string, string>;\n assetPaths: string[];\n}\n\nconst readThemeSnapshot = async (themeDir: string): Promise<ThemeSnapshot> => {\n const files = await readLocalTheme(themeDir);\n const buffers: Record<string, string> = {};\n const assetPaths: string[] = [];\n\n for (const file of files) {\n if (file.path.startsWith('assets/')) {\n assetPaths.push(file.path);\n }\n\n if (isTextPath(file.path)) {\n buffers[file.path] = new TextDecoder().decode(file.bytes);\n }\n }\n\n return { buffers, assetPaths };\n};\n\n// Dev server for one theme folder. The theme is read at start and again on each notifyChanged call.\nexport const startDevServer = async (options: DevServerOptions): Promise<DevServer> => {\n const themeDir = resolve(options.themeDir);\n const assetsDir = join(themeDir, 'assets');\n const reload = createReloadHub();\n let snapshot = await readThemeSnapshot(themeDir);\n\n const renderTemplate = async (response: ServerResponse, templatePath: string, assetOrigin: string): Promise<void> => {\n if (snapshot.buffers[templatePath] === undefined) {\n sendHtml(response, 404, notFoundHtml(`${templatePath} does not exist. See /__templates.`));\n return;\n }\n\n try {\n const data = await options.dataSource.load({ templatePath, buffers: snapshot.buffers });\n const html = await renderThemePage({\n buffers: snapshot.buffers,\n assetPaths: snapshot.assetPaths,\n templatePath,\n data,\n languageCode: options.languageCode,\n countryCode: options.countryCode,\n assetOrigin,\n });\n sendHtml(response, 200, html);\n } catch (error) {\n sendHtml(response, 500, renderErrorPage(error));\n }\n };\n\n const route = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {\n if (request.method !== 'GET') {\n sendResponse(response, 405, { 'Content-Type': 'text/plain; charset=utf-8', Allow: 'GET' }, 'Method not allowed');\n return;\n }\n\n const pathname = new URL(request.url ?? '/', 'http://localhost').pathname;\n const address = server.address() as AddressInfo;\n const assetOrigin = `http://localhost:${address.port}`;\n\n if (pathname === '/__events') {\n reload.open(request, response);\n return;\n }\n\n if (pathname === '/__templates') {\n const templatePaths = Object.keys(snapshot.buffers)\n .filter((path) => /^templates\\/[^/]+\\.json$/.test(path))\n .sort();\n const links = templatePaths.map((path) => ({ href: `/t/${encodeURI(path)}`, label: path }));\n sendHtml(response, 200, linkListHtml('Templates', links));\n return;\n }\n\n if (pathname.startsWith('/assets/')) {\n await serveFile(response, assetsDir, pathname.slice('/assets/'.length));\n return;\n }\n\n if (pathname === '/') {\n await renderTemplate(response, options.templatePath, assetOrigin);\n return;\n }\n\n if (pathname.startsWith('/t/')) {\n const templatePath = safeDecode(pathname.slice('/t/'.length));\n\n if (templatePath === null) {\n sendHtml(response, 400, notFoundHtml('Malformed template path.'));\n return;\n }\n\n await renderTemplate(response, templatePath, assetOrigin);\n return;\n }\n\n sendHtml(response, 404, notFoundHtml(`No route for ${pathname}.`));\n };\n\n const server = createRouteServer(route);\n\n await listenOnLocalhost(server, options.port);\n\n const address = server.address() as AddressInfo;\n\n return {\n url: `http://localhost:${address.port}`,\n notifyChanged: async () => {\n snapshot = await readThemeSnapshot(themeDir);\n reload.broadcast();\n },\n close: () => closeServer(server, reload),\n };\n};\n","import { getThemeAssetUrls } from '@tomsher/cms-core/utils';\nimport { resolveThemeMediaUrl } from '@tomsher/cms-theme-engines/utils';\nimport { applyThemeCustomizerLocaleOverrides } from '@tomsher/cms-theme-engines/utils';\nimport { createLiquidFilters } from '@tomsher/cms-theme-engines/engine';\nimport { defaultLanguageCode } from '@tomsher/cms-core/constants';\nimport { ensureThemeStylesheetsBeforeContent, rewriteLiquidThemeAssetBuffers } from '@tomsher/cms-core/utils';\nimport { liquidThemeFolderNames } from '@tomsher/cms-core/constants';\nimport { renderLiquidThemeBundle } from '@tomsher/cms-theme-engines/engine';\nimport type { StorefrontLocalization } from '@tomsher/cms-core/types';\nimport { buildPreviewRequest, type PreviewData } from './data-source';\n\nexport interface RenderPageOptions {\n buffers: Record<string, string>;\n assetPaths: string[];\n templatePath: string;\n data: PreviewData;\n languageCode: string;\n countryCode?: string;\n assetOrigin: string;\n}\n\nconst buildLocalization = (languageCode: string, countryCode?: string): StorefrontLocalization => {\n return {\n country: countryCode ? { name: countryCode, countryCode } : undefined,\n language: { languageCode, languageName: languageCode },\n availableCountries: [],\n availableLanguages: [],\n };\n};\n\n// Same page context shape as useThemeVisualBuilderPreview.\nconst buildPageContext = (data: PreviewData): Record<string, unknown> => {\n if (!data.page) {\n return {};\n }\n\n const entry = (data.page.entry as Record<string, unknown> | undefined) ?? {};\n\n return {\n page: { ...entry, entity: data.page.entity, type: data.page.type },\n collection: data.collection,\n };\n};\n\n// Renders one template the way the admin editor preview does. Throws on render failure.\nexport const renderThemePage = async (options: RenderPageOptions): Promise<string> => {\n const { buffers, assetPaths, templatePath, data, languageCode, countryCode, assetOrigin } = options;\n const localizedBuffers = applyThemeCustomizerLocaleOverrides(buffers, languageCode, defaultLanguageCode);\n const assetFiles = assetPaths.map((path) => ({ path, fileUrl: `${assetOrigin}/${path}` }));\n const themeAssetUrls = getThemeAssetUrls(assetFiles, liquidThemeFolderNames.assets, resolveThemeMediaUrl);\n const previewBuffers = rewriteLiquidThemeAssetBuffers(localizedBuffers, themeAssetUrls);\n const localization = buildLocalization(languageCode, countryCode);\n const customFilters = createLiquidFilters({ fileBuffers: localizedBuffers, activeLocale: languageCode, localization });\n const { entities: entityQueries } = buildPreviewRequest(buffers, templatePath);\n const renderedHtml = await renderLiquidThemeBundle(previewBuffers, {\n customFilters,\n themeAssetUrls,\n templatePath,\n context: {\n entities: data.entities,\n contentCollections: data.contentCollections,\n entityQueries,\n linkTargets: {},\n contentLoading: false,\n localization,\n ...buildPageContext(data),\n },\n });\n\n return ensureThemeStylesheetsBeforeContent(renderedHtml);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,MAAM,eAAe;;;ACmB9B,IAAM,oBAAoB,CAAC,cAAsB,gBAAiD;AAC9F,SAAO;AAAA,IACH,SAAS,cAAc,EAAE,MAAM,aAAa,YAAY,IAAI;AAAA,IAC5D,UAAU,EAAE,cAAc,cAAc,aAAa;AAAA,IACrD,oBAAoB,CAAC;AAAA,IACrB,oBAAoB,CAAC;AAAA,EACzB;AACJ;AAGA,IAAM,mBAAmB,CAAC,SAA+C;AACrE,MAAI,CAAC,KAAK,MAAM;AACZ,WAAO,CAAC;AAAA,EACZ;AAEA,QAAM,QAAS,KAAK,KAAK,SAAiD,CAAC;AAE3E,SAAO;AAAA,IACH,MAAM,EAAE,GAAG,OAA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5
|
+
createRouteServer,
|
|
6
|
+
linkListHtml,
|
|
7
|
+
listenOnLocalhost,
|
|
8
|
+
notFoundHtml,
|
|
9
|
+
renderErrorPage,
|
|
10
|
+
renderStaticHtmlTheme,
|
|
11
|
+
safeDecode,
|
|
12
|
+
sendHtml,
|
|
13
|
+
sendResponse,
|
|
14
|
+
serveFile
|
|
15
|
+
} from "./chunk-S4NCVJKH.js";
|
|
16
|
+
import {
|
|
17
|
+
isTextPath
|
|
18
|
+
} from "./chunk-O6HJD7DS.js";
|
|
19
|
+
import "./chunk-NRS5OZJC.js";
|
|
20
|
+
import {
|
|
21
|
+
CliError,
|
|
22
|
+
staticThemeFolderNames,
|
|
23
|
+
staticThemeHomePath,
|
|
24
|
+
themeFileExtensions
|
|
25
|
+
} from "./chunk-JNTSZZHB.js";
|
|
26
|
+
|
|
27
|
+
// src/lib/dev/static-server.ts
|
|
28
|
+
import { readdir, readFile } from "fs/promises";
|
|
29
|
+
import { join, relative, resolve, sep } from "path";
|
|
30
|
+
var staticRootPrefix = `${staticThemeFolderNames.root}/`;
|
|
31
|
+
var staticFilesPrefix = "/static-files/";
|
|
32
|
+
var htmlExtension = themeFileExtensions.html;
|
|
33
|
+
var readStaticSnapshot = async (themeDir) => {
|
|
34
|
+
const staticDir = join(themeDir, staticThemeFolderNames.root);
|
|
35
|
+
const entries = await readdir(staticDir, { recursive: true, withFileTypes: true }).catch((error) => {
|
|
36
|
+
if (error.code === "ENOENT") {
|
|
37
|
+
throw new CliError(`No ${staticThemeFolderNames.root}/ folder in ${themeDir}. Pass --mode liquid for a liquid theme.`);
|
|
38
|
+
}
|
|
39
|
+
throw error;
|
|
40
|
+
});
|
|
41
|
+
const files = {};
|
|
42
|
+
const assetUrls = {};
|
|
43
|
+
for (const entry of entries) {
|
|
44
|
+
if (!entry.isFile()) {
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const absolutePath = join(entry.parentPath, entry.name);
|
|
48
|
+
const path = relative(themeDir, absolutePath).split(sep).join("/");
|
|
49
|
+
const relativePath = path.slice(staticRootPrefix.length);
|
|
50
|
+
if (!path.toLowerCase().endsWith(htmlExtension)) {
|
|
51
|
+
assetUrls[path] = `${staticFilesPrefix}${relativePath.split("/").map(encodeURIComponent).join("/")}`;
|
|
52
|
+
}
|
|
53
|
+
if (isTextPath(path)) {
|
|
54
|
+
files[path] = new TextDecoder().decode(await readFile(absolutePath));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { files, assetUrls };
|
|
58
|
+
};
|
|
59
|
+
var pageCandidates = (route) => {
|
|
60
|
+
const name = route.replace(/\/+$/, "");
|
|
61
|
+
if (name === "") {
|
|
62
|
+
return [staticThemeHomePath];
|
|
63
|
+
}
|
|
64
|
+
if (name.endsWith(htmlExtension)) {
|
|
65
|
+
return [`${staticRootPrefix}${name}`];
|
|
66
|
+
}
|
|
67
|
+
return [`${staticRootPrefix}${name}${htmlExtension}`, `${staticRootPrefix}${name}/index${htmlExtension}`];
|
|
68
|
+
};
|
|
69
|
+
var routeOfPage = (path) => {
|
|
70
|
+
const name = path.slice(staticRootPrefix.length, -htmlExtension.length);
|
|
71
|
+
return name === "index" ? "/" : `/${name.replace(/\/index$/, "")}`;
|
|
72
|
+
};
|
|
73
|
+
var startStaticDevServer = async (options) => {
|
|
74
|
+
const themeDir = resolve(options.themeDir);
|
|
75
|
+
const staticDir = join(themeDir, staticThemeFolderNames.root);
|
|
76
|
+
const reload = createReloadHub();
|
|
77
|
+
let snapshot = await readStaticSnapshot(themeDir);
|
|
78
|
+
const renderPage = (response, pathname, route) => {
|
|
79
|
+
const templatePath = pageCandidates(route).find((candidate) => snapshot.files[candidate] !== void 0);
|
|
80
|
+
if (templatePath === void 0) {
|
|
81
|
+
sendHtml(response, 404, notFoundHtml(`No page for ${pathname}. See /__templates.`));
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
const { documentHtml } = renderStaticHtmlTheme({ templatePath, files: snapshot.files, assetUrls: snapshot.assetUrls });
|
|
86
|
+
sendHtml(response, 200, documentHtml ?? "");
|
|
87
|
+
} catch (error) {
|
|
88
|
+
sendHtml(response, 500, renderErrorPage(error));
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
const handleRequest = async (request, response) => {
|
|
92
|
+
if (request.method !== "GET") {
|
|
93
|
+
sendResponse(response, 405, { "Content-Type": "text/plain; charset=utf-8", Allow: "GET" }, "Method not allowed");
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
const pathname = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
97
|
+
if (pathname === "/__events") {
|
|
98
|
+
reload.open(request, response);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (pathname === "/__templates") {
|
|
102
|
+
const links = Object.keys(snapshot.files).filter((path) => path.toLowerCase().endsWith(htmlExtension)).sort().map((path) => ({ href: encodeURI(routeOfPage(path)), label: path }));
|
|
103
|
+
sendHtml(response, 200, linkListHtml("Pages", links));
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
if (pathname.startsWith(staticFilesPrefix)) {
|
|
107
|
+
await serveFile(response, staticDir, pathname.slice(staticFilesPrefix.length));
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
const routePath = safeDecode(pathname.slice(1));
|
|
111
|
+
if (routePath === null) {
|
|
112
|
+
sendHtml(response, 400, notFoundHtml("Malformed page path."));
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
renderPage(response, pathname, routePath);
|
|
116
|
+
};
|
|
117
|
+
const server = createRouteServer(handleRequest);
|
|
118
|
+
await listenOnLocalhost(server, options.port);
|
|
119
|
+
const address = server.address();
|
|
120
|
+
return {
|
|
121
|
+
url: `http://localhost:${address.port}`,
|
|
122
|
+
notifyChanged: async () => {
|
|
123
|
+
snapshot = await readStaticSnapshot(themeDir);
|
|
124
|
+
reload.broadcast();
|
|
125
|
+
},
|
|
126
|
+
close: () => closeServer(server, reload)
|
|
127
|
+
};
|
|
128
|
+
};
|
|
129
|
+
export {
|
|
130
|
+
startStaticDevServer
|
|
131
|
+
};
|
|
132
|
+
//# sourceMappingURL=static-server-SKZUHFNU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/dev/static-server.ts"],"sourcesContent":["import { readdir, readFile } from 'node:fs/promises';\nimport type { IncomingMessage, ServerResponse } from 'node:http';\nimport type { AddressInfo } from 'node:net';\nimport { join, relative, resolve, sep } from 'node:path';\nimport { staticThemeFolderNames, staticThemeHomePath, themeFileExtensions } from '@tomsher/cms-core/constants';\nimport { renderStaticHtmlTheme } from '@tomsher/cms-theme-engines/engine';\nimport { CliError } from '../errors';\nimport { isTextPath } from '../theme-files';\nimport type { DevServer } from './server';\nimport { closeServer, createReloadHub, createRouteServer, linkListHtml, listenOnLocalhost, notFoundHtml, renderErrorPage, safeDecode, sendHtml, sendResponse, serveFile } from './server-shared';\n\nexport interface StaticDevServerOptions {\n themeDir: string;\n port: number;\n}\n\ninterface StaticSnapshot {\n files: Record<string, string>;\n assetUrls: Record<string, string>;\n}\n\nconst staticRootPrefix = `${staticThemeFolderNames.root}/`;\nconst staticFilesPrefix = '/static-files/';\nconst htmlExtension = themeFileExtensions.html;\n\n// Text files are renderer sources. Every non-HTML file gets a local URL that the dev server serves from disk.\nconst readStaticSnapshot = async (themeDir: string): Promise<StaticSnapshot> => {\n const staticDir = join(themeDir, staticThemeFolderNames.root);\n const entries = await readdir(staticDir, { recursive: true, withFileTypes: true }).catch((error: NodeJS.ErrnoException) => {\n if (error.code === 'ENOENT') {\n throw new CliError(`No ${staticThemeFolderNames.root}/ folder in ${themeDir}. Pass --mode liquid for a liquid theme.`);\n }\n\n throw error;\n });\n const files: Record<string, string> = {};\n const assetUrls: Record<string, string> = {};\n\n for (const entry of entries) {\n if (!entry.isFile()) {\n continue;\n }\n\n const absolutePath = join(entry.parentPath, entry.name);\n const path = relative(themeDir, absolutePath).split(sep).join('/');\n const relativePath = path.slice(staticRootPrefix.length);\n\n if (!path.toLowerCase().endsWith(htmlExtension)) {\n assetUrls[path] = `${staticFilesPrefix}${relativePath.split('/').map(encodeURIComponent).join('/')}`;\n }\n\n if (isTextPath(path)) {\n files[path] = new TextDecoder().decode(await readFile(absolutePath));\n }\n }\n\n return { files, assetUrls };\n};\n\n// Lookup order for a route: static/<route>.html, then static/<route>/index.html. The route \"\" is the home page.\nconst pageCandidates = (route: string): string[] => {\n const name = route.replace(/\\/+$/, '');\n\n if (name === '') {\n return [staticThemeHomePath];\n }\n\n if (name.endsWith(htmlExtension)) {\n return [`${staticRootPrefix}${name}`];\n }\n\n return [`${staticRootPrefix}${name}${htmlExtension}`, `${staticRootPrefix}${name}/index${htmlExtension}`];\n};\n\n// static/docs/index.html is served at /docs and static/index.html at /.\nconst routeOfPage = (path: string): string => {\n const name = path.slice(staticRootPrefix.length, -htmlExtension.length);\n\n return name === 'index' ? '/' : `/${name.replace(/\\/index$/, '')}`;\n};\n\n// Dev server for a static theme folder (static/ holds the pages and their assets). Files are re-read on each notifyChanged call.\nexport const startStaticDevServer = async (options: StaticDevServerOptions): Promise<DevServer> => {\n const themeDir = resolve(options.themeDir);\n const staticDir = join(themeDir, staticThemeFolderNames.root);\n const reload = createReloadHub();\n let snapshot = await readStaticSnapshot(themeDir);\n\n const renderPage = (response: ServerResponse, pathname: string, route: string): void => {\n const templatePath = pageCandidates(route).find((candidate) => snapshot.files[candidate] !== undefined);\n\n if (templatePath === undefined) {\n sendHtml(response, 404, notFoundHtml(`No page for ${pathname}. See /__templates.`));\n return;\n }\n\n try {\n const { documentHtml } = renderStaticHtmlTheme({ templatePath, files: snapshot.files, assetUrls: snapshot.assetUrls });\n sendHtml(response, 200, documentHtml ?? '');\n } catch (error) {\n sendHtml(response, 500, renderErrorPage(error));\n }\n };\n\n const handleRequest = async (request: IncomingMessage, response: ServerResponse): Promise<void> => {\n if (request.method !== 'GET') {\n sendResponse(response, 405, { 'Content-Type': 'text/plain; charset=utf-8', Allow: 'GET' }, 'Method not allowed');\n return;\n }\n\n const pathname = new URL(request.url ?? '/', 'http://localhost').pathname;\n\n if (pathname === '/__events') {\n reload.open(request, response);\n return;\n }\n\n if (pathname === '/__templates') {\n const links = Object.keys(snapshot.files)\n .filter((path) => path.toLowerCase().endsWith(htmlExtension))\n .sort()\n .map((path) => ({ href: encodeURI(routeOfPage(path)), label: path }));\n sendHtml(response, 200, linkListHtml('Pages', links));\n return;\n }\n\n if (pathname.startsWith(staticFilesPrefix)) {\n await serveFile(response, staticDir, pathname.slice(staticFilesPrefix.length));\n return;\n }\n\n const routePath = safeDecode(pathname.slice(1));\n\n if (routePath === null) {\n sendHtml(response, 400, notFoundHtml('Malformed page path.'));\n return;\n }\n\n renderPage(response, pathname, routePath);\n };\n\n const server = createRouteServer(handleRequest);\n\n await listenOnLocalhost(server, options.port);\n\n const address = server.address() as AddressInfo;\n\n return {\n url: `http://localhost:${address.port}`,\n notifyChanged: async () => {\n snapshot = await readStaticSnapshot(themeDir);\n reload.broadcast();\n },\n close: () => closeServer(server, reload),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,SAAS,gBAAgB;AAGlC,SAAS,MAAM,UAAU,SAAS,WAAW;AAkB7C,IAAM,mBAAmB,GAAG,uBAAuB,IAAI;AACvD,IAAM,oBAAoB;AAC1B,IAAM,gBAAgB,oBAAoB;AAG1C,IAAM,qBAAqB,OAAO,aAA8C;AAC5E,QAAM,YAAY,KAAK,UAAU,uBAAuB,IAAI;AAC5D,QAAM,UAAU,MAAM,QAAQ,WAAW,EAAE,WAAW,MAAM,eAAe,KAAK,CAAC,EAAE,MAAM,CAAC,UAAiC;AACvH,QAAI,MAAM,SAAS,UAAU;AACzB,YAAM,IAAI,SAAS,MAAM,uBAAuB,IAAI,eAAe,QAAQ,0CAA0C;AAAA,IACzH;AAEA,UAAM;AAAA,EACV,CAAC;AACD,QAAM,QAAgC,CAAC;AACvC,QAAM,YAAoC,CAAC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AAM,CAAC;AAC7E;AAAA,IACJ;AAEA,UAAM,YAAY,WAAW,SAAS,MAAM,CAAC,CAAC;AAE9C,QAAI,cAAc,MAAM;AACpB,eAAS,UAAU,KAAK,aAAa,sBAAsB,CAAC;AAC5D;AAAA,IACJ;AAEA,eAAW,UAAU,UAAU,SAAS;AAAA,EAC5C;AAEA,QAAM,SAAS,kBAAkB,aAAa;AAE9C,QAAM,kBAAkB,QAAQ,QAAQ,IAAI;AAE5C,QAAM,UAAU,OAAO,QAAQ;AAE/B,SAAO;AAAA,IACH,KAAK,oBAAoB,QAAQ,IAAI;AAAA,IACrC,eAAe,YAAY;AACvB,iBAAW,MAAM,mBAAmB,QAAQ;AAC5C,aAAO,UAAU;AAAA,IACrB;AAAA,IACA,OAAO,MAAM,YAAY,QAAQ,MAAM;AAAA,EAC3C;AACJ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tomsher/cms-theme-kit",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Pull a theme from a Tomsher CMS, edit it locally and push it back as a draft.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -22,9 +22,8 @@
|
|
|
22
22
|
"sanitize-html": "^2.18.0"
|
|
23
23
|
},
|
|
24
24
|
"devDependencies": {
|
|
25
|
-
"@tomsher/cms-core": "0.1.
|
|
26
|
-
"@tomsher/
|
|
27
|
-
"@tomsher/static-engine": "0.1.0",
|
|
25
|
+
"@tomsher/cms-core": "0.1.2",
|
|
26
|
+
"@tomsher/cms-theme-engines": "0.1.2",
|
|
28
27
|
"@types/node": "^22.10.0",
|
|
29
28
|
"tsup": "^8.5.0",
|
|
30
29
|
"typescript": "^5.9.3",
|