create-o2s-app 4.1.9 → 4.1.11

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 (45) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/scaffold/clone.js +2 -2
  3. package/dist/scaffold/get-aliases-to-remove.d.ts +9 -0
  4. package/dist/scaffold/get-aliases-to-remove.d.ts.map +1 -0
  5. package/dist/scaffold/get-aliases-to-remove.js +21 -0
  6. package/dist/scaffold/get-aliases-to-remove.spec.d.ts +2 -0
  7. package/dist/scaffold/get-aliases-to-remove.spec.d.ts.map +1 -0
  8. package/dist/scaffold/get-aliases-to-remove.spec.js +26 -0
  9. package/dist/scaffold/index.d.ts.map +1 -1
  10. package/dist/scaffold/index.js +2 -0
  11. package/dist/scaffold/transform-app-module.d.ts.map +1 -1
  12. package/dist/scaffold/transform-app-module.js +4 -15
  13. package/dist/scaffold/transform-blocks-config.d.ts +7 -0
  14. package/dist/scaffold/transform-blocks-config.d.ts.map +1 -0
  15. package/dist/scaffold/transform-blocks-config.js +134 -0
  16. package/dist/scaffold/transform-blocks-config.spec.d.ts +2 -0
  17. package/dist/scaffold/transform-blocks-config.spec.d.ts.map +1 -0
  18. package/dist/scaffold/transform-blocks-config.spec.js +190 -0
  19. package/dist/scaffold/transform-legacy-block-files.spec.d.ts +2 -0
  20. package/dist/scaffold/transform-legacy-block-files.spec.d.ts.map +1 -0
  21. package/dist/scaffold/transform-legacy-block-files.spec.js +89 -0
  22. package/dist/scaffold/transform-page-model.d.ts.map +1 -1
  23. package/dist/scaffold/transform-page-model.js +4 -15
  24. package/dist/scaffold/transform-real-files.spec.d.ts +2 -0
  25. package/dist/scaffold/transform-real-files.spec.d.ts.map +1 -0
  26. package/dist/scaffold/transform-real-files.spec.js +154 -0
  27. package/dist/scaffold/transform-render-blocks.d.ts.map +1 -1
  28. package/dist/scaffold/transform-render-blocks.js +63 -17
  29. package/dist/scaffold/transform-render-blocks.spec.d.ts +2 -0
  30. package/dist/scaffold/transform-render-blocks.spec.d.ts.map +1 -0
  31. package/dist/scaffold/transform-render-blocks.spec.js +126 -0
  32. package/package.json +8 -6
  33. package/src/scaffold/clone.ts +1 -1
  34. package/src/scaffold/get-aliases-to-remove.spec.ts +30 -0
  35. package/src/scaffold/get-aliases-to-remove.ts +19 -0
  36. package/src/scaffold/index.ts +2 -0
  37. package/src/scaffold/transform-app-module.ts +4 -16
  38. package/src/scaffold/transform-blocks-config.spec.ts +215 -0
  39. package/src/scaffold/transform-blocks-config.ts +113 -0
  40. package/src/scaffold/transform-legacy-block-files.spec.ts +68 -0
  41. package/src/scaffold/transform-page-model.ts +4 -16
  42. package/src/scaffold/transform-real-files.spec.ts +153 -0
  43. package/src/scaffold/transform-render-blocks.spec.ts +129 -0
  44. package/src/scaffold/transform-render-blocks.ts +73 -18
  45. package/vitest.config.mjs +3 -0
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.transformPageModel = void 0;
37
+ const get_aliases_to_remove_1 = require("./get-aliases-to-remove");
37
38
  const fs = __importStar(require("fs-extra"));
38
39
  const path = __importStar(require("path"));
39
40
  const FILE_PATH = 'apps/api-harmonization/src/modules/page/page.model.ts';
@@ -41,27 +42,15 @@ const FILE_PATH = 'apps/api-harmonization/src/modules/page/page.model.ts';
41
42
  const BLOCK_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api-harmonization';$/;
42
43
  // Regex matches: | Alias.Model.SomeTypenameBlock['__typename']
43
44
  const UNION_TYPE_REGEX = /^\s+\| (\w+)\.Model\.\w+\['__typename'\]/;
45
+ // TODO: remove this transform once `create-o2s-app/base` registers blocks in
46
+ // `apps/api-harmonization/src/blocks.config.ts` (handled by `transform-blocks-config.ts`).
44
47
  const transformPageModel = async (projectDir, selectedBlockNames) => {
45
48
  const filePath = path.join(projectDir, FILE_PATH);
46
49
  if (!(await fs.pathExists(filePath)))
47
50
  return;
48
51
  const content = await fs.readFile(filePath, 'utf-8');
49
52
  const lines = content.split('\n');
50
- // Discover alias → blockName map from the actual file
51
- const aliasToBlock = new Map();
52
- for (const line of lines) {
53
- const match = line.match(BLOCK_IMPORT_REGEX);
54
- if (match && match[1] && match[2]) {
55
- aliasToBlock.set(match[1], match[2]); // alias → blockName
56
- }
57
- }
58
- // Build set of aliases for blocks the user did NOT select
59
- const aliasesToRemove = new Set();
60
- for (const [alias, blockName] of aliasToBlock.entries()) {
61
- if (!selectedBlockNames.includes(blockName)) {
62
- aliasesToRemove.add(alias);
63
- }
64
- }
53
+ const aliasesToRemove = (0, get_aliases_to_remove_1.getAliasesToRemove)(lines, BLOCK_IMPORT_REGEX, selectedBlockNames);
65
54
  if (aliasesToRemove.size === 0)
66
55
  return;
67
56
  const filteredLines = lines.filter((line) => {
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transform-real-files.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-real-files.spec.d.ts","sourceRoot":"","sources":["../../src/scaffold/transform-real-files.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const transform_blocks_config_1 = require("./transform-blocks-config");
37
+ const transform_render_blocks_1 = require("./transform-render-blocks");
38
+ const fs = __importStar(require("fs-extra"));
39
+ const os = __importStar(require("os"));
40
+ const path = __importStar(require("path"));
41
+ const ts = __importStar(require("typescript"));
42
+ const vitest_1 = require("vitest");
43
+ /**
44
+ * Runs the transforms on the real files from this repository, so a change in their format
45
+ * (e.g. a new type annotation) fails here instead of breaking scaffolded projects.
46
+ */
47
+ const REPO_ROOT = path.resolve(__dirname, '../../../../..');
48
+ const BLOCKS_CONFIG_PATH = 'apps/api-harmonization/src/blocks.config.ts';
49
+ const RENDER_BLOCKS_PATH = 'apps/frontend/src/blocks/renderBlocks.tsx';
50
+ const API_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api-harmonization';$/;
51
+ const FRONTEND_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/frontend';$/;
52
+ const NAMED_IMPORT_REGEX = /^import \{([^}]+)\} from '[^']+';$/;
53
+ const IDENTIFIER_REGEX = /\b[A-Za-z_$][\w$]*\b/g;
54
+ const discoverBlocks = (content, importRegex) => {
55
+ const blocks = new Map(); // blockName → alias
56
+ for (const line of content.split('\n')) {
57
+ const match = line.match(importRegex);
58
+ if (match && match[1] && match[2])
59
+ blocks.set(match[2], match[1]);
60
+ }
61
+ return blocks;
62
+ };
63
+ const identifiers = (lines) => new Set(lines.flatMap((line) => line.match(IDENTIFIER_REGEX) ?? []));
64
+ const namedImports = (lines) => lines.flatMap((line) => {
65
+ const match = line.match(NAMED_IMPORT_REGEX);
66
+ return match && match[1]
67
+ ? match[1].split(',').map((specifier) => specifier
68
+ .split(/\s+as\s+/)
69
+ .pop()
70
+ ?.trim() ?? '')
71
+ : [];
72
+ });
73
+ const syntaxErrors = (content, fileName) => (ts.transpileModule(content, {
74
+ fileName,
75
+ reportDiagnostics: true,
76
+ compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext },
77
+ }).diagnostics ?? []).map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
78
+ /** Block selections to check: none, all, each block alone, all but each block, and alternating halves. */
79
+ const selectionsFor = (blockNames) => [
80
+ ['no blocks', []],
81
+ ['all blocks', blockNames],
82
+ ...blockNames.map((name) => [`only ${name}`, [name]]),
83
+ ...blockNames.map((name) => [`all but ${name}`, blockNames.filter((other) => other !== name)]),
84
+ ['even blocks', blockNames.filter((_, index) => index % 2 === 0)],
85
+ ['odd blocks', blockNames.filter((_, index) => index % 2 === 1)],
86
+ ];
87
+ (0, vitest_1.describe)('transforms on the real repository files', () => {
88
+ let projectDir;
89
+ (0, vitest_1.beforeEach)(async () => {
90
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'create-o2s-app-real-files-'));
91
+ });
92
+ (0, vitest_1.afterEach)(async () => {
93
+ await fs.remove(projectDir);
94
+ });
95
+ (0, vitest_1.describe)(BLOCKS_CONFIG_PATH, async () => {
96
+ const original = await fs.readFile(path.join(REPO_ROOT, BLOCKS_CONFIG_PATH), 'utf-8');
97
+ const blocks = discoverBlocks(original, API_IMPORT_REGEX);
98
+ (0, vitest_1.it)('discovers the blocks registered in the file', () => {
99
+ (0, vitest_1.expect)(blocks.size).toBeGreaterThan(0);
100
+ });
101
+ vitest_1.it.each(selectionsFor([...blocks.keys()]))('%s', async (_, selected) => {
102
+ await fs.outputFile(path.join(projectDir, BLOCKS_CONFIG_PATH), original, 'utf-8');
103
+ await (0, transform_blocks_config_1.transformBlocksConfig)(projectDir, selected);
104
+ const result = await fs.readFile(path.join(projectDir, BLOCKS_CONFIG_PATH), 'utf-8');
105
+ const lines = result.split('\n');
106
+ const used = identifiers(lines);
107
+ for (const [blockName, alias] of blocks) {
108
+ if (selected.includes(blockName)) {
109
+ (0, vitest_1.expect)(result).toContain(`import * as ${alias} from '@o2s/blocks.${blockName}/api-harmonization';`);
110
+ (0, vitest_1.expect)(lines).toContain(` ${alias},`);
111
+ (0, vitest_1.expect)(result).toMatch(new RegExp(`^\\s+\\| ${alias}\\.Model\\.`, 'm'));
112
+ }
113
+ else {
114
+ (0, vitest_1.expect)(result).not.toContain(`'@o2s/blocks.${blockName}/`);
115
+ (0, vitest_1.expect)(used.has(alias)).toBe(false);
116
+ }
117
+ }
118
+ (0, vitest_1.expect)(syntaxErrors(result, 'blocks.config.ts')).toEqual([]);
119
+ });
120
+ });
121
+ (0, vitest_1.describe)(RENDER_BLOCKS_PATH, async () => {
122
+ const original = await fs.readFile(path.join(REPO_ROOT, RENDER_BLOCKS_PATH), 'utf-8');
123
+ const blocks = discoverBlocks(original, FRONTEND_IMPORT_REGEX);
124
+ const originalLines = original.split('\n');
125
+ const originallyUnused = new Set(namedImports(originalLines).filter((name) => !identifiers(originalLines.filter((line) => !NAMED_IMPORT_REGEX.test(line))).has(name)));
126
+ (0, vitest_1.it)('discovers the blocks registered in the file', () => {
127
+ (0, vitest_1.expect)(blocks.size).toBeGreaterThan(0);
128
+ });
129
+ vitest_1.it.each(selectionsFor([...blocks.keys()]))('%s', async (_, selected) => {
130
+ await fs.outputFile(path.join(projectDir, RENDER_BLOCKS_PATH), original, 'utf-8');
131
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, selected);
132
+ const result = await fs.readFile(path.join(projectDir, RENDER_BLOCKS_PATH), 'utf-8');
133
+ const lines = result.split('\n');
134
+ const usedOutsideImports = identifiers(lines.filter((line) => !NAMED_IMPORT_REGEX.test(line)));
135
+ for (const [blockName, alias] of blocks) {
136
+ if (selected.includes(blockName)) {
137
+ (0, vitest_1.expect)(result).toContain(`import * as ${alias} from '@o2s/blocks.${blockName}/frontend';`);
138
+ (0, vitest_1.expect)(result).toContain(`<${alias}.Renderer`);
139
+ }
140
+ else {
141
+ (0, vitest_1.expect)(result).not.toContain(`'@o2s/blocks.${blockName}/`);
142
+ (0, vitest_1.expect)(usedOutsideImports.has(alias)).toBe(false);
143
+ }
144
+ }
145
+ // No named import is left unused by the transform (e.g. onSignOut without user-account).
146
+ for (const name of namedImports(lines)) {
147
+ if (!originallyUnused.has(name))
148
+ (0, vitest_1.expect)(usedOutsideImports.has(name)).toBe(true);
149
+ }
150
+ (0, vitest_1.expect)(result).not.toMatch(/\n\n\n/);
151
+ (0, vitest_1.expect)(syntaxErrors(result, 'renderBlocks.tsx')).toEqual([]);
152
+ });
153
+ });
154
+ });
@@ -1 +1 @@
1
- {"version":3,"file":"transform-render-blocks.d.ts","sourceRoot":"","sources":["../../src/scaffold/transform-render-blocks.ts"],"names":[],"mappings":"AAWA,eAAO,MAAM,qBAAqB,eAAsB,MAAM,sBAAsB,MAAM,EAAE,KAAG,OAAO,CAAC,IAAI,CAkD1G,CAAC"}
1
+ {"version":3,"file":"transform-render-blocks.d.ts","sourceRoot":"","sources":["../../src/scaffold/transform-render-blocks.ts"],"names":[],"mappings":"AA4EA,eAAO,MAAM,qBAAqB,eAAsB,MAAM,sBAAsB,MAAM,EAAE,KAAG,OAAO,CAAC,IAAI,CAwC1G,CAAC"}
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.transformRenderBlocks = void 0;
37
+ const get_aliases_to_remove_1 = require("./get-aliases-to-remove");
37
38
  const fs = __importStar(require("fs-extra"));
38
39
  const path = __importStar(require("path"));
39
40
  const FILE_PATH = 'apps/frontend/src/blocks/renderBlocks.tsx';
@@ -41,31 +42,72 @@ const FILE_PATH = 'apps/frontend/src/blocks/renderBlocks.tsx';
41
42
  const BLOCK_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/frontend';$/;
42
43
  // Regex matches: SomeBlock: (blockProps) => <Alias.Renderer ...
43
44
  const REGISTRY_ENTRY_REGEX = /^\s+\w+:\s*\(blockProps\)\s*=>\s*<(\w+)\.Renderer/;
45
+ // Regex matches a single-line named import: import { a, b as c } from '...';
46
+ const NAMED_IMPORT_REGEX = /^import \{([^}]+)\} from '([^']+)';$/;
47
+ const IDENTIFIER_REGEX = /\b[A-Za-z_$][\w$]*\b/g;
48
+ /**
49
+ * Removes named imports that were only used by the removed registry entries
50
+ * (e.g. `onSignOut`, passed only to the user-account block), so the generated
51
+ * file passes `no-unused-vars`. Imports unrelated to removed entries are left untouched.
52
+ */
53
+ const removeImportsOrphanedByRemovedEntries = (lines, removedEntries) => {
54
+ const candidates = new Set(removedEntries.flatMap((entry) => entry.match(IDENTIFIER_REGEX) ?? []));
55
+ if (candidates.size === 0)
56
+ return lines;
57
+ // Identifiers still referenced outside the named imports (no dynamic RegExp needed)
58
+ const usedIdentifiers = new Set(lines.filter((line) => !NAMED_IMPORT_REGEX.test(line)).flatMap((line) => line.match(IDENTIFIER_REGEX) ?? []));
59
+ const isUsed = (identifier) => usedIdentifiers.has(identifier);
60
+ const result = [];
61
+ // Set when an import line is dropped right after a blank line, so the blank line that
62
+ // separated it from the next import group is dropped too (no double blank lines).
63
+ let skipNextBlankLine = false;
64
+ for (const line of lines) {
65
+ const match = line.match(NAMED_IMPORT_REGEX);
66
+ if (!match || !match[1]) {
67
+ if (skipNextBlankLine && line.trim() === '') {
68
+ skipNextBlankLine = false;
69
+ continue;
70
+ }
71
+ skipNextBlankLine = false;
72
+ result.push(line);
73
+ continue;
74
+ }
75
+ skipNextBlankLine = false;
76
+ const specifiers = match[1]
77
+ .split(',')
78
+ .map((specifier) => specifier.trim())
79
+ .filter(Boolean);
80
+ const kept = specifiers.filter((specifier) => {
81
+ const local = specifier
82
+ .split(/\s+as\s+/)
83
+ .pop()
84
+ ?.trim() ?? specifier;
85
+ return !candidates.has(local) || isUsed(local);
86
+ });
87
+ if (kept.length === specifiers.length) {
88
+ result.push(line);
89
+ }
90
+ else if (kept.length > 0) {
91
+ result.push(`import { ${kept.join(', ')} } from '${match[2]}';`);
92
+ }
93
+ else {
94
+ skipNextBlankLine = result.length === 0 || result[result.length - 1]?.trim() === '';
95
+ }
96
+ }
97
+ return result;
98
+ };
44
99
  const transformRenderBlocks = async (projectDir, selectedBlockNames) => {
45
100
  const filePath = path.join(projectDir, FILE_PATH);
46
101
  if (!(await fs.pathExists(filePath)))
47
102
  return;
48
103
  const content = await fs.readFile(filePath, 'utf-8');
49
104
  const lines = content.split('\n');
50
- // Discover alias → blockName map from the actual file
51
- const aliasToBlock = new Map();
52
- for (const line of lines) {
53
- const match = line.match(BLOCK_IMPORT_REGEX);
54
- if (match && match[1] && match[2]) {
55
- aliasToBlock.set(match[1], match[2]); // alias → blockName
56
- }
57
- }
58
- // Build set of aliases for blocks the user did NOT select
59
- const aliasesToRemove = new Set();
60
- for (const [alias, blockName] of aliasToBlock.entries()) {
61
- if (!selectedBlockNames.includes(blockName)) {
62
- aliasesToRemove.add(alias);
63
- }
64
- }
105
+ const aliasesToRemove = (0, get_aliases_to_remove_1.getAliasesToRemove)(lines, BLOCK_IMPORT_REGEX, selectedBlockNames);
65
106
  if (aliasesToRemove.size === 0)
66
107
  return;
67
108
  // Process line by line
68
109
  const result = [];
110
+ const removedEntries = [];
69
111
  for (let i = 0; i < lines.length; i++) {
70
112
  const line = lines[i];
71
113
  if (line === undefined)
@@ -75,13 +117,17 @@ const transformRenderBlocks = async (projectDir, selectedBlockNames) => {
75
117
  if (importMatch && importMatch[1] && aliasesToRemove.has(importMatch[1])) {
76
118
  continue;
77
119
  }
78
- // Remove BLOCK_REGISTRY entries for unselected blocks
120
+ // Remove BLOCK_REGISTRY entries for unselected blocks.
121
+ // Assumes every entry fits on a single line (true today). If prettier ever wraps an entry,
122
+ // identifiers on the following lines (e.g. `onSignOut={onSignOut}`) are not collected here;
123
+ // the real-file tests in transform-real-files.spec.ts would then fail.
79
124
  const registryMatch = line.match(REGISTRY_ENTRY_REGEX);
80
125
  if (registryMatch && registryMatch[1] && aliasesToRemove.has(registryMatch[1])) {
126
+ removedEntries.push(line);
81
127
  continue;
82
128
  }
83
129
  result.push(line);
84
130
  }
85
- await fs.writeFile(filePath, result.join('\n'), 'utf-8');
131
+ await fs.writeFile(filePath, removeImportsOrphanedByRemovedEntries(result, removedEntries).join('\n'), 'utf-8');
86
132
  };
87
133
  exports.transformRenderBlocks = transformRenderBlocks;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=transform-render-blocks.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transform-render-blocks.spec.d.ts","sourceRoot":"","sources":["../../src/scaffold/transform-render-blocks.spec.ts"],"names":[],"mappings":""}
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ const transform_render_blocks_1 = require("./transform-render-blocks");
37
+ const fs = __importStar(require("fs-extra"));
38
+ const os = __importStar(require("os"));
39
+ const path = __importStar(require("path"));
40
+ const vitest_1 = require("vitest");
41
+ const FILE_PATH = 'apps/frontend/src/blocks/renderBlocks.tsx';
42
+ const RENDER_BLOCKS = `import * as Faq from '@o2s/blocks.faq/frontend';
43
+ import * as TicketList from '@o2s/blocks.ticket-list/frontend';
44
+ import * as UserAccount from '@o2s/blocks.user-account/frontend';
45
+ // BLOCK IMPORT
46
+ import { CMS, Models } from '@o2s/framework/modules';
47
+
48
+ import { auth } from '@/auth';
49
+
50
+ import { routing } from '@/i18n';
51
+
52
+ import { onSignOut } from '../actions/signOut';
53
+
54
+ type BlockProps = Models.BlockProps.FullBlockProps<typeof routing>;
55
+
56
+ export const renderBlocks = async (blocks: CMS.Model.Page.SlotBlock[]) => {
57
+ const session = await auth();
58
+ return blocks.map((block) => BLOCK_REGISTRY[block.__typename]({ ...block, session }));
59
+ };
60
+
61
+ const BLOCK_REGISTRY = {
62
+ FaqBlock: (blockProps) => <Faq.Renderer {...blockProps} />,
63
+ TicketListBlock: (blockProps) => <TicketList.Renderer {...blockProps} />,
64
+ UserAccountBlock: (blockProps) => <UserAccount.Renderer {...blockProps} onSignOut={onSignOut} />,
65
+ // BLOCK REGISTER
66
+ };
67
+ `;
68
+ (0, vitest_1.describe)('transformRenderBlocks', () => {
69
+ let projectDir;
70
+ const writeFile = async (content) => {
71
+ await fs.outputFile(path.join(projectDir, FILE_PATH), content, 'utf-8');
72
+ };
73
+ const readFile = () => fs.readFile(path.join(projectDir, FILE_PATH), 'utf-8');
74
+ (0, vitest_1.beforeEach)(async () => {
75
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'create-o2s-app-render-blocks-'));
76
+ });
77
+ (0, vitest_1.afterEach)(async () => {
78
+ await fs.remove(projectDir);
79
+ });
80
+ (0, vitest_1.it)('removes the import and registry entry of unselected blocks', async () => {
81
+ await writeFile(RENDER_BLOCKS);
82
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq', 'user-account']);
83
+ const result = await readFile();
84
+ (0, vitest_1.expect)(result).not.toContain('@o2s/blocks.ticket-list/frontend');
85
+ (0, vitest_1.expect)(result).not.toContain('TicketListBlock');
86
+ (0, vitest_1.expect)(result).toContain("import * as Faq from '@o2s/blocks.faq/frontend';");
87
+ (0, vitest_1.expect)(result).toContain('UserAccountBlock');
88
+ });
89
+ (0, vitest_1.it)('keeps onSignOut while the user-account block is selected', async () => {
90
+ await writeFile(RENDER_BLOCKS);
91
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq', 'user-account']);
92
+ (0, vitest_1.expect)(await readFile()).toContain("import { onSignOut } from '../actions/signOut';");
93
+ });
94
+ (0, vitest_1.it)('removes onSignOut together with the user-account block without leaving a double blank line', async () => {
95
+ await writeFile(RENDER_BLOCKS);
96
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq', 'ticket-list']);
97
+ const result = await readFile();
98
+ (0, vitest_1.expect)(result).not.toContain('onSignOut');
99
+ (0, vitest_1.expect)(result).not.toContain('UserAccount');
100
+ (0, vitest_1.expect)(result).toContain("import { routing } from '@/i18n';\n\ntype BlockProps");
101
+ (0, vitest_1.expect)(result).not.toMatch(/\n\n\n/);
102
+ });
103
+ (0, vitest_1.it)('does not remove imports that are still used elsewhere in the file', async () => {
104
+ await writeFile(RENDER_BLOCKS.replace('const session = await auth();', 'const session = await auth();\n void onSignOut;'));
105
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq']);
106
+ (0, vitest_1.expect)(await readFile()).toContain("import { onSignOut } from '../actions/signOut';");
107
+ });
108
+ (0, vitest_1.it)('removes only the orphaned specifier from a multi-specifier import', async () => {
109
+ await writeFile(RENDER_BLOCKS.replace("import { onSignOut } from '../actions/signOut';", "import { onSignOut, signOutLabel } from '../actions/signOut';").replace('const session = await auth();', 'const session = await auth();\n void signOutLabel;'));
110
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq']);
111
+ (0, vitest_1.expect)(await readFile()).toContain("import { signOutLabel } from '../actions/signOut';");
112
+ });
113
+ (0, vitest_1.it)('does not touch unrelated imports', async () => {
114
+ await writeFile(RENDER_BLOCKS);
115
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq', 'ticket-list']);
116
+ const result = await readFile();
117
+ (0, vitest_1.expect)(result).toContain("import { CMS, Models } from '@o2s/framework/modules';");
118
+ (0, vitest_1.expect)(result).toContain("import { auth } from '@/auth';");
119
+ (0, vitest_1.expect)(result).toContain("import { routing } from '@/i18n';");
120
+ });
121
+ (0, vitest_1.it)('leaves the file untouched when every block is selected', async () => {
122
+ await writeFile(RENDER_BLOCKS);
123
+ await (0, transform_render_blocks_1.transformRenderBlocks)(projectDir, ['faq', 'ticket-list', 'user-account']);
124
+ (0, vitest_1.expect)(await readFile()).toBe(RENDER_BLOCKS);
125
+ });
126
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-o2s-app",
3
- "version": "4.1.9",
3
+ "version": "4.1.11",
4
4
  "private": false,
5
5
  "license": "MIT",
6
6
  "description": "CLI tool to scaffold new O2S applications with Next.js and NestJS setup.",
@@ -29,17 +29,18 @@
29
29
  "create-o2s-app": "ts-node ./src/index.ts",
30
30
  "build": "tsc7 --preserveWatchOutput && tsc-alias",
31
31
  "lint": "tsc --noEmit && eslint . --max-warnings=0",
32
+ "test": "vitest run",
32
33
  "format": "prettier --write \"src/**/*.{js,jsx,ts,tsx,css,scss,json}\""
33
34
  },
34
35
  "dependencies": {
35
- "@o2s/telemetry": "^1.2.3",
36
+ "@o2s/telemetry": "^1.2.4",
36
37
  "@types/prompts": "^2.4.9",
37
38
  "cli-progress": "^3.12.0",
38
- "commander": "^15.0.0",
39
- "fs-extra": "^11.4.0",
39
+ "commander": "^15.1.0",
40
+ "fs-extra": "^11.4.1",
40
41
  "kleur": "^4.1.5",
41
42
  "prompts": "^2.4.2",
42
- "simple-git": "^3.36.0",
43
+ "simple-git": "^4.1.0",
43
44
  "ts-node": "^10.9.2"
44
45
  },
45
46
  "devDependencies": {
@@ -47,10 +48,11 @@
47
48
  "@o2s/lint-staged-config": "*",
48
49
  "@o2s/prettier-config": "*",
49
50
  "@o2s/typescript-config": "*",
51
+ "@o2s/vitest-config": "*",
50
52
  "@types/cli-progress": "^3.11.6",
51
53
  "@types/fs-extra": "^11.0.4",
52
54
  "eslint": "^9.39.5",
53
- "prettier": "^3.9.6",
55
+ "prettier": "^3.10.1",
54
56
  "typescript": "^6.0.3"
55
57
  }
56
58
  }
@@ -3,7 +3,7 @@ import cliProgress from 'cli-progress';
3
3
  import * as fs from 'fs-extra';
4
4
  import * as os from 'os';
5
5
  import * as path from 'path';
6
- import simpleGit from 'simple-git';
6
+ import { simpleGit } from 'simple-git';
7
7
 
8
8
  export const cloneRepository = async (): Promise<string> => {
9
9
  const tempDir = path.join(os.tmpdir(), `openselfservice-${Date.now()}`);
@@ -0,0 +1,30 @@
1
+ import { getAliasesToRemove } from './get-aliases-to-remove';
2
+ import { describe, expect, it } from 'vitest';
3
+
4
+ const IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api-harmonization';$/;
5
+
6
+ const LINES = [
7
+ "import * as ArticleList from '@o2s/blocks.article-list/api-harmonization';",
8
+ "import * as Article from '@o2s/blocks.article/api-harmonization';",
9
+ "import * as CustomFaq from '@o2s/blocks.faq/api-harmonization';",
10
+ "import { Something } from '@o2s/framework/modules';",
11
+ ' Article,',
12
+ ];
13
+
14
+ describe('getAliasesToRemove', () => {
15
+ it('returns the aliases of unselected blocks', () => {
16
+ expect(getAliasesToRemove(LINES, IMPORT_REGEX, ['article'])).toEqual(new Set(['ArticleList', 'CustomFaq']));
17
+ });
18
+
19
+ it('uses the alias from the file, not one derived from the block name', () => {
20
+ expect(getAliasesToRemove(LINES, IMPORT_REGEX, ['article', 'article-list'])).toEqual(new Set(['CustomFaq']));
21
+ });
22
+
23
+ it('returns an empty set when every block is selected', () => {
24
+ expect(getAliasesToRemove(LINES, IMPORT_REGEX, ['article', 'article-list', 'faq']).size).toBe(0);
25
+ });
26
+
27
+ it('ignores lines that do not match the import regex', () => {
28
+ expect(getAliasesToRemove(LINES, IMPORT_REGEX, [])).toEqual(new Set(['ArticleList', 'Article', 'CustomFaq']));
29
+ });
30
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Finds the import aliases of the blocks the user did NOT select.
3
+ *
4
+ * Aliases are discovered from the file itself (handles special aliases), using `importRegex`,
5
+ * which must capture the alias in group 1 and the block name in group 2, e.g.
6
+ * `import * as Alias from '@o2s/blocks.<name>/api-harmonization';`.
7
+ */
8
+ export const getAliasesToRemove = (lines: string[], importRegex: RegExp, selectedBlockNames: string[]): Set<string> => {
9
+ const aliasesToRemove = new Set<string>();
10
+
11
+ for (const line of lines) {
12
+ const match = line.match(importRegex);
13
+ if (match && match[1] && match[2] && !selectedBlockNames.includes(match[2])) {
14
+ aliasesToRemove.add(match[1]);
15
+ }
16
+ }
17
+
18
+ return aliasesToRemove;
19
+ };
@@ -6,6 +6,7 @@ import { cleanPackageLock, installDependencies } from './install';
6
6
  import { warnUnconfiguredModules } from './transform-app-config';
7
7
  import { transformAppModule } from './transform-app-module';
8
8
  import { transformAppsPackageJson } from './transform-apps-package-json';
9
+ import { transformBlocksConfig } from './transform-blocks-config';
9
10
  import { transformIntegrationConfigs } from './transform-integration-configs';
10
11
  import { transformRootPackageJson } from './transform-package-json';
11
12
  import { transformPageModel } from './transform-page-model';
@@ -72,6 +73,7 @@ export const scaffold = async (
72
73
  console.log('Configuring project for selected blocks...');
73
74
  await Promise.all([
74
75
  transformAppModule(targetDir, selectedBlocks),
76
+ transformBlocksConfig(targetDir, selectedBlocks),
75
77
  transformRenderBlocks(targetDir, selectedBlocks),
76
78
  transformPageModel(targetDir, selectedBlocks),
77
79
  transformAppsPackageJson(targetDir, selectedBlocks, selectedIntegrations),
@@ -1,3 +1,4 @@
1
+ import { getAliasesToRemove } from './get-aliases-to-remove';
1
2
  import * as fs from 'fs-extra';
2
3
  import * as path from 'path';
3
4
 
@@ -9,6 +10,8 @@ const BLOCK_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api
9
10
  // Regex matches: Alias.Module.register(AppConfig),
10
11
  const BLOCK_REGISTRATION_REGEX = /^\s+(\w+)\.Module\.register\(AppConfig\),\s*$/;
11
12
 
13
+ // TODO: remove this transform once `create-o2s-app/base` registers blocks in
14
+ // `apps/api-harmonization/src/blocks.config.ts` (handled by `transform-blocks-config.ts`).
12
15
  export const transformAppModule = async (projectDir: string, selectedBlockNames: string[]): Promise<void> => {
13
16
  const filePath = path.join(projectDir, FILE_PATH);
14
17
 
@@ -17,22 +20,7 @@ export const transformAppModule = async (projectDir: string, selectedBlockNames:
17
20
  const content = await fs.readFile(filePath, 'utf-8');
18
21
  const lines = content.split('\n');
19
22
 
20
- // Discover alias → blockName map from the actual file (handles special aliases)
21
- const aliasToBlock = new Map<string, string>();
22
- for (const line of lines) {
23
- const match = line.match(BLOCK_IMPORT_REGEX);
24
- if (match && match[1] && match[2]) {
25
- aliasToBlock.set(match[1], match[2]); // alias → blockName
26
- }
27
- }
28
-
29
- // Build set of aliases for blocks the user did NOT select
30
- const aliasesToRemove = new Set<string>();
31
- for (const [alias, blockName] of aliasToBlock.entries()) {
32
- if (!selectedBlockNames.includes(blockName)) {
33
- aliasesToRemove.add(alias);
34
- }
35
- }
23
+ const aliasesToRemove = getAliasesToRemove(lines, BLOCK_IMPORT_REGEX, selectedBlockNames);
36
24
 
37
25
  if (aliasesToRemove.size === 0) return;
38
26