UNPKG

11.8 kBTypeScriptView Raw
1import { AnyJson } from '@salesforce/ts-types';
2import { SfError } from './sfError';
3export type Tokens = Array<string | boolean | number | null | undefined>;
4export type StructuredMessage = {
5 message: string;
6 name: string;
7 actions?: string[];
8};
9/**
10 * A loader function to return messages.
11 *
12 * @param locale The local set by the framework.
13 */
14export type LoaderFunction<T extends string> = (locale: string) => Messages<T>;
15export type StoredMessage = string | string[] | {
16 [s: string]: StoredMessage;
17};
18export type StoredMessageMap = Map<string, StoredMessage>;
19/**
20 * The core message framework manages messages and allows them to be accessible by
21 * all plugins and consumers of sfdx-core. It is set up to handle localization down
22 * the road at no additional effort to the consumer. Messages can be used for
23 * anything from user output (like the console), to error messages, to returned
24 * data from a method.
25 *
26 * Messages are loaded from loader functions. The loader functions will only run
27 * when a message is required. This prevents all messages from being loaded into memory at
28 * application startup. The functions can load from memory, a file, or a server.
29 *
30 * In the beginning of your app or file, add the loader functions to be used later. If using
31 * json or js files in a root messages directory (`<moduleRoot>/messages`), load the entire directory
32 * automatically with {@link Messages.importMessagesDirectory}. Message files must be the following formates.
33 *
34 * A `.json` file:
35 * ```json
36 * {
37 * "msgKey": "A message displayed in the user",
38 * "msgGroup": {
39 * "anotherMsgKey": "Another message displayed to the user"
40 * },
41 * "listOfMessage": ["message1", "message2"]
42 * }
43 * ```
44 *
45 * A `.js` file:
46 * ```javascript
47 * module.exports = {
48 * msgKey: 'A message displayed in the user',
49 * msgGroup: {
50 * anotherMsgKey: 'Another message displayed to the user'
51 * },
52 * listOfMessage: ['message1', 'message2']
53 * }
54 * ```
55 *
56 * A `.md` file:
57 * ```markdown
58 * # msgKey
59 * A message displayed in the user
60 *
61 * # msgGroup.anotherMsgKey
62 * Another message displayed to the user
63 *
64 * # listOfMessage
65 * - message1
66 * - message2
67 * ```
68 *
69 * The values support [util.format](https://nodejs.org/api/util.html#util_util_format_format_args) style strings
70 * that apply the tokens passed into {@link Message.getMessage}
71 *
72 * **Note:** When running unit tests individually, you may see errors that the messages aren't found.
73 * This is because `index.js` isn't loaded when tests run like they are when the package is required.
74 * To allow tests to run, import the message directory in each test (it will only
75 * do it once) or load the message file the test depends on individually.
76 *
77 * ```typescript
78 * // Create loader functions for all files in the messages directory
79 * Messages.importMessagesDirectory(__dirname);
80 *
81 * // or, for ESM code
82 * Messages.importMessagesDirectoryFromMetaUrl(import.meta.url)
83 *
84 * // Now you can use the messages from anywhere in your code or file.
85 * // If using importMessageDirectory, the bundle name is the file name.
86 * const messages: Messages = Messages.loadMessages(packageName, bundleName);
87 *
88 * // Messages now contains all the message in the bundleName file.
89 * messages.getMessage('authInfoCreationError');
90 * ```
91 */
92export declare class Messages<T extends string> {
93 readonly messages: StoredMessageMap;
94 private static loaders;
95 private static bundles;
96 /**
97 * The locale of the messages in this bundle.
98 */
99 readonly locale: string;
100 /**
101 * The bundle name.
102 */
103 readonly bundleName: string;
104 /**
105 * Create a new messages bundle.
106 *
107 * **Note:** Use {Messages.loadMessages} unless you are writing your own loader function.
108 *
109 * @param bundleName The bundle name.
110 * @param locale The locale.
111 * @param messages The messages. Can not be modified once created.
112 */
113 constructor(bundleName: string, locale: string, messages: StoredMessageMap);
114 /**
115 * Internal readFile. Exposed for unit testing. Do not use util/fs.readFile as messages.js
116 * should have no internal dependencies.
117 *
118 * @param filePath read file target.
119 * @ignore
120 */
121 static readFile: (filePath: string) => AnyJson;
122 /**
123 * Get the locale. This will always return 'en_US' but will return the
124 * machine's locale in the future.
125 */
126 static getLocale(): string;
127 /**
128 * Set a custom loader function for a package and bundle that will be called on {@link Messages.loadMessages}.
129 *
130 * @param packageName The npm package name.
131 * @param bundle The name of the bundle.
132 * @param loader The loader function.
133 */
134 static setLoaderFunction(packageName: string, bundle: string, loader: LoaderFunction<string>): void;
135 /**
136 * Generate a file loading function. Use {@link Messages.importMessageFile} unless
137 * overriding the bundleName is required, then manually pass the loader
138 * function to {@link Messages.setLoaderFunction}.
139 *
140 * @param bundleName The name of the bundle.
141 * @param filePath The messages file path.
142 */
143 static generateFileLoaderFunction(bundleName: string, filePath: string): LoaderFunction<string>;
144 /**
145 * Add a single message file to the list of loading functions using the file name as the bundle name.
146 * The loader will only be added if the bundle name is not already taken.
147 *
148 * @param packageName The npm package name.
149 * @param filePath The path of the file.
150 */
151 static importMessageFile(packageName: string, filePath: string): void;
152 /**
153 * Support ESM plugins who can't use __dirname
154 *
155 * @param metaUrl pass in `import.meta.url`
156 * @param truncateToProjectPath Will look for the messages directory in the project root (where the package.json file is located).
157 * i.e., the module is typescript and the messages folder is in the top level of the module directory.
158 * @param packageName The npm package name. Figured out from the root directory's package.json.
159 */
160 static importMessagesDirectoryFromMetaUrl(metaUrl: string, truncateToProjectPath?: boolean, packageName?: string): void;
161 /**
162 * Import all json and js files in a messages directory. Use the file name as the bundle key when
163 * {@link Messages.loadMessages} is called. By default, we're assuming the moduleDirectoryPart is a
164 * typescript project and will truncate to root path (where the package.json file is). If your messages
165 * directory is in another spot or you are not using typescript, pass in false for truncateToProjectPath.
166 *
167 * ```
168 * // e.g. If your message directory is in the project root, you would do:
169 * Messages.importMessagesDirectory(__dirname);
170 * ```
171 *
172 * @param moduleDirectoryPath The path to load the messages folder.
173 * @param truncateToProjectPath Will look for the messages directory in the project root (where the package.json file is located).
174 * i.e., the module is typescript and the messages folder is in the top level of the module directory.
175 * @param packageName The npm package name. Figured out from the root directory's package.json.
176 */
177 static importMessagesDirectory(moduleDirectoryPath: string, truncateToProjectPath?: boolean, packageName?: string): void;
178 /**
179 * Load messages for a given package and bundle. If the bundle is not already cached, use the loader function
180 * created from {@link Messages.setLoaderFunction} or {@link Messages.importMessagesDirectory}.
181 *
182 * ```typescript
183 * Messages.importMessagesDirectory(__dirname);
184 * const messages = Messages.loadMessages('packageName', 'bundleName');
185 * ```
186 *
187 * @param packageName The name of the npm package.
188 * @param bundleName The name of the bundle to load.
189 */
190 static loadMessages(packageName: string, bundleName: string): Messages<string>;
191 /**
192 * Check if a bundle already been loaded.
193 *
194 * @param packageName The npm package name.
195 * @param bundleName The bundle name.
196 */
197 static isCached(packageName: string, bundleName: string): boolean;
198 /**
199 * Get a message using a message key and use the tokens as values for tokenization.
200 *
201 * If the key happens to be an array of messages, it will combine with OS.EOL.
202 *
203 * @param key The key of the message.
204 * @param tokens The values to substitute in the message.
205 *
206 * **See** https://nodejs.org/api/util.html#util_util_format_format_args
207 */
208 getMessage(key: T, tokens?: Tokens): string;
209 /**
210 * Get messages using a message key and use the tokens as values for tokenization.
211 *
212 * This will return all messages if the key is an array in the messages file.
213 *
214 * ```json
215 * {
216 * "myKey": [ "message1", "message2" ]
217 * }
218 * ```
219 *
220 * ```markdown
221 * # myKey
222 * * message1
223 * * message2
224 * ```
225 *
226 * @param key The key of the messages.
227 * @param tokens The values to substitute in the message.
228 *
229 * **See** https://nodejs.org/api/util.html#util_util_format_format_args
230 */
231 getMessages(key: T, tokens?: Tokens): string[];
232 /**
233 * Convenience method to create errors using message labels.
234 *
235 * `error.name` will be the upper-cased key, remove prefixed `error.` and will always end in Error.
236 * `error.actions` will be loaded using `${key}.actions` if available.
237 *
238 * @param key The key of the error message.
239 * @param tokens The error message tokens.
240 * @param actionTokens The action messages tokens.
241 * @param exitCodeOrCause The exit code which will be used by SfdxCommand or the underlying error that caused this error to be raised.
242 * @param cause The underlying error that caused this error to be raised.
243 */
244 createError(key: T, tokens?: Tokens, actionTokens?: Tokens, exitCodeOrCause?: number | Error, cause?: Error): SfError;
245 /**
246 * Convenience method to create warning using message labels.
247 *
248 * `warning.name` will be the upper-cased key, remove prefixed `warning.` and will always end in Warning.
249 * `warning.actions` will be loaded using `${key}.actions` if available.
250 *
251 * @param key The key of the warning message.
252 * @param tokens The warning message tokens.
253 * @param actionTokens The action messages tokens.
254 */
255 createWarning(key: T, tokens?: Tokens, actionTokens?: Tokens): StructuredMessage;
256 /**
257 * Convenience method to create info using message labels.
258 *
259 * `info.name` will be the upper-cased key, remove prefixed `info.` and will always end in Info.
260 * `info.actions` will be loaded using `${key}.actions` if available.
261 *
262 * @param key The key of the warning message.
263 * @param tokens The warning message tokens.
264 * @param actionTokens The action messages tokens.
265 */
266 createInfo(key: T, tokens?: Tokens, actionTokens?: Tokens): StructuredMessage;
267 /**
268 * Formats message contents given a message type, key, tokens and actions tokens
269 *
270 * `<type>.name` will be the upper-cased key, remove prefixed `<type>.` and will always end in 'Error | Warning | Info.
271 * `<type>.actions` will be loaded using `${key}.actions` if available.
272 *
273 * @param type The type of the message set must 'error' | 'warning' | 'info'.
274 * @param key The key of the warning message.
275 * @param tokens The warning message tokens.
276 * @param actionTokens The action messages tokens.
277 * @param preserveName Do not require that the name end in the type ('error' | 'warning' | 'info').
278 */
279 private formatMessageContents;
280 private getMessageWithMap;
281}