@rettangoli/fe 0.0.13 → 1.0.0-rc1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,10 +1,10 @@
1
1
  # Rettangoli Frontend
2
2
 
3
- A modern frontend framework that uses YAML for view definitions, web components for composition, and Immer for state management. Build reactive applications with minimal complexity using just 3 types of files.
3
+ A modern frontend framework that uses YAML for view definitions, web components for composition, and Immer for state management. Build reactive applications with minimal complexity using 4 types of files.
4
4
 
5
5
  ## Features
6
6
 
7
- - **🗂️ Three-File Architecture** - `.view.yaml`, `.store.js`, `.handlers.js` files scale from single page to complex applications
7
+ - **🗂️ Four-File Architecture** - `.view.yaml`, `.store.js`, `.handlers.js`, `.schema.yaml` scale from single page to complex applications
8
8
  - **📝 YAML Views** - Declarative UI definitions that compile to virtual DOM
9
9
  - **🧩 Web Components** - Standards-based component architecture
10
10
  - **🔄 Reactive State** - Immer-powered immutable state management
@@ -23,6 +23,7 @@ rtgl fe watch # Start dev server
23
23
 
24
24
  - **[Developer Quickstart](./docs/overview.md)** - Complete introduction and examples
25
25
  - **[View System](./docs/view.md)** - Complete YAML syntax
26
+ - **[Schema System](./docs/schema.md)** - Component API and metadata
26
27
  - **[Store Management](./docs/store.md)** - State patterns
27
28
  - **[Event Handlers](./docs/handlers.md)** - Event handling
28
29
 
@@ -38,7 +39,6 @@ rtgl fe watch # Start dev server
38
39
 
39
40
  **Build & Development:**
40
41
  - [ESBuild](https://esbuild.github.io/) - Fast bundling
41
- - [Vite](https://vite.dev/) - Development server with hot reload
42
42
 
43
43
  **Browser Native:**
44
44
  - Web Components - Component encapsulation
@@ -60,7 +60,7 @@ bun install
60
60
  2. **Create project structure**:
61
61
  ```bash
62
62
  # Scaffold a new component
63
- node ../rettangoli-cli/cli.js fe scaffold --category components --name MyButton
63
+ node ../rettangoli-cli/cli.js fe scaffold --category components --component-name MyButton
64
64
  ```
65
65
 
66
66
  3. **Start development**:
@@ -106,15 +106,31 @@ fe:
106
106
 
107
107
  ## Testing
108
108
 
109
- ### View Components
109
+ ### Unit and Contract Tests
110
110
 
111
- Use visual testing with `rtgl vt`:
111
+ - **Puty contract tests** (`spec/`) — YAML-driven pure-function specs for view, store, schema, and handler contracts.
112
+ - **Vitest integration tests** (`test/`) — runtime behavior tests for component lifecycle, props, events, and DOM.
112
113
 
113
114
  ```bash
114
- rtgl vt generate
115
- rtgl vt report
115
+ bun run test # all tests
116
+ bun run test:puty # contract tests only
117
+ bun run test:vitest # integration tests only
116
118
  ```
117
119
 
120
+ ### End-to-End Testing
121
+
122
+ E2E tests run against real example apps in `examples/` using `@rettangoli/vt`. VT specs define interaction steps (click, write, keypress, etc.) and capture screenshots via Playwright. Assertions are done by comparing candidate screenshots against reference baselines with pixelmatch.
123
+
124
+ ```bash
125
+ # In an example project (e.g. examples/example1/)
126
+ rtgl fe build # build components
127
+ rtgl vt generate # capture screenshots (runs Playwright)
128
+ rtgl vt report # compare against reference — fails on mismatch
129
+ rtgl vt accept # update baselines when changes are intentional
130
+ ```
131
+
132
+ VT specs live in each example's `vt/specs/` directory. See `examples/example1/` for the full setup.
133
+
118
134
  ## Examples
119
135
 
120
136
  For a complete working example, see the todos app in `examples/example1/`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rettangoli/fe",
3
- "version": "0.0.13",
3
+ "version": "1.0.0-rc1",
4
4
  "description": "Frontend framework for building reactive web components",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -25,7 +25,10 @@
25
25
  ".": "./src/index.js",
26
26
  "./cli": "./src/cli/index.js"
27
27
  },
28
- "devDependencies": {},
28
+ "devDependencies": {
29
+ "puty": "^0.1.1",
30
+ "vitest": "^4.0.15"
31
+ },
29
32
  "dependencies": {
30
33
  "esbuild": "^0.25.5",
31
34
  "immer": "^10.1.1",
@@ -36,6 +39,9 @@
36
39
  "vite": "^6.3.5"
37
40
  },
38
41
  "scripts": {
39
- "dev": "node watch.js --watch"
42
+ "dev": "node watch.js --watch",
43
+ "test": "vitest run --reporter=verbose",
44
+ "test:puty": "vitest run puty.spec.js --reporter=verbose",
45
+ "test:vitest": "vitest run test/**/*.test.js --reporter=verbose"
40
46
  }
41
47
  }
@@ -1,8 +1,11 @@
1
+ export const handleBeforeMount = (deps, payload) => {
2
+ //
3
+ }
1
4
 
2
- export const handleOnMount = (deps, event) => {
5
+ export const handleAfterMount = async (deps, payload) => {
3
6
  //
4
7
  }
5
8
 
6
- export const handlerSomeEvent = (deps, event) => {
9
+ export const handleSomeEvent = (deps, payload) => {
7
10
  //
8
11
  }
@@ -0,0 +1,11 @@
1
+ componentName: custom-blank
2
+
3
+ description: Blank component scaffold
4
+
5
+ propsSchema:
6
+ type: object
7
+ properties: {}
8
+
9
+ events: []
10
+
11
+ methods: []
@@ -1,16 +1,5 @@
1
- elementName: custom-blank
2
-
3
- viewDataSchema:
4
- type: object
5
-
6
- propsSchema:
7
- type: object
8
- properties: {}
9
-
10
1
  refs: {}
11
2
 
12
- events: {}
13
-
14
3
  template:
15
4
  - rtgl-view w=f h=f p=md:
16
5
  - rtgl-text s=h2: blank
package/src/cli/build.js CHANGED
@@ -10,29 +10,36 @@ import { load as loadYaml } from "js-yaml";
10
10
  import { parse } from 'jempl';
11
11
  import { extractCategoryAndComponent } from '../commonBuild.js';
12
12
  import { getAllFiles } from '../commonBuild.js';
13
+ import {
14
+ isSupportedComponentFile,
15
+ validateComponentEntries,
16
+ } from "./contracts.js";
13
17
  import path from "node:path";
14
18
 
15
19
  function capitalize(word) {
16
20
  return word ? word[0].toUpperCase() + word.slice(1) : word;
17
21
  }
18
22
 
19
- // Function to process view files - loads YAML and creates temporary JS file
20
- export const writeViewFile = (view, category, component) => {
21
- // const { category, component } = extractCategoryAndComponent(filePath);
22
- const dir = path.join(".temp", category);
23
+ const writeYamlModuleFile = (yamlObject, category, component, fileType, tempDir = path.resolve(process.cwd(), ".temp")) => {
24
+ const dir = path.join(tempDir, category);
23
25
  if (!existsSync(dir)) {
24
26
  mkdirSync(dir, { recursive: true });
25
27
  }
26
28
  writeFileSync(
27
- path.join(dir, `${component}.view.js`),
28
- `export default ${JSON.stringify(view)};`,
29
+ path.join(dir, `${component}.${fileType}.js`),
30
+ `export default ${JSON.stringify(yamlObject)};`,
29
31
  );
30
32
  };
31
33
 
34
+ // Function to process view files - loads YAML and creates temporary JS file
35
+ export const writeViewFile = (view, category, component, tempDir = path.resolve(process.cwd(), ".temp")) => {
36
+ writeYamlModuleFile(view, category, component, "view", tempDir);
37
+ };
38
+
32
39
  export const bundleFile = async (options) => {
33
- const { outfile = "./vt/static/main.js", development = false } = options;
40
+ const { outfile, tempDir, development = false } = options;
34
41
  await esbuild.build({
35
- entryPoints: ["./.temp/dynamicImport.js"],
42
+ entryPoints: [path.join(tempDir, "dynamicImport.js")],
36
43
  bundle: true,
37
44
  minify: !development,
38
45
  sourcemap: !!development,
@@ -48,20 +55,32 @@ export const bundleFile = async (options) => {
48
55
  const buildRettangoliFrontend = async (options) => {
49
56
  console.log("running build with options", options);
50
57
 
51
- const { dirs = ["./example"], outfile = "./vt/static/main.js", setup = "setup.js", development = false } = options;
58
+ const {
59
+ cwd = process.cwd(),
60
+ dirs = ["./example"],
61
+ outfile = "./vt/static/main.js",
62
+ setup = "setup.js",
63
+ development = false
64
+ } = options;
65
+
66
+ // Resolve all paths relative to cwd
67
+ const resolvedDirs = dirs.map(dir => path.resolve(cwd, dir));
68
+ const resolvedSetup = path.resolve(cwd, setup);
69
+ const resolvedOutfile = path.resolve(cwd, outfile);
70
+ const tempDir = path.resolve(cwd, ".temp");
71
+
72
+ // Ensure temp directory exists
73
+ if (!existsSync(tempDir)) {
74
+ mkdirSync(tempDir, { recursive: true });
75
+ }
52
76
 
53
- const allFiles = getAllFiles(dirs).filter((filePath) => {
54
- return (
55
- filePath.endsWith(".store.js") ||
56
- filePath.endsWith(".handlers.js") ||
57
- filePath.endsWith(".view.yaml")
58
- );
59
- });
77
+ const allFiles = getAllFiles(resolvedDirs).filter((filePath) => isSupportedComponentFile(filePath));
60
78
 
61
79
  let output = "";
62
80
 
63
81
  const categories = [];
64
82
  const imports = {};
83
+ const componentContractEntries = [];
65
84
 
66
85
  // unique identifier needed for replacing
67
86
  let count = 10000000000;
@@ -85,42 +104,73 @@ const buildRettangoliFrontend = async (options) => {
85
104
  }
86
105
 
87
106
 
88
- if (["handlers", "store"].includes(fileType)) {
107
+ const componentContractEntry = {
108
+ category,
109
+ component,
110
+ fileType,
111
+ filePath,
112
+ };
113
+
114
+ if (["handlers", "store", "methods"].includes(fileType)) {
115
+ const relativePath = path.relative(tempDir, filePath).replaceAll(path.sep, "/");
89
116
  output += `import * as ${component}${capitalize(
90
117
  fileType,
91
- )} from '../${filePath.replaceAll(path.sep, "/")}';\n`;
118
+ )} from '${relativePath}';\n`;
92
119
 
93
120
  replaceMap[count] = `${component}${capitalize(fileType)}`;
94
121
  imports[category][component][fileType] = count;
95
122
  count++;
96
- } else if (["view"].includes(fileType)) {
97
- const view = loadYaml(readFileSync(filePath, "utf8"));
98
- try {
99
- view.template = parse(view.template);
100
- } catch (error) {
101
- console.error(`Error parsing template in file: ${filePath}`);
102
- throw error;
123
+ } else if (["view", "constants", "schema"].includes(fileType)) {
124
+ const yamlObject = loadYaml(readFileSync(filePath, "utf8")) ?? {};
125
+ componentContractEntry.yamlObject = yamlObject;
126
+ if (fileType === "view") {
127
+ try {
128
+ yamlObject.template = parse(yamlObject.template);
129
+ } catch (error) {
130
+ console.error(`Error parsing template in file: ${filePath}`);
131
+ throw error;
132
+ }
133
+ }
134
+ if (
135
+ fileType === "constants" &&
136
+ (yamlObject === null || typeof yamlObject !== "object" || Array.isArray(yamlObject))
137
+ ) {
138
+ throw new Error(`[Build] ${filePath} must contain a YAML object at the root.`);
103
139
  }
104
- writeViewFile(view, category, component);
140
+
141
+ writeYamlModuleFile(yamlObject, category, component, fileType, tempDir);
105
142
  output += `import ${component}${capitalize(
106
143
  fileType,
107
- )} from './${category}/${component}.view.js';\n`;
144
+ )} from './${category}/${component}.${fileType}.js';\n`;
108
145
  replaceMap[count] = `${component}${capitalize(fileType)}`;
109
146
 
110
147
  imports[category][component][fileType] = count;
111
148
  count++;
112
149
  }
150
+
151
+ componentContractEntries.push(componentContractEntry);
113
152
  }
114
153
 
154
+ validateComponentEntries({
155
+ entries: componentContractEntries,
156
+ errorPrefix: "[Build]",
157
+ });
158
+
159
+ const relativeSetup = path.relative(tempDir, resolvedSetup).replaceAll(path.sep, "/");
115
160
  output += `
116
161
  import { createComponent } from '@rettangoli/fe';
117
- import { deps, patch, h } from '../${setup}';
162
+ import { deps, patch, h } from '${relativeSetup}';
118
163
  const imports = ${JSON.stringify(imports, null, 2)};
119
164
 
120
165
  Object.keys(imports).forEach(category => {
121
166
  Object.keys(imports[category]).forEach(component => {
122
- const webComponent = createComponent({ ...imports[category][component], patch, h }, deps[category])
123
- customElements.define(imports[category][component].view.elementName, webComponent);
167
+ const componentConfig = imports[category][component];
168
+ const webComponent = createComponent({ ...componentConfig, patch, h }, deps[category])
169
+ const elementName = componentConfig.schema?.componentName;
170
+ if (!elementName) {
171
+ throw new Error(\`[Build] Missing schema.componentName for \${category}/\${component}. Define it in .schema.yaml.\`);
172
+ }
173
+ customElements.define(elementName, webComponent);
124
174
  })
125
175
  })
126
176
 
@@ -130,11 +180,11 @@ Object.keys(imports).forEach(category => {
130
180
  output = output.replace(key, replaceMap[key]);
131
181
  });
132
182
 
133
- writeFileSync("./.temp/dynamicImport.js", output);
183
+ writeFileSync(path.join(tempDir, "dynamicImport.js"), output);
134
184
 
135
- await bundleFile({ outfile, development });
185
+ await bundleFile({ outfile: resolvedOutfile, tempDir, development });
136
186
 
137
- console.log(`Build complete. Output file: ${outfile}`);
187
+ console.log(`Build complete. Output file: ${resolvedOutfile}`);
138
188
  };
139
189
 
140
190
  export default buildRettangoliFrontend;
@@ -0,0 +1,53 @@
1
+ import path from "node:path";
2
+ import {
3
+ analyzeComponentDirs,
4
+ formatContractFailureReport,
5
+ } from "./contracts.js";
6
+
7
+ const checkRettangoliFrontend = (options = {}) => {
8
+ const {
9
+ cwd = process.cwd(),
10
+ dirs = ["./example"],
11
+ format = "text",
12
+ } = options;
13
+ const outputFormat = format === "json" ? "json" : "text";
14
+
15
+ const resolvedDirs = dirs.map((dir) => path.resolve(cwd, dir));
16
+ const { errors, summary, index } = analyzeComponentDirs({ dirs: resolvedDirs });
17
+
18
+ if (errors.length > 0) {
19
+ if (outputFormat === "json") {
20
+ console.log(JSON.stringify({
21
+ ok: false,
22
+ prefix: "[Check]",
23
+ summary,
24
+ errors,
25
+ }, null, 2));
26
+ } else {
27
+ console.error(formatContractFailureReport({
28
+ errorPrefix: "[Check]",
29
+ errors,
30
+ }));
31
+ }
32
+ process.exitCode = 1;
33
+ return;
34
+ }
35
+
36
+ const componentCount = Object.values(index).reduce((count, categoryComponents) => {
37
+ return count + Object.keys(categoryComponents).length;
38
+ }, 0);
39
+
40
+ if (outputFormat === "json") {
41
+ console.log(JSON.stringify({
42
+ ok: true,
43
+ prefix: "[Check]",
44
+ componentCount,
45
+ summary,
46
+ }, null, 2));
47
+ return;
48
+ }
49
+
50
+ console.log(`[Check] Component contracts passed for ${componentCount} component(s).`);
51
+ };
52
+
53
+ export default checkRettangoliFrontend;
@@ -0,0 +1,143 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { load as loadYaml } from "js-yaml";
3
+ import { extractCategoryAndComponent, getAllFiles } from "../commonBuild.js";
4
+ import {
5
+ buildComponentContractIndex,
6
+ formatContractErrors as formatContractErrorLines,
7
+ validateComponentContractIndex,
8
+ } from "../core/contracts/componentFiles.js";
9
+
10
+ export const SUPPORTED_COMPONENT_FILE_SUFFIXES = Object.freeze([
11
+ ".store.js",
12
+ ".handlers.js",
13
+ ".methods.js",
14
+ ".constants.yaml",
15
+ ".schema.yaml",
16
+ ".view.yaml",
17
+ ]);
18
+
19
+ export const isSupportedComponentFile = (filePath) => {
20
+ return SUPPORTED_COMPONENT_FILE_SUFFIXES.some((suffix) => filePath.endsWith(suffix));
21
+ };
22
+
23
+ export const collectComponentContractEntriesFromFiles = (allFiles = []) => {
24
+ return allFiles
25
+ .filter((filePath) => isSupportedComponentFile(filePath))
26
+ .map((filePath) => {
27
+ const { category, component, fileType } = extractCategoryAndComponent(filePath);
28
+ const entry = {
29
+ category,
30
+ component,
31
+ fileType,
32
+ filePath,
33
+ };
34
+
35
+ if (["view", "schema"].includes(fileType)) {
36
+ entry.yamlObject = loadYaml(readFileSync(filePath, "utf8")) ?? {};
37
+ }
38
+
39
+ return entry;
40
+ });
41
+ };
42
+
43
+ export const collectComponentContractEntriesFromDirs = (dirs = []) => {
44
+ const allFiles = getAllFiles(dirs);
45
+ return collectComponentContractEntriesFromFiles(allFiles);
46
+ };
47
+
48
+ export const validateComponentEntries = ({
49
+ entries = [],
50
+ errorPrefix = "[Check]",
51
+ }) => {
52
+ const index = buildComponentContractIndex(entries);
53
+ const errors = validateComponentContractIndex(index);
54
+ if (errors.length > 0) {
55
+ throw new Error(
56
+ `${errorPrefix} Component contract validation failed:\n${formatContractErrors(errors).join("\n")}`,
57
+ );
58
+ }
59
+ return {
60
+ index,
61
+ errors,
62
+ };
63
+ };
64
+
65
+ export const validateComponentDirs = ({
66
+ dirs = [],
67
+ errorPrefix = "[Check]",
68
+ }) => {
69
+ const entries = collectComponentContractEntriesFromDirs(dirs);
70
+ const validationResult = validateComponentEntries({ entries, errorPrefix });
71
+ return {
72
+ entries,
73
+ ...validationResult,
74
+ };
75
+ };
76
+
77
+ export const summarizeContractErrors = (errors = []) => {
78
+ const byCode = {};
79
+ const byComponent = {};
80
+
81
+ errors.forEach((error) => {
82
+ const code = error?.code || "UNKNOWN";
83
+ byCode[code] = (byCode[code] || 0) + 1;
84
+
85
+ const componentLabelMatch = String(error?.message || "").match(/^([^:]+):\s/);
86
+ const componentLabel = componentLabelMatch ? componentLabelMatch[1] : "unknown";
87
+ byComponent[componentLabel] = (byComponent[componentLabel] || 0) + 1;
88
+ });
89
+
90
+ const byCodeSorted = Object.entries(byCode)
91
+ .map(([code, count]) => ({ code, count }))
92
+ .sort((a, b) => a.code.localeCompare(b.code));
93
+
94
+ const byComponentSorted = Object.entries(byComponent)
95
+ .map(([component, count]) => ({ component, count }))
96
+ .sort((a, b) => b.count - a.count || a.component.localeCompare(b.component));
97
+
98
+ return {
99
+ total: errors.length,
100
+ byCode: byCodeSorted,
101
+ byComponent: byComponentSorted,
102
+ };
103
+ };
104
+
105
+ export const formatContractFailureReport = ({
106
+ errorPrefix = "[Check]",
107
+ errors = [],
108
+ }) => {
109
+ const summary = summarizeContractErrors(errors);
110
+ const header = `${errorPrefix} Component contract validation failed: ${summary.total} issue(s)`;
111
+ const byCodeLines = summary.byCode.map(({ code, count }) => `- ${code}: ${count}`);
112
+ const byComponentLines = summary.byComponent.map(
113
+ ({ component, count }) => `- ${component}: ${count}`,
114
+ );
115
+ const detailLines = formatContractErrorLines(errors);
116
+
117
+ return [
118
+ header,
119
+ "By rule:",
120
+ ...(byCodeLines.length > 0 ? byCodeLines : ["- none"]),
121
+ "By component:",
122
+ ...(byComponentLines.length > 0 ? byComponentLines : ["- none"]),
123
+ "Details:",
124
+ ...(detailLines.length > 0 ? detailLines : ["- none"]),
125
+ ].join("\n");
126
+ };
127
+
128
+ export const analyzeComponentEntries = ({ entries = [] }) => {
129
+ const index = buildComponentContractIndex(entries);
130
+ const errors = validateComponentContractIndex(index);
131
+ const summary = summarizeContractErrors(errors);
132
+ return {
133
+ entries,
134
+ index,
135
+ errors,
136
+ summary,
137
+ };
138
+ };
139
+
140
+ export const analyzeComponentDirs = ({ dirs = [] }) => {
141
+ const entries = collectComponentContractEntriesFromDirs(dirs);
142
+ return analyzeComponentEntries({ entries });
143
+ };
package/src/cli/index.js CHANGED
@@ -1,11 +1,5 @@
1
- import build from './build.js';
2
- import scaffold from './scaffold.js';
3
- import watch from './watch.js';
4
- import examples from './examples.js';
5
-
6
- export {
7
- build,
8
- scaffold,
9
- watch,
10
- examples
11
- }
1
+ export { default as build } from "./build.js";
2
+ export { default as check } from "./check.js";
3
+ export { default as scaffold } from "./scaffold.js";
4
+ export { default as watch } from "./watch.js";
5
+ export { default as examples } from "./examples.js";
@@ -1,5 +1,6 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
+ import { validateComponentDirs } from './contracts.js';
3
4
 
4
5
  const __dirname = path.dirname(new URL(import.meta.url).pathname);
5
6
 
@@ -37,6 +38,11 @@ const scaffoldPage = (options) => {
37
38
  }
38
39
  });
39
40
 
41
+ validateComponentDirs({
42
+ dirs: [path.resolve(targetDir)],
43
+ errorPrefix: "[Scaffold]",
44
+ });
45
+
40
46
  console.log(`Successfully scaffolded ${targetDir} from template`);
41
47
  }
42
48
 
package/src/cli/watch.js CHANGED
@@ -20,9 +20,10 @@ const setupWatcher = (directory, options) => {
20
20
  console.log(`Detected ${event} in ${directory}/${filename}`);
21
21
  if (filename) {
22
22
  try {
23
+ const changedFilePath = path.join(directory, filename);
23
24
  if (filename.endsWith('.view.yaml')) {
24
- const view = loadYaml(readFileSync(path.join(directory, filename), "utf8"));
25
- const { category, component } = extractCategoryAndComponent(filename);
25
+ const view = loadYaml(readFileSync(changedFilePath, "utf8"));
26
+ const { category, component } = extractCategoryAndComponent(changedFilePath);
26
27
  await writeViewFile(view, category, component);
27
28
  }
28
29