@nuasite/cms-core 0.64.2 → 0.65.0
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/dist/asset-paths.d.ts.map +1 -0
- package/dist/asset-paths.js +55 -0
- package/dist/astro-source-analysis.d.ts.map +1 -0
- package/dist/astro-source-analysis.js +503 -0
- package/dist/byte-range.d.ts.map +1 -0
- package/dist/byte-range.js +31 -0
- package/dist/{types/check-entries.d.ts → check-entries.d.ts} +3 -3
- package/dist/check-entries.d.ts.map +1 -0
- package/dist/check-entries.js +98 -0
- package/dist/{types/check-live.d.ts → check-live.d.ts} +4 -4
- package/dist/check-live.d.ts.map +1 -0
- package/dist/check-live.js +49 -0
- package/dist/{types/check-shape.d.ts → check-shape.d.ts} +4 -4
- package/dist/check-shape.d.ts.map +1 -0
- package/dist/check-shape.js +119 -0
- package/dist/{types/check-write.d.ts → check-write.d.ts} +4 -4
- package/dist/check-write.d.ts.map +1 -0
- package/dist/check-write.js +273 -0
- package/dist/{types/check.d.ts → check.d.ts} +2 -2
- package/dist/check.d.ts.map +1 -0
- package/dist/check.js +366 -0
- package/dist/{types/collection-scanner.d.ts → collection-scanner.d.ts} +2 -2
- package/dist/collection-scanner.d.ts.map +1 -0
- package/dist/collection-scanner.js +1483 -0
- package/dist/{types/component-registry.d.ts → component-registry.d.ts} +1 -1
- package/dist/component-registry.d.ts.map +1 -0
- package/dist/component-registry.js +271 -0
- package/dist/{types/content-config-ast.d.ts → content-config-ast.d.ts} +1 -1
- package/dist/content-config-ast.d.ts.map +1 -0
- package/dist/content-config-ast.js +1614 -0
- package/dist/{types/core.d.ts → core.d.ts} +3 -3
- package/dist/core.d.ts.map +1 -0
- package/dist/core.js +94 -0
- package/dist/editor-write-model.d.ts.map +1 -0
- package/dist/editor-write-model.js +101 -0
- package/dist/fs/glob.d.ts.map +1 -0
- package/dist/fs/glob.js +79 -0
- package/dist/{types/fs → fs}/node-fs.d.ts +1 -1
- package/dist/fs/node-fs.d.ts.map +1 -0
- package/dist/fs/node-fs.js +199 -0
- package/dist/{types/fs → fs}/staged.d.ts +1 -1
- package/dist/fs/staged.d.ts.map +1 -0
- package/dist/fs/staged.js +203 -0
- package/dist/fs/types.d.ts.map +1 -0
- package/dist/fs/types.js +0 -0
- package/dist/{types/handlers → handlers}/entry-ops.d.ts +2 -2
- package/dist/handlers/entry-ops.d.ts.map +1 -0
- package/dist/handlers/entry-ops.js +846 -0
- package/dist/{types/handlers → handlers}/page-ops.d.ts +1 -1
- package/dist/handlers/page-ops.d.ts.map +1 -0
- package/dist/handlers/page-ops.js +165 -0
- package/dist/{types/handlers → handlers}/redirect-ops.d.ts +1 -1
- package/dist/handlers/redirect-ops.d.ts.map +1 -0
- package/dist/handlers/redirect-ops.js +111 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/media/contember.d.ts.map +1 -0
- package/dist/media/contember.js +79 -0
- package/dist/media/errors.d.ts.map +1 -0
- package/dist/media/errors.js +22 -0
- package/dist/{types/media → media}/file-system.d.ts +1 -1
- package/dist/media/file-system.d.ts.map +1 -0
- package/dist/media/file-system.js +124 -0
- package/dist/{types/media → media}/index.d.ts +8 -8
- package/dist/media/index.d.ts.map +1 -0
- package/dist/media/index.js +8 -0
- package/dist/media/local.d.ts.map +1 -0
- package/dist/media/local.js +209 -0
- package/dist/media/mime.d.ts.map +1 -0
- package/dist/media/mime.js +21 -0
- package/dist/media/names.d.ts.map +1 -0
- package/dist/media/names.js +23 -0
- package/dist/{types/media → media}/project-images.d.ts +1 -1
- package/dist/media/project-images.d.ts.map +1 -0
- package/dist/media/project-images.js +99 -0
- package/dist/media/s3.d.ts.map +1 -0
- package/dist/media/s3.js +160 -0
- package/dist/media/type-filter.d.ts.map +1 -0
- package/dist/media/type-filter.js +164 -0
- package/dist/{types/portable.d.ts → portable.d.ts} +25 -25
- package/dist/portable.d.ts.map +1 -0
- package/dist/portable.js +27 -0
- package/dist/{types/project-config-ast.d.ts → project-config-ast.d.ts} +1 -1
- package/dist/project-config-ast.d.ts.map +1 -0
- package/dist/project-config-ast.js +324 -0
- package/dist/public-static-file.d.ts.map +1 -0
- package/dist/public-static-file.js +40 -0
- package/dist/redirects.d.ts.map +1 -0
- package/dist/redirects.js +185 -0
- package/dist/route-scan.d.ts.map +1 -0
- package/dist/route-scan.js +23 -0
- package/dist/schema-port.d.ts.map +1 -0
- package/dist/schema-port.js +30 -0
- package/dist/{types/schema-probe.d.ts → schema-probe.d.ts} +2 -2
- package/dist/schema-probe.d.ts.map +1 -0
- package/dist/schema-probe.js +119 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +163 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +12 -12
- package/src/check-entries.ts +4 -4
- package/src/check-live.ts +4 -4
- package/src/check-shape.ts +5 -5
- package/src/check-write.ts +6 -6
- package/src/check.ts +15 -9
- package/src/collection-scanner.ts +3 -3
- package/src/component-registry.ts +1 -1
- package/src/content-config-ast.ts +1 -1
- package/src/core.ts +8 -8
- package/src/editor-write-model.ts +1 -1
- package/src/fs/node-fs.ts +2 -2
- package/src/fs/staged.ts +6 -3
- package/src/handlers/entry-ops.ts +7 -7
- package/src/handlers/page-ops.ts +2 -2
- package/src/handlers/redirect-ops.ts +2 -2
- package/src/index.ts +4 -4
- package/src/media/contember.ts +1 -1
- package/src/media/file-system.ts +4 -4
- package/src/media/index.ts +8 -8
- package/src/media/local.ts +3 -3
- package/src/media/project-images.ts +2 -2
- package/src/media/s3.ts +3 -3
- package/src/portable.ts +25 -25
- package/src/project-config-ast.ts +1 -1
- package/src/route-scan.ts +1 -1
- package/src/schema-probe.ts +2 -2
- package/src/tsconfig.json +5 -1
- package/dist/types/asset-paths.d.ts.map +0 -1
- package/dist/types/astro-source-analysis.d.ts.map +0 -1
- package/dist/types/byte-range.d.ts.map +0 -1
- package/dist/types/check-entries.d.ts.map +0 -1
- package/dist/types/check-live.d.ts.map +0 -1
- package/dist/types/check-shape.d.ts.map +0 -1
- package/dist/types/check-write.d.ts.map +0 -1
- package/dist/types/check.d.ts.map +0 -1
- package/dist/types/collection-scanner.d.ts.map +0 -1
- package/dist/types/component-registry.d.ts.map +0 -1
- package/dist/types/content-config-ast.d.ts.map +0 -1
- package/dist/types/core.d.ts.map +0 -1
- package/dist/types/editor-write-model.d.ts.map +0 -1
- package/dist/types/fs/glob.d.ts.map +0 -1
- package/dist/types/fs/node-fs.d.ts.map +0 -1
- package/dist/types/fs/staged.d.ts.map +0 -1
- package/dist/types/fs/types.d.ts.map +0 -1
- package/dist/types/handlers/entry-ops.d.ts.map +0 -1
- package/dist/types/handlers/page-ops.d.ts.map +0 -1
- package/dist/types/handlers/redirect-ops.d.ts.map +0 -1
- package/dist/types/index.d.ts +0 -5
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/media/contember.d.ts.map +0 -1
- package/dist/types/media/errors.d.ts.map +0 -1
- package/dist/types/media/file-system.d.ts.map +0 -1
- package/dist/types/media/index.d.ts.map +0 -1
- package/dist/types/media/local.d.ts.map +0 -1
- package/dist/types/media/mime.d.ts.map +0 -1
- package/dist/types/media/names.d.ts.map +0 -1
- package/dist/types/media/project-images.d.ts.map +0 -1
- package/dist/types/media/s3.d.ts.map +0 -1
- package/dist/types/media/type-filter.d.ts.map +0 -1
- package/dist/types/portable.d.ts.map +0 -1
- package/dist/types/project-config-ast.d.ts.map +0 -1
- package/dist/types/public-static-file.d.ts.map +0 -1
- package/dist/types/redirects.d.ts.map +0 -1
- package/dist/types/route-scan.d.ts.map +0 -1
- package/dist/types/schema-port.d.ts.map +0 -1
- package/dist/types/schema-probe.d.ts.map +0 -1
- package/dist/types/shared.d.ts.map +0 -1
- package/dist/types/tsconfig.tsbuildinfo +0 -1
- /package/dist/{types/asset-paths.d.ts → asset-paths.d.ts} +0 -0
- /package/dist/{types/astro-source-analysis.d.ts → astro-source-analysis.d.ts} +0 -0
- /package/dist/{types/byte-range.d.ts → byte-range.d.ts} +0 -0
- /package/dist/{types/editor-write-model.d.ts → editor-write-model.d.ts} +0 -0
- /package/dist/{types/fs → fs}/glob.d.ts +0 -0
- /package/dist/{types/fs → fs}/types.d.ts +0 -0
- /package/dist/{types/media → media}/contember.d.ts +0 -0
- /package/dist/{types/media → media}/errors.d.ts +0 -0
- /package/dist/{types/media → media}/local.d.ts +0 -0
- /package/dist/{types/media → media}/mime.d.ts +0 -0
- /package/dist/{types/media → media}/names.d.ts +0 -0
- /package/dist/{types/media → media}/s3.d.ts +0 -0
- /package/dist/{types/media → media}/type-filter.d.ts +0 -0
- /package/dist/{types/public-static-file.d.ts → public-static-file.d.ts} +0 -0
- /package/dist/{types/redirects.d.ts → redirects.d.ts} +0 -0
- /package/dist/{types/route-scan.d.ts → route-scan.d.ts} +0 -0
- /package/dist/{types/schema-port.d.ts → schema-port.d.ts} +0 -0
- /package/dist/{types/shared.d.ts → shared.d.ts} +0 -0
|
@@ -0,0 +1,1614 @@
|
|
|
1
|
+
import { parse as parseBabel } from '@babel/parser';
|
|
2
|
+
import { isDerivedTransform, isFieldType, } from '@nuasite/cms-types';
|
|
3
|
+
const FIELD_HELPER_TYPES = new Set([
|
|
4
|
+
'text',
|
|
5
|
+
'number',
|
|
6
|
+
'image',
|
|
7
|
+
'file',
|
|
8
|
+
'video',
|
|
9
|
+
'url',
|
|
10
|
+
'email',
|
|
11
|
+
'tel',
|
|
12
|
+
'color',
|
|
13
|
+
'date',
|
|
14
|
+
'datetime',
|
|
15
|
+
'time',
|
|
16
|
+
'year',
|
|
17
|
+
'month',
|
|
18
|
+
'textarea',
|
|
19
|
+
'markdown',
|
|
20
|
+
]);
|
|
21
|
+
const VALID_HINT_KEYS = new Set([
|
|
22
|
+
'min',
|
|
23
|
+
'max',
|
|
24
|
+
'step',
|
|
25
|
+
'placeholder',
|
|
26
|
+
'maxLength',
|
|
27
|
+
'minLength',
|
|
28
|
+
'rows',
|
|
29
|
+
'accept',
|
|
30
|
+
]);
|
|
31
|
+
const WRAPPER_METHODS = new Set(['optional', 'nullable', 'nullish', 'default']);
|
|
32
|
+
/**
|
|
33
|
+
* Follow `Identifier` references through same-file `const` bindings until reaching
|
|
34
|
+
* a non-Identifier node, seeing through type-only wrappers (`as const`, `satisfies`,
|
|
35
|
+
* `!`) on the way — they change nothing about the value a schema declares. Cycle-safe
|
|
36
|
+
* via the visited set. Returns the node it stopped on — the peeled original when the
|
|
37
|
+
* identifier is unbound or already visited.
|
|
38
|
+
*/
|
|
39
|
+
function resolveExpression(node, bindings, visited = new Set()) {
|
|
40
|
+
let current = node;
|
|
41
|
+
for (;;) {
|
|
42
|
+
if (current.type === 'TSAsExpression'
|
|
43
|
+
|| current.type === 'TSSatisfiesExpression'
|
|
44
|
+
|| current.type === 'TSNonNullExpression'
|
|
45
|
+
|| current.type === 'TSTypeAssertion') {
|
|
46
|
+
current = current.expression;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (current.type !== 'Identifier')
|
|
50
|
+
return current;
|
|
51
|
+
if (visited.has(current.name))
|
|
52
|
+
return current;
|
|
53
|
+
visited.add(current.name);
|
|
54
|
+
const next = bindings.get(current.name);
|
|
55
|
+
if (!next)
|
|
56
|
+
return current;
|
|
57
|
+
current = next;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
function isAstNode(value) {
|
|
61
|
+
return typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string';
|
|
62
|
+
}
|
|
63
|
+
/** Visit `node` and everything beneath it, finding children by shape — no @babel/traverse dependency. */
|
|
64
|
+
function walkNodes(node, visit) {
|
|
65
|
+
visit(node);
|
|
66
|
+
const children = Object.values(node);
|
|
67
|
+
for (const child of children) {
|
|
68
|
+
if (Array.isArray(child)) {
|
|
69
|
+
for (const item of child) {
|
|
70
|
+
if (isAstNode(item))
|
|
71
|
+
walkNodes(item, visit);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
else if (isAstNode(child)) {
|
|
75
|
+
walkNodes(child, visit);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/** Record every name a binding construct introduces, destructuring patterns included. */
|
|
80
|
+
function declaredPatternNames(node, record) {
|
|
81
|
+
switch (node.type) {
|
|
82
|
+
case 'Identifier':
|
|
83
|
+
record(node.name);
|
|
84
|
+
return;
|
|
85
|
+
case 'ObjectPattern':
|
|
86
|
+
for (const prop of node.properties)
|
|
87
|
+
declaredPatternNames(prop.type === 'RestElement' ? prop.argument : prop.value, record);
|
|
88
|
+
return;
|
|
89
|
+
case 'ArrayPattern':
|
|
90
|
+
for (const el of node.elements) {
|
|
91
|
+
if (el)
|
|
92
|
+
declaredPatternNames(el, record);
|
|
93
|
+
}
|
|
94
|
+
return;
|
|
95
|
+
case 'AssignmentPattern':
|
|
96
|
+
declaredPatternNames(node.left, record);
|
|
97
|
+
return;
|
|
98
|
+
case 'RestElement':
|
|
99
|
+
declaredPatternNames(node.argument, record);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Names the file declares more than once, anywhere.
|
|
105
|
+
*
|
|
106
|
+
* `bindings` is module-scope only, so a same-named local — a `const` inside the schema
|
|
107
|
+
* callback, a parameter — is invisible to it and an identifier would resolve to the
|
|
108
|
+
* module-level declaration instead: the wrong option list, the wrong type, the wrong
|
|
109
|
+
* `required` flag. Modelling scopes properly is a bigger job than this parser wants, so
|
|
110
|
+
* a name declared twice is simply not resolved and the field degrades as it did before.
|
|
111
|
+
*/
|
|
112
|
+
function shadowedNames(ast) {
|
|
113
|
+
const seen = new Set();
|
|
114
|
+
const shadowed = new Set();
|
|
115
|
+
const record = (name) => {
|
|
116
|
+
if (seen.has(name))
|
|
117
|
+
shadowed.add(name);
|
|
118
|
+
seen.add(name);
|
|
119
|
+
};
|
|
120
|
+
walkNodes(ast, node => {
|
|
121
|
+
switch (node.type) {
|
|
122
|
+
case 'VariableDeclarator':
|
|
123
|
+
declaredPatternNames(node.id, record);
|
|
124
|
+
return;
|
|
125
|
+
case 'FunctionDeclaration':
|
|
126
|
+
case 'FunctionExpression':
|
|
127
|
+
case 'ArrowFunctionExpression':
|
|
128
|
+
for (const param of node.params)
|
|
129
|
+
declaredPatternNames(param, record);
|
|
130
|
+
if (node.type !== 'ArrowFunctionExpression' && node.id)
|
|
131
|
+
record(node.id.name);
|
|
132
|
+
return;
|
|
133
|
+
case 'ClassDeclaration':
|
|
134
|
+
if (node.id)
|
|
135
|
+
record(node.id.name);
|
|
136
|
+
return;
|
|
137
|
+
case 'ImportSpecifier':
|
|
138
|
+
case 'ImportDefaultSpecifier':
|
|
139
|
+
case 'ImportNamespaceSpecifier':
|
|
140
|
+
record(node.local.name);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
return shadowed;
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Parse a TypeScript/JS source string into a Babel `File`. Babel-only — no Astro
|
|
148
|
+
* coupling. Returns null when parsing throws fatally.
|
|
149
|
+
*/
|
|
150
|
+
function parseSource(source) {
|
|
151
|
+
try {
|
|
152
|
+
return parseBabel(source, {
|
|
153
|
+
sourceType: 'module',
|
|
154
|
+
plugins: ['typescript'],
|
|
155
|
+
errorRecovery: true,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/** Where a project may keep its content config, in the order the parser prefers them. */
|
|
163
|
+
export const CONTENT_CONFIG_PATHS = ['src/content/config.ts', 'src/content.config.ts'];
|
|
164
|
+
/**
|
|
165
|
+
* Where Astro also takes a content config from and this reader does not look. A project with
|
|
166
|
+
* one of these has a config; it is only out of the reader's sight.
|
|
167
|
+
*/
|
|
168
|
+
export const UNREAD_CONTENT_CONFIG_PATHS = [
|
|
169
|
+
'src/content.config.mjs',
|
|
170
|
+
'src/content.config.js',
|
|
171
|
+
'src/content.config.mts',
|
|
172
|
+
'src/content/config.mjs',
|
|
173
|
+
'src/content/config.js',
|
|
174
|
+
'src/content/config.mts',
|
|
175
|
+
];
|
|
176
|
+
/**
|
|
177
|
+
* Tell the three apart, for a caller that has to report the empty map rather than just handle it.
|
|
178
|
+
*
|
|
179
|
+
* A parse failure anywhere wins over an empty parse: a config that will not read is a problem to
|
|
180
|
+
* name even when a second one beside it reads cleanly and declares nothing.
|
|
181
|
+
*/
|
|
182
|
+
export async function classifyEmptyContentConfig(fs) {
|
|
183
|
+
let found = false;
|
|
184
|
+
for (const configPath of CONTENT_CONFIG_PATHS) {
|
|
185
|
+
try {
|
|
186
|
+
await fs.stat(configPath);
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
found = true;
|
|
192
|
+
if (parseSource(await fs.readFile(configPath)) === null) {
|
|
193
|
+
return 'unparseable';
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return found ? 'no-collections' : 'missing';
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* Parse the project's Astro content config file (TypeScript) into a structured
|
|
200
|
+
* representation of each collection's schema. Returns an empty map if no config
|
|
201
|
+
* file exists or parsing fails. The mtime-keyed cache (via `fs.stat()`) skips
|
|
202
|
+
* re-reading and re-parsing an unchanged config file.
|
|
203
|
+
*/
|
|
204
|
+
export async function parseContentConfig(fs, cache) {
|
|
205
|
+
return (await readContentConfig(fs, cache)).parsed;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* {@link parseContentConfig}, plus every collection name the config declares — including the
|
|
209
|
+
* ones the parsed map leaves out because neither a schema nor a glob pattern could be read.
|
|
210
|
+
* Same file choice and the same cache.
|
|
211
|
+
*/
|
|
212
|
+
export async function readContentConfig(fs, cache) {
|
|
213
|
+
// A config whose parsed map came back empty may still declare names, all of them unreadable
|
|
214
|
+
// declarations, or export a `collections` the reader cannot see into. The first such read
|
|
215
|
+
// is the answer when no config parses to anything.
|
|
216
|
+
let unparsed;
|
|
217
|
+
for (const configPath of CONTENT_CONFIG_PATHS) {
|
|
218
|
+
let stat;
|
|
219
|
+
try {
|
|
220
|
+
stat = await fs.stat(configPath);
|
|
221
|
+
}
|
|
222
|
+
catch {
|
|
223
|
+
continue;
|
|
224
|
+
}
|
|
225
|
+
let cached = cache.get(configPath);
|
|
226
|
+
if (!cached || cached.mtimeMs !== stat.mtimeMs) {
|
|
227
|
+
const content = await fs.readFile(configPath);
|
|
228
|
+
cached = { mtimeMs: stat.mtimeMs, ...readConfigSource(content) };
|
|
229
|
+
cache.set(configPath, cached);
|
|
230
|
+
}
|
|
231
|
+
if (cached.parsed.size > 0)
|
|
232
|
+
return cached;
|
|
233
|
+
if (!unparsed && (cached.declared.length > 0 || cached.exportsCollections))
|
|
234
|
+
unparsed = cached;
|
|
235
|
+
}
|
|
236
|
+
return unparsed ?? { parsed: new Map(), declared: [], partial: false, exportsCollections: false };
|
|
237
|
+
}
|
|
238
|
+
/** Exported for unit testing — operates on a source string directly. */
|
|
239
|
+
export function parseConfigSource(source, _sourcePath) {
|
|
240
|
+
return readConfigSource(source).parsed;
|
|
241
|
+
}
|
|
242
|
+
function readConfigSource(source) {
|
|
243
|
+
const result = new Map();
|
|
244
|
+
const ast = parseSource(source);
|
|
245
|
+
if (!ast)
|
|
246
|
+
return { parsed: result, declared: [], partial: false, exportsCollections: false };
|
|
247
|
+
// Single pass: collect every top-level `const X = <expr>` binding (so we can
|
|
248
|
+
// later resolve Identifier references like `cs: TestimonialTranslation`),
|
|
249
|
+
// while also picking out `defineCollection({...})` calls and the
|
|
250
|
+
// `export const collections = { name: X, ... }` mapping.
|
|
251
|
+
const bindings = new Map();
|
|
252
|
+
const collectionDecls = new Map();
|
|
253
|
+
const exportMap = new Map(); // varName → collectionName
|
|
254
|
+
const inlineCollections = new Map(); // collectionName → defineCollection arg (inline form)
|
|
255
|
+
for (const stmt of ast.program.body) {
|
|
256
|
+
const varDecl = stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration'
|
|
257
|
+
? stmt.declaration
|
|
258
|
+
: stmt.type === 'VariableDeclaration'
|
|
259
|
+
? stmt
|
|
260
|
+
: null;
|
|
261
|
+
if (!varDecl)
|
|
262
|
+
continue;
|
|
263
|
+
for (const decl of varDecl.declarations) {
|
|
264
|
+
if (decl.id.type !== 'Identifier')
|
|
265
|
+
continue;
|
|
266
|
+
if (!decl.init)
|
|
267
|
+
continue;
|
|
268
|
+
bindings.set(decl.id.name, decl.init);
|
|
269
|
+
if (decl.id.name === 'collections' && decl.init.type === 'ObjectExpression') {
|
|
270
|
+
for (const prop of decl.init.properties) {
|
|
271
|
+
if (prop.type !== 'ObjectProperty')
|
|
272
|
+
continue;
|
|
273
|
+
const key = propertyKeyName(prop.key);
|
|
274
|
+
if (!key)
|
|
275
|
+
continue;
|
|
276
|
+
if (prop.value.type === 'Identifier') {
|
|
277
|
+
exportMap.set(prop.value.name, key);
|
|
278
|
+
}
|
|
279
|
+
else if (prop.value.type === 'CallExpression' && isDefineCollectionCallee(prop.value.callee)) {
|
|
280
|
+
// Inline form: `collections = { name: defineCollection({...}) }`
|
|
281
|
+
const inlineArg = prop.value.arguments[0];
|
|
282
|
+
if (inlineArg?.type === 'ObjectExpression') {
|
|
283
|
+
inlineCollections.set(key, inlineArg);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (decl.init.type === 'CallExpression' && isDefineCollectionCallee(decl.init.callee)) {
|
|
290
|
+
const arg = decl.init.arguments[0];
|
|
291
|
+
if (arg?.type === 'ObjectExpression') {
|
|
292
|
+
collectionDecls.set(decl.id.name, arg);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
// A name the file declares twice cannot be resolved to one binding without a scope
|
|
298
|
+
// model, so drop it and let the fields that mention it stay untyped.
|
|
299
|
+
for (const name of shadowedNames(ast))
|
|
300
|
+
bindings.delete(name);
|
|
301
|
+
// Unify both styles: inline `name: defineCollection({...})` and the
|
|
302
|
+
// `const x = defineCollection({...}); collections = { name: x }` reference form.
|
|
303
|
+
const collectionObjects = new Map(inlineCollections);
|
|
304
|
+
for (const [varName, collectionName] of exportMap) {
|
|
305
|
+
const decl = collectionDecls.get(varName);
|
|
306
|
+
if (decl)
|
|
307
|
+
collectionObjects.set(collectionName, decl);
|
|
308
|
+
}
|
|
309
|
+
for (const [collectionName, decl] of collectionObjects) {
|
|
310
|
+
const loaderProperty = decl.properties.find(p => p.type === 'ObjectProperty'
|
|
311
|
+
&& propertyKeyName(p.key) === 'loader');
|
|
312
|
+
const loaderOptions = loaderProperty?.type === 'ObjectProperty' ? extractGlobLoaderOptions(loaderProperty.value, bindings) : {};
|
|
313
|
+
const loaderPattern = loaderOptions.pattern;
|
|
314
|
+
const loaderBase = loaderOptions.base;
|
|
315
|
+
const cmsProperty = decl.properties.find(p => p.type === 'ObjectProperty'
|
|
316
|
+
&& propertyKeyName(p.key) === 'cms');
|
|
317
|
+
const layout = cmsProperty?.type === 'ObjectProperty' ? parseCmsLayout(cmsProperty.value, bindings) : undefined;
|
|
318
|
+
const declaredPathname = cmsProperty?.type === 'ObjectProperty' ? parseCmsPathname(cmsProperty.value, bindings) : undefined;
|
|
319
|
+
const titleField = cmsProperty?.type === 'ObjectProperty' ? parseCmsTitleField(cmsProperty.value, bindings) : undefined;
|
|
320
|
+
const fragment = cmsProperty?.type === 'ObjectProperty' ? parseCmsFragment(cmsProperty.value, bindings) : undefined;
|
|
321
|
+
const previewOf = cmsProperty?.type === 'ObjectProperty' ? parseCmsPreviewOf(cmsProperty.value, bindings) : undefined;
|
|
322
|
+
const nav = cmsProperty?.type === 'ObjectProperty' ? parseCmsNav(cmsProperty.value, bindings) : undefined;
|
|
323
|
+
// `fragment` (no page of its own) and `pathname` (compose the entry's page URL)
|
|
324
|
+
// contradict each other. Report it rather than silently preferring one — over this
|
|
325
|
+
// channel because `cms-core` can't reach the ErrorCollector in `@nuasite/cms` and must
|
|
326
|
+
// not grow a dependency on it; `warnOnPathnameCollisions` in collection-scanner.ts warns
|
|
327
|
+
// the same way. `fragment` wins, and the warning says so.
|
|
328
|
+
if (fragment && declaredPathname) {
|
|
329
|
+
console.warn(`[cms] collection "${collectionName}": \`cms.fragment\` and \`cms.pathname\` are mutually exclusive — a fragment collection has no page of its own, so the \`pathname\` rule is ignored`);
|
|
330
|
+
}
|
|
331
|
+
const pathname = fragment ? undefined : declaredPathname;
|
|
332
|
+
const schemaProperty = decl.properties.find(p => p.type === 'ObjectProperty'
|
|
333
|
+
&& propertyKeyName(p.key) === 'schema');
|
|
334
|
+
if (!schemaProperty || schemaProperty.type !== 'ObjectProperty') {
|
|
335
|
+
if (!loaderPattern)
|
|
336
|
+
continue;
|
|
337
|
+
result.set(collectionName, {
|
|
338
|
+
name: collectionName,
|
|
339
|
+
fields: [],
|
|
340
|
+
loaderPattern,
|
|
341
|
+
loaderBase,
|
|
342
|
+
layout,
|
|
343
|
+
pathname,
|
|
344
|
+
titleField,
|
|
345
|
+
fragment,
|
|
346
|
+
previewOf,
|
|
347
|
+
...nav,
|
|
348
|
+
});
|
|
349
|
+
continue;
|
|
350
|
+
}
|
|
351
|
+
const schemaObject = unwrapSchemaToObject(schemaProperty.value, bindings);
|
|
352
|
+
if (!schemaObject) {
|
|
353
|
+
if (!loaderPattern)
|
|
354
|
+
continue;
|
|
355
|
+
result.set(collectionName, {
|
|
356
|
+
name: collectionName,
|
|
357
|
+
fields: [],
|
|
358
|
+
loaderPattern,
|
|
359
|
+
loaderBase,
|
|
360
|
+
layout,
|
|
361
|
+
pathname,
|
|
362
|
+
titleField,
|
|
363
|
+
fragment,
|
|
364
|
+
previewOf,
|
|
365
|
+
...nav,
|
|
366
|
+
});
|
|
367
|
+
continue;
|
|
368
|
+
}
|
|
369
|
+
const fields = parseSchemaFields(schemaObject, bindings);
|
|
370
|
+
// Once per parse of the config file, not once per entry: the parse result is cached by
|
|
371
|
+
// mtime, so a bad declaration is reported when it is read, not on every scan that
|
|
372
|
+
// consults it.
|
|
373
|
+
checkDerivedFromDeclarations(collectionName, fields);
|
|
374
|
+
result.set(collectionName, {
|
|
375
|
+
name: collectionName,
|
|
376
|
+
fields,
|
|
377
|
+
...(hasSkippedMembers(schemaObject) ? { partialFields: true } : {}),
|
|
378
|
+
loaderPattern,
|
|
379
|
+
loaderBase,
|
|
380
|
+
layout,
|
|
381
|
+
pathname,
|
|
382
|
+
titleField,
|
|
383
|
+
fragment,
|
|
384
|
+
previewOf,
|
|
385
|
+
...nav,
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
return { parsed: result, ...declaredOrUnknown(ast) };
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* {@link readDeclaredCollections}, which runs on every parse, also for the callers that never
|
|
392
|
+
* ask for a scan report. A config form it trips over must not cost them the parse, so a throw
|
|
393
|
+
* reads as a config whose declarations could not be seen: nothing named, and possibly more.
|
|
394
|
+
*/
|
|
395
|
+
function declaredOrUnknown(ast) {
|
|
396
|
+
try {
|
|
397
|
+
return readDeclaredCollections(ast);
|
|
398
|
+
}
|
|
399
|
+
catch (error) {
|
|
400
|
+
console.warn('[cms] Could not read the collections the content config declares:', error);
|
|
401
|
+
return { declared: [], partial: true, exportsCollections: true };
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Parse a `cms: { display, sidebar, sections }` layout block (the
|
|
406
|
+
* `defineCmsCollection` form) from its ObjectExpression. Unknown/malformed keys
|
|
407
|
+
* are skipped; returns undefined when nothing usable is found.
|
|
408
|
+
*/
|
|
409
|
+
function parseCmsLayout(node, bindings) {
|
|
410
|
+
const resolved = resolveExpression(node, bindings);
|
|
411
|
+
if (resolved.type !== 'ObjectExpression')
|
|
412
|
+
return undefined;
|
|
413
|
+
const layout = {};
|
|
414
|
+
for (const prop of resolved.properties) {
|
|
415
|
+
if (prop.type !== 'ObjectProperty')
|
|
416
|
+
continue;
|
|
417
|
+
const key = propertyKeyName(prop.key);
|
|
418
|
+
const value = resolveExpression(prop.value, bindings);
|
|
419
|
+
if (key === 'display') {
|
|
420
|
+
if (value.type === 'StringLiteral' && (value.value === 'tabs' || value.value === 'sections'))
|
|
421
|
+
layout.display = value.value;
|
|
422
|
+
}
|
|
423
|
+
else if (key === 'sidebar') {
|
|
424
|
+
if (value.type === 'ArrayExpression')
|
|
425
|
+
layout.sidebar = stringArray(value);
|
|
426
|
+
}
|
|
427
|
+
else if (key === 'sections') {
|
|
428
|
+
if (value.type === 'ArrayExpression') {
|
|
429
|
+
const sections = value.elements
|
|
430
|
+
.map(el => (el && el.type !== 'SpreadElement' ? parseLayoutSection(resolveExpression(el, bindings)) : null))
|
|
431
|
+
.filter((s) => s !== null);
|
|
432
|
+
if (sections.length > 0)
|
|
433
|
+
layout.sections = sections;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
return Object.keys(layout).length > 0 ? layout : undefined;
|
|
438
|
+
}
|
|
439
|
+
/** Parse one `{ title, fields, collapsed }` section object. Requires a title + ≥1 field. */
|
|
440
|
+
function parseLayoutSection(node) {
|
|
441
|
+
if (node.type !== 'ObjectExpression')
|
|
442
|
+
return null;
|
|
443
|
+
let title;
|
|
444
|
+
let fields = [];
|
|
445
|
+
let collapsed = false;
|
|
446
|
+
for (const prop of node.properties) {
|
|
447
|
+
if (prop.type !== 'ObjectProperty')
|
|
448
|
+
continue;
|
|
449
|
+
const key = propertyKeyName(prop.key);
|
|
450
|
+
if (key === 'title' && prop.value.type === 'StringLiteral')
|
|
451
|
+
title = prop.value.value;
|
|
452
|
+
else if (key === 'fields' && prop.value.type === 'ArrayExpression')
|
|
453
|
+
fields = stringArray(prop.value);
|
|
454
|
+
else if (key === 'collapsed' && prop.value.type === 'BooleanLiteral')
|
|
455
|
+
collapsed = prop.value.value;
|
|
456
|
+
}
|
|
457
|
+
if (title === undefined || fields.length === 0)
|
|
458
|
+
return null;
|
|
459
|
+
return collapsed ? { title, fields, collapsed } : { title, fields };
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* The complete option list of an `enum([…])` array, or null when any member is unreadable.
|
|
463
|
+
*
|
|
464
|
+
* All-or-nothing on purpose: these options become a *closed* set downstream, so reading
|
|
465
|
+
* `[...BASE, 'blog']` as just `['blog']` would lock the field to the one member we
|
|
466
|
+
* understood — every existing entry invalid, and the editor refusing to write the values
|
|
467
|
+
* the schema does allow. A list we cannot read whole leaves the field open instead.
|
|
468
|
+
*/
|
|
469
|
+
function readEnumOptions(node) {
|
|
470
|
+
const options = [];
|
|
471
|
+
for (const el of node.elements) {
|
|
472
|
+
if (el?.type !== 'StringLiteral')
|
|
473
|
+
return null;
|
|
474
|
+
options.push(el.value);
|
|
475
|
+
}
|
|
476
|
+
return options.length > 0 ? options : null;
|
|
477
|
+
}
|
|
478
|
+
/** Collect string-literal elements from an array expression. */
|
|
479
|
+
function stringArray(node) {
|
|
480
|
+
const out = [];
|
|
481
|
+
for (const el of node.elements) {
|
|
482
|
+
if (el?.type === 'StringLiteral')
|
|
483
|
+
out.push(el.value);
|
|
484
|
+
}
|
|
485
|
+
return out;
|
|
486
|
+
}
|
|
487
|
+
function isDefineCollectionCallee(callee) {
|
|
488
|
+
// `defineCmsCollection` (the @nuasite/cms wrapper carrying a `cms` layout block)
|
|
489
|
+
// is treated identically — at runtime it strips `cms` and returns the Astro config.
|
|
490
|
+
return callee.type === 'Identifier' && (callee.name === 'defineCollection' || callee.name === 'defineCmsCollection');
|
|
491
|
+
}
|
|
492
|
+
/**
|
|
493
|
+
* Parse a `cms: { pathname: [...] }` block into a serializable {@link PathnameSpec}.
|
|
494
|
+
* Robust by design: unknown/malformed entries are skipped and never throw; returns
|
|
495
|
+
* undefined when no usable segment is found.
|
|
496
|
+
*/
|
|
497
|
+
function parseCmsPathname(node, bindings) {
|
|
498
|
+
const resolved = resolveExpression(node, bindings);
|
|
499
|
+
if (resolved.type !== 'ObjectExpression')
|
|
500
|
+
return undefined;
|
|
501
|
+
const pathnameProp = resolved.properties.find(p => p.type === 'ObjectProperty' && propertyKeyName(p.key) === 'pathname');
|
|
502
|
+
if (!pathnameProp || pathnameProp.type !== 'ObjectProperty')
|
|
503
|
+
return undefined;
|
|
504
|
+
const arr = resolveExpression(pathnameProp.value, bindings);
|
|
505
|
+
if (arr.type !== 'ArrayExpression')
|
|
506
|
+
return undefined;
|
|
507
|
+
const spec = [];
|
|
508
|
+
for (const el of arr.elements) {
|
|
509
|
+
if (!el || el.type === 'SpreadElement')
|
|
510
|
+
continue;
|
|
511
|
+
const segment = parsePathnameSegment(resolveExpression(el, bindings));
|
|
512
|
+
if (segment)
|
|
513
|
+
spec.push(segment);
|
|
514
|
+
}
|
|
515
|
+
return spec.length > 0 ? spec : undefined;
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Parse a `cms: { titleField: 'heading' }` block into the field name an entry's
|
|
519
|
+
* browse title is read from. Same shape-tolerant contract as {@link parseCmsPathname}:
|
|
520
|
+
* a non-string or empty value yields undefined, which leaves the fallback chain in place.
|
|
521
|
+
*/
|
|
522
|
+
function parseCmsTitleField(node, bindings) {
|
|
523
|
+
const resolved = resolveExpression(node, bindings);
|
|
524
|
+
if (resolved.type !== 'ObjectExpression')
|
|
525
|
+
return undefined;
|
|
526
|
+
const titleFieldProp = resolved.properties.find(p => p.type === 'ObjectProperty' && propertyKeyName(p.key) === 'titleField');
|
|
527
|
+
if (!titleFieldProp || titleFieldProp.type !== 'ObjectProperty')
|
|
528
|
+
return undefined;
|
|
529
|
+
const value = resolveExpression(titleFieldProp.value, bindings);
|
|
530
|
+
if (value.type !== 'StringLiteral' || value.value === '')
|
|
531
|
+
return undefined;
|
|
532
|
+
return value.value;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Parse a `cms: { fragment: true }` block — the collection declaring it owns no page.
|
|
536
|
+
* Only the literal `true` counts; anything else (including `fragment: false`) leaves the
|
|
537
|
+
* collection routed as usual.
|
|
538
|
+
*/
|
|
539
|
+
function parseCmsFragment(node, bindings) {
|
|
540
|
+
const resolved = resolveExpression(node, bindings);
|
|
541
|
+
if (resolved.type !== 'ObjectExpression')
|
|
542
|
+
return undefined;
|
|
543
|
+
const fragmentProp = resolved.properties.find(p => p.type === 'ObjectProperty' && propertyKeyName(p.key) === 'fragment');
|
|
544
|
+
if (!fragmentProp || fragmentProp.type !== 'ObjectProperty')
|
|
545
|
+
return undefined;
|
|
546
|
+
const value = resolveExpression(fragmentProp.value, bindings);
|
|
547
|
+
return value.type === 'BooleanLiteral' && value.value ? true : undefined;
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Parse a `cms: { previewOf: '/aktualne' }` block into the page a fragment collection is
|
|
551
|
+
* previewed on. Same shape-tolerant contract as {@link parseCmsTitleField}; a non-string
|
|
552
|
+
* or empty value yields undefined, leaving the entries without a preview target.
|
|
553
|
+
*/
|
|
554
|
+
function parseCmsPreviewOf(node, bindings) {
|
|
555
|
+
const resolved = resolveExpression(node, bindings);
|
|
556
|
+
if (resolved.type !== 'ObjectExpression')
|
|
557
|
+
return undefined;
|
|
558
|
+
const previewOfProp = resolved.properties.find(p => p.type === 'ObjectProperty' && propertyKeyName(p.key) === 'previewOf');
|
|
559
|
+
if (!previewOfProp || previewOfProp.type !== 'ObjectProperty')
|
|
560
|
+
return undefined;
|
|
561
|
+
const value = resolveExpression(previewOfProp.value, bindings);
|
|
562
|
+
if (value.type !== 'StringLiteral' || value.value === '')
|
|
563
|
+
return undefined;
|
|
564
|
+
return value.value;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Parse the collection-browser keys of a `cms: { label, hidden, order, group }` block: how
|
|
568
|
+
* the collection is named, placed and sectioned where collections are listed. Same
|
|
569
|
+
* shape-tolerant contract as {@link parseCmsTitleField}: a key whose value is not the
|
|
570
|
+
* expected literal (or is an empty string) is skipped, leaving the default in place. `label`
|
|
571
|
+
* and `group` also take a template literal without substitutions. As with `fragment`, only
|
|
572
|
+
* the literal `true` hides a collection.
|
|
573
|
+
*/
|
|
574
|
+
function parseCmsNav(node, bindings) {
|
|
575
|
+
const resolved = resolveExpression(node, bindings);
|
|
576
|
+
if (resolved.type !== 'ObjectExpression')
|
|
577
|
+
return undefined;
|
|
578
|
+
const nav = {};
|
|
579
|
+
for (const prop of resolved.properties) {
|
|
580
|
+
if (prop.type !== 'ObjectProperty')
|
|
581
|
+
continue;
|
|
582
|
+
const key = propertyKeyName(prop.key);
|
|
583
|
+
const value = resolveExpression(prop.value, bindings);
|
|
584
|
+
if (key === 'label' || key === 'group') {
|
|
585
|
+
// A plain string or a template literal without substitutions: both are static text.
|
|
586
|
+
const text = extractStaticString(value, bindings);
|
|
587
|
+
if (text)
|
|
588
|
+
nav[key] = text;
|
|
589
|
+
}
|
|
590
|
+
else if (key === 'hidden') {
|
|
591
|
+
if (value.type === 'BooleanLiteral' && value.value)
|
|
592
|
+
nav.hidden = true;
|
|
593
|
+
}
|
|
594
|
+
else if (key === 'order') {
|
|
595
|
+
if (value.type === 'NumericLiteral') {
|
|
596
|
+
nav.order = value.value;
|
|
597
|
+
}
|
|
598
|
+
else if (value.type === 'UnaryExpression' && value.operator === '-' && value.argument.type === 'NumericLiteral') {
|
|
599
|
+
nav.order = -value.argument.value;
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
return nav;
|
|
604
|
+
}
|
|
605
|
+
/** Parse one `{ field, map? }` or `{ literal }` segment object. */
|
|
606
|
+
function parsePathnameSegment(node) {
|
|
607
|
+
if (node.type !== 'ObjectExpression')
|
|
608
|
+
return null;
|
|
609
|
+
let field;
|
|
610
|
+
let literal;
|
|
611
|
+
let map;
|
|
612
|
+
for (const prop of node.properties) {
|
|
613
|
+
if (prop.type !== 'ObjectProperty')
|
|
614
|
+
continue;
|
|
615
|
+
const key = propertyKeyName(prop.key);
|
|
616
|
+
if (key === 'field' && prop.value.type === 'StringLiteral')
|
|
617
|
+
field = prop.value.value;
|
|
618
|
+
else if (key === 'literal' && prop.value.type === 'StringLiteral')
|
|
619
|
+
literal = prop.value.value;
|
|
620
|
+
else if (key === 'map' && prop.value.type === 'ObjectExpression')
|
|
621
|
+
map = parseStringRecord(prop.value);
|
|
622
|
+
}
|
|
623
|
+
if (literal !== undefined)
|
|
624
|
+
return { literal };
|
|
625
|
+
if (field !== undefined)
|
|
626
|
+
return map ? { field, map } : { field };
|
|
627
|
+
return null;
|
|
628
|
+
}
|
|
629
|
+
/** Collect string→string pairs from an object expression (non-string values skipped). */
|
|
630
|
+
function parseStringRecord(node) {
|
|
631
|
+
const out = {};
|
|
632
|
+
for (const prop of node.properties) {
|
|
633
|
+
if (prop.type !== 'ObjectProperty')
|
|
634
|
+
continue;
|
|
635
|
+
const key = propertyKeyName(prop.key);
|
|
636
|
+
if (key === null)
|
|
637
|
+
continue;
|
|
638
|
+
if (prop.value.type === 'StringLiteral')
|
|
639
|
+
out[key] = prop.value.value;
|
|
640
|
+
}
|
|
641
|
+
return Object.keys(out).length > 0 ? out : undefined;
|
|
642
|
+
}
|
|
643
|
+
function propertyKeyName(key) {
|
|
644
|
+
if (key.type === 'Identifier')
|
|
645
|
+
return key.name;
|
|
646
|
+
if (key.type === 'StringLiteral')
|
|
647
|
+
return key.value;
|
|
648
|
+
return null;
|
|
649
|
+
}
|
|
650
|
+
function extractGlobLoaderOptions(node, bindings) {
|
|
651
|
+
const resolved = resolveExpression(node, bindings);
|
|
652
|
+
if (resolved.type !== 'CallExpression')
|
|
653
|
+
return {};
|
|
654
|
+
if (!isGlobCallee(resolved.callee))
|
|
655
|
+
return {};
|
|
656
|
+
const arg = resolved.arguments[0];
|
|
657
|
+
if (!arg)
|
|
658
|
+
return {};
|
|
659
|
+
const options = resolveExpression(arg, bindings);
|
|
660
|
+
if (options.type !== 'ObjectExpression')
|
|
661
|
+
return {};
|
|
662
|
+
const result = {};
|
|
663
|
+
for (const prop of options.properties) {
|
|
664
|
+
if (prop.type !== 'ObjectProperty')
|
|
665
|
+
continue;
|
|
666
|
+
const key = propertyKeyName(prop.key);
|
|
667
|
+
if (key !== 'pattern' && key !== 'base')
|
|
668
|
+
continue;
|
|
669
|
+
const value = extractStaticString(prop.value, bindings);
|
|
670
|
+
if (value !== undefined)
|
|
671
|
+
result[key] = value;
|
|
672
|
+
}
|
|
673
|
+
return result;
|
|
674
|
+
}
|
|
675
|
+
function extractStaticString(node, bindings) {
|
|
676
|
+
const resolved = resolveExpression(node, bindings);
|
|
677
|
+
if (resolved.type === 'StringLiteral')
|
|
678
|
+
return resolved.value;
|
|
679
|
+
if (resolved.type === 'TemplateLiteral' && resolved.expressions.length === 0) {
|
|
680
|
+
return resolved.quasis[0]?.value.cooked ?? resolved.quasis[0]?.value.raw;
|
|
681
|
+
}
|
|
682
|
+
return undefined;
|
|
683
|
+
}
|
|
684
|
+
function isGlobCallee(callee) {
|
|
685
|
+
return callee.type === 'Identifier' && callee.name === 'glob';
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Every mention of the string option `name` in the code of a config file, comments aside: as
|
|
689
|
+
* an identifier or as a string of exactly that name, anywhere. One that is the key of a
|
|
690
|
+
* property given a plain string is that string. Any other mention is `null`: another kind of
|
|
691
|
+
* value (a call, a concatenation, a variable), a shorthand, a variable, a parameter or a
|
|
692
|
+
* member of that name, and the name as a string that is not such a key, since a string can be
|
|
693
|
+
* made a key in more ways than can be listed (`Object.defineProperty(config, 'srcDir', …)`,
|
|
694
|
+
* `const KEY = 'srcDir'`). A key given an object literal is left out: it is not a string option, so it is
|
|
695
|
+
* another option of that name. `null` instead of a list for a file that does not parse.
|
|
696
|
+
*
|
|
697
|
+
* For telling whether an option is set to a known value wherever the file could set it,
|
|
698
|
+
* without evaluating the file.
|
|
699
|
+
*/
|
|
700
|
+
export function configOptionMentions(source, name) {
|
|
701
|
+
const ast = parseSource(source);
|
|
702
|
+
if (!ast)
|
|
703
|
+
return null;
|
|
704
|
+
const mentions = [];
|
|
705
|
+
walkValues(ast.program, path => {
|
|
706
|
+
const { node, key } = path.at(-1);
|
|
707
|
+
const parent = path.at(-2)?.node;
|
|
708
|
+
const isKey = parent?.type === 'ObjectProperty' && key === 'key';
|
|
709
|
+
const asString = node.type === 'StringLiteral'
|
|
710
|
+
? node.value
|
|
711
|
+
: node.type === 'TemplateLiteral' && node.expressions.length === 0
|
|
712
|
+
? node.quasis[0]?.value.cooked
|
|
713
|
+
: undefined;
|
|
714
|
+
const named = node.type === 'Identifier' ? node.name === name : asString === name;
|
|
715
|
+
if (!named)
|
|
716
|
+
return;
|
|
717
|
+
// `[name]: …` is keyed by a variable of that name, not by the name.
|
|
718
|
+
if (!isKey || (node.type === 'Identifier' && parent.computed))
|
|
719
|
+
mentions.push(null);
|
|
720
|
+
else if (parent.value.type !== 'ObjectExpression')
|
|
721
|
+
mentions.push(extractStaticString(parent.value, new Map()) ?? null);
|
|
722
|
+
});
|
|
723
|
+
return mentions;
|
|
724
|
+
}
|
|
725
|
+
/** The loaders' own calls. They read what they are handed and hand it on unchanged. */
|
|
726
|
+
const READER_CALLS = ['glob', 'file', 'defineCollection', 'defineCmsCollection'];
|
|
727
|
+
/** Wrappers that change nothing about a value, the ones {@link resolveExpression} sees through. */
|
|
728
|
+
const VALUE_WRAPPERS = new Set(['TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion']);
|
|
729
|
+
/**
|
|
730
|
+
* TypeScript nodes that hold code and not only types; every other `TS…` node is skipped by
|
|
731
|
+
* {@link walkValues}. `TSQualifiedName` is among them for `import alias = blog.loader`, which
|
|
732
|
+
* compiles to a variable; in a type it is below a node that is skipped.
|
|
733
|
+
*/
|
|
734
|
+
const TS_NODES_WITH_CODE = new Set([
|
|
735
|
+
...VALUE_WRAPPERS,
|
|
736
|
+
'TSInstantiationExpression',
|
|
737
|
+
'TSEnumDeclaration',
|
|
738
|
+
'TSEnumMember',
|
|
739
|
+
'TSModuleDeclaration',
|
|
740
|
+
'TSModuleBlock',
|
|
741
|
+
'TSExportAssignment',
|
|
742
|
+
'TSImportEqualsDeclaration',
|
|
743
|
+
'TSQualifiedName',
|
|
744
|
+
'TSParameterProperty',
|
|
745
|
+
]);
|
|
746
|
+
/** Keys of a node that hold no code. */
|
|
747
|
+
const NODE_METADATA = new Set(['loc', 'extra', 'leadingComments', 'trailingComments', 'innerComments']);
|
|
748
|
+
/** Visit every node that can run, with the path that leads to it. Types are passed over: they cannot touch a value. */
|
|
749
|
+
function walkValues(node, visit, path = [{ node, key: '' }]) {
|
|
750
|
+
visit(path);
|
|
751
|
+
const children = Object.entries(node);
|
|
752
|
+
for (const [key, child] of children) {
|
|
753
|
+
if (NODE_METADATA.has(key))
|
|
754
|
+
continue;
|
|
755
|
+
for (const item of Array.isArray(child) ? child : [child]) {
|
|
756
|
+
if (!isAstNode(item) || (item.type.startsWith('TS') && !TS_NODES_WITH_CODE.has(item.type)))
|
|
757
|
+
continue;
|
|
758
|
+
path.push({ node: item, key });
|
|
759
|
+
walkValues(item, visit, path);
|
|
760
|
+
path.pop();
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/** Is the declarator at `path[index]` one of a module-level declaration? */
|
|
765
|
+
function isModuleLevelDeclarator(path, index) {
|
|
766
|
+
const holder = path[index - 2]?.node;
|
|
767
|
+
if (holder?.type === 'ExportNamedDeclaration')
|
|
768
|
+
return path[index - 3]?.node.type === 'Program';
|
|
769
|
+
return holder?.type === 'Program';
|
|
770
|
+
}
|
|
771
|
+
/** A value that cannot be changed in place, so a `const` holding it is what it was declared as, whatever is done with it. */
|
|
772
|
+
function isImmutableLiteral(node) {
|
|
773
|
+
return node.type === 'StringLiteral' || node.type === 'TemplateLiteral' || node.type === 'NumericLiteral'
|
|
774
|
+
|| node.type === 'BooleanLiteral' || node.type === 'NullLiteral' || node.type === 'BigIntLiteral';
|
|
775
|
+
}
|
|
776
|
+
/**
|
|
777
|
+
* The module-level `const`s whose value is, by the time Astro reads the config, what the file
|
|
778
|
+
* declares it as. Only these are followed; a name left out is unknown to the reader.
|
|
779
|
+
*
|
|
780
|
+
* A name is kept when every mention of it in the file is one of a short list of uses that can
|
|
781
|
+
* neither change the value nor hand it to code that can:
|
|
782
|
+
*
|
|
783
|
+
* - its one declaration;
|
|
784
|
+
* - the value of a property in an object literal the reader reads, a first argument of
|
|
785
|
+
* `glob`, `file`, `defineCollection` or `defineCmsCollection` where the reader reads that
|
|
786
|
+
* call, or the whole initializer of another `const` (an alias). "Where the reader reads" is
|
|
787
|
+
* the initializer of a `const` that is itself kept, so a name falls with the one that holds it;
|
|
788
|
+
* - `X.key` where the declaration gives `key` a string, a number, a boolean or `null`, read
|
|
789
|
+
* into a declaration, a property, a call argument, an array, a template, or a binary,
|
|
790
|
+
* logical or conditional expression;
|
|
791
|
+
* - `export { X }`, `export default X`, a type (`typeof X`), and `Object.keys(X)`.
|
|
792
|
+
*
|
|
793
|
+
* Any other mention drops the name: a call that takes it, a member written or called, an
|
|
794
|
+
* array or a spread that holds it, a loop, a conditional, a function that mentions it, a
|
|
795
|
+
* second declaration of the name anywhere (a parameter, a local). So does `eval` or
|
|
796
|
+
* `Function` anywhere in the file, for every name. Listing what is harmless instead of what
|
|
797
|
+
* is harmful means a use nobody thought of leaves a name unknown, not trusted.
|
|
798
|
+
*
|
|
799
|
+
* A `const` that holds a string, a number, a boolean or `null` is kept whatever mentions it:
|
|
800
|
+
* neither the binding nor the value can change.
|
|
801
|
+
*
|
|
802
|
+
* `trusted` names which of the loaders' calls, and `Object`, are not declared in the file
|
|
803
|
+
* itself; a local `glob` is not Astro's.
|
|
804
|
+
*/
|
|
805
|
+
function followedConstants(ast, bindings) {
|
|
806
|
+
const dropped = new Set();
|
|
807
|
+
/** A name → the `const`s whose initializer it is read in: it is kept only while they are. */
|
|
808
|
+
const heldBy = new Map();
|
|
809
|
+
/** A name → the calls it is handed to: it is kept only while they are what they are taken for. */
|
|
810
|
+
const handedTo = new Map();
|
|
811
|
+
const untrusted = new Set();
|
|
812
|
+
let anythingMayChange = false;
|
|
813
|
+
const note = (map, name, values) => {
|
|
814
|
+
map.set(name, new Set([...map.get(name) ?? [], ...values]));
|
|
815
|
+
};
|
|
816
|
+
/** The primitive a `const`'s object literal gives `key`, if that is certain. */
|
|
817
|
+
const holdsPrimitiveAt = (name, key) => {
|
|
818
|
+
const init = bindings.get(name);
|
|
819
|
+
const object = init && resolveExpression(init, new Map());
|
|
820
|
+
const member = object?.type === 'ObjectExpression' ? literalMember(object, key) : undefined;
|
|
821
|
+
return !!member && isImmutableLiteral(resolveExpression(member, new Map()));
|
|
822
|
+
};
|
|
823
|
+
/**
|
|
824
|
+
* The `const` whose initializer the expression at `path[index]` is read in, and the loaders'
|
|
825
|
+
* calls it passes through on the way: it is that initializer, a property value of an object
|
|
826
|
+
* literal that is, or a first argument of one of those calls that is. `null` anywhere else.
|
|
827
|
+
*/
|
|
828
|
+
const readIn = (path, index) => {
|
|
829
|
+
const calls = [];
|
|
830
|
+
for (let at = index;;) {
|
|
831
|
+
const parent = path[at - 1]?.node;
|
|
832
|
+
const { node, key } = path[at];
|
|
833
|
+
if (!parent)
|
|
834
|
+
return null;
|
|
835
|
+
if (VALUE_WRAPPERS.has(parent.type) && key === 'expression') {
|
|
836
|
+
at--;
|
|
837
|
+
}
|
|
838
|
+
else if (parent.type === 'ObjectProperty' && key === 'value' && path[at - 2]?.node.type === 'ObjectExpression') {
|
|
839
|
+
at -= 2;
|
|
840
|
+
}
|
|
841
|
+
else if (parent.type === 'CallExpression' && parent.arguments[0] === node && parent.callee.type === 'Identifier'
|
|
842
|
+
&& READER_CALLS.includes(parent.callee.name)) {
|
|
843
|
+
calls.push(parent.callee.name);
|
|
844
|
+
at--;
|
|
845
|
+
}
|
|
846
|
+
else {
|
|
847
|
+
return parent.type === 'VariableDeclarator' && key === 'init' && parent.id.type === 'Identifier' && isModuleLevelDeclarator(path, at - 1)
|
|
848
|
+
? { holder: parent.id.name, calls }
|
|
849
|
+
: null;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
};
|
|
853
|
+
/** Is the expression at `path[index]` only read, into a place that keeps nothing but its value? */
|
|
854
|
+
const isValueRead = (path, index) => {
|
|
855
|
+
let at = index;
|
|
856
|
+
while (VALUE_WRAPPERS.has(path[at - 1]?.node.type ?? '') && path[at].key === 'expression')
|
|
857
|
+
at--;
|
|
858
|
+
const parent = path[at - 1]?.node;
|
|
859
|
+
const { key } = path[at];
|
|
860
|
+
switch (parent?.type) {
|
|
861
|
+
case 'ObjectProperty':
|
|
862
|
+
return key === 'value' && path[at - 2]?.node.type === 'ObjectExpression';
|
|
863
|
+
case 'CallExpression':
|
|
864
|
+
case 'OptionalCallExpression':
|
|
865
|
+
case 'NewExpression':
|
|
866
|
+
return key === 'arguments';
|
|
867
|
+
case 'VariableDeclarator':
|
|
868
|
+
case 'ArrayExpression':
|
|
869
|
+
case 'TemplateLiteral':
|
|
870
|
+
case 'BinaryExpression':
|
|
871
|
+
case 'LogicalExpression':
|
|
872
|
+
case 'ConditionalExpression':
|
|
873
|
+
return true;
|
|
874
|
+
default:
|
|
875
|
+
return false;
|
|
876
|
+
}
|
|
877
|
+
};
|
|
878
|
+
walkValues(ast.program, path => {
|
|
879
|
+
const { node, key } = path.at(-1);
|
|
880
|
+
const parent = path.at(-2)?.node;
|
|
881
|
+
if (node.type !== 'Identifier' || !parent)
|
|
882
|
+
return;
|
|
883
|
+
const { name } = node;
|
|
884
|
+
// Not a mention of the binding at all: the name of a property.
|
|
885
|
+
const isMemberKey = (parent.type === 'ObjectProperty' || parent.type === 'ObjectMethod' || parent.type === 'ClassMethod' || parent.type === 'ClassProperty')
|
|
886
|
+
&& key === 'key' && !parent.computed;
|
|
887
|
+
const isMemberName = (parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && key === 'property' && !parent.computed;
|
|
888
|
+
const isModuleName = (parent.type === 'ExportSpecifier' && key === 'exported') || (parent.type === 'ImportSpecifier' && key === 'imported');
|
|
889
|
+
// Nor is the `meta` of `import.meta`.
|
|
890
|
+
if (isMemberKey || isMemberName || isModuleName || parent.type === 'MetaProperty')
|
|
891
|
+
return;
|
|
892
|
+
if (name === 'eval' || name === 'Function')
|
|
893
|
+
anythingMayChange = true;
|
|
894
|
+
if (READER_CALLS.includes(name) || name === 'Object') {
|
|
895
|
+
const imported = (parent.type === 'ImportSpecifier' || parent.type === 'ImportDefaultSpecifier' || parent.type === 'ImportNamespaceSpecifier')
|
|
896
|
+
&& key === 'local';
|
|
897
|
+
// `Object` only as the one a method is called on: `Object.keys = …` makes it another.
|
|
898
|
+
const grandparent = path.at(-3)?.node;
|
|
899
|
+
const called = (parent.type === 'CallExpression' && key === 'callee')
|
|
900
|
+
|| (name === 'Object' && parent.type === 'MemberExpression' && key === 'object' && !parent.computed
|
|
901
|
+
&& grandparent?.type === 'CallExpression' && grandparent.callee === parent);
|
|
902
|
+
if (!imported && !called)
|
|
903
|
+
untrusted.add(name);
|
|
904
|
+
}
|
|
905
|
+
if (!bindings.has(name))
|
|
906
|
+
return;
|
|
907
|
+
// Its declaration. Any other declaration of the name is a mention like any other.
|
|
908
|
+
if (parent.type === 'VariableDeclarator' && key === 'id' && isModuleLevelDeclarator(path, path.length - 2))
|
|
909
|
+
return;
|
|
910
|
+
if (parent.type === 'ExportDefaultDeclaration')
|
|
911
|
+
return;
|
|
912
|
+
if (parent.type === 'ExportSpecifier' && key === 'local')
|
|
913
|
+
return;
|
|
914
|
+
if (parent.type === 'CallExpression' && parent.arguments[0] === node && parent.callee.type === 'MemberExpression' && !parent.callee.computed
|
|
915
|
+
&& parent.callee.object.type === 'Identifier' && parent.callee.object.name === 'Object'
|
|
916
|
+
&& parent.callee.property.type === 'Identifier' && parent.callee.property.name === 'keys') {
|
|
917
|
+
note(handedTo, name, ['Object']);
|
|
918
|
+
return;
|
|
919
|
+
}
|
|
920
|
+
if ((parent.type === 'MemberExpression' || parent.type === 'OptionalMemberExpression') && key === 'object' && !parent.computed
|
|
921
|
+
&& parent.property.type === 'Identifier' && holdsPrimitiveAt(name, parent.property.name) && isValueRead(path, path.length - 2))
|
|
922
|
+
return;
|
|
923
|
+
const read = readIn(path, path.length - 1);
|
|
924
|
+
if (read === null) {
|
|
925
|
+
dropped.add(name);
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
note(heldBy, name, [read.holder]);
|
|
929
|
+
note(handedTo, name, read.calls);
|
|
930
|
+
});
|
|
931
|
+
const trusted = new Set([...READER_CALLS, 'Object'].filter(name => !untrusted.has(name)));
|
|
932
|
+
const keeps = (name) => {
|
|
933
|
+
const init = bindings.get(name);
|
|
934
|
+
return init !== undefined && isImmutableLiteral(resolveExpression(init, new Map()));
|
|
935
|
+
};
|
|
936
|
+
const followed = new Map();
|
|
937
|
+
for (const [name, init] of bindings) {
|
|
938
|
+
const handedOn = [...handedTo.get(name) ?? []].every(call => trusted.has(call));
|
|
939
|
+
if (keeps(name) || (!anythingMayChange && !dropped.has(name) && handedOn))
|
|
940
|
+
followed.set(name, init);
|
|
941
|
+
}
|
|
942
|
+
// A name falls with the one whose initializer holds it.
|
|
943
|
+
for (let fell = true; fell;) {
|
|
944
|
+
fell = false;
|
|
945
|
+
for (const [name, holders] of heldBy) {
|
|
946
|
+
if (!followed.has(name) || keeps(name) || [...holders].every(holder => followed.has(holder)))
|
|
947
|
+
continue;
|
|
948
|
+
followed.delete(name);
|
|
949
|
+
fell = true;
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
return { followed, trusted };
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Every collection name the file's `collections` export declares, and whether that is all of
|
|
956
|
+
* them. Reads more forms than the parse above follows (`as`, `satisfies`, a same-file
|
|
957
|
+
* variable, a numeric key): naming a collection commits to nothing, while parsing one gives
|
|
958
|
+
* it a schema and a place in every scan.
|
|
959
|
+
*
|
|
960
|
+
* Identifiers are followed through the module-level `const`s {@link followedConstants} keeps.
|
|
961
|
+
*/
|
|
962
|
+
function readDeclaredCollections(ast) {
|
|
963
|
+
const bindings = new Map();
|
|
964
|
+
let collections;
|
|
965
|
+
let exportsCollections = false;
|
|
966
|
+
// `collections` comes from where this reader does not look: another module, another local
|
|
967
|
+
// name, a `let`, a destructuring…
|
|
968
|
+
let outOfSight = false;
|
|
969
|
+
// …or would, unless this file declares it: `export * from`, `export { collections }` of an import.
|
|
970
|
+
let exportedUndeclared = false;
|
|
971
|
+
for (const stmt of ast.program.body) {
|
|
972
|
+
if (stmt.type === 'ExportAllDeclaration') {
|
|
973
|
+
exportedUndeclared = true;
|
|
974
|
+
exportsCollections = true;
|
|
975
|
+
continue;
|
|
976
|
+
}
|
|
977
|
+
if (stmt.type === 'ExportNamedDeclaration') {
|
|
978
|
+
for (const specifier of stmt.specifiers) {
|
|
979
|
+
const exported = specifier.exported.type === 'Identifier' ? specifier.exported.name : specifier.exported.value;
|
|
980
|
+
if (exported !== 'collections')
|
|
981
|
+
continue;
|
|
982
|
+
exportsCollections = true;
|
|
983
|
+
if (stmt.source || specifier.type !== 'ExportSpecifier' || specifier.local.name !== 'collections')
|
|
984
|
+
outOfSight = true;
|
|
985
|
+
else
|
|
986
|
+
exportedUndeclared = true;
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
const varDecl = stmt.type === 'ExportNamedDeclaration' && stmt.declaration?.type === 'VariableDeclaration'
|
|
990
|
+
? stmt.declaration
|
|
991
|
+
: stmt.type === 'VariableDeclaration'
|
|
992
|
+
? stmt
|
|
993
|
+
: null;
|
|
994
|
+
for (const decl of varDecl?.declarations ?? []) {
|
|
995
|
+
if (stmt.type === 'ExportNamedDeclaration') {
|
|
996
|
+
declaredPatternNames(decl.id, name => {
|
|
997
|
+
if (name === 'collections')
|
|
998
|
+
exportsCollections = true;
|
|
999
|
+
});
|
|
1000
|
+
}
|
|
1001
|
+
if (varDecl?.kind === 'const' && decl.id.type === 'Identifier' && decl.init) {
|
|
1002
|
+
bindings.set(decl.id.name, decl.init);
|
|
1003
|
+
if (decl.id.name === 'collections')
|
|
1004
|
+
collections = decl.init;
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
declaredPatternNames(decl.id, name => {
|
|
1008
|
+
if (name === 'collections')
|
|
1009
|
+
outOfSight = true;
|
|
1010
|
+
});
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
// A config that imports itself can change what it exports without naming it: `self.collections.x = …`.
|
|
1014
|
+
if (importsContentConfig(ast))
|
|
1015
|
+
outOfSight = true;
|
|
1016
|
+
if (!collections)
|
|
1017
|
+
return { declared: [], partial: outOfSight || exportedUndeclared, exportsCollections };
|
|
1018
|
+
const { followed, trusted } = followedConstants(ast, bindings);
|
|
1019
|
+
const object = resolveExpression(collections, followed);
|
|
1020
|
+
if (object.type !== 'ObjectExpression')
|
|
1021
|
+
return { declared: [], partial: true, exportsCollections };
|
|
1022
|
+
// What `collections` holds by the time Astro reads it may be more than the declaration says.
|
|
1023
|
+
let partial = outOfSight || !followed.has('collections') || !isPlainLiteralObject(object);
|
|
1024
|
+
// A name given twice holds what it was given last.
|
|
1025
|
+
const declared = new Map();
|
|
1026
|
+
for (const prop of object.properties) {
|
|
1027
|
+
// A spread, a method or a computed key that is not a string (`[name]: …` is not the name
|
|
1028
|
+
// it spells) hides a name.
|
|
1029
|
+
const name = staticKeyName(prop);
|
|
1030
|
+
if (prop.type !== 'ObjectProperty' || name === null) {
|
|
1031
|
+
partial = true;
|
|
1032
|
+
continue;
|
|
1033
|
+
}
|
|
1034
|
+
if (name === '__proto__')
|
|
1035
|
+
continue;
|
|
1036
|
+
declared.set(name, { name, ...readDeclaredLoader(prop.value, followed, trusted) });
|
|
1037
|
+
}
|
|
1038
|
+
return { declared: [...declared.values()], partial, exportsCollections };
|
|
1039
|
+
}
|
|
1040
|
+
/**
|
|
1041
|
+
* The key an object member is stored under, or `null` when it cannot be told: a spread, or
|
|
1042
|
+
* a computed key that is not a string (`['loader']` is `loader`; `[key]` could be anything).
|
|
1043
|
+
* A numeric key is a name like any other.
|
|
1044
|
+
*/
|
|
1045
|
+
function staticKeyName(prop) {
|
|
1046
|
+
if (prop.type === 'SpreadElement')
|
|
1047
|
+
return null;
|
|
1048
|
+
if (prop.computed)
|
|
1049
|
+
return prop.key.type === 'StringLiteral' ? prop.key.value : null;
|
|
1050
|
+
return prop.key.type === 'NumericLiteral' ? String(prop.key.value) : propertyKeyName(prop.key);
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* An object literal that holds what its own keys say and nothing else: no spread, no key that
|
|
1054
|
+
* cannot be read, and no `__proto__`, which gives it another object's properties to answer with.
|
|
1055
|
+
*/
|
|
1056
|
+
function isPlainLiteralObject(object) {
|
|
1057
|
+
return object.properties.every(prop => {
|
|
1058
|
+
const key = staticKeyName(prop);
|
|
1059
|
+
return key !== null && key !== '__proto__';
|
|
1060
|
+
});
|
|
1061
|
+
}
|
|
1062
|
+
/**
|
|
1063
|
+
* What an object literal holds under `key`: the last member of that name, as a later one
|
|
1064
|
+
* replaces an earlier. `undefined` when it has none; `null` when it has one that is not a
|
|
1065
|
+
* plain value (a getter, a setter, a method).
|
|
1066
|
+
*/
|
|
1067
|
+
function literalMember(object, key) {
|
|
1068
|
+
const member = object.properties.findLast(prop => staticKeyName(prop) === key);
|
|
1069
|
+
if (member === undefined)
|
|
1070
|
+
return undefined;
|
|
1071
|
+
return member.type === 'ObjectProperty' ? member.value : null;
|
|
1072
|
+
}
|
|
1073
|
+
/** A `this` anywhere below `node`: an accessor or a method of a literal can change the literal without naming it. */
|
|
1074
|
+
function mentionsThis(node) {
|
|
1075
|
+
let found = false;
|
|
1076
|
+
walkNodes(node, inner => {
|
|
1077
|
+
if (inner.type === 'ThisExpression')
|
|
1078
|
+
found = true;
|
|
1079
|
+
});
|
|
1080
|
+
return found;
|
|
1081
|
+
}
|
|
1082
|
+
/** A module specifier that may be the content config itself, whatever directory it is given from. */
|
|
1083
|
+
const CONTENT_CONFIG_SPECIFIER = /(?:^|\/)content(?:\.|\/)config(?:\.[cm]?[jt]s)?$/;
|
|
1084
|
+
/** Does the file import a content config, which may be itself? What it exports can then be changed through the import. */
|
|
1085
|
+
function importsContentConfig(ast) {
|
|
1086
|
+
let found = false;
|
|
1087
|
+
walkNodes(ast, node => {
|
|
1088
|
+
const source = node.type === 'ImportDeclaration' || node.type === 'ExportNamedDeclaration'
|
|
1089
|
+
? node.source
|
|
1090
|
+
: node.type === 'CallExpression' && node.callee.type === 'Import'
|
|
1091
|
+
? node.arguments[0]
|
|
1092
|
+
: undefined;
|
|
1093
|
+
if (source?.type === 'StringLiteral' && CONTENT_CONFIG_SPECIFIER.test(source.value))
|
|
1094
|
+
found = true;
|
|
1095
|
+
});
|
|
1096
|
+
return found;
|
|
1097
|
+
}
|
|
1098
|
+
/** The loader facts of a {@link DeclaredCollection}, read off the value its `collections` key holds. */
|
|
1099
|
+
function readDeclaredLoader(value, bindings, trusted) {
|
|
1100
|
+
const isCallOf = (node, names) => node.type === 'CallExpression' && node.callee.type === 'Identifier' && names.includes(node.callee.name) && trusted.has(node.callee.name);
|
|
1101
|
+
const declaration = resolveExpression(value, bindings);
|
|
1102
|
+
if (!isCallOf(declaration, ['defineCollection', 'defineCmsCollection']) || !declaration.arguments[0])
|
|
1103
|
+
return {};
|
|
1104
|
+
const options = resolveExpression(declaration.arguments[0], bindings);
|
|
1105
|
+
if (options.type !== 'ObjectExpression' || mentionsThis(options))
|
|
1106
|
+
return {};
|
|
1107
|
+
// The last `loader` is the one that counts. A spread or a key that cannot be read after it
|
|
1108
|
+
// may replace it, and a `__proto__` may supply one where the literal names none.
|
|
1109
|
+
const lastLoader = options.properties.findLastIndex(prop => staticKeyName(prop) === 'loader');
|
|
1110
|
+
const mayBeReplaced = options.properties.some((prop, index) => {
|
|
1111
|
+
const key = staticKeyName(prop);
|
|
1112
|
+
return key === '__proto__' || (key === null && index > lastLoader);
|
|
1113
|
+
});
|
|
1114
|
+
if (mayBeReplaced)
|
|
1115
|
+
return {};
|
|
1116
|
+
const loader = literalMember(options, 'loader');
|
|
1117
|
+
if (loader === undefined)
|
|
1118
|
+
return { noLoader: true };
|
|
1119
|
+
if (loader === null)
|
|
1120
|
+
return {};
|
|
1121
|
+
const facts = { hasLoader: true };
|
|
1122
|
+
const call = resolveExpression(loader, bindings);
|
|
1123
|
+
if (!isCallOf(call, ['glob', 'file']) || !call.arguments[0])
|
|
1124
|
+
return facts;
|
|
1125
|
+
if (call.callee.name === 'file') {
|
|
1126
|
+
const file = extractStaticString(call.arguments[0], bindings);
|
|
1127
|
+
if (file !== undefined)
|
|
1128
|
+
facts.loaderFile = file;
|
|
1129
|
+
return facts;
|
|
1130
|
+
}
|
|
1131
|
+
const globOptions = resolveExpression(call.arguments[0], bindings);
|
|
1132
|
+
// A spread, a key that cannot be read or a `__proto__` may supply either option, so no literal next to one can be trusted.
|
|
1133
|
+
if (globOptions.type !== 'ObjectExpression' || !isPlainLiteralObject(globOptions) || mentionsThis(globOptions))
|
|
1134
|
+
return facts;
|
|
1135
|
+
const base = literalMember(globOptions, 'base');
|
|
1136
|
+
const pattern = literalMember(globOptions, 'pattern');
|
|
1137
|
+
// Without a `base`, Astro's glob loads from the project root.
|
|
1138
|
+
if (base === undefined)
|
|
1139
|
+
facts.loaderBase = '.';
|
|
1140
|
+
else if (base !== null) {
|
|
1141
|
+
const literal = extractStaticString(base, bindings);
|
|
1142
|
+
if (literal !== undefined)
|
|
1143
|
+
facts.loaderBase = literal;
|
|
1144
|
+
}
|
|
1145
|
+
if (!pattern)
|
|
1146
|
+
return facts;
|
|
1147
|
+
const literal = extractStaticString(pattern, bindings);
|
|
1148
|
+
if (literal !== undefined) {
|
|
1149
|
+
facts.loaderPattern = literal;
|
|
1150
|
+
return facts;
|
|
1151
|
+
}
|
|
1152
|
+
// A list of patterns is a union with its `!` members taken out again.
|
|
1153
|
+
const list = resolveExpression(pattern, bindings);
|
|
1154
|
+
const patterns = list.type === 'ArrayExpression' ? list.elements.map(element => element ? extractStaticString(element, bindings) : undefined) : [];
|
|
1155
|
+
if (patterns.length > 0 && patterns.every(one => one !== undefined))
|
|
1156
|
+
facts.loaderPatterns = patterns;
|
|
1157
|
+
return facts;
|
|
1158
|
+
}
|
|
1159
|
+
/**
|
|
1160
|
+
* Unwrap a `schema:` value down to the top-level (z|n).object({ ... }) ObjectExpression.
|
|
1161
|
+
* Handles direct calls, the Astro callback form `({ image }) => z.object({...})`,
|
|
1162
|
+
* and same-file variable references like `schema: BlogSchema`.
|
|
1163
|
+
*/
|
|
1164
|
+
function unwrapSchemaToObject(node, bindings) {
|
|
1165
|
+
const resolved = resolveExpression(node, bindings);
|
|
1166
|
+
if (resolved.type === 'ArrowFunctionExpression' || resolved.type === 'FunctionExpression') {
|
|
1167
|
+
const body = resolved.body;
|
|
1168
|
+
if (body.type === 'BlockStatement') {
|
|
1169
|
+
for (const stmt of body.body) {
|
|
1170
|
+
if (stmt.type === 'ReturnStatement' && stmt.argument) {
|
|
1171
|
+
return unwrapSchemaToObject(stmt.argument, bindings);
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
return null;
|
|
1175
|
+
}
|
|
1176
|
+
return unwrapSchemaToObject(body, bindings);
|
|
1177
|
+
}
|
|
1178
|
+
if (resolved.type === 'CallExpression') {
|
|
1179
|
+
const callee = resolved.callee;
|
|
1180
|
+
if (callee.type === 'MemberExpression'
|
|
1181
|
+
&& callee.object.type === 'Identifier'
|
|
1182
|
+
&& (callee.object.name === 'z' || callee.object.name === 'n')
|
|
1183
|
+
&& callee.property.type === 'Identifier'
|
|
1184
|
+
&& callee.property.name === 'object') {
|
|
1185
|
+
const arg = resolved.arguments[0];
|
|
1186
|
+
if (!arg)
|
|
1187
|
+
return null;
|
|
1188
|
+
const resolvedArg = resolveExpression(arg, bindings);
|
|
1189
|
+
if (resolvedArg.type === 'ObjectExpression')
|
|
1190
|
+
return resolvedArg;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
return null;
|
|
1194
|
+
}
|
|
1195
|
+
function parseSchemaFields(schemaObject, bindings) {
|
|
1196
|
+
const fields = [];
|
|
1197
|
+
for (const prop of schemaObject.properties) {
|
|
1198
|
+
if (prop.type !== 'ObjectProperty')
|
|
1199
|
+
continue;
|
|
1200
|
+
const name = propertyKeyName(prop.key);
|
|
1201
|
+
if (!name)
|
|
1202
|
+
continue;
|
|
1203
|
+
const field = { name, required: true };
|
|
1204
|
+
analyzeFieldExpression(prop.value, field, bindings);
|
|
1205
|
+
fields.push(field);
|
|
1206
|
+
}
|
|
1207
|
+
return fields;
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Whether members of the schema object were skipped, leaving the field list short.
|
|
1211
|
+
*
|
|
1212
|
+
* A spread (`n.object({ ...base, order: n.number() })`) or a computed key contributes real
|
|
1213
|
+
* fields that never make it into `fields`. The difference matters to anything that treats
|
|
1214
|
+
* the list as exhaustive: an incomplete list is not the same as an empty one, and reading
|
|
1215
|
+
* it as complete turns a legitimate config into a page of warnings.
|
|
1216
|
+
*/
|
|
1217
|
+
function hasSkippedMembers(schemaObject) {
|
|
1218
|
+
return schemaObject.properties.some(prop => prop.type !== 'ObjectProperty' || !propertyKeyName(prop.key));
|
|
1219
|
+
}
|
|
1220
|
+
/**
|
|
1221
|
+
* Walk a field's value expression. Each layer is either a wrapper method call
|
|
1222
|
+
* (`.optional()`, `.default()`, `.nullable()`, `.nullish()`, `.orderBy(...)`)
|
|
1223
|
+
* or the base call (`n.image()`, `image()`, `z.enum([...])`, `n.array(reference(...))`).
|
|
1224
|
+
*
|
|
1225
|
+
* Resolves same-file `Identifier` references against `bindings` at each layer so
|
|
1226
|
+
* patterns like `cs: TestimonialTranslation` and `en: TestimonialTranslation.optional()`
|
|
1227
|
+
* are followed back to their defining call.
|
|
1228
|
+
*/
|
|
1229
|
+
function analyzeFieldExpression(node, field, bindings, helpers = new Set()) {
|
|
1230
|
+
let current = resolveExpression(node, bindings);
|
|
1231
|
+
while (current) {
|
|
1232
|
+
if (current.type !== 'CallExpression')
|
|
1233
|
+
return;
|
|
1234
|
+
if (isBaseCall(current)) {
|
|
1235
|
+
analyzeBaseCall(current, field, bindings);
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
// `tag: optionalTag()` — continue into what the helper returns, so both its type and
|
|
1239
|
+
// the `.optional()` it hides reach the field.
|
|
1240
|
+
if (current.callee.type === 'Identifier') {
|
|
1241
|
+
const returned = sameFileHelperReturn(current, bindings, helpers);
|
|
1242
|
+
if (returned)
|
|
1243
|
+
analyzeFieldExpression(returned, field, bindings, helpers);
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
if (current.callee.type !== 'MemberExpression')
|
|
1247
|
+
return;
|
|
1248
|
+
const property = current.callee.property;
|
|
1249
|
+
const methodName = property.type === 'Identifier' ? property.name : '';
|
|
1250
|
+
// `n.text().array()` — the postfix spelling of `n.array(n.text())`. Without this the
|
|
1251
|
+
// walk steps into the receiver and stamps the *element* type on the list itself.
|
|
1252
|
+
if (methodName === 'array') {
|
|
1253
|
+
const item = { name: '__item__', required: true };
|
|
1254
|
+
analyzeFieldExpression(current.callee.object, item, bindings, helpers);
|
|
1255
|
+
// Keep an array of references flat, exactly as the `n.array(reference())` branch does.
|
|
1256
|
+
if (item.reference) {
|
|
1257
|
+
field.reference = { target: item.reference.target, isArray: true };
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
field.type = 'array';
|
|
1261
|
+
if (item.type)
|
|
1262
|
+
field.itemType = item.type;
|
|
1263
|
+
if (item.fields)
|
|
1264
|
+
field.fields = item.fields;
|
|
1265
|
+
return;
|
|
1266
|
+
}
|
|
1267
|
+
if (WRAPPER_METHODS.has(methodName)) {
|
|
1268
|
+
field.required = false;
|
|
1269
|
+
}
|
|
1270
|
+
else if (methodName === 'orderBy') {
|
|
1271
|
+
const arg = current.arguments[0];
|
|
1272
|
+
const direction = arg?.type === 'StringLiteral' && arg.value === 'desc' ? 'desc' : 'asc';
|
|
1273
|
+
field.orderBy = { direction };
|
|
1274
|
+
}
|
|
1275
|
+
current = resolveExpression(current.callee.object, bindings);
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
/**
|
|
1279
|
+
* The expression a same-file zero-argument helper returns, for field values written as
|
|
1280
|
+
* `tag: optionalTag()`. Cycle-safe via `seen`. A helper taking arguments, or one imported
|
|
1281
|
+
* from another module, resolves to null — its body is not here to read, and guessing at a
|
|
1282
|
+
* type the schema may not declare is worse than leaving the field untyped.
|
|
1283
|
+
*/
|
|
1284
|
+
function sameFileHelperReturn(call, bindings, seen) {
|
|
1285
|
+
if (call.callee.type !== 'Identifier' || call.arguments.length > 0)
|
|
1286
|
+
return null;
|
|
1287
|
+
if (seen.has(call.callee.name))
|
|
1288
|
+
return null;
|
|
1289
|
+
seen.add(call.callee.name);
|
|
1290
|
+
const fn = resolveExpression(call.callee, bindings);
|
|
1291
|
+
if (fn.type !== 'ArrowFunctionExpression' && fn.type !== 'FunctionExpression')
|
|
1292
|
+
return null;
|
|
1293
|
+
if (fn.params.length > 0)
|
|
1294
|
+
return null;
|
|
1295
|
+
if (fn.body.type !== 'BlockStatement')
|
|
1296
|
+
return fn.body;
|
|
1297
|
+
for (const stmt of fn.body.body) {
|
|
1298
|
+
if (stmt.type === 'ReturnStatement' && stmt.argument)
|
|
1299
|
+
return stmt.argument;
|
|
1300
|
+
}
|
|
1301
|
+
return null;
|
|
1302
|
+
}
|
|
1303
|
+
/**
|
|
1304
|
+
* A "base call" is the innermost call that defines the field's type: a Zod/n
|
|
1305
|
+
* helper invocation or a bare `image()` / `reference()` from a callback param.
|
|
1306
|
+
*/
|
|
1307
|
+
function isBaseCall(node) {
|
|
1308
|
+
const callee = node.callee;
|
|
1309
|
+
if (callee.type === 'Identifier') {
|
|
1310
|
+
return callee.name === 'image' || callee.name === 'reference';
|
|
1311
|
+
}
|
|
1312
|
+
if (callee.type === 'MemberExpression') {
|
|
1313
|
+
return callee.object.type === 'Identifier'
|
|
1314
|
+
&& (callee.object.name === 'n' || callee.object.name === 'z');
|
|
1315
|
+
}
|
|
1316
|
+
return false;
|
|
1317
|
+
}
|
|
1318
|
+
function analyzeBaseCall(node, field, bindings) {
|
|
1319
|
+
const callee = node.callee;
|
|
1320
|
+
// Bare image() / reference() from the schema callback form
|
|
1321
|
+
if (callee.type === 'Identifier') {
|
|
1322
|
+
if (callee.name === 'image') {
|
|
1323
|
+
field.type = 'image';
|
|
1324
|
+
field.astroImage = true;
|
|
1325
|
+
return;
|
|
1326
|
+
}
|
|
1327
|
+
if (callee.name === 'reference') {
|
|
1328
|
+
const arg = node.arguments[0];
|
|
1329
|
+
if (arg?.type === 'StringLiteral') {
|
|
1330
|
+
field.reference = { target: arg.value, isArray: false };
|
|
1331
|
+
}
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
if (callee.type !== 'MemberExpression')
|
|
1337
|
+
return;
|
|
1338
|
+
if (callee.object.type !== 'Identifier' || callee.property.type !== 'Identifier')
|
|
1339
|
+
return;
|
|
1340
|
+
const ns = callee.object.name;
|
|
1341
|
+
const fn = callee.property.name;
|
|
1342
|
+
// n.image(), n.url(), n.text(...), etc. — semantic field types from @nuasite/cms.
|
|
1343
|
+
// FIELD_HELPER_TYPES gates to the helper subset (excludes select/array/object/reference,
|
|
1344
|
+
// inferred below, and boolean, which `z` declares the same way); isFieldType narrows
|
|
1345
|
+
// `fn` to FieldType.
|
|
1346
|
+
if (ns === 'n' && FIELD_HELPER_TYPES.has(fn) && isFieldType(fn)) {
|
|
1347
|
+
field.type = fn;
|
|
1348
|
+
const firstArg = node.arguments[0];
|
|
1349
|
+
if (firstArg?.type === 'ObjectExpression') {
|
|
1350
|
+
const hints = parseHintsFromObject(firstArg);
|
|
1351
|
+
if (hints)
|
|
1352
|
+
field.hints = hints;
|
|
1353
|
+
const layout = parseFieldLayoutFromObject(firstArg);
|
|
1354
|
+
if (layout)
|
|
1355
|
+
field.layout = layout;
|
|
1356
|
+
}
|
|
1357
|
+
return;
|
|
1358
|
+
}
|
|
1359
|
+
// (z|n).boolean() → checkbox. Not in FIELD_HELPER_TYPES because that gate is `n`-only,
|
|
1360
|
+
// and a plain `z.boolean()` declares the very same field.
|
|
1361
|
+
if ((ns === 'z' || ns === 'n') && fn === 'boolean') {
|
|
1362
|
+
field.type = 'boolean';
|
|
1363
|
+
return;
|
|
1364
|
+
}
|
|
1365
|
+
// (z|n).enum([...]) → select with options
|
|
1366
|
+
if ((ns === 'z' || ns === 'n') && fn === 'enum') {
|
|
1367
|
+
const arg = node.arguments[0] ? resolveExpression(node.arguments[0], bindings) : undefined;
|
|
1368
|
+
const options = arg?.type === 'ArrayExpression' ? readEnumOptions(arg) : null;
|
|
1369
|
+
if (options) {
|
|
1370
|
+
field.type = 'select';
|
|
1371
|
+
field.options = options;
|
|
1372
|
+
}
|
|
1373
|
+
// `n.enum([…], { label, help, … })` — the value list takes the first argument, so
|
|
1374
|
+
// layout hints ride in the second one; every other marker carries them in the first.
|
|
1375
|
+
// A bare `z.enum([…], { message })` is unaffected: Zod's params share no key with the
|
|
1376
|
+
// layout shape, so nothing is picked up.
|
|
1377
|
+
const hintsArg = node.arguments[1];
|
|
1378
|
+
if (hintsArg?.type === 'ObjectExpression') {
|
|
1379
|
+
const layout = parseFieldLayoutFromObject(hintsArg);
|
|
1380
|
+
if (layout)
|
|
1381
|
+
field.layout = layout;
|
|
1382
|
+
}
|
|
1383
|
+
return;
|
|
1384
|
+
}
|
|
1385
|
+
// (z|n).object({...}) → nested object field
|
|
1386
|
+
if ((ns === 'z' || ns === 'n') && fn === 'object') {
|
|
1387
|
+
const arg = node.arguments[0];
|
|
1388
|
+
if (!arg)
|
|
1389
|
+
return;
|
|
1390
|
+
const resolved = resolveExpression(arg, bindings);
|
|
1391
|
+
if (resolved.type === 'ObjectExpression') {
|
|
1392
|
+
field.type = 'object';
|
|
1393
|
+
field.fields = parseSchemaFields(resolved, bindings);
|
|
1394
|
+
}
|
|
1395
|
+
return;
|
|
1396
|
+
}
|
|
1397
|
+
// (z|n).array(<inner>) → array; inspect the element type
|
|
1398
|
+
if ((ns === 'z' || ns === 'n') && fn === 'array') {
|
|
1399
|
+
const innerRaw = node.arguments[0];
|
|
1400
|
+
if (!innerRaw)
|
|
1401
|
+
return;
|
|
1402
|
+
const inner = resolveExpression(innerRaw, bindings);
|
|
1403
|
+
// Array of references: keep the existing flat shape so detectReferenceFields can wire it up.
|
|
1404
|
+
if (inner.type === 'CallExpression'
|
|
1405
|
+
&& inner.callee.type === 'Identifier'
|
|
1406
|
+
&& inner.callee.name === 'reference') {
|
|
1407
|
+
const target = inner.arguments[0];
|
|
1408
|
+
if (target?.type === 'StringLiteral') {
|
|
1409
|
+
field.reference = { target: target.value, isArray: true };
|
|
1410
|
+
}
|
|
1411
|
+
return;
|
|
1412
|
+
}
|
|
1413
|
+
// Array of anything else: analyze the inner expression and lift its type/fields.
|
|
1414
|
+
// Note: nested arrays (`n.array(n.array(...))`) collapse here — `itemType` records
|
|
1415
|
+
// only the outer element type, the inner element shape is lost. No editor flow
|
|
1416
|
+
// currently renders nested arrays, so we don't carry a recursive `itemDefinition`
|
|
1417
|
+
// yet; add one when editor support arrives.
|
|
1418
|
+
const innerField = { name: '__item__', required: true };
|
|
1419
|
+
analyzeFieldExpression(inner, innerField, bindings);
|
|
1420
|
+
field.type = 'array';
|
|
1421
|
+
if (innerField.type)
|
|
1422
|
+
field.itemType = innerField.type;
|
|
1423
|
+
if (innerField.fields)
|
|
1424
|
+
field.fields = innerField.fields;
|
|
1425
|
+
return;
|
|
1426
|
+
}
|
|
1427
|
+
}
|
|
1428
|
+
function parseHintsFromObject(obj) {
|
|
1429
|
+
const raw = {};
|
|
1430
|
+
for (const prop of obj.properties) {
|
|
1431
|
+
if (prop.type !== 'ObjectProperty')
|
|
1432
|
+
continue;
|
|
1433
|
+
const key = propertyKeyName(prop.key);
|
|
1434
|
+
if (!key || !VALID_HINT_KEYS.has(key))
|
|
1435
|
+
continue;
|
|
1436
|
+
const value = prop.value;
|
|
1437
|
+
if (value.type === 'NumericLiteral') {
|
|
1438
|
+
assignHint(raw, key, value.value);
|
|
1439
|
+
}
|
|
1440
|
+
else if (value.type === 'UnaryExpression'
|
|
1441
|
+
&& value.operator === '-'
|
|
1442
|
+
&& value.argument.type === 'NumericLiteral') {
|
|
1443
|
+
assignHint(raw, key, -value.argument.value);
|
|
1444
|
+
}
|
|
1445
|
+
else if (value.type === 'StringLiteral') {
|
|
1446
|
+
assignHint(raw, key, value.value);
|
|
1447
|
+
}
|
|
1448
|
+
}
|
|
1449
|
+
if (Object.keys(raw).length === 0)
|
|
1450
|
+
return undefined;
|
|
1451
|
+
return raw;
|
|
1452
|
+
}
|
|
1453
|
+
/** Assign a parsed hint value onto the hints object, narrowing per the FieldHints shape. */
|
|
1454
|
+
function assignHint(hints, key, value) {
|
|
1455
|
+
switch (key) {
|
|
1456
|
+
case 'min':
|
|
1457
|
+
case 'max':
|
|
1458
|
+
hints[key] = value;
|
|
1459
|
+
return;
|
|
1460
|
+
case 'step':
|
|
1461
|
+
case 'maxLength':
|
|
1462
|
+
case 'minLength':
|
|
1463
|
+
case 'rows':
|
|
1464
|
+
if (typeof value === 'number')
|
|
1465
|
+
hints[key] = value;
|
|
1466
|
+
return;
|
|
1467
|
+
case 'placeholder':
|
|
1468
|
+
case 'accept':
|
|
1469
|
+
if (typeof value === 'string')
|
|
1470
|
+
hints[key] = value;
|
|
1471
|
+
return;
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
/** Read per-field layout hints (label/help/group/sidebar/width/order/hidden) from a marker's options object. */
|
|
1475
|
+
function parseFieldLayoutFromObject(obj) {
|
|
1476
|
+
const layout = {};
|
|
1477
|
+
for (const prop of obj.properties) {
|
|
1478
|
+
if (prop.type !== 'ObjectProperty')
|
|
1479
|
+
continue;
|
|
1480
|
+
const key = propertyKeyName(prop.key);
|
|
1481
|
+
const value = prop.value;
|
|
1482
|
+
switch (key) {
|
|
1483
|
+
case 'label':
|
|
1484
|
+
if (value.type === 'StringLiteral')
|
|
1485
|
+
layout.label = value.value;
|
|
1486
|
+
break;
|
|
1487
|
+
case 'help':
|
|
1488
|
+
if (value.type === 'StringLiteral')
|
|
1489
|
+
layout.help = value.value;
|
|
1490
|
+
break;
|
|
1491
|
+
case 'group':
|
|
1492
|
+
if (value.type === 'StringLiteral')
|
|
1493
|
+
layout.group = value.value;
|
|
1494
|
+
break;
|
|
1495
|
+
case 'width':
|
|
1496
|
+
if (value.type === 'StringLiteral' && (value.value === 'full' || value.value === 'half'))
|
|
1497
|
+
layout.width = value.value;
|
|
1498
|
+
break;
|
|
1499
|
+
case 'order':
|
|
1500
|
+
if (value.type === 'NumericLiteral') {
|
|
1501
|
+
layout.order = value.value;
|
|
1502
|
+
}
|
|
1503
|
+
else if (value.type === 'UnaryExpression' && value.operator === '-' && value.argument.type === 'NumericLiteral') {
|
|
1504
|
+
layout.order = -value.argument.value;
|
|
1505
|
+
}
|
|
1506
|
+
break;
|
|
1507
|
+
case 'sidebar':
|
|
1508
|
+
if (value.type === 'BooleanLiteral')
|
|
1509
|
+
layout.sidebar = value.value;
|
|
1510
|
+
break;
|
|
1511
|
+
case 'position':
|
|
1512
|
+
if (value.type === 'StringLiteral' && (value.value === 'sidebar' || value.value === 'header'))
|
|
1513
|
+
layout.position = value.value;
|
|
1514
|
+
break;
|
|
1515
|
+
case 'hidden':
|
|
1516
|
+
if (value.type === 'BooleanLiteral')
|
|
1517
|
+
layout.hidden = value.value;
|
|
1518
|
+
break;
|
|
1519
|
+
case 'derivedFrom':
|
|
1520
|
+
parseDerivedFromValue(value, layout);
|
|
1521
|
+
break;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
return Object.keys(layout).length > 0 ? layout : undefined;
|
|
1525
|
+
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Read a `derivedFrom` option in either authoring form:
|
|
1528
|
+
*
|
|
1529
|
+
* ```ts
|
|
1530
|
+
* n.text({ derivedFrom: 'category' }) // → slugifyHref
|
|
1531
|
+
* n.text({ derivedFrom: { field: 'category', transform: 'slug' } })
|
|
1532
|
+
* ```
|
|
1533
|
+
*
|
|
1534
|
+
* `field` is mandatory in the object form — without a source there is nothing to derive
|
|
1535
|
+
* from, so the whole declaration is dropped. An unknown `transform` name is ignored rather
|
|
1536
|
+
* than rejected: the field keeps deriving, on the default transform, instead of silently
|
|
1537
|
+
* dropping out of the recompute because of a typo.
|
|
1538
|
+
*/
|
|
1539
|
+
function parseDerivedFromValue(value, layout) {
|
|
1540
|
+
if (value.type === 'StringLiteral') {
|
|
1541
|
+
if (value.value)
|
|
1542
|
+
layout.derivedFrom = value.value;
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
if (value.type !== 'ObjectExpression')
|
|
1546
|
+
return;
|
|
1547
|
+
let field;
|
|
1548
|
+
let transform;
|
|
1549
|
+
for (const prop of value.properties) {
|
|
1550
|
+
if (prop.type !== 'ObjectProperty')
|
|
1551
|
+
continue;
|
|
1552
|
+
const key = propertyKeyName(prop.key);
|
|
1553
|
+
if (prop.value.type !== 'StringLiteral')
|
|
1554
|
+
continue;
|
|
1555
|
+
if (key === 'field')
|
|
1556
|
+
field = prop.value.value;
|
|
1557
|
+
else if (key === 'transform' && isDerivedTransform(prop.value.value))
|
|
1558
|
+
transform = prop.value.value;
|
|
1559
|
+
}
|
|
1560
|
+
if (!field)
|
|
1561
|
+
return;
|
|
1562
|
+
layout.derivedFrom = field;
|
|
1563
|
+
if (transform)
|
|
1564
|
+
layout.derivedTransform = transform;
|
|
1565
|
+
}
|
|
1566
|
+
/**
|
|
1567
|
+
* Report the `derivedFrom` declarations the recompute cannot honour, and drop the ones that
|
|
1568
|
+
* would otherwise take effect halfway.
|
|
1569
|
+
*
|
|
1570
|
+
* Two kinds, both silent before:
|
|
1571
|
+
*
|
|
1572
|
+
* - **Unknown source.** `derivedFrom: 'catgory'` parses perfectly well, so the field is
|
|
1573
|
+
* hidden (a declaration implies `hidden`) and then never computed, because no such key ever
|
|
1574
|
+
* appears in the frontmatter. The result is a field that has quietly left the CMS. Warn
|
|
1575
|
+
* rather than throw: a typo in one field must not take the whole config down, and the site
|
|
1576
|
+
* still builds.
|
|
1577
|
+
* - **Nested field.** Deriving is a top-level operation — `applyDerivedFields` reads the
|
|
1578
|
+
* entry's top-level frontmatter, which is the only place a source name is unambiguous.
|
|
1579
|
+
* A `derivedFrom` inside `n.object({ … })` used to hide the sub-field anyway and then never
|
|
1580
|
+
* compute it, so the key disappeared from the file on the next write. Rather than invent
|
|
1581
|
+
* "source relative to the parent object" semantics, the declaration is dropped here: the
|
|
1582
|
+
* nested field stays visible and hand-editable, and the warning says why.
|
|
1583
|
+
*
|
|
1584
|
+
* Emitted over `console.warn` for the same reason as `warnOnPathnameCollisions` in
|
|
1585
|
+
* `collection-scanner.ts`: `cms-core` cannot reach the ErrorCollector in `@nuasite/cms` and
|
|
1586
|
+
* must not grow a dependency on it.
|
|
1587
|
+
*/
|
|
1588
|
+
function checkDerivedFromDeclarations(collectionName, fields) {
|
|
1589
|
+
const siblingNames = new Set(fields.map(f => f.name));
|
|
1590
|
+
for (const field of fields) {
|
|
1591
|
+
const source = field.layout?.derivedFrom;
|
|
1592
|
+
if (source !== undefined && !siblingNames.has(source)) {
|
|
1593
|
+
console.warn(`[cms] collection "${collectionName}": field "${field.name}" derives from "${source}", which is not a field of this collection`
|
|
1594
|
+
+ ` — the field is hidden and nothing is ever computed for it`);
|
|
1595
|
+
}
|
|
1596
|
+
dropNestedDerivedFrom(collectionName, field.name, field.fields);
|
|
1597
|
+
}
|
|
1598
|
+
}
|
|
1599
|
+
/** Strip `derivedFrom` from every field below the top level, warning once per declaration. */
|
|
1600
|
+
function dropNestedDerivedFrom(collectionName, path, fields) {
|
|
1601
|
+
if (!fields)
|
|
1602
|
+
return;
|
|
1603
|
+
for (const field of fields) {
|
|
1604
|
+
const fieldPath = `${path}.${field.name}`;
|
|
1605
|
+
const layout = field.layout;
|
|
1606
|
+
if (layout?.derivedFrom !== undefined) {
|
|
1607
|
+
console.warn(`[cms] collection "${collectionName}": field "${fieldPath}" declares \`derivedFrom\` on a nested field, which is not supported`
|
|
1608
|
+
+ ` — only top-level fields derive, so the declaration is ignored and the field stays editable`);
|
|
1609
|
+
delete layout.derivedFrom;
|
|
1610
|
+
delete layout.derivedTransform;
|
|
1611
|
+
}
|
|
1612
|
+
dropNestedDerivedFrom(collectionName, fieldPath, field.fields);
|
|
1613
|
+
}
|
|
1614
|
+
}
|