@graphcommerce/next-config 8.1.0-canary.3 → 8.1.0-canary.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/CHANGELOG.md +134 -2
  2. package/Config.graphqls +4 -2
  3. package/__tests__/config/utils/__snapshots__/mergeEnvIntoConfig.ts.snap +19 -2
  4. package/__tests__/config/utils/replaceConfigInString.ts +4 -0
  5. package/__tests__/interceptors/findPlugins.ts +473 -113
  6. package/__tests__/interceptors/generateInterceptors.ts +610 -322
  7. package/__tests__/interceptors/parseStructure.ts +158 -0
  8. package/__tests__/interceptors/writeInterceptors.ts +23 -14
  9. package/__tests__/utils/resolveDependenciesSync.ts +28 -25
  10. package/dist/config/commands/generateConfig.js +5 -2
  11. package/dist/config/demoConfig.js +19 -4
  12. package/dist/generated/config.js +8 -1
  13. package/dist/interceptors/InterceptorPlugin.js +70 -25
  14. package/dist/interceptors/RenameVisitor.js +19 -0
  15. package/dist/interceptors/Visitor.js +1418 -0
  16. package/dist/interceptors/extractExports.js +201 -0
  17. package/dist/interceptors/findOriginalSource.js +87 -0
  18. package/dist/interceptors/findPlugins.js +21 -53
  19. package/dist/interceptors/generateInterceptor.js +200 -0
  20. package/dist/interceptors/generateInterceptors.js +38 -179
  21. package/dist/interceptors/parseStructure.js +71 -0
  22. package/dist/interceptors/swc.js +16 -0
  23. package/dist/interceptors/writeInterceptors.js +19 -10
  24. package/dist/utils/resolveDependency.js +27 -5
  25. package/dist/withGraphCommerce.js +2 -1
  26. package/package.json +4 -1
  27. package/src/config/commands/generateConfig.ts +5 -2
  28. package/src/config/demoConfig.ts +19 -4
  29. package/src/config/index.ts +4 -2
  30. package/src/generated/config.ts +25 -3
  31. package/src/index.ts +16 -6
  32. package/src/interceptors/InterceptorPlugin.ts +90 -32
  33. package/src/interceptors/RenameVisitor.ts +17 -0
  34. package/src/interceptors/Visitor.ts +1847 -0
  35. package/src/interceptors/extractExports.ts +230 -0
  36. package/src/interceptors/findOriginalSource.ts +105 -0
  37. package/src/interceptors/findPlugins.ts +36 -87
  38. package/src/interceptors/generateInterceptor.ts +271 -0
  39. package/src/interceptors/generateInterceptors.ts +67 -237
  40. package/src/interceptors/parseStructure.ts +82 -0
  41. package/src/interceptors/swc.ts +13 -0
  42. package/src/interceptors/writeInterceptors.ts +26 -10
  43. package/src/utils/resolveDependency.ts +51 -12
  44. package/src/withGraphCommerce.ts +2 -1
@@ -0,0 +1,158 @@
1
+ import { GraphCommerceConfig } from '../../src/generated/config'
2
+ import { parseStructure } from '../../src/interceptors/parseStructure'
3
+ import { parseSync } from '../../src/interceptors/swc'
4
+
5
+ const fakeconfig = {
6
+ googleRecaptchaKey: '123',
7
+ googleAnalyticsId: '123',
8
+ demoMode: true,
9
+ } as GraphCommerceConfig
10
+
11
+ it("correctly parses the new PluginConfig and it's ifConfig configuration", () => {
12
+ const src = `
13
+ import { getProductStaticPaths as getProductStaticPathsType } from '@graphcommerce/magento-product'
14
+ import { PluginConfig } from '@graphcommerce/next-config'
15
+
16
+
17
+ export const config: PluginConfig = {
18
+ type: 'replace',
19
+ module: '@graphcommerce/magento-product',
20
+ ifConfig: 'demoMode',
21
+ }
22
+
23
+ // eslint-disable-next-line @typescript-eslint/require-await
24
+ export const getProductStaticPaths: typeof getProductStaticPathsType = async () => [
25
+ { params: { url: 'demo-product' } },
26
+ ]
27
+ `
28
+ const ast = parseSync(src)
29
+
30
+ const plugins = parseStructure(ast, fakeconfig, './plugins/MyReplace')
31
+ expect(plugins).toHaveLength(1)
32
+ expect(plugins[0]).toMatchInlineSnapshot(`
33
+ {
34
+ "enabled": true,
35
+ "ifConfig": "demoMode",
36
+ "sourceExport": "getProductStaticPaths",
37
+ "sourceModule": "./plugins/MyReplace",
38
+ "targetExport": "getProductStaticPaths",
39
+ "targetModule": "@graphcommerce/magento-product",
40
+ "type": "replace",
41
+ }
42
+ `)
43
+ })
44
+
45
+ it('correctly the classic component plugin config', () => {
46
+ const src = `
47
+ import type { ProdustListItemConfigurableProps } from '@graphcommerce/magento-product-configurable'
48
+ import type { IfConfig, PluginProps } from '@graphcommerce/next-config'
49
+
50
+ export const component = 'ProductListItemConfigurable'
51
+ export const exported = '@graphcommerce/magento-product-configurable'
52
+ export const ifConfig: IfConfig = 'demoMode'
53
+
54
+ function DemoProductListItemConfigurable(props: PluginProps<ProdustListItemConfigurableProps>) {
55
+ const { Prev, ...rest } = props
56
+ return <Prev {...rest} swatchLocations={{ bottomRight: ['dominant_color'] }} />
57
+ }
58
+ export const Plugin = DemoProductListItemConfigurable
59
+ `
60
+ const ast = parseSync(src)
61
+
62
+ const plugins = parseStructure(ast, fakeconfig, './plugins/MyComponentPlugin')
63
+ expect(plugins).toHaveLength(1)
64
+ expect(plugins[0]).toMatchInlineSnapshot(`
65
+ {
66
+ "enabled": true,
67
+ "ifConfig": "demoMode",
68
+ "sourceExport": "Plugin",
69
+ "sourceModule": "./plugins/MyComponentPlugin",
70
+ "targetExport": "ProductListItemConfigurable",
71
+ "targetModule": "@graphcommerce/magento-product-configurable",
72
+ "type": "component",
73
+ }
74
+ `)
75
+ })
76
+
77
+ it('correctly parses the classic function plugin config', () => {
78
+ const src = `
79
+ import { graphqlConfig, setContext } from '@graphcommerce/graphql'
80
+ import type { MethodPlugin } from '@graphcommerce/next-config'
81
+
82
+ export const func = 'graphqlConfig'
83
+ export const exported = '@graphcommerce/graphql'
84
+
85
+ const hygraphGraphqlConfig: MethodPlugin<typeof graphqlConfig> = (prev, config) => {
86
+ const results = prev(config)
87
+
88
+ const locales = config.storefront.hygraphLocales
89
+
90
+ if (!locales) return prev(config)
91
+
92
+ const hygraphLink = setContext((_, context) => {
93
+ if (!context.headers) context.headers = {}
94
+ context.headers['gcms-locales'] = locales.join(',')
95
+ return context
96
+ })
97
+
98
+ return { ...results, links: [...results.links, hygraphLink] }
99
+ }
100
+
101
+ export const plugin = hygraphGraphqlConfig
102
+ `
103
+ const ast = parseSync(src)
104
+
105
+ const plugins = parseStructure(ast, fakeconfig, './plugins/MyClassicFunctionPlugin')
106
+ expect(plugins).toHaveLength(1)
107
+ expect(plugins[0]).toMatchInlineSnapshot(`
108
+ {
109
+ "enabled": true,
110
+ "sourceExport": "plugin",
111
+ "sourceModule": "./plugins/MyClassicFunctionPlugin",
112
+ "targetExport": "graphqlConfig",
113
+ "targetModule": "@graphcommerce/graphql",
114
+ "type": "function",
115
+ }
116
+ `)
117
+ })
118
+
119
+ it('parses the correct export when both the classic and new config is present', () => {
120
+ const src = `import { AddProductsToCartFormProps } from '@graphcommerce/magento-product'
121
+ import { IfConfig, PluginConfig, PluginProps } from '@graphcommerce/next-config'
122
+
123
+ export const component = 'AddProductsToCartForm'
124
+ export const exported = '@graphcommerce/magento-product'
125
+ export const ifConfig: IfConfig = 'demoMode'
126
+
127
+ export const config: PluginConfig = {
128
+ type: 'component',
129
+ module: '@graphcommerce/magento-product',
130
+ ifConfig: 'demoMode',
131
+ }
132
+
133
+ function EnableCrossselsPlugin(props: PluginProps<AddProductsToCartFormProps>) {
134
+ const { Prev, redirect = 'added', ...rest } = props
135
+ return <Prev {...rest} redirect={redirect} />
136
+ }
137
+
138
+ export const AddProductsToCartForm = EnableCrossselsPlugin
139
+ `
140
+
141
+ const plugins = parseStructure(
142
+ parseSync(src),
143
+ fakeconfig,
144
+ './plugins/MyAddProductsToCartFormPlugin.tsx',
145
+ )
146
+ expect(plugins).toHaveLength(1)
147
+ expect(plugins[0]).toMatchInlineSnapshot(`
148
+ {
149
+ "enabled": true,
150
+ "ifConfig": "demoMode",
151
+ "sourceExport": "AddProductsToCartForm",
152
+ "sourceModule": "./plugins/MyAddProductsToCartFormPlugin.tsx",
153
+ "targetExport": "AddProductsToCartForm",
154
+ "targetModule": "@graphcommerce/magento-product",
155
+ "type": "component",
156
+ }
157
+ `)
158
+ })
@@ -3,32 +3,41 @@ import { resolveDependency } from '../../src/utils/resolveDependency'
3
3
 
4
4
  const projectRoot = `${process.cwd()}/examples/magento-graphcms`
5
5
 
6
- it('writes all interceptors to disk', () => {
6
+ it('writes all interceptors to disk', async () => {
7
7
  const resolve = resolveDependency(projectRoot)
8
- generateInterceptors(
8
+ await generateInterceptors(
9
9
  [
10
10
  {
11
- component: 'PaymentMethodContextProvider',
12
- exported: '@graphcommerce/magento-cart-payment-method',
13
- plugin: '@graphcommerce/mollie-magento-payment/plugins/AddMollieMethods',
11
+ type: 'component',
12
+
13
+ targetExport: 'PaymentMethodContextProvider',
14
+ targetModule: '@graphcommerce/magento-cart-payment-method',
15
+ sourceExport: 'Plugin',
16
+ sourceModule: '@graphcommerce/mollie-magento-payment/plugins/AddMollieMethods',
14
17
  enabled: true,
15
18
  },
16
19
  {
17
- component: 'PaymentMethodContextProvider',
18
- exported: '@graphcommerce/magento-cart-payment-method',
19
- plugin: '@graphcommerce/magento-payment-braintree/plugins/AddBraintreeMethods',
20
+ type: 'component',
21
+ sourceExport: 'Plugin',
22
+ targetExport: 'PaymentMethodContextProvider',
23
+ targetModule: '@graphcommerce/magento-cart-payment-method',
24
+ sourceModule: '@graphcommerce/magento-payment-braintree/plugins/AddBraintreeMethods',
20
25
  enabled: true,
21
26
  },
22
27
  {
23
- component: 'PaymentMethodContextProvider',
24
- exported: '@graphcommerce/magento-cart-payment-method',
25
- plugin: '@graphcommerce/magento-payment-included/plugins/AddIncludedMethods',
28
+ type: 'component',
29
+ sourceExport: 'Plugin',
30
+ targetExport: 'PaymentMethodContextProvider',
31
+ targetModule: '@graphcommerce/magento-cart-payment-method',
32
+ sourceModule: '@graphcommerce/magento-payment-included/plugins/AddIncludedMethods',
26
33
  enabled: true,
27
34
  },
28
35
  {
29
- component: 'PaymentMethodContextProvider',
30
- exported: '@graphcommerce/magento-cart-payment-method',
31
- plugin: '@graphcommerce/magento-payment-paypal/plugins/AddPaypalMethods',
36
+ type: 'component',
37
+ sourceExport: 'Plugin',
38
+ targetExport: 'PaymentMethodContextProvider',
39
+ targetModule: '@graphcommerce/magento-cart-payment-method',
40
+ sourceModule: '@graphcommerce/magento-payment-paypal/plugins/AddPaypalMethods',
32
41
  enabled: true,
33
42
  },
34
43
  ],
@@ -9,55 +9,58 @@ it('resolves dependences', () => {
9
9
  Map {
10
10
  "." => "examples/magento-graphcms",
11
11
  "@graphcommerce/cli" => "packages/cli",
12
- "@graphcommerce/hygraph-cli" => "packages/hygraph-cli",
13
12
  "@graphcommerce/demo-magento-graphcommerce" => "packages/demo-magento-graphcommerce",
13
+ "@graphcommerce/ecommerce-ui" => "packages/ecommerce-ui",
14
+ "@graphcommerce/framer-next-pages" => "packages/framer-next-pages",
15
+ "@graphcommerce/framer-scroller" => "packages/framer-scroller",
16
+ "@graphcommerce/framer-utils" => "packages/framer-utils",
14
17
  "@graphcommerce/googleanalytics" => "packages/googleanalytics",
15
- "@graphcommerce/magento-cart-shipping-method" => "packages/magento-cart-shipping-method",
16
18
  "@graphcommerce/googlerecaptcha" => "packages/googlerecaptcha",
17
19
  "@graphcommerce/googletagmanager" => "packages/googletagmanager",
20
+ "@graphcommerce/google-datalayer" => "packages/google-datalayer",
18
21
  "@graphcommerce/graphcms-ui" => "packages/hygraph-ui",
22
+ "@graphcommerce/graphql" => "packages/graphql",
23
+ "@graphcommerce/graphql-codegen-near-operation-file" => "packagesDev/graphql-codegen-near-operation-file",
24
+ "@graphcommerce/graphql-codegen-relay-optimizer-plugin" => "packagesDev/graphql-codegen-relay-optimizer-plugin",
25
+ "@graphcommerce/graphql-mesh" => "packages/graphql-mesh",
26
+ "@graphcommerce/hygraph-cli" => "packages/hygraph-cli",
27
+ "@graphcommerce/hygraph-dynamic-rows" => "packages/hygraph-dynamic-rows",
28
+ "@graphcommerce/image" => "packages/image",
19
29
  "@graphcommerce/lingui-next" => "packages/lingui-next",
20
- "@graphcommerce/next-config" => "packagesDev/next-config",
30
+ "@graphcommerce/magento-cart" => "packages/magento-cart",
21
31
  "@graphcommerce/magento-cart-billing-address" => "packages/magento-cart-billing-address",
22
32
  "@graphcommerce/magento-cart-checkout" => "packages/magento-cart-checkout",
23
33
  "@graphcommerce/magento-cart-coupon" => "packages/magento-cart-coupon",
24
34
  "@graphcommerce/magento-cart-email" => "packages/magento-cart-email",
35
+ "@graphcommerce/magento-cart-items" => "packages/magento-cart-items",
36
+ "@graphcommerce/magento-cart-payment-method" => "packages/magento-cart-payment-method",
37
+ "@graphcommerce/magento-cart-shipping-address" => "packages/magento-cart-shipping-address",
38
+ "@graphcommerce/magento-cart-shipping-method" => "packages/magento-cart-shipping-method",
39
+ "@graphcommerce/magento-category" => "packages/magento-category",
25
40
  "@graphcommerce/magento-cms" => "packages/magento-cms",
26
41
  "@graphcommerce/magento-compare" => "packages/magento-compare",
42
+ "@graphcommerce/magento-customer" => "packages/magento-customer",
43
+ "@graphcommerce/magento-graphql" => "packages/magento-graphql",
27
44
  "@graphcommerce/magento-newsletter" => "packages/magento-newsletter",
28
45
  "@graphcommerce/magento-payment-included" => "packages/magento-payment-included",
29
- "@graphcommerce/magento-cart-payment-method" => "packages/magento-cart-payment-method",
30
- "@graphcommerce/magento-cart-shipping-address" => "packages/magento-cart-shipping-address",
46
+ "@graphcommerce/magento-product" => "packages/magento-product",
31
47
  "@graphcommerce/magento-product-bundle" => "packages/magento-product-bundle",
48
+ "@graphcommerce/magento-product-configurable" => "packages/magento-product-configurable",
32
49
  "@graphcommerce/magento-product-downloadable" => "packages/magento-product-downloadable",
33
50
  "@graphcommerce/magento-product-grouped" => "packages/magento-product-grouped",
51
+ "@graphcommerce/magento-product-simple" => "packages/magento-product-simple",
34
52
  "@graphcommerce/magento-product-virtual" => "packages/magento-product-virtual",
53
+ "@graphcommerce/magento-recently-viewed-products" => "packages/magento-recently-viewed-products",
35
54
  "@graphcommerce/magento-review" => "packages/magento-review",
36
55
  "@graphcommerce/magento-search" => "packages/magento-search",
37
- "@graphcommerce/magento-wishlist" => "packages/magento-wishlist",
38
- "@graphcommerce/magento-product-configurable" => "packages/magento-product-configurable",
39
- "@graphcommerce/magento-product-simple" => "packages/magento-product-simple",
40
- "@graphcommerce/magento-category" => "packages/magento-category",
41
- "@graphcommerce/magento-cart-items" => "packages/magento-cart-items",
42
- "@graphcommerce/magento-product" => "packages/magento-product",
43
- "@graphcommerce/magento-cart" => "packages/magento-cart",
44
- "@graphcommerce/magento-customer" => "packages/magento-customer",
45
56
  "@graphcommerce/magento-store" => "packages/magento-store",
46
- "@graphcommerce/magento-graphql" => "packages/magento-graphql",
47
- "@graphcommerce/ecommerce-ui" => "packages/ecommerce-ui",
48
- "@graphcommerce/react-hook-form" => "packages/react-hook-form",
57
+ "@graphcommerce/magento-wishlist" => "packages/magento-wishlist",
58
+ "@graphcommerce/next-config" => "packagesDev/next-config",
49
59
  "@graphcommerce/next-ui" => "packages/next-ui",
50
- "@graphcommerce/framer-scroller" => "packages/framer-scroller",
51
- "@graphcommerce/framer-next-pages" => "packages/framer-next-pages",
52
- "@graphcommerce/image" => "packages/image",
53
- "@graphcommerce/framer-utils" => "packages/framer-utils",
54
- "@graphcommerce/graphql-mesh" => "packages/graphql-mesh",
55
- "@graphcommerce/graphql" => "packages/graphql",
56
- "@graphcommerce/graphql-codegen-relay-optimizer-plugin" => "packagesDev/graphql-codegen-relay-optimizer-plugin",
57
- "@graphcommerce/graphql-codegen-near-operation-file" => "packagesDev/graphql-codegen-near-operation-file",
58
- "@graphcommerce/prettier-config-pwa" => "packagesDev/prettier-config",
60
+ "@graphcommerce/react-hook-form" => "packages/react-hook-form",
59
61
  "@graphcommerce/eslint-config-pwa" => "packagesDev/eslint-config",
60
62
  "@graphcommerce/typescript-config-pwa" => "packagesDev/typescript-config",
63
+ "@graphcommerce/prettier-config-pwa" => "packagesDev/prettier-config",
61
64
  }
62
65
  `)
63
66
  })
@@ -12,8 +12,11 @@ const packages = [...(0, resolveDependenciesSync_1.resolveDependenciesSync)().va
12
12
  const resolve = (0, resolveDependency_1.resolveDependency)();
13
13
  const schemaLocations = packages.map((p) => `${p}/**/Config.graphqls`);
14
14
  async function generateConfig() {
15
- const targetTs = `${resolve('@graphcommerce/next-config').root}/src/generated/config.ts`;
16
- const targetJs = `${resolve('@graphcommerce/next-config').root}/dist/generated/config.js`;
15
+ const resolved = resolve('@graphcommerce/next-config');
16
+ if (!resolved)
17
+ throw Error('Could not resolve @graphcommerce/next-config');
18
+ const targetTs = `${resolved.root}/src/generated/config.ts`;
19
+ const targetJs = `${resolved.root}/dist/generated/config.js`;
17
20
  await (0, cli_1.generate)({
18
21
  silent: true,
19
22
  schema: ['graphql/**/Config.graphqls', ...schemaLocations],
@@ -13,10 +13,25 @@ exports.demoConfig = {
13
13
  hygraphLocales: ['nl', 'en_us'],
14
14
  cartDisplayPricesInclTax: true,
15
15
  },
16
- { locale: 'fr-be', magentoStoreCode: 'fr_BE', cartDisplayPricesInclTax: true },
17
- { locale: 'nl-be', magentoStoreCode: 'nl_BE', cartDisplayPricesInclTax: true },
18
- { locale: 'en-gb', magentoStoreCode: 'en_GB', cartDisplayPricesInclTax: true },
19
- { locale: 'en-ca', magentoStoreCode: 'en_CA' },
16
+ {
17
+ locale: 'fr-be',
18
+ magentoStoreCode: 'fr_BE',
19
+ cartDisplayPricesInclTax: true,
20
+ linguiLocale: 'fr',
21
+ },
22
+ {
23
+ locale: 'nl-be',
24
+ magentoStoreCode: 'nl_BE',
25
+ cartDisplayPricesInclTax: true,
26
+ linguiLocale: 'nl',
27
+ },
28
+ {
29
+ locale: 'en-gb',
30
+ magentoStoreCode: 'en_GB',
31
+ cartDisplayPricesInclTax: true,
32
+ linguiLocale: 'en',
33
+ },
34
+ { locale: 'en-ca', magentoStoreCode: 'en_CA', linguiLocale: 'en' },
20
35
  ],
21
36
  productFiltersPro: true,
22
37
  productFiltersLayout: 'DEFAULT',
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SidebarGalleryConfigSchema = exports.RecentlyViewedProductsConfigSchema = exports.MagentoConfigurableVariantValuesSchema = exports.GraphCommerceStorefrontConfigSchema = exports.GraphCommerceDebugConfigSchema = exports.GraphCommerceConfigSchema = exports.SidebarGalleryPaginationVariantSchema = exports.ProductFiltersLayoutSchema = exports.CompareVariantSchema = exports.definedNonNullAnySchema = exports.isDefinedNonNullAny = void 0;
3
+ exports.SidebarGalleryConfigSchema = exports.RecentlyViewedProductsConfigSchema = exports.MagentoConfigurableVariantValuesSchema = exports.GraphCommerceStorefrontConfigSchema = exports.GraphCommerceDebugConfigSchema = exports.GraphCommerceConfigSchema = exports.DatalayerConfigSchema = exports.SidebarGalleryPaginationVariantSchema = exports.ProductFiltersLayoutSchema = exports.CompareVariantSchema = exports.definedNonNullAnySchema = exports.isDefinedNonNullAny = void 0;
4
4
  /* eslint-disable */
5
5
  const zod_1 = require("zod");
6
6
  const isDefinedNonNullAny = (v) => v !== undefined && v !== null;
@@ -9,6 +9,12 @@ exports.definedNonNullAnySchema = zod_1.z.any().refine((v) => (0, exports.isDefi
9
9
  exports.CompareVariantSchema = zod_1.z.enum(['CHECKBOX', 'ICON']);
10
10
  exports.ProductFiltersLayoutSchema = zod_1.z.enum(['DEFAULT', 'SIDEBAR']);
11
11
  exports.SidebarGalleryPaginationVariantSchema = zod_1.z.enum(['DOTS', 'THUMBNAILS_BOTTOM']);
12
+ function DatalayerConfigSchema() {
13
+ return zod_1.z.object({
14
+ coreWebVitals: zod_1.z.boolean().nullish()
15
+ });
16
+ }
17
+ exports.DatalayerConfigSchema = DatalayerConfigSchema;
12
18
  function GraphCommerceConfigSchema() {
13
19
  return zod_1.z.object({
14
20
  canonicalBaseUrl: zod_1.z.string().min(1),
@@ -20,6 +26,7 @@ function GraphCommerceConfigSchema() {
20
26
  crossSellsHideCartItems: zod_1.z.boolean().nullish(),
21
27
  crossSellsRedirectItems: zod_1.z.boolean().nullish(),
22
28
  customerRequireEmailConfirmation: zod_1.z.boolean().nullish(),
29
+ dataLayer: DatalayerConfigSchema().nullish(),
23
30
  debug: GraphCommerceDebugConfigSchema().nullish(),
24
31
  demoMode: zod_1.z.boolean().nullish(),
25
32
  enableGuestCheckoutLogin: zod_1.z.boolean().nullish(),
@@ -9,51 +9,96 @@ const resolveDependency_1 = require("../utils/resolveDependency");
9
9
  const findPlugins_1 = require("./findPlugins");
10
10
  const generateInterceptors_1 = require("./generateInterceptors");
11
11
  const writeInterceptors_1 = require("./writeInterceptors");
12
+ let interceptors;
13
+ let interceptorByDepependency;
14
+ let generating = false;
15
+ // let totalGenerationTime = 0
12
16
  class InterceptorPlugin {
13
17
  config;
14
- interceptors;
15
- interceptorByDepependency;
18
+ regenerate;
16
19
  resolveDependency;
17
- constructor(config) {
20
+ constructor(config, regenerate = false) {
18
21
  this.config = config;
22
+ this.regenerate = regenerate;
19
23
  this.resolveDependency = (0, resolveDependency_1.resolveDependency)();
20
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
21
- const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config);
22
- this.interceptors = (0, generateInterceptors_1.generateInterceptors)(plugins, this.resolveDependency, this.config.debug);
23
- this.interceptorByDepependency = Object.fromEntries(Object.values(this.interceptors).map((i) => [i.dependency, i]));
24
- (0, writeInterceptors_1.writeInterceptors)(this.interceptors);
24
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
25
+ if (regenerate)
26
+ this.#generateInterceptors();
25
27
  }
28
+ #generateInterceptors = async () => {
29
+ if (generating)
30
+ return {};
31
+ generating = true;
32
+ const start = Date.now();
33
+ // console.log('Generating interceptors...')
34
+ const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config);
35
+ // console.log(errors)
36
+ // const found = Date.now()
37
+ // console.log('Found plugins in', found - start, 'ms')
38
+ const generatedInterceptors = await (0, generateInterceptors_1.generateInterceptors)(plugins, this.resolveDependency, this.config.debug);
39
+ // const generated = Date.now()
40
+ // console.log('Generated interceptors in', generated - found, 'ms')
41
+ await (0, writeInterceptors_1.writeInterceptors)(generatedInterceptors);
42
+ // const wrote = Date.now()
43
+ // console.log('Wrote interceptors in', wrote - generated, 'ms')
44
+ interceptors = generatedInterceptors;
45
+ interceptorByDepependency = Object.fromEntries(Object.values(interceptors).map((i) => [i.dependency, i]));
46
+ // totalGenerationTime += Date.now() - start
47
+ generating = false;
48
+ return generatedInterceptors;
49
+ };
26
50
  apply(compiler) {
27
51
  const logger = compiler.getInfrastructureLogger('InterceptorPlugin');
28
52
  // After the compilation has succeeded we watch all possible plugin locations.
29
- compiler.hooks.afterCompile.tap('InterceptorPlugin', (compilation) => {
30
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
31
- const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config);
32
- plugins.forEach((p) => {
33
- const absoluteFilePath = `${path_1.default.join(process.cwd(), this.resolveDependency(p.plugin).fromRoot)}.tsx`;
34
- compilation.fileDependencies.add(absoluteFilePath);
53
+ if (this.regenerate) {
54
+ compiler.hooks.afterCompile.tap('InterceptorPlugin', (compilation) => {
55
+ // console.log('generate interceptors after compile')
56
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
57
+ const [plugins, errors] = (0, findPlugins_1.findPlugins)(this.config);
58
+ plugins.forEach((p) => {
59
+ const source = this.resolveDependency(p.sourceModule);
60
+ if (source) {
61
+ const absoluteFilePath = `${path_1.default.join(process.cwd(), source.fromRoot)}.tsx`;
62
+ compilation.fileDependencies.add(absoluteFilePath);
63
+ }
64
+ });
65
+ // eslint-disable-next-line @typescript-eslint/no-floating-promises
66
+ this.#generateInterceptors().then((i) => {
67
+ Object.entries(i).forEach(([key, { sourcePath }]) => {
68
+ const absoluteFilePath = path_1.default.join(process.cwd(), sourcePath);
69
+ compilation.fileDependencies.add(absoluteFilePath);
70
+ });
71
+ });
35
72
  });
36
- this.interceptors = (0, generateInterceptors_1.generateInterceptors)(plugins, this.resolveDependency, this.config.debug);
37
- this.interceptorByDepependency = Object.fromEntries(Object.values(this.interceptors).map((i) => [i.dependency, i]));
38
- (0, writeInterceptors_1.writeInterceptors)(this.interceptors);
39
- });
73
+ }
40
74
  compiler.hooks.normalModuleFactory.tap('InterceptorPlugin', (nmf) => {
41
75
  nmf.hooks.beforeResolve.tap('InterceptorPlugin', (resource) => {
42
76
  const issuer = resource.contextInfo.issuer ?? '';
43
77
  const requestPath = path_1.default.relative(process.cwd(), path_1.default.resolve(resource.context, resource.request));
44
- if (issuer.endsWith('interceptor.tsx') && this.interceptors[requestPath]) {
78
+ if (!interceptors || !interceptorByDepependency) {
79
+ // console.log('interceptors not ready')
80
+ return;
81
+ }
82
+ const split = requestPath.split('/');
83
+ const targets = [
84
+ `${split[split.length - 1]}.interceptor.tsx`,
85
+ `${split[split.length - 1]}.interceptor.ts`,
86
+ ];
87
+ if (targets.some((target) => issuer.endsWith(target)) && interceptors[requestPath]) {
45
88
  logger.log(`Interceptor ${issuer} is requesting the original ${requestPath}`);
46
89
  return;
47
90
  }
48
- const interceptorForRequest = this.interceptorByDepependency[resource.request];
91
+ const interceptorForRequest = interceptorByDepependency[resource.request];
49
92
  if (interceptorForRequest) {
50
- logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`);
51
- resource.request = `${interceptorForRequest.denormalized}.interceptor.tsx`;
93
+ const extension = interceptorForRequest.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts';
94
+ resource.request = `${interceptorForRequest.denormalized}.interceptor${extension}`;
95
+ logger.log(`Intercepting dep... ${interceptorForRequest.dependency}`, resource.request);
52
96
  }
53
- const interceptorForPath = this.interceptors[requestPath];
97
+ const interceptorForPath = interceptors[requestPath];
54
98
  if (interceptorForPath) {
55
- logger.log(`Intercepting fromRoot... ${interceptorForPath.fromRoot}`);
56
- resource.request = `${resource.request}.interceptor.tsx`;
99
+ const extension = interceptorForPath.sourcePath.endsWith('.tsx') ? '.tsx' : '.ts';
100
+ resource.request = `${resource.request}.interceptor${extension}`;
101
+ logger.log(`Intercepting fromRoot... ${interceptorForPath.dependency}`, resource.request);
57
102
  }
58
103
  });
59
104
  });
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RenameVisitor = void 0;
4
+ const Visitor_1 = require("./Visitor");
5
+ class RenameVisitor extends Visitor_1.Visitor {
6
+ replace;
7
+ suffix;
8
+ constructor(replace, suffix) {
9
+ super();
10
+ this.replace = replace;
11
+ this.suffix = suffix;
12
+ }
13
+ visitIdentifier(n) {
14
+ if (this.replace.includes(n.value))
15
+ n.value = this.suffix(n.value);
16
+ return n;
17
+ }
18
+ }
19
+ exports.RenameVisitor = RenameVisitor;