@voxgig/apidef 8.29.0 → 8.30.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +18 -0
  2. package/dist/builder/entity/entity.js +1 -1
  3. package/dist/builder/entity/entity.js.map +1 -1
  4. package/dist/builder/entity/info.js +1 -1
  5. package/dist/builder/entity/info.js.map +1 -1
  6. package/dist/guide/graphql01.js +6 -3
  7. package/dist/guide/graphql01.js.map +1 -1
  8. package/dist/guide/guide.js +2 -10
  9. package/dist/guide/guide.js.map +1 -1
  10. package/dist/guide/heuristic01.js +72 -15
  11. package/dist/guide/heuristic01.js.map +1 -1
  12. package/dist/parse.d.ts +2 -1
  13. package/dist/parse.js +65 -18
  14. package/dist/parse.js.map +1 -1
  15. package/dist/transform/entity.js +3 -3
  16. package/dist/transform/entity.js.map +1 -1
  17. package/dist/transform/field.d.ts +2 -1
  18. package/dist/transform/field.js +10 -1
  19. package/dist/transform/field.js.map +1 -1
  20. package/dist/transform/operation.js +13 -24
  21. package/dist/transform/operation.js.map +1 -1
  22. package/dist/transform/top.js +8 -0
  23. package/dist/transform/top.js.map +1 -1
  24. package/dist/tsconfig.tsbuildinfo +1 -1
  25. package/dist/utility.d.ts +9 -2
  26. package/dist/utility.js +161 -25
  27. package/dist/utility.js.map +1 -1
  28. package/dist/yamlalias.d.ts +3 -0
  29. package/dist/yamlalias.js +269 -0
  30. package/dist/yamlalias.js.map +1 -0
  31. package/package.json +1 -1
  32. package/src/builder/entity/entity.ts +1 -1
  33. package/src/builder/entity/info.ts +1 -1
  34. package/src/guide/graphql01.ts +9 -3
  35. package/src/guide/guide.ts +2 -10
  36. package/src/guide/heuristic01.ts +81 -16
  37. package/src/parse.ts +68 -26
  38. package/src/transform/entity.ts +5 -5
  39. package/src/transform/field.ts +12 -1
  40. package/src/transform/operation.ts +15 -27
  41. package/src/transform/top.ts +9 -0
  42. package/src/utility.ts +186 -25
  43. package/src/yamlalias.ts +295 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voxgig/apidef",
3
- "version": "8.29.0",
3
+ "version": "8.30.0",
4
4
  "main": "dist/apidef.js",
5
5
  "type": "commonjs",
6
6
  "types": "dist/apidef.d.ts",
@@ -56,7 +56,7 @@ function resolveEntity(
56
56
  // The text of one entity's model file.
57
57
  function entitySource(entity: any): string {
58
58
  const { model, relations } = entityAncestorSource(entity)
59
- let entityJSONIC = formatJSONIC(model).trim()
59
+ let entityJSONIC = formatJSONIC(model, { comments: false }).trim()
60
60
  entityJSONIC = entityJSONIC.substring(1, entityJSONIC.length - 1)
61
61
 
62
62
  return `# Entity: ${entity.name}\n\n` +
@@ -33,7 +33,7 @@ function resolveInfo(
33
33
 
34
34
  const modelInfo = { main: { kit: { info: kit.info } } }
35
35
 
36
- let modelDefSrc = formatJSONIC(modelInfo).trim()
36
+ let modelDefSrc = formatJSONIC(modelInfo, { comments: false }).trim()
37
37
 
38
38
  modelDefSrc =
39
39
  '# API Information\n\n' +
@@ -17,6 +17,7 @@ import {
17
17
  depluralize,
18
18
  normalizeFieldName,
19
19
  prefixLeadingDigit,
20
+ guardPrototypeName,
20
21
  } from '../utility'
21
22
 
22
23
 
@@ -351,8 +352,13 @@ function rawEntityName(typeName: string): string {
351
352
  }
352
353
 
353
354
 
355
+ function guardedName(raw: string): string {
356
+ return guardPrototypeName(prefixLeadingDigit(raw))
357
+ }
358
+
359
+
354
360
  function entityName(typeName: string): string {
355
- return prefixLeadingDigit(rawEntityName(typeName))
361
+ return guardedName(rawEntityName(typeName))
356
362
  }
357
363
 
358
364
 
@@ -361,7 +367,7 @@ function resolveEntityName(
361
367
  entities: Record<string, GuideEntity>,
362
368
  ): string {
363
369
  const raw = rawEntityName(typeName)
364
- const base = prefixLeadingDigit(raw)
370
+ const base = guardedName(raw)
365
371
  const guarded = base !== raw
366
372
 
367
373
  let out = base
@@ -369,7 +375,7 @@ function resolveEntityName(
369
375
  const held = entities[out]
370
376
  if (held.orig === typeName) return out
371
377
  const heldRaw = rawEntityName(held.orig)
372
- if (guarded === (prefixLeadingDigit(heldRaw) !== heldRaw)) return out
378
+ if (guarded === (guardedName(heldRaw) !== heldRaw)) return out
373
379
  out = base + i
374
380
  }
375
381
 
@@ -328,7 +328,8 @@ async function buildBaseGuide(ctx: ApiDefContext) {
328
328
 
329
329
  validateBaseBuide(ctx, baseguide)
330
330
 
331
- const sw = (s: string) => ctx.opts.why?.show ? s : ''
331
+ // A why comment interpolates names from the definition; keep it on its line.
332
+ const sw = (s: string) => ctx.opts.why?.show ? s.replace(/[\r\n\u2028\u2029]+/g, ' ') : ''
332
333
  const qs = (v: any) => JSON.stringify(v)
333
334
  const qt = (v: any) => '(' + qs(v) + ')'
334
335
 
@@ -397,15 +398,6 @@ async function buildBaseGuide(ctx: ApiDefContext) {
397
398
  guideBlocks.push(` op: ${opname}: transform: res: ` +
398
399
  `*${'string' === typeof res ? qt(res) : qs(res)}|top`)
399
400
  }
400
- const reqmap: any = op.transform.req
401
- if (null != reqmap && 'object' === typeof reqmap) {
402
- items(reqmap).map(([bodykey, source]: [string, any]) => {
403
- if ('string' === typeof source) {
404
- guideBlocks.push(` op: ${opname}: transform: req: ` +
405
- `${qs(bodykey)}: *${qt(source)}|top`)
406
- }
407
- })
408
- }
409
401
  })
410
402
 
411
403
  guideBlocks.push(` }`)
@@ -9,11 +9,14 @@ import { size, merge, clone, getelem, isempty, items, keysof } from '@voxgig/str
9
9
 
10
10
  import {
11
11
  isEntityWrapperProp, envelopeProp, envelopeItemRef, composedEnvelopeProp, propIsList,
12
- bodyRequestTransform, authExchangeOp, specSecuredByDefault, itemEnvelopeKey,
12
+ recordLists,
13
+ singleEnvelope,
14
+ authExchangeOp, specSecuredByDefault, itemEnvelopeKey,
13
15
  itemEnvelopeTransform, answersPage, pageRecords, answersRecordMap,
14
16
  } from '../utility'
15
17
 
16
18
  import { requestSchema } from '../transform/body'
19
+ import { findExampleObject } from '../transform/field'
17
20
 
18
21
 
19
22
  import {
@@ -66,6 +69,9 @@ import {
66
69
  pathMatch,
67
70
  pluralize,
68
71
  prefixLeadingDigit,
72
+ stripOperationVerb,
73
+ guideParts,
74
+ guidePath,
69
75
  resplitFromCmp,
70
76
  sortedEntries,
71
77
  sortedKeys,
@@ -332,7 +338,7 @@ function PreparePath(spec: TaskSpec) {
332
338
  const pathdesc = {
333
339
  path: pathstr,
334
340
  def: pathdef,
335
- parts: pathstr.split('/').filter((p: string) => '' != p),
341
+ parts: guideParts(pathstr),
336
342
  op: {}
337
343
  }
338
344
 
@@ -806,6 +812,7 @@ function ResolveEntityName(spec: TaskSpec) {
806
812
  const shaped = pathEntityName(data, mdesc, parts, pm, work.pathowner, why_shape)
807
813
  const item = itemOfCollection(data, mdesc, parts)
808
814
  const owner = null == item ? samePathOwner(mdesc, work) : null
815
+ const parent = null == item && null == owner ? collectionOwner(mdesc, parts, work) : null
809
816
  const cmp = ment.cmp as string
810
817
 
811
818
  let entname: string | null = shaped
@@ -816,6 +823,10 @@ function ResolveEntityName(spec: TaskSpec) {
816
823
  why_path.push('same-path-tag=' + owner.entname + '/' + owner.method)
817
824
  entname = owner.entname
818
825
  }
826
+ else if (null != parent && parent !== cmp) {
827
+ why_path.push('collection-tag=' + parent)
828
+ entname = parent
829
+ }
819
830
  else {
820
831
  why_path.push(...why_shape)
821
832
  }
@@ -907,6 +918,23 @@ function samePathOwner(
907
918
  }
908
919
 
909
920
 
921
+ // A method named only from its tag, on a verb route beneath an item, joins the
922
+ // entity that owns the item's collection, so its verb becomes that entity's
923
+ // action: samePathOwner's rule, one level deeper.
924
+ function collectionOwner(mdesc: MethodDesc, parts: string[], work: any): string | null {
925
+ const first = parts.findIndex(isParam)
926
+ if ('tag' !== mdesc.MethodEntity?.ref || first < 1 || first === parts.length - 1 ||
927
+ parts.slice(first + 1).some(isParam)) {
928
+ return null
929
+ }
930
+ const collection = '/' + parts.slice(0, first).join('/')
931
+ const path = Object.keys(work.pathowner).sort(byCodePoint)
932
+ .find((p: string) => collection === guidePath(p))
933
+ const owners = null == path ? {} : work.pathowner[path]
934
+ return owners.GET ?? owners.QUERY ?? owners.POST ?? null
935
+ }
936
+
937
+
910
938
  // The name a method's path shape and component give it, or null where neither
911
939
  // does. A verb on a parent takes the name pathowner holds for the parent.
912
940
  function pathEntityName(
@@ -1290,7 +1318,9 @@ function FindActions(spec: TaskSpec) {
1290
1318
  ) {
1291
1319
  if (isParam(thirdLastPart) && isVerb(secondLastPart) && isVerb(lastPart)) {
1292
1320
  const oldActionName = secondLastPart + '/' + lastPart
1293
- const actionName = secondLastPartCanon + '_' + lastPartCanon
1321
+ // `actions` only gathers the verbs: /{id}/actions/cancel is cancel.
1322
+ const actionName = 'action' === secondLastPartCanon ? lastPartCanon :
1323
+ secondLastPartCanon + '_' + lastPartCanon
1294
1324
  updateAction(methodName, oldActionName, actionName, entdesc, pathdesc,
1295
1325
  'ent-param-3rd-last')
1296
1326
  }
@@ -1380,6 +1410,36 @@ function ResolveOperation(spec: TaskSpec) {
1380
1410
  }
1381
1411
 
1382
1412
 
1413
+ // A list that reads a whole object, or drops lists of records beside the one
1414
+ // it reads, is named so its definition's author can declare it in guide.aontu.
1415
+ function warnListBody(ctx: any, where: string, res: any, props: any) {
1416
+ if (null == props || 0 === keysof(props).length) return
1417
+ if (null == res) {
1418
+ ctx?.warn?.({
1419
+ note: 'list ' + where + ' reads its whole body, an object holding no list of' +
1420
+ ' records: declare what it lists in guide.aontu',
1421
+ })
1422
+ return
1423
+ }
1424
+ const read = 'string' === typeof res ? res.match(/^`body\.([^.`]+)`$/)?.[1] : undefined
1425
+ const lists = recordLists(props)
1426
+ const dropped = null == read ? [] : lists.filter((k: string) => k !== read)
1427
+ if (0 < dropped.length) {
1428
+ ctx?.warn?.({
1429
+ note: 'list ' + where + ' reads `body.' + read + '` and drops ' +
1430
+ dropped.map((k: string) => '`' + k + '`').join(', ') +
1431
+ ': declare the one it reads in guide.aontu',
1432
+ })
1433
+ }
1434
+ else if (null != read && lists.includes(read) && read !== singleEnvelope(props, 'list')) {
1435
+ ctx?.warn?.({
1436
+ note: 'list ' + where + ' reads `body.' + read + '`, beside data of the object' +
1437
+ ' it is in: declare what it lists in guide.aontu',
1438
+ })
1439
+ }
1440
+ }
1441
+
1442
+
1383
1443
  function ResolveTransform(spec: TaskSpec) {
1384
1444
  const mdesc = spec.node.val
1385
1445
  const ment = mdesc.MethodEntity
@@ -1398,9 +1458,9 @@ function ResolveTransform(spec: TaskSpec) {
1398
1458
 
1399
1459
  const op = pathdesc.op
1400
1460
 
1401
- // Only specify transforms if they are not defaults
1461
+ // Only specify transforms if they are not defaults. The request transform
1462
+ // is the operation step's, read from the body the guide names.
1402
1463
  const transform: Record<string, any> = {
1403
- req: undefined,
1404
1464
  res: undefined,
1405
1465
  }
1406
1466
 
@@ -1424,7 +1484,9 @@ function ResolveTransform(spec: TaskSpec) {
1424
1484
  // A list reads records, so an object named for the entity does not win over
1425
1485
  // a list of them beside it, such as the matches beside the competition a
1426
1486
  // page of them repeats. The list is found in the same parts the name is.
1427
- const records = 'list' === opname && null != partprops ? envelopeProp(partprops, opname) : null
1487
+ const example = 'list' === opname ? findExampleObject(mdesc, null) : null
1488
+ const records = 'list' === opname && null != partprops ?
1489
+ envelopeProp(partprops, opname, example) : null
1428
1490
  const holdsRecord = (prop: any) => isEntityWrapperProp(prop) &&
1429
1491
  (null == records || true === propIsList(prop))
1430
1492
 
@@ -1434,13 +1496,17 @@ function ResolveTransform(spec: TaskSpec) {
1434
1496
  else if (named && holdsRecord(partprops?.[entdesc.name])) {
1435
1497
  transform.res = '`body.' + entdesc.name + '`'
1436
1498
  }
1499
+ else if ('list' === opname && named &&
1500
+ recordLists(partprops ?? {}).includes(pluralize(entdesc.name))) {
1501
+ transform.res = '`body.' + pluralize(entdesc.name) + '`'
1502
+ }
1437
1503
  else if (resprops) {
1438
1504
  // The wrapper is often named for the CARDINALITY rather than the
1439
1505
  // entity — `{item: {...}}` from a load, `{items: [...]}` from a list —
1440
1506
  // which the entity-name rules above cannot see. Left unwrapped, list()
1441
1507
  // hands back the envelope where the caller expects an array, and the
1442
1508
  // envelope key is mistaken for a field of the entity.
1443
- const envelope = envelopeProp(resprops, opname)
1509
+ const envelope = envelopeProp(resprops, opname, example)
1444
1510
  if (null != envelope) {
1445
1511
  transform.res = '`body.' + envelope + '`'
1446
1512
  }
@@ -1463,9 +1529,9 @@ function ResolveTransform(spec: TaskSpec) {
1463
1529
  }
1464
1530
  }
1465
1531
 
1466
- const reqschema = getRequestBodySchema(spec.data.def, mdesc)
1467
- debugpath(pathStr, methodName, 'TRANSFORM-REQ', keysof(reqschema?.properties))
1468
- transform.req = bodyRequestTransform(reqschema, [entdesc.origname, entdesc.name])
1532
+ if ('list' === opname) {
1533
+ warnListBody(spec.ctx, methodName + ' ' + pathStr, transform.res, partprops)
1534
+ }
1469
1535
 
1470
1536
  if (!isempty(transform) && null != op[opname]) {
1471
1537
  op[opname].transform = transform
@@ -1847,10 +1913,10 @@ function keyHeld(
1847
1913
  // first parameter follows the collection: one under a collection nested in it
1848
1914
  // is outside.
1849
1915
  function outsideCollection(path: string, collection: string): boolean {
1850
- if (!(path + '/').startsWith(collection + '/')) {
1916
+ if (!(guidePath(path) + '/').startsWith(collection + '/')) {
1851
1917
  return true
1852
1918
  }
1853
- const parts = path.split('/').filter((part) => '' !== part)
1919
+ const parts = guideParts(path)
1854
1920
  const first = parts.findIndex(isParam)
1855
1921
  return -1 < first && collection !== '/' + parts.slice(0, first).join('/')
1856
1922
  }
@@ -2154,9 +2220,8 @@ function inferEntityName(
2154
2220
  why: string[],
2155
2221
  ): string | null {
2156
2222
 
2157
- // Try operationId: e.g. "getUser" -> "user", "listProducts" -> "product"
2158
2223
  if (mdesc.operationId) {
2159
- const opid = canonize(mdesc.operationId)
2224
+ const opid = stripOperationVerb(canonize(mdesc.operationId))
2160
2225
  if (opid.length >= 3) {
2161
2226
  why.push('infer-opid')
2162
2227
  return opid
@@ -2419,7 +2484,7 @@ type SharingEntry = SharingRoute & { parts: string[], resource: string }
2419
2484
  function sharedRoutes(routes: SharingRoute[], records: string[]): string[] {
2420
2485
  const bycmp: Record<string, SharingEntry[]> = Object.create(null)
2421
2486
  for (const route of routes) {
2422
- const parts = route.path.split('/').filter((p) => '' !== p)
2487
+ const parts = guideParts(route.path)
2423
2488
  const resource = pathResource(parts, route.method)
2424
2489
  if (null != resource && !records.includes(route.cmp)) {
2425
2490
  (bycmp[route.cmp] = bycmp[route.cmp] ?? []).push({ ...route, parts, resource })
@@ -2857,7 +2922,7 @@ function entityParamNames(
2857
2922
 
2858
2923
  for (const pathStr of Object.keys(paths).sort(byCodePoint)) {
2859
2924
  out[pathStr] = { ...paths[pathStr] }
2860
- const parts = verbParts(pathStr.split('/').filter((p) => '' !== p))
2925
+ const parts = verbParts(guideParts(pathStr))
2861
2926
  parts.forEach((part, partI) => {
2862
2927
  if (isParam(part)) {
2863
2928
  const place = parts.slice(0, partI + 1).join('/')
package/src/parse.ts CHANGED
@@ -4,6 +4,7 @@ import { Jsonic } from '@tabnas/jsonic'
4
4
  import { Yaml } from '@tabnas/yaml'
5
5
 
6
6
  import { relativizePath } from './utility'
7
+ import { yamlAliasedSize, yamlAliasLimit } from './yamlalias'
7
8
 
8
9
  import { parseGraphQL } from './parse/graphql'
9
10
 
@@ -22,6 +23,7 @@ async function parse(kind: string, source: any, meta: { file: string }) {
22
23
  if ('OpenAPI' === kind) {
23
24
 
24
25
  validateSource(kind, source, meta)
26
+ validateAliases(kind, source, meta)
25
27
 
26
28
  try {
27
29
  const def = await parseOpenAPI(source, meta)
@@ -121,6 +123,7 @@ async function parseOpenAPI(source: any, _meta?: any) {
121
123
  // After resolution, so a pointer into `paths` names the key as written and a
122
124
  // parameter declared by `$ref` counts. See docs/design/derived-names.md
123
125
  normalizeColonPathParams(parsed, _meta)
126
+ dropIgnoredHeaders(parsed)
124
127
 
125
128
  const def = decycle(parsed)
126
129
 
@@ -128,6 +131,38 @@ async function parseOpenAPI(source: any, _meta?: any) {
128
131
  }
129
132
 
130
133
 
134
+ // In an OpenAPI 3 definition, a header parameter named Accept, Content-Type or
135
+ // Authorization is ignored: responses, the request body and the security
136
+ // schemes say those. Each dropped one is recorded for a warning.
137
+ const IGNORED_HEADERS = ['accept', 'content-type', 'authorization']
138
+ const IGNORED_HEADERS_KEY = 'x-apidef-ignored-headers'
139
+
140
+ function dropIgnoredHeaders(parsed: any) {
141
+ delete parsed[IGNORED_HEADERS_KEY]
142
+ if (!String(parsed.openapi ?? '').startsWith('3') || !isRecord(parsed.paths)) return
143
+
144
+ const dropped: { path: string, method?: string, name: string }[] = []
145
+ const kept = (list: any[], path: string, method?: string) => list.filter((param: any) => {
146
+ const ignored = isRecord(param) && 'header' === param.in && 'string' === typeof param.name &&
147
+ IGNORED_HEADERS.includes(param.name.toLowerCase())
148
+ if (ignored) dropped.push({ path, ...(method ? { method: method.toUpperCase() } : {}), name: param.name })
149
+ return !ignored
150
+ })
151
+
152
+ for (const path of Object.keys(parsed.paths).sort()) {
153
+ const item = parsed.paths[path]
154
+ if (!isRecord(item)) continue
155
+ if (Array.isArray(item.parameters)) item.parameters = kept(item.parameters, path)
156
+ for (const method of METHODS) {
157
+ const op = item[method]
158
+ if (isRecord(op) && Array.isArray(op.parameters)) op.parameters = kept(op.parameters, path, method)
159
+ }
160
+ }
161
+
162
+ if (0 < dropped.length) parsed[IGNORED_HEADERS_KEY] = dropped
163
+ }
164
+
165
+
131
166
  // A surrogate escape, or a raw lone surrogate unit.
132
167
  const SURROGATE_RE =
133
168
  /\\(?:u\{?|U)0*[dD][89a-fA-F][0-9a-fA-F]{2}|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
@@ -282,7 +317,6 @@ function addXRefsAndResolve(
282
317
  obj: any,
283
318
  root: any,
284
319
  visited: WeakSet<any> = new WeakSet(),
285
- expanding: Map<any, any> = new Map(),
286
320
  ) {
287
321
  if (!obj || typeof obj !== 'object') return
288
322
  if (visited.has(obj)) return
@@ -295,43 +329,37 @@ function addXRefsAndResolve(
295
329
  const val = obj[key]
296
330
  if (val && typeof val === 'object') {
297
331
  if (typeof val.$ref === 'string') {
298
- resolveRefSite(obj, key, root, visited, expanding)
332
+ resolveRefSite(val, root, visited)
299
333
  } else {
300
- addXRefsAndResolve(val, root, visited, expanding)
334
+ addXRefsAndResolve(val, root, visited)
301
335
  }
302
336
  }
303
337
  }
304
338
  }
305
339
 
306
340
 
307
- function resolveRefSite(
308
- holder: any,
309
- key: string | number,
310
- root: any,
311
- visited: WeakSet<any>,
312
- expanding: Map<any, any>,
313
- ) {
314
- const site = holder[key]
315
-
316
- const inProgress = expanding.get(site)
317
- if (undefined !== inProgress) {
318
- holder[key] = inProgress
319
- return
320
- }
321
-
341
+ // Resolved in place, as in go/parse.go: the site's own keywords win and the
342
+ // target's children stay shared, so each target is walked once.
343
+ function resolveRefSite(site: any, root: any, visited: WeakSet<any>) {
322
344
  const xref = site.$ref
323
345
  const resolved = resolvePointer(root, xref)
324
- if (resolved === undefined) {
346
+ if (undefined !== resolved) {
347
+ replaceOwnKeys(site, { ...resolved, ...refSiblings(site), 'x-ref': xref })
348
+ }
349
+ else {
325
350
  site['x-ref'] = xref
326
- addXRefsAndResolve(site, root, visited, expanding)
327
- return
328
351
  }
352
+ addXRefsAndResolve(site, root, visited)
353
+ }
329
354
 
330
- const copy = { ...resolved, ...refSiblings(site), 'x-ref': xref }
331
- holder[key] = copy
332
- expanding.set(site, copy)
333
- addXRefsAndResolve(copy, root, visited, expanding)
334
- expanding.delete(site)
355
+
356
+ // Defined, not assigned, so a key named __proto__ stays data.
357
+ function replaceOwnKeys(obj: any, src: any) {
358
+ for (const k of Object.keys(obj)) delete obj[k]
359
+ for (const k of Object.keys(src)) {
360
+ Object.defineProperty(obj, k,
361
+ { value: src[k], writable: true, enumerable: true, configurable: true })
362
+ }
335
363
  }
336
364
 
337
365
 
@@ -389,6 +417,19 @@ function followAlias(root: any, node: any, active: Set<string>): any {
389
417
  }
390
418
 
391
419
 
420
+ function validateAliases(kind: string, source: string, meta: { file: string }) {
421
+ const size = yamlAliasedSize(source)
422
+ const limit = yamlAliasLimit(source)
423
+ if (limit < size) {
424
+ throw new Error(
425
+ `@voxgig/apidef: parse: ${kind}: YAML aliases would expand the source to` +
426
+ ` about ${size} bytes, past the limit of ${limit}` +
427
+ ` (${relativizePath(meta.file)})`
428
+ )
429
+ }
430
+ }
431
+
432
+
392
433
  function validateSource(kind: string, source: any, meta: { file: string }) {
393
434
  if (typeof source !== 'string') {
394
435
  throw new Error(
@@ -413,6 +454,7 @@ export {
413
454
  decycledChild,
414
455
  normalizePathKeys,
415
456
  colonPathKeys,
457
+ IGNORED_HEADERS_KEY,
416
458
  }
417
459
 
418
460
 
@@ -23,7 +23,7 @@ import type {
23
23
  } from '../model'
24
24
 
25
25
  import {
26
- cmpRefName, depluralize, foldName, guideActive, paramName, READ_METHODS,
26
+ cmpRefName, depluralize, foldName, guideActive, guidePath, paramName, READ_METHODS,
27
27
  } from '../utility'
28
28
 
29
29
  import { byCodePoint } from '../refcount'
@@ -111,7 +111,7 @@ function mergeCollectionPaths(
111
111
 
112
112
  for (const [ename, entity] of Object.entries(entities)) {
113
113
  for (const pathStr of Object.keys(entity.path ?? {})) {
114
- const m = pathStr.match(/^((?:\/[^\/{}]+)+)\/\{[^}]+\}(\/.*)?$/)
114
+ const m = guidePath(pathStr).match(/^((?:\/[^\/{}]+)+)\/\{[^}]+\}(\/.*)?$/)
115
115
  if (!m) continue
116
116
  const rest = (m[2] ?? '').split('/').filter(Boolean)
117
117
  const item = rest.every((seg: string) => /^\{[^}]+\}$/.test(seg))
@@ -328,14 +328,14 @@ function movePath(entity: any, targetEntity: any, pathStr: string) {
328
328
 
329
329
 
330
330
  function onlyBeneath(entity: any, root: string): boolean {
331
- return Object.keys(entity?.path ?? {}).every((pathStr: string) =>
332
- root === pathStr.replace(/\/+$/, '') || pathStr.startsWith(root + '/'))
331
+ return Object.keys(entity?.path ?? {}).map(guidePath).every((pathStr: string) =>
332
+ root === pathStr || pathStr.startsWith(root + '/'))
333
333
  }
334
334
 
335
335
 
336
336
  // A path of literals only, less any trailing slash, is a collection path.
337
337
  function collectionRoot(pathStr: string): string | null {
338
- const key = pathStr.replace(/\/+$/, '')
338
+ const key = guidePath(pathStr)
339
339
  return /^(?:\/[^\/{}]+)+$/.test(key) ? key : null
340
340
  }
341
341
 
@@ -880,7 +880,7 @@ function findFieldDefs(
880
880
  getx(responses, '202 schema')
881
881
  }
882
882
  if ('list' == mop.name) {
883
- const unwrapped = unwrapArrayWrapper(fieldSets)
883
+ const unwrapped = transformRecords(fieldSets, mpoint.t?.res) ?? unwrapArrayWrapper(fieldSets)
884
884
  envelope = null == unwrapped ? composedEnvelopeProp(fieldSets, 'list') : null
885
885
  const itemkey = itemEnvelopeOf(mpoint.t?.res)
886
886
  if (unwrapped) {
@@ -1114,6 +1114,16 @@ function unwrapExample(example: any, envelope?: string | null): any {
1114
1114
  }
1115
1115
 
1116
1116
 
1117
+ // The records a list's response transform reads from one property of the body,
1118
+ // so its fields follow the list it chose among several.
1119
+ function transformRecords(schema: any, res: any): any {
1120
+ const m = 'string' === typeof res ? res.match(/^`body\.([^`.]+)`$/) : null
1121
+ const items = null == m ? null : mergedProperties(schema)?.[m[1]]?.items
1122
+ return null != items && 'object' === typeof items &&
1123
+ (null != items.properties || Array.isArray(items.allOf)) ? items : null
1124
+ }
1125
+
1126
+
1117
1127
  function unwrapArrayWrapper(schema: any): any {
1118
1128
  if (null == schema || 'object' !== typeof schema) return null
1119
1129
  // Direct list shape — caller can resolve from items directly.
@@ -1201,6 +1211,7 @@ function ownType(type: any): any {
1201
1211
 
1202
1212
  export {
1203
1213
  fieldTransform,
1214
+ findExampleObject,
1204
1215
  inferFieldsFromExamples,
1205
1216
  inferTypeFromValue,
1206
1217
  routeFieldNames,
@@ -81,9 +81,6 @@ const operationTransform: Transform = async function(
81
81
  // After patch has joined update, so each operation's routes are final.
82
82
  for (const mop of Object.values(opm)) {
83
83
  for (const mpoint of mop?.points ?? []) {
84
- if (heuristicRequest(on, mop!, mpoint)) {
85
- mpoint.t.req = undefined
86
- }
87
84
  mpoint.t.req = mpoint.t.req ?? requestDefault(on, kit.entity[entname], opm, mop!, mpoint)
88
85
  mpoint.t.res = mpoint.t.res ?? '`body`'
89
86
  }
@@ -231,28 +228,11 @@ function resolveOp(opname: OpName, on: OpEntity): undefined | ModelOp {
231
228
 
232
229
 
233
230
 
234
- // The request transform the heuristic took from the default body, still in
235
- // place where the guide selects another media type for the point.
236
- function heuristicRequest(on: OpEntity, mop: ModelOp, mpoint: ModelPoint): boolean {
237
- const chosen = guideMedia(on.guide, on.entname, mop.name, mpoint).body
238
- if (null == chosen || null == mpoint.t.req) return false
239
- const generated = bodyRequestTransform(requestSchema(on.def, mpoint.m, mpoint.o), [on.gent.name])
240
- return null != generated && sameTransform(mpoint.t.req, generated)
241
- }
242
-
243
-
244
- function sameTransform(a: any, b: any): boolean {
245
- const canon = (t: any) => 'string' === typeof t ? t :
246
- JSON.stringify(Object.keys(t ?? {}).sort().map((k: string) => [k, t[k]]))
247
- return canon(a) === canon(b)
248
- }
249
-
250
-
251
- // An array body is sent from one field of the request data, named for its
252
- // records, and never for an argument of its operation, a field another route of
253
- // its entity has, as fields span operations, or a carrier already named for an
254
- // array of another type or requiredness. Decided here, not by the guide
255
- // heuristic, as the guide's media type decides the body.
231
+ // The request transform of a point whose guide sets none, read from the body
232
+ // the guide names: an object wraps the record under the entity's name or sends
233
+ // a closed body's own properties; an array is sent from a field named for its
234
+ // records, never for an argument, another route's field, or a carrier already
235
+ // named for an array of another type or requiredness.
256
236
  function requestDefault(
257
237
  on: OpEntity, ment: ModelEntity, opm: ModelOpMap, mop: ModelOp, mpoint: ModelPoint,
258
238
  ): any {
@@ -260,8 +240,7 @@ function requestDefault(
260
240
  const chosen = media(mop.name, mpoint)
261
241
  const list = arrayRequestSchema(on.def, mpoint.m, mpoint.o, chosen)
262
242
  if (null == list) {
263
- return (null == chosen ? undefined :
264
- bodyRequestTransform(requestSchema(on.def, mpoint.m, mpoint.o, chosen), [on.gent.name])) ?? '`reqdata`'
243
+ return bodyRequestTransform(objectSchema(on.def, mpoint, chosen), [on.gent.name]) ?? '`reqdata`'
265
244
  }
266
245
  const required = true === requestDecl(on.def, mpoint.m, mpoint.o)?.required
267
246
  const others = mop.points.filter((q) => q !== mpoint)
@@ -279,6 +258,15 @@ function requestDefault(
279
258
  }
280
259
 
281
260
 
261
+ // The object body a point sends: under the media type the guide names, else
262
+ // the preferred one, else a schema declared on the request body itself.
263
+ function objectSchema(def: any, mpoint: ModelPoint, chosen?: string): any {
264
+ const declared = def?.paths?.[mpoint.o]?.[String(mpoint.m).toLowerCase()]?.requestBody
265
+ return requestSchema(def, mpoint.m, mpoint.o, chosen) ??
266
+ (null == chosen && null != declared && 'object' === typeof declared ? declared.schema : undefined)
267
+ }
268
+
269
+
282
270
  export {
283
271
  operationTransform,
284
272
  }
@@ -8,6 +8,7 @@ import {
8
8
  } from '../utility'
9
9
 
10
10
  import { METHODS } from '../resolved'
11
+ import { IGNORED_HEADERS_KEY } from '../parse'
11
12
 
12
13
  import type { TransformResult } from '../transform'
13
14
 
@@ -134,6 +135,14 @@ const topTransform = async function(
134
135
  }
135
136
  }
136
137
 
138
+ for (const ignored of def[IGNORED_HEADERS_KEY] ?? []) {
139
+ ctx.warn?.({
140
+ note: 'header parameter `' + ignored.name + '` of ' +
141
+ (null == ignored.method ? '' : ignored.method + ' ') + ignored.path +
142
+ ' ignored: OpenAPI ignores Accept, Content-Type and Authorization header parameters',
143
+ })
144
+ }
145
+
137
146
  const summary = resolveSummary(def)
138
147
  if (null != summary) {
139
148
  kit.info.summary = summary