@graphcommerce/next-config 11.0.0-canary.48 → 11.0.0-canary.50
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.
- package/CHANGELOG.md +14 -0
- package/Config.graphqls +24 -7
- package/__tests__/config/defaultValues.ts +8 -0
- package/__tests__/utils/findParentPath.ts +36 -0
- package/dist/generated/config.js +10 -10
- package/dist/index.js +160 -155
- package/dist/utils/findParentPath.js +6 -4
- package/package.json +4 -2
- package/src/commands/generateConfig.ts +21 -13
- package/src/commands/generateConfigValues.ts +160 -226
- package/src/generated/config.ts +27 -12
- package/src/utils/findParentPath.ts +13 -7
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Change Log
|
|
2
2
|
|
|
3
|
+
## 11.0.0-canary.50
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`abcfce1`](https://github.com/graphcommerce-org/graphcommerce/commit/abcfce130beaf5544a6ceec794fdeb99e4b3e3ba) - **Breaking change:** configuration fields are server-only, unless their definition in `Config.graphqls` has `@public`. In the browser, `@graphcommerce/next-config/config` resolves to a file with only the `@public` fields, so secrets such as `previewSecret` and `hygraphSecret` stay out of the client JavaScript and its source maps. Turbopack stops the build on a browser import of a server-only field. See [docs/upgrading/graphcommerce-10-to-11.md](docs/upgrading/graphcommerce-10-to-11.md). ([@paales](https://github.com/paales))
|
|
8
|
+
|
|
9
|
+
### Patch Changes
|
|
10
|
+
|
|
11
|
+
- [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`d17e00b`](https://github.com/graphcommerce-org/graphcommerce/commit/d17e00b0553402cd956c0b93c32979b1ef89f0c7) - A configuration field without a value has the default from `Config.graphqls`, such as `containerSizingShell: 'FULL_WIDTH'`. ([@paales](https://github.com/paales))
|
|
12
|
+
|
|
13
|
+
- [#2707](https://github.com/graphcommerce-org/graphcommerce/pull/2707) [`6f3fcab`](https://github.com/graphcommerce-org/graphcommerce/commit/6f3fcab35fe9b7ab58825ed0ee0c2663bb28e918) - `findParentPath()` returns a parent `@graphcommerce` package only when its `workspaces` contain the directory. Codegen in a checkout inside another GraphCommerce repository, such as a git worktree in `.tmp`, changes only the files of that checkout. ([@paales](https://github.com/paales))
|
|
14
|
+
|
|
15
|
+
## 11.0.0-canary.49
|
|
16
|
+
|
|
3
17
|
## 11.0.0-canary.48
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/Config.graphqls
CHANGED
|
@@ -40,6 +40,20 @@ You can also use the configuration in your `.meshrc.yml` by accessing
|
|
|
40
40
|
endpoint: '{graphCommerce.magentoEndpoint}'
|
|
41
41
|
```
|
|
42
42
|
|
|
43
|
+
## Public and server-only configuration
|
|
44
|
+
|
|
45
|
+
A field with `@public` is available in the browser. A field without `@public` is server-only:
|
|
46
|
+
code that runs in the browser cannot read it.
|
|
47
|
+
|
|
48
|
+
- Turbopack stops the build when browser code imports a server-only field from
|
|
49
|
+
`@graphcommerce/next-config/config`.
|
|
50
|
+
- A server-only field of a storefront, such as `useStorefrontConfig().myServerField`, throws in
|
|
51
|
+
development and returns `undefined` in production.
|
|
52
|
+
- A server-only field of a section, such as `algolia.searchOnlyApiKey`, is `undefined`.
|
|
53
|
+
|
|
54
|
+
Put `@public` on fields with a scalar or enum type. In the browser, a field with an input type, such
|
|
55
|
+
as `debug: GraphCommerceDebugConfig`, contains only the `@public` fields of that input.
|
|
56
|
+
|
|
43
57
|
## Environment variables to override configuration
|
|
44
58
|
|
|
45
59
|
Configuration values can be overwriten by environment variables, with the following rules:
|
|
@@ -64,10 +78,11 @@ Create a graphql/Config.graphqls file in your project and extend the GraphCommer
|
|
|
64
78
|
|
|
65
79
|
```graphql
|
|
66
80
|
extend input GraphCommerceConfig {
|
|
67
|
-
myConfig: String # or Boolean, or Int, or Float, make required with `!`
|
|
81
|
+
myConfig: String @public # or Boolean, or Int, or Float, make required with `!`
|
|
82
|
+
myApiSecret: String
|
|
68
83
|
}
|
|
69
84
|
extend input GraphCommerceStorefrontConfig {
|
|
70
|
-
myField: Boolean
|
|
85
|
+
myField: Boolean @public
|
|
71
86
|
}
|
|
72
87
|
```
|
|
73
88
|
|
|
@@ -102,7 +117,7 @@ input GraphCommerceConfig {
|
|
|
102
117
|
- https://example.com/en
|
|
103
118
|
- https://example.com/en-US
|
|
104
119
|
"""
|
|
105
|
-
canonicalBaseUrl: String!
|
|
120
|
+
canonicalBaseUrl: String! @public
|
|
106
121
|
|
|
107
122
|
"""
|
|
108
123
|
To enable next.js' preview mode, configure the secret you'd like to use.
|
|
@@ -124,19 +139,19 @@ input GraphCommerceStorefrontConfig {
|
|
|
124
139
|
- If there are more, the first one is used.
|
|
125
140
|
- If there is none, the first entry is used.
|
|
126
141
|
"""
|
|
127
|
-
defaultLocale: Boolean
|
|
142
|
+
defaultLocale: Boolean @public
|
|
128
143
|
|
|
129
144
|
"""
|
|
130
145
|
Domain configuration, must be a domain https://tools.ietf.org/html/rfc3986
|
|
131
146
|
"""
|
|
132
|
-
domain: String
|
|
147
|
+
domain: String @public
|
|
133
148
|
|
|
134
149
|
"""
|
|
135
150
|
Must be a [locale string](https://www.unicode.org/reports/tr35/tr35-59/tr35.html#Identifiers) for automatic redirects to work.
|
|
136
151
|
|
|
137
152
|
This value can be used as a sub-path identifier only, make sure linguiLocale is configured for each URL.
|
|
138
153
|
"""
|
|
139
|
-
locale: String!
|
|
154
|
+
locale: String! @public
|
|
140
155
|
|
|
141
156
|
"""
|
|
142
157
|
Allow the site to be indexed by search engines.
|
|
@@ -152,7 +167,7 @@ input GraphCommerceStorefrontConfig {
|
|
|
152
167
|
- https://example.com/en
|
|
153
168
|
- https://example.com/en-US
|
|
154
169
|
"""
|
|
155
|
-
canonicalBaseUrl: String
|
|
170
|
+
canonicalBaseUrl: String @public
|
|
156
171
|
}
|
|
157
172
|
|
|
158
173
|
"""
|
|
@@ -181,3 +196,5 @@ input GraphCommerceDebugConfig {
|
|
|
181
196
|
"""
|
|
182
197
|
pluginStatus: Boolean
|
|
183
198
|
}
|
|
199
|
+
|
|
200
|
+
directive @public on INPUT_FIELD_DEFINITION
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { GraphCommerceConfigSchema } from '../../src/generated/config'
|
|
2
|
+
|
|
3
|
+
it('applies the GraphQL default to a field without a value', () => {
|
|
4
|
+
const { shape } = GraphCommerceConfigSchema()
|
|
5
|
+
expect(shape.containerSizingShell.parse(undefined)).toBe('FULL_WIDTH')
|
|
6
|
+
expect(shape.containerSizingShell.parse(null)).toBeNull()
|
|
7
|
+
expect(shape.containerSizingShell.parse('BREAKPOINT')).toBe('BREAKPOINT')
|
|
8
|
+
})
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
import os from 'os'
|
|
3
|
+
import path from 'path'
|
|
4
|
+
import { findParentPath } from '../../src/utils/findParentPath'
|
|
5
|
+
|
|
6
|
+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'find-parent-path-'))
|
|
7
|
+
|
|
8
|
+
const write = (dir: string, packageJson: object) => {
|
|
9
|
+
fs.mkdirSync(path.join(root, dir), { recursive: true })
|
|
10
|
+
fs.writeFileSync(path.join(root, dir, 'package.json'), JSON.stringify(packageJson))
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
write('.', {
|
|
14
|
+
name: '@graphcommerce/private',
|
|
15
|
+
workspaces: ['graphcommerce', 'graphcommerce/examples/*'],
|
|
16
|
+
})
|
|
17
|
+
write('graphcommerce', { name: '@graphcommerce/graphcommerce', workspaces: ['examples/*'] })
|
|
18
|
+
write('graphcommerce/examples/shop', { name: '@graphcommerce/shop' })
|
|
19
|
+
write('.tmp/worktree', { name: '@graphcommerce/private', workspaces: ['graphcommerce'] })
|
|
20
|
+
write('.tmp/worktree/graphcommerce', { name: '@graphcommerce/graphcommerce' })
|
|
21
|
+
|
|
22
|
+
afterAll(() => fs.rmSync(root, { recursive: true, force: true }))
|
|
23
|
+
|
|
24
|
+
it('returns the parent that has the directory as a workspace', () => {
|
|
25
|
+
expect(findParentPath(path.join(root, 'graphcommerce/examples/shop'))).toBe(
|
|
26
|
+
path.join(root, 'graphcommerce'),
|
|
27
|
+
)
|
|
28
|
+
expect(findParentPath(path.join(root, 'graphcommerce'))).toBe(root)
|
|
29
|
+
expect(findParentPath(path.join(root, '.tmp/worktree/graphcommerce'))).toBe(
|
|
30
|
+
path.join(root, '.tmp/worktree'),
|
|
31
|
+
)
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
it('returns null for a checkout inside another repository', () => {
|
|
35
|
+
expect(findParentPath(path.join(root, '.tmp/worktree'))).toBeNull()
|
|
36
|
+
})
|
package/dist/generated/config.js
CHANGED
|
@@ -22,17 +22,17 @@ function DatalayerConfigSchema() {
|
|
|
22
22
|
}
|
|
23
23
|
function GraphCommerceConfigSchema() {
|
|
24
24
|
return z.object({
|
|
25
|
-
breadcrumbs: z.boolean().
|
|
25
|
+
breadcrumbs: z.boolean().nullish().default(false),
|
|
26
26
|
canonicalBaseUrl: z.string().min(1),
|
|
27
27
|
cartDisplayPricesInclTax: z.boolean().nullish(),
|
|
28
28
|
compare: z.boolean().nullish(),
|
|
29
|
-
compareVariant: CompareVariantSchema.default("ICON")
|
|
30
|
-
configurableVariantForSimple: z.boolean().
|
|
29
|
+
compareVariant: CompareVariantSchema.nullish().default("ICON"),
|
|
30
|
+
configurableVariantForSimple: z.boolean().nullish().default(false),
|
|
31
31
|
configurableVariantValues: z.lazy(() => MagentoConfigurableVariantValuesSchema().nullish()),
|
|
32
|
-
containerSizingContent: ContainerSizingSchema.default("FULL_WIDTH")
|
|
33
|
-
containerSizingShell: ContainerSizingSchema.default("FULL_WIDTH")
|
|
34
|
-
crossSellsHideCartItems: z.boolean().
|
|
35
|
-
crossSellsRedirectItems: z.boolean().
|
|
32
|
+
containerSizingContent: ContainerSizingSchema.nullish().default("FULL_WIDTH"),
|
|
33
|
+
containerSizingShell: ContainerSizingSchema.nullish().default("FULL_WIDTH"),
|
|
34
|
+
crossSellsHideCartItems: z.boolean().nullish().default(false),
|
|
35
|
+
crossSellsRedirectItems: z.boolean().nullish().default(false),
|
|
36
36
|
customerAddressNoteEnable: z.boolean().nullish(),
|
|
37
37
|
customerCompanyFieldsEnable: z.boolean().nullish(),
|
|
38
38
|
customerDeleteEnabled: z.boolean().nullish(),
|
|
@@ -44,7 +44,7 @@ function GraphCommerceConfigSchema() {
|
|
|
44
44
|
googlePlaystore: z.lazy(() => GraphCommerceGooglePlaystoreConfigSchema().nullish()),
|
|
45
45
|
googleRecaptchaKey: z.string().nullish(),
|
|
46
46
|
googleTagmanagerId: z.string().nullish(),
|
|
47
|
-
graphqlMeshEditMode: z.boolean().
|
|
47
|
+
graphqlMeshEditMode: z.boolean().nullish().default(false),
|
|
48
48
|
hygraphManagementApi: z.string().nullish(),
|
|
49
49
|
hygraphProjectId: z.string().nullish(),
|
|
50
50
|
hygraphWriteAccessToken: z.string().nullish(),
|
|
@@ -53,9 +53,9 @@ function GraphCommerceConfigSchema() {
|
|
|
53
53
|
magentoVersion: z.number(),
|
|
54
54
|
permissions: z.lazy(() => GraphCommercePermissionsSchema().nullish()),
|
|
55
55
|
previewSecret: z.string().nullish(),
|
|
56
|
-
productFiltersLayout: ProductFiltersLayoutSchema.default("DEFAULT")
|
|
56
|
+
productFiltersLayout: ProductFiltersLayoutSchema.nullish().default("DEFAULT"),
|
|
57
57
|
productFiltersPro: z.boolean().nullish(),
|
|
58
|
-
productListPaginationVariant: PaginationVariantSchema.default("COMPACT")
|
|
58
|
+
productListPaginationVariant: PaginationVariantSchema.nullish().default("COMPACT"),
|
|
59
59
|
productRoute: z.string().nullish(),
|
|
60
60
|
recentlyViewedProducts: z.lazy(() => RecentlyViewedProductsConfigSchema().nullish()),
|
|
61
61
|
robotsAllow: z.boolean().nullish(),
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import { spawn } from 'child_process';
|
|
|
7
7
|
import { l as loadConfig, t as toEnvStr } from './loadConfig-S8JJz4LU.js';
|
|
8
8
|
export { r as replaceConfigInString } from './loadConfig-S8JJz4LU.js';
|
|
9
9
|
import { parseFileSync, parseSync as parseSync$1, transformFileSync } from '@swc/core';
|
|
10
|
-
import fs$1, { writeFileSync, readFileSync,
|
|
10
|
+
import fs$1, { writeFileSync, readFileSync, rmSync, mkdirSync, existsSync } from 'fs';
|
|
11
11
|
import { resolve as resolve$2 } from 'import-meta-resolve';
|
|
12
12
|
import assert from 'assert';
|
|
13
13
|
import crypto from 'crypto';
|
|
@@ -17,8 +17,8 @@ import prettierConf from '@graphcommerce/prettier-config-pwa';
|
|
|
17
17
|
import prettier from 'prettier';
|
|
18
18
|
import fg from 'fast-glob';
|
|
19
19
|
import { generate } from '@graphql-codegen/cli';
|
|
20
|
-
import {
|
|
21
|
-
export { GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
|
|
20
|
+
import { parse, Kind } from 'graphql';
|
|
21
|
+
export { GraphCommerceConfigSchema, GraphCommerceDebugConfigSchema, GraphCommerceStorefrontConfigSchema } from './generated/config.js';
|
|
22
22
|
import 'cosmiconfig';
|
|
23
23
|
import 'node:fs';
|
|
24
24
|
import 'node:module';
|
|
@@ -1395,6 +1395,10 @@ async function exportConfig() {
|
|
|
1395
1395
|
}
|
|
1396
1396
|
|
|
1397
1397
|
const packages = [...resolveDependenciesSync().values()].filter((p) => p !== ".");
|
|
1398
|
+
const configSchemaLocations = [
|
|
1399
|
+
"graphql/Config.graphqls",
|
|
1400
|
+
...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
|
|
1401
|
+
];
|
|
1398
1402
|
const resolve$1 = resolveDependency();
|
|
1399
1403
|
dotenv.config({ quiet: true });
|
|
1400
1404
|
async function generateConfig() {
|
|
@@ -1402,13 +1406,9 @@ async function generateConfig() {
|
|
|
1402
1406
|
if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
|
|
1403
1407
|
const targetTs = `${resolved.root}/src/generated/config.ts`;
|
|
1404
1408
|
const targetJs = `${resolved.root}/dist/generated/config.js`;
|
|
1405
|
-
const schemaLocations = [
|
|
1406
|
-
"graphql/Config.graphqls",
|
|
1407
|
-
...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`])
|
|
1408
|
-
];
|
|
1409
1409
|
await generate({
|
|
1410
1410
|
silent: true,
|
|
1411
|
-
schema:
|
|
1411
|
+
schema: configSchemaLocations,
|
|
1412
1412
|
generates: {
|
|
1413
1413
|
[targetTs]: {
|
|
1414
1414
|
plugins: ["typescript", "typescript-validation-schema"],
|
|
@@ -1434,13 +1434,21 @@ async function generateConfig() {
|
|
|
1434
1434
|
});
|
|
1435
1435
|
writeFileSync(
|
|
1436
1436
|
targetTs,
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
(
|
|
1442
|
-
|
|
1443
|
-
|
|
1437
|
+
// typescript-validation-schema writes `.default(x).nullish()`: `.nullish()` returns undefined
|
|
1438
|
+
// before `.default()` runs.
|
|
1439
|
+
await prettier.format(
|
|
1440
|
+
readFileSync(targetTs, "utf-8").replace(
|
|
1441
|
+
/\.default\(([^()]+)\)\.nullish\(\)/g,
|
|
1442
|
+
".nullish().default($1)"
|
|
1443
|
+
),
|
|
1444
|
+
{
|
|
1445
|
+
...prettierConf,
|
|
1446
|
+
parser: "typescript",
|
|
1447
|
+
plugins: prettierConf.plugins?.filter(
|
|
1448
|
+
(p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
|
|
1449
|
+
)
|
|
1450
|
+
}
|
|
1451
|
+
)
|
|
1444
1452
|
);
|
|
1445
1453
|
const result = transformFileSync(targetTs, {
|
|
1446
1454
|
module: { type: "nodenext" },
|
|
@@ -1451,155 +1459,152 @@ async function generateConfig() {
|
|
|
1451
1459
|
|
|
1452
1460
|
dotenv.config({ quiet: true });
|
|
1453
1461
|
const resolve = resolveDependency();
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
}
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
if (typeof value === "boolean" || typeof value === "number") return String(value);
|
|
1462
|
-
if (Array.isArray(value) || typeof value === "object" && value !== null) {
|
|
1463
|
-
return JSON.stringify(value, null, 2);
|
|
1464
|
-
}
|
|
1465
|
-
return JSON.stringify(value);
|
|
1466
|
-
}
|
|
1467
|
-
function shouldCreateFile(value) {
|
|
1468
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1469
|
-
}
|
|
1470
|
-
function getSectionSchemaKeys(configKey) {
|
|
1471
|
-
try {
|
|
1472
|
-
const mainSchema = GraphCommerceConfigSchema();
|
|
1473
|
-
const sectionSchema = mainSchema.shape[configKey];
|
|
1474
|
-
if (!sectionSchema) return [];
|
|
1475
|
-
let unwrappedSchema = sectionSchema;
|
|
1476
|
-
while (true) {
|
|
1477
|
-
if (!unwrappedSchema || typeof unwrappedSchema !== "object") break;
|
|
1478
|
-
if (!("_def" in unwrappedSchema)) break;
|
|
1479
|
-
const def = unwrappedSchema._def;
|
|
1480
|
-
const typeName = def?.typeName;
|
|
1481
|
-
if (typeName === "ZodLazy" && def.getter) {
|
|
1482
|
-
unwrappedSchema = def.getter();
|
|
1483
|
-
continue;
|
|
1484
|
-
}
|
|
1485
|
-
if (def.innerType) {
|
|
1486
|
-
unwrappedSchema = def.innerType;
|
|
1487
|
-
continue;
|
|
1488
|
-
}
|
|
1489
|
-
if (typeName === "ZodObject" && def.shape) {
|
|
1490
|
-
const shape = typeof def.shape === "function" ? def.shape() : def.shape;
|
|
1491
|
-
return Object.keys(shape || {});
|
|
1492
|
-
}
|
|
1493
|
-
break;
|
|
1494
|
-
}
|
|
1495
|
-
if (unwrappedSchema && "shape" in unwrappedSchema) {
|
|
1496
|
-
const shape = typeof unwrappedSchema.shape === "function" ? unwrappedSchema.shape() : unwrappedSchema.shape;
|
|
1497
|
-
return Object.keys(shape || {});
|
|
1498
|
-
}
|
|
1499
|
-
} catch {
|
|
1500
|
-
}
|
|
1501
|
-
return [];
|
|
1502
|
-
}
|
|
1503
|
-
async function createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey) {
|
|
1504
|
-
const fileName = `${toFileName(sectionName)}.ts`;
|
|
1505
|
-
const filePath = path.join(targetDir, fileName);
|
|
1506
|
-
const distFileName = `${toFileName(sectionName)}.js`;
|
|
1507
|
-
const distFilePath = path.join(targetDistDir, distFileName);
|
|
1508
|
-
const schemaKeys = getSectionSchemaKeys(configKey);
|
|
1509
|
-
const completeSectionValue = {};
|
|
1510
|
-
for (const key of schemaKeys) {
|
|
1511
|
-
completeSectionValue[key] = sectionValue[key];
|
|
1512
|
-
}
|
|
1513
|
-
const exports = Object.entries(completeSectionValue).map(([key, value]) => {
|
|
1514
|
-
const valueStr = generateValueLiteral(value);
|
|
1515
|
-
const propertyPath = `'${sectionName}.${key}'`;
|
|
1516
|
-
const typeAnnotation = `: Get<GraphCommerceConfig, ${propertyPath}>`;
|
|
1517
|
-
return `export const ${key}${typeAnnotation} = ${valueStr}`;
|
|
1518
|
-
}).join("\n\n");
|
|
1519
|
-
const imports = `import type { GraphCommerceConfig } from '../config'
|
|
1520
|
-
import type { Get } from 'type-fest'` ;
|
|
1521
|
-
const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
|
|
1522
|
-
${imports}
|
|
1523
|
-
|
|
1524
|
-
${exports}
|
|
1525
|
-
`;
|
|
1526
|
-
const formattedContent = await prettier.format(content, {
|
|
1527
|
-
...prettierConf,
|
|
1528
|
-
parser: "typescript",
|
|
1529
|
-
plugins: prettierConf.plugins?.filter(
|
|
1530
|
-
(p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
|
|
1531
|
-
)
|
|
1532
|
-
});
|
|
1533
|
-
writeFileSync(filePath, formattedContent);
|
|
1534
|
-
const result = transformFileSync(filePath, {
|
|
1535
|
-
module: { type: "nodenext" },
|
|
1536
|
-
env: { targets: { node: "18" } }
|
|
1537
|
-
});
|
|
1538
|
-
writeFileSync(distFilePath, result.code);
|
|
1539
|
-
}
|
|
1462
|
+
const header = `// Auto-generated by 'yarn graphcommerce codegen-config-values'`;
|
|
1463
|
+
const typeImports = `import type { GraphCommerceConfig } from '../config'
|
|
1464
|
+
import type { Get } from 'type-fest'`;
|
|
1465
|
+
const literal = (value) => value === void 0 ? "undefined" : JSON.stringify(value, null, 2);
|
|
1466
|
+
const namedType = (type) => type.kind === Kind.NAMED_TYPE ? type.name.value : namedType(type.type);
|
|
1467
|
+
const isPublic = (field) => Boolean(field.directives?.some((directive) => directive.name.value === "public"));
|
|
1468
|
+
const isSection = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1540
1469
|
async function generateConfigValues() {
|
|
1541
1470
|
const resolved = resolve("@graphcommerce/next-config");
|
|
1542
1471
|
if (!resolved) throw Error("Could not resolve @graphcommerce/next-config");
|
|
1543
1472
|
const config = loadConfig(process.cwd());
|
|
1544
|
-
const
|
|
1545
|
-
const
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
}
|
|
1549
|
-
|
|
1550
|
-
|
|
1473
|
+
const srcDir = `${resolved.root}/src/generated/configValues`;
|
|
1474
|
+
const distDir = `${resolved.root}/dist/generated/configValues`;
|
|
1475
|
+
const publicOnlyDir = `${distDir}/publicOnly`;
|
|
1476
|
+
rmSync(srcDir, { recursive: true, force: true });
|
|
1477
|
+
rmSync(distDir, { recursive: true, force: true });
|
|
1478
|
+
mkdirSync(srcDir, { recursive: true });
|
|
1479
|
+
mkdirSync(publicOnlyDir, { recursive: true });
|
|
1480
|
+
const inputs = /* @__PURE__ */ new Map();
|
|
1481
|
+
for (const location of configSchemaLocations.filter((l) => existsSync(l))) {
|
|
1482
|
+
for (const def of parse(readFileSync(location, "utf-8")).definitions) {
|
|
1483
|
+
if (def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION && def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION)
|
|
1484
|
+
continue;
|
|
1485
|
+
const typeName = def.name.value;
|
|
1486
|
+
inputs.set(typeName, [...inputs.get(typeName) ?? [], ...def.fields ?? []]);
|
|
1487
|
+
}
|
|
1551
1488
|
}
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1489
|
+
for (const [typeName, fields] of inputs) {
|
|
1490
|
+
const misplaced = fields.find((f) => isPublic(f) && inputs.has(namedType(f.type)));
|
|
1491
|
+
if (misplaced) {
|
|
1492
|
+
throw Error(
|
|
1493
|
+
`@public on ${typeName}.${misplaced.name.value}: add @public to the fields of ${namedType(misplaced.type)}.`
|
|
1494
|
+
);
|
|
1495
|
+
}
|
|
1559
1496
|
}
|
|
1560
|
-
const
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
if (
|
|
1565
|
-
|
|
1566
|
-
|
|
1497
|
+
const hasPublic = (typeName) => (inputs.get(typeName) ?? []).some(
|
|
1498
|
+
(f) => inputs.has(namedType(f.type)) ? hasPublic(namedType(f.type)) : isPublic(f)
|
|
1499
|
+
);
|
|
1500
|
+
const browserLiteral = (value, typeName, valuePath) => {
|
|
1501
|
+
if (Array.isArray(value))
|
|
1502
|
+
return `[${value.map((item) => browserLiteral(item, typeName, `${valuePath}[]`)).join(",\n")}]`;
|
|
1503
|
+
if (!isSection(value)) return literal(value);
|
|
1504
|
+
const properties = [];
|
|
1505
|
+
const getters = [];
|
|
1506
|
+
for (const field of inputs.get(typeName) ?? []) {
|
|
1507
|
+
const name = field.name.value;
|
|
1508
|
+
const fieldType = namedType(field.type);
|
|
1509
|
+
const isInput = inputs.has(fieldType);
|
|
1510
|
+
if (!(isInput ? hasPublic(fieldType) : isPublic(field))) {
|
|
1511
|
+
const hint = isInput ? `the fields of ${fieldType}` : `${typeName}.${name}`;
|
|
1512
|
+
getters.push(`${name}: serverOnly('${valuePath}.${name}', '${hint}')`);
|
|
1513
|
+
} else if (value[name] !== void 0) {
|
|
1514
|
+
const fieldValue = isInput ? browserLiteral(value[name], fieldType, `${valuePath}.${name}`) : literal(value[name]);
|
|
1515
|
+
properties.push(`${JSON.stringify(name)}: ${fieldValue}`);
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
const object = `{
|
|
1519
|
+
${properties.join(",\n")}
|
|
1520
|
+
}`;
|
|
1521
|
+
return getters.length ? `Object.defineProperties(${object}, {
|
|
1522
|
+
${getters.join(",\n")}
|
|
1523
|
+
})` : object;
|
|
1524
|
+
};
|
|
1525
|
+
const writeServerModule = async (name, content) => {
|
|
1526
|
+
const srcFile = path.join(srcDir, `${name}.ts`);
|
|
1527
|
+
writeFileSync(
|
|
1528
|
+
srcFile,
|
|
1529
|
+
await prettier.format(content, {
|
|
1530
|
+
...prettierConf,
|
|
1531
|
+
parser: "typescript",
|
|
1532
|
+
plugins: prettierConf.plugins?.filter(
|
|
1533
|
+
(p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
|
|
1534
|
+
)
|
|
1535
|
+
})
|
|
1536
|
+
);
|
|
1537
|
+
const { code } = transformFileSync(srcFile, {
|
|
1538
|
+
module: { type: "nodenext" },
|
|
1539
|
+
env: { targets: { node: "20" } }
|
|
1540
|
+
});
|
|
1541
|
+
writeFileSync(path.join(distDir, `${name}.js`), code);
|
|
1542
|
+
};
|
|
1543
|
+
const writePublicOnlyModule = (name, serverOnlyNames, exports) => {
|
|
1544
|
+
const lines = [
|
|
1545
|
+
header,
|
|
1546
|
+
"// Browser build of @graphcommerce/next-config/config: only fields with @public in Config.graphqls.",
|
|
1547
|
+
"// Add @public to a field to read it in the browser. Keep secrets server-only.",
|
|
1548
|
+
...serverOnlyNames.length ? [`// Server-only: ${serverOnlyNames.join(", ")}`] : []
|
|
1549
|
+
];
|
|
1550
|
+
if (exports.some((e) => e.includes("serverOnly("))) {
|
|
1551
|
+
lines.push(`const serverOnly = (valuePath, hint) => ({
|
|
1552
|
+
get() {
|
|
1553
|
+
if (process.env.NODE_ENV !== 'production')
|
|
1554
|
+
throw Error(\`\${valuePath} is server-only. Read it on the server or add @public to \${hint} in Config.graphqls.\`)
|
|
1555
|
+
},
|
|
1556
|
+
})`);
|
|
1557
|
+
}
|
|
1558
|
+
writeFileSync(path.join(publicOnlyDir, `${name}.js`), [...lines, ...exports].join("\n"));
|
|
1559
|
+
};
|
|
1560
|
+
const serverExports = [];
|
|
1561
|
+
const browserExports = [];
|
|
1562
|
+
const serverOnlyKeys = [];
|
|
1563
|
+
let sectionCount = 0;
|
|
1564
|
+
for (const field of inputs.get("GraphCommerceConfig") ?? []) {
|
|
1565
|
+
const key = field.name.value;
|
|
1566
|
+
const value = config[key];
|
|
1567
|
+
const fieldType = namedType(field.type);
|
|
1568
|
+
const sectionFields = inputs.get(fieldType) ?? [];
|
|
1569
|
+
if (isSection(value)) {
|
|
1570
|
+
sectionCount++;
|
|
1571
|
+
const sectionExports = sectionFields.map(
|
|
1572
|
+
({ name }) => `export const ${name.value}: Get<GraphCommerceConfig, '${key}.${name.value}'> = ${literal(value[name.value])}`
|
|
1573
|
+
);
|
|
1574
|
+
await writeServerModule(key, [header, typeImports, ...sectionExports].join("\n\n"));
|
|
1575
|
+
serverExports.push(`export * as ${key} from './${key}.js'`);
|
|
1576
|
+
} else {
|
|
1577
|
+
serverExports.push(
|
|
1578
|
+
`export const ${key}: Get<GraphCommerceConfig, '${key}'> = ${literal(value)}`
|
|
1579
|
+
);
|
|
1580
|
+
}
|
|
1581
|
+
if (!(inputs.has(fieldType) ? hasPublic(fieldType) : isPublic(field))) {
|
|
1582
|
+
serverOnlyKeys.push(key);
|
|
1583
|
+
} else if (isSection(value)) {
|
|
1584
|
+
const sectionServerOnly = [];
|
|
1585
|
+
const sectionPublic = [];
|
|
1586
|
+
for (const sectionField of sectionFields) {
|
|
1587
|
+
const name = sectionField.name.value;
|
|
1588
|
+
const nestedType = namedType(sectionField.type);
|
|
1589
|
+
if (!(inputs.has(nestedType) ? hasPublic(nestedType) : isPublic(sectionField)))
|
|
1590
|
+
sectionServerOnly.push(name);
|
|
1591
|
+
else
|
|
1592
|
+
sectionPublic.push(
|
|
1593
|
+
`export const ${name} = ${browserLiteral(value[name], nestedType, `${key}.${name}`)}`
|
|
1594
|
+
);
|
|
1595
|
+
}
|
|
1596
|
+
writePublicOnlyModule(key, sectionServerOnly, sectionPublic);
|
|
1597
|
+
browserExports.push(`export * as ${key} from './${key}.js'`);
|
|
1567
1598
|
} else {
|
|
1568
|
-
const
|
|
1569
|
-
const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`;
|
|
1570
|
-
rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`);
|
|
1599
|
+
browserExports.push(`export const ${key} = ${browserLiteral(value, fieldType, key)}`);
|
|
1571
1600
|
}
|
|
1572
1601
|
}
|
|
1573
|
-
await
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1602
|
+
await writeServerModule("index", [header, typeImports, ...serverExports].join("\n"));
|
|
1603
|
+
writePublicOnlyModule("index", serverOnlyKeys, browserExports);
|
|
1604
|
+
console.log(`\u2705 Generated config values in ${srcDir} and ${distDir}`);
|
|
1605
|
+
console.log(
|
|
1606
|
+
`\u{1F4C1} ${sectionCount} sections, ${serverExports.length} server exports, ${browserExports.length} browser exports`
|
|
1577
1607
|
);
|
|
1578
|
-
const rootImports = `import type { GraphCommerceConfig } from '../config'
|
|
1579
|
-
import type { Get } from 'type-fest'` ;
|
|
1580
|
-
const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
|
|
1581
|
-
${rootImports}
|
|
1582
|
-
|
|
1583
|
-
${rootExports.join("\n")}
|
|
1584
|
-
`;
|
|
1585
|
-
const formattedIndexContent = await prettier.format(indexContent, {
|
|
1586
|
-
...prettierConf,
|
|
1587
|
-
parser: "typescript",
|
|
1588
|
-
plugins: prettierConf.plugins?.filter(
|
|
1589
|
-
(p) => typeof p === "string" && !p.includes("prettier-plugin-sort-imports")
|
|
1590
|
-
)
|
|
1591
|
-
});
|
|
1592
|
-
const indexPath = path.join(targetDir, "index.ts");
|
|
1593
|
-
const distIndexPath = path.join(targetDistDir, "index.js");
|
|
1594
|
-
writeFileSync(indexPath, formattedIndexContent);
|
|
1595
|
-
const indexResult = transformFileSync(indexPath, {
|
|
1596
|
-
module: { type: "nodenext" },
|
|
1597
|
-
env: { targets: { node: "20" } }
|
|
1598
|
-
});
|
|
1599
|
-
writeFileSync(distIndexPath, indexResult.code);
|
|
1600
|
-
console.log(`\u2705 Generated config values in ${targetDir} and ${targetDistDir}`);
|
|
1601
|
-
console.log(`\u{1F4C1} Created ${nestedObjects.length} nested object files + index.ts/.js`);
|
|
1602
|
-
console.log(`\u{1F4DD} Root exports: ${configEntries.length - nestedObjects.length}`);
|
|
1603
1608
|
}
|
|
1604
1609
|
|
|
1605
1610
|
let graphcommerceConfig;
|
|
@@ -1739,4 +1744,4 @@ function withGraphCommerce(nextConfig, cwd = process.cwd()) {
|
|
|
1739
1744
|
};
|
|
1740
1745
|
}
|
|
1741
1746
|
|
|
1742
|
-
export {
|
|
1747
|
+
export { PackagesSort, TopologicalSort, cleanupInterceptors, codegen, codegenInterceptors, configSchemaLocations, copyFiles, exportConfig, findParentPath, g, generateConfig, generateConfigValues, loadConfig, packageRoots, resolveDependenciesSync, resolveDependency, sig, sortDependencies, withGraphCommerce };
|
|
@@ -19,13 +19,15 @@ function findParentPath(directory) {
|
|
|
19
19
|
log(`Looking for parent packages starting from: ${currentDir}`);
|
|
20
20
|
while (currentDir !== path.parse(currentDir).root) {
|
|
21
21
|
const packageJson = findPackageJson(currentDir);
|
|
22
|
-
if (packageJson) {
|
|
23
|
-
log(`Found package.
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
if (packageJson?.name?.startsWith("@graphcommerce/")) {
|
|
23
|
+
log(`Found package ${packageJson.name} in: ${currentDir}`);
|
|
24
|
+
const workspaces = Array.isArray(packageJson.workspaces) ? packageJson.workspaces : packageJson.workspaces?.packages ?? [];
|
|
25
|
+
const relative = path.relative(currentDir, directory);
|
|
26
|
+
if (workspaces.some((workspace) => path.matchesGlob(relative, workspace))) {
|
|
26
27
|
log(`Found parent @graphcommerce package at: ${currentDir}`);
|
|
27
28
|
return currentDir;
|
|
28
29
|
}
|
|
30
|
+
log(`${relative} is not a workspace of ${packageJson.name}`);
|
|
29
31
|
}
|
|
30
32
|
currentDir = path.dirname(currentDir);
|
|
31
33
|
}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@graphcommerce/next-config",
|
|
3
3
|
"homepage": "https://www.graphcommerce.org/",
|
|
4
4
|
"repository": "github:graphcommerce-org/graphcommerce",
|
|
5
|
-
"version": "11.0.0-canary.
|
|
5
|
+
"version": "11.0.0-canary.50",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": {
|
|
@@ -15,6 +15,8 @@
|
|
|
15
15
|
},
|
|
16
16
|
"./config": {
|
|
17
17
|
"types": "./src/generated/configValues/index.ts",
|
|
18
|
+
"edge-light": "./dist/generated/configValues/index.js",
|
|
19
|
+
"browser": "./dist/generated/configValues/publicOnly/index.js",
|
|
18
20
|
"default": "./dist/generated/configValues/index.js"
|
|
19
21
|
},
|
|
20
22
|
"./loadConfig": {
|
|
@@ -63,7 +65,7 @@
|
|
|
63
65
|
},
|
|
64
66
|
"peerDependencies": {
|
|
65
67
|
"@apollo/client": "*",
|
|
66
|
-
"@graphcommerce/prettier-config-pwa": "^11.0.0-canary.
|
|
68
|
+
"@graphcommerce/prettier-config-pwa": "^11.0.0-canary.50",
|
|
67
69
|
"@lingui/loader": "*",
|
|
68
70
|
"@lingui/macro": "*",
|
|
69
71
|
"@lingui/react": "*",
|
|
@@ -9,6 +9,12 @@ import { resolveDependenciesSync } from '../utils/resolveDependenciesSync'
|
|
|
9
9
|
import { resolveDependency } from '../utils/resolveDependency'
|
|
10
10
|
|
|
11
11
|
const packages = [...resolveDependenciesSync().values()].filter((p) => p !== '.')
|
|
12
|
+
|
|
13
|
+
// Use specific patterns instead of ** to avoid expensive directory traversal
|
|
14
|
+
export const configSchemaLocations = [
|
|
15
|
+
'graphql/Config.graphqls',
|
|
16
|
+
...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`]),
|
|
17
|
+
]
|
|
12
18
|
const resolve = resolveDependency()
|
|
13
19
|
|
|
14
20
|
dotenv.config({ quiet: true })
|
|
@@ -20,15 +26,9 @@ export async function generateConfig() {
|
|
|
20
26
|
const targetTs = `${resolved.root}/src/generated/config.ts`
|
|
21
27
|
const targetJs = `${resolved.root}/dist/generated/config.js`
|
|
22
28
|
|
|
23
|
-
// Use specific patterns instead of ** to avoid expensive directory traversal
|
|
24
|
-
const schemaLocations = [
|
|
25
|
-
'graphql/Config.graphqls',
|
|
26
|
-
...packages.flatMap((p) => [`${p}/Config.graphqls`, `${p}/graphql/Config.graphqls`]),
|
|
27
|
-
]
|
|
28
|
-
|
|
29
29
|
await generate({
|
|
30
30
|
silent: true,
|
|
31
|
-
schema:
|
|
31
|
+
schema: configSchemaLocations,
|
|
32
32
|
generates: {
|
|
33
33
|
[targetTs]: {
|
|
34
34
|
plugins: ['typescript', 'typescript-validation-schema'],
|
|
@@ -55,13 +55,21 @@ export async function generateConfig() {
|
|
|
55
55
|
|
|
56
56
|
writeFileSync(
|
|
57
57
|
targetTs,
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
(
|
|
58
|
+
// typescript-validation-schema writes `.default(x).nullish()`: `.nullish()` returns undefined
|
|
59
|
+
// before `.default()` runs.
|
|
60
|
+
await prettier.format(
|
|
61
|
+
readFileSync(targetTs, 'utf-8').replace(
|
|
62
|
+
/\.default\(([^()]+)\)\.nullish\(\)/g,
|
|
63
|
+
'.nullish().default($1)',
|
|
63
64
|
),
|
|
64
|
-
|
|
65
|
+
{
|
|
66
|
+
...prettierConf,
|
|
67
|
+
parser: 'typescript',
|
|
68
|
+
plugins: prettierConf.plugins?.filter(
|
|
69
|
+
(p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
|
|
70
|
+
),
|
|
71
|
+
},
|
|
72
|
+
),
|
|
65
73
|
)
|
|
66
74
|
|
|
67
75
|
const result = transformFileSync(targetTs, {
|
|
@@ -1,264 +1,198 @@
|
|
|
1
|
-
/* eslint-disable
|
|
2
|
-
import { existsSync, mkdirSync, rmSync, writeFileSync } from 'fs'
|
|
1
|
+
/* eslint-disable no-console */
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'fs'
|
|
3
3
|
import path from 'path'
|
|
4
4
|
import prettierConf from '@graphcommerce/prettier-config-pwa'
|
|
5
5
|
import { transformFileSync } from '@swc/core'
|
|
6
6
|
import dotenv from 'dotenv'
|
|
7
|
+
import type { InputValueDefinitionNode, TypeNode } from 'graphql'
|
|
8
|
+
import { Kind, parse } from 'graphql'
|
|
7
9
|
import prettier from 'prettier'
|
|
8
10
|
import { loadConfig } from '../config/loadConfig'
|
|
9
|
-
import type { GraphCommerceConfig } from '../generated/config'
|
|
10
|
-
import { GraphCommerceConfigSchema } from '../generated/config'
|
|
11
11
|
import { resolveDependency } from '../utils/resolveDependency'
|
|
12
|
+
import { configSchemaLocations } from './generateConfig'
|
|
12
13
|
|
|
13
14
|
dotenv.config({ quiet: true })
|
|
14
15
|
|
|
15
16
|
const resolve = resolveDependency()
|
|
16
17
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
return key
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
/** Generates a TypeScript value literal for the given value */
|
|
23
|
-
function generateValueLiteral(value: unknown): string {
|
|
24
|
-
if (value === null) return 'null'
|
|
25
|
-
if (value === undefined) return 'undefined'
|
|
26
|
-
if (typeof value === 'string') return JSON.stringify(value)
|
|
27
|
-
if (typeof value === 'boolean' || typeof value === 'number') return String(value)
|
|
28
|
-
if (Array.isArray(value) || (typeof value === 'object' && value !== null)) {
|
|
29
|
-
return JSON.stringify(value, null, 2)
|
|
30
|
-
}
|
|
31
|
-
return JSON.stringify(value)
|
|
32
|
-
}
|
|
18
|
+
const header = `// Auto-generated by 'yarn graphcommerce codegen-config-values'`
|
|
19
|
+
const typeImports = `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
|
|
33
20
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
/** Gets the schema keys for a specific config section */
|
|
40
|
-
function getSectionSchemaKeys(configKey: keyof GraphCommerceConfig): string[] {
|
|
41
|
-
try {
|
|
42
|
-
const mainSchema = GraphCommerceConfigSchema()
|
|
43
|
-
const sectionSchema = mainSchema.shape[configKey]
|
|
21
|
+
const literal = (value: unknown) =>
|
|
22
|
+
value === undefined ? 'undefined' : JSON.stringify(value, null, 2)
|
|
44
23
|
|
|
45
|
-
|
|
24
|
+
const namedType = (type: TypeNode): string =>
|
|
25
|
+
type.kind === Kind.NAMED_TYPE ? type.name.value : namedType(type.type)
|
|
46
26
|
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
let unwrappedSchema: any = sectionSchema
|
|
27
|
+
const isPublic = (field: InputValueDefinitionNode) =>
|
|
28
|
+
Boolean(field.directives?.some((directive) => directive.name.value === 'public'))
|
|
50
29
|
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
while (true) {
|
|
54
|
-
if (!unwrappedSchema || typeof unwrappedSchema !== 'object') break
|
|
55
|
-
if (!('_def' in unwrappedSchema)) break
|
|
30
|
+
const isSection = (value: unknown): value is Record<string, unknown> =>
|
|
31
|
+
typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
56
32
|
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
33
|
+
/**
|
|
34
|
+
* Writes `src/generated/configValues` and `dist/generated/configValues` with all values, for the
|
|
35
|
+
* server. Writes `dist/generated/configValues/publicOnly` with only the `@public` values, for the
|
|
36
|
+
* `browser` export condition, with a file per section for tree-shaking. A server-only field of an
|
|
37
|
+
* object in a list, such as `storefront[]`, is a getter that throws in development.
|
|
38
|
+
*/
|
|
39
|
+
export async function generateConfigValues() {
|
|
40
|
+
const resolved = resolve('@graphcommerce/next-config')
|
|
41
|
+
if (!resolved) throw Error('Could not resolve @graphcommerce/next-config')
|
|
66
42
|
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
43
|
+
const config = loadConfig(process.cwd()) as Record<string, unknown>
|
|
44
|
+
const srcDir = `${resolved.root}/src/generated/configValues`
|
|
45
|
+
const distDir = `${resolved.root}/dist/generated/configValues`
|
|
46
|
+
const publicOnlyDir = `${distDir}/publicOnly`
|
|
47
|
+
|
|
48
|
+
rmSync(srcDir, { recursive: true, force: true })
|
|
49
|
+
rmSync(distDir, { recursive: true, force: true })
|
|
50
|
+
mkdirSync(srcDir, { recursive: true })
|
|
51
|
+
mkdirSync(publicOnlyDir, { recursive: true })
|
|
52
|
+
|
|
53
|
+
const inputs = new Map<string, InputValueDefinitionNode[]>()
|
|
54
|
+
for (const location of configSchemaLocations.filter((l) => existsSync(l))) {
|
|
55
|
+
for (const def of parse(readFileSync(location, 'utf-8')).definitions) {
|
|
56
|
+
if (
|
|
57
|
+
def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION &&
|
|
58
|
+
def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION
|
|
59
|
+
)
|
|
70
60
|
continue
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
// Handle ZodObject - this is what we want
|
|
74
|
-
if (typeName === 'ZodObject' && def.shape) {
|
|
75
|
-
const shape =
|
|
76
|
-
typeof def.shape === 'function'
|
|
77
|
-
? (def.shape as () => Record<string, unknown>)()
|
|
78
|
-
: (def.shape as Record<string, unknown>)
|
|
79
|
-
return Object.keys(shape || {})
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
break
|
|
61
|
+
const typeName = def.name.value
|
|
62
|
+
inputs.set(typeName, [...(inputs.get(typeName) ?? []), ...(def.fields ?? [])])
|
|
83
63
|
}
|
|
64
|
+
}
|
|
84
65
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return Object.keys(shape || {})
|
|
66
|
+
for (const [typeName, fields] of inputs) {
|
|
67
|
+
const misplaced = fields.find((f) => isPublic(f) && inputs.has(namedType(f.type)))
|
|
68
|
+
if (misplaced) {
|
|
69
|
+
throw Error(
|
|
70
|
+
`@public on ${typeName}.${misplaced.name.value}: add @public to the fields of ${namedType(misplaced.type)}.`,
|
|
71
|
+
)
|
|
92
72
|
}
|
|
93
|
-
} catch {
|
|
94
|
-
// Silently fail and return empty array
|
|
95
73
|
}
|
|
96
74
|
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
75
|
+
const hasPublic = (typeName: string): boolean =>
|
|
76
|
+
(inputs.get(typeName) ?? []).some((f) =>
|
|
77
|
+
inputs.has(namedType(f.type)) ? hasPublic(namedType(f.type)) : isPublic(f),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
const browserLiteral = (value: unknown, typeName: string, valuePath: string): string => {
|
|
81
|
+
if (Array.isArray(value))
|
|
82
|
+
return `[${value.map((item) => browserLiteral(item, typeName, `${valuePath}[]`)).join(',\n')}]`
|
|
83
|
+
if (!isSection(value)) return literal(value)
|
|
84
|
+
|
|
85
|
+
const properties: string[] = []
|
|
86
|
+
const getters: string[] = []
|
|
87
|
+
for (const field of inputs.get(typeName) ?? []) {
|
|
88
|
+
const name = field.name.value
|
|
89
|
+
const fieldType = namedType(field.type)
|
|
90
|
+
const isInput = inputs.has(fieldType)
|
|
91
|
+
if (!(isInput ? hasPublic(fieldType) : isPublic(field))) {
|
|
92
|
+
const hint = isInput ? `the fields of ${fieldType}` : `${typeName}.${name}`
|
|
93
|
+
getters.push(`${name}: serverOnly('${valuePath}.${name}', '${hint}')`)
|
|
94
|
+
} else if (value[name] !== undefined) {
|
|
95
|
+
const fieldValue = isInput
|
|
96
|
+
? browserLiteral(value[name], fieldType, `${valuePath}.${name}`)
|
|
97
|
+
: literal(value[name])
|
|
98
|
+
properties.push(`${JSON.stringify(name)}: ${fieldValue}`)
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const object = `{\n${properties.join(',\n')}\n}`
|
|
102
|
+
return getters.length
|
|
103
|
+
? `Object.defineProperties(${object}, {\n${getters.join(',\n')}\n})`
|
|
104
|
+
: object
|
|
120
105
|
}
|
|
121
106
|
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
107
|
+
const writeServerModule = async (name: string, content: string) => {
|
|
108
|
+
const srcFile = path.join(srcDir, `${name}.ts`)
|
|
109
|
+
writeFileSync(
|
|
110
|
+
srcFile,
|
|
111
|
+
await prettier.format(content, {
|
|
112
|
+
...prettierConf,
|
|
113
|
+
parser: 'typescript',
|
|
114
|
+
plugins: prettierConf.plugins?.filter(
|
|
115
|
+
(p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
|
|
116
|
+
),
|
|
117
|
+
}),
|
|
118
|
+
)
|
|
119
|
+
const { code } = transformFileSync(srcFile, {
|
|
120
|
+
module: { type: 'nodenext' },
|
|
121
|
+
env: { targets: { node: '20' } },
|
|
132
122
|
})
|
|
133
|
-
.join(
|
|
134
|
-
|
|
135
|
-
// Always need the Get import since we always use type annotations
|
|
136
|
-
const needsGetImport = true
|
|
137
|
-
|
|
138
|
-
const imports = needsGetImport
|
|
139
|
-
? `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
|
|
140
|
-
: `import type { GraphCommerceConfig } from '../config'`
|
|
141
|
-
|
|
142
|
-
const content = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
|
|
143
|
-
${imports}
|
|
144
|
-
|
|
145
|
-
${exports}
|
|
146
|
-
`
|
|
147
|
-
|
|
148
|
-
const formattedContent = await prettier.format(content, {
|
|
149
|
-
...prettierConf,
|
|
150
|
-
parser: 'typescript',
|
|
151
|
-
plugins: prettierConf.plugins?.filter(
|
|
152
|
-
(p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
|
|
153
|
-
),
|
|
154
|
-
})
|
|
155
|
-
|
|
156
|
-
// Write TypeScript file
|
|
157
|
-
writeFileSync(filePath, formattedContent)
|
|
158
|
-
|
|
159
|
-
// Transform and write JavaScript file
|
|
160
|
-
const result = transformFileSync(filePath, {
|
|
161
|
-
module: { type: 'nodenext' },
|
|
162
|
-
env: { targets: { node: '18' } },
|
|
163
|
-
})
|
|
164
|
-
|
|
165
|
-
writeFileSync(distFilePath, result.code)
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
export async function generateConfigValues() {
|
|
169
|
-
const resolved = resolve('@graphcommerce/next-config')
|
|
170
|
-
if (!resolved) throw Error('Could not resolve @graphcommerce/next-config')
|
|
171
|
-
|
|
172
|
-
const config = loadConfig(process.cwd())
|
|
173
|
-
const targetDir = `${resolved.root}/src/generated/configValues`
|
|
174
|
-
const targetDistDir = `${resolved.root}/dist/generated/configValues`
|
|
175
|
-
|
|
176
|
-
// Clean up existing directories and recreate them
|
|
177
|
-
if (existsSync(targetDir)) {
|
|
178
|
-
rmSync(targetDir, { recursive: true, force: true })
|
|
123
|
+
writeFileSync(path.join(distDir, `${name}.js`), code)
|
|
179
124
|
}
|
|
180
|
-
if (existsSync(targetDistDir)) {
|
|
181
|
-
rmSync(targetDistDir, { recursive: true, force: true })
|
|
182
|
-
}
|
|
183
|
-
mkdirSync(targetDir, { recursive: true })
|
|
184
|
-
mkdirSync(targetDistDir, { recursive: true })
|
|
185
|
-
|
|
186
|
-
// Get all schema keys to ensure we include everything, even undefined values
|
|
187
|
-
const schema = GraphCommerceConfigSchema()
|
|
188
|
-
const schemaKeys = Object.keys(schema.shape) as (keyof GraphCommerceConfig)[]
|
|
189
125
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
126
|
+
const writePublicOnlyModule = (name: string, serverOnlyNames: string[], exports: string[]) => {
|
|
127
|
+
const lines = [
|
|
128
|
+
header,
|
|
129
|
+
'// Browser build of @graphcommerce/next-config/config: only fields with @public in Config.graphqls.',
|
|
130
|
+
'// Add @public to a field to read it in the browser. Keep secrets server-only.',
|
|
131
|
+
...(serverOnlyNames.length ? [`// Server-only: ${serverOnlyNames.join(', ')}`] : []),
|
|
132
|
+
]
|
|
133
|
+
if (exports.some((e) => e.includes('serverOnly('))) {
|
|
134
|
+
lines.push(`const serverOnly = (valuePath, hint) => ({
|
|
135
|
+
get() {
|
|
136
|
+
if (process.env.NODE_ENV !== 'production')
|
|
137
|
+
throw Error(\`\${valuePath} is server-only. Read it on the server or add @public to \${hint} in Config.graphqls.\`)
|
|
138
|
+
},
|
|
139
|
+
})`)
|
|
140
|
+
}
|
|
141
|
+
writeFileSync(path.join(publicOnlyDir, `${name}.js`), [...lines, ...exports].join('\n'))
|
|
194
142
|
}
|
|
195
143
|
|
|
196
|
-
const
|
|
197
|
-
const
|
|
198
|
-
const
|
|
144
|
+
const serverExports: string[] = []
|
|
145
|
+
const browserExports: string[] = []
|
|
146
|
+
const serverOnlyKeys: string[] = []
|
|
147
|
+
let sectionCount = 0
|
|
148
|
+
|
|
149
|
+
for (const field of inputs.get('GraphCommerceConfig') ?? []) {
|
|
150
|
+
const key = field.name.value
|
|
151
|
+
const value = config[key]
|
|
152
|
+
const fieldType = namedType(field.type)
|
|
153
|
+
const sectionFields = inputs.get(fieldType) ?? []
|
|
154
|
+
|
|
155
|
+
if (isSection(value)) {
|
|
156
|
+
sectionCount++
|
|
157
|
+
const sectionExports = sectionFields.map(
|
|
158
|
+
({ name }) =>
|
|
159
|
+
`export const ${name.value}: Get<GraphCommerceConfig, '${key}.${name.value}'> = ${literal(value[name.value])}`,
|
|
160
|
+
)
|
|
161
|
+
await writeServerModule(key, [header, typeImports, ...sectionExports].join('\n\n'))
|
|
162
|
+
serverExports.push(`export * as ${key} from './${key}.js'`)
|
|
163
|
+
} else {
|
|
164
|
+
serverExports.push(
|
|
165
|
+
`export const ${key}: Get<GraphCommerceConfig, '${key}'> = ${literal(value)}`,
|
|
166
|
+
)
|
|
167
|
+
}
|
|
199
168
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
169
|
+
if (!(inputs.has(fieldType) ? hasPublic(fieldType) : isPublic(field))) {
|
|
170
|
+
serverOnlyKeys.push(key)
|
|
171
|
+
} else if (isSection(value)) {
|
|
172
|
+
const sectionServerOnly: string[] = []
|
|
173
|
+
const sectionPublic: string[] = []
|
|
174
|
+
for (const sectionField of sectionFields) {
|
|
175
|
+
const name = sectionField.name.value
|
|
176
|
+
const nestedType = namedType(sectionField.type)
|
|
177
|
+
if (!(inputs.has(nestedType) ? hasPublic(nestedType) : isPublic(sectionField)))
|
|
178
|
+
sectionServerOnly.push(name)
|
|
179
|
+
else
|
|
180
|
+
sectionPublic.push(
|
|
181
|
+
`export const ${name} = ${browserLiteral(value[name], nestedType, `${key}.${name}`)}`,
|
|
182
|
+
)
|
|
183
|
+
}
|
|
184
|
+
writePublicOnlyModule(key, sectionServerOnly, sectionPublic)
|
|
185
|
+
browserExports.push(`export * as ${key} from './${key}.js'`)
|
|
206
186
|
} else {
|
|
207
|
-
|
|
208
|
-
const valueStr = generateValueLiteral(value)
|
|
209
|
-
// Always include type annotation
|
|
210
|
-
const typeAnnotation = `: Get<GraphCommerceConfig, '${key}'>`
|
|
211
|
-
rootExports.push(`export const ${key}${typeAnnotation} = ${valueStr}`)
|
|
187
|
+
browserExports.push(`export const ${key} = ${browserLiteral(value, fieldType, key)}`)
|
|
212
188
|
}
|
|
213
189
|
}
|
|
214
190
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
nestedObjects.map(([sectionName, sectionValue, configKey]) =>
|
|
218
|
-
createConfigSectionFile(sectionName, sectionValue, targetDir, targetDistDir, configKey),
|
|
219
|
-
),
|
|
220
|
-
)
|
|
221
|
-
|
|
222
|
-
// Always need the Get import since we always use type annotations
|
|
223
|
-
const rootNeedsGetImport = true
|
|
224
|
-
|
|
225
|
-
const rootImports = rootNeedsGetImport
|
|
226
|
-
? `import type { GraphCommerceConfig } from '../config'\nimport type { Get } from 'type-fest'`
|
|
227
|
-
: `import type { GraphCommerceConfig } from '../config'`
|
|
228
|
-
|
|
229
|
-
// Create the main index file
|
|
230
|
-
const indexContent = `// Auto-generated by 'yarn graphcommerce codegen-config-values'
|
|
231
|
-
${rootImports}
|
|
191
|
+
await writeServerModule('index', [header, typeImports, ...serverExports].join('\n'))
|
|
192
|
+
writePublicOnlyModule('index', serverOnlyKeys, browserExports)
|
|
232
193
|
|
|
233
|
-
${
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
...prettierConf,
|
|
238
|
-
parser: 'typescript',
|
|
239
|
-
plugins: prettierConf.plugins?.filter(
|
|
240
|
-
(p) => typeof p === 'string' && !p.includes('prettier-plugin-sort-imports'),
|
|
241
|
-
),
|
|
242
|
-
})
|
|
243
|
-
|
|
244
|
-
const indexPath = path.join(targetDir, 'index.ts')
|
|
245
|
-
const distIndexPath = path.join(targetDistDir, 'index.js')
|
|
246
|
-
|
|
247
|
-
// Write TypeScript index file
|
|
248
|
-
writeFileSync(indexPath, formattedIndexContent)
|
|
249
|
-
|
|
250
|
-
// Transform and write JavaScript index file
|
|
251
|
-
const indexResult = transformFileSync(indexPath, {
|
|
252
|
-
module: { type: 'nodenext' },
|
|
253
|
-
env: { targets: { node: '20' } },
|
|
254
|
-
})
|
|
255
|
-
|
|
256
|
-
writeFileSync(distIndexPath, indexResult.code)
|
|
257
|
-
|
|
258
|
-
// eslint-disable-next-line no-console
|
|
259
|
-
console.log(`✅ Generated config values in ${targetDir} and ${targetDistDir}`)
|
|
260
|
-
// eslint-disable-next-line no-console
|
|
261
|
-
console.log(`📁 Created ${nestedObjects.length} nested object files + index.ts/.js`)
|
|
262
|
-
// eslint-disable-next-line no-console
|
|
263
|
-
console.log(`📝 Root exports: ${configEntries.length - nestedObjects.length}`)
|
|
194
|
+
console.log(`✅ Generated config values in ${srcDir} and ${distDir}`)
|
|
195
|
+
console.log(
|
|
196
|
+
`📁 ${sectionCount} sections, ${serverExports.length} server exports, ${browserExports.length} browser exports`,
|
|
197
|
+
)
|
|
264
198
|
}
|
package/src/generated/config.ts
CHANGED
|
@@ -87,6 +87,20 @@ export type DatalayerConfig = {
|
|
|
87
87
|
* endpoint: '{graphCommerce.magentoEndpoint}'
|
|
88
88
|
* ```
|
|
89
89
|
*
|
|
90
|
+
* ## Public and server-only configuration
|
|
91
|
+
*
|
|
92
|
+
* A field with `@public` is available in the browser. A field without `@public` is server-only:
|
|
93
|
+
* code that runs in the browser cannot read it.
|
|
94
|
+
*
|
|
95
|
+
* - Turbopack stops the build when browser code imports a server-only field from
|
|
96
|
+
* `@graphcommerce/next-config/config`.
|
|
97
|
+
* - A server-only field of a storefront, such as `useStorefrontConfig().myServerField`, throws in
|
|
98
|
+
* development and returns `undefined` in production.
|
|
99
|
+
* - A server-only field of a section, such as `algolia.searchOnlyApiKey`, is `undefined`.
|
|
100
|
+
*
|
|
101
|
+
* Put `@public` on fields with a scalar or enum type. In the browser, a field with an input type,
|
|
102
|
+
* such as `debug: GraphCommerceDebugConfig`, contains only the `@public` fields of that input.
|
|
103
|
+
*
|
|
90
104
|
* ## Environment variables to override configuration
|
|
91
105
|
*
|
|
92
106
|
* Configuration values can be overwriten by environment variables, with the following rules:
|
|
@@ -113,10 +127,11 @@ export type DatalayerConfig = {
|
|
|
113
127
|
*
|
|
114
128
|
* ```graphql
|
|
115
129
|
* extend input GraphCommerceConfig {
|
|
116
|
-
* myConfig: String # or Boolean, or Int, or Float, make required with `!`
|
|
130
|
+
* myConfig: String @public # or Boolean, or Int, or Float, make required with `!`
|
|
131
|
+
* myApiSecret: String
|
|
117
132
|
* }
|
|
118
133
|
* extend input GraphCommerceStorefrontConfig {
|
|
119
|
-
* myField: Boolean
|
|
134
|
+
* myField: Boolean @public
|
|
120
135
|
* }
|
|
121
136
|
* ```
|
|
122
137
|
*
|
|
@@ -585,17 +600,17 @@ export function DatalayerConfigSchema(): z.ZodObject<Properties<DatalayerConfig>
|
|
|
585
600
|
|
|
586
601
|
export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerceConfig>> {
|
|
587
602
|
return z.object({
|
|
588
|
-
breadcrumbs: z.boolean().
|
|
603
|
+
breadcrumbs: z.boolean().nullish().default(false),
|
|
589
604
|
canonicalBaseUrl: z.string().min(1),
|
|
590
605
|
cartDisplayPricesInclTax: z.boolean().nullish(),
|
|
591
606
|
compare: z.boolean().nullish(),
|
|
592
|
-
compareVariant: CompareVariantSchema.default('ICON')
|
|
593
|
-
configurableVariantForSimple: z.boolean().
|
|
607
|
+
compareVariant: CompareVariantSchema.nullish().default('ICON'),
|
|
608
|
+
configurableVariantForSimple: z.boolean().nullish().default(false),
|
|
594
609
|
configurableVariantValues: z.lazy(() => MagentoConfigurableVariantValuesSchema().nullish()),
|
|
595
|
-
containerSizingContent: ContainerSizingSchema.default('FULL_WIDTH')
|
|
596
|
-
containerSizingShell: ContainerSizingSchema.default('FULL_WIDTH')
|
|
597
|
-
crossSellsHideCartItems: z.boolean().
|
|
598
|
-
crossSellsRedirectItems: z.boolean().
|
|
610
|
+
containerSizingContent: ContainerSizingSchema.nullish().default('FULL_WIDTH'),
|
|
611
|
+
containerSizingShell: ContainerSizingSchema.nullish().default('FULL_WIDTH'),
|
|
612
|
+
crossSellsHideCartItems: z.boolean().nullish().default(false),
|
|
613
|
+
crossSellsRedirectItems: z.boolean().nullish().default(false),
|
|
599
614
|
customerAddressNoteEnable: z.boolean().nullish(),
|
|
600
615
|
customerCompanyFieldsEnable: z.boolean().nullish(),
|
|
601
616
|
customerDeleteEnabled: z.boolean().nullish(),
|
|
@@ -607,7 +622,7 @@ export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerc
|
|
|
607
622
|
googlePlaystore: z.lazy(() => GraphCommerceGooglePlaystoreConfigSchema().nullish()),
|
|
608
623
|
googleRecaptchaKey: z.string().nullish(),
|
|
609
624
|
googleTagmanagerId: z.string().nullish(),
|
|
610
|
-
graphqlMeshEditMode: z.boolean().
|
|
625
|
+
graphqlMeshEditMode: z.boolean().nullish().default(false),
|
|
611
626
|
hygraphManagementApi: z.string().nullish(),
|
|
612
627
|
hygraphProjectId: z.string().nullish(),
|
|
613
628
|
hygraphWriteAccessToken: z.string().nullish(),
|
|
@@ -616,9 +631,9 @@ export function GraphCommerceConfigSchema(): z.ZodObject<Properties<GraphCommerc
|
|
|
616
631
|
magentoVersion: z.number(),
|
|
617
632
|
permissions: z.lazy(() => GraphCommercePermissionsSchema().nullish()),
|
|
618
633
|
previewSecret: z.string().nullish(),
|
|
619
|
-
productFiltersLayout: ProductFiltersLayoutSchema.default('DEFAULT')
|
|
634
|
+
productFiltersLayout: ProductFiltersLayoutSchema.nullish().default('DEFAULT'),
|
|
620
635
|
productFiltersPro: z.boolean().nullish(),
|
|
621
|
-
productListPaginationVariant: PaginationVariantSchema.default('COMPACT')
|
|
636
|
+
productListPaginationVariant: PaginationVariantSchema.nullish().default('COMPACT'),
|
|
622
637
|
productRoute: z.string().nullish(),
|
|
623
638
|
recentlyViewedProducts: z.lazy(() => RecentlyViewedProductsConfigSchema().nullish()),
|
|
624
639
|
robotsAllow: z.boolean().nullish(),
|
|
@@ -5,7 +5,9 @@ const debug = process.env.DEBUG === '1'
|
|
|
5
5
|
// eslint-disable-next-line no-console
|
|
6
6
|
const log = (message: string) => debug && console.log(`isMonorepo: ${message}`)
|
|
7
7
|
|
|
8
|
-
|
|
8
|
+
type PackageJson = { name?: string; workspaces?: string[] | { packages?: string[] } }
|
|
9
|
+
|
|
10
|
+
function findPackageJson(directory: string): PackageJson | null {
|
|
9
11
|
try {
|
|
10
12
|
const packageJsonPath = path.join(directory, 'package.json')
|
|
11
13
|
const content = fs.readFileSync(packageJsonPath, 'utf8')
|
|
@@ -16,8 +18,8 @@ function findPackageJson(directory: string): { name: string } | null {
|
|
|
16
18
|
}
|
|
17
19
|
|
|
18
20
|
/**
|
|
19
|
-
* Finds the path of the parent @graphcommerce package
|
|
20
|
-
* package is found
|
|
21
|
+
* Finds the path of the parent @graphcommerce package that has `directory` as a workspace. Returns
|
|
22
|
+
* null if no parent package is found
|
|
21
23
|
*/
|
|
22
24
|
export function findParentPath(directory: string): string | null {
|
|
23
25
|
let currentDir = directory
|
|
@@ -31,14 +33,18 @@ export function findParentPath(directory: string): string | null {
|
|
|
31
33
|
while (currentDir !== path.parse(currentDir).root) {
|
|
32
34
|
const packageJson = findPackageJson(currentDir)
|
|
33
35
|
|
|
34
|
-
if (packageJson) {
|
|
35
|
-
log(`Found package.
|
|
36
|
-
|
|
36
|
+
if (packageJson?.name?.startsWith('@graphcommerce/')) {
|
|
37
|
+
log(`Found package ${packageJson.name} in: ${currentDir}`)
|
|
38
|
+
const workspaces = Array.isArray(packageJson.workspaces)
|
|
39
|
+
? packageJson.workspaces
|
|
40
|
+
: (packageJson.workspaces?.packages ?? [])
|
|
41
|
+
const relative = path.relative(currentDir, directory)
|
|
37
42
|
|
|
38
|
-
if (
|
|
43
|
+
if (workspaces.some((workspace) => path.matchesGlob(relative, workspace))) {
|
|
39
44
|
log(`Found parent @graphcommerce package at: ${currentDir}`)
|
|
40
45
|
return currentDir
|
|
41
46
|
}
|
|
47
|
+
log(`${relative} is not a workspace of ${packageJson.name}`)
|
|
42
48
|
}
|
|
43
49
|
|
|
44
50
|
currentDir = path.dirname(currentDir)
|