diff --git a/.changeset/config.json b/.changeset/config.json index c27ba767..5eeee38e 100644 --- a/.changeset/config.json +++ b/.changeset/config.json @@ -1,10 +1,10 @@ { - "$schema": "https://unpkg.com/@changesets/config@1.6.4/schema.json", - "changelog": "@changesets/cli/changelog", - "commit": false, - "linked": [], - "access": "public", - "baseBranch": "main", - "updateInternalDependencies": "patch", - "ignore": [] + "$schema": "https://unpkg.com/@changesets/config@1.6.4/schema.json", + "changelog": "@changesets/cli/changelog", + "commit": false, + "linked": [], + "access": "public", + "baseBranch": "main", + "updateInternalDependencies": "patch", + "ignore": [] } diff --git a/.eslintrc.cjs b/.eslintrc.cjs index 509ddd60..a39ebb8f 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -1,23 +1,23 @@ module.exports = { - root: true, - extends: '@theguild', - rules: { - 'unicorn/no-array-push-push': 'off', - 'unicorn/filename-case': 'off', - '@typescript-eslint/no-explicit-any': 'off', - 'no-console': ['error', { allow: ['info', 'warn', 'error', 'time', 'timeEnd'] }], - 'no-restricted-syntax': 'off', - 'import/no-default-export': 'off', - '@typescript-eslint/ban-types': 'off' - }, - ignorePatterns: ['examples', 'website'], - plugins: ['svelte3'], - overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], - settings: { - 'svelte3/typescript': () => require('typescript') - }, - parserOptions: { - sourceType: 'module', - ecmaVersion: 2020 - } + root: true, + extends: '@theguild', + rules: { + 'unicorn/no-array-push-push': 'off', + 'unicorn/filename-case': 'off', + '@typescript-eslint/no-explicit-any': 'off', + 'no-console': ['error', { allow: ['info', 'warn', 'error', 'time', 'timeEnd'] }], + 'no-restricted-syntax': 'off', + 'import/no-default-export': 'off', + '@typescript-eslint/ban-types': 'off', + }, + ignorePatterns: ['examples', 'website'], + plugins: ['svelte3'], + overrides: [{ files: ['*.svelte'], processor: 'svelte3/svelte3' }], + settings: { + 'svelte3/typescript': () => require('typescript'), + }, + parserOptions: { + sourceType: 'module', + ecmaVersion: 2020, + }, }; diff --git a/.gitattributes b/.gitattributes index 21256661..176a458f 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -* text=auto \ No newline at end of file +* text=auto diff --git a/.vscode/extensions.json b/.vscode/extensions.json index dd6bb09b..8b8f8a72 100644 --- a/.vscode/extensions.json +++ b/.vscode/extensions.json @@ -1,7 +1,3 @@ { - "recommendations": [ - "rioukkevin.vscode-git-commit", - "esbenp.prettier-vscode", - "johnpapa.vscode-peacock" - ] + "recommendations": ["rioukkevin.vscode-git-commit", "esbenp.prettier-vscode", "johnpapa.vscode-peacock"] } diff --git a/.vscode/settings.json b/.vscode/settings.json index 6b06fb45..5bed7282 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,183 +1,183 @@ { - "workbench.colorCustomizations": { - "activityBar.activeBackground": "#2f7c47", - "activityBar.activeBorder": "#422c74", - "activityBar.background": "#2f7c47", - "activityBar.foreground": "#e7e7e7", - "activityBar.inactiveForeground": "#e7e7e799", - "activityBarBadge.background": "#422c74", - "activityBarBadge.foreground": "#e7e7e7", - "sash.hoverBorder": "#2f7c47", - "statusBar.background": "#215732", - "statusBar.foreground": "#e7e7e7", - "statusBarItem.hoverBackground": "#2f7c47", - "statusBarItem.remoteBackground": "#215732", - "statusBarItem.remoteForeground": "#e7e7e7", - "titleBar.activeBackground": "#215732", - "titleBar.activeForeground": "#e7e7e7", - "titleBar.inactiveBackground": "#21573299", - "titleBar.inactiveForeground": "#e7e7e799" - }, - "peacock.remoteColor": "#215732", - "vscodeGitCommit.template": ["{icon} {type}: {message}"], - "vscodeGitCommit.variables": { - "icon": "aliasesIcons", - "aliasesIcons": [ - { - "label": ":tada:", - "detail": "๐ŸŽ‰ = Initial (NEW) commit." - }, - { - "label": ":construction:", - "detail": "๐Ÿšง = Work in progress." - }, - { - "label": ":ambulance:", - "detail": "๐Ÿš‘ = Critical hotfix." - }, - { - "label": ":sparkles:", - "detail": "โœจ = Introducing new features." - }, - { - "label": ":beers:", - "detail": "๐Ÿป = Writing code drunkenly." - }, - { - "label": ":hankey:", - "detail": "๐Ÿ’ฉ = Writing bad code that needs to be improved." - }, - { - "label": ":rotating_light:", - "detail": "๐Ÿšจ :rotating_light: = Removing linter warnings." - }, - { - "label": ":rewind:", - "detail": "โช = Reverting changes." - }, - { - "label": ":lock:", - "detail": "๐Ÿ”’ = Fixing security issues." - }, - { - "label": ":zap:", - "detail": "โšก๏ธ = Improving performance." - }, - { - "label": ":children_crossing:", - "detail": "๐Ÿšธ = Improving user experience / usability." - }, - { - "label": ":bug:", - "detail": "๐Ÿ› = Fixing a bug." - }, - { - "label": ":bulb:", - "detail": "๐Ÿ’ก = Documenting source code" - }, - { - "label": ":white_check_mark:", - "detail": "โœ… = Updating tests." - }, - { - "label": ":ok_hand:", - "detail": "๐Ÿ‘Œ = Updating code due to code review changes." - }, - { - "label": ":clown_face:", - "detail": "๐Ÿคก = Mocking things." - }, - { - "label": ":boom:", - "detail": "๐Ÿ’ฅ = Introducing breaking changes." - }, - { - "label": ":arrow_up:", - "detail": "โฌ†๏ธ = Upgrading dependencies." - }, - { - "label": ":fire:", - "detail": "๐Ÿ”ฅ = Removing code or files." - }, - { - "label": ":pencil2:", - "detail": "โœ๏ธ = Fixing typos." - }, - { - "label": ":loud_sound:", - "detail": "๐Ÿ”Š = Adding logs." - }, - { - "label": ":mute:", - "detail": "๐Ÿ”‡ = Removing logs." - }, - { - "label": ":art:", - "detail": "๐ŸŽจ = Improving structure / format of the code." - }, - { - "label": ":recycle:", - "detail": "โ™ป๏ธ = Refactoring code logic." - }, - { - "label": ":construction_worker:", - "detail": "๐Ÿ‘ท = Adding CI build system." - }, - { - "label": ":rocket:", - "detail": "๐Ÿš€ = Deploying stuff." - }, - { - "label": ":label:", - "detail": "๐Ÿท๏ธ = Adding or updating types (Flow, TypeScript)" - }, - { - "label": ":card_file_box:", - "detail": "๐Ÿ—ƒ = Performing database related changes." - }, - { - "label": ":lipstick:", - "detail": "๐Ÿ’„ = Updating the UI and style files." - }, - { - "label": ":twisted_rightwards_arrows:", - "detail": "๐Ÿ”€ = Merging branches." - }, - { - "label": ":package:", - "detail": "๐Ÿ“ฆ = Updating compiled files or packages." - }, - { - "label": ":see_no_evil:", - "detail": "๐Ÿ™ˆ = Adding or updating a .gitignore file" - } - ], - "type": "aliasesType", - "aliasesType": [ - { - "label": "NEW" - }, - { - "label": "REMOVE" - }, - { - "label": "RENAME" - }, - { - "label": "DOC" - }, - { - "label": "UPDATE" - }, - { - "label": "IMPROVE" - }, - { - "label": "FIX" - }, - { - "label": "RELEASE" - } - ] - } + "workbench.colorCustomizations": { + "activityBar.activeBackground": "#2f7c47", + "activityBar.activeBorder": "#422c74", + "activityBar.background": "#2f7c47", + "activityBar.foreground": "#e7e7e7", + "activityBar.inactiveForeground": "#e7e7e799", + "activityBarBadge.background": "#422c74", + "activityBarBadge.foreground": "#e7e7e7", + "sash.hoverBorder": "#2f7c47", + "statusBar.background": "#215732", + "statusBar.foreground": "#e7e7e7", + "statusBarItem.hoverBackground": "#2f7c47", + "statusBarItem.remoteBackground": "#215732", + "statusBarItem.remoteForeground": "#e7e7e7", + "titleBar.activeBackground": "#215732", + "titleBar.activeForeground": "#e7e7e7", + "titleBar.inactiveBackground": "#21573299", + "titleBar.inactiveForeground": "#e7e7e799" + }, + "peacock.remoteColor": "#215732", + "vscodeGitCommit.template": ["{icon} {type}: {message}"], + "vscodeGitCommit.variables": { + "icon": "aliasesIcons", + "aliasesIcons": [ + { + "label": ":tada:", + "detail": "๐ŸŽ‰ = Initial (NEW) commit." + }, + { + "label": ":construction:", + "detail": "๐Ÿšง = Work in progress." + }, + { + "label": ":ambulance:", + "detail": "๐Ÿš‘ = Critical hotfix." + }, + { + "label": ":sparkles:", + "detail": "โœจ = Introducing new features." + }, + { + "label": ":beers:", + "detail": "๐Ÿป = Writing code drunkenly." + }, + { + "label": ":hankey:", + "detail": "๐Ÿ’ฉ = Writing bad code that needs to be improved." + }, + { + "label": ":rotating_light:", + "detail": "๐Ÿšจ :rotating_light: = Removing linter warnings." + }, + { + "label": ":rewind:", + "detail": "โช = Reverting changes." + }, + { + "label": ":lock:", + "detail": "๐Ÿ”’ = Fixing security issues." + }, + { + "label": ":zap:", + "detail": "โšก๏ธ = Improving performance." + }, + { + "label": ":children_crossing:", + "detail": "๐Ÿšธ = Improving user experience / usability." + }, + { + "label": ":bug:", + "detail": "๐Ÿ› = Fixing a bug." + }, + { + "label": ":bulb:", + "detail": "๐Ÿ’ก = Documenting source code" + }, + { + "label": ":white_check_mark:", + "detail": "โœ… = Updating tests." + }, + { + "label": ":ok_hand:", + "detail": "๐Ÿ‘Œ = Updating code due to code review changes." + }, + { + "label": ":clown_face:", + "detail": "๐Ÿคก = Mocking things." + }, + { + "label": ":boom:", + "detail": "๐Ÿ’ฅ = Introducing breaking changes." + }, + { + "label": ":arrow_up:", + "detail": "โฌ†๏ธ = Upgrading dependencies." + }, + { + "label": ":fire:", + "detail": "๐Ÿ”ฅ = Removing code or files." + }, + { + "label": ":pencil2:", + "detail": "โœ๏ธ = Fixing typos." + }, + { + "label": ":loud_sound:", + "detail": "๐Ÿ”Š = Adding logs." + }, + { + "label": ":mute:", + "detail": "๐Ÿ”‡ = Removing logs." + }, + { + "label": ":art:", + "detail": "๐ŸŽจ = Improving structure / format of the code." + }, + { + "label": ":recycle:", + "detail": "โ™ป๏ธ = Refactoring code logic." + }, + { + "label": ":construction_worker:", + "detail": "๐Ÿ‘ท = Adding CI build system." + }, + { + "label": ":rocket:", + "detail": "๐Ÿš€ = Deploying stuff." + }, + { + "label": ":label:", + "detail": "๐Ÿท๏ธ = Adding or updating types (Flow, TypeScript)" + }, + { + "label": ":card_file_box:", + "detail": "๐Ÿ—ƒ = Performing database related changes." + }, + { + "label": ":lipstick:", + "detail": "๐Ÿ’„ = Updating the UI and style files." + }, + { + "label": ":twisted_rightwards_arrows:", + "detail": "๐Ÿ”€ = Merging branches." + }, + { + "label": ":package:", + "detail": "๐Ÿ“ฆ = Updating compiled files or packages." + }, + { + "label": ":see_no_evil:", + "detail": "๐Ÿ™ˆ = Adding or updating a .gitignore file" + } + ], + "type": "aliasesType", + "aliasesType": [ + { + "label": "NEW" + }, + { + "label": "REMOVE" + }, + { + "label": "RENAME" + }, + { + "label": "DOC" + }, + { + "label": "UPDATE" + }, + { + "label": "IMPROVE" + }, + { + "label": "FIX" + }, + { + "label": "RELEASE" + } + ] + } } diff --git a/README.md b/README.md index efa195c9..cfd9793c 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,9 @@ You have 3 main options to use `KitQL`: ## โœจ Contributors + [![All Contributors](https://img.shields.io/badge/all_contributors-14-orange.svg)](#contributors) + Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)): diff --git a/bob.config.js b/bob.config.js index 11e36bf1..571bf6df 100644 --- a/bob.config.js +++ b/bob.config.js @@ -1,34 +1,34 @@ module.exports = { - scope: '@kitql', // Scope of organization - ignore: ['@kitql/all-in'], // ignored packages - track: [ - // files in root that mark the entire workspace as dirty - 'bob.config.js', // we could include it in Bob itself but we decided to turn your life into hell :) - 'package.json', - 'tsconfig.json', - // files in packages that mark the package as dirty - '/src/**', - '/package.json', - '/tsconfig.json' - ], - base: 'origin/main', // we need to compare against something - commands: { - test: { - track: ['/tests/**'], - run(affected) { - // { - // paths: string[] <- ['packages/core', 'packages/cli'] - // names: string[] <- ['@foo/core', '@foo/cli'] - // } + scope: '@kitql', // Scope of organization + ignore: ['@kitql/all-in'], // ignored packages + track: [ + // files in root that mark the entire workspace as dirty + 'bob.config.js', // we could include it in Bob itself but we decided to turn your life into hell :) + 'package.json', + 'tsconfig.json', + // files in packages that mark the package as dirty + '/src/**', + '/package.json', + '/tsconfig.json', + ], + base: 'origin/main', // we need to compare against something + commands: { + test: { + track: ['/tests/**'], + run(affected) { + // { + // paths: string[] <- ['packages/core', 'packages/cli'] + // names: string[] <- ['@foo/core', '@foo/cli'] + // } - // why such a weird syntax? We use spawn, so you have too - return [`yarn`, ['test', ...affected.paths]]; - } - }, - build: { - run() { - return [`yarn`, ['build']]; - } - } - } + // why such a weird syntax? We use spawn, so you have too + return [`yarn`, ['test', ...affected.paths]]; + }, + }, + build: { + run() { + return [`yarn`, ['build']]; + }, + }, + }, }; diff --git a/examples/demo-github-social-preview/.gitignore b/examples/demo-github-social-preview/.gitignore index feb2804b..8f15e07b 100644 --- a/examples/demo-github-social-preview/.gitignore +++ b/examples/demo-github-social-preview/.gitignore @@ -6,4 +6,4 @@ node_modules .env .env.* !.env.example -_kitql \ No newline at end of file +_kitql diff --git a/examples/demo1/.gitignore b/examples/demo1/.gitignore index feb2804b..8f15e07b 100644 --- a/examples/demo1/.gitignore +++ b/examples/demo1/.gitignore @@ -6,4 +6,4 @@ node_modules .env .env.* !.env.example -_kitql \ No newline at end of file +_kitql diff --git a/examples/demo2/.gitignore b/examples/demo2/.gitignore index feb2804b..8f15e07b 100644 --- a/examples/demo2/.gitignore +++ b/examples/demo2/.gitignore @@ -6,4 +6,4 @@ node_modules .env .env.* !.env.example -_kitql \ No newline at end of file +_kitql diff --git a/examples/demo2/tools/preStart.sh b/examples/demo2/tools/preStart.sh index ca2da8f0..951708f3 100755 --- a/examples/demo2/tools/preStart.sh +++ b/examples/demo2/tools/preStart.sh @@ -1 +1 @@ -git log -1 --format="%cd" $RENDER_GIT_COMMIT > ./DEPLOY_DATETIME \ No newline at end of file +git log -1 --format="%cd" $RENDER_GIT_COMMIT > ./DEPLOY_DATETIME diff --git a/package.json b/package.json index aa93ec15..e734c887 100644 --- a/package.json +++ b/package.json @@ -1,58 +1,58 @@ { - "name": "kitql", - "version": "0.0.1", - "author": "jycouet ", - "private": true, - "license": "MIT", - "scripts": { - "prepare": "husky install && yarn workspace @kitql/client prepare", - "dev:t": "yarn build && yarn workspace @kitql/template dev", - "dev:c": "yarn workspace @kitql/client dev", - "dev:w": "cd website && yarn dev", - "test": "vitest --coverage", - "lint": "eslint --ignore-path .gitignore .", - "prettier": "prettier --write --list-different .", - "prettier:check": "prettier --check .", - "test:ci": "vitest run --coverage", - "test:update-badge": "yarn update-badge", - "prebuild": "rimraf packages/*/dist", - "build": "tsc --project tsconfig.json && bob build && rm -rf packages/client/dist/lib/graphql && yarn workspace @kitql/all-in package", - "release:msg": "yarn changeset", - "release:version": "yarn changeset version", - "release": "yarn build && changeset publish", - "reset": "git clean -xdf", - "update": "npm exec --workspaces -- npx ncu -u -p yarn" - }, - "workspaces": { - "packages": [ - "packages/*", - "kit-modules/*", - "website" - ] - }, - "devDependencies": { - "@babel/preset-env": "7.16.11", - "@babel/preset-typescript": "7.16.7", - "@changesets/cli": "2.20.0", - "@theguild/eslint-config": "0.0.1", - "@theguild/prettier-config": "0.0.1", - "@vitest/ui": "0.4.1", - "bob-the-bundler": "1.6.1", - "c8": "7.11.0", - "check-code-coverage": "1.10.0", - "graphql": "16.3.0", - "husky": "8.0.1", - "jsdom": "19.0.0", - "prettier": "^2.6.2", - "rimraf": "3.0.2", - "typescript": "4.5.5", - "vitest": "0.4.1" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - }, - "dependencies": { - "svelte2tsx": "0.5.6" - } + "name": "kitql", + "version": "0.0.1", + "author": "jycouet ", + "private": true, + "license": "MIT", + "scripts": { + "prepare": "husky install && yarn workspace @kitql/client prepare", + "dev:t": "yarn build && yarn workspace @kitql/template dev", + "dev:c": "yarn workspace @kitql/client dev", + "dev:w": "cd website && yarn dev", + "test": "vitest --coverage", + "lint": "eslint --ignore-path .gitignore .", + "prettier": "prettier --write --list-different .", + "prettier:check": "prettier --check .", + "test:ci": "vitest run --coverage", + "test:update-badge": "yarn update-badge", + "prebuild": "rimraf packages/*/dist", + "build": "tsc --project tsconfig.json && bob build && rm -rf packages/client/dist/lib/graphql && yarn workspace @kitql/all-in package", + "release:msg": "yarn changeset", + "release:version": "yarn changeset version", + "release": "yarn build && changeset publish", + "reset": "git clean -xdf", + "update": "npm exec --workspaces -- npx ncu -u -p yarn" + }, + "workspaces": { + "packages": [ + "packages/*", + "kit-modules/*", + "website" + ] + }, + "devDependencies": { + "@babel/preset-env": "7.16.11", + "@babel/preset-typescript": "7.16.7", + "@changesets/cli": "2.20.0", + "@theguild/eslint-config": "0.0.1", + "@theguild/prettier-config": "0.0.1", + "@vitest/ui": "0.4.1", + "bob-the-bundler": "1.6.1", + "c8": "7.11.0", + "check-code-coverage": "1.10.0", + "graphql": "16.3.0", + "husky": "8.0.1", + "jsdom": "19.0.0", + "prettier": "^2.6.2", + "rimraf": "3.0.2", + "typescript": "4.5.5", + "vitest": "0.4.1" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + }, + "dependencies": { + "svelte2tsx": "0.5.6" + } } diff --git a/packages/client/.gitignore b/packages/client/.gitignore index 97505c6f..973eb8ce 100644 --- a/packages/client/.gitignore +++ b/packages/client/.gitignore @@ -6,4 +6,4 @@ node_modules .env .env.* !.env.example -_kitql/ \ No newline at end of file +_kitql/ diff --git a/packages/graphql-codegen/package.json b/packages/graphql-codegen/package.json index a78aa2c8..ac64071d 100644 --- a/packages/graphql-codegen/package.json +++ b/packages/graphql-codegen/package.json @@ -1,54 +1,54 @@ { - "name": "@kitql/graphql-codegen", - "version": "0.5.1", - "description": "GraphQL Code Generator plugin to generate SvelteKit stores in kitql context", - "repository": { - "type": "git", - "url": "https://github.com/jycouet/kitql", - "directory": "packages/graphql-codegen" - }, - "license": "MIT", - "scripts": { - "prepack": "bob prepack" - }, - "devDependencies": { - "tslib": "2.4.0" - }, - "dependencies": { - "@graphql-codegen/plugin-helpers": "2.4.2", - "@graphql-codegen/visitor-plugin-common": "2.8.0", - "auto-bind": "5.0.1", - "change-case-all": "1.0.14" - }, - "peerDependencies": { - "graphql": "^15.0.0 || ^16.0.0" - }, - "main": "dist/index.js", - "module": "dist/index.mjs", - "exports": { - "./package.json": "./package.json", - ".": { - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./*": { - "require": "./dist/*.js", - "import": "./dist/*.mjs" - } - }, - "typings": "dist/index.d.ts", - "typescript": { - "definition": "dist/index.d.ts" - }, - "buildOptions": { - "input": "./src/index.ts" - }, - "publishConfig": { - "directory": "dist", - "access": "public" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - } + "name": "@kitql/graphql-codegen", + "version": "0.5.1", + "description": "GraphQL Code Generator plugin to generate SvelteKit stores in kitql context", + "repository": { + "type": "git", + "url": "https://github.com/jycouet/kitql", + "directory": "packages/graphql-codegen" + }, + "license": "MIT", + "scripts": { + "prepack": "bob prepack" + }, + "devDependencies": { + "tslib": "2.4.0" + }, + "dependencies": { + "@graphql-codegen/plugin-helpers": "2.4.2", + "@graphql-codegen/visitor-plugin-common": "2.8.0", + "auto-bind": "5.0.1", + "change-case-all": "1.0.14" + }, + "peerDependencies": { + "graphql": "^15.0.0 || ^16.0.0" + }, + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + "./package.json": "./package.json", + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./*": { + "require": "./dist/*.js", + "import": "./dist/*.mjs" + } + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" + }, + "buildOptions": { + "input": "./src/index.ts" + }, + "publishConfig": { + "directory": "dist", + "access": "public" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + } } diff --git a/packages/graphql-codegen/src/index.ts b/packages/graphql-codegen/src/index.ts index c56d8657..e031ffe9 100644 --- a/packages/graphql-codegen/src/index.ts +++ b/packages/graphql-codegen/src/index.ts @@ -1,315 +1,287 @@ - import { PluginFunction, Types } from '@graphql-codegen/plugin-helpers'; import { convertFactory, getConfigValue } from '@graphql-codegen/visitor-plugin-common'; import { pascalCase } from 'change-case-all'; import { concatAST, OperationDefinitionNode } from 'graphql'; function getOperationSuffix( - config: { [key: string]: any }, - node: OperationDefinitionNode, - operationType: string + config: { [key: string]: any }, + node: OperationDefinitionNode, + operationType: string ): string { - const { omitOperationSuffix = false, dedupeOperationSuffix = false } = config; - const operationName = node.name.value; + const { omitOperationSuffix = false, dedupeOperationSuffix = false } = config; + const operationName = node.name.value; - return omitOperationSuffix - ? '' - : dedupeOperationSuffix && operationName.toLowerCase().endsWith(operationType.toLowerCase()) - ? '' - : operationType; + return omitOperationSuffix + ? '' + : dedupeOperationSuffix && operationName.toLowerCase().endsWith(operationType.toLowerCase()) + ? '' + : operationType; } -export const plugin: PluginFunction, Types.ComplexPluginOutput> = ( - schema, - documents, - config -) => { - config = config ?? {}; +export const plugin: PluginFunction, Types.ComplexPluginOutput> = (schema, documents, config) => { + config = config ?? {}; - const allAst = concatAST(documents.map((v) => v.document)); - const convertName = convertFactory(config); - const operationResultSuffix = getConfigValue(config.operationResultSuffix, ''); - const operationPrefix = getConfigValue(config.operationPrefix, 'KQL_'); - const jsDocStyle: boolean = getConfigValue(config.jsDocStyle, false); - // ${jsDocStyle ? `` : ``} - const clientPath = getConfigValue(config.clientPath, '../kitQLClient'); + const allAst = concatAST(documents.map(v => v.document)); + const convertName = convertFactory(config); + const operationResultSuffix = getConfigValue(config.operationResultSuffix, ''); + const operationPrefix = getConfigValue(config.operationPrefix, 'KQL_'); + const jsDocStyle: boolean = getConfigValue(config.jsDocStyle, false); + // ${jsDocStyle ? `` : ``} + const clientPath = getConfigValue(config.clientPath, '../kitQLClient'); - const prefixImportBaseTypesFrom = config.importBaseTypesFrom ? 'Types.' : ''; + const prefixImportBaseTypesFrom = config.importBaseTypesFrom ? 'Types.' : ''; - const kqlStoresQuery = []; - const kqlStoresMutation = []; + const kqlStoresQuery = []; + const kqlStoresMutation = []; - const out = allAst.definitions - .map((node) => { - if ( - node.kind === 'OperationDefinition' && - node.name?.value && - node.operation !== 'subscription' - ) { - const operationName = pascalCase(node.name?.value); // AllContinents - const kqlStore = `${operationPrefix}${operationName}`; // KQL_AllContinents - const kqlStoreInternal = `${operationPrefix}${operationName}Store`; // KQL_AllContinentsStore - const operationString = pascalCase(node.operation); // Query Mutation Subscription - const operationTypeSuffix: string = getOperationSuffix(config, node, operationString); - const operationResultType: string = convertName(node, { - suffix: operationTypeSuffix + operationResultSuffix - }); - const kqltypeQuery = `${prefixImportBaseTypesFrom}${operationResultType}`; // Types.AllContinentsQuery - const kqltypeVariable = `${kqltypeQuery}Variables`; // Types.AllContinentsQueryVariables - const kqltypeQueryAndVariable = `${kqltypeQuery}, ${kqltypeVariable}`; // Types.AllContinentsQuery, Types.AllContinentsQueryVariables - const kqltypeDocument = `${prefixImportBaseTypesFrom}${operationName}Document`; // Types.AllContinentsDocument - const fnKeyword = - node.operation === 'query' ? 'query' : node.operation === 'mutation' ? 'mutate' : 'sub'; + const out = allAst.definitions + .map(node => { + if (node.kind === 'OperationDefinition' && node.name?.value && node.operation !== 'subscription') { + const operationName = pascalCase(node.name?.value); // AllContinents + const kqlStore = `${operationPrefix}${operationName}`; // KQL_AllContinents + const kqlStoreInternal = `${operationPrefix}${operationName}Store`; // KQL_AllContinentsStore + const operationString = pascalCase(node.operation); // Query Mutation Subscription + const operationTypeSuffix: string = getOperationSuffix(config, node, operationString); + const operationResultType: string = convertName(node, { + suffix: operationTypeSuffix + operationResultSuffix, + }); + const kqltypeQuery = `${prefixImportBaseTypesFrom}${operationResultType}`; // Types.AllContinentsQuery + const kqltypeVariable = `${kqltypeQuery}Variables`; // Types.AllContinentsQueryVariables + const kqltypeQueryAndVariable = `${kqltypeQuery}, ${kqltypeVariable}`; // Types.AllContinentsQuery, Types.AllContinentsQueryVariables + const kqltypeDocument = `${prefixImportBaseTypesFrom}${operationName}Document`; // Types.AllContinentsDocument + const fnKeyword = node.operation === 'query' ? 'query' : node.operation === 'mutation' ? 'mutate' : 'sub'; - if (node.operation === 'query') { - kqlStoresQuery.push(kqlStore); - } - if (node.operation === 'mutation') { - kqlStoresMutation.push(kqlStore); - } + if (node.operation === 'query') { + kqlStoresQuery.push(kqlStore); + } + if (node.operation === 'mutation') { + kqlStoresMutation.push(kqlStore); + } - const lines = []; - lines.push(`function ${kqlStoreInternal}() {`); - lines.push(` const operationName = '${kqlStore}';`); - lines.push( - ` const operationType = ResponseResultType.${ - node.operation === 'query' ? 'Query' : 'Mutation' - };` - ); - lines.push(``); - lines.push(` // prettier-ignore`); - lines.push( - ` const { subscribe, set, update } = writable${ - jsDocStyle ? `` : `>` - }({...defaultStoreValue, operationName, operationType});` - ); + const lines = []; + lines.push(`function ${kqlStoreInternal}() {`); + lines.push(` const operationName = '${kqlStore}';`); + lines.push(` const operationType = ResponseResultType.${node.operation === 'query' ? 'Query' : 'Mutation'};`); + lines.push(``); + lines.push(` // prettier-ignore`); + lines.push( + ` const { subscribe, set, update } = writable${ + jsDocStyle ? `` : `>` + }({...defaultStoreValue, operationName, operationType});` + ); - lines.push(``); + lines.push(``); - lines.push(` async function ${fnKeyword}Local(`); - // prettier-ignore - lines.push(` params${jsDocStyle ? `` : `?: Request${node.operation === 'query' ? 'Query': ''}Parameters<${kqltypeVariable}>`}`); - lines.push( - ` )${jsDocStyle ? `` : `: Promise>`} {` - ); - // prettier-ignore - lines.push(` let { fetch, variables${node.operation === 'query' ? ', settings': ''} } = params ?? {};`); - if (node.operation === 'query') { - lines.push(` let { cacheMs, policy } = settings ?? {};`); - } - lines.push(``); - lines.push(` const storedVariables = get(${kqlStore}).variables;`); - lines.push(` variables = variables ?? storedVariables;`); - if (node.operation === 'query') { - lines.push(` policy = policy ?? kitQLClient.policy;`); - } - lines.push(``); + lines.push(` async function ${fnKeyword}Local(`); + // prettier-ignore + lines.push(` params${jsDocStyle ? `` : `?: Request${node.operation === 'query' ? 'Query': ''}Parameters<${kqltypeVariable}>`}`); + lines.push(` )${jsDocStyle ? `` : `: Promise>`} {`); + // prettier-ignore + lines.push(` let { fetch, variables${node.operation === 'query' ? ', settings': ''} } = params ?? {};`); + if (node.operation === 'query') { + lines.push(` let { cacheMs, policy } = settings ?? {};`); + } + lines.push(``); + lines.push(` const storedVariables = get(${kqlStore}).variables;`); + lines.push(` variables = variables ?? storedVariables;`); + if (node.operation === 'query') { + lines.push(` policy = policy ?? kitQLClient.policy;`); + } + lines.push(``); - if (node.operation === 'query') { - lines.push( - ` // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data` - ); - lines.push(` if (${jsDocStyle ? `true` : `browser`}) {`); - lines.push(` if (policy !== 'network-only') {`); - lines.push(` // prettier-ignore`); - // prettier-ignore - lines.push(` const cachedData = kitQLClient.requestCache${jsDocStyle ? `` : `<${kqltypeQueryAndVariable}>`}({`); - lines.push( - ` variables, operationName, cacheMs, ${jsDocStyle ? `browser: true` : `browser`}` - ); - lines.push(` });`); - lines.push(` if (cachedData) {`); - lines.push( - ` const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE };` - ); - lines.push(` if (policy === 'cache-first') {`); - lines.push(` set(result);`); - lines.push(` if (!result.isOutdated) {`); - lines.push(` return result;`); - lines.push(` }`); - lines.push(` } else if (policy === 'cache-only') {`); - lines.push(` set(result);`); - lines.push(` return result;`); - lines.push(` } else if (policy === 'cache-and-network') {`); - lines.push(` set(result);`); - lines.push(` }`); - lines.push(` }`); - lines.push(` }`); - lines.push(` }`); - lines.push(``); - } + if (node.operation === 'query') { + lines.push( + ` // Cache only in the browser for now. In SSR, we will need session identif to not mix peoples data` + ); + lines.push(` if (${jsDocStyle ? `true` : `browser`}) {`); + lines.push(` if (policy !== 'network-only') {`); + lines.push(` // prettier-ignore`); + // prettier-ignore + lines.push(` const cachedData = kitQLClient.requestCache${jsDocStyle ? `` : `<${kqltypeQueryAndVariable}>`}({`); + lines.push(` variables, operationName, cacheMs, ${jsDocStyle ? `browser: true` : `browser`}`); + lines.push(` });`); + lines.push(` if (cachedData) {`); + lines.push(` const result = { ...cachedData, isFetching: false, status: RequestStatus.DONE };`); + lines.push(` if (policy === 'cache-first') {`); + lines.push(` set(result);`); + lines.push(` if (!result.isOutdated) {`); + lines.push(` return result;`); + lines.push(` }`); + lines.push(` } else if (policy === 'cache-only') {`); + lines.push(` set(result);`); + lines.push(` return result;`); + lines.push(` } else if (policy === 'cache-and-network') {`); + lines.push(` set(result);`); + lines.push(` }`); + lines.push(` }`); + lines.push(` }`); + lines.push(` }`); + lines.push(``); + } - lines.push(` update((c) => {`); - lines.push(` return { ...c, isFetching: true, status: RequestStatus.LOADING };`); - lines.push(` });`); - lines.push(``); - lines.push(` // prettier-ignore`); - lines.push( - ` const res = await kitQLClient.request${ - jsDocStyle ? `` : `<${kqltypeQueryAndVariable}>` - }({` - ); - lines.push(` skFetch: fetch,`); - lines.push(` document: ${kqltypeDocument},`); - lines.push(` variables, `); - lines.push(` operationName, `); - lines.push(` operationType, `); - lines.push(` ${jsDocStyle ? `browser: true` : `browser`}`); - lines.push(` });`); - lines.push( - ` const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables };` - ); - lines.push(` set(result);`); - lines.push(` return result;`); - lines.push(` }`); + lines.push(` update((c) => {`); + lines.push(` return { ...c, isFetching: true, status: RequestStatus.LOADING };`); + lines.push(` });`); + lines.push(``); + lines.push(` // prettier-ignore`); + lines.push(` const res = await kitQLClient.request${jsDocStyle ? `` : `<${kqltypeQueryAndVariable}>`}({`); + lines.push(` skFetch: fetch,`); + lines.push(` document: ${kqltypeDocument},`); + lines.push(` variables, `); + lines.push(` operationName, `); + lines.push(` operationType, `); + lines.push(` ${jsDocStyle ? `browser: true` : `browser`}`); + lines.push(` });`); + lines.push(` const result = { ...res, isFetching: false, status: RequestStatus.DONE, variables };`); + lines.push(` set(result);`); + lines.push(` return result;`); + lines.push(` }`); - lines.push(``); - lines.push(` return {`); - lines.push(` subscribe,`); + lines.push(``); + lines.push(` return {`); + lines.push(` subscribe,`); - lines.push(``); + lines.push(``); - // Query & Mutation - lines.push(` /**`); - lines.push(` * Can be used for SSR, but simpler option is \`.queryLoad\``); - lines.push(` * @returns fill this store & the cache`); - lines.push(` */`); - lines.push(` ${fnKeyword}: ${fnKeyword}Local,`); - lines.push(``); + // Query & Mutation + lines.push(` /**`); + lines.push(` * Can be used for SSR, but simpler option is \`.queryLoad\``); + lines.push(` * @returns fill this store & the cache`); + lines.push(` */`); + lines.push(` ${fnKeyword}: ${fnKeyword}Local,`); + lines.push(``); - if (node.operation === 'query') { - lines.push(` /**`); - lines.push(` * Ideal for SSR query. To be used in SvelteKit load function`); - lines.push(` * @returns fill this store & the cache`); - lines.push(` */`); - lines.push(` queryLoad: async (`); - lines.push(` params?: RequestQueryParameters<${kqltypeVariable}>`); - lines.push(` ): Promise => {`); - lines.push(` if (clientStarted) {`); - lines.push(` queryLocal(params); // No await on purpose, we are in a client navigation.`); - lines.push(` } else {`); - lines.push(` await queryLocal(params);`); - lines.push(` }`); - lines.push(` },`); - } + if (node.operation === 'query') { + lines.push(` /**`); + lines.push(` * Ideal for SSR query. To be used in SvelteKit load function`); + lines.push(` * @returns fill this store & the cache`); + lines.push(` */`); + lines.push(` queryLoad: async (`); + lines.push(` params?: RequestQueryParameters<${kqltypeVariable}>`); + lines.push(` ): Promise => {`); + lines.push(` if (clientStarted) {`); + lines.push(` queryLocal(params); // No await on purpose, we are in a client navigation.`); + lines.push(` } else {`); + lines.push(` await queryLocal(params);`); + lines.push(` }`); + lines.push(` },`); + } - if (node.operation === 'query') { - // Reset Cache - lines.push(``); - lines.push(` /**`); - lines.push(` * Reset Cache`); - lines.push(` */`); - lines.push(` resetCache(`); - lines.push(` variables${jsDocStyle ? `` : `: ${kqltypeVariable} | null = null`},`); - lines.push(` allOperationKey${jsDocStyle ? `` : `: boolean = true`},`); - lines.push(` withResetStore${jsDocStyle ? `` : `: boolean = true`}`); - lines.push(` ) {`); - lines.push(` kitQLClient.cacheRemove(operationName, { variables, allOperationKey });`); - lines.push(` if (withResetStore) {`); - lines.push(` set({ ...defaultStoreValue, operationName });`); - lines.push(` }`); - lines.push(` },`); - } + if (node.operation === 'query') { + // Reset Cache + lines.push(``); + lines.push(` /**`); + lines.push(` * Reset Cache`); + lines.push(` */`); + lines.push(` resetCache(`); + lines.push(` variables${jsDocStyle ? `` : `: ${kqltypeVariable} | null = null`},`); + lines.push(` allOperationKey${jsDocStyle ? `` : `: boolean = true`},`); + lines.push(` withResetStore${jsDocStyle ? `` : `: boolean = true`}`); + lines.push(` ) {`); + lines.push(` kitQLClient.cacheRemove(operationName, { variables, allOperationKey });`); + lines.push(` if (withResetStore) {`); + lines.push(` set({ ...defaultStoreValue, operationName });`); + lines.push(` }`); + lines.push(` },`); + } - if (node.operation === 'query') { - lines.push(``); - lines.push(` /**`); - lines.push(` * Patch the store &&|| cache with some data.`); - lines.push(` */`); - lines.push(` // prettier-ignore`); - lines.push( - ` patch(data: ${kqltypeQuery}, variables: ${kqltypeVariable} | null = null, type: PatchType = 'cache-and-store'): void {` - ); - lines.push(` let updatedCacheStore = undefined;`); - lines.push(` if(type === 'cache-only' || type === 'cache-and-store') {`); - lines.push( - ` updatedCacheStore = kitQLClient.cacheUpdate<${kqltypeQueryAndVariable}>(operationName, data, { variables });` - ); - lines.push(` }`); - lines.push(` if(type === 'store-only' ) {`); - lines.push(` let toReturn = { ...get(${kqlStore}), data, variables } ;`); - lines.push(` set(toReturn);`); - lines.push(` }`); - lines.push(` if(type === 'cache-and-store' ) {`); - lines.push(` set({...get(${kqlStore}), ...updatedCacheStore});`); - lines.push(` }`); - lines.push(` kitQLClient.logInfo(operationName, "patch", type);`); - lines.push(` }`); - } + if (node.operation === 'query') { + lines.push(``); + lines.push(` /**`); + lines.push(` * Patch the store &&|| cache with some data.`); + lines.push(` */`); + lines.push(` // prettier-ignore`); + lines.push( + ` patch(data: ${kqltypeQuery}, variables: ${kqltypeVariable} | null = null, type: PatchType = 'cache-and-store'): void {` + ); + lines.push(` let updatedCacheStore = undefined;`); + lines.push(` if(type === 'cache-only' || type === 'cache-and-store') {`); + lines.push( + ` updatedCacheStore = kitQLClient.cacheUpdate<${kqltypeQueryAndVariable}>(operationName, data, { variables });` + ); + lines.push(` }`); + lines.push(` if(type === 'store-only' ) {`); + lines.push(` let toReturn = { ...get(${kqlStore}), data, variables } ;`); + lines.push(` set(toReturn);`); + lines.push(` }`); + lines.push(` if(type === 'cache-and-store' ) {`); + lines.push(` set({...get(${kqlStore}), ...updatedCacheStore});`); + lines.push(` }`); + lines.push(` kitQLClient.logInfo(operationName, "patch", type);`); + lines.push(` }`); + } - lines.push(` };`); - lines.push(`}`); - lines.push(`/**`); - lines.push(` * KitQL Svelte Store with the latest \`${operationName}\` Operation`); - lines.push(` */`); - lines.push(`export const ${kqlStore} = ${kqlStoreInternal}();`); - lines.push(``); + lines.push(` };`); + lines.push(`}`); + lines.push(`/**`); + lines.push(` * KitQL Svelte Store with the latest \`${operationName}\` Operation`); + lines.push(` */`); + lines.push(`export const ${kqlStore} = ${kqlStoreInternal}();`); + lines.push(``); - return lines.join('\n'); - } + return lines.join('\n'); + } - return null; - }) - .filter(Boolean); + return null; + }) + .filter(Boolean); - const special = []; - special.push(`/**`); - special.push(` * Init KitQL (to have clientStarted = true!)`); - special.push(` *`); - special.push(` * Waiting for: https://github.com/sveltejs/kit/issues/4447`); - special.push(` */`); - special.push(`export function KQL__Init() {}`); + const special = []; + special.push(`/**`); + special.push(` * Init KitQL (to have clientStarted = true!)`); + special.push(` *`); + special.push(` * Waiting for: https://github.com/sveltejs/kit/issues/4447`); + special.push(` */`); + special.push(`export function KQL__Init() {}`); - special.push(' '); + special.push(' '); - special.push( - `/* Internal. To skip await on a client side navigation in the load function (from queryLoad)! */` - ); - special.push(`let clientStarted = false; // Will be true on a client side navigation`); - special.push(`if (browser) {`); - special.push(` addEventListener('sveltekit:start', () => {`); - special.push(` clientStarted = true;`); - special.push(` });`); - special.push(`}`); + special.push(`/* Internal. To skip await on a client side navigation in the load function (from queryLoad)! */`); + special.push(`let clientStarted = false; // Will be true on a client side navigation`); + special.push(`if (browser) {`); + special.push(` addEventListener('sveltekit:start', () => {`); + special.push(` clientStarted = true;`); + special.push(` });`); + special.push(`}`); - special.push(' '); + special.push(' '); - special.push(`/**`); - special.push(` * ResetAllCaches in One function!`); - special.push(` */`); - special.push(`export function ${operationPrefix}_ResetAllCaches() {`); - for (let i = 0; i < kqlStoresQuery.length; i++) { - const kqlStoreQuery = kqlStoresQuery[i]; - special.push(`\t${kqlStoreQuery}.resetCache();`); - } - special.push('}'); - special.push(' '); + special.push(`/**`); + special.push(` * ResetAllCaches in One function!`); + special.push(` */`); + special.push(`export function ${operationPrefix}_ResetAllCaches() {`); + for (let i = 0; i < kqlStoresQuery.length; i++) { + const kqlStoreQuery = kqlStoresQuery[i]; + special.push(`\t${kqlStoreQuery}.resetCache();`); + } + special.push('}'); + special.push(' '); - special.push(`/* Operations ๐Ÿ‘‡ */`); - const prepend = []; - if (!jsDocStyle) { - prepend.push(`import { browser } from '$app/env';`); - } - if (config.importBaseTypesFrom) { - prepend.push(`import * as Types from '${config.importBaseTypesFrom}';`); - } - prepend.push( - `import { defaultStoreValue, RequestStatus, ResponseResultType` + - `${ - jsDocStyle - ? `` - : `, type PatchType${ - kqlStoresMutation.length > 0 ? ', type RequestParameters' : '' - }, type RequestQueryParameters, type RequestResult` - } } from '@kitql/client';` - ); - prepend.push(`import { get, writable } from 'svelte/store';`); - prepend.push(`import { kitQLClient } from '${clientPath}';`); + special.push(`/* Operations ๐Ÿ‘‡ */`); + const prepend = []; + if (!jsDocStyle) { + prepend.push(`import { browser } from '$app/env';`); + } + if (config.importBaseTypesFrom) { + prepend.push(`import * as Types from '${config.importBaseTypesFrom}';`); + } + prepend.push( + `import { defaultStoreValue, RequestStatus, ResponseResultType` + + `${ + jsDocStyle + ? `` + : `, type PatchType${ + kqlStoresMutation.length > 0 ? ', type RequestParameters' : '' + }, type RequestQueryParameters, type RequestResult` + } } from '@kitql/client';` + ); + prepend.push(`import { get, writable } from 'svelte/store';`); + prepend.push(`import { kitQLClient } from '${clientPath}';`); - prepend.push(' '); + prepend.push(' '); - return { - prepend, - content: [...special, ...out].filter(Boolean).join('\n') - }; + return { + prepend, + content: [...special, ...out].filter(Boolean).join('\n'), + }; }; diff --git a/packages/graphql-codegen/test/plugins.spec.ts b/packages/graphql-codegen/test/plugins.spec.ts index 2c46f749..c8cfe032 100644 --- a/packages/graphql-codegen/test/plugins.spec.ts +++ b/packages/graphql-codegen/test/plugins.spec.ts @@ -4,125 +4,119 @@ import { describe, expect, it } from 'vitest'; import { plugin } from '../src'; const operations = [ - { - document: parse(`query me { id }`) - }, - { - document: parse(`mutation doSomething { id }`) - }, - { - document: parse(`query GetQuery { id }`) - }, - { - document: parse(`fragment Test on Test { t }`) - } + { + document: parse(`query me { id }`), + }, + { + document: parse(`mutation doSomething { id }`), + }, + { + document: parse(`query GetQuery { id }`), + }, + { + document: parse(`fragment Test on Test { t }`), + }, ]; describe('graphql-codegen', () => { - it('Should have a reference to browser', async () => { - const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; - expect(result.prepend).toContain(`import { browser } from '$app/env';`); - }); - - it('Should import from @kitql/client', async () => { - const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; - expect(result.prepend[1]).toMatchInlineSnapshot( - '"import { defaultStoreValue, RequestStatus, ResponseResultType, type PatchType, type RequestParameters, type RequestQueryParameters, type RequestResult } from \'@kitql/client\';"' - ); - }); - - it('Should import from @kitql/client WO Types', async () => { - const result = (await plugin(null as any, operations, { - jsDocStyle: true - })) as Types.ComplexPluginOutput; - expect(result.prepend).toContain( - `import { defaultStoreValue, RequestStatus, ResponseResultType } from '@kitql/client';` - ); - }); - - it('Should look for the instance of kitQLClient', async () => { - const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; - expect(result.prepend).toContain(`import { kitQLClient } from '../kitQLClient';`); - }); - - it('Without importBaseTypesFrom, should not import Types', async () => { - const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; - expect(result.content).toContain( - 'writable>' - ); - expect(result.content).toContain('params?: RequestParameters'); - expect(result.content).toContain( - 'Promise>' - ); - }); - - it('With importBaseTypesFrom, should import Types', async () => { - const result = (await plugin(null as any, operations, { - importBaseTypesFrom: '$graphql/_kitql/graphqlTypes' - })) as Types.ComplexPluginOutput; - - expect(result.prepend).toContain(`import * as Types from '$graphql/_kitql/graphqlTypes';`); - - expect(result.content).toContain( - 'writable>' - ); - expect(result.content).toContain( - 'params?: RequestParameters' - ); - expect(result.content).toContain( - 'Promise>' - ); - }); - - it('With no config, it should still work', async () => { - const result = (await plugin(null as any, operations, undefined)) as Types.ComplexPluginOutput; - expect(result.prepend).not.toBe(null); - expect(result.content).not.toBe(null); - - const result2 = (await plugin(null as any, operations, null)) as Types.ComplexPluginOutput; - expect(result2.prepend).not.toBe(null); - expect(result2.content).not.toBe(null); - }); - - it('config dedupeOperationSuffix, should dedupe Operation Suffix', async () => { - const result = (await plugin(null as any, operations, { - omitOperationSuffix: false, - dedupeOperationSuffix: true - })) as Types.ComplexPluginOutput; - - expect(result.prepend).not.toBe(null); - expect(result.content).not.toBe(null); - }); - - it('config operationPrefix HELLO_YOU', async () => { - const result = (await plugin(null as any, operations, { - operationPrefix: 'HELLO_YOU' - })) as Types.ComplexPluginOutput; - - expect(result.content).contains('export const HELLO_YOUMe = HELLO_YOUMeStore'); - }); - - it('config operationPrefix empty', async () => { - const result = (await plugin(null as any, operations, { - operationPrefix: '' - })) as Types.ComplexPluginOutput; - - expect(result.content).contains('export const Me = MeStore'); - }); - - it('config operationPrefix not defined', async () => { - const result = (await plugin(null as any, operations, { - // operationPrefix: '' - })) as Types.ComplexPluginOutput; - - expect(result.content).contains('export const KQL_Me = KQL_MeStore'); - }); - - it('having function _ResetAllCaches with 2 .resetCache();', async () => { - const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; - - const startLine = 18; - expect(result.content.split('\n').slice(startLine, startLine + 4)).toMatchInlineSnapshot(` + it('Should have a reference to browser', async () => { + const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; + expect(result.prepend).toContain(`import { browser } from '$app/env';`); + }); + + it('Should import from @kitql/client', async () => { + const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; + expect(result.prepend[1]).toMatchInlineSnapshot( + '"import { defaultStoreValue, RequestStatus, ResponseResultType, type PatchType, type RequestParameters, type RequestQueryParameters, type RequestResult } from \'@kitql/client\';"' + ); + }); + + it('Should import from @kitql/client WO Types', async () => { + const result = (await plugin(null as any, operations, { + jsDocStyle: true, + })) as Types.ComplexPluginOutput; + expect(result.prepend).toContain( + `import { defaultStoreValue, RequestStatus, ResponseResultType } from '@kitql/client';` + ); + }); + + it('Should look for the instance of kitQLClient', async () => { + const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; + expect(result.prepend).toContain(`import { kitQLClient } from '../kitQLClient';`); + }); + + it('Without importBaseTypesFrom, should not import Types', async () => { + const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; + expect(result.content).toContain('writable>'); + expect(result.content).toContain('params?: RequestParameters'); + expect(result.content).toContain('Promise>'); + }); + + it('With importBaseTypesFrom, should import Types', async () => { + const result = (await plugin(null as any, operations, { + importBaseTypesFrom: '$graphql/_kitql/graphqlTypes', + })) as Types.ComplexPluginOutput; + + expect(result.prepend).toContain(`import * as Types from '$graphql/_kitql/graphqlTypes';`); + + expect(result.content).toContain( + 'writable>' + ); + expect(result.content).toContain('params?: RequestParameters'); + expect(result.content).toContain( + 'Promise>' + ); + }); + + it('With no config, it should still work', async () => { + const result = (await plugin(null as any, operations, undefined)) as Types.ComplexPluginOutput; + expect(result.prepend).not.toBe(null); + expect(result.content).not.toBe(null); + + const result2 = (await plugin(null as any, operations, null)) as Types.ComplexPluginOutput; + expect(result2.prepend).not.toBe(null); + expect(result2.content).not.toBe(null); + }); + + it('config dedupeOperationSuffix, should dedupe Operation Suffix', async () => { + const result = (await plugin(null as any, operations, { + omitOperationSuffix: false, + dedupeOperationSuffix: true, + })) as Types.ComplexPluginOutput; + + expect(result.prepend).not.toBe(null); + expect(result.content).not.toBe(null); + }); + + it('config operationPrefix HELLO_YOU', async () => { + const result = (await plugin(null as any, operations, { + operationPrefix: 'HELLO_YOU', + })) as Types.ComplexPluginOutput; + + expect(result.content).contains('export const HELLO_YOUMe = HELLO_YOUMeStore'); + }); + + it('config operationPrefix empty', async () => { + const result = (await plugin(null as any, operations, { + operationPrefix: '', + })) as Types.ComplexPluginOutput; + + expect(result.content).contains('export const Me = MeStore'); + }); + + it('config operationPrefix not defined', async () => { + const result = (await plugin(null as any, operations, { + // operationPrefix: '' + })) as Types.ComplexPluginOutput; + + expect(result.content).contains('export const KQL_Me = KQL_MeStore'); + }); + + it('having function _ResetAllCaches with 2 .resetCache();', async () => { + const result = (await plugin(null as any, operations, {})) as Types.ComplexPluginOutput; + + const startLine = 18; + expect(result.content.split('\n').slice(startLine, startLine + 4)).toMatchInlineSnapshot(` [ "export function KQL__ResetAllCaches() {", " KQL_Me.resetCache();", @@ -130,5 +124,5 @@ describe('graphql-codegen', () => { "}", ] `); - }); + }); }); diff --git a/packages/helper/package.json b/packages/helper/package.json index 4a43b17b..5347154b 100644 --- a/packages/helper/package.json +++ b/packages/helper/package.json @@ -1,42 +1,42 @@ { - "name": "@kitql/helper", - "version": "0.3.0", - "repository": { - "type": "git", - "url": "https://github.com/jycouet/kitql", - "directory": "packages/helper" - }, - "license": "MIT", - "scripts": { - "prepack": "bob prepack" - }, - "dependencies": {}, - "main": "dist/index.js", - "module": "dist/index.mjs", - "exports": { - "./package.json": "./package.json", - ".": { - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./*": { - "require": "./dist/*.js", - "import": "./dist/*.mjs" - } - }, - "typings": "dist/index.d.ts", - "typescript": { - "definition": "dist/index.d.ts" - }, - "buildOptions": { - "input": "./src/index.ts" - }, - "publishConfig": { - "directory": "dist", - "access": "public" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - } + "name": "@kitql/helper", + "version": "0.3.0", + "repository": { + "type": "git", + "url": "https://github.com/jycouet/kitql", + "directory": "packages/helper" + }, + "license": "MIT", + "scripts": { + "prepack": "bob prepack" + }, + "dependencies": {}, + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + "./package.json": "./package.json", + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./*": { + "require": "./dist/*.js", + "import": "./dist/*.mjs" + } + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" + }, + "buildOptions": { + "input": "./src/index.ts" + }, + "publishConfig": { + "directory": "dist", + "access": "public" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + } } diff --git a/packages/helper/src/Log.ts b/packages/helper/src/Log.ts index 672b8ef4..399094ac 100644 --- a/packages/helper/src/Log.ts +++ b/packages/helper/src/Log.ts @@ -1,35 +1,35 @@ export function logGreen(str: string) { - return `\x1b[32m${str}\x1b[37m\x1b[0m`; + return `\x1b[32m${str}\x1b[37m\x1b[0m`; } export function logMagneta(str: string) { - return `\x1b[35m${str}\x1b[37m\x1b[0m`; + return `\x1b[35m${str}\x1b[37m\x1b[0m`; } export function logRed(str: string) { - return `\u001B[31m${str}\x1b[37m\x1b[0m`; + return `\u001B[31m${str}\x1b[37m\x1b[0m`; } export function logCyan(str: string) { - return `\x1b[36m${str}\x1b[37m\x1b[0m`; + return `\x1b[36m${str}\x1b[37m\x1b[0m`; } export function logYellow(str: string) { - return `\x1b[33m${str}\x1b[37m\x1b[0m`; + return `\x1b[33m${str}\x1b[37m\x1b[0m`; } export class Log { - private toolName: string; + private toolName: string; - constructor(toolName: string) { - this.toolName = toolName; - } + constructor(toolName: string) { + this.toolName = toolName; + } - info(msg: string) { - console.info(`${logMagneta(`[${this.toolName}]`)} ${msg}`); - } + info(msg: string) { + console.info(`${logMagneta(`[${this.toolName}]`)} ${msg}`); + } - error(msg: string) { - console.error(`${logMagneta(`[${this.toolName}]`)}${logRed(`[E]`)} ${msg}`); - } + error(msg: string) { + console.error(`${logMagneta(`[${this.toolName}]`)}${logRed(`[E]`)} ${msg}`); + } } diff --git a/packages/helper/src/queryStringApprend.ts b/packages/helper/src/queryStringApprend.ts index a81feb96..7eefa50a 100644 --- a/packages/helper/src/queryStringApprend.ts +++ b/packages/helper/src/queryStringApprend.ts @@ -9,28 +9,25 @@ * @param queryString an object with key value pairs, something like { focus: "Hello" } * @returns a sorted query string */ -export function queryStringApprend( - searchParams: URLSearchParams, - queryString: Record -) { - const query = {}; +export function queryStringApprend(searchParams: URLSearchParams, queryString: Record) { + const query = {}; - // 1 Destructure searchParams - searchParams.forEach((v, k) => { - query[k] = v; - }); + // 1 Destructure searchParams + searchParams.forEach((v, k) => { + query[k] = v; + }); - // 2 Upset with our queryString - for (const key in queryString) { - query[key] = queryString[key]; - } + // 2 Upset with our queryString + for (const key in queryString) { + query[key] = queryString[key]; + } - // 3 Transform in a table - const qs = []; - for (const key in query) { - qs.push(`${key}=${query[key]}`); - } + // 3 Transform in a table + const qs = []; + for (const key in query) { + qs.push(`${key}=${query[key]}`); + } - // 4 send back the Query String - return qs.sort().join('&'); + // 4 send back the Query String + return qs.sort().join('&'); } diff --git a/packages/helper/src/sleep.ts b/packages/helper/src/sleep.ts index 459a23ab..f099314a 100644 --- a/packages/helper/src/sleep.ts +++ b/packages/helper/src/sleep.ts @@ -1,6 +1,6 @@ export async function sleep(ms: number) { - if (ms <= 0) { - return; - } - return new Promise(resolve => setTimeout(resolve, ms)); + if (ms <= 0) { + return; + } + return new Promise(resolve => setTimeout(resolve, ms)); } diff --git a/packages/helper/src/stry.ts b/packages/helper/src/stry.ts index 95e52ac2..9458162b 100644 --- a/packages/helper/src/stry.ts +++ b/packages/helper/src/stry.ts @@ -1,34 +1,33 @@ - function sortObject(object: Object) { - const sortedObj = {}; - const keys = Object.keys(object); + const sortedObj = {}; + const keys = Object.keys(object); - keys.sort((key1, key2) => { - (key1 = key1.toLowerCase()), (key2 = key2.toLowerCase()); - if (key1 < key2) return -1; - if (key1 > key2) return 1; - return 0; - }); + keys.sort((key1, key2) => { + (key1 = key1.toLowerCase()), (key2 = key2.toLowerCase()); + if (key1 < key2) return -1; + if (key1 > key2) return 1; + return 0; + }); - for (const index in keys) { - const key = keys[index]; - if (typeof object[key] == 'object' && !Array.isArray(object[key]) && object[key]) { - sortedObj[key] = sortObject(object[key]); - } else { - sortedObj[key] = object[key]; - } - } + for (const index in keys) { + const key = keys[index]; + if (typeof object[key] == 'object' && !Array.isArray(object[key]) && object[key]) { + sortedObj[key] = sortObject(object[key]); + } else { + sortedObj[key] = object[key]; + } + } - return sortedObj; + return sortedObj; } export function stry(obj: Object | null | undefined, space = 2): string | null | undefined { - if (obj === null) { - return null; - } - if (obj === undefined) { - return undefined; - } - const ordered = sortObject(obj); - return JSON.stringify(ordered, null, space); + if (obj === null) { + return null; + } + if (obj === undefined) { + return undefined; + } + const ordered = sortObject(obj); + return JSON.stringify(ordered, null, space); } diff --git a/packages/helper/test/Log.spec.ts b/packages/helper/test/Log.spec.ts index 94b23343..944924d8 100644 --- a/packages/helper/test/Log.spec.ts +++ b/packages/helper/test/Log.spec.ts @@ -2,37 +2,37 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { Log, logCyan, logGreen, logMagneta, logRed, logYellow } from '../src/Log'; describe('kitql - helper - Log', () => { - beforeEach(() => { - vi.restoreAllMocks(); - }); + beforeEach(() => { + vi.restoreAllMocks(); + }); - it('Minimal config', async () => { - const log = new Log('tool name'); - expect(log).to.have.property('toolName', 'tool name'); + it('Minimal config', async () => { + const log = new Log('tool name'); + expect(log).to.have.property('toolName', 'tool name'); - const spy = vi.spyOn(log, 'info'); - log.info('Minimal config'); - expect(spy).toHaveBeenCalledOnce(); - }); + const spy = vi.spyOn(log, 'info'); + log.info('Minimal config'); + expect(spy).toHaveBeenCalledOnce(); + }); - it('with an error', async () => { - const log = new Log('tool name'); - expect(log).to.have.property('toolName', 'tool name'); + it('with an error', async () => { + const log = new Log('tool name'); + expect(log).to.have.property('toolName', 'tool name'); - const spy = vi.spyOn(log, 'error'); - log.error('with an error'); - expect(spy).toHaveBeenCalledOnce(); - }); + const spy = vi.spyOn(log, 'error'); + log.error('with an error'); + expect(spy).toHaveBeenCalledOnce(); + }); - it('with all colors', async () => { - const log = new Log('tool name'); - expect(log).to.have.property('toolName', 'tool name'); + it('with all colors', async () => { + const log = new Log('tool name'); + expect(log).to.have.property('toolName', 'tool name'); - const spy = vi.spyOn(log, 'info'); - log.info( - `with all colors: ${logGreen('green')}, ${logMagneta('magneta')}, ${logRed('red')}, + const spy = vi.spyOn(log, 'info'); + log.info( + `with all colors: ${logGreen('green')}, ${logMagneta('magneta')}, ${logRed('red')}, ${logCyan('cyan')}, ${logYellow('yellow')}` - ); - expect(spy).toHaveBeenCalledOnce(); - }); + ); + expect(spy).toHaveBeenCalledOnce(); + }); }); diff --git a/packages/helper/test/queryStringApprend.spec.ts b/packages/helper/test/queryStringApprend.spec.ts index 98115efb..c6acd5b4 100644 --- a/packages/helper/test/queryStringApprend.spec.ts +++ b/packages/helper/test/queryStringApprend.spec.ts @@ -2,23 +2,23 @@ import { describe, expect, it } from 'vitest'; import { queryStringApprend } from '../src/queryStringApprend'; describe('kitql - helper - queryStringApprend', () => { - it('with empty searchParams', async () => { - const searchParams = new URLSearchParams(); - const qs = queryStringApprend(searchParams, { focus: 'Hello' }); - expect(qs).toMatchInlineSnapshot('"focus=Hello"'); - }); + it('with empty searchParams', async () => { + const searchParams = new URLSearchParams(); + const qs = queryStringApprend(searchParams, { focus: 'Hello' }); + expect(qs).toMatchInlineSnapshot('"focus=Hello"'); + }); - it('with default searchParams', async () => { - const searchParams = new URLSearchParams(); - searchParams.set('page', '7'); - const qs = queryStringApprend(searchParams, { focus: 'Hello' }); - expect(qs).toMatchInlineSnapshot('"focus=Hello&page=7"'); - }); + it('with default searchParams', async () => { + const searchParams = new URLSearchParams(); + searchParams.set('page', '7'); + const qs = queryStringApprend(searchParams, { focus: 'Hello' }); + expect(qs).toMatchInlineSnapshot('"focus=Hello&page=7"'); + }); - it('check sorting qs', async () => { - const searchParams = new URLSearchParams(); - searchParams.set('page', '7'); - const qs = queryStringApprend(searchParams, { focus: 'Hello', sort: 'bestFirst' }); - expect(qs).toMatchInlineSnapshot('"focus=Hello&page=7&sort=bestFirst"'); - }); + it('check sorting qs', async () => { + const searchParams = new URLSearchParams(); + searchParams.set('page', '7'); + const qs = queryStringApprend(searchParams, { focus: 'Hello', sort: 'bestFirst' }); + expect(qs).toMatchInlineSnapshot('"focus=Hello&page=7&sort=bestFirst"'); + }); }); diff --git a/packages/helper/test/stry.spec.ts b/packages/helper/test/stry.spec.ts index d07b4778..cd9cf375 100644 --- a/packages/helper/test/stry.spec.ts +++ b/packages/helper/test/stry.spec.ts @@ -2,60 +2,60 @@ import { describe, expect, it } from 'vitest'; import { stry } from '../src/stry'; describe('kitql - helper - stry', () => { - it('space 2', async () => { - const obj = { hello: 'world' }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('space 2', async () => { + const obj = { hello: 'world' }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"hello\\": \\"world\\" }" `); - }); + }); - it('space 0', async () => { - const obj = { hello: 'world' }; - const result = stry(obj, 0); - expect(result).toMatchInlineSnapshot('"{\\"hello\\":\\"world\\"}"'); - }); + it('space 0', async () => { + const obj = { hello: 'world' }; + const result = stry(obj, 0); + expect(result).toMatchInlineSnapshot('"{\\"hello\\":\\"world\\"}"'); + }); - it('order a b c', async () => { - const obj = { a: 1, c: 3, b: 2 }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('order a b c', async () => { + const obj = { a: 1, c: 3, b: 2 }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"a\\": 1, \\"b\\": 2, \\"c\\": 3 }" `); - }); + }); - it('order A a', async () => { - const obj = { A: 'ONE', a: 1 }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('order A a', async () => { + const obj = { A: 'ONE', a: 1 }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"A\\": \\"ONE\\", \\"a\\": 1 }" `); - }); + }); - it('order a A', async () => { - const obj = { a: 1, A: 'ONE' }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('order a A', async () => { + const obj = { a: 1, A: 'ONE' }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"a\\": 1, \\"A\\": \\"ONE\\" }" `); - }); + }); - it('order a b c with nested', async () => { - const obj = { a: { bb: 22, aa: 11 }, c: 3, b: { aa: 11, bb: 22 } }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('order a b c with nested', async () => { + const obj = { a: { bb: 22, aa: 11 }, c: 3, b: { aa: 11, bb: 22 } }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"a\\": { \\"aa\\": 11, @@ -68,27 +68,27 @@ describe('kitql - helper - stry', () => { \\"c\\": 3 }" `); - }); + }); - it('obj null', async () => { - const obj = null; - const result = stry(obj); - expect(result).toMatchInlineSnapshot('null'); - }); + it('obj null', async () => { + const obj = null; + const result = stry(obj); + expect(result).toMatchInlineSnapshot('null'); + }); - it('obj undefined', async () => { - const obj = undefined; - const result = stry(obj); - expect(result).toMatchInlineSnapshot('undefined'); - }); + it('obj undefined', async () => { + const obj = undefined; + const result = stry(obj); + expect(result).toMatchInlineSnapshot('undefined'); + }); - it('obj will null', async () => { - const obj = { a: null }; - const result = stry(obj); - expect(result).toMatchInlineSnapshot(` + it('obj will null', async () => { + const obj = { a: null }; + const result = stry(obj); + expect(result).toMatchInlineSnapshot(` "{ \\"a\\": null }" `); - }); + }); }); diff --git a/packages/module-codegen/package.json b/packages/module-codegen/package.json index 6c282100..474c9c3a 100644 --- a/packages/module-codegen/package.json +++ b/packages/module-codegen/package.json @@ -1,54 +1,54 @@ { - "name": "@kitql/module-codegen", - "version": "0.3.0", - "description": "KitQL module-codegen", - "repository": { - "type": "git", - "url": "https://github.com/jycouet/kitql", - "directory": "packages/module-codegen" - }, - "type": "module", - "license": "MIT", - "scripts": { - "dev": "cd ../.. && yarn build && cd packages/module-codegen && node ./dist/index.mjs", - "prepack": "bob prepack" - }, - "devDependencies": { - "tslib": "2.4.0" - }, - "dependencies": { - "@kitql/helper": "0.3.0", - "yaml": "2.1.0" - }, - "peerDependencies": { - "graphql": "^15.0.0 || ^16.0.0" - }, - "main": "dist/index.js", - "module": "dist/index.mjs", - "exports": { - "./package.json": "./package.json", - ".": { - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./*": { - "require": "./dist/*.js", - "import": "./dist/*.mjs" - } - }, - "typings": "dist/index.d.ts", - "typescript": { - "definition": "dist/index.d.ts" - }, - "buildOptions": { - "input": "./src/index.ts" - }, - "publishConfig": { - "directory": "dist", - "access": "public" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - } + "name": "@kitql/module-codegen", + "version": "0.3.0", + "description": "KitQL module-codegen", + "repository": { + "type": "git", + "url": "https://github.com/jycouet/kitql", + "directory": "packages/module-codegen" + }, + "type": "module", + "license": "MIT", + "scripts": { + "dev": "cd ../.. && yarn build && cd packages/module-codegen && node ./dist/index.mjs", + "prepack": "bob prepack" + }, + "devDependencies": { + "tslib": "2.4.0" + }, + "dependencies": { + "@kitql/helper": "0.3.0", + "yaml": "2.1.0" + }, + "peerDependencies": { + "graphql": "^15.0.0 || ^16.0.0" + }, + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + "./package.json": "./package.json", + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./*": { + "require": "./dist/*.js", + "import": "./dist/*.mjs" + } + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" + }, + "buildOptions": { + "input": "./src/index.ts" + }, + "publishConfig": { + "directory": "dist", + "access": "public" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + } } diff --git a/packages/module-codegen/src/actionContexts.ts b/packages/module-codegen/src/actionContexts.ts index 4fcf3e1f..46b80a78 100644 --- a/packages/module-codegen/src/actionContexts.ts +++ b/packages/module-codegen/src/actionContexts.ts @@ -4,26 +4,26 @@ import { join } from 'path'; import { write } from './readWrite'; export function actionContext(ctxModules, outputFolder: string) { - const dataCtxModules = []; + const dataCtxModules = []; - ctxModules.forEach(ctx => { - dataCtxModules.push( - `import { getCtx${toPascalCase(ctx.ctxName)} } from '../../modules/${ - ctx.moduleName - }/providers/_ctx${toPascalCase(ctx.ctxName)}';` - ); - }); + ctxModules.forEach(ctx => { + dataCtxModules.push( + `import { getCtx${toPascalCase(ctx.ctxName)} } from '../../modules/${ctx.moduleName}/providers/_ctx${toPascalCase( + ctx.ctxName + )}';` + ); + }); - dataCtxModules.push(``); - dataCtxModules.push(`export function getCtxModules(prisma: any) {`); - dataCtxModules.push(` return {`); - ctxModules.forEach(ctx => { - dataCtxModules.push(` ...getCtx${toPascalCase(ctx.ctxName)}(prisma),`); - }); - dataCtxModules.push(` };`); - dataCtxModules.push(`}`); + dataCtxModules.push(``); + dataCtxModules.push(`export function getCtxModules(prisma: any) {`); + dataCtxModules.push(` return {`); + ctxModules.forEach(ctx => { + dataCtxModules.push(` ...getCtx${toPascalCase(ctx.ctxName)}(prisma),`); + }); + dataCtxModules.push(` };`); + dataCtxModules.push(`}`); - createFolderIfNotExists(join(outputFolder)); + createFolderIfNotExists(join(outputFolder)); - write(join(outputFolder, '_ctxModules.ts'), dataCtxModules); + write(join(outputFolder, '_ctxModules.ts'), dataCtxModules); } diff --git a/packages/module-codegen/src/actionEnum.ts b/packages/module-codegen/src/actionEnum.ts index 9fb983c6..c6156163 100644 --- a/packages/module-codegen/src/actionEnum.ts +++ b/packages/module-codegen/src/actionEnum.ts @@ -5,70 +5,70 @@ import { toPascalCase } from './formatString'; import { write } from './readWrite'; export function actionEnum( - modulePath: string, - moduleOutputFolder: string, - importBaseTypesFrom: string, - enums: Record + modulePath: string, + moduleOutputFolder: string, + importBaseTypesFrom: string, + enums: Record ) { - // Typedefs - createFolderIfNotExists(join(modulePath, '_enums')); - createFolderIfNotExists(join(modulePath, '_enums', 'typedefs')); + // Typedefs + createFolderIfNotExists(join(modulePath, '_enums')); + createFolderIfNotExists(join(modulePath, '_enums', 'typedefs')); - for (const key in enums) { - const list = enums[key]; - const enumFileData = []; + for (const key in enums) { + const list = enums[key]; + const enumFileData = []; - enumFileData.push(`enum ${key} {`); - list.forEach(c => { - enumFileData.push(`\t${c}`); - }); - enumFileData.push(`}`); - enumFileData.push(``); + enumFileData.push(`enum ${key} {`); + list.forEach(c => { + enumFileData.push(`\t${c}`); + }); + enumFileData.push(`}`); + enumFileData.push(``); - write(join(modulePath, '_enums', 'typedefs', `ENUM.${key}.graphql`), enumFileData); - } + write(join(modulePath, '_enums', 'typedefs', `ENUM.${key}.graphql`), enumFileData); + } - // Lists - createFolderIfNotExists(join(modulePath, '_enums', 'ui')); - createFolderIfNotExists(join(modulePath, '_enums', 'ui', 'lists')); + // Lists + createFolderIfNotExists(join(modulePath, '_enums', 'ui')); + createFolderIfNotExists(join(modulePath, '_enums', 'ui', 'lists')); - for (const key in enums) { - const list = enums[key]; - const keyWOEnum = key.replace('Enum', ''); - const enumFileData = []; + for (const key in enums) { + const list = enums[key]; + const keyWOEnum = key.replace('Enum', ''); + const enumFileData = []; - enumFileData.push(`import { type ${key} } from '${importBaseTypesFrom}';`); - enumFileData.push(``); - enumFileData.push(`export const ${keyWOEnum}List: Record<${key}, string> = {`); - list.forEach((c, i) => { - const isLast = i === list.length - 1; - enumFileData.push(`\t${c}: '${toPascalCase(c.toLowerCase())}'${isLast ? '' : ','}`); - }); - enumFileData.push(`};`); - enumFileData.push(``); + enumFileData.push(`import { type ${key} } from '${importBaseTypesFrom}';`); + enumFileData.push(``); + enumFileData.push(`export const ${keyWOEnum}List: Record<${key}, string> = {`); + list.forEach((c, i) => { + const isLast = i === list.length - 1; + enumFileData.push(`\t${c}: '${toPascalCase(c.toLowerCase())}'${isLast ? '' : ','}`); + }); + enumFileData.push(`};`); + enumFileData.push(``); - // Write this file only if it doesn't exist! - // Like this, you can change the value with text that will be displayed in the UI! - if (!existsSync(join(modulePath, '_enums', 'ui', 'lists', `${keyWOEnum}List.ts`))) { - write(join(modulePath, '_enums', 'ui', 'lists', `${keyWOEnum}List.ts`), enumFileData); - } - } + // Write this file only if it doesn't exist! + // Like this, you can change the value with text that will be displayed in the UI! + if (!existsSync(join(modulePath, '_enums', 'ui', 'lists', `${keyWOEnum}List.ts`))) { + write(join(modulePath, '_enums', 'ui', 'lists', `${keyWOEnum}List.ts`), enumFileData); + } + } - // Index - const enumFileData = []; - enumFileData.push(`import { createModule } from 'graphql-modules';`); - enumFileData.push(`import { typeDefs } from './${moduleOutputFolder}/typedefs';`); - enumFileData.push(``); - enumFileData.push(`export const _enumsModule = createModule({`); - enumFileData.push(`\tid: 'enums-module',`); - enumFileData.push(`\ttypeDefs`); - enumFileData.push(`});`); - enumFileData.push(``); + // Index + const enumFileData = []; + enumFileData.push(`import { createModule } from 'graphql-modules';`); + enumFileData.push(`import { typeDefs } from './${moduleOutputFolder}/typedefs';`); + enumFileData.push(``); + enumFileData.push(`export const _enumsModule = createModule({`); + enumFileData.push(`\tid: 'enums-module',`); + enumFileData.push(`\ttypeDefs`); + enumFileData.push(`});`); + enumFileData.push(``); - write(join(modulePath, '_enums', 'index.ts'), enumFileData); + write(join(modulePath, '_enums', 'index.ts'), enumFileData); - const enumsKeys = Object.keys(enums).map(key => { - return key; - }); - return enumsKeys; + const enumsKeys = Object.keys(enums).map(key => { + return key; + }); + return enumsKeys; } diff --git a/packages/module-codegen/src/actionModuleContext.ts b/packages/module-codegen/src/actionModuleContext.ts index 45678b3d..7c2a534e 100644 --- a/packages/module-codegen/src/actionModuleContext.ts +++ b/packages/module-codegen/src/actionModuleContext.ts @@ -6,63 +6,59 @@ import { write } from './readWrite'; // dl{EntityName}Get{Function}s => ctx{EntityName}_Dl_{Function} // ctxIchtts_Dl_ById export function actionModuleContext( - dataloadersModule: { moduleName: string; providerFile: string }[], // ["dlIchttsGetByIds"] - modulesFolder: string, // src/lib/modules - moduleName: string, // ichtts - moduleOutputFolder, //_kitql - withDbProvider + dataloadersModule: { moduleName: string; providerFile: string }[], // ["dlIchttsGetByIds"] + modulesFolder: string, // src/lib/modules + moduleName: string, // ichtts + moduleOutputFolder, //_kitql + withDbProvider ) { - const dataCtxModules = []; + const dataCtxModules = []; - const moduleNamePascalCase = toPascalCase(moduleName); - const functionsName = []; - dataloadersModule.forEach((dataloader) => { - const functionName = dataloader.providerFile - .substring(moduleName.length + 2 + 3) // + 2 => dl & + 3 => Get - .replace(`s.ts`, ''); - functionsName.push(functionName); - }); + const moduleNamePascalCase = toPascalCase(moduleName); + const functionsName = []; + dataloadersModule.forEach(dataloader => { + const functionName = dataloader.providerFile + .substring(moduleName.length + 2 + 3) // + 2 => dl & + 3 => Get + .replace(`s.ts`, ''); + functionsName.push(functionName); + }); - if (withDbProvider) { - dataCtxModules.push(`import { load_DataLoader } from '$graphql/helpers/dataLoaderHelper';`); - dataCtxModules.push(`import { type IKitQLContext } from '$graphql/kitQLServer';`); - if (functionsName.length > 0) { - dataCtxModules.push( - `import { type ${moduleNamePascalCase} } from '$graphql/_kitql/graphqlTypes';` - ); - } - dataCtxModules.push( - `import { Db${moduleNamePascalCase} } from '../providers/Db${moduleNamePascalCase}';` - ); - functionsName.forEach((functionName) => { - dataCtxModules.push( - `import { dl${moduleNamePascalCase}Get${functionName}s } from '../providers/dl${moduleNamePascalCase}Get${functionName}s';` - ); - }); + if (withDbProvider) { + dataCtxModules.push(`import { load_DataLoader } from '$graphql/helpers/dataLoaderHelper';`); + dataCtxModules.push(`import { type IKitQLContext } from '$graphql/kitQLServer';`); + if (functionsName.length > 0) { + dataCtxModules.push(`import { type ${moduleNamePascalCase} } from '$graphql/_kitql/graphqlTypes';`); + } + dataCtxModules.push(`import { Db${moduleNamePascalCase} } from '../providers/Db${moduleNamePascalCase}';`); + functionsName.forEach(functionName => { + dataCtxModules.push( + `import { dl${moduleNamePascalCase}Get${functionName}s } from '../providers/dl${moduleNamePascalCase}Get${functionName}s';` + ); + }); - dataCtxModules.push(``); - dataCtxModules.push(`export function ctx${moduleNamePascalCase}(ctx: IKitQLContext) {`); - dataCtxModules.push(` return ctx.injector.get(Db${moduleNamePascalCase});`); - dataCtxModules.push(`}`); - dataCtxModules.push(``); - } else { - dataCtxModules.push(`// No DbProvider found`); - dataCtxModules.push(`export {}`); - } + dataCtxModules.push(``); + dataCtxModules.push(`export function ctx${moduleNamePascalCase}(ctx: IKitQLContext) {`); + dataCtxModules.push(` return ctx.injector.get(Db${moduleNamePascalCase});`); + dataCtxModules.push(`}`); + dataCtxModules.push(``); + } else { + dataCtxModules.push(`// No DbProvider found`); + dataCtxModules.push(`export {}`); + } - functionsName.forEach((functionName) => { - dataCtxModules.push( - `export async function ctx${moduleNamePascalCase}_Dl_${functionName}(ctx: IKitQLContext, id: string | number) {` - ); - dataCtxModules.push( - ` return load_DataLoader<${moduleNamePascalCase}>(ctx.injector, dl${moduleNamePascalCase}Get${functionName}s.provide, id);` - ); - dataCtxModules.push(`}`); - }); + functionsName.forEach(functionName => { + dataCtxModules.push( + `export async function ctx${moduleNamePascalCase}_Dl_${functionName}(ctx: IKitQLContext, id: string | number) {` + ); + dataCtxModules.push( + ` return load_DataLoader<${moduleNamePascalCase}>(ctx.injector, dl${moduleNamePascalCase}Get${functionName}s.provide, id);` + ); + dataCtxModules.push(`}`); + }); - dataCtxModules.push(``); + dataCtxModules.push(``); - write(join(modulesFolder, moduleName, moduleOutputFolder, 'ctx.ts'), dataCtxModules); + write(join(modulesFolder, moduleName, moduleOutputFolder, 'ctx.ts'), dataCtxModules); - return functionsName.length + (withDbProvider ? 1 : 0); + return functionsName.length + (withDbProvider ? 1 : 0); } diff --git a/packages/module-codegen/src/actionModules.ts b/packages/module-codegen/src/actionModules.ts index 94296279..ecd31eb7 100644 --- a/packages/module-codegen/src/actionModules.ts +++ b/packages/module-codegen/src/actionModules.ts @@ -2,16 +2,16 @@ import { join } from 'path'; import { write } from './readWrite'; export function actionModules(moduleNames: string[], outputFolder: string) { - const dataAppModules = []; - moduleNames.forEach(moduleName => { - dataAppModules.push(`import { ${moduleName}Module } from '$modules/${moduleName}';`); - }); - dataAppModules.push(``); - dataAppModules.push(`export const modules = [`); - moduleNames.forEach(moduleName => { - dataAppModules.push(` ${moduleName}Module,`); - }); - dataAppModules.push(`];`); + const dataAppModules = []; + moduleNames.forEach(moduleName => { + dataAppModules.push(`import { ${moduleName}Module } from '$modules/${moduleName}';`); + }); + dataAppModules.push(``); + dataAppModules.push(`export const modules = [`); + moduleNames.forEach(moduleName => { + dataAppModules.push(` ${moduleName}Module,`); + }); + dataAppModules.push(`];`); - write(join(outputFolder, '_appModules.ts'), dataAppModules); + write(join(outputFolder, '_appModules.ts'), dataAppModules); } diff --git a/packages/module-codegen/src/actionResolvers.ts b/packages/module-codegen/src/actionResolvers.ts index a3b06b1f..f526f274 100644 --- a/packages/module-codegen/src/actionResolvers.ts +++ b/packages/module-codegen/src/actionResolvers.ts @@ -2,32 +2,26 @@ import { join } from 'path'; import { createFolderIfNotExists, getFiles, getFileWODots, getFileWOTS } from './fileFolder'; import { write } from './readWrite'; -export function actionResolvers( - moduleName: string, - modulesFolder: string, - moduleOutputFolder: string -) { - const resolversFolder = 'resolvers'; +export function actionResolvers(moduleName: string, modulesFolder: string, moduleOutputFolder: string) { + const resolversFolder = 'resolvers'; - const resolversFiles = getFiles(join(modulesFolder, moduleName, resolversFolder)); - const dataResolvers = []; - resolversFiles.forEach(resolver => { - dataResolvers.push( - `import { resolvers as ${getFileWODots(resolver)} } from '../resolvers/${getFileWOTS( - resolver - )}';` - ); - }); - dataResolvers.push(``); - dataResolvers.push(`export const resolvers = [`); - resolversFiles.forEach(resolver => { - dataResolvers.push(` ${getFileWODots(resolver)},`); - }); - dataResolvers.push(`];`); + const resolversFiles = getFiles(join(modulesFolder, moduleName, resolversFolder)); + const dataResolvers = []; + resolversFiles.forEach(resolver => { + dataResolvers.push( + `import { resolvers as ${getFileWODots(resolver)} } from '../resolvers/${getFileWOTS(resolver)}';` + ); + }); + dataResolvers.push(``); + dataResolvers.push(`export const resolvers = [`); + resolversFiles.forEach(resolver => { + dataResolvers.push(` ${getFileWODots(resolver)},`); + }); + dataResolvers.push(`];`); - createFolderIfNotExists(join(modulesFolder, moduleName, moduleOutputFolder)); + createFolderIfNotExists(join(modulesFolder, moduleName, moduleOutputFolder)); - write(join(modulesFolder, moduleName, moduleOutputFolder, 'resolvers.ts'), dataResolvers); + write(join(modulesFolder, moduleName, moduleOutputFolder, 'resolvers.ts'), dataResolvers); - return resolversFiles.length; + return resolversFiles.length; } diff --git a/packages/module-codegen/src/actionTypeDefs.ts b/packages/module-codegen/src/actionTypeDefs.ts index 1c310123..bd7246ba 100644 --- a/packages/module-codegen/src/actionTypeDefs.ts +++ b/packages/module-codegen/src/actionTypeDefs.ts @@ -2,28 +2,24 @@ import { join } from 'path'; import { createFolderIfNotExists, getFiles } from './fileFolder'; import { read, write } from './readWrite'; -export function actionTypeDefs( - moduleName: string, - modulesFolder: string, - moduleOutputFolder: string -) { - const typedefsFolder = 'typedefs'; +export function actionTypeDefs(moduleName: string, modulesFolder: string, moduleOutputFolder: string) { + const typedefsFolder = 'typedefs'; - const typedefsFiles = getFiles(join(modulesFolder, moduleName, typedefsFolder)); + const typedefsFiles = getFiles(join(modulesFolder, moduleName, typedefsFolder)); - const dataTypedefs = []; + const dataTypedefs = []; - dataTypedefs.push(`import { gql } from 'graphql-modules'`); - dataTypedefs.push(``); - dataTypedefs.push(`export const typeDefs = gql${'`'}`); - typedefsFiles.forEach(typedefs => { - dataTypedefs.push(read(join(modulesFolder, moduleName, typedefsFolder, typedefs))); - }); - dataTypedefs.push(`${'`'};`); + dataTypedefs.push(`import { gql } from 'graphql-modules'`); + dataTypedefs.push(``); + dataTypedefs.push(`export const typeDefs = gql${'`'}`); + typedefsFiles.forEach(typedefs => { + dataTypedefs.push(read(join(modulesFolder, moduleName, typedefsFolder, typedefs))); + }); + dataTypedefs.push(`${'`'};`); - createFolderIfNotExists(join(modulesFolder, moduleName, moduleOutputFolder)); + createFolderIfNotExists(join(modulesFolder, moduleName, moduleOutputFolder)); - write(join(modulesFolder, moduleName, moduleOutputFolder, 'typedefs.ts'), dataTypedefs); + write(join(modulesFolder, moduleName, moduleOutputFolder, 'typedefs.ts'), dataTypedefs); - return typedefsFiles.length; + return typedefsFiles.length; } diff --git a/packages/module-codegen/src/defaultConfigFile.ts b/packages/module-codegen/src/defaultConfigFile.ts index b62dc006..888bd522 100644 --- a/packages/module-codegen/src/defaultConfigFile.ts +++ b/packages/module-codegen/src/defaultConfigFile.ts @@ -2,39 +2,39 @@ import path from 'path'; import { write } from './readWrite'; export type TConfigFile = { - configs: { - modulesFolder: string; - moduleOutputFolder: string; - outputFolder: string; - }; - actions: { - createEnumsModule?: { prismaFile: string; importBaseTypesFrom: string } | false; - mergeModuleTypedefs: boolean; - mergeModuleResolvers: boolean; - mergeContexts: boolean; - mergeModules: boolean; - }; + configs: { + modulesFolder: string; + moduleOutputFolder: string; + outputFolder: string; + }; + actions: { + createEnumsModule?: { prismaFile: string; importBaseTypesFrom: string } | false; + mergeModuleTypedefs: boolean; + mergeModuleResolvers: boolean; + mergeContexts: boolean; + mergeModules: boolean; + }; }; export function writeDefaultConfigFile(pathFile) { - const data = [ - `configs:`, - ` modulesFolder: ./src/lib/modules`, - ` moduleOutputFolder: _kitql`, - ` outputFolder: ./src/lib/graphql/_kitql`, - ``, - `actions:`, - ` # - createBaseStructure: true`, - ` createEnumsModule:`, - ` prismaFile: ./prisma/schema.prisma`, - ` importBaseTypesFrom: $graphql/_kitql/graphqlTypes`, - ``, - ` mergeModuleTypedefs: true`, - ` mergeModuleResolvers: true`, - ` mergeContexts: true`, - ` mergeModules: true`, - `` - ]; + const data = [ + `configs:`, + ` modulesFolder: ./src/lib/modules`, + ` moduleOutputFolder: _kitql`, + ` outputFolder: ./src/lib/graphql/_kitql`, + ``, + `actions:`, + ` # - createBaseStructure: true`, + ` createEnumsModule:`, + ` prismaFile: ./prisma/schema.prisma`, + ` importBaseTypesFrom: $graphql/_kitql/graphqlTypes`, + ``, + ` mergeModuleTypedefs: true`, + ` mergeModuleResolvers: true`, + ` mergeContexts: true`, + ` mergeModules: true`, + ``, + ]; - write(path.join(pathFile), data); + write(path.join(pathFile), data); } diff --git a/packages/module-codegen/src/fileFolder.ts b/packages/module-codegen/src/fileFolder.ts index 8982754c..ef81f170 100644 --- a/packages/module-codegen/src/fileFolder.ts +++ b/packages/module-codegen/src/fileFolder.ts @@ -4,37 +4,37 @@ import path from 'path'; const rootPath = process.cwd(); export function getDirectories(source) { - return readdirSync(source, { withFileTypes: true }) - .filter((dirent) => dirent.isDirectory()) - .map((dirent) => dirent.name); + return readdirSync(source, { withFileTypes: true }) + .filter(dirent => dirent.isDirectory()) + .map(dirent => dirent.name); } export function getFiles(source) { - if (existsSync(source)) { - return readdirSync(source, { withFileTypes: true }) - .filter((dirent) => dirent.isFile()) - .map((dirent) => dirent.name); - } - return []; + if (existsSync(source)) { + return readdirSync(source, { withFileTypes: true }) + .filter(dirent => dirent.isFile()) + .map(dirent => dirent.name); + } + return []; } export function getFileWOTS(str) { - return str.replace('.ts', ''); + return str.replace('.ts', ''); } export function getFileWODots(str) { - return getFileWOTS(str).replace('.', ''); + return getFileWOTS(str).replace('.', ''); } export function createFolderIfNotExists(folder) { - if (!existsSync(folder)) { - mkdirSync(folder); - } + if (!existsSync(folder)) { + mkdirSync(folder); + } } export function getFullPath(folder) { - if (folder.startsWith('/')) { - return folder; - } - return path.join(rootPath, folder); + if (folder.startsWith('/')) { + return folder; + } + return path.join(rootPath, folder); } diff --git a/packages/module-codegen/src/formatString.ts b/packages/module-codegen/src/formatString.ts index 08221dc7..ad72b170 100644 --- a/packages/module-codegen/src/formatString.ts +++ b/packages/module-codegen/src/formatString.ts @@ -1,6 +1,6 @@ export function pad(num: number, size = 2): string { - const s = '000000000' + num; - return s.substring(s.length - size); + const s = '000000000' + num; + return s.substring(s.length - size); } /** @@ -11,13 +11,10 @@ export function pad(num: number, size = 2): string { * @author kalicki2K */ export function toPascalCase(input: string): string { - return `${input}` - .replace(new RegExp(/[-_]+/, 'g'), ' ') - .replace(new RegExp(/[^\w\s]/, 'g'), '') - .replace( - new RegExp(/\s+(.)(\w+)/, 'g'), - ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}` - ) - .replace(new RegExp(/\s/, 'g'), '') - .replace(new RegExp(/\w/), s => s.toUpperCase()); + return `${input}` + .replace(new RegExp(/[-_]+/, 'g'), ' ') + .replace(new RegExp(/[^\w\s]/, 'g'), '') + .replace(new RegExp(/\s+(.)(\w+)/, 'g'), ($1, $2, $3) => `${$2.toUpperCase() + $3.toLowerCase()}`) + .replace(new RegExp(/\s/, 'g'), '') + .replace(new RegExp(/\w/), s => s.toUpperCase()); } diff --git a/packages/module-codegen/src/index.ts b/packages/module-codegen/src/index.ts index f3e3d403..eb83c0c3 100644 --- a/packages/module-codegen/src/index.ts +++ b/packages/module-codegen/src/index.ts @@ -19,181 +19,169 @@ const log = new Log('KitQL module-codegen'); const configFilePath = getFullPath('.kitql.yaml'); if (fs.existsSync(configFilePath)) { - log.info(`${logGreen('โœ”')} config file found: ${logGreen(configFilePath)}`); - const content = read(configFilePath); - const configFile = YAML.parse(content) as TConfigFile; - - const moduleNames = getDirectories(configFile.configs.modulesFolder); - - // Enums - if (configFile.actions.createEnumsModule) { - log.info(`${logGreen('โณ')} creating ${logGreen('Enums')}`); - const prismaFilePath = getFullPath(configFile.actions.createEnumsModule.prismaFile); - if (fs.existsSync(prismaFilePath)) { - const enums = getPrismaEnum(readLines(prismaFilePath)); - const enumsKeys = actionEnum( - configFile.configs.modulesFolder, - configFile.configs.moduleOutputFolder, - configFile.actions.createEnumsModule.importBaseTypesFrom, - enums - ); - log.info( - `${logGreen('โœ”')} ${logGreen('Enums')} created [${enumsKeys - .map(c => logGreen(c)) - .join(',')}]` - ); - } else { - log.error(`${'โŒ'} file ${logRed(prismaFilePath)} not found!`); - throw new Error(`file ${prismaFilePath} not found!`); - } - } - - // Typedefs && Resolvers - const mergeModuleAction = []; - if (configFile.actions.mergeModuleTypedefs) { - mergeModuleAction.push('Typedefs'); - } - if (configFile.actions.mergeModuleResolvers) { - mergeModuleAction.push('Resolvers'); - } - if (configFile.actions.mergeContexts) { - mergeModuleAction.push('Contexts'); - } - if (mergeModuleAction.length > 0) { - log.info( - `${logGreen('โณ')} merging ${mergeModuleAction - .map(c => logGreen(c)) - .join(' and ')} in modules` - ); - } - - moduleNames.forEach(moduleName => { - let typedefsFilesLen = 0; - let resolversFilesLen = 0; - let contextsFilesLen = 0; - - // TypeDefs - if (configFile.actions.mergeModuleTypedefs) { - typedefsFilesLen = actionTypeDefs( - moduleName, - configFile.configs.modulesFolder, - configFile.configs.moduleOutputFolder - ); - } - - // Resolvers - if (configFile.actions.mergeModuleResolvers) { - resolversFilesLen = actionResolvers( - moduleName, - configFile.configs.modulesFolder, - configFile.configs.moduleOutputFolder - ); - } - - // Contexts - if (configFile.actions.mergeContexts) { - const providersFolder = 'providers'; - const dataloadersModule = []; - const providersFiles = getFiles( - join(configFile.configs.modulesFolder, moduleName, providersFolder) - ); - let withDbProvider = false; - providersFiles.forEach(providerFile => { - if (providerFile.startsWith(`dl${toPascalCase(moduleName)}`)) { - dataloadersModule.push({ moduleName, providerFile }); - } - if (providerFile.startsWith(`Db${toPascalCase(moduleName)}`)) { - withDbProvider = true; - } - }); - contextsFilesLen = actionModuleContext( - dataloadersModule, - configFile.configs.modulesFolder, - moduleName, - configFile.configs.moduleOutputFolder, - withDbProvider - ); - } - - if (mergeModuleAction.length > 0) { - log.info( - `${logGreen('โœ”')} merged - ${logGreen(pad(typedefsFilesLen, 2))} Typedefs | ${logGreen( - pad(resolversFilesLen, 2) - )} Resolvers | ${logGreen(pad(contextsFilesLen, 2))} Contexts for [${logGreen(moduleName)}]` - ); - } - }); - - // mergeContexts - if (configFile.actions.mergeContexts) { - log.info(`${logGreen('โณ')} merging ${logGreen('Contexts')}`); - const ctxModules = []; - const providersFolder = 'providers'; - moduleNames.forEach(moduleName => { - const providersFiles = getFiles( - join(configFile.configs.modulesFolder, moduleName, providersFolder) - ); - providersFiles.forEach(providerFile => { - if (providerFile.startsWith('_ctx')) { - const ctxName = providerFile.replace('_ctx', '').replace('.ts', ''); - ctxModules.push({ moduleName, ctxName }); - } - }); - }); - actionContext(ctxModules, configFile.configs.outputFolder); - - log.info( - `${logGreen('โœ”')} merged ${logGreen( - pad(ctxModules.length, 2) - )} contexts [${ctxModules.map(c => logGreen(c.moduleName + '#' + c.ctxName)).join(',')}]` - ); - } - - // mergeModuleContexts - // if (configFile.actions.mergeContexts) { - // log.info(`${logGreen('โณ')} merging modules ${logGreen('Contexts')}`); - // const providersFolder = 'providers'; - // moduleNames.forEach(moduleName => { - // let dataloadersModule = []; - // const providersFiles = getFiles( - // join(configFile.configs.modulesFolder, moduleName, providersFolder) - // ); - // providersFiles.forEach(providerFile => { - // if (providerFile.startsWith(`dl${toPascalCase(moduleName)}`)) { - // dataloadersModule.push({ moduleName, providerFile }); - // } - // }); - // actionModuleContext( - // dataloadersModule, - // configFile.configs.modulesFolder, - // moduleName, - // configFile.configs.moduleOutputFolder - // ); - // log.info( - // `${logGreen('โœ”')} merged ${logGreen( - // pad(dataloadersModule.length, 2) - // )} contexts [${dataloadersModule - // .map(c => logGreen(c.moduleName + '#' + c.ctxName)) - // .join(',')}]` - // ); - // }); - // } - - // mergeModules - if (configFile.actions.mergeModules) { - log.info(`${logGreen('โณ')} merging ${logGreen('Modules')}`); - actionModules(moduleNames, configFile.configs.outputFolder); - - log.info( - `${logGreen('โœ”')} merged ${logGreen( - pad(moduleNames.length, 2) - )} modules [${moduleNames.map(c => logGreen(c)).join(',')}]` - ); - } - // + log.info(`${logGreen('โœ”')} config file found: ${logGreen(configFilePath)}`); + const content = read(configFilePath); + const configFile = YAML.parse(content) as TConfigFile; + + const moduleNames = getDirectories(configFile.configs.modulesFolder); + + // Enums + if (configFile.actions.createEnumsModule) { + log.info(`${logGreen('โณ')} creating ${logGreen('Enums')}`); + const prismaFilePath = getFullPath(configFile.actions.createEnumsModule.prismaFile); + if (fs.existsSync(prismaFilePath)) { + const enums = getPrismaEnum(readLines(prismaFilePath)); + const enumsKeys = actionEnum( + configFile.configs.modulesFolder, + configFile.configs.moduleOutputFolder, + configFile.actions.createEnumsModule.importBaseTypesFrom, + enums + ); + log.info(`${logGreen('โœ”')} ${logGreen('Enums')} created [${enumsKeys.map(c => logGreen(c)).join(',')}]`); + } else { + log.error(`${'โŒ'} file ${logRed(prismaFilePath)} not found!`); + throw new Error(`file ${prismaFilePath} not found!`); + } + } + + // Typedefs && Resolvers + const mergeModuleAction = []; + if (configFile.actions.mergeModuleTypedefs) { + mergeModuleAction.push('Typedefs'); + } + if (configFile.actions.mergeModuleResolvers) { + mergeModuleAction.push('Resolvers'); + } + if (configFile.actions.mergeContexts) { + mergeModuleAction.push('Contexts'); + } + if (mergeModuleAction.length > 0) { + log.info(`${logGreen('โณ')} merging ${mergeModuleAction.map(c => logGreen(c)).join(' and ')} in modules`); + } + + moduleNames.forEach(moduleName => { + let typedefsFilesLen = 0; + let resolversFilesLen = 0; + let contextsFilesLen = 0; + + // TypeDefs + if (configFile.actions.mergeModuleTypedefs) { + typedefsFilesLen = actionTypeDefs( + moduleName, + configFile.configs.modulesFolder, + configFile.configs.moduleOutputFolder + ); + } + + // Resolvers + if (configFile.actions.mergeModuleResolvers) { + resolversFilesLen = actionResolvers( + moduleName, + configFile.configs.modulesFolder, + configFile.configs.moduleOutputFolder + ); + } + + // Contexts + if (configFile.actions.mergeContexts) { + const providersFolder = 'providers'; + const dataloadersModule = []; + const providersFiles = getFiles(join(configFile.configs.modulesFolder, moduleName, providersFolder)); + let withDbProvider = false; + providersFiles.forEach(providerFile => { + if (providerFile.startsWith(`dl${toPascalCase(moduleName)}`)) { + dataloadersModule.push({ moduleName, providerFile }); + } + if (providerFile.startsWith(`Db${toPascalCase(moduleName)}`)) { + withDbProvider = true; + } + }); + contextsFilesLen = actionModuleContext( + dataloadersModule, + configFile.configs.modulesFolder, + moduleName, + configFile.configs.moduleOutputFolder, + withDbProvider + ); + } + + if (mergeModuleAction.length > 0) { + log.info( + `${logGreen('โœ”')} merged - ${logGreen(pad(typedefsFilesLen, 2))} Typedefs | ${logGreen( + pad(resolversFilesLen, 2) + )} Resolvers | ${logGreen(pad(contextsFilesLen, 2))} Contexts for [${logGreen(moduleName)}]` + ); + } + }); + + // mergeContexts + if (configFile.actions.mergeContexts) { + log.info(`${logGreen('โณ')} merging ${logGreen('Contexts')}`); + const ctxModules = []; + const providersFolder = 'providers'; + moduleNames.forEach(moduleName => { + const providersFiles = getFiles(join(configFile.configs.modulesFolder, moduleName, providersFolder)); + providersFiles.forEach(providerFile => { + if (providerFile.startsWith('_ctx')) { + const ctxName = providerFile.replace('_ctx', '').replace('.ts', ''); + ctxModules.push({ moduleName, ctxName }); + } + }); + }); + actionContext(ctxModules, configFile.configs.outputFolder); + + log.info( + `${logGreen('โœ”')} merged ${logGreen(pad(ctxModules.length, 2))} contexts [${ctxModules + .map(c => logGreen(c.moduleName + '#' + c.ctxName)) + .join(',')}]` + ); + } + + // mergeModuleContexts + // if (configFile.actions.mergeContexts) { + // log.info(`${logGreen('โณ')} merging modules ${logGreen('Contexts')}`); + // const providersFolder = 'providers'; + // moduleNames.forEach(moduleName => { + // let dataloadersModule = []; + // const providersFiles = getFiles( + // join(configFile.configs.modulesFolder, moduleName, providersFolder) + // ); + // providersFiles.forEach(providerFile => { + // if (providerFile.startsWith(`dl${toPascalCase(moduleName)}`)) { + // dataloadersModule.push({ moduleName, providerFile }); + // } + // }); + // actionModuleContext( + // dataloadersModule, + // configFile.configs.modulesFolder, + // moduleName, + // configFile.configs.moduleOutputFolder + // ); + // log.info( + // `${logGreen('โœ”')} merged ${logGreen( + // pad(dataloadersModule.length, 2) + // )} contexts [${dataloadersModule + // .map(c => logGreen(c.moduleName + '#' + c.ctxName)) + // .join(',')}]` + // ); + // }); + // } + + // mergeModules + if (configFile.actions.mergeModules) { + log.info(`${logGreen('โณ')} merging ${logGreen('Modules')}`); + actionModules(moduleNames, configFile.configs.outputFolder); + + log.info( + `${logGreen('โœ”')} merged ${logGreen(pad(moduleNames.length, 2))} modules [${moduleNames + .map(c => logGreen(c)) + .join(',')}]` + ); + } + // } else { - writeDefaultConfigFile(configFilePath); - log.info(`${logGreen('โœ”')} config file created: ${logGreen(configFilePath)}`); + writeDefaultConfigFile(configFilePath); + log.info(`${logGreen('โœ”')} config file created: ${logGreen(configFilePath)}`); } // Done diff --git a/packages/module-codegen/src/prismaHelper.ts b/packages/module-codegen/src/prismaHelper.ts index 846872a1..ebe51456 100644 --- a/packages/module-codegen/src/prismaHelper.ts +++ b/packages/module-codegen/src/prismaHelper.ts @@ -1,24 +1,24 @@ import { toPascalCase } from './formatString'; export function getPrismaEnum(lines: string[]): Record { - const enums = {}; + const enums = {}; - let currentEnum = ''; - lines.forEach((line: string) => { - if (currentEnum !== '') { - if (line.includes('}')) { - currentEnum = ''; - } else { - enums[currentEnum].push(line.trim()); - } - } - if (line.startsWith('enum')) { - const [, enumName] = line.split(' '); - currentEnum = toPascalCase(enumName); - enums[currentEnum] = []; - } - // console.log(`line`, line); - }); + let currentEnum = ''; + lines.forEach((line: string) => { + if (currentEnum !== '') { + if (line.includes('}')) { + currentEnum = ''; + } else { + enums[currentEnum].push(line.trim()); + } + } + if (line.startsWith('enum')) { + const [, enumName] = line.split(' '); + currentEnum = toPascalCase(enumName); + enums[currentEnum] = []; + } + // console.log(`line`, line); + }); - return enums; + return enums; } diff --git a/packages/module-codegen/src/readWrite.ts b/packages/module-codegen/src/readWrite.ts index 67950790..863f58e2 100644 --- a/packages/module-codegen/src/readWrite.ts +++ b/packages/module-codegen/src/readWrite.ts @@ -2,13 +2,13 @@ import path from 'path'; import fs from 'fs'; export function read(pathFile: string): string { - return fs.readFileSync(pathFile, { encoding: 'utf8' }); + return fs.readFileSync(pathFile, { encoding: 'utf8' }); } export function readLines(pathFile: string): string[] { - return read(pathFile).split('\n'); + return read(pathFile).split('\n'); } export function write(pathFile: string, data: string[]) { - fs.writeFileSync(path.join(pathFile), data.join('\n')); + fs.writeFileSync(path.join(pathFile), data.join('\n')); } diff --git a/packages/template/package.json b/packages/template/package.json index 765a59aa..3ad5148a 100644 --- a/packages/template/package.json +++ b/packages/template/package.json @@ -1,51 +1,51 @@ { - "name": "@kitql/template", - "version": "0.3.0", - "description": "KitQL template", - "repository": { - "type": "git", - "url": "https://github.com/jycouet/kitql", - "directory": "packages/template" - }, - "type": "module", - "license": "MIT", - "scripts": { - "dev": "node ./dist/index", - "prepack": "bob prepack" - }, - "devDependencies": { - "tslib": "2.4.0" - }, - "dependencies": { - "yaml": "2.1.0" - }, - "peerDependencies": {}, - "main": "dist/index.js", - "module": "dist/index.mjs", - "exports": { - "./package.json": "./package.json", - ".": { - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./*": { - "require": "./dist/*.js", - "import": "./dist/*.mjs" - } - }, - "typings": "dist/index.d.ts", - "typescript": { - "definition": "dist/index.d.ts" - }, - "buildOptions": { - "input": "./src/index.ts" - }, - "publishConfig": { - "directory": "dist", - "access": "public" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - } + "name": "@kitql/template", + "version": "0.3.0", + "description": "KitQL template", + "repository": { + "type": "git", + "url": "https://github.com/jycouet/kitql", + "directory": "packages/template" + }, + "type": "module", + "license": "MIT", + "scripts": { + "dev": "node ./dist/index", + "prepack": "bob prepack" + }, + "devDependencies": { + "tslib": "2.4.0" + }, + "dependencies": { + "yaml": "2.1.0" + }, + "peerDependencies": {}, + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + "./package.json": "./package.json", + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./*": { + "require": "./dist/*.js", + "import": "./dist/*.mjs" + } + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" + }, + "buildOptions": { + "input": "./src/index.ts" + }, + "publishConfig": { + "directory": "dist", + "access": "public" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + } } diff --git a/packages/template/src/index.ts b/packages/template/src/index.ts index e200f841..f3f65ba9 100644 --- a/packages/template/src/index.ts +++ b/packages/template/src/index.ts @@ -3,30 +3,30 @@ import path from 'path'; import fs from 'fs'; function sar(str, sarObj) { - for (const key in sarObj) { - str = str.replaceAll(key, sarObj[key]); - } - return str; + for (const key in sarObj) { + str = str.replaceAll(key, sarObj[key]); + } + return str; } function getSarObj(confReplacesList: any[], upReplacesList: string[]) { - let sarObj = {}; - confReplacesList.forEach((item) => { - for (const key in item) { - if (upReplacesList.includes(key)) { - sarObj = { ...sarObj, ...item[key][0] }; - } - } - }); - return sarObj; + let sarObj = {}; + confReplacesList.forEach(item => { + for (const key in item) { + if (upReplacesList.includes(key)) { + sarObj = { ...sarObj, ...item[key][0] }; + } + } + }); + return sarObj; } function createRecursiveFolder(folderPath: string) { - if (!fs.existsSync(folderPath)) { - const previousFolderPath = folderPath.split('/').slice(0, -1).join('/'); - createRecursiveFolder(previousFolderPath); - fs.mkdirSync(folderPath); - } + if (!fs.existsSync(folderPath)) { + const previousFolderPath = folderPath.split('/').slice(0, -1).join('/'); + createRecursiveFolder(previousFolderPath); + fs.mkdirSync(folderPath); + } } console.info(`START`); @@ -37,62 +37,62 @@ const configFile = YAML.parse(content); // Files get folders... // Create Folders if they don't exsist .fft, modulename, ... ui, ... -configFile.up.forEach((up) => { - up.files.forEach((file: string) => { - const sarObj = getSarObj(configFile.replacesList, up.replacesList); - const fileName = path.basename(file); - const folders = file.split('/').slice(0, -1); - const fileFrom = path.join(up.basePathFrom, file); - const fileContent = fs.readFileSync(fileFrom, { encoding: 'utf8' }).split('\n'); - const fileTo = path.join(up.basePathTo, ...folders, sar(fileName, sarObj)); - - const dirTo = fileTo.split('/').slice(0, -1).join('/'); - createRecursiveFolder(dirTo); - - let pushLine = true; - let specialLine = false; - let preLineStart = ''; - let preLineEnd = ''; - const fileContentNew = []; - for (let i = 0; i < fileContent.length; i++) { - specialLine = false; - - // Pre Delete - const preKeyWordDelete = fileContent[i].split('//kitql Delete'); - if (preKeyWordDelete.length > 1) { - specialLine = true; - pushLine = !pushLine; - } - - // Pre Comment - const preKeyWordCom = fileContent[i].split('//kitql C('); - if (preKeyWordCom.length > 1) { - specialLine = true; - const preFrom = preKeyWordCom[1].split(')')[0]; - if (preLineStart !== '') { - preLineStart = ''; - preLineEnd = ''; - } else if (preFrom === 'ts') { - preLineStart = '//'; - } - } - - // Pre replace - const preKeyWord = fileContent[i].split('//kitql R('); - if (preKeyWord.length > 1) { - const preFrom = preKeyWord[1].split(')(')[0]; - const preTo = preKeyWord[1].split(')(')[1].split(')')[0]; - - fileContent[i] = preKeyWord[0].replaceAll(preFrom, preTo); - } - - if (!specialLine && pushLine) { - fileContentNew.push(preLineStart + fileContent[i] + preLineEnd); - } - } - - fs.writeFileSync(fileTo, sar(fileContentNew.join('\n'), sarObj), { encoding: 'utf8' }); - }); +configFile.up.forEach(up => { + up.files.forEach((file: string) => { + const sarObj = getSarObj(configFile.replacesList, up.replacesList); + const fileName = path.basename(file); + const folders = file.split('/').slice(0, -1); + const fileFrom = path.join(up.basePathFrom, file); + const fileContent = fs.readFileSync(fileFrom, { encoding: 'utf8' }).split('\n'); + const fileTo = path.join(up.basePathTo, ...folders, sar(fileName, sarObj)); + + const dirTo = fileTo.split('/').slice(0, -1).join('/'); + createRecursiveFolder(dirTo); + + let pushLine = true; + let specialLine = false; + let preLineStart = ''; + let preLineEnd = ''; + const fileContentNew = []; + for (let i = 0; i < fileContent.length; i++) { + specialLine = false; + + // Pre Delete + const preKeyWordDelete = fileContent[i].split('//kitql Delete'); + if (preKeyWordDelete.length > 1) { + specialLine = true; + pushLine = !pushLine; + } + + // Pre Comment + const preKeyWordCom = fileContent[i].split('//kitql C('); + if (preKeyWordCom.length > 1) { + specialLine = true; + const preFrom = preKeyWordCom[1].split(')')[0]; + if (preLineStart !== '') { + preLineStart = ''; + preLineEnd = ''; + } else if (preFrom === 'ts') { + preLineStart = '//'; + } + } + + // Pre replace + const preKeyWord = fileContent[i].split('//kitql R('); + if (preKeyWord.length > 1) { + const preFrom = preKeyWord[1].split(')(')[0]; + const preTo = preKeyWord[1].split(')(')[1].split(')')[0]; + + fileContent[i] = preKeyWord[0].replaceAll(preFrom, preTo); + } + + if (!specialLine && pushLine) { + fileContentNew.push(preLineStart + fileContent[i] + preLineEnd); + } + } + + fs.writeFileSync(fileTo, sar(fileContentNew.join('\n'), sarObj), { encoding: 'utf8' }); + }); }); console.info(`DONE`); diff --git a/packages/vite-plugin-watch-and-run/package.json b/packages/vite-plugin-watch-and-run/package.json index fa2d57bd..1091fb66 100644 --- a/packages/vite-plugin-watch-and-run/package.json +++ b/packages/vite-plugin-watch-and-run/package.json @@ -1,51 +1,51 @@ { - "name": "@kitql/vite-plugin-watch-and-run", - "version": "0.3.0", - "description": "vite-plugin that will watch some files and run a package.json script on change", - "repository": { - "type": "git", - "url": "https://github.com/jycouet/kitql", - "directory": "packages/vite-plugin-watch-and-run", - "homepage": "https://github.com/jycouet/kitql/tree/main/packages/vite-plugin-watch-and-run#readme" - }, - "license": "MIT", - "scripts": { - "test": "vitest run", - "prepack": "bob prepack" - }, - "devDependencies": { - "tslib": "2.4.0" - }, - "dependencies": { - "@kitql/helper": "0.3.0", - "micromatch": "4.0.5" - }, - "main": "dist/index.js", - "module": "dist/index.mjs", - "exports": { - "./package.json": "./package.json", - ".": { - "require": "./dist/index.js", - "import": "./dist/index.mjs" - }, - "./*": { - "require": "./dist/*.js", - "import": "./dist/*.mjs" - } - }, - "typings": "dist/index.d.ts", - "typescript": { - "definition": "dist/index.d.ts" - }, - "buildOptions": { - "input": "./src/index.ts" - }, - "publishConfig": { - "directory": "dist", - "access": "public" - }, - "volta": { - "node": "17.4.0", - "yarn": "1.22.17" - } + "name": "@kitql/vite-plugin-watch-and-run", + "version": "0.3.0", + "description": "vite-plugin that will watch some files and run a package.json script on change", + "repository": { + "type": "git", + "url": "https://github.com/jycouet/kitql", + "directory": "packages/vite-plugin-watch-and-run", + "homepage": "https://github.com/jycouet/kitql/tree/main/packages/vite-plugin-watch-and-run#readme" + }, + "license": "MIT", + "scripts": { + "test": "vitest run", + "prepack": "bob prepack" + }, + "devDependencies": { + "tslib": "2.4.0" + }, + "dependencies": { + "@kitql/helper": "0.3.0", + "micromatch": "4.0.5" + }, + "main": "dist/index.js", + "module": "dist/index.mjs", + "exports": { + "./package.json": "./package.json", + ".": { + "require": "./dist/index.js", + "import": "./dist/index.mjs" + }, + "./*": { + "require": "./dist/*.js", + "import": "./dist/*.mjs" + } + }, + "typings": "dist/index.d.ts", + "typescript": { + "definition": "dist/index.d.ts" + }, + "buildOptions": { + "input": "./src/index.ts" + }, + "publishConfig": { + "directory": "dist", + "access": "public" + }, + "volta": { + "node": "17.4.0", + "yarn": "1.22.17" + } } diff --git a/packages/vite-plugin-watch-and-run/src/index.ts b/packages/vite-plugin-watch-and-run/src/index.ts index 5e2082cf..602a5594 100644 --- a/packages/vite-plugin-watch-and-run/src/index.ts +++ b/packages/vite-plugin-watch-and-run/src/index.ts @@ -3,160 +3,145 @@ import { spawn } from 'child_process'; import micromatch from 'micromatch'; export type Options = { - /** - * watch files to trigger the run action (glob format) - */ - watch: string; - /** - * Kind of watch that will trigger the run action - */ - watchKind?: WatchKind[]; - /** - * run command (yarn gen for example!) - */ - run: string; - /** - * Delay before running the run command (in ms) - * @default 500 ms - */ - delay?: number | null; + /** + * watch files to trigger the run action (glob format) + */ + watch: string; + /** + * Kind of watch that will trigger the run action + */ + watchKind?: WatchKind[]; + /** + * run command (yarn gen for example!) + */ + run: string; + /** + * Delay before running the run command (in ms) + * @default 500 ms + */ + delay?: number | null; }; export type WatchKind = 'ADD' | 'CHANGE' | 'DELETE'; export type StateDetail = { - kind: ('ADD' | 'CHANGE' | 'DELETE')[]; - run: string; - delay: number; - isRunning: boolean; + kind: ('ADD' | 'CHANGE' | 'DELETE')[]; + run: string; + delay: number; + isRunning: boolean; }; function checkConf(params: Options[]) { - if (!Array.isArray(params)) { - throw new Error('plugin watchAndRun, `params` needs to be an array.'); - } - - const paramsChecked: Record = {}; - - for (let i = 0; i < params.length; i++) { - const param = params[i]; - if (!param.watch) { - throw new Error('plugin watch-and-run, `watch` is missing.'); - } - if (!param.run) { - throw new Error('plugin watch-and-run, `run` is missing.'); - } - - paramsChecked[param.watch] = { - kind: param.watchKind ?? ['ADD', 'CHANGE', 'DELETE'], - run: param.run, - delay: param.delay ?? 500, - isRunning: false - }; - } - - return paramsChecked; + if (!Array.isArray(params)) { + throw new Error('plugin watchAndRun, `params` needs to be an array.'); + } + + const paramsChecked: Record = {}; + + for (let i = 0; i < params.length; i++) { + const param = params[i]; + if (!param.watch) { + throw new Error('plugin watch-and-run, `watch` is missing.'); + } + if (!param.run) { + throw new Error('plugin watch-and-run, `run` is missing.'); + } + + paramsChecked[param.watch] = { + kind: param.watchKind ?? ['ADD', 'CHANGE', 'DELETE'], + run: param.run, + delay: param.delay ?? 500, + isRunning: false, + }; + } + + return paramsChecked; } -async function shouldRun( - absolutePath: string, - watchKind: WatchKind, - watchAndRunConf: Record -) { - for (const globToWatch in watchAndRunConf) { - const param = watchAndRunConf[globToWatch]; - if ( - !param.isRunning && - param.kind.includes(watchKind) && - micromatch.isMatch(absolutePath, globToWatch) - ) { - return { - shouldRun: true, - globToWatch, - param - }; - } - } - return { - shouldRun: false, - globToWatch: null, - param: null - }; +async function shouldRun(absolutePath: string, watchKind: WatchKind, watchAndRunConf: Record) { + for (const globToWatch in watchAndRunConf) { + const param = watchAndRunConf[globToWatch]; + if (!param.isRunning && param.kind.includes(watchKind) && micromatch.isMatch(absolutePath, globToWatch)) { + return { + shouldRun: true, + globToWatch, + param, + }; + } + } + return { + shouldRun: false, + globToWatch: null, + param: null, + }; } -async function watcher( - absolutePath: string, - watchKind: WatchKind, - watchAndRunConf: Record -) { - const shouldRunInfo = await shouldRun(absolutePath, watchKind, watchAndRunConf); - if (shouldRunInfo.shouldRun) { - watchAndRunConf[shouldRunInfo.globToWatch].isRunning = true; - - log.info( - `${logGreen('โœ”')} Thx to ${logGreen(shouldRunInfo.globToWatch)}, ` + - `triggered by ${logCyan(watchKind)} ${logGreen(absolutePath)}, ` + - `we will wait ${logCyan(shouldRunInfo.param.delay + 'ms')} and run ${logGreen( - shouldRunInfo.param.run - )}.` - ); - - // Run after a delay - setTimeout(() => { - const child = spawn(shouldRunInfo.param.run, [], { shell: true }); - - //spit stdout to screen - child.stdout.on('data', (data) => { - process.stdout.write(data.toString()); - }); - - //spit stderr to screen - child.stderr.on('data', (data) => { - process.stdout.write(data.toString()); - }); - - child.on('close', (code) => { - if (code === 0) { - log.info(`${logGreen('โœ”')} finished ${logGreen('successfully')}`); - } else { - log.error(`${'โŒ'} finished with some ${logRed('errors')}`); - } - shouldRunInfo.param.isRunning = false; - }); - - return; - }, shouldRunInfo.param.delay); - } - - return; +async function watcher(absolutePath: string, watchKind: WatchKind, watchAndRunConf: Record) { + const shouldRunInfo = await shouldRun(absolutePath, watchKind, watchAndRunConf); + if (shouldRunInfo.shouldRun) { + watchAndRunConf[shouldRunInfo.globToWatch].isRunning = true; + + log.info( + `${logGreen('โœ”')} Thx to ${logGreen(shouldRunInfo.globToWatch)}, ` + + `triggered by ${logCyan(watchKind)} ${logGreen(absolutePath)}, ` + + `we will wait ${logCyan(shouldRunInfo.param.delay + 'ms')} and run ${logGreen(shouldRunInfo.param.run)}.` + ); + + // Run after a delay + setTimeout(() => { + const child = spawn(shouldRunInfo.param.run, [], { shell: true }); + + //spit stdout to screen + child.stdout.on('data', data => { + process.stdout.write(data.toString()); + }); + + //spit stderr to screen + child.stderr.on('data', data => { + process.stdout.write(data.toString()); + }); + + child.on('close', code => { + if (code === 0) { + log.info(`${logGreen('โœ”')} finished ${logGreen('successfully')}`); + } else { + log.error(`${'โŒ'} finished with some ${logRed('errors')}`); + } + shouldRunInfo.param.isRunning = false; + }); + + return; + }, shouldRunInfo.param.delay); + } + + return; } const log = new Log('KitQL vite-plugin-watch-and-run'); - export default function watchAndRun(params: Options[]) { - // check params, throw Errors if not valid and return a new object representing the state of the plugin - const watchAndRunConf = checkConf(params); - - return { - name: 'watch-and-run', - - watchAndRunConf, - - configureServer(server) { - const watcherAdd = async (absolutePath) => { - watcher(absolutePath, 'ADD', watchAndRunConf); - }; - const watcherChange = async (absolutePath) => { - watcher(absolutePath, 'CHANGE', watchAndRunConf); - }; - const watcherDelete = async (absolutePath) => { - watcher(absolutePath, 'DELETE', watchAndRunConf); - }; - - server.watcher.on('add', watcherAdd); - server.watcher.on('change', watcherChange); - server.watcher.on('delete', watcherDelete); - } - }; + // check params, throw Errors if not valid and return a new object representing the state of the plugin + const watchAndRunConf = checkConf(params); + + return { + name: 'watch-and-run', + + watchAndRunConf, + + configureServer(server) { + const watcherAdd = async absolutePath => { + watcher(absolutePath, 'ADD', watchAndRunConf); + }; + const watcherChange = async absolutePath => { + watcher(absolutePath, 'CHANGE', watchAndRunConf); + }; + const watcherDelete = async absolutePath => { + watcher(absolutePath, 'DELETE', watchAndRunConf); + }; + + server.watcher.on('add', watcherAdd); + server.watcher.on('change', watcherChange); + server.watcher.on('delete', watcherDelete); + }, + }; } diff --git a/packages/vite-plugin-watch-and-run/test/plugins.checkConf.spec.ts b/packages/vite-plugin-watch-and-run/test/plugins.checkConf.spec.ts index 339eee3b..fcb36d74 100644 --- a/packages/vite-plugin-watch-and-run/test/plugins.checkConf.spec.ts +++ b/packages/vite-plugin-watch-and-run/test/plugins.checkConf.spec.ts @@ -2,77 +2,73 @@ import watchAndRun from '../src'; import { describe, expect, it, vi } from 'vitest'; describe('vite-plugin-watch-and-run', () => { - it('Should throw an error as no config is sent', async () => { - const t = () => { - watchAndRun(null); - }; - expect(t).toThrowErrorMatchingInlineSnapshot( - '"plugin watchAndRun, `params` needs to be an array."' - ); - }); + it('Should throw an error as no config is sent', async () => { + const t = () => { + watchAndRun(null); + }; + expect(t).toThrowErrorMatchingInlineSnapshot('"plugin watchAndRun, `params` needs to be an array."'); + }); - it('Should throw an error as no watch', async () => { - const t = () => { - watchAndRun([{} as any]); - }; - expect(t).toThrowErrorMatchingInlineSnapshot('"plugin watch-and-run, `watch` is missing."'); - }); + it('Should throw an error as no watch', async () => { + const t = () => { + watchAndRun([{} as any]); + }; + expect(t).toThrowErrorMatchingInlineSnapshot('"plugin watch-and-run, `watch` is missing."'); + }); - it('Should throw an error as no run', async () => { - const t = () => { - watchAndRun([{ watch: 'hello!' } as any]); - }; - expect(t).toThrowErrorMatchingInlineSnapshot('"plugin watch-and-run, `run` is missing."'); - }); + it('Should throw an error as no run', async () => { + const t = () => { + watchAndRun([{ watch: 'hello!' } as any]); + }; + expect(t).toThrowErrorMatchingInlineSnapshot('"plugin watch-and-run, `run` is missing."'); + }); - it('Should have a valid conf, with default delay:500', async () => { - const watch = '**/*.(gql|graphql)'; - const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); + it('Should have a valid conf, with default delay:500', async () => { + const watch = '**/*.(gql|graphql)'; + const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); - expect(plugin.watchAndRunConf).to.have.property(watch).to.have.property('delay', 500); - }); + expect(plugin.watchAndRunConf).to.have.property(watch).to.have.property('delay', 500); + }); - it('Should have a valid conf, with delay 0', async () => { - const watch = '**/*.(gql|graphql)'; - const plugin = watchAndRun([{ watch, run: 'yarn gen', delay: 0 }]); + it('Should have a valid conf, with delay 0', async () => { + const watch = '**/*.(gql|graphql)'; + const plugin = watchAndRun([{ watch, run: 'yarn gen', delay: 0 }]); - expect(plugin.watchAndRunConf).to.have.property(watch).to.have.property('delay', 0); - }); + expect(plugin.watchAndRunConf).to.have.property(watch).to.have.property('delay', 0); + }); - it('Should have a valid conf, with default watchKind:ADD / CHANGE / DELETE', async () => { - const watch = '**/*.(gql|graphql)'; - const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); + it('Should have a valid conf, with default watchKind:ADD / CHANGE / DELETE', async () => { + const watch = '**/*.(gql|graphql)'; + const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); - expect(plugin.watchAndRunConf) - .to.have.property(watch) - .to.have.property('kind') - .to.have.all.members(['ADD', 'CHANGE', 'DELETE']); - }); + expect(plugin.watchAndRunConf) + .to.have.property(watch) + .to.have.property('kind') + .to.have.all.members(['ADD', 'CHANGE', 'DELETE']); + }); - it('Should register all watchers', async () => { - const watch = '**/*.(gql|graphql)'; - const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); + it('Should register all watchers', async () => { + const watch = '**/*.(gql|graphql)'; + const plugin = watchAndRun([{ watch, run: 'yarn gen' }]); - const server = { - watcher: { - on: vi.fn() - } - }; - const spy = vi - .spyOn(server.watcher, 'on') - .mockImplementation((type: 'add' | 'change' | 'delete', callback) => { - if (type === 'add' || type === 'change' || type === 'delete') { - // eslint-disable-next-line unicorn/no-lonely-if - if (typeof callback === 'function') return 'registered'; - } - return 'error'; - }); - plugin.configureServer(server); - expect(spy).toHaveBeenCalledTimes(3); - const operations = ['add', 'change', 'delete']; - spy.mock.calls.forEach((call, index) => { - expect(spy).toHaveBeenNthCalledWith(index + 1, operations[index], call[1]); - expect(spy).toHaveNthReturnedWith(index + 1, 'registered'); - }); - }); + const server = { + watcher: { + on: vi.fn(), + }, + }; + const spy = vi.spyOn(server.watcher, 'on').mockImplementation((type: 'add' | 'change' | 'delete', callback) => { + if (type === 'add' || type === 'change' || type === 'delete') { + // eslint-disable-next-line unicorn/no-lonely-if + if (typeof callback === 'function') return 'registered'; + } + return 'error'; + }); + plugin.configureServer(server); + expect(spy).toHaveBeenCalledTimes(3); + const operations = ['add', 'change', 'delete']; + spy.mock.calls.forEach((call, index) => { + expect(spy).toHaveBeenNthCalledWith(index + 1, operations[index], call[1]); + expect(spy).toHaveNthReturnedWith(index + 1, 'registered'); + }); + }); }); diff --git a/tsconfig.json b/tsconfig.json index 7aeba4d0..784b8302 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,36 +1,36 @@ { - "compilerOptions": { - "incremental": true, - "baseUrl": ".", - "outDir": "dist", - "rootDir": "packages", - "esModuleInterop": true, - "allowSyntheticDefaultImports": true, - "importHelpers": true, - "experimentalDecorators": true, - "module": "esnext", - "target": "es2018", - "lib": ["es6", "esnext", "es2015", "dom"], - "suppressImplicitAnyIndexErrors": true, - "moduleResolution": "node", - "emitDecoratorMetadata": true, - "sourceMap": true, - "declaration": true, - "noImplicitThis": true, - "alwaysStrict": true, - "noImplicitReturns": true, - "noUnusedLocals": false, - "resolveJsonModule": true, - "skipLibCheck": true, - "paths": { - "@kitql/graphql-codegen": ["packages/graphql-codegen/src/index"], - "@kitql/module-codegen": ["packages/module-codegen/src/index"], - "@kitql/helper": ["packages/helper/src/index"], - "@kitql/client": ["packages/client/src/lib/toExport"], - "@kitql/all-in": ["packages/all-in/src/lib"], - "$lib/graphql/_kitql/graphqlTypes": ["packages/client/src/lib/graphql/_kitql/graphqlTypes"] - } - }, - "include": ["packages"], - "exclude": ["**/tests/test-files", "**/tests/test-documents", "**/dist", "**/temp"] + "compilerOptions": { + "incremental": true, + "baseUrl": ".", + "outDir": "dist", + "rootDir": "packages", + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "importHelpers": true, + "experimentalDecorators": true, + "module": "esnext", + "target": "es2018", + "lib": ["es6", "esnext", "es2015", "dom"], + "suppressImplicitAnyIndexErrors": true, + "moduleResolution": "node", + "emitDecoratorMetadata": true, + "sourceMap": true, + "declaration": true, + "noImplicitThis": true, + "alwaysStrict": true, + "noImplicitReturns": true, + "noUnusedLocals": false, + "resolveJsonModule": true, + "skipLibCheck": true, + "paths": { + "@kitql/graphql-codegen": ["packages/graphql-codegen/src/index"], + "@kitql/module-codegen": ["packages/module-codegen/src/index"], + "@kitql/helper": ["packages/helper/src/index"], + "@kitql/client": ["packages/client/src/lib/toExport"], + "@kitql/all-in": ["packages/all-in/src/lib"], + "$lib/graphql/_kitql/graphqlTypes": ["packages/client/src/lib/graphql/_kitql/graphqlTypes"] + } + }, + "include": ["packages"], + "exclude": ["**/tests/test-files", "**/tests/test-documents", "**/dist", "**/temp"] } diff --git a/vite.config.ts b/vite.config.ts index 6457619e..1e72f7ba 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -2,11 +2,11 @@ import { defineConfig } from 'vite'; export default defineConfig({ - test: { - coverage: { - reporter: ['json-summary', 'html'], - exclude: ['**/node_modules/**', '**/vite.config.mjs', '**/dist/**', '**/test/**'] - }, - reporters: 'default' - } + test: { + coverage: { + reporter: ['json-summary', 'html'], + exclude: ['**/node_modules/**', '**/vite.config.mjs', '**/dist/**', '**/test/**'], + }, + reporters: 'default', + }, }); diff --git a/website/docs/README.mdx b/website/docs/README.mdx index 32606cae..6194fba1 100644 --- a/website/docs/README.mdx +++ b/website/docs/README.mdx @@ -23,40 +23,28 @@ Want to see more? Go and check the [demo 1](/docs/demos/01_demo-01) or [demo git - Videos explanations ๐Ÿ‘‡ - - - - - - - - - - + + + + + + + + + +
- KitQL with Svelte & GraphQL from graphql.wtf (11/04/22) - Svelte Society London (23/03/22)The native SvelteKit library for GraphQL (07/02/22)
- - Watch the video - - - - Watch the video - - - - Watch the video - -
+ KitQL with Svelte & GraphQL from graphql.wtf (11/04/22) + Svelte Society London (23/03/22)The native SvelteKit library for GraphQL (07/02/22)
+ + Watch the video + + + + Watch the video + + + + Watch the video + +
diff --git a/website/docs/all-in.mdx b/website/docs/all-in.mdx index bb9dfb46..54970907 100644 --- a/website/docs/all-in.mdx +++ b/website/docs/all-in.mdx @@ -64,25 +64,25 @@ If you want more example, check the [Demo 1](https://raw.githubusercontent.com/j In your `svelte.config.js` add a watchAndRun with the following configuration: ```js -import watchAndRun from '@kitql/vite-plugin-watch-and-run'; +import watchAndRun from '@kitql/vite-plugin-watch-and-run' /** @type {import('@sveltejs/kit').Config} */ const config = { - kit: { - vite: { - plugins: [ - watchAndRun([ - { - watch: '**/*.(gql|graphql)', - run: 'npm run gen' - } - ]) - ] - } - } -}; - -export default config; + kit: { + vite: { + plugins: [ + watchAndRun([ + { + watch: '**/*.(gql|graphql)', + run: 'npm run gen' + } + ]) + ] + } + } +} + +export default config ```

 

@@ -115,10 +115,10 @@ yarn dev # $lib/graphql/operations/AllContinents_QUERY.gql query AllContinents { - continents { - name - code - } + continents { + name + code + } } ``` @@ -129,24 +129,24 @@ query AllContinents { ```html
    - {#each $KQL_AllContinents.data?.continents as continent} -
  • -

    {continent?.name}

    -
  • - {/each} + {#each $KQL_AllContinents.data?.continents as continent} +
  • +

    {continent?.name}

    +
  • + {/each}
``` diff --git a/website/docs/demos/01_demo-01.mdx b/website/docs/demos/01_demo-01.mdx index 678a1b11..464d5813 100644 --- a/website/docs/demos/01_demo-01.mdx +++ b/website/docs/demos/01_demo-01.mdx @@ -35,8 +35,8 @@ yarn dev ## Launch in Stackblitz - Open in StackBlitz + Open in StackBlitz diff --git a/website/docs/demos/03_demo-02.mdx b/website/docs/demos/03_demo-02.mdx index 46c36a3f..831ffa24 100644 --- a/website/docs/demos/03_demo-02.mdx +++ b/website/docs/demos/03_demo-02.mdx @@ -12,8 +12,8 @@ You what to try early usage in `KitQL`? It's here ๐Ÿ‘‡
- Open in StackBlitz + Open in StackBlitz diff --git a/website/docs/setup/02_client.mdx b/website/docs/setup/02_client.mdx index af50050b..974bb7b0 100644 --- a/website/docs/setup/02_client.mdx +++ b/website/docs/setup/02_client.mdx @@ -11,12 +11,12 @@ To use, KitQL Client, create an instance of it in file `./src/lib/graphql/kitQL.ts` ```ts -import { KitQLClient } from '@kitql/client/kitQLClient'; +import { KitQLClient } from '@kitql/client/kitQLClient' -const VITE_HOST = import.meta.env.VITE_HOST; +const VITE_HOST = import.meta.env.VITE_HOST export const kitQLClient = new KitQLClient({ - url: `${VITE_HOST}/api/graphql` -}); + url: `${VITE_HOST}/api/graphql` +}) ``` This `kitQLClient` instance will be used in your stores generated by [KitQL - graphql-codegen](https://github.com/jycouet/kitql/tree/main/packages/graphql-codegen) diff --git a/website/docs/setup/03_vite-plugin-watch-and-run.mdx b/website/docs/setup/03_vite-plugin-watch-and-run.mdx index adb45049..c3c66c7d 100644 --- a/website/docs/setup/03_vite-plugin-watch-and-run.mdx +++ b/website/docs/setup/03_vite-plugin-watch-and-run.mdx @@ -13,26 +13,26 @@ In your `svelte.config.js` add watchAndRun with the following configuration: - `run`: a command to trigger when a file change is detected (You can be very creative ๐Ÿฅณ!) ```js -import watchAndRun from '@kitql/vite-plugin-watch-and-run'; +import watchAndRun from '@kitql/vite-plugin-watch-and-run' /** @type {import('@sveltejs/kit').Config} */ const config = { - kit: { - vite: { - plugins: [ - watchAndRun([ - { - watch: '**/*.(gql|graphql)', - run: 'npm run gen' // to trigger the script "gen" of your package.json - // delay: 500, Optional parameter to delay the run command. - } - ]) - ] - } - } -}; - -export default config; + kit: { + vite: { + plugins: [ + watchAndRun([ + { + watch: '**/*.(gql|graphql)', + run: 'npm run gen' // to trigger the script "gen" of your package.json + // delay: 500, Optional parameter to delay the run command. + } + ]) + ] + } + } +} + +export default config ``` ### Side Notes diff --git a/website/docs/usages/mutations.mdx b/website/docs/usages/mutations.mdx index ebb35224..7a5b585c 100644 --- a/website/docs/usages/mutations.mdx +++ b/website/docs/usages/mutations.mdx @@ -9,10 +9,10 @@ Mutations methods are exposed in a straightforward way from the generated KitQL ```svelte ``` diff --git a/website/docs/usages/patch.mdx b/website/docs/usages/patch.mdx index e4ff98d9..619980ac 100644 --- a/website/docs/usages/patch.mdx +++ b/website/docs/usages/patch.mdx @@ -19,5 +19,5 @@ This is usefull for: - 4/ When data comes back, it will automatically update the store! ```ts -KQL_AllContinents.patch({ continents: [{ name: 'JYC Land', code: 'JYC' }] }); +KQL_AllContinents.patch({ continents: [{ name: 'JYC Land', code: 'JYC' }] }) ``` diff --git a/website/docs/usages/queries.mdx b/website/docs/usages/queries.mdx index 682722e7..08dbce4b 100644 --- a/website/docs/usages/queries.mdx +++ b/website/docs/usages/queries.mdx @@ -11,10 +11,10 @@ sidebar_label: Queries ```svelte @@ -29,12 +29,12 @@ If you do this in the route, you will have the data in `SSR` mode out of the box ```svelte @@ -70,8 +70,8 @@ To have this working well, you should add globally (in `__layout.svelte`) the fo ```svelte ``` @@ -89,7 +89,7 @@ To have this working well, you should add globally (in `__layout.svelte`) the fo To be used like ๐Ÿ‘‡ ```ts -await KQL_AllContinents.query({ settings: { policy: 'cache-and-network' } }); +await KQL_AllContinents.query({ settings: { policy: 'cache-and-network' } }) ```

 

@@ -99,11 +99,11 @@ await KQL_AllContinents.query({ settings: { policy: 'cache-and-network' } }); You can do it query by query like ๐Ÿ‘‡ ```ts -KQL_AllContinents.resetCache(); +KQL_AllContinents.resetCache() ``` Or everything in one cmd ๐Ÿ‘‡ ```ts -KQL__ResetAllCaches; +KQL__ResetAllCaches ``` diff --git a/website/docs/usages/tips.mdx b/website/docs/usages/tips.mdx index af4dbc3e..e1203024 100644 --- a/website/docs/usages/tips.mdx +++ b/website/docs/usages/tips.mdx @@ -11,7 +11,7 @@ Everywhere, you can use: ```svelte @@ -24,29 +24,29 @@ Everywhere, you can use: ## Headers -In your `kitqlClient.ts` you shoud create your own `AppHeaders` type, and use it when creating your `new KitQLClient`. +In your `kitqlClient.ts` you should create your own `AppHeaders` type, and use it when creating your `new KitQLClient`. ```ts -import { KitQLClient } from '@kitql/client'; +import { KitQLClient } from '@kitql/client' //cool stuff to have it typed ๐ŸคŸ export type AppHeaders = { - Authorization?: `Bearer ${string}`; -}; + Authorization?: `Bearer ${string}` +} export const kitQLClient = new KitQLClient({ - url: `https://countries.trevorblades.com/graphql` -}); + url: `https://countries.trevorblades.com/graphql` +}) ``` Then you can ```ts // Get -kitQLClient.getHeaders(); +kitQLClient.getHeaders() // Set -kitQLClient.setHeaders({ Authorization: 'Bearer MY_TOKEN' }); +kitQLClient.setHeaders({ Authorization: 'Bearer MY_TOKEN' }) ``` ## Credential @@ -57,7 +57,7 @@ More info there: https://developer.mozilla.org/en-US/docs/Web/API/Request/creden ```ts export const kitQLClient = new KitQLClient({ - url: `https://countries.trevorblades.com/graphql`, - credentials: 'omit' // | 'same-origin' | 'include' -}); + url: `https://countries.trevorblades.com/graphql`, + credentials: 'omit' // | 'same-origin' | 'include' +}) ``` diff --git a/website/next-i18next.config.js b/website/next-i18next.config.js index 6a3b28ff..fe5519f5 100644 --- a/website/next-i18next.config.js +++ b/website/next-i18next.config.js @@ -1,4 +1,4 @@ exports.i18n = { defaultLocale: 'en', locales: ['en'], -} +}; diff --git a/website/next-sitemap.js b/website/next-sitemap.js index 13c58f87..51def253 100644 --- a/website/next-sitemap.js +++ b/website/next-sitemap.js @@ -1,5 +1,5 @@ /** @type {import('next-sitemap').IConfig} */ module.exports = { - siteUrl: process.env.SITE_URL || 'https://kitql.dev' + siteUrl: process.env.SITE_URL || 'https://kitql.dev', }; diff --git a/website/next.config.mjs b/website/next.config.mjs index 683d2472..cda12523 100644 --- a/website/next.config.mjs +++ b/website/next.config.mjs @@ -11,14 +11,14 @@ const require = createRequire(import.meta.url); const { getRoutes } = require('./routes.ts'); const withBundleAnalyzer = nextBundleAnalyzer({ - enabled: process.env.ANALYZE === 'true' + enabled: process.env.ANALYZE === 'true', }); export default withBundleAnalyzer( - withGuildDocs({ - i18n, - getRoutes, - redirects: () => { - return []; - } - }) + withGuildDocs({ + i18n, + getRoutes, + redirects: () => { + return []; + }, + }) ); diff --git a/website/package.json b/website/package.json index 73bd95e4..a02f947b 100644 --- a/website/package.json +++ b/website/package.json @@ -1,60 +1,60 @@ { - "name": "website", - "version": "0.0.0", - "license": "MIT", - "private": true, - "scripts": { - "build": "next build", - "algolia-sync": "node scripts/algolia-ci.mjs", - "postbuild": "npx next-sitemap && node scripts/sitemap-ci.mjs", - "dev": "concurrently -r \"next-remote-watch ./docs ./routes.ts ./src/pages/_app.tsx ./src/pages/_document.tsx\" \"wait-on -s 1 http://localhost:3000 && open-cli http://localhost:3000\"", - "next": "next", - "start": "next start", - "analyze": "cross-env ANALYZE=true next build", - "check": "exit 0" - }, - "devDependencies": { - "@guild-docs/algolia": "0.0.5", - "@next/bundle-analyzer": "^12.0.10", - "@types/concurrently": "^6.4.0", - "@types/mdx-js__react": "^1.5.5", - "@types/node": "^16.11.7", - "@types/react": "^17.0.39", - "@types/react-dom": "^17.0.11", - "bob-tsm": "^0.4.6", - "concurrently": "^7.0.0", - "cross-env": "^7.0.3", - "esbuild": "^0.14.21", - "esbuild-register": "^3.3.2", - "next-remote-watch": "^1.0.0", - "open-cli": "^7.0.1", - "fast-xml-parser": "^4.0.7", - "typescript": "^4.5.5", - "wait-on": "^6.0.1" - }, - "dependencies": { - "@chakra-ui/icons": "^1.1.5", - "@chakra-ui/react": "^1.8.3", - "@chakra-ui/theme-tools": "^1.3.4", - "@chakra-ui/utils": "^1.10.2", - "@emotion/react": "^11.7.1", - "@emotion/styled": "^11.6.0", - "@graphql-yoga/node": "2.6.0", - "@graphql-yoga/render-graphiql": "2.7.0", - "@guild-docs/client": "^3.0.2", - "@guild-docs/server": "^4.0.0", - "@mdx-js/react": "^2.1.1", - "@theguild/components": "1.11.8", - "framer-motion": "^6.2.6", - "graphql": "16.5.0", - "next": "^12.0.10", - "next-i18next": "^11.0.0", - "next-seo": "^5.2.0", - "next-sitemap": "^2.5.17", - "react": "17.0.2", - "react-dom": "17.0.2", - "react-icons": "^4.3.1", - "react-use": "^17.3.2", - "shiki": "^0.10.1" - } + "name": "website", + "version": "0.0.0", + "license": "MIT", + "private": true, + "scripts": { + "build": "next build", + "algolia-sync": "node scripts/algolia-ci.mjs", + "postbuild": "npx next-sitemap && node scripts/sitemap-ci.mjs", + "dev": "concurrently -r \"next-remote-watch ./docs ./routes.ts ./src/pages/_app.tsx ./src/pages/_document.tsx\" \"wait-on -s 1 http://localhost:3000 && open-cli http://localhost:3000\"", + "next": "next", + "start": "next start", + "analyze": "cross-env ANALYZE=true next build", + "check": "exit 0" + }, + "devDependencies": { + "@guild-docs/algolia": "0.0.5", + "@next/bundle-analyzer": "^12.0.10", + "@types/concurrently": "^6.4.0", + "@types/mdx-js__react": "^1.5.5", + "@types/node": "^16.11.7", + "@types/react": "^17.0.39", + "@types/react-dom": "^17.0.11", + "bob-tsm": "^0.4.6", + "concurrently": "^7.0.0", + "cross-env": "^7.0.3", + "esbuild": "^0.14.21", + "esbuild-register": "^3.3.2", + "next-remote-watch": "^1.0.0", + "open-cli": "^7.0.1", + "fast-xml-parser": "^4.0.7", + "typescript": "^4.5.5", + "wait-on": "^6.0.1" + }, + "dependencies": { + "@chakra-ui/icons": "^1.1.5", + "@chakra-ui/react": "^1.8.3", + "@chakra-ui/theme-tools": "^1.3.4", + "@chakra-ui/utils": "^1.10.2", + "@emotion/react": "^11.7.1", + "@emotion/styled": "^11.6.0", + "@graphql-yoga/node": "2.6.0", + "@graphql-yoga/render-graphiql": "2.7.0", + "@guild-docs/client": "^3.0.2", + "@guild-docs/server": "^4.0.0", + "@mdx-js/react": "^2.1.1", + "@theguild/components": "1.11.8", + "framer-motion": "^6.2.6", + "graphql": "16.5.0", + "next": "^12.0.10", + "next-i18next": "^11.0.0", + "next-seo": "^5.2.0", + "next-sitemap": "^2.5.17", + "react": "17.0.2", + "react-dom": "17.0.2", + "react-icons": "^4.3.1", + "react-use": "^17.3.2", + "shiki": "^0.10.1" + } } diff --git a/website/public/locales/en/common.json b/website/public/locales/en/common.json index a239473e..1dd64c71 100644 --- a/website/public/locales/en/common.json +++ b/website/public/locales/en/common.json @@ -1,3 +1,3 @@ { - "greeting": "Hello!" + "greeting": "Hello!" } diff --git a/website/public/style.css b/website/public/style.css index 6784f92e..5bb1bc58 100644 --- a/website/public/style.css +++ b/website/public/style.css @@ -1,22 +1,22 @@ code[class*='language-'], pre[class*='language-'] { - white-space: pre-wrap !important; - word-break: break-word !important; + white-space: pre-wrap !important; + word-break: break-word !important; } code, code * { - font-family: 'SF Mono', 'Source Code Pro', Menlo, monospace !important; + font-family: 'SF Mono', 'Source Code Pro', Menlo, monospace !important; - margin-top: 0.2em; - margin-bottom: 0.2em; + margin-top: 0.2em; + margin-bottom: 0.2em; } article { - width: 100%; - overflow-x: auto; + width: 100%; + overflow-x: auto; } #__next { - font-family: TGCFont, sans-serif; + font-family: TGCFont, sans-serif; } diff --git a/website/routes.ts b/website/routes.ts index 026120c4..857b5065 100644 --- a/website/routes.ts +++ b/website/routes.ts @@ -1,49 +1,49 @@ import { IRoutes, GenerateRoutes } from '@guild-docs/server'; export function getRoutes(): IRoutes { - const Routes: IRoutes = { - _: { - README: { - $name: 'Introduction' - }, - 'all-in': { - $name: 'Get started' - }, - usages: { - $name: 'Usages', - $routes: ['queries', 'mutations', 'patch', 'tips'] - }, - demos: { - $name: 'Demos', - $routes: ['01_demo-01', '02_demo-github-social-preview', '03_demo-02'] - }, - setup: { - $name: 'Package by package', - $routes: ['01_graphql-codegen', '02_client', '03_vite-plugin-watch-and-run'] - } - } - }; + const Routes: IRoutes = { + _: { + README: { + $name: 'Introduction', + }, + 'all-in': { + $name: 'Get started', + }, + usages: { + $name: 'Usages', + $routes: ['queries', 'mutations', 'patch', 'tips'], + }, + demos: { + $name: 'Demos', + $routes: ['01_demo-01', '02_demo-github-social-preview', '03_demo-02'], + }, + setup: { + $name: 'Package by package', + $routes: ['01_graphql-codegen', '02_client', '03_vite-plugin-watch-and-run'], + }, + }, + }; - GenerateRoutes({ - Routes, - folderPattern: 'docs' - // ignorePaths: ['setup'] - }); + GenerateRoutes({ + Routes, + folderPattern: 'docs', + // ignorePaths: ['setup'] + }); - return { - _: Object.fromEntries( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - Object.entries(Routes._).map(([key, value]) => [`docs/${key}`, value]) - ) - }; + return { + _: Object.fromEntries( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + Object.entries(Routes._).map(([key, value]) => [`docs/${key}`, value]) + ), + }; - // GenerateRoutes({ - // Routes, - // folderPattern: 'docs', - // basePath: 'docs', - // basePathLabel: 'Documentation' - // }); + // GenerateRoutes({ + // Routes, + // folderPattern: 'docs', + // basePath: 'docs', + // basePathLabel: 'Documentation' + // }); - return Routes; + return Routes; } diff --git a/website/scripts/algolia-ci.mjs b/website/scripts/algolia-ci.mjs index 07a3af47..90768c1e 100644 --- a/website/scripts/algolia-ci.mjs +++ b/website/scripts/algolia-ci.mjs @@ -12,9 +12,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url)); const { getRoutes } = require('../routes.ts'); indexToAlgolia({ - routes: [getRoutes()], - source: 'KitQL', - domain: 'https://www.kitql.dev/', - lockfilePath: resolve(__dirname, '../algolia-lockfile.json'), - dryMode: process.env.ALGOLIA_DRY_RUN === 'true' + routes: [getRoutes()], + source: 'KitQL', + domain: 'https://www.kitql.dev/', + lockfilePath: resolve(__dirname, '../algolia-lockfile.json'), + dryMode: process.env.ALGOLIA_DRY_RUN === 'true', }); diff --git a/website/scripts/sitemap-ci.mjs b/website/scripts/sitemap-ci.mjs index 36217abc..e5e7c7ef 100644 --- a/website/scripts/sitemap-ci.mjs +++ b/website/scripts/sitemap-ci.mjs @@ -1,47 +1,43 @@ -import { XMLParser } from 'fast-xml-parser' -import { fileURLToPath } from 'url' -import { dirname } from 'path' -import * as fs from 'fs' -import * as path from 'path' -import config from '../next.config.mjs' +import { XMLParser } from 'fast-xml-parser'; +import { fileURLToPath } from 'url'; +import { dirname } from 'path'; +import * as fs from 'fs'; +import * as path from 'path'; +import config from '../next.config.mjs'; -const __dirname = dirname(fileURLToPath(import.meta.url)) +const __dirname = dirname(fileURLToPath(import.meta.url)); -const sitemapPath = path.join(__dirname, '..', 'public', 'sitemap-0.xml') -const lockfilePath = path.join(__dirname, '..', 'route-lockfile.txt') +const sitemapPath = path.join(__dirname, '..', 'public', 'sitemap-0.xml'); +const lockfilePath = path.join(__dirname, '..', 'route-lockfile.txt'); async function main() { - const parser = new XMLParser() + const parser = new XMLParser(); - const d = parser.parse(fs.readFileSync(sitemapPath, 'utf-8')) + const d = parser.parse(fs.readFileSync(sitemapPath, 'utf-8')); - const routes = d.urlset.url.map((url) => - url.loc.replace(`https://graphql-yoga.com`, ``), - ) + const routes = d.urlset.url.map(url => url.loc.replace(`https://graphql-yoga.com`, ``)); - const redirectsPointingToNonExistingStuff = [] + const redirectsPointingToNonExistingStuff = []; - const redirects = config.redirects() + const redirects = config.redirects(); for (const redirect of redirects) { if (routes.includes(redirect.destination) === false) { - redirectsPointingToNonExistingStuff.push(redirect) + redirectsPointingToNonExistingStuff.push(redirect); } - routes.push(`${redirect.source} -> ${redirect.destination}`) + routes.push(`${redirect.source} -> ${redirect.destination}`); } if (redirectsPointingToNonExistingStuff.length) { console.error( `The following routes do not point to a route:\n\n` + - redirectsPointingToNonExistingStuff.map( - (redirect) => `- "${redirect.source}" -> "${redirect.destination}"`, - ) + - `\n`, - ) - throw new Error('Redirect pointing to nothing.') + redirectsPointingToNonExistingStuff.map(redirect => `- "${redirect.source}" -> "${redirect.destination}"`) + + `\n` + ); + throw new Error('Redirect pointing to nothing.'); } - fs.writeFileSync(lockfilePath, routes.sort().join(`\n`) + `\n`) + fs.writeFileSync(lockfilePath, routes.sort().join(`\n`) + `\n`); } -main() +main(); diff --git a/website/src/giscus-config.ts b/website/src/giscus-config.ts index 3992b266..18592647 100644 --- a/website/src/giscus-config.ts +++ b/website/src/giscus-config.ts @@ -1,8 +1,8 @@ -import { GiscusProps } from '@guild-docs/client/giscus' +import { GiscusProps } from '@guild-docs/client/giscus'; export const giscus: Readonly = { repo: 'dotansimha/graphql-yoga', repoId: 'MDEwOlJlcG9zaXRvcnkxMTA4MTk5Mzk=', category: 'Docs Discussion', categoryId: 'DIC_kwDOBpr6Y84CAquY', -} +}; diff --git a/website/src/google-analytics.ts b/website/src/google-analytics.ts index 565e0fff..2948cd64 100644 --- a/website/src/google-analytics.ts +++ b/website/src/google-analytics.ts @@ -1,12 +1,12 @@ -import { useEffect } from 'react' -import type { NextRouter } from 'next/router' +import { useEffect } from 'react'; +import type { NextRouter } from 'next/router'; // https://developers.google.com/analytics/devguides/collection/gtagjs/pages const pageview = (url: string, trackingId: string) => { - ;(window as any).gtag('config', trackingId, { + (window as any).gtag('config', trackingId, { page_path: url, - }) -} + }); +}; /** * @example @@ -23,22 +23,16 @@ const pageview = (url: string, trackingId: string) => { * ) * } */ -export function useGoogleAnalytics({ - trackingId, - router, -}: { - trackingId: string - router: NextRouter -}) { +export function useGoogleAnalytics({ trackingId, router }: { trackingId: string; router: NextRouter }) { useEffect(() => { const handleRouteChange = (url: string) => { - pageview(url, trackingId) - } - router.events.on('routeChangeComplete', handleRouteChange) + pageview(url, trackingId); + }; + router.events.on('routeChangeComplete', handleRouteChange); return () => { - router.events.off('routeChangeComplete', handleRouteChange) - } - }, [router.events, trackingId]) + router.events.off('routeChangeComplete', handleRouteChange); + }; + }, [router.events, trackingId]); // Why not a component? Next.js + CJS goes crazy when I use `next/router.js` and `next/script.js`. // I get: https://reactjs.org/docs/error-decoder.html/?invariant=130&args%5B%5D=object&args%5B%5D= @@ -62,5 +56,5 @@ export function useGoogleAnalytics({ `, }, }, - } + }; } diff --git a/website/src/pages/_app.tsx b/website/src/pages/_app.tsx index 6b97c42c..4e718c23 100644 --- a/website/src/pages/_app.tsx +++ b/website/src/pages/_app.tsx @@ -5,13 +5,7 @@ import Script from 'next/script'; import { Box, extendTheme, theme as chakraTheme } from '@chakra-ui/react'; import { mode } from '@chakra-ui/theme-tools'; -import { - ExtendComponents, - handlePushRoute, - CombinedThemeProvider, - DocsPage, - AppSeoProps -} from '@guild-docs/client'; +import { ExtendComponents, handlePushRoute, CombinedThemeProvider, DocsPage, AppSeoProps } from '@guild-docs/client'; import { Header, Subheader, Instruction, FooterExtended } from '@theguild/components'; import type { AppProps } from 'next/app'; @@ -23,49 +17,49 @@ import '@algolia/autocomplete-theme-classic'; import '@theguild/components/dist/static/css/SearchBarV2.css'; ExtendComponents({ - Instruction: (props: React.ComponentProps) => ( - - {props.children} - - ) + Instruction: (props: React.ComponentProps) => ( + + {props.children} + + ), }); const styles: typeof chakraTheme['styles'] = { - global: (props) => ({ - body: { - bg: mode('white', 'gray.850')(props) - } - }) + global: props => ({ + body: { + bg: mode('white', 'gray.850')(props), + }, + }), }; const accentColor = '#ff3e00'; const theme = extendTheme({ - colors: { - gray: { - 50: '#fafafa', - 100: '#f5f5f5', - 200: '#e5e5e5', - 300: '#d4d4d4', - 400: '#a3a3a3', - 500: '#737373', - 600: '#525252', - 700: '#404040', - 800: '#262626', - 850: '#1b1b1b', - 900: '#171717' - }, - accentColor - }, - fonts: { - heading: 'TGCFont, sans-serif', - body: 'TGCFont, sans-serif' - }, - config: { - initialColorMode: 'dark', - useSystemColorMode: false - }, - styles + colors: { + gray: { + 50: '#fafafa', + 100: '#f5f5f5', + 200: '#e5e5e5', + 300: '#d4d4d4', + 400: '#a3a3a3', + 500: '#737373', + 600: '#525252', + 700: '#404040', + 800: '#262626', + 850: '#1b1b1b', + 900: '#171717', + }, + accentColor, + }, + fonts: { + heading: 'TGCFont, sans-serif', + body: 'TGCFont, sans-serif', + }, + config: { + initialColorMode: 'dark', + useSystemColorMode: false, + }, + styles, }); const serializedMdx = process.env.SERIALIZED_MDX_ROUTES; @@ -74,88 +68,83 @@ const mdxRoutes = { data: serializedMdx && JSON.parse(serializedMdx) }; const serializedTutorialMdx = process.env.SERIALIZED_TUTORIAL_MDX_ROUTES; function AppContent(appProps: AppProps) { - const { Component, pageProps, router } = appProps; - const googleAnalytics = useGoogleAnalytics({ - router, - trackingId: 'G-246BWRER3C' - }); - - const isDocs = router.asPath.startsWith('/docs'); - - return ( - <> -
-