@gate-forge/pack-http 0.14.0 → 0.15.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.
@@ -40,7 +40,18 @@
40
40
  * in the scanned set is a single `return <client call>(...)` arrow or
41
41
  * function resolves its internal call with the callsite's first
42
42
  * argument substituted for the wrapper's first parameter (one level,
43
- * one parameter — anything deeper is typed unresolved).
43
+ * one parameter — anything deeper is typed unresolved). A wrapper may
44
+ * also name the endpoint parameter (`parameter`) and, when
45
+ * `methodFromBody` is set, keep each concrete verb in its body. The
46
+ * declaration may live in another scanned file, including a default
47
+ * export, and a JSX attribute of that parameter is a callsite.
48
+ * - **Local shapes** (still fail closed): a single-assignment `const`
49
+ * (a closer `let` stays unresolved), both branches of a conditional,
50
+ * a `const` object-literal lookup (every literal value), a destructured
51
+ * relative dynamic-import alias of a configured symbol or builder, and
52
+ * a same-file function whose returns are a finite resolvable set.
53
+ * A `const` named `fetch` whose initializer is not the Fetch API is
54
+ * not a fetch call.
44
55
  */
45
56
  import ts from 'typescript';
46
57
  import { posix } from 'node:path';
@@ -640,6 +651,10 @@ const UNPROVEN_OPTIONS = { kind: 'unproven' };
640
651
  */
641
652
  const MAX_OPTIONS_HOPS = 4;
642
653
  const UNRESOLVED_VALUE = { kind: 'unresolved', text: '' };
654
+ /** Cap on alternatives one expression may prove. Above this, fail closed — never a partial set. */
655
+ const MAX_CALL_TARGETS = 32;
656
+ /** Calls of a declared wrapper into another declared wrapper, before fail closed. */
657
+ const MAX_WRAPPER_DEPTH = 4;
643
658
  function languageKindFor(file) {
644
659
  if (file.endsWith('.tsx'))
645
660
  return ts.ScriptKind.TSX;
@@ -792,11 +807,16 @@ export function scanClientCalls(file, sourceText, config, scannedFiles) {
792
807
  const model = table.modelOf(file);
793
808
  const calls = [];
794
809
  const unresolved = [];
795
- const wrapperSpans = [...(model?.wrappers.values() ?? [])].map((w) => [w.start, w.end]);
810
+ const wrapperSpans = modeledWrapperSpans(model, config, file);
796
811
  const insideWrapper = (node) => wrapperSpans.some(([start, end]) => node.getStart(source) >= start && node.getEnd() <= end);
797
812
  const visit = (node) => {
798
- if (ts.isCallExpression(node) && !insideWrapper(node)) {
799
- extractCall(node, file, config, table, model, calls, unresolved);
813
+ if (!insideWrapper(node)) {
814
+ if (ts.isCallExpression(node)) {
815
+ extractCall(node, file, config, table, model, calls, unresolved);
816
+ }
817
+ else if (ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) {
818
+ extractJsxWrapper(node, file, config, table, calls, unresolved);
819
+ }
800
820
  }
801
821
  ts.forEachChild(node, visit);
802
822
  };
@@ -830,12 +850,14 @@ function extractCall(call, file, config, table, model, calls, unresolved) {
830
850
  const expression = call.expression;
831
851
  // fetch(url[, {method}])
832
852
  if (ts.isIdentifier(expression) && expression.text === 'fetch') {
833
- extractClientCall(call, 'fetch', 'GET', file, config, table, calls, unresolved, location, undefined, reads);
853
+ if (!table.shadowsGlobalFetch(expression)) {
854
+ extractClientCall(call, 'fetch', 'GET', file, config, table, calls, unresolved, location, undefined, reads);
855
+ }
834
856
  return;
835
857
  }
836
858
  // axios.get(url), apiClient.post(url), window.fetch(url)
837
859
  if (ts.isPropertyAccessExpression(expression) && ts.isIdentifier(expression.expression)) {
838
- const objectName = expression.expression.text;
860
+ const objectName = table.configuredClientName(expression.expression, file);
839
861
  const verb = expression.name.text.toLowerCase();
840
862
  const isFetchObject = objectName === 'window' && expression.name.text === 'fetch';
841
863
  if (isFetchObject) {
@@ -884,12 +906,17 @@ function extractCall(call, file, config, table, model, calls, unresolved) {
884
906
  if (wrapperConfig !== undefined) {
885
907
  const wrapperModel = table.modelOf(file)?.wrappers.get(wrapperConfig.name);
886
908
  if (wrapperModel === undefined) {
887
- unresolved.push({
888
- code: FRONTEND_CALL_TARGET_UNRESOLVED,
889
- detail: (`wrapper '${wrapperConfig.name}' has no simple single-return client call in the ` +
890
- 'scanned set; its call targets cannot be resolved statically'),
891
- location,
892
- });
909
+ if (resolvesToDeclaredWrapper(table, wrapperConfig.name, file, config)) {
910
+ const bindings = new Map();
911
+ const declared = table.findFunction(wrapperConfig.name, file);
912
+ const paramName = wrapperConfig.parameter ?? (declared === undefined ? undefined : firstIdentifierParam(declared.fn));
913
+ if (declared !== undefined && paramName !== undefined) {
914
+ const argument = argumentForParameter(declared.fn, paramName, call);
915
+ if (argument !== undefined)
916
+ bindings.set(paramName, [argument, file]);
917
+ }
918
+ resolveExtendedWrapper(wrapperConfig, file, config, table, bindings, calls, unresolved, location, reads);
919
+ }
893
920
  return;
894
921
  }
895
922
  const bound = new BoundTable(table, wrapperModel.parameter, call.arguments[0], file);
@@ -979,6 +1006,12 @@ class BoundTable {
979
1006
  }
980
1007
  return this.inner.evaluate(node, file);
981
1008
  }
1009
+ callTargets(node, file, bindings) {
1010
+ const next = new Map(bindings);
1011
+ if (this.argument !== undefined)
1012
+ next.set(this.parameter, [this.argument, this.argumentFile]);
1013
+ return this.inner.callTargets(node, file, next);
1014
+ }
982
1015
  optionsMethod(node, file, bindings, depth = 0) {
983
1016
  if (ts.isIdentifier(node) &&
984
1017
  node.text === this.parameter &&
@@ -1137,8 +1170,8 @@ function joinInstanceBaseURL(baseURL, callPath) {
1137
1170
  };
1138
1171
  }
1139
1172
  function resolveAndRecord(urlNode, framework, method, file, config, table, calls, unresolved, location, reads = [], baseURL) {
1140
- const resolved = table.evaluate(urlNode, file);
1141
- if (resolved.kind === 'unresolved') {
1173
+ const targets = table.callTargets(urlNode, file);
1174
+ if (targets === undefined || targets.length === 0) {
1142
1175
  unresolved.push({
1143
1176
  code: FRONTEND_CALL_TARGET_UNRESOLVED,
1144
1177
  detail: `call target cannot be resolved statically (${framework})`,
@@ -1146,25 +1179,42 @@ function resolveAndRecord(urlNode, framework, method, file, config, table, calls
1146
1179
  });
1147
1180
  return;
1148
1181
  }
1149
- const joined = joinInstanceBaseURL(baseURL, resolved.text);
1150
- const canonical = normalizeHttpPath(joined.path, { sameOriginHosts: config.sameOriginHosts });
1151
- if (!canonical.ok) {
1152
- unresolved.push({
1153
- code: FRONTEND_CALL_TARGET_UNRESOLVED,
1154
- detail: `call target '${joined.path}': ${canonical.detail}`,
1182
+ recordRawTargets(targets, method, framework, config, calls, unresolved, location, reads, baseURL);
1183
+ }
1184
+ function recordRawTargets(raws, method, framework, config, calls, unresolved, location, reads, baseURL) {
1185
+ const resolved = [];
1186
+ for (const raw of raws) {
1187
+ const joined = joinInstanceBaseURL(baseURL, raw);
1188
+ const canonical = normalizeHttpPath(joined.path, { sameOriginHosts: config.sameOriginHosts });
1189
+ if (!canonical.ok) {
1190
+ unresolved.push({
1191
+ code: FRONTEND_CALL_TARGET_UNRESOLVED,
1192
+ detail: `call target '${joined.path}': ${canonical.detail}`,
1193
+ location,
1194
+ });
1195
+ return;
1196
+ }
1197
+ resolved.push({ raw, canonical: canonical.canonical, joined: joined.joined });
1198
+ }
1199
+ const unique = new Map();
1200
+ for (const item of resolved) {
1201
+ if (!unique.has(item.canonical))
1202
+ unique.set(item.canonical, { raw: item.raw, joined: item.joined });
1203
+ }
1204
+ const many = unique.size > 1;
1205
+ const ordered = [...unique.entries()].sort((left, right) => (left[0] < right[0] ? -1 : left[0] > right[0] ? 1 : 0));
1206
+ for (const [canonical, item] of ordered) {
1207
+ calls.push({
1208
+ method,
1209
+ rawPath: item.raw,
1210
+ canonicalPath: canonical,
1211
+ ...(item.joined !== undefined ? { joinedBaseURL: item.joined } : {}),
1212
+ framework,
1155
1213
  location,
1214
+ ...(many ? { idDisambiguator: canonical } : {}),
1215
+ ...(reads.length > 0 ? { responseReads: reads } : {}),
1156
1216
  });
1157
- return;
1158
1217
  }
1159
- calls.push({
1160
- method,
1161
- rawPath: resolved.text,
1162
- canonicalPath: canonical.canonical,
1163
- ...(joined.joined !== undefined ? { joinedBaseURL: joined.joined } : {}),
1164
- framework,
1165
- location,
1166
- ...(reads.length > 0 ? { responseReads: reads } : {}),
1167
- });
1168
1218
  }
1169
1219
  /**
1170
1220
  * The ONE expression a function-like returns, or undefined when it
@@ -1760,6 +1810,710 @@ class ValueTable {
1760
1810
  }
1761
1811
  return null;
1762
1812
  }
1813
+ /**
1814
+ * Every literal path `node` can take, or undefined when any branch
1815
+ * cannot be proven. A resolved target is exactly a value the code can
1816
+ * call — never a guess, never a partial set.
1817
+ */
1818
+ callTargets(node, file, bindings, seen = new Set()) {
1819
+ const peeled = unwrapOwnExpression(node);
1820
+ if (peeled !== node)
1821
+ return this.callTargets(peeled, file, bindings, seen);
1822
+ if (ts.isSatisfiesExpression(node))
1823
+ return this.callTargets(node.expression, file, bindings, seen);
1824
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node))
1825
+ return [node.text];
1826
+ if (ts.isTemplateExpression(node))
1827
+ return this.expandTemplate(node, file, bindings, seen);
1828
+ if (ts.isConditionalExpression(node))
1829
+ return this.conditionalTargets(node, file, bindings, seen);
1830
+ if (ts.isIdentifier(node))
1831
+ return this.identifierTargets(node, file, bindings, seen);
1832
+ if (ts.isElementAccessExpression(node))
1833
+ return this.lookupTargets(node, file, bindings, seen);
1834
+ if (ts.isCallExpression(node) && ts.isIdentifier(node.expression)) {
1835
+ const alias = this.dynamicImportAlias(node.expression, file);
1836
+ const builderName = alias?.kind === 'builder' ? alias.name : node.expression.text;
1837
+ const builder = alias?.kind === 'client' ? undefined : activeUrlBuilderIn(this.config, builderName, file);
1838
+ if (builder !== undefined) {
1839
+ const argument = node.arguments[0];
1840
+ if (argument === undefined)
1841
+ return undefined;
1842
+ const inner = this.callTargets(argument, file, bindings, seen);
1843
+ if (inner === undefined)
1844
+ return undefined;
1845
+ const base = builder.base ?? '';
1846
+ return inner.map((text) => (text.startsWith('/') || base === '' ? `${base}${text}` : `${base}/${text}`));
1847
+ }
1848
+ if (alias === undefined)
1849
+ return this.finiteFunctionTargets(node, file, bindings, seen);
1850
+ }
1851
+ return undefined;
1852
+ }
1853
+ /** A const binding named `fetch` whose initializer is not the Fetch API. */
1854
+ shadowsGlobalFetch(use) {
1855
+ const local = this.localConstBinding(use);
1856
+ if (local.state !== 'found')
1857
+ return false;
1858
+ const init = unwrapOwnExpression(local.initializer);
1859
+ if (ts.isArrowFunction(init) || ts.isFunctionExpression(init))
1860
+ return true;
1861
+ if (!ts.isCallExpression(init))
1862
+ return false;
1863
+ const callee = init.expression;
1864
+ if (ts.isIdentifier(callee) && callee.text === 'fetch')
1865
+ return false;
1866
+ if (ts.isPropertyAccessExpression(callee) && callee.name.text === 'fetch')
1867
+ return false;
1868
+ return true;
1869
+ }
1870
+ /** Configured client-symbol name for a callsite object, following a dynamic-import alias. */
1871
+ configuredClientName(use, file) {
1872
+ const alias = this.dynamicImportAlias(use, file);
1873
+ return alias?.kind === 'client' ? alias.name : use.text;
1874
+ }
1875
+ /** A function named `name` visible from `file`: same file, or a relative import including default. */
1876
+ findFunction(name, file) {
1877
+ const own = this.modelOf(file)?.functions.get(name);
1878
+ if (own !== undefined)
1879
+ return { fn: own, file };
1880
+ const imported = this.importedExport(file, name);
1881
+ if (imported === null)
1882
+ return undefined;
1883
+ const model = this.modelOf(imported.file);
1884
+ if (model === undefined)
1885
+ return undefined;
1886
+ const fn = imported.exported === 'default' ? defaultExportedFunction(model) : model.functions.get(imported.exported);
1887
+ return fn === undefined ? undefined : { fn, file: imported.file };
1888
+ }
1889
+ identifierTargets(node, file, bindings, seen) {
1890
+ const bound = bindings?.get(node.text);
1891
+ if (bound !== undefined) {
1892
+ const rest = new Map(bindings);
1893
+ rest.delete(node.text);
1894
+ return this.callTargets(bound[0], bound[1], rest, seen);
1895
+ }
1896
+ const local = this.localConstBinding(node);
1897
+ if (local.state === 'shadowed')
1898
+ return undefined;
1899
+ if (local.state === 'found') {
1900
+ const key = `${file}::${node.text}`;
1901
+ if (seen.has(key))
1902
+ return undefined;
1903
+ seen.add(key);
1904
+ const value = this.callTargets(local.initializer, file, bindings, seen);
1905
+ seen.delete(key);
1906
+ return value;
1907
+ }
1908
+ const imported = this.importedFrom(file, node.text);
1909
+ const origin = imported ?? file;
1910
+ const initializer = this.modelOf(origin)?.constants.get(node.text);
1911
+ if (initializer === undefined)
1912
+ return undefined;
1913
+ const key = `${origin}::${node.text}`;
1914
+ if (seen.has(key))
1915
+ return undefined;
1916
+ seen.add(key);
1917
+ const value = this.callTargets(initializer, origin, bindings, seen);
1918
+ seen.delete(key);
1919
+ return value;
1920
+ }
1921
+ conditionalTargets(node, file, bindings, seen) {
1922
+ const proven = this.proveStartsWith(node.condition, file, bindings, seen);
1923
+ if (proven === true)
1924
+ return this.callTargets(node.whenTrue, file, bindings, seen);
1925
+ if (proven === false)
1926
+ return this.callTargets(node.whenFalse, file, bindings, seen);
1927
+ const whenTrue = this.callTargets(node.whenTrue, file, bindings, seen);
1928
+ const whenFalse = this.callTargets(node.whenFalse, file, bindings, seen);
1929
+ if (whenTrue === undefined || whenFalse === undefined)
1930
+ return undefined;
1931
+ const combined = [...whenTrue, ...whenFalse];
1932
+ return combined.length > MAX_CALL_TARGETS ? undefined : combined;
1933
+ }
1934
+ /** `expr.startsWith('literal')` when `expr` is exactly one literal. Otherwise unproven. */
1935
+ proveStartsWith(node, file, bindings, seen) {
1936
+ const expr = unwrapOwnExpression(node);
1937
+ if (ts.isPrefixUnaryExpression(expr) && expr.operator === ts.SyntaxKind.ExclamationToken) {
1938
+ const inner = this.proveStartsWith(expr.operand, file, bindings, seen);
1939
+ return inner === undefined ? undefined : !inner;
1940
+ }
1941
+ if (!ts.isCallExpression(expr) ||
1942
+ !ts.isPropertyAccessExpression(expr.expression) ||
1943
+ expr.expression.name.text !== 'startsWith' ||
1944
+ expr.arguments.length !== 1) {
1945
+ return undefined;
1946
+ }
1947
+ const probe = expr.arguments[0];
1948
+ if (probe === undefined || !ts.isStringLiteral(probe))
1949
+ return undefined;
1950
+ const receiver = this.callTargets(expr.expression.expression, file, bindings, seen);
1951
+ if (receiver === undefined || receiver.length !== 1)
1952
+ return undefined;
1953
+ return (receiver[0] ?? '').startsWith(probe.text);
1954
+ }
1955
+ expandTemplate(node, file, bindings, seen) {
1956
+ let pieces = [{
1957
+ text: node.head.text,
1958
+ rooted: node.head.text.startsWith('/') || node.head.text.startsWith('${'),
1959
+ }];
1960
+ for (const span of node.templateSpans) {
1961
+ const next = [];
1962
+ const substituted = this.pathHoleTargets(span.expression, file, bindings, seen);
1963
+ if (substituted !== undefined) {
1964
+ for (const piece of pieces) {
1965
+ for (const hole of substituted) {
1966
+ next.push({
1967
+ text: piece.text + hole + span.literal.text,
1968
+ rooted: piece.rooted || hole.startsWith('/'),
1969
+ });
1970
+ }
1971
+ }
1972
+ }
1973
+ else {
1974
+ const bound = ts.isIdentifier(span.expression) ? bindings?.get(span.expression.text) : undefined;
1975
+ const holeExpr = bound?.[0] ?? span.expression;
1976
+ const holeFile = bound?.[1] ?? file;
1977
+ const hole = bound === undefined ? this.evaluate(span.expression, file) : this.evaluate(holeExpr, holeFile);
1978
+ if (hole.kind === 'unresolved') {
1979
+ if (pieces.some((piece) => !piece.rooted))
1980
+ return undefined;
1981
+ const suffix = this.trailingQuerySuffix(node, span, holeExpr, holeFile);
1982
+ const slot = suffix ? '?' : '${}';
1983
+ for (const piece of pieces)
1984
+ next.push({ text: piece.text + slot + span.literal.text, rooted: true });
1985
+ }
1986
+ else {
1987
+ for (const piece of pieces) {
1988
+ next.push({
1989
+ text: piece.text + hole.text + span.literal.text,
1990
+ rooted: piece.rooted || hole.text.startsWith('/'),
1991
+ });
1992
+ }
1993
+ }
1994
+ }
1995
+ if (next.length === 0 || next.length > MAX_CALL_TARGETS)
1996
+ return undefined;
1997
+ pieces = next;
1998
+ }
1999
+ return pieces.map((piece) => piece.text);
2000
+ }
2001
+ /** Path-absolute hole alternatives only. Query-shaped holes stay on the suffix model. */
2002
+ pathHoleTargets(expr, file, bindings, seen) {
2003
+ const targets = this.callTargets(expr, file, bindings, seen);
2004
+ if (targets === undefined || targets.length === 0)
2005
+ return undefined;
2006
+ if (!targets.every((text) => text === '' || text.startsWith('/')))
2007
+ return undefined;
2008
+ return targets;
2009
+ }
2010
+ lookupTargets(node, file, bindings, seen) {
2011
+ const object = this.constObjectLiteral(node.expression, file, bindings, seen);
2012
+ if (object === undefined)
2013
+ return undefined;
2014
+ for (const property of object.properties) {
2015
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
2016
+ return undefined;
2017
+ if (ts.isComputedPropertyName(property.name))
2018
+ return undefined;
2019
+ }
2020
+ const index = node.argumentExpression;
2021
+ const selected = index !== undefined && ts.isStringLiteral(index)
2022
+ ? object.properties.filter((property) => propertyNameText(property.name) === index.text)
2023
+ : object.properties;
2024
+ if (selected.length === 0)
2025
+ return undefined;
2026
+ const targets = [];
2027
+ for (const property of selected) {
2028
+ if (!ts.isPropertyAssignment(property) && !ts.isShorthandPropertyAssignment(property))
2029
+ return undefined;
2030
+ const initializer = ts.isPropertyAssignment(property) ? property.initializer : property.name;
2031
+ const part = this.callTargets(initializer, file, bindings, seen);
2032
+ if (part === undefined)
2033
+ return undefined;
2034
+ targets.push(...part);
2035
+ if (targets.length > MAX_CALL_TARGETS)
2036
+ return undefined;
2037
+ }
2038
+ return targets;
2039
+ }
2040
+ constObjectLiteral(expr, file, bindings, seen) {
2041
+ const node = unwrapOwnExpression(expr);
2042
+ if (ts.isObjectLiteralExpression(node))
2043
+ return node;
2044
+ if (!ts.isIdentifier(node))
2045
+ return undefined;
2046
+ const local = this.localConstBinding(node);
2047
+ if (local.state !== 'found')
2048
+ return undefined;
2049
+ const key = `${file}::${node.text}`;
2050
+ if (seen.has(key))
2051
+ return undefined;
2052
+ const initializer = unwrapOwnExpression(local.initializer);
2053
+ return ts.isObjectLiteralExpression(initializer) ? initializer : undefined;
2054
+ }
2055
+ finiteFunctionTargets(call, file, bindings, seen) {
2056
+ if (!ts.isIdentifier(call.expression))
2057
+ return undefined;
2058
+ const name = call.expression.text;
2059
+ const local = this.localConstBinding(call.expression);
2060
+ let fn;
2061
+ if (local.state === 'shadowed')
2062
+ return undefined;
2063
+ if (local.state === 'found') {
2064
+ const init = unwrapOwnExpression(local.initializer);
2065
+ if (!ts.isArrowFunction(init) && !ts.isFunctionExpression(init))
2066
+ return undefined;
2067
+ fn = init;
2068
+ }
2069
+ else {
2070
+ fn = this.modelOf(file)?.functions.get(name);
2071
+ }
2072
+ if (fn === undefined)
2073
+ return undefined;
2074
+ const key = `${file}::fn::${name}`;
2075
+ if (seen.has(key))
2076
+ return undefined;
2077
+ seen.add(key);
2078
+ const returns = collectUrlReturns(fn);
2079
+ if (returns === undefined) {
2080
+ seen.delete(key);
2081
+ return undefined;
2082
+ }
2083
+ const targets = [];
2084
+ for (const returned of returns) {
2085
+ const part = this.callTargets(returned, file, bindings, seen);
2086
+ if (part === undefined) {
2087
+ seen.delete(key);
2088
+ return undefined;
2089
+ }
2090
+ targets.push(...part);
2091
+ if (targets.length > MAX_CALL_TARGETS) {
2092
+ seen.delete(key);
2093
+ return undefined;
2094
+ }
2095
+ }
2096
+ seen.delete(key);
2097
+ return targets.length === 0 ? undefined : targets;
2098
+ }
2099
+ dynamicImportAlias(use, file) {
2100
+ const binding = this.nearestDestructure(use);
2101
+ if (binding === undefined)
2102
+ return undefined;
2103
+ if (binding.exported !== 'default') {
2104
+ if (activeUrlBuilderIn(this.config, binding.exported, file) !== undefined) {
2105
+ return { kind: 'builder', name: binding.exported };
2106
+ }
2107
+ if (clientSymbolActiveIn(this.config, binding.exported, file)) {
2108
+ return { kind: 'client', name: binding.exported };
2109
+ }
2110
+ return undefined;
2111
+ }
2112
+ const resolved = this.resolveSpecifier(file, binding.specifier);
2113
+ if (resolved === null)
2114
+ return undefined;
2115
+ const exported = defaultExportIdentifier(this.modelOf(resolved)?.source);
2116
+ if (exported === undefined || !clientSymbolActiveIn(this.config, exported, file))
2117
+ return undefined;
2118
+ return { kind: 'client', name: exported };
2119
+ }
2120
+ nearestDestructure(use) {
2121
+ let scope = use.parent;
2122
+ while (scope !== undefined) {
2123
+ if (ts.isFunctionLike(scope) || ts.isSourceFile(scope)) {
2124
+ const found = this.destructureInScope(use, scope);
2125
+ if (found === 'other')
2126
+ return undefined;
2127
+ if (found !== undefined)
2128
+ return found;
2129
+ }
2130
+ scope = scope.parent;
2131
+ }
2132
+ return undefined;
2133
+ }
2134
+ destructureInScope(use, scope) {
2135
+ let best;
2136
+ const visit = (node) => {
2137
+ if (node !== scope && ts.isFunctionLike(node))
2138
+ return;
2139
+ if (ts.isVariableDeclaration(node) && node.name.getEnd() <= use.getStart()) {
2140
+ const isConst = (ts.getCombinedNodeFlags(node) & ts.NodeFlags.Const) !== 0;
2141
+ if (ts.isIdentifier(node.name) && node.name.text === use.text) {
2142
+ if (best === undefined || node.name.getStart() > best.pos) {
2143
+ best = { pos: node.name.getStart(), result: 'other' };
2144
+ }
2145
+ }
2146
+ if (ts.isObjectBindingPattern(node.name)) {
2147
+ for (const element of node.name.elements) {
2148
+ if (!ts.isIdentifier(element.name) || element.name.text !== use.text || element.dotDotDotToken !== undefined) {
2149
+ continue;
2150
+ }
2151
+ if (best !== undefined && element.name.getStart() <= best.pos)
2152
+ continue;
2153
+ const specifier = isConst ? awaitImportSpecifier(node.initializer) : undefined;
2154
+ const exported = element.propertyName !== undefined && ts.isIdentifier(element.propertyName)
2155
+ ? element.propertyName.text
2156
+ : element.name.text;
2157
+ best = {
2158
+ pos: element.name.getStart(),
2159
+ result: specifier === undefined ? 'other' : { exported, specifier },
2160
+ };
2161
+ }
2162
+ }
2163
+ }
2164
+ ts.forEachChild(node, visit);
2165
+ };
2166
+ visit(scope);
2167
+ return best?.result;
2168
+ }
2169
+ importedExport(file, localName) {
2170
+ const model = this.modelOf(file);
2171
+ if (model === undefined)
2172
+ return null;
2173
+ let found = null;
2174
+ const visit = (node) => {
2175
+ if (found !== null)
2176
+ return;
2177
+ if (!ts.isImportDeclaration(node) || !ts.isStringLiteral(node.moduleSpecifier)) {
2178
+ ts.forEachChild(node, visit);
2179
+ return;
2180
+ }
2181
+ const specifier = node.moduleSpecifier.text;
2182
+ if (!specifier.startsWith('./') && !specifier.startsWith('../'))
2183
+ return;
2184
+ const resolved = this.resolveSpecifier(file, specifier);
2185
+ if (resolved === null)
2186
+ return;
2187
+ const clause = node.importClause;
2188
+ if (clause?.name?.text === localName) {
2189
+ found = { file: resolved, exported: 'default' };
2190
+ return;
2191
+ }
2192
+ if (clause?.namedBindings !== undefined && ts.isNamedImports(clause.namedBindings)) {
2193
+ for (const element of clause.namedBindings.elements) {
2194
+ if (element.name.text === localName) {
2195
+ found = { file: resolved, exported: element.propertyName?.text ?? element.name.text };
2196
+ return;
2197
+ }
2198
+ }
2199
+ }
2200
+ };
2201
+ visit(model.source);
2202
+ return found;
2203
+ }
2204
+ }
2205
+ function modeledWrapperSpans(model, config, file) {
2206
+ if (model === undefined)
2207
+ return [];
2208
+ const spans = [...model.wrappers.values()].map((wrapper) => [wrapper.start, wrapper.end]);
2209
+ for (const entry of config.wrapperFunctions ?? []) {
2210
+ if (!entryInScope(file, entry))
2211
+ continue;
2212
+ const fn = model.functions.get(entry.name);
2213
+ if (fn === undefined)
2214
+ continue;
2215
+ if (containsClientCall(fn, config, file) || containsConfiguredWrapperCall(fn, config, file)) {
2216
+ spans.push([fn.getStart(), fn.getEnd()]);
2217
+ }
2218
+ }
2219
+ return spans;
2220
+ }
2221
+ function containsConfiguredWrapperCall(node, config, file) {
2222
+ let found = false;
2223
+ const visit = (current) => {
2224
+ if (found || !ts.isCallExpression(current)) {
2225
+ ts.forEachChild(current, visit);
2226
+ return;
2227
+ }
2228
+ if (ts.isIdentifier(current.expression) && activeWrapperIn(config, current.expression.text, file) !== undefined) {
2229
+ found = true;
2230
+ return;
2231
+ }
2232
+ ts.forEachChild(current, visit);
2233
+ };
2234
+ visit(node);
2235
+ return found;
2236
+ }
2237
+ function collectUrlReturns(fn) {
2238
+ const body = fn.body;
2239
+ if (body === undefined)
2240
+ return undefined;
2241
+ if (!ts.isBlock(body))
2242
+ return [body];
2243
+ const returns = [];
2244
+ let poison = false;
2245
+ const visit = (node) => {
2246
+ if (poison)
2247
+ return;
2248
+ if (node !== body && ts.isFunctionLike(node))
2249
+ return;
2250
+ if (ts.isReturnStatement(node)) {
2251
+ if (node.expression === undefined) {
2252
+ poison = true;
2253
+ return;
2254
+ }
2255
+ const expr = unwrapOwnExpression(node.expression);
2256
+ if (expr.kind === ts.SyntaxKind.NullKeyword)
2257
+ return;
2258
+ if (ts.isIdentifier(expr) && expr.text === 'undefined')
2259
+ return;
2260
+ returns.push(node.expression);
2261
+ return;
2262
+ }
2263
+ ts.forEachChild(node, visit);
2264
+ };
2265
+ visit(body);
2266
+ if (poison || returns.length === 0)
2267
+ return undefined;
2268
+ return returns;
2269
+ }
2270
+ function awaitImportSpecifier(expr) {
2271
+ if (expr === undefined)
2272
+ return undefined;
2273
+ const inner = unwrapOwnExpression(ts.isAwaitExpression(expr) ? expr.expression : expr);
2274
+ if (!ts.isCallExpression(inner) || inner.expression.kind !== ts.SyntaxKind.ImportKeyword)
2275
+ return undefined;
2276
+ const arg = inner.arguments[0];
2277
+ if (arg === undefined || !ts.isStringLiteral(arg))
2278
+ return undefined;
2279
+ if (!arg.text.startsWith('./') && !arg.text.startsWith('../'))
2280
+ return undefined;
2281
+ return arg.text;
2282
+ }
2283
+ function defaultExportedFunction(model) {
2284
+ for (const statement of model.source.statements) {
2285
+ if (ts.isFunctionDeclaration(statement) &&
2286
+ statement.name !== undefined &&
2287
+ statement.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.DefaultKeyword) === true) {
2288
+ return statement;
2289
+ }
2290
+ if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
2291
+ return model.functions.get(statement.expression.text);
2292
+ }
2293
+ }
2294
+ return undefined;
2295
+ }
2296
+ function defaultExportIdentifier(source) {
2297
+ if (source === undefined)
2298
+ return undefined;
2299
+ for (const statement of source.statements) {
2300
+ if (ts.isFunctionDeclaration(statement) &&
2301
+ statement.name !== undefined &&
2302
+ statement.modifiers?.some((mod) => mod.kind === ts.SyntaxKind.DefaultKeyword) === true) {
2303
+ return statement.name.text;
2304
+ }
2305
+ if (ts.isExportAssignment(statement) && ts.isIdentifier(statement.expression)) {
2306
+ return statement.expression.text;
2307
+ }
2308
+ }
2309
+ return undefined;
2310
+ }
2311
+ function firstIdentifierParam(fn) {
2312
+ const first = fn.parameters[0];
2313
+ return first !== undefined && ts.isIdentifier(first.name) ? first.name.text : undefined;
2314
+ }
2315
+ function argumentForParameter(fn, paramName, call) {
2316
+ for (let index = 0; index < fn.parameters.length; index += 1) {
2317
+ const parameter = fn.parameters[index];
2318
+ if (parameter === undefined)
2319
+ continue;
2320
+ if (ts.isIdentifier(parameter.name) && parameter.name.text === paramName)
2321
+ return call.arguments[index];
2322
+ if (!ts.isObjectBindingPattern(parameter.name))
2323
+ continue;
2324
+ for (const element of parameter.name.elements) {
2325
+ if (!ts.isIdentifier(element.name) || element.name.text !== paramName)
2326
+ continue;
2327
+ const prop = element.propertyName !== undefined && ts.isIdentifier(element.propertyName)
2328
+ ? element.propertyName.text
2329
+ : element.name.text;
2330
+ const argument = call.arguments[index];
2331
+ return argument === undefined ? undefined : objectProperty(argument, prop);
2332
+ }
2333
+ }
2334
+ return undefined;
2335
+ }
2336
+ function objectProperty(expr, name) {
2337
+ const unwrapped = unwrapOwnExpression(expr);
2338
+ if (!ts.isObjectLiteralExpression(unwrapped))
2339
+ return undefined;
2340
+ for (const property of unwrapped.properties) {
2341
+ if (ts.isShorthandPropertyAssignment(property) && property.name.text === name)
2342
+ return property.name;
2343
+ if (ts.isPropertyAssignment(property) &&
2344
+ ts.isIdentifier(property.name) &&
2345
+ property.name.text === name) {
2346
+ return property.initializer;
2347
+ }
2348
+ }
2349
+ return undefined;
2350
+ }
2351
+ function jsxAttributeExpression(node, name) {
2352
+ for (const attr of node.attributes.properties) {
2353
+ if (!ts.isJsxAttribute(attr) || !ts.isIdentifier(attr.name) || attr.name.text !== name)
2354
+ continue;
2355
+ const init = attr.initializer;
2356
+ if (init === undefined)
2357
+ return undefined;
2358
+ if (ts.isStringLiteral(init))
2359
+ return init;
2360
+ if (ts.isJsxExpression(init) && init.expression !== undefined && ts.isExpression(init.expression)) {
2361
+ return init.expression;
2362
+ }
2363
+ }
2364
+ return undefined;
2365
+ }
2366
+ function resolvesToDeclaredWrapper(table, name, file, config) {
2367
+ const declared = table.findFunction(name, file);
2368
+ // No local binding: the configured name still stands, and an unmodeled
2369
+ // declaration stays a finding. A binding that is a different function
2370
+ // (same local name, other module, no client call) is not this wrapper.
2371
+ if (declared === undefined)
2372
+ return true;
2373
+ return containsClientCall(declared.fn, config, declared.file)
2374
+ || containsConfiguredWrapperCall(declared.fn, config, declared.file);
2375
+ }
2376
+ function extractJsxWrapper(node, file, config, table, calls, unresolved) {
2377
+ if (!ts.isIdentifier(node.tagName))
2378
+ return;
2379
+ const wrapperConfig = activeWrapperIn(config, node.tagName.text, file);
2380
+ if (wrapperConfig === undefined || !resolvesToDeclaredWrapper(table, wrapperConfig.name, file, config))
2381
+ return;
2382
+ const source = table.modelOf(file)?.source;
2383
+ if (source === undefined)
2384
+ return;
2385
+ const bindings = new Map();
2386
+ if (wrapperConfig.parameter !== undefined) {
2387
+ const attr = jsxAttributeExpression(node, wrapperConfig.parameter);
2388
+ if (attr !== undefined)
2389
+ bindings.set(wrapperConfig.parameter, [attr, file]);
2390
+ }
2391
+ resolveExtendedWrapper(wrapperConfig, file, config, table, bindings, calls, unresolved, locationOf(file, source, node), []);
2392
+ }
2393
+ function resolveExtendedWrapper(wrapperConfig, file, config, table, bindings, calls, unresolved, location, reads) {
2394
+ const declared = table.findFunction(wrapperConfig.name, file);
2395
+ if (declared === undefined) {
2396
+ unresolved.push({
2397
+ code: FRONTEND_CALL_TARGET_UNRESOLVED,
2398
+ detail: (`wrapper '${wrapperConfig.name}' has no simple single-return client call in the ` +
2399
+ 'scanned set; its call targets cannot be resolved statically'),
2400
+ location,
2401
+ });
2402
+ return;
2403
+ }
2404
+ const body = wrapperBodyTargets(declared.fn, declared.file, wrapperConfig, config, table, bindings, 0, new Set());
2405
+ if (body === 'unmodeled') {
2406
+ unresolved.push({
2407
+ code: FRONTEND_CALL_TARGET_UNRESOLVED,
2408
+ detail: (`wrapper '${wrapperConfig.name}' has no simple single-return client call in the ` +
2409
+ 'scanned set; its call targets cannot be resolved statically'),
2410
+ location,
2411
+ });
2412
+ return;
2413
+ }
2414
+ if (body === 'unresolved') {
2415
+ unresolved.push({
2416
+ code: FRONTEND_CALL_TARGET_UNRESOLVED,
2417
+ detail: `call target cannot be resolved statically (${wrapperConfig.name})`,
2418
+ location,
2419
+ });
2420
+ return;
2421
+ }
2422
+ const byMethod = new Map();
2423
+ for (const target of body) {
2424
+ const list = byMethod.get(target.method) ?? [];
2425
+ list.push(target.raw);
2426
+ byMethod.set(target.method, list);
2427
+ }
2428
+ for (const [method, raws] of byMethod) {
2429
+ recordRawTargets(raws, method, wrapperConfig.name, config, calls, unresolved, location, reads);
2430
+ }
2431
+ }
2432
+ function wrapperBodyTargets(fn, fnFile, entry, config, table, bindings, depth, stack) {
2433
+ const stackKey = `${fnFile}::${entry.name}`;
2434
+ if (depth > MAX_WRAPPER_DEPTH || stack.has(stackKey))
2435
+ return 'unmodeled';
2436
+ stack.add(stackKey);
2437
+ const found = [];
2438
+ let saw = false;
2439
+ let failed = false;
2440
+ const visit = (node) => {
2441
+ if (failed || !ts.isCallExpression(node)) {
2442
+ if (!failed)
2443
+ ts.forEachChild(node, visit);
2444
+ return;
2445
+ }
2446
+ const client = clientCallOf(node, config, fnFile, table);
2447
+ if (client !== undefined) {
2448
+ saw = true;
2449
+ if (entry.methodFromBody !== true && client.method !== entry.method) {
2450
+ failed = true;
2451
+ return;
2452
+ }
2453
+ const targets = table.callTargets(client.url, fnFile, bindings);
2454
+ if (targets === undefined) {
2455
+ failed = true;
2456
+ return;
2457
+ }
2458
+ const method = entry.methodFromBody === true ? client.method : entry.method;
2459
+ for (const raw of targets)
2460
+ found.push({ method, raw });
2461
+ return;
2462
+ }
2463
+ const nestedName = ts.isIdentifier(node.expression) ? node.expression.text : undefined;
2464
+ const nested = nestedName === undefined ? undefined : activeWrapperIn(config, nestedName, fnFile);
2465
+ if (nested !== undefined && nested.name !== entry.name) {
2466
+ saw = true;
2467
+ const innerFn = table.findFunction(nested.name, fnFile);
2468
+ if (innerFn === undefined) {
2469
+ failed = true;
2470
+ return;
2471
+ }
2472
+ const paramName = nested.parameter ?? firstIdentifierParam(innerFn.fn);
2473
+ const next = new Map(bindings);
2474
+ if (paramName !== undefined) {
2475
+ const argument = argumentForParameter(innerFn.fn, paramName, node);
2476
+ if (argument !== undefined) {
2477
+ const followed = ts.isIdentifier(argument) ? bindings.get(argument.text) : undefined;
2478
+ next.set(paramName, followed ?? [argument, fnFile]);
2479
+ }
2480
+ }
2481
+ const inner = wrapperBodyTargets(innerFn.fn, innerFn.file, nested, config, table, next, depth + 1, stack);
2482
+ if (inner === 'unmodeled' || inner === 'unresolved') {
2483
+ failed = true;
2484
+ return;
2485
+ }
2486
+ found.push(...inner);
2487
+ return;
2488
+ }
2489
+ ts.forEachChild(node, visit);
2490
+ };
2491
+ if (fn.body !== undefined)
2492
+ visit(fn.body);
2493
+ stack.delete(stackKey);
2494
+ if (!saw)
2495
+ return 'unmodeled';
2496
+ if (failed || found.length === 0)
2497
+ return 'unresolved';
2498
+ return found;
2499
+ }
2500
+ function clientCallOf(call, config, file, table) {
2501
+ const expression = call.expression;
2502
+ if (ts.isIdentifier(expression) && expression.text === 'fetch' && !table.shadowsGlobalFetch(expression)) {
2503
+ const url = call.arguments[0];
2504
+ return url === undefined ? undefined : { url, method: 'GET' };
2505
+ }
2506
+ if (!ts.isPropertyAccessExpression(expression) || !ts.isIdentifier(expression.expression))
2507
+ return undefined;
2508
+ const objectName = table.configuredClientName(expression.expression, file);
2509
+ const verb = expression.name.text.toLowerCase();
2510
+ if (!(objectName === 'axios' || clientSymbolActiveIn(config, objectName, file)) || !VERB_METHODS.has(verb)) {
2511
+ return undefined;
2512
+ }
2513
+ const url = call.arguments[0];
2514
+ if (url === undefined)
2515
+ return undefined;
2516
+ return { url, method: VERB_METHODS.get(verb) ?? 'GET' };
1763
2517
  }
1764
2518
  /**
1765
2519
  * Validates the include/exclude scoping fields of one object-form
@@ -1843,11 +2597,21 @@ export function parseClientScanConfigDocument(section, at) {
1843
2597
  if (Array.isArray(document['wrapperFunctions'])) {
1844
2598
  config.wrapperFunctions = document['wrapperFunctions'].map((entry) => {
1845
2599
  const record = entry;
1846
- const method = normalizeHttpMethodValue(String(record['method'] ?? 'GET'));
2600
+ const methodFromBody = record['methodFromBody'] === true;
2601
+ const method = methodFromBody && record['method'] === undefined
2602
+ ? 'GET'
2603
+ : normalizeHttpMethodValue(String(record['method'] ?? 'GET'));
1847
2604
  if (method === null) {
1848
2605
  throw new Error(`invalid http client config: wrapper method must be a concrete verb at ${at}`);
1849
2606
  }
1850
- return { name: String(record['name']), method, ...parseEntryScoping(record, 'wrapperFunctions', at) };
2607
+ const parameter = typeof record['parameter'] === 'string' ? record['parameter'] : undefined;
2608
+ return {
2609
+ name: String(record['name']),
2610
+ method,
2611
+ ...(methodFromBody ? { methodFromBody: true } : {}),
2612
+ ...(parameter === undefined ? {} : { parameter }),
2613
+ ...parseEntryScoping(record, 'wrapperFunctions', at),
2614
+ };
1851
2615
  });
1852
2616
  }
1853
2617
  if (Array.isArray(document['urlBuilders'])) {