@workos/oagen-emitters 0.6.6 → 0.6.8

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,6 +1,14 @@
1
1
  import type { Service, EmitterContext, GeneratedFile, Operation, TypeRef, Parameter, Model } from '@workos/oagen';
2
2
  import { planOperation } from '@workos/oagen';
3
- import { className, fieldName, fileName, methodName, safeParamName, resolveMethodName } from './naming.js';
3
+ import {
4
+ className,
5
+ fieldName,
6
+ fileName,
7
+ methodName,
8
+ safeParamName,
9
+ resolveMethodName,
10
+ scopedGroupVariantClassName,
11
+ } from './naming.js';
4
12
  import { mapTypeRefForYard } from './type-map.js';
5
13
  import {
6
14
  buildResolvedLookup,
@@ -13,6 +21,7 @@ import {
13
21
  } from '../shared/resolved-ops.js';
14
22
  import { isListWrapperModel } from '../shared/model-utils.js';
15
23
  import { generateWrapperMethods, collectWrapperResponseModels } from './wrappers.js';
24
+ import { buildGroupOwnerMap, collectVariantsForMountTarget, emitInlineVariantClass } from './parameter-groups.js';
16
25
 
17
26
  /**
18
27
  * Generate Ruby resource (service) classes from IR services.
@@ -35,6 +44,11 @@ export function generateResources(services: Service[], ctx: EmitterContext): Gen
35
44
  if (isListWrapperModel(m)) listWrapperModels.set(m.name, m);
36
45
  }
37
46
 
47
+ // Resolve groupName -> owner mountTarget once per generation pass; every
48
+ // dispatcher and YARD `@param` reference resolves variant classes through
49
+ // this map so cross-resource references stay consistent.
50
+ const groupOwners = buildGroupOwnerMap(ctx);
51
+
38
52
  for (const [mountTarget, group] of groups) {
39
53
  const cls = className(mountTarget);
40
54
  const file = fileName(mountTarget);
@@ -88,6 +102,7 @@ export function generateResources(services: Service[], ctx: EmitterContext): Gen
88
102
  modelByName,
89
103
  listWrapperModels,
90
104
  requires,
105
+ groupOwners,
91
106
  });
92
107
  methodBodies.push(body);
93
108
 
@@ -121,6 +136,18 @@ export function generateResources(services: Service[], ctx: EmitterContext): Gen
121
136
  }
122
137
  lines.push('module WorkOS');
123
138
  lines.push(` class ${cls}`);
139
+
140
+ // Inline parameter-group variant classes owned by this mount target.
141
+ // Zeitwerk's `loader.collapse` flattens `lib/workos/<service>/` so files
142
+ // there can't define `WorkOS::<Service>::*` constants — variants must
143
+ // live inside the service's own file. Matches Python's per-resource
144
+ // dataclass layout.
145
+ const variants = collectVariantsForMountTarget(ctx, ctx.spec.models as Model[], mountTarget);
146
+ for (const v of variants) {
147
+ for (const line of emitInlineVariantClass(v)) lines.push(line);
148
+ lines.push('');
149
+ }
150
+
124
151
  lines.push(' def initialize(client)');
125
152
  lines.push(' @client = client');
126
153
  lines.push(' end');
@@ -154,6 +181,7 @@ function emitMethod(args: {
154
181
  modelByName: Map<string, Model>;
155
182
  listWrapperModels: Map<string, Model>;
156
183
  requires: Set<string>;
184
+ groupOwners: Map<string, string>;
157
185
  }): string {
158
186
  const {
159
187
  op,
@@ -166,9 +194,19 @@ function emitMethod(args: {
166
194
  modelByName,
167
195
  listWrapperModels,
168
196
  requires,
197
+ groupOwners,
169
198
  } = args;
170
199
  void enumNames;
171
200
 
201
+ /** Fully-qualified Ruby constant for a variant (e.g. WorkOS::UserManagement::PasswordPlaintext). */
202
+ const variantClassRef = (group: { name: string }, variantName: string): string => {
203
+ const owner = groupOwners.get(group.name);
204
+ if (!owner) {
205
+ throw new Error(`No owner mount target found for parameter group '${group.name}'`);
206
+ }
207
+ return scopedGroupVariantClassName(owner, group.name, variantName);
208
+ };
209
+
172
210
  const plan = planOperation(op);
173
211
  const lines: string[] = [];
174
212
 
@@ -177,8 +215,11 @@ function emitMethod(args: {
177
215
  const groupedParamNames = collectGroupedParamNames(op);
178
216
  const queryParams = (op.queryParams ?? []).filter((q) => !groupedParamNames.has(q.name));
179
217
 
180
- // Request body params: if body is a model, expand its fields.
181
- const bodyFields = getRequestBodyFields(op, hiddenParams, modelByName);
218
+ // Request body params: if body is a model, expand its fields. Drop any field
219
+ // whose name is also a parameter-group name — those are dispatched by the
220
+ // group kwarg below, so emitting them as flat kwargs would shadow the group
221
+ // and cause `String#[Symbol]` TypeErrors when the dispatcher reads `:type`.
222
+ const bodyFields = getRequestBodyFields(op, hiddenParams, modelByName).filter((f) => !groupedParamNames.has(f.name));
182
223
 
183
224
  // Detect path/body name collisions and build a rename map for body fields.
184
225
  // When a body field's snake_case name matches a path param, prefix with "body_"
@@ -269,7 +310,16 @@ function emitMethod(args: {
269
310
  sigParts.push('request_options: {}');
270
311
 
271
312
  // YARD docs.
272
- const doc = buildYardDoc(op, pathParams, queryParams, bodyFields, hiddenParams, bodyFieldRenames, listWrapperModels);
313
+ const doc = buildYardDoc(
314
+ op,
315
+ pathParams,
316
+ queryParams,
317
+ bodyFields,
318
+ hiddenParams,
319
+ bodyFieldRenames,
320
+ listWrapperModels,
321
+ variantClassRef,
322
+ );
273
323
  for (const line of doc) lines.push(` ${line}`);
274
324
 
275
325
  // Signature.
@@ -309,30 +359,41 @@ function emitMethod(args: {
309
359
  const groupsGoToQuery = hasGroups && !hasBodyMethod;
310
360
  const hasQuery = qEntries.length > 0 || groupsGoToQuery;
311
361
  if (hasQuery) {
362
+ // Skip `.compact` when no entry can be nil — required kwargs are always
363
+ // passed (Ruby raises ArgumentError otherwise), so the literal has no nil
364
+ // values to drop. Group dispatch happens after the literal is built and
365
+ // doesn't contribute potentially-nil entries either.
366
+ const queryHasNilable = qEntries.some((q) => !q.required);
367
+ const queryCompact = queryHasNilable ? '.compact' : '';
312
368
  lines.push(' params = {');
313
369
  for (let i = 0; i < qEntries.length; i++) {
314
370
  const q = qEntries[i];
315
371
  const sep = i === qEntries.length - 1 && !groupsGoToQuery ? '' : ',';
316
372
  lines.push(` ${rubyStringLit(q.name)} => ${safeParamName(q.name)}${sep}`);
317
373
  }
318
- lines.push(' }.compact');
374
+ lines.push(` }${queryCompact}`);
319
375
 
320
376
  if (groupsGoToQuery) {
321
- // Parameter group dispatch: merge grouped params into the query hash
377
+ // Parameter group dispatch: callers pass a typed variant class instance
378
+ // (e.g. `WorkOS::ParentResourceById`); we pattern-match on its class
379
+ // and forward its readers into the query hash.
322
380
  for (const group of op.parameterGroups ?? []) {
323
381
  const prop = fieldName(group.name);
324
382
  if (group.optional) {
325
383
  lines.push(` if ${prop}`);
326
- lines.push(` case ${prop}[:type]`);
384
+ lines.push(` case ${prop}`);
327
385
  } else {
328
- lines.push(` case ${prop}[:type]`);
386
+ lines.push(` case ${prop}`);
329
387
  }
330
388
  for (const variant of group.variants) {
331
- lines.push(` when ${rubyStringLit(variant.name)}`);
389
+ const variantClass = variantClassRef(group, variant.name);
390
+ lines.push(` when ${variantClass}`);
332
391
  for (const p of variant.parameters) {
333
- lines.push(` params[${rubyStringLit(p.name)}] = ${prop}[:${fieldName(p.name)}]`);
392
+ lines.push(` params[${rubyStringLit(p.name)}] = ${prop}.${fieldName(p.name)}`);
334
393
  }
335
394
  }
395
+ lines.push(` else`);
396
+ lines.push(` raise ArgumentError, ${dispatchErrorLiteral(group, prop, variantClassRef)}`);
336
397
  lines.push(' end');
337
398
  if (group.optional) {
338
399
  lines.push(' end');
@@ -341,8 +402,12 @@ function emitMethod(args: {
341
402
  }
342
403
  }
343
404
 
344
- // Request body
345
- const hasBody = bodyFields.length > 0 && !['get', 'head'].includes(method_http);
405
+ // Request body. Emit when there are non-group body fields OR a parameter
406
+ // group dispatches into the body the latter case matters when an
407
+ // operation's body is exclusively managed by a group (e.g.
408
+ // update_organization_membership's `role`), where filtering the group's
409
+ // leaves leaves bodyFields empty but the request still needs a payload.
410
+ const hasBody = (bodyFields.length > 0 && !['get', 'head'].includes(method_http)) || (hasGroups && hasBodyMethod);
346
411
 
347
412
  if (hasBody) {
348
413
  const bodyEntries: string[] = [];
@@ -355,35 +420,44 @@ function emitMethod(args: {
355
420
  const optKey = fc === 'client_secret' ? 'api_key' : fc;
356
421
  bodyEntries.push(`${rubyStringLit(fc)} => (request_options[:${optKey}] || @client.${clientProp})`);
357
422
  }
423
+ // Track whether any literal entry can be nil — defaults/inferFromClient
424
+ // resolve to non-nil values, so only optional body kwargs are nilable.
425
+ let bodyHasNilable = false;
358
426
  for (const f of bodyFields) {
359
427
  if (hiddenParams.has(f.name)) continue;
360
428
  bodyEntries.push(`${rubyStringLit(f.name)} => ${bodyKwargName(f.name)}`);
429
+ if (!f.required) bodyHasNilable = true;
361
430
  }
431
+ const bodyCompact = bodyHasNilable ? '.compact' : '';
362
432
  lines.push(' body = {');
363
433
  for (let i = 0; i < bodyEntries.length; i++) {
364
434
  const sep = i === bodyEntries.length - 1 ? '' : ',';
365
435
  lines.push(` ${bodyEntries[i]}${sep}`);
366
436
  }
367
- lines.push(' }.compact');
437
+ lines.push(` }${bodyCompact}`);
368
438
 
369
439
  // Parameter group dispatch into body for POST/PUT/PATCH so sensitive
370
440
  // fields (passwords, role slugs) never leak into the URL query string.
371
441
  // DELETE groups are already handled via query above (groupsGoToQuery).
442
+ // Callers pass a typed variant class instance and we pattern-match on it.
372
443
  if (hasGroups && hasBodyMethod) {
373
444
  for (const group of op.parameterGroups ?? []) {
374
445
  const prop = fieldName(group.name);
375
446
  if (group.optional) {
376
447
  lines.push(` if ${prop}`);
377
- lines.push(` case ${prop}[:type]`);
448
+ lines.push(` case ${prop}`);
378
449
  } else {
379
- lines.push(` case ${prop}[:type]`);
450
+ lines.push(` case ${prop}`);
380
451
  }
381
452
  for (const variant of group.variants) {
382
- lines.push(` when ${rubyStringLit(variant.name)}`);
453
+ const variantClass = variantClassRef(group, variant.name);
454
+ lines.push(` when ${variantClass}`);
383
455
  for (const p of variant.parameters) {
384
- lines.push(` body[${rubyStringLit(p.name)}] = ${prop}[:${fieldName(p.name)}]`);
456
+ lines.push(` body[${rubyStringLit(p.name)}] = ${prop}.${fieldName(p.name)}`);
385
457
  }
386
458
  }
459
+ lines.push(` else`);
460
+ lines.push(` raise ArgumentError, ${dispatchErrorLiteral(group, prop, variantClassRef)}`);
387
461
  lines.push(' end');
388
462
  if (group.optional) {
389
463
  lines.push(' end');
@@ -719,8 +793,9 @@ function buildYardDoc(
719
793
  queryParams: Parameter[],
720
794
  bodyFields: { name: string; required: boolean; type: TypeRef; description?: string; deprecated?: boolean }[],
721
795
  hiddenParams: Set<string>,
722
- bodyFieldRenames?: Map<string, string>,
723
- listWrapperModels?: Map<string, Model>,
796
+ bodyFieldRenames: Map<string, string> | undefined,
797
+ listWrapperModels: Map<string, Model> | undefined,
798
+ variantClassRef: (group: { name: string }, variantName: string) => string,
724
799
  ): string[] {
725
800
  const lines: string[] = [];
726
801
  const summary = op.description ?? `${op.httpMethod.toUpperCase()} ${op.path}`;
@@ -764,6 +839,16 @@ function buildYardDoc(
764
839
  const deprecatedPrefix = q.deprecated ? '(deprecated) ' : '';
765
840
  lines.push(`# @param ${n} [${type}${suffix}] ${deprecatedPrefix}${oneLine(q.description)}`.trim());
766
841
  }
842
+ // Parameter group kwargs: the type bracket lists the variant classes the
843
+ // caller may pass; no extra prose needed since YARD already renders them.
844
+ for (const group of op.parameterGroups ?? []) {
845
+ const n = fieldName(group.name);
846
+ if (emittedParamNames.has(n)) continue;
847
+ emittedParamNames.add(n);
848
+ const variantTypes = group.variants.map((v) => variantClassRef(group, v.name)).join(', ');
849
+ const suffix = group.optional ? ', nil' : '';
850
+ lines.push(`# @param ${n} [${variantTypes}${suffix}] Identifies the ${group.name.replace(/_/g, ' ')}.`);
851
+ }
767
852
  lines.push(`# @param request_options [Hash] (see WorkOS::Types::RequestOptions)`);
768
853
 
769
854
  // Return type: void for unknown-primitive, ListStruct for list wrappers and
@@ -797,3 +882,17 @@ void methodName;
797
882
  function rubyStringLit(s: string): string {
798
883
  return `'${s.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
799
884
  }
885
+
886
+ /**
887
+ * Build a Ruby double-quoted string expression for the `else raise ArgumentError`
888
+ * arm of a parameter-group dispatcher. Lists the expected variant classes and
889
+ * interpolates the actual class of the value the caller passed.
890
+ */
891
+ function dispatchErrorLiteral(
892
+ group: { name: string; variants: { name: string }[] },
893
+ prop: string,
894
+ variantClassRef: (group: { name: string }, variantName: string) => string,
895
+ ): string {
896
+ const expected = group.variants.map((v) => variantClassRef(group, v.name)).join(', ');
897
+ return `"expected ${prop} to be one of: ${expected}, got #{${prop}.class}"`;
898
+ }
package/src/ruby/tests.ts CHANGED
@@ -1,8 +1,23 @@
1
1
  import type { ApiSpec, EmitterContext, GeneratedFile, Model, Operation, ResolvedWrapper, TypeRef } from '@workos/oagen';
2
- import { className, fileName, fieldName, safeParamName, servicePropertyName, resolveMethodName } from './naming.js';
3
- import { buildResolvedLookup, groupByMount, lookupResolved, buildHiddenParams } from '../shared/resolved-ops.js';
2
+ import {
3
+ className,
4
+ fileName,
5
+ fieldName,
6
+ safeParamName,
7
+ scopedGroupVariantClassName,
8
+ servicePropertyName,
9
+ resolveMethodName,
10
+ } from './naming.js';
11
+ import {
12
+ buildResolvedLookup,
13
+ groupByMount,
14
+ lookupResolved,
15
+ buildHiddenParams,
16
+ collectBodyFieldTypes,
17
+ } from '../shared/resolved-ops.js';
4
18
  import { isListWrapperModel, isListMetadataModel } from '../shared/model-utils.js';
5
19
  import { resolveWrapperParams } from '../shared/wrapper-utils.js';
20
+ import { buildGroupOwnerMap, pickVariantParamType } from './parameter-groups.js';
6
21
 
7
22
  /**
8
23
  * Generate Ruby Minitest test files for each service and per-method.
@@ -17,10 +32,12 @@ export function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile
17
32
  const files: GeneratedFile[] = [];
18
33
 
19
34
  const groups = groupByMount(ctx);
35
+ const models = spec.models as Model[];
20
36
  const modelByName = new Map<string, Model>();
21
- for (const m of spec.models as Model[]) modelByName.set(m.name, m);
37
+ for (const m of models) modelByName.set(m.name, m);
22
38
 
23
39
  const lookup = buildResolvedLookup(ctx);
40
+ const groupOwners = buildGroupOwnerMap(ctx);
24
41
 
25
42
  for (const [mountTarget, group] of groups) {
26
43
  const cls = className(mountTarget);
@@ -68,31 +85,63 @@ export function generateTests(spec: ApiSpec, ctx: EmitterContext): GeneratedFile
68
85
 
69
86
  const resolved = lookupResolved(op, lookup);
70
87
  const hiddenParams = buildHiddenParams(resolved);
71
- const callArgs = buildCallArgsStub(op, modelByName, hiddenParams);
88
+ const callArgs = buildCallArgsStub(op, modelByName, hiddenParams, groupOwners, models);
89
+ const bodyMatcher = buildBodyMatcher(op, modelByName, hiddenParams, models);
72
90
 
73
91
  // Collect method info for the parameterized 401 test (T20).
74
92
  authMethodManifest.push({ method, httpMethodSym, stubUrl, callArgs });
75
93
 
76
94
  const stubRegex = stubUrlRegex(stubUrl);
77
95
  lines.push(` def test_${method}_returns_expected_result`);
96
+ lines.push(` stub_request(${httpMethodSym}, ${stubRegex})`);
97
+ if (bodyMatcher) lines.push(` .with(body: ${bodyMatcher})`);
78
98
  if (isList) {
79
- lines.push(` stub_request(${httpMethodSym}, ${stubRegex})`);
80
99
  lines.push(` .to_return(body: '{"data": [], "list_metadata": {}}', status: 200)`);
81
100
  lines.push(` result = @client.${prop}.${method}(${callArgs})`);
82
101
  lines.push(' assert_kind_of WorkOS::Types::ListStruct, result');
83
102
  } else if (op.response.kind === 'primitive') {
84
- lines.push(` stub_request(${httpMethodSym}, ${stubRegex})`);
85
103
  lines.push(` .to_return(body: "{}", status: 200)`);
86
104
  lines.push(` result = @client.${prop}.${method}(${callArgs})`);
87
105
  lines.push(' assert_nil result');
88
106
  } else {
89
- lines.push(` stub_request(${httpMethodSym}, ${stubRegex})`);
90
107
  lines.push(` .to_return(body: "{}", status: 200)`);
91
108
  lines.push(` result = @client.${prop}.${method}(${callArgs})`);
92
109
  lines.push(' refute_nil result');
93
110
  }
94
111
  lines.push(' end');
95
112
 
113
+ // Per-variant tests: for every parameter group with more than one
114
+ // variant, emit one extra test per non-first variant so the second/third
115
+ // arm of the dispatcher gets exercised. Without this, a wrong wire-name
116
+ // mapping in (e.g.) ResourceTargetByExternalId would slip through.
117
+ for (const group of op.parameterGroups ?? []) {
118
+ for (let vi = 1; vi < group.variants.length; vi++) {
119
+ const variant = group.variants[vi];
120
+ const overrides = new Map<string, number>([[group.name, vi]]);
121
+ const variantCallArgs = buildCallArgsStub(op, modelByName, hiddenParams, groupOwners, models, overrides);
122
+ const variantBodyMatcher = buildBodyMatcher(op, modelByName, hiddenParams, models, overrides);
123
+ const suffix = `with_${fieldName(group.name)}_${fieldName(variant.name)}`;
124
+ lines.push('');
125
+ lines.push(` def test_${method}_${suffix}_returns_expected_result`);
126
+ lines.push(` stub_request(${httpMethodSym}, ${stubRegex})`);
127
+ if (variantBodyMatcher) lines.push(` .with(body: ${variantBodyMatcher})`);
128
+ if (isList) {
129
+ lines.push(` .to_return(body: '{"data": [], "list_metadata": {}}', status: 200)`);
130
+ lines.push(` result = @client.${prop}.${method}(${variantCallArgs})`);
131
+ lines.push(' assert_kind_of WorkOS::Types::ListStruct, result');
132
+ } else if (op.response.kind === 'primitive') {
133
+ lines.push(` .to_return(body: "{}", status: 200)`);
134
+ lines.push(` result = @client.${prop}.${method}(${variantCallArgs})`);
135
+ lines.push(' assert_nil result');
136
+ } else {
137
+ lines.push(` .to_return(body: "{}", status: 200)`);
138
+ lines.push(` result = @client.${prop}.${method}(${variantCallArgs})`);
139
+ lines.push(' refute_nil result');
140
+ }
141
+ lines.push(' end');
142
+ }
143
+ }
144
+
96
145
  // Wrapper tests (union split variants).
97
146
  if (resolved?.wrappers && resolved.wrappers.length > 0) {
98
147
  for (const wrapper of resolved.wrappers) {
@@ -278,8 +327,19 @@ function roundTripStub(ref: TypeRef, enumNames: Set<string>): string {
278
327
  }
279
328
  }
280
329
 
281
- /** Build minimal placeholder arguments for calling the SDK method from a test. */
282
- function buildCallArgsStub(op: Operation, modelByName: Map<string, Model>, hiddenParams: Set<string>): string {
330
+ /** Build minimal placeholder arguments for calling the SDK method from a test.
331
+ * `variantOverrides` selects a non-zero variant index per group; absent groups
332
+ * default to variant 0. Used to emit per-variant test cases that exercise the
333
+ * second/third arm of each parameter-group dispatcher.
334
+ */
335
+ function buildCallArgsStub(
336
+ op: Operation,
337
+ modelByName: Map<string, Model>,
338
+ hiddenParams: Set<string>,
339
+ groupOwners: Map<string, string>,
340
+ models: Model[],
341
+ variantOverrides: Map<string, number> = new Map(),
342
+ ): string {
283
343
  const parts: string[] = [];
284
344
  const seen = new Set<string>();
285
345
 
@@ -323,24 +383,104 @@ function buildCallArgsStub(op: Operation, modelByName: Map<string, Model>, hidde
323
383
  parts.push(`${name}: ${stubValueFor(q.type)}`);
324
384
  }
325
385
 
326
- // Required parameter group kwargs.
386
+ // Parameter group kwargs (required and optional): instantiate the first
387
+ // variant's class. Optional groups are exercised too so the dispatcher
388
+ // code path is covered — passing nothing would skip the body block and
389
+ // hide silent-drop bugs (see workos/oagen-emitters#66).
390
+ //
391
+ // Variant param types are recovered from the body model: the IR's leaf type
392
+ // is often a bare primitive (`role_slugs: string`) even when the body model
393
+ // declares a richer shape (`Array<String>`). Stubbing without recovery would
394
+ // pass `"stub"` to `RoleMultiple.new(role_slugs:)` while the class signature
395
+ // declares `T::Array[String]` — the test passes locally but ships an invalid
396
+ // wire body the API rejects.
397
+ const bodyFieldTypes = collectBodyFieldTypes(op, models);
327
398
  for (const group of op.parameterGroups ?? []) {
328
- if (group.optional) continue;
329
399
  const name = fieldName(group.name);
330
400
  if (seen.has(name)) continue;
331
401
  seen.add(name);
332
- // Stub as a hash with the first variant's type discriminant.
333
- const firstVariant = group.variants[0];
334
- if (firstVariant) {
335
- parts.push(`${name}: { type: "${firstVariant.name}" }`);
336
- } else {
337
- parts.push(`${name}: {}`);
402
+ const idx = variantOverrides.get(group.name) ?? 0;
403
+ const variant = group.variants[idx];
404
+ if (variant) {
405
+ const owner = groupOwners.get(group.name);
406
+ if (!owner) {
407
+ throw new Error(`No owner mount target found for parameter group '${group.name}'`);
408
+ }
409
+ const variantClass = scopedGroupVariantClassName(owner, group.name, variant.name);
410
+ const fieldStubs = variant.parameters
411
+ .map((p) => `${fieldName(p.name)}: ${stubValueFor(pickVariantParamType(p.type, bodyFieldTypes.get(p.name)))}`)
412
+ .join(', ');
413
+ parts.push(`${name}: ${variantClass}.new(${fieldStubs})`);
338
414
  }
339
415
  }
340
416
 
341
417
  return parts.join(', ');
342
418
  }
343
419
 
420
+ /**
421
+ * Build a Ruby `hash_including(...)` matcher describing the wire body the
422
+ * SDK should send for an operation whose body is constructed (in part) by a
423
+ * parameter-group dispatcher. Returns `null` for operations without body
424
+ * groups — those are still stubbed without a body matcher.
425
+ *
426
+ * The matcher includes every required non-group body field plus the first
427
+ * variant's wire-name leaves for each group dispatched into the body. This
428
+ * catches regressions where the dispatcher silently drops a passed group
429
+ * (the original `update_organization_membership` regression).
430
+ */
431
+ function buildBodyMatcher(
432
+ op: Operation,
433
+ modelByName: Map<string, Model>,
434
+ hiddenParams: Set<string>,
435
+ models: Model[],
436
+ variantOverrides: Map<string, number> = new Map(),
437
+ ): string | null {
438
+ const httpMethod = op.httpMethod.toLowerCase();
439
+ const hasBodyMethod = !['get', 'head', 'delete'].includes(httpMethod);
440
+ const hasGroups = (op.parameterGroups?.length ?? 0) > 0;
441
+ if (!hasBodyMethod || !hasGroups) return null;
442
+
443
+ const groupedParamNames = new Set<string>();
444
+ for (const group of op.parameterGroups ?? []) {
445
+ for (const variant of group.variants) {
446
+ for (const p of variant.parameters) groupedParamNames.add(p.name);
447
+ }
448
+ }
449
+
450
+ const entries: string[] = [];
451
+
452
+ // Required non-group body fields, keyed by wire name.
453
+ if (op.requestBody) {
454
+ const bodyModel = resolveBodyModel(op.requestBody, modelByName);
455
+ if (bodyModel) {
456
+ for (const f of bodyModel.fields) {
457
+ if (!f.required) continue;
458
+ if (hiddenParams.has(f.name)) continue;
459
+ if (groupedParamNames.has(f.name)) continue;
460
+ entries.push(`"${f.name}" => ${stubValueFor(f.type)}`);
461
+ }
462
+ }
463
+ }
464
+
465
+ // Selected variant of each group: its leaves get pumped into the body. The
466
+ // matcher value must use the recovered (body-model) type, not the IR leaf —
467
+ // see buildCallArgsStub for the same reasoning. Without this, the matcher
468
+ // shape diverges from what the SDK actually sends.
469
+ const bodyFieldTypes = collectBodyFieldTypes(op, models);
470
+ for (const group of op.parameterGroups ?? []) {
471
+ const idx = variantOverrides.get(group.name) ?? 0;
472
+ const variant = group.variants[idx];
473
+ if (!variant) continue;
474
+ for (const p of variant.parameters) {
475
+ const recovered = pickVariantParamType(p.type, bodyFieldTypes.get(p.name));
476
+ entries.push(`"${p.name}" => ${stubValueFor(recovered)}`);
477
+ }
478
+ }
479
+
480
+ if (entries.length === 0) return null;
481
+ return `hash_including(${entries.join(', ')})`;
482
+ }
483
+
344
484
  function resolveBodyModel(ref: TypeRef, modelByName: Map<string, Model>): Model | null {
345
485
  if (ref.kind === 'model') return modelByName.get(ref.name) ?? null;
346
486
  if (ref.kind === 'nullable') return resolveBodyModel(ref.inner, modelByName);
@@ -417,7 +557,10 @@ function stubValueFor(ref: TypeRef): string {
417
557
  return `nil`;
418
558
  }
419
559
  case 'array':
420
- return `[]`;
560
+ // Single-element array — exercises the wire shape under hash_including
561
+ // matchers. An empty `[]` would match `"role_slugs": []` on the wire,
562
+ // hiding regressions where the SDK serializes the wrong type.
563
+ return `[${stubValueFor(ref.items)}]`;
421
564
  case 'map':
422
565
  return `{}`;
423
566
  case 'enum':
@@ -255,4 +255,81 @@ describe('dotnet/models', () => {
255
255
  expect(orgFile).toBeDefined();
256
256
  expect(orgFile.content).toContain('List<OrganizationDomain>');
257
257
  });
258
+
259
+ it('emits internal set on discriminator property of base class', () => {
260
+ const models: Model[] = [
261
+ {
262
+ name: 'EventSchema',
263
+ fields: [
264
+ { name: 'id', type: { kind: 'primitive', type: 'string' }, required: true },
265
+ { name: 'event', type: { kind: 'primitive', type: 'string' }, required: true },
266
+ {
267
+ name: 'data',
268
+ type: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } },
269
+ required: true,
270
+ },
271
+ ],
272
+ },
273
+ {
274
+ name: 'UserCreated',
275
+ fields: [
276
+ { name: 'id', type: { kind: 'primitive', type: 'string' }, required: true },
277
+ { name: 'event', type: { kind: 'literal', value: 'user.created' }, required: true },
278
+ { name: 'data', type: { kind: 'model', name: 'UserCreatedData' }, required: true },
279
+ ],
280
+ },
281
+ {
282
+ name: 'UserCreatedData',
283
+ fields: [{ name: 'user_id', type: { kind: 'primitive', type: 'string' }, required: true }],
284
+ },
285
+ ];
286
+
287
+ primeEnumAliases([]);
288
+ const discCtx = {
289
+ discriminatorBases: new Set(['EventSchema']),
290
+ variantToBase: new Map([['UserCreated', 'EventSchema']]),
291
+ discriminatorProperties: new Map([['EventSchema', 'event']]),
292
+ };
293
+ const files = generateModels(models, { ...ctx, spec: { ...emptySpec, models } }, discCtx);
294
+
295
+ const baseFile = files.find((f) => f.path.includes('EventSchema.cs'))!;
296
+ expect(baseFile).toBeDefined();
297
+
298
+ // The discriminator property "event" should have internal set
299
+ expect(baseFile.content).toContain('Event { get; internal set; }');
300
+ // Non-discriminator required fields should NOT have internal set
301
+ expect(baseFile.content).toContain('Id { get; set; }');
302
+ });
303
+
304
+ it('adds remarks to dictionary accessors on discriminator base class', () => {
305
+ const models: Model[] = [
306
+ {
307
+ name: 'EventSchema',
308
+ fields: [
309
+ { name: 'id', type: { kind: 'primitive', type: 'string' }, required: true },
310
+ { name: 'event', type: { kind: 'primitive', type: 'string' }, required: true },
311
+ {
312
+ name: 'data',
313
+ type: { kind: 'map', valueType: { kind: 'primitive', type: 'unknown' } },
314
+ required: true,
315
+ },
316
+ ],
317
+ },
318
+ ];
319
+
320
+ primeEnumAliases([]);
321
+ const discCtx = {
322
+ discriminatorBases: new Set(['EventSchema']),
323
+ variantToBase: new Map<string, string>(),
324
+ discriminatorProperties: new Map([['EventSchema', 'event']]),
325
+ };
326
+ const files = generateModels(models, { ...ctx, spec: { ...emptySpec, models } }, discCtx);
327
+
328
+ const baseFile = files.find((f) => f.path.includes('EventSchema.cs'))!;
329
+ expect(baseFile).toBeDefined();
330
+
331
+ // Dictionary accessors on discriminator bases should have a remarks note
332
+ expect(baseFile.content).toContain('/// <remarks>');
333
+ expect(baseFile.content).toContain('forward-compatible');
334
+ });
258
335
  });