@techspokes/typescript-wsdl-client 1.1.8 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +22 -3
  2. package/dist/checkedPlanning.js +27 -4
  3. package/dist/cli.js +17 -1
  4. package/dist/client/checkedDirectRuntime.d.ts +11 -1
  5. package/dist/client/checkedDirectRuntime.js +19 -2
  6. package/dist/client/directClientRuntime.d.ts +18 -1
  7. package/dist/client/directClientRuntime.js +15 -3
  8. package/dist/client/directClientVersion.d.ts +2 -0
  9. package/dist/client/directClientVersion.js +2 -0
  10. package/dist/client/generateClient.js +72 -16
  11. package/dist/client/generateDirectClient.js +14 -9
  12. package/dist/client/generateOperations.js +30 -11
  13. package/dist/client/generateUtils.js +5 -1
  14. package/dist/compiler/canonicalGraph.d.ts +4 -15
  15. package/dist/compiler/canonicalGraph.js +1 -8
  16. package/dist/compiler/componentRecordProjection.d.ts +3 -0
  17. package/dist/compiler/componentRecordProjection.js +10 -0
  18. package/dist/compiler/declarationIdentity.d.ts +22 -0
  19. package/dist/compiler/declarationIdentity.js +9 -0
  20. package/dist/compiler/directCodec.d.ts +22 -2
  21. package/dist/compiler/directCodec.js +40 -7
  22. package/dist/compiler/directOperation.d.ts +28 -5
  23. package/dist/compiler/directOperation.js +84 -14
  24. package/dist/compiler/directSoap.d.ts +40 -10
  25. package/dist/compiler/directSoap.js +151 -18
  26. package/dist/compiler/directSoapSource.js +3 -2
  27. package/dist/compiler/directSourceCapsule.js +69 -4
  28. package/dist/compiler/directStructure.js +6 -2
  29. package/dist/compiler/directStructurePlan.d.ts +10 -1
  30. package/dist/compiler/directStructurePlan.js +27 -7
  31. package/dist/compiler/directValues.d.ts +15 -3
  32. package/dist/compiler/directValues.js +20 -4
  33. package/dist/compiler/legacyDeclarations.d.ts +26 -0
  34. package/dist/compiler/legacyDeclarations.js +144 -0
  35. package/dist/compiler/projectionScalar.d.ts +18 -1
  36. package/dist/compiler/projectionScalar.js +47 -13
  37. package/dist/compiler/rpcStringValues.d.ts +30 -0
  38. package/dist/compiler/rpcStringValues.js +196 -0
  39. package/dist/compiler/rpcTypedValues.d.ts +48 -0
  40. package/dist/compiler/rpcTypedValues.js +190 -0
  41. package/dist/compiler/schemaCompiler.js +44 -109
  42. package/dist/compiler/semanticCatalog.d.ts +2 -2
  43. package/dist/compiler/soapHeaders.d.ts +10 -4
  44. package/dist/compiler/soapHeaders.js +28 -9
  45. package/dist/gateway/generateCheckedGateway.js +26 -6
  46. package/dist/gateway/generateComposedGateway.d.ts +16 -0
  47. package/dist/gateway/generateComposedGateway.js +65 -0
  48. package/dist/gateway/generateGateway.js +1 -0
  49. package/dist/gateway/generators.js +19 -4
  50. package/dist/gateway/helpers.d.ts +1 -0
  51. package/dist/gateway/helpers.js +15 -0
  52. package/dist/generation/componentShape.js +25 -1
  53. package/dist/index.d.ts +5 -1
  54. package/dist/index.js +3 -1
  55. package/dist/loader/orderedSyntax.d.ts +4 -0
  56. package/dist/loader/orderedSyntax.js +18 -4
  57. package/dist/multiServicePipeline.d.ts +41 -0
  58. package/dist/multiServicePipeline.js +287 -0
  59. package/dist/openapi/composeOpenAPI.d.ts +29 -0
  60. package/dist/openapi/composeOpenAPI.js +322 -0
  61. package/dist/pipeline.d.ts +1 -1
  62. package/dist/pipeline.js +2 -0
  63. package/docs/agent-skill.md +10 -1
  64. package/docs/api-reference.md +127 -9
  65. package/docs/checked-gateway.md +10 -0
  66. package/docs/checked-generation.md +11 -5
  67. package/docs/cli-reference.md +25 -5
  68. package/docs/concepts.md +4 -5
  69. package/docs/configuration.md +10 -3
  70. package/docs/corpus.md +1 -1
  71. package/docs/gateway-guide.md +104 -27
  72. package/docs/generated-code.md +12 -6
  73. package/docs/migration-playbook.md +4 -0
  74. package/docs/migration.md +134 -6
  75. package/docs/output-anatomy.md +20 -17
  76. package/docs/production.md +7 -5
  77. package/docs/start-here.md +12 -2
  78. package/docs/supported-patterns.md +23 -0
  79. package/docs/testing.md +2 -0
  80. package/docs/troubleshooting.md +3 -1
  81. package/llms.txt +9 -1
  82. package/package.json +2 -2
  83. package/src/runtime/clientStreamMethods.tpl.txt +156 -148
  84. package/src/runtime/operationsStreamHelper.tpl.txt +6 -6
  85. package/src/runtime/streamXml.ts +48 -20
@@ -19,7 +19,31 @@ export function lowerComponentShape(contract, supplied, role, check) {
19
19
  const owned = inspectComponentRecordProjection(supplied, contract);
20
20
  return lowerComponentShape(owned.companion, owned.mapping, role, check);
21
21
  }
22
- const { projection, applicationGroups } = inspectComponentValueMapping(supplied, contract), { context } = inspectDirectOperation(contract);
22
+ const { mapping, projection, applicationGroups, rpcParts } = inspectComponentValueMapping(supplied, contract), { context } = inspectDirectOperation(contract);
23
+ if ('parts' in mapping.root) {
24
+ const properties = Object.create(null);
25
+ const required = [], members = [];
26
+ for (const part of mapping.root.parts) {
27
+ check();
28
+ const plan = rpcParts?.find(plan => plan.name === part.name)?.projection;
29
+ let type = 'string';
30
+ if (plan?.root.kind === 'record') {
31
+ const record = plan.records[0];
32
+ const fields = Object.fromEntries(record.slots.map(slot => [slot.element.name.local, { type: 'boolean' }]));
33
+ properties[part.name] = { type: 'object', properties: fields, required: Object.keys(fields), additionalProperties: false };
34
+ type = `{${record.slots.map(slot => `readonly ${literal(slot.element.name.local)}: boolean`).join('; ')}}`;
35
+ }
36
+ else {
37
+ type = plan?.root.kind === 'scalar' && plan.root.builtin.local === 'boolean' ? 'boolean' : 'string';
38
+ properties[part.name] = { type };
39
+ }
40
+ required.push(part.name);
41
+ members.push(`readonly ${literal(part.name)}: ${type}`);
42
+ }
43
+ return { type: `{${members.join('; ')}}`, declarations: [], schema: { type: 'object', additionalProperties: false, properties, required } };
44
+ }
45
+ if (!projection)
46
+ throw new TypeError('Native document projection required');
23
47
  const names = new Map(projection.records.map((record, index) => [record.type.id, applicationGroups
24
48
  ? applicationRecordName(record.type.id) : `${role}_Record_${index}`]));
25
49
  const definitions = Object.create(null);
package/dist/index.d.ts CHANGED
@@ -5,13 +5,17 @@ export { buildSecurity, loadSecurityConfigFile, parseSecurityConfig, SecurityCon
5
5
  export { generateTests } from "./test/generateTests.js";
6
6
  export { runGenerationPipeline } from "./pipeline.js";
7
7
  export type { PipelineOptions } from './pipeline.js';
8
+ export { runMultiServicePipeline, loadMultiServiceConfig } from './multiServicePipeline.js';
9
+ export type { MultiServicePipelineOptions, MultiServicePipelineResult, MultiServiceEntry } from './multiServicePipeline.js';
10
+ export { composeOpenApiDocuments } from './openapi/composeOpenAPI.js';
11
+ export type { ComposedOpenApiDocument, OpenApiCompositionEntry, OpenApiCompositionOptions } from './openapi/composeOpenAPI.js';
8
12
  export type { CheckedComponentOptions, CheckedInventory } from './checkedPipeline.js';
9
13
  export { planCheckedComponents, formatCheckedComponentPlan, writeCheckedPlanningFile, CheckedPlanningError } from './checkedPlanning.js';
10
14
  export type { CheckedComponentPlan, ComponentPlanBlocker } from './checkedPlanning.js';
11
15
  export type { ComponentRecordProjectionSpec, ComponentRecordProjectionAssociation } from './compiler/componentRecordProjection.js';
12
16
  export { loadStreamConfigFile, parseStreamConfig, StreamConfigError, type OperationStreamMetadata, type ShapeCatalogRef, type StreamConfig, } from "./util/streamConfig.js";
13
17
  export { applyShapeCatalogs, type ApplyShapeCatalogsOptions } from "./compiler/shapeResolver.js";
14
- export { checkedDirectRuntimeV1, checkedComponentRuntimeV1 } from './client/checkedDirectRuntime.js';
18
+ export { checkedDirectRuntimeV1, checkedComponentRuntimeV1, checkedComponentRuntimeV2 } from './client/checkedDirectRuntime.js';
15
19
  /**
16
20
  * Compiles a WSDL file to TypeScript client code
17
21
  *
package/dist/index.js CHANGED
@@ -27,10 +27,12 @@ export { generateGateway } from "./gateway/generateGateway.js";
27
27
  export { buildSecurity, loadSecurityConfigFile, parseSecurityConfig, SecurityConfigError, } from "./util/securityConfig.js";
28
28
  export { generateTests } from "./test/generateTests.js";
29
29
  export { runGenerationPipeline } from "./pipeline.js";
30
+ export { runMultiServicePipeline, loadMultiServiceConfig } from './multiServicePipeline.js';
31
+ export { composeOpenApiDocuments } from './openapi/composeOpenAPI.js';
30
32
  export { planCheckedComponents, formatCheckedComponentPlan, writeCheckedPlanningFile, CheckedPlanningError } from './checkedPlanning.js';
31
33
  export { loadStreamConfigFile, parseStreamConfig, StreamConfigError, } from "./util/streamConfig.js";
32
34
  export { applyShapeCatalogs } from "./compiler/shapeResolver.js";
33
- export { checkedDirectRuntimeV1, checkedComponentRuntimeV1 } from './client/checkedDirectRuntime.js';
35
+ export { checkedDirectRuntimeV1, checkedComponentRuntimeV1, checkedComponentRuntimeV2 } from './client/checkedDirectRuntime.js';
34
36
  // noinspection JSUnusedGlobalSymbols
35
37
  /**
36
38
  * Compiles a WSDL file to TypeScript client code
@@ -70,6 +70,10 @@ export declare function resolveLexicalQName(lexical: string, node: SyntaxElement
70
70
  export declare function decodeMetadataXml(bytes: Uint8Array): string;
71
71
  /** Positions are one-based lines/columns and zero-based UTF-16 offsets in decoded XML. */
72
72
  export interface OrderedSyntaxOptions {
73
+ /** Explicit component SOAP response policy; source and shipped direct decoding remain separate. */
74
+ componentResponseEncoding?: {
75
+ charset?: string;
76
+ };
73
77
  /** Internal metadata boundary; payload/capsule callers retain the existing encoding policy. */
74
78
  metadataEncoding?: boolean;
75
79
  maxDepth?: number;
@@ -55,19 +55,33 @@ const xmlEncodingDeclaration = /^<\?xml\s[^?]*encoding\s*=\s*["']([^"']+)["']/i;
55
55
  export function decodeMetadataXml(bytes) {
56
56
  return decodeXml(bytes, true, true);
57
57
  }
58
- function decodeXml(bytes, strictBom = false, metadata = false) {
58
+ function decodeXml(bytes, strictBom = false, metadata = false, response) {
59
59
  let encoding = bytes[0] === 0xff && bytes[1] === 0xfe ? "utf-16le"
60
60
  : bytes[0] === 0xfe && bytes[1] === 0xff ? "utf-16be" : "utf-8";
61
61
  try {
62
62
  const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
63
63
  // @why Sniff only an ASCII declaration, never guess Latin1 after UTF-8 failure.
64
64
  // A BOM fixes the encoding and must agree with the decoded declaration.
65
- if (metadata && encoding === 'utf-8' && !(bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf)) {
65
+ const bom = encoding !== 'utf-8' || bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf;
66
+ const canonical = (label) => label.toLowerCase() === 'utf8' ? 'utf-8' : label.toLowerCase();
67
+ const agrees = (label) => canonical(label) === encoding || canonical(label) === 'utf-16' && encoding.startsWith('utf-16');
68
+ if ((metadata || response) && !bom) {
66
69
  const end = buffer.indexOf('>');
67
70
  const declaration = xmlEncodingDeclaration.exec(buffer.toString('latin1', 0, end < 0 ? 0 : end + 1))?.[1].toLowerCase();
68
- if (declaration === 'iso-8859-1')
71
+ if (response) {
72
+ const asserted = response.charset ?? declaration;
73
+ if (asserted) {
74
+ const selected = canonical(asserted);
75
+ if (!['utf-8', 'iso-8859-1'].includes(selected))
76
+ throw new SchemaLoadingError('unsupported-capability', 'Unsupported XML byte encoding');
77
+ encoding = selected;
78
+ }
79
+ }
80
+ else if (declaration === 'iso-8859-1')
69
81
  encoding = 'iso-8859-1';
70
82
  }
83
+ if (response?.charset && !agrees(response.charset))
84
+ throw new SchemaLoadingError('unsupported-capability', 'HTTP charset disagrees with XML bytes');
71
85
  // TextDecoder's ISO label aliases Windows-1252; Buffer supplies actual ISO byte identity.
72
86
  const text = encoding === 'iso-8859-1' ? buffer.toString('latin1') : new TextDecoder(encoding, { fatal: true }).decode(bytes);
73
87
  if (strictBom && text.startsWith('\ufeff'))
@@ -107,7 +121,7 @@ export function parseOrderedSyntax(bytes, uri, options = {}) {
107
121
  const charge = (amount) => options.chargeWork?.(amount);
108
122
  charge(4096 + bytes.byteLength * 64);
109
123
  const digest = createHash("sha256").update(bytes).digest("hex");
110
- const text = options.metadataEncoding ? decodeMetadataXml(bytes) : decodeXml(bytes, options.xml10Only);
124
+ const text = options.metadataEncoding ? decodeMetadataXml(bytes) : decodeXml(bytes, options.xml10Only, false, options.componentResponseEncoding);
111
125
  const lines = [0];
112
126
  for (let i = 0; i < text.length; i++) {
113
127
  if (text[i] === "\r") {
@@ -0,0 +1,41 @@
1
+ import { type PipelineOptions } from "./pipeline.js";
2
+ import { type ComposedOpenApiDocument, type OpenApiCompositionOptions } from "./openapi/composeOpenAPI.js";
3
+ import type { CompiledCatalog } from "./compiler/schemaCompiler.js";
4
+ export interface MultiServiceEntry {
5
+ key: string;
6
+ generation: PipelineOptions;
7
+ }
8
+ export interface MultiServicePipelineOptions {
9
+ services: readonly MultiServiceEntry[];
10
+ openapi: OpenApiCompositionOptions & {
11
+ outFile: string;
12
+ };
13
+ gateway: {
14
+ outDir: string;
15
+ imports?: "js" | "ts" | "bare";
16
+ openapiPath?: string | false;
17
+ };
18
+ }
19
+ export interface MultiServicePipelineResult {
20
+ openapiDoc: ComposedOpenApiDocument;
21
+ services: Record<string, {
22
+ compiled: CompiledCatalog;
23
+ clientDir: string;
24
+ gatewayDir: string;
25
+ }>;
26
+ pluginFile: string;
27
+ openapiFile: string;
28
+ }
29
+ /** Generate independent WSDL clients behind one typed gateway and discoverable API definition.
30
+ * @param options Explicit per-service pipelines and disjoint aggregate output paths.
31
+ * @returns Matched aggregate artifacts and each service's unmerged compiled catalog.
32
+ * @throws For configuration/output conflicts, source generation failures or invalid API composition.
33
+ * @sideEffects Generates each selected legacy service in caller order, then publishes the aggregate spec/plugin pair.
34
+ * @constraints Failure preserves previous aggregate spec/plugin files; earlier generated service dependencies are not rolled back.
35
+ */
36
+ export declare function runMultiServicePipeline(options: MultiServicePipelineOptions): Promise<MultiServicePipelineResult>;
37
+ /** Load a composition config with paths resolved against its own directory.
38
+ * @throws For invalid JSON or missing required output/source paths when the pipeline validates it.
39
+ * @constraints Runtime client options and credentials are deliberately not generation configuration.
40
+ */
41
+ export declare function loadMultiServiceConfig(file: string): Promise<MultiServicePipelineOptions>;
@@ -0,0 +1,287 @@
1
+ import fs from "node:fs/promises";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { types } from "node:util";
6
+ import { fileURLToPath } from "node:url";
7
+ import { runGenerationPipeline } from "./pipeline.js";
8
+ import { composeOpenApiDocuments } from "./openapi/composeOpenAPI.js";
9
+ import { buildComposedGatewaySource } from "./gateway/generateComposedGateway.js";
10
+ import { deriveClientName } from "./util/tools.js";
11
+ import { slugName } from "./gateway/helpers.js";
12
+ const data = (value, label) => {
13
+ if (!value || typeof value !== "object" || Array.isArray(value) || types.isProxy(value) || ![null, Object.prototype].includes(Object.getPrototypeOf(value)))
14
+ throw new TypeError(`${label} must be a data object`);
15
+ for (const property of Object.values(Object.getOwnPropertyDescriptors(value)))
16
+ if (!Object.hasOwn(property, "value"))
17
+ throw new TypeError(`${label} must not contain accessors`);
18
+ return value;
19
+ };
20
+ const text = (value, label) => {
21
+ if (typeof value !== "string" || !value.trim())
22
+ throw new TypeError(`${label} must be a nonempty string`);
23
+ return value;
24
+ };
25
+ const known = (value, allowed, label) => {
26
+ for (const key of Reflect.ownKeys(value))
27
+ if (typeof key !== "string" || !allowed.includes(key))
28
+ throw new TypeError(`Unknown ${label} option: ${String(key)}`);
29
+ };
30
+ const localPath = (value, label) => {
31
+ // @why Lexically different output paths can share a symlink/junction target; ownership checks must compare their filesystem destinations.
32
+ let ancestor = path.resolve(text(value, label));
33
+ const missing = [];
34
+ while (!existsSync(ancestor)) {
35
+ missing.unshift(path.basename(ancestor));
36
+ const parent = path.dirname(ancestor);
37
+ if (parent === ancestor)
38
+ throw new TypeError(`Cannot resolve output filesystem root for ${label}`);
39
+ ancestor = parent;
40
+ }
41
+ return path.join(realpathSync(ancestor), ...missing);
42
+ };
43
+ const canonical = (value) => process.platform === "win32" ? value.toLowerCase() : value;
44
+ const within = (directory, file) => {
45
+ const relative = path.relative(canonical(directory), canonical(file));
46
+ return relative === "" || relative !== ".." && !relative.startsWith(".." + path.sep) && !path.isAbsolute(relative);
47
+ };
48
+ const prefix = (value) => {
49
+ const result = text(value, "generation.openapi.basePath");
50
+ if (!/^\/(?:[a-zA-Z0-9._~-]+\/)*[a-zA-Z0-9._~-]+$/.test(result) || result.split("/").some(segment => segment === "." || segment === ".."))
51
+ throw new TypeError("Each service needs an explicit static OpenAPI basePath without trailing slash");
52
+ return result;
53
+ };
54
+ function prepare(options) {
55
+ const input = data(options, "composition");
56
+ if (Object.keys(input).some(key => !["services", "openapi", "gateway"].includes(key)))
57
+ throw new TypeError("Unknown multi-service composition option");
58
+ if (!Array.isArray(options.services) || options.services.length === 0)
59
+ throw new TypeError("At least one independent service is required");
60
+ known(data(options.openapi, "aggregate OpenAPI"), ["outFile", "title", "version", "description", "servers"], "aggregate OpenAPI");
61
+ known(data(options.gateway, "aggregate gateway"), ["outDir", "imports", "openapiPath"], "aggregate gateway");
62
+ for (const name of ["title", "version", "description"])
63
+ if (options.openapi[name] !== undefined && typeof options.openapi[name] !== "string")
64
+ throw new TypeError(`openapi.${name} must be a string`);
65
+ if (options.openapi.servers !== undefined && (!Array.isArray(options.openapi.servers) || options.openapi.servers.some(server => typeof server !== "string" || !server)))
66
+ throw new TypeError("openapi.servers must contain server URL strings");
67
+ const outFile = localPath(options.openapi.outFile, "openapi.outFile");
68
+ if (path.extname(outFile).toLowerCase() !== ".json")
69
+ throw new TypeError("The aggregate OpenAPI output must be a JSON file");
70
+ const gatewayDir = localPath(options.gateway.outDir, "gateway.outDir");
71
+ if (options.gateway.imports !== undefined && !["js", "ts", "bare"].includes(options.gateway.imports))
72
+ throw new TypeError("Invalid aggregate import extension mode");
73
+ const openapiPath = options.gateway.openapiPath === false ? false : options.gateway.openapiPath ?? "/openapi.json";
74
+ if (openapiPath !== false && (!/^\/[^?#\\]*$/.test(openapiPath) || openapiPath.includes("//")))
75
+ throw new TypeError("Invalid OpenAPI discovery path");
76
+ const keys = new Set(), slugs = new Set(), decorators = new Set(), prefixes = new Set();
77
+ const outputs = [
78
+ { owner: "aggregate", role: "gateway", file: gatewayDir, directory: true },
79
+ { owner: "aggregate", role: "openapi", file: outFile, directory: false },
80
+ ];
81
+ const entries = options.services.map(entry => {
82
+ data(entry, "service entry");
83
+ if (Object.keys(entry).some(key => !["key", "generation"].includes(key)))
84
+ throw new TypeError("Unknown service entry option");
85
+ const key = text(entry.key, "service key");
86
+ if (!/^[a-z][a-z0-9-]*$/.test(key) || keys.has(key))
87
+ throw new TypeError("Unique lowercase service keys required");
88
+ keys.add(key);
89
+ const generation = data(entry.generation, `generation for ${key}`);
90
+ known(generation, ["model", "checkedComponents", "wsdl", "catalogOut", "clientOutDir", "compiler", "openapi", "gateway", "app", "test", "streamConfigFile", "streamConfig"], "service generation");
91
+ if (generation.model !== undefined && generation.model !== "legacy" || generation.checkedComponents !== undefined || generation.app !== undefined || generation.test !== undefined)
92
+ throw new TypeError("Multi-service generation currently composes legacy service routers; app/test/checked settings are not aggregate settings");
93
+ text(generation.wsdl, `${key}.wsdl`);
94
+ if (!generation.openapi || !generation.gateway)
95
+ throw new TypeError(`Service ${key} requires OpenAPI and gateway generation`);
96
+ data(generation.openapi, "service OpenAPI");
97
+ data(generation.gateway, "service gateway");
98
+ const basePath = prefix(generation.openapi.basePath);
99
+ if (prefixes.has(basePath))
100
+ throw new TypeError(`Duplicate service basePath ${basePath}`);
101
+ prefixes.add(basePath);
102
+ const clientDir = localPath(generation.clientOutDir, `${key}.clientOutDir`);
103
+ const catalogOut = localPath(generation.catalogOut, `${key}.catalogOut`);
104
+ const serviceOpenapi = localPath(generation.openapi.outFile, `${key}.openapi.outFile`);
105
+ const serviceGateway = localPath(generation.gateway.outDir, `${key}.gateway.outDir`);
106
+ if (!slugName(text(generation.gateway.versionSlug, `${key}.gateway.versionSlug`)))
107
+ throw new TypeError("A normalized gateway version slug is required");
108
+ const slug = slugName(text(generation.gateway.serviceSlug, `${key}.gateway.serviceSlug`));
109
+ if (!slug || slugs.has(slug))
110
+ throw new TypeError("Gateway service slugs must remain unique after normalization");
111
+ slugs.add(slug);
112
+ const decorator = generation.gateway.clientDecoratorName ?? `wsdl_${key.replaceAll("-", "_")}Client`;
113
+ if (!/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(decorator) || decorators.has(decorator))
114
+ throw new TypeError("Unique valid client decorators required");
115
+ decorators.add(decorator);
116
+ if (generation.gateway.emitPlugin === false || generation.gateway.stubHandlers === true || generation.gateway.emitRuntime === false)
117
+ throw new TypeError("Composition requires complete service plugins and runtime handlers");
118
+ for (const target of [clientDir, serviceGateway])
119
+ if (path.parse(target).root !== path.parse(gatewayDir).root)
120
+ throw new TypeError("Composed generated modules must share a filesystem root");
121
+ outputs.push({ owner: key, role: "client", file: clientDir, directory: true }, { owner: key, role: "gateway", file: serviceGateway, directory: true }, { owner: key, role: "catalog", file: catalogOut, directory: false }, { owner: key, role: "openapi", file: serviceOpenapi, directory: false });
122
+ return { key, generation: { ...generation, catalogOut, clientOutDir: clientDir,
123
+ openapi: { ...generation.openapi, basePath, outFile: serviceOpenapi },
124
+ gateway: { ...generation.gateway, outDir: serviceGateway, clientDecoratorName: decorator } } };
125
+ });
126
+ for (let a = 0; a < outputs.length; a++)
127
+ for (let b = a + 1; b < outputs.length; b++) {
128
+ const left = outputs[a], right = outputs[b];
129
+ if (canonical(left.file) === canonical(right.file))
130
+ throw new TypeError(`Conflicting output paths: ${left.role} and ${right.role}`);
131
+ const overlap = left.directory && within(left.file, right.file) || right.directory && within(right.file, left.file);
132
+ if (overlap && (left.owner !== right.owner || left.directory && right.directory))
133
+ throw new TypeError("Service output ownership must not overlap");
134
+ const file = left.directory ? right : left, directory = left.directory ? left : right;
135
+ if (overlap && !file.directory && directory.directory) {
136
+ const relative = path.relative(directory.file, file.file).replaceAll("\\", "/");
137
+ if (relative.endsWith(".ts") || /^(?:routes|schemas)(?:\/|$)/.test(relative))
138
+ throw new TypeError("Output file conflicts with generated service modules");
139
+ }
140
+ }
141
+ for (const entry of entries) {
142
+ const source = entry.generation.wsdl;
143
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(source) && !source.startsWith("file:"))
144
+ continue;
145
+ const sourceFile = localPath(source.startsWith("file:") ? fileURLToPath(source) : source, "source WSDL");
146
+ if (outputs.some(output => output.directory ? within(output.file, sourceFile) : canonical(output.file) === canonical(sourceFile)))
147
+ throw new TypeError("Source WSDLs must remain outside generated output ownership");
148
+ }
149
+ return { entries, outFile, gatewayDir, openapiPath };
150
+ }
151
+ /** Publish the matched spec/plugin after all service generation and composition checks succeed.
152
+ * @constraints Uses only individually owned staging files; never removes a consumer output tree.
153
+ */
154
+ async function publish(files) {
155
+ const staged = [];
156
+ try {
157
+ for (const { file, content } of files) {
158
+ await fs.mkdir(path.dirname(file), { recursive: true });
159
+ let previous;
160
+ try {
161
+ previous = await fs.readFile(file);
162
+ }
163
+ catch (error) {
164
+ if (error.code !== "ENOENT")
165
+ throw error;
166
+ }
167
+ const temporary = file + ".stage-" + randomUUID();
168
+ staged.push({ file, temporary, previous, committed: false });
169
+ await fs.writeFile(temporary, content, { flag: "wx" });
170
+ }
171
+ for (const entry of staged) {
172
+ await fs.rename(entry.temporary, entry.file);
173
+ entry.committed = true;
174
+ }
175
+ }
176
+ catch (error) {
177
+ for (const entry of [...staged].reverse())
178
+ if (entry.committed) {
179
+ if (entry.previous === undefined)
180
+ await fs.unlink(entry.file);
181
+ else
182
+ await fs.writeFile(entry.file, entry.previous);
183
+ }
184
+ throw error;
185
+ }
186
+ finally {
187
+ for (const entry of staged)
188
+ await fs.unlink(entry.temporary).catch(error => { if (error.code !== "ENOENT")
189
+ throw error; });
190
+ }
191
+ }
192
+ /** Generate independent WSDL clients behind one typed gateway and discoverable API definition.
193
+ * @param options Explicit per-service pipelines and disjoint aggregate output paths.
194
+ * @returns Matched aggregate artifacts and each service's unmerged compiled catalog.
195
+ * @throws For configuration/output conflicts, source generation failures or invalid API composition.
196
+ * @sideEffects Generates each selected legacy service in caller order, then publishes the aggregate spec/plugin pair.
197
+ * @constraints Failure preserves previous aggregate spec/plugin files; earlier generated service dependencies are not rolled back.
198
+ */
199
+ export async function runMultiServicePipeline(options) {
200
+ const prepared = prepare(options);
201
+ const services = Object.create(null);
202
+ const documents = [];
203
+ const routers = [];
204
+ for (const { key, generation } of prepared.entries) {
205
+ const result = await runGenerationPipeline(generation);
206
+ const compiled = result.compiled;
207
+ const fileSlugs = new Set();
208
+ const expectedOperations = new Set(compiled.operations.map(operation => operation.name));
209
+ if (expectedOperations.size !== compiled.operations.length)
210
+ throw new TypeError(`Service ${key} has overloaded operation names that cannot own unique gateway routes`);
211
+ for (const operation of compiled.operations) {
212
+ const slug = slugName(operation.name);
213
+ if (!slug || fileSlugs.has(slug))
214
+ throw new TypeError(`Service ${key} has colliding generated operation filenames`);
215
+ fileSlugs.add(slug);
216
+ }
217
+ const described = [];
218
+ const document = data(result.openapiDoc, "generated OpenAPI");
219
+ for (const item of Object.values(data(document.paths, "generated paths"))) {
220
+ const pathItem = data(item, "generated path item");
221
+ for (const method of ["get", "put", "post", "delete", "options", "head", "patch", "trace"]) {
222
+ if (pathItem[method] !== undefined)
223
+ described.push(text(data(pathItem[method], "generated operation").operationId, "operationId"));
224
+ }
225
+ }
226
+ if (described.length !== expectedOperations.size || described.some(name => !expectedOperations.has(name)))
227
+ throw new TypeError(`Service ${key} loses operations through generated route collisions`);
228
+ const className = deriveClientName(compiled);
229
+ if (generation.gateway.clientClassName && generation.gateway.clientClassName !== className)
230
+ throw new TypeError("Configure compiler.clientName to keep client and gateway classes matched");
231
+ services[key] = { compiled, clientDir: generation.clientOutDir, gatewayDir: generation.gateway.outDir };
232
+ documents.push({ key, document: result.openapiDoc });
233
+ routers.push({ key, clientDir: generation.clientOutDir, gatewayDir: generation.gateway.outDir, clientClassName: className });
234
+ }
235
+ const openapiDoc = composeOpenApiDocuments(documents, options.openapi);
236
+ const { default: SwaggerParser } = await import("@apidevtools/swagger-parser");
237
+ const validator = new SwaggerParser();
238
+ await validator.validate(structuredClone(openapiDoc), { resolve: { external: false } });
239
+ if (prepared.openapiPath !== false && Object.hasOwn(openapiDoc.paths, prepared.openapiPath))
240
+ throw new TypeError("OpenAPI discovery path conflicts with a service route");
241
+ const pluginFile = path.join(prepared.gatewayDir, "plugin.ts");
242
+ const source = buildComposedGatewaySource(routers, { outDir: prepared.gatewayDir, openapiFile: prepared.outFile,
243
+ imports: options.gateway.imports, openapiPath: prepared.openapiPath });
244
+ await publish([{ file: prepared.outFile, content: JSON.stringify(openapiDoc, null, 2) + "\n" }, { file: pluginFile, content: source }]);
245
+ return { openapiDoc, services, pluginFile, openapiFile: prepared.outFile };
246
+ }
247
+ /** Load a composition config with paths resolved against its own directory.
248
+ * @throws For invalid JSON or missing required output/source paths when the pipeline validates it.
249
+ * @constraints Runtime client options and credentials are deliberately not generation configuration.
250
+ */
251
+ export async function loadMultiServiceConfig(file) {
252
+ const absolute = path.resolve(file), base = path.dirname(absolute);
253
+ const options = JSON.parse(await fs.readFile(absolute, "utf8"));
254
+ data(options, "composition");
255
+ data(options.openapi, "aggregate OpenAPI");
256
+ data(options.gateway, "aggregate gateway");
257
+ if (!Array.isArray(options.services))
258
+ throw new TypeError("services must be an array");
259
+ const resolve = (value) => value === undefined ? undefined : path.resolve(base, text(value, "config path"));
260
+ const source = (value) => /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? value : resolve(value);
261
+ options.openapi.outFile = resolve(options.openapi.outFile);
262
+ options.gateway.outDir = resolve(options.gateway.outDir);
263
+ for (const entry of options.services) {
264
+ data(entry, "service");
265
+ const generation = data(entry.generation, "generation");
266
+ generation.wsdl = source(text(generation.wsdl, "wsdl"));
267
+ generation.catalogOut = resolve(generation.catalogOut);
268
+ generation.clientOutDir = resolve(generation.clientOutDir);
269
+ generation.streamConfigFile = resolve(generation.streamConfigFile);
270
+ if (generation.openapi) {
271
+ generation.openapi.outFile = resolve(generation.openapi.outFile);
272
+ generation.openapi.tagsFile = resolve(generation.openapi.tagsFile);
273
+ generation.openapi.opsFile = resolve(generation.openapi.opsFile);
274
+ generation.openapi.securityConfigFile = resolve(generation.openapi.securityConfigFile);
275
+ }
276
+ if (generation.gateway)
277
+ generation.gateway.outDir = resolve(generation.gateway.outDir);
278
+ if (generation.streamConfig)
279
+ for (const shape of Object.values(generation.streamConfig.shapeCatalogs)) {
280
+ if (shape.catalogFile)
281
+ shape.catalogFile = resolve(shape.catalogFile);
282
+ if (shape.wsdlSource)
283
+ shape.wsdlSource = source(shape.wsdlSource);
284
+ }
285
+ }
286
+ return options;
287
+ }
@@ -0,0 +1,29 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
2
+ export interface JsonObject {
3
+ [key: string]: JsonValue;
4
+ }
5
+ export interface ComposedOpenApiDocument extends JsonObject {
6
+ openapi: string;
7
+ info: JsonObject;
8
+ paths: Record<string, JsonObject>;
9
+ components: Record<string, Record<string, JsonValue>>;
10
+ }
11
+ export interface OpenApiCompositionOptions {
12
+ title?: string;
13
+ version?: string;
14
+ description?: string;
15
+ servers?: readonly string[];
16
+ }
17
+ export interface OpenApiCompositionEntry {
18
+ key: string;
19
+ document: unknown;
20
+ }
21
+ /** Compose service-scoped OpenAPI contracts without changing SOAP client ownership.
22
+ * @param entries Self-contained OpenAPI 3.1 documents whose HTTP paths already contain their service prefixes.
23
+ * @param options Combined API metadata and default gateway servers; custom source servers remain operation-local.
24
+ * @returns A fresh deterministic document with qualified component names and operation identifiers.
25
+ * @throws For invalid JSON, duplicate service keys/paths/operation IDs, unresolved local references or unsupported relative references/schema resources.
26
+ * @constraints Only reference-bearing OpenAPI/JSON Schema positions are rewritten; examples, literal values and extensions remain data.
27
+ * @see https://spec.openapis.org/oas/v3.1.0.html Reference, Link, Security Requirement and Schema objects govern distinct reference positions.
28
+ */
29
+ export declare function composeOpenApiDocuments(entries: readonly OpenApiCompositionEntry[], options?: OpenApiCompositionOptions): ComposedOpenApiDocument;