@builder.io/mitosis 0.0.80 → 0.0.82

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 (49) hide show
  1. package/dist/src/generators/alpine/generate.js +3 -2
  2. package/dist/src/generators/angular.js +67 -28
  3. package/dist/src/generators/helpers/context.d.ts +2 -0
  4. package/dist/src/generators/helpers/context.js +10 -2
  5. package/dist/src/generators/html.js +42 -20
  6. package/dist/src/generators/marko/generate.js +21 -15
  7. package/dist/src/generators/mitosis.d.ts +2 -1
  8. package/dist/src/generators/mitosis.js +5 -5
  9. package/dist/src/generators/qwik/component-generator.js +1 -1
  10. package/dist/src/generators/qwik/src-generator.js +2 -0
  11. package/dist/src/generators/react/generator.d.ts +2 -1
  12. package/dist/src/generators/react/generator.js +73 -20
  13. package/dist/src/generators/solid/index.js +17 -7
  14. package/dist/src/generators/svelte/blocks.js +15 -6
  15. package/dist/src/generators/svelte/svelte.js +15 -11
  16. package/dist/src/generators/vue/blocks.js +12 -6
  17. package/dist/src/generators/vue/compositionApi.js +16 -2
  18. package/dist/src/generators/vue/helpers.js +45 -22
  19. package/dist/src/generators/vue/optionsApi.js +25 -15
  20. package/dist/src/generators/vue/vue.js +5 -2
  21. package/dist/src/helpers/babel-transform.js +30 -19
  22. package/dist/src/helpers/patterns.d.ts +1 -0
  23. package/dist/src/helpers/patterns.js +5 -3
  24. package/dist/src/helpers/plugins/process-code.js +6 -6
  25. package/dist/src/helpers/process-http-requests.js +3 -3
  26. package/dist/src/helpers/replace-identifiers.d.ts +5 -3
  27. package/dist/src/helpers/replace-identifiers.js +124 -21
  28. package/dist/src/helpers/slots.js +3 -1
  29. package/dist/src/helpers/strip-state-and-props-refs.d.ts +23 -4
  30. package/dist/src/helpers/strip-state-and-props-refs.js +57 -53
  31. package/dist/src/helpers/styles/collect-css.js +2 -2
  32. package/dist/src/helpers/styles/helpers.js +10 -11
  33. package/dist/src/helpers/typescript.d.ts +1 -0
  34. package/dist/src/helpers/typescript.js +3 -0
  35. package/dist/src/parsers/jsx/element-parser.js +3 -2
  36. package/dist/src/parsers/jsx/function-parser.js +3 -10
  37. package/dist/src/parsers/jsx/helpers.d.ts +4 -0
  38. package/dist/src/parsers/jsx/helpers.js +11 -1
  39. package/dist/src/parsers/jsx/state.d.ts +1 -1
  40. package/dist/src/parsers/jsx/state.js +85 -39
  41. package/dist/src/parsers/svelte/helpers/post-process.d.ts +10 -5
  42. package/dist/src/parsers/svelte/helpers/post-process.js +51 -16
  43. package/dist/src/parsers/svelte/html/element.js +29 -11
  44. package/dist/src/parsers/svelte/html/slot.js +3 -8
  45. package/dist/src/parsers/svelte/instance/reactive.js +10 -1
  46. package/dist/src/parsers/svelte/instance/references.js +2 -2
  47. package/dist/src/types/mitosis-component.d.ts +1 -1
  48. package/dist/tsconfig.build.tsbuildinfo +1 -1
  49. package/package.json +1 -1
@@ -175,7 +175,9 @@ var componentToVue = function (userOptions) {
175
175
  (0, lodash_1.size)(Object.keys(component.state).filter(function (key) { var _a; return ((_a = component.state[key]) === null || _a === void 0 ? void 0 : _a.type) === 'property'; })) && vueImports.push('ref');
176
176
  }
177
177
  var tsLangAttribute = options.typescript ? "lang='ts'" : '';
178
- var str = (0, dedent_1.default)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n <template>\n ", "\n </template>\n\n\n <script ", " ", ">\n ", "\n ", "\n\n ", "\n\n ", "\n </script>\n\n ", "\n "], ["\n <template>\n ", "\n </template>\n\n\n <script ", " ", ">\n ", "\n ", "\n\n ", "\n\n ", "\n </script>\n\n ", "\n "])), template, options.api === 'composition' ? 'setup' : '', tsLangAttribute, vueImports.length ? "import { ".concat((0, lodash_1.uniq)(vueImports).sort().join(', '), " } from \"vue\"") : '', (options.typescript && ((_h = component.types) === null || _h === void 0 ? void 0 : _h.join('\n'))) || '', (0, render_imports_1.renderPreComponent)({
178
+ var str = (0, dedent_1.default)(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n ", "\n\n\n <script ", " ", ">\n ", "\n ", "\n\n ", "\n\n ", "\n </script>\n\n ", "\n "], ["\n ", "\n\n\n <script ", " ", ">\n ", "\n ", "\n\n ", "\n\n ", "\n </script>\n\n ", "\n "])), template.trim().length > 0
179
+ ? "<template>\n ".concat(template, "\n </template>")
180
+ : '', options.api === 'composition' ? 'setup' : '', tsLangAttribute, vueImports.length ? "import { ".concat((0, lodash_1.uniq)(vueImports).sort().join(', '), " } from \"vue\"") : '', (options.typescript && ((_h = component.types) === null || _h === void 0 ? void 0 : _h.join('\n'))) || '', (0, render_imports_1.renderPreComponent)({
179
181
  component: component,
180
182
  target: 'vue',
181
183
  asyncComponentImports: options.asyncComponentImports,
@@ -205,8 +207,9 @@ var componentToVue = function (userOptions) {
205
207
  str = (0, plugins_1.runPostCodePlugins)(str, options.plugins);
206
208
  for (var _i = 0, removePatterns_1 = removePatterns; _i < removePatterns_1.length; _i++) {
207
209
  var pattern = removePatterns_1[_i];
208
- str = str.replace(pattern, '');
210
+ str = str.replace(pattern, '').trim();
209
211
  }
212
+ str = str.replace(/<script(.*)>\n?<\/script>/g, '').trim();
210
213
  return str;
211
214
  };
212
215
  };
@@ -38,31 +38,33 @@ var jsxPlugin = require('@babel/plugin-syntax-jsx');
38
38
  var tsPreset = require('@babel/preset-typescript');
39
39
  var decorators = require('@babel/plugin-syntax-decorators');
40
40
  var function_1 = require("fp-ts/lib/function");
41
+ var patterns_1 = require("./patterns");
41
42
  var handleErrorOrExpression = function (_a) {
42
43
  var code = _a.code, useCode = _a.useCode, result = _a.result, visitor = _a.visitor;
43
44
  try {
44
45
  // If it can't, e.g. this is an expression or code fragment, modify the code below and try again
45
46
  // Detect method fragments. These get passed sometimes and otherwise
46
47
  // generate compile errors. They are of the form `foo() { ... }`
47
- var isMethod = Boolean(!code.startsWith('function') && code.match(/^[a-z0-9_]+\s*\([^\)]*\)\s*[\{:]/i));
48
- if (isMethod) {
48
+ var isMethod = Boolean(!code.trim().startsWith('function') && code.trim().match(/^[a-z0-9_]+\s*\([^\)]*\)\s*[\{:]/i));
49
+ var isGetter = (0, patterns_1.checkIsGetter)(code);
50
+ var isMethodOrGetter = isMethod || isGetter;
51
+ if (isMethodOrGetter) {
49
52
  useCode = "function ".concat(useCode);
50
53
  }
54
+ result = (0, function_1.pipe)(
51
55
  // Parse the code as an expression (instead of the default, a block) by giving it a fake variable assignment
52
56
  // e.g. if the code parsed is { ... } babel will treat that as a block by deafult, unless processed as an expression
53
57
  // that is an object
54
- useCode = "let _ = ".concat(useCode);
55
- result = (0, function_1.pipe)((0, exports.babelTransformCode)(useCode, visitor), trimSemicolons, function (str) {
56
- // Remove our fake variable assignment
57
- return str.replace(/let _ =\s/, '');
58
- });
59
- if (isMethod) {
58
+ "let _ = ".concat(useCode), function (code) { return (0, exports.babelTransformCode)(code, visitor); }, trimSemicolons,
59
+ // Remove our fake variable assignment
60
+ function (str) { return str.replace(/let _ =\s/, ''); });
61
+ if (isMethodOrGetter) {
60
62
  return result.replace('function', '');
61
63
  }
62
64
  return result;
63
65
  }
64
66
  catch (err) {
65
- console.error('Error parsing code:\n', code, '\n', result);
67
+ // console.error('Error parsing code:\n', { code, result, useCode });
66
68
  throw err;
67
69
  }
68
70
  };
@@ -109,18 +111,27 @@ var babelTransformExpression = function (code, visitor, initialType) {
109
111
  if (!code) {
110
112
  return '';
111
113
  }
112
- var type = getType(code, initialType);
113
- var useCode = type === 'functionBody' ? "function(){".concat(code, "}") : code;
114
- if (type !== 'expression') {
115
- try {
116
- return (0, function_1.pipe)((0, exports.babelTransformCode)(useCode, visitor), trimExpression(type));
114
+ var isGetter = code.trim().startsWith('get ');
115
+ return (0, function_1.pipe)(code, function (code) {
116
+ code = isGetter ? code.replace('get', 'function ') : code;
117
+ var type = getType(code, initialType);
118
+ var useCode = type === 'functionBody' ? "function(){".concat(code, "}") : code;
119
+ return { type: type, useCode: useCode };
120
+ }, function (_a) {
121
+ var type = _a.type, useCode = _a.useCode;
122
+ if (type !== 'expression') {
123
+ try {
124
+ return (0, function_1.pipe)((0, exports.babelTransformCode)(useCode, visitor), trimExpression(type));
125
+ }
126
+ catch (error) {
127
+ return handleErrorOrExpression({ code: code, useCode: useCode, result: null, visitor: visitor });
128
+ }
117
129
  }
118
- catch (error) {
130
+ else {
119
131
  return handleErrorOrExpression({ code: code, useCode: useCode, result: null, visitor: visitor });
120
132
  }
121
- }
122
- else {
123
- return handleErrorOrExpression({ code: code, useCode: useCode, result: null, visitor: visitor });
124
- }
133
+ }, function (transformed) {
134
+ return isGetter ? transformed.replace('function ', 'get ') : transformed;
135
+ });
125
136
  };
126
137
  exports.babelTransformExpression = babelTransformExpression;
@@ -1,5 +1,6 @@
1
1
  export declare const GETTER: RegExp;
2
2
  export declare const SETTER: RegExp;
3
+ export declare const checkIsGetter: (code: string) => RegExpMatchArray | null;
3
4
  export declare const stripGetter: (str: string) => string;
4
5
  export declare const replaceGetterWithFunction: (str: string) => string;
5
6
  export declare const prefixWithFunction: (str: string) => string;
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.prefixWithFunction = exports.replaceGetterWithFunction = exports.stripGetter = exports.SETTER = exports.GETTER = void 0;
4
- exports.GETTER = /^get /;
5
- exports.SETTER = /^set /;
3
+ exports.prefixWithFunction = exports.replaceGetterWithFunction = exports.stripGetter = exports.checkIsGetter = exports.SETTER = exports.GETTER = void 0;
4
+ exports.GETTER = /^\s*get /;
5
+ exports.SETTER = /^\s*set /;
6
+ var checkIsGetter = function (code) { return code.match(exports.GETTER); };
7
+ exports.checkIsGetter = checkIsGetter;
6
8
  var stripGetter = function (str) { return str.replace(exports.GETTER, ''); };
7
9
  exports.stripGetter = stripGetter;
8
10
  var replaceGetterWithFunction = function (str) { return str.replace(/^(get )?/, 'function '); };
@@ -9,12 +9,12 @@ var traverse_nodes_1 = require("../traverse-nodes");
9
9
  var preProcessBlockCode = function (_a) {
10
10
  var json = _a.json, codeProcessor = _a.codeProcessor;
11
11
  var propertiesProcessor = codeProcessor('properties');
12
- for (var key in json.properties) {
13
- var value = json.properties[key];
14
- if (value) {
15
- json.properties[key] = propertiesProcessor(value);
16
- }
17
- }
12
+ // for (const key in json.properties) {
13
+ // const value = json.properties[key];
14
+ // if (key !== '_text' && value) {
15
+ // json.properties[key] = propertiesProcessor(value);
16
+ // }
17
+ // }
18
18
  var bindingsProcessor = codeProcessor('bindings');
19
19
  for (var key in json.bindings) {
20
20
  var value = json.bindings[key];
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.processHttpRequests = void 0;
4
4
  function processHttpRequests(json) {
5
- var _a, _b;
6
- var httpRequests = (_a = json.meta.useMetadata) === null || _a === void 0 ? void 0 : _a.httpRequests;
7
- var onMount = ((_b = json.hooks.onMount) === null || _b === void 0 ? void 0 : _b.code) ? json.hooks.onMount : { code: '' };
5
+ var _a, _b, _c;
6
+ var httpRequests = (_b = (_a = json === null || json === void 0 ? void 0 : json.meta) === null || _a === void 0 ? void 0 : _a.useMetadata) === null || _b === void 0 ? void 0 : _b.httpRequests;
7
+ var onMount = ((_c = json.hooks.onMount) === null || _c === void 0 ? void 0 : _c.code) ? json.hooks.onMount : { code: '' };
8
8
  if (httpRequests) {
9
9
  for (var key in httpRequests) {
10
10
  if (!json.state[key]) {
@@ -1,5 +1,7 @@
1
- export declare const replaceIdentifiers: ({ code, from, to, }: {
1
+ declare type ReplaceArgs = {
2
2
  code: string;
3
3
  from: string | string[];
4
- to: string | ((identifier: string) => string);
5
- }) => string;
4
+ to: string | ((identifier: string) => string) | null;
5
+ };
6
+ export declare const replaceIdentifiers: ({ code, from, to }: ReplaceArgs) => string;
7
+ export {};
@@ -1,33 +1,136 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  exports.replaceIdentifiers = void 0;
4
7
  var core_1 = require("@babel/core");
8
+ var generator_1 = __importDefault(require("@babel/generator"));
9
+ var function_1 = require("fp-ts/lib/function");
5
10
  var babel_transform_1 = require("./babel-transform");
6
- var checkShouldReplaceIdentifier = function (path) {
7
- // Identifier should not be an (optional) property access - like `foo` in `this.foo` or `this?.foo`
8
- var isPropertyAccess = (core_1.types.isMemberExpression(path.parent) || core_1.types.isOptionalMemberExpression(path.parent)) &&
9
- path.parent.property === path.node;
10
- if (isPropertyAccess) {
11
- return false;
11
+ /**
12
+ * Given a `to` function given by the user, figure out the best argument to provide to the `to` function.
13
+ * This function makes a best guess based on the AST structure it's dealing with.
14
+ */
15
+ var getToParam = function (path) {
16
+ if (core_1.types.isMemberExpression(path.node) || core_1.types.isOptionalMemberExpression(path.node)) {
17
+ // if simple member expression e.g. `props.foo`, returns `foo`
18
+ if (core_1.types.isIdentifier(path.node.property)) {
19
+ var newLocal = path.node.property.name;
20
+ return newLocal;
21
+ }
22
+ else {
23
+ // if nested member expression e.g. `props.foo.bar.baz`, returns `foo.bar.baz`
24
+ var x = (0, generator_1.default)(path.node.property).code;
25
+ return x;
26
+ }
12
27
  }
13
- // Identifier should not be a function name - like `foo` in `function foo() {}`
14
- var isFunctionName = core_1.types.isFunctionDeclaration(path.parent) && path.parent.id === path.node;
15
- if (isFunctionName) {
16
- return false;
28
+ else {
29
+ // if naked identifier e.g. `foo`, returns `foo`
30
+ return path.node.name;
31
+ }
32
+ };
33
+ var _replaceIdentifiers = function (path, _a) {
34
+ var from = _a.from, to = _a.to;
35
+ var memberExpressionObject = core_1.types.isIdentifier(path.node) ? path.node : path.node.object;
36
+ var normalizedFrom = Array.isArray(from) ? from : [from];
37
+ if (!core_1.types.isIdentifier(memberExpressionObject)) {
38
+ return;
39
+ }
40
+ var matchesFrom = normalizedFrom.includes(memberExpressionObject.name);
41
+ if (matchesFrom) {
42
+ if (to) {
43
+ // `props.foo` to `state`, e.g. `state.foo`
44
+ if (typeof to === 'string') {
45
+ var cleanedIdentifier = (0, function_1.pipe)(
46
+ // Remove trailing `.` if it exists in the user-provided string, as the dot is generated
47
+ // by babel from the AST
48
+ to.endsWith('.') ? to.substring(0, to.length - 1) : to, core_1.types.identifier);
49
+ if (core_1.types.isIdentifier(path.node)) {
50
+ path.replaceWith(cleanedIdentifier);
51
+ }
52
+ else {
53
+ path.replaceWith(core_1.types.memberExpression(cleanedIdentifier, path.node.property));
54
+ }
55
+ // `props.foo` to (name) => `state.${name}.bar`, e.g. `state.foo.bar`
56
+ }
57
+ else {
58
+ try {
59
+ var newMemberExpression = (0, function_1.pipe)(getToParam(path), to, function (expression) {
60
+ var _a = expression.split('.'), head = _a[0], tail = _a.slice(1);
61
+ return [head, tail.join('.')];
62
+ }, function (_a) {
63
+ var obj = _a[0], prop = _a[1];
64
+ var objIdentifier = core_1.types.identifier(obj);
65
+ if (prop === '') {
66
+ return objIdentifier;
67
+ }
68
+ else {
69
+ return core_1.types.memberExpression(objIdentifier, core_1.types.identifier(prop));
70
+ }
71
+ });
72
+ /**
73
+ * If both `path` and `newMemberExpression` are equal nodes, do nothing.
74
+ * This is to prevent infinite loops when the user-provided `to` function returns the same identifier.
75
+ *
76
+ * The infinite loop probably happens because we end up traversing the new `Identifier` node again?
77
+ */
78
+ if ((0, generator_1.default)(path.node).code === (0, generator_1.default)(newMemberExpression).code) {
79
+ return;
80
+ }
81
+ path.replaceWith(newMemberExpression);
82
+ }
83
+ catch (err) {
84
+ console.error('Could not replace', path.node, 'with', to);
85
+ // throw err;
86
+ }
87
+ }
88
+ }
89
+ else {
90
+ if (core_1.types.isIdentifier(path.node)) {
91
+ console.error("Could not replace Identifier '".concat(from.toString(), "' with nothing."));
92
+ }
93
+ else {
94
+ // if we're looking at a member expression, e.g. `props.foo` and no `to` was provided, then we want to strip out
95
+ // the identifier and end up with `foo`. So we replace the member expression with just its `property` value.
96
+ path.replaceWith(path.node.property);
97
+ }
98
+ }
17
99
  }
18
- return true;
19
100
  };
20
101
  var replaceIdentifiers = function (_a) {
21
102
  var code = _a.code, from = _a.from, to = _a.to;
22
- return (0, babel_transform_1.babelTransformExpression)(code, {
23
- Identifier: function (path) {
24
- var matchesFrom = Array.isArray(from)
25
- ? from.includes(path.node.name)
26
- : path.node.name === from;
27
- if (checkShouldReplaceIdentifier(path) && matchesFrom) {
28
- path.replaceWith(core_1.types.identifier(typeof to === 'string' ? to : to(path.node.name)));
29
- }
30
- },
31
- });
103
+ try {
104
+ return (0, function_1.pipe)((0, babel_transform_1.babelTransformExpression)(code, {
105
+ MemberExpression: function (path) {
106
+ _replaceIdentifiers(path, { from: from, to: to });
107
+ },
108
+ OptionalMemberExpression: function (path) {
109
+ _replaceIdentifiers(path, { from: from, to: to });
110
+ },
111
+ Identifier: function (path) {
112
+ // we only want to ignore certain identifiers:
113
+ if (
114
+ // (optional) member expressions are already handled in other visitors
115
+ !core_1.types.isMemberExpression(path.parent) &&
116
+ !core_1.types.isOptionalMemberExpression(path.parent) &&
117
+ // function declaration identifiers shouldn't be transformed
118
+ !core_1.types.isFunctionDeclaration(path.parent)) {
119
+ _replaceIdentifiers(path, { from: from, to: to });
120
+ }
121
+ },
122
+ }),
123
+ // merely running `babel.transform` will add spaces around the code, even if we don't end up replacing anything.
124
+ // This is why we need to trim the output.
125
+ function (code) { return code.trim(); });
126
+ }
127
+ catch (err) {
128
+ // console.error('could not replace identifiers for ', {
129
+ // code,
130
+ // from: from.toString(),
131
+ // to: to?.toString(),
132
+ // });
133
+ throw err;
134
+ }
32
135
  };
33
136
  exports.replaceIdentifiers = replaceIdentifiers;
@@ -6,7 +6,9 @@ var babel_transform_1 = require("./babel-transform");
6
6
  var SLOT_PREFIX = 'slot';
7
7
  var isSlotProperty = function (key) { return key.startsWith(SLOT_PREFIX); };
8
8
  exports.isSlotProperty = isSlotProperty;
9
- var stripSlotPrefix = function (key) { return key.substring(SLOT_PREFIX.length); };
9
+ var stripSlotPrefix = function (key) {
10
+ return (0, exports.isSlotProperty)(key) ? key.substring(SLOT_PREFIX.length) : key;
11
+ };
10
12
  exports.stripSlotPrefix = stripSlotPrefix;
11
13
  function replaceSlotsInString(code, mapper) {
12
14
  return (0, babel_transform_1.babelTransformExpression)(code, {
@@ -2,18 +2,37 @@ export declare type StripStateAndPropsRefsOptions = {
2
2
  replaceWith?: string | ((name: string) => string);
3
3
  includeProps?: boolean;
4
4
  includeState?: boolean;
5
- contextVars?: string[];
5
+ };
6
+ /**
7
+ * Do not use this anywhere. We are migrating to AST transforms and should avoid Regex String.replace() as they are
8
+ * very brittle.
9
+ *
10
+ * If you need to re-use this, re-create it as an AST tranform first.
11
+ */
12
+ export declare const DO_NOT_USE_CONTEXT_VARS_TRANSFORMS: ({ code, contextVars, context, }: {
13
+ code: string;
14
+ contextVars?: string[] | undefined;
15
+ context: string;
16
+ }) => string;
17
+ export declare type DO_NOT_USE_ARGS = {
6
18
  outputVars?: string[];
19
+ domRefs?: string[];
7
20
  stateVars?: string[];
21
+ contextVars?: string[];
8
22
  context?: string;
9
- domRefs?: string[];
10
23
  };
24
+ /**
25
+ * Do not use these anywhere. We are migrating to AST transforms and should avoid Regex String.replace() as they are
26
+ * very brittle.
27
+ *
28
+ * If you need to re-use a part of this, re-create it as an AST tranform first.
29
+ */
30
+ export declare const DO_NOT_USE_VARS_TRANSFORMS: (newCode: string, { context, domRefs, outputVars, stateVars, contextVars }: DO_NOT_USE_ARGS) => string;
11
31
  /**
12
32
  * Remove state. and props. from expressions, e.g.
13
33
  * state.foo -> foo
14
34
  *
15
- * This is for support for frameworks like Vue, Svelte, liquid, etc
35
+ * This is for support for frameworks like Vue, Svelte, liquid, etc
16
36
  *
17
- * @todo proper ref replacement with babel
18
37
  */
19
38
  export declare const stripStateAndPropsRefs: (code?: string, _options?: StripStateAndPropsRefsOptions) => string;
@@ -11,82 +11,86 @@ var __assign = (this && this.__assign) || function () {
11
11
  return __assign.apply(this, arguments);
12
12
  };
13
13
  Object.defineProperty(exports, "__esModule", { value: true });
14
- exports.stripStateAndPropsRefs = void 0;
14
+ exports.stripStateAndPropsRefs = exports.DO_NOT_USE_VARS_TRANSFORMS = exports.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS = void 0;
15
+ var replace_identifiers_1 = require("./replace-identifiers");
15
16
  var DEFAULT_OPTIONS = {
16
17
  replaceWith: '',
17
- contextVars: [],
18
- outputVars: [],
19
- stateVars: [],
20
- context: 'this.',
21
- domRefs: [],
22
18
  includeProps: true,
23
19
  includeState: true,
24
20
  };
25
21
  /**
26
- * Remove state. and props. from expressions, e.g.
27
- * state.foo -> foo
28
- *
29
- * This is for support for frameworks like Vue, Svelte, liquid, etc
22
+ * Do not use this anywhere. We are migrating to AST transforms and should avoid Regex String.replace() as they are
23
+ * very brittle.
30
24
  *
31
- * @todo proper ref replacement with babel
25
+ * If you need to re-use this, re-create it as an AST tranform first.
32
26
  */
33
- var stripStateAndPropsRefs = function (code, _options) {
34
- if (_options === void 0) { _options = {}; }
35
- var newCode = code || '';
36
- var _a = __assign(__assign({}, DEFAULT_OPTIONS), _options), replaceWith = _a.replaceWith, contextVars = _a.contextVars, outputVars = _a.outputVars, context = _a.context, domRefs = _a.domRefs, includeProps = _a.includeProps, includeState = _a.includeState, stateVars = _a.stateVars;
37
- contextVars.forEach(function (_var) {
38
- newCode = newCode.replace(
27
+ var DO_NOT_USE_CONTEXT_VARS_TRANSFORMS = function (_a) {
28
+ var code = _a.code, contextVars = _a.contextVars, context = _a.context;
29
+ contextVars === null || contextVars === void 0 ? void 0 : contextVars.forEach(function (_var) {
30
+ code = code.replace(
39
31
  // determine expression edge cases - https://regex101.com/r/iNcTSM/1
40
32
  new RegExp('(^|\\n|\\r| |;|\\(|\\[|!)' + _var + '(\\?\\.|\\.|\\(| |;|\\)|$)', 'g'), '$1' + context + _var + '$2');
41
33
  });
42
- outputVars.forEach(function (_var) {
34
+ return code;
35
+ };
36
+ exports.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS = DO_NOT_USE_CONTEXT_VARS_TRANSFORMS;
37
+ /**
38
+ * Do not use these anywhere. We are migrating to AST transforms and should avoid Regex String.replace() as they are
39
+ * very brittle.
40
+ *
41
+ * If you need to re-use a part of this, re-create it as an AST tranform first.
42
+ */
43
+ var DO_NOT_USE_VARS_TRANSFORMS = function (newCode, _a) {
44
+ var _b = _a.context, context = _b === void 0 ? 'this.' : _b, domRefs = _a.domRefs, outputVars = _a.outputVars, stateVars = _a.stateVars, contextVars = _a.contextVars;
45
+ newCode = (0, exports.DO_NOT_USE_CONTEXT_VARS_TRANSFORMS)({ code: newCode, context: context, contextVars: contextVars });
46
+ outputVars === null || outputVars === void 0 ? void 0 : outputVars.forEach(function (_var) {
43
47
  // determine expression edge cases onMessage( to this.onMessage.emit(
44
48
  var regexp = '(^|\\s|;|\\()(props\\.?)' + _var + '\\(';
45
49
  var replacer = '$1' + context + _var + '.emit(';
46
50
  newCode = newCode.replace(new RegExp(regexp, 'g'), replacer);
47
51
  });
52
+ var matchPropertyAccessorsArguments = '\\?\\.|,|\\.|\\(| |;|\\)|\\]|$'; // foo?.stuff | foo) | foo | foo] etc.
53
+ var matchVariableUseInClass = '^|\\n|\\r| |;|\\(|\\[|!|,'; // foo | (foo | !foo | foo, | [foo etc.
54
+ domRefs === null || domRefs === void 0 ? void 0 : domRefs.forEach(function (_var) {
55
+ newCode = newCode.replace(new RegExp("(".concat(matchVariableUseInClass, ")").concat(_var, "(").concat(matchPropertyAccessorsArguments, ")"), 'g'), '$1' + 'this.' + _var + '$2');
56
+ });
57
+ stateVars === null || stateVars === void 0 ? void 0 : stateVars.forEach(function (_var) {
58
+ newCode = newCode.replace(
59
+ /*
60
+ 1. Skip anything that is a class variable declaration
61
+ myClass() {
62
+ stuff = 'hi'
63
+ foo = 'bar' <-- in the event that formatting is off
64
+ }
65
+ 2. Skip anything that is the name of a function declaration or a getter
66
+ stuff = function stuff() {} or get stuff
67
+ 3. If the conditions are met then try to match all use cases of the class variables, see above.
68
+ */
69
+ new RegExp("(?!^".concat(_var, "|^ ").concat(_var, ")(?<!function|get)(").concat(matchVariableUseInClass, ")").concat(_var, "(").concat(matchPropertyAccessorsArguments, ")"), 'g'), '$1' + 'this.' + _var + '$2');
70
+ });
71
+ return newCode;
72
+ };
73
+ exports.DO_NOT_USE_VARS_TRANSFORMS = DO_NOT_USE_VARS_TRANSFORMS;
74
+ /**
75
+ * Remove state. and props. from expressions, e.g.
76
+ * state.foo -> foo
77
+ *
78
+ * This is for support for frameworks like Vue, Svelte, liquid, etc
79
+ *
80
+ */
81
+ var stripStateAndPropsRefs = function (code, _options) {
82
+ if (_options === void 0) { _options = {}; }
83
+ var newCode = code || '';
84
+ var _a = __assign(__assign({}, DEFAULT_OPTIONS), _options), replaceWith = _a.replaceWith, includeProps = _a.includeProps, includeState = _a.includeState;
48
85
  if (includeProps !== false) {
49
- if (typeof replaceWith === 'string') {
50
- newCode = newCode.replace(/props\./g, replaceWith);
51
- }
52
- else {
53
- newCode = newCode.replace(/props\.([\$a-z0-9_]+)/gi, function (memo, name) { return replaceWith(name); });
54
- }
86
+ newCode = (0, replace_identifiers_1.replaceIdentifiers)({ code: newCode, from: 'props', to: replaceWith || null });
55
87
  // TODO: webcomponent edge-case
56
88
  if (/el\.this\.props/.test(newCode)) {
57
89
  newCode = newCode.replace(/el\.this\.props/g, 'el.props');
58
90
  }
59
91
  }
60
92
  if (includeState !== false) {
61
- if (typeof replaceWith === 'string') {
62
- newCode = newCode.replace(/state\./g, replaceWith);
63
- }
64
- else {
65
- newCode = newCode.replace(/state\.([\$a-z0-9_]+)/gi, function (memo, name) { return replaceWith(name); });
66
- }
67
- }
68
- var matchPropertyAccessorsArguments = '\\?\\.|,|\\.|\\(| |;|\\)|\\]|$'; // foo?.stuff | foo) | foo | foo] etc.
69
- var matchVariableUseInClass = '^|\\n|\\r| |;|\\(|\\[|!|,'; // foo | (foo | !foo | foo, | [foo etc.
70
- if (domRefs.length) {
71
- domRefs.forEach(function (_var) {
72
- newCode = newCode.replace(new RegExp("(".concat(matchVariableUseInClass, ")").concat(_var, "(").concat(matchPropertyAccessorsArguments, ")"), 'g'), '$1' + 'this.' + _var + '$2');
73
- });
74
- }
75
- if (stateVars.length) {
76
- stateVars.forEach(function (_var) {
77
- newCode = newCode.replace(
78
- /*
79
- 1. Skip anything that is a class variable declaration
80
- myClass() {
81
- stuff = 'hi'
82
- foo = 'bar' <-- in the event that formatting is off
83
- }
84
- 2. Skip anything that is the name of a function declaration or a getter
85
- stuff = function stuff() {} or get stuff
86
- 3. If the conditions are met then try to match all use cases of the class variables, see above.
87
- */
88
- new RegExp("(?!^".concat(_var, "|^ ").concat(_var, ")(?<!function|get)(").concat(matchVariableUseInClass, ")").concat(_var, "(").concat(matchPropertyAccessorsArguments, ")"), 'g'), '$1' + 'this.' + _var + '$2');
89
- });
93
+ newCode = (0, replace_identifiers_1.replaceIdentifiers)({ code: newCode, from: 'state', to: replaceWith || null });
90
94
  }
91
95
  return newCode;
92
96
  };
@@ -71,7 +71,7 @@ var classStyleMapToCss = function (map) {
71
71
  var str = '';
72
72
  for (var key in map) {
73
73
  var styles = (0, helpers_1.getStylesOnly)(map[key]);
74
- str += ".".concat(key, " { ").concat((0, helpers_1.styleMapToCss)(styles), " }");
74
+ str += ".".concat(key, " {\n").concat((0, helpers_1.styleMapToCss)(styles), "\n}");
75
75
  var nestedSelectors = (0, helpers_1.getNestedSelectors)(map[key]);
76
76
  for (var nestedSelector in nestedSelectors) {
77
77
  var value = nestedSelectors[nestedSelector];
@@ -82,7 +82,7 @@ var classStyleMapToCss = function (map) {
82
82
  var useSelector = nestedSelector.includes('&')
83
83
  ? nestedSelector.replace(/&/g, ".".concat(key))
84
84
  : ".".concat(key, " ").concat(nestedSelector);
85
- str += "".concat(useSelector, " { ").concat((0, helpers_1.styleMapToCss)(value), " }");
85
+ str += "".concat(useSelector, " {\n").concat((0, helpers_1.styleMapToCss)(value), "\n}");
86
86
  }
87
87
  }
88
88
  }
@@ -69,16 +69,15 @@ var parseCssObject = function (css) {
69
69
  };
70
70
  exports.parseCssObject = parseCssObject;
71
71
  var styleMapToCss = function (map) {
72
- var str = '';
73
- for (var key in map) {
74
- var value = map[key];
75
- if (typeof value === 'string') {
76
- str += "\n".concat((0, dash_case_1.dashCase)(key), ": ").concat(value, ";");
77
- }
78
- else {
79
- // TODO: do nothing
80
- }
81
- }
82
- return str;
72
+ return Object.entries(map)
73
+ .filter(function (_a) {
74
+ var key = _a[0], value = _a[1];
75
+ return typeof value === 'string';
76
+ })
77
+ .map(function (_a) {
78
+ var key = _a[0], value = _a[1];
79
+ return " ".concat((0, dash_case_1.dashCase)(key), ": ").concat(value, ";");
80
+ })
81
+ .join('\n');
83
82
  };
84
83
  exports.styleMapToCss = styleMapToCss;
@@ -3,3 +3,4 @@ export declare type OmitObj<T, U> = T extends U ? Omit<T, keyof U> : never;
3
3
  export declare type Dictionary<T> = {
4
4
  [key: string]: T;
5
5
  };
6
+ export declare const objectHasKey: <T>(object: T, key: PropertyKey) => key is keyof T;
@@ -1,2 +1,5 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.objectHasKey = void 0;
4
+ var objectHasKey = function (object, key) { return key in object; };
5
+ exports.objectHasKey = objectHasKey;
@@ -43,6 +43,7 @@ var generator_1 = __importDefault(require("@babel/generator"));
43
43
  var nullable_1 = require("../../helpers/nullable");
44
44
  var create_mitosis_node_1 = require("../../helpers/create-mitosis-node");
45
45
  var function_1 = require("fp-ts/lib/function");
46
+ var helpers_1 = require("./helpers");
46
47
  var types = babel.types;
47
48
  var getForArguments = function (params) {
48
49
  var _a = params
@@ -191,7 +192,7 @@ var jsxElementToJson = function (node) {
191
192
  name: nodeName,
192
193
  properties: node.openingElement.attributes.reduce(function (memo, item) {
193
194
  if (types.isJSXAttribute(item)) {
194
- var key = item.name.name;
195
+ var key = (0, helpers_1.transformAttributeName)(item.name.name);
195
196
  var value = item.value;
196
197
  if (types.isStringLiteral(value)) {
197
198
  memo[key] = value.value;
@@ -206,7 +207,7 @@ var jsxElementToJson = function (node) {
206
207
  }, {}),
207
208
  bindings: node.openingElement.attributes.reduce(function (memo, item) {
208
209
  if (types.isJSXAttribute(item)) {
209
- var key = item.name.name;
210
+ var key = (0, helpers_1.transformAttributeName)(item.name.name);
210
211
  var value = item.value;
211
212
  // boolean attribute
212
213
  if (value === null) {