From 446ae64da0e89d44ecb81cc1162add3d296ee771 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Thu, 4 Jan 2024 14:14:29 -0500 Subject: [PATCH 01/23] WIP to have graphql setup of trusted docs --- docs/docs/cli-commands.md | 7 + .../setup/graphql/features/trusted-docs.ts | 186 ++++++++++++++++++ .../cli/src/commands/setup/graphql/graphql.js | 14 ++ 3 files changed, 207 insertions(+) create mode 100644 packages/cli/src/commands/setup/graphql/features/trusted-docs.ts create mode 100644 packages/cli/src/commands/setup/graphql/graphql.js diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index 7e85cddf3516..96cc7c0e126f 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -1999,6 +1999,13 @@ We perform a simple compatibility check in an attempt to make you aware of poten It's the author of the npm package's responsibility to specify the correct compatibility range, so **you should always research the packages you use with this command**. Especially since they will be executing code on your machine! +### setup graphql + +This command creates the necessary files to support GraphQL features like trusted documents. + +#### setup graphql trusted-docs + + ### setup realtime This command creates the necessary files, installs the required packages, and provides examples to setup RedwoodJS Realtime from GraphQL live queries and subscriptions. See the Realtime docs for more information. diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts b/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts new file mode 100644 index 000000000000..8c08d5514261 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts @@ -0,0 +1,186 @@ +import fs from 'fs' +import path from 'path' + +import { Listr } from 'listr2' +import { format } from 'prettier' +import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' + +import { + recordTelemetryAttributes, + prettierOptions, +} from '@redwoodjs/cli-helpers' +import { getConfigPath } from '@redwoodjs/project-config' + +import { getPaths } from '../../../../lib' +import c from '../../../../lib/colors' + +export const command = 'trusted-docs' +export const description = 'Set up Trusted Documents for GraphQL' + +export function builder(yargs: any) { + yargs.option('force', { + alias: 'f', + default: false, + description: 'Overwrite existing configuration', + type: 'boolean', + }) + yargs.option('install', { + alias: 'i', + default: true, + description: 'Install packages', + type: 'boolean', + }) +} +function configureGraphQLHandlerWithStore() { + return { + title: 'Configuring the GraphQL Handler to use a Trusted Documents store..', + task: async () => { + // locate "api/functions/graphql.[js|ts]" + let graphQlSourcePath: string | undefined + const functionsDir = getPaths().api.functions + if (fs.existsSync(path.join(functionsDir, 'graphql.ts'))) { + graphQlSourcePath = path.join(functionsDir, 'graphql.ts') + } else if (fs.existsSync(path.join(functionsDir, 'graphql.js'))) { + graphQlSourcePath = path.join(functionsDir, 'graphql.js') + } + + if (!graphQlSourcePath) { + console.warn( + c.warning( + `Unable to find the GraphQL Handler source file: ${path.join( + functionsDir, + 'graphql.(js|ts)' + )}` + ) + ) + return + } + + // add import + const project = new Project() + const graphQlSourceFile = + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + project.addSourceFileAtPathIfExists(graphQlSourcePath)! + let graphQlSourceFileChanged = false + let identified = false + + const imports = graphQlSourceFile.getImportDeclarations() + if ( + !imports.some( + (i) => i.getModuleSpecifierValue() === 'src/lib/trustedDocumentsStore' + ) + ) { + graphQlSourceFile.addImportDeclaration({ + moduleSpecifier: 'src/lib/trustedDocumentsStore', + namedImports: ['store'], + }) + graphQlSourceFileChanged = true + } + + // add "trustedDocuments" option to `createGraphQLHandler` call + graphQlSourceFile + .getDescendantsOfKind(SyntaxKind.CallExpression) + .forEach((expr) => { + if (identified) { + return + } + + if ( + expr.getExpression().asKind(SyntaxKind.Identifier)?.getText() === + 'createGraphQLHandler' + ) { + const arg = expr + .getArguments()[0] + ?.asKind(SyntaxKind.ObjectLiteralExpression) + if (arg) { + identified = true + const props = arg.getProperties() + const trustedDocsProp = props.find( + (p): p is PropertyAssignment => + p.asKind(SyntaxKind.PropertyAssignment)?.getName() === + 'trustedDocuments' + ) + if (!trustedDocsProp) { + arg.addPropertyAssignment({ + name: 'trustedDocuments', + initializer: '{ store }', + }) + graphQlSourceFileChanged = true + } + } + } + }) + + if (!identified) { + console.warn( + c.warning( + 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' + ) + ) + } + + if (graphQlSourceFileChanged) { + await project.save() + const updatedHandler = fs.readFileSync(graphQlSourcePath, 'utf-8') + const prettifiedHandler = format(updatedHandler, { + ...prettierOptions(), + parser: 'babel-ts', + }) + fs.writeFileSync(graphQlSourcePath, prettifiedHandler, 'utf-8') + } + }, + } +} + +export async function handler({ + force, + install, +}: { + force: boolean + install: boolean +}) { + recordTelemetryAttributes({ + command: 'setup graphql trusted-docs', + force, + install, + }) + + // const rwPaths = getPaths() + + const tasks = new Listr( + [ + { + title: 'Update graphql handler..', + skip: () => false, + task: () => console.log('handler update'), + }, + { + title: 'Update Redwood Project toml..', + skip: () => false, + task: () => { + const redwoodTomlPath = getConfigPath() + const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') + + // const config = getConfig(redwoodTomlPath) + + const tomlToAppend = `[graphql]\n trustedDocuments = true` + + console.debug('tomlToAppend', tomlToAppend) + + const newConfig = originalTomlContent + '\n' + tomlToAppend + + fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') + }, + }, + configureGraphQLHandlerWithStore(), + ], + { rendererOptions: { collapseSubtasks: false } } + ) + + try { + await tasks.run() + } catch (e: any) { + console.error(c.error(e.message)) + process.exit(e?.exitCode || 1) + } +} diff --git a/packages/cli/src/commands/setup/graphql/graphql.js b/packages/cli/src/commands/setup/graphql/graphql.js new file mode 100644 index 000000000000..7970d75793dc --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/graphql.js @@ -0,0 +1,14 @@ +import terminalLink from 'terminal-link' + +export const command = 'graphql ' +export const description = 'Set up GraphQL feature support' +export const builder = (yargs) => + yargs + .commandDir('./features') + .demandCommand() + .epilogue( + `Also see the ${terminalLink( + 'Redwood CLI Reference', + 'https://redwoodjs.com/docs/cli-commands#setup-graphql' + )}` + ) From cc647b385a99ceacc1e2121823d06c1491a9c16f Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Thu, 4 Jan 2024 14:27:28 -0500 Subject: [PATCH 02/23] cleanup command and add docs --- docs/docs/cli-commands.md | 39 ++++++++++++++++++- docs/docs/graphql/trusted-documents.md | 5 +++ .../setup/graphql/features/trusted-docs.ts | 31 ++++++--------- 3 files changed, 55 insertions(+), 20 deletions(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index 96cc7c0e126f..9fa745306741 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2003,14 +2003,51 @@ It's the author of the npm package's responsibility to specify the correct compa This command creates the necessary files to support GraphQL features like trusted documents. +#### Usage + +Run `yarn rw setup graphql ` + + #### setup graphql trusted-docs +This command creates the necessary configuratiion to start using [GraphQL Trusted Documents](./graphql/trusted-documents.md). + + +``` +yarn redwood setup graphql trusted-documents +``` + +| Arguments & Options | Description | +| :------------------ | :----------------------- | +| `--force, -f` | Forgo compatibility checks | + +#### Usage + +Run `yarn rw graphql trusted-documents` + +#### Example + +```bash +~/redwood-app$ yarn rw graphql trusted-documents +✔ Update Redwood Project Configuration to enable GraphQL Trusted Documents ... +✔ Generating Trusted Documents store ... +✔ Configuring the GraphQL Handler to use a Trusted Documents store ... +``` + + +If you have not setup the RedwoodJS server file, it will be setup: + +```bash +✔ Adding the experimental server file... +✔ Adding config to redwood.toml... +✔ Adding required api packages... +``` + ### setup realtime This command creates the necessary files, installs the required packages, and provides examples to setup RedwoodJS Realtime from GraphQL live queries and subscriptions. See the Realtime docs for more information. - ``` yarn redwood setup realtime ``` diff --git a/docs/docs/graphql/trusted-documents.md b/docs/docs/graphql/trusted-documents.md index 9b67a7f0e02e..c55159232bf2 100644 --- a/docs/docs/graphql/trusted-documents.md +++ b/docs/docs/graphql/trusted-documents.md @@ -93,6 +93,11 @@ Thus preventing unwanted queries or GraphQl traversal attacks, ## Configure Trusted Documents +Below are instructions to manually configure Trusted Documents in your redwoodJS project. + +Alternatively, you can use the `yarn redwood setup graphql trusted-documents` [CLI setup command](../cli-commands.md#setup-graphql-trusted-docs). + + ### Configure redwood.toml Setting `trustedDocuments` to true will diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts b/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts index 8c08d5514261..15b488ca4eab 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts @@ -1,6 +1,7 @@ import fs from 'fs' import path from 'path' +import execa from 'execa' import { Listr } from 'listr2' import { format } from 'prettier' import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' @@ -24,16 +25,12 @@ export function builder(yargs: any) { description: 'Overwrite existing configuration', type: 'boolean', }) - yargs.option('install', { - alias: 'i', - default: true, - description: 'Install packages', - type: 'boolean', - }) } + function configureGraphQLHandlerWithStore() { return { - title: 'Configuring the GraphQL Handler to use a Trusted Documents store..', + title: + 'Configuring the GraphQL Handler to use a Trusted Documents store ...', task: async () => { // locate "api/functions/graphql.[js|ts]" let graphQlSourcePath: string | undefined @@ -145,33 +142,29 @@ export async function handler({ install, }) - // const rwPaths = getPaths() - const tasks = new Listr( [ { - title: 'Update graphql handler..', - skip: () => false, - task: () => console.log('handler update'), - }, - { - title: 'Update Redwood Project toml..', + title: + 'Update Redwood Project Configuration to enable GraphQL Trusted Documents ...', skip: () => false, task: () => { const redwoodTomlPath = getConfigPath() const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') - // const config = getConfig(redwoodTomlPath) - const tomlToAppend = `[graphql]\n trustedDocuments = true` - console.debug('tomlToAppend', tomlToAppend) - const newConfig = originalTomlContent + '\n' + tomlToAppend fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') }, }, + { + title: 'Generating Trusted Documents store ...', + task: () => { + execa.commandSync('yarn redwood generate types', { stdio: 'ignore' }) + }, + }, configureGraphQLHandlerWithStore(), ], { rendererOptions: { collapseSubtasks: false } } From 608b5d465f1a23b1f3689f5ea7ac770d7a46ae92 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 12:06:33 -0500 Subject: [PATCH 03/23] Update docs/docs/cli-commands.md Co-authored-by: Tobbe Lundberg --- docs/docs/cli-commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index 9fa745306741..7435bba7b67e 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2010,7 +2010,7 @@ Run `yarn rw setup graphql ` #### setup graphql trusted-docs -This command creates the necessary configuratiion to start using [GraphQL Trusted Documents](./graphql/trusted-documents.md). +This command creates the necessary configuration to start using [GraphQL Trusted Documents](./graphql/trusted-documents.md). ``` From 9cd43eb42105ca50eef62bc53024a56caa151599 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 12:06:41 -0500 Subject: [PATCH 04/23] Update docs/docs/cli-commands.md Co-authored-by: Tobbe Lundberg --- docs/docs/cli-commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index 7435bba7b67e..fadb0a532a3e 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2023,7 +2023,7 @@ yarn redwood setup graphql trusted-documents #### Usage -Run `yarn rw graphql trusted-documents` +Run `yarn rw setup graphql trusted-documents` #### Example From bc275696c793f1c275c1403d1d97d4ad780be469 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 12:06:49 -0500 Subject: [PATCH 05/23] Update docs/docs/cli-commands.md Co-authored-by: Tobbe Lundberg --- docs/docs/cli-commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index fadb0a532a3e..cce168832e56 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2028,7 +2028,7 @@ Run `yarn rw setup graphql trusted-documents` #### Example ```bash -~/redwood-app$ yarn rw graphql trusted-documents +~/redwood-app$ yarn rw setup graphql trusted-documents ✔ Update Redwood Project Configuration to enable GraphQL Trusted Documents ... ✔ Generating Trusted Documents store ... ✔ Configuring the GraphQL Handler to use a Trusted Documents store ... From a68de95e4fadcb1f369931935a4017c3665026c6 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 12:06:56 -0500 Subject: [PATCH 06/23] Update docs/docs/graphql/trusted-documents.md Co-authored-by: Tobbe Lundberg --- docs/docs/graphql/trusted-documents.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs/graphql/trusted-documents.md b/docs/docs/graphql/trusted-documents.md index c55159232bf2..a8f1aaf98881 100644 --- a/docs/docs/graphql/trusted-documents.md +++ b/docs/docs/graphql/trusted-documents.md @@ -93,7 +93,7 @@ Thus preventing unwanted queries or GraphQl traversal attacks, ## Configure Trusted Documents -Below are instructions to manually configure Trusted Documents in your redwoodJS project. +Below are instructions to manually configure Trusted Documents in your RedwoodJS project. Alternatively, you can use the `yarn redwood setup graphql trusted-documents` [CLI setup command](../cli-commands.md#setup-graphql-trusted-docs). From 75773d6e9d71aaa0828f55a78116c716f5f403b6 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 12:58:33 -0500 Subject: [PATCH 07/23] Refactor to improve toml setup --- packages/cli-helpers/src/lib/index.ts | 15 ++++ .../{trusted-docs.ts => trusted-documents.ts} | 84 ++++++++++++++----- 2 files changed, 80 insertions(+), 19 deletions(-) rename packages/cli/src/commands/setup/graphql/features/{trusted-docs.ts => trusted-documents.ts} (62%) diff --git a/packages/cli-helpers/src/lib/index.ts b/packages/cli-helpers/src/lib/index.ts index 30861f18062c..90e5f8c6e2eb 100644 --- a/packages/cli-helpers/src/lib/index.ts +++ b/packages/cli-helpers/src/lib/index.ts @@ -60,6 +60,21 @@ export const prettierOptions = () => { } } +export const prettifyFile = (filename: string, parser: string | undefined) => { + try { + const file = fs.readFileSync(filename, 'utf-8') + const prettifiedFile = format(file, { + ...prettierOptions(), + parser: parser || 'babel-ts', + }) + fs.writeFileSync(filename, prettifiedFile, 'utf-8') + } catch (e) { + const message = `Could not prettify ${filename}` + console.error(colors.error(message)) + throw Error(message) + } +} + export const prettify = ( templateFilename: string, renderedTemplate: string diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts similarity index 62% rename from packages/cli/src/commands/setup/graphql/features/trusted-docs.ts rename to packages/cli/src/commands/setup/graphql/features/trusted-documents.ts index 15b488ca4eab..330c515b3601 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-docs.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts @@ -3,19 +3,15 @@ import path from 'path' import execa from 'execa' import { Listr } from 'listr2' -import { format } from 'prettier' import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' -import { - recordTelemetryAttributes, - prettierOptions, -} from '@redwoodjs/cli-helpers' +import { recordTelemetryAttributes, prettifyFile } from '@redwoodjs/cli-helpers' import { getConfigPath } from '@redwoodjs/project-config' import { getPaths } from '../../../../lib' import c from '../../../../lib/colors' -export const command = 'trusted-docs' +export const command = 'trusted-documents' export const description = 'Set up Trusted Documents for GraphQL' export function builder(yargs: any) { @@ -43,7 +39,7 @@ function configureGraphQLHandlerWithStore() { if (!graphQlSourcePath) { console.warn( - c.warning( + c.yellow( `Unable to find the GraphQL Handler source file: ${path.join( functionsDir, 'graphql.(js|ts)' @@ -56,8 +52,20 @@ function configureGraphQLHandlerWithStore() { // add import const project = new Project() const graphQlSourceFile = - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - project.addSourceFileAtPathIfExists(graphQlSourcePath)! + project.addSourceFileAtPathIfExists(graphQlSourcePath) + + if (!graphQlSourceFile) { + console.error( + c.error( + `Unable to determine the GraphQL Handler source path for: ${path.join( + functionsDir, + 'graphql.(js|ts)' + )}` + ) + ) + return + } + let graphQlSourceFileChanged = false let identified = false @@ -118,12 +126,7 @@ function configureGraphQLHandlerWithStore() { if (graphQlSourceFileChanged) { await project.save() - const updatedHandler = fs.readFileSync(graphQlSourcePath, 'utf-8') - const prettifiedHandler = format(updatedHandler, { - ...prettierOptions(), - parser: 'babel-ts', - }) - fs.writeFileSync(graphQlSourcePath, prettifiedHandler, 'utf-8') + prettifyFile(graphQlSourcePath, 'babel-ts') } }, } @@ -137,7 +140,7 @@ export async function handler({ install: boolean }) { recordTelemetryAttributes({ - command: 'setup graphql trusted-docs', + command: 'setup graphql trusted-documents', force, install, }) @@ -151,12 +154,55 @@ export async function handler({ task: () => { const redwoodTomlPath = getConfigPath() const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') + let newConfig = undefined + + const graphqlExists = originalTomlContent.includes('[graphql]') - const tomlToAppend = `[graphql]\n trustedDocuments = true` + const trustedDocumentsExists = + originalTomlContent.includes('trustedDocuments =') || + originalTomlContent.includes('trustedDocuments=') - const newConfig = originalTomlContent + '\n' + tomlToAppend + const fragmentsExists = + originalTomlContent.includes('fragments =') || + originalTomlContent.includes('fragments=') - fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') + if (trustedDocumentsExists) { + console.info( + c.white( + 'GraphQL Trusted Documents are already enabled in your Redwood project.' + ) + ) + } else if (graphqlExists && fragmentsExists) { + const insertIndex = originalTomlContent.indexOf('fragments') + const trustedDocuments = 'trustedDocuments = true\n ' + newConfig = + originalTomlContent.slice(0, insertIndex) + + trustedDocuments + + originalTomlContent.slice(insertIndex) + } else { + if (!graphqlExists) { + const tomlToAppend = `[graphql]\n trustedDocuments = true` + + newConfig = originalTomlContent + '\n' + tomlToAppend + } else { + const graphqlIndex = originalTomlContent.indexOf('[graphql]') + const insertIndex = graphqlIndex + '[graphql]\n'.length + newConfig = + originalTomlContent.slice(0, insertIndex) + + ' trustedDocuments = true\n' + + originalTomlContent.slice(insertIndex) + } + } + + if (newConfig && (force || !trustedDocumentsExists)) { + fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') + } else { + console.warn( + c.yellow( + 'Unable to update Redwood Project Configuration to enable GraphQL Trusted Documents. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-redwood-project-configuration' + ) + ) + } }, }, { From 8f1551355cf624de340bfe18603780f1d488336b Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 13:20:37 -0500 Subject: [PATCH 08/23] removed commandDir --- docs/docs/cli-commands.md | 2 +- .../graphql/features/trusted-documents.ts | 39 ++++++------------- .../cli/src/commands/setup/graphql/graphql.js | 4 +- 3 files changed, 14 insertions(+), 31 deletions(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index cce168832e56..b64db0961315 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2019,7 +2019,7 @@ yarn redwood setup graphql trusted-documents | Arguments & Options | Description | | :------------------ | :----------------------- | -| `--force, -f` | Forgo compatibility checks | +| `--force, -f` | Force overwrite files | #### Usage diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts index 330c515b3601..d98a3c615c2b 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts @@ -9,7 +9,6 @@ import { recordTelemetryAttributes, prettifyFile } from '@redwoodjs/cli-helpers' import { getConfigPath } from '@redwoodjs/project-config' import { getPaths } from '../../../../lib' -import c from '../../../../lib/colors' export const command = 'trusted-documents' export const description = 'Set up Trusted Documents for GraphQL' @@ -39,12 +38,10 @@ function configureGraphQLHandlerWithStore() { if (!graphQlSourcePath) { console.warn( - c.yellow( - `Unable to find the GraphQL Handler source file: ${path.join( - functionsDir, - 'graphql.(js|ts)' - )}` - ) + `Unable to find the GraphQL Handler source file: ${path.join( + functionsDir, + 'graphql.(js|ts)' + )}` ) return } @@ -56,12 +53,10 @@ function configureGraphQLHandlerWithStore() { if (!graphQlSourceFile) { console.error( - c.error( - `Unable to determine the GraphQL Handler source path for: ${path.join( - functionsDir, - 'graphql.(js|ts)' - )}` - ) + `Unable to determine the GraphQL Handler source path for: ${path.join( + functionsDir, + 'graphql.(js|ts)' + )}` ) return } @@ -118,9 +113,7 @@ function configureGraphQLHandlerWithStore() { if (!identified) { console.warn( - c.warning( - 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' - ) + 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' ) } @@ -150,7 +143,6 @@ export async function handler({ { title: 'Update Redwood Project Configuration to enable GraphQL Trusted Documents ...', - skip: () => false, task: () => { const redwoodTomlPath = getConfigPath() const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') @@ -168,9 +160,7 @@ export async function handler({ if (trustedDocumentsExists) { console.info( - c.white( - 'GraphQL Trusted Documents are already enabled in your Redwood project.' - ) + 'GraphQL Trusted Documents are already enabled in your Redwood project.' ) } else if (graphqlExists && fragmentsExists) { const insertIndex = originalTomlContent.indexOf('fragments') @@ -193,15 +183,8 @@ export async function handler({ originalTomlContent.slice(insertIndex) } } - if (newConfig && (force || !trustedDocumentsExists)) { fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') - } else { - console.warn( - c.yellow( - 'Unable to update Redwood Project Configuration to enable GraphQL Trusted Documents. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-redwood-project-configuration' - ) - ) } }, }, @@ -219,7 +202,7 @@ export async function handler({ try { await tasks.run() } catch (e: any) { - console.error(c.error(e.message)) + console.error(e.message) process.exit(e?.exitCode || 1) } } diff --git a/packages/cli/src/commands/setup/graphql/graphql.js b/packages/cli/src/commands/setup/graphql/graphql.js index 7970d75793dc..dd2aa93b016f 100644 --- a/packages/cli/src/commands/setup/graphql/graphql.js +++ b/packages/cli/src/commands/setup/graphql/graphql.js @@ -1,11 +1,11 @@ import terminalLink from 'terminal-link' +import * as trustedDocumentsCommand from './features/trusted-documents' export const command = 'graphql ' export const description = 'Set up GraphQL feature support' export const builder = (yargs) => yargs - .commandDir('./features') - .demandCommand() + .command(trustedDocumentsCommand) .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', From 717be40b1f28df014dac2f221adaae0ac66cb9ad Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Mon, 8 Jan 2024 13:23:15 -0500 Subject: [PATCH 09/23] removed force option --- docs/docs/cli-commands.md | 4 ---- .../commands/setup/graphql/features/trusted-documents.ts | 9 +-------- 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/docs/docs/cli-commands.md b/docs/docs/cli-commands.md index b64db0961315..160e9debedb5 100644 --- a/docs/docs/cli-commands.md +++ b/docs/docs/cli-commands.md @@ -2017,10 +2017,6 @@ This command creates the necessary configuration to start using [GraphQL Trusted yarn redwood setup graphql trusted-documents ``` -| Arguments & Options | Description | -| :------------------ | :----------------------- | -| `--force, -f` | Force overwrite files | - #### Usage Run `yarn rw setup graphql trusted-documents` diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts index d98a3c615c2b..c9a9368fac94 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts @@ -13,14 +13,7 @@ import { getPaths } from '../../../../lib' export const command = 'trusted-documents' export const description = 'Set up Trusted Documents for GraphQL' -export function builder(yargs: any) { - yargs.option('force', { - alias: 'f', - default: false, - description: 'Overwrite existing configuration', - type: 'boolean', - }) -} +export function builder() {} function configureGraphQLHandlerWithStore() { return { From d9eeed354c4d0ac3e27467f50aa87d1ee89e63f8 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Tue, 9 Jan 2024 11:32:09 -0500 Subject: [PATCH 10/23] Adds tests for trusted document toml updates --- .../setup/graphql/__fixtures__/default.toml | 21 ++ .../setup/graphql/__fixtures__/fragments.toml | 23 ++ .../fragments_no_space_equals.toml | 23 ++ .../trusted_docs_already_setup.toml | 24 ++ ...ed_docs_already_setup_no_space_equals.toml | 23 ++ ...sted_docs_and_fragments_already_setup.toml | 24 ++ .../trusted-documents.test.js.snap | 114 +++++++++ .../__tests__/trusted-documents.test.js | 79 ++++++ .../graphql/features/trusted-documents.ts | 232 ++++++++++-------- 9 files changed, 455 insertions(+), 108 deletions(-) create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/default.toml create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml create mode 100644 packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap create mode 100644 packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/default.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/default.toml new file mode 100644 index 000000000000..5ec850926377 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/default.toml @@ -0,0 +1,21 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml new file mode 100644 index 000000000000..5fb1d209abb0 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml @@ -0,0 +1,23 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[graphql] + fragments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml new file mode 100644 index 000000000000..149af9b99d53 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml @@ -0,0 +1,23 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[graphql] + fragments=true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml new file mode 100644 index 000000000000..6d0fa706cd91 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml @@ -0,0 +1,24 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[graphql] + trustedDocuments = true + fragments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml new file mode 100644 index 000000000000..b07dfb46c621 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml @@ -0,0 +1,23 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[graphql] + trustedDocuments=true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml new file mode 100644 index 000000000000..6d0fa706cd91 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml @@ -0,0 +1,24 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +[graphql] + trustedDocuments = true + fragments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap b/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap new file mode 100644 index 000000000000..9485cec96ba2 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap @@ -0,0 +1,114 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql fragments are already setup updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` +{ + "newConfig": "# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run \`yarn rw dev\`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "\${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "\${API_DEV_PORT:8911}" +[graphql] + trustedDocuments = true + fragments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] +", + "trustedDocumentsExists": false, +} +`; + +exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql fragments are already setup using no spaces updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` +{ + "newConfig": "# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run \`yarn rw dev\`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "\${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "\${API_DEV_PORT:8911}" +[graphql] + trustedDocuments = true + fragments=true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] +", + "trustedDocumentsExists": false, +} +`; + +exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents and fragments are already setup makes no changes as trusted documents are already setup 1`] = ` +{ + "newConfig": undefined, + "trustedDocumentsExists": true, +} +`; + +exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents are already setup makes no changes as trusted documents are already setup 1`] = ` +{ + "newConfig": undefined, + "trustedDocumentsExists": true, +} +`; + +exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents are already setup using no spaces makes no changes as trusted documents are already setup 1`] = ` +{ + "newConfig": undefined, + "trustedDocumentsExists": true, +} +`; + +exports[`Trusted documents setup tests Project toml configuration updates default toml where no graphql or trusted documents is setup updates the toml file with graphql and trusted documents enabled 1`] = ` +{ + "newConfig": "# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run \`yarn rw dev\`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "\${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "\${API_DEV_PORT:8911}" +[browser] + open = true +[notifications] + versionUpdates = ["latest"] + +[graphql] + trustedDocuments = true", + "trustedDocumentsExists": false, +} +`; diff --git a/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js b/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js new file mode 100644 index 000000000000..dbf3cd407c8b --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js @@ -0,0 +1,79 @@ +import path from 'path' + +import { updateRedwoodToml } from '../features/trusted-documents' +describe('Trusted documents setup tests', () => { + describe('Project toml configuration updates', () => { + describe('default toml where no graphql or trusted documents is setup', () => { + it('updates the toml file with graphql and trusted documents enabled', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'default.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + describe('default toml where graphql fragments are already setup', () => { + it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'fragments.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + describe('default toml where graphql fragments are already setup using no spaces', () => { + it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'fragments_no_space_equals.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + describe('default toml where graphql trusted documents are already setup', () => { + it('makes no changes as trusted documents are already setup', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'trusted_docs_already_setup.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + describe('default toml where graphql trusted documents are already setup using no spaces', () => { + it('makes no changes as trusted documents are already setup', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'trusted_docs_already_setup_no_space_equals.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + describe('default toml where graphql trusted documents and fragments are already setup', () => { + it('makes no changes as trusted documents are already setup', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'trusted_docs_and_fragments_already_setup.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) + }) +}) diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts index c9a9368fac94..b5c8f1de0a95 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts @@ -15,6 +15,124 @@ export const description = 'Set up Trusted Documents for GraphQL' export function builder() {} +export function updateGraphQLHandler(graphQlSourcePath: string) { + // add import + const project = new Project() + const graphQlSourceFile = + project.addSourceFileAtPathIfExists(graphQlSourcePath) + + if (!graphQlSourceFile) { + console.error( + `Unable to determine the GraphQL Handler source path for: ${path.join( + functionsDir, + 'graphql.(js|ts)' + )}` + ) + return + } + + let graphQlSourceFileChanged = false + let identified = false + + const imports = graphQlSourceFile.getImportDeclarations() + if ( + !imports.some( + (i) => i.getModuleSpecifierValue() === 'src/lib/trustedDocumentsStore' + ) + ) { + graphQlSourceFile.addImportDeclaration({ + moduleSpecifier: 'src/lib/trustedDocumentsStore', + namedImports: ['store'], + }) + graphQlSourceFileChanged = true + } + + // add "trustedDocuments" option to `createGraphQLHandler` call + graphQlSourceFile + .getDescendantsOfKind(SyntaxKind.CallExpression) + .forEach((expr) => { + if (identified) { + return + } + + if ( + expr.getExpression().asKind(SyntaxKind.Identifier)?.getText() === + 'createGraphQLHandler' + ) { + const arg = expr + .getArguments()[0] + ?.asKind(SyntaxKind.ObjectLiteralExpression) + if (arg) { + identified = true + const props = arg.getProperties() + const trustedDocsProp = props.find( + (p): p is PropertyAssignment => + p.asKind(SyntaxKind.PropertyAssignment)?.getName() === + 'trustedDocuments' + ) + if (!trustedDocsProp) { + arg.addPropertyAssignment({ + name: 'trustedDocuments', + initializer: '{ store }', + }) + graphQlSourceFileChanged = true + } + } + } + }) + + if (!identified) { + console.warn( + 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' + ) + } + + return { graphQlSourceFileChanged, project } +} + +export function updateRedwoodToml(redwoodTomlPath: string) { + let newConfig = undefined + + const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') + const graphqlExists = originalTomlContent.includes('[graphql]') + + const trustedDocumentsExists = + originalTomlContent.includes('trustedDocuments =') || + originalTomlContent.includes('trustedDocuments=') + + const fragmentsExists = + originalTomlContent.includes('fragments =') || + originalTomlContent.includes('fragments=') + + if (trustedDocumentsExists) { + console.info( + 'GraphQL Trusted Documents are already enabled in your Redwood project.' + ) + } else if (graphqlExists && fragmentsExists) { + const insertIndex = originalTomlContent.indexOf('fragments') + const trustedDocuments = 'trustedDocuments = true\n ' + newConfig = + originalTomlContent.slice(0, insertIndex) + + trustedDocuments + + originalTomlContent.slice(insertIndex) + } else { + if (!graphqlExists) { + const tomlToAppend = `[graphql]\n trustedDocuments = true` + + newConfig = originalTomlContent + '\n' + tomlToAppend + } else { + const graphqlIndex = originalTomlContent.indexOf('[graphql]') + const insertIndex = graphqlIndex + '[graphql]\n'.length + newConfig = + originalTomlContent.slice(0, insertIndex) + + ' trustedDocuments = true\n' + + originalTomlContent.slice(insertIndex) + } + } + + return { newConfig, trustedDocumentsExists } +} + function configureGraphQLHandlerWithStore() { return { title: @@ -39,76 +157,8 @@ function configureGraphQLHandlerWithStore() { return } - // add import - const project = new Project() - const graphQlSourceFile = - project.addSourceFileAtPathIfExists(graphQlSourcePath) - - if (!graphQlSourceFile) { - console.error( - `Unable to determine the GraphQL Handler source path for: ${path.join( - functionsDir, - 'graphql.(js|ts)' - )}` - ) - return - } - - let graphQlSourceFileChanged = false - let identified = false - - const imports = graphQlSourceFile.getImportDeclarations() - if ( - !imports.some( - (i) => i.getModuleSpecifierValue() === 'src/lib/trustedDocumentsStore' - ) - ) { - graphQlSourceFile.addImportDeclaration({ - moduleSpecifier: 'src/lib/trustedDocumentsStore', - namedImports: ['store'], - }) - graphQlSourceFileChanged = true - } - - // add "trustedDocuments" option to `createGraphQLHandler` call - graphQlSourceFile - .getDescendantsOfKind(SyntaxKind.CallExpression) - .forEach((expr) => { - if (identified) { - return - } - - if ( - expr.getExpression().asKind(SyntaxKind.Identifier)?.getText() === - 'createGraphQLHandler' - ) { - const arg = expr - .getArguments()[0] - ?.asKind(SyntaxKind.ObjectLiteralExpression) - if (arg) { - identified = true - const props = arg.getProperties() - const trustedDocsProp = props.find( - (p): p is PropertyAssignment => - p.asKind(SyntaxKind.PropertyAssignment)?.getName() === - 'trustedDocuments' - ) - if (!trustedDocsProp) { - arg.addPropertyAssignment({ - name: 'trustedDocuments', - initializer: '{ store }', - }) - graphQlSourceFileChanged = true - } - } - } - }) - - if (!identified) { - console.warn( - 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' - ) - } + const { project, graphQlSourceFileChanged } = + updateGraphQLHandler(graphQlSourcePath) if (graphQlSourceFileChanged) { await project.save() @@ -138,44 +188,10 @@ export async function handler({ 'Update Redwood Project Configuration to enable GraphQL Trusted Documents ...', task: () => { const redwoodTomlPath = getConfigPath() - const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') - let newConfig = undefined - - const graphqlExists = originalTomlContent.includes('[graphql]') - - const trustedDocumentsExists = - originalTomlContent.includes('trustedDocuments =') || - originalTomlContent.includes('trustedDocuments=') - - const fragmentsExists = - originalTomlContent.includes('fragments =') || - originalTomlContent.includes('fragments=') - - if (trustedDocumentsExists) { - console.info( - 'GraphQL Trusted Documents are already enabled in your Redwood project.' - ) - } else if (graphqlExists && fragmentsExists) { - const insertIndex = originalTomlContent.indexOf('fragments') - const trustedDocuments = 'trustedDocuments = true\n ' - newConfig = - originalTomlContent.slice(0, insertIndex) + - trustedDocuments + - originalTomlContent.slice(insertIndex) - } else { - if (!graphqlExists) { - const tomlToAppend = `[graphql]\n trustedDocuments = true` - - newConfig = originalTomlContent + '\n' + tomlToAppend - } else { - const graphqlIndex = originalTomlContent.indexOf('[graphql]') - const insertIndex = graphqlIndex + '[graphql]\n'.length - newConfig = - originalTomlContent.slice(0, insertIndex) + - ' trustedDocuments = true\n' + - originalTomlContent.slice(insertIndex) - } - } + + const { newConfig, trustedDocumentsExists } = + updateRedwoodToml(redwoodTomlPath) + if (newConfig && (force || !trustedDocumentsExists)) { fs.writeFileSync(redwoodTomlPath, newConfig, 'utf-8') } From 167704901a88d2712529b9edaea882735bb7c123 Mon Sep 17 00:00:00 2001 From: David Thyresson Date: Tue, 9 Jan 2024 12:11:41 -0500 Subject: [PATCH 11/23] Tests for graphql handler store updates --- .../graphQLHandler/defaultHandler.js | 25 +++++++++++++++ .../trustedDocumentSetupHandler.js | 27 ++++++++++++++++ .../__fixtures__/{ => toml}/default.toml | 0 .../__fixtures__/{ => toml}/fragments.toml | 0 .../{ => toml}/fragments_no_space_equals.toml | 0 .../trusted_docs_already_setup.toml | 0 ...ed_docs_already_setup_no_space_equals.toml | 0 ...sted_docs_and_fragments_already_setup.toml | 0 .../trusted-documents.test.js.snap | 31 +++++++++++++++++++ .../__tests__/trusted-documents.test.js | 29 ++++++++++++++++- .../graphql/features/trusted-documents.ts | 3 +- 11 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js create mode 100644 packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/default.toml (100%) rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/fragments.toml (100%) rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/fragments_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/trusted_docs_already_setup.toml (100%) rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/trusted_docs_already_setup_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/__fixtures__/{ => toml}/trusted_docs_and_fragments_already_setup.toml (100%) diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js b/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js new file mode 100644 index 000000000000..e9c53e285fad --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js @@ -0,0 +1,25 @@ +import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { cookieName, getCurrentUser } from 'src/lib/auth' +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' + +const authDecoder = createAuthDecoder(cookieName) + +export const handler = createGraphQLHandler({ + authDecoder, + getCurrentUser, + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, +}) diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js b/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js new file mode 100644 index 000000000000..1c835d1fb82e --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js @@ -0,0 +1,27 @@ +import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { cookieName, getCurrentUser } from 'src/lib/auth' +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' +import { store } from 'src/lib/trustedDocumentsStore' + +const authDecoder = createAuthDecoder(cookieName) + +export const handler = createGraphQLHandler({ + authDecoder, + getCurrentUser, + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, + trustedDocuments: { store }, +}) diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/default.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/default.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/default.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/default.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/fragments.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/fragments_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_already_setup_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml b/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/trusted_docs_and_fragments_already_setup.toml rename to packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap b/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap index 9485cec96ba2..44061fadcbc7 100644 --- a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap +++ b/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap @@ -1,5 +1,36 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP +exports[`Trusted documents setup tests GraphQL Handler updates default handler where the trusted document store is not configured updates the handler with the trusted document store 1`] = ` +"import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { cookieName, getCurrentUser } from 'src/lib/auth' +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' +import { store } from 'src/lib/trustedDocumentsStore' + +const authDecoder = createAuthDecoder(cookieName) + +export const handler = createGraphQLHandler({ + authDecoder, + getCurrentUser, + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, + trustedDocuments: { store }, +}) +" +`; + exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql fragments are already setup updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` { "newConfig": "# This file contains the configuration settings for your Redwood app. diff --git a/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js b/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js index dbf3cd407c8b..d9d35f187430 100644 --- a/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js +++ b/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js @@ -1,6 +1,10 @@ import path from 'path' -import { updateRedwoodToml } from '../features/trusted-documents' +import { + updateGraphQLHandler, + updateRedwoodToml, +} from '../features/trusted-documents' + describe('Trusted documents setup tests', () => { describe('Project toml configuration updates', () => { describe('default toml where no graphql or trusted documents is setup', () => { @@ -9,6 +13,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'default.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -21,6 +26,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'fragments.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -33,6 +39,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'fragments_no_space_equals.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -45,6 +52,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'trusted_docs_already_setup.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -57,6 +65,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'trusted_docs_already_setup_no_space_equals.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -69,6 +78,7 @@ describe('Trusted documents setup tests', () => { __dirname, '../', '__fixtures__', + 'toml', 'trusted_docs_and_fragments_already_setup.toml' ) const result = updateRedwoodToml(redwoodTomlPath) @@ -76,4 +86,21 @@ describe('Trusted documents setup tests', () => { }) }) }) + describe('GraphQL Handler updates', () => { + describe('default handler where the trusted document store is not configured', () => { + it('updates the handler with the trusted document store', async () => { + const handlerPath = path.join( + __dirname, + '../', + '__fixtures__', + 'graphQLHandler', + 'trustedDocumentSetupHandler.js' + ) + const { graphQlSourceFile, graphQlSourceFileChanged } = + updateGraphQLHandler(handlerPath) + expect(graphQlSourceFileChanged).toBe(false) + expect(graphQlSourceFile.getFullText()).toMatchSnapshot() + }) + }) + }) }) diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts index b5c8f1de0a95..199014a9b5fd 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts +++ b/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts @@ -18,6 +18,7 @@ export function builder() {} export function updateGraphQLHandler(graphQlSourcePath: string) { // add import const project = new Project() + const graphQlSourceFile = project.addSourceFileAtPathIfExists(graphQlSourcePath) @@ -87,7 +88,7 @@ export function updateGraphQLHandler(graphQlSourcePath: string) { ) } - return { graphQlSourceFileChanged, project } + return { graphQlSourceFileChanged, graphQlSourceFile, project } } export function updateRedwoodToml(redwoodTomlPath: string) { From 89a06df456a2474f4689dc96ffd5ad7072f0db84 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 14:26:42 +0100 Subject: [PATCH 12/23] async handler and TS fixes --- packages/cli-helpers/src/lib/index.ts | 8 ++--- .../trustedDocuments/trustedDocuments.ts | 25 ++++++++++++++++ .../trustedDocumentsHandler.ts} | 30 ++++--------------- .../cli/src/commands/setup/graphql/graphql.js | 14 --------- .../cli/src/commands/setup/graphql/graphql.ts | 2 ++ 5 files changed, 37 insertions(+), 42 deletions(-) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts rename packages/cli/src/commands/setup/graphql/features/{trusted-documents.ts => trustedDocuments/trustedDocumentsHandler.ts} (90%) delete mode 100644 packages/cli/src/commands/setup/graphql/graphql.js diff --git a/packages/cli-helpers/src/lib/index.ts b/packages/cli-helpers/src/lib/index.ts index 21e7ce2c628b..e4ef9299581e 100644 --- a/packages/cli-helpers/src/lib/index.ts +++ b/packages/cli-helpers/src/lib/index.ts @@ -70,16 +70,16 @@ export const prettierOptions = () => { } } -export const prettifyFile = (filename: string, parser: string | undefined) => { +export const prettifyFile = (filePath: string, parser: string | undefined) => { try { - const file = fs.readFileSync(filename, 'utf-8') + const file = fs.readFileSync(filePath, 'utf-8') const prettifiedFile = format(file, { ...prettierOptions(), parser: parser || 'babel-ts', }) - fs.writeFileSync(filename, prettifiedFile, 'utf-8') + fs.writeFileSync(filePath, prettifiedFile, 'utf-8') } catch (e) { - const message = `Could not prettify ${filename}` + const message = `Could not prettify ${filePath}` console.error(colors.error(message)) throw Error(message) } diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts new file mode 100644 index 000000000000..22362293848f --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts @@ -0,0 +1,25 @@ +import type { Argv } from 'yargs' + +import { recordTelemetryAttributes } from '@redwoodjs/cli-helpers' + +export const command = 'trusted-documents' +export const description = 'Set up Trusted Documents for GraphQL' + +export function builder(yargs: Argv) { + return yargs.option('force', { + alias: 'f', + default: false, + description: 'Overwrite existing configuration', + type: 'boolean', + }) +} + +export async function handler({ force }: { force: boolean }) { + recordTelemetryAttributes({ + command: 'setup graphql trusted-documents', + force, + }) + + const { handler } = await import('./trustedDocumentsHandler') + return handler({ force }) +} diff --git a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts similarity index 90% rename from packages/cli/src/commands/setup/graphql/features/trusted-documents.ts rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index 199014a9b5fd..c98ad9ae7287 100644 --- a/packages/cli/src/commands/setup/graphql/features/trusted-documents.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -6,14 +6,7 @@ import { Listr } from 'listr2' import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' import { recordTelemetryAttributes, prettifyFile } from '@redwoodjs/cli-helpers' -import { getConfigPath } from '@redwoodjs/project-config' - -import { getPaths } from '../../../../lib' - -export const command = 'trusted-documents' -export const description = 'Set up Trusted Documents for GraphQL' - -export function builder() {} +import { getConfigPath, getPaths } from '@redwoodjs/project-config' export function updateGraphQLHandler(graphQlSourcePath: string) { // add import @@ -24,10 +17,7 @@ export function updateGraphQLHandler(graphQlSourcePath: string) { if (!graphQlSourceFile) { console.error( - `Unable to determine the GraphQL Handler source path for: ${path.join( - functionsDir, - 'graphql.(js|ts)' - )}` + `Unable to determine the GraphQL Handler source path for: ${graphQlSourcePath}` ) return } @@ -158,28 +148,20 @@ function configureGraphQLHandlerWithStore() { return } - const { project, graphQlSourceFileChanged } = - updateGraphQLHandler(graphQlSourcePath) + const updateResult = updateGraphQLHandler(graphQlSourcePath) - if (graphQlSourceFileChanged) { - await project.save() + if (updateResult?.graphQlSourceFileChanged) { + await updateResult?.project.save() prettifyFile(graphQlSourcePath, 'babel-ts') } }, } } -export async function handler({ - force, - install, -}: { - force: boolean - install: boolean -}) { +export async function handler({ force }: { force: boolean }) { recordTelemetryAttributes({ command: 'setup graphql trusted-documents', force, - install, }) const tasks = new Listr( diff --git a/packages/cli/src/commands/setup/graphql/graphql.js b/packages/cli/src/commands/setup/graphql/graphql.js deleted file mode 100644 index dd2aa93b016f..000000000000 --- a/packages/cli/src/commands/setup/graphql/graphql.js +++ /dev/null @@ -1,14 +0,0 @@ -import terminalLink from 'terminal-link' - -import * as trustedDocumentsCommand from './features/trusted-documents' -export const command = 'graphql ' -export const description = 'Set up GraphQL feature support' -export const builder = (yargs) => - yargs - .command(trustedDocumentsCommand) - .epilogue( - `Also see the ${terminalLink( - 'Redwood CLI Reference', - 'https://redwoodjs.com/docs/cli-commands#setup-graphql' - )}` - ) diff --git a/packages/cli/src/commands/setup/graphql/graphql.ts b/packages/cli/src/commands/setup/graphql/graphql.ts index aca51785336d..2a4c810bd703 100644 --- a/packages/cli/src/commands/setup/graphql/graphql.ts +++ b/packages/cli/src/commands/setup/graphql/graphql.ts @@ -2,12 +2,14 @@ import terminalLink from 'terminal-link' import type { Argv } from 'yargs' import * as fragmentsCommand from './features/fragments/fragments' +import * as trustedDocumentsCommand from './features/trustedDocuments/trustedDocuments' export const command = 'graphql ' export const description = 'Set up GraphQL feature support' export function builder(yargs: Argv) { return yargs .command(fragmentsCommand) + .command(trustedDocumentsCommand) .epilogue( `Also see the ${terminalLink( 'Redwood CLI Reference', From d69acf3938e67629de899dd8c0a7d0cbcfa8b548 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 14:43:34 +0100 Subject: [PATCH 13/23] Fix import and TS issue in test --- ...rusted-documents.test.js => trustedDocuments.test.ts} | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) rename packages/cli/src/commands/setup/graphql/__tests__/{trusted-documents.test.js => trustedDocuments.test.ts} (92%) diff --git a/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js b/packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts similarity index 92% rename from packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js rename to packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts index d9d35f187430..b385d647bcf6 100644 --- a/packages/cli/src/commands/setup/graphql/__tests__/trusted-documents.test.js +++ b/packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts @@ -3,7 +3,7 @@ import path from 'path' import { updateGraphQLHandler, updateRedwoodToml, -} from '../features/trusted-documents' +} from '../features/trustedDocuments/trustedDocumentsHandler' describe('Trusted documents setup tests', () => { describe('Project toml configuration updates', () => { @@ -96,10 +96,9 @@ describe('Trusted documents setup tests', () => { 'graphQLHandler', 'trustedDocumentSetupHandler.js' ) - const { graphQlSourceFile, graphQlSourceFileChanged } = - updateGraphQLHandler(handlerPath) - expect(graphQlSourceFileChanged).toBe(false) - expect(graphQlSourceFile.getFullText()).toMatchSnapshot() + const updateResult = updateGraphQLHandler(handlerPath) + expect(updateResult?.graphQlSourceFileChanged).toBe(false) + expect(updateResult?.graphQlSourceFile.getFullText()).toMatchSnapshot() }) }) }) From 2cb9ad38df27f953a43e69fa3518500972952c24 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 14:47:19 +0100 Subject: [PATCH 14/23] Update test snapshot --- ...usted-documents.test.js.snap => trustedDocuments.test.ts.snap} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/{trusted-documents.test.js.snap => trustedDocuments.test.ts.snap} (100%) diff --git a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap b/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trustedDocuments.test.ts.snap similarity index 100% rename from packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trusted-documents.test.js.snap rename to packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trustedDocuments.test.ts.snap From 2b551f2a471a9ce6262a2bf8eb494fa05ba0fcaa Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 15:22:28 +0100 Subject: [PATCH 15/23] More robust redwood.toml handling --- .../features/fragments/fragmentsHandler.ts | 3 +- .../graphQLHandler/defaultHandler.js | 0 .../trustedDocumentSetupHandler.js | 0 .../__fixtures__/toml/default.toml | 0 .../__fixtures__/toml/fragments.toml | 0 .../toml/fragments_no_space_equals.toml | 0 .../toml/trusted_docs_already_setup.toml | 0 ...ed_docs_already_setup_no_space_equals.toml | 0 ...sted_docs_and_fragments_already_setup.toml | 0 .../toml/trusted_docs_commented_graphql.toml | 23 +++++ .../trustedDocuments.test.ts.snap | 36 +++++++- .../__tests__/trustedDocuments.test.ts | 15 +++- .../trustedDocumentsHandler.ts | 89 ++++++++++++------- 13 files changed, 129 insertions(+), 37 deletions(-) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/graphQLHandler/defaultHandler.js (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/default.toml (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/fragments.toml (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/fragments_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/trusted_docs_already_setup.toml (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml (100%) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__tests__/__snapshots__/trustedDocuments.test.ts.snap (82%) rename packages/cli/src/commands/setup/graphql/{ => features/trustedDocuments}/__tests__/trustedDocuments.test.ts (88%) diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts index fb296f120b83..5251ae2c1524 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts @@ -54,7 +54,8 @@ export async function handler({ force }: Args) { const hasExistingGraphqlSection = !!redwoodTomlObject?.graphql let newTomlContent = - originalTomlContent + '\n\n[graphql]\n fragments = true' + originalTomlContent.replace(/\n$/, '') + + '\n\n[graphql]\n fragments = true' if (hasExistingGraphqlSection) { const existingGraphqlSetting = Object.keys( diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/defaultHandler.js similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/defaultHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/defaultHandler.js diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/default.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/default.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/default.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/default.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/fragments_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml new file mode 100644 index 000000000000..ad3aa27c57aa --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml @@ -0,0 +1,23 @@ +# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run `yarn rw dev`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "${API_DEV_PORT:8911}" +# [graphql] +# trustedDocuments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] diff --git a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trustedDocuments.test.ts.snap b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap similarity index 82% rename from packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trustedDocuments.test.ts.snap rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap index 44061fadcbc7..5a4d71492361 100644 --- a/packages/cli/src/commands/setup/graphql/__tests__/__snapshots__/trustedDocuments.test.ts.snap +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap @@ -51,8 +51,8 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul [api] port = "\${API_DEV_PORT:8911}" [graphql] - trustedDocuments = true fragments = true + trustedDocuments = true [browser] open = true [notifications] @@ -82,8 +82,8 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul [api] port = "\${API_DEV_PORT:8911}" [graphql] - trustedDocuments = true fragments=true + trustedDocuments = true [browser] open = true [notifications] @@ -143,3 +143,35 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul "trustedDocumentsExists": false, } `; + +exports[`Trusted documents setup tests Project toml configuration updates toml where graphql section is commented out adds a new section with \`trustedDocuments = true\` 1`] = ` +{ + "newConfig": "# This file contains the configuration settings for your Redwood app. +# This file is also what makes your Redwood app a Redwood app. +# If you remove it and try to run \`yarn rw dev\`, you'll get an error. +# +# For the full list of options, see the "App Configuration: redwood.toml" doc: +# https://redwoodjs.com/docs/app-configuration-redwood-toml + +[web] + title = "Redwood App" + port = "\${WEB_DEV_PORT:8910}" + apiUrl = "/.redwood/functions" # You can customize graphql and dbauth urls individually too: see https://redwoodjs.com/docs/app-configuration-redwood-toml#api-paths + includeEnvironmentVariables = [ + # Add any ENV vars that should be available to the web side to this array + # See https://redwoodjs.com/docs/environment-variables#web + ] +[api] + port = "\${API_DEV_PORT:8911}" +# [graphql] +# trustedDocuments = true +[browser] + open = true +[notifications] + versionUpdates = ["latest"] + +[graphql] + trustedDocuments = true", + "trustedDocumentsExists": false, +} +`; diff --git a/packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts similarity index 88% rename from packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index b385d647bcf6..bcfd6243baf0 100644 --- a/packages/cli/src/commands/setup/graphql/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -3,7 +3,7 @@ import path from 'path' import { updateGraphQLHandler, updateRedwoodToml, -} from '../features/trustedDocuments/trustedDocumentsHandler' +} from '../trustedDocumentsHandler' describe('Trusted documents setup tests', () => { describe('Project toml configuration updates', () => { @@ -85,6 +85,19 @@ describe('Trusted documents setup tests', () => { expect(result).toMatchSnapshot() }) }) + describe('toml where graphql section is commented out', () => { + it('adds a new section with `trustedDocuments = true`', () => { + const redwoodTomlPath = path.join( + __dirname, + '../', + '__fixtures__', + 'toml', + 'trusted_docs_commented_graphql.toml' + ) + const result = updateRedwoodToml(redwoodTomlPath) + expect(result).toMatchSnapshot() + }) + }) }) describe('GraphQL Handler updates', () => { describe('default handler where the trusted document store is not configured', () => { diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index c98ad9ae7287..48acf92bff75 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -1,6 +1,7 @@ import fs from 'fs' import path from 'path' +import toml from '@iarna/toml' import execa from 'execa' import { Listr } from 'listr2' import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' @@ -82,46 +83,68 @@ export function updateGraphQLHandler(graphQlSourcePath: string) { } export function updateRedwoodToml(redwoodTomlPath: string) { - let newConfig = undefined - const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') - const graphqlExists = originalTomlContent.includes('[graphql]') - - const trustedDocumentsExists = - originalTomlContent.includes('trustedDocuments =') || - originalTomlContent.includes('trustedDocuments=') - - const fragmentsExists = - originalTomlContent.includes('fragments =') || - originalTomlContent.includes('fragments=') + const redwoodTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') + // Can't type toml.parse because this PR has not been included in a released yet + // https://github.com/iarna/iarna-toml/commit/5a89e6e65281e4544e23d3dbaf9e8428ed8140e9 + const redwoodTomlObject = toml.parse(redwoodTomlContent) as any + const hasExistingGraphqlSection = !!redwoodTomlObject?.graphql - if (trustedDocumentsExists) { + if (redwoodTomlObject?.graphql?.trustedDocuments) { console.info( 'GraphQL Trusted Documents are already enabled in your Redwood project.' ) - } else if (graphqlExists && fragmentsExists) { - const insertIndex = originalTomlContent.indexOf('fragments') - const trustedDocuments = 'trustedDocuments = true\n ' - newConfig = - originalTomlContent.slice(0, insertIndex) + - trustedDocuments + - originalTomlContent.slice(insertIndex) - } else { - if (!graphqlExists) { - const tomlToAppend = `[graphql]\n trustedDocuments = true` - - newConfig = originalTomlContent + '\n' + tomlToAppend - } else { - const graphqlIndex = originalTomlContent.indexOf('[graphql]') - const insertIndex = graphqlIndex + '[graphql]\n'.length - newConfig = - originalTomlContent.slice(0, insertIndex) + - ' trustedDocuments = true\n' + - originalTomlContent.slice(insertIndex) - } + + return { newConfig: undefined, trustedDocumentsExists: true } + } + + let newTomlContent = + originalTomlContent.replace(/\n$/, '') + + '\n\n[graphql]\n trustedDocuments = true' + + if (hasExistingGraphqlSection) { + const existingGraphqlSetting = Object.keys(redwoodTomlObject.graphql) + + let inGraphqlSection = false + let indentation = '' + let lastGraphqlSettingIndex = 0 + + const tomlLines = originalTomlContent.split('\n') + tomlLines.forEach((line, index) => { + if (line.startsWith('[graphql]')) { + inGraphqlSection = true + lastGraphqlSettingIndex = index + } else { + if (/^\s*\[/.test(line)) { + inGraphqlSection = false + } + } + + if (inGraphqlSection) { + const matches = line.match( + new RegExp(`^(\\s*)(${existingGraphqlSetting})\\s*=`, 'i') + ) + + if (matches) { + indentation = matches[1] + } + + if (/^\s*\w+\s*=/.test(line)) { + lastGraphqlSettingIndex = index + } + } + }) + + tomlLines.splice( + lastGraphqlSettingIndex + 1, + 0, + `${indentation}trustedDocuments = true` + ) + + newTomlContent = tomlLines.join('\n') } - return { newConfig, trustedDocumentsExists } + return { newConfig: newTomlContent, trustedDocumentsExists: false } } function configureGraphQLHandlerWithStore() { From e01e9626a550770bb92e7bb592f71fd2ecd00fd0 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 15:46:49 +0100 Subject: [PATCH 16/23] Fix tsconfig --- packages/cli/tsconfig.json | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.json index a12c30f06606..1bac37ddc8ca 100644 --- a/packages/cli/tsconfig.json +++ b/packages/cli/tsconfig.json @@ -7,5 +7,9 @@ "noEmit": true }, "include": ["src", "./testUtils.d.ts"], - "exclude": ["**/__testfixtures__"] + "exclude": ["**/__testfixtures__"], + "references": [ + { "path": "../cli-helpers" }, + { "path": "../project-config" }, + ] } From 063a67fb9ba9ae581c7fc892e6c15bd86ace323c Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 15:47:18 +0100 Subject: [PATCH 17/23] Move all tasks to array, and silence logs in test --- .../__tests__/trustedDocuments.test.ts | 3 ++ .../trustedDocumentsHandler.ts | 51 +++++-------------- 2 files changed, 17 insertions(+), 37 deletions(-) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index bcfd6243baf0..d404eec707c1 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -5,6 +5,9 @@ import { updateRedwoodToml, } from '../trustedDocumentsHandler' +// Silence console.info +console.info = jest.fn() + describe('Trusted documents setup tests', () => { describe('Project toml configuration updates', () => { describe('default toml where no graphql or trusted documents is setup', () => { diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index 48acf92bff75..6816ae77b724 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -1,12 +1,11 @@ import fs from 'fs' -import path from 'path' import toml from '@iarna/toml' import execa from 'execa' import { Listr } from 'listr2' import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' -import { recordTelemetryAttributes, prettifyFile } from '@redwoodjs/cli-helpers' +import { prettifyFile } from '@redwoodjs/cli-helpers' import { getConfigPath, getPaths } from '@redwoodjs/project-config' export function updateGraphQLHandler(graphQlSourcePath: string) { @@ -147,46 +146,18 @@ export function updateRedwoodToml(redwoodTomlPath: string) { return { newConfig: newTomlContent, trustedDocumentsExists: false } } -function configureGraphQLHandlerWithStore() { - return { - title: - 'Configuring the GraphQL Handler to use a Trusted Documents store ...', - task: async () => { - // locate "api/functions/graphql.[js|ts]" - let graphQlSourcePath: string | undefined - const functionsDir = getPaths().api.functions - if (fs.existsSync(path.join(functionsDir, 'graphql.ts'))) { - graphQlSourcePath = path.join(functionsDir, 'graphql.ts') - } else if (fs.existsSync(path.join(functionsDir, 'graphql.js'))) { - graphQlSourcePath = path.join(functionsDir, 'graphql.js') - } - - if (!graphQlSourcePath) { - console.warn( - `Unable to find the GraphQL Handler source file: ${path.join( - functionsDir, - 'graphql.(js|ts)' - )}` - ) - return - } +async function configureGraphQLHandlerWithStore() { + const graphQlSourcePath = getPaths().api.graphql - const updateResult = updateGraphQLHandler(graphQlSourcePath) + const updateResult = updateGraphQLHandler(graphQlSourcePath) - if (updateResult?.graphQlSourceFileChanged) { - await updateResult?.project.save() - prettifyFile(graphQlSourcePath, 'babel-ts') - } - }, + if (updateResult?.graphQlSourceFileChanged) { + await updateResult?.project.save() + prettifyFile(graphQlSourcePath, 'babel-ts') } } export async function handler({ force }: { force: boolean }) { - recordTelemetryAttributes({ - command: 'setup graphql trusted-documents', - force, - }) - const tasks = new Listr( [ { @@ -209,7 +180,13 @@ export async function handler({ force }: { force: boolean }) { execa.commandSync('yarn redwood generate types', { stdio: 'ignore' }) }, }, - configureGraphQLHandlerWithStore(), + { + title: + 'Configuring the GraphQL Handler to use a Trusted Documents store ...', + task: async () => { + return configureGraphQLHandlerWithStore() + }, + }, ], { rendererOptions: { collapseSubtasks: false } } ) From 7ad7da2f94521b2790eebc03dc016f9285b7fa56 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 16:27:17 +0100 Subject: [PATCH 18/23] Move __fixtures__ --- .../__fixtures__/graphQLHandler/defaultHandler.js | 0 .../graphQLHandler/trustedDocumentSetupHandler.js | 0 .../{ => __tests__}/__fixtures__/toml/default.toml | 0 .../{ => __tests__}/__fixtures__/toml/fragments.toml | 0 .../__fixtures__/toml/fragments_no_space_equals.toml | 0 .../__fixtures__/toml/trusted_docs_already_setup.toml | 0 .../toml/trusted_docs_already_setup_no_space_equals.toml | 0 .../toml/trusted_docs_and_fragments_already_setup.toml | 0 .../__fixtures__/toml/trusted_docs_commented_graphql.toml | 0 .../trustedDocuments/__tests__/trustedDocuments.test.ts | 8 -------- 10 files changed, 8 deletions(-) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/graphQLHandler/defaultHandler.js (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/default.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/fragments.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/fragments_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/trusted_docs_already_setup.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{ => __tests__}/__fixtures__/toml/trusted_docs_commented_graphql.toml (100%) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/defaultHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/defaultHandler.js similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/defaultHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/defaultHandler.js diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/default.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/default.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/default.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/default.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/fragments.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/fragments.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/fragments_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/fragments_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/fragments_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_commented_graphql.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__fixtures__/toml/trusted_docs_commented_graphql.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_commented_graphql.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index d404eec707c1..200f065331be 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -14,7 +14,6 @@ describe('Trusted documents setup tests', () => { it('updates the toml file with graphql and trusted documents enabled', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'default.toml' @@ -27,7 +26,6 @@ describe('Trusted documents setup tests', () => { it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'fragments.toml' @@ -40,7 +38,6 @@ describe('Trusted documents setup tests', () => { it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'fragments_no_space_equals.toml' @@ -53,7 +50,6 @@ describe('Trusted documents setup tests', () => { it('makes no changes as trusted documents are already setup', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'trusted_docs_already_setup.toml' @@ -66,7 +62,6 @@ describe('Trusted documents setup tests', () => { it('makes no changes as trusted documents are already setup', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'trusted_docs_already_setup_no_space_equals.toml' @@ -79,7 +74,6 @@ describe('Trusted documents setup tests', () => { it('makes no changes as trusted documents are already setup', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'trusted_docs_and_fragments_already_setup.toml' @@ -92,7 +86,6 @@ describe('Trusted documents setup tests', () => { it('adds a new section with `trustedDocuments = true`', () => { const redwoodTomlPath = path.join( __dirname, - '../', '__fixtures__', 'toml', 'trusted_docs_commented_graphql.toml' @@ -107,7 +100,6 @@ describe('Trusted documents setup tests', () => { it('updates the handler with the trusted document store', async () => { const handlerPath = path.join( __dirname, - '../', '__fixtures__', 'graphQLHandler', 'trustedDocumentSetupHandler.js' From 23f281c88d5d7a4ee54e6229fd67ac0b58920534 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Thu, 11 Jan 2024 18:26:31 +0100 Subject: [PATCH 19/23] Fix whiteline in test --- .../features/fragments/__tests__/fragmentsHandler.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts b/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts index c60ea5f4100d..2e271612b4a4 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/__tests__/fragmentsHandler.test.ts @@ -138,7 +138,7 @@ test('redwood.toml is updated even if `fragments = true` exists for other sectio await handler({ force: false }) expect(vol.toJSON()[FIXTURE_PATH + '/redwood.toml']).toEqual( - toml + '\n\n[graphql]\n fragments = true' + toml + '\n[graphql]\n fragments = true' ) }) From bd476bee6c5938384cff837843889b73ef4f6c1c Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Fri, 12 Jan 2024 08:23:50 +0100 Subject: [PATCH 20/23] fragments: refactor->rename --- .../setup/graphql/features/fragments/fragmentsHandler.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts index 5251ae2c1524..dc9b4937e2da 100644 --- a/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/fragments/fragmentsHandler.ts @@ -122,13 +122,13 @@ export async function handler({ force }: Args) { { title: 'Add possibleTypes to the GraphQL cache config', task: async () => { - const result = await runTransform({ + const transformResult = await runTransform({ transformPath: path.join(__dirname, 'appGqlConfigTransform.js'), targetPaths: [getPaths().web.app], }) - if (result.error) { - throw new Error(result.error) + if (transformResult.error) { + throw new Error(transformResult.error) } const appPath = getPaths().web.app From 6b144bb03ea9f7e42ac952674526bb19be210435 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Fri, 12 Jan 2024 09:15:28 +0100 Subject: [PATCH 21/23] Move to jscodeshift --- packages/cli-helpers/src/lib/index.ts | 15 - .../__codemod_tests__/grapqlTransform.test.ts | 13 + .../alreadySetUp/input/graphql.js} | 7 +- .../alreadySetUp/output/graphql.js | 32 ++ .../graphql/input/graphql.js} | 0 .../graphql/output/graphql.js | 32 ++ ...trusted_docs_fragments_already_setup.toml} | 0 ...toml => trusted_docs_no_space_equals.toml} | 0 .../trustedDocuments.test.ts.snap | 88 +----- .../__tests__/trustedDocuments.test.ts | 275 +++++++++++++----- .../trustedDocuments/graphqlTransform.ts | 57 ++++ .../trustedDocumentsHandler.ts | 112 ++----- 12 files changed, 374 insertions(+), 257 deletions(-) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/__codemod_tests__/grapqlTransform.test.ts rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js => __testfixtures__/alreadySetUp/input/graphql.js} (95%) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/output/graphql.js rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/{__tests__/__fixtures__/graphQLHandler/defaultHandler.js => __testfixtures__/graphql/input/graphql.js} (100%) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/output/graphql.js rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/{trusted_docs_and_fragments_already_setup.toml => trusted_docs_fragments_already_setup.toml} (100%) rename packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/{trusted_docs_already_setup_no_space_equals.toml => trusted_docs_no_space_equals.toml} (100%) create mode 100644 packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts diff --git a/packages/cli-helpers/src/lib/index.ts b/packages/cli-helpers/src/lib/index.ts index e4ef9299581e..d55f3fa08123 100644 --- a/packages/cli-helpers/src/lib/index.ts +++ b/packages/cli-helpers/src/lib/index.ts @@ -70,21 +70,6 @@ export const prettierOptions = () => { } } -export const prettifyFile = (filePath: string, parser: string | undefined) => { - try { - const file = fs.readFileSync(filePath, 'utf-8') - const prettifiedFile = format(file, { - ...prettierOptions(), - parser: parser || 'babel-ts', - }) - fs.writeFileSync(filePath, prettifiedFile, 'utf-8') - } catch (e) { - const message = `Could not prettify ${filePath}` - console.error(colors.error(message)) - throw Error(message) - } -} - export const prettify = ( templateFilename: string, renderedTemplate: string diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__codemod_tests__/grapqlTransform.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__codemod_tests__/grapqlTransform.test.ts new file mode 100644 index 000000000000..a44dd63ff138 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__codemod_tests__/grapqlTransform.test.ts @@ -0,0 +1,13 @@ +describe('trusted-documents graphql handler transform', () => { + test('Default handler', async () => { + await matchFolderTransform('graphqlTransform', 'graphql', { + useJsCodeshift: true, + }) + }) + + test('Handler with the store already set up', async () => { + await matchFolderTransform('graphqlTransform', 'alreadySetUp', { + useJsCodeshift: true, + }) + }) +}) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/input/graphql.js similarity index 95% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/input/graphql.js index 1c835d1fb82e..ceb92dbf9d5b 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/trustedDocumentSetupHandler.js +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/input/graphql.js @@ -8,6 +8,7 @@ import services from 'src/services/**/*.{js,ts}' import { cookieName, getCurrentUser } from 'src/lib/auth' import { db } from 'src/lib/db' import { logger } from 'src/lib/logger' + import { store } from 'src/lib/trustedDocumentsStore' const authDecoder = createAuthDecoder(cookieName) @@ -19,9 +20,13 @@ export const handler = createGraphQLHandler({ directives, sdls, services, + onException: () => { // Disconnect from your database with an unhandled exception. db.$disconnect() }, - trustedDocuments: { store }, + + trustedDocuments: { + store + }, }) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/output/graphql.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/output/graphql.js new file mode 100644 index 000000000000..ceb92dbf9d5b --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/alreadySetUp/output/graphql.js @@ -0,0 +1,32 @@ +import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { cookieName, getCurrentUser } from 'src/lib/auth' +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' + +import { store } from 'src/lib/trustedDocumentsStore' + +const authDecoder = createAuthDecoder(cookieName) + +export const handler = createGraphQLHandler({ + authDecoder, + getCurrentUser, + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, + + trustedDocuments: { + store + }, +}) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/defaultHandler.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/input/graphql.js similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/graphQLHandler/defaultHandler.js rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/input/graphql.js diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/output/graphql.js b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/output/graphql.js new file mode 100644 index 000000000000..ceb92dbf9d5b --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__testfixtures__/graphql/output/graphql.js @@ -0,0 +1,32 @@ +import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' +import { createGraphQLHandler } from '@redwoodjs/graphql-server' + +import directives from 'src/directives/**/*.{js,ts}' +import sdls from 'src/graphql/**/*.sdl.{js,ts}' +import services from 'src/services/**/*.{js,ts}' + +import { cookieName, getCurrentUser } from 'src/lib/auth' +import { db } from 'src/lib/db' +import { logger } from 'src/lib/logger' + +import { store } from 'src/lib/trustedDocumentsStore' + +const authDecoder = createAuthDecoder(cookieName) + +export const handler = createGraphQLHandler({ + authDecoder, + getCurrentUser, + loggerConfig: { logger, options: {} }, + directives, + sdls, + services, + + onException: () => { + // Disconnect from your database with an unhandled exception. + db.$disconnect() + }, + + trustedDocuments: { + store + }, +}) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_fragments_already_setup.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_and_fragments_already_setup.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_fragments_already_setup.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_no_space_equals.toml similarity index 100% rename from packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_already_setup_no_space_equals.toml rename to packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__fixtures__/toml/trusted_docs_no_space_equals.toml diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap index 5a4d71492361..05ac34b420f2 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/__snapshots__/trustedDocuments.test.ts.snap @@ -1,39 +1,7 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`Trusted documents setup tests GraphQL Handler updates default handler where the trusted document store is not configured updates the handler with the trusted document store 1`] = ` -"import { createAuthDecoder } from '@redwoodjs/auth-dbauth-api' -import { createGraphQLHandler } from '@redwoodjs/graphql-server' - -import directives from 'src/directives/**/*.{js,ts}' -import sdls from 'src/graphql/**/*.sdl.{js,ts}' -import services from 'src/services/**/*.{js,ts}' - -import { cookieName, getCurrentUser } from 'src/lib/auth' -import { db } from 'src/lib/db' -import { logger } from 'src/lib/logger' -import { store } from 'src/lib/trustedDocumentsStore' - -const authDecoder = createAuthDecoder(cookieName) - -export const handler = createGraphQLHandler({ - authDecoder, - getCurrentUser, - loggerConfig: { logger, options: {} }, - directives, - sdls, - services, - onException: () => { - // Disconnect from your database with an unhandled exception. - db.$disconnect() - }, - trustedDocuments: { store }, -}) -" -`; - -exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql fragments are already setup updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` -{ - "newConfig": "# This file contains the configuration settings for your Redwood app. +exports[`Trusted documents setup Project toml configuration updates default toml where graphql fragments are already setup updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` +"# This file contains the configuration settings for your Redwood app. # This file is also what makes your Redwood app a Redwood app. # If you remove it and try to run \`yarn rw dev\`, you'll get an error. # @@ -57,14 +25,11 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul open = true [notifications] versionUpdates = ["latest"] -", - "trustedDocumentsExists": false, -} +" `; -exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql fragments are already setup using no spaces updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` -{ - "newConfig": "# This file contains the configuration settings for your Redwood app. +exports[`Trusted documents setup Project toml configuration updates default toml where graphql fragments are already setup using no spaces updates the toml file with graphql and trusted documents enabled and keeps fragments 1`] = ` +"# This file contains the configuration settings for your Redwood app. # This file is also what makes your Redwood app a Redwood app. # If you remove it and try to run \`yarn rw dev\`, you'll get an error. # @@ -88,35 +53,11 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul open = true [notifications] versionUpdates = ["latest"] -", - "trustedDocumentsExists": false, -} -`; - -exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents and fragments are already setup makes no changes as trusted documents are already setup 1`] = ` -{ - "newConfig": undefined, - "trustedDocumentsExists": true, -} -`; - -exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents are already setup makes no changes as trusted documents are already setup 1`] = ` -{ - "newConfig": undefined, - "trustedDocumentsExists": true, -} -`; - -exports[`Trusted documents setup tests Project toml configuration updates default toml where graphql trusted documents are already setup using no spaces makes no changes as trusted documents are already setup 1`] = ` -{ - "newConfig": undefined, - "trustedDocumentsExists": true, -} +" `; -exports[`Trusted documents setup tests Project toml configuration updates default toml where no graphql or trusted documents is setup updates the toml file with graphql and trusted documents enabled 1`] = ` -{ - "newConfig": "# This file contains the configuration settings for your Redwood app. +exports[`Trusted documents setup Project toml configuration updates default toml where no graphql or trusted documents is setup updates the toml file with graphql and trusted documents enabled 1`] = ` +"# This file contains the configuration settings for your Redwood app. # This file is also what makes your Redwood app a Redwood app. # If you remove it and try to run \`yarn rw dev\`, you'll get an error. # @@ -139,14 +80,11 @@ exports[`Trusted documents setup tests Project toml configuration updates defaul versionUpdates = ["latest"] [graphql] - trustedDocuments = true", - "trustedDocumentsExists": false, -} + trustedDocuments = true" `; -exports[`Trusted documents setup tests Project toml configuration updates toml where graphql section is commented out adds a new section with \`trustedDocuments = true\` 1`] = ` -{ - "newConfig": "# This file contains the configuration settings for your Redwood app. +exports[`Trusted documents setup Project toml configuration updates toml where graphql section is commented out adds a new section with \`trustedDocuments = true\` 1`] = ` +"# This file contains the configuration settings for your Redwood app. # This file is also what makes your Redwood app a Redwood app. # If you remove it and try to run \`yarn rw dev\`, you'll get an error. # @@ -171,7 +109,5 @@ exports[`Trusted documents setup tests Project toml configuration updates toml w versionUpdates = ["latest"] [graphql] - trustedDocuments = true", - "trustedDocumentsExists": false, -} + trustedDocuments = true" `; diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index 200f065331be..a00837f8ab4e 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -1,112 +1,233 @@ -import path from 'path' +let mockExecutedTaskTitles: Array = [] +let mockSkippedTaskTitles: Array = [] -import { - updateGraphQLHandler, - updateRedwoodToml, -} from '../trustedDocumentsHandler' +jest.mock('fs', () => require('memfs').fs) +jest.mock('node:fs', () => require('memfs').fs) +jest.mock('execa') +// The jscodeshift parts are tested by another test +jest.mock('../../fragments/runTransform', () => { + return { + runTransform: () => { + return {} + }, + } +}) + +jest.mock('listr2', () => { + return { + // Return a constructor function, since we're calling `new` on Listr + Listr: jest.fn().mockImplementation((tasks: Array) => { + return { + run: async () => { + mockExecutedTaskTitles = [] + mockSkippedTaskTitles = [] + + for (const task of tasks) { + const skip = + typeof task.skip === 'function' ? task.skip : () => task.skip + + if (skip()) { + mockSkippedTaskTitles.push(task.title) + } else { + mockExecutedTaskTitles.push(task.title) + await task.task() + } + } + }, + } + }), + } +}) + +import path from 'node:path' + +import { vol } from 'memfs' + +import { handler } from '../trustedDocumentsHandler' + +// Set up RWJS_CWD +let original_RWJS_CWD: string | undefined +const APP_PATH = '/redwood-app' + +const tomlFixtures: Record = {} + +beforeAll(() => { + original_RWJS_CWD = process.env.RWJS_CWD + process.env.RWJS_CWD = APP_PATH + + const actualFs = jest.requireActual('fs') + const tomlFixturesPath = path.join(__dirname, '__fixtures__', 'toml') + + tomlFixtures.default = actualFs.readFileSync( + path.join(tomlFixturesPath, 'default.toml'), + 'utf-8' + ) + + tomlFixtures.fragments = actualFs.readFileSync( + path.join(tomlFixturesPath, 'fragments.toml'), + 'utf-8' + ) + + tomlFixtures.fragmentsNoSpaceEquals = actualFs.readFileSync( + path.join(tomlFixturesPath, 'fragments_no_space_equals.toml'), + 'utf-8' + ) + + tomlFixtures.trustedDocsAlreadySetup = actualFs.readFileSync( + path.join(tomlFixturesPath, 'trusted_docs_already_setup.toml'), + 'utf-8' + ) + + tomlFixtures.trustedDocsNoSpaceEquals = actualFs.readFileSync( + path.join(tomlFixturesPath, 'trusted_docs_no_space_equals.toml'), + 'utf-8' + ) + + tomlFixtures.trustedDocsFragmentsAlreadySetup = actualFs.readFileSync( + path.join(tomlFixturesPath, 'trusted_docs_fragments_already_setup.toml'), + 'utf-8' + ) + + tomlFixtures.trustedDocsCommentedGraphql = actualFs.readFileSync( + path.join(tomlFixturesPath, 'trusted_docs_commented_graphql.toml'), + 'utf-8' + ) +}) + +afterAll(() => { + process.env.RWJS_CWD = original_RWJS_CWD + jest.resetAllMocks() + jest.resetModules() +}) // Silence console.info console.info = jest.fn() -describe('Trusted documents setup tests', () => { +describe('Trusted documents setup', () => { + it('runs all tasks', async () => { + vol.fromJSON({ 'redwood.toml': '', 'web/src/App.tsx': '' }, APP_PATH) + + await handler({ force: false }) + + expect(mockExecutedTaskTitles).toMatchInlineSnapshot(` + [ + "Update Redwood Project Configuration to enable GraphQL Trusted Documents ...", + "Generating Trusted Documents store ...", + "Configuring the GraphQL Handler to use a Trusted Documents store ...", + ] + `) + }) + describe('Project toml configuration updates', () => { describe('default toml where no graphql or trusted documents is setup', () => { - it('updates the toml file with graphql and trusted documents enabled', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'default.toml' + it('updates the toml file with graphql and trusted documents enabled', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.default, + 'api/src/functions/graphql.js': '', + }, + APP_PATH ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toMatchSnapshot() }) }) describe('default toml where graphql fragments are already setup', () => { - it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'fragments.toml' + it('updates the toml file with graphql and trusted documents enabled and keeps fragments', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.fragments, + 'api/src/functions/graphql.ts': '', + }, + APP_PATH ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toMatchSnapshot() }) }) describe('default toml where graphql fragments are already setup using no spaces', () => { - it('updates the toml file with graphql and trusted documents enabled and keeps fragments', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'fragments_no_space_equals.toml' + it('updates the toml file with graphql and trusted documents enabled and keeps fragments', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.fragmentsNoSpaceEquals, + 'api/src/functions/graphql.js': '', + }, + APP_PATH ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toMatchSnapshot() }) }) describe('default toml where graphql trusted documents are already setup', () => { - it('makes no changes as trusted documents are already setup', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'trusted_docs_already_setup.toml' + it('makes no changes as trusted documents are already setup', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.trustedDocsAlreadySetup, + 'api/src/functions/graphql.js': '', + }, + APP_PATH + ) + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( + tomlFixtures.trustedDocsAlreadySetup ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() }) }) describe('default toml where graphql trusted documents are already setup using no spaces', () => { - it('makes no changes as trusted documents are already setup', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'trusted_docs_already_setup_no_space_equals.toml' + it('makes no changes as trusted documents are already setup', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.trustedDocsNoSpaceEquals, + 'api/src/functions/graphql.js': '', + }, + APP_PATH + ) + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( + tomlFixtures.trustedDocsNoSpaceEquals ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() }) }) describe('default toml where graphql trusted documents and fragments are already setup', () => { - it('makes no changes as trusted documents are already setup', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'trusted_docs_and_fragments_already_setup.toml' + it('makes no changes as trusted documents are already setup', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.trustedDocsFragmentsAlreadySetup, + 'api/src/functions/graphql.js': '', + }, + APP_PATH ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() - }) - }) - describe('toml where graphql section is commented out', () => { - it('adds a new section with `trustedDocuments = true`', () => { - const redwoodTomlPath = path.join( - __dirname, - '__fixtures__', - 'toml', - 'trusted_docs_commented_graphql.toml' + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toEqual( + tomlFixtures.trustedDocsFragmentsAlreadySetup ) - const result = updateRedwoodToml(redwoodTomlPath) - expect(result).toMatchSnapshot() }) }) - }) - describe('GraphQL Handler updates', () => { - describe('default handler where the trusted document store is not configured', () => { - it('updates the handler with the trusted document store', async () => { - const handlerPath = path.join( - __dirname, - '__fixtures__', - 'graphQLHandler', - 'trustedDocumentSetupHandler.js' + describe('toml where graphql section is commented out', () => { + it('adds a new section with `trustedDocuments = true`', async () => { + vol.fromJSON( + { + 'redwood.toml': tomlFixtures.trustedDocsCommentedGraphql, + 'api/src/functions/graphql.js': '', + }, + APP_PATH ) - const updateResult = updateGraphQLHandler(handlerPath) - expect(updateResult?.graphQlSourceFileChanged).toBe(false) - expect(updateResult?.graphQlSourceFile.getFullText()).toMatchSnapshot() + + await handler({ force: false }) + + expect(vol.toJSON()[APP_PATH + '/redwood.toml']).toMatchSnapshot() }) }) }) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts new file mode 100644 index 000000000000..b862074f0fa0 --- /dev/null +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts @@ -0,0 +1,57 @@ +import type { FileInfo, API } from 'jscodeshift' + +export default function transform(file: FileInfo, api: API) { + const j = api.jscodeshift + const root = j(file.source) + + const allImports = root.find(j.ImportDeclaration) + + const hasStoreImport = allImports.some((i) => { + return i.get('source').value.value === 'src/lib/trustedDocumentsStore' + }) + + if (!hasStoreImport) { + allImports + .at(-1) + .insertAfter( + j.importDeclaration( + [j.importSpecifier(j.identifier('store'))], + j.literal('src/lib/trustedDocumentsStore') + ) + ) + } + + const createGraphQLHandlerCalls = root.find(j.CallExpression, { + callee: { + name: 'createGraphQLHandler', + }, + }) + + const existingTrustedDocumentsProperty = createGraphQLHandlerCalls.find( + j.ObjectProperty, + { + key: { + name: 'trustedDocuments', + }, + } + ) + + if (existingTrustedDocumentsProperty.length === 0) { + const storeProperty = j.objectProperty( + j.identifier('store'), + j.identifier('store') + ) + storeProperty.shorthand = true + + createGraphQLHandlerCalls + .get(0) + .node.arguments[0].properties.push( + j.objectProperty( + j.identifier('trustedDocuments'), + j.objectExpression([storeProperty]) + ) + ) + } + + return root.toSource() +} diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index 6816ae77b724..b19fcac83e0d 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -1,87 +1,17 @@ -import fs from 'fs' +import fs from 'node:fs' +import path from 'node:path' import toml from '@iarna/toml' import execa from 'execa' import { Listr } from 'listr2' -import { Project, SyntaxKind, type PropertyAssignment } from 'ts-morph' +import { format } from 'prettier' -import { prettifyFile } from '@redwoodjs/cli-helpers' +import { prettierOptions } from '@redwoodjs/cli-helpers' import { getConfigPath, getPaths } from '@redwoodjs/project-config' -export function updateGraphQLHandler(graphQlSourcePath: string) { - // add import - const project = new Project() +import { runTransform } from '../fragments/runTransform' - const graphQlSourceFile = - project.addSourceFileAtPathIfExists(graphQlSourcePath) - - if (!graphQlSourceFile) { - console.error( - `Unable to determine the GraphQL Handler source path for: ${graphQlSourcePath}` - ) - return - } - - let graphQlSourceFileChanged = false - let identified = false - - const imports = graphQlSourceFile.getImportDeclarations() - if ( - !imports.some( - (i) => i.getModuleSpecifierValue() === 'src/lib/trustedDocumentsStore' - ) - ) { - graphQlSourceFile.addImportDeclaration({ - moduleSpecifier: 'src/lib/trustedDocumentsStore', - namedImports: ['store'], - }) - graphQlSourceFileChanged = true - } - - // add "trustedDocuments" option to `createGraphQLHandler` call - graphQlSourceFile - .getDescendantsOfKind(SyntaxKind.CallExpression) - .forEach((expr) => { - if (identified) { - return - } - - if ( - expr.getExpression().asKind(SyntaxKind.Identifier)?.getText() === - 'createGraphQLHandler' - ) { - const arg = expr - .getArguments()[0] - ?.asKind(SyntaxKind.ObjectLiteralExpression) - if (arg) { - identified = true - const props = arg.getProperties() - const trustedDocsProp = props.find( - (p): p is PropertyAssignment => - p.asKind(SyntaxKind.PropertyAssignment)?.getName() === - 'trustedDocuments' - ) - if (!trustedDocsProp) { - arg.addPropertyAssignment({ - name: 'trustedDocuments', - initializer: '{ store }', - }) - graphQlSourceFileChanged = true - } - } - } - }) - - if (!identified) { - console.warn( - 'Unable to determine how to setup Trusted Documents in the GraphQL Handler. Please add it manually following https://docs.redwoodjs.com/docs/graphql/trusted-documents#configure-graphql-handler' - ) - } - - return { graphQlSourceFileChanged, graphQlSourceFile, project } -} - -export function updateRedwoodToml(redwoodTomlPath: string) { +function updateRedwoodToml(redwoodTomlPath: string) { const originalTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') const redwoodTomlContent = fs.readFileSync(redwoodTomlPath, 'utf-8') // Can't type toml.parse because this PR has not been included in a released yet @@ -146,17 +76,6 @@ export function updateRedwoodToml(redwoodTomlPath: string) { return { newConfig: newTomlContent, trustedDocumentsExists: false } } -async function configureGraphQLHandlerWithStore() { - const graphQlSourcePath = getPaths().api.graphql - - const updateResult = updateGraphQLHandler(graphQlSourcePath) - - if (updateResult?.graphQlSourceFileChanged) { - await updateResult?.project.save() - prettifyFile(graphQlSourcePath, 'babel-ts') - } -} - export async function handler({ force }: { force: boolean }) { const tasks = new Listr( [ @@ -184,7 +103,24 @@ export async function handler({ force }: { force: boolean }) { title: 'Configuring the GraphQL Handler to use a Trusted Documents store ...', task: async () => { - return configureGraphQLHandlerWithStore() + const transformResult = await runTransform({ + transformPath: path.join(__dirname, 'graphqlTransform.js'), + targetPaths: [getPaths().web.app], + }) + + if (transformResult.error) { + throw new Error(transformResult.error) + } + + const appPath = getPaths().web.app + const source = fs.readFileSync(appPath, 'utf-8') + + const prettifiedApp = format(source, { + ...prettierOptions(), + parser: 'babel-ts', + }) + + fs.writeFileSync(getPaths().web.app, prettifiedApp, 'utf-8') }, }, ], From c8f0bbbf6acba03e5b7b492472cf1a941ec14c5b Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Fri, 12 Jan 2024 10:36:16 +0100 Subject: [PATCH 22/23] Fix paths --- .../trustedDocuments/graphqlTransform.ts | 7 +++++++ .../trustedDocuments/trustedDocuments.ts | 2 +- .../trustedDocuments/trustedDocumentsHandler.ts | 17 ++++++++++++----- 3 files changed, 20 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts index b862074f0fa0..7a3e636d75fb 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/graphqlTransform.ts @@ -27,6 +27,13 @@ export default function transform(file: FileInfo, api: API) { }, }) + if (createGraphQLHandlerCalls.length === 0) { + throw new Error( + "Error updating your graphql handler function. You'll have to do it manually. " + + "(Couldn't find a call to `createGraphQLHandler`)" + ) + } + const existingTrustedDocumentsProperty = createGraphQLHandlerCalls.find( j.ObjectProperty, { diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts index 22362293848f..d561ce51e886 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocuments.ts @@ -20,6 +20,6 @@ export async function handler({ force }: { force: boolean }) { force, }) - const { handler } = await import('./trustedDocumentsHandler') + const { handler } = await import('./trustedDocumentsHandler.js') return handler({ force }) } diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts index b19fcac83e0d..fe93c5d6fc22 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/trustedDocumentsHandler.ts @@ -7,7 +7,7 @@ import { Listr } from 'listr2' import { format } from 'prettier' import { prettierOptions } from '@redwoodjs/cli-helpers' -import { getConfigPath, getPaths } from '@redwoodjs/project-config' +import { getConfigPath, getPaths, resolveFile } from '@redwoodjs/project-config' import { runTransform } from '../fragments/runTransform' @@ -103,24 +103,31 @@ export async function handler({ force }: { force: boolean }) { title: 'Configuring the GraphQL Handler to use a Trusted Documents store ...', task: async () => { + const graphqlPath = resolveFile( + path.join(getPaths().api.functions, 'graphql') + ) + + if (!graphqlPath) { + throw new Error('Could not find a GraphQL handler in your project.') + } + const transformResult = await runTransform({ transformPath: path.join(__dirname, 'graphqlTransform.js'), - targetPaths: [getPaths().web.app], + targetPaths: [graphqlPath], }) if (transformResult.error) { throw new Error(transformResult.error) } - const appPath = getPaths().web.app - const source = fs.readFileSync(appPath, 'utf-8') + const source = fs.readFileSync(graphqlPath, 'utf-8') const prettifiedApp = format(source, { ...prettierOptions(), parser: 'babel-ts', }) - fs.writeFileSync(getPaths().web.app, prettifiedApp, 'utf-8') + fs.writeFileSync(graphqlPath, prettifiedApp, 'utf-8') }, }, ], From f5af9388f337d8583be1afdcf8fc6756dd94d308 Mon Sep 17 00:00:00 2001 From: Tobbe Lundberg Date: Fri, 12 Jan 2024 10:55:48 +0100 Subject: [PATCH 23/23] Update filepath in test --- .../trustedDocuments/__tests__/trustedDocuments.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts index a00837f8ab4e..7e026ca59ab4 100644 --- a/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts +++ b/packages/cli/src/commands/setup/graphql/features/trustedDocuments/__tests__/trustedDocuments.test.ts @@ -105,7 +105,7 @@ console.info = jest.fn() describe('Trusted documents setup', () => { it('runs all tasks', async () => { - vol.fromJSON({ 'redwood.toml': '', 'web/src/App.tsx': '' }, APP_PATH) + vol.fromJSON({ 'redwood.toml': '', 'api/src/functions/graphql.js': '' }, APP_PATH) await handler({ force: false })