-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmigrate_between_ld_instances.ts
More file actions
1931 lines (1701 loc) · 72.7 KB
/
Copy pathmigrate_between_ld_instances.ts
File metadata and controls
1931 lines (1701 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// deno-lint-ignore-file no-explicit-any
import yargs from "https://deno.land/x/yargs@v17.7.2-deno/deno.ts";
import {
buildPatch,
buildRules,
buildRulesReplace,
consoleLogger,
getJson,
ldAPIPatchRequest,
ldAPIPostRequest,
ldAPIRequest,
rateLimitRequest,
sha256HexUtf8,
type Rule,
checkViewExists,
createView,
type View,
ConflictTracker,
applyConflictPrefix,
// delay
} from "../../utils/utils.ts";
import * as Colors from "https://deno.land/std@0.149.0/fmt/colors.ts";
import { parse as parseYaml } from "https://deno.land/std@0.224.0/yaml/parse.ts";
import { getDestinationApiKey } from "../../utils/api_keys.ts";
interface Arguments {
projKeySource: string;
projKeyDest: string;
assignMaintainerIds: boolean;
migrateSegments: boolean;
conflictPrefix?: string;
targetView?: string;
environments?: string;
envMap?: string;
domain?: string;
config?: string;
dryRun?: boolean;
incremental?: boolean;
since?: string;
}
interface SyncManifestEnv {
version: number;
lastModified?: string;
}
interface SyncManifestFlag {
version: number;
lastModified?: string;
contentHash?: string; // Hash of variations+defaults+env config; LD may not bump version for value-only changes
environments: Record<string, SyncManifestEnv>;
}
interface SyncManifestSegment {
version: number;
lastModified?: number;
}
interface SyncManifest {
lastSyncTimestamp: string;
sourceProject: string;
destProject: string;
flags: Record<string, SyncManifestFlag>;
segments?: Record<string, Record<string, SyncManifestSegment>>; // segments[envKey][segmentKey]
}
interface MigrationConfig {
source: {
projectKey: string;
domain?: string;
};
destination: {
projectKey: string;
domain?: string;
};
options?: {
assignMaintainerIds?: boolean;
migrateSegments?: boolean;
conflictPrefix?: string;
targetView?: string;
environments?: string[];
environmentMapping?: Record<string, string>;
dryRun?: boolean;
incremental?: boolean;
since?: string;
};
}
// ==================== Dry Run Helpers ====================
/**
* Simulates an API POST request in dry-run mode
*/
function simulatePostRequest(resource: string, data: any): Response {
console.log(Colors.gray(` [DRY RUN] Would POST to ${resource}`));
return new Response(JSON.stringify({ success: true, _id: 'dry-run-id' }), {
status: 201,
headers: { 'Content-Type': 'application/json' }
});
}
/**
* Simulates an API PATCH request in dry-run mode
*/
function simulatePatchRequest(resource: string, patches: any[], context?: string): Response {
if (context) {
console.log(Colors.gray(` [DRY RUN] Would PATCH ${resource} for ${context} with ${patches.length} operation(s)`));
} else {
console.log(Colors.gray(` [DRY RUN] Would PATCH ${resource} with ${patches.length} operation(s)`));
}
return new Response(JSON.stringify({ success: true }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
});
}
/**
* Wraps POST requests with dry-run support
*/
async function dryRunAwarePost(
dryRun: boolean,
apiKey: string,
domain: string,
path: string,
body: any,
useBeta = false,
rateLimit: string = 'default'
): Promise<Response> {
if (dryRun) {
return simulatePostRequest(path, body);
}
return await rateLimitRequest(
ldAPIPostRequest(apiKey, domain, path, body, useBeta),
rateLimit
);
}
/**
* Wraps PATCH requests with dry-run support
*/
async function dryRunAwarePatch(
dryRun: boolean,
apiKey: string,
domain: string,
path: string,
patches: any[],
_useBeta = false, // Not currently supported by ldAPIPatchRequest
rateLimit: string = 'default',
context?: string // Optional context for better dry-run logging (e.g., environment name)
): Promise<Response> {
if (dryRun) {
return simulatePatchRequest(path, patches, context);
}
return await rateLimitRequest(
ldAPIPatchRequest(apiKey, domain, path, patches),
rateLimit
);
}
// ==================== Project Helpers ====================
// Add function to check if project exists
async function checkProjectExists(apiKey: string, domain: string, projectKey: string): Promise<boolean> {
const req = ldAPIRequest(apiKey, domain, `projects/${projectKey}`);
const response = await rateLimitRequest(req, 'projects');
return response.status === 200;
}
// Add function to get existing project environments
async function getExistingEnvironments(apiKey: string, domain: string, projectKey: string): Promise<string[]> {
const req = ldAPIRequest(apiKey, domain, `projects/${projectKey}/environments`);
const response = await rateLimitRequest(req, 'environments');
if (response.status === 200) {
const data = await response.json();
return data.items.map((env: any) => env.key);
}
return [];
}
const cliArgs: Arguments = (yargs(Deno.args)
.alias("p", "projKeySource")
.alias("d", "projKeyDest")
.alias("m", "assignMaintainerIds")
.alias("s", "migrateSegments")
.alias("c", "conflictPrefix")
.alias("v", "targetView")
.alias("e", "environments")
.alias("env-map", "envMap")
.alias("domain", "domain")
.alias("f", "config")
.alias("dry-run", "dryRun")
.alias("i", "incremental")
.alias("since", "since")
.boolean("m")
.boolean("s")
.boolean("dry-run")
.boolean("incremental")
.default("m", false)
.default("s", true)
.describe("c", "Prefix to use when resolving key conflicts (e.g., 'imported-')")
.describe("v", "View key to link all migrated flags to")
.describe("e", "Comma-separated list of environment keys to migrate (e.g., 'production,staging')")
.describe("env-map", "Environment mapping in format 'source1:dest1,source2:dest2' (e.g., 'prod:production,dev:development')")
.describe("domain", "Destination LaunchDarkly domain (default: app.launchdarkly.com)")
.describe("f", "Path to YAML config file. CLI arguments override config file values.")
.describe("dry-run", "Preview migration without making any changes")
.describe("incremental", "Skip flags unchanged since last sync (version-based)")
.describe("since", "Only sync flags modified after this date (ISO 8601, e.g. 2026-01-15)")
.parse() as unknown) as Arguments;
// Load and merge config file if provided
let inputArgs = cliArgs;
if (cliArgs.config) {
console.log(Colors.cyan(`Loading configuration from: ${cliArgs.config}`));
try {
const configContent = await Deno.readTextFile(cliArgs.config);
const config = parseYaml(configContent) as MigrationConfig;
// Merge config file with CLI args (CLI args take precedence)
inputArgs = {
projKeySource: cliArgs.projKeySource || config.source.projectKey,
projKeyDest: cliArgs.projKeyDest || config.destination.projectKey,
assignMaintainerIds: cliArgs.assignMaintainerIds !== undefined && cliArgs.assignMaintainerIds !== false
? cliArgs.assignMaintainerIds
: config.options?.assignMaintainerIds ?? false,
migrateSegments: cliArgs.migrateSegments !== undefined && cliArgs.migrateSegments !== true
? cliArgs.migrateSegments
: config.options?.migrateSegments ?? true,
conflictPrefix: cliArgs.conflictPrefix || config.options?.conflictPrefix,
targetView: cliArgs.targetView || config.options?.targetView,
environments: cliArgs.environments || config.options?.environments?.join(','),
envMap: cliArgs.envMap || (config.options?.environmentMapping
? Object.entries(config.options.environmentMapping).map(([k, v]) => `${k}:${v}`).join(',')
: undefined),
domain: cliArgs.domain || config.destination?.domain,
dryRun: cliArgs.dryRun ?? config.options?.dryRun ?? false,
incremental: cliArgs.incremental ?? config.options?.incremental ?? false,
since: cliArgs.since || config.options?.since,
config: cliArgs.config
};
console.log(Colors.green(`✓ Configuration loaded successfully\n`));
} catch (error) {
console.log(Colors.red(`Error loading config file: ${error instanceof Error ? error.message : String(error)}`));
Deno.exit(1);
}
}
console.log(Colors.blue("\n=== Migration Script Starting ==="));
console.log(Colors.gray(`Source Project: ${cliArgs.projKeySource || '(from config)'}`));
console.log(Colors.gray(`Destination Project: ${cliArgs.projKeyDest || '(from config)'}`));
// Validate required arguments
if (!inputArgs.projKeySource || !inputArgs.projKeyDest) {
console.log(Colors.red(`Error: Both source project (-p) and destination project (-d) are required.`));
console.log(Colors.yellow(`Provide them via CLI arguments or config file.`));
Deno.exit(1);
}
console.log(Colors.blue("\n📋 Configuration Summary:"));
console.log(Colors.gray(` Source: ${inputArgs.projKeySource}`));
console.log(Colors.gray(` Destination: ${inputArgs.projKeyDest}`));
console.log(Colors.gray(` Assign Maintainers: ${inputArgs.assignMaintainerIds}`));
console.log(Colors.gray(` Migrate Segments: ${inputArgs.migrateSegments}`));
console.log(Colors.gray(` Conflict Prefix: ${inputArgs.conflictPrefix || 'none'}`));
console.log(Colors.gray(` Target View: ${inputArgs.targetView || 'none'}`));
console.log(Colors.gray(` Environments: ${inputArgs.environments || 'all'}`));
console.log(Colors.gray(` Env Mapping: ${inputArgs.envMap || 'none'}`));
console.log(Colors.gray(` Domain: ${inputArgs.domain || 'app.launchdarkly.com'}`));
console.log(Colors.gray(` Dry Run: ${inputArgs.dryRun || false}`));
console.log(Colors.gray(` Incremental: ${inputArgs.incremental || false}`));
console.log(Colors.gray(` Since: ${inputArgs.since || 'none'}`));
// Validate --incremental and --since are mutually exclusive
if (inputArgs.incremental && inputArgs.since) {
console.log(Colors.red(`Error: --incremental and --since are mutually exclusive. Use one or the other.`));
Deno.exit(1);
}
if (inputArgs.dryRun) {
console.log(Colors.yellow("\n⚠️ DRY RUN MODE - No changes will be made"));
console.log(Colors.yellow("All API write operations will be simulated\n"));
}
// Get destination API key
console.log(Colors.blue("\n🔑 Loading API key from config..."));
const apiKey = await getDestinationApiKey();
console.log(Colors.green("✓ API key loaded"));
const domain = inputArgs.domain || "app.launchdarkly.com";
console.log(Colors.gray(`Using domain: ${domain}\n`));
// Get current authenticated member ID for approval request fallback
let currentMemberId: string | null = null;
try {
const memberReq = ldAPIRequest(apiKey, domain, "members/me");
const memberResp = await rateLimitRequest(memberReq, 'members');
if (memberResp.status === 200) {
const memberData = await memberResp.json();
currentMemberId = memberData._id;
console.log(Colors.gray(`Authenticated as member: ${memberData.email || currentMemberId}`));
} else {
console.log(Colors.gray(`Authenticated with service token (approval requests may not notify anyone)`));
}
} catch (error) {
console.log(Colors.gray(`Could not determine authenticated user type`));
}
// Parse environment mapping
const envMapping: Record<string, string> = {};
const reverseEnvMapping: Record<string, string> = {};
if (inputArgs.envMap) {
const mappings = inputArgs.envMap.split(',').map(m => m.trim());
for (const mapping of mappings) {
const [source, dest] = mapping.split(':').map(s => s.trim());
if (!source || !dest) {
console.log(Colors.red(`Error: Invalid environment mapping format: "${mapping}"`));
console.log(Colors.red(`Expected format: "source:dest" (e.g., "prod:production")`));
Deno.exit(1);
}
envMapping[source] = dest;
reverseEnvMapping[dest] = source;
}
console.log(Colors.cyan(`\n=== Environment Mapping ===`));
console.log("Source → Destination:");
Object.entries(envMapping).forEach(([src, dst]) => {
console.log(` ${src} → ${dst}`);
});
console.log();
}
// Initialize conflict tracker
const conflictTracker = new ConflictTracker();
if (inputArgs.conflictPrefix) {
console.log(Colors.cyan(`Conflict prefix enabled: "${inputArgs.conflictPrefix}"`));
console.log(Colors.cyan(`Resources with conflicting keys will be created with this prefix.`));
}
// Load maintainer mapping if needed
console.log(Colors.blue("👥 Loading maintainer mapping..."));
let maintainerMapping: Record<string, string | null> = {};
if (inputArgs.assignMaintainerIds) {
try {
maintainerMapping = await getJson("./data/launchdarkly-migrations/mappings/maintainer_mapping.json") || {};
console.log(Colors.green(`✓ Loaded maintainer mapping with ${Object.keys(maintainerMapping).length} entries`));
} catch (error) {
console.log(Colors.yellow(`⚠ Warning: Could not load maintainer mapping file: ${error}`));
console.log(Colors.yellow(` Continuing without maintainer mapping...`));
}
} else {
console.log(Colors.gray(" Maintainer mapping disabled"));
}
// Project Data //
console.log(Colors.blue(`\n📦 Loading source project data from: ${inputArgs.projKeySource}...`));
const projectJson = await getJson(
`./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/project.json`,
);
if (!projectJson) {
console.log(Colors.red(`❌ Error: Could not load project data from ./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/project.json`));
console.log(Colors.yellow(`Make sure you've run the extract-source step first!`));
Deno.exit(1);
}
console.log(Colors.green(`✓ Project data loaded`));
const buildEnv: Array<any> = [];
projectJson.environments.items.forEach((env: any) => {
const newEnv: any = {
name: env.name,
key: env.key,
color: env.color,
};
if (env.defaultTtl) newEnv.defaultTtl = env.defaultTtl;
if (env.confirmChanges) newEnv.confirmChanges = env.confirmChanges;
if (env.secureMode) newEnv.secureMode = env.secureMode;
if (env.defaultTrackEvents) newEnv.defaultTrackEvents = env.defaultTrackEvents;
if (env.tags) newEnv.tags = env.tags;
buildEnv.push(newEnv);
});
let envkeys: Array<string> = buildEnv.map((env: any) => env.key);
// Filter environments if specified
if (inputArgs.environments) {
const requestedEnvs = inputArgs.environments.split(',').map(e => e.trim());
const originalEnvCount = envkeys.length;
envkeys = envkeys.filter(key => requestedEnvs.includes(key));
console.log(Colors.cyan(`\n=== Environment Filtering ===`));
console.log(`Requested environments: ${requestedEnvs.join(', ')}`);
console.log(`Matched environments: ${envkeys.join(', ')}`);
const notFound = requestedEnvs.filter(e => !envkeys.includes(e));
if (notFound.length > 0) {
console.log(Colors.yellow(`Warning: Requested environments not found in source: ${notFound.join(', ')}`));
}
if (envkeys.length === 0) {
console.log(Colors.red(`Error: None of the requested environments exist in source project.`));
console.log(Colors.red(`Available environments: ${buildEnv.map((e: any) => e.key).join(', ')}`));
Deno.exit(1);
}
console.log(`Migrating ${envkeys.length} of ${originalEnvCount} environments\n`);
}
// Apply environment mapping if specified
// If mapping is provided, filter to only mapped source environments
if (inputArgs.envMap) {
const mappedSourceEnvs = Object.keys(envMapping);
const originalEnvCount = envkeys.length;
envkeys = envkeys.filter(key => mappedSourceEnvs.includes(key));
if (envkeys.length === 0) {
console.log(Colors.red(`Error: None of the mapped source environments exist in the source project.`));
console.log(Colors.red(`Mapped source environments: ${mappedSourceEnvs.join(', ')}`));
console.log(Colors.red(`Available source environments: ${buildEnv.map((e: any) => e.key).join(', ')}`));
Deno.exit(1);
}
console.log(Colors.cyan(`Migrating ${envkeys.length} mapped environment(s)\n`));
}
// Destination project must already exist; we do not create projects.
const targetProjectExists = await checkProjectExists(apiKey, domain, inputArgs.projKeyDest);
if (!targetProjectExists) {
console.log(Colors.red(`\n❌ Destination project "${inputArgs.projKeyDest}" does not exist.`));
console.log(Colors.yellow(` Create the project in LaunchDarkly first, then run migration again.`));
Deno.exit(1);
}
// Get existing environments
console.log(Colors.blue(` Fetching existing environments for ${inputArgs.projKeyDest}...`));
const existingEnvs = await getExistingEnvironments(apiKey, domain, inputArgs.projKeyDest);
console.log(Colors.gray(` Found existing environments: ${existingEnvs.join(', ')}`));
// If environment mapping is enabled, check destination environments exist
if (inputArgs.envMap) {
const mappedDestEnvs = envkeys.map(srcKey => envMapping[srcKey]);
const missingDestEnvs = mappedDestEnvs.filter(destKey => !existingEnvs.includes(destKey));
if (missingDestEnvs.length > 0) {
console.log(Colors.red(`Error: The following mapped destination environments don't exist in target project:`));
missingDestEnvs.forEach(destKey => {
const srcKey = reverseEnvMapping[destKey];
console.log(Colors.red(` ${srcKey} → ${destKey} (destination "${destKey}" not found)`));
});
console.log(Colors.red(`Available destination environments: ${existingEnvs.join(', ')}`));
Deno.exit(1);
}
} else {
// Keep SOURCE env keys; only include those that exist in the target project.
// (We must use source keys so that flag.environments[env] matches extracted flag data.)
const missingEnvs = envkeys.filter(key => !existingEnvs.includes(key));
if (missingEnvs.length > 0) {
console.log(Colors.yellow(`Warning: The following environments from source project don't exist in target project: ${missingEnvs.join(', ')}`));
console.log(Colors.yellow('Skipping these environments...'));
}
envkeys = envkeys.filter(key => existingEnvs.includes(key));
if (envkeys.length > 0) {
console.log(Colors.cyan(`Migrating ${envkeys.length} environment(s) that exist in both projects\n`));
}
}
// View Management //
console.log(Colors.cyan("\n=== View Management ==="));
const allViewKeys = new Set<string>();
// Extract views from flags
console.log(Colors.blue("\n📋 Loading flag list..."));
const flagList: Array<string> = await getJson(
`./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/flags.json`,
);
if (!flagList) {
console.log(Colors.red(`❌ Error: Could not load flag list from ./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/flags.json`));
Deno.exit(1);
}
console.log(Colors.green(`✓ Loaded ${flagList.length} flags`));
console.log("Extracting view associations from source flags...");
const flagsDir = `./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/flags`;
for (const flagkey of flagList) {
const d = await sha256HexUtf8(flagkey);
const flag = await getJson(`${flagsDir}/${flagkey}-${d}.json`) ?? await getJson(`${flagsDir}/${flagkey}.json`);
if (flag && flag.viewKeys && Array.isArray(flag.viewKeys)) {
flag.viewKeys.forEach((viewKey: string) => allViewKeys.add(viewKey));
}
}
// Add target view if specified
if (inputArgs.targetView) {
allViewKeys.add(inputArgs.targetView);
console.log(Colors.cyan(`Target view specified: "${inputArgs.targetView}"`));
}
if (allViewKeys.size > 0) {
console.log(`Found ${allViewKeys.size} unique view(s) to create/verify: ${Array.from(allViewKeys).join(', ')}`);
// Create views in destination project
for (const viewKey of allViewKeys) {
console.log(`Checking/creating view: ${viewKey}`);
const viewExists = await checkViewExists(apiKey, domain, inputArgs.projKeyDest, viewKey);
if (viewExists) {
console.log(Colors.green(` ✓ View "${viewKey}" already exists`));
} else {
console.log(` Creating view "${viewKey}"...`);
const viewData: View = {
key: viewKey,
name: viewKey,
description: `Migrated from project ${inputArgs.projKeySource}`,
};
const result = await createView(apiKey, domain, inputArgs.projKeyDest, viewData);
if (result.success) {
console.log(Colors.green(` ✓ View "${viewKey}" created successfully`));
} else {
console.log(Colors.yellow(` ⚠ Failed to create view "${viewKey}": ${result.error}`));
}
}
}
} else {
console.log("No views found in source flags.");
}
// ==================== Incremental Sync ====================
/** Hash of migratable flag content; LD may not bump version for variation value changes */
async function flagContentHash(flag: any, envKeys: string[]): Promise<string> {
const stripIds = (v: any[]) => (v || []).map(({ _id, ...rest }: any) => rest);
const stripRuleIds = (r: any) => ({ ...r, clauses: (r.clauses || []).map(({ _id, ...c }: any) => c) });
const envs: Record<string, unknown> = {};
for (const k of envKeys) {
const e = flag.environments?.[k];
if (e) envs[k] = { offVariation: e.offVariation, fallthrough: e.fallthrough, rules: (e.rules || []).map(stripRuleIds) };
}
const payload = { variations: stripIds(flag.variations || []), defaults: flag.defaults, envs };
return sha256HexUtf8(JSON.stringify(payload));
}
const syncManifestPath = `./data/launchdarkly-migrations/sync-manifest-${inputArgs.projKeySource}-${inputArgs.projKeyDest}.json`;
let previousManifest: SyncManifest | null = null;
const updatedManifestFlags: Record<string, SyncManifestFlag> = {};
const updatedManifestSegments: Record<string, Record<string, SyncManifestSegment>> = {};
let incrementalSkipCount = 0;
let incrementalEnvSkipCount = 0;
let incrementalSegmentSkipCount = 0;
// Always try to load previous manifest for tracking; only use it for skipping when --incremental
try {
previousManifest = await getJson(syncManifestPath) as SyncManifest | null;
} catch {
// No manifest yet
}
if (inputArgs.incremental) {
if (previousManifest) {
const flagCount = Object.keys(previousManifest.flags).length;
const segCount = previousManifest.segments
? Object.values(previousManifest.segments).reduce((sum, envSegs) => sum + Object.keys(envSegs).length, 0)
: 0;
const segPart = segCount > 0 ? `, ${segCount} segments` : '';
console.log(Colors.cyan(`\n📋 Incremental sync: loaded manifest from ${previousManifest.lastSyncTimestamp} (${flagCount} flags${segPart} tracked)`));
} else {
console.log(Colors.cyan(`\n📋 Incremental sync: no previous manifest found, will sync all flags`));
}
}
// Migrate segments if enabled
console.log(Colors.blue("\n🔷 Starting segment migration..."));
if (inputArgs.migrateSegments) {
console.log(Colors.green(" Segment migration enabled"));
// Filter environments to only those selected
const envsToMigrate = projectJson.environments.items.filter((env: any) => envkeys.includes(env.key));
console.log(Colors.gray(` Processing ${envsToMigrate.length} environment(s) for segments`));
for (const env of envsToMigrate) {
const segmentData = await getJson(
`./data/launchdarkly-migrations/source/project/${inputArgs.projKeySource}/segments/${env.key}.json`,
);
// Skip if no segment data exists for this environment
if (!segmentData || !segmentData.items) {
console.log(Colors.yellow(` ⚠ No segment data found for environment: ${env.key}, skipping...`));
continue;
}
// Determine destination environment key (mapped or original)
const destEnvKey = inputArgs.envMap && envMapping[env.key] ? envMapping[env.key] : env.key;
// We are ignoring big segments/synced segments for now
for (const segment of segmentData.items) {
if (segment.unbounded == true) {
console.log(Colors.yellow(
`Segment: ${segment.key} in Environment ${env.key} is a big segment (unbounded), skipping`,
));
console.log(Colors.gray(
` → Unbounded = synced from an external store or very large list; this migration does not copy big segments. Recreate or reconnect in the destination if needed.`,
));
continue;
}
// Incremental sync: skip segments that haven't changed since last sync
if (inputArgs.incremental && previousManifest) {
const prevSegment = previousManifest.segments?.[env.key]?.[segment.key];
if (prevSegment && segment.version !== undefined && prevSegment.version === segment.version) {
console.log(Colors.gray(` ✓ ${segment.key}: unchanged (v${segment.version}), skipping`));
incrementalSegmentSkipCount++;
// Carry forward previous manifest entry
if (!updatedManifestSegments[env.key]) updatedManifestSegments[env.key] = {};
updatedManifestSegments[env.key][segment.key] = prevSegment;
continue;
}
}
let segmentKey = segment.key;
let segmentName = segment.name;
let attemptCount = 0;
let segmentCreated = false;
while (!segmentCreated && attemptCount < 2) {
attemptCount++;
const newSegment: any = {
name: segmentName,
key: segmentKey,
};
if (segment.tags) newSegment.tags = segment.tags;
if (segment.description) newSegment.description = segment.description;
const segmentResp = await dryRunAwarePost(
inputArgs.dryRun || false,
apiKey,
domain,
`segments/${inputArgs.projKeyDest}/${destEnvKey}`,
newSegment,
false,
'segments'
);
const segmentStatus = await segmentResp.status;
if (segmentStatus === 201 || segmentStatus === 200) {
segmentCreated = true;
console.log(Colors.green(` ✓ Segment ${newSegment.key} created (status: ${segmentStatus})`));
} else if (segmentStatus === 409) {
// Segment already exists
if (inputArgs.conflictPrefix && attemptCount === 1) {
// Conflict detected with prefix enabled, retry with prefix
console.log(Colors.yellow(` ⚠ Segment "${segmentKey}" already exists, retrying with prefix...`));
segmentKey = applyConflictPrefix(segment.key, inputArgs.conflictPrefix);
segmentName = `${inputArgs.conflictPrefix}${segment.name}`;
conflictTracker.addResolution({
originalKey: segment.key,
resolvedKey: segmentKey,
resourceType: 'segment',
conflictPrefix: inputArgs.conflictPrefix
});
} else {
// No prefix or second attempt - segment exists, proceed to update it
segmentCreated = true;
console.log(Colors.yellow(` ⚠ Segment "${segmentKey}" already exists, will update rules...`));
break; // Exit retry loop and proceed to patching
}
} else {
console.log(Colors.red(` ✗ Error creating segment ${newSegment.key} (status: ${segmentStatus})`));
if (segmentStatus > 201) {
console.log(Colors.gray(` Payload: ${JSON.stringify(newSegment)}`));
}
break; // Exit loop on non-conflict errors
}
}
// Build Segment Patches - use the possibly updated segmentKey
if (segmentCreated) {
const sgmtPatches = [];
// Legacy user targeting (single context kind) — use replace for idempotency
if (segment.included?.length > 0) {
sgmtPatches.push(buildPatch("included", "replace", segment.included));
}
if (segment.excluded?.length > 0) {
sgmtPatches.push(buildPatch("excluded", "replace", segment.excluded));
}
// Multi-context targeting — use replace for the whole array for idempotency
if (segment.includedContexts?.length > 0) {
sgmtPatches.push(buildPatch("includedContexts", "replace", segment.includedContexts));
console.log(Colors.gray(` Replacing ${segment.includedContexts.length} includedContexts entries`));
}
if (segment.excludedContexts?.length > 0) {
sgmtPatches.push(buildPatch("excludedContexts", "replace", segment.excludedContexts));
console.log(Colors.gray(` Replacing ${segment.excludedContexts.length} excludedContexts entries`));
}
if (segment.rules?.length > 0) {
console.log(`Copying Segment: ${segmentKey} rules`);
sgmtPatches.push(buildRulesReplace(segment.rules));
}
const patchRules = await dryRunAwarePatch(
inputArgs.dryRun || false,
apiKey,
domain,
`segments/${inputArgs.projKeyDest}/${destEnvKey}/${segmentKey}`,
sgmtPatches,
false,
'segments',
`environment: ${destEnvKey}` // Pass environment context for better dry-run logging
);
const segPatchStatus = patchRules.statusText;
consoleLogger(
patchRules.status,
`Patching segment ${segmentKey} status: ${segPatchStatus}`,
);
}
// Track segment version for sync manifest only if it was actually created/patched
if (segmentCreated) {
if (!updatedManifestSegments[env.key]) updatedManifestSegments[env.key] = {};
updatedManifestSegments[env.key][segment.key] = {
version: segment.version ?? 0,
lastModified: segment.lastModifiedDate,
};
}
};
};
} else {
console.log(Colors.gray(" Segment migration disabled, skipping..."));
}
// ==================== Semantic Patch Conversion ====================
// Converts JSON Patch operations to LaunchDarkly's Semantic Patch format
type VariationIdMapper = (index: number) => string | undefined;
type SemanticInstruction = Record<string, any>;
type ConversionResult = { instructions: SemanticInstruction[], skippedFields: string[] };
/**
* Creates a variation ID mapper from flag variations
*/
const createVariationMapper = (variations: any[]): VariationIdMapper =>
(index: number) => variations[index]?._id;
/**
* Extracts the environment field name from a JSON Patch path
*/
const extractFieldFromPath = (path: string): string | null => {
const pathParts = path.split('/');
const envIndex = pathParts.indexOf('environments');
return envIndex !== -1 ? pathParts[envIndex + 2] : null;
};
/**
* Converts rollout variations from indices to UUIDs
*/
const convertRolloutVariations = (rollout: any, getVariationId: VariationIdMapper) => ({
...rollout,
variations: rollout.variations?.map((v: any) => ({
...v,
variation: getVariationId(v.variation) || v.variation
}))
});
/**
* Converts a flag on/off patch to semantic instruction
*/
const convertOnOffInstruction = (value: boolean): SemanticInstruction => ({
kind: value ? 'turnFlagOn' : 'turnFlagOff'
});
/**
* Converts an off variation patch to semantic instruction
*/
const convertOffVariationInstruction = (
value: number,
getVariationId: VariationIdMapper
): SemanticInstruction | null => {
const variationId = getVariationId(value);
return variationId ? { kind: 'updateOffVariation', variationId } : null;
};
/**
* Converts a fallthrough patch to semantic instruction
*/
const convertFallthroughInstruction = (
value: any,
getVariationId: VariationIdMapper
): SemanticInstruction | null => {
const instruction: SemanticInstruction = {
kind: 'updateFallthroughVariationOrRollout'
};
if (value.variation !== undefined) {
const variationId = getVariationId(value.variation);
if (variationId) {
instruction.variationId = variationId;
}
} else if (value.rollout) {
instruction.rollout = convertRolloutVariations(value.rollout, getVariationId);
}
return (instruction.variationId || instruction.rollout) ? instruction : null;
};
/**
* Converts a rule patch to semantic instruction
*/
const convertRuleInstruction = (
patch: any,
getVariationId: VariationIdMapper
): SemanticInstruction | null => {
if (patch.op !== 'add' || !patch.path.includes('rules/-')) {
return null;
}
const instruction: SemanticInstruction = {
kind: 'addRule',
clauses: patch.value.clauses || [],
...(patch.value.description && { description: patch.value.description })
};
if (patch.value.variation !== undefined) {
const variationId = getVariationId(patch.value.variation);
if (variationId) {
instruction.variationId = variationId;
}
} else if (patch.value.rollout) {
instruction.rollout = convertRolloutVariations(patch.value.rollout, getVariationId);
}
return instruction;
};
/**
* Converts a single JSON Patch to a semantic instruction
*/
const convertPatchToSemanticInstruction = (
patch: any,
getVariationId: VariationIdMapper
): { instruction: SemanticInstruction | null, shouldSkip: boolean, multipleInstructions?: SemanticInstruction[] } => {
const field = extractFieldFromPath(patch.path);
if (!field) return { instruction: null, shouldSkip: false };
switch (field) {
case 'on':
return { instruction: convertOnOffInstruction(patch.value), shouldSkip: false };
case 'offVariation':
return { instruction: convertOffVariationInstruction(patch.value, getVariationId), shouldSkip: false };
case 'fallthrough':
return { instruction: convertFallthroughInstruction(patch.value, getVariationId), shouldSkip: false };
case 'rules':
// Handle replace op on entire rules array
if (patch.op === 'replace' && Array.isArray(patch.value)) {
// NOTE: The LD semantic patch API has no "removeAllRules" instruction.
// For approval-required envs, old rules won't be auto-removed.
if (patch.value.length > 0) {
console.log(Colors.yellow(`\t ⚠ Approval workflow: converting rules replace to addRule instructions (existing rules cannot be removed via semantic patch)`));
}
const instructions = patch.value.map((rule: any) => {
const inst: SemanticInstruction = { kind: 'addRule', clauses: rule.clauses || [] };
if (rule.description) inst.description = rule.description;
if (rule.variation !== undefined) {
const vid = getVariationId(rule.variation);
if (vid) inst.variationId = vid;
} else if (rule.rollout) {
inst.rollout = convertRolloutVariations(rule.rollout, getVariationId);
}
return inst;
});
return { instruction: null, shouldSkip: false, multipleInstructions: instructions };
}
return { instruction: convertRuleInstruction(patch, getVariationId), shouldSkip: false };
case 'trackEvents':
return { instruction: null, shouldSkip: true };
default:
return { instruction: null, shouldSkip: true };
}
};
/**
* Convert JSON Patch format to Semantic Patch format for approval requests
*/
const convertToSemanticPatch = (
jsonPatches: any[],
envKey: string,
variations: any[]
): ConversionResult => {
const getVariationId = createVariationMapper(variations);
const skippedFields = new Set<string>();
const instructions = jsonPatches.reduce<SemanticInstruction[]>((acc, patch) => {
const { instruction, shouldSkip, multipleInstructions } = convertPatchToSemanticInstruction(patch, getVariationId);
if (shouldSkip) {
const field = extractFieldFromPath(patch.path);
if (field) skippedFields.add(field);
}
if (multipleInstructions) {
acc.push(...multipleInstructions);
} else if (instruction) {
acc.push(instruction);
}
return acc;
}, []);
if (skippedFields.size > 0) {
console.log(Colors.gray(
`\t ⓘ Skipped fields (set manually after approval): ${Array.from(skippedFields).join(', ')}`
));
}
return {
instructions,
skippedFields: Array.from(skippedFields)
};
};
// ==================== Approval Request Management ====================
type ApprovalRequest = { _id: string; status: string };
type ApprovalRequestBody = {
description: string;
instructions: SemanticInstruction[];
notifyMemberIds?: string[];
};
/**
* Checks if an approval request is active (should prevent duplicate creation)
*/
const isActiveApprovalRequest = (request: ApprovalRequest): boolean => {
const activeStatuses = ['pending', 'scheduled', 'failed'];
return activeStatuses.includes(request.status);
};
/**
* Finds active approval requests for a flag environment
*/
const findActiveApprovalRequests = async (
flagKey: string,
env: string
): Promise<ApprovalRequest[]> => {
const listApprovalsReq = ldAPIRequest(
apiKey,
domain,
`projects/${inputArgs.projKeyDest}/flags/${flagKey}/environments/${env}/approval-requests`
);
const response = await rateLimitRequest(listApprovalsReq, 'approval-requests');
if (response.status !== 200) {
return [];
}
const data = await response.json();
return (data.items || []).filter(isActiveApprovalRequest);
};
/**
* Determines who should be notified about an approval request
* Priority: 1. Flag maintainer, 2. Authenticated member, 3. No one
*/
const determineNotificationRecipients = (
maintainerId: string | null,
fallbackMemberId: string | null
): { recipients: string[], warning: string | null } => {
if (maintainerId) {
return { recipients: [maintainerId], warning: null };
}
if (fallbackMemberId) {
return {
recipients: [fallbackMemberId],
warning: 'No maintainer mapped, notifying creating member'
};
}
return {
recipients: [],
warning: 'No one to notify (service token used and no maintainer)'
};
};
/**
* Creates an approval request body
*/
const createApprovalRequestBody = (