@slates/profiles 1.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.ts ADDED
@@ -0,0 +1,422 @@
1
+ import { execFileSync } from 'child_process';
2
+ import { randomUUID } from 'crypto';
3
+ import { mkdir, readFile, writeFile } from 'fs/promises';
4
+ import path from 'path';
5
+ import {
6
+ SlatesCliStoreData,
7
+ SlatesCliStoreScope,
8
+ SlatesOAuthCredentialRecord,
9
+ SlatesProfileRecord,
10
+ SlatesProfileTarget,
11
+ SlatesStoredAuth
12
+ } from './types';
13
+
14
+ type SlatesLegacyCliStoreData = {
15
+ version?: number;
16
+ currentProfileId: string | null;
17
+ profiles: Record<string, SlatesProfileRecord>;
18
+ };
19
+
20
+ let STORE_VERSION = 3 as const;
21
+ let CLI_DIR_NAME = '.slates-cli';
22
+ let PROFILES_DIR_NAME = 'profiles';
23
+ let STORE_FILE_NAME = 'store.json';
24
+ let GITIGNORE_FILE_NAME = '.gitignore';
25
+
26
+ let createEmptyStore = (): SlatesCliStoreData => ({
27
+ version: STORE_VERSION,
28
+ currentProfileId: null,
29
+ profiles: {},
30
+ oauthCredentials: {}
31
+ });
32
+
33
+ let now = () => new Date().toISOString();
34
+
35
+ let ensureDir = async (dirPath: string) => {
36
+ await mkdir(dirPath, { recursive: true });
37
+ };
38
+
39
+ let ensureGitIgnore = async (dirPath: string) => {
40
+ let filePath = path.join(dirPath, GITIGNORE_FILE_NAME);
41
+ await writeFile(filePath, '*\n!.gitignore\n', { encoding: 'utf-8' }).catch(async error => {
42
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return;
43
+ throw error;
44
+ });
45
+ };
46
+
47
+ export let resolveSlatesCliRoot = (cwd: string = process.cwd()) => {
48
+ try {
49
+ return execFileSync('git', ['rev-parse', '--show-toplevel'], {
50
+ cwd,
51
+ stdio: ['ignore', 'pipe', 'ignore'],
52
+ encoding: 'utf-8'
53
+ }).trim();
54
+ } catch {
55
+ return cwd;
56
+ }
57
+ };
58
+
59
+ export let resolveSlatesCliDir = (cwd: string = process.cwd()) =>
60
+ path.join(resolveSlatesCliRoot(cwd), CLI_DIR_NAME);
61
+
62
+ export let resolveSlatesCliProfilesDir = (cwd: string = process.cwd()) =>
63
+ path.join(resolveSlatesCliDir(cwd), PROFILES_DIR_NAME);
64
+
65
+ let normalizeScopeKey = (scopeKey: string) =>
66
+ path.posix.normalize(scopeKey.replace(/\\/g, '/')).replace(/^\.?\//, '');
67
+
68
+ let splitScopeKey = (scopeKey: string) =>
69
+ normalizeScopeKey(scopeKey)
70
+ .split('/')
71
+ .filter(Boolean)
72
+ .filter(segment => segment !== '.' && segment !== '..');
73
+
74
+ let resolveScopedStoreDir = (rootDir: string, scopeKey: string) =>
75
+ path.join(resolveSlatesCliProfilesDir(rootDir), ...splitScopeKey(scopeKey));
76
+
77
+ let resolveScopedStorePath = (rootDir: string, scopeKey: string) =>
78
+ path.join(resolveScopedStoreDir(rootDir, scopeKey), STORE_FILE_NAME);
79
+
80
+ let inferRootDirFromStorePath = (storePath: string) => {
81
+ let normalized = path.resolve(storePath);
82
+ let parts = normalized.split(path.sep).filter(Boolean);
83
+ let cliDirIndex = parts.lastIndexOf(CLI_DIR_NAME);
84
+
85
+ if (cliDirIndex === -1) {
86
+ throw new Error(`Could not infer Slates CLI root from store path: ${storePath}`);
87
+ }
88
+
89
+ let rootParts = parts.slice(0, cliDirIndex);
90
+ return path.join(path.sep, ...rootParts);
91
+ };
92
+
93
+ let resolveScopeKeyFromStorePath = (rootDir: string, storePath: string) => {
94
+ let profilesDir = resolveSlatesCliProfilesDir(rootDir);
95
+ let relativeDir = path.relative(profilesDir, path.dirname(storePath));
96
+ if (!relativeDir || relativeDir.startsWith('..') || path.isAbsolute(relativeDir)) {
97
+ return null;
98
+ }
99
+
100
+ return normalizeScopeKey(relativeDir);
101
+ };
102
+
103
+ let readStoreData = async <
104
+ T extends { currentProfileId: string | null; profiles: Record<string, any> }
105
+ >(
106
+ storePath: string
107
+ ): Promise<T | null> => {
108
+ try {
109
+ let raw = await readFile(storePath, 'utf-8');
110
+ if (!raw.trim()) {
111
+ return null;
112
+ }
113
+
114
+ return JSON.parse(raw) as T;
115
+ } catch (error) {
116
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
117
+ return null;
118
+ }
119
+
120
+ throw error;
121
+ }
122
+ };
123
+
124
+ let isProfileInScope = (rootDir: string, scopeKey: string, profile: SlatesProfileRecord) => {
125
+ if (profile.target.type !== 'local') {
126
+ return false;
127
+ }
128
+
129
+ let scopeDir = path.resolve(rootDir, ...splitScopeKey(scopeKey));
130
+ let entryPath = path.isAbsolute(profile.target.entry)
131
+ ? profile.target.entry
132
+ : path.resolve(rootDir, profile.target.entry);
133
+ let relative = path.relative(scopeDir, entryPath);
134
+ return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
135
+ };
136
+
137
+ let loadMigratedLegacyStore = async (
138
+ rootDir: string,
139
+ scopeKey: string
140
+ ): Promise<SlatesCliStoreData> => {
141
+ let legacyStorePath = path.join(resolveSlatesCliDir(rootDir), STORE_FILE_NAME);
142
+ let legacy = await readStoreData<SlatesLegacyCliStoreData>(legacyStorePath);
143
+ if (!legacy) {
144
+ return createEmptyStore();
145
+ }
146
+
147
+ let profiles = Object.fromEntries(
148
+ Object.entries(legacy.profiles ?? {}).filter(([, profile]) =>
149
+ isProfileInScope(rootDir, scopeKey, profile)
150
+ )
151
+ );
152
+
153
+ let currentProfileId =
154
+ legacy.currentProfileId && profiles[legacy.currentProfileId]
155
+ ? legacy.currentProfileId
156
+ : null;
157
+
158
+ return {
159
+ version: STORE_VERSION,
160
+ currentProfileId,
161
+ profiles,
162
+ oauthCredentials: {}
163
+ };
164
+ };
165
+
166
+ export class SlatesCliStore {
167
+ constructor(
168
+ readonly rootDir: string,
169
+ readonly dirPath: string,
170
+ readonly storePath: string,
171
+ readonly scope: SlatesCliStoreScope | null,
172
+ readonly data: SlatesCliStoreData
173
+ ) {}
174
+
175
+ static async open(
176
+ opts: { cwd?: string; scope?: SlatesCliStoreScope; storePath?: string } = {}
177
+ ) {
178
+ let rootDir = opts.storePath
179
+ ? inferRootDirFromStorePath(opts.storePath)
180
+ : resolveSlatesCliRoot(opts.cwd);
181
+ let cliDir = resolveSlatesCliDir(rootDir);
182
+ let scopeKey = opts.storePath
183
+ ? resolveScopeKeyFromStorePath(rootDir, opts.storePath)
184
+ : opts.scope?.key
185
+ ? normalizeScopeKey(opts.scope.key)
186
+ : null;
187
+ let dirPath = opts.storePath
188
+ ? path.dirname(opts.storePath)
189
+ : scopeKey
190
+ ? resolveScopedStoreDir(rootDir, scopeKey)
191
+ : cliDir;
192
+ let storePath =
193
+ opts.storePath ??
194
+ (scopeKey
195
+ ? resolveScopedStorePath(rootDir, scopeKey)
196
+ : path.join(cliDir, STORE_FILE_NAME));
197
+
198
+ await ensureDir(cliDir);
199
+ await ensureGitIgnore(cliDir);
200
+ await ensureDir(dirPath);
201
+
202
+ let parsed = await readStoreData<SlatesCliStoreData>(storePath);
203
+ let data = parsed
204
+ ? {
205
+ version: STORE_VERSION,
206
+ currentProfileId: parsed.currentProfileId ?? null,
207
+ profiles: parsed.profiles ?? {},
208
+ oauthCredentials: parsed.oauthCredentials ?? {}
209
+ }
210
+ : scopeKey
211
+ ? await loadMigratedLegacyStore(rootDir, scopeKey)
212
+ : createEmptyStore();
213
+
214
+ if (!parsed) {
215
+ await writeFile(storePath, JSON.stringify(data, null, 2) + '\n', 'utf-8');
216
+ }
217
+
218
+ return new SlatesCliStore(
219
+ rootDir,
220
+ dirPath,
221
+ storePath,
222
+ scopeKey ? { key: scopeKey, name: opts.scope?.name } : null,
223
+ data
224
+ );
225
+ }
226
+
227
+ async save() {
228
+ await ensureDir(this.dirPath);
229
+ await ensureDir(resolveSlatesCliDir(this.rootDir));
230
+ await ensureGitIgnore(resolveSlatesCliDir(this.rootDir));
231
+ await writeFile(this.storePath, JSON.stringify(this.data, null, 2) + '\n', 'utf-8');
232
+ }
233
+
234
+ listProfiles() {
235
+ return Object.values(this.data.profiles).sort((a, b) => a.name.localeCompare(b.name));
236
+ }
237
+
238
+ listOAuthCredentials(authMethodId?: string) {
239
+ return Object.values(this.data.oauthCredentials)
240
+ .filter(credential => !authMethodId || credential.authMethodId === authMethodId)
241
+ .sort((a, b) => a.name.localeCompare(b.name));
242
+ }
243
+
244
+ getOAuthCredential(credentialId?: string | null, authMethodId?: string | null) {
245
+ if (credentialId) {
246
+ let direct = this.data.oauthCredentials[credentialId];
247
+ if (direct && (!authMethodId || direct.authMethodId === authMethodId)) {
248
+ return direct;
249
+ }
250
+
251
+ let matches = this.listOAuthCredentials(authMethodId ?? undefined).filter(
252
+ credential => credential.name === credentialId
253
+ );
254
+ if (matches.length === 1) {
255
+ return matches[0]!;
256
+ }
257
+ }
258
+
259
+ return this.listOAuthCredentials(authMethodId ?? undefined)[0] ?? null;
260
+ }
261
+
262
+ getProfile(profileId?: string | null) {
263
+ if (profileId) {
264
+ if (this.data.profiles[profileId]) {
265
+ return this.data.profiles[profileId] ?? null;
266
+ }
267
+
268
+ let matches = this.listProfiles().filter(profile => profile.name === profileId);
269
+ if (matches.length === 1) {
270
+ return matches[0]!;
271
+ }
272
+ }
273
+
274
+ if (this.data.currentProfileId && this.data.profiles[this.data.currentProfileId]) {
275
+ return this.data.profiles[this.data.currentProfileId]!;
276
+ }
277
+
278
+ return this.listProfiles()[0] ?? null;
279
+ }
280
+
281
+ requireProfile(profileId?: string | null) {
282
+ let profile = this.getProfile(profileId);
283
+ if (!profile) {
284
+ throw new Error('No Slates profile found for this integration.');
285
+ }
286
+
287
+ return profile;
288
+ }
289
+
290
+ upsertProfile(d: {
291
+ profileId?: string;
292
+ name: string;
293
+ target: SlatesProfileTarget;
294
+ config?: SlatesProfileRecord['config'];
295
+ session?: SlatesProfileRecord['session'];
296
+ metadata?: SlatesProfileRecord['metadata'];
297
+ }) {
298
+ let existing = d.profileId ? this.data.profiles[d.profileId] : undefined;
299
+ let id = existing?.id ?? d.profileId ?? randomUUID();
300
+ let createdAt = existing?.createdAt ?? now();
301
+
302
+ let profile: SlatesProfileRecord = {
303
+ id,
304
+ name: d.name,
305
+ target: d.target,
306
+ config: d.config ?? existing?.config ?? null,
307
+ auth: existing?.auth ?? {},
308
+ session: d.session ?? existing?.session ?? null,
309
+ metadata: {
310
+ provider: d.metadata?.provider ?? existing?.metadata?.provider ?? null,
311
+ actions: d.metadata?.actions ?? existing?.metadata?.actions ?? null
312
+ },
313
+ createdAt,
314
+ updatedAt: now()
315
+ };
316
+
317
+ this.data.profiles[id] = profile;
318
+ if (!this.data.currentProfileId) {
319
+ this.data.currentProfileId = id;
320
+ }
321
+
322
+ return profile;
323
+ }
324
+
325
+ upsertOAuthCredential(d: {
326
+ credentialId?: string;
327
+ name: string;
328
+ authMethodId: string;
329
+ clientId: string;
330
+ clientSecret: string;
331
+ }) {
332
+ let existing = d.credentialId ? this.data.oauthCredentials[d.credentialId] : undefined;
333
+ let id = existing?.id ?? d.credentialId ?? randomUUID();
334
+ let credential: SlatesOAuthCredentialRecord = {
335
+ id,
336
+ name: d.name,
337
+ authMethodId: d.authMethodId,
338
+ clientId: d.clientId,
339
+ clientSecret: d.clientSecret,
340
+ createdAt: existing?.createdAt ?? now(),
341
+ updatedAt: now()
342
+ };
343
+
344
+ this.data.oauthCredentials[id] = credential;
345
+ return credential;
346
+ }
347
+
348
+ setCurrentProfile(profileId: string) {
349
+ if (!this.data.profiles[profileId]) {
350
+ throw new Error(`Unknown profile: ${profileId}`);
351
+ }
352
+
353
+ this.data.currentProfileId = profileId;
354
+ }
355
+
356
+ removeProfile(profileId: string) {
357
+ delete this.data.profiles[profileId];
358
+
359
+ if (this.data.currentProfileId === profileId) {
360
+ this.data.currentProfileId = this.listProfiles()[0]?.id ?? null;
361
+ }
362
+ }
363
+
364
+ setProfileConfig(profileId: string, config: SlatesProfileRecord['config']) {
365
+ let profile = this.requireProfile(profileId);
366
+ profile.config = config;
367
+ profile.updatedAt = now();
368
+ return profile;
369
+ }
370
+
371
+ setProfileSession(profileId: string, session: SlatesProfileRecord['session']) {
372
+ let profile = this.requireProfile(profileId);
373
+ profile.session = session;
374
+ profile.updatedAt = now();
375
+ return profile;
376
+ }
377
+
378
+ setProfileMetadata(profileId: string, metadata: Partial<SlatesProfileRecord['metadata']>) {
379
+ let profile = this.requireProfile(profileId);
380
+ profile.metadata = {
381
+ provider: metadata.provider ?? profile.metadata.provider ?? null,
382
+ actions: metadata.actions ?? profile.metadata.actions ?? null
383
+ };
384
+ profile.updatedAt = now();
385
+ return profile;
386
+ }
387
+
388
+ upsertAuth(
389
+ profileId: string,
390
+ auth: Omit<SlatesStoredAuth, 'id' | 'createdAt' | 'updatedAt'> & { id?: string }
391
+ ) {
392
+ let profile = this.requireProfile(profileId);
393
+ let existing = profile.auth[auth.authMethodId];
394
+
395
+ profile.auth[auth.authMethodId] = {
396
+ ...auth,
397
+ id: auth.id ?? existing?.id ?? randomUUID(),
398
+ createdAt: existing?.createdAt ?? now(),
399
+ updatedAt: now()
400
+ };
401
+ profile.updatedAt = now();
402
+
403
+ return profile.auth[auth.authMethodId]!;
404
+ }
405
+
406
+ getAuth(profileId: string, authMethodId?: string | null) {
407
+ let profile = this.requireProfile(profileId);
408
+ if (authMethodId) return profile.auth[authMethodId] ?? null;
409
+ return Object.values(profile.auth)[0] ?? null;
410
+ }
411
+
412
+ listAuth(profileId: string) {
413
+ let profile = this.requireProfile(profileId);
414
+ return Object.values(profile.auth).sort((a, b) =>
415
+ a.authMethodId.localeCompare(b.authMethodId)
416
+ );
417
+ }
418
+ }
419
+
420
+ export let openSlatesCliStore = async (
421
+ opts: { cwd?: string; scope?: SlatesCliStoreScope; storePath?: string } = {}
422
+ ) => SlatesCliStore.open(opts);
package/src/types.ts ADDED
@@ -0,0 +1,67 @@
1
+ import { SlatesJsonObject } from '@slates/client';
2
+ import { SlateAuthenticationMethod, SlatesAction } from '@slates/proto';
3
+
4
+ export interface SlatesStoredAuth {
5
+ id: string;
6
+ authMethodId: string;
7
+ authMethodName?: string;
8
+ authType: SlateAuthenticationMethod['type'];
9
+ input: SlatesJsonObject;
10
+ output: SlatesJsonObject;
11
+ scopes: string[];
12
+ oauthCredentialId?: string;
13
+ clientId?: string;
14
+ clientSecret?: string;
15
+ callbackState?: SlatesJsonObject | null;
16
+ profile?: SlatesJsonObject | null;
17
+ createdAt: string;
18
+ updatedAt: string;
19
+ }
20
+
21
+ export interface SlatesOAuthCredentialRecord {
22
+ id: string;
23
+ name: string;
24
+ authMethodId: string;
25
+ clientId: string;
26
+ clientSecret: string;
27
+ createdAt: string;
28
+ updatedAt: string;
29
+ }
30
+
31
+ export interface SlatesLocalProfileTarget {
32
+ type: 'local';
33
+ entry: string;
34
+ exportName?: string;
35
+ }
36
+
37
+ export type SlatesProfileTarget = SlatesLocalProfileTarget;
38
+
39
+ export interface SlatesCliStoreScope {
40
+ key: string;
41
+ name?: string;
42
+ }
43
+
44
+ export interface SlatesProfileRecord {
45
+ id: string;
46
+ name: string;
47
+ target: SlatesProfileTarget;
48
+ config: SlatesJsonObject | null;
49
+ auth: Record<string, SlatesStoredAuth>;
50
+ session: {
51
+ id: string;
52
+ state: SlatesJsonObject;
53
+ } | null;
54
+ metadata: {
55
+ provider?: SlatesJsonObject | null;
56
+ actions?: SlatesAction[] | null;
57
+ };
58
+ createdAt: string;
59
+ updatedAt: string;
60
+ }
61
+
62
+ export interface SlatesCliStoreData {
63
+ version: 3;
64
+ currentProfileId: string | null;
65
+ profiles: Record<string, SlatesProfileRecord>;
66
+ oauthCredentials: Record<string, SlatesOAuthCredentialRecord>;
67
+ }