@powersync/cli-core 0.9.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.
Files changed (49) hide show
  1. package/LICENSE +67 -0
  2. package/README.md +24 -0
  3. package/dist/api/validate-sync-config.d.ts +63 -0
  4. package/dist/api/validate-sync-config.js +103 -0
  5. package/dist/clients/AccountsHubClientSDKClient.d.ts +67 -0
  6. package/dist/clients/AccountsHubClientSDKClient.js +66 -0
  7. package/dist/clients/cli-client-headers.d.ts +10 -0
  8. package/dist/clients/cli-client-headers.js +28 -0
  9. package/dist/clients/create-cloud-client.d.ts +6 -0
  10. package/dist/clients/create-cloud-client.js +36 -0
  11. package/dist/clients/create-self-hosted-client.d.ts +10 -0
  12. package/dist/clients/create-self-hosted-client.js +21 -0
  13. package/dist/command-types/CloudInstanceCommand.d.ts +62 -0
  14. package/dist/command-types/CloudInstanceCommand.js +190 -0
  15. package/dist/command-types/HelpGroup.d.ts +23 -0
  16. package/dist/command-types/HelpGroup.js +25 -0
  17. package/dist/command-types/InstanceCommand.d.ts +15 -0
  18. package/dist/command-types/InstanceCommand.js +42 -0
  19. package/dist/command-types/PowerSyncCommand.d.ts +29 -0
  20. package/dist/command-types/PowerSyncCommand.js +37 -0
  21. package/dist/command-types/SelfHostedInstanceCommand.d.ts +25 -0
  22. package/dist/command-types/SelfHostedInstanceCommand.js +97 -0
  23. package/dist/command-types/SharedInstanceCommand.d.ts +51 -0
  24. package/dist/command-types/SharedInstanceCommand.js +217 -0
  25. package/dist/index.d.ts +25 -0
  26. package/dist/index.js +25 -0
  27. package/dist/services/Services.d.ts +6 -0
  28. package/dist/services/Services.js +8 -0
  29. package/dist/services/authentication/AuthenticationService.d.ts +5 -0
  30. package/dist/services/authentication/AuthenticationService.js +1 -0
  31. package/dist/services/authentication/AuthenticationServiceImpl.d.ts +12 -0
  32. package/dist/services/authentication/AuthenticationServiceImpl.js +41 -0
  33. package/dist/services/storage/KeychainSecureStorage.d.ts +2 -0
  34. package/dist/services/storage/KeychainSecureStorage.js +58 -0
  35. package/dist/services/storage/StorageImp.d.ts +18 -0
  36. package/dist/services/storage/StorageImp.js +85 -0
  37. package/dist/services/storage/StorageService.d.ts +24 -0
  38. package/dist/services/storage/StorageService.js +1 -0
  39. package/dist/utils/ensure-service-type.d.ts +16 -0
  40. package/dist/utils/ensure-service-type.js +37 -0
  41. package/dist/utils/env.d.ts +11 -0
  42. package/dist/utils/env.js +13 -0
  43. package/dist/utils/object-id.d.ts +1 -0
  44. package/dist/utils/object-id.js +1 -0
  45. package/dist/utils/project-config.d.ts +12 -0
  46. package/dist/utils/project-config.js +12 -0
  47. package/dist/utils/yaml.d.ts +23 -0
  48. package/dist/utils/yaml.js +76 -0
  49. package/package.json +53 -0
@@ -0,0 +1,217 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import { CLIConfig, ResolvedCloudCLIConfig, ResolvedSelfHostedCLIConfig, ServiceCloudConfig, ServiceSelfHostedConfig, validateCloudConfig, validateSelfHostedConfig } from '@powersync/cli-schemas';
3
+ import { existsSync, readFileSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { getDefaultOrgId } from '../clients/AccountsHubClientSDKClient.js';
6
+ import { createCloudClient } from '../clients/create-cloud-client.js';
7
+ import { ensureServiceTypeMatches, ServiceType } from '../utils/ensure-service-type.js';
8
+ import { env } from '../utils/env.js';
9
+ import { CLI_FILENAME, SERVICE_FILENAME, SYNC_FILENAME } from '../utils/project-config.js';
10
+ import { parseYamlFile } from '../utils/yaml.js';
11
+ import { CommandHelpGroup, HelpGroup } from './HelpGroup.js';
12
+ import { DEFAULT_ENSURE_CONFIG_OPTIONS, InstanceCommand } from './InstanceCommand.js';
13
+ /**
14
+ * Base command for operations that work with either a Cloud or self-hosted PowerSync instance.
15
+ *
16
+ * Resolution order:
17
+ *
18
+ * 1. **Context (cloud vs self-hosted)** — Cannot mix both.
19
+ * - First from flags.
20
+ * - Then from cli.yaml (if present).
21
+ * - Then from environment variables.
22
+ *
23
+ * 2. **Per-field values** (instance_id, org_id, project_id for cloud; api_url, api_key for self-hosted):
24
+ * - Cloud: flags → cli.yaml → env.
25
+ * - Self-hosted: api_url from flag → cli.yaml → env; api_key from env → cli.yaml only (no flag).
26
+ *
27
+ * @example
28
+ * # Use linked project (cli.yaml determines cloud vs self-hosted)
29
+ * pnpm exec powersync some-shared-cmd
30
+ * # Force cloud with env
31
+ * INSTANCE_ID=... ORG_ID=... PROJECT_ID=... pnpm exec powersync some-shared-cmd
32
+ * # Force self-hosted with flag
33
+ * pnpm exec powersync some-shared-cmd --api-url=https://...
34
+ * # Force cloud with flags
35
+ * pnpm exec powersync some-shared-cmd --instance-id=... --org-id=... --project-id=...
36
+ */
37
+ export class SharedInstanceCommand extends InstanceCommand {
38
+ static commandHelpGroup = CommandHelpGroup.INSTANCE;
39
+ static flags = {
40
+ 'api-url': Flags.string({
41
+ description: '[Self-hosted] PowerSync API URL. When set, context is treated as self-hosted (exclusive with --instance-id). Resolved: flag → cli.yaml → API_URL.',
42
+ // Can't use this flag with cloud flags
43
+ exclusive: ['instance-id', 'org-id', 'project-id'],
44
+ helpGroup: HelpGroup.SELF_HOSTED_PROJECT,
45
+ required: false
46
+ }),
47
+ 'instance-id': Flags.string({
48
+ dependsOn: ['project-id'],
49
+ description: '[Cloud] PowerSync Cloud instance ID (BSON ObjectID). When set, context is treated as cloud (exclusive with --api-url). Resolved: flag → cli.yaml → INSTANCE_ID.',
50
+ helpGroup: HelpGroup.CLOUD_PROJECT,
51
+ required: false
52
+ }),
53
+ 'org-id': Flags.string({
54
+ description: '[Cloud] Organization ID (optional). Defaults to the token’s single org when only one is available; pass explicitly if the token has multiple orgs. Resolved: flag → cli.yaml → ORG_ID.',
55
+ helpGroup: HelpGroup.CLOUD_PROJECT,
56
+ required: false
57
+ }),
58
+ 'project-id': Flags.string({
59
+ description: '[Cloud] Project ID. Resolved: flag → cli.yaml → PROJECT_ID.',
60
+ helpGroup: HelpGroup.CLOUD_PROJECT,
61
+ required: false
62
+ }),
63
+ ...InstanceCommand.flags
64
+ };
65
+ cloudClient = createCloudClient();
66
+ /**
67
+ * Some commands require contacting a provisioned PowerSync instance.
68
+ * This verifies that the linked instance is provisioned, and shows an error with next steps if it's not.
69
+ */
70
+ async ensureCloudProvisioned(project) {
71
+ const status = await this.cloudClient.getInstanceStatus({
72
+ app_id: project.linked.project_id,
73
+ id: project.linked.instance_id,
74
+ org_id: project.linked.org_id
75
+ });
76
+ if (!status.provisioned) {
77
+ this.styledError({
78
+ message: `Instance ${project.linked.instance_id} is not provisioned. Please provision the instance with ${ux.colorize('blue', 'powersync deploy')} before running this command.`
79
+ });
80
+ }
81
+ }
82
+ async loadProject(flags, options = DEFAULT_ENSURE_CONFIG_OPTIONS) {
83
+ const resolvedOptions = {
84
+ ...DEFAULT_ENSURE_CONFIG_OPTIONS,
85
+ // Keep this order so call-site options override defaults.
86
+ ...options
87
+ };
88
+ const projectDir = this.ensureProjectDirectory(flags);
89
+ const linkPath = join(projectDir, CLI_FILENAME);
90
+ // 1) Context type: flags first, then link file, then env (see class JSDoc for resolution order).
91
+ const hasCloudFlagInputs = flags['instance-id'] || flags['org-id'] || flags['project-id'];
92
+ const hasSelfHostedFlagInputs = flags['api-url'];
93
+ if (hasCloudFlagInputs && hasSelfHostedFlagInputs) {
94
+ this.styledError({ message: 'Cannot use both cloud and self-hosted inputs. Use one or the other.' });
95
+ }
96
+ let projectType = hasSelfHostedFlagInputs
97
+ ? ServiceType.SELF_HOSTED
98
+ : hasCloudFlagInputs
99
+ ? ServiceType.CLOUD
100
+ : null;
101
+ // If type not set by flags, use link file type (if present).
102
+ let rawCLIConfig = null;
103
+ if (existsSync(linkPath)) {
104
+ const doc = parseYamlFile(linkPath);
105
+ rawCLIConfig = CLIConfig.decode(doc.contents?.toJSON());
106
+ if (rawCLIConfig.type === 'self-hosted') {
107
+ projectType = ServiceType.SELF_HOSTED;
108
+ }
109
+ else if (rawCLIConfig.type === 'cloud') {
110
+ projectType = ServiceType.CLOUD;
111
+ }
112
+ }
113
+ // If type still not set, use env inputs.
114
+ if (!projectType) {
115
+ const hasCloudEnvInputs = env.INSTANCE_ID || env.ORG_ID || env.PROJECT_ID;
116
+ const hasSelfHostedEnvInputs = env.API_URL;
117
+ if (hasCloudEnvInputs && hasSelfHostedEnvInputs) {
118
+ this.styledError({ message: 'Cannot use both cloud and self-hosted inputs. Use one or the other.' });
119
+ }
120
+ projectType = hasSelfHostedEnvInputs ? ServiceType.SELF_HOSTED : hasCloudEnvInputs ? ServiceType.CLOUD : null;
121
+ }
122
+ const linkMissingErrorMessage = [
123
+ 'Linking is required before using this command.',
124
+ 'Provide --api-url (self-hosted) or --instance-id with --org-id and --project-id (cloud), or link the project first.'
125
+ ].join('\n');
126
+ // If we don't have a project type by now, we need to error
127
+ if (!projectType) {
128
+ this.styledError({ message: linkMissingErrorMessage });
129
+ }
130
+ // 2) Per-field: flags → link file → env (see class JSDoc).
131
+ let cliConfig = null;
132
+ if (projectType === 'self-hosted') {
133
+ const _rawSelfHostedCLIConfig = rawCLIConfig ?? { type: 'self-hosted' };
134
+ try {
135
+ cliConfig = ResolvedSelfHostedCLIConfig.decode({
136
+ ..._rawSelfHostedCLIConfig,
137
+ api_key: env.PS_ADMIN_TOKEN ?? _rawSelfHostedCLIConfig.api_key,
138
+ api_url: flags['api-url'] ?? _rawSelfHostedCLIConfig.api_url ?? env.API_URL
139
+ });
140
+ }
141
+ catch (error) {
142
+ this.styledError({ error, message: linkMissingErrorMessage });
143
+ }
144
+ }
145
+ else {
146
+ const _rawCloudCLIConfig = rawCLIConfig ?? { type: 'cloud' };
147
+ try {
148
+ let org_id = flags['org-id'] ?? _rawCloudCLIConfig.org_id ?? env.ORG_ID;
149
+ if (org_id == null && (flags['instance-id'] || env.INSTANCE_ID)) {
150
+ org_id = await getDefaultOrgId();
151
+ }
152
+ cliConfig = ResolvedCloudCLIConfig.decode({
153
+ ..._rawCloudCLIConfig,
154
+ instance_id: flags['instance-id'] ?? _rawCloudCLIConfig.instance_id ?? env.INSTANCE_ID,
155
+ org_id: org_id,
156
+ project_id: flags['project-id'] ?? _rawCloudCLIConfig.project_id ?? env.PROJECT_ID
157
+ });
158
+ }
159
+ catch (error) {
160
+ this.styledError({ error, message: linkMissingErrorMessage });
161
+ }
162
+ }
163
+ if (!cliConfig) {
164
+ this.styledError({ message: linkMissingErrorMessage });
165
+ }
166
+ // ensure the link config is valid
167
+ ensureServiceTypeMatches({
168
+ command: this,
169
+ configRequired: false,
170
+ directoryLabel: projectDir,
171
+ expectedType: projectType,
172
+ projectDir
173
+ });
174
+ const syncRulesPath = join(projectDir, SYNC_FILENAME);
175
+ let syncRulesContent;
176
+ if (existsSync(syncRulesPath)) {
177
+ syncRulesContent = readFileSync(syncRulesPath, 'utf8');
178
+ }
179
+ if (!existsSync(join(projectDir, SERVICE_FILENAME)) && resolvedOptions.configFileRequired) {
180
+ this.styledError({
181
+ message: `Config file "${SERVICE_FILENAME}" not found in directory "${projectDir}". This command requires a config file to run. Please create one and try again.`
182
+ });
183
+ }
184
+ if (projectType === ServiceType.CLOUD) {
185
+ return {
186
+ linked: cliConfig,
187
+ projectDirectory: projectDir,
188
+ syncRulesContent
189
+ };
190
+ }
191
+ return {
192
+ linked: cliConfig,
193
+ projectDirectory: projectDir,
194
+ syncRulesContent
195
+ };
196
+ }
197
+ parseCloudConfig(projectDirectory) {
198
+ const servicePath = join(projectDirectory, SERVICE_FILENAME);
199
+ const doc = parseYamlFile(servicePath);
200
+ // validate the config with full schema
201
+ const validationResult = validateCloudConfig(doc.contents?.toJSON());
202
+ if (!validationResult.valid) {
203
+ throw new Error(`Invalid cloud config: ${validationResult.errors?.join('\n')}`);
204
+ }
205
+ return ServiceCloudConfig.decode(doc.contents?.toJSON());
206
+ }
207
+ parseSelfHostedConfig(projectDirectory) {
208
+ const servicePath = join(projectDirectory, SERVICE_FILENAME);
209
+ const doc = parseYamlFile(servicePath);
210
+ // validate the config with full schema
211
+ const validationResult = validateSelfHostedConfig(doc.contents?.toJSON());
212
+ if (!validationResult.valid) {
213
+ throw new Error(`Invalid self-hosted config: ${validationResult.errors?.join('\n')}`);
214
+ }
215
+ return ServiceSelfHostedConfig.decode(doc.contents?.toJSON());
216
+ }
217
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Core API for PowerSync CLI and plugins.
3
+ * Plugins (e.g. plugin-docker) import from @powersync/cli-core.
4
+ */
5
+ export * from './api/validate-sync-config.js';
6
+ export * from './clients/AccountsHubClientSDKClient.js';
7
+ export * from './clients/cli-client-headers.js';
8
+ export * from './clients/create-cloud-client.js';
9
+ export * from './clients/create-self-hosted-client.js';
10
+ export * from './command-types/CloudInstanceCommand.js';
11
+ export * from './command-types/HelpGroup.js';
12
+ export * from './command-types/InstanceCommand.js';
13
+ export * from './command-types/PowerSyncCommand.js';
14
+ export * from './command-types/SelfHostedInstanceCommand.js';
15
+ export * from './command-types/SharedInstanceCommand.js';
16
+ export * from './services/authentication/AuthenticationService.js';
17
+ export * from './services/authentication/AuthenticationServiceImpl.js';
18
+ export * from './services/Services.js';
19
+ export * from './services/storage/StorageImp.js';
20
+ export * from './services/storage/StorageService.js';
21
+ export * from './utils/ensure-service-type.js';
22
+ export * from './utils/env.js';
23
+ export * from './utils/object-id.js';
24
+ export * from './utils/project-config.js';
25
+ export * from './utils/yaml.js';
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Core API for PowerSync CLI and plugins.
3
+ * Plugins (e.g. plugin-docker) import from @powersync/cli-core.
4
+ */
5
+ export * from './api/validate-sync-config.js';
6
+ export * from './clients/AccountsHubClientSDKClient.js';
7
+ export * from './clients/cli-client-headers.js';
8
+ export * from './clients/create-cloud-client.js';
9
+ export * from './clients/create-self-hosted-client.js';
10
+ export * from './command-types/CloudInstanceCommand.js';
11
+ export * from './command-types/HelpGroup.js';
12
+ export * from './command-types/InstanceCommand.js';
13
+ export * from './command-types/PowerSyncCommand.js';
14
+ export * from './command-types/SelfHostedInstanceCommand.js';
15
+ export * from './command-types/SharedInstanceCommand.js';
16
+ export * from './services/authentication/AuthenticationService.js';
17
+ export * from './services/authentication/AuthenticationServiceImpl.js';
18
+ export * from './services/Services.js';
19
+ export * from './services/storage/StorageImp.js';
20
+ export * from './services/storage/StorageService.js';
21
+ export * from './utils/ensure-service-type.js';
22
+ export * from './utils/env.js';
23
+ export * from './utils/object-id.js';
24
+ export * from './utils/project-config.js';
25
+ export * from './utils/yaml.js';
@@ -0,0 +1,6 @@
1
+ import { AuthenticationServiceImpl } from './authentication/AuthenticationServiceImpl.js';
2
+ import { StorageImpl } from './storage/StorageImp.js';
3
+ export declare const Services: {
4
+ authentication: AuthenticationServiceImpl;
5
+ storage: StorageImpl;
6
+ };
@@ -0,0 +1,8 @@
1
+ import { AuthenticationServiceImpl } from './authentication/AuthenticationServiceImpl.js';
2
+ import { StorageImpl } from './storage/StorageImp.js';
3
+ const storage = new StorageImpl();
4
+ const authenticationService = new AuthenticationServiceImpl({ storage });
5
+ export const Services = {
6
+ authentication: authenticationService,
7
+ storage
8
+ };
@@ -0,0 +1,5 @@
1
+ export interface AuthenticationService {
2
+ deleteToken(): Promise<void>;
3
+ getToken(): Promise<null | string>;
4
+ setToken(token: string): Promise<void>;
5
+ }
@@ -0,0 +1,12 @@
1
+ import { StorageService } from '../storage/StorageService.js';
2
+ import { AuthenticationService } from './AuthenticationService.js';
3
+ export type AuthenticationServiceImplOptions = {
4
+ storage: StorageService;
5
+ };
6
+ export declare class AuthenticationServiceImpl implements AuthenticationService {
7
+ protected storage: StorageService;
8
+ constructor(options: AuthenticationServiceImplOptions);
9
+ deleteToken(): Promise<void>;
10
+ getToken(): Promise<null | string>;
11
+ setToken(token: string): Promise<void>;
12
+ }
@@ -0,0 +1,41 @@
1
+ const TOKEN_KEY = 'auth-token';
2
+ export class AuthenticationServiceImpl {
3
+ storage;
4
+ constructor(options) {
5
+ this.storage = options.storage;
6
+ }
7
+ async deleteToken() {
8
+ if (this.storage.capabilities.supportsSecureStorage) {
9
+ await this.storage.secureStorage.removeItem(TOKEN_KEY);
10
+ return;
11
+ }
12
+ const config = await this.storage.getInsecureConfig();
13
+ if (!config.auth || config.auth.token === undefined) {
14
+ return;
15
+ }
16
+ delete config.auth.token;
17
+ if (Object.keys(config.auth).length === 0) {
18
+ delete config.auth;
19
+ }
20
+ await this.storage.updateInsecureConfig(config);
21
+ }
22
+ async getToken() {
23
+ if (this.storage.capabilities.supportsSecureStorage) {
24
+ return this.storage.secureStorage.getItem(TOKEN_KEY);
25
+ }
26
+ const config = await this.storage.getInsecureConfig();
27
+ return config.auth?.token ?? null;
28
+ }
29
+ async setToken(token) {
30
+ if (this.storage.capabilities.supportsSecureStorage) {
31
+ await this.storage.secureStorage.setItem(TOKEN_KEY, token);
32
+ return;
33
+ }
34
+ const config = await this.storage.getInsecureConfig();
35
+ config.auth = {
36
+ ...config.auth,
37
+ token
38
+ };
39
+ await this.storage.updateInsecureConfig(config);
40
+ }
41
+ }
@@ -0,0 +1,2 @@
1
+ import { BaseStorage } from './StorageService.js';
2
+ export declare function createKeychainSecureStorage(): BaseStorage;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Interface for storing and retrieving the PowerSync auth token securely.
3
+ * Implementations are platform-specific (e.g. macOS Keychain).
4
+ */
5
+ const SERVICE_NAME = 'PowerSync CLI';
6
+ export function createKeychainSecureStorage() {
7
+ const keychainPromise = import('keychain').then((m) => m.default ?? m);
8
+ return {
9
+ async getItem(key) {
10
+ const keychain = await keychainPromise;
11
+ return new Promise((resolve, reject) => {
12
+ keychain.getPassword({
13
+ account: key,
14
+ service: SERVICE_NAME
15
+ }, (err, password) => {
16
+ if (err) {
17
+ if (err.message?.includes('could not be found') ||
18
+ err.code === 'PasswordNotFound') {
19
+ resolve(null);
20
+ return;
21
+ }
22
+ reject(err);
23
+ return;
24
+ }
25
+ resolve(password ?? null);
26
+ });
27
+ });
28
+ },
29
+ async removeItem(key) {
30
+ const keychain = await keychainPromise;
31
+ return new Promise((resolve, reject) => {
32
+ keychain.deletePassword({ account: key, service: SERVICE_NAME }, (err) => {
33
+ if (err) {
34
+ if (err.message?.includes('could not be found') ||
35
+ err.code === 'PasswordNotFound') {
36
+ resolve();
37
+ return;
38
+ }
39
+ reject(err);
40
+ return;
41
+ }
42
+ resolve();
43
+ });
44
+ });
45
+ },
46
+ async setItem(key, value) {
47
+ const keychain = await keychainPromise;
48
+ return new Promise((resolve, reject) => {
49
+ keychain.setPassword({ account: key, password: value, service: SERVICE_NAME }, (err) => {
50
+ if (err)
51
+ reject(err);
52
+ else
53
+ resolve();
54
+ });
55
+ });
56
+ }
57
+ };
58
+ }
@@ -0,0 +1,18 @@
1
+ import { BaseStorage, InsecureStorageConfig, StorageCapabilities, StorageService } from './StorageService.js';
2
+ export declare const StubSecureStorage: BaseStorage;
3
+ export declare class ConfigFileStorage {
4
+ private readonly configPath;
5
+ constructor(configPath: string);
6
+ getConfig(): Promise<InsecureStorageConfig>;
7
+ updateConfig(config: InsecureStorageConfig): Promise<void>;
8
+ }
9
+ export declare class StorageImpl implements StorageService {
10
+ protected _configStorage: ConfigFileStorage;
11
+ protected _secureStorage: BaseStorage | null;
12
+ readonly insecureStoragePath: string;
13
+ constructor();
14
+ get capabilities(): StorageCapabilities;
15
+ get secureStorage(): BaseStorage;
16
+ getInsecureConfig(): Promise<InsecureStorageConfig>;
17
+ updateInsecureConfig(config: InsecureStorageConfig): Promise<void>;
18
+ }
@@ -0,0 +1,85 @@
1
+ import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
2
+ import { homedir } from 'node:os';
3
+ import { dirname, join } from 'node:path';
4
+ import * as yaml from 'yaml';
5
+ import { createKeychainSecureStorage } from './KeychainSecureStorage.js';
6
+ export const StubSecureStorage = {
7
+ getItem: () => Promise.reject(new Error('Secure storage is not supported')),
8
+ removeItem: () => Promise.reject(new Error('Secure storage is not supported')),
9
+ setItem: () => Promise.reject(new Error('Secure storage is not supported'))
10
+ };
11
+ function isObjectRecord(value) {
12
+ return typeof value === 'object' && value !== null;
13
+ }
14
+ function isValidInsecureConfig(config) {
15
+ if (!isObjectRecord(config)) {
16
+ return false;
17
+ }
18
+ if (config.auth === undefined) {
19
+ return true;
20
+ }
21
+ if (!isObjectRecord(config.auth)) {
22
+ return false;
23
+ }
24
+ if (config.auth.token !== undefined && typeof config.auth.token !== 'string') {
25
+ return false;
26
+ }
27
+ return true;
28
+ }
29
+ export class ConfigFileStorage {
30
+ configPath;
31
+ constructor(configPath) {
32
+ this.configPath = configPath;
33
+ }
34
+ async getConfig() {
35
+ try {
36
+ const contents = await readFile(this.configPath, 'utf8');
37
+ const parsed = yaml.parse(contents);
38
+ if (!isValidInsecureConfig(parsed)) {
39
+ throw new Error(`Invalid config file shape at ${this.configPath}`);
40
+ }
41
+ return parsed;
42
+ }
43
+ catch (error) {
44
+ if (error.code === 'ENOENT') {
45
+ return {};
46
+ }
47
+ throw error;
48
+ }
49
+ }
50
+ async updateConfig(config) {
51
+ if (!isValidInsecureConfig(config)) {
52
+ throw new Error(`Invalid config file shape at ${this.configPath}`);
53
+ }
54
+ if (Object.keys(config).length === 0) {
55
+ await rm(this.configPath, { force: true });
56
+ return;
57
+ }
58
+ await mkdir(dirname(this.configPath), { recursive: true });
59
+ await writeFile(this.configPath, yaml.stringify(config), 'utf8');
60
+ }
61
+ }
62
+ export class StorageImpl {
63
+ _configStorage;
64
+ _secureStorage;
65
+ insecureStoragePath = join(process.env.XDG_CONFIG_HOME ?? join(homedir(), '.config'), 'powersync', 'config.yaml');
66
+ constructor() {
67
+ this._configStorage = new ConfigFileStorage(this.insecureStoragePath);
68
+ // Secure storage is only supported on macOS for now
69
+ this._secureStorage = process.platform === 'darwin' ? createKeychainSecureStorage() : null;
70
+ }
71
+ get capabilities() {
72
+ return {
73
+ supportsSecureStorage: this._secureStorage !== null
74
+ };
75
+ }
76
+ get secureStorage() {
77
+ return this._secureStorage ?? StubSecureStorage;
78
+ }
79
+ async getInsecureConfig() {
80
+ return this._configStorage.getConfig();
81
+ }
82
+ async updateInsecureConfig(config) {
83
+ await this._configStorage.updateConfig(config);
84
+ }
85
+ }
@@ -0,0 +1,24 @@
1
+ export interface BaseStorage {
2
+ getItem(key: string): Promise<null | string>;
3
+ removeItem(key: string): Promise<void>;
4
+ setItem(key: string, value: string): Promise<void>;
5
+ }
6
+ export interface StorageCapabilities {
7
+ supportsSecureStorage: boolean;
8
+ }
9
+ export type InsecureAuthConfig = Record<string, unknown> & {
10
+ token?: string;
11
+ };
12
+ export type InsecureStorageConfig = Record<string, unknown> & {
13
+ auth?: InsecureAuthConfig;
14
+ };
15
+ /**
16
+ * General storage interface.
17
+ */
18
+ export interface StorageService {
19
+ capabilities: StorageCapabilities;
20
+ getInsecureConfig(): Promise<InsecureStorageConfig>;
21
+ insecureStoragePath: string;
22
+ secureStorage: BaseStorage;
23
+ updateInsecureConfig(config: InsecureStorageConfig): Promise<void>;
24
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ import { PowerSyncCommand } from '../command-types/PowerSyncCommand.js';
2
+ export declare enum ServiceType {
3
+ CLOUD = "cloud",
4
+ SELF_HOSTED = "self-hosted"
5
+ }
6
+ export type EnsureServiceTypeMatchesOptions = {
7
+ command: PowerSyncCommand;
8
+ configRequired: boolean;
9
+ directoryLabel: string;
10
+ expectedType: ServiceType;
11
+ projectDir: string;
12
+ };
13
+ /**
14
+ * Ensures, if it exists, that service.yaml in the project dir has _type matching the expected service type.
15
+ */
16
+ export declare function ensureServiceTypeMatches(options: EnsureServiceTypeMatchesOptions): void;
@@ -0,0 +1,37 @@
1
+ import { ux } from '@oclif/core';
2
+ import { existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { SERVICE_FILENAME } from './project-config.js';
5
+ import { parseYamlFile } from './yaml.js';
6
+ export var ServiceType;
7
+ (function (ServiceType) {
8
+ ServiceType["CLOUD"] = "cloud";
9
+ ServiceType["SELF_HOSTED"] = "self-hosted";
10
+ })(ServiceType || (ServiceType = {}));
11
+ /**
12
+ * Ensures, if it exists, that service.yaml in the project dir has _type matching the expected service type.
13
+ */
14
+ export function ensureServiceTypeMatches(options) {
15
+ const { command, configRequired, directoryLabel, expectedType, projectDir } = options;
16
+ const servicePath = join(projectDir, SERVICE_FILENAME);
17
+ if (!existsSync(servicePath)) {
18
+ if (configRequired) {
19
+ command.styledError({
20
+ message: `${SERVICE_FILENAME} in "${directoryLabel}" is missing. Add \`_type: ${expectedType}\` for this command.`
21
+ });
22
+ }
23
+ return;
24
+ }
25
+ const service = parseYamlFile(servicePath);
26
+ const serviceJson = service.contents?.toJSON();
27
+ if (serviceJson?._type === undefined || serviceJson?._type === null) {
28
+ command.styledError({
29
+ message: `${SERVICE_FILENAME} in "${directoryLabel}" is missing \`_type\`. Add \`_type: ${expectedType}\` for this command.`
30
+ });
31
+ }
32
+ if (serviceJson?._type !== expectedType) {
33
+ command.styledError({
34
+ message: `${SERVICE_FILENAME} in "${directoryLabel}" has \`_type: ${serviceJson?._type}\` but this command requires \`_type: ${expectedType}\`. Use ${ux.colorize('blue', `powersync init ${expectedType}`)} to create a project of the correct type, or change _type in ${SERVICE_FILENAME}.`
35
+ });
36
+ }
37
+ }
@@ -0,0 +1,11 @@
1
+ export type ENV = {
2
+ _PS_ACCOUNTS_HUB_SERVICE_URL: string;
3
+ _PS_DASHBOARD_URL: string;
4
+ _PS_MANAGEMENT_SERVICE_URL: string;
5
+ API_URL?: string;
6
+ INSTANCE_ID?: string;
7
+ ORG_ID?: string;
8
+ PROJECT_ID?: string;
9
+ PS_ADMIN_TOKEN?: string;
10
+ };
11
+ export declare const env: ENV;
@@ -0,0 +1,13 @@
1
+ const DEFAULT_PS_MANAGEMENT_SERVICE_URL = 'https://powersync-api.journeyapps.com';
2
+ const DEFAULT_PS_ACCOUNTS_HUB_SERVICE_URL = 'https://accounts.journeyapps.com';
3
+ const DEFAULT_PS_DASHBOARD_URL = 'https://dashboard.powersync.com';
4
+ export const env = {
5
+ _PS_ACCOUNTS_HUB_SERVICE_URL: process.env._PS_ACCOUNTS_HUB_SERVICE_URL || DEFAULT_PS_ACCOUNTS_HUB_SERVICE_URL,
6
+ _PS_DASHBOARD_URL: process.env._PS_DASHBOARD_URL || DEFAULT_PS_DASHBOARD_URL,
7
+ _PS_MANAGEMENT_SERVICE_URL: process.env._PS_MANAGEMENT_SERVICE_URL || DEFAULT_PS_MANAGEMENT_SERVICE_URL,
8
+ API_URL: process.env.API_URL,
9
+ INSTANCE_ID: process.env.INSTANCE_ID,
10
+ ORG_ID: process.env.ORG_ID,
11
+ PROJECT_ID: process.env.PROJECT_ID,
12
+ PS_ADMIN_TOKEN: process.env.PS_ADMIN_TOKEN
13
+ };
@@ -0,0 +1 @@
1
+ export declare const OBJECT_ID_REGEX: RegExp;
@@ -0,0 +1 @@
1
+ export const OBJECT_ID_REGEX = /^[0-9a-fA-F]{24}$/;
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The filename used to store CLI instance binding (cloud or self-hosted).
3
+ */
4
+ export declare const CLI_FILENAME = "cli.yaml";
5
+ /**
6
+ * The filename used to store the service configuration.
7
+ */
8
+ export declare const SERVICE_FILENAME = "service.yaml";
9
+ /**
10
+ * The filename used to store the sync config.
11
+ */
12
+ export declare const SYNC_FILENAME = "sync-config.yaml";
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The filename used to store CLI instance binding (cloud or self-hosted).
3
+ */
4
+ export const CLI_FILENAME = 'cli.yaml';
5
+ /**
6
+ * The filename used to store the service configuration.
7
+ */
8
+ export const SERVICE_FILENAME = 'service.yaml';
9
+ /**
10
+ * The filename used to store the sync config.
11
+ */
12
+ export const SYNC_FILENAME = 'sync-config.yaml';