@bigbinary/babel-preset-neeto 1.0.2

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 (52) hide show
  1. package/.editorconfig +10 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc.js +6 -0
  4. package/.github/CODEOWNERS +1 -0
  5. package/.github/pull_request_template.md +18 -0
  6. package/.github/release-drafter.yml +8 -0
  7. package/.github/workflows/auto_update_prs_with_latest_main.yml +15 -0
  8. package/.github/workflows/create_and_publish_releases.yml +77 -0
  9. package/.github/workflows/publish.yml +26 -0
  10. package/.husky/helpers/lint_staged.sh +5 -0
  11. package/.husky/pre-commit +5 -0
  12. package/.node-version +1 -0
  13. package/.nvmrc +1 -0
  14. package/.prettierignore +1 -0
  15. package/.prettierrc.js +1 -0
  16. package/.scripts/run_eslint_on_modified_files.sh +5 -0
  17. package/.semaphore/semaphore.yml +32 -0
  18. package/README.md +71 -0
  19. package/babel.config.js +1 -0
  20. package/docs/zustand-pick.md +159 -0
  21. package/index.js +5 -0
  22. package/jsconfig.json +19 -0
  23. package/package.json +66 -0
  24. package/src/plugins/messages.js +8 -0
  25. package/src/plugins/utils.js +41 -0
  26. package/src/plugins/zustand-pick/constants.js +75 -0
  27. package/src/plugins/zustand-pick/index.js +94 -0
  28. package/src/tests/utils.js +38 -0
  29. package/src/tests/zustand-pick/no-changes/non-pick-calls.js +1 -0
  30. package/src/tests/zustand-pick/no-changes/non-standard-zustand-store.js +1 -0
  31. package/src/tests/zustand-pick/no-changes/normal-zustand-calls.js +1 -0
  32. package/src/tests/zustand-pick/syntax-errors/direct-pick-access1.js +1 -0
  33. package/src/tests/zustand-pick/syntax-errors/direct-pick-access2.js +1 -0
  34. package/src/tests/zustand-pick/syntax-errors/pick-multiple-arguments.js +1 -0
  35. package/src/tests/zustand-pick/syntax-errors/pick-nested-properties.js +3 -0
  36. package/src/tests/zustand-pick/syntax-errors/pick-path-array-expressions.js +1 -0
  37. package/src/tests/zustand-pick/syntax-errors/pick-path-array-templates.js +1 -0
  38. package/src/tests/zustand-pick/transformations/array-pick/input.js +6 -0
  39. package/src/tests/zustand-pick/transformations/array-pick/output.js +8 -0
  40. package/src/tests/zustand-pick/transformations/dynamic-declare/input.js +2 -0
  41. package/src/tests/zustand-pick/transformations/dynamic-declare/output.js +13 -0
  42. package/src/tests/zustand-pick/transformations/dynamic-pick/input.js +1 -0
  43. package/src/tests/zustand-pick/transformations/dynamic-pick/output.js +7 -0
  44. package/src/tests/zustand-pick/transformations/empty-pick/input.js +1 -0
  45. package/src/tests/zustand-pick/transformations/empty-pick/output.js +8 -0
  46. package/src/tests/zustand-pick/transformations/no-duplicate-import/input.js +2 -0
  47. package/src/tests/zustand-pick/transformations/no-duplicate-import/output.js +8 -0
  48. package/src/tests/zustand-pick/transformations/string-pick/input.js +1 -0
  49. package/src/tests/zustand-pick/transformations/string-pick/output.js +9 -0
  50. package/src/tests/zustand-pick/transformations/with-other-imports/input.js +4 -0
  51. package/src/tests/zustand-pick/transformations/with-other-imports/output.js +10 -0
  52. package/src/tests/zustand-pick/zustand-pick.spec.js +18 -0
package/.editorconfig ADDED
@@ -0,0 +1,10 @@
1
+ # VScode respects this. More info at editorconfig.org
2
+ root = true
3
+
4
+ [*]
5
+ charset = utf-8
6
+ end_of_line = lf
7
+ indent_size = 2
8
+ indent_style = space
9
+ insert_final_newline = true
10
+ trim_trailing_whitespace = true
package/.eslintignore ADDED
@@ -0,0 +1,3 @@
1
+ src/tests/*/syntax-errors/*.js
2
+ src/tests/*/no-changes/*.js
3
+ src/tests/*/transformations/**/*.js
package/.eslintrc.js ADDED
@@ -0,0 +1,6 @@
1
+ // eslint-disable-next-line import/extensions
2
+ const defaultConfig = require("@bigbinary/neeto-commons-frontend/configs/nanos/eslint/index.js");
3
+
4
+ defaultConfig.rules["@bigbinary/neeto/file-name-and-export-name-standards"] =
5
+ "off";
6
+ module.exports = defaultConfig;
@@ -0,0 +1 @@
1
+ * @Amaljith-K
@@ -0,0 +1,18 @@
1
+ - Fixes #issue_number
2
+
3
+ **Description**
4
+
5
+ **Checklist**
6
+
7
+ - [ ] I have made corresponding changes to the documentation.
8
+ - [ ] I have verified the functionality in some of the neeto web-apps.
9
+ - [ ] I have added the necessary label (patch/minor/major - If package publish
10
+ is required).
11
+
12
+ **Reviewers**
13
+
14
+ <!---
15
+ ------------- NOTES -------------
16
+ 1. Do not add a patch/minor/major label if a release is not required.
17
+ 2. Strike through the points ~~like this~~ if not applicable.
18
+ --->
@@ -0,0 +1,8 @@
1
+ name-template: "v$RESOLVED_VERSION"
2
+ tag-template: "v$RESOLVED_VERSION"
3
+ template: |
4
+ ## What's Changed
5
+ $CHANGES
6
+
7
+
8
+ **Full Changelog**: https://github.com/bigbinary/$REPOSITORY/compare/$PREVIOUS_TAG...v$RESOLVED_VERSION
@@ -0,0 +1,15 @@
1
+ name: PR-autoupdate-from-main
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+
8
+ jobs:
9
+ Auto:
10
+ name: Auto-update
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: bigbinary/pr-auto-update@v2.1.6
14
+ with:
15
+ github_token: ${{ secrets.AUTOREBASE_TOKEN }}
@@ -0,0 +1,77 @@
1
+ name: "Create and publish releases"
2
+ on:
3
+ pull_request:
4
+ branches:
5
+ - main
6
+ types: [closed]
7
+ jobs:
8
+ release:
9
+ name: "Create Release"
10
+ runs-on: ubuntu-latest
11
+ if: >-
12
+ ${{ github.event.pull_request.merged == true && (
13
+ contains(github.event.pull_request.labels.*.name, 'patch') ||
14
+ contains(github.event.pull_request.labels.*.name, 'minor') ||
15
+ contains(github.event.pull_request.labels.*.name, 'major') ) }}
16
+ steps:
17
+ - name: Checkout the repository
18
+ uses: actions/checkout@93ea575cb5d8a053eaa0ac8fa3b40d7e05a33cc8
19
+
20
+ - name: Setup git user
21
+ run: |
22
+ git config user.name "Joseph Mathew"
23
+ git config user.email "joseph.mathew@bigbinary.com"
24
+ - name: Setup NodeJS LTS version
25
+ uses: actions/setup-node@8c91899e586c5b171469028077307d293428b516
26
+ with:
27
+ node-version-file: ".nvmrc"
28
+
29
+ - name: Setup the project
30
+ run: yarn install
31
+
32
+ - name: Prefix version tag with "v"
33
+ run: yarn config set version-tag-prefix "v"
34
+
35
+ - name: Disable Git commit hooks
36
+ run: git config core.hooksPath /dev/null
37
+
38
+ - name: Bump the patch version and create git tag on release
39
+ if: ${{ contains(github.event.pull_request.labels.*.name, 'patch') }}
40
+ run: yarn version --patch
41
+
42
+ - name: Bump the minor version and create git tag on release
43
+ if: ${{ contains(github.event.pull_request.labels.*.name, 'minor') }}
44
+ run: yarn version --minor
45
+
46
+ - name: Bump the major version and create git tag on release
47
+ if: ${{ contains(github.event.pull_request.labels.*.name, 'major') }}
48
+ run: yarn version --major
49
+
50
+ - name: Get the package version from package.json
51
+ uses: tyankatsu0105/read-package-version-actions@5aad2bb630a577ee4255546eb3ee0593df68f6ca
52
+ id: package-version
53
+
54
+ - name: Create a new version release commit
55
+ uses: EndBug/add-and-commit@050a66787244b10a4874a2a5f682130263edc192
56
+ with:
57
+ message: "New version release"
58
+
59
+ - name: Push the commit to main
60
+ uses: ad-m/github-push-action@492de9080c3179a3187bd456763f988f9a06e196
61
+ with:
62
+ github_token: ${{ secrets.GITHUB_TOKEN }}
63
+ branch: main
64
+
65
+ - name: Create a release draft on release
66
+ uses: release-drafter/release-drafter@ac463ffd9cc4c6ad5682af93dc3e3591c4657ee3
67
+ env:
68
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
69
+ with:
70
+ tag: v${{ steps.package-version.outputs.version }}
71
+ publish: true
72
+
73
+ - name: Publish the package on NPM
74
+ uses: JS-DevTools/npm-publish@22595ff8c4d0d9f53cef0656fbb90fbe06ee885c
75
+ with:
76
+ access: "public"
77
+ token: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1,26 @@
1
+ name: Publish to npm
2
+
3
+ on:
4
+ release:
5
+ types: [created]
6
+
7
+ jobs:
8
+ publish:
9
+ runs-on: ubuntu-latest
10
+ steps:
11
+ - name: Checkout the repository
12
+ uses: actions/checkout@v3
13
+
14
+ - name: Setup NodeJS LTS version
15
+ uses: actions/setup-node@v3
16
+ with:
17
+ node-version: "18.12.0"
18
+
19
+ - name: Setup the project
20
+ run: yarn install
21
+
22
+ - name: Publish the package on NPM
23
+ uses: JS-DevTools/npm-publish@v1
24
+ with:
25
+ access: "public"
26
+ token: ${{ secrets.NPM_TOKEN }}
@@ -0,0 +1,5 @@
1
+ #!/bin/sh
2
+
3
+ lint_staged_files() {
4
+ npx lint-staged
5
+ }
@@ -0,0 +1,5 @@
1
+ #!/bin/sh
2
+ . "$(dirname "$0")/_/husky.sh"
3
+ . "$(dirname "$0")/helpers/lint_staged.sh"
4
+
5
+ lint_staged_files
package/.node-version ADDED
@@ -0,0 +1 @@
1
+ 18.12
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ 18.12
@@ -0,0 +1 @@
1
+ **/output.js
package/.prettierrc.js ADDED
@@ -0,0 +1 @@
1
+ module.exports = require("@bigbinary/neeto-commons-frontend/configs/prettier.js");
@@ -0,0 +1,5 @@
1
+ checkout
2
+ git fetch --unshallow 2> /dev/null
3
+ git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
4
+ git fetch origin main
5
+ git diff-tree --diff-filter=a -r --no-commit-id --name-only HEAD remotes/origin/main | grep --color=none -i -e "\.js$" | xargs npx eslint
@@ -0,0 +1,32 @@
1
+ version: v1.0
2
+ name: cicheck
3
+ agent:
4
+ machine:
5
+ type: e1-standard-2
6
+ os_image: ubuntu2004
7
+ auto_cancel:
8
+ running:
9
+ when: "branch != 'main'"
10
+ fail_fast:
11
+ stop:
12
+ when: "true"
13
+ global_job_config:
14
+ prologue:
15
+ commands:
16
+ - checkout
17
+ - sem-version node 18.12
18
+ - yarn install
19
+ env_vars:
20
+ - name: ENV
21
+ value: test
22
+ blocks:
23
+ - name: Code lints and tests
24
+ task:
25
+ jobs:
26
+ - name: ESLint
27
+ commands:
28
+ - ".scripts/run_eslint_on_modified_files.sh"
29
+ - name: Tests
30
+ commands:
31
+ - "yarn test"
32
+ dependencies: []
package/README.md ADDED
@@ -0,0 +1,71 @@
1
+ # babel-preset-neeto
2
+
3
+ A babel transformer to minimize boilerplate code in neeto products.
4
+
5
+ ## Available plugins
6
+
7
+ - [zustand-pick](./docs/zustand-pick.md)
8
+
9
+ ## Development instructions
10
+
11
+ - We don't use bundling as of now in this repo. All newly added plugins should
12
+ be exported from `index.js` in the repo's root folder to access it from host
13
+ projects. Also, use CJS `require` style for importing functions & other
14
+ elements.
15
+ - Make sure to add names for all newly added plugins. See
16
+ [this example](https://github.com/bigbinary/babel-preset-neeto/blob/f3f545493081473194c9187ea2493339a1ab3480/src/plugins/zustand-pick/index.js)
17
+ - The plugins should be designed in a fail-fast way. It should throw syntax
18
+ errors rather than fail at runtime for invalid usages. That is, if some
19
+ proposed syntax is used in an invalid way, it should not be ignored. Refer
20
+ [to this example](https://github.com/bigbinary/babel-preset-neeto/blob/f3f545493081473194c9187ea2493339a1ab3480/src/plugins/zustand-pick/index.js)
21
+ - All the plugins should reside directly under `src/plugins` folder. It can
22
+ either be a file or a folder with `index.js`. The name of file/folder should
23
+ be kebab-cased to improve readability.
24
+ - All syntax error messages should reside inside `src/plugins/messages.js` file.
25
+ It should show a shortened link to the documentation of the failing plugin.
26
+ - For each plugin, there should be a documentation file inside `docs` folder.
27
+ The documentation should be an `.md` file with the same name as the plugin
28
+ (kebab-cased). The doc should mention these things:
29
+
30
+ - The motivation behind introducing the new syntax
31
+ - Allowed syntaxes
32
+ - Possible incorrect usages (Disallowed syntaxes)
33
+
34
+ While writing the doc, it should be kept as simple as possible. The readers
35
+ are general React developers and not Babel plugin developers. No need to
36
+ expose project-specific technical aspects to them in the plugin doc.
37
+
38
+ - Every transformation plugin should have detailed tests associated with it. It
39
+ should cover all possible positive and negative test cases. We can specify an
40
+ input file and an output file. When the input is transformed, it should
41
+ generate the output code. Here is how tests can be written:
42
+ - We use the library `babel-plugin-tester` for simplifying tests
43
+ - Tests are classified into three categories.
44
+ - transformations: we specify `input.js` and `output.js` for all allowed
45
+ syntaxes.
46
+ - no-changes: we specify cases where we won't make any changes even though
47
+ the code is similar to the allowed syntax.
48
+ - syntax-errors: all possible cases where we raise errors. This should cover
49
+ all invalid usages of our proposed syntax.
50
+ - A test will have its own folder under `src/tests` folder (with plugin name
51
+ kebab-cased). It will contain 3 folders for fixtures (input/output file for
52
+ each category of the test) and a spec file (also named the same as the
53
+ plugin in kebab-case).
54
+ - `no-changes` and `syntax-error` will have several possible cases inside
55
+ them. Each case will be a separate JS file (with a brief kebab-cased
56
+ description for the test case as the file name).
57
+ - `transformations` folder will contain sub-folders for each test case. The
58
+ folder name will be a brief description of the test case. Each subfolder
59
+ will contain two files `input.js` and `output.js`. When Babel transforms
60
+ the `input.js` file, the result should be identical to `output.js`
61
+ (including white spaces).
62
+ - Refer `src/tests/zustand-pick` folder for an example.
63
+ - We can copy and paste the boilerplate from
64
+ `src/tests/zustand-pick/zustand-pick.spec.js` for other tests as well for
65
+ now. We can add a utility function later. You can run the tests using
66
+ `yarn test` command.
67
+
68
+ ## References
69
+
70
+ - Learning material:
71
+ https://github.com/jamiebuilds/babel-handbook/blob/master/translations/en/plugin-handbook.md
@@ -0,0 +1 @@
1
+ module.exports = require("@bigbinary/neeto-commons-frontend/configs/babel.js");
@@ -0,0 +1,159 @@
1
+ # Zustand pick transformer
2
+
3
+ ## Motivation
4
+
5
+ When we wanted to pick some properties from a zustand store, this is what we
6
+ need to do:
7
+
8
+ ```js
9
+ import { shallow } from "zustand/shallow";
10
+
11
+ const { order, customer } = useGlobalStore(
12
+ store => ({
13
+ order: store[sessionId]?.globals.order,
14
+ customer: store[sessionId]?.globals.customer,
15
+ }),
16
+ shallow
17
+ );
18
+ ```
19
+
20
+ This involves a lot of boilerplate code just to access two properties from a
21
+ store containing nested values.
22
+
23
+ This transformer is capable of generating all these boilerplate at the time of
24
+ transpiling (during bundling) so that we can focus on our business logic. If
25
+ this plugin is added to your babel configuration, you can write the following
26
+ code to get a similar effect as the above code:
27
+
28
+ ```js
29
+ const { order, customer } = useGlobalStore.pick([sessionId, "globals"]);
30
+ ```
31
+
32
+ You might also notice that we don't have the
33
+ `import { shallow } from "zustand/shallow"` statement in this piece of code. We
34
+ don't need that. The plugin will automatically add it for us at the time of
35
+ transpiling.
36
+
37
+ The plugin detects that `order` and `customer` properties are to be fetched from
38
+ the `store[sessionId].globals` property from `useGlobalStore` and it generates
39
+ code for it. Note that the plugin will automatically add
40
+ `import { shallow } from "zustand/shallow"` for us. We don't need to add it
41
+ ourselves.
42
+
43
+ ## Allowed syntaxes
44
+
45
+ To explain the allowed syntaxes take this zustand store as the example:
46
+
47
+ ```js
48
+ const useGlobalStore = create((set, get) => ({
49
+ order: {
50
+ id: "#1230",
51
+ user: {
52
+ email: "oliver@example.com",
53
+ address: {
54
+ "location 1": { street: "293, 1st Floor", city: "Mumbai" }
55
+ "location 2": { street: "295, 3st Floor", city: "Chennai" }
56
+ },
57
+ },
58
+ items: {
59
+ // itemID: { ...properties }
60
+ "47e91f1a-0c4d-4a79-a939-1319d8659bd2": { quantity: 10, price: 100 },
61
+ "64b7e54c-5d8a-443a-b70b-fff3d6937eba": { quantity: 3, price: 34 },
62
+ },
63
+ },
64
+
65
+ setOrder: order => set({ order }),
66
+ }));
67
+ ```
68
+
69
+ These are the allowed syntaxes:
70
+
71
+ ```js
72
+ // picks `order` data and `setOrder` action from the store
73
+ const { order, setOrder } = useGlobalStore.pick();
74
+
75
+ // picks `id` and `user` from inside store.order
76
+ const { id, user } = useGlobalStore.pick("order");
77
+
78
+ // picks `quantity` of dynamically obtained item of id `itemId`
79
+ const { quantity } = useGlobalStore.pick(["order", "items", itemId]);
80
+
81
+ // picks all stored properties of dynamically obtained item of id `itemId`
82
+ const { [itemId]: itemDetails } = useGlobalStore.pick(["order", "items"]);
83
+
84
+ // picks all stored properties of the location at `index` from store.order.user.address
85
+ const { [`location ${index}`]: address } = useGlobalStore.pick([
86
+ "order",
87
+ "user",
88
+ "address",
89
+ ]);
90
+ ```
91
+
92
+ ## Disallowed syntaxes
93
+
94
+ We have introduced a type definition for `pick` method from zustand stores from
95
+ neeto-commons-frontend to make IDE capable of pointing out errors as you type.
96
+ But it is not 100% foolproof. So here is a list of usages that are flagged as
97
+ syntax errors during transpilation.
98
+
99
+ 1. Nesting is not allowed in the variable declaration.
100
+
101
+ **incorrect**
102
+
103
+ ```js
104
+ const {
105
+ order: { user },
106
+ } = useGlobalStore.pick();
107
+ ```
108
+
109
+ **correct**
110
+
111
+ ```js
112
+ const { order } = useGlobalStore.pick();
113
+ const { user } = useGlobalStore.pick("order"); // to get nested item
114
+ ```
115
+
116
+ 2. Expressions are not allowed in picking path array
117
+
118
+ **incorrect**
119
+
120
+ ```js
121
+ // expressions are not allowed
122
+ const { user } = useGlobalStore.pick(["order", index + 1]);
123
+ // string templates are not allowed
124
+ const { user } = useGlobalStore.pick(["order", `#${orderId}`]);
125
+ ```
126
+
127
+ **correct**
128
+
129
+ ```js
130
+ // only use literals of String, Numbers or Booleans
131
+ // and variables as elements of the path array
132
+ const indexPlusOne = index + 1;
133
+ const { user } = useGlobalStore.pick(["order", indexPlusOne, 0, true]);
134
+ ```
135
+
136
+ 3. Pick only accepts a single parameter:
137
+
138
+ **incorrect**
139
+
140
+ ```js
141
+ const { user } = useGlobalStore.pick("order", "user");
142
+ ```
143
+
144
+ **correct**
145
+
146
+ ```js
147
+ // use arrays to specify nested path
148
+ const { name } = useGlobalStore.pick(["order", "user"]);
149
+ // use key directly to get its nested properties.
150
+ const { user } = useGlobalStore.pick("order");
151
+ // pass no arguments to get the top level properties
152
+ const { order, setOrder } = useGlobalStore.pick();
153
+ ```
154
+
155
+ 4. You might also encounter errors if some other plugin transforms the code
156
+ before babel-plugin-neeto. If your syntax is correct, and you are still
157
+ getting errors, check for other babel-plugins or babel-presets transforming
158
+ your code before we do. **babel-plugin-neeto expects that it runs first on
159
+ the code before any other plugin performs transformations.**
package/index.js ADDED
@@ -0,0 +1,5 @@
1
+ const zustandPick = require("./src/plugins/zustand-pick");
2
+
3
+ module.exports = () => ({
4
+ plugins: [zustandPick],
5
+ });
package/jsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "allowSyntheticDefaultImports": true,
5
+ "strictNullChecks": true,
6
+ "lib": ["DOM", "DOM.Iterable", "ESNext"],
7
+ "module": "ESNext",
8
+ "moduleResolution": "NodeNext",
9
+ "baseUrl": ".",
10
+ "pretty": true,
11
+ "experimentalDecorators": true,
12
+ "esModuleInterop": true,
13
+ "checkJs": true,
14
+ "resolveJsonModule": true,
15
+ "jsx": "preserve"
16
+ },
17
+ "exclude": ["**/node_modules", "**/.*/"],
18
+ "include": ["./**/*.js"]
19
+ }
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@bigbinary/babel-preset-neeto",
3
+ "version": "1.0.2",
4
+ "description": "A babel preset to transform short code to boilerplate at compile time",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "prepare": "husky install"
9
+ },
10
+ "lint-staged": {
11
+ "src/**/*.js": [
12
+ "prettier --write",
13
+ "eslint --fix"
14
+ ],
15
+ "index.js": [
16
+ "prettier --write",
17
+ "eslint --fix"
18
+ ],
19
+ "package.json": [
20
+ "prettier --write",
21
+ "eslint --fix"
22
+ ],
23
+ "*.md": [
24
+ "prettier --write"
25
+ ]
26
+ },
27
+ "keywords": [
28
+ "babel",
29
+ "neeto"
30
+ ],
31
+ "author": "Amaljith K",
32
+ "license": "ISC",
33
+ "dependencies": {
34
+ "@bigbinary/neeto-commons-frontend": "^2.0.63",
35
+ "ramda": "^0.29.0"
36
+ },
37
+ "devDependencies": {
38
+ "@babel/cli": "^7.21.0",
39
+ "@babel/core": "^7.21.4",
40
+ "@babel/eslint-parser": "7.17.0",
41
+ "@babel/plugin-syntax-dynamic-import": "7.8.3",
42
+ "@babel/plugin-transform-runtime": "7.19.1",
43
+ "@babel/preset-env": "7.17.10",
44
+ "@babel/preset-react": "7.16.7",
45
+ "@bigbinary/eslint-plugin-neeto": "^1.0.30",
46
+ "babel-plugin-dynamic-import-node": "2.3.3",
47
+ "babel-plugin-macros": "3.1.0",
48
+ "babel-plugin-tester": "^11.0.4",
49
+ "babel-plugin-transform-react-remove-prop-types": "0.4.24",
50
+ "eslint": "8.14.0",
51
+ "eslint-config-prettier": "8.5.0",
52
+ "eslint-plugin-cypress": "2.12.1",
53
+ "eslint-plugin-import": "2.26.0",
54
+ "eslint-plugin-jam3": "0.2.3",
55
+ "eslint-plugin-json": "3.1.0",
56
+ "eslint-plugin-prettier": "4.0.0",
57
+ "eslint-plugin-promise": "6.0.0",
58
+ "eslint-plugin-react": "7.29.4",
59
+ "eslint-plugin-react-hooks": "4.5.0",
60
+ "eslint-plugin-unused-imports": "2.0.0",
61
+ "husky": "^8.0.0",
62
+ "jest": "^29.5.0",
63
+ "lint-staged": "^13.2.0",
64
+ "prettier": "^2.8.7"
65
+ }
66
+ }
@@ -0,0 +1,8 @@
1
+ /* eslint-disable @bigbinary/neeto/no-dangling-constants */
2
+
3
+ const INCORRECT_ZUSTAND_PICK_USAGE =
4
+ "Invalid use of zustand store pick method. You can find a list of allowed usages here: https://bit.ly/zustand-pick-syntax";
5
+
6
+ module.exports = {
7
+ INCORRECT_ZUSTAND_PICK_USAGE,
8
+ };
@@ -0,0 +1,41 @@
1
+ const { matches } = require("@bigbinary/neeto-commons-frontend/pure");
2
+ const { any } = require("ramda");
3
+
4
+ const getImportAST = (source, importName) => ({
5
+ type: "ImportDeclaration",
6
+ specifiers: any(
7
+ matches({
8
+ type: "ImportSpecifier",
9
+ imported: { type: "Identifier", name: importName },
10
+ })
11
+ ),
12
+ source: { type: "StringLiteral", value: source },
13
+ });
14
+
15
+ const addNamedImport = ({ path, types, source, importName }) => {
16
+ const parent = path.findParent(path => path.node.type === "Program");
17
+ if (parent.node.body.some(matches(getImportAST(source, importName)))) return;
18
+
19
+ parent
20
+ .get("body.0")
21
+ .insertBefore(
22
+ types.importDeclaration(
23
+ [
24
+ types.importSpecifier(
25
+ types.identifier(importName),
26
+ types.identifier(importName)
27
+ ),
28
+ ],
29
+ types.stringLiteral(source)
30
+ )
31
+ );
32
+ };
33
+
34
+ const matchesWithLength = patternArray => originalArray =>
35
+ originalArray.length === patternArray.length &&
36
+ matches(patternArray, originalArray);
37
+
38
+ const matchesAny = (patterns, object) =>
39
+ patterns.some(pattern => matches(pattern, object));
40
+
41
+ module.exports = { addNamedImport, matchesWithLength, matchesAny };
@@ -0,0 +1,75 @@
1
+ const { matches } = require("@bigbinary/neeto-commons-frontend/pure");
2
+ const { test, isEmpty, mergeDeepLeft, all, includes, __ } = require("ramda");
3
+
4
+ const { matchesWithLength } = require("../utils");
5
+
6
+ const VALID_ARRAY_ELEMENT_TYPES = [
7
+ "StringLiteral",
8
+ "Identifier",
9
+ "NumericLiteral",
10
+ "BooleanLiteral",
11
+ ];
12
+
13
+ const VALID_PICK_ARGUMENT_TYPES = [
14
+ "StringLiteral",
15
+ "Identifier",
16
+ "ArrayExpression",
17
+ ];
18
+
19
+ const VALID_PICK_ARGUMENT = {
20
+ type: includes(__, VALID_PICK_ARGUMENT_TYPES),
21
+ elements: (elements, root) =>
22
+ root.type !== "ArrayExpression" ||
23
+ elements.every(({ type }) => VALID_ARRAY_ELEMENT_TYPES.includes(type)),
24
+ };
25
+
26
+ const PICK_GENERIC_PATTERN = {
27
+ type: "VariableDeclarator",
28
+ init: {
29
+ type: "CallExpression",
30
+ callee: {
31
+ type: "MemberExpression",
32
+ computed: false,
33
+ object: {
34
+ type: "Identifier",
35
+ name: test(/^use[a-zA-Z0-9]+Store$/),
36
+ },
37
+ property: {
38
+ type: "Identifier",
39
+ name: "pick",
40
+ },
41
+ },
42
+ },
43
+ };
44
+
45
+ const PICK_STRICT_PATTERN = {
46
+ type: "VariableDeclaration",
47
+ kind: "const",
48
+ declarations: matchesWithLength([
49
+ mergeDeepLeft(
50
+ {
51
+ id: {
52
+ type: "ObjectPattern",
53
+ properties: all(
54
+ matches({
55
+ type: "ObjectProperty",
56
+ method: false,
57
+ value: { type: "Identifier" },
58
+ })
59
+ ),
60
+ },
61
+ init: {
62
+ arguments: args =>
63
+ isEmpty(args) ||
64
+ (args.length === 1 && matches(VALID_PICK_ARGUMENT, args[0])),
65
+ },
66
+ },
67
+ PICK_GENERIC_PATTERN
68
+ ),
69
+ ]),
70
+ };
71
+
72
+ module.exports = {
73
+ PICK_GENERIC_PATTERN,
74
+ PICK_STRICT_PATTERN,
75
+ };
@@ -0,0 +1,94 @@
1
+ const { matches } = require("@bigbinary/neeto-commons-frontend/pure");
2
+ const { last } = require("ramda");
3
+
4
+ const { PICK_GENERIC_PATTERN, PICK_STRICT_PATTERN } = require("./constants");
5
+
6
+ const { INCORRECT_ZUSTAND_PICK_USAGE } = require("../messages");
7
+ const { addNamedImport } = require("../utils");
8
+
9
+ const getPropertyAccessNode = (types, propertyPath) => {
10
+ if (propertyPath.length === 1) {
11
+ return types.memberExpression(
12
+ types.identifier("store"),
13
+ propertyPath[0],
14
+ true
15
+ );
16
+ }
17
+
18
+ return types.optionalMemberExpression(
19
+ getPropertyAccessNode(
20
+ types,
21
+ propertyPath.slice(0, propertyPath.length - 1)
22
+ ),
23
+ last(propertyPath),
24
+ true,
25
+ true
26
+ );
27
+ };
28
+
29
+ module.exports = function ({ types }) {
30
+ return {
31
+ name: "Zustand pick transformer",
32
+ visitor: {
33
+ VariableDeclaration(astPath) {
34
+ const declaratorPath = astPath.get("declarations.0");
35
+ const declarator = declaratorPath.node;
36
+ if (!matches(PICK_GENERIC_PATTERN, declarator)) return;
37
+
38
+ if (!matches(PICK_STRICT_PATTERN, astPath.node)) {
39
+ throw astPath.buildCodeFrameError(INCORRECT_ZUSTAND_PICK_USAGE);
40
+ }
41
+
42
+ const [argument] = declarator.init.arguments;
43
+ let propertyPath;
44
+ if (argument === undefined) {
45
+ propertyPath = [];
46
+ } else if (["Identifier", "StringLiteral"].includes(argument.type)) {
47
+ propertyPath = [argument];
48
+ } else if (argument.type === "ArrayExpression") {
49
+ propertyPath = argument.elements;
50
+ } else return;
51
+
52
+ const toObjectProperty = ({ key, computed }) =>
53
+ types.objectProperty(
54
+ key,
55
+ getPropertyAccessNode(types, [
56
+ ...propertyPath,
57
+ computed ? key : types.stringLiteral(key.name),
58
+ ]),
59
+ computed
60
+ );
61
+
62
+ declarator.init = types.callExpression(
63
+ types.identifier(declarator.init.callee.object.name),
64
+ [
65
+ types.arrowFunctionExpression(
66
+ [types.identifier("store")],
67
+ types.objectExpression(
68
+ declarator.id.properties.map(toObjectProperty)
69
+ )
70
+ ),
71
+ types.identifier("shallow"),
72
+ ]
73
+ );
74
+
75
+ addNamedImport({
76
+ path: astPath,
77
+ types,
78
+ source: "zustand/shallow",
79
+ importName: "shallow",
80
+ });
81
+ },
82
+ CallExpression(astPath) {
83
+ // The variable declarator would have already transformed
84
+ // `useStore.pick()` by the time babel runs this.
85
+ // So no more `useStore.pick()` expressions should be seen anywhere.
86
+ // If we still can see such usage, it means that people are using
87
+ // `useStore.pick()` somewhere other than variable declaration.
88
+ if (matches(PICK_GENERIC_PATTERN.init, astPath.node)) {
89
+ throw astPath.buildCodeFrameError(INCORRECT_ZUSTAND_PICK_USAGE);
90
+ }
91
+ },
92
+ },
93
+ };
94
+ };
@@ -0,0 +1,38 @@
1
+ const fs = require("fs");
2
+ const path = require("path");
3
+
4
+ const { fromPairs } = require("ramda");
5
+
6
+ const getPositiveCases = dirName =>
7
+ fromPairs(
8
+ fs
9
+ .readdirSync(path.join(dirName, "no-changes"))
10
+ .map(key => [`No change: ${key}`, { fixture: `no-changes/${key}` }])
11
+ );
12
+
13
+ const getNegativeCases = dirName =>
14
+ fromPairs(
15
+ fs.readdirSync(path.join(dirName, "transformations")).map(key => [
16
+ `Transform: ${key}`,
17
+ {
18
+ fixture: `transformations/${key}/input.js`,
19
+ outputFixture: `transformations/${key}/output.js`,
20
+ },
21
+ ])
22
+ );
23
+
24
+ const getIncorrectSyntaxCases = (dirName, error) =>
25
+ fromPairs(
26
+ fs
27
+ .readdirSync(path.join(dirName, "syntax-errors"))
28
+ .map(key => [
29
+ `Raise syntax error: ${key}`,
30
+ { fixture: `syntax-errors/${key}`, throws: error },
31
+ ])
32
+ );
33
+
34
+ module.exports = {
35
+ getNegativeCases,
36
+ getPositiveCases,
37
+ getIncorrectSyntaxCases,
38
+ };
@@ -0,0 +1 @@
1
+ const { name, email } = useSampleStore.pock();
@@ -0,0 +1 @@
1
+ const { name, email } = useSampleStor.pick();
@@ -0,0 +1 @@
1
+ const { name, email } = useSampleStore(pick(["name", "email"]));
@@ -0,0 +1 @@
1
+ const { name } = useGlobalStore.pick("order").user;
@@ -0,0 +1 @@
1
+ const name = useGlobalStore.pick("order")?.user.name;
@@ -0,0 +1 @@
1
+ const { user } = useGlobalStore.pick("order", "user");
@@ -0,0 +1,3 @@
1
+ const {
2
+ order: { user },
3
+ } = useGlobalStore.pick();
@@ -0,0 +1 @@
1
+ const { user } = useGlobalStore.pick(["order", index + 1]);
@@ -0,0 +1 @@
1
+ const { user } = useGlobalStore.pick(["order", `#${orderId}`]);
@@ -0,0 +1,6 @@
1
+ const { order, customer } = useGlobalStore.pick([
2
+ "state",
3
+ sessionId,
4
+ "current",
5
+ data,
6
+ ]);
@@ -0,0 +1,8 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { order, customer } = useGlobalStore(
3
+ store => ({
4
+ order: store["state"]?.[sessionId]?.["current"]?.[data]?.["order"],
5
+ customer: store["state"]?.[sessionId]?.["current"]?.[data]?.["customer"],
6
+ }),
7
+ shallow
8
+ );
@@ -0,0 +1,2 @@
1
+ const { [`customer ${id}`]: customer } = useGlobalStore.pick(sessionId);
2
+ const { [orderId]: order } = useGlobalStore.pick([sessionId, "orders"]);
@@ -0,0 +1,13 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { [`customer ${id}`]: customer } = useGlobalStore(
3
+ store => ({
4
+ [`customer ${id}`]: store[sessionId]?.[`customer ${id}`],
5
+ }),
6
+ shallow
7
+ );
8
+ const { [orderId]: order } = useGlobalStore(
9
+ store => ({
10
+ [orderId]: store[sessionId]?.["orders"]?.[orderId],
11
+ }),
12
+ shallow
13
+ );
@@ -0,0 +1 @@
1
+ const { customer } = useGlobalStore.pick(sessionId);
@@ -0,0 +1,7 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { customer } = useGlobalStore(
3
+ store => ({
4
+ customer: store[sessionId]?.["customer"],
5
+ }),
6
+ shallow
7
+ );
@@ -0,0 +1 @@
1
+ const { order, customer } = useGlobalStore.pick();
@@ -0,0 +1,8 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { order, customer } = useGlobalStore(
3
+ store => ({
4
+ order: store["order"],
5
+ customer: store["customer"],
6
+ }),
7
+ shallow
8
+ );
@@ -0,0 +1,2 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { order, customer } = useGlobalStore.pick();
@@ -0,0 +1,8 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { order, customer } = useGlobalStore(
3
+ store => ({
4
+ order: store["order"],
5
+ customer: store["customer"],
6
+ }),
7
+ shallow
8
+ );
@@ -0,0 +1 @@
1
+ const { order, customer, address } = useGlobalStore.pick("state");
@@ -0,0 +1,9 @@
1
+ import { shallow } from "zustand/shallow";
2
+ const { order, customer, address } = useGlobalStore(
3
+ store => ({
4
+ order: store["state"]?.["order"],
5
+ customer: store["state"]?.["customer"],
6
+ address: store["state"]?.["address"],
7
+ }),
8
+ shallow
9
+ );
@@ -0,0 +1,4 @@
1
+ import React from "react";
2
+ import { sample } from "somewhere";
3
+
4
+ const { order, customer } = useGlobalStore.pick();
@@ -0,0 +1,10 @@
1
+ import { shallow } from "zustand/shallow";
2
+ import React from "react";
3
+ import { sample } from "somewhere";
4
+ const { order, customer } = useGlobalStore(
5
+ store => ({
6
+ order: store["order"],
7
+ customer: store["customer"],
8
+ }),
9
+ shallow
10
+ );
@@ -0,0 +1,18 @@
1
+ const { pluginTester } = require("babel-plugin-tester");
2
+
3
+ const { INCORRECT_ZUSTAND_PICK_USAGE } = require("../../plugins/messages");
4
+ const zustandPick = require("../../plugins/zustand-pick");
5
+ const {
6
+ getPositiveCases,
7
+ getNegativeCases,
8
+ getIncorrectSyntaxCases,
9
+ } = require("../utils");
10
+
11
+ pluginTester({
12
+ plugin: zustandPick,
13
+ tests: {
14
+ ...getPositiveCases(__dirname),
15
+ ...getIncorrectSyntaxCases(__dirname, INCORRECT_ZUSTAND_PICK_USAGE),
16
+ ...getNegativeCases(__dirname),
17
+ },
18
+ });