@voxgig/apidef 8.32.3 → 8.33.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.
@@ -8,14 +8,15 @@ import { each } from 'jostraca'
8
8
  import { size, merge, clone, getelem, isempty, items, keysof } from '@voxgig/struct'
9
9
 
10
10
  import {
11
- isEntityWrapperProp, envelopeProp, envelopeItemRef, composedEnvelopeProp, propIsList,
12
- recordLists,
13
- singleEnvelope,
11
+ isEntityWrapperProp, envelopeProp, strictEnvelopeProp, envelopeItemRef, composedEnvelopeProp,
12
+ propIsList, literalName, paramOf, paramNoun, recordLists, singleEnvelope,
14
13
  authExchangeOp, specSecuredByDefault, itemEnvelopeKey,
15
- itemEnvelopeTransform, answersPage, pageRecords, answersRecordMap, pageTransform,
14
+ itemEnvelopeTransform, answersPage, pageRecords, answersRecordMap, pageTransform, listingProps,
15
+ responseSchema, rangeResponse, cmpNamespace, wordBreaks,
16
+ PARAM_NOUN_SUFFIX_RE,
16
17
  } from '../utility'
17
18
 
18
- import { requestSchema } from '../transform/body'
19
+ import { requestSchema, selectedRequestSchema } from '../transform/body'
19
20
  import { findExampleObject } from '../transform/field'
20
21
 
21
22
 
@@ -51,6 +52,7 @@ import {
51
52
  canonize,
52
53
  canonizeCmpName,
53
54
  canonizeParam,
55
+ wrapperOf,
54
56
  capture,
55
57
  CMP_REF_RE,
56
58
  cmpRefName,
@@ -80,7 +82,9 @@ import {
80
82
 
81
83
  import { snakify } from 'jostraca'
82
84
 
83
- import { mergeCollectionPaths, mergeFoldedEntities } from '../transform/entity'
85
+ import {
86
+ mergeCollectionPaths, mergeCommandEntities, mergeFoldedEntities, separateSharedPoints,
87
+ } from '../transform/entity'
84
88
 
85
89
  import { byCodePoint, countRefs, satAdd } from '../refcount'
86
90
 
@@ -114,11 +118,59 @@ const METHOD_IDOP: Record<string, string> = {
114
118
  PATCH: 'patch',
115
119
  HEAD: 'head',
116
120
  OPTIONS: 'OPTIONS',
121
+ TRACE: 'TRACE',
117
122
  }
118
123
 
119
124
  // Tried in order: the first shape a path matches decides how its entity is named.
120
125
  const ENTITY_PATH_SHAPES = ['t/p/t/', 't/p/', 'p/t/', 't/', 't/p/p']
121
126
 
127
+ // A trailing literal that is one of these is a verb on the noun before it.
128
+ const VERB_WORDS = new Set([
129
+ 'send', 'resend', 'get', 'fetch', 'list', 'create', 'add', 'update', 'edit', 'delete',
130
+ 'remove', 'search', 'find', 'query', 'lookup', 'check', 'validate', 'verify', 'submit',
131
+ 'cancel', 'approve', 'reject', 'publish', 'unpublish', 'archive', 'unarchive', 'restore',
132
+ 'run', 'execute', 'start', 'stop', 'pause', 'resume', 'retry', 'refresh', 'reset', 'sync',
133
+ 'import', 'export', 'upload', 'download', 'login', 'logout', 'register', 'subscribe',
134
+ 'unsubscribe', 'activate', 'deactivate', 'enable', 'disable', 'lock', 'unlock', 'move',
135
+ 'copy', 'rename', 'merge', 'split', 'assign', 'unassign', 'attach', 'detach', 'invite',
136
+ 'accept', 'decline', 'notify', 'ping', 'count', 'exists', 'preview', 'render', 'generate',
137
+ 'calculate', 'compute', 'convert', 'process', 'trigger', 'dispatch', 'apply', 'revoke',
138
+ 'grant', 'save', 'lock', 'test', 'inject', 'analyze', 'autocomplete', 'bypass', 'contains',
139
+ 'finish', 'reorder', 'shuffle',
140
+ ])
141
+
142
+ // A literal that names an identifier keys a resource rather than naming one.
143
+ const ID_LITERAL_RE = /(^|_)ids?$/
144
+
145
+ // A component named for one of these, alone or as the bare member of a family
146
+ // of results, names no entity.
147
+ const GENERIC_CMP_WORDS = ['default', 'empty', 'ok', 'response', 'result', 'success', 'void']
148
+
149
+ // A version tag groups routes by release, not by resource.
150
+ const VERSION_TAG_RE = /^v\d+([a-z]+\d*)?$/
151
+
152
+ // Literals that name no resource of their own.
153
+ const GENERIC_WORDS = ['history', 'list', 'result']
154
+
155
+ // A key that identifies a resource rather than naming an item.
156
+ const ID_KEY_RE = /_(id|key|uuid)$/
157
+
158
+ // The words that open an operationId's tail after its object.
159
+ const OPID_TAIL_WORDS = ['via', 'by', 'with']
160
+
161
+ // A literal opening with one of these reads, whatever the method.
162
+ const READ_VERBS = ['list', 'search', 'get', 'find', 'query']
163
+
164
+ // The shapes whose naming literal ends the path.
165
+ const LITERAL_LAST_SHAPES = ['t/p/t/', 't/', 'p/t/']
166
+
167
+ // Stripped from a command's body component to name the command.
168
+ const COMMAND_SUFFIXES = [
169
+ '_request', '_input', '_payload', '_body', '_params', '_parameters', '_command', '_dto',
170
+ ]
171
+
172
+ const SCALAR_TYPES = new Set(['string', 'number', 'integer', 'boolean'])
173
+
122
174
  // The matched part that gives each shape its name.
123
175
  const PATH_NAME_INDEX: Record<string, number> = {
124
176
  't/p/t/': 2, 't/p/': 0, 'p/t/': 1, 't/': 0, 't/p/p': 0,
@@ -134,6 +186,7 @@ const METHOD_CONSIDER_ORDER: Record<string, number> = {
134
186
  'DELETE': 500,
135
187
  'HEAD': 600,
136
188
  'OPTIONS': 700,
189
+ 'TRACE': 800,
137
190
  }
138
191
 
139
192
 
@@ -186,12 +239,15 @@ async function heuristic01(ctx: ApiDefContext): Promise<Guide> {
186
239
  distinctShare(ctx.def, sharePath, shareMethods, itemPath, itemMethods)).length
187
240
 
188
241
  guide.metrics.count.entity -= mergeFoldedEntities(guide, ctx.log).length
242
+ guide.metrics.count.entity -= mergeCommandEntities(guide, ctx.log).length
189
243
 
190
244
  // After the merge, which can move a path onto another entity.
191
245
  for (const entity of Object.values(guide.entity) as GuideEntity[]) {
192
246
  nameEntityParams(entity)
193
247
  }
194
248
 
249
+ separateSharedPoints(guide, ctx.def, ctx.log)
250
+
195
251
  const metrics = guide.metrics
196
252
 
197
253
  const entities = Object.values(guide.entity)
@@ -252,6 +308,8 @@ function Prepare(spec: TaskSpec) {
252
308
  def: spec.ctx.def,
253
309
  guide,
254
310
  work: {
311
+ cmpNamespace: cmpNamespace(spec.ctx.def),
312
+ wordBreaks: wordBreaks(spec.ctx.def),
255
313
  pathmap: named(),
256
314
  entmap: named(),
257
315
  envelope: named(),
@@ -317,7 +375,7 @@ function MeasureMethod(spec: TaskSpec) {
317
375
  metrics.count.tag++
318
376
  metrics.found.tag[tag] = {
319
377
  name: tag,
320
- canon: canonize(tag),
378
+ canon: literalName(tag),
321
379
  }
322
380
  }
323
381
  }
@@ -399,7 +457,8 @@ function MeasureEnvelope(spec: TaskSpec) {
399
457
  const work = spec.data.work
400
458
  const mdesc = spec.node.val
401
459
  const opname = methodOpname(mdesc, matchEntityPath(work.pathmap[mdesc.path].parts), [])
402
- const unwrapref = getResponseSchema(successResponse(mdesc.responses))?.['x-ref']
460
+ const unwrapref = null != singletonOf(spec.data, mdesc.path) ? null :
461
+ getResponseSchema(successResponse(mdesc.responses))?.['x-ref']
403
462
 
404
463
  for (const schema of successSchemas(mdesc.responses)) {
405
464
  const xref = schema['x-ref']
@@ -540,11 +599,15 @@ function selectAllMethods(_source: any, spec: TaskSpec): MethodDesc[] {
540
599
  }
541
600
  }
542
601
 
602
+ // Parents resolve before their children whatever the keys are called, so
603
+ // the paths compare with their parameters normalised first.
543
604
  caught.methods.sort((a: any, b: any) => {
544
- if (a.path < b.path) {
605
+ const an = normalizeParams(a.path)
606
+ const bn = normalizeParams(b.path)
607
+ if (an < bn || (an === bn && a.path < b.path)) {
545
608
  return -1
546
609
  }
547
- else if (a.path > b.path) {
610
+ else if (an > bn || (an === bn && a.path > b.path)) {
548
611
  return 1
549
612
  }
550
613
  else if (METHOD_CONSIDER_ORDER[a.method] < METHOD_CONSIDER_ORDER[b.method]) {
@@ -575,7 +638,7 @@ function MeasureTagItems(spec: TaskSpec) {
575
638
  const items = work.tagItems[cmp] = work.tagItems[cmp] ?? {}
576
639
  items[collection] = items[collection] ?? {}
577
640
  items[collection][parts.filter(isParam)
578
- .map((part) => canonizeParam(part.slice(1, -1))).sort().join(',')] = true
641
+ .map((part) => canonizeParam(paramOf(part))).sort().join(',')] = true
579
642
  }
580
643
  }
581
644
 
@@ -597,7 +660,7 @@ function MeasureClaims(spec: TaskSpec) {
597
660
  const name = pathEntityName(data, { ...mdesc, MethodEntity: ment }, parts,
598
661
  matchEntityPath(parts), work.claimowner, [])
599
662
  if (null != name) {
600
- const claim = resplitFromCmp(name, ment.cmp as string, [])
663
+ const claim = resplitFromCmp(name, ment.cmp as string, [], work.wordBreaks)
601
664
  const stored = ensureMinEntityName(claim, {})
602
665
  for (const key of [claim, stored]) {
603
666
  const claims = work.claims[key] = work.claims[key] ?? {}
@@ -656,10 +719,12 @@ function ResolveEntityComponent(spec: TaskSpec) {
656
719
  // Guarded wrapper-suffix stripping folds e.g. BeneficiaryPageResponse
657
720
  // into beneficiary — but only when the remainder is itself a schema
658
721
  // measured by MeasureRef (keys are canonizeCmpName, pre-clean).
659
- xref.cmp = cleanComponentName(xref.cmp,
660
- (n: string) => null != metrics.count.origcmprefs[n])
722
+ xref.cmp = cleanCmp(spec.data, xref.cmp)
661
723
  return xref
662
724
  })
725
+ .flatMap((xref) => unwrapCmp(metrics, xref, why_cmp))
726
+ .filter((xref) => !genericCmp(xref.cmp, metrics.count.origcmprefs,
727
+ cmpSchemaOf(spec.data.def, xref.origcmp)))
663
728
 
664
729
  let goodxrefs = cleanxrefs
665
730
  .filter(xref => {
@@ -817,7 +882,8 @@ function ResolveEntityName(spec: TaskSpec) {
817
882
 
818
883
  let entname: string | null = shaped
819
884
  if (null != owner && (null == shaped ||
820
- resplitFromCmp(owner.entname, cmp, []) !== resplitFromCmp(shaped, cmp, []))) {
885
+ resplitFromCmp(owner.entname, cmp, [], work.wordBreaks) !==
886
+ resplitFromCmp(shaped, cmp, [], work.wordBreaks))) {
821
887
  ment.verb_on_parent = verb_on_parent
822
888
  ment.same_path = owner.entname
823
889
  why_path.push('same-path-tag=' + owner.entname + '/' + owner.method)
@@ -836,7 +902,7 @@ function ResolveEntityName(spec: TaskSpec) {
836
902
  entname = 'entity' + work.entity.count.unresolved
837
903
  }
838
904
 
839
- entname = resplitFromCmp(entname, cmp, why_path)
905
+ entname = resplitFromCmp(entname, cmp, why_path, work.wordBreaks)
840
906
 
841
907
  if (null != item) {
842
908
  why_path.push(item.why + '=' + item.name)
@@ -894,17 +960,20 @@ function ResolveEntityName(spec: TaskSpec) {
894
960
 
895
961
  // A method named only from its tag, as a DELETE answering 204 is, joins the
896
962
  // entity a read of the same path resolved to when that read carries the same
897
- // tag: the tag then groups the path's routes and names no other resource. A
898
- // tag the read does not carry, Admin on the delete of a team, keeps its name.
963
+ // tag: the tag then groups the path's routes and names no other resource.
899
964
  function samePathOwner(
900
965
  mdesc: MethodDesc,
901
966
  work: any,
902
967
  ): { entname: string, method: string } | null {
903
968
  const ment = mdesc.MethodEntity
904
969
  const owner = work.pathowner[mdesc.path]
905
- if (null == owner || 'tag' !== ment?.ref) {
970
+ if (null == owner) {
906
971
  return null
907
972
  }
973
+ if ('tag' !== ment?.ref) {
974
+ return null == ment?.cmp ? componentReadOwner(mdesc.path, owner, work.methods.map(
975
+ (m: MethodDesc) => ({ path: m.path, method: m.method, cmp: m.MethodEntity }))) : null
976
+ }
908
977
  const tags: string[] = mdesc.tags ?? []
909
978
  for (const method of ['GET', 'QUERY', 'PUT', 'PATCH']) {
910
979
  const entname = owner[method]
@@ -918,6 +987,34 @@ function samePathOwner(
918
987
  }
919
988
 
920
989
 
990
+ // A method that answers no component of its own joins the entity a read of
991
+ // its path takes from the component that read answers.
992
+ function componentReadOwner(
993
+ pathStr: string,
994
+ owner: Record<string, string>,
995
+ routes: { path: string, method: string, cmp?: { ref?: string, cmp?: string } | null }[],
996
+ ): { entname: string, method: string } | null {
997
+ for (const method of ['GET', 'QUERY']) {
998
+ const entname = owner[method]
999
+ const read = routes.find((r) => r.path === pathStr && r.method === method)?.cmp
1000
+ if (null != entname && null != read && 'tag' !== read.ref && entname === read.cmp) {
1001
+ return { entname, method }
1002
+ }
1003
+ }
1004
+ return null
1005
+ }
1006
+
1007
+
1008
+ // A component's name cleaned of its affixes and the definition's namespace;
1009
+ // a measured component counts as known with or without the namespace.
1010
+ function cleanCmp(data: { guide: any, work: any }, name: string): string {
1011
+ const refs = data.guide.metrics.count.origcmprefs
1012
+ const ns: string | null = data.work.cmpNamespace ?? null
1013
+ return cleanComponentName(name,
1014
+ (n: string) => null != refs[n] || (null != ns && null != refs[ns + '_' + n]), ns)
1015
+ }
1016
+
1017
+
921
1018
  // A method named only from its tag, on a verb route beneath an item, joins the
922
1019
  // entity that owns the item's collection, so its verb becomes that entity's
923
1020
  // action. The verb is a singular word or a pair of them, behind an optional
@@ -944,7 +1041,8 @@ function collectionOwner(mdesc: MethodDesc, parts: string[], work: any): string
944
1041
 
945
1042
 
946
1043
  // The name a method's path shape and component give it, or null where neither
947
- // does. A verb on a parent takes the name pathowner holds for the parent.
1044
+ // does; a read that views an item joins it, and a POST that reads or commands
1045
+ // is named for what it reads or sends.
948
1046
  function pathEntityName(
949
1047
  data: { def: any, guide: any, work: any },
950
1048
  mdesc: any,
@@ -952,6 +1050,133 @@ function pathEntityName(
952
1050
  pm: PathMatch | null,
953
1051
  pathowner: Record<string, Record<string, string>>,
954
1052
  why: string[],
1053
+ ): string | null {
1054
+ const ment = mdesc.MethodEntity
1055
+ const joined = methodOf(mdesc.path) ?? singletonPartOf(data, parts, pathowner) ??
1056
+ readOfItem(data, mdesc, parts, pathowner)
1057
+ if (null != joined) {
1058
+ ment.verb_on_parent = parts[parts.length - 1] ?? joined.action
1059
+ ment.view_on_parent = 'method-name' !== joined.why && READ_METHODS.includes(mdesc.method)
1060
+ ment.view_action = joined.action
1061
+ why.push(joined.why + '=' + joined.parent)
1062
+ return joined.parent
1063
+ }
1064
+
1065
+ const link = relationshipOf(data, parts, pathowner)
1066
+ if (null != link) {
1067
+ const ment = mdesc.MethodEntity
1068
+ ment.verb_on_parent = parts[parts.length - 1]
1069
+ ment.view_on_parent = READ_METHODS.includes(mdesc.method)
1070
+ ment.view_action = link.action
1071
+ why.push('relationship=' + link.parent)
1072
+ return link.parent
1073
+ }
1074
+ const single = singletonOf(data, mdesc.path)
1075
+ if (null != single) {
1076
+ const name = cleanCmp(data, canonizeCmpName(cmpRefName(single)))
1077
+ mdesc.MethodEntity.singleton = true
1078
+ why.push('singleton=' + name)
1079
+ return name
1080
+ }
1081
+ const verb = verbOfItem(data, mdesc, parts, pathowner)
1082
+ if (null != verb) {
1083
+ const ment = mdesc.MethodEntity
1084
+ ment.verb_on_parent = parts[parts.length - 1]
1085
+ ment.view_on_parent = READ_METHODS.includes(mdesc.method)
1086
+ ment.view_action = verb.action
1087
+ why.push('verb-of-item=' + verb.parent)
1088
+ return verb.parent
1089
+ }
1090
+ const view = viewOfItem(data, mdesc, parts, pathowner)
1091
+ if (null != view) {
1092
+ const ment = mdesc.MethodEntity
1093
+ ment.verb_on_parent = parts[parts.length - 1]
1094
+ ment.view_on_parent = true
1095
+ ment.view_action = view.action
1096
+ why.push('view-of-item=' + view.parent)
1097
+ return view.parent
1098
+ }
1099
+ const write = subWriteOfItem(data, mdesc, parts, pathowner)
1100
+ if (null != write) {
1101
+ const ment = mdesc.MethodEntity
1102
+ ment.verb_on_parent = parts[parts.length - 1]
1103
+ ment.view_action = write.action
1104
+ why.push('sub-write=' + write.parent)
1105
+ return write.parent
1106
+ }
1107
+ const variant = variantOfCollection(data, mdesc, parts, pathowner)
1108
+ if (null != variant) {
1109
+ const ment = mdesc.MethodEntity
1110
+ ment.verb_on_parent = parts[parts.length - 1]
1111
+ ment.view_action = variant.action
1112
+ why.push('variant=' + variant.parent)
1113
+ return variant.parent
1114
+ }
1115
+ const keyed = keyNounOf(data, mdesc, parts)
1116
+ if (null != keyed) {
1117
+ const ment = mdesc.MethodEntity
1118
+ ment.verb_on_parent = parts[parts.length - 1]
1119
+ ment.view_on_parent = READ_METHODS.includes(mdesc.method)
1120
+ ment.view_action = keyed.action
1121
+ why.push('key-noun=' + keyed.parent)
1122
+ return keyed.parent
1123
+ }
1124
+ const queued = asyncResultOf(data, mdesc, parts)
1125
+ if (null != queued) {
1126
+ const ment = mdesc.MethodEntity
1127
+ ment.verb_on_parent = parts[parts.length - 1]
1128
+ ment.view_action = queued.action
1129
+ why.push('async-result=' + queued.parent)
1130
+ return queued.parent
1131
+ }
1132
+ // A short literal names nothing: the component the route answers, else
1133
+ // the route's key, else what a route with no literal is named by, else the
1134
+ // padded literal.
1135
+ if (null != pm && shortLiteral(pm)) {
1136
+ why.push('short-literal')
1137
+ const answered = answeredCmp(mdesc)
1138
+ if (null != answered) {
1139
+ why.push('answers=' + answered)
1140
+ return answered
1141
+ }
1142
+ const key = keyParamOf(data.def, mdesc.path, data.work)
1143
+ const noun = null == key || /version/i.test(key) ? '' : paramNoun(key)
1144
+ if (3 <= noun.length) {
1145
+ why.push('infer-key=' + key)
1146
+ return noun
1147
+ }
1148
+ return inferEntityName(mdesc, parts.filter(isParam), why) ??
1149
+ shapeEntityName(data, mdesc, parts, pm, pathowner, why)
1150
+ }
1151
+ // A read whose literal is a lone verb or a generic word is named for what
1152
+ // it answers; a write stays a command.
1153
+ if (null != pm && READ_METHODS.includes(mdesc.method) && nounless(pm, parts)) {
1154
+ const answered = answeredCmp(mdesc)
1155
+ if (null != answered) {
1156
+ why.push('nounless;answers=' + answered)
1157
+ return answered
1158
+ }
1159
+ }
1160
+ const shaped = shapeEntityName(data, mdesc, parts, pm, pathowner, why)
1161
+ if (null == pm || null == shaped) {
1162
+ return shaped
1163
+ }
1164
+ const read = postRead(mdesc, pm, parts, why)
1165
+ if (null != read) {
1166
+ return '' === read ? shaped : read
1167
+ }
1168
+ return commandName(data, mdesc, pm, parts, why) ?? commandTwin(data, mdesc, pm, parts, why) ?? shaped
1169
+ }
1170
+
1171
+
1172
+ // A verb on a parent takes the name pathowner holds for the parent.
1173
+ function shapeEntityName(
1174
+ data: { def: any, guide: any, work: any },
1175
+ mdesc: any,
1176
+ parts: string[],
1177
+ pm: PathMatch | null,
1178
+ pathowner: Record<string, Record<string, string>>,
1179
+ why: string[],
955
1180
  ): string | null {
956
1181
  if ('t/p/t/' === pm?.expr) {
957
1182
  return entityPathMatch_tpte(data, pm, mdesc, pathowner, why)
@@ -960,7 +1185,7 @@ function pathEntityName(
960
1185
  return entityPathMatch_tpe(data, pm, mdesc, why)
961
1186
  }
962
1187
  else if ('p/t/' === pm?.expr) {
963
- return entityPathMatch_pte(data, pm, mdesc, why)
1188
+ return entityPathMatch_pte(data, pm, mdesc, pathowner, why)
964
1189
  }
965
1190
  else if ('t/' === pm?.expr) {
966
1191
  return entityPathMatch_te(data, pm, mdesc, why)
@@ -983,7 +1208,7 @@ function markRecordOwner(
983
1208
  ) {
984
1209
  const last = parts.filter((part: string) => !isParam(part)).pop()
985
1210
  if (null == recordowner[pathStr] && isSchemaRef(ment.ref) &&
986
- entname === ment.cmp && null != last && entname === canonize(last)) {
1211
+ entname === ment.cmp && null != last && entname === literalName(last)) {
987
1212
  recordowner[pathStr] = entname
988
1213
  }
989
1214
  }
@@ -1023,9 +1248,8 @@ function RenameParams(spec: TaskSpec) {
1023
1248
 
1024
1249
  const applySnakeCaseRename = () => {
1025
1250
  for (const part of parts) {
1026
- const m = part.match(/^\{(.+)\}$/)
1027
- if (!m) continue
1028
- const placeholder = m[1]
1251
+ if (!isParam(part)) continue
1252
+ const placeholder = paramOf(part)
1029
1253
  const snake = depluralize(snakify(normalizeFieldName(placeholder)))
1030
1254
  if (snake !== placeholder && paramRenameCapture.rename[placeholder] === undefined) {
1031
1255
  paramRenameCapture.why[placeholder] = (paramRenameCapture.why[placeholder] ?? [])
@@ -1058,18 +1282,18 @@ function RenameParams(spec: TaskSpec) {
1058
1282
  let partStr = parts[partI]
1059
1283
 
1060
1284
  if (isParam(partStr)) {
1061
- origParams.push(partStr.replace(/[\}\{\*]/g, ''))
1285
+ origParams.push(paramOf(partStr).replace(/\*/g, ''))
1062
1286
 
1063
1287
  const why = []
1064
1288
 
1065
- const oldParam = partStr.substring(1, partStr.length - 1)
1289
+ const oldParam = paramOf(partStr)
1066
1290
  paramRenameCapture.why[oldParam] = (paramRenameCapture.why[oldParam] ?? [])
1067
1291
 
1068
1292
  const lastPart = partI === parts.length - 1
1069
1293
  const secondLastPart = partI === parts.length - 2
1070
1294
  const notLastPart = partI < parts.length - 1
1071
1295
  const hasParent = 0 < partI && !isParam(parts[partI - 1])
1072
- const parentName = hasParent ? canonize(parts[partI - 1]) : null
1296
+ const parentName = hasParent ? literalName(parts[partI - 1]) : null
1073
1297
  const not_exact_id = 'id' !== oldParam
1074
1298
  const probably_an_id =
1075
1299
  oldParam.endsWith('id')
@@ -1160,6 +1384,7 @@ function RenameParams(spec: TaskSpec) {
1160
1384
  || (
1161
1385
  parentName === entdesc.name
1162
1386
  || entdesc.name.endsWith('_' + parentName)
1387
+ || verbAfterNoun(parts, partI, entdesc.name)
1163
1388
  )
1164
1389
  )
1165
1390
  ) {
@@ -1187,7 +1412,7 @@ function RenameParams(spec: TaskSpec) {
1187
1412
  if (
1188
1413
  'id' !== oldParam
1189
1414
  // && fixEntName(partStr) === entdesc.name
1190
- && canonize(partStr) === entdesc.name
1415
+ && literalName(partStr) === entdesc.name
1191
1416
  ) {
1192
1417
  updateParamRename(
1193
1418
  ctx, data, pathStr, methodName, paramRenameCapture, oldParam,
@@ -1279,24 +1504,30 @@ function FindActions(spec: TaskSpec) {
1279
1504
  const parts = verbParts(spec.data.work.pathmap[pathStr].parts)
1280
1505
 
1281
1506
  const fourthLastPart = parts[parts.length - 4]
1282
- const fourthLastPartCanon = canonize(fourthLastPart)
1507
+ const fourthLastPartCanon = literalName(fourthLastPart)
1283
1508
  const thirdLastPart = parts[parts.length - 3]
1284
- const thirdLastPartCanon = canonize(thirdLastPart)
1509
+ const thirdLastPartCanon = literalName(thirdLastPart)
1285
1510
  const secondLastPart = parts[parts.length - 2]
1286
- const secondLastPartCanon = canonize(secondLastPart)
1511
+ const secondLastPartCanon = literalName(secondLastPart)
1287
1512
  const lastPart = parts[parts.length - 1]
1288
- const lastPartCanon = canonize(lastPart)
1513
+ const lastPartCanon = actionWord(lastPart)
1289
1514
 
1290
1515
  const cmp = ment.cmp
1291
1516
 
1292
1517
  if (null != ment.verb_on_parent) {
1293
- if (isVerb(lastPart)) {
1294
- pathdesc.action[lastPartCanon] = pathdesc.action[lastPartCanon] ?? {
1518
+ if (isVerb(lastPart) || null != ment.view_action) {
1519
+ const name = ment.view_action ?? lastPartCanon
1520
+ pathdesc.action[name] = pathdesc.action[name] ?? {
1295
1521
  why_action: ['ent', entdesc.name, 'verb-on-parent', lastPart, methodName],
1296
1522
  }
1297
1523
  }
1298
1524
  }
1299
1525
 
1526
+ // A route its record names ends in its collection's literal, not an action.
1527
+ else if (true === ment.record_named) {
1528
+ // The collection_action below still applies.
1529
+ }
1530
+
1300
1531
  // /api/foo/bar where foo is the entity and bar is the action, no id param
1301
1532
  else if (
1302
1533
  secondLastPartCanon === cmp
@@ -1334,6 +1565,25 @@ function FindActions(spec: TaskSpec) {
1334
1565
  updateAction(methodName, oldActionName, actionName, entdesc, pathdesc,
1335
1566
  'ent-param-3rd-last')
1336
1567
  }
1568
+
1569
+ // /api/foo/{parent}/{param}/action
1570
+ else if (isParam(thirdLastPart) && isParam(secondLastPart) && isVerb(lastPart)) {
1571
+ updateAction(methodName, lastPart, lastPartCanon, entdesc, pathdesc, 'ent-keys-2nd-last')
1572
+ }
1573
+ }
1574
+
1575
+ // /api/foo/{a}/{b}/{c}/action
1576
+ else if (isVerb(lastPart) && keyRunBefore(parts, (part) => {
1577
+ const canon = literalName(part)
1578
+ return canon === cmp || canon === ment.origcmp || canon === entname
1579
+ })) {
1580
+ updateAction(methodName, lastPart, lastPartCanon, entdesc, pathdesc, 'ent-keys-before-last')
1581
+ }
1582
+
1583
+ if (null != ment.collection_action) {
1584
+ pathdesc.action[ment.collection_action] = pathdesc.action[ment.collection_action] ?? {
1585
+ why_action: ['ent', entdesc.name, 'collection', ment.collection_action, methodName],
1586
+ }
1337
1587
  }
1338
1588
 
1339
1589
  debugpath(pathStr, methodName, 'FIND-ACTIONS', cmp, parts, pathdesc.action, pathdesc.why_action)
@@ -1370,11 +1620,19 @@ function ResolveOperation(spec: TaskSpec) {
1370
1620
 
1371
1621
 
1372
1622
  if ('load' === standard_opname) {
1373
- const islist = isListResponse(mdesc, ment.pm, pathStr, why_op, work.listed)
1623
+ const islist = true !== ment.view_on_parent && true !== ment.singleton &&
1624
+ isListResponse(mdesc, ment.pm, pathStr, why_op, work.listed)
1374
1625
  opname = islist ? 'list' : opname
1626
+ if (true === ment.view_on_parent) {
1627
+ why_op.push('view')
1628
+ }
1375
1629
  }
1376
1630
 
1377
-
1631
+ else if ('create' === standard_opname &&
1632
+ (true === ment.post_read || null != postReadVerb(mdesc, ment.pm, parts))) {
1633
+ opname = 'list'
1634
+ why_op.push('post-read')
1635
+ }
1378
1636
 
1379
1637
  else {
1380
1638
  why_op.push('not-load')
@@ -1543,6 +1801,11 @@ function ResolveTransform(spec: TaskSpec) {
1543
1801
  }
1544
1802
  }
1545
1803
 
1804
+ // A singleton is read whole.
1805
+ if (true === ment.singleton) {
1806
+ transform.res = undefined
1807
+ }
1808
+
1546
1809
  if ('list' === opname) {
1547
1810
  warnListBody(spec.ctx, methodName + ' ' + pathStr, transform.res, partprops)
1548
1811
 
@@ -1668,6 +1931,87 @@ function BuildEntity(spec: TaskSpec) {
1668
1931
 
1669
1932
 
1670
1933
 
1934
+ function genericCmp(name: string, refs: Record<string, number>, schema?: any): boolean {
1935
+ if (GENERIC_CMP_WORDS.includes(name) || ID_LITERAL_RE.test(name) ||
1936
+ ('object' === name && 0 === Object.keys(mergedProperties(schema) ?? {}).length)) {
1937
+ return true
1938
+ }
1939
+ const at = name.lastIndexOf('_')
1940
+ const word = name.slice(at + 1)
1941
+ if (at < 1 || !GENERIC_CMP_WORDS.includes(word)) {
1942
+ return false
1943
+ }
1944
+ const prefix = name.slice(0, at + 1)
1945
+ return Object.keys(refs).some((ref) => ref !== name && ref.startsWith(prefix) &&
1946
+ ref.endsWith('_' + word) && prefix.length + word.length < ref.length)
1947
+ }
1948
+
1949
+
1950
+ // The schema a component's original name declares.
1951
+ function cmpSchemaOf(def: any, origcmp: string | undefined): any {
1952
+ return null == origcmp ? undefined :
1953
+ (def?.components?.schemas?.[origcmp] ?? def?.definitions?.[origcmp])
1954
+ }
1955
+
1956
+
1957
+ // An action keeps a verb word's own spelling (`contains`); any other literal
1958
+ // gives its canonical name.
1959
+ function actionWord(part: string | undefined): string {
1960
+ const lit = snakify(String(part ?? '').replace(/\.?\{[^}]*\}/g, ''))
1961
+ return VERB_WORDS.has(lit) ? lit : literalName(part as string)
1962
+ }
1963
+
1964
+
1965
+ // A run of keys between the entity's literal and a trailing verb, as
1966
+ // `/shops/{owner}/{shop}/{order}/cancel` acts on shop.
1967
+ function keyRunBefore(parts: string[], isEnt: (part: string) => boolean): boolean {
1968
+ let at = parts.length - 2
1969
+ while (0 <= at && isParam(parts[at])) {
1970
+ at--
1971
+ }
1972
+ return 3 <= parts.length - 2 - at && 0 <= at && isEnt(parts[at])
1973
+ }
1974
+
1975
+
1976
+ // A verb word as a path literal spells it: singular, or in the third person
1977
+ // (`contains`).
1978
+ function isVerbWord(part: string): boolean {
1979
+ const lit = snakify(part)
1980
+ return VERB_WORDS.has(lit) || (VERB_WORDS.has(literalName(part)) && depluralize(lit) === lit)
1981
+ }
1982
+
1983
+
1984
+ // The parameter after a literal keys it when it is named for the literal, as
1985
+ // `{stop_id}` keys `stop`, which is then a noun whatever verb it spells.
1986
+ function keyedBy(next: string | undefined, name: string): boolean {
1987
+ return null != next && isParam(next) && paramNoun(paramOf(next)) === name
1988
+ }
1989
+
1990
+
1991
+ // The noun the shape's literal gives: the literal before a custom method's
1992
+ // colon, or the noun before the literal when it is a verb, as `/message/send`
1993
+ // names message.
1994
+ function pathNoun(pm: PathMatch, parts: string[], why: string[]): string {
1995
+ const at = pm.index + PATH_NAME_INDEX[pm.expr]
1996
+ const custom = parts[at].match(CUSTOM_METHOD_RE)
1997
+ if (null != custom && !isParam(custom[1])) {
1998
+ why.push('noun-before-method=' + custom[1])
1999
+ return literalName(custom[1])
2000
+ }
2001
+ const name = literalName(parts[at])
2002
+ const lit = snakify(parts[at])
2003
+ if (null != custom || (isVerbWord(parts[at]) && !keyedBy(parts[at + 1], name))) {
2004
+ for (let i = at - 1; 0 <= i; i--) {
2005
+ if (!isParam(parts[i])) {
2006
+ why.push('noun-before-verb=' + parts[i])
2007
+ return literalName(parts[i])
2008
+ }
2009
+ }
2010
+ }
2011
+ return name
2012
+ }
2013
+
2014
+
1671
2015
  function entityPathMatch_tpte(
1672
2016
  data: { def: any, guide: any, work: any },
1673
2017
  pm: PathMatch,
@@ -1678,13 +2022,22 @@ function entityPathMatch_tpte(
1678
2022
  const ment = mdesc.MethodEntity
1679
2023
 
1680
2024
  const pathNameIndex = PATH_NAME_INDEX['t/p/t/']
2025
+ const parts: string[] = data.work.pathmap[mdesc.path].parts
1681
2026
 
1682
2027
  why.push('path=t/p/t/')
1683
2028
  const origPathName = pm[pathNameIndex]
1684
- let entname = canonize(origPathName)
2029
+ let entname = pathNoun(pm, parts, why)
2030
+ const verbish = entname !== literalName(origPathName)
1685
2031
  let ecm = undefined
1686
2032
 
1687
- if (null != ment.cmp) {
2033
+ // A verb's response is its result: the resource before the verb names.
2034
+ if (verbish && 'tag' !== ment.ref) {
2035
+ entname = itemAbove(data, parts, lastKey(parts), pathowner) ?? entname
2036
+ ment.verb_on_parent = getelem(pm, -1)
2037
+ why.push('verb-noun=' + entname)
2038
+ }
2039
+
2040
+ else if (null != ment.cmp) {
1688
2041
  const parent = verbOnParent(data, pm, mdesc, pathowner)
1689
2042
  if (null != parent) {
1690
2043
  entname = parent
@@ -1705,15 +2058,15 @@ function entityPathMatch_tpte(
1705
2058
  why.push('prob-ent=' + ecm.orig)
1706
2059
  }
1707
2060
  else if (endsWithCmp(data, pm)) {
1708
- entname = canonize(getelem(pm, -1))
2061
+ entname = literalName(getelem(pm, -1))
1709
2062
  why.push('prob-ent-last=' + ecm.orig)
1710
2063
  }
1711
2064
  else if (0 < findPathsWithPrefix(data, pm.path, { strict: true })) {
1712
- entname = canonize(getelem(pm, -1))
2065
+ entname = literalName(getelem(pm, -1))
1713
2066
  why.push('prob-ent-prefix=' + ecm.orig)
1714
2067
  }
1715
2068
  else {
1716
- entname = canonize(getelem(pm, -3)) + '_' + entname
2069
+ entname = literalName(getelem(pm, -3)) + '_' + entname
1717
2070
  why.push('prob-ent-part')
1718
2071
  }
1719
2072
  }
@@ -1721,14 +2074,14 @@ function entityPathMatch_tpte(
1721
2074
  // Probably an entity action suffix
1722
2075
  else {
1723
2076
  why.push('prob-ent-act')
1724
- entname = canonize(getelem(pm, -3))
2077
+ entname = literalName(getelem(pm, -3))
1725
2078
  }
1726
2079
 
1727
2080
  return entname
1728
2081
  }
1729
2082
 
1730
2083
  function endsWithCmp(data: any, pm: PathMatch) {
1731
- const last = canonize(getelem(pm, -1))
2084
+ const last = literalName(getelem(pm, -1))
1732
2085
  return isOrigCmp(data, last)
1733
2086
  }
1734
2087
 
@@ -1759,42 +2112,786 @@ function verbOnParent(
1759
2112
  return null
1760
2113
  }
1761
2114
 
1762
- const defpaths = data.def?.paths ?? {}
2115
+ const itemPath = leafItemRoute(data, pm)
2116
+ return null == itemPath ? null : itemOwner(pm, itemPath, pathowner)
2117
+ }
2118
+
1763
2119
 
1764
- // Paths compare with parameters normalised: the item path may spell its
1765
- // key `{id}` where the verb path spells it `{thing_number}`.
2120
+ // The item route a verb path hangs off, or null when a path extends the
2121
+ // verb. Paths compare with parameters normalised: the item path may spell
2122
+ // its key `{id}` where the verb path spells it `{thing_number}`.
2123
+ function leafItemRoute(data: { def: any }, pm: PathMatch): string | null {
1766
2124
  const normalize = (p: string) => p.replace(/\{[^}]+\}/g, '{}')
1767
2125
  const itemNorm = normalize(pm.path.replace(/\/[^/]+$/, ''))
1768
2126
  const prefix = normalize(pm.path) + '/'
1769
-
1770
- let itemPath: undefined | string = undefined
1771
- for (const p of Object.keys(defpaths)) {
2127
+ let itemPath: string | null = null
2128
+ for (const p of Object.keys(data.def?.paths ?? {})) {
1772
2129
  const pn = normalize(p)
1773
2130
  if (pn === itemNorm) {
1774
2131
  itemPath = p
1775
2132
  }
1776
- // A leaf: no path continues past the verb. Compared on a segment
1777
- // boundary, so `/merge` is not "extended" by `/merge-async`.
2133
+ // On a segment boundary, so `/merge` is not extended by `/merge-async`.
1778
2134
  else if (pn.startsWith(prefix)) {
1779
2135
  return null
1780
2136
  }
1781
2137
  }
1782
- if (null == itemPath) {
1783
- return null
1784
- }
2138
+ return itemPath
2139
+ }
2140
+
1785
2141
 
1786
- // Methods resolve in path order, so the item path's owners are already
1787
- // known. The parent is the entity a READ of the item returns: a PUT on
1788
- // the item answering with a one-off acknowledgement is named after that
1789
- // and must not claim the verb. Fall back to any owner, then the literal.
2142
+ // Methods resolve in path order, so the item path's owners are already
2143
+ // known. The parent is the entity a READ of the item returns: a PUT on the
2144
+ // item answering with a one-off acknowledgement is named after that and must
2145
+ // not claim the verb. Fall back to any owner, then the literal.
2146
+ function itemOwner(
2147
+ pm: PathMatch,
2148
+ itemPath: string,
2149
+ pathowner: Record<string, Record<string, string>>,
2150
+ ): string {
1790
2151
  const owners = pathowner[itemPath] ?? {}
1791
2152
  const parent = owners.GET ?? owners.QUERY ??
1792
2153
  Object.values(owners).sort()[0] as undefined | string
1793
- if (null != parent) {
1794
- return parent
2154
+ return parent ?? literalName(getelem(pm, -3))
2155
+ }
2156
+
2157
+
2158
+ // A read whose literals after the item key are singular and whose response
2159
+ // declares no record of its own, or is an array of scalars, is a view of
2160
+ // the item: the nearest resource above takes it as a load action.
2161
+ function viewOfItem(
2162
+ data: { def: any, work: any },
2163
+ mdesc: any,
2164
+ parts: string[],
2165
+ pathowner: Record<string, Record<string, string>>,
2166
+ ): { parent: string, action: string } | null {
2167
+ if (!READ_METHODS.includes(mdesc.method)) {
2168
+ return null
2169
+ }
2170
+ let key = -1
2171
+ for (let i = 0; i < parts.length; i++) {
2172
+ if (isParam(parts[i])) {
2173
+ key = i
2174
+ }
2175
+ }
2176
+ if (key < 0 || parts.length - 1 === key || /version/i.test(parts[key])) {
2177
+ return null
1795
2178
  }
2179
+ const tail = parts.slice(key + 1)
2180
+ const singular = tail.every((part) => {
2181
+ const lit = snakify(part)
2182
+ return '' !== lit && depluralize(lit) === lit
2183
+ })
2184
+ const schema = getResponseSchema(successResponse(mdesc.responses))
2185
+ const payload = responsePayload(schema)
2186
+ if ((!payload.scalars &&
2187
+ (!singular || payload.record || namedRecord(schema, parts[parts.length - 1]))) ||
2188
+ 0 < findPathsWithPrefix(data, mdesc.path, { strict: true })) {
2189
+ return null
2190
+ }
2191
+ const parent = itemAbove(data, parts, key, pathowner)
2192
+ return null == parent ? null : { parent, action: tail.map(literalName).join('_') }
2193
+ }
1796
2194
 
1797
- return canonize(getelem(pm, -3))
2195
+
2196
+ // A response holding a record under the name its route ends in answers that
2197
+ // record, as `/users/{id}/user-role` answers its `user_role`.
2198
+ function namedRecord(schema: any, last: string): boolean {
2199
+ const props = mergedProperties(schema)
2200
+ if (null == props || null == last || isParam(last)) {
2201
+ return false
2202
+ }
2203
+ const key = Object.keys(props).find((k: string) => canonize(k) === canonize(last))
2204
+ return null != key && responsePayload(props[key]).record
2205
+ }
2206
+
2207
+
2208
+ // A key after a verb word that follows the entity's own noun keys the entity,
2209
+ // as `/members/lookup/{member_id}` keys member.
2210
+ function verbAfterNoun(parts: string[], at: number, entname: string): boolean {
2211
+ const verb = parts[at - 1]
2212
+ if (at < 2 || null == verb || isParam(verb) || !VERB_WORDS.has(literalName(verb)) ||
2213
+ depluralize(snakify(verb)) !== snakify(verb)) {
2214
+ return false
2215
+ }
2216
+ for (let i = at - 2; 0 <= i; i--) {
2217
+ if (!isParam(parts[i])) {
2218
+ return literalName(parts[i]) === entname
2219
+ }
2220
+ }
2221
+ return false
2222
+ }
2223
+
2224
+
2225
+ // A `/relationships/<name>` route links the resource before it: that
2226
+ // resource's entity, with the relationship as the action, or null.
2227
+ function relationshipOf(
2228
+ data: { def: any, work: any },
2229
+ parts: string[],
2230
+ pathowner: Record<string, Record<string, string>>,
2231
+ ): { parent: string, action: string } | null {
2232
+ const at = parts.length - 2
2233
+ if (at < 1 || 'relationship' !== literalName(parts[at]) || isParam(parts[at + 1]) ||
2234
+ !isParam(parts[at - 1])) {
2235
+ return null
2236
+ }
2237
+ const parent = itemAbove(data, parts, at - 1, pathowner)
2238
+ return null == parent ? null : { parent, action: verbActionName([parts[at + 1]]) }
2239
+ }
2240
+
2241
+
2242
+ // A read of a singular literal followed by an identifier key named for
2243
+ // another noun, answering no record or page of its own, views that noun's item: the
2244
+ // noun, with the path's literals as the action, or null. A name key names an
2245
+ // item of the literal itself.
2246
+ function keyNounOf(
2247
+ data: { def: any, work: any },
2248
+ mdesc: any,
2249
+ parts: string[],
2250
+ ): { parent: string, action: string } | null {
2251
+ const key = parts.length - 1
2252
+ const keyName = isParam(parts[key]) ? paramOf(parts[key]) : null
2253
+ const lit = key < 1 || isParam(parts[key - 1]) ? '' : snakify(parts[key - 1])
2254
+ if (!READ_METHODS.includes(mdesc.method) || null == keyName || '' === lit ||
2255
+ depluralize(lit) !== lit || /version/i.test(keyName) ||
2256
+ !ID_KEY_RE.test(canonizeParam(keyName)) ||
2257
+ null != pathNamed(data, '/' + parts.slice(0, key).join('/'))) {
2258
+ return null
2259
+ }
2260
+ const noun = paramNoun(keyName)
2261
+ const schema = getResponseSchema(successResponse(mdesc.responses))
2262
+ if (noun.length < 3 || literalName(parts[key - 1]).split('_').includes(noun) ||
2263
+ responsePayload(schema).record ||
2264
+ (answersPage(schema) && true !== data.work.listed?.[schema['x-ref']])) {
2265
+ return null
2266
+ }
2267
+ let from = key - 1
2268
+ while (0 < from && !isParam(parts[from - 1])) {
2269
+ from--
2270
+ }
2271
+ const literals = parts.slice(from, key).filter((part) => !/^v\d+$/i.test(part))
2272
+ return { parent: noun, action: literals.map(literalName).join('_') }
2273
+ }
2274
+
2275
+
2276
+ // A POST answered by an empty Accepted response creates what the route that
2277
+ // reads its results answers with: `/report/render` beside
2278
+ // `/report/renderResults/{resultId}`. That record's name, with the noun the
2279
+ // verb acts on as the action, or null.
2280
+ function asyncResultOf(
2281
+ data: { def: any, guide: any, work: any },
2282
+ mdesc: any,
2283
+ parts: string[],
2284
+ ): { parent: string, action: string } | null {
2285
+ const responses = mdesc.responses
2286
+ const last = parts[parts.length - 1]
2287
+ if ('POST' !== mdesc.method || null == responses?.['202'] || null != responses?.['200'] ||
2288
+ null != responses?.['201'] || null != getResponseSchema(responses['202']) ||
2289
+ null == last || isParam(last)) {
2290
+ return null
2291
+ }
2292
+ const verb = literalName(last)
2293
+ const prefix = '/' + parts.slice(0, -1).join('/')
2294
+ for (const p of sortedKeys(data.def?.paths ?? {})) {
2295
+ const rest = guideParts(p).slice(parts.length - 1)
2296
+ if (!(guidePath(p) + '/').startsWith(prefix + '/') || guideParts(p).length !== parts.length + 1 ||
2297
+ !isParam(rest[1]) || !literalName(rest[0]).startsWith(verb + '_')) {
2298
+ continue
2299
+ }
2300
+ const read = getResponseSchema(successResponse(data.def.paths[p]?.get?.responses))
2301
+ const xref = read?.['x-ref']
2302
+ if ('string' === typeof xref) {
2303
+ const before = parts[parts.length - 2]
2304
+ const noun = null == before ? verb : isParam(before) ?
2305
+ literalName(parts[parts.length - 3] ?? '') : literalName(before)
2306
+ return { parent: cleanCmp(data, cmpRefName(xref)), action: '' === noun ? verb : noun }
2307
+ }
2308
+ }
2309
+ return null
2310
+ }
2311
+
2312
+
2313
+ // A sub-path under an item key that a read answers with a component and a
2314
+ // write sends or answers with the same one is a resource of its own: the
2315
+ // component's reference, or null.
2316
+ // A remote procedure written into the query string, as `?method=a.photos.getInfo`,
2317
+ // names the object before its verb, and the verb is the action.
2318
+ function methodOf(pathStr: string): { parent: string, action: string, why: string } | null {
2319
+ const m = pathStr.match(/[?&]method=([A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+)/)
2320
+ const names = null == m ? [] : m[1].split('.')
2321
+ const parent = 2 <= names.length ? literalName(names[names.length - 2]) : ''
2322
+ const action = 2 <= names.length ? snakify(names[names.length - 1]) : ''
2323
+ return '' === parent || '' === action ? null : { parent, action, why: 'method-name' }
2324
+ }
2325
+
2326
+
2327
+ // A sub-path of a keyless singleton, read, written and deleted with no schema
2328
+ // and no key beneath it, is an action of that singleton, plural or not.
2329
+ function singletonPartOf(
2330
+ data: { def: any, work: any },
2331
+ parts: string[],
2332
+ pathowner: Record<string, Record<string, string>>,
2333
+ ): { parent: string, action: string, why: string } | null {
2334
+ if (parts.length < 2 || parts.some((part) => isParam(part))) {
2335
+ return null
2336
+ }
2337
+ const pathStr = pathNamed(data, '/' + parts.join('/'))
2338
+ const parentPath = pathNamed(data, '/' + parts.slice(0, -1).join('/'))
2339
+ const pathdef = null == pathStr ? null : data.def.paths[pathStr]
2340
+ const parentdef = null == parentPath ? null : data.def.paths[parentPath]
2341
+ if (null == pathdef || null == parentdef?.get || null == pathdef.get || null == pathdef.delete ||
2342
+ !['put', 'patch', 'post'].some((m) => null != pathdef[m]) ||
2343
+ ['get', 'put', 'patch', 'post', 'delete'].some((m) =>
2344
+ null != getResponseSchema(successResponse(pathdef[m]?.responses))) ||
2345
+ 'array' === getResponseSchema(successResponse(parentdef.get.responses))?.type ||
2346
+ 0 < findPathsWithPrefix(data, pathStr as string, { strict: true })) {
2347
+ return null
2348
+ }
2349
+ const parent = pathowner[parentPath as string]?.GET
2350
+ const action = snakify(parts[parts.length - 1]).replace(/[^a-zA-Z0-9_]/g, '')
2351
+ return null == parent || '' === action ? null : { parent, action, why: 'singleton-part' }
2352
+ }
2353
+
2354
+
2355
+ const ITEM_READ_WORDS = ['detail', 'info']
2356
+ const BINARY_MEDIA_RE = /^(application\/(octet-stream|pdf|zip|gzip)|image\/|audio\/|video\/)/i
2357
+
2358
+ // A read beneath an item key that reads the item itself: its `details` or
2359
+ // `info`, spelled as written, or a download whose response is binary, named
2360
+ // as a view is.
2361
+ function readOfItem(
2362
+ data: { def: any, work: any },
2363
+ mdesc: any,
2364
+ parts: string[],
2365
+ pathowner: Record<string, Record<string, string>>,
2366
+ ): { parent: string, action: string, why: string } | null {
2367
+ if ('GET' !== mdesc.method || 0 === parts.length || isParam(parts[parts.length - 1]) &&
2368
+ !binaryResponse(data.def?.paths?.[mdesc.path]?.get?.responses)) {
2369
+ return null
2370
+ }
2371
+ const lastLit = parts.map((part) => !isParam(part)).lastIndexOf(true)
2372
+ const key = parts.slice(0, lastLit).map((part) => isParam(part)).lastIndexOf(true)
2373
+ if (key < 0 || lastLit < 0) {
2374
+ return null
2375
+ }
2376
+ const literals = parts.slice(key + 1).filter((part) => !isParam(part))
2377
+ const detail = parts.length - 1 === lastLit && key === lastLit - 1 &&
2378
+ ITEM_READ_WORDS.includes(literalName(parts[lastLit]))
2379
+ if (!detail && !binaryResponse(data.def?.paths?.[mdesc.path]?.get?.responses)) {
2380
+ return null
2381
+ }
2382
+ const parent = itemAbove(data, parts, key, pathowner)
2383
+ const action = detail ? snakify(parts[lastLit]).replace(/[^a-zA-Z0-9_]/g, '') :
2384
+ literals.map(literalName).filter((word) => '' !== word).join('_')
2385
+ return null == parent || ID_LITERAL_RE.test(parent) || '' === action ? null :
2386
+ { parent, action, why: detail ? 'detail-of-item' : 'download-of-item' }
2387
+ }
2388
+
2389
+
2390
+ // Every success response declares content, and all of it binary.
2391
+ function binaryResponse(responses: any): boolean {
2392
+ const ok = [responses?.['200'], responses?.['201'], responses?.['206'], rangeResponse(responses)]
2393
+ .filter((response) => null != response?.content)
2394
+ return 0 < ok.length && ok.every((response) => {
2395
+ const media = Object.keys(response.content)
2396
+ return 0 < media.length && media.every((mt) => BINARY_MEDIA_RE.test(mt) ||
2397
+ ('*/*' === mt && 'binary' === response.content[mt]?.schema?.format))
2398
+ })
2399
+ }
2400
+
2401
+
2402
+ function singletonOf(data: { def: any, work: any }, pathStr: string): string | null {
2403
+ const work = data.work
2404
+ work.singletons = work.singletons ?? Object.create(null)
2405
+ if (pathStr in work.singletons) {
2406
+ return work.singletons[pathStr]
2407
+ }
2408
+ let found: string | null = null
2409
+ const parts = guideParts(pathStr)
2410
+ const pathdef = data.def?.paths?.[pathStr]
2411
+ const key = lastKey(parts)
2412
+ if (0 <= key && key < parts.length - 1 && !/version/i.test(parts[key]) && null != pathdef &&
2413
+ 0 === findPathsWithPrefix(data, pathStr, { strict: true })) {
2414
+ const read = getResponseSchema(successResponse((pathdef.get ?? pathdef.query)?.responses))
2415
+ const ref = 'array' === read?.type ? null : read?.['x-ref']
2416
+ if ('string' === typeof ref && ['put', 'patch', 'post'].some((m) =>
2417
+ null != pathdef[m] && (
2418
+ ref === getResponseSchema(successResponse(pathdef[m].responses))?.['x-ref'] ||
2419
+ ref === selectedRequestSchema(data.def, m.toUpperCase(), pathStr)?.['x-ref']))) {
2420
+ found = ref
2421
+ }
2422
+ }
2423
+ work.singletons[pathStr] = found
2424
+ return found
2425
+ }
2426
+
2427
+
2428
+ // A write to a singular literal right after an item key, on a path nothing
2429
+ // reads or extends, whose body declares no id, updates the item: the item's
2430
+ // entity and the literal as the action, or null.
2431
+ function subWriteOfItem(
2432
+ data: { def: any, work: any },
2433
+ mdesc: any,
2434
+ parts: string[],
2435
+ pathowner: Record<string, Record<string, string>>,
2436
+ ): { parent: string, action: string } | null {
2437
+ const pathdef = data.def?.paths?.[mdesc.path]
2438
+ const last = parts[parts.length - 1]
2439
+ const lit = null == last || isParam(last) ? '' : snakify(last)
2440
+ const key = parts.length - 2
2441
+ if (!['PUT', 'PATCH'].includes(mdesc.method) || '' === lit || depluralize(lit) !== lit ||
2442
+ key < 0 || !isParam(parts[key]) || /version/i.test(parts[key]) ||
2443
+ null != pathdef?.get || null != pathdef?.query ||
2444
+ 0 < findPathsWithPrefix(data, mdesc.path, { strict: true })) {
2445
+ return null
2446
+ }
2447
+ const body = selectedRequestSchema(data.def, mdesc.method, mdesc.path) ?? mdesc.requestBody?.schema
2448
+ if (null == body || responsePayload(body).record) {
2449
+ return null
2450
+ }
2451
+ const parent = itemAbove(data, parts, key, pathowner)
2452
+ return null == parent ? null : { parent, action: literalName(last) }
2453
+ }
2454
+
2455
+
2456
+ // The entity of the item route a view hangs off, the entity a read of it
2457
+ // returns, else the noun before the key.
2458
+ function itemAbove(
2459
+ data: { def: any, work: any },
2460
+ parts: string[],
2461
+ key: number,
2462
+ pathowner: Record<string, Record<string, string>>,
2463
+ ): string | null {
2464
+ return keyOwner(data, parts, key, pathowner) ??
2465
+ (0 < key && !isParam(parts[key - 1]) ? literalName(parts[key - 1]) : null)
2466
+ }
2467
+
2468
+
2469
+ // The entity holding the item route that ends at a key.
2470
+ function keyOwner(
2471
+ data: { def: any, work: any },
2472
+ parts: string[],
2473
+ key: number,
2474
+ pathowner: Record<string, Record<string, string>>,
2475
+ ): string | null {
2476
+ const itemPath = key < 0 ? null : pathNamed(data, '/' + parts.slice(0, key + 1).join('/'))
2477
+ const owners = null == itemPath ? {} : (pathowner[itemPath] ?? {})
2478
+ return owners.GET ?? owners.QUERY ?? Object.values(owners).sort()[0] ?? null
2479
+ }
2480
+
2481
+
2482
+ // The index of the last parameter of a path, or -1.
2483
+ function lastKey(parts: string[]): number {
2484
+ let key = -1
2485
+ parts.forEach((part, i) => {
2486
+ if (isParam(part)) {
2487
+ key = i
2488
+ }
2489
+ })
2490
+ return key
2491
+ }
2492
+
2493
+
2494
+ // A literal opening with a verb word is a verb on the nearest resource up
2495
+ // the path: a collection of its own between the key and the verb, else the
2496
+ // key's resource. The action is named for the literals after that resource.
2497
+ // A bare verb right after the key is left to the shape rules.
2498
+ function verbOfItem(
2499
+ data: { def: any, work: any },
2500
+ mdesc: any,
2501
+ parts: string[],
2502
+ pathowner: Record<string, Record<string, string>>,
2503
+ ): { parent: string, action: string } | null {
2504
+ const last = parts[parts.length - 1]
2505
+ if (null == last || isParam(last)) {
2506
+ return null
2507
+ }
2508
+ const words = canonize(last).split('_')
2509
+ const key = lastKey(parts)
2510
+ const bare = 1 === words.length
2511
+ if (!VERB_WORDS.has(words[0]) || (key < 0 && bare) || (0 <= key && /version/i.test(parts[key])) ||
2512
+ (bare && (key === parts.length - 2 || depluralize(snakify(last)) !== snakify(last))) ||
2513
+ 0 < findPathsWithPrefix(data, mdesc.path, { strict: true })) {
2514
+ return null
2515
+ }
2516
+ const keyParent = itemAbove(data, parts, key, pathowner)
2517
+ for (let i = parts.length - 2; key < i; i--) {
2518
+ const lit = snakify(parts[i])
2519
+ if (depluralize(lit) === lit) {
2520
+ continue
2521
+ }
2522
+ const route = pathNamed(data, '/' + parts.slice(0, i + 1).join('/'))
2523
+ const owners = null == route ? {} : (pathowner[route] ?? {})
2524
+ const owner = owners.GET ?? owners.QUERY ?? Object.values(owners).sort()[0]
2525
+ if (null != owner && owner !== keyParent) {
2526
+ return { parent: owner, action: verbActionName(parts.slice(i + 1)) }
2527
+ }
2528
+ }
2529
+ return null == keyParent ? null : { parent: keyParent, action: verbActionName(parts.slice(key + 1)) }
2530
+ }
2531
+
2532
+
2533
+ // The verb keeps its own spelling, plural and all; the literals before it
2534
+ // are path nouns, and an `actions` element only gathers the verb after it.
2535
+ function verbActionName(literals: string[]): string {
2536
+ const at = literals.length - 2
2537
+ const kept = 0 <= at && 'action' === literalName(literals[at]) ?
2538
+ [...literals.slice(0, at), literals[at + 1]] : literals
2539
+ const last = kept.length - 1
2540
+ return kept
2541
+ .map((lit, i) => i < last ? literalName(lit) :
2542
+ snakify(lit.replace(/\.?\{[^}]*\}/g, '')).replace(/[^a-zA-Z0-9_]/g, ''))
2543
+ .join('_')
2544
+ }
2545
+
2546
+
2547
+ // A literal too short for a word names nothing.
2548
+ function shortLiteral(pm: PathMatch): boolean {
2549
+ return canonize(pm[PATH_NAME_INDEX[pm.expr]]).replace(/_/g, '').length < 3
2550
+ }
2551
+
2552
+
2553
+ // The naming literal is a generic word, or a verb word with no literal
2554
+ // before it in the path.
2555
+ function nounless(pm: PathMatch, parts: string[]): boolean {
2556
+ const at = pm.index + PATH_NAME_INDEX[pm.expr]
2557
+ const name = literalName(parts[at])
2558
+ return GENERIC_WORDS.includes(name) ||
2559
+ (VERB_WORDS.has(name) && parts.slice(0, at).every((part) => isParam(part)))
2560
+ }
2561
+
2562
+
2563
+ // The component a route answers with, cleaned, when no tag stands for it.
2564
+ function answeredCmp(mdesc: any): string | null {
2565
+ const ment = mdesc.MethodEntity
2566
+ const cmp = 'tag' === ment?.ref ? null : ment?.cmp
2567
+ return 'string' === typeof cmp && 3 <= cmp.replace(/_/g, '').length ? cmp : null
2568
+ }
2569
+
2570
+
2571
+ // The object an operationId names after its leading verb, less a tail that
2572
+ // opens with via, by or with: getting an access token via a provider names
2573
+ // access_token.
2574
+ function opidObject(opid: any): string | null {
2575
+ const words = 'string' === typeof opid ? canonize(opid).split('_').filter((w) => '' !== w) : []
2576
+ if (words.length < 2 || !VERB_WORDS.has(words[0])) {
2577
+ return null
2578
+ }
2579
+ const tail = words.findIndex((word, i) => 1 < i && OPID_TAIL_WORDS.includes(word))
2580
+ const name = canonize(words.slice(1, tail < 0 ? words.length : tail).join('_'))
2581
+ return name.replace(/_/g, '').length < 3 ? null : name
2582
+ }
2583
+
2584
+
2585
+ // The path of the definition that is the given path with its parameters
2586
+ // normalised, or null.
2587
+ function pathNamed(data: { def: any, work: any }, pathStr: string): string | null {
2588
+ const work = data.work
2589
+ if (null == work.normPaths) {
2590
+ work.normPaths = Object.create(null)
2591
+ for (const p of Object.keys(data.def?.paths ?? {})) {
2592
+ work.normPaths[normalizeParams(p)] = work.normPaths[normalizeParams(p)] ?? p
2593
+ }
2594
+ }
2595
+ return work.normPaths[normalizeParams(pathStr)] ?? null
2596
+ }
2597
+
2598
+
2599
+ // What a response carries past its envelopes: whether it reaches an array of
2600
+ // scalars, and whether the record it reaches declares an id, with that record.
2601
+ function responsePayload(schema: any): { scalars: boolean, record: boolean, node: any } {
2602
+ let node = schema
2603
+ let array = false
2604
+ for (let depth = 0; null != node && 'object' === typeof node && depth < 8; depth++) {
2605
+ if ('array' === node.type) {
2606
+ array = true
2607
+ node = node.items
2608
+ continue
2609
+ }
2610
+ const props = mergedProperties(node)
2611
+ if (null == props) {
2612
+ break
2613
+ }
2614
+ if (null != props.id) {
2615
+ return { scalars: false, record: true, node }
2616
+ }
2617
+ const env = strictEnvelopeProp(props, 'list') ?? strictEnvelopeProp(props, 'load')
2618
+ if (null == env) {
2619
+ break
2620
+ }
2621
+ node = props[env]
2622
+ }
2623
+ const scalar = null != node && 'object' === typeof node &&
2624
+ SCALAR_TYPES.has(node.type) && null == mergedProperties(node)
2625
+ return { scalars: array && scalar, record: false, node }
2626
+ }
2627
+
2628
+
2629
+ // The record component the item route of a path answers with, the path's own
2630
+ // when it ends with a parameter, else the item route beneath it: null for none.
2631
+ function recordOf(
2632
+ data: { def: any, guide: any, work: any },
2633
+ pathStr: string,
2634
+ ): { cmp: string, orig: string, shared: boolean } | null {
2635
+ const work = data.work
2636
+ work.itemRecords = work.itemRecords ?? Object.create(null)
2637
+ if (pathStr in work.itemRecords) {
2638
+ return work.itemRecords[pathStr]
2639
+ }
2640
+ const parts = guideParts(pathStr)
2641
+ const itemPath = isParam(parts[parts.length - 1]) ? pathStr :
2642
+ pathNamed(data, pathStr + '/{}')
2643
+ let found: { cmp: string, orig: string, shared: boolean } | null = null
2644
+ const orig = null == itemPath ? null : itemRecordRef(data, itemPath)
2645
+ if (null != orig) {
2646
+ const cmp = cleanCmp(data, canonizeCmpName(orig)).replace(/_v\d+$/, '')
2647
+ found = { cmp, orig, shared: 1 < (itemRecordRoutes(data)[orig]?.size ?? 0) }
2648
+ }
2649
+ work.itemRecords[pathStr] = found
2650
+ return found
2651
+ }
2652
+
2653
+
2654
+ // The component an item route's read answers with when it declares an id.
2655
+ function itemRecordRef(data: { def: any }, itemPath: string): string | null {
2656
+ const read = data.def?.paths?.[itemPath]?.get
2657
+ const schema = getResponseSchema(successResponse(read?.responses))
2658
+ const payload = responsePayload(schema)
2659
+ const xref = (payload.record ? payload.node :
2660
+ recordNode(schema, paramOf(guideParts(itemPath).slice(-1)[0] ?? '')))?.['x-ref']
2661
+ const m = 'string' === typeof xref ? xref.match(/\/(components\/schemas|definitions)\/(.+)$/) : null
2662
+ return null == m ? null : m[2]
2663
+ }
2664
+
2665
+
2666
+ // The record an item's read answers with: an object declaring an `id` or the
2667
+ // field its route's key names, read through a one-record envelope.
2668
+ function recordNode(schema: any, keyName: string | null): any {
2669
+ const key = null == keyName ? null : canonizeParam(keyName)
2670
+ let node = schema
2671
+ for (let depth = 0; null != node && 'object' === typeof node && depth < 8; depth++) {
2672
+ const props = mergedProperties(node)
2673
+ if (null == props) {
2674
+ return null
2675
+ }
2676
+ if (null != props.id || (null != key && Object.keys(props).some((p) => canonizeParam(p) === key))) {
2677
+ return node
2678
+ }
2679
+ const env = envelopeProp(props, 'load')
2680
+ if (null == env) {
2681
+ return null
2682
+ }
2683
+ node = props[env]
2684
+ }
2685
+ return null
2686
+ }
2687
+
2688
+
2689
+ // A read on a literal right after a collection that answers the collection's
2690
+ // own record is a variant of its list: the collection's entity and the
2691
+ // literal as the action, or null.
2692
+ function variantOfCollection(
2693
+ data: { def: any, guide: any, work: any },
2694
+ mdesc: any,
2695
+ parts: string[],
2696
+ pathowner: Record<string, Record<string, string>>,
2697
+ ): { parent: string, action: string } | null {
2698
+ const last = parts[parts.length - 1]
2699
+ if (!READ_METHODS.includes(mdesc.method) || parts.length < 2 || null == last ||
2700
+ isParam(last) || isParam(parts[parts.length - 2])) {
2701
+ return null
2702
+ }
2703
+ const collection = pathNamed(data, '/' + parts.slice(0, -1).join('/'))
2704
+ const record = null == collection ? null : recordOf(data, collection)
2705
+ if (null == record) {
2706
+ return null
2707
+ }
2708
+ let node = getResponseSchema(successResponse(mdesc.responses))
2709
+ const props = 'array' === node?.type ? null : mergedProperties(node)
2710
+ const env = null == props ? null : envelopeProp(props, 'list')
2711
+ node = null == env || null == props ? node : props[env]
2712
+ const xref = 'array' === node?.type ? node.items?.['x-ref'] : null
2713
+ if ('string' !== typeof xref || xref.match(CMP_REF_RE)?.[2] !== record.orig) {
2714
+ return null
2715
+ }
2716
+ const owners = pathowner[collection as string] ?? {}
2717
+ const parent = owners.GET ?? owners.QUERY ?? record.cmp
2718
+ return { parent, action: literalName(last) }
2719
+ }
2720
+
2721
+
2722
+ // The collections whose item routes answer each record, by the item path
2723
+ // with its parameters normalised: a record shared by several names them all,
2724
+ // and each collection's literal becomes its action.
2725
+ function itemRecordRoutes(data: { def: any, work: any }): Record<string, Set<string>> {
2726
+ const work = data.work
2727
+ if (null == work.itemRecordRoutes) {
2728
+ work.itemRecordRoutes = Object.create(null)
2729
+ for (const p of Object.keys(data.def?.paths ?? {})) {
2730
+ const parts = guideParts(p)
2731
+ const orig = 0 < parts.length && isParam(parts[parts.length - 1]) ? itemRecordRef(data, p) : null
2732
+ if (null != orig) {
2733
+ (work.itemRecordRoutes[orig] = work.itemRecordRoutes[orig] ?? new Set()).add(normalizeParams(p))
2734
+ }
2735
+ }
2736
+ }
2737
+ return work.itemRecordRoutes
2738
+ }
2739
+
2740
+
2741
+ // A record named for a literal of the path and the naming literal, as
2742
+ // `call_route_allowed_caller` under `/call_routes/{id}/allowed_callers`, is
2743
+ // qualified rather than wrapped.
2744
+ function pathQualified(parts: string[], cmp: string, lit: string): boolean {
2745
+ if (!cmp.endsWith('_' + lit)) {
2746
+ return false
2747
+ }
2748
+ const prefix = cmp.slice(0, -(lit.length + 1))
2749
+ return parts.some((part) => !isParam(part) && literalName(part) === prefix)
2750
+ }
2751
+
2752
+
2753
+ // Whether a component's name holds the literal's words in a row, compared
2754
+ // singular: such a name wraps the literal and the literal keeps naming.
2755
+ function wrapsLiteral(cmp: string, lit: string): boolean {
2756
+ const cw = cmp.split('_').map((w) => depluralize(w))
2757
+ const lw = lit.split('_').map((w) => depluralize(w))
2758
+ for (let i = 0; i + lw.length <= cw.length; i++) {
2759
+ if (lw.every((w, j) => w === cw[i + j])) {
2760
+ return true
2761
+ }
2762
+ }
2763
+ return false
2764
+ }
2765
+
2766
+
2767
+ // A POST addressed to a singular literal that names no component, with no
2768
+ // item route above it to be a verb on or beneath it to be a collection, is a
2769
+ // command: its body component names it.
2770
+ function commandName(
2771
+ data: { def: any, guide: any, work: any },
2772
+ mdesc: any,
2773
+ pm: PathMatch,
2774
+ parts: string[],
2775
+ why: string[],
2776
+ ): string | null {
2777
+ const ment = mdesc.MethodEntity
2778
+ if ('POST' !== mdesc.method || null != ment.verb_on_parent ||
2779
+ !LITERAL_LAST_SHAPES.includes(pm.expr)) {
2780
+ return null
2781
+ }
2782
+ const last = getelem(pm, -1)
2783
+ const lit = snakify(last)
2784
+ if ('' === lit || depluralize(lit) !== lit || pathNoun(pm, parts, []) !== literalName(last) ||
2785
+ isOrigCmp(data, literalName(last)) || null != keyParamOf(data.def, mdesc.path, data.work) ||
2786
+ ('t/p/t/' === pm.expr && null != leafItemRoute(data, pm)) || readsRecord(data, mdesc.path)) {
2787
+ return null
2788
+ }
2789
+ const source = commandSource(data, mdesc)
2790
+ if (null != source) {
2791
+ why.push(('body' === source.from ? 'command=' : 'command-opid=') + source.name)
2792
+ }
2793
+ return source?.name ?? null
2794
+ }
2795
+
2796
+
2797
+ // What names a command: its body component, else, when no response component
2798
+ // names it either, the object of its operationId.
2799
+ function commandSource(
2800
+ data: { def: any, guide: any, work: any },
2801
+ mdesc: any,
2802
+ ): { name: string, from: 'body' | 'opid' } | null {
2803
+ const body = commandBodyName(data, mdesc)
2804
+ if (null != body) {
2805
+ return { name: body, from: 'body' }
2806
+ }
2807
+ const responded = getResponseSchema(successResponse(mdesc.responses))
2808
+ const object = null == namingRef(responded, data.work.envelope) ? opidObject(mdesc.operationId) : null
2809
+ return null == object ? null : { name: object, from: 'opid' }
2810
+ }
2811
+
2812
+
2813
+ // A path whose read answers with a record is a resource, not a command.
2814
+ function readsRecord(data: { def: any }, pathStr: string): boolean {
2815
+ const mdef = data.def?.paths?.[pathStr]?.get
2816
+ return null != mdef && responsePayload(getResponseSchema(successResponse(mdef.responses))).record
2817
+ }
2818
+
2819
+
2820
+ // The name a command's body component gives under any media type, the first
2821
+ // member of a oneOf, its affixes stripped. A body that is no object, such as
2822
+ // an upload, names nothing.
2823
+ function commandBodyName(data: { def: any, guide: any, work: any }, mdesc: any): string | null {
2824
+ const body = selectedRequestSchema(data.def, mdesc.method, mdesc.path) ?? mdesc.requestBody?.schema
2825
+ const member = Array.isArray(body?.oneOf) ? body.oneOf[0] :
2826
+ Array.isArray(body?.anyOf) ? body.anyOf[0] : body
2827
+ const xref = member?.['x-ref']
2828
+ if ('string' !== typeof xref || null == mergedProperties(member)) {
2829
+ return null
2830
+ }
2831
+ let name = cleanCmp(data, canonizeCmpName(cmpRefName(xref)))
2832
+ for (;;) {
2833
+ const suffix = COMMAND_SUFFIXES.find((sfx) => name.endsWith(sfx) && sfx.length < name.length)
2834
+ if (null == suffix) {
2835
+ break
2836
+ }
2837
+ name = name.slice(0, -suffix.length)
2838
+ }
2839
+ return name.replace(/_/g, '').length < 3 ? null : name
2840
+ }
2841
+
2842
+
2843
+ // A read on a command's path is the command's load.
2844
+ function commandTwin(
2845
+ data: { def: any, guide: any, work: any },
2846
+ mdesc: any,
2847
+ pm: PathMatch,
2848
+ parts: string[],
2849
+ why: string[],
2850
+ ): string | null {
2851
+ const post = data.def?.paths?.[mdesc.path]?.post
2852
+ if (!READ_METHODS.includes(mdesc.method) || null == post || 'object' !== typeof post) {
2853
+ return null
2854
+ }
2855
+ const twin = { method: 'POST', path: mdesc.path, responses: post.responses, MethodEntity: {} }
2856
+ const name = commandName(data, twin, pm, parts, [])
2857
+ if (null != name) {
2858
+ why.push('command-twin=' + name)
2859
+ }
2860
+ return name
2861
+ }
2862
+
2863
+
2864
+ // The read verb a POST's last literal opens with, where it answers a collection.
2865
+ function postReadVerb(mdesc: any, pm: PathMatch | null | undefined, parts: string[]): string | null {
2866
+ if ('POST' !== mdesc.method) {
2867
+ return null
2868
+ }
2869
+ const verbs = verbParts(parts)
2870
+ const last = verbs[verbs.length - 1]
2871
+ const lit = snakify(last)
2872
+ const verb = READ_VERBS.find((v) => lit === v || lit.startsWith(v + '_'))
2873
+ return null == verb || isParam(last) || !isListResponse(mdesc, pm, mdesc.path, []) ? null : verb
2874
+ }
2875
+
2876
+
2877
+ // A POST whose literal opens with a read verb and answers with a collection
2878
+ // lists the noun the literal names, the body its filter; '' keeps the shape's
2879
+ // name where the literal is the verb alone.
2880
+ function postRead(
2881
+ mdesc: any,
2882
+ pm: PathMatch,
2883
+ parts: string[],
2884
+ why: string[],
2885
+ ): string | null {
2886
+ const verb = postReadVerb(mdesc, pm, parts)
2887
+ if (null == verb) {
2888
+ return null
2889
+ }
2890
+ const lit = snakify(verbParts(parts)[verbParts(parts).length - 1])
2891
+ mdesc.MethodEntity.post_read = true
2892
+ why.push('post-read=' + verb)
2893
+ const noun = lit.slice(verb.length + 1)
2894
+ return '' === noun ? '' : literalName(noun)
1798
2895
  }
1799
2896
 
1800
2897
 
@@ -1871,7 +2968,7 @@ function itemOfCollection(
1871
2968
  const work = data.work
1872
2969
  const collection = naming.collection
1873
2970
  const cmp = mdesc.MethodEntity.cmp
1874
- const segment = canonize(collection.substring(collection.lastIndexOf('/') + 1))
2971
+ const segment = literalName(collection.substring(collection.lastIndexOf('/') + 1))
1875
2972
  const own = segment === cmp
1876
2973
  const tagged = own ? segment : cmp + '_' + segment
1877
2974
  const tagOwn = own ? (path: string) => tagNamesRoute(data, path, cmp) : undefined
@@ -1980,7 +3077,7 @@ function isOrigCmp(data: any, name: string) {
1980
3077
 
1981
3078
 
1982
3079
  function entityOccursInPath(parts: string[], entname: string) {
1983
- return parts.some(p => p[0] !== '{' && canonize(p.toLowerCase()) === entname)
3080
+ return parts.some(p => p[0] !== '{' && literalName(p.toLowerCase()) === entname)
1984
3081
  }
1985
3082
 
1986
3083
 
@@ -1989,13 +3086,13 @@ function entityPathMatch_tpe(
1989
3086
  pm: PathMatch, mdesc: any, why: string[]
1990
3087
  ) {
1991
3088
  const ment = mdesc.MethodEntity
1992
- const pathNameIndex = PATH_NAME_INDEX['t/p/']
1993
-
1994
3089
  why.push('path=t/p/')
1995
- const origPathName = pm[pathNameIndex]
1996
- let entname = canonize(origPathName)
3090
+ let entname = pathNoun(pm, data.work.pathmap[mdesc.path].parts, why)
1997
3091
 
1998
- if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
3092
+ if (entname !== literalName(pm[PATH_NAME_INDEX[pm.expr]]) && 'tag' !== ment.ref) {
3093
+ why.push('verb-noun=' + entname)
3094
+ }
3095
+ else if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
1999
3096
  let ecm = entityCmpMatch(data, entname, mdesc, why)
2000
3097
  entname = ecm.name
2001
3098
  }
@@ -2009,16 +3106,25 @@ function entityPathMatch_tpe(
2009
3106
 
2010
3107
  function entityPathMatch_pte(
2011
3108
  data: { def: any, guide: any, work: any },
2012
- pm: PathMatch, mdesc: any, why: string[]
3109
+ pm: PathMatch, mdesc: any,
3110
+ pathowner: Record<string, Record<string, string>>,
3111
+ why: string[]
2013
3112
  ) {
2014
3113
  const ment = mdesc.MethodEntity
2015
- const pathNameIndex = PATH_NAME_INDEX['p/t/']
2016
-
2017
3114
  why.push('path=p/t/')
2018
- const origPathName = pm[pathNameIndex]
2019
- let entname = canonize(origPathName)
2020
-
2021
- if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
3115
+ const parts: string[] = data.work.pathmap[mdesc.path].parts
3116
+ let entname = pathNoun(pm, parts, why)
3117
+
3118
+ if (entname !== literalName(pm[PATH_NAME_INDEX[pm.expr]]) && 'tag' !== ment.ref) {
3119
+ // A verb after a run of keys acts on the item they address.
3120
+ const owner = keyOwner(data, parts, lastKey(parts), pathowner)
3121
+ if (null != owner) {
3122
+ entname = owner
3123
+ ment.verb_on_parent = getelem(pm, -1)
3124
+ }
3125
+ why.push('verb-noun=' + entname)
3126
+ }
3127
+ else if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
2022
3128
  let ecm = entityCmpMatch(data, entname, mdesc, why)
2023
3129
  entname = ecm.name
2024
3130
  }
@@ -2035,13 +3141,13 @@ function entityPathMatch_te(
2035
3141
  pm: PathMatch, mdesc: any, why: string[]
2036
3142
  ) {
2037
3143
  const ment = mdesc.MethodEntity
2038
- const pathNameIndex = PATH_NAME_INDEX['t/']
2039
-
2040
3144
  why.push('path=t/')
2041
- const origPathName = pm[pathNameIndex]
2042
- let entname = canonize(origPathName)
3145
+ let entname = pathNoun(pm, data.work.pathmap[mdesc.path].parts, why)
2043
3146
 
2044
- if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
3147
+ if (entname !== literalName(pm[PATH_NAME_INDEX[pm.expr]]) && 'tag' !== ment.ref) {
3148
+ why.push('verb-noun=' + entname)
3149
+ }
3150
+ else if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
2045
3151
  let ecm = entityCmpMatch(data, entname, mdesc, why)
2046
3152
  entname = ecm.name
2047
3153
  }
@@ -2058,13 +3164,13 @@ function entityPathMatch_tpp(
2058
3164
  pm: PathMatch, mdesc: any, why: string[]
2059
3165
  ) {
2060
3166
  const ment = mdesc.MethodEntity
2061
- const pathNameIndex = PATH_NAME_INDEX['t/p/p']
2062
-
2063
3167
  why.push('path=t/p/p')
2064
- const origPathName = pm[pathNameIndex]
2065
- let entname = canonize(origPathName)
3168
+ let entname = pathNoun(pm, data.work.pathmap[mdesc.path].parts, why)
2066
3169
 
2067
- if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
3170
+ if (entname !== literalName(pm[PATH_NAME_INDEX[pm.expr]]) && 'tag' !== ment.ref) {
3171
+ why.push('verb-noun=' + entname)
3172
+ }
3173
+ else if (null != ment.cmp || probableEntityMethod(data, mdesc, pm, why)) {
2068
3174
  let ecm = entityCmpMatch(data, entname, mdesc, why)
2069
3175
  entname = ecm.name
2070
3176
  }
@@ -2084,7 +3190,7 @@ function getRequestBodySchema(def: any, mdesc: any) {
2084
3190
  // The response an operation's result is read from, down to an Accepted
2085
3191
  // response when nothing else answers, whose body may be the job it queued.
2086
3192
  function successResponse(responses: any): any {
2087
- return responses?.[200] ?? responses?.[201] ?? responses?.[202]
3193
+ return responses?.[200] ?? responses?.[201] ?? responses?.[202] ?? rangeResponse(responses)
2088
3194
  }
2089
3195
 
2090
3196
 
@@ -2092,8 +3198,8 @@ function successResponse(responses: any): any {
2092
3198
  // order they are tried. An Accepted response names nothing, since its body
2093
3199
  // may describe the work rather than the resource.
2094
3200
  function successSchemas(responses: any): any[] {
2095
- return ['200', '201']
2096
- .map((rescode) => getResponseSchema(responses?.[rescode]))
3201
+ return [responses?.['200'], responses?.['201'], rangeResponse(responses)]
3202
+ .map((response) => getResponseSchema(response))
2097
3203
  .filter((schema) => null != schema)
2098
3204
  }
2099
3205
 
@@ -2174,8 +3280,7 @@ function namingRef(schema: any, envelope: Record<string, string>): string | unde
2174
3280
 
2175
3281
 
2176
3282
  function getResponseSchema(response: any) {
2177
- return response?.content?.['application/json']?.schema ??
2178
- response?.schema
3283
+ return responseSchema(response)
2179
3284
  }
2180
3285
 
2181
3286
 
@@ -2214,7 +3319,7 @@ function routeRecordRef(
2214
3319
  ): string | null {
2215
3320
  const responses = def?.paths?.[pathStr]?.[method.toLowerCase()]?.responses
2216
3321
  const schema = getResponseSchema(accepted ? successResponse(responses) :
2217
- responses?.[200] ?? responses?.[201])
3322
+ responses?.[200] ?? responses?.[201] ?? rangeResponse(responses))
2218
3323
  if (null == schema || 'object' !== typeof schema) {
2219
3324
  return null
2220
3325
  }
@@ -2241,6 +3346,20 @@ function inferEntityName(
2241
3346
  why: string[],
2242
3347
  ): string | null {
2243
3348
 
3349
+ // A route with no literal is named for the component it answers, else
3350
+ // for its first parameter's noun, a version aside.
3351
+ const answered = answeredCmp(mdesc)
3352
+ if (null != answered) {
3353
+ why.push('infer-answers=' + answered)
3354
+ return answered
3355
+ }
3356
+ const keys = parts.filter((part) => isParam(part) && !/version/i.test(part))
3357
+ const noun = 0 < keys.length ? paramNoun(paramOf(keys[0])) : ''
3358
+ if (3 <= noun.length) {
3359
+ why.push('infer-param')
3360
+ return noun
3361
+ }
3362
+
2244
3363
  if (mdesc.operationId) {
2245
3364
  const opid = stripOperationVerb(canonize(mdesc.operationId))
2246
3365
  if (opid.length >= 3) {
@@ -2250,7 +3369,8 @@ function inferEntityName(
2250
3369
  }
2251
3370
 
2252
3371
  // Try response schema title
2253
- const response = mdesc.responses?.[200] ?? mdesc.responses?.[201]
3372
+ const response = mdesc.responses?.[200] ?? mdesc.responses?.[201] ??
3373
+ rangeResponse(mdesc.responses)
2254
3374
  const resSchema = getResponseSchema(response)
2255
3375
  if (resSchema?.title) {
2256
3376
  const title = canonize(resSchema.title)
@@ -2263,7 +3383,7 @@ function inferEntityName(
2263
3383
  // Try last non-param path segment
2264
3384
  for (let i = parts.length - 1; i >= 0; i--) {
2265
3385
  if (!isParam(parts[i])) {
2266
- const seg = canonize(parts[i])
3386
+ const seg = literalName(parts[i])
2267
3387
  if (seg.length >= 3) {
2268
3388
  why.push('infer-path-seg')
2269
3389
  return seg
@@ -2271,6 +3391,13 @@ function inferEntityName(
2271
3391
  }
2272
3392
  }
2273
3393
 
3394
+ // A tag names only a route with no usable literal.
3395
+ const tag = mdesc.MethodEntity?.cmp
3396
+ if ('tag' === mdesc.MethodEntity?.ref && 'string' === typeof tag && 3 <= tag.length) {
3397
+ why.push('infer-tag')
3398
+ return tag
3399
+ }
3400
+
2274
3401
  return null
2275
3402
  }
2276
3403
 
@@ -2283,7 +3410,8 @@ function probableEntityMethod(
2283
3410
  ) {
2284
3411
  const reqSchema = getRequestBodySchema(data.def, mdesc)
2285
3412
 
2286
- const response = mdesc.responses?.['201'] || mdesc.responses?.['200']
3413
+ const response = mdesc.responses?.['201'] || mdesc.responses?.['200'] ||
3414
+ rangeResponse(mdesc.responses)
2287
3415
  const resSchema = getResponseSchema(response)
2288
3416
  const noResponse = null == resSchema && null != mdesc.responses?.['204']
2289
3417
 
@@ -2375,7 +3503,48 @@ function entityCmpMatch(
2375
3503
  const unversioned = (ment.cmp ?? '').replace(/_v\d+$/, '')
2376
3504
  const qualifies = unversioned !== ment.cmp && unversioned.endsWith('_' + entname)
2377
3505
 
3506
+ const record = recordOf(data, mdesc.path)
3507
+ const parts: string[] = data.work.pathmap[mdesc.path].parts
3508
+ const recordWraps = null != record && record.cmp !== entname &&
3509
+ wrapsLiteral(record.cmp, entname) && !pathQualified(parts, record.cmp, entname)
3510
+ const cmpWraps = null != ment.cmp && 'tag' !== ment.ref && ment.cmp !== entname &&
3511
+ wrapsLiteral(ment.cmp, entname) && !pathQualified(parts, ment.cmp, entname)
3512
+
3513
+ // The key parameter names the component, whatever the literal beside it:
3514
+ // `/s/{shelf}` answering with a Shelf.
2378
3515
  if (
3516
+ null != ment.cmp
3517
+ && entname != ment.cmp
3518
+ && 'tag' !== ment.ref
3519
+ && keyParamNames(data, mdesc, ment.cmp)
3520
+ ) {
3521
+ why.push('cmp-names-key')
3522
+ out.name = ment.cmp
3523
+ out.orig = ment.origcmp
3524
+ out.cmpish = true
3525
+ out.pathish = false
3526
+ }
3527
+
3528
+ // The record an item route answers names the item and its collection,
3529
+ // whatever its frequency, unless the record's name wraps the literal's.
3530
+ else if (
3531
+ null != record
3532
+ && record.cmp !== entname
3533
+ && !recordWraps
3534
+ ) {
3535
+ why.push('cmp-record=' + record.orig)
3536
+ out.name = record.cmp
3537
+ out.orig = record.orig
3538
+ out.cmpish = true
3539
+ out.pathish = false
3540
+ ment.record_named = true
3541
+ if (record.shared) {
3542
+ ment.collection_action = entname
3543
+ why.push('collection-action=' + entname)
3544
+ }
3545
+ }
3546
+
3547
+ else if (
2379
3548
  null != ment.cmp
2380
3549
  && entname != ment.cmp
2381
3550
  && !ment.cmp.startsWith(entname)
@@ -2384,13 +3553,22 @@ function entityCmpMatch(
2384
3553
  why.push('cmp-shared')
2385
3554
  }
2386
3555
 
2387
- if (qualifies) {
3556
+ // A tag that is not the path's own noun groups routes; the noun names them.
3557
+ if ('tag' === ment.ref && !ID_LITERAL_RE.test(entname) &&
3558
+ !tagHolds(data, data.work.pathmap[mdesc.path].parts, mdesc.path, ment.cmp)) {
3559
+ why.push('path-over-tag')
3560
+ }
3561
+ else if (qualifies) {
2388
3562
  why.push('cmp-qualifies-path')
2389
3563
  out.name = unversioned
2390
3564
  out.orig = ment.origcmp
2391
3565
  out.cmpish = true
2392
3566
  out.pathish = false
2393
3567
  }
3568
+ // A component that wraps the literal's words is the literal's own shape.
3569
+ else if (recordWraps || cmpWraps) {
3570
+ why.push('path-over-wrapper=' + (recordWraps ? record.orig : ment.origcmp))
3571
+ }
2394
3572
  else if (cmpInfrequent && !cmpShared) {
2395
3573
  why.push('cmp-primary')
2396
3574
  out.name = ment.cmp
@@ -2415,9 +3593,13 @@ function entityCmpMatch(
2415
3593
  else if (
2416
3594
  'DELETE' === mdesc.method
2417
3595
  && null == ment.cmp
3596
+ && !recordWraps
2418
3597
  ) {
2419
3598
  let cmps: { cmp: string, origcmp: string }[] =
2420
3599
  findcmps(data, mdesc.path, ['responses'], { uniq: true })
3600
+ .flatMap((found) => unwrapCmp(data.guide.metrics, found, why))
3601
+ .filter((found) => !genericCmp(found.cmp, data.guide.metrics.count.origcmprefs,
3602
+ cmpSchemaOf(data.def, found.origcmp)))
2421
3603
 
2422
3604
  if (1 === cmps.length) {
2423
3605
  out.name = cmps[0].cmp
@@ -2443,6 +3625,122 @@ function entityCmpMatch(
2443
3625
  }
2444
3626
 
2445
3627
 
3628
+ // A tag keeps naming a route whose noun it is not when it names a literal
3629
+ // before the naming literal and the route is a leaf, or ends with a key
3630
+ // whose literal is singular: a selector or a view of the tag's resource.
3631
+ function tagHolds(data: { def: any }, parts: string[], pathStr: string, tag: string): boolean {
3632
+ const pm = matchEntityPath(parts)
3633
+ if (null == pm || VERSION_TAG_RE.test(tag)) {
3634
+ return false
3635
+ }
3636
+ const at = pm.index + PATH_NAME_INDEX[pm.expr]
3637
+ const tagAt = parts.slice(0, at).findIndex((part) => !isParam(part) && literalName(part) === tag)
3638
+ if (tagAt < 0) {
3639
+ return false
3640
+ }
3641
+ const lit = snakify(parts[at])
3642
+ const singular = '' !== lit && depluralize(lit) === lit
3643
+ if (isParam(parts[parts.length - 1])) {
3644
+ return singular
3645
+ }
3646
+ if (0 < findPathsWithPrefix(data, pathStr, { strict: true })) {
3647
+ return false
3648
+ }
3649
+ // Beneath a key a leaf views the keyed resource, unless it is a singular
3650
+ // sub-read answering an id of its own rather than projecting the literal;
3651
+ // without one it is a selector, or what the tag's verb acts over. A key
3652
+ // after another literal keys that literal's resource, not the tag's.
3653
+ const keyAt = parts.slice(0, at).map((part) => isParam(part)).lastIndexOf(true)
3654
+ if (0 <= keyAt) {
3655
+ if (parts.slice(tagAt + 1, keyAt).some((part) => !isParam(part))) {
3656
+ return false
3657
+ }
3658
+ const schema = getResponseSchema(successResponse(data.def?.paths?.[pathStr]?.get?.responses))
3659
+ const name = literalName(parts[at])
3660
+ const projects = Object.keys(mergedProperties(schema) ?? {}).some((prop) =>
3661
+ canonize(prop) === name || canonize(prop).startsWith(name + '_'))
3662
+ return !(singular && 'array' !== schema?.type && !projects && responsePayload(schema).record)
3663
+ }
3664
+ return singular || VERB_WORDS.has(literalName(parts[tagAt]))
3665
+ }
3666
+
3667
+
3668
+ // The key parameter names the component, as a bucket's key does beside the
3669
+ // literal b, and a collection through the item route beneath it.
3670
+ function keyParamNames(data: { def: any, work: any }, mdesc: any, cmp: string): boolean {
3671
+ const key = keyParamOf(data.def, mdesc.path, data.work)
3672
+ return null != key && canonizeParam(key) === cmp
3673
+ }
3674
+
3675
+
3676
+ // The name of the parameter that keys a route's records: its own trailing
3677
+ // parameter, or the one the item route directly beneath a collection takes.
3678
+ function keyParamOf(def: any, pathStr: string, work: { childKeys?: Record<string, string> }): string | null {
3679
+ const parts = guideParts(pathStr)
3680
+ const pm = matchEntityPath(parts)
3681
+ if (null == pm) {
3682
+ return null
3683
+ }
3684
+ const last = parts[parts.length - 1]
3685
+ if ((pm.expr.endsWith('p/') || 't/p/p' === pm.expr) && isParam(last)) {
3686
+ return paramOf(last)
3687
+ }
3688
+ if (isParam(last)) {
3689
+ return null
3690
+ }
3691
+ work.childKeys = work.childKeys ?? childKeyIndex(def)
3692
+ return work.childKeys[normalizeParams(pathStr)] ?? null
3693
+ }
3694
+
3695
+
3696
+ function normalizeParams(pathStr: string): string {
3697
+ return guidePath(pathStr).replace(/\{[^}]+\}/g, '{}')
3698
+ }
3699
+
3700
+
3701
+ // The parameter each path takes directly beneath it, keyed by the path with
3702
+ // its parameters normalised.
3703
+ function childKeyIndex(def: any): Record<string, string> {
3704
+ const index: Record<string, string> = Object.create(null)
3705
+ for (const p of Object.keys(def?.paths ?? {}).sort()) {
3706
+ const parts = guideParts(p)
3707
+ const last = parts[parts.length - 1]
3708
+ if (1 < parts.length && isParam(last)) {
3709
+ const parent = normalizeParams('/' + parts.slice(0, -1).join('/'))
3710
+ index[parent] = index[parent] ?? paramOf(last)
3711
+ }
3712
+ }
3713
+ return index
3714
+ }
3715
+
3716
+
3717
+ // A wrapper names the component it wraps, or nothing: the candidate is
3718
+ // replaced or dropped. The replacement keeps the candidate's other fields.
3719
+ function unwrapCmp<T extends { cmp: string, origcmp: string, val?: string, origcmpref?: string }>(
3720
+ metrics: GuideMetrics,
3721
+ xref: T,
3722
+ why: string[],
3723
+ ): T[] {
3724
+ const inner = wrapperOf(xref.cmp, Object.keys(metrics.found.cmp).sort())
3725
+ if (null == inner) {
3726
+ return [xref]
3727
+ }
3728
+ why.push('wrapper=' + xref.cmp + ('' === inner ? '' : '>' + inner))
3729
+ if ('' === inner) {
3730
+ return []
3731
+ }
3732
+ const orig = (metrics.found.cmp[inner] as any)?.orig ?? inner
3733
+ const out = { ...xref, cmp: inner, origcmp: orig }
3734
+ if (null != xref.val) {
3735
+ out.val = xref.val.replace(/[^/]+$/, orig)
3736
+ }
3737
+ if (null != xref.origcmpref) {
3738
+ out.origcmpref = inner
3739
+ }
3740
+ return [out]
3741
+ }
3742
+
3743
+
2446
3744
  function cmpOccursInPath(data: { def: any, work: any }, cmpname: string): boolean {
2447
3745
  if (null == data.work.potentialCmpsFromPaths) {
2448
3746
  data.work.potentialCmpsFromPaths = Object.create(null)
@@ -2451,7 +3749,7 @@ function cmpOccursInPath(data: { def: any, work: any }, cmpname: string): boolea
2451
3749
 
2452
3750
  parts
2453
3751
  .filter(p => !p.startsWith('{'))
2454
- .map(p => data.work.potentialCmpsFromPaths[canonize(p)] = true)
3752
+ .map(p => data.work.potentialCmpsFromPaths[literalName(p)] = true)
2455
3753
  })
2456
3754
  }
2457
3755
 
@@ -2487,7 +3785,7 @@ function pathResource(parts: string[], method: string): string | null {
2487
3785
  return null
2488
3786
  }
2489
3787
 
2490
- return canonize(pm[PATH_NAME_INDEX[pm.expr]])
3788
+ return literalName(pm[PATH_NAME_INDEX[pm.expr]])
2491
3789
  }
2492
3790
 
2493
3791
 
@@ -2751,13 +4049,10 @@ function isListResponse(
2751
4049
 
2752
4050
  if (!islist && !endParamBare) {
2753
4051
  const properties = resolveSchemaProperties(schema)
2754
-
2755
- each(properties, (prop) => {
2756
- if (prop.type === 'array') {
2757
- why.push('array-prop:' + prop.key$)
2758
- islist = true
2759
- }
2760
- })
4052
+ for (const key of listingProps(properties, pathStr)) {
4053
+ why.push('array-prop:' + key)
4054
+ islist = true
4055
+ }
2761
4056
  }
2762
4057
 
2763
4058
  if (!islist) {
@@ -2809,7 +4104,7 @@ function updateAction(
2809
4104
  ) {
2810
4105
  if (
2811
4106
  // Entity not already encoding action.
2812
- !entityDesc.name.endsWith(canonize(actionName))
4107
+ !entityDesc.name.endsWith(literalName(actionName))
2813
4108
  && null == pathdesc.action[actionName]
2814
4109
  ) {
2815
4110
  pathdesc.action[actionName] = {
@@ -2851,7 +4146,7 @@ function updateParamRename(
2851
4146
  // The clash is with what the path's OTHER parameters end up called: their
2852
4147
  // rename if they have one, their canonical name if not.
2853
4148
  const otherParams = (path.match(/\{([^}]+)\}/g) || [])
2854
- .map((seg) => seg.slice(1, -1))
4149
+ .map((seg) => paramOf(seg))
2855
4150
  .filter((name) => name !== oldParamName)
2856
4151
 
2857
4152
  const takenBy =
@@ -2902,7 +4197,11 @@ function updateParamRename(
2902
4197
 
2903
4198
 
2904
4199
  function isParam(partStr: string) {
2905
- return '{' === partStr[0] && '}' === partStr[partStr.length - 1]
4200
+ if (null == partStr) {
4201
+ return false
4202
+ }
4203
+ const part = partStr.replace(/^\./, '').replace(/\}\.[A-Za-z0-9]+$/, '}')
4204
+ return '{' === part[0] && '}' === part[part.length - 1]
2906
4205
  }
2907
4206
 
2908
4207
 
@@ -2913,16 +4212,21 @@ function isSingular(part: string): boolean {
2913
4212
  }
2914
4213
 
2915
4214
 
2916
- // A segment holding a placeholder, whole or beside other text, names no verb.
4215
+ // A segment holding a placeholder names no verb, unless the placeholder only
4216
+ // trails a literal, as a format does in `retract{format}`.
2917
4217
  function isVerb(partStr: string): boolean {
2918
- return !String(partStr ?? '').includes('{')
4218
+ const part = String(partStr ?? '')
4219
+ const lit = part.replace(/(\.?\{[^}]*\})+$/, '')
4220
+ return !part.includes('{') || ('' !== lit && !lit.includes('{'))
2919
4221
  }
2920
4222
 
2921
4223
 
4224
+ const CUSTOM_METHOD_RE = /^(.+):([A-Za-z][\w-]*)$/
4225
+
2922
4226
  // A custom method (`/schedules:count`, `/users/{id}:activate`) reads as a
2923
4227
  // trailing verb segment after what it acts on.
2924
4228
  function verbParts(parts: string[]): string[] {
2925
- const m = (parts[parts.length - 1] ?? '').match(/^(.+):([A-Za-z][\w-]*)$/)
4229
+ const m = (parts[parts.length - 1] ?? '').match(CUSTOM_METHOD_RE)
2926
4230
  return null == m ? parts : [...parts.slice(0, -1), m[1], m[2]]
2927
4231
  }
2928
4232
 
@@ -2977,7 +4281,7 @@ function entityParamNames(
2977
4281
  parts.forEach((part, partI) => {
2978
4282
  if (isParam(part)) {
2979
4283
  const place = parts.slice(0, partI + 1).join('/')
2980
- ;(places[place] = places[place] ?? []).push({ pathStr, param: part.slice(1, -1) })
4284
+ ;(places[place] = places[place] ?? []).push({ pathStr, param: paramOf(part) })
2981
4285
  }
2982
4286
  })
2983
4287
  }
@@ -3024,7 +4328,7 @@ function paramNameTaken(
3024
4328
  return Object.keys(renames).some((other) =>
3025
4329
  other !== param && renames[other] === name) ||
3026
4330
  (pathStr.match(/\{([^}]+)\}/g) || [])
3027
- .map((seg) => seg.slice(1, -1))
4331
+ .map((seg) => paramOf(seg))
3028
4332
  .some((other) => other !== param && null == renames[other] &&
3029
4333
  canonize(other) === name)
3030
4334
  }
@@ -3159,17 +4463,67 @@ function hasMethod(def: any, pathStr: string, methodName: string) {
3159
4463
 
3160
4464
 
3161
4465
  export {
4466
+ methodOf,
4467
+ singletonPartOf,
4468
+ readOfItem,
4469
+ keyOwner,
3162
4470
  answeredRefs,
4471
+ collectionOwner,
4472
+ listedRefs,
4473
+ pathAnswersPage,
4474
+ pathAnswersRecordMap,
4475
+ randomRoute,
4476
+ selectorRoute,
4477
+ namedRecord,
4478
+ verbAfterNoun,
4479
+ warnListBody,
3163
4480
  arrayBodyField,
4481
+ commandBodyName,
4482
+ commandTwin,
4483
+ itemAbove,
4484
+ pathQualified,
4485
+ readsRecord,
4486
+ recordOf,
4487
+ responsePayload,
4488
+ cmpSchemaOf,
4489
+ tagHolds,
4490
+ wrapsLiteral,
4491
+ isListResponse,
4492
+ LITERAL_LAST_SHAPES,
4493
+ READ_VERBS,
3164
4494
  distinctRecord,
3165
4495
  distinctShare,
3166
4496
  heuristic01,
4497
+ keyParamOf,
4498
+ matchEntityPath,
4499
+ pathNoun,
3167
4500
  namingRef,
3168
4501
  namingSchemas,
4502
+ pathRecordRef,
3169
4503
  pathResource,
3170
4504
  sharedRoutes,
3171
4505
  entityParamNames,
3172
4506
  isNameParam,
3173
4507
  isVerb,
3174
4508
  verbParts,
4509
+ verbOfItem,
4510
+ shortLiteral,
4511
+ normalizeParams,
4512
+ cleanCmp,
4513
+ commandSource,
4514
+ relationshipOf,
4515
+ singletonOf,
4516
+ subWriteOfItem,
4517
+ variantOfCollection,
4518
+ keyNounOf,
4519
+ asyncResultOf,
4520
+ nounless,
4521
+ genericCmp,
4522
+ actionWord,
4523
+ keyRunBefore,
4524
+ VERSION_TAG_RE,
4525
+ isVerbWord,
4526
+ keyedBy,
4527
+ postReadVerb,
4528
+ componentReadOwner,
3175
4529
  }