@voxgig/apidef 8.29.0 → 8.30.1

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 +94 -27
  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 +105 -28
  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.1",
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,31 @@ 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. The verb is a singular word or a pair of them, behind an optional
924
+ // `actions`, and the entity is named for the collection; a plural word is a
925
+ // sub-collection.
926
+ function collectionOwner(mdesc: MethodDesc, parts: string[], work: any): string | null {
927
+ const first = parts.findIndex(isParam)
928
+ if ('tag' !== mdesc.MethodEntity?.ref || first < 1 || first === parts.length - 1 ||
929
+ parts.slice(first + 1).some(isParam)) {
930
+ return null
931
+ }
932
+ const words = parts.slice(first + 1)
933
+ const verb = 2 === words.length && 'action' === canonize(words[0]) ? words.slice(1) : words
934
+ if (2 < verb.length || !verb.every(isSingular)) {
935
+ return null
936
+ }
937
+ const collection = '/' + parts.slice(0, first).join('/')
938
+ const path = Object.keys(work.pathowner).sort(byCodePoint)
939
+ .find((p: string) => collection === guidePath(p))
940
+ const owners = null == path ? {} : work.pathowner[path]
941
+ const owner = owners.GET ?? owners.QUERY ?? owners.POST ?? null
942
+ return owner === canonize(parts[first - 1]) ? owner : null
943
+ }
944
+
945
+
910
946
  // The name a method's path shape and component give it, or null where neither
911
947
  // does. A verb on a parent takes the name pathowner holds for the parent.
912
948
  function pathEntityName(
@@ -1290,7 +1326,9 @@ function FindActions(spec: TaskSpec) {
1290
1326
  ) {
1291
1327
  if (isParam(thirdLastPart) && isVerb(secondLastPart) && isVerb(lastPart)) {
1292
1328
  const oldActionName = secondLastPart + '/' + lastPart
1293
- const actionName = secondLastPartCanon + '_' + lastPartCanon
1329
+ // `actions` only gathers the verbs: /{id}/actions/cancel is cancel.
1330
+ const actionName = 'action' === secondLastPartCanon ? lastPartCanon :
1331
+ secondLastPartCanon + '_' + lastPartCanon
1294
1332
  updateAction(methodName, oldActionName, actionName, entdesc, pathdesc,
1295
1333
  'ent-param-3rd-last')
1296
1334
  }
@@ -1380,6 +1418,37 @@ function ResolveOperation(spec: TaskSpec) {
1380
1418
  }
1381
1419
 
1382
1420
 
1421
+ // A list that reads a whole object, or drops lists of records beside the one
1422
+ // it reads, is named so its definition's author can declare it in guide.aontu.
1423
+ function warnListBody(ctx: any, where: string, res: any, props: any) {
1424
+ if (null == props || 0 === keysof(props).length) return
1425
+ if (null == res) {
1426
+ const what = 0 < recordLists(props).length ? 'the one record its definition declares' :
1427
+ 'an object holding no list of records'
1428
+ ctx?.warn?.({
1429
+ note: 'list ' + where + ' reads its whole body, ' + what + ': declare what it lists in guide.aontu',
1430
+ })
1431
+ return
1432
+ }
1433
+ const read = 'string' === typeof res ? res.match(/^`body\.([^.`]+)`$/)?.[1] : undefined
1434
+ const lists = recordLists(props)
1435
+ const dropped = null == read ? [] : lists.filter((k: string) => k !== read)
1436
+ if (0 < dropped.length) {
1437
+ ctx?.warn?.({
1438
+ note: 'list ' + where + ' reads `body.' + read + '` and drops ' +
1439
+ dropped.map((k: string) => '`' + k + '`').join(', ') +
1440
+ ': declare the one it reads in guide.aontu',
1441
+ })
1442
+ }
1443
+ else if (null != read && lists.includes(read) && read !== singleEnvelope(props, 'list')) {
1444
+ ctx?.warn?.({
1445
+ note: 'list ' + where + ' reads `body.' + read + '`, beside data of the object' +
1446
+ ' it is in: declare what it lists in guide.aontu',
1447
+ })
1448
+ }
1449
+ }
1450
+
1451
+
1383
1452
  function ResolveTransform(spec: TaskSpec) {
1384
1453
  const mdesc = spec.node.val
1385
1454
  const ment = mdesc.MethodEntity
@@ -1398,9 +1467,9 @@ function ResolveTransform(spec: TaskSpec) {
1398
1467
 
1399
1468
  const op = pathdesc.op
1400
1469
 
1401
- // Only specify transforms if they are not defaults
1470
+ // Only specify transforms if they are not defaults. The request transform
1471
+ // is the operation step's, read from the body the guide names.
1402
1472
  const transform: Record<string, any> = {
1403
- req: undefined,
1404
1473
  res: undefined,
1405
1474
  }
1406
1475
 
@@ -1424,7 +1493,9 @@ function ResolveTransform(spec: TaskSpec) {
1424
1493
  // A list reads records, so an object named for the entity does not win over
1425
1494
  // a list of them beside it, such as the matches beside the competition a
1426
1495
  // 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
1496
+ const example = 'list' === opname ? findExampleObject(mdesc, null) : null
1497
+ const records = 'list' === opname && null != partprops ?
1498
+ envelopeProp(partprops, opname, example) : null
1428
1499
  const holdsRecord = (prop: any) => isEntityWrapperProp(prop) &&
1429
1500
  (null == records || true === propIsList(prop))
1430
1501
 
@@ -1434,13 +1505,17 @@ function ResolveTransform(spec: TaskSpec) {
1434
1505
  else if (named && holdsRecord(partprops?.[entdesc.name])) {
1435
1506
  transform.res = '`body.' + entdesc.name + '`'
1436
1507
  }
1508
+ else if ('list' === opname && named &&
1509
+ recordLists(partprops ?? {}).includes(pluralize(entdesc.name))) {
1510
+ transform.res = '`body.' + pluralize(entdesc.name) + '`'
1511
+ }
1437
1512
  else if (resprops) {
1438
- // The wrapper is often named for the CARDINALITY rather than the
1439
- // entity — `{item: {...}}` from a load, `{items: [...]}` from a list —
1440
- // which the entity-name rules above cannot see. Left unwrapped, list()
1441
- // hands back the envelope where the caller expects an array, and the
1442
- // envelope key is mistaken for a field of the entity.
1443
- const envelope = envelopeProp(resprops, opname)
1513
+ // The wrapper is often named for the CARDINALITY rather than the entity,
1514
+ // `{item: {...}}` from a load or `{items: [...]}` from a list, which the
1515
+ // rules above cannot see. The entity's own record is never a page,
1516
+ // whatever lists it holds, though a list route may declare it.
1517
+ const own = null != rescmp && [entdesc.cmp, entdesc.name].includes(cmpRefName(rescmp))
1518
+ const envelope = own ? singleEnvelope(resprops, opname) : envelopeProp(resprops, opname, example)
1444
1519
  if (null != envelope) {
1445
1520
  transform.res = '`body.' + envelope + '`'
1446
1521
  }
@@ -1463,9 +1538,9 @@ function ResolveTransform(spec: TaskSpec) {
1463
1538
  }
1464
1539
  }
1465
1540
 
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])
1541
+ if ('list' === opname) {
1542
+ warnListBody(spec.ctx, methodName + ' ' + pathStr, transform.res, partprops)
1543
+ }
1469
1544
 
1470
1545
  if (!isempty(transform) && null != op[opname]) {
1471
1546
  op[opname].transform = transform
@@ -1661,8 +1736,7 @@ function verbOnParent(
1661
1736
  return null
1662
1737
  }
1663
1738
 
1664
- const lit = snakify(getelem(pm, -1))
1665
- if ('' === lit || depluralize(lit) !== lit) {
1739
+ if (!isSingular(getelem(pm, -1))) {
1666
1740
  return null
1667
1741
  }
1668
1742
 
@@ -1847,10 +1921,10 @@ function keyHeld(
1847
1921
  // first parameter follows the collection: one under a collection nested in it
1848
1922
  // is outside.
1849
1923
  function outsideCollection(path: string, collection: string): boolean {
1850
- if (!(path + '/').startsWith(collection + '/')) {
1924
+ if (!(guidePath(path) + '/').startsWith(collection + '/')) {
1851
1925
  return true
1852
1926
  }
1853
- const parts = path.split('/').filter((part) => '' !== part)
1927
+ const parts = guideParts(path)
1854
1928
  const first = parts.findIndex(isParam)
1855
1929
  return -1 < first && collection !== '/' + parts.slice(0, first).join('/')
1856
1930
  }
@@ -2154,9 +2228,8 @@ function inferEntityName(
2154
2228
  why: string[],
2155
2229
  ): string | null {
2156
2230
 
2157
- // Try operationId: e.g. "getUser" -> "user", "listProducts" -> "product"
2158
2231
  if (mdesc.operationId) {
2159
- const opid = canonize(mdesc.operationId)
2232
+ const opid = stripOperationVerb(canonize(mdesc.operationId))
2160
2233
  if (opid.length >= 3) {
2161
2234
  why.push('infer-opid')
2162
2235
  return opid
@@ -2397,11 +2470,8 @@ function pathResource(parts: string[], method: string): string | null {
2397
2470
  }
2398
2471
 
2399
2472
  const last = parts[parts.length - 1]
2400
- if (!READ_METHODS.includes(method) && !isParam(last)) {
2401
- const lit = snakify(last)
2402
- if ('' !== lit && depluralize(lit) === lit) {
2403
- return null
2404
- }
2473
+ if (!READ_METHODS.includes(method) && !isParam(last) && isSingular(last)) {
2474
+ return null
2405
2475
  }
2406
2476
 
2407
2477
  return canonize(pm[PATH_NAME_INDEX[pm.expr]])
@@ -2419,7 +2489,7 @@ type SharingEntry = SharingRoute & { parts: string[], resource: string }
2419
2489
  function sharedRoutes(routes: SharingRoute[], records: string[]): string[] {
2420
2490
  const bycmp: Record<string, SharingEntry[]> = Object.create(null)
2421
2491
  for (const route of routes) {
2422
- const parts = route.path.split('/').filter((p) => '' !== p)
2492
+ const parts = guideParts(route.path)
2423
2493
  const resource = pathResource(parts, route.method)
2424
2494
  if (null != resource && !records.includes(route.cmp)) {
2425
2495
  (bycmp[route.cmp] = bycmp[route.cmp] ?? []).push({ ...route, parts, resource })
@@ -2797,6 +2867,13 @@ function isParam(partStr: string) {
2797
2867
  }
2798
2868
 
2799
2869
 
2870
+ // A literal that names one thing rather than a collection.
2871
+ function isSingular(part: string): boolean {
2872
+ const lit = snakify(part)
2873
+ return '' !== lit && depluralize(lit) === lit
2874
+ }
2875
+
2876
+
2800
2877
  // A segment holding a placeholder, whole or beside other text, names no verb.
2801
2878
  function isVerb(partStr: string): boolean {
2802
2879
  return !String(partStr ?? '').includes('{')
@@ -2857,7 +2934,7 @@ function entityParamNames(
2857
2934
 
2858
2935
  for (const pathStr of Object.keys(paths).sort(byCodePoint)) {
2859
2936
  out[pathStr] = { ...paths[pathStr] }
2860
- const parts = verbParts(pathStr.split('/').filter((p) => '' !== p))
2937
+ const parts = verbParts(guideParts(pathStr))
2861
2938
  parts.forEach((part, partI) => {
2862
2939
  if (isParam(part)) {
2863
2940
  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
  }