@voxgig/apidef 8.28.1 → 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 (49) 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 +87 -18
  11. package/dist/guide/heuristic01.js.map +1 -1
  12. package/dist/model.d.ts +1 -0
  13. package/dist/parse.d.ts +2 -1
  14. package/dist/parse.js +65 -18
  15. package/dist/parse.js.map +1 -1
  16. package/dist/transform/entity.js +3 -3
  17. package/dist/transform/entity.js.map +1 -1
  18. package/dist/transform/field.d.ts +2 -1
  19. package/dist/transform/field.js +33 -21
  20. package/dist/transform/field.js.map +1 -1
  21. package/dist/transform/flowstep.js +21 -1
  22. package/dist/transform/flowstep.js.map +1 -1
  23. package/dist/transform/operation.js +13 -24
  24. package/dist/transform/operation.js.map +1 -1
  25. package/dist/transform/top.js +8 -0
  26. package/dist/transform/top.js.map +1 -1
  27. package/dist/tsconfig.tsbuildinfo +1 -1
  28. package/dist/utility.d.ts +10 -2
  29. package/dist/utility.js +177 -28
  30. package/dist/utility.js.map +1 -1
  31. package/dist/yamlalias.d.ts +3 -0
  32. package/dist/yamlalias.js +269 -0
  33. package/dist/yamlalias.js.map +1 -0
  34. package/model/apidef.aontu +1 -0
  35. package/package.json +1 -1
  36. package/src/builder/entity/entity.ts +1 -1
  37. package/src/builder/entity/info.ts +1 -1
  38. package/src/guide/graphql01.ts +9 -3
  39. package/src/guide/guide.ts +2 -10
  40. package/src/guide/heuristic01.ts +101 -20
  41. package/src/model.ts +1 -0
  42. package/src/parse.ts +68 -26
  43. package/src/transform/entity.ts +5 -5
  44. package/src/transform/field.ts +39 -21
  45. package/src/transform/flowstep.ts +24 -1
  46. package/src/transform/operation.ts +15 -27
  47. package/src/transform/top.ts +9 -0
  48. package/src/utility.ts +204 -28
  49. package/src/yamlalias.ts +295 -0
@@ -151,6 +151,7 @@ main: kit: type: type({ # Reusable model types.
151
151
  wo?: boolean # Whether the field is write-only.
152
152
  de?: boolean # Whether the field is deprecated.
153
153
  fo?: string # Format declared by the source schema.
154
+ syn?: boolean # Whether apidef added the field with no schema property declaring it.
154
155
  }
155
156
 
156
157
  %point-args: { # One operation argument.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voxgig/apidef",
3
- "version": "8.28.1",
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,
13
- itemEnvelopeTransform, answersPage, pageRecords,
12
+ recordLists,
13
+ singleEnvelope,
14
+ authExchangeOp, specSecuredByDefault, itemEnvelopeKey,
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(
@@ -1011,8 +1039,10 @@ function RenameParams(spec: TaskSpec) {
1011
1039
 
1012
1040
  const origParams = []
1013
1041
 
1014
- // A path whose read answers a page has a trailing parameter that filters it.
1015
- const listed = pathAnswersPage(pathdesc.def, pathStr, ment.pm, work.listed)
1042
+ // A trailing parameter filters a path whose read answers a page of records
1043
+ // or a map of them, and picks the record a random route answers.
1044
+ const filtered = pathAnswersPage(pathdesc.def, pathStr, ment.pm, work.listed) ||
1045
+ pathAnswersRecordMap(pathdesc.def) || randomRoute(parts)
1016
1046
 
1017
1047
  for (let partI = 0; partI < parts.length; partI++) {
1018
1048
  let partStr = parts[partI]
@@ -1115,7 +1145,7 @@ function RenameParams(spec: TaskSpec) {
1115
1145
  else if (
1116
1146
  lastPart
1117
1147
  && not_exact_id
1118
- && !listed
1148
+ && !filtered
1119
1149
  && (!hasParent
1120
1150
  || (
1121
1151
  parentName === entdesc.name
@@ -1288,7 +1318,9 @@ function FindActions(spec: TaskSpec) {
1288
1318
  ) {
1289
1319
  if (isParam(thirdLastPart) && isVerb(secondLastPart) && isVerb(lastPart)) {
1290
1320
  const oldActionName = secondLastPart + '/' + lastPart
1291
- const actionName = secondLastPartCanon + '_' + lastPartCanon
1321
+ // `actions` only gathers the verbs: /{id}/actions/cancel is cancel.
1322
+ const actionName = 'action' === secondLastPartCanon ? lastPartCanon :
1323
+ secondLastPartCanon + '_' + lastPartCanon
1292
1324
  updateAction(methodName, oldActionName, actionName, entdesc, pathdesc,
1293
1325
  'ent-param-3rd-last')
1294
1326
  }
@@ -1378,6 +1410,36 @@ function ResolveOperation(spec: TaskSpec) {
1378
1410
  }
1379
1411
 
1380
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
+
1381
1443
  function ResolveTransform(spec: TaskSpec) {
1382
1444
  const mdesc = spec.node.val
1383
1445
  const ment = mdesc.MethodEntity
@@ -1396,9 +1458,9 @@ function ResolveTransform(spec: TaskSpec) {
1396
1458
 
1397
1459
  const op = pathdesc.op
1398
1460
 
1399
- // 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.
1400
1463
  const transform: Record<string, any> = {
1401
- req: undefined,
1402
1464
  res: undefined,
1403
1465
  }
1404
1466
 
@@ -1422,7 +1484,9 @@ function ResolveTransform(spec: TaskSpec) {
1422
1484
  // A list reads records, so an object named for the entity does not win over
1423
1485
  // a list of them beside it, such as the matches beside the competition a
1424
1486
  // page of them repeats. The list is found in the same parts the name is.
1425
- 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
1426
1490
  const holdsRecord = (prop: any) => isEntityWrapperProp(prop) &&
1427
1491
  (null == records || true === propIsList(prop))
1428
1492
 
@@ -1432,13 +1496,17 @@ function ResolveTransform(spec: TaskSpec) {
1432
1496
  else if (named && holdsRecord(partprops?.[entdesc.name])) {
1433
1497
  transform.res = '`body.' + entdesc.name + '`'
1434
1498
  }
1499
+ else if ('list' === opname && named &&
1500
+ recordLists(partprops ?? {}).includes(pluralize(entdesc.name))) {
1501
+ transform.res = '`body.' + pluralize(entdesc.name) + '`'
1502
+ }
1435
1503
  else if (resprops) {
1436
1504
  // The wrapper is often named for the CARDINALITY rather than the
1437
1505
  // entity — `{item: {...}}` from a load, `{items: [...]}` from a list —
1438
1506
  // which the entity-name rules above cannot see. Left unwrapped, list()
1439
1507
  // hands back the envelope where the caller expects an array, and the
1440
1508
  // envelope key is mistaken for a field of the entity.
1441
- const envelope = envelopeProp(resprops, opname)
1509
+ const envelope = envelopeProp(resprops, opname, example)
1442
1510
  if (null != envelope) {
1443
1511
  transform.res = '`body.' + envelope + '`'
1444
1512
  }
@@ -1461,9 +1529,9 @@ function ResolveTransform(spec: TaskSpec) {
1461
1529
  }
1462
1530
  }
1463
1531
 
1464
- const reqschema = getRequestBodySchema(spec.data.def, mdesc)
1465
- debugpath(pathStr, methodName, 'TRANSFORM-REQ', keysof(reqschema?.properties))
1466
- transform.req = bodyRequestTransform(reqschema, [entdesc.origname, entdesc.name])
1532
+ if ('list' === opname) {
1533
+ warnListBody(spec.ctx, methodName + ' ' + pathStr, transform.res, partprops)
1534
+ }
1467
1535
 
1468
1536
  if (!isempty(transform) && null != op[opname]) {
1469
1537
  op[opname].transform = transform
@@ -1845,10 +1913,10 @@ function keyHeld(
1845
1913
  // first parameter follows the collection: one under a collection nested in it
1846
1914
  // is outside.
1847
1915
  function outsideCollection(path: string, collection: string): boolean {
1848
- if (!(path + '/').startsWith(collection + '/')) {
1916
+ if (!(guidePath(path) + '/').startsWith(collection + '/')) {
1849
1917
  return true
1850
1918
  }
1851
- const parts = path.split('/').filter((part) => '' !== part)
1919
+ const parts = guideParts(path)
1852
1920
  const first = parts.findIndex(isParam)
1853
1921
  return -1 < first && collection !== '/' + parts.slice(0, first).join('/')
1854
1922
  }
@@ -2152,9 +2220,8 @@ function inferEntityName(
2152
2220
  why: string[],
2153
2221
  ): string | null {
2154
2222
 
2155
- // Try operationId: e.g. "getUser" -> "user", "listProducts" -> "product"
2156
2223
  if (mdesc.operationId) {
2157
- const opid = canonize(mdesc.operationId)
2224
+ const opid = stripOperationVerb(canonize(mdesc.operationId))
2158
2225
  if (opid.length >= 3) {
2159
2226
  why.push('infer-opid')
2160
2227
  return opid
@@ -2417,7 +2484,7 @@ type SharingEntry = SharingRoute & { parts: string[], resource: string }
2417
2484
  function sharedRoutes(routes: SharingRoute[], records: string[]): string[] {
2418
2485
  const bycmp: Record<string, SharingEntry[]> = Object.create(null)
2419
2486
  for (const route of routes) {
2420
- const parts = route.path.split('/').filter((p) => '' !== p)
2487
+ const parts = guideParts(route.path)
2421
2488
  const resource = pathResource(parts, route.method)
2422
2489
  if (null != resource && !records.includes(route.cmp)) {
2423
2490
  (bycmp[route.cmp] = bycmp[route.cmp] ?? []).push({ ...route, parts, resource })
@@ -2590,6 +2657,20 @@ function pathAnswersPage(
2590
2657
  }
2591
2658
 
2592
2659
 
2660
+ function pathAnswersRecordMap(pathdef: any): boolean {
2661
+ return ['get', 'query'].some((method: string) => null != pathdef?.[method] &&
2662
+ answersRecordMap(getResponseSchema(successResponse(pathdef[method].responses))))
2663
+ }
2664
+
2665
+
2666
+ // A literal `random` segment before the trailing parameter.
2667
+ function randomRoute(parts: string[]): boolean {
2668
+ const last = parts.length - 1
2669
+ return 0 < last && isParam(parts[last]) && parts.slice(0, last)
2670
+ .some((part: string) => !isParam(part) && 'random' === part.toLowerCase())
2671
+ }
2672
+
2673
+
2593
2674
  // A trailing parameter addresses one record, unless the route answers a page
2594
2675
  // of records that the parameter filters; a component that some route lists
2595
2676
  // is a record, whatever it holds. Resources are named with every trailing
@@ -2841,7 +2922,7 @@ function entityParamNames(
2841
2922
 
2842
2923
  for (const pathStr of Object.keys(paths).sort(byCodePoint)) {
2843
2924
  out[pathStr] = { ...paths[pathStr] }
2844
- const parts = verbParts(pathStr.split('/').filter((p) => '' !== p))
2925
+ const parts = verbParts(guideParts(pathStr))
2845
2926
  parts.forEach((part, partI) => {
2846
2927
  if (isParam(part)) {
2847
2928
  const place = parts.slice(0, partI + 1).join('/')
package/src/model.ts CHANGED
@@ -73,6 +73,7 @@ type ModelField = {
73
73
  wo?: boolean
74
74
  de?: boolean
75
75
  fo?: string
76
+ syn?: boolean
76
77
  union?: {
77
78
  count: number
78
79
  branches: number
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