forked from salesforcecli/plugin-lightning-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetaUtils.ts
More file actions
255 lines (218 loc) · 9.54 KB
/
metaUtils.ts
File metadata and controls
255 lines (218 loc) · 9.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
/*
* Copyright 2026, Salesforce, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Connection, Logger, Messages } from '@salesforce/core';
import { PromptUtils } from './promptUtils.js';
type LightningExperienceSettingsMetadata = {
[key: string]: unknown;
fullName?: string;
enableLightningPreviewPref?: string | boolean;
};
type MyDomainSettingsMetadata = {
[key: string]: unknown;
fullName?: string;
isFirstPartyCookieUseRequired?: string | boolean;
};
type MetadataUpdateResult = {
success: boolean;
fullName: string;
errors?: Array<{ message: string }>;
};
const sharedMessages = Messages.loadMessages('@salesforce/plugin-lightning-dev', 'shared.utils');
/**
* Utility class for managing Salesforce metadata settings related to Lightning Development.
*/
export class MetaUtils {
private static logger = Logger.childFromRoot('metaUtils');
/**
* Retrieves the Lightning Experience Settings metadata from the org.
*
* @param connection the connection to the org
* @returns LightningExperienceSettingsMetadata object containing the settings
* @throws Error if unable to retrieve the metadata
*/
public static async getLightningExperienceSettings(
connection: Connection
): Promise<LightningExperienceSettingsMetadata> {
this.logger.debug('Retrieving Lightning Experience Settings metadata');
const metadata = await connection.metadata.read('LightningExperienceSettings', 'enableLightningPreviewPref');
if (!metadata) {
throw new Error('Unable to retrieve Lightning Experience Settings metadata.');
}
if (Array.isArray(metadata)) {
if (metadata.length === 0) {
throw new Error('Lightning Experience Settings metadata response was empty.');
}
return metadata[0] as LightningExperienceSettingsMetadata;
}
return metadata as LightningExperienceSettingsMetadata;
}
/**
* Checks if Lightning Preview (Local Dev) is enabled for the org.
*
* @param connection the connection to the org
* @returns boolean indicating whether Lightning Preview is enabled
*/
public static async isLightningPreviewEnabled(connection: Connection): Promise<boolean> {
try {
const settings = await this.getLightningExperienceSettings(connection);
const flagValue = settings.enableLightningPreviewPref ?? 'false';
const enabled = String(flagValue).toLowerCase().trim() === 'true';
this.logger.debug(`Lightning Preview enabled: ${enabled}`);
return enabled;
} catch (error) {
this.logger.warn('Error checking Lightning Preview status, assuming disabled:', error);
return false;
}
}
/**
* Enables or disables Lightning Preview (Local Dev) for the org by updating the metadata.
*
* @param connection the connection to the org
* @param enable boolean indicating whether to enable (true) or disable (false) Lightning Preview
* @throws Error if the metadata update fails
*/
public static async setLightningPreviewEnabled(connection: Connection, enable: boolean): Promise<void> {
this.logger.debug(`Setting Lightning Preview enabled to: ${enable}`);
const updateResult = await connection.metadata.update('LightningExperienceSettings', {
fullName: 'enableLightningPreviewPref',
enableLightningPreviewPref: enable ? 'true' : 'false',
});
const results = Array.isArray(updateResult) ? updateResult : [updateResult];
const typedResults = results as MetadataUpdateResult[];
const errors = typedResults.filter((result) => !result.success);
if (errors.length > 0) {
const message = errors
.flatMap((result) => (Array.isArray(result.errors) ? result.errors : result.errors ? [result.errors] : []))
.filter((error): error is { message: string } => Boolean(error))
.map((error) => error.message)
.join(' ');
throw new Error(message || 'Failed to update Lightning Preview setting.');
}
this.logger.debug('Successfully updated Lightning Preview setting');
}
/**
* Retrieves the My Domain Settings metadata from the org.
*
* @param connection the connection to the org
* @returns MyDomainSettingsMetadata object containing the settings
* @throws Error if unable to retrieve the metadata
*/
public static async getMyDomainSettings(connection: Connection): Promise<MyDomainSettingsMetadata> {
this.logger.debug('Retrieving My Domain Settings metadata');
const metadata = await connection.metadata.read('MyDomainSettings', 'MyDomain');
if (!metadata) {
throw new Error('Unable to retrieve My Domain settings metadata.');
}
if (Array.isArray(metadata)) {
if (metadata.length === 0) {
throw new Error('My Domain settings metadata response was empty.');
}
return metadata[0] as MyDomainSettingsMetadata;
}
return metadata as MyDomainSettingsMetadata;
}
/**
* Checks if first-party cookies are required for the org.
*
* @param connection the connection to the org
* @returns boolean indicating whether first-party cookies are required
*/
public static async isFirstPartyCookieRequired(connection: Connection): Promise<boolean> {
try {
const settings = await this.getMyDomainSettings(connection);
const flagValue = settings.isFirstPartyCookieUseRequired ?? 'false';
const required = String(flagValue).toLowerCase().trim() === 'true';
this.logger.debug(`First-party cookie required: ${required}`);
return required;
} catch (error) {
this.logger.warn('Error checking first-party cookie requirement, assuming not required:', error);
return false;
}
}
/**
* Updates the My Domain setting that controls whether first-party cookies are required.
*
* @param connection the connection to the org
* @param requireFirstPartyCookies boolean indicating whether to require first-party cookies
* @throws Error if the metadata update fails
*/
public static async setMyDomainFirstPartyCookieRequirement(
connection: Connection,
requireFirstPartyCookies: boolean
): Promise<void> {
this.logger.debug(`Setting first-party cookie requirement to: ${requireFirstPartyCookies}`);
const updateResult = await connection.metadata.update('MyDomainSettings', {
fullName: 'MyDomain',
isFirstPartyCookieUseRequired: requireFirstPartyCookies ? 'true' : 'false',
});
const results = Array.isArray(updateResult) ? updateResult : [updateResult];
const typedResults = results as MetadataUpdateResult[];
const errors = typedResults.filter((result) => !result.success);
if (errors.length > 0) {
const message = errors
.flatMap((result) => (Array.isArray(result.errors) ? result.errors : result.errors ? [result.errors] : []))
.filter((error): error is { message: string } => Boolean(error))
.map((error) => error.message)
.join(' ');
throw new Error(message || 'Failed to update My Domain first-party cookie requirement.');
}
this.logger.debug('Successfully updated first-party cookie requirement');
}
/**
* Ensures first-party cookies are not required for the org. If they are required, this method will disable the requirement.
*
* @param connection the connection to the org
* @returns boolean indicating whether first-party cookies were already not required (true) or had to be disabled (false)
*/
public static async ensureFirstPartyCookiesNotRequired(connection: Connection): Promise<boolean> {
const isRequired = await this.isFirstPartyCookieRequired(connection);
if (isRequired) {
this.logger.info('First-party cookies are required. Disabling requirement...');
await this.setMyDomainFirstPartyCookieRequirement(connection, false);
return false;
}
this.logger.debug('First-party cookies are not required');
return true;
}
/**
* Enables local dev if required and permitted. If executed via VSCode command
* the user's response is already assigned to AUTO_ENABLE_LOCAL_DEV and it will be used.
* If executed via command line, this method will prompt the user.
*
* @param connection the connection to the org
* @returns true if enabled
* @throws local dev not enabled error if not enabled
*/
public static async handleLocalDevEnablement(connection: Connection): Promise<boolean | undefined> {
const isLightningPreviewEnabled = await this.isLightningPreviewEnabled(connection);
if (!isLightningPreviewEnabled) {
const autoEnableLocalDev = process.env.AUTO_ENABLE_LOCAL_DEV;
// If executed via VSCode command, autoEnableLocalDev will contain the users choice, provided via UI.
// Else, prompt the user on the command line.
const enableLocalDev =
autoEnableLocalDev !== undefined
? autoEnableLocalDev === 'true'
: await PromptUtils.promptUserToEnableLocalDev();
if (enableLocalDev) {
await this.setLightningPreviewEnabled(connection, true);
await this.ensureFirstPartyCookiesNotRequired(connection);
return true;
} else {
throw new Error(sharedMessages.getMessage('error.localdev.not.enabled'));
}
}
}
}