@likec4/config 1.57.0 → 1.59.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/index.mjs CHANGED
@@ -1,421 +1 @@
1
- import JSON5 from "json5";
2
- import z from "zod/v4";
3
- import { BorderStyles, ElementShapes, IconPositions, RelationshipArrowTypes, Sizes, ThemeColors, computeColorValues } from "@likec4/core/styles";
4
- import { exact } from "@likec4/core/types";
5
- //#region src/schema.image-alias.ts
6
- const IMAGE_ALIAS_KEY_REGEX = /^@[A-Za-z0-9_-]*$/;
7
- const IMAGE_ALIAS_VALUE_REGEX = /^(?!\/|[A-Za-z]:[\\\/])(?!.*:\/\/).*$/;
8
- const ImageAliasKey = z.string().min(1, "Image alias key cannot be empty").regex(IMAGE_ALIAS_KEY_REGEX, "Image alias key must match /^@\\w+$/");
9
- const ImageAliasValue = z.string().min(1, "Image alias value cannot be empty").regex(IMAGE_ALIAS_VALUE_REGEX, "Image alias value must be a relative path (no leading slash or protocol)");
10
- const ImageAliasesSchema = z.record(ImageAliasKey, ImageAliasValue).meta({
11
- id: "ImageAliases",
12
- description: "Map of image alias prefixes to relative paths (keys must match /^@\\w+$/; values must be relative paths without protocol or leading slash)."
13
- });
14
- //#endregion
15
- //#region src/schema.include.ts
16
- const IncludePathValue = z.string().min(1, "Include path cannot be empty").regex(/^(?!\/|[A-Za-z]:[\\\/])(?!.*:\/\/).*$/, "Include path must be a relative path (no leading slash, drive letter, or protocol)");
17
- const IncludeSchema = z.strictObject({
18
- paths: z.array(IncludePathValue).meta({ description: [
19
- "Additional relative directory paths to include LikeC4 source files from, searched recursively.",
20
- "Paths are relative to the project folder (the folder containing this config file).",
21
- "Example: [\"../shared\", \"../common/specs\"]"
22
- ].join("\n") }),
23
- maxDepth: z.number().int().min(1).max(20).default(3).meta({ description: [
24
- "Maximum directory depth to scan when searching for .c4 files in include paths.",
25
- "Prevents excessive scanning of deeply nested directories.",
26
- "Default: 3"
27
- ].join("\n") }),
28
- fileThreshold: z.number().int().min(1).max(1e4).default(30).meta({ description: [
29
- "Maximum number of files to load from include paths before warning.",
30
- "Helps identify performance issues from accidentally including large directories.",
31
- "Default: 30"
32
- ].join("\n") })
33
- }).meta({
34
- id: "include-config",
35
- description: ["Configuration for including additional LikeC4 source files from other directories.", "Example: { \"paths\": [\"../shared\", \"../common/specs\"], \"maxDepth\": 5, \"fileThreshold\": 50 }"].join("\n")
36
- });
37
- //#endregion
38
- //#region src/schema.theme.ts
39
- const opacity = z.int().min(0, "Opacity must be between 0 and 100").max(100, "Opacity must be between 0 and 100").meta({
40
- id: "Opacity",
41
- description: "Opacity 0-100%"
42
- });
43
- const shape = z.enum(ElementShapes).meta({ id: "ElementShape" });
44
- const border = z.enum(BorderStyles).meta({ id: "BorderStyle" });
45
- const size = z.enum(Sizes).meta({ id: "ElementSize" });
46
- const iconPosition = z.enum(IconPositions).meta({ id: "IconPosition" });
47
- const arrow = z.enum(RelationshipArrowTypes).meta({ id: "ArrowType" });
48
- const line = z.enum([
49
- "dashed",
50
- "solid",
51
- "dotted"
52
- ]).meta({ id: "LineType" });
53
- const themeColor = z.enum(ThemeColors).meta({ id: "ThemeColorName" });
54
- const customColor = z.custom().refine((v) => typeof v === "string", "Custom color name must be a string").transform((value) => value).meta({ id: "CustomColorName" });
55
- const color = themeColor.or(customColor).transform((value) => value).meta({ id: "ColorName" });
56
- const colorSchema = z.string().min(1, "Color value cannot be empty").meta({ id: "ColorLiteral" });
57
- const ElementColorValuesSchema = z.strictObject({
58
- fill: colorSchema.meta({ description: "Background color" }),
59
- stroke: colorSchema.meta({ description: "Stroke color (border, paths above background)" }),
60
- hiContrast: colorSchema.meta({ description: "High contrast text color (title)" }),
61
- loContrast: colorSchema.meta({ description: "Low contrast text color (description)" })
62
- }).meta({ id: "ElementColorValues" }).transform((value) => value);
63
- const RelationshipColorValuesSchema = z.strictObject({
64
- line: colorSchema.meta({ description: "Line color" }),
65
- label: colorSchema.meta({ description: "Label text color" }),
66
- labelBg: colorSchema.optional().default("rgba(0, 0, 0, 0.5)").meta({ description: "Label background color" })
67
- }).meta({ id: "RelationshipColorValues" }).transform((value) => value);
68
- const ThemeColorValuesSchema = z.strictObject({
69
- elements: ElementColorValuesSchema.or(colorSchema.transform((v) => computeColorValues(v).elements)).meta({ description: "Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values" }),
70
- relationships: RelationshipColorValuesSchema.or(colorSchema.transform((v) => computeColorValues(v).relationships)).meta({ description: "Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values" })
71
- }).transform((value) => value).meta({
72
- id: "StrictThemeColorValues",
73
- description: "Exact color value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color value"
74
- }).or(colorSchema.transform((v) => computeColorValues(v))).transform((value) => value).meta({
75
- id: "ThemeColorValues",
76
- description: "Exact value (hex, rgb, rgba, hsl, hsla ...) or break down of specific color values"
77
- });
78
- const ThemeColorsSchema = z.partialRecord(color, ThemeColorValuesSchema).transform((value) => value);
79
- const DimensionsSchema = z.strictObject({
80
- width: z.number().min(50),
81
- height: z.number().min(50)
82
- }).meta({
83
- id: "Dimensions",
84
- description: "Defines dimensions for theme size"
85
- });
86
- const LikeC4Config_Styles_Theme_Sizes = z.partialRecord(size, DimensionsSchema);
87
- const LikeC4Config_Styles_Theme = z.strictObject({
88
- colors: ThemeColorsSchema.optional().meta({ description: "Override theme colors" }),
89
- sizes: LikeC4Config_Styles_Theme_Sizes.optional().meta({ description: "Override theme sizes" })
90
- }).meta({
91
- id: "ThemeCustomization",
92
- description: "Customize theme colors and sizes"
93
- }).transform(({ colors, sizes }) => {
94
- return exact({
95
- colors: colors ? exact(colors) : void 0,
96
- sizes: sizes ? exact(sizes) : void 0
97
- });
98
- });
99
- const LikeC4Config_Styles_Defaults_Group = z.strictObject({
100
- color: color.optional().meta({ description: "Default color for groups\n(must be a valid color name from the theme)" }),
101
- opacity: opacity.optional().meta({ description: "Default opacity for groups" }),
102
- border: border.optional().meta({ description: "Default border for groups" })
103
- }).meta({ id: "GroupDefaultStyleValues" });
104
- const LikeC4Config_Styles_Defaults_Relationship = z.strictObject({
105
- color: color.optional().meta({ description: "Default color for relationships\n(must be a valid color name from the theme)" }),
106
- line: line.optional().meta({ description: "Default line style for relationships" }),
107
- arrow: arrow.optional().meta({ description: "Default arrow style for relationships" })
108
- }).meta({
109
- id: "RelationshipDefaultStyleValues",
110
- description: "Override default values for relationship style properties\nThese values will be used if such property is not defined"
111
- });
112
- const LikeC4Config_Styles_Defaults = z.strictObject({
113
- color: color.optional().meta({ description: "Default color for elements\n(must be a valid color name from the theme)" }),
114
- opacity: opacity.optional().meta({ description: "Default opacity (0-100%) for elements when displayed as a group (like a container)" }),
115
- border: border.optional().meta({ description: "Default border style for elements when displayed as a group (like a container)" }),
116
- size: size.optional().meta({ description: "Default size for elements" }),
117
- shape: shape.optional().meta({ description: "Default shape for elements" }),
118
- iconPosition: iconPosition.optional().meta({ description: "Default icon position for elements" }),
119
- group: LikeC4Config_Styles_Defaults_Group.optional().meta({ description: "Override default values for group style properties\nThese values will be used if such property is not defined" }),
120
- relationship: LikeC4Config_Styles_Defaults_Relationship.optional().meta({ description: "Override default values for relationship style properties\nThese values will be used if such property is not defined" })
121
- }).meta({ id: "DefaultStyleValues" });
122
- const LikeC4Config_Styles_CustomStylesheets = z.union([z.string().min(1, "Custom CSS file path cannot be empty"), z.array(z.string().min(1, "Custom CSS file path cannot be empty"))]).meta({ id: "CustomStylesheets" });
123
- const LikeC4StylesConfigSchema = z.strictObject({
124
- theme: LikeC4Config_Styles_Theme.optional().meta({ description: "Project theme customization" }),
125
- defaults: LikeC4Config_Styles_Defaults.optional().meta({ description: "Override default values for style properties\nThese values will be used if such property is not defined" }),
126
- customCss: LikeC4Config_Styles_CustomStylesheets.optional().meta({ description: "Custom CSS (or list of CSS files) to be included in the generated diagrams" })
127
- }).transform(({ theme, defaults, customCss }) => exact({
128
- defaults: normalizeDefaults(defaults),
129
- customCss: normalizeStylesheets(customCss),
130
- theme
131
- }));
132
- function normalizeDefaults(defaults) {
133
- if (!defaults) return;
134
- const { relationship, group, ...rest } = defaults;
135
- return exact({
136
- ...rest,
137
- relationship: relationship && exact(relationship),
138
- group: group && exact(group)
139
- });
140
- }
141
- function normalizeStylesheets(stylesheets) {
142
- if (!stylesheets) return;
143
- const paths = (Array.isArray(stylesheets) ? stylesheets : [stylesheets]).filter(Boolean);
144
- if (paths.length === 0) return;
145
- return {
146
- paths,
147
- content: ""
148
- };
149
- }
150
- //#endregion
151
- //#region src/schema.ts
152
- const ManualLayoutsConfigSchema = z.strictObject({ outDir: z.string().default(".likec4").meta({ description: [
153
- "Path to the directory where manual layouts will be stored,",
154
- "relative to the folder containing the project config. ",
155
- "",
156
- "Defaults to '.likec4'."
157
- ].join("\n") }) }).meta({
158
- id: "ManualLayoutsConfig",
159
- description: "Configuration for manual layouts"
160
- });
161
- const LandingPageSchema = z.union([
162
- z.strictObject({ redirect: z.literal(true) }),
163
- z.strictObject({ include: z.array(z.string().nonempty().refine((s) => s !== "#", { message: "selector cannot be \"#\"" })).nonempty("include list cannot be empty") }),
164
- z.strictObject({ exclude: z.array(z.string().nonempty().refine((s) => s !== "#", { message: "selector cannot be \"#\"" })).nonempty("exclude list cannot be empty") })
165
- ]).meta({
166
- id: "LandingPageConfig",
167
- description: "Configure the landing page. Use redirect to go to the index view, or include/exclude to filter the view grid."
168
- });
169
- const LikeC4ProjectJsonConfigSchema = z.object({
170
- name: z.string().nonempty("Project name cannot be empty").refine((value) => value !== "default", {
171
- abort: true,
172
- error: "Project name cannot be \"default\""
173
- }).refine((value) => !value.includes(".") && !value.includes("@") && !value.includes("#"), {
174
- abort: true,
175
- error: "Project name cannot contain \".\", \"@\" or \"#\", try to use A-z, 0-9, _ and -"
176
- }).meta({ description: "Project name, must be unique in the workspace" }),
177
- extends: z.union([z.string().min(1, "Extend path cannot be empty"), z.array(z.string().min(1, "Extend path cannot be empty")).min(1, "Extend list cannot be empty")]).optional().meta({ description: "Extend styles from other config files" }),
178
- title: z.string().nonempty("Project title cannot be empty if specified").optional().meta({ description: "A human readable title for the project" }),
179
- contactPerson: z.string().nonempty("Contact person cannot be empty if specified").optional().meta({ description: "A person who has been involved in creating or maintaining this project" }),
180
- metadata: z.record(z.string(), z.any()).optional().meta({ description: "Arbitrary metadata as key-value pairs for custom project information" }),
181
- styles: LikeC4StylesConfigSchema.optional().meta({ description: "Project styles customization" }),
182
- imageAliases: ImageAliasesSchema.optional(),
183
- include: IncludeSchema.optional(),
184
- exclude: z.array(z.string()).optional().meta({ description: "List of file patterns to exclude from the project, default is [\"**/node_modules/**\"]" }),
185
- manualLayouts: ManualLayoutsConfigSchema.optional(),
186
- inferTechnologyFromIcon: z.boolean().optional().meta({ description: [
187
- "Automatically derive element technology from icon name when technology is not set explicitly.",
188
- "Applies to aws:, azure:, gcp:, and tech: icons. Bootstrap icons are excluded.",
189
- "Defaults to true."
190
- ].join("\n") }),
191
- implicitViews: z.boolean().optional().meta({ description: "Auto-generate scoped views for elements without explicit views. Defaults to false." }),
192
- landingPage: LandingPageSchema.optional()
193
- }).meta({
194
- id: "LikeC4ProjectConfig",
195
- description: "LikeC4 Project Configuration"
196
- });
197
- const FunctionType = z.instanceof(Function);
198
- const GeneratorsSchema = z.record(z.string(), FunctionType);
199
- const LikeC4ProjectConfigSchema = LikeC4ProjectJsonConfigSchema.extend({ generators: GeneratorsSchema.optional() });
200
- /**
201
- * Validates Object into a LikeC4ProjectConfig object.
202
- * Zod v4 can strip optional union keys (e.g. landingPage) from parse output;
203
- * we validate landingPage once with LandingPageSchema and merge onto the result.
204
- */
205
- function validateProjectConfig(config) {
206
- const inputLandingPage = config["landingPage"];
207
- let validatedLandingPage = null;
208
- if (inputLandingPage != null) {
209
- const lpResult = LandingPageSchema.safeParse(inputLandingPage);
210
- if (!lpResult.success) throw new Error("Config validation failed:\n" + z.prettifyError(lpResult.error));
211
- validatedLandingPage = lpResult.data;
212
- }
213
- const parsed = LikeC4ProjectJsonConfigSchema.safeParse(config);
214
- if (!parsed.success) throw new Error("Config validation failed:\n" + z.prettifyError(parsed.error));
215
- let data = parsed.data;
216
- if (validatedLandingPage !== null) data = {
217
- ...data,
218
- landingPage: validatedLandingPage
219
- };
220
- const generatorsInput = config["generators"];
221
- if (generatorsInput != null && typeof generatorsInput === "object" && !Array.isArray(generatorsInput)) {
222
- const genParsed = GeneratorsSchema.safeParse(generatorsInput);
223
- if (!genParsed.success) throw new Error("Config validation failed (generators):\n" + z.prettifyError(genParsed.error));
224
- return {
225
- ...data,
226
- generators: genParsed.data
227
- };
228
- }
229
- return data;
230
- }
231
- /**
232
- * Parses JSON string into a LikeC4ProjectConfig object.
233
- * Does not process "extends" - use `loadConfig` function instead
234
- */
235
- function parseProjectConfigJSON(config) {
236
- return validateProjectConfig(JSON5.parse(config.trim() || "{}"));
237
- }
238
- const LikeC4ProjectConfigOps = {
239
- parse: parseProjectConfigJSON,
240
- validate: validateProjectConfig,
241
- normalizeInclude: (include) => {
242
- const parsed = IncludeSchema.safeParse(include);
243
- if (parsed.success) return parsed.data;
244
- return {
245
- paths: [],
246
- maxDepth: 3,
247
- fileThreshold: 30
248
- };
249
- }
250
- };
251
- //#endregion
252
- //#region src/filenames.ts
253
- /** Trim trailing slashes and backslashes (no regex, avoids S5852 ReDoS). */
254
- function trimTrailingSlashes(s) {
255
- let end = s.length;
256
- while (end > 0 && (s[end - 1] === "/" || s[end - 1] === "\\")) end--;
257
- return s.slice(0, end);
258
- }
259
- /** Split by / or \ without regex (avoids S5852 ReDoS). */
260
- function splitPath(s) {
261
- return s.split("/").flatMap((part) => part.split("\\"));
262
- }
263
- /** basename compatible with Node and browser (no node:path for Vite/playground bundle). */
264
- function basename(path) {
265
- const trimmed = trimTrailingSlashes(path);
266
- const segments = splitPath(trimmed);
267
- return segments[segments.length - 1] || trimmed;
268
- }
269
- /** Known LikeC4 JSON config filenames (RC and .json). */
270
- const configJsonFilenames = [
271
- ".likec4rc",
272
- ".likec4.config.json",
273
- "likec4.config.json"
274
- ];
275
- /** Known LikeC4 non-JSON config filenames (JS, MJS, TS, MTS). */
276
- const configNonJsonFilenames = [
277
- "likec4.config.js",
278
- "likec4.config.cjs",
279
- "likec4.config.mjs",
280
- "likec4.config.ts",
281
- "likec4.config.cts",
282
- "likec4.config.mts"
283
- ];
284
- /** All known LikeC4 config filenames (JSON and non-JSON). */
285
- const ConfigFilenames = [...configJsonFilenames, ...configNonJsonFilenames];
286
- /** Returns true if the **basename** of the given path matches a known config filename. */
287
- function isLikeC4JsonConfig(filename) {
288
- return configJsonFilenames.includes(basename(filename));
289
- }
290
- /**
291
- * Returns true if the **basename** of the given path matches a known non-JSON config filename (JS, MJS, TS, MTS).
292
- */
293
- function isLikeC4NonJsonConfig(filename) {
294
- return configNonJsonFilenames.includes(basename(filename));
295
- }
296
- /**
297
- * Returns true if the **basename** of the given path matches a known LikeC4 config file (JSON or non-JSON).
298
- */
299
- function isLikeC4Config(filename) {
300
- return isLikeC4JsonConfig(filename) || isLikeC4NonJsonConfig(filename);
301
- }
302
- //#endregion
303
- //#region src/define-config.ts
304
- /**
305
- * Defines LikeC4 Project, allows custom generators that can be executed using CLI:
306
- *
307
- * `$ likec4 gen <generator-name>`
308
- *
309
- * or VSCode command `LikeC4: Run code generator`
310
- *
311
- * @example
312
- * ```ts
313
- * export default defineConfig({
314
- * name: 'my-project',
315
- * title: 'My Project',
316
- *
317
- * exclude: ['picomatch pattern'],
318
- * generators: {
319
- * '<generator-name>': async ({ likec4model, ctx }) => {
320
- * await ctx.write('my-generator.txt', likec4model.project.id)
321
- * }
322
- * }
323
- * })
324
- * ```
325
- */
326
- function defineConfig(config) {
327
- return LikeC4ProjectConfigSchema.parse(config);
328
- }
329
- /**
330
- * Define reusable custom generators
331
- *
332
- * @example
333
- * ```ts
334
- * // generators.ts
335
- * export default defineGenerators({
336
- * 'my-generator': async ({ likec4model, ctx }) => {
337
- * await ctx.write('my-generator.txt', likec4model.project.id)
338
- * }
339
- * })
340
- *
341
- * // likec4.config.ts
342
- * import generators from './generators'
343
- *
344
- * export default defineConfig({
345
- * name: 'my-project',
346
- * generators,
347
- * })
348
- * ```
349
- */
350
- function defineGenerators(generators) {
351
- return GeneratorsSchema.parse(generators);
352
- }
353
- /**
354
- * Define reusable custom theme color
355
- * @example
356
- * ```ts
357
- * export default defineThemeColor({
358
- * element: {
359
- * fill: 'red'
360
- * }
361
- * })
362
- * ```
363
- */
364
- function defineThemeColor(colors) {
365
- return ThemeColorValuesSchema.parse(colors);
366
- }
367
- /**
368
- * Define reusable custom theme
369
- * @example
370
- * ```ts
371
- * import { defineThemeColor, defineTheme } from 'likec4/config'
372
- *
373
- * export default defineTheme({
374
- * colors: {
375
- * primary: '#FF0000',
376
- * // Or use defineThemeColor
377
- * red: defineThemeColor({
378
- * elements: {
379
- * fill: 'red'
380
- * }
381
- * })
382
- * }
383
- * })
384
- * ```
385
- */
386
- function defineTheme(theme) {
387
- return LikeC4Config_Styles_Theme.parse(theme);
388
- }
389
- /**
390
- * Define reusable custom style
391
- * @example
392
- * ```ts
393
- * import { defineStyle, defineThemeColor } from 'likec4/config'
394
- *
395
- * export default defineStyle({
396
- * theme: {
397
- * colors: {
398
- * red: defineThemeColor({
399
- * elements: {
400
- * fill: 'red'
401
- * }
402
- * })
403
- * }
404
- * },
405
- * defaults: {
406
- * color: 'red',
407
- * opacity: 50,
408
- * border: 'solid',
409
- * size: 'sm',
410
- * relationship: {
411
- * color: 'grey',
412
- * line: 'solid',
413
- * }
414
- * }
415
- * })
416
- */
417
- function defineStyle(styles) {
418
- return LikeC4StylesConfigSchema.parse(styles);
419
- }
420
- //#endregion
421
- export { ConfigFilenames, LikeC4ProjectConfigOps, LikeC4StylesConfigSchema, defineConfig, defineGenerators, defineStyle, defineTheme, defineThemeColor, isLikeC4Config, isLikeC4JsonConfig, isLikeC4NonJsonConfig };
1
+ import{a as e,c as t,i as n,l as r,n as i,o as a,p as o,r as s,s as c,t as l,u}from"./chunks/src.mjs";export{a as ConfigFilenames,u as LikeC4ProjectConfigOps,o as LikeC4StylesConfigSchema,l as defineConfig,i as defineGenerators,s as defineStyle,n as defineTheme,e as defineThemeColor,c as isLikeC4Config,t as isLikeC4JsonConfig,r as isLikeC4NonJsonConfig};