sf-plugin-data 0.2.0 → 0.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.
@@ -0,0 +1,109 @@
1
+ import { Flags, SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { AuthInfo, ConfigAggregator, Connection, StateAggregator } from '@salesforce/core';
3
+ import { plugin } from '../../../plugin.js';
4
+ import { DataSpaceError } from '../../../services/data-space-check.js';
5
+ import { listDataSpaces } from '../../../services/list-data-spaces.js';
6
+ import { operationDiagnostic } from '../../../services/operation-diagnostic.js';
7
+ import { annotateDiagnostics, formatDiagnostic } from '../../../errors/registry.js';
8
+ import { exitCodeOf } from '../../../exit-code.js';
9
+ /**
10
+ * List the data spaces of the org: the names `--dataspace` takes in every other command.
11
+ */
12
+ export default class ListDataSpace extends SfCommand {
13
+ static aliases = [
14
+ 'datacloud:list:dataspace',
15
+ 'd360:list:dataspace',
16
+ 'dc:list:dataspace',
17
+ ];
18
+ static summary = 'List the data spaces of the org.';
19
+ static description = 'Reads every Data360 data space of the org (GET /ssot/data-spaces at API 68, page by page until the list is complete) and shows its name, label and prefix. The name is what --dataspace takes in the other sf data360 commands; the prefix (every data space but default has one) is what Salesforce puts in front of some names in that data space, such as ds2_Individual__dlm. A list that cannot be read completely is DATASPACE_READ_FAILED and nothing is shown. Read-only: nothing in the org changes.';
20
+ static examples = [
21
+ 'sf data360 list dataspace -o source',
22
+ 'sf data360 list dataspace -o source --json',
23
+ ];
24
+ static flags = {
25
+ 'target-org': Flags.string({
26
+ char: 'o',
27
+ summary: 'Authenticated target org alias or username.',
28
+ }),
29
+ };
30
+ resolveConnection = async (alias) => {
31
+ const aggregator = await ConfigAggregator.create();
32
+ const state = await StateAggregator.getInstance();
33
+ const target = alias ?? aggregator.getPropertyValue('target-org');
34
+ return Connection.create({
35
+ authInfo: await AuthInfo.create({
36
+ username: target ? state.aliases.resolveUsername(target) : undefined,
37
+ }),
38
+ connectionOptions: { version: '68.0' },
39
+ });
40
+ };
41
+ /**
42
+ * Read the org's data spaces.
43
+ * @returns {Promise<ListDataSpaceEnvelope>} List receipt.
44
+ */
45
+ async run() {
46
+ const { flags } = (await this.parse(ListDataSpace));
47
+ const envelope = {
48
+ contract: 'sf-data360-list-dataspace',
49
+ contractVersion: '1.0.0',
50
+ status: 'blocked',
51
+ metadata: { operation: 'list-dataspace', apiVersion: '68.0', plugin },
52
+ provenance: { command: 'sf data360 list dataspace', generatedAt: new Date().toISOString() },
53
+ diagnostics: { warnings: [], errors: [] },
54
+ result: { items: [] },
55
+ };
56
+ let connection;
57
+ try {
58
+ connection = await this.resolveConnection(flags['target-org']);
59
+ }
60
+ catch {
61
+ envelope.diagnostics.errors.push({
62
+ code: 'TARGET_ORG_REQUIRED',
63
+ message: 'No usable target org: pass -o with an authenticated alias or username, or set target-org.',
64
+ retryable: false,
65
+ });
66
+ return this.finish(envelope);
67
+ }
68
+ try {
69
+ envelope.result.items = await listDataSpaces(connection);
70
+ envelope.status = 'success';
71
+ }
72
+ catch (error) {
73
+ envelope.status = 'failed';
74
+ envelope.diagnostics.errors.push({
75
+ code: error instanceof DataSpaceError ? error.code : 'DATASPACE_READ_FAILED',
76
+ message: operationDiagnostic(error, 'The data space list was not read completely. Nothing in the org changed.'),
77
+ retryable: false,
78
+ });
79
+ }
80
+ return this.finish(envelope);
81
+ }
82
+ /**
83
+ * Set the exit code and print the human list.
84
+ * @param {ListDataSpaceEnvelope} envelope Filled receipt.
85
+ * @returns {ListDataSpaceEnvelope} The same receipt.
86
+ */
87
+ finish(envelope) {
88
+ const exitCode = exitCodeOf(envelope);
89
+ if (exitCode !== 0)
90
+ process.exitCode = exitCode;
91
+ annotateDiagnostics(envelope);
92
+ if (!this.jsonEnabled()) {
93
+ if (envelope.status === 'success') {
94
+ const rows = [
95
+ ['Name', 'Label', 'Prefix'],
96
+ ...envelope.result.items.map((item) => [item.name, item.label, item.prefix ?? '']),
97
+ ];
98
+ const widths = [0, 1].map((column) => Math.max(...rows.map((row) => row[column].length)));
99
+ for (const row of rows)
100
+ this.log(`${row[0].padEnd(widths[0])} ${row[1].padEnd(widths[1])} ${row[2]}`.trimEnd());
101
+ }
102
+ else
103
+ this.log(`List data spaces: ${envelope.status}.`);
104
+ for (const diagnostic of envelope.diagnostics.errors)
105
+ this.log(formatDiagnostic(diagnostic));
106
+ }
107
+ return envelope;
108
+ }
109
+ }
@@ -10,7 +10,7 @@ import { calculatedInsightReadContext } from '../../services/native-calculated-i
10
10
  export type PublishEnvelope = {
11
11
  contract: 'sf-data360-publish';
12
12
  contractVersion: '1.0.0';
13
- status: 'success' | 'processing' | 'blocked' | 'failed';
13
+ status: 'success' | 'accepted' | 'processing' | 'blocked' | 'failed';
14
14
  metadata: {
15
15
  operation: 'publish';
16
16
  preview: boolean;
@@ -51,7 +51,7 @@ export type PublishEnvelope = {
51
51
  export default class Publish extends SfCommand<PublishEnvelope> {
52
52
  static readonly aliases: string[];
53
53
  static readonly summary = "Publish one Data360 Calculated Insight draft or one segment.";
54
- static readonly description = "Segment: -m segment:Name (the segment as the org holds it) or -d data360/segments/Name.segment.json (or one of its .segment.<model>.sql files; the org must hold the definition of the file, otherwise SEGMENT_PUBLISH_DEFINITION_MISMATCH: deploy it first). A file retrieved as-is (verbatim) is refused with VERBATIM_NOT_DEPLOYABLE. --api-version auto (68.0) or 68.0, in the run data space (--dataspace; a segment or file of another data space is SEGMENT_DATASPACE_MISMATCH). The segment is read by name (absent is SEGMENT_PUBLISH_ADMISSION_FAILED), then one API 68 POST /ssot/segments/{marketSegmentId}/actions/publish without a body starts the publish; it runs on command, needs no acknowledgement flag and is never resent. Salesforce decides whether the segment can be published now, also while it is PROCESSING or COUNTING; a 4xx answer is reported with its text (SEGMENT_PUBLISH_REJECTED). The segment is then read every 30 seconds (progress on stderr) until publishStatus is SUCCESS (published) or FAILED (SEGMENT_PUBLISH_FAILED) for this publish. --wait-timeout sets that wait in whole seconds (default 1800; a publish took about 15 minutes in a test); when it runs out the result is publishing (status processing, exit 0, SEGMENT_PUBLISH_STILL_PROCESSING): still processing, not failed, and not resent. --async returns right after Salesforce accepted the POST, without any read afterwards: outcome publishing, mutation acknowledged-processing, status processing, exit 0, SEGMENT_PUBLISH_STARTED (started, not finished); --async and --wait-timeout cannot be combined. Members are readable only after SUCCESS. --preview reads the segment and reports what would be published without publishing. Calculated insight: requires one exact --source-dir data360/calculatedInsights/Name__cio.calculatedInsight-meta.json or its .calculatedInsight-meta.sql file (the JSON is joined with its SQL; a missing SQL file or another Name__cio.calculatedInsight-meta.* file beside them is refused with INVALID_SOURCE), --api-version auto (68.0) or 68.0 and the run data space (--dataspace, default: default; --data-space is a compatibility alias), which c__dataSpace in the file must name (CI_DATASPACE_MISMATCH otherwise). The insight must exist (create it with sf data360 deploy, --draft for a draft). An ACTIVE insight that holds every key of the file is unchanged; otherwise one API 68 PATCH sends the file (translated like deploy) with draft: false, and the insight is read until it is ACTIVE with the file; with --async it is not read after Salesforce accepted the PATCH (outcome publishing, mutation acknowledged-processing, status processing, exit 0, CI_PUBLISH_STARTED). Salesforce decides; a 4xx answer is reported as rejected. --preview is read-only. An unknown outcome is not retried or rolled back.";
54
+ static readonly description = "Segment: -m segment:Name (the segment as the org holds it) or -d data360/segments/Name.segment.json (or one of its .segment.<model>.sql files; the org must hold the definition of the file, otherwise SEGMENT_PUBLISH_DEFINITION_MISMATCH: deploy it first). A file retrieved as-is (verbatim) is refused with VERBATIM_NOT_DEPLOYABLE. --api-version auto (68.0) or 68.0, in the run data space (--dataspace; a segment or file of another data space is SEGMENT_DATASPACE_MISMATCH). The segment is read by name (absent is SEGMENT_PUBLISH_ADMISSION_FAILED), then one API 68 POST /ssot/segments/{marketSegmentId}/actions/publish without a body starts the publish; it runs on command, needs no acknowledgement flag and is never resent. Salesforce decides whether the segment can be published now, also while it is PROCESSING or COUNTING; a 4xx answer is reported with its text (SEGMENT_PUBLISH_REJECTED). The segment is then read every 30 seconds (progress on stderr) until publishStatus is SUCCESS (published) or FAILED (SEGMENT_PUBLISH_FAILED) for this publish. --wait-timeout sets that wait in whole seconds (default 1800; a publish took about 15 minutes in a test); when it runs out the result is publishing (status processing, exit 69, SEGMENT_PUBLISH_STILL_PROCESSING): still processing, not failed, and not resent. --async returns right after Salesforce accepted the POST, without any read afterwards: outcome publishing, mutation acknowledged-processing, status accepted, exit 0, SEGMENT_PUBLISH_STARTED (started, not finished); --async and --wait-timeout cannot be combined. Members are readable only after SUCCESS. --preview reads the segment and reports what would be published without publishing. Calculated insight: requires one exact --source-dir data360/calculatedInsights/Name__cio.calculatedInsight-meta.json or its .calculatedInsight-meta.sql file (the JSON is joined with its SQL; a missing SQL file or another Name__cio.calculatedInsight-meta.* file beside them is refused with INVALID_SOURCE), --api-version auto (68.0) or 68.0 and the run data space (--dataspace, default: default; --data-space is a compatibility alias), which c__dataSpace in the file must name (CI_DATASPACE_MISMATCH otherwise). The insight must exist (create it with sf data360 deploy, --draft for a draft). An ACTIVE insight that holds every key of the file is unchanged; otherwise one API 68 PATCH sends the file (translated like deploy) with draft: false, and the insight is read until it is ACTIVE with the file; with --async it is not read after Salesforce accepted the PATCH (outcome publishing, mutation acknowledged-processing, status accepted, exit 0, CI_PUBLISH_STARTED). Salesforce decides; a 4xx answer is reported as rejected. --preview is read-only. An unknown outcome is not retried or rolled back.";
55
55
  static readonly flags: {
56
56
  'target-org': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
57
57
  'source-dir': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -8,6 +8,7 @@ import { publishSegment, segmentPublishWait } from '../../services/publish-segme
8
8
  import { publishCalculatedInsight } from '../../services/publish-calculated-insight.js';
9
9
  import { calculatedInsightReadContext } from '../../services/native-calculated-insight.js';
10
10
  import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js';
11
+ import { exitCodeOf } from '../../exit-code.js';
11
12
  /**
12
13
  * Publish one native Calculated Insight draft (JSON plus SQL file) without deploying or
13
14
  * scheduling it, or publish one segment and wait for the result (--async: return once started).
@@ -15,7 +16,7 @@ import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js'
15
16
  export default class Publish extends SfCommand {
16
17
  static aliases = ['datacloud:publish', 'd360:publish', 'dc:publish'];
17
18
  static summary = 'Publish one Data360 Calculated Insight draft or one segment.';
18
- static description = 'Segment: -m segment:Name (the segment as the org holds it) or -d data360/segments/Name.segment.json (or one of its .segment.<model>.sql files; the org must hold the definition of the file, otherwise SEGMENT_PUBLISH_DEFINITION_MISMATCH: deploy it first). A file retrieved as-is (verbatim) is refused with VERBATIM_NOT_DEPLOYABLE. --api-version auto (68.0) or 68.0, in the run data space (--dataspace; a segment or file of another data space is SEGMENT_DATASPACE_MISMATCH). The segment is read by name (absent is SEGMENT_PUBLISH_ADMISSION_FAILED), then one API 68 POST /ssot/segments/{marketSegmentId}/actions/publish without a body starts the publish; it runs on command, needs no acknowledgement flag and is never resent. Salesforce decides whether the segment can be published now, also while it is PROCESSING or COUNTING; a 4xx answer is reported with its text (SEGMENT_PUBLISH_REJECTED). The segment is then read every 30 seconds (progress on stderr) until publishStatus is SUCCESS (published) or FAILED (SEGMENT_PUBLISH_FAILED) for this publish. --wait-timeout sets that wait in whole seconds (default 1800; a publish took about 15 minutes in a test); when it runs out the result is publishing (status processing, exit 0, SEGMENT_PUBLISH_STILL_PROCESSING): still processing, not failed, and not resent. --async returns right after Salesforce accepted the POST, without any read afterwards: outcome publishing, mutation acknowledged-processing, status processing, exit 0, SEGMENT_PUBLISH_STARTED (started, not finished); --async and --wait-timeout cannot be combined. Members are readable only after SUCCESS. --preview reads the segment and reports what would be published without publishing. Calculated insight: requires one exact --source-dir data360/calculatedInsights/Name__cio.calculatedInsight-meta.json or its .calculatedInsight-meta.sql file (the JSON is joined with its SQL; a missing SQL file or another Name__cio.calculatedInsight-meta.* file beside them is refused with INVALID_SOURCE), --api-version auto (68.0) or 68.0 and the run data space (--dataspace, default: default; --data-space is a compatibility alias), which c__dataSpace in the file must name (CI_DATASPACE_MISMATCH otherwise). The insight must exist (create it with sf data360 deploy, --draft for a draft). An ACTIVE insight that holds every key of the file is unchanged; otherwise one API 68 PATCH sends the file (translated like deploy) with draft: false, and the insight is read until it is ACTIVE with the file; with --async it is not read after Salesforce accepted the PATCH (outcome publishing, mutation acknowledged-processing, status processing, exit 0, CI_PUBLISH_STARTED). Salesforce decides; a 4xx answer is reported as rejected. --preview is read-only. An unknown outcome is not retried or rolled back.';
19
+ static description = 'Segment: -m segment:Name (the segment as the org holds it) or -d data360/segments/Name.segment.json (or one of its .segment.<model>.sql files; the org must hold the definition of the file, otherwise SEGMENT_PUBLISH_DEFINITION_MISMATCH: deploy it first). A file retrieved as-is (verbatim) is refused with VERBATIM_NOT_DEPLOYABLE. --api-version auto (68.0) or 68.0, in the run data space (--dataspace; a segment or file of another data space is SEGMENT_DATASPACE_MISMATCH). The segment is read by name (absent is SEGMENT_PUBLISH_ADMISSION_FAILED), then one API 68 POST /ssot/segments/{marketSegmentId}/actions/publish without a body starts the publish; it runs on command, needs no acknowledgement flag and is never resent. Salesforce decides whether the segment can be published now, also while it is PROCESSING or COUNTING; a 4xx answer is reported with its text (SEGMENT_PUBLISH_REJECTED). The segment is then read every 30 seconds (progress on stderr) until publishStatus is SUCCESS (published) or FAILED (SEGMENT_PUBLISH_FAILED) for this publish. --wait-timeout sets that wait in whole seconds (default 1800; a publish took about 15 minutes in a test); when it runs out the result is publishing (status processing, exit 69, SEGMENT_PUBLISH_STILL_PROCESSING): still processing, not failed, and not resent. --async returns right after Salesforce accepted the POST, without any read afterwards: outcome publishing, mutation acknowledged-processing, status accepted, exit 0, SEGMENT_PUBLISH_STARTED (started, not finished); --async and --wait-timeout cannot be combined. Members are readable only after SUCCESS. --preview reads the segment and reports what would be published without publishing. Calculated insight: requires one exact --source-dir data360/calculatedInsights/Name__cio.calculatedInsight-meta.json or its .calculatedInsight-meta.sql file (the JSON is joined with its SQL; a missing SQL file or another Name__cio.calculatedInsight-meta.* file beside them is refused with INVALID_SOURCE), --api-version auto (68.0) or 68.0 and the run data space (--dataspace, default: default; --data-space is a compatibility alias), which c__dataSpace in the file must name (CI_DATASPACE_MISMATCH otherwise). The insight must exist (create it with sf data360 deploy, --draft for a draft). An ACTIVE insight that holds every key of the file is unchanged; otherwise one API 68 PATCH sends the file (translated like deploy) with draft: false, and the insight is read until it is ACTIVE with the file; with --async it is not read after Salesforce accepted the PATCH (outcome publishing, mutation acknowledged-processing, status accepted, exit 0, CI_PUBLISH_STARTED). Salesforce decides; a 4xx answer is reported as rejected. --preview is read-only. An unknown outcome is not retried or rolled back.';
19
20
  static flags = {
20
21
  'target-org': Flags.string({
21
22
  char: 'o',
@@ -33,11 +34,11 @@ export default class Publish extends SfCommand {
33
34
  async: Flags.boolean({
34
35
  default: false,
35
36
  exclusive: ['wait-timeout'],
36
- summary: 'Start the publish and return at once (status processing, exit 0) without waiting for the result; not with --wait-timeout.',
37
+ summary: 'Start the publish and return at once (status accepted, exit 0) without waiting for the result; not with --wait-timeout.',
37
38
  }),
38
39
  'wait-timeout': Flags.integer({
39
40
  exclusive: ['async'],
40
- summary: `Segment only: seconds to wait for SUCCESS or FAILED (default ${segmentPublishWait.timeoutSeconds}).`,
41
+ summary: `Segment only: seconds to wait for SUCCESS or FAILED (default ${segmentPublishWait.timeoutSeconds}); when it runs out, status processing, exit 69.`,
41
42
  }),
42
43
  'api-version': Flags.string({ summary: 'Native lifecycle route: auto (68.0) or 68.0.' }),
43
44
  dataspace: Flags.string({
@@ -164,7 +165,9 @@ export default class Publish extends SfCommand {
164
165
  : result.outcome === 'blocked'
165
166
  ? 'blocked'
166
167
  : result.outcome === 'publishing'
167
- ? 'processing'
168
+ ? flags.async
169
+ ? 'accepted'
170
+ : 'processing'
168
171
  : 'success';
169
172
  // A publish started with --async is reported on the item, not as an error.
170
173
  if (result.outcome !== 'publishing')
@@ -246,7 +249,9 @@ export default class Publish extends SfCommand {
246
249
  : result.outcome === 'blocked'
247
250
  ? 'blocked'
248
251
  : result.outcome === 'publishing'
249
- ? 'processing'
252
+ ? flags.async
253
+ ? 'accepted'
254
+ : 'processing'
250
255
  : 'success';
251
256
  // Still processing is reported on the item, not as an error.
252
257
  if (result.outcome !== 'publishing')
@@ -271,8 +276,9 @@ export default class Publish extends SfCommand {
271
276
  * @returns {PublishEnvelope} The same receipt.
272
277
  */
273
278
  finish(envelope, preview) {
274
- if (envelope.status !== 'success' && envelope.status !== 'processing')
275
- process.exitCode = 1;
279
+ const exitCode = exitCodeOf(envelope);
280
+ if (exitCode !== 0)
281
+ process.exitCode = exitCode;
276
282
  annotateDiagnostics(envelope);
277
283
  if (!this.jsonEnabled()) {
278
284
  this.log(`Publish${preview ? ' preview' : ''}: ${envelope.status}.`);
@@ -37,7 +37,7 @@ import { acquireRetrieveSelection } from '../../services/acquire-retrieve-select
37
37
  export type RetrieveEnvelope = {
38
38
  contract: 'sf-data360-retrieve';
39
39
  contractVersion: '1.1.0';
40
- status: 'success' | 'blocked' | 'failed';
40
+ status: 'success' | 'partial' | 'blocked' | 'failed';
41
41
  metadata: {
42
42
  operation: 'retrieve';
43
43
  plugin: {
@@ -108,10 +108,19 @@ type ListedEntries = {
108
108
  declare const retrieveFamilies: readonly ["dlo", "dmo", "mapping", "relationship", "segment", "calculated-insight", "identity-resolution", "data-stream", "data-transform", "data-graph"];
109
109
  /** Family named on a diagnostic. */
110
110
  export type RetrieveFamily = (typeof retrieveFamilies)[number];
111
+ type RetrieveFlags = {
112
+ 'target-org'?: string;
113
+ 'api-version': string;
114
+ dataspace?: string;
115
+ metadata?: string[];
116
+ 'output-dir'?: string;
117
+ overwrite: boolean;
118
+ };
111
119
  export default class Retrieve extends SfCommand<RetrieveEnvelope> {
112
120
  static readonly aliases: string[];
113
121
  static readonly summary = "Retrieve any mix of Data360 DLOs, DMOs, mappings, relationships, data streams, data transforms, data graphs, Segments, calculated insights and identity resolution configuration.";
114
- static readonly description = "Any mix of selectors is retrieved in one run with one result: every selector is checked before the org is read, and a refused selector blocks the whole run (with several families selected, the refusal names its family). The families are then read one after another (DLO, DMO, mapping, relationship, Segment, calculated insight and identity resolution first, then data streams, data transforms and data graphs), each with its own API version and data space rules; one family failing does not stop the others. Exact -m data-transform:Name retrieves a transform (custom, system or packaged) at API68 in the run data space (c__dataSpace: its dataSpaceName or, without one, the data space of its MktDataTransform record read with SOQL; one without any data space is handled in default only; another data space is TRANSFORM_DATASPACE_MISMATCH, never a verbatim file) into data360/dataTransforms/<Name>.dataTransform.json: its create/update input as Salesforce returns it (definition or definitions, fullRunFrequency, write mode and the rest as read), without server-owned output object fields, plus its schedule projected onto the keys the schedule PUT takes (no schedule key when the transform has none, so a deploy of the file leaves the schedule alone; also left out, with a warning, when the schedule read fails). A transform with both definition and definitions is written as-is (verbatim), and deploy refuses that file. Bare -m data-transform retrieves every transform of the run data space the API lists (kept by the dataSpaceName of each entry, or its MktDataTransform record for an entry without one), each through the same path; one failing transform never blocks the others. Exact -m data-stream:ApiName retrieves an Ingestion API stream (any refresh mode and DLO category) as portable JSON using native API68 reads, when its DLO belongs to the run data space (the file lists every data space of the DLO in c__dataSpace); a stream of any other connector (for example Salesforce CRM, SalesforceDotCom) is written as its GET without server-owned keys and the system fields and mappings Salesforce adds, formulas decoded. Bare -m data-stream retrieves every stream the API lists (unless its DLO names only other data spaces), each through the same path. Native DLO, DMO and mapping retrieval writes canonical JSON under data360/<type>, retaining definition fields without source record IDs. A DLO file lists every data space the DLO belongs to in its top-level c__dataSpace key; the DLOs of the run data space are retrieved. Every retrieve first checks that the org has the run data space (one GET /ssot/data-spaces; UNKNOWN_DATASPACE otherwise). Default/auto uses API68; explicit numeric versions >=61 are preserved, and <=60 is rejected before calls. Omit selectors for all three native families, use -m dlo, -m dmo or -m mapping for complete type inventory, or repeat type:ApiName for exact selections. Omitted selectors and -m dlo (also beside other families) retrieve every DLO the Data 360 API lists in the data space, connector- and stream-created ones included; a DLO whose read or file fails gets its own diagnostic and the others are still retrieved. Mapping JSON uses the native APIs; only its label (spec.label) is read with the Metadata API (readMetadata of ObjectSourceTargetMap, up to 10 names per call), left out when it equals the mapping name (the default) and, with a warning, when that read fails. DMOs retrieved beside other families use the same native JSON at the native version. Prerequisites are checked, never pulled in; select every component to retrieve explicitly. Every DMO selection uses this native route, and --api-version latest is not accepted. Exact -m relationship:Dmo__dlm writes every relationship whose source is that DMO as native JSON under data360/relationship/<Name>.relationship-meta.json; bare -m relationship does so for every DMO the API lists, one DMO after another. Repeat -m dmo:ApiName, -m segment:ApiName, -m calculated-insight:ApiName__cio, -m data-graph:ApiName or -m identity-resolution:ExactObjectApiName for exact selection. Graph retrieval uses native API68 (auto or explicit 68.0; other versions are rejected) and writes *.native-dataGraph.json authored intent without generated identities in the run data space (c__dataSpace, and definition.dataspaceName as read; a graph of another data space is DATA_GRAPH_DATASPACE_MISMATCH, never a verbatim file); repeat data-graph:ApiName for several graphs, read one after another. Bare -m data-graph retrieves every graph of the run data space the API lists. Calculated insights use the API68 GET only (auto or 68.0, in the run data space, written to c__dataSpace): -m calculated-insight:ApiName__cio retrieves that insight and bare -m calculated-insight every insight the API lists, whatever its status, schedule or SQL; each is written as data360/calculatedInsights/<ApiName>.calculatedInsight-meta.json (the GET body as returned, without status, run history, source-CI links, creation type, sub type and the dimensions and measures Salesforce derives from the SQL) plus its SQL as plain text in <ApiName>.calculatedInsight-meta.sql. IR uses native API68 owner reads in the run data space (c__dataSpace; the file keeps the names Salesforce stores, ds2_Individual_<id> and ds2_Individual__dlm outside default; a ruleset of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH, never a verbatim file); auto and explicit numeric68 are supported, while numeric67 is rejected. -m identity-resolution:ExactObjectApiName retrieves that ruleset and bare -m identity-resolution every ruleset of the run data space the API lists (kept by the dataSpaceName of each entry, as the list answers every data space). Auto selects fixed qualified routes, never probes or upgrades an explicit numeric pin. Segment uses auto or 68.0 in the run data space (c__dataSpace; a segment of another data space is SEGMENT_DATASPACE_MISMATCH; the file carries the stored name, <prefix>_<Name> in a non-default data space; other versions are refused): -m segment:ApiName retrieves that segment and bare -m segment every segment of the run data space the API lists (kept by the dataSpace of each entry). A SQL (DBT) segment is written as one portable data360/segments/<Name>.segment.json with its DBT model names, and the SQL of each model as Salesforce returns it in <Name>.segment.<model>.sql beside it; a UI segment (built in the segment canvas) is written as a normal <Name>.segment.json with its criteria as JSON. Any other segment type is written with the same keys, without SQL files (a Waterfall with its child segments by API name in childSegments, named with one segment list read); the lookback and the refresh schedule are kept (schedule in the write shape; no schedule key for a segment that does not refresh), and a key the plugin does not know stays in the file and deploy refuses it. A segment with parameters (no write takes them), schedule details the plugin does not know or UI criteria that are not a JSON object is written as-is (verbatim) and deploy refuses that file. Use -m dmo or omit selectors for existing DMO inventory; omitted selectors do not include segments. Unsupported objects produce per-object diagnostics and a nonzero aggregate while successful files are retained. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.";
122
+ static readonly description = "Any mix of selectors is retrieved in one run with one result: every selector is checked before the org is read, and a refused selector blocks the whole run (with several families selected, the refusal names its family). The families are then read one after another (DLO, DMO, mapping, relationship, Segment, calculated insight and identity resolution first, then data streams, data transforms and data graphs), each with its own API version and data space rules; one family failing does not stop the others. Exact -m data-transform:Name retrieves a transform (custom, system or packaged) at API68 in the run data space (c__dataSpace: its dataSpaceName or, without one, the data space of its MktDataTransform record read with SOQL; one without any data space is handled in default only; another data space is TRANSFORM_DATASPACE_MISMATCH, never a verbatim file) into data360/dataTransforms/<Name>.dataTransform.json: its create/update input as Salesforce returns it (definition or definitions, fullRunFrequency, write mode and the rest as read), without server-owned output object fields, plus its schedule projected onto the keys the schedule PUT takes (no schedule key when the transform has none, so a deploy of the file leaves the schedule alone; also left out, with a warning, when the schedule read fails). A transform with both definition and definitions is written as-is (verbatim), and deploy refuses that file. Bare -m data-transform retrieves every transform of the run data space the API lists (kept by the dataSpaceName of each entry, or its MktDataTransform record for an entry without one), each through the same path; one failing transform never blocks the others. Exact -m data-stream:ApiName retrieves an Ingestion API stream (any refresh mode and DLO category) as portable JSON using native API68 reads, when its DLO belongs to the run data space (the file lists every data space of the DLO in c__dataSpace); a stream of any other connector (for example Salesforce CRM, SalesforceDotCom) is written as its GET without server-owned keys and the system fields and mappings Salesforce adds, formulas decoded. Bare -m data-stream retrieves every stream the API lists (unless its DLO names only other data spaces), each through the same path. Native DLO, DMO and mapping retrieval writes canonical JSON under data360/<type>, retaining definition fields without source record IDs. A DLO file lists every data space the DLO belongs to in its top-level c__dataSpace key; the DLOs of the run data space are retrieved. Every retrieve first checks that the org has the run data space (one GET /ssot/data-spaces; UNKNOWN_DATASPACE otherwise). Default/auto uses API68; explicit numeric versions >=61 are preserved, and <=60 is rejected before calls. Omit -m to retrieve every family (dlo, dmo, mapping, relationship, data-stream, data-transform, data-graph, segment, identity-resolution and calculated-insight), each as if named bare, in the run data space; -m narrows the run to the families and names it lists. Families fixed at API68 (for example data graphs, Segments, calculated insights and identity resolution) refuse another explicit --api-version, which blocks a run without -m; to pin an older native version, name the native families with -m. Use -m dlo, -m dmo or -m mapping for complete type inventory, or repeat type:ApiName for exact selections. Omitted selectors and -m dlo (also beside other families) retrieve every DLO the Data 360 API lists in the data space, connector- and stream-created ones included; a DLO whose read or file fails gets its own diagnostic and the others are still retrieved. Mapping JSON uses the native APIs; only its label (spec.label) is read with the Metadata API (readMetadata of ObjectSourceTargetMap, up to 10 names per call), left out when it equals the mapping name (the default) and, with a warning, when that read fails. DMOs retrieved beside other families use the same native JSON at the native version. Prerequisites are checked, never pulled in; select every component to retrieve explicitly. Every DMO selection uses this native route, and --api-version latest is not accepted. Exact -m relationship:Dmo__dlm writes every relationship whose source is that DMO as native JSON under data360/relationship/<Name>.relationship-meta.json; bare -m relationship does so for every DMO the API lists, one DMO after another. Repeat -m dmo:ApiName, -m segment:ApiName, -m calculated-insight:ApiName__cio, -m data-graph:ApiName or -m identity-resolution:ExactObjectApiName for exact selection. Graph retrieval uses native API68 (auto or explicit 68.0; other versions are rejected) and writes *.native-dataGraph.json authored intent without generated identities in the run data space (c__dataSpace, and definition.dataspaceName as read; a graph of another data space is DATA_GRAPH_DATASPACE_MISMATCH, never a verbatim file); repeat data-graph:ApiName for several graphs, read one after another. Bare -m data-graph retrieves every graph of the run data space the API lists. Calculated insights use the API68 GET only (auto or 68.0, in the run data space, written to c__dataSpace): -m calculated-insight:ApiName__cio retrieves that insight and bare -m calculated-insight every insight the API lists, whatever its status, schedule or SQL; each is written as data360/calculatedInsights/<ApiName>.calculatedInsight-meta.json (the GET body as returned, without status, run history, source-CI links, creation type, sub type and the dimensions and measures Salesforce derives from the SQL) plus its SQL as plain text in <ApiName>.calculatedInsight-meta.sql. IR uses native API68 owner reads in the run data space (c__dataSpace; the file keeps the names Salesforce stores, ds2_Individual_<id> and ds2_Individual__dlm outside default; a ruleset of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH, never a verbatim file); auto and explicit numeric68 are supported, while numeric67 is rejected. -m identity-resolution:ExactObjectApiName retrieves that ruleset and bare -m identity-resolution every ruleset of the run data space the API lists (kept by the dataSpaceName of each entry, as the list answers every data space). Auto selects fixed qualified routes, never probes or upgrades an explicit numeric pin. Segment uses auto or 68.0 in the run data space (c__dataSpace; a segment of another data space is SEGMENT_DATASPACE_MISMATCH; the file carries the stored name, <prefix>_<Name> in a non-default data space; other versions are refused): -m segment:ApiName retrieves that segment and bare -m segment every segment of the run data space the API lists (kept by the dataSpace of each entry). A SQL (DBT) segment is written as one portable data360/segments/<Name>.segment.json with its DBT model names, and the SQL of each model as Salesforce returns it in <Name>.segment.<model>.sql beside it; a UI segment (built in the segment canvas) is written as a normal <Name>.segment.json with its criteria as JSON. Any other segment type is written with the same keys, without SQL files (a Waterfall with its child segments by API name in childSegments, named with one segment list read); the lookback and the refresh schedule are kept (schedule in the write shape; no schedule key for a segment that does not refresh), and a key the plugin does not know stays in the file and deploy refuses it. A segment with parameters (no write takes them), schedule details the plugin does not know or UI criteria that are not a JSON object is written as-is (verbatim) and deploy refuses that file. Use -m dmo or omit selectors for existing DMO inventory. Unsupported objects produce per-object diagnostics while successful files are retained: the run is partial (exit 68) when some files were written, otherwise exit 1. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.";
123
+ static readonly examples: string[];
115
124
  static readonly flags: {
116
125
  'target-org': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
117
126
  'api-version': import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
@@ -283,7 +292,7 @@ export default class Retrieve extends SfCommand<RetrieveEnvelope> {
283
292
  private prepareDataGraphs;
284
293
  /**
285
294
  * Validate every other selector (DLO, DMO, mapping, relationship, Segment, calculated
286
- * insight, identity resolution); an empty selection is every native family.
295
+ * insight, identity resolution).
287
296
  * @param {string[]} selectors The selectors of no other group.
288
297
  * @param {RetrieveRun} context Shared command state.
289
298
  * @returns {GroupPlan} A refusal, or the group's read.
@@ -314,9 +323,22 @@ export default class Retrieve extends SfCommand<RetrieveEnvelope> {
314
323
  */
315
324
  run(): Promise<RetrieveEnvelope>;
316
325
  /**
317
- * The run itself; see run.
326
+ * The envelope of a retrieve with these flags, without printing or setting an exit code; the
327
+ * library (runRetrieve) and the command share it.
328
+ * @param {RetrieveFlags} flags Parsed flags.
318
329
  * @returns {Promise<RetrieveEnvelope>} Versioned retrieval outcome and payload-free diagnostics.
319
330
  */
320
- private retrieveAll;
331
+ protected retrieveEnvelope(flags: RetrieveFlags): Promise<RetrieveEnvelope>;
332
+ /**
333
+ * Human output of a finished run.
334
+ * @param {RetrieveOutcome} outcome The run's envelope and what its lines need.
335
+ */
336
+ private printOutcome;
337
+ /**
338
+ * The run itself; see run. It prints nothing and leaves process.exitCode alone.
339
+ * @param {RetrieveFlags} flags Parsed flags.
340
+ * @returns {Promise<RetrieveOutcome>} The envelope and what the human output needs.
341
+ */
342
+ private retrieveOutcome;
321
343
  }
322
344
  export {};
@@ -8,6 +8,7 @@ import { getConnectDiagnostic, retainConnectDiagnostic, } from '../../transport/
8
8
  import { retrieveNativeDataGraph } from '../../services/command-native-data-graph.js';
9
9
  import { explanationOf, operationDiagnostic } from '../../services/operation-diagnostic.js';
10
10
  import { annotateDiagnostics, formatDiagnostic } from '../../errors/registry.js';
11
+ import { exitCodeOf } from '../../exit-code.js';
11
12
  import { dataStreamApiVersion, nativeApiVersion } from '../../transport/api-version.js';
12
13
  import { DataStreamError } from '../../artifacts/data-stream-document.js';
13
14
  import { writeDataStreamDocument } from '../../artifacts/write-data-stream.js';
@@ -119,13 +120,31 @@ function selectorFamily(selector) {
119
120
  function inGroup(group, value) {
120
121
  return value === group || value.startsWith(`${group}:`);
121
122
  }
123
+ /** Bare native selectors of an omitted -m; they run as one rest group (see groupSelectors). */
124
+ const everyNativeFamily = ['dlo', 'dmo', 'mapping', 'relationship'];
125
+ /** Bare selectors of an omitted -m, one per family. */
126
+ const everyFamily = [
127
+ ...everyNativeFamily,
128
+ 'data-stream',
129
+ 'data-transform',
130
+ 'data-graph',
131
+ 'segment',
132
+ 'identity-resolution',
133
+ 'calculated-insight',
134
+ ];
122
135
  /**
123
- * Split the selection into groups in run order; groups without selectors are left out, and an
124
- * empty selection is the rest group alone (every native family).
136
+ * Split the selection into groups in run order; groups without selectors are left out. An empty
137
+ * selection is every family bare, with the native families (DLO, DMO, mapping, relationship) in
138
+ * a rest group of their own before the other rest families, because bare mapping cannot share a
139
+ * group with segments, calculated insights or identity resolution (MAPPING_INVENTORY_UNQUALIFIED).
125
140
  * @param {string[]} selectors Every -m selector.
126
141
  * @returns {Array<[string, string[]]>} Non-empty groups in run order.
127
142
  */
128
143
  function groupSelectors(selectors) {
144
+ if (selectors.length === 0) {
145
+ const [rest, ...others] = groupSelectors(everyFamily.filter((value) => !everyNativeFamily.includes(value)));
146
+ return [['rest', everyNativeFamily], rest, ...others];
147
+ }
129
148
  return selectorGroups
130
149
  .map((group) => [
131
150
  group,
@@ -133,7 +152,7 @@ function groupSelectors(selectors) {
133
152
  ? selectors.filter((value) => !selectorGroups.some((other) => other !== 'rest' && inGroup(other, value)))
134
153
  : selectors.filter((value) => inGroup(group, value)),
135
154
  ])
136
- .filter(([group, members]) => members.length > 0 || (group === 'rest' && selectors.length === 0));
155
+ .filter(([, members]) => members.length > 0);
137
156
  }
138
157
  /**
139
158
  * Status of one group from the diagnostics it added.
@@ -191,7 +210,12 @@ function verbatimStreamNative(response) {
191
210
  export default class Retrieve extends SfCommand {
192
211
  static aliases = ['datacloud:retrieve', 'd360:retrieve', 'dc:retrieve'];
193
212
  static summary = 'Retrieve any mix of Data360 DLOs, DMOs, mappings, relationships, data streams, data transforms, data graphs, Segments, calculated insights and identity resolution configuration.';
194
- static description = 'Any mix of selectors is retrieved in one run with one result: every selector is checked before the org is read, and a refused selector blocks the whole run (with several families selected, the refusal names its family). The families are then read one after another (DLO, DMO, mapping, relationship, Segment, calculated insight and identity resolution first, then data streams, data transforms and data graphs), each with its own API version and data space rules; one family failing does not stop the others. Exact -m data-transform:Name retrieves a transform (custom, system or packaged) at API68 in the run data space (c__dataSpace: its dataSpaceName or, without one, the data space of its MktDataTransform record read with SOQL; one without any data space is handled in default only; another data space is TRANSFORM_DATASPACE_MISMATCH, never a verbatim file) into data360/dataTransforms/<Name>.dataTransform.json: its create/update input as Salesforce returns it (definition or definitions, fullRunFrequency, write mode and the rest as read), without server-owned output object fields, plus its schedule projected onto the keys the schedule PUT takes (no schedule key when the transform has none, so a deploy of the file leaves the schedule alone; also left out, with a warning, when the schedule read fails). A transform with both definition and definitions is written as-is (verbatim), and deploy refuses that file. Bare -m data-transform retrieves every transform of the run data space the API lists (kept by the dataSpaceName of each entry, or its MktDataTransform record for an entry without one), each through the same path; one failing transform never blocks the others. Exact -m data-stream:ApiName retrieves an Ingestion API stream (any refresh mode and DLO category) as portable JSON using native API68 reads, when its DLO belongs to the run data space (the file lists every data space of the DLO in c__dataSpace); a stream of any other connector (for example Salesforce CRM, SalesforceDotCom) is written as its GET without server-owned keys and the system fields and mappings Salesforce adds, formulas decoded. Bare -m data-stream retrieves every stream the API lists (unless its DLO names only other data spaces), each through the same path. Native DLO, DMO and mapping retrieval writes canonical JSON under data360/<type>, retaining definition fields without source record IDs. A DLO file lists every data space the DLO belongs to in its top-level c__dataSpace key; the DLOs of the run data space are retrieved. Every retrieve first checks that the org has the run data space (one GET /ssot/data-spaces; UNKNOWN_DATASPACE otherwise). Default/auto uses API68; explicit numeric versions >=61 are preserved, and <=60 is rejected before calls. Omit selectors for all three native families, use -m dlo, -m dmo or -m mapping for complete type inventory, or repeat type:ApiName for exact selections. Omitted selectors and -m dlo (also beside other families) retrieve every DLO the Data 360 API lists in the data space, connector- and stream-created ones included; a DLO whose read or file fails gets its own diagnostic and the others are still retrieved. Mapping JSON uses the native APIs; only its label (spec.label) is read with the Metadata API (readMetadata of ObjectSourceTargetMap, up to 10 names per call), left out when it equals the mapping name (the default) and, with a warning, when that read fails. DMOs retrieved beside other families use the same native JSON at the native version. Prerequisites are checked, never pulled in; select every component to retrieve explicitly. Every DMO selection uses this native route, and --api-version latest is not accepted. Exact -m relationship:Dmo__dlm writes every relationship whose source is that DMO as native JSON under data360/relationship/<Name>.relationship-meta.json; bare -m relationship does so for every DMO the API lists, one DMO after another. Repeat -m dmo:ApiName, -m segment:ApiName, -m calculated-insight:ApiName__cio, -m data-graph:ApiName or -m identity-resolution:ExactObjectApiName for exact selection. Graph retrieval uses native API68 (auto or explicit 68.0; other versions are rejected) and writes *.native-dataGraph.json authored intent without generated identities in the run data space (c__dataSpace, and definition.dataspaceName as read; a graph of another data space is DATA_GRAPH_DATASPACE_MISMATCH, never a verbatim file); repeat data-graph:ApiName for several graphs, read one after another. Bare -m data-graph retrieves every graph of the run data space the API lists. Calculated insights use the API68 GET only (auto or 68.0, in the run data space, written to c__dataSpace): -m calculated-insight:ApiName__cio retrieves that insight and bare -m calculated-insight every insight the API lists, whatever its status, schedule or SQL; each is written as data360/calculatedInsights/<ApiName>.calculatedInsight-meta.json (the GET body as returned, without status, run history, source-CI links, creation type, sub type and the dimensions and measures Salesforce derives from the SQL) plus its SQL as plain text in <ApiName>.calculatedInsight-meta.sql. IR uses native API68 owner reads in the run data space (c__dataSpace; the file keeps the names Salesforce stores, ds2_Individual_<id> and ds2_Individual__dlm outside default; a ruleset of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH, never a verbatim file); auto and explicit numeric68 are supported, while numeric67 is rejected. -m identity-resolution:ExactObjectApiName retrieves that ruleset and bare -m identity-resolution every ruleset of the run data space the API lists (kept by the dataSpaceName of each entry, as the list answers every data space). Auto selects fixed qualified routes, never probes or upgrades an explicit numeric pin. Segment uses auto or 68.0 in the run data space (c__dataSpace; a segment of another data space is SEGMENT_DATASPACE_MISMATCH; the file carries the stored name, <prefix>_<Name> in a non-default data space; other versions are refused): -m segment:ApiName retrieves that segment and bare -m segment every segment of the run data space the API lists (kept by the dataSpace of each entry). A SQL (DBT) segment is written as one portable data360/segments/<Name>.segment.json with its DBT model names, and the SQL of each model as Salesforce returns it in <Name>.segment.<model>.sql beside it; a UI segment (built in the segment canvas) is written as a normal <Name>.segment.json with its criteria as JSON. Any other segment type is written with the same keys, without SQL files (a Waterfall with its child segments by API name in childSegments, named with one segment list read); the lookback and the refresh schedule are kept (schedule in the write shape; no schedule key for a segment that does not refresh), and a key the plugin does not know stays in the file and deploy refuses it. A segment with parameters (no write takes them), schedule details the plugin does not know or UI criteria that are not a JSON object is written as-is (verbatim) and deploy refuses that file. Use -m dmo or omit selectors for existing DMO inventory; omitted selectors do not include segments. Unsupported objects produce per-object diagnostics and a nonzero aggregate while successful files are retained. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.';
213
+ static description = 'Any mix of selectors is retrieved in one run with one result: every selector is checked before the org is read, and a refused selector blocks the whole run (with several families selected, the refusal names its family). The families are then read one after another (DLO, DMO, mapping, relationship, Segment, calculated insight and identity resolution first, then data streams, data transforms and data graphs), each with its own API version and data space rules; one family failing does not stop the others. Exact -m data-transform:Name retrieves a transform (custom, system or packaged) at API68 in the run data space (c__dataSpace: its dataSpaceName or, without one, the data space of its MktDataTransform record read with SOQL; one without any data space is handled in default only; another data space is TRANSFORM_DATASPACE_MISMATCH, never a verbatim file) into data360/dataTransforms/<Name>.dataTransform.json: its create/update input as Salesforce returns it (definition or definitions, fullRunFrequency, write mode and the rest as read), without server-owned output object fields, plus its schedule projected onto the keys the schedule PUT takes (no schedule key when the transform has none, so a deploy of the file leaves the schedule alone; also left out, with a warning, when the schedule read fails). A transform with both definition and definitions is written as-is (verbatim), and deploy refuses that file. Bare -m data-transform retrieves every transform of the run data space the API lists (kept by the dataSpaceName of each entry, or its MktDataTransform record for an entry without one), each through the same path; one failing transform never blocks the others. Exact -m data-stream:ApiName retrieves an Ingestion API stream (any refresh mode and DLO category) as portable JSON using native API68 reads, when its DLO belongs to the run data space (the file lists every data space of the DLO in c__dataSpace); a stream of any other connector (for example Salesforce CRM, SalesforceDotCom) is written as its GET without server-owned keys and the system fields and mappings Salesforce adds, formulas decoded. Bare -m data-stream retrieves every stream the API lists (unless its DLO names only other data spaces), each through the same path. Native DLO, DMO and mapping retrieval writes canonical JSON under data360/<type>, retaining definition fields without source record IDs. A DLO file lists every data space the DLO belongs to in its top-level c__dataSpace key; the DLOs of the run data space are retrieved. Every retrieve first checks that the org has the run data space (one GET /ssot/data-spaces; UNKNOWN_DATASPACE otherwise). Default/auto uses API68; explicit numeric versions >=61 are preserved, and <=60 is rejected before calls. Omit -m to retrieve every family (dlo, dmo, mapping, relationship, data-stream, data-transform, data-graph, segment, identity-resolution and calculated-insight), each as if named bare, in the run data space; -m narrows the run to the families and names it lists. Families fixed at API68 (for example data graphs, Segments, calculated insights and identity resolution) refuse another explicit --api-version, which blocks a run without -m; to pin an older native version, name the native families with -m. Use -m dlo, -m dmo or -m mapping for complete type inventory, or repeat type:ApiName for exact selections. Omitted selectors and -m dlo (also beside other families) retrieve every DLO the Data 360 API lists in the data space, connector- and stream-created ones included; a DLO whose read or file fails gets its own diagnostic and the others are still retrieved. Mapping JSON uses the native APIs; only its label (spec.label) is read with the Metadata API (readMetadata of ObjectSourceTargetMap, up to 10 names per call), left out when it equals the mapping name (the default) and, with a warning, when that read fails. DMOs retrieved beside other families use the same native JSON at the native version. Prerequisites are checked, never pulled in; select every component to retrieve explicitly. Every DMO selection uses this native route, and --api-version latest is not accepted. Exact -m relationship:Dmo__dlm writes every relationship whose source is that DMO as native JSON under data360/relationship/<Name>.relationship-meta.json; bare -m relationship does so for every DMO the API lists, one DMO after another. Repeat -m dmo:ApiName, -m segment:ApiName, -m calculated-insight:ApiName__cio, -m data-graph:ApiName or -m identity-resolution:ExactObjectApiName for exact selection. Graph retrieval uses native API68 (auto or explicit 68.0; other versions are rejected) and writes *.native-dataGraph.json authored intent without generated identities in the run data space (c__dataSpace, and definition.dataspaceName as read; a graph of another data space is DATA_GRAPH_DATASPACE_MISMATCH, never a verbatim file); repeat data-graph:ApiName for several graphs, read one after another. Bare -m data-graph retrieves every graph of the run data space the API lists. Calculated insights use the API68 GET only (auto or 68.0, in the run data space, written to c__dataSpace): -m calculated-insight:ApiName__cio retrieves that insight and bare -m calculated-insight every insight the API lists, whatever its status, schedule or SQL; each is written as data360/calculatedInsights/<ApiName>.calculatedInsight-meta.json (the GET body as returned, without status, run history, source-CI links, creation type, sub type and the dimensions and measures Salesforce derives from the SQL) plus its SQL as plain text in <ApiName>.calculatedInsight-meta.sql. IR uses native API68 owner reads in the run data space (c__dataSpace; the file keeps the names Salesforce stores, ds2_Individual_<id> and ds2_Individual__dlm outside default; a ruleset of another data space is IDENTITY_RESOLUTION_DATASPACE_MISMATCH, never a verbatim file); auto and explicit numeric68 are supported, while numeric67 is rejected. -m identity-resolution:ExactObjectApiName retrieves that ruleset and bare -m identity-resolution every ruleset of the run data space the API lists (kept by the dataSpaceName of each entry, as the list answers every data space). Auto selects fixed qualified routes, never probes or upgrades an explicit numeric pin. Segment uses auto or 68.0 in the run data space (c__dataSpace; a segment of another data space is SEGMENT_DATASPACE_MISMATCH; the file carries the stored name, <prefix>_<Name> in a non-default data space; other versions are refused): -m segment:ApiName retrieves that segment and bare -m segment every segment of the run data space the API lists (kept by the dataSpace of each entry). A SQL (DBT) segment is written as one portable data360/segments/<Name>.segment.json with its DBT model names, and the SQL of each model as Salesforce returns it in <Name>.segment.<model>.sql beside it; a UI segment (built in the segment canvas) is written as a normal <Name>.segment.json with its criteria as JSON. Any other segment type is written with the same keys, without SQL files (a Waterfall with its child segments by API name in childSegments, named with one segment list read); the lookback and the refresh schedule are kept (schedule in the write shape; no schedule key for a segment that does not refresh), and a key the plugin does not know stays in the file and deploy refuses it. A segment with parameters (no write takes them), schedule details the plugin does not know or UI criteria that are not a JSON object is written as-is (verbatim) and deploy refuses that file. Use -m dmo or omit selectors for existing DMO inventory. Unsupported objects produce per-object diagnostics while successful files are retained: the run is partial (exit 68) when some files were written, otherwise exit 1. Differing files require --overwrite; identical bytes are unchanged. Retrieval never mutates the org.';
214
+ static examples = [
215
+ 'Retrieve every family of the default data space:\n<%= config.bin %> <%= command.id %> --target-org my-org',
216
+ 'Retrieve every family of another data space:\n<%= config.bin %> <%= command.id %> --target-org my-org --dataspace marketing',
217
+ 'Retrieve only DMOs and one segment:\n<%= config.bin %> <%= command.id %> --target-org my-org -m dmo -m segment:Active_Buyers',
218
+ ];
195
219
  static flags = {
196
220
  'target-org': Flags.string({
197
221
  char: 'o',
@@ -210,7 +234,7 @@ export default class Retrieve extends SfCommand {
210
234
  char: 'm',
211
235
  multiple: true,
212
236
  multipleNonGreedy: true,
213
- summary: 'Repeat to mix families in one run. Native dlo/dmo/mapping type or type:ApiName JSON selections; bare dlo is every DLO the API lists; omitted selects all native families. relationship:Dmo__dlm (relationships whose source is that DMO), data-stream:ApiName, data-transform:Name, data-graph:ApiName, segment:ApiName, identity-resolution:ExactObjectApiName and calculated-insight:ApiName__cio, or the bare family name for every one the API lists (bare relationship: those of every listed DMO).',
237
+ summary: 'Repeat to mix families in one run. Native dlo/dmo/mapping type or type:ApiName JSON selections; bare dlo is every DLO the API lists; omitted selects every family below, each bare. relationship:Dmo__dlm (relationships whose source is that DMO), data-stream:ApiName, data-transform:Name, data-graph:ApiName, segment:ApiName, identity-resolution:ExactObjectApiName and calculated-insight:ApiName__cio, or the bare family name for every one the API lists (bare relationship: those of every listed DMO).',
214
238
  }),
215
239
  'output-dir': Flags.directory({
216
240
  char: 'd',
@@ -353,7 +377,8 @@ export default class Retrieve extends SfCommand {
353
377
  return {
354
378
  getOrgId: () => connection.getAuthInfoFields().orgId,
355
379
  getConnection: (version) => {
356
- if (version)
380
+ // Only a numeric version reaches the connection; @salesforce/core rejects `auto`.
381
+ if (version && /^[1-9]\d\.0$/u.test(version))
357
382
  connection.setApiVersion(version);
358
383
  return connection;
359
384
  },
@@ -939,7 +964,7 @@ export default class Retrieve extends SfCommand {
939
964
  }
940
965
  /**
941
966
  * Validate every other selector (DLO, DMO, mapping, relationship, Segment, calculated
942
- * insight, identity resolution); an empty selection is every native family.
967
+ * insight, identity resolution).
943
968
  * @param {string[]} selectors The selectors of no other group.
944
969
  * @param {RetrieveRun} context Shared command state.
945
970
  * @returns {GroupPlan} A refusal, or the group's read.
@@ -1420,7 +1445,8 @@ export default class Retrieve extends SfCommand {
1420
1445
  for (const apiName of dlos) {
1421
1446
  let nativeOf = nothingRead;
1422
1447
  try {
1423
- const target = flags['target-org'] ?? org.getConnection(flags['api-version']).getUsername();
1448
+ // DLO reads are pinned at 68.0; `--api-version` may be `auto`, never a connection version.
1449
+ const target = flags['target-org'] ?? org.getConnection('68.0').getUsername();
1424
1450
  if (!target)
1425
1451
  throw new SegmentError('TARGET_ORG_REQUIRED');
1426
1452
  const reads = recordNativeReads(this.createDloClient(target, '68.0', this.ssotSender(target, '68.0', org.getConnection()), listed.dlo));
@@ -1800,14 +1826,71 @@ export default class Retrieve extends SfCommand {
1800
1826
  */
1801
1827
  async run() {
1802
1828
  // Each output directory's ancestor chain is checked once per run; every file still is.
1803
- return withCheckedDirectories(async () => this.retrieveAll());
1829
+ return withCheckedDirectories(async () => {
1830
+ const { flags } = await this.parse(Retrieve);
1831
+ const outcome = await this.retrieveOutcome(flags);
1832
+ const exitCode = exitCodeOf(outcome.envelope);
1833
+ if (exitCode !== 0)
1834
+ process.exitCode = exitCode;
1835
+ if (!this.jsonEnabled())
1836
+ this.printOutcome(outcome);
1837
+ return outcome.envelope;
1838
+ });
1804
1839
  }
1805
1840
  /**
1806
- * The run itself; see run.
1841
+ * The envelope of a retrieve with these flags, without printing or setting an exit code; the
1842
+ * library (runRetrieve) and the command share it.
1843
+ * @param {RetrieveFlags} flags Parsed flags.
1807
1844
  * @returns {Promise<RetrieveEnvelope>} Versioned retrieval outcome and payload-free diagnostics.
1808
1845
  */
1809
- async retrieveAll() {
1810
- const { flags } = await this.parse(Retrieve);
1846
+ async retrieveEnvelope(flags) {
1847
+ return withCheckedDirectories(async () => {
1848
+ const { envelope } = await this.retrieveOutcome(flags);
1849
+ return envelope;
1850
+ });
1851
+ }
1852
+ /**
1853
+ * Human output of a finished run.
1854
+ * @param {RetrieveOutcome} outcome The run's envelope and what its lines need.
1855
+ */
1856
+ printOutcome(outcome) {
1857
+ const { envelope, code, outputTypes, errorTypes, effectiveScope } = outcome;
1858
+ this.log(`Retrieve: ${envelope.status}${code ? ` (${code})` : ''}.`);
1859
+ // The default data space goes without saying; any other is named.
1860
+ if (effectiveScope !== 'default')
1861
+ this.log(`Data space: ${effectiveScope}.`);
1862
+ const groups = new Set([
1863
+ ...outputTypes,
1864
+ ...envelope.result.items.map((item) => item.family ?? 'dmo'),
1865
+ ]);
1866
+ const printError = (diagnostic) => {
1867
+ this.log(formatDiagnostic(diagnostic, diagnostic.identity
1868
+ ? `${errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'}:${diagnostic.identity.apiName}: `
1869
+ : ''));
1870
+ };
1871
+ for (const family of groups) {
1872
+ const items = envelope.result.items.filter((item) => (item.family ?? 'dmo') === family);
1873
+ for (const item of items)
1874
+ this.log(`Downloaded ${family}:${item.identity.apiName} (${item.outcome}).`);
1875
+ for (const diagnostic of envelope.diagnostics.errors)
1876
+ if (diagnostic.identity &&
1877
+ (errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo') === family)
1878
+ printError(diagnostic);
1879
+ this.log(`Downloaded ${family}: ${items.length}`);
1880
+ }
1881
+ for (const diagnostic of envelope.diagnostics.errors)
1882
+ if (!diagnostic.identity ||
1883
+ !groups.has(errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'))
1884
+ printError(diagnostic);
1885
+ for (const warning of envelope.diagnostics.warnings)
1886
+ this.log(`Warning: ${warning}`);
1887
+ }
1888
+ /**
1889
+ * The run itself; see run. It prints nothing and leaves process.exitCode alone.
1890
+ * @param {RetrieveFlags} flags Parsed flags.
1891
+ * @returns {Promise<RetrieveOutcome>} The envelope and what the human output needs.
1892
+ */
1893
+ async retrieveOutcome(flags) {
1811
1894
  const effectiveScope = flags.dataspace ?? 'default';
1812
1895
  // Writers require an absolute project root; resolve a relative -d against the cwd once.
1813
1896
  const outputDirectory = path.resolve(flags['output-dir'] ?? process.cwd());
@@ -1834,14 +1917,19 @@ export default class Retrieve extends SfCommand {
1834
1917
  dataSpace: effectiveScope,
1835
1918
  outputDir: outputDirectory,
1836
1919
  },
1837
- selection: flags.metadata ?? [],
1920
+ selection: flags.metadata ?? [...everyFamily],
1838
1921
  items: [],
1839
1922
  },
1840
1923
  };
1841
1924
  const outputTypes = new Set();
1842
1925
  const errorTypes = new Map();
1843
1926
  const finish = (status, code, error, family) => {
1844
- envelope.status = status;
1927
+ // A run that wrote (or found unchanged) at least one file while another item or family
1928
+ // failed or was blocked is partial; nothing written keeps blocked or failed.
1929
+ envelope.status =
1930
+ (status === 'failed' || status === 'blocked') && envelope.result.items.length > 0
1931
+ ? 'partial'
1932
+ : status;
1845
1933
  if (code)
1846
1934
  envelope.diagnostics.errors.push({
1847
1935
  code,
@@ -1851,41 +1939,8 @@ export default class Retrieve extends SfCommand {
1851
1939
  retryable: false,
1852
1940
  ...(family ? { family } : {}),
1853
1941
  });
1854
- if (status !== 'success')
1855
- process.exitCode = 1;
1856
1942
  annotateDiagnostics(envelope);
1857
- if (!this.jsonEnabled()) {
1858
- this.log(`Retrieve: ${status}${code ? ` (${code})` : ''}.`);
1859
- // The default data space goes without saying; any other is named.
1860
- if (effectiveScope !== 'default')
1861
- this.log(`Data space: ${effectiveScope}.`);
1862
- const groups = new Set([
1863
- ...outputTypes,
1864
- ...envelope.result.items.map((item) => item.family ?? 'dmo'),
1865
- ]);
1866
- const printError = (diagnostic) => {
1867
- this.log(formatDiagnostic(diagnostic, diagnostic.identity
1868
- ? `${errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'}:${diagnostic.identity.apiName}: `
1869
- : ''));
1870
- };
1871
- for (const family of groups) {
1872
- const items = envelope.result.items.filter((item) => (item.family ?? 'dmo') === family);
1873
- for (const item of items)
1874
- this.log(`Downloaded ${family}:${item.identity.apiName} (${item.outcome}).`);
1875
- for (const diagnostic of envelope.diagnostics.errors)
1876
- if (diagnostic.identity &&
1877
- (errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo') === family)
1878
- printError(diagnostic);
1879
- this.log(`Downloaded ${family}: ${items.length}`);
1880
- }
1881
- for (const diagnostic of envelope.diagnostics.errors)
1882
- if (!diagnostic.identity ||
1883
- !groups.has(errorTypes.get(diagnostic) ?? diagnostic.family ?? 'dmo'))
1884
- printError(diagnostic);
1885
- for (const warning of envelope.diagnostics.warnings)
1886
- this.log(`Warning: ${warning}`);
1887
- }
1888
- return envelope;
1943
+ return { envelope, code, outputTypes, errorTypes, effectiveScope };
1889
1944
  };
1890
1945
  const context = {
1891
1946
  flags,
@@ -10,6 +10,7 @@ import { operationDiagnostic } from '../../../../services/operation-diagnostic.j
10
10
  import { openBoundSsot } from '../../../../transport/bound-ssot.js';
11
11
  import { ConnectError } from '../../../../transport/connect-client.js';
12
12
  import { annotateDiagnostics, formatDiagnostic } from '../../../../errors/registry.js';
13
+ import { exitCodeOf } from '../../../../exit-code.js';
13
14
  /**
14
15
  * Export the members of one published segment as CSV or JSON rows: a data export, written
15
16
  * outside the `data360/` definition folders.
@@ -299,8 +300,9 @@ export default class SegmentMembersExport extends SfCommand {
299
300
  * @returns {SegmentMembersEnvelope} The same receipt.
300
301
  */
301
302
  finish(envelope) {
302
- if (envelope.status !== 'success')
303
- process.exitCode = 1;
303
+ const exitCode = exitCodeOf(envelope);
304
+ if (exitCode !== 0)
305
+ process.exitCode = exitCode;
304
306
  annotateDiagnostics(envelope);
305
307
  if (!this.jsonEnabled()) {
306
308
  const { result } = envelope;
@@ -36,6 +36,7 @@ export const hints = {
36
36
  NATIVE_INVENTORY_UNCONFIRMED: 'The list of DLOs or DMOs from the org could not be confirmed complete, so nothing was retrieved. Retrieve exact members with -m dmo:<Name> or -m dlo:<Name>, or rerun later.',
37
37
  NATIVE_PARENT_SETTLEMENT_UNCONFIRMED: 'A parent DLO or DMO was written but could not be confirmed ready, so dependent items were not deployed. Wait, check the parent with deploy --preview, then rerun.',
38
38
  NATIVE_RETRIEVE_FAILED: 'This DLO, DMO, mapping or relationship could not be retrieved for a reason without a more specific code. Read the message, check the org session, then rerun.',
39
+ NOTHING_TO_DEPLOY: 'Every selected file was a verbatim file and was skipped, so there was nothing to deploy and nothing was sent. Select files the plugin can represent, or retrieve the objects again.',
39
40
  OUTPUT_CHANGED: 'The target file changed on disk while the plugin was writing it, so the write stopped. Make sure nothing else edits the project during the run, then rerun.',
40
41
  OUTPUT_FAILED: 'The retrieved definition could not be written to the project. Check that the output folder is writable, has free space and that the temp folder settings are valid, then rerun.',
41
42
  OVERWRITE_REQUIRED: 'A different version of this file already exists in the project. Compare it with the org, then rerun with --overwrite (-x) to replace it, or keep your local file.',
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Salesforce CLI exit code for a command envelope's top-level status.
3
+ * success and accepted (--async) are 0, partial is 68, processing is 69, anything else is 1.
4
+ * @param {object} envelope Command envelope (or any object with its status).
5
+ * @param {string} envelope.status Top-level envelope status.
6
+ * @returns {0 | 1 | 68 | 69} The exit code.
7
+ */
8
+ export declare function exitCodeOf(envelope: {
9
+ status: string;
10
+ }): 0 | 1 | 68 | 69;