-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsdk-release-metadata.mjs
More file actions
1261 lines (1157 loc) · 51.5 KB
/
Copy pathsdk-release-metadata.mjs
File metadata and controls
1261 lines (1157 loc) · 51.5 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
#!/usr/bin/env node
import { execFileSync } from 'node:child_process';
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
const SCOPE_LABELS = {
admin_portal: 'admin portal',
api_keys: 'API key',
audit_logs: 'audit log',
authorization: 'authorization',
connect: 'Connect',
directory_sync: 'directory sync',
events: 'events',
feature_flags: 'feature flag',
fga: 'FGA',
groups: 'groups',
multi_factor_auth: 'MFA',
organization_domains: 'organization domain',
organization_membership: 'organization membership',
organizations: 'organization',
passwordless: 'passwordless',
pipes: 'Pipes',
radar: 'radar',
roles: 'roles',
sso: 'SSO',
user_management: 'user management',
vault: 'vault',
webhooks: 'webhook',
widgets: 'widget',
client: 'client',
sdk: 'SDK',
};
const SCOPE_DOC_URLS = {
admin_portal: 'https://workos.com/docs/reference/admin-portal',
api_keys: 'https://workos.com/docs/reference/authkit/api-keys',
audit_logs: 'https://workos.com/docs/reference/audit-logs',
authorization: 'https://workos.com/docs/reference/fga',
connect: 'https://workos.com/docs/reference/workos-connect/standalone',
directory_sync: 'https://workos.com/docs/reference/directory-sync',
events: 'https://workos.com/docs/reference/events',
feature_flags: 'https://workos.com/docs/reference/feature-flags',
fga: 'https://workos.com/docs/reference/fga',
groups: 'https://workos.com/docs/reference/groups',
multi_factor_auth: 'https://workos.com/docs/reference/authkit/mfa',
organization_domains: 'https://workos.com/docs/reference/domain-verification',
organization_membership: 'https://workos.com/docs/reference/authkit/organization-membership',
organizations: 'https://workos.com/docs/reference/organization',
pipes: 'https://workos.com/docs/reference/pipes',
radar: 'https://workos.com/docs/reference/radar',
sso: 'https://workos.com/docs/reference/sso',
user_management: 'https://workos.com/docs/reference/authkit/user',
vault: 'https://workos.com/docs/reference/vault',
webhooks: 'https://workos.com/docs/reference/webhooks',
widgets: 'https://workos.com/docs/reference/widgets',
client: 'https://workos.com/docs/reference',
};
const SERVICE_SCOPE_OVERRIDES = new Map(
Object.entries({
ApplicationClientSecrets: 'connect',
Applications: 'connect',
Connections: 'sso',
Directories: 'directory_sync',
DirectoryGroups: 'directory_sync',
DirectoryUsers: 'directory_sync',
FeatureFlagsTargets: 'feature_flags',
MultiFactorAuthChallenges: 'multi_factor_auth',
OrganizationsApiKeys: 'api_keys',
OrganizationsFeatureFlags: 'feature_flags',
Permissions: 'authorization',
PipesProvider: 'pipes',
UserManagementAuthentication: 'user_management',
UserManagementCorsOrigins: 'user_management',
UserManagementDataProviders: 'pipes',
UserManagementInvitations: 'user_management',
UserManagementJWTTemplate: 'user_management',
UserManagementMagicAuth: 'user_management',
UserManagementMultiFactorAuthentication: 'multi_factor_auth',
UserManagementOrganizationMembership: 'organization_membership',
UserManagementOrganizationMembershipGroups: 'organization_membership',
UserManagementRedirectUris: 'user_management',
UserManagementSessionTokens: 'user_management',
UserManagementUsers: 'user_management',
UserManagementUsersAuthorizedApplications: 'user_management',
UserManagementUsersFeatureFlags: 'feature_flags',
WorkosConnect: 'connect',
}),
);
function printHelp() {
process.stdout.write(`Usage:
node scripts/sdk-release-metadata.mjs --diff-report <file> --old-ir <file> --new-ir <file> [options]
node scripts/sdk-release-metadata.mjs --spec-commit <sha> [options]
Build deterministic SDK release metadata from structured OpenAPI and compat diffs.
Inputs:
--diff-report <file> JSON output from "oagen diff".
--old-ir <file> JSON output from "oagen parse" for the previous spec.
--new-ir <file> JSON output from "oagen parse" for the current spec.
--compat-report <file> Optional SDK compat report JSON. When omitted and
--sdk-repo is given, one is derived from the checkout
(baseline ref vs current tree) without regenerating.
--changed-files <file> Optional newline-delimited SDK file list for file attribution.
--services <csv> Optional comma-separated post-mount service names (the
batch's staged scope). Restricts entries to those
services' scopes so the title/notes describe only what
the batch generated. Omit for full generation.
Commit convenience:
--spec-commit <sha> Use the spec state at this openapi-spec commit, then diff
against the previous spec-changing commit.
--openapi-repo <path> openapi-spec checkout for --spec-commit. Defaults to cwd.
--spec-path <path> Spec path in the repo. Defaults to spec/open-api-spec.yaml.
--sdk-repo <path> SDK checkout used to derive changed files and, when
--compat-report is omitted, an SDK compat report.
--sdk-base <rev> Diff base for --sdk-repo. Defaults to origin/main...HEAD.
--lang <language> SDK language for compat extraction. Inferred from the
--sdk-repo basename (e.g. workos-python → python).
Output:
--format json Default. Emits entries consumed by generate-prs.yml.
Includes scope_sources/scope_candidates provenance.
--format changelog Emits markdown sections for manual .changelog-pending repair.
Known scopes include docs_url metadata and render as
docs links in changelog markdown.
--strict-scopes Fail when a user-facing entry resolves to sdk or lacks
docs_url metadata.
--pr-number <number> Optional, changelog format only. Adds a linked PR heading.
--pr-url <url> Optional, changelog format only. Adds a linked PR heading.
--output <file> Write output to a file instead of stdout.
Examples:
node scripts/sdk-release-metadata.mjs --spec-commit dee95fc --sdk-repo ../backend/workos-dotnet
node scripts/sdk-release-metadata.mjs \\
--spec-commit dee95fc \\
--sdk-repo ../backend/workos-dotnet \\
--format changelog \\
--pr-number 263 \\
--pr-url https://github.com/workos/workos-dotnet/pull/263
`);
}
function parseArgs(argv) {
const args = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (arg === '-h') {
args.help = 'true';
continue;
}
if (!arg.startsWith('--')) continue;
const key = arg.slice(2);
const value = argv[i + 1] && !argv[i + 1].startsWith('--') ? argv[++i] : 'true';
args[key] = value;
}
return args;
}
function readJson(path, fallback) {
if (!path || !existsSync(path)) return fallback;
return JSON.parse(readFileSync(path, 'utf8'));
}
function readLines(path) {
if (!path || !existsSync(path)) return [];
return readFileSync(path, 'utf8')
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
}
function changedFilesFromArgs(args) {
if (args['changed-files']) return readLines(args['changed-files']);
if (!args['sdk-repo']) return [];
const base = args['sdk-base'] ?? 'origin/main...HEAD';
return run('git', ['-C', args['sdk-repo'], 'diff', '--name-only', base])
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
}
function run(command, args, opts = {}) {
try {
return execFileSync(command, args, {
cwd: opts.cwd,
encoding: 'utf8',
maxBuffer: 64 * 1024 * 1024,
stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (err) {
if (opts.allowExitCodes?.includes(err.status)) return err.stdout;
throw err;
}
}
function git(repo, args) {
return run('git', ['-C', repo, ...args]).trim();
}
function prepareSpecInputs(args) {
if (!args['spec-commit']) return args;
const repo = args['openapi-repo'] ?? process.cwd();
const specPath = args['spec-path'] ?? 'spec/open-api-spec.yaml';
const commit = args['spec-commit'];
const tmp = mkdtempSync(join(tmpdir(), 'sdk-release-metadata-'));
try {
const currentSpecCommit = git(repo, ['log', '--format=%H', '-n', '1', commit, '--', specPath]);
if (!currentSpecCommit) {
throw new Error(`No spec commit found at or before ${commit} for ${specPath}`);
}
const previousCommit = git(repo, ['log', '--format=%H', '-n', '1', `${currentSpecCommit}^`, '--', specPath]);
if (!previousCommit) {
throw new Error(`No previous spec commit found before ${currentSpecCommit} for ${specPath}`);
}
const oldSpecPath = join(tmp, 'old-open-api-spec.yaml');
const newSpecPath = join(tmp, 'new-open-api-spec.yaml');
const oldIrPath = join(tmp, 'old-ir.json');
const newIrPath = join(tmp, 'new-ir.json');
const diffPath = join(tmp, 'diff-report.json');
writeFileSync(oldSpecPath, run('git', ['-C', repo, 'show', `${previousCommit}:${specPath}`]));
writeFileSync(newSpecPath, run('git', ['-C', repo, 'show', `${commit}:${specPath}`]));
writeFileSync(oldIrPath, run('npx', ['oagen', 'parse', '--spec', oldSpecPath], { cwd: repo }));
writeFileSync(newIrPath, run('npx', ['oagen', 'parse', '--spec', newSpecPath], { cwd: repo }));
writeFileSync(
diffPath,
run('npx', ['oagen', 'diff', '--old', oldSpecPath, '--new', newSpecPath], {
cwd: repo,
allowExitCodes: [1, 2],
}),
);
return {
...args,
'diff-report': args['diff-report'] ?? diffPath,
'old-ir': args['old-ir'] ?? oldIrPath,
'new-ir': args['new-ir'] ?? newIrPath,
// Absolute path to the spec at the requested commit, so a downstream
// compat derivation extracts against that historical spec rather than the
// current checkout (see prepareCompatInputs).
_specPath: newSpecPath,
_tmpdir: tmp,
};
} catch (err) {
rmSync(tmp, { recursive: true, force: true });
throw err;
}
}
function inferLanguage(sdkRepo) {
const base =
String(sdkRepo)
.replace(/[\\/]+$/, '')
.split(/[\\/]/)
.pop() ?? '';
const match = base.match(/^workos-(.+)$/);
return match ? match[1] : base;
}
// Derive an SDK compat report from an existing checkout WITHOUT regenerating
// the SDK: snapshot the current tree (candidate) and the tree at the base ref
// (baseline, via a throwaway git worktree), then diff. This lets the changelog
// surface SDK-surface changes — e.g. a method rename — that the spec diff alone
// cannot see. Fails open: any problem just means the changelog is built from
// the spec diff only. Skipped when --compat-report is passed explicitly (so
// CI, which supplies its own per-language reports, is unaffected).
function prepareCompatInputs(args) {
if (!args['sdk-repo'] || args['compat-report']) return args;
const sdkRepo = args['sdk-repo'];
const lang = args.lang ?? inferLanguage(sdkRepo);
const openapiRepo = args['openapi-repo'] ?? process.cwd();
// Prefer the spec snapshot pinned by prepareSpecInputs (--spec-commit) so a
// historical changelog repair extracts compat against that commit's spec, not
// whatever is checked out now. Falls back to the working-tree spec otherwise.
const specPath = args._specPath ?? join(openapiRepo, args['spec-path'] ?? 'spec/open-api-spec.yaml');
const rawBase = args['sdk-base'] ?? 'origin/main...HEAD';
const leftRef = rawBase.split(/\.\.\.?/)[0] || 'origin/main';
const tmp = mkdtempSync(join(tmpdir(), 'sdk-release-compat-'));
const baselineSrc = join(tmp, 'baseline-src');
let worktreeAdded = false;
let succeeded = false;
try {
const baselineCommit = rawBase.includes('...')
? git(sdkRepo, ['merge-base', leftRef, 'HEAD'])
: git(sdkRepo, ['rev-parse', leftRef]);
git(sdkRepo, ['worktree', 'add', '--detach', baselineSrc, baselineCommit]);
worktreeAdded = true;
const baselineOut = join(tmp, 'baseline');
const candidateOut = join(tmp, 'candidate');
mkdirSync(baselineOut, { recursive: true });
mkdirSync(candidateOut, { recursive: true });
const extract = (sdkPath, output) =>
run('npx', ['oagen', 'compat-extract', '--lang', lang, '--sdk-path', sdkPath, '--output', output, '--spec', specPath], {
cwd: openapiRepo,
});
extract(baselineSrc, baselineOut);
extract(sdkRepo, candidateOut);
const reportPath = join(tmp, 'compat-report.json');
run(
'npx',
[
'oagen',
'compat-diff',
'--baseline',
join(baselineOut, '.oagen-compat-snapshot.json'),
'--candidate',
join(candidateOut, '.oagen-compat-snapshot.json'),
'--output',
reportPath,
'--fail-on',
'none',
],
{ cwd: openapiRepo, allowExitCodes: [1] },
);
succeeded = true;
return { ...args, 'compat-report': reportPath, _compatTmpdir: tmp };
} catch (err) {
process.stderr.write(
`warning: could not derive SDK compat report (${err.message}); changelog will use the spec diff only\n`,
);
return args;
} finally {
if (worktreeAdded) {
try {
git(sdkRepo, ['worktree', 'remove', '--force', baselineSrc]);
} catch {
try {
git(sdkRepo, ['worktree', 'prune']);
} catch {
// best-effort cleanup
}
}
}
if (!succeeded) rmSync(tmp, { recursive: true, force: true });
}
}
function toSnakeCase(value) {
return String(value)
.replace(/([a-z0-9])([A-Z])/g, '$1_$2')
.replace(/[^A-Za-z0-9]+/g, '_')
.replace(/^_+|_+$/g, '')
.toLowerCase();
}
function normalize(value) {
return String(value).toLowerCase().replace(/[^a-z0-9]/g, '');
}
function unique(values) {
return [...new Set(values.filter(Boolean))];
}
function sortStable(values) {
return [...values].sort((a, b) => a.localeCompare(b));
}
export function publicScopeFromService(serviceName) {
if (!serviceName) return 'sdk';
if (SERVICE_SCOPE_OVERRIDES.has(serviceName)) return SERVICE_SCOPE_OVERRIDES.get(serviceName);
if (serviceName.startsWith('Directory')) return 'directory_sync';
if (serviceName.startsWith('FeatureFlags')) return 'feature_flags';
if (serviceName.startsWith('MultiFactorAuth')) return 'multi_factor_auth';
if (serviceName.startsWith('OrganizationDomains')) return 'organization_domains';
if (serviceName.startsWith('Organizations')) return 'organizations';
if (serviceName.startsWith('UserManagement')) return 'user_management';
return toSnakeCase(serviceName);
}
// Map a `--services` selection (post-mount service names, comma-separated, as the
// SDK bot passes them) to the set of changelog SCOPE keys those services own.
// A scoped batch's release notes and PR title must describe only the staged
// services — otherwise an unrelated change that happened to land in the spec
// between staging and generation (a watermark/drift skew) drives the title, e.g.
// a Pipes-only batch getting titled "Add `resource_type_slug` to authorization
// models". Returns null when nothing is selected (full generation) so callers
// keep every scope. `'true'` is the no-value sentinel from parseArgs.
export function scopesForServices(servicesArg) {
if (!servicesArg || servicesArg === 'true') return null;
const names = String(servicesArg)
.split(',')
.map((name) => name.trim())
.filter(Boolean);
if (names.length === 0) return null;
return new Set(names.map((name) => publicScopeFromService(name)));
}
function scopeFromName(name) {
if (!name) return 'sdk';
if (/DataIntegration|Pipe/.test(name)) return 'pipes';
if (/SessionAuthenticate/.test(name)) return 'user_management';
if (/WebhookEndpointEvents|Webhook/.test(name)) return 'webhooks';
if (/^(ApiKey|ExpireApiKey|OrganizationApiKey|UserApiKey)/.test(name)) return 'api_keys';
if (/^(Dsync|Directory)/.test(name)) return 'directory_sync';
if (/^Radar/.test(name)) return 'radar';
if (/^(Vault|Object$|ObjectMetadata|ObjectSummary|ObjectVersion|ObjectWithoutValue)/.test(name)) return 'vault';
if (/^AuditLog/.test(name)) return 'audit_logs';
if (/^(Application|Connect|UserObject$|ApplicationCredentials|ExternalAuth|RedirectUriInput)/.test(name)) return 'connect';
if (/^(Group|CreateGroup|UpdateGroup)/.test(name)) return 'groups';
if (/OrganizationMembership/.test(name)) return 'organization_membership';
if (/^OrganizationDomain/.test(name)) return 'organization_domains';
if (/^DomainVerification/.test(name)) return 'organization_domains';
if (/^Organization/.test(name)) return 'organizations';
if (/^(Connection|SSO|Sso)/.test(name)) return 'sso';
if (/^(AuthenticationFactor|AuthenticationChallenge|ChallengeAuthenticationFactor|MultiFactor|Mfa)/.test(name)) {
return 'multi_factor_auth';
}
if (/^(FeatureFlag|Flag)/.test(name)) return 'feature_flags';
if (/^(Invitation|MagicAuth|PasswordReset|RevokeSession|Session|User|CreateUser|UpdateUser|EmailChange)/.test(name)) {
return 'user_management';
}
if (/^(Role|Permission)/.test(name)) return 'authorization';
if (/^Widget/.test(name)) return 'widgets';
if (/^Event/.test(name)) return 'events';
// Admin Portal generate-link intent options (`GenerateLinkDto`). The SSO and
// domain-verification variants resolve to their own scopes via the rules
// above; this catches the bare `IntentOptions` aggregate and any other
// intent-options type not otherwise classified.
if (/IntentOptions$/.test(name)) return 'admin_portal';
return 'sdk';
}
function scopeFromFile(path) {
const normalized = normalize(path);
if (/apikey|apikeys|api_keys/.test(normalized)) return 'api_keys';
if (/webhook/.test(normalized)) return 'webhooks';
if (/auditlog|auditlogs|audit_logs/.test(normalized)) return 'audit_logs';
if (/directorysync|directory_sync|dsync/.test(normalized)) return 'directory_sync';
if (/radar/.test(normalized)) return 'radar';
if (/vault|vaultobject/.test(normalized)) return 'vault';
if (/connect|applicationcredential|externalauth|userobject/.test(normalized)) return 'connect';
if (/featureflag|featureflags|feature_flags/.test(normalized)) return 'feature_flags';
if (/multifactorauth|multi_factor_auth|mfa/.test(normalized)) return 'multi_factor_auth';
if (/organizationdomain|organizationdomains|organization_domains|domainverification|domain_verification/.test(normalized)) return 'organization_domains';
if (/organizationmembership|organizationmemberships/.test(normalized)) return 'organization_membership';
if (/organization|organizations/.test(normalized)) return 'organizations';
if (/user_management|usermanagement|revoke_session|revokesession|createuser|updateuser/.test(normalized)) {
return 'user_management';
}
if (/sso|connection/.test(normalized)) return 'sso';
if (/group/.test(normalized)) return 'groups';
if (/permission|role|authorization/.test(normalized)) return 'authorization';
if (/widget/.test(normalized)) return 'widgets';
return 'sdk';
}
function labelForScope(scope) {
return SCOPE_LABELS[scope] ?? scope.replaceAll('_', ' ');
}
function docsUrlForScope(scope) {
return SCOPE_DOC_URLS[scope];
}
function code(value) {
return `\`${value}\``;
}
// Drill through wrappers (list/optional/etc.) to the underlying model or enum
// name, so a response/request type can be named in the changelog.
function primaryTypeName(type) {
if (!type || typeof type !== 'object') return null;
if ((type.kind === 'model' || type.kind === 'enum') && type.name) return type.name;
return primaryTypeName(type.inner) ?? primaryTypeName(type.items) ?? null;
}
export function buildIndexes(specs) {
const modelByName = new Map();
const enumByName = new Map();
const enumWireValues = new Map();
const symbolScopes = new Map();
const operationByKey = new Map();
const serviceNames = new Set();
// Per-side (old vs new) maps of operation → response/request type name, used
// to describe *what* changed in a modified operation. specs is [oldIr, newIr].
const responseTypeByKey = { old: new Map(), new: new Map() };
const requestTypeByKey = { old: new Map(), new: new Map() };
specs.forEach((spec, i) => {
const slot = i === 0 ? 'old' : 'new';
for (const service of spec?.services ?? []) {
for (const operation of service.operations ?? []) {
const key = `${service.name}.${operation.name}`;
const resp = primaryTypeName(operation.response);
if (resp) responseTypeByKey[slot].set(key, resp);
const req = primaryTypeName(operation.requestBody);
if (req) requestTypeByKey[slot].set(key, req);
}
}
});
for (const spec of specs.filter(Boolean)) {
for (const model of spec.models ?? []) modelByName.set(model.name, model);
for (const enm of spec.enums ?? []) {
enumByName.set(enm.name, enm);
for (const value of enm.values ?? []) {
enumWireValues.set(`${enm.name}.${value.name}`, value.value ?? value.name);
}
}
}
const addScope = (kind, name, scope) => {
if (!name || !scope) return;
const key = `${kind}:${name}`;
const set = symbolScopes.get(key) ?? new Set();
set.add(scope);
symbolScopes.set(key, set);
};
const collectTypeRefs = (type, out) => {
if (!type || typeof type !== 'object') return;
if (type.kind === 'model') out.models.add(type.name);
if (type.kind === 'enum') out.enums.add(type.name);
if (type.inner) collectTypeRefs(type.inner, out);
if (type.items) collectTypeRefs(type.items, out);
if (type.values) collectTypeRefs(type.values, out);
for (const variant of type.variants ?? []) collectTypeRefs(variant, out);
};
const collectModelClosure = (modelName, out, seen = new Set()) => {
if (!modelName || seen.has(modelName)) return;
seen.add(modelName);
out.models.add(modelName);
const model = modelByName.get(modelName);
if (!model) return;
for (const field of model.fields ?? []) {
const nested = { models: new Set(), enums: new Set() };
collectTypeRefs(field.type, nested);
for (const enumName of nested.enums) out.enums.add(enumName);
for (const nestedModel of nested.models) collectModelClosure(nestedModel, out, seen);
}
};
for (const spec of specs.filter(Boolean)) {
for (const service of spec.services ?? []) {
const scope = publicScopeFromService(service.name);
serviceNames.add(service.name);
for (const operation of service.operations ?? []) {
operationByKey.set(`${service.name}.${operation.name}`, operation);
const direct = { models: new Set(), enums: new Set() };
for (const param of [
...(operation.pathParams ?? []),
...(operation.queryParams ?? []),
...(operation.headerParams ?? []),
]) {
collectTypeRefs(param.type, direct);
}
collectTypeRefs(operation.requestBody, direct);
collectTypeRefs(operation.response, direct);
for (const response of operation.successResponses ?? []) collectTypeRefs(response.type, direct);
for (const error of operation.errors ?? []) collectTypeRefs(error.type, direct);
const all = { models: new Set(), enums: new Set(direct.enums) };
for (const modelName of direct.models) collectModelClosure(modelName, all);
for (const modelName of all.models) addScope('model', modelName, scope);
for (const enumName of all.enums) addScope('enum', enumName, scope);
}
}
}
const typeNames = new Set([...modelByName.keys(), ...enumByName.keys()]);
return { enumWireValues, symbolScopes, operationByKey, responseTypeByKey, requestTypeByKey, serviceNames, typeNames };
}
function resolveServiceScope(serviceName) {
const scope = publicScopeFromService(serviceName);
const snake = toSnakeCase(serviceName);
const source = SERVICE_SCOPE_OVERRIDES.has(serviceName)
? 'service_override'
: scope === snake
? 'service_name'
: 'service_rule';
return { scope, source, candidates: [scope] };
}
function resolveSymbolScope(kind, name, indexes) {
const refs = indexes.symbolScopes.get(`${kind}:${name}`);
const candidates = refs ? sortStable([...refs]) : [];
const fallback = scopeFromName(name);
if (fallback !== 'sdk') {
return {
scope: fallback,
source: candidates.includes(fallback) ? 'name_and_ir' : 'name',
candidates,
};
}
if (candidates.length === 1) {
return { scope: candidates[0], source: 'ir', candidates };
}
if (candidates.length > 1) {
return { scope: candidates[0], source: 'ir_ambiguous', candidates };
}
return { scope: 'sdk', source: 'unresolved', candidates: [] };
}
function scopeFields(resolution) {
return {
scope: resolution.scope,
scope_source: resolution.source,
scope_candidates: resolution.candidates,
};
}
function enumDisplay(enumName, valueName, indexes) {
const wire = indexes.enumWireValues.get(`${enumName}.${valueName}`);
if (wire) return `\`${wire}\``;
return `\`${valueName}\``;
}
function severityToPrefix(severity) {
if (severity === 'breaking') return 'feat!';
if (severity === 'additive') return 'feat';
return 'fix';
}
// Per policy, only a changed call signature or a removed/renamed *type* is
// breaking. Field-, enum-value-, and response/request-shape changes are backend
// API changes — never breaking, even when the spec differ classifies them so.
// Cap those kinds: a would-be-breaking severity becomes `fix` (it is neither a
// feature nor a major bump); additive severities pass through unchanged.
const BACKEND_ONLY_DIFF_KINDS = new Set([
'field-added',
'field-removed',
'field-type-changed',
'field-format-changed',
'field-required-changed',
'field-access-changed',
'value-removed',
'value-modified',
'response-changed',
'request-body-changed',
]);
// Pure additions can't break a caller and aren't a fix — a new field/value is a
// feature. Floor these at `additive` (→ feat) regardless of what the differ
// classified them as: it sometimes flags an added field `breaking` (reads it as
// a request-shape tightening), which the backend-only cap below would otherwise
// collapse to `fix`, and a missing/odd classification would fall through to
// `fix` via severityToPrefix. Either way a new field would land under **Fixes**
// while the release bumped minor — see model-added/enum-added, hardcoded the
// same way.
const ADDITIVE_DIFF_KINDS = new Set(['field-added', 'value-added']);
function capSeverity(kind, severity) {
if (ADDITIVE_DIFF_KINDS.has(kind)) return 'additive';
return BACKEND_ONLY_DIFF_KINDS.has(kind) && severity === 'breaking' ? 'fix' : severity;
}
function addFact(facts, fact) {
facts.push({
symbols: [],
scope_source: 'unknown',
scope_candidates: [],
...fact,
prefix: severityToPrefix(fact.severity),
});
}
function operationDetail(change, indexes, action) {
const operation = indexes.operationByKey.get(`${change.serviceName}.${change.operationName}`);
if (operation?.httpMethod && operation?.path) {
return `${action} endpoint \`${operation.httpMethod.toUpperCase()} ${operation.path}\`.`;
}
return `${action} operation in \`${change.serviceName}\`.`;
}
export function factsFromDiff(diffReport, indexes) {
const facts = [];
for (const change of diffReport.changes ?? []) {
if (change.kind === 'model-added') {
const scope = resolveSymbolScope('model', change.name, indexes);
addFact(facts, {
severity: 'additive',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Added model \`${change.name}\`.`,
});
} else if (change.kind === 'model-removed') {
const scope = resolveSymbolScope('model', change.name, indexes);
addFact(facts, {
severity: 'breaking',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Removed model \`${change.name}\`.`,
});
} else if (change.kind === 'model-modified') {
const scope = resolveSymbolScope('model', change.name, indexes);
for (const fieldChange of change.fieldChanges ?? []) {
// The spec differ encodes a field's required/optional *direction* in the
// classification (made-required reads as breaking). Capture it before the
// severity is capped, since the changelog wording depends on it.
const madeRequired = fieldChange.classification === 'breaking';
let detail;
if (fieldChange.kind === 'field-added') {
detail = `Added \`${fieldChange.fieldName}\` to \`${change.name}\`.`;
} else if (fieldChange.kind === 'field-removed') {
detail = `Removed \`${fieldChange.fieldName}\` from \`${change.name}\`.`;
} else if (fieldChange.kind === 'field-required-changed') {
detail = madeRequired
? `Made \`${change.name}.${fieldChange.fieldName}\` required.`
: `Made \`${change.name}.${fieldChange.fieldName}\` optional.`;
} else if (fieldChange.kind === 'field-type-changed') {
detail = `Changed the type of \`${change.name}.${fieldChange.fieldName}\`.`;
} else if (fieldChange.kind === 'field-format-changed') {
detail = `Changed the format of \`${change.name}.${fieldChange.fieldName}\`.`;
} else {
detail = `Changed access for \`${change.name}.${fieldChange.fieldName}\`.`;
}
addFact(facts, {
severity: capSeverity(fieldChange.kind, fieldChange.classification),
...scopeFields(scope),
kind: fieldChange.kind,
symbols: [change.name, fieldChange.fieldName],
fieldName: fieldChange.fieldName,
modelName: change.name,
...(fieldChange.kind === 'field-required-changed' ? { madeRequired } : {}),
detail,
});
}
} else if (change.kind === 'enum-added') {
const scope = resolveSymbolScope('enum', change.name, indexes);
addFact(facts, {
severity: 'additive',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Added enum \`${change.name}\`.`,
});
} else if (change.kind === 'enum-removed') {
const scope = resolveSymbolScope('enum', change.name, indexes);
addFact(facts, {
severity: 'breaking',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Removed enum \`${change.name}\`.`,
});
} else if (change.kind === 'enum-modified') {
const scope = resolveSymbolScope('enum', change.name, indexes);
for (const valueChange of change.valueChanges ?? []) {
let detail;
if (valueChange.kind === 'value-added') {
detail = `Added ${enumDisplay(change.name, valueChange.valueName, indexes)} to \`${change.name}\`.`;
} else if (valueChange.kind === 'value-removed') {
detail = `Removed ${enumDisplay(change.name, valueChange.valueName, indexes)} from \`${change.name}\`.`;
} else {
detail = `Changed ${enumDisplay(change.name, valueChange.valueName, indexes)} in \`${change.name}\`.`;
}
addFact(facts, {
severity: capSeverity(valueChange.kind, valueChange.classification),
...scopeFields(scope),
kind: valueChange.kind,
symbols: [change.name, valueChange.valueName],
enumName: change.name,
valueName: valueChange.valueName,
detail,
});
}
} else if (change.kind === 'service-added') {
const scope = resolveServiceScope(change.name);
addFact(facts, {
severity: 'additive',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Added service \`${change.name}\`.`,
});
} else if (change.kind === 'service-removed') {
const scope = resolveServiceScope(change.name);
addFact(facts, {
severity: 'breaking',
...scopeFields(scope),
kind: change.kind,
symbols: [change.name],
detail: `Removed service \`${change.name}\`.`,
});
} else if (change.kind === 'operation-added') {
const scope = resolveServiceScope(change.serviceName);
addFact(facts, {
severity: 'additive',
...scopeFields(scope),
kind: change.kind,
symbols: [change.serviceName, change.operationName],
detail: operationDetail(change, indexes, 'Added'),
});
} else if (change.kind === 'operation-removed') {
const scope = resolveServiceScope(change.serviceName);
addFact(facts, {
severity: 'breaking',
...scopeFields(scope),
kind: change.kind,
symbols: [change.serviceName, change.operationName],
detail: operationDetail(change, indexes, 'Removed'),
});
} else if (change.kind === 'operation-modified') {
const scope = resolveServiceScope(change.serviceName);
for (const paramChange of change.paramChanges ?? []) {
const severity = paramChange.classification;
const param = `\`${change.serviceName}.${change.operationName}.${paramChange.paramName}\``;
let detail;
if (paramChange.kind === 'param-added') detail = `Added parameter ${param}.`;
else if (paramChange.kind === 'param-removed') detail = `Removed parameter ${param}.`;
else if (paramChange.kind === 'param-required-changed') detail = `Changed required status for parameter ${param}.`;
else if (paramChange.kind === 'param-default-changed') detail = `Changed default for parameter ${param}.`;
else detail = `Changed parameter ${param}.`;
addFact(facts, {
severity,
...scopeFields(scope),
kind: paramChange.kind,
symbols: [change.serviceName, change.operationName, paramChange.paramName],
detail,
});
}
const opKey = `${change.serviceName}.${change.operationName}`;
if (change.responseChanged) {
const oldType = indexes.responseTypeByKey?.old.get(opKey);
const newType = indexes.responseTypeByKey?.new.get(opKey);
addFact(facts, {
severity: capSeverity('response-changed', change.classification),
...scopeFields(scope),
kind: 'response-changed',
symbols: [change.serviceName, change.operationName],
detail:
oldType && newType && oldType !== newType
? `Changed response of \`${opKey}\` from \`${oldType}\` to \`${newType}\`.`
: `Changed response for \`${opKey}\`.`,
});
}
if (change.requestBodyChanged) {
const oldType = indexes.requestTypeByKey?.old.get(opKey);
const newType = indexes.requestTypeByKey?.new.get(opKey);
addFact(facts, {
severity: capSeverity('request-body-changed', change.classification),
...scopeFields(scope),
kind: 'request-body-changed',
symbols: [change.serviceName, change.operationName],
detail:
oldType && newType && oldType !== newType
? `Changed request body of \`${opKey}\` from \`${oldType}\` to \`${newType}\`.`
: `Changed request body for \`${opKey}\`.`,
});
}
}
}
return facts;
}
// Pair a removed callable with an added one under the same owner into a
// rename, so the changelog reads "renamed X to Y" instead of a bare removal
// plus an unrelated-looking addition. Mirrors pairRemoveAddRows in
// sdk-compat-pr-comment.mjs: only pair member symbols (owner.member), and only
// when an owner has exactly one logical removal and one logical addition, to
// avoid guessing among multiple candidates. Returns a Map of every removed
// symbol → { from, to } display representatives.
function renamesFromCompat(compatReport) {
// Some SDKs emit a coroutine/async member variant alongside the base method
// (e.g. Kotlin's `fooSuspend`). Collapse them to a single logical member so
// one rename isn't counted as multiple removals/additions.
const VARIANT_SUFFIX = /Suspend$/;
const index = (map, symbol) => {
const dot = symbol.lastIndexOf('.');
if (dot === -1) return;
const owner = symbol.slice(0, dot).replace(/_/g, '').toLowerCase();
const member = symbol.slice(dot + 1);
const base = member.replace(VARIANT_SUFFIX, '').toLowerCase();
if (!map.has(owner)) map.set(owner, { bases: new Set(), symbols: [], rep: null });
const entry = map.get(owner);
entry.bases.add(base);
entry.symbols.push(symbol);
// Prefer the variant without the suffix as the display representative.
if (entry.rep === null || !VARIANT_SUFFIX.test(member)) entry.rep = symbol;
};
const removedByOwner = new Map();
const addedByOwner = new Map();
for (const change of compatReport?.changes ?? []) {
if (change.category === 'symbol_removed') index(removedByOwner, String(change.symbol ?? ''));
else if (change.category === 'symbol_added') index(addedByOwner, String(change.symbol ?? ''));
}
const renames = new Map();
for (const [owner, removed] of removedByOwner) {
const added = addedByOwner.get(owner);
if (removed.bases.size !== 1 || added?.bases.size !== 1) continue;
for (const symbol of removed.symbols) renames.set(symbol, { from: removed.rep, to: added.rep });
}
return renames;
}
// Compat categories the tool may flag breaking that are still backend API
// changes under our policy: a field's type, an enum member value, a method's
// return type, or a default moving. Only call-signature and whole-type changes
// stay breaking.
const NON_BREAKING_COMPAT_CATEGORIES = new Set([
'field_type_changed',
'enum_member_value_changed',
'return_type_changed',
'default_value_changed',
]);
// Decide whether a breaking-severity compat change is breaking under our policy.
// `symbol_removed`/`symbol_renamed` carry no kind, so split owner from member and
// consult the IR: a member of a model/enum is a property (field rename/removal —
// not breaking); a whole type/service or a service/client member is call surface.
function compatChangeIsBreaking(change, indexes) {
const category = String(change.category ?? '');
if (NON_BREAKING_COMPAT_CATEGORIES.has(category)) return false;
if (category === 'symbol_removed' || category === 'symbol_renamed') {
const symbol = String(change.symbol ?? '');
const dot = symbol.lastIndexOf('.');
if (dot === -1) return true; // whole type/service removed or renamed
const owner = symbol.slice(0, dot).replace(/^Async(?=[A-Z])/, '');
if (indexes?.serviceNames?.has(owner) || owner === 'Client') return true;
if (indexes?.typeNames?.has(owner)) return false;
return true; // unknown owner — preserve breaking rather than drop a real removal
}
return true;
}
function factsFromCompat(compatReport, existingFacts, indexes) {
const facts = [];
const existingBreakingScopes = new Set(existingFacts.filter((fact) => fact.severity === 'breaking').map((fact) => fact.scope));
const renames = renamesFromCompat(compatReport);
// Only one breaking fact survives per scope (the dedup below), so prefer the
// sync symbol over its `Async*` mirror when both changed — the sync surface
// is the primary public API and reads better in the changelog.
const isAsync = (change) => (/^Async(?=[A-Z])/.test(String(change.symbol ?? '')) ? 1 : 0);
const breakingChanges = (compatReport?.changes ?? [])
.filter((change) => change.severity === 'breaking' && compatChangeIsBreaking(change, indexes))
.sort((a, b) => isAsync(a) - isAsync(b));
for (const change of breakingChanges) {
// Strip the Python async-client prefix (`AsyncPipes` → `Pipes`) so async
// surface symbols resolve to the same scope as their sync counterparts.
const root = String(change.symbol ?? '').split('.')[0].replace(/^Async(?=[A-Z])/, '');
const serviceScope = resolveServiceScope(root);
const nameScope = scopeFromName(root);
const scope = serviceScope.scope !== toSnakeCase(root) ? serviceScope.scope : nameScope;
const targetScope = scope === 'sdk' && root === 'Client' ? 'client' : scope;
const source =
targetScope === 'client'
? 'compat_client'
: serviceScope.scope !== toSnakeCase(root)
? `compat_${serviceScope.source}`
: nameScope !== 'sdk'
? 'compat_name'
: 'compat_unresolved';
if (existingBreakingScopes.has(targetScope)) continue;
const renamed = renames.get(String(change.symbol ?? ''));
addFact(facts, {
severity: 'breaking',
scope: targetScope,
scope_source: source,
scope_candidates: [targetScope],
kind: renamed ? 'sdk-surface-renamed' : 'sdk-surface-breaking',
symbols: renamed ? [renamed.from, renamed.to] : [change.symbol],
detail: renamed
? `SDK surface change: \`${renamed.from}\` was renamed to \`${renamed.to}\`.`
: `SDK surface change: ${change.message ?? change.symbol}.`,
});
existingBreakingScopes.add(targetScope);
}
return facts;
}
export function groupFacts(facts) {
const groups = new Map();
for (const fact of facts) {
const key = `${fact.scope}:${fact.severity}`;
const group = groups.get(key) ?? {
scope: fact.scope,
severity: fact.severity,
prefix: severityToPrefix(fact.severity),
facts: [],
symbols: new Set(),
scopeSources: new Set(),
scopeCandidates: new Set(),
};