From 85825ac4a5e6bbcac922e581a5b6eb6eb4630640 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 01:17:09 +0300 Subject: [PATCH 01/10] feat: move to common lodash package; --- .../components/card/index.tsx | 2 +- .../pages/components-overview/index.tsx | 2 +- bin/generate-docs-urls.js | 4 +- package.json | 12 +---- packages/collapse/package.json | 5 +- packages/collapse/src/Component.tsx | 2 +- packages/input-autocomplete/package.json | 4 +- .../src/mobile/Component.mobile.tsx | 2 +- .../screenshot-utils/createStorybookUrl.ts | 2 +- packages/screenshot-utils/helpers.ts | 2 +- packages/scrollbar/package.json | 6 +-- packages/scrollbar/src/Component.tsx | 2 +- packages/tabs/package.json | 17 +++---- .../components/scroll-controls/Component.tsx | 2 +- yarn.lock | 47 +++---------------- 15 files changed, 33 insertions(+), 78 deletions(-) diff --git a/.storybook/pages/components-overview/components/card/index.tsx b/.storybook/pages/components-overview/components/card/index.tsx index 5b352e0a6a..58465620bc 100644 --- a/.storybook/pages/components-overview/components/card/index.tsx +++ b/.storybook/pages/components-overview/components/card/index.tsx @@ -1,5 +1,5 @@ import React from 'react'; -import kebab from 'lodash.kebabcase'; +import kebab from 'lodash/kebabcase'; import cn from 'classnames'; import { Typography } from '@alfalab/core-components-typography'; diff --git a/.storybook/pages/components-overview/index.tsx b/.storybook/pages/components-overview/index.tsx index 7652931676..ab128ec892 100644 --- a/.storybook/pages/components-overview/index.tsx +++ b/.storybook/pages/components-overview/index.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useState } from 'react'; -import _throttle from 'lodash.throttle'; +import _throttle from 'lodash/throttle'; import { Gap } from '@alfalab/core-components-gap'; import { Input, InputProps } from '@alfalab/core-components-input'; diff --git a/bin/generate-docs-urls.js b/bin/generate-docs-urls.js index fa8e29bed4..483438c71e 100644 --- a/bin/generate-docs-urls.js +++ b/bin/generate-docs-urls.js @@ -1,8 +1,8 @@ const path = require('path'); const fs = require('fs'); const { promisify } = require('util'); -const camelCase = require('lodash.camelcase'); -const upperfirst = require('lodash.upperfirst'); +const camelCase = require('lodash/camelcase'); +const upperfirst = require('lodash/upperfirst'); const findComponentPath = require('../tools/storybook/findComponentPath'); const readDir = promisify(fs.readdir); diff --git a/package.json b/package.json index bc57cb75f9..b540e154cd 100644 --- a/package.json +++ b/package.json @@ -79,9 +79,7 @@ "element-closest": "^3.0.2", "intersection-observer": "^0.12.0", "libphonenumber-js": "^1.10.30", - "lodash.debounce": "^4.0.8", - "lodash.memoize": "^4.1.2", - "lodash.throttle": "^4.1.1", + "lodash": "^4.17.21", "mdast-util-gfm-strikethrough": "^0.2.3", "micromark-extension-gfm-strikethrough": "^0.6.5", "nouislider": "^15.6.0", @@ -129,10 +127,7 @@ "@types/element-closest": "^3.0.0", "@types/jest": "^26.0.15", "@types/jest-image-snapshot": "^6.1.0", - "@types/lodash.camelcase": "^4.3.6", - "@types/lodash.debounce": "^4.0.6", - "@types/lodash.kebabcase": "^4.1.6", - "@types/lodash.upperfirst": "^4.3.6", + "@types/lodash": "^4.17.13", "@types/node": "^13.5.0", "@types/react": "^18.0.15", "@types/react-dom": "^18.0.6", @@ -180,9 +175,6 @@ "lerna": "^6.1.0", "levenary": "^1.1.1", "lint-staged": "^12.5.0", - "lodash.camelcase": "^4.3.0", - "lodash.kebabcase": "^4.1.1", - "lodash.upperfirst": "^4.3.1", "mini-css-extract-plugin": "^2.7.5", "playwright": "^1.33.0", "postcss-cli": "^7.1.0", diff --git a/packages/collapse/package.json b/packages/collapse/package.json index 6313e34b3b..b3a457f147 100644 --- a/packages/collapse/package.json +++ b/packages/collapse/package.json @@ -18,9 +18,12 @@ "@alfalab/icons-glyph": "^2.139.0", "@juggle/resize-observer": "^3.3.1", "classnames": "^2.3.1", - "lodash.debounce": "^4.0.8", + "lodash": "^4.17.21", "tslib": "^2.4.0" }, + "devDependencies": { + "@types/lodash": "^4.17.13" + }, "themesVersion": "13.6.0", "varsVersion": "9.16.0" } diff --git a/packages/collapse/src/Component.tsx b/packages/collapse/src/Component.tsx index 58aaa12930..9278b70953 100644 --- a/packages/collapse/src/Component.tsx +++ b/packages/collapse/src/Component.tsx @@ -1,7 +1,7 @@ import React, { forwardRef, useCallback, useEffect, useRef, useState } from 'react'; import { ResizeObserver as ResizeObserverPolyfill } from '@juggle/resize-observer'; import cn from 'classnames'; -import debounce from 'lodash.debounce'; +import debounce from 'lodash/debounce'; import { Link } from '@alfalab/core-components-link'; import { ChevronDownSIcon } from '@alfalab/icons-glyph/ChevronDownSIcon'; diff --git a/packages/input-autocomplete/package.json b/packages/input-autocomplete/package.json index c0437e700f..74d4f4ba2f 100644 --- a/packages/input-autocomplete/package.json +++ b/packages/input-autocomplete/package.json @@ -22,12 +22,12 @@ "@alfalab/core-components-mq": "^4.4.0", "@alfalab/hooks": "^1.13.0", "classnames": "^2.3.1", - "lodash.throttle": "^4.1.1", + "lodash": "^4.17.21", "react-merge-refs": "^1.1.0", "tslib": "^2.4.0" }, "devDependencies": { - "@types/lodash.throttle": "^4.1.7" + "@types/lodash": "^4.17.13" }, "themesVersion": "13.6.0", "varsVersion": "9.16.0" diff --git a/packages/input-autocomplete/src/mobile/Component.mobile.tsx b/packages/input-autocomplete/src/mobile/Component.mobile.tsx index 290d2a2ec0..f2ab632956 100644 --- a/packages/input-autocomplete/src/mobile/Component.mobile.tsx +++ b/packages/input-autocomplete/src/mobile/Component.mobile.tsx @@ -1,7 +1,7 @@ import React, { Ref, useMemo, useRef, useState } from 'react'; import mergeRefs from 'react-merge-refs'; import cn from 'classnames'; -import throttle from 'lodash.throttle'; +import throttle from 'lodash/throttle'; import { SelectMobile, diff --git a/packages/screenshot-utils/createStorybookUrl.ts b/packages/screenshot-utils/createStorybookUrl.ts index 0e51fbc4a9..faadba006e 100644 --- a/packages/screenshot-utils/createStorybookUrl.ts +++ b/packages/screenshot-utils/createStorybookUrl.ts @@ -1,4 +1,4 @@ -import kebab from 'lodash.kebabcase'; +import kebab from 'lodash/kebabcase'; import findComponentPath from '../../tools/storybook/findComponentPath'; diff --git a/packages/screenshot-utils/helpers.ts b/packages/screenshot-utils/helpers.ts index f4b2e5252a..f74a26e2d1 100644 --- a/packages/screenshot-utils/helpers.ts +++ b/packages/screenshot-utils/helpers.ts @@ -14,7 +14,7 @@ import { } from 'playwright'; import axios from 'axios'; import { MatchImageSnapshotOptions } from 'jest-image-snapshot'; -import kebab from 'lodash.kebabcase'; +import kebab from 'lodash/kebabcase'; import { ScreenshotOpts, EvaluateFn } from './setupScreenshotTesting'; type CustomSnapshotIdentifierParams = { diff --git a/packages/scrollbar/package.json b/packages/scrollbar/package.json index dc022bcd49..b238b26339 100644 --- a/packages/scrollbar/package.json +++ b/packages/scrollbar/package.json @@ -18,15 +18,13 @@ "@juggle/resize-observer": "^3.3.1", "can-use-dom": "^0.1.0", "classnames": "^2.3.1", - "lodash.debounce": "^4.0.8", - "lodash.memoize": "^4.1.2", - "lodash.throttle": "^4.1.1", + "lodash": "^4.17.21", "react-merge-refs": "1.1.0", "simplebar": "^5.3.8", "tslib": "^2.4.0" }, "devDependencies": { - "@types/lodash.throttle": "^4.1.7" + "@types/lodash": "^4.17.13" }, "themesVersion": "13.6.0", "varsVersion": "9.16.0" diff --git a/packages/scrollbar/src/Component.tsx b/packages/scrollbar/src/Component.tsx index 421c41df58..f90e16cfd0 100644 --- a/packages/scrollbar/src/Component.tsx +++ b/packages/scrollbar/src/Component.tsx @@ -1,7 +1,7 @@ import React, { HTMLAttributes, useEffect, useRef, useState } from 'react'; import mergeRefs from 'react-merge-refs'; import cn from 'classnames'; -import throttle from 'lodash.throttle'; +import throttle from 'lodash/throttle'; import SimpleBar from 'simplebar/src/simplebar'; import defaultColors from './default.module.css'; diff --git a/packages/tabs/package.json b/packages/tabs/package.json index 16c5c9f988..674ac50133 100644 --- a/packages/tabs/package.json +++ b/packages/tabs/package.json @@ -10,24 +10,21 @@ "access": "public", "directory": "dist" }, - "devDependencies": { - "@types/lodash.debounce": "^4.0.6" - }, + "devDependencies": {}, "dependencies": { - "@alfalab/core-components-keyboard-focusable": "^4.1.0", - "@alfalab/core-components-tag": "^8.6.2", - "@alfalab/core-components-picker-button": "^11.12.6", "@alfalab/core-components-badge": "^5.6.1", + "@alfalab/core-components-icon-button": "^6.11.2", + "@alfalab/core-components-keyboard-focusable": "^4.1.0", "@alfalab/core-components-mq": "^4.4.0", - "@alfalab/hooks": "^1.13.0", + "@alfalab/core-components-picker-button": "^11.12.6", "@alfalab/core-components-shared": "^0.14.0", - "@alfalab/core-components-icon-button": "^6.11.2", "@alfalab/core-components-skeleton": "^5.2.0", + "@alfalab/core-components-tag": "^8.6.2", + "@alfalab/hooks": "^1.13.0", "@alfalab/icons-glyph": "^2.139.0", + "@juggle/resize-observer": "^3.3.1", "classnames": "^2.3.1", "compute-scroll-into-view": "^3.1.0", - "lodash.debounce": "^4.0.8", - "@juggle/resize-observer": "^3.3.1", "tslib": "^2.4.0" }, "peerDependencies": { diff --git a/packages/tabs/src/components/scroll-controls/Component.tsx b/packages/tabs/src/components/scroll-controls/Component.tsx index dc8639a64c..b760f44545 100644 --- a/packages/tabs/src/components/scroll-controls/Component.tsx +++ b/packages/tabs/src/components/scroll-controls/Component.tsx @@ -1,6 +1,6 @@ import React, { forwardRef, RefObject, useEffect, useState } from 'react'; import cn from 'classnames'; -import _debounce from 'lodash.debounce'; +import _debounce from 'lodash/debounce'; import { IconButton } from '@alfalab/core-components-icon-button'; import { ChevronLeftCompactSIcon } from '@alfalab/icons-glyph/ChevronLeftCompactSIcon'; diff --git a/yarn.lock b/yarn.lock index 88bdcf4be8..e188b45bf6 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5481,46 +5481,16 @@ resolved "https://registry.yarnpkg.com/@types/lockfile/-/lockfile-1.0.2.tgz#3f77e84171a2b7e3198bd5717c7547a54393baf8" integrity sha512-jD5VbvhfMhaYN4M3qPJuhMVUg3Dfc4tvPvLEAXn6GXbs/ajDFtCQahX37GIE65ipTI3I+hEvNaXS3MYAn9Ce3Q== -"@types/lodash.camelcase@^4.3.6": - version "4.3.6" - resolved "https://registry.npmjs.org/@types/lodash.camelcase/-/lodash.camelcase-4.3.6.tgz" - integrity sha512-hd/TEuPd76Jtf1xEq85CHbCqR+iqvs5IOKyrYbiaOg69BRQgPN9XkvLj8Jl8rBp/dfJ2wQ1AVcP8mZmybq7kIg== - dependencies: - "@types/lodash" "*" - -"@types/lodash.debounce@^4.0.6": - version "4.0.6" - resolved "https://registry.npmjs.org/@types/lodash.debounce/-/lodash.debounce-4.0.6.tgz" - integrity sha512-4WTmnnhCfDvvuLMaF3KV4Qfki93KebocUF45msxhYyjMttZDQYzHkO639ohhk8+oco2cluAFL3t5+Jn4mleylQ== - dependencies: - "@types/lodash" "*" - -"@types/lodash.kebabcase@^4.1.6": - version "4.1.6" - resolved "https://registry.npmjs.org/@types/lodash.kebabcase/-/lodash.kebabcase-4.1.6.tgz" - integrity sha512-+RAD9pCAa8kuVyCYTeDNiwBXwD/0u0p+hos3NSqD+tXTjJextbfF3farfYB+ssAKgEssoewXEtBsfwBpsI7gsA== - dependencies: - "@types/lodash" "*" - -"@types/lodash.throttle@^4.1.7": - version "4.1.7" - resolved "https://registry.yarnpkg.com/@types/lodash.throttle/-/lodash.throttle-4.1.7.tgz#4ef379eb4f778068022310ef166625f420b6ba58" - integrity sha512-znwGDpjCHQ4FpLLx19w4OXDqq8+OvREa05H89obtSyXyOFKL3dDjCslsmfBz0T2FU8dmf5Wx1QvogbINiGIu9g== - dependencies: - "@types/lodash" "*" - -"@types/lodash.upperfirst@^4.3.6": - version "4.3.6" - resolved "https://registry.npmjs.org/@types/lodash.upperfirst/-/lodash.upperfirst-4.3.6.tgz" - integrity sha512-op4ctKkT1eD/Nt8MCPlN7O2IQrYWIcH1rOPHM86SKzbliLG50eVXM6+qzkdxtBV7DZb3W/1Up2+k43WK9F0Bgg== - dependencies: - "@types/lodash" "*" - -"@types/lodash@*", "@types/lodash@^4.14.167": +"@types/lodash@^4.14.167": version "4.14.182" resolved "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.182.tgz" integrity sha512-/THyiqyQAP9AfARo4pF+aCGcyiQ94tX/Is2I7HofNRqoYLgN1PBoOWu2/zTA5zMxzP5EFutMtWtGAFRKUe961Q== +"@types/lodash@^4.17.13": + version "4.17.13" + resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.13.tgz#786e2d67cfd95e32862143abe7463a7f90c300eb" + integrity sha512-lfx+dftrEZcdBPczf9d0Qv0x+j/rfNCMuC6OcfXmO8gkfeNAY88PgKUbvG56whcN23gc27yenwF6oJZXGFpYxg== + "@types/mdast@^3.0.0": version "3.0.3" resolved "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.3.tgz" @@ -14531,11 +14501,6 @@ lodash.uniq@^4.5.0: resolved "https://registry.npmjs.org/lodash.uniq/-/lodash.uniq-4.5.0.tgz" integrity sha1-0CJTc662Uq3BvILklFM5qEJ1R3M= -lodash.upperfirst@^4.3.1: - version "4.3.1" - resolved "https://registry.npmjs.org/lodash.upperfirst/-/lodash.upperfirst-4.3.1.tgz" - integrity sha1-E2Xt9DFIBIHvDRxolXpe2Z1J984= - lodash@4.17.21, lodash@^4.17.11, lodash@^4.17.12, lodash@^4.17.14, lodash@^4.17.15, lodash@^4.17.19, lodash@^4.17.20, lodash@^4.17.21, lodash@^4.17.4, lodash@^4.7.0: version "4.17.21" resolved "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz" From a1588729279c8d17027b4440e74730571850522d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 01:34:37 +0300 Subject: [PATCH 02/10] feat: add sideeffects; --- packages/collapse/package.json | 1 + packages/custom-picker-button/package.json | 1 + packages/input-autocomplete/package.json | 1 + .../international-phone-input/package.json | 1 + packages/picker-button/package.json | 1 + packages/scrollbar/package.json | 1 + packages/select-with-tags/package.json | 1 + packages/select/package.json | 1 + packages/table/package.json | 1 + packages/tabs/package.json | 18 +++++++++++------- 10 files changed, 20 insertions(+), 7 deletions(-) diff --git a/packages/collapse/package.json b/packages/collapse/package.json index b3a457f147..9ca32478f6 100644 --- a/packages/collapse/package.json +++ b/packages/collapse/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/custom-picker-button/package.json b/packages/custom-picker-button/package.json index 78d68bf57a..3367205670 100644 --- a/packages/custom-picker-button/package.json +++ b/packages/custom-picker-button/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/input-autocomplete/package.json b/packages/input-autocomplete/package.json index 74d4f4ba2f..75c0c63125 100644 --- a/packages/input-autocomplete/package.json +++ b/packages/input-autocomplete/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/international-phone-input/package.json b/packages/international-phone-input/package.json index 33e43f4faa..fe76670c54 100644 --- a/packages/international-phone-input/package.json +++ b/packages/international-phone-input/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/picker-button/package.json b/packages/picker-button/package.json index 8e422589d5..4cb4f78645 100644 --- a/packages/picker-button/package.json +++ b/packages/picker-button/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/scrollbar/package.json b/packages/scrollbar/package.json index b238b26339..a9d868861e 100644 --- a/packages/scrollbar/package.json +++ b/packages/scrollbar/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/select-with-tags/package.json b/packages/select-with-tags/package.json index a2d1a5203e..f6d81b802c 100644 --- a/packages/select-with-tags/package.json +++ b/packages/select-with-tags/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/select/package.json b/packages/select/package.json index 9d567783c7..699091a73e 100644 --- a/packages/select/package.json +++ b/packages/select/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/table/package.json b/packages/table/package.json index a590dc1894..e8ef40efda 100644 --- a/packages/table/package.json +++ b/packages/table/package.json @@ -10,6 +10,7 @@ "access": "public", "directory": "dist" }, + "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/tabs/package.json b/packages/tabs/package.json index 674ac50133..684e0642ae 100644 --- a/packages/tabs/package.json +++ b/packages/tabs/package.json @@ -10,21 +10,25 @@ "access": "public", "directory": "dist" }, - "devDependencies": {}, + "sideEffects": false, + "devDependencies": { + "@types/lodash": "^4.17.13" + }, "dependencies": { - "@alfalab/core-components-badge": "^5.6.1", - "@alfalab/core-components-icon-button": "^6.11.2", "@alfalab/core-components-keyboard-focusable": "^4.1.0", - "@alfalab/core-components-mq": "^4.4.0", + "@alfalab/core-components-tag": "^8.6.2", "@alfalab/core-components-picker-button": "^11.12.6", + "@alfalab/core-components-badge": "^5.6.1", + "@alfalab/core-components-mq": "^4.4.0", + "@alfalab/hooks": "^1.13.0", "@alfalab/core-components-shared": "^0.14.0", + "@alfalab/core-components-icon-button": "^6.11.2", "@alfalab/core-components-skeleton": "^5.2.0", - "@alfalab/core-components-tag": "^8.6.2", - "@alfalab/hooks": "^1.13.0", "@alfalab/icons-glyph": "^2.139.0", - "@juggle/resize-observer": "^3.3.1", "classnames": "^2.3.1", "compute-scroll-into-view": "^3.1.0", + "lodash": "^4.17.21", + "@juggle/resize-observer": "^3.3.1", "tslib": "^2.4.0" }, "peerDependencies": { From fdd1fafd5f75e1724db6cfa568c732310b389c74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 01:47:59 +0300 Subject: [PATCH 03/10] fix: code; --- .changeset/beige-kangaroos-try.md | 8 ++++++++ packages/collapse/package.json | 1 - packages/custom-picker-button/package.json | 1 - packages/input-autocomplete/package.json | 1 - packages/international-phone-input/package.json | 1 - packages/picker-button/package.json | 1 - packages/scrollbar/package.json | 1 - packages/select-with-tags/package.json | 1 - packages/select/package.json | 1 - packages/table/package.json | 1 - packages/tabs/package.json | 1 - 11 files changed, 8 insertions(+), 10 deletions(-) create mode 100644 .changeset/beige-kangaroos-try.md diff --git a/.changeset/beige-kangaroos-try.md b/.changeset/beige-kangaroos-try.md new file mode 100644 index 0000000000..dcf60a6aef --- /dev/null +++ b/.changeset/beige-kangaroos-try.md @@ -0,0 +1,8 @@ +--- +'@alfalab/core-components-collapse': minor +'@alfalab/core-components-input-autocomplete': minor +'@alfalab/core-components-scrollbar': minor +'@alfalab/core-components-tabs': minor +--- + +- Замена использование lodash на коммон пакет diff --git a/packages/collapse/package.json b/packages/collapse/package.json index 9ca32478f6..b3a457f147 100644 --- a/packages/collapse/package.json +++ b/packages/collapse/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/custom-picker-button/package.json b/packages/custom-picker-button/package.json index 3367205670..78d68bf57a 100644 --- a/packages/custom-picker-button/package.json +++ b/packages/custom-picker-button/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/input-autocomplete/package.json b/packages/input-autocomplete/package.json index 75c0c63125..74d4f4ba2f 100644 --- a/packages/input-autocomplete/package.json +++ b/packages/input-autocomplete/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/international-phone-input/package.json b/packages/international-phone-input/package.json index fe76670c54..33e43f4faa 100644 --- a/packages/international-phone-input/package.json +++ b/packages/international-phone-input/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/picker-button/package.json b/packages/picker-button/package.json index 4cb4f78645..8e422589d5 100644 --- a/packages/picker-button/package.json +++ b/packages/picker-button/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/scrollbar/package.json b/packages/scrollbar/package.json index a9d868861e..b238b26339 100644 --- a/packages/scrollbar/package.json +++ b/packages/scrollbar/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/select-with-tags/package.json b/packages/select-with-tags/package.json index f6d81b802c..a2d1a5203e 100644 --- a/packages/select-with-tags/package.json +++ b/packages/select-with-tags/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0" }, diff --git a/packages/select/package.json b/packages/select/package.json index 699091a73e..9d567783c7 100644 --- a/packages/select/package.json +++ b/packages/select/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/table/package.json b/packages/table/package.json index e8ef40efda..a590dc1894 100644 --- a/packages/table/package.json +++ b/packages/table/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "peerDependencies": { "react": "^16.9.0 || ^17.0.1 || ^18.0.0", "react-dom": "^16.9.0 || ^17.0.1 || ^18.0.0" diff --git a/packages/tabs/package.json b/packages/tabs/package.json index 684e0642ae..2de6759d0a 100644 --- a/packages/tabs/package.json +++ b/packages/tabs/package.json @@ -10,7 +10,6 @@ "access": "public", "directory": "dist" }, - "sideEffects": false, "devDependencies": { "@types/lodash": "^4.17.13" }, From 10f43685d6d66b898e725cd15a247f1b526b58ef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 11:46:30 +0300 Subject: [PATCH 04/10] fix: require named; --- bin/analyze-package-sizes.mjs | 187 +++++++++++++++++++++++++++++++++- bin/generate-docs-urls.js | 4 +- 2 files changed, 185 insertions(+), 6 deletions(-) diff --git a/bin/analyze-package-sizes.mjs b/bin/analyze-package-sizes.mjs index 8725dfb25b..1077889d22 100644 --- a/bin/analyze-package-sizes.mjs +++ b/bin/analyze-package-sizes.mjs @@ -2,6 +2,133 @@ import * as esbuild from 'esbuild'; import globby from 'globby'; import shell from 'shelljs'; import fs from 'node:fs'; +import { Project } from 'ts-morph'; +import path from 'path'; +import ts from 'typescript'; +import ProgressBar from 'progress'; + +// import { parseImports } from 'parse-imports' + +/** + * Получает список всех экспортов из TypeScript файла, включая реэкспорты. + * @param {string} filePath - Путь к файлу + * @param {Set} visitedFiles - Для предотвращения циклов при рекурсивных вызовах + * @returns {string[]} Список имен экспортов + */ +function getExports(filePath, visitedFiles = new Set()) { + const absoluteFilePath = path.resolve(filePath); + + // Проверяем, что файл ещё не обрабатывался + if (visitedFiles.has(absoluteFilePath)) return []; + visitedFiles.add(absoluteFilePath); + + // Создаем программу TypeScript + const program = ts.createProgram([absoluteFilePath], {}); + const checker = program.getTypeChecker(); + const sourceFile = program.getSourceFile(absoluteFilePath); + + // console.info({filePath, absoluteFilePath}) + + if (!sourceFile) { + throw new Error(`Файл не найден: ${absoluteFilePath}`); + } + + const exports = new Set(); + + ts.forEachChild(sourceFile, (node) => { + // Обрабатываем именованные экспорты: export { x, y } или export const x = ... + if (ts.isExportDeclaration(node)) { + if (node.exportClause) { + node.exportClause.elements.forEach((element) => { + exports.add(element.name.text); + }); + } + // Реэкспорты: export * from './module' + if (node.moduleSpecifier) { + const modulePath = resolveModulePath(node.moduleSpecifier.text, absoluteFilePath); + if (modulePath) { + const reexports = getExports(modulePath, visitedFiles); + reexports.forEach((exp) => exports.add(exp)); + } + } + } + + // Экспорт через export const/let/function/class + if (ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) { + const modifiers = node.modifiers || []; + const isExported = modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword); + + if (isExported && node.name) { + exports.add(node.name.text); + } + } + + // Default экспорт: export default ... + if (ts.isExportAssignment(node)) { + exports.add("default"); + } + }); + + return Array.from(exports); +} + +/** + * Разрешает путь модуля для реэкспорта с учетом доступных расширений. + * @param {string} moduleSpecifier - Спецификатор модуля + * @param {string} currentFilePath - Текущий обрабатываемый файл + * @returns {string} Абсолютный путь к модулю + */ +function resolveModulePath(moduleSpecifier, currentFilePath) { + const dir = path.dirname(currentFilePath); + let fullPath = path.resolve(dir, moduleSpecifier); + + // Проверяем наличие файла с нужным расширением + const extensions = ["/package.json", "/index.ts", "/index.tsx", ".ts", ".tsx", ".js", ".jsx"]; + for (const ext of extensions) { + if (fs.existsSync(fullPath + ext)) { + return fullPath + ext; + } + } + + // Если модуль уже содержит расширение и файл существует, возвращаем его + if (fs.existsSync(fullPath)) { + return fullPath; + } + + console.error(`Не удалось найти модуль: ${moduleSpecifier} (по пути: ${fullPath})`); + + return null; +} + +const sortingBundleSizeMap = (data) => { +// Функция для подсчёта суммы значений второго уровня + const calculateSum = (obj) => { + return Object.values(obj).reduce((sum, value) => sum + value, 0); + }; + +// Преобразование объекта в массив с вычислением суммы для каждого ключа первого уровня + const sortableData = Object.entries(data).map(([key, value]) => ({ + key, + sum: calculateSum(value), + details: value + })); + +// Сортировка ключей первого уровня по убыванию суммы + const sortedData = sortableData.sort((a, b) => b.sum - a.sum); + +// Преобразование обратно в объект, если нужно + const sortedObject = Object.fromEntries( + sortedData.map(({ key, details }) => [key, details]) + ); + + return sortedObject; +}; + +async function getNamedExports(filePath) { + const project = new Project(); + const sourceFile = project.addSourceFileAtPath(filePath); + return sourceFile.getExportSymbols().map((symbol) => symbol.getName()); +} const packages = shell.exec( `lerna list \\ @@ -30,14 +157,53 @@ const ENTRY_POINTS = [ 'collapsible', ]; +const makeFileName = (packageName, name, path) => + path.substring(('./packages/').length).replace(/[^a-z\d-]/gi, '_') + + '.' + + name; + async function calculateBundleSize(packageName) { const entryPoints = await globby([ `./packages/${packageName}/src/{${ENTRY_POINTS.join(',')}}/index.ts`, `./packages/${packageName}/src/index.ts`, ]); + const entryPointsNamed = []; + + // const imports = [...(await parseImports(code))] + // + // console.info(entryPoints) + + + for (const filePath of entryPoints) { + // const namedExports = await getNamedExports(filePath); + let namedExports + try { + namedExports = getExports(filePath); + } catch (e) {console.error(e)} + + // console.info(filePath, namedExports, namedExports2) + + if (namedExports.length) { + for (const exportName of namedExports) { + try { + const virtualPath = + './.temp/' + makeFileName(packageName, exportName, filePath) + '.ts'; + fs.writeFileSync(virtualPath, `export { ${exportName} } from '.${filePath}';`); + entryPointsNamed.push(virtualPath); + } catch (e) { + console.error(e); + } + } + } else { + entryPointsNamed.push(filePath); + } + } + + // console.info(entryPointsNamed) + const result = await esbuild.build({ - entryPoints, + entryPoints: entryPointsNamed, bundle: true, write: false, legalComments: 'none', @@ -56,7 +222,7 @@ async function calculateBundleSize(packageName) { // Debug, показывает размер всех зависимостей пакета // if (packageName === 'date-range-input') { - // console.log(await esbuild.analyzeMetafile(result.metafile)); + // console.log(); // } const bundleSizeMap = Object.keys(result.metafile.outputs).reduce((acc, path) => { @@ -83,16 +249,29 @@ async function calculateBundleSize(packageName) { } async function run() { + const bar = new ProgressBar('[:bar] :percent', { total: packageList.length }); + let timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + console.log('\ncomplete\n'); + clearInterval(timer); + } + }, 1000); + const bundleSizeMap = {}; - while (packageList.length > 0) { + // console.info(packageList.length) + while (packageList.length > 0) { // 120 пакетов const pkgName = packageList.pop(); bundleSizeMap[pkgName] = await calculateBundleSize(pkgName); } + const sorted = sortingBundleSizeMap(bundleSizeMap); + // console.info(2, sorted); + await fs.promises.writeFile( './.storybook/package-sizes.json', - JSON.stringify(bundleSizeMap, null, 4), + JSON.stringify(sorted, null, 4), ); } diff --git a/bin/generate-docs-urls.js b/bin/generate-docs-urls.js index 483438c71e..428a6c3403 100644 --- a/bin/generate-docs-urls.js +++ b/bin/generate-docs-urls.js @@ -1,8 +1,8 @@ const path = require('path'); const fs = require('fs'); const { promisify } = require('util'); -const camelCase = require('lodash/camelcase'); -const upperfirst = require('lodash/upperfirst'); +const { camelCase } = require('lodash/camelcase'); +const { upperfirst } = require('lodash/upperfirst'); const findComponentPath = require('../tools/storybook/findComponentPath'); const readDir = promisify(fs.readdir); From 911e1242f51a2feba52992bd23edf0d630b2d772 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 16:49:48 +0300 Subject: [PATCH 05/10] fix: rollback scrollbar (old vendor inside); --- packages/scrollbar/package.json | 8 +++++-- packages/scrollbar/src/Component.tsx | 2 +- yarn.lock | 31 +++++++++++++++++++++++----- 3 files changed, 33 insertions(+), 8 deletions(-) diff --git a/packages/scrollbar/package.json b/packages/scrollbar/package.json index b238b26339..348a769e1b 100644 --- a/packages/scrollbar/package.json +++ b/packages/scrollbar/package.json @@ -18,13 +18,17 @@ "@juggle/resize-observer": "^3.3.1", "can-use-dom": "^0.1.0", "classnames": "^2.3.1", - "lodash": "^4.17.21", + "lodash.debounce": "^4.0.8", + "lodash.memoize": "^4.1.2", + "lodash.throttle": "^4.1.1", "react-merge-refs": "1.1.0", "simplebar": "^5.3.8", "tslib": "^2.4.0" }, "devDependencies": { - "@types/lodash": "^4.17.13" + "@types/lodash.debounce": "^4.0.9", + "@types/lodash.memoize": "^4.1.9", + "@types/lodash.throttle": "^4.1.9" }, "themesVersion": "13.6.0", "varsVersion": "9.16.0" diff --git a/packages/scrollbar/src/Component.tsx b/packages/scrollbar/src/Component.tsx index f90e16cfd0..421c41df58 100644 --- a/packages/scrollbar/src/Component.tsx +++ b/packages/scrollbar/src/Component.tsx @@ -1,7 +1,7 @@ import React, { HTMLAttributes, useEffect, useRef, useState } from 'react'; import mergeRefs from 'react-merge-refs'; import cn from 'classnames'; -import throttle from 'lodash/throttle'; +import throttle from 'lodash.throttle'; import SimpleBar from 'simplebar/src/simplebar'; import defaultColors from './default.module.css'; diff --git a/yarn.lock b/yarn.lock index e188b45bf6..e946568af2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5481,16 +5481,37 @@ resolved "https://registry.yarnpkg.com/@types/lockfile/-/lockfile-1.0.2.tgz#3f77e84171a2b7e3198bd5717c7547a54393baf8" integrity sha512-jD5VbvhfMhaYN4M3qPJuhMVUg3Dfc4tvPvLEAXn6GXbs/ajDFtCQahX37GIE65ipTI3I+hEvNaXS3MYAn9Ce3Q== -"@types/lodash@^4.14.167": - version "4.14.182" - resolved "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.182.tgz" - integrity sha512-/THyiqyQAP9AfARo4pF+aCGcyiQ94tX/Is2I7HofNRqoYLgN1PBoOWu2/zTA5zMxzP5EFutMtWtGAFRKUe961Q== +"@types/lodash.debounce@^4.0.9": + version "4.0.9" + resolved "https://registry.yarnpkg.com/@types/lodash.debounce/-/lodash.debounce-4.0.9.tgz#0f5f21c507bce7521b5e30e7a24440975ac860a5" + integrity sha512-Ma5JcgTREwpLRwMM+XwBR7DaWe96nC38uCBDFKZWbNKD+osjVzdpnUSwBcqCptrp16sSOLBAUb50Car5I0TCsQ== + dependencies: + "@types/lodash" "*" + +"@types/lodash.memoize@^4.1.9": + version "4.1.9" + resolved "https://registry.yarnpkg.com/@types/lodash.memoize/-/lodash.memoize-4.1.9.tgz#9f8912d39b6e450c0d342a2b74c99d331bf2016b" + integrity sha512-glY1nQuoqX4Ft8Uk+KfJudOD7DQbbEDF6k9XpGncaohW3RW4eSWBlx6AA0fZCrh40tZcQNH4jS/Oc59J6Eq+aw== + dependencies: + "@types/lodash" "*" -"@types/lodash@^4.17.13": +"@types/lodash.throttle@^4.1.9": + version "4.1.9" + resolved "https://registry.yarnpkg.com/@types/lodash.throttle/-/lodash.throttle-4.1.9.tgz#f17a6ae084f7c0117bd7df145b379537bc9615c5" + integrity sha512-PCPVfpfueguWZQB7pJQK890F2scYKoDUL3iM522AptHWn7d5NQmeS/LTEHIcLr5PaTzl3dK2Z0xSUHHTHwaL5g== + dependencies: + "@types/lodash" "*" + +"@types/lodash@*", "@types/lodash@^4.17.13": version "4.17.13" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.17.13.tgz#786e2d67cfd95e32862143abe7463a7f90c300eb" integrity sha512-lfx+dftrEZcdBPczf9d0Qv0x+j/rfNCMuC6OcfXmO8gkfeNAY88PgKUbvG56whcN23gc27yenwF6oJZXGFpYxg== +"@types/lodash@^4.14.167": + version "4.14.182" + resolved "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.182.tgz" + integrity sha512-/THyiqyQAP9AfARo4pF+aCGcyiQ94tX/Is2I7HofNRqoYLgN1PBoOWu2/zTA5zMxzP5EFutMtWtGAFRKUe961Q== + "@types/mdast@^3.0.0": version "3.0.3" resolved "https://registry.npmjs.org/@types/mdast/-/mdast-3.0.3.tgz" From 0f80dde5d518513a729f7b8a37e889d54ffb5d74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 17:00:47 +0300 Subject: [PATCH 06/10] fix: rollback code; --- bin/analyze-package-sizes.mjs | 187 +-------------------- bin/analyze-package-sizes_my.mjs | 280 +++++++++++++++++++++++++++++++ 2 files changed, 284 insertions(+), 183 deletions(-) create mode 100644 bin/analyze-package-sizes_my.mjs diff --git a/bin/analyze-package-sizes.mjs b/bin/analyze-package-sizes.mjs index 1077889d22..8725dfb25b 100644 --- a/bin/analyze-package-sizes.mjs +++ b/bin/analyze-package-sizes.mjs @@ -2,133 +2,6 @@ import * as esbuild from 'esbuild'; import globby from 'globby'; import shell from 'shelljs'; import fs from 'node:fs'; -import { Project } from 'ts-morph'; -import path from 'path'; -import ts from 'typescript'; -import ProgressBar from 'progress'; - -// import { parseImports } from 'parse-imports' - -/** - * Получает список всех экспортов из TypeScript файла, включая реэкспорты. - * @param {string} filePath - Путь к файлу - * @param {Set} visitedFiles - Для предотвращения циклов при рекурсивных вызовах - * @returns {string[]} Список имен экспортов - */ -function getExports(filePath, visitedFiles = new Set()) { - const absoluteFilePath = path.resolve(filePath); - - // Проверяем, что файл ещё не обрабатывался - if (visitedFiles.has(absoluteFilePath)) return []; - visitedFiles.add(absoluteFilePath); - - // Создаем программу TypeScript - const program = ts.createProgram([absoluteFilePath], {}); - const checker = program.getTypeChecker(); - const sourceFile = program.getSourceFile(absoluteFilePath); - - // console.info({filePath, absoluteFilePath}) - - if (!sourceFile) { - throw new Error(`Файл не найден: ${absoluteFilePath}`); - } - - const exports = new Set(); - - ts.forEachChild(sourceFile, (node) => { - // Обрабатываем именованные экспорты: export { x, y } или export const x = ... - if (ts.isExportDeclaration(node)) { - if (node.exportClause) { - node.exportClause.elements.forEach((element) => { - exports.add(element.name.text); - }); - } - // Реэкспорты: export * from './module' - if (node.moduleSpecifier) { - const modulePath = resolveModulePath(node.moduleSpecifier.text, absoluteFilePath); - if (modulePath) { - const reexports = getExports(modulePath, visitedFiles); - reexports.forEach((exp) => exports.add(exp)); - } - } - } - - // Экспорт через export const/let/function/class - if (ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) { - const modifiers = node.modifiers || []; - const isExported = modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword); - - if (isExported && node.name) { - exports.add(node.name.text); - } - } - - // Default экспорт: export default ... - if (ts.isExportAssignment(node)) { - exports.add("default"); - } - }); - - return Array.from(exports); -} - -/** - * Разрешает путь модуля для реэкспорта с учетом доступных расширений. - * @param {string} moduleSpecifier - Спецификатор модуля - * @param {string} currentFilePath - Текущий обрабатываемый файл - * @returns {string} Абсолютный путь к модулю - */ -function resolveModulePath(moduleSpecifier, currentFilePath) { - const dir = path.dirname(currentFilePath); - let fullPath = path.resolve(dir, moduleSpecifier); - - // Проверяем наличие файла с нужным расширением - const extensions = ["/package.json", "/index.ts", "/index.tsx", ".ts", ".tsx", ".js", ".jsx"]; - for (const ext of extensions) { - if (fs.existsSync(fullPath + ext)) { - return fullPath + ext; - } - } - - // Если модуль уже содержит расширение и файл существует, возвращаем его - if (fs.existsSync(fullPath)) { - return fullPath; - } - - console.error(`Не удалось найти модуль: ${moduleSpecifier} (по пути: ${fullPath})`); - - return null; -} - -const sortingBundleSizeMap = (data) => { -// Функция для подсчёта суммы значений второго уровня - const calculateSum = (obj) => { - return Object.values(obj).reduce((sum, value) => sum + value, 0); - }; - -// Преобразование объекта в массив с вычислением суммы для каждого ключа первого уровня - const sortableData = Object.entries(data).map(([key, value]) => ({ - key, - sum: calculateSum(value), - details: value - })); - -// Сортировка ключей первого уровня по убыванию суммы - const sortedData = sortableData.sort((a, b) => b.sum - a.sum); - -// Преобразование обратно в объект, если нужно - const sortedObject = Object.fromEntries( - sortedData.map(({ key, details }) => [key, details]) - ); - - return sortedObject; -}; - -async function getNamedExports(filePath) { - const project = new Project(); - const sourceFile = project.addSourceFileAtPath(filePath); - return sourceFile.getExportSymbols().map((symbol) => symbol.getName()); -} const packages = shell.exec( `lerna list \\ @@ -157,53 +30,14 @@ const ENTRY_POINTS = [ 'collapsible', ]; -const makeFileName = (packageName, name, path) => - path.substring(('./packages/').length).replace(/[^a-z\d-]/gi, '_') + - '.' + - name; - async function calculateBundleSize(packageName) { const entryPoints = await globby([ `./packages/${packageName}/src/{${ENTRY_POINTS.join(',')}}/index.ts`, `./packages/${packageName}/src/index.ts`, ]); - const entryPointsNamed = []; - - // const imports = [...(await parseImports(code))] - // - // console.info(entryPoints) - - - for (const filePath of entryPoints) { - // const namedExports = await getNamedExports(filePath); - let namedExports - try { - namedExports = getExports(filePath); - } catch (e) {console.error(e)} - - // console.info(filePath, namedExports, namedExports2) - - if (namedExports.length) { - for (const exportName of namedExports) { - try { - const virtualPath = - './.temp/' + makeFileName(packageName, exportName, filePath) + '.ts'; - fs.writeFileSync(virtualPath, `export { ${exportName} } from '.${filePath}';`); - entryPointsNamed.push(virtualPath); - } catch (e) { - console.error(e); - } - } - } else { - entryPointsNamed.push(filePath); - } - } - - // console.info(entryPointsNamed) - const result = await esbuild.build({ - entryPoints: entryPointsNamed, + entryPoints, bundle: true, write: false, legalComments: 'none', @@ -222,7 +56,7 @@ async function calculateBundleSize(packageName) { // Debug, показывает размер всех зависимостей пакета // if (packageName === 'date-range-input') { - // console.log(); + // console.log(await esbuild.analyzeMetafile(result.metafile)); // } const bundleSizeMap = Object.keys(result.metafile.outputs).reduce((acc, path) => { @@ -249,29 +83,16 @@ async function calculateBundleSize(packageName) { } async function run() { - const bar = new ProgressBar('[:bar] :percent', { total: packageList.length }); - let timer = setInterval(function () { - bar.tick(); - if (bar.complete) { - console.log('\ncomplete\n'); - clearInterval(timer); - } - }, 1000); - const bundleSizeMap = {}; - // console.info(packageList.length) - while (packageList.length > 0) { // 120 пакетов + while (packageList.length > 0) { const pkgName = packageList.pop(); bundleSizeMap[pkgName] = await calculateBundleSize(pkgName); } - const sorted = sortingBundleSizeMap(bundleSizeMap); - // console.info(2, sorted); - await fs.promises.writeFile( './.storybook/package-sizes.json', - JSON.stringify(sorted, null, 4), + JSON.stringify(bundleSizeMap, null, 4), ); } diff --git a/bin/analyze-package-sizes_my.mjs b/bin/analyze-package-sizes_my.mjs new file mode 100644 index 0000000000..1077889d22 --- /dev/null +++ b/bin/analyze-package-sizes_my.mjs @@ -0,0 +1,280 @@ +import * as esbuild from 'esbuild'; +import globby from 'globby'; +import shell from 'shelljs'; +import fs from 'node:fs'; +import { Project } from 'ts-morph'; +import path from 'path'; +import ts from 'typescript'; +import ProgressBar from 'progress'; + +// import { parseImports } from 'parse-imports' + +/** + * Получает список всех экспортов из TypeScript файла, включая реэкспорты. + * @param {string} filePath - Путь к файлу + * @param {Set} visitedFiles - Для предотвращения циклов при рекурсивных вызовах + * @returns {string[]} Список имен экспортов + */ +function getExports(filePath, visitedFiles = new Set()) { + const absoluteFilePath = path.resolve(filePath); + + // Проверяем, что файл ещё не обрабатывался + if (visitedFiles.has(absoluteFilePath)) return []; + visitedFiles.add(absoluteFilePath); + + // Создаем программу TypeScript + const program = ts.createProgram([absoluteFilePath], {}); + const checker = program.getTypeChecker(); + const sourceFile = program.getSourceFile(absoluteFilePath); + + // console.info({filePath, absoluteFilePath}) + + if (!sourceFile) { + throw new Error(`Файл не найден: ${absoluteFilePath}`); + } + + const exports = new Set(); + + ts.forEachChild(sourceFile, (node) => { + // Обрабатываем именованные экспорты: export { x, y } или export const x = ... + if (ts.isExportDeclaration(node)) { + if (node.exportClause) { + node.exportClause.elements.forEach((element) => { + exports.add(element.name.text); + }); + } + // Реэкспорты: export * from './module' + if (node.moduleSpecifier) { + const modulePath = resolveModulePath(node.moduleSpecifier.text, absoluteFilePath); + if (modulePath) { + const reexports = getExports(modulePath, visitedFiles); + reexports.forEach((exp) => exports.add(exp)); + } + } + } + + // Экспорт через export const/let/function/class + if (ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) { + const modifiers = node.modifiers || []; + const isExported = modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword); + + if (isExported && node.name) { + exports.add(node.name.text); + } + } + + // Default экспорт: export default ... + if (ts.isExportAssignment(node)) { + exports.add("default"); + } + }); + + return Array.from(exports); +} + +/** + * Разрешает путь модуля для реэкспорта с учетом доступных расширений. + * @param {string} moduleSpecifier - Спецификатор модуля + * @param {string} currentFilePath - Текущий обрабатываемый файл + * @returns {string} Абсолютный путь к модулю + */ +function resolveModulePath(moduleSpecifier, currentFilePath) { + const dir = path.dirname(currentFilePath); + let fullPath = path.resolve(dir, moduleSpecifier); + + // Проверяем наличие файла с нужным расширением + const extensions = ["/package.json", "/index.ts", "/index.tsx", ".ts", ".tsx", ".js", ".jsx"]; + for (const ext of extensions) { + if (fs.existsSync(fullPath + ext)) { + return fullPath + ext; + } + } + + // Если модуль уже содержит расширение и файл существует, возвращаем его + if (fs.existsSync(fullPath)) { + return fullPath; + } + + console.error(`Не удалось найти модуль: ${moduleSpecifier} (по пути: ${fullPath})`); + + return null; +} + +const sortingBundleSizeMap = (data) => { +// Функция для подсчёта суммы значений второго уровня + const calculateSum = (obj) => { + return Object.values(obj).reduce((sum, value) => sum + value, 0); + }; + +// Преобразование объекта в массив с вычислением суммы для каждого ключа первого уровня + const sortableData = Object.entries(data).map(([key, value]) => ({ + key, + sum: calculateSum(value), + details: value + })); + +// Сортировка ключей первого уровня по убыванию суммы + const sortedData = sortableData.sort((a, b) => b.sum - a.sum); + +// Преобразование обратно в объект, если нужно + const sortedObject = Object.fromEntries( + sortedData.map(({ key, details }) => [key, details]) + ); + + return sortedObject; +}; + +async function getNamedExports(filePath) { + const project = new Project(); + const sourceFile = project.addSourceFileAtPath(filePath); + return sourceFile.getExportSymbols().map((symbol) => symbol.getName()); +} + +const packages = shell.exec( + `lerna list \\ + --ignore @alfalab/core-components-codemod \\ + --ignore @alfalab/core-components-vars \\ + --ignore @alfalab/core-components-themes \\ + --all`, + { silent: true }, +).stdout; + +const packageList = packages + .split('\n') + .map((pkg) => pkg.trim()) + .filter(Boolean) + .map((pkg) => pkg.replace('@alfalab/core-components-', '')); + +const ENTRY_POINTS = [ + 'desktop', + 'mobile', + 'responsive', + 'circle', + 'super-ellipse', + 'rectangle', + 'no-shape', + 'shared', + 'collapsible', +]; + +const makeFileName = (packageName, name, path) => + path.substring(('./packages/').length).replace(/[^a-z\d-]/gi, '_') + + '.' + + name; + +async function calculateBundleSize(packageName) { + const entryPoints = await globby([ + `./packages/${packageName}/src/{${ENTRY_POINTS.join(',')}}/index.ts`, + `./packages/${packageName}/src/index.ts`, + ]); + + const entryPointsNamed = []; + + // const imports = [...(await parseImports(code))] + // + // console.info(entryPoints) + + + for (const filePath of entryPoints) { + // const namedExports = await getNamedExports(filePath); + let namedExports + try { + namedExports = getExports(filePath); + } catch (e) {console.error(e)} + + // console.info(filePath, namedExports, namedExports2) + + if (namedExports.length) { + for (const exportName of namedExports) { + try { + const virtualPath = + './.temp/' + makeFileName(packageName, exportName, filePath) + '.ts'; + fs.writeFileSync(virtualPath, `export { ${exportName} } from '.${filePath}';`); + entryPointsNamed.push(virtualPath); + } catch (e) { + console.error(e); + } + } + } else { + entryPointsNamed.push(filePath); + } + } + + // console.info(entryPointsNamed) + + const result = await esbuild.build({ + entryPoints: entryPointsNamed, + bundle: true, + write: false, + legalComments: 'none', + outdir: `packages/${packageName}`, + minify: true, + minifyWhitespace: true, + minifyIdentifiers: true, + minifySyntax: true, + sourcemap: false, + treeShaking: true, + target: 'esnext', + format: 'esm', + external: ['react', 'react-dom', '*.css'], + metafile: true, + }); + + // Debug, показывает размер всех зависимостей пакета + // if (packageName === 'date-range-input') { + // console.log(); + // } + + const bundleSizeMap = Object.keys(result.metafile.outputs).reduce((acc, path) => { + const pathParts = path.split('/'); + const entry = + pathParts.slice(-2)[0] === packageName + ? pathParts.slice(-1)[0] + : pathParts.slice(-2)[0]; + + acc[entry.endsWith('.js') ? entry : entry + '.js'] = +( + result.metafile.outputs[path].bytes / 1024 + ).toFixed(1); + + return acc; + }, {}); + + // Сортируем ключи по алфавиту, иначе выводятся в случайном порядке + return Object.keys(bundleSizeMap) + .sort() + .reduce((obj, key) => { + obj[key] = bundleSizeMap[key]; + return obj; + }, {}); +} + +async function run() { + const bar = new ProgressBar('[:bar] :percent', { total: packageList.length }); + let timer = setInterval(function () { + bar.tick(); + if (bar.complete) { + console.log('\ncomplete\n'); + clearInterval(timer); + } + }, 1000); + + const bundleSizeMap = {}; + // console.info(packageList.length) + while (packageList.length > 0) { // 120 пакетов + const pkgName = packageList.pop(); + + bundleSizeMap[pkgName] = await calculateBundleSize(pkgName); + } + + const sorted = sortingBundleSizeMap(bundleSizeMap); + // console.info(2, sorted); + + await fs.promises.writeFile( + './.storybook/package-sizes.json', + JSON.stringify(sorted, null, 4), + ); +} + +run() + .then(() => process.exit(0)) + .catch(() => process.exit(1)); From e8f73de2b818892351b494f039e92109b0b5fcb3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 17:04:06 +0300 Subject: [PATCH 07/10] fix: rollback code; --- bin/analyze-package-sizes_my.mjs | 280 ------------------------------- 1 file changed, 280 deletions(-) delete mode 100644 bin/analyze-package-sizes_my.mjs diff --git a/bin/analyze-package-sizes_my.mjs b/bin/analyze-package-sizes_my.mjs deleted file mode 100644 index 1077889d22..0000000000 --- a/bin/analyze-package-sizes_my.mjs +++ /dev/null @@ -1,280 +0,0 @@ -import * as esbuild from 'esbuild'; -import globby from 'globby'; -import shell from 'shelljs'; -import fs from 'node:fs'; -import { Project } from 'ts-morph'; -import path from 'path'; -import ts from 'typescript'; -import ProgressBar from 'progress'; - -// import { parseImports } from 'parse-imports' - -/** - * Получает список всех экспортов из TypeScript файла, включая реэкспорты. - * @param {string} filePath - Путь к файлу - * @param {Set} visitedFiles - Для предотвращения циклов при рекурсивных вызовах - * @returns {string[]} Список имен экспортов - */ -function getExports(filePath, visitedFiles = new Set()) { - const absoluteFilePath = path.resolve(filePath); - - // Проверяем, что файл ещё не обрабатывался - if (visitedFiles.has(absoluteFilePath)) return []; - visitedFiles.add(absoluteFilePath); - - // Создаем программу TypeScript - const program = ts.createProgram([absoluteFilePath], {}); - const checker = program.getTypeChecker(); - const sourceFile = program.getSourceFile(absoluteFilePath); - - // console.info({filePath, absoluteFilePath}) - - if (!sourceFile) { - throw new Error(`Файл не найден: ${absoluteFilePath}`); - } - - const exports = new Set(); - - ts.forEachChild(sourceFile, (node) => { - // Обрабатываем именованные экспорты: export { x, y } или export const x = ... - if (ts.isExportDeclaration(node)) { - if (node.exportClause) { - node.exportClause.elements.forEach((element) => { - exports.add(element.name.text); - }); - } - // Реэкспорты: export * from './module' - if (node.moduleSpecifier) { - const modulePath = resolveModulePath(node.moduleSpecifier.text, absoluteFilePath); - if (modulePath) { - const reexports = getExports(modulePath, visitedFiles); - reexports.forEach((exp) => exports.add(exp)); - } - } - } - - // Экспорт через export const/let/function/class - if (ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) { - const modifiers = node.modifiers || []; - const isExported = modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword); - - if (isExported && node.name) { - exports.add(node.name.text); - } - } - - // Default экспорт: export default ... - if (ts.isExportAssignment(node)) { - exports.add("default"); - } - }); - - return Array.from(exports); -} - -/** - * Разрешает путь модуля для реэкспорта с учетом доступных расширений. - * @param {string} moduleSpecifier - Спецификатор модуля - * @param {string} currentFilePath - Текущий обрабатываемый файл - * @returns {string} Абсолютный путь к модулю - */ -function resolveModulePath(moduleSpecifier, currentFilePath) { - const dir = path.dirname(currentFilePath); - let fullPath = path.resolve(dir, moduleSpecifier); - - // Проверяем наличие файла с нужным расширением - const extensions = ["/package.json", "/index.ts", "/index.tsx", ".ts", ".tsx", ".js", ".jsx"]; - for (const ext of extensions) { - if (fs.existsSync(fullPath + ext)) { - return fullPath + ext; - } - } - - // Если модуль уже содержит расширение и файл существует, возвращаем его - if (fs.existsSync(fullPath)) { - return fullPath; - } - - console.error(`Не удалось найти модуль: ${moduleSpecifier} (по пути: ${fullPath})`); - - return null; -} - -const sortingBundleSizeMap = (data) => { -// Функция для подсчёта суммы значений второго уровня - const calculateSum = (obj) => { - return Object.values(obj).reduce((sum, value) => sum + value, 0); - }; - -// Преобразование объекта в массив с вычислением суммы для каждого ключа первого уровня - const sortableData = Object.entries(data).map(([key, value]) => ({ - key, - sum: calculateSum(value), - details: value - })); - -// Сортировка ключей первого уровня по убыванию суммы - const sortedData = sortableData.sort((a, b) => b.sum - a.sum); - -// Преобразование обратно в объект, если нужно - const sortedObject = Object.fromEntries( - sortedData.map(({ key, details }) => [key, details]) - ); - - return sortedObject; -}; - -async function getNamedExports(filePath) { - const project = new Project(); - const sourceFile = project.addSourceFileAtPath(filePath); - return sourceFile.getExportSymbols().map((symbol) => symbol.getName()); -} - -const packages = shell.exec( - `lerna list \\ - --ignore @alfalab/core-components-codemod \\ - --ignore @alfalab/core-components-vars \\ - --ignore @alfalab/core-components-themes \\ - --all`, - { silent: true }, -).stdout; - -const packageList = packages - .split('\n') - .map((pkg) => pkg.trim()) - .filter(Boolean) - .map((pkg) => pkg.replace('@alfalab/core-components-', '')); - -const ENTRY_POINTS = [ - 'desktop', - 'mobile', - 'responsive', - 'circle', - 'super-ellipse', - 'rectangle', - 'no-shape', - 'shared', - 'collapsible', -]; - -const makeFileName = (packageName, name, path) => - path.substring(('./packages/').length).replace(/[^a-z\d-]/gi, '_') + - '.' + - name; - -async function calculateBundleSize(packageName) { - const entryPoints = await globby([ - `./packages/${packageName}/src/{${ENTRY_POINTS.join(',')}}/index.ts`, - `./packages/${packageName}/src/index.ts`, - ]); - - const entryPointsNamed = []; - - // const imports = [...(await parseImports(code))] - // - // console.info(entryPoints) - - - for (const filePath of entryPoints) { - // const namedExports = await getNamedExports(filePath); - let namedExports - try { - namedExports = getExports(filePath); - } catch (e) {console.error(e)} - - // console.info(filePath, namedExports, namedExports2) - - if (namedExports.length) { - for (const exportName of namedExports) { - try { - const virtualPath = - './.temp/' + makeFileName(packageName, exportName, filePath) + '.ts'; - fs.writeFileSync(virtualPath, `export { ${exportName} } from '.${filePath}';`); - entryPointsNamed.push(virtualPath); - } catch (e) { - console.error(e); - } - } - } else { - entryPointsNamed.push(filePath); - } - } - - // console.info(entryPointsNamed) - - const result = await esbuild.build({ - entryPoints: entryPointsNamed, - bundle: true, - write: false, - legalComments: 'none', - outdir: `packages/${packageName}`, - minify: true, - minifyWhitespace: true, - minifyIdentifiers: true, - minifySyntax: true, - sourcemap: false, - treeShaking: true, - target: 'esnext', - format: 'esm', - external: ['react', 'react-dom', '*.css'], - metafile: true, - }); - - // Debug, показывает размер всех зависимостей пакета - // if (packageName === 'date-range-input') { - // console.log(); - // } - - const bundleSizeMap = Object.keys(result.metafile.outputs).reduce((acc, path) => { - const pathParts = path.split('/'); - const entry = - pathParts.slice(-2)[0] === packageName - ? pathParts.slice(-1)[0] - : pathParts.slice(-2)[0]; - - acc[entry.endsWith('.js') ? entry : entry + '.js'] = +( - result.metafile.outputs[path].bytes / 1024 - ).toFixed(1); - - return acc; - }, {}); - - // Сортируем ключи по алфавиту, иначе выводятся в случайном порядке - return Object.keys(bundleSizeMap) - .sort() - .reduce((obj, key) => { - obj[key] = bundleSizeMap[key]; - return obj; - }, {}); -} - -async function run() { - const bar = new ProgressBar('[:bar] :percent', { total: packageList.length }); - let timer = setInterval(function () { - bar.tick(); - if (bar.complete) { - console.log('\ncomplete\n'); - clearInterval(timer); - } - }, 1000); - - const bundleSizeMap = {}; - // console.info(packageList.length) - while (packageList.length > 0) { // 120 пакетов - const pkgName = packageList.pop(); - - bundleSizeMap[pkgName] = await calculateBundleSize(pkgName); - } - - const sorted = sortingBundleSizeMap(bundleSizeMap); - // console.info(2, sorted); - - await fs.promises.writeFile( - './.storybook/package-sizes.json', - JSON.stringify(sorted, null, 4), - ); -} - -run() - .then(() => process.exit(0)) - .catch(() => process.exit(1)); From 3a1162b4b30b3e0e14255a70eede23ee0e072419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 18:32:30 +0300 Subject: [PATCH 08/10] fix: imports; --- .storybook/pages/components-overview/components/card/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.storybook/pages/components-overview/components/card/index.tsx b/.storybook/pages/components-overview/components/card/index.tsx index 58465620bc..b7d8a956f6 100644 --- a/.storybook/pages/components-overview/components/card/index.tsx +++ b/.storybook/pages/components-overview/components/card/index.tsx @@ -1,6 +1,6 @@ import React from 'react'; -import kebab from 'lodash/kebabcase'; import cn from 'classnames'; +import kebab from 'lodash/kebabCase'; import { Typography } from '@alfalab/core-components-typography'; From 8555f476f752b3dd718e3b283b1fded2063b970d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Denis=20=F0=9F=8E=83=20Khripkov?= Date: Mon, 2 Dec 2024 18:58:35 +0300 Subject: [PATCH 09/10] fix: imports; --- .changeset/beige-kangaroos-try.md | 1 - packages/screenshot-utils/createStorybookUrl.ts | 2 +- packages/screenshot-utils/helpers.ts | 2 +- packages/scrollbar/package.json | 4 +--- yarn.lock | 16 +--------------- 5 files changed, 4 insertions(+), 21 deletions(-) diff --git a/.changeset/beige-kangaroos-try.md b/.changeset/beige-kangaroos-try.md index dcf60a6aef..931ab55cd0 100644 --- a/.changeset/beige-kangaroos-try.md +++ b/.changeset/beige-kangaroos-try.md @@ -1,7 +1,6 @@ --- '@alfalab/core-components-collapse': minor '@alfalab/core-components-input-autocomplete': minor -'@alfalab/core-components-scrollbar': minor '@alfalab/core-components-tabs': minor --- diff --git a/packages/screenshot-utils/createStorybookUrl.ts b/packages/screenshot-utils/createStorybookUrl.ts index faadba006e..b5cffe72a6 100644 --- a/packages/screenshot-utils/createStorybookUrl.ts +++ b/packages/screenshot-utils/createStorybookUrl.ts @@ -1,4 +1,4 @@ -import kebab from 'lodash/kebabcase'; +import kebab from 'lodash/kebabCase'; import findComponentPath from '../../tools/storybook/findComponentPath'; diff --git a/packages/screenshot-utils/helpers.ts b/packages/screenshot-utils/helpers.ts index f74a26e2d1..eb3b4859c9 100644 --- a/packages/screenshot-utils/helpers.ts +++ b/packages/screenshot-utils/helpers.ts @@ -14,7 +14,7 @@ import { } from 'playwright'; import axios from 'axios'; import { MatchImageSnapshotOptions } from 'jest-image-snapshot'; -import kebab from 'lodash/kebabcase'; +import kebab from 'lodash/kebabCase'; import { ScreenshotOpts, EvaluateFn } from './setupScreenshotTesting'; type CustomSnapshotIdentifierParams = { diff --git a/packages/scrollbar/package.json b/packages/scrollbar/package.json index 348a769e1b..dc022bcd49 100644 --- a/packages/scrollbar/package.json +++ b/packages/scrollbar/package.json @@ -26,9 +26,7 @@ "tslib": "^2.4.0" }, "devDependencies": { - "@types/lodash.debounce": "^4.0.9", - "@types/lodash.memoize": "^4.1.9", - "@types/lodash.throttle": "^4.1.9" + "@types/lodash.throttle": "^4.1.7" }, "themesVersion": "13.6.0", "varsVersion": "9.16.0" diff --git a/yarn.lock b/yarn.lock index e946568af2..a66b19231f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5481,21 +5481,7 @@ resolved "https://registry.yarnpkg.com/@types/lockfile/-/lockfile-1.0.2.tgz#3f77e84171a2b7e3198bd5717c7547a54393baf8" integrity sha512-jD5VbvhfMhaYN4M3qPJuhMVUg3Dfc4tvPvLEAXn6GXbs/ajDFtCQahX37GIE65ipTI3I+hEvNaXS3MYAn9Ce3Q== -"@types/lodash.debounce@^4.0.9": - version "4.0.9" - resolved "https://registry.yarnpkg.com/@types/lodash.debounce/-/lodash.debounce-4.0.9.tgz#0f5f21c507bce7521b5e30e7a24440975ac860a5" - integrity sha512-Ma5JcgTREwpLRwMM+XwBR7DaWe96nC38uCBDFKZWbNKD+osjVzdpnUSwBcqCptrp16sSOLBAUb50Car5I0TCsQ== - dependencies: - "@types/lodash" "*" - -"@types/lodash.memoize@^4.1.9": - version "4.1.9" - resolved "https://registry.yarnpkg.com/@types/lodash.memoize/-/lodash.memoize-4.1.9.tgz#9f8912d39b6e450c0d342a2b74c99d331bf2016b" - integrity sha512-glY1nQuoqX4Ft8Uk+KfJudOD7DQbbEDF6k9XpGncaohW3RW4eSWBlx6AA0fZCrh40tZcQNH4jS/Oc59J6Eq+aw== - dependencies: - "@types/lodash" "*" - -"@types/lodash.throttle@^4.1.9": +"@types/lodash.throttle@^4.1.7": version "4.1.9" resolved "https://registry.yarnpkg.com/@types/lodash.throttle/-/lodash.throttle-4.1.9.tgz#f17a6ae084f7c0117bd7df145b379537bc9615c5" integrity sha512-PCPVfpfueguWZQB7pJQK890F2scYKoDUL3iM522AptHWn7d5NQmeS/LTEHIcLr5PaTzl3dK2Z0xSUHHTHwaL5g== From 72520601b2fdb5b4a094771cc32b68beaa5953dc Mon Sep 17 00:00:00 2001 From: denisx Date: Thu, 5 Dec 2024 11:30:57 +0300 Subject: [PATCH 10/10] Update beige-kangaroos-try.md Change minor -> patch --- .changeset/beige-kangaroos-try.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.changeset/beige-kangaroos-try.md b/.changeset/beige-kangaroos-try.md index 931ab55cd0..a643b92ec9 100644 --- a/.changeset/beige-kangaroos-try.md +++ b/.changeset/beige-kangaroos-try.md @@ -1,7 +1,7 @@ --- -'@alfalab/core-components-collapse': minor -'@alfalab/core-components-input-autocomplete': minor -'@alfalab/core-components-tabs': minor +'@alfalab/core-components-collapse': patch +'@alfalab/core-components-input-autocomplete': patch +'@alfalab/core-components-tabs': patch --- - Замена использование lodash на коммон пакет