@powersync/cli-core 0.0.0-dev-20260305082615

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,190 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import { ResolvedCloudCLIConfig, ServiceCloudConfig, validateCloudConfig } 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 { OBJECT_ID_REGEX } from '../utils/object-id.js';
10
+ import { CLI_FILENAME, SERVICE_FILENAME, SYNC_FILENAME } from '../utils/project-config.js';
11
+ import { parseYamlFile } from '../utils/yaml.js';
12
+ import { CommandHelpGroup, HelpGroup } from './HelpGroup.js';
13
+ import { DEFAULT_ENSURE_CONFIG_OPTIONS, InstanceCommand } from './InstanceCommand.js';
14
+ /**
15
+ * Base command for operations that require a Cloud-type PowerSync project (service.yaml _type: cloud).
16
+ *
17
+ * Instance context (instance_id, org_id, project_id) is resolved in this order:
18
+ * 1. Command-line flags (--instance-id, --org-id, --project-id)
19
+ * 2. Linked config from cli.yaml
20
+ * 3. Environment variables (INSTANCE_ID, ORG_ID, PROJECT_ID)
21
+ * 4. If org_id is still missing: token's single org (via accounts API); error if multiple orgs.
22
+ *
23
+ * @example
24
+ * # Use linked project (cli.yaml)
25
+ * pnpm exec powersync some-cloud-cmd
26
+ * # Override with env
27
+ * INSTANCE_ID=... ORG_ID=... PROJECT_ID=... pnpm exec powersync some-cloud-cmd
28
+ * # Override with flags
29
+ * pnpm exec powersync some-cloud-cmd --instance-id=... --org-id=... --project-id=...
30
+ */
31
+ export class CloudInstanceCommand extends InstanceCommand {
32
+ static commandHelpGroup = CommandHelpGroup.CLOUD;
33
+ static flags = {
34
+ /**
35
+ * Instance ID, org ID, and project ID are resolved in order: flags → cli.yaml → env (INSTANCE_ID, ORG_ID, PROJECT_ID).
36
+ */
37
+ ...InstanceCommand.flags,
38
+ 'instance-id': Flags.string({
39
+ dependsOn: ['project-id'],
40
+ description: 'PowerSync Cloud instance ID. Manually passed if the current context has not been linked.',
41
+ helpGroup: HelpGroup.CLOUD_PROJECT,
42
+ required: false
43
+ }),
44
+ 'org-id': Flags.string({
45
+ description: 'Organization ID (optional). Defaults to the token’s single org when only one is available; pass explicitly if the token has multiple orgs.',
46
+ helpGroup: HelpGroup.CLOUD_PROJECT,
47
+ required: false
48
+ }),
49
+ 'project-id': Flags.string({
50
+ description: 'Project ID. Manually passed if the current context has not been linked.',
51
+ helpGroup: HelpGroup.CLOUD_PROJECT,
52
+ required: false
53
+ })
54
+ };
55
+ _project = null;
56
+ /**
57
+ * Used to interface with the PowerSync Management API for Cloud instances. Automatically created with the token from login (or PS_ADMIN_TOKEN env variable).
58
+ */
59
+ client = createCloudClient();
60
+ /**
61
+ * The parsed service config from the service.yaml file. Call parseLocalConfig() before accessing this property. This is set to the parsed config after calling parseLocalConfig() to avoid multiple parses of the same config.
62
+ */
63
+ serviceConfig = null;
64
+ /**
65
+ * The currently loaded project, including linked instance information and sync config content. Call loadProject() before accessing this property. This is set to the loaded project after calling loadProject() to avoid multiple loads of the same project.
66
+ */
67
+ get project() {
68
+ if (!this._project) {
69
+ throw new Error('Project not loaded. Call loadProject() first.');
70
+ }
71
+ return this._project;
72
+ }
73
+ /**
74
+ * Some commands require contacting a provisioned PowerSync instance.
75
+ * This verifies that the linked instance is provisioned, and shows an error with next steps if it's not.
76
+ */
77
+ async ensureProvisioned() {
78
+ const status = await this.client.getInstanceStatus({
79
+ app_id: this.project.linked.project_id,
80
+ id: this.project.linked.instance_id,
81
+ org_id: this.project.linked.org_id
82
+ });
83
+ if (!status.provisioned) {
84
+ this.styledError({
85
+ message: `Instance ${this.project.linked.instance_id} is not provisioned. Please provision the instance with ${ux.colorize('blue', 'powersync deploy')} before running this command.`
86
+ });
87
+ }
88
+ }
89
+ async loadProject(flags, options = DEFAULT_ENSURE_CONFIG_OPTIONS) {
90
+ const resolvedOptions = {
91
+ ...DEFAULT_ENSURE_CONFIG_OPTIONS,
92
+ // Keep this order so call-site options override defaults.
93
+ ...options
94
+ };
95
+ const projectDir = this.ensureProjectDirectory(flags);
96
+ // Check if the service.yaml file is present and has _type: cloud
97
+ ensureServiceTypeMatches({
98
+ command: this,
99
+ configRequired: resolvedOptions.configFileRequired,
100
+ directoryLabel: flags.directory,
101
+ expectedType: ServiceType.CLOUD,
102
+ projectDir
103
+ });
104
+ const linkPath = join(projectDir, CLI_FILENAME);
105
+ let linked = null;
106
+ let rawLink = null;
107
+ if (existsSync(linkPath)) {
108
+ try {
109
+ const doc = parseYamlFile(linkPath);
110
+ rawLink = doc.contents?.toJSON();
111
+ }
112
+ catch (error) {
113
+ this.styledError({
114
+ error,
115
+ message: `Failed to parse ${CLI_FILENAME} as CloudCLIConfig`
116
+ });
117
+ }
118
+ }
119
+ const instance_id = flags['instance-id'] ?? rawLink?.instance_id ?? env.INSTANCE_ID;
120
+ const project_id = flags['project-id'] ?? rawLink?.project_id ?? env.PROJECT_ID;
121
+ let org_id = flags['org-id'] ?? rawLink?.org_id ?? env.ORG_ID;
122
+ try {
123
+ if (org_id == null && instance_id != null) {
124
+ org_id = await getDefaultOrgId();
125
+ }
126
+ }
127
+ catch (error) {
128
+ this.styledError({
129
+ error,
130
+ message: 'Linking is required before using this command. Provide flags, link the project (cli.yaml), or set environment variables.'
131
+ });
132
+ }
133
+ if (instance_id != null || project_id != null || org_id != null) {
134
+ this.ensureObjectIdIfPresent(instance_id, '--instance-id');
135
+ this.ensureObjectIdIfPresent(org_id, '--org-id');
136
+ this.ensureObjectIdIfPresent(project_id, '--project-id');
137
+ try {
138
+ linked = ResolvedCloudCLIConfig.decode({
139
+ instance_id: instance_id,
140
+ org_id: org_id,
141
+ project_id: project_id,
142
+ type: 'cloud'
143
+ });
144
+ }
145
+ catch (error) {
146
+ this.styledError({
147
+ error,
148
+ message: 'Linking is required before using this command. Provide flags, link the project (cli.yaml), or set environment variables.'
149
+ });
150
+ }
151
+ }
152
+ if (!linked) {
153
+ this.styledError({
154
+ message: 'Linking is required before using this command. No linking information was found in the current context.'
155
+ });
156
+ }
157
+ const syncRulesPath = join(projectDir, SYNC_FILENAME);
158
+ let syncRulesContent;
159
+ if (existsSync(syncRulesPath)) {
160
+ syncRulesContent = readFileSync(syncRulesPath, 'utf8');
161
+ }
162
+ this._project = {
163
+ linked,
164
+ projectDirectory: projectDir,
165
+ syncRulesContent
166
+ };
167
+ return this._project;
168
+ }
169
+ parseLocalConfig(projectDirectory) {
170
+ const servicePath = join(projectDirectory, SERVICE_FILENAME);
171
+ const doc = parseYamlFile(servicePath);
172
+ // validate the config with full schema
173
+ const validationResult = validateCloudConfig(doc.contents?.toJSON());
174
+ if (!validationResult.valid) {
175
+ throw new Error(`Invalid cloud config: ${validationResult.errors?.join('\n')}`);
176
+ }
177
+ this.serviceConfig = ServiceCloudConfig.decode(doc.contents?.toJSON());
178
+ return this.serviceConfig;
179
+ }
180
+ ensureObjectIdIfPresent(value, flagName) {
181
+ if (value == null) {
182
+ return;
183
+ }
184
+ if (!OBJECT_ID_REGEX.test(value)) {
185
+ this.styledError({
186
+ message: `Invalid ${flagName} "${value}". Expected a BSON ObjectID (24 hex characters).`
187
+ });
188
+ }
189
+ }
190
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Groups for command flag inheritance.
3
+ * https://oclif.io/docs/flag_inheritance/
4
+ */
5
+ export declare enum HelpGroup {
6
+ CLOUD_PROJECT = "CLOUD_PROJECT",
7
+ PROJECT = "PROJECT",
8
+ SELF_HOSTED_PROJECT = "SELF_HOSTED_PROJECT"
9
+ }
10
+ /**
11
+ * Section headings used to group commands in the root help output.
12
+ * Set `static commandHelpGroup = CommandHelpGroup.<VALUE>` on a command class (or its base) to control which section it appears in.
13
+ * The string value is the category name; " COMMANDS" is appended automatically when rendering.
14
+ * Commands without a `commandHelpGroup` are shown under ADDITIONAL COMMANDS.
15
+ */
16
+ export declare enum CommandHelpGroup {
17
+ ADDITIONAL = "ADDITIONAL",
18
+ AUTHENTICATION = "AUTHENTICATION",
19
+ CLOUD = "CLOUD",
20
+ INSTANCE = "INSTANCE",
21
+ LOCAL_DEVELOPMENT = "LOCAL DEVELOPMENT",
22
+ PROJECT_SETUP = "PROJECT SETUP"
23
+ }
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Groups for command flag inheritance.
3
+ * https://oclif.io/docs/flag_inheritance/
4
+ */
5
+ export var HelpGroup;
6
+ (function (HelpGroup) {
7
+ HelpGroup["CLOUD_PROJECT"] = "CLOUD_PROJECT";
8
+ HelpGroup["PROJECT"] = "PROJECT";
9
+ HelpGroup["SELF_HOSTED_PROJECT"] = "SELF_HOSTED_PROJECT";
10
+ })(HelpGroup || (HelpGroup = {}));
11
+ /**
12
+ * Section headings used to group commands in the root help output.
13
+ * Set `static commandHelpGroup = CommandHelpGroup.<VALUE>` on a command class (or its base) to control which section it appears in.
14
+ * The string value is the category name; " COMMANDS" is appended automatically when rendering.
15
+ * Commands without a `commandHelpGroup` are shown under ADDITIONAL COMMANDS.
16
+ */
17
+ export var CommandHelpGroup;
18
+ (function (CommandHelpGroup) {
19
+ CommandHelpGroup["ADDITIONAL"] = "ADDITIONAL";
20
+ CommandHelpGroup["AUTHENTICATION"] = "AUTHENTICATION";
21
+ CommandHelpGroup["CLOUD"] = "CLOUD";
22
+ CommandHelpGroup["INSTANCE"] = "INSTANCE";
23
+ CommandHelpGroup["LOCAL_DEVELOPMENT"] = "LOCAL DEVELOPMENT";
24
+ CommandHelpGroup["PROJECT_SETUP"] = "PROJECT SETUP";
25
+ })(CommandHelpGroup || (CommandHelpGroup = {}));
@@ -0,0 +1,15 @@
1
+ import { PowerSyncCommand } from './PowerSyncCommand.js';
2
+ export type EnsureConfigOptions = {
3
+ configFileRequired?: boolean;
4
+ };
5
+ export declare const DEFAULT_ENSURE_CONFIG_OPTIONS: Required<EnsureConfigOptions>;
6
+ export declare const DEFAULT_INSTANCE_DIRECTORY = "powersync";
7
+ /** Base command for operations that target a PowerSync project directory (e.g. link, init). */
8
+ export declare abstract class InstanceCommand extends PowerSyncCommand {
9
+ static flags: {
10
+ directory: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
11
+ };
12
+ ensureProjectDirectory(flags: {
13
+ directory: string;
14
+ }): string;
15
+ }
@@ -0,0 +1,42 @@
1
+ import { Flags, ux } from '@oclif/core';
2
+ import fs from 'node:fs';
3
+ import { CLI_FILENAME } from '../utils/project-config.js';
4
+ import { HelpGroup } from './HelpGroup.js';
5
+ import { PowerSyncCommand } from './PowerSyncCommand.js';
6
+ export const DEFAULT_ENSURE_CONFIG_OPTIONS = {
7
+ /**
8
+ * Only the deploy and config related commands actually require the config to be present.
9
+ */
10
+ configFileRequired: false
11
+ };
12
+ export const DEFAULT_INSTANCE_DIRECTORY = 'powersync';
13
+ /** Base command for operations that target a PowerSync project directory (e.g. link, init). */
14
+ export class InstanceCommand extends PowerSyncCommand {
15
+ static flags = {
16
+ ...PowerSyncCommand.flags,
17
+ directory: Flags.string({
18
+ async default() {
19
+ // Before we default, we need to ensure only 1 linked project is present.
20
+ const directories = fs.readdirSync(process.cwd()).filter((dir) => fs.existsSync(`${dir}/${CLI_FILENAME}`));
21
+ if (directories.length > 1) {
22
+ throw new Error([
23
+ `Multiple directories containing ${CLI_FILENAME} found. Please specify the target directory with --directory.`,
24
+ ...directories.map((dir) => `Use ${ux.colorize('blue', `--directory=${dir}`)} to target the ${dir} config.`)
25
+ ].join('\n'));
26
+ }
27
+ return DEFAULT_INSTANCE_DIRECTORY;
28
+ },
29
+ description: 'Directory containing PowerSync config. Defaults to "powersync". This is required if multiple powersync config files are present in subdirectories of the current working directory.',
30
+ helpGroup: HelpGroup.PROJECT
31
+ })
32
+ };
33
+ ensureProjectDirectory(flags) {
34
+ const projectDir = this.resolveProjectDir(flags);
35
+ if (!fs.existsSync(projectDir)) {
36
+ this.styledError({
37
+ message: `Directory "${flags.directory}" not found. Run ${ux.colorize('blue', 'powersync init cloud')} or ${ux.colorize('blue', 'powersync init self-hosted')} first to create the project.`
38
+ });
39
+ }
40
+ return projectDir;
41
+ }
42
+ }
@@ -0,0 +1,29 @@
1
+ import { Command } from '@oclif/core';
2
+ import { CommandHelpGroup } from './HelpGroup.js';
3
+ export type StyledErrorParams = {
4
+ error?: Error | unknown;
5
+ exitCode?: number;
6
+ message: string;
7
+ suggestions?: string[];
8
+ };
9
+ /** Base command for operations that target a PowerSync project directory (e.g. link, init). */
10
+ export declare abstract class PowerSyncCommand extends Command {
11
+ /**
12
+ * Controls which section this command appears under in the root help output.
13
+ * Override in subclasses or individual commands to place them in the correct section.
14
+ * Defaults to undefined, which maps to ADDITIONAL_COMMANDS in the help renderer.
15
+ */
16
+ static commandHelpGroup?: CommandHelpGroup;
17
+ /** Resolves the project directory path from the --directory flag (relative to cwd). */
18
+ resolveProjectDir(flags: {
19
+ directory: string;
20
+ }): string;
21
+ /**
22
+ * Reports a styled error via this.error. Normalizes a catch-block error (any) to an Error
23
+ * and includes the cause in the displayed message.
24
+ *
25
+ * Like {@link Command.error}, this ends execution: it throws and the process exits, so code
26
+ * after a call to styledError will not run.
27
+ */
28
+ styledError(params: StyledErrorParams): never;
29
+ }
@@ -0,0 +1,37 @@
1
+ import { Command, ux } from '@oclif/core';
2
+ import { join } from 'node:path';
3
+ /** Base command for operations that target a PowerSync project directory (e.g. link, init). */
4
+ export class PowerSyncCommand extends Command {
5
+ /**
6
+ * Controls which section this command appears under in the root help output.
7
+ * Override in subclasses or individual commands to place them in the correct section.
8
+ * Defaults to undefined, which maps to ADDITIONAL_COMMANDS in the help renderer.
9
+ */
10
+ static commandHelpGroup;
11
+ /** Resolves the project directory path from the --directory flag (relative to cwd). */
12
+ resolveProjectDir(flags) {
13
+ return join(process.cwd(), flags.directory);
14
+ }
15
+ /**
16
+ * Reports a styled error via this.error. Normalizes a catch-block error (any) to an Error
17
+ * and includes the cause in the displayed message.
18
+ *
19
+ * Like {@link Command.error}, this ends execution: it throws and the process exits, so code
20
+ * after a call to styledError will not run.
21
+ */
22
+ styledError(params) {
23
+ const { error, exitCode = 1, message, suggestions } = params;
24
+ // Journey SDK errors contain additional fields that we want to pass to the error handler.
25
+ const journeyError = error != null && typeof error === 'object' && 'is_journey_error' in error ? error : undefined;
26
+ const journeyErrorMessage = journeyError ? JSON.stringify(journeyError.toJSON(), null, '\t') : undefined;
27
+ const errorDetails = journeyErrorMessage ?? (error == null ? '' : error instanceof Error ? error.message : String(error));
28
+ const displayMessage = errorDetails ? `${message}, :: ${errorDetails}` : message;
29
+ this.error(ux.colorize('red', displayMessage), {
30
+ ...(error instanceof Error ? error : {}),
31
+ ...(journeyError?.errorData?.code && { code: journeyError.errorData.code }),
32
+ exit: exitCode,
33
+ message: journeyErrorMessage ?? message,
34
+ ...(suggestions?.length && { suggestions })
35
+ });
36
+ }
37
+ }
@@ -0,0 +1,25 @@
1
+ import { Interfaces } from '@oclif/core';
2
+ import { ResolvedSelfHostedCLIConfig, ServiceSelfHostedConfigDecoded } from '@powersync/cli-schemas';
3
+ import { EnsureConfigOptions, InstanceCommand } from './InstanceCommand.js';
4
+ export type SelfHostedProject = {
5
+ linked: ResolvedSelfHostedCLIConfig;
6
+ projectDirectory: string;
7
+ };
8
+ export type SelfHostedInstanceCommandFlags = Interfaces.InferredFlags<typeof SelfHostedInstanceCommand.baseFlags & typeof SelfHostedInstanceCommand.flags>;
9
+ /**
10
+ * Base command for operations that require a self-hosted PowerSync project (service.yaml _type: self-hosted).
11
+ * Import from @powersync/cli-core when building plugins.
12
+ */
13
+ export declare abstract class SelfHostedInstanceCommand extends InstanceCommand {
14
+ static flags: {
15
+ 'api-url': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
16
+ directory: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
17
+ };
18
+ protected _project: null | SelfHostedProject;
19
+ /**
20
+ * The currently loaded project, including linked instance information and sync config content. Call loadProject() before accessing this property. This is set to the loaded project after calling loadProject() to avoid multiple loads of the same project.
21
+ */
22
+ get project(): SelfHostedProject;
23
+ loadProject(flags: SelfHostedInstanceCommandFlags, options?: EnsureConfigOptions): SelfHostedProject;
24
+ parseLocalConfig(projectDirectory: string): ServiceSelfHostedConfigDecoded;
25
+ }
@@ -0,0 +1,97 @@
1
+ import { Flags } from '@oclif/core';
2
+ import { ResolvedSelfHostedCLIConfig, ServiceSelfHostedConfig, validateSelfHostedConfig } from '@powersync/cli-schemas';
3
+ import { existsSync } from 'node:fs';
4
+ import { join } from 'node:path';
5
+ import { ensureServiceTypeMatches, ServiceType } from '../utils/ensure-service-type.js';
6
+ import { env } from '../utils/env.js';
7
+ import { CLI_FILENAME, SERVICE_FILENAME } from '../utils/project-config.js';
8
+ import { parseYamlFile } from '../utils/yaml.js';
9
+ import { HelpGroup } from './HelpGroup.js';
10
+ import { DEFAULT_ENSURE_CONFIG_OPTIONS, InstanceCommand } from './InstanceCommand.js';
11
+ /**
12
+ * Base command for operations that require a self-hosted PowerSync project (service.yaml _type: self-hosted).
13
+ * Import from @powersync/cli-core when building plugins.
14
+ */
15
+ export class SelfHostedInstanceCommand extends InstanceCommand {
16
+ static flags = {
17
+ ...InstanceCommand.flags,
18
+ 'api-url': Flags.string({
19
+ description: 'PowerSync API URL. Resolved: flag → cli.yaml → API_URL environment variable.',
20
+ helpGroup: HelpGroup.SELF_HOSTED_PROJECT,
21
+ required: false
22
+ })
23
+ };
24
+ _project = null;
25
+ /**
26
+ * The currently loaded project, including linked instance information and sync config content. Call loadProject() before accessing this property. This is set to the loaded project after calling loadProject() to avoid multiple loads of the same project.
27
+ */
28
+ get project() {
29
+ if (!this._project) {
30
+ throw new Error('Project not loaded. Call loadProject() first.');
31
+ }
32
+ return this._project;
33
+ }
34
+ loadProject(flags, options = DEFAULT_ENSURE_CONFIG_OPTIONS) {
35
+ const resolvedOptions = {
36
+ ...DEFAULT_ENSURE_CONFIG_OPTIONS,
37
+ // Keep this order so call-site options override defaults.
38
+ ...options
39
+ };
40
+ const projectDir = this.ensureProjectDirectory(flags);
41
+ ensureServiceTypeMatches({
42
+ command: this,
43
+ configRequired: resolvedOptions.configFileRequired,
44
+ directoryLabel: flags.directory,
45
+ expectedType: ServiceType.SELF_HOSTED,
46
+ projectDir
47
+ });
48
+ const linkPath = join(projectDir, CLI_FILENAME);
49
+ let rawLink = null;
50
+ if (existsSync(linkPath)) {
51
+ try {
52
+ const doc = parseYamlFile(linkPath);
53
+ rawLink = doc.contents?.toJSON();
54
+ }
55
+ catch {
56
+ rawLink = null;
57
+ }
58
+ }
59
+ const api_url = flags['api-url'] ?? rawLink?.api_url ?? env.API_URL;
60
+ const api_key = env.PS_ADMIN_TOKEN ?? rawLink?.api_key;
61
+ let linked = null;
62
+ try {
63
+ linked = ResolvedSelfHostedCLIConfig.decode({
64
+ ...rawLink,
65
+ api_key: api_key,
66
+ api_url: api_url,
67
+ type: 'self-hosted'
68
+ });
69
+ }
70
+ catch (error) {
71
+ this.styledError({
72
+ error,
73
+ message: 'Linking is required. Set API_URL and PS_ADMIN_TOKEN, or link the project first (cli.yaml).'
74
+ });
75
+ }
76
+ if (!linked) {
77
+ this.styledError({
78
+ message: 'Linking is required for this command. Set API_URL and PS_ADMIN_TOKEN, or link the project first (cli.yaml).'
79
+ });
80
+ }
81
+ this._project = {
82
+ linked,
83
+ projectDirectory: projectDir
84
+ };
85
+ return this._project;
86
+ }
87
+ parseLocalConfig(projectDirectory) {
88
+ const servicePath = join(projectDirectory, SERVICE_FILENAME);
89
+ const doc = parseYamlFile(servicePath);
90
+ // validate the config with full schema
91
+ const validationResult = validateSelfHostedConfig(doc.contents?.toJSON());
92
+ if (!validationResult.valid) {
93
+ throw new Error(`Invalid self-hosted config: ${validationResult.errors?.join('\n')}`);
94
+ }
95
+ return ServiceSelfHostedConfig.decode(doc.contents?.toJSON());
96
+ }
97
+ }
@@ -0,0 +1,51 @@
1
+ import { Interfaces } from '@oclif/core';
2
+ import { ServiceCloudConfigDecoded, ServiceSelfHostedConfigDecoded } from '@powersync/cli-schemas';
3
+ import { PowerSyncManagementClient } from '@powersync/management-client';
4
+ import { CloudProject } from './CloudInstanceCommand.js';
5
+ import { CommandHelpGroup } from './HelpGroup.js';
6
+ import { EnsureConfigOptions, InstanceCommand } from './InstanceCommand.js';
7
+ import { SelfHostedProject } from './SelfHostedInstanceCommand.js';
8
+ export type SharedInstanceCommandFlags = Interfaces.InferredFlags<typeof SharedInstanceCommand.baseFlags & typeof SharedInstanceCommand.flags>;
9
+ /**
10
+ * Base command for operations that work with either a Cloud or self-hosted PowerSync instance.
11
+ *
12
+ * Resolution order:
13
+ *
14
+ * 1. **Context (cloud vs self-hosted)** — Cannot mix both.
15
+ * - First from flags.
16
+ * - Then from cli.yaml (if present).
17
+ * - Then from environment variables.
18
+ *
19
+ * 2. **Per-field values** (instance_id, org_id, project_id for cloud; api_url, api_key for self-hosted):
20
+ * - Cloud: flags → cli.yaml → env.
21
+ * - Self-hosted: api_url from flag → cli.yaml → env; api_key from env → cli.yaml only (no flag).
22
+ *
23
+ * @example
24
+ * # Use linked project (cli.yaml determines cloud vs self-hosted)
25
+ * pnpm exec powersync some-shared-cmd
26
+ * # Force cloud with env
27
+ * INSTANCE_ID=... ORG_ID=... PROJECT_ID=... pnpm exec powersync some-shared-cmd
28
+ * # Force self-hosted with flag
29
+ * pnpm exec powersync some-shared-cmd --api-url=https://...
30
+ * # Force cloud with flags
31
+ * pnpm exec powersync some-shared-cmd --instance-id=... --org-id=... --project-id=...
32
+ */
33
+ export declare abstract class SharedInstanceCommand extends InstanceCommand {
34
+ static commandHelpGroup: CommandHelpGroup;
35
+ static flags: {
36
+ directory: Interfaces.OptionFlag<string, Interfaces.CustomOptions>;
37
+ 'api-url': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
38
+ 'instance-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
39
+ 'org-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
40
+ 'project-id': Interfaces.OptionFlag<string | undefined, Interfaces.CustomOptions>;
41
+ };
42
+ cloudClient: PowerSyncManagementClient;
43
+ /**
44
+ * Some commands require contacting a provisioned PowerSync instance.
45
+ * This verifies that the linked instance is provisioned, and shows an error with next steps if it's not.
46
+ */
47
+ ensureCloudProvisioned(project: CloudProject): Promise<void>;
48
+ loadProject(flags: SharedInstanceCommandFlags, options?: EnsureConfigOptions): Promise<CloudProject | SelfHostedProject>;
49
+ parseCloudConfig(projectDirectory: string): ServiceCloudConfigDecoded;
50
+ parseSelfHostedConfig(projectDirectory: string): ServiceSelfHostedConfigDecoded;
51
+ }