@voxgig/apidef 8.16.0 → 8.17.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.
@@ -103,6 +103,13 @@ const METHOD_IDOP: Record<string, string> = {
103
103
  // Tried in order: the first shape a path matches decides how its entity is named.
104
104
  const ENTITY_PATH_SHAPES = ['t/p/t/', 't/p/', 'p/t/', 't/', 't/p/p']
105
105
 
106
+ // The matched part that gives each shape its name.
107
+ const PATH_NAME_INDEX: Record<string, number> = {
108
+ 't/p/t/': 2, 't/p/': 0, 'p/t/': 1, 't/': 0, 't/p/p': 0,
109
+ }
110
+
111
+ const READ_METHODS = ['GET', 'QUERY', 'HEAD', 'OPTIONS']
112
+
106
113
  const METHOD_CONSIDER_ORDER: Record<string, number> = {
107
114
  'GET': 100,
108
115
  'QUERY': 150,
@@ -130,6 +137,8 @@ async function heuristic01(ctx: ApiDefContext): Promise<Guide> {
130
137
  { select: selectCmpXrefs, apply: MeasureRef },
131
138
  { select: selectAllMethods, apply: MeasureEnvelope },
132
139
  MeasureEnvelopeItems,
140
+ { select: selectAllMethods, apply: MeasureSharing },
141
+ MeasureShared,
133
142
  {
134
143
  select: selectAllMethods, apply: [
135
144
  ResolveEntityComponent,
@@ -152,7 +161,7 @@ async function heuristic01(ctx: ApiDefContext): Promise<Guide> {
152
161
 
153
162
  const guide = result.data.guide
154
163
 
155
- mergeCollectionPaths(guide, ctx.log)
164
+ guide.metrics.count.entity -= mergeCollectionPaths(guide, ctx.log).length
156
165
 
157
166
  const metrics = guide.metrics
158
167
 
@@ -214,6 +223,7 @@ function Prepare(spec: TaskSpec) {
214
223
  pathmap: {},
215
224
  entmap: {},
216
225
  envelope: {},
226
+ sharing: { routes: [], records: {}, yields: {} },
217
227
  entity: {
218
228
  count: {
219
229
  seen: 0,
@@ -355,6 +365,36 @@ function MeasureEnvelopeItems(spec: TaskSpec) {
355
365
  }
356
366
 
357
367
 
368
+ // Records every route whose operation answers with a response component, and
369
+ // whether that component declares an `id`, before any method is named.
370
+ function MeasureSharing(spec: TaskSpec) {
371
+ const work = spec.data.work
372
+ const mdesc = spec.node.val
373
+ const parts: string[] = work.pathmap[mdesc.path].parts
374
+ const op = methodOpname(mdesc, matchEntityPath(parts), []) ?? ''
375
+ const sharing = work.sharing
376
+
377
+ const xrefs = findPotentialSchemaRefs(mdesc.path, mdesc.method, mdesc.responses, work.envelope, [])
378
+ for (const xref of xrefs) {
379
+ const m = xref.match(/\/(components\/schemas|definitions)\/(.+)$/)
380
+ if (null != m) {
381
+ const cmp = canonizeCmpName(m[2])
382
+ sharing.routes.push({ cmp, method: mdesc.method, path: mdesc.path, op })
383
+ sharing.records[cmp] = true === sharing.records[cmp] || declaresId(refSchema(spec.data.def, xref))
384
+ }
385
+ }
386
+ }
387
+
388
+
389
+ function MeasureShared(spec: TaskSpec) {
390
+ const sharing = spec.data.work.sharing
391
+ const records = Object.keys(sharing.records).filter((cmp) => sharing.records[cmp])
392
+ for (const key of sharedRoutes(sharing.routes, records)) {
393
+ sharing.yields[key] = true
394
+ }
395
+ }
396
+
397
+
358
398
  function selectAllMethods(_source: any, spec: TaskSpec): MethodDesc[] {
359
399
  const ctx = spec.ctx
360
400
 
@@ -365,6 +405,12 @@ function selectAllMethods(_source: any, spec: TaskSpec): MethodDesc[] {
365
405
  for (const [m, mdef] of sortedEntries(pdef)) {
366
406
  const method = m.toUpperCase()
367
407
 
408
+ // A path item also holds parameters, servers, summary and the like.
409
+ if (null == METHOD_CONSIDER_ORDER[method] ||
410
+ null == mdef || 'object' !== typeof mdef || Array.isArray(mdef)) {
411
+ continue
412
+ }
413
+
368
414
  caught.methods.push({
369
415
  path,
370
416
  method,
@@ -537,6 +583,8 @@ function ResolveEntityComponent(spec: TaskSpec) {
537
583
  (pathStr.includes('/' + ftag + '/') || pathStr.includes('/' + tagdesc.canon + '/'))
538
584
  && out.cmp !== tagdesc.canon
539
585
  ) {
586
+ const rescmp = out.cmp
587
+ const rescmpoccur = metrics.count.origcmprefs[out.origcmpref ?? ''] ?? 0
540
588
  out = makeMethodEntityDesc({
541
589
  ref: 'tag',
542
590
  cmp: tagdesc.canon,
@@ -544,6 +592,8 @@ function ResolveEntityComponent(spec: TaskSpec) {
544
592
  why_cmp,
545
593
  entname: tagdesc.canon,
546
594
  })
595
+ out.rescmp = rescmp
596
+ out.rescmpoccur = rescmpoccur
547
597
  why_cmp.push('tag/path=' + out.cmp)
548
598
  }
549
599
  }
@@ -674,8 +724,6 @@ function ResolveEntityName(spec: TaskSpec) {
674
724
  function RenameParams(spec: TaskSpec) {
675
725
  const ctx = spec.ctx
676
726
  const data = spec.data
677
- const guide = data.guide
678
- const metrics = guide.metrics
679
727
 
680
728
  const mdesc = spec.node.val
681
729
  const ment = mdesc.MethodEntity
@@ -728,12 +776,6 @@ function RenameParams(spec: TaskSpec) {
728
776
  return
729
777
  }
730
778
 
731
- const cmpname = mdesc.cmp
732
- const considerCmp =
733
- null != cmpname &&
734
- 0 < metrics.count.uniqschema &&
735
- mdesc.method_rate < IS_ENTCMP_METHOD_RATE
736
-
737
779
  const origParams = []
738
780
 
739
781
  for (let partI = 0; partI < parts.length; partI++) {
@@ -784,14 +826,8 @@ function RenameParams(spec: TaskSpec) {
784
826
  // actually an action
785
827
  if (
786
828
  secondLastPart
787
- && (
788
- (
789
- parentName !== entdesc.name
790
- && entdesc.name.startsWith(parentName + '_')
791
- )
792
- // || parentName === cmp.name
793
- || parentName === cmpname
794
- )
829
+ && parentName !== entdesc.name
830
+ && entdesc.name.startsWith(parentName + '_')
795
831
  ) {
796
832
  updateParamRename(
797
833
  ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
@@ -802,13 +838,6 @@ function RenameParams(spec: TaskSpec) {
802
838
  parts[partI + 1], entdesc, pathDesc, 'action-not-parent')
803
839
  }
804
840
 
805
- else if (hasParent && parentName === cmpname) {
806
- updateParamRename(
807
- ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
808
- 'id', 'id-parent-cmp')
809
- why.push('id-parent-cmp')
810
- }
811
-
812
841
  else if (hasParent && parentName === entdesc.name) {
813
842
  updateParamRename(
814
843
  ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
@@ -839,12 +868,10 @@ function RenameParams(spec: TaskSpec) {
839
868
  || entdesc.name.endsWith('_' + parentName)
840
869
  )
841
870
  )
842
- && (!considerCmp || cmpname === entdesc.name)
843
871
  ) {
844
872
  updateParamRename(
845
873
  ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
846
- 'id', 'end-id;' + methodName + ';parent=' + hasParent + '/' + parentName +
847
- ';cmp=' + considerCmp + (null == cmpname ? '' : '/' + cmpname))
874
+ 'id', 'end-id;' + methodName + ';parent=' + hasParent + '/' + parentName)
848
875
  why.push('end-id')
849
876
  }
850
877
 
@@ -881,18 +908,6 @@ function RenameParams(spec: TaskSpec) {
881
908
  }
882
909
  }
883
910
 
884
- // Primary ent id not at end!
885
- else if (
886
- hasParent
887
- && parentName === cmpname
888
- ) {
889
- updateParamRename(
890
- ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
891
- 'id', 'id-not-last')
892
-
893
- why.push('id-not-last')
894
- }
895
-
896
911
  // Not primary ent.
897
912
  else {
898
913
  why.push('default')
@@ -930,9 +945,6 @@ function RenameParams(spec: TaskSpec) {
930
945
  parentName,
931
946
  not_exact_id,
932
947
  probably_an_id,
933
- considerCmp,
934
- cmp: mdesc.cmp,
935
- cmpname,
936
948
  paramRenameCapture,
937
949
  entdesc
938
950
  }
@@ -1239,7 +1251,7 @@ function entityPathMatch_tpte(
1239
1251
  ) {
1240
1252
  const ment = mdesc.MethodEntity
1241
1253
 
1242
- const pathNameIndex = 2
1254
+ const pathNameIndex = PATH_NAME_INDEX['t/p/t/']
1243
1255
 
1244
1256
  why.push('path=t/p/t/')
1245
1257
  const origPathName = pm[pathNameIndex]
@@ -1301,12 +1313,12 @@ function verbOnParent(
1301
1313
  mdesc: any,
1302
1314
  ): null | string {
1303
1315
  const method = mdesc.method
1304
- if ('GET' === method || 'QUERY' === method || 'HEAD' === method || 'OPTIONS' === method) {
1316
+ if (READ_METHODS.includes(method)) {
1305
1317
  return null
1306
1318
  }
1307
1319
 
1308
1320
  const ment = mdesc.MethodEntity
1309
- if (1 < (ment.cmpoccur ?? 0)) {
1321
+ if (1 < (ment.rescmpoccur ?? ment.cmpoccur ?? 0)) {
1310
1322
  return null
1311
1323
  }
1312
1324
 
@@ -1316,7 +1328,7 @@ function verbOnParent(
1316
1328
  }
1317
1329
 
1318
1330
  const verb = canonize(getelem(pm, -1))
1319
- const cmp = String(ment.cmp ?? '')
1331
+ const cmp = String(ment.rescmp ?? ment.cmp ?? '')
1320
1332
  if ('' === verb || cmp === verb || cmp.endsWith('_' + verb)) {
1321
1333
  return null
1322
1334
  }
@@ -1375,7 +1387,7 @@ function entityPathMatch_tpe(
1375
1387
  pm: PathMatch, mdesc: any, why: string[]
1376
1388
  ) {
1377
1389
  const ment = mdesc.MethodEntity
1378
- const pathNameIndex = 0
1390
+ const pathNameIndex = PATH_NAME_INDEX['t/p/']
1379
1391
 
1380
1392
  why.push('path=t/p/')
1381
1393
  const origPathName = pm[pathNameIndex]
@@ -1398,7 +1410,7 @@ function entityPathMatch_pte(
1398
1410
  pm: PathMatch, mdesc: any, why: string[]
1399
1411
  ) {
1400
1412
  const ment = mdesc.MethodEntity
1401
- const pathNameIndex = 1
1413
+ const pathNameIndex = PATH_NAME_INDEX['p/t/']
1402
1414
 
1403
1415
  why.push('path=p/t/')
1404
1416
  const origPathName = pm[pathNameIndex]
@@ -1421,7 +1433,7 @@ function entityPathMatch_te(
1421
1433
  pm: PathMatch, mdesc: any, why: string[]
1422
1434
  ) {
1423
1435
  const ment = mdesc.MethodEntity
1424
- const pathNameIndex = 0
1436
+ const pathNameIndex = PATH_NAME_INDEX['t/']
1425
1437
 
1426
1438
  why.push('path=t/')
1427
1439
  const origPathName = pm[pathNameIndex]
@@ -1444,7 +1456,7 @@ function entityPathMatch_tpp(
1444
1456
  pm: PathMatch, mdesc: any, why: string[]
1445
1457
  ) {
1446
1458
  const ment = mdesc.MethodEntity
1447
- const pathNameIndex = 0
1459
+ const pathNameIndex = PATH_NAME_INDEX['t/p/p']
1448
1460
 
1449
1461
  why.push('path=t/p/p')
1450
1462
  const origPathName = pm[pathNameIndex]
@@ -1622,12 +1634,19 @@ function entityCmpMatch(
1622
1634
  || ment.path_rate < IS_ENTCMP_PATH_RATE
1623
1635
  )
1624
1636
 
1637
+ const cmpShared =
1638
+ true === data.work.sharing.yields[ment.origcmpref + ' ' + mdesc.method + ' ' + mdesc.path]
1639
+
1625
1640
  if (
1626
1641
  null != ment.cmp
1627
1642
  && entname != ment.cmp
1628
1643
  && !ment.cmp.startsWith(entname)
1629
1644
  ) {
1630
- if (cmpInfrequent) {
1645
+ if (cmpInfrequent && cmpShared) {
1646
+ why.push('cmp-shared')
1647
+ }
1648
+
1649
+ if (cmpInfrequent && !cmpShared) {
1631
1650
  why.push('cmp-primary')
1632
1651
  out.name = ment.cmp
1633
1652
  out.orig = ment.origcmp
@@ -1709,6 +1728,155 @@ function matchEntityPath(parts: string[]): PathMatch | null {
1709
1728
  }
1710
1729
 
1711
1730
 
1731
+ // The resource a method's path names by itself, as its shape names it. A
1732
+ // write to a singular trailing literal is a verb on another resource, and
1733
+ // names none.
1734
+ function pathResource(parts: string[], method: string): string | null {
1735
+ const pm = matchEntityPath(parts)
1736
+ if (null == pm) {
1737
+ return null
1738
+ }
1739
+
1740
+ const last = parts[parts.length - 1]
1741
+ if (!READ_METHODS.includes(method) && !isParam(last)) {
1742
+ const lit = snakify(last)
1743
+ if ('' !== lit && depluralize(lit) === lit) {
1744
+ return null
1745
+ }
1746
+ }
1747
+
1748
+ return canonize(pm[PATH_NAME_INDEX[pm.expr]])
1749
+ }
1750
+
1751
+
1752
+ type SharingRoute = { cmp: string, method: string, path: string, op: string }
1753
+
1754
+ type SharingEntry = SharingRoute & { parts: string[], resource: string }
1755
+
1756
+
1757
+ // The routes that keep their own path's name for the component they answer
1758
+ // with, each keyed `cmp METHOD path`: those of a component that several
1759
+ // resources share, where a record (one that declares an `id`) is never shared.
1760
+ function sharedRoutes(routes: SharingRoute[], records: string[]): string[] {
1761
+ const bycmp: Record<string, SharingEntry[]> = {}
1762
+ for (const route of routes) {
1763
+ const parts = route.path.split('/').filter((p) => '' !== p)
1764
+ const resource = pathResource(parts, route.method)
1765
+ if (null != resource && !records.includes(route.cmp)) {
1766
+ (bycmp[route.cmp] = bycmp[route.cmp] ?? []).push({ ...route, parts, resource })
1767
+ }
1768
+ }
1769
+
1770
+ const taking: SharingEntry[] = []
1771
+ for (const cmp of Object.keys(bycmp).sort()) {
1772
+ const names = new Set(bycmp[cmp].map((entry) => entry.resource))
1773
+ const counted = bycmp[cmp].filter((entry) => !isSharingView(entry, names))
1774
+ const group = aliasGroups(counted)
1775
+ if (new Set(counted.map((entry) => group[entry.resource])).size < 2) {
1776
+ continue
1777
+ }
1778
+ const members: Record<string, number> = {}
1779
+ for (const name of new Set(counted.map((entry) => entry.resource))) {
1780
+ members[group[name]] = (members[group[name]] ?? 0) + 1
1781
+ }
1782
+ taking.push(...counted.filter((entry) => 1 === members[group[entry.resource]]))
1783
+ }
1784
+
1785
+ const cmps: Record<string, Set<string>> = {}
1786
+ const routesOf: Record<string, Set<string>> = {}
1787
+ for (const entry of taking) {
1788
+ (cmps[entry.resource] = cmps[entry.resource] ?? new Set()).add(entry.cmp)
1789
+ const key = entry.resource + ' ' + entry.op + ' ' + paramNames(entry.parts)
1790
+ ;(routesOf[key] = routesOf[key] ?? new Set()).add(entry.path)
1791
+ }
1792
+ const blocked = new Set(Object.keys(cmps).filter((name) => 1 < cmps[name].size))
1793
+ for (const key of Object.keys(routesOf)) {
1794
+ if (1 < routesOf[key].size) {
1795
+ blocked.add(key.split(' ')[0])
1796
+ }
1797
+ }
1798
+
1799
+ return taking
1800
+ .filter((entry) => !blocked.has(entry.resource))
1801
+ .map((entry) => entry.cmp + ' ' + entry.method + ' ' + entry.path)
1802
+ .sort()
1803
+ }
1804
+
1805
+
1806
+ // A route beneath a segment that names another of the component's resources
1807
+ // is a view of that resource, such as `/builds/latest` of `/builds`.
1808
+ function isSharingView(entry: SharingEntry, names: Set<string>): boolean {
1809
+ for (let i = 1; i < entry.parts.length; i++) {
1810
+ const name = pathResource(entry.parts.slice(0, i), 'GET')
1811
+ if (null != name && name !== entry.resource && names.has(name)) {
1812
+ return true
1813
+ }
1814
+ }
1815
+ return false
1816
+ }
1817
+
1818
+
1819
+ // Item routes under the same parent keyed by the same parameters address the
1820
+ // same records, so the resources they name are one: each maps to its group.
1821
+ function aliasGroups(entries: SharingEntry[]): Record<string, string> {
1822
+ const group: Record<string, string> = {}
1823
+ const find = (name: string): string => group[name] === name ? name : find(group[name])
1824
+ for (const entry of entries) {
1825
+ group[entry.resource] = entry.resource
1826
+ }
1827
+
1828
+ const first: Record<string, string> = {}
1829
+ for (const entry of entries) {
1830
+ if (!isParam(entry.parts[entry.parts.length - 1])) {
1831
+ continue
1832
+ }
1833
+ const pm = matchEntityPath(entry.parts) as PathMatch
1834
+ const parent = entry.parts.slice(0, pm.index + PATH_NAME_INDEX[pm.expr])
1835
+ .map((p) => isParam(p) ? '{}' : p).join('/')
1836
+ const key = parent + ' ' + paramNames(entry.parts)
1837
+ const other = first[key] = first[key] ?? entry.resource
1838
+ const [a, b] = [find(other), find(entry.resource)].sort()
1839
+ group[b] = a
1840
+ }
1841
+
1842
+ for (const name of Object.keys(group)) {
1843
+ group[name] = find(name)
1844
+ }
1845
+ return group
1846
+ }
1847
+
1848
+
1849
+ function paramNames(parts: string[]): string {
1850
+ return parts.filter(isParam).sort().join(',')
1851
+ }
1852
+
1853
+
1854
+ // The schema a local `$ref` pointer names in the definition.
1855
+ function refSchema(def: any, xref: string): any {
1856
+ if (!xref.startsWith('#/')) {
1857
+ return undefined
1858
+ }
1859
+ let node = def
1860
+ for (const seg of xref.slice(2).split('/')) {
1861
+ const key = seg.replace(/~1/g, '/').replace(/~0/g, '~')
1862
+ node = null != node && 'object' === typeof node && Object.prototype.hasOwnProperty.call(node, key)
1863
+ ? node[key] : undefined
1864
+ }
1865
+ return node
1866
+ }
1867
+
1868
+
1869
+ // Read in place: resolveSchemaProperties merges, and merging rewrites the
1870
+ // nodes the def's schemas share.
1871
+ function declaresId(schema: any): boolean {
1872
+ if (null == schema || 'object' !== typeof schema) {
1873
+ return false
1874
+ }
1875
+ const parts = [schema, ...(Array.isArray(schema.allOf) ? schema.allOf : [])]
1876
+ return parts.some((part: any) => null != part?.properties?.id)
1877
+ }
1878
+
1879
+
1712
1880
  // The operation ResolveOperation will assign, needed before the entity is
1713
1881
  // named: whether a response unwraps as an envelope depends on it.
1714
1882
  function methodOpname(
@@ -2011,5 +2179,7 @@ function hasMethod(def: any, pathStr: string, methodName: string) {
2011
2179
 
2012
2180
 
2013
2181
  export {
2014
- heuristic01
2182
+ heuristic01,
2183
+ pathResource,
2184
+ sharedRoutes,
2015
2185
  }