@wengine-ai/claude-code-router-shared 2.0.41 → 2.3.235

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.
@@ -1,720 +0,0 @@
1
- /**
2
- * Dynamic configuration Schema handler
3
- * Responsible for parsing and validating configuration schema, handling conditional logic and variable replacement
4
- */
5
-
6
- import path from 'path';
7
- import {
8
- RequiredInput,
9
- InputType,
10
- Condition,
11
- DynamicOptions,
12
- InputOption,
13
- ConfigMapping,
14
- TemplateConfig,
15
- PresetConfigSection,
16
- PresetFile,
17
- ManifestFile,
18
- UserInputValues,
19
- } from './types';
20
-
21
- /**
22
- * Parse field path (supports arrays and nesting)
23
- * Example: Providers[0].name => ['Providers', '0', 'name']
24
- */
25
- export function parseFieldPath(path: string): string[] {
26
- const regex = /(\w+)|\[(\d+)\]/g;
27
- const parts: string[] = [];
28
- let match;
29
-
30
- while ((match = regex.exec(path)) !== null) {
31
- parts.push(match[1] || match[2]);
32
- }
33
-
34
- return parts;
35
- }
36
-
37
- /**
38
- * Get value from object by field path
39
- */
40
- export function getValueByPath(obj: any, path: string): any {
41
- const parts = parseFieldPath(path);
42
- let current = obj;
43
-
44
- for (const part of parts) {
45
- if (current == null) {
46
- return undefined;
47
- }
48
- current = current[part];
49
- }
50
-
51
- return current;
52
- }
53
-
54
- /**
55
- * Set value in object by field path
56
- */
57
- export function setValueByPath(obj: any, path: string, value: any): void {
58
- const parts = parseFieldPath(path);
59
- const lastKey = parts.pop()!;
60
- let current = obj;
61
-
62
- for (const part of parts) {
63
- if (!(part in current)) {
64
- // Determine if it's an array or object
65
- const nextPart = parts[parts.indexOf(part) + 1];
66
- if (nextPart && /^\d+$/.test(nextPart)) {
67
- current[part] = [];
68
- } else {
69
- current[part] = {};
70
- }
71
- }
72
- current = current[part];
73
- }
74
-
75
- current[lastKey] = value;
76
- }
77
-
78
- /**
79
- * Evaluate conditional expression
80
- */
81
- export function evaluateCondition(
82
- condition: Condition,
83
- values: UserInputValues
84
- ): boolean {
85
- const actualValue = values[condition.field];
86
-
87
- // Handle exists operator
88
- if (condition.operator === 'exists') {
89
- return actualValue !== undefined && actualValue !== null;
90
- }
91
-
92
- // Handle in operator
93
- if (condition.operator === 'in') {
94
- return Array.isArray(condition.value) && condition.value.includes(actualValue);
95
- }
96
-
97
- // Handle nin operator
98
- if (condition.operator === 'nin') {
99
- return Array.isArray(condition.value) && !condition.value.includes(actualValue);
100
- }
101
-
102
- // Handle other operators
103
- switch (condition.operator) {
104
- case 'eq':
105
- return actualValue === condition.value;
106
- case 'ne':
107
- return actualValue !== condition.value;
108
- case 'gt':
109
- return actualValue > condition.value;
110
- case 'lt':
111
- return actualValue < condition.value;
112
- case 'gte':
113
- return actualValue >= condition.value;
114
- case 'lte':
115
- return actualValue <= condition.value;
116
- default:
117
- // Default to eq
118
- return actualValue === condition.value;
119
- }
120
- }
121
-
122
- /**
123
- * Evaluate multiple conditions (AND logic)
124
- */
125
- export function evaluateConditions(
126
- conditions: Condition | Condition[],
127
- values: UserInputValues
128
- ): boolean {
129
- if (!conditions) {
130
- return true;
131
- }
132
-
133
- if (!Array.isArray(conditions)) {
134
- return evaluateCondition(conditions, values);
135
- }
136
-
137
- // If array, use AND logic (all conditions must be satisfied)
138
- return conditions.every(condition => evaluateCondition(condition, values));
139
- }
140
-
141
- /**
142
- * Determine if field should be displayed
143
- */
144
- export function shouldShowField(
145
- field: RequiredInput,
146
- values: UserInputValues
147
- ): boolean {
148
- if (!field.when) {
149
- return true;
150
- }
151
-
152
- return evaluateConditions(field.when, values);
153
- }
154
-
155
- /**
156
- * Get dynamic options list
157
- */
158
- export function getDynamicOptions(
159
- dynamicOptions: DynamicOptions,
160
- presetConfig: PresetConfigSection,
161
- values: UserInputValues
162
- ): InputOption[] {
163
- switch (dynamicOptions.type) {
164
- case 'static':
165
- return dynamicOptions.options || [];
166
-
167
- case 'providers': {
168
- // Extract options from preset's Providers
169
- const providers = presetConfig.Providers || [];
170
- return providers.map((p: any) => ({
171
- label: p.name || p.id || String(p),
172
- value: p.name || p.id || String(p),
173
- description: p.api_base_url,
174
- }));
175
- }
176
-
177
- case 'models': {
178
- // Extract from specified provider's models
179
- const providerField = dynamicOptions.providerField;
180
- if (!providerField) {
181
- return [];
182
- }
183
-
184
- // Parse provider reference (e.g. #{selectedProvider})
185
- const providerId = String(providerField).replace(/^#{(.+)}$/, '$1');
186
- const selectedProvider = values[providerId];
187
-
188
- if (!selectedProvider || !presetConfig.Providers) {
189
- return [];
190
- }
191
-
192
- // Find corresponding provider
193
- const provider = presetConfig.Providers.find(
194
- (p: any) => p.name === selectedProvider || p.id === selectedProvider
195
- );
196
-
197
- if (!provider || !provider.models) {
198
- return [];
199
- }
200
-
201
- return provider.models.map((model: string) => ({
202
- label: model,
203
- value: model,
204
- }));
205
- }
206
-
207
- case 'custom':
208
- // Reserved, not implemented yet
209
- return [];
210
-
211
- default:
212
- return [];
213
- }
214
- }
215
-
216
- /**
217
- * Resolve options (supports static and dynamic options)
218
- */
219
- export function resolveOptions(
220
- field: RequiredInput,
221
- presetConfig: PresetConfigSection,
222
- values: UserInputValues
223
- ): InputOption[] {
224
- if (!field.options) {
225
- return [];
226
- }
227
-
228
- // Determine if static or dynamic options
229
- const options = field.options as any;
230
-
231
- if (Array.isArray(options)) {
232
- // Static options array
233
- return options as InputOption[];
234
- }
235
-
236
- if (options.type) {
237
- // Dynamic options
238
- return getDynamicOptions(options, presetConfig, values);
239
- }
240
-
241
- return [];
242
- }
243
-
244
- /**
245
- * Template variable replacement
246
- * Supports #{variable} syntax (different from statusline's {{variable}} format)
247
- */
248
- export function replaceTemplateVariables(
249
- template: any,
250
- values: UserInputValues
251
- ): any {
252
- if (template === null || template === undefined) {
253
- return template;
254
- }
255
-
256
- // Handle strings
257
- if (typeof template === 'string') {
258
- return template.replace(/#{(\w+)}/g, (_, key) => {
259
- return values[key] !== undefined ? String(values[key]) : '';
260
- });
261
- }
262
-
263
- // Handle arrays
264
- if (Array.isArray(template)) {
265
- return template.map(item => replaceTemplateVariables(item, values));
266
- }
267
-
268
- // Handle objects
269
- if (typeof template === 'object') {
270
- const result: any = {};
271
- for (const [key, value] of Object.entries(template)) {
272
- result[key] = replaceTemplateVariables(value, values);
273
- }
274
- return result;
275
- }
276
-
277
- // Return other types directly
278
- return template;
279
- }
280
-
281
- /**
282
- * Apply configuration mappings
283
- */
284
- export function applyConfigMappings(
285
- mappings: ConfigMapping[],
286
- values: UserInputValues,
287
- config: PresetConfigSection
288
- ): PresetConfigSection {
289
- const result = { ...config };
290
-
291
- for (const mapping of mappings) {
292
- // Check condition
293
- if (mapping.when && !evaluateConditions(mapping.when, values)) {
294
- continue;
295
- }
296
-
297
- // Resolve value
298
- let value: any;
299
- if (typeof mapping.value === 'string' && mapping.value.startsWith('#')) {
300
- // Variable reference
301
- const varName = mapping.value.replace(/^#{(.+)}$/, '$1');
302
- value = values[varName];
303
- } else {
304
- // Fixed value
305
- value = mapping.value;
306
- }
307
-
308
- // Apply to target path
309
- setValueByPath(result, mapping.target, value);
310
- }
311
-
312
- return result;
313
- }
314
-
315
- /**
316
- * Get all field ids defined in schema
317
- */
318
- function getSchemaFields(schema?: RequiredInput[]): Set<string> {
319
- if (!schema) return new Set();
320
- return new Set(schema.map(field => field.id));
321
- }
322
-
323
- /**
324
- * Apply user inputs to preset configuration
325
- * This is the core function of the preset configuration system, uniformly handling
326
- * configuration application for both CLI and UI layers
327
- *
328
- * @param presetFile Preset file object
329
- * @param values User input values (schema id -> value)
330
- * @returns Applied configuration object
331
- */
332
- export function applyUserInputs(
333
- presetFile: PresetFile,
334
- values: UserInputValues
335
- ): PresetConfigSection {
336
- let config: PresetConfigSection = {};
337
-
338
- // Get field ids defined in schema, for subsequent filtering
339
- const schemaFields = getSchemaFields(presetFile.schema);
340
-
341
- // 1. First apply template (if exists)
342
- // template completely defines configuration structure, using #{variable} placeholders
343
- if (presetFile.template) {
344
- config = replaceTemplateVariables(presetFile.template, values) as any;
345
- } else {
346
- // If no template, start from preset's existing config
347
- // Keep all fields, including schema's id fields (because they may contain placeholders)
348
- // These fields will be updated or replaced in subsequent configMappings
349
- config = presetFile.config ? { ...presetFile.config } : {};
350
-
351
- // Replace placeholders in config (e.g. #{apiKey} -> actual value)
352
- config = replaceTemplateVariables(config, values) as any;
353
-
354
- // Finally, remove schema id fields (they should not appear in final configuration)
355
- for (const schemaField of schemaFields) {
356
- delete config[schemaField];
357
- }
358
- }
359
-
360
- // 2. Then apply configMappings (if exists)
361
- // Map user inputs to specific configuration paths
362
- if (presetFile.configMappings && presetFile.configMappings.length > 0) {
363
- config = applyConfigMappings(presetFile.configMappings, values, config);
364
- }
365
-
366
- // 3. Compatible with legacy: apply to keys containing paths (e.g. "Providers[0].api_key")
367
- for (const [key, value] of Object.entries(values)) {
368
- if (key.includes('.') || key.includes('[')) {
369
- setValueByPath(config, key, value);
370
- }
371
- }
372
-
373
- return config;
374
- }
375
-
376
- /**
377
- * Validate user input
378
- */
379
- export function validateInput(
380
- field: RequiredInput,
381
- value: any
382
- ): { valid: boolean; error?: string } {
383
- // Check required
384
- if (field.required !== false && (value === undefined || value === null || value === '')) {
385
- return {
386
- valid: false,
387
- error: `${field.label || field.id} is required`,
388
- };
389
- }
390
-
391
- // If value is empty and not required, skip validation
392
- if (!value && field.required === false) {
393
- return { valid: true };
394
- }
395
-
396
- // Type check
397
- switch (field.type) {
398
- case InputType.NUMBER:
399
- if (isNaN(Number(value))) {
400
- return {
401
- valid: false,
402
- error: `${field.label || field.id} must be a number`,
403
- };
404
- }
405
- const numValue = Number(value);
406
- if (field.min !== undefined && numValue < field.min) {
407
- return {
408
- valid: false,
409
- error: `${field.label || field.id} must be at least ${field.min}`,
410
- };
411
- }
412
- if (field.max !== undefined && numValue > field.max) {
413
- return {
414
- valid: false,
415
- error: `${field.label || field.id} must be at most ${field.max}`,
416
- };
417
- }
418
- break;
419
-
420
- case InputType.SELECT:
421
- case InputType.MULTISELECT:
422
- // Check if value is in options
423
- // Skip here for now, as options need to be dynamically retrieved
424
- break;
425
- }
426
-
427
- // Custom validator
428
- if (field.validator) {
429
- if (field.validator instanceof RegExp) {
430
- if (!field.validator.test(String(value))) {
431
- return {
432
- valid: false,
433
- error: `${field.label || field.id} format is invalid`,
434
- };
435
- }
436
- } else if (typeof field.validator === 'string') {
437
- const regex = new RegExp(field.validator);
438
- if (!regex.test(String(value))) {
439
- return {
440
- valid: false,
441
- error: `${field.label || field.id} format is invalid`,
442
- };
443
- }
444
- } else if (typeof field.validator === 'function') {
445
- const result = field.validator(value);
446
- if (result === false) {
447
- return {
448
- valid: false,
449
- error: `${field.label || field.id} is invalid`,
450
- };
451
- } else if (typeof result === 'string') {
452
- return {
453
- valid: false,
454
- error: result,
455
- };
456
- }
457
- }
458
- }
459
-
460
- return { valid: true };
461
- }
462
-
463
- /**
464
- * Get field default value
465
- */
466
- export function getDefaultValue(field: RequiredInput): any {
467
- if (field.defaultValue !== undefined) {
468
- return field.defaultValue;
469
- }
470
-
471
- // Return default value based on type
472
- switch (field.type) {
473
- case InputType.CONFIRM:
474
- return false;
475
- case InputType.MULTISELECT:
476
- return [];
477
- case InputType.NUMBER:
478
- return 0;
479
- default:
480
- return '';
481
- }
482
- }
483
-
484
- /**
485
- * Sort fields by dependency
486
- * Ensure dependent fields are arranged first
487
- */
488
- export function sortFieldsByDependencies(
489
- fields: RequiredInput[]
490
- ): RequiredInput[] {
491
- const sorted: RequiredInput[] = [];
492
- const visited = new Set<string>();
493
-
494
- function visit(field: RequiredInput) {
495
- if (visited.has(field.id)) {
496
- return;
497
- }
498
-
499
- visited.add(field.id);
500
-
501
- // First handle dependent fields
502
- const dependencies = field.dependsOn || [];
503
- for (const depId of dependencies) {
504
- const depField = fields.find(f => f.id === depId);
505
- if (depField) {
506
- visit(depField);
507
- }
508
- }
509
-
510
- // Extract dependencies from when conditions
511
- if (field.when) {
512
- const conditions = Array.isArray(field.when) ? field.when : [field.when];
513
- for (const cond of conditions) {
514
- const depField = fields.find(f => f.id === cond.field);
515
- if (depField) {
516
- visit(depField);
517
- }
518
- }
519
- }
520
-
521
- sorted.push(field);
522
- }
523
-
524
- for (const field of fields) {
525
- visit(field);
526
- }
527
-
528
- return sorted;
529
- }
530
-
531
- /**
532
- * Build field dependency graph (for optimizing update order)
533
- */
534
- export function buildDependencyGraph(
535
- fields: RequiredInput[]
536
- ): Map<string, Set<string>> {
537
- const graph = new Map<string, Set<string>>();
538
-
539
- for (const field of fields) {
540
- const deps = new Set<string>();
541
-
542
- // Extract from dependsOn
543
- if (field.dependsOn) {
544
- for (const dep of field.dependsOn) {
545
- deps.add(dep);
546
- }
547
- }
548
-
549
- // Extract dependencies from when conditions
550
- if (field.when) {
551
- const conditions = Array.isArray(field.when) ? field.when : [field.when];
552
- for (const cond of conditions) {
553
- deps.add(cond.field);
554
- }
555
- }
556
-
557
- // Extract dependencies from dynamic options
558
- if (field.options) {
559
- const options = field.options as any;
560
- if (options.type === 'models' && options.providerField) {
561
- const providerId = String(options.providerField).replace(/^#{(.+)}$/, '$1');
562
- deps.add(providerId);
563
- }
564
- }
565
-
566
- graph.set(field.id, deps);
567
- }
568
-
569
- return graph;
570
- }
571
-
572
- /**
573
- * Get affected fields (when a field value changes, which fields need to be recalculated)
574
- */
575
- export function getAffectedFields(
576
- changedFieldId: string,
577
- fields: RequiredInput[]
578
- ): Set<string> {
579
- const affected = new Set<string>();
580
- const graph = buildDependencyGraph(fields);
581
-
582
- // Find all fields that depend on changedFieldId
583
- for (const [fieldId, deps] of graph.entries()) {
584
- if (deps.has(changedFieldId)) {
585
- affected.add(fieldId);
586
- }
587
- }
588
-
589
- return affected;
590
- }
591
-
592
- /**
593
- * Process StatusLine configuration, convert relative scriptPath to absolute path
594
- * @param statusLineConfig StatusLine configuration
595
- * @param presetDir Preset directory path
596
- */
597
- function processStatusLineConfig(statusLineConfig: any, presetDir?: string): any {
598
- if (!statusLineConfig || typeof statusLineConfig !== 'object') {
599
- return statusLineConfig;
600
- }
601
-
602
- const result = { ...statusLineConfig };
603
-
604
- // Process each theme's modules
605
- for (const themeKey of Object.keys(result)) {
606
- const theme = result[themeKey];
607
- if (theme && typeof theme === 'object' && theme.modules) {
608
- const modules = Array.isArray(theme.modules) ? theme.modules : [];
609
- const processedModules = modules.map((module: any) => {
610
- // If module has scriptPath and presetDir is provided, convert to absolute path
611
- if (module.scriptPath && presetDir && !module.scriptPath.startsWith('/')) {
612
- return {
613
- ...module,
614
- scriptPath: path.join(presetDir, module.scriptPath)
615
- };
616
- }
617
- return module;
618
- });
619
- result[themeKey] = {
620
- ...theme,
621
- modules: processedModules
622
- };
623
- }
624
- }
625
-
626
- return result;
627
- }
628
-
629
- /**
630
- * Process transformers configuration, convert relative path to absolute path
631
- * @param transformersConfig Transformers configuration array
632
- * @param presetDir Preset directory path
633
- */
634
- function processTransformersConfig(transformersConfig: any[], presetDir?: string): any[] {
635
- if (!transformersConfig || !Array.isArray(transformersConfig)) {
636
- return transformersConfig;
637
- }
638
-
639
- if (!presetDir) {
640
- return transformersConfig;
641
- }
642
-
643
- return transformersConfig.map((transformer: any) => {
644
- // If transformer has path and it's a relative path, convert to absolute path
645
- if (transformer.path && !transformer.path.startsWith('/')) {
646
- return {
647
- ...transformer,
648
- path: path.join(presetDir, transformer.path)
649
- };
650
- }
651
- return transformer;
652
- });
653
- }
654
-
655
- /**
656
- * Load configuration from Manifest and apply userValues
657
- * Used when reading installed presets, applying user configuration values at runtime
658
- *
659
- * @param manifest Manifest object (contains original configuration and userValues)
660
- * @param presetDir Optional preset directory path (for resolving relative paths like scriptPath)
661
- * @returns Applied configuration object
662
- */
663
- export function loadConfigFromManifest(manifest: ManifestFile, presetDir?: string): PresetConfigSection {
664
- // Convert manifest to PresetFile format
665
- const presetFile: PresetFile = {
666
- metadata: {
667
- name: manifest.name,
668
- version: manifest.version,
669
- description: manifest.description,
670
- author: manifest.author,
671
- homepage: manifest.homepage,
672
- repository: manifest.repository,
673
- license: manifest.license,
674
- keywords: manifest.keywords,
675
- ccrVersion: manifest.ccrVersion,
676
- source: manifest.source,
677
- sourceType: manifest.sourceType,
678
- checksum: manifest.checksum,
679
- },
680
- config: {},
681
- schema: manifest.schema,
682
- template: manifest.template,
683
- configMappings: manifest.configMappings,
684
- };
685
-
686
- // Extract configuration section from manifest (exclude metadata and dynamic configuration fields)
687
- const METADATA_FIELDS = [
688
- 'name', 'version', 'description', 'author', 'homepage', 'repository',
689
- 'license', 'keywords', 'ccrVersion', 'source', 'sourceType', 'checksum',
690
- ];
691
- const DYNAMIC_CONFIG_FIELDS = ['schema', 'template', 'configMappings', 'userValues'];
692
-
693
- for (const [key, value] of Object.entries(manifest)) {
694
- if (!METADATA_FIELDS.includes(key) && !DYNAMIC_CONFIG_FIELDS.includes(key)) {
695
- presetFile.config[key] = value;
696
- }
697
- }
698
-
699
- let config: PresetConfigSection;
700
-
701
- // If userValues exist, apply them
702
- if (manifest.userValues && Object.keys(manifest.userValues).length > 0) {
703
- config = applyUserInputs(presetFile, manifest.userValues);
704
- } else {
705
- // If no userValues, use original configuration directly
706
- config = presetFile.config;
707
- }
708
-
709
- // Process StatusLine configuration (convert relative scriptPath to absolute path)
710
- if (config.StatusLine) {
711
- config.StatusLine = processStatusLineConfig(config.StatusLine, presetDir);
712
- }
713
-
714
- // Process transformers configuration (convert relative path to absolute path)
715
- if (config.transformers) {
716
- config.transformers = processTransformersConfig(config.transformers, presetDir);
717
- }
718
-
719
- return config;
720
- }