From 8b253224997b59ac74d72813214dfc224f526c0a Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 10:53:48 +0100 Subject: [PATCH 01/16] When a dependency is optional or has peerDependenciesMeta set to optional, make sure it doesn't crash when it is not found when calling resolveDependenciesSync --- .changeset/cold-eggs-visit.md | 5 ++++ .../dist/utils/resolveDependenciesSync.js | 26 ++++++++++++++--- .../src/utils/resolveDependenciesSync.ts | 29 +++++++++++++++---- 3 files changed, 51 insertions(+), 9 deletions(-) create mode 100644 .changeset/cold-eggs-visit.md diff --git a/.changeset/cold-eggs-visit.md b/.changeset/cold-eggs-visit.md new file mode 100644 index 0000000000..6b777b0dcf --- /dev/null +++ b/.changeset/cold-eggs-visit.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/next-config': patch +--- + +When a dependency is optional or has peerDependenciesMeta set to optional, make sure it doesn't crash when it is not found when calling resolveDependenciesSync diff --git a/packagesDev/next-config/dist/utils/resolveDependenciesSync.js b/packagesDev/next-config/dist/utils/resolveDependenciesSync.js index 36b09e0e08..cf3615757c 100644 --- a/packagesDev/next-config/dist/utils/resolveDependenciesSync.js +++ b/packagesDev/next-config/dist/utils/resolveDependenciesSync.js @@ -35,14 +35,32 @@ function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, ? !(e.length >= 0 && e.some((v) => name.startsWith(v))) : false)), ]; + const optionalPeerDependencies = Object.entries(packageJson.peerDependenciesMeta ?? {}) + .filter(([_, v]) => v?.optional) + .map(([key]) => key); + const optionalDependencies = Object.keys(packageJson.optionalDependencies ?? {}); + const optional = new Set([...optionalPeerDependencies, ...optionalDependencies]); + const availableDependencies = dependencies.filter((dep) => { + if (optional.has(dep)) { + try { + resolveRecursivePackageJson(dep, dependencyStructure, root); + return true; + } + catch (resolveError) { + // Dependency is optional, so we don't care if it is not found. + return false; + } + } + else { + resolveRecursivePackageJson(dep, dependencyStructure, root); + return true; + } + }); const name = isRoot ? '.' : packageJson.name; dependencyStructure[name] = { dirName: node_path_1.default.dirname(node_path_1.default.relative(process.cwd(), fileName)), - dependencies, + dependencies: availableDependencies, }; - dependencies.forEach((dep) => { - resolveRecursivePackageJson(dep, dependencyStructure, root); - }); return dependencyStructure; } /** diff --git a/packagesDev/next-config/src/utils/resolveDependenciesSync.ts b/packagesDev/next-config/src/utils/resolveDependenciesSync.ts index d444998e92..bd68a1e000 100644 --- a/packagesDev/next-config/src/utils/resolveDependenciesSync.ts +++ b/packagesDev/next-config/src/utils/resolveDependenciesSync.ts @@ -16,6 +16,7 @@ function resolveRecursivePackageJson( additionalDependencies: string[] = [], ) { const isRoot = dependencyPath === root + const fileName = require.resolve(path.join(dependencyPath, 'package.json')) const packageJsonFile = fs.readFileSync(fileName, 'utf-8').toString() const packageJson = JSON.parse(packageJsonFile) as PackageJson @@ -48,16 +49,34 @@ function resolveRecursivePackageJson( ), ] + const optionalPeerDependencies = Object.entries(packageJson.peerDependenciesMeta ?? {}) + .filter(([_, v]) => v?.optional) + .map(([key]) => key) + + const optionalDependencies = Object.keys(packageJson.optionalDependencies ?? {}) + const optional = new Set([...optionalPeerDependencies, ...optionalDependencies]) + + const availableDependencies = dependencies.filter((dep) => { + if (optional.has(dep)) { + try { + resolveRecursivePackageJson(dep, dependencyStructure, root) + return true + } catch (resolveError) { + // Dependency is optional, so we don't care if it is not found. + return false + } + } else { + resolveRecursivePackageJson(dep, dependencyStructure, root) + return true + } + }) + const name = isRoot ? '.' : packageJson.name dependencyStructure[name] = { dirName: path.dirname(path.relative(process.cwd(), fileName)), - dependencies, + dependencies: availableDependencies, } - dependencies.forEach((dep) => { - resolveRecursivePackageJson(dep, dependencyStructure, root) - }) - return dependencyStructure } From 30b7356790efbac0f0017ef61cb1619b920100ab Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 11:06:57 +0100 Subject: [PATCH 02/16] Solve issue where withGraphCommerce had a hard dependency on Magento specific configurations --- .changeset/late-paws-smell.md | 5 +++++ packagesDev/next-config/dist/withGraphCommerce.js | 12 +++++++++--- packagesDev/next-config/src/withGraphCommerce.ts | 14 +++++++++++--- 3 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 .changeset/late-paws-smell.md diff --git a/.changeset/late-paws-smell.md b/.changeset/late-paws-smell.md new file mode 100644 index 0000000000..f2e3261f61 --- /dev/null +++ b/.changeset/late-paws-smell.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/next-config': patch +--- + +Solve issue where withGraphCommerce had a hard dependency on Magento specific configurations diff --git a/packagesDev/next-config/dist/withGraphCommerce.js b/packagesDev/next-config/dist/withGraphCommerce.js index 53f4b27c69..fa6b0b1947 100644 --- a/packagesDev/next-config/dist/withGraphCommerce.js +++ b/packagesDev/next-config/dist/withGraphCommerce.js @@ -56,11 +56,15 @@ function withGraphCommerce(nextConfig, cwd = process.cwd()) { images: { ...nextConfig.images, remotePatterns: [ - { hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname }, + 'magentoEndpoint' in graphcommerceConfig + ? { + hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname, + } + : undefined, { hostname: '**.graphassets.com' }, { hostname: '*.graphcommerce.org' }, ...(nextConfig.images?.remotePatterns ?? []), - ], + ].filter((v) => !!v), }, redirects: async () => { const redirects = (await nextConfig.redirects?.()) ?? []; @@ -82,7 +86,9 @@ function withGraphCommerce(nextConfig, cwd = process.cwd()) { if (Array.isArray(rewrites)) { rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] }; } - if (graphcommerceConfig.productRoute && graphcommerceConfig.productRoute !== '/p/') { + if ('productRoute' in graphcommerceConfig && + typeof graphcommerceConfig.productRoute === 'string' && + graphcommerceConfig.productRoute !== '/p/') { rewrites.beforeFiles.push({ source: `${graphcommerceConfig.productRoute ?? '/p/'}:path*`, destination: '/p/:path*', diff --git a/packagesDev/next-config/src/withGraphCommerce.ts b/packagesDev/next-config/src/withGraphCommerce.ts index 51e6524f54..97eb58c9fa 100644 --- a/packagesDev/next-config/src/withGraphCommerce.ts +++ b/packagesDev/next-config/src/withGraphCommerce.ts @@ -70,11 +70,15 @@ export function withGraphCommerce(nextConfig: NextConfig, cwd: string = process. images: { ...nextConfig.images, remotePatterns: [ - { hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname }, + 'magentoEndpoint' in graphcommerceConfig + ? { + hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname, + } + : undefined, { hostname: '**.graphassets.com' }, { hostname: '*.graphcommerce.org' }, ...(nextConfig.images?.remotePatterns ?? []), - ], + ].filter((v) => !!v), }, redirects: async () => { const redirects = (await nextConfig.redirects?.()) ?? [] @@ -103,7 +107,11 @@ export function withGraphCommerce(nextConfig: NextConfig, cwd: string = process. rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] } } - if (graphcommerceConfig.productRoute && graphcommerceConfig.productRoute !== '/p/') { + if ( + 'productRoute' in graphcommerceConfig && + typeof graphcommerceConfig.productRoute === 'string' && + graphcommerceConfig.productRoute !== '/p/' + ) { rewrites.beforeFiles.push({ source: `${graphcommerceConfig.productRoute ?? '/p/'}:path*`, destination: '/p/:path*', From 2c79a4cba2779bc367104ebb13e6c0d6feb6574f Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 11:09:40 +0100 Subject: [PATCH 03/16] Remove redirects for `/product/$type/[url]` routes, those haven't been used for years anymore. --- .changeset/eighty-pianos-protect.md | 5 +++++ .../next-config/dist/withGraphCommerce.js | 15 -------------- .../next-config/src/withGraphCommerce.ts | 20 ------------------- 3 files changed, 5 insertions(+), 35 deletions(-) create mode 100644 .changeset/eighty-pianos-protect.md diff --git a/.changeset/eighty-pianos-protect.md b/.changeset/eighty-pianos-protect.md new file mode 100644 index 0000000000..a21b68d253 --- /dev/null +++ b/.changeset/eighty-pianos-protect.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/next-config': patch +--- + +Remove redirects for `/product/$type/[url]` routes, those haven't been used for years anymore. diff --git a/packagesDev/next-config/dist/withGraphCommerce.js b/packagesDev/next-config/dist/withGraphCommerce.js index fa6b0b1947..961cd10df0 100644 --- a/packagesDev/next-config/dist/withGraphCommerce.js +++ b/packagesDev/next-config/dist/withGraphCommerce.js @@ -66,21 +66,6 @@ function withGraphCommerce(nextConfig, cwd = process.cwd()) { ...(nextConfig.images?.remotePatterns ?? []), ].filter((v) => !!v), }, - redirects: async () => { - const redirects = (await nextConfig.redirects?.()) ?? []; - const destination = `${graphcommerceConfig.productRoute ?? '/p/'}:url*`; - redirects.push(...[ - { source: '/product/bundle/:url*', destination, permanent: true }, - { source: '/product/configurable/:url*', destination, permanent: true }, - { source: '/product/downloadable/:url*', destination, permanent: true }, - { source: '/product/grouped/:url*', destination, permanent: true }, - { source: '/product/virtual/:url*', destination, permanent: true }, - { source: '/customer/account', destination: '/account', permanent: true }, - ]); - if (destination !== '/product/:url*') - redirects.push({ source: '/product/:url*', destination, permanent: true }); - return redirects; - }, rewrites: async () => { let rewrites = (await nextConfig.rewrites?.()) ?? []; if (Array.isArray(rewrites)) { diff --git a/packagesDev/next-config/src/withGraphCommerce.ts b/packagesDev/next-config/src/withGraphCommerce.ts index 97eb58c9fa..07b1e31eb8 100644 --- a/packagesDev/next-config/src/withGraphCommerce.ts +++ b/packagesDev/next-config/src/withGraphCommerce.ts @@ -80,26 +80,6 @@ export function withGraphCommerce(nextConfig: NextConfig, cwd: string = process. ...(nextConfig.images?.remotePatterns ?? []), ].filter((v) => !!v), }, - redirects: async () => { - const redirects = (await nextConfig.redirects?.()) ?? [] - - const destination = `${graphcommerceConfig.productRoute ?? '/p/'}:url*` - - redirects.push( - ...[ - { source: '/product/bundle/:url*', destination, permanent: true }, - { source: '/product/configurable/:url*', destination, permanent: true }, - { source: '/product/downloadable/:url*', destination, permanent: true }, - { source: '/product/grouped/:url*', destination, permanent: true }, - { source: '/product/virtual/:url*', destination, permanent: true }, - { source: '/customer/account', destination: '/account', permanent: true }, - ], - ) - if (destination !== '/product/:url*') - redirects.push({ source: '/product/:url*', destination, permanent: true }) - - return redirects - }, rewrites: async () => { let rewrites = (await nextConfig.rewrites?.()) ?? [] From 494a6a5a357a0409a5e703c74f1109844dc7aca4 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 11:24:41 +0100 Subject: [PATCH 04/16] Add compiled js --- .../dist/fragment-resolver.js | 5 ++++- .../graphql-codegen-near-operation-file/dist/index.js | 2 +- .../dist/resolve-document-imports.js | 3 ++- .../graphql-codegen-near-operation-file/dist/utils.js | 3 ++- packagesDev/next-config/dist/commands/codegen.js | 6 +++--- packagesDev/next-config/dist/commands/copyFiles.js | 10 +++++----- .../next-config/dist/config/commands/generateConfig.js | 1 - .../dist/config/utils/mergeEnvIntoConfig.js | 4 +--- .../next-config/dist/interceptors/writeInterceptors.js | 2 +- 9 files changed, 19 insertions(+), 17 deletions(-) diff --git a/packagesDev/graphql-codegen-near-operation-file/dist/fragment-resolver.js b/packagesDev/graphql-codegen-near-operation-file/dist/fragment-resolver.js index 0433042f70..3c3eb7d2ae 100644 --- a/packagesDev/graphql-codegen-near-operation-file/dist/fragment-resolver.js +++ b/packagesDev/graphql-codegen-near-operation-file/dist/fragment-resolver.js @@ -78,7 +78,10 @@ ${duplicateFragmentNames.join('\n')}\n\n`); } return registry; } -/** Builds a fragment "resolver" that collects `externalFragments` definitions and `fragmentImportStatements` */ +/** + * Builds a fragment "resolver" that collects `externalFragments` definitions and + * `fragmentImportStatements` + */ function buildFragmentResolver(collectorOptions, presetOptions, schemaObject) { const fragmentRegistry = buildFragmentRegistry(collectorOptions, presetOptions, schemaObject); const { baseOutputDir } = presetOptions; diff --git a/packagesDev/graphql-codegen-near-operation-file/dist/index.js b/packagesDev/graphql-codegen-near-operation-file/dist/index.js index fc85625070..1dfb9398e5 100644 --- a/packagesDev/graphql-codegen-near-operation-file/dist/index.js +++ b/packagesDev/graphql-codegen-near-operation-file/dist/index.js @@ -4,9 +4,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.preset = exports.resolveDocumentImports = void 0; +const path_1 = require("path"); const add_1 = __importDefault(require("@graphql-codegen/add")); const graphql_1 = require("graphql"); -const path_1 = require("path"); const env_1 = require("./directive/env"); const injectable_1 = require("./directive/injectable"); const resolve_document_imports_1 = require("./resolve-document-imports"); diff --git a/packagesDev/graphql-codegen-near-operation-file/dist/resolve-document-imports.js b/packagesDev/graphql-codegen-near-operation-file/dist/resolve-document-imports.js index 99f2152a6e..769528a23d 100644 --- a/packagesDev/graphql-codegen-near-operation-file/dist/resolve-document-imports.js +++ b/packagesDev/graphql-codegen-near-operation-file/dist/resolve-document-imports.js @@ -35,10 +35,11 @@ var __importStar = (this && this.__importStar) || (function () { })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveDocumentImports = resolveDocumentImports; +/* eslint-disable import/no-cycle */ +const path_1 = require("path"); const plugin_helpers_1 = require("@graphql-codegen/plugin-helpers"); const visitor_plugin_common_1 = require("@graphql-codegen/visitor-plugin-common"); const graphql_1 = require("graphql"); -const path_1 = require("path"); const fragment_resolver_1 = __importStar(require("./fragment-resolver")); const utils_1 = require("./utils"); function getFragmentName(documentFile) { diff --git a/packagesDev/graphql-codegen-near-operation-file/dist/utils.js b/packagesDev/graphql-codegen-near-operation-file/dist/utils.js index 3848202f02..0ba2d1259f 100644 --- a/packagesDev/graphql-codegen-near-operation-file/dist/utils.js +++ b/packagesDev/graphql-codegen-near-operation-file/dist/utils.js @@ -6,9 +6,10 @@ Object.defineProperty(exports, "__esModule", { value: true }); exports.defineFilepathSubfolder = defineFilepathSubfolder; exports.appendExtensionToFilePath = appendExtensionToFilePath; exports.extractExternalFragmentsInUse = extractExternalFragmentsInUse; +/* eslint-disable import/no-cycle */ +const path_1 = require("path"); const graphql_1 = require("graphql"); const parse_filepath_1 = __importDefault(require("parse-filepath")); -const path_1 = require("path"); function defineFilepathSubfolder(baseFilePath, folder) { const parsedPath = (0, parse_filepath_1.default)(baseFilePath); return (0, path_1.join)(parsedPath.dir, folder, parsedPath.base).replace(/\\/g, '/'); diff --git a/packagesDev/next-config/dist/commands/codegen.js b/packagesDev/next-config/dist/commands/codegen.js index e557b2f201..3f6596fca8 100644 --- a/packagesDev/next-config/dist/commands/codegen.js +++ b/packagesDev/next-config/dist/commands/codegen.js @@ -7,12 +7,12 @@ const copyFiles_1 = require("./copyFiles"); /** Run all code generation steps in sequence */ async function codegen() { // Copy files from packages to project - console.log('🔄 Copying files from packages to project...'); + console.info('🔄 Copying files from packages to project...'); await (0, copyFiles_1.copyFiles)(); // Generate GraphCommerce config types - console.log('⚙️ Generating GraphCommerce config types...'); + console.info('⚙️ Generating GraphCommerce config types...'); await (0, generateConfig_1.generateConfig)(); // Generate interceptors - console.log('🔌 Generating interceptors...'); + console.info('🔌 Generating interceptors...'); await (0, codegenInterceptors_1.codegenInterceptors)(); } diff --git a/packagesDev/next-config/dist/commands/copyFiles.js b/packagesDev/next-config/dist/commands/copyFiles.js index 44688d2614..cf838ef1bb 100644 --- a/packagesDev/next-config/dist/commands/copyFiles.js +++ b/packagesDev/next-config/dist/commands/copyFiles.js @@ -12,7 +12,7 @@ const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync"); // Add debug logging helper const debug = (...args) => { if (process.env.DEBUG) - console.log('[copy-files]', ...args); + console.info('[copy-files]', ...args); }; // Add constants for the magic comments const MANAGED_BY_GC = '// managed by: graphcommerce'; @@ -185,7 +185,7 @@ Found in packages: return; } if (management === 'unmanaged') { - console.log(`Note: File ${file} has been modified. Add '${MANAGED_LOCALLY.trim()}' at the top to manage it locally.`); + console.info(`Note: File ${file} has been modified. Add '${MANAGED_LOCALLY.trim()}' at the top to manage it locally.`); debug(`File ${file} doesn't have management comment, skipping`); return; } @@ -197,7 +197,7 @@ Found in packages: Source: ${sourcePath}`); process.exit(1); } - console.log(`Creating new file: ${file}\nSource: ${sourcePath}`); + console.info(`Creating new file: ${file}\nSource: ${sourcePath}`); debug('File does not exist yet'); } // Skip if content is identical (including magic comment) @@ -209,7 +209,7 @@ Source: ${sourcePath}`); // Copy the file with magic comment await promises_1.default.writeFile(targetPath, contentWithComment); if (targetContent) { - console.log(`Updated managed file: ${file}`); + console.info(`Updated managed file: ${file}`); debug(`Overwrote existing file: ${file}`); } // If the file is managed by GraphCommerce (new or updated), add it to managedFiles @@ -263,7 +263,7 @@ Source: ${sourcePath}`); // Then try to remove the file try { await promises_1.default.unlink(filePath); - console.log(`Removed managed file: ${file}`); + console.info(`Removed managed file: ${file}`); debug(`Removed file: ${file}`); } catch (err) { diff --git a/packagesDev/next-config/dist/config/commands/generateConfig.js b/packagesDev/next-config/dist/config/commands/generateConfig.js index 68f35751df..469108af1b 100644 --- a/packagesDev/next-config/dist/config/commands/generateConfig.js +++ b/packagesDev/next-config/dist/config/commands/generateConfig.js @@ -4,7 +4,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) { }; Object.defineProperty(exports, "__esModule", { value: true }); exports.generateConfig = generateConfig; -// eslint-disable-next-line import/no-extraneous-dependencies const fs_1 = require("fs"); const cli_1 = require("@graphql-codegen/cli"); const core_1 = require("@swc/core"); diff --git a/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js b/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js index 4e1e39187c..fff97be9f7 100644 --- a/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js +++ b/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js @@ -150,9 +150,7 @@ function mergeEnvIntoConfig(schema, config, env) { function formatAppliedEnv(applyResult) { let hasError = false; let hasWarning = false; - const lines = applyResult.map(({ from, to, envValue, envVar, dotVar, error, warning }) => { - const fromFmt = chalk_1.default.red(JSON.stringify(from)); - const toFmt = chalk_1.default.green(JSON.stringify(to)); + const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => { const envVariableFmt = `${envVar}`; const dotVariableFmt = chalk_1.default.bold.underline(`${dotVar}`); const baseLog = `${envVariableFmt} => ${dotVariableFmt}`; diff --git a/packagesDev/next-config/dist/interceptors/writeInterceptors.js b/packagesDev/next-config/dist/interceptors/writeInterceptors.js index b1b59b8442..2604ea8852 100644 --- a/packagesDev/next-config/dist/interceptors/writeInterceptors.js +++ b/packagesDev/next-config/dist/interceptors/writeInterceptors.js @@ -5,9 +5,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", { value: true }); exports.writeInterceptors = writeInterceptors; // eslint-disable-next-line import/no-extraneous-dependencies -const glob_1 = require("glob"); const promises_1 = __importDefault(require("node:fs/promises")); const path_1 = __importDefault(require("path")); +const glob_1 = require("glob"); const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync"); function checkFileExists(file) { return promises_1.default From 5ffa0ee1d620f4f1c38bc5df36cbd527bcc43cf9 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 12:56:30 +0100 Subject: [PATCH 05/16] Migrated `@graphcommerce/next-config` package to `"type": "module"` --- .changeset/wicked-stingrays-buy.md | 5 + .../config/utils/replaceConfigInString.ts | 1 - .../next-config/dist/commands/codegen.js | 18 - .../next-config/dist/commands/copyFiles.js | 297 -- .../dist/config/commands/exportConfig.js | 16 - .../dist/config/commands/generateConfig.js | 56 - .../next-config/dist/config/demoConfig.js | 52 - packagesDev/next-config/dist/config/index.js | 19 - .../next-config/dist/config/loadConfig.js | 62 - .../dist/config/utils/configToImportMeta.js | 39 - .../next-config/dist/config/utils/diff.js | 33 - .../dist/config/utils/exportConfigToEnv.js | 31 - .../dist/config/utils/mergeEnvIntoConfig.js | 182 - .../config/utils/replaceConfigInString.js | 12 - .../dist/config/utils/rewriteLegacyEnv.js | 115 - .../next-config/dist/generated/config.js | 307 +- packagesDev/next-config/dist/index.js | 3495 ++++++++++++++++- .../dist/interceptors/InterceptorPlugin.js | 108 - .../dist/interceptors/RenameVisitor.js | 19 - .../next-config/dist/interceptors/Visitor.js | 1414 ------- .../commands/codegenInterceptors.js | 22 - .../dist/interceptors/extractExports.js | 159 - .../dist/interceptors/findOriginalSource.js | 103 - .../dist/interceptors/findPlugins.js | 68 - .../dist/interceptors/generateInterceptor.js | 219 -- .../dist/interceptors/generateInterceptors.js | 56 - .../dist/interceptors/parseStructure.js | 84 - .../next-config/dist/interceptors/swc.js | 15 - .../dist/interceptors/writeInterceptors.js | 44 - .../next-config/dist/utils/PackagesSort.js | 7 - .../next-config/dist/utils/TopologicalSort.js | 87 - .../next-config/dist/utils/isMonorepo.js | 47 - .../next-config/dist/utils/packageRoots.js | 31 - .../dist/utils/resolveDependenciesSync.js | 96 - .../dist/utils/resolveDependency.js | 70 - packagesDev/next-config/dist/utils/sig.js | 34 - .../next-config/dist/withGraphCommerce.js | 153 - packagesDev/next-config/package.json | 39 +- .../src/config/commands/generateConfig.ts | 18 +- .../next-config/src/config/demoConfig.ts | 1 - .../next-config/src/config/loadConfig.ts | 1 - .../src/config/utils/mergeEnvIntoConfig.ts | 14 +- .../src/config/utils/rewriteLegacyEnv.ts | 4 +- .../next-config/src/generated/config.ts | 15 +- .../src/interceptors/generateInterceptor.ts | 2 - .../src/interceptors/parseStructure.ts | 6 +- .../src/utils/resolveDependenciesSync.ts | 20 +- .../next-config/src/withGraphCommerce.ts | 38 +- packagesDev/next-config/tsconfig.json | 2 +- 49 files changed, 3695 insertions(+), 4041 deletions(-) create mode 100644 .changeset/wicked-stingrays-buy.md delete mode 100644 packagesDev/next-config/dist/commands/codegen.js delete mode 100644 packagesDev/next-config/dist/commands/copyFiles.js delete mode 100644 packagesDev/next-config/dist/config/commands/exportConfig.js delete mode 100644 packagesDev/next-config/dist/config/commands/generateConfig.js delete mode 100644 packagesDev/next-config/dist/config/demoConfig.js delete mode 100644 packagesDev/next-config/dist/config/index.js delete mode 100644 packagesDev/next-config/dist/config/loadConfig.js delete mode 100644 packagesDev/next-config/dist/config/utils/configToImportMeta.js delete mode 100644 packagesDev/next-config/dist/config/utils/diff.js delete mode 100644 packagesDev/next-config/dist/config/utils/exportConfigToEnv.js delete mode 100644 packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js delete mode 100644 packagesDev/next-config/dist/config/utils/replaceConfigInString.js delete mode 100644 packagesDev/next-config/dist/config/utils/rewriteLegacyEnv.js mode change 100644 => 100755 packagesDev/next-config/dist/generated/config.js mode change 100644 => 100755 packagesDev/next-config/dist/index.js delete mode 100644 packagesDev/next-config/dist/interceptors/InterceptorPlugin.js delete mode 100644 packagesDev/next-config/dist/interceptors/RenameVisitor.js delete mode 100644 packagesDev/next-config/dist/interceptors/Visitor.js delete mode 100644 packagesDev/next-config/dist/interceptors/commands/codegenInterceptors.js delete mode 100644 packagesDev/next-config/dist/interceptors/extractExports.js delete mode 100644 packagesDev/next-config/dist/interceptors/findOriginalSource.js delete mode 100644 packagesDev/next-config/dist/interceptors/findPlugins.js delete mode 100644 packagesDev/next-config/dist/interceptors/generateInterceptor.js delete mode 100644 packagesDev/next-config/dist/interceptors/generateInterceptors.js delete mode 100644 packagesDev/next-config/dist/interceptors/parseStructure.js delete mode 100644 packagesDev/next-config/dist/interceptors/swc.js delete mode 100644 packagesDev/next-config/dist/interceptors/writeInterceptors.js delete mode 100644 packagesDev/next-config/dist/utils/PackagesSort.js delete mode 100644 packagesDev/next-config/dist/utils/TopologicalSort.js delete mode 100644 packagesDev/next-config/dist/utils/isMonorepo.js delete mode 100644 packagesDev/next-config/dist/utils/packageRoots.js delete mode 100644 packagesDev/next-config/dist/utils/resolveDependenciesSync.js delete mode 100644 packagesDev/next-config/dist/utils/resolveDependency.js delete mode 100644 packagesDev/next-config/dist/utils/sig.js delete mode 100644 packagesDev/next-config/dist/withGraphCommerce.js diff --git a/.changeset/wicked-stingrays-buy.md b/.changeset/wicked-stingrays-buy.md new file mode 100644 index 0000000000..76840a0612 --- /dev/null +++ b/.changeset/wicked-stingrays-buy.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/next-config': patch +--- + +Migrated `@graphcommerce/next-config` package to `"type": "module"` diff --git a/packagesDev/next-config/__tests__/config/utils/replaceConfigInString.ts b/packagesDev/next-config/__tests__/config/utils/replaceConfigInString.ts index 0976231e9f..0bfcaa163d 100644 --- a/packagesDev/next-config/__tests__/config/utils/replaceConfigInString.ts +++ b/packagesDev/next-config/__tests__/config/utils/replaceConfigInString.ts @@ -1,4 +1,3 @@ -// eslint-disable-next-line import/no-extraneous-dependencies import yaml from 'js-yaml' import { demoConfig } from '../../../src/config/demoConfig' import { replaceConfigInString } from '../../../src/config/utils/replaceConfigInString' diff --git a/packagesDev/next-config/dist/commands/codegen.js b/packagesDev/next-config/dist/commands/codegen.js deleted file mode 100644 index 3f6596fca8..0000000000 --- a/packagesDev/next-config/dist/commands/codegen.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.codegen = codegen; -const generateConfig_1 = require("../config/commands/generateConfig"); -const codegenInterceptors_1 = require("../interceptors/commands/codegenInterceptors"); -const copyFiles_1 = require("./copyFiles"); -/** Run all code generation steps in sequence */ -async function codegen() { - // Copy files from packages to project - console.info('🔄 Copying files from packages to project...'); - await (0, copyFiles_1.copyFiles)(); - // Generate GraphCommerce config types - console.info('⚙️ Generating GraphCommerce config types...'); - await (0, generateConfig_1.generateConfig)(); - // Generate interceptors - console.info('🔌 Generating interceptors...'); - await (0, codegenInterceptors_1.codegenInterceptors)(); -} diff --git a/packagesDev/next-config/dist/commands/copyFiles.js b/packagesDev/next-config/dist/commands/copyFiles.js deleted file mode 100644 index cf838ef1bb..0000000000 --- a/packagesDev/next-config/dist/commands/copyFiles.js +++ /dev/null @@ -1,297 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.copyFiles = copyFiles; -/* eslint-disable no-await-in-loop */ -const promises_1 = __importDefault(require("fs/promises")); -const path_1 = __importDefault(require("path")); -const fast_glob_1 = __importDefault(require("fast-glob")); -const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync"); -// Add debug logging helper -const debug = (...args) => { - if (process.env.DEBUG) - console.info('[copy-files]', ...args); -}; -// Add constants for the magic comments -const MANAGED_BY_GC = '// managed by: graphcommerce'; -const MANAGED_LOCALLY = '// managed by: local'; -const GITIGNORE_SECTION_START = '# managed by: graphcommerce'; -const GITIGNORE_SECTION_END = '# end managed by: graphcommerce'; -/** - * Updates the .gitignore file with a list of GraphCommerce managed files - * - * - Removes any existing GraphCommerce managed files section - * - If managedFiles is not empty, adds a new section with the files - * - If managedFiles is empty, just cleans up the existing section - * - Ensures the file ends with a newline - */ -async function updateGitignore(managedFiles) { - const escapedFiles = managedFiles - .map((file) => - // Escape special characters in file names - file.replace(/[*+?^${}()|[\]\\]/g, '\\$&')) - .sort(); - const gitignorePath = path_1.default.join(process.cwd(), '.gitignore'); - let content; - try { - content = await promises_1.default.readFile(gitignorePath, 'utf-8'); - debug('Reading existing .gitignore'); - } - catch (err) { - debug('.gitignore not found, creating new file'); - content = ''; - } - // Remove existing GraphCommerce section if it exists - const sectionRegex = new RegExp(`${GITIGNORE_SECTION_START}[\\s\\S]*?${GITIGNORE_SECTION_END}\\n?`, 'g'); - content = content.replace(sectionRegex, ''); - // Only add new section if there are files to manage - if (escapedFiles.length > 0) { - const newSection = [ - GITIGNORE_SECTION_START, - ...escapedFiles, - GITIGNORE_SECTION_END, - '', // Empty line at the end - ].join('\n'); - // Append the new section - content = `${content.trim()}\n\n${newSection}`; - debug(`Updated .gitignore with ${managedFiles.length} managed files`); - } - else { - content = `${content.trim()}\n`; - debug('Cleaned up .gitignore managed section'); - } - await promises_1.default.writeFile(gitignorePath, content); -} -/** Determines how a file should be managed based on its content */ -function getFileManagement(content) { - if (!content) - return 'graphcommerce'; - const contentStr = content.toString(); - if (contentStr.startsWith(MANAGED_LOCALLY)) - return 'local'; - if (contentStr.startsWith(MANAGED_BY_GC)) - return 'graphcommerce'; - return 'unmanaged'; -} -/** - * The packages are @graphcommerce/* packages and have special treatment. - * - * 1. Glob the `copy/**` directory for each package and generate a list of files that need to be - * copied. Error if a file with the same path exists in another package. - * 2. Copy the files to the project directory (cwd). - * - * 1. If the file doesn't exist: Create directories and the file with "managed by: graphcommerce" - * 2. If the file exists and starts with "managed by: local": Skip the file - * 3. If the file exists but doesn't have a management comment: Suggest adding "managed by: local" - * 4. If the file is managed by graphcommerce: Update if content differs - */ -async function copyFiles() { - const startTime = performance.now(); - debug('Starting copyFiles'); - const cwd = process.cwd(); - const deps = (0, resolveDependenciesSync_1.resolveDependenciesSync)(); - const packages = [...deps.values()].filter((p) => p !== '.'); - // Track files and their source packages to detect conflicts - const fileMap = new Map(); - const managedFiles = new Set(); - const existingManagedFiles = new Set(); - // First scan existing files to find GraphCommerce managed ones - const scanStart = performance.now(); - try { - // Use only default patterns for testing - const gitignorePatterns = [ - '**/dist/**', - '**/build/**', - '**/.next/**', - '**/.git/**', - '**/node_modules/**', - ]; - const allFiles = await (0, fast_glob_1.default)('**/*', { - cwd, - dot: true, - ignore: gitignorePatterns, - onlyFiles: true, - }); - debug(`Found ${allFiles.length} project files in ${(performance.now() - scanStart).toFixed(0)}ms`); - const readStart = performance.now(); - await Promise.all(allFiles.map(async (file) => { - const filePath = path_1.default.join(cwd, file); - try { - const content = await promises_1.default.readFile(filePath); - if (getFileManagement(content) === 'graphcommerce') { - existingManagedFiles.add(file); - debug(`Found existing managed file: ${file}`); - } - } - catch (err) { - debug(`Error reading file ${file}:`, err); - } - })); - debug(`Read ${existingManagedFiles.size} managed files in ${(performance.now() - readStart).toFixed(0)}ms`); - } - catch (err) { - debug('Error scanning project files:', err); - } - // First pass: collect all files and check for conflicts - const collectStart = performance.now(); - await Promise.all(packages.map(async (pkg) => { - const copyDir = path_1.default.join(pkg, 'copy'); - try { - const files = await (0, fast_glob_1.default)('**/*', { cwd: copyDir, dot: true, suppressErrors: true }); - if (files.length > 0) { - debug(`Found files in ${pkg}:`, files); - for (const file of files) { - const sourcePath = path_1.default.join(copyDir, file); - const existing = fileMap.get(file); - if (existing) { - console.error(`Error: File conflict detected for '${file}' -Found in packages: - - ${existing.packagePath} -> ${existing.sourcePath} - - ${pkg} -> ${sourcePath}`); - process.exit(1); - } - fileMap.set(file, { sourcePath, packagePath: pkg }); - } - } - } - catch (err) { - if (err.code === 'ENOENT') - return; - console.error(`Error scanning directory ${copyDir}: ${err.message}\nPath: ${copyDir}`); - process.exit(1); - } - })); - debug(`Collected ${fileMap.size} files in ${(performance.now() - collectStart).toFixed(0)}ms`); - // Second pass: copy files and handle removals - const copyStart = performance.now(); - await Promise.all(Array.from(fileMap.entries()).map(async ([file, { sourcePath }]) => { - const targetPath = path_1.default.join(cwd, file); - debug(`Processing file: ${file}`); - try { - await promises_1.default.mkdir(path_1.default.dirname(targetPath), { recursive: true }); - const sourceContent = await promises_1.default.readFile(sourcePath); - const contentWithComment = Buffer.concat([ - Buffer.from(`${MANAGED_BY_GC}\n// to modify this file, change it to managed by: local\n\n`), - sourceContent, - ]); - let targetContent; - try { - targetContent = await promises_1.default.readFile(targetPath); - const management = getFileManagement(targetContent); - if (management === 'local') { - debug(`File ${file} is managed locally, skipping`); - return; - } - if (management === 'unmanaged') { - console.info(`Note: File ${file} has been modified. Add '${MANAGED_LOCALLY.trim()}' at the top to manage it locally.`); - debug(`File ${file} doesn't have management comment, skipping`); - return; - } - debug(`File ${file} is managed by graphcommerce, will update if needed`); - } - catch (err) { - if (err.code !== 'ENOENT') { - console.error(`Error reading file ${file}: ${err.message} -Source: ${sourcePath}`); - process.exit(1); - } - console.info(`Creating new file: ${file}\nSource: ${sourcePath}`); - debug('File does not exist yet'); - } - // Skip if content is identical (including magic comment) - if (targetContent && Buffer.compare(contentWithComment, targetContent) === 0) { - debug(`File ${file} content is identical to source, skipping`); - managedFiles.add(file); - return; - } - // Copy the file with magic comment - await promises_1.default.writeFile(targetPath, contentWithComment); - if (targetContent) { - console.info(`Updated managed file: ${file}`); - debug(`Overwrote existing file: ${file}`); - } - // If the file is managed by GraphCommerce (new or updated), add it to managedFiles - if (!targetContent || targetContent.toString().startsWith(MANAGED_BY_GC)) { - managedFiles.add(file); - debug('Added managed file:', file); - } - } - catch (err) { - console.error(`Error copying file ${file}: ${err.message} -Source: ${sourcePath}`); - process.exit(1); - } - })); - debug(`Copied ${managedFiles.size} files in ${(performance.now() - copyStart).toFixed(0)}ms`); - // Remove files that are no longer provided - const removeStart = performance.now(); - const filesToRemove = Array.from(existingManagedFiles).filter((file) => !managedFiles.has(file)); - debug(`Files to remove: ${filesToRemove.length}`); - // Helper function to recursively clean up empty directories - async function cleanupEmptyDirs(startPath) { - let currentDir = startPath; - while (currentDir !== cwd) { - try { - const dirContents = await promises_1.default.readdir(currentDir); - if (dirContents.length === 0) { - await promises_1.default.rmdir(currentDir); - debug(`Removed empty directory: ${currentDir}`); - currentDir = path_1.default.dirname(currentDir); - } - else { - break; // Stop if directory is not empty - } - } - catch (err) { - if (err.code === 'EACCES') { - console.error(`Error cleaning up directory ${currentDir}: ${err.message}`); - process.exit(1); - } - break; // Stop on other errors (like ENOENT) - } - } - } - // Process file removals in parallel - await Promise.all(filesToRemove.map(async (file) => { - const filePath = path_1.default.join(cwd, file); - const dirPath = path_1.default.dirname(filePath); - try { - // First check if the directory exists and is accessible - await promises_1.default.readdir(dirPath); - // Then try to remove the file - try { - await promises_1.default.unlink(filePath); - console.info(`Removed managed file: ${file}`); - debug(`Removed file: ${file}`); - } - catch (err) { - if (err.code !== 'ENOENT') { - console.error(`Error removing file ${file}: ${err.message}`); - process.exit(1); - } - } - // Finally, try to clean up empty directories - await cleanupEmptyDirs(dirPath); - } - catch (err) { - if (err.code === 'EACCES') { - console.error(`Error accessing directory ${dirPath}: ${err.message}`); - process.exit(1); - } - // Ignore ENOENT errors for directories that don't exist - } - })); - debug(`Removed files in ${(performance.now() - removeStart).toFixed(0)}ms`); - // Update .gitignore with current list of managed files - if (managedFiles.size > 0) { - debug('Found managed files:', Array.from(managedFiles)); - await updateGitignore(Array.from(managedFiles)); - } - else { - debug('No managed files found, cleaning up .gitignore section'); - await updateGitignore([]); - } - debug(`Total execution time: ${(performance.now() - startTime).toFixed(0)}ms`); -} diff --git a/packagesDev/next-config/dist/config/commands/exportConfig.js b/packagesDev/next-config/dist/config/commands/exportConfig.js deleted file mode 100644 index 3f27f3efd7..0000000000 --- a/packagesDev/next-config/dist/config/commands/exportConfig.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.exportConfig = exportConfig; -const dotenv_1 = __importDefault(require("dotenv")); -const loadConfig_1 = require("../loadConfig"); -const exportConfigToEnv_1 = require("../utils/exportConfigToEnv"); -dotenv_1.default.config(); -// eslint-disable-next-line @typescript-eslint/require-await -async function exportConfig() { - const conf = (0, loadConfig_1.loadConfig)(process.cwd()); - // eslint-disable-next-line no-console - console.log((0, exportConfigToEnv_1.exportConfigToEnv)(conf)); -} diff --git a/packagesDev/next-config/dist/config/commands/generateConfig.js b/packagesDev/next-config/dist/config/commands/generateConfig.js deleted file mode 100644 index 469108af1b..0000000000 --- a/packagesDev/next-config/dist/config/commands/generateConfig.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateConfig = generateConfig; -const fs_1 = require("fs"); -const cli_1 = require("@graphql-codegen/cli"); -const core_1 = require("@swc/core"); -const dotenv_1 = __importDefault(require("dotenv")); -const isMonorepo_1 = require("../../utils/isMonorepo"); -const resolveDependenciesSync_1 = require("../../utils/resolveDependenciesSync"); -const resolveDependency_1 = require("../../utils/resolveDependency"); -dotenv_1.default.config(); -const packages = [...(0, resolveDependenciesSync_1.resolveDependenciesSync)().values()].filter((p) => p !== '.'); -const resolve = (0, resolveDependency_1.resolveDependency)(); -const schemaLocations = packages.map((p) => `${p}/**/Config.graphqls`); -async function generateConfig() { - const resolved = resolve('@graphcommerce/next-config'); - if (!resolved) - throw Error('Could not resolve @graphcommerce/next-config'); - const targetTs = `${resolved.root}/src/generated/config.ts`; - const targetJs = `${resolved.root}/dist/generated/config.js`; - await (0, cli_1.generate)({ - silent: true, - schema: ['graphql/**/Config.graphqls', ...schemaLocations], - generates: { - [targetTs]: { - plugins: ['typescript', 'typescript-validation-schema', 'add'], - config: { - // enumsAsTypes: true, - content: '/* eslint-disable */', - schema: 'zod', - notAllowEmptyString: true, - strictScalars: true, - enumsAsTypes: true, - scalarSchemas: { - Domain: 'z.string()', - DateTime: 'z.date()', - RichTextAST: 'z.object.json()', - }, - }, - }, - ...((0, isMonorepo_1.findParentPath)(process.cwd()) && { - '../../docs/framework/config.md': { - plugins: ['@graphcommerce/graphql-codegen-markdown-docs'], - }, - }), - }, - }); - const result = (0, core_1.transformFileSync)(targetTs, { - module: { type: 'commonjs' }, - env: { targets: { node: '18' } }, - }); - (0, fs_1.writeFileSync)(targetJs, result.code); -} diff --git a/packagesDev/next-config/dist/config/demoConfig.js b/packagesDev/next-config/dist/config/demoConfig.js deleted file mode 100644 index 964e3512a1..0000000000 --- a/packagesDev/next-config/dist/config/demoConfig.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.demoConfig = void 0; -exports.demoConfig = { - canonicalBaseUrl: 'https://graphcommerce.vercel.app', - hygraphEndpoint: 'https://eu-central-1.cdn.hygraph.com/content/ckhx7xadya6xs01yxdujt8i80/master', - magentoEndpoint: 'https://configurator.reachdigital.dev/graphql', - magentoVersion: 247, - storefront: [ - { locale: 'en', magentoStoreCode: 'en_US', defaultLocale: true }, - { - locale: 'nl', - magentoStoreCode: 'nl_NL', - hygraphLocales: ['nl', 'en_us'], - cartDisplayPricesInclTax: true, - }, - { - locale: 'fr-be', - magentoStoreCode: 'fr_BE', - cartDisplayPricesInclTax: true, - linguiLocale: 'fr', - }, - { - locale: 'nl-be', - magentoStoreCode: 'nl_BE', - cartDisplayPricesInclTax: true, - linguiLocale: 'nl', - }, - { - locale: 'en-gb', - magentoStoreCode: 'en_GB', - cartDisplayPricesInclTax: true, - linguiLocale: 'en', - }, - { locale: 'en-ca', magentoStoreCode: 'en_CA', linguiLocale: 'en' }, - ], - productFiltersPro: true, - productFiltersLayout: 'DEFAULT', - productListPaginationVariant: 'COMPACT', - compareVariant: 'ICON', - robotsAllow: false, - demoMode: true, - limitSsg: true, - compare: true, - sidebarGallery: { paginationVariant: 'DOTS' }, - configurableVariantForSimple: true, - configurableVariantValues: { url: true, content: true, gallery: true }, - recentlyViewedProducts: { enabled: true, maxCount: 20 }, - breadcrumbs: false, - customerDeleteEnabled: true, - previewSecret: 'SECRET', -}; diff --git a/packagesDev/next-config/dist/config/index.js b/packagesDev/next-config/dist/config/index.js deleted file mode 100644 index 760009ec74..0000000000 --- a/packagesDev/next-config/dist/config/index.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./commands/generateConfig"), exports); -__exportStar(require("./commands/exportConfig"), exports); -__exportStar(require("./loadConfig"), exports); diff --git a/packagesDev/next-config/dist/config/loadConfig.js b/packagesDev/next-config/dist/config/loadConfig.js deleted file mode 100644 index d283605a78..0000000000 --- a/packagesDev/next-config/dist/config/loadConfig.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.loadConfig = loadConfig; -/* eslint-disable no-console */ -// eslint-disable-next-line import/no-extraneous-dependencies -const cosmiconfig_1 = require("cosmiconfig"); -const config_1 = require("../generated/config"); -const demoConfig_1 = require("./demoConfig"); -const mergeEnvIntoConfig_1 = require("./utils/mergeEnvIntoConfig"); -const rewriteLegacyEnv_1 = require("./utils/rewriteLegacyEnv"); -__exportStar(require("./utils/configToImportMeta"), exports); -__exportStar(require("./utils/replaceConfigInString"), exports); -const moduleName = 'graphcommerce'; -const loader = (0, cosmiconfig_1.cosmiconfigSync)(moduleName); -function loadConfig(cwd) { - const isMainProcess = !process.send; - try { - const result = loader.search(cwd); - let confFile = result?.config; - if (!confFile) { - if (isMainProcess) - console.warn('No graphcommerce.config.js found in the project, using demo config'); - confFile = demoConfig_1.demoConfig; - } - confFile ||= {}; - const schema = (0, config_1.GraphCommerceConfigSchema)(); - const [mergedConfig, applyResult] = (0, rewriteLegacyEnv_1.rewriteLegacyEnv)(schema, process.env, - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - confFile); - if (applyResult.length > 0 && isMainProcess) - console.log((0, mergeEnvIntoConfig_1.formatAppliedEnv)(applyResult)); - const finalParse = schema.parse(mergedConfig); - if (process.env.DEBUG && isMainProcess) { - console.log('Parsed configuration'); - console.log(finalParse); - } - return finalParse; - } - catch (error) { - if (error instanceof Error) { - if (isMainProcess) { - console.log('Error while parsing graphcommerce.config.js', error.message); - process.exit(1); - } - } - throw error; - } -} diff --git a/packagesDev/next-config/dist/config/utils/configToImportMeta.js b/packagesDev/next-config/dist/config/utils/configToImportMeta.js deleted file mode 100644 index 67a3db8c37..0000000000 --- a/packagesDev/next-config/dist/config/utils/configToImportMeta.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.configToImportMeta = configToImportMeta; -function flattenKeys(value, initialPathPrefix, stringify) { - // Is a scalar: - if (value === null || value === undefined || typeof value === 'number') { - return { [initialPathPrefix]: value }; - } - if (typeof value === 'string') { - return { [initialPathPrefix]: stringify ? JSON.stringify(value) : value }; - } - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return { - [initialPathPrefix]: stringify || Array.isArray(value) ? JSON.stringify(value) : value, - }; - } - if (typeof value === 'object') { - let outputValue = value; - if (stringify) - outputValue = - process.env.NODE_ENV !== 'production' - ? `{ __debug: "'${initialPathPrefix}' can not be destructured, please access deeper properties directly" }` - : '{}'; - return { - [initialPathPrefix]: outputValue, - ...Object.keys(value) - .map((key) => { - const deep = value[key]; - return flattenKeys(deep, `${initialPathPrefix}.${key}`, stringify); - }) - .reduce((acc, path) => ({ ...acc, ...path }), {}), - }; - } - throw Error(`Unexpected value: ${value}`); -} -/** The result of this function is passed to the webpack DefinePlugin as import.meta.graphCommerce.* */ -function configToImportMeta(config, path = 'import.meta.graphCommerce', stringify = true) { - return flattenKeys(config, path, stringify); -} diff --git a/packagesDev/next-config/dist/config/utils/diff.js b/packagesDev/next-config/dist/config/utils/diff.js deleted file mode 100644 index aa147f8f2d..0000000000 --- a/packagesDev/next-config/dist/config/utils/diff.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.default = diff; -function isObject(val) { - return typeof val === 'object' && val !== null; -} -function isArray(val) { - return Array.isArray(val); -} -/** Simple diff function, retuns the values of the second object. */ -function diff(item1, item2) { - const item1Type = typeof item2; - const item2Type = typeof item2; - const isSame = item1Type === item2Type; - // If the types aren't the same we always have a diff - if (!isSame) - return item2; - if (isArray(item1) && isArray(item2)) { - const res = item1.map((val, idx) => diff(val, item2[idx])).filter((val) => !!val); - return res.length ? res : undefined; - } - if (isObject(item1) && isObject(item2)) { - const entriesRight = Object.fromEntries(Object.entries(item1) - .map(([key, val]) => [key, diff(val, item2[key])]) - .filter((entry) => !!entry[1])); - const entriesLeft = Object.fromEntries(Object.entries(item2) - .map(([key, val]) => [key, diff(item1[key], val)]) - .filter((entry) => !!entry[1])); - const entries = { ...entriesRight, ...entriesLeft }; - return Object.keys(entries).length ? entries : undefined; - } - return item2 === item1 ? undefined : item2; -} diff --git a/packagesDev/next-config/dist/config/utils/exportConfigToEnv.js b/packagesDev/next-config/dist/config/utils/exportConfigToEnv.js deleted file mode 100644 index e7e19c84b1..0000000000 --- a/packagesDev/next-config/dist/config/utils/exportConfigToEnv.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.exportConfigToEnv = exportConfigToEnv; -const mergeEnvIntoConfig_1 = require("./mergeEnvIntoConfig"); -const fmt = (value) => { - let formattedValue = value; - if (typeof formattedValue === 'boolean') { - formattedValue = formattedValue ? '1' : '0'; - } - if (typeof formattedValue === 'object') { - formattedValue = JSON.stringify(formattedValue); - } - if (typeof formattedValue === 'number') { - formattedValue = String(formattedValue); - } - return formattedValue; -}; -function exportConfigToEnv(config) { - let env = ''; - Object.entries(config).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((val, idx) => { - env += `${(0, mergeEnvIntoConfig_1.toEnvStr)([key, `${idx}`])}='${fmt(val)}'\n`; - }); - } - else { - env += `${(0, mergeEnvIntoConfig_1.toEnvStr)([key])}='${fmt(value)}'\n`; - } - }); - return env; -} diff --git a/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js b/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js deleted file mode 100644 index fff97be9f7..0000000000 --- a/packagesDev/next-config/dist/config/utils/mergeEnvIntoConfig.js +++ /dev/null @@ -1,182 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toEnvStr = void 0; -exports.configToEnvSchema = configToEnvSchema; -exports.mergeEnvIntoConfig = mergeEnvIntoConfig; -exports.formatAppliedEnv = formatAppliedEnv; -/* eslint-disable import/no-extraneous-dependencies */ -const utilities_1 = require("@apollo/client/utilities"); -const chalk_1 = __importDefault(require("chalk")); -const lodash_1 = require("lodash"); -const snakeCase_1 = __importDefault(require("lodash/snakeCase")); -const zod_1 = require("zod"); -const diff_1 = __importDefault(require("./diff")); -const fmt = (s) => s.split(/(\d+)/).map(snakeCase_1.default).join(''); -const toEnvStr = (path) => ['GC', ...path].map(fmt).join('_').toUpperCase(); -exports.toEnvStr = toEnvStr; -const dotNotation = (pathParts) => pathParts - .map((v) => { - const idx = Number(v); - return !Number.isNaN(idx) ? `[${idx}]` : v; -}) - .join('.'); -function isJSON(str) { - if (!str) - return true; - try { - JSON.parse(str); - } - catch (e) { - return false; - } - return true; -} -function configToEnvSchema(schema) { - const envSchema = {}; - const envToDot = {}; - function walk(incomming, path = []) { - let node = incomming; - if (node instanceof zod_1.ZodEffects) - node = node.innerType(); - if (node instanceof zod_1.ZodOptional) - node = node.unwrap(); - if (node instanceof zod_1.ZodNullable) - node = node.unwrap(); - if (node instanceof zod_1.ZodDefault) - node = node.removeDefault(); - if (node instanceof zod_1.ZodObject) { - if (path.length > 0) { - envSchema[(0, exports.toEnvStr)(path)] = zod_1.z - .string() - .optional() - .refine(isJSON, { message: 'Invalid JSON' }) - .transform((val) => (val ? JSON.parse(val) : val)); - envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path); - } - const typeNode = node; - Object.keys(typeNode.shape).forEach((key) => { - walk(typeNode.shape[key], [...path, key]); - }); - return; - } - if (node instanceof zod_1.ZodArray) { - const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; - if (path.length > 0) { - envSchema[(0, exports.toEnvStr)(path)] = zod_1.z - .string() - .optional() - .refine(isJSON, { message: 'Invalid JSON' }) - .transform((val) => (val ? JSON.parse(val) : val)); - envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path); - } - arr.forEach((key) => { - walk(node.element, [...path, String(key)]); - }); - return; - } - if (node instanceof zod_1.ZodNumber) { - envSchema[(0, exports.toEnvStr)(path)] = zod_1.z.coerce.number().optional(); - envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path); - return; - } - if (node instanceof zod_1.ZodString || node instanceof zod_1.ZodEnum) { - envSchema[(0, exports.toEnvStr)(path)] = node.optional(); - envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path); - return; - } - if (node instanceof zod_1.ZodBoolean) { - envSchema[(0, exports.toEnvStr)(path)] = zod_1.z - .enum(['true', '1', 'false', '0']) - .optional() - .transform((v) => { - if (v === 'true' || v === '1') - return true; - if (v === 'false' || v === '0') - return false; - return v; - }); - envToDot[(0, exports.toEnvStr)(path)] = dotNotation(path); - return; - } - throw Error(`[@graphcommerce/next-config] Unknown type in schema ${node.constructor.name}. This is probably a bug please create an issue.`); - } - walk(schema); - return [zod_1.z.object(envSchema), envToDot]; -} -const filterEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith('GC_'))); -function mergeEnvIntoConfig(schema, config, env) { - const filteredEnv = filterEnv(env); - const newConfig = (0, utilities_1.cloneDeep)(config); - const [envSchema, envToDot] = configToEnvSchema(schema); - const result = envSchema.safeParse(filteredEnv); - const applyResult = []; - if (!result.success) { - Object.entries(result.error.flatten().fieldErrors).forEach(([envVar, error]) => { - const dotVar = envToDot[envVar]; - const envValue = filteredEnv[envVar]; - applyResult.push({ envVar, envValue, dotVar, error }); - }); - return [undefined, applyResult]; - } - Object.entries(result.data).forEach(([envVar, value]) => { - const dotVar = envToDot[envVar]; - const envValue = filteredEnv[envVar]; - if (!dotVar) { - applyResult.push({ envVar, envValue }); - return; - } - const dotValue = (0, lodash_1.get)(newConfig, dotVar); - const merged = (0, utilities_1.mergeDeep)(dotValue, value); - const from = (0, diff_1.default)(merged, dotValue); - const to = (0, diff_1.default)(dotValue, merged); - applyResult.push({ envVar, envValue, dotVar, from, to }); - (0, lodash_1.set)(newConfig, dotVar, merged); - }); - return [newConfig, applyResult]; -} -/** - * Prints the applied env variables to the console - * - * The format is: - * - * - If from and to is empty, the value is unchanged: `=` (white) - * - If the from is empty, a new value is applied: `+` (green) - * - If the to is empty, a value is removed: `-` (red) - * - If both from and to is not empty, a value is changed: `~` (yellow) - */ -function formatAppliedEnv(applyResult) { - let hasError = false; - let hasWarning = false; - const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => { - const envVariableFmt = `${envVar}`; - const dotVariableFmt = chalk_1.default.bold.underline(`${dotVar}`); - const baseLog = `${envVariableFmt} => ${dotVariableFmt}`; - if (error) { - hasError = true; - return `${chalk_1.default.red(` ⨉ ${envVariableFmt}`)} => ${error.join(', ')}`; - } - if (warning) { - hasWarning = true; - return `${chalk_1.default.yellowBright(` ‼ ${envVariableFmt}`)} => ${warning.join(', ')}`; - } - if (!dotVar) - return chalk_1.default.red(`${envVariableFmt} => ignored (no matching config)`); - if (from === undefined && to === undefined) - return ` = ${baseLog}: (ignored)`; - if (from === undefined && to !== undefined) - return ` ${chalk_1.default.green('+')} ${baseLog}`; - if (from !== undefined && to === undefined) - return ` ${chalk_1.default.red('-')} ${baseLog}`; - return ` ${chalk_1.default.yellowBright('~')} ${baseLog}`; - }); - let header = chalk_1.default.blueBright('info'); - if (hasWarning) - header = chalk_1.default.yellowBright('warning'); - if (hasError) - header = chalk_1.default.yellowBright('error'); - header += ' - Loaded GraphCommerce env variables'; - return [header, ...lines].join('\n'); -} diff --git a/packagesDev/next-config/dist/config/utils/replaceConfigInString.js b/packagesDev/next-config/dist/config/utils/replaceConfigInString.js deleted file mode 100644 index 37a1fe5318..0000000000 --- a/packagesDev/next-config/dist/config/utils/replaceConfigInString.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.replaceConfigInString = replaceConfigInString; -const configToImportMeta_1 = require("./configToImportMeta"); -function replaceConfigInString(str, config) { - let result = str; - const replacers = (0, configToImportMeta_1.configToImportMeta)(config, 'graphCommerce', false); - Object.entries(replacers).forEach(([from, to]) => { - result = result.replace(new RegExp(`{${from}}`, 'g'), to); - }); - return result; -} diff --git a/packagesDev/next-config/dist/config/utils/rewriteLegacyEnv.js b/packagesDev/next-config/dist/config/utils/rewriteLegacyEnv.js deleted file mode 100644 index cf6e51a594..0000000000 --- a/packagesDev/next-config/dist/config/utils/rewriteLegacyEnv.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.rewriteLegacyEnv = rewriteLegacyEnv; -const cloneDeep_1 = __importDefault(require("lodash/cloneDeep")); -const mergeEnvIntoConfig_1 = require("./mergeEnvIntoConfig"); -function rewriteLegacyEnv(schema, env, config = {}) { - const clonedEnv = (0, cloneDeep_1.default)(env); - const applied = []; - function renamedTo(to) { - return (envVar, envValue) => { - applied.push({ - warning: [`should be renamed to ${to}='${envValue}'`], - envVar, - envValue, - }); - clonedEnv[to] = envValue; - }; - } - function notUsed() { - return (envVar, envValue) => { - applied.push({ - warning: ['should be removed'], - envVar, - envValue, - }); - }; - } - const parsers = { - MAGENTO_ENDPOINT: renamedTo('GC_MAGENTO_ENDPOINT'), - GRAPHCMS_URL: renamedTo('GC_HYGRAPH_ENDPOINT'), - NEXT_PUBLIC_GRAPHQL_ENDPOINT: notUsed(), - IMAGE_DOMAINS: (envVar, envValue) => { - applied.push({ - warning: [ - 'should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options', - ], - envVar, - envValue, - }); - }, - NEXT_PUBLIC_LOCALE_STORES: (envVar, envValue) => { - const parsed = JSON.parse(envValue); - applied.push({ - warning: ['env variable is is modified, rewritten to GC_STOREFRONT.'], - envVar, - envValue, - }); - clonedEnv.GC_STOREFRONT = JSON.stringify(Object.entries(parsed).map(([locale, magentoStoreCode], index) => { - if (!config.storefront) - config.storefront = []; - config.storefront[index] = { ...config.storefront[index], locale, magentoStoreCode }; - return { locale, magentoStoreCode }; - })); - }, - NEXT_PUBLIC_SITE_URL: renamedTo('GC_CANONICAL_BASE_URL'), - NEXT_PUBLIC_GTM_ID: renamedTo('GC_GOOGLE_TAGMANAGER_ID'), - NEXT_PUBLIC_GOOGLE_ANALYTICS: (envVar, envValue) => { - if (envValue.startsWith('{')) { - const parsed = JSON.parse(envValue); - clonedEnv.GC_GOOGLE_ANALYTICS_ID = 'enabled'; - if (!config.storefront) - config.storefront = []; - config.storefront.forEach((storefront, index) => { - if (parsed[storefront.locale]) { - clonedEnv[`GC_STOREFRONT_${index}_GOOGLE_ANALYTICS_ID`] = parsed[storefront.locale]; - } - }); - applied.push({ - warning: ['should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID'], - envVar, - envValue, - }); - return; - } - renamedTo('GC_GOOGLE_ANALYTICS_ID'); - }, - NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: renamedTo('GC_GOOGLE_RECAPTCHA_KEY'), - NEXT_PUBLIC_DISPLAY_INCL_TAX: (envVar, envValue) => { - const inclTax = envValue.split(',').map((i) => i.trim()); - if (!config.storefront) - config.storefront = []; - config.storefront.forEach((storefront, index) => { - if (!inclTax.includes(storefront.locale)) - return; - clonedEnv[`GC_STOREFRONT_${index}_CART_DISPLAY_PRICES_INCL_TAX`] = '1'; - }); - applied.push({ - warning: ['env variable is renamed, move to configuration: cartDisplayPricesInclTax'], - envVar, - envValue, - }); - clonedEnv.GC_DISPLAY_PRICES_INCL_TAX = envValue; - }, - PREVIEW_SECRET: renamedTo('GC_PREVIEW_SECRET'), - DEMO_MAGENTO_GRAPHCOMMERCE: renamedTo('GC_DEMO_MODE'), - }; - if (env.SKIP_MIGRATION === '1' || env.SKIP_MIGRATION === 'true') { - return (0, mergeEnvIntoConfig_1.mergeEnvIntoConfig)(schema, config, clonedEnv); - } - Object.entries(env).forEach(([key, value]) => { - if (value === undefined) - return; - try { - parsers[key]?.(key, value); - } - catch (e) { - console.error(`Error parsing ${key}`, e); - } - }); - const [newConfig, envApplied] = (0, mergeEnvIntoConfig_1.mergeEnvIntoConfig)(schema, config, clonedEnv); - return [newConfig, [...applied, ...envApplied]]; -} diff --git a/packagesDev/next-config/dist/generated/config.js b/packagesDev/next-config/dist/generated/config.js old mode 100644 new mode 100755 index 71f23e744d..339e3717d6 --- a/packagesDev/next-config/dist/generated/config.js +++ b/packagesDev/next-config/dist/generated/config.js @@ -1,216 +1,129 @@ -/* eslint-disable */ "use strict"; -Object.defineProperty(exports, "__esModule", { - value: true -}); -function _export(target, all) { - for(var name in all)Object.defineProperty(target, name, { - enumerable: true, - get: all[name] - }); -} -_export(exports, { - CartPermissionsSchema: function() { - return CartPermissionsSchema; - }, - CompareVariantSchema: function() { - return CompareVariantSchema; - }, - ContainerSizingSchema: function() { - return ContainerSizingSchema; - }, - CustomerAccountPermissionsSchema: function() { - return CustomerAccountPermissionsSchema; - }, - DatalayerConfigSchema: function() { - return DatalayerConfigSchema; - }, - GraphCommerceConfigSchema: function() { - return GraphCommerceConfigSchema; - }, - GraphCommerceDebugConfigSchema: function() { - return GraphCommerceDebugConfigSchema; - }, - GraphCommerceGooglePlaystoreConfigSchema: function() { - return GraphCommerceGooglePlaystoreConfigSchema; - }, - GraphCommercePermissionsSchema: function() { - return GraphCommercePermissionsSchema; - }, - GraphCommerceStorefrontConfigSchema: function() { - return GraphCommerceStorefrontConfigSchema; - }, - MagentoConfigurableVariantValuesSchema: function() { - return MagentoConfigurableVariantValuesSchema; - }, - PaginationVariantSchema: function() { - return PaginationVariantSchema; - }, - ProductFiltersLayoutSchema: function() { - return ProductFiltersLayoutSchema; - }, - RecentlyViewedProductsConfigSchema: function() { - return RecentlyViewedProductsConfigSchema; - }, - SidebarGalleryConfigSchema: function() { - return SidebarGalleryConfigSchema; - }, - SidebarGalleryPaginationVariantSchema: function() { - return SidebarGalleryPaginationVariantSchema; - }, - WebsitePermissionsSchema: function() { - return WebsitePermissionsSchema; - }, - definedNonNullAnySchema: function() { - return definedNonNullAnySchema; - }, - isDefinedNonNullAny: function() { - return isDefinedNonNullAny; - } -}); -const _zod = require("zod"); -const isDefinedNonNullAny = (v)=>v !== undefined && v !== null; -const definedNonNullAnySchema = _zod.z.any().refine((v)=>isDefinedNonNullAny(v)); -const CartPermissionsSchema = _zod.z.enum([ - 'CUSTOMER_ONLY', - 'DISABLED', - 'ENABLED' -]); -const CompareVariantSchema = _zod.z.enum([ - 'CHECKBOX', - 'ICON' -]); -const ContainerSizingSchema = _zod.z.enum([ - 'BREAKPOINT', - 'FULL_WIDTH' -]); -const CustomerAccountPermissionsSchema = _zod.z.enum([ - 'DISABLED', - 'DISABLE_REGISTRATION', - 'ENABLED' -]); -const PaginationVariantSchema = _zod.z.enum([ - 'COMPACT', - 'EXTENDED' -]); -const ProductFiltersLayoutSchema = _zod.z.enum([ - 'DEFAULT', - 'SIDEBAR' -]); -const SidebarGalleryPaginationVariantSchema = _zod.z.enum([ - 'DOTS', - 'THUMBNAILS_BOTTOM' -]); -const WebsitePermissionsSchema = _zod.z.enum([ - 'ENABLED' +import { z } from 'zod'; + +const isDefinedNonNullAny = (v) => v !== undefined && v !== null; +const definedNonNullAnySchema = z.any().refine((v) => isDefinedNonNullAny(v)); +const CartPermissionsSchema = z.enum(["CUSTOMER_ONLY", "DISABLED", "ENABLED"]); +const CompareVariantSchema = z.enum(["CHECKBOX", "ICON"]); +const ContainerSizingSchema = z.enum(["BREAKPOINT", "FULL_WIDTH"]); +const CustomerAccountPermissionsSchema = z.enum([ + "DISABLED", + "DISABLE_REGISTRATION", + "ENABLED" ]); +const PaginationVariantSchema = z.enum(["COMPACT", "EXTENDED"]); +const ProductFiltersLayoutSchema = z.enum(["DEFAULT", "SIDEBAR"]); +const SidebarGalleryPaginationVariantSchema = z.enum(["DOTS", "THUMBNAILS_BOTTOM"]); +const WebsitePermissionsSchema = z.enum(["ENABLED"]); function DatalayerConfigSchema() { - return _zod.z.object({ - coreWebVitals: _zod.z.boolean().nullish() - }); + return z.object({ + coreWebVitals: z.boolean().nullish() + }); } function GraphCommerceConfigSchema() { - return _zod.z.object({ - breadcrumbs: _zod.z.boolean().default(false).nullish(), - canonicalBaseUrl: _zod.z.string().min(1), - cartDisplayPricesInclTax: _zod.z.boolean().nullish(), - compare: _zod.z.boolean().nullish(), - compareVariant: CompareVariantSchema.default("ICON").nullish(), - configurableVariantForSimple: _zod.z.boolean().default(false).nullish(), - configurableVariantValues: MagentoConfigurableVariantValuesSchema().nullish(), - containerSizingContent: ContainerSizingSchema.default("FULL_WIDTH").nullish(), - containerSizingShell: ContainerSizingSchema.default("FULL_WIDTH").nullish(), - crossSellsHideCartItems: _zod.z.boolean().default(false).nullish(), - crossSellsRedirectItems: _zod.z.boolean().default(false).nullish(), - customerAddressNoteEnable: _zod.z.boolean().nullish(), - customerCompanyFieldsEnable: _zod.z.boolean().nullish(), - customerDeleteEnabled: _zod.z.boolean().nullish(), - customerXMagentoCacheIdDisable: _zod.z.boolean().nullish(), - dataLayer: DatalayerConfigSchema().nullish(), - debug: GraphCommerceDebugConfigSchema().nullish(), - demoMode: _zod.z.boolean().default(true).nullish(), - enableGuestCheckoutLogin: _zod.z.boolean().nullish(), - googleAnalyticsId: _zod.z.string().nullish(), - googlePlaystore: GraphCommerceGooglePlaystoreConfigSchema().nullish(), - googleRecaptchaKey: _zod.z.string().nullish(), - googleTagmanagerId: _zod.z.string().nullish(), - graphqlMeshEditMode: _zod.z.boolean().default(false).nullish(), - hygraphEndpoint: _zod.z.string().min(1), - hygraphManagementApi: _zod.z.string().nullish(), - hygraphProjectId: _zod.z.string().nullish(), - hygraphWriteAccessToken: _zod.z.string().nullish(), - limitSsg: _zod.z.boolean().nullish(), - magentoEndpoint: _zod.z.string().min(1), - magentoVersion: _zod.z.number(), - permissions: GraphCommercePermissionsSchema().nullish(), - previewSecret: _zod.z.string().nullish(), - productFiltersLayout: ProductFiltersLayoutSchema.default("DEFAULT").nullish(), - productFiltersPro: _zod.z.boolean().nullish(), - productListPaginationVariant: PaginationVariantSchema.default("COMPACT").nullish(), - productRoute: _zod.z.string().nullish(), - recentlyViewedProducts: RecentlyViewedProductsConfigSchema().nullish(), - robotsAllow: _zod.z.boolean().nullish(), - sidebarGallery: SidebarGalleryConfigSchema().nullish(), - storefront: _zod.z.array(GraphCommerceStorefrontConfigSchema()), - wishlistHideForGuests: _zod.z.boolean().nullish(), - wishlistShowFeedbackMessage: _zod.z.boolean().nullish() - }); + return z.object({ + breadcrumbs: z.boolean().default(false).nullish(), + canonicalBaseUrl: z.string().min(1), + cartDisplayPricesInclTax: z.boolean().nullish(), + compare: z.boolean().nullish(), + compareVariant: CompareVariantSchema.default("ICON").nullish(), + configurableVariantForSimple: z.boolean().default(false).nullish(), + configurableVariantValues: MagentoConfigurableVariantValuesSchema().nullish(), + containerSizingContent: ContainerSizingSchema.default("FULL_WIDTH").nullish(), + containerSizingShell: ContainerSizingSchema.default("FULL_WIDTH").nullish(), + crossSellsHideCartItems: z.boolean().default(false).nullish(), + crossSellsRedirectItems: z.boolean().default(false).nullish(), + customerAddressNoteEnable: z.boolean().nullish(), + customerCompanyFieldsEnable: z.boolean().nullish(), + customerDeleteEnabled: z.boolean().nullish(), + customerXMagentoCacheIdDisable: z.boolean().nullish(), + dataLayer: DatalayerConfigSchema().nullish(), + debug: GraphCommerceDebugConfigSchema().nullish(), + demoMode: z.boolean().default(true).nullish(), + enableGuestCheckoutLogin: z.boolean().nullish(), + googleAnalyticsId: z.string().nullish(), + googlePlaystore: GraphCommerceGooglePlaystoreConfigSchema().nullish(), + googleRecaptchaKey: z.string().nullish(), + googleTagmanagerId: z.string().nullish(), + graphqlMeshEditMode: z.boolean().default(false).nullish(), + hygraphEndpoint: z.string().min(1), + hygraphManagementApi: z.string().nullish(), + hygraphProjectId: z.string().nullish(), + hygraphWriteAccessToken: z.string().nullish(), + limitSsg: z.boolean().nullish(), + magentoEndpoint: z.string().min(1), + magentoVersion: z.number(), + permissions: GraphCommercePermissionsSchema().nullish(), + previewSecret: z.string().nullish(), + productFiltersLayout: ProductFiltersLayoutSchema.default("DEFAULT").nullish(), + productFiltersPro: z.boolean().nullish(), + productListPaginationVariant: PaginationVariantSchema.default("COMPACT").nullish(), + productRoute: z.string().nullish(), + recentlyViewedProducts: RecentlyViewedProductsConfigSchema().nullish(), + robotsAllow: z.boolean().nullish(), + sidebarGallery: SidebarGalleryConfigSchema().nullish(), + storefront: z.array(GraphCommerceStorefrontConfigSchema()), + wishlistHideForGuests: z.boolean().nullish(), + wishlistShowFeedbackMessage: z.boolean().nullish() + }); } function GraphCommerceDebugConfigSchema() { - return _zod.z.object({ - cart: _zod.z.boolean().nullish(), - pluginStatus: _zod.z.boolean().nullish(), - sessions: _zod.z.boolean().nullish(), - webpackCircularDependencyPlugin: _zod.z.boolean().nullish(), - webpackDuplicatesPlugin: _zod.z.boolean().nullish() - }); + return z.object({ + cart: z.boolean().nullish(), + pluginStatus: z.boolean().nullish(), + sessions: z.boolean().nullish(), + webpackCircularDependencyPlugin: z.boolean().nullish(), + webpackDuplicatesPlugin: z.boolean().nullish() + }); } function GraphCommerceGooglePlaystoreConfigSchema() { - return _zod.z.object({ - packageName: _zod.z.string().min(1), - sha256CertificateFingerprint: _zod.z.string().min(1) - }); + return z.object({ + packageName: z.string().min(1), + sha256CertificateFingerprint: z.string().min(1) + }); } function GraphCommercePermissionsSchema() { - return _zod.z.object({ - cart: CartPermissionsSchema.nullish(), - checkout: CartPermissionsSchema.nullish(), - customerAccount: CustomerAccountPermissionsSchema.nullish(), - website: WebsitePermissionsSchema.nullish() - }); + return z.object({ + cart: CartPermissionsSchema.nullish(), + checkout: CartPermissionsSchema.nullish(), + customerAccount: CustomerAccountPermissionsSchema.nullish(), + website: WebsitePermissionsSchema.nullish() + }); } function GraphCommerceStorefrontConfigSchema() { - return _zod.z.object({ - canonicalBaseUrl: _zod.z.string().nullish(), - cartDisplayPricesInclTax: _zod.z.boolean().nullish(), - customerCompanyFieldsEnable: _zod.z.boolean().nullish(), - defaultLocale: _zod.z.boolean().nullish(), - domain: _zod.z.string().nullish(), - googleAnalyticsId: _zod.z.string().nullish(), - googleRecaptchaKey: _zod.z.string().nullish(), - googleTagmanagerId: _zod.z.string().nullish(), - hygraphLocales: _zod.z.array(_zod.z.string().min(1)).nullish(), - linguiLocale: _zod.z.string().nullish(), - locale: _zod.z.string().min(1), - magentoStoreCode: _zod.z.string().min(1), - permissions: GraphCommercePermissionsSchema().nullish(), - robotsAllow: _zod.z.boolean().nullish() - }); + return z.object({ + canonicalBaseUrl: z.string().nullish(), + cartDisplayPricesInclTax: z.boolean().nullish(), + customerCompanyFieldsEnable: z.boolean().nullish(), + defaultLocale: z.boolean().nullish(), + domain: z.string().nullish(), + googleAnalyticsId: z.string().nullish(), + googleRecaptchaKey: z.string().nullish(), + googleTagmanagerId: z.string().nullish(), + hygraphLocales: z.array(z.string().min(1)).nullish(), + linguiLocale: z.string().nullish(), + locale: z.string().min(1), + magentoStoreCode: z.string().min(1), + permissions: GraphCommercePermissionsSchema().nullish(), + robotsAllow: z.boolean().nullish() + }); } function MagentoConfigurableVariantValuesSchema() { - return _zod.z.object({ - content: _zod.z.boolean().nullish(), - gallery: _zod.z.boolean().nullish(), - url: _zod.z.boolean().nullish() - }); + return z.object({ + content: z.boolean().nullish(), + gallery: z.boolean().nullish(), + url: z.boolean().nullish() + }); } function RecentlyViewedProductsConfigSchema() { - return _zod.z.object({ - enabled: _zod.z.boolean().nullish(), - maxCount: _zod.z.number().nullish() - }); + return z.object({ + enabled: z.boolean().nullish(), + maxCount: z.number().nullish() + }); } function SidebarGalleryConfigSchema() { - return _zod.z.object({ - paginationVariant: SidebarGalleryPaginationVariantSchema.nullish() - }); + return z.object({ + paginationVariant: SidebarGalleryPaginationVariantSchema.nullish() + }); } + +export { CartPermissionsSchema, CompareVariantSchema, ContainerSizingSchema, CustomerAccountPermissionsSchema, DatalayerConfigSchema, GraphCommerceConfigSchema, GraphCommerceDebugConfigSchema, GraphCommerceGooglePlaystoreConfigSchema, GraphCommercePermissionsSchema, GraphCommerceStorefrontConfigSchema, MagentoConfigurableVariantValuesSchema, PaginationVariantSchema, ProductFiltersLayoutSchema, RecentlyViewedProductsConfigSchema, SidebarGalleryConfigSchema, SidebarGalleryPaginationVariantSchema, WebsitePermissionsSchema, definedNonNullAnySchema, isDefinedNonNullAny }; diff --git a/packagesDev/next-config/dist/index.js b/packagesDev/next-config/dist/index.js old mode 100644 new mode 100755 index 1e35e60b55..6d7b04c52c --- a/packagesDev/next-config/dist/index.js +++ b/packagesDev/next-config/dist/index.js @@ -1,26 +1,3469 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./utils/isMonorepo"), exports); -__exportStar(require("./utils/resolveDependenciesSync"), exports); -__exportStar(require("./utils/packageRoots"), exports); -__exportStar(require("./utils/sig"), exports); -__exportStar(require("./withGraphCommerce"), exports); -__exportStar(require("./generated/config"), exports); -__exportStar(require("./config"), exports); -__exportStar(require("./interceptors/commands/codegenInterceptors"), exports); -__exportStar(require("./commands/copyFiles"), exports); -__exportStar(require("./commands/codegen"), exports); +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'module'; +import assert from 'assert'; +import crypto from 'crypto'; +import webpack from 'webpack'; +import { cosmiconfigSync } from 'cosmiconfig'; +import { GraphCommerceConfigSchema } from './generated/config.js'; +export { CartPermissionsSchema, CompareVariantSchema, ContainerSizingSchema, CustomerAccountPermissionsSchema, DatalayerConfigSchema, GraphCommerceDebugConfigSchema, GraphCommerceGooglePlaystoreConfigSchema, GraphCommercePermissionsSchema, GraphCommerceStorefrontConfigSchema, MagentoConfigurableVariantValuesSchema, PaginationVariantSchema, ProductFiltersLayoutSchema, RecentlyViewedProductsConfigSchema, SidebarGalleryConfigSchema, SidebarGalleryPaginationVariantSchema, WebsitePermissionsSchema, definedNonNullAnySchema, isDefinedNonNullAny } from './generated/config.js'; +import chalk from 'chalk'; +import lodash from 'lodash'; +import { z, ZodEffects, ZodOptional, ZodNullable, ZodDefault, ZodObject, ZodArray, ZodNumber, ZodString, ZodEnum, ZodBoolean } from 'zod'; +import path$1 from 'path'; +import { parseFileSync, parseSync as parseSync$1, printSync as printSync$1, transformFileSync } from '@swc/core'; +import { sync } from 'glob'; +import fs$1 from 'node:fs/promises'; +import prettierConf from '@graphcommerce/prettier-config-pwa'; +import prettier from 'prettier'; +import { writeFileSync, readFileSync } from 'fs'; +import { generate } from '@graphql-codegen/cli'; +import dotenv from 'dotenv'; +import fs$2 from 'fs/promises'; +import fg from 'fast-glob'; + +const debug$1 = process.env.DEBUG === "1"; +const log = (message) => debug$1 && console.log(`isMonorepo: ${message}`); +function findPackageJson$1(directory) { + try { + const packageJsonPath = path.join(directory, "package.json"); + const content = fs.readFileSync(packageJsonPath, "utf8"); + return JSON.parse(content); + } catch { + return null; + } +} +function findParentPath(directory) { + let currentDir = directory; + log(`Starting directory: ${currentDir}`); + currentDir = path.dirname(currentDir); + log(`Looking for parent packages starting from: ${currentDir}`); + while (currentDir !== path.parse(currentDir).root) { + const packageJson = findPackageJson$1(currentDir); + if (packageJson) { + log(`Found package.json in: ${currentDir}`); + log(`Package name: ${packageJson.name}`); + if (packageJson.name.startsWith("@graphcommerce/")) { + log(`Found parent @graphcommerce package at: ${currentDir}`); + return currentDir; + } + } + currentDir = path.dirname(currentDir); + } + log("No parent @graphcommerce package found"); + return null; +} + +var require$1 = ( + true + ? /* @__PURE__ */ createRequire(import.meta.url) + : require + ); + +class TopologicalSort { + #nodes; + #visitedNodes; + #sortedKeysStack; + constructor(nodes) { + this.#nodes = /* @__PURE__ */ new Map(); + this.addMultipleInternalNodes(nodes); + } + /** @public */ + addNode(key, node) { + return this.addInternalNode(key, node); + } + /** @public */ + addNodes(nodes) { + this.addMultipleInternalNodes(nodes); + } + /** @public */ + addEdge(fromKey, toKey) { + assert(this.#nodes.has(fromKey), `Source package with ${fromKey} key should exist`); + assert(this.#nodes.has(toKey), `Target package with ${toKey} key should exist`); + const sourceNode = this.#nodes.get(fromKey); + const targetNode = this.#nodes.get(toKey); + assert.strictEqual( + sourceNode !== undefined, + true, + `Source package with key ${fromKey} doesn't exist` + ); + assert.strictEqual( + targetNode !== undefined, + true, + `Target package with key ${toKey} doesn't exist` + ); + assert.strictEqual( + sourceNode.children.has(toKey), + false, + `Source package ${fromKey} already has an edge to target node ${toKey}` + ); + sourceNode.children.set(toKey, targetNode); + } + /** @public */ + sort() { + this.#visitedNodes = /* @__PURE__ */ new Set(); + this.#sortedKeysStack = []; + const output = /* @__PURE__ */ new Map(); + for (const [key] of this.#nodes) { + this.exploreNode(key, []); + } + for (let i = this.#sortedKeysStack.length - 1; i >= 0; i--) { + const node = this.#nodes.get(this.#sortedKeysStack[i]); + output.set(this.#sortedKeysStack[i], node); + } + return output; + } + exploreNode(nodeKey, explorePath) { + const newExplorePath = [...explorePath, nodeKey]; + if (explorePath.length) { + if (explorePath.includes(nodeKey)) { + throw Error( + `Package ${nodeKey} forms circular dependency: ${newExplorePath.slice(newExplorePath.indexOf(nodeKey)).join(" -> ")}` + ); + } + } + const node = this.#nodes.get(nodeKey); + if (this.#visitedNodes.has(node)) return; + this.#visitedNodes.add(node); + for (const [childNodeKey] of node.children) { + this.exploreNode(childNodeKey, newExplorePath); + } + this.#sortedKeysStack.push(nodeKey); + } + addInternalNode(key, node) { + assert.strictEqual(this.#nodes.has(key), false, `Node ${key} already exists`); + this.#nodes.set(key, { + children: /* @__PURE__ */ new Map(), + node + }); + return this; + } + addMultipleInternalNodes(nodes) { + const nodesFlat = [...nodes]; + for (let i = nodes.size - 1; i >= 0; i--) { + const [key, node] = nodesFlat[i]; + this.addInternalNode(key, node); + } + } +} + +class PackagesSort extends TopologicalSort { +} + +function g(data) { + const iv = crypto.randomBytes(16); + const cipher = crypto.createCipheriv("aes-256-cbc", "BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN", iv); + let encrypted = cipher.update(JSON.stringify(data), "utf-8", "hex"); + encrypted += cipher.final("hex"); + return Buffer.from(`${iv.toString("hex")}:${encrypted}`).toString(); +} +function sig() { + const l = process.env[atob("R0NfTElDRU5TRQ==")]; + if (!l) return; + if (!globalThis.gcl) + try { + const decipher = crypto.createDecipheriv( + "aes-256-cbc", + "BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN", + Buffer.from(l.split(":")[0], "hex") + ); + let decrypted = decipher.update(l.split(":")[1], "hex", "utf-8"); + decrypted += decipher.final("utf-8"); + globalThis.gcl = JSON.parse(decrypted); + } catch (error) { + } +} + +const resolveCache = /* @__PURE__ */ new Map(); +function findPackageJson(id, root) { + let dir = id.startsWith("/") ? id : require$1.resolve(id); + let packageJsonLocation = path.join(dir, "package.json"); + while (!fs.existsSync(packageJsonLocation)) { + dir = path.dirname(dir); + if (dir === root) throw Error(`Can't find package.json for ${id}`); + packageJsonLocation = path.join(dir, "package.json"); + } + return packageJsonLocation; +} +function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, additionalDependencies = []) { + const isRoot = dependencyPath === root; + let fileName; + try { + fileName = require$1.resolve(path.join(dependencyPath, "package.json")); + } catch (e2) { + fileName = findPackageJson(dependencyPath, root); + } + if (!fileName) throw Error(`Can't find package.json for ${dependencyPath}`); + const packageJsonFile = fs.readFileSync(fileName, "utf-8").toString(); + const packageJson = JSON.parse(packageJsonFile); + const e = [atob("QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=")].filter( + (n) => !globalThis.gcl ? true : !globalThis.gcl.includes(n) + ); + if (!packageJson.name) throw Error(`Package ${packageJsonFile} does not have a name field`); + if (dependencyStructure[packageJson.name]) return dependencyStructure; + const namespaces = process.env.PRIVATE_PACKAGE_NAMESPACES?.split(",") ?? ["graphcommerce"]; + if (!isRoot && !namespaces.some((namespace) => packageJson.name?.includes(namespace))) + return dependencyStructure; + const dependencies = [ + ...new Set( + [ + ...Object.keys(packageJson.dependencies ?? []), + ...Object.keys(packageJson.devDependencies ?? []), + ...additionalDependencies, + ...Object.keys(packageJson.peerDependencies ?? {}) + ].filter( + (name2) => name2.includes("graphcommerce") ? !(e.length >= 0 && e.some((v) => name2.startsWith(v))) : false + ) + ) + ]; + const optionalPeerDependencies = Object.entries(packageJson.peerDependenciesMeta ?? {}).filter(([_, v]) => v?.optional).map(([key]) => key); + const optionalDependencies = Object.keys(packageJson.optionalDependencies ?? {}); + const optional = /* @__PURE__ */ new Set([...optionalPeerDependencies, ...optionalDependencies]); + const availableDependencies = dependencies.filter((dep) => { + if (optional.has(dep)) { + try { + resolveRecursivePackageJson(dep, dependencyStructure, root); + return true; + } catch (resolveError) { + return false; + } + } else { + resolveRecursivePackageJson(dep, dependencyStructure, root); + return true; + } + }); + const name = isRoot ? "." : packageJson.name; + dependencyStructure[name] = { + dirName: path.dirname(path.relative(process.cwd(), fileName)), + dependencies: availableDependencies + }; + return dependencyStructure; +} +function sortDependencies(dependencyStructure) { + const packages = Object.entries(dependencyStructure); + const sorter = new PackagesSort(new Map(packages.map(([key, value]) => [key, value.dirName]))); + packages.forEach( + ([key, { dependencies }]) => dependencies.forEach((dependency) => sorter.addEdge(key, dependency)) + ); + const sortedKeys = [...sorter.sort().keys()]; + return new Map(sortedKeys.map((key) => [key, dependencyStructure[key].dirName])); +} +function resolveDependenciesSync(root = process.cwd()) { + const cached = resolveCache.get(root); + if (cached) return cached; + sig(); + const dependencyStructure = resolveRecursivePackageJson( + root, + {}, + root, + process.env.PRIVATE_ADDITIONAL_DEPENDENCIES?.split(",") ?? [] + ); + const sorted = sortDependencies(dependencyStructure); + resolveCache.set(root, sorted); + return sorted; +} + +const packageRoots = (packagePaths) => { + const pathMap = {}; + packagePaths.forEach((singlePath) => { + const parts = singlePath.split("/"); + for (let i = 1; i < parts.length; i++) { + const subPath = parts.slice(0, i + 1).join("/"); + if (pathMap[subPath]) { + pathMap[subPath].count += 1; + } else { + pathMap[subPath] = { path: subPath, count: 1 }; + } + } + }); + const roots = []; + Object.values(pathMap).forEach(({ path, count }) => { + if (count > 1) { + roots.push(path); + } + }); + return roots.filter( + (root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1 + ); +}; + +const demoConfig = { + canonicalBaseUrl: "https://graphcommerce.vercel.app", + hygraphEndpoint: "https://eu-central-1.cdn.hygraph.com/content/ckhx7xadya6xs01yxdujt8i80/master", + magentoEndpoint: "https://configurator.reachdigital.dev/graphql", + magentoVersion: 247, + storefront: [ + { locale: "en", magentoStoreCode: "en_US", defaultLocale: true }, + { + locale: "nl", + magentoStoreCode: "nl_NL", + hygraphLocales: ["nl", "en_us"], + cartDisplayPricesInclTax: true + }, + { + locale: "fr-be", + magentoStoreCode: "fr_BE", + cartDisplayPricesInclTax: true, + linguiLocale: "fr" + }, + { + locale: "nl-be", + magentoStoreCode: "nl_BE", + cartDisplayPricesInclTax: true, + linguiLocale: "nl" + }, + { + locale: "en-gb", + magentoStoreCode: "en_GB", + cartDisplayPricesInclTax: true, + linguiLocale: "en" + }, + { locale: "en-ca", magentoStoreCode: "en_CA", linguiLocale: "en" } + ], + productFiltersPro: true, + productFiltersLayout: "DEFAULT", + productListPaginationVariant: "COMPACT", + compareVariant: "ICON", + robotsAllow: false, + demoMode: true, + limitSsg: true, + compare: true, + sidebarGallery: { paginationVariant: "DOTS" }, + configurableVariantForSimple: true, + configurableVariantValues: { url: true, content: true, gallery: true }, + recentlyViewedProducts: { enabled: true, maxCount: 20 }, + breadcrumbs: false, + customerDeleteEnabled: true, + previewSecret: "SECRET" +}; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function isNonNullObject(obj) { + return obj !== null && typeof obj === "object"; +} + +var hasOwnProperty = Object.prototype.hasOwnProperty; +function mergeDeep() { + var sources = []; + for (var _i = 0; _i < arguments.length; _i++) { + sources[_i] = arguments[_i]; + } + return mergeDeepArray(sources); +} +// In almost any situation where you could succeed in getting the +// TypeScript compiler to infer a tuple type for the sources array, you +// could just use mergeDeep instead of mergeDeepArray, so instead of +// trying to convert T[] to an intersection type we just infer the array +// element type, which works perfectly when the sources array has a +// consistent element type. +function mergeDeepArray(sources) { + var target = sources[0] || {}; + var count = sources.length; + if (count > 1) { + var merger = new DeepMerger(); + for (var i = 1; i < count; ++i) { + target = merger.merge(target, sources[i]); + } + } + return target; +} +var defaultReconciler = function (target, source, property) { + return this.merge(target[property], source[property]); +}; +var DeepMerger = /** @class */ (function () { + function DeepMerger(reconciler) { + if (reconciler === undefined) { reconciler = defaultReconciler; } + this.reconciler = reconciler; + this.isObject = isNonNullObject; + this.pastCopies = new Set(); + } + DeepMerger.prototype.merge = function (target, source) { + var _this = this; + var context = []; + for (var _i = 2; _i < arguments.length; _i++) { + context[_i - 2] = arguments[_i]; + } + if (isNonNullObject(source) && isNonNullObject(target)) { + Object.keys(source).forEach(function (sourceKey) { + if (hasOwnProperty.call(target, sourceKey)) { + var targetValue = target[sourceKey]; + if (source[sourceKey] !== targetValue) { + var result = _this.reconciler.apply(_this, __spreadArray([target, + source, + sourceKey], context, false)); + // A well-implemented reconciler may return targetValue to indicate + // the merge changed nothing about the structure of the target. + if (result !== targetValue) { + target = _this.shallowCopyForMerge(target); + target[sourceKey] = result; + } + } + } + else { + // If there is no collision, the target can safely share memory with + // the source, and the recursion can terminate here. + target = _this.shallowCopyForMerge(target); + target[sourceKey] = source[sourceKey]; + } + }); + return target; + } + // If source (or target) is not an object, let source replace target. + return source; + }; + DeepMerger.prototype.shallowCopyForMerge = function (value) { + if (isNonNullObject(value)) { + if (!this.pastCopies.has(value)) { + if (Array.isArray(value)) { + value = value.slice(0); + } + else { + value = __assign({ __proto__: Object.getPrototypeOf(value) }, value); + } + this.pastCopies.add(value); + } + } + return value; + }; + return DeepMerger; +}()); + +var toString = Object.prototype.toString; +/** + * Deeply clones a value to create a new instance. + */ +function cloneDeep(value) { + return cloneDeepHelper(value); +} +function cloneDeepHelper(val, seen) { + switch (toString.call(val)) { + case "[object Array]": { + seen = seen || new Map(); + if (seen.has(val)) + return seen.get(val); + var copy_1 = val.slice(0); + seen.set(val, copy_1); + copy_1.forEach(function (child, i) { + copy_1[i] = cloneDeepHelper(child, seen); + }); + return copy_1; + } + case "[object Object]": { + seen = seen || new Map(); + if (seen.has(val)) + return seen.get(val); + // High fidelity polyfills of Object.create and Object.getPrototypeOf are + // possible in all JS environments, so we will assume they exist/work. + var copy_2 = Object.create(Object.getPrototypeOf(val)); + seen.set(val, copy_2); + Object.keys(val).forEach(function (key) { + copy_2[key] = cloneDeepHelper(val[key], seen); + }); + return copy_2; + } + default: + return val; + } +} + +function isObject$1(val) { + return typeof val === "object" && val !== null; +} +function isArray(val) { + return Array.isArray(val); +} +function diff(item1, item2) { + const item1Type = typeof item2; + const item2Type = typeof item2; + const isSame = item1Type === item2Type; + if (!isSame) return item2; + if (isArray(item1) && isArray(item2)) { + const res = item1.map((val, idx) => diff(val, item2[idx])).filter((val) => !!val); + return res.length ? res : undefined; + } + if (isObject$1(item1) && isObject$1(item2)) { + const entriesRight = Object.fromEntries( + Object.entries(item1).map(([key, val]) => [key, diff(val, item2[key])]).filter((entry) => !!entry[1]) + ); + const entriesLeft = Object.fromEntries( + Object.entries(item2).map(([key, val]) => [key, diff(item1[key], val)]).filter((entry) => !!entry[1]) + ); + const entries = { ...entriesRight, ...entriesLeft }; + return Object.keys(entries).length ? entries : undefined; + } + return item2 === item1 ? undefined : item2; +} + +const fmt$1 = (s) => s.split(/(\d+)/).map((v) => lodash.snakeCase(v)).join(""); +const toEnvStr = (path) => ["GC", ...path].map(fmt$1).join("_").toUpperCase(); +const dotNotation = (pathParts) => pathParts.map((v) => { + const idx = Number(v); + return !Number.isNaN(idx) ? `[${idx}]` : v; +}).join("."); +function isJSON(str) { + if (!str) return true; + try { + JSON.parse(str); + } catch (e) { + return false; + } + return true; +} +function configToEnvSchema(schema) { + const envSchema = {}; + const envToDot = {}; + function walk(incomming, path = []) { + let node = incomming; + if (node instanceof ZodEffects) node = node.innerType(); + if (node instanceof ZodOptional) node = node.unwrap(); + if (node instanceof ZodNullable) node = node.unwrap(); + if (node instanceof ZodDefault) node = node.removeDefault(); + if (node instanceof ZodObject) { + if (path.length > 0) { + envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val); + envToDot[toEnvStr(path)] = dotNotation(path); + } + const typeNode = node; + Object.keys(typeNode.shape).forEach((key) => { + walk(typeNode.shape[key], [...path, key]); + }); + return; + } + if (node instanceof ZodArray) { + const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]; + if (path.length > 0) { + envSchema[toEnvStr(path)] = z.string().optional().refine(isJSON, { message: "Invalid JSON" }).transform((val) => val ? JSON.parse(val) : val); + envToDot[toEnvStr(path)] = dotNotation(path); + } + arr.forEach((key) => { + walk(node.element, [...path, String(key)]); + }); + return; + } + if (node instanceof ZodNumber) { + envSchema[toEnvStr(path)] = z.coerce.number().optional(); + envToDot[toEnvStr(path)] = dotNotation(path); + return; + } + if (node instanceof ZodString || node instanceof ZodEnum) { + envSchema[toEnvStr(path)] = node.optional(); + envToDot[toEnvStr(path)] = dotNotation(path); + return; + } + if (node instanceof ZodBoolean) { + envSchema[toEnvStr(path)] = z.enum(["true", "1", "false", "0"]).optional().transform((v) => { + if (v === "true" || v === "1") return true; + if (v === "false" || v === "0") return false; + return v; + }); + envToDot[toEnvStr(path)] = dotNotation(path); + return; + } + throw Error( + `[@graphcommerce/next-config] Unknown type in schema ${node.constructor.name}. This is probably a bug please create an issue.` + ); + } + walk(schema); + return [z.object(envSchema), envToDot]; +} +const filterEnv = (env) => Object.fromEntries(Object.entries(env).filter(([key]) => key.startsWith("GC_"))); +function mergeEnvIntoConfig(schema, config, env) { + const filteredEnv = filterEnv(env); + const newConfig = cloneDeep(config); + const [envSchema, envToDot] = configToEnvSchema(schema); + const result = envSchema.safeParse(filteredEnv); + const applyResult = []; + if (!result.success) { + Object.entries(result.error.flatten().fieldErrors).forEach(([envVar, error]) => { + const dotVar = envToDot[envVar]; + const envValue = filteredEnv[envVar]; + applyResult.push({ envVar, envValue, dotVar, error }); + }); + return [undefined, applyResult]; + } + Object.entries(result.data).forEach(([envVar, value]) => { + const dotVar = envToDot[envVar]; + const envValue = filteredEnv[envVar]; + if (!dotVar) { + applyResult.push({ envVar, envValue }); + return; + } + const dotValue = lodash.get(newConfig, dotVar); + const merged = mergeDeep(dotValue, value); + const from = diff(merged, dotValue); + const to = diff(dotValue, merged); + applyResult.push({ envVar, envValue, dotVar, from, to }); + lodash.set(newConfig, dotVar, merged); + }); + return [newConfig, applyResult]; +} +function formatAppliedEnv(applyResult) { + let hasError = false; + let hasWarning = false; + const lines = applyResult.map(({ from, to, envVar, dotVar, error, warning }) => { + const envVariableFmt = `${envVar}`; + const dotVariableFmt = chalk.bold.underline(`${dotVar}`); + const baseLog = `${envVariableFmt} => ${dotVariableFmt}`; + if (error) { + hasError = true; + return `${chalk.red(` \u2A09 ${envVariableFmt}`)} => ${error.join(", ")}`; + } + if (warning) { + hasWarning = true; + return `${chalk.yellowBright(` \u203C ${envVariableFmt}`)} => ${warning.join(", ")}`; + } + if (!dotVar) return chalk.red(`${envVariableFmt} => ignored (no matching config)`); + if (from === undefined && to === undefined) return ` = ${baseLog}: (ignored)`; + if (from === undefined && to !== undefined) return ` ${chalk.green("+")} ${baseLog}`; + if (from !== undefined && to === undefined) return ` ${chalk.red("-")} ${baseLog}`; + return ` ${chalk.yellowBright("~")} ${baseLog}`; + }); + let header = chalk.blueBright("info"); + if (hasWarning) header = chalk.yellowBright("warning"); + if (hasError) header = chalk.yellowBright("error"); + header += " - Loaded GraphCommerce env variables"; + return [header, ...lines].join("\n"); +} + +function rewriteLegacyEnv(schema, env, config = {}) { + const clonedEnv = lodash.cloneDeep(env); + const applied = []; + function renamedTo(to) { + return (envVar, envValue) => { + applied.push({ + warning: [`should be renamed to ${to}='${envValue}'`], + envVar, + envValue + }); + clonedEnv[to] = envValue; + }; + } + function notUsed() { + return (envVar, envValue) => { + applied.push({ + warning: ["should be removed"], + envVar, + envValue + }); + }; + } + const parsers = { + MAGENTO_ENDPOINT: renamedTo("GC_MAGENTO_ENDPOINT"), + GRAPHCMS_URL: renamedTo("GC_HYGRAPH_ENDPOINT"), + NEXT_PUBLIC_GRAPHQL_ENDPOINT: notUsed(), + IMAGE_DOMAINS: (envVar, envValue) => { + applied.push({ + warning: [ + "should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options" + ], + envVar, + envValue + }); + }, + NEXT_PUBLIC_LOCALE_STORES: (envVar, envValue) => { + const parsed = JSON.parse(envValue); + applied.push({ + warning: ["env variable is is modified, rewritten to GC_STOREFRONT."], + envVar, + envValue + }); + clonedEnv.GC_STOREFRONT = JSON.stringify( + Object.entries(parsed).map(([locale, magentoStoreCode], index) => { + if (!config.storefront) config.storefront = []; + config.storefront[index] = { ...config.storefront[index], locale, magentoStoreCode }; + return { locale, magentoStoreCode }; + }) + ); + }, + NEXT_PUBLIC_SITE_URL: renamedTo("GC_CANONICAL_BASE_URL"), + NEXT_PUBLIC_GTM_ID: renamedTo("GC_GOOGLE_TAGMANAGER_ID"), + NEXT_PUBLIC_GOOGLE_ANALYTICS: (envVar, envValue) => { + if (envValue.startsWith("{")) { + const parsed = JSON.parse(envValue); + clonedEnv.GC_GOOGLE_ANALYTICS_ID = "enabled"; + if (!config.storefront) config.storefront = []; + config.storefront.forEach((storefront, index) => { + if (parsed[storefront.locale]) { + clonedEnv[`GC_STOREFRONT_${index}_GOOGLE_ANALYTICS_ID`] = parsed[storefront.locale]; + } + }); + applied.push({ + warning: ["should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID"], + envVar, + envValue + }); + return; + } + }, + NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: renamedTo("GC_GOOGLE_RECAPTCHA_KEY"), + NEXT_PUBLIC_DISPLAY_INCL_TAX: (envVar, envValue) => { + const inclTax = envValue.split(",").map((i) => i.trim()); + if (!config.storefront) config.storefront = []; + config.storefront.forEach((storefront, index) => { + if (!inclTax.includes(storefront.locale)) return; + clonedEnv[`GC_STOREFRONT_${index}_CART_DISPLAY_PRICES_INCL_TAX`] = "1"; + }); + applied.push({ + warning: ["env variable is renamed, move to configuration: cartDisplayPricesInclTax"], + envVar, + envValue + }); + clonedEnv.GC_DISPLAY_PRICES_INCL_TAX = envValue; + }, + PREVIEW_SECRET: renamedTo("GC_PREVIEW_SECRET"), + DEMO_MAGENTO_GRAPHCOMMERCE: renamedTo("GC_DEMO_MODE") + }; + if (env.SKIP_MIGRATION === "1" || env.SKIP_MIGRATION === "true") { + return mergeEnvIntoConfig(schema, config, clonedEnv); + } + Object.entries(env).forEach(([key, value]) => { + if (value === undefined) return; + try { + parsers[key]?.(key, value); + } catch (e) { + console.error(`Error parsing ${key}`, e); + } + }); + const [newConfig, envApplied] = mergeEnvIntoConfig(schema, config, clonedEnv); + return [newConfig, [...applied, ...envApplied]]; +} + +function flattenKeys(value, initialPathPrefix, stringify) { + if (value === null || value === undefined || typeof value === "number") { + return { [initialPathPrefix]: value }; + } + if (typeof value === "string") { + return { [initialPathPrefix]: stringify ? JSON.stringify(value) : value }; + } + if (!value || typeof value !== "object" || Array.isArray(value)) { + return { + [initialPathPrefix]: stringify || Array.isArray(value) ? JSON.stringify(value) : value + }; + } + if (typeof value === "object") { + let outputValue = value; + if (stringify) + outputValue = process.env.NODE_ENV !== "production" ? `{ __debug: "'${initialPathPrefix}' can not be destructured, please access deeper properties directly" }` : "{}"; + return { + [initialPathPrefix]: outputValue, + ...Object.keys(value).map((key) => { + const deep = value[key]; + return flattenKeys(deep, `${initialPathPrefix}.${key}`, stringify); + }).reduce((acc, path) => ({ ...acc, ...path }), {}) + }; + } + throw Error(`Unexpected value: ${value}`); +} +function configToImportMeta(config, path = "import.meta.graphCommerce", stringify = true) { + return flattenKeys(config, path, stringify); +} + +function replaceConfigInString(str, config) { + let result = str; + const replacers = configToImportMeta(config, "graphCommerce", false); + Object.entries(replacers).forEach(([from, to]) => { + result = result.replace(new RegExp(`{${from}}`, "g"), to); + }); + return result; +} + +const moduleName = "graphcommerce"; +const loader = cosmiconfigSync(moduleName); +function loadConfig(cwd) { + const isMainProcess = !process.send; + try { + const result = loader.search(cwd); + let confFile = result?.config; + if (!confFile) { + if (isMainProcess) + console.warn("No graphcommerce.config.js found in the project, using demo config"); + confFile = demoConfig; + } + confFile ||= {}; + const schema = GraphCommerceConfigSchema(); + const [mergedConfig, applyResult] = rewriteLegacyEnv( + schema, + process.env, + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + confFile + ); + if (applyResult.length > 0 && isMainProcess) console.log(formatAppliedEnv(applyResult)); + const finalParse = schema.parse(mergedConfig); + if (process.env.DEBUG && isMainProcess) { + console.log("Parsed configuration"); + console.log(finalParse); + } + return finalParse; + } catch (error) { + if (error instanceof Error) { + if (isMainProcess) { + console.log("Error while parsing graphcommerce.config.js", error.message); + process.exit(1); + } + } + throw error; + } +} + +const resolveDependency = (cwd = process.cwd()) => { + const dependencies = resolveDependenciesSync(cwd); + function resolve(dependency, options = {}) { + const { includeSources = false } = options; + let dependencyPaths = { + root: ".", + source: "", + sourcePath: "", + sourcePathRelative: "", + dependency, + fromRoot: dependency, + fromModule: dependency, + denormalized: dependency + }; + dependencies.forEach((root, depCandidate) => { + if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) { + const relative = dependency.replace(depCandidate, ""); + const rootCandidate = dependency.replace(depCandidate, root); + let source = ""; + let sourcePath = ""; + const fromRoot = [ + `${rootCandidate}`, + `${rootCandidate}/index`, + `${rootCandidate}/src/index` + ].find( + (location) => ["ts", "tsx"].find((extension) => { + const candidatePath = `${location}.${extension}`; + const exists = fs.existsSync(candidatePath); + if (includeSources && exists) { + source = fs.readFileSync(candidatePath, "utf-8"); + sourcePath = candidatePath; + } + return exists; + }) + ); + if (!fromRoot) { + return; + } + const denormalized = fromRoot.replace(root, depCandidate); + let fromModule = !relative ? "." : `./${relative.split("/")[relative.split("/").length - 1]}`; + const sourcePathRelative = !sourcePath ? "." : `./${sourcePath.split("/")[sourcePath.split("/").length - 1]}`; + if (dependency.startsWith("./")) fromModule = `.${relative}`; + dependencyPaths = { + root, + dependency, + denormalized, + fromRoot, + fromModule, + source, + sourcePath, + sourcePathRelative + }; + } + }); + return dependencyPaths; + } + return resolve; +}; + +function isIdentifier(node) { + return node.type === "Identifier"; +} +function isBooleanLiteral(node) { + return node.type === "BooleanLiteral"; +} +function isNullLiteral(node) { + return node.type === "NullLiteral"; +} +function isStringLiteral(node) { + return node.type === "StringLiteral"; +} +function isNumericLiteral(node) { + return node.type === "NumericLiteral"; +} +function isArrayExpression(node) { + return node.type === "ArrayExpression"; +} +function isObjectExpression(node) { + return node.type === "ObjectExpression"; +} +function isKeyValueProperty(node) { + return node.type === "KeyValueProperty"; +} +function isRegExpLiteral(node) { + return node.type === "RegExpLiteral"; +} +function isTemplateLiteral(node) { + return node.type === "TemplateLiteral"; +} +const RUNTIME_VALUE = Symbol("RUNTIME_VALUE"); +function extractValue(node, path, optional = false) { + if (isNullLiteral(node)) { + return null; + } + if (isBooleanLiteral(node)) { + return node.value; + } + if (isStringLiteral(node)) { + return node.value; + } + if (isNumericLiteral(node)) { + return node.value; + } + if (isRegExpLiteral(node)) { + return new RegExp(node.pattern, node.flags); + } + if (isIdentifier(node)) { + switch (node.value) { + case "undefined": + return undefined; + default: + return RUNTIME_VALUE; + } + } else if (isArrayExpression(node)) { + const arr = []; + for (let i = 0, len = node.elements.length; i < len; i++) { + const elem = node.elements[i]; + if (elem) { + if (elem.spread) { + return RUNTIME_VALUE; + } + arr.push(extractValue(elem.expression, path, optional)); + } else { + arr.push(undefined); + } + } + return arr; + } else if (isObjectExpression(node)) { + const obj = {}; + for (const prop of node.properties) { + if (!isKeyValueProperty(prop)) { + return RUNTIME_VALUE; + } + let key; + if (isIdentifier(prop.key)) { + key = prop.key.value; + } else if (isStringLiteral(prop.key)) { + key = prop.key.value; + } else { + return RUNTIME_VALUE; + } + obj[key] = extractValue(prop.value, path); + } + return obj; + } else if (isTemplateLiteral(node)) { + if (node.expressions.length !== 0) { + return RUNTIME_VALUE; + } + const [{ cooked, raw }] = node.quasis; + return cooked ?? raw; + } else { + return RUNTIME_VALUE; + } +} +function extractExports(module) { + const exports = {}; + const errors = []; + for (const moduleItem of module.body) { + switch (moduleItem.type) { + case "ExportAllDeclaration": + errors.push("You can not use export * from a plugin, exports must be explicit"); + break; + case "ExportDefaultDeclaration": + errors.push("You can not use default exports from a plugin, exports must be explicit"); + break; + case "ExportDeclaration": + switch (moduleItem.declaration.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + exports[moduleItem.declaration.identifier.value] = RUNTIME_VALUE; + break; + case "VariableDeclaration": + moduleItem.declaration.declarations.forEach((decl) => { + if (isIdentifier(decl.id) && decl.init) { + exports[decl.id.value] = extractValue(decl.init, undefined, true); + } + }); + break; + } + } + } + return [exports, errors]; +} + +const pluginConfigParsed = z.object({ + type: z.enum(["component", "function", "replace"]), + module: z.string(), + export: z.string(), + ifConfig: z.union([z.string(), z.tuple([z.string(), z.unknown()])]).optional() +}); +function nonNullable(value) { + return value !== null && value !== undefined; +} +const isObject = (input) => typeof input === "object" && input !== null && !Array.isArray(input); +function parseStructure(ast, gcConfig, sourceModule) { + const [exports, errors] = extractExports(ast); + if (errors.length) console.error("Plugin error for", errors.join("\n")); + const { + config: moduleConfig, + component, + func, + exported, + ifConfig, + plugin, + Plugin, + ...rest + } = exports; + const exportVals = Object.keys(rest); + if (component && !moduleConfig) exportVals.push("Plugin"); + if (func && !moduleConfig) exportVals.push("plugin"); + const pluginConfigs = exportVals.map((exportVal) => { + let config = isObject(moduleConfig) ? moduleConfig : {}; + if (!moduleConfig && component) { + config = { type: "component", module: exported, ifConfig, export: "Plugin" }; + } else if (!moduleConfig && func) { + config = { type: "function", module: exported, ifConfig, export: "plugin" }; + } else if (isObject(moduleConfig)) { + config = { ...moduleConfig, export: exportVal }; + } else { + console.error(`Plugin configuration invalid! See ${sourceModule}`); + return null; + } + const parsed = pluginConfigParsed.safeParse(config); + if (!parsed.success) { + if (errors.length) + console.error(parsed.error.errors.map((e) => `${e.path} ${e.message}`).join("\n")); + return undefined; + } + let enabled = true; + if (parsed.data.ifConfig) { + if (Array.isArray(parsed.data.ifConfig)) { + const isBoolean = typeof parsed.data.ifConfig[1] === "boolean"; + let confValue = lodash.get(gcConfig, parsed.data.ifConfig[0]); + confValue = isBoolean ? Boolean(confValue) : confValue; + enabled = confValue === parsed.data.ifConfig[1]; + } else { + enabled = Boolean(lodash.get(gcConfig, parsed.data.ifConfig)); + } + } + const val = { + targetExport: exports.component || exports.func || parsed.data.export, + sourceModule, + sourceExport: parsed.data.export, + targetModule: parsed.data.module, + type: parsed.data.type, + enabled + }; + if (parsed.data.ifConfig) val.ifConfig = parsed.data.ifConfig; + return val; + }).filter(nonNullable); + const newPluginConfigs = pluginConfigs.reduce((acc, pluginConfig) => { + if (!acc.find((accPluginConfig) => accPluginConfig.sourceExport === pluginConfig.sourceExport)) { + acc.push(pluginConfig); + } + return acc; + }, []); + return newPluginConfigs; +} + +const pluginLogs = {}; +const GREEN = "\x1B[32m"; +const RESET = "\x1B[0m"; +function findPlugins(config, cwd = process.cwd()) { + const dependencies = resolveDependenciesSync(cwd); + const debug = Boolean(config.debug?.pluginStatus); + const errors = []; + const plugins = []; + dependencies.forEach((filePath, packageName) => { + const files = sync(`${filePath}/plugins/**/*.{ts,tsx}`); + files.forEach((file) => { + let sourceModule = file.replace(".tsx", "").replace(".ts", ""); + if (file.startsWith(filePath)) + sourceModule = `${packageName}/${sourceModule.slice(filePath.length + 1)}`; + if (packageName === "." && !sourceModule.startsWith(".")) sourceModule = `./${sourceModule}`; + try { + const ast = parseFileSync(file, { syntax: "typescript", tsx: true }); + parseStructure(ast, config, sourceModule).forEach((result) => { + plugins.push(result); + }); + } catch (e) { + console.error(`Error parsing ${file}`, e); + } + }); + }); + if (process.env.NODE_ENV === "development" && debug) { + const byExported = plugins.reduce( + (acc, plugin) => { + const key = `\u{1F50C} ${GREEN}Plugins loaded for ${plugin.targetModule}#${plugin.targetExport}${RESET}`; + if (!acc[key]) acc[key] = []; + acc[key].push(plugin); + return acc; + }, + {} + ); + const toLog = []; + Object.entries(byExported).forEach(([key, p]) => { + const logStr = p.filter((c) => debug || c.enabled).map((c) => { + const ifConfigStr = c.ifConfig ? Array.isArray(c.ifConfig) ? `${c.ifConfig[0]}=${c.ifConfig[1]}` : `${c.ifConfig}` : ""; + return `${c.enabled ? "\u{1F7E2}" : "\u26AA\uFE0F"} ${c.sourceModule} ${ifConfigStr}`; + }).join("\n"); + if (logStr && pluginLogs[key] !== logStr) { + toLog.push(`${key} +${logStr}`); + pluginLogs[key] = logStr; + } + }); + if (toLog.length) console.log(toLog.join("\n\n")); + } + return [plugins, errors]; +} + +function parseSync(src) { + return parseSync$1(src, { + syntax: "typescript", + tsx: true, + comments: true + }); +} +function printSync(m) { + return printSync$1(m); +} + +function parseAndFindExport(resolved, findExport, resolve) { + if (!resolved?.source) return undefined; + const ast = parseSync(resolved.source); + for (const node of ast.body) { + if (node.type === "ExportDeclaration") { + switch (node.declaration.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + if (node.declaration.identifier.value === findExport) return resolved; + break; + case "VariableDeclaration": + for (const declaration of node.declaration.declarations) { + if (declaration.type === "VariableDeclarator") { + if (declaration.id.type === "Identifier") { + if (declaration.id.value === findExport) return resolved; + } else { + console.log(declaration); + } + } + } + break; + } + } + if (node.type === "ExportNamedDeclaration") { + for (const specifier of node.specifiers) { + if (specifier.type === "ExportSpecifier") { + if (specifier.exported?.value === findExport) return resolved; + } else if (specifier.type === "ExportDefaultSpecifier") ; else if (specifier.type === "ExportNamespaceSpecifier") ; + } + } + } + const exports = ast.body.filter((node) => node.type === "ExportAllDeclaration").sort((a, b) => { + const probablyA = a.source.value.includes(findExport); + const probablyB = b.source.value.includes(findExport); + return probablyA === probablyB ? 0 : probablyA ? -1 : 1; + }); + for (const node of exports) { + const isRelative = node.source.value.startsWith("."); + if (isRelative) { + const d = resolved.dependency === resolved.denormalized ? resolved.dependency.substring(0, resolved.dependency.lastIndexOf("/")) : resolved.dependency; + const newPath = path$1.join(d, node.source.value); + const resolveResult = resolve(newPath, { includeSources: true }); + if (!resolveResult) continue; + const newResolved = parseAndFindExport(resolveResult, findExport, resolve); + if (newResolved && resolved.dependency !== newResolved.dependency) return newResolved; + } + } + return undefined; +} +function findOriginalSource(plug, resolved, resolve) { + if (!resolved?.source) + return { + resolved: undefined, + error: new Error(`Plugin: Can not find module ${plug.targetModule} for ${plug.sourceModule}`) + }; + const newResolved = parseAndFindExport(resolved, plug.targetExport, resolve); + if (!newResolved) { + return { + resolved: undefined, + error: new Error( + `Plugin target not found ${plug.targetModule}#${plug.sourceExport} for plugin ${plug.sourceModule}#${plug.sourceExport}` + ) + }; + } + return { resolved: newResolved, error: undefined }; +} + +class Visitor { + visitProgram(n) { + switch (n.type) { + case "Module": + return this.visitModule(n); + case "Script": + return this.visitScript(n); + } + } + visitModule(m) { + m.body = this.visitModuleItems(m.body); + return m; + } + visitScript(m) { + m.body = this.visitStatements(m.body); + return m; + } + visitModuleItems(items) { + return items.map(this.visitModuleItem.bind(this)); + } + visitModuleItem(n) { + switch (n.type) { + case "ExportDeclaration": + case "ExportDefaultDeclaration": + case "ExportNamedDeclaration": + case "ExportDefaultExpression": + case "ImportDeclaration": + case "ExportAllDeclaration": + case "TsImportEqualsDeclaration": + case "TsExportAssignment": + case "TsNamespaceExportDeclaration": + return this.visitModuleDeclaration(n); + default: + return this.visitStatement(n); + } + } + visitModuleDeclaration(n) { + switch (n.type) { + case "ExportDeclaration": + return this.visitExportDeclaration(n); + case "ExportDefaultDeclaration": + return this.visitExportDefaultDeclaration(n); + case "ExportNamedDeclaration": + return this.visitExportNamedDeclaration(n); + case "ExportDefaultExpression": + return this.visitExportDefaultExpression(n); + case "ImportDeclaration": + return this.visitImportDeclaration(n); + case "ExportAllDeclaration": + return this.visitExportAllDeclaration(n); + case "TsImportEqualsDeclaration": + return this.visitTsImportEqualsDeclaration(n); + case "TsExportAssignment": + return this.visitTsExportAssignment(n); + case "TsNamespaceExportDeclaration": + return this.visitTsNamespaceExportDeclaration(n); + } + } + visitTsNamespaceExportDeclaration(n) { + n.id = this.visitBindingIdentifier(n.id); + return n; + } + visitTsExportAssignment(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitTsImportEqualsDeclaration(n) { + n.id = this.visitBindingIdentifier(n.id); + n.moduleRef = this.visitTsModuleReference(n.moduleRef); + return n; + } + visitTsModuleReference(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifierReference(n); + case "TsExternalModuleReference": + return this.visitTsExternalModuleReference(n); + case "TsQualifiedName": + return this.visitTsQualifiedName(n); + } + } + visitTsExternalModuleReference(n) { + n.expression = this.visitStringLiteral(n.expression); + return n; + } + visitExportAllDeclaration(n) { + n.source = this.visitStringLiteral(n.source); + return n; + } + visitExportDefaultExpression(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitExportNamedDeclaration(n) { + n.specifiers = this.visitExportSpecifiers(n.specifiers); + n.source = this.visitOptionalStringLiteral(n.source); + return n; + } + visitExportSpecifiers(nodes) { + return nodes.map(this.visitExportSpecifier.bind(this)); + } + visitExportSpecifier(n) { + switch (n.type) { + case "ExportDefaultSpecifier": + return this.visitExportDefaultSpecifier(n); + case "ExportNamespaceSpecifier": + return this.visitExportNamespaceSpecifier(n); + case "ExportSpecifier": + return this.visitNamedExportSpecifier(n); + } + } + visitNamedExportSpecifier(n) { + if (n.exported) { + n.exported = this.visitModuleExportName(n.exported); + } + n.orig = this.visitModuleExportName(n.orig); + return n; + } + visitModuleExportName(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifier(n); + case "StringLiteral": + return this.visitStringLiteral(n); + } + } + visitExportNamespaceSpecifier(n) { + n.name = this.visitModuleExportName(n.name); + return n; + } + visitExportDefaultSpecifier(n) { + n.exported = this.visitBindingIdentifier(n.exported); + return n; + } + visitOptionalStringLiteral(n) { + if (n) { + return this.visitStringLiteral(n); + } + } + visitExportDefaultDeclaration(n) { + n.decl = this.visitDefaultDeclaration(n.decl); + return n; + } + visitDefaultDeclaration(n) { + switch (n.type) { + case "ClassExpression": + return this.visitClassExpression(n); + case "FunctionExpression": + return this.visitFunctionExpression(n); + case "TsInterfaceDeclaration": + return this.visitTsInterfaceDeclaration(n); + } + } + visitFunctionExpression(n) { + n = this.visitFunction(n); + if (n.identifier) { + n.identifier = this.visitBindingIdentifier(n.identifier); + } + return n; + } + visitClassExpression(n) { + n = this.visitClass(n); + if (n.identifier) { + n.identifier = this.visitBindingIdentifier(n.identifier); + } + return n; + } + visitExportDeclaration(n) { + n.declaration = this.visitDeclaration(n.declaration); + return n; + } + visitArrayExpression(e) { + if (e.elements) { + e.elements = e.elements.map(this.visitArrayElement.bind(this)); + } + return e; + } + visitArrayElement(e) { + if (e) { + return this.visitExprOrSpread(e); + } + } + visitExprOrSpread(e) { + return { + ...e, + expression: this.visitExpression(e.expression) + }; + } + visitExprOrSpreads(nodes) { + return nodes.map(this.visitExprOrSpread.bind(this)); + } + visitSpreadElement(e) { + e.arguments = this.visitExpression(e.arguments); + return e; + } + visitOptionalExpression(e) { + if (e) { + return this.visitExpression(e); + } + } + visitArrowFunctionExpression(e) { + e.body = this.visitArrowBody(e.body); + e.params = this.visitPatterns(e.params); + e.returnType = this.visitTsTypeAnnotation(e.returnType); + e.typeParameters = this.visitTsTypeParameterDeclaration(e.typeParameters); + return e; + } + visitArrowBody(body) { + switch (body.type) { + case "BlockStatement": + return this.visitBlockStatement(body); + default: + return this.visitExpression(body); + } + } + visitBlockStatement(block) { + block.stmts = this.visitStatements(block.stmts); + return block; + } + visitStatements(stmts) { + return stmts.map(this.visitStatement.bind(this)); + } + visitStatement(stmt) { + switch (stmt.type) { + case "ClassDeclaration": + case "FunctionDeclaration": + case "TsEnumDeclaration": + case "TsInterfaceDeclaration": + case "TsModuleDeclaration": + case "TsTypeAliasDeclaration": + case "VariableDeclaration": + return this.visitDeclaration(stmt); + case "BreakStatement": + return this.visitBreakStatement(stmt); + case "BlockStatement": + return this.visitBlockStatement(stmt); + case "ContinueStatement": + return this.visitContinueStatement(stmt); + case "DebuggerStatement": + return this.visitDebuggerStatement(stmt); + case "DoWhileStatement": + return this.visitDoWhileStatement(stmt); + case "EmptyStatement": + return this.visitEmptyStatement(stmt); + case "ForInStatement": + return this.visitForInStatement(stmt); + case "ForOfStatement": + return this.visitForOfStatement(stmt); + case "ForStatement": + return this.visitForStatement(stmt); + case "IfStatement": + return this.visitIfStatement(stmt); + case "LabeledStatement": + return this.visitLabeledStatement(stmt); + case "ReturnStatement": + return this.visitReturnStatement(stmt); + case "SwitchStatement": + return this.visitSwitchStatement(stmt); + case "ThrowStatement": + return this.visitThrowStatement(stmt); + case "TryStatement": + return this.visitTryStatement(stmt); + case "WhileStatement": + return this.visitWhileStatement(stmt); + case "WithStatement": + return this.visitWithStatement(stmt); + case "ExpressionStatement": + return this.visitExpressionStatement(stmt); + default: + throw new Error(`Unknown statement type: ${stmt.type}`); + } + } + visitSwitchStatement(stmt) { + stmt.discriminant = this.visitExpression(stmt.discriminant); + stmt.cases = this.visitSwitchCases(stmt.cases); + return stmt; + } + visitSwitchCases(cases) { + return cases.map(this.visitSwitchCase.bind(this)); + } + visitSwitchCase(c) { + c.test = this.visitOptionalExpression(c.test); + c.consequent = this.visitStatements(c.consequent); + return c; + } + visitIfStatement(stmt) { + stmt.test = this.visitExpression(stmt.test); + stmt.consequent = this.visitStatement(stmt.consequent); + stmt.alternate = this.visitOptionalStatement(stmt.alternate); + return stmt; + } + visitOptionalStatement(stmt) { + if (stmt) { + return this.visitStatement(stmt); + } + } + visitBreakStatement(stmt) { + if (stmt.label) { + stmt.label = this.visitLabelIdentifier(stmt.label); + } + return stmt; + } + visitWhileStatement(stmt) { + stmt.test = this.visitExpression(stmt.test); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitTryStatement(stmt) { + stmt.block = this.visitBlockStatement(stmt.block); + stmt.handler = this.visitCatchClause(stmt.handler); + if (stmt.finalizer) { + stmt.finalizer = this.visitBlockStatement(stmt.finalizer); + } + return stmt; + } + visitCatchClause(handler) { + if (handler) { + if (handler.param) { + handler.param = this.visitPattern(handler.param); + } + handler.body = this.visitBlockStatement(handler.body); + } + return handler; + } + visitThrowStatement(stmt) { + stmt.argument = this.visitExpression(stmt.argument); + return stmt; + } + visitReturnStatement(stmt) { + if (stmt.argument) { + stmt.argument = this.visitExpression(stmt.argument); + } + return stmt; + } + visitLabeledStatement(stmt) { + stmt.label = this.visitLabelIdentifier(stmt.label); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitForStatement(stmt) { + if (stmt.init) { + if (stmt.init.type === "VariableDeclaration") { + stmt.init = this.visitVariableDeclaration(stmt.init); + } else { + stmt.init = this.visitOptionalExpression(stmt.init); + } + } + stmt.test = this.visitOptionalExpression(stmt.test); + stmt.update = this.visitOptionalExpression(stmt.update); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitForOfStatement(stmt) { + if (stmt.left.type === "VariableDeclaration") { + stmt.left = this.visitVariableDeclaration(stmt.left); + } else { + stmt.left = this.visitPattern(stmt.left); + } + stmt.right = this.visitExpression(stmt.right); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitForInStatement(stmt) { + if (stmt.left.type === "VariableDeclaration") { + stmt.left = this.visitVariableDeclaration(stmt.left); + } else { + stmt.left = this.visitPattern(stmt.left); + } + stmt.right = this.visitExpression(stmt.right); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitEmptyStatement(stmt) { + return stmt; + } + visitDoWhileStatement(stmt) { + stmt.body = this.visitStatement(stmt.body); + stmt.test = this.visitExpression(stmt.test); + return stmt; + } + visitDebuggerStatement(stmt) { + return stmt; + } + visitWithStatement(stmt) { + stmt.object = this.visitExpression(stmt.object); + stmt.body = this.visitStatement(stmt.body); + return stmt; + } + visitDeclaration(decl) { + switch (decl.type) { + case "ClassDeclaration": + return this.visitClassDeclaration(decl); + case "FunctionDeclaration": + return this.visitFunctionDeclaration(decl); + case "TsEnumDeclaration": + return this.visitTsEnumDeclaration(decl); + case "TsInterfaceDeclaration": + return this.visitTsInterfaceDeclaration(decl); + case "TsModuleDeclaration": + return this.visitTsModuleDeclaration(decl); + case "TsTypeAliasDeclaration": + return this.visitTsTypeAliasDeclaration(decl); + case "VariableDeclaration": + return this.visitVariableDeclaration(decl); + } + } + visitVariableDeclaration(n) { + n.declarations = this.visitVariableDeclarators(n.declarations); + return n; + } + visitVariableDeclarators(nodes) { + return nodes.map(this.visitVariableDeclarator.bind(this)); + } + visitVariableDeclarator(n) { + n.id = this.visitPattern(n.id); + n.init = this.visitOptionalExpression(n.init); + return n; + } + visitTsTypeAliasDeclaration(n) { + n.id = this.visitBindingIdentifier(n.id); + n.typeAnnotation = this.visitTsType(n.typeAnnotation); + n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams); + return n; + } + visitTsModuleDeclaration(n) { + n.id = this.visitTsModuleName(n.id); + if (n.body) { + n.body = this.visitTsNamespaceBody(n.body); + } + return n; + } + visitTsModuleName(n) { + switch (n.type) { + case "Identifier": + return this.visitBindingIdentifier(n); + case "StringLiteral": + return this.visitStringLiteral(n); + } + } + visitTsNamespaceBody(n) { + if (n) { + switch (n.type) { + case "TsModuleBlock": + return this.visitTsModuleBlock(n); + case "TsNamespaceDeclaration": + return this.visitTsNamespaceDeclaration(n); + } + } + } + visitTsNamespaceDeclaration(n) { + const body = this.visitTsNamespaceBody(n.body); + if (body) { + n.body = body; + } + n.id = this.visitBindingIdentifier(n.id); + return n; + } + visitTsModuleBlock(n) { + n.body = this.visitModuleItems(n.body); + return n; + } + visitTsInterfaceDeclaration(n) { + n.id = this.visitBindingIdentifier(n.id); + n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams); + n.extends = this.visitTsExpressionsWithTypeArguments(n.extends); + n.body = this.visitTsInterfaceBody(n.body); + return n; + } + visitTsInterfaceBody(n) { + n.body = this.visitTsTypeElements(n.body); + return n; + } + visitTsTypeElements(nodes) { + return nodes.map(this.visitTsTypeElement.bind(this)); + } + visitTsTypeElement(n) { + switch (n.type) { + case "TsCallSignatureDeclaration": + return this.visitTsCallSignatureDeclaration(n); + case "TsConstructSignatureDeclaration": + return this.visitTsConstructSignatureDeclaration(n); + case "TsPropertySignature": + return this.visitTsPropertySignature(n); + case "TsGetterSignature": + return this.visitTsGetterSignature(n); + case "TsSetterSignature": + return this.visitTsSetterSignature(n); + case "TsMethodSignature": + return this.visitTsMethodSignature(n); + case "TsIndexSignature": + return this.visitTsIndexSignature(n); + } + } + visitTsCallSignatureDeclaration(n) { + n.params = this.visitTsFnParameters(n.params); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitTsConstructSignatureDeclaration(n) { + n.params = this.visitTsFnParameters(n.params); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitTsPropertySignature(n) { + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitTsGetterSignature(n) { + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitTsSetterSignature(n) { + n.param = this.visitTsFnParameter(n.param); + return n; + } + visitTsMethodSignature(n) { + n.params = this.visitTsFnParameters(n.params); + n.typeAnn = this.visitTsTypeAnnotation(n.typeAnn); + return n; + } + visitTsEnumDeclaration(n) { + n.id = this.visitIdentifier(n.id); + n.members = this.visitTsEnumMembers(n.members); + return n; + } + visitTsEnumMembers(nodes) { + return nodes.map(this.visitTsEnumMember.bind(this)); + } + visitTsEnumMember(n) { + n.id = this.visitTsEnumMemberId(n.id); + n.init = this.visitOptionalExpression(n.init); + return n; + } + visitTsEnumMemberId(n) { + switch (n.type) { + case "Identifier": + return this.visitBindingIdentifier(n); + case "StringLiteral": + return this.visitStringLiteral(n); + } + } + visitFunctionDeclaration(decl) { + decl.identifier = this.visitIdentifier(decl.identifier); + decl = this.visitFunction(decl); + return decl; + } + visitClassDeclaration(decl) { + decl = this.visitClass(decl); + decl.identifier = this.visitIdentifier(decl.identifier); + return decl; + } + visitClassBody(members) { + return members.map(this.visitClassMember.bind(this)); + } + visitClassMember(member) { + switch (member.type) { + case "ClassMethod": + return this.visitClassMethod(member); + case "ClassProperty": + return this.visitClassProperty(member); + case "Constructor": + return this.visitConstructor(member); + case "PrivateMethod": + return this.visitPrivateMethod(member); + case "PrivateProperty": + return this.visitPrivateProperty(member); + case "TsIndexSignature": + return this.visitTsIndexSignature(member); + case "EmptyStatement": + return this.visitEmptyStatement(member); + case "StaticBlock": + return this.visitStaticBlock(member); + } + } + visitTsIndexSignature(n) { + n.params = this.visitTsFnParameters(n.params); + if (n.typeAnnotation) n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitTsFnParameters(params) { + return params.map(this.visitTsFnParameter.bind(this)); + } + visitTsFnParameter(n) { + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitPrivateProperty(n) { + n.decorators = this.visitDecorators(n.decorators); + n.key = this.visitPrivateName(n.key); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + n.value = this.visitOptionalExpression(n.value); + return n; + } + visitPrivateMethod(n) { + n.accessibility = this.visitAccessibility(n.accessibility); + n.function = this.visitFunction(n.function); + n.key = this.visitPrivateName(n.key); + return n; + } + visitPrivateName(n) { + return n; + } + visitConstructor(n) { + n.accessibility = this.visitAccessibility(n.accessibility); + n.key = this.visitPropertyName(n.key); + n.params = this.visitConstructorParameters(n.params); + if (n.body) { + n.body = this.visitBlockStatement(n.body); + } + return n; + } + visitConstructorParameters(nodes) { + return nodes.map(this.visitConstructorParameter.bind(this)); + } + visitConstructorParameter(n) { + switch (n.type) { + case "TsParameterProperty": + return this.visitTsParameterProperty(n); + default: + return this.visitParameter(n); + } + } + visitStaticBlock(n) { + n.body = this.visitBlockStatement(n.body); + return n; + } + visitTsParameterProperty(n) { + n.accessibility = this.visitAccessibility(n.accessibility); + n.decorators = this.visitDecorators(n.decorators); + n.param = this.visitTsParameterPropertyParameter(n.param); + return n; + } + visitTsParameterPropertyParameter(n) { + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitPropertyName(key) { + switch (key.type) { + case "Identifier": + return this.visitBindingIdentifier(key); + case "StringLiteral": + return this.visitStringLiteral(key); + case "NumericLiteral": + return this.visitNumericLiteral(key); + case "BigIntLiteral": + return this.visitBigIntLiteral(key); + default: + return this.visitComputedPropertyKey(key); + } + } + visitAccessibility(n) { + return n; + } + visitClassProperty(n) { + n.accessibility = this.visitAccessibility(n.accessibility); + n.decorators = this.visitDecorators(n.decorators); + n.key = this.visitPropertyName(n.key); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + n.value = this.visitOptionalExpression(n.value); + return n; + } + visitClassMethod(n) { + n.accessibility = this.visitAccessibility(n.accessibility); + n.function = this.visitFunction(n.function); + n.key = this.visitPropertyName(n.key); + return n; + } + visitComputedPropertyKey(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitClass(n) { + n.decorators = this.visitDecorators(n.decorators); + n.superClass = this.visitOptionalExpression(n.superClass); + n.superTypeParams = this.visitTsTypeParameterInstantiation(n.superTypeParams); + if (n.implements) { + n.implements = this.visitTsExpressionsWithTypeArguments(n.implements); + } + n.body = this.visitClassBody(n.body); + return n; + } + visitFunction(n) { + n.decorators = this.visitDecorators(n.decorators); + n.params = this.visitParameters(n.params); + if (n.body) { + n.body = this.visitBlockStatement(n.body); + } + n.returnType = this.visitTsTypeAnnotation(n.returnType); + n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters); + return n; + } + visitTsExpressionsWithTypeArguments(nodes) { + return nodes.map(this.visitTsExpressionWithTypeArguments.bind(this)); + } + visitTsExpressionWithTypeArguments(n) { + n.expression = this.visitExpression(n.expression); + n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); + return n; + } + visitTsTypeParameterInstantiation(n) { + if (n) { + n.params = this.visitTsTypes(n.params); + } + return n; + } + visitTsTypes(nodes) { + return nodes.map(this.visitTsType.bind(this)); + } + visitTsEntityName(n) { + switch (n.type) { + case "Identifier": + return this.visitBindingIdentifier(n); + case "TsQualifiedName": + return this.visitTsQualifiedName(n); + } + } + visitTsQualifiedName(n) { + n.left = this.visitTsEntityName(n.left); + n.right = this.visitIdentifier(n.right); + return n; + } + visitDecorators(nodes) { + if (nodes) { + return nodes.map(this.visitDecorator.bind(this)); + } + } + visitDecorator(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitExpressionStatement(stmt) { + stmt.expression = this.visitExpression(stmt.expression); + return stmt; + } + visitContinueStatement(stmt) { + if (stmt.label) { + stmt.label = this.visitLabelIdentifier(stmt.label); + } + return stmt; + } + visitExpression(n) { + switch (n.type) { + case "ArrayExpression": + return this.visitArrayExpression(n); + case "ArrowFunctionExpression": + return this.visitArrowFunctionExpression(n); + case "AssignmentExpression": + return this.visitAssignmentExpression(n); + case "AwaitExpression": + return this.visitAwaitExpression(n); + case "BigIntLiteral": + return this.visitBigIntLiteral(n); + case "BinaryExpression": + return this.visitBinaryExpression(n); + case "BooleanLiteral": + return this.visitBooleanLiteral(n); + case "CallExpression": + return this.visitCallExpression(n); + case "ClassExpression": + return this.visitClassExpression(n); + case "ConditionalExpression": + return this.visitConditionalExpression(n); + case "FunctionExpression": + return this.visitFunctionExpression(n); + case "Identifier": + return this.visitIdentifierReference(n); + case "JSXElement": + return this.visitJSXElement(n); + case "JSXEmptyExpression": + return this.visitJSXEmptyExpression(n); + case "JSXFragment": + return this.visitJSXFragment(n); + case "JSXMemberExpression": + return this.visitJSXMemberExpression(n); + case "JSXNamespacedName": + return this.visitJSXNamespacedName(n); + case "JSXText": + return this.visitJSXText(n); + case "MemberExpression": + return this.visitMemberExpression(n); + case "SuperPropExpression": + return this.visitSuperPropExpression(n); + case "MetaProperty": + return this.visitMetaProperty(n); + case "NewExpression": + return this.visitNewExpression(n); + case "NullLiteral": + return this.visitNullLiteral(n); + case "NumericLiteral": + return this.visitNumericLiteral(n); + case "ObjectExpression": + return this.visitObjectExpression(n); + case "ParenthesisExpression": + return this.visitParenthesisExpression(n); + case "PrivateName": + return this.visitPrivateName(n); + case "RegExpLiteral": + return this.visitRegExpLiteral(n); + case "SequenceExpression": + return this.visitSequenceExpression(n); + case "StringLiteral": + return this.visitStringLiteral(n); + case "TaggedTemplateExpression": + return this.visitTaggedTemplateExpression(n); + case "TemplateLiteral": + return this.visitTemplateLiteral(n); + case "ThisExpression": + return this.visitThisExpression(n); + case "TsAsExpression": + return this.visitTsAsExpression(n); + case "TsSatisfiesExpression": + return this.visitTsSatisfiesExpression(n); + case "TsNonNullExpression": + return this.visitTsNonNullExpression(n); + case "TsTypeAssertion": + return this.visitTsTypeAssertion(n); + case "TsConstAssertion": + return this.visitTsConstAssertion(n); + case "TsInstantiation": + return this.visitTsInstantiation(n); + case "UnaryExpression": + return this.visitUnaryExpression(n); + case "UpdateExpression": + return this.visitUpdateExpression(n); + case "YieldExpression": + return this.visitYieldExpression(n); + case "OptionalChainingExpression": + return this.visitOptionalChainingExpression(n); + case "Invalid": + return n; + } + } + visitOptionalChainingExpression(n) { + n.base = this.visitMemberExpressionOrOptionalChainingCall(n.base); + return n; + } + visitMemberExpressionOrOptionalChainingCall(n) { + switch (n.type) { + case "MemberExpression": + return this.visitMemberExpression(n); + case "CallExpression": + return this.visitOptionalChainingCall(n); + } + } + visitOptionalChainingCall(n) { + n.callee = this.visitExpression(n.callee); + n.arguments = this.visitExprOrSpreads(n.arguments); + if (n.typeArguments) n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); + return n; + } + visitAssignmentExpression(n) { + n.left = this.visitPatternOrExpression(n.left); + n.right = this.visitExpression(n.right); + return n; + } + visitPatternOrExpression(n) { + switch (n.type) { + case "ObjectPattern": + case "ArrayPattern": + case "Identifier": + case "AssignmentPattern": + case "RestElement": + return this.visitPattern(n); + default: + return this.visitExpression(n); + } + } + visitYieldExpression(n) { + n.argument = this.visitOptionalExpression(n.argument); + return n; + } + visitUpdateExpression(n) { + n.argument = this.visitExpression(n.argument); + return n; + } + visitUnaryExpression(n) { + n.argument = this.visitExpression(n.argument); + return n; + } + visitTsTypeAssertion(n) { + n.expression = this.visitExpression(n.expression); + n.typeAnnotation = this.visitTsType(n.typeAnnotation); + return n; + } + visitTsConstAssertion(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitTsInstantiation(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitTsNonNullExpression(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitTsAsExpression(n) { + n.expression = this.visitExpression(n.expression); + n.typeAnnotation = this.visitTsType(n.typeAnnotation); + return n; + } + visitTsSatisfiesExpression(n) { + n.expression = this.visitExpression(n.expression); + n.typeAnnotation = this.visitTsType(n.typeAnnotation); + return n; + } + visitThisExpression(n) { + return n; + } + visitTemplateLiteral(n) { + n.expressions = n.expressions.map(this.visitExpression.bind(this)); + return n; + } + visitParameters(n) { + return n.map(this.visitParameter.bind(this)); + } + visitParameter(n) { + n.pat = this.visitPattern(n.pat); + return n; + } + visitTaggedTemplateExpression(n) { + n.tag = this.visitExpression(n.tag); + const template = this.visitTemplateLiteral(n.template); + if (template.type === "TemplateLiteral") { + n.template = template; + } + return n; + } + visitSequenceExpression(n) { + n.expressions = n.expressions.map(this.visitExpression.bind(this)); + return n; + } + visitRegExpLiteral(n) { + return n; + } + visitParenthesisExpression(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitObjectExpression(n) { + if (n.properties) { + n.properties = this.visitObjectProperties(n.properties); + } + return n; + } + visitObjectProperties(nodes) { + return nodes.map(this.visitObjectProperty.bind(this)); + } + visitObjectProperty(n) { + switch (n.type) { + case "SpreadElement": + return this.visitSpreadElement(n); + default: + return this.visitProperty(n); + } + } + visitProperty(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifier(n); + case "AssignmentProperty": + return this.visitAssignmentProperty(n); + case "GetterProperty": + return this.visitGetterProperty(n); + case "KeyValueProperty": + return this.visitKeyValueProperty(n); + case "MethodProperty": + return this.visitMethodProperty(n); + case "SetterProperty": + return this.visitSetterProperty(n); + } + } + visitSetterProperty(n) { + n.key = this.visitPropertyName(n.key); + n.param = this.visitPattern(n.param); + if (n.body) { + n.body = this.visitBlockStatement(n.body); + } + return n; + } + visitMethodProperty(n) { + n.key = this.visitPropertyName(n.key); + if (n.body) { + n.body = this.visitBlockStatement(n.body); + } + n.decorators = this.visitDecorators(n.decorators); + n.params = this.visitParameters(n.params); + n.returnType = this.visitTsTypeAnnotation(n.returnType); + n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters); + return n; + } + visitKeyValueProperty(n) { + n.key = this.visitPropertyName(n.key); + n.value = this.visitExpression(n.value); + return n; + } + visitGetterProperty(n) { + n.key = this.visitPropertyName(n.key); + if (n.body) { + n.body = this.visitBlockStatement(n.body); + } + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitAssignmentProperty(n) { + n.key = this.visitIdentifier(n.key); + n.value = this.visitExpression(n.value); + return n; + } + visitNullLiteral(n) { + return n; + } + visitNewExpression(n) { + n.callee = this.visitExpression(n.callee); + if (n.arguments) { + n.arguments = this.visitArguments(n.arguments); + } + n.typeArguments = this.visitTsTypeArguments(n.typeArguments); + return n; + } + visitTsTypeArguments(n) { + if (n) { + n.params = this.visitTsTypes(n.params); + } + return n; + } + visitArguments(nodes) { + return nodes.map(this.visitArgument.bind(this)); + } + visitArgument(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitMetaProperty(n) { + return n; + } + visitMemberExpression(n) { + n.object = this.visitExpression(n.object); + switch (n.property.type) { + case "Computed": { + n.property = this.visitComputedPropertyKey(n.property); + return n; + } + case "Identifier": { + n.property = this.visitIdentifier(n.property); + return n; + } + case "PrivateName": { + n.property = this.visitPrivateName(n.property); + return n; + } + } + } + visitSuperPropExpression(n) { + switch (n.property.type) { + case "Computed": { + n.property = this.visitComputedPropertyKey(n.property); + return n; + } + case "Identifier": { + n.property = this.visitIdentifier(n.property); + return n; + } + } + } + visitCallee(n) { + if (n.type === "Super" || n.type === "Import") { + return n; + } + return this.visitExpression(n); + } + visitJSXText(n) { + return n; + } + visitJSXNamespacedName(n) { + n.namespace = this.visitIdentifierReference(n.namespace); + n.name = this.visitIdentifierReference(n.name); + return n; + } + visitJSXMemberExpression(n) { + n.object = this.visitJSXObject(n.object); + n.property = this.visitIdentifierReference(n.property); + return n; + } + visitJSXObject(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifierReference(n); + case "JSXMemberExpression": + return this.visitJSXMemberExpression(n); + } + } + visitJSXFragment(n) { + n.opening = this.visitJSXOpeningFragment(n.opening); + if (n.children) { + n.children = this.visitJSXElementChildren(n.children); + } + n.closing = this.visitJSXClosingFragment(n.closing); + return n; + } + visitJSXClosingFragment(n) { + return n; + } + visitJSXElementChildren(nodes) { + return nodes.map(this.visitJSXElementChild.bind(this)); + } + visitJSXElementChild(n) { + switch (n.type) { + case "JSXElement": + return this.visitJSXElement(n); + case "JSXExpressionContainer": + return this.visitJSXExpressionContainer(n); + case "JSXFragment": + return this.visitJSXFragment(n); + case "JSXSpreadChild": + return this.visitJSXSpreadChild(n); + case "JSXText": + return this.visitJSXText(n); + } + } + visitJSXExpressionContainer(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitJSXSpreadChild(n) { + n.expression = this.visitExpression(n.expression); + return n; + } + visitJSXOpeningFragment(n) { + return n; + } + visitJSXEmptyExpression(n) { + return n; + } + visitJSXElement(n) { + n.opening = this.visitJSXOpeningElement(n.opening); + n.children = this.visitJSXElementChildren(n.children); + n.closing = this.visitJSXClosingElement(n.closing); + return n; + } + visitJSXClosingElement(n) { + if (n) { + n.name = this.visitJSXElementName(n.name); + } + return n; + } + visitJSXElementName(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifierReference(n); + case "JSXMemberExpression": + return this.visitJSXMemberExpression(n); + case "JSXNamespacedName": + return this.visitJSXNamespacedName(n); + } + } + visitJSXOpeningElement(n) { + n.name = this.visitJSXElementName(n.name); + n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); + n.attributes = this.visitJSXAttributeOrSpreads(n.attributes); + return n; + } + visitJSXAttributes(attrs) { + if (attrs) return attrs.map(this.visitJSXAttributeOrSpread.bind(this)); + } + visitJSXAttributeOrSpread(n) { + switch (n.type) { + case "JSXAttribute": + return this.visitJSXAttribute(n); + case "SpreadElement": + return this.visitSpreadElement(n); + } + } + visitJSXAttributeOrSpreads(nodes) { + return nodes.map(this.visitJSXAttributeOrSpread.bind(this)); + } + visitJSXAttribute(n) { + n.name = this.visitJSXAttributeName(n.name); + n.value = this.visitJSXAttributeValue(n.value); + return n; + } + visitJSXAttributeValue(n) { + if (!n) return n; + switch (n.type) { + case "BooleanLiteral": + return this.visitBooleanLiteral(n); + case "NullLiteral": + return this.visitNullLiteral(n); + case "NumericLiteral": + return this.visitNumericLiteral(n); + case "JSXText": + return this.visitJSXText(n); + case "StringLiteral": + return this.visitStringLiteral(n); + case "JSXElement": + return this.visitJSXElement(n); + case "JSXExpressionContainer": + return this.visitJSXExpressionContainer(n); + case "JSXFragment": + return this.visitJSXFragment(n); + } + return n; + } + visitJSXAttributeName(n) { + switch (n.type) { + case "Identifier": + return this.visitIdentifierReference(n); + case "JSXNamespacedName": + return this.visitJSXNamespacedName(n); + } + } + visitConditionalExpression(n) { + n.test = this.visitExpression(n.test); + n.consequent = this.visitExpression(n.consequent); + n.alternate = this.visitExpression(n.alternate); + return n; + } + visitCallExpression(n) { + n.callee = this.visitCallee(n.callee); + n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); + if (n.arguments) { + n.arguments = this.visitArguments(n.arguments); + } + return n; + } + visitBooleanLiteral(n) { + return n; + } + visitBinaryExpression(n) { + n.left = this.visitExpression(n.left); + n.right = this.visitExpression(n.right); + return n; + } + visitAwaitExpression(n) { + n.argument = this.visitExpression(n.argument); + return n; + } + visitTsTypeParameterDeclaration(n) { + if (n) { + n.parameters = this.visitTsTypeParameters(n.parameters); + } + return n; + } + visitTsTypeParameters(nodes) { + return nodes.map(this.visitTsTypeParameter.bind(this)); + } + visitTsTypeParameter(n) { + if (n.constraint) { + n.constraint = this.visitTsType(n.constraint); + } + if (n.default) { + n.default = this.visitTsType(n.default); + } + n.name = this.visitIdentifierReference(n.name); + return n; + } + visitTsTypeAnnotation(a) { + if (a) { + a.typeAnnotation = this.visitTsType(a.typeAnnotation); + } + return a; + } + visitTsType(n) { + return n; + } + visitPatterns(nodes) { + return nodes.map(this.visitPattern.bind(this)); + } + visitImportDeclaration(n) { + n.source = this.visitStringLiteral(n.source); + n.specifiers = this.visitImportSpecifiers(n.specifiers || []); + return n; + } + visitImportSpecifiers(nodes) { + return nodes.map(this.visitImportSpecifier.bind(this)); + } + visitImportSpecifier(node) { + switch (node.type) { + case "ImportDefaultSpecifier": + return this.visitImportDefaultSpecifier(node); + case "ImportNamespaceSpecifier": + return this.visitImportNamespaceSpecifier(node); + case "ImportSpecifier": + return this.visitNamedImportSpecifier(node); + } + } + visitNamedImportSpecifier(node) { + node.local = this.visitBindingIdentifier(node.local); + if (node.imported) { + node.imported = this.visitModuleExportName(node.imported); + } + return node; + } + visitImportNamespaceSpecifier(node) { + node.local = this.visitBindingIdentifier(node.local); + return node; + } + visitImportDefaultSpecifier(node) { + node.local = this.visitBindingIdentifier(node.local); + return node; + } + visitBindingIdentifier(i) { + if (i.typeAnnotation) { + i.typeAnnotation = this.visitTsTypeAnnotation(i.typeAnnotation); + } + return this.visitIdentifier(i); + } + visitIdentifierReference(i) { + return this.visitIdentifier(i); + } + visitLabelIdentifier(label) { + return this.visitIdentifier(label); + } + visitIdentifier(n) { + return n; + } + visitStringLiteral(n) { + return n; + } + visitNumericLiteral(n) { + return n; + } + visitBigIntLiteral(n) { + return n; + } + visitPattern(n) { + switch (n.type) { + case "Identifier": + return this.visitBindingIdentifier(n); + case "ArrayPattern": + return this.visitArrayPattern(n); + case "ObjectPattern": + return this.visitObjectPattern(n); + case "AssignmentPattern": + return this.visitAssignmentPattern(n); + case "RestElement": + return this.visitRestElement(n); + default: + return this.visitExpression(n); + } + } + visitRestElement(n) { + n.argument = this.visitPattern(n.argument); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitAssignmentPattern(n) { + n.left = this.visitPattern(n.left); + n.right = this.visitExpression(n.right); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitObjectPattern(n) { + n.properties = this.visitObjectPatternProperties(n.properties || []); + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + return n; + } + visitObjectPatternProperties(nodes) { + return nodes.map(this.visitObjectPatternProperty.bind(this)); + } + visitObjectPatternProperty(n) { + switch (n.type) { + case "AssignmentPatternProperty": + return this.visitAssignmentPatternProperty(n); + case "KeyValuePatternProperty": + return this.visitKeyValuePatternProperty(n); + case "RestElement": + return this.visitRestElement(n); + } + } + visitKeyValuePatternProperty(n) { + n.key = this.visitPropertyName(n.key); + n.value = this.visitPattern(n.value); + return n; + } + visitAssignmentPatternProperty(n) { + n.key = this.visitBindingIdentifier(n.key); + n.value = this.visitOptionalExpression(n.value); + return n; + } + visitArrayPattern(n) { + n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); + n.elements = this.visitArrayPatternElements(n.elements); + return n; + } + visitArrayPatternElements(nodes) { + return nodes.map(this.visitArrayPatternElement.bind(this)); + } + visitArrayPatternElement(n) { + if (n) { + n = this.visitPattern(n); + } + return n; + } +} + +class RenameVisitor extends Visitor { + constructor(replace, suffix) { + super(); + this.replace = replace; + this.suffix = suffix; + } + visitIdentifier(n) { + if (this.replace.includes(n.value)) n.value = this.suffix(n.value); + return n; + } +} + +function isPluginBaseConfig(plugin) { + return typeof plugin.type === "string" && typeof plugin.sourceModule === "string" && typeof plugin.enabled === "boolean" && typeof plugin.targetExport === "string"; +} +function isReactPluginConfig(plugin) { + if (!isPluginBaseConfig(plugin)) return false; + return plugin.type === "component"; +} +function isMethodPluginConfig(plugin) { + if (!isPluginBaseConfig(plugin)) return false; + return plugin.type === "function"; +} +function isReplacePluginConfig(plugin) { + if (!isPluginBaseConfig(plugin)) return false; + return plugin.type === "replace"; +} +function isPluginConfig(plugin) { + return isPluginBaseConfig(plugin); +} +const SOURCE_START = "/** SOURCE_START */"; +const SOURCE_END = "/** SOURCE_END */"; +const originalSuffix = "Original"; +const interceptorSuffix = "Interceptor"; +const disabledSuffix = "Disabled"; +const name = (plugin) => `${plugin.sourceExport}${plugin.sourceModule.split("/")[plugin.sourceModule.split("/").length - 1].replace(/[^a-zA-Z0-9]/g, "")}`; +const fileName = (plugin) => `${plugin.sourceModule}#${plugin.sourceExport}`; +const originalName = (n) => `${n}${originalSuffix}`; +const sourceName = (n) => `${n}`; +const interceptorName = (n) => `${n}${interceptorSuffix}`; +const interceptorPropsName = (n) => `${n}Props`; +function moveRelativeDown(plugins) { + return [...plugins].sort((a, b) => { + if (a.sourceModule.startsWith(".") && !b.sourceModule.startsWith(".")) return 1; + if (!a.sourceModule.startsWith(".") && b.sourceModule.startsWith(".")) return -1; + return 0; + }); +} +const generateIdentifyer = (s) => Math.abs( + s.split("").reduce((a, b) => { + a = (a << 5) - a + b.charCodeAt(0); + return a & a; + }, 0) +).toString(); +function extractIdentifier(source) { + if (!source) return null; + const match = source.match(/\/\* hash:(\d+) \*\//); + if (!match) return null; + return match[1]; +} +async function generateInterceptor(interceptor, config, oldInterceptorSource) { + const identifer = generateIdentifyer(JSON.stringify(interceptor) + JSON.stringify(config)); + const { dependency, targetExports, source } = interceptor; + if (oldInterceptorSource && identifer === extractIdentifier(oldInterceptorSource)) + return { ...interceptor, template: oldInterceptorSource }; + const pluginConfigs = [...Object.entries(targetExports)].map(([, plugins]) => plugins).flat(); + const duplicateImports = /* @__PURE__ */ new Set(); + const pluginImports = moveRelativeDown( + [...pluginConfigs].sort((a, b) => a.sourceModule.localeCompare(b.sourceModule)) + ).map( + (plugin) => `import { ${plugin.sourceExport} as ${sourceName(name(plugin))} } from '${plugin.sourceModule}'` + ).filter((str) => { + if (duplicateImports.has(str)) return false; + duplicateImports.add(str); + return true; + }).join("\n"); + const ast = parseSync(source); + new RenameVisitor(Object.keys(targetExports), (s) => originalName(s)).visitModule(ast); + const pluginExports = Object.entries(targetExports).map(([base, plugins]) => { + const duplicateInterceptors = /* @__PURE__ */ new Set(); + let carry = originalName(base); + let carryProps = []; + const pluginSee = []; + pluginSee.push( + `@see {@link file://${interceptor.sourcePathRelative}} for original source file` + ); + const pluginStr = plugins.reverse().filter((p) => { + if (duplicateInterceptors.has(name(p))) return false; + duplicateInterceptors.add(name(p)); + return true; + }).map((p) => { + let result; + const wrapChain = plugins.reverse().map((pl) => name(pl)).join(" wrapping "); + if (isReplacePluginConfig(p)) { + new RenameVisitor( + [originalName(p.targetExport)], + (s) => s.replace(originalSuffix, disabledSuffix) + ).visitModule(ast); + carryProps.push(`React.ComponentProps`); + pluginSee.push( + `@see {${sourceName(name(p))}} for replacement of the original source (original source not used)` + ); + } + if (isReactPluginConfig(p)) { + const withBraces = config.pluginStatus || process.env.NODE_ENV === "development"; + result = ` + type ${interceptorPropsName(name(p))} = ${carryProps.join(" & ")} & OmitPrev, 'Prev'> + + const ${interceptorName(name(p))} = (props: ${interceptorPropsName(name(p))}) => ${withBraces ? "{" : "("} + ${config.pluginStatus ? `logOnce(\`\u{1F50C} Rendering ${base} with plugin(s): ${wrapChain} wrapping <${base}/>\`)` : ""} + + ${process.env.NODE_ENV === "development" ? `if(!props['data-plugin']) + logOnce('${fileName(p)} does not spread props to prev: . This will cause issues if multiple plugins are applied to this component.')` : ""} + ${withBraces ? "return" : ""} <${sourceName(name(p))} {...props} Prev={${carry}} /> + ${withBraces ? "}" : ")"}`; + carryProps = [interceptorPropsName(name(p))]; + pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`); + } + if (isMethodPluginConfig(p)) { + result = `const ${interceptorName(name(p))}: typeof ${carry} = (...args) => { + ${config.pluginStatus ? `logOnce(\`\u{1F50C} Calling ${base} with plugin(s): ${wrapChain} wrapping ${base}()\`)` : ""} + return ${sourceName(name(p))}(${carry}, ...args) + }`; + pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`); + } + carry = p.type === "replace" ? sourceName(name(p)) : interceptorName(name(p)); + return result; + }).filter((v) => !!v).join("\n"); + const isComponent = plugins.every((p) => isReactPluginConfig(p)); + if (isComponent && plugins.some((p) => isMethodPluginConfig(p))) { + throw new Error(`Cannot mix React and Method plugins for ${base} in ${dependency}.`); + } + const seeString = ` + /** + * Here you see the 'interceptor' that is applying all the configured plugins. + * + * This file is NOT meant to be modified directly and is auto-generated if the plugins or the original source changes. + * + ${pluginSee.map((s) => `* ${s}`).join("\n")} + */`; + if (process.env.NODE_ENV === "development" && isComponent) { + return `${pluginStr} + ${seeString} + export const ${base}: typeof ${carry} = (props) => { + return <${carry} {...props} data-plugin /> + }`; + } + return ` + ${pluginStr} + ${seeString} + export const ${base} = ${carry} + `; + }).join("\n"); + const logOnce = config.pluginStatus || process.env.NODE_ENV === "development" ? ` + const logged: Set = new Set(); + const logOnce = (log: string, ...additional: unknown[]) => { + if (logged.has(log)) return + logged.add(log) + console.warn(log, ...additional) + } + ` : ""; + const template = `/* hash:${identifer} */ + /* eslint-disable */ + /* This file is automatically generated for ${dependency} */ + ${Object.values(targetExports).some((t) => t.some((p) => p.type === "component")) ? "import type { DistributedOmit as OmitPrev } from 'type-fest'" : ""} + + ${pluginImports} + + /** @see {@link file://${interceptor.sourcePathRelative}} for source of original */ + ${SOURCE_START} + ${printSync(ast).code} + ${SOURCE_END} + ${logOnce}${pluginExports} + `; + let templateFormatted; + try { + templateFormatted = await prettier.format(template, { ...prettierConf, parser: "typescript" }); + } catch (e) { + console.log("Error formatting interceptor: ", e, "using raw template."); + templateFormatted = template; + } + return { ...interceptor, template: templateFormatted }; +} + +async function generateInterceptors(plugins, resolve, config, force) { + const byTargetModuleAndExport = moveRelativeDown(plugins).reduce( + (acc, plug) => { + let { sourceModule: pluginPath } = plug; + if (!isPluginConfig(plug) || !plug.enabled) return acc; + const result = resolve(plug.targetModule, { includeSources: true }); + const { error, resolved } = findOriginalSource(plug, result, resolve); + if (error) { + console.error(error.message); + return acc; + } + const { fromRoot } = resolved; + if (pluginPath.startsWith(".")) { + const resolvedPlugin = resolve(pluginPath); + if (resolvedPlugin) { + pluginPath = path.relative( + resolved.fromRoot.split("/").slice(0, -1).join("/"), + resolvedPlugin.fromRoot + ); + } + } + if (!acc[resolved.fromRoot]) { + acc[resolved.fromRoot] = { + ...resolved, + target: `${resolved.fromRoot}.interceptor`, + targetExports: {} + }; + } + if (!acc[fromRoot].targetExports[plug.targetExport]) + acc[fromRoot].targetExports[plug.targetExport] = []; + acc[fromRoot].targetExports[plug.targetExport].push({ ...plug, sourceModule: pluginPath }); + return acc; + }, + {} + ); + return Object.fromEntries( + await Promise.all( + Object.entries(byTargetModuleAndExport).map(async ([target, interceptor]) => { + const file = `${interceptor.fromRoot}.interceptor.tsx`; + const originalSource = !force && await fs$1.access(file, fs$1.constants.F_OK).then(() => true).catch(() => false) ? (await fs$1.readFile(file)).toString() : undefined; + return [ + target, + await generateInterceptor(interceptor, config ?? {}, originalSource) + ]; + }) + ) + ); +} + +function checkFileExists(file) { + return fs$1.access(file, fs$1.constants.F_OK).then(() => true).catch(() => false); +} +async function writeInterceptors(interceptors, cwd = process.cwd()) { + const dependencies = resolveDependenciesSync(cwd); + const existing = /* @__PURE__ */ new Set(); + dependencies.forEach((dependency) => { + const files = sync( + [`${dependency}/**/*.interceptor.tsx`, `${dependency}/**/*.interceptor.ts`], + { cwd } + ); + files.forEach((file) => existing.add(file)); + }); + const written = Object.entries(interceptors).map(async ([, plugin]) => { + const extension = plugin.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts"; + const relativeFile = `${plugin.fromRoot}.interceptor${extension}`; + if (existing.has(relativeFile)) { + existing.delete(relativeFile); + } + if (existing.has(`./${relativeFile}`)) { + existing.delete(`./${relativeFile}`); + } + const fileToWrite = path$1.join(cwd, relativeFile); + const isSame = await checkFileExists(fileToWrite) && (await fs$1.readFile(fileToWrite, "utf8")).toString() === plugin.template; + if (!isSame) await fs$1.writeFile(fileToWrite, plugin.template); + }); + const cleaned = [...existing].map( + async (file) => await checkFileExists(file) && await fs$1.unlink(file) + ); + await Promise.all(written); + await Promise.all(cleaned); +} + +let interceptors; +let interceptorByDepependency; +let generating = false; +class InterceptorPlugin { + constructor(config, regenerate = false) { + this.config = config; + this.regenerate = regenerate; + this.resolveDependency = resolveDependency(); + if (regenerate) this.#generateInterceptors(); + } + resolveDependency; + #generateInterceptors = async () => { + if (generating) return {}; + generating = true; + const [plugins] = findPlugins(this.config); + const generatedInterceptors = await generateInterceptors( + plugins, + this.resolveDependency, + this.config.debug + ); + await writeInterceptors(generatedInterceptors); + interceptors = generatedInterceptors; + interceptorByDepependency = Object.fromEntries( + Object.values(interceptors).map((i) => [i.dependency, i]) + ); + generating = false; + return generatedInterceptors; + }; + /** @public */ + apply(compiler) { + const logger = compiler.getInfrastructureLogger("InterceptorPlugin"); + if (this.regenerate) { + compiler.hooks.afterCompile.tap("InterceptorPlugin", (compilation) => { + const [plugins, errors] = findPlugins(this.config); + plugins.forEach((p) => { + const source = this.resolveDependency(p.sourceModule); + if (source) { + const absoluteFilePath = `${path$1.join(process.cwd(), source.fromRoot)}.tsx`; + compilation.fileDependencies.add(absoluteFilePath); + } + }); + this.#generateInterceptors().then((i) => { + Object.entries(i).forEach(([, { sourcePath }]) => { + const absoluteFilePath = path$1.join(process.cwd(), sourcePath); + compilation.fileDependencies.add(absoluteFilePath); + }); + }); + }); + } + compiler.hooks.normalModuleFactory.tap("InterceptorPlugin", (nmf) => { + nmf.hooks.beforeResolve.tap("InterceptorPlugin", (resource) => { + const issuer = resource.contextInfo.issuer ?? ""; + const requestPath = path$1.relative( + process.cwd(), + path$1.resolve(resource.context, resource.request) + ); + if (!interceptors || !interceptorByDepependency) { + return; + } + const split = requestPath.split("/"); + const targets = [ + `${split[split.length - 1]}.interceptor.tsx`, + `${split[split.length - 1]}.interceptor.ts` + ]; + if (targets.some((target) => issuer.endsWith(target)) && interceptors[requestPath]) { + logger.log(`Interceptor ${issuer} is requesting the original ${requestPath}`); + return; + } + const interceptorForRequest = interceptorByDepependency[resource.request]; + if (interceptorForRequest) { + const extension = interceptorForRequest.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts"; + resource.request = `${interceptorForRequest.denormalized}.interceptor${extension}`; + logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`, resource.request); + } + const interceptorForPath = interceptors[requestPath]; + if (interceptorForPath) { + const extension = interceptorForPath.sourcePath.endsWith(".tsx") ? ".tsx" : ".ts"; + resource.request = `${resource.request}.interceptor${extension}`; + logger.log(`Intercepting fromRoot... ${interceptorForPath.dependency}`, resource.request); + } + }); + }); + } +} + +let graphcommerceConfig; +function domains(config) { + return Object.values( + config.storefront.reduce( + (acc, loc) => { + if (!loc.domain) return acc; + acc[loc.domain] = { + defaultLocale: loc.locale, + locales: [...acc[loc.domain]?.locales ?? [], loc.locale], + domain: loc.domain, + http: process.env.NODE_ENV === "development" || undefined + }; + return acc; + }, + {} + ) + ); +} +function withGraphCommerce(nextConfig, cwd = process.cwd()) { + graphcommerceConfig ??= loadConfig(cwd); + const importMetaPaths = configToImportMeta(graphcommerceConfig); + const { storefront } = graphcommerceConfig; + const transpilePackages = [ + ...[...resolveDependenciesSync().keys()].slice(1), + ...nextConfig.transpilePackages ?? [] + ]; + return { + ...nextConfig, + bundlePagesRouterDependencies: true, + experimental: { + ...nextConfig.experimental, + scrollRestoration: true, + swcPlugins: [...nextConfig.experimental?.swcPlugins ?? [], ["@lingui/swc-plugin", {}]] + }, + i18n: { + ...nextConfig.i18n, + defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale, + locales: storefront.map((locale) => locale.locale), + domains: [...domains(graphcommerceConfig), ...nextConfig.i18n?.domains ?? []] + }, + images: { + ...nextConfig.images, + remotePatterns: [ + "magentoEndpoint" in graphcommerceConfig ? { + hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname + } : undefined, + { hostname: "**.graphassets.com" }, + { hostname: "*.graphcommerce.org" }, + ...nextConfig.images?.remotePatterns ?? [] + ].filter((v) => !!v) + }, + rewrites: async () => { + let rewrites = await nextConfig.rewrites?.() ?? []; + if (Array.isArray(rewrites)) { + rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] }; + } + if ("productRoute" in graphcommerceConfig && typeof graphcommerceConfig.productRoute === "string" && graphcommerceConfig.productRoute !== "/p/") { + rewrites.beforeFiles.push({ + source: `${graphcommerceConfig.productRoute ?? "/p/"}:path*`, + destination: "/p/:path*" + }); + } + return rewrites; + }, + transpilePackages, + webpack: (config, options) => { + if (!config.module) config.module = { rules: [] }; + config.module = { + ...config.module, + rules: [ + ...config.module.rules ?? [], + // Allow importing yml/yaml files for graphql-mesh + { test: /\.ya?ml$/, use: "js-yaml-loader" }, + // @lingui .po file support + { test: /\.po/, use: "@lingui/loader" } + ], + exprContextCritical: false + }; + if (!config.plugins) config.plugins = []; + config.plugins.push(new webpack.DefinePlugin(importMetaPaths)); + config.plugins.push(new webpack.DefinePlugin({ "globalThis.__DEV__": options.dev })); + if (!options.isServer) ; + config.snapshot = { + ...config.snapshot ?? {}, + managedPaths: [ + new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join("|")})`) + ] + }; + config.watchOptions = { + ...config.watchOptions ?? {}, + ignored: new RegExp( + `^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join( + "|" + )})))(/((?:[^/]*(?:/|$))*)(?:$|/))?` + ) + }; + if (!config.resolve) config.resolve = {}; + if (!options.isServer && !options.dev) { + config.resolve.alias = { + ...config.resolve.alias, + "@mui/base": "@mui/base/modern", + "@mui/lab": "@mui/lab/modern", + "@mui/material": "@mui/material/modern", + "@mui/styled-engine": "@mui/styled-engine/modern", + "@mui/system": "@mui/system/modern" + }; + } + config.plugins.push(new InterceptorPlugin(graphcommerceConfig, !options.isServer)); + return typeof nextConfig.webpack === "function" ? nextConfig.webpack(config, options) : config; + } + }; +} + +dotenv.config(); +const packages = [...resolveDependenciesSync().values()].filter((p) => p !== "."); +const resolve = resolveDependency(); +const schemaLocations = packages.map((p) => `${p}/**/Config.graphqls`); +async function generateConfig() { + const resolved = resolve("@graphcommerce/next-config"); + if (!resolved) throw Error("Could not resolve @graphcommerce/next-config"); + const targetTs = `${resolved.root}/src/generated/config.ts`; + const targetJs = `${resolved.root}/dist/generated/config.js`; + await generate({ + silent: true, + schema: ["graphql/**/Config.graphqls", ...schemaLocations], + generates: { + [targetTs]: { + plugins: ["typescript", "typescript-validation-schema", "add"], + config: { + // enumsAsTypes: true, + content: "/* eslint-disable */", + schema: "zod", + notAllowEmptyString: true, + strictScalars: true, + enumsAsTypes: true, + scalarSchemas: { + Domain: "z.string()", + DateTime: "z.date()", + RichTextAST: "z.object.json()" + } + } + }, + ...findParentPath(process.cwd()) && { + "../../docs/framework/config.md": { + plugins: ["@graphcommerce/graphql-codegen-markdown-docs"] + } + } + } + }); + writeFileSync( + targetTs, + await prettier.format(readFileSync(targetTs, "utf-8"), { + ...prettierConf, + parser: "typescript", + plugins: prettierConf.plugins?.filter( + (p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports") + ) + }) + ); + const result = transformFileSync(targetTs, { + module: { type: "nodenext" }, + env: { targets: { node: "18" } } + }); + console.log(targetJs); + writeFileSync(targetJs, result.code); +} + +const fmt = (value) => { + let formattedValue = value; + if (typeof formattedValue === "boolean") { + formattedValue = formattedValue ? "1" : "0"; + } + if (typeof formattedValue === "object") { + formattedValue = JSON.stringify(formattedValue); + } + if (typeof formattedValue === "number") { + formattedValue = String(formattedValue); + } + return formattedValue; +}; +function exportConfigToEnv(config) { + let env = ""; + Object.entries(config).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((val, idx) => { + env += `${toEnvStr([key, `${idx}`])}='${fmt(val)}' +`; + }); + } else { + env += `${toEnvStr([key])}='${fmt(value)}' +`; + } + }); + return env; +} + +dotenv.config(); +async function exportConfig() { + const conf = loadConfig(process.cwd()); + console.log(exportConfigToEnv(conf)); +} + +dotenv.config(); +async function codegenInterceptors() { + const conf = loadConfig(process.cwd()); + const [plugins] = findPlugins(conf); + const generatedInterceptors = await generateInterceptors( + plugins, + resolveDependency(), + conf.debug, + true + ); + await writeInterceptors(generatedInterceptors); +} + +const debug = (...args) => { + if (process.env.DEBUG) console.info("[copy-files]", ...args); +}; +const MANAGED_BY_GC = "// managed by: graphcommerce"; +const MANAGED_LOCALLY = "// managed by: local"; +const GITIGNORE_SECTION_START = "# managed by: graphcommerce"; +const GITIGNORE_SECTION_END = "# end managed by: graphcommerce"; +async function updateGitignore(managedFiles) { + const escapedFiles = managedFiles.map( + (file) => ( + // Escape special characters in file names + file.replace(/[*+?^${}()|[\]\\]/g, "\\$&") + ) + ).sort(); + const gitignorePath = path$1.join(process.cwd(), ".gitignore"); + let content; + try { + content = await fs$2.readFile(gitignorePath, "utf-8"); + debug("Reading existing .gitignore"); + } catch (err) { + debug(".gitignore not found, creating new file"); + content = ""; + } + const sectionRegex = new RegExp( + `${GITIGNORE_SECTION_START}[\\s\\S]*?${GITIGNORE_SECTION_END}\\n?`, + "g" + ); + content = content.replace(sectionRegex, ""); + if (escapedFiles.length > 0) { + const newSection = [ + GITIGNORE_SECTION_START, + ...escapedFiles, + GITIGNORE_SECTION_END, + "" + // Empty line at the end + ].join("\n"); + content = `${content.trim()} + +${newSection}`; + debug(`Updated .gitignore with ${managedFiles.length} managed files`); + } else { + content = `${content.trim()} +`; + debug("Cleaned up .gitignore managed section"); + } + await fs$2.writeFile(gitignorePath, content); +} +function getFileManagement(content) { + if (!content) return "graphcommerce"; + const contentStr = content.toString(); + if (contentStr.startsWith(MANAGED_LOCALLY)) return "local"; + if (contentStr.startsWith(MANAGED_BY_GC)) return "graphcommerce"; + return "unmanaged"; +} +async function copyFiles() { + const startTime = performance.now(); + debug("Starting copyFiles"); + const cwd = process.cwd(); + const deps = resolveDependenciesSync(); + const packages = [...deps.values()].filter((p) => p !== "."); + const fileMap = /* @__PURE__ */ new Map(); + const managedFiles = /* @__PURE__ */ new Set(); + const existingManagedFiles = /* @__PURE__ */ new Set(); + const scanStart = performance.now(); + try { + const gitignorePatterns = [ + "**/dist/**", + "**/build/**", + "**/.next/**", + "**/.git/**", + "**/node_modules/**" + ]; + const allFiles = await fg("**/*", { + cwd, + dot: true, + ignore: gitignorePatterns, + onlyFiles: true + }); + debug( + `Found ${allFiles.length} project files in ${(performance.now() - scanStart).toFixed(0)}ms` + ); + const readStart = performance.now(); + await Promise.all( + allFiles.map(async (file) => { + const filePath = path$1.join(cwd, file); + try { + const content = await fs$2.readFile(filePath); + if (getFileManagement(content) === "graphcommerce") { + existingManagedFiles.add(file); + debug(`Found existing managed file: ${file}`); + } + } catch (err) { + debug(`Error reading file ${file}:`, err); + } + }) + ); + debug( + `Read ${existingManagedFiles.size} managed files in ${(performance.now() - readStart).toFixed(0)}ms` + ); + } catch (err) { + debug("Error scanning project files:", err); + } + const collectStart = performance.now(); + await Promise.all( + packages.map(async (pkg) => { + const copyDir = path$1.join(pkg, "copy"); + try { + const files = await fg("**/*", { cwd: copyDir, dot: true, suppressErrors: true }); + if (files.length > 0) { + debug(`Found files in ${pkg}:`, files); + for (const file of files) { + const sourcePath = path$1.join(copyDir, file); + const existing = fileMap.get(file); + if (existing) { + console.error(`Error: File conflict detected for '${file}' +Found in packages: + - ${existing.packagePath} -> ${existing.sourcePath} + - ${pkg} -> ${sourcePath}`); + process.exit(1); + } + fileMap.set(file, { sourcePath, packagePath: pkg }); + } + } + } catch (err) { + if (err.code === "ENOENT") return; + console.error( + `Error scanning directory ${copyDir}: ${err.message} +Path: ${copyDir}` + ); + process.exit(1); + } + }) + ); + debug(`Collected ${fileMap.size} files in ${(performance.now() - collectStart).toFixed(0)}ms`); + const copyStart = performance.now(); + await Promise.all( + Array.from(fileMap.entries()).map(async ([file, { sourcePath }]) => { + const targetPath = path$1.join(cwd, file); + debug(`Processing file: ${file}`); + try { + await fs$2.mkdir(path$1.dirname(targetPath), { recursive: true }); + const sourceContent = await fs$2.readFile(sourcePath); + const contentWithComment = Buffer.concat([ + Buffer.from( + `${MANAGED_BY_GC} +// to modify this file, change it to managed by: local + +` + ), + sourceContent + ]); + let targetContent; + try { + targetContent = await fs$2.readFile(targetPath); + const management = getFileManagement(targetContent); + if (management === "local") { + debug(`File ${file} is managed locally, skipping`); + return; + } + if (management === "unmanaged") { + console.info( + `Note: File ${file} has been modified. Add '${MANAGED_LOCALLY.trim()}' at the top to manage it locally.` + ); + debug(`File ${file} doesn't have management comment, skipping`); + return; + } + debug(`File ${file} is managed by graphcommerce, will update if needed`); + } catch (err) { + if (err.code !== "ENOENT") { + console.error(`Error reading file ${file}: ${err.message} +Source: ${sourcePath}`); + process.exit(1); + } + console.info(`Creating new file: ${file} +Source: ${sourcePath}`); + debug("File does not exist yet"); + } + if (targetContent && Buffer.compare(contentWithComment, targetContent) === 0) { + debug(`File ${file} content is identical to source, skipping`); + managedFiles.add(file); + return; + } + await fs$2.writeFile(targetPath, contentWithComment); + if (targetContent) { + console.info(`Updated managed file: ${file}`); + debug(`Overwrote existing file: ${file}`); + } + if (!targetContent || targetContent.toString().startsWith(MANAGED_BY_GC)) { + managedFiles.add(file); + debug("Added managed file:", file); + } + } catch (err) { + console.error(`Error copying file ${file}: ${err.message} +Source: ${sourcePath}`); + process.exit(1); + } + }) + ); + debug(`Copied ${managedFiles.size} files in ${(performance.now() - copyStart).toFixed(0)}ms`); + const removeStart = performance.now(); + const filesToRemove = Array.from(existingManagedFiles).filter((file) => !managedFiles.has(file)); + debug(`Files to remove: ${filesToRemove.length}`); + async function cleanupEmptyDirs(startPath) { + let currentDir = startPath; + while (currentDir !== cwd) { + try { + const dirContents = await fs$2.readdir(currentDir); + if (dirContents.length === 0) { + await fs$2.rmdir(currentDir); + debug(`Removed empty directory: ${currentDir}`); + currentDir = path$1.dirname(currentDir); + } else { + break; + } + } catch (err) { + if (err.code === "EACCES") { + console.error(`Error cleaning up directory ${currentDir}: ${err.message}`); + process.exit(1); + } + break; + } + } + } + await Promise.all( + filesToRemove.map(async (file) => { + const filePath = path$1.join(cwd, file); + const dirPath = path$1.dirname(filePath); + try { + await fs$2.readdir(dirPath); + try { + await fs$2.unlink(filePath); + console.info(`Removed managed file: ${file}`); + debug(`Removed file: ${file}`); + } catch (err) { + if (err.code !== "ENOENT") { + console.error(`Error removing file ${file}: ${err.message}`); + process.exit(1); + } + } + await cleanupEmptyDirs(dirPath); + } catch (err) { + if (err.code === "EACCES") { + console.error(`Error accessing directory ${dirPath}: ${err.message}`); + process.exit(1); + } + } + }) + ); + debug(`Removed files in ${(performance.now() - removeStart).toFixed(0)}ms`); + if (managedFiles.size > 0) { + debug("Found managed files:", Array.from(managedFiles)); + await updateGitignore(Array.from(managedFiles)); + } else { + debug("No managed files found, cleaning up .gitignore section"); + await updateGitignore([]); + } + debug(`Total execution time: ${(performance.now() - startTime).toFixed(0)}ms`); +} + +async function codegen() { + console.info("\u{1F504} Copying files from packages to project..."); + await copyFiles(); + console.info("\u2699\uFE0F Generating GraphCommerce config types..."); + await generateConfig(); + console.info("\u{1F50C} Generating interceptors..."); + await codegenInterceptors(); +} + +export { GraphCommerceConfigSchema, codegen, codegenInterceptors, configToImportMeta, copyFiles, exportConfig, findParentPath, g, generateConfig, loadConfig, packageRoots, replaceConfigInString, resolveDependenciesSync, sig, sortDependencies, withGraphCommerce }; diff --git a/packagesDev/next-config/dist/interceptors/InterceptorPlugin.js b/packagesDev/next-config/dist/interceptors/InterceptorPlugin.js deleted file mode 100644 index 8c6e51b3cb..0000000000 --- a/packagesDev/next-config/dist/interceptors/InterceptorPlugin.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InterceptorPlugin = void 0; -const path_1 = __importDefault(require("path")); -const resolveDependency_1 = require("../utils/resolveDependency"); -const findPlugins_1 = require("./findPlugins"); -const generateInterceptors_1 = require("./generateInterceptors"); -const writeInterceptors_1 = require("./writeInterceptors"); -let interceptors; -let interceptorByDepependency; -let generating = false; -// let totalGenerationTime = 0 -class InterceptorPlugin { - config; - regenerate; - resolveDependency; - constructor(config, regenerate = false) { - this.config = config; - this.regenerate = regenerate; - this.resolveDependency = (0, resolveDependency_1.resolveDependency)(); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - if (regenerate) - this.#generateInterceptors(); - } - #generateInterceptors = async () => { - if (generating) - return {}; - generating = true; - // const start = Date.now() - // console.log('Generating interceptors...') - const [plugins] = (0, findPlugins_1.findPlugins)(this.config); - // console.log(errors) - // const found = Date.now() - // console.log('Found plugins in', found - start, 'ms') - const generatedInterceptors = await (0, generateInterceptors_1.generateInterceptors)(plugins, this.resolveDependency, this.config.debug); - // const generated = Date.now() - // console.log('Generated interceptors in', generated - found, 'ms') - await (0, writeInterceptors_1.writeInterceptors)(generatedInterceptors); - // const wrote = Date.now() - // console.log('Wrote interceptors in', wrote - generated, 'ms') - interceptors = generatedInterceptors; - interceptorByDepependency = Object.fromEntries(Object.values(interceptors).map((i) => [i.dependency, i])); - // totalGenerationTime += Date.now() - start - generating = false; - return generatedInterceptors; - }; - /** @public */ - apply(compiler) { - const logger = compiler.getInfrastructureLogger('InterceptorPlugin'); - // After the compilation has succeeded we watch all possible plugin locations. - if (this.regenerate) { - compiler.hooks.afterCompile.tap('InterceptorPlugin', (compilation) => { - // console.log('generate interceptors after compile') - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config); - plugins.forEach((p) => { - const source = this.resolveDependency(p.sourceModule); - if (source) { - const absoluteFilePath = `${path_1.default.join(process.cwd(), source.fromRoot)}.tsx`; - compilation.fileDependencies.add(absoluteFilePath); - } - }); - // eslint-disable-next-line @typescript-eslint/no-floating-promises - this.#generateInterceptors().then((i) => { - Object.entries(i).forEach(([, { sourcePath }]) => { - const absoluteFilePath = path_1.default.join(process.cwd(), sourcePath); - compilation.fileDependencies.add(absoluteFilePath); - }); - }); - }); - } - compiler.hooks.normalModuleFactory.tap('InterceptorPlugin', (nmf) => { - nmf.hooks.beforeResolve.tap('InterceptorPlugin', (resource) => { - const issuer = resource.contextInfo.issuer ?? ''; - const requestPath = path_1.default.relative(process.cwd(), path_1.default.resolve(resource.context, resource.request)); - if (!interceptors || !interceptorByDepependency) { - // console.log('interceptors not ready') - return; - } - const split = requestPath.split('/'); - const targets = [ - `${split[split.length - 1]}.interceptor.tsx`, - `${split[split.length - 1]}.interceptor.ts`, - ]; - if (targets.some((target) => issuer.endsWith(target)) && interceptors[requestPath]) { - logger.log(`Interceptor ${issuer} is requesting the original ${requestPath}`); - return; - } - const interceptorForRequest = interceptorByDepependency[resource.request]; - if (interceptorForRequest) { - const extension = interceptorForRequest.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts'; - resource.request = `${interceptorForRequest.denormalized}.interceptor${extension}`; - logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`, resource.request); - } - const interceptorForPath = interceptors[requestPath]; - if (interceptorForPath) { - const extension = interceptorForPath.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts'; - resource.request = `${resource.request}.interceptor${extension}`; - logger.log(`Intercepting fromRoot... ${interceptorForPath.dependency}`, resource.request); - } - }); - }); - } -} -exports.InterceptorPlugin = InterceptorPlugin; diff --git a/packagesDev/next-config/dist/interceptors/RenameVisitor.js b/packagesDev/next-config/dist/interceptors/RenameVisitor.js deleted file mode 100644 index 635db37336..0000000000 --- a/packagesDev/next-config/dist/interceptors/RenameVisitor.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RenameVisitor = void 0; -const Visitor_1 = require("./Visitor"); -class RenameVisitor extends Visitor_1.Visitor { - replace; - suffix; - constructor(replace, suffix) { - super(); - this.replace = replace; - this.suffix = suffix; - } - visitIdentifier(n) { - if (this.replace.includes(n.value)) - n.value = this.suffix(n.value); - return n; - } -} -exports.RenameVisitor = RenameVisitor; diff --git a/packagesDev/next-config/dist/interceptors/Visitor.js b/packagesDev/next-config/dist/interceptors/Visitor.js deleted file mode 100644 index c06f9509d7..0000000000 --- a/packagesDev/next-config/dist/interceptors/Visitor.js +++ /dev/null @@ -1,1414 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Visitor = void 0; -/* eslint-disable no-param-reassign */ -/* eslint-disable class-methods-use-this */ -/* eslint-disable consistent-return */ -/** - * @deprecated JavaScript API is deprecated. Please use Wasm plugin instead. - * @public - */ -class Visitor { - visitProgram(n) { - switch (n.type) { - case 'Module': - return this.visitModule(n); - case 'Script': - return this.visitScript(n); - } - } - visitModule(m) { - m.body = this.visitModuleItems(m.body); - return m; - } - visitScript(m) { - m.body = this.visitStatements(m.body); - return m; - } - visitModuleItems(items) { - return items.map(this.visitModuleItem.bind(this)); - } - visitModuleItem(n) { - switch (n.type) { - case 'ExportDeclaration': - case 'ExportDefaultDeclaration': - case 'ExportNamedDeclaration': - case 'ExportDefaultExpression': - case 'ImportDeclaration': - case 'ExportAllDeclaration': - case 'TsImportEqualsDeclaration': - case 'TsExportAssignment': - case 'TsNamespaceExportDeclaration': - return this.visitModuleDeclaration(n); - default: - return this.visitStatement(n); - } - } - visitModuleDeclaration(n) { - switch (n.type) { - case 'ExportDeclaration': - return this.visitExportDeclaration(n); - case 'ExportDefaultDeclaration': - return this.visitExportDefaultDeclaration(n); - case 'ExportNamedDeclaration': - return this.visitExportNamedDeclaration(n); - case 'ExportDefaultExpression': - return this.visitExportDefaultExpression(n); - case 'ImportDeclaration': - return this.visitImportDeclaration(n); - case 'ExportAllDeclaration': - return this.visitExportAllDeclaration(n); - case 'TsImportEqualsDeclaration': - return this.visitTsImportEqualsDeclaration(n); - case 'TsExportAssignment': - return this.visitTsExportAssignment(n); - case 'TsNamespaceExportDeclaration': - return this.visitTsNamespaceExportDeclaration(n); - } - } - visitTsNamespaceExportDeclaration(n) { - n.id = this.visitBindingIdentifier(n.id); - return n; - } - visitTsExportAssignment(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitTsImportEqualsDeclaration(n) { - n.id = this.visitBindingIdentifier(n.id); - n.moduleRef = this.visitTsModuleReference(n.moduleRef); - return n; - } - visitTsModuleReference(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifierReference(n); - case 'TsExternalModuleReference': - return this.visitTsExternalModuleReference(n); - case 'TsQualifiedName': - return this.visitTsQualifiedName(n); - } - } - visitTsExternalModuleReference(n) { - n.expression = this.visitStringLiteral(n.expression); - return n; - } - visitExportAllDeclaration(n) { - n.source = this.visitStringLiteral(n.source); - return n; - } - visitExportDefaultExpression(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitExportNamedDeclaration(n) { - n.specifiers = this.visitExportSpecifiers(n.specifiers); - n.source = this.visitOptionalStringLiteral(n.source); - return n; - } - visitExportSpecifiers(nodes) { - return nodes.map(this.visitExportSpecifier.bind(this)); - } - visitExportSpecifier(n) { - switch (n.type) { - case 'ExportDefaultSpecifier': - return this.visitExportDefaultSpecifier(n); - case 'ExportNamespaceSpecifier': - return this.visitExportNamespaceSpecifier(n); - case 'ExportSpecifier': - return this.visitNamedExportSpecifier(n); - } - } - visitNamedExportSpecifier(n) { - if (n.exported) { - n.exported = this.visitModuleExportName(n.exported); - } - n.orig = this.visitModuleExportName(n.orig); - return n; - } - visitModuleExportName(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifier(n); - case 'StringLiteral': - return this.visitStringLiteral(n); - } - } - visitExportNamespaceSpecifier(n) { - n.name = this.visitModuleExportName(n.name); - return n; - } - visitExportDefaultSpecifier(n) { - n.exported = this.visitBindingIdentifier(n.exported); - return n; - } - visitOptionalStringLiteral(n) { - if (n) { - return this.visitStringLiteral(n); - } - } - visitExportDefaultDeclaration(n) { - n.decl = this.visitDefaultDeclaration(n.decl); - return n; - } - visitDefaultDeclaration(n) { - switch (n.type) { - case 'ClassExpression': - return this.visitClassExpression(n); - case 'FunctionExpression': - return this.visitFunctionExpression(n); - case 'TsInterfaceDeclaration': - return this.visitTsInterfaceDeclaration(n); - } - } - visitFunctionExpression(n) { - n = this.visitFunction(n); - if (n.identifier) { - n.identifier = this.visitBindingIdentifier(n.identifier); - } - return n; - } - visitClassExpression(n) { - n = this.visitClass(n); - if (n.identifier) { - n.identifier = this.visitBindingIdentifier(n.identifier); - } - return n; - } - visitExportDeclaration(n) { - n.declaration = this.visitDeclaration(n.declaration); - return n; - } - visitArrayExpression(e) { - if (e.elements) { - e.elements = e.elements.map(this.visitArrayElement.bind(this)); - } - return e; - } - visitArrayElement(e) { - if (e) { - return this.visitExprOrSpread(e); - } - } - visitExprOrSpread(e) { - return { - ...e, - expression: this.visitExpression(e.expression), - }; - } - visitExprOrSpreads(nodes) { - return nodes.map(this.visitExprOrSpread.bind(this)); - } - visitSpreadElement(e) { - e.arguments = this.visitExpression(e.arguments); - return e; - } - visitOptionalExpression(e) { - if (e) { - return this.visitExpression(e); - } - } - visitArrowFunctionExpression(e) { - e.body = this.visitArrowBody(e.body); - e.params = this.visitPatterns(e.params); - e.returnType = this.visitTsTypeAnnotation(e.returnType); - e.typeParameters = this.visitTsTypeParameterDeclaration(e.typeParameters); - return e; - } - visitArrowBody(body) { - switch (body.type) { - case 'BlockStatement': - return this.visitBlockStatement(body); - default: - return this.visitExpression(body); - } - } - visitBlockStatement(block) { - block.stmts = this.visitStatements(block.stmts); - return block; - } - visitStatements(stmts) { - return stmts.map(this.visitStatement.bind(this)); - } - visitStatement(stmt) { - switch (stmt.type) { - case 'ClassDeclaration': - case 'FunctionDeclaration': - case 'TsEnumDeclaration': - case 'TsInterfaceDeclaration': - case 'TsModuleDeclaration': - case 'TsTypeAliasDeclaration': - case 'VariableDeclaration': - return this.visitDeclaration(stmt); - case 'BreakStatement': - return this.visitBreakStatement(stmt); - case 'BlockStatement': - return this.visitBlockStatement(stmt); - case 'ContinueStatement': - return this.visitContinueStatement(stmt); - case 'DebuggerStatement': - return this.visitDebuggerStatement(stmt); - case 'DoWhileStatement': - return this.visitDoWhileStatement(stmt); - case 'EmptyStatement': - return this.visitEmptyStatement(stmt); - case 'ForInStatement': - return this.visitForInStatement(stmt); - case 'ForOfStatement': - return this.visitForOfStatement(stmt); - case 'ForStatement': - return this.visitForStatement(stmt); - case 'IfStatement': - return this.visitIfStatement(stmt); - case 'LabeledStatement': - return this.visitLabeledStatement(stmt); - case 'ReturnStatement': - return this.visitReturnStatement(stmt); - case 'SwitchStatement': - return this.visitSwitchStatement(stmt); - case 'ThrowStatement': - return this.visitThrowStatement(stmt); - case 'TryStatement': - return this.visitTryStatement(stmt); - case 'WhileStatement': - return this.visitWhileStatement(stmt); - case 'WithStatement': - return this.visitWithStatement(stmt); - case 'ExpressionStatement': - return this.visitExpressionStatement(stmt); - default: - throw new Error(`Unknown statement type: ${stmt.type}`); - } - } - visitSwitchStatement(stmt) { - stmt.discriminant = this.visitExpression(stmt.discriminant); - stmt.cases = this.visitSwitchCases(stmt.cases); - return stmt; - } - visitSwitchCases(cases) { - return cases.map(this.visitSwitchCase.bind(this)); - } - visitSwitchCase(c) { - c.test = this.visitOptionalExpression(c.test); - c.consequent = this.visitStatements(c.consequent); - return c; - } - visitIfStatement(stmt) { - stmt.test = this.visitExpression(stmt.test); - stmt.consequent = this.visitStatement(stmt.consequent); - stmt.alternate = this.visitOptionalStatement(stmt.alternate); - return stmt; - } - visitOptionalStatement(stmt) { - if (stmt) { - return this.visitStatement(stmt); - } - } - visitBreakStatement(stmt) { - if (stmt.label) { - stmt.label = this.visitLabelIdentifier(stmt.label); - } - return stmt; - } - visitWhileStatement(stmt) { - stmt.test = this.visitExpression(stmt.test); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitTryStatement(stmt) { - stmt.block = this.visitBlockStatement(stmt.block); - stmt.handler = this.visitCatchClause(stmt.handler); - if (stmt.finalizer) { - stmt.finalizer = this.visitBlockStatement(stmt.finalizer); - } - return stmt; - } - visitCatchClause(handler) { - if (handler) { - if (handler.param) { - handler.param = this.visitPattern(handler.param); - } - handler.body = this.visitBlockStatement(handler.body); - } - return handler; - } - visitThrowStatement(stmt) { - stmt.argument = this.visitExpression(stmt.argument); - return stmt; - } - visitReturnStatement(stmt) { - if (stmt.argument) { - stmt.argument = this.visitExpression(stmt.argument); - } - return stmt; - } - visitLabeledStatement(stmt) { - stmt.label = this.visitLabelIdentifier(stmt.label); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitForStatement(stmt) { - if (stmt.init) { - if (stmt.init.type === 'VariableDeclaration') { - stmt.init = this.visitVariableDeclaration(stmt.init); - } - else { - stmt.init = this.visitOptionalExpression(stmt.init); - } - } - stmt.test = this.visitOptionalExpression(stmt.test); - stmt.update = this.visitOptionalExpression(stmt.update); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitForOfStatement(stmt) { - if (stmt.left.type === 'VariableDeclaration') { - stmt.left = this.visitVariableDeclaration(stmt.left); - } - else { - stmt.left = this.visitPattern(stmt.left); - } - stmt.right = this.visitExpression(stmt.right); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitForInStatement(stmt) { - if (stmt.left.type === 'VariableDeclaration') { - stmt.left = this.visitVariableDeclaration(stmt.left); - } - else { - stmt.left = this.visitPattern(stmt.left); - } - stmt.right = this.visitExpression(stmt.right); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitEmptyStatement(stmt) { - return stmt; - } - visitDoWhileStatement(stmt) { - stmt.body = this.visitStatement(stmt.body); - stmt.test = this.visitExpression(stmt.test); - return stmt; - } - visitDebuggerStatement(stmt) { - return stmt; - } - visitWithStatement(stmt) { - stmt.object = this.visitExpression(stmt.object); - stmt.body = this.visitStatement(stmt.body); - return stmt; - } - visitDeclaration(decl) { - switch (decl.type) { - case 'ClassDeclaration': - return this.visitClassDeclaration(decl); - case 'FunctionDeclaration': - return this.visitFunctionDeclaration(decl); - case 'TsEnumDeclaration': - return this.visitTsEnumDeclaration(decl); - case 'TsInterfaceDeclaration': - return this.visitTsInterfaceDeclaration(decl); - case 'TsModuleDeclaration': - return this.visitTsModuleDeclaration(decl); - case 'TsTypeAliasDeclaration': - return this.visitTsTypeAliasDeclaration(decl); - case 'VariableDeclaration': - return this.visitVariableDeclaration(decl); - } - } - visitVariableDeclaration(n) { - n.declarations = this.visitVariableDeclarators(n.declarations); - return n; - } - visitVariableDeclarators(nodes) { - return nodes.map(this.visitVariableDeclarator.bind(this)); - } - visitVariableDeclarator(n) { - n.id = this.visitPattern(n.id); - n.init = this.visitOptionalExpression(n.init); - return n; - } - visitTsTypeAliasDeclaration(n) { - n.id = this.visitBindingIdentifier(n.id); - n.typeAnnotation = this.visitTsType(n.typeAnnotation); - n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams); - return n; - } - visitTsModuleDeclaration(n) { - n.id = this.visitTsModuleName(n.id); - if (n.body) { - n.body = this.visitTsNamespaceBody(n.body); - } - return n; - } - visitTsModuleName(n) { - switch (n.type) { - case 'Identifier': - return this.visitBindingIdentifier(n); - case 'StringLiteral': - return this.visitStringLiteral(n); - } - } - visitTsNamespaceBody(n) { - if (n) { - switch (n.type) { - case 'TsModuleBlock': - return this.visitTsModuleBlock(n); - case 'TsNamespaceDeclaration': - return this.visitTsNamespaceDeclaration(n); - } - } - } - visitTsNamespaceDeclaration(n) { - const body = this.visitTsNamespaceBody(n.body); - if (body) { - n.body = body; - } - n.id = this.visitBindingIdentifier(n.id); - return n; - } - visitTsModuleBlock(n) { - n.body = this.visitModuleItems(n.body); - return n; - } - visitTsInterfaceDeclaration(n) { - n.id = this.visitBindingIdentifier(n.id); - n.typeParams = this.visitTsTypeParameterDeclaration(n.typeParams); - n.extends = this.visitTsExpressionsWithTypeArguments(n.extends); - n.body = this.visitTsInterfaceBody(n.body); - return n; - } - visitTsInterfaceBody(n) { - n.body = this.visitTsTypeElements(n.body); - return n; - } - visitTsTypeElements(nodes) { - return nodes.map(this.visitTsTypeElement.bind(this)); - } - visitTsTypeElement(n) { - switch (n.type) { - case 'TsCallSignatureDeclaration': - return this.visitTsCallSignatureDeclaration(n); - case 'TsConstructSignatureDeclaration': - return this.visitTsConstructSignatureDeclaration(n); - case 'TsPropertySignature': - return this.visitTsPropertySignature(n); - case 'TsGetterSignature': - return this.visitTsGetterSignature(n); - case 'TsSetterSignature': - return this.visitTsSetterSignature(n); - case 'TsMethodSignature': - return this.visitTsMethodSignature(n); - case 'TsIndexSignature': - return this.visitTsIndexSignature(n); - } - } - visitTsCallSignatureDeclaration(n) { - n.params = this.visitTsFnParameters(n.params); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitTsConstructSignatureDeclaration(n) { - n.params = this.visitTsFnParameters(n.params); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitTsPropertySignature(n) { - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitTsGetterSignature(n) { - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitTsSetterSignature(n) { - n.param = this.visitTsFnParameter(n.param); - return n; - } - visitTsMethodSignature(n) { - n.params = this.visitTsFnParameters(n.params); - n.typeAnn = this.visitTsTypeAnnotation(n.typeAnn); - return n; - } - visitTsEnumDeclaration(n) { - n.id = this.visitIdentifier(n.id); - n.members = this.visitTsEnumMembers(n.members); - return n; - } - visitTsEnumMembers(nodes) { - return nodes.map(this.visitTsEnumMember.bind(this)); - } - visitTsEnumMember(n) { - n.id = this.visitTsEnumMemberId(n.id); - n.init = this.visitOptionalExpression(n.init); - return n; - } - visitTsEnumMemberId(n) { - switch (n.type) { - case 'Identifier': - return this.visitBindingIdentifier(n); - case 'StringLiteral': - return this.visitStringLiteral(n); - } - } - visitFunctionDeclaration(decl) { - decl.identifier = this.visitIdentifier(decl.identifier); - decl = this.visitFunction(decl); - return decl; - } - visitClassDeclaration(decl) { - decl = this.visitClass(decl); - decl.identifier = this.visitIdentifier(decl.identifier); - return decl; - } - visitClassBody(members) { - return members.map(this.visitClassMember.bind(this)); - } - visitClassMember(member) { - switch (member.type) { - case 'ClassMethod': - return this.visitClassMethod(member); - case 'ClassProperty': - return this.visitClassProperty(member); - case 'Constructor': - return this.visitConstructor(member); - case 'PrivateMethod': - return this.visitPrivateMethod(member); - case 'PrivateProperty': - return this.visitPrivateProperty(member); - case 'TsIndexSignature': - return this.visitTsIndexSignature(member); - case 'EmptyStatement': - return this.visitEmptyStatement(member); - case 'StaticBlock': - return this.visitStaticBlock(member); - } - } - visitTsIndexSignature(n) { - n.params = this.visitTsFnParameters(n.params); - if (n.typeAnnotation) - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitTsFnParameters(params) { - return params.map(this.visitTsFnParameter.bind(this)); - } - visitTsFnParameter(n) { - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitPrivateProperty(n) { - n.decorators = this.visitDecorators(n.decorators); - n.key = this.visitPrivateName(n.key); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - n.value = this.visitOptionalExpression(n.value); - return n; - } - visitPrivateMethod(n) { - n.accessibility = this.visitAccessibility(n.accessibility); - n.function = this.visitFunction(n.function); - n.key = this.visitPrivateName(n.key); - return n; - } - visitPrivateName(n) { - return n; - } - visitConstructor(n) { - n.accessibility = this.visitAccessibility(n.accessibility); - n.key = this.visitPropertyName(n.key); - n.params = this.visitConstructorParameters(n.params); - if (n.body) { - n.body = this.visitBlockStatement(n.body); - } - return n; - } - visitConstructorParameters(nodes) { - return nodes.map(this.visitConstructorParameter.bind(this)); - } - visitConstructorParameter(n) { - switch (n.type) { - case 'TsParameterProperty': - return this.visitTsParameterProperty(n); - default: - return this.visitParameter(n); - } - } - visitStaticBlock(n) { - n.body = this.visitBlockStatement(n.body); - return n; - } - visitTsParameterProperty(n) { - n.accessibility = this.visitAccessibility(n.accessibility); - n.decorators = this.visitDecorators(n.decorators); - n.param = this.visitTsParameterPropertyParameter(n.param); - return n; - } - visitTsParameterPropertyParameter(n) { - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitPropertyName(key) { - switch (key.type) { - case 'Identifier': - return this.visitBindingIdentifier(key); - case 'StringLiteral': - return this.visitStringLiteral(key); - case 'NumericLiteral': - return this.visitNumericLiteral(key); - case 'BigIntLiteral': - return this.visitBigIntLiteral(key); - default: - return this.visitComputedPropertyKey(key); - } - } - visitAccessibility(n) { - return n; - } - visitClassProperty(n) { - n.accessibility = this.visitAccessibility(n.accessibility); - n.decorators = this.visitDecorators(n.decorators); - n.key = this.visitPropertyName(n.key); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - n.value = this.visitOptionalExpression(n.value); - return n; - } - visitClassMethod(n) { - n.accessibility = this.visitAccessibility(n.accessibility); - n.function = this.visitFunction(n.function); - n.key = this.visitPropertyName(n.key); - return n; - } - visitComputedPropertyKey(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitClass(n) { - n.decorators = this.visitDecorators(n.decorators); - n.superClass = this.visitOptionalExpression(n.superClass); - n.superTypeParams = this.visitTsTypeParameterInstantiation(n.superTypeParams); - if (n.implements) { - n.implements = this.visitTsExpressionsWithTypeArguments(n.implements); - } - n.body = this.visitClassBody(n.body); - return n; - } - visitFunction(n) { - n.decorators = this.visitDecorators(n.decorators); - n.params = this.visitParameters(n.params); - if (n.body) { - n.body = this.visitBlockStatement(n.body); - } - n.returnType = this.visitTsTypeAnnotation(n.returnType); - n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters); - return n; - } - visitTsExpressionsWithTypeArguments(nodes) { - return nodes.map(this.visitTsExpressionWithTypeArguments.bind(this)); - } - visitTsExpressionWithTypeArguments(n) { - n.expression = this.visitExpression(n.expression); - n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); - return n; - } - visitTsTypeParameterInstantiation(n) { - if (n) { - n.params = this.visitTsTypes(n.params); - } - return n; - } - visitTsTypes(nodes) { - return nodes.map(this.visitTsType.bind(this)); - } - visitTsEntityName(n) { - switch (n.type) { - case 'Identifier': - return this.visitBindingIdentifier(n); - case 'TsQualifiedName': - return this.visitTsQualifiedName(n); - } - } - visitTsQualifiedName(n) { - n.left = this.visitTsEntityName(n.left); - n.right = this.visitIdentifier(n.right); - return n; - } - visitDecorators(nodes) { - if (nodes) { - return nodes.map(this.visitDecorator.bind(this)); - } - } - visitDecorator(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitExpressionStatement(stmt) { - stmt.expression = this.visitExpression(stmt.expression); - return stmt; - } - visitContinueStatement(stmt) { - if (stmt.label) { - stmt.label = this.visitLabelIdentifier(stmt.label); - } - return stmt; - } - visitExpression(n) { - switch (n.type) { - case 'ArrayExpression': - return this.visitArrayExpression(n); - case 'ArrowFunctionExpression': - return this.visitArrowFunctionExpression(n); - case 'AssignmentExpression': - return this.visitAssignmentExpression(n); - case 'AwaitExpression': - return this.visitAwaitExpression(n); - case 'BigIntLiteral': - return this.visitBigIntLiteral(n); - case 'BinaryExpression': - return this.visitBinaryExpression(n); - case 'BooleanLiteral': - return this.visitBooleanLiteral(n); - case 'CallExpression': - return this.visitCallExpression(n); - case 'ClassExpression': - return this.visitClassExpression(n); - case 'ConditionalExpression': - return this.visitConditionalExpression(n); - case 'FunctionExpression': - return this.visitFunctionExpression(n); - case 'Identifier': - return this.visitIdentifierReference(n); - case 'JSXElement': - return this.visitJSXElement(n); - case 'JSXEmptyExpression': - return this.visitJSXEmptyExpression(n); - case 'JSXFragment': - return this.visitJSXFragment(n); - case 'JSXMemberExpression': - return this.visitJSXMemberExpression(n); - case 'JSXNamespacedName': - return this.visitJSXNamespacedName(n); - case 'JSXText': - return this.visitJSXText(n); - case 'MemberExpression': - return this.visitMemberExpression(n); - case 'SuperPropExpression': - return this.visitSuperPropExpression(n); - case 'MetaProperty': - return this.visitMetaProperty(n); - case 'NewExpression': - return this.visitNewExpression(n); - case 'NullLiteral': - return this.visitNullLiteral(n); - case 'NumericLiteral': - return this.visitNumericLiteral(n); - case 'ObjectExpression': - return this.visitObjectExpression(n); - case 'ParenthesisExpression': - return this.visitParenthesisExpression(n); - case 'PrivateName': - return this.visitPrivateName(n); - case 'RegExpLiteral': - return this.visitRegExpLiteral(n); - case 'SequenceExpression': - return this.visitSequenceExpression(n); - case 'StringLiteral': - return this.visitStringLiteral(n); - case 'TaggedTemplateExpression': - return this.visitTaggedTemplateExpression(n); - case 'TemplateLiteral': - return this.visitTemplateLiteral(n); - case 'ThisExpression': - return this.visitThisExpression(n); - case 'TsAsExpression': - return this.visitTsAsExpression(n); - case 'TsSatisfiesExpression': - return this.visitTsSatisfiesExpression(n); - case 'TsNonNullExpression': - return this.visitTsNonNullExpression(n); - case 'TsTypeAssertion': - return this.visitTsTypeAssertion(n); - case 'TsConstAssertion': - return this.visitTsConstAssertion(n); - case 'TsInstantiation': - return this.visitTsInstantiation(n); - case 'UnaryExpression': - return this.visitUnaryExpression(n); - case 'UpdateExpression': - return this.visitUpdateExpression(n); - case 'YieldExpression': - return this.visitYieldExpression(n); - case 'OptionalChainingExpression': - return this.visitOptionalChainingExpression(n); - case 'Invalid': - return n; - } - } - visitOptionalChainingExpression(n) { - n.base = this.visitMemberExpressionOrOptionalChainingCall(n.base); - return n; - } - visitMemberExpressionOrOptionalChainingCall(n) { - switch (n.type) { - case 'MemberExpression': - return this.visitMemberExpression(n); - case 'CallExpression': - return this.visitOptionalChainingCall(n); - } - } - visitOptionalChainingCall(n) { - n.callee = this.visitExpression(n.callee); - n.arguments = this.visitExprOrSpreads(n.arguments); - if (n.typeArguments) - n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); - return n; - } - visitAssignmentExpression(n) { - n.left = this.visitPatternOrExpression(n.left); - n.right = this.visitExpression(n.right); - return n; - } - visitPatternOrExpression(n) { - switch (n.type) { - case 'ObjectPattern': - case 'ArrayPattern': - case 'Identifier': - case 'AssignmentPattern': - case 'RestElement': - return this.visitPattern(n); - default: - return this.visitExpression(n); - } - } - visitYieldExpression(n) { - n.argument = this.visitOptionalExpression(n.argument); - return n; - } - visitUpdateExpression(n) { - n.argument = this.visitExpression(n.argument); - return n; - } - visitUnaryExpression(n) { - n.argument = this.visitExpression(n.argument); - return n; - } - visitTsTypeAssertion(n) { - n.expression = this.visitExpression(n.expression); - n.typeAnnotation = this.visitTsType(n.typeAnnotation); - return n; - } - visitTsConstAssertion(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitTsInstantiation(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitTsNonNullExpression(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitTsAsExpression(n) { - n.expression = this.visitExpression(n.expression); - n.typeAnnotation = this.visitTsType(n.typeAnnotation); - return n; - } - visitTsSatisfiesExpression(n) { - n.expression = this.visitExpression(n.expression); - n.typeAnnotation = this.visitTsType(n.typeAnnotation); - return n; - } - visitThisExpression(n) { - return n; - } - visitTemplateLiteral(n) { - n.expressions = n.expressions.map(this.visitExpression.bind(this)); - return n; - } - visitParameters(n) { - return n.map(this.visitParameter.bind(this)); - } - visitParameter(n) { - n.pat = this.visitPattern(n.pat); - return n; - } - visitTaggedTemplateExpression(n) { - n.tag = this.visitExpression(n.tag); - const template = this.visitTemplateLiteral(n.template); - if (template.type === 'TemplateLiteral') { - n.template = template; - } - return n; - } - visitSequenceExpression(n) { - n.expressions = n.expressions.map(this.visitExpression.bind(this)); - return n; - } - visitRegExpLiteral(n) { - return n; - } - visitParenthesisExpression(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitObjectExpression(n) { - if (n.properties) { - n.properties = this.visitObjectProperties(n.properties); - } - return n; - } - visitObjectProperties(nodes) { - return nodes.map(this.visitObjectProperty.bind(this)); - } - visitObjectProperty(n) { - switch (n.type) { - case 'SpreadElement': - return this.visitSpreadElement(n); - default: - return this.visitProperty(n); - } - } - visitProperty(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifier(n); - case 'AssignmentProperty': - return this.visitAssignmentProperty(n); - case 'GetterProperty': - return this.visitGetterProperty(n); - case 'KeyValueProperty': - return this.visitKeyValueProperty(n); - case 'MethodProperty': - return this.visitMethodProperty(n); - case 'SetterProperty': - return this.visitSetterProperty(n); - } - } - visitSetterProperty(n) { - n.key = this.visitPropertyName(n.key); - n.param = this.visitPattern(n.param); - if (n.body) { - n.body = this.visitBlockStatement(n.body); - } - return n; - } - visitMethodProperty(n) { - n.key = this.visitPropertyName(n.key); - if (n.body) { - n.body = this.visitBlockStatement(n.body); - } - n.decorators = this.visitDecorators(n.decorators); - n.params = this.visitParameters(n.params); - n.returnType = this.visitTsTypeAnnotation(n.returnType); - n.typeParameters = this.visitTsTypeParameterDeclaration(n.typeParameters); - return n; - } - visitKeyValueProperty(n) { - n.key = this.visitPropertyName(n.key); - n.value = this.visitExpression(n.value); - return n; - } - visitGetterProperty(n) { - n.key = this.visitPropertyName(n.key); - if (n.body) { - n.body = this.visitBlockStatement(n.body); - } - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitAssignmentProperty(n) { - n.key = this.visitIdentifier(n.key); - n.value = this.visitExpression(n.value); - return n; - } - visitNullLiteral(n) { - return n; - } - visitNewExpression(n) { - n.callee = this.visitExpression(n.callee); - if (n.arguments) { - n.arguments = this.visitArguments(n.arguments); - } - n.typeArguments = this.visitTsTypeArguments(n.typeArguments); - return n; - } - visitTsTypeArguments(n) { - if (n) { - n.params = this.visitTsTypes(n.params); - } - return n; - } - visitArguments(nodes) { - return nodes.map(this.visitArgument.bind(this)); - } - visitArgument(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitMetaProperty(n) { - return n; - } - visitMemberExpression(n) { - n.object = this.visitExpression(n.object); - switch (n.property.type) { - case 'Computed': { - n.property = this.visitComputedPropertyKey(n.property); - return n; - } - case 'Identifier': { - n.property = this.visitIdentifier(n.property); - return n; - } - case 'PrivateName': { - n.property = this.visitPrivateName(n.property); - return n; - } - } - } - visitSuperPropExpression(n) { - switch (n.property.type) { - case 'Computed': { - n.property = this.visitComputedPropertyKey(n.property); - return n; - } - case 'Identifier': { - n.property = this.visitIdentifier(n.property); - return n; - } - } - } - visitCallee(n) { - if (n.type === 'Super' || n.type === 'Import') { - return n; - } - return this.visitExpression(n); - } - visitJSXText(n) { - return n; - } - visitJSXNamespacedName(n) { - n.namespace = this.visitIdentifierReference(n.namespace); - n.name = this.visitIdentifierReference(n.name); - return n; - } - visitJSXMemberExpression(n) { - n.object = this.visitJSXObject(n.object); - n.property = this.visitIdentifierReference(n.property); - return n; - } - visitJSXObject(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifierReference(n); - case 'JSXMemberExpression': - return this.visitJSXMemberExpression(n); - } - } - visitJSXFragment(n) { - n.opening = this.visitJSXOpeningFragment(n.opening); - if (n.children) { - n.children = this.visitJSXElementChildren(n.children); - } - n.closing = this.visitJSXClosingFragment(n.closing); - return n; - } - visitJSXClosingFragment(n) { - return n; - } - visitJSXElementChildren(nodes) { - return nodes.map(this.visitJSXElementChild.bind(this)); - } - visitJSXElementChild(n) { - switch (n.type) { - case 'JSXElement': - return this.visitJSXElement(n); - case 'JSXExpressionContainer': - return this.visitJSXExpressionContainer(n); - case 'JSXFragment': - return this.visitJSXFragment(n); - case 'JSXSpreadChild': - return this.visitJSXSpreadChild(n); - case 'JSXText': - return this.visitJSXText(n); - } - } - visitJSXExpressionContainer(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitJSXSpreadChild(n) { - n.expression = this.visitExpression(n.expression); - return n; - } - visitJSXOpeningFragment(n) { - return n; - } - visitJSXEmptyExpression(n) { - return n; - } - visitJSXElement(n) { - n.opening = this.visitJSXOpeningElement(n.opening); - n.children = this.visitJSXElementChildren(n.children); - n.closing = this.visitJSXClosingElement(n.closing); - return n; - } - visitJSXClosingElement(n) { - if (n) { - n.name = this.visitJSXElementName(n.name); - } - return n; - } - visitJSXElementName(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifierReference(n); - case 'JSXMemberExpression': - return this.visitJSXMemberExpression(n); - case 'JSXNamespacedName': - return this.visitJSXNamespacedName(n); - } - } - visitJSXOpeningElement(n) { - n.name = this.visitJSXElementName(n.name); - n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); - n.attributes = this.visitJSXAttributeOrSpreads(n.attributes); - return n; - } - visitJSXAttributes(attrs) { - if (attrs) - return attrs.map(this.visitJSXAttributeOrSpread.bind(this)); - } - visitJSXAttributeOrSpread(n) { - switch (n.type) { - case 'JSXAttribute': - return this.visitJSXAttribute(n); - case 'SpreadElement': - return this.visitSpreadElement(n); - } - } - visitJSXAttributeOrSpreads(nodes) { - return nodes.map(this.visitJSXAttributeOrSpread.bind(this)); - } - visitJSXAttribute(n) { - n.name = this.visitJSXAttributeName(n.name); - n.value = this.visitJSXAttributeValue(n.value); - return n; - } - visitJSXAttributeValue(n) { - if (!n) - return n; - switch (n.type) { - case 'BooleanLiteral': - return this.visitBooleanLiteral(n); - case 'NullLiteral': - return this.visitNullLiteral(n); - case 'NumericLiteral': - return this.visitNumericLiteral(n); - case 'JSXText': - return this.visitJSXText(n); - case 'StringLiteral': - return this.visitStringLiteral(n); - case 'JSXElement': - return this.visitJSXElement(n); - case 'JSXExpressionContainer': - return this.visitJSXExpressionContainer(n); - case 'JSXFragment': - return this.visitJSXFragment(n); - } - return n; - } - visitJSXAttributeName(n) { - switch (n.type) { - case 'Identifier': - return this.visitIdentifierReference(n); - case 'JSXNamespacedName': - return this.visitJSXNamespacedName(n); - } - } - visitConditionalExpression(n) { - n.test = this.visitExpression(n.test); - n.consequent = this.visitExpression(n.consequent); - n.alternate = this.visitExpression(n.alternate); - return n; - } - visitCallExpression(n) { - n.callee = this.visitCallee(n.callee); - n.typeArguments = this.visitTsTypeParameterInstantiation(n.typeArguments); - if (n.arguments) { - n.arguments = this.visitArguments(n.arguments); - } - return n; - } - visitBooleanLiteral(n) { - return n; - } - visitBinaryExpression(n) { - n.left = this.visitExpression(n.left); - n.right = this.visitExpression(n.right); - return n; - } - visitAwaitExpression(n) { - n.argument = this.visitExpression(n.argument); - return n; - } - visitTsTypeParameterDeclaration(n) { - if (n) { - n.parameters = this.visitTsTypeParameters(n.parameters); - } - return n; - } - visitTsTypeParameters(nodes) { - return nodes.map(this.visitTsTypeParameter.bind(this)); - } - visitTsTypeParameter(n) { - if (n.constraint) { - n.constraint = this.visitTsType(n.constraint); - } - if (n.default) { - n.default = this.visitTsType(n.default); - } - n.name = this.visitIdentifierReference(n.name); - return n; - } - visitTsTypeAnnotation(a) { - if (a) { - a.typeAnnotation = this.visitTsType(a.typeAnnotation); - } - return a; - } - visitTsType(n) { - return n; - throw new Error('Method visitTsType not implemented.'); - } - visitPatterns(nodes) { - return nodes.map(this.visitPattern.bind(this)); - } - visitImportDeclaration(n) { - n.source = this.visitStringLiteral(n.source); - n.specifiers = this.visitImportSpecifiers(n.specifiers || []); - return n; - } - visitImportSpecifiers(nodes) { - return nodes.map(this.visitImportSpecifier.bind(this)); - } - visitImportSpecifier(node) { - switch (node.type) { - case 'ImportDefaultSpecifier': - return this.visitImportDefaultSpecifier(node); - case 'ImportNamespaceSpecifier': - return this.visitImportNamespaceSpecifier(node); - case 'ImportSpecifier': - return this.visitNamedImportSpecifier(node); - } - } - visitNamedImportSpecifier(node) { - node.local = this.visitBindingIdentifier(node.local); - if (node.imported) { - node.imported = this.visitModuleExportName(node.imported); - } - return node; - } - visitImportNamespaceSpecifier(node) { - node.local = this.visitBindingIdentifier(node.local); - return node; - } - visitImportDefaultSpecifier(node) { - node.local = this.visitBindingIdentifier(node.local); - return node; - } - visitBindingIdentifier(i) { - if (i.typeAnnotation) { - i.typeAnnotation = this.visitTsTypeAnnotation(i.typeAnnotation); - } - return this.visitIdentifier(i); - } - visitIdentifierReference(i) { - return this.visitIdentifier(i); - } - visitLabelIdentifier(label) { - return this.visitIdentifier(label); - } - visitIdentifier(n) { - return n; - } - visitStringLiteral(n) { - return n; - } - visitNumericLiteral(n) { - return n; - } - visitBigIntLiteral(n) { - return n; - } - visitPattern(n) { - switch (n.type) { - case 'Identifier': - return this.visitBindingIdentifier(n); - case 'ArrayPattern': - return this.visitArrayPattern(n); - case 'ObjectPattern': - return this.visitObjectPattern(n); - case 'AssignmentPattern': - return this.visitAssignmentPattern(n); - case 'RestElement': - return this.visitRestElement(n); - default: - return this.visitExpression(n); - } - } - visitRestElement(n) { - n.argument = this.visitPattern(n.argument); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitAssignmentPattern(n) { - n.left = this.visitPattern(n.left); - n.right = this.visitExpression(n.right); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitObjectPattern(n) { - n.properties = this.visitObjectPatternProperties(n.properties || []); - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - return n; - } - visitObjectPatternProperties(nodes) { - return nodes.map(this.visitObjectPatternProperty.bind(this)); - } - visitObjectPatternProperty(n) { - switch (n.type) { - case 'AssignmentPatternProperty': - return this.visitAssignmentPatternProperty(n); - case 'KeyValuePatternProperty': - return this.visitKeyValuePatternProperty(n); - case 'RestElement': - return this.visitRestElement(n); - } - } - visitKeyValuePatternProperty(n) { - n.key = this.visitPropertyName(n.key); - n.value = this.visitPattern(n.value); - return n; - } - visitAssignmentPatternProperty(n) { - n.key = this.visitBindingIdentifier(n.key); - n.value = this.visitOptionalExpression(n.value); - return n; - } - visitArrayPattern(n) { - n.typeAnnotation = this.visitTsTypeAnnotation(n.typeAnnotation); - n.elements = this.visitArrayPatternElements(n.elements); - return n; - } - visitArrayPatternElements(nodes) { - return nodes.map(this.visitArrayPatternElement.bind(this)); - } - visitArrayPatternElement(n) { - if (n) { - n = this.visitPattern(n); - } - return n; - } -} -exports.Visitor = Visitor; diff --git a/packagesDev/next-config/dist/interceptors/commands/codegenInterceptors.js b/packagesDev/next-config/dist/interceptors/commands/codegenInterceptors.js deleted file mode 100644 index ef0a15c755..0000000000 --- a/packagesDev/next-config/dist/interceptors/commands/codegenInterceptors.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.codegenInterceptors = codegenInterceptors; -const dotenv_1 = __importDefault(require("dotenv")); -const loadConfig_1 = require("../../config/loadConfig"); -const resolveDependency_1 = require("../../utils/resolveDependency"); -const findPlugins_1 = require("../findPlugins"); -const generateInterceptors_1 = require("../generateInterceptors"); -const writeInterceptors_1 = require("../writeInterceptors"); -dotenv_1.default.config(); -// eslint-disable-next-line @typescript-eslint/require-await -async function codegenInterceptors() { - const conf = (0, loadConfig_1.loadConfig)(process.cwd()); - const [plugins] = (0, findPlugins_1.findPlugins)(conf); - const generatedInterceptors = await (0, generateInterceptors_1.generateInterceptors)(plugins, (0, resolveDependency_1.resolveDependency)(), conf.debug, true); - // const generated = Date.now() - // console.log('Generated interceptors in', generated - found, 'ms') - await (0, writeInterceptors_1.writeInterceptors)(generatedInterceptors); -} diff --git a/packagesDev/next-config/dist/interceptors/extractExports.js b/packagesDev/next-config/dist/interceptors/extractExports.js deleted file mode 100644 index 6b8bbdc245..0000000000 --- a/packagesDev/next-config/dist/interceptors/extractExports.js +++ /dev/null @@ -1,159 +0,0 @@ -"use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.extractExports = extractExports; -function isIdentifier(node) { - return node.type === 'Identifier'; -} -function isBooleanLiteral(node) { - return node.type === 'BooleanLiteral'; -} -function isNullLiteral(node) { - return node.type === 'NullLiteral'; -} -function isStringLiteral(node) { - return node.type === 'StringLiteral'; -} -function isNumericLiteral(node) { - return node.type === 'NumericLiteral'; -} -function isArrayExpression(node) { - return node.type === 'ArrayExpression'; -} -function isObjectExpression(node) { - return node.type === 'ObjectExpression'; -} -function isKeyValueProperty(node) { - return node.type === 'KeyValueProperty'; -} -function isRegExpLiteral(node) { - return node.type === 'RegExpLiteral'; -} -function isTemplateLiteral(node) { - return node.type === 'TemplateLiteral'; -} -const RUNTIME_VALUE = Symbol('RUNTIME_VALUE'); -function extractValue(node, path, optional = false) { - if (isNullLiteral(node)) { - return null; - } - if (isBooleanLiteral(node)) { - // e.g. true / false - return node.value; - } - if (isStringLiteral(node)) { - // e.g. "abc" - return node.value; - } - if (isNumericLiteral(node)) { - // e.g. 123 - return node.value; - } - if (isRegExpLiteral(node)) { - // e.g. /abc/i - return new RegExp(node.pattern, node.flags); - } - if (isIdentifier(node)) { - switch (node.value) { - case 'undefined': - return undefined; - default: - return RUNTIME_VALUE; - } - } - else if (isArrayExpression(node)) { - // e.g. [1, 2, 3] - const arr = []; - for (let i = 0, len = node.elements.length; i < len; i++) { - const elem = node.elements[i]; - if (elem) { - if (elem.spread) { - // e.g. [ ...a ] - return RUNTIME_VALUE; - } - arr.push(extractValue(elem.expression, path && [...path, `[${i}]`], optional)); - } - else { - // e.g. [1, , 2] - // ^^ - arr.push(undefined); - } - } - return arr; - } - else if (isObjectExpression(node)) { - // e.g. { a: 1, b: 2 } - const obj = {}; - for (const prop of node.properties) { - if (!isKeyValueProperty(prop)) { - // e.g. { ...a } - return RUNTIME_VALUE; - } - let key; - if (isIdentifier(prop.key)) { - // e.g. { a: 1, b: 2 } - key = prop.key.value; - } - else if (isStringLiteral(prop.key)) { - // e.g. { "a": 1, "b": 2 } - key = prop.key.value; - } - else { - return RUNTIME_VALUE; - } - obj[key] = extractValue(prop.value, path && [...path, key]); - } - return obj; - } - else if (isTemplateLiteral(node)) { - // e.g. `abc` - if (node.expressions.length !== 0) { - // TODO: should we add support for `${'e'}d${'g'}'e'`? - return RUNTIME_VALUE; - } - // When TemplateLiteral has 0 expressions, the length of quasis is always 1. - // Because when parsing TemplateLiteral, the parser yields the first quasi, - // then the first expression, then the next quasi, then the next expression, etc., - // until the last quasi. - // Thus if there is no expression, the parser ends at the frst and also last quasis - // - // A "cooked" interpretation where backslashes have special meaning, while a - // "raw" interpretation where backslashes do not have special meaning - // https://exploringjs.com/impatient-js/ch_template-literals.html#template-strings-cooked-vs-raw - const [{ cooked, raw }] = node.quasis; - return cooked ?? raw; - } - else { - return RUNTIME_VALUE; - } -} -function extractExports(module) { - const exports = {}; - const errors = []; - for (const moduleItem of module.body) { - switch (moduleItem.type) { - case 'ExportAllDeclaration': - errors.push('You can not use export * from a plugin, exports must be explicit'); - break; - case 'ExportDefaultDeclaration': - errors.push('You can not use default exports from a plugin, exports must be explicit'); - break; - case 'ExportDeclaration': - switch (moduleItem.declaration.type) { - case 'ClassDeclaration': - case 'FunctionDeclaration': - exports[moduleItem.declaration.identifier.value] = RUNTIME_VALUE; - // node.identifier.value - break; - case 'VariableDeclaration': - moduleItem.declaration.declarations.forEach((decl) => { - if (isIdentifier(decl.id) && decl.init) { - exports[decl.id.value] = extractValue(decl.init, undefined, true); - } - }); - break; - } - } - } - return [exports, errors]; -} diff --git a/packagesDev/next-config/dist/interceptors/findOriginalSource.js b/packagesDev/next-config/dist/interceptors/findOriginalSource.js deleted file mode 100644 index daabeea971..0000000000 --- a/packagesDev/next-config/dist/interceptors/findOriginalSource.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findOriginalSource = findOriginalSource; -const path_1 = __importDefault(require("path")); -const swc_1 = require("./swc"); -function parseAndFindExport(resolved, findExport, resolve) { - if (!resolved?.source) - return undefined; - const ast = (0, swc_1.parseSync)(resolved.source); - for (const node of ast.body) { - if (node.type === 'ExportDeclaration') { - switch (node.declaration.type) { - case 'ClassDeclaration': - case 'FunctionDeclaration': - if (node.declaration.identifier.value === findExport) - return resolved; - break; - case 'VariableDeclaration': - for (const declaration of node.declaration.declarations) { - if (declaration.type === 'VariableDeclarator') { - if (declaration.id.type === 'Identifier') { - if (declaration.id.value === findExport) - return resolved; - } - else { - // eslint-disable-next-line no-console - console.log(declaration); - } - } - } - break; - } - } - if (node.type === 'ExportNamedDeclaration') { - for (const specifier of node.specifiers) { - if (specifier.type === 'ExportSpecifier') { - if (specifier.exported?.value === findExport) - return resolved; - } - else if (specifier.type === 'ExportDefaultSpecifier') { - // todo - } - else if (specifier.type === 'ExportNamespaceSpecifier') { - // todo - } - } - } - // todo: if (node.type === 'ExportDefaultDeclaration') {} - // todo: if (node.type === 'ExportDefaultExpression') {} - } - const exports = ast.body - .filter((node) => node.type === 'ExportAllDeclaration') - .sort((a, b) => { - const probablyA = a.source.value.includes(findExport); - const probablyB = b.source.value.includes(findExport); - // eslint-disable-next-line no-nested-ternary - return probablyA === probablyB ? 0 : probablyA ? -1 : 1; - }); - for (const node of exports) { - const isRelative = node.source.value.startsWith('.'); - if (isRelative) { - const d = resolved.dependency === resolved.denormalized - ? resolved.dependency.substring(0, resolved.dependency.lastIndexOf('/')) - : resolved.dependency; - const newPath = path_1.default.join(d, node.source.value); - const resolveResult = resolve(newPath, { includeSources: true }); - // eslint-disable-next-line no-continue - if (!resolveResult) - continue; - const newResolved = parseAndFindExport(resolveResult, findExport, resolve); - if (newResolved && resolved.dependency !== newResolved.dependency) - return newResolved; - } - } - return undefined; -} -// const cachedResults = new Map() -function findOriginalSource(plug, resolved, resolve) { - if (!resolved?.source) - return { - resolved: undefined, - error: new Error(`Plugin: Can not find module ${plug.targetModule} for ${plug.sourceModule}`), - }; - // const cacheKey = `${plug.targetModule}#${plug.targetExport}` - // if (cachedResults.has(cacheKey)) { - // return { - // resolved: cachedResults.get(cacheKey) as NonNullable, - // error: undefined, - // } - // } - const newResolved = parseAndFindExport(resolved, plug.targetExport, resolve); - if (!newResolved) { - return { - resolved: undefined, - error: new Error(`Plugin target not found ${plug.targetModule}#${plug.sourceExport} for plugin ${plug.sourceModule}#${plug.sourceExport}`), - }; - } - // cachedResults.set(cacheKey, newResolved) - return { resolved: newResolved, error: undefined }; -} diff --git a/packagesDev/next-config/dist/interceptors/findPlugins.js b/packagesDev/next-config/dist/interceptors/findPlugins.js deleted file mode 100644 index a3081ab15b..0000000000 --- a/packagesDev/next-config/dist/interceptors/findPlugins.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findPlugins = findPlugins; -const core_1 = require("@swc/core"); -const glob_1 = require("glob"); -const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync"); -const parseStructure_1 = require("./parseStructure"); -const pluginLogs = {}; -// ANSI escape codes for console colors -const GREEN = '\x1b[32m'; -const RESET = '\x1b[0m'; -function findPlugins(config, cwd = process.cwd()) { - const dependencies = (0, resolveDependenciesSync_1.resolveDependenciesSync)(cwd); - const debug = Boolean(config.debug?.pluginStatus); - const errors = []; - const plugins = []; - dependencies.forEach((filePath, packageName) => { - const files = (0, glob_1.sync)(`${filePath}/plugins/**/*.{ts,tsx}`); - files.forEach((file) => { - let sourceModule = file.replace('.tsx', '').replace('.ts', ''); - if (file.startsWith(filePath)) - sourceModule = `${packageName}/${sourceModule.slice(filePath.length + 1)}`; - if (packageName === '.' && !sourceModule.startsWith('.')) - sourceModule = `./${sourceModule}`; - try { - const ast = (0, core_1.parseFileSync)(file, { syntax: 'typescript', tsx: true }); - (0, parseStructure_1.parseStructure)(ast, config, sourceModule).forEach((result) => { - plugins.push(result); - }); - } - catch (e) { - console.error(`Error parsing ${file}`, e); - } - }); - }); - if (process.env.NODE_ENV === 'development' && debug) { - const byExported = plugins.reduce((acc, plugin) => { - const key = `🔌 ${GREEN}Plugins loaded for ${plugin.targetModule}#${plugin.targetExport}${RESET}`; - if (!acc[key]) - acc[key] = []; - acc[key].push(plugin); - return acc; - }, {}); - const toLog = []; - Object.entries(byExported).forEach(([key, p]) => { - const logStr = p - .filter((c) => debug || c.enabled) - .map((c) => { - // eslint-disable-next-line no-nested-ternary - const ifConfigStr = c.ifConfig - ? Array.isArray(c.ifConfig) - ? `${c.ifConfig[0]}=${c.ifConfig[1]}` - : `${c.ifConfig}` - : ''; - return `${c.enabled ? '🟢' : '⚪️'} ${c.sourceModule} ${ifConfigStr}`; - }) - .join('\n'); - if (logStr && pluginLogs[key] !== logStr) { - toLog.push(`${key}\n${logStr}`); - pluginLogs[key] = logStr; - } - }); - // eslint-disable-next-line no-console - if (toLog.length) - console.log(toLog.join('\n\n')); - } - return [plugins, errors]; -} diff --git a/packagesDev/next-config/dist/interceptors/generateInterceptor.js b/packagesDev/next-config/dist/interceptors/generateInterceptor.js deleted file mode 100644 index 840c4454fc..0000000000 --- a/packagesDev/next-config/dist/interceptors/generateInterceptor.js +++ /dev/null @@ -1,219 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SOURCE_END = exports.SOURCE_START = void 0; -exports.isPluginBaseConfig = isPluginBaseConfig; -exports.isReactPluginConfig = isReactPluginConfig; -exports.isMethodPluginConfig = isMethodPluginConfig; -exports.isReplacePluginConfig = isReplacePluginConfig; -exports.isPluginConfig = isPluginConfig; -exports.moveRelativeDown = moveRelativeDown; -exports.generateInterceptor = generateInterceptor; -// eslint-disable-next-line import/no-extraneous-dependencies -const prettier_config_pwa_1 = __importDefault(require("@graphcommerce/prettier-config-pwa")); -// eslint-disable-next-line import/no-extraneous-dependencies -const prettier_1 = __importDefault(require("prettier")); -const RenameVisitor_1 = require("./RenameVisitor"); -const swc_1 = require("./swc"); -/** @public */ -function isPluginBaseConfig(plugin) { - return (typeof plugin.type === 'string' && - typeof plugin.sourceModule === 'string' && - typeof plugin.enabled === 'boolean' && - typeof plugin.targetExport === 'string'); -} -/** @public */ -function isReactPluginConfig(plugin) { - if (!isPluginBaseConfig(plugin)) - return false; - return plugin.type === 'component'; -} -/** @public */ -function isMethodPluginConfig(plugin) { - if (!isPluginBaseConfig(plugin)) - return false; - return plugin.type === 'function'; -} -/** @public */ -function isReplacePluginConfig(plugin) { - if (!isPluginBaseConfig(plugin)) - return false; - return plugin.type === 'replace'; -} -function isPluginConfig(plugin) { - return isPluginBaseConfig(plugin); -} -exports.SOURCE_START = '/** SOURCE_START */'; -exports.SOURCE_END = '/** SOURCE_END */'; -const originalSuffix = 'Original'; -const interceptorSuffix = 'Interceptor'; -const disabledSuffix = 'Disabled'; -const name = (plugin) => `${plugin.sourceExport}${plugin.sourceModule - .split('/')[plugin.sourceModule.split('/').length - 1].replace(/[^a-zA-Z0-9]/g, '')}`; -const fileName = (plugin) => `${plugin.sourceModule}#${plugin.sourceExport}`; -const originalName = (n) => `${n}${originalSuffix}`; -const sourceName = (n) => `${n}`; -const interceptorName = (n) => `${n}${interceptorSuffix}`; -const interceptorPropsName = (n) => `${n}Props`; -function moveRelativeDown(plugins) { - return [...plugins].sort((a, b) => { - if (a.sourceModule.startsWith('.') && !b.sourceModule.startsWith('.')) - return 1; - if (!a.sourceModule.startsWith('.') && b.sourceModule.startsWith('.')) - return -1; - return 0; - }); -} -const generateIdentifyer = (s) => Math.abs(s.split('').reduce((a, b) => { - // eslint-disable-next-line no-param-reassign, no-bitwise - a = (a << 5) - a + b.charCodeAt(0); - // eslint-disable-next-line no-bitwise - return a & a; -}, 0)).toString(); -/** The is on the first line, with the format: /* hash:${identifer} */ -function extractIdentifier(source) { - if (!source) - return null; - const match = source.match(/\/\* hash:(\d+) \*\//); - if (!match) - return null; - return match[1]; -} -async function generateInterceptor(interceptor, config, oldInterceptorSource) { - const identifer = generateIdentifyer(JSON.stringify(interceptor) + JSON.stringify(config)); - const { dependency, targetExports, source } = interceptor; - if (oldInterceptorSource && identifer === extractIdentifier(oldInterceptorSource)) - return { ...interceptor, template: oldInterceptorSource }; - const pluginConfigs = [...Object.entries(targetExports)].map(([, plugins]) => plugins).flat(); - // console.log('pluginConfigs', pluginConfigs) - const duplicateImports = new Set(); - const pluginImports = moveRelativeDown([...pluginConfigs].sort((a, b) => a.sourceModule.localeCompare(b.sourceModule))) - .map((plugin) => `import { ${plugin.sourceExport} as ${sourceName(name(plugin))} } from '${plugin.sourceModule}'`) - .filter((str) => { - if (duplicateImports.has(str)) - return false; - duplicateImports.add(str); - return true; - }) - .join('\n'); - const ast = (0, swc_1.parseSync)(source); - new RenameVisitor_1.RenameVisitor(Object.keys(targetExports), (s) => originalName(s)).visitModule(ast); - const pluginExports = Object.entries(targetExports) - .map(([base, plugins]) => { - const duplicateInterceptors = new Set(); - let carry = originalName(base); - let carryProps = []; - const pluginSee = []; - pluginSee.push(`@see {@link file://${interceptor.sourcePathRelative}} for original source file`); - const pluginStr = plugins - .reverse() - .filter((p) => { - if (duplicateInterceptors.has(name(p))) - return false; - duplicateInterceptors.add(name(p)); - return true; - }) - .map((p) => { - let result; - const wrapChain = plugins - .reverse() - .map((pl) => name(pl)) - .join(' wrapping '); - if (isReplacePluginConfig(p)) { - new RenameVisitor_1.RenameVisitor([originalName(p.targetExport)], (s) => s.replace(originalSuffix, disabledSuffix)).visitModule(ast); - carryProps.push(`React.ComponentProps`); - pluginSee.push(`@see {${sourceName(name(p))}} for replacement of the original source (original source not used)`); - } - if (isReactPluginConfig(p)) { - const withBraces = config.pluginStatus || process.env.NODE_ENV === 'development'; - result = ` - type ${interceptorPropsName(name(p))} = ${carryProps.join(' & ')} & OmitPrev, 'Prev'> - - const ${interceptorName(name(p))} = (props: ${interceptorPropsName(name(p))}) => ${withBraces ? '{' : '('} - ${config.pluginStatus ? `logOnce(\`🔌 Rendering ${base} with plugin(s): ${wrapChain} wrapping <${base}/>\`)` : ''} - - ${process.env.NODE_ENV === 'development' - ? `if(!props['data-plugin']) - logOnce('${fileName(p)} does not spread props to prev: . This will cause issues if multiple plugins are applied to this component.')` - : ''} - ${withBraces ? 'return' : ''} <${sourceName(name(p))} {...props} Prev={${carry}} /> - ${withBraces ? '}' : ')'}`; - carryProps = [interceptorPropsName(name(p))]; - pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`); - } - if (isMethodPluginConfig(p)) { - result = `const ${interceptorName(name(p))}: typeof ${carry} = (...args) => { - ${config.pluginStatus ? `logOnce(\`🔌 Calling ${base} with plugin(s): ${wrapChain} wrapping ${base}()\`)` : ''} - return ${sourceName(name(p))}(${carry}, ...args) - }`; - pluginSee.push(`@see {${sourceName(name(p))}} for source of applied plugin`); - } - carry = p.type === 'replace' ? sourceName(name(p)) : interceptorName(name(p)); - return result; - }) - .filter((v) => !!v) - .join('\n'); - const isComponent = plugins.every((p) => isReactPluginConfig(p)); - if (isComponent && plugins.some((p) => isMethodPluginConfig(p))) { - throw new Error(`Cannot mix React and Method plugins for ${base} in ${dependency}.`); - } - const seeString = ` - /** - * Here you see the 'interceptor' that is applying all the configured plugins. - * - * This file is NOT meant to be modified directly and is auto-generated if the plugins or the original source changes. - * - ${pluginSee.map((s) => `* ${s}`).join('\n')} - */`; - if (process.env.NODE_ENV === 'development' && isComponent) { - return `${pluginStr} - ${seeString} - export const ${base}: typeof ${carry} = (props) => { - return <${carry} {...props} data-plugin /> - }`; - } - return ` - ${pluginStr} - ${seeString} - export const ${base} = ${carry} - `; - }) - .join('\n'); - const logOnce = config.pluginStatus || process.env.NODE_ENV === 'development' - ? ` - const logged: Set = new Set(); - const logOnce = (log: string, ...additional: unknown[]) => { - if (logged.has(log)) return - logged.add(log) - console.warn(log, ...additional) - } - ` - : ''; - const template = `/* hash:${identifer} */ - /* eslint-disable */ - /* This file is automatically generated for ${dependency} */ - ${Object.values(targetExports).some((t) => t.some((p) => p.type === 'component')) - ? "import type { DistributedOmit as OmitPrev } from 'type-fest'" - : ''} - - ${pluginImports} - - /** @see {@link file://${interceptor.sourcePathRelative}} for source of original */ - ${exports.SOURCE_START} - ${(0, swc_1.printSync)(ast).code} - ${exports.SOURCE_END} - ${logOnce}${pluginExports} - `; - let templateFormatted; - try { - templateFormatted = await prettier_1.default.format(template, { ...prettier_config_pwa_1.default, parser: 'typescript' }); - } - catch (e) { - // eslint-disable-next-line no-console - console.log('Error formatting interceptor: ', e, 'using raw template.'); - templateFormatted = template; - } - return { ...interceptor, template: templateFormatted }; -} diff --git a/packagesDev/next-config/dist/interceptors/generateInterceptors.js b/packagesDev/next-config/dist/interceptors/generateInterceptors.js deleted file mode 100644 index 391e44249b..0000000000 --- a/packagesDev/next-config/dist/interceptors/generateInterceptors.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.generateInterceptors = generateInterceptors; -// eslint-disable-next-line import/no-extraneous-dependencies -const promises_1 = __importDefault(require("node:fs/promises")); -const node_path_1 = __importDefault(require("node:path")); -const findOriginalSource_1 = require("./findOriginalSource"); -const generateInterceptor_1 = require("./generateInterceptor"); -async function generateInterceptors(plugins, resolve, config, force) { - const byTargetModuleAndExport = (0, generateInterceptor_1.moveRelativeDown)(plugins).reduce((acc, plug) => { - let { sourceModule: pluginPath } = plug; - if (!(0, generateInterceptor_1.isPluginConfig)(plug) || !plug.enabled) - return acc; - const result = resolve(plug.targetModule, { includeSources: true }); - const { error, resolved } = (0, findOriginalSource_1.findOriginalSource)(plug, result, resolve); - if (error) { - console.error(error.message); - return acc; - } - const { fromRoot } = resolved; - if (pluginPath.startsWith('.')) { - const resolvedPlugin = resolve(pluginPath); - if (resolvedPlugin) { - pluginPath = node_path_1.default.relative(resolved.fromRoot.split('/').slice(0, -1).join('/'), resolvedPlugin.fromRoot); - } - } - if (!acc[resolved.fromRoot]) { - acc[resolved.fromRoot] = { - ...resolved, - target: `${resolved.fromRoot}.interceptor`, - targetExports: {}, - }; - } - if (!acc[fromRoot].targetExports[plug.targetExport]) - acc[fromRoot].targetExports[plug.targetExport] = []; - acc[fromRoot].targetExports[plug.targetExport].push({ ...plug, sourceModule: pluginPath }); - return acc; - }, {}); - return Object.fromEntries(await Promise.all(Object.entries(byTargetModuleAndExport).map(async ([target, interceptor]) => { - const file = `${interceptor.fromRoot}.interceptor.tsx`; - const originalSource = !force && - (await promises_1.default - .access(file, promises_1.default.constants.F_OK) - .then(() => true) - .catch(() => false)) - ? (await promises_1.default.readFile(file)).toString() - : undefined; - return [ - target, - await (0, generateInterceptor_1.generateInterceptor)(interceptor, config ?? {}, originalSource), - ]; - }))); -} diff --git a/packagesDev/next-config/dist/interceptors/parseStructure.js b/packagesDev/next-config/dist/interceptors/parseStructure.js deleted file mode 100644 index ff40075af1..0000000000 --- a/packagesDev/next-config/dist/interceptors/parseStructure.js +++ /dev/null @@ -1,84 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseStructure = parseStructure; -const get_1 = __importDefault(require("lodash/get")); -const zod_1 = require("zod"); -const extractExports_1 = require("./extractExports"); -const pluginConfigParsed = zod_1.z.object({ - type: zod_1.z.enum(['component', 'function', 'replace']), - module: zod_1.z.string(), - export: zod_1.z.string(), - ifConfig: zod_1.z.union([zod_1.z.string(), zod_1.z.tuple([zod_1.z.string(), zod_1.z.unknown()])]).optional(), -}); -function nonNullable(value) { - return value !== null && value !== undefined; -} -const isObject = (input) => typeof input === 'object' && input !== null && !Array.isArray(input); -function parseStructure(ast, gcConfig, sourceModule) { - const [exports, errors] = (0, extractExports_1.extractExports)(ast); - if (errors.length) - console.error('Plugin error for', errors.join('\n')); - const { config: moduleConfig, component, func, exported, ifConfig, plugin, Plugin, ...rest } = exports; - const exportVals = Object.keys(rest); - if (component && !moduleConfig) - exportVals.push('Plugin'); - if (func && !moduleConfig) - exportVals.push('plugin'); - const pluginConfigs = exportVals - .map((exportVal) => { - let config = isObject(moduleConfig) ? moduleConfig : {}; - if (!moduleConfig && component) { - config = { type: 'component', module: exported, ifConfig, export: 'Plugin' }; - } - else if (!moduleConfig && func) { - config = { type: 'function', module: exported, ifConfig, export: 'plugin' }; - } - else if (isObject(moduleConfig)) { - config = { ...moduleConfig, export: exportVal }; - } - else { - console.error(`Plugin configuration invalid! See ${sourceModule}`); - return null; - } - const parsed = pluginConfigParsed.safeParse(config); - if (!parsed.success) { - if (errors.length) - console.error(parsed.error.errors.map((e) => `${e.path} ${e.message}`).join('\n')); - return undefined; - } - let enabled = true; - if (parsed.data.ifConfig) { - if (Array.isArray(parsed.data.ifConfig)) { - const isBoolean = typeof parsed.data.ifConfig[1] === 'boolean'; - let confValue = (0, get_1.default)(gcConfig, parsed.data.ifConfig[0]); - confValue = isBoolean ? Boolean(confValue) : confValue; - enabled = confValue === parsed.data.ifConfig[1]; - } - else { - enabled = Boolean((0, get_1.default)(gcConfig, parsed.data.ifConfig)); - } - } - const val = { - targetExport: exports.component || exports.func || parsed.data.export, - sourceModule, - sourceExport: parsed.data.export, - targetModule: parsed.data.module, - type: parsed.data.type, - enabled, - }; - if (parsed.data.ifConfig) - val.ifConfig = parsed.data.ifConfig; - return val; - }) - .filter(nonNullable); - const newPluginConfigs = pluginConfigs.reduce((acc, pluginConfig) => { - if (!acc.find((accPluginConfig) => accPluginConfig.sourceExport === pluginConfig.sourceExport)) { - acc.push(pluginConfig); - } - return acc; - }, []); - return newPluginConfigs; -} diff --git a/packagesDev/next-config/dist/interceptors/swc.js b/packagesDev/next-config/dist/interceptors/swc.js deleted file mode 100644 index a8b8d96a61..0000000000 --- a/packagesDev/next-config/dist/interceptors/swc.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseSync = parseSync; -exports.printSync = printSync; -const core_1 = require("@swc/core"); -function parseSync(src) { - return (0, core_1.parseSync)(src, { - syntax: 'typescript', - tsx: true, - comments: true, - }); -} -function printSync(m) { - return (0, core_1.printSync)(m); -} diff --git a/packagesDev/next-config/dist/interceptors/writeInterceptors.js b/packagesDev/next-config/dist/interceptors/writeInterceptors.js deleted file mode 100644 index 2604ea8852..0000000000 --- a/packagesDev/next-config/dist/interceptors/writeInterceptors.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.writeInterceptors = writeInterceptors; -// eslint-disable-next-line import/no-extraneous-dependencies -const promises_1 = __importDefault(require("node:fs/promises")); -const path_1 = __importDefault(require("path")); -const glob_1 = require("glob"); -const resolveDependenciesSync_1 = require("../utils/resolveDependenciesSync"); -function checkFileExists(file) { - return promises_1.default - .access(file, promises_1.default.constants.F_OK) - .then(() => true) - .catch(() => false); -} -async function writeInterceptors(interceptors, cwd = process.cwd()) { - const dependencies = (0, resolveDependenciesSync_1.resolveDependenciesSync)(cwd); - const existing = new Set(); - dependencies.forEach((dependency) => { - const files = (0, glob_1.sync)([`${dependency}/**/*.interceptor.tsx`, `${dependency}/**/*.interceptor.ts`], { cwd }); - files.forEach((file) => existing.add(file)); - }); - const written = Object.entries(interceptors).map(async ([, plugin]) => { - const extension = plugin.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts'; - const relativeFile = `${plugin.fromRoot}.interceptor${extension}`; - if (existing.has(relativeFile)) { - existing.delete(relativeFile); - } - if (existing.has(`./${relativeFile}`)) { - existing.delete(`./${relativeFile}`); - } - const fileToWrite = path_1.default.join(cwd, relativeFile); - const isSame = (await checkFileExists(fileToWrite)) && - (await promises_1.default.readFile(fileToWrite, 'utf8')).toString() === plugin.template; - if (!isSame) - await promises_1.default.writeFile(fileToWrite, plugin.template); - }); - // Cleanup unused interceptors - const cleaned = [...existing].map(async (file) => (await checkFileExists(file)) && (await promises_1.default.unlink(file))); - await Promise.all(written); - await Promise.all(cleaned); -} diff --git a/packagesDev/next-config/dist/utils/PackagesSort.js b/packagesDev/next-config/dist/utils/PackagesSort.js deleted file mode 100644 index 965a53f3d9..0000000000 --- a/packagesDev/next-config/dist/utils/PackagesSort.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PackagesSort = void 0; -const TopologicalSort_1 = require("./TopologicalSort"); -class PackagesSort extends TopologicalSort_1.TopologicalSort { -} -exports.PackagesSort = PackagesSort; diff --git a/packagesDev/next-config/dist/utils/TopologicalSort.js b/packagesDev/next-config/dist/utils/TopologicalSort.js deleted file mode 100644 index f15dbea92f..0000000000 --- a/packagesDev/next-config/dist/utils/TopologicalSort.js +++ /dev/null @@ -1,87 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TopologicalSort = void 0; -/* eslint-disable @typescript-eslint/no-non-null-assertion */ -const assert_1 = __importDefault(require("assert")); -class TopologicalSort { - #nodes; - #visitedNodes; - #sortedKeysStack; - constructor(nodes) { - this.#nodes = new Map(); - this.addMultipleInternalNodes(nodes); - } - /** @public */ - addNode(key, node) { - return this.addInternalNode(key, node); - } - /** @public */ - addNodes(nodes) { - this.addMultipleInternalNodes(nodes); - } - /** @public */ - addEdge(fromKey, toKey) { - (0, assert_1.default)(this.#nodes.has(fromKey), `Source package with ${fromKey} key should exist`); - (0, assert_1.default)(this.#nodes.has(toKey), `Target package with ${toKey} key should exist`); - const sourceNode = this.#nodes.get(fromKey); - const targetNode = this.#nodes.get(toKey); - assert_1.default.strictEqual(sourceNode !== undefined, true, `Source package with key ${fromKey} doesn't exist`); - assert_1.default.strictEqual(targetNode !== undefined, true, `Target package with key ${toKey} doesn't exist`); - assert_1.default.strictEqual(sourceNode.children.has(toKey), false, `Source package ${fromKey} already has an edge to target node ${toKey}`); - sourceNode.children.set(toKey, targetNode); - } - /** @public */ - sort() { - this.#visitedNodes = new Set(); - this.#sortedKeysStack = []; - const output = new Map(); - for (const [key] of this.#nodes) { - this.exploreNode(key, []); - } - for (let i = this.#sortedKeysStack.length - 1; i >= 0; i--) { - const node = this.#nodes.get(this.#sortedKeysStack[i]); - output.set(this.#sortedKeysStack[i], node); - } - return output; - } - exploreNode(nodeKey, explorePath) { - const newExplorePath = [...explorePath, nodeKey]; - // we should check circular dependencies starting from node 2 - if (explorePath.length) { - if (explorePath.includes(nodeKey)) { - throw Error(`Package ${nodeKey} forms circular dependency: ${newExplorePath - .slice(newExplorePath.indexOf(nodeKey)) - .join(' -> ')}`); - } - } - const node = this.#nodes.get(nodeKey); - if (this.#visitedNodes.has(node)) - return; - // mark node as visited so that it and its children - // won't be explored next time - this.#visitedNodes.add(node); - for (const [childNodeKey] of node.children) { - this.exploreNode(childNodeKey, newExplorePath); - } - this.#sortedKeysStack.push(nodeKey); - } - addInternalNode(key, node) { - assert_1.default.strictEqual(this.#nodes.has(key), false, `Node ${key} already exists`); - this.#nodes.set(key, { - children: new Map(), - node, - }); - return this; - } - addMultipleInternalNodes(nodes) { - const nodesFlat = [...nodes]; - for (let i = nodes.size - 1; i >= 0; i--) { - const [key, node] = nodesFlat[i]; - this.addInternalNode(key, node); - } - } -} -exports.TopologicalSort = TopologicalSort; diff --git a/packagesDev/next-config/dist/utils/isMonorepo.js b/packagesDev/next-config/dist/utils/isMonorepo.js deleted file mode 100644 index a3b60b8a30..0000000000 --- a/packagesDev/next-config/dist/utils/isMonorepo.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.findParentPath = findParentPath; -const node_fs_1 = __importDefault(require("node:fs")); -const node_path_1 = __importDefault(require("node:path")); -const debug = process.env.DEBUG === '1'; -// eslint-disable-next-line no-console -const log = (message) => debug && console.log(`isMonorepo: ${message}`); -function findPackageJson(directory) { - try { - const packageJsonPath = node_path_1.default.join(directory, 'package.json'); - const content = node_fs_1.default.readFileSync(packageJsonPath, 'utf8'); - return JSON.parse(content); - } - catch { - return null; - } -} -/** - * Finds the path of the parent @graphcommerce package if it exists Returns null if no parent - * package is found - */ -function findParentPath(directory) { - let currentDir = directory; - log(`Starting directory: ${currentDir}`); - // Start from the parent directory - currentDir = node_path_1.default.dirname(currentDir); - log(`Looking for parent packages starting from: ${currentDir}`); - // Keep going up until we find a root package or hit the filesystem root - while (currentDir !== node_path_1.default.parse(currentDir).root) { - const packageJson = findPackageJson(currentDir); - if (packageJson) { - log(`Found package.json in: ${currentDir}`); - log(`Package name: ${packageJson.name}`); - if (packageJson.name.startsWith('@graphcommerce/')) { - log(`Found parent @graphcommerce package at: ${currentDir}`); - return currentDir; - } - } - currentDir = node_path_1.default.dirname(currentDir); - } - log('No parent @graphcommerce package found'); - return null; -} diff --git a/packagesDev/next-config/dist/utils/packageRoots.js b/packagesDev/next-config/dist/utils/packageRoots.js deleted file mode 100644 index e4e3addeae..0000000000 --- a/packagesDev/next-config/dist/utils/packageRoots.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.packageRoots = void 0; -const packageRoots = (packagePaths) => { - const pathMap = {}; - // Iterate over each path in the array - packagePaths.forEach((singlePath) => { - const parts = singlePath.split('/'); - // Iterate through each part of the path - for (let i = 1; i < parts.length; i++) { - const subPath = parts.slice(0, i + 1).join('/'); - // Increment the count of this subPath - if (pathMap[subPath]) { - pathMap[subPath].count += 1; - } - else { - pathMap[subPath] = { path: subPath, count: 1 }; - } - } - }); - // Filter the paths that appear more than once - const roots = []; - Object.values(pathMap).forEach(({ path, count }) => { - if (count > 1) { - roots.push(path); - } - }); - // Filter out the sub-paths which are part of another longer sub-path - return roots.filter((root, index, self) => self.findIndex((r) => r !== root && r.startsWith(`${root}/`)) === -1); -}; -exports.packageRoots = packageRoots; diff --git a/packagesDev/next-config/dist/utils/resolveDependenciesSync.js b/packagesDev/next-config/dist/utils/resolveDependenciesSync.js deleted file mode 100644 index cf3615757c..0000000000 --- a/packagesDev/next-config/dist/utils/resolveDependenciesSync.js +++ /dev/null @@ -1,96 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sortDependencies = sortDependencies; -exports.resolveDependenciesSync = resolveDependenciesSync; -const node_fs_1 = __importDefault(require("node:fs")); -const node_path_1 = __importDefault(require("node:path")); -const PackagesSort_1 = require("./PackagesSort"); -const sig_1 = require("./sig"); -const resolveCache = new Map(); -function resolveRecursivePackageJson(dependencyPath, dependencyStructure, root, additionalDependencies = []) { - const isRoot = dependencyPath === root; - const fileName = require.resolve(node_path_1.default.join(dependencyPath, 'package.json')); - const packageJsonFile = node_fs_1.default.readFileSync(fileName, 'utf-8').toString(); - const packageJson = JSON.parse(packageJsonFile); - const e = [atob('QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=')].filter((n) => !globalThis.gcl ? true : !globalThis.gcl.includes(n)); - if (!packageJson.name) - throw Error(`Package ${packageJsonFile} does not have a name field`); - // Previously processed - if (dependencyStructure[packageJson.name]) - return dependencyStructure; - // To have additional namespaces be considered as a graphcommerce package, set PRIVATE_PACKAGE_NAMESPACES - const namespaces = process.env.PRIVATE_PACKAGE_NAMESPACES?.split(',') ?? ['graphcommerce']; - if (!isRoot && !namespaces.some((namespace) => packageJson.name?.includes(namespace))) - return dependencyStructure; - const dependencies = [ - ...new Set([ - ...Object.keys(packageJson.dependencies ?? []), - ...Object.keys(packageJson.devDependencies ?? []), - ...additionalDependencies, - ...Object.keys(packageJson.peerDependencies ?? {}), - ].filter((name) => name.includes('graphcommerce') - ? !(e.length >= 0 && e.some((v) => name.startsWith(v))) - : false)), - ]; - const optionalPeerDependencies = Object.entries(packageJson.peerDependenciesMeta ?? {}) - .filter(([_, v]) => v?.optional) - .map(([key]) => key); - const optionalDependencies = Object.keys(packageJson.optionalDependencies ?? {}); - const optional = new Set([...optionalPeerDependencies, ...optionalDependencies]); - const availableDependencies = dependencies.filter((dep) => { - if (optional.has(dep)) { - try { - resolveRecursivePackageJson(dep, dependencyStructure, root); - return true; - } - catch (resolveError) { - // Dependency is optional, so we don't care if it is not found. - return false; - } - } - else { - resolveRecursivePackageJson(dep, dependencyStructure, root); - return true; - } - }); - const name = isRoot ? '.' : packageJson.name; - dependencyStructure[name] = { - dirName: node_path_1.default.dirname(node_path_1.default.relative(process.cwd(), fileName)), - dependencies: availableDependencies, - }; - return dependencyStructure; -} -/** - * We're sorting all dependencies topologically - * - * This can detect dependency cycles and throw an error - */ -function sortDependencies(dependencyStructure) { - const packages = Object.entries(dependencyStructure); - const sorter = new PackagesSort_1.PackagesSort(new Map(packages.map(([key, value]) => [key, value.dirName]))); - packages.forEach(([key, { dependencies }]) => dependencies.forEach((dependency) => sorter.addEdge(key, dependency))); - const sortedKeys = [...sorter.sort().keys()]; - return new Map(sortedKeys.map((key) => [key, dependencyStructure[key].dirName])); -} -/** - * This will return a list of all dependencies that have `graphcommerce` in the name, matching: - * - * - `@graphcommerce/package-name` - * - `@mycompany/graphcommerce-my-feature` - * - * It will traverse children until it finds a package that doesn't contain graphcommerce in the name - * and stop there, not checking children. - */ -function resolveDependenciesSync(root = process.cwd()) { - const cached = resolveCache.get(root); - if (cached) - return cached; - (0, sig_1.sig)(); - const dependencyStructure = resolveRecursivePackageJson(root, {}, root, process.env.PRIVATE_ADDITIONAL_DEPENDENCIES?.split(',') ?? []); - const sorted = sortDependencies(dependencyStructure); - resolveCache.set(root, sorted); - return sorted; -} diff --git a/packagesDev/next-config/dist/utils/resolveDependency.js b/packagesDev/next-config/dist/utils/resolveDependency.js deleted file mode 100644 index 5c237b3afd..0000000000 --- a/packagesDev/next-config/dist/utils/resolveDependency.js +++ /dev/null @@ -1,70 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveDependency = void 0; -const node_fs_1 = __importDefault(require("node:fs")); -const resolveDependenciesSync_1 = require("./resolveDependenciesSync"); -const resolveDependency = (cwd = process.cwd()) => { - const dependencies = (0, resolveDependenciesSync_1.resolveDependenciesSync)(cwd); - function resolve(dependency, options = {}) { - const { includeSources = false } = options; - let dependencyPaths = { - root: '.', - source: '', - sourcePath: '', - sourcePathRelative: '', - dependency, - fromRoot: dependency, - fromModule: dependency, - denormalized: dependency, - }; - dependencies.forEach((root, depCandidate) => { - if (dependency === depCandidate || dependency.startsWith(`${depCandidate}/`)) { - const relative = dependency.replace(depCandidate, ''); - const rootCandidate = dependency.replace(depCandidate, root); - let source = ''; - let sourcePath = ''; - const fromRoot = [ - `${rootCandidate}`, - `${rootCandidate}/index`, - `${rootCandidate}/src/index`, - ].find((location) => ['ts', 'tsx'].find((extension) => { - const candidatePath = `${location}.${extension}`; - const exists = node_fs_1.default.existsSync(candidatePath); - if (includeSources && exists) { - source = node_fs_1.default.readFileSync(candidatePath, 'utf-8'); - sourcePath = candidatePath; - } - return exists; - })); - if (!fromRoot) { - return; - } - const denormalized = fromRoot.replace(root, depCandidate); - let fromModule = !relative - ? '.' - : `./${relative.split('/')[relative.split('/').length - 1]}`; - const sourcePathRelative = !sourcePath - ? '.' - : `./${sourcePath.split('/')[sourcePath.split('/').length - 1]}`; - if (dependency.startsWith('./')) - fromModule = `.${relative}`; - dependencyPaths = { - root, - dependency, - denormalized, - fromRoot, - fromModule, - source, - sourcePath, - sourcePathRelative, - }; - } - }); - return dependencyPaths; - } - return resolve; -}; -exports.resolveDependency = resolveDependency; diff --git a/packagesDev/next-config/dist/utils/sig.js b/packagesDev/next-config/dist/utils/sig.js deleted file mode 100644 index e296344bd1..0000000000 --- a/packagesDev/next-config/dist/utils/sig.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.g = g; -exports.sig = sig; -// import necessary modules -const crypto_1 = __importDefault(require("crypto")); -// Function to generate a license key based on input data -function g(data) { - const iv = crypto_1.default.randomBytes(16); // Initialization vector - const cipher = crypto_1.default.createCipheriv('aes-256-cbc', 'BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN', iv); - let encrypted = cipher.update(JSON.stringify(data), 'utf-8', 'hex'); - encrypted += cipher.final('hex'); - // Return the IV and the encrypted data as a single string, encoded in base64 - return Buffer.from(`${iv.toString('hex')}:${encrypted}`).toString(); -} -// Function to validate and decode the license key -function sig() { - const l = process.env[atob('R0NfTElDRU5TRQ==')]; - if (!l) - return; - if (!globalThis.gcl) - try { - const decipher = crypto_1.default.createDecipheriv('aes-256-cbc', 'BbcFEkUydGw3nE9ZPm7gbxTIIBQ9IiKN', Buffer.from(l.split(':')[0], 'hex')); - let decrypted = decipher.update(l.split(':')[1], 'hex', 'utf-8'); - decrypted += decipher.final('utf-8'); - globalThis.gcl = JSON.parse(decrypted); // Parse and return the decoded data - } - catch (error) { - // Silent - } -} diff --git a/packagesDev/next-config/dist/withGraphCommerce.js b/packagesDev/next-config/dist/withGraphCommerce.js deleted file mode 100644 index 961cd10df0..0000000000 --- a/packagesDev/next-config/dist/withGraphCommerce.js +++ /dev/null @@ -1,153 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.withGraphCommerce = withGraphCommerce; -// import CircularDependencyPlugin from 'circular-dependency-plugin' -const plugin_1 = require("inspectpack/plugin"); -const webpack_1 = require("webpack"); -const loadConfig_1 = require("./config/loadConfig"); -const configToImportMeta_1 = require("./config/utils/configToImportMeta"); -const InterceptorPlugin_1 = require("./interceptors/InterceptorPlugin"); -const resolveDependenciesSync_1 = require("./utils/resolveDependenciesSync"); -let graphcommerceConfig; -function domains(config) { - return Object.values(config.storefront.reduce((acc, loc) => { - if (!loc.domain) - return acc; - acc[loc.domain] = { - defaultLocale: loc.locale, - locales: [...(acc[loc.domain]?.locales ?? []), loc.locale], - domain: loc.domain, - http: process.env.NODE_ENV === 'development' || undefined, - }; - return acc; - }, {})); -} -/** - * GraphCommerce configuration: . - * - * ```ts - * const { withGraphCommerce } = require('@graphcommerce/next-config') - * - * module.exports = withGraphCommerce(nextConfig) - * ``` - */ -function withGraphCommerce(nextConfig, cwd = process.cwd()) { - graphcommerceConfig ??= (0, loadConfig_1.loadConfig)(cwd); - const importMetaPaths = (0, configToImportMeta_1.configToImportMeta)(graphcommerceConfig); - const { storefront } = graphcommerceConfig; - const transpilePackages = [ - ...[...(0, resolveDependenciesSync_1.resolveDependenciesSync)().keys()].slice(1), - ...(nextConfig.transpilePackages ?? []), - ]; - return { - ...nextConfig, - bundlePagesRouterDependencies: true, - experimental: { - ...nextConfig.experimental, - scrollRestoration: true, - swcPlugins: [...(nextConfig.experimental?.swcPlugins ?? []), ['@lingui/swc-plugin', {}]], - }, - i18n: { - ...nextConfig.i18n, - defaultLocale: storefront.find((locale) => locale.defaultLocale)?.locale ?? storefront[0].locale, - locales: storefront.map((locale) => locale.locale), - domains: [...domains(graphcommerceConfig), ...(nextConfig.i18n?.domains ?? [])], - }, - images: { - ...nextConfig.images, - remotePatterns: [ - 'magentoEndpoint' in graphcommerceConfig - ? { - hostname: new URL(graphcommerceConfig.magentoEndpoint).hostname, - } - : undefined, - { hostname: '**.graphassets.com' }, - { hostname: '*.graphcommerce.org' }, - ...(nextConfig.images?.remotePatterns ?? []), - ].filter((v) => !!v), - }, - rewrites: async () => { - let rewrites = (await nextConfig.rewrites?.()) ?? []; - if (Array.isArray(rewrites)) { - rewrites = { beforeFiles: rewrites, afterFiles: [], fallback: [] }; - } - if ('productRoute' in graphcommerceConfig && - typeof graphcommerceConfig.productRoute === 'string' && - graphcommerceConfig.productRoute !== '/p/') { - rewrites.beforeFiles.push({ - source: `${graphcommerceConfig.productRoute ?? '/p/'}:path*`, - destination: '/p/:path*', - }); - } - return rewrites; - }, - transpilePackages, - webpack: (config, options) => { - if (!config.module) - config.module = { rules: [] }; - config.module = { - ...config.module, - rules: [ - ...(config.module.rules ?? []), - // Allow importing yml/yaml files for graphql-mesh - { test: /\.ya?ml$/, use: 'js-yaml-loader' }, - // @lingui .po file support - { test: /\.po/, use: '@lingui/loader' }, - ], - exprContextCritical: false, - }; - if (!config.plugins) - config.plugins = []; - // Make import.meta.graphCommerce available for usage. - config.plugins.push(new webpack_1.DefinePlugin(importMetaPaths)); - // To properly properly treeshake @apollo/client we need to define the __DEV__ property - config.plugins.push(new webpack_1.DefinePlugin({ 'globalThis.__DEV__': options.dev })); - if (!options.isServer) { - // if (graphcommerceConfig.debug?.webpackCircularDependencyPlugin) { - // config.plugins.push( - // new CircularDependencyPlugin({ - // exclude: /readable-stream|duplexer2|node_modules\/next/, - // }), - // ) - // } - if (graphcommerceConfig.debug?.webpackDuplicatesPlugin) { - config.plugins.push(new plugin_1.DuplicatesPlugin({ - ignoredPackages: [ - // very small - 'react-is', - // build issue - 'tslib', - // server - 'isarray', - 'readable-stream', - ], - })); - } - } - config.snapshot = { - ...(config.snapshot ?? {}), - managedPaths: [ - new RegExp(`^(.+?[\\/]node_modules[\\/])(?!${transpilePackages.join('|')})`), - ], - }; - config.watchOptions = { - ...(config.watchOptions ?? {}), - ignored: new RegExp(`^((?:[^/]*(?:/|$))*)(.(git|next)|(node_modules[\\/](?!${transpilePackages.join('|')})))(/((?:[^/]*(?:/|$))*)(?:$|/))?`), - }; - if (!config.resolve) - config.resolve = {}; - if (!options.isServer && !options.dev) { - config.resolve.alias = { - ...config.resolve.alias, - '@mui/base': '@mui/base/modern', - '@mui/lab': '@mui/lab/modern', - '@mui/material': '@mui/material/modern', - '@mui/styled-engine': '@mui/styled-engine/modern', - '@mui/system': '@mui/system/modern', - }; - } - config.plugins.push(new InterceptorPlugin_1.InterceptorPlugin(graphcommerceConfig, !options.isServer)); - return typeof nextConfig.webpack === 'function' ? nextConfig.webpack(config, options) : config; - }, - }; -} diff --git a/packagesDev/next-config/package.json b/packagesDev/next-config/package.json index b293cbf785..d5e89d9c3d 100644 --- a/packagesDev/next-config/package.json +++ b/packagesDev/next-config/package.json @@ -3,27 +3,37 @@ "homepage": "https://www.graphcommerce.org/", "repository": "github:graphcommerce-org/graphcommerce", "version": "9.0.4-canary.9", - "type": "commonjs", - "main": "dist/index.js", - "types": "src/index.ts", + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./dist/index.js" + }, + "./config": { + "default": "./dist/generated/config.js" + } + }, "scripts": { - "dev": "tsc -W --preserveWatchOutput", - "build": "tsc", - "prepack": "tsc" + "dev": "pkgroll --clean-dist --watch", + "build": "pkgroll --clean-dist", + "prepack": "pkgroll --clean-dist" }, "dependencies": { "@graphql-codegen/cli": "5.0.3", "@swc/core": "1.10.1", "@swc/wasm-web": "^1.10.1", "@types/circular-dependency-plugin": "^5.0.8", + "@types/js-yaml": "^4", "@types/lodash": "^4.17.13", "babel-plugin-macros": "^3.1.0", "chalk": "^4", "circular-dependency-plugin": "^5.2.2", + "cosmiconfig": "^8.3.6", "fast-glob": "^3.3.2", "glob": "^10.4.5", "graphql": "^16.10.0", "inspectpack": "^4.7.1", + "js-yaml": "^4.1.0", "js-yaml-loader": "^1.2.2", "lodash": "^4.17.21", "react": "^18.3.1", @@ -33,10 +43,25 @@ "zod": "^3.24.1" }, "peerDependencies": { + "@graphcommerce/prettier-config-pwa": "^9.0.4-canary.9", "@lingui/loader": "*", "@lingui/macro": "*", "@lingui/react": "*", "dotenv": "^16", - "next": "*" + "next": "*", + "prettier": "^3" + }, + "prettier": "@graphcommerce/prettier-config-pwa", + "eslint": { + "extends": "@graphcommerce/eslint-config-pwa" + }, + "eslintConfig": { + "extends": "@graphcommerce/eslint-config-pwa", + "parserOptions": { + "project": "./tsconfig.json" + } + }, + "devDependencies": { + "pkgroll": "^2.5.1" } } diff --git a/packagesDev/next-config/src/config/commands/generateConfig.ts b/packagesDev/next-config/src/config/commands/generateConfig.ts index 09e3c7bb10..82a019da5c 100644 --- a/packagesDev/next-config/src/config/commands/generateConfig.ts +++ b/packagesDev/next-config/src/config/commands/generateConfig.ts @@ -1,7 +1,9 @@ -import { writeFileSync } from 'fs' +import { readFileSync, writeFileSync } from 'fs' +import prettierConf from '@graphcommerce/prettier-config-pwa' import { generate } from '@graphql-codegen/cli' import { transformFileSync } from '@swc/core' import dotenv from 'dotenv' +import prettier from 'prettier' import { findParentPath } from '../../utils/isMonorepo' import { resolveDependenciesSync } from '../../utils/resolveDependenciesSync' import { resolveDependency } from '../../utils/resolveDependency' @@ -49,10 +51,22 @@ export async function generateConfig() { }, }) + writeFileSync( + targetTs, + await prettier.format(readFileSync(targetTs, 'utf-8'), { + ...prettierConf, + parser: 'typescript', + plugins: prettierConf.plugins?.filter( + (p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'), + ), + }), + ) + const result = transformFileSync(targetTs, { - module: { type: 'commonjs' }, + module: { type: 'nodenext' }, env: { targets: { node: '18' } }, }) + console.log(targetJs) writeFileSync(targetJs, result.code) } diff --git a/packagesDev/next-config/src/config/demoConfig.ts b/packagesDev/next-config/src/config/demoConfig.ts index da3d641f3b..8d0b07021f 100644 --- a/packagesDev/next-config/src/config/demoConfig.ts +++ b/packagesDev/next-config/src/config/demoConfig.ts @@ -1,4 +1,3 @@ -// eslint-disable-next-line import/no-extraneous-dependencies import type { PartialDeep } from 'type-fest' import type { GraphCommerceConfig, GraphCommerceStorefrontConfig } from '../generated/config' diff --git a/packagesDev/next-config/src/config/loadConfig.ts b/packagesDev/next-config/src/config/loadConfig.ts index 79eef29dc2..9f70d17c13 100644 --- a/packagesDev/next-config/src/config/loadConfig.ts +++ b/packagesDev/next-config/src/config/loadConfig.ts @@ -1,5 +1,4 @@ /* eslint-disable no-console */ -// eslint-disable-next-line import/no-extraneous-dependencies import { cosmiconfigSync } from 'cosmiconfig' import type { GraphCommerceConfig } from '../generated/config' import { GraphCommerceConfigSchema } from '../generated/config' diff --git a/packagesDev/next-config/src/config/utils/mergeEnvIntoConfig.ts b/packagesDev/next-config/src/config/utils/mergeEnvIntoConfig.ts index e5872307d2..ee5a44838d 100644 --- a/packagesDev/next-config/src/config/utils/mergeEnvIntoConfig.ts +++ b/packagesDev/next-config/src/config/utils/mergeEnvIntoConfig.ts @@ -1,8 +1,6 @@ -/* eslint-disable import/no-extraneous-dependencies */ import { cloneDeep, mergeDeep } from '@apollo/client/utilities' import chalk from 'chalk' -import { get, set } from 'lodash' -import snakeCase from 'lodash/snakeCase' +import lodash from 'lodash' import type { ZodAny, ZodRawShape, ZodTypeAny } from 'zod' import { z, @@ -19,7 +17,11 @@ import { } from 'zod' import diff from './diff' -const fmt = (s: string) => s.split(/(\d+)/).map(snakeCase).join('') +const fmt = (s: string) => + s + .split(/(\d+)/) + .map((v) => lodash.snakeCase(v)) + .join('') export const toEnvStr = (path: string[]) => ['GC', ...path].map(fmt).join('_').toUpperCase() const dotNotation = (pathParts: string[]) => pathParts @@ -178,14 +180,14 @@ export function mergeEnvIntoConfig( return } - const dotValue = get(newConfig, dotVar) + const dotValue = lodash.get(newConfig, dotVar) const merged = mergeDeep(dotValue, value) const from = diff(merged, dotValue) const to = diff(dotValue, merged) applyResult.push({ envVar, envValue, dotVar, from, to }) - set(newConfig, dotVar, merged) + lodash.set(newConfig, dotVar, merged) }) return [newConfig, applyResult] as const diff --git a/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts b/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts index d26d83b7c6..fa0e1421ec 100644 --- a/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts +++ b/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts @@ -1,4 +1,4 @@ -import cloneDeep from 'lodash/cloneDeep' +import lodash from 'lodash' import type { GraphCommerceConfig } from '../../generated/config' import type { ApplyResult, ZodNode } from './mergeEnvIntoConfig' import { mergeEnvIntoConfig } from './mergeEnvIntoConfig' @@ -8,7 +8,7 @@ export function rewriteLegacyEnv( env: Record, config: Partial = {}, ) { - const clonedEnv: Record = cloneDeep(env) + const clonedEnv: Record = lodash.cloneDeep(env) const applied: ApplyResult = [] function renamedTo(to: string) { diff --git a/packagesDev/next-config/src/generated/config.ts b/packagesDev/next-config/src/generated/config.ts index 11b764f701..eb3672f1a7 100644 --- a/packagesDev/next-config/src/generated/config.ts +++ b/packagesDev/next-config/src/generated/config.ts @@ -1,6 +1,5 @@ /* eslint-disable */ import { z } from 'zod' - export type Maybe = T | null export type InputMaybe = Maybe export type Exact = { [K in keyof T]: T[K] } @@ -55,7 +54,12 @@ export type DatalayerConfig = { * Configuration can be accessed in your project with the `import.meta.graphCommerce` object. * * ```tsx - * import { storefrontAll, storefrontConfig, storefrontConfigDefault, useStorefrontConfig } from '@graphcommerce/next-ui' + * import { + * storefrontAll, + * storefrontConfig, + * storefrontConfigDefault, + * useStorefrontConfig, + * } from '@graphcommerce/next-ui' * * // Accessing a global value * const globalConf = import.meta.graphCommerce.cartDisplayPricesInclTax @@ -69,7 +73,8 @@ export type DatalayerConfig = { * * // Or as single line * const scopedConfigWithFallback2 = - * useStorefrontConfig().cartDisplayPricesInclTax ?? import.meta.graphCommerce.cartDisplayPricesInclTax + * useStorefrontConfig().cartDisplayPricesInclTax ?? + * import.meta.graphCommerce.cartDisplayPricesInclTax * * return
{googleRecaptchaKey}
* } @@ -259,7 +264,9 @@ export type GraphCommerceConfig = { */ graphqlMeshEditMode?: InputMaybe /** - * The HyGraph endpoint.> Read-only endpoint that allows low latency and high read-throughput content delivery. + * The HyGraph endpoint. + * + * > Read-only endpoint that allows low latency and high read-throughput content delivery. * * Project settings -> API Access -> High Performance Read-only Content API */ diff --git a/packagesDev/next-config/src/interceptors/generateInterceptor.ts b/packagesDev/next-config/src/interceptors/generateInterceptor.ts index 2b0ff59cfc..2fdfae5de5 100644 --- a/packagesDev/next-config/src/interceptors/generateInterceptor.ts +++ b/packagesDev/next-config/src/interceptors/generateInterceptor.ts @@ -1,6 +1,4 @@ -// eslint-disable-next-line import/no-extraneous-dependencies import prettierConf from '@graphcommerce/prettier-config-pwa' -// eslint-disable-next-line import/no-extraneous-dependencies import prettier from 'prettier' import type { GraphCommerceDebugConfig } from '../generated/config' import type { ResolveDependencyReturn } from '../utils/resolveDependency' diff --git a/packagesDev/next-config/src/interceptors/parseStructure.ts b/packagesDev/next-config/src/interceptors/parseStructure.ts index f6e32beffb..05002b5cc6 100644 --- a/packagesDev/next-config/src/interceptors/parseStructure.ts +++ b/packagesDev/next-config/src/interceptors/parseStructure.ts @@ -1,5 +1,5 @@ import type { Module } from '@swc/core' -import get from 'lodash/get' +import lodash from 'lodash' import { z } from 'zod' import type { GraphCommerceConfig } from '../generated/config' import { extractExports } from './extractExports' @@ -66,12 +66,12 @@ export function parseStructure(ast: Module, gcConfig: GraphCommerceConfig, sourc if (parsed.data.ifConfig) { if (Array.isArray(parsed.data.ifConfig)) { const isBoolean = typeof parsed.data.ifConfig[1] === 'boolean' - let confValue = get(gcConfig, parsed.data.ifConfig[0]) + let confValue = lodash.get(gcConfig, parsed.data.ifConfig[0]) confValue = isBoolean ? Boolean(confValue) : confValue enabled = confValue === parsed.data.ifConfig[1] } else { - enabled = Boolean(get(gcConfig, parsed.data.ifConfig)) + enabled = Boolean(lodash.get(gcConfig, parsed.data.ifConfig)) } } diff --git a/packagesDev/next-config/src/utils/resolveDependenciesSync.ts b/packagesDev/next-config/src/utils/resolveDependenciesSync.ts index bd68a1e000..e2e9fb5dbe 100644 --- a/packagesDev/next-config/src/utils/resolveDependenciesSync.ts +++ b/packagesDev/next-config/src/utils/resolveDependenciesSync.ts @@ -9,6 +9,17 @@ type DependencyStructure = Record = new Map() +function findPackageJson(id: string, root: string) { + let dir = id.startsWith('/') ? id : require.resolve(id) + let packageJsonLocation = path.join(dir, 'package.json') + while (!fs.existsSync(packageJsonLocation)) { + dir = path.dirname(dir) + if (dir === root) throw Error(`Can't find package.json for ${id}`) + packageJsonLocation = path.join(dir, 'package.json') + } + return packageJsonLocation +} + function resolveRecursivePackageJson( dependencyPath: string, dependencyStructure: DependencyStructure, @@ -17,7 +28,14 @@ function resolveRecursivePackageJson( ) { const isRoot = dependencyPath === root - const fileName = require.resolve(path.join(dependencyPath, 'package.json')) + let fileName: string + try { + fileName = require.resolve(path.join(dependencyPath, 'package.json')) + } catch (e) { + fileName = findPackageJson(dependencyPath, root) + } + if (!fileName) throw Error(`Can't find package.json for ${dependencyPath}`) + const packageJsonFile = fs.readFileSync(fileName, 'utf-8').toString() const packageJson = JSON.parse(packageJsonFile) as PackageJson const e = [atob('QGdyYXBoY29tbWVyY2UvYWRvYmUtY29tbWVyY2U=')].filter((n) => diff --git a/packagesDev/next-config/src/withGraphCommerce.ts b/packagesDev/next-config/src/withGraphCommerce.ts index 07b1e31eb8..f0d2b7c47c 100644 --- a/packagesDev/next-config/src/withGraphCommerce.ts +++ b/packagesDev/next-config/src/withGraphCommerce.ts @@ -1,9 +1,9 @@ // import CircularDependencyPlugin from 'circular-dependency-plugin' -import { DuplicatesPlugin } from 'inspectpack/plugin' +// import { DuplicatesPlugin } from 'inspectpack/plugin' import type { NextConfig } from 'next' import type { DomainLocale } from 'next/dist/server/config' import type { Configuration } from 'webpack' -import { DefinePlugin } from 'webpack' +import webpack from 'webpack' import { loadConfig } from './config/loadConfig' import { configToImportMeta } from './config/utils/configToImportMeta' import type { GraphCommerceConfig } from './generated/config' @@ -119,10 +119,10 @@ export function withGraphCommerce(nextConfig: NextConfig, cwd: string = process. if (!config.plugins) config.plugins = [] // Make import.meta.graphCommerce available for usage. - config.plugins.push(new DefinePlugin(importMetaPaths)) + config.plugins.push(new webpack.DefinePlugin(importMetaPaths)) // To properly properly treeshake @apollo/client we need to define the __DEV__ property - config.plugins.push(new DefinePlugin({ 'globalThis.__DEV__': options.dev })) + config.plugins.push(new webpack.DefinePlugin({ 'globalThis.__DEV__': options.dev })) if (!options.isServer) { // if (graphcommerceConfig.debug?.webpackCircularDependencyPlugin) { @@ -132,21 +132,21 @@ export function withGraphCommerce(nextConfig: NextConfig, cwd: string = process. // }), // ) // } - if (graphcommerceConfig.debug?.webpackDuplicatesPlugin) { - config.plugins.push( - new DuplicatesPlugin({ - ignoredPackages: [ - // very small - 'react-is', - // build issue - 'tslib', - // server - 'isarray', - 'readable-stream', - ], - }), - ) - } + // if (graphcommerceConfig.debug?.webpackDuplicatesPlugin) { + // config.plugins.push( + // new DuplicatesPlugin({ + // ignoredPackages: [ + // // very small + // 'react-is', + // // build issue + // 'tslib', + // // server + // 'isarray', + // 'readable-stream', + // ], + // }), + // ) + // } } config.snapshot = { diff --git a/packagesDev/next-config/tsconfig.json b/packagesDev/next-config/tsconfig.json index 70df72da77..07f275149d 100644 --- a/packagesDev/next-config/tsconfig.json +++ b/packagesDev/next-config/tsconfig.json @@ -1,6 +1,6 @@ { "exclude": ["**/node_modules", "example", "dist", "**/.*/", "__tests__", "__mocks__"], - "include": ["**/*.ts", "**/*.tsx"], + "include": ["src/index.ts"], "extends": "@graphcommerce/typescript-config-pwa/node.json", "compilerOptions": { "rootDir": "src", From af04d45d51bdb1b7f0221a96dc0867234a581cc8 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 12:58:35 +0100 Subject: [PATCH 06/16] Added missing WebWorker tsconfig for magento-open-source example --- .changeset/shaggy-ligers-obey.md | 5 +++++ examples/magento-open-source/tsconfig.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) create mode 100644 .changeset/shaggy-ligers-obey.md diff --git a/.changeset/shaggy-ligers-obey.md b/.changeset/shaggy-ligers-obey.md new file mode 100644 index 0000000000..badf6fc3ed --- /dev/null +++ b/.changeset/shaggy-ligers-obey.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/misc': patch +--- + +Added missing WebWorker tsconfig for magento-open-source example diff --git a/examples/magento-open-source/tsconfig.json b/examples/magento-open-source/tsconfig.json index e63a246507..d386dfdb07 100644 --- a/examples/magento-open-source/tsconfig.json +++ b/examples/magento-open-source/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "target": "ESNext", - "lib": ["DOM", "DOM.Iterable", "ESNext"], + "lib": ["DOM", "DOM.Iterable", "ESNext", "WebWorker"], "allowJs": true, "skipLibCheck": true, "strict": true, From f6c26bf12e82ebcd8f794a659dd582eed8809508 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:04:55 +0100 Subject: [PATCH 07/16] Updated generated config, do not disable eslint for the file, as that is not necessary anymore. --- .../next-config/dist/generated/config.js | 254 ++++++++++-------- packagesDev/next-config/dist/index.js | 4 +- .../src/config/commands/generateConfig.ts | 4 +- .../next-config/src/generated/config.ts | 1 - 4 files changed, 138 insertions(+), 125 deletions(-) diff --git a/packagesDev/next-config/dist/generated/config.js b/packagesDev/next-config/dist/generated/config.js index 339e3717d6..fe8802be32 100755 --- a/packagesDev/next-config/dist/generated/config.js +++ b/packagesDev/next-config/dist/generated/config.js @@ -1,129 +1,147 @@ import { z } from 'zod'; - -const isDefinedNonNullAny = (v) => v !== undefined && v !== null; -const definedNonNullAnySchema = z.any().refine((v) => isDefinedNonNullAny(v)); -const CartPermissionsSchema = z.enum(["CUSTOMER_ONLY", "DISABLED", "ENABLED"]); -const CompareVariantSchema = z.enum(["CHECKBOX", "ICON"]); -const ContainerSizingSchema = z.enum(["BREAKPOINT", "FULL_WIDTH"]); -const CustomerAccountPermissionsSchema = z.enum([ - "DISABLED", - "DISABLE_REGISTRATION", - "ENABLED" +export const isDefinedNonNullAny = (v)=>v !== undefined && v !== null; +export const definedNonNullAnySchema = z.any().refine((v)=>isDefinedNonNullAny(v)); +export const CartPermissionsSchema = z.enum([ + 'CUSTOMER_ONLY', + 'DISABLED', + 'ENABLED' ]); -const PaginationVariantSchema = z.enum(["COMPACT", "EXTENDED"]); -const ProductFiltersLayoutSchema = z.enum(["DEFAULT", "SIDEBAR"]); -const SidebarGalleryPaginationVariantSchema = z.enum(["DOTS", "THUMBNAILS_BOTTOM"]); -const WebsitePermissionsSchema = z.enum(["ENABLED"]); -function DatalayerConfigSchema() { - return z.object({ - coreWebVitals: z.boolean().nullish() - }); +export const CompareVariantSchema = z.enum([ + 'CHECKBOX', + 'ICON' +]); +export const ContainerSizingSchema = z.enum([ + 'BREAKPOINT', + 'FULL_WIDTH' +]); +export const CustomerAccountPermissionsSchema = z.enum([ + 'DISABLED', + 'DISABLE_REGISTRATION', + 'ENABLED' +]); +export const PaginationVariantSchema = z.enum([ + 'COMPACT', + 'EXTENDED' +]); +export const ProductFiltersLayoutSchema = z.enum([ + 'DEFAULT', + 'SIDEBAR' +]); +export const SidebarGalleryPaginationVariantSchema = z.enum([ + 'DOTS', + 'THUMBNAILS_BOTTOM' +]); +export const WebsitePermissionsSchema = z.enum([ + 'ENABLED' +]); +export function DatalayerConfigSchema() { + return z.object({ + coreWebVitals: z.boolean().nullish() + }); } -function GraphCommerceConfigSchema() { - return z.object({ - breadcrumbs: z.boolean().default(false).nullish(), - canonicalBaseUrl: z.string().min(1), - cartDisplayPricesInclTax: z.boolean().nullish(), - compare: z.boolean().nullish(), - compareVariant: CompareVariantSchema.default("ICON").nullish(), - configurableVariantForSimple: z.boolean().default(false).nullish(), - configurableVariantValues: MagentoConfigurableVariantValuesSchema().nullish(), - containerSizingContent: ContainerSizingSchema.default("FULL_WIDTH").nullish(), - containerSizingShell: ContainerSizingSchema.default("FULL_WIDTH").nullish(), - crossSellsHideCartItems: z.boolean().default(false).nullish(), - crossSellsRedirectItems: z.boolean().default(false).nullish(), - customerAddressNoteEnable: z.boolean().nullish(), - customerCompanyFieldsEnable: z.boolean().nullish(), - customerDeleteEnabled: z.boolean().nullish(), - customerXMagentoCacheIdDisable: z.boolean().nullish(), - dataLayer: DatalayerConfigSchema().nullish(), - debug: GraphCommerceDebugConfigSchema().nullish(), - demoMode: z.boolean().default(true).nullish(), - enableGuestCheckoutLogin: z.boolean().nullish(), - googleAnalyticsId: z.string().nullish(), - googlePlaystore: GraphCommerceGooglePlaystoreConfigSchema().nullish(), - googleRecaptchaKey: z.string().nullish(), - googleTagmanagerId: z.string().nullish(), - graphqlMeshEditMode: z.boolean().default(false).nullish(), - hygraphEndpoint: z.string().min(1), - hygraphManagementApi: z.string().nullish(), - hygraphProjectId: z.string().nullish(), - hygraphWriteAccessToken: z.string().nullish(), - limitSsg: z.boolean().nullish(), - magentoEndpoint: z.string().min(1), - magentoVersion: z.number(), - permissions: GraphCommercePermissionsSchema().nullish(), - previewSecret: z.string().nullish(), - productFiltersLayout: ProductFiltersLayoutSchema.default("DEFAULT").nullish(), - productFiltersPro: z.boolean().nullish(), - productListPaginationVariant: PaginationVariantSchema.default("COMPACT").nullish(), - productRoute: z.string().nullish(), - recentlyViewedProducts: RecentlyViewedProductsConfigSchema().nullish(), - robotsAllow: z.boolean().nullish(), - sidebarGallery: SidebarGalleryConfigSchema().nullish(), - storefront: z.array(GraphCommerceStorefrontConfigSchema()), - wishlistHideForGuests: z.boolean().nullish(), - wishlistShowFeedbackMessage: z.boolean().nullish() - }); +export function GraphCommerceConfigSchema() { + return z.object({ + breadcrumbs: z.boolean().default(false).nullish(), + canonicalBaseUrl: z.string().min(1), + cartDisplayPricesInclTax: z.boolean().nullish(), + compare: z.boolean().nullish(), + compareVariant: CompareVariantSchema.default('ICON').nullish(), + configurableVariantForSimple: z.boolean().default(false).nullish(), + configurableVariantValues: MagentoConfigurableVariantValuesSchema().nullish(), + containerSizingContent: ContainerSizingSchema.default('FULL_WIDTH').nullish(), + containerSizingShell: ContainerSizingSchema.default('FULL_WIDTH').nullish(), + crossSellsHideCartItems: z.boolean().default(false).nullish(), + crossSellsRedirectItems: z.boolean().default(false).nullish(), + customerAddressNoteEnable: z.boolean().nullish(), + customerCompanyFieldsEnable: z.boolean().nullish(), + customerDeleteEnabled: z.boolean().nullish(), + customerXMagentoCacheIdDisable: z.boolean().nullish(), + dataLayer: DatalayerConfigSchema().nullish(), + debug: GraphCommerceDebugConfigSchema().nullish(), + demoMode: z.boolean().default(true).nullish(), + enableGuestCheckoutLogin: z.boolean().nullish(), + googleAnalyticsId: z.string().nullish(), + googlePlaystore: GraphCommerceGooglePlaystoreConfigSchema().nullish(), + googleRecaptchaKey: z.string().nullish(), + googleTagmanagerId: z.string().nullish(), + graphqlMeshEditMode: z.boolean().default(false).nullish(), + hygraphEndpoint: z.string().min(1), + hygraphManagementApi: z.string().nullish(), + hygraphProjectId: z.string().nullish(), + hygraphWriteAccessToken: z.string().nullish(), + limitSsg: z.boolean().nullish(), + magentoEndpoint: z.string().min(1), + magentoVersion: z.number(), + permissions: GraphCommercePermissionsSchema().nullish(), + previewSecret: z.string().nullish(), + productFiltersLayout: ProductFiltersLayoutSchema.default('DEFAULT').nullish(), + productFiltersPro: z.boolean().nullish(), + productListPaginationVariant: PaginationVariantSchema.default('COMPACT').nullish(), + productRoute: z.string().nullish(), + recentlyViewedProducts: RecentlyViewedProductsConfigSchema().nullish(), + robotsAllow: z.boolean().nullish(), + sidebarGallery: SidebarGalleryConfigSchema().nullish(), + storefront: z.array(GraphCommerceStorefrontConfigSchema()), + wishlistHideForGuests: z.boolean().nullish(), + wishlistShowFeedbackMessage: z.boolean().nullish() + }); } -function GraphCommerceDebugConfigSchema() { - return z.object({ - cart: z.boolean().nullish(), - pluginStatus: z.boolean().nullish(), - sessions: z.boolean().nullish(), - webpackCircularDependencyPlugin: z.boolean().nullish(), - webpackDuplicatesPlugin: z.boolean().nullish() - }); +export function GraphCommerceDebugConfigSchema() { + return z.object({ + cart: z.boolean().nullish(), + pluginStatus: z.boolean().nullish(), + sessions: z.boolean().nullish(), + webpackCircularDependencyPlugin: z.boolean().nullish(), + webpackDuplicatesPlugin: z.boolean().nullish() + }); } -function GraphCommerceGooglePlaystoreConfigSchema() { - return z.object({ - packageName: z.string().min(1), - sha256CertificateFingerprint: z.string().min(1) - }); +export function GraphCommerceGooglePlaystoreConfigSchema() { + return z.object({ + packageName: z.string().min(1), + sha256CertificateFingerprint: z.string().min(1) + }); } -function GraphCommercePermissionsSchema() { - return z.object({ - cart: CartPermissionsSchema.nullish(), - checkout: CartPermissionsSchema.nullish(), - customerAccount: CustomerAccountPermissionsSchema.nullish(), - website: WebsitePermissionsSchema.nullish() - }); +export function GraphCommercePermissionsSchema() { + return z.object({ + cart: CartPermissionsSchema.nullish(), + checkout: CartPermissionsSchema.nullish(), + customerAccount: CustomerAccountPermissionsSchema.nullish(), + website: WebsitePermissionsSchema.nullish() + }); } -function GraphCommerceStorefrontConfigSchema() { - return z.object({ - canonicalBaseUrl: z.string().nullish(), - cartDisplayPricesInclTax: z.boolean().nullish(), - customerCompanyFieldsEnable: z.boolean().nullish(), - defaultLocale: z.boolean().nullish(), - domain: z.string().nullish(), - googleAnalyticsId: z.string().nullish(), - googleRecaptchaKey: z.string().nullish(), - googleTagmanagerId: z.string().nullish(), - hygraphLocales: z.array(z.string().min(1)).nullish(), - linguiLocale: z.string().nullish(), - locale: z.string().min(1), - magentoStoreCode: z.string().min(1), - permissions: GraphCommercePermissionsSchema().nullish(), - robotsAllow: z.boolean().nullish() - }); +export function GraphCommerceStorefrontConfigSchema() { + return z.object({ + canonicalBaseUrl: z.string().nullish(), + cartDisplayPricesInclTax: z.boolean().nullish(), + customerCompanyFieldsEnable: z.boolean().nullish(), + defaultLocale: z.boolean().nullish(), + domain: z.string().nullish(), + googleAnalyticsId: z.string().nullish(), + googleRecaptchaKey: z.string().nullish(), + googleTagmanagerId: z.string().nullish(), + hygraphLocales: z.array(z.string().min(1)).nullish(), + linguiLocale: z.string().nullish(), + locale: z.string().min(1), + magentoStoreCode: z.string().min(1), + permissions: GraphCommercePermissionsSchema().nullish(), + robotsAllow: z.boolean().nullish() + }); } -function MagentoConfigurableVariantValuesSchema() { - return z.object({ - content: z.boolean().nullish(), - gallery: z.boolean().nullish(), - url: z.boolean().nullish() - }); +export function MagentoConfigurableVariantValuesSchema() { + return z.object({ + content: z.boolean().nullish(), + gallery: z.boolean().nullish(), + url: z.boolean().nullish() + }); } -function RecentlyViewedProductsConfigSchema() { - return z.object({ - enabled: z.boolean().nullish(), - maxCount: z.number().nullish() - }); +export function RecentlyViewedProductsConfigSchema() { + return z.object({ + enabled: z.boolean().nullish(), + maxCount: z.number().nullish() + }); } -function SidebarGalleryConfigSchema() { - return z.object({ - paginationVariant: SidebarGalleryPaginationVariantSchema.nullish() - }); +export function SidebarGalleryConfigSchema() { + return z.object({ + paginationVariant: SidebarGalleryPaginationVariantSchema.nullish() + }); } - -export { CartPermissionsSchema, CompareVariantSchema, ContainerSizingSchema, CustomerAccountPermissionsSchema, DatalayerConfigSchema, GraphCommerceConfigSchema, GraphCommerceDebugConfigSchema, GraphCommerceGooglePlaystoreConfigSchema, GraphCommercePermissionsSchema, GraphCommerceStorefrontConfigSchema, MagentoConfigurableVariantValuesSchema, PaginationVariantSchema, ProductFiltersLayoutSchema, RecentlyViewedProductsConfigSchema, SidebarGalleryConfigSchema, SidebarGalleryPaginationVariantSchema, WebsitePermissionsSchema, definedNonNullAnySchema, isDefinedNonNullAny }; diff --git a/packagesDev/next-config/dist/index.js b/packagesDev/next-config/dist/index.js index 6d7b04c52c..9442f70163 100755 --- a/packagesDev/next-config/dist/index.js +++ b/packagesDev/next-config/dist/index.js @@ -3110,10 +3110,9 @@ async function generateConfig() { schema: ["graphql/**/Config.graphqls", ...schemaLocations], generates: { [targetTs]: { - plugins: ["typescript", "typescript-validation-schema", "add"], + plugins: ["typescript", "typescript-validation-schema"], config: { // enumsAsTypes: true, - content: "/* eslint-disable */", schema: "zod", notAllowEmptyString: true, strictScalars: true, @@ -3146,7 +3145,6 @@ async function generateConfig() { module: { type: "nodenext" }, env: { targets: { node: "18" } } }); - console.log(targetJs); writeFileSync(targetJs, result.code); } diff --git a/packagesDev/next-config/src/config/commands/generateConfig.ts b/packagesDev/next-config/src/config/commands/generateConfig.ts index 82a019da5c..77cc430b3b 100644 --- a/packagesDev/next-config/src/config/commands/generateConfig.ts +++ b/packagesDev/next-config/src/config/commands/generateConfig.ts @@ -28,10 +28,9 @@ export async function generateConfig() { schema: ['graphql/**/Config.graphqls', ...schemaLocations], generates: { [targetTs]: { - plugins: ['typescript', 'typescript-validation-schema', 'add'], + plugins: ['typescript', 'typescript-validation-schema'], config: { // enumsAsTypes: true, - content: '/* eslint-disable */', schema: 'zod', notAllowEmptyString: true, strictScalars: true, @@ -66,7 +65,6 @@ export async function generateConfig() { module: { type: 'nodenext' }, env: { targets: { node: '18' } }, }) - console.log(targetJs) writeFileSync(targetJs, result.code) } diff --git a/packagesDev/next-config/src/generated/config.ts b/packagesDev/next-config/src/generated/config.ts index eb3672f1a7..655f56e230 100644 --- a/packagesDev/next-config/src/generated/config.ts +++ b/packagesDev/next-config/src/generated/config.ts @@ -1,4 +1,3 @@ -/* eslint-disable */ import { z } from 'zod' export type Maybe = T | null export type InputMaybe = Maybe From c25bb105c6bf0a043dde734be41f350cfbe3ebdb Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:06:17 +0100 Subject: [PATCH 08/16] Migrated `@graphcommerce/hygraph-cli` package to `"type": "module"` --- .changeset/serious-glasses-call.md | 5 + packages/hygraph-cli/dist/UpsertClient.js | 80 -- packages/hygraph-cli/dist/index.js | 933 +++++++++++++++++- .../hygraph-cli/dist/migrateHygraphCli.js | 88 -- .../dist/migrationActionFactory.js | 133 --- .../dist/migrations/graphcommerce5to6.js | 98 -- .../dist/migrations/graphcommerce6to7.js | 206 ---- .../dist/migrations/graphcommerce7to8.js | 41 - .../dist/migrations/graphcommerce8to9.js | 68 -- packages/hygraph-cli/dist/migrations/index.js | 13 - packages/hygraph-cli/dist/readSchema.js | 50 - packages/hygraph-cli/dist/types.js | 2 - packages/hygraph-cli/dist/utils/getConfig.js | 19 - .../hygraph-cli/dist/utils/getEndpointUrl.js | 43 - .../dist/utils/getManagementClient.js | 15 - .../dist/utils/graphCommerceLog.js | 15 - packages/hygraph-cli/package.json | 19 +- packages/hygraph-cli/tsconfig.json | 4 +- 18 files changed, 947 insertions(+), 885 deletions(-) create mode 100644 .changeset/serious-glasses-call.md delete mode 100644 packages/hygraph-cli/dist/UpsertClient.js mode change 100644 => 100755 packages/hygraph-cli/dist/index.js delete mode 100644 packages/hygraph-cli/dist/migrateHygraphCli.js delete mode 100644 packages/hygraph-cli/dist/migrationActionFactory.js delete mode 100644 packages/hygraph-cli/dist/migrations/graphcommerce5to6.js delete mode 100644 packages/hygraph-cli/dist/migrations/graphcommerce6to7.js delete mode 100644 packages/hygraph-cli/dist/migrations/graphcommerce7to8.js delete mode 100644 packages/hygraph-cli/dist/migrations/graphcommerce8to9.js delete mode 100644 packages/hygraph-cli/dist/migrations/index.js delete mode 100644 packages/hygraph-cli/dist/readSchema.js delete mode 100644 packages/hygraph-cli/dist/types.js delete mode 100644 packages/hygraph-cli/dist/utils/getConfig.js delete mode 100644 packages/hygraph-cli/dist/utils/getEndpointUrl.js delete mode 100644 packages/hygraph-cli/dist/utils/getManagementClient.js delete mode 100644 packages/hygraph-cli/dist/utils/graphCommerceLog.js diff --git a/.changeset/serious-glasses-call.md b/.changeset/serious-glasses-call.md new file mode 100644 index 0000000000..5670d82fdf --- /dev/null +++ b/.changeset/serious-glasses-call.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/hygraph-cli': patch +--- + +Migrated `@graphcommerce/hygraph-cli` package to `"type": "module"` diff --git a/packages/hygraph-cli/dist/UpsertClient.js b/packages/hygraph-cli/dist/UpsertClient.js deleted file mode 100644 index 7d6b4f199c..0000000000 --- a/packages/hygraph-cli/dist/UpsertClient.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UpsertClient = void 0; -const management_sdk_1 = require("@hygraph/management-sdk"); -class UpsertClient extends management_sdk_1.Client { - schema; - constructor(params, schema) { - super(params); - this.schema = schema; - } - /** @public */ - upsertModel(data) { - const exists = this.schema.models.some((m) => m.apiId === data.apiId); - return exists ? this.createModel(data) : this.updateModel(data); - } - /** @public */ - upsertComponent(data) { - const exists = this.schema.models.some((m) => m.apiId === data.apiId); - return exists ? this.createComponent(data) : this.updateComponent(data); - } - /** @public */ - upsertSimpleField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists - ? this.createSimpleField(data) - : this.updateSimpleField({ ...data, embeddableModels: undefined }); - } - // upsertRemoteField(data: BatchMigrationCreateRemoteFieldInput) { - // const model = this.schema.models.find((m) => m.apiId === data.parentApiId) - // const exists = model?.fields.some((f) => f.apiId === data.apiId) - // return exists ? this.createRemoteField(data) : this.updateRemoteField(data) - // } - /** @public */ - upsertRelationalField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists ? this.createRelationalField(data) : this.updateRelationalField(data); - } - /** @public */ - upsertUnionField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists ? this.createUnionField(data) : this.updateUnionField(data); - } - /** @public */ - upsertComponentField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists ? this.createComponentField(data) : this.updateComponentField(data); - } - /** @public */ - upsertComponentUnionField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists ? this.createComponentUnionField(data) : this.updateComponentUnionField(data); - } - /** @public */ - upsertEnumeration(data) { - const exists = this.schema.enumerations.some((e) => e.apiId === data.apiId); - return exists ? this.createEnumeration(data) : this.updateEnumeration(data); - } - /** @public */ - upsertEnumerableField(data) { - const model = this.schema.models.find((m) => m.apiId === data.parentApiId); - const exists = model?.fields.some((f) => f.apiId === data.apiId); - return exists ? this.createEnumerableField(data) : this.updateEnumerableField(data); - } - /** @public */ - upsertStage(data) { - const exists = this.schema.stages.some((m) => m.apiId === data.apiId); - return exists ? this.createStage(data) : this.updateStage(data); - } - /** @public */ - upsertLocale(data) { - const exists = this.schema.locales.some((m) => m.apiId === data.apiId); - return exists ? this.createLocale(data) : this.updateLocale(data); - } -} -exports.UpsertClient = UpsertClient; diff --git a/packages/hygraph-cli/dist/index.js b/packages/hygraph-cli/dist/index.js old mode 100644 new mode 100755 index de1737db50..5dddeea33d --- a/packages/hygraph-cli/dist/index.js +++ b/packages/hygraph-cli/dist/index.js @@ -1,5 +1,928 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.migrateHygraph = void 0; -var migrateHygraphCli_1 = require("./migrateHygraphCli"); -Object.defineProperty(exports, "migrateHygraph", { enumerable: true, get: function () { return migrateHygraphCli_1.migrateHygraphCli; } }); +import fs from 'fs'; +import { loadConfig } from '@graphcommerce/next-config'; +import dotenv from 'dotenv'; +import prompts from 'prompts'; +import { SimpleFieldType, RelationalFieldType, VisibilityTypes, Client } from '@hygraph/management-sdk'; +import { gql, ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'; +import gql$1 from 'graphql-tag'; + +const capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); +const graphcommerceLog = (message, type) => { + const color = { + error: "\x1B[31m\x1B[1m%s\x1B[0m", + warning: "\x1B[33m\x1B[1m%s\x1B[0m", + info: "\x1B[36m\x1B[1m%s\x1B[0m" + }; + console.log(type ? color[type] : "", `${message}`); +}; + +dotenv.config(); +function migrationActionFactory(schema, client) { + const actionMap = client ? { + create: { + model: (innerprops) => client.createModel(innerprops), + component: (innerprops) => client.createComponent(innerprops), + enumeration: (innerprops) => client.createEnumeration(innerprops), + simpleField: (innerprops) => client.createSimpleField(innerprops), + enumerableField: (innerprops) => client.createEnumerableField(innerprops), + componentField: (innerprops) => client.createComponentField(innerprops), + relationalField: (innerprops) => client.createRelationalField(innerprops), + unionField: (innerprops) => client.createUnionField(innerprops), + componentUnionField: (innerprops) => client.createComponentUnionField(innerprops) + }, + update: { + model: (innerprops) => client.updateModel(innerprops), + component: (innerprops) => client.updateComponent(innerprops), + enumeration: (innerprops) => client.updateEnumeration(innerprops), + simpleField: (innerprops) => client.updateSimpleField(innerprops), + enumerableField: (innerprops) => client.updateEnumerableField(innerprops), + componentField: (innerprops) => client.updateComponentField(innerprops), + relationalField: (innerprops) => client.updateRelationalField(innerprops), + unionField: (innerprops) => client.updateUnionField(innerprops), + componentUnionField: (innerprops) => client.updateComponentUnionField(innerprops) + }, + delete: { + model: (innerprops) => client.deleteModel(innerprops), + component: (innerprops) => client.deleteComponent(innerprops), + enumeration: (innerprops) => client.deleteEnumeration(innerprops), + simpleField: (innerprops) => client.deleteField(innerprops), + enumerableField: (innerprops) => client.deleteField(innerprops), + componentField: (innerprops) => client.deleteField(innerprops), + relationalField: (innerprops) => client.deleteField(innerprops), + unionField: (innerprops) => client.deleteField(innerprops), + componentUnionField: (innerprops) => client.deleteField(innerprops) + } + } : undefined; + const migrationAction = (_schema, type, action, props, parentApiId, parentType) => { + const alreadyExists = () => { + if (action !== "create") { + return false; + } + switch (type) { + case "model": + return schema.models.some((model) => model.apiId === props.apiId); + case "component": + return schema.components.some((component) => component.apiId === props.apiId); + case "enumeration": + return schema.enumerations.some((enumeration) => enumeration.apiId === props.apiId); + case "simpleField": + case "enumerableField": + case "relationalField": + case "unionField": + case "componentUnionField": { + let parent; + switch (parentType) { + case "model": { + parent = schema.models.find((model) => model.apiId === parentApiId); + break; + } + case "component": { + parent = schema.components.find((component) => component.apiId === parentApiId); + break; + } + default: + return false; + } + return parent?.fields.some((field) => field.apiId === props.apiId); + } + default: { + return false; + } + } + }; + const actionFunc = actionMap && actionMap[action] && actionMap[action][type]; + if (!alreadyExists()) { + if (actionFunc) { + graphcommerceLog(`${capitalize(action)} ${type} with apiId ${props.apiId}...`); + actionFunc(props); + } else { + graphcommerceLog(`Action ${action} is not supported for ${type}`, "error"); + } + } else { + graphcommerceLog( + `${capitalize(type)} with apiId ${props.apiId} on ${parentApiId} already exists`, + "warning" + ); + } + }; + return { + migrationAction + }; +} + +const graphcommerce5to6 = async (schema, client) => { + const { migrationAction } = migrationActionFactory(schema, client); + migrationAction(schema, "enumeration", "create", { + displayName: "Row Links Variants", + apiId: "RowLinksVariants", + values: [ + { displayName: "Inline", apiId: "Inline" }, + { displayName: "Image Label Swiper", apiId: "ImageLabelSwiper" }, + { displayName: "Logo Swiper", apiId: "LogoSwiper" }, + { displayName: "USPS", apiId: "Usps" } + ] + }); + migrationAction(schema, "model", "create", { + apiId: "RowLinks", + apiIdPlural: "RowLinksMultiple", + displayName: "Row Links", + description: "Row Links is a Row of PageLinks with different variants" + }); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Identity", + apiId: "identity", + description: "Only used for internal reference", + type: SimpleFieldType.String, + isTitle: true, + isRequired: true, + isUnique: true, + modelApiId: "RowLinks" + }, + "RowLinks", + "model" + ); + migrationAction( + schema, + "enumerableField", + "create", + { + displayName: "Variant", + apiId: "linksVariant", + parentApiId: "RowLinks", + enumerationApiId: "RowLinksVariants", + description: "Different variants for Row Links" + }, + "RowLinks", + "model" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Title", + apiId: "title", + type: SimpleFieldType.String, + isRequired: true, + modelApiId: "RowLinks", + isLocalized: true + }, + "RowLinks", + "model" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Copy", + apiId: "rowLinksCopy", + type: SimpleFieldType.Richtext, + isLocalized: true, + modelApiId: "RowLinks" + }, + "RowLinks", + "model" + ); + migrationAction( + schema, + "relationalField", + "create", + { + displayName: "Links", + apiId: "pageLinks", + modelApiId: "RowLinks", + type: RelationalFieldType.Relation, + reverseField: { + apiId: "rowLinks", + modelApiId: "PageLink", + displayName: "RowLinks", + visibility: VisibilityTypes.Hidden, + isList: true + }, + visibility: VisibilityTypes.ReadWrite, + isList: true + }, + "RowLinks", + "model" + ); + migrationAction( + schema, + "unionField", + "update", + { + apiId: "content", + displayName: "Content", + modelApiId: "Page", + reverseField: { + modelApiIds: [ + "RowLinks", + "RowServiceOptions", + "RowSpecialBanner", + "RowQuote", + "RowProduct", + "RowColumnOne", + "RowColumnTwo", + "RowColumnThree", + "RowHeroBanner", + "RowBlogContent", + "RowButtonList", + "RowContentLinks", + "RowButtonLinkList" + ] + // visibility: VisibilityTypes.Hidden, => Currently not supported for updateUnionField | https://github.com/hygraph/management-sdk/issues/34 + } + }, + "Page", + "model" + ); + return client.run(true); +}; + +const graphcommerce6to7 = async (schema, client) => { + const { migrationAction } = migrationActionFactory(schema, client); + migrationAction(schema, "enumeration", "create", { + displayName: "Row Column One Variants", + apiId: "RowColumnOneVariants", + values: [ + { displayName: "Default", apiId: "Default" }, + { displayName: "Message", apiId: "Message" } + ] + }); + migrationAction(schema, "enumeration", "create", { + displayName: "Dynamic Row Condition Number Operator", + apiId: "DynamicRowConditionNumberOperator", + values: [ + { displayName: "Greater than or equal to", apiId: "GTE" }, + { displayName: "Less than or equal to", apiId: "LTE" }, + { displayName: "Equal to", apiId: "EQUAL" } + ] + }); + migrationAction(schema, "enumeration", "create", { + displayName: "Dynamic Row Placement", + apiId: "DynamicRowPlacement", + values: [ + { displayName: "Before", apiId: "BEFORE" }, + { displayName: "After", apiId: "AFTER" }, + { displayName: "Replace", apiId: "REPLACE" } + ] + }); + migrationAction(schema, "component", "create", { + displayName: "Text", + apiId: "ConditionText", + apiIdPlural: "ConditionTexts" + }); + migrationAction(schema, "component", "create", { + displayName: "Number", + apiId: "ConditionNumber", + apiIdPlural: "ConditionNumbers" + }); + migrationAction(schema, "component", "create", { + displayName: "AND", + apiId: "ConditionAnd", + apiIdPlural: "ConditionAnds", + description: "All of these conditions must match" + }); + migrationAction(schema, "component", "create", { + displayName: "OR", + apiId: "ConditionOr", + apiIdPlural: "ConditionOrs", + description: "One of these conditions must match" + }); + migrationAction( + schema, + "componentUnionField", + "create", + { + displayName: "Conditions", + apiId: "conditions", + parentApiId: "ConditionAnd", + componentApiIds: ["ConditionOr", "ConditionText", "ConditionNumber"], + isList: true + }, + "ConditionAnd", + "component" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Property", + apiId: "property", + type: SimpleFieldType.String, + parentApiId: "ConditionText", + description: "Path to the value of the object being evaluated.\n\nFor products: url_key, category, sku", + isRequired: true, + validations: { + String: { + matches: { + flags: ["i", "s"], + regex: "^[a-z0-9-_.]+$", + errorMessage: "Only letters, numbers, dashes (-), underscores (_) or dots allowed (.)" + } + } + } + }, + "ConditionText", + "component" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Value", + apiId: "value", + type: SimpleFieldType.String, + parentApiId: "ConditionText", + isRequired: true + }, + "ConditionText", + "component" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Property", + apiId: "property", + type: SimpleFieldType.String, + parentApiId: "ConditionNumber", + isRequired: true, + validations: { + String: { + matches: { + flags: ["i", "s"], + regex: "^[a-z0-9-_.]+$", + errorMessage: "Only letters, numbers, dashes (-), underscores (_) or dots allowed (.)" + } + } + } + }, + "ConditionNumber", + "component" + ); + migrationAction( + schema, + "enumerableField", + "create", + { + displayName: "Operator", + apiId: "operator", + parentApiId: "ConditionNumber", + enumerationApiId: "DynamicRowConditionNumberOperator", + isRequired: true + }, + "ConditionNumber", + "component" + ); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Value", + apiId: "value", + type: SimpleFieldType.Float, + parentApiId: "ConditionNumber", + isRequired: true + }, + "ConditionNumber", + "component" + ); + migrationAction(schema, "model", "create", { + displayName: "Dynamic Row", + apiId: "DynamicRow", + apiIdPlural: "DynamicRows", + description: "Dynamic rows allow you to add specific Row models to pages based on the properties of the page" + }); + migrationAction( + schema, + "simpleField", + "create", + { + displayName: "Internal name", + apiId: "internalName", + description: "Only used for internal reference", + type: SimpleFieldType.String, + isTitle: true, + isRequired: true, + isUnique: true, + modelApiId: "DynamicRow" + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "unionField", + "create", + { + displayName: "Row", + apiId: "row", + reverseField: { + modelApiIds: ["RowQuote", "RowLinks", "RowColumnOne"], + apiId: "dynamicRow", + displayName: "DynamicRows", + visibility: VisibilityTypes.Hidden, + isList: true + }, + parentApiId: "DynamicRow" + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "enumerableField", + "create", + { + displayName: "Placement", + apiId: "placement", + parentApiId: "DynamicRow", + enumerationApiId: "DynamicRowPlacement", + description: "Where will the row be placed relative to the target", + isRequired: true + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "unionField", + "create", + { + displayName: "Placement target", + apiId: "target", + description: "Optional: When the target is left blank it will place the Dynamic Row on the start or end.", + reverseField: { + modelApiIds: [ + "RowQuote", + "RowLinks", + "RowColumnOne", + "RowColumnTwo", + "RowColumnThree", + "RowServiceOptions", + "RowContentLinks", + "RowButtonLinkList", + "RowProduct", + "RowSpecialBanner", + "RowHeroBanner", + "RowBlogContent" + ], + apiId: "dynamicRowsTarget", + displayName: "DynamicRowsTarget", + visibility: VisibilityTypes.Hidden, + isList: true + }, + parentApiId: "DynamicRow" + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "componentUnionField", + "create", + { + displayName: "Conditions (OR)", + apiId: "conditions", + parentApiId: "DynamicRow", + description: "One of these conditions must match", + componentApiIds: ["ConditionAnd", "ConditionText", "ConditionNumber"], + isList: true + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "enumerableField", + "create", + { + displayName: "Variant", + apiId: "rowColumnOneVariant", + enumerationApiId: "RowColumnOneVariants", + parentApiId: "RowColumnOne" + }, + "RowColumnOne", + "model" + ); + migrationAction( + schema, + "componentUnionField", + "create", + { + displayName: "Conditions", + apiId: "conditions", + parentApiId: "ConditionOr", + componentApiIds: ["ConditionText", "ConditionNumber"], + isList: true + }, + "ConditionOr", + "component" + ); + return client.run(true); +}; + +const graphcommerce7to8 = async (schema, client) => { + const { migrationAction } = migrationActionFactory(schema, client); + const hasRow = schema.models.find((m) => m.apiId === "DynamicRow")?.fields.some((f) => f.apiId === "row"); + if (hasRow) { + migrationAction(schema, "unionField", "update", { + apiId: "row", + displayName: "Row Deprecated", + parentApiId: "DynamicRow", + description: "This field is deprecated. Use Rows instead." + }); + } + migrationAction( + schema, + "unionField", + "create", + { + displayName: "Rows", + apiId: "rows", + isList: true, + reverseField: { + modelApiIds: ["RowQuote", "RowLinks", "RowColumnOne"], + apiId: "dynamicRows", + displayName: "Dynamic Rows", + visibility: VisibilityTypes.Hidden, + isList: true + }, + parentApiId: "DynamicRow" + }, + "DynamicRow", + "model" + ); + migrationAction( + schema, + "componentUnionField", + "create", + { + displayName: "Conditions", + apiId: "conditions", + parentApiId: "ConditionOr", + componentApiIds: ["ConditionText", "ConditionNumber"], + isList: true + }, + "ConditionOr", + "component" + ); + return client.run(true); +}; + +const graphcommerce8to9 = async (schema, client) => { + const { migrationAction } = migrationActionFactory(schema, client); + const hasRow = schema.models.find((m) => m.apiId === "DynamicRow")?.fields.some((f) => f.apiId === "row"); + if (hasRow) { + migrationAction(schema, "simpleField", "delete", { + apiId: "row", + parentApiId: "DynamicRow" + }); + } + const hasRowCategory = schema.models.some((m) => m.apiId === "RowCategory"); + if (!hasRowCategory) { + migrationAction(schema, "model", "create", { + apiId: "RowCategory", + displayName: "Row Category", + apiIdPlural: "RowProductLists", + description: "A model that displays a category" + }); + migrationAction( + schema, + "simpleField", + "create", + { + position: 1, + type: SimpleFieldType.String, + formConfig: { renderer: "GCMS_SLUG", config: { isLowercase: true } }, + validations: { + String: { + matches: { + regex: "^[a-z0-9]+(?:[-/][a-z0-9]+)*$", + errorMessage: "The category URL must be a valid slug" + } + } + }, + parentApiId: "RowCategory", + displayName: "Category URL", + apiId: "categoryUrl", + description: "The URL of the category, may include slashes", + isTitle: true, + isLocalized: true, + isRequired: true, + visibility: VisibilityTypes.ReadWrite + }, + "RowCategory", + "model" + ); + migrationAction(schema, "enumeration", "create", { + displayName: "Row Category Variant", + apiId: "RowCategoryVariant", + values: [ + { displayName: "Backstory", apiId: "Backstory" }, + { displayName: "Grid", apiId: "Grid" }, + { displayName: "Swipeable", apiId: "Swipeable" } + ] + }); + migrationAction( + schema, + "enumerableField", + "create", + { + displayName: "Variant", + apiId: "variant", + parentApiId: "RowCategory", + enumerationApiId: "RowCategoryVariant", + description: "As what variant wil the RowCategory be displayed", + isRequired: true + }, + "RowCategory", + "model" + ); + } + return client.run(true); +}; + +const availableMigrations = [ + graphcommerce5to6, + graphcommerce6to7, + graphcommerce7to8, + graphcommerce8to9 +]; + +const readSchema = async (managementClient, projectId) => { + const { data } = await managementClient.query({ + query: gql` + query getSchema($projectId: ID!) { + viewer { + project(id: $projectId) { + environment(name: "master") { + contentModel { + locales { + id + apiId + } + stages { + id + apiId + } + models { + apiId + apiIdPlural + fields { + apiId + } + } + components { + apiId + apiIdPlural + fields { + apiId + } + } + enumerations { + apiId + } + } + } + } + } + } + `, + variables: { + projectId + } + }); + return data; +}; + +class UpsertClient extends Client { + constructor(params, schema) { + super(params); + this.schema = schema; + } + /** @public */ + upsertModel(data) { + const exists = this.schema.models.some((m) => m.apiId === data.apiId); + return exists ? this.createModel(data) : this.updateModel(data); + } + /** @public */ + upsertComponent(data) { + const exists = this.schema.models.some((m) => m.apiId === data.apiId); + return exists ? this.createComponent(data) : this.updateComponent(data); + } + /** @public */ + upsertSimpleField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createSimpleField(data) : this.updateSimpleField({ ...data, embeddableModels: undefined }); + } + // upsertRemoteField(data: BatchMigrationCreateRemoteFieldInput) { + // const model = this.schema.models.find((m) => m.apiId === data.parentApiId) + // const exists = model?.fields.some((f) => f.apiId === data.apiId) + // return exists ? this.createRemoteField(data) : this.updateRemoteField(data) + // } + /** @public */ + upsertRelationalField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createRelationalField(data) : this.updateRelationalField(data); + } + /** @public */ + upsertUnionField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createUnionField(data) : this.updateUnionField(data); + } + /** @public */ + upsertComponentField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createComponentField(data) : this.updateComponentField(data); + } + /** @public */ + upsertComponentUnionField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createComponentUnionField(data) : this.updateComponentUnionField(data); + } + /** @public */ + upsertEnumeration(data) { + const exists = this.schema.enumerations.some((e) => e.apiId === data.apiId); + return exists ? this.createEnumeration(data) : this.updateEnumeration(data); + } + /** @public */ + upsertEnumerableField(data) { + const model = this.schema.models.find((m) => m.apiId === data.parentApiId); + const exists = model?.fields.some((f) => f.apiId === data.apiId); + return exists ? this.createEnumerableField(data) : this.updateEnumerableField(data); + } + /** @public */ + upsertStage(data) { + const exists = this.schema.stages.some((m) => m.apiId === data.apiId); + return exists ? this.createStage(data) : this.updateStage(data); + } + /** @public */ + upsertLocale(data) { + const exists = this.schema.locales.some((m) => m.apiId === data.apiId); + return exists ? this.createLocale(data) : this.updateLocale(data); + } +} + +function getConfig(config) { + let { + hygraphProjectId: projectId, + hygraphWriteAccessToken: authToken, + hygraphManagementApi: uri, + hygraphEndpoint + } = config; + if (!authToken) { + throw new Error("Please provide GC_HYGRAPH_WRITE_ACCESS_TOKEN in your env file."); + } + if (!projectId) { + projectId = new URL(hygraphEndpoint).pathname.split("/")?.[1]; + } + if (!uri) { + const endpoint = new URL(hygraphEndpoint); + endpoint.hostname = `management-${endpoint.hostname}`.replace(".cdn", ""); + endpoint.pathname = "graphql"; + uri = endpoint.toString(); + } + return { projectId, authToken, uri }; +} + +async function getEnvironment(client, config) { + const endpoints = await client.query({ + query: gql$1` + query Environments($projectId: ID!) { + viewer { + id + project(id: $projectId) { + environments { + name + endpoint + migrations { + name + status + } + } + } + } + } + `, + variables: { projectId: config.projectId }, + errorPolicy: "all" + }); + if (endpoints.errors) { + const isBadInput = endpoints.errors.some((e) => e.extensions?.code === "BAD_USER_INPUT"); + if (isBadInput) { + throw Error(` + Could not find environment for projectId ${config.projectId}. + Please check your GC_HYGRAPH_PROJECT_ID in your env file. + `); + } + throw new Error(`An error occurred: ${endpoints.errors.map((e) => e.message).join("\n")}`); + } + const environment = endpoints.data.viewer.project.environments.find((env) => env.name === "master") ?? endpoints.data.viewer.project.environments?.[0]; + return environment; +} + +function getManagementClient(config) { + const { authToken: accessToken, uri } = config; + return new ApolloClient({ + link: new HttpLink({ + uri, + fetch, + headers: { Authorization: `Bearer ${accessToken}` } + }), + cache: new InMemoryCache() + }); +} + +dotenv.config(); +async function migrateHygraphCli() { + const hygraphConfig = getConfig(loadConfig(process.cwd())); + const packageJson = fs.readFileSync("package.json", "utf8"); + const packageData = JSON.parse(packageJson); + const graphcommerceVersion = packageData.dependencies["@graphcommerce/next-ui"]; + graphcommerceLog(`Graphcommerce version: ${graphcommerceVersion}`, "info"); + const mangementClient = getManagementClient(hygraphConfig); + const schemaViewer = await readSchema(mangementClient, hygraphConfig.projectId); + const schema = schemaViewer.viewer.project.environment.contentModel; + const possibleMigrations = Object.entries(availableMigrations); + const selectMigrationInput = { + type: "select", + name: "selectedMigration", + message: "\x1B[36m\x1B[1m[]: Select migration", + choices: possibleMigrations.map(([name, migration]) => ({ + title: name, + value: { name, migration } + })) + }; + try { + graphcommerceLog("Available migrations: ", "info"); + const selectMigrationOutput = await prompts(selectMigrationInput); + let { migration, name } = selectMigrationOutput.selectedMigration; + graphcommerceLog( + `You have selected the ${selectMigrationOutput.selectedMigration.name} migration`, + "info" + ); + try { + const { endpoint, migrations } = await getEnvironment(mangementClient, hygraphConfig); + const migrationExists = migrations.find( + (m) => m.name?.startsWith(name) && m.status === "SUCCESS" + ); + if (migrationExists) { + if (!process.argv.includes("--force")) { + graphcommerceLog( + `Migration ${name} as ${migrationExists.name} already exists in Hygraph with the status SUCCESS. To rerun this migration use the --force option. Exiting now..`, + "info" + ); + process.exit(1); + } else { + graphcommerceLog( + `Migration ${name} as ${migrationExists.name} already exists in Hygraph with the status SUCCESS. Using --force, rerunning migration..`, + "warning" + ); + } + name = `${name}-${Date.now()}`; + } + const result = await migration( + schema, + new UpsertClient({ authToken: hygraphConfig.authToken, endpoint, name }, schema) + ); + graphcommerceLog(`Migration result: ${JSON.stringify(result)}`, "info"); + if (!result) { + graphcommerceLog( + "No migration client found. Please make sure your GC_HYGRAPH_WRITE_ACCESS_TOKEN in your env file is correct." + ); + process.exit(1); + } + if (result.status !== "SUCCESS") { + graphcommerceLog(`Migration not successful: ${result.status} ${name}: +${result.errors}`); + process.exit(1); + } + graphcommerceLog(`Migration successful: ${name}`, "info"); + } catch (err) { + if (err instanceof Error) { + const garbledErrorIndex = err.message.indexOf(': {"'); + const msg = garbledErrorIndex > 0 ? err.message.slice(0, garbledErrorIndex) : err.message; + graphcommerceLog(`${msg}`, "error"); + } + } + } catch (error) { + graphcommerceLog(`An error occurred: ${error}`, "error"); + } +} + +export { migrateHygraphCli as migrateHygraph }; diff --git a/packages/hygraph-cli/dist/migrateHygraphCli.js b/packages/hygraph-cli/dist/migrateHygraphCli.js deleted file mode 100644 index abcb85965c..0000000000 --- a/packages/hygraph-cli/dist/migrateHygraphCli.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.migrateHygraphCli = migrateHygraphCli; -const fs_1 = __importDefault(require("fs")); -const next_config_1 = require("@graphcommerce/next-config"); -const dotenv_1 = __importDefault(require("dotenv")); -const prompts_1 = __importDefault(require("prompts")); -const migrations_1 = require("./migrations"); -const readSchema_1 = require("./readSchema"); -const UpsertClient_1 = require("./UpsertClient"); -const getConfig_1 = require("./utils/getConfig"); -const getEndpointUrl_1 = require("./utils/getEndpointUrl"); -const getManagementClient_1 = require("./utils/getManagementClient"); -const graphCommerceLog_1 = require("./utils/graphCommerceLog"); -dotenv_1.default.config(); -async function migrateHygraphCli() { - const hygraphConfig = (0, getConfig_1.getConfig)((0, next_config_1.loadConfig)(process.cwd())); - /** - * Extracting the current GC version. Are we gonna use the current version to determine which - * scripts should be runned? Or do we let the user pick the migration from a list? 🤔 - */ - const packageJson = fs_1.default.readFileSync('package.json', 'utf8'); - const packageData = JSON.parse(packageJson); - const graphcommerceVersion = packageData.dependencies['@graphcommerce/next-ui']; - (0, graphCommerceLog_1.graphcommerceLog)(`Graphcommerce version: ${graphcommerceVersion}`, 'info'); - const mangementClient = (0, getManagementClient_1.getManagementClient)(hygraphConfig); - // Extract the currently existing models, components and enumerations from the Hygraph schema. - const schemaViewer = await (0, readSchema_1.readSchema)(mangementClient, hygraphConfig.projectId); - const schema = schemaViewer.viewer.project.environment.contentModel; - // A list of possible migrations - const possibleMigrations = Object.entries(migrations_1.availableMigrations); - // Here we setup the list we ask the user to choose from - const selectMigrationInput = { - type: 'select', - name: 'selectedMigration', - message: '\x1b[36m\x1b[1m[]: Select migration', - choices: possibleMigrations.map(([name, migration]) => ({ - title: name, - value: { name, migration }, - })), - }; - // Here we ask the user to choose a migration from a list of possible migrations - try { - (0, graphCommerceLog_1.graphcommerceLog)('Available migrations: ', 'info'); - const selectMigrationOutput = await (0, prompts_1.default)(selectMigrationInput); - let { migration, name } = selectMigrationOutput.selectedMigration; - (0, graphCommerceLog_1.graphcommerceLog)(`You have selected the ${selectMigrationOutput.selectedMigration.name} migration`, 'info'); - try { - const { endpoint, migrations } = await (0, getEndpointUrl_1.getEnvironment)(mangementClient, hygraphConfig); - const migrationExists = migrations.find((m) => m.name?.startsWith(name) && m.status === 'SUCCESS'); - if (migrationExists) { - if (!process.argv.includes('--force')) { - (0, graphCommerceLog_1.graphcommerceLog)(`Migration ${name} as ${migrationExists.name} already exists in Hygraph with the status SUCCESS. To rerun this migration use the --force option. Exiting now..`, 'info'); - process.exit(1); - } - else { - (0, graphCommerceLog_1.graphcommerceLog)(`Migration ${name} as ${migrationExists.name} already exists in Hygraph with the status SUCCESS. Using --force, rerunning migration..`, 'warning'); - } - name = `${name}-${Date.now()}`; - } - // Here we try to run the migration - const result = await migration(schema, new UpsertClient_1.UpsertClient({ authToken: hygraphConfig.authToken, endpoint, name }, schema)); - (0, graphCommerceLog_1.graphcommerceLog)(`Migration result: ${JSON.stringify(result)}`, 'info'); - if (!result) { - (0, graphCommerceLog_1.graphcommerceLog)('No migration client found. Please make sure your GC_HYGRAPH_WRITE_ACCESS_TOKEN in your env file is correct.'); - process.exit(1); - } - if (result.status !== 'SUCCESS') { - (0, graphCommerceLog_1.graphcommerceLog)(`Migration not successful: ${result.status} ${name}:\n${result.errors}`); - process.exit(1); - } - (0, graphCommerceLog_1.graphcommerceLog)(`Migration successful: ${name}`, 'info'); - } - catch (err) { - if (err instanceof Error) { - const garbledErrorIndex = err.message.indexOf(': {"'); - const msg = garbledErrorIndex > 0 ? err.message.slice(0, garbledErrorIndex) : err.message; - (0, graphCommerceLog_1.graphcommerceLog)(`${msg}`, 'error'); - } - } - } - catch (error) { - (0, graphCommerceLog_1.graphcommerceLog)(`An error occurred: ${error}`, 'error'); - } -} diff --git a/packages/hygraph-cli/dist/migrationActionFactory.js b/packages/hygraph-cli/dist/migrationActionFactory.js deleted file mode 100644 index 89b5ce4049..0000000000 --- a/packages/hygraph-cli/dist/migrationActionFactory.js +++ /dev/null @@ -1,133 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.migrationActionFactory = migrationActionFactory; -const dotenv_1 = __importDefault(require("dotenv")); -const graphCommerceLog_1 = require("./utils/graphCommerceLog"); -dotenv_1.default.config(); -function migrationActionFactory(schema, client) { - /** - * This constant is used to assign the right action of the management SDK to the migratioAction - * function - */ - const actionMap = client - ? { - create: { - model: (innerprops) => client.createModel(innerprops), - component: (innerprops) => client.createComponent(innerprops), - enumeration: (innerprops) => client.createEnumeration(innerprops), - simpleField: (innerprops) => client.createSimpleField(innerprops), - enumerableField: (innerprops) => client.createEnumerableField(innerprops), - componentField: (innerprops) => client.createComponentField(innerprops), - relationalField: (innerprops) => client.createRelationalField(innerprops), - unionField: (innerprops) => client.createUnionField(innerprops), - componentUnionField: (innerprops) => client.createComponentUnionField(innerprops), - }, - update: { - model: (innerprops) => client.updateModel(innerprops), - component: (innerprops) => client.updateComponent(innerprops), - enumeration: (innerprops) => client.updateEnumeration(innerprops), - simpleField: (innerprops) => client.updateSimpleField(innerprops), - enumerableField: (innerprops) => client.updateEnumerableField(innerprops), - componentField: (innerprops) => client.updateComponentField(innerprops), - relationalField: (innerprops) => client.updateRelationalField(innerprops), - unionField: (innerprops) => client.updateUnionField(innerprops), - componentUnionField: (innerprops) => client.updateComponentUnionField(innerprops), - }, - delete: { - model: (innerprops) => client.deleteModel(innerprops), - component: (innerprops) => client.deleteComponent(innerprops), - enumeration: (innerprops) => client.deleteEnumeration(innerprops), - simpleField: (innerprops) => client.deleteField(innerprops), - enumerableField: (innerprops) => client.deleteField(innerprops), - componentField: (innerprops) => client.deleteField(innerprops), - relationalField: (innerprops) => client.deleteField(innerprops), - unionField: (innerprops) => client.deleteField(innerprops), - componentUnionField: (innerprops) => client.deleteField(innerprops), - }, - } - : undefined; - /** - * This function is our variation on the client.migrationAction functions from the hygraph - * management sdk. - * - * MigrationAction() is better suited because it is a single function for all actions. More - * importantly, if the action fails, because a field with the apiID already exists for instance. it - * will skip this action but still continue the whole migration, while the management sdk function - * will bail. - * - * It takes the schema as argument, which is always the same. - * - * Then it takes the type of schema entity you want to do an action upon, and the action you want to - * do. - * - * The fourth arguments are the props that belong to the action you want to do. For instance, if you - * want to create a model, you need to pass the props that belong to a model. - * - * The last two arguments are optional. If you want to create a field, you need to pass the apiId of - * the model or component you want to create the field on. If you want to create a field on a - * component, you also need to pass the parentType, which is either 'model' or 'component'. - */ - const migrationAction = (_schema, type, action, props, parentApiId, parentType) => { - /** - * Check if the entity already exists. - * If an update or deletion is made, it does not matter if the entity already exists - */ - const alreadyExists = () => { - if (action !== 'create') { - return false; - } - switch (type) { - case 'model': - return schema.models.some((model) => model.apiId === props.apiId); - case 'component': - return schema.components.some((component) => component.apiId === props.apiId); - case 'enumeration': - return schema.enumerations.some((enumeration) => enumeration.apiId === props.apiId); - case 'simpleField': - case 'enumerableField': - case 'relationalField': - case 'unionField': - case 'componentUnionField': { - let parent; - switch (parentType) { - case 'model': { - parent = schema.models.find((model) => model.apiId === parentApiId); - break; - } - case 'component': { - parent = schema.components.find((component) => component.apiId === parentApiId); - break; - } - default: - return false; - } - return parent?.fields.some((field) => field.apiId === props.apiId); - } - default: { - return false; - } - } - }; - const actionFunc = actionMap && actionMap[action] && actionMap[action][type]; - if (!alreadyExists()) { - if (actionFunc) { - (0, graphCommerceLog_1.graphcommerceLog)(`${(0, graphCommerceLog_1.capitalize)(action)} ${type} with apiId ${props.apiId}...`); - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore | This error is a loss on typescript autocomplete, but the function is called correctly - actionFunc(props); - } - else { - (0, graphCommerceLog_1.graphcommerceLog)(`Action ${action} is not supported for ${type}`, 'error'); - } - } - else { - (0, graphCommerceLog_1.graphcommerceLog)(`${(0, graphCommerceLog_1.capitalize)(type)} with apiId ${props.apiId} on ${parentApiId} already exists`, 'warning'); - } - }; - return { - migrationAction, - }; -} diff --git a/packages/hygraph-cli/dist/migrations/graphcommerce5to6.js b/packages/hygraph-cli/dist/migrations/graphcommerce5to6.js deleted file mode 100644 index 1ac6c4082b..0000000000 --- a/packages/hygraph-cli/dist/migrations/graphcommerce5to6.js +++ /dev/null @@ -1,98 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.graphcommerce5to6 = void 0; -const management_sdk_1 = require("@hygraph/management-sdk"); -const migrationActionFactory_1 = require("../migrationActionFactory"); -const graphcommerce5to6 = async (schema, client) => { - const { migrationAction } = (0, migrationActionFactory_1.migrationActionFactory)(schema, client); - // ? ENUMERATIONS - migrationAction(schema, 'enumeration', 'create', { - displayName: 'Row Links Variants', - apiId: 'RowLinksVariants', - values: [ - { displayName: 'Inline', apiId: 'Inline' }, - { displayName: 'Image Label Swiper', apiId: 'ImageLabelSwiper' }, - { displayName: 'Logo Swiper', apiId: 'LogoSwiper' }, - { displayName: 'USPS', apiId: 'Usps' }, - ], - }); - // ? MODEL - migrationAction(schema, 'model', 'create', { - apiId: 'RowLinks', - apiIdPlural: 'RowLinksMultiple', - displayName: 'Row Links', - description: 'Row Links is a Row of PageLinks with different variants', - }); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Identity', - apiId: 'identity', - description: 'Only used for internal reference', - type: management_sdk_1.SimpleFieldType.String, - isTitle: true, - isRequired: true, - isUnique: true, - modelApiId: 'RowLinks', - }, 'RowLinks', 'model'); - migrationAction(schema, 'enumerableField', 'create', { - displayName: 'Variant', - apiId: 'linksVariant', - parentApiId: 'RowLinks', - enumerationApiId: 'RowLinksVariants', - description: 'Different variants for Row Links', - }, 'RowLinks', 'model'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Title', - apiId: 'title', - type: management_sdk_1.SimpleFieldType.String, - isRequired: true, - modelApiId: 'RowLinks', - isLocalized: true, - }, 'RowLinks', 'model'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Copy', - apiId: 'rowLinksCopy', - type: management_sdk_1.SimpleFieldType.Richtext, - isLocalized: true, - modelApiId: 'RowLinks', - }, 'RowLinks', 'model'); - migrationAction(schema, 'relationalField', 'create', { - displayName: 'Links', - apiId: 'pageLinks', - modelApiId: 'RowLinks', - type: management_sdk_1.RelationalFieldType.Relation, - reverseField: { - apiId: 'rowLinks', - modelApiId: 'PageLink', - displayName: 'RowLinks', - visibility: management_sdk_1.VisibilityTypes.Hidden, - isList: true, - }, - visibility: management_sdk_1.VisibilityTypes.ReadWrite, - isList: true, - }, 'RowLinks', 'model'); - migrationAction(schema, 'unionField', 'update', { - apiId: 'content', - displayName: 'Content', - modelApiId: 'Page', - reverseField: { - modelApiIds: [ - 'RowLinks', - 'RowServiceOptions', - 'RowSpecialBanner', - 'RowQuote', - 'RowProduct', - 'RowColumnOne', - 'RowColumnTwo', - 'RowColumnThree', - 'RowHeroBanner', - 'RowBlogContent', - 'RowButtonList', - 'RowContentLinks', - 'RowButtonLinkList', - ], - // visibility: VisibilityTypes.Hidden, => Currently not supported for updateUnionField | https://github.com/hygraph/management-sdk/issues/34 - }, - }, 'Page', 'model'); - return client.run(true); -}; -exports.graphcommerce5to6 = graphcommerce5to6; diff --git a/packages/hygraph-cli/dist/migrations/graphcommerce6to7.js b/packages/hygraph-cli/dist/migrations/graphcommerce6to7.js deleted file mode 100644 index b7abe0a3c7..0000000000 --- a/packages/hygraph-cli/dist/migrations/graphcommerce6to7.js +++ /dev/null @@ -1,206 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.graphcommerce6to7 = void 0; -const management_sdk_1 = require("@hygraph/management-sdk"); -const migrationActionFactory_1 = require("../migrationActionFactory"); -const graphcommerce6to7 = async (schema, client) => { - const { migrationAction } = (0, migrationActionFactory_1.migrationActionFactory)(schema, client); - // ? ENUMERATIONS - migrationAction(schema, 'enumeration', 'create', { - displayName: 'Row Column One Variants', - apiId: 'RowColumnOneVariants', - values: [ - { displayName: 'Default', apiId: 'Default' }, - { displayName: 'Message', apiId: 'Message' }, - ], - }); - migrationAction(schema, 'enumeration', 'create', { - displayName: 'Dynamic Row Condition Number Operator', - apiId: 'DynamicRowConditionNumberOperator', - values: [ - { displayName: 'Greater than or equal to', apiId: 'GTE' }, - { displayName: 'Less than or equal to', apiId: 'LTE' }, - { displayName: 'Equal to', apiId: 'EQUAL' }, - ], - }); - migrationAction(schema, 'enumeration', 'create', { - displayName: 'Dynamic Row Placement', - apiId: 'DynamicRowPlacement', - values: [ - { displayName: 'Before', apiId: 'BEFORE' }, - { displayName: 'After', apiId: 'AFTER' }, - { displayName: 'Replace', apiId: 'REPLACE' }, - ], - }); - // ? COMPONENTS - migrationAction(schema, 'component', 'create', { - displayName: 'Text', - apiId: 'ConditionText', - apiIdPlural: 'ConditionTexts', - }); - migrationAction(schema, 'component', 'create', { - displayName: 'Number', - apiId: 'ConditionNumber', - apiIdPlural: 'ConditionNumbers', - }); - migrationAction(schema, 'component', 'create', { - displayName: 'AND', - apiId: 'ConditionAnd', - apiIdPlural: 'ConditionAnds', - description: 'All of these conditions must match', - }); - migrationAction(schema, 'component', 'create', { - displayName: 'OR', - apiId: 'ConditionOr', - apiIdPlural: 'ConditionOrs', - description: 'One of these conditions must match', - }); - migrationAction(schema, 'componentUnionField', 'create', { - displayName: 'Conditions', - apiId: 'conditions', - parentApiId: 'ConditionAnd', - componentApiIds: ['ConditionOr', 'ConditionText', 'ConditionNumber'], - isList: true, - }, 'ConditionAnd', 'component'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Property', - apiId: 'property', - type: management_sdk_1.SimpleFieldType.String, - parentApiId: 'ConditionText', - description: 'Path to the value of the object being evaluated.\n\nFor products: url_key, category, sku', - isRequired: true, - validations: { - String: { - matches: { - flags: ['i', 's'], - regex: '^[a-z0-9-_.]+$', - errorMessage: 'Only letters, numbers, dashes (-), underscores (_) or dots allowed (.)', - }, - }, - }, - }, 'ConditionText', 'component'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Value', - apiId: 'value', - type: management_sdk_1.SimpleFieldType.String, - parentApiId: 'ConditionText', - isRequired: true, - }, 'ConditionText', 'component'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Property', - apiId: 'property', - type: management_sdk_1.SimpleFieldType.String, - parentApiId: 'ConditionNumber', - isRequired: true, - validations: { - String: { - matches: { - flags: ['i', 's'], - regex: '^[a-z0-9-_.]+$', - errorMessage: 'Only letters, numbers, dashes (-), underscores (_) or dots allowed (.)', - }, - }, - }, - }, 'ConditionNumber', 'component'); - migrationAction(schema, 'enumerableField', 'create', { - displayName: 'Operator', - apiId: 'operator', - parentApiId: 'ConditionNumber', - enumerationApiId: 'DynamicRowConditionNumberOperator', - isRequired: true, - }, 'ConditionNumber', 'component'); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Value', - apiId: 'value', - type: management_sdk_1.SimpleFieldType.Float, - parentApiId: 'ConditionNumber', - isRequired: true, - }, 'ConditionNumber', 'component'); - // ? MODEL - migrationAction(schema, 'model', 'create', { - displayName: 'Dynamic Row', - apiId: 'DynamicRow', - apiIdPlural: 'DynamicRows', - description: 'Dynamic rows allow you to add specific Row models to pages based on the properties of the page', - }); - migrationAction(schema, 'simpleField', 'create', { - displayName: 'Internal name', - apiId: 'internalName', - description: 'Only used for internal reference', - type: management_sdk_1.SimpleFieldType.String, - isTitle: true, - isRequired: true, - isUnique: true, - modelApiId: 'DynamicRow', - }, 'DynamicRow', 'model'); - migrationAction(schema, 'unionField', 'create', { - displayName: 'Row', - apiId: 'row', - reverseField: { - modelApiIds: ['RowQuote', 'RowLinks', 'RowColumnOne'], - apiId: 'dynamicRow', - displayName: 'DynamicRows', - visibility: management_sdk_1.VisibilityTypes.Hidden, - isList: true, - }, - parentApiId: 'DynamicRow', - }, 'DynamicRow', 'model'); - migrationAction(schema, 'enumerableField', 'create', { - displayName: 'Placement', - apiId: 'placement', - parentApiId: 'DynamicRow', - enumerationApiId: 'DynamicRowPlacement', - description: 'Where will the row be placed relative to the target', - isRequired: true, - }, 'DynamicRow', 'model'); - migrationAction(schema, 'unionField', 'create', { - displayName: 'Placement target', - apiId: 'target', - description: 'Optional: When the target is left blank it will place the Dynamic Row on the start or end.', - reverseField: { - modelApiIds: [ - 'RowQuote', - 'RowLinks', - 'RowColumnOne', - 'RowColumnTwo', - 'RowColumnThree', - 'RowServiceOptions', - 'RowContentLinks', - 'RowButtonLinkList', - 'RowProduct', - 'RowSpecialBanner', - 'RowHeroBanner', - 'RowBlogContent', - ], - apiId: 'dynamicRowsTarget', - displayName: 'DynamicRowsTarget', - visibility: management_sdk_1.VisibilityTypes.Hidden, - isList: true, - }, - parentApiId: 'DynamicRow', - }, 'DynamicRow', 'model'); - migrationAction(schema, 'componentUnionField', 'create', { - displayName: 'Conditions (OR)', - apiId: 'conditions', - parentApiId: 'DynamicRow', - description: 'One of these conditions must match', - componentApiIds: ['ConditionAnd', 'ConditionText', 'ConditionNumber'], - isList: true, - }, 'DynamicRow', 'model'); - // ? Row Column One - migrationAction(schema, 'enumerableField', 'create', { - displayName: 'Variant', - apiId: 'rowColumnOneVariant', - enumerationApiId: 'RowColumnOneVariants', - parentApiId: 'RowColumnOne', - }, 'RowColumnOne', 'model'); - migrationAction(schema, 'componentUnionField', 'create', { - displayName: 'Conditions', - apiId: 'conditions', - parentApiId: 'ConditionOr', - componentApiIds: ['ConditionText', 'ConditionNumber'], - isList: true, - }, 'ConditionOr', 'component'); - return client.run(true); -}; -exports.graphcommerce6to7 = graphcommerce6to7; diff --git a/packages/hygraph-cli/dist/migrations/graphcommerce7to8.js b/packages/hygraph-cli/dist/migrations/graphcommerce7to8.js deleted file mode 100644 index 5bdad876e7..0000000000 --- a/packages/hygraph-cli/dist/migrations/graphcommerce7to8.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.graphcommerce7to8 = void 0; -const management_sdk_1 = require("@hygraph/management-sdk"); -const migrationActionFactory_1 = require("../migrationActionFactory"); -const graphcommerce7to8 = async (schema, client) => { - const { migrationAction } = (0, migrationActionFactory_1.migrationActionFactory)(schema, client); - const hasRow = schema.models - .find((m) => m.apiId === 'DynamicRow') - ?.fields.some((f) => f.apiId === 'row'); - if (hasRow) { - migrationAction(schema, 'unionField', 'update', { - apiId: 'row', - displayName: 'Row Deprecated', - parentApiId: 'DynamicRow', - description: 'This field is deprecated. Use Rows instead.', - }); - } - migrationAction(schema, 'unionField', 'create', { - displayName: 'Rows', - apiId: 'rows', - isList: true, - reverseField: { - modelApiIds: ['RowQuote', 'RowLinks', 'RowColumnOne'], - apiId: 'dynamicRows', - displayName: 'Dynamic Rows', - visibility: management_sdk_1.VisibilityTypes.Hidden, - isList: true, - }, - parentApiId: 'DynamicRow', - }, 'DynamicRow', 'model'); - migrationAction(schema, 'componentUnionField', 'create', { - displayName: 'Conditions', - apiId: 'conditions', - parentApiId: 'ConditionOr', - componentApiIds: ['ConditionText', 'ConditionNumber'], - isList: true, - }, 'ConditionOr', 'component'); - return client.run(true); -}; -exports.graphcommerce7to8 = graphcommerce7to8; diff --git a/packages/hygraph-cli/dist/migrations/graphcommerce8to9.js b/packages/hygraph-cli/dist/migrations/graphcommerce8to9.js deleted file mode 100644 index 45cd2866f8..0000000000 --- a/packages/hygraph-cli/dist/migrations/graphcommerce8to9.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.graphcommerce8to9 = void 0; -const management_sdk_1 = require("@hygraph/management-sdk"); -const migrationActionFactory_1 = require("../migrationActionFactory"); -const graphcommerce8to9 = async (schema, client) => { - const { migrationAction } = (0, migrationActionFactory_1.migrationActionFactory)(schema, client); - // Removes the deprecated 'Row' field which was deprecated in GC@7.1 - const hasRow = schema.models - .find((m) => m.apiId === 'DynamicRow') - ?.fields.some((f) => f.apiId === 'row'); - if (hasRow) { - migrationAction(schema, 'simpleField', 'delete', { - apiId: 'row', - parentApiId: 'DynamicRow', - }); - } - const hasRowCategory = schema.models.some((m) => m.apiId === 'RowCategory'); - // - if (!hasRowCategory) { - migrationAction(schema, 'model', 'create', { - apiId: 'RowCategory', - displayName: 'Row Category', - apiIdPlural: 'RowProductLists', - description: 'A model that displays a category', - }); - migrationAction(schema, 'simpleField', 'create', { - position: 1, - type: management_sdk_1.SimpleFieldType.String, - formConfig: { renderer: 'GCMS_SLUG', config: { isLowercase: true } }, - validations: { - String: { - matches: { - regex: '^[a-z0-9]+(?:[-/][a-z0-9]+)*$', - errorMessage: 'The category URL must be a valid slug', - }, - }, - }, - parentApiId: 'RowCategory', - displayName: 'Category URL', - apiId: 'categoryUrl', - description: 'The URL of the category, may include slashes', - isTitle: true, - isLocalized: true, - isRequired: true, - visibility: management_sdk_1.VisibilityTypes.ReadWrite, - }, 'RowCategory', 'model'); - migrationAction(schema, 'enumeration', 'create', { - displayName: 'Row Category Variant', - apiId: 'RowCategoryVariant', - values: [ - { displayName: 'Backstory', apiId: 'Backstory' }, - { displayName: 'Grid', apiId: 'Grid' }, - { displayName: 'Swipeable', apiId: 'Swipeable' }, - ], - }); - migrationAction(schema, 'enumerableField', 'create', { - displayName: 'Variant', - apiId: 'variant', - parentApiId: 'RowCategory', - enumerationApiId: 'RowCategoryVariant', - description: 'As what variant wil the RowCategory be displayed', - isRequired: true, - }, 'RowCategory', 'model'); - } - return client.run(true); -}; -exports.graphcommerce8to9 = graphcommerce8to9; diff --git a/packages/hygraph-cli/dist/migrations/index.js b/packages/hygraph-cli/dist/migrations/index.js deleted file mode 100644 index db2d200179..0000000000 --- a/packages/hygraph-cli/dist/migrations/index.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.availableMigrations = void 0; -const graphcommerce5to6_1 = require("./graphcommerce5to6"); -const graphcommerce6to7_1 = require("./graphcommerce6to7"); -const graphcommerce7to8_1 = require("./graphcommerce7to8"); -const graphcommerce8to9_1 = require("./graphcommerce8to9"); -exports.availableMigrations = [ - graphcommerce5to6_1.graphcommerce5to6, - graphcommerce6to7_1.graphcommerce6to7, - graphcommerce7to8_1.graphcommerce7to8, - graphcommerce8to9_1.graphcommerce8to9, -]; diff --git a/packages/hygraph-cli/dist/readSchema.js b/packages/hygraph-cli/dist/readSchema.js deleted file mode 100644 index 9f3513431f..0000000000 --- a/packages/hygraph-cli/dist/readSchema.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.readSchema = void 0; -const client_1 = require("@apollo/client"); -const readSchema = async (managementClient, projectId) => { - const { data } = await managementClient.query({ - query: (0, client_1.gql) ` - query getSchema($projectId: ID!) { - viewer { - project(id: $projectId) { - environment(name: "master") { - contentModel { - locales { - id - apiId - } - stages { - id - apiId - } - models { - apiId - apiIdPlural - fields { - apiId - } - } - components { - apiId - apiIdPlural - fields { - apiId - } - } - enumerations { - apiId - } - } - } - } - } - } - `, - variables: { - projectId, - }, - }); - return data; -}; -exports.readSchema = readSchema; diff --git a/packages/hygraph-cli/dist/types.js b/packages/hygraph-cli/dist/types.js deleted file mode 100644 index c8ad2e549b..0000000000 --- a/packages/hygraph-cli/dist/types.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); diff --git a/packages/hygraph-cli/dist/utils/getConfig.js b/packages/hygraph-cli/dist/utils/getConfig.js deleted file mode 100644 index 3279435dc7..0000000000 --- a/packages/hygraph-cli/dist/utils/getConfig.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getConfig = getConfig; -function getConfig(config) { - let { hygraphProjectId: projectId, hygraphWriteAccessToken: authToken, hygraphManagementApi: uri, hygraphEndpoint, } = config; - if (!authToken) { - throw new Error('Please provide GC_HYGRAPH_WRITE_ACCESS_TOKEN in your env file.'); - } - if (!projectId) { - projectId = new URL(hygraphEndpoint).pathname.split('/')?.[1]; - } - if (!uri) { - const endpoint = new URL(hygraphEndpoint); - endpoint.hostname = `management-${endpoint.hostname}`.replace('.cdn', ''); - endpoint.pathname = 'graphql'; - uri = endpoint.toString(); - } - return { projectId, authToken, uri }; -} diff --git a/packages/hygraph-cli/dist/utils/getEndpointUrl.js b/packages/hygraph-cli/dist/utils/getEndpointUrl.js deleted file mode 100644 index 8cd5e32944..0000000000 --- a/packages/hygraph-cli/dist/utils/getEndpointUrl.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getEnvironment = getEnvironment; -const graphql_tag_1 = __importDefault(require("graphql-tag")); -async function getEnvironment(client, config) { - const endpoints = await client.query({ - query: (0, graphql_tag_1.default) ` - query Environments($projectId: ID!) { - viewer { - id - project(id: $projectId) { - environments { - name - endpoint - migrations { - name - status - } - } - } - } - } - `, - variables: { projectId: config.projectId }, - errorPolicy: 'all', - }); - if (endpoints.errors) { - const isBadInput = endpoints.errors.some((e) => e.extensions?.code === 'BAD_USER_INPUT'); - if (isBadInput) { - throw Error(` - Could not find environment for projectId ${config.projectId}. - Please check your GC_HYGRAPH_PROJECT_ID in your env file. - `); - } - throw new Error(`An error occurred: ${endpoints.errors.map((e) => e.message).join('\n')}`); - } - const environment = endpoints.data.viewer.project.environments.find((env) => env.name === 'master') ?? - endpoints.data.viewer.project.environments?.[0]; - return environment; -} diff --git a/packages/hygraph-cli/dist/utils/getManagementClient.js b/packages/hygraph-cli/dist/utils/getManagementClient.js deleted file mode 100644 index d263128612..0000000000 --- a/packages/hygraph-cli/dist/utils/getManagementClient.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getManagementClient = getManagementClient; -const client_1 = require("@apollo/client"); -function getManagementClient(config) { - const { authToken: accessToken, uri } = config; - return new client_1.ApolloClient({ - link: new client_1.HttpLink({ - uri, - fetch, - headers: { Authorization: `Bearer ${accessToken}` }, - }), - cache: new client_1.InMemoryCache(), - }); -} diff --git a/packages/hygraph-cli/dist/utils/graphCommerceLog.js b/packages/hygraph-cli/dist/utils/graphCommerceLog.js deleted file mode 100644 index fdcc270c7f..0000000000 --- a/packages/hygraph-cli/dist/utils/graphCommerceLog.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.graphcommerceLog = exports.capitalize = void 0; -const capitalize = (word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(); -exports.capitalize = capitalize; -const graphcommerceLog = (message, type) => { - const color = { - error: '\x1b[31m\x1b[1m%s\x1b[0m', - warning: '\x1b[33m\x1b[1m%s\x1b[0m', - info: '\x1b[36m\x1b[1m%s\x1b[0m', - }; - // eslint-disable-next-line no-console - console.log(type ? color[type] : '', `${message}`); -}; -exports.graphcommerceLog = graphcommerceLog; diff --git a/packages/hygraph-cli/package.json b/packages/hygraph-cli/package.json index 5b81252b54..d2389a918f 100644 --- a/packages/hygraph-cli/package.json +++ b/packages/hygraph-cli/package.json @@ -3,16 +3,21 @@ "homepage": "https://www.graphcommerce.org/", "repository": "github:graphcommerce-org/graphcommerce", "version": "9.0.4-canary.9", + "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./dist/index.js" + } + }, "scripts": { - "dev": "tsc --preserveWatchOutput --watch", - "build": "tsc", - "prepack": "tsc" + "dev": "pkgroll --clean-dist --watch", + "build": "pkgroll --clean-dist", + "prepack": "pkgroll --clean-dist" }, - "type": "commonjs", - "main": "dist/index.js", - "types": "src/index.ts", "dependencies": { "@hygraph/management-sdk": "1.2.5", + "@types/prompts": "^2.4.9", "@whatwg-node/fetch": "^0.10.1", "graphql": "^16.10.0", "graphql-tag": "^2.12.6", @@ -27,7 +32,7 @@ "dotenv": "^16.1.4" }, "devDependencies": { - "@types/prompts": "^2.4.9", + "pkgroll": "^2.5.1", "typescript": "5.7.2" }, "sideEffects": false, diff --git a/packages/hygraph-cli/tsconfig.json b/packages/hygraph-cli/tsconfig.json index 473919f5fc..a607c2be66 100644 --- a/packages/hygraph-cli/tsconfig.json +++ b/packages/hygraph-cli/tsconfig.json @@ -11,7 +11,7 @@ "noLib": false, "strict": true, "resolveJsonModule": true, - "moduleResolution": "Node", - "module": "CommonJS" + "moduleResolution": "Bundler", + "module": "ESNext" } } From 446ee0c6932ed64298b77b406a195ede020d43e7 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:10:12 +0100 Subject: [PATCH 09/16] Make sure the cli package can be properly resolved with resolveDependenciesSync --- packages/cli/dist/bin/codegen.js | 6 +++--- packages/cli/dist/bin/mesh.js | 2 +- packages/cli/dist/index.js | 1 + packages/cli/package.json | 12 +++++++++--- 4 files changed, 14 insertions(+), 7 deletions(-) create mode 100755 packages/cli/dist/index.js diff --git a/packages/cli/dist/bin/codegen.js b/packages/cli/dist/bin/codegen.js index 2ed98d458e..52611440ae 100755 --- a/packages/cli/dist/bin/codegen.js +++ b/packages/cli/dist/bin/codegen.js @@ -1,9 +1,9 @@ #!/usr/bin/env node +import fs from 'node:fs/promises'; +import path from 'node:path'; import { resolveDependenciesSync, packageRoots } from '@graphcommerce/next-config'; import { cliError, loadCodegenConfig, runCli } from '@graphql-codegen/cli'; import dotenv from 'dotenv'; -import fs from 'node:fs/promises'; -import path from 'node:path'; import { rimraf } from 'rimraf'; import yaml from 'yaml'; @@ -19,7 +19,7 @@ async function cleanup() { }); } catch (e) { } - return void 0; + return undefined; } function appendDocumentLocations(conf, packages) { const documents = Array.isArray(conf.documents) ? conf.documents : [conf.documents]; diff --git a/packages/cli/dist/bin/mesh.js b/packages/cli/dist/bin/mesh.js index 07d73d1eb0..888d43d5c4 100755 --- a/packages/cli/dist/bin/mesh.js +++ b/packages/cli/dist/bin/mesh.js @@ -98,7 +98,7 @@ async function cleanup() { }); } catch (e) { } - return void 0; + return undefined; } const main = async () => { const baseConf = await findConfig({}); diff --git a/packages/cli/dist/index.js b/packages/cli/dist/index.js new file mode 100755 index 0000000000..8b13789179 --- /dev/null +++ b/packages/cli/dist/index.js @@ -0,0 +1 @@ + diff --git a/packages/cli/package.json b/packages/cli/package.json index 0140a200f9..71d870bf17 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -4,11 +4,17 @@ "repository": "github:graphcommerce-org/graphcommerce", "version": "9.0.4-canary.9", "scripts": { - "dev": "pkgroll --watch", - "build": "pkgroll", - "prepack": "pkgroll" + "dev": "pkgroll --clean-dist --watch", + "build": "pkgroll --clean-dist", + "prepack": "pkgroll --clean-dist" }, "type": "module", + "exports": { + ".": { + "types": "./src/index.ts", + "default": "./dist/index.js" + } + }, "bin": { "gc-gql-codegen": "dist/bin/codegen.js", "gc-mesh": "dist/bin/mesh.js", From cbf92b83a677c51c62dc723dcc7bf456a79125e4 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:12:26 +0100 Subject: [PATCH 10/16] Remove dependencies from `@graphcommerce/googletagmanager` and `@graphcommerce/googleanalytics` on Magento packages and make the datalayer optional --- .changeset/shiny-pillows-love.md | 6 ++++++ packages/googleanalytics/package.json | 15 +-------------- packages/googletagmanager/package.json | 5 +++++ 3 files changed, 12 insertions(+), 14 deletions(-) create mode 100644 .changeset/shiny-pillows-love.md diff --git a/.changeset/shiny-pillows-love.md b/.changeset/shiny-pillows-love.md new file mode 100644 index 0000000000..6e633ff3bf --- /dev/null +++ b/.changeset/shiny-pillows-love.md @@ -0,0 +1,6 @@ +--- +'@graphcommerce/googletagmanager': patch +'@graphcommerce/googleanalytics': patch +--- + +Remove dependencies from `@graphcommerce/googletagmanager` and `@graphcommerce/googleanalytics` on Magento packages and make the datalayer optional diff --git a/packages/googleanalytics/package.json b/packages/googleanalytics/package.json index 7779e32c2b..775e617639 100644 --- a/packages/googleanalytics/package.json +++ b/packages/googleanalytics/package.json @@ -15,10 +15,6 @@ "@graphcommerce/eslint-config-pwa": "^9.0.4-canary.9", "@graphcommerce/google-datalayer": "9.0.4-canary.9", "@graphcommerce/graphql-mesh": "^9.0.4-canary.9", - "@graphcommerce/magento-cart": "^9.0.4-canary.9", - "@graphcommerce/magento-cart-payment-method": "^9.0.4-canary.9", - "@graphcommerce/magento-cart-shipping-method": "^9.0.4-canary.9", - "@graphcommerce/magento-product": "^9.0.4-canary.9", "@graphcommerce/next-config": "^9.0.4-canary.9", "@graphcommerce/next-ui": "^9.0.4-canary.9", "@graphcommerce/prettier-config-pwa": "^9.0.4-canary.9", @@ -29,16 +25,7 @@ "react-dom": "^18.2.0" }, "peerDependenciesMeta": { - "@graphcommerce/magento-cart": { - "optional": true - }, - "@graphcommerce/magento-cart-payment-method": { - "optional": true - }, - "@graphcommerce/magento-cart-shipping-method": { - "optional": true - }, - "@graphcommerce/magento-product": { + "@graphcommerce/google-datalayer": { "optional": true } } diff --git a/packages/googletagmanager/package.json b/packages/googletagmanager/package.json index d80a346bb0..5e22e11516 100644 --- a/packages/googletagmanager/package.json +++ b/packages/googletagmanager/package.json @@ -24,5 +24,10 @@ "next": "*", "react": "^18.2.0", "react-dom": "^18.2.0" + }, + "peerDependenciesMeta": { + "@graphcommerce/google-datalayer": { + "optional": true + } } } From 2085f0b30dfadd9ab589fde962f59e87b3f30b34 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:14:29 +0100 Subject: [PATCH 11/16] Forward `` component to `` --- .changeset/green-guests-kick.md | 5 +++++ packages/hygraph-ui/components/Asset/Asset.tsx | 4 ++-- 2 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 .changeset/green-guests-kick.md diff --git a/.changeset/green-guests-kick.md b/.changeset/green-guests-kick.md new file mode 100644 index 0000000000..b18c959c7f --- /dev/null +++ b/.changeset/green-guests-kick.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/hygraph-ui': patch +--- + +Forward `` component to `` diff --git a/packages/hygraph-ui/components/Asset/Asset.tsx b/packages/hygraph-ui/components/Asset/Asset.tsx index 0404328311..988c0f0ed8 100644 --- a/packages/hygraph-ui/components/Asset/Asset.tsx +++ b/packages/hygraph-ui/components/Asset/Asset.tsx @@ -22,7 +22,7 @@ export type AssetProps = { } & Omit export const Asset = memo((props) => { - const { asset, sx = [], ...imgProps } = props + const { asset, sx = [], unoptimized = false, ...imgProps } = props if (isImage(asset)) { const { url, height, mimeType, size, width, alt, ...assetProps } = asset @@ -34,7 +34,7 @@ export const Asset = memo((props) => { alt={alt ?? undefined} {...imgProps} {...assetProps} - unoptimized={mimeType === 'image/svg+xml'} + unoptimized={typeof unoptimized === 'boolean' ? unoptimized : mimeType === 'image/svg+xml'} sx={[...(Array.isArray(sx) ? sx : [sx])]} /> ) From cf9eafb9d71991852510f632c692679810b9e76f Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:23:51 +0100 Subject: [PATCH 12/16] Prepare the RichTex for embed and code-block --- .changeset/gold-eels-report.md | 5 +++++ packages/hygraph-ui/components/RichText/RichText.tsx | 5 +++-- .../components/RichText/defaultRenderers.tsx | 10 ++++++++++ packages/hygraph-ui/components/RichText/types.ts | 12 ++++++++++++ 4 files changed, 30 insertions(+), 2 deletions(-) create mode 100644 .changeset/gold-eels-report.md diff --git a/.changeset/gold-eels-report.md b/.changeset/gold-eels-report.md new file mode 100644 index 0000000000..a8c373f07e --- /dev/null +++ b/.changeset/gold-eels-report.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/hygraph-ui': patch +--- + +Prepare the RichTex for embed and code-block diff --git a/packages/hygraph-ui/components/RichText/RichText.tsx b/packages/hygraph-ui/components/RichText/RichText.tsx index 2ebc505317..3eed798afc 100644 --- a/packages/hygraph-ui/components/RichText/RichText.tsx +++ b/packages/hygraph-ui/components/RichText/RichText.tsx @@ -56,10 +56,11 @@ function RenderText({ last, ...textProps }: TextNode & AdditionalProps) { - let type: 'bold' | 'italic' | 'underlined' | undefined + let type: 'bold' | 'italic' | 'underlined' | 'code' | undefined if (textProps.bold) type = 'bold' if (textProps.italic) type = 'italic' + if (textProps.code) type = 'code' if (textProps.underlined) type = 'underlined' const sx = useRenderProps({ first, last, sxRenderer }, type) @@ -98,7 +99,7 @@ function RenderNode(node: ElementOrTextNode & AdditionalProps) { return null } -function RenderChildren({ +export function RenderChildren({ childNodes, noMargin, ...props diff --git a/packages/hygraph-ui/components/RichText/defaultRenderers.tsx b/packages/hygraph-ui/components/RichText/defaultRenderers.tsx index d9aa5521d2..1651c0c535 100644 --- a/packages/hygraph-ui/components/RichText/defaultRenderers.tsx +++ b/packages/hygraph-ui/components/RichText/defaultRenderers.tsx @@ -55,4 +55,14 @@ export const defaultRenderers: Renderers = { italic: (props) => , underlined: (props) => , class: (props) => , + 'code-block': (props) => ( + + + + ), + embed: ({ id, nodeId, nodeType, children, isInline, ...props }) => ( + + {id} {nodeId} {nodeType} {children} + + ), } diff --git a/packages/hygraph-ui/components/RichText/types.ts b/packages/hygraph-ui/components/RichText/types.ts index 8b7a91b822..0f5f0adff2 100644 --- a/packages/hygraph-ui/components/RichText/types.ts +++ b/packages/hygraph-ui/components/RichText/types.ts @@ -21,6 +21,7 @@ type BaseElementTypes = | 'table_row' | 'table_cell' | 'code' + | 'code-block' | 'bold' | 'italic' | 'underlined' @@ -80,6 +81,14 @@ type IframeElement = { height?: number } +type EmbedElement = { + type: 'embed' + id: string + nodeId: string + nodeType: string + isInline?: boolean +} + export type ElementNode = | SimpleElement | LinkElement @@ -87,6 +96,8 @@ export type ElementNode = | VideoElement | IframeElement | ClassElement + | EmbedElement + export type ElementOrTextNode = ElementNode | TextNode type RendererBase = { sx?: SxProps; children?: React.ReactNode } @@ -102,6 +113,7 @@ export type Renderers = { video: Renderer iframe: Renderer class: Renderer + embed: Renderer } export type SxRenderer = { From 935f8f9ebe5e79b336e56d40cb1ec96ce17b84d7 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:24:21 +0100 Subject: [PATCH 13/16] Remove dependency on Magento for @graphcommerec/react-hook-form --- .changeset/beige-suns-know.md | 5 ++ .../__mocks__/TestShippingAddressForm.graphql | 16 ------ .../__tests__/useFormGqlMutation.tsx | 35 ------------- .../__tests__/useGqlDocumentHandler.tsx | 52 ------------------- 4 files changed, 5 insertions(+), 103 deletions(-) create mode 100644 .changeset/beige-suns-know.md delete mode 100644 packages/react-hook-form/__mocks__/TestShippingAddressForm.graphql delete mode 100644 packages/react-hook-form/__tests__/useFormGqlMutation.tsx delete mode 100644 packages/react-hook-form/__tests__/useGqlDocumentHandler.tsx diff --git a/.changeset/beige-suns-know.md b/.changeset/beige-suns-know.md new file mode 100644 index 0000000000..a3cfafb8d4 --- /dev/null +++ b/.changeset/beige-suns-know.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/react-hook-form': patch +--- + +Remove dependency on Magento for @graphcommerec/react-hook-form diff --git a/packages/react-hook-form/__mocks__/TestShippingAddressForm.graphql b/packages/react-hook-form/__mocks__/TestShippingAddressForm.graphql deleted file mode 100644 index 83da7b97eb..0000000000 --- a/packages/react-hook-form/__mocks__/TestShippingAddressForm.graphql +++ /dev/null @@ -1,16 +0,0 @@ -mutation TestShippingAddressForm( - $cartId: String! - $address: CartAddressInput! - $customerNote: String = "joi" -) { - setShippingAddressesOnCart( - input: { - cart_id: $cartId - shipping_addresses: [{ address: $address, customer_notes: $customerNote }] - } - ) { - cart { - id - } - } -} diff --git a/packages/react-hook-form/__tests__/useFormGqlMutation.tsx b/packages/react-hook-form/__tests__/useFormGqlMutation.tsx deleted file mode 100644 index 8c6b4a7b63..0000000000 --- a/packages/react-hook-form/__tests__/useFormGqlMutation.tsx +++ /dev/null @@ -1,35 +0,0 @@ -/* eslint-disable @typescript-eslint/ban-ts-comment */ -import { ApolloClient, InMemoryCache } from '@apollo/client' -import { renderHook } from '@testing-library/react' -import { TestShippingAddressFormDocument } from '../__mocks__/TestShippingAddressForm.gql' -import { useFormGqlMutation } from '../src/useFormGqlMutation' - -describe('useFormGqlMutation', () => { - const { result } = renderHook(() => - useFormGqlMutation( - TestShippingAddressFormDocument, - {}, - { - client: new ApolloClient({ - cache: new InMemoryCache(), - }), - }, - ), - ) - - it('can register stuff', () => { - result.current.register('address.telephone') - result.current.register('customerNote') - result.current.register('address.street.0') - - // @ts-expect-error should not be posssible - result.current.register('address.street.hoi') - }) - - it('extracts required fields correctly', () => { - expect(result.current.required).toEqual({ address: true, cartId: true, customerNote: false }) - }) - it('extracts defaults correctly', () => { - expect(result.current.defaultVariables).toEqual({ customerNote: 'joi' }) - }) -}) diff --git a/packages/react-hook-form/__tests__/useGqlDocumentHandler.tsx b/packages/react-hook-form/__tests__/useGqlDocumentHandler.tsx deleted file mode 100644 index 3b11bb4ac0..0000000000 --- a/packages/react-hook-form/__tests__/useGqlDocumentHandler.tsx +++ /dev/null @@ -1,52 +0,0 @@ -import { TestShippingAddressFormDocument } from '../__mocks__/TestShippingAddressForm.gql' -import { handlerFactory } from '../src/useGqlDocumentHandler' - -describe('useGqlDocumentHandler', () => { - const { - required, - defaultVariables: defaults, - encode, - } = handlerFactory(TestShippingAddressFormDocument) - - const address = { - cartId: '12', - customerNote: 'hoi', - address: { - firstname: 'Firstname', - lastname: 'Lastname', - company: 'GraphComemrce', - country_code: 'NL', - street: ['Streetline 1', 'Streetline 2'], - city: 'City', - telephone: '0987654321', - postcode: '1234AB', - save_in_address_book: true, - }, - } - - it('extracts required fields correctly', () => { - expect(required).toEqual({ address: true, cartId: true, customerNote: false }) - }) - it('extracts defaults correctly', () => { - expect(defaults).toEqual({ customerNote: 'joi' }) - }) - - it('encodes objects correctly', () => { - const result = encode(address) - expect(result).toEqual({ - cartId: '12', - customerNote: 'hoi', - address: { - firstname: 'Firstname', - lastname: 'Lastname', - company: 'GraphComemrce', - country_code: 'NL', - street: ['Streetline 1', 'Streetline 2'], - city: 'City', - telephone: '0987654321', - postcode: '1234AB', - save_in_address_book: true, - }, - }) - }) -}) From 9825f59b8626c315e6092950faceeab4311a5424 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:38:56 +0100 Subject: [PATCH 14/16] Remove rewriteLegacyEnv as that hasn't been used for years --- .changeset/spicy-shrimps-battle.md | 5 + .../config/utils/mergeEnvIntoConfig.ts | 13 +- .../config/utils/rewriteLegancyEnv.ts | 79 ----------- packagesDev/next-config/dist/index.js | 110 +-------------- .../next-config/src/config/loadConfig.ts | 11 +- .../src/config/utils/rewriteLegacyEnv.ts | 125 ------------------ 6 files changed, 21 insertions(+), 322 deletions(-) create mode 100644 .changeset/spicy-shrimps-battle.md delete mode 100644 packagesDev/next-config/__tests__/config/utils/rewriteLegancyEnv.ts delete mode 100644 packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts diff --git a/.changeset/spicy-shrimps-battle.md b/.changeset/spicy-shrimps-battle.md new file mode 100644 index 0000000000..f724dfa45c --- /dev/null +++ b/.changeset/spicy-shrimps-battle.md @@ -0,0 +1,5 @@ +--- +'@graphcommerce/next-config': patch +--- + +Remove rewriteLegacyEnv as that hasn't been used for years diff --git a/packagesDev/next-config/__tests__/config/utils/mergeEnvIntoConfig.ts b/packagesDev/next-config/__tests__/config/utils/mergeEnvIntoConfig.ts index 493d789250..067f2183b4 100644 --- a/packagesDev/next-config/__tests__/config/utils/mergeEnvIntoConfig.ts +++ b/packagesDev/next-config/__tests__/config/utils/mergeEnvIntoConfig.ts @@ -5,7 +5,18 @@ import { } from '../../../src/config/utils/mergeEnvIntoConfig' import type { GraphCommerceConfig } from '../../../src/generated/config' import { GraphCommerceConfigSchema } from '../../../src/generated/config' -import { removeColor } from './rewriteLegancyEnv' + +export const removeColor = (str: string) => + str.replace( + new RegExp( + [ + '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', + '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))', + ].join('|'), + 'g', + ), + '', + ) const env = { GC_ADVANCED_FILTERS: '0', diff --git a/packagesDev/next-config/__tests__/config/utils/rewriteLegancyEnv.ts b/packagesDev/next-config/__tests__/config/utils/rewriteLegancyEnv.ts deleted file mode 100644 index 9391adbf74..0000000000 --- a/packagesDev/next-config/__tests__/config/utils/rewriteLegancyEnv.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { formatAppliedEnv } from '../../../src/config/utils/mergeEnvIntoConfig' -import { rewriteLegacyEnv } from '../../../src/config/utils/rewriteLegacyEnv' -import type { GraphCommerceConfig } from '../../../src/generated/config' -import { GraphCommerceConfigSchema } from '../../../src/generated/config' - -export const removeColor = (str: string) => - str.replace( - new RegExp( - [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-nq-uy=><~]))', - ].join('|'), - 'g', - ), - '', - ) -it('rewrites legacy env', () => { - const configFile: GraphCommerceConfig = { - storefront: [{ locale: 'en', hygraphLocales: ['en'], magentoStoreCode: 'en_us' }], - productFiltersPro: false, - canonicalBaseUrl: 'https://example.com', - hygraphEndpoint: 'https://example.com', - magentoEndpoint: 'https://example.com', - previewSecret: 'secret', - robotsAllow: true, - magentoVersion: 246, - } - const legacyEnv = { - GRAPHCMS_URL: 'https://api-eu-central-1.graphcms.com/v2/ckhx7xadya6xs01yxdujt8i80/master', - MAGENTO_ENDPOINT: 'https://backend.reachdigital.dev/graphql', - NEXT_PUBLIC_GRAPHQL_ENDPOINT: 'http://localhost:3000/api/graphql', - IMAGE_DOMAINS: 'backend.reachdigital.dev,media.graphcms.com,media.graphassets.com', - NEXT_PUBLIC_LOCALE_STORES: - '{"en-us": "en_US", "nl-nl": "nl_NL", "fr-be": "fr_BE", "nl-be": "nl_BE", "en-gb": "en_GB", "en-ca": "en_CA"}', - NEXT_PUBLIC_SITE_URL: 'https://graphcommerce.vercel.app/', - NEXT_PUBLIC_GTM_ID: '123', - NEXT_PUBLIC_GOOGLE_ANALYTICS: - '{"en-us": "G-111", "nl-nl": "G-222", "fr-be": "G-333", "nl-be": "G-444", "en-gb":"G-555", "en-ca": "G-666"}', - NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: '', - NEXT_PUBLIC_DISPLAY_INCL_TAX: 'nl,fr-be,nl-be,en-gb,eu', - PREVIEW_SECRET: 'dya6xs01y', - DEMO_MAGENTO_GRAPHCOMMERCE: '1', - SOME_KEY: 'bla', - } - const [, appliedRewrite] = rewriteLegacyEnv(GraphCommerceConfigSchema(), legacyEnv, configFile) - expect(removeColor(formatAppliedEnv(appliedRewrite))).toMatchInlineSnapshot(` - "warning - Loaded GraphCommerce env variables - ‼ GRAPHCMS_URL => should be renamed to GC_HYGRAPH_ENDPOINT='https://api-eu-central-1.graphcms.com/v2/ckhx7xadya6xs01yxdujt8i80/master' - ‼ MAGENTO_ENDPOINT => should be renamed to GC_MAGENTO_ENDPOINT='https://backend.reachdigital.dev/graphql' - ‼ NEXT_PUBLIC_GRAPHQL_ENDPOINT => should be removed - ‼ IMAGE_DOMAINS => should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options - ‼ NEXT_PUBLIC_LOCALE_STORES => env variable is is modified, rewritten to GC_STOREFRONT. - ‼ NEXT_PUBLIC_SITE_URL => should be renamed to GC_CANONICAL_BASE_URL='https://graphcommerce.vercel.app/' - ‼ NEXT_PUBLIC_GTM_ID => should be renamed to GC_GOOGLE_TAGMANAGER_ID='123' - ‼ NEXT_PUBLIC_GOOGLE_ANALYTICS => should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID - ‼ NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY => should be renamed to GC_GOOGLE_RECAPTCHA_KEY='' - ‼ NEXT_PUBLIC_DISPLAY_INCL_TAX => env variable is renamed, move to configuration: cartDisplayPricesInclTax - ‼ PREVIEW_SECRET => should be renamed to GC_PREVIEW_SECRET='dya6xs01y' - ‼ DEMO_MAGENTO_GRAPHCOMMERCE => should be renamed to GC_DEMO_MODE='1' - ~ GC_CANONICAL_BASE_URL => canonicalBaseUrl - + GC_DEMO_MODE => demoMode - + GC_GOOGLE_ANALYTICS_ID => googleAnalyticsId - + GC_GOOGLE_RECAPTCHA_KEY => googleRecaptchaKey - + GC_GOOGLE_TAGMANAGER_ID => googleTagmanagerId - ~ GC_HYGRAPH_ENDPOINT => hygraphEndpoint - ~ GC_MAGENTO_ENDPOINT => magentoEndpoint - ~ GC_PREVIEW_SECRET => previewSecret - = GC_STOREFRONT => storefront: (ignored) - + GC_STOREFRONT_0_GOOGLE_ANALYTICS_ID => storefront.[0].googleAnalyticsId - + GC_STOREFRONT_1_GOOGLE_ANALYTICS_ID => storefront.[1].googleAnalyticsId - + GC_STOREFRONT_2_CART_DISPLAY_PRICES_INCL_TAX => storefront.[2].cartDisplayPricesInclTax - + GC_STOREFRONT_2_GOOGLE_ANALYTICS_ID => storefront.[2].googleAnalyticsId - + GC_STOREFRONT_3_CART_DISPLAY_PRICES_INCL_TAX => storefront.[3].cartDisplayPricesInclTax - + GC_STOREFRONT_3_GOOGLE_ANALYTICS_ID => storefront.[3].googleAnalyticsId - + GC_STOREFRONT_4_CART_DISPLAY_PRICES_INCL_TAX => storefront.[4].cartDisplayPricesInclTax - + GC_STOREFRONT_4_GOOGLE_ANALYTICS_ID => storefront.[4].googleAnalyticsId - + GC_STOREFRONT_5_GOOGLE_ANALYTICS_ID => storefront.[5].googleAnalyticsId" - `) -}) diff --git a/packagesDev/next-config/dist/index.js b/packagesDev/next-config/dist/index.js index 9442f70163..8260b6baa2 100755 --- a/packagesDev/next-config/dist/index.js +++ b/packagesDev/next-config/dist/index.js @@ -667,109 +667,6 @@ function formatAppliedEnv(applyResult) { return [header, ...lines].join("\n"); } -function rewriteLegacyEnv(schema, env, config = {}) { - const clonedEnv = lodash.cloneDeep(env); - const applied = []; - function renamedTo(to) { - return (envVar, envValue) => { - applied.push({ - warning: [`should be renamed to ${to}='${envValue}'`], - envVar, - envValue - }); - clonedEnv[to] = envValue; - }; - } - function notUsed() { - return (envVar, envValue) => { - applied.push({ - warning: ["should be removed"], - envVar, - envValue - }); - }; - } - const parsers = { - MAGENTO_ENDPOINT: renamedTo("GC_MAGENTO_ENDPOINT"), - GRAPHCMS_URL: renamedTo("GC_HYGRAPH_ENDPOINT"), - NEXT_PUBLIC_GRAPHQL_ENDPOINT: notUsed(), - IMAGE_DOMAINS: (envVar, envValue) => { - applied.push({ - warning: [ - "should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options" - ], - envVar, - envValue - }); - }, - NEXT_PUBLIC_LOCALE_STORES: (envVar, envValue) => { - const parsed = JSON.parse(envValue); - applied.push({ - warning: ["env variable is is modified, rewritten to GC_STOREFRONT."], - envVar, - envValue - }); - clonedEnv.GC_STOREFRONT = JSON.stringify( - Object.entries(parsed).map(([locale, magentoStoreCode], index) => { - if (!config.storefront) config.storefront = []; - config.storefront[index] = { ...config.storefront[index], locale, magentoStoreCode }; - return { locale, magentoStoreCode }; - }) - ); - }, - NEXT_PUBLIC_SITE_URL: renamedTo("GC_CANONICAL_BASE_URL"), - NEXT_PUBLIC_GTM_ID: renamedTo("GC_GOOGLE_TAGMANAGER_ID"), - NEXT_PUBLIC_GOOGLE_ANALYTICS: (envVar, envValue) => { - if (envValue.startsWith("{")) { - const parsed = JSON.parse(envValue); - clonedEnv.GC_GOOGLE_ANALYTICS_ID = "enabled"; - if (!config.storefront) config.storefront = []; - config.storefront.forEach((storefront, index) => { - if (parsed[storefront.locale]) { - clonedEnv[`GC_STOREFRONT_${index}_GOOGLE_ANALYTICS_ID`] = parsed[storefront.locale]; - } - }); - applied.push({ - warning: ["should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID"], - envVar, - envValue - }); - return; - } - }, - NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: renamedTo("GC_GOOGLE_RECAPTCHA_KEY"), - NEXT_PUBLIC_DISPLAY_INCL_TAX: (envVar, envValue) => { - const inclTax = envValue.split(",").map((i) => i.trim()); - if (!config.storefront) config.storefront = []; - config.storefront.forEach((storefront, index) => { - if (!inclTax.includes(storefront.locale)) return; - clonedEnv[`GC_STOREFRONT_${index}_CART_DISPLAY_PRICES_INCL_TAX`] = "1"; - }); - applied.push({ - warning: ["env variable is renamed, move to configuration: cartDisplayPricesInclTax"], - envVar, - envValue - }); - clonedEnv.GC_DISPLAY_PRICES_INCL_TAX = envValue; - }, - PREVIEW_SECRET: renamedTo("GC_PREVIEW_SECRET"), - DEMO_MAGENTO_GRAPHCOMMERCE: renamedTo("GC_DEMO_MODE") - }; - if (env.SKIP_MIGRATION === "1" || env.SKIP_MIGRATION === "true") { - return mergeEnvIntoConfig(schema, config, clonedEnv); - } - Object.entries(env).forEach(([key, value]) => { - if (value === undefined) return; - try { - parsers[key]?.(key, value); - } catch (e) { - console.error(`Error parsing ${key}`, e); - } - }); - const [newConfig, envApplied] = mergeEnvIntoConfig(schema, config, clonedEnv); - return [newConfig, [...applied, ...envApplied]]; -} - function flattenKeys(value, initialPathPrefix, stringify) { if (value === null || value === undefined || typeof value === "number") { return { [initialPathPrefix]: value }; @@ -823,12 +720,7 @@ function loadConfig(cwd) { } confFile ||= {}; const schema = GraphCommerceConfigSchema(); - const [mergedConfig, applyResult] = rewriteLegacyEnv( - schema, - process.env, - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - confFile - ); + const [mergedConfig, applyResult] = mergeEnvIntoConfig(schema, confFile, process.env); if (applyResult.length > 0 && isMainProcess) console.log(formatAppliedEnv(applyResult)); const finalParse = schema.parse(mergedConfig); if (process.env.DEBUG && isMainProcess) { diff --git a/packagesDev/next-config/src/config/loadConfig.ts b/packagesDev/next-config/src/config/loadConfig.ts index 9f70d17c13..bf4843204c 100644 --- a/packagesDev/next-config/src/config/loadConfig.ts +++ b/packagesDev/next-config/src/config/loadConfig.ts @@ -3,8 +3,7 @@ import { cosmiconfigSync } from 'cosmiconfig' import type { GraphCommerceConfig } from '../generated/config' import { GraphCommerceConfigSchema } from '../generated/config' import { demoConfig } from './demoConfig' -import { formatAppliedEnv } from './utils/mergeEnvIntoConfig' -import { rewriteLegacyEnv } from './utils/rewriteLegacyEnv' +import { formatAppliedEnv, mergeEnvIntoConfig } from './utils/mergeEnvIntoConfig' export * from './utils/configToImportMeta' export * from './utils/replaceConfigInString' @@ -27,12 +26,8 @@ export function loadConfig(cwd: string): GraphCommerceConfig { confFile ||= {} const schema = GraphCommerceConfigSchema() - const [mergedConfig, applyResult] = rewriteLegacyEnv( - schema, - process.env, - // eslint-disable-next-line @typescript-eslint/no-unsafe-argument - confFile, - ) + // eslint-disable-next-line @typescript-eslint/no-unsafe-argument + const [mergedConfig, applyResult] = mergeEnvIntoConfig(schema, confFile, process.env) if (applyResult.length > 0 && isMainProcess) console.log(formatAppliedEnv(applyResult)) diff --git a/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts b/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts deleted file mode 100644 index fa0e1421ec..0000000000 --- a/packagesDev/next-config/src/config/utils/rewriteLegacyEnv.ts +++ /dev/null @@ -1,125 +0,0 @@ -import lodash from 'lodash' -import type { GraphCommerceConfig } from '../../generated/config' -import type { ApplyResult, ZodNode } from './mergeEnvIntoConfig' -import { mergeEnvIntoConfig } from './mergeEnvIntoConfig' - -export function rewriteLegacyEnv( - schema: ZodNode, - env: Record, - config: Partial = {}, -) { - const clonedEnv: Record = lodash.cloneDeep(env) - const applied: ApplyResult = [] - - function renamedTo(to: string) { - return (envVar: string, envValue: string) => { - applied.push({ - warning: [`should be renamed to ${to}='${envValue}'`], - envVar, - envValue, - }) - clonedEnv[to] = envValue - } - } - - function notUsed() { - return (envVar: string, envValue: string) => { - applied.push({ - warning: ['should be removed'], - envVar, - envValue, - }) - } - } - - const parsers: Record void> = { - MAGENTO_ENDPOINT: renamedTo('GC_MAGENTO_ENDPOINT'), - GRAPHCMS_URL: renamedTo('GC_HYGRAPH_ENDPOINT'), - NEXT_PUBLIC_GRAPHQL_ENDPOINT: notUsed(), - IMAGE_DOMAINS: (envVar: string, envValue: string) => { - applied.push({ - warning: [ - 'should be removed: will automatically add the Magento/Hygraph URL. For more advanced configurations, see: https://nextjs.org/docs/api-reference/next/image#configuration-options', - ], - envVar, - envValue, - }) - }, - NEXT_PUBLIC_LOCALE_STORES: (envVar: string, envValue: string) => { - const parsed = JSON.parse(envValue) as Record - - applied.push({ - warning: ['env variable is is modified, rewritten to GC_STOREFRONT.'], - envVar, - envValue, - }) - - clonedEnv.GC_STOREFRONT = JSON.stringify( - Object.entries(parsed).map(([locale, magentoStoreCode], index) => { - if (!config.storefront) config.storefront = [] - config.storefront[index] = { ...config.storefront[index], locale, magentoStoreCode } - return { locale, magentoStoreCode } - }), - ) - }, - NEXT_PUBLIC_SITE_URL: renamedTo('GC_CANONICAL_BASE_URL'), - NEXT_PUBLIC_GTM_ID: renamedTo('GC_GOOGLE_TAGMANAGER_ID'), - NEXT_PUBLIC_GOOGLE_ANALYTICS: (envVar: string, envValue: string) => { - if (envValue.startsWith('{')) { - const parsed = JSON.parse(envValue) as Record - - clonedEnv.GC_GOOGLE_ANALYTICS_ID = 'enabled' - if (!config.storefront) config.storefront = [] - config.storefront.forEach((storefront, index) => { - if (parsed[storefront.locale]) { - clonedEnv[`GC_STOREFRONT_${index}_GOOGLE_ANALYTICS_ID`] = parsed[storefront.locale] - } - }) - - applied.push({ - warning: ['should be rewritten to GC_STOREFRONT_*_GOOGLE_ANALYTICS_ID'], - envVar, - envValue, - }) - - return - } - renamedTo('GC_GOOGLE_ANALYTICS_ID') - }, - NEXT_PUBLIC_GOOGLE_RECAPTCHA_V3_SITE_KEY: renamedTo('GC_GOOGLE_RECAPTCHA_KEY'), - NEXT_PUBLIC_DISPLAY_INCL_TAX: (envVar: string, envValue: string) => { - const inclTax = envValue.split(',').map((i) => i.trim()) - - if (!config.storefront) config.storefront = [] - config.storefront.forEach((storefront, index) => { - if (!inclTax.includes(storefront.locale)) return - clonedEnv[`GC_STOREFRONT_${index}_CART_DISPLAY_PRICES_INCL_TAX`] = '1' - }) - - applied.push({ - warning: ['env variable is renamed, move to configuration: cartDisplayPricesInclTax'], - envVar, - envValue, - }) - clonedEnv.GC_DISPLAY_PRICES_INCL_TAX = envValue - }, - PREVIEW_SECRET: renamedTo('GC_PREVIEW_SECRET'), - DEMO_MAGENTO_GRAPHCOMMERCE: renamedTo('GC_DEMO_MODE'), - } - - if (env.SKIP_MIGRATION === '1' || env.SKIP_MIGRATION === 'true') { - return mergeEnvIntoConfig(schema, config, clonedEnv) - } - - Object.entries(env).forEach(([key, value]) => { - if (value === undefined) return - try { - parsers[key]?.(key, value) - } catch (e) { - console.error(`Error parsing ${key}`, e) - } - }) - - const [newConfig, envApplied] = mergeEnvIntoConfig(schema, config, clonedEnv) - return [newConfig, [...applied, ...envApplied] as ApplyResult] as const -} From 3aead79de6fb240113debe0bc216b64552b51b89 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:39:33 +0100 Subject: [PATCH 15/16] Dependency sort order in tests --- .../__tests__/interceptors/findPlugins.ts | 543 +++++++++--------- .../utils/resolveDependenciesSync.ts | 88 +-- 2 files changed, 314 insertions(+), 317 deletions(-) diff --git a/packagesDev/next-config/__tests__/interceptors/findPlugins.ts b/packagesDev/next-config/__tests__/interceptors/findPlugins.ts index 5074976851..387887b1fc 100644 --- a/packagesDev/next-config/__tests__/interceptors/findPlugins.ts +++ b/packagesDev/next-config/__tests__/interceptors/findPlugins.ts @@ -1,6 +1,5 @@ import type { GraphCommerceConfig } from '../../src/generated/config' import { findPlugins } from '../../src/interceptors/findPlugins' - const projectRoot = `${process.cwd()}/examples/magento-graphcms` it('finds plugins', () => { const fakeconfig = { @@ -26,147 +25,154 @@ it('finds plugins', () => { }, { "enabled": true, - "ifConfig": "demoMode", - "sourceExport": "RowLinks", - "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoRowLinks", - "targetExport": "RowLinks", - "targetModule": "@graphcommerce/next-ui", - "type": "component", + "sourceExport": "meshConfig", + "sourceModule": "@graphcommerce/algolia-recommend/plugins/meshConfigAlgoliaRecommend", + "targetExport": "meshConfig", + "targetModule": "@graphcommerce/graphql-mesh/meshConfig", + "type": "function", }, { "enabled": true, - "ifConfig": "demoMode", - "sourceExport": "RecentlyViewedProducts", - "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoRecentlyViewedProducts", - "targetExport": "RecentlyViewedProducts", - "targetModule": "@graphcommerce/magento-recently-viewed-products", - "type": "component", + "sourceExport": "getSearchSuggestionsInput", + "sourceModule": "@graphcommerce/algolia-personalization/plugins/getSearchSuggestionsInputPersonalization", + "targetExport": "getSearchSuggestionsInput", + "targetModule": "@graphcommerce/algolia-products", + "type": "function", }, { "enabled": true, - "ifConfig": "demoMode", - "sourceExport": "ProductListItemConfigurable", - "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoProductListItemConfigurable", - "targetExport": "ProductListItemConfigurable", - "targetModule": "@graphcommerce/magento-product-configurable", - "type": "component", + "sourceExport": "getSearchResultsInput", + "sourceModule": "@graphcommerce/algolia-personalization/plugins/getSearchResultsInputPersonalization", + "targetExport": "getSearchResultsInput", + "targetModule": "@graphcommerce/algolia-products", + "type": "function", }, { "enabled": true, - "ifConfig": "googleAnalyticsId", - "sourceExport": "sendEvent", - "sourceModule": "@graphcommerce/googleanalytics/plugins/gtagEvent", - "targetExport": "sendEvent", + "sourceExport": "getPrivateQueryContext", + "sourceModule": "@graphcommerce/algolia-personalization/plugins/InContextInputAlgoliaUserToken", + "targetExport": "getPrivateQueryContext", + "targetModule": "@graphcommerce/graphql", + "type": "function", + }, + { + "enabled": true, + "sourceExport": "usePrivateQueryContext", + "sourceModule": "@graphcommerce/algolia-personalization/plugins/InContextInputAlgoliaUserToken", + "targetExport": "usePrivateQueryContext", + "targetModule": "@graphcommerce/graphql", + "type": "function", + }, + { + "enabled": true, + "sourceExport": "useSendEvent", + "sourceModule": "@graphcommerce/algolia-insights/plugins/useSendEventAlgolia", + "targetExport": "useSendEvent", "targetModule": "@graphcommerce/google-datalayer", "type": "function", }, { "enabled": true, - "ifConfig": "googleAnalyticsId", - "sourceExport": "DocumentHeadEnd", - "sourceModule": "@graphcommerce/googleanalytics/plugins/GoogleAnalyticsTag", - "targetExport": "DocumentHeadEnd", - "targetModule": "@graphcommerce/next-ui/server", - "type": "component", + "sourceExport": "meshConfig", + "sourceModule": "@graphcommerce/algolia-insights/plugins/meshConfigAlgoliaInsights", + "targetExport": "meshConfig", + "targetModule": "@graphcommerce/graphql-mesh/meshConfig", + "type": "function", }, { "enabled": true, - "ifConfig": "googleRecaptchaKey", - "sourceExport": "GraphQLProvider", - "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaGraphQLProvider", - "targetExport": "GraphQLProvider", - "targetModule": "@graphcommerce/graphql", - "type": "component", + "sourceExport": "getSearchSuggestionsInput", + "sourceModule": "@graphcommerce/algolia-insights/plugins/getSearchSuggestionsInputInsights", + "targetExport": "getSearchSuggestionsInput", + "targetModule": "@graphcommerce/algolia-products", + "type": "function", }, { "enabled": true, - "ifConfig": "googleRecaptchaKey", - "sourceExport": "ApolloErrorSnackbar", - "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorSnackbar", - "targetExport": "ApolloErrorSnackbar", - "targetModule": "@graphcommerce/ecommerce-ui", - "type": "component", + "sourceExport": "getSearchResultsInput", + "sourceModule": "@graphcommerce/algolia-insights/plugins/getSearchResultsInputInsights", + "targetExport": "getSearchResultsInput", + "targetModule": "@graphcommerce/algolia-products", + "type": "function", }, { "enabled": true, - "ifConfig": "googleRecaptchaKey", - "sourceExport": "ApolloErrorFullPage", - "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorFullPage", - "targetExport": "ApolloErrorFullPage", - "targetModule": "@graphcommerce/ecommerce-ui", - "type": "component", + "sourceExport": "meshConfig", + "sourceModule": "@graphcommerce/algolia-categories/plugins/meshConfigAlgoliaCategories", + "targetExport": "meshConfig", + "targetModule": "@graphcommerce/graphql-mesh/meshConfig", + "type": "function", }, { "enabled": true, - "ifConfig": "googleRecaptchaKey", - "sourceExport": "ApolloErrorAlert", - "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorAlert", - "targetExport": "ApolloErrorAlert", - "targetModule": "@graphcommerce/ecommerce-ui", - "type": "component", + "sourceExport": "meshConfig", + "sourceModule": "@graphcommerce/algolia-products/plugins/meshConfigAlgolia", + "targetExport": "meshConfig", + "targetModule": "@graphcommerce/graphql-mesh/meshConfig", + "type": "function", }, { "enabled": true, - "sourceExport": "hygraphPageContent", - "sourceModule": "@graphcommerce/hygraph-dynamic-rows/plugins/hygraphDynamicRowsPageContent", - "targetExport": "hygraphPageContent", - "targetModule": "@graphcommerce/hygraph-ui", + "sourceExport": "useProductListApplySearchDefaults", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", + "targetExport": "useProductListApplySearchDefaults", + "targetModule": "@graphcommerce/magento-search", "type": "function", }, { "enabled": true, - "sourceExport": "previewModeDefaults", - "sourceModule": "@graphcommerce/hygraph-ui/plugins/hygraphPreviewModeDefaults", - "targetExport": "previewModeDefaults", - "targetModule": "@graphcommerce/ecommerce-ui", + "sourceExport": "productListApplySearchDefaults", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", + "targetExport": "productListApplySearchDefaults", + "targetModule": "@graphcommerce/magento-search", "type": "function", }, { "enabled": true, - "sourceExport": "graphqlConfig", - "sourceModule": "@graphcommerce/hygraph-ui/plugins/hygraphGraphqlConfig", - "targetExport": "graphqlConfig", - "targetModule": "@graphcommerce/graphql", + "sourceExport": "searchDefaultsToProductListFilters", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", + "targetExport": "searchDefaultsToProductListFilters", + "targetModule": "@graphcommerce/magento-search", "type": "function", }, { "enabled": true, - "sourceExport": "PreviewModeToolbar", - "sourceModule": "@graphcommerce/hygraph-ui/plugins/HygraphPreviewModeToolbar", - "targetExport": "PreviewModeToolbar", - "targetModule": "@graphcommerce/ecommerce-ui", + "sourceExport": "ProductListItemsBase", + "sourceModule": "@graphcommerce/algolia-products/plugins/ProductListItemsBaseAlgolia", + "targetExport": "ProductListItemsBase", + "targetModule": "@graphcommerce/magento-product", "type": "component", }, { "enabled": true, - "sourceExport": "meshConfig", - "sourceModule": "@graphcommerce/magento-graphql-rest/plugins/meshConfigM2Rest", - "targetExport": "meshConfig", - "targetModule": "@graphcommerce/graphql-mesh/meshConfig", - "type": "function", + "sourceExport": "PaymentMethodContextProvider", + "sourceModule": "@graphcommerce/magento-payment-paypal/plugins/AddPaypalMethods", + "targetExport": "PaymentMethodContextProvider", + "targetModule": "@graphcommerce/magento-cart-payment-method", + "type": "component", }, { "enabled": true, "sourceExport": "PaymentMethodContextProvider", - "sourceModule": "@graphcommerce/magento-payment-included/plugins/AddIncludedMethods", + "sourceModule": "@graphcommerce/mollie-magento-payment/plugins/AddMollieMethods", "targetExport": "PaymentMethodContextProvider", "targetModule": "@graphcommerce/magento-cart-payment-method", "type": "component", }, { "enabled": true, - "sourceExport": "CartItemActionCard", - "sourceModule": "@graphcommerce/magento-product-bundle/plugins/BundleCartItemActionCard", - "targetExport": "CartItemActionCard", - "targetModule": "@graphcommerce/magento-cart-items", + "sourceExport": "PaymentMethodContextProvider", + "sourceModule": "@graphcommerce/magento-payment-braintree/plugins/AddBraintreeMethods", + "targetExport": "PaymentMethodContextProvider", + "targetModule": "@graphcommerce/magento-cart-payment-method", "type": "component", }, { "enabled": true, - "sourceExport": "CartItemActionCard", - "sourceModule": "@graphcommerce/magento-product-virtual/plugins/VirtualCartItemActionCard", - "targetExport": "CartItemActionCard", - "targetModule": "@graphcommerce/magento-cart-items", + "sourceExport": "ShippingMethodForm", + "sourceModule": "@graphcommerce/magento-cart-pickup/plugins/AddPickupInStore", + "targetExport": "ShippingMethodForm", + "targetModule": "@graphcommerce/magento-cart-shipping-method", "type": "component", }, { @@ -193,58 +199,18 @@ it('finds plugins', () => { "targetModule": "@graphcommerce/magento-wishlist", "type": "component", }, - { - "enabled": true, - "sourceExport": "ShippingMethodForm", - "sourceModule": "@graphcommerce/magento-cart-pickup/plugins/AddPickupInStore", - "targetExport": "ShippingMethodForm", - "targetModule": "@graphcommerce/magento-cart-shipping-method", - "type": "component", - }, - { - "enabled": true, - "sourceExport": "PaymentMethodContextProvider", - "sourceModule": "@graphcommerce/magento-payment-braintree/plugins/AddBraintreeMethods", - "targetExport": "PaymentMethodContextProvider", - "targetModule": "@graphcommerce/magento-cart-payment-method", - "type": "component", - }, - { - "enabled": true, - "sourceExport": "PaymentMethodContextProvider", - "sourceModule": "@graphcommerce/mollie-magento-payment/plugins/AddMollieMethods", - "targetExport": "PaymentMethodContextProvider", - "targetModule": "@graphcommerce/magento-cart-payment-method", - "type": "component", - }, { "enabled": true, "sourceExport": "CartItemActionCard", - "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableCartItemActionCard", + "sourceModule": "@graphcommerce/magento-product-bundle/plugins/BundleCartItemActionCard", "targetExport": "CartItemActionCard", "targetModule": "@graphcommerce/magento-cart-items", "type": "component", }, - { - "enabled": true, - "sourceExport": "ProductPagePriceTiers", - "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableProductPage/ConfigurableProductPagePriceTiers", - "targetExport": "ProductPagePriceTiers", - "targetModule": "@graphcommerce/magento-product", - "type": "component", - }, - { - "enabled": true, - "sourceExport": "ProductPagePrice", - "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableProductPage/ConfigurableProductPagePrice", - "targetExport": "ProductPagePrice", - "targetModule": "@graphcommerce/magento-product", - "type": "component", - }, { "enabled": true, "sourceExport": "CartItemActionCard", - "sourceModule": "@graphcommerce/magento-product-simple/plugins/SimpleCartItemActionCard", + "sourceModule": "@graphcommerce/magento-product-virtual/plugins/VirtualCartItemActionCard", "targetExport": "CartItemActionCard", "targetModule": "@graphcommerce/magento-cart-items", "type": "component", @@ -252,7 +218,7 @@ it('finds plugins', () => { { "enabled": true, "sourceExport": "PaymentMethodContextProvider", - "sourceModule": "@graphcommerce/magento-payment-paypal/plugins/AddPaypalMethods", + "sourceModule": "@graphcommerce/magento-payment-included/plugins/AddIncludedMethods", "targetExport": "PaymentMethodContextProvider", "targetModule": "@graphcommerce/magento-cart-payment-method", "type": "component", @@ -260,121 +226,95 @@ it('finds plugins', () => { { "enabled": true, "sourceExport": "meshConfig", - "sourceModule": "@graphcommerce/algolia-categories/plugins/meshConfigAlgoliaCategories", + "sourceModule": "@graphcommerce/magento-graphql-rest/plugins/meshConfigM2Rest", "targetExport": "meshConfig", "targetModule": "@graphcommerce/graphql-mesh/meshConfig", "type": "function", }, { "enabled": true, - "sourceExport": "getSearchSuggestionsInput", - "sourceModule": "@graphcommerce/algolia-personalization/plugins/getSearchSuggestionsInputPersonalization", - "targetExport": "getSearchSuggestionsInput", - "targetModule": "@graphcommerce/algolia-products", - "type": "function", - }, - { - "enabled": true, - "sourceExport": "getSearchResultsInput", - "sourceModule": "@graphcommerce/algolia-personalization/plugins/getSearchResultsInputPersonalization", - "targetExport": "getSearchResultsInput", - "targetModule": "@graphcommerce/algolia-products", + "sourceExport": "hygraphPageContent", + "sourceModule": "@graphcommerce/hygraph-dynamic-rows/plugins/hygraphDynamicRowsPageContent", + "targetExport": "hygraphPageContent", + "targetModule": "@graphcommerce/hygraph-ui", "type": "function", }, { "enabled": true, - "sourceExport": "getPrivateQueryContext", - "sourceModule": "@graphcommerce/algolia-personalization/plugins/InContextInputAlgoliaUserToken", - "targetExport": "getPrivateQueryContext", - "targetModule": "@graphcommerce/graphql", + "sourceExport": "previewModeDefaults", + "sourceModule": "@graphcommerce/hygraph-ui/plugins/hygraphPreviewModeDefaults", + "targetExport": "previewModeDefaults", + "targetModule": "@graphcommerce/ecommerce-ui", "type": "function", }, { "enabled": true, - "sourceExport": "usePrivateQueryContext", - "sourceModule": "@graphcommerce/algolia-personalization/plugins/InContextInputAlgoliaUserToken", - "targetExport": "usePrivateQueryContext", + "sourceExport": "graphqlConfig", + "sourceModule": "@graphcommerce/hygraph-ui/plugins/hygraphGraphqlConfig", + "targetExport": "graphqlConfig", "targetModule": "@graphcommerce/graphql", "type": "function", }, { "enabled": true, - "sourceExport": "useSendEvent", - "sourceModule": "@graphcommerce/algolia-insights/plugins/useSendEventAlgolia", - "targetExport": "useSendEvent", - "targetModule": "@graphcommerce/google-datalayer", - "type": "function", - }, - { - "enabled": true, - "sourceExport": "meshConfig", - "sourceModule": "@graphcommerce/algolia-insights/plugins/meshConfigAlgoliaInsights", - "targetExport": "meshConfig", - "targetModule": "@graphcommerce/graphql-mesh/meshConfig", - "type": "function", - }, - { - "enabled": true, - "sourceExport": "getSearchSuggestionsInput", - "sourceModule": "@graphcommerce/algolia-insights/plugins/getSearchSuggestionsInputInsights", - "targetExport": "getSearchSuggestionsInput", - "targetModule": "@graphcommerce/algolia-products", - "type": "function", - }, - { - "enabled": true, - "sourceExport": "getSearchResultsInput", - "sourceModule": "@graphcommerce/algolia-insights/plugins/getSearchResultsInputInsights", - "targetExport": "getSearchResultsInput", - "targetModule": "@graphcommerce/algolia-products", - "type": "function", + "sourceExport": "PreviewModeToolbar", + "sourceModule": "@graphcommerce/hygraph-ui/plugins/HygraphPreviewModeToolbar", + "targetExport": "PreviewModeToolbar", + "targetModule": "@graphcommerce/ecommerce-ui", + "type": "component", }, { "enabled": true, - "sourceExport": "meshConfig", - "sourceModule": "@graphcommerce/algolia-recommend/plugins/meshConfigAlgoliaRecommend", - "targetExport": "meshConfig", - "targetModule": "@graphcommerce/graphql-mesh/meshConfig", - "type": "function", + "ifConfig": "googleRecaptchaKey", + "sourceExport": "GraphQLProvider", + "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaGraphQLProvider", + "targetExport": "GraphQLProvider", + "targetModule": "@graphcommerce/graphql", + "type": "component", }, { "enabled": true, - "sourceExport": "meshConfig", - "sourceModule": "@graphcommerce/algolia-products/plugins/meshConfigAlgolia", - "targetExport": "meshConfig", - "targetModule": "@graphcommerce/graphql-mesh/meshConfig", - "type": "function", + "ifConfig": "googleRecaptchaKey", + "sourceExport": "ApolloErrorSnackbar", + "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorSnackbar", + "targetExport": "ApolloErrorSnackbar", + "targetModule": "@graphcommerce/ecommerce-ui", + "type": "component", }, { "enabled": true, - "sourceExport": "useProductListApplySearchDefaults", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", - "targetExport": "useProductListApplySearchDefaults", - "targetModule": "@graphcommerce/magento-search", - "type": "function", + "ifConfig": "googleRecaptchaKey", + "sourceExport": "ApolloErrorFullPage", + "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorFullPage", + "targetExport": "ApolloErrorFullPage", + "targetModule": "@graphcommerce/ecommerce-ui", + "type": "component", }, { "enabled": true, - "sourceExport": "productListApplySearchDefaults", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", - "targetExport": "productListApplySearchDefaults", - "targetModule": "@graphcommerce/magento-search", - "type": "function", + "ifConfig": "googleRecaptchaKey", + "sourceExport": "ApolloErrorAlert", + "sourceModule": "@graphcommerce/googlerecaptcha/plugins/GrecaptchaApolloErrorAlert", + "targetExport": "ApolloErrorAlert", + "targetModule": "@graphcommerce/ecommerce-ui", + "type": "component", }, { "enabled": true, - "sourceExport": "searchDefaultsToProductListFilters", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoSearchApplyAlgoliaEngine", - "targetExport": "searchDefaultsToProductListFilters", - "targetModule": "@graphcommerce/magento-search", + "ifConfig": "googleAnalyticsId", + "sourceExport": "sendEvent", + "sourceModule": "@graphcommerce/googleanalytics/plugins/gtagEvent", + "targetExport": "sendEvent", + "targetModule": "@graphcommerce/google-datalayer", "type": "function", }, { "enabled": true, - "sourceExport": "ProductListItemsBase", - "sourceModule": "@graphcommerce/algolia-products/plugins/ProductListItemsBaseAlgolia", - "targetExport": "ProductListItemsBase", - "targetModule": "@graphcommerce/magento-product", + "ifConfig": "googleAnalyticsId", + "sourceExport": "DocumentHeadEnd", + "sourceModule": "@graphcommerce/googleanalytics/plugins/GoogleAnalyticsTag", + "targetExport": "DocumentHeadEnd", + "targetModule": "@graphcommerce/next-ui/server", "type": "component", }, { @@ -465,6 +405,65 @@ it('finds plugins', () => { "targetModule": "@graphcommerce/magento-product", "type": "component", }, + { + "enabled": true, + "ifConfig": "demoMode", + "sourceExport": "RowLinks", + "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoRowLinks", + "targetExport": "RowLinks", + "targetModule": "@graphcommerce/next-ui", + "type": "component", + }, + { + "enabled": true, + "ifConfig": "demoMode", + "sourceExport": "RecentlyViewedProducts", + "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoRecentlyViewedProducts", + "targetExport": "RecentlyViewedProducts", + "targetModule": "@graphcommerce/magento-recently-viewed-products", + "type": "component", + }, + { + "enabled": true, + "ifConfig": "demoMode", + "sourceExport": "ProductListItemConfigurable", + "sourceModule": "@graphcommerce/demo-magento-graphcommerce/plugins/demo/DemoProductListItemConfigurable", + "targetExport": "ProductListItemConfigurable", + "targetModule": "@graphcommerce/magento-product-configurable", + "type": "component", + }, + { + "enabled": true, + "sourceExport": "CartItemActionCard", + "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableCartItemActionCard", + "targetExport": "CartItemActionCard", + "targetModule": "@graphcommerce/magento-cart-items", + "type": "component", + }, + { + "enabled": true, + "sourceExport": "ProductPagePriceTiers", + "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableProductPage/ConfigurableProductPagePriceTiers", + "targetExport": "ProductPagePriceTiers", + "targetModule": "@graphcommerce/magento-product", + "type": "component", + }, + { + "enabled": true, + "sourceExport": "ProductPagePrice", + "sourceModule": "@graphcommerce/magento-product-configurable/plugins/ConfigurableProductPage/ConfigurableProductPagePrice", + "targetExport": "ProductPagePrice", + "targetModule": "@graphcommerce/magento-product", + "type": "component", + }, + { + "enabled": true, + "sourceExport": "CartItemActionCard", + "sourceModule": "@graphcommerce/magento-product-simple/plugins/SimpleCartItemActionCard", + "targetExport": "CartItemActionCard", + "targetModule": "@graphcommerce/magento-cart-items", + "type": "component", + }, { "enabled": true, "sourceExport": "useSignInForm", @@ -551,43 +550,42 @@ it('finds plugins', () => { }, ] `) - expect(disabled).toMatchInlineSnapshot( - ` + expect(disabled).toMatchInlineSnapshot(` [ { "enabled": false, - "ifConfig": "recentlyViewedProducts.enabled", - "sourceExport": "ProductPageMeta", - "sourceModule": "@graphcommerce/magento-recently-viewed-products/plugins/RegisterProductAsRecentlyViewed", - "targetExport": "ProductPageMeta", + "ifConfig": "algolia.catalogEnabled", + "sourceExport": "useProductListApplyCategoryDefaults", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", + "targetExport": "useProductListApplyCategoryDefaults", "targetModule": "@graphcommerce/magento-product", - "type": "component", + "type": "function", }, { "enabled": false, - "ifConfig": "googleTagmanagerId", - "sourceExport": "sendEvent", - "sourceModule": "@graphcommerce/googletagmanager/plugins/tagmanagerEvent", - "targetExport": "sendEvent", - "targetModule": "@graphcommerce/google-datalayer", + "ifConfig": "algolia.catalogEnabled", + "sourceExport": "productListApplyCategoryDefaults", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", + "targetExport": "productListApplyCategoryDefaults", + "targetModule": "@graphcommerce/magento-product", "type": "function", }, { "enabled": false, - "ifConfig": "googleTagmanagerId", - "sourceExport": "DocumentBodyStart", - "sourceModule": "@graphcommerce/googletagmanager/plugins/GoogleTagmanagerTag", - "targetExport": "DocumentBodyStart", - "targetModule": "@graphcommerce/next-ui/server", - "type": "component", + "ifConfig": "algolia.catalogEnabled", + "sourceExport": "categoryDefaultsToProductListFilters", + "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", + "targetExport": "categoryDefaultsToProductListFilters", + "targetModule": "@graphcommerce/magento-product", + "type": "function", }, { "enabled": false, - "ifConfig": "googleTagmanagerId", - "sourceExport": "DocumentHeadEnd", - "sourceModule": "@graphcommerce/googletagmanager/plugins/GoogleTagmanagerTag", - "targetExport": "DocumentHeadEnd", - "targetModule": "@graphcommerce/next-ui/server", + "ifConfig": "algolia.customerGroupPricingEnabled", + "sourceExport": "GraphQLProvider", + "sourceModule": "@graphcommerce/algolia-products/plugins/GraphQLProviderAlgoliaCustomerGroupId", + "targetExport": "GraphQLProvider", + "targetModule": "@graphcommerce/graphql", "type": "component", }, { @@ -626,6 +624,51 @@ it('finds plugins', () => { "targetModule": "@graphcommerce/magento-cart", "type": "component", }, + { + "enabled": false, + "ifConfig": "googleTagmanagerId", + "sourceExport": "sendEvent", + "sourceModule": "@graphcommerce/googletagmanager/plugins/tagmanagerEvent", + "targetExport": "sendEvent", + "targetModule": "@graphcommerce/google-datalayer", + "type": "function", + }, + { + "enabled": false, + "ifConfig": "googleTagmanagerId", + "sourceExport": "DocumentBodyStart", + "sourceModule": "@graphcommerce/googletagmanager/plugins/GoogleTagmanagerTag", + "targetExport": "DocumentBodyStart", + "targetModule": "@graphcommerce/next-ui/server", + "type": "component", + }, + { + "enabled": false, + "ifConfig": "googleTagmanagerId", + "sourceExport": "DocumentHeadEnd", + "sourceModule": "@graphcommerce/googletagmanager/plugins/GoogleTagmanagerTag", + "targetExport": "DocumentHeadEnd", + "targetModule": "@graphcommerce/next-ui/server", + "type": "component", + }, + { + "enabled": false, + "ifConfig": "dataLayer.coreWebVitals", + "sourceExport": "FramerNextPages", + "sourceModule": "@graphcommerce/google-datalayer/plugins/GoogleDatalayerWebVitals", + "targetExport": "FramerNextPages", + "targetModule": "@graphcommerce/framer-next-pages", + "type": "component", + }, + { + "enabled": false, + "ifConfig": "recentlyViewedProducts.enabled", + "sourceExport": "ProductPageMeta", + "sourceModule": "@graphcommerce/magento-recently-viewed-products/plugins/RegisterProductAsRecentlyViewed", + "targetExport": "ProductPageMeta", + "targetModule": "@graphcommerce/magento-product", + "type": "component", + }, { "enabled": false, "ifConfig": "configurableVariantValues.content", @@ -680,51 +723,6 @@ it('finds plugins', () => { "targetModule": "@graphcommerce/magento-product", "type": "component", }, - { - "enabled": false, - "ifConfig": "algolia.catalogEnabled", - "sourceExport": "useProductListApplyCategoryDefaults", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", - "targetExport": "useProductListApplyCategoryDefaults", - "targetModule": "@graphcommerce/magento-product", - "type": "function", - }, - { - "enabled": false, - "ifConfig": "algolia.catalogEnabled", - "sourceExport": "productListApplyCategoryDefaults", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", - "targetExport": "productListApplyCategoryDefaults", - "targetModule": "@graphcommerce/magento-product", - "type": "function", - }, - { - "enabled": false, - "ifConfig": "algolia.catalogEnabled", - "sourceExport": "categoryDefaultsToProductListFilters", - "sourceModule": "@graphcommerce/algolia-products/plugins/magentoProductApplyAlgoliaEngine", - "targetExport": "categoryDefaultsToProductListFilters", - "targetModule": "@graphcommerce/magento-product", - "type": "function", - }, - { - "enabled": false, - "ifConfig": "algolia.customerGroupPricingEnabled", - "sourceExport": "GraphQLProvider", - "sourceModule": "@graphcommerce/algolia-products/plugins/GraphQLProviderAlgoliaCustomerGroupId", - "targetExport": "GraphQLProvider", - "targetModule": "@graphcommerce/graphql", - "type": "component", - }, - { - "enabled": false, - "ifConfig": "dataLayer.coreWebVitals", - "sourceExport": "FramerNextPages", - "sourceModule": "@graphcommerce/google-datalayer/plugins/GoogleDatalayerWebVitals", - "targetExport": "FramerNextPages", - "targetModule": "@graphcommerce/framer-next-pages", - "type": "component", - }, { "enabled": false, "ifConfig": "debug.cart", @@ -753,6 +751,5 @@ it('finds plugins', () => { "type": "component", }, ] - `, - ) + `) }) diff --git a/packagesDev/next-config/__tests__/utils/resolveDependenciesSync.ts b/packagesDev/next-config/__tests__/utils/resolveDependenciesSync.ts index b992ff1608..9162b8697c 100644 --- a/packagesDev/next-config/__tests__/utils/resolveDependenciesSync.ts +++ b/packagesDev/next-config/__tests__/utils/resolveDependenciesSync.ts @@ -1,74 +1,74 @@ import { resolveDependenciesSync, sortDependencies } from '../../src/utils/resolveDependenciesSync' const projectRoot = `${process.cwd()}/examples/magento-graphcms` -it('resolves dependences', () => { +it('It resolves and sorts dependencies beginning with the root example package and ending with the the packages used everywhere.', () => { const dependencies = resolveDependenciesSync(projectRoot) expect(dependencies).toMatchInlineSnapshot( ` Map { "." => "examples/magento-graphcms", - "@graphcommerce/cli" => "packages/cli", - "@graphcommerce/hygraph-cli" => "packages/hygraph-cli", - "@graphcommerce/demo-magento-graphcommerce" => "packages/demo-magento-graphcommerce", - "@graphcommerce/magento-recently-viewed-products" => "packages/magento-recently-viewed-products", - "@graphcommerce/google-playstore" => "packages/google-playstore", - "@graphcommerce/googleanalytics" => "packages/googleanalytics", - "@graphcommerce/googlerecaptcha" => "packages/googlerecaptcha", - "@graphcommerce/googletagmanager" => "packages/googletagmanager", - "@graphcommerce/hygraph-dynamic-rows" => "packages/hygraph-dynamic-rows", - "@graphcommerce/hygraph-ui" => "packages/hygraph-ui", - "@graphcommerce/magento-cart-billing-address" => "packages/magento-cart-billing-address", - "@graphcommerce/magento-cart-checkout" => "packages/magento-cart-checkout", - "@graphcommerce/magento-cart-coupon" => "packages/magento-cart-coupon", - "@graphcommerce/magento-cart-email" => "packages/magento-cart-email", - "@graphcommerce/magento-cms" => "packages/magento-cms", - "@graphcommerce/magento-compare" => "packages/magento-compare", - "@graphcommerce/magento-graphql-rest" => "packages/magento-graphql-rest", - "@graphcommerce/magento-newsletter" => "packages/magento-newsletter", - "@graphcommerce/magento-payment-included" => "packages/magento-payment-included", - "@graphcommerce/magento-product-bundle" => "packages/magento-product-bundle", - "@graphcommerce/magento-product-downloadable" => "packages/magento-product-downloadable", - "@graphcommerce/magento-product-grouped" => "packages/magento-product-grouped", - "@graphcommerce/magento-product-virtual" => "packages/magento-product-virtual", - "@graphcommerce/magento-review" => "packages/magento-review", - "@graphcommerce/magento-wishlist" => "packages/magento-wishlist", - "@graphcommerce/service-worker" => "packages/service-worker", - "@graphcommerce/magento-cart-pickup" => "packages/magento-cart-pickup", - "@graphcommerce/magento-payment-braintree" => "packages/magento-payment-braintree", - "@graphcommerce/mollie-magento-payment" => "packages/mollie-magento-payment", - "@graphcommerce/magento-product-configurable" => "packages/magento-product-configurable", - "@graphcommerce/magento-product-simple" => "packages/magento-product-simple", - "@graphcommerce/magento-category" => "packages/magento-category", - "@graphcommerce/magento-cart-items" => "packages/magento-cart-items", - "@graphcommerce/lingui-next" => "packages/lingui-next", - "@graphcommerce/magento-payment-paypal" => "packages/magento-payment-paypal", - "@graphcommerce/algolia-categories" => "packages/algolia-categories", + "@graphcommerce/algolia-recommend" => "packages/algolia-recommend", "@graphcommerce/algolia-personalization" => "packages/algolia-personalization", "@graphcommerce/algolia-insights" => "packages/algolia-insights", - "@graphcommerce/algolia-recommend" => "packages/algolia-recommend", + "@graphcommerce/algolia-categories" => "packages/algolia-categories", "@graphcommerce/algolia-products" => "packages/algolia-products", - "@graphcommerce/next-config" => "packagesDev/next-config", + "@graphcommerce/magento-payment-paypal" => "packages/magento-payment-paypal", + "@graphcommerce/mollie-magento-payment" => "packages/mollie-magento-payment", + "@graphcommerce/magento-payment-braintree" => "packages/magento-payment-braintree", + "@graphcommerce/magento-cart-pickup" => "packages/magento-cart-pickup", + "@graphcommerce/service-worker" => "packages/service-worker", + "@graphcommerce/magento-wishlist" => "packages/magento-wishlist", + "@graphcommerce/magento-review" => "packages/magento-review", + "@graphcommerce/magento-product-grouped" => "packages/magento-product-grouped", + "@graphcommerce/magento-product-downloadable" => "packages/magento-product-downloadable", + "@graphcommerce/magento-product-bundle" => "packages/magento-product-bundle", + "@graphcommerce/magento-product-virtual" => "packages/magento-product-virtual", + "@graphcommerce/magento-payment-included" => "packages/magento-payment-included", + "@graphcommerce/magento-newsletter" => "packages/magento-newsletter", + "@graphcommerce/magento-graphql-rest" => "packages/magento-graphql-rest", "@graphcommerce/magento-search" => "packages/magento-search", + "@graphcommerce/magento-compare" => "packages/magento-compare", + "@graphcommerce/magento-cms" => "packages/magento-cms", + "@graphcommerce/magento-cart-email" => "packages/magento-cart-email", + "@graphcommerce/magento-cart-checkout" => "packages/magento-cart-checkout", + "@graphcommerce/magento-cart-coupon" => "packages/magento-cart-coupon", + "@graphcommerce/magento-cart-billing-address" => "packages/magento-cart-billing-address", + "@graphcommerce/hygraph-dynamic-rows" => "packages/hygraph-dynamic-rows", + "@graphcommerce/hygraph-ui" => "packages/hygraph-ui", + "@graphcommerce/googletagmanager" => "packages/googletagmanager", + "@graphcommerce/googlerecaptcha" => "packages/googlerecaptcha", + "@graphcommerce/googleanalytics" => "packages/googleanalytics", + "@graphcommerce/google-playstore" => "packages/google-playstore", "@graphcommerce/google-datalayer" => "packages/google-datalayer", - "@graphcommerce/magento-product" => "packages/magento-product", "@graphcommerce/magento-cart-shipping-method" => "packages/magento-cart-shipping-method", "@graphcommerce/magento-cart-payment-method" => "packages/magento-cart-payment-method", "@graphcommerce/magento-cart-shipping-address" => "packages/magento-cart-shipping-address", + "@graphcommerce/demo-magento-graphcommerce" => "packages/demo-magento-graphcommerce", + "@graphcommerce/magento-recently-viewed-products" => "packages/magento-recently-viewed-products", + "@graphcommerce/magento-product-configurable" => "packages/magento-product-configurable", + "@graphcommerce/magento-product-simple" => "packages/magento-product-simple", + "@graphcommerce/magento-category" => "packages/magento-category", + "@graphcommerce/magento-cart-items" => "packages/magento-cart-items", + "@graphcommerce/lingui-next" => "packages/lingui-next", + "@graphcommerce/magento-product" => "packages/magento-product", "@graphcommerce/magento-cart" => "packages/magento-cart", "@graphcommerce/magento-customer" => "packages/magento-customer", "@graphcommerce/magento-store" => "packages/magento-store", "@graphcommerce/magento-graphql" => "packages/magento-graphql", - "@graphcommerce/graphql-mesh" => "packages/graphql-mesh", "@graphcommerce/ecommerce-ui" => "packages/ecommerce-ui", "@graphcommerce/react-hook-form" => "packages/react-hook-form", "@graphcommerce/next-ui" => "packages/next-ui", - "@graphcommerce/framer-scroller" => "packages/framer-scroller", - "@graphcommerce/image" => "packages/image", "@graphcommerce/framer-next-pages" => "packages/framer-next-pages", - "@graphcommerce/framer-utils" => "packages/framer-utils", "@graphcommerce/graphql" => "packages/graphql", "@graphcommerce/graphql-codegen-relay-optimizer-plugin" => "packagesDev/graphql-codegen-relay-optimizer-plugin", "@graphcommerce/graphql-codegen-near-operation-file" => "packagesDev/graphql-codegen-near-operation-file", + "@graphcommerce/framer-scroller" => "packages/framer-scroller", + "@graphcommerce/image" => "packages/image", + "@graphcommerce/framer-utils" => "packages/framer-utils", + "@graphcommerce/cli" => "packages/cli", + "@graphcommerce/hygraph-cli" => "packages/hygraph-cli", + "@graphcommerce/next-config" => "packagesDev/next-config", + "@graphcommerce/graphql-mesh" => "packages/graphql-mesh", "@graphcommerce/prettier-config-pwa" => "packagesDev/prettier-config", "@graphcommerce/eslint-config-pwa" => "packagesDev/eslint-config", "@graphcommerce/typescript-config-pwa" => "packagesDev/typescript-config", From 4e5d525a4d983c73bf006762d078bee17f40add2 Mon Sep 17 00:00:00 2001 From: Paul Hachmang Date: Thu, 23 Jan 2025 13:52:22 +0100 Subject: [PATCH 16/16] Make sure the types are available from packages and sovle RichText type error --- packages/cli/package.json | 2 +- packages/hygraph-ui/components/RichText/types.ts | 1 + packagesDev/next-config/package.json | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/cli/package.json b/packages/cli/package.json index 71d870bf17..ff7eeb6506 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -9,9 +9,9 @@ "prepack": "pkgroll --clean-dist" }, "type": "module", + "types": "./src/index.ts", "exports": { ".": { - "types": "./src/index.ts", "default": "./dist/index.js" } }, diff --git a/packages/hygraph-ui/components/RichText/types.ts b/packages/hygraph-ui/components/RichText/types.ts index 0f5f0adff2..97d96f76b6 100644 --- a/packages/hygraph-ui/components/RichText/types.ts +++ b/packages/hygraph-ui/components/RichText/types.ts @@ -83,6 +83,7 @@ type IframeElement = { type EmbedElement = { type: 'embed' + children: ElementOrTextNode[] id: string nodeId: string nodeType: string diff --git a/packagesDev/next-config/package.json b/packagesDev/next-config/package.json index d5e89d9c3d..832278190b 100644 --- a/packagesDev/next-config/package.json +++ b/packagesDev/next-config/package.json @@ -4,9 +4,9 @@ "repository": "github:graphcommerce-org/graphcommerce", "version": "9.0.4-canary.9", "type": "module", + "types": "./src/index.ts", "exports": { ".": { - "types": "./src/index.ts", "default": "./dist/index.js" }, "./config": {