storyblok 4.23.4 → 4.24.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/README.md +2 -2
- package/dist/index.mjs +218 -40
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -56,8 +56,8 @@
|
|
|
56
56
|
|
|
57
57
|
## Documentation
|
|
58
58
|
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
For complete documentation, please visit the
|
|
60
|
+
[package reference](https://www.storyblok.com/docs/tooling/cli).
|
|
61
61
|
|
|
62
62
|
## Setup
|
|
63
63
|
|
package/dist/index.mjs
CHANGED
|
@@ -28,6 +28,7 @@ import { pipeline as pipeline$1 } from "node:stream/promises";
|
|
|
28
28
|
import { Buffer } from "node:buffer";
|
|
29
29
|
import Storyblok from "storyblok-js-client";
|
|
30
30
|
import { DENIABLE_FIELD_TYPES, TAG_LIST_KEYS } from "@storyblok/schema";
|
|
31
|
+
import * as officialFieldPlugins from "@storyblok/schema/field-plugins";
|
|
31
32
|
import { createTwoFilesPatch } from "diff";
|
|
32
33
|
//#region src/constants.ts
|
|
33
34
|
const commands = {
|
|
@@ -158,12 +159,32 @@ const directories = {
|
|
|
158
159
|
* Splits an iterable into batches of at most `size` items, preserving order.
|
|
159
160
|
* Returns `[]` for empty input. If `size <= 0`, returns the full input as a single batch.
|
|
160
161
|
*/
|
|
161
|
-
const chunk = (items, size) => {
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
162
|
+
const chunk = (items, size) => chunkByWeight(items, {
|
|
163
|
+
maxSize: size,
|
|
164
|
+
maxWeight: Infinity,
|
|
165
|
+
weightOf: () => 0
|
|
166
|
+
});
|
|
167
|
+
/**
|
|
168
|
+
* Splits an iterable into batches, preserving order, so that each batch holds at most `maxSize`
|
|
169
|
+
* items and their summed `weightOf` stays within `maxWeight`. An item heavier than `maxWeight`
|
|
170
|
+
* gets a batch of its own rather than being dropped. A `maxSize <= 0` means no size limit.
|
|
171
|
+
*/
|
|
172
|
+
const chunkByWeight = (items, { maxSize, maxWeight, weightOf }) => {
|
|
173
|
+
const sizeLimit = maxSize > 0 ? maxSize : Infinity;
|
|
165
174
|
const chunks = [];
|
|
166
|
-
|
|
175
|
+
let current = [];
|
|
176
|
+
let currentWeight = 0;
|
|
177
|
+
for (const item of items) {
|
|
178
|
+
const weight = weightOf(item);
|
|
179
|
+
if (current.length > 0 && (current.length >= sizeLimit || currentWeight + weight > maxWeight)) {
|
|
180
|
+
chunks.push(current);
|
|
181
|
+
current = [];
|
|
182
|
+
currentWeight = 0;
|
|
183
|
+
}
|
|
184
|
+
current.push(item);
|
|
185
|
+
currentWeight += weight;
|
|
186
|
+
}
|
|
187
|
+
if (current.length > 0) chunks.push(current);
|
|
167
188
|
return chunks;
|
|
168
189
|
};
|
|
169
190
|
//#endregion
|
|
@@ -953,6 +974,17 @@ const slugify = (text) => text.toString().toLowerCase().replace(/\s+/g, "-").rep
|
|
|
953
974
|
function createRegexFromGlob(pattern) {
|
|
954
975
|
return new RegExp(`^${pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\\\*/g, ".*")}$`);
|
|
955
976
|
}
|
|
977
|
+
let runtimeErrorExitCode = 1;
|
|
978
|
+
/**
|
|
979
|
+
* Lets a run reserve `1` for its result, as `--exit-code` does for differences,
|
|
980
|
+
* by moving runtime errors to `2`.
|
|
981
|
+
*/
|
|
982
|
+
function setRuntimeErrorExitCode(code) {
|
|
983
|
+
runtimeErrorExitCode = code;
|
|
984
|
+
}
|
|
985
|
+
function getRuntimeErrorExitCode() {
|
|
986
|
+
return runtimeErrorExitCode;
|
|
987
|
+
}
|
|
956
988
|
//#endregion
|
|
957
989
|
//#region src/lib/ui/ui.ts
|
|
958
990
|
let stdoutEpipeGuarded = false;
|
|
@@ -966,7 +998,7 @@ let stdoutEpipeGuarded = false;
|
|
|
966
998
|
* run looks like a failure to CI. There is nothing left to write, so EPIPE is
|
|
967
999
|
* swallowed.
|
|
968
1000
|
*
|
|
969
|
-
* Any other stdout error is reported
|
|
1001
|
+
* Any other stdout error is reported as a runtime error. Rethrowing it here would land
|
|
970
1002
|
* in the same trap the guard exists to avoid: a throw inside an `'error'`
|
|
971
1003
|
* listener is an uncaught exception, so the stack trace and clobbered exit code
|
|
972
1004
|
* come back for every `code` that is not EPIPE.
|
|
@@ -977,7 +1009,7 @@ function guardStdoutEpipe(ui) {
|
|
|
977
1009
|
process.stdout.on("error", (error) => {
|
|
978
1010
|
if (error.code === "EPIPE") return;
|
|
979
1011
|
ui.error(`Failed to write to stdout: ${error.message}`);
|
|
980
|
-
process.exitCode =
|
|
1012
|
+
process.exitCode = getRuntimeErrorExitCode();
|
|
981
1013
|
});
|
|
982
1014
|
}
|
|
983
1015
|
const noopProgressBar = {
|
|
@@ -1243,7 +1275,7 @@ function handleError(error, verbose = false, context) {
|
|
|
1243
1275
|
errorCode: "code" in error ? String(error.code) : "UNKNOWN_ERROR",
|
|
1244
1276
|
context
|
|
1245
1277
|
});
|
|
1246
|
-
if (!process.exitCode) process.exitCode = error instanceof CommandError ? 2 :
|
|
1278
|
+
if (!process.exitCode) process.exitCode = error instanceof CommandError ? 2 : getRuntimeErrorExitCode();
|
|
1247
1279
|
}
|
|
1248
1280
|
function logOnlyError(error, context) {
|
|
1249
1281
|
getLogger().error(error.message, {
|
|
@@ -1949,6 +1981,7 @@ function getProgram() {
|
|
|
1949
1981
|
else programInstance.option(option.flags, option.description, option.defaultValue);
|
|
1950
1982
|
programInstance.hook("preAction", async (thisCommand, actionCommand) => {
|
|
1951
1983
|
const targetCommand = actionCommand ?? thisCommand;
|
|
1984
|
+
setRuntimeErrorExitCode(targetCommand.opts().exitCode ? 2 : 1);
|
|
1952
1985
|
const ancestry = getCommandAncestry(targetCommand);
|
|
1953
1986
|
const resolvedConfig = await resolveConfig(targetCommand, ancestry);
|
|
1954
1987
|
applyConfigToCommander(ancestry, resolvedConfig);
|
|
@@ -4079,6 +4112,16 @@ const normalizeFullSlug = (slug) => slug.replace(/\/$/, "");
|
|
|
4079
4112
|
* than let the filter silently select an empty set.
|
|
4080
4113
|
*/
|
|
4081
4114
|
const normalizeStartsWith = (prefix) => prefix.replace(/^\/+/, "");
|
|
4115
|
+
/**
|
|
4116
|
+
* How `stories push` handles story content that does not match the local
|
|
4117
|
+
* component schemas: abort (`strict`), report and push anyway (`warn`), or skip
|
|
4118
|
+
* the check (`ignore`).
|
|
4119
|
+
*/
|
|
4120
|
+
const PUSH_VALIDATE_MODES = [
|
|
4121
|
+
"strict",
|
|
4122
|
+
"warn",
|
|
4123
|
+
"ignore"
|
|
4124
|
+
];
|
|
4082
4125
|
//#endregion
|
|
4083
4126
|
//#region src/commands/stories/actions.ts
|
|
4084
4127
|
/**
|
|
@@ -4168,6 +4211,9 @@ const updateStory = async (spaceId, storyId, payload) => {
|
|
|
4168
4211
|
}
|
|
4169
4212
|
};
|
|
4170
4213
|
const PREFETCH_CHUNK_SIZE = 100;
|
|
4214
|
+
const PREFETCH_MAX_ENCODED_SLUGS_LENGTH = 6e3;
|
|
4215
|
+
const ENCODED_SEPARATOR_LENGTH = 3;
|
|
4216
|
+
const MAX_REPORTED_SLUG_LENGTH = 100;
|
|
4171
4217
|
const PREFETCH_PER_PAGE = 100;
|
|
4172
4218
|
const addRef = (result, story) => {
|
|
4173
4219
|
const ref = {
|
|
@@ -4212,6 +4258,8 @@ const fetchChunkAllPages = async (spaceId, params, onPageStories) => {
|
|
|
4212
4258
|
*
|
|
4213
4259
|
* Slug and id batches are dispatched concurrently through the MAPI client's
|
|
4214
4260
|
* existing throttle (default 6 requests per second, auto-retries 429).
|
|
4261
|
+
*
|
|
4262
|
+
* Throws before any request if a slug is too long to fit into a lookup URL.
|
|
4215
4263
|
*/
|
|
4216
4264
|
const prefetchTargetStoriesByKeys = async (spaceId, keys, options) => {
|
|
4217
4265
|
const result = {
|
|
@@ -4223,8 +4271,20 @@ const prefetchTargetStoriesByKeys = async (spaceId, keys, options) => {
|
|
|
4223
4271
|
const idSet = /* @__PURE__ */ new Set();
|
|
4224
4272
|
for (const id of keys.ids) if (typeof id === "number" && Number.isFinite(id)) idSet.add(id);
|
|
4225
4273
|
options?.onTotal?.(slugSet.size + idSet.size);
|
|
4274
|
+
const encodedSlugLength = (slug) => encodeURIComponent(slug).length + ENCODED_SEPARATOR_LENGTH;
|
|
4275
|
+
const unmatchableSlugs = [...slugSet].filter((slug) => encodedSlugLength(slug) > PREFETCH_MAX_ENCODED_SLUGS_LENGTH);
|
|
4276
|
+
if (unmatchableSlugs.length > 0) {
|
|
4277
|
+
const reportedSlugs = unmatchableSlugs.map((slug) => {
|
|
4278
|
+
return ` ${slug.length > MAX_REPORTED_SLUG_LENGTH ? `…${slug.slice(-100)}` : slug} (${encodedSlugLength(slug)} characters)`;
|
|
4279
|
+
});
|
|
4280
|
+
throw new Error([`Full slugs longer than ${PREFETCH_MAX_ENCODED_SLUGS_LENGTH} URL-encoded characters can't be matched with existing stories in the target space. Shorten the slugs or nest the stories in fewer folders. Affected stories (${unmatchableSlugs.length}):`, ...reportedSlugs].join("\n"));
|
|
4281
|
+
}
|
|
4226
4282
|
if (slugSet.size === 0 && idSet.size === 0) return result;
|
|
4227
|
-
const slugChunks =
|
|
4283
|
+
const slugChunks = chunkByWeight(slugSet, {
|
|
4284
|
+
maxSize: PREFETCH_CHUNK_SIZE,
|
|
4285
|
+
maxWeight: PREFETCH_MAX_ENCODED_SLUGS_LENGTH,
|
|
4286
|
+
weightOf: encodedSlugLength
|
|
4287
|
+
});
|
|
4228
4288
|
const idChunks = chunk(idSet, PREFETCH_CHUNK_SIZE);
|
|
4229
4289
|
const requests = [];
|
|
4230
4290
|
for (const slugs of slugChunks) requests.push((async () => {
|
|
@@ -8994,21 +9054,23 @@ const formatStoryList = (stories) => {
|
|
|
8994
9054
|
return `${sorted.slice(0, MAX_STORIES_PER_ENTRY).join(", ")}, and ${sorted.length - MAX_STORIES_PER_ENTRY} more`;
|
|
8995
9055
|
};
|
|
8996
9056
|
/**
|
|
8997
|
-
* Builds the multi-line
|
|
8998
|
-
*
|
|
8999
|
-
*
|
|
9000
|
-
*
|
|
9001
|
-
*
|
|
9057
|
+
* Builds the multi-line message shown to the user when `collectSchemaIssues`
|
|
9058
|
+
* finds at least one problem. Splits the two kinds of issues into separate
|
|
9059
|
+
* sections with tailored remedies: the fix for a missing component schema is
|
|
9060
|
+
* different from the fix for an undeclared field, and running
|
|
9061
|
+
* `storyblok components pull` is not always the right answer. The headline
|
|
9062
|
+
* depends on whether the push aborts (`strict`) or continues (`warn`).
|
|
9002
9063
|
*/
|
|
9003
|
-
const formatSchemaIssues = (issues) => {
|
|
9004
|
-
const lines = ["Schema validation failed. Push aborted."];
|
|
9064
|
+
const formatSchemaIssues = (issues, mode) => {
|
|
9065
|
+
const lines = [mode === "strict" ? "Schema validation failed. Push aborted." : "Schema validation found issues. Continuing the push in warn mode (`--validate=warn`)."];
|
|
9005
9066
|
if (issues.missingSchemas.size > 0) {
|
|
9006
9067
|
lines.push("");
|
|
9007
9068
|
lines.push("Missing component schemas:");
|
|
9008
9069
|
const sortedMissing = [...issues.missingSchemas.entries()].sort(([a], [b]) => a.localeCompare(b));
|
|
9009
9070
|
for (const [component, stories] of sortedMissing) lines.push(` - ${component} (in stories: ${formatStoryList(stories)})`);
|
|
9010
9071
|
lines.push("");
|
|
9011
|
-
lines.push("
|
|
9072
|
+
if (mode === "warn") lines.push("These components are pushed as they are. References inside them are not mapped to the target space.");
|
|
9073
|
+
lines.push(`${mode === "strict" ? "If" : "To resolve: if"} these components exist in Storyblok, run \`storyblok components pull\` to sync them locally.`);
|
|
9012
9074
|
lines.push("Otherwise, create them in Storyblok first, or remove the references from the affected stories.");
|
|
9013
9075
|
}
|
|
9014
9076
|
if (issues.driftByComponent.size > 0) {
|
|
@@ -9020,10 +9082,15 @@ const formatSchemaIssues = (issues) => {
|
|
|
9020
9082
|
for (const [field, stories] of sortedFields) lines.push(` - ${component}.${field} (in stories: ${formatStoryList(stories)})`);
|
|
9021
9083
|
}
|
|
9022
9084
|
lines.push("");
|
|
9023
|
-
lines.push("These fields
|
|
9085
|
+
if (mode === "warn") lines.push("These fields are pushed as they are. References inside them are not mapped to the target space.");
|
|
9086
|
+
lines.push(`${mode === "strict" ? "To fix" : "To resolve"}, either:`);
|
|
9024
9087
|
lines.push(" - Add the field to the component in Storyblok, then run `storyblok components pull`");
|
|
9025
9088
|
lines.push(" - Or remove the field from the affected story JSON files");
|
|
9026
9089
|
}
|
|
9090
|
+
if (mode === "strict") {
|
|
9091
|
+
lines.push("");
|
|
9092
|
+
lines.push("To push anyway, run the command with `--validate=warn`.");
|
|
9093
|
+
}
|
|
9027
9094
|
return lines.join("\n");
|
|
9028
9095
|
};
|
|
9029
9096
|
const hasSchemaIssues = (issues) => issues.missingSchemas.size > 0 || issues.driftByComponent.size > 0;
|
|
@@ -9837,7 +9904,7 @@ var FailureCollector = class {
|
|
|
9837
9904
|
};
|
|
9838
9905
|
//#endregion
|
|
9839
9906
|
//#region src/commands/stories/push/index.ts
|
|
9840
|
-
storiesCommand.command("push").option("-s, --space <space>", "space ID").option("-f, --from <from>", "source space id").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("--publish", "Publish stories after pushing").option("--cleanup", "delete local stories after a successful push (note: does not cleanup manifests)").description(`Push local stories to a Storyblok space.`).action(async (options, command) => {
|
|
9907
|
+
storiesCommand.command("push").option("-s, --space <space>", "space ID").option("-f, --from <from>", "source space id").option("-d, --dry-run", "Preview changes without applying them to Storyblok").option("--publish", "Publish stories after pushing").option("--cleanup", "delete local stories after a successful push (note: does not cleanup manifests)").addOption(new Option("--validate <mode>", "how to handle stories that do not match the local component schemas").choices(PUSH_VALIDATE_MODES).default("strict")).description(`Push local stories to a Storyblok space.`).action(async (options, command) => {
|
|
9841
9908
|
const ui = getUI();
|
|
9842
9909
|
const logger = getLogger();
|
|
9843
9910
|
const reporter = getReporter();
|
|
@@ -9891,18 +9958,28 @@ storiesCommand.command("push").option("-s, --space <space>", "space ID").option(
|
|
|
9891
9958
|
return;
|
|
9892
9959
|
}
|
|
9893
9960
|
const storiesDirectoryPath = resolveCommandPath(directories.stories, fromSpace, basePath);
|
|
9894
|
-
const
|
|
9895
|
-
|
|
9896
|
-
|
|
9897
|
-
|
|
9898
|
-
|
|
9899
|
-
|
|
9900
|
-
|
|
9901
|
-
|
|
9902
|
-
|
|
9903
|
-
|
|
9904
|
-
|
|
9905
|
-
|
|
9961
|
+
const validateMode = options.validate;
|
|
9962
|
+
if (validateMode === "ignore") logger.info("Schema validation skipped");
|
|
9963
|
+
else {
|
|
9964
|
+
const schemaIssues = await collectSchemaIssues({
|
|
9965
|
+
directoryPath: storiesDirectoryPath,
|
|
9966
|
+
schemas
|
|
9967
|
+
});
|
|
9968
|
+
if (hasSchemaIssues(schemaIssues)) {
|
|
9969
|
+
const message = formatSchemaIssues(schemaIssues, validateMode);
|
|
9970
|
+
if (validateMode === "strict") {
|
|
9971
|
+
ui.error(message);
|
|
9972
|
+
logger.error(message);
|
|
9973
|
+
const total = Math.max(schemaIssues.total, 1);
|
|
9974
|
+
summary.creationResults.total = total;
|
|
9975
|
+
summary.creationResults.failed = total;
|
|
9976
|
+
process.exitCode = 1;
|
|
9977
|
+
return;
|
|
9978
|
+
}
|
|
9979
|
+
ui.warn(message);
|
|
9980
|
+
ui.br();
|
|
9981
|
+
logger.warn(message);
|
|
9982
|
+
}
|
|
9906
9983
|
}
|
|
9907
9984
|
const warnAboutCustomPlugins = (story) => {
|
|
9908
9985
|
const warned = /* @__PURE__ */ new Set();
|
|
@@ -11945,7 +12022,8 @@ function formatSchemaDiff(result, from, to) {
|
|
|
11945
12022
|
}
|
|
11946
12023
|
//#endregion
|
|
11947
12024
|
//#region src/commands/schema/diff/index.ts
|
|
11948
|
-
|
|
12025
|
+
const EXIT_CODE_SCHEMAS_DIFFER = 1;
|
|
12026
|
+
schemaCommand.command("diff").description("Diff two schemas (space IDs or local entry files) and report what changed").requiredOption("--from <space-id|path>", "Base schema to compare against: a space ID or a path to a schema entry file").requiredOption("--to <space-id|path>", "Target schema: a space ID or a path to a schema entry file").option("--exit-code", "Exit 0 when the schemas match, 1 when they differ, and 2 on error, like git diff --exit-code").addHelpText("after", `
|
|
11949
12027
|
Entities are reported as added, changed, or removed relative to --to.
|
|
11950
12028
|
|
|
11951
12029
|
Use --from <space-id> --to <path> for the comparison \`schema push <path>\` makes
|
|
@@ -11955,7 +12033,9 @@ the per-space group uuids and tag ids are translated to folder paths and tag
|
|
|
11955
12033
|
names before comparing.
|
|
11956
12034
|
|
|
11957
12035
|
"removed" means absent from --to, not that a push would delete it: \`schema push\`
|
|
11958
|
-
leaves remote-only entities alone unless it is given --delete
|
|
12036
|
+
leaves remote-only entities alone unless it is given --delete.
|
|
12037
|
+
|
|
12038
|
+
Without --exit-code, differences exit 0 and failures exit non-zero.`).action(async (options, command) => {
|
|
11959
12039
|
const ui = getUI();
|
|
11960
12040
|
const logger = getLogger();
|
|
11961
12041
|
const { verbose } = command.optsWithGlobals();
|
|
@@ -11990,6 +12070,8 @@ leaves remote-only entities alone unless it is given --delete.`).action(async (o
|
|
|
11990
12070
|
unchanged: diffResult.unchanged,
|
|
11991
12071
|
stale: diffResult.stale
|
|
11992
12072
|
});
|
|
12073
|
+
const hasDrift = diffResult.creates + diffResult.updates + diffResult.stale > 0;
|
|
12074
|
+
if (options.exitCode && hasDrift) process.exitCode = EXIT_CODE_SCHEMAS_DIFFER;
|
|
11993
12075
|
} catch (maybeError) {
|
|
11994
12076
|
handleError(toError(maybeError), verbose);
|
|
11995
12077
|
}
|
|
@@ -12035,8 +12117,8 @@ function folderVarName(name) {
|
|
|
12035
12117
|
* generated `export const`s and schema-object keys never collide. Index-aligned
|
|
12036
12118
|
* to `rawNames`.
|
|
12037
12119
|
*/
|
|
12038
|
-
function resolveVarNames(rawNames, baseVarName) {
|
|
12039
|
-
const used =
|
|
12120
|
+
function resolveVarNames(rawNames, baseVarName, reservedVarNames = []) {
|
|
12121
|
+
const used = new Set(reservedVarNames);
|
|
12040
12122
|
return rawNames.map((raw) => {
|
|
12041
12123
|
const base = baseVarName(raw);
|
|
12042
12124
|
let candidate = base;
|
|
@@ -12075,6 +12157,15 @@ function resolveFileNames(baseNames, dirKeys) {
|
|
|
12075
12157
|
return candidate;
|
|
12076
12158
|
});
|
|
12077
12159
|
}
|
|
12160
|
+
const FALLBACK_FIELD_PLUGIN_FILE_NAME = "field-plugin";
|
|
12161
|
+
/** Returns the file name (without extension) for a field plugin. e.g. `'@acme/MyPicker'` -> `'acme-my-picker'` */
|
|
12162
|
+
function fieldPluginFileName(fieldType) {
|
|
12163
|
+
return toKebabCase(fieldType) || FALLBACK_FIELD_PLUGIN_FILE_NAME;
|
|
12164
|
+
}
|
|
12165
|
+
/** Returns the variable name for a field plugin file name. e.g. `'acme-my-picker'` -> `'acmeMyPickerFieldPlugin'` */
|
|
12166
|
+
function fieldPluginVarName(fileName) {
|
|
12167
|
+
return `${toCamelCaseIdentifier(fileName)}FieldPlugin`;
|
|
12168
|
+
}
|
|
12078
12169
|
/** Returns the file name (without extension) for a component. e.g. `'teaser_list'` -> `'teaser-list'` */
|
|
12079
12170
|
function componentFileName(name) {
|
|
12080
12171
|
return toKebabCase(name);
|
|
@@ -12109,6 +12200,62 @@ function resolveDatasources(datasources) {
|
|
|
12109
12200
|
fileName: fileNames[i]
|
|
12110
12201
|
}));
|
|
12111
12202
|
}
|
|
12203
|
+
const OFFICIAL_FIELD_PLUGIN_VAR_BY_TYPE = new Map(Object.entries(officialFieldPlugins).flatMap(([varName, plugin]) => isFieldPlugin(plugin) && typeof plugin.fieldType === "string" ? [[plugin.fieldType, varName]] : []));
|
|
12204
|
+
/** Collects the field plugins that the `custom` fields across `components` reference. */
|
|
12205
|
+
function collectCustomFieldTypes(components) {
|
|
12206
|
+
const fieldTypes = /* @__PURE__ */ new Set();
|
|
12207
|
+
const fieldsWithoutFieldType = [];
|
|
12208
|
+
for (const component of components) for (const [fieldName, field] of Object.entries(component.schema ?? {})) {
|
|
12209
|
+
if (!isRecord(field) || field.type !== "custom") continue;
|
|
12210
|
+
if (typeof field.field_type === "string" && field.field_type !== "") fieldTypes.add(field.field_type);
|
|
12211
|
+
else fieldsWithoutFieldType.push(`${component.name}.${fieldName}`);
|
|
12212
|
+
}
|
|
12213
|
+
return {
|
|
12214
|
+
fieldTypes: [...fieldTypes].sort(),
|
|
12215
|
+
fieldsWithoutFieldType
|
|
12216
|
+
};
|
|
12217
|
+
}
|
|
12218
|
+
/** Resolves each field type to an official plugin import or a uniquely named placeholder. */
|
|
12219
|
+
function resolveFieldPlugins(fieldTypes) {
|
|
12220
|
+
const fileNames = resolveFileNames(fieldTypes.filter((fieldType) => !OFFICIAL_FIELD_PLUGIN_VAR_BY_TYPE.has(fieldType)).map(fieldPluginFileName));
|
|
12221
|
+
const varNames = resolveVarNames(fileNames, fieldPluginVarName, OFFICIAL_FIELD_PLUGIN_VAR_BY_TYPE.values());
|
|
12222
|
+
let placeholderIndex = 0;
|
|
12223
|
+
return fieldTypes.map((fieldType) => {
|
|
12224
|
+
const officialVarName = OFFICIAL_FIELD_PLUGIN_VAR_BY_TYPE.get(fieldType);
|
|
12225
|
+
if (officialVarName) return {
|
|
12226
|
+
kind: "official",
|
|
12227
|
+
fieldType,
|
|
12228
|
+
varName: officialVarName
|
|
12229
|
+
};
|
|
12230
|
+
const i = placeholderIndex++;
|
|
12231
|
+
return {
|
|
12232
|
+
kind: "placeholder",
|
|
12233
|
+
fieldType,
|
|
12234
|
+
varName: varNames[i],
|
|
12235
|
+
fileName: fileNames[i]
|
|
12236
|
+
};
|
|
12237
|
+
});
|
|
12238
|
+
}
|
|
12239
|
+
/** Generates a placeholder field plugin file whose validator accepts any value. */
|
|
12240
|
+
function generateFieldPluginFile(fieldType, varName) {
|
|
12241
|
+
return [
|
|
12242
|
+
"import { defineFieldPlugin } from '@storyblok/schema';",
|
|
12243
|
+
"",
|
|
12244
|
+
"// Placeholder: accepts any value. Replace `value` with a Standard Schema validator",
|
|
12245
|
+
"// (Zod, Valibot, ArkType, or hand-written) for the value this plugin stores.",
|
|
12246
|
+
`export const ${varName} = defineFieldPlugin({`,
|
|
12247
|
+
` fieldType: ${quoteString(fieldType)},`,
|
|
12248
|
+
` value: {`,
|
|
12249
|
+
` '~standard': {`,
|
|
12250
|
+
` version: 1,`,
|
|
12251
|
+
` vendor: 'storyblok-placeholder',`,
|
|
12252
|
+
` validate: (value: unknown) => ({ value }),`,
|
|
12253
|
+
` },`,
|
|
12254
|
+
` },`,
|
|
12255
|
+
"});",
|
|
12256
|
+
""
|
|
12257
|
+
].join("\n");
|
|
12258
|
+
}
|
|
12112
12259
|
/**
|
|
12113
12260
|
* Resolves remote component groups to unique `folders.ts` variable names, in
|
|
12114
12261
|
* parent-first order (parents are declared, and thus referenceable, before
|
|
@@ -12512,13 +12659,16 @@ function generateDatasourceFile(datasource, varName) {
|
|
|
12512
12659
|
* Generates a `schema.ts` file that combines the schema object, types, and Story
|
|
12513
12660
|
* alias. Blocks are imported from their group subdirectory (via each resolved
|
|
12514
12661
|
* component's `segments`); the schema object exports `{ blocks, datasources,
|
|
12515
|
-
* folders }` — folders are only included when
|
|
12662
|
+
* folders, fieldPlugins }` — folders and field plugins are only included when
|
|
12663
|
+
* the space has them.
|
|
12516
12664
|
*/
|
|
12517
|
-
function generateSchemaFile(components, datasources, folders = []) {
|
|
12665
|
+
function generateSchemaFile(components, datasources, folders = [], fieldPlugins = []) {
|
|
12518
12666
|
const lines = [];
|
|
12519
12667
|
lines.push("import { defineSchema } from '@storyblok/schema';");
|
|
12520
12668
|
lines.push("import type { Schema as InferSchema, Story as InferStory } from '@storyblok/schema';");
|
|
12521
12669
|
lines.push(components.length > 0 ? "import type { BlockContent, MapiStory as InferStoryMapi } from '@storyblok/schema';" : "import type { MapiStory as InferStoryMapi } from '@storyblok/schema';");
|
|
12670
|
+
const officialFieldPluginVars = fieldPlugins.filter((plugin) => plugin.kind === "official").map((plugin) => plugin.varName);
|
|
12671
|
+
if (officialFieldPluginVars.length > 0) lines.push(`import { ${officialFieldPluginVars.join(", ")} } from '@storyblok/schema/field-plugins';`);
|
|
12522
12672
|
lines.push("");
|
|
12523
12673
|
for (const { varName, fileName, segments } of components) {
|
|
12524
12674
|
const subPath = segments.length > 0 ? `${segments.join("/")}/` : "";
|
|
@@ -12526,6 +12676,7 @@ function generateSchemaFile(components, datasources, folders = []) {
|
|
|
12526
12676
|
}
|
|
12527
12677
|
for (const { varName, fileName } of datasources) lines.push(`import { ${varName} } from './datasources/${fileName}';`);
|
|
12528
12678
|
if (folders.length > 0) lines.push(`import { ${folders.map((f) => f.varName).join(", ")} } from './folders';`);
|
|
12679
|
+
for (const plugin of fieldPlugins) if (plugin.kind === "placeholder") lines.push(`import { ${plugin.varName} } from './field-plugins/${plugin.fileName}';`);
|
|
12529
12680
|
lines.push("");
|
|
12530
12681
|
lines.push("export const schema = defineSchema({");
|
|
12531
12682
|
if (components.length > 0) {
|
|
@@ -12543,6 +12694,11 @@ function generateSchemaFile(components, datasources, folders = []) {
|
|
|
12543
12694
|
for (const { varName } of folders) lines.push(` ${varName},`);
|
|
12544
12695
|
lines.push(" },");
|
|
12545
12696
|
}
|
|
12697
|
+
if (fieldPlugins.length > 0) {
|
|
12698
|
+
lines.push(" fieldPlugins: {");
|
|
12699
|
+
for (const { varName } of fieldPlugins) lines.push(` ${varName},`);
|
|
12700
|
+
lines.push(" },");
|
|
12701
|
+
}
|
|
12546
12702
|
lines.push("});");
|
|
12547
12703
|
lines.push("");
|
|
12548
12704
|
lines.push("export type Schema = InferSchema<typeof schema>;");
|
|
@@ -12582,6 +12738,9 @@ async function writeFileWithDirs(filePath, content) {
|
|
|
12582
12738
|
* The directory layout is local organization only — `schema push` does not read
|
|
12583
12739
|
* it back as groups, the `folder` ref is what's authoritative. Ungrouped blocks
|
|
12584
12740
|
* are written at the blocks root with no folder ref.
|
|
12741
|
+
*
|
|
12742
|
+
* Field plugins without an official definition get a placeholder file in
|
|
12743
|
+
* `field-plugins/`, returned as `placeholderFieldPlugins`.
|
|
12585
12744
|
*/
|
|
12586
12745
|
async function writeSchemaFiles(targetPath, components, componentFolders, datasources, internalTags = []) {
|
|
12587
12746
|
const writtenFiles = [];
|
|
@@ -12589,6 +12748,8 @@ async function writeSchemaFiles(targetPath, components, componentFolders, dataso
|
|
|
12589
12748
|
const resolvedComponents = resolveComponents(components, components.map((comp) => comp.component_group_uuid ? groupPathByUuid.get(comp.component_group_uuid) ?? [] : []));
|
|
12590
12749
|
const resolvedDatasources = resolveDatasources(datasources);
|
|
12591
12750
|
const resolvedFolders = resolveFolders(componentFolders);
|
|
12751
|
+
const { fieldTypes, fieldsWithoutFieldType } = collectCustomFieldTypes(components);
|
|
12752
|
+
const resolvedFieldPlugins = resolveFieldPlugins(fieldTypes);
|
|
12592
12753
|
const folderByUuid = new Map(resolvedFolders.map((r) => [r.folder.uuid, r]));
|
|
12593
12754
|
const folderVarByUuid = new Map([...folderByUuid].map(([uuid, r]) => [uuid, r.varName]));
|
|
12594
12755
|
const tagNameById = new Map(internalTags.filter((tag) => tag.id !== void 0).map((tag) => [String(tag.id), tag.name]));
|
|
@@ -12606,15 +12767,30 @@ async function writeSchemaFiles(targetPath, components, componentFolders, dataso
|
|
|
12606
12767
|
await writeFileWithDirs(filePath, generateDatasourceFile(datasource, varName));
|
|
12607
12768
|
writtenFiles.push(filePath);
|
|
12608
12769
|
}
|
|
12770
|
+
const placeholderFieldPlugins = [];
|
|
12771
|
+
for (const plugin of resolvedFieldPlugins) {
|
|
12772
|
+
if (plugin.kind !== "placeholder") continue;
|
|
12773
|
+
const filePath = join(targetPath, "field-plugins", `${plugin.fileName}.ts`);
|
|
12774
|
+
await writeFileWithDirs(filePath, generateFieldPluginFile(plugin.fieldType, plugin.varName));
|
|
12775
|
+
writtenFiles.push(filePath);
|
|
12776
|
+
placeholderFieldPlugins.push({
|
|
12777
|
+
fieldType: plugin.fieldType,
|
|
12778
|
+
filePath
|
|
12779
|
+
});
|
|
12780
|
+
}
|
|
12609
12781
|
if (resolvedFolders.length > 0) {
|
|
12610
12782
|
const foldersPath = join(targetPath, "folders.ts");
|
|
12611
12783
|
await writeFileWithDirs(foldersPath, generateFoldersFile(resolvedFolders));
|
|
12612
12784
|
writtenFiles.push(foldersPath);
|
|
12613
12785
|
}
|
|
12614
12786
|
const schemaPath = join(targetPath, "schema.ts");
|
|
12615
|
-
await writeFileWithDirs(schemaPath, generateSchemaFile(resolvedComponents, resolvedDatasources, resolvedFolders));
|
|
12787
|
+
await writeFileWithDirs(schemaPath, generateSchemaFile(resolvedComponents, resolvedDatasources, resolvedFolders, resolvedFieldPlugins));
|
|
12616
12788
|
writtenFiles.push(schemaPath);
|
|
12617
|
-
return
|
|
12789
|
+
return {
|
|
12790
|
+
writtenFiles,
|
|
12791
|
+
placeholderFieldPlugins,
|
|
12792
|
+
fieldsWithoutFieldType
|
|
12793
|
+
};
|
|
12618
12794
|
}
|
|
12619
12795
|
//#endregion
|
|
12620
12796
|
//#region src/commands/schema/init/index.ts
|
|
@@ -12664,11 +12840,13 @@ schemaCommand.command("init").description("Initialize a local code-driven schema
|
|
|
12664
12840
|
const { rawComponents, rawComponentFolders, rawInternalTags, rawDatasources } = fetchResult;
|
|
12665
12841
|
fetchSpinner.succeed(`Found: ${rawComponents.length} components, ${rawComponentFolders.length} component folders, ${rawDatasources.length} datasources`);
|
|
12666
12842
|
const writeSpinner = ui.createSpinner(`Generating TypeScript files to ${targetDisplayPath}...`);
|
|
12667
|
-
const writtenFiles = await writeSchemaFiles(targetPath, rawComponents, rawComponentFolders, rawDatasources, rawInternalTags);
|
|
12843
|
+
const { writtenFiles, placeholderFieldPlugins, fieldsWithoutFieldType } = await writeSchemaFiles(targetPath, rawComponents, rawComponentFolders, rawDatasources, rawInternalTags);
|
|
12668
12844
|
summary.total = writtenFiles.length;
|
|
12669
12845
|
summary.succeeded = writtenFiles.length;
|
|
12670
12846
|
writeSpinner.succeed(`Generated ${writtenFiles.length} files`);
|
|
12671
12847
|
ui.list(writtenFiles.map((file) => displayPath(file, options.outDir)));
|
|
12848
|
+
if (placeholderFieldPlugins.length > 0) ui.warn(["Generated placeholder field plugins that accept any value. Define the value each one stores:", ...placeholderFieldPlugins.map(({ fieldType, filePath }) => ` - ${fieldType} (${displayPath(filePath, options.outDir)})`)].join("\n"));
|
|
12849
|
+
if (fieldsWithoutFieldType.length > 0) ui.warn(["Skipped custom fields that name no field plugin:", ...fieldsWithoutFieldType.map((field) => ` - ${field}`)].join("\n"));
|
|
12672
12850
|
ui.ok(`Schema workspace initialized from space ${space} in ${chalk.hex(colorPalette.PRIMARY)(targetDisplayPath)}`, true);
|
|
12673
12851
|
ui.br();
|
|
12674
12852
|
ui.info([
|