@wix/validation-infra 0.0.0-stage → 0.5.1

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 (152) hide show
  1. package/README.md +192 -2
  2. package/dist/constants.d.ts +29 -0
  3. package/dist/constants.js +45 -0
  4. package/dist/index.d.ts +11 -0
  5. package/dist/index.js +13 -0
  6. package/dist/package-readers/constants.d.ts +6 -0
  7. package/dist/package-readers/constants.js +6 -0
  8. package/dist/package-readers/index.d.ts +1 -0
  9. package/dist/package-readers/index.js +1 -0
  10. package/dist/package-readers/read-from-files.d.ts +6 -0
  11. package/dist/package-readers/read-from-files.js +76 -0
  12. package/dist/package-readers/types.d.ts +7 -0
  13. package/dist/package-readers/types.js +1 -0
  14. package/dist/package-readers/utils.d.ts +4 -0
  15. package/dist/package-readers/utils.js +15 -0
  16. package/dist/page-model/build-page-model.d.ts +3 -0
  17. package/dist/page-model/build-page-model.js +12 -0
  18. package/dist/page-model/connect-css.d.ts +3 -0
  19. package/dist/page-model/connect-css.js +43 -0
  20. package/dist/page-model/constants.d.ts +17 -0
  21. package/dist/page-model/constants.js +17 -0
  22. package/dist/page-model/css-selectors.d.ts +2 -0
  23. package/dist/page-model/css-selectors.js +7 -0
  24. package/dist/page-model/index.d.ts +4 -0
  25. package/dist/page-model/index.js +4 -0
  26. package/dist/page-model/pages.d.ts +2 -0
  27. package/dist/page-model/pages.js +18 -0
  28. package/dist/page-model/read-css.d.ts +4 -0
  29. package/dist/page-model/read-css.js +98 -0
  30. package/dist/page-model/read-structure.d.ts +3 -0
  31. package/dist/page-model/read-structure.js +59 -0
  32. package/dist/page-model/read-theme.d.ts +6 -0
  33. package/dist/page-model/read-theme.js +14 -0
  34. package/dist/page-model/types.d.ts +92 -0
  35. package/dist/page-model/types.js +1 -0
  36. package/dist/page-model/utils.d.ts +16 -0
  37. package/dist/page-model/utils.js +29 -0
  38. package/dist/project-model/index.d.ts +5 -0
  39. package/dist/project-model/index.js +5 -0
  40. package/dist/project-model/menu-files.d.ts +4 -0
  41. package/dist/project-model/menu-files.js +14 -0
  42. package/dist/project-model/package-json.d.ts +5 -0
  43. package/dist/project-model/package-json.js +27 -0
  44. package/dist/project-model/popups.d.ts +4 -0
  45. package/dist/project-model/popups.js +12 -0
  46. package/dist/project-model/project-model.d.ts +4 -0
  47. package/dist/project-model/project-model.js +14 -0
  48. package/dist/project-model/types.d.ts +20 -0
  49. package/dist/project-model/types.js +2 -0
  50. package/dist/rules/index.d.ts +4 -0
  51. package/dist/rules/index.js +5 -0
  52. package/dist/rules/project/define-project-rule.d.ts +5 -0
  53. package/dist/rules/project/define-project-rule.js +4 -0
  54. package/dist/rules/project/index.d.ts +2 -0
  55. package/dist/rules/project/index.js +2 -0
  56. package/dist/rules/project/types.d.ts +16 -0
  57. package/dist/rules/project/types.js +1 -0
  58. package/dist/rules/site-app/define-rule.d.ts +5 -0
  59. package/dist/rules/site-app/define-rule.js +4 -0
  60. package/dist/rules/site-app/index.d.ts +2 -0
  61. package/dist/rules/site-app/index.js +1 -0
  62. package/dist/rules/site-app/types.d.ts +26 -0
  63. package/dist/rules/site-app/types.js +1 -0
  64. package/dist/rules/site-code/define-site-code-rule.d.ts +5 -0
  65. package/dist/rules/site-code/define-site-code-rule.js +4 -0
  66. package/dist/rules/site-code/index.d.ts +2 -0
  67. package/dist/rules/site-code/index.js +2 -0
  68. package/dist/rules/site-code/types.d.ts +11 -0
  69. package/dist/rules/site-code/types.js +1 -0
  70. package/dist/rules/types.d.ts +13 -0
  71. package/dist/rules/types.js +3 -0
  72. package/dist/rules-adapter/eslint/index.d.ts +1 -0
  73. package/dist/rules-adapter/eslint/index.js +1 -0
  74. package/dist/rules-adapter/eslint/types.d.ts +5 -0
  75. package/dist/rules-adapter/eslint/types.js +1 -0
  76. package/dist/rules-adapter/index.d.ts +2 -0
  77. package/dist/rules-adapter/index.js +2 -0
  78. package/dist/rules-adapter/types.d.ts +16 -0
  79. package/dist/rules-adapter/types.js +1 -0
  80. package/dist/rules-adapter/utils.d.ts +7 -0
  81. package/dist/rules-adapter/utils.js +20 -0
  82. package/dist/rules-api/component-catalog.d.ts +8 -0
  83. package/dist/rules-api/component-catalog.js +28 -0
  84. package/dist/rules-api/constants.d.ts +7 -0
  85. package/dist/rules-api/constants.js +7 -0
  86. package/dist/rules-api/index.d.ts +18 -0
  87. package/dist/rules-api/index.js +14 -0
  88. package/dist/rules-api/report.d.ts +8 -0
  89. package/dist/rules-api/report.js +13 -0
  90. package/dist/rules-api/rules-api.d.ts +13 -0
  91. package/dist/rules-api/rules-api.js +139 -0
  92. package/dist/rules-api/types.d.ts +141 -0
  93. package/dist/rules-api/types.js +1 -0
  94. package/dist/rules-api/utils.d.ts +14 -0
  95. package/dist/rules-api/utils.js +27 -0
  96. package/dist/shared/constants.d.ts +188 -0
  97. package/dist/shared/constants.js +242 -0
  98. package/dist/shared/css-variables.d.ts +9 -0
  99. package/dist/shared/css-variables.js +38 -0
  100. package/dist/shared/css.d.ts +78 -0
  101. package/dist/shared/css.js +426 -0
  102. package/dist/shared/element-match.d.ts +16 -0
  103. package/dist/shared/element-match.js +72 -0
  104. package/dist/shared/font-weights.d.ts +2 -0
  105. package/dist/shared/font-weights.js +551 -0
  106. package/dist/shared/index.d.ts +16 -0
  107. package/dist/shared/index.js +15 -0
  108. package/dist/shared/interactions-config.d.ts +15 -0
  109. package/dist/shared/interactions-config.js +120 -0
  110. package/dist/shared/links.d.ts +21 -0
  111. package/dist/shared/links.js +93 -0
  112. package/dist/shared/posix-path.d.ts +8 -0
  113. package/dist/shared/posix-path.js +27 -0
  114. package/dist/shared/site-files-tree-mapping.d.ts +40 -0
  115. package/dist/shared/site-files-tree-mapping.js +41 -0
  116. package/dist/shared/site-folders.d.ts +3 -0
  117. package/dist/shared/site-folders.js +17 -0
  118. package/dist/shared/site-media.d.ts +3 -0
  119. package/dist/shared/site-media.js +11 -0
  120. package/dist/shared/syntax-tree.d.ts +4 -0
  121. package/dist/shared/syntax-tree.js +30 -0
  122. package/dist/shared/transformation-values.d.ts +22 -0
  123. package/dist/shared/transformation-values.js +74 -0
  124. package/dist/shared/types.d.ts +477 -0
  125. package/dist/shared/types.js +1 -0
  126. package/dist/shared/utils.d.ts +155 -0
  127. package/dist/shared/utils.js +553 -0
  128. package/dist/shared/wrapper-contract.d.ts +31 -0
  129. package/dist/shared/wrapper-contract.js +157 -0
  130. package/dist/shared/wrapper-image-props.d.ts +3 -0
  131. package/dist/shared/wrapper-image-props.js +75 -0
  132. package/dist/site-code-model/constants.d.ts +107 -0
  133. package/dist/site-code-model/constants.js +102 -0
  134. package/dist/site-code-model/index.d.ts +3 -0
  135. package/dist/site-code-model/index.js +4 -0
  136. package/dist/site-code-model/manifest-values.d.ts +15 -0
  137. package/dist/site-code-model/manifest-values.js +88 -0
  138. package/dist/site-code-model/read-module.d.ts +4 -0
  139. package/dist/site-code-model/read-module.js +267 -0
  140. package/dist/site-code-model/read-site-code-model.d.ts +9 -0
  141. package/dist/site-code-model/read-site-code-model.js +42 -0
  142. package/dist/site-code-model/source-locations.d.ts +5 -0
  143. package/dist/site-code-model/source-locations.js +95 -0
  144. package/dist/site-code-model/types.d.ts +102 -0
  145. package/dist/site-code-model/types.js +1 -0
  146. package/dist/testing.d.ts +24 -0
  147. package/dist/testing.js +61 -0
  148. package/dist/types.d.ts +95 -0
  149. package/dist/types.js +1 -0
  150. package/dist/validate.d.ts +7 -0
  151. package/dist/validate.js +180 -0
  152. package/package.json +59 -3
@@ -0,0 +1,267 @@
1
+ // One module of the site code, read statically: its imports and consts, its exports, and its registration calls, each
2
+ // value evaluated as the build would compute it, with the place it's written in. Nothing runs: what isn't read is UNKNOWN.
3
+ import { parse } from '@typescript-eslint/parser';
4
+ import { createSourceReader, getImportedName, walk } from "../shared/index.js";
5
+ import { CONST_DECLARATION, DEFAULT_EXPORT, EXTENSION_REGISTRY, EXTENSION_REGISTRY_SOURCES, MANIFEST_FUNCTIONS, NAMESPACE_IMPORT, NEGATIVE, NODE_TYPE, REGISTRATIONS, RELATIVE_IMPORT, SCALAR_TYPES, TYPE_KEY, TYPE_ONLY, TYPE_WRAPPERS, UNKNOWN, URL_IMPORT, VALUE_PROPERTY, } from "./constants.js";
6
+ import { childOf, deepmerge, isObject, getNearestValue, toManifestValue, unknownAt, withEditorElementDefaults } from "./manifest-values.js";
7
+ import { getFixLocation } from "./source-locations.js";
8
+ /** Exports that hold only a module's explicit exports, as one of its `export *`s isn't read: read by name, an explicit
9
+ * export is its value and any other name is UNKNOWN; read whole (`import * as`, `export * as`, `export *`), UNKNOWN. */
10
+ const partialExports = new WeakSet();
11
+ /** Throws for a file that doesn't parse, naming it. */
12
+ export function readModule(file, text, readImport, readFile) {
13
+ const program = parseProgram(file, text);
14
+ const { loc } = createSourceReader(text);
15
+ const { bindings, exported, exportAll } = readDeclarations(program.body);
16
+ const scope = { file, bindings, readImport, evaluating: new Set(), placeAt: (node) => ({ file, line: loc(node).start.line }) };
17
+ return {
18
+ registrations: () => getCalls(program).flatMap((call) => toExtension(scope, call, readFile)),
19
+ // An import cycle reads as UNKNOWN.
20
+ exports: readOnce(() => readExports(scope, exported, exportAll), unknownAt({ file, line: 1 })),
21
+ };
22
+ }
23
+ // ── reading the module ──
24
+ function parseProgram(file, text) {
25
+ try {
26
+ return parse(text, { filePath: file, ecmaFeatures: { jsx: true }, range: true });
27
+ }
28
+ catch (error) {
29
+ throw new Error(`${file}: ${error instanceof Error ? error.message : String(error)}`);
30
+ }
31
+ }
32
+ /** The names the module declares (its imports and consts), and each export: its expression, or the local name it exports. */
33
+ function readDeclarations(body) {
34
+ const bindings = new Map();
35
+ const exported = new Map();
36
+ const exportAll = [];
37
+ for (const statement of body) {
38
+ if (statement.type === NODE_TYPE.ImportDeclaration) {
39
+ for (const specifier of statement.specifiers)
40
+ bindings.set(specifier.local.name, { source: statement.source.value, imported: getImportedName(specifier) });
41
+ continue;
42
+ }
43
+ if (statement.exportKind === TYPE_ONLY)
44
+ continue;
45
+ if (statement.type === NODE_TYPE.ExportDefaultDeclaration)
46
+ exported.set(DEFAULT_EXPORT, { expression: statement.declaration });
47
+ if (statement.type === NODE_TYPE.ExportAllDeclaration) {
48
+ if (statement.exported)
49
+ exported.set(nameOf(statement.exported), { source: statement.source.value, imported: NAMESPACE_IMPORT });
50
+ else
51
+ exportAll.push(statement.source.value);
52
+ }
53
+ if (statement.type === NODE_TYPE.ExportNamedDeclaration)
54
+ for (const specifier of statement.specifiers) {
55
+ if (specifier.exportKind === TYPE_ONLY)
56
+ continue;
57
+ exported.set(nameOf(specifier.exported), statement.source
58
+ ? { source: statement.source.value, imported: nameOf(specifier.local) }
59
+ : { local: specifier.local.name });
60
+ }
61
+ const declaration = statement.type === NODE_TYPE.ExportNamedDeclaration ? statement.declaration : statement;
62
+ if (declaration?.type !== NODE_TYPE.VariableDeclaration)
63
+ continue;
64
+ for (const declarator of declaration.declarations) {
65
+ if (declarator.id.type !== NODE_TYPE.Identifier)
66
+ continue;
67
+ bindings.set(declarator.id.name, { init: declaration.kind === CONST_DECLARATION ? declarator.init : null });
68
+ if (statement.type === NODE_TYPE.ExportNamedDeclaration)
69
+ exported.set(declarator.id.name, { local: declarator.id.name });
70
+ }
71
+ }
72
+ return { bindings, exported, exportAll };
73
+ }
74
+ /** The module's exports. When an `export *` isn't read, only the explicit exports are kept, and the module read whole is UNKNOWN. */
75
+ function readExports(scope, exported, exportAll) {
76
+ const place = { file: scope.file, line: 1 };
77
+ const stars = readStarExports(scope, exportAll, place);
78
+ const value = new Map(stars ?? []);
79
+ // Explicit exports take precedence over stars, regardless of declaration order.
80
+ for (const [name, binding] of exported)
81
+ value.set(name, 'source' in binding ? evaluateImport(scope, binding, place)
82
+ : 'local' in binding ? evaluateName(scope, binding.local, place) : evaluate(scope, binding.expression));
83
+ const exports = { place, value };
84
+ if (!stars)
85
+ partialExports.add(exports);
86
+ return exports;
87
+ }
88
+ /** The names the `export *`s add, without `default`; a name two of them export differently is UNKNOWN. Null when one
89
+ * star's module isn't read (a package, a file that's missing): it may add any name, or make one ambiguous. */
90
+ function readStarExports(scope, exportAll, place) {
91
+ const value = new Map();
92
+ for (const source of exportAll) {
93
+ const imported = evaluateImport(scope, { source, imported: NAMESPACE_IMPORT }, place);
94
+ if (!isObject(imported))
95
+ return null;
96
+ for (const [name, child] of imported.value) {
97
+ if (name !== DEFAULT_EXPORT)
98
+ value.set(name, value.has(name) && value.get(name) !== child ? unknownAt(place) : child);
99
+ }
100
+ }
101
+ return value;
102
+ }
103
+ function getCalls(program) {
104
+ const calls = [];
105
+ walk(program, [], (node) => { if (node.type === NODE_TYPE.CallExpression)
106
+ calls.push(node); });
107
+ return calls;
108
+ }
109
+ /** A registration call as an extension; none for any other call. readFile reads a generated value's source, for fixAt. */
110
+ function toExtension(scope, call, readFile) {
111
+ const kind = getRegistrationKind(scope, call.callee);
112
+ if (!kind)
113
+ return [];
114
+ const argument = call.arguments[0];
115
+ const config = argument && !isSpread(argument) ? evaluate(scope, argument) : unknownAt(scope.placeAt(call));
116
+ const type = childOf(config, TYPE_KEY)?.value;
117
+ return [{
118
+ kind,
119
+ type: typeof type === 'string' ? type : UNKNOWN,
120
+ file: scope.file,
121
+ manifest: isObject(config) ? toManifestValue(config) : UNKNOWN,
122
+ where: (path) => getNearestValue(config, path).place,
123
+ fixAt: (path) => getFixLocation(config, path, readFile),
124
+ }];
125
+ }
126
+ /** `extensions.editorReactComponent` → 'component'; undefined for any other callee (`x.toString` included). */
127
+ function getRegistrationKind(scope, callee) {
128
+ if (callee.type !== NODE_TYPE.MemberExpression || callee.computed)
129
+ return undefined;
130
+ if (!EXTENSION_REGISTRY_SOURCES.some((source) => isImportOf(scope, callee.object, { name: EXTENSION_REGISTRY, source })))
131
+ return undefined;
132
+ return Object.hasOwn(REGISTRATIONS, callee.property.name) ? REGISTRATIONS[callee.property.name] : undefined;
133
+ }
134
+ // ── evaluating a value ──
135
+ function evaluate(scope, node) {
136
+ if (TYPE_WRAPPERS.includes(node.type))
137
+ return evaluate(scope, node.expression);
138
+ const place = scope.placeAt(node);
139
+ switch (node.type) {
140
+ case NODE_TYPE.Literal:
141
+ case NODE_TYPE.TemplateLiteral:
142
+ return { place, value: scalarOf(node) };
143
+ case NODE_TYPE.UnaryExpression: {
144
+ const operand = evaluate(scope, node.argument).value;
145
+ return { place, value: node.operator === NEGATIVE && typeof operand === 'number' ? -operand : UNKNOWN };
146
+ }
147
+ case NODE_TYPE.Identifier:
148
+ return evaluateName(scope, node.name, place);
149
+ case NODE_TYPE.MemberExpression: {
150
+ const key = keyOf(node.property, node.computed);
151
+ return (key !== null && childOf(evaluate(scope, node.object), key)) || unknownAt(place);
152
+ }
153
+ case NODE_TYPE.ArrayExpression:
154
+ return evaluateArray(scope, node, place);
155
+ case NODE_TYPE.ObjectExpression:
156
+ return evaluateObject(scope, node, place);
157
+ case NODE_TYPE.CallExpression:
158
+ return evaluateCall(scope, node, place);
159
+ default:
160
+ return unknownAt(place);
161
+ }
162
+ }
163
+ /** A value written in place: a string, a number, a boolean, null, a template without `${…}`. */
164
+ function scalarOf(node) {
165
+ if (node.type === NODE_TYPE.TemplateLiteral)
166
+ return node.expressions.length === 0 ? (node.quasis[0].value.cooked ?? '') : UNKNOWN;
167
+ return node.type === NODE_TYPE.Literal && (node.value === null || SCALAR_TYPES.includes(typeof node.value)) ? node.value : UNKNOWN;
168
+ }
169
+ function evaluateName(scope, name, place) {
170
+ const binding = scope.bindings.get(name);
171
+ if (!binding || scope.evaluating.has(name))
172
+ return unknownAt(place);
173
+ if (!('init' in binding))
174
+ return evaluateImport(scope, binding, place);
175
+ if (!binding.init)
176
+ return unknownAt(place);
177
+ scope.evaluating.add(name);
178
+ try {
179
+ return evaluate(scope, binding.init);
180
+ }
181
+ finally {
182
+ scope.evaluating.delete(name);
183
+ }
184
+ }
185
+ /** A `?url` import is its source; a relative import is that module's export; a package's export is UNKNOWN. */
186
+ function evaluateImport({ file, readImport }, { source, imported }, place) {
187
+ if (source.endsWith(URL_IMPORT))
188
+ return { place, value: source };
189
+ const module = source.startsWith(RELATIVE_IMPORT) ? readImport(file, source) : undefined;
190
+ if (imported === NAMESPACE_IMPORT && module)
191
+ return partialExports.has(module) ? unknownAt(place) : module;
192
+ return (module && childOf(module, imported)) || unknownAt(place);
193
+ }
194
+ function evaluateArray(scope, node, place) {
195
+ const value = [];
196
+ for (const element of node.elements) {
197
+ const items = element === null ? null : isSpread(element) ? itemsOf(evaluate(scope, element.argument)) : [evaluate(scope, element)];
198
+ if (!items)
199
+ return unknownAt(place);
200
+ value.push(...items);
201
+ }
202
+ return { place, value };
203
+ }
204
+ function evaluateObject(scope, node, place) {
205
+ const value = new Map();
206
+ for (const property of node.properties) {
207
+ const entries = isSpread(property) ? entriesOf(evaluate(scope, property.argument)) : propertyEntry(scope, property);
208
+ if (!entries)
209
+ return unknownAt(place);
210
+ for (const [key, child] of entries)
211
+ value.set(key, child);
212
+ }
213
+ return { place, value };
214
+ }
215
+ /** `key: value`, placed on its key's line; null for a key computed from code, a getter or a setter. A method is UNKNOWN. */
216
+ function propertyEntry(scope, property) {
217
+ const key = keyOf(property.key, property.computed);
218
+ if (key === null || property.kind !== VALUE_PROPERTY)
219
+ return null;
220
+ const place = scope.placeAt(property);
221
+ return [[key, property.method ? unknownAt(place) : { ...evaluate(scope, property.value), place }]];
222
+ }
223
+ /** deepmerge and withEditorElementDefaults, imported from their packages, as those packages do them; any other call, and
224
+ * the deepmerge package's call with options, is UNKNOWN. */
225
+ function evaluateCall(scope, node, place) {
226
+ const calls = (manifestFunction) => isImportOf(scope, node.callee, manifestFunction);
227
+ const args = node.arguments;
228
+ if (args.some(isSpread))
229
+ return unknownAt(place);
230
+ if (calls(MANIFEST_FUNCTIONS.deepmerge) || (calls(MANIFEST_FUNCTIONS.deepmergePackage) && args.length === 2))
231
+ return args.map((argument) => evaluate(scope, argument)).reduce(deepmerge, { place, value: new Map() });
232
+ if (calls(MANIFEST_FUNCTIONS.withEditorElementDefaults) && args.length === 2)
233
+ return withEditorElementDefaults(evaluate(scope, args[0]), evaluate(scope, args[1]));
234
+ return unknownAt(place);
235
+ }
236
+ // ── small helpers ──
237
+ /** read(), once; while it's being read (an import cycle), whileReading. A read that throws (a module it imports doesn't
238
+ * parse) throws again the next time. */
239
+ function readOnce(read, whileReading) {
240
+ let value;
241
+ let reading = false;
242
+ return () => {
243
+ if (value !== undefined)
244
+ return value;
245
+ if (reading)
246
+ return whileReading;
247
+ reading = true;
248
+ try {
249
+ return (value = read());
250
+ }
251
+ finally {
252
+ reading = false;
253
+ }
254
+ };
255
+ }
256
+ const isSpread = (node) => node.type === NODE_TYPE.SpreadElement;
257
+ const itemsOf = ({ value }) => (Array.isArray(value) ? value : null);
258
+ const entriesOf = (placed) => (isObject(placed) ? [...placed.value] : null);
259
+ /** true when the callee is that name imported from that package (`import { deepmerge as merge } from 'deepmerge-ts'` too). */
260
+ function isImportOf(scope, callee, { name, source }) {
261
+ const binding = callee.type === NODE_TYPE.Identifier ? scope.bindings.get(callee.name) : undefined;
262
+ return binding !== undefined && 'imported' in binding && binding.imported === name && binding.source === source;
263
+ }
264
+ /** An identifier's name, or a string literal's value (`export { a as 'b' }`). */
265
+ const nameOf = (node) => node.name ?? String(node.value);
266
+ /** A property's or a member's key: `a`, `'a'`, `[0]`; null for one computed from code. */
267
+ const keyOf = (key, computed) => computed ? (key.type === NODE_TYPE.Literal ? String(key.value) : null) : nameOf(key);
@@ -0,0 +1,9 @@
1
+ import { type ReadFile } from '../shared/index.ts';
2
+ import type { Extension, SiteCodeModel } from './types.ts';
3
+ /** A file (from the site root) the Wix CLI registers extensions in: `<name>.extension.ts` under packages/site-code/src. */
4
+ export declare const isExtensionFile: (file: string) => boolean;
5
+ /** The site code of these files (from the site root): every extension they register. */
6
+ export declare function readSiteCodeModel(files: readonly string[], readExtensions: (file: string) => readonly Extension[]): SiteCodeModel;
7
+ /** The extensions an extension file registers. One reader for every extension file: a file is read once, for every
8
+ * extension that imports it. Throws for a file (the extension, or a module whose value it reads) that doesn't parse, naming the file. */
9
+ export declare function createExtensionReader(readFile: ReadFile): (file: string) => readonly Extension[];
@@ -0,0 +1,42 @@
1
+ // The site-code model: each extension under packages/site-code/src with its manifest. The recipe: an extension file →
2
+ // its module, read statically (read-module.ts) → its registration calls.
3
+ import { EXTENSION_FILE, SITE_CODE_SRC, posixPath } from "../shared/index.js";
4
+ import { MODULE_EXTENSIONS, SOURCE_MODULE, TYPESCRIPT_EXTENSIONS, UNKNOWN } from "./constants.js";
5
+ import { readModule } from "./read-module.js";
6
+ /** A file (from the site root) the Wix CLI registers extensions in: `<name>.extension.ts` under packages/site-code/src. */
7
+ export const isExtensionFile = (file) => file.startsWith(`${SITE_CODE_SRC}/`) && EXTENSION_FILE.test(file);
8
+ /** The site code of these files (from the site root): every extension they register. */
9
+ export function readSiteCodeModel(files, readExtensions) {
10
+ try {
11
+ return { extensions: files.filter(isExtensionFile).toSorted().flatMap(readExtensions) };
12
+ }
13
+ catch {
14
+ return { extensions: UNKNOWN };
15
+ }
16
+ }
17
+ /** The extensions an extension file registers. One reader for every extension file: a file is read once, for every
18
+ * extension that imports it. Throws for a file (the extension, or a module whose value it reads) that doesn't parse, naming the file. */
19
+ export function createExtensionReader(readFile) {
20
+ const modules = new Map();
21
+ const moduleOf = (file) => {
22
+ if (!modules.has(file)) {
23
+ const text = readFile(file);
24
+ modules.set(file, text === undefined ? undefined : readModule(file, text, readImport, readFile));
25
+ }
26
+ return modules.get(file);
27
+ };
28
+ const readImport = (from, source) => {
29
+ const target = posixPath.join(posixPath.dirname(from), source);
30
+ if (!posixPath.isSitePath(target))
31
+ return undefined;
32
+ const file = getImportCandidates(target).find((candidate) => readFile(candidate) !== undefined);
33
+ return file !== undefined && SOURCE_MODULE.test(file) ? moduleOf(file)?.exports() : undefined;
34
+ };
35
+ return (file) => moduleOf(file)?.registrations() ?? [];
36
+ }
37
+ /** The files an import's target can mean, most likely first, as the build resolves it: as written, a `.js` import of a
38
+ * TypeScript source, then an added extension or a directory's entry. */
39
+ function getImportCandidates(target) {
40
+ const typescriptSources = Object.entries(TYPESCRIPT_EXTENSIONS).flatMap(([emitted, sources]) => target.endsWith(emitted) ? sources.map((suffix) => target.slice(0, -emitted.length) + suffix) : []);
41
+ return [target, ...typescriptSources, ...MODULE_EXTENSIONS.map((suffix) => target + suffix)];
42
+ }
@@ -0,0 +1,5 @@
1
+ import { type ReadFile } from '../shared/index.ts';
2
+ import type { LocatedManifestValue, SourceLocation } from './types.ts';
3
+ /** The place of the value at path, or where the agent fixes it when it's generated: the first of its source files the
4
+ * site has (the scaffold's when it has none); line 1 when no line is found. */
5
+ export declare function getFixLocation(config: LocatedManifestValue, path: string, readFile: ReadFile): SourceLocation;
@@ -0,0 +1,95 @@
1
+ // Where the agent fixes a manifest value: where it's written, or for a value of a generated file (which import-site
2
+ // rewrites from the component's code), the file beside it the value is generated from, at the line that writes it
3
+ // when the model finds one by name: a custom property's `--name` in the CSS module, a selector's class in the React file.
4
+ import { parse } from '@typescript-eslint/parser';
5
+ import postcss, {} from 'postcss';
6
+ import { GENERATED_FILE, createSourceReader, walk } from "../shared/index.js";
7
+ import { CLASS_NAME, EDITOR_ELEMENT, GENERATED_FROM, NAMED_CHILDREN, NODE_TYPE, PADDED_SELECTOR_LENGTH, PROPERTY_AT_RULE, SELECTOR_PADDING } from "./constants.js";
8
+ import { getNearestValue } from "./manifest-values.js";
9
+ const { data, selector, cssCustomProperties } = EDITOR_ELEMENT;
10
+ /** The place of the value at path, or where the agent fixes it when it's generated: the first of its source files the
11
+ * site has (the scaffold's when it has none); line 1 when no line is found. */
12
+ export function getFixLocation(config, path, readFile) {
13
+ const { place, value } = getNearestValue(config, path);
14
+ if (!GENERATED_FILE.test(place.file))
15
+ return place;
16
+ const { key, name } = getGeneratedSource(path);
17
+ const sources = GENERATED_FROM[key].map((suffix) => place.file.replace(GENERATED_FILE, suffix));
18
+ const file = sources.find((source) => readFile(source) !== undefined) ?? sources[0];
19
+ const text = readFile(file);
20
+ const line = text === undefined ? undefined
21
+ : key === cssCustomProperties && name ? customPropertyLine(text, name)
22
+ : key === selector && typeof value === 'string' ? classNameLine(file, text, value)
23
+ : undefined;
24
+ return { file, line: line ?? 1 };
25
+ }
26
+ /** The last key on the path that names a source, and the app's name under it; `data` (the props) for a path under no such
27
+ * key. A name the app gives is never that key: in `data.selector.dataType`, `selector` is a data field. */
28
+ function getGeneratedSource(path) {
29
+ const keys = path.split('.');
30
+ let source = { key: data };
31
+ for (let index = 0; index < keys.length; index++) {
32
+ if (!Object.hasOwn(GENERATED_FROM, keys[index]))
33
+ continue;
34
+ source = NAMED_CHILDREN.includes(keys[index]) ? { key: keys[index], name: keys[++index] } : { key: keys[index] };
35
+ }
36
+ return source;
37
+ }
38
+ /** `@property --name`, which the generator reads the type from first; else the first `--name:` declaration. */
39
+ function customPropertyLine(text, name) {
40
+ const root = parseCss(text);
41
+ let line;
42
+ root?.walkAtRules(PROPERTY_AT_RULE, (rule) => { if (rule.params.trim() === `--${name}`)
43
+ line ??= rule.source?.start?.line; });
44
+ root?.walkDecls(`--${name}`, (declaration) => { line ??= declaration.source?.start?.line; });
45
+ return line;
46
+ }
47
+ /** The first string in a `className` that holds the selector's class (`'title'` in `classNames('title', styles.title)`). A
48
+ * padded-length selector is its class as written first, then without the padding: `.ab_` is the class `ab_`, or `ab`. */
49
+ function classNameLine(file, text, selectorValue) {
50
+ if (!selectorValue.startsWith('.'))
51
+ return undefined;
52
+ const name = selectorValue.slice(1);
53
+ const names = selectorValue.length === PADDED_SELECTOR_LENGTH ? [name, name.replace(SELECTOR_PADDING, '')] : [name];
54
+ const lines = classNameLines(file, text);
55
+ return names.map((candidate) => lines.get(candidate)).find((line) => line !== undefined);
56
+ }
57
+ /** Each class a `className` string writes, and the line of its first one. */
58
+ function classNameLines(file, text) {
59
+ const { loc } = createSourceReader(text);
60
+ const lines = new Map();
61
+ let program;
62
+ try {
63
+ program = parse(text, { filePath: file, ecmaFeatures: { jsx: true }, range: true });
64
+ }
65
+ catch {
66
+ return lines;
67
+ }
68
+ walk(program, [], (node) => {
69
+ if (node.type !== NODE_TYPE.JSXAttribute)
70
+ return;
71
+ const { name, value } = node;
72
+ if (name.type !== NODE_TYPE.JSXIdentifier || name.name !== CLASS_NAME || !value)
73
+ return;
74
+ walk(value, [], (part) => {
75
+ for (const className of classesOf(part))
76
+ if (!lines.has(className))
77
+ lines.set(className, loc(part).start.line);
78
+ });
79
+ });
80
+ return lines;
81
+ }
82
+ /** The class names a string literal or a template's text writes. */
83
+ function classesOf(node) {
84
+ const text = node.type === NODE_TYPE.Literal ? node.value : node.type === NODE_TYPE.TemplateElement ? node.value.cooked : undefined;
85
+ return typeof text === 'string' ? text.split(/\s+/) : [];
86
+ }
87
+ /** The CSS module as parsed; undefined for one that doesn't parse (the build reports it, not this lookup). */
88
+ function parseCss(text) {
89
+ try {
90
+ return postcss.parse(text);
91
+ }
92
+ catch {
93
+ return undefined;
94
+ }
95
+ }
@@ -0,0 +1,102 @@
1
+ import type { AstNode } from '../shared/index.ts';
2
+ import type { UNKNOWN } from './constants.ts';
3
+ /** The site code as a whole, for a check across extensions (a duplicate `type`, a `refElement` that names another
4
+ * component's `type`). */
5
+ export interface SiteCodeModel {
6
+ /** Every extension of the site, in its files' order; UNKNOWN when an extension file, or a module whose value it
7
+ * reads, doesn't parse: any extension may be registered then. An import whose value isn't read is not parsed. */
8
+ extensions: readonly Extension[] | typeof UNKNOWN;
9
+ }
10
+ /** One registration of the site code, what a site-code rule checks: `extensions.editorReactComponent({…})`, `contextProvider`
11
+ * or `functionLibrary`. */
12
+ export interface Extension {
13
+ kind: ExtensionKind;
14
+ /** `companionApp.<Name>`; UNKNOWN when `type` isn't a string written in place. */
15
+ type: string | typeof UNKNOWN;
16
+ /** The extension file, from the site root. */
17
+ file: string;
18
+ /** The object passed to the registration, merged as the Wix CLI merges it: `deepmerge` joins objects and concatenates
19
+ * arrays; `withEditorElementDefaults` fills `data.<key>.defaultValue` from the props' defaults. A `?url` import's
20
+ * identifier is its source (`'./component.tsx?url'`). UNKNOWN when the object isn't read (`{ ...base, type }`,
21
+ * `base` from a package): it may hold any key. */
22
+ manifest: Manifest | typeof UNKNOWN;
23
+ /** Where the value at a dotted path (`editorElement.data.label.dataType`) is written: the generated file, the props
24
+ * file or the extension. A path that isn't there gives the nearest value above it. */
25
+ where(path: string): SourceLocation;
26
+ /** Where the agent fixes the value at a path: where(path), except a value of the generated file, which import-site
27
+ * rewrites from the React code: that one is fixed in the file it's generated from: `<name>.module.css` under
28
+ * `cssProperties` or `cssCustomProperties`, `<name>.tsx` under `selector` or `elements`, else `<name>.props.ts`
29
+ * (a JavaScript component: `<name>.jsx` for both, as it has no props file); at the line that writes it when found
30
+ * by name (a custom property's `--name`, a selector's class), else line 1. */
31
+ fixAt(path: string): SourceLocation;
32
+ }
33
+ export type ExtensionKind = 'component' | 'contextProvider' | 'functionLibrary';
34
+ export type Manifest = {
35
+ [key: string]: ManifestValue;
36
+ };
37
+ export type ManifestValue = Scalar | ManifestValue[] | {
38
+ [key: string]: ManifestValue;
39
+ };
40
+ export type Scalar = string | number | boolean | null | typeof UNKNOWN;
41
+ /** A file of the site (from its root) and a line in it. */
42
+ export interface SourceLocation {
43
+ file: string;
44
+ line: number;
45
+ }
46
+ /** A manifest value as the model reads it: with the place it's written in, and each child's. `toManifestValue` drops the places. */
47
+ export interface LocatedManifestValue {
48
+ place: SourceLocation;
49
+ value: Scalar | LocatedManifestValue[] | Map<string, LocatedManifestValue>;
50
+ }
51
+ /** A located value that is an object: each key's value, with its place. */
52
+ export type LocatedManifestObject = {
53
+ place: SourceLocation;
54
+ value: Map<string, LocatedManifestValue>;
55
+ };
56
+ export interface ParsedModule {
57
+ /** Every `extensions.<kind>({…})` call in the file, as an extension. */
58
+ registrations(): Extension[];
59
+ /** The module's exports, as an object: each named export, and `default`. Read once. */
60
+ exports(): LocatedManifestValue;
61
+ }
62
+ /** Another module's exports, by an import's source in this file; undefined when there's no such module. */
63
+ export type ReadImport = (from: string, source: string) => LocatedManifestValue | undefined;
64
+ /** The parser's nodes, read by field name: the evaluator reads a dozen node types, and its unions would type each by hand. */
65
+ export type SyntaxNode = AstNode & {
66
+ [key: string]: any;
67
+ };
68
+ /** A name imported from a module: the import's source, and the name it's exported under there (`default`, `*`). */
69
+ export interface ImportBinding {
70
+ source: string;
71
+ imported: string;
72
+ }
73
+ /** A name the module declares: an import, or a variable (a const's value's code; none for a let or a var, which the
74
+ * code may assign again). */
75
+ export type Binding = ImportBinding | {
76
+ init: SyntaxNode | null;
77
+ };
78
+ /** An export of the module: the local name it exports, its expression (`export default …`), or another module's export. */
79
+ export type ExportBinding = {
80
+ local: string;
81
+ } | {
82
+ expression: SyntaxNode;
83
+ } | ImportBinding;
84
+ /** What evaluating a module's code needs: its file and names, a node's place, and how to read another module. */
85
+ export interface EvaluationScope {
86
+ file: string;
87
+ bindings: Map<string, Binding>;
88
+ placeAt(node: SyntaxNode): SourceLocation;
89
+ readImport: ReadImport;
90
+ /** The consts being read: a const that reads itself is UNKNOWN. */
91
+ evaluating: Set<string>;
92
+ }
93
+ /** A function a manifest is built with: the name its package exports it under, and that package. */
94
+ export interface ManifestFunction {
95
+ name: string;
96
+ source: string;
97
+ }
98
+ /** The file a generated value is written from, by the key that names it (GENERATED_FROM), and the app's name under that key. */
99
+ export interface GeneratedSource {
100
+ key: string;
101
+ name?: string;
102
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,24 @@
1
+ import type { Rule, ProjectRule, SiteCodeRule } from './rules/index.ts';
2
+ import { type Files } from './shared/index.ts';
3
+ export { SITE_MANIFEST, TEST_PAGE } from './constants.ts';
4
+ /** For a test that runs validate() with its own inputs (packageFiles, companions) and compares each rule's problems in the order found. */
5
+ export { validateInFoundOrder } from './validate.ts';
6
+ /** A page's files: structure.jsx, layout.css and style.css, in TEST_PAGE. */
7
+ export declare function page(structure: string, layoutCss?: string, styleCss?: string): Files;
8
+ /** The site's theme.css, shared by every page. */
9
+ export declare const theme: (css: string) => Files;
10
+ /** "rule: message (line N)", for each problem the rules report on one page of these files: rule after rule (rules sharing a name
11
+ * once, as one rule), each in the order it finds them. */
12
+ export declare function lint(files: Files, rules: readonly Rule<string>[], jsxFile?: string): string[];
13
+ /** Each structure file (structure.jsx, or .tsx) as a page of one in-memory site (or in the folder given), the rule run on every page.
14
+ * siteFiles: other files of the site (its component catalog). For each: "rule (line N)" per problem, in line order. */
15
+ export declare function lintWithEslint(rule: Rule<string>, structures: {
16
+ text: string;
17
+ tsx?: boolean;
18
+ folder?: string;
19
+ }[], siteFiles?: Files): string[][];
20
+ /** "file: message" ("file:line: message" when the problem names its line), for each problem the project rule reports on a site of these files. */
21
+ export declare function checkProject(rule: ProjectRule<string>, files: Files): string[];
22
+ /** "file: message" ("file:line: message" when the problem names its line), for each problem the site-code rule reports on a site of these
23
+ * files: the rule gets the site code's model, read as validate() reads it. */
24
+ export declare function checkSiteCode(rule: SiteCodeRule<string>, files: Files): string[];
@@ -0,0 +1,61 @@
1
+ // @wix/validation-infra/testing: what a rule's tests need, in any rule package. An in-memory site, and rules run on it through
2
+ // validate(), the way a site is linted. Each result is a line a test compares whole (.agents/reference/conventions/rule-tests.md).
3
+ import { PAGE_RULES, TEST_PAGE } from "./constants.js";
4
+ import { createProjectModel } from "./project-model/index.js";
5
+ import { createExtensionReader, readSiteCodeModel } from "./site-code-model/index.js";
6
+ import { THEME_FILE } from "./shared/index.js";
7
+ import { validate, validateInFoundOrder } from "./validate.js";
8
+ export { SITE_MANIFEST, TEST_PAGE } from "./constants.js";
9
+ /** For a test that runs validate() with its own inputs (packageFiles, companions) and compares each rule's problems in the order found. */
10
+ export { validateInFoundOrder } from "./validate.js";
11
+ /** A page's files: structure.jsx, layout.css and style.css, in TEST_PAGE. */
12
+ export function page(structure, layoutCss = '', styleCss = '') {
13
+ return { [`${TEST_PAGE}/structure.jsx`]: structure, [`${TEST_PAGE}/layout.css`]: layoutCss, [`${TEST_PAGE}/style.css`]: styleCss };
14
+ }
15
+ /** The site's theme.css, shared by every page. */
16
+ export const theme = (css) => ({ [THEME_FILE]: css });
17
+ /** "rule: message (line N)", for each problem the rules report on one page of these files: rule after rule (rules sharing a name
18
+ * once, as one rule), each in the order it finds them. */
19
+ export function lint(files, rules, jsxFile = `${TEST_PAGE}/structure.jsx`) {
20
+ const problems = validateOrThrow(validateInFoundOrder, files, rules, [jsxFile]);
21
+ const names = [...new Set(rules.map((rule) => rule.name))];
22
+ return names.flatMap((name) => problems.filter((problem) => problem.rule === name).map((problem) => `${name}: ${problem.message} (line ${problem.line})`));
23
+ }
24
+ /** Each structure file (structure.jsx, or .tsx) as a page of one in-memory site (or in the folder given), the rule run on every page.
25
+ * siteFiles: other files of the site (its component catalog). For each: "rule (line N)" per problem, in line order. */
26
+ export function lintWithEslint(rule, structures, siteFiles = {}) {
27
+ const files = { ...siteFiles };
28
+ const jsxFiles = structures.map(({ text, tsx, folder }, index) => {
29
+ folder ??= `packages/site-app/src/pages/p${index}`;
30
+ for (const file of ['layout.css', 'style.css'])
31
+ files[`${folder}/${file}`] = '';
32
+ const jsxFile = `${folder}/structure.${tsx ? 'tsx' : 'jsx'}`;
33
+ files[jsxFile] = text;
34
+ return jsxFile;
35
+ });
36
+ const problems = validateOrThrow(validate, files, [rule], jsxFiles);
37
+ return jsxFiles.map((jsxFile) => problems
38
+ .filter((problem) => problem.file === jsxFile)
39
+ .map((problem) => `${rule.name} (line ${problem.line})`)
40
+ .sort((a, b) => Number(/\d+/.exec(a)) - Number(/\d+/.exec(b))));
41
+ }
42
+ /** "file: message" ("file:line: message" when the problem names its line), for each problem the project rule reports on a site of these files. */
43
+ export function checkProject(rule, files) {
44
+ const project = createProjectModel(rule.name, Object.keys(files), (file) => files[file]);
45
+ return rule.check(project).map(formatProjectProblem);
46
+ }
47
+ /** "file: message" ("file:line: message" when the problem names its line), for each problem the site-code rule reports on a site of these
48
+ * files: the rule gets the site code's model, read as validate() reads it. */
49
+ export function checkSiteCode(rule, files) {
50
+ const project = createProjectModel(rule.name, Object.keys(files), (file) => files[file]);
51
+ return rule.check(readSiteCodeModel(project.files, createExtensionReader(project.readFile)), project).map(formatProjectProblem);
52
+ }
53
+ const formatProjectProblem = ({ file, line, message }) => `${file}${line === undefined ? '' : `:${line}`}: ${message}`;
54
+ /** validate() (or validateInFoundOrder) on these files; a file that doesn't parse, or a rule that throws, throws: a test never passes on a page no rule ran on. */
55
+ function validateOrThrow(run, files, rules, only) {
56
+ const problems = run({ files, rules, only });
57
+ const broken = problems.find((problem) => problem.rule === 'parse' || problem.rule === PAGE_RULES);
58
+ if (broken)
59
+ throw new Error(`${broken.file}:${broken.line}:${broken.column}: ${broken.message}`);
60
+ return problems;
61
+ }