sf-plugin-data 0.0.0-stage → 0.1.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.
@@ -0,0 +1,67 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import type { DmoUpdatePatch } from '../artifacts/dmo-update-delta.js';
3
+ export type TransportErrorCode = 'INVALID_REQUEST' | 'AUTHENTICATION_FAILED' | 'REQUEST_FAILED' | 'INVALID_PAGE' | 'INCOMPLETE_LIST';
4
+ /** An intentionally payload-free diagnostic safe for JSON and console output. */
5
+ export declare class ConnectError extends Error {
6
+ readonly code: TransportErrorCode;
7
+ readonly statusCode?: number | undefined;
8
+ constructor(code: TransportErrorCode, statusCode?: number | undefined);
9
+ }
10
+ type AuthenticatedConnection = Pick<Connection, 'instanceUrl' | 'request'>;
11
+ /** Bounded SSOT transport; Salesforce core owns credentials. */
12
+ export declare class ConnectClient {
13
+ private readonly connection;
14
+ private readonly apiVersion;
15
+ private readonly origin;
16
+ private readonly prefix;
17
+ constructor(connection: AuthenticatedConnection, apiVersion: string);
18
+ /**
19
+ * Load existing Salesforce CLI authentication without exposing token fields.
20
+ * @param {string} aliasOrUsername Explicit existing org alias or username.
21
+ * @param {string} apiVersion Explicit version; endpoint support is checked by future adapters.
22
+ * @returns {Promise<ConnectClient>} An authenticated client, without making a resource request.
23
+ */
24
+ static create(aliasOrUsername: string, apiVersion: string): Promise<ConnectClient>;
25
+ /**
26
+ * Read a single SSOT response. Does not infer pagination or retry a failed call.
27
+ * @template T
28
+ * @param {string} path Root-relative SSOT path or same-origin absolute URL, with optional query.
29
+ * @returns {Promise<T>} The unmodified resource response; callers must validate its schema.
30
+ */
31
+ get<T = unknown>(path: string): Promise<T>;
32
+ /**
33
+ * Create one validated authored DMO at the fixed API65 endpoint, without retry or redirect.
34
+ * A per-call receiver masks JSforce's refresh delegate (which otherwise replays POST on 401).
35
+ * Never mutates the supplied connection or exposes a generic write route.
36
+ * @param {unknown} document Independently validated authored-only default-space document.
37
+ * @returns {Promise<unknown>} Untrusted response, never proof of successful creation.
38
+ */
39
+ createDataModelObject(document: unknown): Promise<unknown>;
40
+ /**
41
+ * Send one PATCH to an exact API65 DMO route without refresh, retry or redirect.
42
+ * Callers must qualify the patch and authorize execution independently; this is transport only.
43
+ * @param {string} dataModelObjectName Exact qualified DMO API name.
44
+ * @param {DmoUpdatePatch} patch Caller-qualified update payload, not validated here.
45
+ * @returns {Promise<unknown>} Untrusted response, never proof of a successful update.
46
+ */
47
+ patchDataModelObject(dataModelObjectName: string, patch: DmoUpdatePatch): Promise<unknown>;
48
+ private writeReceiver;
49
+ private read;
50
+ private send;
51
+ /**
52
+ * Read the offset-paginated DMO inventory, without projecting resource fields.
53
+ * A short page terminates the list; unsupported continuation shapes fail closed.
54
+ * @returns {Promise<Array<Record<string, unknown>>>} Complete raw DMO entries or an error, never a partial list.
55
+ */
56
+ listDataModelObjects(): Promise<Array<Record<string, unknown>>>;
57
+ /**
58
+ * Acquire raw incoming and outgoing relationships in one explicit data space.
59
+ * Pagination metadata must prove exhaustion; raw records are not portable artifacts.
60
+ * @param {string} dataModelObjectName Exact DMO API name, including any namespace.
61
+ * @param {string} dataSpace Exact server data-space name; never silently defaults.
62
+ * @returns {Promise<Array<Record<string, unknown>>>} Complete raw relationships or an error.
63
+ */
64
+ listDataModelObjectRelationships(dataModelObjectName: string, dataSpace: string): Promise<Array<Record<string, unknown>>>;
65
+ private safeUrl;
66
+ }
67
+ export {};
@@ -0,0 +1,306 @@
1
+ import { Org } from '@salesforce/core';
2
+ import { buildDmoCreateRequestFromDocument } from '../artifacts/dmo-document.js';
3
+ /** An intentionally payload-free diagnostic safe for JSON and console output. */
4
+ export class ConnectError extends Error {
5
+ code;
6
+ statusCode;
7
+ constructor(code, statusCode) {
8
+ super(code === 'AUTHENTICATION_FAILED'
9
+ ? 'Salesforce authentication failed.'
10
+ : 'Data360 request failed.');
11
+ this.code = code;
12
+ this.statusCode = statusCode;
13
+ this.name = 'ConnectError';
14
+ }
15
+ }
16
+ /** Bounded SSOT transport; Salesforce core owns credentials. */
17
+ export class ConnectClient {
18
+ connection;
19
+ apiVersion;
20
+ origin;
21
+ prefix;
22
+ constructor(connection, apiVersion) {
23
+ this.connection = connection;
24
+ this.apiVersion = apiVersion;
25
+ if (!/^\d{2,3}\.0$/u.test(apiVersion))
26
+ throw new ConnectError('INVALID_REQUEST');
27
+ try {
28
+ const instance = new URL(connection.instanceUrl);
29
+ if (instance.protocol !== 'https:' ||
30
+ instance.username ||
31
+ instance.password ||
32
+ instance.pathname !== '/' ||
33
+ instance.search ||
34
+ instance.hash)
35
+ throw new Error('Invalid origin');
36
+ this.origin = instance.origin;
37
+ }
38
+ catch {
39
+ throw new ConnectError('INVALID_REQUEST');
40
+ }
41
+ this.prefix = `/services/data/v${apiVersion}/ssot/`;
42
+ }
43
+ /**
44
+ * Load existing Salesforce CLI authentication without exposing token fields.
45
+ * @param {string} aliasOrUsername Explicit existing org alias or username.
46
+ * @param {string} apiVersion Explicit version; endpoint support is checked by future adapters.
47
+ * @returns {Promise<ConnectClient>} An authenticated client, without making a resource request.
48
+ */
49
+ static async create(aliasOrUsername, apiVersion) {
50
+ if (!aliasOrUsername.trim() || !/^\d{2,3}\.0$/u.test(apiVersion)) {
51
+ throw new ConnectError('INVALID_REQUEST');
52
+ }
53
+ try {
54
+ const org = await Org.create({ aliasOrUsername });
55
+ return new ConnectClient(org.getConnection(apiVersion), apiVersion);
56
+ }
57
+ catch {
58
+ throw new ConnectError('AUTHENTICATION_FAILED');
59
+ }
60
+ }
61
+ /**
62
+ * Read a single SSOT response. Does not infer pagination or retry a failed call.
63
+ * @template T
64
+ * @param {string} path Root-relative SSOT path or same-origin absolute URL, with optional query.
65
+ * @returns {Promise<T>} The unmodified resource response; callers must validate its schema.
66
+ */
67
+ async get(path) {
68
+ return this.read(path);
69
+ }
70
+ /**
71
+ * Create one validated authored DMO at the fixed API65 endpoint, without retry or redirect.
72
+ * A per-call receiver masks JSforce's refresh delegate (which otherwise replays POST on 401).
73
+ * Never mutates the supplied connection or exposes a generic write route.
74
+ * @param {unknown} document Independently validated authored-only default-space document.
75
+ * @returns {Promise<unknown>} Untrusted response, never proof of successful creation.
76
+ */
77
+ async createDataModelObject(document) {
78
+ if (this.apiVersion !== '65.0')
79
+ throw new ConnectError('INVALID_REQUEST');
80
+ const body = JSON.stringify(buildDmoCreateRequestFromDocument(document, 'default'));
81
+ return this.send({
82
+ method: 'POST',
83
+ url: this.safeUrl(`${this.prefix}data-model-objects`),
84
+ body,
85
+ headers: { 'content-type': 'application/json' },
86
+ }, this.writeReceiver());
87
+ }
88
+ /**
89
+ * Send one PATCH to an exact API65 DMO route without refresh, retry or redirect.
90
+ * Callers must qualify the patch and authorize execution independently; this is transport only.
91
+ * @param {string} dataModelObjectName Exact qualified DMO API name.
92
+ * @param {DmoUpdatePatch} patch Caller-qualified update payload, not validated here.
93
+ * @returns {Promise<unknown>} Untrusted response, never proof of a successful update.
94
+ */
95
+ async patchDataModelObject(dataModelObjectName, patch) {
96
+ if (this.apiVersion !== '65.0' || !/^[A-Za-z][A-Za-z0-9_]*__dlm$/u.test(dataModelObjectName))
97
+ throw new ConnectError('INVALID_REQUEST');
98
+ try {
99
+ return await this.send({
100
+ method: 'PATCH',
101
+ url: this.safeUrl(`${this.prefix}data-model-objects/${dataModelObjectName}`),
102
+ body: JSON.stringify(patch),
103
+ headers: { 'content-type': 'application/json' },
104
+ }, this.writeReceiver());
105
+ }
106
+ catch (error) {
107
+ if (error instanceof ConnectError)
108
+ throw error;
109
+ throw new ConnectError('INVALID_REQUEST');
110
+ }
111
+ }
112
+ writeReceiver() {
113
+ const receiver = Object.create(this.connection);
114
+ Object.defineProperty(receiver, '_refreshDelegate', { value: undefined });
115
+ return receiver;
116
+ }
117
+ async read(path, noContentResponse) {
118
+ return this.send({ method: 'GET', url: this.safeUrl(path) }, this.connection, noContentResponse);
119
+ }
120
+ async send(request, receiver, noContentResponse) {
121
+ try {
122
+ return await receiver.request(request,
123
+ // Core narrows options to JSON, but its JSforce transport supports a redirect guard.
124
+ {
125
+ noContentResponse,
126
+ retry: { maxRetries: 0 },
127
+ followRedirect: () => {
128
+ throw new ConnectError('INVALID_REQUEST');
129
+ },
130
+ });
131
+ }
132
+ catch (error) {
133
+ if (error instanceof ConnectError)
134
+ throw error;
135
+ const status = error && typeof error === 'object' && 'statusCode' in error ? error.statusCode : undefined;
136
+ const statusCode = typeof status === 'number' && Number.isInteger(status) && status >= 400 && status <= 599
137
+ ? status
138
+ : undefined;
139
+ const expired = error &&
140
+ typeof error === 'object' &&
141
+ 'name' in error &&
142
+ error.name === 'INVALID_SESSION_ID';
143
+ throw new ConnectError(statusCode === 401 || expired ? 'AUTHENTICATION_FAILED' : 'REQUEST_FAILED', statusCode);
144
+ }
145
+ }
146
+ /**
147
+ * Read the offset-paginated DMO inventory, without projecting resource fields.
148
+ * A short page terminates the list; unsupported continuation shapes fail closed.
149
+ * @returns {Promise<Array<Record<string, unknown>>>} Complete raw DMO entries or an error, never a partial list.
150
+ */
151
+ async listDataModelObjects() {
152
+ const result = [];
153
+ const identities = new Set();
154
+ const limit = 50;
155
+ // The official endpoint caps SOQL offsets at 2000. Never probe beyond it.
156
+ for (let offset = 0; offset <= 2000; offset += limit) {
157
+ const page = await this.get(`${this.prefix}data-model-objects?limit=${limit}&offset=${offset}&orderBy=ASC`);
158
+ if (!page || typeof page !== 'object' || Array.isArray(page)) {
159
+ throw new ConnectError('INVALID_PAGE');
160
+ }
161
+ const envelope = page;
162
+ if (!Array.isArray(envelope.dataModelObject) ||
163
+ envelope.dataModelObject.length > limit ||
164
+ // DMO pagination has no documented server-provided continuation URL/token.
165
+ ['nextPageUrl', 'nextPageToken'].some((key) => envelope[key] != undefined)) {
166
+ throw new ConnectError('INVALID_PAGE');
167
+ }
168
+ for (const entry of envelope.dataModelObject) {
169
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
170
+ throw new ConnectError('INVALID_PAGE');
171
+ }
172
+ const item = entry;
173
+ if (typeof item.name !== 'string' ||
174
+ !item.name.trim() ||
175
+ typeof item.dataSpaceName !== 'string' ||
176
+ !item.dataSpaceName.trim()) {
177
+ throw new ConnectError('INVALID_PAGE');
178
+ }
179
+ const identity = JSON.stringify([item.dataSpaceName, item.name]);
180
+ if (identities.has(identity))
181
+ throw new ConnectError('INCOMPLETE_LIST');
182
+ identities.add(identity);
183
+ result.push(item);
184
+ }
185
+ if (envelope.dataModelObject.length < limit)
186
+ return result;
187
+ }
188
+ // A full final permitted page cannot prove exhaustion, even if exactly full.
189
+ throw new ConnectError('INCOMPLETE_LIST');
190
+ }
191
+ /**
192
+ * Acquire raw incoming and outgoing relationships in one explicit data space.
193
+ * Pagination metadata must prove exhaustion; raw records are not portable artifacts.
194
+ * @param {string} dataModelObjectName Exact DMO API name, including any namespace.
195
+ * @param {string} dataSpace Exact server data-space name; never silently defaults.
196
+ * @returns {Promise<Array<Record<string, unknown>>>} Complete raw relationships or an error.
197
+ */
198
+ async listDataModelObjectRelationships(dataModelObjectName, dataSpace) {
199
+ if (Number(this.apiVersion) < 64 ||
200
+ !/^[A-Za-z][A-Za-z0-9_]*__dlm$/u.test(dataModelObjectName) ||
201
+ !/^[A-Za-z][A-Za-z0-9_]*$/u.test(dataSpace))
202
+ throw new ConnectError('INVALID_REQUEST');
203
+ const result = [];
204
+ const identities = new Set();
205
+ const limit = 20;
206
+ let total;
207
+ const envelopeKeys = new Set([
208
+ 'relationships',
209
+ 'count',
210
+ 'totalSize',
211
+ 'sortBy',
212
+ 'currentPageToken',
213
+ 'currentPageUrl',
214
+ 'nextPageToken',
215
+ 'nextPageUrl',
216
+ 'previousPageToken',
217
+ 'previousPageUrl',
218
+ ]);
219
+ // Local safety budget, not a claim about this endpoint's server offset ceiling.
220
+ for (let offset = 0; offset <= 2000; offset += limit) {
221
+ // JSforce substitutes this private sentinel only for HTTP 204, not malformed JSON.
222
+ const emptyResponse = Symbol('relationship-no-content');
223
+ const page = await this.read(`${this.prefix}data-model-objects/${dataModelObjectName}/relationships?dataspace=${dataSpace}&limit=${limit}&offset=${offset}&orderBy=ASC&sortBy=DeveloperName`, emptyResponse);
224
+ if (page === emptyResponse) {
225
+ if (offset === 0)
226
+ return [];
227
+ throw new ConnectError('INCOMPLETE_LIST');
228
+ }
229
+ if (!page || typeof page !== 'object' || Array.isArray(page))
230
+ throw new ConnectError('INVALID_PAGE');
231
+ const envelope = page;
232
+ if (Object.keys(envelope).some((key) => !envelopeKeys.has(key)) ||
233
+ !Array.isArray(envelope.relationships) ||
234
+ envelope.relationships.length > limit ||
235
+ (envelope.count !== undefined && envelope.count !== envelope.relationships.length) ||
236
+ !Number.isSafeInteger(envelope.totalSize) ||
237
+ envelope.totalSize < 0 ||
238
+ (envelope.sortBy != undefined && envelope.sortBy !== 'DeveloperName') ||
239
+ [...envelopeKeys].some((key) => (key.endsWith('Url') || key.endsWith('Token')) &&
240
+ envelope[key] != undefined &&
241
+ typeof envelope[key] !== 'string'))
242
+ throw new ConnectError('INVALID_PAGE');
243
+ if (total !== undefined && total !== envelope.totalSize)
244
+ throw new ConnectError('INCOMPLETE_LIST');
245
+ total = envelope.totalSize;
246
+ for (const entry of envelope.relationships) {
247
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
248
+ throw new ConnectError('INVALID_PAGE');
249
+ const item = entry;
250
+ const entities = [item.sourceObject, item.targetObject];
251
+ if (typeof item.name !== 'string' ||
252
+ !item.name.trim() ||
253
+ entities.some((entity) => !entity ||
254
+ typeof entity !== 'object' ||
255
+ Array.isArray(entity) ||
256
+ typeof entity.name !== 'string' ||
257
+ !entity.name) ||
258
+ !entities.some((entity) => entity.name === dataModelObjectName))
259
+ throw new ConnectError('INVALID_PAGE');
260
+ if (identities.has(item.name))
261
+ throw new ConnectError('INCOMPLETE_LIST');
262
+ identities.add(item.name);
263
+ // Preserve every field, including unfamiliar semantics, for later strict projection.
264
+ result.push(item);
265
+ }
266
+ if (result.length > total)
267
+ throw new ConnectError('INVALID_PAGE');
268
+ if (result.length === total) {
269
+ if (envelope.nextPageUrl || envelope.nextPageToken)
270
+ throw new ConnectError('INCOMPLETE_LIST');
271
+ return result;
272
+ }
273
+ if (envelope.relationships.length !== limit)
274
+ throw new ConnectError('INCOMPLETE_LIST');
275
+ // Response URLs can reference legacy routes/versions. Never follow them.
276
+ }
277
+ throw new ConnectError('INCOMPLETE_LIST');
278
+ }
279
+ safeUrl(path) {
280
+ // Reject normalization ambiguities before URL parsing, including nested encodings.
281
+ if (/[\\\s#\p{Cc}]/u.test(path) || /%(?:2e|2f|5c|25|0[0-9a-f]|1[0-9a-f]|7f)/iu.test(path)) {
282
+ throw new ConnectError('INVALID_REQUEST');
283
+ }
284
+ try {
285
+ const url = new URL(path, this.origin);
286
+ const rawPath = path.startsWith('https://') ? path.slice(path.indexOf('/', 8)) : path;
287
+ if (!(path.startsWith('/') && !path.startsWith('//')) && !path.startsWith(`${this.origin}/`))
288
+ throw new Error('Invalid URL');
289
+ if (url.origin !== this.origin ||
290
+ url.username ||
291
+ url.password ||
292
+ !url.pathname.startsWith(this.prefix) ||
293
+ url.pathname === this.prefix ||
294
+ rawPath
295
+ .split('?')[0]
296
+ .split('/')
297
+ .some((part) => part === '.' || part === '..') ||
298
+ url.pathname.includes('//'))
299
+ throw new Error('Invalid path');
300
+ return url.href;
301
+ }
302
+ catch {
303
+ throw new ConnectError('INVALID_REQUEST');
304
+ }
305
+ }
306
+ }
package/package.json CHANGED
@@ -1,6 +1,75 @@
1
1
  {
2
2
  "name": "sf-plugin-data",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Salesforce CLI bootstrap for portable Data360 configuration",
5
+ "author": {
6
+ "name": "Jörn Berkefeld",
7
+ "email": "joern.berkefeld@gmail.com"
8
+ },
9
+ "license": "MIT",
10
+ "type": "module",
11
+ "engines": {
12
+ "node": "^22.22.2 || ^24.15.0"
13
+ },
14
+ "files": [
15
+ "bin",
16
+ "lib",
17
+ "README.md",
18
+ "LICENSE",
19
+ "docs"
20
+ ],
21
+ "oclif": {
22
+ "bin": "sf",
23
+ "commands": "./lib/commands",
24
+ "topicSeparator": " ",
25
+ "topics": {
26
+ "data360": {
27
+ "description": "Portable Data360 configuration: bounded DMO retrieval, deployment preview and guarded writes."
28
+ },
29
+ "datacloud": {
30
+ "description": "Alias for data360: portable Data360 configuration."
31
+ },
32
+ "d360": {
33
+ "description": "Alias for data360: portable Data360 configuration."
34
+ },
35
+ "dc": {
36
+ "description": "Alias for data360: portable Data360 configuration."
37
+ }
38
+ }
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.json",
42
+ "lint": "eslint src test scripts bin eslint.config.js --max-warnings 0",
43
+ "lint:fix": "npm run lint -- --fix",
44
+ "format": "prettier --write .",
45
+ "format:check": "prettier --check .",
46
+ "test": "npm run build && node --test test/*.test.mjs",
47
+ "smoke": "node --test test/cli.test.mjs",
48
+ "smoke:package": "node scripts/package-smoke.mjs",
49
+ "prepare": "husky || true",
50
+ "prepack": "npm run build"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public",
54
+ "registry": "https://registry.npmjs.org/"
55
+ },
56
+ "dependencies": {
57
+ "@oclif/core": "4.13.2",
58
+ "@salesforce/core": "8.31.3",
59
+ "@salesforce/sf-plugins-core": "12.2.0"
60
+ },
61
+ "devDependencies": {
62
+ "@eslint/js": "9.39.4",
63
+ "@types/node": "22.19.0",
64
+ "eslint": "9.39.4",
65
+ "eslint-config-prettier": "10.1.8",
66
+ "eslint-plugin-jsdoc": "54.7.0",
67
+ "eslint-plugin-prettier": "5.5.6",
68
+ "eslint-plugin-unicorn": "64.0.0",
69
+ "globals": "17.9.0",
70
+ "husky": "9.1.7",
71
+ "prettier": "3.9.6",
72
+ "typescript": "5.9.3",
73
+ "typescript-eslint": "8.67.0"
74
+ }
75
+ }