@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,553 @@
1
+ import { AUDIO_PREFIX, AUDIO_URL_METHOD, DATA_KEY, DOCUMENT_PREFIX, DOCUMENT_URL_METHOD, ELEMENT_PROPS, EVENT_ATTRIBUTE, EXCLUDED_DATA_KEYS, FULL_READ, GLOBAL_SECTION_MODULE_SOURCE, IMAGE_PREFIX, IMAGE_URL_METHOD, KIND_BY_IMPORT_SOURCE, NO_DATA_TYPES, NOT_A_VALUE, NOT_READ_IN_TYPES, PLAIN_READ, RESERVED_ATTRIBUTES, RESERVED_ENTRY_KEYS, SHARED_COMP_ID, STRUCTURE, TRANSFORM_BUILDERS, TYPE_BY_IMPORT_SOURCE, VISIBILITY_PREFIX, } from "./constants.js";
2
+ /** <Band> with `import { Section as Band } from '@wix/origami-system-components/Section'` → 'section'. `<Band.Item>` is Band's. A wrapper is the named export: `<Show>` from the runtime is null.
3
+ * A context provider ('provider') is known from the site's component catalog: rulesApi.getType adds it. */
4
+ export function getType(element, program) {
5
+ const found = getTagImport(element, program);
6
+ const entry = found && TYPE_BY_IMPORT_SOURCE.find(([pattern]) => pattern.test(found.source));
7
+ if (!entry)
8
+ return null;
9
+ const [, type, imported] = entry;
10
+ return imported === undefined || found.imported === imported ? type : null;
11
+ }
12
+ /** 'Header' for `<Header_mb7ogqqn>` imported from global/components/Header_mb7ogqqn, 'Footer' for a Footer_…, null for anything else
13
+ * (converter 0.97 identity.ts globalSectionModuleOf): the reference a <Page> takes in its header / footer attribute. */
14
+ export function getGlobalSectionModule(element, program) {
15
+ const found = getTagImport(element, program);
16
+ const module = found && GLOBAL_SECTION_MODULE_SOURCE.exec(found.source)?.[1];
17
+ return module === 'Header' || module === 'Footer' ? module : null;
18
+ }
19
+ /** Converter 0.81: are the tag's attributes saved as its component's data? Yes on a builder component (its import gives a componentType):
20
+ * imported, not from `document` and not from a local file. No on the DM's own tags (`Page`, the sections) and a global component's reference. */
21
+ export function hasDataAttributes(element, program) {
22
+ const found = getTagImport(element, program);
23
+ const type = getType(element, program);
24
+ return found !== null && found.kind !== 'core' && !found.source.startsWith('.') && !(type && NO_DATA_TYPES.includes(type));
25
+ }
26
+ /** What an import's source is: 'runtime' for @wix/origami-runtime, 'interact' for @wix/interact/…; null for anything else. */
27
+ export const getImportKind = (source) => KIND_BY_IMPORT_SOURCE.find(([pattern]) => pattern.test(source))?.[1] ?? null;
28
+ /** Where a name of the file comes from; null when no import brings it in. */
29
+ export function getImport(name, program) {
30
+ for (const { source, specifiers } of program.body.filter(isImport)) {
31
+ const specifier = specifiers.find(({ local }) => local.name === name);
32
+ if (!specifier)
33
+ continue;
34
+ return { imported: getImportedName(specifier), source: source.value, kind: getImportKind(source.value) };
35
+ }
36
+ return null;
37
+ }
38
+ /** The import of a tag: of `Band` for <Band.Item>; null when nothing imports it. */
39
+ export const getTagImport = (element, program) => getImport(getTagName(element).split('.')[0], program);
40
+ /** The name a specifier is exported under: `import X` → 'default', `import * as X` → '*', `import { Remove as Hide }` → 'Remove', `import { 'a-b' as ab }` → 'a-b'. */
41
+ export function getImportedName({ type, imported }) {
42
+ if (type === 'ImportDefaultSpecifier')
43
+ return 'default';
44
+ if (type === 'ImportNamespaceSpecifier')
45
+ return '*';
46
+ return typeof imported?.name === 'string' ? imported.name : String(imported?.value);
47
+ }
48
+ /** 'Section', 'Band.Item', 'svg:rect'. */
49
+ export function getTagName(element) {
50
+ const text = (name) => {
51
+ if (name.type === 'JSXIdentifier')
52
+ return name.name;
53
+ if (name.type === 'JSXNamespacedName')
54
+ return `${name.namespace.name}:${name.name.name}`;
55
+ return `${text(name.object)}.${name.property.name}`;
56
+ };
57
+ return text(element.openingElement.name);
58
+ }
59
+ /** An attribute's value as a string: x="a" and x={'a'} → 'a'; no value, or any other expression → null. */
60
+ export function getLiteralString(value) {
61
+ const literal = value?.type === 'JSXExpressionContainer' ? value.expression : value;
62
+ return literal?.type === 'Literal' && typeof literal.value === 'string' ? literal.value : null;
63
+ }
64
+ /** id="sec" and id={'sec'} → 'sec'; no id, or id={variable} → null. */
65
+ export function getId(element) {
66
+ return getLiteralString(getAttribute(element, 'id')?.value);
67
+ }
68
+ /** The elements this one holds in its attributes (`content={<X />}`, or inside the attribute's object or array, `elementProps` too), each with the attribute it is in, its name, and its path: the name, then a step per object key down to the element; an array item's position goes on the step of the key that holds the array. Not its children, and not the elements inside those elements.
69
+ * path is null when the way has no such spelling: a computed key, an array item that isn't an object (an element directly in an array, an array in an array). */
70
+ export function getAttributeElements(owner) {
71
+ const elementsIn = (written, path) => {
72
+ const value = written && bare(written);
73
+ switch (value?.type) {
74
+ case 'JSXElement': return [{ element: value, path }];
75
+ case 'JSXExpressionContainer': return elementsIn(value.expression, path);
76
+ case 'ObjectExpression': return value.properties.flatMap((property) => {
77
+ const key = getKeyName(property);
78
+ return property.type === 'Property' ? elementsIn(property.value, path && key !== null ? [...path, { key }] : null) : [];
79
+ });
80
+ case 'ArrayExpression': return value.elements.flatMap((item, index) => elementsIn(item, path && item && bare(item).type === 'ObjectExpression' ? [...path.slice(0, -1), { key: path.at(-1).key, index }] : null));
81
+ default: return [];
82
+ }
83
+ };
84
+ return owner.openingElement.attributes.filter(isAttribute).flatMap((attribute) => {
85
+ const name = getName(attribute);
86
+ return elementsIn(attribute.value, [{ key: name }]).map(({ element, path }) => ({ element, attribute: attribute, name, path }));
87
+ });
88
+ }
89
+ /** An attribute's value as plain data: literals (including a negative number such as `-1`), objects and arrays. undefined for what has no known value (no such attribute, an element, a variable, a call); inside an object or array such a value stays as undefined in its place. A computed key and a spread are left out. */
90
+ export function getAttributeValue(owner, name) {
91
+ const valueOf = (written) => {
92
+ const value = written && bare(written);
93
+ switch (value?.type) {
94
+ case 'Literal': return value.value instanceof RegExp ? undefined : typeof value.value === 'bigint' ? Number(value.value) : value.value;
95
+ case 'JSXExpressionContainer': return valueOf(value.expression);
96
+ case 'UnaryExpression': {
97
+ const argument = value.argument && bare(value.argument);
98
+ const number = value.operator === '-' && argument?.type === 'Literal' ? valueOf(argument) : undefined;
99
+ return typeof number === 'number' ? -number : undefined;
100
+ }
101
+ case 'ObjectExpression': return Object.fromEntries(value.properties.flatMap((property) => {
102
+ const key = getKeyName(property);
103
+ return property.type === 'Property' && key !== null ? [[key, valueOf(property.value)]] : [];
104
+ }));
105
+ case 'ArrayExpression': return value.elements.map(valueOf);
106
+ default: return undefined;
107
+ }
108
+ };
109
+ return valueOf(getAttribute(owner, name)?.value);
110
+ }
111
+ /** The interaction key, as componentClassOf reads it: a string's first space-delimited word or an array's first string item; null for a non-literal, never the id. */
112
+ export function getComponentClass(element) {
113
+ const className = getAttributeValue(element, 'className');
114
+ if (typeof className === 'string')
115
+ return className.split(' ')[0];
116
+ return Array.isArray(className) && typeof className[0] === 'string' ? className[0] : null;
117
+ }
118
+ /** `a`, `'a'` → 'a'; a computed key, or one that isn't a name or a string → null. */
119
+ const getKeyName = (property) => property.computed || !property.key ? null : property.key.type === 'Identifier' ? (property.key.name ?? null) : property.key.type === 'Literal' && typeof property.key.value === 'string' ? property.key.value : null;
120
+ /** Elements, text and {expressions}, in order. Whitespace and JSX comments are skipped. */
121
+ export function getChildren(element) {
122
+ return element.children.filter((child) => {
123
+ if (child.type === 'JSXText')
124
+ return String(child.value).trim() !== '';
125
+ return !(child.type === 'JSXExpressionContainer' && child.expression?.type === 'JSXEmptyExpression');
126
+ });
127
+ }
128
+ /** The element's attribute with this name (`a:b` for a namespaced one); undefined without one. A tool's element gives the tool's attribute. */
129
+ export function getAttribute(element, name) {
130
+ return element.openingElement.attributes.find((attribute) => isAttribute(attribute) && getName(attribute) === name);
131
+ }
132
+ /** The attribute's name: `type`, or `a:b` for a namespaced one. */
133
+ export const getName = (attribute) => (attribute.name.type === 'JSXIdentifier' ? attribute.name.name : `${attribute.name.namespace.name}:${attribute.name.name.name}`);
134
+ /** What the attribute's {…} holds, without parentheses; null for a string value, no value, or `{}`. */
135
+ export function getExpression(attribute) {
136
+ const value = attribute?.value;
137
+ if (value?.type !== 'JSXExpressionContainer' || value.expression.type === 'JSXEmptyExpression')
138
+ return null;
139
+ return bare(value.expression);
140
+ }
141
+ /** The object written out in a value, in parentheses or in an attribute's `{…}`: `x={{ a: 1 }}` → `{ a: 1 }`; null for any other value. */
142
+ export function getObject(node) {
143
+ if (!node)
144
+ return null;
145
+ const value = node.type === 'JSXAttribute' ? getExpression(node) : bare(node);
146
+ return value?.type === 'ObjectExpression' ? value : null;
147
+ }
148
+ /** Not the component's data: the converter's reserved attributes, and `sharedCompId` (reservedAttributes.ts). */
149
+ export const isReservedAttribute = (name) => RESERVED_ATTRIBUTES.includes(name) || name === SHARED_COMP_ID;
150
+ /** The node inside its parentheses: `((x))` → `x`. */
151
+ export function bare(node) {
152
+ return node.type === 'ParenthesizedExpression' ? bare(node.expression) : node;
153
+ }
154
+ /** An object's `key: value` entries: no spread, no computed key. */
155
+ export const getProperties = (object) => object.properties.filter((property) => property.type === 'Property' && !property.computed);
156
+ /** The object's entry with this key; undefined without one. */
157
+ export const getProperty = (object, key) => getProperties(object).find((property) => getKey(property) === key);
158
+ /** null for a number key: the import reads only name and string keys, and fails on any other. */
159
+ export function getKey(property) {
160
+ if (property.key.type === 'Identifier')
161
+ return property.key.name;
162
+ return property.key.type === 'Literal' && typeof property.key.value === 'string' ? property.key.value : null;
163
+ }
164
+ /** The names a `className` array declares after its class, as the import reads its terms (parseJsx.ts splitClassName): its strings, split on
165
+ * spaces, and its objects' keys: `['comp-x', 'open', { hover: … }]` → 'open', 'hover'. None for a className that isn't an array. */
166
+ export function getClassNameTerms(element) {
167
+ const className = getExpression(getAttribute(element, 'className'));
168
+ if (className?.type !== 'ArrayExpression')
169
+ return [];
170
+ return className.elements.slice(1).flatMap((term) => {
171
+ if (term?.type === 'Literal' && typeof term.value === 'string')
172
+ return term.value.split(/\s+/).filter(Boolean);
173
+ return term?.type === 'ObjectExpression' ? getProperties(term).map((property) => getKey(property) ?? '') : [];
174
+ });
175
+ }
176
+ /** The inner elements' own states, the classes the runtime writes for an `elementProps` entry's className keys, at any depth: `<class>-<key>--<name>`
177
+ * (css-codec/states.ts applicativeClassPrefixOf:250, parse/fromBundle.ts applicativeClassesOfJsx:760): `elementProps={{ label: { className: { busy: … } } }}` →
178
+ * 'comp-btn-label--busy'. */
179
+ export function getInnerElementStates(node, className) {
180
+ return new Set(getElementPropsEntries(node).flatMap(({ key, entry }) => {
181
+ const terms = getObject(getProperty(entry, 'className')?.value);
182
+ return (terms ? getProperties(terms) : []).flatMap((term) => {
183
+ const name = getKey(term);
184
+ return name && !name.startsWith(VISIBILITY_PREFIX) ? [`${className}-${key}--${name}`] : [];
185
+ });
186
+ }));
187
+ }
188
+ /** An element's `elementProps` entries, at any depth: each entry, then the entries of its own `elementProps`. An entry with no string key or no object
189
+ * value is left out, and so are the entries under it. */
190
+ export function getElementPropsEntries(element) {
191
+ return getEntries(getObject(getAttribute(element, ELEMENT_PROPS)), []);
192
+ }
193
+ function getEntries(elementProps, path) {
194
+ if (!elementProps)
195
+ return [];
196
+ return getProperties(elementProps).flatMap((property) => {
197
+ const key = getKey(property);
198
+ const entry = getObject(property.value);
199
+ if (key === null || !entry)
200
+ return [];
201
+ const at = [...path, key];
202
+ return [{ key, entry, path: at }, ...getEntries(getObject(getProperty(entry, ELEMENT_PROPS)?.value), at)];
203
+ });
204
+ }
205
+ /** A top-level function or variable declaration, including a named export; nested helpers do not count. */
206
+ export function findDeclaration(program, name) {
207
+ for (const statement of program.body) {
208
+ const node = statement.type === 'ExportNamedDeclaration' ? statement.declaration : statement;
209
+ if (node?.type === 'FunctionDeclaration' && node.id?.name === name)
210
+ return node;
211
+ if (node?.type === 'VariableDeclaration') {
212
+ const declarator = node.declarations.find((declaration) => declaration.id.type === 'Identifier' && declaration.id.name === name);
213
+ if (declarator)
214
+ return declarator;
215
+ }
216
+ }
217
+ return null;
218
+ }
219
+ /** The function `export const Structure = () => …` at the top of the file. Any `Structure` declarator counts, as the page model reads it; no-free-code reports a wrong form. */
220
+ export function isStructure(node) {
221
+ const declarator = node.parent;
222
+ return declarator?.type === 'VariableDeclarator' && declarator.id?.type === 'Identifier' && declarator.id.name === STRUCTURE
223
+ && declarator.parent?.parent?.type === 'ExportNamedDeclaration' && declarator.parent.parent.parent?.type === 'Program';
224
+ }
225
+ /** The import reads the element: it is not inside a function other than Structure or a renderItem template, a call, a condition, or an {expression} child. */
226
+ export function isReadByImport(element) {
227
+ for (let up = element.parent; up.type !== 'JSXElement' && up.type !== 'Program'; up = up.parent) {
228
+ if (up.type === 'ArrowFunctionExpression')
229
+ return isStructure(up) || getCallbackKind(up) === 'template';
230
+ if (NOT_READ_IN_TYPES.includes(up.type) || (up.type === 'JSXExpressionContainer' && up.parent.type !== 'JSXAttribute'))
231
+ return false;
232
+ }
233
+ return true;
234
+ }
235
+ /** The node's parent, past parentheses, and its child on the way up: the node itself, or the parentheses around it. */
236
+ function getOuter(node) {
237
+ let child = node;
238
+ while (child.parent?.type === 'ParenthesizedExpression')
239
+ child = child.parent;
240
+ return [child.parent, child];
241
+ }
242
+ /** The callbacks whose parameters the import reads as bindings: 'template' for a slot's template, `renderItem={(item, index, length) => <X />}`, an attribute's
243
+ * arrow that returns one element (parseJsx.ts templateCallbackOf); 'transform' for `map(source, (item, index) => ({…}))` and `shape(source, (obj) => ({…}))`
244
+ * (astValue.ts transformCallbackOf). null for any other node. */
245
+ export function getCallbackKind(syntax) {
246
+ const node = syntax;
247
+ if (node.type !== 'ArrowFunctionExpression')
248
+ return null;
249
+ const body = node.body && bare(node.body);
250
+ const [outer, child] = getOuter(node);
251
+ if (body?.type === 'JSXElement' && outer?.type === 'JSXExpressionContainer' && outer.parent?.type === 'JSXAttribute')
252
+ return 'template';
253
+ const isTransform = outer?.type === 'CallExpression' && outer.callee?.type === 'Identifier' && TRANSFORM_BUILDERS.includes(outer.callee.name) && outer.arguments?.[1] === child;
254
+ return isTransform ? 'transform' : null;
255
+ }
256
+ /** A read of a callback's parameter, `item`, `item.name`, `item['link-1']`, which the import reads as a binding (astValue.ts templateReadOf):
257
+ * 'template' off a renderItem's parameter, 'transform' off a map() or shape() callback's. null for any other value, or inside any other function. */
258
+ export function getParamReadKind(syntax) {
259
+ const node = syntax;
260
+ let root = node;
261
+ while (root.type === 'MemberExpression' && root.object)
262
+ root = root.object;
263
+ if (root.type !== 'Identifier')
264
+ return null;
265
+ for (let up = node.parent; up && up.type !== 'Program'; up = up.parent) {
266
+ if (up.type !== 'ArrowFunctionExpression' && up.type !== 'FunctionExpression')
267
+ continue;
268
+ const kind = getCallbackKind(up);
269
+ if (!kind)
270
+ return null;
271
+ if (up.params?.some((param) => param.type === 'Identifier' && param.name === root.name))
272
+ return kind;
273
+ }
274
+ return null;
275
+ }
276
+ /** A call, or a read of a renderItem / map() parameter (`item.name`): the import reads it as a binding, not as data (parseJsx.ts takeBoundProp).
277
+ * Any call: the bindings rule reports one that isn't a builder. Not `a ?? b` (isFallback): a rule that takes it reads its sides itself, as
278
+ * data-values does with a row read and its stored data. */
279
+ export const isBound = (value) => !!value && (value.type === 'CallExpression' || getParamReadKind(value) !== null);
280
+ /** `a ?? b`: since converter 0.104 the import reads it only as a renderItem row read with its stored data on the right (parseJsx.ts takeBoundProp). */
281
+ export const isFallback = (value) => value.type === 'LogicalExpression' && value.operator === '??';
282
+ /** The stored data of `attr={item.x ?? data}`, a renderItem read with its data (converter 0.103, DM-16073): the import reads the right side as the
283
+ * attribute's data. The left side is read through names or string keys only (astValue.ts templateReadOf), and the right side isn't a read
284
+ * (parseJsx.ts takeBoundProp). Any other value, as it is. */
285
+ export function getStoredData(value) {
286
+ return value && isFallback(value) && getParamReadKind(value.left) === 'template' && isNamedRead(value.left) && !getParamReadKind(value.right) ? value.right : value;
287
+ }
288
+ const isNamedRead = (node) => node.type !== 'MemberExpression' || ((!node.computed || (node.property.type === 'Literal' && typeof node.property.value === 'string')) && isNamedRead(node.object));
289
+ /** `{ placeholder: … }` alone: a call's options, not a data item (decode.ts isPlaceholderOptions). */
290
+ export const isPlaceholderOptions = (object) => object.properties.length === 1 && getProperties(object).length === 1 && getKey(getProperties(object)[0]) === 'placeholder';
291
+ /** A component in a message: `<Image>` img, or `<Image>` when it has no id. */
292
+ export function ownerOf(element) {
293
+ const id = getId(element);
294
+ return `\`<${getTagName(element)}>\`${id ? ` ${id}` : ''}`;
295
+ }
296
+ /** One letter added, removed or changed, as the converter counts it (dataKeys.ts, reservedAttrNearMiss). */
297
+ export function isOneEditAway(name, target) {
298
+ const delta = name.length - target.length;
299
+ if (name === target || Math.abs(delta) > 1)
300
+ return false;
301
+ let edits = 0;
302
+ for (let i = 0, j = 0; i < name.length || j < target.length;) {
303
+ if (name[i] === target[j]) {
304
+ i++;
305
+ j++;
306
+ continue;
307
+ }
308
+ if (edits === 1)
309
+ return false;
310
+ edits = 1;
311
+ if (delta >= 0)
312
+ i++;
313
+ if (delta <= 0)
314
+ j++;
315
+ }
316
+ return true;
317
+ }
318
+ /** A TypeScript node (`TSTypeAnnotation`, `TSAsExpression`…), an `import type` / `export type` / `{ type Y }`, or a `declare` / `abstract` declaration. JavaScript, null and undefined: false. */
319
+ export function isTypeScript(node) {
320
+ return !!node && (node.type.startsWith('TS') || node.importKind === 'type' || node.exportKind === 'type' || node.declare === true || node.abstract === true);
321
+ }
322
+ /** The names a function destructures from its one parameter: `({ id, className })` → ['id', 'className']. A property with a default, a new name, a computed key or `...rest` is null. `()` and `({})` → []; any other parameters → null. */
323
+ export function getPropNames(fn) {
324
+ if (fn.params.length === 0)
325
+ return [];
326
+ const [param] = fn.params;
327
+ if (fn.params.length > 1 || param.type !== 'ObjectPattern')
328
+ return null;
329
+ return (param.properties ?? []).map(({ type, computed, key, value }) => type === 'Property' && !computed && key?.type === 'Identifier' && value?.type === 'Identifier' && value.name === key.name ? String(key.name) : null);
330
+ }
331
+ export const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
332
+ const isImport = (statement) => statement.type === 'ImportDeclaration';
333
+ const isAttribute = (attribute) => attribute.type === 'JSXAttribute';
334
+ // ── a data value, as the import reads it (data-values' reader; page-structure reads a page's data with it too) ──
335
+ const isProperty = (node, name) => node.type === 'MemberExpression' && !node.computed && !node.optional && node.property.type === 'Identifier' && node.property.name === name;
336
+ const isImportedAs = (node, rulesApi, kind, imported) => {
337
+ if (node.type !== 'Identifier')
338
+ return false;
339
+ const found = rulesApi.getImport(node);
340
+ return found?.kind === kind && (imported === undefined || found.imported === imported);
341
+ };
342
+ /** `media.<method>(…)`, with `media` imported from '@wix/sdk'. */
343
+ export function isMediaCall(node, method, rulesApi) {
344
+ if (node.type !== 'CallExpression' || node.optional || node.callee.type !== 'MemberExpression' || !isProperty(node.callee, method))
345
+ return false;
346
+ return isImportedAs(node.callee.object, rulesApi, 'sdk', 'media');
347
+ }
348
+ /** `media.getCroppedImageUrl('wix:image://v1/…', …)` with the export's eight arguments. */
349
+ export function isImageCall(node, rulesApi) {
350
+ if (!isMediaCall(node, IMAGE_URL_METHOD, rulesApi) || node.arguments.length !== 8)
351
+ return false;
352
+ const id = getDataValue(node.arguments[0]);
353
+ return typeof id === 'string' && id.startsWith(IMAGE_PREFIX);
354
+ }
355
+ /** The identifier in `media.getDocumentUrl('wix:document://v1/…').url`; null for any other value. */
356
+ export function getDocumentIdentifier(node, rulesApi) {
357
+ if (!isProperty(node, 'url') || node.type !== 'MemberExpression')
358
+ return null;
359
+ const call = node.object;
360
+ if (!isMediaCall(call, DOCUMENT_URL_METHOD, rulesApi) || call.arguments.length !== 1)
361
+ return null;
362
+ const identifier = getDataValue(call.arguments[0]);
363
+ return typeof identifier === 'string' && identifier.startsWith(DOCUMENT_PREFIX) ? identifier : null;
364
+ }
365
+ /** The identifier in `media.getAudioUrl('wix:audio://v1/…').url`, or `.duration` when property is 'duration'; null for any other value (converter 0.112,
366
+ * audioExpression.ts:88 resolveAudioExpression). */
367
+ export function getAudioIdentifier(node, rulesApi, property = 'url') {
368
+ if (!isProperty(node, property) || node.type !== 'MemberExpression')
369
+ return null;
370
+ const call = node.object;
371
+ if (!isMediaCall(call, AUDIO_URL_METHOD, rulesApi) || call.arguments.length !== 1)
372
+ return null;
373
+ const identifier = getDataValue(call.arguments[0]);
374
+ return typeof identifier === 'string' && identifier.startsWith(AUDIO_PREFIX) ? identifier : null;
375
+ }
376
+ /** The first part of a value the import can't read as data (astValue.ts), or null when it reads all of it: a string, a number, true / false,
377
+ * null, a negative number, a call by name (a builder: the bindings rule's), an element, a menu or media reference, and an array or object of
378
+ * these. */
379
+ export const getNonLiteral = (node, rulesApi, getText, path = '') => nonLiteralIn(node, FULL_READ, rulesApi, getText, path);
380
+ /** An object's first part the import can't read as data: each level is checked whole (its entries, then its keys once) before the values inside it, as the import does. readValue reads each value (getNonLiteral by default). */
381
+ export const getNonLiteralInObject = (object, rulesApi, getText, path, readValue) => nonLiteralInObject(object, FULL_READ, rulesApi, getText, path, readValue);
382
+ function nonLiteralIn(node, mode, rulesApi, getText, path = '') {
383
+ if (node === null)
384
+ return null;
385
+ const value = bare(node);
386
+ switch (value.type) {
387
+ case 'Literal':
388
+ return ['string', 'number', 'boolean'].includes(typeof value.value) || value.raw === 'null' ? null : { node: value, what: `\`${value.raw}\`, which isn't a string, number, true / false or null` };
389
+ case 'UnaryExpression':
390
+ return value.operator === '-' && value.argument.type === 'Literal' && typeof value.argument.value === 'number' ? null : { node: value, what: `\`${getText(value)}\`` };
391
+ case 'Identifier':
392
+ if (mode.menus && isImportedAs(value, rulesApi, 'menu'))
393
+ return null;
394
+ return { node: value, what: `the variable \`${value.name}\`` };
395
+ case 'MemberExpression':
396
+ if (mode.menus && isProperty(value, 'items') && isImportedAs(value.object, rulesApi, 'menu'))
397
+ return null;
398
+ if (mode.media && getDocumentIdentifier(value, rulesApi) !== null)
399
+ return null;
400
+ if (mode.media && (getAudioIdentifier(value, rulesApi) ?? getAudioIdentifier(value, rulesApi, 'duration')) !== null)
401
+ return null;
402
+ return { node: value, what: `\`${getText(value)}\`` };
403
+ case 'CallExpression':
404
+ if (value.callee.type === 'Identifier')
405
+ return null;
406
+ if (mode.media && isImageCall(value, rulesApi))
407
+ return value.arguments.map((argument) => nonLiteralIn(argument, PLAIN_READ, rulesApi, getText)).find(Boolean) ?? null;
408
+ return { node: value, what: `a call to \`${getText(value.callee)}\`` };
409
+ case 'JSXElement':
410
+ return mode.jsx ? null : { node: value, what: 'an element' };
411
+ case 'FunctionExpression':
412
+ case 'ArrowFunctionExpression':
413
+ return { node: value, what: 'a function' };
414
+ case 'TemplateLiteral':
415
+ return { node: value, what: `a template string (\`${getText(value)}\`)` };
416
+ case 'ArrayExpression':
417
+ if (value.elements.some((element) => element === null || element.type === 'SpreadElement'))
418
+ return { node: value, what: 'an array with a spread or an empty place (`[a, , b]`)' };
419
+ return value.elements.map((element) => nonLiteralIn(element, mode, rulesApi, getText)).find(Boolean) ?? null;
420
+ case 'ObjectExpression':
421
+ return nonLiteralInObject(value, mode, rulesApi, getText, path);
422
+ default:
423
+ return { node: value, what: `\`${getText(value)}\`` };
424
+ }
425
+ }
426
+ function nonLiteralInObject(object, mode, rulesApi, getText, path, readValue) {
427
+ const keys = new Set();
428
+ for (const property of object.properties) {
429
+ if (property.type === 'SpreadElement')
430
+ return { node: property, what: `a spread (\`${getText(property)}\`)` };
431
+ if (property.computed || property.kind !== 'init')
432
+ return { node: property, what: `\`${getText(property)}\`, which isn't a \`key: value\` entry` };
433
+ const key = getKey(property);
434
+ if (key === null)
435
+ return { node: property, what: `the key \`${getText(property.key)}\`, which isn't a name or a string` };
436
+ const dotted = path ? `${path}.${key}` : key;
437
+ if (keys.has(key))
438
+ return { node: property, what: `the key \`${dotted}\` twice` };
439
+ keys.add(key);
440
+ }
441
+ const read = readValue ?? ((property, at) => nonLiteralIn(property.value, mode, rulesApi, getText, at));
442
+ for (const property of getProperties(object)) {
443
+ const found = read(property, path ? `${path}.${getKey(property)}` : getKey(property));
444
+ if (found)
445
+ return found;
446
+ }
447
+ return null;
448
+ }
449
+ /** A value written out, as plain data: a string, a number, true / false, null, a negative number, and an array or object of these. NOT_A_VALUE for anything else, or when anything inside is. */
450
+ export function getDataValue(node) {
451
+ if (node === null)
452
+ return NOT_A_VALUE;
453
+ const value = bare(node);
454
+ if (value.type === 'Literal')
455
+ return value.raw === 'null' || ['string', 'number', 'boolean'].includes(typeof value.value) ? value.value : NOT_A_VALUE;
456
+ if (value.type === 'UnaryExpression')
457
+ return value.operator === '-' && value.argument.type === 'Literal' && typeof value.argument.value === 'number' ? -value.argument.value : NOT_A_VALUE;
458
+ if (value.type === 'ArrayExpression') {
459
+ const items = value.elements.map((element) => (element && element.type !== 'SpreadElement' ? getDataValue(element) : NOT_A_VALUE));
460
+ return items.includes(NOT_A_VALUE) ? NOT_A_VALUE : items;
461
+ }
462
+ if (value.type !== 'ObjectExpression' || getProperties(value).length !== value.properties.length)
463
+ return NOT_A_VALUE;
464
+ const entries = getProperties(value).map((property) => [getKey(property), getDataValue(property.value)]);
465
+ return entries.some(([key, item]) => key === null || item === NOT_A_VALUE) ? NOT_A_VALUE : Object.fromEntries(entries);
466
+ }
467
+ /** Never data, as an attribute or a key (dataKeys.ts): an excluded name, `data-*`, `aria-*`, an `on…` event, or a name that isn't a data key. */
468
+ export const isExcludedDataKey = (name) => EXCLUDED_DATA_KEYS.includes(name) || name.startsWith('data-') || name.startsWith('aria-') || EVENT_ATTRIBUTE.test(name) || !DATA_KEY.test(name);
469
+ /** The reserved attribute this name is one edit away from (a typo the converter refuses); undefined for none. */
470
+ export const getReservedNearMiss = (name) => RESERVED_ATTRIBUTES.find((target) => isOneEditAway(name, target));
471
+ /** A builder component's attribute the import saves as its data: not reserved, not excluded, and not a reserved name's near miss. */
472
+ export const isDataName = (name) => !isReservedAttribute(name) && !isExcludedDataKey(name) && getReservedNearMiss(name) === undefined;
473
+ /** An elementProps value's first part the import can't read as data, as it reads an inner part's entry (parseJsx.ts innerElementNodeOfValue):
474
+ * an entry's `bindings` and `className`, and a bound value of its own (a call, a template's or a transform's param), are bindings, not data.
475
+ * A data key's `item.x ?? data` is read by its stored data (getStoredData). */
476
+ export function getNonLiteralInElementProps(node, rulesApi, getText, path = '') {
477
+ const map = getObject(node);
478
+ if (!map)
479
+ return getNonLiteral(node, rulesApi, getText, path);
480
+ const readEntry = (property, at) => {
481
+ const key = getKey(property);
482
+ const value = bare(RESERVED_ENTRY_KEYS.includes(key) ? property.value : getStoredData(property.value));
483
+ if (key === 'bindings' || key === 'className' || (!RESERVED_ENTRY_KEYS.includes(key) && isBound(value)))
484
+ return null;
485
+ return key === 'elementProps' ? getNonLiteralInElementProps(value, rulesApi, getText, at) : getNonLiteral(value, rulesApi, getText, at);
486
+ };
487
+ return getNonLiteralInObject(map, rulesApi, getText, path, (property, at) => {
488
+ const entry = getObject(property.value);
489
+ return entry ? getNonLiteralInObject(entry, rulesApi, getText, at, readEntry) : getNonLiteral(property.value, rulesApi, getText, at);
490
+ });
491
+ }
492
+ /** An object literal's values; none for anything else. */
493
+ export const getPropertyValues = (value) => {
494
+ const object = getObject(value);
495
+ return object ? getProperties(object).map((property) => property.value) : [];
496
+ };
497
+ /** The value at `keys` through nested object literals, or undefined. */
498
+ export const getObjectValue = (node, ...keys) => keys.reduce((value, key) => (getObject(value) ? getProperty(getObject(value), key)?.value : undefined), node);
499
+ /** An array literal's items, holes and spreads left out; none for anything else. */
500
+ export const getArrayItems = (value) => value && bare(value).type === 'ArrayExpression' ? bare(value).elements.filter((element) => element !== null && element.type !== 'SpreadElement') : [];
501
+ export const getJSXAttributes = (element) => element.openingElement.attributes.filter((attribute) => attribute.type === 'JSXAttribute');
502
+ /** The attributes the import saves as the component's data: none on a tag without data attributes; not a reserved, excluded or bound one, nor a renderItem. */
503
+ export const getDataAttributes = (element, reader) => !reader.hasDataAttributes(element) ? [] : getJSXAttributes(element).filter((attribute) => isDataName(getName(attribute)) && !isBound(getExpression(attribute)) && getCallbackKind(getExpression(attribute) ?? attribute) !== 'template');
504
+ /** An elementProps entry's keys the import saves as data: not a reserved entry key, nor a bound one. */
505
+ export const getEntryDataKeys = (entry) => getProperties(entry).filter((property) => getKey(property) !== null && !RESERVED_ENTRY_KEYS.includes(getKey(property)) && !isBound(bare(property.value)));
506
+ /**
507
+ * The objects the import reads as an argument's data item, in any attribute (decode.ts callOptionsOf, decodeDataRef): each object argument of an
508
+ * `fn()` or a `callback()` after its function, or of a called ctx() or row member, but a `{ placeholder }`. The bindings rule checks the rest.
509
+ */
510
+ export function getDataItemArguments(element, reader) {
511
+ const found = [];
512
+ const walk = (node) => {
513
+ if (node === null)
514
+ return;
515
+ const value = bare(node);
516
+ if (value.type === 'ArrayExpression')
517
+ for (const element of value.elements)
518
+ if (element && element.type !== 'SpreadElement')
519
+ walk(element);
520
+ if (value.type === 'ObjectExpression')
521
+ for (const property of getProperties(value))
522
+ walk(property.value);
523
+ // a map() or shape() callback's object is read in its own scope, with its fn() calls (astValue.ts transformEntriesOf)
524
+ if (value.type === 'ArrowFunctionExpression' && getCallbackKind(value) === 'transform')
525
+ walk(value.body);
526
+ if (value.type !== 'CallExpression')
527
+ return;
528
+ const takes = getDataItemsTakenBy(value, reader);
529
+ value.arguments.forEach((argument, index) => {
530
+ if (argument.type === 'SpreadElement')
531
+ return;
532
+ const object = bare(argument);
533
+ if (takes && index >= takes.from && object.type === 'ObjectExpression' && !isPlaceholderOptions(object))
534
+ found.push({ node: object, label: takes.label });
535
+ else
536
+ walk(argument);
537
+ });
538
+ };
539
+ for (const attribute of getJSXAttributes(element))
540
+ walk(getExpression(attribute));
541
+ return found;
542
+ }
543
+ /** A call whose arguments are data items (decode.ts functionLibraryBindingOf, decodeCallback, methodBindingOf): from which argument, and how a message names one. */
544
+ function getDataItemsTakenBy(call, reader) {
545
+ const { callee } = call;
546
+ if (callee.type === 'Identifier') {
547
+ const builder = reader.getBuilder(call);
548
+ return builder === 'fn' ? { from: 1, label: 'an `fn()` argument' } : builder === 'callback' ? { from: 1, label: 'a `callback()` argument' } : null;
549
+ }
550
+ const isCalledCtx = reader.getBuilder(callee) === 'ctx';
551
+ const isRowMember = callee.type === 'MemberExpression' && getParamReadKind(callee) === 'template';
552
+ return isCalledCtx || isRowMember ? { from: 0, label: 'an argument of a called `ctx()` or row member' } : null;
553
+ }
@@ -0,0 +1,31 @@
1
+ import type { ContractVar, ReadPackageFile, SelectorSegment, WrapperContract } from './types.ts';
2
+ /** A block's key: its compounds and combinators, one space apart, the last compound's state classes taken off ('.label.button__label--hover'
3
+ * → '.label', '.wrapper>.label:hover' → '.wrapper > .label'); null when the last has no class or type. */
4
+ export declare function blockKey(segments: string[]): string | null;
5
+ /** A reader of the wrappers' contracts, each resolved once per source and structure file and parsed once per file: the contract found as
6
+ * the site's node finds `<source>/component-contract.json`, else `<source>/css`, from the structure file; null when the package has neither.
7
+ * A system component has only the JSON (`@wix/origami-system-components/InternalContainer/component-contract.json`), which messages then name. */
8
+ export declare function createContractReader(readPackageFile: ReadPackageFile): (source: string, fromFile: string) => WrapperContract | null;
9
+ /** Whether a var is one of a block's own (the root's, or a part's: '.label'), not a nested component's. */
10
+ export declare const isBlockVar: ({ root }: Pick<WrapperContract, "root">, block: string) => ({ nested, inline }: ContractVar) => boolean;
11
+ /** A part's element and classes as written, its other states left out: `.button.hamburger-close-button`. */
12
+ export declare const getWrittenPart: ({ base, states }: SelectorSegment) => string;
13
+ /** The nested component's selector a part is, as written, with or without more classes after it: the longest it matches; undefined for none.
14
+ * @deprecated Use getNestedElement, which finds it as the build does. */
15
+ export declare function getNestedSelector(part: SelectorSegment, nested: string[]): string | undefined;
16
+ /** The nested component a rule's parts (after the component's own) name, as the build resolves an enum's element (origami-transforms
17
+ * element-match, element-match.ts): its classes in any order, with more classes; the one matched nearest the end wins, the more specific on a
18
+ * tie. `last` when it's the last compound (not when the rule styles one of its parts); undefined for none, or one a `+` or `~` goes past (its
19
+ * sibling isn't its part, and DMS's converter matches the contract's combinators). Ported from origami-lint at 76488285. */
20
+ export declare function getNestedElement(parts: SelectorSegment[], nested: string[]): {
21
+ selector: string;
22
+ last: boolean;
23
+ } | undefined;
24
+ /** A compound's element and the state classes after it, its pseudo-classes and attributes left out, as defaults.css writes a state
25
+ * (a functional state's `${selector}.${className}`, erc/defaultsCss.ts): the element is its type and first class, the rest are states: `.label.button__label--hover`
26
+ * → '.label', ['button__label--hover']; `.button.selected` → '.button', ['selected']; a type's class with `--` is a state too: `a.button--hover`
27
+ * → 'a', ['button--hover']. */
28
+ export declare function splitCompound(compound: string): {
29
+ element: string;
30
+ states: string[];
31
+ };