@salesforce/ui-bundle-external-service-codegen 0.0.0-stage → 12.13.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.
package/LICENSE.txt ADDED
@@ -0,0 +1,82 @@
1
+ Terms of Use
2
+
3
+ Copyright 2026 Salesforce, Inc. All rights reserved.
4
+
5
+ These Terms of Use govern the download, installation, and/or use of this
6
+ software provided by Salesforce, Inc. ("Salesforce") (the "Software"), were
7
+ last updated on April 15, 2025, and constitute a legally binding
8
+ agreement between you and Salesforce. If you do not agree to these Terms of
9
+ Use, do not install or use the Software.
10
+
11
+ Salesforce grants you a worldwide, non-exclusive, no-charge, royalty-free
12
+ copyright license to reproduce, prepare derivative works of, publicly
13
+ display, publicly perform, sublicense, and distribute the Software and
14
+ derivative works subject to these Terms. These Terms shall be included in
15
+ all copies or substantial portions of the Software.
16
+
17
+ Subject to the limited rights expressly granted hereunder, Salesforce
18
+ reserves all rights, title, and interest in and to all intellectual
19
+ property subsisting in the Software. No rights are granted to you hereunder
20
+ other than as expressly set forth herein. Users residing in countries on
21
+ the United States Office of Foreign Assets Control sanction list, or which
22
+ are otherwise subject to a US export embargo, may not use the Software.
23
+
24
+ Implementation of the Software may require development work, for which you
25
+ are responsible. The Software may contain bugs, errors and
26
+ incompatibilities and is made available on an AS IS basis without support,
27
+ updates, or service level commitments.
28
+
29
+ Salesforce reserves the right at any time to modify, suspend, or
30
+ discontinue, the Software (or any part thereof) with or without notice. You
31
+ agree that Salesforce shall not be liable to you or to any third party for
32
+ any modification, suspension, or discontinuance.
33
+
34
+ You agree to defend Salesforce against any claim, demand, suit or
35
+ proceeding made or brought against Salesforce by a third party arising out
36
+ of or accruing from (a) your use of the Software, and (b) any application
37
+ you develop with the Software that infringes any copyright, trademark,
38
+ trade secret, trade dress, patent, or other intellectual property right of
39
+ any person or defames any person or violates their rights of publicity or
40
+ privacy (each a "Claim Against Salesforce"), and will indemnify Salesforce
41
+ from any damages, attorney fees, and costs finally awarded against
42
+ Salesforce as a result of, or for any amounts paid by Salesforce under a
43
+ settlement approved by you in writing of, a Claim Against Salesforce,
44
+ provided Salesforce (x) promptly gives you written notice of the Claim
45
+ Against Salesforce, (y) gives you sole control of the defense and
46
+ settlement of the Claim Against Salesforce (except that you may not settle
47
+ any Claim Against Salesforce unless it unconditionally releases Salesforce
48
+ of all liability), and (z) gives you all reasonable assistance, at your
49
+ expense.
50
+
51
+ WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE SOFTWARE IS NOT
52
+ SUPPORTED AND IS PROVIDED "AS IS," WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
53
+ IMPLIED. IN NO EVENT SHALL SALESFORCE HAVE ANY LIABILITY FOR ANY DAMAGES,
54
+ INCLUDING, BUT NOT LIMITED TO, DIRECT, INDIRECT, SPECIAL, INCIDENTAL,
55
+ PUNITIVE, OR CONSEQUENTIAL DAMAGES, OR DAMAGES BASED ON LOST PROFITS, DATA,
56
+ OR USE, IN CONNECTION WITH THE SOFTWARE, HOWEVER CAUSED AND WHETHER IN
57
+ CONTRACT, TORT, OR UNDER ANY OTHER THEORY OF LIABILITY, WHETHER OR NOT YOU
58
+ HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
59
+
60
+ These Terms of Use shall be governed exclusively by the internal laws of
61
+ the State of California, without regard to its conflicts of laws
62
+ rules. Each party hereby consents to the exclusive jurisdiction of the
63
+ state and federal courts located in San Francisco County, California to
64
+ adjudicate any dispute arising out of or relating to these Terms of Use and
65
+ the download, installation, and/or use of the Software. Except as expressly
66
+ stated herein, these Terms of Use constitute the entire agreement between
67
+ the parties, and supersede all prior and contemporaneous agreements,
68
+ proposals, or representations, written or oral, concerning their subject
69
+ matter. No modification, amendment, or waiver of any provision of these
70
+ Terms of Use shall be effective unless it is by an update to these Terms of
71
+ Use that Salesforce makes available, or is in writing and signed by the
72
+ party against whom the modification, amendment, or waiver is to be
73
+ asserted.
74
+
75
+ Data Privacy: Salesforce may collect, process, and store device,
76
+ system, and other information related to your use of the Software. This
77
+ information includes, but is not limited to, IP address, user metrics, and
78
+ other data ("Usage Data"). Salesforce may use Usage Data for analytics,
79
+ product development, and marketing purposes. You acknowledge that files
80
+ generated in conjunction with the Software may contain sensitive or
81
+ confidential data, and you are solely responsible for anonymizing and
82
+ protecting such data.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # @salesforce/ui-bundle-external-service-codegen
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Generates typed clients for External Services published to a Salesforce org, from each service's OpenAPI spec (`api-spec.yaml`). A UI Bundle then calls a service as an ordinary typed function, with no action-name strings, `body` wrappers or hand-written response types.
4
+
5
+ It is a separate, opt-in package: only bundles that call External Services install it. It's a CLI plus a Node API, and its output is plain TypeScript, so it adds nothing to your build setup. Calls go through `@salesforce/external-service-sdk`.
6
+
7
+ ## Install
8
+
9
+ ```
10
+ npm install @salesforce/ui-bundle-external-service-codegen
11
+ ```
12
+
13
+ Install it as a regular dependency, not a dev dependency, because the UI imports its generated clients. `@salesforce/external-service-sdk` and `@salesforce/platform-sdk` are peer dependencies.
14
+
15
+ ## Use
16
+
17
+ 1. Put each service in the project, next to the bundles (or give an explicit spec path, see Options):
18
+ ```
19
+ force-app/main/default/
20
+ ├── uiBundles/invoiceApp/
21
+ │ └── package.json
22
+ └── compute/
23
+ ├── InvoiceParser/
24
+ │ └── api-spec.yaml
25
+ └── ShippingRates/
26
+ └── api-spec.yaml
27
+ ```
28
+ Every `compute/<Name>/` folder with an `api-spec.yaml` (or `.yml`, `.json`) in the package directories listed in `sfdx-project.json` gets a client. No list is needed.
29
+ 2. Run the generator before dev and build, in the bundle's `package.json`:
30
+ ```json
31
+ "scripts": {
32
+ "codegen": "ui-bundle-external-service-codegen",
33
+ "prebuild": "ui-bundle-external-service-codegen",
34
+ "predev": "ui-bundle-external-service-codegen",
35
+ "postinstall": "ui-bundle-external-service-codegen"
36
+ }
37
+ ```
38
+ That's the only setup. There's no tsconfig `paths` entry, bundler alias, plugin or `package.json` `imports` entry: the clients resolve through this package's own `exports`, like any npm package.
39
+ 3. Call the service:
40
+
41
+ ```ts
42
+ import { parseInvoice } from "@salesforce/ui-bundle-external-service-codegen/InvoiceParser";
43
+ import { isExternalServiceError } from "@salesforce/ui-bundle-external-service-codegen";
44
+
45
+ try {
46
+ const result = await parseInvoice({ opportunityId, pdfBase64, filename });
47
+ } catch (e) {
48
+ if (isExternalServiceError(e) && e.status === 409) {
49
+ /* already parsed */
50
+ }
51
+ }
52
+ ```
53
+
54
+ Failures throw `ExternalServiceError` (`kind`, `status`, `body`), the same error as calling `sdk.ext.externalService.invoke({ actionName, input })`. Check it with `isExternalServiceError`. `instanceof` does not see errors thrown by `@salesforce/external-service-sdk`.
55
+
56
+ 4. Optional: replace the transport once at app start. The default calls `@salesforce/external-service-sdk`.
57
+
58
+ ```ts
59
+ import { setTransport, dataSdkTransport } from "@salesforce/ui-bundle-external-service-codegen";
60
+
61
+ setTransport(dataSdkTransport()); // or your own (service, action, input) => response body
62
+ ```
63
+
64
+ A custom transport returns the service's response body and throws `ExternalServiceError` on failure.
65
+
66
+ ## Package entry points
67
+
68
+ | Import | What |
69
+ | -------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
70
+ | `@salesforce/ui-bundle-external-service-codegen/<ServiceName>` | The generated client: named types per schema, one async function per operation, an error-status union per operation, `ExternalServiceError` |
71
+ | `@salesforce/ui-bundle-external-service-codegen` | The runtime, shipped with the package: `ExternalServiceError`, `setTransport`, `dataSdkTransport`, `Transport` |
72
+ | `@salesforce/ui-bundle-external-service-codegen/codegen` | The Node API the CLI uses (`loadConfig`, `generate`), for bundler plugins or scripts |
73
+
74
+ ## Output
75
+
76
+ The generator writes plain JavaScript plus `.d.ts` into the installed package's `generated/` folder (`node_modules/@salesforce/ui-bundle-external-service-codegen/generated/`), the way Prisma generates `@prisma/client`:
77
+
78
+ | File | Contents |
79
+ | --------------------------- | ----------------------------------------------- |
80
+ | `<ServiceName>.js` | One function per operation, calling the runtime |
81
+ | `<ServiceName>.d.ts` | Types and JSDoc for the client |
82
+ | `<ServiceName>.schema.d.ts` | Raw types from `openapi-typescript` |
83
+
84
+ - Nothing is written into the bundle's source, so nothing is checked in. `postinstall`, `predev` and `prebuild` regenerate it after every install and before every run.
85
+ - The generated output ends up in `dist/` only through the bundler, like any dependency.
86
+ - When a client changes, the generator deletes `node_modules/.vite`, because Vite pre-bundles dependencies and doesn't notice changed package contents. Restart the dev server after a spec change.
87
+
88
+ ## How it works
89
+
90
+ 1. Finds the services: every `compute/<Name>/` with a spec, unless `package.json` `"externalServiceCodegen.services"` (or `ui-bundle.json` `"compute"`) lists them.
91
+ 2. Uses each one's `compute/<Name>/api-spec.yaml`, or an explicit spec path.
92
+ 3. Parses the spec. `openapi-typescript` turns the schemas into `<ServiceName>.schema.d.ts`. `required` controls `?`, and `nullable` adds `| null`.
93
+ 4. For each operation (`src/mapping.js`):
94
+ - `operationId` becomes the function name (camelCase) and the action name;
95
+ - the request body's schema becomes the parameter type;
96
+ - the first 2xx response's schema becomes the return type;
97
+ - the other status codes become an error-status union.
98
+ 5. Writes only files whose content changed, and removes clients for services that are gone. The header holds the spec path and a hash; `--check` compares instead of writing. The CLI prints where it wrote and the import path for each service.
99
+
100
+ ## Options (`package.json` → `"externalServiceCodegen"`)
101
+
102
+ | Key | Default | Purpose |
103
+ | ---------- | ----------------------------------- | --------------------------------------------------------------------------------------- |
104
+ | `services` | every `compute/<Name>/` with a spec | Limit to a list of names, or `{ "<Name>": "<spec path>" }` for services in another repo |
105
+ | `inputKey` | `body` | `schemaName` sends `body_<SchemaName>` |
106
+
107
+ ## CLI
108
+
109
+ ```
110
+ ui-bundle-external-service-codegen [--root <bundleDir>] [--service <Name>]... [--check] [--watch]
111
+ ```
112
+
113
+ `--check` writes nothing and exits 1 if any generated file is missing or stale. Use it in CI.
114
+
115
+ ## Limitations
116
+
117
+ - Operations with path or query parameters are skipped, and listed in the generated file.
118
+ - Only `application/json` bodies.
119
+ - The action name is the `operationId` as written, and the request is sent under the `body` key.
120
+ - Reads the local spec only. Nothing checks it against the spec published in the org, so re-publish after every spec change.
121
+ - If a monorepo hoists the package to a shared `node_modules`, every bundle writes into the same `generated/` folder. Two bundles with different specs under the same service name would collide.
122
+ - Bundler persistent caches may treat `node_modules` as immutable. A dev server restart (or a cache clear) picks up regenerated clients.
123
+
124
+ ## Test
125
+
126
+ ```
127
+ npm test
128
+ ```
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@salesforce/ui-bundle-external-service-codegen",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "12.13.0",
4
+ "description": "Generates typed clients for External Services published to a Salesforce org, from each service's OpenAPI spec, so a UI Bundle calls them as ordinary typed functions.",
5
+ "license": "SEE LICENSE IN LICENSE.txt",
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./runtime/index.d.ts",
10
+ "default": "./runtime/index.js"
11
+ },
12
+ "./codegen": {
13
+ "types": "./src/index.d.ts",
14
+ "default": "./src/index.js"
15
+ },
16
+ "./package.json": "./package.json",
17
+ "./*": {
18
+ "types": "./generated/*.d.ts",
19
+ "default": "./generated/*.js"
20
+ }
21
+ },
22
+ "bin": {
23
+ "ui-bundle-external-service-codegen": "./src/cli.js"
24
+ },
25
+ "files": [
26
+ "src",
27
+ "runtime"
28
+ ],
29
+ "scripts": {
30
+ "build": "mkdir -p dist",
31
+ "clean": "rm -rf generated",
32
+ "test": "node --test test/*.test.js"
33
+ },
34
+ "dependencies": {
35
+ "openapi-typescript": "^7.13.0",
36
+ "yaml": "^2.9.1"
37
+ },
38
+ "peerDependencies": {
39
+ "@salesforce/platform-sdk": "^13.3.0",
40
+ "@salesforce/external-service-sdk": "^13.3.0"
41
+ },
42
+ "devDependencies": {
43
+ "@salesforce/platform-sdk": "^13.3.0",
44
+ "@salesforce/external-service-sdk": "^13.3.0",
45
+ "typescript": "^5.9.3"
46
+ },
47
+ "engines": {
48
+ "node": ">=22"
49
+ },
50
+ "publishConfig": {
51
+ "access": "public"
52
+ }
53
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ export class ExternalServiceError extends Error {
8
+ name: "ExternalServiceError";
9
+ kind: string;
10
+ action: string;
11
+ status?: number;
12
+ body?: unknown;
13
+ constructor(args: {
14
+ kind: string;
15
+ action: string;
16
+ message: string;
17
+ status?: number;
18
+ body?: unknown;
19
+ });
20
+ }
21
+
22
+ /** Matches errors from this runtime and from @salesforce/external-service-sdk. */
23
+ export function isExternalServiceError(error: unknown): error is ExternalServiceError;
24
+
25
+ /**
26
+ * Sends one External Service action and returns the service's response body.
27
+ * Throw an `ExternalServiceError` for any failure so callers see one error type.
28
+ */
29
+ export type Transport = (
30
+ service: string,
31
+ action: string,
32
+ input: Record<string, unknown>,
33
+ ) => Promise<unknown>;
34
+
35
+ /**
36
+ * The default transport. Calls `@salesforce/external-service-sdk` as
37
+ * `invoke({ actionName: "Service.Action", input })`. The action URL version is
38
+ * pinned by that package.
39
+ */
40
+ export declare function dataSdkTransport(): Transport;
41
+
42
+ /** Replaces the transport for every generated client. Call once at app start. */
43
+ export declare function setTransport(transport: Transport): void;
44
+
45
+ /** Used by the generated clients. */
46
+ export declare function invoke<T>(
47
+ service: string,
48
+ action: string,
49
+ input: Record<string, unknown>,
50
+ ): Promise<T>;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ // Browser runtime shared by every generated client. It sends each call through
8
+ // the transport (by default @salesforce/external-service-sdk) and lets that
9
+ // SDK's ExternalServiceError propagate unchanged.
10
+
11
+ export class ExternalServiceError extends Error {
12
+ /**
13
+ * @param {{ kind: string, action: string, message: string, status?: number, body?: unknown }} args
14
+ */
15
+ constructor({ kind, action, message, status, body }) {
16
+ super(`External Service action ${action} failed (${kind}): ${message}`);
17
+ this.name = "ExternalServiceError";
18
+ this.kind = kind;
19
+ this.action = action;
20
+ this.status = status;
21
+ this.body = body;
22
+ }
23
+ }
24
+
25
+ /** Matches errors from this runtime and from @salesforce/external-service-sdk. */
26
+ export function isExternalServiceError(error) {
27
+ if (error === null || typeof error !== "object") return false;
28
+ return (
29
+ error.name === "ExternalServiceError" &&
30
+ typeof error.kind === "string" &&
31
+ typeof error.action === "string"
32
+ );
33
+ }
34
+
35
+ export function dataSdkTransport() {
36
+ let sdk;
37
+ return async (service, action, input) => {
38
+ const { createDataSDK } = await import("@salesforce/platform-sdk");
39
+ const { externalService } = await import("@salesforce/external-service-sdk");
40
+ const { invoke } = await import("@salesforce/external-service-sdk/invoke");
41
+ sdk ??= createDataSDK({
42
+ extensions: [externalService({ invoke })],
43
+ });
44
+ const call = (await sdk).ext.externalService.invoke;
45
+ if (!call) {
46
+ throw new ExternalServiceError({
47
+ kind: "transport",
48
+ action: `${service}.${action}`,
49
+ message: "externalService.invoke is unavailable on this surface",
50
+ });
51
+ }
52
+ return call({ actionName: `${service}.${action}`, input });
53
+ };
54
+ }
55
+
56
+ let transport = dataSdkTransport();
57
+
58
+ export function setTransport(next) {
59
+ transport = next;
60
+ }
61
+
62
+ export function invoke(service, action, input) {
63
+ return transport(service, action, input);
64
+ }
package/src/cli.js ADDED
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) 2026, Salesforce, Inc.,
4
+ * All rights reserved.
5
+ * For full license text, see the LICENSE.txt file
6
+ */
7
+
8
+ // ui-bundle-external-service-codegen [--root <bundleDir>] [--service <Name>]... [--check] [--watch]
9
+
10
+ import { watch } from "node:fs";
11
+ import path from "node:path";
12
+ import { parseArgs } from "node:util";
13
+ import { generate, loadConfig } from "./index.js";
14
+
15
+ const { values } = parseArgs({
16
+ options: {
17
+ root: { type: "string", default: process.cwd() },
18
+ service: { type: "string", multiple: true },
19
+ check: { type: "boolean", default: false },
20
+ watch: { type: "boolean", default: false },
21
+ help: { type: "boolean", short: "h", default: false },
22
+ },
23
+ });
24
+
25
+ if (values.help) {
26
+ console.log(`Usage: ui-bundle-external-service-codegen [options]
27
+
28
+ Generates typed clients for the External Services a UI Bundle calls, from each
29
+ service's api-spec.yaml. Import them as @salesforce/ui-bundle-external-service-codegen/<Name>.
30
+
31
+ By default, every compute/<Name>/ folder with an api-spec.yaml in the sfdx
32
+ project's package directories is generated. To limit or extend that, list
33
+ services in package.json "externalServiceCodegen.services" (or ui-bundle.json "compute"):
34
+ a name resolves to compute/<Name>/; an object entry maps a name to a spec path.
35
+
36
+ Clients are written into the installed package
37
+ (node_modules/@salesforce/ui-bundle-external-service-codegen/generated/).
38
+
39
+ Options:
40
+ --root <dir> UI Bundle directory (default: current directory)
41
+ --service <name> Generate only this service (repeatable)
42
+ --check Exit 1 if generated files are missing or stale; write nothing
43
+ --watch Regenerate when a spec changes
44
+ -h, --help Show this help`);
45
+ process.exit(0);
46
+ }
47
+
48
+ const root = path.resolve(values.root);
49
+ const rel = (f) => path.relative(root, f);
50
+
51
+ async function run(only) {
52
+ const config = await loadConfig(root);
53
+ if (Object.keys(config.services).length === 0) {
54
+ console.log(
55
+ "ui-bundle-external-service-codegen: no compute/<Name>/api-spec.yaml found and no services declared; nothing to do",
56
+ );
57
+ return { specs: {}, ok: true };
58
+ }
59
+ const { results, specs, skipped } = await generate(config, {
60
+ check: values.check,
61
+ only: only ?? values.service,
62
+ });
63
+ const names = only ?? values.service ?? Object.keys(config.services);
64
+ console.log(
65
+ `ui-bundle-external-service-codegen: ${names.length} service(s)${config.discoveredAll ? " found in compute/" : ""} -> ${rel(config.outDir)}`,
66
+ );
67
+ for (const name of names)
68
+ console.log(
69
+ ` ${name.padEnd(20)} ${rel(specs[name])} => import from '@salesforce/ui-bundle-external-service-codegen/${name}'`,
70
+ );
71
+ for (const { file, status } of results)
72
+ if (status !== "unchanged") console.log(` ${status.padEnd(9)} ${rel(file)}`);
73
+ for (const [service, ops] of Object.entries(skipped)) {
74
+ for (const s of ops) console.warn(` skipped ${service} ${s.where}: ${s.reason}`);
75
+ }
76
+ const stale = results.filter((r) => r.status === "stale");
77
+ if (stale.length)
78
+ console.error(
79
+ `ui-bundle-external-service-codegen: ${stale.length} generated file(s) out of date; run without --check`,
80
+ );
81
+ return { specs, ok: stale.length === 0 };
82
+ }
83
+
84
+ try {
85
+ const { specs, ok } = await run();
86
+ if (!values.watch) process.exit(ok ? 0 : 1);
87
+
88
+ console.log("ui-bundle-external-service-codegen: watching specs");
89
+ for (const [service, specPath] of Object.entries(specs)) {
90
+ let timer;
91
+ watch(specPath, () => {
92
+ clearTimeout(timer);
93
+ timer = setTimeout(
94
+ () =>
95
+ run([service]).catch((e) =>
96
+ console.error(`ui-bundle-external-service-codegen: ${e.message}`),
97
+ ),
98
+ 100,
99
+ );
100
+ });
101
+ }
102
+ } catch (e) {
103
+ console.error(`ui-bundle-external-service-codegen: ${e.message}`);
104
+ process.exit(1);
105
+ }
package/src/emit.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ // Emits plain JavaScript plus .d.ts, with no framework or bundler dependency.
8
+ // The generated code imports only the package's own runtime (../runtime).
9
+
10
+ import { createHash } from "node:crypto";
11
+ import openapiTS, { astToString } from "openapi-typescript";
12
+ import { mapOperations } from "./mapping.js";
13
+
14
+ const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
15
+ const RESERVED = new Set(["invoke", "components", "operations", "paths"]);
16
+
17
+ /** @param {string} text */
18
+ export function hash(text) {
19
+ return createHash("sha256").update(text).digest("hex").slice(0, 16);
20
+ }
21
+
22
+ /** @param {Array<string | undefined>} lines @param {string} [indent] */
23
+ function jsdoc(lines, indent = "") {
24
+ const body = lines.filter((l) => l !== undefined).flatMap((l) => l.trimEnd().split("\n"));
25
+ if (body.length === 0) return "";
26
+ return `${indent}/**\n${body.map((l) => `${indent} * ${l}`.trimEnd()).join("\n")}\n${indent} */\n`;
27
+ }
28
+
29
+ /**
30
+ * @param {object} args
31
+ * @param {string} args.serviceName External Service name, e.g. InvoiceParser
32
+ * @param {Record<string, any>} args.spec parsed OpenAPI document
33
+ * @param {string} args.specText raw spec text, hashed into the header
34
+ * @param {string} args.specLabel path shown in the header
35
+ * @param {import('./mapping.js').defaultRules} [args.rules]
36
+ * @returns {Promise<{ files: Record<string, string>, skipped: Array<object> }>}
37
+ */
38
+ export async function emitService({ serviceName, spec, specText, specLabel, rules }) {
39
+ const header =
40
+ `// @generated by ui-bundle-external-service-codegen from ${specLabel}. Do not edit.\n` +
41
+ `// spec-sha256: ${hash(specText)}\n`;
42
+
43
+ const schemaTs = astToString(await openapiTS(structuredClone(spec), { alphabetize: false }));
44
+ const { operations, skipped } = mapOperations(spec, rules);
45
+
46
+ const schemaNames = Object.keys(spec.components?.schemas ?? {}).filter(
47
+ (n) => IDENTIFIER.test(n) && !RESERVED.has(n),
48
+ );
49
+ const fnNames = new Set(operations.map((o) => o.functionName));
50
+ const aliasNames = schemaNames.filter((n) => !fnNames.has(n));
51
+
52
+ const uses = { components: aliasNames.length > 0, operations: false };
53
+ const typeOf = (schemaName, inlineExpr) => {
54
+ if (schemaName && aliasNames.includes(schemaName)) return schemaName;
55
+ uses.operations = true;
56
+ return inlineExpr;
57
+ };
58
+
59
+ const decls = [];
60
+ const fns = [];
61
+ for (const op of operations) {
62
+ const opRef = `operations[${JSON.stringify(op.operationId)}]`;
63
+ const requestType = op.request
64
+ ? typeOf(
65
+ op.request.schemaName,
66
+ `NonNullable<${opRef}['requestBody']>['content']['application/json']`,
67
+ )
68
+ : undefined;
69
+ const responseType = op.success?.hasBody
70
+ ? typeOf(
71
+ op.success.schemaName,
72
+ `${opRef}['responses'][${op.success.status}]['content']['application/json']`,
73
+ )
74
+ : "void";
75
+ const errorType = `${op.operationId[0].toUpperCase()}${op.operationId.slice(1)}ErrorStatus`;
76
+ const errorUnion = op.errors.length ? op.errors.map((e) => e.status).join(" | ") : "never";
77
+ const doc = jsdoc([
78
+ op.description,
79
+ ...op.errors.map(
80
+ (e) =>
81
+ `@throws ExternalServiceError with status ${e.status}${e.description ? `: ${e.description.trim()}` : ""}`,
82
+ ),
83
+ op.deprecated ? "@deprecated" : undefined,
84
+ ]);
85
+
86
+ decls.push(
87
+ `/** Error statuses the service declares for ${op.operationId}. */\n` +
88
+ `export type ${errorType} = ${errorUnion};\n\n` +
89
+ doc +
90
+ `export declare function ${op.functionName}(${requestType ? `request${op.request.required ? "" : "?"}: ${requestType}` : ""}): Promise<${responseType}>;\n`,
91
+ );
92
+ fns.push(
93
+ `export function ${op.functionName}(${requestType ? "request" : ""}) {\n` +
94
+ ` return invoke(SERVICE, ${JSON.stringify(op.actionName)}, ${requestType ? `{ ${JSON.stringify(op.inputKey)}: request }` : "{}"});\n` +
95
+ `}\n`,
96
+ );
97
+ }
98
+
99
+ const notGenerated = skipped.length
100
+ ? `\n// Not generated:\n${skipped.map((s) => `// ${s.where}${s.operationId ? ` (${s.operationId})` : ""}: ${s.reason}`).join("\n")}\n`
101
+ : "";
102
+ const typeImports = [uses.components && "components", uses.operations && "operations"].filter(
103
+ Boolean,
104
+ );
105
+ const serviceDts =
106
+ header +
107
+ `\n` +
108
+ (typeImports.length
109
+ ? `import type { ${typeImports.join(", ")} } from './${serviceName}.schema.js';\n\n`
110
+ : "") +
111
+ `export { ExternalServiceError } from '../runtime/index.js';\n\n` +
112
+ (aliasNames.length
113
+ ? aliasNames.map((n) => `export type ${n} = components['schemas']['${n}'];`).join("\n") +
114
+ "\n\n"
115
+ : "") +
116
+ decls.join("\n") +
117
+ notGenerated;
118
+ const serviceJs =
119
+ header +
120
+ `\n` +
121
+ `import { invoke } from '../runtime/index.js';\n\n` +
122
+ `export { ExternalServiceError } from '../runtime/index.js';\n\n` +
123
+ `const SERVICE = ${JSON.stringify(serviceName)};\n\n` +
124
+ fns.join("\n");
125
+
126
+ return {
127
+ files: {
128
+ [`${serviceName}.schema.d.ts`]: header + "\n" + schemaTs,
129
+ [`${serviceName}.d.ts`]: serviceDts,
130
+ [`${serviceName}.js`]: serviceJs,
131
+ },
132
+ skipped,
133
+ };
134
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ export const PACKAGE_NAME: string;
8
+
9
+ export interface Rules {
10
+ /** Invocable action name for an operation. Default: the operationId as written. */
11
+ actionName?: (op: { operationId: string; method: string; route: string }) => string;
12
+ /** `body` (default) or `body_<SchemaName>`. */
13
+ inputKey?: "body" | "schemaName";
14
+ }
15
+
16
+ export interface Config {
17
+ root: string;
18
+ /** `generated/` in the copy of this package the bundle resolves. */
19
+ outDir: string;
20
+ /** Service name -> spec path (undefined if a declared service has no compute/<Name>/ folder). */
21
+ services: Record<string, string | undefined>;
22
+ /** True when no service list is declared and every compute/<Name>/ folder is used. */
23
+ discoveredAll: boolean;
24
+ rules?: Rules;
25
+ }
26
+
27
+ export type FileStatus = "written" | "unchanged" | "stale" | "removed";
28
+
29
+ export function loadConfig(root: string): Promise<Config>;
30
+ export function resolveSpec(config: Config, serviceName: string): Promise<string>;
31
+ export function generate(
32
+ config: Config,
33
+ options?: { check?: boolean; only?: string[] },
34
+ ): Promise<{
35
+ results: { file: string; status: FileStatus }[];
36
+ specs: Record<string, string>;
37
+ skipped: Record<string, { where: string; operationId?: string; reason: string }[]>;
38
+ }>;
39
+
40
+ export function toFunctionName(operationId: string): string;
41
+ export function mapOperations(
42
+ spec: Record<string, unknown>,
43
+ rules?: Rules,
44
+ ): { operations: unknown[]; skipped: unknown[] };
45
+ export function emitService(args: {
46
+ serviceName: string;
47
+ spec: Record<string, unknown>;
48
+ specText: string;
49
+ specLabel: string;
50
+ rules?: Rules;
51
+ }): Promise<{ files: Record<string, string>; skipped: unknown[] }>;
package/src/index.js ADDED
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ // Finds the services a UI Bundle calls, resolves each one's api-spec.yaml and
8
+ // writes the generated clients into this package's `generated/` folder, so the
9
+ // UI imports `@salesforce/ui-bundle-external-service-codegen/<ServiceName>` through the
10
+ // package's own "exports" and no bundler or tsconfig setup is needed.
11
+
12
+ import { existsSync } from "node:fs";
13
+ import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";
14
+ import { createRequire } from "node:module";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import YAML from "yaml";
18
+ import { emitService } from "./emit.js";
19
+
20
+ export { mapOperations, toFunctionName } from "./mapping.js";
21
+ export { emitService } from "./emit.js";
22
+
23
+ export const PACKAGE_NAME = "@salesforce/ui-bundle-external-service-codegen";
24
+ const SPEC_FILES = ["api-spec.yaml", "api-spec.yml", "api-spec.json"];
25
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", ".sf", ".sfdx"]);
26
+
27
+ async function readJson(file) {
28
+ return existsSync(file) ? JSON.parse(await readFile(file, "utf8")) : undefined;
29
+ }
30
+
31
+ /**
32
+ * Reads options from `package.json` "externalServiceCodegen". Without a service list
33
+ * (`externalServiceCodegen.services` or `ui-bundle.json` "compute"), every
34
+ * `compute/<Name>/` folder with a spec in the project's package directories is used.
35
+ *
36
+ * @param {string} root UI Bundle directory
37
+ */
38
+ export async function loadConfig(root) {
39
+ const pkg = (await readJson(path.join(root, "package.json"))) ?? {};
40
+ const uiBundle = (await readJson(path.join(root, "ui-bundle.json"))) ?? {};
41
+ const own = pkg.externalServiceCodegen ?? {};
42
+ const declared = own.services ?? uiBundle.compute;
43
+ const discovered = await discoverServices(root);
44
+ // Array form: names, resolved from compute/<Name>/. Object form: name -> spec path.
45
+ const services =
46
+ declared === undefined
47
+ ? discovered
48
+ : Array.isArray(declared)
49
+ ? Object.fromEntries(declared.map((n) => [n, discovered[n]]))
50
+ : Object.fromEntries(Object.entries(declared).map(([n, p]) => [n, path.resolve(root, p)]));
51
+ return {
52
+ root,
53
+ outDir: path.join(installedPackageDir(root), "generated"),
54
+ services,
55
+ discoveredAll: declared === undefined,
56
+ rules: own.inputKey ? { inputKey: own.inputKey } : undefined,
57
+ };
58
+ }
59
+
60
+ // The copy of this package the bundle's imports resolve to; this one if the bundle has none.
61
+ function installedPackageDir(root) {
62
+ try {
63
+ return path.dirname(
64
+ createRequire(path.join(root, "package.json")).resolve(`${PACKAGE_NAME}/package.json`),
65
+ );
66
+ } catch {
67
+ return path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
68
+ }
69
+ }
70
+
71
+ function findUp(start, file) {
72
+ for (let dir = start; ; dir = path.dirname(dir)) {
73
+ if (existsSync(path.join(dir, file))) return dir;
74
+ if (path.dirname(dir) === dir) return undefined;
75
+ }
76
+ }
77
+
78
+ // Every compute/<Name>/ folder that holds a spec, across the package directories in sfdx-project.json.
79
+ async function discoverServices(root) {
80
+ const projectDir = findUp(root, "sfdx-project.json");
81
+ if (!projectDir) return {};
82
+ const project = await readJson(path.join(projectDir, "sfdx-project.json"));
83
+ const found = {};
84
+ const walk = async (dir, depth) => {
85
+ if (depth > 6) return;
86
+ for (const e of await readdir(dir, { withFileTypes: true }).catch(() => [])) {
87
+ if (!e.isDirectory() || SKIP_DIRS.has(e.name)) continue;
88
+ const child = path.join(dir, e.name);
89
+ if (e.name !== "compute") {
90
+ await walk(child, depth + 1);
91
+ continue;
92
+ }
93
+ for (const svc of await readdir(child, { withFileTypes: true })) {
94
+ const spec =
95
+ svc.isDirectory() &&
96
+ SPEC_FILES.map((f) => path.join(child, svc.name, f)).find(existsSync);
97
+ if (spec) found[svc.name] ??= spec;
98
+ }
99
+ }
100
+ };
101
+ for (const pkgDir of project.packageDirectories ?? [])
102
+ await walk(path.join(projectDir, pkgDir.path), 0);
103
+ return found;
104
+ }
105
+
106
+ /** The spec path for a service: explicit, or found under compute/<ServiceName>/. */
107
+ export async function resolveSpec(config, serviceName) {
108
+ const spec = config.services[serviceName];
109
+ if (spec) return spec;
110
+ throw new Error(
111
+ `${serviceName}: no compute/${serviceName}/api-spec.yaml in the package directories of the sfdx project above ${config.root}; give the spec path in package.json "externalServiceCodegen.services"`,
112
+ );
113
+ }
114
+
115
+ async function writeIfChanged(file, content, check) {
116
+ const current = existsSync(file) ? await readFile(file, "utf8") : undefined;
117
+ if (current === content) return "unchanged";
118
+ if (check) return "stale";
119
+ await mkdir(path.dirname(file), { recursive: true });
120
+ await writeFile(file, content);
121
+ return "written";
122
+ }
123
+
124
+ /**
125
+ * Generates one service, or all of them when `only` is omitted.
126
+ *
127
+ * @param {Awaited<ReturnType<typeof loadConfig>>} config
128
+ * @param {{ check?: boolean, only?: string[] }} [options] `check` reports stale files without writing
129
+ * @returns {Promise<{ results: Array<{ file: string, status: 'written' | 'unchanged' | 'stale' }>, specs: Record<string, string>, skipped: Record<string, object[]> }>}
130
+ */
131
+ export async function generate(config, { check = false, only } = {}) {
132
+ const results = [];
133
+ const specs = {};
134
+ const skipped = {};
135
+ const record = async (file, content) =>
136
+ results.push({ file, status: await writeIfChanged(file, content, check) });
137
+
138
+ for (const serviceName of only ?? Object.keys(config.services)) {
139
+ const specPath = await resolveSpec(config, serviceName);
140
+ const specText = await readFile(specPath, "utf8");
141
+ const spec = specPath.endsWith(".json") ? JSON.parse(specText) : YAML.parse(specText);
142
+ const out = await emitService({
143
+ serviceName,
144
+ spec,
145
+ specText,
146
+ specLabel: path.relative(config.root, specPath).split(path.sep).join("/"),
147
+ rules: config.rules,
148
+ });
149
+ specs[serviceName] = specPath;
150
+ if (out.skipped.length) skipped[serviceName] = out.skipped;
151
+ for (const [name, content] of Object.entries(out.files))
152
+ await record(path.join(config.outDir, name), content);
153
+ }
154
+ // On a full run, drop clients for services that are gone.
155
+ if (!only) {
156
+ const keep = new Set(results.map((r) => path.basename(r.file)));
157
+ for (const f of await readdir(config.outDir).catch(() => [])) {
158
+ if (keep.has(f)) continue;
159
+ results.push({ file: path.join(config.outDir, f), status: check ? "stale" : "removed" });
160
+ if (!check) await rm(path.join(config.outDir, f), { force: true });
161
+ }
162
+ }
163
+ // Vite pre-bundles node_modules into node_modules/.vite and doesn't notice changed
164
+ // package contents, so drop that cache when a client changes.
165
+ if (results.some((r) => r.status === "written" || r.status === "removed"))
166
+ await rm(path.join(config.root, "node_modules/.vite"), { recursive: true, force: true });
167
+ return { results, specs, skipped };
168
+ }
package/src/mapping.js ADDED
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Copyright (c) 2026, Salesforce, Inc.,
3
+ * All rights reserved.
4
+ * For full license text, see the LICENSE.txt file
5
+ */
6
+
7
+ // Maps OpenAPI operations to the External Services Invocable Action shape.
8
+ // This is the single place the request-key and action-name rules live, so
9
+ // they can change once AppLink confirms them without touching the emitter.
10
+
11
+ const HTTP_METHODS = ["get", "put", "post", "delete", "patch"];
12
+ const SCHEMA_REF = /^#\/components\/schemas\/([^/]+)$/;
13
+ // Not valid as an exported function name.
14
+ const RESERVED_WORDS = new Set(
15
+ "arguments await break case catch class const continue debugger default delete do else enum eval export extends false finally for function if implements import in instanceof interface let new null package private protected public return static super switch this throw true try typeof var void while with yield".split(
16
+ " ",
17
+ ),
18
+ );
19
+
20
+ /**
21
+ * @param {string} operationId
22
+ * @returns {string} camelCase function name, e.g. ParseInvoice -> parseInvoice
23
+ */
24
+ export function toFunctionName(operationId) {
25
+ const words = operationId.split(/[^A-Za-z0-9]+/).filter(Boolean);
26
+ const joined = words.map((w, i) => (i === 0 ? w : w[0].toUpperCase() + w.slice(1))).join("");
27
+ const name = joined[0].toLowerCase() + joined.slice(1);
28
+ return /^[0-9]/.test(name) || RESERVED_WORDS.has(name) ? `_${name}` : name;
29
+ }
30
+
31
+ /** @param {unknown} schema */
32
+ export function schemaRefName(schema) {
33
+ const ref = schema && typeof schema === "object" ? schema.$ref : undefined;
34
+ const match = typeof ref === "string" ? ref.match(SCHEMA_REF) : null;
35
+ return match ? match[1] : undefined;
36
+ }
37
+
38
+ /**
39
+ * Default rules for the External Services Invocable Action shape:
40
+ * the action name is the operationId as written, and the request body goes
41
+ * under `body`. Set `inputKey` to 'schemaName' for `body_<SchemaName>`.
42
+ */
43
+ export const defaultRules = {
44
+ actionName: (op) => op.operationId,
45
+ inputKey: "body",
46
+ };
47
+
48
+ /**
49
+ * @param {Record<string, any>} spec parsed OpenAPI 3.x document
50
+ * @param {{ actionName?: (op: { operationId: string }) => string, inputKey?: 'body' | 'schemaName' }} [rules]
51
+ */
52
+ export function mapOperations(spec, rules = {}) {
53
+ const { actionName, inputKey } = { ...defaultRules, ...rules };
54
+ const operations = [];
55
+ const skipped = [];
56
+
57
+ for (const [route, pathItem] of Object.entries(spec.paths ?? {})) {
58
+ for (const method of HTTP_METHODS) {
59
+ const op = pathItem?.[method];
60
+ if (!op) continue;
61
+ const where = `${method.toUpperCase()} ${route}`;
62
+ if (!op.operationId) {
63
+ skipped.push({ where, reason: "no operationId" });
64
+ continue;
65
+ }
66
+ const parameters = [...(pathItem.parameters ?? []), ...(op.parameters ?? [])];
67
+ if (parameters.length > 0) {
68
+ skipped.push({
69
+ where,
70
+ operationId: op.operationId,
71
+ reason: "path/query parameters are not supported yet",
72
+ });
73
+ continue;
74
+ }
75
+
76
+ const requestSchema = op.requestBody?.content?.["application/json"]?.schema;
77
+ const requestSchemaName = schemaRefName(requestSchema);
78
+ if (op.requestBody && !requestSchema) {
79
+ skipped.push({
80
+ where,
81
+ operationId: op.operationId,
82
+ reason: "request body is not application/json",
83
+ });
84
+ continue;
85
+ }
86
+
87
+ const statuses = Object.keys(op.responses ?? {}).filter((s) => /^\d{3}$/.test(s));
88
+ const successStatus = statuses.find((s) => s.startsWith("2"));
89
+ const successSchema = successStatus
90
+ ? op.responses[successStatus]?.content?.["application/json"]?.schema
91
+ : undefined;
92
+
93
+ const functionName = toFunctionName(op.operationId);
94
+ if (operations.some((o) => o.functionName === functionName)) {
95
+ skipped.push({
96
+ where,
97
+ operationId: op.operationId,
98
+ reason: `function name ${functionName} is already used by another operation`,
99
+ });
100
+ continue;
101
+ }
102
+
103
+ operations.push({
104
+ operationId: op.operationId,
105
+ functionName,
106
+ actionName: actionName({ operationId: op.operationId, method, route }),
107
+ inputKey: !requestSchema
108
+ ? undefined
109
+ : inputKey === "schemaName" && requestSchemaName
110
+ ? `body_${requestSchemaName}`
111
+ : "body",
112
+ description: op.description ?? op.summary,
113
+ deprecated: op.deprecated === true,
114
+ request: requestSchema
115
+ ? { schemaName: requestSchemaName, required: op.requestBody.required === true }
116
+ : undefined,
117
+ success: successStatus
118
+ ? {
119
+ status: Number(successStatus),
120
+ schemaName: schemaRefName(successSchema),
121
+ hasBody: !!successSchema,
122
+ }
123
+ : undefined,
124
+ errors: statuses
125
+ .filter((s) => !s.startsWith("2"))
126
+ .map((s) => ({ status: Number(s), description: op.responses[s]?.description })),
127
+ });
128
+ }
129
+ }
130
+ return { operations, skipped };
131
+ }