create-template-bricks 0.0.0-stage → 1.0.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.
Files changed (157) hide show
  1. package/README.md +85 -2
  2. package/bin/cli.js +403 -0
  3. package/package.json +49 -4
  4. package/templates/base/.babelrc +18 -0
  5. package/templates/base/.editorconfig +22 -0
  6. package/templates/base/.eslintrc.json +130 -0
  7. package/templates/base/AGENTS.md +49 -0
  8. package/templates/base/README.md +121 -0
  9. package/templates/base/gulpfile.js +46 -0
  10. package/templates/base/package.json +82 -0
  11. package/templates/base/postcss.config.mjs +6 -0
  12. package/templates/base/src/assets/css/vendor/.gitkeep +0 -0
  13. package/templates/base/src/assets/fonts/.gitkeep +0 -0
  14. package/templates/base/src/assets/img/Logo.svg +32 -0
  15. package/templates/base/src/assets/img/favicons/favicon.ico +0 -0
  16. package/templates/base/src/assets/img/sprite/cup-bronze.png +0 -0
  17. package/templates/base/src/assets/img/sprite/cup-bronze@2x.png +0 -0
  18. package/templates/base/src/assets/img/sprite.png +0 -0
  19. package/templates/base/src/assets/img/sprite@2x.png +0 -0
  20. package/templates/base/src/assets/img/svg-sprite/close.svg +3 -0
  21. package/templates/base/src/assets/img/svg-sprite/favorite.svg +3 -0
  22. package/templates/base/src/assets/img/svg-sprite/keyboard.svg +3 -0
  23. package/templates/base/src/assets/js/vendor/.gitkeep +0 -0
  24. package/templates/base/src/styles/core/base.scss +31 -0
  25. package/templates/base/src/styles/core/extends.scss +11 -0
  26. package/templates/base/src/styles/core/fonts.scss +0 -0
  27. package/templates/base/src/styles/core/index.scss +10 -0
  28. package/templates/base/src/styles/core/keyframes.scss +49 -0
  29. package/templates/base/src/styles/core/layouts/footer.scss +1 -0
  30. package/templates/base/src/styles/core/layouts/header/index.scss +1 -0
  31. package/templates/base/src/styles/core/layouts/index.scss +2 -0
  32. package/templates/base/src/styles/core/page.scss +16 -0
  33. package/templates/base/src/styles/core/typography.scss +1 -0
  34. package/templates/base/src/styles/core/ui/icons.scss +31 -0
  35. package/templates/base/src/styles/core/ui/index.scss +2 -0
  36. package/templates/base/src/styles/core/ui/scrollbar.scss +14 -0
  37. package/templates/base/src/styles/core/variables.scss +41 -0
  38. package/templates/base/src/styles/index.scss +1 -0
  39. package/templates/base/src/styles/plugins/functions.scss +0 -0
  40. package/templates/base/src/styles/plugins/media.scss +63 -0
  41. package/templates/base/src/styles/plugins/mixins.scss +31 -0
  42. package/templates/base/src/styles/plugins/sprite-mixin.scss +75 -0
  43. package/templates/base/src/styles/plugins/sprite.scss +154 -0
  44. package/templates/base/src/styles.scss +2 -0
  45. package/templates/base/src/tailwind.css +1 -0
  46. package/templates/base/src/tmplConfig.js +22 -0
  47. package/templates/base/tailwind.config.js +23 -0
  48. package/templates/base/tasks/archive.js +37 -0
  49. package/templates/base/tasks/clean.js +17 -0
  50. package/templates/base/tasks/config.js +98 -0
  51. package/templates/base/tasks/copy.js +53 -0
  52. package/templates/base/tasks/helper.js +31 -0
  53. package/templates/base/tasks/images/image-optimize.js +46 -0
  54. package/templates/base/tasks/images/index.js +27 -0
  55. package/templates/base/tasks/images/plugins/optimize-raster.js +44 -0
  56. package/templates/base/tasks/images/png-sprite.js +43 -0
  57. package/templates/base/tasks/template/data.js +28 -0
  58. package/templates/base/tasks/template/index.js +48 -0
  59. package/templates/base/tasks/template/plugins/generate-static-path.js +37 -0
  60. package/templates/base/tasks/template/plugins/nunjucks-relative-paths-includes.js +39 -0
  61. package/templates/base/tasks/template/plugins/nunjucks-relative-system-loader.js +28 -0
  62. package/templates/base/tasks/template/plugins/template-dependencies.js +246 -0
  63. package/templates/base/tasks/template/template.js +172 -0
  64. package/templates/base/tasks/watcher.js +233 -0
  65. package/templates/base/tasks/webpack/env.js +21 -0
  66. package/templates/base/tasks/webpack/plugins/build-status-plugin.js +74 -0
  67. package/templates/base/tasks/webpack/plugins/current-color-plugin.js +225 -0
  68. package/templates/base/tasks/webpack/plugins/removeFilesOnlyJs.js +28 -0
  69. package/templates/base/tasks/webpack/scripts.config.js +147 -0
  70. package/templates/base/tasks/webpack/styles.config.js +126 -0
  71. package/templates/base/tasks/webpack/svg-sprite.config.js +95 -0
  72. package/templates/base/tasks/webpack/watch.js +50 -0
  73. package/templates/base/tsconfig.json +20 -0
  74. package/templates/base/user.config.js +102 -0
  75. package/templates/base/webpack.config.js +9 -0
  76. package/templates/template-js/js/api/api.js +0 -0
  77. package/templates/template-js/js/core/core.js +56 -0
  78. package/templates/template-js/js/main.js +6 -0
  79. package/templates/template-js/js/modules/header.js +15 -0
  80. package/templates/template-js/js/modules/index.js +24 -0
  81. package/templates/template-js/js/services/index.js +1 -0
  82. package/templates/template-js/js/services/query-params.js +19 -0
  83. package/templates/template-js/js/styles.js +2 -0
  84. package/templates/template-js/js/ui/index.js +18 -0
  85. package/templates/template-js/js/utils/constants.js +0 -0
  86. package/templates/template-js/js/utils/create-factory.js +65 -0
  87. package/templates/template-js/js/utils/debounce.js +8 -0
  88. package/templates/template-js/js/utils/delay.js +4 -0
  89. package/templates/template-js/js/utils/is-platform.js +15 -0
  90. package/templates/template-js/js/utils/throttle.js +16 -0
  91. package/templates/template-mjml/emails/assets/images/address-btn.jpg +0 -0
  92. package/templates/template-mjml/emails/assets/images/address.jpg +0 -0
  93. package/templates/template-mjml/emails/assets/images/banner.jpg +0 -0
  94. package/templates/template-mjml/emails/assets/images/close.png +0 -0
  95. package/templates/template-mjml/emails/assets/images/confirm-btn.jpg +0 -0
  96. package/templates/template-mjml/emails/assets/images/facebook.png +0 -0
  97. package/templates/template-mjml/emails/assets/images/forgot.jpg +0 -0
  98. package/templates/template-mjml/emails/assets/images/icon-info.png +0 -0
  99. package/templates/template-mjml/emails/assets/images/img-send.jpg +0 -0
  100. package/templates/template-mjml/emails/assets/images/instagram.png +0 -0
  101. package/templates/template-mjml/emails/assets/images/logo.png +0 -0
  102. package/templates/template-mjml/emails/assets/images/reset-btn.jpg +0 -0
  103. package/templates/template-mjml/emails/assets/images/twitter.png +0 -0
  104. package/templates/template-mjml/emails/pages/address.mjml +55 -0
  105. package/templates/template-mjml/emails/pages/confirm-resend.mjml +63 -0
  106. package/templates/template-mjml/emails/pages/confirm.mjml +44 -0
  107. package/templates/template-mjml/emails/pages/forgot-password.mjml +65 -0
  108. package/templates/template-mjml/emails/shared/ui/head/fonts.mjml +211 -0
  109. package/templates/template-mjml/emails/shared/ui/head/index.mjml +146 -0
  110. package/templates/template-mjml/emails/widgets/footer/ui/index.mjml +12 -0
  111. package/templates/template-nunjucks/templates/layouts/base.njk +23 -0
  112. package/templates/template-nunjucks/templates/pages/index.njk +9 -0
  113. package/templates/template-nunjucks/templates/shared/ui/head/data.json +8 -0
  114. package/templates/template-nunjucks/templates/shared/ui/head/index.njk +13 -0
  115. package/templates/template-nunjucks/templates/shared/ui/icon/index.njk +5 -0
  116. package/templates/template-nunjucks/templates/widgets/footer/index.njk +5 -0
  117. package/templates/template-nunjucks/templates/widgets/footer/model/data.json +4 -0
  118. package/templates/template-nunjucks/templates/widgets/footer/ui/index.njk +7 -0
  119. package/templates/template-nunjucks/templates/widgets/home-hero/index.njk +1 -0
  120. package/templates/template-nunjucks/templates/widgets/home-hero/ui/index.njk +9 -0
  121. package/templates/template-pug/templates/layouts/base.pug +19 -0
  122. package/templates/template-pug/templates/pages/index.pug +12 -0
  123. package/templates/template-pug/templates/shared/lib/blocks.pug +21 -0
  124. package/templates/template-pug/templates/shared/ui/head/data.json +8 -0
  125. package/templates/template-pug/templates/shared/ui/head/index.pug +10 -0
  126. package/templates/template-pug/templates/shared/ui/icon/index.pug +3 -0
  127. package/templates/template-pug/templates/widgets/footer/index.pug +1 -0
  128. package/templates/template-pug/templates/widgets/footer/model/data.json +4 -0
  129. package/templates/template-pug/templates/widgets/footer/ui/index.pug +4 -0
  130. package/templates/template-pug/templates/widgets/home-hero/index.pug +1 -0
  131. package/templates/template-pug/templates/widgets/home-hero/ui/index.pug +6 -0
  132. package/templates/template-ts/ts/api/api.ts +0 -0
  133. package/templates/template-ts/ts/core/core.ts +66 -0
  134. package/templates/template-ts/ts/interfaces/factory.ts +5 -0
  135. package/templates/template-ts/ts/main.ts +6 -0
  136. package/templates/template-ts/ts/modules/header.ts +17 -0
  137. package/templates/template-ts/ts/modules/index.ts +26 -0
  138. package/templates/template-ts/ts/services/index.ts +2 -0
  139. package/templates/template-ts/ts/services/query-params.ts +23 -0
  140. package/templates/template-ts/ts/styles.ts +2 -0
  141. package/templates/template-ts/ts/ui/index.ts +23 -0
  142. package/templates/template-ts/ts/utils/constants.ts +0 -0
  143. package/templates/template-ts/ts/utils/create-factory.ts +91 -0
  144. package/templates/template-ts/ts/utils/debounce.ts +10 -0
  145. package/templates/template-ts/ts/utils/delay.ts +5 -0
  146. package/templates/template-ts/ts/utils/is-platform.ts +21 -0
  147. package/templates/template-ts/ts/utils/throttle.ts +19 -0
  148. package/templates/template-twig/templates/layouts/base.html.twig +26 -0
  149. package/templates/template-twig/templates/pages/index.html.twig +8 -0
  150. package/templates/template-twig/templates/shared/ui/head/data.json +8 -0
  151. package/templates/template-twig/templates/shared/ui/head/index.html.twig +11 -0
  152. package/templates/template-twig/templates/shared/ui/icon/index.html.twig +21 -0
  153. package/templates/template-twig/templates/widgets/footer/index.html.twig +1 -0
  154. package/templates/template-twig/templates/widgets/footer/model/data.json +4 -0
  155. package/templates/template-twig/templates/widgets/footer/ui/index.html.twig +5 -0
  156. package/templates/template-twig/templates/widgets/home-hero/index.html.twig +1 -0
  157. package/templates/template-twig/templates/widgets/home-hero/ui/index.html.twig +9 -0
@@ -0,0 +1,44 @@
1
+ import path from 'node:path';
2
+ import { Transform } from 'node:stream';
3
+ import sharp from 'sharp';
4
+
5
+ const optimize = async (file, optimizePng) => {
6
+ const extension = path.extname(file.path).toLowerCase();
7
+ if (!['.jpg', '.jpeg', '.gif'].includes(extension)
8
+ && !(extension === '.png' && optimizePng)) return;
9
+
10
+ const image = sharp(file.contents, { animated: true }).keepMetadata();
11
+ let output;
12
+
13
+ if (extension === '.jpg' || extension === '.jpeg') {
14
+ output = image.jpeg({ quality: 80, progressive: true });
15
+ } else if (extension === '.png') {
16
+ output = image.png({ compressionLevel: 9 });
17
+ } else {
18
+ output = image.gif({ progressive: true, effort: 3 });
19
+ }
20
+
21
+ const contents = await output.toBuffer();
22
+ if (contents.length < file.contents.length) file.contents = contents;
23
+ };
24
+
25
+ export default function optimizeRaster({ optimizePng }) {
26
+ return new Transform({
27
+ objectMode: true,
28
+ transform(file, encoding, callback) {
29
+ if (file.isNull()) {
30
+ callback(null, file);
31
+ return;
32
+ }
33
+ if (file.isStream()) {
34
+ callback(new Error(`Image optimization requires buffered files: ${file.path}`));
35
+ return;
36
+ }
37
+
38
+ optimize(file, optimizePng).then(
39
+ () => callback(null, file),
40
+ error => callback(new Error(`Cannot optimize image ${file.path}: ${error.message}`, { cause: error }))
41
+ );
42
+ }
43
+ });
44
+ }
@@ -0,0 +1,43 @@
1
+ import gulp from 'gulp';
2
+ import * as config from '../config.js';
3
+ import { $ } from '../helper.js';
4
+ import userConfig from '../../user.config.js';
5
+ const { src, dest } = gulp;
6
+ const { spritePng } = userConfig;
7
+
8
+ const createPngSprite = () => {
9
+ let runSprite = true;
10
+
11
+ return {
12
+ pngSprite: done => {
13
+ if (spritePng && runSprite) {
14
+ runSprite = false;
15
+
16
+ return src([
17
+ `${config.imagesPath.spriteSrc}/*.png`
18
+ ])
19
+ .pipe($.spritesmith({
20
+ imgName: 'sprite.png',
21
+ retinaSrcFilter: `${config.imagesPath.spriteSrc}/*@2x.png`,
22
+ retinaImgName: 'sprite@2x.png',
23
+ retinaImgPath: `${config.imagesPath.dist}`,
24
+ cssName: 'sprite.scss',
25
+ algorithm: 'top-down',
26
+ padding: 2
27
+ }))
28
+ .pipe($.debug({ title: 'sprites' }))
29
+ .pipe($.if(/[.]png$/, dest(`${config.imagesPath.src}`)))
30
+ .pipe($.if(/[.]png$/, dest(`${config.imagesPath.dist}`)))
31
+ .pipe(
32
+ $.if(/[.]scss$/, dest(config.imagesPath.spriteStylesDist))
33
+ );
34
+ }
35
+
36
+ return done();
37
+ }
38
+ };
39
+ };
40
+
41
+ const pngSpriteModule = createPngSprite();
42
+
43
+ export default pngSpriteModule;
@@ -0,0 +1,28 @@
1
+ import gulp from 'gulp';
2
+ import fs from 'fs';
3
+ import { $ } from '../helper.js';
4
+ import { templatePath } from '../config.js';
5
+ const { src, dest } = gulp;
6
+ const {
7
+ dataFileName,
8
+ dataFiles,
9
+ dataDist
10
+ } = templatePath;
11
+
12
+ const createData = () => {
13
+ return {
14
+ dataRun: () => {
15
+ return src(dataFiles)
16
+ .pipe($.mergeJson({ fileName: dataFileName }))
17
+ .pipe(dest(dataDist));
18
+ },
19
+
20
+ dataParser: () => {
21
+ return JSON.parse(fs.readFileSync(dataDist + dataFileName, 'utf8'));
22
+ }
23
+ };
24
+ };
25
+
26
+ const dataModule = createData();
27
+
28
+ export default dataModule;
@@ -0,0 +1,48 @@
1
+ import gulp from 'gulp';
2
+ import { reload } from '../helper.js';
3
+ import dataModule from './data.js';
4
+ import templateTasks from './template.js';
5
+ const { parallel, series } = gulp;
6
+ const { dataRun } = dataModule;
7
+
8
+ const createTemplate = () => {
9
+ const {
10
+ templateCompile,
11
+ templateRecompileAll,
12
+ emailsCompile
13
+ } = templateTasks;
14
+
15
+ const tasks = {
16
+ templateRun: () => {
17
+ return series(
18
+ dataRun,
19
+ parallel(
20
+ templateCompile,
21
+ emailsCompile
22
+ )
23
+ );
24
+ },
25
+
26
+ templates: () => {
27
+ return templateCompile;
28
+ },
29
+
30
+ data: () => {
31
+ return series(
32
+ dataRun,
33
+ templateRecompileAll,
34
+ reload
35
+ );
36
+ },
37
+
38
+ emails: () => {
39
+ return series(emailsCompile, reload);
40
+ }
41
+ };
42
+
43
+ return tasks;
44
+ };
45
+
46
+ const templateModule = createTemplate();
47
+
48
+ export default templateModule;
@@ -0,0 +1,37 @@
1
+ import path from 'node:path';
2
+ import { Transform } from 'node:stream';
3
+ import userConfig from '../../../user.config.js';
4
+
5
+ const generateStaticPath = ({ prefix = userConfig.templateLocals.pathPrefix } = {}) => {
6
+ return new Transform({
7
+ objectMode: true,
8
+ transform(file, encoding, callback) {
9
+ if (file.isNull() || typeof prefix !== 'string' || prefix.length === 0) {
10
+ callback(null, file);
11
+ return;
12
+ }
13
+
14
+ if (file.isStream()) {
15
+ callback(new Error('generate-static-path requires buffered file contents.'));
16
+ return;
17
+ }
18
+
19
+ try {
20
+ const relativePath = file.relative.replace(/\\/g, '/');
21
+ const directory = path.posix.dirname(relativePath);
22
+ const depth = directory === '.'
23
+ ? 0
24
+ : directory.split('/').filter(Boolean).length;
25
+ const replacement = '../'.repeat(depth);
26
+ const content = file.contents.toString('utf8');
27
+
28
+ file.contents = Buffer.from(content.split(prefix).join(replacement), 'utf8');
29
+ callback(null, file);
30
+ } catch (error) {
31
+ callback(error);
32
+ }
33
+ }
34
+ });
35
+ };
36
+
37
+ export default generateStaticPath;
@@ -0,0 +1,39 @@
1
+ import path from 'path';
2
+ import through2 from 'through2';
3
+
4
+ export default function nunjucksResolveRelativeIncludes({ root }) {
5
+ const TAG_RE = /{%\s*(include|extends|import|from)\s+(['"])([^'"]+)\2/g;
6
+
7
+ const toPosix = (p) => p.replace(/\\/g, '/');
8
+
9
+ return through2.obj(function (file, enc, cb) {
10
+ if (file.isNull()) return cb(null, file);
11
+ if (file.isStream()) return cb(new Error('Streaming not supported'));
12
+
13
+ const rootAbs = path.resolve(root);
14
+ const fileDirAbs = path.dirname(file.path);
15
+
16
+ const fromDirRel = toPosix(path.relative(rootAbs, fileDirAbs));
17
+
18
+ let html = file.contents.toString(enc);
19
+
20
+ html = html.replace(TAG_RE, (full, tag, quote, target) => {
21
+ if (!target.startsWith('./') && !target.startsWith('../')) return full;
22
+
23
+ const resolved = path.posix.normalize(
24
+ path.posix.join(fromDirRel ? fromDirRel : '', toPosix(target))
25
+ );
26
+
27
+ if (resolved.startsWith('..')) {
28
+ throw new Error(
29
+ `Nunjucks path escapes root.\nFile: ${file.path}\nTag: ${tag} "${target}"`
30
+ );
31
+ }
32
+
33
+ return `{% ${tag} ${quote}${resolved}${quote}`;
34
+ });
35
+
36
+ file.contents = Buffer.from(html, enc);
37
+ cb(null, file);
38
+ });
39
+ }
@@ -0,0 +1,28 @@
1
+ import nunjucks from 'nunjucks';
2
+ import path from 'path';
3
+
4
+ export default class RelativeFileSystemLoader extends nunjucks.FileSystemLoader {
5
+ constructor(searchPaths, opts = {}) {
6
+ super(searchPaths, { noCache: true, ...opts });
7
+ // eslint-disable-next-line no-underscore-dangle
8
+ this._roots = (Array.isArray(searchPaths) ? searchPaths : [searchPaths])
9
+ .map(p => path.resolve(p));
10
+ }
11
+
12
+ resolve(from, to) {
13
+ if (!to.startsWith('./') && !to.startsWith('../')) return to;
14
+
15
+ const fromDir = from ? path.posix.dirname(from.replace(/\\/g, '/')) : '';
16
+ const resolved = path.posix.normalize(path.posix.join(fromDir, to));
17
+
18
+ if (resolved.startsWith('../')) {
19
+ throw new Error(`Nunjucks path escapes root: from="${from}" to="${to}"`);
20
+ }
21
+
22
+ return resolved;
23
+ }
24
+
25
+ getSource(name) {
26
+ return super.getSource(String(name).replace(/\\/g, '/'));
27
+ }
28
+ }
@@ -0,0 +1,246 @@
1
+ import path from 'node:path';
2
+ import { readdir, readFile } from 'node:fs/promises';
3
+ import { Transform } from 'node:stream';
4
+
5
+ const ENGINE_EXTENSIONS = {
6
+ pug: ['.pug'],
7
+ twig: ['.twig', '.html'],
8
+ nunjucks: ['.njk', '.html']
9
+ };
10
+
11
+ const stripPugComments = content => {
12
+ const lines = [];
13
+ let commentIndent = null;
14
+
15
+ for (const line of content.split(/\r?\n/)) {
16
+ const indent = line.match(/^\s*/)[0].length;
17
+
18
+ if (commentIndent !== null) {
19
+ if (!line.trim() || indent > commentIndent) {
20
+ continue;
21
+ }
22
+
23
+ commentIndent = null;
24
+ }
25
+
26
+ if (line.trimStart().startsWith('//')) {
27
+ commentIndent = indent;
28
+ continue;
29
+ }
30
+
31
+ lines.push(line);
32
+ }
33
+
34
+ return lines.join('\n');
35
+ };
36
+
37
+ const parseReferences = (content, engine) => {
38
+ const references = [];
39
+ let dynamic = false;
40
+
41
+ if (engine === 'pug') {
42
+ const source = stripPugComments(content);
43
+ const tags = source.matchAll(/(?:^|:)[ \t]*(?:include|extends)(?::[\w-]+)?[ \t]+(.+)$/gm);
44
+
45
+ for (const tag of tags) {
46
+ const target = tag[1].trim();
47
+
48
+ if (target.includes('#{') || target.startsWith('@')) {
49
+ dynamic = true;
50
+ } else {
51
+ references.push(target.replace(/^(['"])(.*)\1$/, '$2'));
52
+ }
53
+ }
54
+
55
+ return { references, dynamic };
56
+ }
57
+
58
+ const source = content
59
+ .replace(/{#[\s\S]*?#}/g, '')
60
+ .replace(/{%-?\s*(?:raw|verbatim)\s*-?%}[\s\S]*?{%-?\s*end(?:raw|verbatim)\s*-?%}/g, '');
61
+ const tags = source.matchAll(/{%-?\s*(include|extends|import|from|embed|use)\s+([\s\S]*?)-?%}/g);
62
+
63
+ for (const tag of tags) {
64
+ const expression = tag[2].trim();
65
+ const literal = expression.match(/^(['"])([^'"]+)\1([\s\S]*)$/);
66
+
67
+ // Expressions, fallback lists and concatenated paths cannot be resolved safely.
68
+ if (!literal || !/^(?:\s+(?:with|without|only|ignore|as|import)\b[\s\S]*)?$/.test(literal[3])) {
69
+ dynamic = true;
70
+ continue;
71
+ }
72
+
73
+ if (literal[2].startsWith('@') || literal[2].includes('\\')) {
74
+ dynamic = true;
75
+ continue;
76
+ }
77
+
78
+ references.push(literal[2]);
79
+ }
80
+
81
+ // Twig also supports functional includes and parent templates in expressions.
82
+ if (/\b(?:include|source|extends)\s*\(/.test(source)) {
83
+ dynamic = true;
84
+ }
85
+
86
+ return { references, dynamic };
87
+ };
88
+
89
+ export class TemplateDependencies {
90
+ constructor({ root, engine }) {
91
+ if (!ENGINE_EXTENSIONS[engine]) {
92
+ throw new Error(`Unsupported template engine: ${engine}`);
93
+ }
94
+
95
+ this.root = path.resolve(root);
96
+ this.engine = engine;
97
+ this.extensions = ENGINE_EXTENSIONS[engine];
98
+ this.files = new Map();
99
+ this.parents = new Map();
100
+ this.dynamicFiles = new Set();
101
+ this.initialized = false;
102
+ }
103
+
104
+ resolveReferences(file, reference) {
105
+ const normalized = reference.replace(/\\/g, '/');
106
+ const candidates = new Set();
107
+ const locations = normalized.startsWith('/')
108
+ ? [path.resolve(this.root, `.${normalized}`)]
109
+ : [
110
+ path.resolve(path.dirname(file), normalized),
111
+ path.resolve(this.root, normalized)
112
+ ];
113
+
114
+ for (const location of locations) {
115
+ candidates.add(location);
116
+
117
+ if (this.engine === 'pug' && !path.extname(location)) {
118
+ candidates.add(`${location}.pug`);
119
+ }
120
+ }
121
+
122
+ return candidates;
123
+ }
124
+
125
+ async update(file) {
126
+ let content = null;
127
+
128
+ try {
129
+ content = await readFile(file, 'utf8');
130
+ } catch (error) {
131
+ if (error.code !== 'ENOENT') {
132
+ throw error;
133
+ }
134
+ }
135
+
136
+ const previous = this.files.get(file);
137
+ this.dynamicFiles.delete(file);
138
+
139
+ if (previous) {
140
+ for (const dependency of previous.dependencies) {
141
+ const parents = this.parents.get(dependency);
142
+ parents?.delete(file);
143
+
144
+ if (parents?.size === 0) {
145
+ this.parents.delete(dependency);
146
+ }
147
+ }
148
+ }
149
+
150
+ if (content === null) {
151
+ // Keep incoming edges: parents still reference a deleted partial.
152
+ this.files.delete(file);
153
+ return;
154
+ }
155
+
156
+ const { references, dynamic } = parseReferences(content, this.engine);
157
+ const dependencies = new Set();
158
+
159
+ for (const reference of references) {
160
+ for (const dependency of this.resolveReferences(file, reference)) {
161
+ dependencies.add(dependency);
162
+
163
+ if (!this.parents.has(dependency)) {
164
+ this.parents.set(dependency, new Set());
165
+ }
166
+
167
+ this.parents.get(dependency).add(file);
168
+ }
169
+ }
170
+
171
+ this.files.set(file, { dependencies });
172
+
173
+ if (dynamic) {
174
+ this.dynamicFiles.add(file);
175
+ }
176
+ }
177
+
178
+ async scanDirectory(directory) {
179
+ const entries = await readdir(directory, { withFileTypes: true });
180
+
181
+ for (const entry of entries) {
182
+ const file = path.join(directory, entry.name);
183
+
184
+ if (entry.isDirectory()) {
185
+ await this.scanDirectory(file);
186
+ } else if (entry.isFile() && this.extensions.includes(path.extname(file))) {
187
+ await this.update(file);
188
+ }
189
+ }
190
+ }
191
+
192
+ async scan(changedFiles = []) {
193
+ if (!this.initialized) {
194
+ this.files.clear();
195
+ this.parents.clear();
196
+ this.dynamicFiles.clear();
197
+ await this.scanDirectory(this.root);
198
+ this.initialized = true;
199
+ return null;
200
+ }
201
+
202
+ const changes = Array.isArray(changedFiles) ? changedFiles : [changedFiles];
203
+ const changed = changes.filter(Boolean).map(file => path.resolve(file));
204
+
205
+ if (changed.length === 0) {
206
+ return null;
207
+ }
208
+
209
+ const hadDynamicReferences = this.dynamicFiles.size > 0;
210
+
211
+ for (const file of changed) {
212
+ await this.update(file);
213
+ }
214
+
215
+ if (hadDynamicReferences || this.dynamicFiles.size > 0) {
216
+ return null;
217
+ }
218
+
219
+ const affected = new Set(changed);
220
+ const queue = [...changed];
221
+
222
+ for (let index = 0; index < queue.length; index += 1) {
223
+ for (const parent of this.parents.get(queue[index]) || []) {
224
+ if (!affected.has(parent)) {
225
+ affected.add(parent);
226
+ queue.push(parent);
227
+ }
228
+ }
229
+ }
230
+
231
+ return affected;
232
+ }
233
+
234
+ filter(affected = null) {
235
+ return new Transform({
236
+ objectMode: true,
237
+ transform(file, encoding, callback) {
238
+ if (affected === null || affected.has(path.resolve(file.path))) {
239
+ callback(null, file);
240
+ } else {
241
+ callback();
242
+ }
243
+ }
244
+ });
245
+ }
246
+ }
@@ -0,0 +1,172 @@
1
+ import path from 'path';
2
+ import { fileURLToPath, pathToFileURL } from 'url';
3
+ const dirname = path.dirname(fileURLToPath(import.meta.url));
4
+ import gulp from 'gulp';
5
+ import fs from 'fs';
6
+ import * as config from '../config.js';
7
+ import { $, browser, notifyErr } from '../helper.js';
8
+ import { TemplateDependencies } from './plugins/template-dependencies.js';
9
+ import generateStaticPath from './plugins/generate-static-path.js';
10
+ import nunjucksResolveRelativeIncludes from './plugins/nunjucks-relative-paths-includes.js';
11
+ import RelativeFileSystemLoader from './plugins/nunjucks-relative-system-loader.js';
12
+ import dataModule from './data.js';
13
+ import userConfig from '../../user.config.js';
14
+ import { emailPath, isProduction, templatePath } from '../config.js';
15
+ const { src, dest } = gulp;
16
+ const {
17
+ emailsBuild,
18
+ templateEngine,
19
+ templateLocals,
20
+ prettify,
21
+ htmlMinify,
22
+ sourceFolder
23
+ } = userConfig;
24
+ const { dataParser } = dataModule;
25
+ const dependencies = new TemplateDependencies({
26
+ root: sourceFolder,
27
+ engine: templateEngine
28
+ });
29
+
30
+ const getConfig = async () => {
31
+ const configPath = pathToFileURL(
32
+ path.resolve(dirname, '../..', sourceFolder, 'tmplConfig.js')
33
+ );
34
+
35
+ configPath.searchParams.set('t', Date.now().toString());
36
+ const configModule = await import(configPath.href);
37
+ return configModule.default(templateLocals);
38
+ };
39
+
40
+ const createDependencies = () => {
41
+ const patterns = [];
42
+
43
+ if (isProduction) {
44
+ templateLocals.version = '?ver' + Math.floor(Date.now() / 1000);
45
+ }
46
+
47
+ if (templateLocals.symbolsInject) {
48
+ patterns.push({
49
+ match: '%symbols%',
50
+ replacement: (() => fs.readFileSync(`${config.imagesPath.dist}/symbols.svg`, 'utf8'))
51
+ });
52
+ } else {
53
+ patterns.push({
54
+ match: '%symbols%',
55
+ replacement: ''
56
+ });
57
+ }
58
+
59
+ return {
60
+ patterns
61
+ };
62
+ };
63
+
64
+ const { patterns } = createDependencies();
65
+
66
+ const createTemplateTasks = () => {
67
+ const tasks = {
68
+ templateCompile: () => {
69
+ const changedFiles = global.templateChangedFiles || [];
70
+ const forceFull = isProduction || global.disableTemplateIncremental;
71
+
72
+ return new Promise((resolve, reject) => {
73
+ const scan = isProduction
74
+ ? Promise.resolve(null)
75
+ : dependencies.scan(changedFiles);
76
+
77
+ scan
78
+ .then(affected => tasks.task(resolve, reject, forceFull ? null : affected))
79
+ .catch(reject);
80
+ });
81
+ },
82
+
83
+ templateRecompileAll: () => {
84
+ return new Promise((resolve, reject) => {
85
+ tasks.task(resolve, reject).catch(reject);
86
+ });
87
+ },
88
+
89
+ emailsCompile: (cb) => {
90
+ if (emailsBuild) {
91
+ return src(emailPath.filesSrc)
92
+ .pipe($.plumber(notifyErr()))
93
+ .pipe($.mjml())
94
+ .pipe($.htmlBeautify(prettify))
95
+ .pipe(dest(emailPath.dist));
96
+ }
97
+
98
+ return cb();
99
+ },
100
+
101
+ task: async (resolve = () => {}, reject = () => {}, affected = null) => {
102
+ const tmpConfigData = await getConfig();
103
+ const templateData = dataParser();
104
+
105
+ return src(templatePath.src)
106
+ .pipe($.plumber(notifyErr()))
107
+ .pipe(dependencies.filter(affected))
108
+ .pipe($.if(!isProduction, $.debug()))
109
+ .pipe($.data(() => ({
110
+ ...templateLocals,
111
+ ...templateData,
112
+ ...tmpConfigData,
113
+ alias: (p) => p.replace(/^@/, sourceFolder + '/')
114
+ })))
115
+ .pipe($.if(
116
+ templateEngine === 'nunjucks',
117
+ nunjucksResolveRelativeIncludes({ root: sourceFolder })
118
+ ))
119
+ .pipe(
120
+ $.if(
121
+ templateEngine === 'pug',
122
+ $.pug({
123
+ pretty: !isProduction
124
+ }).on('error', () => browser.notify('<strong>FAIL</strong> Pug')),
125
+
126
+ $.if(
127
+ templateEngine === 'twig',
128
+ $.twig({
129
+ base: sourceFolder
130
+ }).on('error', () => browser.notify('<strong>FAIL</strong> Twig')),
131
+
132
+ $.nunjucksRender({
133
+ loaders: [new RelativeFileSystemLoader(sourceFolder)]
134
+ }).on('error', () => browser.notify('<strong>FAIL</strong> Nunjucks'))
135
+ )
136
+ )
137
+ )
138
+ .pipe($.replaceTask({
139
+ patterns: patterns,
140
+ usePrefix: false
141
+ }))
142
+ .pipe($.if(templateEngine === 'twig', $.rename((p) => {
143
+ const pathObj = p;
144
+
145
+ pathObj.basename = p.basename.replace(/\.html$/i, '');
146
+ pathObj.extname = '.html';
147
+ })))
148
+ .pipe(generateStaticPath())
149
+ .pipe($.htmlBeautify(prettify))
150
+ .pipe($.if(htmlMinify && isProduction, $.htmlmin({
151
+ removeComments: true,
152
+ collapseWhitespace: true,
153
+ collapseBooleanAttributes: true,
154
+ removeAttributeQuotes: true,
155
+ removeRedundantAttributes: false,
156
+ removeEmptyAttributes: true,
157
+ removeScriptTypeAttributes: true,
158
+ removeStyleLinkTypeAttributes: true,
159
+ removeOptionalTags: true
160
+ })))
161
+ .pipe(dest(templatePath.dist))
162
+ .on('end', resolve)
163
+ .on('error', reject);
164
+ }
165
+ };
166
+
167
+ return tasks;
168
+ };
169
+
170
+ const templateTasks = createTemplateTasks();
171
+
172
+ export default templateTasks;